How to consistently start Vim’s command line to make a mapping work in any mode

key mappingkeyboard shortcutsscriptingvimvimrc

I try to normalize access to Vim's command line mode from any other mode in order to simplify my actual mappings. For example to make the <f6> key work from anywhere I define the following mappings:

noremap <script> <unique> <silent> <f6> <sid>:echomsg 'Hello World!'<cr>
noremap! <script> <unique> <silent> <f6> <sid>:echomsg 'Hello World!'<cr>

The above mappings remap to the <sid>: key mapping given below before they get down to work:

noremap <unique> <expr> <sid>: <sid>StartCmdLineMode()
noremap! <unique> <expr> <sid>: <sid>StartCmdLineMode()
function! s:StartCmdLineMode()
  let a=mode()
  if a ==# 'n' 
    return ':'
  " Type <c-v><c-v> to insert ^V. 
  elseif a =~ '[vV^V]'
    return ":\<c-u>"
  elseif a ==# 'no'
    return "\<c-c>:"
  elseif a ==# 'i' 
    return "\<c-o>:"
  elseif a ==# 'c' 
    let b=getcmdtype()
    if b ==# ':' 
      return "\<c-e>\<c-u>"
    else
      return "\<c-c>:"
    endif
  else
    return ''
  endif
endfunction

Is there a staightforward way instead of my obfuscated approach?

Best Answer

When does the following not work?

nnoremap <F6> <ESC><ESC>:command<CR>
Related Question