sucher 0.6.1

A fast terminal viewer for files that are awkward in a browser: markdown, spreadsheets, PDF, images, video, docx, pptx, Keynote, archives and binary.
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
// sucher — a fast terminal viewer for files that are awkward in a browser:
// markdown, source/plain text, spreadsheets (incl. csv/tsv), PDF, images, video,
// docx, pptx, Keynote, archives, binary (hex), and directories. One command
// dispatches by a single classification registry (`format.rs`) to a per-type
// viewer.
//
// Interactive TUI when stdout is a tty; falls back to a one-shot text dump when
// piped or with --plain (markdown can use the kitty text-sizing protocol for
// big headings). The few still-unopenable files (legacy .doc/.ppt binaries,
// audio) print a metadata line rather than being force-rendered.

mod anim;
mod archive;
mod config;
#[cfg(feature = "data")]
mod data;
mod dir;
mod docx;
mod epub;
mod fileop;
mod format;
mod git;
mod hex;
mod highlight;
mod html;
mod icons;
mod imgview;
mod ipynb;
mod keynote;
mod lineedit;
mod markdown;
mod marks;
mod media;
mod pdf;
mod pdfium;
mod plain;
mod pptx;
mod query;
mod search;
mod sheet;
mod svg;
mod text;
mod theme;
mod tui;
mod typeahead;
mod util;
mod video;
mod xlsx;

use format::Format;
use std::io::{self, IsTerminal};
use std::path::Path;
use std::process::ExitCode;
use std::{env, fs};

fn main() -> ExitCode {
    let code = run();
    // Flush the animation frame-stats (opt-in via `SUCHER_ANIM_STATS`) only now,
    // after every viewer has restored the terminal — printing to stderr while the
    // alternate screen was live would corrupt the TUI (ADR 0006). A no-op when
    // the env var is unset, so a normal run stays byte-for-byte silent.
    anim::dump_stats();
    code
}

fn run() -> ExitCode {
    let mut plain_flag = false;
    let mut path: Option<String> = None;
    // Theme/icons overrides from the command line (highest precedence — see
    // `config::load`). Both flags take the following argument.
    let mut cli_theme: Option<String> = None;
    let mut cli_icons: Option<String> = None;
    let mut cli_layout: Option<String> = None;
    // `--no-git` forces the git gutter off, overriding env/file/default.
    let mut cli_no_git = false;
    // `--no-mouse` forces mouse capture off, overriding env/file/default.
    let mut cli_no_mouse = false;
    // `--no-animate` forces navigation animations off, overriding env/file/default.
    let mut cli_no_animate = false;
    let mut args = env::args().skip(1);
    while let Some(arg) = args.next() {
        match arg.as_str() {
            "--plain" | "-p" => plain_flag = true,
            "--theme" => cli_theme = args.next(),
            "--icons" => cli_icons = args.next(),
            "--layout" => cli_layout = args.next(),
            "--no-git" => cli_no_git = true,
            "--no-mouse" => cli_no_mouse = true,
            "--no-animate" => cli_no_animate = true,
            "-h" | "--help" => {
                eprintln!(
                    "usage: sucher [--plain] [--theme NAME] [--icons unicode|nerd|none] [--layout auto|miller|double] [--no-git] [--no-mouse] [--no-animate] [file|dir]"
                );
                return ExitCode::SUCCESS;
            }
            _ => path = Some(arg),
        }
    }

    // Resolve the palette (flag > env > file > default) and install it before
    // any viewer draws. Auto light/dark detection runs here, before the
    // alternate screen. `icons` threads through to the browser for a later phase.
    let cli_git = if cli_no_git { Some(false) } else { None };
    let cli_mouse = if cli_no_mouse { Some(false) } else { None };
    let cli_animate = if cli_no_animate { Some(false) } else { None };
    let config = config::load(
        cli_theme,
        cli_icons,
        cli_layout,
        cli_git,
        cli_mouse,
        cli_animate,
    );
    theme::init(config.palette);
    // Install the navigation-animation toggle beside the palette so any viewer —
    // including the config-less in-process `imgview` — can gate on `anim::enabled()`.
    anim::set_enabled(config.animate);

    // No argument browses the current directory.
    let path = path.unwrap_or_else(|| ".".to_string());

    let interactive = !plain_flag && io::stdout().is_terminal();
    let title = file_title(&path);

    match format::classify_path(Path::new(&path)) {
        // Directories open the file browser (or a plain listing when piped).
        Format::Directory => {
            if interactive {
                if let Err(e) =
                    dir::run(path, config.icons, config.layout, config.git, config.mouse)
                {
                    eprintln!("sucher: {e}");
                    return ExitCode::FAILURE;
                }
            } else {
                return emit(&dir::dump(&path));
            }
        }
        Format::Image => {
            if interactive {
                if let Err(e) = imgview::run(title, path.clone()) {
                    eprintln!("sucher: {e}");
                    return ExitCode::FAILURE;
                }
            } else {
                match crate::util::image_dimensions(std::path::Path::new(&path)) {
                    Ok((w, h)) => return emit(&format!("{path}: image {w}×{h}px\n")),
                    Err(e) => {
                        eprintln!("sucher: {path}: {e}");
                        return ExitCode::FAILURE;
                    }
                }
            }
        }
        // Data files (ADR 0016) reduce to the same grid viewer as spreadsheets;
        // `Format::Data` is only ever produced when the `data` feature is on.
        Format::Sheet | Format::Data => {
            if interactive {
                if let Err(e) = sheet::run(title, path.clone()) {
                    eprintln!("sucher: {e}");
                    return ExitCode::FAILURE;
                }
            } else {
                return emit(&sheet::dump(&path));
            }
        }
        Format::Svg => {
            if interactive {
                if let Err(e) = svg::run(title, path.clone()) {
                    eprintln!("sucher: {e}");
                    return ExitCode::FAILURE;
                }
            } else {
                // Piped: SVG is XML source — dump it faithfully like any text.
                return emit(&text::dump(&path));
            }
        }
        Format::Pdf => {
            if interactive {
                if let Err(e) = pdf::run(title, path.clone()) {
                    eprintln!("sucher: {e}");
                    return ExitCode::FAILURE;
                }
            } else {
                return emit(&pdf::dump(&path));
            }
        }
        Format::Video => {
            if interactive {
                if let Err(e) = video::run(title, path.clone()) {
                    eprintln!("sucher: {e}");
                    return ExitCode::FAILURE;
                }
            } else {
                return emit(&video::dump(&path));
            }
        }
        Format::Docx => {
            let src = match docx::to_markdown(&path) {
                Ok(s) => s,
                Err(e) => {
                    eprintln!("sucher: {path}: {e}");
                    return ExitCode::FAILURE;
                }
            };
            let images = if interactive {
                docx::media(&path)
            } else {
                Vec::new()
            };
            return render_markdown(interactive, title, src, images, Some(path.clone()));
        }
        Format::Pptx => {
            let src = match pptx::to_markdown(&path) {
                Ok(s) => s,
                Err(e) => {
                    eprintln!("sucher: {path}: {e}");
                    return ExitCode::FAILURE;
                }
            };
            let images = if interactive {
                pptx::media(&path)
            } else {
                Vec::new()
            };
            return render_markdown(interactive, title, src, images, Some(path.clone()));
        }
        Format::Epub => {
            let src = match epub::to_markdown(&path) {
                Ok(s) => s,
                Err(e) => {
                    eprintln!("sucher: {path}: {e}");
                    return ExitCode::FAILURE;
                }
            };
            let images = if interactive {
                epub::media(&path)
            } else {
                Vec::new()
            };
            return render_markdown(interactive, title, src, images, Some(path.clone()));
        }
        Format::Ipynb => {
            let src = match ipynb::to_markdown(&path) {
                Ok(s) => s,
                Err(e) => {
                    eprintln!("sucher: {path}: {e}");
                    return ExitCode::FAILURE;
                }
            };
            let images = if interactive {
                ipynb::media(&path)
            } else {
                Vec::new()
            };
            return render_markdown(interactive, title, src, images, Some(path.clone()));
        }
        Format::Keynote => {
            if interactive {
                if let Err(e) = keynote::run(title, path.clone()) {
                    eprintln!("sucher: {e}");
                    return ExitCode::FAILURE;
                }
            } else {
                return emit(&format!("{path}: Keynote presentation\n"));
            }
        }
        Format::Archive => {
            if interactive {
                if let Err(e) = archive::run(title, path.clone()) {
                    eprintln!("sucher: {e}");
                    return ExitCode::FAILURE;
                }
            } else {
                return emit(&archive::dump(&path));
            }
        }
        Format::Binary => {
            if interactive {
                if let Err(e) = hex::run(title, path.clone()) {
                    eprintln!("sucher: {e}");
                    return ExitCode::FAILURE;
                }
            } else {
                return emit(&hex::dump(&path));
            }
        }
        Format::Text => {
            if interactive {
                if let Err(e) = text::run(title, path.clone()) {
                    eprintln!("sucher: {e}");
                    return ExitCode::FAILURE;
                }
            } else {
                return emit(&text::dump(&path));
            }
        }
        Format::Markdown => {
            let src = match fs::read_to_string(&path) {
                Ok(s) => s,
                Err(e) => {
                    eprintln!("sucher: {path}: {e}");
                    return ExitCode::FAILURE;
                }
            };
            return render_markdown(interactive, title, src, Vec::new(), Some(path.clone()));
        }
        // HTML is reduced to markdown (ADR 0008) and rendered like docx/pptx.
        Format::Html => {
            let src = match html::to_markdown(&path) {
                Ok(s) => s,
                Err(e) => {
                    eprintln!("sucher: {path}: {e}");
                    return ExitCode::FAILURE;
                }
            };
            return render_markdown(interactive, title, src, Vec::new(), Some(path.clone()));
        }
        // Recognized but still unopenable (legacy office binaries, audio): show
        // a metadata line, never feed the bytes to a renderer.
        f @ (Format::Doc | Format::Audio) => {
            return unsupported(&path, f, interactive);
        }
    }
    ExitCode::SUCCESS
}

/// A recognized-but-unopenable file: print a concise, honest "no viewer" notice
/// with one metadata line (size + modified). Interactive callers get the notice
/// on stderr; piped callers get just the metadata line on stdout so it composes.
/// Lacking a viewer is not an error, so this returns SUCCESS.
fn unsupported(path: &str, format: Format, interactive: bool) -> ExitCode {
    let name = file_title(path);
    let meta = metadata_line(path);
    if interactive {
        eprintln!("sucher: no viewer for {} ({name})", format.label());
        eprintln!("  {meta}");
        ExitCode::SUCCESS
    } else {
        emit(&format!("{meta}\n"))
    }
}

/// Write a one-shot dump to stdout for piped/non-TTY output. A closed downstream
/// pipe (`v big.md | head`) is a normal, clean exit — treat `BrokenPipe` as
/// success rather than letting the `print!` macro panic on it. The buffer is
/// flushed here so there is no late broken-pipe panic during process teardown.
fn emit(s: &str) -> ExitCode {
    use std::io::Write;
    let mut out = io::stdout();
    match out.write_all(s.as_bytes()).and_then(|()| out.flush()) {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) if e.kind() == io::ErrorKind::BrokenPipe => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("sucher: {e}");
            ExitCode::FAILURE
        }
    }
}

/// One-line "size · modified" summary for a path, human-formatted.
fn metadata_line(path: &str) -> String {
    match fs::metadata(path) {
        Ok(m) => {
            let mut s = util::human_size(m.len());
            if let Ok(t) = m.modified() {
                s.push_str(&format!("  ·  {}", util::rel_time(t)));
            }
            s
        }
        Err(e) => format!("({e})"),
    }
}

fn render_markdown(
    interactive: bool,
    title: String,
    src: String,
    images: Vec<std::path::PathBuf>,
    open: Option<String>,
) -> ExitCode {
    if interactive {
        if let Err(e) = tui::run(title, src, images, open) {
            eprintln!("sucher: {e}");
            return ExitCode::FAILURE;
        }
    } else {
        return emit(&plain::render(&src));
    }
    ExitCode::SUCCESS
}

/// File name used as a viewer title.
fn file_title(path: &str) -> String {
    Path::new(path)
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| path.to_string())
}

/// Open a path in its interactive viewer. Used by the directory browser, which
/// has already torn down its own terminal; each viewer sets up and restores its
/// own. Errors are printed but never abort the caller.
pub fn open_interactive(path: &str) {
    let title = file_title(path);
    let format = format::classify_path(Path::new(path));
    let r = match format {
        Format::Image => imgview::run(title, path.to_string()),
        Format::Svg => svg::run(title, path.to_string()),
        Format::Sheet | Format::Data => sheet::run(title, path.to_string()),
        Format::Pdf => pdf::run(title, path.to_string()),
        Format::Video => video::run(title, path.to_string()),
        Format::Text => text::run(title, path.to_string()),
        Format::Docx => match docx::to_markdown(path) {
            Ok(src) => tui::run(title, src, docx::media(path), Some(path.to_string())),
            Err(e) => {
                eprintln!("sucher: {path}: {e}");
                Ok(())
            }
        },
        Format::Pptx => match pptx::to_markdown(path) {
            Ok(src) => tui::run(title, src, pptx::media(path), Some(path.to_string())),
            Err(e) => {
                eprintln!("sucher: {path}: {e}");
                Ok(())
            }
        },
        Format::Epub => match epub::to_markdown(path) {
            Ok(src) => tui::run(title, src, epub::media(path), Some(path.to_string())),
            Err(e) => {
                eprintln!("sucher: {path}: {e}");
                Ok(())
            }
        },
        Format::Ipynb => match ipynb::to_markdown(path) {
            Ok(src) => tui::run(title, src, ipynb::media(path), Some(path.to_string())),
            Err(e) => {
                eprintln!("sucher: {path}: {e}");
                Ok(())
            }
        },
        Format::Keynote => keynote::run(title, path.to_string()),
        Format::Archive => archive::run(title, path.to_string()),
        Format::Binary => hex::run(title, path.to_string()),
        Format::Markdown => match fs::read_to_string(path) {
            Ok(src) => tui::run(title, src, Vec::new(), Some(path.to_string())),
            Err(e) => {
                eprintln!("sucher: {path}: {e}");
                Ok(())
            }
        },
        Format::Html => match html::to_markdown(path) {
            Ok(src) => tui::run(title, src, Vec::new(), Some(path.to_string())),
            Err(e) => {
                eprintln!("sucher: {path}: {e}");
                Ok(())
            }
        },
        // Directories don't reach here (the browser enters them itself); the
        // remaining variants have no viewer. The browser gates these before
        // calling, but stay honest if reached directly.
        Format::Directory | Format::Doc | Format::Audio => {
            eprintln!("sucher: no viewer for {} ({title})", format.label());
            Ok(())
        }
    };
    if let Err(e) = r {
        eprintln!("sucher: {e}");
    }
}