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