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