Cache KaTeX return values in Ruby script.

This commit is contained in:
Danila Fedorin 2020-05-09 18:14:43 -07:00
parent 307cf74f29
commit bdc6cf985b
1 changed files with 14 additions and 12 deletions

View File

@ -1,33 +1,35 @@
require "open3"
require "nokogiri"
def perform_katex_sub(content)
rendered = content.gsub /\\\(((?:[^\\]|\\[^\)])*)\\\)/ do |match|
puts " Rendering #{$~[1]}"
Open3.popen3("katex") do |i, o, e, t|
i.write $~[1]
def render_cached(cache, command, string, render_comment = nil)
cache.fetch(string) do |new|
puts " Rendering #{render_comment || new}"
cache[string] = Open3.popen3(command) do |i, o, e, t|
i.write new
i.close
o.read.force_encoding(Encoding::UTF_8).strip
end
end
end
def perform_katex_sub(inline_cache, display_cache, content)
rendered = content.gsub /\\\(((?:[^\\]|\\[^\)])*)\\\)/ do |match|
render_cached(inline_cache, "katex", $~[1])
end
rendered = rendered.gsub /\$\$((?:[^\$]|$[^\$])*)\$\$/ do |match|
puts " Rendering display."
Open3.popen3("katex -d") do |i, o, e, t|
i.write $~[1]
i.close
o.read.force_encoding(Encoding::UTF_8).strip
end
render_cached(display_cache, "katex -d", $~[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(self::code)]/text()').each do |t|
t.replace(perform_katex_sub(t.content))
t.replace(perform_katex_sub(inline_cache, display_cache, t.content))
end
File.write(file, document.to_html)
end