From bdc6cf985ba0fa319d613b8ec874eb032dc04b03 Mon Sep 17 00:00:00 2001 From: Danila Fedorin Date: Sat, 9 May 2020 18:14:43 -0700 Subject: [PATCH] Cache KaTeX return values in Ruby script. --- blog/convert.rb | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/blog/convert.rb b/blog/convert.rb index 4962ee2..697dc2d 100644 --- a/blog/convert.rb +++ b/blog/convert.rb @@ -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