leaf-markdown-viewer 1.28.1

Terminal Markdown previewer with a GUI-like experience
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
use std::path::PathBuf;

use anyhow::{bail, Context, Result};

use crate::cli::{AutoCompleteArg, AutoCompleteMode};

const PS1_COMPLETION: &str = include_str!("../completions/leaf.ps1");
const ZSH_COMPLETION: &str = include_str!("../completions/leaf.zsh");
const BASH_COMPLETION: &str = include_str!("../completions/leaf.bash");
const FISH_COMPLETION: &str = include_str!("../completions/leaf.fish");
const NU_COMPLETION: &str = include_str!("../completions/leaf.nu");

enum Shell {
    Pwsh,
    Zsh,
    Bash,
    Fish,
    Nushell,
}

impl Shell {
    fn name(&self) -> &'static str {
        match self {
            Shell::Bash => "bash",
            Shell::Zsh => "zsh",
            Shell::Fish => "fish",
            Shell::Pwsh => "powershell",
            Shell::Nushell => "nushell",
        }
    }
}

fn completion_filename(shell: &Shell) -> &'static str {
    match shell {
        Shell::Bash => "leaf.bash",
        Shell::Zsh => "_leaf",
        Shell::Fish => "leaf.fish",
        Shell::Pwsh => "leaf.ps1",
        Shell::Nushell => "leaf.nu",
    }
}

fn source_line_for(shell: &Shell, path: &std::path::Path) -> Option<String> {
    match shell {
        Shell::Bash | Shell::Zsh => Some(format!("source {}", path.display())),
        Shell::Pwsh => Some(format!(". {}", path.display())),
        Shell::Fish | Shell::Nushell => None,
    }
}

fn detect_shell() -> Result<Shell> {
    if let Ok(shell) = std::env::var("SHELL") {
        let basename = std::path::Path::new(&shell)
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("");
        match basename {
            "zsh" => return Ok(Shell::Zsh),
            "bash" => return Ok(Shell::Bash),
            "fish" => return Ok(Shell::Fish),
            "nu" => return Ok(Shell::Nushell),
            _ => {}
        }
    }

    #[cfg(target_os = "windows")]
    return Ok(Shell::Pwsh);

    #[cfg(not(target_os = "windows"))]
    {
        for (path, shell) in [
            ("/bin/zsh", Shell::Zsh),
            ("/bin/bash", Shell::Bash),
            ("/bin/fish", Shell::Fish),
            ("/bin/nu", Shell::Nushell),
            ("/usr/bin/nu", Shell::Nushell),
        ] {
            if std::path::Path::new(path).exists() {
                return Ok(shell);
            }
        }
        bail!("Cannot detect shell. Set $SHELL to bash, zsh, fish, or nu")
    }
}

fn completion_dir() -> Result<PathBuf> {
    #[cfg(target_os = "windows")]
    {
        let base = std::env::var("APPDATA").context("Cannot determine APPDATA directory")?;
        Ok(PathBuf::from(base).join("leaf").join("completions"))
    }
    #[cfg(not(target_os = "windows"))]
    {
        let home = std::env::var("HOME").context("Cannot determine HOME directory")?;
        Ok(PathBuf::from(home)
            .join(".local")
            .join("share")
            .join("leaf")
            .join("completions"))
    }
}

fn fish_completion_dir() -> Result<PathBuf> {
    let home = std::env::var("HOME").context("Cannot determine HOME directory")?;
    Ok(PathBuf::from(home)
        .join(".config")
        .join("fish")
        .join("completions"))
}

fn nushell_completion_dir() -> Result<PathBuf> {
    #[cfg(target_os = "windows")]
    {
        let base = std::env::var("APPDATA").context("Cannot determine APPDATA directory")?;
        Ok(PathBuf::from(base).join("nushell").join("autoload"))
    }
    #[cfg(not(target_os = "windows"))]
    {
        let home = std::env::var("HOME").context("Cannot determine HOME directory")?;
        Ok(PathBuf::from(home)
            .join(".config")
            .join("nushell")
            .join("autoload"))
    }
}

fn write_completion(dir: &std::path::Path, filename: &str, content: &str) -> Result<PathBuf> {
    std::fs::create_dir_all(dir)
        .with_context(|| format!("Cannot create directory: {}", dir.display()))?;
    let path = dir.join(filename);
    std::fs::write(&path, content)
        .with_context(|| format!("Cannot write completion file: {}", path.display()))?;
    Ok(path)
}

fn rc_path(shell: &Shell) -> Result<PathBuf> {
    match shell {
        Shell::Zsh => {
            let home = std::env::var("HOME").context("Cannot determine HOME directory")?;
            Ok(PathBuf::from(home).join(".zshrc"))
        }
        Shell::Bash => {
            let home = std::env::var("HOME").context("Cannot determine HOME directory")?;
            Ok(PathBuf::from(home).join(".bashrc"))
        }
        Shell::Pwsh | Shell::Fish | Shell::Nushell => {
            bail!("No RC file for this shell")
        }
    }
}

#[cfg(target_os = "windows")]
fn pwsh_profile_paths() -> Result<Vec<PathBuf>> {
    let base = std::env::var("USERPROFILE").context("Cannot determine USERPROFILE directory")?;
    let base = PathBuf::from(base).join("Documents");
    Ok(vec![
        base.join("PowerShell")
            .join("Microsoft.PowerShell_profile.ps1"),
        base.join("WindowsPowerShell")
            .join("Microsoft.PowerShell_profile.ps1"),
    ])
}

fn add_source_line(rc: &std::path::Path, line: &str) -> Result<bool> {
    if let Some(parent) = rc.parent() {
        std::fs::create_dir_all(parent).ok();
    }
    let content = std::fs::read_to_string(rc).unwrap_or_default();
    if content_has_line(&content, line) {
        return Ok(false);
    }
    let mut file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(rc)
        .with_context(|| format!("Cannot open {}", rc.display()))?;
    use std::io::Write;
    if !content.is_empty() && !content.ends_with('\n') {
        writeln!(file)?;
    }
    writeln!(file, "{line}")?;
    Ok(true)
}

fn parse_shell(name: &str) -> Result<Shell> {
    match name {
        "bash" => Ok(Shell::Bash),
        "zsh" => Ok(Shell::Zsh),
        "fish" => Ok(Shell::Fish),
        "powershell" => Ok(Shell::Pwsh),
        "nushell" => Ok(Shell::Nushell),
        _ => bail!("Unknown shell: '{name}'"),
    }
}

fn completion_content(shell: &Shell) -> &'static str {
    match shell {
        Shell::Bash => BASH_COMPLETION,
        Shell::Zsh => ZSH_COMPLETION,
        Shell::Fish => FISH_COMPLETION,
        Shell::Pwsh => PS1_COMPLETION,
        Shell::Nushell => NU_COMPLETION,
    }
}

pub(crate) fn run_auto_complete(arg: &AutoCompleteArg) -> Result<()> {
    let shell = match &arg.shell {
        Some(name) => parse_shell(name)?,
        None => detect_shell()?,
    };

    match arg.mode {
        AutoCompleteMode::Dump => {
            print!("{}", completion_content(&shell));
            Ok(())
        }
        AutoCompleteMode::Remove => remove_completions(&shell),
        AutoCompleteMode::Install => install_completions(&shell),
    }
}

fn check_shell_os_compat(shell: &Shell) -> Result<()> {
    #[cfg(target_os = "windows")]
    if !matches!(shell, Shell::Pwsh | Shell::Nushell) {
        bail!(
            "Shell '{}' is not supported. Use 'powershell' or 'nushell' instead.",
            shell.name()
        );
    }
    #[cfg(not(target_os = "windows"))]
    if matches!(shell, Shell::Pwsh) {
        bail!("Shell 'powershell' is not supported. Use bash, zsh, fish, or nushell.");
    }
    Ok(())
}

fn install_completions(shell: &Shell) -> Result<()> {
    check_shell_os_compat(shell)?;
    let content = completion_content(shell);
    let filename = completion_filename(shell);

    match shell {
        Shell::Pwsh => {
            let dest = write_completion(&completion_dir()?, filename, content)?;
            println!("Completion file installed: {}", dest.display());

            #[cfg(target_os = "windows")]
            {
                let source_line = source_line_for(shell, &dest).expect("pwsh has source line");
                for rc in pwsh_profile_paths()? {
                    if add_source_line(&rc, &source_line)? {
                        println!("Added to {}", rc.display());
                    } else {
                        println!("Already configured in {}", rc.display());
                    }
                }
                println!("\nRestart PowerShell to activate completions.");
            }
        }
        Shell::Zsh | Shell::Bash => {
            let dest = write_completion(&completion_dir()?, filename, content)?;
            println!("Completion file installed: {}", dest.display());

            let source_line = source_line_for(shell, &dest).expect("bash/zsh has source line");
            let rc = rc_path(shell)?;
            if add_source_line(&rc, &source_line)? {
                println!("Added to {}", rc.display());
            } else {
                println!("Already configured in {}", rc.display());
            }
            println!("\nRestart your shell or run: source {}", rc.display());
        }
        Shell::Fish => {
            let dest = write_completion(&fish_completion_dir()?, filename, content)?;
            println!("Completion file installed: {}", dest.display());
            println!("\nCompletions are available in new fish sessions automatically.");
        }
        Shell::Nushell => {
            let dest = write_completion(&nushell_completion_dir()?, filename, content)?;
            println!("Completion file installed: {}", dest.display());
            println!("\nRestart nushell to activate (requires 0.94+ for autoload).");
        }
    }

    Ok(())
}

fn remove_completions(shell: &Shell) -> Result<()> {
    check_shell_os_compat(shell)?;

    let plan = RemovalPlan::compute(shell)?;
    if plan.is_empty() {
        println!("Nothing to remove for {}.", shell.name());
        return Ok(());
    }

    if !crate::config::confirm(&format!("Remove {} completions?", shell.name()))? {
        println!("Remove cancelled.");
        return Ok(());
    }

    for path in &plan.files {
        std::fs::remove_file(path).with_context(|| format!("Cannot remove {}", path.display()))?;
        println!("Removed completion file: {}", path.display());
    }
    for (rc, line) in &plan.rc_lines {
        if remove_source_line(rc, line)? {
            println!("Removed source line from {}", rc.display());
        }
    }
    Ok(())
}

struct RemovalPlan {
    files: Vec<PathBuf>,
    rc_lines: Vec<(PathBuf, String)>,
}

impl RemovalPlan {
    fn is_empty(&self) -> bool {
        self.files.is_empty() && self.rc_lines.is_empty()
    }

    fn compute(shell: &Shell) -> Result<Self> {
        let mut files = Vec::new();
        let mut rc_lines = Vec::new();
        let filename = completion_filename(shell);

        match shell {
            Shell::Pwsh => {
                let path = completion_dir()?.join(filename);
                if path.exists() {
                    files.push(path.clone());
                }
                #[cfg(target_os = "windows")]
                {
                    let source_line = source_line_for(shell, &path).expect("pwsh has source line");
                    for rc in pwsh_profile_paths()? {
                        if rc_contains_line(&rc, &source_line)? {
                            rc_lines.push((rc, source_line.clone()));
                        }
                    }
                }
            }
            Shell::Zsh | Shell::Bash => {
                let path = completion_dir()?.join(filename);
                let source_line = source_line_for(shell, &path).expect("bash/zsh has source line");
                if path.exists() {
                    files.push(path);
                }
                let rc = rc_path(shell)?;
                if rc_contains_line(&rc, &source_line)? {
                    rc_lines.push((rc, source_line));
                }
            }
            Shell::Fish => {
                let path = fish_completion_dir()?.join(filename);
                if path.exists() {
                    files.push(path);
                }
            }
            Shell::Nushell => {
                let path = nushell_completion_dir()?.join(filename);
                if path.exists() {
                    files.push(path);
                }
            }
        }

        Ok(RemovalPlan { files, rc_lines })
    }
}

fn content_has_line(content: &str, line: &str) -> bool {
    let needle = line.trim();
    content.lines().any(|l| l.trim() == needle)
}

fn rc_contains_line(rc: &std::path::Path, line: &str) -> Result<bool> {
    let Ok(content) = std::fs::read_to_string(rc) else {
        return Ok(false);
    };
    Ok(content_has_line(&content, line))
}

fn remove_source_line(rc: &std::path::Path, line: &str) -> Result<bool> {
    let Ok(content) = std::fs::read_to_string(rc) else {
        return Ok(false);
    };
    let needle = line.trim();
    let mut removed = false;
    let filtered: Vec<&str> = content
        .lines()
        .filter(|l| {
            if l.trim() == needle {
                removed = true;
                false
            } else {
                true
            }
        })
        .collect();
    if !removed {
        return Ok(false);
    }
    let mut new_content = filtered.join("\n");
    if content.ends_with('\n') && !new_content.is_empty() {
        new_content.push('\n');
    }
    std::fs::write(rc, new_content).with_context(|| format!("Cannot write {}", rc.display()))?;
    Ok(true)
}