Skip to content

fix C++ chunk indentation in R Markdown documents - #18470

Merged
kevinushey merged 4 commits into
mainfrom
bugfix/rmd-cpp-chunk-indent
Aug 7, 2026
Merged

kevinushey merged 4 commits into
mainfrom
bugfix/rmd-cpp-chunk-indent

Conversation

@kevinushey

@kevinushey kevinushey commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Pressing Enter inside a C++ (e.g. Rcpp) chunk of an R Markdown or Quarto document raised an uncaught exception and skipped auto-indent whenever another completed chunk appeared earlier in the document:

TypeError: Cannot read properties of undefined (reading 'width')

TokenUtils.$tokenizeUpToRow (used by CppCodeModel for C++ chunk indentation) called getLineTokens(line, state, row) without threading a tokenizer context, so every onMatch handler received a fresh empty object; the chunk-end highlight rule then dereferenced the missing chunk information unguarded. Broken since eafc5fa (September 2024), which introduced context-based chunk tracking.

Changes

  • token_utils.js: thread a per-row context through $tokenizeUpToRow, mirroring RCodeModel (including the $invalidateRow / $insertNewRows / $removeRows bookkeeping).
  • utils.js, markdown_highlight_rules.js: guard the chunk-end rules so that a missing chunk context degrades to "this fence closes the chunk" (the pre-context behavior) instead of crashing; same for the quarto #| exit rules and the YAML multiline indent checks. The fallbacks derive their target from the current state name, so embedded modes (e.g. r-quarto-yaml-*) exit to the enclosing mode rather than escaping to top-level start (a dynamically assigned this.next is not prefix-rewritten by Ace's addRules), the markdown fence guard recovers the fence width from the github-block-<N> state name, and each guard warns once on the console when it fires so context-threading regressions stay observable.
  • Tokenizer.java: thread a single tokenizer context through doTokenize (used by Reformat Code), fixing a pre-existing TypeError raised when reformatting R code containing Quarto #| comment lines.
  • Same-class hardening for the shared-context hazards found in the same audit: the chunk / quarto / YAML multiline openers now store fresh context objects instead of mutating an inherited one (the per-row context snapshots kept by TokenUtils.$tokenizeUpToRow and BackgroundTokenizer.$tokenizeRow are shallow copies, so in-place mutation retroactively corrupts the snapshots saved for earlier rows), and the Sweave \Sexpr{} brace count is now stored as primitive context fields so per-row snapshots capture it.

Testing

  • New Playwright test: Enter inside an {Rcpp} chunk below a completed R chunk indents the new line (asserting the exact indent and the r-cpp- tokenizer state); the e2e fixture fails any test raising a client exception, so this also guards the TypeError directly. The test fails without the fix (exception raised, no indent).
  • New src/gwt/test/context_test_rmd.html testpage (run by ant testpage) pins the chunk / quarto #| / YAML multiline / \Sexpr context fixes at the tokenizer level, including the missing-context fallbacks; it fails against the pre-fix code.

Fixes #18468.

TokenUtils tokenized rows without threading a tokenizer context, so
onMatch handlers received a fresh empty object on every call; the
chunk-end highlight rule then dereferenced the missing chunk info and
threw, so pressing Enter in a C++ chunk raised an uncaught TypeError
and skipped auto-indent whenever a completed chunk appeared earlier
in the document.

Thread a per-row context through TokenUtils (mirroring RCodeModel),
and guard the context reads in the chunk, quarto, YAML multiline, and
Sexpr rules so context-less tokenization degrades gracefully instead
of crashing. Also make the chunk/quarto/yaml openers store fresh
context objects (mutating an inherited object corrupts the contexts
saved for previously-tokenized rows), and store the Sexpr brace count
as primitive context fields so per-row context snapshots capture it.

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

posit-snyk-bot commented Aug 7, 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
1980 0 386 5
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 2 0 8 0
✅ desktop-linux 492 0 90 1
✅ desktop-macos 487 0 95 2
✅ desktop-windows 498 0 90 1
✅ server-linux 479 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 b045c65ad34cfe88dc983fc1682741274b68b1f4 - Run #484

@gtritchie

Copy link
Copy Markdown
Member

Code review findings

Actionable items from an automated multi-agent review. The context-threading fix in token_utils.js verified as correct ($contexts/$endStates stay in sync across $invalidateRow/$insertNewRows/$removeRows, and the shallow-copy premise is confirmed at ace-uncompressed.js:43095). The findings below are about the guards layered on top.

Important

  1. src/gwt/acesupport/acemode/utils.js:341, :353, :376, src/gwt/acesupport/acemode/yaml_highlight_rules.js:356 — the hardcoded "start" fallbacks lose the embed prefix. Ace's addRules prefixes only statically declared rule.next; a this.next assigned inside onMatch is not rewritten. The YAML rules are embedded under quarto-yaml- (utils.js:306), and in Rmd the R rules are embedded under r-, so on the fallback path tokenization exits to top-level Markdown start instead of the enclosing chunk state — the remainder of the chunk highlights as prose. Fix: derive the target from state the way yaml_highlight_rules.js:201 already does (state.replace(/start$/, "multiline-string") has an inverse), or thread the closure's endState as utils.js:135 does.

  2. src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/ace/Tokenizer.java:47, :66 — this caller makes the finding-1 fallbacks reachable today, and the guards convert a live crash into silent mis-tokenization rather than fixing it. doTokenize loops getLineTokens(splat[i], state) carrying state across lines but passing no context, so each line gets a fresh {}; r_highlight_rules.js:592 embeds the quarto rules unconditionally, so a Reformat Code / Reformat Document selection containing #| echo: false followed by a non-comment line hits context.quarto undefined (utils.js:341). Pre-PR that is a TypeError inside the reformatter; post-PR it silently tokenizes wrong. Fix: hoist a var context = {}; outside the loop and pass it as the 4th argument, matching the three loops already fixed (token_utils.js:103, r_code_model.js:2176, ace-uncompressed.js:43093).

  3. src/gwt/acesupport/acemode/utils.js:119, markdown_highlight_rules.js:483, yaml_highlight_rules.js:355, sweave_highlight_rules.js:92 — no guard logs or signals when it fires. Before this PR the uncaught TypeError was the only detector for context-threading regressions in the highlighter (it is how pressing Enter in an Rcpp chunk of an R Markdown document throws and skips auto-indent #18468 surfaced); after it, the same desync degrades to wrong highlighting with no stack trace and no reproducible trigger. Degrading rather than throwing is right for a highlighter, but it needn't be silent. Fix: call this.reportError(...) (ace-uncompressed.js:987, used at :2461 for the analogous "state doesn't exist" case) or a once-per-session console.warn before falling back.

  4. Test coverage — three of the five behavioral fixes are unpinned, and the PR description's regression-check claim does not hold. e2e/rstudio/tests/panes/editor/sweave.test.ts contains no \Sexpr at all, and syntax-highlighting.test.ts has no multiline-YAML case, so neither exercises the touched rules. The uncovered fixes are the ones where the shared-object mutation was real rather than defensive: context.yaml and context.quarto are never deleted (the only delete context.* calls are markdown_highlight_rules.js:499, utils.js:136, sweave_highlight_rules.js:95-96), so a second YAML/quarto block reused and overwrote the first block's object, corrupting the saved contexts for every row of block 1. Suggested cheap home: src/gwt/test/autoindent_test_cpp.html already loads token_utils.js, utils.js, and yaml_highlight_rules.js, drives CppCodeModel.getNextLineIndent() over <pre data-expected="N"> fixtures, and its runner (src/gwt/test/runner/runner.mjs, ant testpage) fails the build on any uncaught page error — i.e. exactly this bug class, in seconds and with no rsession. It would also pin the indent width, which the e2e test does not.

Suggestions

  1. src/gwt/acesupport/acemode/markdown_highlight_rules.js:459-462, src/gwt/acesupport/acemode/utils.js:155-158 — the comment claims mutating an inherited object "would corrupt the contexts saved for previously-tokenized rows", but at these two sites that cannot happen: both openers early-return three lines above when chunk.state != null, and chunk.state is set whenever a chunk object is created, so an inherited context.chunk never reaches the mutation. These two hunks are defensive consistency, not bug fixes. The identical rationale is accurate at yaml_highlight_rules.js:194-197 and utils.js:317-318, where the old code had no such guard. Fix: soften the wording at the two chunk-header sites so a reader doesn't conclude the corruption was observed there.

  2. src/gwt/acesupport/acemode/markdown_highlight_rules.js:461, utils.js:157, yaml_highlight_rules.js:195, sweave_highlight_rules.js:60 — "the tokenizer's per-row contexts" points at the wrong component. Tokenizer.prototype.getLineTokens does no copying and stores nothing; it forwards context || {} to onMatch (ace-uncompressed.js:2450). The per-row shallow copies live in BackgroundTokenizer.$tokenizeRow (ace-uncompressed.js:43095) and TokenUtils.$tokenizeUpToRow (token_utils.js:101). Since the bug was that one of those two wasn't maintaining contexts, the comment sends the next reader to the wrong file. Fix: name the two functions.

  3. e2e/rstudio/tests/panes/editor/cpp_chunk_indent.test.ts:53 — toMatch(/^\s+$/) passes on any non-zero indent, so a regression that indents 1 space, 8 spaces, or a tab still passes. The brace is at column 0 and the C++ indent is deterministic. Fix: assert the exact indent, and consider also asserting getState(9) is an r-cpp-* state to pin the mechanism rather than only the symptom.

  4. e2e/rstudio/tests/panes/editor/cpp_chunk_indent.test.ts:44 — new AceEditor(page, 'int add') contradicts the documented convention. pages/ace_editor.page.ts:36-38 and .claude/skills/rstudio-create-playwright-tests/SKILL.md:181-184 prefer the empty marker, which resolves the active editor through the bridge; the non-empty marker does a .ace_editor DOM walk that can land on stale editors from a previous suite's tab close (test(e2e): expose active ace editor via automation bridge #17775 / test(e2e): use activeEditor bridge in autocomplete actions #17784). This suite opens one document, so new AceEditor(page, '') removes a known flake source.

  5. e2e/rstudio/tests/panes/editor/cpp_chunk_indent.test.ts:13 — "The rstudio fixture fails any test that raises a client exception" is the default but not unconditional: e2e/rstudio/fixtures/rstudio.fixture.ts:325-348 downgrades to console.warn when PW_IGNORE_CLIENT_EXCEPTIONS=1. Fix: note the env-var escape hatch so a future reader doesn't assume the regression can never silently pass.

  6. e2e/rstudio/tests/panes/editor/cpp_chunk_indent.test.ts:48,53 — the two 10s refer to different lines and the comments don't say so: gotoLine is 1-based (ace_editor.page.ts:107-111) and getLine is 0-based (:134), so gotoLine(10, …) is int add(int x) { while getLine(10) is the newly inserted line below it. The test is correct; the next person to add or remove a fixture line will likely get it wrong. Fix: make the index base explicit in the second comment.

  7. src/gwt/acesupport/acemode/markdown_highlight_rules.js:483-486 — the chunk == null path discards recoverable information. The state name is github-block-N where N is the opening fence width (set at :468, states registered :509-511), so the width check could be preserved via parseInt(state.slice("github-block-".length), 10) instead of unconditionally closing the fence. (The "start" return target is genuinely top-level Markdown here, so unlike finding 1 it is correct.)

  8. src/gwt/acesupport/acemode/token_utils.js:116-119 — the assumeGood short-circuit compares only the end-state string, so downstream $contexts can go stale when a row's end state is unchanged but its context is not. Concretely, utils.js:164 encodes the chunk state in the state name but keeps the fence width only in context.chunk.width, so editing a fence from 4 backticks to 3 leaves the end state as r-start, rows below are skipped, and they retain width: 4. Pre-existing (identical logic in r_code_model.js:2186-2190 and Ace's BackgroundTokenizer) and a strict improvement over the previous TypeError — flagging so it is a known limitation rather than a surprise, since this PR is what makes $contexts load-bearing in TokenUtils.

  9. src/gwt/acesupport/acemode/r_code_model.js:2176 — getLineTokens(line, state, row, context || {}): context is Object.assign({}, ...) two lines above and can never be falsy, so the || {} is dead and misleadingly implies the context may be absent. token_utils.js:103 correctly omits it; worth making the two consistent.

@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

- derive the missing-context fallback states from the current state name,
  so guards no longer escape embed prefixes (e.g. 'r-quarto-yaml-start'
  now falls back to 'r-start' rather than top-level 'start'); the markdown
  chunk-end guard also recovers the fence width from 'github-block-<N>'
- thread a tokenizer context through Tokenizer.java's doTokenize, fixing
  a TypeError raised when reformatting R code with quarto '#|' lines
- warn (once) on the console when a missing-context guard fires, so
  context-threading regressions stay observable
- add src/gwt/test/context_test_rmd.html covering the C++ chunk indent,
  quarto '#|' and yaml multiline snapshot corruption, \Sexpr brace
  counts, and the new fallbacks; fails against the pre-fix tokenizer
- e2e: resolve the active editor via the empty marker, assert the exact
  indent and the r-cpp tokenizer state, and clarify index-base comments
- clarify which components hold the per-row context snapshots, and soften
  the fresh-object comments where inherited mutation was unreachable
@kevinushey

Copy link
Copy Markdown
Collaborator Author

All 13 items verified and addressed in 8748e17. One deviation on item 3: reportError re-throws asynchronously (setTimeout(() => { throw e; })), which would turn the degraded path back into an uncaught error, so the guards use a once-per-key console.warn instead. Item 12 is documented as a known limitation next to the resume check in token_utils.js rather than changed, since the same resume logic is shared with RCodeModel and Ace's BackgroundTokenizer. The new src/gwt/test/context_test_rmd.html testpage pins the five behavioral fixes (verified red against the pre-fix tokenizer), and the e2e test now asserts the exact indent and the r-cpp- state via the empty-marker editor.

@kevinushey
kevinushey merged commit 7ed4e56 into main Aug 7, 2026
@kevinushey
kevinushey deleted the bugfix/rmd-cpp-chunk-indent branch August 7, 2026 21:21
kevinushey added a commit that referenced this pull request Aug 7, 2026
TokenUtils.$tokenizeUpToRow (factored out on main in #18470) had the
same two defects this branch fixed in RCodeModel: a shallow context
copy, and an assumeGood resume keyed only on the end state. Adopt
cloneContext / equalContexts there too, and drop the now-stale comment
describing the limitation as shared with RCodeModel and the
BackgroundTokenizer.
kevinushey added a commit that referenced this pull request Aug 10, 2026
* invalidate following rows when tokenizer context changes

The Ace background tokenizer re-tokenizes the row following an edited
row only when the edited row's end state changes. Tokenizer contexts
(carrying e.g. rainbow paren / fenced div nesting depth, YAML
multiline-string indents, and chunk fence widths) also flow into
following rows, but context changes did not propagate invalidation,
so an edit that changed only context data left stale highlighting on
every row below. Modes with a code-model scope tree masked this by
force-retokenizing the document after every edit; plain Markdown and
YAML documents showed the stale highlighting indefinitely.

Updates the ace builds with rstudio/rstudio-ace#13, which compares
each row's newly-computed context against the stored one and
invalidates the following row when they differ. The rebuilt artifact
also drops a stray (hand-patched) comment left from the #13605
investigation.

Addresses #18472

* use structural context comparison instead of JSON.stringify

Updates the ace builds with the second commit of rstudio/rstudio-ace#13:
contexts are now deep-copied at the row boundary, so each row's stored
context is an independent snapshot that in-place mutation cannot
corrupt, and compared with a structural equality helper that is
key-order independent, never throws, and depth-caps recursion.

* use structuredClone for context snapshots

Updates the ace builds with the third commit of rstudio/rstudio-ace#13:
contexts are snapshotted with the platform deep clone, supporting nested
objects and arrays as context values.

* harden tokenizer context helpers against non-plain data

Updates the ace builds with the latest rstudio/rstudio-ace#13: contexts
holding a Date, Map, Set, RegExp, or class instance now compare unequal
(Object.keys sees no content on them, so the structural comparison would
have reported any two as equal -- a silently missed invalidation), and
cloneContext skips the structuredClone for missing and empty contexts,
the common case for modes that never touch their context.

* add markdown fenced-div regression test; strengthen yaml test

Review feedback: the rainbow fenced div symptom from #18472 was untested
(and the cleanup list already claimed a syntax_highlight.md file), the
yaml test's final assertion checked only the first token's type, its
off-screen premise was implicit, and the target-editor lookup went
through the marker DOM walk.

The new markdown test inserts a closing fence at the top of a tall plain
.md document and asserts an off-screen block's tokens cycle to the next
rainbow color -- a positive assertion, where the yaml test's is an
absence. Both context tests now pin exact token type/value pairs, assert
the target row sits below the last rendered row before editing (the
guard the tests' validity rests on), resolve the active editor directly,
and give the initial tokenization poll the same 15s budget as the
post-edit one. Both fail against the previous ace build and pass with
this one.

Addresses #18472.

* adopt context helpers in RCodeModel's token cache

Review feedback, folded in from the proposed follow-up:
RCodeModel.$tokenizeUpToRow kept both halves of the bug fixed for ace's
BackgroundTokenizer -- the shallow Object.assign copy let highlight
rules mutate the previous row's stored context through shared nested
objects, and the assumeGood short-circuit keyed only on the end state,
so a context-only change stopped invalidation and following rows kept
stale cached tokens (feeding indentation, folding, and the scope tree).
Use the cloneContext / equalContexts helpers exported from
ace/background_tokenizer, so both incremental caches share the same
snapshot and comparison semantics.

Addresses #18472.

* adopt context helpers in TokenUtils' token cache

TokenUtils.$tokenizeUpToRow (factored out on main in #18470) had the
same two defects this branch fixed in RCodeModel: a shallow context
copy, and an assumeGood resume keyed only on the end state. Adopt
cloneContext / equalContexts there too, and drop the now-stale comment
describing the limitation as shared with RCodeModel and the
BackgroundTokenizer.
gtritchie added a commit that referenced this pull request Aug 10, 2026
* Resolve e2e daily builds per branch, not via /rstudio/latest

The e2e workflows installed the build named by
dailies.rstudio.com/rstudio/latest/index.json while running the tests from
the checked-out branch. Those are two different branches whenever the alias
lags a rollover, and its index.json does lag: after the 2026.08 branch cut
the /rstudio/latest/ page served Autumn Hawkbit (2026.09) while
/rstudio/latest/index.json still named a Yellow Yarrow (2026.08) build. CI
reads the JSON, so the scheduled rotation installed a 2026.08 binary and ran
main's tests against it. Every test covering behavior added after the cut
failed on every platform, with nothing wrong in either the test or the
product -- #18454 and #18470 both landed that way.

Resolve the manifest from version/RELEASE instead. The new
os-resolve-daily-manifest action turns it into the "flower" path segment the
same way docker/jenkins/publish-build.sh does when it writes the manifest, so
the reader and the writer stay in step, and a manifest named after its own
branch cannot be mis-pointed by an alias. It computes a URL and makes no
network request, so it is safe in the jobs that end up using an override URL
instead.

A missing platform key now fails with the branch and key named, and says a
source build is the way to test a branch with no daily. Autumn Hawkbit has no
Windows build yet, so the Windows engines take that path until one is
published; installing a 2026.08 .exe was never a valid substitute.

Addresses #18498

* Trigger PR e2e on resolver and version/RELEASE changes

The pull_request paths filter lists every composite action these workflows
use, but the new os-resolve-daily-manifest was missing, so a PR touching only
the resolver would not run the workflow that exercises it.

version/RELEASE joins it for the same reason one step further out: it selects
which branch's daily each platform resolves, so a change there changes the
binary under test. A flower with no daily yet falls through decide() to a
source build, so such a PR proves the transition works instead of leaving it
to the next cron rotation.

Addresses #18498
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.

pressing Enter in an Rcpp chunk of an R Markdown document throws and skips auto-indent

3 participants