Skip to content

Instantly share code, notes, and snippets.

@AndrewRadev
Last active August 13, 2016 13:57
Show Gist options
  • Save AndrewRadev/5164953 to your computer and use it in GitHub Desktop.
Save AndrewRadev/5164953 to your computer and use it in GitHub Desktop.
Use Vim's :TOhtml to make the core of a syntax highlighter.
#! /usr/bin/env ruby
require 'tempfile'
require 'vimrunner'
require 'nokogiri'
require 'json'
if ARGV.count < 2
puts "USAGE: tohtml <colorscheme-file> <filename> [filenames ...]"
exit 1
end
def parse_html(html)
doc = Nokogiri::HTML(html)
styles = []
doc.css('style').first.content.split("\n").each do |line|
line = line.strip
next if line == '<!--' or line == '-->'
styles << line
end
code = doc.css('#vimCodeElement').first.children.to_s
[styles, code]
end
colorscheme_file = ARGV[0]
filenames = ARGV[1, ARGV.length].dup
css_definitions = []
code_blocks = []
Vimrunner.start_gvim do |vim|
vim.command("source #{colorscheme_file}")
filenames.each do |filename|
styles = nil
code = nil
Tempfile.open('tohtml') do |output|
vim.edit(filename)
vim.command('TOhtml')
vim.command("saveas! #{output.path}")
vim.command('quit')
styles, code = parse_html(output.read)
end
css_definitions += styles
code_blocks << code
end
end
puts({'css' => css_definitions.uniq, 'code' => code_blocks}.to_json)
require 'json'
json = %x[tohtml ~/.vim/colors/andrew.vim test.py html_test.rb]
data = JSON.parse(json)
style = data['css'].join("\n")
code = data['code'].map do |code_block|
"<pre>#{code_block}</pre>"
end.join("\n<br>\n")
puts <<-HTML
<html>
<head>
<title>Tohtml</title>
<style>
#{style}
</style>
</head>
<body>
#{code}
</body>
</html>
HTML
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment