fresh-editor 0.1.43

A lightweight, fast terminal-based text editor with LSP support and TypeScript plugins
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
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
use clap::Parser;
use crossterm::{
    cursor::SetCursorStyle,
    event::{
        poll as event_poll, read as event_read, Event as CrosstermEvent, KeyEvent, KeyEventKind,
        KeyboardEnhancementFlags, MouseEvent, PopKeyboardEnhancementFlags,
        PushKeyboardEnhancementFlags,
    },
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
    ExecutableCommand,
};
#[cfg(target_os = "linux")]
use fresh::services::gpm::{gpm_to_crossterm, GpmClient};
use fresh::services::tracing_setup;
use fresh::{
    app::script_control::ScriptControlMode, app::Editor, config, config::DirectoryContext,
    services::release_checker, services::signal_handler,
};
use ratatui::Terminal;
use std::{
    io::{self, stdout},
    path::PathBuf,
    time::Duration,
};
use tracing_subscriber::{fmt, prelude::*, EnvFilter};

/// A high-performance terminal text editor
#[derive(Parser, Debug)]
#[command(name = "fresh")]
#[command(about = "A terminal text editor with multi-cursor support", long_about = None)]
#[command(version)]
struct Args {
    /// File to open
    #[arg(value_name = "FILE")]
    file: Option<PathBuf>,

    /// Disable plugin loading
    #[arg(long)]
    no_plugins: bool,

    /// Path to configuration file
    #[arg(long, value_name = "PATH")]
    config: Option<PathBuf>,

    /// Path to log file for editor diagnostics (default: system temp dir)
    #[arg(long, value_name = "PATH")]
    log_file: Option<PathBuf>,

    /// Enable event logging to the specified file
    #[arg(long, value_name = "LOG_FILE")]
    event_log: Option<PathBuf>,

    /// Enable script control mode (accepts JSON commands via stdin, outputs to stdout)
    #[arg(long)]
    script_mode: bool,

    /// Terminal width for script control mode (default: 80)
    #[arg(long, default_value = "80")]
    script_width: u16,

    /// Terminal height for script control mode (default: 24)
    #[arg(long, default_value = "24")]
    script_height: u16,

    /// Print script control mode command schema and exit
    #[arg(long)]
    script_schema: bool,

    /// Don't restore previous session (start fresh)
    #[arg(long)]
    no_session: bool,
}

/// Parsed file location from CLI argument in file:line:col format
#[derive(Debug)]
struct FileLocation {
    path: PathBuf,
    line: Option<usize>,
    column: Option<usize>,
}

/// Parse a file path that may include line and column information.
/// Supports formats:
/// - file.txt
/// - file.txt:10
/// - file.txt:10:5
/// - /path/to/file.txt:10:5
///
/// For Windows paths like C:\path\file.txt:10:5, we handle the drive letter
/// prefix properly using std::path APIs.
///
/// If the full path exists as a file, it's used as-is (handles files with colons in name).
fn parse_file_location(input: &str) -> FileLocation {
    use std::path::{Component, Path};

    let full_path = PathBuf::from(input);

    // If the full path exists as a file, use it directly
    // This handles edge cases like files named "foo:10"
    if full_path.is_file() {
        return FileLocation {
            path: full_path,
            line: None,
            column: None,
        };
    }

    // Check if the path has a Windows drive prefix using std::path
    let has_prefix = Path::new(input)
        .components()
        .next()
        .map(|c| matches!(c, Component::Prefix(_)))
        .unwrap_or(false);

    // Calculate where to start looking for :line:col
    // For Windows paths with prefix (e.g., "C:"), skip past the drive letter and colon
    let search_start = if has_prefix {
        // Find the first colon (the drive letter separator) and skip it
        input.find(':').map(|i| i + 1).unwrap_or(0)
    } else {
        0
    };

    // Find the last colon(s) that could be line:col
    let suffix = &input[search_start..];

    // Try to parse from the end: look for :col and :line patterns
    // We work backwards to find numeric suffixes
    let parts: Vec<&str> = suffix.rsplitn(3, ':').collect();

    match parts.as_slice() {
        // Could be "col", "line", "rest" or just parts of the path
        [maybe_col, maybe_line, rest] => {
            if let (Ok(line), Ok(col)) = (maybe_line.parse::<usize>(), maybe_col.parse::<usize>()) {
                // Both parsed as numbers: file:line:col
                let path_str = if has_prefix {
                    format!("{}{}", &input[..search_start], rest)
                } else {
                    rest.to_string()
                };
                return FileLocation {
                    path: PathBuf::from(path_str),
                    line: Some(line),
                    column: Some(col),
                };
            }
            // Fall through - not valid line:col format
        }
        // Could be "line", "rest" or just parts of the path
        [maybe_line, rest] => {
            if let Ok(line) = maybe_line.parse::<usize>() {
                // Parsed as number: file:line
                let path_str = if has_prefix {
                    format!("{}{}", &input[..search_start], rest)
                } else {
                    rest.to_string()
                };
                return FileLocation {
                    path: PathBuf::from(path_str),
                    line: Some(line),
                    column: None,
                };
            }
            // Fall through - not valid line format
        }
        _ => {}
    }

    // No valid line:col suffix found, treat the whole thing as a path
    FileLocation {
        path: full_path,
        line: None,
        column: None,
    }
}

fn main() -> io::Result<()> {
    // Parse command-line arguments
    let args = Args::parse();

    // Handle --script-schema flag
    if args.script_schema {
        println!("{}", fresh::app::script_control::get_command_schema());
        return Ok(());
    }

    // Handle script control mode
    if args.script_mode {
        // Initialize tracing for script mode - log to stderr so it doesn't interfere with JSON output on stdout
        tracing_subscriber::registry()
            .with(fmt::layer().with_writer(io::stderr))
            .with(EnvFilter::from_default_env().add_directive(tracing::Level::INFO.into()))
            .init();

        return run_script_control_mode(&args);
    }

    // Initialize tracing - log to a file to avoid interfering with terminal UI
    // Also create a separate warning log that captures WARN+ and notifies the editor
    let log_file = args
        .log_file
        .unwrap_or_else(|| std::env::temp_dir().join("fresh.log"));
    let mut warning_log_handle = tracing_setup::init_global(&log_file);

    tracing::info!("Editor starting");

    // Install signal handlers for SIGTERM and SIGINT
    signal_handler::install_signal_handlers();
    tracing::info!("Signal handlers installed");

    // Set up panic hook to restore terminal
    let original_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |panic| {
        let _ = stdout().execute(SetCursorStyle::DefaultUserShape);
        let _ = stdout().execute(PopKeyboardEnhancementFlags);
        let _ = disable_raw_mode();
        let _ = stdout().execute(LeaveAlternateScreen);
        original_hook(panic);
    }));

    // Load configuration
    let config = if let Some(config_path) = &args.config {
        match config::Config::load_from_file(config_path) {
            Ok(cfg) => cfg,
            Err(e) => {
                eprintln!(
                    "Error: Failed to load config from {}: {}",
                    config_path.display(),
                    e
                );
                return Err(io::Error::new(io::ErrorKind::InvalidData, e.to_string()));
            }
        }
    } else {
        // Try to load from default location, fall back to defaults
        config::Config::load_or_default()
    };

    // Set up terminal first
    enable_raw_mode()?;
    stdout().execute(EnterAlternateScreen)?;

    // Enable keyboard enhancement flags to support Shift+Up/Down and other modifier combinations
    // This uses the Kitty keyboard protocol for better key detection in supported terminals
    let keyboard_flags = KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES
        | KeyboardEnhancementFlags::REPORT_ALTERNATE_KEYS;
    let _ = stdout().execute(PushKeyboardEnhancementFlags(keyboard_flags));
    tracing::info!("Enabled keyboard enhancement flags: {:?}", keyboard_flags);

    // Try to connect to GPM for mouse support in Linux console
    // Do this BEFORE enabling crossterm mouse capture, since GPM and xterm mouse
    // protocols don't mix well
    #[cfg(target_os = "linux")]
    let gpm_client = match GpmClient::connect() {
        Ok(client) => client,
        Err(e) => {
            tracing::warn!("Failed to connect to GPM: {}", e);
            None
        }
    };
    #[cfg(not(target_os = "linux"))]
    let gpm_client: Option<()> = None;

    // Enable mouse support via crossterm (xterm mouse protocol)
    // Only do this if GPM is NOT connected, since on Linux console GPM handles mouse
    if gpm_client.is_none() {
        let _ = crossterm::execute!(stdout(), crossterm::event::EnableMouseCapture);
        tracing::info!("Enabled crossterm mouse capture");
    } else {
        tracing::info!("Using GPM for mouse capture, skipping crossterm mouse protocol");
    }

    // Enable blinking block cursor for the primary cursor in active split
    let _ = stdout().execute(SetCursorStyle::BlinkingBlock);
    tracing::info!("Enabled blinking block cursor");

    let backend = ratatui::backend::CrosstermBackend::new(stdout());
    let mut terminal = Terminal::new(backend)?;

    // Clear the terminal to ensure proper initialization
    terminal.clear()?;

    let size = terminal.size()?;
    tracing::info!("Terminal size: {}x{}", size.width, size.height);

    // Parse the file argument, extracting any line:col suffix
    let file_location = args
        .file
        .as_ref()
        .map(|p| parse_file_location(p.to_string_lossy().as_ref()));

    // Determine if the provided path is a directory or file
    let (working_dir, file_to_open, show_file_explorer) = if let Some(ref loc) = file_location {
        if loc.path.is_dir() {
            // Path is a directory: use as working dir, don't open any file, show file explorer
            (Some(loc.path.clone()), None, true)
        } else {
            // Path is a file: use current dir as working dir, open the file, don't auto-show explorer
            (None, Some(loc.path.clone()), false)
        }
    } else {
        // No path provided: use current dir, no file, don't auto-show explorer
        (None, None, false)
    };

    // Get directory context from system (data dir, config dir, etc.)
    let dir_context = DirectoryContext::from_system()?;

    // Track the current working directory (may change on restart)
    let mut current_working_dir = working_dir;

    // Track whether this is the first run (for session restore, file open, etc.)
    let mut is_first_run = true;

    // Track whether we should restore session on restart (for project switching)
    let mut restore_session_on_restart = false;

    // Track the last update result for display after exit
    let mut last_update_result = None;

    // Main editor loop - supports restarting with a new working directory
    let result = loop {
        // Create editor with actual terminal size and working directory
        let mut editor = if args.no_plugins {
            Editor::with_plugins_disabled(
                config.clone(),
                size.width,
                size.height,
                current_working_dir.clone(),
                dir_context.clone(),
            )?
        } else {
            Editor::with_working_dir(
                config.clone(),
                size.width,
                size.height,
                current_working_dir.clone(),
                dir_context.clone(),
            )?
        };

        // Enable GPM software cursor if GPM is active
        // (GPM can't draw its cursor on the alternate screen buffer used by TUI apps)
        #[cfg(target_os = "linux")]
        if gpm_client.is_some() {
            editor.set_gpm_active(true);
        }

        // Enable event log streaming if requested (only on first run)
        if is_first_run {
            if let Some(log_path) = &args.event_log {
                tracing::trace!("Event logging enabled: {}", log_path.display());
                editor.enable_event_streaming(log_path)?;
            }
        }

        // Set up warning log monitoring (to open warning log when warnings occur)
        // Note: warning_log_handle is consumed on first use, so this only works on first run
        if is_first_run {
            if let Some(handle) = warning_log_handle.take() {
                editor.set_warning_log(handle.receiver, handle.path);
            }
        }

        // Try to restore previous session:
        // - On first run (unless --no-session flag is set or a file was specified)
        // - After project switch (restore session for the new project)
        let session_enabled = !args.no_session && file_to_open.is_none();
        if (is_first_run && session_enabled) || restore_session_on_restart {
            match editor.try_restore_session() {
                Ok(true) => {
                    tracing::info!("Session restored successfully");
                }
                Ok(false) => {
                    tracing::debug!("No previous session found");
                }
                Err(e) => {
                    tracing::warn!("Failed to restore session: {}", e);
                }
            }
            // Reset the flag after restoring
            restore_session_on_restart = false;
        }

        // Open file if provided (only on first run, this takes precedence over session)
        if is_first_run {
            if let Some(path) = &file_to_open {
                editor.open_file(path)?;

                // Navigate to line:col if specified
                if let Some(ref loc) = file_location {
                    if let Some(line) = loc.line {
                        editor.goto_line_col(line, loc.column);
                    }
                }
            }
        }

        // Show file explorer if directory was provided (only on first run)
        // On restart, always show file explorer for the new project
        if (is_first_run && show_file_explorer) || !is_first_run {
            editor.show_file_explorer();
        }

        // Check for recovery files from a crash and recover them (only on first run)
        if is_first_run && editor.has_recovery_files().unwrap_or(false) {
            tracing::info!("Recovery files found from previous session, recovering...");
            match editor.recover_all_buffers() {
                Ok(count) if count > 0 => {
                    tracing::info!("Recovered {} buffer(s)", count);
                }
                Ok(_) => {
                    tracing::info!("No buffers to recover");
                }
                Err(e) => {
                    tracing::warn!("Failed to recover buffers: {}", e);
                }
            }
        }

        // Start recovery session
        if let Err(e) = editor.start_recovery_session() {
            tracing::warn!("Failed to start recovery session: {}", e);
        }

        // Show status message on restart
        if !is_first_run {
            editor.set_status_message(format!(
                "Switched to project: {}",
                current_working_dir
                    .as_ref()
                    .map(|p| p.display().to_string())
                    .unwrap_or_else(|| ".".to_string())
            ));
        }

        // Run the editor (update checking is now handled internally by Editor)
        #[cfg(target_os = "linux")]
        let loop_result = run_event_loop(&mut editor, &mut terminal, session_enabled, &gpm_client);
        #[cfg(not(target_os = "linux"))]
        let loop_result = run_event_loop(&mut editor, &mut terminal, session_enabled);

        // End recovery session (clean shutdown)
        if let Err(e) = editor.end_recovery_session() {
            tracing::warn!("Failed to end recovery session: {}", e);
        }

        // Save update result before potentially dropping editor
        last_update_result = editor.get_update_result().cloned();

        // Check if we should restart with a new working directory
        if let Some(new_dir) = editor.take_restart_dir() {
            tracing::info!(
                "Restarting editor with new working directory: {}",
                new_dir.display()
            );
            current_working_dir = Some(new_dir);
            is_first_run = false;
            restore_session_on_restart = true; // Restore session for the new project
                                               // Drop the editor to clean up all resources (LSP, plugins, etc.)
            drop(editor);
            // Clear the terminal for the fresh start
            terminal.clear()?;
            continue;
        }

        // Normal exit - break out of the loop
        break loop_result;
    };

    // Clean up terminal
    let _ = crossterm::execute!(stdout(), crossterm::event::DisableMouseCapture);
    let _ = stdout().execute(SetCursorStyle::DefaultUserShape);
    let _ = stdout().execute(PopKeyboardEnhancementFlags);
    disable_raw_mode()?;
    stdout().execute(LeaveAlternateScreen)?;

    // Check for updates after terminal is restored (using cached result)
    if let Some(update_result) = last_update_result {
        if update_result.update_available {
            eprintln!();
            eprintln!(
                "A new version of fresh is available: {} -> {}",
                release_checker::CURRENT_VERSION,
                update_result.latest_version
            );
            if let Some(cmd) = update_result.install_method.update_command() {
                eprintln!("Update with: {}", cmd);
            } else {
                eprintln!(
                    "Download from: https://github.com/sinelaw/fresh/releases/tag/v{}",
                    update_result.latest_version
                );
            }
            eprintln!();
        }
    }

    result
}

/// Run the editor in script control mode
fn run_script_control_mode(args: &Args) -> io::Result<()> {
    // Parse the file argument, extracting any line:col suffix
    let file_location = args
        .file
        .as_ref()
        .map(|p| parse_file_location(p.to_string_lossy().as_ref()));

    // Get directory context from system
    let dir_context = DirectoryContext::from_system()?;

    // Create script control mode instance
    let mut control = if let Some(ref loc) = file_location {
        if loc.path.is_dir() {
            ScriptControlMode::with_working_dir(
                args.script_width,
                args.script_height,
                loc.path.clone(),
                dir_context,
            )?
        } else {
            let mut ctrl =
                ScriptControlMode::new(args.script_width, args.script_height, dir_context)?;
            // Open the file if provided
            ctrl.open_file(&loc.path)?;
            // Navigate to line:col if specified
            if let Some(line) = loc.line {
                ctrl.goto_line_col(line, loc.column);
            }
            ctrl
        }
    } else {
        ScriptControlMode::new(args.script_width, args.script_height, dir_context)?
    };

    control.run()
}

/// Main event loop
#[cfg(target_os = "linux")]
fn run_event_loop(
    editor: &mut Editor,
    terminal: &mut Terminal<ratatui::backend::CrosstermBackend<io::Stdout>>,
    session_enabled: bool,
    gpm_client: &Option<GpmClient>,
) -> io::Result<()> {
    use std::time::Instant;

    const FRAME_DURATION: Duration = Duration::from_millis(16); // 60fps
    let mut last_render = Instant::now();
    let mut needs_render = true;
    let mut pending_event: Option<CrosstermEvent> = None; // For events read during coalescing

    loop {
        if editor.process_async_messages() {
            needs_render = true;
        }

        // Check mouse hover timer for LSP hover requests
        if editor.check_mouse_hover_timer() {
            needs_render = true;
        }

        // Check for warnings and open warning log if any occurred
        if editor.check_warning_log() {
            needs_render = true;
        }

        // Periodic auto-save for recovery
        if let Err(e) = editor.auto_save_dirty_buffers() {
            tracing::debug!("Auto-save error: {}", e);
        }

        if editor.should_quit() {
            // Save session before quitting (if enabled)
            if session_enabled {
                if let Err(e) = editor.save_session() {
                    tracing::warn!("Failed to save session: {}", e);
                } else {
                    tracing::debug!("Session saved successfully");
                }
            }
            break;
        }

        // Render at most 60fps
        if needs_render && last_render.elapsed() >= FRAME_DURATION {
            terminal.draw(|frame| editor.render(frame))?;
            last_render = Instant::now();
            needs_render = false;
        }

        // Get next event - check GPM first if available, then crossterm
        let event = if let Some(e) = pending_event.take() {
            Some(e)
        } else {
            let timeout = if needs_render {
                FRAME_DURATION.saturating_sub(last_render.elapsed())
            } else {
                Duration::from_millis(50)
            };

            // Poll for events from GPM and/or crossterm
            poll_with_gpm(gpm_client.as_ref(), timeout)?
        };

        let Some(event) = event else { continue };

        // Coalesce mouse moves - skip stale ones, keep clicks/keys
        let (event, next) = coalesce_mouse_moves(event)?;
        pending_event = next;

        match event {
            CrosstermEvent::Key(key_event) => {
                // Only process key press events to avoid duplicate events on Windows
                // (Windows sends both Press and Release events, while Linux/macOS only send Press)
                if key_event.kind == KeyEventKind::Press {
                    handle_key_event(editor, key_event)?;
                    needs_render = true;
                }
            }
            CrosstermEvent::Mouse(mouse_event) => {
                if handle_mouse_event(editor, mouse_event)? {
                    needs_render = true;
                }
            }
            CrosstermEvent::Resize(w, h) => {
                editor.resize(w, h);
                needs_render = true;
            }
            _ => {}
        }
    }

    Ok(())
}

/// Main event loop (non-Linux version without GPM)
#[cfg(not(target_os = "linux"))]
fn run_event_loop(
    editor: &mut Editor,
    terminal: &mut Terminal<ratatui::backend::CrosstermBackend<io::Stdout>>,
    session_enabled: bool,
) -> io::Result<()> {
    use std::time::Instant;

    const FRAME_DURATION: Duration = Duration::from_millis(16); // 60fps
    let mut last_render = Instant::now();
    let mut needs_render = true;
    let mut pending_event: Option<CrosstermEvent> = None;

    loop {
        if editor.process_async_messages() {
            needs_render = true;
        }

        // Check mouse hover timer for LSP hover requests
        if editor.check_mouse_hover_timer() {
            needs_render = true;
        }

        // Check for warnings and open warning log if any occurred
        if editor.check_warning_log() {
            needs_render = true;
        }

        if let Err(e) = editor.auto_save_dirty_buffers() {
            tracing::debug!("Auto-save error: {}", e);
        }

        if editor.should_quit() {
            if session_enabled {
                if let Err(e) = editor.save_session() {
                    tracing::warn!("Failed to save session: {}", e);
                } else {
                    tracing::debug!("Session saved successfully");
                }
            }
            break;
        }

        if needs_render && last_render.elapsed() >= FRAME_DURATION {
            terminal.draw(|frame| editor.render(frame))?;
            last_render = Instant::now();
            needs_render = false;
        }

        let event = if let Some(e) = pending_event.take() {
            Some(e)
        } else {
            let timeout = if needs_render {
                FRAME_DURATION.saturating_sub(last_render.elapsed())
            } else {
                Duration::from_millis(50)
            };

            if event_poll(timeout)? {
                Some(event_read()?)
            } else {
                None
            }
        };

        let Some(event) = event else { continue };

        let (event, next) = coalesce_mouse_moves(event)?;
        pending_event = next;

        match event {
            CrosstermEvent::Key(key_event) => {
                if key_event.kind == KeyEventKind::Press {
                    handle_key_event(editor, key_event)?;
                    needs_render = true;
                }
            }
            CrosstermEvent::Mouse(mouse_event) => {
                if handle_mouse_event(editor, mouse_event)? {
                    needs_render = true;
                }
            }
            CrosstermEvent::Resize(w, h) => {
                editor.resize(w, h);
                needs_render = true;
            }
            _ => {}
        }
    }

    Ok(())
}

/// Poll for events from both GPM and crossterm (Linux with libgpm available)
#[cfg(target_os = "linux")]
fn poll_with_gpm(
    gpm_client: Option<&GpmClient>,
    timeout: Duration,
) -> io::Result<Option<CrosstermEvent>> {
    use nix::poll::{poll, PollFd, PollFlags, PollTimeout};
    use std::os::unix::io::{AsRawFd, BorrowedFd};

    // If no GPM client, just use crossterm polling
    let Some(gpm) = gpm_client else {
        return if event_poll(timeout)? {
            Ok(Some(event_read()?))
        } else {
            Ok(None)
        };
    };

    // Set up poll for both stdin (crossterm) and GPM fd
    let stdin_fd = std::io::stdin().as_raw_fd();
    let gpm_fd = gpm.fd();
    tracing::trace!("GPM poll: stdin_fd={}, gpm_fd={}", stdin_fd, gpm_fd);

    // SAFETY: We're borrowing the fds for the duration of the poll call
    let stdin_borrowed = unsafe { BorrowedFd::borrow_raw(stdin_fd) };
    let gpm_borrowed = unsafe { BorrowedFd::borrow_raw(gpm_fd) };

    let mut poll_fds = [
        PollFd::new(stdin_borrowed, PollFlags::POLLIN),
        PollFd::new(gpm_borrowed, PollFlags::POLLIN),
    ];

    // Convert timeout to milliseconds, clamping to u16::MAX (about 65 seconds)
    let timeout_ms = timeout.as_millis().min(u16::MAX as u128) as u16;
    let poll_timeout = PollTimeout::from(timeout_ms);
    let ready = poll(&mut poll_fds, poll_timeout)?;

    if ready == 0 {
        return Ok(None);
    }

    let stdin_revents = poll_fds[0].revents();
    let gpm_revents = poll_fds[1].revents();
    tracing::trace!(
        "GPM poll: ready={}, stdin_revents={:?}, gpm_revents={:?}",
        ready,
        stdin_revents,
        gpm_revents
    );

    // Check GPM first (mouse events are typically less frequent)
    if gpm_revents.map_or(false, |r| r.contains(PollFlags::POLLIN)) {
        tracing::trace!("GPM poll: GPM fd has data, reading event...");
        match gpm.read_event() {
            Ok(Some(gpm_event)) => {
                tracing::trace!(
                    "GPM event received: x={}, y={}, buttons={}, type=0x{:x}",
                    gpm_event.x,
                    gpm_event.y,
                    gpm_event.buttons.0,
                    gpm_event.event_type
                );
                if let Some(mouse_event) = gpm_to_crossterm(&gpm_event) {
                    tracing::trace!("GPM event converted to crossterm: {:?}", mouse_event);
                    return Ok(Some(CrosstermEvent::Mouse(mouse_event)));
                } else {
                    tracing::debug!("GPM event could not be converted to crossterm event");
                }
            }
            Ok(None) => {
                tracing::trace!("GPM poll: read_event returned None");
            }
            Err(e) => {
                tracing::warn!("GPM poll: read_event error: {}", e);
            }
        }
    }

    // Check stdin (crossterm events)
    if stdin_revents.map_or(false, |r| r.contains(PollFlags::POLLIN)) {
        // Use crossterm's read since it handles escape sequence parsing
        if event_poll(Duration::ZERO)? {
            return Ok(Some(event_read()?));
        }
    }

    Ok(None)
}

/// Handle a keyboard event
fn handle_key_event(editor: &mut Editor, key_event: KeyEvent) -> io::Result<()> {
    // Trace the full key event
    tracing::trace!(
        "Key event received: code={:?}, modifiers={:?}, kind={:?}, state={:?}",
        key_event.code,
        key_event.modifiers,
        key_event.kind,
        key_event.state
    );

    // Log the keystroke
    let key_code = format!("{:?}", key_event.code);
    let modifiers = format!("{:?}", key_event.modifiers);
    editor.log_keystroke(&key_code, &modifiers);

    // Delegate to the editor's handle_key method
    editor.handle_key(key_event.code, key_event.modifiers)?;

    Ok(())
}

/// Handle a mouse event
/// Returns true if a re-render is needed
fn handle_mouse_event(editor: &mut Editor, mouse_event: MouseEvent) -> io::Result<bool> {
    tracing::debug!(
        "Mouse event received: kind={:?}, column={}, row={}, modifiers={:?}",
        mouse_event.kind,
        mouse_event.column,
        mouse_event.row,
        mouse_event.modifiers
    );

    // Delegate to the editor's handle_mouse method
    editor.handle_mouse(mouse_event)
}

/// Skip stale mouse move events, return the latest one.
/// If we read a non-move event while draining, return it as pending.
fn coalesce_mouse_moves(
    event: CrosstermEvent,
) -> io::Result<(CrosstermEvent, Option<CrosstermEvent>)> {
    use crossterm::event::MouseEventKind;

    // Only coalesce mouse moves
    if !matches!(&event, CrosstermEvent::Mouse(m) if m.kind == MouseEventKind::Moved) {
        return Ok((event, None));
    }

    let mut latest = event;
    while event_poll(Duration::ZERO)? {
        let next = event_read()?;
        if matches!(&next, CrosstermEvent::Mouse(m) if m.kind == MouseEventKind::Moved) {
            latest = next; // Newer move, skip the old one
        } else {
            return Ok((latest, Some(next))); // Hit a click/key, save it
        }
    }
    Ok((latest, None))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_file_location_simple_path() {
        let loc = parse_file_location("foo.txt");
        assert_eq!(loc.path, PathBuf::from("foo.txt"));
        assert_eq!(loc.line, None);
        assert_eq!(loc.column, None);
    }

    #[test]
    fn test_parse_file_location_with_line() {
        let loc = parse_file_location("foo.txt:42");
        assert_eq!(loc.path, PathBuf::from("foo.txt"));
        assert_eq!(loc.line, Some(42));
        assert_eq!(loc.column, None);
    }

    #[test]
    fn test_parse_file_location_with_line_and_col() {
        let loc = parse_file_location("foo.txt:42:10");
        assert_eq!(loc.path, PathBuf::from("foo.txt"));
        assert_eq!(loc.line, Some(42));
        assert_eq!(loc.column, Some(10));
    }

    #[test]
    fn test_parse_file_location_absolute_path() {
        let loc = parse_file_location("/home/user/foo.txt:100:5");
        assert_eq!(loc.path, PathBuf::from("/home/user/foo.txt"));
        assert_eq!(loc.line, Some(100));
        assert_eq!(loc.column, Some(5));
    }

    #[test]
    fn test_parse_file_location_no_numbers_after_colon() {
        // If the suffix isn't a number, treat the whole thing as a path
        let loc = parse_file_location("foo:bar");
        assert_eq!(loc.path, PathBuf::from("foo:bar"));
        assert_eq!(loc.line, None);
        assert_eq!(loc.column, None);
    }

    #[test]
    fn test_parse_file_location_mixed_suffix() {
        // If only one part is a number, depends on position
        // "foo:10:bar" -> "bar" isn't a number, so no line:col parsing
        let loc = parse_file_location("foo:10:bar");
        assert_eq!(loc.path, PathBuf::from("foo:10:bar"));
        assert_eq!(loc.line, None);
        assert_eq!(loc.column, None);
    }

    #[test]
    fn test_parse_file_location_line_only_not_col() {
        // "foo:bar:10" -> "10" is col, "bar" isn't line, so no parsing
        let loc = parse_file_location("foo:bar:10");
        assert_eq!(loc.path, PathBuf::from("foo:bar:10"));
        assert_eq!(loc.line, None);
        assert_eq!(loc.column, None);
    }
}

// Property tests use Unix-style path generation strategy, skip on Windows
// where path parsing differs (drive letters like C: conflict with :line:col parsing)
#[cfg(all(test, not(windows)))]
mod proptests {
    use super::*;
    use proptest::prelude::*;

    /// Generate a valid Unix-style file path (no colons in path components)
    fn unix_path_strategy() -> impl Strategy<Value = String> {
        prop::collection::vec("[a-zA-Z0-9._-]+", 1..5).prop_map(|components| components.join("/"))
    }

    proptest! {
        /// Property: If we construct "path:line:col", we should get back the path, line, and col
        #[test]
        fn roundtrip_line_col(
            path in unix_path_strategy(),
            line in 1usize..10000,
            col in 1usize..1000
        ) {
            let input = format!("{}:{}:{}", path, line, col);
            let loc = parse_file_location(&input);

            prop_assert_eq!(loc.path, PathBuf::from(&path));
            prop_assert_eq!(loc.line, Some(line));
            prop_assert_eq!(loc.column, Some(col));
        }

        /// Property: If we construct "path:line", we should get back the path and line
        #[test]
        fn roundtrip_line_only(
            path in unix_path_strategy(),
            line in 1usize..10000
        ) {
            let input = format!("{}:{}", path, line);
            let loc = parse_file_location(&input);

            prop_assert_eq!(loc.path, PathBuf::from(&path));
            prop_assert_eq!(loc.line, Some(line));
            prop_assert_eq!(loc.column, None);
        }

        /// Property: A path without any colon-number suffix returns the full path
        #[test]
        fn path_without_numbers_unchanged(
            path in unix_path_strategy()
        ) {
            let loc = parse_file_location(&path);

            prop_assert_eq!(loc.path, PathBuf::from(&path));
            prop_assert_eq!(loc.line, None);
            prop_assert_eq!(loc.column, None);
        }

        /// Property: line and column should always be non-zero when present
        /// (we parse as usize so 0 is valid, but the function doesn't filter)
        #[test]
        fn parsed_values_match_input(
            path in unix_path_strategy(),
            line in 0usize..10000,
            col in 0usize..1000
        ) {
            let input = format!("{}:{}:{}", path, line, col);
            let loc = parse_file_location(&input);

            prop_assert_eq!(loc.line, Some(line));
            prop_assert_eq!(loc.column, Some(col));
        }
    }
}