Vim logo vim online Vim Book Ad

basic Tip #346: Wrap text in HTML/XML tags after prompting for the tag name

 tip karma   Rating 18/9, Viewed by 630 

created:   October 16, 2002 8:33      complexity:   basic
author:   [email protected]      as of Vim:   6.0


Someone else posted this sometime ago on this mailing list, I have enhanced it slightly and made a tip out of it.
I thought it was pretty clever and very generic.

If you have a block of text and you want to wrap it in <TAG_NAME>...</TAG_NAME> then this function will prompt you for the tag name and wrap the text.

If there is no text VISUALLY selected, it will wrap the current word in the tag, otherwise it will wrap the visually selected text.

It will also strip off any leading spaces.
For the end tag, it will use the first word of the tag only.

Consider an ANT build file, which has tags like this:
<target name="init">
...
</target>

When prompted for the tag you would enter:
target name="init"

And it will wrap the text in:
<target name="init">
...
</target>


" Tag Select/Wrapper
" These mappings and TagSelection function will allow you to place " an XML tag around either the current word, or the current selected " text
nmap <Leader>t viw<Leader>t
vnoremap <Leader>t <Esc>:call TagSelection()<CR>

nmap <Leader>t viw<Leader>t
vnoremap <Leader>t <Esc>:call TagSelection()<CR>

function! TagSelection()
  let l:tag = input("Tag name? ")
  " exec "normal `>a</" . l:tag . ">\e"
  " Strip off all but the first work in the tag for the end tag
  exec "normal `>a</" .
              \ substitute( l:tag, '[ \t"]*\(\<\w*\>\).*', '\1>\e', "" )
  exec "normal `<i"
              \ substitute( l:tag, '[ \t"]*\(\<.*\)', '<\1>\e', "" )
endfunction

 rate this tip  Life Changing Helpful Unfulfilling 

<<Visual Studio + vim Quickfix mode + cygwin + XFree86 | Format paragraph without changing the cursor position >>

Additional Notes

If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to [email protected] after searching the archive. Help Bram help Uganda.
SourceForge Logo