revw 0.2.5

A vim-like TUI for managing notes and resources
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
use anyhow::Result;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use crate::app::{App, FileOperation, FormatMode};

pub fn handle_normal_mode(app: &mut App, key: KeyEvent) -> Result<bool> {
    // Handle file operation confirmation/prompt if active
    if let Some(ref op) = app.file_op_pending.clone() {
        return handle_file_operation(app, key, op);
    }

    // Handle substitute confirmation if active
    if !app.substitute_confirmations.is_empty() {
        match key.code {
            KeyCode::Char('y') | KeyCode::Char('n') | KeyCode::Char('a') | KeyCode::Char('q') => {
                if let KeyCode::Char(c) = key.code {
                    app.handle_substitute_confirmation(c);
                }
                return Ok(false);
            }
            KeyCode::Esc => {
                app.handle_substitute_confirmation('q');
                return Ok(false);
            }
            _ => return Ok(false),
        }
    }

    // Handle explorer navigation if explorer has focus
    if app.explorer_open && app.explorer_has_focus {
        return handle_explorer_navigation(app, key);
    }

    // Main normal mode keyboard handling
    match key.code {
        KeyCode::Char('u') => {
            if !app.showing_help && app.format_mode == FormatMode::Edit {
                app.undo();
            }
        }
        KeyCode::Char('v') => {
            // Enter Visual/Select mode in View mode
            if !app.showing_help && app.format_mode == FormatMode::View && !app.relf_entries.is_empty() {
                app.visual_mode = true;
                app.visual_start_index = app.selected_entry_index;
                app.visual_end_index = app.selected_entry_index;
                app.set_status("-- VISUAL --");
            }
        }
        KeyCode::Char('?') => {
            // Toggle help
            app.toggle_help();
        }
        KeyCode::Char('q') | KeyCode::Esc | KeyCode::Char('[') => {
            // Check for Ctrl+[ to exit Visual mode
            if key.code == KeyCode::Char('[') && !key.modifiers.contains(KeyModifiers::CONTROL) {
                // Not Ctrl+[, ignore
            } else {
                // Exit Visual mode if active, otherwise quit
                if app.visual_mode {
                    app.visual_mode = false;
                    app.set_status("");
                } else {
                    return Ok(true);
                }
            }
        }
        KeyCode::Char('w') => {
            // Vim-like: move to start of next word (Edit mode)
            if !app.showing_help && app.format_mode == FormatMode::Edit {
                app.move_to_next_word_start();
            }
        }
        KeyCode::Char('e') => {
            // Vim-like: move to end of next word (Edit mode)
            if !app.showing_help && app.format_mode == FormatMode::Edit {
                app.move_to_next_word_end();
            }
        }
        KeyCode::Char('b') => {
            // Vim-like: move to start of previous word (Edit mode)
            if !app.showing_help && app.format_mode == FormatMode::Edit {
                app.move_to_previous_word_start();
            }
        }
        KeyCode::Char('r') => {
            if !app.showing_help {
                // Clear filter when toggling modes
                if !app.filter_pattern.is_empty() {
                    app.filter_pattern.clear();
                }

                // Toggle between View and Edit only (not Help)
                app.format_mode = match app.format_mode {
                    FormatMode::View => FormatMode::Edit,
                    FormatMode::Edit => FormatMode::View,
                    FormatMode::Help => FormatMode::View, // If somehow in Help, go to View
                };
                let mode_name = match app.format_mode {
                    FormatMode::View => "View",
                    FormatMode::Edit => "Edit",
                    FormatMode::Help => "Help",
                };
                if app.format_mode == FormatMode::View {
                    app.hscroll = 0;
                }
                app.convert_json();
                app.set_status(&format!("{} mode", mode_name));
            }
        }
        KeyCode::Char('i') => {
            if !app.showing_help && app.format_mode == FormatMode::Edit {
                app.input_mode = crate::app::InputMode::Insert;
                app.ensure_cursor_visible();
                app.set_status("-- INSERT --");
            }
        }
        KeyCode::Char('x') => {
            if !app.showing_help && app.format_mode == FormatMode::Edit {
                app.delete_char();
                app.is_modified = true;
            }
        }
        KeyCode::Char('X') => {
            if !app.showing_help && app.format_mode == FormatMode::Edit {
                app.backspace();
                app.is_modified = true;
            }
        }
        KeyCode::Char(':') => {
            // Allow command mode even when showing help (for :h to toggle)
            app.input_mode = crate::app::InputMode::Command;
            app.command_buffer = String::new();
            app.command_history_index = None;
            app.set_status(":");
        }
        KeyCode::Up | KeyCode::Char('k') => {
            if app.showing_help {
                // Allow scrolling in help mode (takes priority)
                app.scroll_up();
            } else if app.format_mode == FormatMode::Edit {
                app.move_cursor_up();
            } else if !app.relf_entries.is_empty() {
                // Move selection up in card view
                if app.selected_entry_index > 0 {
                    app.selected_entry_index -= 1;
                    // Reset horizontal scroll when changing cards
                    app.hscroll = 0;
                    // In Visual mode, extend selection
                    if app.visual_mode {
                        app.visual_end_index = app.selected_entry_index;
                    }
                }
            } else {
                app.relf_jump_up();
            }
        }
        KeyCode::Down | KeyCode::Char('j') => {
            if app.showing_help {
                // Allow scrolling in help mode (takes priority)
                app.scroll_down();
            } else if app.format_mode == FormatMode::Edit {
                app.move_cursor_down();
            } else if !app.relf_entries.is_empty() {
                // Move selection down in card view
                if app.selected_entry_index + 1 < app.relf_entries.len() {
                    app.selected_entry_index += 1;
                    // Reset horizontal scroll when changing cards
                    app.hscroll = 0;
                    // In Visual mode, extend selection
                    if app.visual_mode {
                        app.visual_end_index = app.selected_entry_index;
                    }
                }
            } else {
                app.relf_jump_down();
            }
        }
        KeyCode::Left | KeyCode::Char('h') => {
            if !app.showing_help {
                if app.format_mode == FormatMode::Edit {
                    app.move_cursor_left();
                } else {
                    // Vertical scroll up in View mode (card context)
                    app.hscroll = app.hscroll.saturating_sub(1);
                }
            }
        }
        KeyCode::Right | KeyCode::Char('l') => {
            if !app.showing_help {
                if app.format_mode == FormatMode::Edit {
                    app.move_cursor_right();
                } else {
                    // Vertical scroll down in View mode (card context)
                    // Calculate max scroll based on context field length
                    if !app.relf_entries.is_empty() && app.selected_entry_index < app.relf_entries.len() {
                        let entry = &app.relf_entries[app.selected_entry_index];
                        if let Some(context) = &entry.context {
                            let lines: Vec<&str> = context.lines().collect();
                            // Estimate visible lines: total height divided by number of visible cards
                            // Subtract 2 for card borders (top and bottom)
                            let visible_lines = (app.visible_height as usize / app.max_visible_cards).saturating_sub(2);
                            let max_scroll = lines.len().saturating_sub(visible_lines);
                            if (app.hscroll as usize) < max_scroll {
                                app.hscroll += 1;
                            }
                        }
                    }
                }
            }
        }
        KeyCode::Char('0') => {
            if !app.showing_help && app.format_mode == FormatMode::Edit {
                app.content_cursor_col = 0;
                app.ensure_cursor_visible();
            }
        }
        KeyCode::Char('$') => {
            if !app.showing_help && app.format_mode == FormatMode::Edit {
                let lines = app.get_json_lines();
                if app.content_cursor_line < lines.len() {
                    app.content_cursor_col =
                        lines[app.content_cursor_line].chars().count();
                    app.ensure_cursor_visible();
                }
            }
        }
        KeyCode::PageUp => app.page_up(),
        KeyCode::PageDown => app.page_down(),
        KeyCode::Char('G') => {
            if app.showing_help {
                // Allow scrolling to bottom in help mode (takes priority)
                app.scroll_to_bottom();
            } else if app.format_mode == FormatMode::Edit {
                app.scroll_to_bottom();
                let lines = app.get_json_lines();
                if !lines.is_empty() {
                    app.content_cursor_line = lines.len() - 1;
                    app.content_cursor_col = 0;
                }
            } else if !app.relf_entries.is_empty() {
                // Jump to last card
                app.selected_entry_index = app.relf_entries.len() - 1;
            } else {
                app.scroll_to_bottom();
            }
        }
        KeyCode::Char('/') => {
            if !app.showing_help {
                app.start_search();
            }
        }
        KeyCode::Char('n') => {
            if !app.showing_help {
                app.next_match();
            }
        }
        KeyCode::Char('N') => {
            if !app.showing_help {
                app.prev_match();
            }
        }
        KeyCode::Enter => {
            // Open edit overlay for selected card
            if !app.showing_help && !app.relf_entries.is_empty() {
                app.start_editing_entry();
            }
        }
        KeyCode::Char(c)
            if c == 'g'
                || c == '-'
                || c == '+'
                || app.vim_buffer.starts_with('g') =>
        {
            // Allow gg in help mode for scrolling to top
            app.handle_vim_input(c);
        }
        _ => {
            // Reset dd count if any other key is pressed
            if app.dd_count > 0 {
                app.dd_count = 0;
                app.vim_buffer.clear();
            }
        }
    }

    Ok(false)
}

fn handle_file_operation(app: &mut App, key: KeyEvent, op: &FileOperation) -> Result<bool> {
    match op {
        FileOperation::Delete(_) => {
            // Waiting for yes/no confirmation
            match key.code {
                KeyCode::Esc => {
                    app.cancel_file_operation();
                    return Ok(false);
                }
                KeyCode::Enter => {
                    let input = app.file_op_prompt_buffer.trim().to_lowercase();
                    if input == "yes" {
                        app.handle_file_op_confirmation('y');
                    } else if input == "no" {
                        app.handle_file_op_confirmation('n');
                    } else {
                        app.set_status("Invalid input. Type 'yes' or 'no'");
                        app.file_op_prompt_buffer.clear();
                    }
                    return Ok(false);
                }
                KeyCode::Char(c) => {
                    app.file_op_prompt_buffer.push(c);
                    let path_display = if let FileOperation::Delete(path) = op {
                        let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("unknown");
                        let item_type = if path.is_dir() { "directory" } else { "file" };
                        format!("Delete {} '{}'? (yes/no) {}", item_type, name, app.file_op_prompt_buffer)
                    } else {
                        String::new()
                    };
                    app.set_status(&path_display);
                    return Ok(false);
                }
                KeyCode::Backspace => {
                    if !app.file_op_prompt_buffer.is_empty() {
                        app.file_op_prompt_buffer.pop();
                        let path_display = if let FileOperation::Delete(path) = op {
                            let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("unknown");
                            let item_type = if path.is_dir() { "directory" } else { "file" };
                            format!("Delete {} '{}'? (yes/no) {}", item_type, name, app.file_op_prompt_buffer)
                        } else {
                            String::new()
                        };
                        app.set_status(&path_display);
                    } else {
                        app.cancel_file_operation();
                    }
                    return Ok(false);
                }
                _ => return Ok(false),
            }
        }
        FileOperation::Create | FileOperation::CreateDir | FileOperation::Copy(_) | FileOperation::Rename(_) => {
            // Waiting for filename input
            match key.code {
                KeyCode::Esc => {
                    app.cancel_file_operation();
                    return Ok(false);
                }
                KeyCode::Enter => {
                    app.execute_file_operation();
                    return Ok(false);
                }
                KeyCode::Char(c) => {
                    app.file_op_prompt_buffer.push(c);
                    let prompt_msg = match op {
                        FileOperation::Create => "New file name (must end with .json):",
                        FileOperation::CreateDir => "New directory name:",
                        FileOperation::Copy(src) => {
                            let name = src.file_name().and_then(|n| n.to_str()).unwrap_or("unknown");
                            &format!("Copy '{}' to (must end with .json):", name)
                        }
                        FileOperation::Rename(path) => {
                            if path.is_dir() {
                                "Rename/Move directory to:"
                            } else {
                                "Rename/Move to (must end with .json):"
                            }
                        }
                        _ => "",
                    };
                    app.set_status(&format!("{} {}", prompt_msg, app.file_op_prompt_buffer));
                    return Ok(false);
                }
                KeyCode::Backspace => {
                    if !app.file_op_prompt_buffer.is_empty() {
                        app.file_op_prompt_buffer.pop();
                        let prompt_msg = match op {
                            FileOperation::Create => "New file name (must end with .json):",
                            FileOperation::CreateDir => "New directory name:",
                            FileOperation::Copy(src) => {
                                let name = src.file_name().and_then(|n| n.to_str()).unwrap_or("unknown");
                                &format!("Copy '{}' to (must end with .json):", name)
                            }
                            FileOperation::Rename(path) => {
                                if path.is_dir() {
                                    "Rename/Move directory to:"
                                } else {
                                    "Rename/Move to (must end with .json):"
                                }
                            }
                            _ => "",
                        };
                        app.set_status(&format!("{} {}", prompt_msg, app.file_op_prompt_buffer));
                    } else {
                        app.cancel_file_operation();
                    }
                    return Ok(false);
                }
                _ => return Ok(false),
            }
        }
    }
}

fn handle_explorer_navigation(app: &mut App, key: KeyEvent) -> Result<bool> {
    match key.code {
        KeyCode::Char(':') => {
            // Allow command mode from explorer
            app.input_mode = crate::app::InputMode::Command;
            app.command_buffer = String::new();
            app.command_history_index = None;
            app.set_status(":");
            return Ok(false);
        }
        KeyCode::Char('j') | KeyCode::Down => {
            app.explorer_move_down();
            return Ok(false);
        }
        KeyCode::Char('k') | KeyCode::Up => {
            app.explorer_move_up();
            return Ok(false);
        }
        KeyCode::Enter => {
            // Open file and move focus to right
            app.explorer_select_entry();
            return Ok(false);
        }
        KeyCode::Char('o') => {
            // Check if this might be part of 'go'
            if app.vim_buffer == "g" {
                // Let handle_vim_input process 'go'
                app.handle_vim_input('o');
            } else {
                // Standalone 'o' - open file
                app.explorer_select_entry();
            }
            return Ok(false);
        }
        KeyCode::Char('q') => {
            // Quit program
            return Ok(true);
        }
        KeyCode::Char('g') => {
            // Start of potential 'go' or 'gg'
            app.handle_vim_input('g');
            return Ok(false);
        }
        _ => {}
    }
    Ok(false)
}