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