This is a command that I usually forget how to use. I should write a function and/or keymap for it, however right now this post should suffice.
Sometimes I want to surround some words/methods/keywords etc. with specific characters. Yes, I know there are plugins out there which were written exactly for this this job like tpope/vim-surround, or kylechui/nvim-surround.
With these plugins when I press
ysaw" while hovering the
word, it will give
my double-quote surrounded
However I want to surround them in the whole file, or in a section of a file. And according to the Lazy Vim Engineer Principle it should be completed with as less keystrokes as possible. Not by pressing same key combo again and again until all words consumed.
My editor choice is Neovim and I use Vim and Neovim/Nvim interchangeably.
Let’s assume that I want to surround below words inside double underscores (
__ __) with
enter __dummy__ some more dummy text __dunder__
This is how we achieve this:
susbtitutecommand in Vim
.*is wildcard match. We say match anything inside
&is shorthand for the matched text.
And this is the result we get:
enter “__dummy__ some more dummy text __dunder__”
Wait a minute, this is not supposed to be. It seems this command surrounds the whole line.
The problem is
.* is a greedy match. Actually the reason is that all regex
matches are greedy in Vim, so it gives the whole match after our pattern.
For a non-greedy match we should use
And now the output should look like below:
enter “__dummy__” some more dummy text “__dunder__”
For more information on non-greedy match: