Skip to main content

gpui_base/input/editor/
mod.rs

1use gpui::{
2    App, Div, Entity, EntityId, InteractiveElement as _, IntoElement, Pixels, ShapedLine,
3    SharedString, Stateful, TextRun, TextStyle, View, ViewElement, Window, px,
4};
5
6use 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)]
14pub 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
45impl 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}
98
99/// State for source-code editing.
100///
101/// This is the shared editing engine in its code-editor kind. Languages, line
102/// numbers, folding, indent guides, diagnostics, decorations, and the LSP
103/// providers exist on this kind only, so an ordinary input or textarea never
104/// exposes them.
105pub type EditorState = InputBaseState<EditorMode>;
106
107impl InputModeKind for EditorMode {
108    const MULTI_LINE: bool = true;
109    const CODE_EDITOR: bool = true;
110
111    type Extras = super::EditorExtras;
112
113    fn hover_definition_style(
114        state: &InputBaseState<Self>,
115        _cx: &App,
116    ) -> Option<(std::ops::Range<usize>, gpui::HighlightStyle)> {
117        state.hover_definition_style()
118    }
119
120    fn hover_definition_hitbox(
121        state: &InputBaseState<Self>,
122        window: &mut Window,
123        _cx: &App,
124    ) -> Option<gpui::Hitbox> {
125        state.hover_definition_hitbox(window)
126    }
127
128    fn reset_language_features(state: &mut InputBaseState<Self>) {
129        state.extras.lsp.reset();
130    }
131
132    fn reset_annotations(state: &mut InputBaseState<Self>) {
133        state.extras.hover_popover = None;
134        state.extras.decorations.clear();
135        state.extras.range_decorations.clear();
136        state.extras.gutter_decorations.clear();
137        state.extras.overview_ruler_decorations.clear();
138    }
139
140    fn editing_syntax_context(state: &InputBaseState<Self>, offset: usize) -> super::SyntaxContext {
141        state.syntax_context_at(offset)
142    }
143
144    fn adjust_annotations(
145        state: &mut InputBaseState<Self>,
146        range: &std::ops::Range<usize>,
147        new_len: usize,
148    ) {
149        state.extras.decorations.adjust_for_edit(range, new_len);
150        state
151            .extras
152            .range_decorations
153            .adjust_for_edit(range, new_len);
154        state
155            .extras
156            .gutter_decorations
157            .adjust_for_edit(range, new_len);
158        state
159            .extras
160            .overview_ruler_decorations
161            .adjust_for_edit(range, new_len);
162    }
163
164    fn refresh_language_features(
165        state: &mut InputBaseState<Self>,
166        window: &mut Window,
167        cx: &mut gpui::Context<InputBaseState<Self>>,
168    ) {
169        let text = state.text().clone();
170        state.extras.lsp.update(&text, window, cx);
171    }
172
173    fn accept_inline_completion(
174        state: &mut InputBaseState<Self>,
175        window: &mut Window,
176        cx: &mut gpui::Context<InputBaseState<Self>>,
177    ) -> bool {
178        state.accept_inline_completion(window, cx)
179    }
180
181    fn has_inline_completion(state: &InputBaseState<Self>) -> bool {
182        state.has_inline_completion()
183    }
184
185    fn on_click(
186        state: &mut InputBaseState<Self>,
187        event: &gpui::MouseDownEvent,
188        offset: usize,
189        window: &mut Window,
190        cx: &mut gpui::Context<InputBaseState<Self>>,
191    ) -> bool {
192        state.handle_click_hover_definition(event, offset, window, cx)
193    }
194
195    fn clear_hover_state(
196        state: &mut InputBaseState<Self>,
197        cx: &mut gpui::Context<InputBaseState<Self>>,
198    ) {
199        state.clear_hover_state(cx);
200    }
201
202    fn on_text_typed(
203        state: &mut InputBaseState<Self>,
204        range: &std::ops::Range<usize>,
205        text: &str,
206        window: &mut Window,
207        cx: &mut gpui::Context<InputBaseState<Self>>,
208    ) {
209        state.handle_completion_trigger(range, text, window, cx);
210    }
211
212    fn clear_inline_completion(
213        state: &mut InputBaseState<Self>,
214        cx: &mut gpui::Context<InputBaseState<Self>>,
215    ) {
216        state.clear_inline_completion(cx);
217    }
218
219    fn hide_context_menu(
220        state: &mut InputBaseState<Self>,
221        cx: &mut gpui::Context<InputBaseState<Self>>,
222    ) {
223        state.hide_context_menu(cx);
224    }
225
226    fn is_context_menu_open(state: &InputBaseState<Self>, cx: &App) -> bool {
227        state.is_context_menu_open(cx)
228    }
229
230    fn handle_context_menu_action(
231        state: &mut InputBaseState<Self>,
232        action: Box<dyn gpui::Action>,
233        window: &mut Window,
234        cx: &mut gpui::Context<InputBaseState<Self>>,
235    ) -> bool {
236        state.handle_action_for_context_menu(action, window, cx)
237    }
238
239    fn on_hover_definition(
240        state: &mut InputBaseState<Self>,
241        offset: usize,
242        window: &mut Window,
243        cx: &mut gpui::Context<InputBaseState<Self>>,
244    ) {
245        state.handle_hover_definition(offset, window, cx);
246    }
247
248    fn on_mouse_move(
249        state: &mut InputBaseState<Self>,
250        offset: usize,
251        event: &gpui::MouseMoveEvent,
252        window: &mut Window,
253        cx: &mut gpui::Context<InputBaseState<Self>>,
254    ) {
255        state.handle_mouse_move(offset, event, window, cx);
256    }
257
258    fn drive_highlighter(
259        highlighter: &std::rc::Rc<std::cell::RefCell<Option<Box<dyn super::InputHighlighter>>>>,
260        edit: super::InputEdit,
261        text: &ropey::Rope,
262        folding: bool,
263        window: &mut Window,
264        cx: &mut gpui::Context<InputBaseState<Self>>,
265    ) {
266        let mut highlighter = highlighter.borrow_mut();
267        let Some(highlighter) = highlighter.as_mut() else {
268            return;
269        };
270        highlighter.update(Some(edit), text, folding, window, cx);
271    }
272
273    fn drive_highlighter_batch(
274        highlighter: &std::rc::Rc<std::cell::RefCell<Option<Box<dyn super::InputHighlighter>>>>,
275        edits: &[(super::InputEdit, ropey::Rope)],
276        folding: bool,
277        window: &mut Window,
278        cx: &mut gpui::Context<InputBaseState<Self>>,
279    ) {
280        let mut highlighter = highlighter.borrow_mut();
281        let Some(highlighter) = highlighter.as_mut() else {
282            return;
283        };
284        highlighter.update_batch(edits, folding, window, cx);
285    }
286
287    fn register_actions(
288        element: Stateful<Div>,
289        entity: &Entity<InputBaseState<Self>>,
290        window: &mut Window,
291    ) -> Stateful<Div> {
292        element
293            .key_context("Input mode=editor")
294            .on_action(window.listener_for(entity, InputBaseState::on_action_toggle_code_actions))
295            .on_action(window.listener_for(entity, InputBaseState::on_action_show_completions))
296            .on_action(window.listener_for(entity, InputBaseState::on_action_go_to_definition))
297    }
298}
299
300impl EditorState {
301    /// The LSP providers and their cached results.
302    ///
303    /// This exists on the editor alone: an ordinary input or textarea has no
304    /// language server, and no field to reach one through.
305    pub fn lsp(&self) -> &super::Lsp {
306        &self.extras.lsp
307    }
308
309    /// The LSP providers, mutably. Configure the providers through this.
310    pub fn lsp_mut(&mut self) -> &mut super::Lsp {
311        &mut self.extras.lsp
312    }
313
314    /// Syntax context at `offset`, or `Code` when the language has no provider.
315    pub(crate) fn syntax_context_at(&self, offset: usize) -> super::SyntaxContext {
316        self.mode.syntax_context_at(&self.text, offset)
317    }
318}
319
320/// An unstyled source-code editor.
321pub struct Editor<R = ()> {
322    state: Entity<EditorState>,
323    line_number_renderer: R,
324}
325
326impl Editor {
327    pub fn new(state: &Entity<EditorState>) -> Self {
328        Self {
329            state: state.clone(),
330            line_number_renderer: (),
331        }
332    }
333}
334
335impl<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
346impl<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
354impl<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        })
366    }
367}
368
369/// What a code editor exposes to the renderer. See [`crate::input::InputExtras`].
370impl crate::input::InputExtras for super::EditorExtras {
371    fn decoration_layers(&self) -> Vec<&[super::TextDecoration]> {
372        self.decorations.iter().collect()
373    }
374
375    fn range_decorations(&self, ranges: &[std::ops::Range<usize>]) -> Vec<&super::RangeDecoration> {
376        self.range_decorations.intersecting(ranges)
377    }
378
379    fn gutter_decorations_width(&self) -> Option<gpui::Pixels> {
380        self.gutter_decorations
381            .has_collections()
382            .then_some(self.gutter_decorations_width)
383    }
384
385    fn gutter_decorations(&self, range: std::ops::Range<usize>) -> Vec<&super::GutterDecoration> {
386        self.gutter_decorations.intersecting(&[range])
387    }
388
389    fn overview_ruler_decorations(&self) -> Vec<&super::OverviewRulerDecoration> {
390        self.overview_ruler_decorations.iter().flatten().collect()
391    }
392
393    fn overview_ruler_revision(&self) -> u64 {
394        self.overview_ruler_decorations.revision()
395    }
396
397    fn semantic_token_styles(
398        &self,
399        text: &ropey::Rope,
400        range: &std::ops::Range<usize>,
401        resolver: &dyn crate::input::HighlightStyleResolver,
402    ) -> Vec<(std::ops::Range<usize>, gpui::HighlightStyle)> {
403        self.lsp.semantic_tokens_for_range(text, range, resolver)
404    }
405
406    fn document_color_swatches(
407        &self,
408        text: &ropey::Rope,
409        range: &std::ops::Range<usize>,
410    ) -> Vec<(std::ops::Range<usize>, gpui::Hsla)> {
411        self.lsp.document_colors_for_range(text, range)
412    }
413
414    fn hover_symbol_range(&self) -> Option<std::ops::Range<usize>> {
415        self.hover_popover
416            .as_ref()
417            .map(|session| session.symbol_range.clone())
418    }
419
420    fn inline_completion_item(&self) -> Option<&lsp_types::InlineCompletionItem> {
421        self.inline_completion.item.as_ref()
422    }
423
424    fn context_menu_capabilities(&self) -> (bool, bool) {
425        (
426            self.lsp.definition_provider.is_some(),
427            !self.lsp.code_action_providers.is_empty(),
428        )
429    }
430}