Skip to content

mac: nested math environments keep their highlighting - #216

Merged
GoKubar merged 1 commit into
mainfrom
agent/claude/mac-syntax-nested-math
Sep 13, 2026
Merged

GoKubar merged 1 commit into
mainfrom
agent/claude/mac-syntax-nested-math

Conversation

@GoKubar

@GoKubar GoKubar commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

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.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, with no check that it matched the one that opened:

} else if mode == .mathEnvironment, SyntaxHighlighter.mathEnvironments.contains(env) {
    mode = .text
}

Math environments genuinely nest — cases in align (piecewise functions), split in equation (numbered multi-line equations), array in either — and in every one of those the inner \end dropped the lexer into text mode. Everything up to the real outer \end was then lexed as text.

Repro, run on the Mac against pristine 6c738349

\begin{align}
f &= \begin{cases} 1 \end{cases} \\
g &= \alpha + 2
\end{align}

From the failing run's own dump at base:

token expected actual at base
\alpha .mathCommand (teal) .command (text-mode purple)
\\ .mathCommand .command
g, 2 .math / .number not coloured at all

That 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 \begin inside math nests; 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, 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:

  • paste / programmatic replacement — re-lexes correctly; the hook is NSTextStorage.didProcessEditingNotification, not didChangeText, so textStorage.replaceCharacters and tv.string = … both land, and a whole-buffer rebind additionally forces reset()
  • context-changing edits ($, %, \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 lex
  • large files — no size cap or bail-out exists anywhere; testKeystrokeRelexOn560KBDocument passes
  • scrolling — the paint window is extended from boundsDidChangeNotification
  • comments containing backslashes, \%, \$, \\ at end of line, $$ vs $, \[/\(, nested braces, command name followed by a non-letter — all correct

Two real limits remain, not fixed here (say the word if either is worth a follow-up):

  1. a full reset on 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
  2. an environment split across an \input boundary is lexed wrong in both files, because each open document gets its own highlighter with no project-wide 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 must converge on the depth as well as the mode.

The neighbouring testMathEnvironmentEndsOnlyAtItsEnd is 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.

tests skipped failures
base 6c738349 941 134 3
this branch 942 134 3

swift build clean. The 3 failures are identical at base and unrelated: testBundledInventoryMatchesTheCompiler (bundled supported-latex.json drifted from the compiler's) and two PanelAccessibilityTests switch counts from preference toggles other lanes landed today.

Completion/IntelliSense is #215, kept separate.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu

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
@GoKubar
GoKubar marked this pull request as ready for review September 13, 2026 23:07
@GoKubar
GoKubar merged commit cf64d7b into main Sep 13, 2026
19 of 20 checks passed
@GoKubar
GoKubar deleted the agent/claude/mac-syntax-nested-math branch September 16, 2026 04:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant