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