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