vimtricks.wiki Concise Vim tricks, one at a time.

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

  • :TOhtml is a built-in Vim command provided by the 2html.vim plugin (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.html to 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=light before :TOhtml if you need a light-background export
  • The output includes <pre> tags with per-character <span> elements for each highlight group
  • Run :help 2html.vim to see options like g:html_use_css, g:html_number_lines, and g:html_line_ids for fine-tuned control

Next

How do I replace only part of a matched pattern using \zs and \ze in a substitution?