Skip to content

add support for split editors (two views of one document) - #18460

Merged
kevinushey merged 16 commits into
mainfrom
feature/split-editor
Aug 10, 2026
Merged

kevinushey merged 16 commits into
mainfrom
feature/split-editor

Conversation

@kevinushey

@kevinushey kevinushey commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator

Adds split editor support to the source pane: an editor tab can show a second view of its document, either side by side ("Split Editor Right") or stacked ("Split Editor Down"), so different parts of a file can be viewed and edited at the same time.

Behavior

  • The two views share the document and undo history; selection, cursor, scroll position, and code folds are per-view. This follows Ace's own Split implementation: the secondary view gets a cloned EditSession over the shared Document and UndoManager (sharing a single session is not possible, as Ace sessions own the selection and scroll state).
  • New commands: splitEditorRight, splitEditorDown, removeEditorSplit, toggleEditorSplit (re-enables the most recent orientation), and focusOtherEditorSplit for keyboard navigation between the views. All are user-bindable, appear under View > Split Editor, and are also reachable from a new editor toolbar menu button. When a source editor already holds focus and the document is split, activateSource (Ctrl+1) also toggles focus between the two views.
  • The split state is stored in a document property (editorSplit), so it is restored per-document when the IDE reloads.
  • Commands that read the selection follow the view that last held focus: the run line/selection/statement/paragraph family, run-to/from-line, run function/section, re-run previous, rstudioapi::getEditorContext() and friends, and the status bar cursor position and scope. Everything bound to the document itself (persistence, autosave, lint/spelling/debug markers, chunk output, navigation, find/replace) stays on the primary view; the distinction is documented in TextEditingTarget.Display.
  • Splits are a source-mode feature: the commands are disabled while the visual editor is active, and the split hides with the source editor when visual mode is on (the property survives the round trip).
  • Inline chunk output and chunk toolbars in R Markdown / Quarto documents continue to render in the primary view only, and breakpoints remain managed through the primary view's gutter (clicks in the secondary view's gutter deliberately don't create breakpoints, rather than creating ones that wouldn't register with the debugger). The architecture deliberately keeps the secondary view a full AceEditor with its own line-widget manager, so chunk-output mirroring can be added later without rework.

Notes for reviewers

  • The 2015 proof of concept (Enable editor split (multiple views of same file) #486) swapped the session after construction, which left the cursor-changed handler (bound to the old session's Selection) and the background highlighter pointing at a dead session. Here the cloned session is installed inside the AceEditorWidget constructor, before any session handlers bind.
  • Sharing one UndoManager across two sessions over one document is safe: both sessions report the same delta object, and UndoManager.add dedupes it (delta == this.$lastDelta).
  • The secondary view reuses TextEditingTargetPrefsHelper.registerPrefs() (the same path visual-mode chunk editors use), so editor prefs -- including Vim/Emacs keybindings -- apply to both views, and completion contexts are forwarded from the editing target.

Includes Playwright coverage (e2e/rstudio/tests/panes/editor/split_editor.test.ts) for document/undo sharing across views, per-view cursors, focus switching, split state toggling, and run-line following the focused view.

Fixes #2129.

Adds an editor split to source tabs: a second Ace view of the same
document, side by side or stacked, sharing the document and undo
history while keeping selection, scroll position, and folds per-view.

- new commands: splitEditorRight, splitEditorDown, removeEditorSplit,
  toggleEditorSplit, focusOtherEditorSplit (View > Split Editor), plus
  a toolbar menu button
- split state is stored in the editorSplit document property and
  restored when the document is reopened
- selection-driven commands (run line/selection, rstudioapi editor
  context, status bar position) follow the focused view; document-level
  behavior (persistence, markers, chunk output, breakpoints) stays on
  the primary view
- splits are a source-mode feature; the commands are disabled while
  the visual editor is active

Addresses #2129
@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.

When a source editor already holds focus and its document has an
active split, the activateSource command (Ctrl+1) now moves focus to
the other view instead of doing nothing, giving keyboard users a
toggle between the views without a new binding.

Addresses #2129
… button

Replaces the hand-drawn placeholder with the splitscreen_right icon
from Google's Material Symbols (Apache 2.0; added to NOTICE),
recolored to match the neighboring toolbar icons.

Addresses #2129
Regenerates the icon at 40x36 (the standard 2x toolbar button size;
the previous 22x20 matched the outline toggle, which is an outlier)
with the glyph scaled to fill the button, and increases the ink
density so the dark-theme inversion produces a brighter icon.

Addresses #2129
Scales the glyph ink to 18x14 (logical) within the standard 40x36
toolbar icon canvas, so the icon reads as a split editor window and
carries the same whitespace as its neighbors.

Addresses #2129
The glyph now occupies 14x11 (logical) of the 20x18 button, in line
with the ink coverage of the other toolbar icons (roughly 9-12 wide by
12-16 tall); the previous 18x14 filled the button nearly edge to edge,
which read as oversized next to its neighbors.

Addresses #2129
The filled Material glyph read as a solid blob next to the line-art
toolbar neighbors, especially under the dark-theme invert filter. Replace
it with a hand-drawn frame-plus-divider at the same ink geometry (28x22
physical in a 40x36 canvas), and drop the Material Symbols NOTICE entry
since the icon is no longer derived from it.
@gtritchie

Copy link
Copy Markdown
Member

Code review findings

Actionable items from an automated multi-agent review. Findings 1, 2, 4, 5, 6 were traced through the code by hand; 10 and 11 are code-path arguments that need a running IDE to confirm.

Critical

  1. src/gwt/acesupport/loader.js:597 — cloneSession passes the primary session's Mode object to the clone. RStudio modes are session-bound (r.js:43 does new RCodeModel(session, ...)), and EditSession.setEditorMode (ace/EditSession.java:139) early-returns when the mode constructor matches, so the later setFileType() never rebinds it. The split view's code model therefore points at the primary session forever. Ace calls getNextLineIndent(state, line, tab) with three args, so r_code_model.js:1600 falls back to the primary session's cursor: pressing Enter in the split view indents for the primary view's context and invalidates the shared cache at the wrong row. Fix: new RStudioEditSession(session.getDocument()) so setEditorMode builds a clone-bound mode, or clone.setMode(new Mode(false, clone)).

  2. .../text/TextEditingTargetWidget.java:516 — destroySplitEditor() is reachable only from manageEditorSplit(EDITOR_SPLIT_NONE), and splitEditorRegistrations_ is separate from releaseOnDismiss_, which is all TextEditingTarget.onDismiss() (TextEditingTarget.java:3783) drains. Closing a tab without un-splitting first leaves the ~40 registerPrefs bindings (:496) on the global UserPrefs singleton for the life of the IDE; they keep firing against a detached editor and pin the split editor, its session, and the shared Document, so the primary editor never becomes collectable either. AceEditorNative.destroy() also never runs, so the diagnostics worker outlives the tab. Fix: drive destroySplitEditor() from onDismiss.

Important

  1. .../text/TextEditingTarget.java:4123 — splitEditorRemoved() nulls splitCodeExecution_ without calling detachLastExecuted(); onDismiss at :3803 does. The anchored selection attaches to the shared document, which survives the split, so each split → run code → un-split cycle leaves two live change listeners on the primary document.

  2. .../filetypes/TextFileType.java:502 — no setEnabled call anywhere gates the five split commands on split state. Focus Other Editor Split on an unsplit document silently no-ops (TextEditingTargetWidget.java:377); Remove Editor Split fires a server round trip writing "none" over "none". All five show unconditionally in the command palette.

  3. .../text/TextEditingTargetWidget.java:1449 — splitEditorButton_.setVisible(width >= 590) gates on width only, and adaptToFileType never touches it (unlike toggleDocOutlineButton_). In visual mode the button opens a menu whose every item is disabled. A fix needs both sites, since manageToolbarSizes runs last.

  4. .../text/TextEditingTargetWidget.java:357 — getEditorSplit() returns the pending desiredSplitState_, so while a split awaits layout the guard in focusOtherEditorSplitIfFocused() (TextEditingTarget.java:4043) passes, focusOtherEditorSplit() no-ops on splitEditor_ == null, and Source.onActivateSource still returns early — swallowing Ctrl+1. Fix: gate on a materialized split.

  5. .../text/TextEditingTargetWidget.java:430 — the focus restore uses splitEditorFocusedLast_ ("last editor view to hold focus"), not "an editor view holds focus now", so removing the split while the Console has focus yanks focus into the editor. isEditorViewFocused() (:383) already exists.

  6. .../text/TextEditingTarget.java:4001 (and :4007, :4013, :4019) — the handlers call docUpdateSentinel_.setProperty with no progress indicator; the error path is Debug.logError only. A failed RPC means the editor doesn't split with no user feedback. Consider applying the split locally and treating persistence as best-effort.

  7. .../text/TextEditingTarget.java:4053 — applyEditorSplit accepts any string; manageEditorSplit treats anything that isn't none as a right split and memorizes it in lastEditorSplit_, so a stale or future-version property value is reproduced by the toggle indefinitely. Fix: validate against the three constants.

  8. .../text/TextEditingTargetWidget.java:483 — applyWrapMode(splitEditor_, ...) sets setWrapLimitRange(marginColumn, marginColumn), but setFileType (:491) and registerPrefs (:496) both reach syncMarginPrefs(), which overwrites it with setWrapLimitRange(null, marginColumn). With soft wrap plus margin-column soft wrap enabled, the split view would wrap at its own width while the primary wraps at marginColumn. Fix: move applyWrapMode after registerPrefs.

  9. src/gwt/acesupport/loader.js:596 — both sessions listen to the shared Document, and the primary attached first, so its mergeUndoDeltas is what UndoManager reads. Editor.$historyTracker sets the flag only on the session of the editor running the command, so typing in the split view may produce one undo group per keystroke while typing in the primary merges normally. The e2e test's "undo repeatedly" loop would mask this.

Tests

  1. e2e/rstudio/tests/panes/editor/split_editor.test.ts:55 — afterEach removes the split before closing the tab, structurally excluding the tab-close path (finding 2) from the suite. Add a test that splits, closes without un-splitting, then changes a global editor pref; the fixture fails on uncaught client exceptions.

  2. No test covers reopening a split document — the editorSplit persistence claim and the only path through the deferred desiredSplitState_ / onResize() retry.

  3. Every assertion is toHaveCount(1|2), so orientation is never checked; swapping addWest/addNorth passes the whole suite. The toggle test at :91 also can't distinguish a working lastEditorSplit_ from it being ignored, since the initializer is already EDITOR_SPLIT_RIGHT. Fix: compare the two views' boundingBox(), and run the toggle round-trip after splitEditorDown.

  4. e2e/rstudio/tests/panes/editor/split_editor.test.ts:32 — documentValue's ?? '' fallback makes the shared-undo assertion at :79 pass vacuously if activeEditor() returns null. Throw instead of coalescing.

  5. e2e/rstudio/tests/panes/editor/split_editor.test.ts:76 — the undo test clicks the primary view then presses Ctrl+Z; if the click doesn't move focus, the split view undoes its own edit and the assertion passes anyway. Assert focus before the undo loop, and assert the document still contains split_x <- 10 afterward so an over-undo is caught.

  6. No coverage for: visual mode (the five disabled commands, focusOtherEditorSplitIfFocused returning false, activeDisplay() falling back to docDisplay_); re-run-last-code after removing the split (splitEditorRemoved exists precisely for this); per-view folds, which $cloneFoldData deliberately handles.

Suggestions

  1. src/gwt/acesupport/loader.js:590 — the comment calls folds "per-session state owned by the new session" and rejects one-time copies as the reason breakpoints aren't copied, then copies folds via $cloneFoldData(). State the real intent: folds are seeded from the source session, then diverge.

  2. .../text/ace/AceEditorNative.java:311 — session.renderer = this.renderer is an unexplained Ace-internal coupling that reads as dead code. One line on why the cloned session needs the back-pointer.

  3. .../text/TextEditingTarget.java:374 — the Display primary/secondary note lists "lint/spelling/debug markers" but omits breakpoints, the most user-visible primary-only behavior and the subject of dedicated comments in AceEditorWidget.java:281 and loader.js:594.

  4. The find/replace bar is wired to editor_ only, so Ctrl+F while the split view is focused searches and moves the primary view's cursor. NEWS calls out breakpoints and chunk output as limitations but not this.

  5. .../text/TextEditingTargetWidget.java:425 — switching orientation right↔down re-adds the primary editor as the center widget, then removes it again at :440. Each cycle fires AceEditor.attach()/detach(), rebuilding event listeners, keyboard handlers, completion manager, scope tree, and tokenizer. Guard the editorPanel_.add(editorWidget) so it only runs when the new state is EDITOR_SPLIT_NONE.

@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

RStudio modes bind their code model to the session they are created
with, and EditSession.setEditorMode reuses a mode whose constructor
matches -- so a cloned session sharing the primary's mode object kept a
code model pointed at the primary session forever (Enter in the split
view indented against the primary view's cursor). Create the clone with
a plain text mode instead, so setFileType() builds a clone-bound mode.

Also delegate the clone's mergeUndoDeltas flag to the source session:
the shared UndoManager reads the flag from whichever session reports a
delta first (the primary), so typing in the split view would otherwise
start a new undo group on every keystroke.
- tear down the split view from TextEditingTarget.onDismiss(), so
  closing a split tab releases the ~40 pref bindings registered against
  the UserPrefs singleton (and the editors they capture)
- detach the split executor's last-executed selection anchors when the
  split is removed; they attach to the shared document and leaked
- restore focus after removing a split only when an editor view held it
  (captured before teardown detaches the views), so removing the split
  from e.g. the Console no longer steals focus
- have focusOtherEditorSplit() report whether it moved focus, so Ctrl+1
  falls through to normal source activation while a requested split is
  still waiting on layout instead of being swallowed
- validate the editorSplit document property against the known values;
  stale or future values collapse to none instead of being memorized
  and reproduced by toggleEditorSplit
- apply the soft wrap state after setFileType()/pref registration in
  ensureSplitEditor(); both reset the wrap limit range and clobbered
  the margin-column wrap
- hide the split editor toolbar button in visual mode, where all of its
  menu commands are disabled
- re-add the primary editor as the center widget only when returning to
  a single view, avoiding a redundant detach/attach cycle on right/down
  orientation switches
- mention breakpoints in the Display primary/secondary note, and the
  primary-view Find/Replace limitation in NEWS
- assert split orientation via bounding boxes (right = side by side,
  down = stacked), and verify toggleEditorSplit restores a down split
  rather than the default right orientation
- assert the primary view holds focus before the shared-undo loop, and
  that the original content survives it (guards against an over-undo)
- make documentValue() throw instead of coalescing to '', so content
  assertions cannot pass vacuously without an active editor
- add a close-while-split test (the suite otherwise always removes the
  split before closing) and a reload test covering the editorSplit
  property restore through the deferred-layout path
@kevinushey

Copy link
Copy Markdown
Collaborator Author

Worked through all 22 findings; each was verified against the code before acting. 19 applied across f111bf7, 565e10d, and f825bf6; the split-editor e2e suite passes (7/7) including the new coverage.

Critical

  1. Confirmed end to end -- setEditorMode early-returns on a matching constructor, so the clone kept the primary-bound code model and getNextLineIndent's cursor fallback read the primary session. Fixed in f111bf7: cloneSession now starts from a plain TextMode, and setFileType() builds a clone-bound mode.
  2. Confirmed. TextEditingTarget.onDismiss() now calls a new Display.destroyEditorSplit(), releasing the pref bindings and destroying the split editor (565e10d). A close-while-split e2e test exercises the path (f825bf6).

Important

  1. Fixed -- splitEditorRemoved() now calls detachLastExecuted() before dropping the executor.
  2. Not applied. These follow the house convention for lightweight view commands: enabled per file type, no state gating (compare toggleDocumentOutline, goToNextChunk). Gating removeEditorSplit/focusOtherEditorSplit on split state needs per-tab command management on every tab switch and split change; the no-ops are harmless (manageEditorSplit early-returns on a same-value write). Happy to add if you feel strongly.
  3. Fixed at both sites. Note adaptToFileType runs before initWidget(), so that site can't read layout -- it only clears visibility for visual mode; the width gate stays in manageToolbarSizes.
  4. Fixed -- focusOtherEditorSplit() now reports whether it moved focus and focusOtherEditorSplitIfFocused() returns that, so Ctrl+1 falls through to normal activation while a split awaits layout.
  5. Applied with a variation: the live check can't run where the code sits (teardown detaches the split view first, which blurs it), so isEditorViewFocused() is captured before teardown. Removing the split from the Console no longer steals focus; removing via a server-mode GWT menu now leaves focus with the menu rather than forcing the editor.
  6. Not applied -- this is the same setProperty-then-apply-on-response flow every other doc-property-backed command uses (soft wrap, rainbow parens; see DocUpdateSentinel.modifyProperties). Applying locally with best-effort persistence would make this the one property that can silently diverge from the server.
  7. Fixed -- values are validated against the three constants; unknown values collapse to none and never reach lastEditorSplit_.
  8. Confirmed and fixed (applyWrapMode now runs after setFileType()/pref registration). Worth noting the (margin, margin) vs (null, margin) disagreement between the soft-wrap property path and syncMarginPrefs() predates this PR -- main has the same last-writer-wins wobble on the primary editor.
  9. Confirmed in the ace source: EditSession.onChange passes its own mergeUndoDeltas to UndoManager.add, the primary's listener runs first, and its flag resets between keystrokes via the delayed $syncInformUndoManager. The clone's mergeUndoDeltas is now an accessor delegating to the primary session (f111bf7).

Tests (f825bf6)

  1. Added: split, close without un-splitting, then rebroadcast an editor pref.
  2. Added: reload test covering the editorSplit restore through the deferred-layout path.
  3. Added bounding-box orientation assertions for both orientations, and a toggle round-trip after a down split (distinguishes a working lastEditorSplit_ from the initializer).
  4. documentValue() now throws instead of coalescing.
  5. The undo test asserts the primary view holds focus before undoing, and that the original content survives the unwind.
  6. Agreed but deferred -- visual-mode e2e needs an Rmd fixture and panmirror bring-up; follow-up rather than growing this suite now. The rest of the review's test asks are in.

Suggestions

18-20. Comment fixes applied as suggested (fold seeding wording, session.renderer rationale -- it's the back-pointer RStudioEditor's constructor normally sets, read by auto_brace_insert's ghost-text checks -- and breakpoints in the Display note).
21. Added the Find/Replace limitation to the NEWS entry.
22. Applied -- the primary editor is re-added as the center widget only when returning to a single view. (Attach/detach re-registers the completion/scope subsystems rather than reconstructing them, but the redundant cycle was real.)

@github-actions

github-actions Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

1 test(s) failed

###################- 99% pass rate

Passed Failed Skipped Flaky
2042 1 377 11
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 2 0 8 0
✅ desktop-linux 505 0 90 3
✅ desktop-macos 510 0 86 3
❌ desktop-windows 511 1 90 2
✅ server-linux 492 0 95 3
✅ 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 6e0de142c23e2694561c770338d1b511e6d2a8eb - Run #497

The unscoped .ace_editor locator also matched the console, whose echoed
writeAndOpenFile writeLines() fallback contains the marker text on
Server. Scope the locator to the source panel, and give the post-reload
view assertion the same budget as a file open (the restore is
asynchronous and can exceed the default expect timeout on CI).
TextEditingTargetThemeHelper asserts a single ace_scroller under the
editing target, which an active editor split violates; assertion-enabled
builds (ant draft) throw AssertionError on the deferred split-restore
path after a reload. Release builds already read the primary (first)
view's styles either way.
quit() never returns to a prompt, so executeInConsole's default
prompt-count wait stalled the browser for the full 30s sessionRestart
timeout after every server run, with the session-ended overlay already
on screen. Dispatch with wait:false; the overlay wait that follows is
the completion signal.
@kevinushey
kevinushey merged commit 19f67be into main Aug 10, 2026
26 of 27 checks passed
@kevinushey
kevinushey deleted the feature/split-editor branch August 10, 2026 21:12
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.

View different parts of a source file at the same time

3 participants