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