I have the following mapping:

cnoremap <silent> <CR> <CR>:echo 'Enter pressed'<CR>

This works as expected; the :echo command runs every time I press <CR> in the command line. This is done when entering the commandline with :, /, ?, <C-r>= (in insert), etc.

Is there any way to get the :echo command to run only if I enter the commandline with /?


Here is a mapping from my vimrc where I check if the command type is either forward search OR backward search:

cnoremap <expr> <Tab> getcmdtype() == "/" \|\| getcmdtype() == "?" ? "<CR>/<C-r>/" : "<C-z>"

See :help getcmdtype().

For more granularity, you could use getcmdline() like I did in the function below. The value of getcmdline() is checked against a bunch of patterns to decide what to return instead of <CR>:

function! Shortcut()
    let cmdline = getcmdline()
    if cmdline =~ '\C^ls'
        return "\<CR>:b"
    elseif cmdline =~ '/#$'
        return "\<CR>:"
    elseif cmdline =~ '\v\C^(dli|il)'
        return "\<CR>:" . cmdline[0] . "jump  " . split(cmdline, " ")[1] . "\<S-Left>\<Left>"
    elseif cmdline =~ '\v\C^(cli|lli)'
        return "\<CR>:silent " . repeat(cmdline[0], 2) . "\<Space>"
    elseif cmdline =~ '\C^old'
        return "\<CR>:edit #<"
        return "\<CR>"

cnoremap <expr> <CR> Shortcut()

See :help getcmdline().


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.