Repository navigation
mac: nested math environments keep their highlighting - #216
Merged
Merged
Conversation
The owner reported "some bugs with syntax highlighting not always working".
This is one, and it is a lexing bug rather than an invalidation bug — the
distinction matters, because the incremental machinery around it is sound.
`Mode.mathEnvironment` was a flat flag, unlike `Mode.verbatim(String)`,
which carries its environment name. So `\end{…}` left math mode whenever
the name was *any* recognised math environment, without checking it matched
the one that opened. Math environments genuinely nest — `cases` inside
`align` for a piecewise function, `split` inside `equation` for a numbered
multi-line equation, `array` inside either — and in all of those the inner
`\end` dropped the lexer back into text mode. Everything from there to the
real outer `\end` was then lexed as text.
Reproduced on the Mac against pristine 6c73834, from the run's own dump:
\begin{align}
f &= \begin{cases} 1 \end{cases} \\
g &= \alpha + 2
\end{align}
gives `("\alpha", .command)` — the purple text-mode command colour — where
it must be `.mathCommand`, and `\\` likewise; `g` and `2` lose their math
colouring entirely. That is exactly "sometimes works, sometimes doesn't":
correct in most documents, silently wrong in a pattern any AMS-LaTeX author
hits weekly.
The mode now counts depth (`mathEnvironment(depth:)`): a math `\begin`
inside math nests, and only the outermost `\end` leaves. Verbatim and
comment bodies are still never entered. Depth is one Int per line in the
existing `modes` table, so nothing grows.
Everything else checked and NOT reproduced, so it is named rather than
guessed at: paste and programmatic replacement re-lex correctly (the hook
is `NSTextStorage.didProcessEditingNotification`, not `didChangeText`);
context-changing edits (`$`, `%`, `\begin{verbatim}`, deleting an `\end`)
re-lex forward until the line mode converges, to end of document if it
never does; there is no size cap anywhere, and the 560 KB keystroke test
passes; scroll extends the paint window; comments containing backslashes,
`\%`, `\$`, `\\` at end of line, `$$` vs `$`, `\[`/`\(` and nested braces
are all handled. Two real limits remain and are not fixed here: a full
`reset` on a whole-buffer rebind is O(document) on the main thread, and an
environment split across an `\input` boundary is lexed wrong in both files
because each open document has its own highlighter with no project model.
Tests: `testNestedMathEnvironmentsStayInMathUntilTheOutermostEnd` (two and
three levels deep, the depth unwinding one `\end` at a time, and a math
environment inside verbatim still not being entered) — it fails at the base
with 7 assertions, which is the repro. `\begin{cases}`/`\end{cases}` join
the fuzz atoms of `testRandomEditsMatchFullLex`, so the incremental lexer
has to converge on the depth as well as the mode. The neighbouring
`testMathEnvironmentEndsOnlyAtItsEnd` is documented as unable to see this:
it puts no math between the inner and outer `\end`.
Suite on this Mac: 942 tests, 134 skipped, 3 failures, all three present at
the 6c73834 base and unrelated (supported-latex.json drift, two
preference-panel switch counts).
Implementation-Agent: Claude Opus 5 (mac-syntax lane, linux-primary)
Commit-Executor: Claude Opus 5 via direct agent Git (Cursor usage limit)
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
This was referenced Sep 13, 2026
GoKubar
marked this pull request as ready for review
September 13, 2026 23:07
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Owner feedback on v0.1.2: "there are also some bugs with syntax highlighting not always working."
That was vague, so this is an investigation with one proven fix, and an explicit list of what I checked and could not reproduce.
The bug — lexing, not invalidation
That distinction matters: the incremental machinery around the lexer is sound and well fuzzed. The lexer's state machine is what was wrong.
Mode.mathEnvironmentwas a flat flag — unlikeMode.verbatim(String), which carries its environment name. So\end{…}left math mode whenever the name was any recognised math environment, with no check that it matched the one that opened:Math environments genuinely nest —
casesinalign(piecewise functions),splitinequation(numbered multi-line equations),arrayin either — and in every one of those the inner\enddropped the lexer into text mode. Everything up to the real outer\endwas then lexed as text.Repro, run on the Mac against pristine
6c738349From the failing run's own dump at base:
\alpha.mathCommand(teal).command(text-mode purple)\\.mathCommand.commandg,2.math/.numberThat is exactly "sometimes works, sometimes doesn't": right in most documents, silently wrong in a pattern any AMS-LaTeX author hits weekly.
The fix
mathEnvironment(depth:). A math\begininside math nests; only the outermost\endleaves. Verbatim and comment bodies are still never entered. Depth is oneIntper line in the existingmodestable, so nothing grows, and the incremental lexer's convergence check now has to agree on depth too — which is more correct, since inserting a\begin{cases}really does change every line after it.Checked and NOT reproduced
Named rather than guessed at, since the report was vague:
NSTextStorage.didProcessEditingNotification, notdidChangeText, sotextStorage.replaceCharactersandtv.string = …both land, and a whole-buffer rebind additionally forcesreset()$,%,\begin{verbatim}, deleting an\end) —edit()re-lexes forward until a line's computed mode converges with the stored one, to end of document if it never does; 400-iteration fuzz already pins incremental == full lextestKeystrokeRelexOn560KBDocumentpassesboundsDidChangeNotification\%,\$,\\at end of line,$$vs$,\[/\(, nested braces, command name followed by a non-letter — all correctTwo real limits remain, not fixed here (say the word if either is worth a follow-up):
reseton a whole-buffer rebind is O(document) synchronously on the main thread — a stall on a very large file, which can read as "highlighting stopped", though it always finishes and paints correctly\inputboundary is lexed wrong in both files, because each open document gets its own highlighter with no project-wide modelTests
testNestedMathEnvironmentsStayInMathUntilTheOutermostEnd— two and three levels deep, the depth unwinding one\endat a time, and a math environment insideverbatimstill not being entered. It fails at the base with 7 assertions, which is the repro.\begin{cases}/\end{cases}join the fuzz atoms oftestRandomEditsMatchFullLex, so the incremental lexer must converge on the depth as well as the mode.The neighbouring
testMathEnvironmentEndsOnlyAtItsEndis now documented as unable to see this: it puts no math between the inner and the outer\end, so the wrong mode has nothing to colour wrongly. Left in place, comment added.6c738349swift buildclean. The 3 failures are identical at base and unrelated:testBundledInventoryMatchesTheCompiler(bundledsupported-latex.jsondrifted from the compiler's) and twoPanelAccessibilityTestsswitch counts from preference toggles other lanes landed today.Completion/IntelliSense is #215, kept separate.
🤖 Generated with Claude Code
https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu