How can I quickly quote/unquote words and change quoting (e.g. from '
to "
) in Vim? I know about the surround.vim plugin, but I would like to use just Vim.
21 Answers
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.
-
1These work fine for me. Just googled that pasting in insert mode is also possible with Ctrl+op. Jan 27, 2010 at 19:00
-
1Used in combination with Record Mode (q), works like a charm for quick jobs.– bishopFeb 25, 2015 at 21:29
-
21@Koveras
ciw
works regardless of where your cursor is in the word.cw
only works if your cursor is at the start of the word. See:help iw
.– jamessanApr 25, 2015 at 19:50 -
13Hijacking the top answer to give a nice little trick: if you have several words to replace enclosing single quote in double-quote, you might notice that the first solution of @jamessan does not work with the
.
command. To make it work, useciw' Ctrl+r Ctrl+p"
. Then.
will behave as you want it for the following word: instead of remembering the content of the register, it will remember you want whatever is in the register right now (kind of hard to explain, but if you try both, it will become obvious :-) )– autraNov 25, 2015 at 9:25 -
1@autra Tried a few more variants, <C-r> alone does not work for several words (as you pointed out). <C-r><C-r> doesn't work either (This is supposed to paste contents of register literally). <C-r><C-o> and <C-r><C-p> seem to work (these also paste literally, but differ in auto-indent or not). The difference lies in how Insert mode handles pasting register contents for all of the above variants. More details at mgiuffrida's fascinating answer at stackoverflow.com/questions/20617329/… Apr 19, 2020 at 2:36
Quote a word, using single quotes
ciw'Ctrl+r"'
It was easier for me to do it this way
ciw '' Esc P
-
10
-
2I prefer this as I can use it on terminals/repls with vim mode as Ctrl+r is usually already used for reverse history search.– krockAug 19, 2015 at 5:09
-
6
-
1@WilMooreIII jamessan's accepted answer does not allow
.
either. It pastes the previous word (instead of quoting the new one). So this answer still prevails (at least over that one, probably mappings do the job best).– bloodyFeb 3 at 16:52
Here's some mapping that could help:
:nnoremap <Leader>q" ciw""<Esc>P
:nnoremap <Leader>q' ciw''<Esc>P
:nnoremap <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.
-
Awesome idea! I ended up adding
map <Leader>' gewi'<Esc>A'<Esc>
to my.vimrc
file to insert single quote comments from current position to the end of the line; which helped me while converting some MSDOS scripts to bash. Mar 26, 2014 at 7:57 -
@Geoff, it works fine for single quotes. but for double quotes it insterts ` "" "" ` infront of the word Jul 18, 2014 at 14:28
-
@RameshVel It's possible you had some of your own macros that affected the right hand side of the mapping. I updated the mapping command to nnoremap so that other mappings are not expanded. I also improved the mappings. The previous ones had problems when the cursor is on the first word on a line. Jul 23, 2014 at 3:13
-
2This can also be easily adapted for visual mode to surround a selection with quotes, e.g.
:vnoremap <leader>q c""<esc>P
.– DominikJun 10, 2020 at 13:22
If you use the vim plugin https://github.com/tpope/vim-surround (or use VSCode Vim plugin, which comes with vim-surround pre-installed), its pretty convinient!
add
ysiw' // surround in word `'`
drop
ds' // drop surround `'`
change
cs'" // change surround from `'` to `"`
It even works for html tags!
cst<em> // change surround from current tag to `<em>`
check out the readme on github for better examples
-
2
The macro ways !
press q and q for recording into q register (we use "q" as shortcut to remember "quotes").
press shift + b move cursor to front of current word
press i type ' (a single quotes)
press esc then press e to move to end of word
press a then press ' again to surround the word with quotes.
press esc to get into normal mode.
finally press q to record it into
q
register.
How to use
- Move cursor to desired word.
- Press @q to surround a word with quotes.
- Press @@ if you want repeat it into another word.
You can alter step 4
with anything you like {a line, a word until found some character, etc}.
Make recorded macro persistent
- open .vimrc
- go to end of file
- change to insert mode. type this to make it persistent:
let @q='ctrl + r ctrl + r q'
save and quit
open your files, go to some words
now press
@q
if you do it correctly, magic things should appear in your words.
You can apply this to other macros you loved.
-
4Have to say I like this solution. No surround.vim necessary and easy invocation and creation of the macros. Also easily usable for whatever else you'd need (for me for example quote current word up until the end of the line, perfect for ansible). To show the macro do: "qp . To save it go to .vimrc and do: let @q = 'macro contents' (just for completeness) Apr 7, 2017 at 11:05
-
2I like this a lot. You can nest these macros also. So you could record in register j
@q w
and then you could wrap the nextn
words with quotes using withn@j
. Apr 26, 2018 at 16:39 -
2
-
1Pedantic, but, word and WORD are different in Vim. Shift+b = B, so step 2 should ideally be changed to "... front of current WORD". If you meant beginning of word however, you needn't use Shift. Apr 19, 2020 at 1:25
-
Thanks for point that. I use shift + b purposely to deal with WORD. The macro should run in word or WORD [0]. Actually step 3 should also changes to shift + e. [0] stackoverflow.com/a/14390568/341959– Brain90Apr 19, 2020 at 3:19
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"/
-
1My copied text also had commas in , so i just changed to this
:s/\v([a-Z]+)/"\1"/g
– tsukimiJul 20, 2015 at 23:52
To wrap in single quotes (for example) ciw'<C-r>"'<esc>
works, but repeat won't work. Try:
ciw'<C-r><C-o>"'<esc>
This puts the contents of the default register "literally". Now you can press .
on any word to wrap it in quotes. To learn more see :h[elp] i_ctrl-r
and more about text objects at :h text-objects
Source: http://vimcasts.org/episodes/pasting-from-insert-mode/
-
4Excellent tip! If anybody wants to make a mapping out of this, the proper notation is
ciw'<C-R><C-O>"'<Esc>
.– gltsDec 8, 2013 at 17:45 -
-
@CodeCrack It is CTRL-R. CTRL-R inserts the contents of the register at the cursor and stays in insert mode. Oct 28, 2015 at 11:08
-
This is repeatable as you mentionned, but when stored in a macro, repeating the macro with
.
will rewrite the content of the last actual call.– SbuJul 24, 2019 at 15:16 -
This is awesome! Could someone explain why the
<C-o>
is needed for the.
repeating to work? The help text makes it seem like it would only affect things like autoindenting. Nov 4, 2021 at 20:49
For users of VSCodeVim, Neovim and Macvim, you can do
vwS"
- You can replace
"
with whatever you would like to wrap by. - You can replace
w
with any other selection operator
-
3This also worked well for me on MacVIM but I had to use
viwS'
which wraps the word in single quotes. By far the easiest. May 29, 2019 at 19:31 -
2this only works if you are at the beginning of the word. If you want to do it from anywhere within the word, you can do:
viwS"
– geoywsJul 2, 2019 at 8:04 -
1
Add quote to surrounding of word: v i w S '
- viw: select word under the cursor
- S: add surrounding
- ': single quote
Change surrounding from ' to ": c s ' "
- cs: change surrounding
- ': single quote
- ": change to double quote
-
1The "s" command deletes the character under the cursor and enters insert mode, placing the cursor at the same location where the deleted character was. The "S" command deletes the entire line and enters insert mode at the beginning of the line. Is this what OP want? May 11 at 17:27
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 ".
-
2The most intuitive "manual" solution to me. Instead of the second replacement command (
'r
and"r
), you can just type.
And if you want to change more quotes,;
and,
take you to the next or previous one as they repeat the lastf/F/t/T
search in the same direction or the opposite one, respectively. Mar 10, 2015 at 0:13 -
Also, if you're dealing with "words" you can
B
to jump to the start of the WORDBr"f'.
– CervEdMar 16 at 10:36
Adding Quotes
I started using this quick and dirty function in my .vimrc
:
vnoremap q <esc>:call QuickWrap("'")<cr>
vnoremap Q <esc>:call QuickWrap('"')<cr>
function! QuickWrap(wrapper)
let l:w = a:wrapper
let l:inside_or_around = (&selection == 'exclusive') ? ('i') : ('a')
normal `>
execute "normal " . inside_or_around . escape(w, '\')
normal `<
execute "normal i" . escape(w, '\')
normal `<
endfunction
So now, I visually select whatever I want (typically via viw
- visually select inside word) in quotes and press Q for double quotes, or press q for single quotes.
Removing Quotes
vnoremap s <esc>:call StripWrap()<cr>
function! StripWrap()
normal `>x`<x
endfunction
I use vim-textobj-quotes so that vim treats quotes as a text objects. This means I can do vaq
(visually select around quotes. This finds the nearest quotes and visually selects them. (This is optional, you can just do something like f"vww
). Then I press s
to strip the quotes from the selection.
Changing Quotes
KISS. I remove quotes then add quotes.
For example, to replace single quotes with double quotes, I would perform the steps:
1. remove single quotes: vaqs
, 2. add new quotes: vwQ
.
- http://vim.wikia.com/wiki/Wrap_a_visual_selection_in_an_HTML_tag code from here was modified and used as part of my answer
- https://github.com/beloglazov/vim-textobj-quotes vim-text-obj-quotes
VIM for vscode does it awsomely. It's based one vim-surround if you don't use vscode.
Some examples:
"test" with cursor inside quotes type cs"' to end up with 'test'
"test" with cursor inside quotes type ds" to end up with test
"test" with cursor inside quotes type cs"t and enter 123> to end up with <123>test
test with cursor on word test type ysaw) to end up with (test)
wrap all words with quotes:
s/\(\w\+\)/"\1"/g
before:
aaa,bbb,ccc
after:
"aaa","bbb","ccc"
Here are some simple mappings that can be used to quote and unquote a word:
" 'quote' a word
nnoremap qw :silent! normal mpea'<Esc>bi'<Esc>`pl
" double "quote" a word
nnoremap qd :silent! normal mpea"<Esc>bi"<Esc>`pl
" remove quotes from a word
nnoremap wq :silent! normal mpeld bhd `ph<CR>
-
1It'd be great for everyone if you could elaborate your answer: how to add mappings, how to call them etc. Thanks. Apr 20, 2017 at 19:27
-
1
-
for some reason, the double quote return extra quote at the end like "word"". Aug 11, 2018 at 13:04
-
@ShuaiWang perhaps you've got autopairs or some similar extension installed? Removing that fixed that bug for me.– NephilimSep 16, 2018 at 14:26
I am using the vim-surround
command, almost vim in nature.
Surround.vim is all about "surroundings": parentheses, brackets, quotes, XML tags, and more. The plugin provides mappings to easily delete, change and add such surroundings in pairs.
Plugin 'tpope/vim-surround'
for example, To remove the delimiters entirely, press ds"
.
More details are here:
https://github.com/tpope/vim-surround
I'm using nnoremap in my .vimrc
To single quote a word:
nnoremap sq :silent! normal mpea'<Esc>bi'<Esc>`pl
To remove quotes (works on double quotes as well):
nnoremap qs :silent! normal mpeld bhd `ph<CR>
Rule to remember: 'sq' = single quote.
I wrote a script that does this:
function! WrapSelect (front)
"puts characters around the selected text.
let l:front = a:front
if (a:front == '[')
let l:back = ']'
elseif (a:front == '(')
let l:back = ')'
elseif (a:front == '{')
let l:back = '}'
elseif (a:front == '<')
let l:back = '>'
elseif (a:front =~ " ")
let l:split = split(a:front)
let l:back = l:split[1]
let l:front = l:split[0]
else
let l:back = a:front
endif
"execute: concat all these strings. '.' means "concat without spaces"
"norm means "run in normal mode and also be able to use \<C-x> characters"
"gv means "get the previous visual selection back up"
"c means "cut visual selection and go to insert mode"
"\<C-R> means "insert the contents of a register. in this case, the
"default register"
execute 'norm! gvc' . l:front. "\<C-R>\"" . l:back
endfunction
vnoremap <C-l> :<C-u>call WrapSelect(input('Wrapping? Give both (space separated) or just the first one: '))<cr>
To use, just highlight something, hit control l, and then type a character. If it's one of the characters the function knows about, it'll provide the correct terminating character. If it's not, it'll use the same character to insert on both sides.
Surround.vim can do more than just this, but this was sufficient for my needs.
Visual mode map example to add single quotes around a selected block of text:
:vnoremap qq <Esc>`>a'<Esc>`<i'<Esc>
In NVIM you can use this function and map <leader>sw
or <leader>sW
to use :lua Surround("w")
and :lua Surround("W")
respectively.
After pressing <leader>sw
or <leader>sW
in insert mode you will be asked for the character you want to surround with.
If you want to surround with characters whose closing character is different from the opening character, just type the opening one
Note that this is easily reproduced in VIM.
function Surround(w_or_W)
local open_char = vim.fn.input("Surround with: ")
local closed_char = nil
if open_char == "(" then closed_char = ")" end
if open_char == "[" then closed_char = "]" end
if open_char == "{" then closed_char = "}" end
if open_char == "<" then closed_char = ">" end
if open_char == "'" then closed_char = "'" end
if open_char == '"' then closed_char = '"' end
if open_char == "`" then closed_char = "`" end
if open_char == "/" then closed_char = "/" end
if open_char == "|" then closed_char = "|" end
if w_or_W == "w" then
vim.cmd("normal! ciw" .. open_char)
elseif w_or_W == "W" then
vim.cmd([[normal! ciW]] .. open_char)
end
vim.cmd("normal! p")
vim.cmd("normal! a" .. closed_char)
vim.cmd("normal! a")
end
vim.api.nvim_set_keymap("n", "<leader>sw", ":lua Surround('w')<CR>", { noremap = true, silent = true })
vim.api.nvim_set_keymap("n", "<leader>sW", ":lua Surround('W')<CR>", { noremap = true, silent = true })
how about this?
:%s/\'/"/g
-
2This command operates on the whole file. I just need to change single words. Jan 27, 2010 at 15:16
-
4Without the
%
, it'll work just on the current line unless you've selected the entire file– EmilyJan 27, 2010 at 23:35
You can map a key to surround a word by any char or pair of chars with this line:
noremap " yiw :let surrounder=input('surrounder(s)? ') <bar> :execute 'normal ciw'.surrounder[0].'<c-r>"'.(surrounder[1]??surrounder[0]).'<c-v><esc>'<cr>
in this case is mapped to ", you can change it to whatever you want.
If you enter a single char it will be used as surrounder in both extremes, if you enter 2 chars it will use the first at the beginning and the second at the end.
Ejs:
- you press " over a word and enter ' will result in 'word'
- you press " over a word and enter [] will result in [word]
F'x,x
(and accordingly for double quotes); to toggle from single to double:F'r",.
(and accordingly reverse). Contrary to very complicated answers below.ds'
for deleting quotes andcs'"
for changing.