Skip to main content

gpui_deck/input/editor/
highlighting.rs

1// Modified for GPUI Deck: resolve text colors against the narrow InputColors baseline.
2use std::{ops::Range, rc::Rc, sync::Arc};
3
4use gpui::{AnyElement, Context, HighlightStyle, Hsla, SharedString, Window};
5use ropey::Rope;
6
7use super::{EditorState, FoldRange, InputEdit};
8use crate::InputColors;
9
10/// Resolves semantic highlight names into renderable GPUI styles.
11///
12/// Base deliberately knows nothing about a concrete syntax theme. UI crates and
13/// applications can provide any resolver, independently of their parser.
14pub trait HighlightStyleResolver: Send + Sync {
15    fn style(&self, name: &str) -> Option<HighlightStyle>;
16}
17
18#[derive(Default)]
19struct NoHighlightStyles;
20
21impl HighlightStyleResolver for NoHighlightStyles {
22    fn style(&self, _: &str) -> Option<HighlightStyle> {
23        None
24    }
25}
26
27/// Parser-independent syntax highlighting seam consumed by the Base editor.
28///
29/// Implementations own parsing, incremental state, and language-specific
30/// behavior. Base only asks for styled ranges and fold candidates.
31pub trait InputHighlighter {
32    fn language(&self) -> SharedString;
33
34    fn update(
35        &mut self,
36        edit: Option<InputEdit>,
37        text: &Rope,
38        folding: bool,
39        window: &mut Window,
40        cx: &mut Context<EditorState>,
41    );
42
43    /// Apply several edits made as one change, such as typing with multiple
44    /// cursors. Each entry is an edit with the text as it stood right after
45    /// it, in the order the edits were applied.
46    ///
47    /// The default hands each edit to [`Self::update`] in turn. Override it to
48    /// reparse once for the whole change.
49    fn update_batch(
50        &mut self,
51        edits: &[(InputEdit, Rope)],
52        folding: bool,
53        window: &mut Window,
54        cx: &mut Context<EditorState>,
55    ) {
56        for (edit, text) in edits {
57            self.update(Some(*edit), text, folding, window, cx);
58        }
59    }
60
61    /// Return ordered, non-overlapping style runs that fully cover `range`.
62    /// Use [`HighlightStyle::default`] for text without a semantic style.
63    fn styles(
64        &self,
65        range: &Range<usize>,
66        resolver: &dyn HighlightStyleResolver,
67    ) -> Vec<(Range<usize>, HighlightStyle)>;
68
69    fn fold_ranges(&self, text: &Rope) -> Vec<FoldRange>;
70
71    fn fold_ranges_for_edit(&self, range: Range<usize>, text: &Rope) -> Vec<FoldRange> {
72        let _ = range;
73        self.fold_ranges(text)
74    }
75}
76
77pub type InputHighlighterFactory = Rc<dyn Fn(&str) -> Option<Box<dyn InputHighlighter>>>;
78pub type SharedHighlightStyleResolver = Arc<dyn HighlightStyleResolver>;
79pub type FoldIconRenderer = Rc<dyn Fn(usize, bool) -> AnyElement>;
80
81/// Where in the syntax tree an offset sits, for editing decisions.
82///
83/// Parser-independent: `gpui-component` answers from tree-sitter, apps may
84/// answer heuristically. `None` (no provider installed) means `Code`.
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub enum SyntaxContext {
87    Code,
88    String,
89    Comment,
90}
91
92/// Answers syntax context for editing decisions (pairing, skip, indent).
93///
94/// Created per editor by the application's [`super::LanguageProvider`].
95/// Base never imports a parser; implementations live in UI crates or apps.
96pub trait SyntaxContextProvider {
97    fn context_at(&self, text: &Rope, offset: usize) -> SyntaxContext;
98}
99
100#[derive(Clone, Copy, Default)]
101pub struct DiagnosticColors {
102    pub error: Hsla,
103    pub warning: Hsla,
104    pub info: Hsla,
105    pub hint: Hsla,
106}
107
108/// Application-owned colors and highlight resolver consumed by editor painting.
109#[derive(Clone)]
110pub struct InputEditorStyle {
111    pub foreground: Hsla,
112    pub muted_foreground: Hsla,
113    pub background: Hsla,
114    pub border: Hsla,
115    pub selection: Hsla,
116    pub caret: Hsla,
117    pub diagnostics: DiagnosticColors,
118    pub highlight_styles: SharedHighlightStyleResolver,
119    pub editor_invisible: Option<Hsla>,
120    pub editor_active_line: Option<Hsla>,
121    pub editor_gutter_background: Option<Hsla>,
122    pub fold_icon_renderer: Option<FoldIconRenderer>,
123}
124
125impl InputEditorStyle {
126    /// Fills unset text-editing colors from the application's input baseline.
127    ///
128    /// `Hsla::default()` is fully transparent, and every colour on `Default` is
129    /// that — so an input nothing projected onto painted its glyphs, its caret
130    /// and its selection in nothing at all. Transparent is not a colour anyone
131    /// means for ink, which is what makes it usable as "unset" here.
132    ///
133    /// This is resolution, not assignment: whatever a consumer did project is
134    /// kept exactly. A consumer that projects once at construction gets the
135    /// baseline that is current now rather than the one installed when the
136    /// state was built.
137    pub fn resolved(&self, colors: &InputColors) -> Self {
138        let unset = |value: Hsla| value.a == 0.;
139        let or = |value: Hsla, fallback: Hsla| if unset(value) { fallback } else { value };
140
141        let foreground = or(self.foreground, colors.foreground);
142
143        Self {
144            foreground,
145            muted_foreground: or(self.muted_foreground, colors.muted_foreground),
146            background: or(self.background, colors.background),
147            border: or(self.border, colors.border),
148            selection: or(self.selection, colors.selection),
149            caret: or(self.caret, foreground),
150            ..self.clone()
151        }
152    }
153}
154
155impl Default for InputEditorStyle {
156    fn default() -> Self {
157        Self {
158            foreground: Hsla::default(),
159            muted_foreground: Hsla::default(),
160            background: Hsla::default(),
161            border: Hsla::default(),
162            selection: Hsla::default(),
163            caret: Hsla::default(),
164            diagnostics: DiagnosticColors::default(),
165            highlight_styles: Arc::new(NoHighlightStyles),
166            editor_invisible: None,
167            editor_active_line: None,
168            editor_gutter_background: None,
169            fold_icon_renderer: None,
170        }
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use gpui::hsla;
177
178    use super::InputEditorStyle;
179    use crate::InputColors;
180
181    fn dark() -> InputColors {
182        let mut colors = InputColors::default();
183        colors.foreground = hsla(0., 0., 0.98, 1.0);
184        colors.muted_foreground = hsla(0., 0., 0.64, 1.0);
185        colors.background = hsla(0., 0., 0.04, 1.0);
186        colors.border = hsla(0., 0., 0.15, 1.0);
187        colors.selection = hsla(0.6, 0.5, 0.5, 0.4);
188        colors
189    }
190
191    #[test]
192    fn an_unprojected_style_takes_its_ink_from_the_palette() {
193        let tokens = dark();
194        let resolved = InputEditorStyle::default().resolved(&tokens);
195
196        assert_eq!(resolved.foreground, tokens.foreground);
197        assert_eq!(resolved.caret, tokens.foreground);
198        assert_eq!(resolved.muted_foreground, tokens.muted_foreground);
199        assert_eq!(resolved.background, tokens.background);
200        assert_eq!(resolved.border, tokens.border);
201        // The point of the change: every one of these was transparent, so an
202        // input nothing projected onto painted its text in nothing at all.
203        for colour in [
204            resolved.foreground,
205            resolved.caret,
206            resolved.muted_foreground,
207            resolved.selection,
208        ] {
209            assert!(colour.a > 0., "{colour:?} is still invisible");
210        }
211    }
212
213    #[test]
214    fn a_selection_stays_translucent_enough_to_read_through() {
215        let resolved = InputEditorStyle::default().resolved(&dark());
216        assert_eq!(resolved.selection.a, 0.4);
217    }
218
219    #[test]
220    fn projected_colours_are_kept_verbatim() {
221        let chosen = hsla(0.3, 0.4, 0.5, 1.0);
222        let style = InputEditorStyle {
223            foreground: chosen,
224            selection: chosen.opacity(0.25),
225            caret: chosen,
226            ..Default::default()
227        };
228        let resolved = style.resolved(&dark());
229
230        assert_eq!(resolved.foreground, chosen);
231        assert_eq!(resolved.caret, chosen);
232        assert_eq!(resolved.selection, chosen.opacity(0.25));
233        // And what was not projected still comes from the palette.
234        assert_eq!(resolved.border, dark().border);
235    }
236
237    #[test]
238    fn resolution_never_consumes_its_own_output() {
239        // The projected style is kept verbatim precisely so that this holds:
240        // resolving against a second palette must follow it, not stay on the
241        // first. Resolving in place would have frozen after one pass.
242        let projected = InputEditorStyle::default();
243        let first = projected.resolved(&dark());
244
245        let mut light = InputColors::default();
246        light.foreground = hsla(0., 0., 0.04, 1.0);
247        let second = projected.resolved(&light);
248
249        assert_ne!(first.foreground, second.foreground);
250        assert_eq!(second.foreground, light.foreground);
251    }
252}