Recent changes Random page
GAMING
Technology
 
Gaming
Entertainment
Science Fiction
Biggest wikis
Hobbies
Music
See more...

Pasting code with syntax coloring in emails

From Vim Tips Wiki

(Redirected from To Html)
Jump to: navigation, search

Tip 198 Previous Next created 2002 · complexity basic · author Hari Krishna Dara · version 6.0


Many file types can be displayed with syntax highlighting. :help syntax

Vim provides a script that can create an html document (including the foreground and background colors, and syntax highlighting) from the current file, or from selected lines. :help convert-to-HTML

Contents

[edit] Creating html

In gvim, use "Convert to HTML" on the Syntax menu. A new file is created, containing the html equivalent of all text from the current buffer.

The same operation can be performed by entering a command:

:TOhtml

If you visually select some lines before entering :TOhtml, only the selected lines will be converted.

If your color scheme uses a dark background, you may want to temporarily switch to a white background before creating the html document. One way to do that is to use the command:

:colorscheme default

[edit] Using the html

Of course the html file created by :TOhtml can be used on a web site. In addition, on some systems it may be useful to open the html file in a web browser for printing. On Windows, you can copy text from within Internet Explorer, and paste it into some other applications in RTF format.

[edit] Modifying the html

The html generated by :TOhtml places the color of the background and default foreground into the tag <body>. If the code is pasted into an html-enabled web forum, those colors disappear.

This function solves the problem:

function! MyToHtml(line1, line2)
  exec a:line1.','.a:line2.'TOhtml'
  %g/<body/normal k$dgg
  %s/<body\s*\(bgcolor="[^"]*"\)\s*text=\("[^"]*"\)\s*>/<table \1 cellPadding=0><tr><td><font color=\2>/
  %s#</body>\(.\|\n\)*</html>#\='</font></td></tr><tr><td><font color=white><span style="float: right;color: '.synIDattr(44,"fg").'"><i><small>Generated with Vim(<a style="color: '.synIDattr(44,"fg").'" href="[[VimTip1174>tip]] \#1174</a>)</small></i></span></font></td></tr></table>'#i
endfunction
command -range=% MyToHtml :call MyToHtml(<line1>,<line2>)

Now you can select a range of lines, type :MyToHtml and use the result to post your code to an html-enabled web forum.

 TO DO 

  • Confirm that MyToHtml is doing something useful.
  • Remove the "Generated with Vim...1174" noise added by MyToHtml.

[edit] Comments

There is a Perl module Text::VimColor that runs Vim to generate HTML or XML automatically. There are some usage notes.


Rate this article:
Share this article: