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