Skip to content

Instantly share code, notes, and snippets.

@g0xA52A2A
Last active November 30, 2020 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save g0xA52A2A/a03b05bcff4092277f093de3aa713bf8 to your computer and use it in GitHub Desktop.
Save g0xA52A2A/a03b05bcff4092277f093de3aa713bf8 to your computer and use it in GitHub Desktop.
Lazy case correction for user commands

Some user commands are intended as replacements for built-in commands, for example :Grep may replace :grep. Given the existence of such a "replacement" user command when typing :grep it would be convenient to have it replaced with :Grep for the sake of muscle memory.

For other user commands a similar replacement scheme may be desirable simply to avoid having to chord with the shift key.

We can achieve this with command-line abbreviations.

function! Cabbrev(command, local) abort
  let lowercase = tolower(a:command)

  let rhs  = "(getcmdtype() ==# ':' && getcmdline() ==# '" . lowercase . "')"
  let rhs .= " ? "
  let rhs .=   "'" . a:command . "'"
  let rhs .= " : "
  let rhs .=   "'" . lowercase . "'"

  if !hasmapto(rhs, 'c', 1)
    execute 'cnoreabbrev' (a:local ? '<buffer>' : '') '<expr>' lowercase rhs
  endif
endfunction

augroup AutoAbbreviate
  autocmd!
  autocmd VimEnter *
    \ call map(getcompletion('[A-Z]', 'command'),
    \          "Cabbrev(v:val, 0)")
  autocmd FileType *
    \ call map(getcompletion('[A-Z]', 'command'),
    \          "Cabbrev(v:val, 1)")
augroup END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment