Skip to content

Instantly share code, notes, and snippets.

@PeterRincker
Forked from orlp/gist:8c25ed4abb36372bc6fe
Last active April 18, 2022 20:20
Show Gist options
  • Save PeterRincker/08edd3ea980e778d3986 to your computer and use it in GitHub Desktop.
Save PeterRincker/08edd3ea980e778d3986 to your computer and use it in GitHub Desktop.
Quick Replacements - gn with an n afterwards
" Quick Replace
" Makes *``cgn like workflows faster by automatically moving to next match. Repeat with `.`
"
" Requires repeat.vim
"
" Example mappings:
" nmap cm <Plug>(quick-replace)
" xmap C <Plug>(quick-replace)
"
" mnemonic: cm for change matches
"
" Execute `cmfoo` on a word. Your cursor will then move to the next word after the change.
" Repeat change with `.` (jumps to next match).
" Can also visually select characters and use `C` set match and start a change
if exists('g:loaded_quick_replace') || &cp
finish
endif
let g:loaded_quick_replace = 1
function! s:gn_next()
augroup gn_next_repeat
autocmd!
autocmd CursorMoved <buffer>
\ execute "autocmd! gn_next_repeat" |
\ silent! call repeat#set(v:operator . "\<Plug>(gn-next)" . (v:operator == 'c' ? "\<c-a>\<esc>" : '')) |
\ normal! n
augroup END
return "\<esc>:let &hlsearch=&hlsearch\<cr>" . v:operator . "gn"
endfunction
function! s:match_visual()
let [reg, type] = [@@, getregtype('"')]
normal! gvy
let @/ = '\V' . escape(@@, '\')
call setreg('"', reg, type)
endfunction
onoremap <expr> <SID>(gn-next) <SID>gn_next()
onoremap <script> <Plug>(gn-next) <SID>(gn-next)
nnoremap <script> <Plug>(quick-replace) :let @/ = '\V\<' . escape(expand('<cword>'), '\') . '\>'<cr>c<SID>(gn-next)
nnoremap <script> <Plug>(quick-replace-g*) :let @/ = '\V' . escape(expand('<cword>'), '\')<cr>c<SID>(gn-next)
xnoremap <script> <Plug>(quick-replace) :<c-u>call <SID>match_visual()<cr>c<SID>(gn-next)
if !hasmapto("<Plug>(quick-replace)", 'n')
nmap cm <Plug>(quick-replace)
endif
if !hasmapto("<Plug>(quick-replace)", 'v')
xmap C <Plug>(quick-replace)
endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment