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