| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
de |
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
from __future__ import annotations |
| 25 |
|
| 26 |
__docformat__ = 'reStructuredText' |
| 27 |
|
| 28 |
import pathlib |
| 29 |
import sys |
| 30 |
import unicodedata |
| 31 |
|
| 32 |
from docutils.utils.math import tex2unichar |
| 33 |
|
| 34 |
__version__ = '1.3 (2021-06-02)' |
| 35 |
|
| 36 |
|
| 37 |
class Trace: |
| 38 |
"A tracing class" |
| 39 |
|
| 40 |
debugmode = False |
| 41 |
quietmode = False |
| 42 |
showlinesmode = False |
| 43 |
|
| 44 |
prefix = None |
| 45 |
|
| 46 |
def debug(cls, message) -> None: |
| 47 |
"Show a debug message" |
| 48 |
if not Trace.debugmode or Trace.quietmode: |
| 49 |
return |
| 50 |
Trace.show(message, sys.stdout) |
| 51 |
|
| 52 |
def message(cls, message) -> None: |
| 53 |
"Show a trace message" |
| 54 |
if Trace.quietmode: |
| 55 |
return |
| 56 |
if Trace.prefix and Trace.showlinesmode: |
| 57 |
message = Trace.prefix + message |
| 58 |
Trace.show(message, sys.stdout) |
| 59 |
|
| 60 |
def error(cls, message) -> None: |
| 61 |
"Show an error message" |
| 62 |
message = '* ' + message |
| 63 |
if Trace.prefix and Trace.showlinesmode: |
| 64 |
message = Trace.prefix + message |
| 65 |
Trace.show(message, sys.stderr) |
| 66 |
|
| 67 |
def show(cls, message, channel) -> None: |
| 68 |
"Show a message out of a channel" |
| 69 |
channel.write(message + '\n') |
| 70 |
|
| 71 |
debug = classmethod(debug) |
| 72 |
message = classmethod(message) |
| 73 |
error = classmethod(error) |
| 74 |
show = classmethod(show) |
| 75 |
|
| 76 |
|
| 77 |
class ContainerConfig: |
| 78 |
"Configuration class from elyxer.config file" |
| 79 |
|
| 80 |
extracttext = { |
| 81 |
'allowed': ['FormulaConstant'], |
| 82 |
'extracted': ['AlphaCommand', |
| 83 |
'Bracket', |
| 84 |
'BracketCommand', |
| 85 |
'CombiningFunction', |
| 86 |
'EmptyCommand', |
| 87 |
'FontFunction', |
| 88 |
'Formula', |
| 89 |
'FormulaNumber', |
| 90 |
'FormulaSymbol', |
| 91 |
'OneParamFunction', |
| 92 |
'OversetFunction', |
| 93 |
'RawText', |
| 94 |
'SpacedCommand', |
| 95 |
'SymbolFunction', |
| 96 |
'TextFunction', |
| 97 |
'UndersetFunction', |
| 98 |
], |
| 99 |
} |
| 100 |
|
| 101 |
|
| 102 |
class EscapeConfig: |
| 103 |
"Configuration class from elyxer.config file" |
| 104 |
|
| 105 |
chars = { |
| 106 |
'\n': '', |
| 107 |
"'": '’', |
| 108 |
'`': '‘', |
| 109 |
} |
| 110 |
|
| 111 |
entities = { |
| 112 |
'&': '&', |
| 113 |
'<': '<', |
| 114 |
'>': '>', |
| 115 |
} |
| 116 |
|
| 117 |
|
| 118 |
class FormulaConfig: |
| 119 |
"Configuration class from elyxer.config file" |
| 120 |
|
| 121 |
alphacommands = { |
| 122 |
'\\AmS': '<span class="textsc">AmS</span>', |
| 123 |
'\\AA': 'Å', |
| 124 |
'\\AE': 'Æ', |
| 125 |
'\\DH': 'Ð', |
| 126 |
'\\L': 'Ł', |
| 127 |
'\\O': 'Ø', |
| 128 |
'\\OE': 'Œ', |
| 129 |
'\\TH': 'Þ', |
| 130 |
'\\aa': 'å', |
| 131 |
'\\ae': 'æ', |
| 132 |
'\\dh': 'ð', |
| 133 |
'\\i': 'ı', |
| 134 |
'\\j': 'ȷ', |
| 135 |
'\\l': 'ł', |
| 136 |
'\\o': 'ø', |
| 137 |
'\\oe': 'œ', |
| 138 |
'\\ss': 'ß', |
| 139 |
'\\th': 'þ', |
| 140 |
'\\hbar': 'ħ', har |
| 141 |
} |
| 142 |
for key, value in tex2unichar.mathalpha.items(): |
| 143 |
alphacommands['\\'+key] = value |
| 144 |
|
| 145 |
array = { |
| 146 |
'begin': r'\begin', |
| 147 |
'cellseparator': '&', |
| 148 |
'end': r'\end', |
| 149 |
'rowseparator': r'\\', |
| 150 |
} |
| 151 |
|
| 152 |
bigbrackets = {'(': ['⎛', '⎜', '⎝'], |
| 153 |
')': ['⎞', '⎟', '⎠'], |
| 154 |
'[': ['⎡', '⎢', '⎣'], |
| 155 |
']': ['⎤', '⎥', '⎦'], |
| 156 |
'{': ['⎧', '⎪', '⎨', '⎩'], |
| 157 |
'}': ['⎫', '⎪', '⎬', '⎭'], |
| 158 |
che) |
| 159 |
'|': ['|'], |
| 160 |
ON |
| 161 |
ON |
| 162 |
'‖': ['‖'LINE |
| 163 |
L TO |
| 164 |
} |
| 165 |
|
| 166 |
bracketcommands = { |
| 167 |
'\\left': 'span class="stretchy"', |
| 168 |
'\\left.': '<span class="leftdot"></span>', |
| 169 |
'\\middle': 'span class="stretchy"', |
| 170 |
'\\right': 'span class="stretchy"', |
| 171 |
'\\right.': '<span class="rightdot"></span>', |
| 172 |
} |
| 173 |
|
| 174 |
combiningfunctions = { |
| 175 |
"\\'": '\u0301', ́ |
| 176 |
'\\"': '\u0308', ̈ |
| 177 |
'\\^': '\u0302', ̂ |
| 178 |
'\\`': '\u0300', ̀ |
| 179 |
'\\~': '\u0303', ̃ |
| 180 |
'\\c': '\u0327', ̧ |
| 181 |
'\\r': '\u030a', ̊ |
| 182 |
'\\s': '\u0329', ̩ |
| 183 |
'\\textcircled': '\u20dd', ⃝ |
| 184 |
'\\textsubring': '\u0325', ̥ |
| 185 |
'\\v': '\u030c', ̌ |
| 186 |
} |
| 187 |
for key, value in tex2unichar.mathaccent.items(): |
| 188 |
combiningfunctions['\\'+key] = value |
| 189 |
|
| 190 |
commands = { |
| 191 |
'\\\\': '<br/>', |
| 192 |
'\\\n': ' ', |
| 193 |
'\\\t': ' ', |
| 194 |
'\\centerdot': '\u2B1D', |
| 195 |
'\\colon': ': ', |
| 196 |
'\\copyright': '©', |
| 197 |
'\\dotminus': '∸', |
| 198 |
'\\dots': '…', |
| 199 |
'\\dotsb': '⋯', |
| 200 |
'\\dotsc': '…', |
| 201 |
'\\dotsi': '⋯', |
| 202 |
'\\dotsm': '⋯', |
| 203 |
'\\dotso': '…', |
| 204 |
'\\euro': '€', |
| 205 |
'\\guillemotleft': '«', |
| 206 |
'\\guillemotright': '»', |
| 207 |
'\\lVert': '‖', |
| 208 |
'\\Arrowvert': '‖', |
| 209 |
'\\lvert': '|', |
| 210 |
'\\newline': '<br/>', |
| 211 |
'\\nobreakspace': ' ', |
| 212 |
'\\nolimits': '', |
| 213 |
'\\nonumber': '', |
| 214 |
'\\qquad': ' ', |
| 215 |
'\\rVert': '‖', |
| 216 |
'\\rvert': '|', |
| 217 |
'\\textasciicircum': '^', |
| 218 |
'\\textasciitilde': '~', |
| 219 |
'\\textbackslash': '\\', |
| 220 |
'\\textcopyright': '©', |
| 221 |
'\\textdegree': '°', |
| 222 |
'\\textellipsis': '…', |
| 223 |
'\\textemdash': '—', |
| 224 |
'\\textendash': '—', |
| 225 |
'\\texteuro': '€', |
| 226 |
'\\textgreater': '>', |
| 227 |
'\\textless': '<', |
| 228 |
'\\textordfeminine': 'ª', |
| 229 |
'\\textordmasculine': 'º', |
| 230 |
'\\textquotedblleft': '“', |
| 231 |
'\\textquotedblright': '”', |
| 232 |
'\\textquoteright': '’', |
| 233 |
'\\textregistered': '®', |
| 234 |
'\\textrightarrow': '→', |
| 235 |
'\\textsection': '§', |
| 236 |
'\\texttrademark': '™', |
| 237 |
'\\texttwosuperior': '²', |
| 238 |
'\\textvisiblespace': ' ', |
| 239 |
'\\thickspace': '<span class="thickspace"> </span>', |
| 240 |
'\\;': '<span class="thickspace"> </span>', |
| 241 |
'\\triangle': '\u25B3', |
| 242 |
'\\triangledown': '\u25BD', |
| 243 |
'\\varnothing': '\u2300', GN |
| 244 |
|
| 245 |
'\\Pr': 'Pr', |
| 246 |
'\\arccos': 'arccos', |
| 247 |
'\\arcsin': 'arcsin', |
| 248 |
'\\arctan': 'arctan', |
| 249 |
'\\arg': 'arg', |
| 250 |
'\\cos': 'cos', |
| 251 |
'\\cosh': 'cosh', |
| 252 |
'\\cot': 'cot', |
| 253 |
'\\coth': 'coth', |
| 254 |
'\\csc': 'csc', |
| 255 |
'\\deg': 'deg', |
| 256 |
'\\det': 'det', |
| 257 |
'\\dim': 'dim', |
| 258 |
'\\exp': 'exp', |
| 259 |
'\\gcd': 'gcd', |
| 260 |
'\\hom': 'hom', |
| 261 |
'\\injlim': 'inj lim', |
| 262 |
'\\ker': 'ker', |
| 263 |
'\\lg': 'lg', |
| 264 |
'\\liminf': 'lim inf', |
| 265 |
'\\limsup': 'lim sup', |
| 266 |
'\\ln': 'ln', |
| 267 |
'\\log': 'log', |
| 268 |
'\\projlim': 'proj lim', |
| 269 |
'\\sec': 'sec', |
| 270 |
'\\sin': 'sin', |
| 271 |
'\\sinh': 'sinh', |
| 272 |
'\\tan': 'tan', |
| 273 |
'\\tanh': 'tanh', |
| 274 |
} |
| 275 |
cmddict = {} |
| 276 |
cmddict.update(tex2unichar.mathbin) |
| 277 |
cmddict.update(tex2unichar.mathopen) |
| 278 |
cmddict.update(tex2unichar.mathclose) |
| 279 |
cmddict.update(tex2unichar.mathfence) |
| 280 |
cmddict.update(tex2unichar.mathord) |
| 281 |
cmddict.update(tex2unichar.mathpunct) |
| 282 |
cmddict.update(tex2unichar.space) |
| 283 |
commands.update(('\\' + key, value) for key, value in cmddict.items()) |
| 284 |
|
| 285 |
oversetfunctions = { |
| 286 |
|
| 287 |
, |
| 288 |
'\\bar': '‒',SH |
| 289 |
, |
| 290 |
, |
| 291 |
'\\dddot': '<span class="smallsymbol">⋯</span>', |
| 292 |
igh |
| 293 |
, |
| 294 |
|
| 295 |
|
| 296 |
, |
| 297 |
|
| 298 |
'\\vec': '<span class="smallsymbol">→</span>', |
| 299 |
|
| 300 |
'\\overleftarrow': '⟵', |
| 301 |
'\\overleftrightarrow': '⟷', |
| 302 |
'\\overrightarrow': '⟶', |
| 303 |
'\\widehat': '^', |
| 304 |
'\\widetilde': '~', |
| 305 |
} |
| 306 |
|
| 307 |
undersetfunctions = { |
| 308 |
'\\underleftarrow': '⟵', |
| 309 |
'\\underleftrightarrow': '⟷', |
| 310 |
'\\underrightarrow': '⟶', |
| 311 |
} |
| 312 |
|
| 313 |
endings = { |
| 314 |
'bracket': '}', |
| 315 |
'complex': '\\]', |
| 316 |
'endafter': '}', |
| 317 |
'endbefore': '\\end{', |
| 318 |
'squarebracket': ']', |
| 319 |
} |
| 320 |
|
| 321 |
environments = { |
| 322 |
'align': ['r', 'l'], |
| 323 |
'eqnarray': ['r', 'c', 'l'], |
| 324 |
'gathered': ['l', 'l'], |
| 325 |
'smallmatrix': ['c', 'c'], |
| 326 |
} |
| 327 |
|
| 328 |
fontfunctions = { |
| 329 |
'\\boldsymbol': 'b', '\\mathbb': 'span class="blackboard"', |
| 330 |
'\\mathbb{A}': '𝔸', '\\mathbb{B}': '𝔹', '\\mathbb{C}': 'ℂ', |
| 331 |
'\\mathbb{D}': '𝔻', '\\mathbb{E}': '𝔼', '\\mathbb{F}': '𝔽', |
| 332 |
'\\mathbb{G}': '𝔾', '\\mathbb{H}': 'ℍ', '\\mathbb{J}': '𝕁', |
| 333 |
'\\mathbb{K}': '𝕂', '\\mathbb{L}': '𝕃', '\\mathbb{N}': 'ℕ', |
| 334 |
'\\mathbb{O}': '𝕆', '\\mathbb{P}': 'ℙ', '\\mathbb{Q}': 'ℚ', |
| 335 |
'\\mathbb{R}': 'ℝ', '\\mathbb{S}': '𝕊', '\\mathbb{T}': '𝕋', |
| 336 |
'\\mathbb{W}': '𝕎', '\\mathbb{Z}': 'ℤ', '\\mathbf': 'b', |
| 337 |
'\\mathcal': 'span class="scriptfont"', |
| 338 |
'\\mathcal{B}': 'ℬ', '\\mathcal{E}': 'ℰ', '\\mathcal{F}': |
| 339 |
'ℱ', '\\mathcal{H}': 'ℋ', '\\mathcal{I}': 'ℐ', |
| 340 |
'\\mathcal{L}': 'ℒ', '\\mathcal{M}': 'ℳ', '\\mathcal{R}': 'ℛ', |
| 341 |
'\\mathfrak': 'span class="fraktur"', |
| 342 |
'\\mathfrak{C}': 'ℭ', '\\mathfrak{F}': '𝔉', '\\mathfrak{H}': 'ℌ', |
| 343 |
'\\mathfrak{I}': 'ℑ', '\\mathfrak{R}': 'ℜ', '\\mathfrak{Z}': 'ℨ', |
| 344 |
'\\mathit': 'i', |
| 345 |
'\\mathring{A}': 'Å', '\\mathring{U}': 'Ů', |
| 346 |
'\\mathring{a}': 'å', '\\mathring{u}': 'ů', '\\mathring{w}': 'ẘ', |
| 347 |
'\\mathring{y}': 'ẙ', |
| 348 |
'\\mathrm': 'span class="mathrm"', |
| 349 |
'\\mathscr': 'span class="mathscr"', |
| 350 |
'\\mathscr{B}': 'ℬ', '\\mathscr{E}': 'ℰ', '\\mathscr{F}': 'ℱ', |
| 351 |
'\\mathscr{H}': 'ℋ', '\\mathscr{I}': 'ℐ', '\\mathscr{L}': 'ℒ', |
| 352 |
'\\mathscr{M}': 'ℳ', '\\mathscr{R}': 'ℛ', |
| 353 |
'\\mathsf': 'span class="mathsf"', |
| 354 |
'\\mathtt': 'span class="mathtt"', |
| 355 |
'\\operatorname': 'span class="mathrm"', |
| 356 |
} |
| 357 |
|
| 358 |
hybridfunctions = { |
| 359 |
'\\addcontentsline': ['{$p!}{$q!}{$r!}', 'f0{}', 'ignored'], |
| 360 |
'\\addtocontents': ['{$p!}{$q!}', 'f0{}', 'ignored'], |
| 361 |
'\\backmatter': ['', 'f0{}', 'ignored'], |
| 362 |
'\\binom': ['{$1}{$2}', 'f2{(}f0{f1{$1}f1{$2}}f2{)}', 'span class="binom"', 'span class="binomstack"', 'span class="bigdelimiter size2"'], |
| 363 |
'\\boxed': ['{$1}', 'f0{$1}', 'span class="boxed"'], |
| 364 |
'\\cfrac': ['[$p!]{$1}{$2}', 'f0{f3{(}f1{$1}f3{)/(}f2{$2}f3{)}}', 'span class="fullfraction"', 'span class="numerator align-$p"', 'span class="denominator"', 'span class="ignored"'], |
| 365 |
'\\color': ['{$p!}{$1}', 'f0{$1}', 'span style="color: $p;"'], |
| 366 |
'\\colorbox': ['{$p!}{$1}', 'f0{$1}', 'span class="colorbox" style="background: $p;"'], |
| 367 |
'\\dbinom': ['{$1}{$2}', '(f0{f1{f2{$1}}f1{f2{ }}f1{f2{$2}}})', 'span class="binomial"', 'span class="binomrow"', 'span class="binomcell"'], |
| 368 |
'\\dfrac': ['{$1}{$2}', 'f0{f3{(}f1{$1}f3{)/(}f2{$2}f3{)}}', 'span class="fullfraction"', 'span class="numerator"', 'span class="denominator"', 'span class="ignored"'], |
| 369 |
'\\displaystyle': ['{$1}', 'f0{$1}', 'span class="displaystyle"'], |
| 370 |
'\\fancyfoot': ['[$p!]{$q!}', 'f0{}', 'ignored'], |
| 371 |
'\\fancyhead': ['[$p!]{$q!}', 'f0{}', 'ignored'], |
| 372 |
'\\fbox': ['{$1}', 'f0{$1}', 'span class="fbox"'], |
| 373 |
'\\fboxrule': ['{$p!}', 'f0{}', 'ignored'], |
| 374 |
'\\fboxsep': ['{$p!}', 'f0{}', 'ignored'], |
| 375 |
'\\fcolorbox': ['{$p!}{$q!}{$1}', 'f0{$1}', 'span class="boxed" style="border-color: $p; background: $q;"'], |
| 376 |
'\\frac': ['{$1}{$2}', 'f0{f3{(}f1{$1}f3{)/(}f2{$2}f3{)}}', 'span class="fraction"', 'span class="numerator"', 'span class="denominator"', 'span class="ignored"'], |
| 377 |
'\\framebox': ['[$p!][$q!]{$1}', 'f0{$1}', 'span class="framebox align-$q" style="width: $p;"'], |
| 378 |
'\\frontmatter': ['', 'f0{}', 'ignored'], |
| 379 |
'\\href': ['[$o]{$u!}{$t!}', 'f0{$t}', 'a href="$u"'], |
| 380 |
'\\hspace': ['{$p!}', 'f0{ }', 'span class="hspace" style="width: $p;"'], |
| 381 |
'\\leftroot': ['{$p!}', 'f0{ }', 'span class="leftroot" style="width: $p;px"'], |
| 382 |
|
| 383 |
|
| 384 |
'\\nicefrac': ['{$1}{$2}', 'f0{f1{$1}⁄f2{$2}}', 'span class="fraction"', 'sup class="numerator"', 'sub class="denominator"', 'span class="ignored"'], |
| 385 |
'\\parbox': ['[$p!]{$w!}{$1}', 'f0{1}', 'div class="Boxed" style="width: $w;"'], |
| 386 |
'\\raisebox': ['{$p!}{$1}', 'f0{$1.font}', 'span class="raisebox" style="vertical-align: $p;"'], |
| 387 |
'\\renewenvironment': ['{$1!}{$2!}{$3!}', ''], |
| 388 |
'\\rule': ['[$v!]{$w!}{$h!}', 'f0/', 'hr class="line" style="width: $w; height: $h;"'], |
| 389 |
'\\scriptscriptstyle': ['{$1}', 'f0{$1}', 'span class="scriptscriptstyle"'], |
| 390 |
'\\scriptstyle': ['{$1}', 'f0{$1}', 'span class="scriptstyle"'], |
| 391 |
.) |
| 392 |
'\\sqrt': ['[$0]{$1}', 'f0{f1{$0}f2{√}f4{(}f3{$1}f4{)}}', 'span class="sqrt"', 'sup class="root"', 'span class="radical"', 'span class="root"', 'span class="ignored"'], |
| 393 |
'\\stackrel': ['{$1}{$2}', 'f0{f1{$1}f2{$2}}', 'span class="stackrel"', 'span class="upstackrel"', 'span class="downstackrel"'], |
| 394 |
'\\tbinom': ['{$1}{$2}', '(f0{f1{f2{$1}}f1{f2{ }}f1{f2{$2}}})', 'span class="binomial"', 'span class="binomrow"', 'span class="binomcell"'], |
| 395 |
'\\tfrac': ['{$1}{$2}', 'f0{f3{(}f1{$1}f3{)/(}f2{$2}f3{)}}', 'span class="textfraction"', 'span class="numerator"', 'span class="denominator"', 'span class="ignored"'], |
| 396 |
'\\textcolor': ['{$p!}{$1}', 'f0{$1}', 'span style="color: $p;"'], |
| 397 |
'\\textstyle': ['{$1}', 'f0{$1}', 'span class="textstyle"'], |
| 398 |
'\\thispagestyle': ['{$p!}', 'f0{}', 'ignored'], |
| 399 |
'\\unit': ['[$0]{$1}', '$0f0{$1.font}', 'span class="unit"'], |
| 400 |
'\\unitfrac': ['[$0]{$1}{$2}', '$0f0{f1{$1.font}⁄f2{$2.font}}', 'span class="fraction"', 'sup class="unit"', 'sub class="unit"'], |
| 401 |
'\\uproot': ['{$p!}', 'f0{ }', 'span class="uproot" style="width: $p;px"'], |
| 402 |
'\\url': ['{$u!}', 'f0{$u}', 'a href="$u"'], |
| 403 |
'\\vspace': ['{$p!}', 'f0{ }', 'span class="vspace" style="height: $p;"'], |
| 404 |
} |
| 405 |
|
| 406 |
hybridsizes = { |
| 407 |
'\\binom': '$1+$2', '\\cfrac': '$1+$2', '\\dbinom': '$1+$2+1', |
| 408 |
'\\dfrac': '$1+$2', '\\frac': '$1+$2', '\\tbinom': '$1+$2+1', |
| 409 |
} |
| 410 |
|
| 411 |
labelfunctions = { |
| 412 |
'\\label': 'a name="#"', |
| 413 |
} |
| 414 |
|
| 415 |
limitcommands = { |
| 416 |
'\\biginterleave': '⫼', |
| 417 |
'\\inf': 'inf', |
| 418 |
'\\lim': 'lim', |
| 419 |
'\\max': 'max', |
| 420 |
'\\min': 'min', |
| 421 |
'\\sup': 'sup', |
| 422 |
'\\ointop': '<span class="bigoperator integral">∮</span>', |
| 423 |
'\\bigcap': '<span class="bigoperator">⋂</span>', |
| 424 |
'\\bigcup': '<span class="bigoperator">⋃</span>', |
| 425 |
'\\bigodot': '<span class="bigoperator">⨀</span>', |
| 426 |
'\\bigoplus': '<span class="bigoperator">⨁</span>', |
| 427 |
'\\bigotimes': '<span class="bigoperator">⨂</span>', |
| 428 |
'\\bigsqcap': '<span class="bigoperator">⨅</span>', |
| 429 |
'\\bigsqcup': '<span class="bigoperator">⨆</span>', |
| 430 |
'\\biguplus': '<span class="bigoperator">⨄</span>', |
| 431 |
'\\bigvee': '<span class="bigoperator">⋁</span>', |
| 432 |
'\\bigwedge': '<span class="bigoperator">⋀</span>', |
| 433 |
'\\coprod': '<span class="bigoperator">∐</span>', |
| 434 |
'\\intop': '<span class="bigoperator integral">∫</span>', |
| 435 |
'\\prod': '<span class="bigoperator">∏</span>', |
| 436 |
'\\sum': '<span class="bigoperator">∑</span>', |
| 437 |
'\\varprod': '<span class="bigoperator">⨉</span>', |
| 438 |
'\\zcmp': '⨟', '\\zhide': '⧹', '\\zpipe': '⨠', '\\zproject': '⨡', |
| 439 |
|
| 440 |
|
| 441 |
'\\int': '<span class="bigoperator integral">∫</span>', |
| 442 |
'\\iint': '<span class="bigoperator integral">∬</span>', |
| 443 |
'\\iiint': '<span class="bigoperator integral">∭</span>', |
| 444 |
'\\iiiint': '<span class="bigoperator integral">⨌</span>', |
| 445 |
'\\fint': '<span class="bigoperator integral">⨏</span>', |
| 446 |
'\\idotsint': '<span class="bigoperator integral">∫⋯∫</span>', |
| 447 |
'\\oint': '<span class="bigoperator integral">∮</span>', |
| 448 |
'\\oiint': '<span class="bigoperator integral">∯</span>', |
| 449 |
'\\oiiint': '<span class="bigoperator integral">∰</span>', |
| 450 |
'\\ointclockwise': '<span class="bigoperator integral">∲</span>', |
| 451 |
'\\ointctrclockwise': '<span class="bigoperator integral">∳</span>', |
| 452 |
'\\smallint': '<span class="smallsymbol integral">∫</span>', |
| 453 |
'\\sqint': '<span class="bigoperator integral">⨖</span>', |
| 454 |
'\\varointclockwise': '<span class="bigoperator integral">∲</span>', |
| 455 |
} |
| 456 |
|
| 457 |
modified = { |
| 458 |
'\n': '', ' ': '', '$': '', '&': ' ', '\'': '’', '+': '\u2009+\u2009', |
| 459 |
',': ',\u2009', '-': '\u2009−\u2009', '/': '\u2009⁄\u2009', ':': ' : ', '<': '\u2009<\u2009', |
| 460 |
'=': '\u2009=\u2009', '>': '\u2009>\u2009', '@': '', '~': '\u00a0', |
| 461 |
} |
| 462 |
|
| 463 |
onefunctions = { |
| 464 |
'\\big': 'span class="bigdelimiter size1"', |
| 465 |
'\\bigl': 'span class="bigdelimiter size1"', |
| 466 |
'\\bigr': 'span class="bigdelimiter size1"', |
| 467 |
'\\Big': 'span class="bigdelimiter size2"', |
| 468 |
'\\Bigl': 'span class="bigdelimiter size2"', |
| 469 |
'\\Bigr': 'span class="bigdelimiter size2"', |
| 470 |
'\\bigg': 'span class="bigdelimiter size3"', |
| 471 |
'\\biggl': 'span class="bigdelimiter size3"', |
| 472 |
'\\biggr': 'span class="bigdelimiter size3"', |
| 473 |
'\\Bigg': 'span class="bigdelimiter size4"', |
| 474 |
'\\Biggl': 'span class="bigdelimiter size4"', |
| 475 |
'\\Biggr': 'span class="bigdelimiter size4"', |
| 476 |
|
| 477 |
'\\begin{array}': 'span class="arraydef"', |
| 478 |
'\\centering': 'span class="align-center"', |
| 479 |
'\\ensuremath': 'span class="ensuremath"', |
| 480 |
'\\hphantom': 'span class="phantom"', |
| 481 |
'\\noindent': 'span class="noindent"', |
| 482 |
'\\overbrace': 'span class="overbrace"', |
| 483 |
'\\overline': 'span class="overline"', |
| 484 |
'\\phantom': 'span class="phantom"', |
| 485 |
'\\underbrace': 'span class="underbrace"', |
| 486 |
'\\underline': '', |
| 487 |
'\\vphantom': 'span class="phantom"', |
| 488 |
} |
| 489 |
|
| 490 |
|
| 491 |
spacedcommands = { |
| 492 |
|
| 493 |
'\\nleqq': '\u2266\u0338', ≦̸ |
| 494 |
'\\ngeqq': '\u2267\u0338', ≧̸ |
| 495 |
'\\nleqslant': '\u2a7d\u0338', ⩽̸ |
| 496 |
'\\ngeqslant': '\u2a7e\u0338', ⩾̸ |
| 497 |
'\\nsubseteqq': '\u2AC5\u0338', ⫅̸ |
| 498 |
'\\nsupseteqq': '\u2AC6\u0338', ⫆̸ |
| 499 |
'\\nsqsubset': '\u2276\u228F', ⊏̸ |
| 500 |
|
| 501 |
'\\shortmid': '<span class="smallsymbol">∣</span>', |
| 502 |
'\\shortparallel': '<span class="smallsymbol">∥</span>', |
| 503 |
'\\nshortmid': '<span class="smallsymbol">∤</span>', |
| 504 |
'\\nshortparallel': '<span class="smallsymbol">∦</span>', |
| 505 |
'\\smallfrown': '<span class="smallsymbol">⌢</span>', |
| 506 |
'\\smallsmile': '<span class="smallsymbol">⌣</span>', |
| 507 |
'\\thickapprox': '<span class="boldsymbol">≈</span>', |
| 508 |
'\\thicksim': '<span class="boldsymbol">∼</span>', |
| 509 |
'\\varpropto': '<span class="mathsf">\u221d</span>', TO |
| 510 |
} |
| 511 |
for key, value in tex2unichar.mathrel.items(): |
| 512 |
spacedcommands['\\'+key] = value |
| 513 |
starts = { |
| 514 |
'beginafter': '}', 'beginbefore': '\\begin{', 'bracket': '{', |
| 515 |
'command': '\\', 'comment': '%', 'complex': '\\[', 'simple': '$', |
| 516 |
'squarebracket': '[', 'unnumbered': '*', |
| 517 |
} |
| 518 |
|
| 519 |
symbolfunctions = { |
| 520 |
'^': 'sup', '_': 'sub', |
| 521 |
} |
| 522 |
|
| 523 |
textfunctions = { |
| 524 |
'\\mbox': 'span class="mbox"', |
| 525 |
'\\text': 'span class="text"', |
| 526 |
'\\textbf': 'span class="textbf"', |
| 527 |
'\\textit': 'span class="textit"', |
| 528 |
'\\textnormal': 'span class="textnormal"', |
| 529 |
'\\textrm': 'span class="textrm"', |
| 530 |
'\\textsc': 'span class="textsc"', |
| 531 |
'\\textsf': 'span class="textsf"', |
| 532 |
'\\textsl': 'span class="textsl"', |
| 533 |
'\\texttt': 'span class="texttt"', |
| 534 |
'\\textup': 'span class="normal"', |
| 535 |
} |
| 536 |
|
| 537 |
unmodified = { |
| 538 |
'characters': ['.', '*', '€', '(', ')', '[', ']', |
| 539 |
'·', '!', ';', '|', '§', '"', '?'], |
| 540 |
} |
| 541 |
|
| 542 |
|
| 543 |
class CommandLineParser: |
| 544 |
"A parser for runtime options" |
| 545 |
|
| 546 |
def __init__(self, options) -> None: |
| 547 |
self.options = options |
| 548 |
|
| 549 |
def parseoptions(self, args): |
| 550 |
"Parse command line options" |
| 551 |
if len(args) == 0: |
| 552 |
return None |
| 553 |
while len(args) > 0 and args[0].startswith('--'): |
| 554 |
key, value = self.readoption(args) |
| 555 |
if not key: |
| 556 |
return 'Option ' + value + ' not recognized' |
| 557 |
if not value: |
| 558 |
return 'Option ' + key + ' needs a value' |
| 559 |
setattr(self.options, key, value) |
| 560 |
return None |
| 561 |
|
| 562 |
def readoption(self, args): |
| 563 |
"Read the key and value for an option" |
| 564 |
arg = args[0][2:] |
| 565 |
del args[0] |
| 566 |
if '=' in arg: |
| 567 |
key = self.readequalskey(arg, args) |
| 568 |
else: |
| 569 |
key = arg.replace('-', '') |
| 570 |
if not hasattr(self.options, key): |
| 571 |
return None, key |
| 572 |
current = getattr(self.options, key) |
| 573 |
if isinstance(current, bool): |
| 574 |
return key, True |
| 575 |
|
| 576 |
if len(args) == 0: |
| 577 |
return key, None |
| 578 |
if args[0].startswith('"'): |
| 579 |
initial = args[0] |
| 580 |
del args[0] |
| 581 |
return key, self.readquoted(args, initial) |
| 582 |
value = args[0].decode('utf-8') |
| 583 |
del args[0] |
| 584 |
if isinstance(current, list): |
| 585 |
current.append(value) |
| 586 |
return key, current |
| 587 |
return key, value |
| 588 |
|
| 589 |
def readquoted(self, args, initial): |
| 590 |
"Read a value between quotes" |
| 591 |
Trace.error('Oops') |
| 592 |
value = initial[1:] |
| 593 |
while len(args) > 0 and not args[0].endswith('"') and not args[0].startswith('--'): |
| 594 |
Trace.error('Appending ' + args[0]) |
| 595 |
value += ' ' + args[0] |
| 596 |
del args[0] |
| 597 |
if len(args) == 0 or args[0].startswith('--'): |
| 598 |
return None |
| 599 |
value += ' ' + args[0:-1] |
| 600 |
return value |
| 601 |
|
| 602 |
def readequalskey(self, arg, args): |
| 603 |
"Read a key using equals" |
| 604 |
split = arg.split('=', 1) |
| 605 |
key = split[0] |
| 606 |
value = split[1] |
| 607 |
args.insert(0, value) |
| 608 |
return key |
| 609 |
|
| 610 |
|
| 611 |
class Options: |
| 612 |
"A set of runtime options" |
| 613 |
|
| 614 |
location = None |
| 615 |
|
| 616 |
debug = False |
| 617 |
quiet = False |
| 618 |
version = False |
| 619 |
help = False |
| 620 |
simplemath = False |
| 621 |
showlines = True |
| 622 |
|
| 623 |
branches = {} |
| 624 |
|
| 625 |
def parseoptions(self, args) -> None: |
| 626 |
"Parse command line options" |
| 627 |
Options.location = args[0] |
| 628 |
del args[0] |
| 629 |
parser = CommandLineParser(Options) |
| 630 |
result = parser.parseoptions(args) |
| 631 |
if result: |
| 632 |
Trace.error(result) |
| 633 |
self.usage() |
| 634 |
self.processoptions() |
| 635 |
|
| 636 |
def processoptions(self) -> None: |
| 637 |
"Process all options parsed." |
| 638 |
if Options.help: |
| 639 |
self.usage() |
| 640 |
if Options.version: |
| 641 |
self.showversion() |
| 642 |
|
| 643 |
for param in dir(Trace): |
| 644 |
if param.endswith('mode'): |
| 645 |
setattr(Trace, param, getattr(self, param[:-4])) |
| 646 |
|
| 647 |
def usage(self) -> None: |
| 648 |
"Show correct usage" |
| 649 |
Trace.error(f'Usage: {pathlib.Path(Options.location).parent}' |
| 650 |
' [options] "input string"') |
| 651 |
Trace.error('Convert input string with LaTeX math to MathML') |
| 652 |
self.showoptions() |
| 653 |
|
| 654 |
def showoptions(self) -> None: |
| 655 |
"Show all possible options" |
| 656 |
Trace.error(' --help: show this online help') |
| 657 |
Trace.error(' --quiet: disables all runtime messages') |
| 658 |
Trace.error(' --debug: enable debugging messages (for developers)') |
| 659 |
Trace.error(' --version: show version number and release date') |
| 660 |
Trace.error(' --simplemath: do not generate fancy math constructions') |
| 661 |
sys.exit() |
| 662 |
|
| 663 |
def showversion(self) -> None: |
| 664 |
"Return the current eLyXer version string" |
| 665 |
Trace.error('math2html '+__version__) |
| 666 |
sys.exit() |
| 667 |
|
| 668 |
|
| 669 |
class Cloner: |
| 670 |
"An object used to clone other objects." |
| 671 |
|
| 672 |
def clone(cls, original): |
| 673 |
"Return an exact copy of an object." |
| 674 |
"The original object must have an empty constructor." |
| 675 |
return cls.create(original.__class__) |
| 676 |
|
| 677 |
def create(cls, type): |
| 678 |
"Create an object of a given class." |
| 679 |
clone = type.__new__(type) |
| 680 |
clone.__init__() |
| 681 |
return clone |
| 682 |
|
| 683 |
clone = classmethod(clone) |
| 684 |
create = classmethod(create) |
| 685 |
|
| 686 |
|
| 687 |
class ContainerExtractor: |
| 688 |
"""A class to extract certain containers. |
| 689 |
|
| 690 |
The config parameter is a map containing three lists: |
| 691 |
allowed, copied and extracted. |
| 692 |
Each of the three is a list of class names for containers. |
| 693 |
Allowed containers are included as is into the result. |
| 694 |
Cloned containers are cloned and placed into the result. |
| 695 |
Extracted containers are looked into. |
| 696 |
All other containers are silently ignored. |
| 697 |
""" |
| 698 |
|
| 699 |
def __init__(self, config) -> None: |
| 700 |
self.allowed = config['allowed'] |
| 701 |
self.extracted = config['extracted'] |
| 702 |
|
| 703 |
def extract(self, container): |
| 704 |
"Extract a group of selected containers from a container." |
| 705 |
lst = [] |
| 706 |
locate = lambda c: c.__class__.__name__ in self.allowed |
| 707 |
recursive = lambda c: c.__class__.__name__ in self.extracted |
| 708 |
process = lambda c: self.process(c, lst) |
| 709 |
container.recursivesearch(locate, recursive, process) |
| 710 |
return lst |
| 711 |
|
| 712 |
def process(self, container, lst) -> None: |
| 713 |
"Add allowed containers." |
| 714 |
name = container.__class__.__name__ |
| 715 |
if name in self.allowed: |
| 716 |
lst.append(container) |
| 717 |
else: |
| 718 |
Trace.error('Unknown container class ' + name) |
| 719 |
|
| 720 |
def safeclone(self, container): |
| 721 |
"Return a new container with contents only in a safe list, recursively." |
| 722 |
clone = Cloner.clone(container) |
| 723 |
clone.output = container.output |
| 724 |
clone.contents = self.extract(container) |
| 725 |
return clone |
| 726 |
|
| 727 |
|
| 728 |
class Parser: |
| 729 |
"A generic parser" |
| 730 |
|
| 731 |
def __init__(self) -> None: |
| 732 |
self.begin = 0 |
| 733 |
self.parameters = {} |
| 734 |
|
| 735 |
def parseheader(self, reader): |
| 736 |
"Parse the header" |
| 737 |
header = reader.currentline().split() |
| 738 |
reader.nextline() |
| 739 |
self.begin = reader.linenumber |
| 740 |
return header |
| 741 |
|
| 742 |
def parseparameter(self, reader) -> None: |
| 743 |
"Parse a parameter" |
| 744 |
split = reader.currentline().strip().split(' ', 1) |
| 745 |
reader.nextline() |
| 746 |
if len(split) == 0: |
| 747 |
return |
| 748 |
key = split[0] |
| 749 |
if len(split) == 1: |
| 750 |
self.parameters[key] = True |
| 751 |
return |
| 752 |
if '"' not in split[1]: |
| 753 |
self.parameters[key] = split[1].strip() |
| 754 |
return |
| 755 |
doublesplit = split[1].split('"') |
| 756 |
self.parameters[key] = doublesplit[1] |
| 757 |
|
| 758 |
def parseending(self, reader, process) -> None: |
| 759 |
"Parse until the current ending is found" |
| 760 |
if not self.ending: |
| 761 |
Trace.error('No ending for ' + str(self)) |
| 762 |
return |
| 763 |
while not reader.currentline().startswith(self.ending): |
| 764 |
process() |
| 765 |
|
| 766 |
def parsecontainer(self, reader, contents) -> None: |
| 767 |
container = self.factory.createcontainer(reader) |
| 768 |
if container: |
| 769 |
container.parent = self.parent |
| 770 |
contents.append(container) |
| 771 |
|
| 772 |
def __str__(self) -> str: |
| 773 |
"Return a description" |
| 774 |
return self.__class__.__name__ + ' (' + str(self.begin) + ')' |
| 775 |
|
| 776 |
|
| 777 |
class LoneCommand(Parser): |
| 778 |
"A parser for just one command line" |
| 779 |
|
| 780 |
def parse(self, reader): |
| 781 |
"Read nothing" |
| 782 |
return [] |
| 783 |
|
| 784 |
|
| 785 |
class TextParser(Parser): |
| 786 |
"A parser for a command and a bit of text" |
| 787 |
|
| 788 |
stack = [] |
| 789 |
|
| 790 |
def __init__(self, container) -> None: |
| 791 |
Parser.__init__(self) |
| 792 |
self.ending = None |
| 793 |
if container.__class__.__name__ in ContainerConfig.endings: |
| 794 |
self.ending = ContainerConfig.endings[container.__class__.__name__] |
| 795 |
self.endings = [] |
| 796 |
|
| 797 |
def parse(self, reader): |
| 798 |
"Parse lines as long as they are text" |
| 799 |
TextParser.stack.append(self.ending) |
| 800 |
self.endings = TextParser.stack + [ContainerConfig.endings['Layout'], |
| 801 |
ContainerConfig.endings['Inset'], |
| 802 |
self.ending] |
| 803 |
contents = [] |
| 804 |
while not self.isending(reader): |
| 805 |
self.parsecontainer(reader, contents) |
| 806 |
return contents |
| 807 |
|
| 808 |
def isending(self, reader) -> bool: |
| 809 |
"Check if text is ending" |
| 810 |
current = reader.currentline().split() |
| 811 |
if len(current) == 0: |
| 812 |
return False |
| 813 |
if current[0] in self.endings: |
| 814 |
if current[0] in TextParser.stack: |
| 815 |
TextParser.stack.remove(current[0]) |
| 816 |
else: |
| 817 |
TextParser.stack = [] |
| 818 |
return True |
| 819 |
return False |
| 820 |
|
| 821 |
|
| 822 |
class ExcludingParser(Parser): |
| 823 |
"A parser that excludes the final line" |
| 824 |
|
| 825 |
def parse(self, reader): |
| 826 |
"Parse everything up to (and excluding) the final line" |
| 827 |
contents = [] |
| 828 |
self.parseending(reader, lambda: self.parsecontainer(reader, contents)) |
| 829 |
return contents |
| 830 |
|
| 831 |
|
| 832 |
class BoundedParser(ExcludingParser): |
| 833 |
"A parser bound by a final line" |
| 834 |
|
| 835 |
def parse(self, reader): |
| 836 |
"Parse everything, including the final line" |
| 837 |
contents = ExcludingParser.parse(self, reader) |
| 838 |
|
| 839 |
reader.nextline() |
| 840 |
return contents |
| 841 |
|
| 842 |
|
| 843 |
class BoundedDummy(Parser): |
| 844 |
"A bound parser that ignores everything" |
| 845 |
|
| 846 |
def parse(self, reader): |
| 847 |
"Parse the contents of the container" |
| 848 |
self.parseending(reader, reader.nextline) |
| 849 |
|
| 850 |
reader.nextline() |
| 851 |
return [] |
| 852 |
|
| 853 |
|
| 854 |
class StringParser(Parser): |
| 855 |
"Parses just a string" |
| 856 |
|
| 857 |
def parseheader(self, reader): |
| 858 |
"Do nothing, just take note" |
| 859 |
self.begin = reader.linenumber + 1 |
| 860 |
return [] |
| 861 |
|
| 862 |
def parse(self, reader): |
| 863 |
"Parse a single line" |
| 864 |
contents = reader.currentline() |
| 865 |
reader.nextline() |
| 866 |
return contents |
| 867 |
|
| 868 |
|
| 869 |
class ContainerOutput: |
| 870 |
"The generic HTML output for a container." |
| 871 |
|
| 872 |
def gethtml(self, container) -> None: |
| 873 |
"Show an error." |
| 874 |
Trace.error('gethtml() not implemented for ' + str(self)) |
| 875 |
|
| 876 |
def isempty(self) -> bool: |
| 877 |
"Decide if the output is empty: by default, not empty." |
| 878 |
return False |
| 879 |
|
| 880 |
|
| 881 |
class EmptyOutput(ContainerOutput): |
| 882 |
|
| 883 |
def gethtml(self, container): |
| 884 |
"Return empty HTML code." |
| 885 |
return [] |
| 886 |
|
| 887 |
def isempty(self) -> bool: |
| 888 |
"This output is particularly empty." |
| 889 |
return True |
| 890 |
|
| 891 |
|
| 892 |
class FixedOutput(ContainerOutput): |
| 893 |
"Fixed output" |
| 894 |
|
| 895 |
def gethtml(self, container): |
| 896 |
"Return constant HTML code" |
| 897 |
return container.html |
| 898 |
|
| 899 |
|
| 900 |
class ContentsOutput(ContainerOutput): |
| 901 |
"Outputs the contents converted to HTML" |
| 902 |
|
| 903 |
def gethtml(self, container): |
| 904 |
"Return the HTML code" |
| 905 |
html = [] |
| 906 |
if container.contents is None: |
| 907 |
return html |
| 908 |
for element in container.contents: |
| 909 |
if not hasattr(element, 'gethtml'): |
| 910 |
Trace.error('No html in ' + element.__class__.__name__ + ': ' + str(element)) |
| 911 |
return html |
| 912 |
html += element.gethtml() |
| 913 |
return html |
| 914 |
|
| 915 |
|
| 916 |
class TaggedOutput(ContentsOutput): |
| 917 |
"Outputs an HTML tag surrounding the contents." |
| 918 |
|
| 919 |
tag = None |
| 920 |
breaklines = False |
| 921 |
empty = False |
| 922 |
|
| 923 |
def settag(self, tag, breaklines=False, empty=False): |
| 924 |
"Set the value for the tag and other attributes." |
| 925 |
self.tag = tag |
| 926 |
if breaklines: |
| 927 |
self.breaklines = breaklines |
| 928 |
if empty: |
| 929 |
self.empty = empty |
| 930 |
return self |
| 931 |
|
| 932 |
def setbreaklines(self, breaklines): |
| 933 |
"Set the value for breaklines." |
| 934 |
self.breaklines = breaklines |
| 935 |
return self |
| 936 |
|
| 937 |
def gethtml(self, container): |
| 938 |
"Return the HTML code." |
| 939 |
if self.empty: |
| 940 |
return [self.selfclosing(container)] |
| 941 |
html = [self.open(container)] |
| 942 |
html += ContentsOutput.gethtml(self, container) |
| 943 |
html.append(self.close(container)) |
| 944 |
return html |
| 945 |
|
| 946 |
def open(self, container): |
| 947 |
"Get opening line." |
| 948 |
if not self.checktag(container): |
| 949 |
return '' |
| 950 |
open_tag = '<' + self.tag + '>' |
| 951 |
if self.breaklines: |
| 952 |
return open_tag + '\n' |
| 953 |
return open_tag |
| 954 |
|
| 955 |
def close(self, container): |
| 956 |
"Get closing line." |
| 957 |
if not self.checktag(container): |
| 958 |
return '' |
| 959 |
close = '</' + self.tag.split()[0] + '>' |
| 960 |
if self.breaklines: |
| 961 |
return '\n' + close + '\n' |
| 962 |
return close |
| 963 |
|
| 964 |
def selfclosing(self, container): |
| 965 |
"Get self-closing line." |
| 966 |
if not self.checktag(container): |
| 967 |
return '' |
| 968 |
selfclosing = '<' + self.tag + '/>' |
| 969 |
if self.breaklines: |
| 970 |
return selfclosing + '\n' |
| 971 |
return selfclosing |
| 972 |
|
| 973 |
def checktag(self, container) -> bool: |
| 974 |
"Check that the tag is valid." |
| 975 |
if not self.tag: |
| 976 |
Trace.error('No tag in ' + str(container)) |
| 977 |
return False |
| 978 |
if self.tag == '': |
| 979 |
return False |
| 980 |
return True |
| 981 |
|
| 982 |
|
| 983 |
class FilteredOutput(ContentsOutput): |
| 984 |
"Returns the output in the contents, but filtered:" |
| 985 |
"some strings are replaced by others." |
| 986 |
|
| 987 |
def __init__(self) -> None: |
| 988 |
"Initialize the filters." |
| 989 |
self.filters = [] |
| 990 |
|
| 991 |
def addfilter(self, original, replacement) -> None: |
| 992 |
"Add a new filter: replace the original by the replacement." |
| 993 |
self.filters.append((original, replacement)) |
| 994 |
|
| 995 |
def gethtml(self, container): |
| 996 |
"Return the HTML code" |
| 997 |
html = ContentsOutput.gethtml(self, container) |
| 998 |
result = [self.filter(line) for line in html] |
| 999 |
return result |
| 1000 |
|
| 1001 |
def filter(self, line): |
| 1002 |
"Filter a single line with all available filters." |
| 1003 |
for original, replacement in self.filters: |
| 1004 |
if original in line: |
| 1005 |
line = line.replace(original, replacement) |
| 1006 |
return line |
| 1007 |
|
| 1008 |
|
| 1009 |
class StringOutput(ContainerOutput): |
| 1010 |
"Returns a bare string as output" |
| 1011 |
|
| 1012 |
def gethtml(self, container): |
| 1013 |
"Return a bare string" |
| 1014 |
return [container.string] |
| 1015 |
|
| 1016 |
|
| 1017 |
class Globable: |
| 1018 |
"""A bit of text which can be globbed (lumped together in bits). |
| 1019 |
Methods current(), skipcurrent(), checkfor() and isout() have to be |
| 1020 |
implemented by subclasses.""" |
| 1021 |
|
| 1022 |
leavepending = False |
| 1023 |
|
| 1024 |
def __init__(self) -> None: |
| 1025 |
self.endinglist = EndingList() |
| 1026 |
|
| 1027 |
def checkbytemark(self) -> None: |
| 1028 |
"Check for a Unicode byte mark and skip it." |
| 1029 |
if self.finished(): |
| 1030 |
return |
| 1031 |
if ord(self.current()) == 0xfeff: |
| 1032 |
self.skipcurrent() |
| 1033 |
|
| 1034 |
def isout(self) -> bool: |
| 1035 |
"Find out if we are out of the position yet." |
| 1036 |
Trace.error('Unimplemented isout()') |
| 1037 |
return True |
| 1038 |
|
| 1039 |
def current(self) -> str: |
| 1040 |
"Return the current character." |
| 1041 |
Trace.error('Unimplemented current()') |
| 1042 |
return '' |
| 1043 |
|
| 1044 |
def checkfor(self, string) -> bool: |
| 1045 |
"Check for the given string in the current position." |
| 1046 |
Trace.error('Unimplemented checkfor()') |
| 1047 |
return False |
| 1048 |
|
| 1049 |
def finished(self): |
| 1050 |
"Find out if the current text has finished." |
| 1051 |
if self.isout(): |
| 1052 |
if not self.leavepending: |
| 1053 |
self.endinglist.checkpending() |
| 1054 |
return True |
| 1055 |
return self.endinglist.checkin(self) |
| 1056 |
|
| 1057 |
def skipcurrent(self) -> str: |
| 1058 |
"Return the current character and skip it." |
| 1059 |
Trace.error('Unimplemented skipcurrent()') |
| 1060 |
return '' |
| 1061 |
|
| 1062 |
def glob(self, currentcheck): |
| 1063 |
"Glob a bit of text that satisfies a check on the current char." |
| 1064 |
glob = '' |
| 1065 |
while not self.finished() and currentcheck(): |
| 1066 |
glob += self.skipcurrent() |
| 1067 |
return glob |
| 1068 |
|
| 1069 |
def globalpha(self): |
| 1070 |
"Glob a bit of alpha text" |
| 1071 |
return self.glob(lambda: self.current().isalpha()) |
| 1072 |
|
| 1073 |
def globnumber(self): |
| 1074 |
"Glob a row of digits." |
| 1075 |
return self.glob(lambda: self.current().isdigit()) |
| 1076 |
|
| 1077 |
def isidentifier(self) -> bool: |
| 1078 |
"Return if the current character is alphanumeric or _." |
| 1079 |
if self.current().isalnum() or self.current() == '_': |
| 1080 |
return True |
| 1081 |
return False |
| 1082 |
|
| 1083 |
def globidentifier(self): |
| 1084 |
"Glob alphanumeric and _ symbols." |
| 1085 |
return self.glob(self.isidentifier) |
| 1086 |
|
| 1087 |
def isvalue(self) -> bool: |
| 1088 |
"Return if the current character is a value character:" |
| 1089 |
"not a bracket or a space." |
| 1090 |
if self.current().isspace(): |
| 1091 |
return False |
| 1092 |
if self.current() in '{}()': |
| 1093 |
return False |
| 1094 |
return True |
| 1095 |
|
| 1096 |
def globvalue(self): |
| 1097 |
"Glob a value: any symbols but brackets." |
| 1098 |
return self.glob(self.isvalue) |
| 1099 |
|
| 1100 |
def skipspace(self): |
| 1101 |
"Skip all whitespace at current position." |
| 1102 |
return self.glob(lambda: self.current().isspace()) |
| 1103 |
|
| 1104 |
def globincluding(self, magicchar): |
| 1105 |
"Glob a bit of text up to (including) the magic char." |
| 1106 |
glob = self.glob(lambda: self.current() != magicchar) + magicchar |
| 1107 |
self.skip(magicchar) |
| 1108 |
return glob |
| 1109 |
|
| 1110 |
def globexcluding(self, excluded): |
| 1111 |
"Glob a bit of text up until (excluding) any excluded character." |
| 1112 |
return self.glob(lambda: self.current() not in excluded) |
| 1113 |
|
| 1114 |
def pushending(self, ending, optional=False) -> None: |
| 1115 |
"Push a new ending to the bottom" |
| 1116 |
self.endinglist.add(ending, optional) |
| 1117 |
|
| 1118 |
def popending(self, expected=None): |
| 1119 |
"Pop the ending found at the current position" |
| 1120 |
if self.isout() and self.leavepending: |
| 1121 |
return expected |
| 1122 |
ending = self.endinglist.pop(self) |
| 1123 |
if expected and expected != ending: |
| 1124 |
Trace.error('Expected ending ' + expected + ', got ' + ending) |
| 1125 |
self.skip(ending) |
| 1126 |
return ending |
| 1127 |
|
| 1128 |
def nextending(self): |
| 1129 |
"Return the next ending in the queue." |
| 1130 |
nextending = self.endinglist.findending(self) |
| 1131 |
if not nextending: |
| 1132 |
return None |
| 1133 |
return nextending.ending |
| 1134 |
|
| 1135 |
|
| 1136 |
class EndingList: |
| 1137 |
"A list of position endings" |
| 1138 |
|
| 1139 |
def __init__(self) -> None: |
| 1140 |
self.endings = [] |
| 1141 |
|
| 1142 |
def add(self, ending, optional=False) -> None: |
| 1143 |
"Add a new ending to the list" |
| 1144 |
self.endings.append(PositionEnding(ending, optional)) |
| 1145 |
|
| 1146 |
def pickpending(self, pos) -> None: |
| 1147 |
"Pick any pending endings from a parse position." |
| 1148 |
self.endings += pos.endinglist.endings |
| 1149 |
|
| 1150 |
def checkin(self, pos) -> bool: |
| 1151 |
"Search for an ending" |
| 1152 |
if self.findending(pos): |
| 1153 |
return True |
| 1154 |
return False |
| 1155 |
|
| 1156 |
def pop(self, pos): |
| 1157 |
"Remove the ending at the current position" |
| 1158 |
if pos.isout(): |
| 1159 |
Trace.error('No ending out of bounds') |
| 1160 |
return '' |
| 1161 |
ending = self.findending(pos) |
| 1162 |
if not ending: |
| 1163 |
Trace.error('No ending at ' + pos.current()) |
| 1164 |
return '' |
| 1165 |
for each in reversed(self.endings): |
| 1166 |
self.endings.remove(each) |
| 1167 |
if each == ending: |
| 1168 |
return each.ending |
| 1169 |
elif not each.optional: |
| 1170 |
Trace.error('Removed non-optional ending ' + each) |
| 1171 |
Trace.error('No endings left') |
| 1172 |
return '' |
| 1173 |
|
| 1174 |
def findending(self, pos): |
| 1175 |
"Find the ending at the current position" |
| 1176 |
if len(self.endings) == 0: |
| 1177 |
return None |
| 1178 |
for index, ending in enumerate(reversed(self.endings)): |
| 1179 |
if ending.checkin(pos): |
| 1180 |
return ending |
| 1181 |
if not ending.optional: |
| 1182 |
return None |
| 1183 |
return None |
| 1184 |
|
| 1185 |
def checkpending(self) -> None: |
| 1186 |
"Check if there are any pending endings" |
| 1187 |
if len(self.endings) != 0: |
| 1188 |
Trace.error('Pending ' + str(self) + ' left open') |
| 1189 |
|
| 1190 |
def __str__(self) -> str: |
| 1191 |
"Printable representation" |
| 1192 |
string = 'endings [' |
| 1193 |
for ending in self.endings: |
| 1194 |
string += str(ending) + ',' |
| 1195 |
if len(self.endings) > 0: |
| 1196 |
string = string[:-1] |
| 1197 |
return string + ']' |
| 1198 |
|
| 1199 |
|
| 1200 |
class PositionEnding: |
| 1201 |
"An ending for a parsing position" |
| 1202 |
|
| 1203 |
def __init__(self, ending, optional) -> None: |
| 1204 |
self.ending = ending |
| 1205 |
self.optional = optional |
| 1206 |
|
| 1207 |
def checkin(self, pos): |
| 1208 |
"Check for the ending" |
| 1209 |
return pos.checkfor(self.ending) |
| 1210 |
|
| 1211 |
def __str__(self) -> str: |
| 1212 |
"Printable representation" |
| 1213 |
string = 'Ending ' + self.ending |
| 1214 |
if self.optional: |
| 1215 |
string += ' (optional)' |
| 1216 |
return string |
| 1217 |
|
| 1218 |
|
| 1219 |
class Position(Globable): |
| 1220 |
"""A position in a text to parse. |
| 1221 |
Including those in Globable, functions to implement by subclasses are: |
| 1222 |
skip(), identifier(), extract(), isout() and current().""" |
| 1223 |
|
| 1224 |
def __init__(self) -> None: |
| 1225 |
Globable.__init__(self) |
| 1226 |
|
| 1227 |
def skip(self, string) -> None: |
| 1228 |
"Skip a string" |
| 1229 |
Trace.error('Unimplemented skip()') |
| 1230 |
|
| 1231 |
def identifier(self) -> str: |
| 1232 |
"Return an identifier for the current position." |
| 1233 |
Trace.error('Unimplemented identifier()') |
| 1234 |
return 'Error' |
| 1235 |
|
| 1236 |
def extract(self, length): |
| 1237 |
"Extract the next string of the given length, or None if not enough text," |
| 1238 |
"without advancing the parse position." |
| 1239 |
Trace.error('Unimplemented extract()') |
| 1240 |
return None |
| 1241 |
|
| 1242 |
def checkfor(self, string): |
| 1243 |
"Check for a string at the given position." |
| 1244 |
return string == self.extract(len(string)) |
| 1245 |
|
| 1246 |
def checkforlower(self, string): |
| 1247 |
"Check for a string in lower case." |
| 1248 |
extracted = self.extract(len(string)) |
| 1249 |
if not extracted: |
| 1250 |
return False |
| 1251 |
return string.lower() == self.extract(len(string)).lower() |
| 1252 |
|
| 1253 |
def skipcurrent(self): |
| 1254 |
"Return the current character and skip it." |
| 1255 |
current = self.current() |
| 1256 |
self.skip(current) |
| 1257 |
return current |
| 1258 |
|
| 1259 |
def __next__(self): |
| 1260 |
"Advance the position and return the next character." |
| 1261 |
self.skipcurrent() |
| 1262 |
return self.current() |
| 1263 |
|
| 1264 |
def checkskip(self, string) -> bool: |
| 1265 |
"Check for a string at the given position; if there, skip it" |
| 1266 |
if not self.checkfor(string): |
| 1267 |
return False |
| 1268 |
self.skip(string) |
| 1269 |
return True |
| 1270 |
|
| 1271 |
def error(self, message) -> None: |
| 1272 |
"Show an error message and the position identifier." |
| 1273 |
Trace.error(message + ': ' + self.identifier()) |
| 1274 |
|
| 1275 |
|
| 1276 |
class TextPosition(Position): |
| 1277 |
"A parse position based on a raw text." |
| 1278 |
|
| 1279 |
def __init__(self, text) -> None: |
| 1280 |
"Create the position from some text." |
| 1281 |
Position.__init__(self) |
| 1282 |
self.pos = 0 |
| 1283 |
self.text = text |
| 1284 |
self.checkbytemark() |
| 1285 |
|
| 1286 |
def skip(self, string) -> None: |
| 1287 |
"Skip a string of characters." |
| 1288 |
self.pos += len(string) |
| 1289 |
|
| 1290 |
def identifier(self): |
| 1291 |
"Return a sample of the remaining text." |
| 1292 |
length = 30 |
| 1293 |
if self.pos + length > len(self.text): |
| 1294 |
length = len(self.text) - self.pos |
| 1295 |
return '*' + self.text[self.pos:self.pos + length] + '*' |
| 1296 |
|
| 1297 |
def isout(self): |
| 1298 |
"Find out if we are out of the text yet." |
| 1299 |
return self.pos >= len(self.text) |
| 1300 |
|
| 1301 |
def current(self): |
| 1302 |
"Return the current character, assuming we are not out." |
| 1303 |
return self.text[self.pos] |
| 1304 |
|
| 1305 |
def extract(self, length): |
| 1306 |
"Extract the next string of the given length, or None if not enough text." |
| 1307 |
if self.pos + length > len(self.text): |
| 1308 |
return None |
| 1309 |
return self.text[self.pos : self.pos + length] |
| 1310 |
|
| 1311 |
|
| 1312 |
class Container: |
| 1313 |
"A container for text and objects in a lyx file" |
| 1314 |
|
| 1315 |
partkey = None |
| 1316 |
parent = None |
| 1317 |
begin = None |
| 1318 |
|
| 1319 |
def __init__(self) -> None: |
| 1320 |
self.contents = [] |
| 1321 |
|
| 1322 |
def process(self) -> None: |
| 1323 |
"Process contents" |
| 1324 |
|
| 1325 |
def gethtml(self): |
| 1326 |
"Get the resulting HTML" |
| 1327 |
html = self.output.gethtml(self) |
| 1328 |
if isinstance(html, str): |
| 1329 |
Trace.error('Raw string ' + html) |
| 1330 |
html = [html] |
| 1331 |
return html |
| 1332 |
|
| 1333 |
def escape(self, line, replacements=EscapeConfig.entities): |
| 1334 |
"Escape a line with replacements from a map" |
| 1335 |
pieces = sorted(replacements.keys()) |
| 1336 |
|
| 1337 |
for piece in pieces: |
| 1338 |
if piece in line: |
| 1339 |
line = line.replace(piece, replacements[piece]) |
| 1340 |
return line |
| 1341 |
|
| 1342 |
def escapeentities(self, line): |
| 1343 |
"Escape all Unicode characters to HTML entities." |
| 1344 |
result = '' |
| 1345 |
pos = TextPosition(line) |
| 1346 |
while not pos.finished(): |
| 1347 |
if ord(pos.current()) > 128: |
| 1348 |
codepoint = hex(ord(pos.current())) |
| 1349 |
if codepoint == '0xd835': |
| 1350 |
codepoint = hex(ord(next(pos)) + 0xf800) |
| 1351 |
result += '&#' + codepoint[1:] + ';' |
| 1352 |
else: |
| 1353 |
result += pos.current() |
| 1354 |
pos.skipcurrent() |
| 1355 |
return result |
| 1356 |
|
| 1357 |
def searchall(self, type): |
| 1358 |
"Search for all embedded containers of a given type" |
| 1359 |
lst = [] |
| 1360 |
self.searchprocess(type, lst.append) |
| 1361 |
return lst |
| 1362 |
|
| 1363 |
def searchremove(self, type): |
| 1364 |
"Search for all containers of a type and remove them" |
| 1365 |
lst = self.searchall(type) |
| 1366 |
for container in lst: |
| 1367 |
container.parent.contents.remove(container) |
| 1368 |
return lst |
| 1369 |
|
| 1370 |
def searchprocess(self, type, process) -> None: |
| 1371 |
"Search for elements of a given type and process them" |
| 1372 |
self.locateprocess(lambda container: isinstance(container, type), process) |
| 1373 |
|
| 1374 |
def locateprocess(self, locate, process) -> None: |
| 1375 |
"Search for all embedded containers and process them" |
| 1376 |
for container in self.contents: |
| 1377 |
container.locateprocess(locate, process) |
| 1378 |
if locate(container): |
| 1379 |
process(container) |
| 1380 |
|
| 1381 |
def recursivesearch(self, locate, recursive, process) -> None: |
| 1382 |
"Perform a recursive search in the container." |
| 1383 |
for container in self.contents: |
| 1384 |
if recursive(container): |
| 1385 |
container.recursivesearch(locate, recursive, process) |
| 1386 |
if locate(container): |
| 1387 |
process(container) |
| 1388 |
|
| 1389 |
def extracttext(self): |
| 1390 |
"Extract all text from allowed containers." |
| 1391 |
constants = ContainerExtractor(ContainerConfig.extracttext).extract(self) |
| 1392 |
return ''.join(constant.string for constant in constants) |
| 1393 |
|
| 1394 |
def group(self, index, group, isingroup) -> None: |
| 1395 |
"Group some adjoining elements into a group" |
| 1396 |
if index >= len(self.contents): |
| 1397 |
return |
| 1398 |
if hasattr(self.contents[index], 'grouped'): |
| 1399 |
return |
| 1400 |
while index < len(self.contents) and isingroup(self.contents[index]): |
| 1401 |
self.contents[index].grouped = True |
| 1402 |
group.contents.append(self.contents[index]) |
| 1403 |
self.contents.pop(index) |
| 1404 |
self.contents.insert(index, group) |
| 1405 |
|
| 1406 |
def remove(self, index) -> None: |
| 1407 |
"Remove a container but leave its contents" |
| 1408 |
container = self.contents[index] |
| 1409 |
self.contents.pop(index) |
| 1410 |
while len(container.contents) > 0: |
| 1411 |
self.contents.insert(index, container.contents.pop()) |
| 1412 |
|
| 1413 |
def tree(self, level=0) -> None: |
| 1414 |
"Show in a tree" |
| 1415 |
Trace.debug(" " * level + str(self)) |
| 1416 |
for container in self.contents: |
| 1417 |
container.tree(level + 1) |
| 1418 |
|
| 1419 |
def getparameter(self, name): |
| 1420 |
"Get the value of a parameter, if present." |
| 1421 |
if name not in self.parameters: |
| 1422 |
return None |
| 1423 |
return self.parameters[name] |
| 1424 |
|
| 1425 |
def getparameterlist(self, name): |
| 1426 |
"Get the value of a comma-separated parameter as a list." |
| 1427 |
paramtext = self.getparameter(name) |
| 1428 |
if not paramtext: |
| 1429 |
return [] |
| 1430 |
return paramtext.split(',') |
| 1431 |
|
| 1432 |
def hasemptyoutput(self) -> bool: |
| 1433 |
"Check if the parent's output is empty." |
| 1434 |
current = self.parent |
| 1435 |
while current: |
| 1436 |
if current.output.isempty(): |
| 1437 |
return True |
| 1438 |
current = current.parent |
| 1439 |
return False |
| 1440 |
|
| 1441 |
def __str__(self) -> str: |
| 1442 |
"Get a description" |
| 1443 |
if not self.begin: |
| 1444 |
return self.__class__.__name__ |
| 1445 |
return self.__class__.__name__ + '@' + str(self.begin) |
| 1446 |
|
| 1447 |
|
| 1448 |
class BlackBox(Container): |
| 1449 |
"A container that does not output anything" |
| 1450 |
|
| 1451 |
def __init__(self) -> None: |
| 1452 |
self.parser = LoneCommand() |
| 1453 |
self.output = EmptyOutput() |
| 1454 |
self.contents = [] |
| 1455 |
|
| 1456 |
|
| 1457 |
class StringContainer(Container): |
| 1458 |
"A container for a single string" |
| 1459 |
|
| 1460 |
parsed = None |
| 1461 |
|
| 1462 |
def __init__(self) -> None: |
| 1463 |
self.parser = StringParser() |
| 1464 |
self.output = StringOutput() |
| 1465 |
self.string = '' |
| 1466 |
|
| 1467 |
def process(self) -> None: |
| 1468 |
"Replace special chars from the contents." |
| 1469 |
if self.parsed: |
| 1470 |
self.string = self.replacespecial(self.parsed) |
| 1471 |
self.parsed = None |
| 1472 |
|
| 1473 |
def replacespecial(self, line): |
| 1474 |
"Replace all special chars from a line" |
| 1475 |
replaced = self.escape(line, EscapeConfig.entities) |
| 1476 |
replaced = self.changeline(replaced) |
| 1477 |
if ContainerConfig.string['startcommand'] in replaced and len(replaced) > 1: |
| 1478 |
|
| 1479 |
if self.begin: |
| 1480 |
message = 'Unknown command at ' + str(self.begin) + ': ' |
| 1481 |
else: |
| 1482 |
message = 'Unknown command: ' |
| 1483 |
Trace.error(message + replaced.strip()) |
| 1484 |
return replaced |
| 1485 |
|
| 1486 |
def changeline(self, line): |
| 1487 |
return self.escape(line, EscapeConfig.chars) |
| 1488 |
|
| 1489 |
def extracttext(self): |
| 1490 |
"Return all text." |
| 1491 |
return self.string |
| 1492 |
|
| 1493 |
def __str__(self) -> str: |
| 1494 |
"Return a printable representation." |
| 1495 |
result = 'StringContainer' |
| 1496 |
if self.begin: |
| 1497 |
result += '@' + str(self.begin) |
| 1498 |
ellipsis = '...' |
| 1499 |
if len(self.string.strip()) <= 15: |
| 1500 |
ellipsis = '' |
| 1501 |
return result + ' (' + self.string.strip()[:15] + ellipsis + ')' |
| 1502 |
|
| 1503 |
|
| 1504 |
class Constant(StringContainer): |
| 1505 |
"A constant string" |
| 1506 |
|
| 1507 |
def __init__(self, text) -> None: |
| 1508 |
self.contents = [] |
| 1509 |
self.string = text |
| 1510 |
self.output = StringOutput() |
| 1511 |
|
| 1512 |
def __str__(self) -> str: |
| 1513 |
return 'Constant: ' + self.string |
| 1514 |
|
| 1515 |
|
| 1516 |
class DocumentParameters: |
| 1517 |
"Global parameters for the document." |
| 1518 |
|
| 1519 |
displaymode = False |
| 1520 |
|
| 1521 |
|
| 1522 |
class FormulaParser(Parser): |
| 1523 |
"Parses a formula" |
| 1524 |
|
| 1525 |
def parseheader(self, reader): |
| 1526 |
"See if the formula is inlined" |
| 1527 |
self.begin = reader.linenumber + 1 |
| 1528 |
type = self.parsetype(reader) |
| 1529 |
if not type: |
| 1530 |
reader.nextline() |
| 1531 |
type = self.parsetype(reader) |
| 1532 |
if not type: |
| 1533 |
Trace.error('Unknown formula type in ' + reader.currentline().strip()) |
| 1534 |
return ['unknown'] |
| 1535 |
return [type] |
| 1536 |
|
| 1537 |
def parsetype(self, reader): |
| 1538 |
"Get the formula type from the first line." |
| 1539 |
if reader.currentline().find(FormulaConfig.starts['simple']) >= 0: |
| 1540 |
return 'inline' |
| 1541 |
if reader.currentline().find(FormulaConfig.starts['complex']) >= 0: |
| 1542 |
return 'block' |
| 1543 |
if reader.currentline().find(FormulaConfig.starts['unnumbered']) >= 0: |
| 1544 |
return 'block' |
| 1545 |
if reader.currentline().find(FormulaConfig.starts['beginbefore']) >= 0: |
| 1546 |
return 'numbered' |
| 1547 |
return None |
| 1548 |
|
| 1549 |
def parse(self, reader): |
| 1550 |
"Parse the formula until the end" |
| 1551 |
formula = self.parseformula(reader) |
| 1552 |
while not reader.currentline().startswith(self.ending): |
| 1553 |
stripped = reader.currentline().strip() |
| 1554 |
if len(stripped) > 0: |
| 1555 |
Trace.error('Unparsed formula line ' + stripped) |
| 1556 |
reader.nextline() |
| 1557 |
reader.nextline() |
| 1558 |
return formula |
| 1559 |
|
| 1560 |
def parseformula(self, reader): |
| 1561 |
"Parse the formula contents" |
| 1562 |
simple = FormulaConfig.starts['simple'] |
| 1563 |
if simple in reader.currentline(): |
| 1564 |
rest = reader.currentline().split(simple, 1)[1] |
| 1565 |
if simple in rest: |
| 1566 |
|
| 1567 |
return self.parsesingleliner(reader, simple, simple) |
| 1568 |
|
| 1569 |
return self.parsemultiliner(reader, simple, simple) |
| 1570 |
if FormulaConfig.starts['complex'] in reader.currentline(): |
| 1571 |
|
| 1572 |
return self.parsemultiliner(reader, FormulaConfig.starts['complex'], |
| 1573 |
FormulaConfig.endings['complex']) |
| 1574 |
beginbefore = FormulaConfig.starts['beginbefore'] |
| 1575 |
beginafter = FormulaConfig.starts['beginafter'] |
| 1576 |
if beginbefore in reader.currentline(): |
| 1577 |
if reader.currentline().strip().endswith(beginafter): |
| 1578 |
current = reader.currentline().strip() |
| 1579 |
endsplit = current.split(beginbefore)[1].split(beginafter) |
| 1580 |
startpiece = beginbefore + endsplit[0] + beginafter |
| 1581 |
endbefore = FormulaConfig.endings['endbefore'] |
| 1582 |
endafter = FormulaConfig.endings['endafter'] |
| 1583 |
endpiece = endbefore + endsplit[0] + endafter |
| 1584 |
return startpiece + self.parsemultiliner(reader, startpiece, endpiece) + endpiece |
| 1585 |
Trace.error('Missing ' + beginafter + ' in ' + reader.currentline()) |
| 1586 |
return '' |
| 1587 |
begincommand = FormulaConfig.starts['command'] |
| 1588 |
beginbracket = FormulaConfig.starts['bracket'] |
| 1589 |
if begincommand in reader.currentline() and beginbracket in reader.currentline(): |
| 1590 |
endbracket = FormulaConfig.endings['bracket'] |
| 1591 |
return self.parsemultiliner(reader, beginbracket, endbracket) |
| 1592 |
Trace.error('Formula beginning ' + reader.currentline() + ' is unknown') |
| 1593 |
return '' |
| 1594 |
|
| 1595 |
def parsesingleliner(self, reader, start, ending): |
| 1596 |
"Parse a formula in one line" |
| 1597 |
line = reader.currentline().strip() |
| 1598 |
if start not in line: |
| 1599 |
Trace.error('Line ' + line + ' does not contain formula start ' + start) |
| 1600 |
return '' |
| 1601 |
if not line.endswith(ending): |
| 1602 |
Trace.error('Formula ' + line + ' does not end with ' + ending) |
| 1603 |
return '' |
| 1604 |
index = line.index(start) |
| 1605 |
rest = line[index + len(start):-len(ending)] |
| 1606 |
reader.nextline() |
| 1607 |
return rest |
| 1608 |
|
| 1609 |
def parsemultiliner(self, reader, start, ending): |
| 1610 |
"Parse a formula in multiple lines" |
| 1611 |
formula = '' |
| 1612 |
line = reader.currentline() |
| 1613 |
if start not in line: |
| 1614 |
Trace.error('Line ' + line.strip() + ' does not contain formula start ' + start) |
| 1615 |
return '' |
| 1616 |
index = line.index(start) |
| 1617 |
line = line[index + len(start):].strip() |
| 1618 |
while not line.endswith(ending): |
| 1619 |
formula += line + '\n' |
| 1620 |
reader.nextline() |
| 1621 |
line = reader.currentline() |
| 1622 |
formula += line[:-len(ending)] |
| 1623 |
reader.nextline() |
| 1624 |
return formula |
| 1625 |
|
| 1626 |
|
| 1627 |
class FormulaBit(Container): |
| 1628 |
"A bit of a formula" |
| 1629 |
|
| 1630 |
type = None |
| 1631 |
size = 1 |
| 1632 |
original = '' |
| 1633 |
|
| 1634 |
def __init__(self) -> None: |
| 1635 |
"The formula bit type can be 'alpha', 'number', 'font'." |
| 1636 |
self.contents = [] |
| 1637 |
self.output = ContentsOutput() |
| 1638 |
|
| 1639 |
def setfactory(self, factory): |
| 1640 |
"Set the internal formula factory." |
| 1641 |
self.factory = factory |
| 1642 |
return self |
| 1643 |
|
| 1644 |
def add(self, bit) -> None: |
| 1645 |
"Add any kind of formula bit already processed" |
| 1646 |
self.contents.append(bit) |
| 1647 |
self.original += bit.original |
| 1648 |
bit.parent = self |
| 1649 |
|
| 1650 |
def skiporiginal(self, string, pos) -> None: |
| 1651 |
"Skip a string and add it to the original formula" |
| 1652 |
self.original += string |
| 1653 |
if not pos.checkskip(string): |
| 1654 |
Trace.error('String ' + string + ' not at ' + pos.identifier()) |
| 1655 |
|
| 1656 |
def computesize(self): |
| 1657 |
"Compute the size of the bit as the max of the sizes of all contents." |
| 1658 |
if len(self.contents) == 0: |
| 1659 |
return 1 |
| 1660 |
self.size = max(element.size for element in self.contents) |
| 1661 |
return self.size |
| 1662 |
|
| 1663 |
def clone(self): |
| 1664 |
"Return a copy of itself." |
| 1665 |
return self.factory.parseformula(self.original) |
| 1666 |
|
| 1667 |
def __str__(self) -> str: |
| 1668 |
"Get a string representation" |
| 1669 |
return self.__class__.__name__ + ' read in ' + self.original |
| 1670 |
|
| 1671 |
|
| 1672 |
class TaggedBit(FormulaBit): |
| 1673 |
"A tagged string in a formula" |
| 1674 |
|
| 1675 |
def constant(self, constant, tag): |
| 1676 |
"Set the constant and the tag" |
| 1677 |
self.output = TaggedOutput().settag(tag) |
| 1678 |
self.add(FormulaConstant(constant)) |
| 1679 |
return self |
| 1680 |
|
| 1681 |
def complete(self, contents, tag, breaklines=False): |
| 1682 |
"Set the constant and the tag" |
| 1683 |
self.contents = contents |
| 1684 |
self.output = TaggedOutput().settag(tag, breaklines) |
| 1685 |
return self |
| 1686 |
|
| 1687 |
def selfcomplete(self, tag): |
| 1688 |
"Set the self-closing tag, no contents (as in <hr/>)." |
| 1689 |
self.output = TaggedOutput().settag(tag, empty=True) |
| 1690 |
return self |
| 1691 |
|
| 1692 |
|
| 1693 |
class FormulaConstant(Constant): |
| 1694 |
"A constant string in a formula" |
| 1695 |
|
| 1696 |
def __init__(self, string) -> None: |
| 1697 |
"Set the constant string" |
| 1698 |
Constant.__init__(self, string) |
| 1699 |
self.original = string |
| 1700 |
self.size = 1 |
| 1701 |
self.type = None |
| 1702 |
|
| 1703 |
def computesize(self): |
| 1704 |
"Compute the size of the constant: always 1." |
| 1705 |
return self.size |
| 1706 |
|
| 1707 |
def clone(self): |
| 1708 |
"Return a copy of itself." |
| 1709 |
return FormulaConstant(self.original) |
| 1710 |
|
| 1711 |
def __str__(self) -> str: |
| 1712 |
"Return a printable representation." |
| 1713 |
return 'Formula constant: ' + self.string |
| 1714 |
|
| 1715 |
|
| 1716 |
class RawText(FormulaBit): |
| 1717 |
"A bit of text inside a formula" |
| 1718 |
|
| 1719 |
def detect(self, pos): |
| 1720 |
"Detect a bit of raw text" |
| 1721 |
return pos.current().isalpha() |
| 1722 |
|
| 1723 |
def parsebit(self, pos) -> None: |
| 1724 |
"Parse alphabetic text" |
| 1725 |
alpha = pos.globalpha() |
| 1726 |
self.add(FormulaConstant(alpha)) |
| 1727 |
self.type = 'alpha' |
| 1728 |
|
| 1729 |
|
| 1730 |
class FormulaSymbol(FormulaBit): |
| 1731 |
"A symbol inside a formula" |
| 1732 |
|
| 1733 |
modified = FormulaConfig.modified |
| 1734 |
unmodified = FormulaConfig.unmodified['characters'] |
| 1735 |
|
| 1736 |
def detect(self, pos) -> bool: |
| 1737 |
"Detect a symbol" |
| 1738 |
if pos.current() in FormulaSymbol.unmodified: |
| 1739 |
return True |
| 1740 |
if pos.current() in FormulaSymbol.modified: |
| 1741 |
return True |
| 1742 |
return False |
| 1743 |
|
| 1744 |
def parsebit(self, pos) -> None: |
| 1745 |
"Parse the symbol" |
| 1746 |
if pos.current() in FormulaSymbol.unmodified: |
| 1747 |
self.addsymbol(pos.current(), pos) |
| 1748 |
return |
| 1749 |
if pos.current() in FormulaSymbol.modified: |
| 1750 |
self.addsymbol(FormulaSymbol.modified[pos.current()], pos) |
| 1751 |
return |
| 1752 |
Trace.error('Symbol ' + pos.current() + ' not found') |
| 1753 |
|
| 1754 |
def addsymbol(self, symbol, pos) -> None: |
| 1755 |
"Add a symbol" |
| 1756 |
self.skiporiginal(pos.current(), pos) |
| 1757 |
self.contents.append(FormulaConstant(symbol)) |
| 1758 |
|
| 1759 |
|
| 1760 |
class FormulaNumber(FormulaBit): |
| 1761 |
"A string of digits in a formula" |
| 1762 |
|
| 1763 |
def detect(self, pos): |
| 1764 |
"Detect a digit" |
| 1765 |
return pos.current().isdigit() |
| 1766 |
|
| 1767 |
def parsebit(self, pos) -> None: |
| 1768 |
"Parse a bunch of digits" |
| 1769 |
digits = pos.glob(lambda: pos.current().isdigit()) |
| 1770 |
self.add(FormulaConstant(digits)) |
| 1771 |
self.type = 'number' |
| 1772 |
|
| 1773 |
|
| 1774 |
class Comment(FormulaBit): |
| 1775 |
"A LaTeX comment: % to the end of the line." |
| 1776 |
|
| 1777 |
start = FormulaConfig.starts['comment'] |
| 1778 |
|
| 1779 |
def detect(self, pos): |
| 1780 |
"Detect the %." |
| 1781 |
return pos.current() == self.start |
| 1782 |
|
| 1783 |
def parsebit(self, pos) -> None: |
| 1784 |
"Parse to the end of the line." |
| 1785 |
self.original += pos.globincluding('\n') |
| 1786 |
|
| 1787 |
|
| 1788 |
class WhiteSpace(FormulaBit): |
| 1789 |
"Some white space inside a formula." |
| 1790 |
|
| 1791 |
def detect(self, pos): |
| 1792 |
"Detect the white space." |
| 1793 |
return pos.current().isspace() |
| 1794 |
|
| 1795 |
def parsebit(self, pos) -> None: |
| 1796 |
"Parse all whitespace." |
| 1797 |
self.original += pos.skipspace() |
| 1798 |
|
| 1799 |
def __str__(self) -> str: |
| 1800 |
"Return a printable representation." |
| 1801 |
return 'Whitespace: *' + self.original + '*' |
| 1802 |
|
| 1803 |
|
| 1804 |
class Bracket(FormulaBit): |
| 1805 |
"A {} bracket inside a formula" |
| 1806 |
|
| 1807 |
start = FormulaConfig.starts['bracket'] |
| 1808 |
ending = FormulaConfig.endings['bracket'] |
| 1809 |
|
| 1810 |
def __init__(self) -> None: |
| 1811 |
"Create a (possibly literal) new bracket" |
| 1812 |
FormulaBit.__init__(self) |
| 1813 |
self.inner = None |
| 1814 |
|
| 1815 |
def detect(self, pos): |
| 1816 |
"Detect the start of a bracket" |
| 1817 |
return pos.checkfor(self.start) |
| 1818 |
|
| 1819 |
def parsebit(self, pos): |
| 1820 |
"Parse the bracket" |
| 1821 |
self.parsecomplete(pos, self.innerformula) |
| 1822 |
return self |
| 1823 |
|
| 1824 |
def parsetext(self, pos): |
| 1825 |
"Parse a text bracket" |
| 1826 |
self.parsecomplete(pos, self.innertext) |
| 1827 |
return self |
| 1828 |
|
| 1829 |
def parseliteral(self, pos): |
| 1830 |
"Parse a literal bracket" |
| 1831 |
self.parsecomplete(pos, self.innerliteral) |
| 1832 |
return self |
| 1833 |
|
| 1834 |
def parsecomplete(self, pos, innerparser): |
| 1835 |
"Parse the start and end marks" |
| 1836 |
if not pos.checkfor(self.start): |
| 1837 |
Trace.error('Bracket should start with ' + self.start + ' at ' + pos.identifier()) |
| 1838 |
return None |
| 1839 |
self.skiporiginal(self.start, pos) |
| 1840 |
pos.pushending(self.ending) |
| 1841 |
innerparser(pos) |
| 1842 |
self.original += pos.popending(self.ending) |
| 1843 |
self.computesize() |
| 1844 |
|
| 1845 |
def innerformula(self, pos) -> None: |
| 1846 |
"Parse a whole formula inside the bracket" |
| 1847 |
while not pos.finished(): |
| 1848 |
self.add(self.factory.parseany(pos)) |
| 1849 |
|
| 1850 |
def innertext(self, pos) -> None: |
| 1851 |
"Parse some text inside the bracket, following textual rules." |
| 1852 |
specialchars = list(FormulaConfig.symbolfunctions.keys()) + [ |
| 1853 |
FormulaConfig.starts['command'], |
| 1854 |
FormulaConfig.starts['bracket'], |
| 1855 |
Comment.start, |
| 1856 |
] |
| 1857 |
while not pos.finished(): |
| 1858 |
if pos.current() in specialchars: |
| 1859 |
self.add(self.factory.parseany(pos)) |
| 1860 |
if pos.checkskip(' '): |
| 1861 |
self.original += ' ' |
| 1862 |
else: |
| 1863 |
self.add(FormulaConstant(pos.skipcurrent())) |
| 1864 |
|
| 1865 |
def innerliteral(self, pos) -> None: |
| 1866 |
"Parse a literal inside the bracket, which does not generate HTML." |
| 1867 |
self.literal = '' |
| 1868 |
while not pos.finished() and not pos.current() == self.ending: |
| 1869 |
if pos.current() == self.start: |
| 1870 |
self.parseliteral(pos) |
| 1871 |
else: |
| 1872 |
self.literal += pos.skipcurrent() |
| 1873 |
self.original += self.literal |
| 1874 |
|
| 1875 |
|
| 1876 |
class SquareBracket(Bracket): |
| 1877 |
"A [] bracket inside a formula" |
| 1878 |
|
| 1879 |
start = FormulaConfig.starts['squarebracket'] |
| 1880 |
ending = FormulaConfig.endings['squarebracket'] |
| 1881 |
|
| 1882 |
def clone(self): |
| 1883 |
"Return a new square bracket with the same contents." |
| 1884 |
bracket = SquareBracket() |
| 1885 |
bracket.contents = self.contents |
| 1886 |
return bracket |
| 1887 |
|
| 1888 |
|
| 1889 |
class MathsProcessor: |
| 1890 |
"A processor for a maths construction inside the FormulaProcessor." |
| 1891 |
|
| 1892 |
def process(self, contents, index) -> None: |
| 1893 |
"Process an element inside a formula." |
| 1894 |
Trace.error('Unimplemented process() in ' + str(self)) |
| 1895 |
|
| 1896 |
def __str__(self) -> str: |
| 1897 |
"Return a printable description." |
| 1898 |
return 'Maths processor ' + self.__class__.__name__ |
| 1899 |
|
| 1900 |
|
| 1901 |
class FormulaProcessor: |
| 1902 |
"A processor specifically for formulas." |
| 1903 |
|
| 1904 |
processors = [] |
| 1905 |
|
| 1906 |
def process(self, bit) -> None: |
| 1907 |
"Process the contents of every formula bit, recursively." |
| 1908 |
self.processcontents(bit) |
| 1909 |
self.processinsides(bit) |
| 1910 |
self.traversewhole(bit) |
| 1911 |
|
| 1912 |
def processcontents(self, bit) -> None: |
| 1913 |
"Process the contents of a formula bit." |
| 1914 |
if not isinstance(bit, FormulaBit): |
| 1915 |
return |
| 1916 |
bit.process() |
| 1917 |
for element in bit.contents: |
| 1918 |
self.processcontents(element) |
| 1919 |
|
| 1920 |
def processinsides(self, bit) -> None: |
| 1921 |
"Process the insides (limits, brackets) in a formula bit." |
| 1922 |
if not isinstance(bit, FormulaBit): |
| 1923 |
return |
| 1924 |
for index, element in enumerate(bit.contents): |
| 1925 |
for processor in self.processors: |
| 1926 |
processor.process(bit.contents, index) |
| 1927 |
|
| 1928 |
self.processinsides(element) |
| 1929 |
|
| 1930 |
def traversewhole(self, formula) -> None: |
| 1931 |
"Traverse over the contents to alter variables and space units." |
| 1932 |
last = None |
| 1933 |
for bit, contents in self.traverse(formula): |
| 1934 |
if bit.type == 'alpha': |
| 1935 |
self.italicize(bit, contents) |
| 1936 |
elif bit.type == 'font' and last and last.type == 'number': |
| 1937 |
bit.contents.insert(0, FormulaConstant('\u2009')) |
| 1938 |
last = bit |
| 1939 |
|
| 1940 |
def traverse(self, bit): |
| 1941 |
"Traverse a formula and yield a flattened structure of (bit, list) pairs." |
| 1942 |
for element in bit.contents: |
| 1943 |
if hasattr(element, 'type') and element.type: |
| 1944 |
yield element, bit.contents |
| 1945 |
elif isinstance(element, FormulaBit): |
| 1946 |
yield from self.traverse(element) |
| 1947 |
|
| 1948 |
def italicize(self, bit, contents) -> None: |
| 1949 |
"Italicize the given bit of text." |
| 1950 |
index = contents.index(bit) |
| 1951 |
contents[index] = TaggedBit().complete([bit], 'i') |
| 1952 |
|
| 1953 |
|
| 1954 |
class Formula(Container): |
| 1955 |
"A LaTeX formula" |
| 1956 |
|
| 1957 |
def __init__(self) -> None: |
| 1958 |
self.parser = FormulaParser() |
| 1959 |
self.output = TaggedOutput().settag('span class="formula"') |
| 1960 |
|
| 1961 |
def process(self) -> None: |
| 1962 |
"Convert the formula to tags" |
| 1963 |
if self.header[0] == 'inline': |
| 1964 |
DocumentParameters.displaymode = False |
| 1965 |
else: |
| 1966 |
DocumentParameters.displaymode = True |
| 1967 |
self.output.settag('div class="formula"', True) |
| 1968 |
self.classic() |
| 1969 |
|
| 1970 |
def classic(self) -> None: |
| 1971 |
"Make the contents using classic output generation with XHTML and CSS." |
| 1972 |
whole = FormulaFactory().parseformula(self.parsed) |
| 1973 |
FormulaProcessor().process(whole) |
| 1974 |
whole.parent = self |
| 1975 |
self.contents = [whole] |
| 1976 |
|
| 1977 |
def parse(self, pos): |
| 1978 |
"Parse using a parse position instead of self.parser." |
| 1979 |
if pos.checkskip('$$'): |
| 1980 |
self.parsedollarblock(pos) |
| 1981 |
elif pos.checkskip('$'): |
| 1982 |
self.parsedollarinline(pos) |
| 1983 |
elif pos.checkskip('\\('): |
| 1984 |
self.parseinlineto(pos, '\\)') |
| 1985 |
elif pos.checkskip('\\['): |
| 1986 |
self.parseblockto(pos, '\\]') |
| 1987 |
else: |
| 1988 |
pos.error('Unparseable formula') |
| 1989 |
self.process() |
| 1990 |
return self |
| 1991 |
|
| 1992 |
def parsedollarinline(self, pos) -> None: |
| 1993 |
"Parse a $...$ formula." |
| 1994 |
self.header = ['inline'] |
| 1995 |
self.parsedollar(pos) |
| 1996 |
|
| 1997 |
def parsedollarblock(self, pos) -> None: |
| 1998 |
"Parse a $$...$$ formula." |
| 1999 |
self.header = ['block'] |
| 2000 |
self.parsedollar(pos) |
| 2001 |
if not pos.checkskip('$'): |
| 2002 |
pos.error('Formula should be $$...$$, but last $ is missing.') |
| 2003 |
|
| 2004 |
def parsedollar(self, pos) -> None: |
| 2005 |
"Parse to the next $." |
| 2006 |
pos.pushending('$') |
| 2007 |
self.parsed = pos.globexcluding('$') |
| 2008 |
pos.popending('$') |
| 2009 |
|
| 2010 |
def parseinlineto(self, pos, limit) -> None: |
| 2011 |
"Parse a \\(...\\) formula." |
| 2012 |
self.header = ['inline'] |
| 2013 |
self.parseupto(pos, limit) |
| 2014 |
|
| 2015 |
def parseblockto(self, pos, limit) -> None: |
| 2016 |
"Parse a \\[...\\] formula." |
| 2017 |
self.header = ['block'] |
| 2018 |
self.parseupto(pos, limit) |
| 2019 |
|
| 2020 |
def parseupto(self, pos, limit) -> None: |
| 2021 |
"Parse a formula that ends with the given command." |
| 2022 |
pos.pushending(limit) |
| 2023 |
self.parsed = pos.glob(lambda: True) |
| 2024 |
pos.popending(limit) |
| 2025 |
|
| 2026 |
def __str__(self) -> str: |
| 2027 |
"Return a printable representation." |
| 2028 |
if self.partkey and self.partkey.number: |
| 2029 |
return 'Formula (' + self.partkey.number + ')' |
| 2030 |
return 'Unnumbered formula' |
| 2031 |
|
| 2032 |
|
| 2033 |
class WholeFormula(FormulaBit): |
| 2034 |
"Parse a whole formula" |
| 2035 |
|
| 2036 |
def detect(self, pos) -> bool: |
| 2037 |
"Not outside the formula is enough." |
| 2038 |
return not pos.finished() |
| 2039 |
|
| 2040 |
def parsebit(self, pos) -> None: |
| 2041 |
"Parse with any formula bit" |
| 2042 |
while not pos.finished(): |
| 2043 |
self.add(self.factory.parseany(pos)) |
| 2044 |
|
| 2045 |
|
| 2046 |
class FormulaFactory: |
| 2047 |
"Construct bits of formula" |
| 2048 |
|
| 2049 |
|
| 2050 |
types = [FormulaSymbol, RawText, FormulaNumber, Bracket, Comment, WhiteSpace] |
| 2051 |
skippedtypes = [Comment, WhiteSpace] |
| 2052 |
defining = False |
| 2053 |
|
| 2054 |
def __init__(self) -> None: |
| 2055 |
"Initialize the map of instances." |
| 2056 |
self.instances = {} |
| 2057 |
|
| 2058 |
def detecttype(self, type, pos): |
| 2059 |
"Detect a bit of a given type." |
| 2060 |
if pos.finished(): |
| 2061 |
return False |
| 2062 |
return self.instance(type).detect(pos) |
| 2063 |
|
| 2064 |
def instance(self, type): |
| 2065 |
"Get an instance of the given type." |
| 2066 |
if type not in self.instances or not self.instances[type]: |
| 2067 |
self.instances[type] = self.create(type) |
| 2068 |
return self.instances[type] |
| 2069 |
|
| 2070 |
def create(self, type): |
| 2071 |
"Create a new formula bit of the given type." |
| 2072 |
return Cloner.create(type).setfactory(self) |
| 2073 |
|
| 2074 |
def clearskipped(self, pos) -> None: |
| 2075 |
"Clear any skipped types." |
| 2076 |
while not pos.finished(): |
| 2077 |
if not self.skipany(pos): |
| 2078 |
return |
| 2079 |
return |
| 2080 |
|
| 2081 |
def skipany(self, pos): |
| 2082 |
"Skip any skipped types." |
| 2083 |
for type in self.skippedtypes: |
| 2084 |
if self.instance(type).detect(pos): |
| 2085 |
return self.parsetype(type, pos) |
| 2086 |
return None |
| 2087 |
|
| 2088 |
def parseany(self, pos): |
| 2089 |
"Parse any formula bit at the current location." |
| 2090 |
for type in self.types + self.skippedtypes: |
| 2091 |
if self.detecttype(type, pos): |
| 2092 |
return self.parsetype(type, pos) |
| 2093 |
Trace.error('Unrecognized formula at ' + pos.identifier()) |
| 2094 |
return FormulaConstant(pos.skipcurrent()) |
| 2095 |
|
| 2096 |
def parsetype(self, type, pos): |
| 2097 |
"Parse the given type and return it." |
| 2098 |
bit = self.instance(type) |
| 2099 |
self.instances[type] = None |
| 2100 |
returnedbit = bit.parsebit(pos) |
| 2101 |
if returnedbit: |
| 2102 |
return returnedbit.setfactory(self) |
| 2103 |
return bit |
| 2104 |
|
| 2105 |
def parseformula(self, formula): |
| 2106 |
"Parse a string of text that contains a whole formula." |
| 2107 |
pos = TextPosition(formula) |
| 2108 |
whole = self.create(WholeFormula) |
| 2109 |
if whole.detect(pos): |
| 2110 |
whole.parsebit(pos) |
| 2111 |
return whole |
| 2112 |
|
| 2113 |
if not pos.finished(): |
| 2114 |
Trace.error('Unknown formula at: ' + pos.identifier()) |
| 2115 |
whole.add(TaggedBit().constant(formula, 'span class="unknown"')) |
| 2116 |
return whole |
| 2117 |
|
| 2118 |
|
| 2119 |
class FormulaCommand(FormulaBit): |
| 2120 |
"A LaTeX command inside a formula" |
| 2121 |
|
| 2122 |
types = [] |
| 2123 |
start = FormulaConfig.starts['command'] |
| 2124 |
commandmap = None |
| 2125 |
|
| 2126 |
def detect(self, pos): |
| 2127 |
"Find the current command." |
| 2128 |
return pos.checkfor(FormulaCommand.start) |
| 2129 |
|
| 2130 |
def parsebit(self, pos): |
| 2131 |
"Parse the command." |
| 2132 |
command = self.extractcommand(pos) |
| 2133 |
bit = self.parsewithcommand(command, pos) |
| 2134 |
if bit: |
| 2135 |
return bit |
| 2136 |
if command.startswith(('\\up', '\\Up')): |
| 2137 |
upgreek = self.parseupgreek(command, pos) |
| 2138 |
if upgreek: |
| 2139 |
return upgreek |
| 2140 |
if not self.factory.defining: |
| 2141 |
Trace.error('Unknown command ' + command) |
| 2142 |
self.output = TaggedOutput().settag('span class="unknown"') |
| 2143 |
self.add(FormulaConstant(command)) |
| 2144 |
return None |
| 2145 |
|
| 2146 |
def parsewithcommand(self, command, pos): |
| 2147 |
"Parse the command type once we have the command." |
| 2148 |
for type in FormulaCommand.types: |
| 2149 |
if command in type.commandmap: |
| 2150 |
return self.parsecommandtype(command, type, pos) |
| 2151 |
return None |
| 2152 |
|
| 2153 |
def parsecommandtype(self, command, type, pos): |
| 2154 |
"Parse a given command type." |
| 2155 |
bit = self.factory.create(type) |
| 2156 |
bit.setcommand(command) |
| 2157 |
returned = bit.parsebit(pos) |
| 2158 |
if returned: |
| 2159 |
return returned |
| 2160 |
return bit |
| 2161 |
|
| 2162 |
def extractcommand(self, pos): |
| 2163 |
"Extract the command from the current position." |
| 2164 |
if not pos.checkskip(FormulaCommand.start): |
| 2165 |
pos.error('Missing command start ' + FormulaCommand.start) |
| 2166 |
return |
| 2167 |
if pos.finished(): |
| 2168 |
return self.emptycommand(pos) |
| 2169 |
if pos.current().isalpha(): |
| 2170 |
|
| 2171 |
command = FormulaCommand.start + pos.globalpha() |
| 2172 |
|
| 2173 |
pos.checkskip('*') |
| 2174 |
return command |
| 2175 |
|
| 2176 |
return FormulaCommand.start + pos.skipcurrent() |
| 2177 |
|
| 2178 |
def emptycommand(self, pos): |
| 2179 |
"""Check for an empty command: look for command disguised as ending. |
| 2180 |
Special case against '{ \\{ \\} }' situation.""" |
| 2181 |
command = '' |
| 2182 |
if not pos.isout(): |
| 2183 |
ending = pos.nextending() |
| 2184 |
if ending and pos.checkskip(ending): |
| 2185 |
command = ending |
| 2186 |
return FormulaCommand.start + command |
| 2187 |
|
| 2188 |
def parseupgreek(self, command, pos): |
| 2189 |
"Parse the Greek \\up command.." |
| 2190 |
if len(command) < 4: |
| 2191 |
return None |
| 2192 |
if command.startswith('\\up'): |
| 2193 |
upcommand = '\\' + command[3:] |
| 2194 |
elif pos.checkskip('\\Up'): |
| 2195 |
upcommand = '\\' + command[3:4].upper() + command[4:] |
| 2196 |
else: |
| 2197 |
Trace.error('Impossible upgreek command: ' + command) |
| 2198 |
return |
| 2199 |
upgreek = self.parsewithcommand(upcommand, pos) |
| 2200 |
if upgreek: |
| 2201 |
upgreek.type = 'font' |
| 2202 |
return upgreek |
| 2203 |
|
| 2204 |
|
| 2205 |
class CommandBit(FormulaCommand): |
| 2206 |
"A formula bit that includes a command" |
| 2207 |
|
| 2208 |
def setcommand(self, command) -> None: |
| 2209 |
"Set the command in the bit" |
| 2210 |
self.command = command |
| 2211 |
if self.commandmap: |
| 2212 |
self.original += command |
| 2213 |
self.translated = self.commandmap[self.command] |
| 2214 |
|
| 2215 |
def parseparameter(self, pos): |
| 2216 |
"Parse a parameter at the current position" |
| 2217 |
self.factory.clearskipped(pos) |
| 2218 |
if pos.finished(): |
| 2219 |
return None |
| 2220 |
parameter = self.factory.parseany(pos) |
| 2221 |
self.add(parameter) |
| 2222 |
return parameter |
| 2223 |
|
| 2224 |
def parsesquare(self, pos): |
| 2225 |
"Parse a square bracket" |
| 2226 |
self.factory.clearskipped(pos) |
| 2227 |
if not self.factory.detecttype(SquareBracket, pos): |
| 2228 |
return None |
| 2229 |
bracket = self.factory.parsetype(SquareBracket, pos) |
| 2230 |
self.add(bracket) |
| 2231 |
return bracket |
| 2232 |
|
| 2233 |
def parseliteral(self, pos): |
| 2234 |
"Parse a literal bracket." |
| 2235 |
self.factory.clearskipped(pos) |
| 2236 |
if not self.factory.detecttype(Bracket, pos): |
| 2237 |
if not pos.isvalue(): |
| 2238 |
Trace.error('No literal parameter found at: ' + pos.identifier()) |
| 2239 |
return None |
| 2240 |
return pos.globvalue() |
| 2241 |
bracket = Bracket().setfactory(self.factory) |
| 2242 |
self.add(bracket.parseliteral(pos)) |
| 2243 |
return bracket.literal |
| 2244 |
|
| 2245 |
def parsesquareliteral(self, pos): |
| 2246 |
"Parse a square bracket literally." |
| 2247 |
self.factory.clearskipped(pos) |
| 2248 |
if not self.factory.detecttype(SquareBracket, pos): |
| 2249 |
return None |
| 2250 |
bracket = SquareBracket().setfactory(self.factory) |
| 2251 |
self.add(bracket.parseliteral(pos)) |
| 2252 |
return bracket.literal |
| 2253 |
|
| 2254 |
def parsetext(self, pos): |
| 2255 |
"Parse a text parameter." |
| 2256 |
self.factory.clearskipped(pos) |
| 2257 |
if not self.factory.detecttype(Bracket, pos): |
| 2258 |
Trace.error('No text parameter for ' + self.command) |
| 2259 |
return None |
| 2260 |
bracket = Bracket().setfactory(self.factory).parsetext(pos) |
| 2261 |
self.add(bracket) |
| 2262 |
return bracket |
| 2263 |
|
| 2264 |
|
| 2265 |
class EmptyCommand(CommandBit): |
| 2266 |
"An empty command (without parameters)" |
| 2267 |
|
| 2268 |
commandmap = FormulaConfig.commands |
| 2269 |
|
| 2270 |
def parsebit(self, pos) -> None: |
| 2271 |
"Parse a command without parameters" |
| 2272 |
self.contents = [FormulaConstant(self.translated)] |
| 2273 |
|
| 2274 |
|
| 2275 |
class SpacedCommand(CommandBit): |
| 2276 |
"""An empty command which should have math spacing in formulas.""" |
| 2277 |
|
| 2278 |
commandmap = FormulaConfig.spacedcommands |
| 2279 |
|
| 2280 |
def parsebit(self, pos) -> None: |
| 2281 |
"Place as contents the command translated and spaced." |
| 2282 |
|
| 2283 |
|
| 2284 |
|
| 2285 |
self.contents = [FormulaConstant('\u2009' + self.translated + '\u2009')] |
| 2286 |
|
| 2287 |
|
| 2288 |
class AlphaCommand(EmptyCommand): |
| 2289 |
"""A command without parameters whose result is alphabetical.""" |
| 2290 |
|
| 2291 |
commandmap = FormulaConfig.alphacommands |
| 2292 |
greek_capitals = ('\\Xi', '\\Theta', '\\Pi', '\\Sigma', '\\Gamma', |
| 2293 |
'\\Lambda', '\\Phi', '\\Psi', '\\Delta', |
| 2294 |
'\\Upsilon', '\\Omega') |
| 2295 |
|
| 2296 |
def parsebit(self, pos) -> None: |
| 2297 |
"Parse the command and set type to alpha" |
| 2298 |
EmptyCommand.parsebit(self, pos) |
| 2299 |
if self.command not in self.greek_capitals: |
| 2300 |
|
| 2301 |
|
| 2302 |
self.type = 'alpha' |
| 2303 |
|
| 2304 |
|
| 2305 |
class OneParamFunction(CommandBit): |
| 2306 |
"A function of one parameter" |
| 2307 |
|
| 2308 |
commandmap = FormulaConfig.onefunctions |
| 2309 |
simplified = False |
| 2310 |
|
| 2311 |
def parsebit(self, pos) -> None: |
| 2312 |
"Parse a function with one parameter" |
| 2313 |
self.output = TaggedOutput().settag(self.translated) |
| 2314 |
self.parseparameter(pos) |
| 2315 |
self.simplifyifpossible() |
| 2316 |
|
| 2317 |
def simplifyifpossible(self) -> None: |
| 2318 |
"Try to simplify to a single character." |
| 2319 |
if self.original in self.commandmap: |
| 2320 |
self.output = FixedOutput() |
| 2321 |
self.html = [self.commandmap[self.original]] |
| 2322 |
self.simplified = True |
| 2323 |
|
| 2324 |
|
| 2325 |
class SymbolFunction(CommandBit): |
| 2326 |
"Find a function which is represented by a symbol (like _ or ^)" |
| 2327 |
|
| 2328 |
commandmap = FormulaConfig.symbolfunctions |
| 2329 |
|
| 2330 |
def detect(self, pos) -> bool: |
| 2331 |
"Find the symbol" |
| 2332 |
return pos.current() in SymbolFunction.commandmap |
| 2333 |
|
| 2334 |
def parsebit(self, pos) -> None: |
| 2335 |
"Parse the symbol" |
| 2336 |
self.setcommand(pos.current()) |
| 2337 |
pos.skip(self.command) |
| 2338 |
self.output = TaggedOutput().settag(self.translated) |
| 2339 |
self.parseparameter(pos) |
| 2340 |
|
| 2341 |
|
| 2342 |
class TextFunction(CommandBit): |
| 2343 |
"A function where parameters are read as text." |
| 2344 |
|
| 2345 |
commandmap = FormulaConfig.textfunctions |
| 2346 |
|
| 2347 |
def parsebit(self, pos) -> None: |
| 2348 |
"Parse a text parameter" |
| 2349 |
self.output = TaggedOutput().settag(self.translated) |
| 2350 |
self.parsetext(pos) |
| 2351 |
|
| 2352 |
def process(self) -> None: |
| 2353 |
"Set the type to font" |
| 2354 |
self.type = 'font' |
| 2355 |
|
| 2356 |
|
| 2357 |
class FontFunction(OneParamFunction): |
| 2358 |
"""A function of one parameter that changes the font.""" |
| 2359 |
|
| 2360 |
|
| 2361 |
commandmap = FormulaConfig.fontfunctions |
| 2362 |
|
| 2363 |
def process(self) -> None: |
| 2364 |
"Simplify if possible using a single character." |
| 2365 |
self.type = 'font' |
| 2366 |
self.simplifyifpossible() |
| 2367 |
|
| 2368 |
|
| 2369 |
FormulaFactory.types += [FormulaCommand, SymbolFunction] |
| 2370 |
FormulaCommand.types = [ |
| 2371 |
AlphaCommand, EmptyCommand, OneParamFunction, FontFunction, |
| 2372 |
TextFunction, SpacedCommand] |
| 2373 |
|
| 2374 |
|
| 2375 |
class BigBracket: |
| 2376 |
"A big bracket generator." |
| 2377 |
|
| 2378 |
def __init__(self, size, bracket, alignment='l') -> None: |
| 2379 |
"Set the size and symbol for the bracket." |
| 2380 |
self.size = size |
| 2381 |
self.original = bracket |
| 2382 |
self.alignment = alignment |
| 2383 |
self.pieces = None |
| 2384 |
if bracket in FormulaConfig.bigbrackets: |
| 2385 |
self.pieces = FormulaConfig.bigbrackets[bracket] |
| 2386 |
|
| 2387 |
def getpiece(self, index): |
| 2388 |
"Return the nth piece for the bracket." |
| 2389 |
function = getattr(self, 'getpiece' + str(len(self.pieces))) |
| 2390 |
return function(index) |
| 2391 |
|
| 2392 |
def getpiece1(self, index): |
| 2393 |
"Return the only piece for a single-piece bracket." |
| 2394 |
return self.pieces[0] |
| 2395 |
|
| 2396 |
def getpiece3(self, index): |
| 2397 |
"Get the nth piece for a 3-piece bracket: parenthesis or square bracket." |
| 2398 |
if index == 0: |
| 2399 |
return self.pieces[0] |
| 2400 |
if index == self.size - 1: |
| 2401 |
return self.pieces[-1] |
| 2402 |
return self.pieces[1] |
| 2403 |
|
| 2404 |
def getpiece4(self, index): |
| 2405 |
"Get the nth piece for a 4-piece bracket: curly bracket." |
| 2406 |
if index == 0: |
| 2407 |
return self.pieces[0] |
| 2408 |
if index == self.size - 1: |
| 2409 |
return self.pieces[3] |
| 2410 |
if index == (self.size - 1)/2: |
| 2411 |
return self.pieces[2] |
| 2412 |
return self.pieces[1] |
| 2413 |
|
| 2414 |
def getcell(self, index): |
| 2415 |
"Get the bracket piece as an array cell." |
| 2416 |
piece = self.getpiece(index) |
| 2417 |
span = 'span class="bracket align-' + self.alignment + '"' |
| 2418 |
return TaggedBit().constant(piece, span) |
| 2419 |
|
| 2420 |
def getcontents(self): |
| 2421 |
"Get the bracket as an array or as a single bracket." |
| 2422 |
if self.size == 1 or not self.pieces: |
| 2423 |
return self.getsinglebracket() |
| 2424 |
rows = [] |
| 2425 |
for index in range(self.size): |
| 2426 |
cell = self.getcell(index) |
| 2427 |
rows.append(TaggedBit().complete([cell], 'span class="arrayrow"')) |
| 2428 |
return [TaggedBit().complete(rows, 'span class="array"')] |
| 2429 |
|
| 2430 |
def getsinglebracket(self): |
| 2431 |
"Return the bracket as a single sign." |
| 2432 |
if self.original == '.': |
| 2433 |
return [TaggedBit().constant('', 'span class="emptydot"')] |
| 2434 |
return [TaggedBit().constant(self.original, 'span class="stretchy"')] |
| 2435 |
|
| 2436 |
|
| 2437 |
class FormulaEquation(CommandBit): |
| 2438 |
"A simple numbered equation." |
| 2439 |
|
| 2440 |
piece = 'equation' |
| 2441 |
|
| 2442 |
def parsebit(self, pos) -> None: |
| 2443 |
"Parse the array" |
| 2444 |
self.output = ContentsOutput() |
| 2445 |
self.add(self.factory.parsetype(WholeFormula, pos)) |
| 2446 |
|
| 2447 |
|
| 2448 |
class FormulaCell(FormulaCommand): |
| 2449 |
"An array cell inside a row" |
| 2450 |
|
| 2451 |
def setalignment(self, alignment): |
| 2452 |
self.alignment = alignment |
| 2453 |
self.output = TaggedOutput().settag('span class="arraycell align-' |
| 2454 |
+ alignment + '"', True) |
| 2455 |
return self |
| 2456 |
|
| 2457 |
def parsebit(self, pos) -> None: |
| 2458 |
self.factory.clearskipped(pos) |
| 2459 |
if pos.finished(): |
| 2460 |
return |
| 2461 |
self.add(self.factory.parsetype(WholeFormula, pos)) |
| 2462 |
|
| 2463 |
|
| 2464 |
class FormulaRow(FormulaCommand): |
| 2465 |
"An array row inside an array" |
| 2466 |
|
| 2467 |
cellseparator = FormulaConfig.array['cellseparator'] |
| 2468 |
|
| 2469 |
def setalignments(self, alignments): |
| 2470 |
self.alignments = alignments |
| 2471 |
self.output = TaggedOutput().settag('span class="arrayrow"', True) |
| 2472 |
return self |
| 2473 |
|
| 2474 |
def parsebit(self, pos) -> None: |
| 2475 |
"Parse a whole row" |
| 2476 |
index = 0 |
| 2477 |
pos.pushending(self.cellseparator, optional=True) |
| 2478 |
while not pos.finished(): |
| 2479 |
cell = self.createcell(index) |
| 2480 |
cell.parsebit(pos) |
| 2481 |
self.add(cell) |
| 2482 |
index += 1 |
| 2483 |
pos.checkskip(self.cellseparator) |
| 2484 |
if len(self.contents) == 0: |
| 2485 |
self.output = EmptyOutput() |
| 2486 |
|
| 2487 |
def createcell(self, index): |
| 2488 |
"Create the cell that corresponds to the given index." |
| 2489 |
alignment = self.alignments[index % len(self.alignments)] |
| 2490 |
return self.factory.create(FormulaCell).setalignment(alignment) |
| 2491 |
|
| 2492 |
|
| 2493 |
class MultiRowFormula(CommandBit): |
| 2494 |
"A formula with multiple rows." |
| 2495 |
|
| 2496 |
def parserows(self, pos) -> None: |
| 2497 |
"Parse all rows, finish when no more row ends" |
| 2498 |
self.rows = [] |
| 2499 |
first = True |
| 2500 |
for row in self.iteraterows(pos): |
| 2501 |
if first: |
| 2502 |
first = False |
| 2503 |
else: |
| 2504 |
|
| 2505 |
self.addempty() |
| 2506 |
row.parsebit(pos) |
| 2507 |
self.addrow(row) |
| 2508 |
self.size = len(self.rows) |
| 2509 |
|
| 2510 |
def iteraterows(self, pos): |
| 2511 |
"Iterate over all rows, end when no more row ends" |
| 2512 |
rowseparator = FormulaConfig.array['rowseparator'] |
| 2513 |
while True: |
| 2514 |
pos.pushending(rowseparator, True) |
| 2515 |
row = self.factory.create(FormulaRow) |
| 2516 |
yield row.setalignments(self.alignments) |
| 2517 |
if pos.checkfor(rowseparator): |
| 2518 |
self.original += pos.popending(rowseparator) |
| 2519 |
else: |
| 2520 |
return |
| 2521 |
|
| 2522 |
def addempty(self) -> None: |
| 2523 |
"Add an empty row." |
| 2524 |
row = self.factory.create(FormulaRow).setalignments(self.alignments) |
| 2525 |
for index, originalcell in enumerate(self.rows[-1].contents): |
| 2526 |
cell = row.createcell(index) |
| 2527 |
cell.add(FormulaConstant(' ')) |
| 2528 |
row.add(cell) |
| 2529 |
self.addrow(row) |
| 2530 |
|
| 2531 |
def addrow(self, row) -> None: |
| 2532 |
"Add a row to the contents and to the list of rows." |
| 2533 |
self.rows.append(row) |
| 2534 |
self.add(row) |
| 2535 |
|
| 2536 |
|
| 2537 |
class FormulaArray(MultiRowFormula): |
| 2538 |
"An array within a formula" |
| 2539 |
|
| 2540 |
piece = 'array' |
| 2541 |
|
| 2542 |
def parsebit(self, pos) -> None: |
| 2543 |
"Parse the array" |
| 2544 |
self.output = TaggedOutput().settag('span class="array"', False) |
| 2545 |
self.parsealignments(pos) |
| 2546 |
self.parserows(pos) |
| 2547 |
|
| 2548 |
def parsealignments(self, pos) -> None: |
| 2549 |
"Parse the different alignments" |
| 2550 |
|
| 2551 |
self.valign = 'c' |
| 2552 |
literal = self.parsesquareliteral(pos) |
| 2553 |
if literal: |
| 2554 |
self.valign = literal |
| 2555 |
|
| 2556 |
literal = self.parseliteral(pos) |
| 2557 |
self.alignments = [] |
| 2558 |
for s in literal: |
| 2559 |
self.alignments.append(s) |
| 2560 |
|
| 2561 |
|
| 2562 |
class FormulaMatrix(MultiRowFormula): |
| 2563 |
"A matrix (array with center alignment)." |
| 2564 |
|
| 2565 |
piece = 'matrix' |
| 2566 |
|
| 2567 |
def parsebit(self, pos) -> None: |
| 2568 |
"Parse the matrix, set alignments to 'c'." |
| 2569 |
self.output = TaggedOutput().settag('span class="array"', False) |
| 2570 |
self.valign = 'c' |
| 2571 |
self.alignments = ['c'] |
| 2572 |
self.parserows(pos) |
| 2573 |
|
| 2574 |
|
| 2575 |
class FormulaCases(MultiRowFormula): |
| 2576 |
"A cases statement" |
| 2577 |
|
| 2578 |
piece = 'cases' |
| 2579 |
|
| 2580 |
def parsebit(self, pos) -> None: |
| 2581 |
"Parse the cases" |
| 2582 |
self.output = ContentsOutput() |
| 2583 |
self.alignments = ['l', 'l'] |
| 2584 |
self.parserows(pos) |
| 2585 |
for row in self.contents: |
| 2586 |
for cell in row.contents: |
| 2587 |
cell.output.settag('span class="case align-l"', True) |
| 2588 |
cell.contents.append(FormulaConstant(' ')) |
| 2589 |
array = TaggedBit().complete(self.contents, 'span class="bracketcases"', True) |
| 2590 |
brace = BigBracket(len(self.contents), '{', 'l') |
| 2591 |
self.contents = brace.getcontents() + [array] |
| 2592 |
|
| 2593 |
|
| 2594 |
class EquationEnvironment(MultiRowFormula): |
| 2595 |
"A \\begin{}...\\end equation environment with rows and cells." |
| 2596 |
|
| 2597 |
def parsebit(self, pos) -> None: |
| 2598 |
"Parse the whole environment." |
| 2599 |
environment = self.piece.replace('*', '') |
| 2600 |
self.output = TaggedOutput().settag( |
| 2601 |
'span class="environment %s"'%environment, False) |
| 2602 |
if environment in FormulaConfig.environments: |
| 2603 |
self.alignments = FormulaConfig.environments[environment] |
| 2604 |
else: |
| 2605 |
Trace.error('Unknown equation environment ' + self.piece) |
| 2606 |
|
| 2607 |
self.output = TaggedOutput().settag('span class="unknown"') |
| 2608 |
self.add(FormulaConstant('\\begin{%s} '%environment)) |
| 2609 |
|
| 2610 |
self.alignments = ['l'] |
| 2611 |
self.parserows(pos) |
| 2612 |
|
| 2613 |
|
| 2614 |
class BeginCommand(CommandBit): |
| 2615 |
"A \\begin{}...\\end command and what it entails (array, cases, aligned)" |
| 2616 |
|
| 2617 |
commandmap = {FormulaConfig.array['begin']: ''} |
| 2618 |
|
| 2619 |
types = [FormulaEquation, FormulaArray, FormulaCases, FormulaMatrix] |
| 2620 |
|
| 2621 |
def parsebit(self, pos) -> None: |
| 2622 |
"Parse the begin command" |
| 2623 |
command = self.parseliteral(pos) |
| 2624 |
bit = self.findbit(command) |
| 2625 |
ending = FormulaConfig.array['end'] + '{' + command + '}' |
| 2626 |
pos.pushending(ending) |
| 2627 |
bit.parsebit(pos) |
| 2628 |
self.add(bit) |
| 2629 |
self.original += pos.popending(ending) |
| 2630 |
self.size = bit.size |
| 2631 |
|
| 2632 |
def findbit(self, piece): |
| 2633 |
"Find the command bit corresponding to the \\begin{piece}" |
| 2634 |
for type in BeginCommand.types: |
| 2635 |
if piece.replace('*', '') == type.piece: |
| 2636 |
return self.factory.create(type) |
| 2637 |
bit = self.factory.create(EquationEnvironment) |
| 2638 |
bit.piece = piece |
| 2639 |
return bit |
| 2640 |
|
| 2641 |
|
| 2642 |
FormulaCommand.types += [BeginCommand] |
| 2643 |
|
| 2644 |
|
| 2645 |
class CombiningFunction(OneParamFunction): |
| 2646 |
|
| 2647 |
commandmap = FormulaConfig.combiningfunctions |
| 2648 |
|
| 2649 |
def parsebit(self, pos) -> None: |
| 2650 |
"Parse a combining function." |
| 2651 |
combining = self.translated |
| 2652 |
parameter = self.parsesingleparameter(pos) |
| 2653 |
if not parameter: |
| 2654 |
Trace.error('Missing parameter for combining function ' + self.command) |
| 2655 |
return |
| 2656 |
|
| 2657 |
|
| 2658 |
if not isinstance(parameter, FormulaConstant): |
| 2659 |
try: |
| 2660 |
extractor = ContainerExtractor(ContainerConfig.extracttext) |
| 2661 |
parameter = extractor.extract(parameter)[0] |
| 2662 |
except IndexError: |
| 2663 |
Trace.error('No base character found for "%s".' % self.command) |
| 2664 |
return |
| 2665 |
|
| 2666 |
|
| 2667 |
if parameter.string.startswith('\u2009'): |
| 2668 |
i = 2 |
| 2669 |
else: |
| 2670 |
i = 1 |
| 2671 |
parameter.string = parameter.string[:i] + combining + parameter.string[i:] |
| 2672 |
y. |
| 2673 |
parameter.string = unicodedata.normalize('NFC', parameter.string) |
| 2674 |
|
| 2675 |
def parsesingleparameter(self, pos): |
| 2676 |
"Parse a parameter, or a single letter." |
| 2677 |
self.factory.clearskipped(pos) |
| 2678 |
if pos.finished(): |
| 2679 |
return None |
| 2680 |
return self.parseparameter(pos) |
| 2681 |
|
| 2682 |
|
| 2683 |
class OversetFunction(OneParamFunction): |
| 2684 |
"A function that decorates some bit of text with an overset." |
| 2685 |
|
| 2686 |
commandmap = FormulaConfig.oversetfunctions |
| 2687 |
|
| 2688 |
def parsebit(self, pos) -> None: |
| 2689 |
"Parse an overset-function" |
| 2690 |
symbol = self.translated |
| 2691 |
self.symbol = TaggedBit().constant(symbol, 'sup') |
| 2692 |
self.parameter = self.parseparameter(pos) |
| 2693 |
self.output = TaggedOutput().settag('span class="embellished"') |
| 2694 |
self.contents.insert(0, self.symbol) |
| 2695 |
self.parameter.output = TaggedOutput().settag('span class="base"') |
| 2696 |
self.simplifyifpossible() |
| 2697 |
|
| 2698 |
|
| 2699 |
class UndersetFunction(OneParamFunction): |
| 2700 |
"A function that decorates some bit of text with an underset." |
| 2701 |
|
| 2702 |
commandmap = FormulaConfig.undersetfunctions |
| 2703 |
|
| 2704 |
def parsebit(self, pos) -> None: |
| 2705 |
"Parse an underset-function" |
| 2706 |
symbol = self.translated |
| 2707 |
self.symbol = TaggedBit().constant(symbol, 'sub') |
| 2708 |
self.parameter = self.parseparameter(pos) |
| 2709 |
self.output = TaggedOutput().settag('span class="embellished"') |
| 2710 |
self.contents.insert(0, self.symbol) |
| 2711 |
self.parameter.output = TaggedOutput().settag('span class="base"') |
| 2712 |
self.simplifyifpossible() |
| 2713 |
|
| 2714 |
|
| 2715 |
class LimitCommand(EmptyCommand): |
| 2716 |
"A command which accepts limits above and below, in display mode." |
| 2717 |
|
| 2718 |
commandmap = FormulaConfig.limitcommands |
| 2719 |
|
| 2720 |
def parsebit(self, pos) -> None: |
| 2721 |
"Parse a limit command." |
| 2722 |
self.output = TaggedOutput().settag('span class="limits"') |
| 2723 |
symbol = self.translated |
| 2724 |
self.contents.append(TaggedBit().constant(symbol, 'span class="limit"')) |
| 2725 |
|
| 2726 |
|
| 2727 |
class LimitPreviousCommand(LimitCommand): |
| 2728 |
"A command to limit the previous command." |
| 2729 |
|
| 2730 |
commandmap = None |
| 2731 |
|
| 2732 |
def parsebit(self, pos) -> None: |
| 2733 |
"Do nothing." |
| 2734 |
self.output = TaggedOutput().settag('span class="limits"') |
| 2735 |
self.factory.clearskipped(pos) |
| 2736 |
|
| 2737 |
def __str__(self) -> str: |
| 2738 |
"Return a printable representation." |
| 2739 |
return 'Limit previous command' |
| 2740 |
|
| 2741 |
|
| 2742 |
class LimitsProcessor(MathsProcessor): |
| 2743 |
"A processor for limits inside an element." |
| 2744 |
|
| 2745 |
def process(self, contents, index) -> None: |
| 2746 |
"Process the limits for an element." |
| 2747 |
if Options.simplemath: |
| 2748 |
return |
| 2749 |
if self.checklimits(contents, index): |
| 2750 |
self.modifylimits(contents, index) |
| 2751 |
if self.checkscript(contents, index) and self.checkscript(contents, index + 1): |
| 2752 |
self.modifyscripts(contents, index) |
| 2753 |
|
| 2754 |
def checklimits(self, contents, index): |
| 2755 |
"Check if the current position has a limits command." |
| 2756 |
|
| 2757 |
if not DocumentParameters.displaymode: |
| 2758 |
return False |
| 2759 |
if self.checkcommand(contents, index + 1, LimitPreviousCommand): |
| 2760 |
self.limitsahead(contents, index) |
| 2761 |
return False |
| 2762 |
if not isinstance(contents[index], LimitCommand): |
| 2763 |
return False |
| 2764 |
return self.checkscript(contents, index + 1) |
| 2765 |
|
| 2766 |
def limitsahead(self, contents, index) -> None: |
| 2767 |
"Limit the current element based on the next." |
| 2768 |
contents[index + 1].add(contents[index].clone()) |
| 2769 |
contents[index].output = EmptyOutput() |
| 2770 |
|
| 2771 |
def modifylimits(self, contents, index) -> None: |
| 2772 |
"Modify a limits commands so that the limits appear above and below." |
| 2773 |
limited = contents[index] |
| 2774 |
subscript = self.getlimit(contents, index + 1) |
| 2775 |
if self.checkscript(contents, index + 1): |
| 2776 |
superscript = self.getlimit(contents, index + 1) |
| 2777 |
else: |
| 2778 |
superscript = TaggedBit().constant('\u2009', 'sup class="limit"') |
| 2779 |
|
| 2780 |
if subscript.command == '^': |
| 2781 |
superscript, subscript = subscript, superscript |
| 2782 |
limited.contents.append(subscript) |
| 2783 |
limited.contents.insert(0, superscript) |
| 2784 |
|
| 2785 |
def getlimit(self, contents, index): |
| 2786 |
"Get the limit for a limits command." |
| 2787 |
limit = self.getscript(contents, index) |
| 2788 |
limit.output.tag = limit.output.tag.replace('script', 'limit') |
| 2789 |
return limit |
| 2790 |
|
| 2791 |
def modifyscripts(self, contents, index) -> None: |
| 2792 |
"Modify the super- and subscript to appear vertically aligned." |
| 2793 |
subscript = self.getscript(contents, index) |
| 2794 |
|
| 2795 |
superscript = self.getscript(contents, index) |
| 2796 |
|
| 2797 |
if subscript.command == '^': |
| 2798 |
superscript, subscript = subscript, superscript |
| 2799 |
scripts = TaggedBit().complete([superscript, subscript], 'span class="scripts"') |
| 2800 |
contents.insert(index, scripts) |
| 2801 |
|
| 2802 |
def checkscript(self, contents, index): |
| 2803 |
"Check if the current element is a sub- or superscript." |
| 2804 |
return self.checkcommand(contents, index, SymbolFunction) |
| 2805 |
|
| 2806 |
def checkcommand(self, contents, index, type): |
| 2807 |
"Check for the given type as the current element." |
| 2808 |
if len(contents) <= index: |
| 2809 |
return False |
| 2810 |
return isinstance(contents[index], type) |
| 2811 |
|
| 2812 |
def getscript(self, contents, index): |
| 2813 |
"Get the sub- or superscript." |
| 2814 |
bit = contents[index] |
| 2815 |
bit.output.tag += ' class="script"' |
| 2816 |
del contents[index] |
| 2817 |
return bit |
| 2818 |
|
| 2819 |
|
| 2820 |
class BracketCommand(OneParamFunction): |
| 2821 |
"A command which defines a bracket." |
| 2822 |
|
| 2823 |
commandmap = FormulaConfig.bracketcommands |
| 2824 |
|
| 2825 |
def parsebit(self, pos) -> None: |
| 2826 |
"Parse the bracket." |
| 2827 |
OneParamFunction.parsebit(self, pos) |
| 2828 |
|
| 2829 |
def create(self, direction, character): |
| 2830 |
"Create the bracket for the given character." |
| 2831 |
self.original = character |
| 2832 |
self.command = '\\' + direction |
| 2833 |
self.contents = [FormulaConstant(character)] |
| 2834 |
return self |
| 2835 |
|
| 2836 |
|
| 2837 |
class BracketProcessor(MathsProcessor): |
| 2838 |
"A processor for bracket commands." |
| 2839 |
|
| 2840 |
def process(self, contents, index): |
| 2841 |
"Convert the bracket using Unicode pieces, if possible." |
| 2842 |
if Options.simplemath: |
| 2843 |
return |
| 2844 |
if self.checkleft(contents, index): |
| 2845 |
return self.processleft(contents, index) |
| 2846 |
|
| 2847 |
def processleft(self, contents, index) -> None: |
| 2848 |
"Process a left bracket." |
| 2849 |
rightindex = self.findright(contents, index + 1) |
| 2850 |
if not rightindex: |
| 2851 |
return |
| 2852 |
size = self.findmax(contents, index, rightindex) |
| 2853 |
self.resize(contents[index], size) |
| 2854 |
self.resize(contents[rightindex], size) |
| 2855 |
|
| 2856 |
def checkleft(self, contents, index): |
| 2857 |
"Check if the command at the given index is left." |
| 2858 |
return self.checkdirection(contents[index], '\\left') |
| 2859 |
|
| 2860 |
def checkright(self, contents, index): |
| 2861 |
"Check if the command at the given index is right." |
| 2862 |
return self.checkdirection(contents[index], '\\right') |
| 2863 |
|
| 2864 |
def checkdirection(self, bit, command): |
| 2865 |
"Check if the given bit is the desired bracket command." |
| 2866 |
if not isinstance(bit, BracketCommand): |
| 2867 |
return False |
| 2868 |
return bit.command == command |
| 2869 |
|
| 2870 |
def findright(self, contents, index): |
| 2871 |
"Find the right bracket starting at the given index, or 0." |
| 2872 |
depth = 1 |
| 2873 |
while index < len(contents): |
| 2874 |
if self.checkleft(contents, index): |
| 2875 |
depth += 1 |
| 2876 |
if self.checkright(contents, index): |
| 2877 |
depth -= 1 |
| 2878 |
if depth == 0: |
| 2879 |
return index |
| 2880 |
index += 1 |
| 2881 |
return None |
| 2882 |
|
| 2883 |
def findmax(self, contents, leftindex, rightindex): |
| 2884 |
"Find the max size of the contents between the two given indices." |
| 2885 |
sliced = contents[leftindex:rightindex] |
| 2886 |
return max(element.size for element in sliced) |
| 2887 |
|
| 2888 |
def resize(self, command, size) -> None: |
| 2889 |
"Resize a bracket command to the given size." |
| 2890 |
character = command.extracttext() |
| 2891 |
alignment = command.command.replace('\\', '') |
| 2892 |
bracket = BigBracket(size, character, alignment) |
| 2893 |
command.output = ContentsOutput() |
| 2894 |
command.contents = bracket.getcontents() |
| 2895 |
|
| 2896 |
|
| 2897 |
FormulaCommand.types += [OversetFunction, UndersetFunction, |
| 2898 |
CombiningFunction, LimitCommand, BracketCommand] |
| 2899 |
|
| 2900 |
FormulaProcessor.processors += [ |
| 2901 |
LimitsProcessor(), BracketProcessor(), |
| 2902 |
] |
| 2903 |
|
| 2904 |
|
| 2905 |
class ParameterDefinition: |
| 2906 |
"The definition of a parameter in a hybrid function." |
| 2907 |
"[] parameters are optional, {} parameters are mandatory." |
| 2908 |
"Each parameter has a one-character name, like {$1} or {$p}." |
| 2909 |
"A parameter that ends in ! like {$p!} is a literal." |
| 2910 |
"Example: [$1]{$p!} reads an optional parameter $1 and a literal mandatory parameter p." |
| 2911 |
|
| 2912 |
parambrackets = [('[', ']'), ('{', '}')] |
| 2913 |
|
| 2914 |
def __init__(self) -> None: |
| 2915 |
self.name = None |
| 2916 |
self.literal = False |
| 2917 |
self.optional = False |
| 2918 |
self.value = None |
| 2919 |
self.literalvalue = None |
| 2920 |
|
| 2921 |
def parse(self, pos): |
| 2922 |
"Parse a parameter definition: [$0], {$x}, {$1!}..." |
| 2923 |
for (opening, closing) in ParameterDefinition.parambrackets: |
| 2924 |
if pos.checkskip(opening): |
| 2925 |
if opening == '[': |
| 2926 |
self.optional = True |
| 2927 |
if not pos.checkskip('$'): |
| 2928 |
Trace.error('Wrong parameter name, did you mean $' + pos.current() + '?') |
| 2929 |
return None |
| 2930 |
self.name = pos.skipcurrent() |
| 2931 |
if pos.checkskip('!'): |
| 2932 |
self.literal = True |
| 2933 |
if not pos.checkskip(closing): |
| 2934 |
Trace.error('Wrong parameter closing ' + pos.skipcurrent()) |
| 2935 |
return None |
| 2936 |
return self |
| 2937 |
Trace.error('Wrong character in parameter template: ' + pos.skipcurrent()) |
| 2938 |
return None |
| 2939 |
|
| 2940 |
def read(self, pos, function) -> None: |
| 2941 |
"Read the parameter itself using the definition." |
| 2942 |
if self.literal: |
| 2943 |
if self.optional: |
| 2944 |
self.literalvalue = function.parsesquareliteral(pos) |
| 2945 |
else: |
| 2946 |
self.literalvalue = function.parseliteral(pos) |
| 2947 |
if self.literalvalue: |
| 2948 |
self.value = FormulaConstant(self.literalvalue) |
| 2949 |
elif self.optional: |
| 2950 |
self.value = function.parsesquare(pos) |
| 2951 |
else: |
| 2952 |
self.value = function.parseparameter(pos) |
| 2953 |
|
| 2954 |
def __str__(self) -> str: |
| 2955 |
"Return a printable representation." |
| 2956 |
result = 'param ' + self.name |
| 2957 |
if self.value: |
| 2958 |
result += ': ' + str(self.value) |
| 2959 |
else: |
| 2960 |
result += ' (empty)' |
| 2961 |
return result |
| 2962 |
|
| 2963 |
|
| 2964 |
class ParameterFunction(CommandBit): |
| 2965 |
"A function with a variable number of parameters defined in a template." |
| 2966 |
"The parameters are defined as a parameter definition." |
| 2967 |
|
| 2968 |
def readparams(self, readtemplate, pos) -> None: |
| 2969 |
"Read the params according to the template." |
| 2970 |
self.params = {} |
| 2971 |
for paramdef in self.paramdefs(readtemplate): |
| 2972 |
paramdef.read(pos, self) |
| 2973 |
self.params['$' + paramdef.name] = paramdef |
| 2974 |
|
| 2975 |
def paramdefs(self, readtemplate): |
| 2976 |
"Read each param definition in the template" |
| 2977 |
pos = TextPosition(readtemplate) |
| 2978 |
while not pos.finished(): |
| 2979 |
paramdef = ParameterDefinition().parse(pos) |
| 2980 |
if paramdef: |
| 2981 |
yield paramdef |
| 2982 |
|
| 2983 |
def getparam(self, name): |
| 2984 |
"Get a parameter as parsed." |
| 2985 |
if name not in self.params: |
| 2986 |
return None |
| 2987 |
return self.params[name] |
| 2988 |
|
| 2989 |
def getvalue(self, name): |
| 2990 |
"Get the value of a parameter." |
| 2991 |
return self.getparam(name).value |
| 2992 |
|
| 2993 |
def getliteralvalue(self, name): |
| 2994 |
"Get the literal value of a parameter." |
| 2995 |
param = self.getparam(name) |
| 2996 |
if not param or not param.literalvalue: |
| 2997 |
return None |
| 2998 |
return param.literalvalue |
| 2999 |
|
| 3000 |
|
| 3001 |
class HybridFunction(ParameterFunction): |
| 3002 |
""" |
| 3003 |
A parameter function where the output is also defined using a template. |
| 3004 |
The template can use a number of functions; each function has an associated |
| 3005 |
tag. |
| 3006 |
Example: [f0{$1},span class="fbox"] defines a function f0 which corresponds |
| 3007 |
to a span of class fbox, yielding <span class="fbox">$1</span>. |
| 3008 |
Literal parameters can be used in tags definitions: |
| 3009 |
[f0{$1},span style="color: $p;"] |
| 3010 |
yields <span style="color: $p;">$1</span>, where $p is a literal parameter. |
| 3011 |
Sizes can be specified in hybridsizes, e.g. adding parameter sizes. By |
| 3012 |
default the resulting size is the max of all arguments. Sizes are used |
| 3013 |
to generate the right parameters. |
| 3014 |
A function followed by a single / is output as a self-closing XHTML tag: |
| 3015 |
[f0/,hr] |
| 3016 |
will generate <hr/>. |
| 3017 |
""" |
| 3018 |
|
| 3019 |
commandmap = FormulaConfig.hybridfunctions |
| 3020 |
|
| 3021 |
def parsebit(self, pos) -> None: |
| 3022 |
"Parse a function with [] and {} parameters" |
| 3023 |
readtemplate = self.translated[0] |
| 3024 |
writetemplate = self.translated[1] |
| 3025 |
self.readparams(readtemplate, pos) |
| 3026 |
self.contents = self.writeparams(writetemplate) |
| 3027 |
self.computehybridsize() |
| 3028 |
|
| 3029 |
def writeparams(self, writetemplate): |
| 3030 |
"Write all params according to the template" |
| 3031 |
return self.writepos(TextPosition(writetemplate)) |
| 3032 |
|
| 3033 |
def writepos(self, pos): |
| 3034 |
"Write all params as read in the parse position." |
| 3035 |
result = [] |
| 3036 |
while not pos.finished(): |
| 3037 |
if pos.checkskip('$'): |
| 3038 |
param = self.writeparam(pos) |
| 3039 |
if param: |
| 3040 |
result.append(param) |
| 3041 |
elif pos.checkskip('f'): |
| 3042 |
function = self.writefunction(pos) |
| 3043 |
if function: |
| 3044 |
function.type = None |
| 3045 |
result.append(function) |
| 3046 |
elif pos.checkskip('('): |
| 3047 |
result.append(self.writebracket('left', '(')) |
| 3048 |
elif pos.checkskip(')'): |
| 3049 |
result.append(self.writebracket('right', ')')) |
| 3050 |
else: |
| 3051 |
result.append(FormulaConstant(pos.skipcurrent())) |
| 3052 |
return result |
| 3053 |
|
| 3054 |
def writeparam(self, pos): |
| 3055 |
"Write a single param of the form $0, $x..." |
| 3056 |
name = '$' + pos.skipcurrent() |
| 3057 |
if name not in self.params: |
| 3058 |
Trace.error('Unknown parameter ' + name) |
| 3059 |
return None |
| 3060 |
if not self.params[name]: |
| 3061 |
return None |
| 3062 |
if pos.checkskip('.'): |
| 3063 |
self.params[name].value.type = pos.globalpha() |
| 3064 |
return self.params[name].value |
| 3065 |
|
| 3066 |
def writefunction(self, pos): |
| 3067 |
"Write a single function f0,...,fn." |
| 3068 |
tag = self.readtag(pos) |
| 3069 |
if not tag: |
| 3070 |
return None |
| 3071 |
if pos.checkskip('/'): |
| 3072 |
|
| 3073 |
return TaggedBit().selfcomplete(tag) |
| 3074 |
if not pos.checkskip('{'): |
| 3075 |
Trace.error('Function should be defined in {}') |
| 3076 |
return None |
| 3077 |
pos.pushending('}') |
| 3078 |
contents = self.writepos(pos) |
| 3079 |
pos.popending() |
| 3080 |
if len(contents) == 0: |
| 3081 |
return None |
| 3082 |
return TaggedBit().complete(contents, tag) |
| 3083 |
|
| 3084 |
def readtag(self, pos): |
| 3085 |
"Get the tag corresponding to the given index. Does parameter substitution." |
| 3086 |
if not pos.current().isdigit(): |
| 3087 |
Trace.error('Function should be f0,...,f9: f' + pos.current()) |
| 3088 |
return None |
| 3089 |
index = int(pos.skipcurrent()) |
| 3090 |
if 2 + index > len(self.translated): |
| 3091 |
Trace.error('Function f' + str(index) + ' is not defined') |
| 3092 |
return None |
| 3093 |
tag = self.translated[2 + index] |
| 3094 |
if '$' not in tag: |
| 3095 |
return tag |
| 3096 |
for variable in self.params: |
| 3097 |
if variable in tag: |
| 3098 |
param = self.params[variable] |
| 3099 |
if not param.literal: |
| 3100 |
Trace.error('Parameters in tag ' + tag + ' should be literal: {' + variable + '!}') |
| 3101 |
continue |
| 3102 |
if param.literalvalue: |
| 3103 |
value = param.literalvalue |
| 3104 |
else: |
| 3105 |
value = '' |
| 3106 |
tag = tag.replace(variable, value) |
| 3107 |
return tag |
| 3108 |
|
| 3109 |
def writebracket(self, direction, character): |
| 3110 |
"Return a new bracket looking at the given direction." |
| 3111 |
return self.factory.create(BracketCommand).create(direction, character) |
| 3112 |
|
| 3113 |
def computehybridsize(self) -> None: |
| 3114 |
"Compute the size of the hybrid function." |
| 3115 |
if self.command not in HybridSize.configsizes: |
| 3116 |
self.computesize() |
| 3117 |
return |
| 3118 |
self.size = HybridSize().getsize(self) |
| 3119 |
|
| 3120 |
for element in self.contents: |
| 3121 |
element.size = self.size |
| 3122 |
|
| 3123 |
|
| 3124 |
class HybridSize: |
| 3125 |
"The size associated with a hybrid function." |
| 3126 |
|
| 3127 |
configsizes = FormulaConfig.hybridsizes |
| 3128 |
|
| 3129 |
def getsize(self, function): |
| 3130 |
"Read the size for a function and parse it." |
| 3131 |
sizestring = self.configsizes[function.command] |
| 3132 |
for name in function.params: |
| 3133 |
if name in sizestring: |
| 3134 |
size = function.params[name].value.computesize() |
| 3135 |
sizestring = sizestring.replace(name, str(size)) |
| 3136 |
if '$' in sizestring: |
| 3137 |
Trace.error('Unconverted variable in hybrid size: ' + sizestring) |
| 3138 |
return 1 |
| 3139 |
return eval(sizestring) |
| 3140 |
|
| 3141 |
|
| 3142 |
FormulaCommand.types += [HybridFunction] |
| 3143 |
|
| 3144 |
|
| 3145 |
def math2html(formula): |
| 3146 |
"Convert some TeX math to HTML." |
| 3147 |
factory = FormulaFactory() |
| 3148 |
whole = factory.parseformula(formula) |
| 3149 |
FormulaProcessor().process(whole) |
| 3150 |
whole.process() |
| 3151 |
return ''.join(whole.gethtml()) |
| 3152 |
|
| 3153 |
|
| 3154 |
def main() -> None: |
| 3155 |
"Main function, called if invoked from the command line" |
| 3156 |
args = sys.argv |
| 3157 |
Options().parseoptions(args) |
| 3158 |
if len(args) != 1: |
| 3159 |
Trace.error('Usage: math2html.py escaped_string') |
| 3160 |
exit() |
| 3161 |
result = math2html(args[0]) |
| 3162 |
Trace.message(result) |
| 3163 |
|
| 3164 |
|
| 3165 |
if __name__ == '__main__': |
| 3166 |
main() |