Wikia

Vim Tips Wiki

Changes: Simple Macros to quote and unquote a word

Edit

Back to page

(tweak + move in fixed method from 605 (originally from 1011))
(Change <tt> to <code>, perhaps also minor tweak.)
 
Line 12: Line 12:
 
|category2=
 
|category2=
 
}}
 
}}
Here are some simple mappings that can be used to quote and unquote a word. Place the cursor over a word and press <tt>qw</tt> to place single quotes, or <tt>qd</tt> to place double quotes around the word. To remove quotes press <tt>wq</tt>.
+
Here are some simple mappings that can be used to quote and unquote a word. Place the cursor over a word and press <code>qw</code> to place single quotes, or <code>qd</code> to place double quotes around the word. To remove quotes press <code>wq</code>.
   
 
<pre>
 
<pre>

Latest revision as of 05:51, July 13, 2012

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>

Around Wikia's network

Random Wiki