1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
use std::path::{Path, PathBuf};
use crate::edit::{Edit, EditHistory};
use crate::error::Result;
use crate::file::FileHandler;
/// Cursor position in the buffer
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Cursor {
/// Line number (0-indexed)
pub row: usize,
/// Column in actual string (0-indexed)
pub col: usize,
/// Visual column (accounting for tabs)
pub render_col: usize,
/// Preferred column for vertical movement
pub desired_col: usize,
}
impl Cursor {
/// Create a new cursor at position (0, 0)
pub fn new() -> Self {
Self {
row: 0,
col: 0,
render_col: 0,
desired_col: 0,
}
}
}
impl Default for Cursor {
fn default() -> Self {
Self::new()
}
}
/// Text buffer with cursor and editing state
pub struct Buffer {
/// Lines of text in the buffer
lines: Vec<String>,
/// Current cursor position
cursor: Cursor,
/// File path if opened from a file
filename: Option<PathBuf>,
/// Whether the buffer has been modified
modified: bool,
/// Cut/copy buffer for storing cut or copied text
cutbuffer: Vec<String>,
/// Mark position for text selection
mark: Option<Cursor>,
/// Edit history for undo/redo operations
edit_history: EditHistory,
/// Tab size for cursor calculations
tab_size: usize,
}
impl Buffer {
/// Create a new empty buffer
pub fn new() -> Self {
Self {
lines: vec![String::new()],
cursor: Cursor::new(),
filename: None,
modified: false,
cutbuffer: Vec::new(),
mark: None,
edit_history: EditHistory::new(),
tab_size: 4,
}
}
/// Create a buffer from a file
pub fn from_file(path: &Path) -> Result<Self> {
let lines = FileHandler::read_file(path)?;
Ok(Self {
lines,
cursor: Cursor::new(),
filename: Some(path.to_path_buf()),
modified: false,
cutbuffer: Vec::new(),
mark: None,
edit_history: EditHistory::new(),
tab_size: 4,
})
}
/// Set the tab size for cursor calculations
pub fn set_tab_size(&mut self, size: usize) {
self.tab_size = size;
self.update_render_col();
}
/// Get the current cursor position
pub fn cursor(&self) -> &Cursor {
&self.cursor
}
/// Get a mutable reference to the cursor
pub fn cursor_mut(&mut self) -> &mut Cursor {
&mut self.cursor
}
/// Get the filename if set
pub fn filename(&self) -> Option<&PathBuf> {
self.filename.as_ref()
}
/// Set the filename
pub fn set_filename(&mut self, filename: PathBuf) {
self.filename = Some(filename);
}
/// Check if the buffer has been modified
pub fn is_modified(&self) -> bool {
self.modified
}
/// Get the number of lines in the buffer
pub fn len(&self) -> usize {
self.lines.len()
}
/// Check if the buffer is empty
pub fn is_empty(&self) -> bool {
self.lines.is_empty() || (self.lines.len() == 1 && self.lines[0].is_empty())
}
/// Get a line by index
pub fn get_line(&self, row: usize) -> Option<&str> {
self.lines.get(row).map(|s| s.as_str())
}
/// Get all lines
pub fn lines(&self) -> &[String] {
&self.lines
}
/// Get the cutbuffer
pub fn cutbuffer(&self) -> &[String] {
&self.cutbuffer
}
/// Get a mutable reference to the edit history
pub fn edit_history_mut(&mut self) -> &mut EditHistory {
&mut self.edit_history
}
/// Cut the current line to the cutbuffer
/// If append is true, append to existing cutbuffer; otherwise, clear it first
pub fn cut_line(&mut self, append: bool) {
let row = self.cursor.row;
// Ensure the row exists
if row >= self.lines.len() {
return;
}
// Get the current line
let line = self.lines[row].clone();
if append {
// Append to existing cutbuffer
self.cutbuffer.push(line);
} else {
// Clear cutbuffer and add current line
self.cutbuffer.clear();
self.cutbuffer.push(line);
}
// Remove the line from the buffer
self.lines.remove(row);
// If we removed the last line, add an empty line
if self.lines.is_empty() {
self.lines.push(String::new());
}
// Adjust cursor position
if row >= self.lines.len() {
self.cursor.row = self.lines.len().saturating_sub(1);
}
// Keep cursor at the beginning of the line
self.cursor.col = 0;
self.cursor.desired_col = 0;
self.update_render_col();
self.modified = true;
}
/// Paste the cutbuffer at the current cursor position
pub fn paste(&mut self) {
if self.cutbuffer.is_empty() {
return;
}
let row = self.cursor.row;
let col = self.cursor.col;
// Ensure the row exists
if row >= self.lines.len() {
return;
}
if self.cutbuffer.len() == 1 {
// Single line paste: insert at cursor position
let paste_text = &self.cutbuffer[0];
let current_line = &self.lines[row];
// Split current line at cursor
let before = ¤t_line[..col];
let after = ¤t_line[col..];
// Insert the pasted text
self.lines[row] = format!("{}{}{}", before, paste_text, after);
// Move cursor to end of pasted text
self.cursor.col = col + paste_text.len();
} else {
// Multi-line paste
let current_line = &self.lines[row];
let before = current_line[..col].to_string();
let after = current_line[col..].to_string();
// First line: append to the part before cursor
let mut first_line = before;
first_line.push_str(&self.cutbuffer[0]);
self.lines[row] = first_line;
// Insert middle lines
for (i, line) in self.cutbuffer.iter().enumerate().skip(1).take(self.cutbuffer.len() - 2) {
self.lines.insert(row + i, line.clone());
}
// Last line: prepend to the part after cursor
let mut last_line = self.cutbuffer[self.cutbuffer.len() - 1].clone();
last_line.push_str(&after);
self.lines.insert(row + self.cutbuffer.len() - 1, last_line);
// Move cursor to end of pasted content
self.cursor.row = row + self.cutbuffer.len() - 1;
self.cursor.col = self.cutbuffer[self.cutbuffer.len() - 1].len();
}
self.cursor.desired_col = self.cursor.col;
self.update_render_col();
self.modified = true;
}
/// Copy the current line to the cutbuffer without removing it
pub fn copy_line(&mut self) {
let row = self.cursor.row;
// Ensure the row exists
if row >= self.lines.len() {
return;
}
// Get the current line
let line = self.lines[row].clone();
// Clear cutbuffer and add current line
self.cutbuffer.clear();
self.cutbuffer.push(line);
}
/// Set the mark at the current cursor position
pub fn set_mark(&mut self) {
self.mark = Some(self.cursor);
}
/// Get the mark position
pub fn mark(&self) -> Option<&Cursor> {
self.mark.as_ref()
}
/// Clear the mark
pub fn clear_mark(&mut self) {
self.mark = None;
}
/// Cut text from mark to cursor
pub fn cut_marked_text(&mut self) {
// Check if mark is set
let mark = match self.mark {
Some(m) => m,
None => return,
};
let cursor = self.cursor;
// Determine the start and end positions (mark could be before or after cursor)
let (start, end) = if mark.row < cursor.row || (mark.row == cursor.row && mark.col < cursor.col) {
(mark, cursor)
} else {
(cursor, mark)
};
// Clear the cutbuffer
self.cutbuffer.clear();
if start.row == end.row {
// Single line selection
if start.row >= self.lines.len() {
self.clear_mark();
return;
}
let line = &self.lines[start.row];
let start_col = start.col.min(line.len());
let end_col = end.col.min(line.len());
// Extract the selected text
let selected = line[start_col..end_col].to_string();
self.cutbuffer.push(selected);
// Remove the selected text
self.lines[start.row] = format!("{}{}", &line[..start_col], &line[end_col..]);
// Move cursor to start position
self.cursor.row = start.row;
self.cursor.col = start_col;
} else {
// Multi-line selection
if start.row >= self.lines.len() || end.row >= self.lines.len() {
self.clear_mark();
return;
}
// First line: from start.col to end of line
let first_line = &self.lines[start.row];
let start_col = start.col.min(first_line.len());
let first_part = first_line[start_col..].to_string();
self.cutbuffer.push(first_part);
// Middle lines: entire lines
for row in (start.row + 1)..end.row {
if row < self.lines.len() {
self.cutbuffer.push(self.lines[row].clone());
}
}
// Last line: from beginning to end.col
let last_line = &self.lines[end.row];
let end_col = end.col.min(last_line.len());
let last_part = last_line[..end_col].to_string();
self.cutbuffer.push(last_part);
// Now remove the selected text
// Keep the part before selection on first line and part after selection on last line
let before = self.lines[start.row][..start_col].to_string();
let after = self.lines[end.row][end_col..].to_string();
let combined = format!("{}{}", before, after);
// Remove all lines from start.row to end.row
for _ in start.row..=end.row {
if start.row < self.lines.len() {
self.lines.remove(start.row);
}
}
// Insert the combined line
self.lines.insert(start.row, combined);
// Move cursor to start position
self.cursor.row = start.row;
self.cursor.col = start_col;
}
self.cursor.desired_col = self.cursor.col;
self.update_render_col();
self.modified = true;
// Clear the mark after cutting
self.clear_mark();
}
/// Insert a character at the current cursor position
pub fn insert_char(&mut self, c: char) {
let row = self.cursor.row;
let col = self.cursor.col;
// Ensure the row exists
if row >= self.lines.len() {
return;
}
// Push edit to history before modification
self.edit_history.push(Edit::InsertChar { row, col, ch: c });
// Insert the character at the cursor position
let line = &mut self.lines[row];
if col <= line.len() {
line.insert(col, c);
self.cursor.col += 1;
self.cursor.desired_col = self.cursor.col;
self.update_render_col();
self.modified = true;
}
}
/// Delete the character at the current cursor position (Delete key)
pub fn delete_char(&mut self) {
let row = self.cursor.row;
let col = self.cursor.col;
// Ensure the row exists
if row >= self.lines.len() {
return;
}
let line = &self.lines[row];
// If at the end of the line, join with the next line
if col >= line.len() {
if row + 1 < self.lines.len() {
// Push edit to history before modification (joining lines)
self.edit_history.push(Edit::JoinLines { row });
let next_line = self.lines.remove(row + 1);
self.lines[row].push_str(&next_line);
self.update_render_col();
self.modified = true;
}
} else {
// Get the character before deleting
let ch = self.lines[row].chars().nth(col).unwrap();
// Push edit to history before modification
self.edit_history.push(Edit::DeleteChar { row, col, ch });
// Delete the character at the cursor
self.lines[row].remove(col);
self.update_render_col();
self.modified = true;
}
}
/// Delete the character before the cursor (Backspace key)
pub fn delete_char_before(&mut self) {
let row = self.cursor.row;
let col = self.cursor.col;
if col > 0 {
// Get the character before deleting
let ch = self.lines[row].chars().nth(col - 1).unwrap();
// Push edit to history before modification
self.edit_history.push(Edit::DeleteChar { row, col: col - 1, ch });
// Delete character before cursor in the same line
self.cursor.col -= 1;
self.lines[row].remove(self.cursor.col);
self.cursor.desired_col = self.cursor.col;
self.update_render_col();
self.modified = true;
} else if row > 0 {
// At the beginning of a line, join with previous line
// Push edit to history before modification (joining lines)
self.edit_history.push(Edit::JoinLines { row: row - 1 });
let current_line = self.lines.remove(row);
self.cursor.row -= 1;
self.cursor.col = self.lines[self.cursor.row].len();
self.lines[self.cursor.row].push_str(¤t_line);
self.cursor.desired_col = self.cursor.col;
self.update_render_col();
self.modified = true;
}
}
/// Insert a newline at the current cursor position
/// If auto_indent is enabled, preserves the indentation of the current line
pub fn insert_newline(&mut self) {
self.insert_newline_with_config(false);
}
/// Insert a newline at the current cursor position with configuration
/// If auto_indent is enabled, preserves the indentation of the current line
pub fn insert_newline_with_config(&mut self, auto_indent: bool) {
let row = self.cursor.row;
let col = self.cursor.col;
// Ensure the row exists
if row >= self.lines.len() {
return;
}
// Push edit to history before modification
self.edit_history.push(Edit::SplitLine { row, col });
// Split the current line at the cursor position
let current_line = &self.lines[row];
let mut new_line = current_line[col..].to_string();
self.lines[row].truncate(col);
// If auto-indent is enabled, count leading whitespace and add it to the new line
if auto_indent {
let leading_whitespace = self.get_leading_whitespace(row);
new_line = format!("{}{}", leading_whitespace, new_line);
}
// Insert the new line after the current line
self.lines.insert(row + 1, new_line);
// Move cursor to the beginning of the new line
self.cursor.row += 1;
// If auto-indent is enabled, move cursor to after the indentation
if auto_indent {
let indent_len = self.get_leading_whitespace(self.cursor.row).len();
self.cursor.col = indent_len;
} else {
self.cursor.col = 0;
}
self.modified = true;
}
/// Get the leading whitespace (tabs and spaces) from a line
fn get_leading_whitespace(&self, row: usize) -> String {
if row >= self.lines.len() {
return String::new();
}
let line = &self.lines[row];
line.chars()
.take_while(|&c| c == ' ' || c == '\t')
.collect()
}
/// Move cursor up one line
pub fn move_cursor_up(&mut self) {
if self.cursor.row > 0 {
self.cursor.row -= 1;
self.adjust_cursor_col();
}
}
/// Move cursor down one line
pub fn move_cursor_down(&mut self) {
if self.cursor.row + 1 < self.lines.len() {
self.cursor.row += 1;
self.adjust_cursor_col();
}
}
/// Move cursor left one character
pub fn move_cursor_left(&mut self) {
if self.cursor.col > 0 {
self.cursor.col -= 1;
self.cursor.desired_col = self.cursor.col;
self.update_render_col();
} else if self.cursor.row > 0 {
// Move to end of previous line
self.cursor.row -= 1;
self.cursor.col = self.lines[self.cursor.row].len();
self.cursor.desired_col = self.cursor.col;
self.update_render_col();
}
}
/// Move cursor right one character
pub fn move_cursor_right(&mut self) {
if self.cursor.row < self.lines.len() {
let line_len = self.lines[self.cursor.row].len();
if self.cursor.col < line_len {
self.cursor.col += 1;
self.cursor.desired_col = self.cursor.col;
self.update_render_col();
} else if self.cursor.row + 1 < self.lines.len() {
// Move to beginning of next line
self.cursor.row += 1;
self.cursor.col = 0;
self.cursor.desired_col = 0;
self.update_render_col();
}
}
}
/// Move cursor to the beginning of the current line
pub fn move_to_line_start(&mut self) {
self.cursor.col = 0;
self.cursor.desired_col = 0;
self.update_render_col();
}
/// Move cursor to the end of the current line
pub fn move_to_line_end(&mut self) {
if self.cursor.row < self.lines.len() {
self.cursor.col = self.lines[self.cursor.row].len();
self.cursor.desired_col = self.cursor.col;
self.update_render_col();
}
}
/// Move cursor to a specific line (1-indexed for user interface)
pub fn move_to_line(&mut self, line_number: usize) {
if line_number > 0 && line_number <= self.lines.len() {
self.cursor.row = line_number - 1;
self.cursor.col = 0;
self.cursor.desired_col = 0;
self.update_render_col();
}
}
/// Adjust cursor column after vertical movement, respecting desired_col
fn adjust_cursor_col(&mut self) {
if self.cursor.row < self.lines.len() {
let line_len = self.lines[self.cursor.row].len();
self.cursor.col = self.cursor.desired_col.min(line_len);
self.update_render_col();
}
}
/// Update render_col based on current col and tab handling
fn update_render_col(&mut self) {
if self.cursor.row >= self.lines.len() {
self.cursor.render_col = 0;
return;
}
let line = &self.lines[self.cursor.row];
let mut render_col = 0;
for (i, ch) in line.chars().enumerate() {
if i >= self.cursor.col {
break;
}
if ch == '\t' {
// Tab stops at multiples of tab_size
render_col += self.tab_size - (render_col % self.tab_size);
} else {
render_col += 1;
}
}
self.cursor.render_col = render_col;
}
/// Save the buffer to its current filename
///
/// Returns an error if no filename is set
pub fn save(&mut self) -> Result<()> {
if let Some(ref filename) = self.filename {
FileHandler::write_file(filename, &self.lines)?;
self.modified = false;
Ok(())
} else {
Err(crate::error::EditorError::BufferError(
"No filename set for buffer".to_string()
))
}
}
/// Save the buffer to a new filename
///
/// Updates the buffer's filename to the new path
pub fn save_as(&mut self, path: &Path) -> Result<()> {
FileHandler::write_file(path, &self.lines)?;
self.filename = Some(path.to_path_buf());
self.modified = false;
Ok(())
}
/// Insert the contents of a file at the current cursor position
///
/// This implements the Ctrl+R functionality
pub fn insert_file(&mut self, path: &Path) -> Result<()> {
let file_lines = FileHandler::read_file(path)?;
if file_lines.is_empty() {
return Ok(());
}
let row = self.cursor.row;
let col = self.cursor.col;
// Ensure the row exists
if row >= self.lines.len() {
return Ok(());
}
// Split the current line at cursor position
let current_line = &self.lines[row];
let before = current_line[..col].to_string();
let after = current_line[col..].to_string();
// First line: append to the part before cursor
let mut first_line = before;
first_line.push_str(&file_lines[0]);
if file_lines.len() == 1 {
// Single line file: insert on current line
first_line.push_str(&after);
self.lines[row] = first_line;
self.cursor.col = col + file_lines[0].len();
} else {
// Multi-line file
self.lines[row] = first_line;
// Insert middle lines
for (i, line) in file_lines.iter().enumerate().skip(1).take(file_lines.len() - 2) {
self.lines.insert(row + i, line.clone());
}
// Last line: prepend to the part after cursor
let mut last_line = file_lines[file_lines.len() - 1].clone();
last_line.push_str(&after);
self.lines.insert(row + file_lines.len() - 1, last_line);
// Move cursor to end of inserted content
self.cursor.row = row + file_lines.len() - 1;
self.cursor.col = file_lines[file_lines.len() - 1].len();
}
self.modified = true;
self.update_render_col();
Ok(())
}
/// Replace text at a specific position
///
/// Used for search and replace functionality
pub fn replace_at(&mut self, row: usize, col: usize, query: &str, replacement: &str) {
// Ensure the row exists
if row >= self.lines.len() {
return;
}
let line = &self.lines[row];
// Check if the query matches at the specified position
if col + query.len() <= line.len() {
let text_at_pos = &line[col..col + query.len()];
// Case-insensitive comparison (matching nano's default behavior)
if text_at_pos.to_lowercase() == query.to_lowercase() {
// Replace the text
let before = &line[..col];
let after = &line[col + query.len()..];
self.lines[row] = format!("{}{}{}", before, replacement, after);
self.modified = true;
}
}
}
/// Perform an undo operation
/// Returns true if undo was successful, false if nothing to undo
pub fn undo(&mut self) -> bool {
if let Some(edit) = self.edit_history.undo() {
// Apply the inverse operation
match edit {
Edit::InsertChar { row, col, ch: _ } => {
// Undo insert: delete the character
if row < self.lines.len() && col < self.lines[row].len() {
self.lines[row].remove(col);
self.cursor.row = row;
self.cursor.col = col;
}
}
Edit::DeleteChar { row, col, ch } => {
// Undo delete: insert the character back
if row < self.lines.len() && col <= self.lines[row].len() {
self.lines[row].insert(col, ch);
self.cursor.row = row;
self.cursor.col = col;
}
}
Edit::InsertLine { row, content: _ } => {
// Undo insert line: delete the line
if row < self.lines.len() {
self.lines.remove(row);
if self.lines.is_empty() {
self.lines.push(String::new());
}
self.cursor.row = row.min(self.lines.len() - 1);
self.cursor.col = 0;
}
}
Edit::DeleteLine { row, content } => {
// Undo delete line: insert the line back
if row <= self.lines.len() {
self.lines.insert(row, content);
self.cursor.row = row;
self.cursor.col = 0;
}
}
Edit::SplitLine { row, col } => {
// Undo split: join the lines back
if row < self.lines.len() && row + 1 < self.lines.len() {
let next_line = self.lines.remove(row + 1);
self.lines[row].push_str(&next_line);
self.cursor.row = row;
self.cursor.col = col;
}
}
Edit::JoinLines { row } => {
// Undo join: split the lines
if row < self.lines.len() {
// Find where the join happened (at the end of the first line)
let split_pos = self.lines[row].len();
let new_line = self.lines[row][split_pos..].to_string();
self.lines[row].truncate(split_pos);
self.lines.insert(row + 1, new_line);
self.cursor.row = row;
self.cursor.col = split_pos;
}
}
}
self.cursor.desired_col = self.cursor.col;
self.update_render_col();
self.modified = true;
true
} else {
false
}
}
/// Perform a redo operation
/// Returns true if redo was successful, false if nothing to redo
pub fn redo(&mut self) -> bool {
if let Some(edit) = self.edit_history.redo() {
// Reapply the operation
match edit {
Edit::InsertChar { row, col, ch } => {
// Redo insert: insert the character
if row < self.lines.len() && col <= self.lines[row].len() {
self.lines[row].insert(col, ch);
self.cursor.row = row;
self.cursor.col = col + 1;
}
}
Edit::DeleteChar { row, col, ch: _ } => {
// Redo delete: delete the character
if row < self.lines.len() && col < self.lines[row].len() {
self.lines[row].remove(col);
self.cursor.row = row;
self.cursor.col = col;
}
}
Edit::InsertLine { row, content } => {
// Redo insert line: insert the line
if row <= self.lines.len() {
self.lines.insert(row, content);
self.cursor.row = row;
self.cursor.col = 0;
}
}
Edit::DeleteLine { row, content: _ } => {
// Redo delete line: delete the line
if row < self.lines.len() {
self.lines.remove(row);
if self.lines.is_empty() {
self.lines.push(String::new());
}
self.cursor.row = row.min(self.lines.len() - 1);
self.cursor.col = 0;
}
}
Edit::SplitLine { row, col } => {
// Redo split: split the line
if row < self.lines.len() && col <= self.lines[row].len() {
let new_line = self.lines[row][col..].to_string();
self.lines[row].truncate(col);
self.lines.insert(row + 1, new_line);
self.cursor.row = row + 1;
self.cursor.col = 0;
}
}
Edit::JoinLines { row } => {
// Redo join: join the lines
if row < self.lines.len() && row + 1 < self.lines.len() {
let next_line = self.lines.remove(row + 1);
self.lines[row].push_str(&next_line);
self.cursor.row = row;
self.cursor.col = self.lines[row].len();
}
}
}
self.cursor.desired_col = self.cursor.col;
self.update_render_col();
self.modified = true;
true
} else {
false
}
}
/// Indent the current line
/// Adds a tab character or spaces (based on use_spaces) at the beginning of the line
pub fn indent_line(&mut self, use_spaces: bool, tab_size: usize) {
let row = self.cursor.row;
// Ensure the row exists
if row >= self.lines.len() {
return;
}
// Determine what to insert
let indent_str = if use_spaces {
" ".repeat(tab_size)
} else {
"\t".to_string()
};
// Insert at the beginning of the line
self.lines[row].insert_str(0, &indent_str);
// Update cursor position - move it forward by the indent amount
self.cursor.col += indent_str.len();
self.cursor.desired_col = self.cursor.col;
self.update_render_col();
self.modified = true;
}
/// Unindent the current line
/// Removes one tab or tab_size spaces from the beginning of the line if present
pub fn unindent_line(&mut self, tab_size: usize) {
let row = self.cursor.row;
// Ensure the row exists
if row >= self.lines.len() {
return;
}
let line = &self.lines[row];
// Check if line starts with a tab
if line.starts_with('\t') {
// Remove the tab
self.lines[row].remove(0);
// Update cursor position - move it back by 1 if it was after the tab
if self.cursor.col > 0 {
self.cursor.col -= 1;
}
self.cursor.desired_col = self.cursor.col;
self.update_render_col();
self.modified = true;
} else {
// Check if line starts with spaces
let spaces_to_remove = line.chars()
.take(tab_size)
.take_while(|&c| c == ' ')
.count();
if spaces_to_remove > 0 {
// Remove the spaces
self.lines[row].drain(0..spaces_to_remove);
// Update cursor position - move it back by the number of spaces removed
if self.cursor.col >= spaces_to_remove {
self.cursor.col -= spaces_to_remove;
} else {
self.cursor.col = 0;
}
self.cursor.desired_col = self.cursor.col;
self.update_render_col();
self.modified = true;
}
}
}
/// Justify the current paragraph to fit within the specified line width
/// A paragraph is defined as consecutive non-empty lines separated by blank lines
pub fn justify_paragraph(&mut self, line_width: usize) {
let row = self.cursor.row;
// Ensure the row exists
if row >= self.lines.len() {
return;
}
// Find the start of the paragraph (first non-empty line before or at cursor)
let mut para_start = row;
while para_start > 0 {
let prev_line = self.lines[para_start - 1].trim();
if prev_line.is_empty() {
break;
}
para_start -= 1;
}
// Find the end of the paragraph (last non-empty line after or at cursor)
let mut para_end = row;
while para_end + 1 < self.lines.len() {
let next_line = self.lines[para_end + 1].trim();
if next_line.is_empty() {
break;
}
para_end += 1;
}
// If cursor is on a blank line, do nothing
if self.lines[row].trim().is_empty() {
return;
}
// Collect all words from the paragraph
let mut words = Vec::new();
for i in para_start..=para_end {
let line = &self.lines[i];
// Split by whitespace and collect non-empty words
for word in line.split_whitespace() {
words.push(word.to_string());
}
}
// If no words, nothing to justify
if words.is_empty() {
return;
}
// Reflow words to fit within line_width
let mut new_lines = Vec::new();
let mut current_line = String::new();
for word in words {
// Check if adding this word would exceed line width
let test_line = if current_line.is_empty() {
word.clone()
} else {
format!("{} {}", current_line, word)
};
if test_line.len() <= line_width {
// Word fits on current line
current_line = test_line;
} else {
// Word doesn't fit, start a new line
if !current_line.is_empty() {
new_lines.push(current_line);
}
current_line = word;
}
}
// Add the last line if not empty
if !current_line.is_empty() {
new_lines.push(current_line);
}
// If no new lines were created, nothing to do
if new_lines.is_empty() {
return;
}
// Calculate cursor position relative to paragraph start
let cursor_offset_in_para = row - para_start;
// Remove old paragraph lines
for _ in para_start..=para_end {
if para_start < self.lines.len() {
self.lines.remove(para_start);
}
}
// Insert new justified lines
for (i, line) in new_lines.iter().enumerate() {
self.lines.insert(para_start + i, line.clone());
}
// Adjust cursor position
// Try to keep cursor in roughly the same position relative to the paragraph
let new_cursor_row = (para_start + cursor_offset_in_para).min(para_start + new_lines.len() - 1);
self.cursor.row = new_cursor_row;
// Move cursor to end of line
self.cursor.col = self.lines[new_cursor_row].len();
self.cursor.desired_col = self.cursor.col;
self.update_render_col();
self.modified = true;
}
}
impl Default for Buffer {
fn default() -> Self {
Self::new()
}
}