treemd 0.5.12

A markdown navigator with tree-based structural navigation and syntax highlighting
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
mod app;
mod help_text;
mod image_cache;
mod interactive;
mod kitty_animation;
#[cfg(all(feature = "mermaid", unix))]
mod mermaid;
mod syntax;
pub mod terminal_compat;
pub mod theme;
pub mod tty; // Public module for TTY handling
mod ui;
mod watcher;

pub use app::{ActionResult, App};
pub use interactive::InteractiveState;
pub use terminal_compat::{ColorMode, TerminalCapabilities};
pub use theme::ThemeName;

use crate::keybindings::Action;
use color_eyre::Result;
use crossterm::ExecutableCommand;
use crossterm::event::{KeyCode, MouseEvent, MouseEventKind};
use crossterm::terminal::{
    BeginSynchronizedUpdate, EndSynchronizedUpdate, EnterAlternateScreen, LeaveAlternateScreen,
};
use opensesame::{Editor, EditorConfig};
use ratatui::DefaultTerminal;
use std::io::stdout;
use std::path::Path;
use std::time::Duration;

/// Suspend the TUI, run an external editor, then restore the TUI.
///
/// If line is provided and the editor supports it, the file will be opened at that line.
/// Uses the provided EditorConfig for editor selection and arguments.
fn run_editor(
    terminal: &mut DefaultTerminal,
    file: &Path,
    line: Option<u32>,
    editor_config: &EditorConfig,
) -> Result<()> {
    // Leave alternate screen and disable raw mode to give editor full terminal control
    stdout().execute(LeaveAlternateScreen)?;
    tty::suspend_raw_mode()?;

    // Build editor command with config
    let mut builder = Editor::builder()
        .file(file)
        .with_config(editor_config.clone());

    if let Some(l) = line {
        builder = builder.line(l);
    }

    let result = builder.open();

    // Restore terminal state
    stdout().execute(EnterAlternateScreen)?;
    tty::resume_raw_mode()?;
    terminal.clear()?;

    result.map_err(|e| color_eyre::eyre::eyre!("{}", e))
}

/// Run the TUI application.
///
/// This function handles the main event loop for the interactive terminal interface.
/// It processes keyboard events and renders the UI until the user quits.
///
/// # Arguments
///
/// * `terminal` - A mutable reference to a ratatui terminal
/// * `app` - The App instance to run
///
/// # Returns
///
/// Returns `Ok(())` on successful exit, or an error if something goes wrong.
pub fn run(terminal: &mut DefaultTerminal, app: App) -> Result<()> {
    let mut app = app;

    // Handle startup file picker if needed (scans directory)
    if app.startup_needs_file_picker {
        app.enter_file_picker();
    }

    // Create file watcher for live reload
    let mut file_watcher = watcher::FileWatcher::new().ok();
    if let Some(ref mut watcher) = file_watcher {
        let _ = watcher.watch(&app.current_file_path);
    }

    let mut needs_redraw = true;

    loop {
        if needs_redraw {
            // Use synchronized output when animating GIFs (reduces flicker).
            let use_sync = app.is_image_modal_open()
                && app.image_modal.gif_frames.len() > 1
                && !app.has_kitty_animation();

            if use_sync {
                let _ = stdout().execute(BeginSynchronizedUpdate);
            }

            terminal.draw(|frame| ui::render(frame, &mut app))?;

            if use_sync {
                let _ = stdout().execute(EndSynchronizedUpdate);
            }

            // If mermaid image dims arrived during this frame, schedule an immediate
            // second draw so the corrected placeholder sizes take effect without
            // requiring a keypress.
            #[cfg(all(feature = "mermaid", unix))]
            if app.mermaid_needs_reindex {
                needs_redraw = true;
                continue;
            }

            needs_redraw = false;
        }

        // Update file watcher if the current file changed (e.g., via navigation)
        if app.file_path_changed {
            app.file_path_changed = false;
            if let Some(ref mut watcher) = file_watcher {
                let _ = watcher.watch(&app.current_file_path);
            }
        }

        // Handle pending editor file open (from link following non-markdown files)
        if let Some(file_path) = app.pending_editor_file.take() {
            let filename = file_path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("file");
            let editor_config = app.editor_config();
            match run_editor(terminal, &file_path, None, &editor_config) {
                Ok(_) => {
                    app.status_message = Some(format!("✓ Opened {} in editor", filename));
                }
                Err(e) => {
                    app.status_message = Some(format!("✗ Failed to open {}: {}", filename, e));
                }
            }
            needs_redraw = true;
            continue; // Redraw after returning from editor
        }

        // Poll for events with dynamic timeout:
        // - When GIF is animating: use time until next frame (for smooth playback)
        // - Otherwise: 100ms for responsive UI updates
        let poll_timeout = app
            .time_until_next_frame()
            .unwrap_or(Duration::from_millis(100));
        let event_ready = tty::poll_event(poll_timeout)?;

        // Check the file watcher every iteration, regardless of whether there
        // was a keyboard event. Otherwise a debounced reload could stall
        // behind a stream of keypresses indefinitely.
        if app.suppress_file_watch {
            app.suppress_file_watch = false;
            if let Some(ref mut watcher) = file_watcher {
                watcher.check_for_changes(); // Drain events, ignore result
            }
        } else if let Some(ref mut watcher) = file_watcher
            && watcher.check_for_changes()
        {
            // Save state before reload
            let was_interactive = app.mode == app::AppMode::Interactive;
            let saved_scroll = app.content_scroll;
            let saved_element_idx = app.interactive_state.current_index;

            // File changed externally - reload with state preservation
            if let Err(e) = app.reload_current_file() {
                app.status_message = Some(format!("✗ Reload failed: {}", e));
            } else {
                // Re-index interactive elements if in interactive mode
                if was_interactive {
                    app.reindex_interactive_elements();
                    // Restore element selection if still valid
                    if let Some(idx) = saved_element_idx
                        && idx < app.interactive_state.elements.len()
                    {
                        app.interactive_state.current_index = Some(idx);
                    }
                }
                // Restore scroll position
                app.content_scroll = saved_scroll.min(app.max_content_scroll());
                app.content_scroll_state = app
                    .content_scroll_state
                    .position(app.content_scroll as usize);
                // Sync previous_selection to prevent update_content_metrics() from resetting scroll
                app.sync_previous_selection();

                app.status_message = Some("↻ File reloaded (external change)".to_string());
            }
            needs_redraw = true;
        }

        if !event_ready {
            // GIF animation needs redraw on timeout
            if app.is_image_modal_open() && app.image_modal.gif_frames.len() > 1 {
                needs_redraw = true;
            }
            continue;
        }

        // Any input event requires a redraw
        needs_redraw = true;

        let event = tty::read_event()?;

        // Mouse handling — keep simple: scroll wheel scrolls content / outline.
        if let Some(mouse) = event.as_mouse_event() {
            handle_mouse(&mut app, mouse);
            continue;
        }

        if let Some(key) = event.as_key_press_event() {
            // When image modal is open, handle modal-specific keys
            if app.is_image_modal_open() {
                match key.code {
                    KeyCode::Esc | KeyCode::Char('q') => {
                        app.close_image_modal();
                    }
                    // Manual frame stepping for GIFs
                    KeyCode::Left | KeyCode::Char('h') => {
                        app.modal_prev_frame();
                    }
                    KeyCode::Right | KeyCode::Char('l') => {
                        app.modal_next_frame();
                    }
                    // Toggle play/pause for GIF animation
                    KeyCode::Char(' ') => {
                        app.modal_toggle_animation();
                    }
                    _ => {}
                }
                continue;
            }

            // Handle text input modes separately - these need raw character input
            let handled = handle_text_input(&mut app, key.code, key.modifiers);

            if !handled {
                // Handle vim-style count prefix (digits before motion commands)
                // Only in modes where count makes sense (Normal, Interactive)
                // Skip in LinkFollow mode where 1-9 jump to links
                let digit_handled = if let KeyCode::Char(c) = key.code {
                    if c.is_ascii_digit()
                        && key.modifiers.is_empty()
                        && matches!(app.mode, app::AppMode::Normal | app::AppMode::Interactive)
                    {
                        // Special case: '0' without existing count goes to start (like vim)
                        if c == '0' && !app.has_count() {
                            false // Let '0' be handled as a motion (go to first)
                        } else {
                            app.accumulate_count_digit(c)
                        }
                    } else {
                        false
                    }
                } else {
                    false
                };

                if !digit_handled {
                    // Try to get an action from the keybinding system
                    if let Some(action) = app.get_action_for_key(key.code, key.modifiers) {
                        // Special handling for CommandPalette confirm - it may return Quit
                        if action == Action::ConfirmAction
                            && app.mode == app::AppMode::CommandPalette
                        {
                            if app.execute_selected_command() {
                                return Ok(()); // Quit command executed
                            }
                        } else {
                            match app.execute_action(action) {
                                ActionResult::Quit => return Ok(()),
                                ActionResult::RunEditor(path, line) => {
                                    let editor_config = app.editor_config();
                                    match run_editor(terminal, &path, line, &editor_config) {
                                        Ok(_) => {
                                            if let Err(e) = app.reload_current_file() {
                                                app.status_message =
                                                    Some(format!("✗ Failed to reload: {}", e));
                                            } else {
                                                app.status_message = Some(
                                                    "✓ File reloaded after editing".to_string(),
                                                );
                                            }
                                            app.update_content_metrics();
                                        }
                                        Err(e) => {
                                            app.status_message =
                                                Some(format!("✗ Editor failed: {}", e));
                                        }
                                    }
                                }
                                ActionResult::Redraw => {
                                    terminal.clear()?;
                                }
                                ActionResult::Continue => {}
                            }
                        }
                    } else {
                        // No action found - clear count prefix (invalid key cancels count)
                        app.clear_count();
                    }
                }
            }
        }
    }
}

/// Handle a mouse event. Currently scroll-only — pointer-click routing into
/// outline/content panes would require knowing the laid-out rects, which the
/// renderer hasn't published yet.
fn handle_mouse(app: &mut App, mouse: MouseEvent) {
    use crate::keybindings::Action;

    // Scroll wheel maps to existing actions so keybindings stay authoritative.
    let action = match mouse.kind {
        MouseEventKind::ScrollDown => Some(Action::Next),
        MouseEventKind::ScrollUp => Some(Action::Previous),
        _ => None,
    };

    if let Some(a) = action {
        // Bypass quit/editor/redraw return paths — scroll never produces them.
        let _ = app.execute_action(a);
    }
}

/// Handle text input for search/edit modes
/// Returns true if the key was handled
fn handle_text_input(
    app: &mut App,
    code: KeyCode,
    modifiers: crossterm::event::KeyModifiers,
) -> bool {
    // Text input modes: outline search, doc search, link search, command palette, cell edit

    // Outline search mode - only handle input when active
    if app.show_search && app.outline_search_active {
        match code {
            KeyCode::Char('u') if modifiers.contains(crossterm::event::KeyModifiers::CONTROL) => {
                app.search_query.clear();
                app.filter_outline();
                return true;
            }
            KeyCode::Char(c) => {
                app.search_input(c);
                return true;
            }
            _ => {}
        }
    }

    // Doc search input mode
    if app.mode == app::AppMode::DocSearch && app.doc_search.active {
        match code {
            KeyCode::Char('u') if modifiers.contains(crossterm::event::KeyModifiers::CONTROL) => {
                app.doc_search.query.clear();
                app.update_doc_search_matches();
                return true;
            }
            KeyCode::Char(c) => {
                app.doc_search_input(c);
                return true;
            }
            _ => {}
        }
    }

    // Link search input mode
    if app.mode == app::AppMode::LinkFollow
        && app.link_picker.active
        && let KeyCode::Char(c) = code
    {
        app.link_search_push(c);
        return true;
    }

    // File search input mode (FilePicker with file_search_active flag)
    if ((app.mode == app::AppMode::FilePicker && app.file_picker.active)
        || app.mode == app::AppMode::FileSearch)
        && let KeyCode::Char(c) = code
    {
        app.file_search_push(c);
        return true;
    }

    // Command palette input mode
    if app.mode == app::AppMode::CommandPalette
        && let KeyCode::Char(c) = code
    {
        app.command_palette_input(c);
        return true;
    }

    // Cell edit mode
    if app.mode == app::AppMode::CellEdit
        && let KeyCode::Char(c) = code
    {
        app.cell_edit_value.push(c);
        return true;
    }

    false
}