Skip to content

Instantly share code, notes, and snippets.

@g0xA52A2A
Last active June 11, 2020 09:51
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/dfa9ccf6ae1b829d396aa61e8968b2c2 to your computer and use it in GitHub Desktop.
Save g0xA52A2A/dfa9ccf6ae1b829d396aa61e8968b2c2 to your computer and use it in GitHub Desktop.

In lieu of a set verymagic option in Vim we need to have plethora of mappings to insert \v.

The AutoVeryMagic() function / command-line mapping is the main item of interest here. It should only insert \v where needed.

augroup AutoVeryMagic
  autocmd!
  autocmd CmdlineEnter /,\? if empty(getcmdline()) | call feedkeys('\v', 'n') | endif
augroup END

function! AutoVeryMagic()
  let word  = get(split(strpart(getcmdline(), 0, getcmdpos())), -1, '')
  let word  = get(split(word, '[^a-z]'), -1, '')
  let words = [ 'g', 's', 'v']

  let command  = getcompletion(word, 'command')
  if &ignorecase
    call filter(word, "v:val =~# word")
  endif
  let command  = get(command, 0, '')
  let commands = [ 'global', 'substitute', 'vglobal']

  if index(words, word) != -1 || index(commands, command) != -1
    return '/\v'
  else
    return '/'
  endif
endfunction

cnoremap <expr> / getcmdtype() == ':' ? AutoVeryMagic() : '/'

cnoremap <expr> <C-U> index(['/', '?'], getcmdtype()) != -1 ? "\<C-U>\\v" : "\<C-U>"

There is at least one known edge case at the time of writing. When closing a /{pattern}/ if there is a space followed by a key letter or word that would match any of the :g[lobal], :s[ubstitute], or :v[global] commands an extra \v will be inserted.

E.G. typing :s/ s/ yields :s/\v s/\v.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment