Repository navigation
show git changes in the editor gutter - #19204
Conversation
Marks lines added, changed, or removed relative to the Git index beside the line numbers, updating as the user types. The diff is computed client-side with Ace's ext/diff provider against the index version fetched through a new git_diff_base_contents RPC. New pref show_git_diff_gutter (Code > Display), on by default. Addresses #2846
Next/Previous Change and Revert Change at Cursor commands (Tools > Version Control), a peek widget opened by clicking a marker that shows the index version with a Revert button, and the diff now honors the ignore-whitespace preference. Addresses #2846
…nds when off Git integration can stay on for a project while the editor adornments are turned off: the checkbox now lives with the other Git settings, and Next/Previous Change and Revert Change at Cursor follow it. Addresses #2846
… files Review follow-ups: actions flush a pending diff before using it; marker clicks also swallow click/dblclick so Ace's fold toggle stays out of it; a base refresh closes the peek; the RPC applies the source loader's line-ending normalization; empty files diff as pure additions/deletions (the provider cannot take an empty side); ignore-whitespace matches git diff -w; the gutter commands need a Git session. Addresses #2846
…across unchanged refreshes Gutter cells gain 6px of right padding while the gutter is attached so the marker and its click target sit beyond Ace's fold arrow (which hangs into the padding), and the peek now closes only when the base contents actually change rather than on every re-fetch. Addresses #2846
…d follow the focused editor view The base RPC checks the index entry's mode (git ls-files --stage) so symlinks and submodules are left unmarked, and no longer strips control characters the editor keeps. A split editor view gets its own gutter fed the same base, the cursor-driven commands act on the view that holds the cursor, and visual mode disables them along with the other source-editor commands. Addresses #2846
… focus The base RPC looks the path up with a literal pathspec and checks the entry for exactly that path, so a symlink named like a glob cannot borrow a regular file's entry; and the split editor view schedules the same focus-triggered base refresh as the primary view. Addresses #2846
…h-encoding, and strip ESC like the editor The peek never displaces an existing line widget (Ace keeps one per row and the notebook persists chunk output by enumerating them); the base is keyed by encoding as well as path and re-fetched when a reopen with another encoding completes; and the base drops ESC characters the way the editor does when it loads a document. Addresses #2846
The gutter re-syncs on the SourceFileSavedEvent a rename raises, so a renamed document drops its old base at once; MathJax no longer adopts a line widget of another kind on an equation's row, and a peek stacked under another widget closes itself. Addresses #2846
… open peek Addresses #2846
…ase refreshes Addresses #2846
RStudio E2E - all platformsAll tests passed!
View / download the full reportView report online -- opens in the browser, no download needed. Available for 14 days. Download playwright-report.zip -- extract and open
All platforms - commit |
…t undone Reverting from a peek (or the Revert Change command) used the base as last fetched; the focus-driven re-fetch arrives 500ms plus a round trip later, so staging the file in the Terminal while a peek was open and then clicking Revert restored the pre-staging text. The gutter now asks the Java side for a fresh base first (setBaseRefresher / refreshBase), and the peek's Revert goes ahead only if the peek survived that refresh, while the command reverts only the chunk that was under the cursor when it was issued.
…cannot be re-fetched A revert deferred across the base re-fetch could land after the user had typed into the chunk's rows, where the chunk keeps its coordinates and the late revert would erase the edit; the gutter now counts document revisions and stands down when one happened meanwhile. A failed re-fetch no longer leaves the previous base in place for the revert to use: the base is dropped (markers and peek go) until the next refresh succeeds.
…r path A revert waiting on the base re-fetch survived a Save As: the path change dropped the base but kept the callbacks, which then ran against the new path's base, whose chunks can share the old ones' coordinates. The callbacks now run as soon as the base is dropped, where they find nothing to revert.
gtritchie
left a comment
There was a problem hiding this comment.
Findings are inline, roughly in order of importance. The first is a bug: Revert can write a filtered blob (git-crypt ciphertext, an LFS pointer) into the buffer. The diff-timeout one is real but only hits pathological diffs. The rest are consistency, accessibility, i18n, and performance points. Each comment says whether I reproduced it or only traced it in the code.
| // the stage is spelled out, or a name such as "0:script.R" would be read | ||
| // as stage 0 of script.R | ||
| core::system::ProcessResult procResult; | ||
| error = gitExec(gitArgs() << "show" << ":0:" + relativePath, root, &procResult); |
There was a problem hiding this comment.
git show :0:<path> returns the index blob as stored, without the smudge side of .gitattributes filters, while the editor shows the smudged working copy. For files under git-crypt, Git LFS, or ident, every line gets marked as changed, the peek shows the stored form (ciphertext, the LFS pointer), and Revert writes it into the buffer.
Reproduced with a rot13 clean/smudge filter on *.R: the working copy reads x <- hello, git show :0:a.R prints k <- uryyb, and git cat-file --filters :0:a.R prints x <- hello. git cat-file --filters (Git 2.11+) looks like the drop-in replacement.
There was a problem hiding this comment.
Confirmed with the same rot13 setup. Switched to git cat-file --filters :0:<path> in 3a0bd42; eol conversion comes through as well. A failing cat-file now reads as untracked, so an old Git loses markers rather than showing the stored form. Covered by a new e2e test.
| { | ||
| var DiffProvider = require("ace/ext/diff/providers/default").DiffProvider; | ||
| return new DiffProvider().compute(base, lines, { | ||
| maxComputationTimeMs: MAX_COMPUTATION_MS |
There was a problem hiding this comment.
When the computation runs past maxComputationTimeMs, the provider doesn't come back empty. The line-alignment step returns DiffAlgorithmResult.trivialTimedOut (one change spanning both documents), and computeDiff drops hitTimeout, so the "bail out" promised at line 50 ends up marking every line as modified.
I ran the bundled ext-diff-uncompressed.js under Node. Two unrelated 20k-line files sharing a 2-line header and 1-line footer took 256ms and returned a single chunk, old 0-20003 / new 0-20003, header and footer included. A one-line edit in the same file took 4ms, so this is only the pathological case. There, though, the whole gutter turns blue, each typing pause costs about 250ms, and Peek/Revert act on a file-sized chunk. A line-count cap before diffing, or treating a compute that used up the whole budget as a failure (the provider doesn't expose hitTimeout), would cover it.
There was a problem hiding this comment.
Reproduced under Node: the timed-out result is one chunk over both documents, header and footer included. The provider does not expose hitTimeout, so 3a0bd42 times the compute and drops any result that used the full budget. That leaves the per-pause cost in the pathological case, but the gutter now shows nothing instead of everything.
| { | ||
| // The base only moves when the index does (commit, stage, checkout); | ||
| // status refreshes driven by file changes leave it alone. | ||
| releaseOnDismiss.add(gitState_.get().addVcsRefreshHandler(event -> |
There was a problem hiding this comment.
Every open document registers this handler and the focus handler below, and GitState.refresh() always fires Reason.VcsOperation (GitState.java:95). That covers commits, Git pane refreshes, and the server's vcs_refresh (terminal exit, session resume, a .gitignore change). Each one sends a git_diff_base_contents per open document, all at once since each 500ms timer is scheduled by the same event. Each request runs two git processes on the session's main thread and re-sends the full contents, even when the base hasn't moved.
I haven't measured it, but with many tabs open on Windows, where process spawn is slow, it could add up to a noticeable stall after every commit. Two options: defer background documents until they're activated (the focus re-fetch already covers that path), and return the blob sha that ls-files --stage already reads, so an unchanged base can be skipped.
There was a problem hiding this comment.
Both suggestions taken in 3a0bd42. Background documents defer the refresh until they are next activated, and the fetch names the base it holds; the server answers unchanged with no contents when the index still has it. Two e2e tests cover the response shape and the deferral.
|
|
||
| // the change navigation and revert commands only make sense with the | ||
| // gutter markers they act on, which exist for Git alone | ||
| boolean gutterEnabled = vcsCommandsEnabled && |
There was a problem hiding this comment.
gutterEnabled builds on vcsCommandsEnabled, which requires the path to start with the active project directory. The gutter itself (TextEditingTargetGitDiffGutter.isEnabled()) and the backend (filePath.isWithin(root), SessionGit.cpp:2710) only check the Git root. In a repo whose .Rproj sits in a subdirectory, a file like ../shared/utils.R gets markers and a working peek and Revert, but Next Change, Previous Change, and Revert Change at Cursor are unavailable for it. Gating both on the same root would make them agree.
There was a problem hiding this comment.
Agreed they should agree. The client has no Git root, so 3a0bd42 gates the three commands on the gutter's own conditions instead of the project directory. Outside the root the server reports untracked, so there are no markers and the commands are no-ops, the same as an untracked file inside the root.
| // gains while attached (see themeStyles.css) so that it lies beyond Ace's | ||
| // fold arrow; a click there opens the peek instead of reaching Ace (and the | ||
| // breakpoint toggle behind it). | ||
| var MARKER_HIT_WIDTH = 6; |
There was a problem hiding this comment.
Two accessibility gaps. Added and modified lines get the same 3px bar in the same spot and differ only in color (#2da44e vs #0969da in themeStyles.css), which WCAG 1.4.1 (Level A) rules out. And the peek opens only from a mousedown on this 6px strip. None of the three commands opens it, so a keyboard user can revert a change but can't see what the revert will restore. A shape difference for modified lines (e.g. a dashed or narrower bar) and a command to show the change at the cursor would cover both.
There was a problem hiding this comment.
3a0bd42 makes the modified marker dashed (added stays solid), and adds Show Change at Cursor, which toggles the same peek from the keyboard, so Revert Change at Cursor can be previewed first. e2e test added.
|
|
||
| var label; | ||
| if (isDeletion(chunk)) | ||
| label = "Removed " + pluralize(oldLines.length, "line"); |
There was a problem hiding this comment.
These strings ("Removed/Added/Changed N lines", "previously:", "Revert", "Close") and pluralize() are English-only, while the commands and preference this PR adds are translated (CmdConstants_fr, PrefsConstants_fr). With the UI in French, the peek's text stays English. The strings could come from a GWT constants interface, passed in through GitDiffGutterNative.create().
There was a problem hiding this comment.
Moved to EditorsTextConstants with @PluralCount forms, passed into the JS module from GitDiffGutterNative.create(); en and fr strings in 3a0bd42.
|
|
||
| // a widget of another kind (e.g. the Git gutter's peek) has no MathJax | ||
| // root to render into; create our own alongside it instead | ||
| if (widget != null && !StringUtil.equals(widget.getType(), LINE_WIDGET_TYPE)) |
There was a problem hiding this comment.
The same assumption remains at line 127: the document-change timer treats any widget on a LaTeX range's end row as an existing preview and calls renderLatex(range, true). Under the default latex_preview_on_cursor_idle = always that doesn't matter, since the preview takes the row on cursor idle anyway, as your test expects. With never or inline_only, though, a peek on a $$ block's closing row plus typing inside the math sends renderLatexImpl down its popup branch, so an equation popup the user turned off appears. Traced in the code, not reproduced in the app. The same getType() check at 127 would close it.
There was a problem hiding this comment.
Right, same gap at line 127. The same type check is applied there in 3a0bd42, and the existing equation-preview test now types inside the equation with previews off and asserts nothing renders.
| // callback runs once the fetch has been applied -- or has failed, or the | ||
| // document has moved to another path, in which case the base has been | ||
| // dropped and there is nothing left to revert to. | ||
| private void refreshBase(JavaScriptObject callback) |
There was a problem hiding this comment.
A design note rather than a bug. Freshness is inferred from editor focus, and each revert pays for a full re-fetch, plus the revision and path bookkeeping that settles reverts while they wait. The backend already has the index identity: the blob sha in the ls-files --stage line it parses. If the response returned it, and the client sent back the sha it holds so the server could answer "unchanged", the focus and pre-revert checks would cost almost nothing. A .git/index stat check could replace the focus heuristic outright.
There was a problem hiding this comment.
Done together with the fan-out thread: the id is the blob sha plus the encoding used to decode it, so a Reopen with Encoding still re-fetches. The focus heuristic stays as the trigger; the cheap unchanged answer makes it affordable.
|
|
||
| this.closePeek(); | ||
| session.replace(range, text); | ||
| this.update(); |
There was a problem hiding this comment.
Minor: the session.replace on the line above already fires the editor's change event synchronously, which schedules another update() 150ms later, so every revert runs the full diff twice. Relatedly, with ignore-whitespace on, update() re-strips the unchanging base on every call (line 229). Caching the stripped lines in setBase/setIgnoreWhitespace avoids that.
There was a problem hiding this comment.
Both in 3a0bd42: the revert now flushes the update the change event scheduled instead of running a second one, and the stripped base is cached until the base or the preference changes.
…open the peek from the keyboard Review follow-ups for #19204: - The base is read with `git cat-file --filters :0:<path>` rather than `git show`, so a file under a clean/smudge filter (git-crypt, LFS, ident, eol) compares against what the editor shows instead of the stored form. - A fetch names the base it holds (blob sha plus encoding); the server answers "unchanged" without reading or sending the blob when the index still has it. Background documents no longer fetch on every Git refresh: they note the refresh and fetch when next shown. - A diff that used up its time budget is dropped rather than shown as one whole-document change; a revert runs one diff, not two; the stripped base for ignore-whitespace is cached. - New command Show Change at Cursor toggles the peek without the mouse, and the modified marker is dashed so it differs from the added one in shape, not only colour. - The peek's text comes from EditorsTextConstants (en + fr). - MathJax's document-change timer only treats its own line widget as an existing preview, so typing near a peek no longer opens a popup that the preference turned off. - The gutter commands share the gutter's own gate (Git session, saved path, preference) instead of the project-directory rule.
The 150ms debounce made the markers trail the keystroke. The diff is client-side and takes a millisecond or two, so an edit now queues it as a microtask: the markers update in the frame that paints the edit, and the many change events of one operation (replace all, a reformat) are diffed once. A document whose last diff took over 20ms falls back to diffing once typing pauses, and returns to immediate mode when a diff is fast again. Also tells a timed-out line alignment (one chunk spanning both documents, budget spent) from a sound alignment whose character refinement ran out of budget, which is harmless: only the former is dropped.
…a per-kind accent The markers open the peek on click, like the fold arrow beside them, so they show a pointer; the bar's box is widened to the click target with a transparent border so the cursor covers exactly what a click opens. The peek was red whatever the change, even for an addition with no previous lines to show. Its frame is now neutral with a left accent in the colour of the marker it came from (green added, blue modified, red removed), and only the previous lines keep a faint red tint, as removed lines in a diff do.
gtritchie
left a comment
There was a problem hiding this comment.
Round 2. The nine round-1 threads are addressed; I checked each fix against 445f63e. Two new findings from the changes, inline: the per-edit diff is expensive in mid-sized files, and a document still visible in an inactive source column keeps stale markers after a commit.
| return; | ||
|
|
||
| this.updatePending = true; | ||
| Promise.resolve().then(run); |
There was a problem hiding this comment.
The comment at line 50 assumes a diff takes a millisecond or two, but that holds only above about 850 lines. When the two documents total under 1,700 lines, the provider aligns lines with an O(n·m) dynamic-programming pass (ext-diff-uncompressed.js:3980), and that now runs on every keystroke before the frame paints.
I timed one character typed mid-file into real R files from this repo, under Node with the bundled ext-diff (median of 20 runs):
| File | Lines | Per keystroke |
|---|---|---|
NotebookPlots.R |
309 | 3.3ms |
NotebookData.R |
552 | 10.2ms |
AppCommands.R |
674 | 15.0ms |
SessionBreakpoints.R |
784 | 21.5ms |
SessionDataImportV2.R |
858 | 0.2ms |
The last row is past the DP threshold. So a 300-750-line script spends 3-20ms of each keystroke before paint; files that cross SLOW_DIFF_MS fall back to the 150ms debounce.
Trimming the identical leading and trailing lines, diffing only the middle, and offsetting the chunks returned identical chunks in 0.1-0.2ms on all four files. How much it helps depends on how clustered the uncommitted changes are: the middle runs from the first changed line to the last, so a file with edits near both ends gets little out of it.
There was a problem hiding this comment.
Reproduced, with larger numbers here (14-85ms for the same files). 6b05734 trims the lines common to both ends and diffs only the middle; a lone edit now takes well under a millisecond on all four. Edits near both ends still cover most of the file, as you noted.
Trimming surfaced a gap in the timeout rule: a large replaced block spends the budget in the provider's character-level refinement, and after trimming that result spans the whole region, so it read as a timed-out alignment. Such a result is now recomputed on one-character per-line tokens, where the refinement is negligible. A side effect is that a wholesale replacement of a file, which lost its markers entirely before, is now marked throughout. Blocks of ~800+ replaced lines still exceed the budget in the alignment itself, and a large replaced block still costs ~250ms per typing pause; diffing on tokens from the start would fix both but changes the provider's placement heuristics for ordinary edits, so that is filed as #19218. e2e tests added for the offsets and the wholesale case.
| if (gutter_ == null) | ||
| return; | ||
|
|
||
| if (!active_) |
There was a problem hiding this comment.
active_ tracks the active column's active tab, which isn't the same as visible. Activating a column calls prevColumn.setActiveEditor("") (SourceColumnManager.java:540), which runs onDeactivate() on the document still shown in the previous column (SourceColumn.java:375), so its refreshes are deferred here.
Scenario: script.R in the main column, helpers.R in a second column, both edited. Click into script.R, then commit both from the Git pane. helpers.R stays on screen with its pre-commit markers until you click into its column, which re-activates it and runs the deferred refresh. I traced this in the code but haven't run it, and the e2e suite has no multi-column case. Deferring only for documents that aren't visible, or refreshing each column's active tab, would keep the saving for hidden tabs.
There was a problem hiding this comment.
Confirmed by running it: with the fix reverted, the new multi-column e2e test fails with the stale marker still in place. 6b05734 refreshes any document that is on screen (the existing effective-visibility check on the editor element) rather than only the active one, so a document showing in another column picks up the commit; hidden tabs still defer.
The provider aligns inputs under 1,700 lines in total with a quadratic dynamic-programming pass, so a 300-800 line script cost 3-20ms per keystroke. Only the lines between the first and last difference are now handed to it, and the chunks shifted back; a lone edit diffs in well under a millisecond. Edits near both ends of a file still cover most of it. That exposed an ambiguity in the timeout rule: a large replaced block spends the whole budget in the provider's character-level refinement (quadratic in the block, and unused here), and after trimming its result spans the whole region, which read as a timed-out alignment. Such a result is now recomputed on one-character per-line tokens, which leaves the budget to the alignment; a wholesale replacement of a file, which used to lose its markers entirely, is marked throughout. A document showing in an inactive source column is deactivated when another column becomes active, so it deferred its refresh and kept stale markers after a commit until clicked. The refresh now runs for any document on screen.
gtritchie
left a comment
There was a problem hiding this comment.
Round-2 fixes verified at 6b05734: the gutter now diffs only the region between the first and last difference (chunks rebuilt the edited document in 3,000 of 3,000 random edit sets, and a 10-line replaced block in a 760-line file dropped from 22ms to 3ms), and a document showing in an inactive source column now refreshes after a commit.
Intent
Fixes #2846.
Files in a Git project now get change markers in the editor gutter, between the line numbers and the code: a green bar beside added lines, a blue bar beside modified lines, and a small red wedge at the seam where lines were removed (at the bottom of the last line when the removal was at the end of the file). The markers follow the buffer as the user types, without a save, and compare against the Git index, so staging a hunk clears its markers the same way it clears it from Review Changes. Untracked files, files outside the repository, and non-Git projects get no markers.
Clicking a marker opens a peek below the change showing the index version of those lines, with a Revert button. Tools > Version Control gains Next Change / Previous Change (Cmd+Alt+PageDown / PageUp, wrapping around like Find) and Revert Change at Cursor. The diff honors the existing Git "ignore whitespace" preference.
A new preference, Show changes in the editor gutter (Git/SVN,
show_git_diff_gutter), is on by default. Turning it off removes the markers, the peek, and the three commands while leaving the rest of the Git integration (pane, Review Changes, menus) in place -- for anyone who wants Git in the project but not in the editor.Approach
Romain's 2022 proof of concept (#11985) parsed a unified diff from
git_diff_fileon every save. Since then Ace has grownext/diff, with a port of VS Code's diff algorithm, and our fork (1.43.5) already carries it. This PR reuses that algorithm and builds the rest around it:Backend: a new
git_diff_base_contents(path, encoding)RPC runsgit show :<path>(the index version) and returns{ tracked, contents }, converting the contents with the document's encoding. A file outside the repository or absent from the index reportstracked = falsewithout logging, since that is the normal case for new files.Ace: a new acesupport module,
rstudio/git_diff_gutter, diffs the base lines against the live document withace/ext/diff/providers/default(debounced, with the provider's computation timeout) and paintsace_git-added/ace_git-modified/ace_git-deleted/ace_git-deleted-belowonto the gutter cells on each gutter render, since the gutter recycles its cell elements.ext-diff.jsis now shipped alongsideext-language_tools.js(and copied bybuild-ace), and loads on demand the first time a gutter attaches.GWT:
TextEditingTargetGitDiffGutterowns the per-document lifecycle. It fetches the base once per path and again when the index may have moved: onGitStaterefreshes with a VCS-operation reason (every git action RStudio runs itself, plus the Git pane's refresh), when the editor regains focus (so commits made in the Terminal are picked up on the next click into the editor), and on Save As. Status refreshes driven by file changes are ignored, since a save does not move the index.Styling lives in
themeStyles.css, with light and dark variants, and is drawn at the right edge of the gutter cell so it stays clear of the annotation icons and breakpoints on the left.Peek and revert: the acesupport module intercepts mousedown on the marker strip (capture phase, so the breakpoint toggle that hangs off Ace's gutter handler never sees it) and opens an Ace line widget below the change. Revert replaces the chunk's new range with the base lines through
session.replace, so it is a single undo step; chunks touching the end of the document take the newline before them rather than after. An open peek survives recomputes only while its chunk is unchanged.Commands: the three commands follow
vcsFileDiffand friends --context="vcs", shown and enabled bySourceColumn.manageVcsCommands, listed byTextFileType, and handled inTextEditingTarget, which delegates to the per-document gutter.Not in this PR: scrollbar zones. Ace's
ScrollDiffDecoratorneeds its custom scrollbar, which RStudio does not enable.Automated Tests
e2e/rstudio/tests/panes/editor/git_diff_gutter.test.tsbuilds a repo R-side (so it also runs in Server mode) and checks: markers on open at the expected rows for an added, a modified, and a removed line; a live update while typing without a save; Next/Previous Change stepping through the three changes and wrapping; Revert Change at Cursor restoring each kind of change, down to an exact match with the index; the peek opening on a marker click, closing on a second click, and reverting from its button; the ignore-whitespace preference; markers clearing after a commit plus Git refresh, with a fresh edit then diffed against the new base; the preference toggle detaching and re-attaching the gutter and hiding and restoring the commands; and an untracked file staying unmarked. The Global Options panes spec still passes with the new checkbox. Passes locally intest:server-dev.QA Notes
Open a Git project, edit a committed file, and check the three marker kinds in both a light and a dark editor theme. Click a marker to peek and revert; step through changes with Cmd+Alt+PageDown / PageUp. A click on the left part of a gutter cell should still toggle a breakpoint. Commit from the Terminal and click back into the editor: the markers should clear. Toggle the preference in Global Options > Git/SVN: the markers and the three Version Control menu items should disappear together, with the Git pane unaffected.
Documentation
None added; the preference is self-describing in Global Options. Happy to add a line to the User Guide's Git page if wanted.
Checklist
NEWS.md