nanorust 0.1.0

A terminal-based text editor written in Rust, inspired by GNU nano
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
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
use crate::buffer::Buffer;
use crate::config::Config;
use crate::display::Display;
use crate::error::Result;
use crate::search::SearchEngine;
use crate::terminal::Terminal;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

/// Main editor struct integrating all components
pub struct Editor {
    buffer: Buffer,
    terminal: Terminal,
    display: Display,
    config: Config,
    running: bool,
    #[allow(dead_code)]
    row_offset: usize,
    #[allow(dead_code)]
    col_offset: usize,
    #[allow(dead_code)]
    quit_requested: bool,
    #[allow(dead_code)]
    save_prompt_shown: bool,
    search_engine: Option<SearchEngine>,
    last_command: Option<crate::input::Key>,
    interrupt_flag: Arc<AtomicBool>,
    show_help: bool,
}

impl Editor {
    /// Create a new editor instance with default configuration
    pub fn new() -> Result<Self> {
        let config = Config::default();
        Self::with_config(config)
    }

    /// Create a new editor instance with provided configuration
    pub fn with_config(config: Config) -> Result<Self> {
        let terminal = Terminal::new()?;
        let mut display = Display::new();
        let mut buffer = Buffer::new();
        
        // Apply configuration to display
        display.set_show_line_numbers(config.show_line_numbers);
        display.set_tab_size(config.tab_size);
        
        // Apply configuration to buffer
        buffer.set_tab_size(config.tab_size);

        // Set up SIGINT handler
        let interrupt_flag = Arc::new(AtomicBool::new(false));
        let flag_clone = Arc::clone(&interrupt_flag);
        
        // Register signal handler for SIGINT (Ctrl+C)
        signal_hook::flag::register(signal_hook::consts::SIGINT, flag_clone)
            .map_err(|e| crate::error::EditorError::TerminalError(format!("Failed to register SIGINT handler: {}", e)))?;

        Ok(Editor {
            buffer,
            terminal,
            display,
            config,
            running: true,
            row_offset: 0,
            col_offset: 0,
            quit_requested: false,
            save_prompt_shown: false,
            search_engine: None,
            last_command: None,
            interrupt_flag,
            show_help: false,
        })
    }

    /// Open a file and load it into the buffer
    pub fn open_file(&mut self, path: &Path) -> Result<()> {
        self.buffer = Buffer::from_file(path)?;
        self.buffer.set_tab_size(self.config.tab_size);
        // Update syntax highlighter based on file extension
        self.display.update_highlighter(&self.buffer);
        Ok(())
    }

    /// Main event loop
    pub fn run(&mut self) -> Result<()> {
        while self.running {
            // Check for interrupt signal (SIGINT/Ctrl+C)
            if self.interrupt_flag.load(Ordering::Relaxed) {
                // Reset the flag
                self.interrupt_flag.store(false, Ordering::Relaxed);
                
                // Handle graceful shutdown
                if let Err(e) = self.handle_interrupt() {
                    self.display_error(&format!("Error during shutdown: {}", e));
                }
                
                // If still running after interrupt handling, continue
                if !self.running {
                    break;
                }
            }

            // Check for resize events before rendering
            if let Ok(Some(crate::input::Key::Resize)) = crate::input::poll_resize() {
                // Update terminal size
                if let Err(e) = self.terminal.update_size() {
                    self.display_error(&format!("Resize error: {}", e));
                }
                // Recalculate viewport offsets
                self.update_viewport();
            }

            // Refresh screen with current buffer state
            if let Err(e) = self.refresh_screen() {
                self.display_error(&format!("Display error: {}", e));
            }

            // Read and handle key input
            match crate::input::read_key() {
                Ok(key) => {
                    if let Err(e) = self.handle_key(key) {
                        self.display_error(&format!("Error: {}", e));
                    }
                }
                Err(e) => {
                    self.display_error(&format!("Input error: {}", e));
                }
            }

            // Update viewport offsets to keep cursor visible
            self.update_viewport();
        }

        Ok(())
    }

    /// Refresh the screen by rendering buffer, status bar, and help bar
    fn refresh_screen(&mut self) -> Result<()> {
        if self.show_help {
            // Render help screen instead of buffer content
            self.display.render_help_screen(&mut self.terminal)?;
        } else {
            // Use the display's render_screen method which handles everything
            self.display.render_screen(&mut self.terminal, &self.buffer)?;
        }
        Ok(())
    }

    /// Update viewport offsets to keep cursor visible on screen
    /// Note: Display handles viewport internally, but we keep this for future use
    fn update_viewport(&mut self) {
        // Display now handles viewport updates internally
        // This method is kept for potential future customization
    }

    /// Display an error message in the status bar
    fn display_error(&mut self, message: &str) {
        self.display.show_message(message.to_string());
    }

    /// Handle key input and dispatch to appropriate actions
    fn handle_key(&mut self, key: crate::input::Key) -> Result<()> {
        use crate::input::{Direction, Key};

        // If help screen is showing, any key press should close it
        if self.show_help {
            self.show_help = false;
            return Ok(());
        }

        // Store the current key for tracking consecutive operations
        let current_key = key.clone();

        match key {
            // Regular character input
            Key::Char(c) => {
                if self.config.view_only {
                    self.display.show_message("View mode - cannot edit".to_string());
                } else {
                    self.buffer.insert_char(c);
                }
            }

            // Backspace - delete character before cursor
            Key::Backspace => {
                if self.config.view_only {
                    self.display.show_message("View mode - cannot edit".to_string());
                } else {
                    self.buffer.delete_char_before();
                }
            }

            // Delete - delete character at cursor
            Key::Delete => {
                if self.config.view_only {
                    self.display.show_message("View mode - cannot edit".to_string());
                } else {
                    self.buffer.delete_char();
                }
            }

            // Enter - insert newline
            Key::Enter => {
                if self.config.view_only {
                    self.display.show_message("View mode - cannot edit".to_string());
                } else {
                    self.buffer.insert_newline_with_config(self.config.auto_indent);
                }
            }

            // Arrow keys - cursor movement
            Key::Arrow(Direction::Up) => {
                self.buffer.move_cursor_up();
            }
            Key::Arrow(Direction::Down) => {
                self.buffer.move_cursor_down();
            }
            Key::Arrow(Direction::Left) => {
                self.buffer.move_cursor_left();
            }
            Key::Arrow(Direction::Right) => {
                self.buffer.move_cursor_right();
            }

            // Home - move to beginning of line
            Key::Home => {
                self.buffer.move_to_line_start();
            }

            // End - move to end of line
            Key::End => {
                self.buffer.move_to_line_end();
            }

            // Page Up - scroll up one page
            Key::PageUp => {
                let size = self.terminal.get_size();
                let visible_rows = size.rows.saturating_sub(4) as usize;
                for _ in 0..visible_rows {
                    self.buffer.move_cursor_up();
                }
            }

            // Page Down - scroll down one page
            Key::PageDown => {
                let size = self.terminal.get_size();
                let visible_rows = size.rows.saturating_sub(4) as usize;
                for _ in 0..visible_rows {
                    self.buffer.move_cursor_down();
                }
            }

            // Tab - insert tab character
            Key::Tab => {
                if self.config.view_only {
                    self.display.show_message("View mode - cannot edit".to_string());
                } else {
                    self.buffer.insert_char('\t');
                }
            }

            // Ctrl+O - Save (Write Out)
            Key::Ctrl('o') => {
                if self.config.view_only {
                    self.display.show_message("View mode - cannot save".to_string());
                } else {
                    self.handle_save()?;
                }
            }

            // Ctrl+X - Exit
            Key::Ctrl('x') => {
                self.handle_quit()?;
            }

            // Ctrl+A - Move to beginning of line
            Key::Ctrl('a') => {
                self.buffer.move_to_line_start();
            }

            // Ctrl+E - Move to end of line
            Key::Ctrl('e') => {
                self.buffer.move_to_line_end();
            }

            // Ctrl+Y - Page up
            Key::Ctrl('y') => {
                let size = self.terminal.get_size();
                let visible_rows = size.rows.saturating_sub(4) as usize;
                for _ in 0..visible_rows {
                    self.buffer.move_cursor_up();
                }
            }

            // Ctrl+V - Page down
            Key::Ctrl('v') => {
                let size = self.terminal.get_size();
                let visible_rows = size.rows.saturating_sub(4) as usize;
                for _ in 0..visible_rows {
                    self.buffer.move_cursor_down();
                }
            }

            // Ctrl+_ - Go to line
            Key::Ctrl('_') => {
                self.handle_goto_line()?;
            }

            // Ctrl+R - Insert file
            Key::Ctrl('r') => {
                if self.config.view_only {
                    self.display.show_message("View mode - cannot edit".to_string());
                } else {
                    self.handle_insert_file()?;
                }
            }

            // Ctrl+W - Search (Where Is)
            Key::Ctrl('w') => {
                self.handle_search()?;
            }

            // Ctrl+\ - Replace
            Key::Ctrl('\\') => {
                if self.config.view_only {
                    self.display.show_message("View mode - cannot edit".to_string());
                } else {
                    self.handle_replace()?;
                }
            }

            // Ctrl+K - Cut line
            Key::Ctrl('k') => {
                if self.config.view_only {
                    self.display.show_message("View mode - cannot edit".to_string());
                } else {
                    self.handle_cut()?;
                }
            }

            // Ctrl+U - Paste
            Key::Ctrl('u') => {
                if self.config.view_only {
                    self.display.show_message("View mode - cannot edit".to_string());
                } else {
                    self.handle_paste()?;
                }
            }

            // Alt+6 - Copy line (allowed in view mode)
            Key::Alt('6') => {
                self.handle_copy()?;
            }

            // Ctrl+^ - Set mark for text selection (allowed in view mode)
            Key::Ctrl('^') => {
                self.handle_set_mark()?;
            }

            // Alt+U - Undo
            Key::Alt('u') => {
                if self.config.view_only {
                    self.display.show_message("View mode - cannot edit".to_string());
                } else {
                    self.handle_undo()?;
                }
            }

            // Alt+E - Redo
            Key::Alt('e') => {
                if self.config.view_only {
                    self.display.show_message("View mode - cannot edit".to_string());
                } else {
                    self.handle_redo()?;
                }
            }

            // Alt+} - Indent current line
            Key::Alt('}') => {
                if self.config.view_only {
                    self.display.show_message("View mode - cannot edit".to_string());
                } else {
                    self.handle_indent()?;
                }
            }

            // Alt+{ - Unindent current line
            Key::Alt('{') => {
                if self.config.view_only {
                    self.display.show_message("View mode - cannot edit".to_string());
                } else {
                    self.handle_unindent()?;
                }
            }

            // Alt+Y - Toggle syntax highlighting (allowed in view mode)
            Key::Alt('y') => {
                self.handle_toggle_syntax_highlighting()?;
            }

            // Ctrl+J - Justify paragraph
            Key::Ctrl('j') => {
                if self.config.view_only {
                    self.display.show_message("View mode - cannot edit".to_string());
                } else {
                    self.handle_justify()?;
                }
            }

            // Ctrl+Z - Suspend editor
            Key::Ctrl('z') => {
                self.handle_suspend()?;
            }

            // Ctrl+G - Show help screen
            Key::Ctrl('g') => {
                self.show_help = true;
            }

            // Resize event - update terminal size and redraw
            Key::Resize => {
                self.terminal.update_size()?;
                self.update_viewport();
                // Screen will be redrawn in the next iteration
            }

            // Other keys - ignore for now (will be implemented in later tasks)
            _ => {}
        }

        // Update last_command after handling the key
        self.last_command = Some(current_key);

        Ok(())
    }

    /// Handle save command (Ctrl+O)
    fn handle_save(&mut self) -> Result<()> {
        use crate::commands::CommandProcessor;

        // If buffer has no filename, prompt for one
        if self.buffer.filename().is_none() {
            match CommandProcessor::prompt_filename(
                &mut self.terminal,
                &mut self.display,
                self.buffer.filename(),
            )? {
                Some(path) => {
                    // Save to the new filename
                    if let Err(e) = self.buffer.save_as(&path) {
                        self.display.show_message(format!("Error saving file: {}", e));
                    } else {
                        let lines = self.buffer.len();
                        self.display.show_message(format!("Wrote {} lines", lines));
                    }
                }
                None => {
                    // User cancelled
                    self.display.show_message("Cancelled".to_string());
                }
            }
        } else {
            // Save to existing filename
            if let Err(e) = self.buffer.save() {
                self.display.show_message(format!("Error saving file: {}", e));
            } else {
                let lines = self.buffer.len();
                self.display.show_message(format!("Wrote {} lines", lines));
            }
        }

        Ok(())
    }

    /// Handle quit command (Ctrl+X)
    fn handle_quit(&mut self) -> Result<()> {
        use crate::input::Key;
        
        // If buffer is modified, prompt to save
        if self.buffer.is_modified() {
            // Show prompt
            self.terminal.move_cursor_to_status_line()?;
            self.terminal.clear_current_line()?;
            self.terminal.write_str("Save modified buffer? (Y/N/C) ")?;
            self.terminal.flush()?;

            // Read response
            match crate::input::read_key()? {
                Key::Char('y') | Key::Char('Y') => {
                    // Save and quit
                    self.handle_save()?;
                    // Only quit if save was successful (buffer is no longer modified)
                    if !self.buffer.is_modified() {
                        self.running = false;
                    }
                }
                Key::Char('n') | Key::Char('N') => {
                    // Quit without saving
                    self.running = false;
                }
                Key::Char('c') | Key::Char('C') | Key::Ctrl('c') | Key::Ctrl('g') => {
                    // Cancel quit
                    self.display.show_message("Cancelled".to_string());
                }
                _ => {
                    // Invalid input, cancel
                    self.display.show_message("Cancelled".to_string());
                }
            }
        } else {
            // No modifications, just quit
            self.running = false;
        }

        Ok(())
    }

    /// Handle go to line command (Ctrl+_)
    fn handle_goto_line(&mut self) -> Result<()> {
        match crate::commands::CommandProcessor::prompt_goto_line(&mut self.terminal, &mut self.display)? {
            Some(line_num) => {
                self.buffer.move_to_line(line_num);
                self.display.show_message(format!("Moved to line {}", line_num));
            }
            None => {
                // User cancelled or invalid input
            }
        }

        Ok(())
    }

    /// Handle insert file command (Ctrl+R)
    fn handle_insert_file(&mut self) -> Result<()> {
        // Prompt for filename
        self.terminal.move_cursor_to_status_line()?;
        self.terminal.clear_current_line()?;
        self.terminal.write_str("File to insert: ")?;
        self.terminal.flush()?;

        // Read the filename using the helper function
        match Self::read_input_for_prompt(&mut self.terminal) {
            Ok(filename) if !filename.is_empty() => {
                let path = std::path::PathBuf::from(filename);
                match self.buffer.insert_file(&path) {
                    Ok(_) => {
                        self.display.show_message(format!("Inserted file: {}", path.display()));
                    }
                    Err(e) => {
                        self.display.show_message(format!("Error inserting file: {}", e));
                    }
                }
            }
            Ok(_) => {
                // Empty filename, cancel
                self.display.show_message("Cancelled".to_string());
            }
            Err(_) => {
                // User cancelled
                self.display.show_message("Cancelled".to_string());
            }
        }

        Ok(())
    }

    /// Handle search command (Ctrl+W)
    fn handle_search(&mut self) -> Result<()> {
        // If we already have a search engine, use it to find next occurrence
        if let Some(ref mut search_engine) = self.search_engine {
            // Find next occurrence
            if let Some((row, col)) = search_engine.find_next(&self.buffer) {
                // Move cursor to the match position
                self.buffer.cursor_mut().row = row;
                self.buffer.cursor_mut().col = col;
                self.display.show_message(format!("Found: {}", search_engine.query()));
            } else {
                self.display.show_message("Not found".to_string());
            }
        } else {
            // Prompt for search string
            match crate::commands::CommandProcessor::prompt_search(&mut self.terminal, &mut self.display)? {
                Some(query) => {
                    // Create new search engine (case-insensitive by default, like nano)
                    let mut search_engine = SearchEngine::new(query, false);
                    
                    // Find first occurrence
                    if let Some((row, col)) = search_engine.find_next(&self.buffer) {
                        // Move cursor to the match position
                        self.buffer.cursor_mut().row = row;
                        self.buffer.cursor_mut().col = col;
                        self.display.show_message(format!("Found: {}", search_engine.query()));
                        
                        // Store the search engine for repeated searches
                        self.search_engine = Some(search_engine);
                    } else {
                        self.display.show_message("Not found".to_string());
                    }
                }
                None => {
                    // User cancelled
                }
            }
        }

        Ok(())
    }

    /// Handle replace command (Ctrl+\)
    fn handle_replace(&mut self) -> Result<()> {
        use crate::input::Key;

        // Prompt for search and replacement strings
        let (query, replacement) = match crate::commands::CommandProcessor::prompt_replace(
            &mut self.terminal,
            &mut self.display,
        )? {
            Some((q, r)) => (q, r),
            None => return Ok(()), // User cancelled
        };

        // Create search engine
        let mut search_engine = SearchEngine::new(query.clone(), false);
        let mut replacement_count = 0;
        let mut replace_all = false;

        // Find first match
        loop {
            // Refresh screen to show current position
            self.refresh_screen()?;

            // Find next occurrence
            let match_pos = if let Some(pos) = search_engine.find_next(&self.buffer) {
                pos
            } else {
                // No more matches
                break;
            };

            // Move cursor to the match
            self.buffer.cursor_mut().row = match_pos.0;
            self.buffer.cursor_mut().col = match_pos.1;

            // Refresh screen to show the match
            self.refresh_screen()?;

            if !replace_all {
                // Prompt for action
                self.terminal.move_cursor_to_status_line()?;
                self.terminal.clear_current_line()?;
                self.terminal.write_str("Replace this instance? (Y/N/A/^C) ")?;
                self.terminal.flush()?;

                // Read user response
                match crate::input::read_key()? {
                    Key::Char('y') | Key::Char('Y') => {
                        // Replace current and continue
                        self.buffer.replace_at(match_pos.0, match_pos.1, &query, &replacement);
                        replacement_count += 1;
                        
                        // Move cursor past the replacement to avoid finding it again
                        self.buffer.cursor_mut().col += replacement.len();
                    }
                    Key::Char('n') | Key::Char('N') => {
                        // Skip this match and continue
                        // Move cursor past the match to find next
                        self.buffer.cursor_mut().col += query.len();
                    }
                    Key::Char('a') | Key::Char('A') => {
                        // Replace all remaining matches
                        replace_all = true;
                        self.buffer.replace_at(match_pos.0, match_pos.1, &query, &replacement);
                        replacement_count += 1;
                        
                        // Move cursor past the replacement
                        self.buffer.cursor_mut().col += replacement.len();
                    }
                    Key::Ctrl('c') | Key::Ctrl('g') => {
                        // Cancel replace operation
                        self.display.show_message("Cancelled".to_string());
                        return Ok(());
                    }
                    _ => {
                        // Invalid input, skip
                        self.buffer.cursor_mut().col += query.len();
                    }
                }
            } else {
                // Replace all mode - replace without prompting
                self.buffer.replace_at(match_pos.0, match_pos.1, &query, &replacement);
                replacement_count += 1;
                
                // Move cursor past the replacement
                self.buffer.cursor_mut().col += replacement.len();
            }
        }

        // Show completion message
        if replacement_count > 0 {
            self.display.show_message(format!("Replaced {} occurrence(s)", replacement_count));
        } else {
            self.display.show_message("Not found".to_string());
        }

        Ok(())
    }

    /// Handle cut command (Ctrl+K)
    fn handle_cut(&mut self) -> Result<()> {
        use crate::input::Key;

        // Check if mark is set - if so, cut marked text
        if self.buffer.mark().is_some() {
            self.buffer.cut_marked_text();
        } else {
            // Check if the last command was also Ctrl+K
            let append = matches!(self.last_command, Some(Key::Ctrl('k')));

            // Cut the current line
            self.buffer.cut_line(append);
        }

        Ok(())
    }

    /// Handle paste command (Ctrl+U)
    fn handle_paste(&mut self) -> Result<()> {
        // Paste the cutbuffer at cursor position
        self.buffer.paste();

        Ok(())
    }

    /// Handle copy command (Alt+6)
    fn handle_copy(&mut self) -> Result<()> {
        // Copy the current line to cutbuffer
        self.buffer.copy_line();

        Ok(())
    }

    /// Handle set mark command (Ctrl+^)
    fn handle_set_mark(&mut self) -> Result<()> {
        // Set the mark at current cursor position
        self.buffer.set_mark();
        
        // Display message
        self.display.show_message("Mark Set".to_string());

        Ok(())
    }

    /// Handle undo command (Alt+U)
    fn handle_undo(&mut self) -> Result<()> {
        if self.buffer.undo() {
            self.display.show_message("Undo".to_string());
        } else {
            self.display.show_message("Nothing to undo".to_string());
        }

        Ok(())
    }

    /// Handle redo command (Alt+E)
    fn handle_redo(&mut self) -> Result<()> {
        if self.buffer.redo() {
            self.display.show_message("Redo".to_string());
        } else {
            self.display.show_message("Nothing to redo".to_string());
        }

        Ok(())
    }

    /// Handle indent command (Alt+})
    fn handle_indent(&mut self) -> Result<()> {
        self.buffer.indent_line(self.config.use_spaces, self.config.tab_size);
        Ok(())
    }

    /// Handle unindent command (Alt+{)
    fn handle_unindent(&mut self) -> Result<()> {
        self.buffer.unindent_line(self.config.tab_size);
        Ok(())
    }

    /// Handle toggle syntax highlighting command (Alt+Y)
    fn handle_toggle_syntax_highlighting(&mut self) -> Result<()> {
        self.display.toggle_syntax_highlighting();
        let status = if self.display.is_syntax_highlighting_enabled() {
            "Syntax highlighting enabled"
        } else {
            "Syntax highlighting disabled"
        };
        self.display.show_message(status.to_string());
        Ok(())
    }

    /// Handle justify paragraph command (Ctrl+J)
    fn handle_justify(&mut self) -> Result<()> {
        self.buffer.justify_paragraph(self.config.line_width);
        self.display.show_message("Justified paragraph".to_string());
        Ok(())
    }

    /// Handle suspend command (Ctrl+Z)
    fn handle_suspend(&mut self) -> Result<()> {
        // Suspend the terminal (this will restore terminal state and send SIGTSTP)
        self.terminal.suspend()?;
        
        // When we resume (after SIGCONT), we'll be here
        // Resume the terminal
        self.terminal.resume()?;
        
        // Show a message that we've resumed
        self.display.show_message("Resumed".to_string());
        
        Ok(())
    }

    /// Handle interrupt signal (SIGINT/Ctrl+C)
    fn handle_interrupt(&mut self) -> Result<()> {
        // If buffer is modified, prompt to save
        if self.buffer.is_modified() {
            // Use the same quit handling logic
            self.handle_quit()?;
        } else {
            // No modifications, just quit
            self.running = false;
        }
        
        Ok(())
    }

    /// Helper function to read input for prompts
    fn read_input_for_prompt(terminal: &mut Terminal) -> Result<String> {
        use crate::input::Key;
        
        let mut input = String::new();

        loop {
            let key = crate::input::read_key()?;

            match key {
                Key::Enter => break,
                Key::Char(ch) => {
                    input.push(ch);
                    terminal.write_str(&ch.to_string())?;
                    terminal.flush()?;
                }
                Key::Backspace => {
                    if input.pop().is_some() {
                        terminal.write_str("\x08 \x08")?;
                        terminal.flush()?;
                    }
                }
                Key::Ctrl('c') | Key::Ctrl('g') => {
                    return Err(crate::error::EditorError::ParseError("Input cancelled".to_string()));
                }
                _ => {}
            }
        }

        Ok(input)
    }
}