Documentation
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
use std::{collections::VecDeque, path::PathBuf};

use orfail::OrFail;
use tuinix::{KeyCode, TerminalPosition, TerminalSize};

use crate::{
    action::ExternalCommandAction,
    buffer::{TextBuffer, TextPosition},
    clipboard::Clipboard,
    keybindings::KeybindingsContext,
};

pub const MAX_HISTORY_SIZE: usize = 1000;

#[derive(Debug)]
pub struct State {
    pub path: PathBuf,
    pub cursor: TextPosition,
    pub viewport: TextPosition, // Top-left position of the visible text area
    pub recenter_viewport: bool,
    pub buffer: TextBuffer,
    pub message: Option<String>,
    pub context: KeybindingsContext,
    pub mark: Option<TextPosition>,
    pub clipboard: Clipboard,
    pub editing: bool,
    pub history: VecDeque<(TextPosition, TextBuffer)>,
    pub undo_index: usize,
}

impl State {
    pub fn new(path: PathBuf) -> orfail::Result<Self> {
        let mut buffer = TextBuffer::default();
        buffer.load_file(&path).or_fail()?;
        Ok(Self {
            path,
            cursor: TextPosition::default(),
            viewport: TextPosition::default(),
            recenter_viewport: false,
            buffer,
            message: None,
            context: KeybindingsContext::default(),
            mark: None,
            clipboard: Clipboard::default(),
            editing: false,
            history: VecDeque::new(),
            undo_index: 0,
        })
    }

    pub fn set_message(&mut self, message: impl Into<String>) {
        self.message = Some(message.into());
    }

    pub fn terminal_cursor_position(&self) -> TerminalPosition {
        let pos = self.cursor_position();
        let screen_row = pos.row.saturating_sub(self.viewport.row);
        let screen_col = pos.col.saturating_sub(self.viewport.col);
        TerminalPosition::row_col(screen_row, screen_col)
    }

    pub fn cursor_position(&self) -> TextPosition {
        self.buffer.adjust_to_char_boundary(self.cursor, true)
    }

    pub fn adjust_viewport(&mut self, text_area_size: TerminalSize) {
        let cursor_pos = self.cursor_position();
        let available_rows = text_area_size.rows;
        let available_cols = text_area_size.cols;

        if self.recenter_viewport {
            // Center the cursor in the viewport
            self.viewport.row = cursor_pos.row.saturating_sub(available_rows / 2);
            self.viewport.col = cursor_pos.col.saturating_sub(available_cols / 2);
            self.recenter_viewport = false;
            return;
        }

        // Existing viewport adjustment logic
        // Adjust vertical viewport
        if cursor_pos.row < self.viewport.row {
            // Cursor is above viewport, scroll up
            self.viewport.row = cursor_pos.row;
        } else if cursor_pos.row >= self.viewport.row + available_rows {
            // Cursor is below viewport, scroll down
            self.viewport.row = cursor_pos
                .row
                .saturating_sub(available_rows.saturating_sub(1));
        }

        // Adjust horizontal viewport
        if cursor_pos.col < self.viewport.col {
            // Cursor is left of viewport, scroll left
            self.viewport.col = cursor_pos.col;
        } else if cursor_pos.col >= self.viewport.col + available_cols {
            // Cursor is right of viewport, scroll right
            self.viewport.col = cursor_pos
                .col
                .saturating_sub(available_cols.saturating_sub(1));
        }
    }

    fn start_editing(&mut self) {
        if self.editing {
            return;
        }

        while self.history.len() >= MAX_HISTORY_SIZE {
            self.history.pop_front();
        }

        self.history.push_back((self.cursor, self.buffer.clone()));
        self.undo_index = self.history.len();

        self.editing = true;
    }

    fn finish_editing(&mut self) {
        self.editing = false;
    }

    pub fn handle_cursor_up(&mut self) {
        self.cursor.row = self.cursor.row.saturating_sub(1);
        self.finish_editing();
    }

    pub fn handle_cursor_down(&mut self) {
        self.cursor.row = self.cursor.row.saturating_add(1).min(self.buffer.rows());
        self.finish_editing();
    }

    pub fn handle_cursor_left(&mut self) {
        if self.cursor.col > 0 {
            self.cursor.col = self.cursor.col.saturating_sub(1);
            self.cursor = self.buffer.adjust_to_char_boundary(self.cursor, true);
        } else if self.cursor.row > 0 {
            // Move to end of previous line
            self.cursor.row = self.cursor.row.saturating_sub(1);
            self.cursor.col = self.buffer.cols(self.cursor.row);
        }
        self.finish_editing();
    }

    pub fn handle_cursor_right(&mut self) {
        let current_cols = self.buffer.cols(self.cursor.row);
        if self.cursor.col < current_cols {
            self.cursor.col = self.cursor.col.saturating_add(1);
            self.cursor = self.buffer.adjust_to_char_boundary(self.cursor, false);
        } else if self.cursor.row < self.buffer.rows() {
            // Move to beginning of next line
            self.cursor.row = self.cursor.row.saturating_add(1);
            self.cursor.col = 0;
        }
        self.finish_editing();
    }

    pub fn handle_cursor_line_start(&mut self) {
        self.cursor.col = 0;
        self.finish_editing();
    }

    pub fn handle_cursor_line_end(&mut self) {
        self.cursor.col = self.buffer.cols(self.cursor.row);
        self.finish_editing();
    }

    pub fn handle_cursor_buffer_start(&mut self) {
        self.cursor = TextPosition::default();
        self.finish_editing();
    }

    pub fn handle_cursor_buffer_end(&mut self) {
        self.cursor.row = self.buffer.rows();
        self.cursor.col = 0;
        self.finish_editing();
    }

    pub fn handle_char_delete_backward(&mut self) {
        self.start_editing();
        if let Some(new_pos) = self.buffer.delete_char_before(self.cursor) {
            self.cursor = new_pos;
        }
    }

    pub fn handle_char_delete_forward(&mut self) {
        self.start_editing();
        self.buffer.delete_char_at(self.cursor);
    }

    pub fn handle_buffer_save(&mut self) -> orfail::Result<()> {
        self.buffer.save_to_file(&self.path).or_fail()?;
        self.set_message(format!("Saved: {}", self.path.display()));
        Ok(())
    }

    pub fn handle_buffer_reload(&mut self) -> orfail::Result<()> {
        self.finish_editing();
        self.start_editing();

        // Reload the buffer from file
        self.buffer.load_file(&self.path).or_fail()?;

        // Try to preserve cursor position, but adjust if the file has changed
        let max_row = self.buffer.rows();
        self.cursor.row = self.cursor.row.min(max_row);

        if self.cursor.row < max_row {
            let max_col = self.buffer.cols(self.cursor.row);
            self.cursor.col = self.cursor.col.min(max_col);
        } else {
            self.cursor.col = 0;
        }

        // Adjust cursor to proper character boundary
        self.cursor = self.buffer.adjust_to_char_boundary(self.cursor, true);

        self.set_message(format!("Reloaded: {}", self.path.display()));
        self.finish_editing();
        Ok(())
    }

    pub fn handle_char_insert(&mut self, key: tuinix::KeyInput) {
        self.start_editing();
        // Only insert printable characters
        if let KeyCode::Char(ch) = key.code
            && !ch.is_control()
        {
            self.cursor = self.buffer.insert_char_at(self.cursor, ch);
        }
    }

    pub fn handle_newline_insert(&mut self) {
        self.finish_editing();
        self.start_editing();
        self.cursor = self.buffer.insert_newline_at(self.cursor);
        self.finish_editing();
    }

    pub fn handle_buffer_undo(&mut self) {
        if self.editing {
            self.finish_editing();
            self.start_editing();
            self.editing = false;
        }

        let Some(i) = self.undo_index.checked_sub(1) else {
            self.set_message("Nothing to undo");
            return;
        };

        let (cursor, buffer) = self.history[i].clone();
        self.cursor = cursor;
        self.buffer = buffer;
        self.undo_index = i;
        self.set_message(format!("Undo ({})", self.history.len() - i));
    }

    pub fn handle_mark_set(&mut self) {
        self.finish_editing();

        let cursor_pos = self.cursor_position();
        if self.mark == Some(cursor_pos) {
            // If mark is already at cursor position, deactivate it
            self.mark = None;
            self.set_message("Mark deactivated");
        } else {
            // Set mark at current cursor position
            self.mark = Some(cursor_pos);
            self.set_message("Mark set");
        }
    }

    pub fn handle_mark_copy(&mut self) -> orfail::Result<()> {
        self.finish_editing();

        if let Some(mark_pos) = self.mark.take() {
            let cursor_pos = self.cursor_position();
            let (start, end) = if mark_pos <= cursor_pos {
                (mark_pos, cursor_pos)
            } else {
                (cursor_pos, mark_pos)
            };

            if let Some(text) = self.get_text_in_range(start, end) {
                self.clipboard.write(&text).or_fail()?;
                self.set_message(format!("Copied {} characters", text.len()));
            } else {
                self.set_message("Nothing to copy");
            }
        } else {
            self.set_message("No mark set");
        }
        Ok(())
    }

    pub fn handle_mark_cut(&mut self) -> orfail::Result<()> {
        self.finish_editing();

        if let Some(mark_pos) = self.mark.take() {
            let cursor_pos = self.cursor_position();
            let (start, end) = if mark_pos <= cursor_pos {
                (mark_pos, cursor_pos)
            } else {
                (cursor_pos, mark_pos)
            };

            if let Some(text) = self.get_text_in_range(start, end) {
                // Delete the selected text
                self.delete_text_in_range(start, end);
                self.cursor = start;
                self.mark = None;

                self.clipboard.write(&text).or_fail()?;
                self.set_message(format!("Cut {} characters", text.len()));
            } else {
                self.set_message("Nothing to cut");
            }
        } else {
            self.set_message("No mark set");
        }
        Ok(())
    }

    // Helper method to get text in a range
    fn get_text_in_range(&self, start: TextPosition, end: TextPosition) -> Option<String> {
        if start == end {
            return None;
        }

        let mut result = String::new();

        if start.row == end.row {
            // Single line selection
            if let Some(line) = self.buffer.text.get(start.row) {
                for (col, ch) in line.char_cols() {
                    if col >= start.col && col < end.col {
                        result.push(ch);
                    }
                }
            }
        } else {
            // Multi-line selection
            for row in start.row..=end.row {
                if let Some(line) = self.buffer.text.get(row) {
                    if row == start.row {
                        // First line: from start.col to end of line
                        for (col, ch) in line.char_cols() {
                            if col >= start.col {
                                result.push(ch);
                            }
                        }
                        result.push('\n');
                    } else if row == end.row {
                        // Last line: from start of line to end.col
                        for (col, ch) in line.char_cols() {
                            if col < end.col {
                                result.push(ch);
                            }
                        }
                    } else {
                        // Middle lines: entire line
                        result.push_str(&line.to_string());
                        result.push('\n');
                    }
                }
            }
        }

        if result.is_empty() {
            None
        } else {
            Some(result)
        }
    }

    // Helper method to delete text in a range
    fn delete_text_in_range(&mut self, start: TextPosition, end: TextPosition) {
        if start == end {
            return;
        }

        // TODO: This should be implemented as a compound undo action
        // For now, we'll do a simple implementation

        if start.row == end.row {
            // Single line deletion
            if let Some(line) = self.buffer.text.get_mut(start.row) {
                let start_char_idx = line.char_index_at_col(start.col);
                let end_char_idx = line.char_index_at_col(end.col);

                for _ in start_char_idx..end_char_idx {
                    if start_char_idx < line.len() {
                        line.0.remove(start_char_idx);
                    }
                }
            }
        } else {
            // Multi-line deletion
            // Remove complete middle lines
            for _ in start.row + 1..end.row {
                if start.row + 1 < self.buffer.text.len() {
                    self.buffer.text.remove(start.row + 1);
                }
            }

            // Handle first and last lines
            if let Some(start_line) = self.buffer.text.get_mut(start.row) {
                let chars_to_keep: Vec<char> = start_line
                    .char_cols()
                    .filter(|(col, _)| *col < start.col)
                    .map(|(_, ch)| ch)
                    .collect();
                start_line.0 = chars_to_keep;
            }

            if start.row + 1 < self.buffer.text.len() {
                if let Some(end_line) = self.buffer.text.get(start.row + 1).cloned() {
                    let chars_to_keep: Vec<char> = end_line
                        .char_cols()
                        .filter(|(col, _)| *col >= end.col)
                        .map(|(_, ch)| ch)
                        .collect();

                    if let Some(start_line) = self.buffer.text.get_mut(start.row) {
                        start_line.0.extend(chars_to_keep);
                    }

                    self.buffer.text.remove(start.row + 1);
                }
            }
        }

        self.buffer.dirty = true;
    }

    pub fn handle_clipboard_paste(&mut self) -> orfail::Result<()> {
        self.finish_editing();

        let text = self.clipboard.read().or_fail()?;

        if text.is_empty() {
            self.set_message("Clipboard is empty");
            return Ok(());
        }

        // Split text into lines
        let lines: Vec<&str> = text.lines().collect();

        if lines.is_empty() {
            self.set_message("Nothing to paste");
            return Ok(());
        }
        self.start_editing();

        // Insert the text
        if lines.len() == 1 {
            // Single line paste
            let line = lines[0];
            for ch in line.chars() {
                self.cursor = self.buffer.insert_char_at(self.cursor, ch);
            }
            self.set_message(format!("Pasted {} characters", line.len()));
        } else {
            // Multi-line paste
            let mut total_chars = 0;

            // Insert first line
            for ch in lines[0].chars() {
                self.cursor = self.buffer.insert_char_at(self.cursor, ch);
                total_chars += 1;
            }

            // Insert newline and subsequent lines
            for line in &lines[1..] {
                self.cursor = self.buffer.insert_newline_at(self.cursor);
                total_chars += 1; // Count the newline

                for ch in line.chars() {
                    self.cursor = self.buffer.insert_char_at(self.cursor, ch);
                    total_chars += 1;
                }
            }

            self.set_message(format!(
                "Pasted {} characters across {} lines",
                total_chars,
                lines.len()
            ));
        }

        self.finish_editing();
        Ok(())
    }

    pub fn handle_external_command(
        &mut self,
        action: &ExternalCommandAction,
    ) -> orfail::Result<()> {
        self.finish_editing();

        let mut cmd = std::process::Command::new(&action.command);

        for arg in &action.args {
            cmd.arg(arg);
        }

        let stdin_input = if let Some(mark_pos) = self.mark {
            let cursor_pos = self.cursor_position();
            let (start, end) = if mark_pos <= cursor_pos {
                (mark_pos, cursor_pos)
            } else {
                (cursor_pos, mark_pos)
            };
            self.get_text_in_range(start, end)
        } else {
            None
        };
        cmd.stdin(std::process::Stdio::piped());
        cmd.stdout(std::process::Stdio::piped());
        cmd.stderr(std::process::Stdio::piped());

        let mut child = match cmd.spawn() {
            Err(e) => {
                self.set_message(format!("Failed to execute command: {}", e));
                return Ok(());
            }
            Ok(child) => child,
        };

        // Write to stdin if we have marked text
        if let Some(mut stdin) = child.stdin.take() {
            if let Some(text) = stdin_input {
                use std::io::Write;
                let _ = stdin.write_all(text.as_bytes());
            }
        }

        let output = match child.wait_with_output() {
            Err(e) => {
                self.set_message(format!("Failed to wait for command: {}", e));
                return Ok(());
            }
            Ok(output) => output,
        };

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            self.set_message(format!("Command failed: {}", stderr.trim()));
            return Ok(());
        }

        self.start_editing();

        let stdout = String::from_utf8_lossy(&output.stdout);

        if let Some(mark_pos) = self.mark.take() {
            // Replace marked region with output
            let cursor_pos = self.cursor_position();
            let (start, end) = if mark_pos <= cursor_pos {
                (mark_pos, cursor_pos)
            } else {
                (cursor_pos, mark_pos)
            };

            self.start_editing();

            // Delete the marked region
            self.delete_text_in_range(start, end);
            self.cursor = start;

            // Insert the command output
            let output_str = stdout.trim_end(); // Remove trailing whitespace/newlines
            let lines: Vec<&str> = output_str.lines().collect();

            if !lines.is_empty() {
                // Insert first line
                for ch in lines[0].chars() {
                    self.cursor = self.buffer.insert_char_at(self.cursor, ch);
                }

                // Insert subsequent lines with newlines
                for line in &lines[1..] {
                    self.cursor = self.buffer.insert_newline_at(self.cursor);
                    for ch in line.chars() {
                        self.cursor = self.buffer.insert_char_at(self.cursor, ch);
                    }
                }
            }

            self.finish_editing();
            self.set_message(format!(
                "Replaced region with command output ({} chars)",
                output_str.len()
            ));
        } else {
            // No marked region, insert output at cursor
            self.start_editing();

            let output_str = stdout.trim_end();
            let lines: Vec<&str> = output_str.lines().collect();

            if !lines.is_empty() {
                // Insert first line
                for ch in lines[0].chars() {
                    self.cursor = self.buffer.insert_char_at(self.cursor, ch);
                }

                // Insert subsequent lines with newlines
                for line in &lines[1..] {
                    self.cursor = self.buffer.insert_newline_at(self.cursor);
                    for ch in line.chars() {
                        self.cursor = self.buffer.insert_char_at(self.cursor, ch);
                    }
                }
            }

            self.finish_editing();
            self.set_message(format!(
                "Inserted command output ({} chars)",
                output_str.len()
            ));
        }
        self.finish_editing();

        Ok(())
    }

    pub fn handle_view_recenter(&mut self) {
        self.finish_editing();
        self.recenter_viewport = true;
        self.set_message("View recentered");
    }
}