1pub mod buffer;
2pub mod display_map;
3mod element;
4pub mod movement;
5
6use crate::{
7 settings::{HighlightId, Settings},
8 theme::{EditorStyle, Theme},
9 time::ReplicaId,
10 util::{post_inc, Bias},
11 workspace,
12 worktree::{File, Worktree},
13};
14use anyhow::Result;
15pub use buffer::*;
16pub use display_map::DisplayPoint;
17use display_map::*;
18pub use element::*;
19use gpui::{
20 action, color::Color, font_cache::FamilyId, fonts::Properties as FontProperties,
21 geometry::vector::Vector2F, keymap::Binding, text_layout, AppContext, ClipboardItem, Element,
22 ElementBox, Entity, FontCache, ModelHandle, MutableAppContext, RenderContext, Task,
23 TextLayoutCache, View, ViewContext, WeakViewHandle,
24};
25use postage::watch;
26use serde::{Deserialize, Serialize};
27use smallvec::SmallVec;
28use smol::Timer;
29use std::{
30 cell::RefCell,
31 cmp::{self, Ordering},
32 collections::BTreeMap,
33 fmt::Write,
34 iter::FromIterator,
35 mem,
36 ops::{Range, RangeInclusive},
37 path::Path,
38 rc::Rc,
39 sync::Arc,
40 time::Duration,
41};
42
43const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
44const MAX_LINE_LEN: usize = 1024;
45
46action!(Cancel);
47action!(Backspace);
48action!(Delete);
49action!(Newline);
50action!(Insert, String);
51action!(DeleteLine);
52action!(DeleteToPreviousWordBoundary);
53action!(DeleteToNextWordBoundary);
54action!(DeleteToBeginningOfLine);
55action!(DeleteToEndOfLine);
56action!(CutToEndOfLine);
57action!(DuplicateLine);
58action!(MoveLineUp);
59action!(MoveLineDown);
60action!(Cut);
61action!(Copy);
62action!(Paste);
63action!(Undo);
64action!(Redo);
65action!(MoveUp);
66action!(MoveDown);
67action!(MoveLeft);
68action!(MoveRight);
69action!(MoveToPreviousWordBoundary);
70action!(MoveToNextWordBoundary);
71action!(MoveToBeginningOfLine);
72action!(MoveToEndOfLine);
73action!(MoveToBeginning);
74action!(MoveToEnd);
75action!(SelectUp);
76action!(SelectDown);
77action!(SelectLeft);
78action!(SelectRight);
79action!(SelectToPreviousWordBoundary);
80action!(SelectToNextWordBoundary);
81action!(SelectToBeginningOfLine, bool);
82action!(SelectToEndOfLine);
83action!(SelectToBeginning);
84action!(SelectToEnd);
85action!(SelectAll);
86action!(SelectLine);
87action!(SplitSelectionIntoLines);
88action!(AddSelectionAbove);
89action!(AddSelectionBelow);
90action!(SelectLargerSyntaxNode);
91action!(SelectSmallerSyntaxNode);
92action!(MoveToEnclosingBracket);
93action!(PageUp);
94action!(PageDown);
95action!(Fold);
96action!(Unfold);
97action!(FoldSelectedRanges);
98action!(Scroll, Vector2F);
99action!(Select, SelectPhase);
100
101pub fn init(cx: &mut MutableAppContext) {
102 cx.add_bindings(vec![
103 Binding::new("escape", Cancel, Some("Editor")),
104 Binding::new("backspace", Backspace, Some("Editor")),
105 Binding::new("ctrl-h", Backspace, Some("Editor")),
106 Binding::new("delete", Delete, Some("Editor")),
107 Binding::new("ctrl-d", Delete, Some("Editor")),
108 Binding::new("enter", Newline, Some("Editor && mode == full")),
109 Binding::new("alt-enter", Newline, Some("Editor && mode == auto_height")),
110 Binding::new("tab", Insert("\t".into()), Some("Editor")),
111 Binding::new("ctrl-shift-K", DeleteLine, Some("Editor")),
112 Binding::new(
113 "alt-backspace",
114 DeleteToPreviousWordBoundary,
115 Some("Editor"),
116 ),
117 Binding::new("alt-h", DeleteToPreviousWordBoundary, Some("Editor")),
118 Binding::new("alt-delete", DeleteToNextWordBoundary, Some("Editor")),
119 Binding::new("alt-d", DeleteToNextWordBoundary, Some("Editor")),
120 Binding::new("cmd-backspace", DeleteToBeginningOfLine, Some("Editor")),
121 Binding::new("cmd-delete", DeleteToEndOfLine, Some("Editor")),
122 Binding::new("ctrl-k", CutToEndOfLine, Some("Editor")),
123 Binding::new("cmd-shift-D", DuplicateLine, Some("Editor")),
124 Binding::new("ctrl-cmd-up", MoveLineUp, Some("Editor")),
125 Binding::new("ctrl-cmd-down", MoveLineDown, Some("Editor")),
126 Binding::new("cmd-x", Cut, Some("Editor")),
127 Binding::new("cmd-c", Copy, Some("Editor")),
128 Binding::new("cmd-v", Paste, Some("Editor")),
129 Binding::new("cmd-z", Undo, Some("Editor")),
130 Binding::new("cmd-shift-Z", Redo, Some("Editor")),
131 Binding::new("up", MoveUp, Some("Editor")),
132 Binding::new("down", MoveDown, Some("Editor")),
133 Binding::new("left", MoveLeft, Some("Editor")),
134 Binding::new("right", MoveRight, Some("Editor")),
135 Binding::new("ctrl-p", MoveUp, Some("Editor")),
136 Binding::new("ctrl-n", MoveDown, Some("Editor")),
137 Binding::new("ctrl-b", MoveLeft, Some("Editor")),
138 Binding::new("ctrl-f", MoveRight, Some("Editor")),
139 Binding::new("alt-left", MoveToPreviousWordBoundary, Some("Editor")),
140 Binding::new("alt-b", MoveToPreviousWordBoundary, Some("Editor")),
141 Binding::new("alt-right", MoveToNextWordBoundary, Some("Editor")),
142 Binding::new("alt-f", MoveToNextWordBoundary, Some("Editor")),
143 Binding::new("cmd-left", MoveToBeginningOfLine, Some("Editor")),
144 Binding::new("ctrl-a", MoveToBeginningOfLine, Some("Editor")),
145 Binding::new("cmd-right", MoveToEndOfLine, Some("Editor")),
146 Binding::new("ctrl-e", MoveToEndOfLine, Some("Editor")),
147 Binding::new("cmd-up", MoveToBeginning, Some("Editor")),
148 Binding::new("cmd-down", MoveToEnd, Some("Editor")),
149 Binding::new("shift-up", SelectUp, Some("Editor")),
150 Binding::new("ctrl-shift-P", SelectUp, Some("Editor")),
151 Binding::new("shift-down", SelectDown, Some("Editor")),
152 Binding::new("ctrl-shift-N", SelectDown, Some("Editor")),
153 Binding::new("shift-left", SelectLeft, Some("Editor")),
154 Binding::new("ctrl-shift-B", SelectLeft, Some("Editor")),
155 Binding::new("shift-right", SelectRight, Some("Editor")),
156 Binding::new("ctrl-shift-F", SelectRight, Some("Editor")),
157 Binding::new(
158 "alt-shift-left",
159 SelectToPreviousWordBoundary,
160 Some("Editor"),
161 ),
162 Binding::new("alt-shift-B", SelectToPreviousWordBoundary, Some("Editor")),
163 Binding::new("alt-shift-right", SelectToNextWordBoundary, Some("Editor")),
164 Binding::new("alt-shift-F", SelectToNextWordBoundary, Some("Editor")),
165 Binding::new(
166 "cmd-shift-left",
167 SelectToBeginningOfLine(true),
168 Some("Editor"),
169 ),
170 Binding::new(
171 "ctrl-shift-A",
172 SelectToBeginningOfLine(true),
173 Some("Editor"),
174 ),
175 Binding::new("cmd-shift-right", SelectToEndOfLine, Some("Editor")),
176 Binding::new("ctrl-shift-E", SelectToEndOfLine, Some("Editor")),
177 Binding::new("cmd-shift-up", SelectToBeginning, Some("Editor")),
178 Binding::new("cmd-shift-down", SelectToEnd, Some("Editor")),
179 Binding::new("cmd-a", SelectAll, Some("Editor")),
180 Binding::new("cmd-l", SelectLine, Some("Editor")),
181 Binding::new("cmd-shift-L", SplitSelectionIntoLines, Some("Editor")),
182 Binding::new("cmd-alt-up", AddSelectionAbove, Some("Editor")),
183 Binding::new("cmd-ctrl-p", AddSelectionAbove, Some("Editor")),
184 Binding::new("cmd-alt-down", AddSelectionBelow, Some("Editor")),
185 Binding::new("cmd-ctrl-n", AddSelectionBelow, Some("Editor")),
186 Binding::new("alt-up", SelectLargerSyntaxNode, Some("Editor")),
187 Binding::new("ctrl-w", SelectLargerSyntaxNode, Some("Editor")),
188 Binding::new("alt-down", SelectSmallerSyntaxNode, Some("Editor")),
189 Binding::new("ctrl-shift-W", SelectSmallerSyntaxNode, Some("Editor")),
190 Binding::new("ctrl-m", MoveToEnclosingBracket, Some("Editor")),
191 Binding::new("pageup", PageUp, Some("Editor")),
192 Binding::new("pagedown", PageDown, Some("Editor")),
193 Binding::new("alt-cmd-[", Fold, Some("Editor")),
194 Binding::new("alt-cmd-]", Unfold, Some("Editor")),
195 Binding::new("alt-cmd-f", FoldSelectedRanges, Some("Editor")),
196 ]);
197
198 cx.add_action(|this: &mut Editor, action: &Scroll, cx| this.set_scroll_position(action.0, cx));
199 cx.add_action(Editor::select);
200 cx.add_action(Editor::cancel);
201 cx.add_action(Editor::insert);
202 cx.add_action(Editor::newline);
203 cx.add_action(Editor::backspace);
204 cx.add_action(Editor::delete);
205 cx.add_action(Editor::delete_line);
206 cx.add_action(Editor::delete_to_previous_word_boundary);
207 cx.add_action(Editor::delete_to_next_word_boundary);
208 cx.add_action(Editor::delete_to_beginning_of_line);
209 cx.add_action(Editor::delete_to_end_of_line);
210 cx.add_action(Editor::cut_to_end_of_line);
211 cx.add_action(Editor::duplicate_line);
212 cx.add_action(Editor::move_line_up);
213 cx.add_action(Editor::move_line_down);
214 cx.add_action(Editor::cut);
215 cx.add_action(Editor::copy);
216 cx.add_action(Editor::paste);
217 cx.add_action(Editor::undo);
218 cx.add_action(Editor::redo);
219 cx.add_action(Editor::move_up);
220 cx.add_action(Editor::move_down);
221 cx.add_action(Editor::move_left);
222 cx.add_action(Editor::move_right);
223 cx.add_action(Editor::move_to_previous_word_boundary);
224 cx.add_action(Editor::move_to_next_word_boundary);
225 cx.add_action(Editor::move_to_beginning_of_line);
226 cx.add_action(Editor::move_to_end_of_line);
227 cx.add_action(Editor::move_to_beginning);
228 cx.add_action(Editor::move_to_end);
229 cx.add_action(Editor::select_up);
230 cx.add_action(Editor::select_down);
231 cx.add_action(Editor::select_left);
232 cx.add_action(Editor::select_right);
233 cx.add_action(Editor::select_to_previous_word_boundary);
234 cx.add_action(Editor::select_to_next_word_boundary);
235 cx.add_action(Editor::select_to_beginning_of_line);
236 cx.add_action(Editor::select_to_end_of_line);
237 cx.add_action(Editor::select_to_beginning);
238 cx.add_action(Editor::select_to_end);
239 cx.add_action(Editor::select_all);
240 cx.add_action(Editor::select_line);
241 cx.add_action(Editor::split_selection_into_lines);
242 cx.add_action(Editor::add_selection_above);
243 cx.add_action(Editor::add_selection_below);
244 cx.add_action(Editor::select_larger_syntax_node);
245 cx.add_action(Editor::select_smaller_syntax_node);
246 cx.add_action(Editor::move_to_enclosing_bracket);
247 cx.add_action(Editor::page_up);
248 cx.add_action(Editor::page_down);
249 cx.add_action(Editor::fold);
250 cx.add_action(Editor::unfold);
251 cx.add_action(Editor::fold_selected_ranges);
252}
253
254#[derive(Clone, Debug)]
255pub enum SelectPhase {
256 Begin {
257 position: DisplayPoint,
258 add: bool,
259 },
260 Update {
261 position: DisplayPoint,
262 scroll_position: Vector2F,
263 },
264 End,
265}
266
267#[derive(Copy, Clone, PartialEq, Eq)]
268pub enum EditorMode {
269 SingleLine,
270 AutoHeight { max_lines: usize },
271 Full,
272}
273
274pub struct Editor {
275 handle: WeakViewHandle<Self>,
276 buffer: ModelHandle<Buffer>,
277 display_map: ModelHandle<DisplayMap>,
278 selection_set_id: SelectionSetId,
279 pending_selection: Option<Selection>,
280 next_selection_id: usize,
281 add_selections_state: Option<AddSelectionsState>,
282 select_larger_syntax_node_stack: Vec<Vec<Selection>>,
283 scroll_position: Vector2F,
284 scroll_top_anchor: Anchor,
285 autoscroll_requested: bool,
286 build_style: Option<Rc<RefCell<dyn FnMut(&mut MutableAppContext) -> EditorStyle>>>,
287 settings: watch::Receiver<Settings>,
288 focused: bool,
289 cursors_visible: bool,
290 blink_epoch: usize,
291 blinking_paused: bool,
292 mode: EditorMode,
293 placeholder_text: Option<Arc<str>>,
294}
295
296pub struct Snapshot {
297 pub mode: EditorMode,
298 pub display_snapshot: DisplayMapSnapshot,
299 pub placeholder_text: Option<Arc<str>>,
300 pub theme: Arc<Theme>,
301 pub font_family: FamilyId,
302 pub font_size: f32,
303 is_focused: bool,
304 scroll_position: Vector2F,
305 scroll_top_anchor: Anchor,
306}
307
308struct AddSelectionsState {
309 above: bool,
310 stack: Vec<usize>,
311}
312
313#[derive(Serialize, Deserialize)]
314struct ClipboardSelection {
315 len: usize,
316 is_entire_line: bool,
317}
318
319impl Editor {
320 pub fn single_line(settings: watch::Receiver<Settings>, cx: &mut ViewContext<Self>) -> Self {
321 let buffer = cx.add_model(|cx| Buffer::new(0, String::new(), cx));
322 let mut view = Self::for_buffer(buffer, settings, cx);
323 view.mode = EditorMode::SingleLine;
324 view
325 }
326
327 pub fn auto_height(
328 max_lines: usize,
329 settings: watch::Receiver<Settings>,
330 cx: &mut ViewContext<Self>,
331 ) -> Self {
332 let buffer = cx.add_model(|cx| Buffer::new(0, String::new(), cx));
333 let mut view = Self::for_buffer(buffer, settings, cx);
334 view.mode = EditorMode::AutoHeight { max_lines };
335 view
336 }
337
338 pub fn for_buffer(
339 buffer: ModelHandle<Buffer>,
340 settings: watch::Receiver<Settings>,
341 cx: &mut ViewContext<Self>,
342 ) -> Self {
343 let display_map =
344 cx.add_model(|cx| DisplayMap::new(buffer.clone(), settings.borrow().clone(), None, cx));
345 cx.observe(&buffer, Self::on_buffer_changed).detach();
346 cx.subscribe(&buffer, Self::on_buffer_event).detach();
347 cx.observe(&display_map, Self::on_display_map_changed)
348 .detach();
349
350 let mut next_selection_id = 0;
351 let selection_set_id = buffer.update(cx, |buffer, cx| {
352 buffer.add_selection_set(
353 vec![Selection {
354 id: post_inc(&mut next_selection_id),
355 start: buffer.anchor_before(0),
356 end: buffer.anchor_before(0),
357 reversed: false,
358 goal: SelectionGoal::None,
359 }],
360 cx,
361 )
362 });
363 Self {
364 handle: cx.handle().downgrade(),
365 buffer,
366 display_map,
367 selection_set_id,
368 pending_selection: None,
369 next_selection_id,
370 add_selections_state: None,
371 select_larger_syntax_node_stack: Vec::new(),
372 build_style: None,
373 scroll_position: Vector2F::zero(),
374 scroll_top_anchor: Anchor::min(),
375 autoscroll_requested: false,
376 settings,
377 focused: false,
378 cursors_visible: false,
379 blink_epoch: 0,
380 blinking_paused: false,
381 mode: EditorMode::Full,
382 placeholder_text: None,
383 }
384 }
385
386 pub fn with_style(
387 mut self,
388 f: impl 'static + FnMut(&mut MutableAppContext) -> EditorStyle,
389 ) -> Self {
390 self.build_style = Some(Rc::new(RefCell::new(f)));
391 self
392 }
393
394 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
395 self.buffer.read(cx).replica_id()
396 }
397
398 pub fn buffer(&self) -> &ModelHandle<Buffer> {
399 &self.buffer
400 }
401
402 pub fn snapshot(&mut self, cx: &mut MutableAppContext) -> Snapshot {
403 let settings = self.settings.borrow();
404
405 Snapshot {
406 mode: self.mode,
407 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
408 scroll_position: self.scroll_position,
409 scroll_top_anchor: self.scroll_top_anchor.clone(),
410 theme: settings.theme.clone(),
411 placeholder_text: self.placeholder_text.clone(),
412 font_family: settings.buffer_font_family,
413 font_size: settings.buffer_font_size,
414 is_focused: self
415 .handle
416 .upgrade(cx)
417 .map_or(false, |handle| handle.is_focused(cx)),
418 }
419 }
420
421 pub fn set_placeholder_text(
422 &mut self,
423 placeholder_text: impl Into<Arc<str>>,
424 cx: &mut ViewContext<Self>,
425 ) {
426 self.placeholder_text = Some(placeholder_text.into());
427 cx.notify();
428 }
429
430 fn set_scroll_position(&mut self, mut scroll_position: Vector2F, cx: &mut ViewContext<Self>) {
431 let map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
432 let scroll_top_buffer_offset =
433 DisplayPoint::new(scroll_position.y() as u32, 0).to_buffer_offset(&map, Bias::Right);
434 self.scroll_top_anchor = self
435 .buffer
436 .read(cx)
437 .anchor_at(scroll_top_buffer_offset, Bias::Right);
438 scroll_position.set_y(scroll_position.y().fract());
439 self.scroll_position = scroll_position;
440 cx.notify();
441 }
442
443 pub fn clamp_scroll_left(&mut self, max: f32) -> bool {
444 if max < self.scroll_position.x() {
445 self.scroll_position.set_x(max);
446 true
447 } else {
448 false
449 }
450 }
451
452 pub fn autoscroll_vertically(
453 &mut self,
454 viewport_height: f32,
455 line_height: f32,
456 cx: &mut ViewContext<Self>,
457 ) -> bool {
458 let visible_lines = viewport_height / line_height;
459 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
460 let mut scroll_position =
461 compute_scroll_position(&display_map, self.scroll_position, &self.scroll_top_anchor);
462 let max_scroll_top = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
463 (display_map.max_point().row() as f32 - visible_lines + 1.).max(0.)
464 } else {
465 display_map.max_point().row().saturating_sub(1) as f32
466 };
467 if scroll_position.y() > max_scroll_top {
468 scroll_position.set_y(max_scroll_top);
469 self.set_scroll_position(scroll_position, cx);
470 }
471
472 if self.autoscroll_requested {
473 self.autoscroll_requested = false;
474 } else {
475 return false;
476 }
477
478 let first_cursor_top = self
479 .selections(cx)
480 .first()
481 .unwrap()
482 .head()
483 .to_display_point(&display_map, Bias::Left)
484 .row() as f32;
485 let last_cursor_bottom = self
486 .selections(cx)
487 .last()
488 .unwrap()
489 .head()
490 .to_display_point(&display_map, Bias::Right)
491 .row() as f32
492 + 1.0;
493
494 let margin = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
495 0.
496 } else {
497 ((visible_lines - (last_cursor_bottom - first_cursor_top)) / 2.0)
498 .floor()
499 .min(3.0)
500 };
501 if margin < 0.0 {
502 return false;
503 }
504
505 let target_top = (first_cursor_top - margin).max(0.0);
506 let target_bottom = last_cursor_bottom + margin;
507 let start_row = scroll_position.y();
508 let end_row = start_row + visible_lines;
509
510 if target_top < start_row {
511 scroll_position.set_y(target_top);
512 self.set_scroll_position(scroll_position, cx);
513 } else if target_bottom >= end_row {
514 scroll_position.set_y(target_bottom - visible_lines);
515 self.set_scroll_position(scroll_position, cx);
516 }
517
518 true
519 }
520
521 pub fn autoscroll_horizontally(
522 &mut self,
523 start_row: u32,
524 viewport_width: f32,
525 scroll_width: f32,
526 max_glyph_width: f32,
527 layouts: &[text_layout::Line],
528 cx: &mut MutableAppContext,
529 ) -> bool {
530 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
531 let mut target_left = std::f32::INFINITY;
532 let mut target_right = 0.0_f32;
533 for selection in self.selections(cx) {
534 let head = selection.head().to_display_point(&display_map, Bias::Left);
535 let start_column = head.column().saturating_sub(3);
536 let end_column = cmp::min(display_map.line_len(head.row()), head.column() + 3);
537 target_left = target_left
538 .min(layouts[(head.row() - start_row) as usize].x_for_index(start_column as usize));
539 target_right = target_right.max(
540 layouts[(head.row() - start_row) as usize].x_for_index(end_column as usize)
541 + max_glyph_width,
542 );
543 }
544 target_right = target_right.min(scroll_width);
545
546 if target_right - target_left > viewport_width {
547 return false;
548 }
549
550 let scroll_left = self.scroll_position.x() * max_glyph_width;
551 let scroll_right = scroll_left + viewport_width;
552
553 if target_left < scroll_left {
554 self.scroll_position.set_x(target_left / max_glyph_width);
555 true
556 } else if target_right > scroll_right {
557 self.scroll_position
558 .set_x((target_right - viewport_width) / max_glyph_width);
559 true
560 } else {
561 false
562 }
563 }
564
565 fn select(&mut self, Select(phase): &Select, cx: &mut ViewContext<Self>) {
566 match phase {
567 SelectPhase::Begin { position, add } => self.begin_selection(*position, *add, cx),
568 SelectPhase::Update {
569 position,
570 scroll_position,
571 } => self.update_selection(*position, *scroll_position, cx),
572 SelectPhase::End => self.end_selection(cx),
573 }
574 }
575
576 fn begin_selection(&mut self, position: DisplayPoint, add: bool, cx: &mut ViewContext<Self>) {
577 if !self.focused {
578 cx.focus_self();
579 cx.emit(Event::Activate);
580 }
581
582 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
583 let cursor = display_map.anchor_before(position, Bias::Left);
584 let selection = Selection {
585 id: post_inc(&mut self.next_selection_id),
586 start: cursor.clone(),
587 end: cursor,
588 reversed: false,
589 goal: SelectionGoal::None,
590 };
591
592 if !add {
593 self.update_selections(Vec::new(), false, cx);
594 }
595 self.pending_selection = Some(selection);
596
597 cx.notify();
598 }
599
600 fn update_selection(
601 &mut self,
602 position: DisplayPoint,
603 scroll_position: Vector2F,
604 cx: &mut ViewContext<Self>,
605 ) {
606 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
607 let buffer = self.buffer.read(cx);
608 let cursor = display_map.anchor_before(position, Bias::Left);
609 if let Some(selection) = self.pending_selection.as_mut() {
610 selection.set_head(buffer, cursor);
611 } else {
612 log::error!("update_selection dispatched with no pending selection");
613 return;
614 }
615
616 self.set_scroll_position(scroll_position, cx);
617 cx.notify();
618 }
619
620 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
621 if let Some(selection) = self.pending_selection.take() {
622 let mut selections = self.selections(cx.as_ref()).to_vec();
623 let ix = self.selection_insertion_index(&selections, &selection.start, cx.as_ref());
624 selections.insert(ix, selection);
625 self.update_selections(selections, false, cx);
626 } else {
627 log::error!("end_selection dispatched with no pending selection");
628 }
629 }
630
631 pub fn is_selecting(&self) -> bool {
632 self.pending_selection.is_some()
633 }
634
635 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
636 let selections = self.selections(cx.as_ref());
637 if let Some(pending_selection) = self.pending_selection.take() {
638 if selections.is_empty() {
639 self.update_selections(vec![pending_selection], true, cx);
640 }
641 } else {
642 let mut oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
643 if selections.len() == 1 {
644 oldest_selection.start = oldest_selection.head().clone();
645 oldest_selection.end = oldest_selection.head().clone();
646 }
647 self.update_selections(vec![oldest_selection], true, cx);
648 }
649 }
650
651 fn select_ranges<I, T>(&mut self, ranges: I, autoscroll: bool, cx: &mut ViewContext<Self>)
652 where
653 I: IntoIterator<Item = Range<T>>,
654 T: ToOffset,
655 {
656 let buffer = self.buffer.read(cx);
657 let mut selections = Vec::new();
658 for range in ranges {
659 let mut start = range.start.to_offset(buffer);
660 let mut end = range.end.to_offset(buffer);
661 let reversed = if start > end {
662 mem::swap(&mut start, &mut end);
663 true
664 } else {
665 false
666 };
667 selections.push(Selection {
668 id: post_inc(&mut self.next_selection_id),
669 start: buffer.anchor_before(start),
670 end: buffer.anchor_before(end),
671 reversed,
672 goal: SelectionGoal::None,
673 });
674 }
675 self.update_selections(selections, autoscroll, cx);
676 }
677
678 #[cfg(test)]
679 fn select_display_ranges<'a, T>(&mut self, ranges: T, cx: &mut ViewContext<Self>) -> Result<()>
680 where
681 T: IntoIterator<Item = &'a Range<DisplayPoint>>,
682 {
683 let mut selections = Vec::new();
684 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
685 for range in ranges {
686 let mut start = range.start;
687 let mut end = range.end;
688 let reversed = if start > end {
689 mem::swap(&mut start, &mut end);
690 true
691 } else {
692 false
693 };
694
695 selections.push(Selection {
696 id: post_inc(&mut self.next_selection_id),
697 start: display_map.anchor_before(start, Bias::Left),
698 end: display_map.anchor_before(end, Bias::Left),
699 reversed,
700 goal: SelectionGoal::None,
701 });
702 }
703 self.update_selections(selections, false, cx);
704 Ok(())
705 }
706
707 pub fn insert(&mut self, action: &Insert, cx: &mut ViewContext<Self>) {
708 let mut old_selections = SmallVec::<[_; 32]>::new();
709 {
710 let buffer = self.buffer.read(cx);
711 for selection in self.selections(cx.as_ref()) {
712 let start = selection.start.to_offset(buffer);
713 let end = selection.end.to_offset(buffer);
714 old_selections.push((selection.id, start..end));
715 }
716 }
717
718 self.start_transaction(cx);
719 let mut new_selections = Vec::new();
720 self.buffer.update(cx, |buffer, cx| {
721 let edit_ranges = old_selections.iter().map(|(_, range)| range.clone());
722 buffer.edit(edit_ranges, action.0.as_str(), cx);
723 let text_len = action.0.len() as isize;
724 let mut delta = 0_isize;
725 new_selections = old_selections
726 .into_iter()
727 .map(|(id, range)| {
728 let start = range.start as isize;
729 let end = range.end as isize;
730 let anchor = buffer.anchor_before((start + delta + text_len) as usize);
731 let deleted_count = end - start;
732 delta += text_len - deleted_count;
733 Selection {
734 id,
735 start: anchor.clone(),
736 end: anchor,
737 reversed: false,
738 goal: SelectionGoal::None,
739 }
740 })
741 .collect();
742 });
743
744 self.update_selections(new_selections, true, cx);
745 self.end_transaction(cx);
746 }
747
748 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
749 self.start_transaction(cx);
750 self.select_all(&SelectAll, cx);
751 self.insert(&Insert(String::new()), cx);
752 self.end_transaction(cx);
753 }
754
755 fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
756 self.insert(&Insert("\n".into()), cx);
757 }
758
759 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
760 self.start_transaction(cx);
761 let mut selections = self.selections(cx.as_ref()).to_vec();
762 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
763 {
764 let buffer = self.buffer.read(cx);
765 for selection in &mut selections {
766 let range = selection.point_range(buffer);
767 if range.start == range.end {
768 let head = selection.head().to_display_point(&display_map, Bias::Left);
769 let cursor = display_map
770 .anchor_before(movement::left(&display_map, head).unwrap(), Bias::Left);
771 selection.set_head(&buffer, cursor);
772 selection.goal = SelectionGoal::None;
773 }
774 }
775 }
776
777 self.update_selections(selections, true, cx);
778 self.insert(&Insert(String::new()), cx);
779 self.end_transaction(cx);
780 }
781
782 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
783 self.start_transaction(cx);
784 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
785 let mut selections = self.selections(cx.as_ref()).to_vec();
786 {
787 let buffer = self.buffer.read(cx);
788 for selection in &mut selections {
789 let range = selection.point_range(buffer);
790 if range.start == range.end {
791 let head = selection.head().to_display_point(&display_map, Bias::Left);
792 let cursor = display_map
793 .anchor_before(movement::right(&display_map, head).unwrap(), Bias::Right);
794 selection.set_head(&buffer, cursor);
795 selection.goal = SelectionGoal::None;
796 }
797 }
798 }
799
800 self.update_selections(selections, true, cx);
801 self.insert(&Insert(String::new()), cx);
802 self.end_transaction(cx);
803 }
804
805 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
806 self.start_transaction(cx);
807
808 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
809 let app = cx.as_ref();
810 let buffer = self.buffer.read(app);
811
812 let mut new_cursors = Vec::new();
813 let mut edit_ranges = Vec::new();
814
815 let mut selections = self.selections(app).iter().peekable();
816 while let Some(selection) = selections.next() {
817 let mut rows = selection.spanned_rows(false, &display_map).buffer_rows;
818 let goal_display_column = selection
819 .head()
820 .to_display_point(&display_map, Bias::Left)
821 .column();
822
823 // Accumulate contiguous regions of rows that we want to delete.
824 while let Some(next_selection) = selections.peek() {
825 let next_rows = next_selection.spanned_rows(false, &display_map).buffer_rows;
826 if next_rows.start <= rows.end {
827 rows.end = next_rows.end;
828 selections.next().unwrap();
829 } else {
830 break;
831 }
832 }
833
834 let mut edit_start = Point::new(rows.start, 0).to_offset(buffer);
835 let edit_end;
836 let cursor_buffer_row;
837 if buffer.max_point().row >= rows.end {
838 // If there's a line after the range, delete the \n from the end of the row range
839 // and position the cursor on the next line.
840 edit_end = Point::new(rows.end, 0).to_offset(buffer);
841 cursor_buffer_row = rows.end;
842 } else {
843 // If there isn't a line after the range, delete the \n from the line before the
844 // start of the row range and position the cursor there.
845 edit_start = edit_start.saturating_sub(1);
846 edit_end = buffer.len();
847 cursor_buffer_row = rows.start.saturating_sub(1);
848 }
849
850 let mut cursor =
851 Point::new(cursor_buffer_row, 0).to_display_point(&display_map, Bias::Left);
852 *cursor.column_mut() =
853 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
854
855 new_cursors.push((
856 selection.id,
857 cursor.to_buffer_point(&display_map, Bias::Left),
858 ));
859 edit_ranges.push(edit_start..edit_end);
860 }
861
862 new_cursors.sort_unstable_by_key(|(_, range)| range.clone());
863 let new_selections = new_cursors
864 .into_iter()
865 .map(|(id, cursor)| {
866 let anchor = buffer.anchor_before(cursor);
867 Selection {
868 id,
869 start: anchor.clone(),
870 end: anchor,
871 reversed: false,
872 goal: SelectionGoal::None,
873 }
874 })
875 .collect();
876 self.buffer
877 .update(cx, |buffer, cx| buffer.edit(edit_ranges, "", cx));
878 self.update_selections(new_selections, true, cx);
879 self.end_transaction(cx);
880 }
881
882 pub fn duplicate_line(&mut self, _: &DuplicateLine, cx: &mut ViewContext<Self>) {
883 self.start_transaction(cx);
884
885 let mut selections = self.selections(cx.as_ref()).to_vec();
886 {
887 // Temporarily bias selections right to allow newly duplicate lines to push them down
888 // when the selections are at the beginning of a line.
889 let buffer = self.buffer.read(cx);
890 for selection in &mut selections {
891 selection.start = selection.start.bias_right(buffer);
892 selection.end = selection.end.bias_right(buffer);
893 }
894 }
895 self.update_selections(selections.clone(), false, cx);
896
897 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
898 let buffer = self.buffer.read(cx);
899
900 let mut edits = Vec::new();
901 let mut selections_iter = selections.iter_mut().peekable();
902 while let Some(selection) = selections_iter.next() {
903 // Avoid duplicating the same lines twice.
904 let mut rows = selection.spanned_rows(false, &display_map).buffer_rows;
905 while let Some(next_selection) = selections_iter.peek() {
906 let next_rows = next_selection.spanned_rows(false, &display_map).buffer_rows;
907 if next_rows.start <= rows.end - 1 {
908 rows.end = next_rows.end;
909 selections_iter.next().unwrap();
910 } else {
911 break;
912 }
913 }
914
915 // Copy the text from the selected row region and splice it at the start of the region.
916 let start = Point::new(rows.start, 0);
917 let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
918 let text = buffer
919 .text_for_range(start..end)
920 .chain(Some("\n"))
921 .collect::<String>();
922 edits.push((start, text));
923 }
924
925 self.buffer.update(cx, |buffer, cx| {
926 for (offset, text) in edits.into_iter().rev() {
927 buffer.edit(Some(offset..offset), text, cx);
928 }
929 });
930
931 // Restore bias on selections.
932 let buffer = self.buffer.read(cx);
933 for selection in &mut selections {
934 selection.start = selection.start.bias_left(buffer);
935 selection.end = selection.end.bias_left(buffer);
936 }
937 self.update_selections(selections, true, cx);
938
939 self.end_transaction(cx);
940 }
941
942 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
943 self.start_transaction(cx);
944
945 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
946 let app = cx.as_ref();
947 let buffer = self.buffer.read(cx);
948
949 let mut edits = Vec::new();
950 let mut new_selection_ranges = Vec::new();
951 let mut old_folds = Vec::new();
952 let mut new_folds = Vec::new();
953
954 let mut selections = self.selections(app).iter().peekable();
955 let mut contiguous_selections = Vec::new();
956 while let Some(selection) = selections.next() {
957 // Accumulate contiguous regions of rows that we want to move.
958 contiguous_selections.push(selection.point_range(buffer));
959 let SpannedRows {
960 mut buffer_rows,
961 mut display_rows,
962 } = selection.spanned_rows(false, &display_map);
963
964 while let Some(next_selection) = selections.peek() {
965 let SpannedRows {
966 buffer_rows: next_buffer_rows,
967 display_rows: next_display_rows,
968 } = next_selection.spanned_rows(false, &display_map);
969 if next_buffer_rows.start <= buffer_rows.end {
970 buffer_rows.end = next_buffer_rows.end;
971 display_rows.end = next_display_rows.end;
972 contiguous_selections.push(next_selection.point_range(buffer));
973 selections.next().unwrap();
974 } else {
975 break;
976 }
977 }
978
979 // Cut the text from the selected rows and paste it at the start of the previous line.
980 if display_rows.start != 0 {
981 let start = Point::new(buffer_rows.start, 0).to_offset(buffer);
982 let end = Point::new(buffer_rows.end - 1, buffer.line_len(buffer_rows.end - 1))
983 .to_offset(buffer);
984
985 let prev_row_display_start = DisplayPoint::new(display_rows.start - 1, 0);
986 let prev_row_buffer_start = display_map.prev_row_boundary(prev_row_display_start).1;
987 let prev_row_buffer_start_offset = prev_row_buffer_start.to_offset(buffer);
988
989 let mut text = String::new();
990 text.extend(buffer.text_for_range(start..end));
991 text.push('\n');
992 edits.push((
993 prev_row_buffer_start_offset..prev_row_buffer_start_offset,
994 text,
995 ));
996 edits.push((start - 1..end, String::new()));
997
998 let row_delta = buffer_rows.start - prev_row_buffer_start.row;
999
1000 // Move selections up.
1001 for range in &mut contiguous_selections {
1002 range.start.row -= row_delta;
1003 range.end.row -= row_delta;
1004 }
1005
1006 // Move folds up.
1007 old_folds.push(start..end);
1008 for fold in display_map.folds_in_range(start..end) {
1009 let mut start = fold.start.to_point(buffer);
1010 let mut end = fold.end.to_point(buffer);
1011 start.row -= row_delta;
1012 end.row -= row_delta;
1013 new_folds.push(start..end);
1014 }
1015 }
1016
1017 new_selection_ranges.extend(contiguous_selections.drain(..));
1018 }
1019
1020 self.unfold_ranges(old_folds, cx);
1021 self.buffer.update(cx, |buffer, cx| {
1022 for (range, text) in edits.into_iter().rev() {
1023 buffer.edit(Some(range), text, cx);
1024 }
1025 });
1026 self.fold_ranges(new_folds, cx);
1027 self.select_ranges(new_selection_ranges, true, cx);
1028
1029 self.end_transaction(cx);
1030 }
1031
1032 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
1033 self.start_transaction(cx);
1034
1035 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1036 let app = cx.as_ref();
1037 let buffer = self.buffer.read(cx);
1038
1039 let mut edits = Vec::new();
1040 let mut new_selection_ranges = Vec::new();
1041 let mut old_folds = Vec::new();
1042 let mut new_folds = Vec::new();
1043
1044 let mut selections = self.selections(app).iter().peekable();
1045 let mut contiguous_selections = Vec::new();
1046 while let Some(selection) = selections.next() {
1047 // Accumulate contiguous regions of rows that we want to move.
1048 contiguous_selections.push(selection.point_range(buffer));
1049 let SpannedRows {
1050 mut buffer_rows,
1051 mut display_rows,
1052 } = selection.spanned_rows(false, &display_map);
1053 while let Some(next_selection) = selections.peek() {
1054 let SpannedRows {
1055 buffer_rows: next_buffer_rows,
1056 display_rows: next_display_rows,
1057 } = next_selection.spanned_rows(false, &display_map);
1058 if next_buffer_rows.start <= buffer_rows.end {
1059 buffer_rows.end = next_buffer_rows.end;
1060 display_rows.end = next_display_rows.end;
1061 contiguous_selections.push(next_selection.point_range(buffer));
1062 selections.next().unwrap();
1063 } else {
1064 break;
1065 }
1066 }
1067
1068 // Cut the text from the selected rows and paste it at the end of the next line.
1069 if display_rows.end <= display_map.max_point().row() {
1070 let start = Point::new(buffer_rows.start, 0).to_offset(buffer);
1071 let end = Point::new(buffer_rows.end - 1, buffer.line_len(buffer_rows.end - 1))
1072 .to_offset(buffer);
1073
1074 let next_row_display_end =
1075 DisplayPoint::new(display_rows.end, display_map.line_len(display_rows.end));
1076 let next_row_buffer_end = display_map.next_row_boundary(next_row_display_end).1;
1077 let next_row_buffer_end_offset = next_row_buffer_end.to_offset(buffer);
1078
1079 let mut text = String::new();
1080 text.push('\n');
1081 text.extend(buffer.text_for_range(start..end));
1082 edits.push((start..end + 1, String::new()));
1083 edits.push((next_row_buffer_end_offset..next_row_buffer_end_offset, text));
1084
1085 let row_delta = next_row_buffer_end.row - buffer_rows.end + 1;
1086
1087 // Move selections down.
1088 for range in &mut contiguous_selections {
1089 range.start.row += row_delta;
1090 range.end.row += row_delta;
1091 }
1092
1093 // Move folds down.
1094 old_folds.push(start..end);
1095 for fold in display_map.folds_in_range(start..end) {
1096 let mut start = fold.start.to_point(buffer);
1097 let mut end = fold.end.to_point(buffer);
1098 start.row += row_delta;
1099 end.row += row_delta;
1100 new_folds.push(start..end);
1101 }
1102 }
1103
1104 new_selection_ranges.extend(contiguous_selections.drain(..));
1105 }
1106
1107 self.unfold_ranges(old_folds, cx);
1108 self.buffer.update(cx, |buffer, cx| {
1109 for (range, text) in edits.into_iter().rev() {
1110 buffer.edit(Some(range), text, cx);
1111 }
1112 });
1113 self.fold_ranges(new_folds, cx);
1114 self.select_ranges(new_selection_ranges, true, cx);
1115
1116 self.end_transaction(cx);
1117 }
1118
1119 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
1120 self.start_transaction(cx);
1121 let mut text = String::new();
1122 let mut selections = self.selections(cx.as_ref()).to_vec();
1123 let mut clipboard_selections = Vec::with_capacity(selections.len());
1124 {
1125 let buffer = self.buffer.read(cx);
1126 let max_point = buffer.max_point();
1127 for selection in &mut selections {
1128 let mut start = selection.start.to_point(buffer);
1129 let mut end = selection.end.to_point(buffer);
1130 let is_entire_line = start == end;
1131 if is_entire_line {
1132 start = Point::new(start.row, 0);
1133 end = cmp::min(max_point, Point::new(start.row + 1, 0));
1134 selection.start = buffer.anchor_before(start);
1135 selection.end = buffer.anchor_before(end);
1136 }
1137 let mut len = 0;
1138 for chunk in buffer.text_for_range(start..end) {
1139 text.push_str(chunk);
1140 len += chunk.len();
1141 }
1142 clipboard_selections.push(ClipboardSelection {
1143 len,
1144 is_entire_line,
1145 });
1146 }
1147 }
1148 self.update_selections(selections, true, cx);
1149 self.insert(&Insert(String::new()), cx);
1150 self.end_transaction(cx);
1151
1152 cx.as_mut()
1153 .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
1154 }
1155
1156 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
1157 let buffer = self.buffer.read(cx);
1158 let max_point = buffer.max_point();
1159 let mut text = String::new();
1160 let selections = self.selections(cx.as_ref());
1161 let mut clipboard_selections = Vec::with_capacity(selections.len());
1162 for selection in selections {
1163 let mut start = selection.start.to_point(buffer);
1164 let mut end = selection.end.to_point(buffer);
1165 let is_entire_line = start == end;
1166 if is_entire_line {
1167 start = Point::new(start.row, 0);
1168 end = cmp::min(max_point, Point::new(start.row + 1, 0));
1169 }
1170 let mut len = 0;
1171 for chunk in buffer.text_for_range(start..end) {
1172 text.push_str(chunk);
1173 len += chunk.len();
1174 }
1175 clipboard_selections.push(ClipboardSelection {
1176 len,
1177 is_entire_line,
1178 });
1179 }
1180
1181 cx.as_mut()
1182 .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
1183 }
1184
1185 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
1186 if let Some(item) = cx.as_mut().read_from_clipboard() {
1187 let clipboard_text = item.text();
1188 if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
1189 let selections = self.selections(cx.as_ref()).to_vec();
1190 if clipboard_selections.len() != selections.len() {
1191 let merged_selection = ClipboardSelection {
1192 len: clipboard_selections.iter().map(|s| s.len).sum(),
1193 is_entire_line: clipboard_selections.iter().all(|s| s.is_entire_line),
1194 };
1195 clipboard_selections.clear();
1196 clipboard_selections.push(merged_selection);
1197 }
1198
1199 self.start_transaction(cx);
1200 let mut new_selections = Vec::with_capacity(selections.len());
1201 let mut clipboard_chars = clipboard_text.chars().cycle();
1202 for (selection, clipboard_selection) in
1203 selections.iter().zip(clipboard_selections.iter().cycle())
1204 {
1205 let to_insert =
1206 String::from_iter(clipboard_chars.by_ref().take(clipboard_selection.len));
1207
1208 self.buffer.update(cx, |buffer, cx| {
1209 let selection_start = selection.start.to_point(&*buffer);
1210 let selection_end = selection.end.to_point(&*buffer);
1211
1212 // If the corresponding selection was empty when this slice of the
1213 // clipboard text was written, then the entire line containing the
1214 // selection was copied. If this selection is also currently empty,
1215 // then paste the line before the current line of the buffer.
1216 let new_selection_start = selection.end.bias_right(buffer);
1217 if selection_start == selection_end && clipboard_selection.is_entire_line {
1218 let line_start = Point::new(selection_start.row, 0);
1219 buffer.edit(Some(line_start..line_start), to_insert, cx);
1220 } else {
1221 buffer.edit(Some(&selection.start..&selection.end), to_insert, cx);
1222 };
1223
1224 let new_selection_start = new_selection_start.bias_left(buffer);
1225 new_selections.push(Selection {
1226 id: selection.id,
1227 start: new_selection_start.clone(),
1228 end: new_selection_start,
1229 reversed: false,
1230 goal: SelectionGoal::None,
1231 });
1232 });
1233 }
1234 self.update_selections(new_selections, true, cx);
1235 self.end_transaction(cx);
1236 } else {
1237 self.insert(&Insert(clipboard_text.into()), cx);
1238 }
1239 }
1240 }
1241
1242 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
1243 self.buffer.update(cx, |buffer, cx| buffer.undo(cx));
1244 }
1245
1246 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
1247 self.buffer.update(cx, |buffer, cx| buffer.redo(cx));
1248 }
1249
1250 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
1251 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1252 let app = cx.as_ref();
1253 let mut selections = self.selections(app).to_vec();
1254 {
1255 for selection in &mut selections {
1256 let start = selection.start.to_display_point(&display_map, Bias::Left);
1257 let end = selection.end.to_display_point(&display_map, Bias::Left);
1258
1259 if start != end {
1260 selection.end = selection.start.clone();
1261 } else {
1262 let cursor = display_map
1263 .anchor_before(movement::left(&display_map, start).unwrap(), Bias::Left);
1264 selection.start = cursor.clone();
1265 selection.end = cursor;
1266 }
1267 selection.reversed = false;
1268 selection.goal = SelectionGoal::None;
1269 }
1270 }
1271 self.update_selections(selections, true, cx);
1272 }
1273
1274 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
1275 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1276 let mut selections = self.selections(cx.as_ref()).to_vec();
1277 {
1278 let buffer = self.buffer.read(cx);
1279 for selection in &mut selections {
1280 let head = selection.head().to_display_point(&display_map, Bias::Left);
1281 let cursor = display_map
1282 .anchor_before(movement::left(&display_map, head).unwrap(), Bias::Left);
1283 selection.set_head(&buffer, cursor);
1284 selection.goal = SelectionGoal::None;
1285 }
1286 }
1287 self.update_selections(selections, true, cx);
1288 }
1289
1290 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
1291 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1292 let mut selections = self.selections(cx.as_ref()).to_vec();
1293 {
1294 for selection in &mut selections {
1295 let start = selection.start.to_display_point(&display_map, Bias::Left);
1296 let end = selection.end.to_display_point(&display_map, Bias::Left);
1297
1298 if start != end {
1299 selection.start = selection.end.clone();
1300 } else {
1301 let cursor = display_map
1302 .anchor_before(movement::right(&display_map, end).unwrap(), Bias::Right);
1303 selection.start = cursor.clone();
1304 selection.end = cursor;
1305 }
1306 selection.reversed = false;
1307 selection.goal = SelectionGoal::None;
1308 }
1309 }
1310 self.update_selections(selections, true, cx);
1311 }
1312
1313 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
1314 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1315 let mut selections = self.selections(cx.as_ref()).to_vec();
1316 {
1317 let app = cx.as_ref();
1318 let buffer = self.buffer.read(app);
1319 for selection in &mut selections {
1320 let head = selection.head().to_display_point(&display_map, Bias::Left);
1321 let cursor = display_map
1322 .anchor_before(movement::right(&display_map, head).unwrap(), Bias::Right);
1323 selection.set_head(&buffer, cursor);
1324 selection.goal = SelectionGoal::None;
1325 }
1326 }
1327 self.update_selections(selections, true, cx);
1328 }
1329
1330 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
1331 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1332 if matches!(self.mode, EditorMode::SingleLine) {
1333 cx.propagate_action();
1334 } else {
1335 let mut selections = self.selections(cx.as_ref()).to_vec();
1336 {
1337 for selection in &mut selections {
1338 let start = selection.start.to_display_point(&display_map, Bias::Left);
1339 let end = selection.end.to_display_point(&display_map, Bias::Left);
1340 if start != end {
1341 selection.goal = SelectionGoal::None;
1342 }
1343
1344 let (start, goal) = movement::up(&display_map, start, selection.goal).unwrap();
1345 let cursor = display_map.anchor_before(start, Bias::Left);
1346 selection.start = cursor.clone();
1347 selection.end = cursor;
1348 selection.goal = goal;
1349 selection.reversed = false;
1350 }
1351 }
1352 self.update_selections(selections, true, cx);
1353 }
1354 }
1355
1356 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
1357 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1358 let mut selections = self.selections(cx.as_ref()).to_vec();
1359 {
1360 let app = cx.as_ref();
1361 let buffer = self.buffer.read(app);
1362 for selection in &mut selections {
1363 let head = selection.head().to_display_point(&display_map, Bias::Left);
1364 let (head, goal) = movement::up(&display_map, head, selection.goal).unwrap();
1365 selection.set_head(&buffer, display_map.anchor_before(head, Bias::Left));
1366 selection.goal = goal;
1367 }
1368 }
1369 self.update_selections(selections, true, cx);
1370 }
1371
1372 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
1373 if matches!(self.mode, EditorMode::SingleLine) {
1374 cx.propagate_action();
1375 } else {
1376 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1377 let mut selections = self.selections(cx.as_ref()).to_vec();
1378 {
1379 for selection in &mut selections {
1380 let start = selection.start.to_display_point(&display_map, Bias::Left);
1381 let end = selection.end.to_display_point(&display_map, Bias::Left);
1382 if start != end {
1383 selection.goal = SelectionGoal::None;
1384 }
1385
1386 let (start, goal) = movement::down(&display_map, end, selection.goal).unwrap();
1387 let cursor = display_map.anchor_before(start, Bias::Right);
1388 selection.start = cursor.clone();
1389 selection.end = cursor;
1390 selection.goal = goal;
1391 selection.reversed = false;
1392 }
1393 }
1394 self.update_selections(selections, true, cx);
1395 }
1396 }
1397
1398 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
1399 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1400 let mut selections = self.selections(cx).to_vec();
1401 {
1402 let app = cx.as_ref();
1403 let buffer = self.buffer.read(app);
1404 for selection in &mut selections {
1405 let head = selection.head().to_display_point(&display_map, Bias::Left);
1406 let (head, goal) = movement::down(&display_map, head, selection.goal).unwrap();
1407 selection.set_head(&buffer, display_map.anchor_before(head, Bias::Right));
1408 selection.goal = goal;
1409 }
1410 }
1411 self.update_selections(selections, true, cx);
1412 }
1413
1414 pub fn move_to_previous_word_boundary(
1415 &mut self,
1416 _: &MoveToPreviousWordBoundary,
1417 cx: &mut ViewContext<Self>,
1418 ) {
1419 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1420 let mut selections = self.selections(cx).to_vec();
1421 {
1422 for selection in &mut selections {
1423 let head = selection.head().to_display_point(&display_map, Bias::Left);
1424 let new_head = movement::prev_word_boundary(&display_map, head).unwrap();
1425 let anchor = display_map.anchor_before(new_head, Bias::Left);
1426 selection.start = anchor.clone();
1427 selection.end = anchor;
1428 selection.reversed = false;
1429 selection.goal = SelectionGoal::None;
1430 }
1431 }
1432 self.update_selections(selections, true, cx);
1433 }
1434
1435 pub fn select_to_previous_word_boundary(
1436 &mut self,
1437 _: &SelectToPreviousWordBoundary,
1438 cx: &mut ViewContext<Self>,
1439 ) {
1440 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1441 let mut selections = self.selections(cx).to_vec();
1442 {
1443 let buffer = self.buffer.read(cx);
1444 for selection in &mut selections {
1445 let head = selection.head().to_display_point(&display_map, Bias::Left);
1446 let new_head = movement::prev_word_boundary(&display_map, head).unwrap();
1447 let anchor = display_map.anchor_before(new_head, Bias::Left);
1448 selection.set_head(buffer, anchor);
1449 selection.goal = SelectionGoal::None;
1450 }
1451 }
1452 self.update_selections(selections, true, cx);
1453 }
1454
1455 pub fn delete_to_previous_word_boundary(
1456 &mut self,
1457 _: &DeleteToPreviousWordBoundary,
1458 cx: &mut ViewContext<Self>,
1459 ) {
1460 self.start_transaction(cx);
1461 self.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
1462 self.backspace(&Backspace, cx);
1463 self.end_transaction(cx);
1464 }
1465
1466 pub fn move_to_next_word_boundary(
1467 &mut self,
1468 _: &MoveToNextWordBoundary,
1469 cx: &mut ViewContext<Self>,
1470 ) {
1471 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1472 let mut selections = self.selections(cx).to_vec();
1473 {
1474 for selection in &mut selections {
1475 let head = selection.head().to_display_point(&display_map, Bias::Left);
1476 let new_head = movement::next_word_boundary(&display_map, head).unwrap();
1477 let anchor = display_map.anchor_before(new_head, Bias::Left);
1478 selection.start = anchor.clone();
1479 selection.end = anchor;
1480 selection.reversed = false;
1481 selection.goal = SelectionGoal::None;
1482 }
1483 }
1484 self.update_selections(selections, true, cx);
1485 }
1486
1487 pub fn select_to_next_word_boundary(
1488 &mut self,
1489 _: &SelectToNextWordBoundary,
1490 cx: &mut ViewContext<Self>,
1491 ) {
1492 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1493 let mut selections = self.selections(cx).to_vec();
1494 {
1495 let buffer = self.buffer.read(cx);
1496 for selection in &mut selections {
1497 let head = selection.head().to_display_point(&display_map, Bias::Left);
1498 let new_head = movement::next_word_boundary(&display_map, head).unwrap();
1499 let anchor = display_map.anchor_before(new_head, Bias::Left);
1500 selection.set_head(buffer, anchor);
1501 selection.goal = SelectionGoal::None;
1502 }
1503 }
1504 self.update_selections(selections, true, cx);
1505 }
1506
1507 pub fn delete_to_next_word_boundary(
1508 &mut self,
1509 _: &DeleteToNextWordBoundary,
1510 cx: &mut ViewContext<Self>,
1511 ) {
1512 self.start_transaction(cx);
1513 self.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
1514 self.delete(&Delete, cx);
1515 self.end_transaction(cx);
1516 }
1517
1518 pub fn move_to_beginning_of_line(
1519 &mut self,
1520 _: &MoveToBeginningOfLine,
1521 cx: &mut ViewContext<Self>,
1522 ) {
1523 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1524 let mut selections = self.selections(cx).to_vec();
1525 {
1526 for selection in &mut selections {
1527 let head = selection.head().to_display_point(&display_map, Bias::Left);
1528 let new_head = movement::line_beginning(&display_map, head, true).unwrap();
1529 let anchor = display_map.anchor_before(new_head, Bias::Left);
1530 selection.start = anchor.clone();
1531 selection.end = anchor;
1532 selection.reversed = false;
1533 selection.goal = SelectionGoal::None;
1534 }
1535 }
1536 self.update_selections(selections, true, cx);
1537 }
1538
1539 pub fn select_to_beginning_of_line(
1540 &mut self,
1541 SelectToBeginningOfLine(toggle_indent): &SelectToBeginningOfLine,
1542 cx: &mut ViewContext<Self>,
1543 ) {
1544 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1545 let mut selections = self.selections(cx).to_vec();
1546 {
1547 let buffer = self.buffer.read(cx);
1548 for selection in &mut selections {
1549 let head = selection.head().to_display_point(&display_map, Bias::Left);
1550 let new_head =
1551 movement::line_beginning(&display_map, head, *toggle_indent).unwrap();
1552 let anchor = display_map.anchor_before(new_head, Bias::Left);
1553 selection.set_head(buffer, anchor);
1554 selection.goal = SelectionGoal::None;
1555 }
1556 }
1557 self.update_selections(selections, true, cx);
1558 }
1559
1560 pub fn delete_to_beginning_of_line(
1561 &mut self,
1562 _: &DeleteToBeginningOfLine,
1563 cx: &mut ViewContext<Self>,
1564 ) {
1565 self.start_transaction(cx);
1566 self.select_to_beginning_of_line(&SelectToBeginningOfLine(false), cx);
1567 self.backspace(&Backspace, cx);
1568 self.end_transaction(cx);
1569 }
1570
1571 pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
1572 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1573 let mut selections = self.selections(cx).to_vec();
1574 {
1575 for selection in &mut selections {
1576 let head = selection.head().to_display_point(&display_map, Bias::Left);
1577 let new_head = movement::line_end(&display_map, head).unwrap();
1578 let anchor = display_map.anchor_before(new_head, Bias::Left);
1579 selection.start = anchor.clone();
1580 selection.end = anchor;
1581 selection.reversed = false;
1582 selection.goal = SelectionGoal::None;
1583 }
1584 }
1585 self.update_selections(selections, true, cx);
1586 }
1587
1588 pub fn select_to_end_of_line(&mut self, _: &SelectToEndOfLine, cx: &mut ViewContext<Self>) {
1589 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1590 let mut selections = self.selections(cx).to_vec();
1591 {
1592 let buffer = self.buffer.read(cx);
1593 for selection in &mut selections {
1594 let head = selection.head().to_display_point(&display_map, Bias::Left);
1595 let new_head = movement::line_end(&display_map, head).unwrap();
1596 let anchor = display_map.anchor_before(new_head, Bias::Left);
1597 selection.set_head(buffer, anchor);
1598 selection.goal = SelectionGoal::None;
1599 }
1600 }
1601 self.update_selections(selections, true, cx);
1602 }
1603
1604 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
1605 self.start_transaction(cx);
1606 self.select_to_end_of_line(&SelectToEndOfLine, cx);
1607 self.delete(&Delete, cx);
1608 self.end_transaction(cx);
1609 }
1610
1611 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
1612 self.start_transaction(cx);
1613 self.select_to_end_of_line(&SelectToEndOfLine, cx);
1614 self.cut(&Cut, cx);
1615 self.end_transaction(cx);
1616 }
1617
1618 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
1619 let buffer = self.buffer.read(cx);
1620 let cursor = buffer.anchor_before(Point::new(0, 0));
1621 let selection = Selection {
1622 id: post_inc(&mut self.next_selection_id),
1623 start: cursor.clone(),
1624 end: cursor,
1625 reversed: false,
1626 goal: SelectionGoal::None,
1627 };
1628 self.update_selections(vec![selection], true, cx);
1629 }
1630
1631 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
1632 let mut selection = self.selections(cx.as_ref()).last().unwrap().clone();
1633 selection.set_head(self.buffer.read(cx), Anchor::min());
1634 self.update_selections(vec![selection], true, cx);
1635 }
1636
1637 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
1638 let buffer = self.buffer.read(cx);
1639 let cursor = buffer.anchor_before(buffer.max_point());
1640 let selection = Selection {
1641 id: post_inc(&mut self.next_selection_id),
1642 start: cursor.clone(),
1643 end: cursor,
1644 reversed: false,
1645 goal: SelectionGoal::None,
1646 };
1647 self.update_selections(vec![selection], true, cx);
1648 }
1649
1650 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
1651 let mut selection = self.selections(cx.as_ref()).last().unwrap().clone();
1652 selection.set_head(self.buffer.read(cx), Anchor::max());
1653 self.update_selections(vec![selection], true, cx);
1654 }
1655
1656 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
1657 let selection = Selection {
1658 id: post_inc(&mut self.next_selection_id),
1659 start: Anchor::min(),
1660 end: Anchor::max(),
1661 reversed: false,
1662 goal: SelectionGoal::None,
1663 };
1664 self.update_selections(vec![selection], false, cx);
1665 }
1666
1667 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
1668 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1669 let buffer = self.buffer.read(cx);
1670 let mut selections = self.selections(cx).to_vec();
1671 let max_point = buffer.max_point();
1672 for selection in &mut selections {
1673 let rows = selection.spanned_rows(true, &display_map).buffer_rows;
1674 selection.start = buffer.anchor_before(Point::new(rows.start, 0));
1675 selection.end = buffer.anchor_before(cmp::min(max_point, Point::new(rows.end, 0)));
1676 selection.reversed = false;
1677 }
1678 self.update_selections(selections, true, cx);
1679 }
1680
1681 pub fn split_selection_into_lines(
1682 &mut self,
1683 _: &SplitSelectionIntoLines,
1684 cx: &mut ViewContext<Self>,
1685 ) {
1686 let app = cx.as_ref();
1687 let buffer = self.buffer.read(app);
1688
1689 let mut to_unfold = Vec::new();
1690 let mut new_selections = Vec::new();
1691 for selection in self.selections(app) {
1692 let range = selection.point_range(buffer).sorted();
1693 if range.start.row != range.end.row {
1694 new_selections.push(Selection {
1695 id: post_inc(&mut self.next_selection_id),
1696 start: selection.start.clone(),
1697 end: selection.start.clone(),
1698 reversed: false,
1699 goal: SelectionGoal::None,
1700 });
1701 }
1702 for row in range.start.row + 1..range.end.row {
1703 let cursor = buffer.anchor_before(Point::new(row, buffer.line_len(row)));
1704 new_selections.push(Selection {
1705 id: post_inc(&mut self.next_selection_id),
1706 start: cursor.clone(),
1707 end: cursor,
1708 reversed: false,
1709 goal: SelectionGoal::None,
1710 });
1711 }
1712 new_selections.push(Selection {
1713 id: selection.id,
1714 start: selection.end.clone(),
1715 end: selection.end.clone(),
1716 reversed: false,
1717 goal: SelectionGoal::None,
1718 });
1719 to_unfold.push(range);
1720 }
1721 self.unfold_ranges(to_unfold, cx);
1722 self.update_selections(new_selections, true, cx);
1723 }
1724
1725 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
1726 self.add_selection(true, cx);
1727 }
1728
1729 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
1730 self.add_selection(false, cx);
1731 }
1732
1733 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
1734 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1735 let mut selections = self.selections(cx).to_vec();
1736 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
1737 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
1738 let range = oldest_selection.display_range(&display_map).sorted();
1739 let columns = cmp::min(range.start.column(), range.end.column())
1740 ..cmp::max(range.start.column(), range.end.column());
1741
1742 selections.clear();
1743 let mut stack = Vec::new();
1744 for row in range.start.row()..=range.end.row() {
1745 if let Some(selection) = self.build_columnar_selection(
1746 &display_map,
1747 row,
1748 &columns,
1749 oldest_selection.reversed,
1750 ) {
1751 stack.push(selection.id);
1752 selections.push(selection);
1753 }
1754 }
1755
1756 if above {
1757 stack.reverse();
1758 }
1759
1760 AddSelectionsState { above, stack }
1761 });
1762
1763 let last_added_selection = *state.stack.last().unwrap();
1764 let mut new_selections = Vec::new();
1765 if above == state.above {
1766 let end_row = if above {
1767 0
1768 } else {
1769 display_map.max_point().row()
1770 };
1771
1772 'outer: for selection in selections {
1773 if selection.id == last_added_selection {
1774 let range = selection.display_range(&display_map).sorted();
1775 debug_assert_eq!(range.start.row(), range.end.row());
1776 let mut row = range.start.row();
1777 let columns = if let SelectionGoal::ColumnRange { start, end } = selection.goal
1778 {
1779 start..end
1780 } else {
1781 cmp::min(range.start.column(), range.end.column())
1782 ..cmp::max(range.start.column(), range.end.column())
1783 };
1784
1785 while row != end_row {
1786 if above {
1787 row -= 1;
1788 } else {
1789 row += 1;
1790 }
1791
1792 if let Some(new_selection) = self.build_columnar_selection(
1793 &display_map,
1794 row,
1795 &columns,
1796 selection.reversed,
1797 ) {
1798 state.stack.push(new_selection.id);
1799 if above {
1800 new_selections.push(new_selection);
1801 new_selections.push(selection);
1802 } else {
1803 new_selections.push(selection);
1804 new_selections.push(new_selection);
1805 }
1806
1807 continue 'outer;
1808 }
1809 }
1810 }
1811
1812 new_selections.push(selection);
1813 }
1814 } else {
1815 new_selections = selections;
1816 new_selections.retain(|s| s.id != last_added_selection);
1817 state.stack.pop();
1818 }
1819
1820 self.update_selections(new_selections, true, cx);
1821 if state.stack.len() > 1 {
1822 self.add_selections_state = Some(state);
1823 }
1824 }
1825
1826 pub fn select_larger_syntax_node(
1827 &mut self,
1828 _: &SelectLargerSyntaxNode,
1829 cx: &mut ViewContext<Self>,
1830 ) {
1831 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1832 let buffer = self.buffer.read(cx);
1833
1834 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
1835 let mut selected_larger_node = false;
1836 let old_selections = self.selections(cx).to_vec();
1837 let mut new_selection_ranges = Vec::new();
1838 for selection in &old_selections {
1839 let old_range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
1840 let mut new_range = old_range.clone();
1841 while let Some(containing_range) = buffer.range_for_syntax_ancestor(new_range.clone()) {
1842 new_range = containing_range;
1843 if !display_map.intersects_fold(new_range.start)
1844 && !display_map.intersects_fold(new_range.end)
1845 {
1846 break;
1847 }
1848 }
1849
1850 selected_larger_node |= new_range != old_range;
1851 new_selection_ranges.push((selection.id, new_range, selection.reversed));
1852 }
1853
1854 if selected_larger_node {
1855 stack.push(old_selections);
1856 new_selection_ranges.sort_unstable_by_key(|(_, range, _)| range.start.clone());
1857 let new_selections = new_selection_ranges
1858 .into_iter()
1859 .map(|(id, range, reversed)| Selection {
1860 id,
1861 start: buffer.anchor_before(range.start),
1862 end: buffer.anchor_before(range.end),
1863 reversed,
1864 goal: SelectionGoal::None,
1865 })
1866 .collect();
1867 self.update_selections(new_selections, true, cx);
1868 }
1869 self.select_larger_syntax_node_stack = stack;
1870 }
1871
1872 pub fn select_smaller_syntax_node(
1873 &mut self,
1874 _: &SelectSmallerSyntaxNode,
1875 cx: &mut ViewContext<Self>,
1876 ) {
1877 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
1878 if let Some(selections) = stack.pop() {
1879 self.update_selections(selections, true, cx);
1880 }
1881 self.select_larger_syntax_node_stack = stack;
1882 }
1883
1884 pub fn move_to_enclosing_bracket(
1885 &mut self,
1886 _: &MoveToEnclosingBracket,
1887 cx: &mut ViewContext<Self>,
1888 ) {
1889 let buffer = self.buffer.read(cx.as_ref());
1890 let mut selections = self.selections(cx.as_ref()).to_vec();
1891 for selection in &mut selections {
1892 let selection_range = selection.offset_range(buffer);
1893 if let Some((open_range, close_range)) =
1894 buffer.enclosing_bracket_ranges(selection_range.clone())
1895 {
1896 let close_range = close_range.to_inclusive();
1897 let destination = if close_range.contains(&selection_range.start)
1898 && close_range.contains(&selection_range.end)
1899 {
1900 open_range.end
1901 } else {
1902 *close_range.start()
1903 };
1904 selection.start = buffer.anchor_before(destination);
1905 selection.end = selection.start.clone();
1906 }
1907 }
1908
1909 self.update_selections(selections, true, cx);
1910 }
1911
1912 fn build_columnar_selection(
1913 &mut self,
1914 display_map: &DisplayMapSnapshot,
1915 row: u32,
1916 columns: &Range<u32>,
1917 reversed: bool,
1918 ) -> Option<Selection> {
1919 let is_empty = columns.start == columns.end;
1920 let line_len = display_map.line_len(row);
1921 if columns.start < line_len || (is_empty && columns.start == line_len) {
1922 let start = DisplayPoint::new(row, columns.start);
1923 let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
1924 Some(Selection {
1925 id: post_inc(&mut self.next_selection_id),
1926 start: display_map.anchor_before(start, Bias::Left),
1927 end: display_map.anchor_before(end, Bias::Left),
1928 reversed,
1929 goal: SelectionGoal::ColumnRange {
1930 start: columns.start,
1931 end: columns.end,
1932 },
1933 })
1934 } else {
1935 None
1936 }
1937 }
1938
1939 pub fn active_selection_sets<'a>(
1940 &'a self,
1941 cx: &'a AppContext,
1942 ) -> impl 'a + Iterator<Item = SelectionSetId> {
1943 let buffer = self.buffer.read(cx);
1944 let replica_id = buffer.replica_id();
1945 buffer
1946 .selection_sets()
1947 .filter(move |(set_id, set)| {
1948 set.active && (set_id.replica_id != replica_id || **set_id == self.selection_set_id)
1949 })
1950 .map(|(set_id, _)| *set_id)
1951 }
1952
1953 pub fn selections_in_range<'a>(
1954 &'a self,
1955 set_id: SelectionSetId,
1956 range: Range<DisplayPoint>,
1957 cx: &'a mut MutableAppContext,
1958 ) -> impl 'a + Iterator<Item = Range<DisplayPoint>> {
1959 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1960 let buffer = self.buffer.read(cx);
1961 let selections = &buffer.selection_set(set_id).unwrap().selections;
1962 let start = display_map.anchor_before(range.start, Bias::Left);
1963 let start_index = self.selection_insertion_index(selections, &start, cx);
1964 let pending_selection = if set_id.replica_id == self.buffer.read(cx).replica_id() {
1965 self.pending_selection.as_ref().and_then(|s| {
1966 let selection_range = s.display_range(&display_map);
1967 if selection_range.start <= range.end || selection_range.end <= range.end {
1968 Some(selection_range)
1969 } else {
1970 None
1971 }
1972 })
1973 } else {
1974 None
1975 };
1976 selections[start_index..]
1977 .iter()
1978 .map(move |s| s.display_range(&display_map))
1979 .take_while(move |r| r.start <= range.end || r.end <= range.end)
1980 .chain(pending_selection)
1981 }
1982
1983 fn selection_insertion_index(
1984 &self,
1985 selections: &[Selection],
1986 start: &Anchor,
1987 cx: &AppContext,
1988 ) -> usize {
1989 let buffer = self.buffer.read(cx);
1990 match selections.binary_search_by(|probe| probe.start.cmp(&start, buffer).unwrap()) {
1991 Ok(index) => index,
1992 Err(index) => {
1993 if index > 0
1994 && selections[index - 1].end.cmp(&start, buffer).unwrap() == Ordering::Greater
1995 {
1996 index - 1
1997 } else {
1998 index
1999 }
2000 }
2001 }
2002 }
2003
2004 fn selections<'a>(&self, cx: &'a AppContext) -> &'a [Selection] {
2005 let buffer = self.buffer.read(cx);
2006 &buffer
2007 .selection_set(self.selection_set_id)
2008 .unwrap()
2009 .selections
2010 }
2011
2012 fn update_selections(
2013 &mut self,
2014 mut selections: Vec<Selection>,
2015 autoscroll: bool,
2016 cx: &mut ViewContext<Self>,
2017 ) {
2018 // Merge overlapping selections.
2019 let buffer = self.buffer.read(cx);
2020 let mut i = 1;
2021 while i < selections.len() {
2022 if selections[i - 1]
2023 .end
2024 .cmp(&selections[i].start, buffer)
2025 .unwrap()
2026 >= Ordering::Equal
2027 {
2028 let removed = selections.remove(i);
2029 if removed.start.cmp(&selections[i - 1].start, buffer).unwrap() < Ordering::Equal {
2030 selections[i - 1].start = removed.start;
2031 }
2032 if removed.end.cmp(&selections[i - 1].end, buffer).unwrap() > Ordering::Equal {
2033 selections[i - 1].end = removed.end;
2034 }
2035 } else {
2036 i += 1;
2037 }
2038 }
2039
2040 self.buffer.update(cx, |buffer, cx| {
2041 buffer
2042 .update_selection_set(self.selection_set_id, selections, cx)
2043 .unwrap();
2044 });
2045 self.pause_cursor_blinking(cx);
2046
2047 if autoscroll {
2048 self.autoscroll_requested = true;
2049 cx.notify();
2050 }
2051
2052 self.add_selections_state = None;
2053 self.select_larger_syntax_node_stack.clear();
2054 }
2055
2056 fn start_transaction(&self, cx: &mut ViewContext<Self>) {
2057 self.buffer.update(cx, |buffer, _| {
2058 buffer
2059 .start_transaction(Some(self.selection_set_id))
2060 .unwrap()
2061 });
2062 }
2063
2064 fn end_transaction(&self, cx: &mut ViewContext<Self>) {
2065 self.buffer.update(cx, |buffer, cx| {
2066 buffer
2067 .end_transaction(Some(self.selection_set_id), cx)
2068 .unwrap()
2069 });
2070 }
2071
2072 pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
2073 log::info!("Editor::page_up");
2074 }
2075
2076 pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
2077 log::info!("Editor::page_down");
2078 }
2079
2080 pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
2081 let mut fold_ranges = Vec::new();
2082
2083 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2084 for selection in self.selections(cx) {
2085 let range = selection.display_range(&display_map).sorted();
2086 let buffer_start_row = range.start.to_buffer_point(&display_map, Bias::Left).row;
2087
2088 for row in (0..=range.end.row()).rev() {
2089 if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
2090 let fold_range = self.foldable_range_for_line(&display_map, row);
2091 if fold_range.end.row >= buffer_start_row {
2092 fold_ranges.push(fold_range);
2093 if row <= range.start.row() {
2094 break;
2095 }
2096 }
2097 }
2098 }
2099 }
2100
2101 self.fold_ranges(fold_ranges, cx);
2102 }
2103
2104 pub fn unfold(&mut self, _: &Unfold, cx: &mut ViewContext<Self>) {
2105 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2106 let buffer = self.buffer.read(cx);
2107 let ranges = self
2108 .selections(cx)
2109 .iter()
2110 .map(|s| {
2111 let range = s.display_range(&display_map).sorted();
2112 let mut start = range.start.to_buffer_point(&display_map, Bias::Left);
2113 let mut end = range.end.to_buffer_point(&display_map, Bias::Left);
2114 start.column = 0;
2115 end.column = buffer.line_len(end.row);
2116 start..end
2117 })
2118 .collect::<Vec<_>>();
2119 self.unfold_ranges(ranges, cx);
2120 }
2121
2122 fn is_line_foldable(&self, display_map: &DisplayMapSnapshot, display_row: u32) -> bool {
2123 let max_point = display_map.max_point();
2124 if display_row >= max_point.row() {
2125 false
2126 } else {
2127 let (start_indent, is_blank) = display_map.line_indent(display_row);
2128 if is_blank {
2129 false
2130 } else {
2131 for display_row in display_row + 1..=max_point.row() {
2132 let (indent, is_blank) = display_map.line_indent(display_row);
2133 if !is_blank {
2134 return indent > start_indent;
2135 }
2136 }
2137 false
2138 }
2139 }
2140 }
2141
2142 fn foldable_range_for_line(
2143 &self,
2144 display_map: &DisplayMapSnapshot,
2145 start_row: u32,
2146 ) -> Range<Point> {
2147 let max_point = display_map.max_point();
2148
2149 let (start_indent, _) = display_map.line_indent(start_row);
2150 let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
2151 let mut end = None;
2152 for row in start_row + 1..=max_point.row() {
2153 let (indent, is_blank) = display_map.line_indent(row);
2154 if !is_blank && indent <= start_indent {
2155 end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
2156 break;
2157 }
2158 }
2159
2160 let end = end.unwrap_or(max_point);
2161 return start.to_buffer_point(display_map, Bias::Left)
2162 ..end.to_buffer_point(display_map, Bias::Left);
2163 }
2164
2165 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
2166 let buffer = self.buffer.read(cx);
2167 let ranges = self
2168 .selections(cx.as_ref())
2169 .iter()
2170 .map(|s| s.point_range(buffer).sorted())
2171 .collect();
2172 self.fold_ranges(ranges, cx);
2173 }
2174
2175 fn fold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
2176 if !ranges.is_empty() {
2177 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
2178 self.autoscroll_requested = true;
2179 cx.notify();
2180 }
2181 }
2182
2183 fn unfold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
2184 if !ranges.is_empty() {
2185 self.display_map
2186 .update(cx, |map, cx| map.unfold(ranges, cx));
2187 self.autoscroll_requested = true;
2188 cx.notify();
2189 }
2190 }
2191
2192 pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
2193 self.display_map
2194 .update(cx, |map, cx| map.snapshot(cx))
2195 .longest_row()
2196 }
2197
2198 pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
2199 self.display_map
2200 .update(cx, |map, cx| map.snapshot(cx))
2201 .max_point()
2202 }
2203
2204 pub fn text(&self, cx: &AppContext) -> String {
2205 self.buffer.read(cx).text()
2206 }
2207
2208 pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
2209 self.display_map
2210 .update(cx, |map, cx| map.snapshot(cx))
2211 .text()
2212 }
2213
2214 pub fn font_size(&self) -> f32 {
2215 self.settings.borrow().buffer_font_size
2216 }
2217
2218 pub fn set_wrap_width(&self, width: f32, cx: &mut MutableAppContext) -> bool {
2219 self.display_map
2220 .update(cx, |map, cx| map.set_wrap_width(Some(width), cx))
2221 }
2222
2223 fn next_blink_epoch(&mut self) -> usize {
2224 self.blink_epoch += 1;
2225 self.blink_epoch
2226 }
2227
2228 fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
2229 self.cursors_visible = true;
2230 cx.notify();
2231
2232 let epoch = self.next_blink_epoch();
2233 cx.spawn(|this, mut cx| {
2234 let this = this.downgrade();
2235 async move {
2236 Timer::after(CURSOR_BLINK_INTERVAL).await;
2237 if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
2238 this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
2239 }
2240 }
2241 })
2242 .detach();
2243 }
2244
2245 fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
2246 if epoch == self.blink_epoch {
2247 self.blinking_paused = false;
2248 self.blink_cursors(epoch, cx);
2249 }
2250 }
2251
2252 fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
2253 if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
2254 self.cursors_visible = !self.cursors_visible;
2255 cx.notify();
2256
2257 let epoch = self.next_blink_epoch();
2258 cx.spawn(|this, mut cx| {
2259 let this = this.downgrade();
2260 async move {
2261 Timer::after(CURSOR_BLINK_INTERVAL).await;
2262 if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
2263 this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
2264 }
2265 }
2266 })
2267 .detach();
2268 }
2269 }
2270
2271 pub fn cursors_visible(&self) -> bool {
2272 self.cursors_visible
2273 }
2274
2275 fn on_buffer_changed(&mut self, _: ModelHandle<Buffer>, cx: &mut ViewContext<Self>) {
2276 cx.notify();
2277 }
2278
2279 fn on_buffer_event(
2280 &mut self,
2281 _: ModelHandle<Buffer>,
2282 event: &buffer::Event,
2283 cx: &mut ViewContext<Self>,
2284 ) {
2285 match event {
2286 buffer::Event::Edited => cx.emit(Event::Edited),
2287 buffer::Event::Dirtied => cx.emit(Event::Dirtied),
2288 buffer::Event::Saved => cx.emit(Event::Saved),
2289 buffer::Event::FileHandleChanged => cx.emit(Event::FileHandleChanged),
2290 buffer::Event::Reloaded => cx.emit(Event::FileHandleChanged),
2291 buffer::Event::Reparsed => {}
2292 }
2293 }
2294
2295 fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
2296 cx.notify();
2297 }
2298}
2299
2300impl Snapshot {
2301 pub fn scroll_position(&self) -> Vector2F {
2302 compute_scroll_position(
2303 &self.display_snapshot,
2304 self.scroll_position,
2305 &self.scroll_top_anchor,
2306 )
2307 }
2308
2309 pub fn max_point(&self) -> DisplayPoint {
2310 self.display_snapshot.max_point()
2311 }
2312
2313 pub fn longest_row(&self) -> u32 {
2314 self.display_snapshot.longest_row()
2315 }
2316
2317 pub fn line_len(&self, display_row: u32) -> u32 {
2318 self.display_snapshot.line_len(display_row)
2319 }
2320
2321 pub fn font_ascent(&self, font_cache: &FontCache) -> f32 {
2322 let font_id = font_cache.default_font(self.font_family);
2323 let ascent = font_cache.metric(font_id, |m| m.ascent);
2324 font_cache.scale_metric(ascent, font_id, self.font_size)
2325 }
2326
2327 pub fn font_descent(&self, font_cache: &FontCache) -> f32 {
2328 let font_id = font_cache.default_font(self.font_family);
2329 let descent = font_cache.metric(font_id, |m| m.descent);
2330 font_cache.scale_metric(descent, font_id, self.font_size)
2331 }
2332
2333 pub fn line_height(&self, font_cache: &FontCache) -> f32 {
2334 let font_id = font_cache.default_font(self.font_family);
2335 font_cache.line_height(font_id, self.font_size)
2336 }
2337
2338 pub fn em_width(&self, font_cache: &FontCache) -> f32 {
2339 let font_id = font_cache.default_font(self.font_family);
2340 font_cache.em_width(font_id, self.font_size)
2341 }
2342
2343 // TODO: Can we make this not return a result?
2344 pub fn max_line_number_width(
2345 &self,
2346 font_cache: &FontCache,
2347 layout_cache: &TextLayoutCache,
2348 ) -> Result<f32> {
2349 let font_size = self.font_size;
2350 let font_id = font_cache.select_font(self.font_family, &FontProperties::new())?;
2351 let digit_count = (self.display_snapshot.buffer_row_count() as f32)
2352 .log10()
2353 .floor() as usize
2354 + 1;
2355
2356 Ok(layout_cache
2357 .layout_str(
2358 "1".repeat(digit_count).as_str(),
2359 font_size,
2360 &[(digit_count, font_id, Color::black())],
2361 )
2362 .width())
2363 }
2364
2365 pub fn layout_line_numbers(
2366 &self,
2367 rows: Range<u32>,
2368 active_rows: &BTreeMap<u32, bool>,
2369 font_cache: &FontCache,
2370 layout_cache: &TextLayoutCache,
2371 theme: &Theme,
2372 ) -> Result<Vec<Option<text_layout::Line>>> {
2373 let font_id = font_cache.select_font(self.font_family, &FontProperties::new())?;
2374
2375 let mut layouts = Vec::with_capacity(rows.len());
2376 let mut line_number = String::new();
2377 for (ix, (buffer_row, soft_wrapped)) in self
2378 .display_snapshot
2379 .buffer_rows(rows.start)
2380 .take((rows.end - rows.start) as usize)
2381 .enumerate()
2382 {
2383 let display_row = rows.start + ix as u32;
2384 let color = if active_rows.contains_key(&display_row) {
2385 theme.editor.line_number_active
2386 } else {
2387 theme.editor.line_number
2388 };
2389 if soft_wrapped {
2390 layouts.push(None);
2391 } else {
2392 line_number.clear();
2393 write!(&mut line_number, "{}", buffer_row + 1).unwrap();
2394 layouts.push(Some(layout_cache.layout_str(
2395 &line_number,
2396 self.font_size,
2397 &[(line_number.len(), font_id, color)],
2398 )));
2399 }
2400 }
2401
2402 Ok(layouts)
2403 }
2404
2405 pub fn layout_lines(
2406 &mut self,
2407 mut rows: Range<u32>,
2408 style: &EditorStyle,
2409 font_cache: &FontCache,
2410 layout_cache: &TextLayoutCache,
2411 ) -> Result<Vec<text_layout::Line>> {
2412 rows.end = cmp::min(rows.end, self.display_snapshot.max_point().row() + 1);
2413 if rows.start >= rows.end {
2414 return Ok(Vec::new());
2415 }
2416
2417 // When the editor is empty and unfocused, then show the placeholder.
2418 if self.display_snapshot.is_empty() && !self.is_focused {
2419 let placeholder_lines = self
2420 .placeholder_text
2421 .as_ref()
2422 .map_or("", AsRef::as_ref)
2423 .split('\n')
2424 .skip(rows.start as usize)
2425 .take(rows.len());
2426 let font_id = font_cache
2427 .select_font(self.font_family, &style.placeholder_text.font_properties)?;
2428 return Ok(placeholder_lines
2429 .into_iter()
2430 .map(|line| {
2431 layout_cache.layout_str(
2432 line,
2433 self.font_size,
2434 &[(line.len(), font_id, style.placeholder_text.color)],
2435 )
2436 })
2437 .collect());
2438 }
2439
2440 let mut prev_font_properties = FontProperties::new();
2441 let mut prev_font_id = font_cache
2442 .select_font(self.font_family, &prev_font_properties)
2443 .unwrap();
2444
2445 let mut layouts = Vec::with_capacity(rows.len());
2446 let mut line = String::new();
2447 let mut styles = Vec::new();
2448 let mut row = rows.start;
2449 let mut line_exceeded_max_len = false;
2450 let chunks = self
2451 .display_snapshot
2452 .highlighted_chunks_for_rows(rows.clone());
2453
2454 'outer: for (chunk, style_ix) in chunks.chain(Some(("\n", HighlightId::default()))) {
2455 for (ix, mut line_chunk) in chunk.split('\n').enumerate() {
2456 if ix > 0 {
2457 layouts.push(layout_cache.layout_str(&line, self.font_size, &styles));
2458 line.clear();
2459 styles.clear();
2460 row += 1;
2461 line_exceeded_max_len = false;
2462 if row == rows.end {
2463 break 'outer;
2464 }
2465 }
2466
2467 if !line_chunk.is_empty() && !line_exceeded_max_len {
2468 let style = self
2469 .theme
2470 .syntax
2471 .highlight_style(style_ix)
2472 .unwrap_or(style.text.clone());
2473 // Avoid a lookup if the font properties match the previous ones.
2474 let font_id = if style.font_properties == prev_font_properties {
2475 prev_font_id
2476 } else {
2477 font_cache.select_font(self.font_family, &style.font_properties)?
2478 };
2479
2480 if line.len() + line_chunk.len() > MAX_LINE_LEN {
2481 let mut chunk_len = MAX_LINE_LEN - line.len();
2482 while !line_chunk.is_char_boundary(chunk_len) {
2483 chunk_len -= 1;
2484 }
2485 line_chunk = &line_chunk[..chunk_len];
2486 line_exceeded_max_len = true;
2487 }
2488
2489 line.push_str(line_chunk);
2490 styles.push((line_chunk.len(), font_id, style.color));
2491 prev_font_id = font_id;
2492 prev_font_properties = style.font_properties;
2493 }
2494 }
2495 }
2496
2497 Ok(layouts)
2498 }
2499
2500 pub fn layout_line(
2501 &self,
2502 row: u32,
2503 font_cache: &FontCache,
2504 layout_cache: &TextLayoutCache,
2505 ) -> Result<text_layout::Line> {
2506 let font_id = font_cache.select_font(self.font_family, &FontProperties::new())?;
2507
2508 let mut line = self.display_snapshot.line(row);
2509
2510 if line.len() > MAX_LINE_LEN {
2511 let mut len = MAX_LINE_LEN;
2512 while !line.is_char_boundary(len) {
2513 len -= 1;
2514 }
2515 line.truncate(len);
2516 }
2517
2518 Ok(layout_cache.layout_str(
2519 &line,
2520 self.font_size,
2521 &[(
2522 self.display_snapshot.line_len(row) as usize,
2523 font_id,
2524 Color::black(),
2525 )],
2526 ))
2527 }
2528
2529 pub fn prev_row_boundary(&self, point: DisplayPoint) -> (DisplayPoint, Point) {
2530 self.display_snapshot.prev_row_boundary(point)
2531 }
2532
2533 pub fn next_row_boundary(&self, point: DisplayPoint) -> (DisplayPoint, Point) {
2534 self.display_snapshot.next_row_boundary(point)
2535 }
2536}
2537
2538fn compute_scroll_position(
2539 snapshot: &DisplayMapSnapshot,
2540 mut scroll_position: Vector2F,
2541 scroll_top_anchor: &Anchor,
2542) -> Vector2F {
2543 let scroll_top = scroll_top_anchor
2544 .to_display_point(snapshot, Bias::Left)
2545 .row() as f32;
2546 scroll_position.set_y(scroll_top + scroll_position.y());
2547 scroll_position
2548}
2549
2550pub enum Event {
2551 Activate,
2552 Edited,
2553 Blurred,
2554 Dirtied,
2555 Saved,
2556 FileHandleChanged,
2557}
2558
2559impl Entity for Editor {
2560 type Event = Event;
2561
2562 fn release(&mut self, cx: &mut MutableAppContext) {
2563 self.buffer.update(cx, |buffer, cx| {
2564 buffer
2565 .remove_selection_set(self.selection_set_id, cx)
2566 .unwrap();
2567 });
2568 }
2569}
2570
2571impl View for Editor {
2572 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
2573 let style = self
2574 .build_style
2575 .as_ref()
2576 .map_or(Default::default(), |build| (build.borrow_mut())(cx));
2577 EditorElement::new(self.handle.clone(), style).boxed()
2578 }
2579
2580 fn ui_name() -> &'static str {
2581 "Editor"
2582 }
2583
2584 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
2585 self.focused = true;
2586 self.blink_cursors(self.blink_epoch, cx);
2587 self.buffer.update(cx, |buffer, cx| {
2588 buffer
2589 .set_active_selection_set(Some(self.selection_set_id), cx)
2590 .unwrap();
2591 });
2592 }
2593
2594 fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
2595 self.focused = false;
2596 self.cursors_visible = false;
2597 self.buffer.update(cx, |buffer, cx| {
2598 buffer.set_active_selection_set(None, cx).unwrap();
2599 });
2600 cx.emit(Event::Blurred);
2601 cx.notify();
2602 }
2603
2604 fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
2605 let mut cx = Self::default_keymap_context();
2606 let mode = match self.mode {
2607 EditorMode::SingleLine => "single_line",
2608 EditorMode::AutoHeight { .. } => "auto_height",
2609 EditorMode::Full => "full",
2610 };
2611 cx.map.insert("mode".into(), mode.into());
2612 cx
2613 }
2614}
2615
2616impl workspace::Item for Buffer {
2617 type View = Editor;
2618
2619 fn file(&self) -> Option<&File> {
2620 self.file()
2621 }
2622
2623 fn build_view(
2624 handle: ModelHandle<Self>,
2625 settings: watch::Receiver<Settings>,
2626 cx: &mut ViewContext<Self::View>,
2627 ) -> Self::View {
2628 Editor::for_buffer(handle, settings.clone(), cx)
2629 .with_style(move |_| settings.borrow().theme.editor.clone())
2630 }
2631}
2632
2633impl workspace::ItemView for Editor {
2634 fn should_activate_item_on_event(event: &Self::Event) -> bool {
2635 matches!(event, Event::Activate)
2636 }
2637
2638 fn should_update_tab_on_event(event: &Self::Event) -> bool {
2639 matches!(
2640 event,
2641 Event::Saved | Event::Dirtied | Event::FileHandleChanged
2642 )
2643 }
2644
2645 fn title(&self, cx: &AppContext) -> std::string::String {
2646 let filename = self
2647 .buffer
2648 .read(cx)
2649 .file()
2650 .and_then(|file| file.file_name(cx));
2651 if let Some(name) = filename {
2652 name.to_string_lossy().into()
2653 } else {
2654 "untitled".into()
2655 }
2656 }
2657
2658 fn entry_id(&self, cx: &AppContext) -> Option<(usize, Arc<Path>)> {
2659 self.buffer.read(cx).file().map(|file| file.entry_id())
2660 }
2661
2662 fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
2663 where
2664 Self: Sized,
2665 {
2666 let mut clone = Editor::for_buffer(self.buffer.clone(), self.settings.clone(), cx);
2667 clone.scroll_position = self.scroll_position;
2668 clone.scroll_top_anchor = self.scroll_top_anchor.clone();
2669 clone.build_style = self.build_style.clone();
2670 Some(clone)
2671 }
2672
2673 fn save(&mut self, cx: &mut ViewContext<Self>) -> Result<Task<Result<()>>> {
2674 let save = self.buffer.update(cx, |b, cx| b.save(cx))?;
2675 Ok(cx.spawn(|_, _| async move {
2676 save.await?;
2677 Ok(())
2678 }))
2679 }
2680
2681 fn save_as(
2682 &mut self,
2683 worktree: &ModelHandle<Worktree>,
2684 path: &Path,
2685 cx: &mut ViewContext<Self>,
2686 ) -> Task<Result<()>> {
2687 self.buffer
2688 .update(cx, |b, cx| b.save_as(worktree, path, cx))
2689 }
2690
2691 fn is_dirty(&self, cx: &AppContext) -> bool {
2692 self.buffer.read(cx).is_dirty()
2693 }
2694
2695 fn has_conflict(&self, cx: &AppContext) -> bool {
2696 self.buffer.read(cx).has_conflict()
2697 }
2698}
2699
2700#[cfg(test)]
2701mod tests {
2702 use super::*;
2703 use crate::{editor::Point, language::LanguageRegistry, settings, test::sample_text};
2704 use buffer::History;
2705 use unindent::Unindent;
2706
2707 #[gpui::test]
2708 fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
2709 let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
2710 let settings = settings::test(&cx).1;
2711 let (_, editor) = cx.add_window(Default::default(), |cx| {
2712 Editor::for_buffer(buffer, settings, cx)
2713 });
2714
2715 editor.update(cx, |view, cx| {
2716 view.begin_selection(DisplayPoint::new(2, 2), false, cx);
2717 });
2718
2719 assert_eq!(
2720 editor.update(cx, |view, cx| view.selection_ranges(cx)),
2721 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
2722 );
2723
2724 editor.update(cx, |view, cx| {
2725 view.update_selection(DisplayPoint::new(3, 3), Vector2F::zero(), cx);
2726 });
2727
2728 assert_eq!(
2729 editor.update(cx, |view, cx| view.selection_ranges(cx)),
2730 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
2731 );
2732
2733 editor.update(cx, |view, cx| {
2734 view.update_selection(DisplayPoint::new(1, 1), Vector2F::zero(), cx);
2735 });
2736
2737 assert_eq!(
2738 editor.update(cx, |view, cx| view.selection_ranges(cx)),
2739 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
2740 );
2741
2742 editor.update(cx, |view, cx| {
2743 view.end_selection(cx);
2744 view.update_selection(DisplayPoint::new(3, 3), Vector2F::zero(), cx);
2745 });
2746
2747 assert_eq!(
2748 editor.update(cx, |view, cx| view.selection_ranges(cx)),
2749 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
2750 );
2751
2752 editor.update(cx, |view, cx| {
2753 view.begin_selection(DisplayPoint::new(3, 3), true, cx);
2754 view.update_selection(DisplayPoint::new(0, 0), Vector2F::zero(), cx);
2755 });
2756
2757 assert_eq!(
2758 editor.update(cx, |view, cx| view.selection_ranges(cx)),
2759 [
2760 DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
2761 DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
2762 ]
2763 );
2764
2765 editor.update(cx, |view, cx| {
2766 view.end_selection(cx);
2767 });
2768
2769 assert_eq!(
2770 editor.update(cx, |view, cx| view.selection_ranges(cx)),
2771 [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
2772 );
2773 }
2774
2775 #[gpui::test]
2776 fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
2777 let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
2778 let settings = settings::test(&cx).1;
2779 let (_, view) = cx.add_window(Default::default(), |cx| {
2780 Editor::for_buffer(buffer, settings, cx)
2781 });
2782
2783 view.update(cx, |view, cx| {
2784 view.begin_selection(DisplayPoint::new(2, 2), false, cx);
2785 assert_eq!(
2786 view.selection_ranges(cx),
2787 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
2788 );
2789 });
2790
2791 view.update(cx, |view, cx| {
2792 view.update_selection(DisplayPoint::new(3, 3), Vector2F::zero(), cx);
2793 assert_eq!(
2794 view.selection_ranges(cx),
2795 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
2796 );
2797 });
2798
2799 view.update(cx, |view, cx| {
2800 view.cancel(&Cancel, cx);
2801 view.update_selection(DisplayPoint::new(1, 1), Vector2F::zero(), cx);
2802 assert_eq!(
2803 view.selection_ranges(cx),
2804 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
2805 );
2806 });
2807 }
2808
2809 #[gpui::test]
2810 fn test_cancel(cx: &mut gpui::MutableAppContext) {
2811 let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
2812 let settings = settings::test(&cx).1;
2813 let (_, view) = cx.add_window(Default::default(), |cx| {
2814 Editor::for_buffer(buffer, settings, cx)
2815 });
2816
2817 view.update(cx, |view, cx| {
2818 view.begin_selection(DisplayPoint::new(3, 4), false, cx);
2819 view.update_selection(DisplayPoint::new(1, 1), Vector2F::zero(), cx);
2820 view.end_selection(cx);
2821
2822 view.begin_selection(DisplayPoint::new(0, 1), true, cx);
2823 view.update_selection(DisplayPoint::new(0, 3), Vector2F::zero(), cx);
2824 view.end_selection(cx);
2825 assert_eq!(
2826 view.selection_ranges(cx),
2827 [
2828 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
2829 DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
2830 ]
2831 );
2832 });
2833
2834 view.update(cx, |view, cx| {
2835 view.cancel(&Cancel, cx);
2836 assert_eq!(
2837 view.selection_ranges(cx),
2838 [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
2839 );
2840 });
2841
2842 view.update(cx, |view, cx| {
2843 view.cancel(&Cancel, cx);
2844 assert_eq!(
2845 view.selection_ranges(cx),
2846 [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
2847 );
2848 });
2849 }
2850
2851 #[gpui::test]
2852 fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
2853 let layout_cache = TextLayoutCache::new(cx.platform().fonts());
2854 let font_cache = cx.font_cache().clone();
2855
2856 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6), cx));
2857
2858 let settings = settings::test(&cx).1;
2859 let (_, editor) = cx.add_window(Default::default(), |cx| {
2860 Editor::for_buffer(buffer.clone(), settings.clone(), cx)
2861 });
2862
2863 let layouts = editor.update(cx, |editor, cx| {
2864 editor
2865 .snapshot(cx)
2866 .layout_line_numbers(
2867 0..6,
2868 &Default::default(),
2869 &font_cache,
2870 &layout_cache,
2871 &settings.borrow().theme,
2872 )
2873 .unwrap()
2874 });
2875 assert_eq!(layouts.len(), 6);
2876 }
2877
2878 #[gpui::test]
2879 fn test_fold(cx: &mut gpui::MutableAppContext) {
2880 let buffer = cx.add_model(|cx| {
2881 Buffer::new(
2882 0,
2883 "
2884 impl Foo {
2885 // Hello!
2886
2887 fn a() {
2888 1
2889 }
2890
2891 fn b() {
2892 2
2893 }
2894
2895 fn c() {
2896 3
2897 }
2898 }
2899 "
2900 .unindent(),
2901 cx,
2902 )
2903 });
2904 let settings = settings::test(&cx).1;
2905 let (_, view) = cx.add_window(Default::default(), |cx| {
2906 Editor::for_buffer(buffer.clone(), settings, cx)
2907 });
2908
2909 view.update(cx, |view, cx| {
2910 view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx)
2911 .unwrap();
2912 view.fold(&Fold, cx);
2913 assert_eq!(
2914 view.display_text(cx),
2915 "
2916 impl Foo {
2917 // Hello!
2918
2919 fn a() {
2920 1
2921 }
2922
2923 fn b() {…
2924 }
2925
2926 fn c() {…
2927 }
2928 }
2929 "
2930 .unindent(),
2931 );
2932
2933 view.fold(&Fold, cx);
2934 assert_eq!(
2935 view.display_text(cx),
2936 "
2937 impl Foo {…
2938 }
2939 "
2940 .unindent(),
2941 );
2942
2943 view.unfold(&Unfold, cx);
2944 assert_eq!(
2945 view.display_text(cx),
2946 "
2947 impl Foo {
2948 // Hello!
2949
2950 fn a() {
2951 1
2952 }
2953
2954 fn b() {…
2955 }
2956
2957 fn c() {…
2958 }
2959 }
2960 "
2961 .unindent(),
2962 );
2963
2964 view.unfold(&Unfold, cx);
2965 assert_eq!(view.display_text(cx), buffer.read(cx).text());
2966 });
2967 }
2968
2969 #[gpui::test]
2970 fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
2971 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6), cx));
2972 let settings = settings::test(&cx).1;
2973 let (_, view) = cx.add_window(Default::default(), |cx| {
2974 Editor::for_buffer(buffer.clone(), settings, cx)
2975 });
2976
2977 buffer.update(cx, |buffer, cx| {
2978 buffer.edit(
2979 vec![
2980 Point::new(1, 0)..Point::new(1, 0),
2981 Point::new(1, 1)..Point::new(1, 1),
2982 ],
2983 "\t",
2984 cx,
2985 );
2986 });
2987
2988 view.update(cx, |view, cx| {
2989 assert_eq!(
2990 view.selection_ranges(cx),
2991 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
2992 );
2993
2994 view.move_down(&MoveDown, cx);
2995 assert_eq!(
2996 view.selection_ranges(cx),
2997 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
2998 );
2999
3000 view.move_right(&MoveRight, cx);
3001 assert_eq!(
3002 view.selection_ranges(cx),
3003 &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
3004 );
3005
3006 view.move_left(&MoveLeft, cx);
3007 assert_eq!(
3008 view.selection_ranges(cx),
3009 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
3010 );
3011
3012 view.move_up(&MoveUp, cx);
3013 assert_eq!(
3014 view.selection_ranges(cx),
3015 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
3016 );
3017
3018 view.move_to_end(&MoveToEnd, cx);
3019 assert_eq!(
3020 view.selection_ranges(cx),
3021 &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
3022 );
3023
3024 view.move_to_beginning(&MoveToBeginning, cx);
3025 assert_eq!(
3026 view.selection_ranges(cx),
3027 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
3028 );
3029
3030 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx)
3031 .unwrap();
3032 view.select_to_beginning(&SelectToBeginning, cx);
3033 assert_eq!(
3034 view.selection_ranges(cx),
3035 &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
3036 );
3037
3038 view.select_to_end(&SelectToEnd, cx);
3039 assert_eq!(
3040 view.selection_ranges(cx),
3041 &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
3042 );
3043 });
3044 }
3045
3046 #[gpui::test]
3047 fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
3048 let buffer = cx.add_model(|cx| Buffer::new(0, "ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx));
3049 let settings = settings::test(&cx).1;
3050 let (_, view) = cx.add_window(Default::default(), |cx| {
3051 Editor::for_buffer(buffer.clone(), settings, cx)
3052 });
3053
3054 assert_eq!('ⓐ'.len_utf8(), 3);
3055 assert_eq!('α'.len_utf8(), 2);
3056
3057 view.update(cx, |view, cx| {
3058 view.fold_ranges(
3059 vec![
3060 Point::new(0, 6)..Point::new(0, 12),
3061 Point::new(1, 2)..Point::new(1, 4),
3062 Point::new(2, 4)..Point::new(2, 8),
3063 ],
3064 cx,
3065 );
3066 assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
3067
3068 view.move_right(&MoveRight, cx);
3069 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐ".len())]);
3070 view.move_right(&MoveRight, cx);
3071 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ".len())]);
3072 view.move_right(&MoveRight, cx);
3073 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…".len())]);
3074
3075 view.move_down(&MoveDown, cx);
3076 assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab…".len())]);
3077 view.move_left(&MoveLeft, cx);
3078 assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab".len())]);
3079 view.move_left(&MoveLeft, cx);
3080 assert_eq!(view.selection_ranges(cx), &[empty_range(1, "a".len())]);
3081
3082 view.move_down(&MoveDown, cx);
3083 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "α".len())]);
3084 view.move_right(&MoveRight, cx);
3085 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ".len())]);
3086 view.move_right(&MoveRight, cx);
3087 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ…".len())]);
3088 view.move_right(&MoveRight, cx);
3089 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ…ε".len())]);
3090
3091 view.move_up(&MoveUp, cx);
3092 assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab…e".len())]);
3093 view.move_up(&MoveUp, cx);
3094 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…ⓔ".len())]);
3095 view.move_left(&MoveLeft, cx);
3096 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…".len())]);
3097 view.move_left(&MoveLeft, cx);
3098 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ".len())]);
3099 view.move_left(&MoveLeft, cx);
3100 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐ".len())]);
3101 });
3102 }
3103
3104 #[gpui::test]
3105 fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
3106 let buffer = cx.add_model(|cx| Buffer::new(0, "ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx));
3107 let settings = settings::test(&cx).1;
3108 let (_, view) = cx.add_window(Default::default(), |cx| {
3109 Editor::for_buffer(buffer.clone(), settings, cx)
3110 });
3111 view.update(cx, |view, cx| {
3112 view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx)
3113 .unwrap();
3114
3115 view.move_down(&MoveDown, cx);
3116 assert_eq!(view.selection_ranges(cx), &[empty_range(1, "abcd".len())]);
3117
3118 view.move_down(&MoveDown, cx);
3119 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβγ".len())]);
3120
3121 view.move_down(&MoveDown, cx);
3122 assert_eq!(view.selection_ranges(cx), &[empty_range(3, "abcd".len())]);
3123
3124 view.move_down(&MoveDown, cx);
3125 assert_eq!(view.selection_ranges(cx), &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]);
3126
3127 view.move_up(&MoveUp, cx);
3128 assert_eq!(view.selection_ranges(cx), &[empty_range(3, "abcd".len())]);
3129
3130 view.move_up(&MoveUp, cx);
3131 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβγ".len())]);
3132 });
3133 }
3134
3135 #[gpui::test]
3136 fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
3137 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\n def", cx));
3138 let settings = settings::test(&cx).1;
3139 let (_, view) = cx.add_window(Default::default(), |cx| {
3140 Editor::for_buffer(buffer, settings, cx)
3141 });
3142 view.update(cx, |view, cx| {
3143 view.select_display_ranges(
3144 &[
3145 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
3146 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
3147 ],
3148 cx,
3149 )
3150 .unwrap();
3151 });
3152
3153 view.update(cx, |view, cx| {
3154 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
3155 assert_eq!(
3156 view.selection_ranges(cx),
3157 &[
3158 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3159 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
3160 ]
3161 );
3162 });
3163
3164 view.update(cx, |view, cx| {
3165 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
3166 assert_eq!(
3167 view.selection_ranges(cx),
3168 &[
3169 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3170 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3171 ]
3172 );
3173 });
3174
3175 view.update(cx, |view, cx| {
3176 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
3177 assert_eq!(
3178 view.selection_ranges(cx),
3179 &[
3180 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3181 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
3182 ]
3183 );
3184 });
3185
3186 view.update(cx, |view, cx| {
3187 view.move_to_end_of_line(&MoveToEndOfLine, cx);
3188 assert_eq!(
3189 view.selection_ranges(cx),
3190 &[
3191 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3192 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
3193 ]
3194 );
3195 });
3196
3197 // Moving to the end of line again is a no-op.
3198 view.update(cx, |view, cx| {
3199 view.move_to_end_of_line(&MoveToEndOfLine, cx);
3200 assert_eq!(
3201 view.selection_ranges(cx),
3202 &[
3203 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3204 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
3205 ]
3206 );
3207 });
3208
3209 view.update(cx, |view, cx| {
3210 view.move_left(&MoveLeft, cx);
3211 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
3212 assert_eq!(
3213 view.selection_ranges(cx),
3214 &[
3215 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
3216 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
3217 ]
3218 );
3219 });
3220
3221 view.update(cx, |view, cx| {
3222 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
3223 assert_eq!(
3224 view.selection_ranges(cx),
3225 &[
3226 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
3227 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
3228 ]
3229 );
3230 });
3231
3232 view.update(cx, |view, cx| {
3233 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
3234 assert_eq!(
3235 view.selection_ranges(cx),
3236 &[
3237 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
3238 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
3239 ]
3240 );
3241 });
3242
3243 view.update(cx, |view, cx| {
3244 view.select_to_end_of_line(&SelectToEndOfLine, cx);
3245 assert_eq!(
3246 view.selection_ranges(cx),
3247 &[
3248 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
3249 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
3250 ]
3251 );
3252 });
3253
3254 view.update(cx, |view, cx| {
3255 view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
3256 assert_eq!(view.display_text(cx), "ab\n de");
3257 assert_eq!(
3258 view.selection_ranges(cx),
3259 &[
3260 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3261 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
3262 ]
3263 );
3264 });
3265
3266 view.update(cx, |view, cx| {
3267 view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
3268 assert_eq!(view.display_text(cx), "\n");
3269 assert_eq!(
3270 view.selection_ranges(cx),
3271 &[
3272 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3273 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3274 ]
3275 );
3276 });
3277 }
3278
3279 #[gpui::test]
3280 fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
3281 let buffer =
3282 cx.add_model(|cx| Buffer::new(0, "use std::str::{foo, bar}\n\n {baz.qux()}", cx));
3283 let settings = settings::test(&cx).1;
3284 let (_, view) = cx.add_window(Default::default(), |cx| {
3285 Editor::for_buffer(buffer, settings, cx)
3286 });
3287 view.update(cx, |view, cx| {
3288 view.select_display_ranges(
3289 &[
3290 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
3291 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
3292 ],
3293 cx,
3294 )
3295 .unwrap();
3296 });
3297
3298 view.update(cx, |view, cx| {
3299 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3300 assert_eq!(
3301 view.selection_ranges(cx),
3302 &[
3303 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
3304 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
3305 ]
3306 );
3307 });
3308
3309 view.update(cx, |view, cx| {
3310 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3311 assert_eq!(
3312 view.selection_ranges(cx),
3313 &[
3314 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
3315 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
3316 ]
3317 );
3318 });
3319
3320 view.update(cx, |view, cx| {
3321 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3322 assert_eq!(
3323 view.selection_ranges(cx),
3324 &[
3325 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
3326 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
3327 ]
3328 );
3329 });
3330
3331 view.update(cx, |view, cx| {
3332 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3333 assert_eq!(
3334 view.selection_ranges(cx),
3335 &[
3336 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3337 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3338 ]
3339 );
3340 });
3341
3342 view.update(cx, |view, cx| {
3343 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3344 assert_eq!(
3345 view.selection_ranges(cx),
3346 &[
3347 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3348 DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
3349 ]
3350 );
3351 });
3352
3353 view.update(cx, |view, cx| {
3354 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3355 assert_eq!(
3356 view.selection_ranges(cx),
3357 &[
3358 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3359 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
3360 ]
3361 );
3362 });
3363
3364 view.update(cx, |view, cx| {
3365 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3366 assert_eq!(
3367 view.selection_ranges(cx),
3368 &[
3369 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3370 DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
3371 ]
3372 );
3373 });
3374
3375 view.update(cx, |view, cx| {
3376 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3377 assert_eq!(
3378 view.selection_ranges(cx),
3379 &[
3380 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
3381 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3382 ]
3383 );
3384 });
3385
3386 view.update(cx, |view, cx| {
3387 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3388 assert_eq!(
3389 view.selection_ranges(cx),
3390 &[
3391 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
3392 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
3393 ]
3394 );
3395 });
3396
3397 view.update(cx, |view, cx| {
3398 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3399 assert_eq!(
3400 view.selection_ranges(cx),
3401 &[
3402 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
3403 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
3404 ]
3405 );
3406 });
3407
3408 view.update(cx, |view, cx| {
3409 view.move_right(&MoveRight, cx);
3410 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
3411 assert_eq!(
3412 view.selection_ranges(cx),
3413 &[
3414 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
3415 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 2),
3416 ]
3417 );
3418 });
3419
3420 view.update(cx, |view, cx| {
3421 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
3422 assert_eq!(
3423 view.selection_ranges(cx),
3424 &[
3425 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
3426 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 0),
3427 ]
3428 );
3429 });
3430
3431 view.update(cx, |view, cx| {
3432 view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
3433 assert_eq!(
3434 view.selection_ranges(cx),
3435 &[
3436 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
3437 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 2),
3438 ]
3439 );
3440 });
3441
3442 view.update(cx, |view, cx| {
3443 view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
3444 assert_eq!(
3445 view.display_text(cx),
3446 "use std::s::{foo, bar}\n\n {az.qux()}"
3447 );
3448 assert_eq!(
3449 view.selection_ranges(cx),
3450 &[
3451 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 10),
3452 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
3453 ]
3454 );
3455 });
3456
3457 view.update(cx, |view, cx| {
3458 view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
3459 assert_eq!(
3460 view.display_text(cx),
3461 "use std::::{foo, bar}\n\n az.qux()}"
3462 );
3463 assert_eq!(
3464 view.selection_ranges(cx),
3465 &[
3466 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
3467 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
3468 ]
3469 );
3470 });
3471 }
3472
3473 #[gpui::test]
3474 fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
3475 let buffer =
3476 cx.add_model(|cx| Buffer::new(0, "use one::{\n two::three::four::five\n};", cx));
3477 let settings = settings::test(&cx).1;
3478 let (_, view) = cx.add_window(Default::default(), |cx| {
3479 Editor::for_buffer(buffer, settings, cx)
3480 });
3481
3482 view.update(cx, |view, cx| {
3483 view.set_wrap_width(140., cx);
3484 assert_eq!(
3485 view.display_text(cx),
3486 "use one::{\n two::three::\n four::five\n};"
3487 );
3488
3489 view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx)
3490 .unwrap();
3491
3492 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3493 assert_eq!(
3494 view.selection_ranges(cx),
3495 &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
3496 );
3497
3498 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3499 assert_eq!(
3500 view.selection_ranges(cx),
3501 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
3502 );
3503
3504 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3505 assert_eq!(
3506 view.selection_ranges(cx),
3507 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
3508 );
3509
3510 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3511 assert_eq!(
3512 view.selection_ranges(cx),
3513 &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
3514 );
3515
3516 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3517 assert_eq!(
3518 view.selection_ranges(cx),
3519 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
3520 );
3521
3522 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3523 assert_eq!(
3524 view.selection_ranges(cx),
3525 &[DisplayPoint::new(1, 15)..DisplayPoint::new(1, 15)]
3526 );
3527 });
3528 }
3529
3530 #[gpui::test]
3531 fn test_backspace(cx: &mut gpui::MutableAppContext) {
3532 let buffer = cx.add_model(|cx| {
3533 Buffer::new(
3534 0,
3535 "one two three\nfour five six\nseven eight nine\nten\n",
3536 cx,
3537 )
3538 });
3539 let settings = settings::test(&cx).1;
3540 let (_, view) = cx.add_window(Default::default(), |cx| {
3541 Editor::for_buffer(buffer.clone(), settings, cx)
3542 });
3543
3544 view.update(cx, |view, cx| {
3545 view.select_display_ranges(
3546 &[
3547 // an empty selection - the preceding character is deleted
3548 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3549 // one character selected - it is deleted
3550 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
3551 // a line suffix selected - it is deleted
3552 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
3553 ],
3554 cx,
3555 )
3556 .unwrap();
3557 view.backspace(&Backspace, cx);
3558 });
3559
3560 assert_eq!(
3561 buffer.read(cx).text(),
3562 "oe two three\nfou five six\nseven ten\n"
3563 );
3564 }
3565
3566 #[gpui::test]
3567 fn test_delete(cx: &mut gpui::MutableAppContext) {
3568 let buffer = cx.add_model(|cx| {
3569 Buffer::new(
3570 0,
3571 "one two three\nfour five six\nseven eight nine\nten\n",
3572 cx,
3573 )
3574 });
3575 let settings = settings::test(&cx).1;
3576 let (_, view) = cx.add_window(Default::default(), |cx| {
3577 Editor::for_buffer(buffer.clone(), settings, cx)
3578 });
3579
3580 view.update(cx, |view, cx| {
3581 view.select_display_ranges(
3582 &[
3583 // an empty selection - the following character is deleted
3584 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3585 // one character selected - it is deleted
3586 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
3587 // a line suffix selected - it is deleted
3588 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
3589 ],
3590 cx,
3591 )
3592 .unwrap();
3593 view.delete(&Delete, cx);
3594 });
3595
3596 assert_eq!(
3597 buffer.read(cx).text(),
3598 "on two three\nfou five six\nseven ten\n"
3599 );
3600 }
3601
3602 #[gpui::test]
3603 fn test_delete_line(cx: &mut gpui::MutableAppContext) {
3604 let settings = settings::test(&cx).1;
3605 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
3606 let (_, view) = cx.add_window(Default::default(), |cx| {
3607 Editor::for_buffer(buffer, settings, cx)
3608 });
3609 view.update(cx, |view, cx| {
3610 view.select_display_ranges(
3611 &[
3612 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
3613 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
3614 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
3615 ],
3616 cx,
3617 )
3618 .unwrap();
3619 view.delete_line(&DeleteLine, cx);
3620 assert_eq!(view.display_text(cx), "ghi");
3621 assert_eq!(
3622 view.selection_ranges(cx),
3623 vec![
3624 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3625 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
3626 ]
3627 );
3628 });
3629
3630 let settings = settings::test(&cx).1;
3631 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
3632 let (_, view) = cx.add_window(Default::default(), |cx| {
3633 Editor::for_buffer(buffer, settings, cx)
3634 });
3635 view.update(cx, |view, cx| {
3636 view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx)
3637 .unwrap();
3638 view.delete_line(&DeleteLine, cx);
3639 assert_eq!(view.display_text(cx), "ghi\n");
3640 assert_eq!(
3641 view.selection_ranges(cx),
3642 vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
3643 );
3644 });
3645 }
3646
3647 #[gpui::test]
3648 fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
3649 let settings = settings::test(&cx).1;
3650 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
3651 let (_, view) = cx.add_window(Default::default(), |cx| {
3652 Editor::for_buffer(buffer, settings, cx)
3653 });
3654 view.update(cx, |view, cx| {
3655 view.select_display_ranges(
3656 &[
3657 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
3658 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3659 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3660 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
3661 ],
3662 cx,
3663 )
3664 .unwrap();
3665 view.duplicate_line(&DuplicateLine, cx);
3666 assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
3667 assert_eq!(
3668 view.selection_ranges(cx),
3669 vec![
3670 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
3671 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
3672 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
3673 DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
3674 ]
3675 );
3676 });
3677
3678 let settings = settings::test(&cx).1;
3679 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
3680 let (_, view) = cx.add_window(Default::default(), |cx| {
3681 Editor::for_buffer(buffer, settings, cx)
3682 });
3683 view.update(cx, |view, cx| {
3684 view.select_display_ranges(
3685 &[
3686 DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
3687 DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
3688 ],
3689 cx,
3690 )
3691 .unwrap();
3692 view.duplicate_line(&DuplicateLine, cx);
3693 assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
3694 assert_eq!(
3695 view.selection_ranges(cx),
3696 vec![
3697 DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
3698 DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
3699 ]
3700 );
3701 });
3702 }
3703
3704 #[gpui::test]
3705 fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
3706 let settings = settings::test(&cx).1;
3707 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(10, 5), cx));
3708 let (_, view) = cx.add_window(Default::default(), |cx| {
3709 Editor::for_buffer(buffer, settings, cx)
3710 });
3711 view.update(cx, |view, cx| {
3712 view.fold_ranges(
3713 vec![
3714 Point::new(0, 2)..Point::new(1, 2),
3715 Point::new(2, 3)..Point::new(4, 1),
3716 Point::new(7, 0)..Point::new(8, 4),
3717 ],
3718 cx,
3719 );
3720 view.select_display_ranges(
3721 &[
3722 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
3723 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
3724 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
3725 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
3726 ],
3727 cx,
3728 )
3729 .unwrap();
3730 assert_eq!(
3731 view.display_text(cx),
3732 "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
3733 );
3734
3735 view.move_line_up(&MoveLineUp, cx);
3736 assert_eq!(
3737 view.display_text(cx),
3738 "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
3739 );
3740 assert_eq!(
3741 view.selection_ranges(cx),
3742 vec![
3743 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
3744 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
3745 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
3746 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
3747 ]
3748 );
3749 });
3750
3751 view.update(cx, |view, cx| {
3752 view.move_line_down(&MoveLineDown, cx);
3753 assert_eq!(
3754 view.display_text(cx),
3755 "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
3756 );
3757 assert_eq!(
3758 view.selection_ranges(cx),
3759 vec![
3760 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
3761 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
3762 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
3763 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
3764 ]
3765 );
3766 });
3767
3768 view.update(cx, |view, cx| {
3769 view.move_line_down(&MoveLineDown, cx);
3770 assert_eq!(
3771 view.display_text(cx),
3772 "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
3773 );
3774 assert_eq!(
3775 view.selection_ranges(cx),
3776 vec![
3777 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
3778 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
3779 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
3780 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
3781 ]
3782 );
3783 });
3784
3785 view.update(cx, |view, cx| {
3786 view.move_line_up(&MoveLineUp, cx);
3787 assert_eq!(
3788 view.display_text(cx),
3789 "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
3790 );
3791 assert_eq!(
3792 view.selection_ranges(cx),
3793 vec![
3794 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
3795 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
3796 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
3797 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
3798 ]
3799 );
3800 });
3801 }
3802
3803 #[gpui::test]
3804 fn test_clipboard(cx: &mut gpui::MutableAppContext) {
3805 let buffer = cx.add_model(|cx| Buffer::new(0, "one two three four five six ", cx));
3806 let settings = settings::test(&cx).1;
3807 let view = cx
3808 .add_window(Default::default(), |cx| {
3809 Editor::for_buffer(buffer.clone(), settings, cx)
3810 })
3811 .1;
3812
3813 // Cut with three selections. Clipboard text is divided into three slices.
3814 view.update(cx, |view, cx| {
3815 view.select_ranges(vec![0..4, 8..14, 19..24], false, cx);
3816 view.cut(&Cut, cx);
3817 assert_eq!(view.display_text(cx), "two four six ");
3818 });
3819
3820 // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
3821 view.update(cx, |view, cx| {
3822 view.select_ranges(vec![4..4, 9..9, 13..13], false, cx);
3823 view.paste(&Paste, cx);
3824 assert_eq!(view.display_text(cx), "two one four three six five ");
3825 assert_eq!(
3826 view.selection_ranges(cx),
3827 &[
3828 DisplayPoint::new(0, 8)..DisplayPoint::new(0, 8),
3829 DisplayPoint::new(0, 19)..DisplayPoint::new(0, 19),
3830 DisplayPoint::new(0, 28)..DisplayPoint::new(0, 28)
3831 ]
3832 );
3833 });
3834
3835 // Paste again but with only two cursors. Since the number of cursors doesn't
3836 // match the number of slices in the clipboard, the entire clipboard text
3837 // is pasted at each cursor.
3838 view.update(cx, |view, cx| {
3839 view.select_ranges(vec![0..0, 28..28], false, cx);
3840 view.insert(&Insert("( ".into()), cx);
3841 view.paste(&Paste, cx);
3842 view.insert(&Insert(") ".into()), cx);
3843 assert_eq!(
3844 view.display_text(cx),
3845 "( one three five ) two one four three six five ( one three five ) "
3846 );
3847 });
3848
3849 view.update(cx, |view, cx| {
3850 view.select_ranges(vec![0..0], false, cx);
3851 view.insert(&Insert("123\n4567\n89\n".into()), cx);
3852 assert_eq!(
3853 view.display_text(cx),
3854 "123\n4567\n89\n( one three five ) two one four three six five ( one three five ) "
3855 );
3856 });
3857
3858 // Cut with three selections, one of which is full-line.
3859 view.update(cx, |view, cx| {
3860 view.select_display_ranges(
3861 &[
3862 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
3863 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
3864 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
3865 ],
3866 cx,
3867 )
3868 .unwrap();
3869 view.cut(&Cut, cx);
3870 assert_eq!(
3871 view.display_text(cx),
3872 "13\n9\n( one three five ) two one four three six five ( one three five ) "
3873 );
3874 });
3875
3876 // Paste with three selections, noticing how the copied selection that was full-line
3877 // gets inserted before the second cursor.
3878 view.update(cx, |view, cx| {
3879 view.select_display_ranges(
3880 &[
3881 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
3882 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
3883 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
3884 ],
3885 cx,
3886 )
3887 .unwrap();
3888 view.paste(&Paste, cx);
3889 assert_eq!(
3890 view.display_text(cx),
3891 "123\n4567\n9\n( 8ne three five ) two one four three six five ( one three five ) "
3892 );
3893 assert_eq!(
3894 view.selection_ranges(cx),
3895 &[
3896 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3897 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
3898 DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
3899 ]
3900 );
3901 });
3902
3903 // Copy with a single cursor only, which writes the whole line into the clipboard.
3904 view.update(cx, |view, cx| {
3905 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx)
3906 .unwrap();
3907 view.copy(&Copy, cx);
3908 });
3909
3910 // Paste with three selections, noticing how the copied full-line selection is inserted
3911 // before the empty selections but replaces the selection that is non-empty.
3912 view.update(cx, |view, cx| {
3913 view.select_display_ranges(
3914 &[
3915 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
3916 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
3917 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
3918 ],
3919 cx,
3920 )
3921 .unwrap();
3922 view.paste(&Paste, cx);
3923 assert_eq!(
3924 view.display_text(cx),
3925 "123\n123\n123\n67\n123\n9\n( 8ne three five ) two one four three six five ( one three five ) "
3926 );
3927 assert_eq!(
3928 view.selection_ranges(cx),
3929 &[
3930 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
3931 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
3932 DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
3933 ]
3934 );
3935 });
3936 }
3937
3938 #[gpui::test]
3939 fn test_select_all(cx: &mut gpui::MutableAppContext) {
3940 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\nde\nfgh", cx));
3941 let settings = settings::test(&cx).1;
3942 let (_, view) = cx.add_window(Default::default(), |cx| {
3943 Editor::for_buffer(buffer, settings, cx)
3944 });
3945 view.update(cx, |view, cx| {
3946 view.select_all(&SelectAll, cx);
3947 assert_eq!(
3948 view.selection_ranges(cx),
3949 &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
3950 );
3951 });
3952 }
3953
3954 #[gpui::test]
3955 fn test_select_line(cx: &mut gpui::MutableAppContext) {
3956 let settings = settings::test(&cx).1;
3957 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 5), cx));
3958 let (_, view) = cx.add_window(Default::default(), |cx| {
3959 Editor::for_buffer(buffer, settings, cx)
3960 });
3961 view.update(cx, |view, cx| {
3962 view.select_display_ranges(
3963 &[
3964 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
3965 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3966 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3967 DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
3968 ],
3969 cx,
3970 )
3971 .unwrap();
3972 view.select_line(&SelectLine, cx);
3973 assert_eq!(
3974 view.selection_ranges(cx),
3975 vec![
3976 DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
3977 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
3978 ]
3979 );
3980 });
3981
3982 view.update(cx, |view, cx| {
3983 view.select_line(&SelectLine, cx);
3984 assert_eq!(
3985 view.selection_ranges(cx),
3986 vec![
3987 DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
3988 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
3989 ]
3990 );
3991 });
3992
3993 view.update(cx, |view, cx| {
3994 view.select_line(&SelectLine, cx);
3995 assert_eq!(
3996 view.selection_ranges(cx),
3997 vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
3998 );
3999 });
4000 }
4001
4002 #[gpui::test]
4003 fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
4004 let settings = settings::test(&cx).1;
4005 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(9, 5), cx));
4006 let (_, view) = cx.add_window(Default::default(), |cx| {
4007 Editor::for_buffer(buffer, settings, cx)
4008 });
4009 view.update(cx, |view, cx| {
4010 view.fold_ranges(
4011 vec![
4012 Point::new(0, 2)..Point::new(1, 2),
4013 Point::new(2, 3)..Point::new(4, 1),
4014 Point::new(7, 0)..Point::new(8, 4),
4015 ],
4016 cx,
4017 );
4018 view.select_display_ranges(
4019 &[
4020 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4021 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4022 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4023 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
4024 ],
4025 cx,
4026 )
4027 .unwrap();
4028 assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
4029 });
4030
4031 view.update(cx, |view, cx| {
4032 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
4033 assert_eq!(
4034 view.display_text(cx),
4035 "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
4036 );
4037 assert_eq!(
4038 view.selection_ranges(cx),
4039 [
4040 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4041 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4042 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
4043 DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
4044 ]
4045 );
4046 });
4047
4048 view.update(cx, |view, cx| {
4049 view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx)
4050 .unwrap();
4051 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
4052 assert_eq!(
4053 view.display_text(cx),
4054 "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
4055 );
4056 assert_eq!(
4057 view.selection_ranges(cx),
4058 [
4059 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4060 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4061 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
4062 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
4063 DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
4064 DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
4065 DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
4066 DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
4067 ]
4068 );
4069 });
4070 }
4071
4072 #[gpui::test]
4073 fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
4074 let settings = settings::test(&cx).1;
4075 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndefghi\n\njk\nlmno\n", cx));
4076 let (_, view) = cx.add_window(Default::default(), |cx| {
4077 Editor::for_buffer(buffer, settings, cx)
4078 });
4079
4080 view.update(cx, |view, cx| {
4081 view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx)
4082 .unwrap();
4083 });
4084 view.update(cx, |view, cx| {
4085 view.add_selection_above(&AddSelectionAbove, cx);
4086 assert_eq!(
4087 view.selection_ranges(cx),
4088 vec![
4089 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4090 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
4091 ]
4092 );
4093 });
4094
4095 view.update(cx, |view, cx| {
4096 view.add_selection_above(&AddSelectionAbove, cx);
4097 assert_eq!(
4098 view.selection_ranges(cx),
4099 vec![
4100 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4101 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
4102 ]
4103 );
4104 });
4105
4106 view.update(cx, |view, cx| {
4107 view.add_selection_below(&AddSelectionBelow, cx);
4108 assert_eq!(
4109 view.selection_ranges(cx),
4110 vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
4111 );
4112 });
4113
4114 view.update(cx, |view, cx| {
4115 view.add_selection_below(&AddSelectionBelow, cx);
4116 assert_eq!(
4117 view.selection_ranges(cx),
4118 vec![
4119 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
4120 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
4121 ]
4122 );
4123 });
4124
4125 view.update(cx, |view, cx| {
4126 view.add_selection_below(&AddSelectionBelow, cx);
4127 assert_eq!(
4128 view.selection_ranges(cx),
4129 vec![
4130 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
4131 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
4132 ]
4133 );
4134 });
4135
4136 view.update(cx, |view, cx| {
4137 view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx)
4138 .unwrap();
4139 });
4140 view.update(cx, |view, cx| {
4141 view.add_selection_below(&AddSelectionBelow, cx);
4142 assert_eq!(
4143 view.selection_ranges(cx),
4144 vec![
4145 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4146 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
4147 ]
4148 );
4149 });
4150
4151 view.update(cx, |view, cx| {
4152 view.add_selection_below(&AddSelectionBelow, cx);
4153 assert_eq!(
4154 view.selection_ranges(cx),
4155 vec![
4156 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4157 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
4158 ]
4159 );
4160 });
4161
4162 view.update(cx, |view, cx| {
4163 view.add_selection_above(&AddSelectionAbove, cx);
4164 assert_eq!(
4165 view.selection_ranges(cx),
4166 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
4167 );
4168 });
4169
4170 view.update(cx, |view, cx| {
4171 view.add_selection_above(&AddSelectionAbove, cx);
4172 assert_eq!(
4173 view.selection_ranges(cx),
4174 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
4175 );
4176 });
4177
4178 view.update(cx, |view, cx| {
4179 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx)
4180 .unwrap();
4181 view.add_selection_below(&AddSelectionBelow, cx);
4182 assert_eq!(
4183 view.selection_ranges(cx),
4184 vec![
4185 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4186 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
4187 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
4188 ]
4189 );
4190 });
4191
4192 view.update(cx, |view, cx| {
4193 view.add_selection_below(&AddSelectionBelow, cx);
4194 assert_eq!(
4195 view.selection_ranges(cx),
4196 vec![
4197 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4198 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
4199 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
4200 DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
4201 ]
4202 );
4203 });
4204
4205 view.update(cx, |view, cx| {
4206 view.add_selection_above(&AddSelectionAbove, cx);
4207 assert_eq!(
4208 view.selection_ranges(cx),
4209 vec![
4210 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4211 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
4212 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
4213 ]
4214 );
4215 });
4216
4217 view.update(cx, |view, cx| {
4218 view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx)
4219 .unwrap();
4220 });
4221 view.update(cx, |view, cx| {
4222 view.add_selection_above(&AddSelectionAbove, cx);
4223 assert_eq!(
4224 view.selection_ranges(cx),
4225 vec![
4226 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
4227 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
4228 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
4229 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
4230 ]
4231 );
4232 });
4233
4234 view.update(cx, |view, cx| {
4235 view.add_selection_below(&AddSelectionBelow, cx);
4236 assert_eq!(
4237 view.selection_ranges(cx),
4238 vec![
4239 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
4240 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
4241 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
4242 ]
4243 );
4244 });
4245 }
4246
4247 #[gpui::test]
4248 async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
4249 let settings = cx.read(settings::test).1;
4250 let languages = LanguageRegistry::new();
4251 let lang = languages.select_language("z.rs");
4252 let text = r#"
4253 use mod1::mod2::{mod3, mod4};
4254
4255 fn fn_1(param1: bool, param2: &str) {
4256 let var1 = "text";
4257 }
4258 "#
4259 .unindent();
4260 let buffer = cx.add_model(|cx| {
4261 let history = History::new(text.into());
4262 Buffer::from_history(0, history, None, lang.cloned(), cx)
4263 });
4264 let (_, view) = cx.add_window(|cx| Editor::for_buffer(buffer, settings.clone(), cx));
4265 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing())
4266 .await;
4267
4268 view.update(&mut cx, |view, cx| {
4269 view.select_display_ranges(
4270 &[
4271 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
4272 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
4273 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
4274 ],
4275 cx,
4276 )
4277 .unwrap();
4278 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4279 });
4280 assert_eq!(
4281 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4282 &[
4283 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
4284 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
4285 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
4286 ]
4287 );
4288
4289 view.update(&mut cx, |view, cx| {
4290 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4291 });
4292 assert_eq!(
4293 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4294 &[
4295 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
4296 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
4297 ]
4298 );
4299
4300 view.update(&mut cx, |view, cx| {
4301 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4302 });
4303 assert_eq!(
4304 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4305 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
4306 );
4307
4308 // Trying to expand the selected syntax node one more time has no effect.
4309 view.update(&mut cx, |view, cx| {
4310 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4311 });
4312 assert_eq!(
4313 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4314 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
4315 );
4316
4317 view.update(&mut cx, |view, cx| {
4318 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
4319 });
4320 assert_eq!(
4321 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4322 &[
4323 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
4324 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
4325 ]
4326 );
4327
4328 view.update(&mut cx, |view, cx| {
4329 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
4330 });
4331 assert_eq!(
4332 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4333 &[
4334 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
4335 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
4336 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
4337 ]
4338 );
4339
4340 view.update(&mut cx, |view, cx| {
4341 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
4342 });
4343 assert_eq!(
4344 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4345 &[
4346 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
4347 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
4348 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
4349 ]
4350 );
4351
4352 // Trying to shrink the selected syntax node one more time has no effect.
4353 view.update(&mut cx, |view, cx| {
4354 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
4355 });
4356 assert_eq!(
4357 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4358 &[
4359 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
4360 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
4361 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
4362 ]
4363 );
4364
4365 // Ensure that we keep expanding the selection if the larger selection starts or ends within
4366 // a fold.
4367 view.update(&mut cx, |view, cx| {
4368 view.fold_ranges(
4369 vec![
4370 Point::new(0, 21)..Point::new(0, 24),
4371 Point::new(3, 20)..Point::new(3, 22),
4372 ],
4373 cx,
4374 );
4375 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4376 });
4377 assert_eq!(
4378 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4379 &[
4380 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
4381 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
4382 DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
4383 ]
4384 );
4385 }
4386
4387 impl Editor {
4388 fn selection_ranges(&self, cx: &mut MutableAppContext) -> Vec<Range<DisplayPoint>> {
4389 self.selections_in_range(
4390 self.selection_set_id,
4391 DisplayPoint::zero()..self.max_point(cx),
4392 cx,
4393 )
4394 .collect::<Vec<_>>()
4395 }
4396 }
4397
4398 fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
4399 let point = DisplayPoint::new(row as u32, column as u32);
4400 point..point
4401 }
4402}
4403
4404trait RangeExt<T> {
4405 fn sorted(&self) -> Range<T>;
4406 fn to_inclusive(&self) -> RangeInclusive<T>;
4407}
4408
4409impl<T: Ord + Clone> RangeExt<T> for Range<T> {
4410 fn sorted(&self) -> Self {
4411 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
4412 }
4413
4414 fn to_inclusive(&self) -> RangeInclusive<T> {
4415 self.start.clone()..=self.end.clone()
4416 }
4417}