BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-base / src / input / base / mode.rs

mode.rs

mode.rs 15.4 KiB Download Raw
1use crate::input::InputModeKind;
2use std::rc::Rc;
3use std::{cell::RefCell, ops::Range};
4
5use gpui::{Context, Pixels, Window};
6use ropey::Rope;
7
8use super::DisplayMap;
9use crate::input::{
10 DiagnosticSet, EditorLanguage, InputEdit, InputHighlighter, InputHighlighterFactory,
11 LanguageConfig, RopeExt as _, TabSize,
12};
13
14const BLOCK_GROWTH_FACTOR: usize = 2;
15
16/// What changed, handed to the syntax highlighter.
17pub(crate) struct HighlighterUpdate<'a> {
18 pub(super) selected_range: &'a Range<usize>,
19 pub(super) old_text: &'a Rope,
20 pub(super) new_text: &'a Rope,
21 pub(super) change_text: &'a str,
22 pub(super) force: bool,
23}
24
25/// How the input lays its text out: rows, growth, and the code-editor extras.
26///
27/// This does not say what *kind* of input this is — that is fixed at the type
28/// level by [`crate::input::InputModeKind`], and asking it here is what used to
29/// let the two disagree.
30#[derive(Clone)]
31pub(crate) enum LayoutMode {
32 /// A plain text input mode.
33 PlainText { tab: TabSize, rows: usize },
34 /// An auto grow input mode.
35 AutoGrow {
36 rows: usize,
37 min_rows: usize,
38 max_rows: usize,
39 },
40 /// A code editor input mode.
41 CodeEditor {
42 tab: TabSize,
43 rows: usize,
44 /// Show line number
45 line_number: bool,
46 language: Box<EditorLanguage>,
47 indent_guides: bool,
48 folding: bool,
49 highlighter: Rc<RefCell<Option<Box<dyn InputHighlighter>>>>,
50 highlighter_factory: Option<InputHighlighterFactory>,
51 diagnostics: DiagnosticSet,
52 /// Automatic delimiter ranges, adjusted with document edits.
53 auto_closed_pairs: super::auto_close::AutoClosedPairs,
54 auto_close: bool,
55 smart_indent: bool,
56 },
57}
58
59impl Default for LayoutMode {
60 fn default() -> Self {
61 LayoutMode::plain_text()
62 }
63}
64
65#[allow(unused)]
66impl LayoutMode {
67 /// Create a plain input mode with default settings.
68 pub(super) fn plain_text() -> Self {
69 LayoutMode::PlainText {
70 tab: TabSize::default(),
71 rows: 1,
72 }
73 }
74
75 /// Create a code editor input mode with default settings.
76 ///
77 /// Starts with no language; the state sets one through its own builder.
78 pub(super) fn code_editor(language: EditorLanguage) -> Self {
79 LayoutMode::CodeEditor {
80 rows: 2,
81 tab: TabSize::default(),
82 language: Box::new(language),
83 highlighter: Rc::new(RefCell::new(None)),
84 highlighter_factory: None,
85 line_number: true,
86 indent_guides: true,
87 folding: true,
88 diagnostics: DiagnosticSet::new(&Rope::new()),
89 auto_closed_pairs: Default::default(),
90 auto_close: true,
91 smart_indent: true,
92 }
93 }
94
95 /// Create an auto grow input mode with given min and max rows.
96 pub(super) fn auto_grow(min_rows: usize, max_rows: usize) -> Self {
97 LayoutMode::AutoGrow {
98 rows: min_rows,
99 min_rows,
100 max_rows,
101 }
102 }
103
104 /// Return true if this layout is a code editor with folding enabled.
105 #[inline]
106 pub(crate) fn is_folding(&self) -> bool {
107 if cfg!(target_family = "wasm") {
108 return false;
109 }
110
111 matches!(self, LayoutMode::CodeEditor { folding: true, .. })
112 }
113
114 pub(super) fn language_config(&self) -> Option<Rc<LanguageConfig>> {
115 match self {
116 Self::CodeEditor { language, .. } => Some(language.config()),
117 _ => None,
118 }
119 }
120
121 pub(super) fn syntax_context_at(
122 &self,
123 text: &Rope,
124 offset: usize,
125 ) -> crate::input::SyntaxContext {
126 match self {
127 Self::CodeEditor { language, .. } => language.context_at(text, offset),
128 _ => crate::input::SyntaxContext::Code,
129 }
130 }
131
132 pub(super) fn is_auto_close(&self) -> bool {
133 matches!(
134 self,
135 Self::CodeEditor {
136 auto_close: true,
137 ..
138 }
139 )
140 }
141
142 pub(super) fn is_smart_indent(&self) -> bool {
143 matches!(
144 self,
145 Self::CodeEditor {
146 smart_indent: true,
147 ..
148 }
149 )
150 }
151
152 pub(super) fn set_auto_close(&mut self, enabled: bool) {
153 if let Self::CodeEditor { auto_close, .. } = self {
154 *auto_close = enabled;
155 }
156 }
157
158 pub(super) fn set_smart_indent(&mut self, enabled: bool) {
159 if let Self::CodeEditor { smart_indent, .. } = self {
160 *smart_indent = enabled;
161 }
162 }
163
164 pub(super) fn auto_closed_pairs(&self) -> &super::auto_close::AutoClosedPairs {
165 match self {
166 Self::CodeEditor {
167 auto_closed_pairs, ..
168 } => auto_closed_pairs,
169 _ => super::auto_close::AutoClosedPairs::empty(),
170 }
171 }
172
173 pub(super) fn restore_auto_closed_pairs(&mut self, pairs: super::auto_close::AutoClosedPairs) {
174 if let Self::CodeEditor {
175 auto_closed_pairs, ..
176 } = self
177 {
178 *auto_closed_pairs = pairs;
179 }
180 }
181
182 pub(super) fn track_auto_closed_pair(&mut self, open: Range<usize>, close: Range<usize>) {
183 if let Self::CodeEditor {
184 auto_closed_pairs, ..
185 } = self
186 {
187 auto_closed_pairs.record(open, close);
188 }
189 }
190
191 pub(super) fn adjust_auto_closed_pair(&mut self, edit: &Range<usize>, new_len: usize) {
192 let Self::CodeEditor {
193 auto_closed_pairs, ..
194 } = self
195 else {
196 return;
197 };
198 auto_closed_pairs.adjust(edit, new_len);
199 }
200
201 #[inline]
202 pub(super) fn is_auto_grow(&self) -> bool {
203 matches!(self, LayoutMode::AutoGrow { .. })
204 }
205
206 pub(super) fn set_rows(&mut self, new_rows: usize) {
207 match self {
208 LayoutMode::PlainText { rows, .. } => {
209 *rows = new_rows;
210 }
211 LayoutMode::CodeEditor { rows, .. } => {
212 *rows = new_rows;
213 }
214 LayoutMode::AutoGrow {
215 rows,
216 min_rows,
217 max_rows,
218 } => {
219 *rows = new_rows.clamp(*min_rows, *max_rows);
220 }
221 }
222 }
223
224 /// Grow the row count to fit the content. Block tokens add their height on top of
225 /// `max_rows`, up to `BLOCK_GROWTH_FACTOR` times it.
226 ///
227 /// Callers gate this on the input being multi-line; a single-line field
228 /// keeps its one row. Only auto grow follows the content: in the other
229 /// modes `rows` is the configured height.
230 pub(super) fn update_auto_grow(&mut self, display_map: &DisplayMap, line_height: Pixels) {
231 if !self.is_auto_grow() {
232 return;
233 }
234 let content_rows = display_map.content_rows(line_height);
235 let block_rows = content_rows.saturating_sub(display_map.wrap_row_count());
236 if let LayoutMode::AutoGrow {
237 rows,
238 min_rows,
239 max_rows,
240 } = self
241 {
242 let cap = (*max_rows + block_rows).min(*max_rows * BLOCK_GROWTH_FACTOR);
243 *rows = content_rows.clamp(*min_rows, cap.max(*max_rows));
244 }
245 }
246
247 /// At least 1 row be return.
248 pub(super) fn rows(&self) -> usize {
249 match self {
250 LayoutMode::PlainText { rows, .. } => *rows,
251 LayoutMode::CodeEditor { rows, .. } => *rows,
252 LayoutMode::AutoGrow { rows, .. } => *rows,
253 }
254 .max(1)
255 }
256
257 /// At least 1 row be return.
258 #[allow(unused)]
259 pub(super) fn min_rows(&self) -> usize {
260 match self {
261 LayoutMode::AutoGrow { min_rows, .. } => *min_rows,
262 _ => 1,
263 }
264 .max(1)
265 }
266
267 #[allow(unused)]
268 pub(super) fn max_rows(&self) -> usize {
269 match self {
270 LayoutMode::AutoGrow { max_rows, .. } => *max_rows,
271 _ => usize::MAX,
272 }
273 }
274
275 /// Return false if the mode is not [`LayoutMode::CodeEditor`].
276 #[inline]
277 pub(super) fn line_number(&self) -> bool {
278 match self {
279 LayoutMode::CodeEditor { line_number, .. } => *line_number,
280 _ => false,
281 }
282 }
283
284 /// Update the syntax highlighter with new text.
285 ///
286 pub(crate) fn update_highlighter<M: InputModeKind>(
287 &mut self,
288 update: HighlighterUpdate<'_>,
289 window: &mut Window,
290 cx: &mut Context<crate::input::InputBaseState<M>>,
291 ) {
292 match &self {
293 LayoutMode::CodeEditor {
294 language,
295 highlighter,
296 highlighter_factory,
297 folding,
298 ..
299 } => {
300 if !update.force && highlighter.borrow().is_some() {
301 return;
302 }
303 if !ensure_highlighter(highlighter, highlighter_factory.as_ref(), language) {
304 return;
305 }
306
307 let edit = replacement_input_edit(
308 update.old_text,
309 update.new_text,
310 update.selected_range,
311 update.change_text,
312 );
313 M::drive_highlighter(highlighter, edit, update.new_text, *folding, window, cx);
314 }
315 _ => {}
316 }
317 }
318
319 /// Drive the highlighter once for several edits applied as one change,
320 /// each paired with the text right after it, in application order.
321 pub(crate) fn update_highlighter_batch<M: InputModeKind>(
322 &mut self,
323 edits: &[(InputEdit, Rope)],
324 window: &mut Window,
325 cx: &mut Context<crate::input::InputBaseState<M>>,
326 ) {
327 let LayoutMode::CodeEditor {
328 language,
329 highlighter,
330 highlighter_factory,
331 folding,
332 ..
333 } = &self
334 else {
335 return;
336 };
337 if !ensure_highlighter(highlighter, highlighter_factory.as_ref(), language) {
338 return;
339 }
340 M::drive_highlighter_batch(highlighter, edits, *folding, window, cx);
341 }
342
343 #[allow(unused)]
344 pub(super) fn diagnostics(&self) -> Option<&DiagnosticSet> {
345 match self {
346 LayoutMode::CodeEditor { diagnostics, .. } => Some(diagnostics),
347 _ => None,
348 }
349 }
350
351 pub(super) fn diagnostics_mut(&mut self) -> Option<&mut DiagnosticSet> {
352 match self {
353 LayoutMode::CodeEditor { diagnostics, .. } => Some(diagnostics),
354 _ => None,
355 }
356 }
357
358 /// Get a reference to the highlighter (if available)
359 pub(super) fn highlighter(&self) -> Option<&Rc<RefCell<Option<Box<dyn InputHighlighter>>>>> {
360 match self {
361 LayoutMode::CodeEditor { highlighter, .. } => Some(highlighter),
362 _ => None,
363 }
364 }
365
366 pub(super) fn set_highlighter_factory(&mut self, factory: InputHighlighterFactory) {
367 if let LayoutMode::CodeEditor {
368 highlighter_factory,
369 highlighter,
370 ..
371 } = self
372 {
373 *highlighter_factory = Some(factory);
374 *highlighter.borrow_mut() = None;
375 }
376 }
377
378 pub(super) fn ensure_highlighter_factory(&mut self, factory: InputHighlighterFactory) {
379 if let LayoutMode::CodeEditor {
380 highlighter_factory,
381 ..
382 } = self
383 {
384 if highlighter_factory.is_none() {
385 *highlighter_factory = Some(factory);
386 }
387 }
388 }
389}
390
391/// Create the highlighter from the factory if there is none yet. Returns
392/// whether one is installed.
393fn ensure_highlighter(
394 highlighter: &RefCell<Option<Box<dyn InputHighlighter>>>,
395 highlighter_factory: Option<&InputHighlighterFactory>,
396 language: &EditorLanguage,
397) -> bool {
398 let mut highlighter = highlighter.borrow_mut();
399 if highlighter.is_none()
400 && let Some(factory) = highlighter_factory
401 {
402 *highlighter = factory(&language.name());
403 }
404 highlighter.is_some()
405}
406
407/// Builds the tree-sitter edit for a text replacement.
408///
409/// Byte offsets and positions for `start`/`old_end` come from `old_text`;
410/// `new_end` byte/position come from the post-edit `text`.
411pub(super) fn replacement_input_edit(
412 old_text: &Rope,
413 new_text: &Rope,
414 selected_range: &Range<usize>,
415 change_text: &str,
416) -> InputEdit {
417 let start_byte = selected_range.start.min(old_text.len());
418 let old_end_byte = selected_range.end.min(old_text.len()).max(start_byte);
419 let new_end_byte = (start_byte + change_text.len()).min(new_text.len());
420
421 InputEdit {
422 start_byte,
423 old_end_byte,
424 new_end_byte,
425 start_position: old_text.offset_to_point(start_byte),
426 old_end_position: old_text.offset_to_point(old_end_byte),
427 new_end_position: new_text.offset_to_point(new_end_byte),
428 }
429}
430
431#[cfg(test)]
432mod tests {
433 use ropey::Rope;
434
435 use super::replacement_input_edit;
436 use crate::input::{DiagnosticSet, Point, TabSize, mode::LayoutMode};
437
438 #[test]
439 fn test_replacement_input_edit_backspace_at_end_uses_old_range() {
440 let old_text = Rope::from_str("-=");
441 let text = Rope::from_str("-");
442 let edit = replacement_input_edit(&old_text, &text, &(1..2), "");
443
444 assert_eq!(edit.start_byte, 1);
445 assert_eq!(edit.old_end_byte, 2);
446 assert_eq!(edit.new_end_byte, 1);
447 assert_eq!(edit.start_position, Point::new(0, 1));
448 assert_eq!(edit.old_end_position, Point::new(0, 2));
449 assert_eq!(edit.new_end_position, Point::new(0, 1));
450 }
451
452 #[test]
453 fn test_code_editor() {
454 let mode = LayoutMode::code_editor(Default::default());
455 assert_eq!(mode.line_number(), true);
456 assert_eq!(mode.has_indent_guides(), true);
457 assert_eq!(mode.max_rows(), usize::MAX);
458 assert_eq!(mode.min_rows(), 1);
459 assert_eq!(mode.is_folding(), true);
460
461 let mode = LayoutMode::CodeEditor {
462 line_number: false,
463 indent_guides: false,
464 folding: false,
465 rows: 0,
466 tab: Default::default(),
467 language: Box::default(),
468 highlighter: Default::default(),
469 highlighter_factory: None,
470 diagnostics: DiagnosticSet::new(&Rope::new()),
471 auto_closed_pairs: Default::default(),
472 auto_close: false,
473 smart_indent: false,
474 };
475 assert_eq!(mode.line_number(), false);
476 assert_eq!(mode.has_indent_guides(), false);
477 assert_eq!(mode.min_rows(), 1);
478 assert_eq!(mode.is_folding(), false);
479 assert_eq!(mode.is_auto_close(), false);
480 assert_eq!(mode.is_smart_indent(), false);
481 }
482
483 #[test]
484 fn test_plain() {
485 let mode = LayoutMode::PlainText {
486 tab: TabSize::default(),
487 rows: 5,
488 };
489 assert_eq!(mode.line_number(), false);
490 assert_eq!(mode.rows(), 5);
491 assert_eq!(mode.max_rows(), usize::MAX);
492 assert_eq!(mode.min_rows(), 1);
493
494 let mode = LayoutMode::plain_text();
495 assert_eq!(mode.line_number(), false);
496 assert_eq!(mode.rows(), 1);
497 assert_eq!(mode.min_rows(), 1);
498 }
499
500 #[test]
501 fn test_auto_grow() {
502 let mut mode = LayoutMode::auto_grow(2, 5);
503 assert_eq!(mode.line_number(), false);
504 assert_eq!(mode.rows(), 2);
505 assert_eq!(mode.max_rows(), 5);
506 assert_eq!(mode.min_rows(), 2);
507
508 mode.set_rows(4);
509 assert_eq!(mode.rows(), 4);
510
511 mode.set_rows(1);
512 assert_eq!(mode.rows(), 2);
513
514 mode.set_rows(10);
515 assert_eq!(mode.rows(), 5);
516 }
517}