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