What's the best shortcut or plugin to comment out HTML/XML elements?
And also need to uncomment.
You can use a combination of matching XML tags, as can be seen in this question and Perl's search and replace.
For instance, given this snippet:
<TypeDef name="a">
<ArrayType high="14" low="0">
<UndefType type="node">
</UndefType>
</ArrayType>
</TypeDef>
Put the cursor on either the opening or closing TypeDef and type the following sequence:
vat:s/^\(.*\)$/<!-- \1 -->/
v
- puts you into visual modeat
- selects the whole XML tag:s/^\(.*\)$/<!-- \1 -->/
- surrounds each line with '<!-- ... -->'
, the comment delimiters for XMLAlternatively, you can just delete it like this:
dat
d
- delete according to the following movementsat
- as beforeTo delete id use then use vat:s/-->//
to delete comments
I use the tComment plugin. You can find a detailed video tutorial here on how to install and use it.
The plugin is very useful as it allows you to toggle comments from both the command and input interface, and you can do so using both visual mode and motions (like gcw
, or gc3w
)
To comment: vato<ESC>i<!-- <ESC>vatA --><ESC>
vato
Esc
i<!--
Esc
vat
A -->
Esc
Note: You may use I
to insert directly from visual mode, and it'll work with multi-line blocks, but for single line elements it'll mess up the indentation.
To uncomment: vat<ESC>4xvato<Esc>5X
vat
Esc
4x
vato
5X
You may add these lines to your .vimrc (or init.vim in neovim) to remap shortcuts:
" Comment HTML element
nnoremap <silent> <leader>h :set lazyredraw<cr>mhvato<ESC>i<!-- <ESC>vatA --><ESC>`h:set nolazyredraw<cr>
" Uncomment HTML element
nnoremap <silent> <leader>H :set lazyredraw<cr>mhvat<ESC>4xvato<ESC>5X`h:set nolazyredraw<cr>
Warning:
u
ndo if you try to uncomment a non-commented area for it will delete some characters. You could avoid this by replacing 4x
with d2f-
and 5X
with dF!
, but then you'd have issues with this kind of workaround and anything else in the same line that contains -...- or !.Notes:
<leader>h
and <leader>H
to what you'd like to use.:set lazyredraw
is to hide intermediate steps by not redrawing the screen and :set nolazyredraw
to avoid possible visual glitches afterwards.mh
is to save current cursor position and `h
is to jump back to that line and column. You may replace h with any other lower case letter.Tip: Use :source $MYVIMRC to apply changes done to .vimrc (or init.vim) without having to restart vim.