Cache KaTeX return values in Ruby script.
This commit is contained in:
parent
307cf74f29
commit
bdc6cf985b
|
@ -1,33 +1,35 @@
|
||||||
require "open3"
|
require "open3"
|
||||||
require "nokogiri"
|
require "nokogiri"
|
||||||
|
|
||||||
def perform_katex_sub(content)
|
def render_cached(cache, command, string, render_comment = nil)
|
||||||
rendered = content.gsub /\\\(((?:[^\\]|\\[^\)])*)\\\)/ do |match|
|
cache.fetch(string) do |new|
|
||||||
puts " Rendering #{$~[1]}"
|
puts " Rendering #{render_comment || new}"
|
||||||
Open3.popen3("katex") do |i, o, e, t|
|
cache[string] = Open3.popen3(command) do |i, o, e, t|
|
||||||
i.write $~[1]
|
i.write new
|
||||||
i.close
|
i.close
|
||||||
o.read.force_encoding(Encoding::UTF_8).strip
|
o.read.force_encoding(Encoding::UTF_8).strip
|
||||||
end
|
end
|
||||||
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|
|
rendered = rendered.gsub /\$\$((?:[^\$]|$[^\$])*)\$\$/ do |match|
|
||||||
puts " Rendering display."
|
render_cached(display_cache, "katex -d", $~[1], "display")
|
||||||
Open3.popen3("katex -d") do |i, o, e, t|
|
|
||||||
i.write $~[1]
|
|
||||||
i.close
|
|
||||||
o.read.force_encoding(Encoding::UTF_8).strip
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
return rendered
|
return rendered
|
||||||
end
|
end
|
||||||
|
|
||||||
files = ARGV[0..-1]
|
files = ARGV[0..-1]
|
||||||
|
inline_cache, display_cache = {}, {}
|
||||||
|
|
||||||
files.each do |file|
|
files.each do |file|
|
||||||
puts "Rendering file: #{file}"
|
puts "Rendering file: #{file}"
|
||||||
document = Nokogiri::HTML.parse(File.open(file))
|
document = Nokogiri::HTML.parse(File.open(file))
|
||||||
document.search('//*[not(self::code)]/text()').each do |t|
|
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
|
end
|
||||||
File.write(file, document.to_html)
|
File.write(file, document.to_html)
|
||||||
end
|
end
|
||||||
|
|
Reference in New Issue
Block a user