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