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 clock::ReplicaId;
12use collections::{HashMap, HashSet};
13pub use display_map::DisplayPoint;
14use display_map::*;
15pub use element::*;
16use gpui::{
17 action,
18 elements::*,
19 fonts::TextStyle,
20 geometry::vector::{vec2f, Vector2F},
21 keymap::Binding,
22 text_layout, AppContext, ClipboardItem, Element, ElementBox, Entity, ModelHandle,
23 MutableAppContext, RenderContext, View, ViewContext, WeakModelHandle, WeakViewHandle,
24};
25use items::BufferItemHandle;
26use itertools::Itertools as _;
27use language::{
28 BracketPair, Buffer, Diagnostic, DiagnosticSeverity, Language, Point, Selection, SelectionGoal,
29 TransactionId,
30};
31pub use multi_buffer::{Anchor, ExcerptId, ExcerptProperties, MultiBuffer};
32use multi_buffer::{AnchorRangeExt, MultiBufferChunks, MultiBufferSnapshot, ToOffset, ToPoint};
33use postage::watch;
34use serde::{Deserialize, Serialize};
35use smallvec::SmallVec;
36use smol::Timer;
37use std::{
38 cmp,
39 iter::{self, FromIterator},
40 mem,
41 ops::{Deref, Range, RangeInclusive, Sub},
42 sync::Arc,
43 time::{Duration, Instant},
44};
45use sum_tree::Bias;
46use text::rope::TextDimension;
47use theme::{DiagnosticStyle, EditorStyle};
48use util::post_inc;
49use workspace::{EntryOpener, Workspace};
50
51const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
52const MAX_LINE_LEN: usize = 1024;
53
54action!(Cancel);
55action!(Backspace);
56action!(Delete);
57action!(Input, String);
58action!(Newline);
59action!(Tab);
60action!(Outdent);
61action!(DeleteLine);
62action!(DeleteToPreviousWordBoundary);
63action!(DeleteToNextWordBoundary);
64action!(DeleteToBeginningOfLine);
65action!(DeleteToEndOfLine);
66action!(CutToEndOfLine);
67action!(DuplicateLine);
68action!(MoveLineUp);
69action!(MoveLineDown);
70action!(Cut);
71action!(Copy);
72action!(Paste);
73action!(Undo);
74action!(Redo);
75action!(MoveUp);
76action!(MoveDown);
77action!(MoveLeft);
78action!(MoveRight);
79action!(MoveToPreviousWordBoundary);
80action!(MoveToNextWordBoundary);
81action!(MoveToBeginningOfLine);
82action!(MoveToEndOfLine);
83action!(MoveToBeginning);
84action!(MoveToEnd);
85action!(SelectUp);
86action!(SelectDown);
87action!(SelectLeft);
88action!(SelectRight);
89action!(SelectToPreviousWordBoundary);
90action!(SelectToNextWordBoundary);
91action!(SelectToBeginningOfLine, bool);
92action!(SelectToEndOfLine);
93action!(SelectToBeginning);
94action!(SelectToEnd);
95action!(SelectAll);
96action!(SelectLine);
97action!(SplitSelectionIntoLines);
98action!(AddSelectionAbove);
99action!(AddSelectionBelow);
100action!(SelectNext, bool);
101action!(ToggleComments);
102action!(SelectLargerSyntaxNode);
103action!(SelectSmallerSyntaxNode);
104action!(MoveToEnclosingBracket);
105action!(ShowNextDiagnostic);
106action!(PageUp);
107action!(PageDown);
108action!(Fold);
109action!(Unfold);
110action!(FoldSelectedRanges);
111action!(Scroll, Vector2F);
112action!(Select, SelectPhase);
113
114pub fn init(cx: &mut MutableAppContext, entry_openers: &mut Vec<Box<dyn EntryOpener>>) {
115 entry_openers.push(Box::new(items::BufferOpener));
116 cx.add_bindings(vec![
117 Binding::new("escape", Cancel, Some("Editor")),
118 Binding::new("backspace", Backspace, Some("Editor")),
119 Binding::new("ctrl-h", Backspace, Some("Editor")),
120 Binding::new("delete", Delete, Some("Editor")),
121 Binding::new("ctrl-d", Delete, Some("Editor")),
122 Binding::new("enter", Newline, Some("Editor && mode == full")),
123 Binding::new(
124 "alt-enter",
125 Input("\n".into()),
126 Some("Editor && mode == auto_height"),
127 ),
128 Binding::new("tab", Tab, Some("Editor")),
129 Binding::new("shift-tab", Outdent, Some("Editor")),
130 Binding::new("ctrl-shift-K", DeleteLine, Some("Editor")),
131 Binding::new(
132 "alt-backspace",
133 DeleteToPreviousWordBoundary,
134 Some("Editor"),
135 ),
136 Binding::new("alt-h", DeleteToPreviousWordBoundary, Some("Editor")),
137 Binding::new("alt-delete", DeleteToNextWordBoundary, Some("Editor")),
138 Binding::new("alt-d", DeleteToNextWordBoundary, Some("Editor")),
139 Binding::new("cmd-backspace", DeleteToBeginningOfLine, Some("Editor")),
140 Binding::new("cmd-delete", DeleteToEndOfLine, Some("Editor")),
141 Binding::new("ctrl-k", CutToEndOfLine, Some("Editor")),
142 Binding::new("cmd-shift-D", DuplicateLine, Some("Editor")),
143 Binding::new("ctrl-cmd-up", MoveLineUp, Some("Editor")),
144 Binding::new("ctrl-cmd-down", MoveLineDown, Some("Editor")),
145 Binding::new("cmd-x", Cut, Some("Editor")),
146 Binding::new("cmd-c", Copy, Some("Editor")),
147 Binding::new("cmd-v", Paste, Some("Editor")),
148 Binding::new("cmd-z", Undo, Some("Editor")),
149 Binding::new("cmd-shift-Z", Redo, Some("Editor")),
150 Binding::new("up", MoveUp, Some("Editor")),
151 Binding::new("down", MoveDown, Some("Editor")),
152 Binding::new("left", MoveLeft, Some("Editor")),
153 Binding::new("right", MoveRight, Some("Editor")),
154 Binding::new("ctrl-p", MoveUp, Some("Editor")),
155 Binding::new("ctrl-n", MoveDown, Some("Editor")),
156 Binding::new("ctrl-b", MoveLeft, Some("Editor")),
157 Binding::new("ctrl-f", MoveRight, Some("Editor")),
158 Binding::new("alt-left", MoveToPreviousWordBoundary, Some("Editor")),
159 Binding::new("alt-b", MoveToPreviousWordBoundary, Some("Editor")),
160 Binding::new("alt-right", MoveToNextWordBoundary, Some("Editor")),
161 Binding::new("alt-f", MoveToNextWordBoundary, Some("Editor")),
162 Binding::new("cmd-left", MoveToBeginningOfLine, Some("Editor")),
163 Binding::new("ctrl-a", MoveToBeginningOfLine, Some("Editor")),
164 Binding::new("cmd-right", MoveToEndOfLine, Some("Editor")),
165 Binding::new("ctrl-e", MoveToEndOfLine, Some("Editor")),
166 Binding::new("cmd-up", MoveToBeginning, Some("Editor")),
167 Binding::new("cmd-down", MoveToEnd, Some("Editor")),
168 Binding::new("shift-up", SelectUp, Some("Editor")),
169 Binding::new("ctrl-shift-P", SelectUp, Some("Editor")),
170 Binding::new("shift-down", SelectDown, Some("Editor")),
171 Binding::new("ctrl-shift-N", SelectDown, Some("Editor")),
172 Binding::new("shift-left", SelectLeft, Some("Editor")),
173 Binding::new("ctrl-shift-B", SelectLeft, Some("Editor")),
174 Binding::new("shift-right", SelectRight, Some("Editor")),
175 Binding::new("ctrl-shift-F", SelectRight, Some("Editor")),
176 Binding::new(
177 "alt-shift-left",
178 SelectToPreviousWordBoundary,
179 Some("Editor"),
180 ),
181 Binding::new("alt-shift-B", SelectToPreviousWordBoundary, Some("Editor")),
182 Binding::new("alt-shift-right", SelectToNextWordBoundary, Some("Editor")),
183 Binding::new("alt-shift-F", SelectToNextWordBoundary, Some("Editor")),
184 Binding::new(
185 "cmd-shift-left",
186 SelectToBeginningOfLine(true),
187 Some("Editor"),
188 ),
189 Binding::new(
190 "ctrl-shift-A",
191 SelectToBeginningOfLine(true),
192 Some("Editor"),
193 ),
194 Binding::new("cmd-shift-right", SelectToEndOfLine, Some("Editor")),
195 Binding::new("ctrl-shift-E", SelectToEndOfLine, Some("Editor")),
196 Binding::new("cmd-shift-up", SelectToBeginning, Some("Editor")),
197 Binding::new("cmd-shift-down", SelectToEnd, Some("Editor")),
198 Binding::new("cmd-a", SelectAll, Some("Editor")),
199 Binding::new("cmd-l", SelectLine, Some("Editor")),
200 Binding::new("cmd-shift-L", SplitSelectionIntoLines, Some("Editor")),
201 Binding::new("cmd-alt-up", AddSelectionAbove, Some("Editor")),
202 Binding::new("cmd-ctrl-p", AddSelectionAbove, Some("Editor")),
203 Binding::new("cmd-alt-down", AddSelectionBelow, Some("Editor")),
204 Binding::new("cmd-ctrl-n", AddSelectionBelow, Some("Editor")),
205 Binding::new("cmd-d", SelectNext(false), Some("Editor")),
206 Binding::new("cmd-k cmd-d", SelectNext(true), Some("Editor")),
207 Binding::new("cmd-/", ToggleComments, Some("Editor")),
208 Binding::new("alt-up", SelectLargerSyntaxNode, Some("Editor")),
209 Binding::new("ctrl-w", SelectLargerSyntaxNode, Some("Editor")),
210 Binding::new("alt-down", SelectSmallerSyntaxNode, Some("Editor")),
211 Binding::new("ctrl-shift-W", SelectSmallerSyntaxNode, Some("Editor")),
212 Binding::new("f8", ShowNextDiagnostic, Some("Editor")),
213 Binding::new("ctrl-m", MoveToEnclosingBracket, Some("Editor")),
214 Binding::new("pageup", PageUp, Some("Editor")),
215 Binding::new("pagedown", PageDown, Some("Editor")),
216 Binding::new("alt-cmd-[", Fold, Some("Editor")),
217 Binding::new("alt-cmd-]", Unfold, Some("Editor")),
218 Binding::new("alt-cmd-f", FoldSelectedRanges, Some("Editor")),
219 ]);
220
221 cx.add_action(Editor::open_new);
222 cx.add_action(|this: &mut Editor, action: &Scroll, cx| this.set_scroll_position(action.0, cx));
223 cx.add_action(Editor::select);
224 cx.add_action(Editor::cancel);
225 cx.add_action(Editor::handle_input);
226 cx.add_action(Editor::newline);
227 cx.add_action(Editor::backspace);
228 cx.add_action(Editor::delete);
229 cx.add_action(Editor::tab);
230 cx.add_action(Editor::outdent);
231 cx.add_action(Editor::delete_line);
232 cx.add_action(Editor::delete_to_previous_word_boundary);
233 cx.add_action(Editor::delete_to_next_word_boundary);
234 cx.add_action(Editor::delete_to_beginning_of_line);
235 cx.add_action(Editor::delete_to_end_of_line);
236 cx.add_action(Editor::cut_to_end_of_line);
237 cx.add_action(Editor::duplicate_line);
238 cx.add_action(Editor::move_line_up);
239 cx.add_action(Editor::move_line_down);
240 cx.add_action(Editor::cut);
241 cx.add_action(Editor::copy);
242 cx.add_action(Editor::paste);
243 cx.add_action(Editor::undo);
244 cx.add_action(Editor::redo);
245 cx.add_action(Editor::move_up);
246 cx.add_action(Editor::move_down);
247 cx.add_action(Editor::move_left);
248 cx.add_action(Editor::move_right);
249 cx.add_action(Editor::move_to_previous_word_boundary);
250 cx.add_action(Editor::move_to_next_word_boundary);
251 cx.add_action(Editor::move_to_beginning_of_line);
252 cx.add_action(Editor::move_to_end_of_line);
253 cx.add_action(Editor::move_to_beginning);
254 cx.add_action(Editor::move_to_end);
255 cx.add_action(Editor::select_up);
256 cx.add_action(Editor::select_down);
257 cx.add_action(Editor::select_left);
258 cx.add_action(Editor::select_right);
259 cx.add_action(Editor::select_to_previous_word_boundary);
260 cx.add_action(Editor::select_to_next_word_boundary);
261 cx.add_action(Editor::select_to_beginning_of_line);
262 cx.add_action(Editor::select_to_end_of_line);
263 cx.add_action(Editor::select_to_beginning);
264 cx.add_action(Editor::select_to_end);
265 cx.add_action(Editor::select_all);
266 cx.add_action(Editor::select_line);
267 cx.add_action(Editor::split_selection_into_lines);
268 cx.add_action(Editor::add_selection_above);
269 cx.add_action(Editor::add_selection_below);
270 cx.add_action(Editor::select_next);
271 cx.add_action(Editor::toggle_comments);
272 cx.add_action(Editor::select_larger_syntax_node);
273 cx.add_action(Editor::select_smaller_syntax_node);
274 cx.add_action(Editor::move_to_enclosing_bracket);
275 cx.add_action(Editor::show_next_diagnostic);
276 cx.add_action(Editor::page_up);
277 cx.add_action(Editor::page_down);
278 cx.add_action(Editor::fold);
279 cx.add_action(Editor::unfold);
280 cx.add_action(Editor::fold_selected_ranges);
281}
282
283trait SelectionExt {
284 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
285 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
286 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
287 fn spanned_rows(
288 &self,
289 include_end_if_at_line_start: bool,
290 map: &DisplaySnapshot,
291 ) -> SpannedRows;
292}
293
294struct SpannedRows {
295 buffer_rows: Range<u32>,
296 display_rows: Range<u32>,
297}
298
299#[derive(Clone, Debug)]
300pub enum SelectPhase {
301 Begin {
302 position: DisplayPoint,
303 add: bool,
304 click_count: usize,
305 },
306 BeginColumnar {
307 position: DisplayPoint,
308 overshoot: u32,
309 },
310 Extend {
311 position: DisplayPoint,
312 click_count: usize,
313 },
314 Update {
315 position: DisplayPoint,
316 overshoot: u32,
317 scroll_position: Vector2F,
318 },
319 End,
320}
321
322#[derive(Clone, Debug)]
323enum SelectMode {
324 Character,
325 Word(Range<Anchor>),
326 Line(Range<Anchor>),
327 All,
328}
329
330#[derive(PartialEq, Eq)]
331pub enum Autoscroll {
332 Fit,
333 Center,
334 Newest,
335}
336
337#[derive(Copy, Clone, PartialEq, Eq)]
338pub enum EditorMode {
339 SingleLine,
340 AutoHeight { max_lines: usize },
341 Full,
342}
343
344#[derive(Clone)]
345pub struct EditorSettings {
346 pub tab_size: usize,
347 pub soft_wrap: SoftWrap,
348 pub style: EditorStyle,
349}
350
351#[derive(Clone)]
352pub enum SoftWrap {
353 None,
354 EditorWidth,
355 Column(u32),
356}
357
358pub type BuildSettings = Arc<dyn 'static + Send + Sync + Fn(&AppContext) -> EditorSettings>;
359
360pub struct Editor {
361 handle: WeakViewHandle<Self>,
362 buffer: ModelHandle<MultiBuffer>,
363 display_map: ModelHandle<DisplayMap>,
364 next_selection_id: usize,
365 selections: Arc<[Selection<Anchor>]>,
366 pending_selection: Option<PendingSelection>,
367 columnar_selection_tail: Option<Anchor>,
368 add_selections_state: Option<AddSelectionsState>,
369 select_next_state: Option<SelectNextState>,
370 selection_history:
371 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
372 autoclose_stack: Vec<BracketPairState>,
373 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
374 active_diagnostics: Option<ActiveDiagnosticGroup>,
375 scroll_position: Vector2F,
376 scroll_top_anchor: Anchor,
377 autoscroll_request: Option<Autoscroll>,
378 build_settings: BuildSettings,
379 focused: bool,
380 show_local_cursors: bool,
381 blink_epoch: usize,
382 blinking_paused: bool,
383 mode: EditorMode,
384 placeholder_text: Option<Arc<str>>,
385 highlighted_row: Option<u32>,
386}
387
388pub struct EditorSnapshot {
389 pub mode: EditorMode,
390 pub display_snapshot: DisplaySnapshot,
391 pub placeholder_text: Option<Arc<str>>,
392 is_focused: bool,
393 scroll_position: Vector2F,
394 scroll_top_anchor: Anchor,
395}
396
397struct PendingSelection {
398 selection: Selection<Anchor>,
399 mode: SelectMode,
400}
401
402struct AddSelectionsState {
403 above: bool,
404 stack: Vec<usize>,
405}
406
407struct SelectNextState {
408 query: AhoCorasick,
409 wordwise: bool,
410 done: bool,
411}
412
413#[derive(Debug)]
414struct BracketPairState {
415 ranges: Vec<Range<Anchor>>,
416 pair: BracketPair,
417}
418
419#[derive(Debug)]
420struct ActiveDiagnosticGroup {
421 primary_range: Range<Anchor>,
422 primary_message: String,
423 blocks: HashMap<BlockId, Diagnostic>,
424 is_valid: bool,
425}
426
427#[derive(Serialize, Deserialize)]
428struct ClipboardSelection {
429 len: usize,
430 is_entire_line: bool,
431}
432
433impl Editor {
434 pub fn single_line(build_settings: BuildSettings, cx: &mut ViewContext<Self>) -> Self {
435 let buffer = cx.add_model(|cx| Buffer::new(0, String::new(), cx));
436 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
437 let mut view = Self::for_buffer(buffer, build_settings, cx);
438 view.mode = EditorMode::SingleLine;
439 view
440 }
441
442 pub fn auto_height(
443 max_lines: usize,
444 build_settings: BuildSettings,
445 cx: &mut ViewContext<Self>,
446 ) -> Self {
447 let buffer = cx.add_model(|cx| Buffer::new(0, String::new(), cx));
448 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
449 let mut view = Self::for_buffer(buffer, build_settings, cx);
450 view.mode = EditorMode::AutoHeight { max_lines };
451 view
452 }
453
454 pub fn for_buffer(
455 buffer: ModelHandle<MultiBuffer>,
456 build_settings: BuildSettings,
457 cx: &mut ViewContext<Self>,
458 ) -> Self {
459 Self::new(buffer, build_settings, cx)
460 }
461
462 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
463 let mut clone = Self::new(self.buffer.clone(), self.build_settings.clone(), cx);
464 clone.scroll_position = self.scroll_position;
465 clone.scroll_top_anchor = self.scroll_top_anchor.clone();
466 clone
467 }
468
469 pub fn new(
470 buffer: ModelHandle<MultiBuffer>,
471 build_settings: BuildSettings,
472 cx: &mut ViewContext<Self>,
473 ) -> Self {
474 let settings = build_settings(cx);
475 let display_map = cx.add_model(|cx| {
476 DisplayMap::new(
477 buffer.clone(),
478 settings.tab_size,
479 settings.style.text.font_id,
480 settings.style.text.font_size,
481 None,
482 cx,
483 )
484 });
485 cx.observe(&buffer, Self::on_buffer_changed).detach();
486 cx.subscribe(&buffer, Self::on_buffer_event).detach();
487 cx.observe(&display_map, Self::on_display_map_changed)
488 .detach();
489
490 let mut this = Self {
491 handle: cx.weak_handle(),
492 buffer,
493 display_map,
494 selections: Arc::from([]),
495 pending_selection: None,
496 columnar_selection_tail: None,
497 next_selection_id: 0,
498 add_selections_state: None,
499 select_next_state: None,
500 selection_history: Default::default(),
501 autoclose_stack: Default::default(),
502 select_larger_syntax_node_stack: Vec::new(),
503 active_diagnostics: None,
504 build_settings,
505 scroll_position: Vector2F::zero(),
506 scroll_top_anchor: Anchor::min(),
507 autoscroll_request: None,
508 focused: false,
509 show_local_cursors: false,
510 blink_epoch: 0,
511 blinking_paused: false,
512 mode: EditorMode::Full,
513 placeholder_text: None,
514 highlighted_row: None,
515 };
516 let selection = Selection {
517 id: post_inc(&mut this.next_selection_id),
518 start: 0,
519 end: 0,
520 reversed: false,
521 goal: SelectionGoal::None,
522 };
523 this.update_selections(vec![selection], None, cx);
524 this
525 }
526
527 pub fn open_new(
528 workspace: &mut Workspace,
529 _: &workspace::OpenNew,
530 cx: &mut ViewContext<Workspace>,
531 ) {
532 let buffer = cx.add_model(|cx| {
533 Buffer::new(0, "", cx).with_language(Some(language::PLAIN_TEXT.clone()), None, cx)
534 });
535 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
536 workspace.add_item(BufferItemHandle(buffer), cx);
537 }
538
539 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
540 self.buffer.read(cx).replica_id()
541 }
542
543 pub fn buffer(&self) -> &ModelHandle<MultiBuffer> {
544 &self.buffer
545 }
546
547 pub fn snapshot(&mut self, cx: &mut MutableAppContext) -> EditorSnapshot {
548 EditorSnapshot {
549 mode: self.mode,
550 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
551 scroll_position: self.scroll_position,
552 scroll_top_anchor: self.scroll_top_anchor.clone(),
553 placeholder_text: self.placeholder_text.clone(),
554 is_focused: self
555 .handle
556 .upgrade(cx)
557 .map_or(false, |handle| handle.is_focused(cx)),
558 }
559 }
560
561 pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc<Language>> {
562 self.buffer.read(cx).language(cx)
563 }
564
565 pub fn set_placeholder_text(
566 &mut self,
567 placeholder_text: impl Into<Arc<str>>,
568 cx: &mut ViewContext<Self>,
569 ) {
570 self.placeholder_text = Some(placeholder_text.into());
571 cx.notify();
572 }
573
574 pub fn set_scroll_position(&mut self, scroll_position: Vector2F, cx: &mut ViewContext<Self>) {
575 let map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
576 let scroll_top_buffer_offset =
577 DisplayPoint::new(scroll_position.y() as u32, 0).to_offset(&map, Bias::Right);
578 self.scroll_top_anchor = map
579 .buffer_snapshot
580 .anchor_at(scroll_top_buffer_offset, Bias::Right);
581 self.scroll_position = vec2f(
582 scroll_position.x(),
583 scroll_position.y() - self.scroll_top_anchor.to_display_point(&map).row() as f32,
584 );
585
586 cx.notify();
587 }
588
589 pub fn scroll_position(&self, cx: &mut ViewContext<Self>) -> Vector2F {
590 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
591 compute_scroll_position(&display_map, self.scroll_position, &self.scroll_top_anchor)
592 }
593
594 pub fn clamp_scroll_left(&mut self, max: f32) -> bool {
595 if max < self.scroll_position.x() {
596 self.scroll_position.set_x(max);
597 true
598 } else {
599 false
600 }
601 }
602
603 pub fn autoscroll_vertically(
604 &mut self,
605 viewport_height: f32,
606 line_height: f32,
607 cx: &mut ViewContext<Self>,
608 ) -> bool {
609 let visible_lines = viewport_height / line_height;
610 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
611 let mut scroll_position =
612 compute_scroll_position(&display_map, self.scroll_position, &self.scroll_top_anchor);
613 let max_scroll_top = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
614 (display_map.max_point().row() as f32 - visible_lines + 1.).max(0.)
615 } else {
616 display_map.max_point().row().saturating_sub(1) as f32
617 };
618 if scroll_position.y() > max_scroll_top {
619 scroll_position.set_y(max_scroll_top);
620 self.set_scroll_position(scroll_position, cx);
621 }
622
623 let autoscroll = if let Some(autoscroll) = self.autoscroll_request.take() {
624 autoscroll
625 } else {
626 return false;
627 };
628
629 let first_cursor_top;
630 let last_cursor_bottom;
631 if autoscroll == Autoscroll::Newest {
632 let newest_selection = self.newest_selection::<Point>(&display_map.buffer_snapshot);
633 first_cursor_top = newest_selection.head().to_display_point(&display_map).row() as f32;
634 last_cursor_bottom = first_cursor_top + 1.;
635 } else {
636 let selections = self.local_selections::<Point>(cx);
637 first_cursor_top = selections
638 .first()
639 .unwrap()
640 .head()
641 .to_display_point(&display_map)
642 .row() as f32;
643 last_cursor_bottom = selections
644 .last()
645 .unwrap()
646 .head()
647 .to_display_point(&display_map)
648 .row() as f32
649 + 1.0;
650 }
651
652 let margin = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
653 0.
654 } else {
655 ((visible_lines - (last_cursor_bottom - first_cursor_top)) / 2.0).floor()
656 };
657 if margin < 0.0 {
658 return false;
659 }
660
661 match autoscroll {
662 Autoscroll::Fit | Autoscroll::Newest => {
663 let margin = margin.min(3.0);
664 let target_top = (first_cursor_top - margin).max(0.0);
665 let target_bottom = last_cursor_bottom + margin;
666 let start_row = scroll_position.y();
667 let end_row = start_row + visible_lines;
668
669 if target_top < start_row {
670 scroll_position.set_y(target_top);
671 self.set_scroll_position(scroll_position, cx);
672 } else if target_bottom >= end_row {
673 scroll_position.set_y(target_bottom - visible_lines);
674 self.set_scroll_position(scroll_position, cx);
675 }
676 }
677 Autoscroll::Center => {
678 scroll_position.set_y((first_cursor_top - margin).max(0.0));
679 self.set_scroll_position(scroll_position, cx);
680 }
681 }
682
683 true
684 }
685
686 pub fn autoscroll_horizontally(
687 &mut self,
688 start_row: u32,
689 viewport_width: f32,
690 scroll_width: f32,
691 max_glyph_width: f32,
692 layouts: &[text_layout::Line],
693 cx: &mut ViewContext<Self>,
694 ) -> bool {
695 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
696 let selections = self.local_selections::<Point>(cx);
697 let mut target_left = std::f32::INFINITY;
698 let mut target_right = 0.0_f32;
699 for selection in selections {
700 let head = selection.head().to_display_point(&display_map);
701 if head.row() >= start_row && head.row() < start_row + layouts.len() as u32 {
702 let start_column = head.column().saturating_sub(3);
703 let end_column = cmp::min(display_map.line_len(head.row()), head.column() + 3);
704 target_left = target_left.min(
705 layouts[(head.row() - start_row) as usize].x_for_index(start_column as usize),
706 );
707 target_right = target_right.max(
708 layouts[(head.row() - start_row) as usize].x_for_index(end_column as usize)
709 + max_glyph_width,
710 );
711 }
712 }
713 target_right = target_right.min(scroll_width);
714
715 if target_right - target_left > viewport_width {
716 return false;
717 }
718
719 let scroll_left = self.scroll_position.x() * max_glyph_width;
720 let scroll_right = scroll_left + viewport_width;
721
722 if target_left < scroll_left {
723 self.scroll_position.set_x(target_left / max_glyph_width);
724 true
725 } else if target_right > scroll_right {
726 self.scroll_position
727 .set_x((target_right - viewport_width) / max_glyph_width);
728 true
729 } else {
730 false
731 }
732 }
733
734 fn select(&mut self, Select(phase): &Select, cx: &mut ViewContext<Self>) {
735 match phase {
736 SelectPhase::Begin {
737 position,
738 add,
739 click_count,
740 } => self.begin_selection(*position, *add, *click_count, cx),
741 SelectPhase::BeginColumnar {
742 position,
743 overshoot,
744 } => self.begin_columnar_selection(*position, *overshoot, cx),
745 SelectPhase::Extend {
746 position,
747 click_count,
748 } => self.extend_selection(*position, *click_count, cx),
749 SelectPhase::Update {
750 position,
751 overshoot,
752 scroll_position,
753 } => self.update_selection(*position, *overshoot, *scroll_position, cx),
754 SelectPhase::End => self.end_selection(cx),
755 }
756 }
757
758 fn extend_selection(
759 &mut self,
760 position: DisplayPoint,
761 click_count: usize,
762 cx: &mut ViewContext<Self>,
763 ) {
764 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
765 let tail = self
766 .newest_selection::<usize>(&display_map.buffer_snapshot)
767 .tail();
768 self.begin_selection(position, false, click_count, cx);
769
770 let position = position.to_offset(&display_map, Bias::Left);
771 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
772 let pending = self.pending_selection.as_mut().unwrap();
773
774 if position >= tail {
775 pending.selection.start = tail_anchor.clone();
776 } else {
777 pending.selection.end = tail_anchor.clone();
778 pending.selection.reversed = true;
779 }
780
781 match &mut pending.mode {
782 SelectMode::Word(range) | SelectMode::Line(range) => {
783 *range = tail_anchor.clone()..tail_anchor
784 }
785 _ => {}
786 }
787 }
788
789 fn begin_selection(
790 &mut self,
791 position: DisplayPoint,
792 add: bool,
793 click_count: usize,
794 cx: &mut ViewContext<Self>,
795 ) {
796 if !self.focused {
797 cx.focus_self();
798 cx.emit(Event::Activate);
799 }
800
801 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
802 let buffer = &display_map.buffer_snapshot;
803 let start;
804 let end;
805 let mode;
806 match click_count {
807 1 => {
808 start = buffer.anchor_before(position.to_point(&display_map));
809 end = start.clone();
810 mode = SelectMode::Character;
811 }
812 2 => {
813 let range = movement::surrounding_word(&display_map, position);
814 start = buffer.anchor_before(range.start.to_point(&display_map));
815 end = buffer.anchor_before(range.end.to_point(&display_map));
816 mode = SelectMode::Word(start.clone()..end.clone());
817 }
818 3 => {
819 let position = display_map.clip_point(position, Bias::Left);
820 let line_start = movement::line_beginning(&display_map, position, false);
821 let mut next_line_start = line_start.clone();
822 *next_line_start.row_mut() += 1;
823 *next_line_start.column_mut() = 0;
824 next_line_start = display_map.clip_point(next_line_start, Bias::Right);
825
826 start = buffer.anchor_before(line_start.to_point(&display_map));
827 end = buffer.anchor_before(next_line_start.to_point(&display_map));
828 mode = SelectMode::Line(start.clone()..end.clone());
829 }
830 _ => {
831 start = buffer.anchor_before(0);
832 end = buffer.anchor_before(buffer.len());
833 mode = SelectMode::All;
834 }
835 }
836
837 let selection = Selection {
838 id: post_inc(&mut self.next_selection_id),
839 start,
840 end,
841 reversed: false,
842 goal: SelectionGoal::None,
843 };
844
845 if !add {
846 self.update_selections::<usize>(Vec::new(), None, cx);
847 } else if click_count > 1 {
848 // Remove the newest selection since it was only added as part of this multi-click.
849 let newest_selection = self.newest_selection::<usize>(buffer);
850 let mut selections = self.local_selections(cx);
851 selections.retain(|selection| selection.id != newest_selection.id);
852 self.update_selections::<usize>(selections, None, cx)
853 }
854
855 self.pending_selection = Some(PendingSelection { selection, mode });
856
857 cx.notify();
858 }
859
860 fn begin_columnar_selection(
861 &mut self,
862 position: DisplayPoint,
863 overshoot: u32,
864 cx: &mut ViewContext<Self>,
865 ) {
866 if !self.focused {
867 cx.focus_self();
868 cx.emit(Event::Activate);
869 }
870
871 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
872 let tail = self
873 .newest_selection::<Point>(&display_map.buffer_snapshot)
874 .tail();
875 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
876
877 self.select_columns(
878 tail.to_display_point(&display_map),
879 position,
880 overshoot,
881 &display_map,
882 cx,
883 );
884 }
885
886 fn update_selection(
887 &mut self,
888 position: DisplayPoint,
889 overshoot: u32,
890 scroll_position: Vector2F,
891 cx: &mut ViewContext<Self>,
892 ) {
893 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
894
895 if let Some(tail) = self.columnar_selection_tail.as_ref() {
896 let tail = tail.to_display_point(&display_map);
897 self.select_columns(tail, position, overshoot, &display_map, cx);
898 } else if let Some(PendingSelection { selection, mode }) = self.pending_selection.as_mut() {
899 let buffer = self.buffer.read(cx).snapshot(cx);
900 let head;
901 let tail;
902 match mode {
903 SelectMode::Character => {
904 head = position.to_point(&display_map);
905 tail = selection.tail().to_point(&buffer);
906 }
907 SelectMode::Word(original_range) => {
908 let original_display_range = original_range.start.to_display_point(&display_map)
909 ..original_range.end.to_display_point(&display_map);
910 let original_buffer_range = original_display_range.start.to_point(&display_map)
911 ..original_display_range.end.to_point(&display_map);
912 if movement::is_inside_word(&display_map, position)
913 || original_display_range.contains(&position)
914 {
915 let word_range = movement::surrounding_word(&display_map, position);
916 if word_range.start < original_display_range.start {
917 head = word_range.start.to_point(&display_map);
918 } else {
919 head = word_range.end.to_point(&display_map);
920 }
921 } else {
922 head = position.to_point(&display_map);
923 }
924
925 if head <= original_buffer_range.start {
926 tail = original_buffer_range.end;
927 } else {
928 tail = original_buffer_range.start;
929 }
930 }
931 SelectMode::Line(original_range) => {
932 let original_display_range = original_range.start.to_display_point(&display_map)
933 ..original_range.end.to_display_point(&display_map);
934 let original_buffer_range = original_display_range.start.to_point(&display_map)
935 ..original_display_range.end.to_point(&display_map);
936 let line_start = movement::line_beginning(&display_map, position, false);
937 let mut next_line_start = line_start.clone();
938 *next_line_start.row_mut() += 1;
939 *next_line_start.column_mut() = 0;
940 next_line_start = display_map.clip_point(next_line_start, Bias::Right);
941
942 if line_start < original_display_range.start {
943 head = line_start.to_point(&display_map);
944 } else {
945 head = next_line_start.to_point(&display_map);
946 }
947
948 if head <= original_buffer_range.start {
949 tail = original_buffer_range.end;
950 } else {
951 tail = original_buffer_range.start;
952 }
953 }
954 SelectMode::All => {
955 return;
956 }
957 };
958
959 if head < tail {
960 selection.start = buffer.anchor_before(head);
961 selection.end = buffer.anchor_before(tail);
962 selection.reversed = true;
963 } else {
964 selection.start = buffer.anchor_before(tail);
965 selection.end = buffer.anchor_before(head);
966 selection.reversed = false;
967 }
968 } else {
969 log::error!("update_selection dispatched with no pending selection");
970 return;
971 }
972
973 self.set_scroll_position(scroll_position, cx);
974 cx.notify();
975 }
976
977 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
978 self.columnar_selection_tail.take();
979 if self.pending_selection.is_some() {
980 let selections = self.local_selections::<usize>(cx);
981 self.update_selections(selections, None, cx);
982 }
983 }
984
985 fn select_columns(
986 &mut self,
987 tail: DisplayPoint,
988 head: DisplayPoint,
989 overshoot: u32,
990 display_map: &DisplaySnapshot,
991 cx: &mut ViewContext<Self>,
992 ) {
993 let start_row = cmp::min(tail.row(), head.row());
994 let end_row = cmp::max(tail.row(), head.row());
995 let start_column = cmp::min(tail.column(), head.column() + overshoot);
996 let end_column = cmp::max(tail.column(), head.column() + overshoot);
997 let reversed = start_column < tail.column();
998
999 let selections = (start_row..=end_row)
1000 .filter_map(|row| {
1001 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
1002 let start = display_map
1003 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
1004 .to_point(&display_map);
1005 let end = display_map
1006 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
1007 .to_point(&display_map);
1008 Some(Selection {
1009 id: post_inc(&mut self.next_selection_id),
1010 start,
1011 end,
1012 reversed,
1013 goal: SelectionGoal::None,
1014 })
1015 } else {
1016 None
1017 }
1018 })
1019 .collect::<Vec<_>>();
1020
1021 self.update_selections(selections, None, cx);
1022 cx.notify();
1023 }
1024
1025 pub fn is_selecting(&self) -> bool {
1026 self.pending_selection.is_some() || self.columnar_selection_tail.is_some()
1027 }
1028
1029 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
1030 if self.active_diagnostics.is_some() {
1031 self.dismiss_diagnostics(cx);
1032 } else if let Some(PendingSelection { selection, .. }) = self.pending_selection.take() {
1033 let buffer = self.buffer.read(cx).snapshot(cx);
1034 let selection = Selection {
1035 id: selection.id,
1036 start: selection.start.to_point(&buffer),
1037 end: selection.end.to_point(&buffer),
1038 reversed: selection.reversed,
1039 goal: selection.goal,
1040 };
1041 if self.local_selections::<Point>(cx).is_empty() {
1042 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
1043 }
1044 } else {
1045 let buffer = self.buffer.read(cx).snapshot(cx);
1046 let mut oldest_selection = self.oldest_selection::<usize>(&buffer);
1047 if self.selection_count() == 1 {
1048 if oldest_selection.is_empty() {
1049 cx.propagate_action();
1050 return;
1051 }
1052
1053 oldest_selection.start = oldest_selection.head().clone();
1054 oldest_selection.end = oldest_selection.head().clone();
1055 }
1056 self.update_selections(vec![oldest_selection], Some(Autoscroll::Fit), cx);
1057 }
1058 }
1059
1060 pub fn select_ranges<I, T>(
1061 &mut self,
1062 ranges: I,
1063 autoscroll: Option<Autoscroll>,
1064 cx: &mut ViewContext<Self>,
1065 ) where
1066 I: IntoIterator<Item = Range<T>>,
1067 T: ToOffset,
1068 {
1069 let buffer = self.buffer.read(cx).snapshot(cx);
1070 let selections = ranges
1071 .into_iter()
1072 .map(|range| {
1073 let mut start = range.start.to_offset(&buffer);
1074 let mut end = range.end.to_offset(&buffer);
1075 let reversed = if start > end {
1076 mem::swap(&mut start, &mut end);
1077 true
1078 } else {
1079 false
1080 };
1081 Selection {
1082 id: post_inc(&mut self.next_selection_id),
1083 start,
1084 end,
1085 reversed,
1086 goal: SelectionGoal::None,
1087 }
1088 })
1089 .collect();
1090 self.update_selections(selections, autoscroll, cx);
1091 }
1092
1093 #[cfg(test)]
1094 fn select_display_ranges<'a, T>(
1095 &mut self,
1096 ranges: T,
1097 cx: &mut ViewContext<Self>,
1098 ) -> anyhow::Result<()>
1099 where
1100 T: IntoIterator<Item = &'a Range<DisplayPoint>>,
1101 {
1102 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1103 let selections = ranges
1104 .into_iter()
1105 .map(|range| {
1106 let mut start = range.start;
1107 let mut end = range.end;
1108 let reversed = if start > end {
1109 mem::swap(&mut start, &mut end);
1110 true
1111 } else {
1112 false
1113 };
1114 Selection {
1115 id: post_inc(&mut self.next_selection_id),
1116 start: start.to_point(&display_map),
1117 end: end.to_point(&display_map),
1118 reversed,
1119 goal: SelectionGoal::None,
1120 }
1121 })
1122 .collect();
1123 self.update_selections(selections, None, cx);
1124 Ok(())
1125 }
1126
1127 pub fn handle_input(&mut self, action: &Input, cx: &mut ViewContext<Self>) {
1128 let text = action.0.as_ref();
1129 if !self.skip_autoclose_end(text, cx) {
1130 self.start_transaction(cx);
1131 self.insert(text, cx);
1132 self.autoclose_pairs(cx);
1133 self.end_transaction(cx);
1134 }
1135 }
1136
1137 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
1138 self.start_transaction(cx);
1139 let mut old_selections = SmallVec::<[_; 32]>::new();
1140 {
1141 let selections = self.local_selections::<Point>(cx);
1142 let buffer = self.buffer.read(cx).snapshot(cx);
1143 for selection in selections.iter() {
1144 let start_point = selection.start;
1145 let indent = buffer
1146 .indent_column_for_line(start_point.row)
1147 .min(start_point.column);
1148 let start = selection.start.to_offset(&buffer);
1149 let end = selection.end.to_offset(&buffer);
1150
1151 let mut insert_extra_newline = false;
1152 if let Some(language) = buffer.language() {
1153 let leading_whitespace_len = buffer
1154 .reversed_chars_at(start)
1155 .take_while(|c| c.is_whitespace() && *c != '\n')
1156 .map(|c| c.len_utf8())
1157 .sum::<usize>();
1158
1159 let trailing_whitespace_len = buffer
1160 .chars_at(end)
1161 .take_while(|c| c.is_whitespace() && *c != '\n')
1162 .map(|c| c.len_utf8())
1163 .sum::<usize>();
1164
1165 insert_extra_newline = language.brackets().iter().any(|pair| {
1166 let pair_start = pair.start.trim_end();
1167 let pair_end = pair.end.trim_start();
1168
1169 pair.newline
1170 && buffer.contains_str_at(end + trailing_whitespace_len, pair_end)
1171 && buffer.contains_str_at(
1172 (start - leading_whitespace_len).saturating_sub(pair_start.len()),
1173 pair_start,
1174 )
1175 });
1176 }
1177
1178 old_selections.push((selection.id, start..end, indent, insert_extra_newline));
1179 }
1180 }
1181
1182 let mut new_selections = Vec::with_capacity(old_selections.len());
1183 self.buffer.update(cx, |buffer, cx| {
1184 let mut delta = 0_isize;
1185 let mut pending_edit: Option<PendingEdit> = None;
1186 for (_, range, indent, insert_extra_newline) in &old_selections {
1187 if pending_edit.as_ref().map_or(false, |pending| {
1188 pending.indent != *indent
1189 || pending.insert_extra_newline != *insert_extra_newline
1190 }) {
1191 let pending = pending_edit.take().unwrap();
1192 let mut new_text = String::with_capacity(1 + pending.indent as usize);
1193 new_text.push('\n');
1194 new_text.extend(iter::repeat(' ').take(pending.indent as usize));
1195 if pending.insert_extra_newline {
1196 new_text = new_text.repeat(2);
1197 }
1198 buffer.edit_with_autoindent(pending.ranges, new_text, cx);
1199 delta += pending.delta;
1200 }
1201
1202 let start = (range.start as isize + delta) as usize;
1203 let end = (range.end as isize + delta) as usize;
1204 let mut text_len = *indent as usize + 1;
1205 if *insert_extra_newline {
1206 text_len *= 2;
1207 }
1208
1209 let pending = pending_edit.get_or_insert_with(Default::default);
1210 pending.delta += text_len as isize - (end - start) as isize;
1211 pending.indent = *indent;
1212 pending.insert_extra_newline = *insert_extra_newline;
1213 pending.ranges.push(start..end);
1214 }
1215
1216 let pending = pending_edit.unwrap();
1217 let mut new_text = String::with_capacity(1 + pending.indent as usize);
1218 new_text.push('\n');
1219 new_text.extend(iter::repeat(' ').take(pending.indent as usize));
1220 if pending.insert_extra_newline {
1221 new_text = new_text.repeat(2);
1222 }
1223 buffer.edit_with_autoindent(pending.ranges, new_text, cx);
1224
1225 let mut delta = 0_isize;
1226 new_selections.extend(old_selections.into_iter().map(
1227 |(id, range, indent, insert_extra_newline)| {
1228 let start = (range.start as isize + delta) as usize;
1229 let end = (range.end as isize + delta) as usize;
1230 let text_before_cursor_len = indent as usize + 1;
1231 let cursor = start + text_before_cursor_len;
1232 let text_len = if insert_extra_newline {
1233 text_before_cursor_len * 2
1234 } else {
1235 text_before_cursor_len
1236 };
1237 delta += text_len as isize - (end - start) as isize;
1238 Selection {
1239 id,
1240 start: cursor,
1241 end: cursor,
1242 reversed: false,
1243 goal: SelectionGoal::None,
1244 }
1245 },
1246 ))
1247 });
1248
1249 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
1250 self.end_transaction(cx);
1251
1252 #[derive(Default)]
1253 struct PendingEdit {
1254 indent: u32,
1255 insert_extra_newline: bool,
1256 delta: isize,
1257 ranges: SmallVec<[Range<usize>; 32]>,
1258 }
1259 }
1260
1261 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
1262 self.start_transaction(cx);
1263 let old_selections = self.local_selections::<usize>(cx);
1264 self.buffer.update(cx, |buffer, cx| {
1265 let edit_ranges = old_selections.iter().map(|s| s.start..s.end);
1266 buffer.edit_with_autoindent(edit_ranges, text, cx);
1267 });
1268
1269 let selections = self.local_selections::<usize>(cx);
1270 self.update_selections(selections, Some(Autoscroll::Fit), cx);
1271 self.end_transaction(cx);
1272 }
1273
1274 fn autoclose_pairs(&mut self, cx: &mut ViewContext<Self>) {
1275 let selections = self.local_selections::<usize>(cx);
1276 let mut bracket_pair_state = None;
1277 let mut new_selections = None;
1278 self.buffer.update(cx, |buffer, cx| {
1279 let mut snapshot = buffer.snapshot(cx);
1280 let left_biased_selections = selections
1281 .iter()
1282 .map(|selection| Selection {
1283 id: selection.id,
1284 start: snapshot.anchor_before(selection.start),
1285 end: snapshot.anchor_before(selection.end),
1286 reversed: selection.reversed,
1287 goal: selection.goal,
1288 })
1289 .collect::<Vec<_>>();
1290
1291 let autoclose_pair = snapshot.language().and_then(|language| {
1292 let first_selection_start = selections.first().unwrap().start;
1293 let pair = language.brackets().iter().find(|pair| {
1294 snapshot.contains_str_at(
1295 first_selection_start.saturating_sub(pair.start.len()),
1296 &pair.start,
1297 )
1298 });
1299 pair.and_then(|pair| {
1300 let should_autoclose = selections[1..].iter().all(|selection| {
1301 snapshot.contains_str_at(
1302 selection.start.saturating_sub(pair.start.len()),
1303 &pair.start,
1304 )
1305 });
1306
1307 if should_autoclose {
1308 Some(pair.clone())
1309 } else {
1310 None
1311 }
1312 })
1313 });
1314
1315 if let Some(pair) = autoclose_pair {
1316 let selection_ranges = selections
1317 .iter()
1318 .map(|selection| {
1319 let start = selection.start.to_offset(&snapshot);
1320 start..start
1321 })
1322 .collect::<SmallVec<[_; 32]>>();
1323
1324 buffer.edit(selection_ranges, &pair.end, cx);
1325 snapshot = buffer.snapshot(cx);
1326
1327 new_selections = Some(
1328 self.resolve_selections::<usize, _>(left_biased_selections.iter(), &snapshot)
1329 .collect::<Vec<_>>(),
1330 );
1331
1332 if pair.end.len() == 1 {
1333 let mut delta = 0;
1334 bracket_pair_state = Some(BracketPairState {
1335 ranges: selections
1336 .iter()
1337 .map(move |selection| {
1338 let offset = selection.start + delta;
1339 delta += 1;
1340 snapshot.anchor_before(offset)..snapshot.anchor_after(offset)
1341 })
1342 .collect(),
1343 pair,
1344 });
1345 }
1346 }
1347 });
1348
1349 if let Some(new_selections) = new_selections {
1350 self.update_selections(new_selections, None, cx);
1351 }
1352 if let Some(bracket_pair_state) = bracket_pair_state {
1353 self.autoclose_stack.push(bracket_pair_state);
1354 }
1355 }
1356
1357 fn skip_autoclose_end(&mut self, text: &str, cx: &mut ViewContext<Self>) -> bool {
1358 let old_selections = self.local_selections::<usize>(cx);
1359 let autoclose_pair = if let Some(autoclose_pair) = self.autoclose_stack.last() {
1360 autoclose_pair
1361 } else {
1362 return false;
1363 };
1364 if text != autoclose_pair.pair.end {
1365 return false;
1366 }
1367
1368 debug_assert_eq!(old_selections.len(), autoclose_pair.ranges.len());
1369
1370 let buffer = self.buffer.read(cx).snapshot(cx);
1371 if old_selections
1372 .iter()
1373 .zip(autoclose_pair.ranges.iter().map(|r| r.to_offset(&buffer)))
1374 .all(|(selection, autoclose_range)| {
1375 let autoclose_range_end = autoclose_range.end.to_offset(&buffer);
1376 selection.is_empty() && selection.start == autoclose_range_end
1377 })
1378 {
1379 let new_selections = old_selections
1380 .into_iter()
1381 .map(|selection| {
1382 let cursor = selection.start + 1;
1383 Selection {
1384 id: selection.id,
1385 start: cursor,
1386 end: cursor,
1387 reversed: false,
1388 goal: SelectionGoal::None,
1389 }
1390 })
1391 .collect();
1392 self.autoclose_stack.pop();
1393 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
1394 true
1395 } else {
1396 false
1397 }
1398 }
1399
1400 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
1401 self.start_transaction(cx);
1402 self.select_all(&SelectAll, cx);
1403 self.insert("", cx);
1404 self.end_transaction(cx);
1405 }
1406
1407 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
1408 self.start_transaction(cx);
1409 let mut selections = self.local_selections::<Point>(cx);
1410 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1411 for selection in &mut selections {
1412 if selection.is_empty() {
1413 let head = selection.head().to_display_point(&display_map);
1414 let cursor = movement::left(&display_map, head)
1415 .unwrap()
1416 .to_point(&display_map);
1417 selection.set_head(cursor);
1418 selection.goal = SelectionGoal::None;
1419 }
1420 }
1421 self.update_selections(selections, Some(Autoscroll::Fit), cx);
1422 self.insert("", cx);
1423 self.end_transaction(cx);
1424 }
1425
1426 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
1427 self.start_transaction(cx);
1428 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1429 let mut selections = self.local_selections::<Point>(cx);
1430 for selection in &mut selections {
1431 if selection.is_empty() {
1432 let head = selection.head().to_display_point(&display_map);
1433 let cursor = movement::right(&display_map, head)
1434 .unwrap()
1435 .to_point(&display_map);
1436 selection.set_head(cursor);
1437 selection.goal = SelectionGoal::None;
1438 }
1439 }
1440 self.update_selections(selections, Some(Autoscroll::Fit), cx);
1441 self.insert(&"", cx);
1442 self.end_transaction(cx);
1443 }
1444
1445 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
1446 self.start_transaction(cx);
1447 let tab_size = (self.build_settings)(cx).tab_size;
1448 let mut selections = self.local_selections::<Point>(cx);
1449 let mut last_indent = None;
1450 self.buffer.update(cx, |buffer, cx| {
1451 for selection in &mut selections {
1452 if selection.is_empty() {
1453 let char_column = buffer
1454 .read(cx)
1455 .text_for_range(Point::new(selection.start.row, 0)..selection.start)
1456 .flat_map(str::chars)
1457 .count();
1458 let chars_to_next_tab_stop = tab_size - (char_column % tab_size);
1459 buffer.edit(
1460 [selection.start..selection.start],
1461 " ".repeat(chars_to_next_tab_stop),
1462 cx,
1463 );
1464 selection.start.column += chars_to_next_tab_stop as u32;
1465 selection.end = selection.start;
1466 } else {
1467 let mut start_row = selection.start.row;
1468 let mut end_row = selection.end.row + 1;
1469
1470 // If a selection ends at the beginning of a line, don't indent
1471 // that last line.
1472 if selection.end.column == 0 {
1473 end_row -= 1;
1474 }
1475
1476 // Avoid re-indenting a row that has already been indented by a
1477 // previous selection, but still update this selection's column
1478 // to reflect that indentation.
1479 if let Some((last_indent_row, last_indent_len)) = last_indent {
1480 if last_indent_row == selection.start.row {
1481 selection.start.column += last_indent_len;
1482 start_row += 1;
1483 }
1484 if last_indent_row == selection.end.row {
1485 selection.end.column += last_indent_len;
1486 }
1487 }
1488
1489 for row in start_row..end_row {
1490 let indent_column = buffer.read(cx).indent_column_for_line(row) as usize;
1491 let columns_to_next_tab_stop = tab_size - (indent_column % tab_size);
1492 let row_start = Point::new(row, 0);
1493 buffer.edit(
1494 [row_start..row_start],
1495 " ".repeat(columns_to_next_tab_stop),
1496 cx,
1497 );
1498
1499 // Update this selection's endpoints to reflect the indentation.
1500 if row == selection.start.row {
1501 selection.start.column += columns_to_next_tab_stop as u32;
1502 }
1503 if row == selection.end.row {
1504 selection.end.column += columns_to_next_tab_stop as u32;
1505 }
1506
1507 last_indent = Some((row, columns_to_next_tab_stop as u32));
1508 }
1509 }
1510 }
1511 });
1512
1513 self.update_selections(selections, Some(Autoscroll::Fit), cx);
1514 self.end_transaction(cx);
1515 }
1516
1517 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
1518 self.start_transaction(cx);
1519 let tab_size = (self.build_settings)(cx).tab_size;
1520 let selections = self.local_selections::<Point>(cx);
1521 let mut deletion_ranges = Vec::new();
1522 let mut last_outdent = None;
1523 {
1524 let buffer = self.buffer.read(cx).read(cx);
1525 for selection in &selections {
1526 let mut start_row = selection.start.row;
1527 let mut end_row = selection.end.row + 1;
1528
1529 // If a selection ends at the beginning of a line, don't indent
1530 // that last line.
1531 if selection.end.column == 0 {
1532 end_row -= 1;
1533 }
1534
1535 // Avoid re-outdenting a row that has already been outdented by a
1536 // previous selection.
1537 if let Some(last_row) = last_outdent {
1538 if last_row == selection.start.row {
1539 start_row += 1;
1540 }
1541 }
1542
1543 for row in start_row..end_row {
1544 let column = buffer.indent_column_for_line(row) as usize;
1545 if column > 0 {
1546 let mut deletion_len = (column % tab_size) as u32;
1547 if deletion_len == 0 {
1548 deletion_len = tab_size as u32;
1549 }
1550 deletion_ranges.push(Point::new(row, 0)..Point::new(row, deletion_len));
1551 last_outdent = Some(row);
1552 }
1553 }
1554 }
1555 }
1556 self.buffer.update(cx, |buffer, cx| {
1557 buffer.edit(deletion_ranges, "", cx);
1558 });
1559
1560 self.update_selections(
1561 self.local_selections::<usize>(cx),
1562 Some(Autoscroll::Fit),
1563 cx,
1564 );
1565 self.end_transaction(cx);
1566 }
1567
1568 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
1569 self.start_transaction(cx);
1570
1571 let selections = self.local_selections::<Point>(cx);
1572 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1573 let buffer = self.buffer.read(cx).snapshot(cx);
1574
1575 let mut row_delta = 0;
1576 let mut new_cursors = Vec::new();
1577 let mut edit_ranges = Vec::new();
1578 let mut selections = selections.iter().peekable();
1579 while let Some(selection) = selections.next() {
1580 let mut rows = selection.spanned_rows(false, &display_map).buffer_rows;
1581 let goal_display_column = selection.head().to_display_point(&display_map).column();
1582
1583 // Accumulate contiguous regions of rows that we want to delete.
1584 while let Some(next_selection) = selections.peek() {
1585 let next_rows = next_selection.spanned_rows(false, &display_map).buffer_rows;
1586 if next_rows.start <= rows.end {
1587 rows.end = next_rows.end;
1588 selections.next().unwrap();
1589 } else {
1590 break;
1591 }
1592 }
1593
1594 let mut edit_start = Point::new(rows.start, 0).to_offset(&buffer);
1595 let edit_end;
1596 let cursor_buffer_row;
1597 if buffer.max_point().row >= rows.end {
1598 // If there's a line after the range, delete the \n from the end of the row range
1599 // and position the cursor on the next line.
1600 edit_end = Point::new(rows.end, 0).to_offset(&buffer);
1601 cursor_buffer_row = rows.start;
1602 } else {
1603 // If there isn't a line after the range, delete the \n from the line before the
1604 // start of the row range and position the cursor there.
1605 edit_start = edit_start.saturating_sub(1);
1606 edit_end = buffer.len();
1607 cursor_buffer_row = rows.start.saturating_sub(1);
1608 }
1609
1610 let mut cursor =
1611 Point::new(cursor_buffer_row - row_delta, 0).to_display_point(&display_map);
1612 *cursor.column_mut() =
1613 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
1614 row_delta += rows.len() as u32;
1615
1616 new_cursors.push((selection.id, cursor.to_point(&display_map)));
1617 edit_ranges.push(edit_start..edit_end);
1618 }
1619
1620 new_cursors.sort_unstable_by_key(|(_, point)| point.clone());
1621 let new_selections = new_cursors
1622 .into_iter()
1623 .map(|(id, cursor)| Selection {
1624 id,
1625 start: cursor,
1626 end: cursor,
1627 reversed: false,
1628 goal: SelectionGoal::None,
1629 })
1630 .collect();
1631 self.buffer
1632 .update(cx, |buffer, cx| buffer.edit(edit_ranges, "", cx));
1633 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
1634 self.end_transaction(cx);
1635 }
1636
1637 pub fn duplicate_line(&mut self, _: &DuplicateLine, cx: &mut ViewContext<Self>) {
1638 self.start_transaction(cx);
1639
1640 let mut selections = self.local_selections::<Point>(cx);
1641 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1642 let buffer = &display_map.buffer_snapshot;
1643
1644 let mut edits = Vec::new();
1645 let mut selections_iter = selections.iter().peekable();
1646 while let Some(selection) = selections_iter.next() {
1647 // Avoid duplicating the same lines twice.
1648 let mut rows = selection.spanned_rows(false, &display_map).buffer_rows;
1649
1650 while let Some(next_selection) = selections_iter.peek() {
1651 let next_rows = next_selection.spanned_rows(false, &display_map).buffer_rows;
1652 if next_rows.start <= rows.end - 1 {
1653 rows.end = next_rows.end;
1654 selections_iter.next().unwrap();
1655 } else {
1656 break;
1657 }
1658 }
1659
1660 // Copy the text from the selected row region and splice it at the start of the region.
1661 let start = Point::new(rows.start, 0);
1662 let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
1663 let text = buffer
1664 .text_for_range(start..end)
1665 .chain(Some("\n"))
1666 .collect::<String>();
1667 edits.push((start, text, rows.len() as u32));
1668 }
1669
1670 let mut edits_iter = edits.iter().peekable();
1671 let mut row_delta = 0;
1672 for selection in selections.iter_mut() {
1673 while let Some((point, _, line_count)) = edits_iter.peek() {
1674 if *point <= selection.start {
1675 row_delta += line_count;
1676 edits_iter.next();
1677 } else {
1678 break;
1679 }
1680 }
1681 selection.start.row += row_delta;
1682 selection.end.row += row_delta;
1683 }
1684
1685 self.buffer.update(cx, |buffer, cx| {
1686 for (point, text, _) in edits.into_iter().rev() {
1687 buffer.edit(Some(point..point), text, cx);
1688 }
1689 });
1690
1691 self.update_selections(selections, Some(Autoscroll::Fit), cx);
1692 self.end_transaction(cx);
1693 }
1694
1695 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
1696 self.start_transaction(cx);
1697
1698 let selections = self.local_selections::<Point>(cx);
1699 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1700 let buffer = self.buffer.read(cx).snapshot(cx);
1701
1702 let mut edits = Vec::new();
1703 let mut new_selection_ranges = Vec::new();
1704 let mut old_folds = Vec::new();
1705 let mut new_folds = Vec::new();
1706
1707 let mut selections = selections.iter().peekable();
1708 let mut contiguous_selections = Vec::new();
1709 while let Some(selection) = selections.next() {
1710 // Accumulate contiguous regions of rows that we want to move.
1711 contiguous_selections.push(selection.point_range(&buffer));
1712 let SpannedRows {
1713 mut buffer_rows,
1714 mut display_rows,
1715 } = selection.spanned_rows(false, &display_map);
1716
1717 while let Some(next_selection) = selections.peek() {
1718 let SpannedRows {
1719 buffer_rows: next_buffer_rows,
1720 display_rows: next_display_rows,
1721 } = next_selection.spanned_rows(false, &display_map);
1722 if next_buffer_rows.start <= buffer_rows.end {
1723 buffer_rows.end = next_buffer_rows.end;
1724 display_rows.end = next_display_rows.end;
1725 contiguous_selections.push(next_selection.point_range(&buffer));
1726 selections.next().unwrap();
1727 } else {
1728 break;
1729 }
1730 }
1731
1732 // Cut the text from the selected rows and paste it at the start of the previous line.
1733 if display_rows.start != 0 {
1734 let start = Point::new(buffer_rows.start, 0).to_offset(&buffer);
1735 let end = Point::new(buffer_rows.end - 1, buffer.line_len(buffer_rows.end - 1))
1736 .to_offset(&buffer);
1737
1738 let prev_row_display_start = DisplayPoint::new(display_rows.start - 1, 0);
1739 let prev_row_buffer_start = display_map.prev_row_boundary(prev_row_display_start).1;
1740 let prev_row_buffer_start_offset = prev_row_buffer_start.to_offset(&buffer);
1741
1742 let mut text = String::new();
1743 text.extend(buffer.text_for_range(start..end));
1744 text.push('\n');
1745 edits.push((
1746 prev_row_buffer_start_offset..prev_row_buffer_start_offset,
1747 text,
1748 ));
1749 edits.push((start - 1..end, String::new()));
1750
1751 let row_delta = buffer_rows.start - prev_row_buffer_start.row;
1752
1753 // Move selections up.
1754 for range in &mut contiguous_selections {
1755 range.start.row -= row_delta;
1756 range.end.row -= row_delta;
1757 }
1758
1759 // Move folds up.
1760 old_folds.push(start..end);
1761 for fold in display_map.folds_in_range(start..end) {
1762 let mut start = fold.start.to_point(&buffer);
1763 let mut end = fold.end.to_point(&buffer);
1764 start.row -= row_delta;
1765 end.row -= row_delta;
1766 new_folds.push(start..end);
1767 }
1768 }
1769
1770 new_selection_ranges.extend(contiguous_selections.drain(..));
1771 }
1772
1773 self.unfold_ranges(old_folds, cx);
1774 self.buffer.update(cx, |buffer, cx| {
1775 for (range, text) in edits.into_iter().rev() {
1776 buffer.edit(Some(range), text, cx);
1777 }
1778 });
1779 self.fold_ranges(new_folds, cx);
1780 self.select_ranges(new_selection_ranges, Some(Autoscroll::Fit), cx);
1781
1782 self.end_transaction(cx);
1783 }
1784
1785 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
1786 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1787 let buffer = self.buffer.read(cx).snapshot(cx);
1788
1789 let mut deletes = Vec::new();
1790 let mut inserts = Vec::new();
1791 // let mut new_selection_ranges = Vec::new();
1792 let mut unfold_ranges = Vec::new();
1793 let mut refold_ranges = Vec::new();
1794
1795 let selections = self.local_selections::<Point>(cx);
1796 let mut selections = selections.iter().peekable();
1797 let mut contiguous_row_selections = Vec::new();
1798 let mut new_selections = Vec::new();
1799
1800 while let Some(selection) = selections.next() {
1801 // Find all the selections that span a contiguous row range
1802 contiguous_row_selections.push(selection.clone());
1803 let start_row = selection.start.row;
1804 let mut end_row = if selection.end.column > 0 || selection.is_empty() {
1805 display_map
1806 .next_row_boundary(selection.end.to_display_point(&display_map))
1807 .1
1808 .row
1809 + 1
1810 } else {
1811 selection.end.row
1812 };
1813
1814 while let Some(next_selection) = selections.peek() {
1815 if next_selection.start.row <= end_row {
1816 end_row = if next_selection.end.column > 0 || next_selection.is_empty() {
1817 display_map
1818 .next_row_boundary(next_selection.end.to_display_point(&display_map))
1819 .1
1820 .row
1821 + 1
1822 } else {
1823 next_selection.end.row
1824 };
1825 contiguous_row_selections.push(selections.next().unwrap().clone());
1826 } else {
1827 break;
1828 }
1829 }
1830
1831 // Move the text spanned by the row range to be after the last line of the row range
1832 if end_row <= buffer.max_point().row {
1833 let range_to_move = Point::new(start_row, 0)..Point::new(end_row, 0);
1834 let insertion_point = Point::new(end_row, buffer.line_len(end_row));
1835 let insertion_row = insertion_point.row + 1;
1836 let mut text = String::from("\n");
1837 text.extend(buffer.text_for_range(range_to_move.clone()));
1838 text.pop(); // Drop trailing newline
1839 deletes.push(range_to_move.clone());
1840 inserts.push((insertion_point, text));
1841
1842 // Make the selections relative to the insertion row
1843 new_selections.extend(contiguous_row_selections.drain(..).map(|mut selection| {
1844 selection.start.row = insertion_row + selection.start.row - start_row;
1845 selection.end.row = insertion_row + selection.end.row - start_row;
1846 selection
1847 }));
1848
1849 // Unfold all the folds spanned by these rows
1850 unfold_ranges.push(range_to_move.clone());
1851
1852 // Refold ranges relative to the insertion row
1853 for fold in display_map.folds_in_range(
1854 buffer.anchor_before(range_to_move.start)
1855 ..buffer.anchor_after(range_to_move.end),
1856 ) {
1857 let mut start = fold.start.to_point(&buffer);
1858 let mut end = fold.end.to_point(&buffer);
1859 start.row = insertion_row + start.row - start_row;
1860 end.row = insertion_row + end.row - start_row;
1861 refold_ranges.push(start..end);
1862 }
1863 } else {
1864 new_selections.extend(contiguous_row_selections.drain(..));
1865 }
1866 }
1867
1868 self.start_transaction(cx);
1869 self.unfold_ranges(unfold_ranges, cx);
1870 self.buffer.update(cx, |buffer, cx| {
1871 for (point, text) in inserts.into_iter().rev() {
1872 buffer.edit([point..point], text, cx);
1873 }
1874 });
1875 self.fold_ranges(refold_ranges, cx);
1876 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
1877 self.buffer.update(cx, |buffer, cx| {
1878 buffer.edit(deletes.into_iter().rev(), "", cx);
1879 });
1880 self.end_transaction(cx);
1881 }
1882
1883 pub fn move_line_down2(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
1884 let selections = self.local_selections::<Point>(cx);
1885 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1886 let buffer = self.buffer.read(cx).snapshot(cx);
1887
1888 let mut edits = Vec::new();
1889 let mut new_selection_ranges = Vec::new();
1890 let mut old_folds = Vec::new();
1891 let mut new_folds = Vec::new();
1892
1893 let mut selections = selections.iter().peekable();
1894 let mut contiguous_selections = Vec::new();
1895 while let Some(selection) = selections.next() {
1896 // Accumulate contiguous regions of rows that we want to move.
1897 contiguous_selections.push(selection.point_range(&buffer));
1898
1899 let SpannedRows {
1900 mut buffer_rows,
1901 mut display_rows,
1902 } = selection.spanned_rows(false, &display_map);
1903
1904 while let Some(next_selection) = selections.peek() {
1905 let SpannedRows {
1906 buffer_rows: next_buffer_rows,
1907 display_rows: next_display_rows,
1908 } = next_selection.spanned_rows(false, &display_map);
1909 if next_buffer_rows.start <= buffer_rows.end {
1910 buffer_rows.end = next_buffer_rows.end;
1911 display_rows.end = next_display_rows.end;
1912 contiguous_selections.push(next_selection.point_range(&buffer));
1913 selections.next().unwrap();
1914 } else {
1915 break;
1916 }
1917 }
1918
1919 println!("spanned buffer rows {:?}", buffer_rows);
1920 println!("spanned display rows {:?}", display_rows);
1921
1922 // Cut the text from the selected rows and paste it at the end of the next line.
1923 if display_rows.end <= display_map.max_point().row() {
1924 let start = Point::new(buffer_rows.start, 0).to_offset(&buffer);
1925 let end = Point::new(buffer_rows.end - 1, buffer.line_len(buffer_rows.end - 1))
1926 .to_offset(&buffer);
1927
1928 let next_row_display_end =
1929 DisplayPoint::new(display_rows.end, display_map.line_len(display_rows.end));
1930 let next_row_buffer_end = display_map.next_row_boundary(next_row_display_end).1;
1931 let next_row_buffer_end_offset = next_row_buffer_end.to_offset(&buffer);
1932
1933 dbg!(next_row_display_end);
1934 dbg!(next_row_buffer_end);
1935
1936 let mut text = String::new();
1937 text.push('\n');
1938 text.extend(buffer.text_for_range(start..end));
1939 edits.push((start..end + 1, String::new()));
1940 edits.push((next_row_buffer_end_offset..next_row_buffer_end_offset, text));
1941
1942 // Move selections down.
1943 let display_row_delta = next_row_display_end.row() - display_rows.end + 1;
1944 for range in &mut contiguous_selections {
1945 range.start.row += display_row_delta;
1946 range.end.row += display_row_delta;
1947 }
1948
1949 // Move folds down.
1950 old_folds.push(start..end);
1951 let buffer_row_delta = next_row_buffer_end.row - buffer_rows.end + 1;
1952 for fold in display_map.folds_in_range(start..end) {
1953 let mut start = fold.start.to_point(&buffer);
1954 let mut end = fold.end.to_point(&buffer);
1955 start.row += buffer_row_delta;
1956 end.row += buffer_row_delta;
1957 new_folds.push(start..end);
1958 }
1959 }
1960
1961 new_selection_ranges.extend(contiguous_selections.drain(..));
1962 }
1963
1964 self.start_transaction(cx);
1965
1966 self.unfold_ranges(old_folds, cx);
1967 self.buffer.update(cx, |buffer, cx| {
1968 for (range, text) in edits.into_iter().rev() {
1969 buffer.edit(Some(range), text, cx);
1970 }
1971 });
1972 self.fold_ranges(new_folds, cx);
1973 self.select_ranges(new_selection_ranges, Some(Autoscroll::Fit), cx);
1974
1975 self.end_transaction(cx);
1976 }
1977
1978 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
1979 self.start_transaction(cx);
1980 let mut text = String::new();
1981 let mut selections = self.local_selections::<Point>(cx);
1982 let mut clipboard_selections = Vec::with_capacity(selections.len());
1983 {
1984 let buffer = self.buffer.read(cx).read(cx);
1985 let max_point = buffer.max_point();
1986 for selection in &mut selections {
1987 let is_entire_line = selection.is_empty();
1988 if is_entire_line {
1989 selection.start = Point::new(selection.start.row, 0);
1990 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
1991 }
1992 let mut len = 0;
1993 for chunk in buffer.text_for_range(selection.start..selection.end) {
1994 text.push_str(chunk);
1995 len += chunk.len();
1996 }
1997 clipboard_selections.push(ClipboardSelection {
1998 len,
1999 is_entire_line,
2000 });
2001 }
2002 }
2003 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2004 self.insert("", cx);
2005 self.end_transaction(cx);
2006
2007 cx.as_mut()
2008 .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
2009 }
2010
2011 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
2012 let selections = self.local_selections::<Point>(cx);
2013 let mut text = String::new();
2014 let mut clipboard_selections = Vec::with_capacity(selections.len());
2015 {
2016 let buffer = self.buffer.read(cx).read(cx);
2017 let max_point = buffer.max_point();
2018 for selection in selections.iter() {
2019 let mut start = selection.start;
2020 let mut end = selection.end;
2021 let is_entire_line = selection.is_empty();
2022 if is_entire_line {
2023 start = Point::new(start.row, 0);
2024 end = cmp::min(max_point, Point::new(start.row + 1, 0));
2025 }
2026 let mut len = 0;
2027 for chunk in buffer.text_for_range(start..end) {
2028 text.push_str(chunk);
2029 len += chunk.len();
2030 }
2031 clipboard_selections.push(ClipboardSelection {
2032 len,
2033 is_entire_line,
2034 });
2035 }
2036 }
2037
2038 cx.as_mut()
2039 .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
2040 }
2041
2042 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
2043 if let Some(item) = cx.as_mut().read_from_clipboard() {
2044 let clipboard_text = item.text();
2045 if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
2046 let mut selections = self.local_selections::<usize>(cx);
2047 let all_selections_were_entire_line =
2048 clipboard_selections.iter().all(|s| s.is_entire_line);
2049 if clipboard_selections.len() != selections.len() {
2050 clipboard_selections.clear();
2051 }
2052
2053 let mut delta = 0_isize;
2054 let mut start_offset = 0;
2055 for (i, selection) in selections.iter_mut().enumerate() {
2056 let to_insert;
2057 let entire_line;
2058 if let Some(clipboard_selection) = clipboard_selections.get(i) {
2059 let end_offset = start_offset + clipboard_selection.len;
2060 to_insert = &clipboard_text[start_offset..end_offset];
2061 entire_line = clipboard_selection.is_entire_line;
2062 start_offset = end_offset
2063 } else {
2064 to_insert = clipboard_text.as_str();
2065 entire_line = all_selections_were_entire_line;
2066 }
2067
2068 selection.start = (selection.start as isize + delta) as usize;
2069 selection.end = (selection.end as isize + delta) as usize;
2070
2071 self.buffer.update(cx, |buffer, cx| {
2072 // If the corresponding selection was empty when this slice of the
2073 // clipboard text was written, then the entire line containing the
2074 // selection was copied. If this selection is also currently empty,
2075 // then paste the line before the current line of the buffer.
2076 let range = if selection.is_empty() && entire_line {
2077 let column = selection.start.to_point(&buffer.read(cx)).column as usize;
2078 let line_start = selection.start - column;
2079 line_start..line_start
2080 } else {
2081 selection.start..selection.end
2082 };
2083
2084 delta += to_insert.len() as isize - range.len() as isize;
2085 buffer.edit([range], to_insert, cx);
2086 selection.start += to_insert.len();
2087 selection.end = selection.start;
2088 });
2089 }
2090 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2091 } else {
2092 self.insert(clipboard_text, cx);
2093 }
2094 }
2095 }
2096
2097 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
2098 if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
2099 if let Some((selections, _)) = self.selection_history.get(&tx_id).cloned() {
2100 self.set_selections(selections, cx);
2101 }
2102 self.request_autoscroll(Autoscroll::Fit, cx);
2103 }
2104 }
2105
2106 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
2107 if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
2108 if let Some((_, Some(selections))) = self.selection_history.get(&tx_id).cloned() {
2109 self.set_selections(selections, cx);
2110 }
2111 self.request_autoscroll(Autoscroll::Fit, cx);
2112 }
2113 }
2114
2115 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
2116 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2117 let mut selections = self.local_selections::<Point>(cx);
2118 for selection in &mut selections {
2119 let start = selection.start.to_display_point(&display_map);
2120 let end = selection.end.to_display_point(&display_map);
2121
2122 if start != end {
2123 selection.end = selection.start.clone();
2124 } else {
2125 let cursor = movement::left(&display_map, start)
2126 .unwrap()
2127 .to_point(&display_map);
2128 selection.start = cursor.clone();
2129 selection.end = cursor;
2130 }
2131 selection.reversed = false;
2132 selection.goal = SelectionGoal::None;
2133 }
2134 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2135 }
2136
2137 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
2138 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2139 let mut selections = self.local_selections::<Point>(cx);
2140 for selection in &mut selections {
2141 let head = selection.head().to_display_point(&display_map);
2142 let cursor = movement::left(&display_map, head)
2143 .unwrap()
2144 .to_point(&display_map);
2145 selection.set_head(cursor);
2146 selection.goal = SelectionGoal::None;
2147 }
2148 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2149 }
2150
2151 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
2152 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2153 let mut selections = self.local_selections::<Point>(cx);
2154 for selection in &mut selections {
2155 let start = selection.start.to_display_point(&display_map);
2156 let end = selection.end.to_display_point(&display_map);
2157
2158 if start != end {
2159 selection.start = selection.end.clone();
2160 } else {
2161 let cursor = movement::right(&display_map, end)
2162 .unwrap()
2163 .to_point(&display_map);
2164 selection.start = cursor;
2165 selection.end = cursor;
2166 }
2167 selection.reversed = false;
2168 selection.goal = SelectionGoal::None;
2169 }
2170 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2171 }
2172
2173 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
2174 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2175 let mut selections = self.local_selections::<Point>(cx);
2176 for selection in &mut selections {
2177 let head = selection.head().to_display_point(&display_map);
2178 let cursor = movement::right(&display_map, head)
2179 .unwrap()
2180 .to_point(&display_map);
2181 selection.set_head(cursor);
2182 selection.goal = SelectionGoal::None;
2183 }
2184 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2185 }
2186
2187 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
2188 if matches!(self.mode, EditorMode::SingleLine) {
2189 cx.propagate_action();
2190 return;
2191 }
2192
2193 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2194 let mut selections = self.local_selections::<Point>(cx);
2195 for selection in &mut selections {
2196 let start = selection.start.to_display_point(&display_map);
2197 let end = selection.end.to_display_point(&display_map);
2198 if start != end {
2199 selection.goal = SelectionGoal::None;
2200 }
2201
2202 let (start, goal) = movement::up(&display_map, start, selection.goal).unwrap();
2203 let cursor = start.to_point(&display_map);
2204 selection.start = cursor;
2205 selection.end = cursor;
2206 selection.goal = goal;
2207 selection.reversed = false;
2208 }
2209 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2210 }
2211
2212 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
2213 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2214 let mut selections = self.local_selections::<Point>(cx);
2215 for selection in &mut selections {
2216 let head = selection.head().to_display_point(&display_map);
2217 let (head, goal) = movement::up(&display_map, head, selection.goal).unwrap();
2218 let cursor = head.to_point(&display_map);
2219 selection.set_head(cursor);
2220 selection.goal = goal;
2221 }
2222 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2223 }
2224
2225 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
2226 if matches!(self.mode, EditorMode::SingleLine) {
2227 cx.propagate_action();
2228 return;
2229 }
2230
2231 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2232 let mut selections = self.local_selections::<Point>(cx);
2233 for selection in &mut selections {
2234 let start = selection.start.to_display_point(&display_map);
2235 let end = selection.end.to_display_point(&display_map);
2236 if start != end {
2237 selection.goal = SelectionGoal::None;
2238 }
2239
2240 let (start, goal) = movement::down(&display_map, end, selection.goal).unwrap();
2241 let cursor = start.to_point(&display_map);
2242 selection.start = cursor;
2243 selection.end = cursor;
2244 selection.goal = goal;
2245 selection.reversed = false;
2246 }
2247 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2248 }
2249
2250 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
2251 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2252 let mut selections = self.local_selections::<Point>(cx);
2253 for selection in &mut selections {
2254 let head = selection.head().to_display_point(&display_map);
2255 let (head, goal) = movement::down(&display_map, head, selection.goal).unwrap();
2256 let cursor = head.to_point(&display_map);
2257 selection.set_head(cursor);
2258 selection.goal = goal;
2259 }
2260 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2261 }
2262
2263 pub fn move_to_previous_word_boundary(
2264 &mut self,
2265 _: &MoveToPreviousWordBoundary,
2266 cx: &mut ViewContext<Self>,
2267 ) {
2268 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2269 let mut selections = self.local_selections::<Point>(cx);
2270 for selection in &mut selections {
2271 let head = selection.head().to_display_point(&display_map);
2272 let cursor = movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2273 selection.start = cursor.clone();
2274 selection.end = cursor;
2275 selection.reversed = false;
2276 selection.goal = SelectionGoal::None;
2277 }
2278 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2279 }
2280
2281 pub fn select_to_previous_word_boundary(
2282 &mut self,
2283 _: &SelectToPreviousWordBoundary,
2284 cx: &mut ViewContext<Self>,
2285 ) {
2286 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2287 let mut selections = self.local_selections::<Point>(cx);
2288 for selection in &mut selections {
2289 let head = selection.head().to_display_point(&display_map);
2290 let cursor = movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2291 selection.set_head(cursor);
2292 selection.goal = SelectionGoal::None;
2293 }
2294 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2295 }
2296
2297 pub fn delete_to_previous_word_boundary(
2298 &mut self,
2299 _: &DeleteToPreviousWordBoundary,
2300 cx: &mut ViewContext<Self>,
2301 ) {
2302 self.start_transaction(cx);
2303 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2304 let mut selections = self.local_selections::<Point>(cx);
2305 for selection in &mut selections {
2306 if selection.is_empty() {
2307 let head = selection.head().to_display_point(&display_map);
2308 let cursor =
2309 movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2310 selection.set_head(cursor);
2311 selection.goal = SelectionGoal::None;
2312 }
2313 }
2314 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2315 self.insert("", cx);
2316 self.end_transaction(cx);
2317 }
2318
2319 pub fn move_to_next_word_boundary(
2320 &mut self,
2321 _: &MoveToNextWordBoundary,
2322 cx: &mut ViewContext<Self>,
2323 ) {
2324 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2325 let mut selections = self.local_selections::<Point>(cx);
2326 for selection in &mut selections {
2327 let head = selection.head().to_display_point(&display_map);
2328 let cursor = movement::next_word_boundary(&display_map, head).to_point(&display_map);
2329 selection.start = cursor;
2330 selection.end = cursor;
2331 selection.reversed = false;
2332 selection.goal = SelectionGoal::None;
2333 }
2334 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2335 }
2336
2337 pub fn select_to_next_word_boundary(
2338 &mut self,
2339 _: &SelectToNextWordBoundary,
2340 cx: &mut ViewContext<Self>,
2341 ) {
2342 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2343 let mut selections = self.local_selections::<Point>(cx);
2344 for selection in &mut selections {
2345 let head = selection.head().to_display_point(&display_map);
2346 let cursor = movement::next_word_boundary(&display_map, head).to_point(&display_map);
2347 selection.set_head(cursor);
2348 selection.goal = SelectionGoal::None;
2349 }
2350 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2351 }
2352
2353 pub fn delete_to_next_word_boundary(
2354 &mut self,
2355 _: &DeleteToNextWordBoundary,
2356 cx: &mut ViewContext<Self>,
2357 ) {
2358 self.start_transaction(cx);
2359 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2360 let mut selections = self.local_selections::<Point>(cx);
2361 for selection in &mut selections {
2362 if selection.is_empty() {
2363 let head = selection.head().to_display_point(&display_map);
2364 let cursor =
2365 movement::next_word_boundary(&display_map, head).to_point(&display_map);
2366 selection.set_head(cursor);
2367 selection.goal = SelectionGoal::None;
2368 }
2369 }
2370 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2371 self.insert("", cx);
2372 self.end_transaction(cx);
2373 }
2374
2375 pub fn move_to_beginning_of_line(
2376 &mut self,
2377 _: &MoveToBeginningOfLine,
2378 cx: &mut ViewContext<Self>,
2379 ) {
2380 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2381 let mut selections = self.local_selections::<Point>(cx);
2382 for selection in &mut selections {
2383 let head = selection.head().to_display_point(&display_map);
2384 let new_head = movement::line_beginning(&display_map, head, true);
2385 let cursor = new_head.to_point(&display_map);
2386 selection.start = cursor;
2387 selection.end = cursor;
2388 selection.reversed = false;
2389 selection.goal = SelectionGoal::None;
2390 }
2391 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2392 }
2393
2394 pub fn select_to_beginning_of_line(
2395 &mut self,
2396 SelectToBeginningOfLine(toggle_indent): &SelectToBeginningOfLine,
2397 cx: &mut ViewContext<Self>,
2398 ) {
2399 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2400 let mut selections = self.local_selections::<Point>(cx);
2401 for selection in &mut selections {
2402 let head = selection.head().to_display_point(&display_map);
2403 let new_head = movement::line_beginning(&display_map, head, *toggle_indent);
2404 selection.set_head(new_head.to_point(&display_map));
2405 selection.goal = SelectionGoal::None;
2406 }
2407 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2408 }
2409
2410 pub fn delete_to_beginning_of_line(
2411 &mut self,
2412 _: &DeleteToBeginningOfLine,
2413 cx: &mut ViewContext<Self>,
2414 ) {
2415 self.start_transaction(cx);
2416 self.select_to_beginning_of_line(&SelectToBeginningOfLine(false), cx);
2417 self.backspace(&Backspace, cx);
2418 self.end_transaction(cx);
2419 }
2420
2421 pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
2422 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2423 let mut selections = self.local_selections::<Point>(cx);
2424 {
2425 for selection in &mut selections {
2426 let head = selection.head().to_display_point(&display_map);
2427 let new_head = movement::line_end(&display_map, head);
2428 let anchor = new_head.to_point(&display_map);
2429 selection.start = anchor.clone();
2430 selection.end = anchor;
2431 selection.reversed = false;
2432 selection.goal = SelectionGoal::None;
2433 }
2434 }
2435 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2436 }
2437
2438 pub fn select_to_end_of_line(&mut self, _: &SelectToEndOfLine, cx: &mut ViewContext<Self>) {
2439 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2440 let mut selections = self.local_selections::<Point>(cx);
2441 for selection in &mut selections {
2442 let head = selection.head().to_display_point(&display_map);
2443 let new_head = movement::line_end(&display_map, head);
2444 selection.set_head(new_head.to_point(&display_map));
2445 selection.goal = SelectionGoal::None;
2446 }
2447 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2448 }
2449
2450 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
2451 self.start_transaction(cx);
2452 self.select_to_end_of_line(&SelectToEndOfLine, cx);
2453 self.delete(&Delete, cx);
2454 self.end_transaction(cx);
2455 }
2456
2457 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
2458 self.start_transaction(cx);
2459 self.select_to_end_of_line(&SelectToEndOfLine, cx);
2460 self.cut(&Cut, cx);
2461 self.end_transaction(cx);
2462 }
2463
2464 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
2465 let selection = Selection {
2466 id: post_inc(&mut self.next_selection_id),
2467 start: 0,
2468 end: 0,
2469 reversed: false,
2470 goal: SelectionGoal::None,
2471 };
2472 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2473 }
2474
2475 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
2476 let mut selection = self.local_selections::<Point>(cx).last().unwrap().clone();
2477 selection.set_head(Point::zero());
2478 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2479 }
2480
2481 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
2482 let cursor = self.buffer.read(cx).read(cx).len();
2483 let selection = Selection {
2484 id: post_inc(&mut self.next_selection_id),
2485 start: cursor,
2486 end: cursor,
2487 reversed: false,
2488 goal: SelectionGoal::None,
2489 };
2490 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2491 }
2492
2493 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
2494 let mut selection = self.local_selections::<usize>(cx).first().unwrap().clone();
2495 selection.set_head(self.buffer.read(cx).read(cx).len());
2496 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2497 }
2498
2499 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
2500 let selection = Selection {
2501 id: post_inc(&mut self.next_selection_id),
2502 start: 0,
2503 end: self.buffer.read(cx).read(cx).len(),
2504 reversed: false,
2505 goal: SelectionGoal::None,
2506 };
2507 self.update_selections(vec![selection], None, cx);
2508 }
2509
2510 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
2511 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2512 let mut selections = self.local_selections::<Point>(cx);
2513 let max_point = display_map.buffer_snapshot.max_point();
2514 for selection in &mut selections {
2515 let rows = selection.spanned_rows(true, &display_map).buffer_rows;
2516 selection.start = Point::new(rows.start, 0);
2517 selection.end = cmp::min(max_point, Point::new(rows.end, 0));
2518 selection.reversed = false;
2519 }
2520 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2521 }
2522
2523 pub fn split_selection_into_lines(
2524 &mut self,
2525 _: &SplitSelectionIntoLines,
2526 cx: &mut ViewContext<Self>,
2527 ) {
2528 let mut to_unfold = Vec::new();
2529 let mut new_selections = Vec::new();
2530 {
2531 let selections = self.local_selections::<Point>(cx);
2532 let buffer = self.buffer.read(cx).read(cx);
2533 for selection in selections {
2534 for row in selection.start.row..selection.end.row {
2535 let cursor = Point::new(row, buffer.line_len(row));
2536 new_selections.push(Selection {
2537 id: post_inc(&mut self.next_selection_id),
2538 start: cursor,
2539 end: cursor,
2540 reversed: false,
2541 goal: SelectionGoal::None,
2542 });
2543 }
2544 new_selections.push(Selection {
2545 id: selection.id,
2546 start: selection.end,
2547 end: selection.end,
2548 reversed: false,
2549 goal: SelectionGoal::None,
2550 });
2551 to_unfold.push(selection.start..selection.end);
2552 }
2553 }
2554 self.unfold_ranges(to_unfold, cx);
2555 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2556 }
2557
2558 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
2559 self.add_selection(true, cx);
2560 }
2561
2562 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
2563 self.add_selection(false, cx);
2564 }
2565
2566 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
2567 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2568 let mut selections = self.local_selections::<Point>(cx);
2569 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
2570 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
2571 let range = oldest_selection.display_range(&display_map).sorted();
2572 let columns = cmp::min(range.start.column(), range.end.column())
2573 ..cmp::max(range.start.column(), range.end.column());
2574
2575 selections.clear();
2576 let mut stack = Vec::new();
2577 for row in range.start.row()..=range.end.row() {
2578 if let Some(selection) = self.build_columnar_selection(
2579 &display_map,
2580 row,
2581 &columns,
2582 oldest_selection.reversed,
2583 ) {
2584 stack.push(selection.id);
2585 selections.push(selection);
2586 }
2587 }
2588
2589 if above {
2590 stack.reverse();
2591 }
2592
2593 AddSelectionsState { above, stack }
2594 });
2595
2596 let last_added_selection = *state.stack.last().unwrap();
2597 let mut new_selections = Vec::new();
2598 if above == state.above {
2599 let end_row = if above {
2600 0
2601 } else {
2602 display_map.max_point().row()
2603 };
2604
2605 'outer: for selection in selections {
2606 if selection.id == last_added_selection {
2607 let range = selection.display_range(&display_map).sorted();
2608 debug_assert_eq!(range.start.row(), range.end.row());
2609 let mut row = range.start.row();
2610 let columns = if let SelectionGoal::ColumnRange { start, end } = selection.goal
2611 {
2612 start..end
2613 } else {
2614 cmp::min(range.start.column(), range.end.column())
2615 ..cmp::max(range.start.column(), range.end.column())
2616 };
2617
2618 while row != end_row {
2619 if above {
2620 row -= 1;
2621 } else {
2622 row += 1;
2623 }
2624
2625 if let Some(new_selection) = self.build_columnar_selection(
2626 &display_map,
2627 row,
2628 &columns,
2629 selection.reversed,
2630 ) {
2631 state.stack.push(new_selection.id);
2632 if above {
2633 new_selections.push(new_selection);
2634 new_selections.push(selection);
2635 } else {
2636 new_selections.push(selection);
2637 new_selections.push(new_selection);
2638 }
2639
2640 continue 'outer;
2641 }
2642 }
2643 }
2644
2645 new_selections.push(selection);
2646 }
2647 } else {
2648 new_selections = selections;
2649 new_selections.retain(|s| s.id != last_added_selection);
2650 state.stack.pop();
2651 }
2652
2653 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2654 if state.stack.len() > 1 {
2655 self.add_selections_state = Some(state);
2656 }
2657 }
2658
2659 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) {
2660 let replace_newest = action.0;
2661 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2662 let buffer = &display_map.buffer_snapshot;
2663 let mut selections = self.local_selections::<usize>(cx);
2664 if let Some(mut select_next_state) = self.select_next_state.take() {
2665 let query = &select_next_state.query;
2666 if !select_next_state.done {
2667 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
2668 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
2669 let mut next_selected_range = None;
2670
2671 let bytes_after_last_selection =
2672 buffer.bytes_in_range(last_selection.end..buffer.len());
2673 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
2674 let query_matches = query
2675 .stream_find_iter(bytes_after_last_selection)
2676 .map(|result| (last_selection.end, result))
2677 .chain(
2678 query
2679 .stream_find_iter(bytes_before_first_selection)
2680 .map(|result| (0, result)),
2681 );
2682 for (start_offset, query_match) in query_matches {
2683 let query_match = query_match.unwrap(); // can only fail due to I/O
2684 let offset_range =
2685 start_offset + query_match.start()..start_offset + query_match.end();
2686 let display_range = offset_range.start.to_display_point(&display_map)
2687 ..offset_range.end.to_display_point(&display_map);
2688
2689 if !select_next_state.wordwise
2690 || (!movement::is_inside_word(&display_map, display_range.start)
2691 && !movement::is_inside_word(&display_map, display_range.end))
2692 {
2693 next_selected_range = Some(offset_range);
2694 break;
2695 }
2696 }
2697
2698 if let Some(next_selected_range) = next_selected_range {
2699 if replace_newest {
2700 if let Some(newest_id) =
2701 selections.iter().max_by_key(|s| s.id).map(|s| s.id)
2702 {
2703 selections.retain(|s| s.id != newest_id);
2704 }
2705 }
2706 selections.push(Selection {
2707 id: post_inc(&mut self.next_selection_id),
2708 start: next_selected_range.start,
2709 end: next_selected_range.end,
2710 reversed: false,
2711 goal: SelectionGoal::None,
2712 });
2713 selections.sort_unstable_by_key(|s| s.start);
2714 self.update_selections(selections, Some(Autoscroll::Newest), cx);
2715 } else {
2716 select_next_state.done = true;
2717 }
2718 }
2719
2720 self.select_next_state = Some(select_next_state);
2721 } else if selections.len() == 1 {
2722 let selection = selections.last_mut().unwrap();
2723 if selection.start == selection.end {
2724 let word_range = movement::surrounding_word(
2725 &display_map,
2726 selection.start.to_display_point(&display_map),
2727 );
2728 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
2729 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
2730 selection.goal = SelectionGoal::None;
2731 selection.reversed = false;
2732
2733 let query = buffer
2734 .text_for_range(selection.start..selection.end)
2735 .collect::<String>();
2736 let select_state = SelectNextState {
2737 query: AhoCorasick::new_auto_configured(&[query]),
2738 wordwise: true,
2739 done: false,
2740 };
2741 self.update_selections(selections, Some(Autoscroll::Newest), cx);
2742 self.select_next_state = Some(select_state);
2743 } else {
2744 let query = buffer
2745 .text_for_range(selection.start..selection.end)
2746 .collect::<String>();
2747 self.select_next_state = Some(SelectNextState {
2748 query: AhoCorasick::new_auto_configured(&[query]),
2749 wordwise: false,
2750 done: false,
2751 });
2752 self.select_next(action, cx);
2753 }
2754 }
2755 }
2756
2757 pub fn toggle_comments(&mut self, _: &ToggleComments, cx: &mut ViewContext<Self>) {
2758 // Get the line comment prefix. Split its trailing whitespace into a separate string,
2759 // as that portion won't be used for detecting if a line is a comment.
2760 let full_comment_prefix =
2761 if let Some(prefix) = self.language(cx).and_then(|l| l.line_comment_prefix()) {
2762 prefix.to_string()
2763 } else {
2764 return;
2765 };
2766 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
2767 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
2768
2769 self.start_transaction(cx);
2770 let mut selections = self.local_selections::<Point>(cx);
2771 let mut all_selection_lines_are_comments = true;
2772 let mut edit_ranges = Vec::new();
2773 let mut last_toggled_row = None;
2774 self.buffer.update(cx, |buffer, cx| {
2775 for selection in &mut selections {
2776 edit_ranges.clear();
2777 let snapshot = buffer.snapshot(cx);
2778
2779 let end_row =
2780 if selection.end.row > selection.start.row && selection.end.column == 0 {
2781 selection.end.row
2782 } else {
2783 selection.end.row + 1
2784 };
2785
2786 for row in selection.start.row..end_row {
2787 // If multiple selections contain a given row, avoid processing that
2788 // row more than once.
2789 if last_toggled_row == Some(row) {
2790 continue;
2791 } else {
2792 last_toggled_row = Some(row);
2793 }
2794
2795 if snapshot.is_line_blank(row) {
2796 continue;
2797 }
2798
2799 let start = Point::new(row, snapshot.indent_column_for_line(row));
2800 let mut line_bytes = snapshot
2801 .bytes_in_range(start..snapshot.max_point())
2802 .flatten()
2803 .copied();
2804
2805 // If this line currently begins with the line comment prefix, then record
2806 // the range containing the prefix.
2807 if all_selection_lines_are_comments
2808 && line_bytes
2809 .by_ref()
2810 .take(comment_prefix.len())
2811 .eq(comment_prefix.bytes())
2812 {
2813 // Include any whitespace that matches the comment prefix.
2814 let matching_whitespace_len = line_bytes
2815 .zip(comment_prefix_whitespace.bytes())
2816 .take_while(|(a, b)| a == b)
2817 .count() as u32;
2818 let end = Point::new(
2819 row,
2820 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
2821 );
2822 edit_ranges.push(start..end);
2823 }
2824 // If this line does not begin with the line comment prefix, then record
2825 // the position where the prefix should be inserted.
2826 else {
2827 all_selection_lines_are_comments = false;
2828 edit_ranges.push(start..start);
2829 }
2830 }
2831
2832 if !edit_ranges.is_empty() {
2833 if all_selection_lines_are_comments {
2834 buffer.edit(edit_ranges.iter().cloned(), "", cx);
2835 } else {
2836 let min_column = edit_ranges.iter().map(|r| r.start.column).min().unwrap();
2837 let edit_ranges = edit_ranges.iter().map(|range| {
2838 let position = Point::new(range.start.row, min_column);
2839 position..position
2840 });
2841 buffer.edit(edit_ranges, &full_comment_prefix, cx);
2842 }
2843 }
2844 }
2845 });
2846
2847 self.update_selections(
2848 self.local_selections::<usize>(cx),
2849 Some(Autoscroll::Fit),
2850 cx,
2851 );
2852 self.end_transaction(cx);
2853 }
2854
2855 pub fn select_larger_syntax_node(
2856 &mut self,
2857 _: &SelectLargerSyntaxNode,
2858 cx: &mut ViewContext<Self>,
2859 ) {
2860 let old_selections = self.local_selections::<usize>(cx).into_boxed_slice();
2861 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2862 let buffer = self.buffer.read(cx).snapshot(cx);
2863
2864 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
2865 let mut selected_larger_node = false;
2866 let mut new_selections = old_selections
2867 .iter()
2868 .map(|selection| {
2869 let old_range = selection.start..selection.end;
2870 let mut new_range = old_range.clone();
2871 while let Some(containing_range) =
2872 buffer.range_for_syntax_ancestor(new_range.clone())
2873 {
2874 new_range = containing_range;
2875 if !display_map.intersects_fold(new_range.start)
2876 && !display_map.intersects_fold(new_range.end)
2877 {
2878 break;
2879 }
2880 }
2881
2882 selected_larger_node |= new_range != old_range;
2883 Selection {
2884 id: selection.id,
2885 start: new_range.start,
2886 end: new_range.end,
2887 goal: SelectionGoal::None,
2888 reversed: selection.reversed,
2889 }
2890 })
2891 .collect::<Vec<_>>();
2892
2893 if selected_larger_node {
2894 stack.push(old_selections);
2895 new_selections.sort_unstable_by_key(|selection| selection.start);
2896 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2897 }
2898 self.select_larger_syntax_node_stack = stack;
2899 }
2900
2901 pub fn select_smaller_syntax_node(
2902 &mut self,
2903 _: &SelectSmallerSyntaxNode,
2904 cx: &mut ViewContext<Self>,
2905 ) {
2906 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
2907 if let Some(selections) = stack.pop() {
2908 self.update_selections(selections.to_vec(), Some(Autoscroll::Fit), cx);
2909 }
2910 self.select_larger_syntax_node_stack = stack;
2911 }
2912
2913 pub fn move_to_enclosing_bracket(
2914 &mut self,
2915 _: &MoveToEnclosingBracket,
2916 cx: &mut ViewContext<Self>,
2917 ) {
2918 let mut selections = self.local_selections::<usize>(cx);
2919 let buffer = self.buffer.read(cx).snapshot(cx);
2920 for selection in &mut selections {
2921 if let Some((open_range, close_range)) =
2922 buffer.enclosing_bracket_ranges(selection.start..selection.end)
2923 {
2924 let close_range = close_range.to_inclusive();
2925 let destination = if close_range.contains(&selection.start)
2926 && close_range.contains(&selection.end)
2927 {
2928 open_range.end
2929 } else {
2930 *close_range.start()
2931 };
2932 selection.start = destination;
2933 selection.end = destination;
2934 }
2935 }
2936
2937 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2938 }
2939
2940 pub fn show_next_diagnostic(&mut self, _: &ShowNextDiagnostic, cx: &mut ViewContext<Self>) {
2941 let buffer = self.buffer.read(cx).snapshot(cx);
2942 let selection = self.newest_selection::<usize>(&buffer);
2943 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
2944 active_diagnostics
2945 .primary_range
2946 .to_offset(&buffer)
2947 .to_inclusive()
2948 });
2949 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
2950 if active_primary_range.contains(&selection.head()) {
2951 *active_primary_range.end()
2952 } else {
2953 selection.head()
2954 }
2955 } else {
2956 selection.head()
2957 };
2958
2959 loop {
2960 let next_group = buffer
2961 .diagnostics_in_range::<_, usize>(search_start..buffer.len())
2962 .find_map(|(provider_name, entry)| {
2963 if entry.diagnostic.is_primary
2964 && !entry.range.is_empty()
2965 && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
2966 {
2967 Some((provider_name, entry.range, entry.diagnostic.group_id))
2968 } else {
2969 None
2970 }
2971 });
2972
2973 if let Some((provider_name, primary_range, group_id)) = next_group {
2974 self.activate_diagnostics(provider_name, group_id, cx);
2975 self.update_selections(
2976 vec![Selection {
2977 id: selection.id,
2978 start: primary_range.start,
2979 end: primary_range.start,
2980 reversed: false,
2981 goal: SelectionGoal::None,
2982 }],
2983 Some(Autoscroll::Center),
2984 cx,
2985 );
2986 break;
2987 } else if search_start == 0 {
2988 break;
2989 } else {
2990 // Cycle around to the start of the buffer.
2991 search_start = 0;
2992 }
2993 }
2994 }
2995
2996 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
2997 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
2998 let buffer = self.buffer.read(cx).snapshot(cx);
2999 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
3000 let is_valid = buffer
3001 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
3002 .any(|(_, entry)| {
3003 entry.diagnostic.is_primary
3004 && !entry.range.is_empty()
3005 && entry.range.start == primary_range_start
3006 && entry.diagnostic.message == active_diagnostics.primary_message
3007 });
3008
3009 if is_valid != active_diagnostics.is_valid {
3010 active_diagnostics.is_valid = is_valid;
3011 let mut new_styles = HashMap::default();
3012 for (block_id, diagnostic) in &active_diagnostics.blocks {
3013 new_styles.insert(
3014 *block_id,
3015 diagnostic_block_renderer(
3016 diagnostic.clone(),
3017 is_valid,
3018 self.build_settings.clone(),
3019 ),
3020 );
3021 }
3022 self.display_map
3023 .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
3024 }
3025 }
3026 }
3027
3028 fn activate_diagnostics(
3029 &mut self,
3030 provider_name: &str,
3031 group_id: usize,
3032 cx: &mut ViewContext<Self>,
3033 ) {
3034 self.dismiss_diagnostics(cx);
3035 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
3036 let buffer = self.buffer.read(cx).snapshot(cx);
3037
3038 let mut primary_range = None;
3039 let mut primary_message = None;
3040 let mut group_end = Point::zero();
3041 let diagnostic_group = buffer
3042 .diagnostic_group::<Point>(provider_name, group_id)
3043 .map(|entry| {
3044 if entry.range.end > group_end {
3045 group_end = entry.range.end;
3046 }
3047 if entry.diagnostic.is_primary {
3048 primary_range = Some(entry.range.clone());
3049 primary_message = Some(entry.diagnostic.message.clone());
3050 }
3051 entry
3052 })
3053 .collect::<Vec<_>>();
3054 let primary_range = primary_range.unwrap();
3055 let primary_message = primary_message.unwrap();
3056 let primary_range =
3057 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
3058
3059 let blocks = display_map
3060 .insert_blocks(
3061 diagnostic_group.iter().map(|entry| {
3062 let build_settings = self.build_settings.clone();
3063 let diagnostic = entry.diagnostic.clone();
3064 let message_height = diagnostic.message.lines().count() as u8;
3065
3066 BlockProperties {
3067 position: entry.range.start,
3068 height: message_height,
3069 render: diagnostic_block_renderer(diagnostic, true, build_settings),
3070 disposition: BlockDisposition::Below,
3071 }
3072 }),
3073 cx,
3074 )
3075 .into_iter()
3076 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
3077 .collect();
3078
3079 Some(ActiveDiagnosticGroup {
3080 primary_range,
3081 primary_message,
3082 blocks,
3083 is_valid: true,
3084 })
3085 });
3086 }
3087
3088 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
3089 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
3090 self.display_map.update(cx, |display_map, cx| {
3091 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
3092 });
3093 cx.notify();
3094 }
3095 }
3096
3097 fn build_columnar_selection(
3098 &mut self,
3099 display_map: &DisplaySnapshot,
3100 row: u32,
3101 columns: &Range<u32>,
3102 reversed: bool,
3103 ) -> Option<Selection<Point>> {
3104 let is_empty = columns.start == columns.end;
3105 let line_len = display_map.line_len(row);
3106 if columns.start < line_len || (is_empty && columns.start == line_len) {
3107 let start = DisplayPoint::new(row, columns.start);
3108 let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
3109 Some(Selection {
3110 id: post_inc(&mut self.next_selection_id),
3111 start: start.to_point(display_map),
3112 end: end.to_point(display_map),
3113 reversed,
3114 goal: SelectionGoal::ColumnRange {
3115 start: columns.start,
3116 end: columns.end,
3117 },
3118 })
3119 } else {
3120 None
3121 }
3122 }
3123
3124 pub fn visible_selections<'a>(
3125 &'a self,
3126 display_rows: Range<u32>,
3127 cx: &'a mut MutableAppContext,
3128 ) -> HashMap<ReplicaId, Vec<Selection<DisplayPoint>>> {
3129 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3130 let buffer = &display_map.buffer_snapshot;
3131
3132 let start = if display_rows.start == 0 {
3133 Anchor::min()
3134 } else {
3135 buffer.anchor_before(
3136 DisplayPoint::new(display_rows.start, 0).to_offset(&display_map, Bias::Left),
3137 )
3138 };
3139 let end = if display_rows.end > display_map.max_point().row() {
3140 Anchor::max()
3141 } else {
3142 buffer.anchor_before(
3143 DisplayPoint::new(display_rows.end, 0).to_offset(&display_map, Bias::Right),
3144 )
3145 };
3146
3147 let start_ix = match self
3148 .selections
3149 .binary_search_by(|probe| probe.end.cmp(&start, &buffer).unwrap())
3150 {
3151 Ok(ix) | Err(ix) => ix,
3152 };
3153 let end_ix = match self
3154 .selections
3155 .binary_search_by(|probe| probe.start.cmp(&end, &buffer).unwrap())
3156 {
3157 Ok(ix) => ix + 1,
3158 Err(ix) => ix,
3159 };
3160
3161 fn display_selection(
3162 selection: &Selection<Anchor>,
3163 display_map: &DisplaySnapshot,
3164 ) -> Selection<DisplayPoint> {
3165 Selection {
3166 id: selection.id,
3167 start: selection.start.to_display_point(&display_map),
3168 end: selection.end.to_display_point(&display_map),
3169 reversed: selection.reversed,
3170 goal: selection.goal,
3171 }
3172 }
3173
3174 let mut result = HashMap::default();
3175
3176 result.insert(
3177 self.replica_id(cx),
3178 self.selections[start_ix..end_ix]
3179 .iter()
3180 .chain(
3181 self.pending_selection
3182 .as_ref()
3183 .map(|pending| &pending.selection),
3184 )
3185 .map(|s| display_selection(s, &display_map))
3186 .collect(),
3187 );
3188
3189 for (replica_id, selection) in display_map
3190 .buffer_snapshot
3191 .remote_selections_in_range(&(start..end))
3192 {
3193 result
3194 .entry(replica_id)
3195 .or_insert(Vec::new())
3196 .push(display_selection(&selection, &display_map));
3197 }
3198
3199 result
3200 }
3201
3202 pub fn local_selections<'a, D>(&self, cx: &'a AppContext) -> Vec<Selection<D>>
3203 where
3204 D: 'a + TextDimension + Ord + Sub<D, Output = D>,
3205 {
3206 let buffer = self.buffer.read(cx).snapshot(cx);
3207 let mut selections = self
3208 .resolve_selections::<D, _>(self.selections.iter(), &buffer)
3209 .peekable();
3210
3211 let mut pending_selection = self.pending_selection::<D>(&buffer);
3212
3213 iter::from_fn(move || {
3214 if let Some(pending) = pending_selection.as_mut() {
3215 while let Some(next_selection) = selections.peek() {
3216 if pending.start <= next_selection.end && pending.end >= next_selection.start {
3217 let next_selection = selections.next().unwrap();
3218 if next_selection.start < pending.start {
3219 pending.start = next_selection.start;
3220 }
3221 if next_selection.end > pending.end {
3222 pending.end = next_selection.end;
3223 }
3224 } else if next_selection.end < pending.start {
3225 return selections.next();
3226 } else {
3227 break;
3228 }
3229 }
3230
3231 pending_selection.take()
3232 } else {
3233 selections.next()
3234 }
3235 })
3236 .collect()
3237 }
3238
3239 pub fn local_anchor_selections(&self) -> &Arc<[Selection<Anchor>]> {
3240 &self.selections
3241 }
3242
3243 fn resolve_selections<'a, D, I>(
3244 &self,
3245 selections: I,
3246 snapshot: &MultiBufferSnapshot,
3247 ) -> impl 'a + Iterator<Item = Selection<D>>
3248 where
3249 D: TextDimension + Ord + Sub<D, Output = D>,
3250 I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
3251 {
3252 let (to_summarize, selections) = selections.into_iter().tee();
3253 let mut summaries = snapshot
3254 .summaries_for_anchors::<D, _>(to_summarize.flat_map(|s| [&s.start, &s.end]))
3255 .into_iter();
3256 selections.map(move |s| Selection {
3257 id: s.id,
3258 start: summaries.next().unwrap(),
3259 end: summaries.next().unwrap(),
3260 reversed: s.reversed,
3261 goal: s.goal,
3262 })
3263 }
3264
3265 fn pending_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3266 &self,
3267 snapshot: &MultiBufferSnapshot,
3268 ) -> Option<Selection<D>> {
3269 self.pending_selection
3270 .as_ref()
3271 .map(|pending| self.resolve_selection(&pending.selection, &snapshot))
3272 }
3273
3274 fn resolve_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3275 &self,
3276 selection: &Selection<Anchor>,
3277 buffer: &MultiBufferSnapshot,
3278 ) -> Selection<D> {
3279 Selection {
3280 id: selection.id,
3281 start: selection.start.summary::<D>(&buffer),
3282 end: selection.end.summary::<D>(&buffer),
3283 reversed: selection.reversed,
3284 goal: selection.goal,
3285 }
3286 }
3287
3288 fn selection_count<'a>(&self) -> usize {
3289 let mut count = self.selections.len();
3290 if self.pending_selection.is_some() {
3291 count += 1;
3292 }
3293 count
3294 }
3295
3296 pub fn oldest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3297 &self,
3298 snapshot: &MultiBufferSnapshot,
3299 ) -> Selection<D> {
3300 self.selections
3301 .iter()
3302 .min_by_key(|s| s.id)
3303 .map(|selection| self.resolve_selection(selection, snapshot))
3304 .or_else(|| self.pending_selection(snapshot))
3305 .unwrap()
3306 }
3307
3308 pub fn newest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3309 &self,
3310 snapshot: &MultiBufferSnapshot,
3311 ) -> Selection<D> {
3312 self.pending_selection(snapshot)
3313 .or_else(|| {
3314 self.selections
3315 .iter()
3316 .max_by_key(|s| s.id)
3317 .map(|selection| self.resolve_selection(selection, snapshot))
3318 })
3319 .unwrap()
3320 }
3321
3322 pub fn update_selections<T>(
3323 &mut self,
3324 mut selections: Vec<Selection<T>>,
3325 autoscroll: Option<Autoscroll>,
3326 cx: &mut ViewContext<Self>,
3327 ) where
3328 T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
3329 {
3330 // Merge overlapping selections.
3331 let buffer = self.buffer.read(cx).snapshot(cx);
3332 let mut i = 1;
3333 while i < selections.len() {
3334 if selections[i - 1].end >= selections[i].start {
3335 let removed = selections.remove(i);
3336 if removed.start < selections[i - 1].start {
3337 selections[i - 1].start = removed.start;
3338 }
3339 if removed.end > selections[i - 1].end {
3340 selections[i - 1].end = removed.end;
3341 }
3342 } else {
3343 i += 1;
3344 }
3345 }
3346
3347 self.pending_selection = None;
3348 self.add_selections_state = None;
3349 self.select_next_state = None;
3350 self.select_larger_syntax_node_stack.clear();
3351 while let Some(autoclose_pair) = self.autoclose_stack.last() {
3352 let all_selections_inside_autoclose_ranges =
3353 if selections.len() == autoclose_pair.ranges.len() {
3354 selections
3355 .iter()
3356 .zip(autoclose_pair.ranges.iter().map(|r| r.to_point(&buffer)))
3357 .all(|(selection, autoclose_range)| {
3358 let head = selection.head().to_point(&buffer);
3359 autoclose_range.start <= head && autoclose_range.end >= head
3360 })
3361 } else {
3362 false
3363 };
3364
3365 if all_selections_inside_autoclose_ranges {
3366 break;
3367 } else {
3368 self.autoclose_stack.pop();
3369 }
3370 }
3371
3372 if let Some(autoscroll) = autoscroll {
3373 self.request_autoscroll(autoscroll, cx);
3374 }
3375 self.pause_cursor_blinking(cx);
3376
3377 self.set_selections(
3378 Arc::from_iter(selections.into_iter().map(|selection| {
3379 let end_bias = if selection.end > selection.start {
3380 Bias::Left
3381 } else {
3382 Bias::Right
3383 };
3384 Selection {
3385 id: selection.id,
3386 start: buffer.anchor_after(selection.start),
3387 end: buffer.anchor_at(selection.end, end_bias),
3388 reversed: selection.reversed,
3389 goal: selection.goal,
3390 }
3391 })),
3392 cx,
3393 );
3394 }
3395
3396 fn set_selections(&mut self, selections: Arc<[Selection<Anchor>]>, cx: &mut ViewContext<Self>) {
3397 self.selections = selections;
3398 self.buffer.update(cx, |buffer, cx| {
3399 buffer.set_active_selections(&self.selections, cx)
3400 });
3401 }
3402
3403 fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
3404 self.autoscroll_request = Some(autoscroll);
3405 cx.notify();
3406 }
3407
3408 fn start_transaction(&mut self, cx: &mut ViewContext<Self>) {
3409 self.start_transaction_at(Instant::now(), cx);
3410 }
3411
3412 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
3413 self.end_selection(cx);
3414 if let Some(tx_id) = self
3415 .buffer
3416 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
3417 {
3418 self.selection_history
3419 .insert(tx_id, (self.selections.clone(), None));
3420 }
3421 }
3422
3423 fn end_transaction(&mut self, cx: &mut ViewContext<Self>) {
3424 self.end_transaction_at(Instant::now(), cx);
3425 }
3426
3427 fn end_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
3428 if let Some(tx_id) = self
3429 .buffer
3430 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
3431 {
3432 self.selection_history.get_mut(&tx_id).unwrap().1 = Some(self.selections.clone());
3433 }
3434 }
3435
3436 pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
3437 log::info!("Editor::page_up");
3438 }
3439
3440 pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
3441 log::info!("Editor::page_down");
3442 }
3443
3444 pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
3445 let mut fold_ranges = Vec::new();
3446
3447 let selections = self.local_selections::<Point>(cx);
3448 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3449 for selection in selections {
3450 let range = selection.display_range(&display_map).sorted();
3451 let buffer_start_row = range.start.to_point(&display_map).row;
3452
3453 for row in (0..=range.end.row()).rev() {
3454 if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
3455 let fold_range = self.foldable_range_for_line(&display_map, row);
3456 if fold_range.end.row >= buffer_start_row {
3457 fold_ranges.push(fold_range);
3458 if row <= range.start.row() {
3459 break;
3460 }
3461 }
3462 }
3463 }
3464 }
3465
3466 self.fold_ranges(fold_ranges, cx);
3467 }
3468
3469 pub fn unfold(&mut self, _: &Unfold, cx: &mut ViewContext<Self>) {
3470 let selections = self.local_selections::<Point>(cx);
3471 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3472 let buffer = &display_map.buffer_snapshot;
3473 let ranges = selections
3474 .iter()
3475 .map(|s| {
3476 let range = s.display_range(&display_map).sorted();
3477 let mut start = range.start.to_point(&display_map);
3478 let mut end = range.end.to_point(&display_map);
3479 start.column = 0;
3480 end.column = buffer.line_len(end.row);
3481 start..end
3482 })
3483 .collect::<Vec<_>>();
3484 self.unfold_ranges(ranges, cx);
3485 }
3486
3487 fn is_line_foldable(&self, display_map: &DisplaySnapshot, display_row: u32) -> bool {
3488 let max_point = display_map.max_point();
3489 if display_row >= max_point.row() {
3490 false
3491 } else {
3492 let (start_indent, is_blank) = display_map.line_indent(display_row);
3493 if is_blank {
3494 false
3495 } else {
3496 for display_row in display_row + 1..=max_point.row() {
3497 let (indent, is_blank) = display_map.line_indent(display_row);
3498 if !is_blank {
3499 return indent > start_indent;
3500 }
3501 }
3502 false
3503 }
3504 }
3505 }
3506
3507 fn foldable_range_for_line(
3508 &self,
3509 display_map: &DisplaySnapshot,
3510 start_row: u32,
3511 ) -> Range<Point> {
3512 let max_point = display_map.max_point();
3513
3514 let (start_indent, _) = display_map.line_indent(start_row);
3515 let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
3516 let mut end = None;
3517 for row in start_row + 1..=max_point.row() {
3518 let (indent, is_blank) = display_map.line_indent(row);
3519 if !is_blank && indent <= start_indent {
3520 end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
3521 break;
3522 }
3523 }
3524
3525 let end = end.unwrap_or(max_point);
3526 return start.to_point(display_map)..end.to_point(display_map);
3527 }
3528
3529 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
3530 let selections = self.local_selections::<Point>(cx);
3531 let ranges = selections.into_iter().map(|s| s.start..s.end);
3532 self.fold_ranges(ranges, cx);
3533 }
3534
3535 fn fold_ranges<T: ToOffset>(
3536 &mut self,
3537 ranges: impl IntoIterator<Item = Range<T>>,
3538 cx: &mut ViewContext<Self>,
3539 ) {
3540 let mut ranges = ranges.into_iter().peekable();
3541 if ranges.peek().is_some() {
3542 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
3543 self.request_autoscroll(Autoscroll::Fit, cx);
3544 cx.notify();
3545 }
3546 }
3547
3548 fn unfold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
3549 if !ranges.is_empty() {
3550 self.display_map
3551 .update(cx, |map, cx| map.unfold(ranges, cx));
3552 self.request_autoscroll(Autoscroll::Fit, cx);
3553 cx.notify();
3554 }
3555 }
3556
3557 pub fn insert_blocks<P>(
3558 &mut self,
3559 blocks: impl IntoIterator<Item = BlockProperties<P>>,
3560 cx: &mut ViewContext<Self>,
3561 ) -> Vec<BlockId>
3562 where
3563 P: ToOffset + Clone,
3564 {
3565 let blocks = self
3566 .display_map
3567 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
3568 self.request_autoscroll(Autoscroll::Fit, cx);
3569 blocks
3570 }
3571
3572 pub fn replace_blocks(
3573 &mut self,
3574 blocks: HashMap<BlockId, RenderBlock>,
3575 cx: &mut ViewContext<Self>,
3576 ) {
3577 self.display_map
3578 .update(cx, |display_map, _| display_map.replace_blocks(blocks));
3579 self.request_autoscroll(Autoscroll::Fit, cx);
3580 }
3581
3582 pub fn remove_blocks(&mut self, block_ids: HashSet<BlockId>, cx: &mut ViewContext<Self>) {
3583 self.display_map.update(cx, |display_map, cx| {
3584 display_map.remove_blocks(block_ids, cx)
3585 });
3586 }
3587
3588 pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
3589 self.display_map
3590 .update(cx, |map, cx| map.snapshot(cx))
3591 .longest_row()
3592 }
3593
3594 pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
3595 self.display_map
3596 .update(cx, |map, cx| map.snapshot(cx))
3597 .max_point()
3598 }
3599
3600 pub fn text(&self, cx: &AppContext) -> String {
3601 self.buffer.read(cx).read(cx).text()
3602 }
3603
3604 pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
3605 self.display_map
3606 .update(cx, |map, cx| map.snapshot(cx))
3607 .text()
3608 }
3609
3610 pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut MutableAppContext) -> bool {
3611 self.display_map
3612 .update(cx, |map, cx| map.set_wrap_width(width, cx))
3613 }
3614
3615 pub fn set_highlighted_row(&mut self, row: Option<u32>) {
3616 self.highlighted_row = row;
3617 }
3618
3619 pub fn highlighted_row(&mut self) -> Option<u32> {
3620 self.highlighted_row
3621 }
3622
3623 fn next_blink_epoch(&mut self) -> usize {
3624 self.blink_epoch += 1;
3625 self.blink_epoch
3626 }
3627
3628 fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
3629 self.show_local_cursors = true;
3630 cx.notify();
3631
3632 let epoch = self.next_blink_epoch();
3633 cx.spawn(|this, mut cx| {
3634 let this = this.downgrade();
3635 async move {
3636 Timer::after(CURSOR_BLINK_INTERVAL).await;
3637 if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
3638 this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
3639 }
3640 }
3641 })
3642 .detach();
3643 }
3644
3645 fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
3646 if epoch == self.blink_epoch {
3647 self.blinking_paused = false;
3648 self.blink_cursors(epoch, cx);
3649 }
3650 }
3651
3652 fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
3653 if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
3654 self.show_local_cursors = !self.show_local_cursors;
3655 cx.notify();
3656
3657 let epoch = self.next_blink_epoch();
3658 cx.spawn(|this, mut cx| {
3659 let this = this.downgrade();
3660 async move {
3661 Timer::after(CURSOR_BLINK_INTERVAL).await;
3662 if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
3663 this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
3664 }
3665 }
3666 })
3667 .detach();
3668 }
3669 }
3670
3671 pub fn show_local_cursors(&self) -> bool {
3672 self.show_local_cursors
3673 }
3674
3675 fn on_buffer_changed(&mut self, _: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Self>) {
3676 self.refresh_active_diagnostics(cx);
3677 cx.notify();
3678 }
3679
3680 fn on_buffer_event(
3681 &mut self,
3682 _: ModelHandle<MultiBuffer>,
3683 event: &language::Event,
3684 cx: &mut ViewContext<Self>,
3685 ) {
3686 match event {
3687 language::Event::Edited => cx.emit(Event::Edited),
3688 language::Event::Dirtied => cx.emit(Event::Dirtied),
3689 language::Event::Saved => cx.emit(Event::Saved),
3690 language::Event::FileHandleChanged => cx.emit(Event::FileHandleChanged),
3691 language::Event::Reloaded => cx.emit(Event::FileHandleChanged),
3692 language::Event::Closed => cx.emit(Event::Closed),
3693 _ => {}
3694 }
3695 }
3696
3697 fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
3698 cx.notify();
3699 }
3700}
3701
3702impl EditorSnapshot {
3703 pub fn is_focused(&self) -> bool {
3704 self.is_focused
3705 }
3706
3707 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
3708 self.placeholder_text.as_ref()
3709 }
3710
3711 pub fn scroll_position(&self) -> Vector2F {
3712 compute_scroll_position(
3713 &self.display_snapshot,
3714 self.scroll_position,
3715 &self.scroll_top_anchor,
3716 )
3717 }
3718}
3719
3720impl Deref for EditorSnapshot {
3721 type Target = DisplaySnapshot;
3722
3723 fn deref(&self) -> &Self::Target {
3724 &self.display_snapshot
3725 }
3726}
3727
3728impl EditorSettings {
3729 #[cfg(any(test, feature = "test-support"))]
3730 pub fn test(cx: &AppContext) -> Self {
3731 Self {
3732 tab_size: 4,
3733 soft_wrap: SoftWrap::None,
3734 style: {
3735 let font_cache: &gpui::FontCache = cx.font_cache();
3736 let font_family_name = Arc::from("Monaco");
3737 let font_properties = Default::default();
3738 let font_family_id = font_cache.load_family(&[&font_family_name]).unwrap();
3739 let font_id = font_cache
3740 .select_font(font_family_id, &font_properties)
3741 .unwrap();
3742 EditorStyle {
3743 text: gpui::fonts::TextStyle {
3744 font_family_name,
3745 font_family_id,
3746 font_id,
3747 font_size: 14.,
3748 color: gpui::color::Color::from_u32(0xff0000ff),
3749 font_properties,
3750 underline: None,
3751 },
3752 placeholder_text: None,
3753 background: Default::default(),
3754 gutter_background: Default::default(),
3755 active_line_background: Default::default(),
3756 highlighted_line_background: Default::default(),
3757 line_number: Default::default(),
3758 line_number_active: Default::default(),
3759 selection: Default::default(),
3760 guest_selections: Default::default(),
3761 syntax: Default::default(),
3762 error_diagnostic: Default::default(),
3763 invalid_error_diagnostic: Default::default(),
3764 warning_diagnostic: Default::default(),
3765 invalid_warning_diagnostic: Default::default(),
3766 information_diagnostic: Default::default(),
3767 invalid_information_diagnostic: Default::default(),
3768 hint_diagnostic: Default::default(),
3769 invalid_hint_diagnostic: Default::default(),
3770 }
3771 },
3772 }
3773 }
3774}
3775
3776fn compute_scroll_position(
3777 snapshot: &DisplaySnapshot,
3778 mut scroll_position: Vector2F,
3779 scroll_top_anchor: &Anchor,
3780) -> Vector2F {
3781 let scroll_top = scroll_top_anchor.to_display_point(snapshot).row() as f32;
3782 scroll_position.set_y(scroll_top + scroll_position.y());
3783 scroll_position
3784}
3785
3786#[derive(Copy, Clone)]
3787pub enum Event {
3788 Activate,
3789 Edited,
3790 Blurred,
3791 Dirtied,
3792 Saved,
3793 FileHandleChanged,
3794 Closed,
3795}
3796
3797impl Entity for Editor {
3798 type Event = Event;
3799}
3800
3801impl View for Editor {
3802 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
3803 let settings = (self.build_settings)(cx);
3804 self.display_map.update(cx, |map, cx| {
3805 map.set_font(
3806 settings.style.text.font_id,
3807 settings.style.text.font_size,
3808 cx,
3809 )
3810 });
3811 EditorElement::new(self.handle.clone(), settings).boxed()
3812 }
3813
3814 fn ui_name() -> &'static str {
3815 "Editor"
3816 }
3817
3818 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
3819 self.focused = true;
3820 self.blink_cursors(self.blink_epoch, cx);
3821 self.buffer.update(cx, |buffer, cx| {
3822 buffer.set_active_selections(&self.selections, cx)
3823 });
3824 }
3825
3826 fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
3827 self.focused = false;
3828 self.show_local_cursors = false;
3829 self.buffer
3830 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
3831 cx.emit(Event::Blurred);
3832 cx.notify();
3833 }
3834
3835 fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
3836 let mut cx = Self::default_keymap_context();
3837 let mode = match self.mode {
3838 EditorMode::SingleLine => "single_line",
3839 EditorMode::AutoHeight { .. } => "auto_height",
3840 EditorMode::Full => "full",
3841 };
3842 cx.map.insert("mode".into(), mode.into());
3843 cx
3844 }
3845}
3846
3847impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
3848 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
3849 let start = self.start.to_point(buffer);
3850 let end = self.end.to_point(buffer);
3851 if self.reversed {
3852 end..start
3853 } else {
3854 start..end
3855 }
3856 }
3857
3858 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
3859 let start = self.start.to_offset(buffer);
3860 let end = self.end.to_offset(buffer);
3861 if self.reversed {
3862 end..start
3863 } else {
3864 start..end
3865 }
3866 }
3867
3868 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
3869 let start = self
3870 .start
3871 .to_point(&map.buffer_snapshot)
3872 .to_display_point(map);
3873 let end = self
3874 .end
3875 .to_point(&map.buffer_snapshot)
3876 .to_display_point(map);
3877 if self.reversed {
3878 end..start
3879 } else {
3880 start..end
3881 }
3882 }
3883
3884 fn spanned_rows(
3885 &self,
3886 include_end_if_at_line_start: bool,
3887 map: &DisplaySnapshot,
3888 ) -> SpannedRows {
3889 let display_start = self
3890 .start
3891 .to_point(&map.buffer_snapshot)
3892 .to_display_point(map);
3893 let mut display_end = self
3894 .end
3895 .to_point(&map.buffer_snapshot)
3896 .to_display_point(map);
3897 if !include_end_if_at_line_start
3898 && display_end.row() != map.max_point().row()
3899 && display_start.row() != display_end.row()
3900 && display_end.column() == 0
3901 {
3902 *display_end.row_mut() -= 1;
3903 }
3904
3905 let (display_start, buffer_start) = map.prev_row_boundary(display_start);
3906 let (display_end, buffer_end) = map.next_row_boundary(display_end);
3907
3908 SpannedRows {
3909 buffer_rows: buffer_start.row..buffer_end.row + 1,
3910 display_rows: display_start.row()..display_end.row() + 1,
3911 }
3912 }
3913}
3914
3915pub fn diagnostic_block_renderer(
3916 diagnostic: Diagnostic,
3917 is_valid: bool,
3918 build_settings: BuildSettings,
3919) -> RenderBlock {
3920 Arc::new(move |cx: &BlockContext| {
3921 let settings = build_settings(cx);
3922 let mut text_style = settings.style.text.clone();
3923 text_style.color = diagnostic_style(diagnostic.severity, is_valid, &settings.style).text;
3924 Text::new(diagnostic.message.clone(), text_style)
3925 .contained()
3926 .with_margin_left(cx.anchor_x)
3927 .boxed()
3928 })
3929}
3930
3931pub fn diagnostic_header_renderer(
3932 buffer: ModelHandle<Buffer>,
3933 diagnostic: Diagnostic,
3934 is_valid: bool,
3935 build_settings: BuildSettings,
3936) -> RenderBlock {
3937 Arc::new(move |cx| {
3938 let settings = build_settings(cx);
3939 let mut text_style = settings.style.text.clone();
3940 text_style.color = diagnostic_style(diagnostic.severity, is_valid, &settings.style).text;
3941 let file_path = if let Some(file) = buffer.read(&**cx).file() {
3942 file.path().to_string_lossy().to_string()
3943 } else {
3944 "untitled".to_string()
3945 };
3946
3947 Flex::column()
3948 .with_child(Label::new(diagnostic.message.clone(), text_style).boxed())
3949 .with_child(Label::new(file_path, settings.style.text.clone()).boxed())
3950 .boxed()
3951 })
3952}
3953
3954pub fn context_header_renderer(build_settings: BuildSettings) -> RenderBlock {
3955 Arc::new(move |cx| {
3956 let settings = build_settings(cx);
3957 let text_style = settings.style.text.clone();
3958 Label::new("...".to_string(), text_style).boxed()
3959 })
3960}
3961
3962pub fn diagnostic_style(
3963 severity: DiagnosticSeverity,
3964 valid: bool,
3965 style: &EditorStyle,
3966) -> DiagnosticStyle {
3967 match (severity, valid) {
3968 (DiagnosticSeverity::ERROR, true) => style.error_diagnostic,
3969 (DiagnosticSeverity::ERROR, false) => style.invalid_error_diagnostic,
3970 (DiagnosticSeverity::WARNING, true) => style.warning_diagnostic,
3971 (DiagnosticSeverity::WARNING, false) => style.invalid_warning_diagnostic,
3972 (DiagnosticSeverity::INFORMATION, true) => style.information_diagnostic,
3973 (DiagnosticSeverity::INFORMATION, false) => style.invalid_information_diagnostic,
3974 (DiagnosticSeverity::HINT, true) => style.hint_diagnostic,
3975 (DiagnosticSeverity::HINT, false) => style.invalid_hint_diagnostic,
3976 _ => Default::default(),
3977 }
3978}
3979
3980pub fn settings_builder(
3981 buffer: WeakModelHandle<MultiBuffer>,
3982 settings: watch::Receiver<workspace::Settings>,
3983) -> BuildSettings {
3984 Arc::new(move |cx| {
3985 let settings = settings.borrow();
3986 let font_cache = cx.font_cache();
3987 let font_family_id = settings.buffer_font_family;
3988 let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
3989 let font_properties = Default::default();
3990 let font_id = font_cache
3991 .select_font(font_family_id, &font_properties)
3992 .unwrap();
3993 let font_size = settings.buffer_font_size;
3994
3995 let mut theme = settings.theme.editor.clone();
3996 theme.text = TextStyle {
3997 color: theme.text.color,
3998 font_family_name,
3999 font_family_id,
4000 font_id,
4001 font_size,
4002 font_properties,
4003 underline: None,
4004 };
4005 let language = buffer.upgrade(cx).and_then(|buf| buf.read(cx).language(cx));
4006 let soft_wrap = match settings.soft_wrap(language) {
4007 workspace::settings::SoftWrap::None => SoftWrap::None,
4008 workspace::settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
4009 workspace::settings::SoftWrap::PreferredLineLength => {
4010 SoftWrap::Column(settings.preferred_line_length(language).saturating_sub(1))
4011 }
4012 };
4013
4014 EditorSettings {
4015 tab_size: settings.tab_size,
4016 soft_wrap,
4017 style: theme,
4018 }
4019 })
4020}
4021
4022#[cfg(test)]
4023mod tests {
4024 use super::*;
4025 use language::LanguageConfig;
4026 use std::time::Instant;
4027 use text::Point;
4028 use unindent::Unindent;
4029 use util::test::sample_text;
4030
4031 #[gpui::test]
4032 fn test_undo_redo_with_selection_restoration(cx: &mut MutableAppContext) {
4033 let mut now = Instant::now();
4034 let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
4035 let group_interval = buffer.read(cx).transaction_group_interval();
4036 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
4037 let settings = EditorSettings::test(cx);
4038 let (_, editor) = cx.add_window(Default::default(), |cx| {
4039 build_editor(buffer.clone(), settings, cx)
4040 });
4041
4042 editor.update(cx, |editor, cx| {
4043 editor.start_transaction_at(now, cx);
4044 editor.select_ranges([2..4], None, cx);
4045 editor.insert("cd", cx);
4046 editor.end_transaction_at(now, cx);
4047 assert_eq!(editor.text(cx), "12cd56");
4048 assert_eq!(editor.selected_ranges(cx), vec![4..4]);
4049
4050 editor.start_transaction_at(now, cx);
4051 editor.select_ranges([4..5], None, cx);
4052 editor.insert("e", cx);
4053 editor.end_transaction_at(now, cx);
4054 assert_eq!(editor.text(cx), "12cde6");
4055 assert_eq!(editor.selected_ranges(cx), vec![5..5]);
4056
4057 now += group_interval + Duration::from_millis(1);
4058 editor.select_ranges([2..2], None, cx);
4059
4060 // Simulate an edit in another editor
4061 buffer.update(cx, |buffer, cx| {
4062 buffer.start_transaction_at(now, cx);
4063 buffer.edit([0..1], "a", cx);
4064 buffer.edit([1..1], "b", cx);
4065 buffer.end_transaction_at(now, cx);
4066 });
4067
4068 assert_eq!(editor.text(cx), "ab2cde6");
4069 assert_eq!(editor.selected_ranges(cx), vec![3..3]);
4070
4071 // Last transaction happened past the group interval in a different editor.
4072 // Undo it individually and don't restore selections.
4073 editor.undo(&Undo, cx);
4074 assert_eq!(editor.text(cx), "12cde6");
4075 assert_eq!(editor.selected_ranges(cx), vec![2..2]);
4076
4077 // First two transactions happened within the group interval in this editor.
4078 // Undo them together and restore selections.
4079 editor.undo(&Undo, cx);
4080 editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
4081 assert_eq!(editor.text(cx), "123456");
4082 assert_eq!(editor.selected_ranges(cx), vec![0..0]);
4083
4084 // Redo the first two transactions together.
4085 editor.redo(&Redo, cx);
4086 assert_eq!(editor.text(cx), "12cde6");
4087 assert_eq!(editor.selected_ranges(cx), vec![5..5]);
4088
4089 // Redo the last transaction on its own.
4090 editor.redo(&Redo, cx);
4091 assert_eq!(editor.text(cx), "ab2cde6");
4092 assert_eq!(editor.selected_ranges(cx), vec![6..6]);
4093
4094 // Test empty transactions.
4095 editor.start_transaction_at(now, cx);
4096 editor.end_transaction_at(now, cx);
4097 editor.undo(&Undo, cx);
4098 assert_eq!(editor.text(cx), "12cde6");
4099 });
4100 }
4101
4102 #[gpui::test]
4103 fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
4104 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
4105 let settings = EditorSettings::test(cx);
4106 let (_, editor) =
4107 cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4108
4109 editor.update(cx, |view, cx| {
4110 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
4111 });
4112
4113 assert_eq!(
4114 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4115 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
4116 );
4117
4118 editor.update(cx, |view, cx| {
4119 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
4120 });
4121
4122 assert_eq!(
4123 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4124 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
4125 );
4126
4127 editor.update(cx, |view, cx| {
4128 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
4129 });
4130
4131 assert_eq!(
4132 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4133 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
4134 );
4135
4136 editor.update(cx, |view, cx| {
4137 view.end_selection(cx);
4138 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
4139 });
4140
4141 assert_eq!(
4142 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4143 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
4144 );
4145
4146 editor.update(cx, |view, cx| {
4147 view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
4148 view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
4149 });
4150
4151 assert_eq!(
4152 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4153 [
4154 DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
4155 DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
4156 ]
4157 );
4158
4159 editor.update(cx, |view, cx| {
4160 view.end_selection(cx);
4161 });
4162
4163 assert_eq!(
4164 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4165 [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
4166 );
4167 }
4168
4169 #[gpui::test]
4170 fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
4171 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
4172 let settings = EditorSettings::test(cx);
4173 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4174
4175 view.update(cx, |view, cx| {
4176 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
4177 assert_eq!(
4178 view.selected_display_ranges(cx),
4179 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
4180 );
4181 });
4182
4183 view.update(cx, |view, cx| {
4184 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
4185 assert_eq!(
4186 view.selected_display_ranges(cx),
4187 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
4188 );
4189 });
4190
4191 view.update(cx, |view, cx| {
4192 view.cancel(&Cancel, cx);
4193 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
4194 assert_eq!(
4195 view.selected_display_ranges(cx),
4196 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
4197 );
4198 });
4199 }
4200
4201 #[gpui::test]
4202 fn test_cancel(cx: &mut gpui::MutableAppContext) {
4203 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
4204 let settings = EditorSettings::test(cx);
4205 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4206
4207 view.update(cx, |view, cx| {
4208 view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
4209 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
4210 view.end_selection(cx);
4211
4212 view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
4213 view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
4214 view.end_selection(cx);
4215 assert_eq!(
4216 view.selected_display_ranges(cx),
4217 [
4218 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4219 DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
4220 ]
4221 );
4222 });
4223
4224 view.update(cx, |view, cx| {
4225 view.cancel(&Cancel, cx);
4226 assert_eq!(
4227 view.selected_display_ranges(cx),
4228 [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
4229 );
4230 });
4231
4232 view.update(cx, |view, cx| {
4233 view.cancel(&Cancel, cx);
4234 assert_eq!(
4235 view.selected_display_ranges(cx),
4236 [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
4237 );
4238 });
4239 }
4240
4241 #[gpui::test]
4242 fn test_fold(cx: &mut gpui::MutableAppContext) {
4243 let buffer = MultiBuffer::build_simple(
4244 &"
4245 impl Foo {
4246 // Hello!
4247
4248 fn a() {
4249 1
4250 }
4251
4252 fn b() {
4253 2
4254 }
4255
4256 fn c() {
4257 3
4258 }
4259 }
4260 "
4261 .unindent(),
4262 cx,
4263 );
4264 let settings = EditorSettings::test(&cx);
4265 let (_, view) = cx.add_window(Default::default(), |cx| {
4266 build_editor(buffer.clone(), settings, cx)
4267 });
4268
4269 view.update(cx, |view, cx| {
4270 view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx)
4271 .unwrap();
4272 view.fold(&Fold, cx);
4273 assert_eq!(
4274 view.display_text(cx),
4275 "
4276 impl Foo {
4277 // Hello!
4278
4279 fn a() {
4280 1
4281 }
4282
4283 fn b() {…
4284 }
4285
4286 fn c() {…
4287 }
4288 }
4289 "
4290 .unindent(),
4291 );
4292
4293 view.fold(&Fold, cx);
4294 assert_eq!(
4295 view.display_text(cx),
4296 "
4297 impl Foo {…
4298 }
4299 "
4300 .unindent(),
4301 );
4302
4303 view.unfold(&Unfold, cx);
4304 assert_eq!(
4305 view.display_text(cx),
4306 "
4307 impl Foo {
4308 // Hello!
4309
4310 fn a() {
4311 1
4312 }
4313
4314 fn b() {…
4315 }
4316
4317 fn c() {…
4318 }
4319 }
4320 "
4321 .unindent(),
4322 );
4323
4324 view.unfold(&Unfold, cx);
4325 assert_eq!(view.display_text(cx), buffer.read(cx).read(cx).text());
4326 });
4327 }
4328
4329 #[gpui::test]
4330 fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
4331 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
4332 let settings = EditorSettings::test(&cx);
4333 let (_, view) = cx.add_window(Default::default(), |cx| {
4334 build_editor(buffer.clone(), settings, cx)
4335 });
4336
4337 buffer.update(cx, |buffer, cx| {
4338 buffer.edit(
4339 vec![
4340 Point::new(1, 0)..Point::new(1, 0),
4341 Point::new(1, 1)..Point::new(1, 1),
4342 ],
4343 "\t",
4344 cx,
4345 );
4346 });
4347
4348 view.update(cx, |view, cx| {
4349 assert_eq!(
4350 view.selected_display_ranges(cx),
4351 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4352 );
4353
4354 view.move_down(&MoveDown, cx);
4355 assert_eq!(
4356 view.selected_display_ranges(cx),
4357 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
4358 );
4359
4360 view.move_right(&MoveRight, cx);
4361 assert_eq!(
4362 view.selected_display_ranges(cx),
4363 &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
4364 );
4365
4366 view.move_left(&MoveLeft, cx);
4367 assert_eq!(
4368 view.selected_display_ranges(cx),
4369 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
4370 );
4371
4372 view.move_up(&MoveUp, cx);
4373 assert_eq!(
4374 view.selected_display_ranges(cx),
4375 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4376 );
4377
4378 view.move_to_end(&MoveToEnd, cx);
4379 assert_eq!(
4380 view.selected_display_ranges(cx),
4381 &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
4382 );
4383
4384 view.move_to_beginning(&MoveToBeginning, cx);
4385 assert_eq!(
4386 view.selected_display_ranges(cx),
4387 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4388 );
4389
4390 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx)
4391 .unwrap();
4392 view.select_to_beginning(&SelectToBeginning, cx);
4393 assert_eq!(
4394 view.selected_display_ranges(cx),
4395 &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
4396 );
4397
4398 view.select_to_end(&SelectToEnd, cx);
4399 assert_eq!(
4400 view.selected_display_ranges(cx),
4401 &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
4402 );
4403 });
4404 }
4405
4406 #[gpui::test]
4407 fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
4408 let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
4409 let settings = EditorSettings::test(&cx);
4410 let (_, view) = cx.add_window(Default::default(), |cx| {
4411 build_editor(buffer.clone(), settings, cx)
4412 });
4413
4414 assert_eq!('ⓐ'.len_utf8(), 3);
4415 assert_eq!('α'.len_utf8(), 2);
4416
4417 view.update(cx, |view, cx| {
4418 view.fold_ranges(
4419 vec![
4420 Point::new(0, 6)..Point::new(0, 12),
4421 Point::new(1, 2)..Point::new(1, 4),
4422 Point::new(2, 4)..Point::new(2, 8),
4423 ],
4424 cx,
4425 );
4426 assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
4427
4428 view.move_right(&MoveRight, cx);
4429 assert_eq!(
4430 view.selected_display_ranges(cx),
4431 &[empty_range(0, "ⓐ".len())]
4432 );
4433 view.move_right(&MoveRight, cx);
4434 assert_eq!(
4435 view.selected_display_ranges(cx),
4436 &[empty_range(0, "ⓐⓑ".len())]
4437 );
4438 view.move_right(&MoveRight, cx);
4439 assert_eq!(
4440 view.selected_display_ranges(cx),
4441 &[empty_range(0, "ⓐⓑ…".len())]
4442 );
4443
4444 view.move_down(&MoveDown, cx);
4445 assert_eq!(
4446 view.selected_display_ranges(cx),
4447 &[empty_range(1, "ab…".len())]
4448 );
4449 view.move_left(&MoveLeft, cx);
4450 assert_eq!(
4451 view.selected_display_ranges(cx),
4452 &[empty_range(1, "ab".len())]
4453 );
4454 view.move_left(&MoveLeft, cx);
4455 assert_eq!(
4456 view.selected_display_ranges(cx),
4457 &[empty_range(1, "a".len())]
4458 );
4459
4460 view.move_down(&MoveDown, cx);
4461 assert_eq!(
4462 view.selected_display_ranges(cx),
4463 &[empty_range(2, "α".len())]
4464 );
4465 view.move_right(&MoveRight, cx);
4466 assert_eq!(
4467 view.selected_display_ranges(cx),
4468 &[empty_range(2, "αβ".len())]
4469 );
4470 view.move_right(&MoveRight, cx);
4471 assert_eq!(
4472 view.selected_display_ranges(cx),
4473 &[empty_range(2, "αβ…".len())]
4474 );
4475 view.move_right(&MoveRight, cx);
4476 assert_eq!(
4477 view.selected_display_ranges(cx),
4478 &[empty_range(2, "αβ…ε".len())]
4479 );
4480
4481 view.move_up(&MoveUp, cx);
4482 assert_eq!(
4483 view.selected_display_ranges(cx),
4484 &[empty_range(1, "ab…e".len())]
4485 );
4486 view.move_up(&MoveUp, cx);
4487 assert_eq!(
4488 view.selected_display_ranges(cx),
4489 &[empty_range(0, "ⓐⓑ…ⓔ".len())]
4490 );
4491 view.move_left(&MoveLeft, cx);
4492 assert_eq!(
4493 view.selected_display_ranges(cx),
4494 &[empty_range(0, "ⓐⓑ…".len())]
4495 );
4496 view.move_left(&MoveLeft, cx);
4497 assert_eq!(
4498 view.selected_display_ranges(cx),
4499 &[empty_range(0, "ⓐⓑ".len())]
4500 );
4501 view.move_left(&MoveLeft, cx);
4502 assert_eq!(
4503 view.selected_display_ranges(cx),
4504 &[empty_range(0, "ⓐ".len())]
4505 );
4506 });
4507 }
4508
4509 #[gpui::test]
4510 fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
4511 let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
4512 let settings = EditorSettings::test(&cx);
4513 let (_, view) = cx.add_window(Default::default(), |cx| {
4514 build_editor(buffer.clone(), settings, cx)
4515 });
4516 view.update(cx, |view, cx| {
4517 view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx)
4518 .unwrap();
4519
4520 view.move_down(&MoveDown, cx);
4521 assert_eq!(
4522 view.selected_display_ranges(cx),
4523 &[empty_range(1, "abcd".len())]
4524 );
4525
4526 view.move_down(&MoveDown, cx);
4527 assert_eq!(
4528 view.selected_display_ranges(cx),
4529 &[empty_range(2, "αβγ".len())]
4530 );
4531
4532 view.move_down(&MoveDown, cx);
4533 assert_eq!(
4534 view.selected_display_ranges(cx),
4535 &[empty_range(3, "abcd".len())]
4536 );
4537
4538 view.move_down(&MoveDown, cx);
4539 assert_eq!(
4540 view.selected_display_ranges(cx),
4541 &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
4542 );
4543
4544 view.move_up(&MoveUp, cx);
4545 assert_eq!(
4546 view.selected_display_ranges(cx),
4547 &[empty_range(3, "abcd".len())]
4548 );
4549
4550 view.move_up(&MoveUp, cx);
4551 assert_eq!(
4552 view.selected_display_ranges(cx),
4553 &[empty_range(2, "αβγ".len())]
4554 );
4555 });
4556 }
4557
4558 #[gpui::test]
4559 fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
4560 let buffer = MultiBuffer::build_simple("abc\n def", cx);
4561 let settings = EditorSettings::test(&cx);
4562 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4563 view.update(cx, |view, cx| {
4564 view.select_display_ranges(
4565 &[
4566 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4567 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4568 ],
4569 cx,
4570 )
4571 .unwrap();
4572 });
4573
4574 view.update(cx, |view, cx| {
4575 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4576 assert_eq!(
4577 view.selected_display_ranges(cx),
4578 &[
4579 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4580 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4581 ]
4582 );
4583 });
4584
4585 view.update(cx, |view, cx| {
4586 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4587 assert_eq!(
4588 view.selected_display_ranges(cx),
4589 &[
4590 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4591 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4592 ]
4593 );
4594 });
4595
4596 view.update(cx, |view, cx| {
4597 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4598 assert_eq!(
4599 view.selected_display_ranges(cx),
4600 &[
4601 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4602 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4603 ]
4604 );
4605 });
4606
4607 view.update(cx, |view, cx| {
4608 view.move_to_end_of_line(&MoveToEndOfLine, cx);
4609 assert_eq!(
4610 view.selected_display_ranges(cx),
4611 &[
4612 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4613 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4614 ]
4615 );
4616 });
4617
4618 // Moving to the end of line again is a no-op.
4619 view.update(cx, |view, cx| {
4620 view.move_to_end_of_line(&MoveToEndOfLine, cx);
4621 assert_eq!(
4622 view.selected_display_ranges(cx),
4623 &[
4624 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4625 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4626 ]
4627 );
4628 });
4629
4630 view.update(cx, |view, cx| {
4631 view.move_left(&MoveLeft, cx);
4632 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4633 assert_eq!(
4634 view.selected_display_ranges(cx),
4635 &[
4636 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4637 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4638 ]
4639 );
4640 });
4641
4642 view.update(cx, |view, cx| {
4643 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4644 assert_eq!(
4645 view.selected_display_ranges(cx),
4646 &[
4647 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4648 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
4649 ]
4650 );
4651 });
4652
4653 view.update(cx, |view, cx| {
4654 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4655 assert_eq!(
4656 view.selected_display_ranges(cx),
4657 &[
4658 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4659 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4660 ]
4661 );
4662 });
4663
4664 view.update(cx, |view, cx| {
4665 view.select_to_end_of_line(&SelectToEndOfLine, cx);
4666 assert_eq!(
4667 view.selected_display_ranges(cx),
4668 &[
4669 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
4670 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
4671 ]
4672 );
4673 });
4674
4675 view.update(cx, |view, cx| {
4676 view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
4677 assert_eq!(view.display_text(cx), "ab\n de");
4678 assert_eq!(
4679 view.selected_display_ranges(cx),
4680 &[
4681 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4682 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4683 ]
4684 );
4685 });
4686
4687 view.update(cx, |view, cx| {
4688 view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
4689 assert_eq!(view.display_text(cx), "\n");
4690 assert_eq!(
4691 view.selected_display_ranges(cx),
4692 &[
4693 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4694 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4695 ]
4696 );
4697 });
4698 }
4699
4700 #[gpui::test]
4701 fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
4702 let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n {baz.qux()}", cx);
4703 let settings = EditorSettings::test(&cx);
4704 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4705 view.update(cx, |view, cx| {
4706 view.select_display_ranges(
4707 &[
4708 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
4709 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
4710 ],
4711 cx,
4712 )
4713 .unwrap();
4714 });
4715
4716 view.update(cx, |view, cx| {
4717 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4718 assert_eq!(
4719 view.selected_display_ranges(cx),
4720 &[
4721 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4722 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4723 ]
4724 );
4725 });
4726
4727 view.update(cx, |view, cx| {
4728 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4729 assert_eq!(
4730 view.selected_display_ranges(cx),
4731 &[
4732 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4733 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
4734 ]
4735 );
4736 });
4737
4738 view.update(cx, |view, cx| {
4739 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4740 assert_eq!(
4741 view.selected_display_ranges(cx),
4742 &[
4743 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
4744 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
4745 ]
4746 );
4747 });
4748
4749 view.update(cx, |view, cx| {
4750 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4751 assert_eq!(
4752 view.selected_display_ranges(cx),
4753 &[
4754 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4755 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4756 ]
4757 );
4758 });
4759
4760 view.update(cx, |view, cx| {
4761 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4762 assert_eq!(
4763 view.selected_display_ranges(cx),
4764 &[
4765 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4766 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
4767 ]
4768 );
4769 });
4770
4771 view.update(cx, |view, cx| {
4772 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4773 assert_eq!(
4774 view.selected_display_ranges(cx),
4775 &[
4776 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4777 DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
4778 ]
4779 );
4780 });
4781
4782 view.update(cx, |view, cx| {
4783 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4784 assert_eq!(
4785 view.selected_display_ranges(cx),
4786 &[
4787 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4788 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4789 ]
4790 );
4791 });
4792
4793 view.update(cx, |view, cx| {
4794 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4795 assert_eq!(
4796 view.selected_display_ranges(cx),
4797 &[
4798 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4799 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4800 ]
4801 );
4802 });
4803
4804 view.update(cx, |view, cx| {
4805 view.move_right(&MoveRight, cx);
4806 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4807 assert_eq!(
4808 view.selected_display_ranges(cx),
4809 &[
4810 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4811 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4812 ]
4813 );
4814 });
4815
4816 view.update(cx, |view, cx| {
4817 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4818 assert_eq!(
4819 view.selected_display_ranges(cx),
4820 &[
4821 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
4822 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
4823 ]
4824 );
4825 });
4826
4827 view.update(cx, |view, cx| {
4828 view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
4829 assert_eq!(
4830 view.selected_display_ranges(cx),
4831 &[
4832 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4833 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4834 ]
4835 );
4836 });
4837 }
4838
4839 #[gpui::test]
4840 fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
4841 let buffer = MultiBuffer::build_simple("use one::{\n two::three::four::five\n};", cx);
4842 let settings = EditorSettings::test(&cx);
4843 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4844
4845 view.update(cx, |view, cx| {
4846 view.set_wrap_width(Some(140.), cx);
4847 assert_eq!(
4848 view.display_text(cx),
4849 "use one::{\n two::three::\n four::five\n};"
4850 );
4851
4852 view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx)
4853 .unwrap();
4854
4855 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4856 assert_eq!(
4857 view.selected_display_ranges(cx),
4858 &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
4859 );
4860
4861 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4862 assert_eq!(
4863 view.selected_display_ranges(cx),
4864 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
4865 );
4866
4867 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4868 assert_eq!(
4869 view.selected_display_ranges(cx),
4870 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
4871 );
4872
4873 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4874 assert_eq!(
4875 view.selected_display_ranges(cx),
4876 &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
4877 );
4878
4879 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4880 assert_eq!(
4881 view.selected_display_ranges(cx),
4882 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
4883 );
4884
4885 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4886 assert_eq!(
4887 view.selected_display_ranges(cx),
4888 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
4889 );
4890 });
4891 }
4892
4893 #[gpui::test]
4894 fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
4895 let buffer = MultiBuffer::build_simple("one two three four", cx);
4896 let settings = EditorSettings::test(&cx);
4897 let (_, view) = cx.add_window(Default::default(), |cx| {
4898 build_editor(buffer.clone(), settings, cx)
4899 });
4900
4901 view.update(cx, |view, cx| {
4902 view.select_display_ranges(
4903 &[
4904 // an empty selection - the preceding word fragment is deleted
4905 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4906 // characters selected - they are deleted
4907 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
4908 ],
4909 cx,
4910 )
4911 .unwrap();
4912 view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
4913 });
4914
4915 assert_eq!(buffer.read(cx).read(cx).text(), "e two te four");
4916
4917 view.update(cx, |view, cx| {
4918 view.select_display_ranges(
4919 &[
4920 // an empty selection - the following word fragment is deleted
4921 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4922 // characters selected - they are deleted
4923 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
4924 ],
4925 cx,
4926 )
4927 .unwrap();
4928 view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
4929 });
4930
4931 assert_eq!(buffer.read(cx).read(cx).text(), "e t te our");
4932 }
4933
4934 #[gpui::test]
4935 fn test_newline(cx: &mut gpui::MutableAppContext) {
4936 let buffer = MultiBuffer::build_simple("aaaa\n bbbb\n", cx);
4937 let settings = EditorSettings::test(&cx);
4938 let (_, view) = cx.add_window(Default::default(), |cx| {
4939 build_editor(buffer.clone(), settings, cx)
4940 });
4941
4942 view.update(cx, |view, cx| {
4943 view.select_display_ranges(
4944 &[
4945 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4946 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4947 DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
4948 ],
4949 cx,
4950 )
4951 .unwrap();
4952
4953 view.newline(&Newline, cx);
4954 assert_eq!(view.text(cx), "aa\naa\n \n bb\n bb\n");
4955 });
4956 }
4957
4958 #[gpui::test]
4959 fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
4960 let buffer = MultiBuffer::build_simple(" one two\nthree\n four", cx);
4961 let settings = EditorSettings::test(&cx);
4962 let (_, view) = cx.add_window(Default::default(), |cx| {
4963 build_editor(buffer.clone(), settings, cx)
4964 });
4965
4966 view.update(cx, |view, cx| {
4967 // two selections on the same line
4968 view.select_display_ranges(
4969 &[
4970 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
4971 DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
4972 ],
4973 cx,
4974 )
4975 .unwrap();
4976
4977 // indent from mid-tabstop to full tabstop
4978 view.tab(&Tab, cx);
4979 assert_eq!(view.text(cx), " one two\nthree\n four");
4980 assert_eq!(
4981 view.selected_display_ranges(cx),
4982 &[
4983 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
4984 DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
4985 ]
4986 );
4987
4988 // outdent from 1 tabstop to 0 tabstops
4989 view.outdent(&Outdent, cx);
4990 assert_eq!(view.text(cx), "one two\nthree\n four");
4991 assert_eq!(
4992 view.selected_display_ranges(cx),
4993 &[
4994 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
4995 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
4996 ]
4997 );
4998
4999 // select across line ending
5000 view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx)
5001 .unwrap();
5002
5003 // indent and outdent affect only the preceding line
5004 view.tab(&Tab, cx);
5005 assert_eq!(view.text(cx), "one two\n three\n four");
5006 assert_eq!(
5007 view.selected_display_ranges(cx),
5008 &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
5009 );
5010 view.outdent(&Outdent, cx);
5011 assert_eq!(view.text(cx), "one two\nthree\n four");
5012 assert_eq!(
5013 view.selected_display_ranges(cx),
5014 &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
5015 );
5016 });
5017 }
5018
5019 #[gpui::test]
5020 fn test_backspace(cx: &mut gpui::MutableAppContext) {
5021 let buffer =
5022 MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
5023 let settings = EditorSettings::test(&cx);
5024 let (_, view) = cx.add_window(Default::default(), |cx| {
5025 build_editor(buffer.clone(), settings, cx)
5026 });
5027
5028 view.update(cx, |view, cx| {
5029 view.select_display_ranges(
5030 &[
5031 // an empty selection - the preceding character is deleted
5032 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5033 // one character selected - it is deleted
5034 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5035 // a line suffix selected - it is deleted
5036 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
5037 ],
5038 cx,
5039 )
5040 .unwrap();
5041 view.backspace(&Backspace, cx);
5042 });
5043
5044 assert_eq!(
5045 buffer.read(cx).read(cx).text(),
5046 "oe two three\nfou five six\nseven ten\n"
5047 );
5048 }
5049
5050 #[gpui::test]
5051 fn test_delete(cx: &mut gpui::MutableAppContext) {
5052 let buffer =
5053 MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
5054 let settings = EditorSettings::test(&cx);
5055 let (_, view) = cx.add_window(Default::default(), |cx| {
5056 build_editor(buffer.clone(), settings, cx)
5057 });
5058
5059 view.update(cx, |view, cx| {
5060 view.select_display_ranges(
5061 &[
5062 // an empty selection - the following character is deleted
5063 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5064 // one character selected - it is deleted
5065 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5066 // a line suffix selected - it is deleted
5067 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
5068 ],
5069 cx,
5070 )
5071 .unwrap();
5072 view.delete(&Delete, cx);
5073 });
5074
5075 assert_eq!(
5076 buffer.read(cx).read(cx).text(),
5077 "on two three\nfou five six\nseven ten\n"
5078 );
5079 }
5080
5081 #[gpui::test]
5082 fn test_delete_line(cx: &mut gpui::MutableAppContext) {
5083 let settings = EditorSettings::test(&cx);
5084 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5085 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5086 view.update(cx, |view, cx| {
5087 view.select_display_ranges(
5088 &[
5089 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5090 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
5091 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5092 ],
5093 cx,
5094 )
5095 .unwrap();
5096 view.delete_line(&DeleteLine, cx);
5097 assert_eq!(view.display_text(cx), "ghi");
5098 assert_eq!(
5099 view.selected_display_ranges(cx),
5100 vec![
5101 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
5102 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
5103 ]
5104 );
5105 });
5106
5107 let settings = EditorSettings::test(&cx);
5108 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5109 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5110 view.update(cx, |view, cx| {
5111 view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx)
5112 .unwrap();
5113 view.delete_line(&DeleteLine, cx);
5114 assert_eq!(view.display_text(cx), "ghi\n");
5115 assert_eq!(
5116 view.selected_display_ranges(cx),
5117 vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
5118 );
5119 });
5120 }
5121
5122 #[gpui::test]
5123 fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
5124 let settings = EditorSettings::test(&cx);
5125 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5126 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5127 view.update(cx, |view, cx| {
5128 view.select_display_ranges(
5129 &[
5130 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5131 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5132 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5133 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5134 ],
5135 cx,
5136 )
5137 .unwrap();
5138 view.duplicate_line(&DuplicateLine, cx);
5139 assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
5140 assert_eq!(
5141 view.selected_display_ranges(cx),
5142 vec![
5143 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
5144 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
5145 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5146 DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
5147 ]
5148 );
5149 });
5150
5151 let settings = EditorSettings::test(&cx);
5152 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5153 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5154 view.update(cx, |view, cx| {
5155 view.select_display_ranges(
5156 &[
5157 DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
5158 DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
5159 ],
5160 cx,
5161 )
5162 .unwrap();
5163 view.duplicate_line(&DuplicateLine, cx);
5164 assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
5165 assert_eq!(
5166 view.selected_display_ranges(cx),
5167 vec![
5168 DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
5169 DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
5170 ]
5171 );
5172 });
5173 }
5174
5175 #[gpui::test]
5176 fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
5177 let settings = EditorSettings::test(&cx);
5178 let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
5179 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5180 view.update(cx, |view, cx| {
5181 view.fold_ranges(
5182 vec![
5183 Point::new(0, 2)..Point::new(1, 2),
5184 Point::new(2, 3)..Point::new(4, 1),
5185 Point::new(7, 0)..Point::new(8, 4),
5186 ],
5187 cx,
5188 );
5189 view.select_display_ranges(
5190 &[
5191 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5192 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5193 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5194 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
5195 ],
5196 cx,
5197 )
5198 .unwrap();
5199 assert_eq!(
5200 view.display_text(cx),
5201 "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
5202 );
5203
5204 view.move_line_up(&MoveLineUp, cx);
5205 assert_eq!(
5206 view.display_text(cx),
5207 "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
5208 );
5209 assert_eq!(
5210 view.selected_display_ranges(cx),
5211 vec![
5212 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5213 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5214 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
5215 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
5216 ]
5217 );
5218 });
5219
5220 view.update(cx, |view, cx| {
5221 view.move_line_down(&MoveLineDown, cx);
5222 assert_eq!(
5223 view.display_text(cx),
5224 "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
5225 );
5226 assert_eq!(
5227 view.selected_display_ranges(cx),
5228 vec![
5229 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5230 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5231 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5232 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
5233 ]
5234 );
5235 });
5236
5237 view.update(cx, |view, cx| {
5238 view.move_line_down(&MoveLineDown, cx);
5239 assert_eq!(
5240 view.display_text(cx),
5241 "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
5242 );
5243 assert_eq!(
5244 view.selected_display_ranges(cx),
5245 vec![
5246 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5247 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5248 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5249 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
5250 ]
5251 );
5252 });
5253
5254 view.update(cx, |view, cx| {
5255 view.move_line_up(&MoveLineUp, cx);
5256 assert_eq!(
5257 view.display_text(cx),
5258 "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
5259 );
5260 assert_eq!(
5261 view.selected_display_ranges(cx),
5262 vec![
5263 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5264 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5265 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
5266 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
5267 ]
5268 );
5269 });
5270 }
5271
5272 #[gpui::test]
5273 fn test_clipboard(cx: &mut gpui::MutableAppContext) {
5274 let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
5275 let settings = EditorSettings::test(&cx);
5276 let view = cx
5277 .add_window(Default::default(), |cx| {
5278 build_editor(buffer.clone(), settings, cx)
5279 })
5280 .1;
5281
5282 // Cut with three selections. Clipboard text is divided into three slices.
5283 view.update(cx, |view, cx| {
5284 view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
5285 view.cut(&Cut, cx);
5286 assert_eq!(view.display_text(cx), "two four six ");
5287 });
5288
5289 // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
5290 view.update(cx, |view, cx| {
5291 view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
5292 view.paste(&Paste, cx);
5293 assert_eq!(view.display_text(cx), "two one✅ four three six five ");
5294 assert_eq!(
5295 view.selected_display_ranges(cx),
5296 &[
5297 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
5298 DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
5299 DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
5300 ]
5301 );
5302 });
5303
5304 // Paste again but with only two cursors. Since the number of cursors doesn't
5305 // match the number of slices in the clipboard, the entire clipboard text
5306 // is pasted at each cursor.
5307 view.update(cx, |view, cx| {
5308 view.select_ranges(vec![0..0, 31..31], None, cx);
5309 view.handle_input(&Input("( ".into()), cx);
5310 view.paste(&Paste, cx);
5311 view.handle_input(&Input(") ".into()), cx);
5312 assert_eq!(
5313 view.display_text(cx),
5314 "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5315 );
5316 });
5317
5318 view.update(cx, |view, cx| {
5319 view.select_ranges(vec![0..0], None, cx);
5320 view.handle_input(&Input("123\n4567\n89\n".into()), cx);
5321 assert_eq!(
5322 view.display_text(cx),
5323 "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5324 );
5325 });
5326
5327 // Cut with three selections, one of which is full-line.
5328 view.update(cx, |view, cx| {
5329 view.select_display_ranges(
5330 &[
5331 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
5332 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5333 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
5334 ],
5335 cx,
5336 )
5337 .unwrap();
5338 view.cut(&Cut, cx);
5339 assert_eq!(
5340 view.display_text(cx),
5341 "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5342 );
5343 });
5344
5345 // Paste with three selections, noticing how the copied selection that was full-line
5346 // gets inserted before the second cursor.
5347 view.update(cx, |view, cx| {
5348 view.select_display_ranges(
5349 &[
5350 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5351 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5352 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
5353 ],
5354 cx,
5355 )
5356 .unwrap();
5357 view.paste(&Paste, cx);
5358 assert_eq!(
5359 view.display_text(cx),
5360 "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
5361 );
5362 assert_eq!(
5363 view.selected_display_ranges(cx),
5364 &[
5365 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5366 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5367 DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
5368 ]
5369 );
5370 });
5371
5372 // Copy with a single cursor only, which writes the whole line into the clipboard.
5373 view.update(cx, |view, cx| {
5374 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx)
5375 .unwrap();
5376 view.copy(&Copy, cx);
5377 });
5378
5379 // Paste with three selections, noticing how the copied full-line selection is inserted
5380 // before the empty selections but replaces the selection that is non-empty.
5381 view.update(cx, |view, cx| {
5382 view.select_display_ranges(
5383 &[
5384 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5385 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
5386 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5387 ],
5388 cx,
5389 )
5390 .unwrap();
5391 view.paste(&Paste, cx);
5392 assert_eq!(
5393 view.display_text(cx),
5394 "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
5395 );
5396 assert_eq!(
5397 view.selected_display_ranges(cx),
5398 &[
5399 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5400 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5401 DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
5402 ]
5403 );
5404 });
5405 }
5406
5407 #[gpui::test]
5408 fn test_select_all(cx: &mut gpui::MutableAppContext) {
5409 let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
5410 let settings = EditorSettings::test(&cx);
5411 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5412 view.update(cx, |view, cx| {
5413 view.select_all(&SelectAll, cx);
5414 assert_eq!(
5415 view.selected_display_ranges(cx),
5416 &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
5417 );
5418 });
5419 }
5420
5421 #[gpui::test]
5422 fn test_select_line(cx: &mut gpui::MutableAppContext) {
5423 let settings = EditorSettings::test(&cx);
5424 let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
5425 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5426 view.update(cx, |view, cx| {
5427 view.select_display_ranges(
5428 &[
5429 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5430 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5431 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5432 DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
5433 ],
5434 cx,
5435 )
5436 .unwrap();
5437 view.select_line(&SelectLine, cx);
5438 assert_eq!(
5439 view.selected_display_ranges(cx),
5440 vec![
5441 DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
5442 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
5443 ]
5444 );
5445 });
5446
5447 view.update(cx, |view, cx| {
5448 view.select_line(&SelectLine, cx);
5449 assert_eq!(
5450 view.selected_display_ranges(cx),
5451 vec![
5452 DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
5453 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
5454 ]
5455 );
5456 });
5457
5458 view.update(cx, |view, cx| {
5459 view.select_line(&SelectLine, cx);
5460 assert_eq!(
5461 view.selected_display_ranges(cx),
5462 vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
5463 );
5464 });
5465 }
5466
5467 #[gpui::test]
5468 fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
5469 let settings = EditorSettings::test(&cx);
5470 let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
5471 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5472 view.update(cx, |view, cx| {
5473 view.fold_ranges(
5474 vec![
5475 Point::new(0, 2)..Point::new(1, 2),
5476 Point::new(2, 3)..Point::new(4, 1),
5477 Point::new(7, 0)..Point::new(8, 4),
5478 ],
5479 cx,
5480 );
5481 view.select_display_ranges(
5482 &[
5483 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5484 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5485 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5486 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
5487 ],
5488 cx,
5489 )
5490 .unwrap();
5491 assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
5492 });
5493
5494 view.update(cx, |view, cx| {
5495 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5496 assert_eq!(
5497 view.display_text(cx),
5498 "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
5499 );
5500 assert_eq!(
5501 view.selected_display_ranges(cx),
5502 [
5503 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5504 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5505 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
5506 DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
5507 ]
5508 );
5509 });
5510
5511 view.update(cx, |view, cx| {
5512 view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx)
5513 .unwrap();
5514 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5515 assert_eq!(
5516 view.display_text(cx),
5517 "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
5518 );
5519 assert_eq!(
5520 view.selected_display_ranges(cx),
5521 [
5522 DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
5523 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
5524 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
5525 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
5526 DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
5527 DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
5528 DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
5529 DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
5530 ]
5531 );
5532 });
5533 }
5534
5535 #[gpui::test]
5536 fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
5537 let settings = EditorSettings::test(&cx);
5538 let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
5539 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5540
5541 view.update(cx, |view, cx| {
5542 view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx)
5543 .unwrap();
5544 });
5545 view.update(cx, |view, cx| {
5546 view.add_selection_above(&AddSelectionAbove, cx);
5547 assert_eq!(
5548 view.selected_display_ranges(cx),
5549 vec![
5550 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5551 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5552 ]
5553 );
5554 });
5555
5556 view.update(cx, |view, cx| {
5557 view.add_selection_above(&AddSelectionAbove, cx);
5558 assert_eq!(
5559 view.selected_display_ranges(cx),
5560 vec![
5561 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5562 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5563 ]
5564 );
5565 });
5566
5567 view.update(cx, |view, cx| {
5568 view.add_selection_below(&AddSelectionBelow, cx);
5569 assert_eq!(
5570 view.selected_display_ranges(cx),
5571 vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
5572 );
5573 });
5574
5575 view.update(cx, |view, cx| {
5576 view.add_selection_below(&AddSelectionBelow, cx);
5577 assert_eq!(
5578 view.selected_display_ranges(cx),
5579 vec![
5580 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5581 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5582 ]
5583 );
5584 });
5585
5586 view.update(cx, |view, cx| {
5587 view.add_selection_below(&AddSelectionBelow, cx);
5588 assert_eq!(
5589 view.selected_display_ranges(cx),
5590 vec![
5591 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5592 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5593 ]
5594 );
5595 });
5596
5597 view.update(cx, |view, cx| {
5598 view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx)
5599 .unwrap();
5600 });
5601 view.update(cx, |view, cx| {
5602 view.add_selection_below(&AddSelectionBelow, cx);
5603 assert_eq!(
5604 view.selected_display_ranges(cx),
5605 vec![
5606 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5607 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5608 ]
5609 );
5610 });
5611
5612 view.update(cx, |view, cx| {
5613 view.add_selection_below(&AddSelectionBelow, cx);
5614 assert_eq!(
5615 view.selected_display_ranges(cx),
5616 vec![
5617 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5618 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5619 ]
5620 );
5621 });
5622
5623 view.update(cx, |view, cx| {
5624 view.add_selection_above(&AddSelectionAbove, cx);
5625 assert_eq!(
5626 view.selected_display_ranges(cx),
5627 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5628 );
5629 });
5630
5631 view.update(cx, |view, cx| {
5632 view.add_selection_above(&AddSelectionAbove, cx);
5633 assert_eq!(
5634 view.selected_display_ranges(cx),
5635 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5636 );
5637 });
5638
5639 view.update(cx, |view, cx| {
5640 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx)
5641 .unwrap();
5642 view.add_selection_below(&AddSelectionBelow, cx);
5643 assert_eq!(
5644 view.selected_display_ranges(cx),
5645 vec![
5646 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5647 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5648 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5649 ]
5650 );
5651 });
5652
5653 view.update(cx, |view, cx| {
5654 view.add_selection_below(&AddSelectionBelow, cx);
5655 assert_eq!(
5656 view.selected_display_ranges(cx),
5657 vec![
5658 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5659 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5660 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5661 DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
5662 ]
5663 );
5664 });
5665
5666 view.update(cx, |view, cx| {
5667 view.add_selection_above(&AddSelectionAbove, cx);
5668 assert_eq!(
5669 view.selected_display_ranges(cx),
5670 vec![
5671 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5672 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5673 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5674 ]
5675 );
5676 });
5677
5678 view.update(cx, |view, cx| {
5679 view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx)
5680 .unwrap();
5681 });
5682 view.update(cx, |view, cx| {
5683 view.add_selection_above(&AddSelectionAbove, cx);
5684 assert_eq!(
5685 view.selected_display_ranges(cx),
5686 vec![
5687 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
5688 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5689 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5690 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5691 ]
5692 );
5693 });
5694
5695 view.update(cx, |view, cx| {
5696 view.add_selection_below(&AddSelectionBelow, cx);
5697 assert_eq!(
5698 view.selected_display_ranges(cx),
5699 vec![
5700 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5701 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5702 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5703 ]
5704 );
5705 });
5706 }
5707
5708 #[gpui::test]
5709 async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
5710 let settings = cx.read(EditorSettings::test);
5711 let language = Some(Arc::new(Language::new(
5712 LanguageConfig::default(),
5713 Some(tree_sitter_rust::language()),
5714 )));
5715
5716 let text = r#"
5717 use mod1::mod2::{mod3, mod4};
5718
5719 fn fn_1(param1: bool, param2: &str) {
5720 let var1 = "text";
5721 }
5722 "#
5723 .unindent();
5724
5725 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5726 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5727 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5728 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5729 .await;
5730
5731 view.update(&mut cx, |view, cx| {
5732 view.select_display_ranges(
5733 &[
5734 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5735 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5736 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5737 ],
5738 cx,
5739 )
5740 .unwrap();
5741 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5742 });
5743 assert_eq!(
5744 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5745 &[
5746 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5747 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5748 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5749 ]
5750 );
5751
5752 view.update(&mut cx, |view, cx| {
5753 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5754 });
5755 assert_eq!(
5756 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5757 &[
5758 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5759 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5760 ]
5761 );
5762
5763 view.update(&mut cx, |view, cx| {
5764 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5765 });
5766 assert_eq!(
5767 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5768 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5769 );
5770
5771 // Trying to expand the selected syntax node one more time has no effect.
5772 view.update(&mut cx, |view, cx| {
5773 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5774 });
5775 assert_eq!(
5776 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5777 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5778 );
5779
5780 view.update(&mut cx, |view, cx| {
5781 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5782 });
5783 assert_eq!(
5784 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5785 &[
5786 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5787 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5788 ]
5789 );
5790
5791 view.update(&mut cx, |view, cx| {
5792 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5793 });
5794 assert_eq!(
5795 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5796 &[
5797 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5798 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5799 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5800 ]
5801 );
5802
5803 view.update(&mut cx, |view, cx| {
5804 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5805 });
5806 assert_eq!(
5807 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5808 &[
5809 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5810 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5811 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5812 ]
5813 );
5814
5815 // Trying to shrink the selected syntax node one more time has no effect.
5816 view.update(&mut cx, |view, cx| {
5817 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5818 });
5819 assert_eq!(
5820 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5821 &[
5822 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5823 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5824 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5825 ]
5826 );
5827
5828 // Ensure that we keep expanding the selection if the larger selection starts or ends within
5829 // a fold.
5830 view.update(&mut cx, |view, cx| {
5831 view.fold_ranges(
5832 vec![
5833 Point::new(0, 21)..Point::new(0, 24),
5834 Point::new(3, 20)..Point::new(3, 22),
5835 ],
5836 cx,
5837 );
5838 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5839 });
5840 assert_eq!(
5841 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5842 &[
5843 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5844 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5845 DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
5846 ]
5847 );
5848 }
5849
5850 #[gpui::test]
5851 async fn test_autoindent_selections(mut cx: gpui::TestAppContext) {
5852 let settings = cx.read(EditorSettings::test);
5853 let language = Some(Arc::new(
5854 Language::new(
5855 LanguageConfig {
5856 brackets: vec![
5857 BracketPair {
5858 start: "{".to_string(),
5859 end: "}".to_string(),
5860 close: false,
5861 newline: true,
5862 },
5863 BracketPair {
5864 start: "(".to_string(),
5865 end: ")".to_string(),
5866 close: false,
5867 newline: true,
5868 },
5869 ],
5870 ..Default::default()
5871 },
5872 Some(tree_sitter_rust::language()),
5873 )
5874 .with_indents_query(
5875 r#"
5876 (_ "(" ")" @end) @indent
5877 (_ "{" "}" @end) @indent
5878 "#,
5879 )
5880 .unwrap(),
5881 ));
5882
5883 let text = "fn a() {}";
5884
5885 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5886 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5887 let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5888 editor
5889 .condition(&cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
5890 .await;
5891
5892 editor.update(&mut cx, |editor, cx| {
5893 editor.select_ranges([5..5, 8..8, 9..9], None, cx);
5894 editor.newline(&Newline, cx);
5895 assert_eq!(editor.text(cx), "fn a(\n \n) {\n \n}\n");
5896 assert_eq!(
5897 editor.selected_ranges(cx),
5898 &[
5899 Point::new(1, 4)..Point::new(1, 4),
5900 Point::new(3, 4)..Point::new(3, 4),
5901 Point::new(5, 0)..Point::new(5, 0)
5902 ]
5903 );
5904 });
5905 }
5906
5907 #[gpui::test]
5908 async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
5909 let settings = cx.read(EditorSettings::test);
5910 let language = Some(Arc::new(Language::new(
5911 LanguageConfig {
5912 brackets: vec![
5913 BracketPair {
5914 start: "{".to_string(),
5915 end: "}".to_string(),
5916 close: true,
5917 newline: true,
5918 },
5919 BracketPair {
5920 start: "/*".to_string(),
5921 end: " */".to_string(),
5922 close: true,
5923 newline: true,
5924 },
5925 ],
5926 ..Default::default()
5927 },
5928 Some(tree_sitter_rust::language()),
5929 )));
5930
5931 let text = r#"
5932 a
5933
5934 /
5935
5936 "#
5937 .unindent();
5938
5939 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5940 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5941 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5942 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5943 .await;
5944
5945 view.update(&mut cx, |view, cx| {
5946 view.select_display_ranges(
5947 &[
5948 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5949 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5950 ],
5951 cx,
5952 )
5953 .unwrap();
5954 view.handle_input(&Input("{".to_string()), cx);
5955 view.handle_input(&Input("{".to_string()), cx);
5956 view.handle_input(&Input("{".to_string()), cx);
5957 assert_eq!(
5958 view.text(cx),
5959 "
5960 {{{}}}
5961 {{{}}}
5962 /
5963
5964 "
5965 .unindent()
5966 );
5967
5968 view.move_right(&MoveRight, cx);
5969 view.handle_input(&Input("}".to_string()), cx);
5970 view.handle_input(&Input("}".to_string()), cx);
5971 view.handle_input(&Input("}".to_string()), cx);
5972 assert_eq!(
5973 view.text(cx),
5974 "
5975 {{{}}}}
5976 {{{}}}}
5977 /
5978
5979 "
5980 .unindent()
5981 );
5982
5983 view.undo(&Undo, cx);
5984 view.handle_input(&Input("/".to_string()), cx);
5985 view.handle_input(&Input("*".to_string()), cx);
5986 assert_eq!(
5987 view.text(cx),
5988 "
5989 /* */
5990 /* */
5991 /
5992
5993 "
5994 .unindent()
5995 );
5996
5997 view.undo(&Undo, cx);
5998 view.select_display_ranges(
5999 &[
6000 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
6001 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
6002 ],
6003 cx,
6004 )
6005 .unwrap();
6006 view.handle_input(&Input("*".to_string()), cx);
6007 assert_eq!(
6008 view.text(cx),
6009 "
6010 a
6011
6012 /*
6013 *
6014 "
6015 .unindent()
6016 );
6017 });
6018 }
6019
6020 #[gpui::test]
6021 async fn test_toggle_comment(mut cx: gpui::TestAppContext) {
6022 let settings = cx.read(EditorSettings::test);
6023 let language = Some(Arc::new(Language::new(
6024 LanguageConfig {
6025 line_comment: Some("// ".to_string()),
6026 ..Default::default()
6027 },
6028 Some(tree_sitter_rust::language()),
6029 )));
6030
6031 let text = "
6032 fn a() {
6033 //b();
6034 // c();
6035 // d();
6036 }
6037 "
6038 .unindent();
6039
6040 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
6041 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6042 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
6043
6044 view.update(&mut cx, |editor, cx| {
6045 // If multiple selections intersect a line, the line is only
6046 // toggled once.
6047 editor
6048 .select_display_ranges(
6049 &[
6050 DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
6051 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
6052 ],
6053 cx,
6054 )
6055 .unwrap();
6056 editor.toggle_comments(&ToggleComments, cx);
6057 assert_eq!(
6058 editor.text(cx),
6059 "
6060 fn a() {
6061 b();
6062 c();
6063 d();
6064 }
6065 "
6066 .unindent()
6067 );
6068
6069 // The comment prefix is inserted at the same column for every line
6070 // in a selection.
6071 editor
6072 .select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx)
6073 .unwrap();
6074 editor.toggle_comments(&ToggleComments, cx);
6075 assert_eq!(
6076 editor.text(cx),
6077 "
6078 fn a() {
6079 // b();
6080 // c();
6081 // d();
6082 }
6083 "
6084 .unindent()
6085 );
6086
6087 // If a selection ends at the beginning of a line, that line is not toggled.
6088 editor
6089 .select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx)
6090 .unwrap();
6091 editor.toggle_comments(&ToggleComments, cx);
6092 assert_eq!(
6093 editor.text(cx),
6094 "
6095 fn a() {
6096 // b();
6097 c();
6098 // d();
6099 }
6100 "
6101 .unindent()
6102 );
6103 });
6104 }
6105
6106 #[gpui::test]
6107 fn test_editing_disjoint_excerpts(cx: &mut gpui::MutableAppContext) {
6108 let settings = EditorSettings::test(cx);
6109 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
6110 let multibuffer = cx.add_model(|cx| {
6111 let mut multibuffer = MultiBuffer::new(0);
6112 multibuffer.push_excerpt(
6113 ExcerptProperties {
6114 buffer: &buffer,
6115 range: Point::new(0, 0)..Point::new(0, 4),
6116 },
6117 cx,
6118 );
6119 multibuffer.push_excerpt(
6120 ExcerptProperties {
6121 buffer: &buffer,
6122 range: Point::new(1, 0)..Point::new(1, 4),
6123 },
6124 cx,
6125 );
6126 multibuffer
6127 });
6128
6129 assert_eq!(multibuffer.read(cx).read(cx).text(), "aaaa\nbbbb");
6130
6131 let (_, view) = cx.add_window(Default::default(), |cx| {
6132 build_editor(multibuffer, settings, cx)
6133 });
6134 view.update(cx, |view, cx| {
6135 view.select_display_ranges(
6136 &[
6137 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6138 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6139 ],
6140 cx,
6141 )
6142 .unwrap();
6143
6144 view.handle_input(&Input("X".to_string()), cx);
6145 assert_eq!(view.text(cx), "Xaaaa\nXbbbb");
6146 assert_eq!(
6147 view.selected_display_ranges(cx),
6148 &[
6149 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6150 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6151 ]
6152 )
6153 });
6154 }
6155
6156 #[gpui::test]
6157 fn test_editing_overlapping_excerpts(cx: &mut gpui::MutableAppContext) {
6158 let settings = EditorSettings::test(cx);
6159 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
6160 let multibuffer = cx.add_model(|cx| {
6161 let mut multibuffer = MultiBuffer::new(0);
6162 multibuffer.push_excerpt(
6163 ExcerptProperties {
6164 buffer: &buffer,
6165 range: Point::new(0, 0)..Point::new(1, 4),
6166 },
6167 cx,
6168 );
6169 multibuffer.push_excerpt(
6170 ExcerptProperties {
6171 buffer: &buffer,
6172 range: Point::new(1, 0)..Point::new(2, 4),
6173 },
6174 cx,
6175 );
6176 multibuffer
6177 });
6178
6179 assert_eq!(
6180 multibuffer.read(cx).read(cx).text(),
6181 "aaaa\nbbbb\nbbbb\ncccc"
6182 );
6183
6184 let (_, view) = cx.add_window(Default::default(), |cx| {
6185 build_editor(multibuffer, settings, cx)
6186 });
6187 view.update(cx, |view, cx| {
6188 view.select_display_ranges(
6189 &[
6190 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6191 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
6192 ],
6193 cx,
6194 )
6195 .unwrap();
6196
6197 view.handle_input(&Input("X".to_string()), cx);
6198 assert_eq!(view.text(cx), "aaaa\nbXbbXb\nbXbbXb\ncccc");
6199 assert_eq!(
6200 view.selected_display_ranges(cx),
6201 &[
6202 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6203 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
6204 ]
6205 )
6206 });
6207 }
6208
6209 #[gpui::test]
6210 async fn test_extra_newline_insertion(mut cx: gpui::TestAppContext) {
6211 let settings = cx.read(EditorSettings::test);
6212 let language = Some(Arc::new(Language::new(
6213 LanguageConfig {
6214 brackets: vec![
6215 BracketPair {
6216 start: "{".to_string(),
6217 end: "}".to_string(),
6218 close: true,
6219 newline: true,
6220 },
6221 BracketPair {
6222 start: "/* ".to_string(),
6223 end: " */".to_string(),
6224 close: true,
6225 newline: true,
6226 },
6227 ],
6228 ..Default::default()
6229 },
6230 Some(tree_sitter_rust::language()),
6231 )));
6232
6233 let text = concat!(
6234 "{ }\n", // Suppress rustfmt
6235 " x\n", //
6236 " /* */\n", //
6237 "x\n", //
6238 "{{} }\n", //
6239 );
6240
6241 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
6242 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6243 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
6244 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
6245 .await;
6246
6247 view.update(&mut cx, |view, cx| {
6248 view.select_display_ranges(
6249 &[
6250 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
6251 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
6252 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
6253 ],
6254 cx,
6255 )
6256 .unwrap();
6257 view.newline(&Newline, cx);
6258
6259 assert_eq!(
6260 view.buffer().read(cx).read(cx).text(),
6261 concat!(
6262 "{ \n", // Suppress rustfmt
6263 "\n", //
6264 "}\n", //
6265 " x\n", //
6266 " /* \n", //
6267 " \n", //
6268 " */\n", //
6269 "x\n", //
6270 "{{} \n", //
6271 "}\n", //
6272 )
6273 );
6274 });
6275 }
6276
6277 impl Editor {
6278 fn selected_ranges<D: TextDimension + Ord + Sub<D, Output = D>>(
6279 &self,
6280 cx: &mut MutableAppContext,
6281 ) -> Vec<Range<D>> {
6282 self.local_selections::<D>(cx)
6283 .iter()
6284 .map(|s| {
6285 if s.reversed {
6286 s.end.clone()..s.start.clone()
6287 } else {
6288 s.start.clone()..s.end.clone()
6289 }
6290 })
6291 .collect()
6292 }
6293
6294 fn selected_display_ranges(&self, cx: &mut MutableAppContext) -> Vec<Range<DisplayPoint>> {
6295 let display_map = self
6296 .display_map
6297 .update(cx, |display_map, cx| display_map.snapshot(cx));
6298 self.selections
6299 .iter()
6300 .chain(
6301 self.pending_selection
6302 .as_ref()
6303 .map(|pending| &pending.selection),
6304 )
6305 .map(|s| {
6306 if s.reversed {
6307 s.end.to_display_point(&display_map)..s.start.to_display_point(&display_map)
6308 } else {
6309 s.start.to_display_point(&display_map)..s.end.to_display_point(&display_map)
6310 }
6311 })
6312 .collect()
6313 }
6314 }
6315
6316 fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
6317 let point = DisplayPoint::new(row as u32, column as u32);
6318 point..point
6319 }
6320
6321 fn build_editor(
6322 buffer: ModelHandle<MultiBuffer>,
6323 settings: EditorSettings,
6324 cx: &mut ViewContext<Editor>,
6325 ) -> Editor {
6326 Editor::for_buffer(buffer, Arc::new(move |_| settings.clone()), cx)
6327 }
6328}
6329
6330trait RangeExt<T> {
6331 fn sorted(&self) -> Range<T>;
6332 fn to_inclusive(&self) -> RangeInclusive<T>;
6333}
6334
6335impl<T: Ord + Clone> RangeExt<T> for Range<T> {
6336 fn sorted(&self) -> Self {
6337 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
6338 }
6339
6340 fn to_inclusive(&self) -> RangeInclusive<T> {
6341 self.start.clone()..=self.end.clone()
6342 }
6343}