History Report a problem
Article Edit this page Discussion

Wrap a visual selection in an HTML tag

From Vim Tips Wiki

(Redirected from VimTip1495)
Jump to: navigation, search

Tip 1495 Previous TipNext Tip

Created: January 29, 2007 Complexity: intermediate Author: Max Cantor Minimum version: 5.7 Karma: 12/6 Imported from: Tip#1495


There are a bunch of HTML wrapper tips and tricks out there, but I couldn't find any that suited my desire to be able to quickly wrap an arbitrary visual highlight in an arbitrary HTML tag.

I haven't tested the function below thoroughly, but it works in every visual mode, even if you're doing per-character visual mode and end your selection on a different line. I like to make all of my HTML tags uppercase, but if you don't bother, you can change the line:

let a:tag = toupper( input( "Tag to wrap block: ") )

to

let a:tag = input( "Tag to wrap block: ")

There may be a quicker way to input the arbitrary tag than with an input() call, but I kind of like this one.

Here's the function, and a mapping to go with it:

" Wraps visual selection in an HTML tag
vmap ,w <ESC>:call VisualHTMLTagWrap()<CR>
function! VisualHTMLTagWrap()
  let a:tag = toupper( input( "Tag to wrap block: ") )
  let a:jumpright = 2 + len( a:tag )
  normal `<
  let a:init_line = line( "." )
  exe "normal i<".a:tag.">"
  normal `>
  let a:end_line = line( "." )
  " Don't jump if we're on a new line
  if( a:init_line == a:end_line )
    " Jump right to compensate for the characters we've added
    exe "normal ".a:jumpright."l"
  endif
  exe "normal a</".a:tag.">"
endfunction

[edit] Comments

Why don't you do it the opposite way:

normal `>
exe "normal a</".a:tag.">"
normal `<
exe "normal i<".a:tag.">"

Here, you don't have to care about shifting your selected area.

[edit] Tags case

Since XHTML defines all tags and attributes to be in lowercase, I'd suggest to follow this convention in HTML as well.


Rate this article:

Share this article:

Hubs Highlights International Sites Wikia messages
Entertainment
Gaming
Cartoons & Comics
Science Fiction
Hobbies
Sports
See all...
Grand Theft Auto
Pixar
Legend of Zelda Wiki
Terminator Wiki
Everquest II Wiki
Flash Gordon
German
Spanish
Chinese
Japanese
More...
Wikia is hiring for several open positions
Send this article to a friend
"Wrap a visual selection in an HTML tag"
 
 
Hi!

I thought you'd like this page from Wikia!

http://vim.wikia.com

Come check it out!
Send confirmation


.