diff --git a/convert.rb b/convert.rb index bbcbd00..51e8c94 100644 --- a/convert.rb +++ b/convert.rb @@ -25,13 +25,16 @@ class KatexRenderer end def substitute(content) + found_any = false rendered = content.gsub /\\\(((?:[^\\]|\\[^\)])*)\\\)/ do |match| + found_any = true render(false, $~[1]) end rendered = rendered.gsub /\$\$((?:[^\$]|$[^\$])*)\$\$/ do |match| + found_any = true render(true, $~[1]) end - return rendered + return rendered, found_any end end @@ -58,8 +61,16 @@ renderer = KatexRenderer.new(katex) files.each do |file| puts "Rendering file: #{file}" document = Nokogiri::HTML.parse(File.open(file)) + found_any = false document.search('//*[not(ancestor-or-self::code or ancestor-or-self::script)]/text()').each do |t| - t.replace(renderer.substitute(t.content)) + rendered, found_any = renderer.substitute(t.content) + t.replace(rendered) end + + # If we didn't find any mathematical equations, no need to include KaTeX CSS. + unless found_any + document.css('link[href$="katex.css"], link[href$="katex.min.css"]').each(&:remove) + end + File.write(file, document.to_html(encoding: 'UTF-8')) end