Skip to content

color fenced divs by nesting depth - #18467

Merged
kevinushey merged 3 commits into
mainfrom
bugfix/nested-fenced-div-colors
Aug 7, 2026
Merged

kevinushey merged 3 commits into
mainfrom
bugfix/nested-fenced-div-colors

Conversation

@kevinushey

Copy link
Copy Markdown
Collaborator

Summary

The rainbow fenced div highlighting in the source editor assigned colors from a counter that only advanced on closing fences, so colors did not follow the document's nesting structure: nested divs shared their parent's color, and sibling divs at the same level received different colors.

This regressed in #14744, which replaced the original color stack (it abused the Ace tokenizer stack, breaking editor tools) with a simple counter that tracked the wrong thing.

Fences are now colored by nesting depth, mirroring the rainbow parentheses logic in rainbow_paren_highlight_rules.js: a nested div gets a different color than its parent, siblings at the same depth share a color, and opening/closing fences of the same div always match. This also matches Positron's behavior for nested fenced divs.

Testing

  • Added a Playwright test covering the nested fenced div example from the issue, asserting the fence color at every fence row.
  • Updated the existing sibling-callout test: two top-level divs now share a color (same depth) instead of cycling.
  • Full syntax-highlighting.test.ts suite passes locally (desktop-dev).

Fixes #18464.

The rainbow fenced div highlighting assigned colors from a counter
that only advanced on closing fences, so nested divs shared their
parent's color and unrelated fences drifted through the palette.
Color fences by nesting depth instead, mirroring the rainbow
parentheses logic: nested divs get new colors, siblings at the same
depth share one, and open/close pairs always match.

Addresses #18464
@kevinushey kevinushey added this to the 2026.08 (Yellow Yarrow) milestone Aug 6, 2026
@posit-snyk-bot

posit-snyk-bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

✅ Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
✅ Open Source Security 0 0 0 0 0 issues
✅ Licenses 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

@github-actions

github-actions Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

#################### 100% pass rate

Passed Failed Skipped Flaky
1986 0 377 4
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 2 0 8 0
✅ desktop-linux 491 0 90 1
✅ desktop-macos 496 0 86 1
✅ desktop-windows 497 0 90 1
✅ server-linux 478 0 95 1
✅ setup 22 0 8 0
View / download the full report

View report online -- opens in the browser, no download needed. Available for 14 days.

Download playwright-report.zip -- extract and open index.html

Includes screenshots, traces, and step-by-step details for every test. Expires in 15 days.


All platforms - commit 7129f1679937db6643b9a2e093764fc2dc1e0eb4 - Run #480

@gtritchie

Copy link
Copy Markdown
Member

Code review findings

Actionable items from an automated multi-agent review. The core change is correct: the open/close
color invariant holds algebraically at every depth, and unmatched fences, the depth-0 clamp,
nesting past 7 colors, and fences inside code chunks were all checked and behave sensibly.

Findings 1 and 2 were verified by running the real Ace BackgroundTokenizer and the real
highlight rules in Node against both main and this branch, so the divergences below are measured
rather than inferred — but neither has been confirmed on a live editor yet.

Important

  1. src/gwt/acesupport/acemode/markdown_highlight_rules.js:215-236 — editing a fence line leaves
    stale colors on every fence below it. BackgroundTokenizer.$tokenizeRow cascades invalidation
    to row + 1 only when the Ace state string changes
    (.../text/ace/ace-uncompressed.js:43098), and this rule's next is unconditionally
    "start" (:236), so a depth change can never trigger the cascade; $worker then skips every
    row that still has cached tokens. Measured on three sibling callouts with :::: {#outer} typed
    in at the top: row 1's opening fence recolors to depth 1 while its own closing fence at row 3
    stays at depth 0 — i.e. the "opening and closing fences always match" invariant in the PR body
    and NEWS.md is visibly broken on screen until the tab is reopened or the pref toggled.

    The mechanism is pre-existing and shared verbatim with rainbow_paren_highlight_rules.js:47-59,
    but this PR widens the trigger set: under main only closing fences moved the counter, so
    inserting an opening fence was stale-free (verified). Now every fence line moves it.

    A real fix means making context part of Ace's invalidation key, which is out of scope here and
    would fix rainbow parens too. Suggest either softening the "always match" wording or opening a
    follow-up, so this doesn't return as "Nested fenced divs are highlighted with incorrect fence colors in RStudio source editor #18464 isn't actually fixed."

  2. src/gwt/acesupport/acemode/markdown_highlight_rules.js:206 — the match regex requires column 0,
    so a closing fence indented by the 1-3 spaces Pandoc allows is tokenized as plain text and never
    decrements the depth. One invisible fence then shifts every color for the rest of the file. For
    ::: {#a} / x / ::: / ::: {#b} / y / :::, main colors both divs fenced_div_0
    (correct — they are siblings), while this branch colors #b and its closer fenced_div_1.
    That is the exact complaint in Nested fenced divs are highlighted with incorrect fence colors in RStudio source editor #18464, reintroduced for a Pandoc-legal document. The regex gap is
    pre-existing; the depth model is what turns it into visible mis-coloring. Relaxing to
    ^[ ]{0,3}[:]{3,} would cover the common case.

  3. src/gwt/acesupport/acemode/markdown_highlight_rules.js:219 — the Math.max(0, depth - 1) clamp
    is the only genuinely new branch in the diff and nothing exercises it; every fence in both tests
    is balanced, so depth never reaches 0 at a closing fence. Without the clamp a single stray
    ::: emits fenced_div_-1 (-1 % 7 === -1), a class with no CSS rule
    (themeStyles.css:150-156 defines only 0-6), leaving every fence below it unstyled. Fix: four
    lines of content — a leading bare :::, then a balanced div — asserting the div still gets
    fenced_div_0.

  4. e2e/rstudio/tests/panes/editor/syntax-highlighting.test.ts:139 — the finally restores
    rainbow_fenced_divs to false, but the schema default is true
    (user-prefs-schema.json:633), so every later test in the worker silently sees fences tokenized
    as keyword.operator. Fix: clearPref(page, 'rainbow_fenced_divs')
    (e2e/rstudio/utils/commands.ts:624). Same bug in the pre-existing twin at :90 — which is why
    the new test needs its explicit setPref(true) at :113 at all.

Suggestions

  1. src/gwt/acesupport/acemode/markdown_highlight_rules.js:221,224 — var color is declared twice
    in one function scope with the identical expression, and depth is reassigned so it means
    "depth before this line" on entry and "depth of the div being closed" after. Both collapse
    together:

    var depth = context.fences || 0;
    var close = /^[:]{3,}\s*$/.test(val);
    
    if (close)
       depth = Math.max(0, depth - 1);
    
    var color = depth % $numFencedDivsColors;
    context.fences = close ? depth : depth + 1;

    Style only — running the exact ant ext Closure config (simple / warning="default") over all
    64 acesupport sources on this branch produces zero warnings, so this is not a zero-warnings
    violation.

  2. e2e/rstudio/tests/panes/editor/syntax-highlighting.test.ts:133-136 — the loop asserts only
    tokens[0]?.type. Adding t.value would pin that the /^([:]{3,})(.*)$/ split still yields
    "::::::" for a 6-colon fence, and would make a row-index drift fail loudly instead of relying
    on the drifted row happening not to be a same-color fence. The companion fenced_div_text_N
    token is also unasserted at depth > 0.

  3. src/gwt/acesupport/acemode/markdown_highlight_rules.js:204 — // opening fenced div now labels
    a block whose closing-fence branch is the larger of the two and does its own depth bookkeeping.
    Someone grepping for where closing fences are handled will skip this block.

  4. e2e/rstudio/tests/panes/editor/syntax-highlighting.test.ts:121-130 — the eight row indices are
    hand-computed literals against a template literal ten lines above, and the comments are the only
    thing tying them together. Inserting one line into content invalidates all eight and the test
    could still pass by accident (rows 8/10/12 all expect color 2). Annotating which div each closer
    belongs to (// ::: (closes #1.1.1)) makes drift visible on review; deriving the rows from
    content.split('\n') removes the risk.

  5. Edge cases 2/3 have a cheaper home than E2E: src/gwt/test/highlight_test_sql.html and
    highlight_test_cpp.html already assert token types against a real Ace session with no rsession
    and no IDE, run headless via ant testpage (src/gwt/build.xml:597). Adding a markdown page
    means one new HTML file plus one string in the PAGES array at src/gwt/test/runner/runner.mjs:21.
    Stray-close, color wrap, setRainbowFencedDivs(false), and the edit-then-retokenize case in
    finding 1 all fit there in seconds rather than a full IDE launch.

  6. src/gwt/acesupport/acemode/markdown_highlight_rules.js:87 — exports.setNumFencedDivsColors
    has no callers anywhere in the repo (nor does its twin setNumParenColors at
    rainbow_paren_highlight_rules.js:31), so the palette size is fixed at 7. Pre-existing dead
    API; if it were ever wired to a value above 7, tokens like fenced_div_7 would render unstyled
    with no error.

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feedback posted

- simplify the fenced div onMatch depth bookkeeping and fix the stale
  'opening fenced div' comment
- restore rainbow_fenced_divs with clearPref() in the e2e tests so later
  tests see the schema default (true) again
- derive fence rows from the test content and assert full token
  type/value pairs in the nested fenced div e2e test
- add a standalone markdown highlight test page covering nesting depth,
  the unmatched-close clamp, color wrap past seven levels, indented
  (non-)fences, and rainbow-off
@kevinushey

Copy link
Copy Markdown
Collaborator Author

Thanks -- applied most of this in 6b5fb57.

1 (stale colors on edit): The mechanism is real, but it's already tracked and fixed: #18472 covers exactly this staleness, and PR #18473 (with rstudio/rstudio-ace#13) makes the per-row context part of the background tokenizer's invalidation key -- which fixes the same issue for rainbow parens too. Once that lands, the on-screen invariant holds; I'd rather merge that alongside this PR than soften the NEWS wording.

2 (indented fences): Checked against pandoc (3.10.1, plus quarto's bundled pandoc): the markdown reader used for .md/.Rmd/.qmd does not accept indented fences -- ::: parses as a plain paragraph, #a stays open (closing implicitly at EOF), and #b in your example is a nested div per pandoc:

[ Div ("a",...) [ Para [Str "x"], Para [Str ":::"], Div ("b",...) [...] ] ]

So coloring #b at depth 1 matches the actual parse, and main's sibling coloring was the incorrect one. Relaxing to ^[ ]{0,3} would make the highlighter decrement on a line pandoc treats as text -- the same invisible-fence color shift, in the other direction. (Only commonmark_x accepts indented closes, and that's not the reader these file types use.) Added a test-page case pinning the column-0 behavior with a comment explaining why.

3, 9: Added src/gwt/test/highlight_test_markdown.html (runs under ant testpage) covering nesting/siblings, the stray-close clamp, color wrap past seven levels, indented non-fences, and rainbow-off. Skipped the edit-then-retokenize case there since it depends on #18473, which carries its own e2e test.

4: Both tests now clearPref() instead of restoring false (schema default is true) -- including the pre-existing callout test.

5-8: Applied: collapsed the depth/color bookkeeping, fixed the stale comment, derived the fence rows from the test content, and the e2e loop now asserts full token type/value pairs.

10: Left as-is -- pre-existing dead API shared with setNumParenColors; happy to sweep both in a separate cleanup if wanted.

@kevinushey
kevinushey merged commit b00254b into main Aug 7, 2026
7 of 12 checks passed
@kevinushey
kevinushey deleted the bugfix/nested-fenced-div-colors branch August 7, 2026 21:18
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.

Nested fenced divs are highlighted with incorrect fence colors in RStudio source editor

3 participants