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