Module: Katex

Defined in:
lib/katex.rb,
lib/katex/engine.rb,
lib/katex/version.rb

Overview

Provides a Ruby wrapper for KaTeX server-side rendering.

Defined Under Namespace

Classes: Engine

Constant Summary collapse

VERSION =
'0.10.0'
KATEX_VERSION =
'v0.16.7'

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.execjs_runtimeObject

The ExecJS runtime factory, default: ‘-> { ExecJS.runtime }`. Set this before calling any other methods to use a different runtime.

This proc is guaranteed to be called at most once.



52
53
54
# File 'lib/katex.rb', line 52

def execjs_runtime
  @execjs_runtime
end

Class Method Details

.gem_pathObject



65
66
67
68
# File 'lib/katex.rb', line 65

def gem_path
  @gem_path ||=
    File.expand_path(File.join(File.dirname(__FILE__), '..'))
end

.katex_contextObject



54
55
56
57
58
# File 'lib/katex.rb', line 54

def katex_context
  @load_context_mutex.synchronize do
    @context ||= @execjs_runtime.call.compile File.read katex_js_path
  end
end

.katex_js_pathObject



60
61
62
63
# File 'lib/katex.rb', line 60

def katex_js_path
  File.expand_path File.join('vendor', 'katex', 'javascripts', 'katex.js'),
                   gem_path
end

.render(math, display_mode: false, throw_on_error: true, error_color: '#cc0000', macros: {}, **render_options) ⇒ String

Note:

This method is thread-safe as long as your ExecJS runtime is thread-safe. MiniRacer is the recommended runtime.

Renders the given math expression to HTML via katex.renderToString.

Parameters:

  • math (String)

    The math (Latex) expression

  • display_mode (Boolean) (defaults to: false)

    Whether to render in display mode.

  • throw_on_error (Boolean) (defaults to: true)

    Whether to raise on error. If false, renders the error message instead (even in case of ParseError, unlike the native katex).

  • error_color (String) (defaults to: '#cc0000')

    Error text CSS color.

  • render_options (Hash)

    Additional options for katex.renderToString. See github.com/Khan/KaTeX#rendering-options.

Returns:

  • (String)

    HTML. If strings respond to html_safe, the result will be HTML-safe.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/katex.rb', line 30

def render(math, display_mode: false, throw_on_error: true,
           error_color: '#cc0000', macros: {}, **render_options)
  maybe_html_safe katex_context.call(
    'katex.renderToString',
    math,
    displayMode: display_mode,
    throwOnError: throw_on_error,
    errorColor: error_color,
    macros: macros,
    **render_options
  )
rescue ExecJS::ProgramError => e
  raise e if throw_on_error

  render_exception e, error_color
end