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 #<"
else
return "\<CR>"
endif
endfunction
cnoremap <expr> <CR> Shortcut()
See :help getcmdline()
.