vorto 0.15.3

A Vim-flavored modal terminal editor with batteries included: tree-sitter, LSP, fuzzy pickers, vim-surround, multi-cursor, and optional Copilot.
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
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
//! Apply a `Cmd` stream to `App`.
//!
//! The third stage of the input pipeline: where `handle_expr` produced a
//! list of non-buffer state changes, `run_cmds` actually performs them.
//! Most variants are thin shims over existing `App` helpers
//! (`enter_mode`, `open_prompt`, `buffer_cycle`, the `lsp_*` methods,
//! …); this module is the dispatcher, not the implementer.

use std::path::Path;
use std::time::Duration;

use anyhow::Result;

use super::eval::word_under_cursor;
use super::{App, Toast, root_cause};
use crate::effect::{Cmd, ScrollAnchor};
use crate::lsp;

/// Upper bound on how long save waits for `textDocument/formatting`
/// before giving up and writing the un-formatted buffer. Generous
/// enough for rust-analyzer's first-format-after-startup; short enough
/// that a wedged server doesn't strand the user.
const LSP_FORMAT_TIMEOUT: Duration = Duration::from_secs(3);

impl App {
    pub(super) fn run_cmds(&mut self, cmds: Vec<Cmd>) -> Result<()> {
        for cmd in cmds {
            self.run_cmd(cmd)?;
        }
        Ok(())
    }

    fn run_cmd(&mut self, cmd: Cmd) -> Result<()> {
        match cmd {
            Cmd::EnterMode(m) => self.enter_mode(m),
            Cmd::ToastInfo(s) => self.push_toast(Toast::info(s)),
            Cmd::ToastError(s) => self.push_toast(Toast::error(s)),
            Cmd::OpenPrompt(k) => self.open_prompt(k),
            Cmd::OpenRenamePrompt => self.open_rename_prompt(),
            Cmd::SetSearch { pattern, forward } => self.search.set(pattern, forward),
            Cmd::JumpSearch { reverse } => {
                let forward = self.search.last_forward ^ reverse;
                self.run_jump_search(forward);
            }
            Cmd::SearchSelectMatch { reverse } => {
                let forward = self.search.last_forward ^ reverse;
                self.run_search_select(forward);
            }
            Cmd::SetLastFind(lf) => self.last_find = Some(lf),
            Cmd::Scroll(anchor) => self.run_scroll(anchor),
            Cmd::Save {
                path,
                then_quit,
                force,
            } => self.run_save(path.as_deref(), then_quit, force),
            Cmd::SaveAll { then_quit, force } => self.run_save_all(then_quit, force),
            Cmd::OpenPath(path) => self.open_path(&path)?,
            Cmd::Reload => self.run_reload(),
            Cmd::ReloadAll => self.run_reload_all(),
            Cmd::ConfigReload => self.run_config_reload(),
            Cmd::LspJump { method, label } => self.lsp_jump(method, label),
            Cmd::LspFindReferences => self.lsp_find_references(),
            Cmd::LspCodeAction => self.lsp_code_action(),
            Cmd::LspHover => self.lsp_hover(),
            Cmd::OpenLspStatus { all } => self.open_lsp_status(all),
            Cmd::GotoDiagnostic { forward, count } => self.run_goto_diagnostic(forward, count),
            Cmd::GotoConflict { forward, count } => self.run_goto_conflict(forward, count),
            Cmd::BufferCycle { forward } => self.buffer_cycle(forward)?,
            Cmd::BufferDelete { force } => self.buffer_delete(force)?,
            Cmd::BufferDeleteAll => self.buffer_delete_all()?,
            Cmd::NewScratchBuffer => {
                // Always mint a fresh id: `:new` is documented as "give
                // me a new buffer", which would feel broken if it kept
                // reusing the single Scratch(0) slot.
                let id = self.mint_scratch_id();
                self.switch_to_buffer(crate::buffer_ref::BufferRef::Scratch(id))?;
            }
            Cmd::Quit => self.should_quit = true,
            Cmd::StartJumpLabel => self.start_jump_label(),
            Cmd::JumpBack { count } => self.jump_back(count),
            Cmd::JumpForward { count } => self.jump_forward(count),
            Cmd::SelectWholeBuffer => self.run_select_whole_buffer(),
            Cmd::SyncYank => self.sync_yank_to_clipboard(),
            Cmd::SplitWindow { dir } => self.split_window(dir),
            Cmd::CloseWindow => self.close_window(),
            Cmd::FocusWindow { dir } => self.focus_window(dir),
            Cmd::CycleWindow => self.cycle_window(),
        }
        Ok(())
    }

    /// Push the current `Buffer.yank` onto the OS clipboard. Initializes
    /// the `arboard` handle on first use; both init failure and a failed
    /// `set_text` are swallowed silently so that headless / sandboxed
    /// environments don't surface a noisy error on every yank — the
    /// internal register keeps working and `p` paste-in-vorto is
    /// unaffected.
    pub(super) fn sync_yank_to_clipboard(&mut self) {
        if self.clipboard.is_none() {
            self.clipboard = arboard::Clipboard::new().ok();
        }
        let yank = self.active_doc().yank.clone();
        if let Some(cb) = self.clipboard.as_mut() {
            let _ = cb.set_text(yank);
        }
    }

    /// `gA` — select every line in the buffer. Sets the visual anchor
    /// at (0, 0) directly rather than going through `enter_mode`, since
    /// the latter only pins the anchor on a Normal→Visual transition
    /// and we want a fresh selection even if we're already in some
    /// visual mode.
    fn run_select_whole_buffer(&mut self) {
        let last = self.active_doc().lines.len().saturating_sub(1);
        self.visual_anchor = Some(crate::editor::Cursor { row: 0, col: 0 });
        self.editor.mode = crate::mode::Mode::VisualLine;
        self.editor.cursor = crate::editor::Cursor { row: last, col: 0 };
    }

    /// `]d` / `[d` — move the cursor to the next/previous LSP
    /// diagnostic in the current buffer. Diagnostics are sorted by
    /// `(line, column)` upstream (in `lsp_coordinator`), so the walk
    /// is just a linear scan. Wraps at the buffer boundary so repeated
    /// presses cycle. Centers the viewport on the landing position
    /// and surfaces the diagnostic message as an info toast — the
    /// inline marker would otherwise be the only feedback that the
    /// jump fired, and that's easy to miss after a long jump.
    fn run_goto_diagnostic(&mut self, forward: bool, count: u32) {
        let Some(diags) = self.current_diagnostics() else {
            self.push_toast(Toast::info("no diagnostics"));
            return;
        };
        if diags.is_empty() {
            self.push_toast(Toast::info("no diagnostics"));
            return;
        }
        let n = diags.len();
        let cur = self.editor.cursor;
        // Index of the next match in `forward` direction strictly past
        // the cursor; falls back to wrap-around when the cursor sits
        // at/after the last (forward) or at/before the first (back).
        let start = if forward {
            diags
                .iter()
                .position(|d| {
                    let p = d.range.start;
                    (p.line as usize, p.character as usize) > (cur.row, cur.col)
                })
                .unwrap_or(0)
        } else {
            diags
                .iter()
                .rposition(|d| {
                    let p = d.range.start;
                    (p.line as usize, p.character as usize) < (cur.row, cur.col)
                })
                .unwrap_or(n - 1)
        };
        // Count: walk `count - 1` more steps in the same direction,
        // wrapping. count == 0 shouldn't reach here (the parser maps
        // bare `]d` to count == 1) but guard with max(1) just in case.
        let steps = count.max(1) as usize - 1;
        let idx = if forward {
            (start + steps) % n
        } else {
            // (start - steps) mod n, computed without going negative.
            (start + n - (steps % n)) % n
        };
        let target = &diags[idx];
        // Clamp against the live buffer — servers occasionally publish
        // diagnostics that point past EOF (in-flight edits race against
        // the next `publishDiagnostics`).
        let last_row = self.active_doc().lines.len().saturating_sub(1);
        let row = (target.range.start.line as usize).min(last_row);
        let col = target.range.start.character as usize;
        self.record_jump();
        self.editor.cursor = crate::editor::Cursor { row, col };
        ed_op_ref!(self, clamp_col(false));
        self.run_scroll(ScrollAnchor::Center);
        self.push_toast(Toast::info(target.message.clone()));
    }

    /// Body of `]c` / `[c`. Lands the cursor on the `<<<<<<<` line of the
    /// next / previous conflict, wrapping at
    /// the buffer boundary so repeated presses cycle. Centers the
    /// viewport and toasts the position (`conflict 2/3`) since a marker
    /// far off-screen would otherwise give no sign the jump fired.
    pub(super) fn run_goto_conflict(&mut self, forward: bool, count: u32) {
        let hunks = self.active_doc().conflict_hunks();
        if hunks.is_empty() {
            self.push_toast(Toast::info("no conflict markers in this buffer"));
            return;
        }
        let n = hunks.len();
        let row = self.editor.cursor.row;
        // First hunk strictly past the cursor (forward) or before it
        // (back); wrap to the far end when the cursor is already beyond
        // the last / first one.
        let start = if forward {
            hunks.iter().position(|h| h.start > row).unwrap_or(0)
        } else {
            hunks.iter().rposition(|h| h.start < row).unwrap_or(n - 1)
        };
        let steps = count.max(1) as usize - 1;
        let idx = if forward {
            (start + steps) % n
        } else {
            (start + n - (steps % n)) % n
        };
        let target = hunks[idx].start;
        self.record_jump();
        self.editor.cursor = crate::editor::Cursor {
            row: target,
            col: 0,
        };
        ed_op_ref!(self, clamp_col(false));
        self.run_scroll(ScrollAnchor::Center);
        self.push_toast(Toast::info(format!(
            "conflict {}/{} at line {}",
            idx + 1,
            n,
            target + 1
        )));
    }

    pub(super) fn run_jump_search(&mut self, forward: bool) {
        if let Some(c) = self
            .search
            .find_next(&self.editor, self.active_doc(), forward)
        {
            self.record_jump();
            self.editor.cursor = c;
        } else {
            self.push_toast(Toast::error("pattern not found"));
        }
    }

    /// Body of `gn` / `gN`. Looks up the next match in the requested
    /// direction; in Normal mode, drop the cursor on the match start
    /// and enter Visual (which pins the anchor there); in Visual,
    /// keep the existing anchor and only extend the active end. Either
    /// way, the cursor lands on the match's last char so the selection
    /// covers the whole match. Shared with Visual-mode key handling.
    pub(super) fn run_search_select(&mut self, forward: bool) {
        let Some((start, end_incl)) =
            self.search
                .find_match_range(&self.editor, self.active_doc(), forward)
        else {
            self.push_toast(Toast::error("pattern not found"));
            return;
        };
        if !self.editor.mode.is_visual() {
            self.record_jump();
            self.editor.cursor = start;
            self.enter_mode(crate::mode::Mode::Visual);
        }
        self.editor.cursor = end_incl;
    }

    /// Visual mode's `*` / `#` — extract the word under the cursor,
    /// seed the search state, then jump. The Normal-mode counterpart
    /// goes through `Cmd::SetSearch` + `Cmd::JumpSearch` from
    /// `handle_motion`; visual mode bypasses the Cmd pipeline so this
    /// shim collapses both into one call.
    pub(super) fn search_word_under_cursor(&mut self, forward: bool) {
        let Some(word) = word_under_cursor(&self.editor, self.active_doc()) else {
            self.push_toast(Toast::error("no word under cursor"));
            return;
        };
        self.search.set(word, forward);
        self.run_jump_search(forward);
    }

    pub(super) fn run_scroll(&mut self, anchor: ScrollAnchor) {
        let height = self.active_doc().viewport_height.get();
        if height == 0 {
            // Viewport size isn't known yet (most often: we just thawed
            // a sleeping buffer, which resets `viewport_height` to 0 by
            // design — see `SleepingBuffer::thaw`). Defer to the next
            // draw via `pending_center`; the sticky scroll path in
            // `compute_scroll` reads and clears it.
            if matches!(anchor, ScrollAnchor::Center) {
                self.active_doc().pending_center.set(true);
            }
            return;
        }
        let cur = self.editor.cursor.row;
        let last = self.active_doc().lines.len().saturating_sub(1);
        let scroll = match anchor {
            ScrollAnchor::Top => cur,
            ScrollAnchor::Center => cur.saturating_sub(height / 2),
            ScrollAnchor::Bottom => cur + 1 - height.min(cur + 1),
        };
        let max_scroll = last.saturating_sub(height.saturating_sub(1));
        self.active_doc().scroll.set(scroll.min(max_scroll));
    }

    /// Persist the active buffer to disk and, when `then_quit`, set
    /// `should_quit` only if the write succeeded. A failed save
    /// (no file name, missing parent dir, permission denied, …)
    /// surfaces as a toast and the editor stays open — propagating
    /// the error would tear down the run loop, which is the wrong
    /// response to a fat-fingered path. `force` enables `:w!`
    /// semantics: missing parent directories are created instead of
    /// reported as an error.
    fn run_save(&mut self, path: Option<&Path>, then_quit: bool, force: bool) {
        // Format-on-save runs only for in-place saves (not `:w <path>`):
        // for a save-as, the buffer's current language is ambiguous
        // with respect to the new path, and we'd rather avoid surprising
        // the user by rewriting their text right before changing where
        // it lives. In-place saves go through the formatter step,
        // which is no-op when no formatter is configured and no LSP
        // is attached.
        if path.is_none() && self.active_doc().path.is_some() {
            self.run_format_on_save();
        }

        let target = path
            .map(|p| p.to_path_buf())
            .or_else(|| self.active_doc().path.clone());
        let Some(target) = target else {
            self.push_toast(Toast::error("no file name (use :w <path>)"));
            return;
        };

        // External-edit guard: only for in-place saves where we have a
        // baseline `disk_meta` from load/reload. `:w <path>` deliberately
        // skips this — saving *to* a different file shouldn't be gated
        // on the original file's drift state. `:w!` bypasses too, since
        // forcing a write past a missing parent dir already implies
        // "I know what I'm doing." If the file has since vanished we
        // also refuse (without force) — silently re-creating it would
        // mask an external `rm`.
        if path.is_none()
            && !force
            && let Some(expected) = self.active_doc().disk_meta
        {
            match crate::editor::FileMeta::of(&target) {
                Some(actual) if actual != expected => {
                    self.push_toast(Toast::error(
                        "file changed on disk since open (use :w! or :reload)",
                    ));
                    return;
                }
                None => {
                    self.push_toast(Toast::error("file no longer on disk (use :w! to recreate)"));
                    return;
                }
                _ => {}
            }
        }

        let parent_missing = target
            .parent()
            .map(|p| !p.as_os_str().is_empty() && !p.exists())
            .unwrap_or(false);
        if parent_missing {
            if !force {
                self.push_toast(Toast::error(format!(
                    "no such directory: {} (use :w!)",
                    target.parent().unwrap().display()
                )));
                return;
            }
            if let Err(e) = std::fs::create_dir_all(target.parent().unwrap()) {
                self.push_toast(Toast::error(format!(
                    "mkdir {}: {}",
                    target.parent().unwrap().display(),
                    e
                )));
                return;
            }
        }

        let result = if path.is_some() {
            self.active_doc_mut().save_as(&target)
        } else {
            self.active_doc_mut().save()
        };
        let wrote = match result {
            Ok(()) => {
                let msg = if path.is_some() {
                    format!("written to {}", target.display())
                } else {
                    "written".to_string()
                };
                self.push_toast(Toast::info(msg));
                true
            }
            Err(e) => {
                self.push_toast(Toast::error(format!("save: {}", root_cause(&e))));
                false
            }
        };
        if wrote {
            // Many servers (rust-analyzer in particular) only re-run
            // their full checker on save, so this notify is what makes
            // fresh diagnostics arrive.
            self.run_notify_lsp_save();
            if then_quit {
                self.should_quit = true;
            }
        }
    }

    /// `:wa` / `:wqa` — write every dirty file-backed buffer.
    ///
    /// Three populations get written:
    ///   - The active buffer — formatted on save, exactly like `:w`.
    ///   - Buffers parked in other panes — live in the `documents` pool.
    ///   - Sleeping buffers shown in no pane — thawed, written, re-frozen.
    ///
    /// Unnamed (scratch) buffers can't be written and are counted as
    /// skipped. Without `force` each write is gated by the same pre-write
    /// guards as `:w` — a file that drifted on disk, vanished, or whose
    /// parent directory is missing is left untouched and reported, and
    /// `:wa!` lifts all three. With `then_quit` the editor only exits
    /// when every dirty buffer wrote cleanly — no block, no error, no
    /// unnamed buffer left behind.
    fn run_save_all(&mut self, then_quit: bool, force: bool) {
        use crate::buffer_ref::BufferRef;

        // The pre-write guards `:w` applies, mirrored so `:wa` doesn't
        // silently do what `:w` refuses. A `None` baseline means the
        // buffer was never read from disk (a brand-new file), so only
        // the missing-parent case can block it.
        enum Block {
            /// External tool rewrote the file since we loaded it.
            Drift,
            /// The backing file is gone (or its metadata is unreadable).
            Vanished,
            /// Target's parent directory doesn't exist yet.
            NoDir,
        }
        fn save_block(path: &Path, expected: Option<crate::editor::FileMeta>) -> Option<Block> {
            if let Some(exp) = expected {
                return match crate::editor::FileMeta::of(path) {
                    Some(actual) if actual != exp => Some(Block::Drift),
                    Some(_) => None,
                    None => Some(Block::Vanished),
                };
            }
            let parent_missing = path
                .parent()
                .map(|p| !p.as_os_str().is_empty() && !p.exists())
                .unwrap_or(false);
            parent_missing.then_some(Block::NoDir)
        }
        fn label_of(r: &BufferRef) -> String {
            match r {
                BufferRef::File(p) => p
                    .file_name()
                    .map(|n| n.to_string_lossy().into_owned())
                    .unwrap_or_else(|| p.display().to_string()),
                BufferRef::Scratch(id) => BufferRef::scratch_label(*id),
            }
        }

        // The focused buffer gets format-on-save for parity with `:w`;
        // the rest are written verbatim — reformatting buffers the user
        // isn't looking at would be surprising.
        if self.active_doc().path.is_some() && self.active_doc().dirty {
            self.run_format_on_save();
        }

        let active_ref = self.editor.doc.clone();
        let mut saved = 0usize;
        let mut active_saved = false;
        let mut unnamed = 0usize;
        let mut drifted = 0usize;
        let mut vanished = 0usize;
        let mut no_dir = 0usize;
        let mut errors: Vec<String> = Vec::new();
        let mut tally_block = |b: Block| match b {
            Block::Drift => drifted += 1,
            Block::Vanished => vanished += 1,
            Block::NoDir => no_dir += 1,
        };

        // Live documents: the active buffer plus any parked in panes.
        // One entry per ref, so two panes sharing a document write once.
        let doc_refs: Vec<BufferRef> = self.documents.keys().cloned().collect();
        for r in doc_refs {
            let doc = self.documents.get(&r).expect("ref from keys");
            if !doc.dirty {
                continue;
            }
            let Some(path) = doc.path.clone() else {
                unnamed += 1;
                continue;
            };
            if !force && let Some(b) = save_block(&path, doc.disk_meta) {
                tally_block(b);
                continue;
            }
            match self.documents.get_mut(&r).expect("ref from keys").save() {
                Ok(()) => {
                    saved += 1;
                    active_saved |= r == active_ref;
                }
                Err(e) => errors.push(format!("{}: {}", label_of(&r), root_cause(&e))),
            }
        }

        // Sleeping documents: thaw, write, re-freeze. Thawing
        // decompresses, but `:wa` is rare enough that correctness beats
        // the saved cycles.
        let sleeping_refs: Vec<BufferRef> = self
            .sleeping
            .iter()
            .filter(|(_, s)| s.dirty)
            .map(|(r, _)| r.clone())
            .collect();
        for r in sleeping_refs {
            let sb = self.sleeping.remove(&r).expect("ref from keys");
            if sb.path().is_none() {
                unnamed += 1;
                self.sleeping.insert(r, sb);
                continue;
            }
            let mut buf = sb.thaw();
            let path = buf.path.clone().expect("path present, checked above");
            match (force, save_block(&path, buf.disk_meta)) {
                (false, Some(b)) => tally_block(b),
                _ => match buf.save() {
                    Ok(()) => saved += 1,
                    Err(e) => errors.push(format!("{}: {}", label_of(&r), root_cause(&e))),
                },
            }
            self.sleeping.insert(r, super::SleepingBuffer::freeze(buf));
        }

        // `did_save` only has a live client for the active buffer (the
        // LSP is detached on switch-away), so notify only when the active
        // doc actually wrote — otherwise we'd emit a spurious save for a
        // file that didn't change.
        if active_saved {
            self.run_notify_lsp_save();
        }

        // One summary toast rather than one per buffer.
        let mut parts = Vec::new();
        if saved > 0 {
            parts.push(format!("wrote {saved}"));
        }
        if unnamed > 0 {
            parts.push(format!("{unnamed} unnamed skipped"));
        }
        if drifted > 0 {
            parts.push(format!("{drifted} changed on disk"));
        }
        if vanished > 0 {
            parts.push(format!("{vanished} missing on disk"));
        }
        if no_dir > 0 {
            parts.push(format!("{no_dir} missing parent dir"));
        }
        // Drift / vanished / missing-dir are all liftable with `:wa!`;
        // append the hint once so the message stays readable.
        let forceable = drifted + vanished + no_dir > 0;
        if forceable {
            parts.push("use :wa!".to_string());
        }
        let blocked = forceable || !errors.is_empty() || unnamed > 0;
        if !errors.is_empty() {
            self.push_toast(Toast::error(format!("save all: {}", errors.join("; "))));
        } else if parts.is_empty() {
            self.push_toast(Toast::info("nothing to write"));
        } else if blocked {
            self.push_toast(Toast::error(parts.join(", ")));
        } else {
            self.push_toast(Toast::info(parts.join(", ")));
        }

        if then_quit && !blocked {
            self.should_quit = true;
        }
    }

    /// External formatter > LSP `textDocument/formatting` > no-op.
    /// Errors surface as toasts but never abort the save: the user
    /// asked to save and we'd rather write the un-formatted bytes
    /// than refuse the action. Format failures during save (e.g.
    /// rustfmt rejecting a syntax error) are common enough that
    /// blocking the save would be hostile.
    fn run_format_on_save(&mut self) {
        let eff = self.effective_editor();
        if !eff.format_on_save {
            return;
        }
        let formatter = self
            .active_doc()
            .path
            .as_deref()
            .and_then(|p| self.config.languages.by_path(p))
            .and_then(|lang| lang.formatter.clone());

        // A configured formatter wins when present: it's the user's
        // explicit choice, and the LSP would typically just shell out
        // to the same tool anyway (gopls → gofmt, rust-analyzer →
        // rustfmt).
        match formatter {
            Some(crate::config::Formatter::Command(fmt)) => {
                let cwd = self
                    .active_doc()
                    .path
                    .as_ref()
                    .and_then(|p| p.parent())
                    .map(|p| p.to_path_buf())
                    .unwrap_or_else(|| self.lsp.startup_cwd().to_path_buf());
                let text = self.active_doc().lines.join("\n");
                match crate::format::run_external(&fmt, &text, &cwd) {
                    Ok(formatted) => self.apply_formatted_text(formatted),
                    Err(e) => {
                        self.push_toast(Toast::fatal(format!(
                            "format `{}`: {}",
                            fmt.command,
                            root_cause(&e)
                        )));
                    }
                }
            }
            // Format via the named LSP servers in priority order. An
            // `Ok(None)` means none of the configured servers matched an
            // attached client — a typo in the name, or a server that
            // isn't in this language's `lsp` list (so it never attaches)
            // / hasn't finished starting up. Surface a toast rather than
            // silently skipping the format, since "save does nothing" is
            // otherwise impossible to diagnose.
            Some(crate::config::Formatter::Lsp(servers)) => {
                let options = self.formatting_options();
                match self
                    .lsp
                    .format_with_servers(&servers, options, LSP_FORMAT_TIMEOUT)
                {
                    Ok(Some(edits)) if !edits.is_empty() => self.apply_format_edits(edits),
                    Ok(Some(_)) => {}
                    Ok(None) => {
                        self.push_toast(Toast::warn(format!(
                            "format: no configured formatter LSP attached ({})",
                            servers.join(", ")
                        )));
                    }
                    Err(e) => {
                        self.push_toast(Toast::fatal(format!("lsp format: {}", root_cause(&e))));
                    }
                }
            }
            // Fall through to LSP. `format_first_client` returns Ok(None)
            // when no client is attached — quietly do nothing in that
            // case so saves on plain-text buffers don't surface noise.
            None => {
                let options = self.formatting_options();
                match self.lsp.format_first_client(options, LSP_FORMAT_TIMEOUT) {
                    Ok(Some(edits)) if !edits.is_empty() => self.apply_format_edits(edits),
                    Ok(_) => {}
                    Err(e) => {
                        self.push_toast(Toast::fatal(format!("lsp format: {}", root_cause(&e))));
                    }
                }
            }
        }
    }

    /// Replace the buffer's text wholesale with the external
    /// formatter's stdout. Snapshots first so undo lands on the
    /// pre-format state. Cursor is clamped — the formatter typically
    /// only adds/removes whitespace so the row is usually still valid,
    /// but a wholesale rewrite is allowed to break that.
    fn apply_formatted_text(&mut self, formatted: String) {
        let new_lines: Vec<String> = formatted.split('\n').map(|s| s.to_string()).collect();
        let new_lines = if new_lines.is_empty() {
            vec![String::new()]
        } else {
            // External formatters typically end output with a trailing
            // newline, which `split('\n')` turns into a stray empty
            // last element. Drop it so the buffer doesn't grow an
            // extra blank line on every save.
            let mut v = new_lines;
            if v.len() > 1 && v.last().map(|s| s.is_empty()).unwrap_or(false) {
                v.pop();
            }
            v
        };
        if new_lines == self.active_doc().lines {
            return;
        }
        ed_op!(self, snapshot());
        let doc = self.active_doc_mut();
        doc.lines = new_lines;
        doc.bump_version();
        doc.dirty = true;
        self.clamp_cursor_to_buffer();
    }

    /// Apply a list of LSP `TextEdit`s to the buffer. Snapshots first
    /// so undo lands on the pre-format state; bumps the version so
    /// the highlighter re-runs against the rewritten text.
    fn apply_format_edits(&mut self, edits: Vec<lsp::TextEdit>) {
        ed_op!(self, snapshot());
        let doc = self.active_doc_mut();
        let mut lines = std::mem::take(&mut doc.lines);
        lsp::apply_text_edits(&mut lines, edits);
        if lines.is_empty() {
            lines.push(String::new());
        }
        let doc = self.active_doc_mut();
        doc.lines = lines;
        doc.bump_version();
        doc.dirty = true;
        self.clamp_cursor_to_buffer();
    }

    /// Pin the cursor inside the (possibly shrunken) buffer after a
    /// format rewrite. Conservative: just clamps row/col without
    /// trying to track the cursor's logical position through the
    /// edit — formatters mostly preserve structure, and the user
    /// can scroll back if the cursor lands somewhere unexpected.
    fn clamp_cursor_to_buffer(&mut self) {
        let last_row = self.active_doc().lines.len().saturating_sub(1);
        if self.editor.cursor.row > last_row {
            self.editor.cursor.row = last_row;
        }
        let row_len = self
            .active_doc()
            .lines
            .get(self.editor.cursor.row)
            .map(|s| s.chars().count())
            .unwrap_or(0);
        if self.editor.cursor.col > row_len {
            self.editor.cursor.col = row_len;
        }
    }

    /// LSP `FormattingOptions` derived from the buffer's effective
    /// editor settings. Servers honour these to pick tab vs. space
    /// (gopls in particular needs `insertSpaces: false`).
    fn formatting_options(&self) -> serde_json::Value {
        let eff = self.effective_editor();
        serde_json::json!({
            "tabSize": eff.indent_width,
            "insertSpaces": !eff.use_tabs,
            "trimTrailingWhitespace": true,
            "insertFinalNewline": true,
            "trimFinalNewlines": true,
        })
    }

    /// `:reload` — re-read the active buffer's backing file from
    /// disk. Always reloads: `reload_from_disk` takes an undo
    /// snapshot before the content is replaced, so unsaved edits
    /// are recoverable with `u`. The version bump triggers the
    /// normal `didChange` sync so the LSP picks up the new content
    /// on the next tick.
    fn run_reload(&mut self) {
        let Some(path) = self.active_doc().path.clone() else {
            self.push_toast(Toast::error("no file name"));
            return;
        };
        match ed_op!(self, reload_from_disk()) {
            Ok(true) => self.push_toast(Toast::info(format!("reloaded {}", path.display()))),
            Ok(false) => self.push_toast(Toast::info("reloaded (no change)")),
            Err(e) => self.push_toast(Toast::error(format!("reload: {}", root_cause(&e)))),
        }
    }

    /// `:reload-all` — re-read every file-backed buffer.
    ///
    /// - Active and parked buffers always reload: `reload_from_disk`
    ///   snapshots first, so unsaved edits are recoverable via `u`
    ///   in each pane.
    /// - Clean sleeping entries are dropped so the next visit
    ///   triggers a fresh load; cheaper than thawing them just to
    ///   reload them back.
    /// - Dirty sleeping entries are left alone — their unsaved
    ///   edits live only inside the frozen snapshot, with no
    ///   undo stack reachable from the active pane, so dropping
    ///   would be unrecoverable data loss. They surface unchanged
    ///   on the next visit.
    fn run_reload_all(&mut self) {
        let mut reloaded = 0usize;
        let mut unchanged = 0usize;
        let mut errors: Vec<String> = Vec::new();

        if self.active_doc().path.is_some() {
            match ed_op!(self, reload_from_disk()) {
                Ok(true) => reloaded += 1,
                Ok(false) => unchanged += 1,
                Err(e) => errors.push(format!("active: {}", root_cause(&e))),
            }
        }

        // Inactive panes' sessions, each resolving its own document.
        // Two panes sharing one document reload it twice — the second
        // pass sees disk == buffer and reports "unchanged", so it's a
        // harmless no-op (no double snapshot).
        let inactive_panes: Vec<crate::app::PaneId> = self
            .pane_content
            .iter()
            .filter_map(|(id, c)| match c {
                crate::app::PaneContent::Editor(_) => Some(*id),
                crate::app::PaneContent::Agent => None,
            })
            .collect();
        for pane in inactive_panes {
            let doc_ref = match self.pane_content.get(&pane) {
                Some(crate::app::PaneContent::Editor(ed)) => ed.doc.clone(),
                _ => continue,
            };
            let has_path = self
                .documents
                .get(&doc_ref)
                .map(|d| d.path.is_some())
                .unwrap_or(false);
            if !has_path {
                continue;
            }
            // Disjoint fields: the pane's editor and its pooled document.
            let Some(crate::app::PaneContent::Editor(mut ed)) = self.pane_content.remove(&pane)
            else {
                continue;
            };
            let result = {
                let doc = self
                    .documents
                    .get_mut(&doc_ref)
                    .expect("pane doc present in pool");
                ed.reload_from_disk(doc)
            };
            self.pane_content
                .insert(pane, crate::app::PaneContent::Editor(ed));
            match result {
                Ok(true) => reloaded += 1,
                Ok(false) => unchanged += 1,
                Err(e) => {
                    let label = match &doc_ref {
                        crate::buffer_ref::BufferRef::File(p) => p.display().to_string(),
                        crate::buffer_ref::BufferRef::Scratch(id) => {
                            crate::buffer_ref::BufferRef::scratch_label(*id)
                        }
                    };
                    errors.push(format!("{label}: {}", root_cause(&e)));
                }
            }
        }

        let clean_keys: Vec<_> = self
            .sleeping
            .iter()
            .filter_map(|(k, s)| match k {
                crate::buffer_ref::BufferRef::File(_) if !s.dirty => Some(k.clone()),
                _ => None,
            })
            .collect();
        let preserved_dirty = self
            .sleeping
            .iter()
            .filter(|(k, s)| matches!(k, crate::buffer_ref::BufferRef::File(_)) && s.dirty)
            .count();
        for k in &clean_keys {
            self.sleeping.remove(k);
            reloaded += 1;
        }

        let mut parts = Vec::new();
        if reloaded > 0 {
            parts.push(format!("reloaded {reloaded}"));
        }
        if unchanged > 0 {
            parts.push(format!("{unchanged} unchanged"));
        }
        if preserved_dirty > 0 {
            parts.push(format!("{preserved_dirty} dirty kept"));
        }
        if parts.is_empty() && errors.is_empty() {
            self.push_toast(Toast::info("no file-backed buffers"));
        } else if errors.is_empty() {
            self.push_toast(Toast::info(parts.join(", ")));
        } else {
            let summary = if parts.is_empty() {
                String::from("reload-all failed")
            } else {
                parts.join(", ")
            };
            self.push_toast(Toast::error(format!(
                "{summary}; errors: {}",
                errors.join("; ")
            )));
        }
    }

    /// `:config-reload` — re-read the user config file and re-apply the
    /// settings that can change at runtime.
    ///
    /// Resolves the path exactly as startup does ([`crate::config::default_path`]),
    /// so a workspace-local `.vorto` still wins. On a load/parse error the
    /// current config is left untouched and the error surfaces as a toast,
    /// matching the "bad config never breaks a running editor" stance.
    ///
    /// What takes effect immediately: keymap, cursor shapes, `[editor]` /
    /// `[finder]` options, the agent catalog, the grammar recipe catalog,
    /// and the active theme. What does *not*: already running LSP servers
    /// and the syntax/preview workers, which captured their slice of the
    /// config at startup and need a restart to pick up changes — the
    /// success toast says as much so a "why didn't it change" is answered
    /// up front. A theme that fails to load is a partial success: the rest
    /// of the config is applied and the toast drops to warn, not error
    /// (a real load/parse failure already errors out above without
    /// touching the running config).
    fn run_config_reload(&mut self) {
        let path = crate::config::default_path();
        let new_config = match crate::config::Config::load(path.as_deref()) {
            Ok(c) => c,
            Err(e) => {
                self.push_toast(Toast::error(format!("config: {}", root_cause(&e))));
                return;
            }
        };

        // Rebuild the merged grammar recipe catalog from the new sources,
        // mirroring `App::new`.
        self.grammar_recipes = crate::grammar::cli::merged_recipes(&new_config.grammars);

        // Re-apply the theme. A bad name is non-fatal — keep whatever's
        // active and note it, so a typo doesn't blank the screen.
        let theme_warning = match crate::theme::load_by_name(&new_config.theme) {
            Ok(t) => {
                crate::theme::set_active(t);
                None
            }
            Err(e) => Some(format!("theme `{}`: {}", new_config.theme, root_cause(&e))),
        };

        self.config = new_config;

        let where_from = path
            .as_deref()
            .map(|p| p.display().to_string())
            .unwrap_or_else(|| "<defaults>".into());
        // Hint that the live-reloadable settings are in effect but the
        // process-bound subsystems aren't — see the doc comment.
        const RESTART_HINT: &str = "restart for lsp/grammar/syntax";
        match theme_warning {
            Some(w) => self.push_toast(Toast::warn(format!(
                "config reloaded ({where_from}); {w}; {RESTART_HINT}"
            ))),
            None => self.push_toast(Toast::info(format!(
                "config reloaded ({where_from}); {RESTART_HINT}"
            ))),
        }
    }

    fn run_notify_lsp_save(&mut self) {
        let text = self.active_doc().lines.join("\n");
        if let Err(e) = self.lsp.did_save(&text) {
            self.push_toast(Toast::error(format!("lsp didSave: {}", root_cause(&e))));
        }
    }
}

#[cfg(test)]
mod save_all_tests {
    use super::*;
    use crate::buffer_ref::BufferRef;
    use crate::editor::{Buffer, FileMeta};
    use std::fs;

    fn test_app() -> App {
        let config = crate::config::Config::load(None).expect("default config loads");
        let loader =
            crate::syntax::Loader::new(std::path::PathBuf::new(), std::path::PathBuf::new());
        let (tx, _rx) = std::sync::mpsc::channel();
        let cwd = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
        App::new(config, loader, tx, cwd)
    }

    /// Unique scratch dir under the system temp, namespaced by pid + tag
    /// so parallel test runs don't collide.
    fn temp_dir(tag: &str) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!("vorto-wa-{}-{tag}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    /// A file-backed buffer holding `text` with the dirty bit raised over
    /// an up-to-date `disk_meta` baseline — i.e. unsaved edits that the
    /// external-edit guard will consider drift-free.
    fn dirty_doc(path: &std::path::Path, text: &str) -> Buffer {
        let mut b = Buffer::new();
        b.lines = text.split('\n').map(|s| s.to_string()).collect();
        b.path = Some(path.to_path_buf());
        b.dirty = true;
        b.disk_meta = FileMeta::of(path);
        b
    }

    #[test]
    fn save_all_writes_active_and_sleeping_buffers() {
        let dir = temp_dir("multi");
        let active = dir.join("active.txt");
        let sleeping = dir.join("sleeping.txt");
        fs::write(&active, "old active\n").unwrap();
        fs::write(&sleeping, "old sleeping\n").unwrap();

        let mut app = test_app();

        // Active buffer: edited in memory, stale on disk.
        let active_ref = BufferRef::File(active.clone());
        app.documents
            .insert(active_ref.clone(), dirty_doc(&active, "new active"));
        app.editor.doc = active_ref.clone();

        // A buffer the user switched away from: frozen in `sleeping`.
        let sleeping_ref = BufferRef::File(sleeping.clone());
        app.sleeping.insert(
            sleeping_ref.clone(),
            crate::app::SleepingBuffer::freeze(dirty_doc(&sleeping, "new sleeping")),
        );

        app.run_save_all(false, false);

        // Both the focused buffer and the one shown in no pane hit disk.
        assert_eq!(fs::read_to_string(&active).unwrap(), "new active");
        assert_eq!(fs::read_to_string(&sleeping).unwrap(), "new sleeping");
        assert!(!app.documents.get(&active_ref).unwrap().dirty);
        assert!(!app.sleeping.get(&sleeping_ref).unwrap().dirty);

        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn save_all_refuses_disk_drift_until_forced() {
        let dir = temp_dir("drift");
        let file = dir.join("drift.txt");
        fs::write(&file, "orig").unwrap();

        let mut app = test_app();
        let r = BufferRef::File(file.clone());
        app.documents
            .insert(r.clone(), dirty_doc(&file, "edited in editor"));

        // Another tool rewrites the file out from under us; the differing
        // length is enough for the FileMeta baseline to register drift.
        fs::write(&file, "EXTERNALLY CHANGED ON DISK").unwrap();

        // Plain `:wa` leaves the drifted file alone and keeps the buffer
        // dirty so the edits aren't lost.
        app.run_save_all(false, false);
        assert_eq!(
            fs::read_to_string(&file).unwrap(),
            "EXTERNALLY CHANGED ON DISK"
        );
        assert!(app.documents.get(&r).unwrap().dirty);

        // `:wa!` overwrites.
        app.run_save_all(false, true);
        assert_eq!(fs::read_to_string(&file).unwrap(), "edited in editor");
        assert!(!app.documents.get(&r).unwrap().dirty);

        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn save_all_refuses_missing_parent_dir_until_forced() {
        let dir = temp_dir("nodir");
        // `newsub` does not exist; a brand-new buffer (no disk baseline)
        // points into it, mirroring `:e a/newsub/new.txt`.
        let target = dir.join("newsub").join("new.txt");

        let mut app = test_app();
        let r = BufferRef::File(target.clone());
        let mut buf = Buffer::new();
        buf.lines = vec!["fresh".to_string()];
        buf.path = Some(target.clone());
        buf.dirty = true;
        app.documents.insert(r.clone(), buf);

        // Plain `:wa` refuses rather than silently creating the dir —
        // matching `:w`'s "no such directory" guard.
        app.run_save_all(false, false);
        assert!(!target.exists());
        assert!(app.documents.get(&r).unwrap().dirty);

        // `:wa!` creates the missing parent and writes.
        app.run_save_all(false, true);
        assert_eq!(fs::read_to_string(&target).unwrap(), "fresh");
        assert!(!app.documents.get(&r).unwrap().dirty);

        fs::remove_dir_all(&dir).ok();
    }
}