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