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