Top Level Namespace

Defined Under Namespace

Modules: Jektex, JekyllCustomPermalink

Constant Summary collapse

PATH_TO_JS =
"./katex.min.js"
CACHE_DIR =
"./.jektex-cache/"
CACHE_FILE =
"jektex-cache.marshal"
PATH_TO_CACHE =
CACHE_DIR + CACHE_FILE
KATEX =
ExecJS.compile(open(PATH_TO_JS).read)
PARSE_ERROR_PLACEHOLDER =
"<b style='color: red;'>PARSE ERROR</b>"

Instance Method Summary collapse

Instance Method Details

#convert(doc) ⇒ Object

[View source]

16
17
18
19
20
21
22
# File 'lib/jektex/jektex.rb', line 16

def convert(doc)
  # convert HTML enetities back to characters
  post = HTMLEntities.new.decode(doc.to_s)
  post = post.gsub(/(\\\()((.|\n)*?)(?<!\\)\\\)/) { |m| escape_method($1, $2, doc.path) }
  post = post.gsub(/(\\\[)((.|\n)*?)(?<!\\)\\\]/) { |m| escape_method($1, $2, doc.path) }
  return post
end

#escape_method(type, string, doc_path) ⇒ Object

[View source]

24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/jektex/jektex.rb', line 24

def escape_method( type, string, doc_path )
  @display = false

  # detect if expression is display view
  case type.downcase
    when /\(/
      @display = false
    else /\[/
      @display = true
  end

  # generate a hash from the math expression
  @expression_hash = Digest::SHA2.hexdigest(string) + @display.to_s

  # use it if it exists
  if($cache.has_key?(@expression_hash))
    $count_newly_generated_expressions += 1
    print_stats
    return $cache[@expression_hash]

  # else generate one and store it
  else
    # create the cache directory, if it doesn't exist
    begin
      # render using ExecJS
      @result =  KATEX.call("katex.renderToString", string, 
                          {displayMode: @display,  macros: $global_macros})
    rescue SystemExit, Interrupt
      # save cache to disk
      File.open(PATH_TO_CACHE, "w"){|to_file| Marshal.dump($cache, to_file)}
      # this stops jekyll being immune to interupts and kill command
      raise
    rescue Exception => e
      # catch parse error
      puts "\e[31m " + e.message.gsub("ParseError: ", "") + "\n\t"  + doc_path + "\e[0m"
      return PARSE_ERROR_PLACEHOLDER
    end
    # save to cache
    $cache[@expression_hash] = @result
    # update count of newly generated expressions
    $count_newly_generated_expressions += 1
    print_stats
    return @result
  end
end
[View source]

70
71
72
73
74
75
76
# File 'lib/jektex/jektex.rb', line 70

def print_stats
  print "             LaTeX: " + 
        ($count_newly_generated_expressions).to_s + 
        " expressions rendered (" + $cache.size.to_s + 
        " already cached)        \r"
  $stdout.flush
end