1use std::collections::VecDeque;
2use std::ops::Range;
3
4use unicode_segmentation::UnicodeSegmentation as _;
5use unicode_width::UnicodeWidthStr as _;
6
7pub const MAX_EDITOR_BYTES: usize = 256 * 1024;
9pub const MAX_EDITOR_HISTORY: usize = 100;
11const MAX_UNDO_STATES: usize = 100;
12const WORD_SEPARATORS: &str = "`~!@#$%^&*()-=+[{]}\\|;:'\",.<>/?";
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
16pub enum EditorError {
17 #[error("editor input exceeds its size limit")]
19 TooLarge,
20 #[error("editor size limit must be non-zero")]
22 InvalidLimit,
23}
24
25#[derive(Debug, Clone)]
26struct EditorSnapshot {
27 text: String,
28 cursor: usize,
29}
30
31#[derive(Debug, Clone)]
33pub struct Editor {
34 text: String,
35 cursor: usize,
36 max_bytes: usize,
37 undo: VecDeque<EditorSnapshot>,
38 kill_buffer: String,
39 history: VecDeque<String>,
40 history_index: Option<usize>,
41 history_draft: Option<EditorSnapshot>,
42}
43
44impl Default for Editor {
45 fn default() -> Self {
46 Self::with_limit("", MAX_EDITOR_BYTES).expect("the default editor limit is valid")
47 }
48}
49
50impl Editor {
51 #[must_use]
53 pub fn new() -> Self {
54 Self::default()
55 }
56
57 pub fn with_limit(text: impl Into<String>, max_bytes: usize) -> Result<Self, EditorError> {
63 if max_bytes == 0 {
64 return Err(EditorError::InvalidLimit);
65 }
66 let text = text.into();
67 if text.len() > max_bytes {
68 return Err(EditorError::TooLarge);
69 }
70 let cursor = text.len();
71 Ok(Self {
72 text,
73 cursor,
74 max_bytes,
75 undo: VecDeque::new(),
76 kill_buffer: String::new(),
77 history: VecDeque::new(),
78 history_index: None,
79 history_draft: None,
80 })
81 }
82
83 #[must_use]
85 pub fn text(&self) -> &str {
86 &self.text
87 }
88
89 #[must_use]
91 pub const fn cursor_byte(&self) -> usize {
92 self.cursor
93 }
94
95 #[must_use]
97 pub fn cursor_display_column(&self) -> usize {
98 let start = self.text[..self.cursor]
99 .rfind('\n')
100 .map_or(0, |index| index + 1);
101 self.text[start..self.cursor].width()
102 }
103
104 pub fn insert_char(&mut self, character: char) -> Result<(), EditorError> {
110 let mut encoded = [0_u8; 4];
111 self.insert_paste(character.encode_utf8(&mut encoded))
112 }
113
114 pub fn insert_paste(&mut self, text: &str) -> Result<(), EditorError> {
120 if self.text.len().saturating_add(text.len()) > self.max_bytes {
121 return Err(EditorError::TooLarge);
122 }
123 if text.is_empty() {
124 return Ok(());
125 }
126 self.record_undo();
127 self.text.insert_str(self.cursor, text);
128 self.cursor += text.len();
129 self.reset_history_navigation();
130 Ok(())
131 }
132
133 pub fn insert_newline(&mut self) -> Result<(), EditorError> {
139 self.insert_char('\n')
140 }
141
142 pub fn move_left(&mut self) {
144 self.cursor = previous_grapheme_boundary(&self.text, self.cursor);
145 }
146
147 pub fn move_right(&mut self) {
149 self.cursor = next_grapheme_boundary(&self.text, self.cursor);
150 }
151
152 pub fn move_word_left(&mut self) {
154 self.cursor = self.previous_word_start();
155 }
156
157 pub fn move_word_right(&mut self) {
159 self.cursor = self.next_word_end();
160 }
161
162 pub fn move_home(&mut self) {
164 self.cursor = self.current_line_start();
165 }
166
167 pub fn move_home_or_previous_line(&mut self) {
169 let start = self.current_line_start();
170 self.cursor = if self.cursor == start && start > 0 {
171 self.text[..start - 1]
172 .rfind('\n')
173 .map_or(0, |index| index + 1)
174 } else {
175 start
176 };
177 }
178
179 pub fn move_end(&mut self) {
181 self.cursor = self.current_line_end();
182 }
183
184 pub fn move_end_or_next_line(&mut self) {
186 let end = self.current_line_end();
187 self.cursor = if self.cursor == end && end < self.text.len() {
188 self.text[end + 1..]
189 .find('\n')
190 .map_or(self.text.len(), |index| end + 1 + index)
191 } else {
192 end
193 };
194 }
195
196 pub fn move_up(&mut self) {
198 let current_start = self.text[..self.cursor]
199 .rfind('\n')
200 .map_or(0, |index| index + 1);
201 if current_start == 0 {
202 return;
203 }
204 let previous_end = current_start - 1;
205 let previous_start = self.text[..previous_end]
206 .rfind('\n')
207 .map_or(0, |index| index + 1);
208 self.cursor = byte_at_display_column(
209 &self.text,
210 previous_start,
211 previous_end,
212 self.cursor_display_column(),
213 );
214 }
215
216 pub fn move_down(&mut self) {
218 let column = self.cursor_display_column();
219 let current_end = self.text[self.cursor..]
220 .find('\n')
221 .map_or(self.text.len(), |index| self.cursor + index);
222 if current_end == self.text.len() {
223 return;
224 }
225 let next_start = current_end + 1;
226 let next_end = self.text[next_start..]
227 .find('\n')
228 .map_or(self.text.len(), |index| next_start + index);
229 self.cursor = byte_at_display_column(&self.text, next_start, next_end, column);
230 }
231
232 pub fn delete_backward(&mut self) -> bool {
234 let start = previous_grapheme_boundary(&self.text, self.cursor);
235 if start == self.cursor {
236 return false;
237 }
238 self.record_undo();
239 self.text.replace_range(start..self.cursor, "");
240 self.cursor = start;
241 self.reset_history_navigation();
242 true
243 }
244
245 pub fn delete_forward(&mut self) -> bool {
247 let end = next_grapheme_boundary(&self.text, self.cursor);
248 if end == self.cursor {
249 return false;
250 }
251 self.record_undo();
252 self.text.replace_range(self.cursor..end, "");
253 self.reset_history_navigation();
254 true
255 }
256
257 pub fn delete_word_backward(&mut self) -> bool {
259 if self.cursor == 0 {
260 return false;
261 }
262 self.kill_range(self.previous_word_start()..self.cursor)
263 }
264
265 pub fn delete_word_forward(&mut self) -> bool {
267 let end = self.next_word_end();
268 self.kill_range(self.cursor..end)
269 }
270
271 pub fn kill_to_line_start(&mut self) -> bool {
273 let start = self.current_line_start();
274 let start = if self.cursor == start && start > 0 {
275 start - 1
276 } else {
277 start
278 };
279 self.kill_range(start..self.cursor)
280 }
281
282 pub fn kill_to_line_end(&mut self) -> bool {
284 let end = self.current_line_end();
285 let end = if self.cursor == end && end < self.text.len() {
286 end + 1
287 } else {
288 end
289 };
290 self.kill_range(self.cursor..end)
291 }
292
293 #[must_use]
295 pub fn has_kill_buffer(&self) -> bool {
296 !self.kill_buffer.is_empty()
297 }
298
299 pub fn yank(&mut self) -> Result<bool, EditorError> {
305 if self.kill_buffer.is_empty() {
306 return Ok(false);
307 }
308 let killed = self.kill_buffer.clone();
309 self.insert_paste(&killed)?;
310 Ok(true)
311 }
312
313 pub fn clear(&mut self) -> bool {
315 if self.text.is_empty() {
316 return false;
317 }
318 self.record_undo();
319 self.text.clear();
320 self.cursor = 0;
321 self.reset_history_navigation();
322 true
323 }
324
325 pub fn undo(&mut self) -> bool {
327 let Some(snapshot) = self.undo.pop_back() else {
328 return false;
329 };
330 self.text = snapshot.text;
331 self.cursor = snapshot.cursor;
332 self.reset_history_navigation();
333 true
334 }
335
336 pub fn submit(&mut self) -> Option<String> {
338 if self.text.trim().is_empty() {
339 return None;
340 }
341 let submitted = std::mem::take(&mut self.text);
342 self.cursor = 0;
343 if self.history.back() != Some(&submitted) {
344 if self.history.len() == MAX_EDITOR_HISTORY {
345 self.history.pop_front();
346 }
347 self.history.push_back(submitted.clone());
348 }
349 self.undo.clear();
350 self.reset_history_navigation();
351 Some(submitted)
352 }
353
354 pub fn previous_history(&mut self) -> bool {
356 if self.history.is_empty() {
357 return false;
358 }
359 let index = self
360 .history_index
361 .map_or(self.history.len() - 1, |index| index.saturating_sub(1));
362 if self.history_index.is_none() {
363 self.history_draft = Some(EditorSnapshot {
364 text: self.text.clone(),
365 cursor: self.cursor,
366 });
367 }
368 self.history_index = Some(index);
369 self.text.clone_from(&self.history[index]);
370 self.cursor = self.text.len();
371 true
372 }
373
374 pub fn next_history(&mut self) -> bool {
376 let Some(index) = self.history_index else {
377 return false;
378 };
379 if index + 1 < self.history.len() {
380 self.history_index = Some(index + 1);
381 self.text.clone_from(&self.history[index + 1]);
382 self.cursor = self.text.len();
383 } else {
384 let draft = self.history_draft.take().unwrap_or(EditorSnapshot {
385 text: String::new(),
386 cursor: 0,
387 });
388 self.text = draft.text;
389 self.cursor = draft.cursor;
390 self.history_index = None;
391 }
392 true
393 }
394
395 fn record_undo(&mut self) {
396 if self.undo.len() == MAX_UNDO_STATES {
397 self.undo.pop_front();
398 }
399 self.undo.push_back(EditorSnapshot {
400 text: self.text.clone(),
401 cursor: self.cursor,
402 });
403 }
404
405 fn reset_history_navigation(&mut self) {
406 self.history_index = None;
407 self.history_draft = None;
408 }
409
410 fn current_line_start(&self) -> usize {
411 self.text[..self.cursor]
412 .rfind('\n')
413 .map_or(0, |index| index + 1)
414 }
415
416 fn current_line_end(&self) -> usize {
417 self.text[self.cursor..]
418 .find('\n')
419 .map_or(self.text.len(), |index| self.cursor + index)
420 }
421
422 fn previous_word_start(&self) -> usize {
423 let prefix = &self.text[..self.cursor];
424 let Some((last_index, character)) = prefix
425 .char_indices()
426 .rev()
427 .find(|(_, character)| !character.is_whitespace())
428 else {
429 return 0;
430 };
431 let run_start = prefix[..last_index]
432 .char_indices()
433 .rev()
434 .find(|(_, character)| character.is_whitespace())
435 .map_or(0, |(index, character)| index + character.len_utf8());
436 let run_end = last_index + character.len_utf8();
437 let mut pieces = split_word_pieces(&prefix[run_start..run_end])
438 .into_iter()
439 .rev()
440 .peekable();
441 let Some((piece_start, piece)) = pieces.next() else {
442 return run_start;
443 };
444 let mut start = run_start + piece_start;
445 if piece.chars().all(is_word_separator) {
446 while let Some((index, piece)) = pieces.peek() {
447 if !piece.chars().all(is_word_separator) {
448 break;
449 }
450 start = run_start + *index;
451 pieces.next();
452 }
453 }
454 start
455 }
456
457 fn next_word_end(&self) -> usize {
458 let suffix = &self.text[self.cursor..];
459 let Some(first_non_whitespace) = suffix.find(|character: char| !character.is_whitespace())
460 else {
461 return self.text.len();
462 };
463 let run = &suffix[first_non_whitespace..];
464 let run = &run[..run.find(char::is_whitespace).unwrap_or(run.len())];
465 let mut pieces = split_word_pieces(run).into_iter().peekable();
466 let Some((start, piece)) = pieces.next() else {
467 return self.cursor + first_non_whitespace;
468 };
469 let word_start = self.cursor + first_non_whitespace + start;
470 let mut end = word_start + piece.len();
471 if piece.chars().all(is_word_separator) {
472 while let Some((index, piece)) = pieces.peek() {
473 if !piece.chars().all(is_word_separator) {
474 break;
475 }
476 end = self.cursor + first_non_whitespace + *index + piece.len();
477 pieces.next();
478 }
479 }
480 end
481 }
482
483 fn kill_range(&mut self, range: Range<usize>) -> bool {
484 if range.is_empty() {
485 return false;
486 }
487 self.record_undo();
488 self.kill_buffer = self.text[range.clone()].to_owned();
489 self.text.replace_range(range.clone(), "");
490 self.cursor = range.start;
491 self.reset_history_navigation();
492 true
493 }
494}
495
496fn is_word_separator(character: char) -> bool {
497 WORD_SEPARATORS.contains(character)
498}
499
500fn split_word_pieces(run: &str) -> Vec<(usize, &str)> {
501 let mut pieces = Vec::new();
502 for (segment_start, segment) in run.split_word_bound_indices() {
503 let mut piece_start = 0;
504 let mut characters = segment.char_indices();
505 let Some((_, first_character)) = characters.next() else {
506 continue;
507 };
508 let mut in_separator = is_word_separator(first_character);
509 for (index, character) in characters {
510 let separator = is_word_separator(character);
511 if separator == in_separator {
512 continue;
513 }
514 pieces.push((segment_start + piece_start, &segment[piece_start..index]));
515 piece_start = index;
516 in_separator = separator;
517 }
518 pieces.push((segment_start + piece_start, &segment[piece_start..]));
519 }
520 pieces
521}
522
523fn previous_grapheme_boundary(text: &str, cursor: usize) -> usize {
524 text[..cursor]
525 .grapheme_indices(true)
526 .next_back()
527 .map_or(cursor, |(index, _)| index)
528}
529
530fn next_grapheme_boundary(text: &str, cursor: usize) -> usize {
531 text[cursor..]
532 .graphemes(true)
533 .next()
534 .map_or(cursor, |grapheme| cursor + grapheme.len())
535}
536
537fn byte_at_display_column(text: &str, start: usize, end: usize, target: usize) -> usize {
538 let mut width = 0_usize;
539 let mut cursor = start;
540 for grapheme in text[start..end].graphemes(true) {
541 let next = width.saturating_add(grapheme.width());
542 if next > target {
543 break;
544 }
545 width = next;
546 cursor += grapheme.len();
547 }
548 cursor
549}