Skip to content

Instantly share code, notes, and snippets.

@charlesetc
Last active April 29, 2019 23:19
Show Gist options
  • Save charlesetc/06abaa79a5950e64ef7ff2f831817817 to your computer and use it in GitHub Desktop.
Save charlesetc/06abaa79a5950e64ef7ff2f831817817 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'tempfile'
require 'open3'
INF = 10000000000
def ap(file)
File.absolute_path file
end
def convert_file(text)
infile = Tempfile.new("latex")
outfile = Tempfile.new("latex")
errfile = Tempfile.new("latex")
output = []
while text =~ /\(\$[^$].*[^$]\$\)/m or text =~ /\[\$[^$].*[^$]\$\]/m
round_index = (text.index /\(\$[^$]/) || INF
square_index = (text.index /\[\$[^$]/) || INF
if round_index < square_index then
c = text[text.index(/\(\$[^$]/) + 2]
first_bit, middle = text.split(/\(\$[^$]/, 2)
middle = c + middle
c = middle[middle.index(/[^$]\$\)/)]
middle, last_bit = middle.split(/[^$]\$\)/, 2)
middle += c
flags = ""
else
c = text[text.index(/\[\$[^$]/) + 2]
first_bit, middle = text.split(/\[\$[^$]/, 2)
middle = c + middle
c = middle[middle.index(/[^$]\$\]/)]
middle, last_bit = middle.split(/[^$]\$\]/, 2)
middle += c
flags = "-d"
end
File.write(infile, middle)
converted = ""
if system("katex #{flags} -i #{ap infile} -o #{ap outfile} 2> #{ap errfile}")
converted = File.read outfile
output << first_bit << converted
text = last_bit
else
puts middle
STDERR.puts (File.read errfile)
exit 1
end
end
output << text
output.join
.gsub("($$", "($")
.gsub("$$)", "$)")
.gsub("[$$", "[$")
.gsub("$$]", "$]")
end
Dir.glob("*.md").each do |filepath|
txt = convert_file(File.read(filepath))
File.write(File.join("hugo-site/content", filepath), txt)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment