Vim: highlight-select-change flow
Vim (and Emacs Evil) usage tip to make the search/replace flow more visual:
- highlight: use
*to highlight the text you want to replace - select: select the area for the replacement in visual mode
- change: execute
:'<,'>s//new_word/gor:dor:g, etc.
In this scenario, we can see the words that will be replaced, and we limit the operation to the selected visual area.
The key is that we highlight the word with * first. Then we can
skip the search pattern for :s or other commands, and we see this pattern
on the screen.
Note that the :s command does not have to repeat the search pattern:
we use the s//replacement form, which automatically uses the last search.
By default, * only highlights the word under the cursor. This code makes it work for a visual selection:
" Visual search
" select text and hit * / # to find it
" http://got-ravings.blogspot.com/2008/07/vim-pr0n-visual-search-mappings.html
" https://github.com/godlygeek/vim-files/blob/master/plugin/vsearch.vim
" Visual mode search
function! s:VSetSearch()
let temp = @@
norm! gvy
let @/ = '\V' . substitute(escape(@@, '\'), '\n', '\\n', 'g')
" Use this line instead of the above to match matches spanning across lines
"let @/ = '\V' . substitute(escape(@@, '\'), '\_s\+', '\\_s\\+', 'g')
call histadd('/', substitute(@/, '[?/]', '\="\\%d".char2nr(submatch(0))', 'g'))
let @@ = temp
endfunction
" xnoremap - only for visual mode, but not for select mode
xnoremap * :<C-u>call <SID>VSetSearch()<CR>/<CR>N
xnoremap # :<C-u>call <SID>VSetSearch()<CR>?<CR>N
For Emacs Evil:
;; Visual search: select text and hit * / # to search for it literally.
;; Stays on the first match, like the normal-state * / # above.
(use-package evil-visualstar
:after evil
:config
(defun my-evil-visualstar-forward-stay ()
"Search for the visual selection forward but stay on the first match."
(interactive)
(call-interactively 'evil-visualstar/begin-search-forward)
(evil-ex-search-previous))
(defun my-evil-visualstar-backward-stay ()
"Search for the visual selection backward but stay on the first match."
(interactive)
(call-interactively 'evil-visualstar/begin-search-backward)
(evil-ex-search-previous))
(define-key evil-visual-state-map (kbd "*") 'my-evil-visualstar-forward-stay)
(define-key evil-visual-state-map (kbd "#") 'my-evil-visualstar-backward-stay))