I was curious if there is a way to surround several words at once with quotes using vim. I am using tpope surround and repeat but I was wondering if there is a command like
3ysw"
so from
one two three
to
"one" "two" "three"
You can visually select the range with v3e
, and then run a substitution command on it: :s/\v(\w+)/"\1"/g
(the range '<,'>
should automatically be inserted).
Personally though, I'd rather surround one word with ysw"
, and then do w.w.
(repeat as often as needed).
Alternatively, record a macro that does both steps (surrounding and moving on to the next word), then call it n times:
qqysw"3wq
After this is in your q
register, you can then call 2@q
to perform the surroundings on the remaining words.
When you want to enquote three words, beginning with the one your cursor is currently placed within, you can do:
bv3ec'<Ctrl+r>"'
b
places the cursor at the beginning of the current word, v
enters visual mode, 3e
jumps at the end of the current 3-word sequence, c
cuts the selection and enters insert mode, where you insert the left enclosing quote '
and press <Ctrl+r>"
in order to paste current contents of the clipboard buffer, before you insert the other enclosing quote '
.
Omit the leading b
if you start off with the cursor at the first character of the first word.
Another substitution option
s,\w\+,"&",g
s ............. substitute current line (add %s for the whole file)
\w\+ .......... one word or more
"&" ........... & represents the whole match on the search part
g ............. every occurrence on the line
OBS: When using substitution we can use a different delimiter in order to make easy to type. (Also useful when searching for things like "/my/pattern/")