Fandom

Vim Tips Wiki

Simple Macros to quote and unquote a word

1,624pages on
this wiki
Add New Page
Talk0 Share

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.

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

CommentsEdit

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
endfunction

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
endfunction

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

Surround current word or visually selected text with double quotes:

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

Also on Fandom

Random Wiki