1+ -- VERSION 2021-01-19
2+
3+
14-- DESCRIPTION
25--
36-- This Lua filter for Pandoc converts LaTeX math to MathJax generated
@@ -75,6 +78,17 @@ local extensions = ''
7578-- /usr/local/lib/node_modules/mathjax-node-cli/node_modules/mathjax/unpacked/\
7679-- extensions/
7780
81+ -- Speed up conversion by caching SVG.
82+ local cache = true
83+
84+ local _cache = {}
85+ _cache .DisplayMath = {}
86+ _cache .InlineMath = {}
87+
88+ local tags = {}
89+ tags .DisplayMath = {' <span class="math display">' , ' </span>' }
90+ tags .InlineMath = {' <span class="math inline">' , ' </span>' }
91+
7892
7993function Meta (meta )
8094
@@ -87,14 +101,15 @@ function Meta(meta)
87101 ex = tostring (meta .math2svg_ex or ex )
88102 width = tostring (meta .math2svg_width or width )
89103 extensions = tostring (meta .math2svg_extensions or extensions )
104+ cache = tostring (meta .math2svg_cache or cache )
90105
91106end
92107
93108
94109function Math (elem )
95110
96111 local svg = nil
97- local tags = nil
112+
98113 local argumentlist = {
99114 ' --speech' , speech ,
100115 ' --linebreaks' , linebreaks ,
@@ -117,26 +132,45 @@ function Math(elem)
117132 -- extensions extra MathJax extensions [default: ""]
118133-- e.g. 'Safe,TeX/noUndefined'
119134
120- if elem .mathtype == ' DisplayMath' and display2svg then
121- svg = pandoc .pipe (tex2svg , argumentlist , ' ' )
122- tags = {' <span class="math display">' , ' </span>' }
135+ if (elem .mathtype == ' DisplayMath' and display2svg )
136+ or (elem .mathtype == ' InlineMath' and inline2svg ) then
137+
138+ if cache then
139+ -- Attempt to retrieve cache.
140+ svg = _cache [elem .mathtype ][elem .text ]
141+ end
142+
143+ if not svg then
144+
145+ if elem .mathtype == ' InlineMath' then
146+ -- Add the --inline argument to the argument list.
147+ table.insert (argumentlist , 1 , ' --inline' )
148+ end
149+
150+ -- Generate SVG.
151+ svg = pandoc .pipe (tex2svg , argumentlist , ' ' )
152+
153+ if cache then
154+ -- Add to cache.
155+ _cache [elem .mathtype ][elem .text ] = svg
156+ end
123157
124- elseif elem .mathtype == ' InlineMath' and inline2svg then
125- table.insert (argumentlist , 1 , ' --inline' )
126- svg = pandoc .pipe (tex2svg , argumentlist , ' ' )
127- tags = {' <span class="math inline">' , ' </span>' }
158+ end
128159
129160 end
130161
162+ -- Return
131163 if svg then
132164
133165 if FORMAT :match ' ^html.?' then
134- svg = tags [1 ] .. svg .. tags [2 ]
166+ svg = tags [elem . mathtype ][ 1 ] .. svg .. tags [ elem . mathtype ] [2 ]
135167 return pandoc .RawInline (FORMAT , svg )
168+
136169 else
137170 local filename = pandoc .sha1 (svg ) .. ' .svg'
138171 pandoc .mediabag .insert (filename , ' image/svg+xml' , svg )
139172 return pandoc .Image (' ' , filename )
173+
140174 end
141175
142176 else
@@ -145,7 +179,7 @@ function Math(elem)
145179
146180 end
147181
148- end
182+ end -- function
149183
150184
151185-- Redefining the execution order.
0 commit comments