Damson: a Material You code editor in Rust

Runs Kate's syntax definitions directly, on a hand-written editor core.
Spring-driven UI with a pop-out scrolling preview, baked-in terminal
grown from a morphing button, jelly tabs, command palette, side panels,
git, language servers and hot exit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-06 17:05:28 -06:00
commit 65defa1ae3
4 changed files with 13923 additions and 0 deletions

264
src/text/buffer.rs Normal file
View file

@ -0,0 +1,264 @@
//! The text itself: a rope, any number of selections, and grouped undo.
use ropey::Rope;
use std::ops::Range;
use std::time::{Duration, Instant};
/// One selection; `anchor == head` is a plain cursor. Positions are char indices into the rope.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Sel {
pub anchor: usize,
pub head: usize,
/// Column to return to while moving through shorter lines.
pub want_col: Option<usize>,
}
impl Sel {
pub fn cursor(at: usize) -> Sel {
Sel { anchor: at, head: at, want_col: None }
}
pub fn range(&self) -> Range<usize> {
self.anchor.min(self.head)..self.anchor.max(self.head)
}
pub fn is_empty(&self) -> bool {
self.anchor == self.head
}
}
/// Typing runs of the same kind undo together.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EditKind {
Typing,
Deleting,
Other,
}
#[derive(Clone, Debug)]
struct Edit {
pos: usize,
del: String,
ins: String,
}
#[derive(Clone, Debug)]
struct Group {
edits: Vec<Edit>,
before: Vec<Sel>,
after: Vec<Sel>,
kind: EditKind,
at: Instant,
}
/// Lines touched by an edit: `old` lines starting at `first` became `new` lines.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LineChange {
pub first: usize,
pub old: usize,
pub new: usize,
}
pub struct Buffer {
pub rope: Rope,
pub sels: Vec<Sel>,
pub primary: usize,
undo: Vec<Group>,
redo: Vec<Group>,
/// Bumped on every text change.
pub version: u64,
saved_marker: Option<usize>,
/// Line changes since the document last looked; drained by `Doc`.
pub changes: Vec<LineChange>,
}
const COALESCE: Duration = Duration::from_millis(900);
impl Buffer {
pub fn new(text: &str) -> Buffer {
Buffer { rope: Rope::from_str(text), sels: vec![Sel::cursor(0)], primary: 0, undo: vec![], redo: vec![], version: 0, saved_marker: Some(0), changes: vec![] }
}
pub fn mark_saved(&mut self) {
self.saved_marker = Some(self.undo.len());
}
pub fn is_modified(&self) -> bool {
self.saved_marker != Some(self.undo.len())
}
pub fn can_undo(&self) -> bool {
!self.undo.is_empty()
}
pub fn can_redo(&self) -> bool {
!self.redo.is_empty()
}
pub fn len(&self) -> usize {
self.rope.len_chars()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn lines(&self) -> usize {
self.rope.len_lines()
}
pub fn head(&self) -> usize {
self.sels[self.primary.min(self.sels.len() - 1)].head
}
/// (line, char column) of a position.
pub fn pos(&self, at: usize) -> (usize, usize) {
let at = at.min(self.len());
let l = self.rope.char_to_line(at);
(l, at - self.rope.line_to_char(l))
}
pub fn at(&self, line: usize, col: usize) -> usize {
let line = line.min(self.lines() - 1);
self.rope.line_to_char(line) + col.min(self.line_len(line))
}
/// Length of a line in chars, without its line break.
pub fn line_len(&self, line: usize) -> usize {
let s = self.rope.line(line);
let mut n = s.len_chars();
while n > 0 && matches!(s.char(n - 1), '\n' | '\r') {
n -= 1;
}
n
}
pub fn line_text(&self, line: usize) -> String {
if line >= self.lines() {
return String::new();
}
let mut s = self.rope.line(line).to_string();
while s.ends_with('\n') || s.ends_with('\r') {
s.pop();
}
s
}
pub fn text(&self, r: Range<usize>) -> String {
self.rope.slice(r).to_string()
}
/// Replaces ranges with texts. The ranges may come in any order but must not overlap.
/// `place` gets, for each change in order, where its new text starts and how long it is, and
/// returns the selection that should follow it.
pub fn apply(&mut self, mut changes: Vec<(Range<usize>, String)>, kind: EditKind, place: impl Fn(usize, usize, usize) -> Sel) {
changes.sort_by_key(|c| c.0.start);
let before = self.sels.clone();
let mut delta = 0isize;
let mut after = vec![];
for (i, (r, s)) in changes.iter().enumerate() {
let start = (r.start as isize + delta) as usize;
let n = s.chars().count();
after.push(place(i, start, n));
delta += n as isize - r.len() as isize;
}
// back to front, so earlier positions stay valid
let mut edits = vec![];
for (r, s) in changes.into_iter().rev() {
if r.is_empty() && s.is_empty() {
continue;
}
let del = self.rope.slice(r.clone()).to_string();
self.raw_edit(r.start, r.end, &s);
edits.push(Edit { pos: r.start, del, ins: s });
}
self.set_sels(after);
if edits.is_empty() {
return;
}
self.redo.clear();
let now = Instant::now();
let saved_here = self.saved_marker == Some(self.undo.len());
if let Some(g) = self.undo.last_mut() {
if kind != EditKind::Other && g.kind == kind && now - g.at < COALESCE && !saved_here {
g.edits.extend(edits);
g.after = self.sels.clone();
g.at = now;
return;
}
}
if self.saved_marker.is_some_and(|m| m > self.undo.len()) {
self.saved_marker = None;
}
self.undo.push(Group { edits, before, after: self.sels.clone(), kind, at: now });
}
fn raw_edit(&mut self, start: usize, end: usize, ins: &str) {
let first = self.rope.char_to_line(start);
let last = self.rope.char_to_line(end);
self.rope.remove(start..end);
self.rope.insert(start, ins);
let new = ins.matches('\n').count();
self.changes.push(LineChange { first, old: last - first + 1, new: new + 1 });
self.version += 1;
}
pub fn undo(&mut self) -> bool {
let Some(g) = self.undo.pop() else { return false };
for e in g.edits.iter().rev() {
self.raw_edit(e.pos, e.pos + e.ins.chars().count(), &e.del);
}
self.set_sels(g.before.clone());
self.redo.push(g);
true
}
pub fn redo(&mut self) -> bool {
let Some(mut g) = self.redo.pop() else { return false };
for e in g.edits.iter() {
self.raw_edit(e.pos, e.pos + e.del.chars().count(), &e.ins);
}
self.set_sels(g.after.clone());
g.at = Instant::now() - COALESCE;
self.undo.push(g);
true
}
/// Sets the selections, sorted, with overlapping ones merged. The last one becomes primary.
pub fn set_sels(&mut self, mut v: Vec<Sel>) {
if v.is_empty() {
v.push(Sel::cursor(0));
}
let len = self.len();
for s in &mut v {
s.anchor = s.anchor.min(len);
s.head = s.head.min(len);
}
let last = v[v.len() - 1];
v.sort_by_key(|s| s.range().start);
let mut out: Vec<Sel> = vec![];
for s in v {
if let Some(p) = out.last_mut() {
let (pr, sr) = (p.range(), s.range());
if sr.start < pr.end || (sr.start == pr.end && (pr.is_empty() || sr.is_empty())) {
let (a, b) = (pr.start.min(sr.start), pr.end.max(sr.end));
let backward = p.head < p.anchor;
*p = Sel { anchor: if backward { b } else { a }, head: if backward { a } else { b }, want_col: None };
continue;
}
}
out.push(s);
}
self.primary = out.iter().position(|s| s.range().contains(&last.head) || s.head == last.head).unwrap_or(out.len() - 1);
self.sels = out;
}
pub fn set_cursor(&mut self, at: usize) {
self.set_sels(vec![Sel::cursor(at)]);
}
pub fn selected_text(&self) -> String {
let parts: Vec<String> = self.sels.iter().filter(|s| !s.is_empty()).map(|s| self.text(s.range())).collect();
parts.join("\n")
}
}

635
src/text/commands.rs Normal file
View file

@ -0,0 +1,635 @@
//! Editing commands on a `Buffer`. Every command works on all selections at once.
use super::buffer::{Buffer, EditKind, Sel};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Move {
Left, Right, Up, Down, WordLeft, WordRight, Home, End, DocStart, DocEnd, PageUp(usize), PageDown(usize),
}
fn is_word(c: char) -> bool {
c.is_alphanumeric() || c == '_'
}
pub struct Prefs {
pub tab_width: usize,
pub spaces: bool,
pub auto_close: bool,
}
impl Default for Prefs {
fn default() -> Self {
Prefs { tab_width: 4, spaces: true, auto_close: true }
}
}
impl Buffer {
fn word_left(&self, mut at: usize) -> usize {
let c = |i: usize| self.rope.char(i);
while at > 0 && c(at - 1).is_whitespace() { at -= 1 }
if at == 0 { return 0 }
let word = is_word(c(at - 1));
while at > 0 && !c(at - 1).is_whitespace() && is_word(c(at - 1)) == word { at -= 1 }
at
}
fn word_right(&self, mut at: usize) -> usize {
let n = self.len();
let c = |i: usize| self.rope.char(i);
while at < n && c(at).is_whitespace() { at += 1 }
if at == n { return n }
let word = is_word(c(at));
while at < n && !c(at).is_whitespace() && is_word(c(at)) == word { at += 1 }
at
}
/// The word around a position.
pub fn word_at(&self, at: usize) -> std::ops::Range<usize> {
let n = self.len();
let (mut a, mut b) = (at.min(n), at.min(n));
while a > 0 && is_word(self.rope.char(a - 1)) { a -= 1 }
while b < n && is_word(self.rope.char(b)) { b += 1 }
a..b
}
fn first_text_col(&self, line: usize) -> usize {
self.rope.line(line).chars().take(self.line_len(line)).take_while(|c| *c == ' ' || *c == '\t').count()
}
fn step(&self, s: &Sel, m: Move) -> (usize, Option<usize>) {
let (line, col) = self.pos(s.head);
let vertical = |lines: isize| {
let want = s.want_col.unwrap_or(col);
let target = (line as isize + lines).clamp(0, self.lines() as isize - 1) as usize;
if target == line {
let edge = if lines < 0 { 0 } else { self.len() };
return (edge, None);
}
(self.at(target, want), Some(want))
};
match m {
Move::Left => (s.head.saturating_sub(1), None),
Move::Right => ((s.head + 1).min(self.len()), None),
Move::Up => vertical(-1),
Move::Down => vertical(1),
Move::PageUp(n) => vertical(-(n as isize)),
Move::PageDown(n) => vertical(n as isize),
Move::WordLeft => (self.word_left(s.head), None),
Move::WordRight => (self.word_right(s.head), None),
Move::Home => {
let t = self.first_text_col(line);
(self.at(line, if col == t { 0 } else { t }), None)
}
Move::End => (self.at(line, usize::MAX), None),
Move::DocStart => (0, None),
Move::DocEnd => (self.len(), None),
}
}
pub fn move_cursors(&mut self, m: Move, extend: bool) {
let next: Vec<Sel> = self.sels.iter().map(|s| {
// a selection collapses towards the direction of travel
if !extend && !s.is_empty() && matches!(m, Move::Left | Move::Right) {
let r = s.range();
return Sel::cursor(if m == Move::Left { r.start } else { r.end });
}
let (h, want) = self.step(s, m);
Sel { anchor: if extend { s.anchor } else { h }, head: h, want_col: want }
}).collect();
self.set_sels(next);
}
pub fn select_all(&mut self) {
self.set_sels(vec![Sel { anchor: 0, head: self.len(), want_col: None }]);
}
/// Inserts text at every cursor; when the paste has one line per cursor, each gets its own.
pub fn insert(&mut self, text: &str, kind: EditKind) {
let parts: Vec<&str> = text.split('\n').collect();
let per_cursor = self.sels.len() > 1 && parts.len() == self.sels.len();
let changes = self.sels.iter().enumerate().map(|(i, s)| (s.range(), if per_cursor { parts[i].to_string() } else { text.to_string() })).collect();
self.apply(changes, kind, |_, st, n| Sel::cursor(st + n));
}
/// Typed text: wraps selections in brackets, closes pairs and types over closers.
pub fn type_text(&mut self, text: &str, p: &Prefs) {
let mut cs = text.chars();
let (Some(c), None) = (cs.next(), cs.next()) else {
return self.insert(text, EditKind::Typing);
};
let close = match c { '(' => ')', '[' => ']', '{' => '}', '"' => '"', '\'' => '\'', '`' => '`', _ => '\0' };
if p.auto_close {
if close != '\0' && self.sels.iter().all(|s| !s.is_empty()) {
let changes = self.sels.iter().map(|s| (s.range(), format!("{c}{}{close}", self.text(s.range())))).collect();
return self.apply(changes, EditKind::Other, |_, st, n| Sel { anchor: st + 1, head: st + n - 1, want_col: None });
}
if matches!(c, ')' | ']' | '}' | '"' | '\'' | '`') && self.sels.iter().all(|s| s.is_empty() && s.head < self.len() && self.rope.char(s.head) == c) {
let next = self.sels.iter().map(|s| Sel::cursor(s.head + 1)).collect();
return self.set_sels(next);
}
let boundary = |s: &Sel| {
let after = (s.head < self.len()).then(|| self.rope.char(s.head));
let before = (s.head > 0).then(|| self.rope.char(s.head - 1));
let free_after = after.is_none_or(|a| a.is_whitespace() || ")]}>,;:".contains(a));
let quote = matches!(c, '"' | '\'' | '`');
free_after && !(quote && before.is_some_and(is_word))
};
if close != '\0' && self.sels.iter().all(|s| s.is_empty() && boundary(s)) {
let changes = self.sels.iter().map(|s| (s.range(), format!("{c}{close}"))).collect();
return self.apply(changes, EditKind::Typing, |_, st, _| Sel::cursor(st + 1));
}
}
self.insert(text, EditKind::Typing);
}
pub fn newline(&mut self, p: &Prefs) {
let items: Vec<(std::ops::Range<usize>, String, usize)> = self.sels.iter().map(|s| {
let r = s.range();
let (line, col) = self.pos(r.start);
let lt = self.line_text(line);
let indent: String = lt.chars().take(col).take_while(|c| *c == ' ' || *c == '\t').collect();
let before = lt.chars().take(col).collect::<String>();
let before = before.trim_end();
let opens = before.ends_with(['{', '(', '[']) || before.ends_with(':');
let closes = r.end < self.len() && matches!(self.rope.char(r.end), '}' | ')' | ']');
let unit = if p.spaces { " ".repeat(p.tab_width) } else { "\t".to_string() };
let mut t = format!("\n{indent}");
let mut back = 0;
if opens {
t.push_str(&unit);
if closes && !before.ends_with(':') {
let tail = format!("\n{indent}");
back = tail.chars().count();
t.push_str(&tail);
}
}
(r, t, back)
}).collect();
let backs: Vec<usize> = items.iter().map(|i| i.2).collect();
let mut order: Vec<usize> = (0..items.len()).collect();
order.sort_by_key(|i| items[*i].0.start);
let ordered_backs: Vec<usize> = order.iter().map(|i| backs[*i]).collect();
self.apply(items.into_iter().map(|i| (i.0, i.1)).collect(), EditKind::Other, move |i, st, n| Sel::cursor(st + n - ordered_backs[i]));
}
pub fn backspace(&mut self, p: &Prefs) {
let changes = self.sels.iter().map(|s| {
if !s.is_empty() {
return (s.range(), String::new());
}
let at = s.head;
if at == 0 {
return (0..0, String::new());
}
let (line, col) = self.pos(at);
let lead = self.first_text_col(line);
// inside indentation, remove back to the previous tab stop
if col > 0 && col <= lead && p.spaces && self.rope.char(at - 1) == ' ' {
let n = ((col - 1) % p.tab_width) + 1;
return (at - n..at, String::new());
}
let prev = self.rope.char(at - 1);
let next = (at < self.len()).then(|| self.rope.char(at));
let pair = matches!((prev, next), ('(', Some(')')) | ('[', Some(']')) | ('{', Some('}')) | ('"', Some('"')) | ('\'', Some('\'')) | ('`', Some('`')));
(at - 1..if pair { at + 1 } else { at }, String::new())
}).collect();
self.apply(changes, EditKind::Deleting, |_, st, _| Sel::cursor(st));
}
pub fn delete_forward(&mut self) {
let n = self.len();
let changes = self.sels.iter().map(|s| (if s.is_empty() { s.head..(s.head + 1).min(n) } else { s.range() }, String::new())).collect();
self.apply(changes, EditKind::Deleting, |_, st, _| Sel::cursor(st));
}
pub fn delete_word(&mut self, forward: bool) {
let changes = self.sels.iter().map(|s| {
let r = if !s.is_empty() { s.range() } else if forward { s.head..self.word_right(s.head) } else { self.word_left(s.head)..s.head };
(r, String::new())
}).collect();
self.apply(changes, EditKind::Deleting, |_, st, _| Sel::cursor(st));
}
/// Whole lines covered by the selections, merged, first to last.
fn covered_lines(&self) -> Vec<(usize, usize)> {
let mut v: Vec<(usize, usize)> = vec![];
for s in &self.sels {
let r = s.range();
let a = self.pos(r.start).0;
let (mut b, c) = self.pos(r.end);
if !s.is_empty() && c == 0 && b > a { b -= 1 }
match v.last_mut() {
Some(l) if a <= l.1 + 1 => l.1 = l.1.max(b),
_ => v.push((a, b)),
}
}
v
}
fn line_start(&self, l: usize) -> usize {
self.rope.line_to_char(l)
}
/// Runs `f` for each line's change, keeping selections on the same text.
fn edit_lines(&mut self, f: impl Fn(&Buffer, usize) -> Option<(std::ops::Range<usize>, String)>) {
let mut changes = vec![];
for (a, b) in self.covered_lines() {
for l in a..=b {
if let Some(c) = f(self, l) {
changes.push(c);
}
}
}
let map = |at: usize| {
let mut pos = at as isize;
for (r, s) in &changes {
if r.end <= at { pos += s.chars().count() as isize - r.len() as isize }
else if r.start < at { pos += (s.chars().count() as isize - r.len() as isize).max(r.start as isize - at as isize) }
}
pos.max(0) as usize
};
let next: Vec<Sel> = self.sels.iter().map(|s| Sel { anchor: map(s.anchor), head: map(s.head), want_col: None }).collect();
self.apply(changes, EditKind::Other, |_, _, _| Sel::cursor(0));
self.set_sels(next);
}
pub fn indent(&mut self, p: &Prefs) {
if self.sels.iter().all(|s| s.is_empty() || self.pos(s.anchor).0 == self.pos(s.head).0) {
let changes = self.sels.iter().map(|s| {
let t = if p.spaces { " ".repeat(p.tab_width - self.pos(s.range().start).1 % p.tab_width) } else { "\t".to_string() };
(s.range(), t)
}).collect();
return self.apply(changes, EditKind::Typing, |_, st, n| Sel::cursor(st + n));
}
let unit = if p.spaces { " ".repeat(p.tab_width) } else { "\t".to_string() };
self.edit_lines(|b, l| (b.line_len(l) > 0).then(|| (b.line_start(l)..b.line_start(l), unit.clone())));
}
pub fn unindent(&mut self, p: &Prefs) {
let w = p.tab_width;
self.edit_lines(|b, l| {
let t = b.line_text(l);
let n = if t.starts_with('\t') { 1 } else { t.chars().take(w).take_while(|c| *c == ' ').count() };
(n > 0).then(|| (b.line_start(l)..b.line_start(l) + n, String::new()))
});
}
pub fn toggle_comment(&mut self, line: Option<&str>, block: Option<(&str, &str)>) {
let Some(tok) = line else {
let Some((a, b)) = block else { return };
let changes = self.sels.iter().map(|s| {
let t = self.text(s.range());
let inner = t.strip_prefix(a).and_then(|x| x.strip_suffix(b));
(s.range(), inner.map(str::to_string).unwrap_or_else(|| format!("{a}{t}{b}")))
}).collect();
return self.apply(changes, EditKind::Other, |_, st, n| Sel { anchor: st, head: st + n, want_col: None });
};
let lines = self.covered_lines();
let all = lines.iter().all(|(a, b)| (*a..=*b).all(|l| {
let t = self.line_text(l);
t.trim().is_empty() || t.trim_start().starts_with(tok)
}));
let col = lines.iter().flat_map(|(a, b)| *a..=*b).filter(|l| !self.line_text(*l).trim().is_empty()).map(|l| self.first_text_col(l)).min().unwrap_or(0);
self.edit_lines(|b, l| {
let t = b.line_text(l);
if t.trim().is_empty() {
return None;
}
if all {
let c = b.first_text_col(l);
let n = tok.chars().count();
let extra = t.chars().nth(c + n).is_some_and(|x| x == ' ') as usize;
let s = b.line_start(l) + c;
Some((s..s + n + extra, String::new()))
} else {
let s = b.line_start(l) + col;
Some((s..s, format!("{tok} ")))
}
});
}
pub fn duplicate_lines(&mut self) {
let mut changes = vec![];
for (a, b) in self.covered_lines() {
let end = if b + 1 < self.lines() { self.line_start(b + 1) } else { self.len() };
let mut t = self.text(self.line_start(a)..end);
if !t.ends_with('\n') { t.insert(0, '\n'); }
changes.push((end..end, t));
}
let sels = self.sels.clone();
self.apply(changes, EditKind::Other, |_, _, _| Sel::cursor(0));
self.set_sels(sels);
}
pub fn delete_lines(&mut self) {
let mut changes = vec![];
for (a, b) in self.covered_lines() {
let start = self.line_start(a);
let r = if b + 1 < self.lines() { start..self.line_start(b + 1) } else { start.saturating_sub(1)..self.len() };
changes.push((r, String::new()));
}
self.apply(changes, EditKind::Other, |_, st, _| Sel::cursor(st));
}
pub fn move_lines(&mut self, up: bool) {
let cov = self.covered_lines();
let (first, last) = (cov[0].0, cov[cov.len() - 1].1);
if (up && first == 0) || (!up && last + 1 >= self.lines()) {
return;
}
let (a, b) = if up { (first - 1, last) } else { (first, last + 1) };
let end = if b + 1 < self.lines() { self.line_start(b + 1) } else { self.len() };
let start = self.line_start(a);
let mut ls: Vec<String> = (a..=b).map(|l| self.line_text(l)).collect();
let shift;
if up {
let l = ls.remove(0);
shift = -((l.chars().count() + 1) as isize);
ls.push(l);
} else {
let l = ls.pop().unwrap();
shift = l.chars().count() as isize + 1;
ls.insert(0, l);
}
let mut t = ls.join("\n");
if b + 1 < self.lines() { t.push('\n') }
let sels: Vec<Sel> = self.sels.iter().map(|s| Sel { anchor: (s.anchor as isize + shift) as usize, head: (s.head as isize + shift) as usize, want_col: s.want_col }).collect();
self.apply(vec![(start..end, t)], EditKind::Other, |_, _, _| Sel::cursor(0));
self.set_sels(sels);
}
pub fn join_lines(&mut self) {
let mut changes = vec![];
for (a, b) in self.covered_lines() {
let b = if a == b { (a + 1).min(self.lines() - 1) } else { b };
for l in a..b {
let e = self.at(l, usize::MAX);
let s = self.line_start(l + 1) + self.first_text_col(l + 1);
changes.push((e..s, " ".to_string()));
}
}
self.apply(changes, EditKind::Other, |_, st, _| Sel::cursor(st));
}
pub fn transform(&mut self, f: impl Fn(&str) -> String) {
let changes = self.sels.iter().map(|s| {
let r = if s.is_empty() { self.word_at(s.head) } else { s.range() };
let t = f(&self.text(r.clone()));
(r, t)
}).collect();
self.apply(changes, EditKind::Other, |_, st, n| Sel { anchor: st, head: st + n, want_col: None });
}
pub fn sort_lines(&mut self) {
let mut changes = vec![];
for (a, b) in self.covered_lines() {
if a == b { continue }
let mut ls: Vec<String> = (a..=b).map(|l| self.line_text(l)).collect();
ls.sort();
changes.push((self.line_start(a)..self.at(b, usize::MAX), ls.join("\n")));
}
self.apply(changes, EditKind::Other, |_, st, n| Sel { anchor: st, head: st + n, want_col: None });
}
pub fn trim_trailing(&mut self) {
let mut changes = vec![];
for l in 0..self.lines() {
let t = self.line_text(l);
let n = t.trim_end_matches([' ', '\t']).chars().count();
let total = t.chars().count();
if n < total {
let s = self.line_start(l);
changes.push((s + n..s + total, String::new()));
}
}
let map: Vec<(usize, usize)> = changes.iter().map(|c: &(std::ops::Range<usize>, String)| (c.0.start, c.0.len())).collect();
let fix = |at: usize| at - map.iter().map(|(s, n)| if *s + *n <= at { *n } else if *s < at { at - *s } else { 0 }).sum::<usize>();
let next: Vec<Sel> = self.sels.iter().map(|s| Sel { anchor: fix(s.anchor), head: fix(s.head), want_col: None }).collect();
self.apply(changes, EditKind::Other, |_, _, _| Sel::cursor(0));
self.set_sels(next);
}
/// Adds a cursor on the line above or below each edge cursor (Kate's Ctrl+Alt+Up/Down).
pub fn add_cursor_vertical(&mut self, down: bool) {
let edge = if down { self.sels.iter().max_by_key(|s| s.head) } else { self.sels.iter().min_by_key(|s| s.head) };
let Some(s) = edge.copied() else { return };
let (l, c) = self.pos(s.head);
let want = s.want_col.unwrap_or(c);
if (down && l + 1 >= self.lines()) || (!down && l == 0) {
return;
}
let t = if down { l + 1 } else { l - 1 };
let at = self.at(t, want);
let mut v = self.sels.clone();
v.push(Sel { anchor: at, head: at, want_col: Some(want) });
self.set_sels(v);
}
/// Selects the word under the cursor, then each next occurrence (Kate's Alt+J).
pub fn select_next(&mut self) {
let last = self.sels[self.primary];
if last.is_empty() {
let r = self.word_at(last.head);
if r.is_empty() { return }
let mut v = self.sels.clone();
v[self.primary] = Sel { anchor: r.start, head: r.end, want_col: None };
return self.set_sels(v);
}
let needle = self.text(last.range());
let hay = self.rope.to_string();
let byte = self.rope.char_to_byte(last.range().end);
let hit = hay[byte..].find(&needle).map(|i| i + byte).or_else(|| hay.find(&needle));
let Some(b) = hit else { return };
let a = self.rope.byte_to_char(b);
if self.sels.iter().any(|s| s.range().start == a) { return }
let mut v = self.sels.clone();
v.push(Sel { anchor: a, head: a + needle.chars().count(), want_col: None });
self.set_sels(v);
}
/// The bracket matching one next to a position.
pub fn matching_bracket(&self, at: usize) -> Option<(usize, usize)> {
let pairs = [('(', ')'), ('[', ']'), ('{', '}')];
let probe = |i: usize| -> Option<(usize, usize)> {
let c = self.rope.get_char(i)?;
let (open, close, fwd) = pairs.iter().find_map(|(a, b)| if c == *a { Some((*a, *b, true)) } else if c == *b { Some((*a, *b, false)) } else { None })?;
let (mut depth, mut j, mut steps) = (0i32, i as isize, 0);
while j >= 0 && (j as usize) < self.len() && steps < 200_000 {
let x = self.rope.char(j as usize);
if x == open { depth += if fwd { 1 } else { -1 } }
if x == close { depth += if fwd { -1 } else { 1 } }
if depth == 0 { return Some((i, j as usize)) }
j += if fwd { 1 } else { -1 };
steps += 1;
}
None
};
probe(at).or_else(|| at.checked_sub(1).and_then(probe))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn b(t: &str) -> Buffer { Buffer::new(t) }
fn text(b: &Buffer) -> String { b.rope.to_string() }
fn p() -> Prefs { Prefs::default() }
#[test]
fn typing_undoes_as_one_group() {
let mut x = b("");
for c in "hello".chars() { x.type_text(&c.to_string(), &p()); }
assert_eq!(text(&x), "hello");
assert!(x.is_modified());
x.undo();
assert_eq!(text(&x), "");
assert!(!x.is_modified());
x.redo();
assert_eq!(text(&x), "hello");
}
#[test]
fn multi_cursor_types_everywhere_and_undoes() {
let mut x = b("a\nb\nc");
x.add_cursor_vertical(true);
x.add_cursor_vertical(true);
assert_eq!(x.sels.len(), 3);
x.insert("> ", EditKind::Other);
assert_eq!(text(&x), "> a\n> b\n> c");
x.undo();
assert_eq!(text(&x), "a\nb\nc");
assert_eq!(x.sels.len(), 3);
}
#[test]
fn brackets_pair_wrap_and_type_over() {
let mut x = b("");
x.type_text("(", &p());
assert_eq!(text(&x), "()");
x.type_text(")", &p());
assert_eq!(text(&x), "()");
assert_eq!(x.head(), 2);
let mut y = b("word");
y.select_all();
y.type_text("[", &p());
assert_eq!(text(&y), "[word]");
assert_eq!(y.selected_text(), "word");
}
#[test]
fn apostrophe_after_a_word_does_not_pair() {
let mut x = b("don");
x.set_cursor(3);
x.type_text("'", &p());
assert_eq!(text(&x), "don'");
}
#[test]
fn newline_indents_and_splits_braces() {
let mut x = b(" fn a() {}");
x.set_cursor(10);
x.newline(&p());
assert_eq!(text(&x), " fn a() {\n \n }");
assert_eq!(x.pos(x.head()), (1, 6));
}
#[test]
fn multi_cursor_newline_keeps_each_cursor() {
let mut x = b("{}\n{}");
x.set_sels(vec![Sel::cursor(1), Sel::cursor(4)]);
x.newline(&p());
assert_eq!(text(&x), "{\n \n}\n{\n \n}");
assert_eq!(x.sels.len(), 2);
assert_eq!(x.pos(x.sels[0].head), (1, 4));
assert_eq!(x.pos(x.sels[1].head), (4, 4));
}
#[test]
fn backspace_clears_indent_stop_and_pairs() {
let mut x = b(" a");
x.set_cursor(8);
x.backspace(&p());
assert_eq!(text(&x), " a");
let mut y = b("()");
y.set_cursor(1);
y.backspace(&p());
assert_eq!(text(&y), "");
}
#[test]
fn comment_toggles_on_and_off() {
let mut x = b(" a\n b");
x.select_all();
x.toggle_comment(Some("//"), None);
assert_eq!(text(&x), " // a\n // b");
x.toggle_comment(Some("//"), None);
assert_eq!(text(&x), " a\n b");
}
#[test]
fn move_and_duplicate_lines() {
let mut x = b("one\ntwo\nthree");
x.set_cursor(x.at(1, 1));
x.move_lines(true);
assert_eq!(text(&x), "two\none\nthree");
assert_eq!(x.pos(x.head()), (0, 1));
x.move_lines(false);
x.move_lines(false);
assert_eq!(text(&x), "one\nthree\ntwo");
assert_eq!(x.pos(x.head()), (2, 1));
x.duplicate_lines();
assert_eq!(text(&x), "one\nthree\ntwo\ntwo");
}
#[test]
fn selection_kept_through_indent() {
let mut x = b("a\nb");
x.select_all();
x.indent(&p());
assert_eq!(text(&x), " a\n b");
x.unindent(&p());
assert_eq!(text(&x), "a\nb");
}
#[test]
fn next_occurrence_wraps() {
let mut x = b("foo bar foo");
x.set_cursor(1);
x.select_next();
assert_eq!(x.selected_text(), "foo");
x.select_next();
assert_eq!(x.sels.len(), 2);
}
#[test]
fn saved_point_survives_undo_past_it() {
let mut x = b("");
x.insert("a", EditKind::Other);
x.mark_saved();
x.insert("b", EditKind::Other);
x.undo();
assert!(!x.is_modified());
x.undo();
assert!(x.is_modified());
x.insert("c", EditKind::Other);
assert!(x.is_modified());
}
#[test]
fn matching_brackets() {
let x = b("a(b[c]d)");
assert_eq!(x.matching_bracket(1), Some((1, 7)));
assert_eq!(x.matching_bracket(8), Some((7, 1)));
}
#[test]
fn vertical_move_keeps_column() {
let mut x = b("long line\nx\nlong line");
x.set_cursor(6);
x.move_cursors(Move::Down, false);
assert_eq!(x.pos(x.head()), (1, 1));
x.move_cursors(Move::Down, false);
assert_eq!(x.pos(x.head()), (2, 6));
}
}

419
src/text/doc.rs Normal file
View file

@ -0,0 +1,419 @@
//! An open file: its buffer plus highlighting, folding, and file details.
use super::buffer::{Buffer, LineChange};
use crate::syntax::def::DefMeta;
use crate::syntax::engine::Highlighter;
use crate::syntax::{FoldEvent, Registry, Span, State};
use std::collections::{BTreeSet, HashMap};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::SystemTime;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Eol { Lf, CrLf, Cr }
impl Eol {
pub fn label(self) -> &'static str {
match self { Eol::Lf => "LF", Eol::CrLf => "CRLF", Eol::Cr => "CR" }
}
pub fn text(self) -> &'static str {
match self { Eol::Lf => "\n", Eol::CrLf => "\r\n", Eol::Cr => "\r" }
}
}
#[derive(Clone, Default)]
pub struct LineHl {
pub spans: Arc<Vec<Span>>,
pub folds: Arc<Vec<(u32, FoldEvent)>>,
pub end: Option<Arc<State>>,
}
pub struct Doc {
pub id: u64,
pub buf: Buffer,
pub path: Option<PathBuf>,
pub language: String,
pub meta: DefMeta,
pub encoding: &'static encoding_rs::Encoding,
pub bom: bool,
pub eol: Eol,
pub mtime: Option<SystemTime>,
pub hl: Vec<LineHl>,
start_state: Option<Arc<State>>,
/// First line that may be out of date, and the line up to which it certainly is.
dirty: Option<(usize, usize)>,
pub folded: BTreeSet<usize>,
pub fold_ends: HashMap<usize, usize>,
fold_version: u64,
pub bookmarks: BTreeSet<usize>,
/// Bumped whenever the colours of any line change; the preview redraws from this.
pub hl_version: u64,
/// App time of the last save, for the tick on the tab.
pub saved_at: f64,
}
fn decode(bytes: &[u8]) -> (String, &'static encoding_rs::Encoding, bool) {
if let Some((enc, skip)) = encoding_rs::Encoding::for_bom(bytes) {
let (t, _) = enc.decode_without_bom_handling(&bytes[skip..]);
return (t.into_owned(), enc, true);
}
match std::str::from_utf8(bytes) {
Ok(s) => (s.to_string(), encoding_rs::UTF_8, false),
Err(_) => {
let (t, _) = encoding_rs::WINDOWS_1252.decode_without_bom_handling(bytes);
(t.into_owned(), encoding_rs::WINDOWS_1252, false)
}
}
}
impl Doc {
pub fn new(id: u64, text: &str, path: Option<PathBuf>, reg: &mut Registry) -> Doc {
let eol = if text.contains("\r\n") { Eol::CrLf } else if text.contains('\r') { Eol::Cr } else { Eol::Lf };
let norm = if eol == Eol::Lf { text.to_string() } else { text.replace("\r\n", "\n").replace('\r', "\n") };
let mut d = Doc {
id, buf: Buffer::new(&norm), path, language: String::new(), meta: DefMeta::default(),
encoding: encoding_rs::UTF_8, bom: false, eol, mtime: None, hl: vec![], start_state: None,
dirty: None, folded: BTreeSet::new(), fold_ends: HashMap::new(), fold_version: u64::MAX,
bookmarks: BTreeSet::new(), hl_version: 0, saved_at: f64::MIN,
};
let name = d.file_name();
let first = d.buf.line_text(0);
let lang = reg.detect(&name, &first).map(str::to_string).unwrap_or_else(|| "None".to_string());
d.set_language(&lang, reg);
d
}
pub fn open(id: u64, path: PathBuf, reg: &mut Registry) -> std::io::Result<Doc> {
let bytes = std::fs::read(&path)?;
let (text, enc, bom) = decode(&bytes);
let mtime = std::fs::metadata(&path).and_then(|m| m.modified()).ok();
let mut d = Doc::new(id, &text, Some(path), reg);
d.encoding = enc;
d.bom = bom;
d.mtime = mtime;
Ok(d)
}
/// Replaces the text with what's on disk, as an edit, so it can be undone.
pub fn reload(&mut self) -> std::io::Result<()> {
let Some(path) = self.path.clone() else { return Ok(()) };
let bytes = std::fs::read(&path)?;
let (text, enc, bom) = decode(&bytes);
let keep = self.buf.head();
self.buf.select_all();
self.buf.insert(&text.replace("\r\n", "\n").replace('\r', "\n"), super::EditKind::Other);
self.buf.set_cursor(keep);
self.encoding = enc;
self.bom = bom;
self.mtime = std::fs::metadata(&path).and_then(|m| m.modified()).ok();
// it matches the disk now, whatever it held before
self.buf.mark_saved();
Ok(())
}
pub fn file_name(&self) -> String {
self.path.as_ref().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()
}
pub fn title(&self) -> String {
let n = self.file_name();
if n.is_empty() { "Untitled".to_string() } else { n }
}
pub fn set_language(&mut self, name: &str, reg: &mut Registry) {
self.language = name.to_string();
self.meta = reg.meta(name);
self.start_state = reg.initial_state(name).map(Arc::new);
self.hl = vec![LineHl::default(); self.buf.lines()];
self.dirty = Some((0, self.buf.lines()));
self.hl_version += 1;
self.fold_version = u64::MAX;
}
pub fn save(&mut self) -> std::io::Result<()> {
let Some(path) = self.path.clone() else {
return Err(std::io::Error::other("no file name"));
};
let mut text = self.buf.rope.to_string();
if self.eol != Eol::Lf {
text = text.replace('\n', self.eol.text());
}
let (enc, _, _) = self.encoding.encode(&text);
let mut bytes = Vec::with_capacity(enc.len() + 3);
if self.bom && self.encoding == encoding_rs::UTF_8 {
bytes.extend_from_slice(&[0xEF, 0xBB, 0xBF]);
}
bytes.extend_from_slice(&enc);
// write beside the file, then swap, so a crash mid-save can't leave half a file
// (a symlink stays a link: the swap happens at the file it points to)
let target = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
let name = target.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let tmp = target.with_file_name(format!(".{name}.damson-tmp"));
std::fs::write(&tmp, &bytes)?;
if let Ok(m) = std::fs::metadata(&target) {
let _ = std::fs::set_permissions(&tmp, m.permissions());
}
std::fs::rename(&tmp, &target)?;
self.mtime = std::fs::metadata(&path).and_then(|m| m.modified()).ok();
self.buf.mark_saved();
Ok(())
}
/// Brings the line tables in step with edits made to the buffer.
pub fn sync_edits(&mut self) {
let changes: Vec<LineChange> = std::mem::take(&mut self.buf.changes);
for c in changes {
let end = (c.first + c.old).min(self.hl.len());
let first = c.first.min(self.hl.len());
self.hl.splice(first..end, std::iter::repeat_n(LineHl::default(), c.new));
let delta = c.new as isize - c.old as isize;
let shift = |s: &BTreeSet<usize>| -> BTreeSet<usize> {
s.iter().filter_map(|l| {
if *l < c.first { Some(*l) }
else if *l >= c.first + c.old { Some((*l as isize + delta) as usize) }
else if delta == 0 { Some(*l) } else { None }
}).collect()
};
self.folded = shift(&self.folded);
self.bookmarks = shift(&self.bookmarks);
let (a, b) = self.dirty.unwrap_or((c.first, c.first));
let b = if b >= c.first + c.old { (b as isize + delta) as usize } else { c.first + c.new };
self.dirty = Some((a.min(c.first), b.max(c.first + c.new)));
}
self.hl.resize(self.buf.lines(), LineHl::default());
}
pub fn highlight_pending(&self) -> bool {
self.dirty.is_some() && self.start_state.is_some()
}
/// Highlights onward from the first dirty line until `until`, or until `max_lines` are done,
/// stopping early when a line ends in the same state it had before.
pub fn highlight(&mut self, reg: &Registry, until: usize, max_lines: usize) {
self.sync_edits();
let Some(start_state) = self.start_state.clone() else {
self.dirty = None;
return;
};
let Some((mut line, must)) = self.dirty else { return };
let total = self.buf.lines();
let mut state: State = if line == 0 {
(*start_state).clone()
} else {
match self.hl.get(line - 1).and_then(|h| h.end.clone()) {
Some(s) => (*s).clone(),
None => (*start_state).clone(),
}
};
let mut h = Highlighter::new(&reg.compiled);
let mut done = 0;
while line < total && ((line <= until && done < 3000) || done < max_lines) {
let text = self.buf.line_text(line);
let r = h.line(&text, &mut state);
let same = self.hl[line].end.as_deref() == Some(&state);
self.hl[line] = LineHl { spans: Arc::new(r.spans), folds: Arc::new(r.folds), end: Some(Arc::new(state.clone())) };
line += 1;
done += 1;
if same && line >= must {
self.dirty = None;
self.hl_version += 1;
self.fold_version = u64::MAX;
return;
}
}
self.hl_version += 1;
self.fold_version = u64::MAX;
self.dirty = if line >= total { None } else { Some((line, must)) };
}
/// Works out which lines start a foldable range.
pub fn refresh_folds(&mut self, tab: usize) {
if self.fold_version == self.hl_version {
return;
}
self.fold_version = self.hl_version;
self.fold_ends.clear();
if self.meta.indent_fold {
self.indent_folds(tab);
} else {
let mut stack: Vec<(u32, usize)> = vec![];
for (l, h) in self.hl.iter().enumerate() {
for (_, ev) in h.folds.iter() {
match ev {
FoldEvent::Begin(r) => stack.push((*r, l)),
FoldEvent::End(r) => {
if let Some(p) = stack.iter().rposition(|s| s.0 == *r) {
let (_, start) = stack[p];
stack.truncate(p);
if l > start {
let e = self.fold_ends.entry(start).or_insert(l);
*e = (*e).max(l);
}
}
}
}
}
}
}
let keep = self.fold_ends.clone();
self.folded.retain(|l| keep.contains_key(l));
}
fn indent_folds(&mut self, tab: usize) {
let n = self.buf.lines().min(200_000);
let indent: Vec<Option<usize>> = (0..n).map(|l| {
let t = self.buf.line_text(l);
if t.trim().is_empty() { return None }
Some(t.chars().take_while(|c| c.is_whitespace()).map(|c| if c == '\t' { tab } else { 1 }).sum())
}).collect();
let mut stack: Vec<(usize, usize)> = vec![];
let mut last = 0;
for (l, i) in indent.iter().enumerate() {
let Some(i) = i else { continue };
while let Some(&(si, start)) = stack.last() {
if *i <= si {
stack.pop();
if last > start { self.fold_ends.insert(start, last); }
} else { break }
}
stack.push((*i, l));
last = l;
}
for (_, start) in stack {
if last > start { self.fold_ends.insert(start, last); }
}
}
pub fn toggle_fold(&mut self, line: usize) {
if !self.folded.remove(&line) && self.fold_ends.contains_key(&line) {
self.folded.insert(line);
}
}
/// Is this line hidden inside a folded range?
pub fn hidden_lines(&self) -> Vec<(usize, usize)> {
let mut v: Vec<(usize, usize)> = vec![];
for l in &self.folded {
let Some(e) = self.fold_ends.get(l) else { continue };
if v.last().is_some_and(|p| *l < p.1) { continue }
v.push((*l + 1, *e));
}
v
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::syntax::DefStyle;
fn style(d: &Doc, reg: &Registry, line: usize, col: u32) -> DefStyle {
let s = d.hl[line].spans.iter().find(|s| s.start <= col && col < s.end).unwrap();
reg.compiled.styles[s.style as usize].base
}
#[test]
fn opening_a_block_comment_recolours_later_lines_and_undo_restores() {
let mut reg = Registry::scan();
let mut d = Doc::new(1, "let a = 1;\nlet b = 2;\nlet c = 3;\n", Some("x.rs".into()), &mut reg);
d.highlight(&reg, 10, 1000);
assert_eq!(d.language, "Rust");
assert_eq!(style(&d, &reg, 2, 0), DefStyle::Keyword);
d.buf.set_cursor(0);
d.buf.insert("/*", crate::text::EditKind::Other);
d.highlight(&reg, 10, 1000);
assert_eq!(style(&d, &reg, 2, 0), DefStyle::Comment);
d.buf.undo();
d.highlight(&reg, 10, 1000);
assert_eq!(style(&d, &reg, 2, 0), DefStyle::Keyword);
}
#[test]
fn line_tables_track_insert_and_delete() {
let mut reg = Registry::scan();
let mut d = Doc::new(1, "a\nb\nc\n", Some("x.rs".into()), &mut reg);
d.highlight(&reg, 10, 1000);
d.buf.set_cursor(2);
d.buf.insert("x\ny\n", crate::text::EditKind::Other);
d.sync_edits();
assert_eq!(d.hl.len(), d.buf.lines());
d.buf.select_all();
d.buf.insert("", crate::text::EditKind::Other);
d.sync_edits();
assert_eq!(d.hl.len(), 1);
}
#[test]
fn folds_come_from_syntax_and_indentation() {
let mut reg = Registry::scan();
let mut d = Doc::new(1, "fn a() {\n b();\n}\n", Some("x.rs".into()), &mut reg);
d.highlight(&reg, 10, 1000);
d.refresh_folds(4);
assert_eq!(d.fold_ends.get(&0), Some(&2));
let mut p = Doc::new(2, "def a():\n b()\n c()\nd()\n", Some("x.py".into()), &mut reg);
p.highlight(&reg, 10, 1000);
p.refresh_folds(4);
assert_eq!(p.fold_ends.get(&0), Some(&2));
}
#[test]
fn saving_keeps_a_symlink_a_symlink() {
let dir = std::env::temp_dir().join(format!("damson-link-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let (real, link) = (dir.join("real.txt"), dir.join("link.txt"));
std::fs::write(&real, "old").unwrap();
std::os::unix::fs::symlink(&real, &link).unwrap();
let mut reg = Registry::scan();
let mut d = Doc::new(1, "new", Some(link.clone()), &mut reg);
d.save().unwrap();
assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
assert_eq!(std::fs::read_to_string(&real).unwrap(), "new");
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn reload_can_be_undone_and_reads_latin1() {
let dir = std::env::temp_dir().join(format!("damson-reload-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let p = dir.join("a.txt");
std::fs::write(&p, "one").unwrap();
let mut reg = Registry::scan();
let mut d = Doc::open(1, p.clone(), &mut reg).unwrap();
d.buf.insert("unsaved ", crate::text::EditKind::Other);
std::fs::write(&p, [b'c', b'a', b'f', 0xE9]).unwrap();
d.reload().unwrap();
assert_eq!(d.buf.rope.to_string(), "caf\u{e9}");
assert!(!d.buf.is_modified());
d.buf.undo();
assert_eq!(d.buf.rope.to_string(), "unsaved one");
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn jumping_deep_into_a_huge_file_stays_bounded() {
let mut reg = Registry::scan();
let text = "let x = 1;\n".repeat(200_000);
let mut d = Doc::new(1, &text, Some("x.rs".into()), &mut reg);
let t = std::time::Instant::now();
d.highlight(&reg, 190_000, 0);
assert!(d.highlight_pending(), "should stop early and finish in the background");
assert!(t.elapsed().as_millis() < 500, "took {:?}", t.elapsed());
}
#[test]
fn save_round_trips_crlf() {
let dir = std::env::temp_dir().join(format!("damson-doc-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let p = dir.join("a.txt");
std::fs::write(&p, "one\r\ntwo\r\n").unwrap();
let mut reg = Registry::scan();
let mut d = Doc::open(1, p.clone(), &mut reg).unwrap();
assert_eq!(d.eol, Eol::CrLf);
d.buf.set_cursor(0);
d.buf.insert("z", crate::text::EditKind::Other);
d.save().unwrap();
assert_eq!(std::fs::read_to_string(&p).unwrap(), "zone\r\ntwo\r\n");
assert!(!d.buf.is_modified());
std::fs::remove_dir_all(dir).unwrap();
}
}

6
src/text/mod.rs Normal file
View file

@ -0,0 +1,6 @@
pub mod buffer;
pub mod commands;
pub mod doc;
pub use buffer::{Buffer, EditKind, Sel};
pub use doc::Doc;