Class: Jekyll::JekyllTexEqn::Generate

Inherits:
Object
  • Object
show all
Defined in:
lib/jekyll-tex-eqn.rb

Overview

Tool-class for doing all the SVG generation

Constant Summary collapse

@@basedir =
Util.get_option(Util::TMPDIR_KEY, Util::DEFAULT_TMPDIR)
@@outdir =
Util.get_option(Util::OUTPUTDIR_KEY, Util::DEFAULT_OUTPUTDIR)
@@backend =
Util.get_option(Util::BACKEND_KEY, Util::DEFAULT_BACKEND)
@@options =
Util.get_option(Util::OPTIONS_KEY, []).join(" ")
@@pdf =

This is the PDF command. The provided options are mandatory for smooth running:

* "-halt-on-error" means LaTeX will exit upon error, instead of 
asking the user to provide a solution
* "-interaction nonstopmode" remove any form of interaction with
LaTeX
* "-file-line-error" put the file name and the line number for errors
(better for debugging your code)
* "--jobname=output" means the result of LaTeX will be named
"output.pdf"; this makes things easier during the process
"#{@@backend} -halt-on-error -interaction nonstopmode -file-line-error --jobname=output #{@@options}"

Class Method Summary collapse

Class Method Details

.do_render(context, content, scale, begineqn, endeqn) ⇒ Object

Perform a full rendering step, i.e. create the Tex file, compile, crop and transform into an SVG



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/jekyll-tex-eqn.rb', line 217

def self.do_render(context, content, scale, begineqn, endeqn)
  content.strip!
  path = context.registers[:page]['path']
  file = Generate.filename(path, content)
  texbase = "#{@@basedir}/#{file}"
  texfile = "#{texbase}.tex"
  svgfile = "#{@@outdir}/#{file}.svg"

  # If the SVG file already exists, no need to re-render it (usually)
  # If the TeX file already exists, this usually mean something went wrong and it is
  # erroneous!
  if !File.exist?(texfile) && !File.exist?(svgfile) then
    Jekyll.logger.info("Generating image file #{file}")
    Generate.generate_file(context, content, begineqn, endeqn, texfile)
    Jekyll.logger.info("Processing file #{file}")
    Generate.run_cmd(texbase, svgfile)
    File.delete(texfile)
    if File.exist?(texbase) then
      FileUtils.remove_dir("#{@@basedir}/#{file}")
    end
  end

  # Retrieve SVG dimensions
  svghead = File.readlines(svgfile)[1]
  width = svghead[/width="(\d+)[a-z]+"/,1]
  height = svghead[/height="(\d+)[a-z]+"/,1]

  { file: svgfile, width: width.to_f * scale, height: height.to_f * scale } # Dimensions are scaled
end

.filename(filepath, content) ⇒ Object

Build a file name where the code will be stored, based on the "host" file path (i.e. file where the equation is located) and the equation's content. The filename is generated by making sure there are no spaces, and using a hash function on the content to obtain (virtually) unique names.



176
177
178
179
180
181
182
183
# File 'lib/jekyll-tex-eqn.rb', line 176

def self.filename(filepath, content)
  id = Digest::MD5.hexdigest content
  pagepath = filepath.gsub("/", "_").gsub(" ", "-")
  while pagepath[0] == '_' do # Weird jekyll behaviour: files starting with an underscore are not copied during build
    pagepath = pagepath[1..-1]
  end
  "#{pagepath}-#{id}"
end

.generate_file(context, content, begineqn, endeqn, file) ⇒ Object

Generate a tex file from the given content, using the provided equation environment opener and closer (e.g. [-], \beginequation-\endequation, etc.)



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/jekyll-tex-eqn.rb', line 187

def self.generate_file(context, content, begineqn, endeqn, file)
  text =  "\\documentclass{minimal}\n"
  pkgs = Util.get_option(Util::PACKAGES_KEY, Util::DEFAULT_PACKAGES)
  pkgs.concat Util.get_option(Util::EXTRAPACKAGES_KEY, [])
  for p in pkgs do
    text << "\\usepackage"
    if p.include?(:option) then
      text << '[' << (p[:option].nil? ? p['option'] : p[:option]) << ']'
    end
    text << '{' << (p[:name].nil? ? p['name'] : p[:name]) << '}' << "\n"
  end
  
  text << Util.get_option(Util::EXTRAHEAD_KEY, "")
  text << "\n\\begin{document}\n"
  text << begineqn 
  text << content
  text << endeqn << "\n"
  text << "\\end{document}\n"
  
  begin
    File.open(file, 'w') { |f|
      f.write text
    }
  rescue => e
    raise Util.report(context, "error while creating tex file '#{file}'", e)
  end
end

.run_cmd(texbase, svgfile) ⇒ Object

Run the set of commands that perform the conversion from TeX to SVG This takes as argument "basedir", the directory where TeX files are located, and "base" the basename of the .tex file to process (more convenient when browsing directory). Also takes "outdir", the directory where to export the SVG, and "pdf", the pdfxx command that performs the TeX => PDF conversion (easier because then this value is calculated only once).



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/jekyll-tex-eqn.rb', line 124

def self.run_cmd(texbase, svgfile)
  text = ""

  Jekyll.logger.debug("Clean up...")

  # Cleanup if needed (in case of past error for instance)
  if !File.exist?("#{texbase}") then
    Dir.mkdir("#{texbase}")
  end

  # Ensure output dir exists
  if !File.exist?("#{@@outdir}") then
    Dir.mkdir("#{@@outdir}")
  end

  # Run pdfxx, compile TeX into PDF
  Jekyll.logger.debug("Run LaTeX compiler (#{@pdf})")
  text = %x|#{@@pdf} -output-directory=#{texbase}/ #{texbase}.tex 2>&1|
  if $?.exitstatus != 0 then
    raise "[#{texbase}] Error #{$?.exitstatus} while executing backend:\n#{text}"
  end

  # Use pdfcrop to crop the PDF
  Jekyll.logger.debug("Crop PDF")
  text = %x|pdfcrop #{texbase}/output.pdf #{texbase}/output-crop.pdf 2>&1|
  if $?.exitstatus != 0 then
    raise "[#{texbase}] Error #{$?.exitstatus} while croping PDF:\n#{text}"
  end

  # Use pdf2svg to transform the cropped PDF into an SVG
  Jekyll.logger.debug("Convert PDF to SVG")
  text = %x|pdf2svg #{texbase}/output-crop.pdf #{svgfile} 2>&1|
  if $?.exitstatus != 0 then
    raise "[#{texbase}] Error #{$?.exitstatus} while generating SVG:\n#{text}"
  end

  # Optional: optimzie SVG using SVGO
  if Util.get_option(Util::OPTIMIZE_KEY, Util::DEFAULT_OPTIMIZE) == "true" then
    Jekyll.logger.debug("Optimize SVG file")
    text = %x|svgo -i #{svgfile}|
    if $?.exitstatus != 0 then
      raise "[#{svgfile}] Error #{$?.exitstatus} while optimizeing SVG:\n#{text}"
    end
  end

end