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