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 pub 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 settings = (this.build_settings)(cx);
4112 let buffer = this.buffer.read(cx).read(cx);
4113 let offset = position.to_offset(&buffer);
4114 let start = offset - lookbehind;
4115 let end = offset + lookahead;
4116 let rename_range = buffer.anchor_before(start)..buffer.anchor_after(end);
4117 drop(buffer);
4118
4119 this.buffer
4120 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
4121 this.pending_rename = Some(RenameState {
4122 range: rename_range.clone(),
4123 first_transaction: None,
4124 });
4125 this.select_ranges([start..end], None, cx);
4126 this.highlight_ranges::<Rename>(
4127 vec![rename_range],
4128 settings.style.highlighted_line_background,
4129 cx,
4130 );
4131 });
4132 }
4133
4134 Ok(())
4135 }))
4136 }
4137
4138 pub fn confirm_rename(
4139 workspace: &mut Workspace,
4140 _: &ConfirmRename,
4141 cx: &mut ViewContext<Workspace>,
4142 ) -> Option<Task<Result<()>>> {
4143 let editor = workspace.active_item(cx)?.act_as::<Editor>(cx)?;
4144
4145 let (buffer, position, new_name) = editor.update(cx, |editor, cx| {
4146 let (range, new_name) = editor.take_rename(cx)?;
4147 let (buffer, position) = editor
4148 .buffer
4149 .read(cx)
4150 .text_anchor_for_position(range.start.clone(), cx)?;
4151 Some((buffer, position, new_name))
4152 })?;
4153
4154 let rename = workspace.project().clone().update(cx, |project, cx| {
4155 project.perform_rename(buffer, position, new_name.clone(), true, cx)
4156 });
4157
4158 Some(cx.spawn(|workspace, cx| async move {
4159 let project_transaction = rename.await?;
4160 Self::open_project_transaction(
4161 editor,
4162 workspace,
4163 project_transaction,
4164 format!("Rename: {}", new_name),
4165 cx,
4166 )
4167 .await
4168 }))
4169 }
4170
4171 fn take_rename(&mut self, cx: &mut ViewContext<Self>) -> Option<(Range<Anchor>, String)> {
4172 let rename = self.pending_rename.take()?;
4173 let new_name = self
4174 .buffer
4175 .read(cx)
4176 .read(cx)
4177 .text_for_range(rename.range.clone())
4178 .collect::<String>();
4179
4180 self.clear_highlighted_ranges::<Rename>(cx);
4181 if let Some(transaction_id) = rename.first_transaction {
4182 self.buffer.update(cx, |buffer, cx| {
4183 buffer.undo_to_transaction(transaction_id, false, cx)
4184 });
4185 }
4186
4187 Some((rename.range, new_name))
4188 }
4189
4190 fn invalidate_rename_range(
4191 &mut self,
4192 buffer: &MultiBufferSnapshot,
4193 cx: &mut ViewContext<Self>,
4194 ) {
4195 if let Some(rename) = self.pending_rename.as_ref() {
4196 if self.selections.len() == 1 {
4197 let head = self.selections[0].head().to_offset(buffer);
4198 let range = rename.range.to_offset(buffer).to_inclusive();
4199 if range.contains(&head) {
4200 return;
4201 }
4202 }
4203
4204 self.take_rename(cx);
4205 }
4206 }
4207
4208 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
4209 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
4210 let buffer = self.buffer.read(cx).snapshot(cx);
4211 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
4212 let is_valid = buffer
4213 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
4214 .any(|entry| {
4215 entry.diagnostic.is_primary
4216 && !entry.range.is_empty()
4217 && entry.range.start == primary_range_start
4218 && entry.diagnostic.message == active_diagnostics.primary_message
4219 });
4220
4221 if is_valid != active_diagnostics.is_valid {
4222 active_diagnostics.is_valid = is_valid;
4223 let mut new_styles = HashMap::default();
4224 for (block_id, diagnostic) in &active_diagnostics.blocks {
4225 new_styles.insert(
4226 *block_id,
4227 diagnostic_block_renderer(
4228 diagnostic.clone(),
4229 is_valid,
4230 self.build_settings.clone(),
4231 ),
4232 );
4233 }
4234 self.display_map
4235 .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
4236 }
4237 }
4238 }
4239
4240 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
4241 self.dismiss_diagnostics(cx);
4242 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
4243 let buffer = self.buffer.read(cx).snapshot(cx);
4244
4245 let mut primary_range = None;
4246 let mut primary_message = None;
4247 let mut group_end = Point::zero();
4248 let diagnostic_group = buffer
4249 .diagnostic_group::<Point>(group_id)
4250 .map(|entry| {
4251 if entry.range.end > group_end {
4252 group_end = entry.range.end;
4253 }
4254 if entry.diagnostic.is_primary {
4255 primary_range = Some(entry.range.clone());
4256 primary_message = Some(entry.diagnostic.message.clone());
4257 }
4258 entry
4259 })
4260 .collect::<Vec<_>>();
4261 let primary_range = primary_range.unwrap();
4262 let primary_message = primary_message.unwrap();
4263 let primary_range =
4264 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
4265
4266 let blocks = display_map
4267 .insert_blocks(
4268 diagnostic_group.iter().map(|entry| {
4269 let build_settings = self.build_settings.clone();
4270 let diagnostic = entry.diagnostic.clone();
4271 let message_height = diagnostic.message.lines().count() as u8;
4272
4273 BlockProperties {
4274 position: buffer.anchor_after(entry.range.start),
4275 height: message_height,
4276 render: diagnostic_block_renderer(diagnostic, true, build_settings),
4277 disposition: BlockDisposition::Below,
4278 }
4279 }),
4280 cx,
4281 )
4282 .into_iter()
4283 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
4284 .collect();
4285
4286 Some(ActiveDiagnosticGroup {
4287 primary_range,
4288 primary_message,
4289 blocks,
4290 is_valid: true,
4291 })
4292 });
4293 }
4294
4295 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
4296 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
4297 self.display_map.update(cx, |display_map, cx| {
4298 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
4299 });
4300 cx.notify();
4301 }
4302 }
4303
4304 fn build_columnar_selection(
4305 &mut self,
4306 display_map: &DisplaySnapshot,
4307 row: u32,
4308 columns: &Range<u32>,
4309 reversed: bool,
4310 ) -> Option<Selection<Point>> {
4311 let is_empty = columns.start == columns.end;
4312 let line_len = display_map.line_len(row);
4313 if columns.start < line_len || (is_empty && columns.start == line_len) {
4314 let start = DisplayPoint::new(row, columns.start);
4315 let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
4316 Some(Selection {
4317 id: post_inc(&mut self.next_selection_id),
4318 start: start.to_point(display_map),
4319 end: end.to_point(display_map),
4320 reversed,
4321 goal: SelectionGoal::ColumnRange {
4322 start: columns.start,
4323 end: columns.end,
4324 },
4325 })
4326 } else {
4327 None
4328 }
4329 }
4330
4331 pub fn local_selections_in_range(
4332 &self,
4333 range: Range<Anchor>,
4334 display_map: &DisplaySnapshot,
4335 ) -> Vec<Selection<Point>> {
4336 let buffer = &display_map.buffer_snapshot;
4337
4338 let start_ix = match self
4339 .selections
4340 .binary_search_by(|probe| probe.end.cmp(&range.start, &buffer).unwrap())
4341 {
4342 Ok(ix) | Err(ix) => ix,
4343 };
4344 let end_ix = match self
4345 .selections
4346 .binary_search_by(|probe| probe.start.cmp(&range.end, &buffer).unwrap())
4347 {
4348 Ok(ix) => ix + 1,
4349 Err(ix) => ix,
4350 };
4351
4352 fn point_selection(
4353 selection: &Selection<Anchor>,
4354 buffer: &MultiBufferSnapshot,
4355 ) -> Selection<Point> {
4356 let start = selection.start.to_point(&buffer);
4357 let end = selection.end.to_point(&buffer);
4358 Selection {
4359 id: selection.id,
4360 start,
4361 end,
4362 reversed: selection.reversed,
4363 goal: selection.goal,
4364 }
4365 }
4366
4367 self.selections[start_ix..end_ix]
4368 .iter()
4369 .chain(
4370 self.pending_selection
4371 .as_ref()
4372 .map(|pending| &pending.selection),
4373 )
4374 .map(|s| point_selection(s, &buffer))
4375 .collect()
4376 }
4377
4378 pub fn local_selections<'a, D>(&self, cx: &'a AppContext) -> Vec<Selection<D>>
4379 where
4380 D: 'a + TextDimension + Ord + Sub<D, Output = D>,
4381 {
4382 let buffer = self.buffer.read(cx).snapshot(cx);
4383 let mut selections = self
4384 .resolve_selections::<D, _>(self.selections.iter(), &buffer)
4385 .peekable();
4386
4387 let mut pending_selection = self.pending_selection::<D>(&buffer);
4388
4389 iter::from_fn(move || {
4390 if let Some(pending) = pending_selection.as_mut() {
4391 while let Some(next_selection) = selections.peek() {
4392 if pending.start <= next_selection.end && pending.end >= next_selection.start {
4393 let next_selection = selections.next().unwrap();
4394 if next_selection.start < pending.start {
4395 pending.start = next_selection.start;
4396 }
4397 if next_selection.end > pending.end {
4398 pending.end = next_selection.end;
4399 }
4400 } else if next_selection.end < pending.start {
4401 return selections.next();
4402 } else {
4403 break;
4404 }
4405 }
4406
4407 pending_selection.take()
4408 } else {
4409 selections.next()
4410 }
4411 })
4412 .collect()
4413 }
4414
4415 fn resolve_selections<'a, D, I>(
4416 &self,
4417 selections: I,
4418 snapshot: &MultiBufferSnapshot,
4419 ) -> impl 'a + Iterator<Item = Selection<D>>
4420 where
4421 D: TextDimension + Ord + Sub<D, Output = D>,
4422 I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
4423 {
4424 let (to_summarize, selections) = selections.into_iter().tee();
4425 let mut summaries = snapshot
4426 .summaries_for_anchors::<D, _>(to_summarize.flat_map(|s| [&s.start, &s.end]))
4427 .into_iter();
4428 selections.map(move |s| Selection {
4429 id: s.id,
4430 start: summaries.next().unwrap(),
4431 end: summaries.next().unwrap(),
4432 reversed: s.reversed,
4433 goal: s.goal,
4434 })
4435 }
4436
4437 fn pending_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4438 &self,
4439 snapshot: &MultiBufferSnapshot,
4440 ) -> Option<Selection<D>> {
4441 self.pending_selection
4442 .as_ref()
4443 .map(|pending| self.resolve_selection(&pending.selection, &snapshot))
4444 }
4445
4446 fn resolve_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4447 &self,
4448 selection: &Selection<Anchor>,
4449 buffer: &MultiBufferSnapshot,
4450 ) -> Selection<D> {
4451 Selection {
4452 id: selection.id,
4453 start: selection.start.summary::<D>(&buffer),
4454 end: selection.end.summary::<D>(&buffer),
4455 reversed: selection.reversed,
4456 goal: selection.goal,
4457 }
4458 }
4459
4460 fn selection_count<'a>(&self) -> usize {
4461 let mut count = self.selections.len();
4462 if self.pending_selection.is_some() {
4463 count += 1;
4464 }
4465 count
4466 }
4467
4468 pub fn oldest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4469 &self,
4470 snapshot: &MultiBufferSnapshot,
4471 ) -> Selection<D> {
4472 self.selections
4473 .iter()
4474 .min_by_key(|s| s.id)
4475 .map(|selection| self.resolve_selection(selection, snapshot))
4476 .or_else(|| self.pending_selection(snapshot))
4477 .unwrap()
4478 }
4479
4480 pub fn newest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4481 &self,
4482 snapshot: &MultiBufferSnapshot,
4483 ) -> Selection<D> {
4484 self.resolve_selection(self.newest_anchor_selection(), snapshot)
4485 }
4486
4487 pub fn newest_anchor_selection(&self) -> &Selection<Anchor> {
4488 self.pending_selection
4489 .as_ref()
4490 .map(|s| &s.selection)
4491 .or_else(|| self.selections.iter().max_by_key(|s| s.id))
4492 .unwrap()
4493 }
4494
4495 pub fn update_selections<T>(
4496 &mut self,
4497 mut selections: Vec<Selection<T>>,
4498 autoscroll: Option<Autoscroll>,
4499 cx: &mut ViewContext<Self>,
4500 ) where
4501 T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
4502 {
4503 let buffer = self.buffer.read(cx).snapshot(cx);
4504 selections.sort_unstable_by_key(|s| s.start);
4505
4506 // Merge overlapping selections.
4507 let mut i = 1;
4508 while i < selections.len() {
4509 if selections[i - 1].end >= selections[i].start {
4510 let removed = selections.remove(i);
4511 if removed.start < selections[i - 1].start {
4512 selections[i - 1].start = removed.start;
4513 }
4514 if removed.end > selections[i - 1].end {
4515 selections[i - 1].end = removed.end;
4516 }
4517 } else {
4518 i += 1;
4519 }
4520 }
4521
4522 if let Some(autoscroll) = autoscroll {
4523 self.request_autoscroll(autoscroll, cx);
4524 }
4525
4526 self.set_selections(
4527 Arc::from_iter(selections.into_iter().map(|selection| {
4528 let end_bias = if selection.end > selection.start {
4529 Bias::Left
4530 } else {
4531 Bias::Right
4532 };
4533 Selection {
4534 id: selection.id,
4535 start: buffer.anchor_after(selection.start),
4536 end: buffer.anchor_at(selection.end, end_bias),
4537 reversed: selection.reversed,
4538 goal: selection.goal,
4539 }
4540 })),
4541 None,
4542 cx,
4543 );
4544 }
4545
4546 /// Compute new ranges for any selections that were located in excerpts that have
4547 /// since been removed.
4548 ///
4549 /// Returns a `HashMap` indicating which selections whose former head position
4550 /// was no longer present. The keys of the map are selection ids. The values are
4551 /// the id of the new excerpt where the head of the selection has been moved.
4552 pub fn refresh_selections(&mut self, cx: &mut ViewContext<Self>) -> HashMap<usize, ExcerptId> {
4553 let snapshot = self.buffer.read(cx).read(cx);
4554 let anchors_with_status = snapshot.refresh_anchors(
4555 self.selections
4556 .iter()
4557 .flat_map(|selection| [&selection.start, &selection.end]),
4558 );
4559 let offsets =
4560 snapshot.summaries_for_anchors::<usize, _>(anchors_with_status.iter().map(|a| &a.1));
4561 let offsets = offsets.chunks(2);
4562 let statuses = anchors_with_status
4563 .chunks(2)
4564 .map(|a| (a[0].0 / 2, a[0].2, a[1].2));
4565
4566 let mut selections_with_lost_position = HashMap::default();
4567 let new_selections = offsets
4568 .zip(statuses)
4569 .map(|(offsets, (selection_ix, kept_start, kept_end))| {
4570 let selection = &self.selections[selection_ix];
4571 let kept_head = if selection.reversed {
4572 kept_start
4573 } else {
4574 kept_end
4575 };
4576 if !kept_head {
4577 selections_with_lost_position
4578 .insert(selection.id, selection.head().excerpt_id.clone());
4579 }
4580
4581 Selection {
4582 id: selection.id,
4583 start: offsets[0],
4584 end: offsets[1],
4585 reversed: selection.reversed,
4586 goal: selection.goal,
4587 }
4588 })
4589 .collect();
4590 drop(snapshot);
4591 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
4592 selections_with_lost_position
4593 }
4594
4595 fn set_selections(
4596 &mut self,
4597 selections: Arc<[Selection<Anchor>]>,
4598 pending_selection: Option<PendingSelection>,
4599 cx: &mut ViewContext<Self>,
4600 ) {
4601 let old_cursor_position = self.newest_anchor_selection().head();
4602
4603 self.selections = selections;
4604 self.pending_selection = pending_selection;
4605 if self.focused {
4606 self.buffer.update(cx, |buffer, cx| {
4607 buffer.set_active_selections(&self.selections, cx)
4608 });
4609 }
4610
4611 let display_map = self
4612 .display_map
4613 .update(cx, |display_map, cx| display_map.snapshot(cx));
4614 let buffer = &display_map.buffer_snapshot;
4615 self.add_selections_state = None;
4616 self.select_next_state = None;
4617 self.select_larger_syntax_node_stack.clear();
4618 self.autoclose_stack.invalidate(&self.selections, &buffer);
4619 self.snippet_stack.invalidate(&self.selections, &buffer);
4620 self.invalidate_rename_range(&buffer, cx);
4621
4622 let new_cursor_position = self.newest_anchor_selection().head();
4623
4624 self.push_to_nav_history(
4625 old_cursor_position.clone(),
4626 Some(new_cursor_position.to_point(&buffer)),
4627 cx,
4628 );
4629
4630 let completion_menu = match self.context_menu.as_mut() {
4631 Some(ContextMenu::Completions(menu)) => Some(menu),
4632 _ => {
4633 self.context_menu.take();
4634 None
4635 }
4636 };
4637
4638 if let Some(completion_menu) = completion_menu {
4639 let cursor_position = new_cursor_position.to_offset(&buffer);
4640 let (word_range, kind) =
4641 buffer.surrounding_word(completion_menu.initial_position.clone());
4642 if kind == Some(CharKind::Word) && word_range.to_inclusive().contains(&cursor_position)
4643 {
4644 let query = Self::completion_query(&buffer, cursor_position);
4645 cx.background()
4646 .block(completion_menu.filter(query.as_deref(), cx.background().clone()));
4647 self.show_completions(&ShowCompletions, cx);
4648 } else {
4649 self.hide_context_menu(cx);
4650 }
4651 }
4652
4653 if old_cursor_position.to_display_point(&display_map).row()
4654 != new_cursor_position.to_display_point(&display_map).row()
4655 {
4656 self.available_code_actions.take();
4657 }
4658 self.refresh_code_actions(cx);
4659
4660 self.pause_cursor_blinking(cx);
4661 cx.emit(Event::SelectionsChanged);
4662 }
4663
4664 pub fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
4665 self.autoscroll_request = Some(autoscroll);
4666 cx.notify();
4667 }
4668
4669 fn start_transaction(&mut self, cx: &mut ViewContext<Self>) {
4670 self.start_transaction_at(Instant::now(), cx);
4671 }
4672
4673 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
4674 self.end_selection(cx);
4675 if let Some(tx_id) = self
4676 .buffer
4677 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
4678 {
4679 self.selection_history
4680 .insert(tx_id, (self.selections.clone(), None));
4681 }
4682 }
4683
4684 fn end_transaction(&mut self, cx: &mut ViewContext<Self>) {
4685 self.end_transaction_at(Instant::now(), cx);
4686 }
4687
4688 fn end_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
4689 if let Some(tx_id) = self
4690 .buffer
4691 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
4692 {
4693 if let Some(rename) = self.pending_rename.as_mut() {
4694 if rename.first_transaction.is_none() {
4695 rename.first_transaction = Some(tx_id);
4696 }
4697 }
4698
4699 if let Some((_, end_selections)) = self.selection_history.get_mut(&tx_id) {
4700 *end_selections = Some(self.selections.clone());
4701 } else {
4702 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
4703 }
4704 }
4705 }
4706
4707 pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
4708 log::info!("Editor::page_up");
4709 }
4710
4711 pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
4712 log::info!("Editor::page_down");
4713 }
4714
4715 pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
4716 let mut fold_ranges = Vec::new();
4717
4718 let selections = self.local_selections::<Point>(cx);
4719 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4720 for selection in selections {
4721 let range = selection.display_range(&display_map).sorted();
4722 let buffer_start_row = range.start.to_point(&display_map).row;
4723
4724 for row in (0..=range.end.row()).rev() {
4725 if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
4726 let fold_range = self.foldable_range_for_line(&display_map, row);
4727 if fold_range.end.row >= buffer_start_row {
4728 fold_ranges.push(fold_range);
4729 if row <= range.start.row() {
4730 break;
4731 }
4732 }
4733 }
4734 }
4735 }
4736
4737 self.fold_ranges(fold_ranges, cx);
4738 }
4739
4740 pub fn unfold(&mut self, _: &Unfold, cx: &mut ViewContext<Self>) {
4741 let selections = self.local_selections::<Point>(cx);
4742 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4743 let buffer = &display_map.buffer_snapshot;
4744 let ranges = selections
4745 .iter()
4746 .map(|s| {
4747 let range = s.display_range(&display_map).sorted();
4748 let mut start = range.start.to_point(&display_map);
4749 let mut end = range.end.to_point(&display_map);
4750 start.column = 0;
4751 end.column = buffer.line_len(end.row);
4752 start..end
4753 })
4754 .collect::<Vec<_>>();
4755 self.unfold_ranges(ranges, cx);
4756 }
4757
4758 fn is_line_foldable(&self, display_map: &DisplaySnapshot, display_row: u32) -> bool {
4759 let max_point = display_map.max_point();
4760 if display_row >= max_point.row() {
4761 false
4762 } else {
4763 let (start_indent, is_blank) = display_map.line_indent(display_row);
4764 if is_blank {
4765 false
4766 } else {
4767 for display_row in display_row + 1..=max_point.row() {
4768 let (indent, is_blank) = display_map.line_indent(display_row);
4769 if !is_blank {
4770 return indent > start_indent;
4771 }
4772 }
4773 false
4774 }
4775 }
4776 }
4777
4778 fn foldable_range_for_line(
4779 &self,
4780 display_map: &DisplaySnapshot,
4781 start_row: u32,
4782 ) -> Range<Point> {
4783 let max_point = display_map.max_point();
4784
4785 let (start_indent, _) = display_map.line_indent(start_row);
4786 let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
4787 let mut end = None;
4788 for row in start_row + 1..=max_point.row() {
4789 let (indent, is_blank) = display_map.line_indent(row);
4790 if !is_blank && indent <= start_indent {
4791 end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
4792 break;
4793 }
4794 }
4795
4796 let end = end.unwrap_or(max_point);
4797 return start.to_point(display_map)..end.to_point(display_map);
4798 }
4799
4800 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
4801 let selections = self.local_selections::<Point>(cx);
4802 let ranges = selections.into_iter().map(|s| s.start..s.end);
4803 self.fold_ranges(ranges, cx);
4804 }
4805
4806 fn fold_ranges<T: ToOffset>(
4807 &mut self,
4808 ranges: impl IntoIterator<Item = Range<T>>,
4809 cx: &mut ViewContext<Self>,
4810 ) {
4811 let mut ranges = ranges.into_iter().peekable();
4812 if ranges.peek().is_some() {
4813 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
4814 self.request_autoscroll(Autoscroll::Fit, cx);
4815 cx.notify();
4816 }
4817 }
4818
4819 fn unfold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
4820 if !ranges.is_empty() {
4821 self.display_map
4822 .update(cx, |map, cx| map.unfold(ranges, cx));
4823 self.request_autoscroll(Autoscroll::Fit, cx);
4824 cx.notify();
4825 }
4826 }
4827
4828 pub fn insert_blocks(
4829 &mut self,
4830 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
4831 cx: &mut ViewContext<Self>,
4832 ) -> Vec<BlockId> {
4833 let blocks = self
4834 .display_map
4835 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
4836 self.request_autoscroll(Autoscroll::Fit, cx);
4837 blocks
4838 }
4839
4840 pub fn replace_blocks(
4841 &mut self,
4842 blocks: HashMap<BlockId, RenderBlock>,
4843 cx: &mut ViewContext<Self>,
4844 ) {
4845 self.display_map
4846 .update(cx, |display_map, _| display_map.replace_blocks(blocks));
4847 self.request_autoscroll(Autoscroll::Fit, cx);
4848 }
4849
4850 pub fn remove_blocks(&mut self, block_ids: HashSet<BlockId>, cx: &mut ViewContext<Self>) {
4851 self.display_map.update(cx, |display_map, cx| {
4852 display_map.remove_blocks(block_ids, cx)
4853 });
4854 }
4855
4856 pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
4857 self.display_map
4858 .update(cx, |map, cx| map.snapshot(cx))
4859 .longest_row()
4860 }
4861
4862 pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
4863 self.display_map
4864 .update(cx, |map, cx| map.snapshot(cx))
4865 .max_point()
4866 }
4867
4868 pub fn text(&self, cx: &AppContext) -> String {
4869 self.buffer.read(cx).read(cx).text()
4870 }
4871
4872 pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
4873 self.display_map
4874 .update(cx, |map, cx| map.snapshot(cx))
4875 .text()
4876 }
4877
4878 pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut MutableAppContext) -> bool {
4879 self.display_map
4880 .update(cx, |map, cx| map.set_wrap_width(width, cx))
4881 }
4882
4883 pub fn set_highlighted_rows(&mut self, rows: Option<Range<u32>>) {
4884 self.highlighted_rows = rows;
4885 }
4886
4887 pub fn highlighted_rows(&self) -> Option<Range<u32>> {
4888 self.highlighted_rows.clone()
4889 }
4890
4891 pub fn highlight_ranges<T: 'static>(
4892 &mut self,
4893 ranges: Vec<Range<Anchor>>,
4894 color: Color,
4895 cx: &mut ViewContext<Self>,
4896 ) {
4897 self.highlighted_ranges
4898 .insert(TypeId::of::<T>(), (color, ranges));
4899 cx.notify();
4900 }
4901
4902 pub fn clear_highlighted_ranges<T: 'static>(
4903 &mut self,
4904 cx: &mut ViewContext<Self>,
4905 ) -> Option<(Color, Vec<Range<Anchor>>)> {
4906 cx.notify();
4907 self.highlighted_ranges.remove(&TypeId::of::<T>())
4908 }
4909
4910 #[cfg(feature = "test-support")]
4911 pub fn all_highlighted_ranges(
4912 &mut self,
4913 cx: &mut ViewContext<Self>,
4914 ) -> Vec<(Range<DisplayPoint>, Color)> {
4915 let snapshot = self.snapshot(cx);
4916 let buffer = &snapshot.buffer_snapshot;
4917 let start = buffer.anchor_before(0);
4918 let end = buffer.anchor_after(buffer.len());
4919 self.highlighted_ranges_in_range(start..end, &snapshot)
4920 }
4921
4922 pub fn highlighted_ranges_for_type<T: 'static>(&self) -> Option<(Color, &[Range<Anchor>])> {
4923 self.highlighted_ranges
4924 .get(&TypeId::of::<T>())
4925 .map(|(color, ranges)| (*color, ranges.as_slice()))
4926 }
4927
4928 pub fn highlighted_ranges_in_range(
4929 &self,
4930 search_range: Range<Anchor>,
4931 display_snapshot: &DisplaySnapshot,
4932 ) -> Vec<(Range<DisplayPoint>, Color)> {
4933 let mut results = Vec::new();
4934 let buffer = &display_snapshot.buffer_snapshot;
4935 for (color, ranges) in self.highlighted_ranges.values() {
4936 let start_ix = match ranges.binary_search_by(|probe| {
4937 let cmp = probe.end.cmp(&search_range.start, &buffer).unwrap();
4938 if cmp.is_gt() {
4939 Ordering::Greater
4940 } else {
4941 Ordering::Less
4942 }
4943 }) {
4944 Ok(i) | Err(i) => i,
4945 };
4946 for range in &ranges[start_ix..] {
4947 if range.start.cmp(&search_range.end, &buffer).unwrap().is_ge() {
4948 break;
4949 }
4950 let start = range
4951 .start
4952 .to_point(buffer)
4953 .to_display_point(display_snapshot);
4954 let end = range
4955 .end
4956 .to_point(buffer)
4957 .to_display_point(display_snapshot);
4958 results.push((start..end, *color))
4959 }
4960 }
4961 results
4962 }
4963
4964 fn next_blink_epoch(&mut self) -> usize {
4965 self.blink_epoch += 1;
4966 self.blink_epoch
4967 }
4968
4969 fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
4970 if !self.focused {
4971 return;
4972 }
4973
4974 self.show_local_cursors = true;
4975 cx.notify();
4976
4977 let epoch = self.next_blink_epoch();
4978 cx.spawn(|this, mut cx| {
4979 let this = this.downgrade();
4980 async move {
4981 Timer::after(CURSOR_BLINK_INTERVAL).await;
4982 if let Some(this) = this.upgrade(&cx) {
4983 this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
4984 }
4985 }
4986 })
4987 .detach();
4988 }
4989
4990 fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
4991 if epoch == self.blink_epoch {
4992 self.blinking_paused = false;
4993 self.blink_cursors(epoch, cx);
4994 }
4995 }
4996
4997 fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
4998 if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
4999 self.show_local_cursors = !self.show_local_cursors;
5000 cx.notify();
5001
5002 let epoch = self.next_blink_epoch();
5003 cx.spawn(|this, mut cx| {
5004 let this = this.downgrade();
5005 async move {
5006 Timer::after(CURSOR_BLINK_INTERVAL).await;
5007 if let Some(this) = this.upgrade(&cx) {
5008 this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
5009 }
5010 }
5011 })
5012 .detach();
5013 }
5014 }
5015
5016 pub fn show_local_cursors(&self) -> bool {
5017 self.show_local_cursors
5018 }
5019
5020 fn on_buffer_changed(&mut self, _: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Self>) {
5021 cx.notify();
5022 }
5023
5024 fn on_buffer_event(
5025 &mut self,
5026 _: ModelHandle<MultiBuffer>,
5027 event: &language::Event,
5028 cx: &mut ViewContext<Self>,
5029 ) {
5030 match event {
5031 language::Event::Edited => {
5032 self.refresh_active_diagnostics(cx);
5033 self.refresh_code_actions(cx);
5034 cx.emit(Event::Edited);
5035 }
5036 language::Event::Dirtied => cx.emit(Event::Dirtied),
5037 language::Event::Saved => cx.emit(Event::Saved),
5038 language::Event::FileHandleChanged => cx.emit(Event::TitleChanged),
5039 language::Event::Reloaded => cx.emit(Event::TitleChanged),
5040 language::Event::Closed => cx.emit(Event::Closed),
5041 language::Event::DiagnosticsUpdated => {
5042 self.refresh_active_diagnostics(cx);
5043 }
5044 _ => {}
5045 }
5046 }
5047
5048 fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
5049 cx.notify();
5050 }
5051}
5052
5053impl EditorSnapshot {
5054 pub fn is_focused(&self) -> bool {
5055 self.is_focused
5056 }
5057
5058 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
5059 self.placeholder_text.as_ref()
5060 }
5061
5062 pub fn scroll_position(&self) -> Vector2F {
5063 compute_scroll_position(
5064 &self.display_snapshot,
5065 self.scroll_position,
5066 &self.scroll_top_anchor,
5067 )
5068 }
5069}
5070
5071impl Deref for EditorSnapshot {
5072 type Target = DisplaySnapshot;
5073
5074 fn deref(&self) -> &Self::Target {
5075 &self.display_snapshot
5076 }
5077}
5078
5079impl EditorSettings {
5080 #[cfg(any(test, feature = "test-support"))]
5081 pub fn test(cx: &AppContext) -> Self {
5082 use theme::{ContainedLabel, ContainedText, DiagnosticHeader, DiagnosticPathHeader};
5083
5084 Self {
5085 tab_size: 4,
5086 soft_wrap: SoftWrap::None,
5087 style: {
5088 let font_cache: &gpui::FontCache = cx.font_cache();
5089 let font_family_name = Arc::from("Monaco");
5090 let font_properties = Default::default();
5091 let font_family_id = font_cache.load_family(&[&font_family_name]).unwrap();
5092 let font_id = font_cache
5093 .select_font(font_family_id, &font_properties)
5094 .unwrap();
5095 let text = gpui::fonts::TextStyle {
5096 font_family_name,
5097 font_family_id,
5098 font_id,
5099 font_size: 14.,
5100 color: gpui::color::Color::from_u32(0xff0000ff),
5101 font_properties,
5102 underline: None,
5103 };
5104 let default_diagnostic_style = DiagnosticStyle {
5105 message: text.clone().into(),
5106 header: Default::default(),
5107 text_scale_factor: 1.,
5108 };
5109 EditorStyle {
5110 text: text.clone(),
5111 placeholder_text: None,
5112 background: Default::default(),
5113 gutter_background: Default::default(),
5114 gutter_padding_factor: 2.,
5115 active_line_background: Default::default(),
5116 highlighted_line_background: Default::default(),
5117 line_number: Default::default(),
5118 line_number_active: Default::default(),
5119 selection: Default::default(),
5120 guest_selections: Default::default(),
5121 syntax: Default::default(),
5122 diagnostic_path_header: DiagnosticPathHeader {
5123 container: Default::default(),
5124 filename: ContainedText {
5125 container: Default::default(),
5126 text: text.clone(),
5127 },
5128 path: ContainedText {
5129 container: Default::default(),
5130 text: text.clone(),
5131 },
5132 text_scale_factor: 1.,
5133 },
5134 diagnostic_header: DiagnosticHeader {
5135 container: Default::default(),
5136 message: ContainedLabel {
5137 container: Default::default(),
5138 label: text.clone().into(),
5139 },
5140 code: ContainedText {
5141 container: Default::default(),
5142 text: text.clone(),
5143 },
5144 icon_width_factor: 1.,
5145 text_scale_factor: 1.,
5146 },
5147 error_diagnostic: default_diagnostic_style.clone(),
5148 invalid_error_diagnostic: default_diagnostic_style.clone(),
5149 warning_diagnostic: default_diagnostic_style.clone(),
5150 invalid_warning_diagnostic: default_diagnostic_style.clone(),
5151 information_diagnostic: default_diagnostic_style.clone(),
5152 invalid_information_diagnostic: default_diagnostic_style.clone(),
5153 hint_diagnostic: default_diagnostic_style.clone(),
5154 invalid_hint_diagnostic: default_diagnostic_style.clone(),
5155 autocomplete: Default::default(),
5156 code_actions_indicator: Default::default(),
5157 }
5158 },
5159 }
5160 }
5161}
5162
5163fn compute_scroll_position(
5164 snapshot: &DisplaySnapshot,
5165 mut scroll_position: Vector2F,
5166 scroll_top_anchor: &Option<Anchor>,
5167) -> Vector2F {
5168 if let Some(anchor) = scroll_top_anchor {
5169 let scroll_top = anchor.to_display_point(snapshot).row() as f32;
5170 scroll_position.set_y(scroll_top + scroll_position.y());
5171 } else {
5172 scroll_position.set_y(0.);
5173 }
5174 scroll_position
5175}
5176
5177#[derive(Copy, Clone)]
5178pub enum Event {
5179 Activate,
5180 Edited,
5181 Blurred,
5182 Dirtied,
5183 Saved,
5184 TitleChanged,
5185 SelectionsChanged,
5186 Closed,
5187}
5188
5189impl Entity for Editor {
5190 type Event = Event;
5191}
5192
5193impl View for Editor {
5194 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
5195 let settings = (self.build_settings)(cx);
5196 self.display_map.update(cx, |map, cx| {
5197 map.set_font(
5198 settings.style.text.font_id,
5199 settings.style.text.font_size,
5200 cx,
5201 )
5202 });
5203 EditorElement::new(self.handle.clone(), settings).boxed()
5204 }
5205
5206 fn ui_name() -> &'static str {
5207 "Editor"
5208 }
5209
5210 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
5211 self.focused = true;
5212 self.blink_cursors(self.blink_epoch, cx);
5213 self.buffer.update(cx, |buffer, cx| {
5214 buffer.finalize_last_transaction(cx);
5215 buffer.set_active_selections(&self.selections, cx)
5216 });
5217 }
5218
5219 fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
5220 self.focused = false;
5221 self.show_local_cursors = false;
5222 self.buffer
5223 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
5224 self.hide_context_menu(cx);
5225 cx.emit(Event::Blurred);
5226 cx.notify();
5227 }
5228
5229 fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
5230 let mut cx = Self::default_keymap_context();
5231 let mode = match self.mode {
5232 EditorMode::SingleLine => "single_line",
5233 EditorMode::AutoHeight { .. } => "auto_height",
5234 EditorMode::Full => "full",
5235 };
5236 cx.map.insert("mode".into(), mode.into());
5237 if self.pending_rename.is_some() {
5238 cx.set.insert("renaming".into());
5239 }
5240 match self.context_menu.as_ref() {
5241 Some(ContextMenu::Completions(_)) => {
5242 cx.set.insert("showing_completions".into());
5243 }
5244 Some(ContextMenu::CodeActions(_)) => {
5245 cx.set.insert("showing_code_actions".into());
5246 }
5247 None => {}
5248 }
5249 cx
5250 }
5251}
5252
5253impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
5254 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
5255 let start = self.start.to_point(buffer);
5256 let end = self.end.to_point(buffer);
5257 if self.reversed {
5258 end..start
5259 } else {
5260 start..end
5261 }
5262 }
5263
5264 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
5265 let start = self.start.to_offset(buffer);
5266 let end = self.end.to_offset(buffer);
5267 if self.reversed {
5268 end..start
5269 } else {
5270 start..end
5271 }
5272 }
5273
5274 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
5275 let start = self
5276 .start
5277 .to_point(&map.buffer_snapshot)
5278 .to_display_point(map);
5279 let end = self
5280 .end
5281 .to_point(&map.buffer_snapshot)
5282 .to_display_point(map);
5283 if self.reversed {
5284 end..start
5285 } else {
5286 start..end
5287 }
5288 }
5289
5290 fn spanned_rows(
5291 &self,
5292 include_end_if_at_line_start: bool,
5293 map: &DisplaySnapshot,
5294 ) -> Range<u32> {
5295 let start = self.start.to_point(&map.buffer_snapshot);
5296 let mut end = self.end.to_point(&map.buffer_snapshot);
5297 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
5298 end.row -= 1;
5299 }
5300
5301 let buffer_start = map.prev_line_boundary(start).0;
5302 let buffer_end = map.next_line_boundary(end).0;
5303 buffer_start.row..buffer_end.row + 1
5304 }
5305}
5306
5307impl<T: InvalidationRegion> InvalidationStack<T> {
5308 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
5309 where
5310 S: Clone + ToOffset,
5311 {
5312 while let Some(region) = self.last() {
5313 let all_selections_inside_invalidation_ranges =
5314 if selections.len() == region.ranges().len() {
5315 selections
5316 .iter()
5317 .zip(region.ranges().iter().map(|r| r.to_offset(&buffer)))
5318 .all(|(selection, invalidation_range)| {
5319 let head = selection.head().to_offset(&buffer);
5320 invalidation_range.start <= head && invalidation_range.end >= head
5321 })
5322 } else {
5323 false
5324 };
5325
5326 if all_selections_inside_invalidation_ranges {
5327 break;
5328 } else {
5329 self.pop();
5330 }
5331 }
5332 }
5333}
5334
5335impl<T> Default for InvalidationStack<T> {
5336 fn default() -> Self {
5337 Self(Default::default())
5338 }
5339}
5340
5341impl<T> Deref for InvalidationStack<T> {
5342 type Target = Vec<T>;
5343
5344 fn deref(&self) -> &Self::Target {
5345 &self.0
5346 }
5347}
5348
5349impl<T> DerefMut for InvalidationStack<T> {
5350 fn deref_mut(&mut self) -> &mut Self::Target {
5351 &mut self.0
5352 }
5353}
5354
5355impl InvalidationRegion for BracketPairState {
5356 fn ranges(&self) -> &[Range<Anchor>] {
5357 &self.ranges
5358 }
5359}
5360
5361impl InvalidationRegion for SnippetState {
5362 fn ranges(&self) -> &[Range<Anchor>] {
5363 &self.ranges[self.active_index]
5364 }
5365}
5366
5367pub fn diagnostic_block_renderer(
5368 diagnostic: Diagnostic,
5369 is_valid: bool,
5370 build_settings: BuildSettings,
5371) -> RenderBlock {
5372 let mut highlighted_lines = Vec::new();
5373 for line in diagnostic.message.lines() {
5374 highlighted_lines.push(highlight_diagnostic_message(line));
5375 }
5376
5377 Arc::new(move |cx: &BlockContext| {
5378 let settings = build_settings(cx);
5379 let style = diagnostic_style(diagnostic.severity, is_valid, &settings.style);
5380 let font_size = (style.text_scale_factor * settings.style.text.font_size).round();
5381 Flex::column()
5382 .with_children(highlighted_lines.iter().map(|(line, highlights)| {
5383 Label::new(
5384 line.clone(),
5385 style.message.clone().with_font_size(font_size),
5386 )
5387 .with_highlights(highlights.clone())
5388 .contained()
5389 .with_margin_left(cx.anchor_x)
5390 .boxed()
5391 }))
5392 .aligned()
5393 .left()
5394 .boxed()
5395 })
5396}
5397
5398pub fn highlight_diagnostic_message(message: &str) -> (String, Vec<usize>) {
5399 let mut message_without_backticks = String::new();
5400 let mut prev_offset = 0;
5401 let mut inside_block = false;
5402 let mut highlights = Vec::new();
5403 for (match_ix, (offset, _)) in message
5404 .match_indices('`')
5405 .chain([(message.len(), "")])
5406 .enumerate()
5407 {
5408 message_without_backticks.push_str(&message[prev_offset..offset]);
5409 if inside_block {
5410 highlights.extend(prev_offset - match_ix..offset - match_ix);
5411 }
5412
5413 inside_block = !inside_block;
5414 prev_offset = offset + 1;
5415 }
5416
5417 (message_without_backticks, highlights)
5418}
5419
5420pub fn diagnostic_style(
5421 severity: DiagnosticSeverity,
5422 valid: bool,
5423 style: &EditorStyle,
5424) -> DiagnosticStyle {
5425 match (severity, valid) {
5426 (DiagnosticSeverity::ERROR, true) => style.error_diagnostic.clone(),
5427 (DiagnosticSeverity::ERROR, false) => style.invalid_error_diagnostic.clone(),
5428 (DiagnosticSeverity::WARNING, true) => style.warning_diagnostic.clone(),
5429 (DiagnosticSeverity::WARNING, false) => style.invalid_warning_diagnostic.clone(),
5430 (DiagnosticSeverity::INFORMATION, true) => style.information_diagnostic.clone(),
5431 (DiagnosticSeverity::INFORMATION, false) => style.invalid_information_diagnostic.clone(),
5432 (DiagnosticSeverity::HINT, true) => style.hint_diagnostic.clone(),
5433 (DiagnosticSeverity::HINT, false) => style.invalid_hint_diagnostic.clone(),
5434 _ => DiagnosticStyle {
5435 message: style.text.clone().into(),
5436 header: Default::default(),
5437 text_scale_factor: 1.,
5438 },
5439 }
5440}
5441
5442pub fn settings_builder(
5443 buffer: WeakModelHandle<MultiBuffer>,
5444 settings: watch::Receiver<workspace::Settings>,
5445) -> BuildSettings {
5446 Arc::new(move |cx| {
5447 let settings = settings.borrow();
5448 let font_cache = cx.font_cache();
5449 let font_family_id = settings.buffer_font_family;
5450 let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
5451 let font_properties = Default::default();
5452 let font_id = font_cache
5453 .select_font(font_family_id, &font_properties)
5454 .unwrap();
5455 let font_size = settings.buffer_font_size;
5456
5457 let mut theme = settings.theme.editor.clone();
5458 theme.text = TextStyle {
5459 color: theme.text.color,
5460 font_family_name,
5461 font_family_id,
5462 font_id,
5463 font_size,
5464 font_properties,
5465 underline: None,
5466 };
5467 let language = buffer.upgrade(cx).and_then(|buf| buf.read(cx).language(cx));
5468 let soft_wrap = match settings.soft_wrap(language) {
5469 workspace::settings::SoftWrap::None => SoftWrap::None,
5470 workspace::settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
5471 workspace::settings::SoftWrap::PreferredLineLength => {
5472 SoftWrap::Column(settings.preferred_line_length(language).saturating_sub(1))
5473 }
5474 };
5475
5476 EditorSettings {
5477 tab_size: settings.tab_size,
5478 soft_wrap,
5479 style: theme,
5480 }
5481 })
5482}
5483
5484pub fn combine_syntax_and_fuzzy_match_highlights(
5485 text: &str,
5486 default_style: HighlightStyle,
5487 syntax_ranges: impl Iterator<Item = (Range<usize>, HighlightStyle)>,
5488 match_indices: &[usize],
5489) -> Vec<(Range<usize>, HighlightStyle)> {
5490 let mut result = Vec::new();
5491 let mut match_indices = match_indices.iter().copied().peekable();
5492
5493 for (range, mut syntax_highlight) in syntax_ranges.chain([(usize::MAX..0, Default::default())])
5494 {
5495 syntax_highlight.font_properties.weight(Default::default());
5496
5497 // Add highlights for any fuzzy match characters before the next
5498 // syntax highlight range.
5499 while let Some(&match_index) = match_indices.peek() {
5500 if match_index >= range.start {
5501 break;
5502 }
5503 match_indices.next();
5504 let end_index = char_ix_after(match_index, text);
5505 let mut match_style = default_style;
5506 match_style.font_properties.weight(fonts::Weight::BOLD);
5507 result.push((match_index..end_index, match_style));
5508 }
5509
5510 if range.start == usize::MAX {
5511 break;
5512 }
5513
5514 // Add highlights for any fuzzy match characters within the
5515 // syntax highlight range.
5516 let mut offset = range.start;
5517 while let Some(&match_index) = match_indices.peek() {
5518 if match_index >= range.end {
5519 break;
5520 }
5521
5522 match_indices.next();
5523 if match_index > offset {
5524 result.push((offset..match_index, syntax_highlight));
5525 }
5526
5527 let mut end_index = char_ix_after(match_index, text);
5528 while let Some(&next_match_index) = match_indices.peek() {
5529 if next_match_index == end_index && next_match_index < range.end {
5530 end_index = char_ix_after(next_match_index, text);
5531 match_indices.next();
5532 } else {
5533 break;
5534 }
5535 }
5536
5537 let mut match_style = syntax_highlight;
5538 match_style.font_properties.weight(fonts::Weight::BOLD);
5539 result.push((match_index..end_index, match_style));
5540 offset = end_index;
5541 }
5542
5543 if offset < range.end {
5544 result.push((offset..range.end, syntax_highlight));
5545 }
5546 }
5547
5548 fn char_ix_after(ix: usize, text: &str) -> usize {
5549 ix + text[ix..].chars().next().unwrap().len_utf8()
5550 }
5551
5552 result
5553}
5554
5555fn styled_runs_for_completion_label<'a>(
5556 label: &'a CompletionLabel,
5557 default_color: Color,
5558 syntax_theme: &'a theme::SyntaxTheme,
5559) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
5560 const MUTED_OPACITY: usize = 165;
5561
5562 let mut muted_default_style = HighlightStyle {
5563 color: default_color,
5564 ..Default::default()
5565 };
5566 muted_default_style.color.a = ((default_color.a as usize * MUTED_OPACITY) / 255) as u8;
5567
5568 let mut prev_end = label.filter_range.end;
5569 label
5570 .runs
5571 .iter()
5572 .enumerate()
5573 .flat_map(move |(ix, (range, highlight_id))| {
5574 let style = if let Some(style) = highlight_id.style(syntax_theme) {
5575 style
5576 } else {
5577 return Default::default();
5578 };
5579 let mut muted_style = style.clone();
5580 muted_style.color.a = ((style.color.a as usize * MUTED_OPACITY) / 255) as u8;
5581
5582 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
5583 if range.start >= label.filter_range.end {
5584 if range.start > prev_end {
5585 runs.push((prev_end..range.start, muted_default_style));
5586 }
5587 runs.push((range.clone(), muted_style));
5588 } else if range.end <= label.filter_range.end {
5589 runs.push((range.clone(), style));
5590 } else {
5591 runs.push((range.start..label.filter_range.end, style));
5592 runs.push((label.filter_range.end..range.end, muted_style));
5593 }
5594 prev_end = cmp::max(prev_end, range.end);
5595
5596 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
5597 runs.push((prev_end..label.text.len(), muted_default_style));
5598 }
5599
5600 runs
5601 })
5602}
5603
5604#[cfg(test)]
5605mod tests {
5606 use super::*;
5607 use language::LanguageConfig;
5608 use lsp::FakeLanguageServer;
5609 use project::{FakeFs, ProjectPath};
5610 use smol::stream::StreamExt;
5611 use std::{cell::RefCell, rc::Rc, time::Instant};
5612 use text::Point;
5613 use unindent::Unindent;
5614 use util::test::sample_text;
5615
5616 #[gpui::test]
5617 fn test_undo_redo_with_selection_restoration(cx: &mut MutableAppContext) {
5618 let mut now = Instant::now();
5619 let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
5620 let group_interval = buffer.read(cx).transaction_group_interval();
5621 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5622 let settings = EditorSettings::test(cx);
5623 let (_, editor) = cx.add_window(Default::default(), |cx| {
5624 build_editor(buffer.clone(), settings, cx)
5625 });
5626
5627 editor.update(cx, |editor, cx| {
5628 editor.start_transaction_at(now, cx);
5629 editor.select_ranges([2..4], None, cx);
5630 editor.insert("cd", cx);
5631 editor.end_transaction_at(now, cx);
5632 assert_eq!(editor.text(cx), "12cd56");
5633 assert_eq!(editor.selected_ranges(cx), vec![4..4]);
5634
5635 editor.start_transaction_at(now, cx);
5636 editor.select_ranges([4..5], None, cx);
5637 editor.insert("e", cx);
5638 editor.end_transaction_at(now, cx);
5639 assert_eq!(editor.text(cx), "12cde6");
5640 assert_eq!(editor.selected_ranges(cx), vec![5..5]);
5641
5642 now += group_interval + Duration::from_millis(1);
5643 editor.select_ranges([2..2], None, cx);
5644
5645 // Simulate an edit in another editor
5646 buffer.update(cx, |buffer, cx| {
5647 buffer.start_transaction_at(now, cx);
5648 buffer.edit([0..1], "a", cx);
5649 buffer.edit([1..1], "b", cx);
5650 buffer.end_transaction_at(now, cx);
5651 });
5652
5653 assert_eq!(editor.text(cx), "ab2cde6");
5654 assert_eq!(editor.selected_ranges(cx), vec![3..3]);
5655
5656 // Last transaction happened past the group interval in a different editor.
5657 // Undo it individually and don't restore selections.
5658 editor.undo(&Undo, cx);
5659 assert_eq!(editor.text(cx), "12cde6");
5660 assert_eq!(editor.selected_ranges(cx), vec![2..2]);
5661
5662 // First two transactions happened within the group interval in this editor.
5663 // Undo them together and restore selections.
5664 editor.undo(&Undo, cx);
5665 editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
5666 assert_eq!(editor.text(cx), "123456");
5667 assert_eq!(editor.selected_ranges(cx), vec![0..0]);
5668
5669 // Redo the first two transactions together.
5670 editor.redo(&Redo, cx);
5671 assert_eq!(editor.text(cx), "12cde6");
5672 assert_eq!(editor.selected_ranges(cx), vec![5..5]);
5673
5674 // Redo the last transaction on its own.
5675 editor.redo(&Redo, cx);
5676 assert_eq!(editor.text(cx), "ab2cde6");
5677 assert_eq!(editor.selected_ranges(cx), vec![6..6]);
5678
5679 // Test empty transactions.
5680 editor.start_transaction_at(now, cx);
5681 editor.end_transaction_at(now, cx);
5682 editor.undo(&Undo, cx);
5683 assert_eq!(editor.text(cx), "12cde6");
5684 });
5685 }
5686
5687 #[gpui::test]
5688 fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
5689 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
5690 let settings = EditorSettings::test(cx);
5691 let (_, editor) =
5692 cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5693
5694 editor.update(cx, |view, cx| {
5695 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
5696 });
5697
5698 assert_eq!(
5699 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5700 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
5701 );
5702
5703 editor.update(cx, |view, cx| {
5704 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
5705 });
5706
5707 assert_eq!(
5708 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5709 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
5710 );
5711
5712 editor.update(cx, |view, cx| {
5713 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
5714 });
5715
5716 assert_eq!(
5717 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5718 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
5719 );
5720
5721 editor.update(cx, |view, cx| {
5722 view.end_selection(cx);
5723 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
5724 });
5725
5726 assert_eq!(
5727 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5728 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
5729 );
5730
5731 editor.update(cx, |view, cx| {
5732 view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
5733 view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
5734 });
5735
5736 assert_eq!(
5737 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5738 [
5739 DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
5740 DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
5741 ]
5742 );
5743
5744 editor.update(cx, |view, cx| {
5745 view.end_selection(cx);
5746 });
5747
5748 assert_eq!(
5749 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5750 [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
5751 );
5752 }
5753
5754 #[gpui::test]
5755 fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
5756 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
5757 let settings = EditorSettings::test(cx);
5758 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5759
5760 view.update(cx, |view, cx| {
5761 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
5762 assert_eq!(
5763 view.selected_display_ranges(cx),
5764 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
5765 );
5766 });
5767
5768 view.update(cx, |view, cx| {
5769 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
5770 assert_eq!(
5771 view.selected_display_ranges(cx),
5772 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
5773 );
5774 });
5775
5776 view.update(cx, |view, cx| {
5777 view.cancel(&Cancel, cx);
5778 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
5779 assert_eq!(
5780 view.selected_display_ranges(cx),
5781 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
5782 );
5783 });
5784 }
5785
5786 #[gpui::test]
5787 fn test_navigation_history(cx: &mut gpui::MutableAppContext) {
5788 cx.add_window(Default::default(), |cx| {
5789 use workspace::ItemView;
5790 let nav_history = Rc::new(RefCell::new(workspace::NavHistory::default()));
5791 let settings = EditorSettings::test(&cx);
5792 let buffer = MultiBuffer::build_simple(&sample_text(30, 5, 'a'), cx);
5793 let mut editor = build_editor(buffer.clone(), settings, cx);
5794 editor.nav_history = Some(ItemNavHistory::new(nav_history.clone(), &cx.handle()));
5795
5796 // Move the cursor a small distance.
5797 // Nothing is added to the navigation history.
5798 editor.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
5799 editor.select_display_ranges(&[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)], cx);
5800 assert!(nav_history.borrow_mut().pop_backward().is_none());
5801
5802 // Move the cursor a large distance.
5803 // The history can jump back to the previous position.
5804 editor.select_display_ranges(&[DisplayPoint::new(13, 0)..DisplayPoint::new(13, 3)], cx);
5805 let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
5806 editor.navigate(nav_entry.data.unwrap(), cx);
5807 assert_eq!(nav_entry.item_view.id(), cx.view_id());
5808 assert_eq!(
5809 editor.selected_display_ranges(cx),
5810 &[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)]
5811 );
5812
5813 // Move the cursor a small distance via the mouse.
5814 // Nothing is added to the navigation history.
5815 editor.begin_selection(DisplayPoint::new(5, 0), false, 1, cx);
5816 editor.end_selection(cx);
5817 assert_eq!(
5818 editor.selected_display_ranges(cx),
5819 &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
5820 );
5821 assert!(nav_history.borrow_mut().pop_backward().is_none());
5822
5823 // Move the cursor a large distance via the mouse.
5824 // The history can jump back to the previous position.
5825 editor.begin_selection(DisplayPoint::new(15, 0), false, 1, cx);
5826 editor.end_selection(cx);
5827 assert_eq!(
5828 editor.selected_display_ranges(cx),
5829 &[DisplayPoint::new(15, 0)..DisplayPoint::new(15, 0)]
5830 );
5831 let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
5832 editor.navigate(nav_entry.data.unwrap(), cx);
5833 assert_eq!(nav_entry.item_view.id(), cx.view_id());
5834 assert_eq!(
5835 editor.selected_display_ranges(cx),
5836 &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
5837 );
5838
5839 editor
5840 });
5841 }
5842
5843 #[gpui::test]
5844 fn test_cancel(cx: &mut gpui::MutableAppContext) {
5845 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
5846 let settings = EditorSettings::test(cx);
5847 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5848
5849 view.update(cx, |view, cx| {
5850 view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
5851 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
5852 view.end_selection(cx);
5853
5854 view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
5855 view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
5856 view.end_selection(cx);
5857 assert_eq!(
5858 view.selected_display_ranges(cx),
5859 [
5860 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5861 DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
5862 ]
5863 );
5864 });
5865
5866 view.update(cx, |view, cx| {
5867 view.cancel(&Cancel, cx);
5868 assert_eq!(
5869 view.selected_display_ranges(cx),
5870 [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
5871 );
5872 });
5873
5874 view.update(cx, |view, cx| {
5875 view.cancel(&Cancel, cx);
5876 assert_eq!(
5877 view.selected_display_ranges(cx),
5878 [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
5879 );
5880 });
5881 }
5882
5883 #[gpui::test]
5884 fn test_fold(cx: &mut gpui::MutableAppContext) {
5885 let buffer = MultiBuffer::build_simple(
5886 &"
5887 impl Foo {
5888 // Hello!
5889
5890 fn a() {
5891 1
5892 }
5893
5894 fn b() {
5895 2
5896 }
5897
5898 fn c() {
5899 3
5900 }
5901 }
5902 "
5903 .unindent(),
5904 cx,
5905 );
5906 let settings = EditorSettings::test(&cx);
5907 let (_, view) = cx.add_window(Default::default(), |cx| {
5908 build_editor(buffer.clone(), settings, cx)
5909 });
5910
5911 view.update(cx, |view, cx| {
5912 view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx);
5913 view.fold(&Fold, cx);
5914 assert_eq!(
5915 view.display_text(cx),
5916 "
5917 impl Foo {
5918 // Hello!
5919
5920 fn a() {
5921 1
5922 }
5923
5924 fn b() {…
5925 }
5926
5927 fn c() {…
5928 }
5929 }
5930 "
5931 .unindent(),
5932 );
5933
5934 view.fold(&Fold, cx);
5935 assert_eq!(
5936 view.display_text(cx),
5937 "
5938 impl Foo {…
5939 }
5940 "
5941 .unindent(),
5942 );
5943
5944 view.unfold(&Unfold, cx);
5945 assert_eq!(
5946 view.display_text(cx),
5947 "
5948 impl Foo {
5949 // Hello!
5950
5951 fn a() {
5952 1
5953 }
5954
5955 fn b() {…
5956 }
5957
5958 fn c() {…
5959 }
5960 }
5961 "
5962 .unindent(),
5963 );
5964
5965 view.unfold(&Unfold, cx);
5966 assert_eq!(view.display_text(cx), buffer.read(cx).read(cx).text());
5967 });
5968 }
5969
5970 #[gpui::test]
5971 fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
5972 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
5973 let settings = EditorSettings::test(&cx);
5974 let (_, view) = cx.add_window(Default::default(), |cx| {
5975 build_editor(buffer.clone(), settings, cx)
5976 });
5977
5978 buffer.update(cx, |buffer, cx| {
5979 buffer.edit(
5980 vec![
5981 Point::new(1, 0)..Point::new(1, 0),
5982 Point::new(1, 1)..Point::new(1, 1),
5983 ],
5984 "\t",
5985 cx,
5986 );
5987 });
5988
5989 view.update(cx, |view, cx| {
5990 assert_eq!(
5991 view.selected_display_ranges(cx),
5992 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
5993 );
5994
5995 view.move_down(&MoveDown, cx);
5996 assert_eq!(
5997 view.selected_display_ranges(cx),
5998 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
5999 );
6000
6001 view.move_right(&MoveRight, cx);
6002 assert_eq!(
6003 view.selected_display_ranges(cx),
6004 &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
6005 );
6006
6007 view.move_left(&MoveLeft, cx);
6008 assert_eq!(
6009 view.selected_display_ranges(cx),
6010 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6011 );
6012
6013 view.move_up(&MoveUp, cx);
6014 assert_eq!(
6015 view.selected_display_ranges(cx),
6016 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6017 );
6018
6019 view.move_to_end(&MoveToEnd, cx);
6020 assert_eq!(
6021 view.selected_display_ranges(cx),
6022 &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
6023 );
6024
6025 view.move_to_beginning(&MoveToBeginning, cx);
6026 assert_eq!(
6027 view.selected_display_ranges(cx),
6028 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6029 );
6030
6031 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx);
6032 view.select_to_beginning(&SelectToBeginning, cx);
6033 assert_eq!(
6034 view.selected_display_ranges(cx),
6035 &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
6036 );
6037
6038 view.select_to_end(&SelectToEnd, cx);
6039 assert_eq!(
6040 view.selected_display_ranges(cx),
6041 &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
6042 );
6043 });
6044 }
6045
6046 #[gpui::test]
6047 fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
6048 let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
6049 let settings = EditorSettings::test(&cx);
6050 let (_, view) = cx.add_window(Default::default(), |cx| {
6051 build_editor(buffer.clone(), settings, cx)
6052 });
6053
6054 assert_eq!('ⓐ'.len_utf8(), 3);
6055 assert_eq!('α'.len_utf8(), 2);
6056
6057 view.update(cx, |view, cx| {
6058 view.fold_ranges(
6059 vec![
6060 Point::new(0, 6)..Point::new(0, 12),
6061 Point::new(1, 2)..Point::new(1, 4),
6062 Point::new(2, 4)..Point::new(2, 8),
6063 ],
6064 cx,
6065 );
6066 assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
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 view.move_right(&MoveRight, cx);
6079 assert_eq!(
6080 view.selected_display_ranges(cx),
6081 &[empty_range(0, "ⓐⓑ…".len())]
6082 );
6083
6084 view.move_down(&MoveDown, 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, "ab".len())]
6093 );
6094 view.move_left(&MoveLeft, cx);
6095 assert_eq!(
6096 view.selected_display_ranges(cx),
6097 &[empty_range(1, "a".len())]
6098 );
6099
6100 view.move_down(&MoveDown, 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 view.move_right(&MoveRight, cx);
6116 assert_eq!(
6117 view.selected_display_ranges(cx),
6118 &[empty_range(2, "αβ…ε".len())]
6119 );
6120
6121 view.move_up(&MoveUp, cx);
6122 assert_eq!(
6123 view.selected_display_ranges(cx),
6124 &[empty_range(1, "ab…e".len())]
6125 );
6126 view.move_up(&MoveUp, 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 view.move_left(&MoveLeft, cx);
6142 assert_eq!(
6143 view.selected_display_ranges(cx),
6144 &[empty_range(0, "ⓐ".len())]
6145 );
6146 });
6147 }
6148
6149 #[gpui::test]
6150 fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
6151 let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
6152 let settings = EditorSettings::test(&cx);
6153 let (_, view) = cx.add_window(Default::default(), |cx| {
6154 build_editor(buffer.clone(), settings, cx)
6155 });
6156 view.update(cx, |view, cx| {
6157 view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx);
6158 view.move_down(&MoveDown, cx);
6159 assert_eq!(
6160 view.selected_display_ranges(cx),
6161 &[empty_range(1, "abcd".len())]
6162 );
6163
6164 view.move_down(&MoveDown, cx);
6165 assert_eq!(
6166 view.selected_display_ranges(cx),
6167 &[empty_range(2, "αβγ".len())]
6168 );
6169
6170 view.move_down(&MoveDown, cx);
6171 assert_eq!(
6172 view.selected_display_ranges(cx),
6173 &[empty_range(3, "abcd".len())]
6174 );
6175
6176 view.move_down(&MoveDown, cx);
6177 assert_eq!(
6178 view.selected_display_ranges(cx),
6179 &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
6180 );
6181
6182 view.move_up(&MoveUp, cx);
6183 assert_eq!(
6184 view.selected_display_ranges(cx),
6185 &[empty_range(3, "abcd".len())]
6186 );
6187
6188 view.move_up(&MoveUp, cx);
6189 assert_eq!(
6190 view.selected_display_ranges(cx),
6191 &[empty_range(2, "αβγ".len())]
6192 );
6193 });
6194 }
6195
6196 #[gpui::test]
6197 fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
6198 let buffer = MultiBuffer::build_simple("abc\n def", cx);
6199 let settings = EditorSettings::test(&cx);
6200 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6201 view.update(cx, |view, cx| {
6202 view.select_display_ranges(
6203 &[
6204 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6205 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
6206 ],
6207 cx,
6208 );
6209 });
6210
6211 view.update(cx, |view, cx| {
6212 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6213 assert_eq!(
6214 view.selected_display_ranges(cx),
6215 &[
6216 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6217 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6218 ]
6219 );
6220 });
6221
6222 view.update(cx, |view, cx| {
6223 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6224 assert_eq!(
6225 view.selected_display_ranges(cx),
6226 &[
6227 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6228 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6229 ]
6230 );
6231 });
6232
6233 view.update(cx, |view, cx| {
6234 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6235 assert_eq!(
6236 view.selected_display_ranges(cx),
6237 &[
6238 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6239 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6240 ]
6241 );
6242 });
6243
6244 view.update(cx, |view, cx| {
6245 view.move_to_end_of_line(&MoveToEndOfLine, cx);
6246 assert_eq!(
6247 view.selected_display_ranges(cx),
6248 &[
6249 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6250 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
6251 ]
6252 );
6253 });
6254
6255 // Moving to the end of line again is a no-op.
6256 view.update(cx, |view, cx| {
6257 view.move_to_end_of_line(&MoveToEndOfLine, cx);
6258 assert_eq!(
6259 view.selected_display_ranges(cx),
6260 &[
6261 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6262 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
6263 ]
6264 );
6265 });
6266
6267 view.update(cx, |view, cx| {
6268 view.move_left(&MoveLeft, cx);
6269 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6270 assert_eq!(
6271 view.selected_display_ranges(cx),
6272 &[
6273 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6274 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
6275 ]
6276 );
6277 });
6278
6279 view.update(cx, |view, cx| {
6280 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6281 assert_eq!(
6282 view.selected_display_ranges(cx),
6283 &[
6284 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6285 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
6286 ]
6287 );
6288 });
6289
6290 view.update(cx, |view, cx| {
6291 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6292 assert_eq!(
6293 view.selected_display_ranges(cx),
6294 &[
6295 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6296 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
6297 ]
6298 );
6299 });
6300
6301 view.update(cx, |view, cx| {
6302 view.select_to_end_of_line(&SelectToEndOfLine(true), cx);
6303 assert_eq!(
6304 view.selected_display_ranges(cx),
6305 &[
6306 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
6307 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
6308 ]
6309 );
6310 });
6311
6312 view.update(cx, |view, cx| {
6313 view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
6314 assert_eq!(view.display_text(cx), "ab\n de");
6315 assert_eq!(
6316 view.selected_display_ranges(cx),
6317 &[
6318 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6319 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
6320 ]
6321 );
6322 });
6323
6324 view.update(cx, |view, cx| {
6325 view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
6326 assert_eq!(view.display_text(cx), "\n");
6327 assert_eq!(
6328 view.selected_display_ranges(cx),
6329 &[
6330 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6331 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6332 ]
6333 );
6334 });
6335 }
6336
6337 #[gpui::test]
6338 fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
6339 let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n {baz.qux()}", cx);
6340 let settings = EditorSettings::test(&cx);
6341 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6342 view.update(cx, |view, cx| {
6343 view.select_display_ranges(
6344 &[
6345 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
6346 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
6347 ],
6348 cx,
6349 );
6350 });
6351
6352 view.update(cx, |view, cx| {
6353 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6354 assert_eq!(
6355 view.selected_display_ranges(cx),
6356 &[
6357 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
6358 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
6359 ]
6360 );
6361 });
6362
6363 view.update(cx, |view, cx| {
6364 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6365 assert_eq!(
6366 view.selected_display_ranges(cx),
6367 &[
6368 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
6369 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
6370 ]
6371 );
6372 });
6373
6374 view.update(cx, |view, cx| {
6375 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6376 assert_eq!(
6377 view.selected_display_ranges(cx),
6378 &[
6379 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
6380 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
6381 ]
6382 );
6383 });
6384
6385 view.update(cx, |view, cx| {
6386 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6387 assert_eq!(
6388 view.selected_display_ranges(cx),
6389 &[
6390 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6391 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6392 ]
6393 );
6394 });
6395
6396 view.update(cx, |view, cx| {
6397 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6398 assert_eq!(
6399 view.selected_display_ranges(cx),
6400 &[
6401 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6402 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
6403 ]
6404 );
6405 });
6406
6407 view.update(cx, |view, cx| {
6408 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6409 assert_eq!(
6410 view.selected_display_ranges(cx),
6411 &[
6412 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6413 DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
6414 ]
6415 );
6416 });
6417
6418 view.update(cx, |view, cx| {
6419 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6420 assert_eq!(
6421 view.selected_display_ranges(cx),
6422 &[
6423 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
6424 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6425 ]
6426 );
6427 });
6428
6429 view.update(cx, |view, cx| {
6430 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6431 assert_eq!(
6432 view.selected_display_ranges(cx),
6433 &[
6434 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
6435 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
6436 ]
6437 );
6438 });
6439
6440 view.update(cx, |view, cx| {
6441 view.move_right(&MoveRight, cx);
6442 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
6443 assert_eq!(
6444 view.selected_display_ranges(cx),
6445 &[
6446 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
6447 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
6448 ]
6449 );
6450 });
6451
6452 view.update(cx, |view, cx| {
6453 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
6454 assert_eq!(
6455 view.selected_display_ranges(cx),
6456 &[
6457 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
6458 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
6459 ]
6460 );
6461 });
6462
6463 view.update(cx, |view, cx| {
6464 view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
6465 assert_eq!(
6466 view.selected_display_ranges(cx),
6467 &[
6468 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
6469 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
6470 ]
6471 );
6472 });
6473 }
6474
6475 #[gpui::test]
6476 fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
6477 let buffer = MultiBuffer::build_simple("use one::{\n two::three::four::five\n};", cx);
6478 let settings = EditorSettings::test(&cx);
6479 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6480
6481 view.update(cx, |view, cx| {
6482 view.set_wrap_width(Some(140.), cx);
6483 assert_eq!(
6484 view.display_text(cx),
6485 "use one::{\n two::three::\n four::five\n};"
6486 );
6487
6488 view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx);
6489
6490 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6491 assert_eq!(
6492 view.selected_display_ranges(cx),
6493 &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
6494 );
6495
6496 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6497 assert_eq!(
6498 view.selected_display_ranges(cx),
6499 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
6500 );
6501
6502 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6503 assert_eq!(
6504 view.selected_display_ranges(cx),
6505 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
6506 );
6507
6508 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6509 assert_eq!(
6510 view.selected_display_ranges(cx),
6511 &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
6512 );
6513
6514 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6515 assert_eq!(
6516 view.selected_display_ranges(cx),
6517 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
6518 );
6519
6520 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6521 assert_eq!(
6522 view.selected_display_ranges(cx),
6523 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
6524 );
6525 });
6526 }
6527
6528 #[gpui::test]
6529 fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
6530 let buffer = MultiBuffer::build_simple("one two three four", cx);
6531 let settings = EditorSettings::test(&cx);
6532 let (_, view) = cx.add_window(Default::default(), |cx| {
6533 build_editor(buffer.clone(), settings, cx)
6534 });
6535
6536 view.update(cx, |view, cx| {
6537 view.select_display_ranges(
6538 &[
6539 // an empty selection - the preceding word fragment is deleted
6540 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6541 // characters selected - they are deleted
6542 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
6543 ],
6544 cx,
6545 );
6546 view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
6547 });
6548
6549 assert_eq!(buffer.read(cx).read(cx).text(), "e two te four");
6550
6551 view.update(cx, |view, cx| {
6552 view.select_display_ranges(
6553 &[
6554 // an empty selection - the following word fragment is deleted
6555 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6556 // characters selected - they are deleted
6557 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
6558 ],
6559 cx,
6560 );
6561 view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
6562 });
6563
6564 assert_eq!(buffer.read(cx).read(cx).text(), "e t te our");
6565 }
6566
6567 #[gpui::test]
6568 fn test_newline(cx: &mut gpui::MutableAppContext) {
6569 let buffer = MultiBuffer::build_simple("aaaa\n bbbb\n", cx);
6570 let settings = EditorSettings::test(&cx);
6571 let (_, view) = cx.add_window(Default::default(), |cx| {
6572 build_editor(buffer.clone(), settings, cx)
6573 });
6574
6575 view.update(cx, |view, cx| {
6576 view.select_display_ranges(
6577 &[
6578 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6579 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6580 DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
6581 ],
6582 cx,
6583 );
6584
6585 view.newline(&Newline, cx);
6586 assert_eq!(view.text(cx), "aa\naa\n \n bb\n bb\n");
6587 });
6588 }
6589
6590 #[gpui::test]
6591 fn test_newline_with_old_selections(cx: &mut gpui::MutableAppContext) {
6592 let buffer = MultiBuffer::build_simple(
6593 "
6594 a
6595 b(
6596 X
6597 )
6598 c(
6599 X
6600 )
6601 "
6602 .unindent()
6603 .as_str(),
6604 cx,
6605 );
6606
6607 let settings = EditorSettings::test(&cx);
6608 let (_, editor) = cx.add_window(Default::default(), |cx| {
6609 let mut editor = build_editor(buffer.clone(), settings, cx);
6610 editor.select_ranges(
6611 [
6612 Point::new(2, 4)..Point::new(2, 5),
6613 Point::new(5, 4)..Point::new(5, 5),
6614 ],
6615 None,
6616 cx,
6617 );
6618 editor
6619 });
6620
6621 // Edit the buffer directly, deleting ranges surrounding the editor's selections
6622 buffer.update(cx, |buffer, cx| {
6623 buffer.edit(
6624 [
6625 Point::new(1, 2)..Point::new(3, 0),
6626 Point::new(4, 2)..Point::new(6, 0),
6627 ],
6628 "",
6629 cx,
6630 );
6631 assert_eq!(
6632 buffer.read(cx).text(),
6633 "
6634 a
6635 b()
6636 c()
6637 "
6638 .unindent()
6639 );
6640 });
6641
6642 editor.update(cx, |editor, cx| {
6643 assert_eq!(
6644 editor.selected_ranges(cx),
6645 &[
6646 Point::new(1, 2)..Point::new(1, 2),
6647 Point::new(2, 2)..Point::new(2, 2),
6648 ],
6649 );
6650
6651 editor.newline(&Newline, cx);
6652 assert_eq!(
6653 editor.text(cx),
6654 "
6655 a
6656 b(
6657 )
6658 c(
6659 )
6660 "
6661 .unindent()
6662 );
6663
6664 // The selections are moved after the inserted newlines
6665 assert_eq!(
6666 editor.selected_ranges(cx),
6667 &[
6668 Point::new(2, 0)..Point::new(2, 0),
6669 Point::new(4, 0)..Point::new(4, 0),
6670 ],
6671 );
6672 });
6673 }
6674
6675 #[gpui::test]
6676 fn test_insert_with_old_selections(cx: &mut gpui::MutableAppContext) {
6677 let buffer = MultiBuffer::build_simple("a( X ), b( Y ), c( Z )", cx);
6678
6679 let settings = EditorSettings::test(&cx);
6680 let (_, editor) = cx.add_window(Default::default(), |cx| {
6681 let mut editor = build_editor(buffer.clone(), settings, cx);
6682 editor.select_ranges([3..4, 11..12, 19..20], None, cx);
6683 editor
6684 });
6685
6686 // Edit the buffer directly, deleting ranges surrounding the editor's selections
6687 buffer.update(cx, |buffer, cx| {
6688 buffer.edit([2..5, 10..13, 18..21], "", cx);
6689 assert_eq!(buffer.read(cx).text(), "a(), b(), c()".unindent());
6690 });
6691
6692 editor.update(cx, |editor, cx| {
6693 assert_eq!(editor.selected_ranges(cx), &[2..2, 7..7, 12..12],);
6694
6695 editor.insert("Z", cx);
6696 assert_eq!(editor.text(cx), "a(Z), b(Z), c(Z)");
6697
6698 // The selections are moved after the inserted characters
6699 assert_eq!(editor.selected_ranges(cx), &[3..3, 9..9, 15..15],);
6700 });
6701 }
6702
6703 #[gpui::test]
6704 fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
6705 let buffer = MultiBuffer::build_simple(" one two\nthree\n four", cx);
6706 let settings = EditorSettings::test(&cx);
6707 let (_, view) = cx.add_window(Default::default(), |cx| {
6708 build_editor(buffer.clone(), settings, cx)
6709 });
6710
6711 view.update(cx, |view, cx| {
6712 // two selections on the same line
6713 view.select_display_ranges(
6714 &[
6715 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
6716 DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
6717 ],
6718 cx,
6719 );
6720
6721 // indent from mid-tabstop to full tabstop
6722 view.tab(&Tab, cx);
6723 assert_eq!(view.text(cx), " one two\nthree\n four");
6724 assert_eq!(
6725 view.selected_display_ranges(cx),
6726 &[
6727 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
6728 DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
6729 ]
6730 );
6731
6732 // outdent from 1 tabstop to 0 tabstops
6733 view.outdent(&Outdent, cx);
6734 assert_eq!(view.text(cx), "one two\nthree\n four");
6735 assert_eq!(
6736 view.selected_display_ranges(cx),
6737 &[
6738 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
6739 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
6740 ]
6741 );
6742
6743 // select across line ending
6744 view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx);
6745
6746 // indent and outdent affect only the preceding line
6747 view.tab(&Tab, cx);
6748 assert_eq!(view.text(cx), "one two\n three\n four");
6749 assert_eq!(
6750 view.selected_display_ranges(cx),
6751 &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
6752 );
6753 view.outdent(&Outdent, cx);
6754 assert_eq!(view.text(cx), "one two\nthree\n four");
6755 assert_eq!(
6756 view.selected_display_ranges(cx),
6757 &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
6758 );
6759
6760 // Ensure that indenting/outdenting works when the cursor is at column 0.
6761 view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
6762 view.tab(&Tab, cx);
6763 assert_eq!(view.text(cx), "one two\n three\n four");
6764 assert_eq!(
6765 view.selected_display_ranges(cx),
6766 &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
6767 );
6768
6769 view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
6770 view.outdent(&Outdent, cx);
6771 assert_eq!(view.text(cx), "one two\nthree\n four");
6772 assert_eq!(
6773 view.selected_display_ranges(cx),
6774 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6775 );
6776 });
6777 }
6778
6779 #[gpui::test]
6780 fn test_backspace(cx: &mut gpui::MutableAppContext) {
6781 let buffer =
6782 MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
6783 let settings = EditorSettings::test(&cx);
6784 let (_, view) = cx.add_window(Default::default(), |cx| {
6785 build_editor(buffer.clone(), settings, cx)
6786 });
6787
6788 view.update(cx, |view, cx| {
6789 view.select_display_ranges(
6790 &[
6791 // an empty selection - the preceding character is deleted
6792 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6793 // one character selected - it is deleted
6794 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
6795 // a line suffix selected - it is deleted
6796 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
6797 ],
6798 cx,
6799 );
6800 view.backspace(&Backspace, cx);
6801 });
6802
6803 assert_eq!(
6804 buffer.read(cx).read(cx).text(),
6805 "oe two three\nfou five six\nseven ten\n"
6806 );
6807 }
6808
6809 #[gpui::test]
6810 fn test_delete(cx: &mut gpui::MutableAppContext) {
6811 let buffer =
6812 MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
6813 let settings = EditorSettings::test(&cx);
6814 let (_, view) = cx.add_window(Default::default(), |cx| {
6815 build_editor(buffer.clone(), settings, cx)
6816 });
6817
6818 view.update(cx, |view, cx| {
6819 view.select_display_ranges(
6820 &[
6821 // an empty selection - the following character is deleted
6822 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6823 // one character selected - it is deleted
6824 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
6825 // a line suffix selected - it is deleted
6826 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
6827 ],
6828 cx,
6829 );
6830 view.delete(&Delete, cx);
6831 });
6832
6833 assert_eq!(
6834 buffer.read(cx).read(cx).text(),
6835 "on two three\nfou five six\nseven ten\n"
6836 );
6837 }
6838
6839 #[gpui::test]
6840 fn test_delete_line(cx: &mut gpui::MutableAppContext) {
6841 let settings = EditorSettings::test(&cx);
6842 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
6843 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6844 view.update(cx, |view, cx| {
6845 view.select_display_ranges(
6846 &[
6847 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6848 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
6849 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
6850 ],
6851 cx,
6852 );
6853 view.delete_line(&DeleteLine, cx);
6854 assert_eq!(view.display_text(cx), "ghi");
6855 assert_eq!(
6856 view.selected_display_ranges(cx),
6857 vec![
6858 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6859 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
6860 ]
6861 );
6862 });
6863
6864 let settings = EditorSettings::test(&cx);
6865 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
6866 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6867 view.update(cx, |view, cx| {
6868 view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx);
6869 view.delete_line(&DeleteLine, cx);
6870 assert_eq!(view.display_text(cx), "ghi\n");
6871 assert_eq!(
6872 view.selected_display_ranges(cx),
6873 vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
6874 );
6875 });
6876 }
6877
6878 #[gpui::test]
6879 fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
6880 let settings = EditorSettings::test(&cx);
6881 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
6882 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6883 view.update(cx, |view, cx| {
6884 view.select_display_ranges(
6885 &[
6886 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
6887 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6888 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6889 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
6890 ],
6891 cx,
6892 );
6893 view.duplicate_line(&DuplicateLine, cx);
6894 assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
6895 assert_eq!(
6896 view.selected_display_ranges(cx),
6897 vec![
6898 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
6899 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6900 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
6901 DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
6902 ]
6903 );
6904 });
6905
6906 let settings = EditorSettings::test(&cx);
6907 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
6908 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6909 view.update(cx, |view, cx| {
6910 view.select_display_ranges(
6911 &[
6912 DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
6913 DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
6914 ],
6915 cx,
6916 );
6917 view.duplicate_line(&DuplicateLine, cx);
6918 assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
6919 assert_eq!(
6920 view.selected_display_ranges(cx),
6921 vec![
6922 DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
6923 DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
6924 ]
6925 );
6926 });
6927 }
6928
6929 #[gpui::test]
6930 fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
6931 let settings = EditorSettings::test(&cx);
6932 let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
6933 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6934 view.update(cx, |view, cx| {
6935 view.fold_ranges(
6936 vec![
6937 Point::new(0, 2)..Point::new(1, 2),
6938 Point::new(2, 3)..Point::new(4, 1),
6939 Point::new(7, 0)..Point::new(8, 4),
6940 ],
6941 cx,
6942 );
6943 view.select_display_ranges(
6944 &[
6945 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6946 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
6947 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
6948 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
6949 ],
6950 cx,
6951 );
6952 assert_eq!(
6953 view.display_text(cx),
6954 "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
6955 );
6956
6957 view.move_line_up(&MoveLineUp, cx);
6958 assert_eq!(
6959 view.display_text(cx),
6960 "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
6961 );
6962 assert_eq!(
6963 view.selected_display_ranges(cx),
6964 vec![
6965 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6966 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
6967 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
6968 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
6969 ]
6970 );
6971 });
6972
6973 view.update(cx, |view, cx| {
6974 view.move_line_down(&MoveLineDown, cx);
6975 assert_eq!(
6976 view.display_text(cx),
6977 "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
6978 );
6979 assert_eq!(
6980 view.selected_display_ranges(cx),
6981 vec![
6982 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6983 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
6984 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
6985 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
6986 ]
6987 );
6988 });
6989
6990 view.update(cx, |view, cx| {
6991 view.move_line_down(&MoveLineDown, cx);
6992 assert_eq!(
6993 view.display_text(cx),
6994 "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
6995 );
6996 assert_eq!(
6997 view.selected_display_ranges(cx),
6998 vec![
6999 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7000 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7001 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7002 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
7003 ]
7004 );
7005 });
7006
7007 view.update(cx, |view, cx| {
7008 view.move_line_up(&MoveLineUp, cx);
7009 assert_eq!(
7010 view.display_text(cx),
7011 "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
7012 );
7013 assert_eq!(
7014 view.selected_display_ranges(cx),
7015 vec![
7016 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7017 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7018 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
7019 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
7020 ]
7021 );
7022 });
7023 }
7024
7025 #[gpui::test]
7026 fn test_move_line_up_down_with_blocks(cx: &mut gpui::MutableAppContext) {
7027 let settings = EditorSettings::test(&cx);
7028 let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
7029 let snapshot = buffer.read(cx).snapshot(cx);
7030 let (_, editor) =
7031 cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7032 editor.update(cx, |editor, cx| {
7033 editor.insert_blocks(
7034 [BlockProperties {
7035 position: snapshot.anchor_after(Point::new(2, 0)),
7036 disposition: BlockDisposition::Below,
7037 height: 1,
7038 render: Arc::new(|_| Empty::new().boxed()),
7039 }],
7040 cx,
7041 );
7042 editor.select_ranges([Point::new(2, 0)..Point::new(2, 0)], None, cx);
7043 editor.move_line_down(&MoveLineDown, cx);
7044 });
7045 }
7046
7047 #[gpui::test]
7048 fn test_clipboard(cx: &mut gpui::MutableAppContext) {
7049 let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
7050 let settings = EditorSettings::test(&cx);
7051 let view = cx
7052 .add_window(Default::default(), |cx| {
7053 build_editor(buffer.clone(), settings, cx)
7054 })
7055 .1;
7056
7057 // Cut with three selections. Clipboard text is divided into three slices.
7058 view.update(cx, |view, cx| {
7059 view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
7060 view.cut(&Cut, cx);
7061 assert_eq!(view.display_text(cx), "two four six ");
7062 });
7063
7064 // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
7065 view.update(cx, |view, cx| {
7066 view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
7067 view.paste(&Paste, cx);
7068 assert_eq!(view.display_text(cx), "two one✅ four three six five ");
7069 assert_eq!(
7070 view.selected_display_ranges(cx),
7071 &[
7072 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
7073 DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
7074 DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
7075 ]
7076 );
7077 });
7078
7079 // Paste again but with only two cursors. Since the number of cursors doesn't
7080 // match the number of slices in the clipboard, the entire clipboard text
7081 // is pasted at each cursor.
7082 view.update(cx, |view, cx| {
7083 view.select_ranges(vec![0..0, 31..31], None, cx);
7084 view.handle_input(&Input("( ".into()), cx);
7085 view.paste(&Paste, cx);
7086 view.handle_input(&Input(") ".into()), cx);
7087 assert_eq!(
7088 view.display_text(cx),
7089 "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7090 );
7091 });
7092
7093 view.update(cx, |view, cx| {
7094 view.select_ranges(vec![0..0], None, cx);
7095 view.handle_input(&Input("123\n4567\n89\n".into()), cx);
7096 assert_eq!(
7097 view.display_text(cx),
7098 "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7099 );
7100 });
7101
7102 // Cut with three selections, one of which is full-line.
7103 view.update(cx, |view, cx| {
7104 view.select_display_ranges(
7105 &[
7106 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
7107 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7108 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
7109 ],
7110 cx,
7111 );
7112 view.cut(&Cut, cx);
7113 assert_eq!(
7114 view.display_text(cx),
7115 "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7116 );
7117 });
7118
7119 // Paste with three selections, noticing how the copied selection that was full-line
7120 // gets inserted before the second cursor.
7121 view.update(cx, |view, cx| {
7122 view.select_display_ranges(
7123 &[
7124 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7125 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7126 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
7127 ],
7128 cx,
7129 );
7130 view.paste(&Paste, cx);
7131 assert_eq!(
7132 view.display_text(cx),
7133 "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
7134 );
7135 assert_eq!(
7136 view.selected_display_ranges(cx),
7137 &[
7138 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7139 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7140 DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
7141 ]
7142 );
7143 });
7144
7145 // Copy with a single cursor only, which writes the whole line into the clipboard.
7146 view.update(cx, |view, cx| {
7147 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx);
7148 view.copy(&Copy, cx);
7149 });
7150
7151 // Paste with three selections, noticing how the copied full-line selection is inserted
7152 // before the empty selections but replaces the selection that is non-empty.
7153 view.update(cx, |view, cx| {
7154 view.select_display_ranges(
7155 &[
7156 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7157 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
7158 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7159 ],
7160 cx,
7161 );
7162 view.paste(&Paste, cx);
7163 assert_eq!(
7164 view.display_text(cx),
7165 "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
7166 );
7167 assert_eq!(
7168 view.selected_display_ranges(cx),
7169 &[
7170 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7171 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7172 DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
7173 ]
7174 );
7175 });
7176 }
7177
7178 #[gpui::test]
7179 fn test_select_all(cx: &mut gpui::MutableAppContext) {
7180 let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
7181 let settings = EditorSettings::test(&cx);
7182 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7183 view.update(cx, |view, cx| {
7184 view.select_all(&SelectAll, cx);
7185 assert_eq!(
7186 view.selected_display_ranges(cx),
7187 &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
7188 );
7189 });
7190 }
7191
7192 #[gpui::test]
7193 fn test_select_line(cx: &mut gpui::MutableAppContext) {
7194 let settings = EditorSettings::test(&cx);
7195 let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
7196 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7197 view.update(cx, |view, cx| {
7198 view.select_display_ranges(
7199 &[
7200 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7201 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7202 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7203 DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
7204 ],
7205 cx,
7206 );
7207 view.select_line(&SelectLine, cx);
7208 assert_eq!(
7209 view.selected_display_ranges(cx),
7210 vec![
7211 DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
7212 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
7213 ]
7214 );
7215 });
7216
7217 view.update(cx, |view, cx| {
7218 view.select_line(&SelectLine, cx);
7219 assert_eq!(
7220 view.selected_display_ranges(cx),
7221 vec![
7222 DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
7223 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
7224 ]
7225 );
7226 });
7227
7228 view.update(cx, |view, cx| {
7229 view.select_line(&SelectLine, cx);
7230 assert_eq!(
7231 view.selected_display_ranges(cx),
7232 vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
7233 );
7234 });
7235 }
7236
7237 #[gpui::test]
7238 fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
7239 let settings = EditorSettings::test(&cx);
7240 let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
7241 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7242 view.update(cx, |view, cx| {
7243 view.fold_ranges(
7244 vec![
7245 Point::new(0, 2)..Point::new(1, 2),
7246 Point::new(2, 3)..Point::new(4, 1),
7247 Point::new(7, 0)..Point::new(8, 4),
7248 ],
7249 cx,
7250 );
7251 view.select_display_ranges(
7252 &[
7253 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7254 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7255 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7256 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
7257 ],
7258 cx,
7259 );
7260 assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
7261 });
7262
7263 view.update(cx, |view, cx| {
7264 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
7265 assert_eq!(
7266 view.display_text(cx),
7267 "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
7268 );
7269 assert_eq!(
7270 view.selected_display_ranges(cx),
7271 [
7272 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7273 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7274 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
7275 DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
7276 ]
7277 );
7278 });
7279
7280 view.update(cx, |view, cx| {
7281 view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx);
7282 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
7283 assert_eq!(
7284 view.display_text(cx),
7285 "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
7286 );
7287 assert_eq!(
7288 view.selected_display_ranges(cx),
7289 [
7290 DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
7291 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
7292 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
7293 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
7294 DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
7295 DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
7296 DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
7297 DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
7298 ]
7299 );
7300 });
7301 }
7302
7303 #[gpui::test]
7304 fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
7305 let settings = EditorSettings::test(&cx);
7306 let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
7307 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7308
7309 view.update(cx, |view, cx| {
7310 view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx);
7311 });
7312 view.update(cx, |view, cx| {
7313 view.add_selection_above(&AddSelectionAbove, cx);
7314 assert_eq!(
7315 view.selected_display_ranges(cx),
7316 vec![
7317 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7318 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
7319 ]
7320 );
7321 });
7322
7323 view.update(cx, |view, cx| {
7324 view.add_selection_above(&AddSelectionAbove, cx);
7325 assert_eq!(
7326 view.selected_display_ranges(cx),
7327 vec![
7328 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7329 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
7330 ]
7331 );
7332 });
7333
7334 view.update(cx, |view, cx| {
7335 view.add_selection_below(&AddSelectionBelow, cx);
7336 assert_eq!(
7337 view.selected_display_ranges(cx),
7338 vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
7339 );
7340 });
7341
7342 view.update(cx, |view, cx| {
7343 view.add_selection_below(&AddSelectionBelow, cx);
7344 assert_eq!(
7345 view.selected_display_ranges(cx),
7346 vec![
7347 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
7348 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
7349 ]
7350 );
7351 });
7352
7353 view.update(cx, |view, cx| {
7354 view.add_selection_below(&AddSelectionBelow, cx);
7355 assert_eq!(
7356 view.selected_display_ranges(cx),
7357 vec![
7358 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
7359 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
7360 ]
7361 );
7362 });
7363
7364 view.update(cx, |view, cx| {
7365 view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx);
7366 });
7367 view.update(cx, |view, cx| {
7368 view.add_selection_below(&AddSelectionBelow, cx);
7369 assert_eq!(
7370 view.selected_display_ranges(cx),
7371 vec![
7372 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7373 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
7374 ]
7375 );
7376 });
7377
7378 view.update(cx, |view, cx| {
7379 view.add_selection_below(&AddSelectionBelow, cx);
7380 assert_eq!(
7381 view.selected_display_ranges(cx),
7382 vec![
7383 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7384 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
7385 ]
7386 );
7387 });
7388
7389 view.update(cx, |view, cx| {
7390 view.add_selection_above(&AddSelectionAbove, cx);
7391 assert_eq!(
7392 view.selected_display_ranges(cx),
7393 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
7394 );
7395 });
7396
7397 view.update(cx, |view, cx| {
7398 view.add_selection_above(&AddSelectionAbove, cx);
7399 assert_eq!(
7400 view.selected_display_ranges(cx),
7401 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
7402 );
7403 });
7404
7405 view.update(cx, |view, cx| {
7406 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx);
7407 view.add_selection_below(&AddSelectionBelow, cx);
7408 assert_eq!(
7409 view.selected_display_ranges(cx),
7410 vec![
7411 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
7412 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
7413 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
7414 ]
7415 );
7416 });
7417
7418 view.update(cx, |view, cx| {
7419 view.add_selection_below(&AddSelectionBelow, cx);
7420 assert_eq!(
7421 view.selected_display_ranges(cx),
7422 vec![
7423 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
7424 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
7425 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
7426 DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
7427 ]
7428 );
7429 });
7430
7431 view.update(cx, |view, cx| {
7432 view.add_selection_above(&AddSelectionAbove, cx);
7433 assert_eq!(
7434 view.selected_display_ranges(cx),
7435 vec![
7436 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
7437 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
7438 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
7439 ]
7440 );
7441 });
7442
7443 view.update(cx, |view, cx| {
7444 view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx);
7445 });
7446 view.update(cx, |view, cx| {
7447 view.add_selection_above(&AddSelectionAbove, cx);
7448 assert_eq!(
7449 view.selected_display_ranges(cx),
7450 vec![
7451 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
7452 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
7453 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
7454 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
7455 ]
7456 );
7457 });
7458
7459 view.update(cx, |view, cx| {
7460 view.add_selection_below(&AddSelectionBelow, cx);
7461 assert_eq!(
7462 view.selected_display_ranges(cx),
7463 vec![
7464 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
7465 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
7466 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
7467 ]
7468 );
7469 });
7470 }
7471
7472 #[gpui::test]
7473 async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
7474 let settings = cx.read(EditorSettings::test);
7475 let language = Arc::new(Language::new(
7476 LanguageConfig::default(),
7477 Some(tree_sitter_rust::language()),
7478 ));
7479
7480 let text = r#"
7481 use mod1::mod2::{mod3, mod4};
7482
7483 fn fn_1(param1: bool, param2: &str) {
7484 let var1 = "text";
7485 }
7486 "#
7487 .unindent();
7488
7489 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
7490 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7491 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7492 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
7493 .await;
7494
7495 view.update(&mut cx, |view, cx| {
7496 view.select_display_ranges(
7497 &[
7498 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
7499 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
7500 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
7501 ],
7502 cx,
7503 );
7504 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7505 });
7506 assert_eq!(
7507 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7508 &[
7509 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
7510 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
7511 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
7512 ]
7513 );
7514
7515 view.update(&mut cx, |view, cx| {
7516 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7517 });
7518 assert_eq!(
7519 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7520 &[
7521 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
7522 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
7523 ]
7524 );
7525
7526 view.update(&mut cx, |view, cx| {
7527 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7528 });
7529 assert_eq!(
7530 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7531 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
7532 );
7533
7534 // Trying to expand the selected syntax node one more time has no effect.
7535 view.update(&mut cx, |view, cx| {
7536 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7537 });
7538 assert_eq!(
7539 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7540 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
7541 );
7542
7543 view.update(&mut cx, |view, cx| {
7544 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
7545 });
7546 assert_eq!(
7547 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7548 &[
7549 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
7550 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
7551 ]
7552 );
7553
7554 view.update(&mut cx, |view, cx| {
7555 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
7556 });
7557 assert_eq!(
7558 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7559 &[
7560 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
7561 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
7562 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
7563 ]
7564 );
7565
7566 view.update(&mut cx, |view, cx| {
7567 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
7568 });
7569 assert_eq!(
7570 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7571 &[
7572 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
7573 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
7574 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
7575 ]
7576 );
7577
7578 // Trying to shrink the selected syntax node one more time has no effect.
7579 view.update(&mut cx, |view, cx| {
7580 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
7581 });
7582 assert_eq!(
7583 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7584 &[
7585 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
7586 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
7587 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
7588 ]
7589 );
7590
7591 // Ensure that we keep expanding the selection if the larger selection starts or ends within
7592 // a fold.
7593 view.update(&mut cx, |view, cx| {
7594 view.fold_ranges(
7595 vec![
7596 Point::new(0, 21)..Point::new(0, 24),
7597 Point::new(3, 20)..Point::new(3, 22),
7598 ],
7599 cx,
7600 );
7601 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7602 });
7603 assert_eq!(
7604 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7605 &[
7606 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
7607 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
7608 DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
7609 ]
7610 );
7611 }
7612
7613 #[gpui::test]
7614 async fn test_autoindent_selections(mut cx: gpui::TestAppContext) {
7615 let settings = cx.read(EditorSettings::test);
7616 let language = Arc::new(
7617 Language::new(
7618 LanguageConfig {
7619 brackets: vec![
7620 BracketPair {
7621 start: "{".to_string(),
7622 end: "}".to_string(),
7623 close: false,
7624 newline: true,
7625 },
7626 BracketPair {
7627 start: "(".to_string(),
7628 end: ")".to_string(),
7629 close: false,
7630 newline: true,
7631 },
7632 ],
7633 ..Default::default()
7634 },
7635 Some(tree_sitter_rust::language()),
7636 )
7637 .with_indents_query(
7638 r#"
7639 (_ "(" ")" @end) @indent
7640 (_ "{" "}" @end) @indent
7641 "#,
7642 )
7643 .unwrap(),
7644 );
7645
7646 let text = "fn a() {}";
7647
7648 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
7649 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7650 let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7651 editor
7652 .condition(&cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
7653 .await;
7654
7655 editor.update(&mut cx, |editor, cx| {
7656 editor.select_ranges([5..5, 8..8, 9..9], None, cx);
7657 editor.newline(&Newline, cx);
7658 assert_eq!(editor.text(cx), "fn a(\n \n) {\n \n}\n");
7659 assert_eq!(
7660 editor.selected_ranges(cx),
7661 &[
7662 Point::new(1, 4)..Point::new(1, 4),
7663 Point::new(3, 4)..Point::new(3, 4),
7664 Point::new(5, 0)..Point::new(5, 0)
7665 ]
7666 );
7667 });
7668 }
7669
7670 #[gpui::test]
7671 async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
7672 let settings = cx.read(EditorSettings::test);
7673 let language = Arc::new(Language::new(
7674 LanguageConfig {
7675 brackets: vec![
7676 BracketPair {
7677 start: "{".to_string(),
7678 end: "}".to_string(),
7679 close: true,
7680 newline: true,
7681 },
7682 BracketPair {
7683 start: "/*".to_string(),
7684 end: " */".to_string(),
7685 close: true,
7686 newline: true,
7687 },
7688 ],
7689 ..Default::default()
7690 },
7691 Some(tree_sitter_rust::language()),
7692 ));
7693
7694 let text = r#"
7695 a
7696
7697 /
7698
7699 "#
7700 .unindent();
7701
7702 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
7703 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7704 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7705 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
7706 .await;
7707
7708 view.update(&mut cx, |view, cx| {
7709 view.select_display_ranges(
7710 &[
7711 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7712 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7713 ],
7714 cx,
7715 );
7716 view.handle_input(&Input("{".to_string()), cx);
7717 view.handle_input(&Input("{".to_string()), cx);
7718 view.handle_input(&Input("{".to_string()), cx);
7719 assert_eq!(
7720 view.text(cx),
7721 "
7722 {{{}}}
7723 {{{}}}
7724 /
7725
7726 "
7727 .unindent()
7728 );
7729
7730 view.move_right(&MoveRight, cx);
7731 view.handle_input(&Input("}".to_string()), cx);
7732 view.handle_input(&Input("}".to_string()), cx);
7733 view.handle_input(&Input("}".to_string()), cx);
7734 assert_eq!(
7735 view.text(cx),
7736 "
7737 {{{}}}}
7738 {{{}}}}
7739 /
7740
7741 "
7742 .unindent()
7743 );
7744
7745 view.undo(&Undo, cx);
7746 view.handle_input(&Input("/".to_string()), cx);
7747 view.handle_input(&Input("*".to_string()), cx);
7748 assert_eq!(
7749 view.text(cx),
7750 "
7751 /* */
7752 /* */
7753 /
7754
7755 "
7756 .unindent()
7757 );
7758
7759 view.undo(&Undo, cx);
7760 view.select_display_ranges(
7761 &[
7762 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7763 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7764 ],
7765 cx,
7766 );
7767 view.handle_input(&Input("*".to_string()), cx);
7768 assert_eq!(
7769 view.text(cx),
7770 "
7771 a
7772
7773 /*
7774 *
7775 "
7776 .unindent()
7777 );
7778 });
7779 }
7780
7781 #[gpui::test]
7782 async fn test_snippets(mut cx: gpui::TestAppContext) {
7783 let settings = cx.read(EditorSettings::test);
7784
7785 let text = "
7786 a. b
7787 a. b
7788 a. b
7789 "
7790 .unindent();
7791 let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
7792 let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7793
7794 editor.update(&mut cx, |editor, cx| {
7795 let buffer = &editor.snapshot(cx).buffer_snapshot;
7796 let snippet = Snippet::parse("f(${1:one}, ${2:two}, ${1:three})$0").unwrap();
7797 let insertion_ranges = [
7798 Point::new(0, 2).to_offset(buffer)..Point::new(0, 2).to_offset(buffer),
7799 Point::new(1, 2).to_offset(buffer)..Point::new(1, 2).to_offset(buffer),
7800 Point::new(2, 2).to_offset(buffer)..Point::new(2, 2).to_offset(buffer),
7801 ];
7802
7803 editor
7804 .insert_snippet(&insertion_ranges, snippet, cx)
7805 .unwrap();
7806 assert_eq!(
7807 editor.text(cx),
7808 "
7809 a.f(one, two, three) b
7810 a.f(one, two, three) b
7811 a.f(one, two, three) b
7812 "
7813 .unindent()
7814 );
7815 assert_eq!(
7816 editor.selected_ranges::<Point>(cx),
7817 &[
7818 Point::new(0, 4)..Point::new(0, 7),
7819 Point::new(0, 14)..Point::new(0, 19),
7820 Point::new(1, 4)..Point::new(1, 7),
7821 Point::new(1, 14)..Point::new(1, 19),
7822 Point::new(2, 4)..Point::new(2, 7),
7823 Point::new(2, 14)..Point::new(2, 19),
7824 ]
7825 );
7826
7827 // Can't move earlier than the first tab stop
7828 editor.move_to_prev_snippet_tabstop(cx);
7829 assert_eq!(
7830 editor.selected_ranges::<Point>(cx),
7831 &[
7832 Point::new(0, 4)..Point::new(0, 7),
7833 Point::new(0, 14)..Point::new(0, 19),
7834 Point::new(1, 4)..Point::new(1, 7),
7835 Point::new(1, 14)..Point::new(1, 19),
7836 Point::new(2, 4)..Point::new(2, 7),
7837 Point::new(2, 14)..Point::new(2, 19),
7838 ]
7839 );
7840
7841 assert!(editor.move_to_next_snippet_tabstop(cx));
7842 assert_eq!(
7843 editor.selected_ranges::<Point>(cx),
7844 &[
7845 Point::new(0, 9)..Point::new(0, 12),
7846 Point::new(1, 9)..Point::new(1, 12),
7847 Point::new(2, 9)..Point::new(2, 12)
7848 ]
7849 );
7850
7851 editor.move_to_prev_snippet_tabstop(cx);
7852 assert_eq!(
7853 editor.selected_ranges::<Point>(cx),
7854 &[
7855 Point::new(0, 4)..Point::new(0, 7),
7856 Point::new(0, 14)..Point::new(0, 19),
7857 Point::new(1, 4)..Point::new(1, 7),
7858 Point::new(1, 14)..Point::new(1, 19),
7859 Point::new(2, 4)..Point::new(2, 7),
7860 Point::new(2, 14)..Point::new(2, 19),
7861 ]
7862 );
7863
7864 assert!(editor.move_to_next_snippet_tabstop(cx));
7865 assert!(editor.move_to_next_snippet_tabstop(cx));
7866 assert_eq!(
7867 editor.selected_ranges::<Point>(cx),
7868 &[
7869 Point::new(0, 20)..Point::new(0, 20),
7870 Point::new(1, 20)..Point::new(1, 20),
7871 Point::new(2, 20)..Point::new(2, 20)
7872 ]
7873 );
7874
7875 // As soon as the last tab stop is reached, snippet state is gone
7876 editor.move_to_prev_snippet_tabstop(cx);
7877 assert_eq!(
7878 editor.selected_ranges::<Point>(cx),
7879 &[
7880 Point::new(0, 20)..Point::new(0, 20),
7881 Point::new(1, 20)..Point::new(1, 20),
7882 Point::new(2, 20)..Point::new(2, 20)
7883 ]
7884 );
7885 });
7886 }
7887
7888 #[gpui::test]
7889 async fn test_completion(mut cx: gpui::TestAppContext) {
7890 let settings = cx.read(EditorSettings::test);
7891 let (language_server, mut fake) = lsp::LanguageServer::fake_with_capabilities(
7892 lsp::ServerCapabilities {
7893 completion_provider: Some(lsp::CompletionOptions {
7894 trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
7895 ..Default::default()
7896 }),
7897 ..Default::default()
7898 },
7899 cx.background(),
7900 );
7901
7902 let text = "
7903 one
7904 two
7905 three
7906 "
7907 .unindent();
7908
7909 let fs = FakeFs::new(cx.background().clone());
7910 fs.insert_file("/file", text).await;
7911
7912 let project = Project::test(fs, &mut cx);
7913
7914 let (worktree, relative_path) = project
7915 .update(&mut cx, |project, cx| {
7916 project.find_or_create_local_worktree("/file", false, cx)
7917 })
7918 .await
7919 .unwrap();
7920 let project_path = ProjectPath {
7921 worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
7922 path: relative_path.into(),
7923 };
7924 let buffer = project
7925 .update(&mut cx, |project, cx| project.open_buffer(project_path, cx))
7926 .await
7927 .unwrap();
7928 buffer.update(&mut cx, |buffer, cx| {
7929 buffer.set_language_server(Some(language_server), cx);
7930 });
7931
7932 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7933 buffer.next_notification(&cx).await;
7934
7935 let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7936
7937 editor.update(&mut cx, |editor, cx| {
7938 editor.project = Some(project);
7939 editor.select_ranges([Point::new(0, 3)..Point::new(0, 3)], None, cx);
7940 editor.handle_input(&Input(".".to_string()), cx);
7941 });
7942
7943 handle_completion_request(
7944 &mut fake,
7945 "/file",
7946 Point::new(0, 4),
7947 vec![
7948 (Point::new(0, 4)..Point::new(0, 4), "first_completion"),
7949 (Point::new(0, 4)..Point::new(0, 4), "second_completion"),
7950 ],
7951 )
7952 .await;
7953 editor
7954 .condition(&cx, |editor, _| editor.context_menu_visible())
7955 .await;
7956
7957 let apply_additional_edits = editor.update(&mut cx, |editor, cx| {
7958 editor.move_down(&MoveDown, cx);
7959 let apply_additional_edits = editor
7960 .confirm_completion(&ConfirmCompletion(None), cx)
7961 .unwrap();
7962 assert_eq!(
7963 editor.text(cx),
7964 "
7965 one.second_completion
7966 two
7967 three
7968 "
7969 .unindent()
7970 );
7971 apply_additional_edits
7972 });
7973
7974 handle_resolve_completion_request(
7975 &mut fake,
7976 Some((Point::new(2, 5)..Point::new(2, 5), "\nadditional edit")),
7977 )
7978 .await;
7979 apply_additional_edits.await.unwrap();
7980 assert_eq!(
7981 editor.read_with(&cx, |editor, cx| editor.text(cx)),
7982 "
7983 one.second_completion
7984 two
7985 three
7986 additional edit
7987 "
7988 .unindent()
7989 );
7990
7991 editor.update(&mut cx, |editor, cx| {
7992 editor.select_ranges(
7993 [
7994 Point::new(1, 3)..Point::new(1, 3),
7995 Point::new(2, 5)..Point::new(2, 5),
7996 ],
7997 None,
7998 cx,
7999 );
8000
8001 editor.handle_input(&Input(" ".to_string()), cx);
8002 assert!(editor.context_menu.is_none());
8003 editor.handle_input(&Input("s".to_string()), cx);
8004 assert!(editor.context_menu.is_none());
8005 });
8006
8007 handle_completion_request(
8008 &mut fake,
8009 "/file",
8010 Point::new(2, 7),
8011 vec![
8012 (Point::new(2, 6)..Point::new(2, 7), "fourth_completion"),
8013 (Point::new(2, 6)..Point::new(2, 7), "fifth_completion"),
8014 (Point::new(2, 6)..Point::new(2, 7), "sixth_completion"),
8015 ],
8016 )
8017 .await;
8018 editor
8019 .condition(&cx, |editor, _| editor.context_menu_visible())
8020 .await;
8021
8022 editor.update(&mut cx, |editor, cx| {
8023 editor.handle_input(&Input("i".to_string()), cx);
8024 });
8025
8026 handle_completion_request(
8027 &mut fake,
8028 "/file",
8029 Point::new(2, 8),
8030 vec![
8031 (Point::new(2, 6)..Point::new(2, 8), "fourth_completion"),
8032 (Point::new(2, 6)..Point::new(2, 8), "fifth_completion"),
8033 (Point::new(2, 6)..Point::new(2, 8), "sixth_completion"),
8034 ],
8035 )
8036 .await;
8037 editor
8038 .condition(&cx, |editor, _| editor.context_menu_visible())
8039 .await;
8040
8041 let apply_additional_edits = editor.update(&mut cx, |editor, cx| {
8042 let apply_additional_edits = editor
8043 .confirm_completion(&ConfirmCompletion(None), cx)
8044 .unwrap();
8045 assert_eq!(
8046 editor.text(cx),
8047 "
8048 one.second_completion
8049 two sixth_completion
8050 three sixth_completion
8051 additional edit
8052 "
8053 .unindent()
8054 );
8055 apply_additional_edits
8056 });
8057 handle_resolve_completion_request(&mut fake, None).await;
8058 apply_additional_edits.await.unwrap();
8059
8060 async fn handle_completion_request(
8061 fake: &mut FakeLanguageServer,
8062 path: &'static str,
8063 position: Point,
8064 completions: Vec<(Range<Point>, &'static str)>,
8065 ) {
8066 fake.handle_request::<lsp::request::Completion, _>(move |params| {
8067 assert_eq!(
8068 params.text_document_position.text_document.uri,
8069 lsp::Url::from_file_path(path).unwrap()
8070 );
8071 assert_eq!(
8072 params.text_document_position.position,
8073 lsp::Position::new(position.row, position.column)
8074 );
8075 Some(lsp::CompletionResponse::Array(
8076 completions
8077 .iter()
8078 .map(|(range, new_text)| lsp::CompletionItem {
8079 label: new_text.to_string(),
8080 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
8081 range: lsp::Range::new(
8082 lsp::Position::new(range.start.row, range.start.column),
8083 lsp::Position::new(range.start.row, range.start.column),
8084 ),
8085 new_text: new_text.to_string(),
8086 })),
8087 ..Default::default()
8088 })
8089 .collect(),
8090 ))
8091 })
8092 .next()
8093 .await;
8094 }
8095
8096 async fn handle_resolve_completion_request(
8097 fake: &mut FakeLanguageServer,
8098 edit: Option<(Range<Point>, &'static str)>,
8099 ) {
8100 fake.handle_request::<lsp::request::ResolveCompletionItem, _>(move |_| {
8101 lsp::CompletionItem {
8102 additional_text_edits: edit.clone().map(|(range, new_text)| {
8103 vec![lsp::TextEdit::new(
8104 lsp::Range::new(
8105 lsp::Position::new(range.start.row, range.start.column),
8106 lsp::Position::new(range.end.row, range.end.column),
8107 ),
8108 new_text.to_string(),
8109 )]
8110 }),
8111 ..Default::default()
8112 }
8113 })
8114 .next()
8115 .await;
8116 }
8117 }
8118
8119 #[gpui::test]
8120 async fn test_toggle_comment(mut cx: gpui::TestAppContext) {
8121 let settings = cx.read(EditorSettings::test);
8122 let language = Arc::new(Language::new(
8123 LanguageConfig {
8124 line_comment: Some("// ".to_string()),
8125 ..Default::default()
8126 },
8127 Some(tree_sitter_rust::language()),
8128 ));
8129
8130 let text = "
8131 fn a() {
8132 //b();
8133 // c();
8134 // d();
8135 }
8136 "
8137 .unindent();
8138
8139 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8140 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8141 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
8142
8143 view.update(&mut cx, |editor, cx| {
8144 // If multiple selections intersect a line, the line is only
8145 // toggled once.
8146 editor.select_display_ranges(
8147 &[
8148 DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
8149 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
8150 ],
8151 cx,
8152 );
8153 editor.toggle_comments(&ToggleComments, cx);
8154 assert_eq!(
8155 editor.text(cx),
8156 "
8157 fn a() {
8158 b();
8159 c();
8160 d();
8161 }
8162 "
8163 .unindent()
8164 );
8165
8166 // The comment prefix is inserted at the same column for every line
8167 // in a selection.
8168 editor.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx);
8169 editor.toggle_comments(&ToggleComments, cx);
8170 assert_eq!(
8171 editor.text(cx),
8172 "
8173 fn a() {
8174 // b();
8175 // c();
8176 // d();
8177 }
8178 "
8179 .unindent()
8180 );
8181
8182 // If a selection ends at the beginning of a line, that line is not toggled.
8183 editor.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx);
8184 editor.toggle_comments(&ToggleComments, cx);
8185 assert_eq!(
8186 editor.text(cx),
8187 "
8188 fn a() {
8189 // b();
8190 c();
8191 // d();
8192 }
8193 "
8194 .unindent()
8195 );
8196 });
8197 }
8198
8199 #[gpui::test]
8200 fn test_editing_disjoint_excerpts(cx: &mut gpui::MutableAppContext) {
8201 let settings = EditorSettings::test(cx);
8202 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8203 let multibuffer = cx.add_model(|cx| {
8204 let mut multibuffer = MultiBuffer::new(0);
8205 multibuffer.push_excerpts(
8206 buffer.clone(),
8207 [
8208 Point::new(0, 0)..Point::new(0, 4),
8209 Point::new(1, 0)..Point::new(1, 4),
8210 ],
8211 cx,
8212 );
8213 multibuffer
8214 });
8215
8216 assert_eq!(multibuffer.read(cx).read(cx).text(), "aaaa\nbbbb");
8217
8218 let (_, view) = cx.add_window(Default::default(), |cx| {
8219 build_editor(multibuffer, settings, cx)
8220 });
8221 view.update(cx, |view, cx| {
8222 assert_eq!(view.text(cx), "aaaa\nbbbb");
8223 view.select_ranges(
8224 [
8225 Point::new(0, 0)..Point::new(0, 0),
8226 Point::new(1, 0)..Point::new(1, 0),
8227 ],
8228 None,
8229 cx,
8230 );
8231
8232 view.handle_input(&Input("X".to_string()), cx);
8233 assert_eq!(view.text(cx), "Xaaaa\nXbbbb");
8234 assert_eq!(
8235 view.selected_ranges(cx),
8236 [
8237 Point::new(0, 1)..Point::new(0, 1),
8238 Point::new(1, 1)..Point::new(1, 1),
8239 ]
8240 )
8241 });
8242 }
8243
8244 #[gpui::test]
8245 fn test_editing_overlapping_excerpts(cx: &mut gpui::MutableAppContext) {
8246 let settings = EditorSettings::test(cx);
8247 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8248 let multibuffer = cx.add_model(|cx| {
8249 let mut multibuffer = MultiBuffer::new(0);
8250 multibuffer.push_excerpts(
8251 buffer,
8252 [
8253 Point::new(0, 0)..Point::new(1, 4),
8254 Point::new(1, 0)..Point::new(2, 4),
8255 ],
8256 cx,
8257 );
8258 multibuffer
8259 });
8260
8261 assert_eq!(
8262 multibuffer.read(cx).read(cx).text(),
8263 "aaaa\nbbbb\nbbbb\ncccc"
8264 );
8265
8266 let (_, view) = cx.add_window(Default::default(), |cx| {
8267 build_editor(multibuffer, settings, cx)
8268 });
8269 view.update(cx, |view, cx| {
8270 view.select_ranges(
8271 [
8272 Point::new(1, 1)..Point::new(1, 1),
8273 Point::new(2, 3)..Point::new(2, 3),
8274 ],
8275 None,
8276 cx,
8277 );
8278
8279 view.handle_input(&Input("X".to_string()), cx);
8280 assert_eq!(view.text(cx), "aaaa\nbXbbXb\nbXbbXb\ncccc");
8281 assert_eq!(
8282 view.selected_ranges(cx),
8283 [
8284 Point::new(1, 2)..Point::new(1, 2),
8285 Point::new(2, 5)..Point::new(2, 5),
8286 ]
8287 );
8288
8289 view.newline(&Newline, cx);
8290 assert_eq!(view.text(cx), "aaaa\nbX\nbbX\nb\nbX\nbbX\nb\ncccc");
8291 assert_eq!(
8292 view.selected_ranges(cx),
8293 [
8294 Point::new(2, 0)..Point::new(2, 0),
8295 Point::new(6, 0)..Point::new(6, 0),
8296 ]
8297 );
8298 });
8299 }
8300
8301 #[gpui::test]
8302 fn test_refresh_selections(cx: &mut gpui::MutableAppContext) {
8303 let settings = EditorSettings::test(cx);
8304 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8305 let mut excerpt1_id = None;
8306 let multibuffer = cx.add_model(|cx| {
8307 let mut multibuffer = MultiBuffer::new(0);
8308 excerpt1_id = multibuffer
8309 .push_excerpts(
8310 buffer.clone(),
8311 [
8312 Point::new(0, 0)..Point::new(1, 4),
8313 Point::new(1, 0)..Point::new(2, 4),
8314 ],
8315 cx,
8316 )
8317 .into_iter()
8318 .next();
8319 multibuffer
8320 });
8321 assert_eq!(
8322 multibuffer.read(cx).read(cx).text(),
8323 "aaaa\nbbbb\nbbbb\ncccc"
8324 );
8325 let (_, editor) = cx.add_window(Default::default(), |cx| {
8326 let mut editor = build_editor(multibuffer.clone(), settings, cx);
8327 editor.select_ranges(
8328 [
8329 Point::new(1, 3)..Point::new(1, 3),
8330 Point::new(2, 1)..Point::new(2, 1),
8331 ],
8332 None,
8333 cx,
8334 );
8335 editor
8336 });
8337
8338 // Refreshing selections is a no-op when excerpts haven't changed.
8339 editor.update(cx, |editor, cx| {
8340 editor.refresh_selections(cx);
8341 assert_eq!(
8342 editor.selected_ranges(cx),
8343 [
8344 Point::new(1, 3)..Point::new(1, 3),
8345 Point::new(2, 1)..Point::new(2, 1),
8346 ]
8347 );
8348 });
8349
8350 multibuffer.update(cx, |multibuffer, cx| {
8351 multibuffer.remove_excerpts([&excerpt1_id.unwrap()], cx);
8352 });
8353 editor.update(cx, |editor, cx| {
8354 // Removing an excerpt causes the first selection to become degenerate.
8355 assert_eq!(
8356 editor.selected_ranges(cx),
8357 [
8358 Point::new(0, 0)..Point::new(0, 0),
8359 Point::new(0, 1)..Point::new(0, 1)
8360 ]
8361 );
8362
8363 // Refreshing selections will relocate the first selection to the original buffer
8364 // location.
8365 editor.refresh_selections(cx);
8366 assert_eq!(
8367 editor.selected_ranges(cx),
8368 [
8369 Point::new(0, 1)..Point::new(0, 1),
8370 Point::new(0, 3)..Point::new(0, 3)
8371 ]
8372 );
8373 });
8374 }
8375
8376 #[gpui::test]
8377 async fn test_extra_newline_insertion(mut cx: gpui::TestAppContext) {
8378 let settings = cx.read(EditorSettings::test);
8379 let language = Arc::new(Language::new(
8380 LanguageConfig {
8381 brackets: vec![
8382 BracketPair {
8383 start: "{".to_string(),
8384 end: "}".to_string(),
8385 close: true,
8386 newline: true,
8387 },
8388 BracketPair {
8389 start: "/* ".to_string(),
8390 end: " */".to_string(),
8391 close: true,
8392 newline: true,
8393 },
8394 ],
8395 ..Default::default()
8396 },
8397 Some(tree_sitter_rust::language()),
8398 ));
8399
8400 let text = concat!(
8401 "{ }\n", // Suppress rustfmt
8402 " x\n", //
8403 " /* */\n", //
8404 "x\n", //
8405 "{{} }\n", //
8406 );
8407
8408 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8409 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8410 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
8411 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
8412 .await;
8413
8414 view.update(&mut cx, |view, cx| {
8415 view.select_display_ranges(
8416 &[
8417 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
8418 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
8419 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
8420 ],
8421 cx,
8422 );
8423 view.newline(&Newline, cx);
8424
8425 assert_eq!(
8426 view.buffer().read(cx).read(cx).text(),
8427 concat!(
8428 "{ \n", // Suppress rustfmt
8429 "\n", //
8430 "}\n", //
8431 " x\n", //
8432 " /* \n", //
8433 " \n", //
8434 " */\n", //
8435 "x\n", //
8436 "{{} \n", //
8437 "}\n", //
8438 )
8439 );
8440 });
8441 }
8442
8443 #[gpui::test]
8444 fn test_highlighted_ranges(cx: &mut gpui::MutableAppContext) {
8445 let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
8446 let settings = EditorSettings::test(&cx);
8447 let (_, editor) = cx.add_window(Default::default(), |cx| {
8448 build_editor(buffer.clone(), settings, cx)
8449 });
8450
8451 editor.update(cx, |editor, cx| {
8452 struct Type1;
8453 struct Type2;
8454
8455 let buffer = buffer.read(cx).snapshot(cx);
8456
8457 let anchor_range = |range: Range<Point>| {
8458 buffer.anchor_after(range.start)..buffer.anchor_after(range.end)
8459 };
8460
8461 editor.highlight_ranges::<Type1>(
8462 vec![
8463 anchor_range(Point::new(2, 1)..Point::new(2, 3)),
8464 anchor_range(Point::new(4, 2)..Point::new(4, 4)),
8465 anchor_range(Point::new(6, 3)..Point::new(6, 5)),
8466 anchor_range(Point::new(8, 4)..Point::new(8, 6)),
8467 ],
8468 Color::red(),
8469 cx,
8470 );
8471 editor.highlight_ranges::<Type2>(
8472 vec![
8473 anchor_range(Point::new(3, 2)..Point::new(3, 5)),
8474 anchor_range(Point::new(5, 3)..Point::new(5, 6)),
8475 anchor_range(Point::new(7, 4)..Point::new(7, 7)),
8476 anchor_range(Point::new(9, 5)..Point::new(9, 8)),
8477 ],
8478 Color::green(),
8479 cx,
8480 );
8481
8482 let snapshot = editor.snapshot(cx);
8483 let mut highlighted_ranges = editor.highlighted_ranges_in_range(
8484 anchor_range(Point::new(3, 4)..Point::new(7, 4)),
8485 &snapshot,
8486 );
8487 // Enforce a consistent ordering based on color without relying on the ordering of the
8488 // highlight's `TypeId` which is non-deterministic.
8489 highlighted_ranges.sort_unstable_by_key(|(_, color)| *color);
8490 assert_eq!(
8491 highlighted_ranges,
8492 &[
8493 (
8494 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 5),
8495 Color::green(),
8496 ),
8497 (
8498 DisplayPoint::new(5, 3)..DisplayPoint::new(5, 6),
8499 Color::green(),
8500 ),
8501 (
8502 DisplayPoint::new(4, 2)..DisplayPoint::new(4, 4),
8503 Color::red(),
8504 ),
8505 (
8506 DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
8507 Color::red(),
8508 ),
8509 ]
8510 );
8511 assert_eq!(
8512 editor.highlighted_ranges_in_range(
8513 anchor_range(Point::new(5, 6)..Point::new(6, 4)),
8514 &snapshot,
8515 ),
8516 &[(
8517 DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
8518 Color::red(),
8519 )]
8520 );
8521 });
8522 }
8523
8524 #[test]
8525 fn test_combine_syntax_and_fuzzy_match_highlights() {
8526 let string = "abcdefghijklmnop";
8527 let default = HighlightStyle::default();
8528 let syntax_ranges = [
8529 (
8530 0..3,
8531 HighlightStyle {
8532 color: Color::red(),
8533 ..default
8534 },
8535 ),
8536 (
8537 4..8,
8538 HighlightStyle {
8539 color: Color::green(),
8540 ..default
8541 },
8542 ),
8543 ];
8544 let match_indices = [4, 6, 7, 8];
8545 assert_eq!(
8546 combine_syntax_and_fuzzy_match_highlights(
8547 &string,
8548 default,
8549 syntax_ranges.into_iter(),
8550 &match_indices,
8551 ),
8552 &[
8553 (
8554 0..3,
8555 HighlightStyle {
8556 color: Color::red(),
8557 ..default
8558 },
8559 ),
8560 (
8561 4..5,
8562 HighlightStyle {
8563 color: Color::green(),
8564 font_properties: *fonts::Properties::default().weight(fonts::Weight::BOLD),
8565 ..default
8566 },
8567 ),
8568 (
8569 5..6,
8570 HighlightStyle {
8571 color: Color::green(),
8572 ..default
8573 },
8574 ),
8575 (
8576 6..8,
8577 HighlightStyle {
8578 color: Color::green(),
8579 font_properties: *fonts::Properties::default().weight(fonts::Weight::BOLD),
8580 ..default
8581 },
8582 ),
8583 (
8584 8..9,
8585 HighlightStyle {
8586 font_properties: *fonts::Properties::default().weight(fonts::Weight::BOLD),
8587 ..default
8588 },
8589 ),
8590 ]
8591 );
8592 }
8593
8594 fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
8595 let point = DisplayPoint::new(row as u32, column as u32);
8596 point..point
8597 }
8598
8599 fn build_editor(
8600 buffer: ModelHandle<MultiBuffer>,
8601 settings: EditorSettings,
8602 cx: &mut ViewContext<Editor>,
8603 ) -> Editor {
8604 Editor::for_buffer(buffer, Arc::new(move |_| settings.clone()), None, cx)
8605 }
8606}
8607
8608trait RangeExt<T> {
8609 fn sorted(&self) -> Range<T>;
8610 fn to_inclusive(&self) -> RangeInclusive<T>;
8611}
8612
8613impl<T: Ord + Clone> RangeExt<T> for Range<T> {
8614 fn sorted(&self) -> Self {
8615 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
8616 }
8617
8618 fn to_inclusive(&self) -> RangeInclusive<T> {
8619 self.start.clone()..=self.end.clone()
8620 }
8621}