Vim Tips Wiki

Simple Macros to quote and unquote a word

Redirected from VimTip844

1,624pages on
this wiki
Add New Page
Talk0 Share
Tip 844 Printable Monobook Previous Next

created 2005 · complexity basic · author Anders Thøgersen · version 6.0

Here are some simple mappings that can be used to quote and unquote a word. Place the cursor over a word and press qw to place single quotes, or qd to place double quotes around the word. To remove quotes press wq.

" '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>

See alsoEdit

  • surround.vim plugin to surround text with brackets, quotes; much more


The tip doesn't work for single character words, but this does:

nnoremap qw :silent! normal "zyiw<Esc>:let @z="'".@z."'"<CR>cw<c-r>z<Esc>b
nnoremap qd :silent! normal "zyiw<Esc>:let @z="\"".@z."\""<CR>cw<c-r>z<Esc>b

Blows away the "z" register, though.

I use the following for quoting visual selections (keeps all registers intact)

vmap <silent> <Leader>qs :call Quote("'")<CR>
vmap <silent> <Leader>qd :call Quote('"')<CR>
function! Quote(quote)
  let save = @"
  silent normal gvy
  let @" = a:quote . @" . a:quote
  silent normal gvp
  let @" = save

Here is what I think is the nicest solution for a word-quoting macro.

" Quote a word consisting of letters from iskeyword.
nnoremap <silent> qw :call Quote('"')<CR>
nnoremap <silent> qs :call Quote("'")<CR>
nnoremap <silent> wq :call UnQuote()<CR>
function! Quote(quote)
  normal mz
  exe 's/\(\k*\%#\k*\)/' . a:quote . '\1' . a:quote . '/'
  normal `zl

function! UnQuote()
  normal mz
  exe 's/["' . "'" . ']\(\k*\%#\k*\)[' . "'" . '"]/\1/'
  normal `z

Surround current word or visually selected text with double quotes:

nnoremap <Leader>" ciw"<C-r>""<Esc>
vnoremap <Leader>" c"<C-r>""<Esc>

Ad blocker interference detected!

Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.

Also on Fandom

Random Wiki