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