1pub mod display_map;
2mod element;
3pub mod items;
4pub mod movement;
5mod multi_buffer;
6
7#[cfg(test)]
8mod test;
9
10use aho_corasick::AhoCorasick;
11use anyhow::Result;
12use clock::ReplicaId;
13use collections::{BTreeMap, HashMap, HashSet};
14pub use display_map::DisplayPoint;
15use display_map::*;
16pub use element::*;
17use fuzzy::{StringMatch, StringMatchCandidate};
18use gpui::{
19 action,
20 color::Color,
21 elements::*,
22 executor,
23 fonts::{self, HighlightStyle, TextStyle},
24 geometry::vector::{vec2f, Vector2F},
25 keymap::Binding,
26 platform::CursorStyle,
27 text_layout, AppContext, ClipboardItem, Element, ElementBox, Entity, ModelHandle,
28 MutableAppContext, RenderContext, Task, View, ViewContext, WeakModelHandle, WeakViewHandle,
29};
30use items::BufferItemHandle;
31use itertools::Itertools as _;
32use language::{
33 AnchorRangeExt as _, BracketPair, Buffer, Completion, CompletionLabel, Diagnostic,
34 DiagnosticSeverity, Language, Point, Selection, SelectionGoal, TransactionId,
35};
36use multi_buffer::MultiBufferChunks;
37pub use multi_buffer::{
38 char_kind, Anchor, AnchorRangeExt, CharKind, ExcerptId, ExcerptProperties, MultiBuffer,
39 MultiBufferSnapshot, ToOffset, ToPoint,
40};
41use ordered_float::OrderedFloat;
42use postage::watch;
43use serde::{Deserialize, Serialize};
44use smallvec::SmallVec;
45use smol::Timer;
46use snippet::Snippet;
47use std::{
48 any::TypeId,
49 cmp::{self, Ordering, Reverse},
50 iter::{self, FromIterator},
51 mem,
52 ops::{Deref, DerefMut, Range, RangeInclusive, Sub},
53 sync::Arc,
54 time::{Duration, Instant},
55};
56pub use sum_tree::Bias;
57use text::rope::TextDimension;
58use theme::{DiagnosticStyle, EditorStyle};
59use util::{post_inc, ResultExt, TryFutureExt};
60use workspace::{ItemNavHistory, PathOpener, Workspace};
61
62const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
63const MAX_LINE_LEN: usize = 1024;
64const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
65
66action!(Cancel);
67action!(Backspace);
68action!(Delete);
69action!(Input, String);
70action!(Newline);
71action!(Tab);
72action!(Outdent);
73action!(DeleteLine);
74action!(DeleteToPreviousWordBoundary);
75action!(DeleteToNextWordBoundary);
76action!(DeleteToBeginningOfLine);
77action!(DeleteToEndOfLine);
78action!(CutToEndOfLine);
79action!(DuplicateLine);
80action!(MoveLineUp);
81action!(MoveLineDown);
82action!(Cut);
83action!(Copy);
84action!(Paste);
85action!(Undo);
86action!(Redo);
87action!(MoveUp);
88action!(MoveDown);
89action!(MoveLeft);
90action!(MoveRight);
91action!(MoveToPreviousWordBoundary);
92action!(MoveToNextWordBoundary);
93action!(MoveToBeginningOfLine);
94action!(MoveToEndOfLine);
95action!(MoveToBeginning);
96action!(MoveToEnd);
97action!(SelectUp);
98action!(SelectDown);
99action!(SelectLeft);
100action!(SelectRight);
101action!(SelectToPreviousWordBoundary);
102action!(SelectToNextWordBoundary);
103action!(SelectToBeginningOfLine, bool);
104action!(SelectToEndOfLine);
105action!(SelectToBeginning);
106action!(SelectToEnd);
107action!(SelectAll);
108action!(SelectLine);
109action!(SplitSelectionIntoLines);
110action!(AddSelectionAbove);
111action!(AddSelectionBelow);
112action!(SelectNext, bool);
113action!(ToggleComments);
114action!(SelectLargerSyntaxNode);
115action!(SelectSmallerSyntaxNode);
116action!(MoveToEnclosingBracket);
117action!(ShowNextDiagnostic);
118action!(GoToDefinition);
119action!(PageUp);
120action!(PageDown);
121action!(Fold);
122action!(Unfold);
123action!(FoldSelectedRanges);
124action!(Scroll, Vector2F);
125action!(Select, SelectPhase);
126action!(ShowCompletions);
127action!(ConfirmCompletion, Option<usize>);
128
129pub fn init(cx: &mut MutableAppContext, path_openers: &mut Vec<Box<dyn PathOpener>>) {
130 path_openers.push(Box::new(items::BufferOpener));
131 cx.add_bindings(vec![
132 Binding::new("escape", Cancel, Some("Editor")),
133 Binding::new("backspace", Backspace, Some("Editor")),
134 Binding::new("ctrl-h", Backspace, Some("Editor")),
135 Binding::new("delete", Delete, Some("Editor")),
136 Binding::new("ctrl-d", Delete, Some("Editor")),
137 Binding::new("enter", Newline, Some("Editor && mode == full")),
138 Binding::new(
139 "alt-enter",
140 Input("\n".into()),
141 Some("Editor && mode == auto_height"),
142 ),
143 Binding::new(
144 "enter",
145 ConfirmCompletion(None),
146 Some("Editor && completing"),
147 ),
148 Binding::new("tab", Tab, Some("Editor")),
149 Binding::new("tab", ConfirmCompletion(None), Some("Editor && completing")),
150 Binding::new("shift-tab", Outdent, Some("Editor")),
151 Binding::new("ctrl-shift-K", DeleteLine, Some("Editor")),
152 Binding::new(
153 "alt-backspace",
154 DeleteToPreviousWordBoundary,
155 Some("Editor"),
156 ),
157 Binding::new("alt-h", DeleteToPreviousWordBoundary, Some("Editor")),
158 Binding::new("alt-delete", DeleteToNextWordBoundary, Some("Editor")),
159 Binding::new("alt-d", DeleteToNextWordBoundary, Some("Editor")),
160 Binding::new("cmd-backspace", DeleteToBeginningOfLine, Some("Editor")),
161 Binding::new("cmd-delete", DeleteToEndOfLine, Some("Editor")),
162 Binding::new("ctrl-k", CutToEndOfLine, Some("Editor")),
163 Binding::new("cmd-shift-D", DuplicateLine, Some("Editor")),
164 Binding::new("ctrl-cmd-up", MoveLineUp, Some("Editor")),
165 Binding::new("ctrl-cmd-down", MoveLineDown, Some("Editor")),
166 Binding::new("cmd-x", Cut, Some("Editor")),
167 Binding::new("cmd-c", Copy, Some("Editor")),
168 Binding::new("cmd-v", Paste, Some("Editor")),
169 Binding::new("cmd-z", Undo, Some("Editor")),
170 Binding::new("cmd-shift-Z", Redo, Some("Editor")),
171 Binding::new("up", MoveUp, Some("Editor")),
172 Binding::new("down", MoveDown, Some("Editor")),
173 Binding::new("left", MoveLeft, Some("Editor")),
174 Binding::new("right", MoveRight, Some("Editor")),
175 Binding::new("ctrl-p", MoveUp, Some("Editor")),
176 Binding::new("ctrl-n", MoveDown, Some("Editor")),
177 Binding::new("ctrl-b", MoveLeft, Some("Editor")),
178 Binding::new("ctrl-f", MoveRight, Some("Editor")),
179 Binding::new("alt-left", MoveToPreviousWordBoundary, Some("Editor")),
180 Binding::new("alt-b", MoveToPreviousWordBoundary, Some("Editor")),
181 Binding::new("alt-right", MoveToNextWordBoundary, Some("Editor")),
182 Binding::new("alt-f", MoveToNextWordBoundary, Some("Editor")),
183 Binding::new("cmd-left", MoveToBeginningOfLine, Some("Editor")),
184 Binding::new("ctrl-a", MoveToBeginningOfLine, Some("Editor")),
185 Binding::new("cmd-right", MoveToEndOfLine, Some("Editor")),
186 Binding::new("ctrl-e", MoveToEndOfLine, Some("Editor")),
187 Binding::new("cmd-up", MoveToBeginning, Some("Editor")),
188 Binding::new("cmd-down", MoveToEnd, Some("Editor")),
189 Binding::new("shift-up", SelectUp, Some("Editor")),
190 Binding::new("ctrl-shift-P", SelectUp, Some("Editor")),
191 Binding::new("shift-down", SelectDown, Some("Editor")),
192 Binding::new("ctrl-shift-N", SelectDown, Some("Editor")),
193 Binding::new("shift-left", SelectLeft, Some("Editor")),
194 Binding::new("ctrl-shift-B", SelectLeft, Some("Editor")),
195 Binding::new("shift-right", SelectRight, Some("Editor")),
196 Binding::new("ctrl-shift-F", SelectRight, Some("Editor")),
197 Binding::new(
198 "alt-shift-left",
199 SelectToPreviousWordBoundary,
200 Some("Editor"),
201 ),
202 Binding::new("alt-shift-B", SelectToPreviousWordBoundary, Some("Editor")),
203 Binding::new("alt-shift-right", SelectToNextWordBoundary, Some("Editor")),
204 Binding::new("alt-shift-F", SelectToNextWordBoundary, Some("Editor")),
205 Binding::new(
206 "cmd-shift-left",
207 SelectToBeginningOfLine(true),
208 Some("Editor"),
209 ),
210 Binding::new(
211 "ctrl-shift-A",
212 SelectToBeginningOfLine(true),
213 Some("Editor"),
214 ),
215 Binding::new("cmd-shift-right", SelectToEndOfLine, Some("Editor")),
216 Binding::new("ctrl-shift-E", SelectToEndOfLine, Some("Editor")),
217 Binding::new("cmd-shift-up", SelectToBeginning, Some("Editor")),
218 Binding::new("cmd-shift-down", SelectToEnd, Some("Editor")),
219 Binding::new("cmd-a", SelectAll, Some("Editor")),
220 Binding::new("cmd-l", SelectLine, Some("Editor")),
221 Binding::new("cmd-shift-L", SplitSelectionIntoLines, Some("Editor")),
222 Binding::new("cmd-alt-up", AddSelectionAbove, Some("Editor")),
223 Binding::new("cmd-ctrl-p", AddSelectionAbove, Some("Editor")),
224 Binding::new("cmd-alt-down", AddSelectionBelow, Some("Editor")),
225 Binding::new("cmd-ctrl-n", AddSelectionBelow, Some("Editor")),
226 Binding::new("cmd-d", SelectNext(false), Some("Editor")),
227 Binding::new("cmd-k cmd-d", SelectNext(true), Some("Editor")),
228 Binding::new("cmd-/", ToggleComments, Some("Editor")),
229 Binding::new("alt-up", SelectLargerSyntaxNode, Some("Editor")),
230 Binding::new("ctrl-w", SelectLargerSyntaxNode, Some("Editor")),
231 Binding::new("alt-down", SelectSmallerSyntaxNode, Some("Editor")),
232 Binding::new("ctrl-shift-W", SelectSmallerSyntaxNode, Some("Editor")),
233 Binding::new("f8", ShowNextDiagnostic, Some("Editor")),
234 Binding::new("f12", GoToDefinition, Some("Editor")),
235 Binding::new("ctrl-m", MoveToEnclosingBracket, Some("Editor")),
236 Binding::new("pageup", PageUp, Some("Editor")),
237 Binding::new("pagedown", PageDown, Some("Editor")),
238 Binding::new("alt-cmd-[", Fold, Some("Editor")),
239 Binding::new("alt-cmd-]", Unfold, Some("Editor")),
240 Binding::new("alt-cmd-f", FoldSelectedRanges, Some("Editor")),
241 Binding::new("ctrl-space", ShowCompletions, Some("Editor")),
242 ]);
243
244 cx.add_action(Editor::open_new);
245 cx.add_action(|this: &mut Editor, action: &Scroll, cx| this.set_scroll_position(action.0, cx));
246 cx.add_action(Editor::select);
247 cx.add_action(Editor::cancel);
248 cx.add_action(Editor::handle_input);
249 cx.add_action(Editor::newline);
250 cx.add_action(Editor::backspace);
251 cx.add_action(Editor::delete);
252 cx.add_action(Editor::tab);
253 cx.add_action(Editor::outdent);
254 cx.add_action(Editor::delete_line);
255 cx.add_action(Editor::delete_to_previous_word_boundary);
256 cx.add_action(Editor::delete_to_next_word_boundary);
257 cx.add_action(Editor::delete_to_beginning_of_line);
258 cx.add_action(Editor::delete_to_end_of_line);
259 cx.add_action(Editor::cut_to_end_of_line);
260 cx.add_action(Editor::duplicate_line);
261 cx.add_action(Editor::move_line_up);
262 cx.add_action(Editor::move_line_down);
263 cx.add_action(Editor::cut);
264 cx.add_action(Editor::copy);
265 cx.add_action(Editor::paste);
266 cx.add_action(Editor::undo);
267 cx.add_action(Editor::redo);
268 cx.add_action(Editor::move_up);
269 cx.add_action(Editor::move_down);
270 cx.add_action(Editor::move_left);
271 cx.add_action(Editor::move_right);
272 cx.add_action(Editor::move_to_previous_word_boundary);
273 cx.add_action(Editor::move_to_next_word_boundary);
274 cx.add_action(Editor::move_to_beginning_of_line);
275 cx.add_action(Editor::move_to_end_of_line);
276 cx.add_action(Editor::move_to_beginning);
277 cx.add_action(Editor::move_to_end);
278 cx.add_action(Editor::select_up);
279 cx.add_action(Editor::select_down);
280 cx.add_action(Editor::select_left);
281 cx.add_action(Editor::select_right);
282 cx.add_action(Editor::select_to_previous_word_boundary);
283 cx.add_action(Editor::select_to_next_word_boundary);
284 cx.add_action(Editor::select_to_beginning_of_line);
285 cx.add_action(Editor::select_to_end_of_line);
286 cx.add_action(Editor::select_to_beginning);
287 cx.add_action(Editor::select_to_end);
288 cx.add_action(Editor::select_all);
289 cx.add_action(Editor::select_line);
290 cx.add_action(Editor::split_selection_into_lines);
291 cx.add_action(Editor::add_selection_above);
292 cx.add_action(Editor::add_selection_below);
293 cx.add_action(Editor::select_next);
294 cx.add_action(Editor::toggle_comments);
295 cx.add_action(Editor::select_larger_syntax_node);
296 cx.add_action(Editor::select_smaller_syntax_node);
297 cx.add_action(Editor::move_to_enclosing_bracket);
298 cx.add_action(Editor::show_next_diagnostic);
299 cx.add_action(Editor::go_to_definition);
300 cx.add_action(Editor::page_up);
301 cx.add_action(Editor::page_down);
302 cx.add_action(Editor::fold);
303 cx.add_action(Editor::unfold);
304 cx.add_action(Editor::fold_selected_ranges);
305 cx.add_action(Editor::show_completions);
306 cx.add_action(
307 |editor: &mut Editor, &ConfirmCompletion(ix): &ConfirmCompletion, cx| {
308 if let Some(task) = editor.confirm_completion(ix, cx) {
309 task.detach_and_log_err(cx);
310 }
311 },
312 );
313}
314
315trait SelectionExt {
316 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
317 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
318 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
319 fn spanned_rows(&self, include_end_if_at_line_start: bool, map: &DisplaySnapshot)
320 -> Range<u32>;
321}
322
323trait InvalidationRegion {
324 fn ranges(&self) -> &[Range<Anchor>];
325}
326
327#[derive(Clone, Debug)]
328pub enum SelectPhase {
329 Begin {
330 position: DisplayPoint,
331 add: bool,
332 click_count: usize,
333 },
334 BeginColumnar {
335 position: DisplayPoint,
336 overshoot: u32,
337 },
338 Extend {
339 position: DisplayPoint,
340 click_count: usize,
341 },
342 Update {
343 position: DisplayPoint,
344 overshoot: u32,
345 scroll_position: Vector2F,
346 },
347 End,
348}
349
350#[derive(Clone, Debug)]
351enum SelectMode {
352 Character,
353 Word(Range<Anchor>),
354 Line(Range<Anchor>),
355 All,
356}
357
358#[derive(PartialEq, Eq)]
359pub enum Autoscroll {
360 Fit,
361 Center,
362 Newest,
363}
364
365#[derive(Copy, Clone, PartialEq, Eq)]
366pub enum EditorMode {
367 SingleLine,
368 AutoHeight { max_lines: usize },
369 Full,
370}
371
372#[derive(Clone)]
373pub struct EditorSettings {
374 pub tab_size: usize,
375 pub soft_wrap: SoftWrap,
376 pub style: EditorStyle,
377}
378
379#[derive(Clone)]
380pub enum SoftWrap {
381 None,
382 EditorWidth,
383 Column(u32),
384}
385
386type CompletionId = usize;
387
388pub type BuildSettings = Arc<dyn 'static + Send + Sync + Fn(&AppContext) -> EditorSettings>;
389
390pub struct Editor {
391 handle: WeakViewHandle<Self>,
392 buffer: ModelHandle<MultiBuffer>,
393 display_map: ModelHandle<DisplayMap>,
394 next_selection_id: usize,
395 selections: Arc<[Selection<Anchor>]>,
396 pending_selection: Option<PendingSelection>,
397 columnar_selection_tail: Option<Anchor>,
398 add_selections_state: Option<AddSelectionsState>,
399 select_next_state: Option<SelectNextState>,
400 selection_history:
401 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
402 autoclose_stack: InvalidationStack<BracketPairState>,
403 snippet_stack: InvalidationStack<SnippetState>,
404 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
405 active_diagnostics: Option<ActiveDiagnosticGroup>,
406 scroll_position: Vector2F,
407 scroll_top_anchor: Option<Anchor>,
408 autoscroll_request: Option<Autoscroll>,
409 build_settings: BuildSettings,
410 focused: bool,
411 show_local_cursors: bool,
412 blink_epoch: usize,
413 blinking_paused: bool,
414 mode: EditorMode,
415 vertical_scroll_margin: f32,
416 placeholder_text: Option<Arc<str>>,
417 highlighted_rows: Option<Range<u32>>,
418 highlighted_ranges: BTreeMap<TypeId, (Color, Vec<Range<Anchor>>)>,
419 nav_history: Option<ItemNavHistory>,
420 completion_state: Option<CompletionState>,
421 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
422 next_completion_id: CompletionId,
423}
424
425pub struct EditorSnapshot {
426 pub mode: EditorMode,
427 pub display_snapshot: DisplaySnapshot,
428 pub placeholder_text: Option<Arc<str>>,
429 is_focused: bool,
430 scroll_position: Vector2F,
431 scroll_top_anchor: Option<Anchor>,
432}
433
434struct PendingSelection {
435 selection: Selection<Anchor>,
436 mode: SelectMode,
437}
438
439struct AddSelectionsState {
440 above: bool,
441 stack: Vec<usize>,
442}
443
444struct SelectNextState {
445 query: AhoCorasick,
446 wordwise: bool,
447 done: bool,
448}
449
450struct BracketPairState {
451 ranges: Vec<Range<Anchor>>,
452 pair: BracketPair,
453}
454
455struct SnippetState {
456 ranges: Vec<Vec<Range<Anchor>>>,
457 active_index: usize,
458}
459
460struct InvalidationStack<T>(Vec<T>);
461
462struct CompletionState {
463 id: CompletionId,
464 initial_position: Anchor,
465 completions: Arc<[Completion<Anchor>]>,
466 match_candidates: Vec<StringMatchCandidate>,
467 matches: Arc<[StringMatch]>,
468 selected_item: usize,
469 list: UniformListState,
470}
471
472impl CompletionState {
473 pub async fn filter(&mut self, query: Option<&str>, executor: Arc<executor::Background>) {
474 let mut matches = if let Some(query) = query {
475 fuzzy::match_strings(
476 &self.match_candidates,
477 query,
478 false,
479 100,
480 &Default::default(),
481 executor,
482 )
483 .await
484 } else {
485 self.match_candidates
486 .iter()
487 .enumerate()
488 .map(|(candidate_id, candidate)| StringMatch {
489 candidate_id,
490 score: Default::default(),
491 positions: Default::default(),
492 string: candidate.string.clone(),
493 })
494 .collect()
495 };
496 matches.sort_unstable_by_key(|mat| {
497 (
498 Reverse(OrderedFloat(mat.score)),
499 self.completions[mat.candidate_id].sort_key(),
500 )
501 });
502
503 for mat in &mut matches {
504 let filter_start = self.completions[mat.candidate_id].label.filter_range.start;
505 for position in &mut mat.positions {
506 *position += filter_start;
507 }
508 }
509
510 self.matches = matches.into();
511 }
512}
513
514#[derive(Debug)]
515struct ActiveDiagnosticGroup {
516 primary_range: Range<Anchor>,
517 primary_message: String,
518 blocks: HashMap<BlockId, Diagnostic>,
519 is_valid: bool,
520}
521
522#[derive(Serialize, Deserialize)]
523struct ClipboardSelection {
524 len: usize,
525 is_entire_line: bool,
526}
527
528pub struct NavigationData {
529 anchor: Anchor,
530 offset: usize,
531}
532
533impl Editor {
534 pub fn single_line(build_settings: BuildSettings, cx: &mut ViewContext<Self>) -> Self {
535 let buffer = cx.add_model(|cx| Buffer::new(0, String::new(), cx));
536 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
537 let mut view = Self::for_buffer(buffer, build_settings, cx);
538 view.mode = EditorMode::SingleLine;
539 view
540 }
541
542 pub fn auto_height(
543 max_lines: usize,
544 build_settings: BuildSettings,
545 cx: &mut ViewContext<Self>,
546 ) -> Self {
547 let buffer = cx.add_model(|cx| Buffer::new(0, String::new(), cx));
548 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
549 let mut view = Self::for_buffer(buffer, build_settings, cx);
550 view.mode = EditorMode::AutoHeight { max_lines };
551 view
552 }
553
554 pub fn for_buffer(
555 buffer: ModelHandle<MultiBuffer>,
556 build_settings: BuildSettings,
557 cx: &mut ViewContext<Self>,
558 ) -> Self {
559 Self::new(buffer, build_settings, cx)
560 }
561
562 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
563 let mut clone = Self::new(self.buffer.clone(), self.build_settings.clone(), cx);
564 clone.scroll_position = self.scroll_position;
565 clone.scroll_top_anchor = self.scroll_top_anchor.clone();
566 clone.nav_history = self
567 .nav_history
568 .as_ref()
569 .map(|nav_history| ItemNavHistory::new(nav_history.history(), &cx.handle()));
570 clone
571 }
572
573 pub fn new(
574 buffer: ModelHandle<MultiBuffer>,
575 build_settings: BuildSettings,
576 cx: &mut ViewContext<Self>,
577 ) -> Self {
578 let settings = build_settings(cx);
579 let display_map = cx.add_model(|cx| {
580 DisplayMap::new(
581 buffer.clone(),
582 settings.tab_size,
583 settings.style.text.font_id,
584 settings.style.text.font_size,
585 None,
586 cx,
587 )
588 });
589 cx.observe(&buffer, Self::on_buffer_changed).detach();
590 cx.subscribe(&buffer, Self::on_buffer_event).detach();
591 cx.observe(&display_map, Self::on_display_map_changed)
592 .detach();
593
594 let mut this = Self {
595 handle: cx.weak_handle(),
596 buffer,
597 display_map,
598 selections: Arc::from([]),
599 pending_selection: None,
600 columnar_selection_tail: None,
601 next_selection_id: 0,
602 add_selections_state: None,
603 select_next_state: None,
604 selection_history: Default::default(),
605 autoclose_stack: Default::default(),
606 snippet_stack: Default::default(),
607 select_larger_syntax_node_stack: Vec::new(),
608 active_diagnostics: None,
609 build_settings,
610 scroll_position: Vector2F::zero(),
611 scroll_top_anchor: None,
612 autoscroll_request: None,
613 focused: false,
614 show_local_cursors: false,
615 blink_epoch: 0,
616 blinking_paused: false,
617 mode: EditorMode::Full,
618 vertical_scroll_margin: 3.0,
619 placeholder_text: None,
620 highlighted_rows: None,
621 highlighted_ranges: Default::default(),
622 nav_history: None,
623 completion_state: None,
624 completion_tasks: Default::default(),
625 next_completion_id: 0,
626 };
627 let selection = Selection {
628 id: post_inc(&mut this.next_selection_id),
629 start: 0,
630 end: 0,
631 reversed: false,
632 goal: SelectionGoal::None,
633 };
634 this.update_selections(vec![selection], None, cx);
635 this
636 }
637
638 pub fn open_new(
639 workspace: &mut Workspace,
640 _: &workspace::OpenNew,
641 cx: &mut ViewContext<Workspace>,
642 ) {
643 let buffer = cx
644 .add_model(|cx| Buffer::new(0, "", cx).with_language(language::PLAIN_TEXT.clone(), cx));
645 workspace.open_item(BufferItemHandle(buffer), cx);
646 }
647
648 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
649 self.buffer.read(cx).replica_id()
650 }
651
652 pub fn buffer(&self) -> &ModelHandle<MultiBuffer> {
653 &self.buffer
654 }
655
656 pub fn title(&self, cx: &AppContext) -> String {
657 let filename = self
658 .buffer()
659 .read(cx)
660 .file(cx)
661 .map(|file| file.file_name(cx));
662 if let Some(name) = filename {
663 name.to_string_lossy().into()
664 } else {
665 "untitled".into()
666 }
667 }
668
669 pub fn snapshot(&mut self, cx: &mut MutableAppContext) -> EditorSnapshot {
670 EditorSnapshot {
671 mode: self.mode,
672 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
673 scroll_position: self.scroll_position,
674 scroll_top_anchor: self.scroll_top_anchor.clone(),
675 placeholder_text: self.placeholder_text.clone(),
676 is_focused: self
677 .handle
678 .upgrade(cx)
679 .map_or(false, |handle| handle.is_focused(cx)),
680 }
681 }
682
683 pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc<Language>> {
684 self.buffer.read(cx).language(cx)
685 }
686
687 pub fn set_placeholder_text(
688 &mut self,
689 placeholder_text: impl Into<Arc<str>>,
690 cx: &mut ViewContext<Self>,
691 ) {
692 self.placeholder_text = Some(placeholder_text.into());
693 cx.notify();
694 }
695
696 pub fn set_vertical_scroll_margin(&mut self, margin_rows: usize, cx: &mut ViewContext<Self>) {
697 self.vertical_scroll_margin = margin_rows as f32;
698 cx.notify();
699 }
700
701 pub fn set_scroll_position(&mut self, scroll_position: Vector2F, cx: &mut ViewContext<Self>) {
702 let map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
703
704 if scroll_position.y() == 0. {
705 self.scroll_top_anchor = None;
706 self.scroll_position = scroll_position;
707 } else {
708 let scroll_top_buffer_offset =
709 DisplayPoint::new(scroll_position.y() as u32, 0).to_offset(&map, Bias::Right);
710 let anchor = map
711 .buffer_snapshot
712 .anchor_at(scroll_top_buffer_offset, Bias::Right);
713 self.scroll_position = vec2f(
714 scroll_position.x(),
715 scroll_position.y() - anchor.to_display_point(&map).row() as f32,
716 );
717 self.scroll_top_anchor = Some(anchor);
718 }
719
720 cx.notify();
721 }
722
723 pub fn scroll_position(&self, cx: &mut ViewContext<Self>) -> Vector2F {
724 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
725 compute_scroll_position(&display_map, self.scroll_position, &self.scroll_top_anchor)
726 }
727
728 pub fn clamp_scroll_left(&mut self, max: f32) -> bool {
729 if max < self.scroll_position.x() {
730 self.scroll_position.set_x(max);
731 true
732 } else {
733 false
734 }
735 }
736
737 pub fn autoscroll_vertically(
738 &mut self,
739 viewport_height: f32,
740 line_height: f32,
741 cx: &mut ViewContext<Self>,
742 ) -> bool {
743 let visible_lines = viewport_height / line_height;
744 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
745 let mut scroll_position =
746 compute_scroll_position(&display_map, self.scroll_position, &self.scroll_top_anchor);
747 let max_scroll_top = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
748 (display_map.max_point().row() as f32 - visible_lines + 1.).max(0.)
749 } else {
750 display_map.max_point().row().saturating_sub(1) as f32
751 };
752 if scroll_position.y() > max_scroll_top {
753 scroll_position.set_y(max_scroll_top);
754 self.set_scroll_position(scroll_position, cx);
755 }
756
757 let autoscroll = if let Some(autoscroll) = self.autoscroll_request.take() {
758 autoscroll
759 } else {
760 return false;
761 };
762
763 let first_cursor_top;
764 let last_cursor_bottom;
765 if let Some(highlighted_rows) = &self.highlighted_rows {
766 first_cursor_top = highlighted_rows.start as f32;
767 last_cursor_bottom = first_cursor_top + 1.;
768 } else if autoscroll == Autoscroll::Newest {
769 let newest_selection = self.newest_selection::<Point>(&display_map.buffer_snapshot);
770 first_cursor_top = newest_selection.head().to_display_point(&display_map).row() as f32;
771 last_cursor_bottom = first_cursor_top + 1.;
772 } else {
773 let selections = self.local_selections::<Point>(cx);
774 first_cursor_top = selections
775 .first()
776 .unwrap()
777 .head()
778 .to_display_point(&display_map)
779 .row() as f32;
780 last_cursor_bottom = selections
781 .last()
782 .unwrap()
783 .head()
784 .to_display_point(&display_map)
785 .row() as f32
786 + 1.0;
787 }
788
789 let margin = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
790 0.
791 } else {
792 ((visible_lines - (last_cursor_bottom - first_cursor_top)) / 2.0).floor()
793 };
794 if margin < 0.0 {
795 return false;
796 }
797
798 match autoscroll {
799 Autoscroll::Fit | Autoscroll::Newest => {
800 let margin = margin.min(self.vertical_scroll_margin);
801 let target_top = (first_cursor_top - margin).max(0.0);
802 let target_bottom = last_cursor_bottom + margin;
803 let start_row = scroll_position.y();
804 let end_row = start_row + visible_lines;
805
806 if target_top < start_row {
807 scroll_position.set_y(target_top);
808 self.set_scroll_position(scroll_position, cx);
809 } else if target_bottom >= end_row {
810 scroll_position.set_y(target_bottom - visible_lines);
811 self.set_scroll_position(scroll_position, cx);
812 }
813 }
814 Autoscroll::Center => {
815 scroll_position.set_y((first_cursor_top - margin).max(0.0));
816 self.set_scroll_position(scroll_position, cx);
817 }
818 }
819
820 true
821 }
822
823 pub fn autoscroll_horizontally(
824 &mut self,
825 start_row: u32,
826 viewport_width: f32,
827 scroll_width: f32,
828 max_glyph_width: f32,
829 layouts: &[text_layout::Line],
830 cx: &mut ViewContext<Self>,
831 ) -> bool {
832 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
833 let selections = self.local_selections::<Point>(cx);
834
835 let mut target_left;
836 let mut target_right;
837
838 if self.highlighted_rows.is_some() {
839 target_left = 0.0_f32;
840 target_right = 0.0_f32;
841 } else {
842 target_left = std::f32::INFINITY;
843 target_right = 0.0_f32;
844 for selection in selections {
845 let head = selection.head().to_display_point(&display_map);
846 if head.row() >= start_row && head.row() < start_row + layouts.len() as u32 {
847 let start_column = head.column().saturating_sub(3);
848 let end_column = cmp::min(display_map.line_len(head.row()), head.column() + 3);
849 target_left = target_left.min(
850 layouts[(head.row() - start_row) as usize]
851 .x_for_index(start_column as usize),
852 );
853 target_right = target_right.max(
854 layouts[(head.row() - start_row) as usize].x_for_index(end_column as usize)
855 + max_glyph_width,
856 );
857 }
858 }
859 }
860
861 target_right = target_right.min(scroll_width);
862
863 if target_right - target_left > viewport_width {
864 return false;
865 }
866
867 let scroll_left = self.scroll_position.x() * max_glyph_width;
868 let scroll_right = scroll_left + viewport_width;
869
870 if target_left < scroll_left {
871 self.scroll_position.set_x(target_left / max_glyph_width);
872 true
873 } else if target_right > scroll_right {
874 self.scroll_position
875 .set_x((target_right - viewport_width) / max_glyph_width);
876 true
877 } else {
878 false
879 }
880 }
881
882 fn select(&mut self, Select(phase): &Select, cx: &mut ViewContext<Self>) {
883 self.hide_completions(cx);
884
885 match phase {
886 SelectPhase::Begin {
887 position,
888 add,
889 click_count,
890 } => self.begin_selection(*position, *add, *click_count, cx),
891 SelectPhase::BeginColumnar {
892 position,
893 overshoot,
894 } => self.begin_columnar_selection(*position, *overshoot, cx),
895 SelectPhase::Extend {
896 position,
897 click_count,
898 } => self.extend_selection(*position, *click_count, cx),
899 SelectPhase::Update {
900 position,
901 overshoot,
902 scroll_position,
903 } => self.update_selection(*position, *overshoot, *scroll_position, cx),
904 SelectPhase::End => self.end_selection(cx),
905 }
906 }
907
908 fn extend_selection(
909 &mut self,
910 position: DisplayPoint,
911 click_count: usize,
912 cx: &mut ViewContext<Self>,
913 ) {
914 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
915 let tail = self
916 .newest_selection::<usize>(&display_map.buffer_snapshot)
917 .tail();
918 self.begin_selection(position, false, click_count, cx);
919
920 let position = position.to_offset(&display_map, Bias::Left);
921 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
922 let pending = self.pending_selection.as_mut().unwrap();
923
924 if position >= tail {
925 pending.selection.start = tail_anchor.clone();
926 } else {
927 pending.selection.end = tail_anchor.clone();
928 pending.selection.reversed = true;
929 }
930
931 match &mut pending.mode {
932 SelectMode::Word(range) | SelectMode::Line(range) => {
933 *range = tail_anchor.clone()..tail_anchor
934 }
935 _ => {}
936 }
937 }
938
939 fn begin_selection(
940 &mut self,
941 position: DisplayPoint,
942 add: bool,
943 click_count: usize,
944 cx: &mut ViewContext<Self>,
945 ) {
946 if !self.focused {
947 cx.focus_self();
948 cx.emit(Event::Activate);
949 }
950
951 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
952 let buffer = &display_map.buffer_snapshot;
953 let newest_selection = self.newest_anchor_selection().unwrap().clone();
954
955 let start;
956 let end;
957 let mode;
958 match click_count {
959 1 => {
960 start = buffer.anchor_before(position.to_point(&display_map));
961 end = start.clone();
962 mode = SelectMode::Character;
963 }
964 2 => {
965 let range = movement::surrounding_word(&display_map, position);
966 start = buffer.anchor_before(range.start.to_point(&display_map));
967 end = buffer.anchor_before(range.end.to_point(&display_map));
968 mode = SelectMode::Word(start.clone()..end.clone());
969 }
970 3 => {
971 let position = display_map
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(toggle_indent): &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, *toggle_indent);
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);
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(&mut self, _: &SelectToEndOfLine, cx: &mut ViewContext<Self>) {
2971 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2972 let mut selections = self.local_selections::<Point>(cx);
2973 for selection in &mut selections {
2974 let head = selection.head().to_display_point(&display_map);
2975 let new_head = movement::line_end(&display_map, head);
2976 selection.set_head(new_head.to_point(&display_map));
2977 selection.goal = SelectionGoal::None;
2978 }
2979 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2980 }
2981
2982 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
2983 self.start_transaction(cx);
2984 self.select_to_end_of_line(&SelectToEndOfLine, cx);
2985 self.delete(&Delete, cx);
2986 self.end_transaction(cx);
2987 }
2988
2989 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
2990 self.start_transaction(cx);
2991 self.select_to_end_of_line(&SelectToEndOfLine, cx);
2992 self.cut(&Cut, cx);
2993 self.end_transaction(cx);
2994 }
2995
2996 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
2997 if matches!(self.mode, EditorMode::SingleLine) {
2998 cx.propagate_action();
2999 return;
3000 }
3001
3002 let selection = Selection {
3003 id: post_inc(&mut self.next_selection_id),
3004 start: 0,
3005 end: 0,
3006 reversed: false,
3007 goal: SelectionGoal::None,
3008 };
3009 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
3010 }
3011
3012 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
3013 let mut selection = self.local_selections::<Point>(cx).last().unwrap().clone();
3014 selection.set_head(Point::zero());
3015 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
3016 }
3017
3018 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
3019 if matches!(self.mode, EditorMode::SingleLine) {
3020 cx.propagate_action();
3021 return;
3022 }
3023
3024 let cursor = self.buffer.read(cx).read(cx).len();
3025 let selection = Selection {
3026 id: post_inc(&mut self.next_selection_id),
3027 start: cursor,
3028 end: cursor,
3029 reversed: false,
3030 goal: SelectionGoal::None,
3031 };
3032 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
3033 }
3034
3035 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
3036 self.nav_history = nav_history;
3037 }
3038
3039 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
3040 self.nav_history.as_ref()
3041 }
3042
3043 fn push_to_nav_history(
3044 &self,
3045 position: Anchor,
3046 new_position: Option<Point>,
3047 cx: &mut ViewContext<Self>,
3048 ) {
3049 if let Some(nav_history) = &self.nav_history {
3050 let buffer = self.buffer.read(cx).read(cx);
3051 let offset = position.to_offset(&buffer);
3052 let point = position.to_point(&buffer);
3053 drop(buffer);
3054
3055 if let Some(new_position) = new_position {
3056 let row_delta = (new_position.row as i64 - point.row as i64).abs();
3057 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
3058 return;
3059 }
3060 }
3061
3062 nav_history.push(Some(NavigationData {
3063 anchor: position,
3064 offset,
3065 }));
3066 }
3067 }
3068
3069 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
3070 let mut selection = self.local_selections::<usize>(cx).first().unwrap().clone();
3071 selection.set_head(self.buffer.read(cx).read(cx).len());
3072 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
3073 }
3074
3075 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
3076 let selection = Selection {
3077 id: post_inc(&mut self.next_selection_id),
3078 start: 0,
3079 end: self.buffer.read(cx).read(cx).len(),
3080 reversed: false,
3081 goal: SelectionGoal::None,
3082 };
3083 self.update_selections(vec![selection], None, cx);
3084 }
3085
3086 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
3087 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3088 let mut selections = self.local_selections::<Point>(cx);
3089 let max_point = display_map.buffer_snapshot.max_point();
3090 for selection in &mut selections {
3091 let rows = selection.spanned_rows(true, &display_map);
3092 selection.start = Point::new(rows.start, 0);
3093 selection.end = cmp::min(max_point, Point::new(rows.end, 0));
3094 selection.reversed = false;
3095 }
3096 self.update_selections(selections, Some(Autoscroll::Fit), cx);
3097 }
3098
3099 pub fn split_selection_into_lines(
3100 &mut self,
3101 _: &SplitSelectionIntoLines,
3102 cx: &mut ViewContext<Self>,
3103 ) {
3104 let mut to_unfold = Vec::new();
3105 let mut new_selections = Vec::new();
3106 {
3107 let selections = self.local_selections::<Point>(cx);
3108 let buffer = self.buffer.read(cx).read(cx);
3109 for selection in selections {
3110 for row in selection.start.row..selection.end.row {
3111 let cursor = Point::new(row, buffer.line_len(row));
3112 new_selections.push(Selection {
3113 id: post_inc(&mut self.next_selection_id),
3114 start: cursor,
3115 end: cursor,
3116 reversed: false,
3117 goal: SelectionGoal::None,
3118 });
3119 }
3120 new_selections.push(Selection {
3121 id: selection.id,
3122 start: selection.end,
3123 end: selection.end,
3124 reversed: false,
3125 goal: SelectionGoal::None,
3126 });
3127 to_unfold.push(selection.start..selection.end);
3128 }
3129 }
3130 self.unfold_ranges(to_unfold, cx);
3131 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
3132 }
3133
3134 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
3135 self.add_selection(true, cx);
3136 }
3137
3138 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
3139 self.add_selection(false, cx);
3140 }
3141
3142 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
3143 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3144 let mut selections = self.local_selections::<Point>(cx);
3145 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
3146 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
3147 let range = oldest_selection.display_range(&display_map).sorted();
3148 let columns = cmp::min(range.start.column(), range.end.column())
3149 ..cmp::max(range.start.column(), range.end.column());
3150
3151 selections.clear();
3152 let mut stack = Vec::new();
3153 for row in range.start.row()..=range.end.row() {
3154 if let Some(selection) = self.build_columnar_selection(
3155 &display_map,
3156 row,
3157 &columns,
3158 oldest_selection.reversed,
3159 ) {
3160 stack.push(selection.id);
3161 selections.push(selection);
3162 }
3163 }
3164
3165 if above {
3166 stack.reverse();
3167 }
3168
3169 AddSelectionsState { above, stack }
3170 });
3171
3172 let last_added_selection = *state.stack.last().unwrap();
3173 let mut new_selections = Vec::new();
3174 if above == state.above {
3175 let end_row = if above {
3176 0
3177 } else {
3178 display_map.max_point().row()
3179 };
3180
3181 'outer: for selection in selections {
3182 if selection.id == last_added_selection {
3183 let range = selection.display_range(&display_map).sorted();
3184 debug_assert_eq!(range.start.row(), range.end.row());
3185 let mut row = range.start.row();
3186 let columns = if let SelectionGoal::ColumnRange { start, end } = selection.goal
3187 {
3188 start..end
3189 } else {
3190 cmp::min(range.start.column(), range.end.column())
3191 ..cmp::max(range.start.column(), range.end.column())
3192 };
3193
3194 while row != end_row {
3195 if above {
3196 row -= 1;
3197 } else {
3198 row += 1;
3199 }
3200
3201 if let Some(new_selection) = self.build_columnar_selection(
3202 &display_map,
3203 row,
3204 &columns,
3205 selection.reversed,
3206 ) {
3207 state.stack.push(new_selection.id);
3208 if above {
3209 new_selections.push(new_selection);
3210 new_selections.push(selection);
3211 } else {
3212 new_selections.push(selection);
3213 new_selections.push(new_selection);
3214 }
3215
3216 continue 'outer;
3217 }
3218 }
3219 }
3220
3221 new_selections.push(selection);
3222 }
3223 } else {
3224 new_selections = selections;
3225 new_selections.retain(|s| s.id != last_added_selection);
3226 state.stack.pop();
3227 }
3228
3229 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
3230 if state.stack.len() > 1 {
3231 self.add_selections_state = Some(state);
3232 }
3233 }
3234
3235 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) {
3236 let replace_newest = action.0;
3237 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3238 let buffer = &display_map.buffer_snapshot;
3239 let mut selections = self.local_selections::<usize>(cx);
3240 if let Some(mut select_next_state) = self.select_next_state.take() {
3241 let query = &select_next_state.query;
3242 if !select_next_state.done {
3243 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
3244 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
3245 let mut next_selected_range = None;
3246
3247 let bytes_after_last_selection =
3248 buffer.bytes_in_range(last_selection.end..buffer.len());
3249 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
3250 let query_matches = query
3251 .stream_find_iter(bytes_after_last_selection)
3252 .map(|result| (last_selection.end, result))
3253 .chain(
3254 query
3255 .stream_find_iter(bytes_before_first_selection)
3256 .map(|result| (0, result)),
3257 );
3258 for (start_offset, query_match) in query_matches {
3259 let query_match = query_match.unwrap(); // can only fail due to I/O
3260 let offset_range =
3261 start_offset + query_match.start()..start_offset + query_match.end();
3262 let display_range = offset_range.start.to_display_point(&display_map)
3263 ..offset_range.end.to_display_point(&display_map);
3264
3265 if !select_next_state.wordwise
3266 || (!movement::is_inside_word(&display_map, display_range.start)
3267 && !movement::is_inside_word(&display_map, display_range.end))
3268 {
3269 next_selected_range = Some(offset_range);
3270 break;
3271 }
3272 }
3273
3274 if let Some(next_selected_range) = next_selected_range {
3275 if replace_newest {
3276 if let Some(newest_id) =
3277 selections.iter().max_by_key(|s| s.id).map(|s| s.id)
3278 {
3279 selections.retain(|s| s.id != newest_id);
3280 }
3281 }
3282 selections.push(Selection {
3283 id: post_inc(&mut self.next_selection_id),
3284 start: next_selected_range.start,
3285 end: next_selected_range.end,
3286 reversed: false,
3287 goal: SelectionGoal::None,
3288 });
3289 self.update_selections(selections, Some(Autoscroll::Newest), cx);
3290 } else {
3291 select_next_state.done = true;
3292 }
3293 }
3294
3295 self.select_next_state = Some(select_next_state);
3296 } else if selections.len() == 1 {
3297 let selection = selections.last_mut().unwrap();
3298 if selection.start == selection.end {
3299 let word_range = movement::surrounding_word(
3300 &display_map,
3301 selection.start.to_display_point(&display_map),
3302 );
3303 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
3304 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
3305 selection.goal = SelectionGoal::None;
3306 selection.reversed = false;
3307
3308 let query = buffer
3309 .text_for_range(selection.start..selection.end)
3310 .collect::<String>();
3311 let select_state = SelectNextState {
3312 query: AhoCorasick::new_auto_configured(&[query]),
3313 wordwise: true,
3314 done: false,
3315 };
3316 self.update_selections(selections, Some(Autoscroll::Newest), cx);
3317 self.select_next_state = Some(select_state);
3318 } else {
3319 let query = buffer
3320 .text_for_range(selection.start..selection.end)
3321 .collect::<String>();
3322 self.select_next_state = Some(SelectNextState {
3323 query: AhoCorasick::new_auto_configured(&[query]),
3324 wordwise: false,
3325 done: false,
3326 });
3327 self.select_next(action, cx);
3328 }
3329 }
3330 }
3331
3332 pub fn toggle_comments(&mut self, _: &ToggleComments, cx: &mut ViewContext<Self>) {
3333 // Get the line comment prefix. Split its trailing whitespace into a separate string,
3334 // as that portion won't be used for detecting if a line is a comment.
3335 let full_comment_prefix =
3336 if let Some(prefix) = self.language(cx).and_then(|l| l.line_comment_prefix()) {
3337 prefix.to_string()
3338 } else {
3339 return;
3340 };
3341 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
3342 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
3343
3344 self.start_transaction(cx);
3345 let mut selections = self.local_selections::<Point>(cx);
3346 let mut all_selection_lines_are_comments = true;
3347 let mut edit_ranges = Vec::new();
3348 let mut last_toggled_row = None;
3349 self.buffer.update(cx, |buffer, cx| {
3350 for selection in &mut selections {
3351 edit_ranges.clear();
3352 let snapshot = buffer.snapshot(cx);
3353
3354 let end_row =
3355 if selection.end.row > selection.start.row && selection.end.column == 0 {
3356 selection.end.row
3357 } else {
3358 selection.end.row + 1
3359 };
3360
3361 for row in selection.start.row..end_row {
3362 // If multiple selections contain a given row, avoid processing that
3363 // row more than once.
3364 if last_toggled_row == Some(row) {
3365 continue;
3366 } else {
3367 last_toggled_row = Some(row);
3368 }
3369
3370 if snapshot.is_line_blank(row) {
3371 continue;
3372 }
3373
3374 let start = Point::new(row, snapshot.indent_column_for_line(row));
3375 let mut line_bytes = snapshot
3376 .bytes_in_range(start..snapshot.max_point())
3377 .flatten()
3378 .copied();
3379
3380 // If this line currently begins with the line comment prefix, then record
3381 // the range containing the prefix.
3382 if all_selection_lines_are_comments
3383 && line_bytes
3384 .by_ref()
3385 .take(comment_prefix.len())
3386 .eq(comment_prefix.bytes())
3387 {
3388 // Include any whitespace that matches the comment prefix.
3389 let matching_whitespace_len = line_bytes
3390 .zip(comment_prefix_whitespace.bytes())
3391 .take_while(|(a, b)| a == b)
3392 .count() as u32;
3393 let end = Point::new(
3394 row,
3395 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
3396 );
3397 edit_ranges.push(start..end);
3398 }
3399 // If this line does not begin with the line comment prefix, then record
3400 // the position where the prefix should be inserted.
3401 else {
3402 all_selection_lines_are_comments = false;
3403 edit_ranges.push(start..start);
3404 }
3405 }
3406
3407 if !edit_ranges.is_empty() {
3408 if all_selection_lines_are_comments {
3409 buffer.edit(edit_ranges.iter().cloned(), "", cx);
3410 } else {
3411 let min_column = edit_ranges.iter().map(|r| r.start.column).min().unwrap();
3412 let edit_ranges = edit_ranges.iter().map(|range| {
3413 let position = Point::new(range.start.row, min_column);
3414 position..position
3415 });
3416 buffer.edit(edit_ranges, &full_comment_prefix, cx);
3417 }
3418 }
3419 }
3420 });
3421
3422 self.update_selections(
3423 self.local_selections::<usize>(cx),
3424 Some(Autoscroll::Fit),
3425 cx,
3426 );
3427 self.end_transaction(cx);
3428 }
3429
3430 pub fn select_larger_syntax_node(
3431 &mut self,
3432 _: &SelectLargerSyntaxNode,
3433 cx: &mut ViewContext<Self>,
3434 ) {
3435 let old_selections = self.local_selections::<usize>(cx).into_boxed_slice();
3436 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3437 let buffer = self.buffer.read(cx).snapshot(cx);
3438
3439 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
3440 let mut selected_larger_node = false;
3441 let new_selections = old_selections
3442 .iter()
3443 .map(|selection| {
3444 let old_range = selection.start..selection.end;
3445 let mut new_range = old_range.clone();
3446 while let Some(containing_range) =
3447 buffer.range_for_syntax_ancestor(new_range.clone())
3448 {
3449 new_range = containing_range;
3450 if !display_map.intersects_fold(new_range.start)
3451 && !display_map.intersects_fold(new_range.end)
3452 {
3453 break;
3454 }
3455 }
3456
3457 selected_larger_node |= new_range != old_range;
3458 Selection {
3459 id: selection.id,
3460 start: new_range.start,
3461 end: new_range.end,
3462 goal: SelectionGoal::None,
3463 reversed: selection.reversed,
3464 }
3465 })
3466 .collect::<Vec<_>>();
3467
3468 if selected_larger_node {
3469 stack.push(old_selections);
3470 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
3471 }
3472 self.select_larger_syntax_node_stack = stack;
3473 }
3474
3475 pub fn select_smaller_syntax_node(
3476 &mut self,
3477 _: &SelectSmallerSyntaxNode,
3478 cx: &mut ViewContext<Self>,
3479 ) {
3480 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
3481 if let Some(selections) = stack.pop() {
3482 self.update_selections(selections.to_vec(), Some(Autoscroll::Fit), cx);
3483 }
3484 self.select_larger_syntax_node_stack = stack;
3485 }
3486
3487 pub fn move_to_enclosing_bracket(
3488 &mut self,
3489 _: &MoveToEnclosingBracket,
3490 cx: &mut ViewContext<Self>,
3491 ) {
3492 let mut selections = self.local_selections::<usize>(cx);
3493 let buffer = self.buffer.read(cx).snapshot(cx);
3494 for selection in &mut selections {
3495 if let Some((open_range, close_range)) =
3496 buffer.enclosing_bracket_ranges(selection.start..selection.end)
3497 {
3498 let close_range = close_range.to_inclusive();
3499 let destination = if close_range.contains(&selection.start)
3500 && close_range.contains(&selection.end)
3501 {
3502 open_range.end
3503 } else {
3504 *close_range.start()
3505 };
3506 selection.start = destination;
3507 selection.end = destination;
3508 }
3509 }
3510
3511 self.update_selections(selections, Some(Autoscroll::Fit), cx);
3512 }
3513
3514 pub fn show_next_diagnostic(&mut self, _: &ShowNextDiagnostic, cx: &mut ViewContext<Self>) {
3515 let buffer = self.buffer.read(cx).snapshot(cx);
3516 let selection = self.newest_selection::<usize>(&buffer);
3517 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
3518 active_diagnostics
3519 .primary_range
3520 .to_offset(&buffer)
3521 .to_inclusive()
3522 });
3523 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
3524 if active_primary_range.contains(&selection.head()) {
3525 *active_primary_range.end()
3526 } else {
3527 selection.head()
3528 }
3529 } else {
3530 selection.head()
3531 };
3532
3533 loop {
3534 let next_group = buffer
3535 .diagnostics_in_range::<_, usize>(search_start..buffer.len())
3536 .find_map(|entry| {
3537 if entry.diagnostic.is_primary
3538 && !entry.range.is_empty()
3539 && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
3540 {
3541 Some((entry.range, entry.diagnostic.group_id))
3542 } else {
3543 None
3544 }
3545 });
3546
3547 if let Some((primary_range, group_id)) = next_group {
3548 self.activate_diagnostics(group_id, cx);
3549 self.update_selections(
3550 vec![Selection {
3551 id: selection.id,
3552 start: primary_range.start,
3553 end: primary_range.start,
3554 reversed: false,
3555 goal: SelectionGoal::None,
3556 }],
3557 Some(Autoscroll::Center),
3558 cx,
3559 );
3560 break;
3561 } else if search_start == 0 {
3562 break;
3563 } else {
3564 // Cycle around to the start of the buffer, potentially moving back to the start of
3565 // the currently active diagnostic.
3566 search_start = 0;
3567 active_primary_range.take();
3568 }
3569 }
3570 }
3571
3572 pub fn go_to_definition(
3573 workspace: &mut Workspace,
3574 _: &GoToDefinition,
3575 cx: &mut ViewContext<Workspace>,
3576 ) {
3577 let active_item = workspace.active_item(cx);
3578 let editor_handle = if let Some(editor) = active_item
3579 .as_ref()
3580 .and_then(|item| item.act_as::<Self>(cx))
3581 {
3582 editor
3583 } else {
3584 return;
3585 };
3586
3587 let editor = editor_handle.read(cx);
3588 let buffer = editor.buffer.read(cx);
3589 let head = editor.newest_selection::<usize>(&buffer.read(cx)).head();
3590 let (buffer, head) = editor.buffer.read(cx).text_anchor_for_position(head, cx);
3591 let definitions = workspace
3592 .project()
3593 .update(cx, |project, cx| project.definition(&buffer, head, cx));
3594 cx.spawn(|workspace, mut cx| async move {
3595 let definitions = definitions.await?;
3596 workspace.update(&mut cx, |workspace, cx| {
3597 for definition in definitions {
3598 let range = definition
3599 .target_range
3600 .to_offset(definition.target_buffer.read(cx));
3601 let target_editor_handle = workspace
3602 .open_item(BufferItemHandle(definition.target_buffer), cx)
3603 .downcast::<Self>()
3604 .unwrap();
3605
3606 target_editor_handle.update(cx, |target_editor, cx| {
3607 // When selecting a definition in a different buffer, disable the nav history
3608 // to avoid creating a history entry at the previous cursor location.
3609 let disabled_history = if editor_handle == target_editor_handle {
3610 None
3611 } else {
3612 target_editor.nav_history.take()
3613 };
3614 target_editor.select_ranges([range], Some(Autoscroll::Center), cx);
3615 if disabled_history.is_some() {
3616 target_editor.nav_history = disabled_history;
3617 }
3618 });
3619 }
3620 });
3621
3622 Ok::<(), anyhow::Error>(())
3623 })
3624 .detach_and_log_err(cx);
3625 }
3626
3627 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
3628 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
3629 let buffer = self.buffer.read(cx).snapshot(cx);
3630 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
3631 let is_valid = buffer
3632 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
3633 .any(|entry| {
3634 entry.diagnostic.is_primary
3635 && !entry.range.is_empty()
3636 && entry.range.start == primary_range_start
3637 && entry.diagnostic.message == active_diagnostics.primary_message
3638 });
3639
3640 if is_valid != active_diagnostics.is_valid {
3641 active_diagnostics.is_valid = is_valid;
3642 let mut new_styles = HashMap::default();
3643 for (block_id, diagnostic) in &active_diagnostics.blocks {
3644 new_styles.insert(
3645 *block_id,
3646 diagnostic_block_renderer(
3647 diagnostic.clone(),
3648 is_valid,
3649 self.build_settings.clone(),
3650 ),
3651 );
3652 }
3653 self.display_map
3654 .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
3655 }
3656 }
3657 }
3658
3659 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
3660 self.dismiss_diagnostics(cx);
3661 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
3662 let buffer = self.buffer.read(cx).snapshot(cx);
3663
3664 let mut primary_range = None;
3665 let mut primary_message = None;
3666 let mut group_end = Point::zero();
3667 let diagnostic_group = buffer
3668 .diagnostic_group::<Point>(group_id)
3669 .map(|entry| {
3670 if entry.range.end > group_end {
3671 group_end = entry.range.end;
3672 }
3673 if entry.diagnostic.is_primary {
3674 primary_range = Some(entry.range.clone());
3675 primary_message = Some(entry.diagnostic.message.clone());
3676 }
3677 entry
3678 })
3679 .collect::<Vec<_>>();
3680 let primary_range = primary_range.unwrap();
3681 let primary_message = primary_message.unwrap();
3682 let primary_range =
3683 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
3684
3685 let blocks = display_map
3686 .insert_blocks(
3687 diagnostic_group.iter().map(|entry| {
3688 let build_settings = self.build_settings.clone();
3689 let diagnostic = entry.diagnostic.clone();
3690 let message_height = diagnostic.message.lines().count() as u8;
3691
3692 BlockProperties {
3693 position: buffer.anchor_after(entry.range.start),
3694 height: message_height,
3695 render: diagnostic_block_renderer(diagnostic, true, build_settings),
3696 disposition: BlockDisposition::Below,
3697 }
3698 }),
3699 cx,
3700 )
3701 .into_iter()
3702 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
3703 .collect();
3704
3705 Some(ActiveDiagnosticGroup {
3706 primary_range,
3707 primary_message,
3708 blocks,
3709 is_valid: true,
3710 })
3711 });
3712 }
3713
3714 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
3715 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
3716 self.display_map.update(cx, |display_map, cx| {
3717 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
3718 });
3719 cx.notify();
3720 }
3721 }
3722
3723 fn build_columnar_selection(
3724 &mut self,
3725 display_map: &DisplaySnapshot,
3726 row: u32,
3727 columns: &Range<u32>,
3728 reversed: bool,
3729 ) -> Option<Selection<Point>> {
3730 let is_empty = columns.start == columns.end;
3731 let line_len = display_map.line_len(row);
3732 if columns.start < line_len || (is_empty && columns.start == line_len) {
3733 let start = DisplayPoint::new(row, columns.start);
3734 let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
3735 Some(Selection {
3736 id: post_inc(&mut self.next_selection_id),
3737 start: start.to_point(display_map),
3738 end: end.to_point(display_map),
3739 reversed,
3740 goal: SelectionGoal::ColumnRange {
3741 start: columns.start,
3742 end: columns.end,
3743 },
3744 })
3745 } else {
3746 None
3747 }
3748 }
3749
3750 pub fn local_selections_in_range(
3751 &self,
3752 range: Range<Anchor>,
3753 display_map: &DisplaySnapshot,
3754 ) -> Vec<Selection<Point>> {
3755 let buffer = &display_map.buffer_snapshot;
3756
3757 let start_ix = match self
3758 .selections
3759 .binary_search_by(|probe| probe.end.cmp(&range.start, &buffer).unwrap())
3760 {
3761 Ok(ix) | Err(ix) => ix,
3762 };
3763 let end_ix = match self
3764 .selections
3765 .binary_search_by(|probe| probe.start.cmp(&range.end, &buffer).unwrap())
3766 {
3767 Ok(ix) => ix + 1,
3768 Err(ix) => ix,
3769 };
3770
3771 fn point_selection(
3772 selection: &Selection<Anchor>,
3773 buffer: &MultiBufferSnapshot,
3774 ) -> Selection<Point> {
3775 let start = selection.start.to_point(&buffer);
3776 let end = selection.end.to_point(&buffer);
3777 Selection {
3778 id: selection.id,
3779 start,
3780 end,
3781 reversed: selection.reversed,
3782 goal: selection.goal,
3783 }
3784 }
3785
3786 self.selections[start_ix..end_ix]
3787 .iter()
3788 .chain(
3789 self.pending_selection
3790 .as_ref()
3791 .map(|pending| &pending.selection),
3792 )
3793 .map(|s| point_selection(s, &buffer))
3794 .collect()
3795 }
3796
3797 pub fn local_selections<'a, D>(&self, cx: &'a AppContext) -> Vec<Selection<D>>
3798 where
3799 D: 'a + TextDimension + Ord + Sub<D, Output = D>,
3800 {
3801 let buffer = self.buffer.read(cx).snapshot(cx);
3802 let mut selections = self
3803 .resolve_selections::<D, _>(self.selections.iter(), &buffer)
3804 .peekable();
3805
3806 let mut pending_selection = self.pending_selection::<D>(&buffer);
3807
3808 iter::from_fn(move || {
3809 if let Some(pending) = pending_selection.as_mut() {
3810 while let Some(next_selection) = selections.peek() {
3811 if pending.start <= next_selection.end && pending.end >= next_selection.start {
3812 let next_selection = selections.next().unwrap();
3813 if next_selection.start < pending.start {
3814 pending.start = next_selection.start;
3815 }
3816 if next_selection.end > pending.end {
3817 pending.end = next_selection.end;
3818 }
3819 } else if next_selection.end < pending.start {
3820 return selections.next();
3821 } else {
3822 break;
3823 }
3824 }
3825
3826 pending_selection.take()
3827 } else {
3828 selections.next()
3829 }
3830 })
3831 .collect()
3832 }
3833
3834 fn resolve_selections<'a, D, I>(
3835 &self,
3836 selections: I,
3837 snapshot: &MultiBufferSnapshot,
3838 ) -> impl 'a + Iterator<Item = Selection<D>>
3839 where
3840 D: TextDimension + Ord + Sub<D, Output = D>,
3841 I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
3842 {
3843 let (to_summarize, selections) = selections.into_iter().tee();
3844 let mut summaries = snapshot
3845 .summaries_for_anchors::<D, _>(to_summarize.flat_map(|s| [&s.start, &s.end]))
3846 .into_iter();
3847 selections.map(move |s| Selection {
3848 id: s.id,
3849 start: summaries.next().unwrap(),
3850 end: summaries.next().unwrap(),
3851 reversed: s.reversed,
3852 goal: s.goal,
3853 })
3854 }
3855
3856 fn pending_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3857 &self,
3858 snapshot: &MultiBufferSnapshot,
3859 ) -> Option<Selection<D>> {
3860 self.pending_selection
3861 .as_ref()
3862 .map(|pending| self.resolve_selection(&pending.selection, &snapshot))
3863 }
3864
3865 fn resolve_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3866 &self,
3867 selection: &Selection<Anchor>,
3868 buffer: &MultiBufferSnapshot,
3869 ) -> Selection<D> {
3870 Selection {
3871 id: selection.id,
3872 start: selection.start.summary::<D>(&buffer),
3873 end: selection.end.summary::<D>(&buffer),
3874 reversed: selection.reversed,
3875 goal: selection.goal,
3876 }
3877 }
3878
3879 fn selection_count<'a>(&self) -> usize {
3880 let mut count = self.selections.len();
3881 if self.pending_selection.is_some() {
3882 count += 1;
3883 }
3884 count
3885 }
3886
3887 pub fn oldest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3888 &self,
3889 snapshot: &MultiBufferSnapshot,
3890 ) -> Selection<D> {
3891 self.selections
3892 .iter()
3893 .min_by_key(|s| s.id)
3894 .map(|selection| self.resolve_selection(selection, snapshot))
3895 .or_else(|| self.pending_selection(snapshot))
3896 .unwrap()
3897 }
3898
3899 pub fn newest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3900 &self,
3901 snapshot: &MultiBufferSnapshot,
3902 ) -> Selection<D> {
3903 self.resolve_selection(self.newest_anchor_selection().unwrap(), snapshot)
3904 }
3905
3906 pub fn newest_anchor_selection(&self) -> Option<&Selection<Anchor>> {
3907 self.pending_selection
3908 .as_ref()
3909 .map(|s| &s.selection)
3910 .or_else(|| self.selections.iter().max_by_key(|s| s.id))
3911 }
3912
3913 pub fn update_selections<T>(
3914 &mut self,
3915 mut selections: Vec<Selection<T>>,
3916 autoscroll: Option<Autoscroll>,
3917 cx: &mut ViewContext<Self>,
3918 ) where
3919 T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
3920 {
3921 let buffer = self.buffer.read(cx).snapshot(cx);
3922 selections.sort_unstable_by_key(|s| s.start);
3923
3924 // Merge overlapping selections.
3925 let mut i = 1;
3926 while i < selections.len() {
3927 if selections[i - 1].end >= selections[i].start {
3928 let removed = selections.remove(i);
3929 if removed.start < selections[i - 1].start {
3930 selections[i - 1].start = removed.start;
3931 }
3932 if removed.end > selections[i - 1].end {
3933 selections[i - 1].end = removed.end;
3934 }
3935 } else {
3936 i += 1;
3937 }
3938 }
3939
3940 if let Some(autoscroll) = autoscroll {
3941 self.request_autoscroll(autoscroll, cx);
3942 }
3943
3944 self.set_selections(
3945 Arc::from_iter(selections.into_iter().map(|selection| {
3946 let end_bias = if selection.end > selection.start {
3947 Bias::Left
3948 } else {
3949 Bias::Right
3950 };
3951 Selection {
3952 id: selection.id,
3953 start: buffer.anchor_after(selection.start),
3954 end: buffer.anchor_at(selection.end, end_bias),
3955 reversed: selection.reversed,
3956 goal: selection.goal,
3957 }
3958 })),
3959 cx,
3960 );
3961 }
3962
3963 /// Compute new ranges for any selections that were located in excerpts that have
3964 /// since been removed.
3965 ///
3966 /// Returns a `HashMap` indicating which selections whose former head position
3967 /// was no longer present. The keys of the map are selection ids. The values are
3968 /// the id of the new excerpt where the head of the selection has been moved.
3969 pub fn refresh_selections(&mut self, cx: &mut ViewContext<Self>) -> HashMap<usize, ExcerptId> {
3970 let snapshot = self.buffer.read(cx).read(cx);
3971 let anchors_with_status = snapshot.refresh_anchors(
3972 self.selections
3973 .iter()
3974 .flat_map(|selection| [&selection.start, &selection.end]),
3975 );
3976 let offsets =
3977 snapshot.summaries_for_anchors::<usize, _>(anchors_with_status.iter().map(|a| &a.1));
3978 let offsets = offsets.chunks(2);
3979 let statuses = anchors_with_status
3980 .chunks(2)
3981 .map(|a| (a[0].0 / 2, a[0].2, a[1].2));
3982
3983 let mut selections_with_lost_position = HashMap::default();
3984 let new_selections = offsets
3985 .zip(statuses)
3986 .map(|(offsets, (selection_ix, kept_start, kept_end))| {
3987 let selection = &self.selections[selection_ix];
3988 let kept_head = if selection.reversed {
3989 kept_start
3990 } else {
3991 kept_end
3992 };
3993 if !kept_head {
3994 selections_with_lost_position
3995 .insert(selection.id, selection.head().excerpt_id.clone());
3996 }
3997
3998 Selection {
3999 id: selection.id,
4000 start: offsets[0],
4001 end: offsets[1],
4002 reversed: selection.reversed,
4003 goal: selection.goal,
4004 }
4005 })
4006 .collect();
4007 drop(snapshot);
4008 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
4009 selections_with_lost_position
4010 }
4011
4012 fn set_selections(&mut self, selections: Arc<[Selection<Anchor>]>, cx: &mut ViewContext<Self>) {
4013 let old_cursor_position = self.newest_anchor_selection().map(|s| s.head());
4014 self.selections = selections;
4015 if self.focused {
4016 self.buffer.update(cx, |buffer, cx| {
4017 buffer.set_active_selections(&self.selections, cx)
4018 });
4019 }
4020
4021 let buffer = self.buffer.read(cx).snapshot(cx);
4022 self.pending_selection = None;
4023 self.add_selections_state = None;
4024 self.select_next_state = None;
4025 self.select_larger_syntax_node_stack.clear();
4026 self.autoclose_stack.invalidate(&self.selections, &buffer);
4027 self.snippet_stack.invalidate(&self.selections, &buffer);
4028
4029 let new_cursor_position = self
4030 .selections
4031 .iter()
4032 .max_by_key(|s| s.id)
4033 .map(|s| s.head());
4034 if let Some(old_cursor_position) = old_cursor_position {
4035 if let Some(new_cursor_position) = new_cursor_position.as_ref() {
4036 self.push_to_nav_history(
4037 old_cursor_position,
4038 Some(new_cursor_position.to_point(&buffer)),
4039 cx,
4040 );
4041 }
4042 }
4043
4044 if let Some((completion_state, cursor_position)) =
4045 self.completion_state.as_mut().zip(new_cursor_position)
4046 {
4047 let cursor_position = cursor_position.to_offset(&buffer);
4048 let (word_range, kind) =
4049 buffer.surrounding_word(completion_state.initial_position.clone());
4050 if kind == Some(CharKind::Word) && word_range.to_inclusive().contains(&cursor_position)
4051 {
4052 let query = Self::completion_query(&buffer, cursor_position);
4053 cx.background()
4054 .block(completion_state.filter(query.as_deref(), cx.background().clone()));
4055 self.show_completions(&ShowCompletions, cx);
4056 } else {
4057 self.hide_completions(cx);
4058 }
4059 }
4060
4061 self.pause_cursor_blinking(cx);
4062 cx.emit(Event::SelectionsChanged);
4063 }
4064
4065 pub fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
4066 self.autoscroll_request = Some(autoscroll);
4067 cx.notify();
4068 }
4069
4070 fn start_transaction(&mut self, cx: &mut ViewContext<Self>) {
4071 self.start_transaction_at(Instant::now(), cx);
4072 }
4073
4074 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
4075 self.end_selection(cx);
4076 if let Some(tx_id) = self
4077 .buffer
4078 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
4079 {
4080 self.selection_history
4081 .insert(tx_id, (self.selections.clone(), None));
4082 }
4083 }
4084
4085 fn end_transaction(&mut self, cx: &mut ViewContext<Self>) {
4086 self.end_transaction_at(Instant::now(), cx);
4087 }
4088
4089 fn end_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
4090 if let Some(tx_id) = self
4091 .buffer
4092 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
4093 {
4094 if let Some((_, end_selections)) = self.selection_history.get_mut(&tx_id) {
4095 *end_selections = Some(self.selections.clone());
4096 } else {
4097 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
4098 }
4099 }
4100 }
4101
4102 pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
4103 log::info!("Editor::page_up");
4104 }
4105
4106 pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
4107 log::info!("Editor::page_down");
4108 }
4109
4110 pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
4111 let mut fold_ranges = Vec::new();
4112
4113 let selections = self.local_selections::<Point>(cx);
4114 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4115 for selection in selections {
4116 let range = selection.display_range(&display_map).sorted();
4117 let buffer_start_row = range.start.to_point(&display_map).row;
4118
4119 for row in (0..=range.end.row()).rev() {
4120 if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
4121 let fold_range = self.foldable_range_for_line(&display_map, row);
4122 if fold_range.end.row >= buffer_start_row {
4123 fold_ranges.push(fold_range);
4124 if row <= range.start.row() {
4125 break;
4126 }
4127 }
4128 }
4129 }
4130 }
4131
4132 self.fold_ranges(fold_ranges, cx);
4133 }
4134
4135 pub fn unfold(&mut self, _: &Unfold, cx: &mut ViewContext<Self>) {
4136 let selections = self.local_selections::<Point>(cx);
4137 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4138 let buffer = &display_map.buffer_snapshot;
4139 let ranges = selections
4140 .iter()
4141 .map(|s| {
4142 let range = s.display_range(&display_map).sorted();
4143 let mut start = range.start.to_point(&display_map);
4144 let mut end = range.end.to_point(&display_map);
4145 start.column = 0;
4146 end.column = buffer.line_len(end.row);
4147 start..end
4148 })
4149 .collect::<Vec<_>>();
4150 self.unfold_ranges(ranges, cx);
4151 }
4152
4153 fn is_line_foldable(&self, display_map: &DisplaySnapshot, display_row: u32) -> bool {
4154 let max_point = display_map.max_point();
4155 if display_row >= max_point.row() {
4156 false
4157 } else {
4158 let (start_indent, is_blank) = display_map.line_indent(display_row);
4159 if is_blank {
4160 false
4161 } else {
4162 for display_row in display_row + 1..=max_point.row() {
4163 let (indent, is_blank) = display_map.line_indent(display_row);
4164 if !is_blank {
4165 return indent > start_indent;
4166 }
4167 }
4168 false
4169 }
4170 }
4171 }
4172
4173 fn foldable_range_for_line(
4174 &self,
4175 display_map: &DisplaySnapshot,
4176 start_row: u32,
4177 ) -> Range<Point> {
4178 let max_point = display_map.max_point();
4179
4180 let (start_indent, _) = display_map.line_indent(start_row);
4181 let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
4182 let mut end = None;
4183 for row in start_row + 1..=max_point.row() {
4184 let (indent, is_blank) = display_map.line_indent(row);
4185 if !is_blank && indent <= start_indent {
4186 end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
4187 break;
4188 }
4189 }
4190
4191 let end = end.unwrap_or(max_point);
4192 return start.to_point(display_map)..end.to_point(display_map);
4193 }
4194
4195 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
4196 let selections = self.local_selections::<Point>(cx);
4197 let ranges = selections.into_iter().map(|s| s.start..s.end);
4198 self.fold_ranges(ranges, cx);
4199 }
4200
4201 fn fold_ranges<T: ToOffset>(
4202 &mut self,
4203 ranges: impl IntoIterator<Item = Range<T>>,
4204 cx: &mut ViewContext<Self>,
4205 ) {
4206 let mut ranges = ranges.into_iter().peekable();
4207 if ranges.peek().is_some() {
4208 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
4209 self.request_autoscroll(Autoscroll::Fit, cx);
4210 cx.notify();
4211 }
4212 }
4213
4214 fn unfold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
4215 if !ranges.is_empty() {
4216 self.display_map
4217 .update(cx, |map, cx| map.unfold(ranges, cx));
4218 self.request_autoscroll(Autoscroll::Fit, cx);
4219 cx.notify();
4220 }
4221 }
4222
4223 pub fn insert_blocks(
4224 &mut self,
4225 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
4226 cx: &mut ViewContext<Self>,
4227 ) -> Vec<BlockId> {
4228 let blocks = self
4229 .display_map
4230 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
4231 self.request_autoscroll(Autoscroll::Fit, cx);
4232 blocks
4233 }
4234
4235 pub fn replace_blocks(
4236 &mut self,
4237 blocks: HashMap<BlockId, RenderBlock>,
4238 cx: &mut ViewContext<Self>,
4239 ) {
4240 self.display_map
4241 .update(cx, |display_map, _| display_map.replace_blocks(blocks));
4242 self.request_autoscroll(Autoscroll::Fit, cx);
4243 }
4244
4245 pub fn remove_blocks(&mut self, block_ids: HashSet<BlockId>, cx: &mut ViewContext<Self>) {
4246 self.display_map.update(cx, |display_map, cx| {
4247 display_map.remove_blocks(block_ids, cx)
4248 });
4249 }
4250
4251 pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
4252 self.display_map
4253 .update(cx, |map, cx| map.snapshot(cx))
4254 .longest_row()
4255 }
4256
4257 pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
4258 self.display_map
4259 .update(cx, |map, cx| map.snapshot(cx))
4260 .max_point()
4261 }
4262
4263 pub fn text(&self, cx: &AppContext) -> String {
4264 self.buffer.read(cx).read(cx).text()
4265 }
4266
4267 pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
4268 self.display_map
4269 .update(cx, |map, cx| map.snapshot(cx))
4270 .text()
4271 }
4272
4273 pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut MutableAppContext) -> bool {
4274 self.display_map
4275 .update(cx, |map, cx| map.set_wrap_width(width, cx))
4276 }
4277
4278 pub fn set_highlighted_rows(&mut self, rows: Option<Range<u32>>) {
4279 self.highlighted_rows = rows;
4280 }
4281
4282 pub fn highlighted_rows(&self) -> Option<Range<u32>> {
4283 self.highlighted_rows.clone()
4284 }
4285
4286 pub fn highlight_ranges<T: 'static>(
4287 &mut self,
4288 ranges: Vec<Range<Anchor>>,
4289 color: Color,
4290 cx: &mut ViewContext<Self>,
4291 ) {
4292 self.highlighted_ranges
4293 .insert(TypeId::of::<T>(), (color, ranges));
4294 cx.notify();
4295 }
4296
4297 pub fn clear_highlighted_ranges<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
4298 self.highlighted_ranges.remove(&TypeId::of::<T>());
4299 cx.notify();
4300 }
4301
4302 #[cfg(feature = "test-support")]
4303 pub fn all_highlighted_ranges(
4304 &mut self,
4305 cx: &mut ViewContext<Self>,
4306 ) -> Vec<(Range<DisplayPoint>, Color)> {
4307 let snapshot = self.snapshot(cx);
4308 let buffer = &snapshot.buffer_snapshot;
4309 let start = buffer.anchor_before(0);
4310 let end = buffer.anchor_after(buffer.len());
4311 self.highlighted_ranges_in_range(start..end, &snapshot)
4312 }
4313
4314 pub fn highlighted_ranges_for_type<T: 'static>(&self) -> Option<(Color, &[Range<Anchor>])> {
4315 self.highlighted_ranges
4316 .get(&TypeId::of::<T>())
4317 .map(|(color, ranges)| (*color, ranges.as_slice()))
4318 }
4319
4320 pub fn highlighted_ranges_in_range(
4321 &self,
4322 search_range: Range<Anchor>,
4323 display_snapshot: &DisplaySnapshot,
4324 ) -> Vec<(Range<DisplayPoint>, Color)> {
4325 let mut results = Vec::new();
4326 let buffer = &display_snapshot.buffer_snapshot;
4327 for (color, ranges) in self.highlighted_ranges.values() {
4328 let start_ix = match ranges.binary_search_by(|probe| {
4329 let cmp = probe.end.cmp(&search_range.start, &buffer).unwrap();
4330 if cmp.is_gt() {
4331 Ordering::Greater
4332 } else {
4333 Ordering::Less
4334 }
4335 }) {
4336 Ok(i) | Err(i) => i,
4337 };
4338 for range in &ranges[start_ix..] {
4339 if range.start.cmp(&search_range.end, &buffer).unwrap().is_ge() {
4340 break;
4341 }
4342 let start = range
4343 .start
4344 .to_point(buffer)
4345 .to_display_point(display_snapshot);
4346 let end = range
4347 .end
4348 .to_point(buffer)
4349 .to_display_point(display_snapshot);
4350 results.push((start..end, *color))
4351 }
4352 }
4353 results
4354 }
4355
4356 fn next_blink_epoch(&mut self) -> usize {
4357 self.blink_epoch += 1;
4358 self.blink_epoch
4359 }
4360
4361 fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
4362 if !self.focused {
4363 return;
4364 }
4365
4366 self.show_local_cursors = true;
4367 cx.notify();
4368
4369 let epoch = self.next_blink_epoch();
4370 cx.spawn(|this, mut cx| {
4371 let this = this.downgrade();
4372 async move {
4373 Timer::after(CURSOR_BLINK_INTERVAL).await;
4374 if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
4375 this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
4376 }
4377 }
4378 })
4379 .detach();
4380 }
4381
4382 fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
4383 if epoch == self.blink_epoch {
4384 self.blinking_paused = false;
4385 self.blink_cursors(epoch, cx);
4386 }
4387 }
4388
4389 fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
4390 if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
4391 self.show_local_cursors = !self.show_local_cursors;
4392 cx.notify();
4393
4394 let epoch = self.next_blink_epoch();
4395 cx.spawn(|this, mut cx| {
4396 let this = this.downgrade();
4397 async move {
4398 Timer::after(CURSOR_BLINK_INTERVAL).await;
4399 if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
4400 this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
4401 }
4402 }
4403 })
4404 .detach();
4405 }
4406 }
4407
4408 pub fn show_local_cursors(&self) -> bool {
4409 self.show_local_cursors
4410 }
4411
4412 fn on_buffer_changed(&mut self, _: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Self>) {
4413 self.refresh_active_diagnostics(cx);
4414 cx.notify();
4415 }
4416
4417 fn on_buffer_event(
4418 &mut self,
4419 _: ModelHandle<MultiBuffer>,
4420 event: &language::Event,
4421 cx: &mut ViewContext<Self>,
4422 ) {
4423 match event {
4424 language::Event::Edited => cx.emit(Event::Edited),
4425 language::Event::Dirtied => cx.emit(Event::Dirtied),
4426 language::Event::Saved => cx.emit(Event::Saved),
4427 language::Event::FileHandleChanged => cx.emit(Event::TitleChanged),
4428 language::Event::Reloaded => cx.emit(Event::TitleChanged),
4429 language::Event::Closed => cx.emit(Event::Closed),
4430 _ => {}
4431 }
4432 }
4433
4434 fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
4435 cx.notify();
4436 }
4437}
4438
4439impl EditorSnapshot {
4440 pub fn is_focused(&self) -> bool {
4441 self.is_focused
4442 }
4443
4444 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
4445 self.placeholder_text.as_ref()
4446 }
4447
4448 pub fn scroll_position(&self) -> Vector2F {
4449 compute_scroll_position(
4450 &self.display_snapshot,
4451 self.scroll_position,
4452 &self.scroll_top_anchor,
4453 )
4454 }
4455}
4456
4457impl Deref for EditorSnapshot {
4458 type Target = DisplaySnapshot;
4459
4460 fn deref(&self) -> &Self::Target {
4461 &self.display_snapshot
4462 }
4463}
4464
4465impl EditorSettings {
4466 #[cfg(any(test, feature = "test-support"))]
4467 pub fn test(cx: &AppContext) -> Self {
4468 use theme::{ContainedLabel, ContainedText, DiagnosticHeader, DiagnosticPathHeader};
4469
4470 Self {
4471 tab_size: 4,
4472 soft_wrap: SoftWrap::None,
4473 style: {
4474 let font_cache: &gpui::FontCache = cx.font_cache();
4475 let font_family_name = Arc::from("Monaco");
4476 let font_properties = Default::default();
4477 let font_family_id = font_cache.load_family(&[&font_family_name]).unwrap();
4478 let font_id = font_cache
4479 .select_font(font_family_id, &font_properties)
4480 .unwrap();
4481 let text = gpui::fonts::TextStyle {
4482 font_family_name,
4483 font_family_id,
4484 font_id,
4485 font_size: 14.,
4486 color: gpui::color::Color::from_u32(0xff0000ff),
4487 font_properties,
4488 underline: None,
4489 };
4490 let default_diagnostic_style = DiagnosticStyle {
4491 message: text.clone().into(),
4492 header: Default::default(),
4493 text_scale_factor: 1.,
4494 };
4495 EditorStyle {
4496 text: text.clone(),
4497 placeholder_text: None,
4498 background: Default::default(),
4499 gutter_background: Default::default(),
4500 gutter_padding_factor: 2.,
4501 active_line_background: Default::default(),
4502 highlighted_line_background: Default::default(),
4503 line_number: Default::default(),
4504 line_number_active: Default::default(),
4505 selection: Default::default(),
4506 guest_selections: Default::default(),
4507 syntax: Default::default(),
4508 diagnostic_path_header: DiagnosticPathHeader {
4509 container: Default::default(),
4510 filename: ContainedText {
4511 container: Default::default(),
4512 text: text.clone(),
4513 },
4514 path: ContainedText {
4515 container: Default::default(),
4516 text: text.clone(),
4517 },
4518 text_scale_factor: 1.,
4519 },
4520 diagnostic_header: DiagnosticHeader {
4521 container: Default::default(),
4522 message: ContainedLabel {
4523 container: Default::default(),
4524 label: text.clone().into(),
4525 },
4526 code: ContainedText {
4527 container: Default::default(),
4528 text: text.clone(),
4529 },
4530 icon_width_factor: 1.,
4531 text_scale_factor: 1.,
4532 },
4533 error_diagnostic: default_diagnostic_style.clone(),
4534 invalid_error_diagnostic: default_diagnostic_style.clone(),
4535 warning_diagnostic: default_diagnostic_style.clone(),
4536 invalid_warning_diagnostic: default_diagnostic_style.clone(),
4537 information_diagnostic: default_diagnostic_style.clone(),
4538 invalid_information_diagnostic: default_diagnostic_style.clone(),
4539 hint_diagnostic: default_diagnostic_style.clone(),
4540 invalid_hint_diagnostic: default_diagnostic_style.clone(),
4541 autocomplete: Default::default(),
4542 }
4543 },
4544 }
4545 }
4546}
4547
4548fn compute_scroll_position(
4549 snapshot: &DisplaySnapshot,
4550 mut scroll_position: Vector2F,
4551 scroll_top_anchor: &Option<Anchor>,
4552) -> Vector2F {
4553 if let Some(anchor) = scroll_top_anchor {
4554 let scroll_top = anchor.to_display_point(snapshot).row() as f32;
4555 scroll_position.set_y(scroll_top + scroll_position.y());
4556 } else {
4557 scroll_position.set_y(0.);
4558 }
4559 scroll_position
4560}
4561
4562#[derive(Copy, Clone)]
4563pub enum Event {
4564 Activate,
4565 Edited,
4566 Blurred,
4567 Dirtied,
4568 Saved,
4569 TitleChanged,
4570 SelectionsChanged,
4571 Closed,
4572}
4573
4574impl Entity for Editor {
4575 type Event = Event;
4576}
4577
4578impl View for Editor {
4579 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
4580 let settings = (self.build_settings)(cx);
4581 self.display_map.update(cx, |map, cx| {
4582 map.set_font(
4583 settings.style.text.font_id,
4584 settings.style.text.font_size,
4585 cx,
4586 )
4587 });
4588 EditorElement::new(self.handle.clone(), settings).boxed()
4589 }
4590
4591 fn ui_name() -> &'static str {
4592 "Editor"
4593 }
4594
4595 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
4596 self.focused = true;
4597 self.blink_cursors(self.blink_epoch, cx);
4598 self.buffer.update(cx, |buffer, cx| {
4599 buffer.avoid_grouping_next_transaction(cx);
4600 buffer.set_active_selections(&self.selections, cx)
4601 });
4602 }
4603
4604 fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
4605 self.focused = false;
4606 self.show_local_cursors = false;
4607 self.buffer
4608 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
4609 self.hide_completions(cx);
4610 cx.emit(Event::Blurred);
4611 cx.notify();
4612 }
4613
4614 fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
4615 let mut cx = Self::default_keymap_context();
4616 let mode = match self.mode {
4617 EditorMode::SingleLine => "single_line",
4618 EditorMode::AutoHeight { .. } => "auto_height",
4619 EditorMode::Full => "full",
4620 };
4621 cx.map.insert("mode".into(), mode.into());
4622 if self.completion_state.is_some() {
4623 cx.set.insert("completing".into());
4624 }
4625 cx
4626 }
4627}
4628
4629impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
4630 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
4631 let start = self.start.to_point(buffer);
4632 let end = self.end.to_point(buffer);
4633 if self.reversed {
4634 end..start
4635 } else {
4636 start..end
4637 }
4638 }
4639
4640 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
4641 let start = self.start.to_offset(buffer);
4642 let end = self.end.to_offset(buffer);
4643 if self.reversed {
4644 end..start
4645 } else {
4646 start..end
4647 }
4648 }
4649
4650 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
4651 let start = self
4652 .start
4653 .to_point(&map.buffer_snapshot)
4654 .to_display_point(map);
4655 let end = self
4656 .end
4657 .to_point(&map.buffer_snapshot)
4658 .to_display_point(map);
4659 if self.reversed {
4660 end..start
4661 } else {
4662 start..end
4663 }
4664 }
4665
4666 fn spanned_rows(
4667 &self,
4668 include_end_if_at_line_start: bool,
4669 map: &DisplaySnapshot,
4670 ) -> Range<u32> {
4671 let start = self.start.to_point(&map.buffer_snapshot);
4672 let mut end = self.end.to_point(&map.buffer_snapshot);
4673 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
4674 end.row -= 1;
4675 }
4676
4677 let buffer_start = map.prev_line_boundary(start).0;
4678 let buffer_end = map.next_line_boundary(end).0;
4679 buffer_start.row..buffer_end.row + 1
4680 }
4681}
4682
4683impl<T: InvalidationRegion> InvalidationStack<T> {
4684 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
4685 where
4686 S: Clone + ToOffset,
4687 {
4688 while let Some(region) = self.last() {
4689 let all_selections_inside_invalidation_ranges =
4690 if selections.len() == region.ranges().len() {
4691 selections
4692 .iter()
4693 .zip(region.ranges().iter().map(|r| r.to_offset(&buffer)))
4694 .all(|(selection, invalidation_range)| {
4695 let head = selection.head().to_offset(&buffer);
4696 invalidation_range.start <= head && invalidation_range.end >= head
4697 })
4698 } else {
4699 false
4700 };
4701
4702 if all_selections_inside_invalidation_ranges {
4703 break;
4704 } else {
4705 self.pop();
4706 }
4707 }
4708 }
4709}
4710
4711impl<T> Default for InvalidationStack<T> {
4712 fn default() -> Self {
4713 Self(Default::default())
4714 }
4715}
4716
4717impl<T> Deref for InvalidationStack<T> {
4718 type Target = Vec<T>;
4719
4720 fn deref(&self) -> &Self::Target {
4721 &self.0
4722 }
4723}
4724
4725impl<T> DerefMut for InvalidationStack<T> {
4726 fn deref_mut(&mut self) -> &mut Self::Target {
4727 &mut self.0
4728 }
4729}
4730
4731impl InvalidationRegion for BracketPairState {
4732 fn ranges(&self) -> &[Range<Anchor>] {
4733 &self.ranges
4734 }
4735}
4736
4737impl InvalidationRegion for SnippetState {
4738 fn ranges(&self) -> &[Range<Anchor>] {
4739 &self.ranges[self.active_index]
4740 }
4741}
4742
4743pub fn diagnostic_block_renderer(
4744 diagnostic: Diagnostic,
4745 is_valid: bool,
4746 build_settings: BuildSettings,
4747) -> RenderBlock {
4748 let mut highlighted_lines = Vec::new();
4749 for line in diagnostic.message.lines() {
4750 highlighted_lines.push(highlight_diagnostic_message(line));
4751 }
4752
4753 Arc::new(move |cx: &BlockContext| {
4754 let settings = build_settings(cx);
4755 let style = diagnostic_style(diagnostic.severity, is_valid, &settings.style);
4756 let font_size = (style.text_scale_factor * settings.style.text.font_size).round();
4757 Flex::column()
4758 .with_children(highlighted_lines.iter().map(|(line, highlights)| {
4759 Label::new(
4760 line.clone(),
4761 style.message.clone().with_font_size(font_size),
4762 )
4763 .with_highlights(highlights.clone())
4764 .contained()
4765 .with_margin_left(cx.anchor_x)
4766 .boxed()
4767 }))
4768 .aligned()
4769 .left()
4770 .boxed()
4771 })
4772}
4773
4774pub fn highlight_diagnostic_message(message: &str) -> (String, Vec<usize>) {
4775 let mut message_without_backticks = String::new();
4776 let mut prev_offset = 0;
4777 let mut inside_block = false;
4778 let mut highlights = Vec::new();
4779 for (match_ix, (offset, _)) in message
4780 .match_indices('`')
4781 .chain([(message.len(), "")])
4782 .enumerate()
4783 {
4784 message_without_backticks.push_str(&message[prev_offset..offset]);
4785 if inside_block {
4786 highlights.extend(prev_offset - match_ix..offset - match_ix);
4787 }
4788
4789 inside_block = !inside_block;
4790 prev_offset = offset + 1;
4791 }
4792
4793 (message_without_backticks, highlights)
4794}
4795
4796pub fn diagnostic_style(
4797 severity: DiagnosticSeverity,
4798 valid: bool,
4799 style: &EditorStyle,
4800) -> DiagnosticStyle {
4801 match (severity, valid) {
4802 (DiagnosticSeverity::ERROR, true) => style.error_diagnostic.clone(),
4803 (DiagnosticSeverity::ERROR, false) => style.invalid_error_diagnostic.clone(),
4804 (DiagnosticSeverity::WARNING, true) => style.warning_diagnostic.clone(),
4805 (DiagnosticSeverity::WARNING, false) => style.invalid_warning_diagnostic.clone(),
4806 (DiagnosticSeverity::INFORMATION, true) => style.information_diagnostic.clone(),
4807 (DiagnosticSeverity::INFORMATION, false) => style.invalid_information_diagnostic.clone(),
4808 (DiagnosticSeverity::HINT, true) => style.hint_diagnostic.clone(),
4809 (DiagnosticSeverity::HINT, false) => style.invalid_hint_diagnostic.clone(),
4810 _ => DiagnosticStyle {
4811 message: style.text.clone().into(),
4812 header: Default::default(),
4813 text_scale_factor: 1.,
4814 },
4815 }
4816}
4817
4818pub fn settings_builder(
4819 buffer: WeakModelHandle<MultiBuffer>,
4820 settings: watch::Receiver<workspace::Settings>,
4821) -> BuildSettings {
4822 Arc::new(move |cx| {
4823 let settings = settings.borrow();
4824 let font_cache = cx.font_cache();
4825 let font_family_id = settings.buffer_font_family;
4826 let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
4827 let font_properties = Default::default();
4828 let font_id = font_cache
4829 .select_font(font_family_id, &font_properties)
4830 .unwrap();
4831 let font_size = settings.buffer_font_size;
4832
4833 let mut theme = settings.theme.editor.clone();
4834 theme.text = TextStyle {
4835 color: theme.text.color,
4836 font_family_name,
4837 font_family_id,
4838 font_id,
4839 font_size,
4840 font_properties,
4841 underline: None,
4842 };
4843 let language = buffer.upgrade(cx).and_then(|buf| buf.read(cx).language(cx));
4844 let soft_wrap = match settings.soft_wrap(language) {
4845 workspace::settings::SoftWrap::None => SoftWrap::None,
4846 workspace::settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
4847 workspace::settings::SoftWrap::PreferredLineLength => {
4848 SoftWrap::Column(settings.preferred_line_length(language).saturating_sub(1))
4849 }
4850 };
4851
4852 EditorSettings {
4853 tab_size: settings.tab_size,
4854 soft_wrap,
4855 style: theme,
4856 }
4857 })
4858}
4859
4860pub fn combine_syntax_and_fuzzy_match_highlights(
4861 text: &str,
4862 default_style: HighlightStyle,
4863 syntax_ranges: impl Iterator<Item = (Range<usize>, HighlightStyle)>,
4864 match_indices: &[usize],
4865) -> Vec<(Range<usize>, HighlightStyle)> {
4866 let mut result = Vec::new();
4867 let mut match_indices = match_indices.iter().copied().peekable();
4868
4869 for (range, mut syntax_highlight) in syntax_ranges.chain([(usize::MAX..0, Default::default())])
4870 {
4871 syntax_highlight.font_properties.weight(Default::default());
4872
4873 // Add highlights for any fuzzy match characters before the next
4874 // syntax highlight range.
4875 while let Some(&match_index) = match_indices.peek() {
4876 if match_index >= range.start {
4877 break;
4878 }
4879 match_indices.next();
4880 let end_index = char_ix_after(match_index, text);
4881 let mut match_style = default_style;
4882 match_style.font_properties.weight(fonts::Weight::BOLD);
4883 result.push((match_index..end_index, match_style));
4884 }
4885
4886 if range.start == usize::MAX {
4887 break;
4888 }
4889
4890 // Add highlights for any fuzzy match characters within the
4891 // syntax highlight range.
4892 let mut offset = range.start;
4893 while let Some(&match_index) = match_indices.peek() {
4894 if match_index >= range.end {
4895 break;
4896 }
4897
4898 match_indices.next();
4899 if match_index > offset {
4900 result.push((offset..match_index, syntax_highlight));
4901 }
4902
4903 let mut end_index = char_ix_after(match_index, text);
4904 while let Some(&next_match_index) = match_indices.peek() {
4905 if next_match_index == end_index && next_match_index < range.end {
4906 end_index = char_ix_after(next_match_index, text);
4907 match_indices.next();
4908 } else {
4909 break;
4910 }
4911 }
4912
4913 let mut match_style = syntax_highlight;
4914 match_style.font_properties.weight(fonts::Weight::BOLD);
4915 result.push((match_index..end_index, match_style));
4916 offset = end_index;
4917 }
4918
4919 if offset < range.end {
4920 result.push((offset..range.end, syntax_highlight));
4921 }
4922 }
4923
4924 fn char_ix_after(ix: usize, text: &str) -> usize {
4925 ix + text[ix..].chars().next().unwrap().len_utf8()
4926 }
4927
4928 result
4929}
4930
4931fn styled_runs_for_completion_label<'a>(
4932 label: &'a CompletionLabel,
4933 default_color: Color,
4934 syntax_theme: &'a theme::SyntaxTheme,
4935) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
4936 const MUTED_OPACITY: usize = 165;
4937
4938 let mut muted_default_style = HighlightStyle {
4939 color: default_color,
4940 ..Default::default()
4941 };
4942 muted_default_style.color.a = ((default_color.a as usize * MUTED_OPACITY) / 255) as u8;
4943
4944 let mut prev_end = label.filter_range.end;
4945 label
4946 .runs
4947 .iter()
4948 .enumerate()
4949 .flat_map(move |(ix, (range, highlight_id))| {
4950 let style = if let Some(style) = highlight_id.style(syntax_theme) {
4951 style
4952 } else {
4953 return Default::default();
4954 };
4955 let mut muted_style = style.clone();
4956 muted_style.color.a = ((style.color.a as usize * MUTED_OPACITY) / 255) as u8;
4957
4958 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
4959 if range.start >= label.filter_range.end {
4960 if range.start > prev_end {
4961 runs.push((prev_end..range.start, muted_default_style));
4962 }
4963 runs.push((range.clone(), muted_style));
4964 } else if range.end <= label.filter_range.end {
4965 runs.push((range.clone(), style));
4966 } else {
4967 runs.push((range.start..label.filter_range.end, style));
4968 runs.push((label.filter_range.end..range.end, muted_style));
4969 }
4970 prev_end = cmp::max(prev_end, range.end);
4971
4972 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
4973 runs.push((prev_end..label.text.len(), muted_default_style));
4974 }
4975
4976 runs
4977 })
4978}
4979
4980#[cfg(test)]
4981mod tests {
4982 use super::*;
4983 use language::{FakeFile, LanguageConfig};
4984 use lsp::FakeLanguageServer;
4985 use std::{cell::RefCell, path::Path, rc::Rc, time::Instant};
4986 use text::Point;
4987 use unindent::Unindent;
4988 use util::test::sample_text;
4989
4990 #[gpui::test]
4991 fn test_undo_redo_with_selection_restoration(cx: &mut MutableAppContext) {
4992 let mut now = Instant::now();
4993 let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
4994 let group_interval = buffer.read(cx).transaction_group_interval();
4995 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
4996 let settings = EditorSettings::test(cx);
4997 let (_, editor) = cx.add_window(Default::default(), |cx| {
4998 build_editor(buffer.clone(), settings, cx)
4999 });
5000
5001 editor.update(cx, |editor, cx| {
5002 editor.start_transaction_at(now, cx);
5003 editor.select_ranges([2..4], None, cx);
5004 editor.insert("cd", cx);
5005 editor.end_transaction_at(now, cx);
5006 assert_eq!(editor.text(cx), "12cd56");
5007 assert_eq!(editor.selected_ranges(cx), vec![4..4]);
5008
5009 editor.start_transaction_at(now, cx);
5010 editor.select_ranges([4..5], None, cx);
5011 editor.insert("e", cx);
5012 editor.end_transaction_at(now, cx);
5013 assert_eq!(editor.text(cx), "12cde6");
5014 assert_eq!(editor.selected_ranges(cx), vec![5..5]);
5015
5016 now += group_interval + Duration::from_millis(1);
5017 editor.select_ranges([2..2], None, cx);
5018
5019 // Simulate an edit in another editor
5020 buffer.update(cx, |buffer, cx| {
5021 buffer.start_transaction_at(now, cx);
5022 buffer.edit([0..1], "a", cx);
5023 buffer.edit([1..1], "b", cx);
5024 buffer.end_transaction_at(now, cx);
5025 });
5026
5027 assert_eq!(editor.text(cx), "ab2cde6");
5028 assert_eq!(editor.selected_ranges(cx), vec![3..3]);
5029
5030 // Last transaction happened past the group interval in a different editor.
5031 // Undo it individually and don't restore selections.
5032 editor.undo(&Undo, cx);
5033 assert_eq!(editor.text(cx), "12cde6");
5034 assert_eq!(editor.selected_ranges(cx), vec![2..2]);
5035
5036 // First two transactions happened within the group interval in this editor.
5037 // Undo them together and restore selections.
5038 editor.undo(&Undo, cx);
5039 editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
5040 assert_eq!(editor.text(cx), "123456");
5041 assert_eq!(editor.selected_ranges(cx), vec![0..0]);
5042
5043 // Redo the first two transactions together.
5044 editor.redo(&Redo, cx);
5045 assert_eq!(editor.text(cx), "12cde6");
5046 assert_eq!(editor.selected_ranges(cx), vec![5..5]);
5047
5048 // Redo the last transaction on its own.
5049 editor.redo(&Redo, cx);
5050 assert_eq!(editor.text(cx), "ab2cde6");
5051 assert_eq!(editor.selected_ranges(cx), vec![6..6]);
5052
5053 // Test empty transactions.
5054 editor.start_transaction_at(now, cx);
5055 editor.end_transaction_at(now, cx);
5056 editor.undo(&Undo, cx);
5057 assert_eq!(editor.text(cx), "12cde6");
5058 });
5059 }
5060
5061 #[gpui::test]
5062 fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
5063 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
5064 let settings = EditorSettings::test(cx);
5065 let (_, editor) =
5066 cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5067
5068 editor.update(cx, |view, cx| {
5069 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
5070 });
5071
5072 assert_eq!(
5073 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5074 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
5075 );
5076
5077 editor.update(cx, |view, cx| {
5078 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
5079 });
5080
5081 assert_eq!(
5082 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5083 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
5084 );
5085
5086 editor.update(cx, |view, cx| {
5087 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
5088 });
5089
5090 assert_eq!(
5091 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5092 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
5093 );
5094
5095 editor.update(cx, |view, cx| {
5096 view.end_selection(cx);
5097 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
5098 });
5099
5100 assert_eq!(
5101 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5102 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
5103 );
5104
5105 editor.update(cx, |view, cx| {
5106 view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
5107 view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
5108 });
5109
5110 assert_eq!(
5111 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5112 [
5113 DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
5114 DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
5115 ]
5116 );
5117
5118 editor.update(cx, |view, cx| {
5119 view.end_selection(cx);
5120 });
5121
5122 assert_eq!(
5123 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5124 [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
5125 );
5126 }
5127
5128 #[gpui::test]
5129 fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
5130 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
5131 let settings = EditorSettings::test(cx);
5132 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5133
5134 view.update(cx, |view, cx| {
5135 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
5136 assert_eq!(
5137 view.selected_display_ranges(cx),
5138 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
5139 );
5140 });
5141
5142 view.update(cx, |view, cx| {
5143 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
5144 assert_eq!(
5145 view.selected_display_ranges(cx),
5146 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
5147 );
5148 });
5149
5150 view.update(cx, |view, cx| {
5151 view.cancel(&Cancel, cx);
5152 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
5153 assert_eq!(
5154 view.selected_display_ranges(cx),
5155 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
5156 );
5157 });
5158 }
5159
5160 #[gpui::test]
5161 fn test_navigation_history(cx: &mut gpui::MutableAppContext) {
5162 cx.add_window(Default::default(), |cx| {
5163 use workspace::ItemView;
5164 let nav_history = Rc::new(RefCell::new(workspace::NavHistory::default()));
5165 let settings = EditorSettings::test(&cx);
5166 let buffer = MultiBuffer::build_simple(&sample_text(30, 5, 'a'), cx);
5167 let mut editor = build_editor(buffer.clone(), settings, cx);
5168 editor.nav_history = Some(ItemNavHistory::new(nav_history.clone(), &cx.handle()));
5169
5170 // Move the cursor a small distance.
5171 // Nothing is added to the navigation history.
5172 editor.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
5173 editor.select_display_ranges(&[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)], cx);
5174 assert!(nav_history.borrow_mut().pop_backward().is_none());
5175
5176 // Move the cursor a large distance.
5177 // The history can jump back to the previous position.
5178 editor.select_display_ranges(&[DisplayPoint::new(13, 0)..DisplayPoint::new(13, 3)], cx);
5179 let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
5180 editor.navigate(nav_entry.data.unwrap(), cx);
5181 assert_eq!(nav_entry.item_view.id(), cx.view_id());
5182 assert_eq!(
5183 editor.selected_display_ranges(cx),
5184 &[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)]
5185 );
5186
5187 // Move the cursor a small distance via the mouse.
5188 // Nothing is added to the navigation history.
5189 editor.begin_selection(DisplayPoint::new(5, 0), false, 1, cx);
5190 editor.end_selection(cx);
5191 assert_eq!(
5192 editor.selected_display_ranges(cx),
5193 &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
5194 );
5195 assert!(nav_history.borrow_mut().pop_backward().is_none());
5196
5197 // Move the cursor a large distance via the mouse.
5198 // The history can jump back to the previous position.
5199 editor.begin_selection(DisplayPoint::new(15, 0), false, 1, cx);
5200 editor.end_selection(cx);
5201 assert_eq!(
5202 editor.selected_display_ranges(cx),
5203 &[DisplayPoint::new(15, 0)..DisplayPoint::new(15, 0)]
5204 );
5205 let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
5206 editor.navigate(nav_entry.data.unwrap(), cx);
5207 assert_eq!(nav_entry.item_view.id(), cx.view_id());
5208 assert_eq!(
5209 editor.selected_display_ranges(cx),
5210 &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
5211 );
5212
5213 editor
5214 });
5215 }
5216
5217 #[gpui::test]
5218 fn test_cancel(cx: &mut gpui::MutableAppContext) {
5219 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
5220 let settings = EditorSettings::test(cx);
5221 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5222
5223 view.update(cx, |view, cx| {
5224 view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
5225 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
5226 view.end_selection(cx);
5227
5228 view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
5229 view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
5230 view.end_selection(cx);
5231 assert_eq!(
5232 view.selected_display_ranges(cx),
5233 [
5234 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5235 DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
5236 ]
5237 );
5238 });
5239
5240 view.update(cx, |view, cx| {
5241 view.cancel(&Cancel, cx);
5242 assert_eq!(
5243 view.selected_display_ranges(cx),
5244 [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
5245 );
5246 });
5247
5248 view.update(cx, |view, cx| {
5249 view.cancel(&Cancel, cx);
5250 assert_eq!(
5251 view.selected_display_ranges(cx),
5252 [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
5253 );
5254 });
5255 }
5256
5257 #[gpui::test]
5258 fn test_fold(cx: &mut gpui::MutableAppContext) {
5259 let buffer = MultiBuffer::build_simple(
5260 &"
5261 impl Foo {
5262 // Hello!
5263
5264 fn a() {
5265 1
5266 }
5267
5268 fn b() {
5269 2
5270 }
5271
5272 fn c() {
5273 3
5274 }
5275 }
5276 "
5277 .unindent(),
5278 cx,
5279 );
5280 let settings = EditorSettings::test(&cx);
5281 let (_, view) = cx.add_window(Default::default(), |cx| {
5282 build_editor(buffer.clone(), settings, cx)
5283 });
5284
5285 view.update(cx, |view, cx| {
5286 view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx);
5287 view.fold(&Fold, cx);
5288 assert_eq!(
5289 view.display_text(cx),
5290 "
5291 impl Foo {
5292 // Hello!
5293
5294 fn a() {
5295 1
5296 }
5297
5298 fn b() {…
5299 }
5300
5301 fn c() {…
5302 }
5303 }
5304 "
5305 .unindent(),
5306 );
5307
5308 view.fold(&Fold, cx);
5309 assert_eq!(
5310 view.display_text(cx),
5311 "
5312 impl Foo {…
5313 }
5314 "
5315 .unindent(),
5316 );
5317
5318 view.unfold(&Unfold, cx);
5319 assert_eq!(
5320 view.display_text(cx),
5321 "
5322 impl Foo {
5323 // Hello!
5324
5325 fn a() {
5326 1
5327 }
5328
5329 fn b() {…
5330 }
5331
5332 fn c() {…
5333 }
5334 }
5335 "
5336 .unindent(),
5337 );
5338
5339 view.unfold(&Unfold, cx);
5340 assert_eq!(view.display_text(cx), buffer.read(cx).read(cx).text());
5341 });
5342 }
5343
5344 #[gpui::test]
5345 fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
5346 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
5347 let settings = EditorSettings::test(&cx);
5348 let (_, view) = cx.add_window(Default::default(), |cx| {
5349 build_editor(buffer.clone(), settings, cx)
5350 });
5351
5352 buffer.update(cx, |buffer, cx| {
5353 buffer.edit(
5354 vec![
5355 Point::new(1, 0)..Point::new(1, 0),
5356 Point::new(1, 1)..Point::new(1, 1),
5357 ],
5358 "\t",
5359 cx,
5360 );
5361 });
5362
5363 view.update(cx, |view, cx| {
5364 assert_eq!(
5365 view.selected_display_ranges(cx),
5366 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
5367 );
5368
5369 view.move_down(&MoveDown, cx);
5370 assert_eq!(
5371 view.selected_display_ranges(cx),
5372 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
5373 );
5374
5375 view.move_right(&MoveRight, cx);
5376 assert_eq!(
5377 view.selected_display_ranges(cx),
5378 &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
5379 );
5380
5381 view.move_left(&MoveLeft, cx);
5382 assert_eq!(
5383 view.selected_display_ranges(cx),
5384 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
5385 );
5386
5387 view.move_up(&MoveUp, cx);
5388 assert_eq!(
5389 view.selected_display_ranges(cx),
5390 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
5391 );
5392
5393 view.move_to_end(&MoveToEnd, cx);
5394 assert_eq!(
5395 view.selected_display_ranges(cx),
5396 &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
5397 );
5398
5399 view.move_to_beginning(&MoveToBeginning, cx);
5400 assert_eq!(
5401 view.selected_display_ranges(cx),
5402 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
5403 );
5404
5405 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx);
5406 view.select_to_beginning(&SelectToBeginning, cx);
5407 assert_eq!(
5408 view.selected_display_ranges(cx),
5409 &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
5410 );
5411
5412 view.select_to_end(&SelectToEnd, cx);
5413 assert_eq!(
5414 view.selected_display_ranges(cx),
5415 &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
5416 );
5417 });
5418 }
5419
5420 #[gpui::test]
5421 fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
5422 let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
5423 let settings = EditorSettings::test(&cx);
5424 let (_, view) = cx.add_window(Default::default(), |cx| {
5425 build_editor(buffer.clone(), settings, cx)
5426 });
5427
5428 assert_eq!('ⓐ'.len_utf8(), 3);
5429 assert_eq!('α'.len_utf8(), 2);
5430
5431 view.update(cx, |view, cx| {
5432 view.fold_ranges(
5433 vec![
5434 Point::new(0, 6)..Point::new(0, 12),
5435 Point::new(1, 2)..Point::new(1, 4),
5436 Point::new(2, 4)..Point::new(2, 8),
5437 ],
5438 cx,
5439 );
5440 assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
5441
5442 view.move_right(&MoveRight, cx);
5443 assert_eq!(
5444 view.selected_display_ranges(cx),
5445 &[empty_range(0, "ⓐ".len())]
5446 );
5447 view.move_right(&MoveRight, cx);
5448 assert_eq!(
5449 view.selected_display_ranges(cx),
5450 &[empty_range(0, "ⓐⓑ".len())]
5451 );
5452 view.move_right(&MoveRight, cx);
5453 assert_eq!(
5454 view.selected_display_ranges(cx),
5455 &[empty_range(0, "ⓐⓑ…".len())]
5456 );
5457
5458 view.move_down(&MoveDown, cx);
5459 assert_eq!(
5460 view.selected_display_ranges(cx),
5461 &[empty_range(1, "ab…".len())]
5462 );
5463 view.move_left(&MoveLeft, cx);
5464 assert_eq!(
5465 view.selected_display_ranges(cx),
5466 &[empty_range(1, "ab".len())]
5467 );
5468 view.move_left(&MoveLeft, cx);
5469 assert_eq!(
5470 view.selected_display_ranges(cx),
5471 &[empty_range(1, "a".len())]
5472 );
5473
5474 view.move_down(&MoveDown, cx);
5475 assert_eq!(
5476 view.selected_display_ranges(cx),
5477 &[empty_range(2, "α".len())]
5478 );
5479 view.move_right(&MoveRight, cx);
5480 assert_eq!(
5481 view.selected_display_ranges(cx),
5482 &[empty_range(2, "αβ".len())]
5483 );
5484 view.move_right(&MoveRight, cx);
5485 assert_eq!(
5486 view.selected_display_ranges(cx),
5487 &[empty_range(2, "αβ…".len())]
5488 );
5489 view.move_right(&MoveRight, cx);
5490 assert_eq!(
5491 view.selected_display_ranges(cx),
5492 &[empty_range(2, "αβ…ε".len())]
5493 );
5494
5495 view.move_up(&MoveUp, cx);
5496 assert_eq!(
5497 view.selected_display_ranges(cx),
5498 &[empty_range(1, "ab…e".len())]
5499 );
5500 view.move_up(&MoveUp, cx);
5501 assert_eq!(
5502 view.selected_display_ranges(cx),
5503 &[empty_range(0, "ⓐⓑ…ⓔ".len())]
5504 );
5505 view.move_left(&MoveLeft, cx);
5506 assert_eq!(
5507 view.selected_display_ranges(cx),
5508 &[empty_range(0, "ⓐⓑ…".len())]
5509 );
5510 view.move_left(&MoveLeft, cx);
5511 assert_eq!(
5512 view.selected_display_ranges(cx),
5513 &[empty_range(0, "ⓐⓑ".len())]
5514 );
5515 view.move_left(&MoveLeft, cx);
5516 assert_eq!(
5517 view.selected_display_ranges(cx),
5518 &[empty_range(0, "ⓐ".len())]
5519 );
5520 });
5521 }
5522
5523 #[gpui::test]
5524 fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
5525 let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
5526 let settings = EditorSettings::test(&cx);
5527 let (_, view) = cx.add_window(Default::default(), |cx| {
5528 build_editor(buffer.clone(), settings, cx)
5529 });
5530 view.update(cx, |view, cx| {
5531 view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx);
5532 view.move_down(&MoveDown, cx);
5533 assert_eq!(
5534 view.selected_display_ranges(cx),
5535 &[empty_range(1, "abcd".len())]
5536 );
5537
5538 view.move_down(&MoveDown, cx);
5539 assert_eq!(
5540 view.selected_display_ranges(cx),
5541 &[empty_range(2, "αβγ".len())]
5542 );
5543
5544 view.move_down(&MoveDown, cx);
5545 assert_eq!(
5546 view.selected_display_ranges(cx),
5547 &[empty_range(3, "abcd".len())]
5548 );
5549
5550 view.move_down(&MoveDown, cx);
5551 assert_eq!(
5552 view.selected_display_ranges(cx),
5553 &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
5554 );
5555
5556 view.move_up(&MoveUp, cx);
5557 assert_eq!(
5558 view.selected_display_ranges(cx),
5559 &[empty_range(3, "abcd".len())]
5560 );
5561
5562 view.move_up(&MoveUp, cx);
5563 assert_eq!(
5564 view.selected_display_ranges(cx),
5565 &[empty_range(2, "αβγ".len())]
5566 );
5567 });
5568 }
5569
5570 #[gpui::test]
5571 fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
5572 let buffer = MultiBuffer::build_simple("abc\n def", cx);
5573 let settings = EditorSettings::test(&cx);
5574 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5575 view.update(cx, |view, cx| {
5576 view.select_display_ranges(
5577 &[
5578 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5579 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
5580 ],
5581 cx,
5582 );
5583 });
5584
5585 view.update(cx, |view, cx| {
5586 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
5587 assert_eq!(
5588 view.selected_display_ranges(cx),
5589 &[
5590 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
5591 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
5592 ]
5593 );
5594 });
5595
5596 view.update(cx, |view, cx| {
5597 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
5598 assert_eq!(
5599 view.selected_display_ranges(cx),
5600 &[
5601 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
5602 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5603 ]
5604 );
5605 });
5606
5607 view.update(cx, |view, cx| {
5608 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
5609 assert_eq!(
5610 view.selected_display_ranges(cx),
5611 &[
5612 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
5613 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
5614 ]
5615 );
5616 });
5617
5618 view.update(cx, |view, cx| {
5619 view.move_to_end_of_line(&MoveToEndOfLine, cx);
5620 assert_eq!(
5621 view.selected_display_ranges(cx),
5622 &[
5623 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5624 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
5625 ]
5626 );
5627 });
5628
5629 // Moving to the end of line again is a no-op.
5630 view.update(cx, |view, cx| {
5631 view.move_to_end_of_line(&MoveToEndOfLine, cx);
5632 assert_eq!(
5633 view.selected_display_ranges(cx),
5634 &[
5635 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5636 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
5637 ]
5638 );
5639 });
5640
5641 view.update(cx, |view, cx| {
5642 view.move_left(&MoveLeft, cx);
5643 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
5644 assert_eq!(
5645 view.selected_display_ranges(cx),
5646 &[
5647 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
5648 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
5649 ]
5650 );
5651 });
5652
5653 view.update(cx, |view, cx| {
5654 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
5655 assert_eq!(
5656 view.selected_display_ranges(cx),
5657 &[
5658 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
5659 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
5660 ]
5661 );
5662 });
5663
5664 view.update(cx, |view, cx| {
5665 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
5666 assert_eq!(
5667 view.selected_display_ranges(cx),
5668 &[
5669 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
5670 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
5671 ]
5672 );
5673 });
5674
5675 view.update(cx, |view, cx| {
5676 view.select_to_end_of_line(&SelectToEndOfLine, cx);
5677 assert_eq!(
5678 view.selected_display_ranges(cx),
5679 &[
5680 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
5681 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
5682 ]
5683 );
5684 });
5685
5686 view.update(cx, |view, cx| {
5687 view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
5688 assert_eq!(view.display_text(cx), "ab\n de");
5689 assert_eq!(
5690 view.selected_display_ranges(cx),
5691 &[
5692 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5693 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
5694 ]
5695 );
5696 });
5697
5698 view.update(cx, |view, cx| {
5699 view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
5700 assert_eq!(view.display_text(cx), "\n");
5701 assert_eq!(
5702 view.selected_display_ranges(cx),
5703 &[
5704 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
5705 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5706 ]
5707 );
5708 });
5709 }
5710
5711 #[gpui::test]
5712 fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
5713 let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n {baz.qux()}", cx);
5714 let settings = EditorSettings::test(&cx);
5715 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5716 view.update(cx, |view, cx| {
5717 view.select_display_ranges(
5718 &[
5719 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
5720 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
5721 ],
5722 cx,
5723 );
5724 });
5725
5726 view.update(cx, |view, cx| {
5727 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
5728 assert_eq!(
5729 view.selected_display_ranges(cx),
5730 &[
5731 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
5732 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
5733 ]
5734 );
5735 });
5736
5737 view.update(cx, |view, cx| {
5738 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
5739 assert_eq!(
5740 view.selected_display_ranges(cx),
5741 &[
5742 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
5743 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
5744 ]
5745 );
5746 });
5747
5748 view.update(cx, |view, cx| {
5749 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
5750 assert_eq!(
5751 view.selected_display_ranges(cx),
5752 &[
5753 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
5754 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
5755 ]
5756 );
5757 });
5758
5759 view.update(cx, |view, cx| {
5760 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
5761 assert_eq!(
5762 view.selected_display_ranges(cx),
5763 &[
5764 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
5765 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5766 ]
5767 );
5768 });
5769
5770 view.update(cx, |view, cx| {
5771 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
5772 assert_eq!(
5773 view.selected_display_ranges(cx),
5774 &[
5775 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
5776 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
5777 ]
5778 );
5779 });
5780
5781 view.update(cx, |view, cx| {
5782 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
5783 assert_eq!(
5784 view.selected_display_ranges(cx),
5785 &[
5786 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5787 DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
5788 ]
5789 );
5790 });
5791
5792 view.update(cx, |view, cx| {
5793 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
5794 assert_eq!(
5795 view.selected_display_ranges(cx),
5796 &[
5797 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
5798 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5799 ]
5800 );
5801 });
5802
5803 view.update(cx, |view, cx| {
5804 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
5805 assert_eq!(
5806 view.selected_display_ranges(cx),
5807 &[
5808 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
5809 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
5810 ]
5811 );
5812 });
5813
5814 view.update(cx, |view, cx| {
5815 view.move_right(&MoveRight, cx);
5816 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
5817 assert_eq!(
5818 view.selected_display_ranges(cx),
5819 &[
5820 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
5821 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
5822 ]
5823 );
5824 });
5825
5826 view.update(cx, |view, cx| {
5827 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
5828 assert_eq!(
5829 view.selected_display_ranges(cx),
5830 &[
5831 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
5832 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
5833 ]
5834 );
5835 });
5836
5837 view.update(cx, |view, cx| {
5838 view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
5839 assert_eq!(
5840 view.selected_display_ranges(cx),
5841 &[
5842 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
5843 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
5844 ]
5845 );
5846 });
5847 }
5848
5849 #[gpui::test]
5850 fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
5851 let buffer = MultiBuffer::build_simple("use one::{\n two::three::four::five\n};", cx);
5852 let settings = EditorSettings::test(&cx);
5853 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5854
5855 view.update(cx, |view, cx| {
5856 view.set_wrap_width(Some(140.), cx);
5857 assert_eq!(
5858 view.display_text(cx),
5859 "use one::{\n two::three::\n four::five\n};"
5860 );
5861
5862 view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx);
5863
5864 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
5865 assert_eq!(
5866 view.selected_display_ranges(cx),
5867 &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
5868 );
5869
5870 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
5871 assert_eq!(
5872 view.selected_display_ranges(cx),
5873 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
5874 );
5875
5876 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
5877 assert_eq!(
5878 view.selected_display_ranges(cx),
5879 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
5880 );
5881
5882 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
5883 assert_eq!(
5884 view.selected_display_ranges(cx),
5885 &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
5886 );
5887
5888 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
5889 assert_eq!(
5890 view.selected_display_ranges(cx),
5891 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
5892 );
5893
5894 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
5895 assert_eq!(
5896 view.selected_display_ranges(cx),
5897 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
5898 );
5899 });
5900 }
5901
5902 #[gpui::test]
5903 fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
5904 let buffer = MultiBuffer::build_simple("one two three four", cx);
5905 let settings = EditorSettings::test(&cx);
5906 let (_, view) = cx.add_window(Default::default(), |cx| {
5907 build_editor(buffer.clone(), settings, cx)
5908 });
5909
5910 view.update(cx, |view, cx| {
5911 view.select_display_ranges(
5912 &[
5913 // an empty selection - the preceding word fragment is deleted
5914 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5915 // characters selected - they are deleted
5916 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
5917 ],
5918 cx,
5919 );
5920 view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
5921 });
5922
5923 assert_eq!(buffer.read(cx).read(cx).text(), "e two te four");
5924
5925 view.update(cx, |view, cx| {
5926 view.select_display_ranges(
5927 &[
5928 // an empty selection - the following word fragment is deleted
5929 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5930 // characters selected - they are deleted
5931 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
5932 ],
5933 cx,
5934 );
5935 view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
5936 });
5937
5938 assert_eq!(buffer.read(cx).read(cx).text(), "e t te our");
5939 }
5940
5941 #[gpui::test]
5942 fn test_newline(cx: &mut gpui::MutableAppContext) {
5943 let buffer = MultiBuffer::build_simple("aaaa\n bbbb\n", cx);
5944 let settings = EditorSettings::test(&cx);
5945 let (_, view) = cx.add_window(Default::default(), |cx| {
5946 build_editor(buffer.clone(), settings, cx)
5947 });
5948
5949 view.update(cx, |view, cx| {
5950 view.select_display_ranges(
5951 &[
5952 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5953 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
5954 DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
5955 ],
5956 cx,
5957 );
5958
5959 view.newline(&Newline, cx);
5960 assert_eq!(view.text(cx), "aa\naa\n \n bb\n bb\n");
5961 });
5962 }
5963
5964 #[gpui::test]
5965 fn test_newline_with_old_selections(cx: &mut gpui::MutableAppContext) {
5966 let buffer = MultiBuffer::build_simple(
5967 "
5968 a
5969 b(
5970 X
5971 )
5972 c(
5973 X
5974 )
5975 "
5976 .unindent()
5977 .as_str(),
5978 cx,
5979 );
5980
5981 let settings = EditorSettings::test(&cx);
5982 let (_, editor) = cx.add_window(Default::default(), |cx| {
5983 let mut editor = build_editor(buffer.clone(), settings, cx);
5984 editor.select_ranges(
5985 [
5986 Point::new(2, 4)..Point::new(2, 5),
5987 Point::new(5, 4)..Point::new(5, 5),
5988 ],
5989 None,
5990 cx,
5991 );
5992 editor
5993 });
5994
5995 // Edit the buffer directly, deleting ranges surrounding the editor's selections
5996 buffer.update(cx, |buffer, cx| {
5997 buffer.edit(
5998 [
5999 Point::new(1, 2)..Point::new(3, 0),
6000 Point::new(4, 2)..Point::new(6, 0),
6001 ],
6002 "",
6003 cx,
6004 );
6005 assert_eq!(
6006 buffer.read(cx).text(),
6007 "
6008 a
6009 b()
6010 c()
6011 "
6012 .unindent()
6013 );
6014 });
6015
6016 editor.update(cx, |editor, cx| {
6017 assert_eq!(
6018 editor.selected_ranges(cx),
6019 &[
6020 Point::new(1, 2)..Point::new(1, 2),
6021 Point::new(2, 2)..Point::new(2, 2),
6022 ],
6023 );
6024
6025 editor.newline(&Newline, cx);
6026 assert_eq!(
6027 editor.text(cx),
6028 "
6029 a
6030 b(
6031 )
6032 c(
6033 )
6034 "
6035 .unindent()
6036 );
6037
6038 // The selections are moved after the inserted newlines
6039 assert_eq!(
6040 editor.selected_ranges(cx),
6041 &[
6042 Point::new(2, 0)..Point::new(2, 0),
6043 Point::new(4, 0)..Point::new(4, 0),
6044 ],
6045 );
6046 });
6047 }
6048
6049 #[gpui::test]
6050 fn test_insert_with_old_selections(cx: &mut gpui::MutableAppContext) {
6051 let buffer = MultiBuffer::build_simple("a( X ), b( Y ), c( Z )", cx);
6052
6053 let settings = EditorSettings::test(&cx);
6054 let (_, editor) = cx.add_window(Default::default(), |cx| {
6055 let mut editor = build_editor(buffer.clone(), settings, cx);
6056 editor.select_ranges([3..4, 11..12, 19..20], None, cx);
6057 editor
6058 });
6059
6060 // Edit the buffer directly, deleting ranges surrounding the editor's selections
6061 buffer.update(cx, |buffer, cx| {
6062 buffer.edit([2..5, 10..13, 18..21], "", cx);
6063 assert_eq!(buffer.read(cx).text(), "a(), b(), c()".unindent());
6064 });
6065
6066 editor.update(cx, |editor, cx| {
6067 assert_eq!(editor.selected_ranges(cx), &[2..2, 7..7, 12..12],);
6068
6069 editor.insert("Z", cx);
6070 assert_eq!(editor.text(cx), "a(Z), b(Z), c(Z)");
6071
6072 // The selections are moved after the inserted characters
6073 assert_eq!(editor.selected_ranges(cx), &[3..3, 9..9, 15..15],);
6074 });
6075 }
6076
6077 #[gpui::test]
6078 fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
6079 let buffer = MultiBuffer::build_simple(" one two\nthree\n four", cx);
6080 let settings = EditorSettings::test(&cx);
6081 let (_, view) = cx.add_window(Default::default(), |cx| {
6082 build_editor(buffer.clone(), settings, cx)
6083 });
6084
6085 view.update(cx, |view, cx| {
6086 // two selections on the same line
6087 view.select_display_ranges(
6088 &[
6089 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
6090 DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
6091 ],
6092 cx,
6093 );
6094
6095 // indent from mid-tabstop to full tabstop
6096 view.tab(&Tab, cx);
6097 assert_eq!(view.text(cx), " one two\nthree\n four");
6098 assert_eq!(
6099 view.selected_display_ranges(cx),
6100 &[
6101 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
6102 DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
6103 ]
6104 );
6105
6106 // outdent from 1 tabstop to 0 tabstops
6107 view.outdent(&Outdent, cx);
6108 assert_eq!(view.text(cx), "one two\nthree\n four");
6109 assert_eq!(
6110 view.selected_display_ranges(cx),
6111 &[
6112 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
6113 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
6114 ]
6115 );
6116
6117 // select across line ending
6118 view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx);
6119
6120 // indent and outdent affect only the preceding line
6121 view.tab(&Tab, cx);
6122 assert_eq!(view.text(cx), "one two\n three\n four");
6123 assert_eq!(
6124 view.selected_display_ranges(cx),
6125 &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
6126 );
6127 view.outdent(&Outdent, cx);
6128 assert_eq!(view.text(cx), "one two\nthree\n four");
6129 assert_eq!(
6130 view.selected_display_ranges(cx),
6131 &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
6132 );
6133
6134 // Ensure that indenting/outdenting works when the cursor is at column 0.
6135 view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
6136 view.tab(&Tab, cx);
6137 assert_eq!(view.text(cx), "one two\n three\n four");
6138 assert_eq!(
6139 view.selected_display_ranges(cx),
6140 &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
6141 );
6142
6143 view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
6144 view.outdent(&Outdent, cx);
6145 assert_eq!(view.text(cx), "one two\nthree\n four");
6146 assert_eq!(
6147 view.selected_display_ranges(cx),
6148 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6149 );
6150 });
6151 }
6152
6153 #[gpui::test]
6154 fn test_backspace(cx: &mut gpui::MutableAppContext) {
6155 let buffer =
6156 MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
6157 let settings = EditorSettings::test(&cx);
6158 let (_, view) = cx.add_window(Default::default(), |cx| {
6159 build_editor(buffer.clone(), settings, cx)
6160 });
6161
6162 view.update(cx, |view, cx| {
6163 view.select_display_ranges(
6164 &[
6165 // an empty selection - the preceding character is deleted
6166 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6167 // one character selected - it is deleted
6168 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
6169 // a line suffix selected - it is deleted
6170 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
6171 ],
6172 cx,
6173 );
6174 view.backspace(&Backspace, cx);
6175 });
6176
6177 assert_eq!(
6178 buffer.read(cx).read(cx).text(),
6179 "oe two three\nfou five six\nseven ten\n"
6180 );
6181 }
6182
6183 #[gpui::test]
6184 fn test_delete(cx: &mut gpui::MutableAppContext) {
6185 let buffer =
6186 MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
6187 let settings = EditorSettings::test(&cx);
6188 let (_, view) = cx.add_window(Default::default(), |cx| {
6189 build_editor(buffer.clone(), settings, cx)
6190 });
6191
6192 view.update(cx, |view, cx| {
6193 view.select_display_ranges(
6194 &[
6195 // an empty selection - the following character is deleted
6196 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6197 // one character selected - it is deleted
6198 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
6199 // a line suffix selected - it is deleted
6200 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
6201 ],
6202 cx,
6203 );
6204 view.delete(&Delete, cx);
6205 });
6206
6207 assert_eq!(
6208 buffer.read(cx).read(cx).text(),
6209 "on two three\nfou five six\nseven ten\n"
6210 );
6211 }
6212
6213 #[gpui::test]
6214 fn test_delete_line(cx: &mut gpui::MutableAppContext) {
6215 let settings = EditorSettings::test(&cx);
6216 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
6217 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6218 view.update(cx, |view, cx| {
6219 view.select_display_ranges(
6220 &[
6221 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6222 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
6223 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
6224 ],
6225 cx,
6226 );
6227 view.delete_line(&DeleteLine, cx);
6228 assert_eq!(view.display_text(cx), "ghi");
6229 assert_eq!(
6230 view.selected_display_ranges(cx),
6231 vec![
6232 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6233 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
6234 ]
6235 );
6236 });
6237
6238 let settings = EditorSettings::test(&cx);
6239 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
6240 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6241 view.update(cx, |view, cx| {
6242 view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx);
6243 view.delete_line(&DeleteLine, cx);
6244 assert_eq!(view.display_text(cx), "ghi\n");
6245 assert_eq!(
6246 view.selected_display_ranges(cx),
6247 vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
6248 );
6249 });
6250 }
6251
6252 #[gpui::test]
6253 fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
6254 let settings = EditorSettings::test(&cx);
6255 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
6256 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6257 view.update(cx, |view, cx| {
6258 view.select_display_ranges(
6259 &[
6260 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
6261 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6262 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6263 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
6264 ],
6265 cx,
6266 );
6267 view.duplicate_line(&DuplicateLine, cx);
6268 assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
6269 assert_eq!(
6270 view.selected_display_ranges(cx),
6271 vec![
6272 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
6273 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6274 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
6275 DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
6276 ]
6277 );
6278 });
6279
6280 let settings = EditorSettings::test(&cx);
6281 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
6282 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6283 view.update(cx, |view, cx| {
6284 view.select_display_ranges(
6285 &[
6286 DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
6287 DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
6288 ],
6289 cx,
6290 );
6291 view.duplicate_line(&DuplicateLine, cx);
6292 assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
6293 assert_eq!(
6294 view.selected_display_ranges(cx),
6295 vec![
6296 DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
6297 DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
6298 ]
6299 );
6300 });
6301 }
6302
6303 #[gpui::test]
6304 fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
6305 let settings = EditorSettings::test(&cx);
6306 let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
6307 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6308 view.update(cx, |view, cx| {
6309 view.fold_ranges(
6310 vec![
6311 Point::new(0, 2)..Point::new(1, 2),
6312 Point::new(2, 3)..Point::new(4, 1),
6313 Point::new(7, 0)..Point::new(8, 4),
6314 ],
6315 cx,
6316 );
6317 view.select_display_ranges(
6318 &[
6319 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6320 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
6321 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
6322 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
6323 ],
6324 cx,
6325 );
6326 assert_eq!(
6327 view.display_text(cx),
6328 "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
6329 );
6330
6331 view.move_line_up(&MoveLineUp, cx);
6332 assert_eq!(
6333 view.display_text(cx),
6334 "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
6335 );
6336 assert_eq!(
6337 view.selected_display_ranges(cx),
6338 vec![
6339 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6340 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
6341 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
6342 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
6343 ]
6344 );
6345 });
6346
6347 view.update(cx, |view, cx| {
6348 view.move_line_down(&MoveLineDown, cx);
6349 assert_eq!(
6350 view.display_text(cx),
6351 "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
6352 );
6353 assert_eq!(
6354 view.selected_display_ranges(cx),
6355 vec![
6356 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6357 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
6358 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
6359 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
6360 ]
6361 );
6362 });
6363
6364 view.update(cx, |view, cx| {
6365 view.move_line_down(&MoveLineDown, cx);
6366 assert_eq!(
6367 view.display_text(cx),
6368 "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
6369 );
6370 assert_eq!(
6371 view.selected_display_ranges(cx),
6372 vec![
6373 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
6374 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
6375 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
6376 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
6377 ]
6378 );
6379 });
6380
6381 view.update(cx, |view, cx| {
6382 view.move_line_up(&MoveLineUp, cx);
6383 assert_eq!(
6384 view.display_text(cx),
6385 "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
6386 );
6387 assert_eq!(
6388 view.selected_display_ranges(cx),
6389 vec![
6390 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6391 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
6392 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
6393 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
6394 ]
6395 );
6396 });
6397 }
6398
6399 #[gpui::test]
6400 fn test_move_line_up_down_with_blocks(cx: &mut gpui::MutableAppContext) {
6401 let settings = EditorSettings::test(&cx);
6402 let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
6403 let snapshot = buffer.read(cx).snapshot(cx);
6404 let (_, editor) =
6405 cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6406 editor.update(cx, |editor, cx| {
6407 editor.insert_blocks(
6408 [BlockProperties {
6409 position: snapshot.anchor_after(Point::new(2, 0)),
6410 disposition: BlockDisposition::Below,
6411 height: 1,
6412 render: Arc::new(|_| Empty::new().boxed()),
6413 }],
6414 cx,
6415 );
6416 editor.select_ranges([Point::new(2, 0)..Point::new(2, 0)], None, cx);
6417 editor.move_line_down(&MoveLineDown, cx);
6418 });
6419 }
6420
6421 #[gpui::test]
6422 fn test_clipboard(cx: &mut gpui::MutableAppContext) {
6423 let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
6424 let settings = EditorSettings::test(&cx);
6425 let view = cx
6426 .add_window(Default::default(), |cx| {
6427 build_editor(buffer.clone(), settings, cx)
6428 })
6429 .1;
6430
6431 // Cut with three selections. Clipboard text is divided into three slices.
6432 view.update(cx, |view, cx| {
6433 view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
6434 view.cut(&Cut, cx);
6435 assert_eq!(view.display_text(cx), "two four six ");
6436 });
6437
6438 // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
6439 view.update(cx, |view, cx| {
6440 view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
6441 view.paste(&Paste, cx);
6442 assert_eq!(view.display_text(cx), "two one✅ four three six five ");
6443 assert_eq!(
6444 view.selected_display_ranges(cx),
6445 &[
6446 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
6447 DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
6448 DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
6449 ]
6450 );
6451 });
6452
6453 // Paste again but with only two cursors. Since the number of cursors doesn't
6454 // match the number of slices in the clipboard, the entire clipboard text
6455 // is pasted at each cursor.
6456 view.update(cx, |view, cx| {
6457 view.select_ranges(vec![0..0, 31..31], None, cx);
6458 view.handle_input(&Input("( ".into()), cx);
6459 view.paste(&Paste, cx);
6460 view.handle_input(&Input(") ".into()), cx);
6461 assert_eq!(
6462 view.display_text(cx),
6463 "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
6464 );
6465 });
6466
6467 view.update(cx, |view, cx| {
6468 view.select_ranges(vec![0..0], None, cx);
6469 view.handle_input(&Input("123\n4567\n89\n".into()), cx);
6470 assert_eq!(
6471 view.display_text(cx),
6472 "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
6473 );
6474 });
6475
6476 // Cut with three selections, one of which is full-line.
6477 view.update(cx, |view, cx| {
6478 view.select_display_ranges(
6479 &[
6480 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
6481 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6482 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
6483 ],
6484 cx,
6485 );
6486 view.cut(&Cut, cx);
6487 assert_eq!(
6488 view.display_text(cx),
6489 "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
6490 );
6491 });
6492
6493 // Paste with three selections, noticing how the copied selection that was full-line
6494 // gets inserted before the second cursor.
6495 view.update(cx, |view, cx| {
6496 view.select_display_ranges(
6497 &[
6498 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6499 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6500 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
6501 ],
6502 cx,
6503 );
6504 view.paste(&Paste, cx);
6505 assert_eq!(
6506 view.display_text(cx),
6507 "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
6508 );
6509 assert_eq!(
6510 view.selected_display_ranges(cx),
6511 &[
6512 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6513 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
6514 DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
6515 ]
6516 );
6517 });
6518
6519 // Copy with a single cursor only, which writes the whole line into the clipboard.
6520 view.update(cx, |view, cx| {
6521 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx);
6522 view.copy(&Copy, cx);
6523 });
6524
6525 // Paste with three selections, noticing how the copied full-line selection is inserted
6526 // before the empty selections but replaces the selection that is non-empty.
6527 view.update(cx, |view, cx| {
6528 view.select_display_ranges(
6529 &[
6530 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6531 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
6532 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
6533 ],
6534 cx,
6535 );
6536 view.paste(&Paste, cx);
6537 assert_eq!(
6538 view.display_text(cx),
6539 "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
6540 );
6541 assert_eq!(
6542 view.selected_display_ranges(cx),
6543 &[
6544 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6545 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
6546 DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
6547 ]
6548 );
6549 });
6550 }
6551
6552 #[gpui::test]
6553 fn test_select_all(cx: &mut gpui::MutableAppContext) {
6554 let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
6555 let settings = EditorSettings::test(&cx);
6556 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6557 view.update(cx, |view, cx| {
6558 view.select_all(&SelectAll, cx);
6559 assert_eq!(
6560 view.selected_display_ranges(cx),
6561 &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
6562 );
6563 });
6564 }
6565
6566 #[gpui::test]
6567 fn test_select_line(cx: &mut gpui::MutableAppContext) {
6568 let settings = EditorSettings::test(&cx);
6569 let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
6570 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6571 view.update(cx, |view, cx| {
6572 view.select_display_ranges(
6573 &[
6574 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
6575 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6576 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6577 DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
6578 ],
6579 cx,
6580 );
6581 view.select_line(&SelectLine, cx);
6582 assert_eq!(
6583 view.selected_display_ranges(cx),
6584 vec![
6585 DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
6586 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
6587 ]
6588 );
6589 });
6590
6591 view.update(cx, |view, cx| {
6592 view.select_line(&SelectLine, cx);
6593 assert_eq!(
6594 view.selected_display_ranges(cx),
6595 vec![
6596 DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
6597 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
6598 ]
6599 );
6600 });
6601
6602 view.update(cx, |view, cx| {
6603 view.select_line(&SelectLine, cx);
6604 assert_eq!(
6605 view.selected_display_ranges(cx),
6606 vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
6607 );
6608 });
6609 }
6610
6611 #[gpui::test]
6612 fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
6613 let settings = EditorSettings::test(&cx);
6614 let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
6615 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6616 view.update(cx, |view, cx| {
6617 view.fold_ranges(
6618 vec![
6619 Point::new(0, 2)..Point::new(1, 2),
6620 Point::new(2, 3)..Point::new(4, 1),
6621 Point::new(7, 0)..Point::new(8, 4),
6622 ],
6623 cx,
6624 );
6625 view.select_display_ranges(
6626 &[
6627 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
6628 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6629 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6630 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
6631 ],
6632 cx,
6633 );
6634 assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
6635 });
6636
6637 view.update(cx, |view, cx| {
6638 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
6639 assert_eq!(
6640 view.display_text(cx),
6641 "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
6642 );
6643 assert_eq!(
6644 view.selected_display_ranges(cx),
6645 [
6646 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6647 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6648 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
6649 DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
6650 ]
6651 );
6652 });
6653
6654 view.update(cx, |view, cx| {
6655 view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx);
6656 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
6657 assert_eq!(
6658 view.display_text(cx),
6659 "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
6660 );
6661 assert_eq!(
6662 view.selected_display_ranges(cx),
6663 [
6664 DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
6665 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
6666 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
6667 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
6668 DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
6669 DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
6670 DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
6671 DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
6672 ]
6673 );
6674 });
6675 }
6676
6677 #[gpui::test]
6678 fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
6679 let settings = EditorSettings::test(&cx);
6680 let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
6681 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6682
6683 view.update(cx, |view, cx| {
6684 view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx);
6685 });
6686 view.update(cx, |view, cx| {
6687 view.add_selection_above(&AddSelectionAbove, cx);
6688 assert_eq!(
6689 view.selected_display_ranges(cx),
6690 vec![
6691 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6692 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
6693 ]
6694 );
6695 });
6696
6697 view.update(cx, |view, cx| {
6698 view.add_selection_above(&AddSelectionAbove, cx);
6699 assert_eq!(
6700 view.selected_display_ranges(cx),
6701 vec![
6702 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6703 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
6704 ]
6705 );
6706 });
6707
6708 view.update(cx, |view, cx| {
6709 view.add_selection_below(&AddSelectionBelow, cx);
6710 assert_eq!(
6711 view.selected_display_ranges(cx),
6712 vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
6713 );
6714 });
6715
6716 view.update(cx, |view, cx| {
6717 view.add_selection_below(&AddSelectionBelow, cx);
6718 assert_eq!(
6719 view.selected_display_ranges(cx),
6720 vec![
6721 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
6722 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
6723 ]
6724 );
6725 });
6726
6727 view.update(cx, |view, cx| {
6728 view.add_selection_below(&AddSelectionBelow, cx);
6729 assert_eq!(
6730 view.selected_display_ranges(cx),
6731 vec![
6732 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
6733 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
6734 ]
6735 );
6736 });
6737
6738 view.update(cx, |view, cx| {
6739 view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx);
6740 });
6741 view.update(cx, |view, cx| {
6742 view.add_selection_below(&AddSelectionBelow, cx);
6743 assert_eq!(
6744 view.selected_display_ranges(cx),
6745 vec![
6746 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
6747 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
6748 ]
6749 );
6750 });
6751
6752 view.update(cx, |view, cx| {
6753 view.add_selection_below(&AddSelectionBelow, cx);
6754 assert_eq!(
6755 view.selected_display_ranges(cx),
6756 vec![
6757 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
6758 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
6759 ]
6760 );
6761 });
6762
6763 view.update(cx, |view, cx| {
6764 view.add_selection_above(&AddSelectionAbove, cx);
6765 assert_eq!(
6766 view.selected_display_ranges(cx),
6767 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
6768 );
6769 });
6770
6771 view.update(cx, |view, cx| {
6772 view.add_selection_above(&AddSelectionAbove, cx);
6773 assert_eq!(
6774 view.selected_display_ranges(cx),
6775 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
6776 );
6777 });
6778
6779 view.update(cx, |view, cx| {
6780 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx);
6781 view.add_selection_below(&AddSelectionBelow, cx);
6782 assert_eq!(
6783 view.selected_display_ranges(cx),
6784 vec![
6785 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
6786 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
6787 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
6788 ]
6789 );
6790 });
6791
6792 view.update(cx, |view, cx| {
6793 view.add_selection_below(&AddSelectionBelow, cx);
6794 assert_eq!(
6795 view.selected_display_ranges(cx),
6796 vec![
6797 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
6798 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
6799 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
6800 DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
6801 ]
6802 );
6803 });
6804
6805 view.update(cx, |view, cx| {
6806 view.add_selection_above(&AddSelectionAbove, cx);
6807 assert_eq!(
6808 view.selected_display_ranges(cx),
6809 vec![
6810 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
6811 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
6812 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
6813 ]
6814 );
6815 });
6816
6817 view.update(cx, |view, cx| {
6818 view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx);
6819 });
6820 view.update(cx, |view, cx| {
6821 view.add_selection_above(&AddSelectionAbove, cx);
6822 assert_eq!(
6823 view.selected_display_ranges(cx),
6824 vec![
6825 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
6826 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
6827 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
6828 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
6829 ]
6830 );
6831 });
6832
6833 view.update(cx, |view, cx| {
6834 view.add_selection_below(&AddSelectionBelow, cx);
6835 assert_eq!(
6836 view.selected_display_ranges(cx),
6837 vec![
6838 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
6839 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
6840 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
6841 ]
6842 );
6843 });
6844 }
6845
6846 #[gpui::test]
6847 async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
6848 let settings = cx.read(EditorSettings::test);
6849 let language = Arc::new(Language::new(
6850 LanguageConfig::default(),
6851 Some(tree_sitter_rust::language()),
6852 ));
6853
6854 let text = r#"
6855 use mod1::mod2::{mod3, mod4};
6856
6857 fn fn_1(param1: bool, param2: &str) {
6858 let var1 = "text";
6859 }
6860 "#
6861 .unindent();
6862
6863 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
6864 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6865 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
6866 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
6867 .await;
6868
6869 view.update(&mut cx, |view, cx| {
6870 view.select_display_ranges(
6871 &[
6872 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
6873 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
6874 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
6875 ],
6876 cx,
6877 );
6878 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
6879 });
6880 assert_eq!(
6881 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6882 &[
6883 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
6884 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
6885 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
6886 ]
6887 );
6888
6889 view.update(&mut cx, |view, cx| {
6890 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
6891 });
6892 assert_eq!(
6893 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6894 &[
6895 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
6896 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
6897 ]
6898 );
6899
6900 view.update(&mut cx, |view, cx| {
6901 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
6902 });
6903 assert_eq!(
6904 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6905 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
6906 );
6907
6908 // Trying to expand the selected syntax node one more time has no effect.
6909 view.update(&mut cx, |view, cx| {
6910 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
6911 });
6912 assert_eq!(
6913 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6914 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
6915 );
6916
6917 view.update(&mut cx, |view, cx| {
6918 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
6919 });
6920 assert_eq!(
6921 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6922 &[
6923 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
6924 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
6925 ]
6926 );
6927
6928 view.update(&mut cx, |view, cx| {
6929 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
6930 });
6931 assert_eq!(
6932 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6933 &[
6934 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
6935 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
6936 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
6937 ]
6938 );
6939
6940 view.update(&mut cx, |view, cx| {
6941 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
6942 });
6943 assert_eq!(
6944 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6945 &[
6946 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
6947 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
6948 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
6949 ]
6950 );
6951
6952 // Trying to shrink the selected syntax node one more time has no effect.
6953 view.update(&mut cx, |view, cx| {
6954 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
6955 });
6956 assert_eq!(
6957 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6958 &[
6959 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
6960 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
6961 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
6962 ]
6963 );
6964
6965 // Ensure that we keep expanding the selection if the larger selection starts or ends within
6966 // a fold.
6967 view.update(&mut cx, |view, cx| {
6968 view.fold_ranges(
6969 vec![
6970 Point::new(0, 21)..Point::new(0, 24),
6971 Point::new(3, 20)..Point::new(3, 22),
6972 ],
6973 cx,
6974 );
6975 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
6976 });
6977 assert_eq!(
6978 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6979 &[
6980 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
6981 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
6982 DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
6983 ]
6984 );
6985 }
6986
6987 #[gpui::test]
6988 async fn test_autoindent_selections(mut cx: gpui::TestAppContext) {
6989 let settings = cx.read(EditorSettings::test);
6990 let language = Arc::new(
6991 Language::new(
6992 LanguageConfig {
6993 brackets: vec![
6994 BracketPair {
6995 start: "{".to_string(),
6996 end: "}".to_string(),
6997 close: false,
6998 newline: true,
6999 },
7000 BracketPair {
7001 start: "(".to_string(),
7002 end: ")".to_string(),
7003 close: false,
7004 newline: true,
7005 },
7006 ],
7007 ..Default::default()
7008 },
7009 Some(tree_sitter_rust::language()),
7010 )
7011 .with_indents_query(
7012 r#"
7013 (_ "(" ")" @end) @indent
7014 (_ "{" "}" @end) @indent
7015 "#,
7016 )
7017 .unwrap(),
7018 );
7019
7020 let text = "fn a() {}";
7021
7022 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
7023 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7024 let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7025 editor
7026 .condition(&cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
7027 .await;
7028
7029 editor.update(&mut cx, |editor, cx| {
7030 editor.select_ranges([5..5, 8..8, 9..9], None, cx);
7031 editor.newline(&Newline, cx);
7032 assert_eq!(editor.text(cx), "fn a(\n \n) {\n \n}\n");
7033 assert_eq!(
7034 editor.selected_ranges(cx),
7035 &[
7036 Point::new(1, 4)..Point::new(1, 4),
7037 Point::new(3, 4)..Point::new(3, 4),
7038 Point::new(5, 0)..Point::new(5, 0)
7039 ]
7040 );
7041 });
7042 }
7043
7044 #[gpui::test]
7045 async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
7046 let settings = cx.read(EditorSettings::test);
7047 let language = Arc::new(Language::new(
7048 LanguageConfig {
7049 brackets: vec![
7050 BracketPair {
7051 start: "{".to_string(),
7052 end: "}".to_string(),
7053 close: true,
7054 newline: true,
7055 },
7056 BracketPair {
7057 start: "/*".to_string(),
7058 end: " */".to_string(),
7059 close: true,
7060 newline: true,
7061 },
7062 ],
7063 ..Default::default()
7064 },
7065 Some(tree_sitter_rust::language()),
7066 ));
7067
7068 let text = r#"
7069 a
7070
7071 /
7072
7073 "#
7074 .unindent();
7075
7076 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
7077 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7078 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7079 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
7080 .await;
7081
7082 view.update(&mut cx, |view, cx| {
7083 view.select_display_ranges(
7084 &[
7085 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7086 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7087 ],
7088 cx,
7089 );
7090 view.handle_input(&Input("{".to_string()), cx);
7091 view.handle_input(&Input("{".to_string()), cx);
7092 view.handle_input(&Input("{".to_string()), cx);
7093 assert_eq!(
7094 view.text(cx),
7095 "
7096 {{{}}}
7097 {{{}}}
7098 /
7099
7100 "
7101 .unindent()
7102 );
7103
7104 view.move_right(&MoveRight, cx);
7105 view.handle_input(&Input("}".to_string()), cx);
7106 view.handle_input(&Input("}".to_string()), cx);
7107 view.handle_input(&Input("}".to_string()), cx);
7108 assert_eq!(
7109 view.text(cx),
7110 "
7111 {{{}}}}
7112 {{{}}}}
7113 /
7114
7115 "
7116 .unindent()
7117 );
7118
7119 view.undo(&Undo, cx);
7120 view.handle_input(&Input("/".to_string()), cx);
7121 view.handle_input(&Input("*".to_string()), cx);
7122 assert_eq!(
7123 view.text(cx),
7124 "
7125 /* */
7126 /* */
7127 /
7128
7129 "
7130 .unindent()
7131 );
7132
7133 view.undo(&Undo, cx);
7134 view.select_display_ranges(
7135 &[
7136 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7137 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7138 ],
7139 cx,
7140 );
7141 view.handle_input(&Input("*".to_string()), cx);
7142 assert_eq!(
7143 view.text(cx),
7144 "
7145 a
7146
7147 /*
7148 *
7149 "
7150 .unindent()
7151 );
7152 });
7153 }
7154
7155 #[gpui::test]
7156 async fn test_snippets(mut cx: gpui::TestAppContext) {
7157 let settings = cx.read(EditorSettings::test);
7158
7159 let text = "
7160 a. b
7161 a. b
7162 a. b
7163 "
7164 .unindent();
7165 let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
7166 let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7167
7168 editor.update(&mut cx, |editor, cx| {
7169 let buffer = &editor.snapshot(cx).buffer_snapshot;
7170 let snippet = Snippet::parse("f(${1:one}, ${2:two}, ${1:three})$0").unwrap();
7171 let insertion_ranges = [
7172 Point::new(0, 2).to_offset(buffer)..Point::new(0, 2).to_offset(buffer),
7173 Point::new(1, 2).to_offset(buffer)..Point::new(1, 2).to_offset(buffer),
7174 Point::new(2, 2).to_offset(buffer)..Point::new(2, 2).to_offset(buffer),
7175 ];
7176
7177 editor
7178 .insert_snippet(&insertion_ranges, snippet, cx)
7179 .unwrap();
7180 assert_eq!(
7181 editor.text(cx),
7182 "
7183 a.f(one, two, three) b
7184 a.f(one, two, three) b
7185 a.f(one, two, three) b
7186 "
7187 .unindent()
7188 );
7189 assert_eq!(
7190 editor.selected_ranges::<Point>(cx),
7191 &[
7192 Point::new(0, 4)..Point::new(0, 7),
7193 Point::new(0, 14)..Point::new(0, 19),
7194 Point::new(1, 4)..Point::new(1, 7),
7195 Point::new(1, 14)..Point::new(1, 19),
7196 Point::new(2, 4)..Point::new(2, 7),
7197 Point::new(2, 14)..Point::new(2, 19),
7198 ]
7199 );
7200
7201 // Can't move earlier than the first tab stop
7202 editor.move_to_prev_snippet_tabstop(cx);
7203 assert_eq!(
7204 editor.selected_ranges::<Point>(cx),
7205 &[
7206 Point::new(0, 4)..Point::new(0, 7),
7207 Point::new(0, 14)..Point::new(0, 19),
7208 Point::new(1, 4)..Point::new(1, 7),
7209 Point::new(1, 14)..Point::new(1, 19),
7210 Point::new(2, 4)..Point::new(2, 7),
7211 Point::new(2, 14)..Point::new(2, 19),
7212 ]
7213 );
7214
7215 assert!(editor.move_to_next_snippet_tabstop(cx));
7216 assert_eq!(
7217 editor.selected_ranges::<Point>(cx),
7218 &[
7219 Point::new(0, 9)..Point::new(0, 12),
7220 Point::new(1, 9)..Point::new(1, 12),
7221 Point::new(2, 9)..Point::new(2, 12)
7222 ]
7223 );
7224
7225 editor.move_to_prev_snippet_tabstop(cx);
7226 assert_eq!(
7227 editor.selected_ranges::<Point>(cx),
7228 &[
7229 Point::new(0, 4)..Point::new(0, 7),
7230 Point::new(0, 14)..Point::new(0, 19),
7231 Point::new(1, 4)..Point::new(1, 7),
7232 Point::new(1, 14)..Point::new(1, 19),
7233 Point::new(2, 4)..Point::new(2, 7),
7234 Point::new(2, 14)..Point::new(2, 19),
7235 ]
7236 );
7237
7238 assert!(editor.move_to_next_snippet_tabstop(cx));
7239 assert!(editor.move_to_next_snippet_tabstop(cx));
7240 assert_eq!(
7241 editor.selected_ranges::<Point>(cx),
7242 &[
7243 Point::new(0, 20)..Point::new(0, 20),
7244 Point::new(1, 20)..Point::new(1, 20),
7245 Point::new(2, 20)..Point::new(2, 20)
7246 ]
7247 );
7248
7249 // As soon as the last tab stop is reached, snippet state is gone
7250 editor.move_to_prev_snippet_tabstop(cx);
7251 assert_eq!(
7252 editor.selected_ranges::<Point>(cx),
7253 &[
7254 Point::new(0, 20)..Point::new(0, 20),
7255 Point::new(1, 20)..Point::new(1, 20),
7256 Point::new(2, 20)..Point::new(2, 20)
7257 ]
7258 );
7259 });
7260 }
7261
7262 #[gpui::test]
7263 async fn test_completion(mut cx: gpui::TestAppContext) {
7264 let settings = cx.read(EditorSettings::test);
7265 let (language_server, mut fake) = lsp::LanguageServer::fake_with_capabilities(
7266 lsp::ServerCapabilities {
7267 completion_provider: Some(lsp::CompletionOptions {
7268 trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
7269 ..Default::default()
7270 }),
7271 ..Default::default()
7272 },
7273 cx.background(),
7274 )
7275 .await;
7276
7277 let text = "
7278 one
7279 two
7280 three
7281 "
7282 .unindent();
7283 let buffer = cx.add_model(|cx| {
7284 Buffer::from_file(
7285 0,
7286 text,
7287 Box::new(FakeFile {
7288 path: Arc::from(Path::new("/the/file")),
7289 }),
7290 cx,
7291 )
7292 .with_language_server(language_server, cx)
7293 });
7294 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7295 buffer.next_notification(&cx).await;
7296
7297 let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7298
7299 editor.update(&mut cx, |editor, cx| {
7300 editor.select_ranges([Point::new(0, 3)..Point::new(0, 3)], None, cx);
7301 editor.handle_input(&Input(".".to_string()), cx);
7302 });
7303
7304 handle_completion_request(
7305 &mut fake,
7306 "/the/file",
7307 Point::new(0, 4),
7308 &[
7309 (Point::new(0, 4)..Point::new(0, 4), "first_completion"),
7310 (Point::new(0, 4)..Point::new(0, 4), "second_completion"),
7311 ],
7312 )
7313 .await;
7314 editor.next_notification(&cx).await;
7315
7316 let apply_additional_edits = editor.update(&mut cx, |editor, cx| {
7317 editor.move_down(&MoveDown, cx);
7318 let apply_additional_edits = editor.confirm_completion(None, cx).unwrap();
7319 assert_eq!(
7320 editor.text(cx),
7321 "
7322 one.second_completion
7323 two
7324 three
7325 "
7326 .unindent()
7327 );
7328 apply_additional_edits
7329 });
7330
7331 handle_resolve_completion_request(
7332 &mut fake,
7333 Some((Point::new(2, 5)..Point::new(2, 5), "\nadditional edit")),
7334 )
7335 .await;
7336 apply_additional_edits.await.unwrap();
7337 assert_eq!(
7338 editor.read_with(&cx, |editor, cx| editor.text(cx)),
7339 "
7340 one.second_completion
7341 two
7342 three
7343 additional edit
7344 "
7345 .unindent()
7346 );
7347
7348 editor.update(&mut cx, |editor, cx| {
7349 editor.select_ranges(
7350 [
7351 Point::new(1, 3)..Point::new(1, 3),
7352 Point::new(2, 5)..Point::new(2, 5),
7353 ],
7354 None,
7355 cx,
7356 );
7357
7358 editor.handle_input(&Input(" ".to_string()), cx);
7359 assert!(editor.completion_state.is_none());
7360 editor.handle_input(&Input("s".to_string()), cx);
7361 assert!(editor.completion_state.is_none());
7362 });
7363
7364 handle_completion_request(
7365 &mut fake,
7366 "/the/file",
7367 Point::new(2, 7),
7368 &[
7369 (Point::new(2, 6)..Point::new(2, 7), "fourth_completion"),
7370 (Point::new(2, 6)..Point::new(2, 7), "fifth_completion"),
7371 (Point::new(2, 6)..Point::new(2, 7), "sixth_completion"),
7372 ],
7373 )
7374 .await;
7375 editor
7376 .condition(&cx, |editor, _| editor.completion_state.is_some())
7377 .await;
7378
7379 editor.update(&mut cx, |editor, cx| {
7380 editor.handle_input(&Input("i".to_string()), cx);
7381 });
7382
7383 handle_completion_request(
7384 &mut fake,
7385 "/the/file",
7386 Point::new(2, 8),
7387 &[
7388 (Point::new(2, 6)..Point::new(2, 8), "fourth_completion"),
7389 (Point::new(2, 6)..Point::new(2, 8), "fifth_completion"),
7390 (Point::new(2, 6)..Point::new(2, 8), "sixth_completion"),
7391 ],
7392 )
7393 .await;
7394 editor.next_notification(&cx).await;
7395
7396 let apply_additional_edits = editor.update(&mut cx, |editor, cx| {
7397 let apply_additional_edits = editor.confirm_completion(None, cx).unwrap();
7398 assert_eq!(
7399 editor.text(cx),
7400 "
7401 one.second_completion
7402 two sixth_completion
7403 three sixth_completion
7404 additional edit
7405 "
7406 .unindent()
7407 );
7408 apply_additional_edits
7409 });
7410 handle_resolve_completion_request(&mut fake, None).await;
7411 apply_additional_edits.await.unwrap();
7412
7413 async fn handle_completion_request(
7414 fake: &mut FakeLanguageServer,
7415 path: &str,
7416 position: Point,
7417 completions: &[(Range<Point>, &str)],
7418 ) {
7419 let (id, params) = fake.receive_request::<lsp::request::Completion>().await;
7420 assert_eq!(
7421 params.text_document_position.text_document.uri,
7422 lsp::Url::from_file_path(path).unwrap()
7423 );
7424 assert_eq!(
7425 params.text_document_position.position,
7426 lsp::Position::new(position.row, position.column)
7427 );
7428
7429 let completions = completions
7430 .iter()
7431 .map(|(range, new_text)| lsp::CompletionItem {
7432 label: new_text.to_string(),
7433 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
7434 range: lsp::Range::new(
7435 lsp::Position::new(range.start.row, range.start.column),
7436 lsp::Position::new(range.start.row, range.start.column),
7437 ),
7438 new_text: new_text.to_string(),
7439 })),
7440 ..Default::default()
7441 })
7442 .collect();
7443 fake.respond(id, Some(lsp::CompletionResponse::Array(completions)))
7444 .await;
7445 }
7446
7447 async fn handle_resolve_completion_request(
7448 fake: &mut FakeLanguageServer,
7449 edit: Option<(Range<Point>, &str)>,
7450 ) {
7451 let (id, _) = fake
7452 .receive_request::<lsp::request::ResolveCompletionItem>()
7453 .await;
7454 fake.respond(
7455 id,
7456 lsp::CompletionItem {
7457 additional_text_edits: edit.map(|(range, new_text)| {
7458 vec![lsp::TextEdit::new(
7459 lsp::Range::new(
7460 lsp::Position::new(range.start.row, range.start.column),
7461 lsp::Position::new(range.end.row, range.end.column),
7462 ),
7463 new_text.to_string(),
7464 )]
7465 }),
7466 ..Default::default()
7467 },
7468 )
7469 .await;
7470 }
7471 }
7472
7473 #[gpui::test]
7474 async fn test_toggle_comment(mut cx: gpui::TestAppContext) {
7475 let settings = cx.read(EditorSettings::test);
7476 let language = Arc::new(Language::new(
7477 LanguageConfig {
7478 line_comment: Some("// ".to_string()),
7479 ..Default::default()
7480 },
7481 Some(tree_sitter_rust::language()),
7482 ));
7483
7484 let text = "
7485 fn a() {
7486 //b();
7487 // c();
7488 // d();
7489 }
7490 "
7491 .unindent();
7492
7493 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
7494 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7495 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7496
7497 view.update(&mut cx, |editor, cx| {
7498 // If multiple selections intersect a line, the line is only
7499 // toggled once.
7500 editor.select_display_ranges(
7501 &[
7502 DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
7503 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
7504 ],
7505 cx,
7506 );
7507 editor.toggle_comments(&ToggleComments, cx);
7508 assert_eq!(
7509 editor.text(cx),
7510 "
7511 fn a() {
7512 b();
7513 c();
7514 d();
7515 }
7516 "
7517 .unindent()
7518 );
7519
7520 // The comment prefix is inserted at the same column for every line
7521 // in a selection.
7522 editor.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx);
7523 editor.toggle_comments(&ToggleComments, cx);
7524 assert_eq!(
7525 editor.text(cx),
7526 "
7527 fn a() {
7528 // b();
7529 // c();
7530 // d();
7531 }
7532 "
7533 .unindent()
7534 );
7535
7536 // If a selection ends at the beginning of a line, that line is not toggled.
7537 editor.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx);
7538 editor.toggle_comments(&ToggleComments, cx);
7539 assert_eq!(
7540 editor.text(cx),
7541 "
7542 fn a() {
7543 // b();
7544 c();
7545 // d();
7546 }
7547 "
7548 .unindent()
7549 );
7550 });
7551 }
7552
7553 #[gpui::test]
7554 fn test_editing_disjoint_excerpts(cx: &mut gpui::MutableAppContext) {
7555 let settings = EditorSettings::test(cx);
7556 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
7557 let multibuffer = cx.add_model(|cx| {
7558 let mut multibuffer = MultiBuffer::new(0);
7559 multibuffer.push_excerpt(
7560 ExcerptProperties {
7561 buffer: &buffer,
7562 range: Point::new(0, 0)..Point::new(0, 4),
7563 },
7564 cx,
7565 );
7566 multibuffer.push_excerpt(
7567 ExcerptProperties {
7568 buffer: &buffer,
7569 range: Point::new(1, 0)..Point::new(1, 4),
7570 },
7571 cx,
7572 );
7573 multibuffer
7574 });
7575
7576 assert_eq!(multibuffer.read(cx).read(cx).text(), "aaaa\nbbbb");
7577
7578 let (_, view) = cx.add_window(Default::default(), |cx| {
7579 build_editor(multibuffer, settings, cx)
7580 });
7581 view.update(cx, |view, cx| {
7582 view.select_display_ranges(
7583 &[
7584 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7585 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7586 ],
7587 cx,
7588 );
7589
7590 view.handle_input(&Input("X".to_string()), cx);
7591 assert_eq!(view.text(cx), "Xaaaa\nXbbbb");
7592 assert_eq!(
7593 view.selected_display_ranges(cx),
7594 &[
7595 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7596 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7597 ]
7598 )
7599 });
7600 }
7601
7602 #[gpui::test]
7603 fn test_editing_overlapping_excerpts(cx: &mut gpui::MutableAppContext) {
7604 let settings = EditorSettings::test(cx);
7605 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
7606 let multibuffer = cx.add_model(|cx| {
7607 let mut multibuffer = MultiBuffer::new(0);
7608 multibuffer.push_excerpt(
7609 ExcerptProperties {
7610 buffer: &buffer,
7611 range: Point::new(0, 0)..Point::new(1, 4),
7612 },
7613 cx,
7614 );
7615 multibuffer.push_excerpt(
7616 ExcerptProperties {
7617 buffer: &buffer,
7618 range: Point::new(1, 0)..Point::new(2, 4),
7619 },
7620 cx,
7621 );
7622 multibuffer
7623 });
7624
7625 assert_eq!(
7626 multibuffer.read(cx).read(cx).text(),
7627 "aaaa\nbbbb\nbbbb\ncccc"
7628 );
7629
7630 let (_, view) = cx.add_window(Default::default(), |cx| {
7631 build_editor(multibuffer, settings, cx)
7632 });
7633 view.update(cx, |view, cx| {
7634 view.select_display_ranges(
7635 &[
7636 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7637 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
7638 ],
7639 cx,
7640 );
7641
7642 view.handle_input(&Input("X".to_string()), cx);
7643 assert_eq!(view.text(cx), "aaaa\nbXbbXb\nbXbbXb\ncccc");
7644 assert_eq!(
7645 view.selected_display_ranges(cx),
7646 &[
7647 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
7648 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
7649 ]
7650 );
7651
7652 view.newline(&Newline, cx);
7653 assert_eq!(view.text(cx), "aaaa\nbX\nbbX\nb\nbX\nbbX\nb\ncccc");
7654 assert_eq!(
7655 view.selected_display_ranges(cx),
7656 &[
7657 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
7658 DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
7659 ]
7660 );
7661 });
7662 }
7663
7664 #[gpui::test]
7665 fn test_refresh_selections(cx: &mut gpui::MutableAppContext) {
7666 let settings = EditorSettings::test(cx);
7667 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
7668 let mut excerpt1_id = None;
7669 let multibuffer = cx.add_model(|cx| {
7670 let mut multibuffer = MultiBuffer::new(0);
7671 excerpt1_id = Some(multibuffer.push_excerpt(
7672 ExcerptProperties {
7673 buffer: &buffer,
7674 range: Point::new(0, 0)..Point::new(1, 4),
7675 },
7676 cx,
7677 ));
7678 multibuffer.push_excerpt(
7679 ExcerptProperties {
7680 buffer: &buffer,
7681 range: Point::new(1, 0)..Point::new(2, 4),
7682 },
7683 cx,
7684 );
7685 multibuffer
7686 });
7687 assert_eq!(
7688 multibuffer.read(cx).read(cx).text(),
7689 "aaaa\nbbbb\nbbbb\ncccc"
7690 );
7691 let (_, editor) = cx.add_window(Default::default(), |cx| {
7692 let mut editor = build_editor(multibuffer.clone(), settings, cx);
7693 editor.select_display_ranges(
7694 &[
7695 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
7696 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7697 ],
7698 cx,
7699 );
7700 editor
7701 });
7702
7703 // Refreshing selections is a no-op when excerpts haven't changed.
7704 editor.update(cx, |editor, cx| {
7705 editor.refresh_selections(cx);
7706 assert_eq!(
7707 editor.selected_display_ranges(cx),
7708 [
7709 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
7710 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7711 ]
7712 );
7713 });
7714
7715 multibuffer.update(cx, |multibuffer, cx| {
7716 multibuffer.remove_excerpts([&excerpt1_id.unwrap()], cx);
7717 });
7718 editor.update(cx, |editor, cx| {
7719 // Removing an excerpt causes the first selection to become degenerate.
7720 assert_eq!(
7721 editor.selected_display_ranges(cx),
7722 [
7723 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7724 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
7725 ]
7726 );
7727
7728 // Refreshing selections will relocate the first selection to the original buffer
7729 // location.
7730 editor.refresh_selections(cx);
7731 assert_eq!(
7732 editor.selected_display_ranges(cx),
7733 [
7734 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7735 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3)
7736 ]
7737 );
7738 });
7739 }
7740
7741 #[gpui::test]
7742 async fn test_extra_newline_insertion(mut cx: gpui::TestAppContext) {
7743 let settings = cx.read(EditorSettings::test);
7744 let language = Arc::new(Language::new(
7745 LanguageConfig {
7746 brackets: vec![
7747 BracketPair {
7748 start: "{".to_string(),
7749 end: "}".to_string(),
7750 close: true,
7751 newline: true,
7752 },
7753 BracketPair {
7754 start: "/* ".to_string(),
7755 end: " */".to_string(),
7756 close: true,
7757 newline: true,
7758 },
7759 ],
7760 ..Default::default()
7761 },
7762 Some(tree_sitter_rust::language()),
7763 ));
7764
7765 let text = concat!(
7766 "{ }\n", // Suppress rustfmt
7767 " x\n", //
7768 " /* */\n", //
7769 "x\n", //
7770 "{{} }\n", //
7771 );
7772
7773 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
7774 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7775 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7776 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
7777 .await;
7778
7779 view.update(&mut cx, |view, cx| {
7780 view.select_display_ranges(
7781 &[
7782 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
7783 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
7784 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
7785 ],
7786 cx,
7787 );
7788 view.newline(&Newline, cx);
7789
7790 assert_eq!(
7791 view.buffer().read(cx).read(cx).text(),
7792 concat!(
7793 "{ \n", // Suppress rustfmt
7794 "\n", //
7795 "}\n", //
7796 " x\n", //
7797 " /* \n", //
7798 " \n", //
7799 " */\n", //
7800 "x\n", //
7801 "{{} \n", //
7802 "}\n", //
7803 )
7804 );
7805 });
7806 }
7807
7808 #[gpui::test]
7809 fn test_highlighted_ranges(cx: &mut gpui::MutableAppContext) {
7810 let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
7811 let settings = EditorSettings::test(&cx);
7812 let (_, editor) = cx.add_window(Default::default(), |cx| {
7813 build_editor(buffer.clone(), settings, cx)
7814 });
7815
7816 editor.update(cx, |editor, cx| {
7817 struct Type1;
7818 struct Type2;
7819
7820 let buffer = buffer.read(cx).snapshot(cx);
7821
7822 let anchor_range = |range: Range<Point>| {
7823 buffer.anchor_after(range.start)..buffer.anchor_after(range.end)
7824 };
7825
7826 editor.highlight_ranges::<Type1>(
7827 vec![
7828 anchor_range(Point::new(2, 1)..Point::new(2, 3)),
7829 anchor_range(Point::new(4, 2)..Point::new(4, 4)),
7830 anchor_range(Point::new(6, 3)..Point::new(6, 5)),
7831 anchor_range(Point::new(8, 4)..Point::new(8, 6)),
7832 ],
7833 Color::red(),
7834 cx,
7835 );
7836 editor.highlight_ranges::<Type2>(
7837 vec![
7838 anchor_range(Point::new(3, 2)..Point::new(3, 5)),
7839 anchor_range(Point::new(5, 3)..Point::new(5, 6)),
7840 anchor_range(Point::new(7, 4)..Point::new(7, 7)),
7841 anchor_range(Point::new(9, 5)..Point::new(9, 8)),
7842 ],
7843 Color::green(),
7844 cx,
7845 );
7846
7847 let snapshot = editor.snapshot(cx);
7848 let mut highlighted_ranges = editor.highlighted_ranges_in_range(
7849 anchor_range(Point::new(3, 4)..Point::new(7, 4)),
7850 &snapshot,
7851 );
7852 // Enforce a consistent ordering based on color without relying on the ordering of the
7853 // highlight's `TypeId` which is non-deterministic.
7854 highlighted_ranges.sort_unstable_by_key(|(_, color)| *color);
7855 assert_eq!(
7856 highlighted_ranges,
7857 &[
7858 (
7859 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 5),
7860 Color::green(),
7861 ),
7862 (
7863 DisplayPoint::new(5, 3)..DisplayPoint::new(5, 6),
7864 Color::green(),
7865 ),
7866 (
7867 DisplayPoint::new(4, 2)..DisplayPoint::new(4, 4),
7868 Color::red(),
7869 ),
7870 (
7871 DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
7872 Color::red(),
7873 ),
7874 ]
7875 );
7876 assert_eq!(
7877 editor.highlighted_ranges_in_range(
7878 anchor_range(Point::new(5, 6)..Point::new(6, 4)),
7879 &snapshot,
7880 ),
7881 &[(
7882 DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
7883 Color::red(),
7884 )]
7885 );
7886 });
7887 }
7888
7889 #[test]
7890 fn test_combine_syntax_and_fuzzy_match_highlights() {
7891 let string = "abcdefghijklmnop";
7892 let default = HighlightStyle::default();
7893 let syntax_ranges = [
7894 (
7895 0..3,
7896 HighlightStyle {
7897 color: Color::red(),
7898 ..default
7899 },
7900 ),
7901 (
7902 4..8,
7903 HighlightStyle {
7904 color: Color::green(),
7905 ..default
7906 },
7907 ),
7908 ];
7909 let match_indices = [4, 6, 7, 8];
7910 assert_eq!(
7911 combine_syntax_and_fuzzy_match_highlights(
7912 &string,
7913 default,
7914 syntax_ranges.into_iter(),
7915 &match_indices,
7916 ),
7917 &[
7918 (
7919 0..3,
7920 HighlightStyle {
7921 color: Color::red(),
7922 ..default
7923 },
7924 ),
7925 (
7926 4..5,
7927 HighlightStyle {
7928 color: Color::green(),
7929 font_properties: *fonts::Properties::default().weight(fonts::Weight::BOLD),
7930 ..default
7931 },
7932 ),
7933 (
7934 5..6,
7935 HighlightStyle {
7936 color: Color::green(),
7937 ..default
7938 },
7939 ),
7940 (
7941 6..8,
7942 HighlightStyle {
7943 color: Color::green(),
7944 font_properties: *fonts::Properties::default().weight(fonts::Weight::BOLD),
7945 ..default
7946 },
7947 ),
7948 (
7949 8..9,
7950 HighlightStyle {
7951 font_properties: *fonts::Properties::default().weight(fonts::Weight::BOLD),
7952 ..default
7953 },
7954 ),
7955 ]
7956 );
7957 }
7958
7959 fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
7960 let point = DisplayPoint::new(row as u32, column as u32);
7961 point..point
7962 }
7963
7964 fn build_editor(
7965 buffer: ModelHandle<MultiBuffer>,
7966 settings: EditorSettings,
7967 cx: &mut ViewContext<Editor>,
7968 ) -> Editor {
7969 Editor::for_buffer(buffer, Arc::new(move |_| settings.clone()), cx)
7970 }
7971}
7972
7973trait RangeExt<T> {
7974 fn sorted(&self) -> Range<T>;
7975 fn to_inclusive(&self) -> RangeInclusive<T>;
7976}
7977
7978impl<T: Ord + Clone> RangeExt<T> for Range<T> {
7979 fn sorted(&self) -> Self {
7980 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
7981 }
7982
7983 fn to_inclusive(&self) -> RangeInclusive<T> {
7984 self.start.clone()..=self.end.clone()
7985 }
7986}