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