internal/texmath/texmath.go

545ba0bcdea3b534903bd78c918c0c025a97eda7
gitbay/internal/texmath/texmath.go

772 lines · 18546 bytes

49 symbols in this file
  1// Package texmath converts a subset of TeX math to MathML.
  2//
  3// The subset: letters, numbers and operator characters; ^ and _; braces;
  4// \frac and friends, \binom, \sqrt with an optional index; Greek letters and
  5// the common symbols, relations and arrows in symbols.go; function names
  6// (\sin, \lim, \operatorname{...}); large operators, which take their limits
  7// above and below in display style; \left, \middle and \right; accents,
  8// \overline, \underline and the braces; spacing commands; \text; the font
  9// commands \mathrm, \mathbf, \mathbb, \mathcal, \mathscr, \mathfrak, \mathsf,
 10// \mathtt, \mathit, \boldsymbol; and the environments matrix, pmatrix,
 11// bmatrix, Bmatrix, vmatrix, Vmatrix, smallmatrix, cases, aligned, align,
 12// gathered, gather, split, equation and displaymath.
 13//
 14// Anything else, including every command that defines macros, sets colors or
 15// styles, or links, is an error; the caller shows the source instead. The
 16// output uses only the elements and attributes listed in Elements and Attrs,
 17// and its size is linear in the input, which is capped at MaxInput bytes and
 18// MaxDepth levels of nesting.
 19package texmath
 20
 21import (
 22	"errors"
 23	"fmt"
 24	"html"
 25	"strings"
 26	"unicode"
 27	"unicode/utf8"
 28)
 29
 30// Limits on one expression.
 31const (
 32	MaxInput = 8 << 10
 33	MaxDepth = 64
 34)
 35
 36// Elements is every MathML element Convert emits.
 37var Elements = []string{
 38	"math", "mrow", "mi", "mn", "mo", "mtext", "mspace",
 39	"mfrac", "msqrt", "mroot", "msub", "msup", "msubsup",
 40	"munder", "mover", "munderover", "mtable", "mtr", "mtd",
 41}
 42
 43// Attrs is every attribute Convert emits, by element, with the values it
 44// can take: a fixed value, or "<length>" for an em length.
 45var Attrs = map[string]map[string]string{
 46	"math":   {"display": "block"},
 47	"mi":     {"mathvariant": "normal"},
 48	"mo":     {"stretchy": "false"},
 49	"mfrac":  {"linethickness": "0"},
 50	"mover":  {"accent": "true"},
 51	"mspace": {"width": "<length>"},
 52}
 53
 54var (
 55	ErrTooLong = errors.New("texmath: expression too long")
 56	ErrTooDeep = errors.New("texmath: expression nested too deeply")
 57)
 58
 59// Convert renders tex as one <math> element; display selects block layout
 60// and display-style limits.
 61func Convert(tex string, display bool) (string, error) {
 62	if len(tex) > MaxInput {
 63		return "", ErrTooLong
 64	}
 65	if !utf8.ValidString(tex) {
 66		return "", errors.New("texmath: invalid UTF-8")
 67	}
 68	for _, r := range tex {
 69		if isControl(r) {
 70			return "", errors.New("texmath: control character")
 71		}
 72	}
 73	p := &parser{src: tex, display: display}
 74	kids, err := p.list(func(t token) bool { return false })
 75	if err != nil {
 76		return "", err
 77	}
 78	if t := p.peek(); t.kind != eof {
 79		return "", p.unexpected(t)
 80	}
 81	root := &node{tag: "math", kids: kids}
 82	if display {
 83		root.attr("display", "block")
 84	}
 85	var b strings.Builder
 86	root.write(&b)
 87	return b.String(), nil
 88}
 89
 90type node struct {
 91	tag    string
 92	attrs  [][2]string
 93	text   string
 94	kids   []*node
 95	limits bool // a large operator: limits go under and over in display style
 96	fn     bool // a function name: a thin space follows unless a delimiter does
 97}
 98
 99func (n *node) attr(k, v string) *node {
100	n.attrs = append(n.attrs, [2]string{k, v})
101	return n
102}
103
104func (n *node) write(b *strings.Builder) {
105	b.WriteByte('<')
106	b.WriteString(n.tag)
107	for _, a := range n.attrs {
108		b.WriteString(" " + a[0] + `="` + html.EscapeString(a[1]) + `"`)
109	}
110	b.WriteByte('>')
111	b.WriteString(html.EscapeString(n.text))
112	for _, k := range n.kids {
113		k.write(b)
114	}
115	b.WriteString("</" + n.tag + ">")
116}
117
118func el(tag string, kids ...*node) *node { return &node{tag: tag, kids: kids} }
119func leaf(tag, text string) *node        { return &node{tag: tag, text: text} }
120func row(kids []*node) *node             { return &node{tag: "mrow", kids: kids} }
121func space(w string) *node               { return (&node{tag: "mspace"}).attr("width", w) }
122
123// fixed is an operator that must not stretch to the height of its row, the
124// way a bracket typed without \left does not in TeX.
125func fixed(s string) *node { return leaf("mo", s).attr("stretchy", "false") }
126
127type kind int
128
129const (
130	eof  kind = iota
131	char      // one character
132	cmd       // a control sequence; val is its name without the backslash
133)
134
135type token struct {
136	kind kind
137	val  string
138	pos  int
139}
140
141type parser struct {
142	src     string
143	pos     int
144	depth   int
145	display bool
146	font    string
147}
148
149func (p *parser) skip() {
150	for p.pos < len(p.src) {
151		c := p.src[p.pos]
152		switch {
153		case c == ' ' || c == '\t' || c == '\n' || c == '\r':
154			p.pos++
155		case c == '%':
156			for p.pos < len(p.src) && p.src[p.pos] != '\n' {
157				p.pos++
158			}
159		default:
160			return
161		}
162	}
163}
164
165func (p *parser) peek() token {
166	save := p.pos
167	t := p.next()
168	p.pos = save
169	return t
170}
171
172func (p *parser) next() token {
173	p.skip()
174	start := p.pos
175	if p.pos >= len(p.src) {
176		return token{kind: eof, pos: start}
177	}
178	if p.src[p.pos] == '\\' {
179		p.pos++
180		if p.pos >= len(p.src) {
181			return token{kind: cmd, val: "", pos: start}
182		}
183		if isASCIILetter(p.src[p.pos]) {
184			end := p.pos
185			for end < len(p.src) && isASCIILetter(p.src[end]) {
186				end++
187			}
188			name := p.src[p.pos:end]
189			p.pos = end
190			// \operatorname* and friends: the star is part of the name.
191			if p.pos < len(p.src) && p.src[p.pos] == '*' && starred[name] {
192				p.pos++
193				name += "*"
194			}
195			return token{kind: cmd, val: name, pos: start}
196		}
197		r, n := utf8.DecodeRuneInString(p.src[p.pos:])
198		p.pos += n
199		return token{kind: cmd, val: string(r), pos: start}
200	}
201	r, n := utf8.DecodeRuneInString(p.src[p.pos:])
202	p.pos += n
203	return token{kind: char, val: string(r), pos: start}
204}
205
206var starred = map[string]bool{"operatorname": true}
207
208func isASCIILetter(c byte) bool { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' }
209func isDigit(c byte) bool       { return c >= '0' && c <= '9' }
210
211// isControl is a C0 control other than tab and the line ends, DEL, or
212// the noncharacters U+FFFE and U+FFFF.
213func isControl(r rune) bool {
214	switch r {
215	case '\t', '\n', '\r':
216		return false
217	case 0x7F, 0xFFFE, 0xFFFF:
218		return true
219	}
220	return r < 0x20
221}
222
223func (p *parser) unexpected(t token) error {
224	switch t.kind {
225	case eof:
226		return errors.New("texmath: unexpected end of input")
227	case cmd:
228		return fmt.Errorf(`texmath: unexpected \%s at %d`, t.val, t.pos)
229	}
230	return fmt.Errorf("texmath: unexpected %q at %d", t.val, t.pos)
231}
232
233func (p *parser) expect(kind kind, val string) error {
234	if t := p.next(); t.kind != kind || t.val != val {
235		return p.unexpected(t)
236	}
237	return nil
238}
239
240func isChar(t token, s string) bool { return t.kind == char && t.val == s }
241func isCmd(t token, s string) bool  { return t.kind == cmd && t.val == s }
242
243// list parses atoms until the input ends or stop matches the next token,
244// which is left unread.
245func (p *parser) list(stop func(token) bool) ([]*node, error) {
246	var out []*node
247	for {
248		t := p.peek()
249		if t.kind == eof || stop(t) {
250			return out, nil
251		}
252		n, err := p.scripted()
253		if err != nil {
254			return nil, err
255		}
256		if n == nil {
257			continue
258		}
259		out = append(out, n)
260		if n.fn && !p.delimiterNext() {
261			out = append(out, space("0.1667em"))
262		}
263	}
264}
265
266// delimiterNext reports whether the next token closes a group or opens a
267// bracket, where TeX puts no space after a function name.
268func (p *parser) delimiterNext() bool {
269	t := p.peek()
270	if t.kind == eof {
271		return true
272	}
273	if t.kind == char {
274		return strings.Contains("()[]{}|&.,;", t.val)
275	}
276	switch t.val {
277	case "left", "right", "\\", "end", ",", ";", "!", "quad", "qquad", "{", "}":
278		return true
279	}
280	return false
281}
282
283// scripted parses one atom and any sub- and superscripts attached to it.
284func (p *parser) scripted() (*node, error) {
285	var base *node
286	if t := p.peek(); !isChar(t, "^") && !isChar(t, "_") {
287		var err error
288		if base, err = p.atom(); err != nil {
289			return nil, err
290		}
291	}
292	var sub, sup *node
293	limits := base != nil && base.limits && p.display
294	for {
295		t := p.peek()
296		switch {
297		case isCmd(t, "limits"):
298			p.next()
299			limits = base != nil && base.limits
300			continue
301		case isCmd(t, "nolimits"):
302			p.next()
303			limits = false
304			continue
305		case isChar(t, "^"), isChar(t, "_"):
306		default:
307			if sub == nil && sup == nil {
308				return base, nil
309			}
310			if base == nil {
311				base = row(nil)
312			}
313			return script(base, sub, sup, limits), nil
314		}
315		p.next()
316		arg, err := p.arg()
317		if err != nil {
318			return nil, err
319		}
320		if t.val == "^" {
321			if sup != nil {
322				return nil, fmt.Errorf("texmath: double superscript at %d", t.pos)
323			}
324			sup = arg
325		} else {
326			if sub != nil {
327				return nil, fmt.Errorf("texmath: double subscript at %d", t.pos)
328			}
329			sub = arg
330		}
331	}
332}
333
334func script(base, sub, sup *node, limits bool) *node {
335	fn := base.fn
336	var n *node
337	switch {
338	case limits && sub != nil && sup != nil:
339		n = el("munderover", base, sub, sup)
340	case limits && sub != nil:
341		n = el("munder", base, sub)
342	case limits:
343		n = el("mover", base, sup)
344	case sub != nil && sup != nil:
345		n = el("msubsup", base, sub, sup)
346	case sub != nil:
347		n = el("msub", base, sub)
348	default:
349		n = el("msup", base, sup)
350	}
351	n.fn = fn
352	return n
353}
354
355// arg parses a command's argument: a braced group, or else one token.
356func (p *parser) arg() (*node, error) {
357	t := p.peek()
358	switch {
359	case t.kind == eof:
360		return nil, p.unexpected(t)
361	case t.kind == char && strings.Contains("}&^_", t.val):
362		return nil, p.unexpected(t)
363	case t.kind == char && t.val >= "0" && t.val <= "9":
364		p.next()
365		return leaf("mn", p.styled(t.val)), nil
366	}
367	n, err := p.atom()
368	if err == nil && n == nil {
369		// \displaystyle and the like render nothing, so cannot be an argument.
370		return nil, fmt.Errorf(`texmath: \%s cannot be an argument at %d`, t.val, t.pos)
371	}
372	return n, err
373}
374
375func (p *parser) enter() error {
376	p.depth++
377	if p.depth > MaxDepth {
378		return ErrTooDeep
379	}
380	return nil
381}
382
383// atom parses one atom. A nil node with a nil error is a command that
384// renders nothing, such as \displaystyle.
385func (p *parser) atom() (*node, error) {
386	if err := p.enter(); err != nil {
387		return nil, err
388	}
389	defer func() { p.depth-- }()
390	t := p.next()
391	switch t.kind {
392	case eof:
393		return nil, p.unexpected(t)
394	case char:
395		return p.charAtom(t)
396	}
397	return p.command(t)
398}
399
400func (p *parser) charAtom(t token) (*node, error) {
401	r, _ := utf8.DecodeRuneInString(t.val)
402	switch {
403	case t.val == "{":
404		font := p.font
405		kids, err := p.list(func(t token) bool { return isChar(t, "}") })
406		p.font = font
407		if err != nil {
408			return nil, err
409		}
410		if err := p.expect(char, "}"); err != nil {
411			return nil, err
412		}
413		return row(kids), nil
414	case r >= '0' && r <= '9':
415		num := t.val
416		for p.pos < len(p.src) {
417			c := p.src[p.pos]
418			if isDigit(c) || c == '.' && p.pos+1 < len(p.src) && isDigit(p.src[p.pos+1]) {
419				num += string(c)
420				p.pos++
421				continue
422			}
423			break
424		}
425		return leaf("mn", p.styled(num)), nil
426	case unicode.IsLetter(r):
427		n := leaf("mi", p.styled(t.val))
428		if p.font == "rm" {
429			n.attr("mathvariant", "normal")
430		}
431		return n, nil
432	}
433	switch t.val {
434	case "}", "&", "$", "#", "\\":
435		return nil, p.unexpected(t)
436	case "(", ")", "[", "]", "|", "/":
437		return fixed(t.val), nil
438	case "-":
439		return leaf("mo", "−"), nil
440	case "*":
441		return leaf("mo", "∗"), nil
442	case "'":
443		return leaf("mo", "′"), nil
444	case "~":
445		return space("0.3333em"), nil
446	}
447	if r < 0x20 || r == utf8.RuneError {
448		return nil, p.unexpected(t)
449	}
450	return leaf("mo", t.val), nil
451}
452
453func (p *parser) command(t token) (*node, error) {
454	name := t.val
455	if s, ok := symbols[name]; ok {
456		n := leaf(s.tag, s.text)
457		if s.upright {
458			n.attr("mathvariant", "normal")
459		}
460		if s.fixed {
461			n.attr("stretchy", "false")
462		}
463		n.limits = s.limits
464		return n, nil
465	}
466	if w, ok := spaces[name]; ok {
467		return space(w), nil
468	}
469	if f, ok := functions[name]; ok {
470		n := leaf("mi", name)
471		n.limits, n.fn = f, true
472		return n, nil
473	}
474	if a, ok := accents[name]; ok {
475		arg, err := p.arg()
476		if err != nil {
477			return nil, err
478		}
479		if a.under {
480			return el("munder", arg, leaf("mo", a.mark)), nil
481		}
482		n := el("mover", arg, leaf("mo", a.mark))
483		if a.accent {
484			n.attr("accent", "true")
485		}
486		return n, nil
487	}
488	if f, ok := fonts[name]; ok {
489		font := p.font
490		p.font = f
491		arg, err := p.arg()
492		p.font = font
493		return arg, err
494	}
495	switch name {
496	case "frac", "dfrac", "tfrac", "cfrac":
497		num, err := p.arg()
498		if err != nil {
499			return nil, err
500		}
501		den, err := p.arg()
502		if err != nil {
503			return nil, err
504		}
505		return el("mfrac", num, den), nil
506	case "binom", "dbinom", "tbinom":
507		top, err := p.arg()
508		if err != nil {
509			return nil, err
510		}
511		bottom, err := p.arg()
512		if err != nil {
513			return nil, err
514		}
515		frac := el("mfrac", top, bottom).attr("linethickness", "0")
516		return row([]*node{leaf("mo", "("), frac, leaf("mo", ")")}), nil
517	case "sqrt":
518		var index *node
519		if isChar(p.peek(), "[") {
520			p.next()
521			kids, err := p.list(func(t token) bool { return isChar(t, "]") })
522			if err != nil {
523				return nil, err
524			}
525			if err := p.expect(char, "]"); err != nil {
526				return nil, err
527			}
528			index = row(kids)
529		}
530		arg, err := p.arg()
531		if err != nil {
532			return nil, err
533		}
534		if index != nil {
535			return el("mroot", arg, index), nil
536		}
537		return el("msqrt", arg), nil
538	case "left":
539		open, err := p.delimiter()
540		if err != nil {
541			return nil, err
542		}
543		kids, err := p.list(func(t token) bool { return isCmd(t, "right") })
544		if err != nil {
545			return nil, err
546		}
547		if err := p.expect(cmd, "right"); err != nil {
548			return nil, err
549		}
550		cls, err := p.delimiter()
551		if err != nil {
552			return nil, err
553		}
554		var out []*node
555		if open != "" {
556			out = append(out, leaf("mo", open))
557		}
558		out = append(out, kids...)
559		if cls != "" {
560			out = append(out, leaf("mo", cls))
561		}
562		return row(out), nil
563	case "middle":
564		d, err := p.delimiter()
565		if err != nil {
566			return nil, err
567		}
568		return leaf("mo", d), nil
569	case "text", "textrm", "textnormal", "mbox":
570		s, err := p.rawGroup()
571		if err != nil {
572			return nil, err
573		}
574		return leaf("mtext", s), nil
575	case "operatorname", "operatorname*":
576		s, err := p.rawGroup()
577		if err != nil {
578			return nil, err
579		}
580		n := leaf("mi", s)
581		if utf8.RuneCountInString(s) == 1 {
582			n.attr("mathvariant", "normal")
583		}
584		n.limits, n.fn = name == "operatorname*", true
585		return n, nil
586	case "begin":
587		return p.environment()
588	case "displaystyle", "textstyle", "scriptstyle", "scriptscriptstyle", "limits", "nolimits":
589		return nil, nil
590	}
591	return nil, p.unexpected(t)
592}
593
594// rawGroup reads a braced argument as text, for \text and \operatorname.
595// Nested braces must balance; \{, \}, \$, \%, \&, \#, \_ and \\ stand for
596// the character.
597func (p *parser) rawGroup() (string, error) {
598	if err := p.expect(char, "{"); err != nil {
599		return "", err
600	}
601	var b strings.Builder
602	depth := 0
603	for p.pos < len(p.src) {
604		c := p.src[p.pos]
605		switch {
606		case c == '\\' && p.pos+1 < len(p.src) && strings.IndexByte(`{}$%&#_\`, p.src[p.pos+1]) >= 0:
607			b.WriteByte(p.src[p.pos+1])
608			p.pos += 2
609			continue
610		case c == '{':
611			depth++
612		case c == '}':
613			if depth == 0 {
614				p.pos++
615				return b.String(), nil
616			}
617			depth--
618		}
619		b.WriteByte(c)
620		p.pos++
621	}
622	return "", errors.New("texmath: unterminated group")
623}
624
625// delimiter reads what follows \left, \middle or \right; "." is none.
626func (p *parser) delimiter() (string, error) {
627	t := p.next()
628	if t.kind == char {
629		switch t.val {
630		case ".":
631			return "", nil
632		case "<":
633			return "⟨", nil
634		case ">":
635			return "⟩", nil
636		case "(", ")", "[", "]", "|", "/":
637			return t.val, nil
638		}
639	}
640	if t.kind == cmd {
641		if d, ok := delimiters[t.val]; ok {
642			return d, nil
643		}
644	}
645	return "", p.unexpected(t)
646}
647
648type env struct {
649	open, close string
650	table       bool
651}
652
653var environments = map[string]env{
654	"matrix":      {table: true},
655	"smallmatrix": {table: true},
656	"pmatrix":     {"(", ")", true},
657	"bmatrix":     {"[", "]", true},
658	"Bmatrix":     {"{", "}", true},
659	"vmatrix":     {"|", "|", true},
660	"Vmatrix":     {"‖", "‖", true},
661	"cases":       {"{", "", true},
662	"aligned":     {table: true},
663	"align":       {table: true},
664	"align*":      {table: true},
665	"gathered":    {table: true},
666	"gather":      {table: true},
667	"gather*":     {table: true},
668	"split":       {table: true},
669	"equation":    {},
670	"equation*":   {},
671	"displaymath": {},
672}
673
674func (p *parser) envName() (string, error) {
675	if err := p.expect(char, "{"); err != nil {
676		return "", err
677	}
678	end := strings.IndexByte(p.src[p.pos:], '}')
679	if end < 0 {
680		return "", errors.New("texmath: unterminated environment name")
681	}
682	name := p.src[p.pos : p.pos+end]
683	p.pos += end + 1
684	return name, nil
685}
686
687func (p *parser) environment() (*node, error) {
688	name, err := p.envName()
689	if err != nil {
690		return nil, err
691	}
692	e, ok := environments[name]
693	if !ok {
694		return nil, fmt.Errorf("texmath: unsupported environment %q", name)
695	}
696	var body *node
697	if e.table {
698		body, err = p.table()
699	} else {
700		var kids []*node
701		kids, err = p.list(func(t token) bool { return isCmd(t, "end") })
702		body = row(kids)
703	}
704	if err != nil {
705		return nil, err
706	}
707	if err := p.expect(cmd, "end"); err != nil {
708		return nil, err
709	}
710	if end, err := p.envName(); err != nil {
711		return nil, err
712	} else if end != name {
713		return nil, fmt.Errorf(`texmath: \begin{%s} ended by \end{%s}`, name, end)
714	}
715	if e.open == "" && e.close == "" {
716		return body, nil
717	}
718	out := []*node{}
719	if e.open != "" {
720		out = append(out, leaf("mo", e.open))
721	}
722	out = append(out, body)
723	if e.close != "" {
724		out = append(out, leaf("mo", e.close))
725	}
726	return row(out), nil
727}
728
729// table parses rows separated by \\ and cells separated by &, up to \end.
730func (p *parser) table() (*node, error) {
731	stop := func(t token) bool { return isChar(t, "&") || isCmd(t, "\\") || isCmd(t, "end") }
732	tbl := el("mtable")
733	cur := el("mtr")
734	for {
735		kids, err := p.list(stop)
736		if err != nil {
737			return nil, err
738		}
739		cur.kids = append(cur.kids, el("mtd", kids...))
740		t := p.peek()
741		switch {
742		case isChar(t, "&"):
743			p.next()
744		case isCmd(t, "\\"):
745			p.next()
746			tbl.kids = append(tbl.kids, cur)
747			cur = el("mtr")
748		case isCmd(t, "end"):
749			// A trailing \\ leaves one empty cell; it is not a row.
750			if len(cur.kids) > 1 || len(cur.kids[0].kids) > 0 {
751				tbl.kids = append(tbl.kids, cur)
752			}
753			return tbl, nil
754		default:
755			return nil, p.unexpected(t)
756		}
757	}
758}
759
760// styled maps letters and digits into the current font's Mathematical
761// Alphanumeric Symbols, which is how MathML Core spells \mathbb and the rest:
762// mathvariant is honoured only as "normal".
763func (p *parser) styled(s string) string {
764	if p.font == "" || p.font == "rm" {
765		return s
766	}
767	var b strings.Builder
768	for _, r := range s {
769		b.WriteRune(alphanumeric(p.font, r))
770	}
771	return b.String()
772}