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