Module: Calculus::Latex

Included in:
Expression
Defined in:
lib/calculus/latex.rb

Constant Summary collapse

TEMPLATE =
"  \\\\documentclass{article}\n  \\\\usepackage{amsmath,amssymb}\n  \\\\begin{document}\n  \\\\thispagestyle{empty}\n  $$ # $$\n  \\\\end{document}\n".gsub(/^\s+/, '')

Instance Method Summary collapse

Instance Method Details

#missing_commandsObject



32
33
34
35
36
37
# File 'lib/calculus/latex.rb', line 32

def missing_commands
  commands = []
  commands << "latex" unless can_run?("latex -v")
  commands << "dvipng" unless can_run?("dvipng -v")
  commands
end

#to_png(background = 'White', density = 700) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/calculus/latex.rb', line 16

def to_png(background = 'White', density = 700)
  raise CommandNotFoundError, "Required commands missing: #{missing_commands.join(', ')} in PATH. (#{ENV['PATH']})" unless missing_commands.empty?

  temp_path = Dir.mktmpdir
  Dir.chdir(temp_path) do
    File.open("#{sha1}.tex", 'w') do |f|
      f.write(TEMPLATE.sub('#', self.to_s))
    end
    `latex -interaction=nonstopmode #{sha1}.tex && dvipng -q -T tight -bg #{background} -D #{density.to_i} -o #{sha1}.png #{sha1}.dvi`
  end
  return File.join(temp_path, "#{sha1}.png") if $?.exitstatus.zero?
ensure
  File.unlink("#{sha1}.tex") if File.exists?("#{sha1}.tex")
  File.unlink("#{sha1}.dvi") if File.exists?("#{sha1}.dvi")
end