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