1use crate::{
2 history::History,
3 syntax::{Language, Syntax},
4};
5use indigo_text::edit::{self, Edit};
6use ropey::Rope;
7use std::{
8 borrow::Cow,
9 ops::{Deref, Range},
10 sync::Arc,
11};
12use thiserror::Error;
13
14#[derive(Debug, Error)]
15pub enum Error {
16 #[error("Text is empty")]
17 Empty,
18
19 #[error("Text does not end with a newline")]
20 MissingTrailingNewline,
21}
22
23#[derive(Clone)]
24pub struct Text {
25 rope: Rope,
26 syntax: Option<(Syntax, usize)>,
27 history: History<Arc<Edit>>,
28 log: Vec<Arc<Edit>>,
29 pub readonly: bool,
30}
31
32impl Default for Text {
33 fn default() -> Self {
34 Self {
35 rope: Rope::from("\n"),
36 syntax: None,
37 history: History::default(),
38 log: Vec::new(),
39 readonly: false,
40 }
41 }
42}
43
44impl Text {
45 #[must_use]
46 pub fn new() -> Self {
47 Self::default()
48 }
49
50 #[must_use]
51 pub fn rope(&self) -> &Rope {
52 &self.rope
53 }
54
55 #[must_use]
56 pub fn language(&self) -> Option<Language> {
57 self.syntax_stale().map(|s| s.language())
58 }
59
60 #[must_use]
61 pub fn syntax(&mut self) -> Option<&Syntax> {
62 self.reparse();
63 self.syntax_stale()
64 }
65
66 #[must_use]
67 pub fn syntax_stale(&self) -> Option<&Syntax> {
68 self.syntax.as_ref().map(|(s, _)| s)
69 }
70
71 pub fn insert(&mut self, byte_offset: usize, text: &str) -> anyhow::Result<()> {
72 let mut ops = Edit::new();
73 ops.retain(byte_offset);
74 ops.insert(text);
75 ops.retain_rest(&self.rope)?;
76 self.apply(&ops)?;
77 Ok(())
78 }
79
80 pub fn delete(&mut self, range: Range<usize>) -> anyhow::Result<()> {
81 let mut ops = Edit::new();
82 ops.retain(range.start);
83 ops.delete(&Cow::from(self.rope.slice(range.start..range.end)));
84 if range.end == self.rope.len()
85 && (range.start == 0 || self.rope.byte(range.start - 1) != b'\n')
86 {
87 ops.insert("\n");
88 }
89 ops.retain_rest(&self.rope)?;
90 self.apply(&ops)?;
91 Ok(())
92 }
93
94 pub fn apply(&mut self, ops: &Edit) -> anyhow::Result<()> {
95 anyhow::ensure!(!self.readonly, "Cannot modify readonly text");
96 ops.apply(&mut self.rope)?;
97 let ops = Arc::new(ops.clone());
98 self.history.push(Arc::clone(&ops));
99 self.log.push(ops);
100 if cfg!(debug_assertions) {
101 self.assert_invariants().unwrap();
102 }
103 Ok(())
104 }
105
106 pub fn commit(&mut self) {
107 self.history.commit();
108 }
109
110 pub fn undo(&mut self) -> anyhow::Result<bool> {
111 anyhow::ensure!(!self.readonly, "Cannot modify readonly text");
112 if let Some(opss) = self.history.undo() {
113 for ops in opss.iter().rev() {
114 let ops = ops.invert();
115 ops.apply(&mut self.rope)?;
116 self.log.push(Arc::new(ops));
117 }
118 if cfg!(debug_assertions) {
119 self.assert_invariants().unwrap();
120 }
121 Ok(true)
122 } else {
123 Ok(false)
124 }
125 }
126
127 pub fn redo(&mut self) -> anyhow::Result<bool> {
128 anyhow::ensure!(!self.readonly, "Cannot modify readonly text");
129 if let Some(opss) = self.history.redo() {
130 for ops in opss {
131 ops.apply(&mut self.rope)?;
132 self.log.push(Arc::clone(ops));
133 }
134 if cfg!(debug_assertions) {
135 self.assert_invariants().unwrap();
136 }
137 Ok(true)
138 } else {
139 Ok(false)
140 }
141 }
142
143 pub fn set_language(&mut self, language: Language) {
144 self.syntax = Some((Syntax::parse(language, &self.rope), self.version()));
145 }
146
147 pub fn reparse(&mut self) {
148 let version = self.version();
149 if let Some((syntax, parsed_at)) = &mut self.syntax
150 && *parsed_at < version
151 {
152 syntax.reparse(&self.rope);
153 *parsed_at = version;
154 }
155 }
156
157 #[must_use]
158 pub fn create_anchor(&self, byte_offset: usize) -> Anchor {
159 Anchor::new(self, byte_offset)
160 }
161
162 #[must_use]
163 pub fn resolve_anchor(&self, anchor: &Anchor) -> Option<usize> {
164 anchor.resolve(self)
165 }
166
167 #[must_use]
168 pub fn version(&self) -> usize {
169 self.log.len()
170 }
171
172 #[must_use]
173 pub fn ops_since(&self, version: usize) -> Option<&[Arc<Edit>]> {
174 self.log.get(version..)
175 }
176
177 pub fn assert_invariants(&self) -> anyhow::Result<()> {
178 if self.rope.len() == 0 {
179 anyhow::bail!(Error::Empty);
180 }
181 if self.rope.byte(self.rope.len() - 1) != b'\n' {
182 anyhow::bail!(Error::MissingTrailingNewline);
183 }
184 Ok(())
185 }
186}
187
188impl Deref for Text {
189 type Target = Rope;
190
191 fn deref(&self) -> &Self::Target {
192 &self.rope
193 }
194}
195
196impl<'a> From<&'a str> for Text {
197 fn from(str: &'a str) -> Self {
198 Self::from(Rope::from(str))
199 }
200}
201
202impl From<Rope> for Text {
203 fn from(mut rope: Rope) -> Self {
204 if rope.len() == 0 || rope.byte(rope.len() - 1) != b'\n' {
205 rope.insert(rope.len(), "\n");
206 }
207 Self {
208 rope,
209 ..Self::default()
210 }
211 }
212}
213
214pub struct Anchor {
215 byte_offset: usize,
216 version: usize,
217}
218
219impl Anchor {
220 #[must_use]
221 pub fn new(text: &Text, byte_offset: usize) -> Self {
222 Self {
223 byte_offset,
224 version: text.version(),
225 }
226 }
227
228 #[must_use]
229 pub fn resolve(&self, text: &Text) -> Option<usize> {
230 let mut byte_offset = self.byte_offset;
231 for ops in text.ops_since(self.version)? {
232 byte_offset = ops.map_position(byte_offset, edit::Bias::Forward);
233 }
234 Some(byte_offset)
235 }
236}
237
238#[cfg(test)]
239mod tests {
240 use super::*;
241 use std::cmp::{max, min};
242
243 fn has_trailing_newline(text: &Text) -> bool {
244 let rope = text.rope();
245 rope.len() > 0 && rope.byte(rope.len() - 1) == b'\n'
246 }
247
248 #[test]
249 fn constructors_normalize() {
250 assert_eq!(Text::new().to_string(), "\n");
251 assert_eq!(Text::default().to_string(), "\n");
252 assert_eq!(Text::from("").to_string(), "\n");
253 assert_eq!(Text::from("x").to_string(), "x\n");
254 assert_eq!(Text::from("x\n").to_string(), "x\n");
255 assert_eq!(Text::from(Rope::from("x")).to_string(), "x\n");
256 assert_eq!(Text::from("x\r").to_string(), "x\r\n");
258 }
259
260 #[test]
261 fn delete_to_end_keeps_trailing_newline() {
262 let mut text = Text::from("ab\n");
263 text.delete(1..3).unwrap();
264 assert_eq!(text.to_string(), "a\n");
265
266 let mut text = Text::from("ab\n");
268 text.delete(0..3).unwrap();
269 assert_eq!(text.to_string(), "\n");
270
271 let mut text = Text::from("a\nb\n");
273 text.delete(2..4).unwrap();
274 assert_eq!(text.to_string(), "a\n");
275 }
276
277 #[test]
278 fn undo_redo_keep_trailing_newline() {
279 let mut text = Text::from("ab\n");
280 text.delete(0..3).unwrap();
281 text.commit();
282 assert_eq!(text.to_string(), "\n");
283 assert!(text.undo().unwrap());
284 assert_eq!(text.to_string(), "ab\n");
285 assert!(has_trailing_newline(&text));
286 assert!(text.redo().unwrap());
287 assert_eq!(text.to_string(), "\n");
288 assert!(has_trailing_newline(&text));
289 }
290
291 #[hegel::test(test_cases = 1_000)]
292 fn fuzz(tc: hegel::TestCase) {
293 use hegel::generators as gs;
294 use indigo_text::rope::RopeExt as _;
295 #[derive(Default)]
296 struct StateMachine {
297 text: Text,
298 }
299 #[hegel::state_machine]
300 #[expect(clippy::needless_pass_by_value)]
301 impl StateMachine {
302 #[rule]
303 fn insert(&mut self, tc: hegel::TestCase) {
304 let byte_offset = tc.draw(gs::integers::<usize>().max_value(self.text.len()));
308 let byte_offset = self
309 .text
310 .snap_to_grapheme_start(byte_offset)
311 .expect("Text is never empty");
312 let string = tc.draw(gs::text());
313 self.text.insert(byte_offset, &string).unwrap();
314 }
315 #[rule]
316 fn delete(&mut self, tc: hegel::TestCase) {
317 let a = tc.draw(gs::integers::<usize>().max_value(self.text.len()));
318 let b = tc.draw(gs::integers::<usize>().max_value(self.text.len()));
319 let start = self.text.floor_grapheme_boundary(min(a, b));
320 let end = self.text.floor_grapheme_boundary(max(a, b));
321 self.text.delete(start..end).unwrap();
322 }
323 #[rule]
324 fn commit(&mut self, _: hegel::TestCase) {
325 self.text.commit();
326 }
327 #[rule]
328 fn undo(&mut self, _: hegel::TestCase) {
329 self.text.undo().unwrap();
330 }
331 #[rule]
332 fn redo(&mut self, _: hegel::TestCase) {
333 self.text.redo().unwrap();
334 }
335 #[invariant]
336 fn invariants(&self, _: hegel::TestCase) {
337 self.text.assert_invariants().unwrap();
338 }
339 }
340 hegel::stateful::machine(StateMachine::default()).run(tc);
341 }
342}