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
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:
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. Copy-paste of rich text from the browser into an email client or other application often discards the background color. One way to do that is to use the command:
Using the HTMLEdit
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.
Configuring the outputEdit
The latest version of :TOhtml will make standards-compliant code by default, but for Vim versions before 7.3, it is highly recommended to put
:let g:html_use_css = 1 into your .vimrc.
Modifying the HTMLEdit
If you want to paste the generated HTML code into a web forum, often you cannot also paste the CSS generated by default, or prefer not to. Old versions of :TOhtml generate with font tags and the like by default, but you can still use this old behavior in new versions with
:let g:html_use_css = 0 before generating code.
When using this option, 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, by removing the HTML header and replacing the
<body> tag with a
<table> instead. This allows you to paste a valid (albeit deprecated) snippet of HTML into the forum with colors fully defined.
function! MyToHtml(line1, line2) " make sure to generate in the correct format let old_css = 1 if exists('g:html_use_css') let old_css = g:html_use_css endif let g:html_use_css = 0 " generate and delete unneeded lines exec a:line1.','.a:line2.'TOhtml' %g/<body/normal k$dgg " convert body to a table %s/<body\s*\(bgcolor="[^"]*"\)\s*text=\("[^"]*"\)\s*>/<table \1 cellPadding=0><tr><td><font color=\2>/ %s#</body>\(.\|\n\)*</html>#\='</font></td></tr></table>'#i " restore old setting let g:html_use_css = old_css 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.