This repository has been archived on 2024-05-23. You can view files and clone it, but cannot push or open issues or pull requests.
katex-html/convert.rb

39 lines
1.2 KiB
Ruby
Raw Normal View History

require "open3"
require "nokogiri"
require "net/http"
require "json"
2022-03-27 21:21:44 -07:00
require "cgi"
def render_cached(cache, display, string, render_comment = nil)
2022-03-27 21:21:44 -07:00
string = CGI.unescapeHTML string
cache.fetch(string) do |new|
puts " Rendering #{render_comment || new}"
res = Net::HTTP.post URI("http://localhost:8000/render"),
{ :equations => [ { :str => string, :display => display } ] }.to_json,
"Content-Type" => "application/json"
cache[string] = JSON.parse(res.body)[0]
end
end
def perform_katex_sub(inline_cache, display_cache, content)
rendered = content.gsub /\\\(((?:[^\\]|\\[^\)])*)\\\)/ do |match|
render_cached(inline_cache, false, $~[1])
end
rendered = rendered.gsub /\$\$((?:[^\$]|$[^\$])*)\$\$/ do |match|
render_cached(display_cache, true, $~[1], "display")
end
return rendered
end
files = ARGV[0..-1]
inline_cache, display_cache = {}, {}
files.each do |file|
puts "Rendering file: #{file}"
document = Nokogiri::HTML.parse(File.open(file))
document.search('//*[not(ancestor-or-self::code or ancestor-or-self::script)]/text()').each do |t|
t.replace(perform_katex_sub(inline_cache, display_cache, t.content))
end
File.write(file, document.to_html(encoding: 'UTF-8'))
end