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
use crate::buffer::Buffer;
use crate::error::Result;
use crate::terminal::Terminal;
use crate::syntax::{SyntaxHighlighter, HighlightColor};
use termion::color;

/// Help text showing all keybindings in two-column format
const HELP_TEXT: &str = r#"
                    NanoRust Help Text

 NanoRust is a terminal-based text editor written in Rust, inspired by
 GNU nano. There are four main sections of the editor:
 The top line shows the program version, the current filename being edited,
 and whether or not the file has been modified. Next is the main editor
 window showing the file being edited. The status line is the third line
 from the bottom and shows important messages. The bottom two lines show
 the most commonly used shortcuts in the editor.

 Shortcuts are shown as follows: Control-key sequences are notated with a
 caret (^) symbol. Escape-key sequences are notated with the Meta (M-)
 symbol. The following keystrokes are available in the main editor window.
 Alternative keys are shown in parentheses:

 ^G  (F1)     Display this help text
 ^X  (F2)     Close the current buffer / Exit from editor
 ^O  (F3)     Write the current buffer to disk
 ^R  (Ins)    Insert another file into current buffer
 ^W  (F6)     Search forward for a string
 ^\  (M-R)    Search and replace a string
 ^K  (F9)     Cut current line into cutbuffer
 ^U  (F10)    Paste cutbuffer contents at cursor
 ^J           Justify the current paragraph
 ^T           Invoke the spell checker (if available)

 ^C           Display cursor position
 ^_  (M-G)    Go to line and column number
 ^^  (M-A)    Mark text starting from cursor position
 M-6  (M-^)   Copy current line into cutbuffer
 M-U          Undo the last operation
 M-E          Redo the last undone operation
 M-}          Indent the current line
 M-{          Unindent the current line

 ^A  (Home)   Move to beginning of current line
 ^E  (End)    Move to end of current line
 ^Y  (PgUp)   Move to previous screen
 ^V  (PgDn)   Move to next screen
 M-Y          Toggle syntax highlighting on/off
 ^Z           Suspend the editor (return with fg)

                    [ Press any key to continue ]
"#;

/// Status bar information
pub struct StatusBar {
    pub filename: String,
    pub line: usize,
    pub col: usize,
    pub modified: bool,
    pub total_lines: usize,
}

/// Display renderer for the editor
pub struct Display {
    /// Viewport row offset for scrolling
    row_offset: usize,
    /// Viewport column offset for horizontal scrolling
    col_offset: usize,
    /// Temporary message to display in status bar
    message: Option<String>,
    /// Whether to show line numbers
    show_line_numbers: bool,
    /// Tab size for rendering
    tab_size: usize,
    /// Syntax highlighter
    highlighter: Option<SyntaxHighlighter>,
    /// Whether syntax highlighting is enabled
    syntax_highlighting_enabled: bool,
}

impl Display {
    /// Create a new Display instance
    pub fn new() -> Self {
        Self {
            row_offset: 0,
            col_offset: 0,
            message: None,
            show_line_numbers: false,
            tab_size: 4,
            highlighter: None,
            syntax_highlighting_enabled: true,
        }
    }
    
    /// Update the syntax highlighter based on the buffer filename
    pub fn update_highlighter(&mut self, buffer: &Buffer) {
        if let Some(path) = buffer.filename() {
            if let Some(filename) = path.file_name().and_then(|n| n.to_str()) {
                self.highlighter = SyntaxHighlighter::from_filename(filename);
            }
        }
    }
    
    /// Toggle syntax highlighting on/off
    pub fn toggle_syntax_highlighting(&mut self) {
        self.syntax_highlighting_enabled = !self.syntax_highlighting_enabled;
    }
    
    /// Check if syntax highlighting is enabled
    pub fn is_syntax_highlighting_enabled(&self) -> bool {
        self.syntax_highlighting_enabled
    }

    /// Set whether to show line numbers
    pub fn set_show_line_numbers(&mut self, show: bool) {
        self.show_line_numbers = show;
    }

    /// Set tab size for rendering
    pub fn set_tab_size(&mut self, size: usize) {
        self.tab_size = size;
    }

    /// Get the number of visible rows accounting for UI elements
    /// 
    /// Subtracts space for title bar (1 row), status bar (1 row), and help bar (2 rows)
    fn visible_rows(&self, terminal: &Terminal) -> usize {
        let size = terminal.get_size();
        // Reserve 4 rows: 1 for title bar, 1 for status bar, 2 for help bar
        (size.rows as usize).saturating_sub(4)
    }

    /// Render the title bar at the top
    pub fn render_title_bar(&self, terminal: &mut Terminal, buffer: &Buffer) -> Result<()> {
        let size = terminal.get_size();
        
        // Position at top of screen
        terminal.move_cursor(1, 1)?;
        
        // Use inverted colors
        write!(terminal, "{}{}", color::Bg(color::White), color::Fg(color::Black))?;
        
        // Editor name on the left
        let editor_name = " NanoRust 0.1.0";
        
        // Filename or "New Buffer"
        let filename = if let Some(path) = buffer.filename() {
            path.to_string_lossy().to_string()
        } else {
            "New Buffer".to_string()
        };
        
        // Modified indicator
        let modified_indicator = if buffer.is_modified() {
            " [Modified]"
        } else {
            ""
        };
        
        // Build centered filename text
        let file_text = format!("{}{}", filename, modified_indicator);
        
        // Calculate available space for centering (minus editor name)
        let available_width = size.cols as usize - editor_name.len();
        
        // Truncate filename if too long
        let file_text = if file_text.len() > available_width {
            format!("{}...", &file_text[..available_width.saturating_sub(3)])
        } else {
            file_text
        };
        
        // Calculate padding to center the filename in remaining space
        let total_padding = if file_text.len() < available_width {
            available_width - file_text.len()
        } else {
            0
        };
        let left_padding = total_padding / 2;
        let right_padding = total_padding - left_padding;
        
        // Write title bar: editor name on left, filename centered in remaining space
        write!(terminal, "{}", editor_name)?;
        write!(terminal, "{}", " ".repeat(left_padding))?;
        write!(terminal, "{}", file_text)?;
        write!(terminal, "{}", " ".repeat(right_padding))?;
        
        // Reset colors
        write!(terminal, "{}{}", color::Bg(color::Reset), color::Fg(color::Reset))?;
        
        Ok(())
    }

    /// Render the buffer content to the screen
    pub fn render(&mut self, terminal: &mut Terminal, buffer: &Buffer) -> Result<()> {
        let size = terminal.get_size();
        let visible_rows = self.visible_rows(terminal);
        
        // Calculate line number width if showing line numbers
        let line_num_width = if self.show_line_numbers {
            let max_line = buffer.len();
            format!("{}", max_line).len() + 1 // +1 for space after number
        } else {
            0
        };
        
        // Adjust available columns for content
        let content_cols = (size.cols as usize).saturating_sub(line_num_width);
        
        // Update viewport to keep cursor visible
        self.update_viewport(buffer, visible_rows, content_cols);
        
        // Hide cursor during rendering
        terminal.hide_cursor()?;
        
        // Render each visible line
        for screen_row in 0..visible_rows {
            let buffer_row = screen_row + self.row_offset;
            
            // Position cursor at the start of this screen row (accounting for title bar)
            // Title bar is at row 1, content starts at row 2
            terminal.move_cursor((screen_row + 1 + 1) as u16, 1)?;
            
            // Render line number if enabled
            if self.show_line_numbers {
                if buffer_row < buffer.len() {
                    write!(terminal, "{:>width$} ", buffer_row + 1, width = line_num_width - 1)?;
                } else {
                    write!(terminal, "{:>width$} ", "", width = line_num_width - 1)?;
                }
            }
            
            if buffer_row < buffer.len() {
                if let Some(line) = buffer.get_line(buffer_row) {
                    self.render_line(terminal, line, content_cols)?;
                }
            } else {
                // Empty line indicator (tilde like in nano/vim)
                write!(terminal, "~")?;
            }
            
            // Clear to end of line
            write!(terminal, "{}", termion::clear::UntilNewline)?;
        }
        
        // Position cursor at buffer cursor position
        let cursor = buffer.cursor();
        let screen_row = cursor.row.saturating_sub(self.row_offset);
        let screen_col = cursor.render_col.saturating_sub(self.col_offset);
        
        // Move cursor to correct position (accounting for title bar and line numbers)
        // Title bar is at row 1, content starts at row 2, so add 2 to screen_row
        // For column: add line_num_width for line numbers, then +1 for 1-indexed terminal coords
        terminal.move_cursor(
            (screen_row + 1 + 1) as u16,
            (screen_col + line_num_width + 1) as u16
        )?;
        
        // Show cursor
        terminal.show_cursor()?;
        terminal.flush()?;
        
        Ok(())
    }

    /// Render a single line with proper positioning and tab handling
    fn render_line(&self, terminal: &mut Terminal, line: &str, max_cols: usize) -> Result<()> {
        // Get highlighted segments if syntax highlighting is enabled
        let segments = if self.syntax_highlighting_enabled {
            if let Some(ref highlighter) = self.highlighter {
                highlighter.highlight_line(line)
            } else {
                vec![(line.to_string(), HighlightColor::Reset)]
            }
        } else {
            vec![(line.to_string(), HighlightColor::Reset)]
        };
        
        let mut render_col = 0;
        
        for (text, highlight_color) in segments {
            // Apply color
            self.apply_color(terminal, highlight_color)?;
            
            for ch in text.chars() {
                // Skip characters before the horizontal offset
                if render_col < self.col_offset {
                    if ch == '\t' {
                        render_col += self.tab_size - (render_col % self.tab_size);
                    } else {
                        render_col += 1;
                    }
                    continue;
                }
                
                // Stop if we've filled the screen width
                if render_col >= self.col_offset + max_cols {
                    break;
                }
                
                // Render the character
                if ch == '\t' {
                    // Render tab as spaces
                    let spaces = self.tab_size - (render_col % self.tab_size);
                    for _ in 0..spaces {
                        if render_col >= self.col_offset + max_cols {
                            break;
                        }
                        write!(terminal, " ")?;
                        render_col += 1;
                    }
                } else {
                    write!(terminal, "{}", ch)?;
                    render_col += 1;
                }
            }
        }
        
        // Reset color at end of line
        write!(terminal, "{}", color::Fg(color::Reset))?;
        
        Ok(())
    }
    
    /// Apply the appropriate color for syntax highlighting
    fn apply_color(&self, terminal: &mut Terminal, highlight_color: HighlightColor) -> Result<()> {
        match highlight_color {
            HighlightColor::Cyan => write!(terminal, "{}", color::Fg(color::Cyan))?,
            HighlightColor::Yellow => write!(terminal, "{}", color::Fg(color::Yellow))?,
            HighlightColor::Green => write!(terminal, "{}", color::Fg(color::Green))?,
            HighlightColor::Magenta => write!(terminal, "{}", color::Fg(color::Magenta))?,
            HighlightColor::Reset => write!(terminal, "{}", color::Fg(color::Reset))?,
        }
        Ok(())
    }

    /// Update viewport offsets to keep cursor visible
    fn update_viewport(&mut self, buffer: &Buffer, visible_rows: usize, visible_cols: usize) {
        let cursor = buffer.cursor();
        
        // Vertical scrolling
        if cursor.row < self.row_offset {
            self.row_offset = cursor.row;
        }
        if cursor.row >= self.row_offset + visible_rows {
            self.row_offset = cursor.row - visible_rows + 1;
        }
        
        // Horizontal scrolling
        if cursor.render_col < self.col_offset {
            self.col_offset = cursor.render_col;
        }
        if cursor.render_col >= self.col_offset + visible_cols {
            self.col_offset = cursor.render_col - visible_cols + 1;
        }
    }

    /// Render the status bar with inverted colors
    pub fn render_status_bar(&self, terminal: &mut Terminal, status: &StatusBar) -> Result<()> {
        let size = terminal.get_size();
        let visible_rows = self.visible_rows(terminal);
        
        // Position at status bar row (after visible content)
        terminal.move_cursor((visible_rows + 2) as u16, 1)?;
        
        // Use inverted colors
        write!(terminal, "{}{}", color::Bg(color::White), color::Fg(color::Black))?;
        
        // Build status text
        let modified_indicator = if status.modified { " [Modified]" } else { "" };
        let left_status = format!(
            " {}{}",
            status.filename,
            modified_indicator
        );
        
        let right_status = format!(
            "Ln {}, Col {}  {}/{} ",
            status.line,
            status.col,
            status.line,
            status.total_lines
        );
        
        // Calculate padding
        let status_len = left_status.len() + right_status.len();
        let padding = if status_len < size.cols as usize {
            size.cols as usize - status_len
        } else {
            0
        };
        
        // Write status bar
        write!(terminal, "{}", left_status)?;
        write!(terminal, "{}", " ".repeat(padding))?;
        write!(terminal, "{}", right_status)?;
        
        // Reset colors
        write!(terminal, "{}{}", color::Bg(color::Reset), color::Fg(color::Reset))?;
        write!(terminal, "{}", termion::clear::UntilNewline)?;
        
        Ok(())
    }

    /// Render the help bar showing keyboard shortcuts (two rows)
    pub fn render_help_bar(&self, terminal: &mut Terminal) -> Result<()> {
        let visible_rows = self.visible_rows(terminal);
        let size = terminal.get_size();
        let width = size.cols as usize;
        
        // Calculate column width (6 columns per row)
        let col_width = width / 6;
        
        // First row shortcuts
        let row1_shortcuts = [
            "^G Get Help",
            "^O WriteOut",
            "^R Read File",
            "^Y Prev Pg",
            "^K Cut Text",
            "^C Cur Pos",
        ];
        
        // Second row shortcuts
        let row2_shortcuts = [
            "^X Exit",
            "^J Justify",
            "^W Where Is",
            "^V Next Pg",
            "^U Uncut Text",
            "^T To Spell",
        ];
        
        // Render first row
        terminal.move_cursor((visible_rows + 3) as u16, 1)?;
        for shortcut in row1_shortcuts.iter() {
            write!(terminal, "{:<width$}", shortcut, width = col_width)?;
        }
        write!(terminal, "{}", termion::clear::UntilNewline)?;
        
        // Render second row
        terminal.move_cursor((visible_rows + 4) as u16, 1)?;
        for shortcut in row2_shortcuts.iter() {
            write!(terminal, "{:<width$}", shortcut, width = col_width)?;
        }
        write!(terminal, "{}", termion::clear::UntilNewline)?;
        
        Ok(())
    }

    /// Show a temporary message in the status bar area
    pub fn show_message(&mut self, msg: String) {
        self.message = Some(msg);
    }

    /// Clear the temporary message
    pub fn clear_message(&mut self) {
        self.message = None;
    }

    /// Get the current message if any
    pub fn message(&self) -> Option<&str> {
        self.message.as_deref()
    }

    /// Render the complete screen including title bar, content, status bar, and help bar
    pub fn render_screen(&mut self, terminal: &mut Terminal, buffer: &Buffer) -> Result<()> {
        // Don't clear screen to avoid flickering - just render over existing content
        
        // Render title bar
        self.render_title_bar(terminal, buffer)?;
        
        // Render buffer content
        self.render(terminal, buffer)?;
        
        // Build status bar
        let cursor = buffer.cursor();
        let status = StatusBar {
            filename: if let Some(path) = buffer.filename() {
                path.file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or("unnamed")
                    .to_string()
            } else {
                "New Buffer".to_string()
            },
            line: cursor.row + 1, // Convert to 1-indexed
            col: cursor.col + 1,  // Convert to 1-indexed
            modified: buffer.is_modified(),
            total_lines: buffer.len(),
        };
        
        // Render status bar
        self.render_status_bar(terminal, &status)?;
        
        // Render help bar
        self.render_help_bar(terminal)?;
        
        // If there's a message, display it over the status bar
        if let Some(msg) = &self.message {
            let size = terminal.get_size();
            let visible_rows = self.visible_rows(terminal);
            terminal.move_cursor((visible_rows + 2) as u16, 1)?;
            write!(terminal, "{}{}", color::Bg(color::Yellow), color::Fg(color::Black))?;
            write!(terminal, " {}", msg)?;
            write!(terminal, "{}", " ".repeat(size.cols as usize - msg.len() - 1))?;
            write!(terminal, "{}{}", color::Bg(color::Reset), color::Fg(color::Reset))?;
        }
        
        // Move cursor back to the correct position in the content area
        let cursor = buffer.cursor();
        let screen_row = cursor.row.saturating_sub(self.row_offset);
        let screen_col = cursor.render_col.saturating_sub(self.col_offset);
        let line_num_width = if self.show_line_numbers {
            let max_line = buffer.len();
            format!("{}", max_line).len() + 1
        } else {
            0
        };
        
        terminal.move_cursor(
            (screen_row + 1 + 1) as u16,
            (screen_col + line_num_width + 1) as u16
        )?;
        terminal.show_cursor()?;
        
        terminal.flush()?;
        Ok(())
    }

    /// Render the help screen with all keybindings
    pub fn render_help_screen(&mut self, terminal: &mut Terminal) -> Result<()> {
        // Clear screen
        terminal.clear_screen()?;
        
        let size = terminal.get_size();
        let lines: Vec<&str> = HELP_TEXT.lines().collect();
        
        // Calculate starting row to center the help text
        let total_lines = lines.len();
        let start_row = if total_lines < size.rows as usize {
            (size.rows as usize - total_lines) / 2
        } else {
            0
        };
        
        // Render each line of help text
        for (i, line) in lines.iter().enumerate() {
            let row = start_row + i;
            if row >= size.rows as usize {
                break;
            }
            
            terminal.move_cursor(row as u16 + 1, 1)?;
            
            // Truncate line if it's too long
            let display_line = if line.len() > size.cols as usize {
                &line[..size.cols as usize]
            } else {
                line
            };
            
            write!(terminal, "{}", display_line)?;
            write!(terminal, "{}", termion::clear::UntilNewline)?;
        }
        
        terminal.flush()?;
        Ok(())
    }
}

impl Default for Display {
    fn default() -> Self {
        Self::new()
    }
}