Skip to content

Adding shrink empty lines feature - #340739

Open
Aiday Marlen Kyzy (aiday-mar) wants to merge 53 commits into
mainfrom
tricky-jellyfish
Open

Aiday Marlen Kyzy (aiday-mar) wants to merge 53 commits into
mainfrom
tricky-jellyfish

Conversation

@aiday-mar

@aiday-mar Aiday Marlen Kyzy (aiday-mar) commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #66468

Description

Adds built-in support for shrinking lines without letters or numbers in the editor so more vertical space is available for code. This includes empty lines, whitespace-only lines and/or and punctuation-only lines such as {, }, and );, matching the C# example in the issue's screenshot. Lines containing Unicode letters or numbers retain their regular height, including code and comments containing text.

The new editor.shrinkEmptyLines setting accepts a numeric multiplier between 0.25 and 1 inclusive. The multiplier value proportionally reduces the line height of eligible lines and the font size of their non-whitespace content. Spaces and tabs retain their regular font size and width. There is another setting editor.shrinkEmptyLinesKind which controls what lines are shrunk : blank means only blank lines will be shrunk and punctuation means blank lines as well as lines with punctuation will be shrunk.

Shrinking requires variable line heights and variable fonts to be enabled. Outside accessibility mode, these are controlled by editor.allowVariableLineHeights and editor.allowVariableFonts; in accessibility mode, editor.allowVariableFontsInAccessibilityMode controls variable fonts instead. Disabling the relevant capability restores regular sizing.

Investigating Visual Studio

The main issue references the Shrink Empty Lines extension for Visual Studio, which compresses empty lines and lines without alphanumeric characters. The investigation below shows that empty-lines are compressed by 25%, and the line numbers still fit without being scaled.

Screenshot 2026-10-14 at 16 40 20

Line Numbers Overlap

Line numbers are made to scale by the same proportion as a compressed line's height so they fit without overlapping. For example, a line compressed to 0.8 of its regular height also uses 0.8 of the regular line-number font size. This only applies when the line height is smaller than the regular line height.

Model Decoration Font Properties and CSS

The model decoration's fontSize property and its inlineClassName currently serve different purposes, and setting the property alone is not enough to resize the rendered text. fontSize is retained as metadata for the editor's font-size-at-position lookup and input sizing. It also causes the normalized decoration to set affectsFont, allowing the view to identify lines with variable fonts and avoid fixed-width rendering assumptions. However, the direct model-decoration path does not translate that value into a CSS font-size declaration.

The browser only sees the actual visual change when a CSS rule reaches the text spans. This contribution therefore passes the same computed size to DynamicCssRules, obtains a generated class name, and sets that class as the decoration's inlineClassName. When the editor font size or shrink multiplier changes, both the model's fontSize value and the corresponding CSS/class reference must be updated. The CSS reference is released when shrinking is disabled or the contribution is disposed. Interestingly, the higher-level decoration-type adapter already handles the CSS-generation side automatically, but direct model-decoration callers do not receive that behavior.

As a possible next step, we should consider whether setting fontSize on a model decoration should automatically generate and apply the corresponding CSS, making the property authoritative instead of requiring callers to supply matching CSS separately. The same API-contract question applies to fontFamily, fontWeight, and fontStyle: currently their presence contributes to affectsFont, but their values are not retained by normalized model-decoration options or applied as CSS. Such a change would need to define how property-generated styles interact with existing inlineClassName rules and the decoration-type adapter, and who owns and disposes the generated styles. This PR keeps the fix local rather than changing that shared contract.

Punctuation Font Size and Indentation Alignment

Initially when I was applying the smaller font to the whole line, it also shrank its indentation whitespace, moving braces horizontally out of alignment with surrounding code and indentation guides. To avoid this, line height and font size use separate decorations: a whole-line decoration controls vertical compression and sets the whole line font size to a smaller value, and font-size decorations cover only whitespace runs on eligible lines so these are made bigger. Leading indentation, internal spaces, trailing spaces, and tabs retain their regular font size, so punctuation shrinks without compressing whitespace horizontally.

Fixtures

This PR removes font: inherit from the shared light-theme fixture token CSS so decoration-controlled font sizes can render correctly. The shrink-empty-lines feature applies smaller fonts to punctuation on shortened lines, but the font shorthand also resets font-size to the inherited value. In the fixture’s scoped CSS, this overrode the size supplied by the decoration, leaving punctuation at the regular editor font size even though its line height had been reduced. Removing the shorthand while retaining the color and text-decoration rules lets the decoration’s CSS determine the intended font size, so the fixture accurately represents the feature. Because these styles are shared, this also changes the CI-blocking InlayHints, ColorDecorators, and SelectedColorDecorator screenshot baselines. Those differences are expected consequences of the fixture styling adjustment.

Optimization

The line height manager was optimized in order not to perform a splice on every line insert but rather do one sort at the end. The shrinkEmptyLines contribution was optimized in order not to change all the decorations on font and line height change, but rather just change the decoration options. Earlier before the optimization, the _updateAllDecorations call took roughly 400ms while opening sqlite.c file. Now it takes more so around 60ms.

Incorrect vertical alignment of punctuation

Shrinking punctuation while preserving normal-sized spaces and tabs exposed a baseline-alignment issue: even invisible whitespace contributes full-size font metrics, which push smaller braces and inline suggestions downward. The fix applies the reduced font size to the outer line element so text inherits it, while whitespace spans explicitly retain their regular font size and use vertical-align: top. This avoids coupling their alignment to the shared baseline without changing whitespace widths or replacing the editor’s inline layout.

Directly setting the font-size or using a whole line inline decoration?

In order to set the font size of the whole line to a smaller value, we have two possibilities:

  • Enforce the font size on the outer div of the line just like we do with the line height
  • Set a whole line inline decoration which automatically sets the class-name of all spans in the line so that the font size shrinks

A whole-line inline decoration is valid, but it would apply the smaller font to whitespace as well as punctuation. Since whitespace must remain normal-sized to preserve indentation, whitespace spans would receive both the shrinking class and the normal-size override class, making correct CSS precedence essential. Applying the smaller font to the outer line element instead establishes an inherited base size, which whitespace spans can explicitly override without competing font-size rules on the same element. Both approaches can work, but the outer-element approach expresses the intended relationship more naturally: a smaller base font for the line, with normal-sized whitespace as an exception.

Generally the code has been changed so that a fontSize combined with the flag isWholeLine but no inlineClassName sets the font-size on the outer div of the whole line.

Adding an array lineFontSizes

In order to determine whether a line has variable fonts or not, we use this array called lineFontSizes which is calculated inside the InlineDecorationsComputer. This current method only sets the variable-font flag when an inline CSS class is present. However, whole-line font-size decorations can change the font through the outer line element without providing an inline classname. The fix is to also recognize whole-line decorations that affect the font and mark their covered view lines accordingly, while only creating an inline decoration when a class actually exists. This separates font-measurement information from how styling is applied, allowing the renderer to avoid normal-size monospace assumptions when measuring compressed lines.

Update horizontal measurements on config change

On changing the compression multiplier we only change the model decoration options, so the CSS but not the actual decorations themselves, so this does not retrigger a re-rendering of the lines. As a result when you change the config for the compression multiplier, this does not reflect itself correctly in the horizontal measurements calculated by the renderLine method. In order to force a re-render I added a new field lineFontSize to the RenderLineInput so it checks if that has changed or not, if yes, it re-renders.

Manual verification

  • Confirm the default editor.shrinkEmptyLines: 1 leaves every line at the regular height.
  • Set editor.shrinkEmptyLines to 0.5, 0.25, and another value such as 0.7; confirm empty, whitespace-only, and punctuation-only lines, use the corresponding proportion of the regular line height and their line numbers scale without overlapping.
  • Set editor.shrinkEmptyLines to 1, confirm this value leaves every line at the regular height. Enter values below 0.25 and above 1 in settings JSON and confirm the effective value is constrained to the supported 0.25-1 range.
  • Confirm lines containing letters or numbers, including Unicode letters and numbers, code, and comments containing text, retain the regular height and regular line-number font size. Confirm punctuation-only comment delimiters such as // and /**/ shrink.
  • Type a letter or number into a compressed line and confirm it immediately returns to the regular height; delete all letters and numbers while leaving punctuation and confirm it immediately becomes compressed.
  • Change editor.lineHeight, editor.fontSize, and the window zoom level while shrinking is enabled; confirm compressed lines and their line numbers continue to scale proportionally.
  • Disable editor.allowVariableLineHeights and confirm all lines, including brace lines, return to the regular height; re-enable it and confirm shrinking returns.
  • Fold a region containing empty and punctuation-only lines and confirm a visible fold header containing letters or numbers keeps the regular height; unfold it and confirm eligible lines are compressed again.
  • Navigate across consecutive compressed lines with the keyboard and confirm cursor movement, selection, scrolling, and reveal behavior remain correct.
  • Verify that punctuation shrinks while its starting column remains aligned with surrounding code and indentation guides.
  • Line-kind switching: Switch between "blank" and "punctuation" while shrinking is enabled. Also change the kind while disabled, then re-enable it; check for stale formatting.
  • Horizontal measurements: Place the caret at the end of a long punctuation-only line. Change the multiplier without editing text; verify caret position and selection boundaries update correctly.
    • ⚠️ On changing the compression multiplier we only change the model decoration options, so the CSS but not the actual decorations themselves, so this does not retrigger a re-rendering of the lines. In order to force a rerender I added a new field lineFontSize to the RenderLineInput so it checks if that has changed or not.
  • Batched edits: Paste multiple lines, perform multi-cursor insertions/deletions, and undo/redo. Confirm ordinary code never retains stale shrinking decorations.
  • Inline suggestions: Trigger a multiline suggestion on a compressed line. Check the first line’s size and regular-sized continuation lines; accept and undo it to verify reclassification.
  • Inlay hints: Check the inlay hints are smaller on a compressed line.
  • Empty files and file endings: Check compression in empty-editor hints, whitespace-only files, trailing blank lines, and files with or without a final newline.
  • Editor isolation: Open the same file in two splits with different folding states.
  • Mouse targeting: Click near compressed-row boundaries, drag selections, and perform rectangular selections across mixed-height rows.

Future Work

  • Correctly define getFontAtPosition depending on the actual font that is used during rendering.

Copilot AI balanced review requested due to automatic review settings October 9, 2026 14:55

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Batched edits, hidden lines, and model transitions can leave incorrect or stale line-height decorations.

2 open findings
What changed in this PR

Adds configurable compression of whitespace-only editor lines using per-editor line-height decorations.

Changes:

  • Adds off, compact, and veryCompact modes.
  • Implements incremental decoration updates and configuration handling.
  • Adds Monaco declarations and focused browser tests.
File Description
src/​vs/​monaco.d.ts Exposes the new editor options.
src/​vs/​editor/​editor.all.ts Registers the contribution.
src/​vs/​editor/​contrib/​shrinkEmptyLines/​test/​browser/​shrinkEmptyLines.test.ts Tests modes, edits, and configuration changes.
src/​vs/​editor/​contrib/​shrinkEmptyLines/​browser/​shrinkEmptyLines.ts Implements line compression.
src/​vs/​editor/​common/​standalone/​standaloneEnums.ts Adds standalone option identifiers.
src/​vs/​editor/​common/​config/​editorOptions.ts Defines and registers the setting.

🧠 Review effort: Balanced


💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Multi-edit coordinate handling can leave non-empty lines compressed, and model resets leak decoration IDs.

1 open finding
2 resolved since last review

🧠 Review effort: Balanced

@alexdima Alexandru Dima (alexdima) 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.

Just tried this first before looking at the code. The issue asks to shrink empty lines "and/or lines without alphanumeric characters", and its screenshot shows the { / } lines compressed too. This PR only shrinks whitespace-only lines, and its checklist says punctuation-only lines should keep their regular height, which is the opposite. To reproduce, paste the C# sample from the issue's screenshot and enable the setting. The brace lines don't shrink.

Please re-read the issue and its screenshot, update the behaviour and tests to match.

image

@alexdima Alexandru Dima (alexdima) 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.

Thanks for this, it's great to have it built in. I tried it on a few files and read through the implementation; three things stood out:

1. Shrunk punctuation sits below the line's center. On a shrunk line, the view line keeps the editor's regular font size and only the punctuation span gets the smaller font. Inline spans align to their parent's baseline, so a small } sits on the baseline of the regular-size font instead of being centered in the short line, while its line number stays centered. With shrinkEmptyLines: 0.5, a 40 px font and a 60 px line height, the brace is 6.8 px below the line's center (2.9 px at 20/30), and its glyph reaches the bottom edge. Adding verticalAlign: 'top' to the font-size class (createClassNameRef({ fontSize, verticalAlign: 'top' })) centers it in my testing. I haven't checked the cursor height or selection rendering with that change.

The same happens to inline suggestions on a shrunk line: the ghost text sits 7.0 px below the line's center (40/60), and vertical-align: top on its font-size class in ghostTextView.ts centers it too. The ghost text's leading indentation is also scaled down, so the suggestion starts to the left of where the accepted text will appear. That doesn't follow the rest of the feature, where indentation keeps its regular width.

Image Image

2. Could the line rule be configurable? Shrinking every line without letters or numbers works well for Allman style (the C# example in #66468), where both braces are on their own lines and shrink together. With K&R style (if (x) { … }), only the closing brace shrinks, so the pair looks lopsided. An enum such as editor.shrinkEmptyLinesKind: "blank" | "punctuation" would help: "blank" (empty and whitespace-only lines) could be the default, and "punctuation" would be the current behavior. Editor settings are already language-overridable, so people who want the brace behavior could turn it on just for C# with "[csharp]".

Image

3. Should "this line is shrunk" be a core concept? Ghost text and the empty-editor hint both read EditorOption.effectiveShrinkEmptyLines and recompute the smaller font themselves, so every feature that renders inside a line has to know about this option. Ones that don't stay full size: for example, an inlay hint after a shrunk } (like rust-analyzer's closing-brace labels) renders at the regular font inside the half-height line and overflows it. The root cause seems to be that fontSize exists only on decoration ranges, so the core has no line-level font size, and getFontSizeAtPosition returns the regular size on empty shrunk lines. Could the core own this instead? For example, a whole-line decoration's fontSize could apply to the view line itself, so everything rendered in the line inherits it, and keeping indentation at its regular width becomes the special case (an explicit size on whitespace runs). That would likely also fix (1).

Image

@aiday-mar
Aiday Marlen Kyzy (aiday-mar) marked this pull request as draft November 3, 2026 12:50
@aiday-mar

Copy link
Copy Markdown
Collaborator Author

Thanks for the comment. I am working on the changes. One thing I can say is that implementing number 3 does not fix 1. Consider the following html example:

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Mixed-font baseline demo</title>

<style>
    body { font-family: system-ui; }

    .line {
        position: relative;
        width: 320px;
        height: 30px;
        font: 20px/30px Menlo, Monaco, monospace;
        white-space: pre;
        background: #eef3ff;
    }

    .line > span {
        position: absolute;
        top: 0;
        bottom: 0;
    }

    .line::after {
        content: "";
        position: absolute;
        left: 0;
        right: 0;
        top: 50%;
        border-top: 1px dashed #c33;
        pointer-events: none;
    }

    .spaces { font-size: 40px; }
    .brace { outline: 1px solid #16803c; }

    .fixed .spaces { vertical-align: top; }
</style>

<p>Baseline-aligned spaces: bracket shifts down</p>
<div class="line"><span><span class="spaces">    </span><span class="brace">}</span></span></div>

<p>Top-aligned spaces: indentation width unchanged</p>
<div class="line fixed"><span><span class="spaces">    </span><span class="brace">}</span></span></div>
</html>

Opening it in the browser you can see in the first example that despite the brace having the same font size as the outer div, its position is shifted down as before. According to Copilot:

🤖 The parent’s font size does not establish a fixed baseline. The browser computes the line’s baseline from all its inline content. Your example contains:

  • Parent: 20px
  • Brace: 20px
  • Whitespace span: 40px
    Both spans default to vertical-align: baseline, so their baselines must coincide. Although the spaces are invisible, their 40px font still has ascent and descent metrics. Accommodating those metrics moves the shared baseline downward, and the 20px brace follows it

@aiday-mar

Aiday Marlen Kyzy (aiday-mar) commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

🤖 Moving the reduced font size onto the line itself fixes inheritance, but regular-size whitespace can still affect vertical alignment. Even invisible spaces contribute font metrics, and their default baseline alignment can push smaller braces and inline suggestions downward. Applying vertical-align: top or bottom to those whitespace spans avoids this baseline coupling without changing their width; both values work equivalently here because the spans inherit the same line height. Another approach would be to render whitespace at the smaller font size while preserving its original width using regular space and tab metrics, but that requires careful handling of cursor positions and hit testing. Flex/grid alignment or absolute positioning could also avoid the shared baseline, but would alter the existing inline text layout and require additional work to preserve spacing, selection, and cursor geometry. Simply setting vertical-align on the outer line is insufficient because the property is not inherited. Targeting only the regular-size whitespace spans is therefore the least invasive option.

@alexdima Alexandru Dima (alexdima) 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.

Thanks for the update! Centering, the new shrinkEmptyLinesKind setting, and moving the line font size into the core all look good. Inlay hints and ghost text now get the smaller size without knowing about the option. Two things are left:

1. Ghost text indentation still shrinks on empty lines. This was the second half of point 1 in my last review. When the cursor is at column 1 of an empty line, a suggestion's leading whitespace is drawn at the shrunk font size. That happens whenever you click into an existing blank line inside a block. The suggestion then starts about half an indent to the left of where it lands once accepted. With "editor.shrinkEmptyLines": 0.5, a 26 px font and 4-space indentation, console.log(total); starts 31 px into the line, but the accepted text starts at 63 px, lined up with return total; below it. The red line marks where the accepted text starts. I recorded this in a component fixture with a real inline completion provider, and accepted the suggestion through InlineCompletionsModel.accept() because the fixture has no Tab keybinding:

ghost-text-indentation-shrinks.mp4

A suggestion should start where its text will land after accepting, the same way indentation in the document keeps its regular width.

2. The line font size is looked up for every line on every frame, even when shrinking is off. A feature that isn't used shouldn't cost CPU cycles. Right now every editor pays for this one, even with editor.shrinkEmptyLines at its default of 1. ViewLayerRenderer now calls _lineFontSizeForLineNumber for each line it renders or lays out, in the text layer and in both overlay layers. That's about 370 lookups per frame with 63 lines visible. Each call converts the view line to a model line and queries the decoration tree. The only early exit is effectiveAllowVariableFonts, which is on by default.

The cost grows with the number of decorations in the model. With more than 1,000 matches, Find switches to a decoration without an overview ruler or minimap entry. Those matches land in the same decoration tree this query searches, and every decoration on the line is collected before the font ones are filtered out.

I scrolled a 250,000-line file two lines per frame in headless Chromium with default settings, and compared the real lookup with a constant stub. Times are the editor's own JavaScript (setScrollTop + render()), without browser layout or paint:

CPU Decorations in the model Render time per frame, stub Added by the lookup
Unthrottled None 0.33 ms +0.04 ms (+11%)
Unthrottled 19,999 Find matches (about one per line) 0.41 ms +0.06 ms (+15%)
4× slowdown (DevTools "mid-tier") None 2.16 ms +0.19 ms (+9%)
4× slowdown (DevTools "mid-tier") 19,999 Find matches (about one per line) 2.68 ms +0.19 ms (+7%)

With shrinking off, this should be zero.

🤖 Authored with GitHub Copilot on behalf of Alexandru Dima (@alexdima).

This branch has not been deployed

No deployments
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.

Shrink empty lines

3 participants