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