d2latex: fix latex backslashes doubling

This commit is contained in:
Alexander Wang 2025-02-03 17:30:53 -07:00
parent eb1f0cc410
commit bf2754edfc
No known key found for this signature in database
GPG key ID: BE3937D0D52D8927
6 changed files with 562 additions and 554 deletions

View file

@ -1480,12 +1480,6 @@ func (p *parser) parseBlockString() *d2ast.BlockString {
}
if r != endHint {
if (bs.Tag == "latex" || bs.Tag == "tex") && r == '\\' {
// For LaTeX, where single backslash is common, we escape it so that users don't have to write double the backslashes
sb.WriteRune('\\')
sb.WriteRune('\\')
continue
}
sb.WriteRune(r)
continue
}

View file

@ -6,6 +6,7 @@ import (
"math"
"regexp"
"strconv"
"strings"
"oss.terrastruct.com/d2/lib/jsrunner"
"oss.terrastruct.com/util-go/xdefer"
@ -28,6 +29,7 @@ var svgRe = regexp.MustCompile(`<svg[^>]+width="([0-9\.]+)ex" height="([0-9\.]+)
func Render(s string) (_ string, err error) {
defer xdefer.Errorf(&err, "latex failed to parse")
s = doubleBackslashes(s)
runner := jsrunner.NewJSRunner()
if _, err := runner.RunString(polyfillsJS); err != nil {
@ -82,3 +84,15 @@ func Measure(s string) (width, height int, err error) {
return int(math.Ceil(wf * float64(pxPerEx))), int(math.Ceil(hf * float64(pxPerEx))), nil
}
func doubleBackslashes(s string) string {
var result strings.Builder
for i := 0; i < len(s); i++ {
if s[i] == '\\' {
result.WriteString("\\\\")
} else {
result.WriteByte(s[i])
}
}
return result.String()
}

View file

@ -81,7 +81,7 @@
"fields": null,
"methods": null,
"columns": null,
"label": "\\\\begin{equation} \\\\label{eq1}\n\\\\begin{split}\nA & = \\\\frac{\\\\\\\\pi r^2}{2} \\\\\\\\\n & = \\\\frac{1}{2} \\\\pi r^2\n\\\\end{split}\n\\\\end{equation}",
"label": "\\begin{equation} \\label{eq1}\n\\begin{split}\nA & = \\frac{\\\\pi r^2}{2} \\\\\n & = \\frac{1}{2} \\pi r^2\n\\end{split}\n\\end{equation}",
"fontSize": 16,
"fontFamily": "DEFAULT",
"language": "latex",

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 32 KiB

View file

@ -81,7 +81,7 @@
"fields": null,
"methods": null,
"columns": null,
"label": "\\\\begin{equation} \\\\label{eq1}\n\\\\begin{split}\nA & = \\\\frac{\\\\\\\\pi r^2}{2} \\\\\\\\\n & = \\\\frac{1}{2} \\\\pi r^2\n\\\\end{split}\n\\\\end{equation}",
"label": "\\begin{equation} \\label{eq1}\n\\begin{split}\nA & = \\frac{\\\\pi r^2}{2} \\\\\n & = \\frac{1}{2} \\pi r^2\n\\end{split}\n\\end{equation}",
"fontSize": 16,
"fontFamily": "DEFAULT",
"language": "latex",

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 33 KiB