1use ropey::Rope;
4
5use crate::change::{Assoc, ChangeSet, Edit, inside_crlf};
6use crate::commands::{next_grapheme, prev_grapheme};
7use crate::history::{EditKind, Transaction};
8use crate::model::{Options, TextModel};
9use crate::position::{Position, char_to_position, line_end, line_len, position_to_char};
10use crate::selection::{Selection, Selections};
11
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
14pub struct EditorId(pub u32);
15
16#[derive(Clone, Debug)]
18pub struct Cursors {
19 id: EditorId,
20 pub(crate) selections: Selections,
21 synced: u64,
22 cursor_history: Vec<Selections>,
24 pub(crate) expansions: Vec<Selections>,
26 pub(crate) snippet: Option<crate::snippet::SnippetSession>,
28}
29
30const CURSOR_HISTORY: usize = 50;
32
33impl Cursors {
34 pub fn new(id: EditorId, model: &TextModel) -> Self {
35 Self {
36 id,
37 selections: Selections::single(Selection::cursor(0)),
38 synced: model.version(),
39 cursor_history: Vec::new(),
40 expansions: Vec::new(),
41 snippet: None,
42 }
43 }
44
45 pub fn id(&self) -> EditorId {
46 self.id
47 }
48
49 pub fn snippet_active(&self) -> bool {
51 self.snippet.is_some()
52 }
53
54 pub fn selections(&self) -> &Selections {
57 &self.selections
58 }
59
60 pub fn sync(&mut self, model: &TextModel) {
63 if self.synced == model.version() {
64 return;
65 }
66 if let Ok(changes) = model.changes_since(self.synced) {
67 for cs in changes {
68 self.selections = self.selections.map(|s| Selection {
69 anchor: cs.map(s.anchor, Assoc::Before),
70 head: cs.map(s.head, Assoc::Before),
71 goal_column: None,
72 });
73 }
74 }
75 self.selections = snap_selections(model.rope(), &self.selections);
76 self.synced = model.version();
77 }
78}
79
80pub struct Editor<'a> {
82 pub(crate) model: &'a mut TextModel,
83 pub(crate) cursors: &'a mut Cursors,
84}
85
86impl<'a> Editor<'a> {
87 pub fn new(model: &'a mut TextModel, cursors: &'a mut Cursors) -> Self {
88 cursors.sync(model);
89 Self { model, cursors }
90 }
91
92 pub fn model(&self) -> &TextModel {
94 self.model
95 }
96
97 pub fn selections(&self) -> &Selections {
98 &self.cursors.selections
99 }
100
101 pub fn set_selections(&mut self, selections: Selections) {
102 let next = snap_selections(&self.model.rope, &selections);
103 self.record_cursor_state(&next);
104 self.cursors.selections = next;
105 self.model.history.break_group();
106 }
107
108 fn record_cursor_state(&mut self, next: &Selections) {
110 if *next != self.cursors.selections {
111 let h = &mut self.cursors.cursor_history;
112 h.push(self.cursors.selections.clone());
113 if h.len() > CURSOR_HISTORY {
114 h.remove(0);
115 }
116 }
117 }
118
119 pub fn cursor_undo(&mut self) -> bool {
122 match self.cursors.cursor_history.pop() {
123 Some(prev) => {
124 self.cursors.selections = snap_selections(&self.model.rope, &prev);
125 self.model.history.break_group();
126 true
127 }
128 None => false,
129 }
130 }
131
132 pub(crate) fn commit(&mut self, changes: ChangeSet, after: Selections, kind: EditKind) {
135 if changes.is_empty() {
136 self.cursors.selections = snap_selections(&self.model.rope, &after);
137 return;
138 }
139 let before = self.cursors.selections.clone();
140 self.cursors.cursor_history.clear();
141 self.cursors.expansions.clear();
142 let inverse = self.model.apply(&changes);
143 self.cursors.selections = snap_selections(&self.model.rope, &after);
144 self.cursors.synced = self.model.version();
145 let tx =
146 Transaction { changes, inverse, before, after: self.cursors.selections.clone(), origin: self.cursors.id };
147 self.model.history.push(tx, kind);
148 }
149
150 pub(crate) fn replace_each(&mut self, kind: EditKind, mut f: impl FnMut(&Rope, usize, &Selection) -> String) {
152 self.replace_ranges(kind, |rope, i, sel| (sel.start(), sel.end(), f(rope, i, sel)));
153 }
154
155 fn replace_ranges(
158 &mut self,
159 kind: EditKind,
160 mut f: impl FnMut(&Rope, usize, &Selection) -> (usize, usize, String),
161 ) {
162 let mut edits = Vec::with_capacity(self.cursors.selections.len());
163 let mut carets = Vec::with_capacity(self.cursors.selections.len());
164 let mut delta = 0isize;
165 for (i, sel) in self.cursors.selections.iter().enumerate() {
166 let (start, end, text) = f(&self.model.rope, i, sel);
167 let inserted = text.chars().count();
168 carets.push(Selection::cursor(start.wrapping_add_signed(delta) + inserted));
169 delta += inserted as isize - (end - start) as isize;
170 edits.push(Edit::new(start, end, text));
171 }
172 let after = Selections::new(carets, self.cursors.selections.primary_index());
173 self.commit(ChangeSet::new(edits).snap_crlf(&self.model.rope), after, kind);
174 }
175
176 pub fn compose(&mut self, before: usize, text: &str) {
180 self.replace_ranges(EditKind::Typing, |_, _, sel| {
181 if sel.is_empty() {
182 (sel.head.saturating_sub(before), sel.head, text.to_owned())
183 } else {
184 (sel.start(), sel.end(), text.to_owned())
185 }
186 });
187 }
188
189 pub fn paste_each(&mut self, pieces: &[String]) {
191 if pieces.len() != self.cursors.selections.len() {
192 return self.paste(&pieces.join(self.model.line_ending.as_str()));
193 }
194 self.replace_each(EditKind::Other, |_, i, _| pieces[i].clone());
195 self.model.history.break_group();
196 }
197
198 pub fn selection_texts(&self) -> Vec<String> {
200 self.cursors
201 .selections
202 .iter()
203 .filter(|s| !s.is_empty())
204 .map(|s| self.model.rope.slice(s.start()..s.end()).to_string())
205 .collect()
206 }
207
208 fn delete_each(&mut self, kind: EditKind, mut f: impl FnMut(&Rope, &Selection) -> (usize, usize)) {
210 let edits = self
211 .cursors
212 .selections
213 .iter()
214 .map(|s| {
215 let (start, end) = f(&self.model.rope, s);
216 Edit::delete(start, end)
217 })
218 .collect();
219 let changes = ChangeSet::new(edits).snap_crlf(&self.model.rope);
220 let after = self.cursors.selections.map(|s| Selection::cursor(changes.map(s.start(), Assoc::Before)));
221 self.commit(changes, after, kind);
222 }
223
224 pub(crate) fn delete_each_pub(&mut self, kind: EditKind, f: impl FnMut(&Rope, &Selection) -> (usize, usize)) {
225 self.delete_each(kind, f);
226 }
227
228 pub fn move_heads(&mut self, extend: bool, f: impl FnMut(&Rope, &Selection) -> (usize, Option<usize>)) {
231 self.move_each(extend, f);
232 }
233
234 fn move_each(&mut self, extend: bool, mut f: impl FnMut(&Rope, &Selection) -> (usize, Option<usize>)) {
235 let moved = self.cursors.selections.map(|s| {
236 let (head, goal_column) = f(&self.model.rope, s);
237 let anchor = if extend { s.anchor } else { head };
238 Selection { anchor, head, goal_column }
239 });
240 let next = snap_selections(&self.model.rope, &moved);
241 if extend || self.cursors.selections.iter().any(|s| !s.is_empty()) {
243 self.record_cursor_state(&next);
244 }
245 self.cursors.selections = next;
246 self.model.history.break_group();
247 }
248
249 pub fn insert(&mut self, text: &str) {
253 let mut chars = text.chars();
254 let single_char = matches!((chars.next(), chars.next()), (Some(c), None) if c != '\n' && c != '\r');
255 let kind = if single_char { EditKind::Typing } else { EditKind::Other };
256 self.replace_each(kind, |_, _, _| text.to_owned());
257 }
258
259 pub fn newline(&mut self) {
261 let eol = self.model.line_ending.as_str();
262 let o = self.model.options;
263 let unit = if o.insert_spaces { " ".repeat(o.tab_size) } else { "\t".to_owned() };
264 let editing = self.model.editing.clone();
265 let mut caret_offsets: Vec<Option<usize>> = Vec::new();
268 self.replace_each(EditKind::Other, |rope, _, sel| {
269 let line = rope.char_to_line(sel.start());
270 let line_start = rope.line_to_char(line);
271 let indent: String =
272 rope.slice(line_start..sel.start()).chars().take_while(|c| *c == ' ' || *c == '\t').collect();
273 let before: String = rope.slice(line_start..sel.start()).to_string();
274 let before = before.trim_end();
275 let opens = editing.brackets.iter().find(|(open, _)| before.ends_with(open.as_str()));
276 let after_starts = |close: &str| {
277 rope.slice(sel.end()..rope.len_chars()).chars().take(close.chars().count()).eq(close.chars())
278 };
279 match opens {
280 Some((_, close)) if after_starts(close) => {
281 let middle = format!("{eol}{indent}{unit}");
282 caret_offsets.push(Some(middle.chars().count()));
283 format!("{middle}{eol}{indent}")
284 }
285 Some(_) => {
286 caret_offsets.push(None);
287 format!("{eol}{indent}{unit}")
288 }
289 None if editing.indent_after.iter().any(|s| before.ends_with(s.as_str())) => {
290 caret_offsets.push(None);
291 format!("{eol}{indent}{unit}")
292 }
293 None => {
294 caret_offsets.push(None);
295 format!("{eol}{indent}")
296 }
297 }
298 });
299 if caret_offsets.iter().any(Option::is_some) {
300 let rope = &self.model.rope;
303 let mut i = 0;
304 let next = self.cursors.selections.map(|s| {
305 let offset = caret_offsets.get(i).copied().flatten();
306 i += 1;
307 match offset {
308 Some(_) => {
309 let line = rope.char_to_line(s.head);
311 Selection::cursor(crate::position::line_end(rope, line.saturating_sub(1)))
312 }
313 None => *s,
314 }
315 });
316 self.cursors.selections = next;
317 }
318 }
319
320 pub fn indent(&mut self) {
322 let Options { tab_size, insert_spaces } = self.model.options;
323 self.replace_each(EditKind::Other, |rope, _, sel| {
324 if !insert_spaces {
325 return "\t".to_owned();
326 }
327 let column = char_to_position(rope, sel.start()).column;
328 " ".repeat(tab_size - column % tab_size)
329 });
330 }
331
332 pub fn delete_backward(&mut self) {
334 self.delete_each(EditKind::Deleting, |rope, s| {
335 if s.is_empty() { (prev_grapheme(rope, s.head), s.head) } else { (s.start(), s.end()) }
336 });
337 }
338
339 pub fn delete_forward(&mut self) {
341 self.delete_each(EditKind::Deleting, |rope, s| {
342 if s.is_empty() { (s.head, next_grapheme(rope, s.head)) } else { (s.start(), s.end()) }
343 });
344 }
345
346 pub fn delete_word_backward(&mut self) {
348 self.delete_each(EditKind::Other, |rope, s| {
349 if s.is_empty() { (word_left(rope, s.head), s.head) } else { (s.start(), s.end()) }
350 });
351 }
352
353 pub fn delete_word_forward(&mut self) {
355 self.delete_each(EditKind::Other, |rope, s| {
356 if s.is_empty() { (s.head, word_right(rope, s.head)) } else { (s.start(), s.end()) }
357 });
358 }
359
360 pub fn apply_edits(&mut self, edits: Vec<Edit>) {
363 let len = self.model.rope.len_chars();
364 let edits = edits.into_iter().map(|e| Edit::new(e.start.min(len), e.end.min(len), e.text)).collect();
365 let changes = ChangeSet::new(edits).snap_crlf(&self.model.rope);
366 let after = self.cursors.selections.map(|s| Selection {
367 anchor: changes.map(s.anchor, Assoc::After),
368 head: changes.map(s.head, Assoc::After),
369 goal_column: None,
370 });
371 self.commit(changes, after, EditKind::Other);
372 self.model.history.break_group();
373 }
374
375 pub fn copy(&self) -> String {
379 if self.cursors.selections.iter().all(Selection::is_empty) {
380 let mut out = String::new();
381 let mut last_line = None;
382 for s in self.cursors.selections.iter() {
383 let line = self.model.rope.char_to_line(s.head);
384 if last_line == Some(line) {
385 continue;
386 }
387 last_line = Some(line);
388 out.push_str(&self.model.rope.line(line).to_string());
389 if line + 1 == self.model.rope.len_lines() {
390 out.push_str(self.model.line_ending.as_str());
391 }
392 }
393 return out;
394 }
395 let parts: Vec<String> = self
396 .cursors
397 .selections
398 .iter()
399 .filter(|s| !s.is_empty())
400 .map(|s| self.model.rope.slice(s.start()..s.end()).to_string())
401 .collect();
402 parts.join(self.model.line_ending.as_str())
403 }
404
405 pub fn cut(&mut self) -> String {
407 let text = self.copy();
408 if self.cursors.selections.iter().all(Selection::is_empty) {
409 self.delete_each(EditKind::Other, |rope, s| {
410 let line = rope.char_to_line(s.head);
411 (rope.line_to_char(line), rope.line_to_char(line + 1))
412 });
413 } else {
414 self.delete_each(EditKind::Other, |_, s| (s.start(), s.end()));
415 }
416 text
417 }
418
419 pub fn paste(&mut self, text: &str) {
421 let lines: Vec<&str> = text.lines().collect();
422 let spread = self.cursors.selections.len() > 1 && lines.len() == self.cursors.selections.len();
423 self.replace_each(EditKind::Other, |_, i, _| if spread { lines[i].to_owned() } else { text.to_owned() });
424 self.model.history.break_group();
425 }
426
427 pub fn move_left(&mut self, extend: bool) {
430 self.move_each(extend, |rope, s| {
431 if !extend && !s.is_empty() { (s.start(), None) } else { (prev_grapheme(rope, s.head), None) }
432 });
433 }
434
435 pub fn move_right(&mut self, extend: bool) {
436 self.move_each(extend, |rope, s| {
437 if !extend && !s.is_empty() { (s.end(), None) } else { (next_grapheme(rope, s.head), None) }
438 });
439 }
440
441 pub fn move_word_left(&mut self, extend: bool) {
442 self.move_each(extend, |rope, s| (word_left(rope, s.head), None));
443 }
444
445 pub fn move_word_right(&mut self, extend: bool) {
446 self.move_each(extend, |rope, s| (word_right(rope, s.head), None));
447 }
448
449 pub fn move_up(&mut self, extend: bool) {
450 self.move_vertical(-1, extend);
451 }
452
453 pub fn move_down(&mut self, extend: bool) {
454 self.move_vertical(1, extend);
455 }
456
457 pub fn move_vertical(&mut self, lines: isize, extend: bool) {
459 self.move_each(extend, |rope, s| vertical_target(rope, s, lines));
460 }
461
462 pub fn move_line_start(&mut self, extend: bool) {
464 self.move_each(extend, |rope, s| {
465 let line = rope.char_to_line(s.head);
466 let start = rope.line_to_char(line);
467 let indent = rope.line(line).chars().take(line_len(rope, line)).take_while(|c| c.is_whitespace()).count();
468 let target = if s.head == start + indent { start } else { start + indent };
469 (target, None)
470 });
471 }
472
473 pub fn move_line_end(&mut self, extend: bool) {
474 self.move_each(extend, |rope, s| (line_end(rope, rope.char_to_line(s.head)), None));
475 }
476
477 pub fn move_document_start(&mut self, extend: bool) {
478 self.move_each(extend, |_, _| (0, None));
479 }
480
481 pub fn move_document_end(&mut self, extend: bool) {
482 self.move_each(extend, |rope, _| (rope.len_chars(), None));
483 }
484
485 pub fn select_all(&mut self) {
486 self.set_selections(Selections::single(Selection::new(0, self.model.rope.len_chars())));
487 }
488
489 pub fn add_cursor_vertical(&mut self, below: bool) {
491 let sels = self.cursors.selections.as_slice();
492 let source = if below { sels[sels.len() - 1] } else { sels[0] };
493 let (head, goal_column) =
494 vertical_target(&self.model.rope, &Selection::cursor(source.head), if below { 1 } else { -1 });
495 let line = self.model.rope.char_to_line(source.head);
496 let at_edge = if below { line + 1 >= self.model.rope.len_lines() } else { line == 0 };
497 if at_edge {
498 return;
499 }
500 let mut ranges = sels.to_vec();
501 ranges.push(Selection { anchor: head, head, goal_column });
502 let primary = ranges.len() - 1;
503 self.set_selections(Selections::new(ranges, primary));
504 }
505
506 pub fn undo(&mut self) -> bool {
511 let Some(step) = self.model.history.pop_undo() else { return false };
512 for tx in step.transactions.iter().rev() {
513 self.model.apply(&tx.inverse);
514 }
515 let first = &step.transactions[0];
516 if first.origin == self.cursors.id {
517 self.cursors.selections = snap_selections(&self.model.rope, &first.before);
518 self.cursors.synced = self.model.version();
519 } else {
520 self.cursors.sync(self.model);
521 }
522 self.model.history.push_redo(step);
523 true
524 }
525
526 pub fn redo(&mut self) -> bool {
527 let Some(step) = self.model.history.pop_redo() else { return false };
528 for tx in &step.transactions {
529 self.model.apply(&tx.changes);
530 }
531 let last = &step.transactions[step.transactions.len() - 1];
532 if last.origin == self.cursors.id {
533 self.cursors.selections = snap_selections(&self.model.rope, &last.after);
534 self.cursors.synced = self.model.version();
535 } else {
536 self.cursors.sync(self.model);
537 }
538 self.model.history.push_undo(step);
539 true
540 }
541}
542
543fn snap_selections(rope: &Rope, selections: &Selections) -> Selections {
545 let len = rope.len_chars();
546 let snap = |p: usize| {
547 let p = p.min(len);
548 if inside_crlf(rope, p) { p - 1 } else { p }
549 };
550 selections.map(|s| Selection { anchor: snap(s.anchor), head: snap(s.head), goal_column: s.goal_column })
551}
552
553fn prev_boundary(rope: &Rope, pos: usize) -> usize {
555 if pos >= 2 && rope.char(pos - 1) == '\n' && rope.char(pos - 2) == '\r' { pos - 2 } else { pos.saturating_sub(1) }
556}
557
558fn next_boundary(rope: &Rope, pos: usize) -> usize {
560 let len = rope.len_chars();
561 if pos + 1 < len && rope.char(pos) == '\r' && rope.char(pos + 1) == '\n' { pos + 2 } else { (pos + 1).min(len) }
562}
563
564#[derive(Clone, Copy, PartialEq, Eq)]
565enum CharClass {
566 Word,
567 Space,
568 Newline,
569 Punct,
570}
571
572fn char_class(c: char) -> CharClass {
573 match c {
574 '\n' | '\r' => CharClass::Newline,
575 c if c.is_whitespace() => CharClass::Space,
576 c if c.is_alphanumeric() || c == '_' => CharClass::Word,
577 _ => CharClass::Punct,
578 }
579}
580
581pub(crate) fn word_right(rope: &Rope, mut pos: usize) -> usize {
583 let len = rope.len_chars();
584 if pos < len && char_class(rope.char(pos)) == CharClass::Newline {
585 return next_boundary(rope, pos);
586 }
587 while pos < len && char_class(rope.char(pos)) == CharClass::Space {
588 pos += 1;
589 }
590 if pos < len {
591 let class = char_class(rope.char(pos));
592 if class != CharClass::Newline {
593 while pos < len && char_class(rope.char(pos)) == class {
594 pos += 1;
595 }
596 }
597 }
598 pos
599}
600
601pub(crate) fn word_left(rope: &Rope, mut pos: usize) -> usize {
603 if pos > 0 && char_class(rope.char(pos - 1)) == CharClass::Newline {
604 return prev_boundary(rope, pos);
605 }
606 while pos > 0 && char_class(rope.char(pos - 1)) == CharClass::Space {
607 pos -= 1;
608 }
609 if pos > 0 {
610 let class = char_class(rope.char(pos - 1));
611 if class != CharClass::Newline {
612 while pos > 0 && char_class(rope.char(pos - 1)) == class {
613 pos -= 1;
614 }
615 }
616 }
617 pos
618}
619
620pub fn word_at(rope: &Rope, pos: usize) -> (usize, usize) {
622 let len = rope.len_chars();
623 let class_at = |i: usize| (i < len).then(|| char_class(rope.char(i)));
624 let class = match (class_at(pos), pos.checked_sub(1).and_then(class_at)) {
625 (Some(CharClass::Word), _) => CharClass::Word,
626 (_, Some(CharClass::Word)) => CharClass::Word,
627 (Some(c), _) if c != CharClass::Newline => c,
628 (_, Some(c)) if c != CharClass::Newline => c,
629 _ => return (pos, pos),
630 };
631 let (mut start, mut end) = (pos, pos);
632 while start > 0 && char_class(rope.char(start - 1)) == class {
633 start -= 1;
634 }
635 while end < len && char_class(rope.char(end)) == class {
636 end += 1;
637 }
638 (start, end)
639}
640
641fn vertical_target(rope: &Rope, s: &Selection, lines: isize) -> (usize, Option<usize>) {
642 let pos = char_to_position(rope, s.head);
643 let goal = s.goal_column.unwrap_or(pos.column);
644 let target = pos.line as isize + lines;
645 if target < 0 {
646 return (0, None);
647 }
648 if target as usize >= rope.len_lines() {
649 return (rope.len_chars(), None);
650 }
651 (position_to_char(rope, Position::new(target as usize, goal)), Some(goal))
652}