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.vimfor all available options (number of columns, font size, etc.) - Set
g:html_no_progress = 1in your vimrc to skip the progress bar for large files - Set
g:html_line_ids = 1to addidanchors to each line for linking to specific lines - Use
g:html_use_css = 0to inline styles instead of a<style>block (for email clients)