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

How do I export the current buffer as syntax-highlighted HTML from within Vim?

Answer

:%TOhtml

Explanation

Vim ships with a built-in plugin that converts the current buffer into a standalone HTML file, complete with your exact syntax highlighting colors. The resulting file can be shared in emails, pasted into web pages, or used to generate documentation with proper color-coded code.

How it works

  • :%TOhtml — converts the entire buffer to HTML and opens the result in a new buffer
  • :'<,'>TOhtml — converts only the visually selected lines
  • :TOhtml — same as :%TOhtml

Vim reads your current colorscheme and syntax settings to produce accurate colors. The output is a self-contained HTML file with inline CSS — no external stylesheets required.

Example

Open a Python file and run:

:%TOhtml

Vim opens a new buffer named file.py.html with content like:

<!DOCTYPE html>
<html>
<head><title>file.py</title>
<style>...colorscheme CSS...</style>
</head>
<body>...highlighted code...</body>
</html>

Save with :w and open in a browser to view the styled output.

Tips

  • Run :help 2html.vim for all available options (number of columns, font size, etc.)
  • Set g:html_no_progress = 1 in your vimrc to skip the progress bar for large files
  • Set g:html_line_ids = 1 to add id anchors to each line for linking to specific lines
  • Use g:html_use_css = 0 to inline styles instead of a <style> block (for email clients)

Next

How do I highlight all occurrences of a yanked word without typing a search pattern?