How do I export my syntax-highlighted Vim buffer to an HTML file?
Answer
:TOhtml
Explanation
The :TOhtml command converts the current buffer — complete with its syntax highlighting colors — into a standalone HTML file. It faithfully reproduces your colorscheme so the exported HTML looks exactly like your Vim session. This is useful for sharing syntax-highlighted code snippets, creating documentation, or embedding colored code in presentations or web pages without relying on external tools.
How it works
:TOhtmlis a built-in Vim command provided by the2html.vimplugin (shipped with Vim/Neovim)- It opens a new buffer containing the HTML representation of the current file
- The HTML includes inline CSS styles derived from the active colorscheme
- Save the new buffer with
:w snippet.htmlto write it to disk
To convert only a selection, enter visual mode first, then run :'<,'>TOhtml.
Example
To export the current file to HTML:
:TOhtml
:w code_snippet.html
To export only a selected range:
:'<,'>TOhtml
Tips
- Use
:set background=lightbefore:TOhtmlif you need a light-background export - The output includes
<pre>tags with per-character<span>elements for each highlight group - Run
:help 2html.vimto see options likeg:html_use_css,g:html_number_lines, andg:html_line_idsfor fine-tuned control