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