Skip to content

Commit d758da0

Browse files
editor: Add GutterStyle for line-number gap, color and font (#3737)
## Description **Configurable editor line-number styles** This PR adds application-wide defaults and per-editor overrides for the gutter gap, normal and active line-number colors, font family, and font size. These settings let applications style line numbers independently of the editor body. Line-number measurement and painting use the same resolved typography. Wrapping, folding controls, scrollbar geometry, and pointer coordinates follow the resulting gutter width while body typography and row height remain independent. ## Screenshot | Before | After | | ---------------------------- | --------------------------- | | <img width="235" height="261" alt="image" src="https://github.com/user-attachments/assets/99edff5a-d550-496c-9eae-f09b497c6cc4" /> | <img width="261" height="257" alt="image" src="https://github.com/user-attachments/assets/d1bdfe37-b71c-4ffd-9fc2-113869db5928" /> | ## Changes - Add `GutterStyle` with optional properties. Explicit per-editor values override theme defaults; unspecified properties continue to inherit. Zero gaps and transparent colors remain explicit values. - Project the current theme and element settings on every render so removing an override restores the theme settings and later theme changes remain effective. - Document the API in English and Chinese. Theme settings are runtime-only and are not serialized into theme JSON. - Limit this change to Editor; Diff and TextView are unchanged. ## Usage ```rust use gpui_kit::{ px, component::{Theme, input::{Editor, GutterStyle}}, }; Theme::update(cx, |theme| { theme.set_editor_gutter_style( GutterStyle::default() .with_gap(px(12.)) .with_line_number_color(theme.muted_foreground) .with_active_line_number_color(theme.foreground) .with_line_number_font_family("JetBrains Mono") .with_line_number_font_size(px(12.)), ); }); Editor::new(&editor_state).apply_gutter_style( GutterStyle::default().with_line_number_font_size(px(11.)), ) ``` ## Public API ### gpui-base All paths below are relative to `gpui_base::input`. | Signature | Purpose | | --- | --- | | `pub struct GutterStyle` | Optional gutter presentation with private fields; implements `Clone`, `Debug`, `Default`, and `PartialEq`. | | `pub use gutter_style::GutterStyle` | Exposes the style through the public input module. | | `GutterStyle::with_gap(self, gap: Pixels) -> Self` | Sets spacing between the number/folding lane and body text. | | `GutterStyle::with_line_number_color(self, color: Hsla) -> Self` | Sets normal line-number ink. | | `GutterStyle::with_active_line_number_color(self, color: Hsla) -> Self` | Sets current-line number ink. | | `GutterStyle::with_line_number_font_family(self, family: impl Into<SharedString>) -> Self` | Sets the number font independently of the body. | | `GutterStyle::with_line_number_font_size(self, size: Pixels) -> Self` | Sets the number font size without changing body row height. | | `GutterStyle::get_gap(&self) -> Option<Pixels>` | Reads the explicitly configured gap. | | `GutterStyle::get_line_number_color(&self) -> Option<Hsla>` | Reads the explicitly configured normal color. | | `GutterStyle::get_active_line_number_color(&self) -> Option<Hsla>` | Reads the explicitly configured current-line color. | | `GutterStyle::get_line_number_font_family(&self) -> Option<&SharedString>` | Reads the explicitly configured font family. | | `GutterStyle::get_line_number_font_size(&self) -> Option<Pixels>` | Reads the explicitly configured font size. | | `GutterStyle::apply_overrides(&mut self, overrides: &Self)` | Merges only properties explicitly supplied by the overriding style. | | `EditorState::set_gutter_style(&mut self, style: GutterStyle)` | Replaces Base editor presentation for the next layout; callers outside render must notify afterwards. | | `InputExtras::get_gutter_style(&self) -> Option<&GutterStyle>` | Adds a default trait method returning `None`; `EditorExtras` overrides it to expose editor presentation to the generic renderer. | ### gpui-component | Signature | Purpose | | --- | --- | | `input::GutterStyle` (`pub use gpui_base::input::GutterStyle`) | Makes the same style type available through Component. | | `input::Editor::apply_gutter_style(self, style: GutterStyle) -> Self` | Applies per-editor property overrides over the active theme. | | `Theme::set_editor_gutter_style(&mut self, style: GutterStyle)` | Replaces application-wide editor defaults; use inside `Theme::update` to refresh windows. | | `Theme::get_editor_gutter_style(&self) -> &GutterStyle` | Reads configured defaults before per-editor overrides. | The existing Kit re-exports expose these additions without changes to `gpui-kit`. No existing public signatures are removed or changed. ## How to Test ```bash cargo test --locked -p gpui-base -p gpui-component --features gpui-base/test-support,gpui-component/test-support gutter ``` Five gutter tests exercise style construction and partial merging, explicit transparent colors and zero spacing, typography inheritance, theme updates and override removal, and gutter-dependent wrapping and scrollbar placement. They also check that changing gutter typography leaves body metrics unchanged and that clicking at the first caret leaves the selection at the start. ## Checklist - [x] I have read the [CONTRIBUTING](../CONTRIBUTING.md) document and followed the guidelines. - [x] Reviewed the changes in this PR and confirmed AI generated code (If any) is accurate. - [x] Passed `cargo run` for story tests related to the changes. - [ ] Tested macOS, Windows and Linux platforms performance (if the change is platform-specific) --------- Co-authored-by: Jason Lee <huacnlee@gmail.com>
1 parent 3fe533a commit d758da0

14 files changed

Lines changed: 1449 additions & 106 deletions

File tree

‎crates/base/src/input/base/element.rs‎

Lines changed: 292 additions & 72 deletions
Large diffs are not rendered by default.

‎crates/base/src/input/base/state.rs‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ use crate::input::blink_cursor::CURSOR_WIDTH;
4242
use crate::input::movement::MoveDirection;
4343
use crate::input::rope_ext::{next_grapheme_boundary, previous_grapheme_boundary};
4444
use crate::input::{
45-
InputEdit, InputExtras as _, Position, RopeExt as _, element::RIGHT_MARGIN, layout::LastLayout,
45+
EditorLineNumberRenderer, InputEdit, InputExtras as _, Position, RopeExt as _,
46+
element::RIGHT_MARGIN, layout::LastLayout,
4647
};
4748
use crate::overscroll::Overscroll;
4849
use crate::{AutoScroll, StepAction, TestSupportExt as _};
@@ -5401,6 +5402,17 @@ impl<M: InputModeKind> Focusable for InputBaseState<M> {
54015402

54025403
impl<M: InputModeKind> Render for InputBaseState<M> {
54035404
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5405+
self.render_with_line_numbers((), window, cx)
5406+
}
5407+
}
5408+
5409+
impl<M: InputModeKind> InputBaseState<M> {
5410+
pub(crate) fn render_with_line_numbers<R: EditorLineNumberRenderer>(
5411+
&mut self,
5412+
line_number_renderer: R,
5413+
window: &mut Window,
5414+
cx: &mut Context<Self>,
5415+
) -> impl IntoElement {
54045416
// Before anything reads it: the element resolves this style during
54055417
// layout and paint, and both happen after this call in the same frame.
54065418
self.editor_style = self
@@ -5596,7 +5608,11 @@ impl<M: InputModeKind> Render for InputBaseState<M> {
55965608
.pb(self.editor_paddings.bottom)
55975609
.pl(self.editor_paddings.left)
55985610
})
5599-
.child(TextElement::new(entity.clone()).placeholder(self.placeholder.clone()))
5611+
.child(
5612+
TextElement::new(entity.clone())
5613+
.with_line_number_renderer(line_number_renderer)
5614+
.placeholder(self.placeholder.clone()),
5615+
)
56005616
.when(self.shows_scrollbar(), |this| {
56015617
this.child(EditorScrollbar::new(entity.clone()))
56025618
});

‎crates/base/src/input/editor/indent.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::input::InputModeKind;
1+
use crate::input::{EditorLineNumberRenderer, InputModeKind};
22
use crate::input::{
33
Indent, IndentInline, InputBaseState, Outdent, OutdentInline, RopeExt, cursor::CursorSelection,
44
element::TextElement, layout::LastLayout, mode::LayoutMode,
@@ -84,7 +84,7 @@ impl LayoutMode {
8484
}
8585
}
8686

87-
impl<M: InputModeKind> TextElement<M> {
87+
impl<M: InputModeKind, R: EditorLineNumberRenderer> TextElement<M, R> {
8888
/// Measure the indent width in pixels for given column count.
8989
fn measure_indent_width(&self, style: &TextStyle, column: usize, window: &Window) -> Pixels {
9090
let font_size = style.font_size.to_pixels(window.rem_size());

‎crates/base/src/input/editor/mod.rs‎

Lines changed: 130 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,100 @@
1-
use gpui::{App, Div, Entity, InteractiveElement as _, IntoElement, RenderOnce, Stateful, Window};
1+
use gpui::{
2+
App, Div, Entity, EntityId, InteractiveElement as _, IntoElement, Pixels, ShapedLine,
3+
SharedString, Stateful, TextRun, TextStyle, View, ViewElement, Window, px,
4+
};
25

3-
use super::{EditorMode, InputBaseState, InputModeKind};
6+
use super::{EditorMode, InputBaseState, InputModeKind, element::LINE_NUMBER_RIGHT_MARGIN};
7+
8+
/// Supplies computed line-number geometry and glyphs for a single rendered frame.
9+
///
10+
/// The element owns this renderer, never the editing state: application styling
11+
/// must not become retained Base data. Measurement runs before wrapping; shaping
12+
/// runs only for visible buffer lines after wrapping and folding are resolved.
13+
#[doc(hidden)]
14+
pub trait EditorLineNumberRenderer: 'static {
15+
/// Returns the number lane width (excluding the gap) and resolved gap.
16+
/// A zero digit count requests only the gap when line numbers are hidden.
17+
fn measure_line_numbers(
18+
&self,
19+
digit_count: usize,
20+
body_style: &TextStyle,
21+
window: &Window,
22+
) -> (Pixels, Pixels);
23+
24+
/// Resolves a shared vertical offset from the configured fonts before shaping rows.
25+
/// Renderers using body typography need no vertical correction.
26+
fn resolve_line_number_baseline_offset(
27+
&self,
28+
_body_style: &TextStyle,
29+
_window: &Window,
30+
) -> Pixels {
31+
px(0.)
32+
}
33+
34+
/// Shapes one supported, one-based line number, without padding characters.
35+
fn shape_line_number(
36+
&self,
37+
number: usize,
38+
is_active: bool,
39+
body_style: &TextStyle,
40+
window: &Window,
41+
cx: &App,
42+
) -> ShapedLine;
43+
}
44+
45+
impl EditorLineNumberRenderer for () {
46+
fn measure_line_numbers(
47+
&self,
48+
digit_count: usize,
49+
body_style: &TextStyle,
50+
window: &Window,
51+
) -> (Pixels, Pixels) {
52+
if digit_count == 0 {
53+
return (px(0.), LINE_NUMBER_RIGHT_MARGIN);
54+
}
55+
let font_size = body_style.font_size.to_pixels(window.rem_size());
56+
let font_id = window.text_system().resolve_font(&body_style.font());
57+
// Proportional digits can differ in width; every supported digit must fit.
58+
let width = "0123456789"
59+
.chars()
60+
.map(|digit| window.text_system().layout_width(font_id, font_size, digit))
61+
.fold(px(0.), Pixels::max)
62+
* digit_count;
63+
(width, LINE_NUMBER_RIGHT_MARGIN)
64+
}
65+
66+
fn resolve_line_number_baseline_offset(&self, _: &TextStyle, _: &Window) -> Pixels {
67+
// The default renderer uses the body's own font and size.
68+
px(0.)
69+
}
70+
71+
fn shape_line_number(
72+
&self,
73+
number: usize,
74+
_: bool,
75+
body_style: &TextStyle,
76+
window: &Window,
77+
_: &App,
78+
) -> ShapedLine {
79+
let label: SharedString = number.to_string().into();
80+
// Right alignment uses the shaped advance, so padding characters would
81+
// change the label's measured width rather than provide layout spacing.
82+
let run = TextRun {
83+
len: label.len(),
84+
font: body_style.font(),
85+
color: body_style.color,
86+
background_color: None,
87+
underline: None,
88+
strikethrough: None,
89+
};
90+
window.text_system().shape_line(
91+
label,
92+
body_style.font_size.to_pixels(window.rem_size()),
93+
&[run],
94+
None,
95+
)
96+
}
97+
}
498

599
/// State for source-code editing.
6100
///
@@ -224,22 +318,51 @@ impl EditorState {
224318
}
225319

226320
/// An unstyled source-code editor.
227-
#[derive(IntoElement)]
228-
pub struct Editor {
321+
pub struct Editor<R = ()> {
229322
state: Entity<EditorState>,
323+
line_number_renderer: R,
230324
}
231325

232326
impl Editor {
233327
pub fn new(state: &Entity<EditorState>) -> Self {
234328
Self {
235329
state: state.clone(),
330+
line_number_renderer: (),
236331
}
237332
}
238333
}
239334

240-
impl RenderOnce for Editor {
241-
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
242-
self.state
335+
impl<R: EditorLineNumberRenderer> Editor<R> {
336+
/// Supplies presentation for this element's frame without changing editor state.
337+
#[doc(hidden)]
338+
pub fn with_line_number_renderer<T: EditorLineNumberRenderer>(self, renderer: T) -> Editor<T> {
339+
Editor {
340+
state: self.state,
341+
line_number_renderer: renderer,
342+
}
343+
}
344+
}
345+
346+
impl<R: EditorLineNumberRenderer> IntoElement for Editor<R> {
347+
type Element = ViewElement<Self>;
348+
349+
fn into_element(self) -> Self::Element {
350+
ViewElement::new(self)
351+
}
352+
}
353+
354+
impl<R: EditorLineNumberRenderer> View for Editor<R> {
355+
fn entity_id(&self) -> Option<EntityId> {
356+
Some(self.state.entity_id())
357+
}
358+
359+
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
360+
// Preserve the entity's identity for invalidation and element-state scoping.
361+
self.state.update(cx, |state, cx| {
362+
state
363+
.render_with_line_numbers(self.line_number_renderer, window, cx)
364+
.into_any_element()
365+
})
243366
}
244367
}
245368

‎crates/base/src/input/mod.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ pub use diagnostics::{
9999
DiagnosticSummary, DiagnosticTag, RelatedInformation,
100100
};
101101
pub use display_map::{BufferPoint, DisplayMap, DisplayPoint, FoldRange, WrappingIndent};
102-
pub use editor::{Editor, EditorState};
102+
pub use editor::{Editor, EditorLineNumberRenderer, EditorState};
103103
pub use highlighting::{
104104
DiagnosticColors, FoldIconRenderer, FoldPlaceholderRenderer, HighlightStyleResolver,
105105
InputEditorStyle, InputHighlighter, InputHighlighterFactory, SharedHighlightStyleResolver,

‎crates/base/src/layout_direction.rs‎

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -121,27 +121,45 @@ macro_rules! logical_edge {
121121
pub trait LogicalStyledExt: Styled + Sized {
122122
logical_edge!(
123123
/// Padding on the start edge.
124-
ps, pl, pr, DefiniteLength
124+
ps,
125+
pl,
126+
pr,
127+
DefiniteLength
125128
);
126129
logical_edge!(
127130
/// Padding on the end edge.
128-
pe, pr, pl, DefiniteLength
131+
pe,
132+
pr,
133+
pl,
134+
DefiniteLength
129135
);
130136
logical_edge!(
131137
/// Margin on the start edge.
132-
ms, ml, mr, Length
138+
ms,
139+
ml,
140+
mr,
141+
Length
133142
);
134143
logical_edge!(
135144
/// Margin on the end edge.
136-
me, mr, ml, Length
145+
me,
146+
mr,
147+
ml,
148+
Length
137149
);
138150
logical_edge!(
139151
/// Inset from the start edge of the positioned ancestor.
140-
inset_s, left, right, Length
152+
inset_s,
153+
left,
154+
right,
155+
Length
141156
);
142157
logical_edge!(
143158
/// Inset from the end edge of the positioned ancestor.
144-
inset_e, right, left, Length
159+
inset_e,
160+
right,
161+
left,
162+
Length
145163
);
146164

147165
/// Border width on the start edge.

0 commit comments

Comments
 (0)