How can I quickly quote/unquote words and change quoting (e.g. from ' to ") in vim ? I know about surround.vim plugin, but I would like to use just vim.
I don't know any builtin vim command for this, but using r"f'r"
to change from ' to " and r'f"r'
to change from " to ' works if you stand on the first ' or ". The command r'
replaces whatever character is under your cursor with ', and f"
moves you forward to the next ".
surround.vim is going to be your easiest answer. If you are truly set against using it, here are some examples for what you can do. Not necessarily the most efficient, but that's why surround.vim was written.
- Quote a word, using single quotes
ciw'Ctrl+r"'
ciw
- Delete the word the cursor is on, and end up in insert mode.'
- add the first quote.Ctrl+r"
- Insert the contents of the"
register, aka the last yank/delete.'
- add the closing quote.
- Unquote a word that's enclosed in single quotes
di'hPl2x
di'
- Delete the word enclosed by single quotes.hP
- Move the cursor left one place (on top of the opening quote) and put the just deleted text before the quote.l
- Move the cursor right one place (on top of the opening quote).2x
- Delete the two quotes.
- Change single quotes to double quotes
va':s/\%V'\%V/"/g
va'
- Visually select the quoted word and the quotes.:s/
- Start a replacement.\%V'\%V
- Only match single quotes that are within the visually selected region./"/g
- Replace them all with double quotes.
Here's some mapping that could help:
:map <Leader>q" gewi"<Esc>ea"<Esc>
:map <Leader>q' gewi'<Esc>ea'<Esc>
:map <Leader>qd daW"=substitute(@@,"'\\\|\"","","g")<CR>P
If you haven't changed the mapleader variable, then activate the mapping with \q"
\q'
or \qd
. They add double quote around the word under the cursor, single quote around the word under the cursor, delete any quotes around the word under the cursor respectively.
In addition to the other commands, this will enclose all words in a line in double quotes (as per your comment)
:s/\(\S\+\)/"\1"/
or if you want to reduce the number of backslashes, you can put a \v
(very-magic) modifier at the start of the pattern
:s/\v(\S+)/"\1"/