1pub mod display_map;
2mod element;
3pub mod items;
4pub mod movement;
5mod multi_buffer;
6
7#[cfg(test)]
8mod test;
9
10use aho_corasick::AhoCorasick;
11use anyhow::Result;
12use clock::ReplicaId;
13use collections::{BTreeMap, Bound, HashMap, HashSet};
14pub use display_map::DisplayPoint;
15use display_map::*;
16pub use element::*;
17use fuzzy::{StringMatch, StringMatchCandidate};
18use gpui::{
19 action,
20 color::Color,
21 elements::*,
22 executor,
23 fonts::{self, HighlightStyle, TextStyle},
24 geometry::vector::{vec2f, Vector2F},
25 keymap::Binding,
26 platform::CursorStyle,
27 text_layout, AppContext, AsyncAppContext, ClipboardItem, Element, ElementBox, Entity,
28 ModelHandle, MutableAppContext, RenderContext, Task, View, ViewContext, ViewHandle,
29 WeakViewHandle,
30};
31use itertools::Itertools as _;
32pub use language::{char_kind, CharKind};
33use language::{
34 BracketPair, Buffer, CodeAction, CodeLabel, Completion, Diagnostic, DiagnosticSeverity,
35 Language, OffsetRangeExt, Point, Selection, SelectionGoal, TransactionId,
36};
37use multi_buffer::MultiBufferChunks;
38pub use multi_buffer::{
39 Anchor, AnchorRangeExt, ExcerptId, MultiBuffer, MultiBufferSnapshot, ToOffset, ToPoint,
40};
41use ordered_float::OrderedFloat;
42use project::{Project, ProjectTransaction};
43use serde::{Deserialize, Serialize};
44use smallvec::SmallVec;
45use smol::Timer;
46use snippet::Snippet;
47use std::{
48 any::TypeId,
49 cmp::{self, Ordering, Reverse},
50 iter::{self, FromIterator},
51 mem,
52 ops::{Deref, DerefMut, Range, RangeInclusive, Sub},
53 sync::Arc,
54 time::{Duration, Instant},
55};
56pub use sum_tree::Bias;
57use text::rope::TextDimension;
58use theme::DiagnosticStyle;
59use util::{post_inc, ResultExt, TryFutureExt};
60use workspace::{settings, ItemNavHistory, Settings, Workspace};
61
62const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
63const MAX_LINE_LEN: usize = 1024;
64const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
65
66action!(Cancel);
67action!(Backspace);
68action!(Delete);
69action!(Input, String);
70action!(Newline);
71action!(Tab);
72action!(Outdent);
73action!(DeleteLine);
74action!(DeleteToPreviousWordStart);
75action!(DeleteToPreviousSubwordStart);
76action!(DeleteToNextWordEnd);
77action!(DeleteToNextSubwordEnd);
78action!(DeleteToBeginningOfLine);
79action!(DeleteToEndOfLine);
80action!(CutToEndOfLine);
81action!(DuplicateLine);
82action!(MoveLineUp);
83action!(MoveLineDown);
84action!(Cut);
85action!(Copy);
86action!(Paste);
87action!(Undo);
88action!(Redo);
89action!(MoveUp);
90action!(MoveDown);
91action!(MoveLeft);
92action!(MoveRight);
93action!(MoveToPreviousWordStart);
94action!(MoveToPreviousSubwordStart);
95action!(MoveToNextWordEnd);
96action!(MoveToNextSubwordEnd);
97action!(MoveToBeginningOfLine);
98action!(MoveToEndOfLine);
99action!(MoveToBeginning);
100action!(MoveToEnd);
101action!(SelectUp);
102action!(SelectDown);
103action!(SelectLeft);
104action!(SelectRight);
105action!(SelectToPreviousWordStart);
106action!(SelectToPreviousSubwordStart);
107action!(SelectToNextWordEnd);
108action!(SelectToNextSubwordEnd);
109action!(SelectToBeginningOfLine, bool);
110action!(SelectToEndOfLine, bool);
111action!(SelectToBeginning);
112action!(SelectToEnd);
113action!(SelectAll);
114action!(SelectLine);
115action!(SplitSelectionIntoLines);
116action!(AddSelectionAbove);
117action!(AddSelectionBelow);
118action!(SelectNext, bool);
119action!(ToggleComments);
120action!(SelectLargerSyntaxNode);
121action!(SelectSmallerSyntaxNode);
122action!(MoveToEnclosingBracket);
123action!(GoToDiagnostic, Direction);
124action!(GoToDefinition);
125action!(FindAllReferences);
126action!(Rename);
127action!(ConfirmRename);
128action!(PageUp);
129action!(PageDown);
130action!(Fold);
131action!(UnfoldLines);
132action!(FoldSelectedRanges);
133action!(Scroll, Vector2F);
134action!(Select, SelectPhase);
135action!(ShowCompletions);
136action!(ToggleCodeActions, bool);
137action!(ConfirmCompletion, Option<usize>);
138action!(ConfirmCodeAction, Option<usize>);
139action!(OpenExcerpts);
140
141enum DocumentHighlightRead {}
142enum DocumentHighlightWrite {}
143
144#[derive(Copy, Clone, PartialEq, Eq)]
145pub enum Direction {
146 Prev,
147 Next,
148}
149
150pub fn init(cx: &mut MutableAppContext) {
151 cx.add_bindings(vec![
152 Binding::new("escape", Cancel, Some("Editor")),
153 Binding::new("backspace", Backspace, Some("Editor")),
154 Binding::new("ctrl-h", Backspace, Some("Editor")),
155 Binding::new("delete", Delete, Some("Editor")),
156 Binding::new("ctrl-d", Delete, Some("Editor")),
157 Binding::new("enter", Newline, Some("Editor && mode == full")),
158 Binding::new(
159 "alt-enter",
160 Input("\n".into()),
161 Some("Editor && mode == auto_height"),
162 ),
163 Binding::new(
164 "enter",
165 ConfirmCompletion(None),
166 Some("Editor && showing_completions"),
167 ),
168 Binding::new(
169 "enter",
170 ConfirmCodeAction(None),
171 Some("Editor && showing_code_actions"),
172 ),
173 Binding::new("enter", ConfirmRename, Some("Editor && renaming")),
174 Binding::new("tab", Tab, Some("Editor")),
175 Binding::new(
176 "tab",
177 ConfirmCompletion(None),
178 Some("Editor && showing_completions"),
179 ),
180 Binding::new("shift-tab", Outdent, Some("Editor")),
181 Binding::new("ctrl-shift-K", DeleteLine, Some("Editor")),
182 Binding::new("alt-backspace", DeleteToPreviousWordStart, Some("Editor")),
183 Binding::new("alt-h", DeleteToPreviousWordStart, Some("Editor")),
184 Binding::new(
185 "ctrl-alt-backspace",
186 DeleteToPreviousSubwordStart,
187 Some("Editor"),
188 ),
189 Binding::new("ctrl-alt-h", DeleteToPreviousSubwordStart, Some("Editor")),
190 Binding::new("alt-delete", DeleteToNextWordEnd, Some("Editor")),
191 Binding::new("alt-d", DeleteToNextWordEnd, Some("Editor")),
192 Binding::new("ctrl-alt-delete", DeleteToNextSubwordEnd, Some("Editor")),
193 Binding::new("ctrl-alt-d", DeleteToNextSubwordEnd, Some("Editor")),
194 Binding::new("cmd-backspace", DeleteToBeginningOfLine, Some("Editor")),
195 Binding::new("cmd-delete", DeleteToEndOfLine, Some("Editor")),
196 Binding::new("ctrl-k", CutToEndOfLine, Some("Editor")),
197 Binding::new("cmd-shift-D", DuplicateLine, Some("Editor")),
198 Binding::new("ctrl-cmd-up", MoveLineUp, Some("Editor")),
199 Binding::new("ctrl-cmd-down", MoveLineDown, Some("Editor")),
200 Binding::new("cmd-x", Cut, Some("Editor")),
201 Binding::new("cmd-c", Copy, Some("Editor")),
202 Binding::new("cmd-v", Paste, Some("Editor")),
203 Binding::new("cmd-z", Undo, Some("Editor")),
204 Binding::new("cmd-shift-Z", Redo, Some("Editor")),
205 Binding::new("up", MoveUp, Some("Editor")),
206 Binding::new("down", MoveDown, Some("Editor")),
207 Binding::new("left", MoveLeft, Some("Editor")),
208 Binding::new("right", MoveRight, Some("Editor")),
209 Binding::new("ctrl-p", MoveUp, Some("Editor")),
210 Binding::new("ctrl-n", MoveDown, Some("Editor")),
211 Binding::new("ctrl-b", MoveLeft, Some("Editor")),
212 Binding::new("ctrl-f", MoveRight, Some("Editor")),
213 Binding::new("alt-left", MoveToPreviousWordStart, Some("Editor")),
214 Binding::new("alt-b", MoveToPreviousWordStart, Some("Editor")),
215 Binding::new("ctrl-alt-left", MoveToPreviousSubwordStart, Some("Editor")),
216 Binding::new("ctrl-alt-b", MoveToPreviousSubwordStart, Some("Editor")),
217 Binding::new("alt-right", MoveToNextWordEnd, Some("Editor")),
218 Binding::new("alt-f", MoveToNextWordEnd, Some("Editor")),
219 Binding::new("ctrl-alt-right", MoveToNextSubwordEnd, Some("Editor")),
220 Binding::new("ctrl-alt-f", MoveToNextSubwordEnd, Some("Editor")),
221 Binding::new("cmd-left", MoveToBeginningOfLine, Some("Editor")),
222 Binding::new("ctrl-a", MoveToBeginningOfLine, Some("Editor")),
223 Binding::new("cmd-right", MoveToEndOfLine, Some("Editor")),
224 Binding::new("ctrl-e", MoveToEndOfLine, Some("Editor")),
225 Binding::new("cmd-up", MoveToBeginning, Some("Editor")),
226 Binding::new("cmd-down", MoveToEnd, Some("Editor")),
227 Binding::new("shift-up", SelectUp, Some("Editor")),
228 Binding::new("ctrl-shift-P", SelectUp, Some("Editor")),
229 Binding::new("shift-down", SelectDown, Some("Editor")),
230 Binding::new("ctrl-shift-N", SelectDown, Some("Editor")),
231 Binding::new("shift-left", SelectLeft, Some("Editor")),
232 Binding::new("ctrl-shift-B", SelectLeft, Some("Editor")),
233 Binding::new("shift-right", SelectRight, Some("Editor")),
234 Binding::new("ctrl-shift-F", SelectRight, Some("Editor")),
235 Binding::new("alt-shift-left", SelectToPreviousWordStart, Some("Editor")),
236 Binding::new("alt-shift-B", SelectToPreviousWordStart, Some("Editor")),
237 Binding::new(
238 "ctrl-alt-shift-left",
239 SelectToPreviousSubwordStart,
240 Some("Editor"),
241 ),
242 Binding::new(
243 "ctrl-alt-shift-B",
244 SelectToPreviousSubwordStart,
245 Some("Editor"),
246 ),
247 Binding::new("alt-shift-right", SelectToNextWordEnd, Some("Editor")),
248 Binding::new("alt-shift-F", SelectToNextWordEnd, Some("Editor")),
249 Binding::new(
250 "cmd-shift-left",
251 SelectToBeginningOfLine(true),
252 Some("Editor"),
253 ),
254 Binding::new(
255 "ctrl-alt-shift-right",
256 SelectToNextSubwordEnd,
257 Some("Editor"),
258 ),
259 Binding::new("ctrl-alt-shift-F", SelectToNextSubwordEnd, Some("Editor")),
260 Binding::new(
261 "ctrl-shift-A",
262 SelectToBeginningOfLine(true),
263 Some("Editor"),
264 ),
265 Binding::new("cmd-shift-right", SelectToEndOfLine(true), Some("Editor")),
266 Binding::new("ctrl-shift-E", SelectToEndOfLine(true), Some("Editor")),
267 Binding::new("cmd-shift-up", SelectToBeginning, Some("Editor")),
268 Binding::new("cmd-shift-down", SelectToEnd, Some("Editor")),
269 Binding::new("cmd-a", SelectAll, Some("Editor")),
270 Binding::new("cmd-l", SelectLine, Some("Editor")),
271 Binding::new("cmd-shift-L", SplitSelectionIntoLines, Some("Editor")),
272 Binding::new("cmd-alt-up", AddSelectionAbove, Some("Editor")),
273 Binding::new("cmd-ctrl-p", AddSelectionAbove, Some("Editor")),
274 Binding::new("cmd-alt-down", AddSelectionBelow, Some("Editor")),
275 Binding::new("cmd-ctrl-n", AddSelectionBelow, Some("Editor")),
276 Binding::new("cmd-d", SelectNext(false), Some("Editor")),
277 Binding::new("cmd-k cmd-d", SelectNext(true), Some("Editor")),
278 Binding::new("cmd-/", ToggleComments, Some("Editor")),
279 Binding::new("alt-up", SelectLargerSyntaxNode, Some("Editor")),
280 Binding::new("ctrl-w", SelectLargerSyntaxNode, Some("Editor")),
281 Binding::new("alt-down", SelectSmallerSyntaxNode, Some("Editor")),
282 Binding::new("ctrl-shift-W", SelectSmallerSyntaxNode, Some("Editor")),
283 Binding::new("f8", GoToDiagnostic(Direction::Next), Some("Editor")),
284 Binding::new("shift-f8", GoToDiagnostic(Direction::Prev), Some("Editor")),
285 Binding::new("f2", Rename, Some("Editor")),
286 Binding::new("f12", GoToDefinition, Some("Editor")),
287 Binding::new("alt-shift-f12", FindAllReferences, Some("Editor")),
288 Binding::new("ctrl-m", MoveToEnclosingBracket, Some("Editor")),
289 Binding::new("pageup", PageUp, Some("Editor")),
290 Binding::new("pagedown", PageDown, Some("Editor")),
291 Binding::new("alt-cmd-[", Fold, Some("Editor")),
292 Binding::new("alt-cmd-]", UnfoldLines, Some("Editor")),
293 Binding::new("alt-cmd-f", FoldSelectedRanges, Some("Editor")),
294 Binding::new("ctrl-space", ShowCompletions, Some("Editor")),
295 Binding::new("cmd-.", ToggleCodeActions(false), Some("Editor")),
296 Binding::new("alt-enter", OpenExcerpts, Some("Editor")),
297 ]);
298
299 cx.add_action(Editor::open_new);
300 cx.add_action(|this: &mut Editor, action: &Scroll, cx| this.set_scroll_position(action.0, cx));
301 cx.add_action(Editor::select);
302 cx.add_action(Editor::cancel);
303 cx.add_action(Editor::handle_input);
304 cx.add_action(Editor::newline);
305 cx.add_action(Editor::backspace);
306 cx.add_action(Editor::delete);
307 cx.add_action(Editor::tab);
308 cx.add_action(Editor::outdent);
309 cx.add_action(Editor::delete_line);
310 cx.add_action(Editor::delete_to_previous_word_start);
311 cx.add_action(Editor::delete_to_previous_subword_start);
312 cx.add_action(Editor::delete_to_next_word_end);
313 cx.add_action(Editor::delete_to_next_subword_end);
314 cx.add_action(Editor::delete_to_beginning_of_line);
315 cx.add_action(Editor::delete_to_end_of_line);
316 cx.add_action(Editor::cut_to_end_of_line);
317 cx.add_action(Editor::duplicate_line);
318 cx.add_action(Editor::move_line_up);
319 cx.add_action(Editor::move_line_down);
320 cx.add_action(Editor::cut);
321 cx.add_action(Editor::copy);
322 cx.add_action(Editor::paste);
323 cx.add_action(Editor::undo);
324 cx.add_action(Editor::redo);
325 cx.add_action(Editor::move_up);
326 cx.add_action(Editor::move_down);
327 cx.add_action(Editor::move_left);
328 cx.add_action(Editor::move_right);
329 cx.add_action(Editor::move_to_previous_word_start);
330 cx.add_action(Editor::move_to_previous_subword_start);
331 cx.add_action(Editor::move_to_next_word_end);
332 cx.add_action(Editor::move_to_next_subword_end);
333 cx.add_action(Editor::move_to_beginning_of_line);
334 cx.add_action(Editor::move_to_end_of_line);
335 cx.add_action(Editor::move_to_beginning);
336 cx.add_action(Editor::move_to_end);
337 cx.add_action(Editor::select_up);
338 cx.add_action(Editor::select_down);
339 cx.add_action(Editor::select_left);
340 cx.add_action(Editor::select_right);
341 cx.add_action(Editor::select_to_previous_word_start);
342 cx.add_action(Editor::select_to_previous_subword_start);
343 cx.add_action(Editor::select_to_next_word_end);
344 cx.add_action(Editor::select_to_next_subword_end);
345 cx.add_action(Editor::select_to_beginning_of_line);
346 cx.add_action(Editor::select_to_end_of_line);
347 cx.add_action(Editor::select_to_beginning);
348 cx.add_action(Editor::select_to_end);
349 cx.add_action(Editor::select_all);
350 cx.add_action(Editor::select_line);
351 cx.add_action(Editor::split_selection_into_lines);
352 cx.add_action(Editor::add_selection_above);
353 cx.add_action(Editor::add_selection_below);
354 cx.add_action(Editor::select_next);
355 cx.add_action(Editor::toggle_comments);
356 cx.add_action(Editor::select_larger_syntax_node);
357 cx.add_action(Editor::select_smaller_syntax_node);
358 cx.add_action(Editor::move_to_enclosing_bracket);
359 cx.add_action(Editor::go_to_diagnostic);
360 cx.add_action(Editor::go_to_definition);
361 cx.add_action(Editor::page_up);
362 cx.add_action(Editor::page_down);
363 cx.add_action(Editor::fold);
364 cx.add_action(Editor::unfold_lines);
365 cx.add_action(Editor::fold_selected_ranges);
366 cx.add_action(Editor::show_completions);
367 cx.add_action(Editor::toggle_code_actions);
368 cx.add_action(Editor::open_excerpts);
369 cx.add_async_action(Editor::confirm_completion);
370 cx.add_async_action(Editor::confirm_code_action);
371 cx.add_async_action(Editor::rename);
372 cx.add_async_action(Editor::confirm_rename);
373 cx.add_async_action(Editor::find_all_references);
374
375 workspace::register_project_item::<Editor>(cx);
376 workspace::register_followable_item::<Editor>(cx);
377}
378
379trait InvalidationRegion {
380 fn ranges(&self) -> &[Range<Anchor>];
381}
382
383#[derive(Clone, Debug)]
384pub enum SelectPhase {
385 Begin {
386 position: DisplayPoint,
387 add: bool,
388 click_count: usize,
389 },
390 BeginColumnar {
391 position: DisplayPoint,
392 overshoot: u32,
393 },
394 Extend {
395 position: DisplayPoint,
396 click_count: usize,
397 },
398 Update {
399 position: DisplayPoint,
400 overshoot: u32,
401 scroll_position: Vector2F,
402 },
403 End,
404}
405
406#[derive(Clone, Debug)]
407pub enum SelectMode {
408 Character,
409 Word(Range<Anchor>),
410 Line(Range<Anchor>),
411 All,
412}
413
414#[derive(PartialEq, Eq)]
415pub enum Autoscroll {
416 Fit,
417 Center,
418 Newest,
419}
420
421#[derive(Copy, Clone, PartialEq, Eq)]
422pub enum EditorMode {
423 SingleLine,
424 AutoHeight { max_lines: usize },
425 Full,
426}
427
428#[derive(Clone)]
429pub enum SoftWrap {
430 None,
431 EditorWidth,
432 Column(u32),
433}
434
435#[derive(Clone)]
436pub struct EditorStyle {
437 pub text: TextStyle,
438 pub placeholder_text: Option<TextStyle>,
439 pub theme: theme::Editor,
440}
441
442type CompletionId = usize;
443
444pub type GetFieldEditorTheme = fn(&theme::Theme) -> theme::FieldEditor;
445
446type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
447
448pub struct Editor {
449 handle: WeakViewHandle<Self>,
450 buffer: ModelHandle<MultiBuffer>,
451 display_map: ModelHandle<DisplayMap>,
452 next_selection_id: usize,
453 selections: Arc<[Selection<Anchor>]>,
454 pending_selection: Option<PendingSelection>,
455 columnar_selection_tail: Option<Anchor>,
456 add_selections_state: Option<AddSelectionsState>,
457 select_next_state: Option<SelectNextState>,
458 selection_history:
459 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
460 autoclose_stack: InvalidationStack<BracketPairState>,
461 snippet_stack: InvalidationStack<SnippetState>,
462 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
463 active_diagnostics: Option<ActiveDiagnosticGroup>,
464 scroll_position: Vector2F,
465 scroll_top_anchor: Anchor,
466 autoscroll_request: Option<(Autoscroll, bool)>,
467 soft_wrap_mode_override: Option<settings::SoftWrap>,
468 get_field_editor_theme: Option<GetFieldEditorTheme>,
469 override_text_style: Option<Box<OverrideTextStyle>>,
470 project: Option<ModelHandle<Project>>,
471 focused: bool,
472 show_local_cursors: bool,
473 show_local_selections: bool,
474 blink_epoch: usize,
475 blinking_paused: bool,
476 mode: EditorMode,
477 vertical_scroll_margin: f32,
478 placeholder_text: Option<Arc<str>>,
479 highlighted_rows: Option<Range<u32>>,
480 background_highlights: BTreeMap<TypeId, (Color, Vec<Range<Anchor>>)>,
481 nav_history: Option<ItemNavHistory>,
482 context_menu: Option<ContextMenu>,
483 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
484 next_completion_id: CompletionId,
485 available_code_actions: Option<(ModelHandle<Buffer>, Arc<[CodeAction]>)>,
486 code_actions_task: Option<Task<()>>,
487 document_highlights_task: Option<Task<()>>,
488 pending_rename: Option<RenameState>,
489 searchable: bool,
490 cursor_shape: CursorShape,
491 keymap_context_layers: BTreeMap<TypeId, gpui::keymap::Context>,
492 input_enabled: bool,
493 leader_replica_id: Option<u16>,
494}
495
496pub struct EditorSnapshot {
497 pub mode: EditorMode,
498 pub display_snapshot: DisplaySnapshot,
499 pub placeholder_text: Option<Arc<str>>,
500 is_focused: bool,
501 scroll_position: Vector2F,
502 scroll_top_anchor: Anchor,
503}
504
505#[derive(Clone)]
506pub struct PendingSelection {
507 selection: Selection<Anchor>,
508 mode: SelectMode,
509}
510
511struct AddSelectionsState {
512 above: bool,
513 stack: Vec<usize>,
514}
515
516struct SelectNextState {
517 query: AhoCorasick,
518 wordwise: bool,
519 done: bool,
520}
521
522struct BracketPairState {
523 ranges: Vec<Range<Anchor>>,
524 pair: BracketPair,
525}
526
527struct SnippetState {
528 ranges: Vec<Vec<Range<Anchor>>>,
529 active_index: usize,
530}
531
532pub struct RenameState {
533 pub range: Range<Anchor>,
534 pub old_name: String,
535 pub editor: ViewHandle<Editor>,
536 block_id: BlockId,
537}
538
539struct InvalidationStack<T>(Vec<T>);
540
541enum ContextMenu {
542 Completions(CompletionsMenu),
543 CodeActions(CodeActionsMenu),
544}
545
546impl ContextMenu {
547 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) -> bool {
548 if self.visible() {
549 match self {
550 ContextMenu::Completions(menu) => menu.select_prev(cx),
551 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
552 }
553 true
554 } else {
555 false
556 }
557 }
558
559 fn select_next(&mut self, cx: &mut ViewContext<Editor>) -> bool {
560 if self.visible() {
561 match self {
562 ContextMenu::Completions(menu) => menu.select_next(cx),
563 ContextMenu::CodeActions(menu) => menu.select_next(cx),
564 }
565 true
566 } else {
567 false
568 }
569 }
570
571 fn visible(&self) -> bool {
572 match self {
573 ContextMenu::Completions(menu) => menu.visible(),
574 ContextMenu::CodeActions(menu) => menu.visible(),
575 }
576 }
577
578 fn render(
579 &self,
580 cursor_position: DisplayPoint,
581 style: EditorStyle,
582 cx: &AppContext,
583 ) -> (DisplayPoint, ElementBox) {
584 match self {
585 ContextMenu::Completions(menu) => (cursor_position, menu.render(style, cx)),
586 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style),
587 }
588 }
589}
590
591struct CompletionsMenu {
592 id: CompletionId,
593 initial_position: Anchor,
594 buffer: ModelHandle<Buffer>,
595 completions: Arc<[Completion]>,
596 match_candidates: Vec<StringMatchCandidate>,
597 matches: Arc<[StringMatch]>,
598 selected_item: usize,
599 list: UniformListState,
600}
601
602impl CompletionsMenu {
603 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
604 if self.selected_item > 0 {
605 self.selected_item -= 1;
606 self.list.scroll_to(ScrollTarget::Show(self.selected_item));
607 }
608 cx.notify();
609 }
610
611 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
612 if self.selected_item + 1 < self.matches.len() {
613 self.selected_item += 1;
614 self.list.scroll_to(ScrollTarget::Show(self.selected_item));
615 }
616 cx.notify();
617 }
618
619 fn visible(&self) -> bool {
620 !self.matches.is_empty()
621 }
622
623 fn render(&self, style: EditorStyle, _: &AppContext) -> ElementBox {
624 enum CompletionTag {}
625
626 let completions = self.completions.clone();
627 let matches = self.matches.clone();
628 let selected_item = self.selected_item;
629 let container_style = style.autocomplete.container;
630 UniformList::new(self.list.clone(), matches.len(), move |range, items, cx| {
631 let start_ix = range.start;
632 for (ix, mat) in matches[range].iter().enumerate() {
633 let completion = &completions[mat.candidate_id];
634 let item_ix = start_ix + ix;
635 items.push(
636 MouseEventHandler::new::<CompletionTag, _, _>(
637 mat.candidate_id,
638 cx,
639 |state, _| {
640 let item_style = if item_ix == selected_item {
641 style.autocomplete.selected_item
642 } else if state.hovered {
643 style.autocomplete.hovered_item
644 } else {
645 style.autocomplete.item
646 };
647
648 Text::new(completion.label.text.clone(), style.text.clone())
649 .with_soft_wrap(false)
650 .with_highlights(combine_syntax_and_fuzzy_match_highlights(
651 &completion.label.text,
652 style.text.color.into(),
653 styled_runs_for_code_label(&completion.label, &style.syntax),
654 &mat.positions,
655 ))
656 .contained()
657 .with_style(item_style)
658 .boxed()
659 },
660 )
661 .with_cursor_style(CursorStyle::PointingHand)
662 .on_mouse_down(move |cx| {
663 cx.dispatch_action(ConfirmCompletion(Some(item_ix)));
664 })
665 .boxed(),
666 );
667 }
668 })
669 .with_width_from_item(
670 self.matches
671 .iter()
672 .enumerate()
673 .max_by_key(|(_, mat)| {
674 self.completions[mat.candidate_id]
675 .label
676 .text
677 .chars()
678 .count()
679 })
680 .map(|(ix, _)| ix),
681 )
682 .contained()
683 .with_style(container_style)
684 .boxed()
685 }
686
687 pub async fn filter(&mut self, query: Option<&str>, executor: Arc<executor::Background>) {
688 let mut matches = if let Some(query) = query {
689 fuzzy::match_strings(
690 &self.match_candidates,
691 query,
692 false,
693 100,
694 &Default::default(),
695 executor,
696 )
697 .await
698 } else {
699 self.match_candidates
700 .iter()
701 .enumerate()
702 .map(|(candidate_id, candidate)| StringMatch {
703 candidate_id,
704 score: Default::default(),
705 positions: Default::default(),
706 string: candidate.string.clone(),
707 })
708 .collect()
709 };
710 matches.sort_unstable_by_key(|mat| {
711 (
712 Reverse(OrderedFloat(mat.score)),
713 self.completions[mat.candidate_id].sort_key(),
714 )
715 });
716
717 for mat in &mut matches {
718 let filter_start = self.completions[mat.candidate_id].label.filter_range.start;
719 for position in &mut mat.positions {
720 *position += filter_start;
721 }
722 }
723
724 self.matches = matches.into();
725 }
726}
727
728#[derive(Clone)]
729struct CodeActionsMenu {
730 actions: Arc<[CodeAction]>,
731 buffer: ModelHandle<Buffer>,
732 selected_item: usize,
733 list: UniformListState,
734 deployed_from_indicator: bool,
735}
736
737impl CodeActionsMenu {
738 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
739 if self.selected_item > 0 {
740 self.selected_item -= 1;
741 cx.notify()
742 }
743 }
744
745 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
746 if self.selected_item + 1 < self.actions.len() {
747 self.selected_item += 1;
748 cx.notify()
749 }
750 }
751
752 fn visible(&self) -> bool {
753 !self.actions.is_empty()
754 }
755
756 fn render(
757 &self,
758 mut cursor_position: DisplayPoint,
759 style: EditorStyle,
760 ) -> (DisplayPoint, ElementBox) {
761 enum ActionTag {}
762
763 let container_style = style.autocomplete.container;
764 let actions = self.actions.clone();
765 let selected_item = self.selected_item;
766 let element =
767 UniformList::new(self.list.clone(), actions.len(), move |range, items, cx| {
768 let start_ix = range.start;
769 for (ix, action) in actions[range].iter().enumerate() {
770 let item_ix = start_ix + ix;
771 items.push(
772 MouseEventHandler::new::<ActionTag, _, _>(item_ix, cx, |state, _| {
773 let item_style = if item_ix == selected_item {
774 style.autocomplete.selected_item
775 } else if state.hovered {
776 style.autocomplete.hovered_item
777 } else {
778 style.autocomplete.item
779 };
780
781 Text::new(action.lsp_action.title.clone(), style.text.clone())
782 .with_soft_wrap(false)
783 .contained()
784 .with_style(item_style)
785 .boxed()
786 })
787 .with_cursor_style(CursorStyle::PointingHand)
788 .on_mouse_down(move |cx| {
789 cx.dispatch_action(ConfirmCodeAction(Some(item_ix)));
790 })
791 .boxed(),
792 );
793 }
794 })
795 .with_width_from_item(
796 self.actions
797 .iter()
798 .enumerate()
799 .max_by_key(|(_, action)| action.lsp_action.title.chars().count())
800 .map(|(ix, _)| ix),
801 )
802 .contained()
803 .with_style(container_style)
804 .boxed();
805
806 if self.deployed_from_indicator {
807 *cursor_position.column_mut() = 0;
808 }
809
810 (cursor_position, element)
811 }
812}
813
814#[derive(Debug)]
815struct ActiveDiagnosticGroup {
816 primary_range: Range<Anchor>,
817 primary_message: String,
818 blocks: HashMap<BlockId, Diagnostic>,
819 is_valid: bool,
820}
821
822#[derive(Serialize, Deserialize)]
823struct ClipboardSelection {
824 len: usize,
825 is_entire_line: bool,
826}
827
828pub struct NavigationData {
829 anchor: Anchor,
830 offset: usize,
831}
832
833pub struct EditorCreated(pub ViewHandle<Editor>);
834
835impl Editor {
836 pub fn single_line(
837 field_editor_style: Option<GetFieldEditorTheme>,
838 cx: &mut ViewContext<Self>,
839 ) -> Self {
840 let buffer = cx.add_model(|cx| Buffer::new(0, String::new(), cx));
841 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
842 Self::new(EditorMode::SingleLine, buffer, None, field_editor_style, cx)
843 }
844
845 pub fn auto_height(
846 max_lines: usize,
847 field_editor_style: Option<GetFieldEditorTheme>,
848 cx: &mut ViewContext<Self>,
849 ) -> Self {
850 let buffer = cx.add_model(|cx| Buffer::new(0, String::new(), cx));
851 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
852 Self::new(
853 EditorMode::AutoHeight { max_lines },
854 buffer,
855 None,
856 field_editor_style,
857 cx,
858 )
859 }
860
861 pub fn for_buffer(
862 buffer: ModelHandle<Buffer>,
863 project: Option<ModelHandle<Project>>,
864 cx: &mut ViewContext<Self>,
865 ) -> Self {
866 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
867 Self::new(EditorMode::Full, buffer, project, None, cx)
868 }
869
870 pub fn for_multibuffer(
871 buffer: ModelHandle<MultiBuffer>,
872 project: Option<ModelHandle<Project>>,
873 cx: &mut ViewContext<Self>,
874 ) -> Self {
875 Self::new(EditorMode::Full, buffer, project, None, cx)
876 }
877
878 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
879 let mut clone = Self::new(
880 self.mode,
881 self.buffer.clone(),
882 self.project.clone(),
883 self.get_field_editor_theme,
884 cx,
885 );
886 clone.scroll_position = self.scroll_position;
887 clone.scroll_top_anchor = self.scroll_top_anchor.clone();
888 clone.searchable = self.searchable;
889 clone
890 }
891
892 fn new(
893 mode: EditorMode,
894 buffer: ModelHandle<MultiBuffer>,
895 project: Option<ModelHandle<Project>>,
896 get_field_editor_theme: Option<GetFieldEditorTheme>,
897 cx: &mut ViewContext<Self>,
898 ) -> Self {
899 let display_map = cx.add_model(|cx| {
900 let settings = cx.global::<Settings>();
901 let style = build_style(&*settings, get_field_editor_theme, None, cx);
902 DisplayMap::new(
903 buffer.clone(),
904 settings.tab_size,
905 style.text.font_id,
906 style.text.font_size,
907 None,
908 2,
909 1,
910 cx,
911 )
912 });
913 cx.observe(&buffer, Self::on_buffer_changed).detach();
914 cx.subscribe(&buffer, Self::on_buffer_event).detach();
915 cx.observe(&display_map, Self::on_display_map_changed)
916 .detach();
917
918 let mut this = Self {
919 handle: cx.weak_handle(),
920 buffer,
921 display_map,
922 selections: Arc::from([]),
923 pending_selection: Some(PendingSelection {
924 selection: Selection {
925 id: 0,
926 start: Anchor::min(),
927 end: Anchor::min(),
928 reversed: false,
929 goal: SelectionGoal::None,
930 },
931 mode: SelectMode::Character,
932 }),
933 columnar_selection_tail: None,
934 next_selection_id: 1,
935 add_selections_state: None,
936 select_next_state: None,
937 selection_history: Default::default(),
938 autoclose_stack: Default::default(),
939 snippet_stack: Default::default(),
940 select_larger_syntax_node_stack: Vec::new(),
941 active_diagnostics: None,
942 soft_wrap_mode_override: None,
943 get_field_editor_theme,
944 project,
945 scroll_position: Vector2F::zero(),
946 scroll_top_anchor: Anchor::min(),
947 autoscroll_request: None,
948 focused: false,
949 show_local_cursors: false,
950 show_local_selections: true,
951 blink_epoch: 0,
952 blinking_paused: false,
953 mode,
954 vertical_scroll_margin: 3.0,
955 placeholder_text: None,
956 highlighted_rows: None,
957 background_highlights: Default::default(),
958 nav_history: None,
959 context_menu: None,
960 completion_tasks: Default::default(),
961 next_completion_id: 0,
962 available_code_actions: Default::default(),
963 code_actions_task: Default::default(),
964 document_highlights_task: Default::default(),
965 pending_rename: Default::default(),
966 searchable: true,
967 override_text_style: None,
968 cursor_shape: Default::default(),
969 keymap_context_layers: Default::default(),
970 input_enabled: true,
971 leader_replica_id: None,
972 };
973 this.end_selection(cx);
974
975 let editor_created_event = EditorCreated(cx.handle());
976 cx.emit_global(editor_created_event);
977
978 this
979 }
980
981 pub fn open_new(
982 workspace: &mut Workspace,
983 _: &workspace::OpenNew,
984 cx: &mut ViewContext<Workspace>,
985 ) {
986 let project = workspace.project().clone();
987 if project.read(cx).is_remote() {
988 cx.propagate_action();
989 } else if let Some(buffer) = project
990 .update(cx, |project, cx| project.create_buffer(cx))
991 .log_err()
992 {
993 workspace.add_item(
994 Box::new(cx.add_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx))),
995 cx,
996 );
997 }
998 }
999
1000 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
1001 self.buffer.read(cx).replica_id()
1002 }
1003
1004 pub fn buffer(&self) -> &ModelHandle<MultiBuffer> {
1005 &self.buffer
1006 }
1007
1008 pub fn title(&self, cx: &AppContext) -> String {
1009 self.buffer().read(cx).title(cx)
1010 }
1011
1012 pub fn snapshot(&mut self, cx: &mut MutableAppContext) -> EditorSnapshot {
1013 EditorSnapshot {
1014 mode: self.mode,
1015 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1016 scroll_position: self.scroll_position,
1017 scroll_top_anchor: self.scroll_top_anchor.clone(),
1018 placeholder_text: self.placeholder_text.clone(),
1019 is_focused: self
1020 .handle
1021 .upgrade(cx)
1022 .map_or(false, |handle| handle.is_focused(cx)),
1023 }
1024 }
1025
1026 pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc<Language>> {
1027 self.buffer.read(cx).language(cx)
1028 }
1029
1030 fn style(&self, cx: &AppContext) -> EditorStyle {
1031 build_style(
1032 cx.global::<Settings>(),
1033 self.get_field_editor_theme,
1034 self.override_text_style.as_deref(),
1035 cx,
1036 )
1037 }
1038
1039 pub fn mode(&self) -> EditorMode {
1040 self.mode
1041 }
1042
1043 pub fn set_placeholder_text(
1044 &mut self,
1045 placeholder_text: impl Into<Arc<str>>,
1046 cx: &mut ViewContext<Self>,
1047 ) {
1048 self.placeholder_text = Some(placeholder_text.into());
1049 cx.notify();
1050 }
1051
1052 pub fn set_vertical_scroll_margin(&mut self, margin_rows: usize, cx: &mut ViewContext<Self>) {
1053 self.vertical_scroll_margin = margin_rows as f32;
1054 cx.notify();
1055 }
1056
1057 pub fn set_scroll_position(&mut self, scroll_position: Vector2F, cx: &mut ViewContext<Self>) {
1058 self.set_scroll_position_internal(scroll_position, true, cx);
1059 }
1060
1061 fn set_scroll_position_internal(
1062 &mut self,
1063 scroll_position: Vector2F,
1064 local: bool,
1065 cx: &mut ViewContext<Self>,
1066 ) {
1067 let map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1068
1069 if scroll_position.y() == 0. {
1070 self.scroll_top_anchor = Anchor::min();
1071 self.scroll_position = scroll_position;
1072 } else {
1073 let scroll_top_buffer_offset =
1074 DisplayPoint::new(scroll_position.y() as u32, 0).to_offset(&map, Bias::Right);
1075 let anchor = map
1076 .buffer_snapshot
1077 .anchor_at(scroll_top_buffer_offset, Bias::Right);
1078 self.scroll_position = vec2f(
1079 scroll_position.x(),
1080 scroll_position.y() - anchor.to_display_point(&map).row() as f32,
1081 );
1082 self.scroll_top_anchor = anchor;
1083 }
1084
1085 cx.emit(Event::ScrollPositionChanged { local });
1086 cx.notify();
1087 }
1088
1089 fn set_scroll_top_anchor(
1090 &mut self,
1091 anchor: Anchor,
1092 position: Vector2F,
1093 cx: &mut ViewContext<Self>,
1094 ) {
1095 self.scroll_top_anchor = anchor;
1096 self.scroll_position = position;
1097 cx.emit(Event::ScrollPositionChanged { local: false });
1098 cx.notify();
1099 }
1100
1101 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1102 self.cursor_shape = cursor_shape;
1103 cx.notify();
1104 }
1105
1106 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1107 self.display_map
1108 .update(cx, |map, _| map.clip_at_line_ends = clip);
1109 }
1110
1111 pub fn set_keymap_context_layer<Tag: 'static>(&mut self, context: gpui::keymap::Context) {
1112 self.keymap_context_layers
1113 .insert(TypeId::of::<Tag>(), context);
1114 }
1115
1116 pub fn remove_keymap_context_layer<Tag: 'static>(&mut self) {
1117 self.keymap_context_layers.remove(&TypeId::of::<Tag>());
1118 }
1119
1120 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1121 self.input_enabled = input_enabled;
1122 }
1123
1124 pub fn scroll_position(&self, cx: &mut ViewContext<Self>) -> Vector2F {
1125 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1126 compute_scroll_position(&display_map, self.scroll_position, &self.scroll_top_anchor)
1127 }
1128
1129 pub fn clamp_scroll_left(&mut self, max: f32) -> bool {
1130 if max < self.scroll_position.x() {
1131 self.scroll_position.set_x(max);
1132 true
1133 } else {
1134 false
1135 }
1136 }
1137
1138 pub fn autoscroll_vertically(
1139 &mut self,
1140 viewport_height: f32,
1141 line_height: f32,
1142 cx: &mut ViewContext<Self>,
1143 ) -> bool {
1144 let visible_lines = viewport_height / line_height;
1145 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1146 let mut scroll_position =
1147 compute_scroll_position(&display_map, self.scroll_position, &self.scroll_top_anchor);
1148 let max_scroll_top = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
1149 (display_map.max_point().row() as f32 - visible_lines + 1.).max(0.)
1150 } else {
1151 display_map.max_point().row().saturating_sub(1) as f32
1152 };
1153 if scroll_position.y() > max_scroll_top {
1154 scroll_position.set_y(max_scroll_top);
1155 self.set_scroll_position(scroll_position, cx);
1156 }
1157
1158 let (autoscroll, local) = if let Some(autoscroll) = self.autoscroll_request.take() {
1159 autoscroll
1160 } else {
1161 return false;
1162 };
1163
1164 let first_cursor_top;
1165 let last_cursor_bottom;
1166 if let Some(highlighted_rows) = &self.highlighted_rows {
1167 first_cursor_top = highlighted_rows.start as f32;
1168 last_cursor_bottom = first_cursor_top + 1.;
1169 } else if autoscroll == Autoscroll::Newest {
1170 let newest_selection =
1171 self.newest_selection_with_snapshot::<Point>(&display_map.buffer_snapshot);
1172 first_cursor_top = newest_selection.head().to_display_point(&display_map).row() as f32;
1173 last_cursor_bottom = first_cursor_top + 1.;
1174 } else {
1175 let selections = self.local_selections::<Point>(cx);
1176 first_cursor_top = selections
1177 .first()
1178 .unwrap()
1179 .head()
1180 .to_display_point(&display_map)
1181 .row() as f32;
1182 last_cursor_bottom = selections
1183 .last()
1184 .unwrap()
1185 .head()
1186 .to_display_point(&display_map)
1187 .row() as f32
1188 + 1.0;
1189 }
1190
1191 let margin = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
1192 0.
1193 } else {
1194 ((visible_lines - (last_cursor_bottom - first_cursor_top)) / 2.0).floor()
1195 };
1196 if margin < 0.0 {
1197 return false;
1198 }
1199
1200 match autoscroll {
1201 Autoscroll::Fit | Autoscroll::Newest => {
1202 let margin = margin.min(self.vertical_scroll_margin);
1203 let target_top = (first_cursor_top - margin).max(0.0);
1204 let target_bottom = last_cursor_bottom + margin;
1205 let start_row = scroll_position.y();
1206 let end_row = start_row + visible_lines;
1207
1208 if target_top < start_row {
1209 scroll_position.set_y(target_top);
1210 self.set_scroll_position_internal(scroll_position, local, cx);
1211 } else if target_bottom >= end_row {
1212 scroll_position.set_y(target_bottom - visible_lines);
1213 self.set_scroll_position_internal(scroll_position, local, cx);
1214 }
1215 }
1216 Autoscroll::Center => {
1217 scroll_position.set_y((first_cursor_top - margin).max(0.0));
1218 self.set_scroll_position_internal(scroll_position, local, cx);
1219 }
1220 }
1221
1222 true
1223 }
1224
1225 pub fn autoscroll_horizontally(
1226 &mut self,
1227 start_row: u32,
1228 viewport_width: f32,
1229 scroll_width: f32,
1230 max_glyph_width: f32,
1231 layouts: &[text_layout::Line],
1232 cx: &mut ViewContext<Self>,
1233 ) -> bool {
1234 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1235 let selections = self.local_selections::<Point>(cx);
1236
1237 let mut target_left;
1238 let mut target_right;
1239
1240 if self.highlighted_rows.is_some() {
1241 target_left = 0.0_f32;
1242 target_right = 0.0_f32;
1243 } else {
1244 target_left = std::f32::INFINITY;
1245 target_right = 0.0_f32;
1246 for selection in selections {
1247 let head = selection.head().to_display_point(&display_map);
1248 if head.row() >= start_row && head.row() < start_row + layouts.len() as u32 {
1249 let start_column = head.column().saturating_sub(3);
1250 let end_column = cmp::min(display_map.line_len(head.row()), head.column() + 3);
1251 target_left = target_left.min(
1252 layouts[(head.row() - start_row) as usize]
1253 .x_for_index(start_column as usize),
1254 );
1255 target_right = target_right.max(
1256 layouts[(head.row() - start_row) as usize].x_for_index(end_column as usize)
1257 + max_glyph_width,
1258 );
1259 }
1260 }
1261 }
1262
1263 target_right = target_right.min(scroll_width);
1264
1265 if target_right - target_left > viewport_width {
1266 return false;
1267 }
1268
1269 let scroll_left = self.scroll_position.x() * max_glyph_width;
1270 let scroll_right = scroll_left + viewport_width;
1271
1272 if target_left < scroll_left {
1273 self.scroll_position.set_x(target_left / max_glyph_width);
1274 true
1275 } else if target_right > scroll_right {
1276 self.scroll_position
1277 .set_x((target_right - viewport_width) / max_glyph_width);
1278 true
1279 } else {
1280 false
1281 }
1282 }
1283
1284 pub fn replace_selections_with(
1285 &mut self,
1286 cx: &mut ViewContext<Self>,
1287 find_replacement: impl Fn(&DisplaySnapshot) -> DisplayPoint,
1288 ) {
1289 let display_map = self.snapshot(cx);
1290 let cursor = find_replacement(&display_map);
1291 let selection = Selection {
1292 id: post_inc(&mut self.next_selection_id),
1293 start: cursor,
1294 end: cursor,
1295 reversed: false,
1296 goal: SelectionGoal::None,
1297 }
1298 .map(|display_point| display_point.to_point(&display_map));
1299 self.update_selections(vec![selection], None, cx);
1300 }
1301
1302 pub fn move_selections(
1303 &mut self,
1304 cx: &mut ViewContext<Self>,
1305 move_selection: impl Fn(&DisplaySnapshot, &mut Selection<DisplayPoint>),
1306 ) {
1307 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1308 let selections = self
1309 .local_selections::<Point>(cx)
1310 .into_iter()
1311 .map(|selection| {
1312 let mut selection = selection.map(|point| point.to_display_point(&display_map));
1313 move_selection(&display_map, &mut selection);
1314 selection.map(|display_point| display_point.to_point(&display_map))
1315 })
1316 .collect();
1317 self.update_selections(selections, Some(Autoscroll::Fit), cx);
1318 }
1319
1320 pub fn move_selection_heads(
1321 &mut self,
1322 cx: &mut ViewContext<Self>,
1323 update_head: impl Fn(
1324 &DisplaySnapshot,
1325 DisplayPoint,
1326 SelectionGoal,
1327 ) -> (DisplayPoint, SelectionGoal),
1328 ) {
1329 self.move_selections(cx, |map, selection| {
1330 let (new_head, new_goal) = update_head(map, selection.head(), selection.goal);
1331 selection.set_head(new_head, new_goal);
1332 });
1333 }
1334
1335 pub fn move_cursors(
1336 &mut self,
1337 cx: &mut ViewContext<Self>,
1338 update_cursor_position: impl Fn(
1339 &DisplaySnapshot,
1340 DisplayPoint,
1341 SelectionGoal,
1342 ) -> (DisplayPoint, SelectionGoal),
1343 ) {
1344 self.move_selections(cx, |map, selection| {
1345 let (cursor, new_goal) = update_cursor_position(map, selection.head(), selection.goal);
1346 selection.collapse_to(cursor, new_goal)
1347 });
1348 }
1349
1350 fn select(&mut self, Select(phase): &Select, cx: &mut ViewContext<Self>) {
1351 self.hide_context_menu(cx);
1352
1353 match phase {
1354 SelectPhase::Begin {
1355 position,
1356 add,
1357 click_count,
1358 } => self.begin_selection(*position, *add, *click_count, cx),
1359 SelectPhase::BeginColumnar {
1360 position,
1361 overshoot,
1362 } => self.begin_columnar_selection(*position, *overshoot, cx),
1363 SelectPhase::Extend {
1364 position,
1365 click_count,
1366 } => self.extend_selection(*position, *click_count, cx),
1367 SelectPhase::Update {
1368 position,
1369 overshoot,
1370 scroll_position,
1371 } => self.update_selection(*position, *overshoot, *scroll_position, cx),
1372 SelectPhase::End => self.end_selection(cx),
1373 }
1374 }
1375
1376 fn extend_selection(
1377 &mut self,
1378 position: DisplayPoint,
1379 click_count: usize,
1380 cx: &mut ViewContext<Self>,
1381 ) {
1382 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1383 let tail = self
1384 .newest_selection_with_snapshot::<usize>(&display_map.buffer_snapshot)
1385 .tail();
1386 self.begin_selection(position, false, click_count, cx);
1387
1388 let position = position.to_offset(&display_map, Bias::Left);
1389 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
1390 let mut pending = self.pending_selection.clone().unwrap();
1391
1392 if position >= tail {
1393 pending.selection.start = tail_anchor.clone();
1394 } else {
1395 pending.selection.end = tail_anchor.clone();
1396 pending.selection.reversed = true;
1397 }
1398
1399 match &mut pending.mode {
1400 SelectMode::Word(range) | SelectMode::Line(range) => {
1401 *range = tail_anchor.clone()..tail_anchor
1402 }
1403 _ => {}
1404 }
1405
1406 self.set_selections(self.selections.clone(), Some(pending), true, cx);
1407 }
1408
1409 fn begin_selection(
1410 &mut self,
1411 position: DisplayPoint,
1412 add: bool,
1413 click_count: usize,
1414 cx: &mut ViewContext<Self>,
1415 ) {
1416 if !self.focused {
1417 cx.focus_self();
1418 cx.emit(Event::Activate);
1419 }
1420
1421 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1422 let buffer = &display_map.buffer_snapshot;
1423 let newest_selection = self.newest_anchor_selection().clone();
1424
1425 let start;
1426 let end;
1427 let mode;
1428 match click_count {
1429 1 => {
1430 start = buffer.anchor_before(position.to_point(&display_map));
1431 end = start.clone();
1432 mode = SelectMode::Character;
1433 }
1434 2 => {
1435 let range = movement::surrounding_word(&display_map, position);
1436 start = buffer.anchor_before(range.start.to_point(&display_map));
1437 end = buffer.anchor_before(range.end.to_point(&display_map));
1438 mode = SelectMode::Word(start.clone()..end.clone());
1439 }
1440 3 => {
1441 let position = display_map
1442 .clip_point(position, Bias::Left)
1443 .to_point(&display_map);
1444 let line_start = display_map.prev_line_boundary(position).0;
1445 let next_line_start = buffer.clip_point(
1446 display_map.next_line_boundary(position).0 + Point::new(1, 0),
1447 Bias::Left,
1448 );
1449 start = buffer.anchor_before(line_start);
1450 end = buffer.anchor_before(next_line_start);
1451 mode = SelectMode::Line(start.clone()..end.clone());
1452 }
1453 _ => {
1454 start = buffer.anchor_before(0);
1455 end = buffer.anchor_before(buffer.len());
1456 mode = SelectMode::All;
1457 }
1458 }
1459
1460 let selection = Selection {
1461 id: post_inc(&mut self.next_selection_id),
1462 start,
1463 end,
1464 reversed: false,
1465 goal: SelectionGoal::None,
1466 };
1467
1468 let mut selections;
1469 if add {
1470 selections = self.selections.clone();
1471 // Remove the newest selection if it was added due to a previous mouse up
1472 // within this multi-click.
1473 if click_count > 1 {
1474 selections = self
1475 .selections
1476 .iter()
1477 .filter(|selection| selection.id != newest_selection.id)
1478 .cloned()
1479 .collect();
1480 }
1481 } else {
1482 selections = Arc::from([]);
1483 }
1484 self.set_selections(
1485 selections,
1486 Some(PendingSelection { selection, mode }),
1487 true,
1488 cx,
1489 );
1490
1491 cx.notify();
1492 }
1493
1494 fn begin_columnar_selection(
1495 &mut self,
1496 position: DisplayPoint,
1497 overshoot: u32,
1498 cx: &mut ViewContext<Self>,
1499 ) {
1500 if !self.focused {
1501 cx.focus_self();
1502 cx.emit(Event::Activate);
1503 }
1504
1505 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1506 let tail = self
1507 .newest_selection_with_snapshot::<Point>(&display_map.buffer_snapshot)
1508 .tail();
1509 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
1510
1511 self.select_columns(
1512 tail.to_display_point(&display_map),
1513 position,
1514 overshoot,
1515 &display_map,
1516 cx,
1517 );
1518 }
1519
1520 fn update_selection(
1521 &mut self,
1522 position: DisplayPoint,
1523 overshoot: u32,
1524 scroll_position: Vector2F,
1525 cx: &mut ViewContext<Self>,
1526 ) {
1527 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1528
1529 if let Some(tail) = self.columnar_selection_tail.as_ref() {
1530 let tail = tail.to_display_point(&display_map);
1531 self.select_columns(tail, position, overshoot, &display_map, cx);
1532 } else if let Some(mut pending) = self.pending_selection.clone() {
1533 let buffer = self.buffer.read(cx).snapshot(cx);
1534 let head;
1535 let tail;
1536 match &pending.mode {
1537 SelectMode::Character => {
1538 head = position.to_point(&display_map);
1539 tail = pending.selection.tail().to_point(&buffer);
1540 }
1541 SelectMode::Word(original_range) => {
1542 let original_display_range = original_range.start.to_display_point(&display_map)
1543 ..original_range.end.to_display_point(&display_map);
1544 let original_buffer_range = original_display_range.start.to_point(&display_map)
1545 ..original_display_range.end.to_point(&display_map);
1546 if movement::is_inside_word(&display_map, position)
1547 || original_display_range.contains(&position)
1548 {
1549 let word_range = movement::surrounding_word(&display_map, position);
1550 if word_range.start < original_display_range.start {
1551 head = word_range.start.to_point(&display_map);
1552 } else {
1553 head = word_range.end.to_point(&display_map);
1554 }
1555 } else {
1556 head = position.to_point(&display_map);
1557 }
1558
1559 if head <= original_buffer_range.start {
1560 tail = original_buffer_range.end;
1561 } else {
1562 tail = original_buffer_range.start;
1563 }
1564 }
1565 SelectMode::Line(original_range) => {
1566 let original_range = original_range.to_point(&display_map.buffer_snapshot);
1567
1568 let position = display_map
1569 .clip_point(position, Bias::Left)
1570 .to_point(&display_map);
1571 let line_start = display_map.prev_line_boundary(position).0;
1572 let next_line_start = buffer.clip_point(
1573 display_map.next_line_boundary(position).0 + Point::new(1, 0),
1574 Bias::Left,
1575 );
1576
1577 if line_start < original_range.start {
1578 head = line_start
1579 } else {
1580 head = next_line_start
1581 }
1582
1583 if head <= original_range.start {
1584 tail = original_range.end;
1585 } else {
1586 tail = original_range.start;
1587 }
1588 }
1589 SelectMode::All => {
1590 return;
1591 }
1592 };
1593
1594 if head < tail {
1595 pending.selection.start = buffer.anchor_before(head);
1596 pending.selection.end = buffer.anchor_before(tail);
1597 pending.selection.reversed = true;
1598 } else {
1599 pending.selection.start = buffer.anchor_before(tail);
1600 pending.selection.end = buffer.anchor_before(head);
1601 pending.selection.reversed = false;
1602 }
1603 self.set_selections(self.selections.clone(), Some(pending), true, cx);
1604 } else {
1605 log::error!("update_selection dispatched with no pending selection");
1606 return;
1607 }
1608
1609 self.set_scroll_position(scroll_position, cx);
1610 cx.notify();
1611 }
1612
1613 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
1614 self.columnar_selection_tail.take();
1615 if self.pending_selection.is_some() {
1616 let selections = self.local_selections::<usize>(cx);
1617 self.update_selections(selections, None, cx);
1618 }
1619 }
1620
1621 fn select_columns(
1622 &mut self,
1623 tail: DisplayPoint,
1624 head: DisplayPoint,
1625 overshoot: u32,
1626 display_map: &DisplaySnapshot,
1627 cx: &mut ViewContext<Self>,
1628 ) {
1629 let start_row = cmp::min(tail.row(), head.row());
1630 let end_row = cmp::max(tail.row(), head.row());
1631 let start_column = cmp::min(tail.column(), head.column() + overshoot);
1632 let end_column = cmp::max(tail.column(), head.column() + overshoot);
1633 let reversed = start_column < tail.column();
1634
1635 let selections = (start_row..=end_row)
1636 .filter_map(|row| {
1637 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
1638 let start = display_map
1639 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
1640 .to_point(&display_map);
1641 let end = display_map
1642 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
1643 .to_point(&display_map);
1644 Some(Selection {
1645 id: post_inc(&mut self.next_selection_id),
1646 start,
1647 end,
1648 reversed,
1649 goal: SelectionGoal::None,
1650 })
1651 } else {
1652 None
1653 }
1654 })
1655 .collect::<Vec<_>>();
1656
1657 self.update_selections(selections, None, cx);
1658 cx.notify();
1659 }
1660
1661 pub fn is_selecting(&self) -> bool {
1662 self.pending_selection.is_some() || self.columnar_selection_tail.is_some()
1663 }
1664
1665 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
1666 if self.take_rename(false, cx).is_some() {
1667 return;
1668 }
1669
1670 if self.hide_context_menu(cx).is_some() {
1671 return;
1672 }
1673
1674 if self.snippet_stack.pop().is_some() {
1675 return;
1676 }
1677
1678 if self.mode != EditorMode::Full {
1679 cx.propagate_action();
1680 return;
1681 }
1682
1683 if self.active_diagnostics.is_some() {
1684 self.dismiss_diagnostics(cx);
1685 } else if let Some(pending) = self.pending_selection.clone() {
1686 let mut selections = self.selections.clone();
1687 if selections.is_empty() {
1688 selections = Arc::from([pending.selection]);
1689 }
1690 self.set_selections(selections, None, true, cx);
1691 self.request_autoscroll(Autoscroll::Fit, cx);
1692 } else {
1693 let mut oldest_selection = self.oldest_selection::<usize>(&cx);
1694 if self.selection_count() == 1 {
1695 if oldest_selection.is_empty() {
1696 cx.propagate_action();
1697 return;
1698 }
1699
1700 oldest_selection.start = oldest_selection.head().clone();
1701 oldest_selection.end = oldest_selection.head().clone();
1702 }
1703 self.update_selections(vec![oldest_selection], Some(Autoscroll::Fit), cx);
1704 }
1705 }
1706
1707 #[cfg(any(test, feature = "test-support"))]
1708 pub fn selected_ranges<D: TextDimension + Ord + Sub<D, Output = D>>(
1709 &self,
1710 cx: &AppContext,
1711 ) -> Vec<Range<D>> {
1712 self.local_selections::<D>(cx)
1713 .iter()
1714 .map(|s| {
1715 if s.reversed {
1716 s.end.clone()..s.start.clone()
1717 } else {
1718 s.start.clone()..s.end.clone()
1719 }
1720 })
1721 .collect()
1722 }
1723
1724 #[cfg(any(test, feature = "test-support"))]
1725 pub fn selected_display_ranges(&self, cx: &mut MutableAppContext) -> Vec<Range<DisplayPoint>> {
1726 let display_map = self
1727 .display_map
1728 .update(cx, |display_map, cx| display_map.snapshot(cx));
1729 self.selections
1730 .iter()
1731 .chain(
1732 self.pending_selection
1733 .as_ref()
1734 .map(|pending| &pending.selection),
1735 )
1736 .map(|s| {
1737 if s.reversed {
1738 s.end.to_display_point(&display_map)..s.start.to_display_point(&display_map)
1739 } else {
1740 s.start.to_display_point(&display_map)..s.end.to_display_point(&display_map)
1741 }
1742 })
1743 .collect()
1744 }
1745
1746 pub fn select_ranges<I, T>(
1747 &mut self,
1748 ranges: I,
1749 autoscroll: Option<Autoscroll>,
1750 cx: &mut ViewContext<Self>,
1751 ) where
1752 I: IntoIterator<Item = Range<T>>,
1753 T: ToOffset,
1754 {
1755 let buffer = self.buffer.read(cx).snapshot(cx);
1756 let selections = ranges
1757 .into_iter()
1758 .map(|range| {
1759 let mut start = range.start.to_offset(&buffer);
1760 let mut end = range.end.to_offset(&buffer);
1761 let reversed = if start > end {
1762 mem::swap(&mut start, &mut end);
1763 true
1764 } else {
1765 false
1766 };
1767 Selection {
1768 id: post_inc(&mut self.next_selection_id),
1769 start,
1770 end,
1771 reversed,
1772 goal: SelectionGoal::None,
1773 }
1774 })
1775 .collect::<Vec<_>>();
1776 self.update_selections(selections, autoscroll, cx);
1777 }
1778
1779 #[cfg(any(test, feature = "test-support"))]
1780 pub fn select_display_ranges<'a, T>(&mut self, ranges: T, cx: &mut ViewContext<Self>)
1781 where
1782 T: IntoIterator<Item = &'a Range<DisplayPoint>>,
1783 {
1784 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1785 let selections = ranges
1786 .into_iter()
1787 .map(|range| {
1788 let mut start = range.start;
1789 let mut end = range.end;
1790 let reversed = if start > end {
1791 mem::swap(&mut start, &mut end);
1792 true
1793 } else {
1794 false
1795 };
1796 Selection {
1797 id: post_inc(&mut self.next_selection_id),
1798 start: start.to_point(&display_map),
1799 end: end.to_point(&display_map),
1800 reversed,
1801 goal: SelectionGoal::None,
1802 }
1803 })
1804 .collect();
1805 self.update_selections(selections, None, cx);
1806 }
1807
1808 pub fn handle_input(&mut self, action: &Input, cx: &mut ViewContext<Self>) {
1809 if !self.input_enabled {
1810 cx.propagate_action();
1811 return;
1812 }
1813
1814 let text = action.0.as_ref();
1815 if !self.skip_autoclose_end(text, cx) {
1816 self.transact(cx, |this, cx| {
1817 if !this.surround_with_bracket_pair(text, cx) {
1818 this.insert(text, cx);
1819 this.autoclose_bracket_pairs(cx);
1820 }
1821 });
1822 self.trigger_completion_on_input(text, cx);
1823 }
1824 }
1825
1826 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
1827 self.transact(cx, |this, cx| {
1828 let mut old_selections = SmallVec::<[_; 32]>::new();
1829 {
1830 let selections = this.local_selections::<usize>(cx);
1831 let buffer = this.buffer.read(cx).snapshot(cx);
1832 for selection in selections.iter() {
1833 let start_point = selection.start.to_point(&buffer);
1834 let indent = buffer
1835 .indent_column_for_line(start_point.row)
1836 .min(start_point.column);
1837 let start = selection.start;
1838 let end = selection.end;
1839
1840 let mut insert_extra_newline = false;
1841 if let Some(language) = buffer.language() {
1842 let leading_whitespace_len = buffer
1843 .reversed_chars_at(start)
1844 .take_while(|c| c.is_whitespace() && *c != '\n')
1845 .map(|c| c.len_utf8())
1846 .sum::<usize>();
1847
1848 let trailing_whitespace_len = buffer
1849 .chars_at(end)
1850 .take_while(|c| c.is_whitespace() && *c != '\n')
1851 .map(|c| c.len_utf8())
1852 .sum::<usize>();
1853
1854 insert_extra_newline = language.brackets().iter().any(|pair| {
1855 let pair_start = pair.start.trim_end();
1856 let pair_end = pair.end.trim_start();
1857
1858 pair.newline
1859 && buffer.contains_str_at(end + trailing_whitespace_len, pair_end)
1860 && buffer.contains_str_at(
1861 (start - leading_whitespace_len)
1862 .saturating_sub(pair_start.len()),
1863 pair_start,
1864 )
1865 });
1866 }
1867
1868 old_selections.push((
1869 selection.id,
1870 buffer.anchor_after(end),
1871 start..end,
1872 indent,
1873 insert_extra_newline,
1874 ));
1875 }
1876 }
1877
1878 this.buffer.update(cx, |buffer, cx| {
1879 let mut delta = 0_isize;
1880 let mut pending_edit: Option<PendingEdit> = None;
1881 for (_, _, range, indent, insert_extra_newline) in &old_selections {
1882 if pending_edit.as_ref().map_or(false, |pending| {
1883 pending.indent != *indent
1884 || pending.insert_extra_newline != *insert_extra_newline
1885 }) {
1886 let pending = pending_edit.take().unwrap();
1887 let mut new_text = String::with_capacity(1 + pending.indent as usize);
1888 new_text.push('\n');
1889 new_text.extend(iter::repeat(' ').take(pending.indent as usize));
1890 if pending.insert_extra_newline {
1891 new_text = new_text.repeat(2);
1892 }
1893 buffer.edit_with_autoindent(pending.ranges, new_text, cx);
1894 delta += pending.delta;
1895 }
1896
1897 let start = (range.start as isize + delta) as usize;
1898 let end = (range.end as isize + delta) as usize;
1899 let mut text_len = *indent as usize + 1;
1900 if *insert_extra_newline {
1901 text_len *= 2;
1902 }
1903
1904 let pending = pending_edit.get_or_insert_with(Default::default);
1905 pending.delta += text_len as isize - (end - start) as isize;
1906 pending.indent = *indent;
1907 pending.insert_extra_newline = *insert_extra_newline;
1908 pending.ranges.push(start..end);
1909 }
1910
1911 let pending = pending_edit.unwrap();
1912 let mut new_text = String::with_capacity(1 + pending.indent as usize);
1913 new_text.push('\n');
1914 new_text.extend(iter::repeat(' ').take(pending.indent as usize));
1915 if pending.insert_extra_newline {
1916 new_text = new_text.repeat(2);
1917 }
1918 buffer.edit_with_autoindent(pending.ranges, new_text, cx);
1919
1920 let buffer = buffer.read(cx);
1921 this.selections = this
1922 .selections
1923 .iter()
1924 .cloned()
1925 .zip(old_selections)
1926 .map(
1927 |(mut new_selection, (_, end_anchor, _, _, insert_extra_newline))| {
1928 let mut cursor = end_anchor.to_point(&buffer);
1929 if insert_extra_newline {
1930 cursor.row -= 1;
1931 cursor.column = buffer.line_len(cursor.row);
1932 }
1933 let anchor = buffer.anchor_after(cursor);
1934 new_selection.start = anchor.clone();
1935 new_selection.end = anchor;
1936 new_selection
1937 },
1938 )
1939 .collect();
1940 });
1941
1942 this.request_autoscroll(Autoscroll::Fit, cx);
1943 });
1944
1945 #[derive(Default)]
1946 struct PendingEdit {
1947 indent: u32,
1948 insert_extra_newline: bool,
1949 delta: isize,
1950 ranges: SmallVec<[Range<usize>; 32]>,
1951 }
1952 }
1953
1954 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
1955 self.transact(cx, |this, cx| {
1956 let old_selections = this.local_selections::<usize>(cx);
1957 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
1958 let anchors = {
1959 let snapshot = buffer.read(cx);
1960 old_selections
1961 .iter()
1962 .map(|s| (s.id, s.goal, snapshot.anchor_after(s.end)))
1963 .collect::<Vec<_>>()
1964 };
1965 let edit_ranges = old_selections.iter().map(|s| s.start..s.end);
1966 buffer.edit_with_autoindent(edit_ranges, text, cx);
1967 anchors
1968 });
1969
1970 let selections = {
1971 let snapshot = this.buffer.read(cx).read(cx);
1972 selection_anchors
1973 .into_iter()
1974 .map(|(id, goal, position)| {
1975 let position = position.to_offset(&snapshot);
1976 Selection {
1977 id,
1978 start: position,
1979 end: position,
1980 goal,
1981 reversed: false,
1982 }
1983 })
1984 .collect()
1985 };
1986 this.update_selections(selections, Some(Autoscroll::Fit), cx);
1987 });
1988 }
1989
1990 fn trigger_completion_on_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
1991 let selection = self.newest_anchor_selection();
1992 if self
1993 .buffer
1994 .read(cx)
1995 .is_completion_trigger(selection.head(), text, cx)
1996 {
1997 self.show_completions(&ShowCompletions, cx);
1998 } else {
1999 self.hide_context_menu(cx);
2000 }
2001 }
2002
2003 fn surround_with_bracket_pair(&mut self, text: &str, cx: &mut ViewContext<Self>) -> bool {
2004 let snapshot = self.buffer.read(cx).snapshot(cx);
2005 if let Some(pair) = snapshot
2006 .language()
2007 .and_then(|language| language.brackets().iter().find(|b| b.start == text))
2008 .cloned()
2009 {
2010 if self
2011 .local_selections::<usize>(cx)
2012 .iter()
2013 .any(|selection| selection.is_empty())
2014 {
2015 false
2016 } else {
2017 let mut selections = self.selections.to_vec();
2018 for selection in &mut selections {
2019 selection.end = selection.end.bias_left(&snapshot);
2020 }
2021 drop(snapshot);
2022
2023 self.buffer.update(cx, |buffer, cx| {
2024 buffer.edit(
2025 selections.iter().map(|s| s.start.clone()..s.start.clone()),
2026 &pair.start,
2027 cx,
2028 );
2029 buffer.edit(
2030 selections.iter().map(|s| s.end.clone()..s.end.clone()),
2031 &pair.end,
2032 cx,
2033 );
2034 });
2035
2036 let snapshot = self.buffer.read(cx).read(cx);
2037 for selection in &mut selections {
2038 selection.end = selection.end.bias_right(&snapshot);
2039 }
2040 drop(snapshot);
2041
2042 self.set_selections(selections.into(), None, true, cx);
2043 true
2044 }
2045 } else {
2046 false
2047 }
2048 }
2049
2050 fn autoclose_bracket_pairs(&mut self, cx: &mut ViewContext<Self>) {
2051 let selections = self.local_selections::<usize>(cx);
2052 let mut bracket_pair_state = None;
2053 let mut new_selections = None;
2054 self.buffer.update(cx, |buffer, cx| {
2055 let mut snapshot = buffer.snapshot(cx);
2056 let left_biased_selections = selections
2057 .iter()
2058 .map(|selection| Selection {
2059 id: selection.id,
2060 start: snapshot.anchor_before(selection.start),
2061 end: snapshot.anchor_before(selection.end),
2062 reversed: selection.reversed,
2063 goal: selection.goal,
2064 })
2065 .collect::<Vec<_>>();
2066
2067 let autoclose_pair = snapshot.language().and_then(|language| {
2068 let first_selection_start = selections.first().unwrap().start;
2069 let pair = language.brackets().iter().find(|pair| {
2070 snapshot.contains_str_at(
2071 first_selection_start.saturating_sub(pair.start.len()),
2072 &pair.start,
2073 )
2074 });
2075 pair.and_then(|pair| {
2076 let should_autoclose = selections.iter().all(|selection| {
2077 // Ensure all selections are parked at the end of a pair start.
2078 if snapshot.contains_str_at(
2079 selection.start.saturating_sub(pair.start.len()),
2080 &pair.start,
2081 ) {
2082 snapshot
2083 .chars_at(selection.start)
2084 .next()
2085 .map_or(true, |c| language.should_autoclose_before(c))
2086 } else {
2087 false
2088 }
2089 });
2090
2091 if should_autoclose {
2092 Some(pair.clone())
2093 } else {
2094 None
2095 }
2096 })
2097 });
2098
2099 if let Some(pair) = autoclose_pair {
2100 let selection_ranges = selections
2101 .iter()
2102 .map(|selection| {
2103 let start = selection.start.to_offset(&snapshot);
2104 start..start
2105 })
2106 .collect::<SmallVec<[_; 32]>>();
2107
2108 buffer.edit(selection_ranges, &pair.end, cx);
2109 snapshot = buffer.snapshot(cx);
2110
2111 new_selections = Some(
2112 self.resolve_selections::<usize, _>(left_biased_selections.iter(), &snapshot)
2113 .collect::<Vec<_>>(),
2114 );
2115
2116 if pair.end.len() == 1 {
2117 let mut delta = 0;
2118 bracket_pair_state = Some(BracketPairState {
2119 ranges: selections
2120 .iter()
2121 .map(move |selection| {
2122 let offset = selection.start + delta;
2123 delta += 1;
2124 snapshot.anchor_before(offset)..snapshot.anchor_after(offset)
2125 })
2126 .collect(),
2127 pair,
2128 });
2129 }
2130 }
2131 });
2132
2133 if let Some(new_selections) = new_selections {
2134 self.update_selections(new_selections, None, cx);
2135 }
2136 if let Some(bracket_pair_state) = bracket_pair_state {
2137 self.autoclose_stack.push(bracket_pair_state);
2138 }
2139 }
2140
2141 fn skip_autoclose_end(&mut self, text: &str, cx: &mut ViewContext<Self>) -> bool {
2142 let old_selections = self.local_selections::<usize>(cx);
2143 let autoclose_pair = if let Some(autoclose_pair) = self.autoclose_stack.last() {
2144 autoclose_pair
2145 } else {
2146 return false;
2147 };
2148 if text != autoclose_pair.pair.end {
2149 return false;
2150 }
2151
2152 debug_assert_eq!(old_selections.len(), autoclose_pair.ranges.len());
2153
2154 let buffer = self.buffer.read(cx).snapshot(cx);
2155 if old_selections
2156 .iter()
2157 .zip(autoclose_pair.ranges.iter().map(|r| r.to_offset(&buffer)))
2158 .all(|(selection, autoclose_range)| {
2159 let autoclose_range_end = autoclose_range.end.to_offset(&buffer);
2160 selection.is_empty() && selection.start == autoclose_range_end
2161 })
2162 {
2163 let new_selections = old_selections
2164 .into_iter()
2165 .map(|selection| {
2166 let cursor = selection.start + 1;
2167 Selection {
2168 id: selection.id,
2169 start: cursor,
2170 end: cursor,
2171 reversed: false,
2172 goal: SelectionGoal::None,
2173 }
2174 })
2175 .collect();
2176 self.autoclose_stack.pop();
2177 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2178 true
2179 } else {
2180 false
2181 }
2182 }
2183
2184 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
2185 let offset = position.to_offset(buffer);
2186 let (word_range, kind) = buffer.surrounding_word(offset);
2187 if offset > word_range.start && kind == Some(CharKind::Word) {
2188 Some(
2189 buffer
2190 .text_for_range(word_range.start..offset)
2191 .collect::<String>(),
2192 )
2193 } else {
2194 None
2195 }
2196 }
2197
2198 fn show_completions(&mut self, _: &ShowCompletions, cx: &mut ViewContext<Self>) {
2199 if self.pending_rename.is_some() {
2200 return;
2201 }
2202
2203 let project = if let Some(project) = self.project.clone() {
2204 project
2205 } else {
2206 return;
2207 };
2208
2209 let position = self.newest_anchor_selection().head();
2210 let (buffer, buffer_position) = if let Some(output) = self
2211 .buffer
2212 .read(cx)
2213 .text_anchor_for_position(position.clone(), cx)
2214 {
2215 output
2216 } else {
2217 return;
2218 };
2219
2220 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position.clone());
2221 let completions = project.update(cx, |project, cx| {
2222 project.completions(&buffer, buffer_position.clone(), cx)
2223 });
2224
2225 let id = post_inc(&mut self.next_completion_id);
2226 let task = cx.spawn_weak(|this, mut cx| {
2227 async move {
2228 let completions = completions.await?;
2229 if completions.is_empty() {
2230 return Ok(());
2231 }
2232
2233 let mut menu = CompletionsMenu {
2234 id,
2235 initial_position: position,
2236 match_candidates: completions
2237 .iter()
2238 .enumerate()
2239 .map(|(id, completion)| {
2240 StringMatchCandidate::new(
2241 id,
2242 completion.label.text[completion.label.filter_range.clone()].into(),
2243 )
2244 })
2245 .collect(),
2246 buffer,
2247 completions: completions.into(),
2248 matches: Vec::new().into(),
2249 selected_item: 0,
2250 list: Default::default(),
2251 };
2252
2253 menu.filter(query.as_deref(), cx.background()).await;
2254
2255 if let Some(this) = this.upgrade(&cx) {
2256 this.update(&mut cx, |this, cx| {
2257 match this.context_menu.as_ref() {
2258 None => {}
2259 Some(ContextMenu::Completions(prev_menu)) => {
2260 if prev_menu.id > menu.id {
2261 return;
2262 }
2263 }
2264 _ => return,
2265 }
2266
2267 this.completion_tasks.retain(|(id, _)| *id > menu.id);
2268 if this.focused {
2269 this.show_context_menu(ContextMenu::Completions(menu), cx);
2270 }
2271
2272 cx.notify();
2273 });
2274 }
2275 Ok::<_, anyhow::Error>(())
2276 }
2277 .log_err()
2278 });
2279 self.completion_tasks.push((id, task));
2280 }
2281
2282 pub fn confirm_completion(
2283 &mut self,
2284 ConfirmCompletion(completion_ix): &ConfirmCompletion,
2285 cx: &mut ViewContext<Self>,
2286 ) -> Option<Task<Result<()>>> {
2287 use language::ToOffset as _;
2288
2289 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
2290 menu
2291 } else {
2292 return None;
2293 };
2294
2295 let mat = completions_menu
2296 .matches
2297 .get(completion_ix.unwrap_or(completions_menu.selected_item))?;
2298 let buffer_handle = completions_menu.buffer;
2299 let completion = completions_menu.completions.get(mat.candidate_id)?;
2300
2301 let snippet;
2302 let text;
2303 if completion.is_snippet() {
2304 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
2305 text = snippet.as_ref().unwrap().text.clone();
2306 } else {
2307 snippet = None;
2308 text = completion.new_text.clone();
2309 };
2310 let buffer = buffer_handle.read(cx);
2311 let old_range = completion.old_range.to_offset(&buffer);
2312 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
2313
2314 let selections = self.local_selections::<usize>(cx);
2315 let newest_selection = self.newest_anchor_selection();
2316 if newest_selection.start.buffer_id != Some(buffer_handle.id()) {
2317 return None;
2318 }
2319
2320 let lookbehind = newest_selection
2321 .start
2322 .text_anchor
2323 .to_offset(buffer)
2324 .saturating_sub(old_range.start);
2325 let lookahead = old_range
2326 .end
2327 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
2328 let mut common_prefix_len = old_text
2329 .bytes()
2330 .zip(text.bytes())
2331 .take_while(|(a, b)| a == b)
2332 .count();
2333
2334 let snapshot = self.buffer.read(cx).snapshot(cx);
2335 let mut ranges = Vec::new();
2336 for selection in &selections {
2337 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
2338 let start = selection.start.saturating_sub(lookbehind);
2339 let end = selection.end + lookahead;
2340 ranges.push(start + common_prefix_len..end);
2341 } else {
2342 common_prefix_len = 0;
2343 ranges.clear();
2344 ranges.extend(selections.iter().map(|s| {
2345 if s.id == newest_selection.id {
2346 old_range.clone()
2347 } else {
2348 s.start..s.end
2349 }
2350 }));
2351 break;
2352 }
2353 }
2354 let text = &text[common_prefix_len..];
2355
2356 self.transact(cx, |this, cx| {
2357 if let Some(mut snippet) = snippet {
2358 snippet.text = text.to_string();
2359 for tabstop in snippet.tabstops.iter_mut().flatten() {
2360 tabstop.start -= common_prefix_len as isize;
2361 tabstop.end -= common_prefix_len as isize;
2362 }
2363
2364 this.insert_snippet(&ranges, snippet, cx).log_err();
2365 } else {
2366 this.buffer.update(cx, |buffer, cx| {
2367 buffer.edit_with_autoindent(ranges, text, cx);
2368 });
2369 }
2370 });
2371
2372 let project = self.project.clone()?;
2373 let apply_edits = project.update(cx, |project, cx| {
2374 project.apply_additional_edits_for_completion(
2375 buffer_handle,
2376 completion.clone(),
2377 true,
2378 cx,
2379 )
2380 });
2381 Some(cx.foreground().spawn(async move {
2382 apply_edits.await?;
2383 Ok(())
2384 }))
2385 }
2386
2387 pub fn toggle_code_actions(
2388 &mut self,
2389 &ToggleCodeActions(deployed_from_indicator): &ToggleCodeActions,
2390 cx: &mut ViewContext<Self>,
2391 ) {
2392 if matches!(
2393 self.context_menu.as_ref(),
2394 Some(ContextMenu::CodeActions(_))
2395 ) {
2396 self.context_menu.take();
2397 cx.notify();
2398 return;
2399 }
2400
2401 let mut task = self.code_actions_task.take();
2402 cx.spawn_weak(|this, mut cx| async move {
2403 while let Some(prev_task) = task {
2404 prev_task.await;
2405 task = this
2406 .upgrade(&cx)
2407 .and_then(|this| this.update(&mut cx, |this, _| this.code_actions_task.take()));
2408 }
2409
2410 if let Some(this) = this.upgrade(&cx) {
2411 this.update(&mut cx, |this, cx| {
2412 if this.focused {
2413 if let Some((buffer, actions)) = this.available_code_actions.clone() {
2414 this.show_context_menu(
2415 ContextMenu::CodeActions(CodeActionsMenu {
2416 buffer,
2417 actions,
2418 selected_item: Default::default(),
2419 list: Default::default(),
2420 deployed_from_indicator,
2421 }),
2422 cx,
2423 );
2424 }
2425 }
2426 })
2427 }
2428 Ok::<_, anyhow::Error>(())
2429 })
2430 .detach_and_log_err(cx);
2431 }
2432
2433 pub fn confirm_code_action(
2434 workspace: &mut Workspace,
2435 ConfirmCodeAction(action_ix): &ConfirmCodeAction,
2436 cx: &mut ViewContext<Workspace>,
2437 ) -> Option<Task<Result<()>>> {
2438 let editor = workspace.active_item(cx)?.act_as::<Editor>(cx)?;
2439 let actions_menu = if let ContextMenu::CodeActions(menu) =
2440 editor.update(cx, |editor, cx| editor.hide_context_menu(cx))?
2441 {
2442 menu
2443 } else {
2444 return None;
2445 };
2446 let action_ix = action_ix.unwrap_or(actions_menu.selected_item);
2447 let action = actions_menu.actions.get(action_ix)?.clone();
2448 let title = action.lsp_action.title.clone();
2449 let buffer = actions_menu.buffer;
2450
2451 let apply_code_actions = workspace.project().clone().update(cx, |project, cx| {
2452 project.apply_code_action(buffer, action, true, cx)
2453 });
2454 Some(cx.spawn(|workspace, cx| async move {
2455 let project_transaction = apply_code_actions.await?;
2456 Self::open_project_transaction(editor, workspace, project_transaction, title, cx).await
2457 }))
2458 }
2459
2460 async fn open_project_transaction(
2461 this: ViewHandle<Editor>,
2462 workspace: ViewHandle<Workspace>,
2463 transaction: ProjectTransaction,
2464 title: String,
2465 mut cx: AsyncAppContext,
2466 ) -> Result<()> {
2467 let replica_id = this.read_with(&cx, |this, cx| this.replica_id(cx));
2468
2469 // If the project transaction's edits are all contained within this editor, then
2470 // avoid opening a new editor to display them.
2471 let mut entries = transaction.0.iter();
2472 if let Some((buffer, transaction)) = entries.next() {
2473 if entries.next().is_none() {
2474 let excerpt = this.read_with(&cx, |editor, cx| {
2475 editor
2476 .buffer()
2477 .read(cx)
2478 .excerpt_containing(editor.newest_anchor_selection().head(), cx)
2479 });
2480 if let Some((excerpted_buffer, excerpt_range)) = excerpt {
2481 if excerpted_buffer == *buffer {
2482 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
2483 let excerpt_range = excerpt_range.to_offset(&snapshot);
2484 if snapshot
2485 .edited_ranges_for_transaction(transaction)
2486 .all(|range| {
2487 excerpt_range.start <= range.start && excerpt_range.end >= range.end
2488 })
2489 {
2490 return Ok(());
2491 }
2492 }
2493 }
2494 }
2495 }
2496
2497 let mut ranges_to_highlight = Vec::new();
2498 let excerpt_buffer = cx.add_model(|cx| {
2499 let mut multibuffer = MultiBuffer::new(replica_id).with_title(title);
2500 for (buffer, transaction) in &transaction.0 {
2501 let snapshot = buffer.read(cx).snapshot();
2502 ranges_to_highlight.extend(
2503 multibuffer.push_excerpts_with_context_lines(
2504 buffer.clone(),
2505 snapshot
2506 .edited_ranges_for_transaction::<usize>(transaction)
2507 .collect(),
2508 1,
2509 cx,
2510 ),
2511 );
2512 }
2513 multibuffer.push_transaction(&transaction.0);
2514 multibuffer
2515 });
2516
2517 workspace.update(&mut cx, |workspace, cx| {
2518 let project = workspace.project().clone();
2519 let editor =
2520 cx.add_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), cx));
2521 workspace.add_item(Box::new(editor.clone()), cx);
2522 editor.update(cx, |editor, cx| {
2523 let color = editor.style(cx).highlighted_line_background;
2524 editor.highlight_background::<Self>(ranges_to_highlight, color, cx);
2525 });
2526 });
2527
2528 Ok(())
2529 }
2530
2531 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
2532 let project = self.project.as_ref()?;
2533 let buffer = self.buffer.read(cx);
2534 let newest_selection = self.newest_anchor_selection().clone();
2535 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
2536 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
2537 if start_buffer != end_buffer {
2538 return None;
2539 }
2540
2541 let actions = project.update(cx, |project, cx| {
2542 project.code_actions(&start_buffer, start..end, cx)
2543 });
2544 self.code_actions_task = Some(cx.spawn_weak(|this, mut cx| async move {
2545 let actions = actions.await;
2546 if let Some(this) = this.upgrade(&cx) {
2547 this.update(&mut cx, |this, cx| {
2548 this.available_code_actions = actions.log_err().and_then(|actions| {
2549 if actions.is_empty() {
2550 None
2551 } else {
2552 Some((start_buffer, actions.into()))
2553 }
2554 });
2555 cx.notify();
2556 })
2557 }
2558 }));
2559 None
2560 }
2561
2562 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
2563 if self.pending_rename.is_some() {
2564 return None;
2565 }
2566
2567 let project = self.project.as_ref()?;
2568 let buffer = self.buffer.read(cx);
2569 let newest_selection = self.newest_anchor_selection().clone();
2570 let cursor_position = newest_selection.head();
2571 let (cursor_buffer, cursor_buffer_position) =
2572 buffer.text_anchor_for_position(cursor_position.clone(), cx)?;
2573 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
2574 if cursor_buffer != tail_buffer {
2575 return None;
2576 }
2577
2578 let highlights = project.update(cx, |project, cx| {
2579 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
2580 });
2581
2582 self.document_highlights_task = Some(cx.spawn_weak(|this, mut cx| async move {
2583 let highlights = highlights.log_err().await;
2584 if let Some((this, highlights)) = this.upgrade(&cx).zip(highlights) {
2585 this.update(&mut cx, |this, cx| {
2586 if this.pending_rename.is_some() {
2587 return;
2588 }
2589
2590 let buffer_id = cursor_position.buffer_id;
2591 let style = this.style(cx);
2592 let read_background = style.document_highlight_read_background;
2593 let write_background = style.document_highlight_write_background;
2594 let buffer = this.buffer.read(cx);
2595 if !buffer
2596 .text_anchor_for_position(cursor_position, cx)
2597 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
2598 {
2599 return;
2600 }
2601
2602 let cursor_buffer_snapshot = cursor_buffer.read(cx);
2603 let mut write_ranges = Vec::new();
2604 let mut read_ranges = Vec::new();
2605 for highlight in highlights {
2606 for (excerpt_id, excerpt_range) in
2607 buffer.excerpts_for_buffer(&cursor_buffer, cx)
2608 {
2609 let start = highlight
2610 .range
2611 .start
2612 .max(&excerpt_range.start, cursor_buffer_snapshot);
2613 let end = highlight
2614 .range
2615 .end
2616 .min(&excerpt_range.end, cursor_buffer_snapshot);
2617 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
2618 continue;
2619 }
2620
2621 let range = Anchor {
2622 buffer_id,
2623 excerpt_id: excerpt_id.clone(),
2624 text_anchor: start,
2625 }..Anchor {
2626 buffer_id,
2627 excerpt_id,
2628 text_anchor: end,
2629 };
2630 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
2631 write_ranges.push(range);
2632 } else {
2633 read_ranges.push(range);
2634 }
2635 }
2636 }
2637
2638 this.highlight_background::<DocumentHighlightRead>(
2639 read_ranges,
2640 read_background,
2641 cx,
2642 );
2643 this.highlight_background::<DocumentHighlightWrite>(
2644 write_ranges,
2645 write_background,
2646 cx,
2647 );
2648 cx.notify();
2649 });
2650 }
2651 }));
2652 None
2653 }
2654
2655 pub fn render_code_actions_indicator(
2656 &self,
2657 style: &EditorStyle,
2658 cx: &mut ViewContext<Self>,
2659 ) -> Option<ElementBox> {
2660 if self.available_code_actions.is_some() {
2661 enum Tag {}
2662 Some(
2663 MouseEventHandler::new::<Tag, _, _>(0, cx, |_, _| {
2664 Svg::new("icons/zap.svg")
2665 .with_color(style.code_actions_indicator)
2666 .boxed()
2667 })
2668 .with_cursor_style(CursorStyle::PointingHand)
2669 .with_padding(Padding::uniform(3.))
2670 .on_mouse_down(|cx| {
2671 cx.dispatch_action(ToggleCodeActions(true));
2672 })
2673 .boxed(),
2674 )
2675 } else {
2676 None
2677 }
2678 }
2679
2680 pub fn context_menu_visible(&self) -> bool {
2681 self.context_menu
2682 .as_ref()
2683 .map_or(false, |menu| menu.visible())
2684 }
2685
2686 pub fn render_context_menu(
2687 &self,
2688 cursor_position: DisplayPoint,
2689 style: EditorStyle,
2690 cx: &AppContext,
2691 ) -> Option<(DisplayPoint, ElementBox)> {
2692 self.context_menu
2693 .as_ref()
2694 .map(|menu| menu.render(cursor_position, style, cx))
2695 }
2696
2697 fn show_context_menu(&mut self, menu: ContextMenu, cx: &mut ViewContext<Self>) {
2698 if !matches!(menu, ContextMenu::Completions(_)) {
2699 self.completion_tasks.clear();
2700 }
2701 self.context_menu = Some(menu);
2702 cx.notify();
2703 }
2704
2705 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
2706 cx.notify();
2707 self.completion_tasks.clear();
2708 self.context_menu.take()
2709 }
2710
2711 pub fn insert_snippet(
2712 &mut self,
2713 insertion_ranges: &[Range<usize>],
2714 snippet: Snippet,
2715 cx: &mut ViewContext<Self>,
2716 ) -> Result<()> {
2717 let tabstops = self.buffer.update(cx, |buffer, cx| {
2718 buffer.edit_with_autoindent(insertion_ranges.iter().cloned(), &snippet.text, cx);
2719
2720 let snapshot = &*buffer.read(cx);
2721 let snippet = &snippet;
2722 snippet
2723 .tabstops
2724 .iter()
2725 .map(|tabstop| {
2726 let mut tabstop_ranges = tabstop
2727 .iter()
2728 .flat_map(|tabstop_range| {
2729 let mut delta = 0 as isize;
2730 insertion_ranges.iter().map(move |insertion_range| {
2731 let insertion_start = insertion_range.start as isize + delta;
2732 delta +=
2733 snippet.text.len() as isize - insertion_range.len() as isize;
2734
2735 let start = snapshot.anchor_before(
2736 (insertion_start + tabstop_range.start) as usize,
2737 );
2738 let end = snapshot
2739 .anchor_after((insertion_start + tabstop_range.end) as usize);
2740 start..end
2741 })
2742 })
2743 .collect::<Vec<_>>();
2744 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
2745 tabstop_ranges
2746 })
2747 .collect::<Vec<_>>()
2748 });
2749
2750 if let Some(tabstop) = tabstops.first() {
2751 self.select_ranges(tabstop.iter().cloned(), Some(Autoscroll::Fit), cx);
2752 self.snippet_stack.push(SnippetState {
2753 active_index: 0,
2754 ranges: tabstops,
2755 });
2756 }
2757
2758 Ok(())
2759 }
2760
2761 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
2762 self.move_to_snippet_tabstop(Bias::Right, cx)
2763 }
2764
2765 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) {
2766 self.move_to_snippet_tabstop(Bias::Left, cx);
2767 }
2768
2769 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
2770 let buffer = self.buffer.read(cx).snapshot(cx);
2771
2772 if let Some(snippet) = self.snippet_stack.last_mut() {
2773 match bias {
2774 Bias::Left => {
2775 if snippet.active_index > 0 {
2776 snippet.active_index -= 1;
2777 } else {
2778 return false;
2779 }
2780 }
2781 Bias::Right => {
2782 if snippet.active_index + 1 < snippet.ranges.len() {
2783 snippet.active_index += 1;
2784 } else {
2785 return false;
2786 }
2787 }
2788 }
2789 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
2790 let new_selections = current_ranges
2791 .iter()
2792 .map(|new_range| {
2793 let new_range = new_range.to_offset(&buffer);
2794 Selection {
2795 id: post_inc(&mut self.next_selection_id),
2796 start: new_range.start,
2797 end: new_range.end,
2798 reversed: false,
2799 goal: SelectionGoal::None,
2800 }
2801 })
2802 .collect();
2803
2804 // Remove the snippet state when moving to the last tabstop.
2805 if snippet.active_index + 1 == snippet.ranges.len() {
2806 self.snippet_stack.pop();
2807 }
2808
2809 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2810 return true;
2811 }
2812 self.snippet_stack.pop();
2813 }
2814
2815 false
2816 }
2817
2818 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
2819 self.transact(cx, |this, cx| {
2820 this.select_all(&SelectAll, cx);
2821 this.insert("", cx);
2822 });
2823 }
2824
2825 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
2826 let mut selections = self.local_selections::<Point>(cx);
2827 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2828 for selection in &mut selections {
2829 if selection.is_empty() {
2830 let old_head = selection.head();
2831 let mut new_head =
2832 movement::left(&display_map, old_head.to_display_point(&display_map))
2833 .to_point(&display_map);
2834 if let Some((buffer, line_buffer_range)) = display_map
2835 .buffer_snapshot
2836 .buffer_line_for_row(old_head.row)
2837 {
2838 let indent_column = buffer.indent_column_for_line(line_buffer_range.start.row);
2839 if old_head.column <= indent_column && old_head.column > 0 {
2840 let indent = buffer.indent_size();
2841 new_head = cmp::min(
2842 new_head,
2843 Point::new(old_head.row, ((old_head.column - 1) / indent) * indent),
2844 );
2845 }
2846 }
2847
2848 selection.set_head(new_head, SelectionGoal::None);
2849 }
2850 }
2851
2852 self.transact(cx, |this, cx| {
2853 this.update_selections(selections, Some(Autoscroll::Fit), cx);
2854 this.insert("", cx);
2855 });
2856 }
2857
2858 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
2859 self.transact(cx, |this, cx| {
2860 this.move_selections(cx, |map, selection| {
2861 if selection.is_empty() {
2862 let cursor = movement::right(map, selection.head());
2863 selection.set_head(cursor, SelectionGoal::None);
2864 }
2865 });
2866 this.insert(&"", cx);
2867 });
2868 }
2869
2870 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
2871 if self.move_to_next_snippet_tabstop(cx) {
2872 return;
2873 }
2874
2875 let tab_size = cx.global::<Settings>().tab_size;
2876 let mut selections = self.local_selections::<Point>(cx);
2877 self.transact(cx, |this, cx| {
2878 let mut last_indent = None;
2879 this.buffer.update(cx, |buffer, cx| {
2880 for selection in &mut selections {
2881 if selection.is_empty() {
2882 let char_column = buffer
2883 .read(cx)
2884 .text_for_range(Point::new(selection.start.row, 0)..selection.start)
2885 .flat_map(str::chars)
2886 .count();
2887 let chars_to_next_tab_stop = tab_size - (char_column % tab_size);
2888 buffer.edit(
2889 [selection.start..selection.start],
2890 " ".repeat(chars_to_next_tab_stop),
2891 cx,
2892 );
2893 selection.start.column += chars_to_next_tab_stop as u32;
2894 selection.end = selection.start;
2895 } else {
2896 let mut start_row = selection.start.row;
2897 let mut end_row = selection.end.row + 1;
2898
2899 // If a selection ends at the beginning of a line, don't indent
2900 // that last line.
2901 if selection.end.column == 0 {
2902 end_row -= 1;
2903 }
2904
2905 // Avoid re-indenting a row that has already been indented by a
2906 // previous selection, but still update this selection's column
2907 // to reflect that indentation.
2908 if let Some((last_indent_row, last_indent_len)) = last_indent {
2909 if last_indent_row == selection.start.row {
2910 selection.start.column += last_indent_len;
2911 start_row += 1;
2912 }
2913 if last_indent_row == selection.end.row {
2914 selection.end.column += last_indent_len;
2915 }
2916 }
2917
2918 for row in start_row..end_row {
2919 let indent_column =
2920 buffer.read(cx).indent_column_for_line(row) as usize;
2921 let columns_to_next_tab_stop = tab_size - (indent_column % tab_size);
2922 let row_start = Point::new(row, 0);
2923 buffer.edit(
2924 [row_start..row_start],
2925 " ".repeat(columns_to_next_tab_stop),
2926 cx,
2927 );
2928
2929 // Update this selection's endpoints to reflect the indentation.
2930 if row == selection.start.row {
2931 selection.start.column += columns_to_next_tab_stop as u32;
2932 }
2933 if row == selection.end.row {
2934 selection.end.column += columns_to_next_tab_stop as u32;
2935 }
2936
2937 last_indent = Some((row, columns_to_next_tab_stop as u32));
2938 }
2939 }
2940 }
2941 });
2942
2943 this.update_selections(selections, Some(Autoscroll::Fit), cx);
2944 });
2945 }
2946
2947 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
2948 if !self.snippet_stack.is_empty() {
2949 self.move_to_prev_snippet_tabstop(cx);
2950 return;
2951 }
2952
2953 let tab_size = cx.global::<Settings>().tab_size;
2954 let selections = self.local_selections::<Point>(cx);
2955 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2956 let mut deletion_ranges = Vec::new();
2957 let mut last_outdent = None;
2958 {
2959 let buffer = self.buffer.read(cx).read(cx);
2960 for selection in &selections {
2961 let mut rows = selection.spanned_rows(false, &display_map);
2962
2963 // Avoid re-outdenting a row that has already been outdented by a
2964 // previous selection.
2965 if let Some(last_row) = last_outdent {
2966 if last_row == rows.start {
2967 rows.start += 1;
2968 }
2969 }
2970
2971 for row in rows {
2972 let column = buffer.indent_column_for_line(row) as usize;
2973 if column > 0 {
2974 let mut deletion_len = (column % tab_size) as u32;
2975 if deletion_len == 0 {
2976 deletion_len = tab_size as u32;
2977 }
2978 deletion_ranges.push(Point::new(row, 0)..Point::new(row, deletion_len));
2979 last_outdent = Some(row);
2980 }
2981 }
2982 }
2983 }
2984
2985 self.transact(cx, |this, cx| {
2986 this.buffer.update(cx, |buffer, cx| {
2987 buffer.edit(deletion_ranges, "", cx);
2988 });
2989 this.update_selections(
2990 this.local_selections::<usize>(cx),
2991 Some(Autoscroll::Fit),
2992 cx,
2993 );
2994 });
2995 }
2996
2997 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
2998 let selections = self.local_selections::<Point>(cx);
2999 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3000 let buffer = self.buffer.read(cx).snapshot(cx);
3001
3002 let mut new_cursors = Vec::new();
3003 let mut edit_ranges = Vec::new();
3004 let mut selections = selections.iter().peekable();
3005 while let Some(selection) = selections.next() {
3006 let mut rows = selection.spanned_rows(false, &display_map);
3007 let goal_display_column = selection.head().to_display_point(&display_map).column();
3008
3009 // Accumulate contiguous regions of rows that we want to delete.
3010 while let Some(next_selection) = selections.peek() {
3011 let next_rows = next_selection.spanned_rows(false, &display_map);
3012 if next_rows.start <= rows.end {
3013 rows.end = next_rows.end;
3014 selections.next().unwrap();
3015 } else {
3016 break;
3017 }
3018 }
3019
3020 let mut edit_start = Point::new(rows.start, 0).to_offset(&buffer);
3021 let edit_end;
3022 let cursor_buffer_row;
3023 if buffer.max_point().row >= rows.end {
3024 // If there's a line after the range, delete the \n from the end of the row range
3025 // and position the cursor on the next line.
3026 edit_end = Point::new(rows.end, 0).to_offset(&buffer);
3027 cursor_buffer_row = rows.end;
3028 } else {
3029 // If there isn't a line after the range, delete the \n from the line before the
3030 // start of the row range and position the cursor there.
3031 edit_start = edit_start.saturating_sub(1);
3032 edit_end = buffer.len();
3033 cursor_buffer_row = rows.start.saturating_sub(1);
3034 }
3035
3036 let mut cursor = Point::new(cursor_buffer_row, 0).to_display_point(&display_map);
3037 *cursor.column_mut() =
3038 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
3039
3040 new_cursors.push((
3041 selection.id,
3042 buffer.anchor_after(cursor.to_point(&display_map)),
3043 ));
3044 edit_ranges.push(edit_start..edit_end);
3045 }
3046
3047 self.transact(cx, |this, cx| {
3048 let buffer = this.buffer.update(cx, |buffer, cx| {
3049 buffer.edit(edit_ranges, "", cx);
3050 buffer.snapshot(cx)
3051 });
3052 let new_selections = new_cursors
3053 .into_iter()
3054 .map(|(id, cursor)| {
3055 let cursor = cursor.to_point(&buffer);
3056 Selection {
3057 id,
3058 start: cursor,
3059 end: cursor,
3060 reversed: false,
3061 goal: SelectionGoal::None,
3062 }
3063 })
3064 .collect();
3065 this.update_selections(new_selections, Some(Autoscroll::Fit), cx);
3066 });
3067 }
3068
3069 pub fn duplicate_line(&mut self, _: &DuplicateLine, cx: &mut ViewContext<Self>) {
3070 let selections = self.local_selections::<Point>(cx);
3071 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3072 let buffer = &display_map.buffer_snapshot;
3073
3074 let mut edits = Vec::new();
3075 let mut selections_iter = selections.iter().peekable();
3076 while let Some(selection) = selections_iter.next() {
3077 // Avoid duplicating the same lines twice.
3078 let mut rows = selection.spanned_rows(false, &display_map);
3079
3080 while let Some(next_selection) = selections_iter.peek() {
3081 let next_rows = next_selection.spanned_rows(false, &display_map);
3082 if next_rows.start <= rows.end - 1 {
3083 rows.end = next_rows.end;
3084 selections_iter.next().unwrap();
3085 } else {
3086 break;
3087 }
3088 }
3089
3090 // Copy the text from the selected row region and splice it at the start of the region.
3091 let start = Point::new(rows.start, 0);
3092 let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
3093 let text = buffer
3094 .text_for_range(start..end)
3095 .chain(Some("\n"))
3096 .collect::<String>();
3097 edits.push((start, text, rows.len() as u32));
3098 }
3099
3100 self.transact(cx, |this, cx| {
3101 this.buffer.update(cx, |buffer, cx| {
3102 for (point, text, _) in edits.into_iter().rev() {
3103 buffer.edit(Some(point..point), text, cx);
3104 }
3105 });
3106
3107 this.request_autoscroll(Autoscroll::Fit, cx);
3108 });
3109 }
3110
3111 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
3112 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3113 let buffer = self.buffer.read(cx).snapshot(cx);
3114
3115 let mut edits = Vec::new();
3116 let mut unfold_ranges = Vec::new();
3117 let mut refold_ranges = Vec::new();
3118
3119 let selections = self.local_selections::<Point>(cx);
3120 let mut selections = selections.iter().peekable();
3121 let mut contiguous_row_selections = Vec::new();
3122 let mut new_selections = Vec::new();
3123
3124 while let Some(selection) = selections.next() {
3125 // Find all the selections that span a contiguous row range
3126 contiguous_row_selections.push(selection.clone());
3127 let start_row = selection.start.row;
3128 let mut end_row = if selection.end.column > 0 || selection.is_empty() {
3129 display_map.next_line_boundary(selection.end).0.row + 1
3130 } else {
3131 selection.end.row
3132 };
3133
3134 while let Some(next_selection) = selections.peek() {
3135 if next_selection.start.row <= end_row {
3136 end_row = if next_selection.end.column > 0 || next_selection.is_empty() {
3137 display_map.next_line_boundary(next_selection.end).0.row + 1
3138 } else {
3139 next_selection.end.row
3140 };
3141 contiguous_row_selections.push(selections.next().unwrap().clone());
3142 } else {
3143 break;
3144 }
3145 }
3146
3147 // Move the text spanned by the row range to be before the line preceding the row range
3148 if start_row > 0 {
3149 let range_to_move = Point::new(start_row - 1, buffer.line_len(start_row - 1))
3150 ..Point::new(end_row - 1, buffer.line_len(end_row - 1));
3151 let insertion_point = display_map
3152 .prev_line_boundary(Point::new(start_row - 1, 0))
3153 .0;
3154
3155 // Don't move lines across excerpts
3156 if buffer
3157 .excerpt_boundaries_in_range((
3158 Bound::Excluded(insertion_point),
3159 Bound::Included(range_to_move.end),
3160 ))
3161 .next()
3162 .is_none()
3163 {
3164 let text = buffer
3165 .text_for_range(range_to_move.clone())
3166 .flat_map(|s| s.chars())
3167 .skip(1)
3168 .chain(['\n'])
3169 .collect::<String>();
3170
3171 edits.push((
3172 buffer.anchor_after(range_to_move.start)
3173 ..buffer.anchor_before(range_to_move.end),
3174 String::new(),
3175 ));
3176 let insertion_anchor = buffer.anchor_after(insertion_point);
3177 edits.push((insertion_anchor.clone()..insertion_anchor, text));
3178
3179 let row_delta = range_to_move.start.row - insertion_point.row + 1;
3180
3181 // Move selections up
3182 new_selections.extend(contiguous_row_selections.drain(..).map(
3183 |mut selection| {
3184 selection.start.row -= row_delta;
3185 selection.end.row -= row_delta;
3186 selection
3187 },
3188 ));
3189
3190 // Move folds up
3191 unfold_ranges.push(range_to_move.clone());
3192 for fold in display_map.folds_in_range(
3193 buffer.anchor_before(range_to_move.start)
3194 ..buffer.anchor_after(range_to_move.end),
3195 ) {
3196 let mut start = fold.start.to_point(&buffer);
3197 let mut end = fold.end.to_point(&buffer);
3198 start.row -= row_delta;
3199 end.row -= row_delta;
3200 refold_ranges.push(start..end);
3201 }
3202 }
3203 }
3204
3205 // If we didn't move line(s), preserve the existing selections
3206 new_selections.extend(contiguous_row_selections.drain(..));
3207 }
3208
3209 self.transact(cx, |this, cx| {
3210 this.unfold_ranges(unfold_ranges, true, cx);
3211 this.buffer.update(cx, |buffer, cx| {
3212 for (range, text) in edits {
3213 buffer.edit([range], text, cx);
3214 }
3215 });
3216 this.fold_ranges(refold_ranges, cx);
3217 this.update_selections(new_selections, Some(Autoscroll::Fit), cx);
3218 });
3219 }
3220
3221 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
3222 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3223 let buffer = self.buffer.read(cx).snapshot(cx);
3224
3225 let mut edits = Vec::new();
3226 let mut unfold_ranges = Vec::new();
3227 let mut refold_ranges = Vec::new();
3228
3229 let selections = self.local_selections::<Point>(cx);
3230 let mut selections = selections.iter().peekable();
3231 let mut contiguous_row_selections = Vec::new();
3232 let mut new_selections = Vec::new();
3233
3234 while let Some(selection) = selections.next() {
3235 // Find all the selections that span a contiguous row range
3236 contiguous_row_selections.push(selection.clone());
3237 let start_row = selection.start.row;
3238 let mut end_row = if selection.end.column > 0 || selection.is_empty() {
3239 display_map.next_line_boundary(selection.end).0.row + 1
3240 } else {
3241 selection.end.row
3242 };
3243
3244 while let Some(next_selection) = selections.peek() {
3245 if next_selection.start.row <= end_row {
3246 end_row = if next_selection.end.column > 0 || next_selection.is_empty() {
3247 display_map.next_line_boundary(next_selection.end).0.row + 1
3248 } else {
3249 next_selection.end.row
3250 };
3251 contiguous_row_selections.push(selections.next().unwrap().clone());
3252 } else {
3253 break;
3254 }
3255 }
3256
3257 // Move the text spanned by the row range to be after the last line of the row range
3258 if end_row <= buffer.max_point().row {
3259 let range_to_move = Point::new(start_row, 0)..Point::new(end_row, 0);
3260 let insertion_point = display_map.next_line_boundary(Point::new(end_row, 0)).0;
3261
3262 // Don't move lines across excerpt boundaries
3263 if buffer
3264 .excerpt_boundaries_in_range((
3265 Bound::Excluded(range_to_move.start),
3266 Bound::Included(insertion_point),
3267 ))
3268 .next()
3269 .is_none()
3270 {
3271 let mut text = String::from("\n");
3272 text.extend(buffer.text_for_range(range_to_move.clone()));
3273 text.pop(); // Drop trailing newline
3274 edits.push((
3275 buffer.anchor_after(range_to_move.start)
3276 ..buffer.anchor_before(range_to_move.end),
3277 String::new(),
3278 ));
3279 let insertion_anchor = buffer.anchor_after(insertion_point);
3280 edits.push((insertion_anchor.clone()..insertion_anchor, text));
3281
3282 let row_delta = insertion_point.row - range_to_move.end.row + 1;
3283
3284 // Move selections down
3285 new_selections.extend(contiguous_row_selections.drain(..).map(
3286 |mut selection| {
3287 selection.start.row += row_delta;
3288 selection.end.row += row_delta;
3289 selection
3290 },
3291 ));
3292
3293 // Move folds down
3294 unfold_ranges.push(range_to_move.clone());
3295 for fold in display_map.folds_in_range(
3296 buffer.anchor_before(range_to_move.start)
3297 ..buffer.anchor_after(range_to_move.end),
3298 ) {
3299 let mut start = fold.start.to_point(&buffer);
3300 let mut end = fold.end.to_point(&buffer);
3301 start.row += row_delta;
3302 end.row += row_delta;
3303 refold_ranges.push(start..end);
3304 }
3305 }
3306 }
3307
3308 // If we didn't move line(s), preserve the existing selections
3309 new_selections.extend(contiguous_row_selections.drain(..));
3310 }
3311
3312 self.transact(cx, |this, cx| {
3313 this.unfold_ranges(unfold_ranges, true, cx);
3314 this.buffer.update(cx, |buffer, cx| {
3315 for (range, text) in edits {
3316 buffer.edit([range], text, cx);
3317 }
3318 });
3319 this.fold_ranges(refold_ranges, cx);
3320 this.update_selections(new_selections, Some(Autoscroll::Fit), cx);
3321 });
3322 }
3323
3324 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
3325 let mut text = String::new();
3326 let mut selections = self.local_selections::<Point>(cx);
3327 let mut clipboard_selections = Vec::with_capacity(selections.len());
3328 {
3329 let buffer = self.buffer.read(cx).read(cx);
3330 let max_point = buffer.max_point();
3331 for selection in &mut selections {
3332 let is_entire_line = selection.is_empty();
3333 if is_entire_line {
3334 selection.start = Point::new(selection.start.row, 0);
3335 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
3336 selection.goal = SelectionGoal::None;
3337 }
3338 let mut len = 0;
3339 for chunk in buffer.text_for_range(selection.start..selection.end) {
3340 text.push_str(chunk);
3341 len += chunk.len();
3342 }
3343 clipboard_selections.push(ClipboardSelection {
3344 len,
3345 is_entire_line,
3346 });
3347 }
3348 }
3349
3350 self.transact(cx, |this, cx| {
3351 this.update_selections(selections, Some(Autoscroll::Fit), cx);
3352 this.insert("", cx);
3353 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
3354 });
3355 }
3356
3357 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
3358 let selections = self.local_selections::<Point>(cx);
3359 let mut text = String::new();
3360 let mut clipboard_selections = Vec::with_capacity(selections.len());
3361 {
3362 let buffer = self.buffer.read(cx).read(cx);
3363 let max_point = buffer.max_point();
3364 for selection in selections.iter() {
3365 let mut start = selection.start;
3366 let mut end = selection.end;
3367 let is_entire_line = selection.is_empty();
3368 if is_entire_line {
3369 start = Point::new(start.row, 0);
3370 end = cmp::min(max_point, Point::new(start.row + 1, 0));
3371 }
3372 let mut len = 0;
3373 for chunk in buffer.text_for_range(start..end) {
3374 text.push_str(chunk);
3375 len += chunk.len();
3376 }
3377 clipboard_selections.push(ClipboardSelection {
3378 len,
3379 is_entire_line,
3380 });
3381 }
3382 }
3383
3384 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
3385 }
3386
3387 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
3388 self.transact(cx, |this, cx| {
3389 if let Some(item) = cx.as_mut().read_from_clipboard() {
3390 let clipboard_text = item.text();
3391 if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
3392 let mut selections = this.local_selections::<usize>(cx);
3393 let all_selections_were_entire_line =
3394 clipboard_selections.iter().all(|s| s.is_entire_line);
3395 if clipboard_selections.len() != selections.len() {
3396 clipboard_selections.clear();
3397 }
3398
3399 let mut delta = 0_isize;
3400 let mut start_offset = 0;
3401 for (i, selection) in selections.iter_mut().enumerate() {
3402 let to_insert;
3403 let entire_line;
3404 if let Some(clipboard_selection) = clipboard_selections.get(i) {
3405 let end_offset = start_offset + clipboard_selection.len;
3406 to_insert = &clipboard_text[start_offset..end_offset];
3407 entire_line = clipboard_selection.is_entire_line;
3408 start_offset = end_offset
3409 } else {
3410 to_insert = clipboard_text.as_str();
3411 entire_line = all_selections_were_entire_line;
3412 }
3413
3414 selection.start = (selection.start as isize + delta) as usize;
3415 selection.end = (selection.end as isize + delta) as usize;
3416
3417 this.buffer.update(cx, |buffer, cx| {
3418 // If the corresponding selection was empty when this slice of the
3419 // clipboard text was written, then the entire line containing the
3420 // selection was copied. If this selection is also currently empty,
3421 // then paste the line before the current line of the buffer.
3422 let range = if selection.is_empty() && entire_line {
3423 let column =
3424 selection.start.to_point(&buffer.read(cx)).column as usize;
3425 let line_start = selection.start - column;
3426 line_start..line_start
3427 } else {
3428 selection.start..selection.end
3429 };
3430
3431 delta += to_insert.len() as isize - range.len() as isize;
3432 buffer.edit([range], to_insert, cx);
3433 selection.start += to_insert.len();
3434 selection.end = selection.start;
3435 });
3436 }
3437 this.update_selections(selections, Some(Autoscroll::Fit), cx);
3438 } else {
3439 this.insert(clipboard_text, cx);
3440 }
3441 }
3442 });
3443 }
3444
3445 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
3446 if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
3447 if let Some((selections, _)) = self.selection_history.get(&tx_id).cloned() {
3448 self.set_selections(selections, None, true, cx);
3449 }
3450 self.request_autoscroll(Autoscroll::Fit, cx);
3451 cx.emit(Event::Edited);
3452 }
3453 }
3454
3455 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
3456 if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
3457 if let Some((_, Some(selections))) = self.selection_history.get(&tx_id).cloned() {
3458 self.set_selections(selections, None, true, cx);
3459 }
3460 self.request_autoscroll(Autoscroll::Fit, cx);
3461 cx.emit(Event::Edited);
3462 }
3463 }
3464
3465 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
3466 self.buffer
3467 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
3468 }
3469
3470 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
3471 self.move_selections(cx, |map, selection| {
3472 let cursor = if selection.is_empty() {
3473 movement::left(map, selection.start)
3474 } else {
3475 selection.start
3476 };
3477 selection.collapse_to(cursor, SelectionGoal::None);
3478 });
3479 }
3480
3481 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
3482 self.move_selection_heads(cx, |map, head, _| {
3483 (movement::left(map, head), SelectionGoal::None)
3484 });
3485 }
3486
3487 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
3488 self.move_selections(cx, |map, selection| {
3489 let cursor = if selection.is_empty() {
3490 movement::right(map, selection.end)
3491 } else {
3492 selection.end
3493 };
3494 selection.collapse_to(cursor, SelectionGoal::None)
3495 });
3496 }
3497
3498 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
3499 self.move_selection_heads(cx, |map, head, _| {
3500 (movement::right(map, head), SelectionGoal::None)
3501 });
3502 }
3503
3504 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
3505 if self.take_rename(true, cx).is_some() {
3506 return;
3507 }
3508
3509 if let Some(context_menu) = self.context_menu.as_mut() {
3510 if context_menu.select_prev(cx) {
3511 return;
3512 }
3513 }
3514
3515 if matches!(self.mode, EditorMode::SingleLine) {
3516 cx.propagate_action();
3517 return;
3518 }
3519
3520 self.move_selections(cx, |map, selection| {
3521 if !selection.is_empty() {
3522 selection.goal = SelectionGoal::None;
3523 }
3524 let (cursor, goal) = movement::up(&map, selection.start, selection.goal);
3525 selection.collapse_to(cursor, goal);
3526 });
3527 }
3528
3529 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
3530 self.move_selection_heads(cx, movement::up)
3531 }
3532
3533 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
3534 self.take_rename(true, cx);
3535
3536 if let Some(context_menu) = self.context_menu.as_mut() {
3537 if context_menu.select_next(cx) {
3538 return;
3539 }
3540 }
3541
3542 if matches!(self.mode, EditorMode::SingleLine) {
3543 cx.propagate_action();
3544 return;
3545 }
3546
3547 self.move_selections(cx, |map, selection| {
3548 if !selection.is_empty() {
3549 selection.goal = SelectionGoal::None;
3550 }
3551 let (cursor, goal) = movement::down(&map, selection.end, selection.goal);
3552 selection.collapse_to(cursor, goal);
3553 });
3554 }
3555
3556 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
3557 self.move_selection_heads(cx, movement::down)
3558 }
3559
3560 pub fn move_to_previous_word_start(
3561 &mut self,
3562 _: &MoveToPreviousWordStart,
3563 cx: &mut ViewContext<Self>,
3564 ) {
3565 self.move_cursors(cx, |map, head, _| {
3566 (
3567 movement::previous_word_start(map, head),
3568 SelectionGoal::None,
3569 )
3570 });
3571 }
3572
3573 pub fn move_to_previous_subword_start(
3574 &mut self,
3575 _: &MoveToPreviousSubwordStart,
3576 cx: &mut ViewContext<Self>,
3577 ) {
3578 self.move_cursors(cx, |map, head, _| {
3579 (
3580 movement::previous_subword_start(map, head),
3581 SelectionGoal::None,
3582 )
3583 });
3584 }
3585
3586 pub fn select_to_previous_word_start(
3587 &mut self,
3588 _: &SelectToPreviousWordStart,
3589 cx: &mut ViewContext<Self>,
3590 ) {
3591 self.move_selection_heads(cx, |map, head, _| {
3592 (
3593 movement::previous_word_start(map, head),
3594 SelectionGoal::None,
3595 )
3596 });
3597 }
3598
3599 pub fn select_to_previous_subword_start(
3600 &mut self,
3601 _: &SelectToPreviousSubwordStart,
3602 cx: &mut ViewContext<Self>,
3603 ) {
3604 self.move_selection_heads(cx, |map, head, _| {
3605 (
3606 movement::previous_subword_start(map, head),
3607 SelectionGoal::None,
3608 )
3609 });
3610 }
3611
3612 pub fn delete_to_previous_word_start(
3613 &mut self,
3614 _: &DeleteToPreviousWordStart,
3615 cx: &mut ViewContext<Self>,
3616 ) {
3617 self.transact(cx, |this, cx| {
3618 this.move_selections(cx, |map, selection| {
3619 if selection.is_empty() {
3620 let cursor = movement::previous_word_start(map, selection.head());
3621 selection.set_head(cursor, SelectionGoal::None);
3622 }
3623 });
3624 this.insert("", cx);
3625 });
3626 }
3627
3628 pub fn delete_to_previous_subword_start(
3629 &mut self,
3630 _: &DeleteToPreviousSubwordStart,
3631 cx: &mut ViewContext<Self>,
3632 ) {
3633 self.transact(cx, |this, cx| {
3634 this.move_selections(cx, |map, selection| {
3635 if selection.is_empty() {
3636 let cursor = movement::previous_subword_start(map, selection.head());
3637 selection.set_head(cursor, SelectionGoal::None);
3638 }
3639 });
3640 this.insert("", cx);
3641 });
3642 }
3643
3644 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
3645 self.move_cursors(cx, |map, head, _| {
3646 (movement::next_word_end(map, head), SelectionGoal::None)
3647 });
3648 }
3649
3650 pub fn move_to_next_subword_end(
3651 &mut self,
3652 _: &MoveToNextSubwordEnd,
3653 cx: &mut ViewContext<Self>,
3654 ) {
3655 self.move_cursors(cx, |map, head, _| {
3656 (movement::next_subword_end(map, head), SelectionGoal::None)
3657 });
3658 }
3659
3660 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
3661 self.move_selection_heads(cx, |map, head, _| {
3662 (movement::next_word_end(map, head), SelectionGoal::None)
3663 });
3664 }
3665
3666 pub fn select_to_next_subword_end(
3667 &mut self,
3668 _: &SelectToNextSubwordEnd,
3669 cx: &mut ViewContext<Self>,
3670 ) {
3671 self.move_selection_heads(cx, |map, head, _| {
3672 (movement::next_subword_end(map, head), SelectionGoal::None)
3673 });
3674 }
3675
3676 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
3677 self.transact(cx, |this, cx| {
3678 this.move_selections(cx, |map, selection| {
3679 if selection.is_empty() {
3680 let cursor = movement::next_word_end(map, selection.head());
3681 selection.set_head(cursor, SelectionGoal::None);
3682 }
3683 });
3684 this.insert("", cx);
3685 });
3686 }
3687
3688 pub fn delete_to_next_subword_end(
3689 &mut self,
3690 _: &DeleteToNextSubwordEnd,
3691 cx: &mut ViewContext<Self>,
3692 ) {
3693 self.transact(cx, |this, cx| {
3694 this.move_selections(cx, |map, selection| {
3695 if selection.is_empty() {
3696 let cursor = movement::next_subword_end(map, selection.head());
3697 selection.set_head(cursor, SelectionGoal::None);
3698 }
3699 });
3700 this.insert("", cx);
3701 });
3702 }
3703
3704 pub fn move_to_beginning_of_line(
3705 &mut self,
3706 _: &MoveToBeginningOfLine,
3707 cx: &mut ViewContext<Self>,
3708 ) {
3709 self.move_cursors(cx, |map, head, _| {
3710 (
3711 movement::line_beginning(map, head, true),
3712 SelectionGoal::None,
3713 )
3714 });
3715 }
3716
3717 pub fn select_to_beginning_of_line(
3718 &mut self,
3719 SelectToBeginningOfLine(stop_at_soft_boundaries): &SelectToBeginningOfLine,
3720 cx: &mut ViewContext<Self>,
3721 ) {
3722 self.move_selection_heads(cx, |map, head, _| {
3723 (
3724 movement::line_beginning(map, head, *stop_at_soft_boundaries),
3725 SelectionGoal::None,
3726 )
3727 });
3728 }
3729
3730 pub fn delete_to_beginning_of_line(
3731 &mut self,
3732 _: &DeleteToBeginningOfLine,
3733 cx: &mut ViewContext<Self>,
3734 ) {
3735 self.transact(cx, |this, cx| {
3736 this.select_to_beginning_of_line(&SelectToBeginningOfLine(false), cx);
3737 this.backspace(&Backspace, cx);
3738 });
3739 }
3740
3741 pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
3742 self.move_cursors(cx, |map, head, _| {
3743 (movement::line_end(map, head, true), SelectionGoal::None)
3744 });
3745 }
3746
3747 pub fn select_to_end_of_line(
3748 &mut self,
3749 SelectToEndOfLine(stop_at_soft_boundaries): &SelectToEndOfLine,
3750 cx: &mut ViewContext<Self>,
3751 ) {
3752 self.move_selection_heads(cx, |map, head, _| {
3753 (
3754 movement::line_end(map, head, *stop_at_soft_boundaries),
3755 SelectionGoal::None,
3756 )
3757 });
3758 }
3759
3760 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
3761 self.transact(cx, |this, cx| {
3762 this.select_to_end_of_line(&SelectToEndOfLine(false), cx);
3763 this.delete(&Delete, cx);
3764 });
3765 }
3766
3767 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
3768 self.transact(cx, |this, cx| {
3769 this.select_to_end_of_line(&SelectToEndOfLine(false), cx);
3770 this.cut(&Cut, cx);
3771 });
3772 }
3773
3774 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
3775 if matches!(self.mode, EditorMode::SingleLine) {
3776 cx.propagate_action();
3777 return;
3778 }
3779
3780 let selection = Selection {
3781 id: post_inc(&mut self.next_selection_id),
3782 start: 0,
3783 end: 0,
3784 reversed: false,
3785 goal: SelectionGoal::None,
3786 };
3787 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
3788 }
3789
3790 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
3791 let mut selection = self.local_selections::<Point>(cx).last().unwrap().clone();
3792 selection.set_head(Point::zero(), SelectionGoal::None);
3793 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
3794 }
3795
3796 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
3797 if matches!(self.mode, EditorMode::SingleLine) {
3798 cx.propagate_action();
3799 return;
3800 }
3801
3802 let cursor = self.buffer.read(cx).read(cx).len();
3803 let selection = Selection {
3804 id: post_inc(&mut self.next_selection_id),
3805 start: cursor,
3806 end: cursor,
3807 reversed: false,
3808 goal: SelectionGoal::None,
3809 };
3810 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
3811 }
3812
3813 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
3814 self.nav_history = nav_history;
3815 }
3816
3817 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
3818 self.nav_history.as_ref()
3819 }
3820
3821 fn push_to_nav_history(
3822 &self,
3823 position: Anchor,
3824 new_position: Option<Point>,
3825 cx: &mut ViewContext<Self>,
3826 ) {
3827 if let Some(nav_history) = &self.nav_history {
3828 let buffer = self.buffer.read(cx).read(cx);
3829 let offset = position.to_offset(&buffer);
3830 let point = position.to_point(&buffer);
3831 drop(buffer);
3832
3833 if let Some(new_position) = new_position {
3834 let row_delta = (new_position.row as i64 - point.row as i64).abs();
3835 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
3836 return;
3837 }
3838 }
3839
3840 nav_history.push(Some(NavigationData {
3841 anchor: position,
3842 offset,
3843 }));
3844 }
3845 }
3846
3847 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
3848 let mut selection = self.local_selections::<usize>(cx).first().unwrap().clone();
3849 selection.set_head(self.buffer.read(cx).read(cx).len(), SelectionGoal::None);
3850 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
3851 }
3852
3853 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
3854 let selection = Selection {
3855 id: post_inc(&mut self.next_selection_id),
3856 start: 0,
3857 end: self.buffer.read(cx).read(cx).len(),
3858 reversed: false,
3859 goal: SelectionGoal::None,
3860 };
3861 self.update_selections(vec![selection], None, cx);
3862 }
3863
3864 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
3865 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3866 let mut selections = self.local_selections::<Point>(cx);
3867 let max_point = display_map.buffer_snapshot.max_point();
3868 for selection in &mut selections {
3869 let rows = selection.spanned_rows(true, &display_map);
3870 selection.start = Point::new(rows.start, 0);
3871 selection.end = cmp::min(max_point, Point::new(rows.end, 0));
3872 selection.reversed = false;
3873 }
3874 self.update_selections(selections, Some(Autoscroll::Fit), cx);
3875 }
3876
3877 pub fn split_selection_into_lines(
3878 &mut self,
3879 _: &SplitSelectionIntoLines,
3880 cx: &mut ViewContext<Self>,
3881 ) {
3882 let mut to_unfold = Vec::new();
3883 let mut new_selections = Vec::new();
3884 {
3885 let selections = self.local_selections::<Point>(cx);
3886 let buffer = self.buffer.read(cx).read(cx);
3887 for selection in selections {
3888 for row in selection.start.row..selection.end.row {
3889 let cursor = Point::new(row, buffer.line_len(row));
3890 new_selections.push(Selection {
3891 id: post_inc(&mut self.next_selection_id),
3892 start: cursor,
3893 end: cursor,
3894 reversed: false,
3895 goal: SelectionGoal::None,
3896 });
3897 }
3898 new_selections.push(Selection {
3899 id: selection.id,
3900 start: selection.end,
3901 end: selection.end,
3902 reversed: false,
3903 goal: SelectionGoal::None,
3904 });
3905 to_unfold.push(selection.start..selection.end);
3906 }
3907 }
3908 self.unfold_ranges(to_unfold, true, cx);
3909 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
3910 }
3911
3912 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
3913 self.add_selection(true, cx);
3914 }
3915
3916 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
3917 self.add_selection(false, cx);
3918 }
3919
3920 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
3921 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3922 let mut selections = self.local_selections::<Point>(cx);
3923 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
3924 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
3925 let range = oldest_selection.display_range(&display_map).sorted();
3926 let columns = cmp::min(range.start.column(), range.end.column())
3927 ..cmp::max(range.start.column(), range.end.column());
3928
3929 selections.clear();
3930 let mut stack = Vec::new();
3931 for row in range.start.row()..=range.end.row() {
3932 if let Some(selection) = self.build_columnar_selection(
3933 &display_map,
3934 row,
3935 &columns,
3936 oldest_selection.reversed,
3937 ) {
3938 stack.push(selection.id);
3939 selections.push(selection);
3940 }
3941 }
3942
3943 if above {
3944 stack.reverse();
3945 }
3946
3947 AddSelectionsState { above, stack }
3948 });
3949
3950 let last_added_selection = *state.stack.last().unwrap();
3951 let mut new_selections = Vec::new();
3952 if above == state.above {
3953 let end_row = if above {
3954 0
3955 } else {
3956 display_map.max_point().row()
3957 };
3958
3959 'outer: for selection in selections {
3960 if selection.id == last_added_selection {
3961 let range = selection.display_range(&display_map).sorted();
3962 debug_assert_eq!(range.start.row(), range.end.row());
3963 let mut row = range.start.row();
3964 let columns = if let SelectionGoal::ColumnRange { start, end } = selection.goal
3965 {
3966 start..end
3967 } else {
3968 cmp::min(range.start.column(), range.end.column())
3969 ..cmp::max(range.start.column(), range.end.column())
3970 };
3971
3972 while row != end_row {
3973 if above {
3974 row -= 1;
3975 } else {
3976 row += 1;
3977 }
3978
3979 if let Some(new_selection) = self.build_columnar_selection(
3980 &display_map,
3981 row,
3982 &columns,
3983 selection.reversed,
3984 ) {
3985 state.stack.push(new_selection.id);
3986 if above {
3987 new_selections.push(new_selection);
3988 new_selections.push(selection);
3989 } else {
3990 new_selections.push(selection);
3991 new_selections.push(new_selection);
3992 }
3993
3994 continue 'outer;
3995 }
3996 }
3997 }
3998
3999 new_selections.push(selection);
4000 }
4001 } else {
4002 new_selections = selections;
4003 new_selections.retain(|s| s.id != last_added_selection);
4004 state.stack.pop();
4005 }
4006
4007 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
4008 if state.stack.len() > 1 {
4009 self.add_selections_state = Some(state);
4010 }
4011 }
4012
4013 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) {
4014 let replace_newest = action.0;
4015 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4016 let buffer = &display_map.buffer_snapshot;
4017 let mut selections = self.local_selections::<usize>(cx);
4018 if let Some(mut select_next_state) = self.select_next_state.take() {
4019 let query = &select_next_state.query;
4020 if !select_next_state.done {
4021 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
4022 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
4023 let mut next_selected_range = None;
4024
4025 let bytes_after_last_selection =
4026 buffer.bytes_in_range(last_selection.end..buffer.len());
4027 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
4028 let query_matches = query
4029 .stream_find_iter(bytes_after_last_selection)
4030 .map(|result| (last_selection.end, result))
4031 .chain(
4032 query
4033 .stream_find_iter(bytes_before_first_selection)
4034 .map(|result| (0, result)),
4035 );
4036 for (start_offset, query_match) in query_matches {
4037 let query_match = query_match.unwrap(); // can only fail due to I/O
4038 let offset_range =
4039 start_offset + query_match.start()..start_offset + query_match.end();
4040 let display_range = offset_range.start.to_display_point(&display_map)
4041 ..offset_range.end.to_display_point(&display_map);
4042
4043 if !select_next_state.wordwise
4044 || (!movement::is_inside_word(&display_map, display_range.start)
4045 && !movement::is_inside_word(&display_map, display_range.end))
4046 {
4047 next_selected_range = Some(offset_range);
4048 break;
4049 }
4050 }
4051
4052 if let Some(next_selected_range) = next_selected_range {
4053 if replace_newest {
4054 if let Some(newest_id) =
4055 selections.iter().max_by_key(|s| s.id).map(|s| s.id)
4056 {
4057 selections.retain(|s| s.id != newest_id);
4058 }
4059 }
4060 selections.push(Selection {
4061 id: post_inc(&mut self.next_selection_id),
4062 start: next_selected_range.start,
4063 end: next_selected_range.end,
4064 reversed: false,
4065 goal: SelectionGoal::None,
4066 });
4067 self.unfold_ranges([next_selected_range], false, cx);
4068 self.update_selections(selections, Some(Autoscroll::Newest), cx);
4069 } else {
4070 select_next_state.done = true;
4071 }
4072 }
4073
4074 self.select_next_state = Some(select_next_state);
4075 } else if selections.len() == 1 {
4076 let selection = selections.last_mut().unwrap();
4077 if selection.start == selection.end {
4078 let word_range = movement::surrounding_word(
4079 &display_map,
4080 selection.start.to_display_point(&display_map),
4081 );
4082 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
4083 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
4084 selection.goal = SelectionGoal::None;
4085 selection.reversed = false;
4086
4087 let query = buffer
4088 .text_for_range(selection.start..selection.end)
4089 .collect::<String>();
4090 let select_state = SelectNextState {
4091 query: AhoCorasick::new_auto_configured(&[query]),
4092 wordwise: true,
4093 done: false,
4094 };
4095 self.unfold_ranges([selection.start..selection.end], false, cx);
4096 self.update_selections(selections, Some(Autoscroll::Newest), cx);
4097 self.select_next_state = Some(select_state);
4098 } else {
4099 let query = buffer
4100 .text_for_range(selection.start..selection.end)
4101 .collect::<String>();
4102 self.select_next_state = Some(SelectNextState {
4103 query: AhoCorasick::new_auto_configured(&[query]),
4104 wordwise: false,
4105 done: false,
4106 });
4107 self.select_next(action, cx);
4108 }
4109 }
4110 }
4111
4112 pub fn toggle_comments(&mut self, _: &ToggleComments, cx: &mut ViewContext<Self>) {
4113 // Get the line comment prefix. Split its trailing whitespace into a separate string,
4114 // as that portion won't be used for detecting if a line is a comment.
4115 let full_comment_prefix =
4116 if let Some(prefix) = self.language(cx).and_then(|l| l.line_comment_prefix()) {
4117 prefix.to_string()
4118 } else {
4119 return;
4120 };
4121 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
4122 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
4123
4124 self.transact(cx, |this, cx| {
4125 let mut selections = this.local_selections::<Point>(cx);
4126 let mut all_selection_lines_are_comments = true;
4127 let mut edit_ranges = Vec::new();
4128 let mut last_toggled_row = None;
4129 this.buffer.update(cx, |buffer, cx| {
4130 for selection in &mut selections {
4131 edit_ranges.clear();
4132 let snapshot = buffer.snapshot(cx);
4133
4134 let end_row =
4135 if selection.end.row > selection.start.row && selection.end.column == 0 {
4136 selection.end.row
4137 } else {
4138 selection.end.row + 1
4139 };
4140
4141 for row in selection.start.row..end_row {
4142 // If multiple selections contain a given row, avoid processing that
4143 // row more than once.
4144 if last_toggled_row == Some(row) {
4145 continue;
4146 } else {
4147 last_toggled_row = Some(row);
4148 }
4149
4150 if snapshot.is_line_blank(row) {
4151 continue;
4152 }
4153
4154 let start = Point::new(row, snapshot.indent_column_for_line(row));
4155 let mut line_bytes = snapshot
4156 .bytes_in_range(start..snapshot.max_point())
4157 .flatten()
4158 .copied();
4159
4160 // If this line currently begins with the line comment prefix, then record
4161 // the range containing the prefix.
4162 if all_selection_lines_are_comments
4163 && line_bytes
4164 .by_ref()
4165 .take(comment_prefix.len())
4166 .eq(comment_prefix.bytes())
4167 {
4168 // Include any whitespace that matches the comment prefix.
4169 let matching_whitespace_len = line_bytes
4170 .zip(comment_prefix_whitespace.bytes())
4171 .take_while(|(a, b)| a == b)
4172 .count()
4173 as u32;
4174 let end = Point::new(
4175 row,
4176 start.column
4177 + comment_prefix.len() as u32
4178 + matching_whitespace_len,
4179 );
4180 edit_ranges.push(start..end);
4181 }
4182 // If this line does not begin with the line comment prefix, then record
4183 // the position where the prefix should be inserted.
4184 else {
4185 all_selection_lines_are_comments = false;
4186 edit_ranges.push(start..start);
4187 }
4188 }
4189
4190 if !edit_ranges.is_empty() {
4191 if all_selection_lines_are_comments {
4192 buffer.edit(edit_ranges.iter().cloned(), "", cx);
4193 } else {
4194 let min_column =
4195 edit_ranges.iter().map(|r| r.start.column).min().unwrap();
4196 let edit_ranges = edit_ranges.iter().map(|range| {
4197 let position = Point::new(range.start.row, min_column);
4198 position..position
4199 });
4200 buffer.edit(edit_ranges, &full_comment_prefix, cx);
4201 }
4202 }
4203 }
4204 });
4205
4206 this.update_selections(
4207 this.local_selections::<usize>(cx),
4208 Some(Autoscroll::Fit),
4209 cx,
4210 );
4211 });
4212 }
4213
4214 pub fn select_larger_syntax_node(
4215 &mut self,
4216 _: &SelectLargerSyntaxNode,
4217 cx: &mut ViewContext<Self>,
4218 ) {
4219 let old_selections = self.local_selections::<usize>(cx).into_boxed_slice();
4220 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4221 let buffer = self.buffer.read(cx).snapshot(cx);
4222
4223 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
4224 let mut selected_larger_node = false;
4225 let new_selections = old_selections
4226 .iter()
4227 .map(|selection| {
4228 let old_range = selection.start..selection.end;
4229 let mut new_range = old_range.clone();
4230 while let Some(containing_range) =
4231 buffer.range_for_syntax_ancestor(new_range.clone())
4232 {
4233 new_range = containing_range;
4234 if !display_map.intersects_fold(new_range.start)
4235 && !display_map.intersects_fold(new_range.end)
4236 {
4237 break;
4238 }
4239 }
4240
4241 selected_larger_node |= new_range != old_range;
4242 Selection {
4243 id: selection.id,
4244 start: new_range.start,
4245 end: new_range.end,
4246 goal: SelectionGoal::None,
4247 reversed: selection.reversed,
4248 }
4249 })
4250 .collect::<Vec<_>>();
4251
4252 if selected_larger_node {
4253 stack.push(old_selections);
4254 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
4255 }
4256 self.select_larger_syntax_node_stack = stack;
4257 }
4258
4259 pub fn select_smaller_syntax_node(
4260 &mut self,
4261 _: &SelectSmallerSyntaxNode,
4262 cx: &mut ViewContext<Self>,
4263 ) {
4264 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
4265 if let Some(selections) = stack.pop() {
4266 self.update_selections(selections.to_vec(), Some(Autoscroll::Fit), cx);
4267 }
4268 self.select_larger_syntax_node_stack = stack;
4269 }
4270
4271 pub fn move_to_enclosing_bracket(
4272 &mut self,
4273 _: &MoveToEnclosingBracket,
4274 cx: &mut ViewContext<Self>,
4275 ) {
4276 let mut selections = self.local_selections::<usize>(cx);
4277 let buffer = self.buffer.read(cx).snapshot(cx);
4278 for selection in &mut selections {
4279 if let Some((open_range, close_range)) =
4280 buffer.enclosing_bracket_ranges(selection.start..selection.end)
4281 {
4282 let close_range = close_range.to_inclusive();
4283 let destination = if close_range.contains(&selection.start)
4284 && close_range.contains(&selection.end)
4285 {
4286 open_range.end
4287 } else {
4288 *close_range.start()
4289 };
4290 selection.start = destination;
4291 selection.end = destination;
4292 }
4293 }
4294
4295 self.update_selections(selections, Some(Autoscroll::Fit), cx);
4296 }
4297
4298 pub fn go_to_diagnostic(
4299 &mut self,
4300 &GoToDiagnostic(direction): &GoToDiagnostic,
4301 cx: &mut ViewContext<Self>,
4302 ) {
4303 let buffer = self.buffer.read(cx).snapshot(cx);
4304 let selection = self.newest_selection_with_snapshot::<usize>(&buffer);
4305 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
4306 active_diagnostics
4307 .primary_range
4308 .to_offset(&buffer)
4309 .to_inclusive()
4310 });
4311 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
4312 if active_primary_range.contains(&selection.head()) {
4313 *active_primary_range.end()
4314 } else {
4315 selection.head()
4316 }
4317 } else {
4318 selection.head()
4319 };
4320
4321 loop {
4322 let mut diagnostics = if direction == Direction::Prev {
4323 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
4324 } else {
4325 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
4326 };
4327 let group = diagnostics.find_map(|entry| {
4328 if entry.diagnostic.is_primary
4329 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
4330 && !entry.range.is_empty()
4331 && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
4332 {
4333 Some((entry.range, entry.diagnostic.group_id))
4334 } else {
4335 None
4336 }
4337 });
4338
4339 if let Some((primary_range, group_id)) = group {
4340 self.activate_diagnostics(group_id, cx);
4341 self.update_selections(
4342 vec![Selection {
4343 id: selection.id,
4344 start: primary_range.start,
4345 end: primary_range.start,
4346 reversed: false,
4347 goal: SelectionGoal::None,
4348 }],
4349 Some(Autoscroll::Center),
4350 cx,
4351 );
4352 break;
4353 } else {
4354 // Cycle around to the start of the buffer, potentially moving back to the start of
4355 // the currently active diagnostic.
4356 active_primary_range.take();
4357 if direction == Direction::Prev {
4358 if search_start == buffer.len() {
4359 break;
4360 } else {
4361 search_start = buffer.len();
4362 }
4363 } else {
4364 if search_start == 0 {
4365 break;
4366 } else {
4367 search_start = 0;
4368 }
4369 }
4370 }
4371 }
4372 }
4373
4374 pub fn go_to_definition(
4375 workspace: &mut Workspace,
4376 _: &GoToDefinition,
4377 cx: &mut ViewContext<Workspace>,
4378 ) {
4379 let active_item = workspace.active_item(cx);
4380 let editor_handle = if let Some(editor) = active_item
4381 .as_ref()
4382 .and_then(|item| item.act_as::<Self>(cx))
4383 {
4384 editor
4385 } else {
4386 return;
4387 };
4388
4389 let editor = editor_handle.read(cx);
4390 let head = editor.newest_selection::<usize>(cx).head();
4391 let (buffer, head) =
4392 if let Some(text_anchor) = editor.buffer.read(cx).text_anchor_for_position(head, cx) {
4393 text_anchor
4394 } else {
4395 return;
4396 };
4397
4398 let project = workspace.project().clone();
4399 let definitions = project.update(cx, |project, cx| project.definition(&buffer, head, cx));
4400 cx.spawn(|workspace, mut cx| async move {
4401 let definitions = definitions.await?;
4402 workspace.update(&mut cx, |workspace, cx| {
4403 let nav_history = workspace.active_pane().read(cx).nav_history().clone();
4404 for definition in definitions {
4405 let range = definition.range.to_offset(definition.buffer.read(cx));
4406
4407 let target_editor_handle = workspace.open_project_item(definition.buffer, cx);
4408 target_editor_handle.update(cx, |target_editor, cx| {
4409 // When selecting a definition in a different buffer, disable the nav history
4410 // to avoid creating a history entry at the previous cursor location.
4411 if editor_handle != target_editor_handle {
4412 nav_history.borrow_mut().disable();
4413 }
4414 target_editor.select_ranges([range], Some(Autoscroll::Center), cx);
4415 nav_history.borrow_mut().enable();
4416 });
4417 }
4418 });
4419
4420 Ok::<(), anyhow::Error>(())
4421 })
4422 .detach_and_log_err(cx);
4423 }
4424
4425 pub fn find_all_references(
4426 workspace: &mut Workspace,
4427 _: &FindAllReferences,
4428 cx: &mut ViewContext<Workspace>,
4429 ) -> Option<Task<Result<()>>> {
4430 let active_item = workspace.active_item(cx)?;
4431 let editor_handle = active_item.act_as::<Self>(cx)?;
4432
4433 let editor = editor_handle.read(cx);
4434 let head = editor.newest_selection::<usize>(cx).head();
4435 let (buffer, head) = editor.buffer.read(cx).text_anchor_for_position(head, cx)?;
4436 let replica_id = editor.replica_id(cx);
4437
4438 let project = workspace.project().clone();
4439 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
4440 Some(cx.spawn(|workspace, mut cx| async move {
4441 let mut locations = references.await?;
4442 if locations.is_empty() {
4443 return Ok(());
4444 }
4445
4446 locations.sort_by_key(|location| location.buffer.id());
4447 let mut locations = locations.into_iter().peekable();
4448 let mut ranges_to_highlight = Vec::new();
4449
4450 let excerpt_buffer = cx.add_model(|cx| {
4451 let mut symbol_name = None;
4452 let mut multibuffer = MultiBuffer::new(replica_id);
4453 while let Some(location) = locations.next() {
4454 let buffer = location.buffer.read(cx);
4455 let mut ranges_for_buffer = Vec::new();
4456 let range = location.range.to_offset(buffer);
4457 ranges_for_buffer.push(range.clone());
4458 if symbol_name.is_none() {
4459 symbol_name = Some(buffer.text_for_range(range).collect::<String>());
4460 }
4461
4462 while let Some(next_location) = locations.peek() {
4463 if next_location.buffer == location.buffer {
4464 ranges_for_buffer.push(next_location.range.to_offset(buffer));
4465 locations.next();
4466 } else {
4467 break;
4468 }
4469 }
4470
4471 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
4472 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
4473 location.buffer.clone(),
4474 ranges_for_buffer,
4475 1,
4476 cx,
4477 ));
4478 }
4479 multibuffer.with_title(format!("References to `{}`", symbol_name.unwrap()))
4480 });
4481
4482 workspace.update(&mut cx, |workspace, cx| {
4483 let editor =
4484 cx.add_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), cx));
4485 editor.update(cx, |editor, cx| {
4486 let color = editor.style(cx).highlighted_line_background;
4487 editor.highlight_background::<Self>(ranges_to_highlight, color, cx);
4488 });
4489 workspace.add_item(Box::new(editor), cx);
4490 });
4491
4492 Ok(())
4493 }))
4494 }
4495
4496 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
4497 use language::ToOffset as _;
4498
4499 let project = self.project.clone()?;
4500 let selection = self.newest_anchor_selection().clone();
4501 let (cursor_buffer, cursor_buffer_position) = self
4502 .buffer
4503 .read(cx)
4504 .text_anchor_for_position(selection.head(), cx)?;
4505 let (tail_buffer, _) = self
4506 .buffer
4507 .read(cx)
4508 .text_anchor_for_position(selection.tail(), cx)?;
4509 if tail_buffer != cursor_buffer {
4510 return None;
4511 }
4512
4513 let snapshot = cursor_buffer.read(cx).snapshot();
4514 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
4515 let prepare_rename = project.update(cx, |project, cx| {
4516 project.prepare_rename(cursor_buffer, cursor_buffer_offset, cx)
4517 });
4518
4519 Some(cx.spawn(|this, mut cx| async move {
4520 if let Some(rename_range) = prepare_rename.await? {
4521 let rename_buffer_range = rename_range.to_offset(&snapshot);
4522 let cursor_offset_in_rename_range =
4523 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
4524
4525 this.update(&mut cx, |this, cx| {
4526 this.take_rename(false, cx);
4527 let style = this.style(cx);
4528 let buffer = this.buffer.read(cx).read(cx);
4529 let cursor_offset = selection.head().to_offset(&buffer);
4530 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
4531 let rename_end = rename_start + rename_buffer_range.len();
4532 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
4533 let mut old_highlight_id = None;
4534 let old_name = buffer
4535 .chunks(rename_start..rename_end, true)
4536 .map(|chunk| {
4537 if old_highlight_id.is_none() {
4538 old_highlight_id = chunk.syntax_highlight_id;
4539 }
4540 chunk.text
4541 })
4542 .collect();
4543
4544 drop(buffer);
4545
4546 // Position the selection in the rename editor so that it matches the current selection.
4547 this.show_local_selections = false;
4548 let rename_editor = cx.add_view(|cx| {
4549 let mut editor = Editor::single_line(None, cx);
4550 if let Some(old_highlight_id) = old_highlight_id {
4551 editor.override_text_style =
4552 Some(Box::new(move |style| old_highlight_id.style(&style.syntax)));
4553 }
4554 editor
4555 .buffer
4556 .update(cx, |buffer, cx| buffer.edit([0..0], &old_name, cx));
4557 editor.select_all(&SelectAll, cx);
4558 editor
4559 });
4560
4561 let ranges = this
4562 .clear_background_highlights::<DocumentHighlightWrite>(cx)
4563 .into_iter()
4564 .flat_map(|(_, ranges)| ranges)
4565 .chain(
4566 this.clear_background_highlights::<DocumentHighlightRead>(cx)
4567 .into_iter()
4568 .flat_map(|(_, ranges)| ranges),
4569 )
4570 .collect();
4571
4572 this.highlight_text::<Rename>(
4573 ranges,
4574 HighlightStyle {
4575 fade_out: Some(style.rename_fade),
4576 ..Default::default()
4577 },
4578 cx,
4579 );
4580 cx.focus(&rename_editor);
4581 let block_id = this.insert_blocks(
4582 [BlockProperties {
4583 position: range.start.clone(),
4584 height: 1,
4585 render: Arc::new({
4586 let editor = rename_editor.clone();
4587 move |cx: &BlockContext| {
4588 ChildView::new(editor.clone())
4589 .contained()
4590 .with_padding_left(cx.anchor_x)
4591 .boxed()
4592 }
4593 }),
4594 disposition: BlockDisposition::Below,
4595 }],
4596 cx,
4597 )[0];
4598 this.pending_rename = Some(RenameState {
4599 range,
4600 old_name,
4601 editor: rename_editor,
4602 block_id,
4603 });
4604 });
4605 }
4606
4607 Ok(())
4608 }))
4609 }
4610
4611 pub fn confirm_rename(
4612 workspace: &mut Workspace,
4613 _: &ConfirmRename,
4614 cx: &mut ViewContext<Workspace>,
4615 ) -> Option<Task<Result<()>>> {
4616 let editor = workspace.active_item(cx)?.act_as::<Editor>(cx)?;
4617
4618 let (buffer, range, old_name, new_name) = editor.update(cx, |editor, cx| {
4619 let rename = editor.take_rename(false, cx)?;
4620 let buffer = editor.buffer.read(cx);
4621 let (start_buffer, start) =
4622 buffer.text_anchor_for_position(rename.range.start.clone(), cx)?;
4623 let (end_buffer, end) =
4624 buffer.text_anchor_for_position(rename.range.end.clone(), cx)?;
4625 if start_buffer == end_buffer {
4626 let new_name = rename.editor.read(cx).text(cx);
4627 Some((start_buffer, start..end, rename.old_name, new_name))
4628 } else {
4629 None
4630 }
4631 })?;
4632
4633 let rename = workspace.project().clone().update(cx, |project, cx| {
4634 project.perform_rename(
4635 buffer.clone(),
4636 range.start.clone(),
4637 new_name.clone(),
4638 true,
4639 cx,
4640 )
4641 });
4642
4643 Some(cx.spawn(|workspace, mut cx| async move {
4644 let project_transaction = rename.await?;
4645 Self::open_project_transaction(
4646 editor.clone(),
4647 workspace,
4648 project_transaction,
4649 format!("Rename: {} → {}", old_name, new_name),
4650 cx.clone(),
4651 )
4652 .await?;
4653
4654 editor.update(&mut cx, |editor, cx| {
4655 editor.refresh_document_highlights(cx);
4656 });
4657 Ok(())
4658 }))
4659 }
4660
4661 fn take_rename(
4662 &mut self,
4663 moving_cursor: bool,
4664 cx: &mut ViewContext<Self>,
4665 ) -> Option<RenameState> {
4666 let rename = self.pending_rename.take()?;
4667 self.remove_blocks([rename.block_id].into_iter().collect(), cx);
4668 self.clear_text_highlights::<Rename>(cx);
4669 self.show_local_selections = true;
4670
4671 if moving_cursor {
4672 let cursor_in_rename_editor =
4673 rename.editor.read(cx).newest_selection::<usize>(cx).head();
4674
4675 // Update the selection to match the position of the selection inside
4676 // the rename editor.
4677 let snapshot = self.buffer.read(cx).read(cx);
4678 let rename_range = rename.range.to_offset(&snapshot);
4679 let cursor_in_editor = snapshot
4680 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
4681 .min(rename_range.end);
4682 drop(snapshot);
4683
4684 self.update_selections(
4685 vec![Selection {
4686 id: self.newest_anchor_selection().id,
4687 start: cursor_in_editor,
4688 end: cursor_in_editor,
4689 reversed: false,
4690 goal: SelectionGoal::None,
4691 }],
4692 None,
4693 cx,
4694 );
4695 }
4696
4697 Some(rename)
4698 }
4699
4700 fn invalidate_rename_range(
4701 &mut self,
4702 buffer: &MultiBufferSnapshot,
4703 cx: &mut ViewContext<Self>,
4704 ) {
4705 if let Some(rename) = self.pending_rename.as_ref() {
4706 if self.selections.len() == 1 {
4707 let head = self.selections[0].head().to_offset(buffer);
4708 let range = rename.range.to_offset(buffer).to_inclusive();
4709 if range.contains(&head) {
4710 return;
4711 }
4712 }
4713 let rename = self.pending_rename.take().unwrap();
4714 self.remove_blocks([rename.block_id].into_iter().collect(), cx);
4715 self.clear_background_highlights::<Rename>(cx);
4716 }
4717 }
4718
4719 #[cfg(any(test, feature = "test-support"))]
4720 pub fn pending_rename(&self) -> Option<&RenameState> {
4721 self.pending_rename.as_ref()
4722 }
4723
4724 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
4725 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
4726 let buffer = self.buffer.read(cx).snapshot(cx);
4727 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
4728 let is_valid = buffer
4729 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
4730 .any(|entry| {
4731 entry.diagnostic.is_primary
4732 && !entry.range.is_empty()
4733 && entry.range.start == primary_range_start
4734 && entry.diagnostic.message == active_diagnostics.primary_message
4735 });
4736
4737 if is_valid != active_diagnostics.is_valid {
4738 active_diagnostics.is_valid = is_valid;
4739 let mut new_styles = HashMap::default();
4740 for (block_id, diagnostic) in &active_diagnostics.blocks {
4741 new_styles.insert(
4742 *block_id,
4743 diagnostic_block_renderer(diagnostic.clone(), is_valid),
4744 );
4745 }
4746 self.display_map
4747 .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
4748 }
4749 }
4750 }
4751
4752 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
4753 self.dismiss_diagnostics(cx);
4754 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
4755 let buffer = self.buffer.read(cx).snapshot(cx);
4756
4757 let mut primary_range = None;
4758 let mut primary_message = None;
4759 let mut group_end = Point::zero();
4760 let diagnostic_group = buffer
4761 .diagnostic_group::<Point>(group_id)
4762 .map(|entry| {
4763 if entry.range.end > group_end {
4764 group_end = entry.range.end;
4765 }
4766 if entry.diagnostic.is_primary {
4767 primary_range = Some(entry.range.clone());
4768 primary_message = Some(entry.diagnostic.message.clone());
4769 }
4770 entry
4771 })
4772 .collect::<Vec<_>>();
4773 let primary_range = primary_range.unwrap();
4774 let primary_message = primary_message.unwrap();
4775 let primary_range =
4776 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
4777
4778 let blocks = display_map
4779 .insert_blocks(
4780 diagnostic_group.iter().map(|entry| {
4781 let diagnostic = entry.diagnostic.clone();
4782 let message_height = diagnostic.message.lines().count() as u8;
4783 BlockProperties {
4784 position: buffer.anchor_after(entry.range.start),
4785 height: message_height,
4786 render: diagnostic_block_renderer(diagnostic, true),
4787 disposition: BlockDisposition::Below,
4788 }
4789 }),
4790 cx,
4791 )
4792 .into_iter()
4793 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
4794 .collect();
4795
4796 Some(ActiveDiagnosticGroup {
4797 primary_range,
4798 primary_message,
4799 blocks,
4800 is_valid: true,
4801 })
4802 });
4803 }
4804
4805 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
4806 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
4807 self.display_map.update(cx, |display_map, cx| {
4808 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
4809 });
4810 cx.notify();
4811 }
4812 }
4813
4814 fn build_columnar_selection(
4815 &mut self,
4816 display_map: &DisplaySnapshot,
4817 row: u32,
4818 columns: &Range<u32>,
4819 reversed: bool,
4820 ) -> Option<Selection<Point>> {
4821 let is_empty = columns.start == columns.end;
4822 let line_len = display_map.line_len(row);
4823 if columns.start < line_len || (is_empty && columns.start == line_len) {
4824 let start = DisplayPoint::new(row, columns.start);
4825 let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
4826 Some(Selection {
4827 id: post_inc(&mut self.next_selection_id),
4828 start: start.to_point(display_map),
4829 end: end.to_point(display_map),
4830 reversed,
4831 goal: SelectionGoal::ColumnRange {
4832 start: columns.start,
4833 end: columns.end,
4834 },
4835 })
4836 } else {
4837 None
4838 }
4839 }
4840
4841 pub fn local_selections_in_range(
4842 &self,
4843 range: Range<Anchor>,
4844 display_map: &DisplaySnapshot,
4845 ) -> Vec<Selection<Point>> {
4846 let buffer = &display_map.buffer_snapshot;
4847
4848 let start_ix = match self
4849 .selections
4850 .binary_search_by(|probe| probe.end.cmp(&range.start, &buffer))
4851 {
4852 Ok(ix) | Err(ix) => ix,
4853 };
4854 let end_ix = match self
4855 .selections
4856 .binary_search_by(|probe| probe.start.cmp(&range.end, &buffer))
4857 {
4858 Ok(ix) => ix + 1,
4859 Err(ix) => ix,
4860 };
4861
4862 fn point_selection(
4863 selection: &Selection<Anchor>,
4864 buffer: &MultiBufferSnapshot,
4865 ) -> Selection<Point> {
4866 let start = selection.start.to_point(&buffer);
4867 let end = selection.end.to_point(&buffer);
4868 Selection {
4869 id: selection.id,
4870 start,
4871 end,
4872 reversed: selection.reversed,
4873 goal: selection.goal,
4874 }
4875 }
4876
4877 self.selections[start_ix..end_ix]
4878 .iter()
4879 .chain(
4880 self.pending_selection
4881 .as_ref()
4882 .map(|pending| &pending.selection),
4883 )
4884 .map(|s| point_selection(s, &buffer))
4885 .collect()
4886 }
4887
4888 pub fn local_selections<'a, D>(&self, cx: &'a AppContext) -> Vec<Selection<D>>
4889 where
4890 D: 'a + TextDimension + Ord + Sub<D, Output = D>,
4891 {
4892 let buffer = self.buffer.read(cx).snapshot(cx);
4893 let mut selections = self
4894 .resolve_selections::<D, _>(self.selections.iter(), &buffer)
4895 .peekable();
4896
4897 let mut pending_selection = self.pending_selection::<D>(&buffer);
4898
4899 iter::from_fn(move || {
4900 if let Some(pending) = pending_selection.as_mut() {
4901 while let Some(next_selection) = selections.peek() {
4902 if pending.start <= next_selection.end && pending.end >= next_selection.start {
4903 let next_selection = selections.next().unwrap();
4904 if next_selection.start < pending.start {
4905 pending.start = next_selection.start;
4906 }
4907 if next_selection.end > pending.end {
4908 pending.end = next_selection.end;
4909 }
4910 } else if next_selection.end < pending.start {
4911 return selections.next();
4912 } else {
4913 break;
4914 }
4915 }
4916
4917 pending_selection.take()
4918 } else {
4919 selections.next()
4920 }
4921 })
4922 .collect()
4923 }
4924
4925 fn resolve_selections<'a, D, I>(
4926 &self,
4927 selections: I,
4928 snapshot: &MultiBufferSnapshot,
4929 ) -> impl 'a + Iterator<Item = Selection<D>>
4930 where
4931 D: TextDimension + Ord + Sub<D, Output = D>,
4932 I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
4933 {
4934 let (to_summarize, selections) = selections.into_iter().tee();
4935 let mut summaries = snapshot
4936 .summaries_for_anchors::<D, _>(to_summarize.flat_map(|s| [&s.start, &s.end]))
4937 .into_iter();
4938 selections.map(move |s| Selection {
4939 id: s.id,
4940 start: summaries.next().unwrap(),
4941 end: summaries.next().unwrap(),
4942 reversed: s.reversed,
4943 goal: s.goal,
4944 })
4945 }
4946
4947 fn pending_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4948 &self,
4949 snapshot: &MultiBufferSnapshot,
4950 ) -> Option<Selection<D>> {
4951 self.pending_selection
4952 .as_ref()
4953 .map(|pending| self.resolve_selection(&pending.selection, &snapshot))
4954 }
4955
4956 fn resolve_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4957 &self,
4958 selection: &Selection<Anchor>,
4959 buffer: &MultiBufferSnapshot,
4960 ) -> Selection<D> {
4961 Selection {
4962 id: selection.id,
4963 start: selection.start.summary::<D>(&buffer),
4964 end: selection.end.summary::<D>(&buffer),
4965 reversed: selection.reversed,
4966 goal: selection.goal,
4967 }
4968 }
4969
4970 fn selection_count<'a>(&self) -> usize {
4971 let mut count = self.selections.len();
4972 if self.pending_selection.is_some() {
4973 count += 1;
4974 }
4975 count
4976 }
4977
4978 pub fn oldest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4979 &self,
4980 cx: &AppContext,
4981 ) -> Selection<D> {
4982 let snapshot = self.buffer.read(cx).read(cx);
4983 self.selections
4984 .iter()
4985 .min_by_key(|s| s.id)
4986 .map(|selection| self.resolve_selection(selection, &snapshot))
4987 .or_else(|| self.pending_selection(&snapshot))
4988 .unwrap()
4989 }
4990
4991 pub fn newest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4992 &self,
4993 cx: &AppContext,
4994 ) -> Selection<D> {
4995 self.resolve_selection(
4996 self.newest_anchor_selection(),
4997 &self.buffer.read(cx).read(cx),
4998 )
4999 }
5000
5001 pub fn newest_selection_with_snapshot<D: TextDimension + Ord + Sub<D, Output = D>>(
5002 &self,
5003 snapshot: &MultiBufferSnapshot,
5004 ) -> Selection<D> {
5005 self.resolve_selection(self.newest_anchor_selection(), snapshot)
5006 }
5007
5008 pub fn newest_anchor_selection(&self) -> &Selection<Anchor> {
5009 self.pending_selection
5010 .as_ref()
5011 .map(|s| &s.selection)
5012 .or_else(|| self.selections.iter().max_by_key(|s| s.id))
5013 .unwrap()
5014 }
5015
5016 pub fn update_selections<T>(
5017 &mut self,
5018 mut selections: Vec<Selection<T>>,
5019 autoscroll: Option<Autoscroll>,
5020 cx: &mut ViewContext<Self>,
5021 ) where
5022 T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
5023 {
5024 let buffer = self.buffer.read(cx).snapshot(cx);
5025 selections.sort_unstable_by_key(|s| s.start);
5026
5027 // Merge overlapping selections.
5028 let mut i = 1;
5029 while i < selections.len() {
5030 if selections[i - 1].end >= selections[i].start {
5031 let removed = selections.remove(i);
5032 if removed.start < selections[i - 1].start {
5033 selections[i - 1].start = removed.start;
5034 }
5035 if removed.end > selections[i - 1].end {
5036 selections[i - 1].end = removed.end;
5037 }
5038 } else {
5039 i += 1;
5040 }
5041 }
5042
5043 if let Some(autoscroll) = autoscroll {
5044 self.request_autoscroll(autoscroll, cx);
5045 }
5046
5047 self.set_selections(
5048 Arc::from_iter(selections.into_iter().map(|selection| {
5049 let end_bias = if selection.end > selection.start {
5050 Bias::Left
5051 } else {
5052 Bias::Right
5053 };
5054 Selection {
5055 id: selection.id,
5056 start: buffer.anchor_after(selection.start),
5057 end: buffer.anchor_at(selection.end, end_bias),
5058 reversed: selection.reversed,
5059 goal: selection.goal,
5060 }
5061 })),
5062 None,
5063 true,
5064 cx,
5065 );
5066 }
5067
5068 pub fn set_selections_from_remote(
5069 &mut self,
5070 mut selections: Vec<Selection<Anchor>>,
5071 cx: &mut ViewContext<Self>,
5072 ) {
5073 let buffer = self.buffer.read(cx);
5074 let buffer = buffer.read(cx);
5075 selections.sort_by(|a, b| {
5076 a.start
5077 .cmp(&b.start, &*buffer)
5078 .then_with(|| b.end.cmp(&a.end, &*buffer))
5079 });
5080
5081 // Merge overlapping selections
5082 let mut i = 1;
5083 while i < selections.len() {
5084 if selections[i - 1]
5085 .end
5086 .cmp(&selections[i].start, &*buffer)
5087 .is_ge()
5088 {
5089 let removed = selections.remove(i);
5090 if removed
5091 .start
5092 .cmp(&selections[i - 1].start, &*buffer)
5093 .is_lt()
5094 {
5095 selections[i - 1].start = removed.start;
5096 }
5097 if removed.end.cmp(&selections[i - 1].end, &*buffer).is_gt() {
5098 selections[i - 1].end = removed.end;
5099 }
5100 } else {
5101 i += 1;
5102 }
5103 }
5104
5105 drop(buffer);
5106 self.set_selections(selections.into(), None, false, cx);
5107 }
5108
5109 /// Compute new ranges for any selections that were located in excerpts that have
5110 /// since been removed.
5111 ///
5112 /// Returns a `HashMap` indicating which selections whose former head position
5113 /// was no longer present. The keys of the map are selection ids. The values are
5114 /// the id of the new excerpt where the head of the selection has been moved.
5115 pub fn refresh_selections(&mut self, cx: &mut ViewContext<Self>) -> HashMap<usize, ExcerptId> {
5116 let snapshot = self.buffer.read(cx).read(cx);
5117 let mut selections_with_lost_position = HashMap::default();
5118
5119 let mut pending_selection = self.pending_selection.take();
5120 if let Some(pending) = pending_selection.as_mut() {
5121 let anchors =
5122 snapshot.refresh_anchors([&pending.selection.start, &pending.selection.end]);
5123 let (_, start, kept_start) = anchors[0].clone();
5124 let (_, end, kept_end) = anchors[1].clone();
5125 let kept_head = if pending.selection.reversed {
5126 kept_start
5127 } else {
5128 kept_end
5129 };
5130 if !kept_head {
5131 selections_with_lost_position.insert(
5132 pending.selection.id,
5133 pending.selection.head().excerpt_id.clone(),
5134 );
5135 }
5136
5137 pending.selection.start = start;
5138 pending.selection.end = end;
5139 }
5140
5141 let anchors_with_status = snapshot.refresh_anchors(
5142 self.selections
5143 .iter()
5144 .flat_map(|selection| [&selection.start, &selection.end]),
5145 );
5146 self.selections = anchors_with_status
5147 .chunks(2)
5148 .map(|selection_anchors| {
5149 let (anchor_ix, start, kept_start) = selection_anchors[0].clone();
5150 let (_, end, kept_end) = selection_anchors[1].clone();
5151 let selection = &self.selections[anchor_ix / 2];
5152 let kept_head = if selection.reversed {
5153 kept_start
5154 } else {
5155 kept_end
5156 };
5157 if !kept_head {
5158 selections_with_lost_position
5159 .insert(selection.id, selection.head().excerpt_id.clone());
5160 }
5161
5162 Selection {
5163 id: selection.id,
5164 start,
5165 end,
5166 reversed: selection.reversed,
5167 goal: selection.goal,
5168 }
5169 })
5170 .collect();
5171 drop(snapshot);
5172
5173 let new_selections = self.local_selections::<usize>(cx);
5174 if !new_selections.is_empty() {
5175 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
5176 }
5177 self.pending_selection = pending_selection;
5178
5179 selections_with_lost_position
5180 }
5181
5182 fn set_selections(
5183 &mut self,
5184 selections: Arc<[Selection<Anchor>]>,
5185 pending_selection: Option<PendingSelection>,
5186 local: bool,
5187 cx: &mut ViewContext<Self>,
5188 ) {
5189 assert!(
5190 !selections.is_empty() || pending_selection.is_some(),
5191 "must have at least one selection"
5192 );
5193
5194 let old_cursor_position = self.newest_anchor_selection().head();
5195
5196 self.selections = selections;
5197 self.pending_selection = pending_selection;
5198 if self.focused && self.leader_replica_id.is_none() {
5199 self.buffer.update(cx, |buffer, cx| {
5200 buffer.set_active_selections(&self.selections, cx)
5201 });
5202 }
5203
5204 let display_map = self
5205 .display_map
5206 .update(cx, |display_map, cx| display_map.snapshot(cx));
5207 let buffer = &display_map.buffer_snapshot;
5208 self.add_selections_state = None;
5209 self.select_next_state = None;
5210 self.select_larger_syntax_node_stack.clear();
5211 self.autoclose_stack.invalidate(&self.selections, &buffer);
5212 self.snippet_stack.invalidate(&self.selections, &buffer);
5213 self.invalidate_rename_range(&buffer, cx);
5214
5215 let new_cursor_position = self.newest_anchor_selection().head();
5216
5217 self.push_to_nav_history(
5218 old_cursor_position.clone(),
5219 Some(new_cursor_position.to_point(&buffer)),
5220 cx,
5221 );
5222
5223 if local {
5224 let completion_menu = match self.context_menu.as_mut() {
5225 Some(ContextMenu::Completions(menu)) => Some(menu),
5226 _ => {
5227 self.context_menu.take();
5228 None
5229 }
5230 };
5231
5232 if let Some(completion_menu) = completion_menu {
5233 let cursor_position = new_cursor_position.to_offset(&buffer);
5234 let (word_range, kind) =
5235 buffer.surrounding_word(completion_menu.initial_position.clone());
5236 if kind == Some(CharKind::Word)
5237 && word_range.to_inclusive().contains(&cursor_position)
5238 {
5239 let query = Self::completion_query(&buffer, cursor_position);
5240 cx.background()
5241 .block(completion_menu.filter(query.as_deref(), cx.background().clone()));
5242 self.show_completions(&ShowCompletions, cx);
5243 } else {
5244 self.hide_context_menu(cx);
5245 }
5246 }
5247
5248 if old_cursor_position.to_display_point(&display_map).row()
5249 != new_cursor_position.to_display_point(&display_map).row()
5250 {
5251 self.available_code_actions.take();
5252 }
5253 self.refresh_code_actions(cx);
5254 self.refresh_document_highlights(cx);
5255 }
5256
5257 self.pause_cursor_blinking(cx);
5258 cx.emit(Event::SelectionsChanged { local });
5259 }
5260
5261 pub fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
5262 self.autoscroll_request = Some((autoscroll, true));
5263 cx.notify();
5264 }
5265
5266 fn request_autoscroll_remotely(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
5267 self.autoscroll_request = Some((autoscroll, false));
5268 cx.notify();
5269 }
5270
5271 pub fn transact(
5272 &mut self,
5273 cx: &mut ViewContext<Self>,
5274 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
5275 ) {
5276 self.start_transaction_at(Instant::now(), cx);
5277 update(self, cx);
5278 self.end_transaction_at(Instant::now(), cx);
5279 }
5280
5281 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
5282 self.end_selection(cx);
5283 if let Some(tx_id) = self
5284 .buffer
5285 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
5286 {
5287 self.selection_history
5288 .insert(tx_id, (self.selections.clone(), None));
5289 }
5290 }
5291
5292 fn end_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
5293 if let Some(tx_id) = self
5294 .buffer
5295 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
5296 {
5297 if let Some((_, end_selections)) = self.selection_history.get_mut(&tx_id) {
5298 *end_selections = Some(self.selections.clone());
5299 } else {
5300 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
5301 }
5302
5303 cx.emit(Event::Edited);
5304 }
5305 }
5306
5307 pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
5308 log::info!("Editor::page_up");
5309 }
5310
5311 pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
5312 log::info!("Editor::page_down");
5313 }
5314
5315 pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
5316 let mut fold_ranges = Vec::new();
5317
5318 let selections = self.local_selections::<Point>(cx);
5319 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5320 for selection in selections {
5321 let range = selection.display_range(&display_map).sorted();
5322 let buffer_start_row = range.start.to_point(&display_map).row;
5323
5324 for row in (0..=range.end.row()).rev() {
5325 if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
5326 let fold_range = self.foldable_range_for_line(&display_map, row);
5327 if fold_range.end.row >= buffer_start_row {
5328 fold_ranges.push(fold_range);
5329 if row <= range.start.row() {
5330 break;
5331 }
5332 }
5333 }
5334 }
5335 }
5336
5337 self.fold_ranges(fold_ranges, cx);
5338 }
5339
5340 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
5341 let selections = self.local_selections::<Point>(cx);
5342 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5343 let buffer = &display_map.buffer_snapshot;
5344 let ranges = selections
5345 .iter()
5346 .map(|s| {
5347 let range = s.display_range(&display_map).sorted();
5348 let mut start = range.start.to_point(&display_map);
5349 let mut end = range.end.to_point(&display_map);
5350 start.column = 0;
5351 end.column = buffer.line_len(end.row);
5352 start..end
5353 })
5354 .collect::<Vec<_>>();
5355 self.unfold_ranges(ranges, true, cx);
5356 }
5357
5358 fn is_line_foldable(&self, display_map: &DisplaySnapshot, display_row: u32) -> bool {
5359 let max_point = display_map.max_point();
5360 if display_row >= max_point.row() {
5361 false
5362 } else {
5363 let (start_indent, is_blank) = display_map.line_indent(display_row);
5364 if is_blank {
5365 false
5366 } else {
5367 for display_row in display_row + 1..=max_point.row() {
5368 let (indent, is_blank) = display_map.line_indent(display_row);
5369 if !is_blank {
5370 return indent > start_indent;
5371 }
5372 }
5373 false
5374 }
5375 }
5376 }
5377
5378 fn foldable_range_for_line(
5379 &self,
5380 display_map: &DisplaySnapshot,
5381 start_row: u32,
5382 ) -> Range<Point> {
5383 let max_point = display_map.max_point();
5384
5385 let (start_indent, _) = display_map.line_indent(start_row);
5386 let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
5387 let mut end = None;
5388 for row in start_row + 1..=max_point.row() {
5389 let (indent, is_blank) = display_map.line_indent(row);
5390 if !is_blank && indent <= start_indent {
5391 end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
5392 break;
5393 }
5394 }
5395
5396 let end = end.unwrap_or(max_point);
5397 return start.to_point(display_map)..end.to_point(display_map);
5398 }
5399
5400 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
5401 let selections = self.local_selections::<Point>(cx);
5402 let ranges = selections.into_iter().map(|s| s.start..s.end);
5403 self.fold_ranges(ranges, cx);
5404 }
5405
5406 pub fn fold_ranges<T: ToOffset>(
5407 &mut self,
5408 ranges: impl IntoIterator<Item = Range<T>>,
5409 cx: &mut ViewContext<Self>,
5410 ) {
5411 let mut ranges = ranges.into_iter().peekable();
5412 if ranges.peek().is_some() {
5413 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
5414 self.request_autoscroll(Autoscroll::Fit, cx);
5415 cx.notify();
5416 }
5417 }
5418
5419 pub fn unfold_ranges<T: ToOffset>(
5420 &mut self,
5421 ranges: impl IntoIterator<Item = Range<T>>,
5422 inclusive: bool,
5423 cx: &mut ViewContext<Self>,
5424 ) {
5425 let mut ranges = ranges.into_iter().peekable();
5426 if ranges.peek().is_some() {
5427 self.display_map
5428 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
5429 self.request_autoscroll(Autoscroll::Fit, cx);
5430 cx.notify();
5431 }
5432 }
5433
5434 pub fn insert_blocks(
5435 &mut self,
5436 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
5437 cx: &mut ViewContext<Self>,
5438 ) -> Vec<BlockId> {
5439 let blocks = self
5440 .display_map
5441 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
5442 self.request_autoscroll(Autoscroll::Fit, cx);
5443 blocks
5444 }
5445
5446 pub fn replace_blocks(
5447 &mut self,
5448 blocks: HashMap<BlockId, RenderBlock>,
5449 cx: &mut ViewContext<Self>,
5450 ) {
5451 self.display_map
5452 .update(cx, |display_map, _| display_map.replace_blocks(blocks));
5453 self.request_autoscroll(Autoscroll::Fit, cx);
5454 }
5455
5456 pub fn remove_blocks(&mut self, block_ids: HashSet<BlockId>, cx: &mut ViewContext<Self>) {
5457 self.display_map.update(cx, |display_map, cx| {
5458 display_map.remove_blocks(block_ids, cx)
5459 });
5460 }
5461
5462 pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
5463 self.display_map
5464 .update(cx, |map, cx| map.snapshot(cx))
5465 .longest_row()
5466 }
5467
5468 pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
5469 self.display_map
5470 .update(cx, |map, cx| map.snapshot(cx))
5471 .max_point()
5472 }
5473
5474 pub fn text(&self, cx: &AppContext) -> String {
5475 self.buffer.read(cx).read(cx).text()
5476 }
5477
5478 pub fn set_text(&mut self, text: impl Into<String>, cx: &mut ViewContext<Self>) {
5479 self.transact(cx, |this, cx| {
5480 this.buffer
5481 .read(cx)
5482 .as_singleton()
5483 .expect("you can only call set_text on editors for singleton buffers")
5484 .update(cx, |buffer, cx| buffer.set_text(text, cx));
5485 });
5486 }
5487
5488 pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
5489 self.display_map
5490 .update(cx, |map, cx| map.snapshot(cx))
5491 .text()
5492 }
5493
5494 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
5495 let language = self.language(cx);
5496 let settings = cx.global::<Settings>();
5497 let mode = self
5498 .soft_wrap_mode_override
5499 .unwrap_or_else(|| settings.soft_wrap(language));
5500 match mode {
5501 settings::SoftWrap::None => SoftWrap::None,
5502 settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
5503 settings::SoftWrap::PreferredLineLength => {
5504 SoftWrap::Column(settings.preferred_line_length(language))
5505 }
5506 }
5507 }
5508
5509 pub fn set_soft_wrap_mode(&mut self, mode: settings::SoftWrap, cx: &mut ViewContext<Self>) {
5510 self.soft_wrap_mode_override = Some(mode);
5511 cx.notify();
5512 }
5513
5514 pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut MutableAppContext) -> bool {
5515 self.display_map
5516 .update(cx, |map, cx| map.set_wrap_width(width, cx))
5517 }
5518
5519 pub fn highlight_rows(&mut self, rows: Option<Range<u32>>) {
5520 self.highlighted_rows = rows;
5521 }
5522
5523 pub fn highlighted_rows(&self) -> Option<Range<u32>> {
5524 self.highlighted_rows.clone()
5525 }
5526
5527 pub fn highlight_background<T: 'static>(
5528 &mut self,
5529 ranges: Vec<Range<Anchor>>,
5530 color: Color,
5531 cx: &mut ViewContext<Self>,
5532 ) {
5533 self.background_highlights
5534 .insert(TypeId::of::<T>(), (color, ranges));
5535 cx.notify();
5536 }
5537
5538 pub fn clear_background_highlights<T: 'static>(
5539 &mut self,
5540 cx: &mut ViewContext<Self>,
5541 ) -> Option<(Color, Vec<Range<Anchor>>)> {
5542 cx.notify();
5543 self.background_highlights.remove(&TypeId::of::<T>())
5544 }
5545
5546 #[cfg(feature = "test-support")]
5547 pub fn all_background_highlights(
5548 &mut self,
5549 cx: &mut ViewContext<Self>,
5550 ) -> Vec<(Range<DisplayPoint>, Color)> {
5551 let snapshot = self.snapshot(cx);
5552 let buffer = &snapshot.buffer_snapshot;
5553 let start = buffer.anchor_before(0);
5554 let end = buffer.anchor_after(buffer.len());
5555 self.background_highlights_in_range(start..end, &snapshot)
5556 }
5557
5558 pub fn background_highlights_for_type<T: 'static>(&self) -> Option<(Color, &[Range<Anchor>])> {
5559 self.background_highlights
5560 .get(&TypeId::of::<T>())
5561 .map(|(color, ranges)| (*color, ranges.as_slice()))
5562 }
5563
5564 pub fn background_highlights_in_range(
5565 &self,
5566 search_range: Range<Anchor>,
5567 display_snapshot: &DisplaySnapshot,
5568 ) -> Vec<(Range<DisplayPoint>, Color)> {
5569 let mut results = Vec::new();
5570 let buffer = &display_snapshot.buffer_snapshot;
5571 for (color, ranges) in self.background_highlights.values() {
5572 let start_ix = match ranges.binary_search_by(|probe| {
5573 let cmp = probe.end.cmp(&search_range.start, &buffer);
5574 if cmp.is_gt() {
5575 Ordering::Greater
5576 } else {
5577 Ordering::Less
5578 }
5579 }) {
5580 Ok(i) | Err(i) => i,
5581 };
5582 for range in &ranges[start_ix..] {
5583 if range.start.cmp(&search_range.end, &buffer).is_ge() {
5584 break;
5585 }
5586 let start = range
5587 .start
5588 .to_point(buffer)
5589 .to_display_point(display_snapshot);
5590 let end = range
5591 .end
5592 .to_point(buffer)
5593 .to_display_point(display_snapshot);
5594 results.push((start..end, *color))
5595 }
5596 }
5597 results
5598 }
5599
5600 pub fn highlight_text<T: 'static>(
5601 &mut self,
5602 ranges: Vec<Range<Anchor>>,
5603 style: HighlightStyle,
5604 cx: &mut ViewContext<Self>,
5605 ) {
5606 self.display_map.update(cx, |map, _| {
5607 map.highlight_text(TypeId::of::<T>(), ranges, style)
5608 });
5609 cx.notify();
5610 }
5611
5612 pub fn clear_text_highlights<T: 'static>(
5613 &mut self,
5614 cx: &mut ViewContext<Self>,
5615 ) -> Option<Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
5616 cx.notify();
5617 self.display_map
5618 .update(cx, |map, _| map.clear_text_highlights(TypeId::of::<T>()))
5619 }
5620
5621 fn next_blink_epoch(&mut self) -> usize {
5622 self.blink_epoch += 1;
5623 self.blink_epoch
5624 }
5625
5626 fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
5627 if !self.focused {
5628 return;
5629 }
5630
5631 self.show_local_cursors = true;
5632 cx.notify();
5633
5634 let epoch = self.next_blink_epoch();
5635 cx.spawn(|this, mut cx| {
5636 let this = this.downgrade();
5637 async move {
5638 Timer::after(CURSOR_BLINK_INTERVAL).await;
5639 if let Some(this) = this.upgrade(&cx) {
5640 this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
5641 }
5642 }
5643 })
5644 .detach();
5645 }
5646
5647 fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
5648 if epoch == self.blink_epoch {
5649 self.blinking_paused = false;
5650 self.blink_cursors(epoch, cx);
5651 }
5652 }
5653
5654 fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
5655 if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
5656 self.show_local_cursors = !self.show_local_cursors;
5657 cx.notify();
5658
5659 let epoch = self.next_blink_epoch();
5660 cx.spawn(|this, mut cx| {
5661 let this = this.downgrade();
5662 async move {
5663 Timer::after(CURSOR_BLINK_INTERVAL).await;
5664 if let Some(this) = this.upgrade(&cx) {
5665 this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
5666 }
5667 }
5668 })
5669 .detach();
5670 }
5671 }
5672
5673 pub fn show_local_cursors(&self) -> bool {
5674 self.show_local_cursors && self.focused
5675 }
5676
5677 fn on_buffer_changed(&mut self, _: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Self>) {
5678 cx.notify();
5679 }
5680
5681 fn on_buffer_event(
5682 &mut self,
5683 _: ModelHandle<MultiBuffer>,
5684 event: &language::Event,
5685 cx: &mut ViewContext<Self>,
5686 ) {
5687 match event {
5688 language::Event::Edited => {
5689 self.refresh_active_diagnostics(cx);
5690 self.refresh_code_actions(cx);
5691 cx.emit(Event::BufferEdited);
5692 }
5693 language::Event::Dirtied => cx.emit(Event::Dirtied),
5694 language::Event::Saved => cx.emit(Event::Saved),
5695 language::Event::FileHandleChanged => cx.emit(Event::TitleChanged),
5696 language::Event::Reloaded => cx.emit(Event::TitleChanged),
5697 language::Event::Closed => cx.emit(Event::Closed),
5698 language::Event::DiagnosticsUpdated => {
5699 self.refresh_active_diagnostics(cx);
5700 }
5701 _ => {}
5702 }
5703 }
5704
5705 fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
5706 cx.notify();
5707 }
5708
5709 pub fn set_searchable(&mut self, searchable: bool) {
5710 self.searchable = searchable;
5711 }
5712
5713 pub fn searchable(&self) -> bool {
5714 self.searchable
5715 }
5716
5717 fn open_excerpts(workspace: &mut Workspace, _: &OpenExcerpts, cx: &mut ViewContext<Workspace>) {
5718 let active_item = workspace.active_item(cx);
5719 let editor_handle = if let Some(editor) = active_item
5720 .as_ref()
5721 .and_then(|item| item.act_as::<Self>(cx))
5722 {
5723 editor
5724 } else {
5725 cx.propagate_action();
5726 return;
5727 };
5728
5729 let editor = editor_handle.read(cx);
5730 let buffer = editor.buffer.read(cx);
5731 if buffer.is_singleton() {
5732 cx.propagate_action();
5733 return;
5734 }
5735
5736 let mut new_selections_by_buffer = HashMap::default();
5737 for selection in editor.local_selections::<usize>(cx) {
5738 for (buffer, mut range) in
5739 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
5740 {
5741 if selection.reversed {
5742 mem::swap(&mut range.start, &mut range.end);
5743 }
5744 new_selections_by_buffer
5745 .entry(buffer)
5746 .or_insert(Vec::new())
5747 .push(range)
5748 }
5749 }
5750
5751 editor_handle.update(cx, |editor, cx| {
5752 editor.push_to_nav_history(editor.newest_anchor_selection().head(), None, cx);
5753 });
5754 let nav_history = workspace.active_pane().read(cx).nav_history().clone();
5755 nav_history.borrow_mut().disable();
5756
5757 // We defer the pane interaction because we ourselves are a workspace item
5758 // and activating a new item causes the pane to call a method on us reentrantly,
5759 // which panics if we're on the stack.
5760 cx.defer(move |workspace, cx| {
5761 workspace.activate_next_pane(cx);
5762
5763 for (buffer, ranges) in new_selections_by_buffer.into_iter() {
5764 let editor = workspace.open_project_item::<Self>(buffer, cx);
5765 editor.update(cx, |editor, cx| {
5766 editor.select_ranges(ranges, Some(Autoscroll::Newest), cx);
5767 });
5768 }
5769
5770 nav_history.borrow_mut().enable();
5771 });
5772 }
5773}
5774
5775impl EditorSnapshot {
5776 pub fn is_focused(&self) -> bool {
5777 self.is_focused
5778 }
5779
5780 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
5781 self.placeholder_text.as_ref()
5782 }
5783
5784 pub fn scroll_position(&self) -> Vector2F {
5785 compute_scroll_position(
5786 &self.display_snapshot,
5787 self.scroll_position,
5788 &self.scroll_top_anchor,
5789 )
5790 }
5791}
5792
5793impl Deref for EditorSnapshot {
5794 type Target = DisplaySnapshot;
5795
5796 fn deref(&self) -> &Self::Target {
5797 &self.display_snapshot
5798 }
5799}
5800
5801fn compute_scroll_position(
5802 snapshot: &DisplaySnapshot,
5803 mut scroll_position: Vector2F,
5804 scroll_top_anchor: &Anchor,
5805) -> Vector2F {
5806 if *scroll_top_anchor != Anchor::min() {
5807 let scroll_top = scroll_top_anchor.to_display_point(snapshot).row() as f32;
5808 scroll_position.set_y(scroll_top + scroll_position.y());
5809 } else {
5810 scroll_position.set_y(0.);
5811 }
5812 scroll_position
5813}
5814
5815#[derive(Copy, Clone, Debug, PartialEq, Eq)]
5816pub enum Event {
5817 Activate,
5818 BufferEdited,
5819 Edited,
5820 Blurred,
5821 Dirtied,
5822 Saved,
5823 TitleChanged,
5824 SelectionsChanged { local: bool },
5825 ScrollPositionChanged { local: bool },
5826 Closed,
5827}
5828
5829pub struct EditorFocused(pub ViewHandle<Editor>);
5830pub struct EditorBlurred(pub ViewHandle<Editor>);
5831pub struct EditorReleased(pub WeakViewHandle<Editor>);
5832
5833impl Entity for Editor {
5834 type Event = Event;
5835
5836 fn release(&mut self, cx: &mut MutableAppContext) {
5837 cx.emit_global(EditorReleased(self.handle.clone()));
5838 }
5839}
5840
5841impl View for Editor {
5842 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
5843 let style = self.style(cx);
5844 self.display_map.update(cx, |map, cx| {
5845 map.set_font(style.text.font_id, style.text.font_size, cx)
5846 });
5847 EditorElement::new(self.handle.clone(), style.clone(), self.cursor_shape).boxed()
5848 }
5849
5850 fn ui_name() -> &'static str {
5851 "Editor"
5852 }
5853
5854 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
5855 let focused_event = EditorFocused(cx.handle());
5856 cx.emit_global(focused_event);
5857 if let Some(rename) = self.pending_rename.as_ref() {
5858 cx.focus(&rename.editor);
5859 } else {
5860 self.focused = true;
5861 self.blink_cursors(self.blink_epoch, cx);
5862 self.buffer.update(cx, |buffer, cx| {
5863 buffer.finalize_last_transaction(cx);
5864 if self.leader_replica_id.is_none() {
5865 buffer.set_active_selections(&self.selections, cx);
5866 }
5867 });
5868 }
5869 }
5870
5871 fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
5872 let blurred_event = EditorBlurred(cx.handle());
5873 cx.emit_global(blurred_event);
5874 self.focused = false;
5875 self.buffer
5876 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
5877 self.hide_context_menu(cx);
5878 cx.emit(Event::Blurred);
5879 cx.notify();
5880 }
5881
5882 fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
5883 let mut context = Self::default_keymap_context();
5884 let mode = match self.mode {
5885 EditorMode::SingleLine => "single_line",
5886 EditorMode::AutoHeight { .. } => "auto_height",
5887 EditorMode::Full => "full",
5888 };
5889 context.map.insert("mode".into(), mode.into());
5890 if self.pending_rename.is_some() {
5891 context.set.insert("renaming".into());
5892 }
5893 match self.context_menu.as_ref() {
5894 Some(ContextMenu::Completions(_)) => {
5895 context.set.insert("showing_completions".into());
5896 }
5897 Some(ContextMenu::CodeActions(_)) => {
5898 context.set.insert("showing_code_actions".into());
5899 }
5900 None => {}
5901 }
5902
5903 for layer in self.keymap_context_layers.values() {
5904 context.extend(layer);
5905 }
5906
5907 context
5908 }
5909}
5910
5911fn build_style(
5912 settings: &Settings,
5913 get_field_editor_theme: Option<GetFieldEditorTheme>,
5914 override_text_style: Option<&OverrideTextStyle>,
5915 cx: &AppContext,
5916) -> EditorStyle {
5917 let font_cache = cx.font_cache();
5918
5919 let mut theme = settings.theme.editor.clone();
5920 let mut style = if let Some(get_field_editor_theme) = get_field_editor_theme {
5921 let field_editor_theme = get_field_editor_theme(&settings.theme);
5922 theme.text_color = field_editor_theme.text.color;
5923 theme.selection = field_editor_theme.selection;
5924 theme.background = field_editor_theme
5925 .container
5926 .background_color
5927 .unwrap_or_default();
5928 EditorStyle {
5929 text: field_editor_theme.text,
5930 placeholder_text: field_editor_theme.placeholder_text,
5931 theme,
5932 }
5933 } else {
5934 let font_family_id = settings.buffer_font_family;
5935 let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
5936 let font_properties = Default::default();
5937 let font_id = font_cache
5938 .select_font(font_family_id, &font_properties)
5939 .unwrap();
5940 let font_size = settings.buffer_font_size;
5941 EditorStyle {
5942 text: TextStyle {
5943 color: settings.theme.editor.text_color,
5944 font_family_name,
5945 font_family_id,
5946 font_id,
5947 font_size,
5948 font_properties,
5949 underline: Default::default(),
5950 },
5951 placeholder_text: None,
5952 theme,
5953 }
5954 };
5955
5956 if let Some(highlight_style) = override_text_style.and_then(|build_style| build_style(&style)) {
5957 if let Some(highlighted) = style
5958 .text
5959 .clone()
5960 .highlight(highlight_style, font_cache)
5961 .log_err()
5962 {
5963 style.text = highlighted;
5964 }
5965 }
5966
5967 style
5968}
5969
5970trait SelectionExt {
5971 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
5972 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
5973 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
5974 fn spanned_rows(&self, include_end_if_at_line_start: bool, map: &DisplaySnapshot)
5975 -> Range<u32>;
5976}
5977
5978impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
5979 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
5980 let start = self.start.to_point(buffer);
5981 let end = self.end.to_point(buffer);
5982 if self.reversed {
5983 end..start
5984 } else {
5985 start..end
5986 }
5987 }
5988
5989 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
5990 let start = self.start.to_offset(buffer);
5991 let end = self.end.to_offset(buffer);
5992 if self.reversed {
5993 end..start
5994 } else {
5995 start..end
5996 }
5997 }
5998
5999 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
6000 let start = self
6001 .start
6002 .to_point(&map.buffer_snapshot)
6003 .to_display_point(map);
6004 let end = self
6005 .end
6006 .to_point(&map.buffer_snapshot)
6007 .to_display_point(map);
6008 if self.reversed {
6009 end..start
6010 } else {
6011 start..end
6012 }
6013 }
6014
6015 fn spanned_rows(
6016 &self,
6017 include_end_if_at_line_start: bool,
6018 map: &DisplaySnapshot,
6019 ) -> Range<u32> {
6020 let start = self.start.to_point(&map.buffer_snapshot);
6021 let mut end = self.end.to_point(&map.buffer_snapshot);
6022 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
6023 end.row -= 1;
6024 }
6025
6026 let buffer_start = map.prev_line_boundary(start).0;
6027 let buffer_end = map.next_line_boundary(end).0;
6028 buffer_start.row..buffer_end.row + 1
6029 }
6030}
6031
6032impl<T: InvalidationRegion> InvalidationStack<T> {
6033 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
6034 where
6035 S: Clone + ToOffset,
6036 {
6037 while let Some(region) = self.last() {
6038 let all_selections_inside_invalidation_ranges =
6039 if selections.len() == region.ranges().len() {
6040 selections
6041 .iter()
6042 .zip(region.ranges().iter().map(|r| r.to_offset(&buffer)))
6043 .all(|(selection, invalidation_range)| {
6044 let head = selection.head().to_offset(&buffer);
6045 invalidation_range.start <= head && invalidation_range.end >= head
6046 })
6047 } else {
6048 false
6049 };
6050
6051 if all_selections_inside_invalidation_ranges {
6052 break;
6053 } else {
6054 self.pop();
6055 }
6056 }
6057 }
6058}
6059
6060impl<T> Default for InvalidationStack<T> {
6061 fn default() -> Self {
6062 Self(Default::default())
6063 }
6064}
6065
6066impl<T> Deref for InvalidationStack<T> {
6067 type Target = Vec<T>;
6068
6069 fn deref(&self) -> &Self::Target {
6070 &self.0
6071 }
6072}
6073
6074impl<T> DerefMut for InvalidationStack<T> {
6075 fn deref_mut(&mut self) -> &mut Self::Target {
6076 &mut self.0
6077 }
6078}
6079
6080impl InvalidationRegion for BracketPairState {
6081 fn ranges(&self) -> &[Range<Anchor>] {
6082 &self.ranges
6083 }
6084}
6085
6086impl InvalidationRegion for SnippetState {
6087 fn ranges(&self) -> &[Range<Anchor>] {
6088 &self.ranges[self.active_index]
6089 }
6090}
6091
6092impl Deref for EditorStyle {
6093 type Target = theme::Editor;
6094
6095 fn deref(&self) -> &Self::Target {
6096 &self.theme
6097 }
6098}
6099
6100pub fn diagnostic_block_renderer(diagnostic: Diagnostic, is_valid: bool) -> RenderBlock {
6101 let mut highlighted_lines = Vec::new();
6102 for line in diagnostic.message.lines() {
6103 highlighted_lines.push(highlight_diagnostic_message(line));
6104 }
6105
6106 Arc::new(move |cx: &BlockContext| {
6107 let settings = cx.global::<Settings>();
6108 let theme = &settings.theme.editor;
6109 let style = diagnostic_style(diagnostic.severity, is_valid, theme);
6110 let font_size = (style.text_scale_factor * settings.buffer_font_size).round();
6111 Flex::column()
6112 .with_children(highlighted_lines.iter().map(|(line, highlights)| {
6113 Label::new(
6114 line.clone(),
6115 style.message.clone().with_font_size(font_size),
6116 )
6117 .with_highlights(highlights.clone())
6118 .contained()
6119 .with_margin_left(cx.anchor_x)
6120 .boxed()
6121 }))
6122 .aligned()
6123 .left()
6124 .boxed()
6125 })
6126}
6127
6128pub fn highlight_diagnostic_message(message: &str) -> (String, Vec<usize>) {
6129 let mut message_without_backticks = String::new();
6130 let mut prev_offset = 0;
6131 let mut inside_block = false;
6132 let mut highlights = Vec::new();
6133 for (match_ix, (offset, _)) in message
6134 .match_indices('`')
6135 .chain([(message.len(), "")])
6136 .enumerate()
6137 {
6138 message_without_backticks.push_str(&message[prev_offset..offset]);
6139 if inside_block {
6140 highlights.extend(prev_offset - match_ix..offset - match_ix);
6141 }
6142
6143 inside_block = !inside_block;
6144 prev_offset = offset + 1;
6145 }
6146
6147 (message_without_backticks, highlights)
6148}
6149
6150pub fn diagnostic_style(
6151 severity: DiagnosticSeverity,
6152 valid: bool,
6153 theme: &theme::Editor,
6154) -> DiagnosticStyle {
6155 match (severity, valid) {
6156 (DiagnosticSeverity::ERROR, true) => theme.error_diagnostic.clone(),
6157 (DiagnosticSeverity::ERROR, false) => theme.invalid_error_diagnostic.clone(),
6158 (DiagnosticSeverity::WARNING, true) => theme.warning_diagnostic.clone(),
6159 (DiagnosticSeverity::WARNING, false) => theme.invalid_warning_diagnostic.clone(),
6160 (DiagnosticSeverity::INFORMATION, true) => theme.information_diagnostic.clone(),
6161 (DiagnosticSeverity::INFORMATION, false) => theme.invalid_information_diagnostic.clone(),
6162 (DiagnosticSeverity::HINT, true) => theme.hint_diagnostic.clone(),
6163 (DiagnosticSeverity::HINT, false) => theme.invalid_hint_diagnostic.clone(),
6164 _ => theme.invalid_hint_diagnostic.clone(),
6165 }
6166}
6167
6168pub fn combine_syntax_and_fuzzy_match_highlights(
6169 text: &str,
6170 default_style: HighlightStyle,
6171 syntax_ranges: impl Iterator<Item = (Range<usize>, HighlightStyle)>,
6172 match_indices: &[usize],
6173) -> Vec<(Range<usize>, HighlightStyle)> {
6174 let mut result = Vec::new();
6175 let mut match_indices = match_indices.iter().copied().peekable();
6176
6177 for (range, mut syntax_highlight) in syntax_ranges.chain([(usize::MAX..0, Default::default())])
6178 {
6179 syntax_highlight.weight = None;
6180
6181 // Add highlights for any fuzzy match characters before the next
6182 // syntax highlight range.
6183 while let Some(&match_index) = match_indices.peek() {
6184 if match_index >= range.start {
6185 break;
6186 }
6187 match_indices.next();
6188 let end_index = char_ix_after(match_index, text);
6189 let mut match_style = default_style;
6190 match_style.weight = Some(fonts::Weight::BOLD);
6191 result.push((match_index..end_index, match_style));
6192 }
6193
6194 if range.start == usize::MAX {
6195 break;
6196 }
6197
6198 // Add highlights for any fuzzy match characters within the
6199 // syntax highlight range.
6200 let mut offset = range.start;
6201 while let Some(&match_index) = match_indices.peek() {
6202 if match_index >= range.end {
6203 break;
6204 }
6205
6206 match_indices.next();
6207 if match_index > offset {
6208 result.push((offset..match_index, syntax_highlight));
6209 }
6210
6211 let mut end_index = char_ix_after(match_index, text);
6212 while let Some(&next_match_index) = match_indices.peek() {
6213 if next_match_index == end_index && next_match_index < range.end {
6214 end_index = char_ix_after(next_match_index, text);
6215 match_indices.next();
6216 } else {
6217 break;
6218 }
6219 }
6220
6221 let mut match_style = syntax_highlight;
6222 match_style.weight = Some(fonts::Weight::BOLD);
6223 result.push((match_index..end_index, match_style));
6224 offset = end_index;
6225 }
6226
6227 if offset < range.end {
6228 result.push((offset..range.end, syntax_highlight));
6229 }
6230 }
6231
6232 fn char_ix_after(ix: usize, text: &str) -> usize {
6233 ix + text[ix..].chars().next().unwrap().len_utf8()
6234 }
6235
6236 result
6237}
6238
6239pub fn styled_runs_for_code_label<'a>(
6240 label: &'a CodeLabel,
6241 syntax_theme: &'a theme::SyntaxTheme,
6242) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
6243 let fade_out = HighlightStyle {
6244 fade_out: Some(0.35),
6245 ..Default::default()
6246 };
6247
6248 let mut prev_end = label.filter_range.end;
6249 label
6250 .runs
6251 .iter()
6252 .enumerate()
6253 .flat_map(move |(ix, (range, highlight_id))| {
6254 let style = if let Some(style) = highlight_id.style(syntax_theme) {
6255 style
6256 } else {
6257 return Default::default();
6258 };
6259 let mut muted_style = style.clone();
6260 muted_style.highlight(fade_out);
6261
6262 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
6263 if range.start >= label.filter_range.end {
6264 if range.start > prev_end {
6265 runs.push((prev_end..range.start, fade_out));
6266 }
6267 runs.push((range.clone(), muted_style));
6268 } else if range.end <= label.filter_range.end {
6269 runs.push((range.clone(), style));
6270 } else {
6271 runs.push((range.start..label.filter_range.end, style));
6272 runs.push((label.filter_range.end..range.end, muted_style));
6273 }
6274 prev_end = cmp::max(prev_end, range.end);
6275
6276 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
6277 runs.push((prev_end..label.text.len(), fade_out));
6278 }
6279
6280 runs
6281 })
6282}
6283
6284#[cfg(test)]
6285mod tests {
6286
6287 use super::*;
6288 use gpui::{
6289 geometry::rect::RectF,
6290 platform::{WindowBounds, WindowOptions},
6291 };
6292 use language::{LanguageConfig, LanguageServerConfig};
6293 use lsp::FakeLanguageServer;
6294 use project::FakeFs;
6295 use smol::stream::StreamExt;
6296 use std::{cell::RefCell, rc::Rc, time::Instant};
6297 use text::Point;
6298 use unindent::Unindent;
6299 use util::test::{marked_text_by, sample_text};
6300 use workspace::FollowableItem;
6301
6302 #[gpui::test]
6303 fn test_edit_events(cx: &mut MutableAppContext) {
6304 populate_settings(cx);
6305 let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
6306
6307 let events = Rc::new(RefCell::new(Vec::new()));
6308 let (_, editor1) = cx.add_window(Default::default(), {
6309 let events = events.clone();
6310 |cx| {
6311 cx.subscribe(&cx.handle(), move |_, _, event, _| {
6312 if matches!(event, Event::Edited | Event::BufferEdited | Event::Dirtied) {
6313 events.borrow_mut().push(("editor1", *event));
6314 }
6315 })
6316 .detach();
6317 Editor::for_buffer(buffer.clone(), None, cx)
6318 }
6319 });
6320 let (_, editor2) = cx.add_window(Default::default(), {
6321 let events = events.clone();
6322 |cx| {
6323 cx.subscribe(&cx.handle(), move |_, _, event, _| {
6324 if matches!(event, Event::Edited | Event::BufferEdited | Event::Dirtied) {
6325 events.borrow_mut().push(("editor2", *event));
6326 }
6327 })
6328 .detach();
6329 Editor::for_buffer(buffer.clone(), None, cx)
6330 }
6331 });
6332 assert_eq!(mem::take(&mut *events.borrow_mut()), []);
6333
6334 // Mutating editor 1 will emit an `Edited` event only for that editor.
6335 editor1.update(cx, |editor, cx| editor.insert("X", cx));
6336 assert_eq!(
6337 mem::take(&mut *events.borrow_mut()),
6338 [
6339 ("editor1", Event::Edited),
6340 ("editor1", Event::BufferEdited),
6341 ("editor2", Event::BufferEdited),
6342 ("editor1", Event::Dirtied),
6343 ("editor2", Event::Dirtied)
6344 ]
6345 );
6346
6347 // Mutating editor 2 will emit an `Edited` event only for that editor.
6348 editor2.update(cx, |editor, cx| editor.delete(&Delete, cx));
6349 assert_eq!(
6350 mem::take(&mut *events.borrow_mut()),
6351 [
6352 ("editor2", Event::Edited),
6353 ("editor1", Event::BufferEdited),
6354 ("editor2", Event::BufferEdited),
6355 ]
6356 );
6357
6358 // Undoing on editor 1 will emit an `Edited` event only for that editor.
6359 editor1.update(cx, |editor, cx| editor.undo(&Undo, cx));
6360 assert_eq!(
6361 mem::take(&mut *events.borrow_mut()),
6362 [
6363 ("editor1", Event::Edited),
6364 ("editor1", Event::BufferEdited),
6365 ("editor2", Event::BufferEdited),
6366 ]
6367 );
6368
6369 // Redoing on editor 1 will emit an `Edited` event only for that editor.
6370 editor1.update(cx, |editor, cx| editor.redo(&Redo, cx));
6371 assert_eq!(
6372 mem::take(&mut *events.borrow_mut()),
6373 [
6374 ("editor1", Event::Edited),
6375 ("editor1", Event::BufferEdited),
6376 ("editor2", Event::BufferEdited),
6377 ]
6378 );
6379
6380 // Undoing on editor 2 will emit an `Edited` event only for that editor.
6381 editor2.update(cx, |editor, cx| editor.undo(&Undo, cx));
6382 assert_eq!(
6383 mem::take(&mut *events.borrow_mut()),
6384 [
6385 ("editor2", Event::Edited),
6386 ("editor1", Event::BufferEdited),
6387 ("editor2", Event::BufferEdited),
6388 ]
6389 );
6390
6391 // Redoing on editor 2 will emit an `Edited` event only for that editor.
6392 editor2.update(cx, |editor, cx| editor.redo(&Redo, cx));
6393 assert_eq!(
6394 mem::take(&mut *events.borrow_mut()),
6395 [
6396 ("editor2", Event::Edited),
6397 ("editor1", Event::BufferEdited),
6398 ("editor2", Event::BufferEdited),
6399 ]
6400 );
6401
6402 // No event is emitted when the mutation is a no-op.
6403 editor2.update(cx, |editor, cx| {
6404 editor.select_ranges([0..0], None, cx);
6405 editor.backspace(&Backspace, cx);
6406 });
6407 assert_eq!(mem::take(&mut *events.borrow_mut()), []);
6408 }
6409
6410 #[gpui::test]
6411 fn test_undo_redo_with_selection_restoration(cx: &mut MutableAppContext) {
6412 populate_settings(cx);
6413 let mut now = Instant::now();
6414 let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
6415 let group_interval = buffer.read(cx).transaction_group_interval();
6416 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6417 let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6418
6419 editor.update(cx, |editor, cx| {
6420 editor.start_transaction_at(now, cx);
6421 editor.select_ranges([2..4], None, cx);
6422 editor.insert("cd", cx);
6423 editor.end_transaction_at(now, cx);
6424 assert_eq!(editor.text(cx), "12cd56");
6425 assert_eq!(editor.selected_ranges(cx), vec![4..4]);
6426
6427 editor.start_transaction_at(now, cx);
6428 editor.select_ranges([4..5], None, cx);
6429 editor.insert("e", cx);
6430 editor.end_transaction_at(now, cx);
6431 assert_eq!(editor.text(cx), "12cde6");
6432 assert_eq!(editor.selected_ranges(cx), vec![5..5]);
6433
6434 now += group_interval + Duration::from_millis(1);
6435 editor.select_ranges([2..2], None, cx);
6436
6437 // Simulate an edit in another editor
6438 buffer.update(cx, |buffer, cx| {
6439 buffer.start_transaction_at(now, cx);
6440 buffer.edit([0..1], "a", cx);
6441 buffer.edit([1..1], "b", cx);
6442 buffer.end_transaction_at(now, cx);
6443 });
6444
6445 assert_eq!(editor.text(cx), "ab2cde6");
6446 assert_eq!(editor.selected_ranges(cx), vec![3..3]);
6447
6448 // Last transaction happened past the group interval in a different editor.
6449 // Undo it individually and don't restore selections.
6450 editor.undo(&Undo, cx);
6451 assert_eq!(editor.text(cx), "12cde6");
6452 assert_eq!(editor.selected_ranges(cx), vec![2..2]);
6453
6454 // First two transactions happened within the group interval in this editor.
6455 // Undo them together and restore selections.
6456 editor.undo(&Undo, cx);
6457 editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
6458 assert_eq!(editor.text(cx), "123456");
6459 assert_eq!(editor.selected_ranges(cx), vec![0..0]);
6460
6461 // Redo the first two transactions together.
6462 editor.redo(&Redo, cx);
6463 assert_eq!(editor.text(cx), "12cde6");
6464 assert_eq!(editor.selected_ranges(cx), vec![5..5]);
6465
6466 // Redo the last transaction on its own.
6467 editor.redo(&Redo, cx);
6468 assert_eq!(editor.text(cx), "ab2cde6");
6469 assert_eq!(editor.selected_ranges(cx), vec![6..6]);
6470
6471 // Test empty transactions.
6472 editor.start_transaction_at(now, cx);
6473 editor.end_transaction_at(now, cx);
6474 editor.undo(&Undo, cx);
6475 assert_eq!(editor.text(cx), "12cde6");
6476 });
6477 }
6478
6479 #[gpui::test]
6480 fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
6481 populate_settings(cx);
6482
6483 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\nddddddd\n", cx);
6484 let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6485 editor.update(cx, |view, cx| {
6486 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
6487 });
6488 assert_eq!(
6489 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6490 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
6491 );
6492
6493 editor.update(cx, |view, cx| {
6494 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
6495 });
6496
6497 assert_eq!(
6498 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6499 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6500 );
6501
6502 editor.update(cx, |view, cx| {
6503 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6504 });
6505
6506 assert_eq!(
6507 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6508 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
6509 );
6510
6511 editor.update(cx, |view, cx| {
6512 view.end_selection(cx);
6513 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
6514 });
6515
6516 assert_eq!(
6517 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6518 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
6519 );
6520
6521 editor.update(cx, |view, cx| {
6522 view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
6523 view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
6524 });
6525
6526 assert_eq!(
6527 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6528 [
6529 DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
6530 DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
6531 ]
6532 );
6533
6534 editor.update(cx, |view, cx| {
6535 view.end_selection(cx);
6536 });
6537
6538 assert_eq!(
6539 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6540 [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
6541 );
6542 }
6543
6544 #[gpui::test]
6545 fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
6546 populate_settings(cx);
6547 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
6548 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6549
6550 view.update(cx, |view, cx| {
6551 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
6552 assert_eq!(
6553 view.selected_display_ranges(cx),
6554 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
6555 );
6556 });
6557
6558 view.update(cx, |view, cx| {
6559 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
6560 assert_eq!(
6561 view.selected_display_ranges(cx),
6562 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6563 );
6564 });
6565
6566 view.update(cx, |view, cx| {
6567 view.cancel(&Cancel, cx);
6568 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6569 assert_eq!(
6570 view.selected_display_ranges(cx),
6571 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6572 );
6573 });
6574 }
6575
6576 #[gpui::test]
6577 fn test_navigation_history(cx: &mut gpui::MutableAppContext) {
6578 populate_settings(cx);
6579 use workspace::Item;
6580 let nav_history = Rc::new(RefCell::new(workspace::NavHistory::default()));
6581 let buffer = MultiBuffer::build_simple(&sample_text(30, 5, 'a'), cx);
6582
6583 cx.add_window(Default::default(), |cx| {
6584 let mut editor = build_editor(buffer.clone(), cx);
6585 editor.nav_history = Some(ItemNavHistory::new(nav_history.clone(), &cx.handle()));
6586
6587 // Move the cursor a small distance.
6588 // Nothing is added to the navigation history.
6589 editor.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
6590 editor.select_display_ranges(&[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)], cx);
6591 assert!(nav_history.borrow_mut().pop_backward().is_none());
6592
6593 // Move the cursor a large distance.
6594 // The history can jump back to the previous position.
6595 editor.select_display_ranges(&[DisplayPoint::new(13, 0)..DisplayPoint::new(13, 3)], cx);
6596 let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
6597 editor.navigate(nav_entry.data.unwrap(), cx);
6598 assert_eq!(nav_entry.item.id(), cx.view_id());
6599 assert_eq!(
6600 editor.selected_display_ranges(cx),
6601 &[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)]
6602 );
6603 assert!(nav_history.borrow_mut().pop_backward().is_none());
6604
6605 // Move the cursor a small distance via the mouse.
6606 // Nothing is added to the navigation history.
6607 editor.begin_selection(DisplayPoint::new(5, 0), false, 1, cx);
6608 editor.end_selection(cx);
6609 assert_eq!(
6610 editor.selected_display_ranges(cx),
6611 &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
6612 );
6613 assert!(nav_history.borrow_mut().pop_backward().is_none());
6614
6615 // Move the cursor a large distance via the mouse.
6616 // The history can jump back to the previous position.
6617 editor.begin_selection(DisplayPoint::new(15, 0), false, 1, cx);
6618 editor.end_selection(cx);
6619 assert_eq!(
6620 editor.selected_display_ranges(cx),
6621 &[DisplayPoint::new(15, 0)..DisplayPoint::new(15, 0)]
6622 );
6623 let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
6624 editor.navigate(nav_entry.data.unwrap(), cx);
6625 assert_eq!(nav_entry.item.id(), cx.view_id());
6626 assert_eq!(
6627 editor.selected_display_ranges(cx),
6628 &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
6629 );
6630 assert!(nav_history.borrow_mut().pop_backward().is_none());
6631
6632 editor
6633 });
6634 }
6635
6636 #[gpui::test]
6637 fn test_cancel(cx: &mut gpui::MutableAppContext) {
6638 populate_settings(cx);
6639 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
6640 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6641
6642 view.update(cx, |view, cx| {
6643 view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
6644 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6645 view.end_selection(cx);
6646
6647 view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
6648 view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
6649 view.end_selection(cx);
6650 assert_eq!(
6651 view.selected_display_ranges(cx),
6652 [
6653 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
6654 DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
6655 ]
6656 );
6657 });
6658
6659 view.update(cx, |view, cx| {
6660 view.cancel(&Cancel, cx);
6661 assert_eq!(
6662 view.selected_display_ranges(cx),
6663 [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
6664 );
6665 });
6666
6667 view.update(cx, |view, cx| {
6668 view.cancel(&Cancel, cx);
6669 assert_eq!(
6670 view.selected_display_ranges(cx),
6671 [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
6672 );
6673 });
6674 }
6675
6676 #[gpui::test]
6677 fn test_fold(cx: &mut gpui::MutableAppContext) {
6678 populate_settings(cx);
6679 let buffer = MultiBuffer::build_simple(
6680 &"
6681 impl Foo {
6682 // Hello!
6683
6684 fn a() {
6685 1
6686 }
6687
6688 fn b() {
6689 2
6690 }
6691
6692 fn c() {
6693 3
6694 }
6695 }
6696 "
6697 .unindent(),
6698 cx,
6699 );
6700 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6701
6702 view.update(cx, |view, cx| {
6703 view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx);
6704 view.fold(&Fold, cx);
6705 assert_eq!(
6706 view.display_text(cx),
6707 "
6708 impl Foo {
6709 // Hello!
6710
6711 fn a() {
6712 1
6713 }
6714
6715 fn b() {…
6716 }
6717
6718 fn c() {…
6719 }
6720 }
6721 "
6722 .unindent(),
6723 );
6724
6725 view.fold(&Fold, cx);
6726 assert_eq!(
6727 view.display_text(cx),
6728 "
6729 impl Foo {…
6730 }
6731 "
6732 .unindent(),
6733 );
6734
6735 view.unfold_lines(&UnfoldLines, cx);
6736 assert_eq!(
6737 view.display_text(cx),
6738 "
6739 impl Foo {
6740 // Hello!
6741
6742 fn a() {
6743 1
6744 }
6745
6746 fn b() {…
6747 }
6748
6749 fn c() {…
6750 }
6751 }
6752 "
6753 .unindent(),
6754 );
6755
6756 view.unfold_lines(&UnfoldLines, cx);
6757 assert_eq!(view.display_text(cx), buffer.read(cx).read(cx).text());
6758 });
6759 }
6760
6761 #[gpui::test]
6762 fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
6763 populate_settings(cx);
6764 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
6765 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6766
6767 buffer.update(cx, |buffer, cx| {
6768 buffer.edit(
6769 vec![
6770 Point::new(1, 0)..Point::new(1, 0),
6771 Point::new(1, 1)..Point::new(1, 1),
6772 ],
6773 "\t",
6774 cx,
6775 );
6776 });
6777
6778 view.update(cx, |view, cx| {
6779 assert_eq!(
6780 view.selected_display_ranges(cx),
6781 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6782 );
6783
6784 view.move_down(&MoveDown, cx);
6785 assert_eq!(
6786 view.selected_display_ranges(cx),
6787 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6788 );
6789
6790 view.move_right(&MoveRight, cx);
6791 assert_eq!(
6792 view.selected_display_ranges(cx),
6793 &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
6794 );
6795
6796 view.move_left(&MoveLeft, cx);
6797 assert_eq!(
6798 view.selected_display_ranges(cx),
6799 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6800 );
6801
6802 view.move_up(&MoveUp, cx);
6803 assert_eq!(
6804 view.selected_display_ranges(cx),
6805 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6806 );
6807
6808 view.move_to_end(&MoveToEnd, cx);
6809 assert_eq!(
6810 view.selected_display_ranges(cx),
6811 &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
6812 );
6813
6814 view.move_to_beginning(&MoveToBeginning, cx);
6815 assert_eq!(
6816 view.selected_display_ranges(cx),
6817 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6818 );
6819
6820 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx);
6821 view.select_to_beginning(&SelectToBeginning, cx);
6822 assert_eq!(
6823 view.selected_display_ranges(cx),
6824 &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
6825 );
6826
6827 view.select_to_end(&SelectToEnd, cx);
6828 assert_eq!(
6829 view.selected_display_ranges(cx),
6830 &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
6831 );
6832 });
6833 }
6834
6835 #[gpui::test]
6836 fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
6837 populate_settings(cx);
6838 let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
6839 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6840
6841 assert_eq!('ⓐ'.len_utf8(), 3);
6842 assert_eq!('α'.len_utf8(), 2);
6843
6844 view.update(cx, |view, cx| {
6845 view.fold_ranges(
6846 vec![
6847 Point::new(0, 6)..Point::new(0, 12),
6848 Point::new(1, 2)..Point::new(1, 4),
6849 Point::new(2, 4)..Point::new(2, 8),
6850 ],
6851 cx,
6852 );
6853 assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
6854
6855 view.move_right(&MoveRight, cx);
6856 assert_eq!(
6857 view.selected_display_ranges(cx),
6858 &[empty_range(0, "ⓐ".len())]
6859 );
6860 view.move_right(&MoveRight, cx);
6861 assert_eq!(
6862 view.selected_display_ranges(cx),
6863 &[empty_range(0, "ⓐⓑ".len())]
6864 );
6865 view.move_right(&MoveRight, cx);
6866 assert_eq!(
6867 view.selected_display_ranges(cx),
6868 &[empty_range(0, "ⓐⓑ…".len())]
6869 );
6870
6871 view.move_down(&MoveDown, cx);
6872 assert_eq!(
6873 view.selected_display_ranges(cx),
6874 &[empty_range(1, "ab…".len())]
6875 );
6876 view.move_left(&MoveLeft, cx);
6877 assert_eq!(
6878 view.selected_display_ranges(cx),
6879 &[empty_range(1, "ab".len())]
6880 );
6881 view.move_left(&MoveLeft, cx);
6882 assert_eq!(
6883 view.selected_display_ranges(cx),
6884 &[empty_range(1, "a".len())]
6885 );
6886
6887 view.move_down(&MoveDown, cx);
6888 assert_eq!(
6889 view.selected_display_ranges(cx),
6890 &[empty_range(2, "α".len())]
6891 );
6892 view.move_right(&MoveRight, cx);
6893 assert_eq!(
6894 view.selected_display_ranges(cx),
6895 &[empty_range(2, "αβ".len())]
6896 );
6897 view.move_right(&MoveRight, cx);
6898 assert_eq!(
6899 view.selected_display_ranges(cx),
6900 &[empty_range(2, "αβ…".len())]
6901 );
6902 view.move_right(&MoveRight, cx);
6903 assert_eq!(
6904 view.selected_display_ranges(cx),
6905 &[empty_range(2, "αβ…ε".len())]
6906 );
6907
6908 view.move_up(&MoveUp, cx);
6909 assert_eq!(
6910 view.selected_display_ranges(cx),
6911 &[empty_range(1, "ab…e".len())]
6912 );
6913 view.move_up(&MoveUp, cx);
6914 assert_eq!(
6915 view.selected_display_ranges(cx),
6916 &[empty_range(0, "ⓐⓑ…ⓔ".len())]
6917 );
6918 view.move_left(&MoveLeft, cx);
6919 assert_eq!(
6920 view.selected_display_ranges(cx),
6921 &[empty_range(0, "ⓐⓑ…".len())]
6922 );
6923 view.move_left(&MoveLeft, cx);
6924 assert_eq!(
6925 view.selected_display_ranges(cx),
6926 &[empty_range(0, "ⓐⓑ".len())]
6927 );
6928 view.move_left(&MoveLeft, cx);
6929 assert_eq!(
6930 view.selected_display_ranges(cx),
6931 &[empty_range(0, "ⓐ".len())]
6932 );
6933 });
6934 }
6935
6936 #[gpui::test]
6937 fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
6938 populate_settings(cx);
6939 let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
6940 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6941 view.update(cx, |view, cx| {
6942 view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx);
6943 view.move_down(&MoveDown, cx);
6944 assert_eq!(
6945 view.selected_display_ranges(cx),
6946 &[empty_range(1, "abcd".len())]
6947 );
6948
6949 view.move_down(&MoveDown, cx);
6950 assert_eq!(
6951 view.selected_display_ranges(cx),
6952 &[empty_range(2, "αβγ".len())]
6953 );
6954
6955 view.move_down(&MoveDown, cx);
6956 assert_eq!(
6957 view.selected_display_ranges(cx),
6958 &[empty_range(3, "abcd".len())]
6959 );
6960
6961 view.move_down(&MoveDown, cx);
6962 assert_eq!(
6963 view.selected_display_ranges(cx),
6964 &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
6965 );
6966
6967 view.move_up(&MoveUp, cx);
6968 assert_eq!(
6969 view.selected_display_ranges(cx),
6970 &[empty_range(3, "abcd".len())]
6971 );
6972
6973 view.move_up(&MoveUp, cx);
6974 assert_eq!(
6975 view.selected_display_ranges(cx),
6976 &[empty_range(2, "αβγ".len())]
6977 );
6978 });
6979 }
6980
6981 #[gpui::test]
6982 fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
6983 populate_settings(cx);
6984 let buffer = MultiBuffer::build_simple("abc\n def", cx);
6985 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6986 view.update(cx, |view, cx| {
6987 view.select_display_ranges(
6988 &[
6989 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6990 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
6991 ],
6992 cx,
6993 );
6994 });
6995
6996 view.update(cx, |view, cx| {
6997 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6998 assert_eq!(
6999 view.selected_display_ranges(cx),
7000 &[
7001 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7002 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
7003 ]
7004 );
7005 });
7006
7007 view.update(cx, |view, cx| {
7008 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
7009 assert_eq!(
7010 view.selected_display_ranges(cx),
7011 &[
7012 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7013 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7014 ]
7015 );
7016 });
7017
7018 view.update(cx, |view, cx| {
7019 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
7020 assert_eq!(
7021 view.selected_display_ranges(cx),
7022 &[
7023 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7024 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
7025 ]
7026 );
7027 });
7028
7029 view.update(cx, |view, cx| {
7030 view.move_to_end_of_line(&MoveToEndOfLine, cx);
7031 assert_eq!(
7032 view.selected_display_ranges(cx),
7033 &[
7034 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7035 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
7036 ]
7037 );
7038 });
7039
7040 // Moving to the end of line again is a no-op.
7041 view.update(cx, |view, cx| {
7042 view.move_to_end_of_line(&MoveToEndOfLine, cx);
7043 assert_eq!(
7044 view.selected_display_ranges(cx),
7045 &[
7046 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7047 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
7048 ]
7049 );
7050 });
7051
7052 view.update(cx, |view, cx| {
7053 view.move_left(&MoveLeft, cx);
7054 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
7055 assert_eq!(
7056 view.selected_display_ranges(cx),
7057 &[
7058 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
7059 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
7060 ]
7061 );
7062 });
7063
7064 view.update(cx, |view, cx| {
7065 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
7066 assert_eq!(
7067 view.selected_display_ranges(cx),
7068 &[
7069 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
7070 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
7071 ]
7072 );
7073 });
7074
7075 view.update(cx, |view, cx| {
7076 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
7077 assert_eq!(
7078 view.selected_display_ranges(cx),
7079 &[
7080 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
7081 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
7082 ]
7083 );
7084 });
7085
7086 view.update(cx, |view, cx| {
7087 view.select_to_end_of_line(&SelectToEndOfLine(true), cx);
7088 assert_eq!(
7089 view.selected_display_ranges(cx),
7090 &[
7091 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
7092 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
7093 ]
7094 );
7095 });
7096
7097 view.update(cx, |view, cx| {
7098 view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
7099 assert_eq!(view.display_text(cx), "ab\n de");
7100 assert_eq!(
7101 view.selected_display_ranges(cx),
7102 &[
7103 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7104 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
7105 ]
7106 );
7107 });
7108
7109 view.update(cx, |view, cx| {
7110 view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
7111 assert_eq!(view.display_text(cx), "\n");
7112 assert_eq!(
7113 view.selected_display_ranges(cx),
7114 &[
7115 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7116 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7117 ]
7118 );
7119 });
7120 }
7121
7122 #[gpui::test]
7123 fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
7124 populate_settings(cx);
7125 let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n {baz.qux()}", cx);
7126 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7127 view.update(cx, |view, cx| {
7128 view.select_display_ranges(
7129 &[
7130 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
7131 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
7132 ],
7133 cx,
7134 );
7135
7136 view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7137 assert_selection_ranges(
7138 "use std::<>str::{foo, bar}\n\n {[]baz.qux()}",
7139 vec![('<', '>'), ('[', ']')],
7140 view,
7141 cx,
7142 );
7143
7144 view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7145 assert_selection_ranges(
7146 "use std<>::str::{foo, bar}\n\n []{baz.qux()}",
7147 vec![('<', '>'), ('[', ']')],
7148 view,
7149 cx,
7150 );
7151
7152 view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7153 assert_selection_ranges(
7154 "use <>std::str::{foo, bar}\n\n[] {baz.qux()}",
7155 vec![('<', '>'), ('[', ']')],
7156 view,
7157 cx,
7158 );
7159
7160 view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7161 assert_selection_ranges(
7162 "<>use std::str::{foo, bar}\n[]\n {baz.qux()}",
7163 vec![('<', '>'), ('[', ']')],
7164 view,
7165 cx,
7166 );
7167
7168 view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7169 assert_selection_ranges(
7170 "<>use std::str::{foo, bar[]}\n\n {baz.qux()}",
7171 vec![('<', '>'), ('[', ']')],
7172 view,
7173 cx,
7174 );
7175
7176 view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7177 assert_selection_ranges(
7178 "use<> std::str::{foo, bar}[]\n\n {baz.qux()}",
7179 vec![('<', '>'), ('[', ']')],
7180 view,
7181 cx,
7182 );
7183
7184 view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7185 assert_selection_ranges(
7186 "use std<>::str::{foo, bar}\n[]\n {baz.qux()}",
7187 vec![('<', '>'), ('[', ']')],
7188 view,
7189 cx,
7190 );
7191
7192 view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7193 assert_selection_ranges(
7194 "use std::<>str::{foo, bar}\n\n {[]baz.qux()}",
7195 vec![('<', '>'), ('[', ']')],
7196 view,
7197 cx,
7198 );
7199
7200 view.move_right(&MoveRight, cx);
7201 view.select_to_previous_word_start(&SelectToPreviousWordStart, cx);
7202 assert_selection_ranges(
7203 "use std::>s<tr::{foo, bar}\n\n {]b[az.qux()}",
7204 vec![('<', '>'), ('[', ']')],
7205 view,
7206 cx,
7207 );
7208
7209 view.select_to_previous_word_start(&SelectToPreviousWordStart, cx);
7210 assert_selection_ranges(
7211 "use std>::s<tr::{foo, bar}\n\n ]{b[az.qux()}",
7212 vec![('<', '>'), ('[', ']')],
7213 view,
7214 cx,
7215 );
7216
7217 view.select_to_next_word_end(&SelectToNextWordEnd, cx);
7218 assert_selection_ranges(
7219 "use std::>s<tr::{foo, bar}\n\n {]b[az.qux()}",
7220 vec![('<', '>'), ('[', ']')],
7221 view,
7222 cx,
7223 );
7224 });
7225 }
7226
7227 #[gpui::test]
7228 fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
7229 populate_settings(cx);
7230 let buffer = MultiBuffer::build_simple("use one::{\n two::three::four::five\n};", cx);
7231 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7232
7233 view.update(cx, |view, cx| {
7234 view.set_wrap_width(Some(140.), cx);
7235 assert_eq!(
7236 view.display_text(cx),
7237 "use one::{\n two::three::\n four::five\n};"
7238 );
7239
7240 view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx);
7241
7242 view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7243 assert_eq!(
7244 view.selected_display_ranges(cx),
7245 &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
7246 );
7247
7248 view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7249 assert_eq!(
7250 view.selected_display_ranges(cx),
7251 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
7252 );
7253
7254 view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7255 assert_eq!(
7256 view.selected_display_ranges(cx),
7257 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
7258 );
7259
7260 view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7261 assert_eq!(
7262 view.selected_display_ranges(cx),
7263 &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
7264 );
7265
7266 view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7267 assert_eq!(
7268 view.selected_display_ranges(cx),
7269 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
7270 );
7271
7272 view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7273 assert_eq!(
7274 view.selected_display_ranges(cx),
7275 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
7276 );
7277 });
7278 }
7279
7280 #[gpui::test]
7281 fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
7282 populate_settings(cx);
7283 let buffer = MultiBuffer::build_simple("one two three four", cx);
7284 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7285
7286 view.update(cx, |view, cx| {
7287 view.select_display_ranges(
7288 &[
7289 // an empty selection - the preceding word fragment is deleted
7290 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7291 // characters selected - they are deleted
7292 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
7293 ],
7294 cx,
7295 );
7296 view.delete_to_previous_word_start(&DeleteToPreviousWordStart, cx);
7297 });
7298
7299 assert_eq!(buffer.read(cx).read(cx).text(), "e two te four");
7300
7301 view.update(cx, |view, cx| {
7302 view.select_display_ranges(
7303 &[
7304 // an empty selection - the following word fragment is deleted
7305 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7306 // characters selected - they are deleted
7307 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
7308 ],
7309 cx,
7310 );
7311 view.delete_to_next_word_end(&DeleteToNextWordEnd, cx);
7312 });
7313
7314 assert_eq!(buffer.read(cx).read(cx).text(), "e t te our");
7315 }
7316
7317 #[gpui::test]
7318 fn test_newline(cx: &mut gpui::MutableAppContext) {
7319 populate_settings(cx);
7320 let buffer = MultiBuffer::build_simple("aaaa\n bbbb\n", cx);
7321 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7322
7323 view.update(cx, |view, cx| {
7324 view.select_display_ranges(
7325 &[
7326 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7327 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
7328 DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
7329 ],
7330 cx,
7331 );
7332
7333 view.newline(&Newline, cx);
7334 assert_eq!(view.text(cx), "aa\naa\n \n bb\n bb\n");
7335 });
7336 }
7337
7338 #[gpui::test]
7339 fn test_newline_with_old_selections(cx: &mut gpui::MutableAppContext) {
7340 populate_settings(cx);
7341 let buffer = MultiBuffer::build_simple(
7342 "
7343 a
7344 b(
7345 X
7346 )
7347 c(
7348 X
7349 )
7350 "
7351 .unindent()
7352 .as_str(),
7353 cx,
7354 );
7355
7356 let (_, editor) = cx.add_window(Default::default(), |cx| {
7357 let mut editor = build_editor(buffer.clone(), cx);
7358 editor.select_ranges(
7359 [
7360 Point::new(2, 4)..Point::new(2, 5),
7361 Point::new(5, 4)..Point::new(5, 5),
7362 ],
7363 None,
7364 cx,
7365 );
7366 editor
7367 });
7368
7369 // Edit the buffer directly, deleting ranges surrounding the editor's selections
7370 buffer.update(cx, |buffer, cx| {
7371 buffer.edit(
7372 [
7373 Point::new(1, 2)..Point::new(3, 0),
7374 Point::new(4, 2)..Point::new(6, 0),
7375 ],
7376 "",
7377 cx,
7378 );
7379 assert_eq!(
7380 buffer.read(cx).text(),
7381 "
7382 a
7383 b()
7384 c()
7385 "
7386 .unindent()
7387 );
7388 });
7389
7390 editor.update(cx, |editor, cx| {
7391 assert_eq!(
7392 editor.selected_ranges(cx),
7393 &[
7394 Point::new(1, 2)..Point::new(1, 2),
7395 Point::new(2, 2)..Point::new(2, 2),
7396 ],
7397 );
7398
7399 editor.newline(&Newline, cx);
7400 assert_eq!(
7401 editor.text(cx),
7402 "
7403 a
7404 b(
7405 )
7406 c(
7407 )
7408 "
7409 .unindent()
7410 );
7411
7412 // The selections are moved after the inserted newlines
7413 assert_eq!(
7414 editor.selected_ranges(cx),
7415 &[
7416 Point::new(2, 0)..Point::new(2, 0),
7417 Point::new(4, 0)..Point::new(4, 0),
7418 ],
7419 );
7420 });
7421 }
7422
7423 #[gpui::test]
7424 fn test_insert_with_old_selections(cx: &mut gpui::MutableAppContext) {
7425 populate_settings(cx);
7426 let buffer = MultiBuffer::build_simple("a( X ), b( Y ), c( Z )", cx);
7427 let (_, editor) = cx.add_window(Default::default(), |cx| {
7428 let mut editor = build_editor(buffer.clone(), cx);
7429 editor.select_ranges([3..4, 11..12, 19..20], None, cx);
7430 editor
7431 });
7432
7433 // Edit the buffer directly, deleting ranges surrounding the editor's selections
7434 buffer.update(cx, |buffer, cx| {
7435 buffer.edit([2..5, 10..13, 18..21], "", cx);
7436 assert_eq!(buffer.read(cx).text(), "a(), b(), c()".unindent());
7437 });
7438
7439 editor.update(cx, |editor, cx| {
7440 assert_eq!(editor.selected_ranges(cx), &[2..2, 7..7, 12..12],);
7441
7442 editor.insert("Z", cx);
7443 assert_eq!(editor.text(cx), "a(Z), b(Z), c(Z)");
7444
7445 // The selections are moved after the inserted characters
7446 assert_eq!(editor.selected_ranges(cx), &[3..3, 9..9, 15..15],);
7447 });
7448 }
7449
7450 #[gpui::test]
7451 fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
7452 populate_settings(cx);
7453 let buffer = MultiBuffer::build_simple(" one two\nthree\n four", cx);
7454 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7455
7456 view.update(cx, |view, cx| {
7457 // two selections on the same line
7458 view.select_display_ranges(
7459 &[
7460 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
7461 DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
7462 ],
7463 cx,
7464 );
7465
7466 // indent from mid-tabstop to full tabstop
7467 view.tab(&Tab, cx);
7468 assert_eq!(view.text(cx), " one two\nthree\n four");
7469 assert_eq!(
7470 view.selected_display_ranges(cx),
7471 &[
7472 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
7473 DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
7474 ]
7475 );
7476
7477 // outdent from 1 tabstop to 0 tabstops
7478 view.outdent(&Outdent, cx);
7479 assert_eq!(view.text(cx), "one two\nthree\n four");
7480 assert_eq!(
7481 view.selected_display_ranges(cx),
7482 &[
7483 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
7484 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
7485 ]
7486 );
7487
7488 // select across line ending
7489 view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx);
7490
7491 // indent and outdent affect only the preceding line
7492 view.tab(&Tab, cx);
7493 assert_eq!(view.text(cx), "one two\n three\n four");
7494 assert_eq!(
7495 view.selected_display_ranges(cx),
7496 &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
7497 );
7498 view.outdent(&Outdent, cx);
7499 assert_eq!(view.text(cx), "one two\nthree\n four");
7500 assert_eq!(
7501 view.selected_display_ranges(cx),
7502 &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
7503 );
7504
7505 // Ensure that indenting/outdenting works when the cursor is at column 0.
7506 view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
7507 view.tab(&Tab, cx);
7508 assert_eq!(view.text(cx), "one two\n three\n four");
7509 assert_eq!(
7510 view.selected_display_ranges(cx),
7511 &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
7512 );
7513
7514 view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
7515 view.outdent(&Outdent, cx);
7516 assert_eq!(view.text(cx), "one two\nthree\n four");
7517 assert_eq!(
7518 view.selected_display_ranges(cx),
7519 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
7520 );
7521 });
7522 }
7523
7524 #[gpui::test]
7525 fn test_backspace(cx: &mut gpui::MutableAppContext) {
7526 populate_settings(cx);
7527 let (_, view) = cx.add_window(Default::default(), |cx| {
7528 build_editor(MultiBuffer::build_simple("", cx), cx)
7529 });
7530
7531 view.update(cx, |view, cx| {
7532 view.set_text("one two three\nfour five six\nseven eight nine\nten\n", cx);
7533 view.select_display_ranges(
7534 &[
7535 // an empty selection - the preceding character is deleted
7536 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7537 // one character selected - it is deleted
7538 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7539 // a line suffix selected - it is deleted
7540 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
7541 ],
7542 cx,
7543 );
7544 view.backspace(&Backspace, cx);
7545 assert_eq!(view.text(cx), "oe two three\nfou five six\nseven ten\n");
7546
7547 view.set_text(" one\n two\n three\n four", cx);
7548 view.select_display_ranges(
7549 &[
7550 // cursors at the the end of leading indent - last indent is deleted
7551 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
7552 DisplayPoint::new(1, 8)..DisplayPoint::new(1, 8),
7553 // cursors inside leading indent - overlapping indent deletions are coalesced
7554 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
7555 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
7556 DisplayPoint::new(2, 6)..DisplayPoint::new(2, 6),
7557 // cursor at the beginning of a line - preceding newline is deleted
7558 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7559 // selection inside leading indent - only the selected character is deleted
7560 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3),
7561 ],
7562 cx,
7563 );
7564 view.backspace(&Backspace, cx);
7565 assert_eq!(view.text(cx), "one\n two\n three four");
7566 });
7567 }
7568
7569 #[gpui::test]
7570 fn test_delete(cx: &mut gpui::MutableAppContext) {
7571 populate_settings(cx);
7572 let buffer =
7573 MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
7574 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7575
7576 view.update(cx, |view, cx| {
7577 view.select_display_ranges(
7578 &[
7579 // an empty selection - the following character is deleted
7580 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7581 // one character selected - it is deleted
7582 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7583 // a line suffix selected - it is deleted
7584 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
7585 ],
7586 cx,
7587 );
7588 view.delete(&Delete, cx);
7589 });
7590
7591 assert_eq!(
7592 buffer.read(cx).read(cx).text(),
7593 "on two three\nfou five six\nseven ten\n"
7594 );
7595 }
7596
7597 #[gpui::test]
7598 fn test_delete_line(cx: &mut gpui::MutableAppContext) {
7599 populate_settings(cx);
7600 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7601 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7602 view.update(cx, |view, cx| {
7603 view.select_display_ranges(
7604 &[
7605 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7606 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
7607 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7608 ],
7609 cx,
7610 );
7611 view.delete_line(&DeleteLine, cx);
7612 assert_eq!(view.display_text(cx), "ghi");
7613 assert_eq!(
7614 view.selected_display_ranges(cx),
7615 vec![
7616 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7617 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
7618 ]
7619 );
7620 });
7621
7622 populate_settings(cx);
7623 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7624 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7625 view.update(cx, |view, cx| {
7626 view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx);
7627 view.delete_line(&DeleteLine, cx);
7628 assert_eq!(view.display_text(cx), "ghi\n");
7629 assert_eq!(
7630 view.selected_display_ranges(cx),
7631 vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
7632 );
7633 });
7634 }
7635
7636 #[gpui::test]
7637 fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
7638 populate_settings(cx);
7639 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7640 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7641 view.update(cx, |view, cx| {
7642 view.select_display_ranges(
7643 &[
7644 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7645 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7646 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7647 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7648 ],
7649 cx,
7650 );
7651 view.duplicate_line(&DuplicateLine, cx);
7652 assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
7653 assert_eq!(
7654 view.selected_display_ranges(cx),
7655 vec![
7656 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
7657 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
7658 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7659 DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
7660 ]
7661 );
7662 });
7663
7664 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7665 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7666 view.update(cx, |view, cx| {
7667 view.select_display_ranges(
7668 &[
7669 DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
7670 DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
7671 ],
7672 cx,
7673 );
7674 view.duplicate_line(&DuplicateLine, cx);
7675 assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
7676 assert_eq!(
7677 view.selected_display_ranges(cx),
7678 vec![
7679 DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
7680 DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
7681 ]
7682 );
7683 });
7684 }
7685
7686 #[gpui::test]
7687 fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
7688 populate_settings(cx);
7689 let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
7690 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7691 view.update(cx, |view, cx| {
7692 view.fold_ranges(
7693 vec![
7694 Point::new(0, 2)..Point::new(1, 2),
7695 Point::new(2, 3)..Point::new(4, 1),
7696 Point::new(7, 0)..Point::new(8, 4),
7697 ],
7698 cx,
7699 );
7700 view.select_display_ranges(
7701 &[
7702 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7703 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7704 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7705 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
7706 ],
7707 cx,
7708 );
7709 assert_eq!(
7710 view.display_text(cx),
7711 "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
7712 );
7713
7714 view.move_line_up(&MoveLineUp, cx);
7715 assert_eq!(
7716 view.display_text(cx),
7717 "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
7718 );
7719 assert_eq!(
7720 view.selected_display_ranges(cx),
7721 vec![
7722 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7723 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7724 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
7725 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
7726 ]
7727 );
7728 });
7729
7730 view.update(cx, |view, cx| {
7731 view.move_line_down(&MoveLineDown, cx);
7732 assert_eq!(
7733 view.display_text(cx),
7734 "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
7735 );
7736 assert_eq!(
7737 view.selected_display_ranges(cx),
7738 vec![
7739 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7740 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7741 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7742 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
7743 ]
7744 );
7745 });
7746
7747 view.update(cx, |view, cx| {
7748 view.move_line_down(&MoveLineDown, cx);
7749 assert_eq!(
7750 view.display_text(cx),
7751 "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
7752 );
7753 assert_eq!(
7754 view.selected_display_ranges(cx),
7755 vec![
7756 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7757 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7758 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7759 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
7760 ]
7761 );
7762 });
7763
7764 view.update(cx, |view, cx| {
7765 view.move_line_up(&MoveLineUp, cx);
7766 assert_eq!(
7767 view.display_text(cx),
7768 "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
7769 );
7770 assert_eq!(
7771 view.selected_display_ranges(cx),
7772 vec![
7773 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7774 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7775 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
7776 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
7777 ]
7778 );
7779 });
7780 }
7781
7782 #[gpui::test]
7783 fn test_move_line_up_down_with_blocks(cx: &mut gpui::MutableAppContext) {
7784 populate_settings(cx);
7785 let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
7786 let snapshot = buffer.read(cx).snapshot(cx);
7787 let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7788 editor.update(cx, |editor, cx| {
7789 editor.insert_blocks(
7790 [BlockProperties {
7791 position: snapshot.anchor_after(Point::new(2, 0)),
7792 disposition: BlockDisposition::Below,
7793 height: 1,
7794 render: Arc::new(|_| Empty::new().boxed()),
7795 }],
7796 cx,
7797 );
7798 editor.select_ranges([Point::new(2, 0)..Point::new(2, 0)], None, cx);
7799 editor.move_line_down(&MoveLineDown, cx);
7800 });
7801 }
7802
7803 #[gpui::test]
7804 fn test_clipboard(cx: &mut gpui::MutableAppContext) {
7805 populate_settings(cx);
7806 let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
7807 let view = cx
7808 .add_window(Default::default(), |cx| build_editor(buffer.clone(), cx))
7809 .1;
7810
7811 // Cut with three selections. Clipboard text is divided into three slices.
7812 view.update(cx, |view, cx| {
7813 view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
7814 view.cut(&Cut, cx);
7815 assert_eq!(view.display_text(cx), "two four six ");
7816 });
7817
7818 // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
7819 view.update(cx, |view, cx| {
7820 view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
7821 view.paste(&Paste, cx);
7822 assert_eq!(view.display_text(cx), "two one✅ four three six five ");
7823 assert_eq!(
7824 view.selected_display_ranges(cx),
7825 &[
7826 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
7827 DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
7828 DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
7829 ]
7830 );
7831 });
7832
7833 // Paste again but with only two cursors. Since the number of cursors doesn't
7834 // match the number of slices in the clipboard, the entire clipboard text
7835 // is pasted at each cursor.
7836 view.update(cx, |view, cx| {
7837 view.select_ranges(vec![0..0, 31..31], None, cx);
7838 view.handle_input(&Input("( ".into()), cx);
7839 view.paste(&Paste, cx);
7840 view.handle_input(&Input(") ".into()), cx);
7841 assert_eq!(
7842 view.display_text(cx),
7843 "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7844 );
7845 });
7846
7847 view.update(cx, |view, cx| {
7848 view.select_ranges(vec![0..0], None, cx);
7849 view.handle_input(&Input("123\n4567\n89\n".into()), cx);
7850 assert_eq!(
7851 view.display_text(cx),
7852 "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7853 );
7854 });
7855
7856 // Cut with three selections, one of which is full-line.
7857 view.update(cx, |view, cx| {
7858 view.select_display_ranges(
7859 &[
7860 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
7861 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7862 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
7863 ],
7864 cx,
7865 );
7866 view.cut(&Cut, cx);
7867 assert_eq!(
7868 view.display_text(cx),
7869 "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7870 );
7871 });
7872
7873 // Paste with three selections, noticing how the copied selection that was full-line
7874 // gets inserted before the second cursor.
7875 view.update(cx, |view, cx| {
7876 view.select_display_ranges(
7877 &[
7878 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7879 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7880 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
7881 ],
7882 cx,
7883 );
7884 view.paste(&Paste, cx);
7885 assert_eq!(
7886 view.display_text(cx),
7887 "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
7888 );
7889 assert_eq!(
7890 view.selected_display_ranges(cx),
7891 &[
7892 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7893 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7894 DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
7895 ]
7896 );
7897 });
7898
7899 // Copy with a single cursor only, which writes the whole line into the clipboard.
7900 view.update(cx, |view, cx| {
7901 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx);
7902 view.copy(&Copy, cx);
7903 });
7904
7905 // Paste with three selections, noticing how the copied full-line selection is inserted
7906 // before the empty selections but replaces the selection that is non-empty.
7907 view.update(cx, |view, cx| {
7908 view.select_display_ranges(
7909 &[
7910 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7911 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
7912 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7913 ],
7914 cx,
7915 );
7916 view.paste(&Paste, cx);
7917 assert_eq!(
7918 view.display_text(cx),
7919 "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
7920 );
7921 assert_eq!(
7922 view.selected_display_ranges(cx),
7923 &[
7924 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7925 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7926 DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
7927 ]
7928 );
7929 });
7930 }
7931
7932 #[gpui::test]
7933 fn test_select_all(cx: &mut gpui::MutableAppContext) {
7934 populate_settings(cx);
7935 let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
7936 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7937 view.update(cx, |view, cx| {
7938 view.select_all(&SelectAll, cx);
7939 assert_eq!(
7940 view.selected_display_ranges(cx),
7941 &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
7942 );
7943 });
7944 }
7945
7946 #[gpui::test]
7947 fn test_select_line(cx: &mut gpui::MutableAppContext) {
7948 populate_settings(cx);
7949 let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
7950 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7951 view.update(cx, |view, cx| {
7952 view.select_display_ranges(
7953 &[
7954 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7955 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7956 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7957 DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
7958 ],
7959 cx,
7960 );
7961 view.select_line(&SelectLine, cx);
7962 assert_eq!(
7963 view.selected_display_ranges(cx),
7964 vec![
7965 DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
7966 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
7967 ]
7968 );
7969 });
7970
7971 view.update(cx, |view, cx| {
7972 view.select_line(&SelectLine, cx);
7973 assert_eq!(
7974 view.selected_display_ranges(cx),
7975 vec![
7976 DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
7977 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
7978 ]
7979 );
7980 });
7981
7982 view.update(cx, |view, cx| {
7983 view.select_line(&SelectLine, cx);
7984 assert_eq!(
7985 view.selected_display_ranges(cx),
7986 vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
7987 );
7988 });
7989 }
7990
7991 #[gpui::test]
7992 fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
7993 populate_settings(cx);
7994 let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
7995 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7996 view.update(cx, |view, cx| {
7997 view.fold_ranges(
7998 vec![
7999 Point::new(0, 2)..Point::new(1, 2),
8000 Point::new(2, 3)..Point::new(4, 1),
8001 Point::new(7, 0)..Point::new(8, 4),
8002 ],
8003 cx,
8004 );
8005 view.select_display_ranges(
8006 &[
8007 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
8008 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
8009 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
8010 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
8011 ],
8012 cx,
8013 );
8014 assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
8015 });
8016
8017 view.update(cx, |view, cx| {
8018 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
8019 assert_eq!(
8020 view.display_text(cx),
8021 "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
8022 );
8023 assert_eq!(
8024 view.selected_display_ranges(cx),
8025 [
8026 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
8027 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
8028 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
8029 DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
8030 ]
8031 );
8032 });
8033
8034 view.update(cx, |view, cx| {
8035 view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx);
8036 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
8037 assert_eq!(
8038 view.display_text(cx),
8039 "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
8040 );
8041 assert_eq!(
8042 view.selected_display_ranges(cx),
8043 [
8044 DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
8045 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
8046 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
8047 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
8048 DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
8049 DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
8050 DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
8051 DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
8052 ]
8053 );
8054 });
8055 }
8056
8057 #[gpui::test]
8058 fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
8059 populate_settings(cx);
8060 let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
8061 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
8062
8063 view.update(cx, |view, cx| {
8064 view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx);
8065 });
8066 view.update(cx, |view, cx| {
8067 view.add_selection_above(&AddSelectionAbove, cx);
8068 assert_eq!(
8069 view.selected_display_ranges(cx),
8070 vec![
8071 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
8072 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
8073 ]
8074 );
8075 });
8076
8077 view.update(cx, |view, cx| {
8078 view.add_selection_above(&AddSelectionAbove, cx);
8079 assert_eq!(
8080 view.selected_display_ranges(cx),
8081 vec![
8082 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
8083 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
8084 ]
8085 );
8086 });
8087
8088 view.update(cx, |view, cx| {
8089 view.add_selection_below(&AddSelectionBelow, cx);
8090 assert_eq!(
8091 view.selected_display_ranges(cx),
8092 vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
8093 );
8094 });
8095
8096 view.update(cx, |view, cx| {
8097 view.add_selection_below(&AddSelectionBelow, cx);
8098 assert_eq!(
8099 view.selected_display_ranges(cx),
8100 vec![
8101 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
8102 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
8103 ]
8104 );
8105 });
8106
8107 view.update(cx, |view, cx| {
8108 view.add_selection_below(&AddSelectionBelow, cx);
8109 assert_eq!(
8110 view.selected_display_ranges(cx),
8111 vec![
8112 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
8113 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
8114 ]
8115 );
8116 });
8117
8118 view.update(cx, |view, cx| {
8119 view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx);
8120 });
8121 view.update(cx, |view, cx| {
8122 view.add_selection_below(&AddSelectionBelow, cx);
8123 assert_eq!(
8124 view.selected_display_ranges(cx),
8125 vec![
8126 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
8127 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
8128 ]
8129 );
8130 });
8131
8132 view.update(cx, |view, cx| {
8133 view.add_selection_below(&AddSelectionBelow, cx);
8134 assert_eq!(
8135 view.selected_display_ranges(cx),
8136 vec![
8137 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
8138 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
8139 ]
8140 );
8141 });
8142
8143 view.update(cx, |view, cx| {
8144 view.add_selection_above(&AddSelectionAbove, cx);
8145 assert_eq!(
8146 view.selected_display_ranges(cx),
8147 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
8148 );
8149 });
8150
8151 view.update(cx, |view, cx| {
8152 view.add_selection_above(&AddSelectionAbove, cx);
8153 assert_eq!(
8154 view.selected_display_ranges(cx),
8155 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
8156 );
8157 });
8158
8159 view.update(cx, |view, cx| {
8160 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx);
8161 view.add_selection_below(&AddSelectionBelow, cx);
8162 assert_eq!(
8163 view.selected_display_ranges(cx),
8164 vec![
8165 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
8166 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
8167 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
8168 ]
8169 );
8170 });
8171
8172 view.update(cx, |view, cx| {
8173 view.add_selection_below(&AddSelectionBelow, cx);
8174 assert_eq!(
8175 view.selected_display_ranges(cx),
8176 vec![
8177 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
8178 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
8179 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
8180 DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
8181 ]
8182 );
8183 });
8184
8185 view.update(cx, |view, cx| {
8186 view.add_selection_above(&AddSelectionAbove, cx);
8187 assert_eq!(
8188 view.selected_display_ranges(cx),
8189 vec![
8190 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
8191 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
8192 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
8193 ]
8194 );
8195 });
8196
8197 view.update(cx, |view, cx| {
8198 view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx);
8199 });
8200 view.update(cx, |view, cx| {
8201 view.add_selection_above(&AddSelectionAbove, cx);
8202 assert_eq!(
8203 view.selected_display_ranges(cx),
8204 vec![
8205 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
8206 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
8207 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
8208 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
8209 ]
8210 );
8211 });
8212
8213 view.update(cx, |view, cx| {
8214 view.add_selection_below(&AddSelectionBelow, cx);
8215 assert_eq!(
8216 view.selected_display_ranges(cx),
8217 vec![
8218 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
8219 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
8220 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
8221 ]
8222 );
8223 });
8224 }
8225
8226 #[gpui::test]
8227 async fn test_select_larger_smaller_syntax_node(cx: &mut gpui::TestAppContext) {
8228 cx.update(populate_settings);
8229 let language = Arc::new(Language::new(
8230 LanguageConfig::default(),
8231 Some(tree_sitter_rust::language()),
8232 ));
8233
8234 let text = r#"
8235 use mod1::mod2::{mod3, mod4};
8236
8237 fn fn_1(param1: bool, param2: &str) {
8238 let var1 = "text";
8239 }
8240 "#
8241 .unindent();
8242
8243 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8244 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8245 let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
8246 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
8247 .await;
8248
8249 view.update(cx, |view, cx| {
8250 view.select_display_ranges(
8251 &[
8252 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
8253 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
8254 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
8255 ],
8256 cx,
8257 );
8258 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8259 });
8260 assert_eq!(
8261 view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8262 &[
8263 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
8264 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
8265 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
8266 ]
8267 );
8268
8269 view.update(cx, |view, cx| {
8270 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8271 });
8272 assert_eq!(
8273 view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8274 &[
8275 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
8276 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
8277 ]
8278 );
8279
8280 view.update(cx, |view, cx| {
8281 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8282 });
8283 assert_eq!(
8284 view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8285 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
8286 );
8287
8288 // Trying to expand the selected syntax node one more time has no effect.
8289 view.update(cx, |view, cx| {
8290 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8291 });
8292 assert_eq!(
8293 view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8294 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
8295 );
8296
8297 view.update(cx, |view, cx| {
8298 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8299 });
8300 assert_eq!(
8301 view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8302 &[
8303 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
8304 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
8305 ]
8306 );
8307
8308 view.update(cx, |view, cx| {
8309 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8310 });
8311 assert_eq!(
8312 view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8313 &[
8314 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
8315 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
8316 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
8317 ]
8318 );
8319
8320 view.update(cx, |view, cx| {
8321 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8322 });
8323 assert_eq!(
8324 view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8325 &[
8326 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
8327 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
8328 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
8329 ]
8330 );
8331
8332 // Trying to shrink the selected syntax node one more time has no effect.
8333 view.update(cx, |view, cx| {
8334 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8335 });
8336 assert_eq!(
8337 view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8338 &[
8339 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
8340 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
8341 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
8342 ]
8343 );
8344
8345 // Ensure that we keep expanding the selection if the larger selection starts or ends within
8346 // a fold.
8347 view.update(cx, |view, cx| {
8348 view.fold_ranges(
8349 vec![
8350 Point::new(0, 21)..Point::new(0, 24),
8351 Point::new(3, 20)..Point::new(3, 22),
8352 ],
8353 cx,
8354 );
8355 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8356 });
8357 assert_eq!(
8358 view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8359 &[
8360 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
8361 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
8362 DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
8363 ]
8364 );
8365 }
8366
8367 #[gpui::test]
8368 async fn test_autoindent_selections(cx: &mut gpui::TestAppContext) {
8369 cx.update(populate_settings);
8370 let language = Arc::new(
8371 Language::new(
8372 LanguageConfig {
8373 brackets: vec![
8374 BracketPair {
8375 start: "{".to_string(),
8376 end: "}".to_string(),
8377 close: false,
8378 newline: true,
8379 },
8380 BracketPair {
8381 start: "(".to_string(),
8382 end: ")".to_string(),
8383 close: false,
8384 newline: true,
8385 },
8386 ],
8387 ..Default::default()
8388 },
8389 Some(tree_sitter_rust::language()),
8390 )
8391 .with_indents_query(
8392 r#"
8393 (_ "(" ")" @end) @indent
8394 (_ "{" "}" @end) @indent
8395 "#,
8396 )
8397 .unwrap(),
8398 );
8399
8400 let text = "fn a() {}";
8401
8402 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8403 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8404 let (_, editor) = cx.add_window(|cx| build_editor(buffer, cx));
8405 editor
8406 .condition(&cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
8407 .await;
8408
8409 editor.update(cx, |editor, cx| {
8410 editor.select_ranges([5..5, 8..8, 9..9], None, cx);
8411 editor.newline(&Newline, cx);
8412 assert_eq!(editor.text(cx), "fn a(\n \n) {\n \n}\n");
8413 assert_eq!(
8414 editor.selected_ranges(cx),
8415 &[
8416 Point::new(1, 4)..Point::new(1, 4),
8417 Point::new(3, 4)..Point::new(3, 4),
8418 Point::new(5, 0)..Point::new(5, 0)
8419 ]
8420 );
8421 });
8422 }
8423
8424 #[gpui::test]
8425 async fn test_autoclose_pairs(cx: &mut gpui::TestAppContext) {
8426 cx.update(populate_settings);
8427 let language = Arc::new(Language::new(
8428 LanguageConfig {
8429 brackets: vec![
8430 BracketPair {
8431 start: "{".to_string(),
8432 end: "}".to_string(),
8433 close: true,
8434 newline: true,
8435 },
8436 BracketPair {
8437 start: "/*".to_string(),
8438 end: " */".to_string(),
8439 close: true,
8440 newline: true,
8441 },
8442 ],
8443 autoclose_before: "})]".to_string(),
8444 ..Default::default()
8445 },
8446 Some(tree_sitter_rust::language()),
8447 ));
8448
8449 let text = r#"
8450 a
8451
8452 /
8453
8454 "#
8455 .unindent();
8456
8457 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8458 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8459 let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
8460 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
8461 .await;
8462
8463 view.update(cx, |view, cx| {
8464 view.select_display_ranges(
8465 &[
8466 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
8467 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
8468 ],
8469 cx,
8470 );
8471
8472 view.handle_input(&Input("{".to_string()), cx);
8473 view.handle_input(&Input("{".to_string()), cx);
8474 view.handle_input(&Input("{".to_string()), cx);
8475 assert_eq!(
8476 view.text(cx),
8477 "
8478 {{{}}}
8479 {{{}}}
8480 /
8481
8482 "
8483 .unindent()
8484 );
8485
8486 view.move_right(&MoveRight, cx);
8487 view.handle_input(&Input("}".to_string()), cx);
8488 view.handle_input(&Input("}".to_string()), cx);
8489 view.handle_input(&Input("}".to_string()), cx);
8490 assert_eq!(
8491 view.text(cx),
8492 "
8493 {{{}}}}
8494 {{{}}}}
8495 /
8496
8497 "
8498 .unindent()
8499 );
8500
8501 view.undo(&Undo, cx);
8502 view.handle_input(&Input("/".to_string()), cx);
8503 view.handle_input(&Input("*".to_string()), cx);
8504 assert_eq!(
8505 view.text(cx),
8506 "
8507 /* */
8508 /* */
8509 /
8510
8511 "
8512 .unindent()
8513 );
8514
8515 view.undo(&Undo, cx);
8516 view.select_display_ranges(
8517 &[
8518 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
8519 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
8520 ],
8521 cx,
8522 );
8523 view.handle_input(&Input("*".to_string()), cx);
8524 assert_eq!(
8525 view.text(cx),
8526 "
8527 a
8528
8529 /*
8530 *
8531 "
8532 .unindent()
8533 );
8534
8535 // Don't autoclose if the next character isn't whitespace and isn't
8536 // listed in the language's "autoclose_before" section.
8537 view.finalize_last_transaction(cx);
8538 view.select_display_ranges(&[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)], cx);
8539 view.handle_input(&Input("{".to_string()), cx);
8540 assert_eq!(
8541 view.text(cx),
8542 "
8543 {a
8544
8545 /*
8546 *
8547 "
8548 .unindent()
8549 );
8550
8551 view.undo(&Undo, cx);
8552 view.select_display_ranges(&[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1)], cx);
8553 view.handle_input(&Input("{".to_string()), cx);
8554 assert_eq!(
8555 view.text(cx),
8556 "
8557 {a}
8558
8559 /*
8560 *
8561 "
8562 .unindent()
8563 );
8564 assert_eq!(
8565 view.selected_display_ranges(cx),
8566 [DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)]
8567 );
8568 });
8569 }
8570
8571 #[gpui::test]
8572 async fn test_snippets(cx: &mut gpui::TestAppContext) {
8573 cx.update(populate_settings);
8574
8575 let text = "
8576 a. b
8577 a. b
8578 a. b
8579 "
8580 .unindent();
8581 let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
8582 let (_, editor) = cx.add_window(|cx| build_editor(buffer, cx));
8583
8584 editor.update(cx, |editor, cx| {
8585 let buffer = &editor.snapshot(cx).buffer_snapshot;
8586 let snippet = Snippet::parse("f(${1:one}, ${2:two}, ${1:three})$0").unwrap();
8587 let insertion_ranges = [
8588 Point::new(0, 2).to_offset(buffer)..Point::new(0, 2).to_offset(buffer),
8589 Point::new(1, 2).to_offset(buffer)..Point::new(1, 2).to_offset(buffer),
8590 Point::new(2, 2).to_offset(buffer)..Point::new(2, 2).to_offset(buffer),
8591 ];
8592
8593 editor
8594 .insert_snippet(&insertion_ranges, snippet, cx)
8595 .unwrap();
8596 assert_eq!(
8597 editor.text(cx),
8598 "
8599 a.f(one, two, three) b
8600 a.f(one, two, three) b
8601 a.f(one, two, three) b
8602 "
8603 .unindent()
8604 );
8605 assert_eq!(
8606 editor.selected_ranges::<Point>(cx),
8607 &[
8608 Point::new(0, 4)..Point::new(0, 7),
8609 Point::new(0, 14)..Point::new(0, 19),
8610 Point::new(1, 4)..Point::new(1, 7),
8611 Point::new(1, 14)..Point::new(1, 19),
8612 Point::new(2, 4)..Point::new(2, 7),
8613 Point::new(2, 14)..Point::new(2, 19),
8614 ]
8615 );
8616
8617 // Can't move earlier than the first tab stop
8618 editor.move_to_prev_snippet_tabstop(cx);
8619 assert_eq!(
8620 editor.selected_ranges::<Point>(cx),
8621 &[
8622 Point::new(0, 4)..Point::new(0, 7),
8623 Point::new(0, 14)..Point::new(0, 19),
8624 Point::new(1, 4)..Point::new(1, 7),
8625 Point::new(1, 14)..Point::new(1, 19),
8626 Point::new(2, 4)..Point::new(2, 7),
8627 Point::new(2, 14)..Point::new(2, 19),
8628 ]
8629 );
8630
8631 assert!(editor.move_to_next_snippet_tabstop(cx));
8632 assert_eq!(
8633 editor.selected_ranges::<Point>(cx),
8634 &[
8635 Point::new(0, 9)..Point::new(0, 12),
8636 Point::new(1, 9)..Point::new(1, 12),
8637 Point::new(2, 9)..Point::new(2, 12)
8638 ]
8639 );
8640
8641 editor.move_to_prev_snippet_tabstop(cx);
8642 assert_eq!(
8643 editor.selected_ranges::<Point>(cx),
8644 &[
8645 Point::new(0, 4)..Point::new(0, 7),
8646 Point::new(0, 14)..Point::new(0, 19),
8647 Point::new(1, 4)..Point::new(1, 7),
8648 Point::new(1, 14)..Point::new(1, 19),
8649 Point::new(2, 4)..Point::new(2, 7),
8650 Point::new(2, 14)..Point::new(2, 19),
8651 ]
8652 );
8653
8654 assert!(editor.move_to_next_snippet_tabstop(cx));
8655 assert!(editor.move_to_next_snippet_tabstop(cx));
8656 assert_eq!(
8657 editor.selected_ranges::<Point>(cx),
8658 &[
8659 Point::new(0, 20)..Point::new(0, 20),
8660 Point::new(1, 20)..Point::new(1, 20),
8661 Point::new(2, 20)..Point::new(2, 20)
8662 ]
8663 );
8664
8665 // As soon as the last tab stop is reached, snippet state is gone
8666 editor.move_to_prev_snippet_tabstop(cx);
8667 assert_eq!(
8668 editor.selected_ranges::<Point>(cx),
8669 &[
8670 Point::new(0, 20)..Point::new(0, 20),
8671 Point::new(1, 20)..Point::new(1, 20),
8672 Point::new(2, 20)..Point::new(2, 20)
8673 ]
8674 );
8675 });
8676 }
8677
8678 #[gpui::test]
8679 async fn test_completion(cx: &mut gpui::TestAppContext) {
8680 cx.update(populate_settings);
8681
8682 let (mut language_server_config, mut fake_servers) = LanguageServerConfig::fake();
8683 language_server_config.set_fake_capabilities(lsp::ServerCapabilities {
8684 completion_provider: Some(lsp::CompletionOptions {
8685 trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
8686 ..Default::default()
8687 }),
8688 ..Default::default()
8689 });
8690 let language = Arc::new(Language::new(
8691 LanguageConfig {
8692 name: "Rust".into(),
8693 path_suffixes: vec!["rs".to_string()],
8694 language_server: Some(language_server_config),
8695 ..Default::default()
8696 },
8697 Some(tree_sitter_rust::language()),
8698 ));
8699
8700 let text = "
8701 one
8702 two
8703 three
8704 "
8705 .unindent();
8706
8707 let fs = FakeFs::new(cx.background().clone());
8708 fs.insert_file("/file.rs", text).await;
8709
8710 let project = Project::test(fs, cx);
8711 project.update(cx, |project, _| project.languages().add(language));
8712
8713 let worktree_id = project
8714 .update(cx, |project, cx| {
8715 project.find_or_create_local_worktree("/file.rs", true, cx)
8716 })
8717 .await
8718 .unwrap()
8719 .0
8720 .read_with(cx, |tree, _| tree.id());
8721 let buffer = project
8722 .update(cx, |project, cx| project.open_buffer((worktree_id, ""), cx))
8723 .await
8724 .unwrap();
8725 let mut fake_server = fake_servers.next().await.unwrap();
8726
8727 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8728 let (_, editor) = cx.add_window(|cx| build_editor(buffer, cx));
8729
8730 editor.update(cx, |editor, cx| {
8731 editor.project = Some(project);
8732 editor.select_ranges([Point::new(0, 3)..Point::new(0, 3)], None, cx);
8733 editor.handle_input(&Input(".".to_string()), cx);
8734 });
8735
8736 handle_completion_request(
8737 &mut fake_server,
8738 "/file.rs",
8739 Point::new(0, 4),
8740 vec![
8741 (Point::new(0, 4)..Point::new(0, 4), "first_completion"),
8742 (Point::new(0, 4)..Point::new(0, 4), "second_completion"),
8743 ],
8744 )
8745 .await;
8746 editor
8747 .condition(&cx, |editor, _| editor.context_menu_visible())
8748 .await;
8749
8750 let apply_additional_edits = editor.update(cx, |editor, cx| {
8751 editor.move_down(&MoveDown, cx);
8752 let apply_additional_edits = editor
8753 .confirm_completion(&ConfirmCompletion(None), cx)
8754 .unwrap();
8755 assert_eq!(
8756 editor.text(cx),
8757 "
8758 one.second_completion
8759 two
8760 three
8761 "
8762 .unindent()
8763 );
8764 apply_additional_edits
8765 });
8766
8767 handle_resolve_completion_request(
8768 &mut fake_server,
8769 Some((Point::new(2, 5)..Point::new(2, 5), "\nadditional edit")),
8770 )
8771 .await;
8772 apply_additional_edits.await.unwrap();
8773 assert_eq!(
8774 editor.read_with(cx, |editor, cx| editor.text(cx)),
8775 "
8776 one.second_completion
8777 two
8778 three
8779 additional edit
8780 "
8781 .unindent()
8782 );
8783
8784 editor.update(cx, |editor, cx| {
8785 editor.select_ranges(
8786 [
8787 Point::new(1, 3)..Point::new(1, 3),
8788 Point::new(2, 5)..Point::new(2, 5),
8789 ],
8790 None,
8791 cx,
8792 );
8793
8794 editor.handle_input(&Input(" ".to_string()), cx);
8795 assert!(editor.context_menu.is_none());
8796 editor.handle_input(&Input("s".to_string()), cx);
8797 assert!(editor.context_menu.is_none());
8798 });
8799
8800 handle_completion_request(
8801 &mut fake_server,
8802 "/file.rs",
8803 Point::new(2, 7),
8804 vec![
8805 (Point::new(2, 6)..Point::new(2, 7), "fourth_completion"),
8806 (Point::new(2, 6)..Point::new(2, 7), "fifth_completion"),
8807 (Point::new(2, 6)..Point::new(2, 7), "sixth_completion"),
8808 ],
8809 )
8810 .await;
8811 editor
8812 .condition(&cx, |editor, _| editor.context_menu_visible())
8813 .await;
8814
8815 editor.update(cx, |editor, cx| {
8816 editor.handle_input(&Input("i".to_string()), cx);
8817 });
8818
8819 handle_completion_request(
8820 &mut fake_server,
8821 "/file.rs",
8822 Point::new(2, 8),
8823 vec![
8824 (Point::new(2, 6)..Point::new(2, 8), "fourth_completion"),
8825 (Point::new(2, 6)..Point::new(2, 8), "fifth_completion"),
8826 (Point::new(2, 6)..Point::new(2, 8), "sixth_completion"),
8827 ],
8828 )
8829 .await;
8830 editor
8831 .condition(&cx, |editor, _| editor.context_menu_visible())
8832 .await;
8833
8834 let apply_additional_edits = editor.update(cx, |editor, cx| {
8835 let apply_additional_edits = editor
8836 .confirm_completion(&ConfirmCompletion(None), cx)
8837 .unwrap();
8838 assert_eq!(
8839 editor.text(cx),
8840 "
8841 one.second_completion
8842 two sixth_completion
8843 three sixth_completion
8844 additional edit
8845 "
8846 .unindent()
8847 );
8848 apply_additional_edits
8849 });
8850 handle_resolve_completion_request(&mut fake_server, None).await;
8851 apply_additional_edits.await.unwrap();
8852
8853 async fn handle_completion_request(
8854 fake: &mut FakeLanguageServer,
8855 path: &'static str,
8856 position: Point,
8857 completions: Vec<(Range<Point>, &'static str)>,
8858 ) {
8859 fake.handle_request::<lsp::request::Completion, _>(move |params, _| {
8860 assert_eq!(
8861 params.text_document_position.text_document.uri,
8862 lsp::Url::from_file_path(path).unwrap()
8863 );
8864 assert_eq!(
8865 params.text_document_position.position,
8866 lsp::Position::new(position.row, position.column)
8867 );
8868 Some(lsp::CompletionResponse::Array(
8869 completions
8870 .iter()
8871 .map(|(range, new_text)| lsp::CompletionItem {
8872 label: new_text.to_string(),
8873 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
8874 range: lsp::Range::new(
8875 lsp::Position::new(range.start.row, range.start.column),
8876 lsp::Position::new(range.start.row, range.start.column),
8877 ),
8878 new_text: new_text.to_string(),
8879 })),
8880 ..Default::default()
8881 })
8882 .collect(),
8883 ))
8884 })
8885 .next()
8886 .await;
8887 }
8888
8889 async fn handle_resolve_completion_request(
8890 fake: &mut FakeLanguageServer,
8891 edit: Option<(Range<Point>, &'static str)>,
8892 ) {
8893 fake.handle_request::<lsp::request::ResolveCompletionItem, _>(move |_, _| {
8894 lsp::CompletionItem {
8895 additional_text_edits: edit.clone().map(|(range, new_text)| {
8896 vec![lsp::TextEdit::new(
8897 lsp::Range::new(
8898 lsp::Position::new(range.start.row, range.start.column),
8899 lsp::Position::new(range.end.row, range.end.column),
8900 ),
8901 new_text.to_string(),
8902 )]
8903 }),
8904 ..Default::default()
8905 }
8906 })
8907 .next()
8908 .await;
8909 }
8910 }
8911
8912 #[gpui::test]
8913 async fn test_toggle_comment(cx: &mut gpui::TestAppContext) {
8914 cx.update(populate_settings);
8915 let language = Arc::new(Language::new(
8916 LanguageConfig {
8917 line_comment: Some("// ".to_string()),
8918 ..Default::default()
8919 },
8920 Some(tree_sitter_rust::language()),
8921 ));
8922
8923 let text = "
8924 fn a() {
8925 //b();
8926 // c();
8927 // d();
8928 }
8929 "
8930 .unindent();
8931
8932 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8933 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8934 let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
8935
8936 view.update(cx, |editor, cx| {
8937 // If multiple selections intersect a line, the line is only
8938 // toggled once.
8939 editor.select_display_ranges(
8940 &[
8941 DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
8942 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
8943 ],
8944 cx,
8945 );
8946 editor.toggle_comments(&ToggleComments, cx);
8947 assert_eq!(
8948 editor.text(cx),
8949 "
8950 fn a() {
8951 b();
8952 c();
8953 d();
8954 }
8955 "
8956 .unindent()
8957 );
8958
8959 // The comment prefix is inserted at the same column for every line
8960 // in a selection.
8961 editor.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx);
8962 editor.toggle_comments(&ToggleComments, cx);
8963 assert_eq!(
8964 editor.text(cx),
8965 "
8966 fn a() {
8967 // b();
8968 // c();
8969 // d();
8970 }
8971 "
8972 .unindent()
8973 );
8974
8975 // If a selection ends at the beginning of a line, that line is not toggled.
8976 editor.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx);
8977 editor.toggle_comments(&ToggleComments, cx);
8978 assert_eq!(
8979 editor.text(cx),
8980 "
8981 fn a() {
8982 // b();
8983 c();
8984 // d();
8985 }
8986 "
8987 .unindent()
8988 );
8989 });
8990 }
8991
8992 #[gpui::test]
8993 fn test_editing_disjoint_excerpts(cx: &mut gpui::MutableAppContext) {
8994 populate_settings(cx);
8995 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8996 let multibuffer = cx.add_model(|cx| {
8997 let mut multibuffer = MultiBuffer::new(0);
8998 multibuffer.push_excerpts(
8999 buffer.clone(),
9000 [
9001 Point::new(0, 0)..Point::new(0, 4),
9002 Point::new(1, 0)..Point::new(1, 4),
9003 ],
9004 cx,
9005 );
9006 multibuffer
9007 });
9008
9009 assert_eq!(multibuffer.read(cx).read(cx).text(), "aaaa\nbbbb");
9010
9011 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(multibuffer, cx));
9012 view.update(cx, |view, cx| {
9013 assert_eq!(view.text(cx), "aaaa\nbbbb");
9014 view.select_ranges(
9015 [
9016 Point::new(0, 0)..Point::new(0, 0),
9017 Point::new(1, 0)..Point::new(1, 0),
9018 ],
9019 None,
9020 cx,
9021 );
9022
9023 view.handle_input(&Input("X".to_string()), cx);
9024 assert_eq!(view.text(cx), "Xaaaa\nXbbbb");
9025 assert_eq!(
9026 view.selected_ranges(cx),
9027 [
9028 Point::new(0, 1)..Point::new(0, 1),
9029 Point::new(1, 1)..Point::new(1, 1),
9030 ]
9031 )
9032 });
9033 }
9034
9035 #[gpui::test]
9036 fn test_editing_overlapping_excerpts(cx: &mut gpui::MutableAppContext) {
9037 populate_settings(cx);
9038 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
9039 let multibuffer = cx.add_model(|cx| {
9040 let mut multibuffer = MultiBuffer::new(0);
9041 multibuffer.push_excerpts(
9042 buffer,
9043 [
9044 Point::new(0, 0)..Point::new(1, 4),
9045 Point::new(1, 0)..Point::new(2, 4),
9046 ],
9047 cx,
9048 );
9049 multibuffer
9050 });
9051
9052 assert_eq!(
9053 multibuffer.read(cx).read(cx).text(),
9054 "aaaa\nbbbb\nbbbb\ncccc"
9055 );
9056
9057 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(multibuffer, cx));
9058 view.update(cx, |view, cx| {
9059 view.select_ranges(
9060 [
9061 Point::new(1, 1)..Point::new(1, 1),
9062 Point::new(2, 3)..Point::new(2, 3),
9063 ],
9064 None,
9065 cx,
9066 );
9067
9068 view.handle_input(&Input("X".to_string()), cx);
9069 assert_eq!(view.text(cx), "aaaa\nbXbbXb\nbXbbXb\ncccc");
9070 assert_eq!(
9071 view.selected_ranges(cx),
9072 [
9073 Point::new(1, 2)..Point::new(1, 2),
9074 Point::new(2, 5)..Point::new(2, 5),
9075 ]
9076 );
9077
9078 view.newline(&Newline, cx);
9079 assert_eq!(view.text(cx), "aaaa\nbX\nbbX\nb\nbX\nbbX\nb\ncccc");
9080 assert_eq!(
9081 view.selected_ranges(cx),
9082 [
9083 Point::new(2, 0)..Point::new(2, 0),
9084 Point::new(6, 0)..Point::new(6, 0),
9085 ]
9086 );
9087 });
9088 }
9089
9090 #[gpui::test]
9091 fn test_refresh_selections(cx: &mut gpui::MutableAppContext) {
9092 populate_settings(cx);
9093 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
9094 let mut excerpt1_id = None;
9095 let multibuffer = cx.add_model(|cx| {
9096 let mut multibuffer = MultiBuffer::new(0);
9097 excerpt1_id = multibuffer
9098 .push_excerpts(
9099 buffer.clone(),
9100 [
9101 Point::new(0, 0)..Point::new(1, 4),
9102 Point::new(1, 0)..Point::new(2, 4),
9103 ],
9104 cx,
9105 )
9106 .into_iter()
9107 .next();
9108 multibuffer
9109 });
9110 assert_eq!(
9111 multibuffer.read(cx).read(cx).text(),
9112 "aaaa\nbbbb\nbbbb\ncccc"
9113 );
9114 let (_, editor) = cx.add_window(Default::default(), |cx| {
9115 let mut editor = build_editor(multibuffer.clone(), cx);
9116 let snapshot = editor.snapshot(cx);
9117 editor.select_ranges([Point::new(1, 3)..Point::new(1, 3)], None, cx);
9118 editor.begin_selection(Point::new(2, 1).to_display_point(&snapshot), true, 1, cx);
9119 assert_eq!(
9120 editor.selected_ranges(cx),
9121 [
9122 Point::new(1, 3)..Point::new(1, 3),
9123 Point::new(2, 1)..Point::new(2, 1),
9124 ]
9125 );
9126 editor
9127 });
9128
9129 // Refreshing selections is a no-op when excerpts haven't changed.
9130 editor.update(cx, |editor, cx| {
9131 editor.refresh_selections(cx);
9132 assert_eq!(
9133 editor.selected_ranges(cx),
9134 [
9135 Point::new(1, 3)..Point::new(1, 3),
9136 Point::new(2, 1)..Point::new(2, 1),
9137 ]
9138 );
9139 });
9140
9141 multibuffer.update(cx, |multibuffer, cx| {
9142 multibuffer.remove_excerpts([&excerpt1_id.unwrap()], cx);
9143 });
9144 editor.update(cx, |editor, cx| {
9145 // Removing an excerpt causes the first selection to become degenerate.
9146 assert_eq!(
9147 editor.selected_ranges(cx),
9148 [
9149 Point::new(0, 0)..Point::new(0, 0),
9150 Point::new(0, 1)..Point::new(0, 1)
9151 ]
9152 );
9153
9154 // Refreshing selections will relocate the first selection to the original buffer
9155 // location.
9156 editor.refresh_selections(cx);
9157 assert_eq!(
9158 editor.selected_ranges(cx),
9159 [
9160 Point::new(0, 1)..Point::new(0, 1),
9161 Point::new(0, 3)..Point::new(0, 3)
9162 ]
9163 );
9164 assert!(editor.pending_selection.is_some());
9165 });
9166 }
9167
9168 #[gpui::test]
9169 fn test_refresh_selections_while_selecting_with_mouse(cx: &mut gpui::MutableAppContext) {
9170 populate_settings(cx);
9171 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
9172 let mut excerpt1_id = None;
9173 let multibuffer = cx.add_model(|cx| {
9174 let mut multibuffer = MultiBuffer::new(0);
9175 excerpt1_id = multibuffer
9176 .push_excerpts(
9177 buffer.clone(),
9178 [
9179 Point::new(0, 0)..Point::new(1, 4),
9180 Point::new(1, 0)..Point::new(2, 4),
9181 ],
9182 cx,
9183 )
9184 .into_iter()
9185 .next();
9186 multibuffer
9187 });
9188 assert_eq!(
9189 multibuffer.read(cx).read(cx).text(),
9190 "aaaa\nbbbb\nbbbb\ncccc"
9191 );
9192 let (_, editor) = cx.add_window(Default::default(), |cx| {
9193 let mut editor = build_editor(multibuffer.clone(), cx);
9194 let snapshot = editor.snapshot(cx);
9195 editor.begin_selection(Point::new(1, 3).to_display_point(&snapshot), false, 1, cx);
9196 assert_eq!(
9197 editor.selected_ranges(cx),
9198 [Point::new(1, 3)..Point::new(1, 3)]
9199 );
9200 editor
9201 });
9202
9203 multibuffer.update(cx, |multibuffer, cx| {
9204 multibuffer.remove_excerpts([&excerpt1_id.unwrap()], cx);
9205 });
9206 editor.update(cx, |editor, cx| {
9207 assert_eq!(
9208 editor.selected_ranges(cx),
9209 [Point::new(0, 0)..Point::new(0, 0)]
9210 );
9211
9212 // Ensure we don't panic when selections are refreshed and that the pending selection is finalized.
9213 editor.refresh_selections(cx);
9214 assert_eq!(
9215 editor.selected_ranges(cx),
9216 [Point::new(0, 3)..Point::new(0, 3)]
9217 );
9218 assert!(editor.pending_selection.is_some());
9219 });
9220 }
9221
9222 #[gpui::test]
9223 async fn test_extra_newline_insertion(cx: &mut gpui::TestAppContext) {
9224 cx.update(populate_settings);
9225 let language = Arc::new(Language::new(
9226 LanguageConfig {
9227 brackets: vec![
9228 BracketPair {
9229 start: "{".to_string(),
9230 end: "}".to_string(),
9231 close: true,
9232 newline: true,
9233 },
9234 BracketPair {
9235 start: "/* ".to_string(),
9236 end: " */".to_string(),
9237 close: true,
9238 newline: true,
9239 },
9240 ],
9241 ..Default::default()
9242 },
9243 Some(tree_sitter_rust::language()),
9244 ));
9245
9246 let text = concat!(
9247 "{ }\n", // Suppress rustfmt
9248 " x\n", //
9249 " /* */\n", //
9250 "x\n", //
9251 "{{} }\n", //
9252 );
9253
9254 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
9255 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
9256 let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
9257 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
9258 .await;
9259
9260 view.update(cx, |view, cx| {
9261 view.select_display_ranges(
9262 &[
9263 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
9264 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
9265 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
9266 ],
9267 cx,
9268 );
9269 view.newline(&Newline, cx);
9270
9271 assert_eq!(
9272 view.buffer().read(cx).read(cx).text(),
9273 concat!(
9274 "{ \n", // Suppress rustfmt
9275 "\n", //
9276 "}\n", //
9277 " x\n", //
9278 " /* \n", //
9279 " \n", //
9280 " */\n", //
9281 "x\n", //
9282 "{{} \n", //
9283 "}\n", //
9284 )
9285 );
9286 });
9287 }
9288
9289 #[gpui::test]
9290 fn test_highlighted_ranges(cx: &mut gpui::MutableAppContext) {
9291 let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
9292 populate_settings(cx);
9293 let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
9294
9295 editor.update(cx, |editor, cx| {
9296 struct Type1;
9297 struct Type2;
9298
9299 let buffer = buffer.read(cx).snapshot(cx);
9300
9301 let anchor_range = |range: Range<Point>| {
9302 buffer.anchor_after(range.start)..buffer.anchor_after(range.end)
9303 };
9304
9305 editor.highlight_background::<Type1>(
9306 vec![
9307 anchor_range(Point::new(2, 1)..Point::new(2, 3)),
9308 anchor_range(Point::new(4, 2)..Point::new(4, 4)),
9309 anchor_range(Point::new(6, 3)..Point::new(6, 5)),
9310 anchor_range(Point::new(8, 4)..Point::new(8, 6)),
9311 ],
9312 Color::red(),
9313 cx,
9314 );
9315 editor.highlight_background::<Type2>(
9316 vec![
9317 anchor_range(Point::new(3, 2)..Point::new(3, 5)),
9318 anchor_range(Point::new(5, 3)..Point::new(5, 6)),
9319 anchor_range(Point::new(7, 4)..Point::new(7, 7)),
9320 anchor_range(Point::new(9, 5)..Point::new(9, 8)),
9321 ],
9322 Color::green(),
9323 cx,
9324 );
9325
9326 let snapshot = editor.snapshot(cx);
9327 let mut highlighted_ranges = editor.background_highlights_in_range(
9328 anchor_range(Point::new(3, 4)..Point::new(7, 4)),
9329 &snapshot,
9330 );
9331 // Enforce a consistent ordering based on color without relying on the ordering of the
9332 // highlight's `TypeId` which is non-deterministic.
9333 highlighted_ranges.sort_unstable_by_key(|(_, color)| *color);
9334 assert_eq!(
9335 highlighted_ranges,
9336 &[
9337 (
9338 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 5),
9339 Color::green(),
9340 ),
9341 (
9342 DisplayPoint::new(5, 3)..DisplayPoint::new(5, 6),
9343 Color::green(),
9344 ),
9345 (
9346 DisplayPoint::new(4, 2)..DisplayPoint::new(4, 4),
9347 Color::red(),
9348 ),
9349 (
9350 DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
9351 Color::red(),
9352 ),
9353 ]
9354 );
9355 assert_eq!(
9356 editor.background_highlights_in_range(
9357 anchor_range(Point::new(5, 6)..Point::new(6, 4)),
9358 &snapshot,
9359 ),
9360 &[(
9361 DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
9362 Color::red(),
9363 )]
9364 );
9365 });
9366 }
9367
9368 #[gpui::test]
9369 fn test_following(cx: &mut gpui::MutableAppContext) {
9370 let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
9371 populate_settings(cx);
9372
9373 let (_, leader) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
9374 let (_, follower) = cx.add_window(
9375 WindowOptions {
9376 bounds: WindowBounds::Fixed(RectF::from_points(vec2f(0., 0.), vec2f(10., 80.))),
9377 ..Default::default()
9378 },
9379 |cx| build_editor(buffer.clone(), cx),
9380 );
9381
9382 let pending_update = Rc::new(RefCell::new(None));
9383 follower.update(cx, {
9384 let update = pending_update.clone();
9385 |_, cx| {
9386 cx.subscribe(&leader, move |_, leader, event, cx| {
9387 leader
9388 .read(cx)
9389 .add_event_to_update_proto(event, &mut *update.borrow_mut(), cx);
9390 })
9391 .detach();
9392 }
9393 });
9394
9395 // Update the selections only
9396 leader.update(cx, |leader, cx| {
9397 leader.select_ranges([1..1], None, cx);
9398 });
9399 follower.update(cx, |follower, cx| {
9400 follower
9401 .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9402 .unwrap();
9403 });
9404 assert_eq!(follower.read(cx).selected_ranges(cx), vec![1..1]);
9405
9406 // Update the scroll position only
9407 leader.update(cx, |leader, cx| {
9408 leader.set_scroll_position(vec2f(1.5, 3.5), cx);
9409 });
9410 follower.update(cx, |follower, cx| {
9411 follower
9412 .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9413 .unwrap();
9414 });
9415 assert_eq!(
9416 follower.update(cx, |follower, cx| follower.scroll_position(cx)),
9417 vec2f(1.5, 3.5)
9418 );
9419
9420 // Update the selections and scroll position
9421 leader.update(cx, |leader, cx| {
9422 leader.select_ranges([0..0], None, cx);
9423 leader.request_autoscroll(Autoscroll::Newest, cx);
9424 leader.set_scroll_position(vec2f(1.5, 3.5), cx);
9425 });
9426 follower.update(cx, |follower, cx| {
9427 let initial_scroll_position = follower.scroll_position(cx);
9428 follower
9429 .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9430 .unwrap();
9431 assert_eq!(follower.scroll_position(cx), initial_scroll_position);
9432 assert!(follower.autoscroll_request.is_some());
9433 });
9434 assert_eq!(follower.read(cx).selected_ranges(cx), vec![0..0]);
9435
9436 // Creating a pending selection that precedes another selection
9437 leader.update(cx, |leader, cx| {
9438 leader.select_ranges([1..1], None, cx);
9439 leader.begin_selection(DisplayPoint::new(0, 0), true, 1, cx);
9440 });
9441 follower.update(cx, |follower, cx| {
9442 follower
9443 .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9444 .unwrap();
9445 });
9446 assert_eq!(follower.read(cx).selected_ranges(cx), vec![0..0, 1..1]);
9447
9448 // Extend the pending selection so that it surrounds another selection
9449 leader.update(cx, |leader, cx| {
9450 leader.extend_selection(DisplayPoint::new(0, 2), 1, cx);
9451 });
9452 follower.update(cx, |follower, cx| {
9453 follower
9454 .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9455 .unwrap();
9456 });
9457 assert_eq!(follower.read(cx).selected_ranges(cx), vec![0..2]);
9458 }
9459
9460 #[test]
9461 fn test_combine_syntax_and_fuzzy_match_highlights() {
9462 let string = "abcdefghijklmnop";
9463 let syntax_ranges = [
9464 (
9465 0..3,
9466 HighlightStyle {
9467 color: Some(Color::red()),
9468 ..Default::default()
9469 },
9470 ),
9471 (
9472 4..8,
9473 HighlightStyle {
9474 color: Some(Color::green()),
9475 ..Default::default()
9476 },
9477 ),
9478 ];
9479 let match_indices = [4, 6, 7, 8];
9480 assert_eq!(
9481 combine_syntax_and_fuzzy_match_highlights(
9482 &string,
9483 Default::default(),
9484 syntax_ranges.into_iter(),
9485 &match_indices,
9486 ),
9487 &[
9488 (
9489 0..3,
9490 HighlightStyle {
9491 color: Some(Color::red()),
9492 ..Default::default()
9493 },
9494 ),
9495 (
9496 4..5,
9497 HighlightStyle {
9498 color: Some(Color::green()),
9499 weight: Some(fonts::Weight::BOLD),
9500 ..Default::default()
9501 },
9502 ),
9503 (
9504 5..6,
9505 HighlightStyle {
9506 color: Some(Color::green()),
9507 ..Default::default()
9508 },
9509 ),
9510 (
9511 6..8,
9512 HighlightStyle {
9513 color: Some(Color::green()),
9514 weight: Some(fonts::Weight::BOLD),
9515 ..Default::default()
9516 },
9517 ),
9518 (
9519 8..9,
9520 HighlightStyle {
9521 weight: Some(fonts::Weight::BOLD),
9522 ..Default::default()
9523 },
9524 ),
9525 ]
9526 );
9527 }
9528
9529 fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
9530 let point = DisplayPoint::new(row as u32, column as u32);
9531 point..point
9532 }
9533
9534 fn build_editor(buffer: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Editor>) -> Editor {
9535 Editor::new(EditorMode::Full, buffer, None, None, cx)
9536 }
9537
9538 fn populate_settings(cx: &mut gpui::MutableAppContext) {
9539 let settings = Settings::test(cx);
9540 cx.set_global(settings);
9541 }
9542
9543 fn assert_selection_ranges(
9544 marked_text: &str,
9545 selection_marker_pairs: Vec<(char, char)>,
9546 view: &mut Editor,
9547 cx: &mut ViewContext<Editor>,
9548 ) {
9549 let snapshot = view.snapshot(cx).display_snapshot;
9550 let mut marker_chars = Vec::new();
9551 for (start, end) in selection_marker_pairs.iter() {
9552 marker_chars.push(*start);
9553 marker_chars.push(*end);
9554 }
9555 let (_, markers) = marked_text_by(marked_text, marker_chars);
9556 let asserted_ranges: Vec<Range<DisplayPoint>> = selection_marker_pairs
9557 .iter()
9558 .map(|(start, end)| {
9559 let start = markers.get(start).unwrap()[0].to_display_point(&snapshot);
9560 let end = markers.get(end).unwrap()[0].to_display_point(&snapshot);
9561 start..end
9562 })
9563 .collect();
9564 assert_eq!(
9565 view.selected_display_ranges(cx),
9566 &asserted_ranges[..],
9567 "Assert selections are {}",
9568 marked_text
9569 );
9570 }
9571}
9572
9573trait RangeExt<T> {
9574 fn sorted(&self) -> Range<T>;
9575 fn to_inclusive(&self) -> RangeInclusive<T>;
9576}
9577
9578impl<T: Ord + Clone> RangeExt<T> for Range<T> {
9579 fn sorted(&self) -> Self {
9580 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
9581 }
9582
9583 fn to_inclusive(&self) -> RangeInclusive<T> {
9584 self.start.clone()..=self.end.clone()
9585 }
9586}