larpshell 0.1.5

Ctrl+C then Ctrl+V is simply too much work. Just let an LLM rule your terminal directly!!
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
use std::fs::{self, OpenOptions};
use std::io::Write;

use crate::cli::home_dir;
use crate::error::LarpshellError;

pub fn generate_bash_autocomplete() -> &'static str {
    r#"_larpshell_completions() {
    local cur prev
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"

    if [ $COMP_CWORD -eq 1 ]; then
        COMPREPLY=( $(compgen -W "api agent history prompt explain uninstall --help --version" -- "$cur") )
    elif [ $COMP_CWORD -eq 2 ]; then
        case "$prev" in
            agent|history)
                COMPREPLY=( $(compgen -W "on off" -- "$cur") )
                ;;
            prompt)
                COMPREPLY=( $(compgen -W "system explain" -- "$cur") )
                ;;
        esac
    elif [ $COMP_CWORD -eq 3 ]; then
        case "${COMP_WORDS[1]}" in
            prompt)
                COMPREPLY=( $(compgen -W "show edit" -- "$cur") )
                ;;
        esac
    fi
    return 0
}
complete -F _larpshell_completions larpshell"#
}

pub fn generate_zsh_autocomplete() -> &'static str {
    r#"#compdef larpshell

_larpshell() {
    local -a commands
    commands=(
        'api:configure API provider (Gemini, Ollama, OpenRouter, LM Studio, OpenAI)'
        'agent:enable or disable agent mode'
        'explain:explain a shell command'
        'history:enable or disable prompt history'
        'prompt:view or edit system/explain prompts'
        'uninstall:uninstall larpshell'
    )

    _arguments -C \
        '1: :->cmds' \
        '--help[show help information]' \
        '--version[show version information]' \
        '*::arg:->args'

    case "$state" in
        cmds)
            _describe -t commands 'larpshell commands' commands
            ;;
        args)
            case "${words[1]}" in
                agent|history)
                    local -a toggles
                    toggles=('on:enable' 'off:disable')
                    _arguments '1: :->toggle'
                    case "$state" in
                        toggle) _describe -t toggles 'toggle' toggles ;;
                    esac
                    ;;
                prompt)
                    local -a kinds actions
                    kinds=('system:system prompt' 'explain:explain prompt')
                    actions=('show:show prompt' 'edit:edit prompt')
                    _arguments \
                        '1: :->kind' \
                        '2: :->action'
                    case "$state" in
                        kind) _describe -t kinds 'prompt kind' kinds ;;
                        action) _describe -t actions 'prompt action' actions ;;
                    esac
                    ;;
            esac
            ;;
    esac
}

_larpshell"#
}

pub fn generate_fish_autocomplete() -> &'static str {
    r#"# larpshell autocomplete
complete -c larpshell -f
complete -c larpshell -n "__fish_use_subcommand" -a api -d 'configure API provider (Gemini, Ollama, OpenRouter, LM Studio, OpenAI)'
complete -c larpshell -n "__fish_use_subcommand" -a agent -d 'enable or disable agent mode'
complete -c larpshell -n "__fish_use_subcommand" -a explain -d 'explain a shell command'
complete -c larpshell -n "__fish_use_subcommand" -a history -d 'enable or disable prompt history'
complete -c larpshell -n "__fish_use_subcommand" -a prompt -d 'view or edit system/explain prompts'
complete -c larpshell -n "__fish_use_subcommand" -a uninstall -d 'uninstall larpshell'
complete -c larpshell -l help -d 'show help information'
complete -c larpshell -l version -d 'show version information'
complete -c larpshell -n "__fish_seen_subcommand_from agent" -a "on off" -d 'toggle agent mode'
complete -c larpshell -n "__fish_seen_subcommand_from history" -a "on off" -d 'toggle history'
complete -c larpshell -n "__fish_seen_subcommand_from prompt" -a system -d 'system prompt'
complete -c larpshell -n "__fish_seen_subcommand_from prompt" -a explain -d 'explain prompt'
complete -c larpshell -n "__fish_seen_subcommand_from prompt; and __fish_seen_subcommand_from system explain" -a "show edit" -d 'prompt action'"#
}

pub fn generate_bash_function() -> &'static str {
    r#"larpshell() {
    if [ $# -eq 0 ]; then
        command larpshell
        return $?
    fi

    case "$1" in
        api|agent|explain|history|uninstall|prompt|--help|-h|--version|-V)
            command larpshell "$@"
            return $?
            ;;
    esac

    local cmd=$(command larpshell "$@")
    local exit_code=$?
    if [ $exit_code -eq 0 ] && [ -n "$cmd" ]; then
        if [[ "$cmd" =~ ^(Usage:|error:|Commands:|larpshell\ [0-9]|$'\e'|$'\033'|✓|.*:$) ]]; then
            echo "$cmd"
            return 0
        fi
        eval "$cmd"
    else
        return $exit_code
    fi
}"#
}

pub fn generate_fish_function() -> &'static str {
    r#"function larpshell
    if test (count $argv) -eq 0
        command larpshell
        return $status
    end

    switch $argv[1]
        case api explain history uninstall prompt -- help --help -h --version -V
            command larpshell $argv
            return $status
    end

    set cmd (command larpshell $argv)
    set exit_code $status
    if test $exit_code -eq 0 -a -n "$cmd"
        if string match -qr '^(Usage:|error:|Commands:|larpshell [0-9]|\x1b|\e|✓|.*:$)' -- "$cmd"
            echo "$cmd"
            return 0
        end
        eval $cmd
    else
        return $exit_code
    end
end"#
}

pub fn auto_setup_shell_function() -> Result<bool, LarpshellError> {
    verify_and_fix_integrations()?;
    let bash_added = setup_bash_integration()?;
    let fish_added = setup_fish_integration()?;
    let autocomplete_added = setup_autocomplete()?;
    Ok(bash_added || fish_added || autocomplete_added)
}

fn verify_and_fix_integrations() -> Result<(), LarpshellError> {
    verify_and_fix_bash_integration()?;
    verify_and_fix_fish_integration()?;
    verify_and_fix_autocomplete()?;
    Ok(())
}

fn verify_and_fix_autocomplete() -> Result<(), LarpshellError> {
    verify_and_fix_bash_autocomplete()?;
    verify_and_fix_zsh_autocomplete()?;
    verify_and_fix_fish_autocomplete()?;
    Ok(())
}

fn verify_and_fix_bash_autocomplete() -> Result<(), LarpshellError> {
    let home = home_dir();
    let completion_path = home.join(".local/share/bash-completion/completions/larpshell");

    if !completion_path.exists() {
        return Ok(());
    }

    let content = fs::read_to_string(&completion_path)?;
    let expected = generate_bash_autocomplete();

    if !content.contains(expected) {
        let mut file = OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(&completion_path)?;
        writeln!(file, "# larpshell bash autocomplete")?;
        writeln!(file, "{}", expected)?;
    }

    Ok(())
}

fn verify_and_fix_zsh_autocomplete() -> Result<(), LarpshellError> {
    let home = home_dir();
    let completion_path = home.join(".local/share/zsh/site-functions/_larpshell");

    if !completion_path.exists() {
        return Ok(());
    }

    let content = fs::read_to_string(&completion_path)?;
    let expected = generate_zsh_autocomplete();

    if !content.contains(expected) {
        let mut file = OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(&completion_path)?;
        writeln!(file, "# larpshell zsh autocomplete")?;
        writeln!(file, "{}", expected)?;
    }

    Ok(())
}

fn verify_and_fix_fish_autocomplete() -> Result<(), LarpshellError> {
    let home = home_dir();
    let completion_path = home.join(".config/fish/completions/larpshell.fish");

    if !completion_path.exists() {
        return Ok(());
    }

    let content = fs::read_to_string(&completion_path)?;
    let expected = generate_fish_autocomplete();

    if !content.contains(expected) {
        let mut file = OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(&completion_path)?;
        writeln!(file, "{}", expected)?;
    }

    Ok(())
}

fn verify_and_fix_bash_integration() -> Result<(), LarpshellError> {
    let home = home_dir();
    let bashrc_path = home.join(".bashrc");

    if !bashrc_path.exists() {
        return Ok(());
    }

    let content = fs::read_to_string(&bashrc_path)?;

    // check if integration exists
    if !content.contains("larpshell()") {
        return Ok(());
    }

    // extract the function and verify it matches
    let expected_function = generate_bash_function();

    if !content.contains(expected_function) {
        // function exists but doesn't match - remove and reinstall
        remove_bash_integration()?;
        setup_bash_integration()?;
    }

    Ok(())
}

fn verify_and_fix_fish_integration() -> Result<(), LarpshellError> {
    let home = home_dir();
    let fish_function_path = home.join(".config/fish/functions/larpshell.fish");

    if !fish_function_path.exists() {
        return Ok(());
    }

    let content = fs::read_to_string(&fish_function_path)?;

    // verify the function matches expected content
    let expected_function = generate_fish_function();

    if !content.contains(expected_function) {
        // function exists but doesn't match - remove and reinstall
        remove_fish_integration()?;
        setup_fish_integration()?;
    }

    Ok(())
}

fn setup_bash_integration() -> Result<bool, LarpshellError> {
    let home = home_dir();
    let bashrc_path = home.join(".bashrc");

    if !bashrc_path.exists() {
        return Ok(false);
    }

    let content = fs::read_to_string(&bashrc_path)?;

    if content.contains("larpshell() {") || content.contains("larpshell()") {
        return Ok(false);
    }

    let mut file = OpenOptions::new().append(true).open(&bashrc_path)?;

    writeln!(file, "\n# larpshell shell integration")?;
    writeln!(file, "{}", generate_bash_function())?;

    Ok(true)
}

fn setup_fish_integration() -> Result<bool, LarpshellError> {
    let home = home_dir();
    let fish_functions_dir = home.join(".config/fish/functions");
    let fish_function_path = fish_functions_dir.join("larpshell.fish");

    if fish_function_path.exists() {
        return Ok(false);
    }

    let fish_config_dir = home.join(".config/fish");
    if !fish_config_dir.exists() {
        return Ok(false);
    }

    fs::create_dir_all(&fish_functions_dir)?;

    let mut file = OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(true)
        .open(&fish_function_path)?;

    writeln!(file, "# larpshell shell integration")?;
    writeln!(file, "{}", generate_fish_function())?;

    Ok(true)
}

/// Removes a marked function block from shell config content.
/// Looks for `marker` as a comment line, then tracks brace depth starting from
/// the line matching `function_sig` until braces balance to zero.
/// Returns the cleaned content and whether the block was found.
fn remove_marked_function_block(content: &str, marker: &str, function_sig: &str) -> (String, bool) {
    let lines: Vec<&str> = content.lines().collect();
    let mut new_lines = Vec::new();
    let mut skip = false;
    let mut brace_depth = 0;
    let mut in_function = false;
    let mut found = false;

    for line in lines {
        if line.trim() == marker {
            skip = true;
            found = true;
            continue;
        }

        if skip {
            if !in_function && line.contains(function_sig) {
                in_function = true;
                brace_depth += line.matches('{').count() as i32;
            } else if in_function {
                brace_depth += line.matches('{').count() as i32;
                brace_depth -= line.matches('}').count() as i32;

                if brace_depth == 0 {
                    skip = false;
                    in_function = false;
                    continue;
                }
            }
            continue;
        }

        new_lines.push(line);
    }

    if found {
        while new_lines.last().is_some_and(|l| l.trim().is_empty()) {
            new_lines.pop();
        }
    }

    (new_lines.join("\n") + "\n", found)
}

pub fn remove_bash_integration() -> Result<bool, LarpshellError> {
    let home = home_dir();
    let bashrc_path = home.join(".bashrc");

    if !bashrc_path.exists() {
        return Ok(false);
    }

    let content = fs::read_to_string(&bashrc_path)?;

    if !content.contains("larpshell() {") && !content.contains("larpshell()") {
        return Ok(false);
    }

    let (new_content, found) =
        remove_marked_function_block(&content, "# larpshell shell integration", "larpshell()");

    if found {
        fs::write(&bashrc_path, new_content)?;
    }

    Ok(found)
}

pub fn remove_fish_integration() -> Result<bool, LarpshellError> {
    let home = home_dir();
    let fish_function_path = home.join(".config/fish/functions/larpshell.fish");

    if fish_function_path.exists() {
        fs::remove_file(&fish_function_path)?;
        Ok(true)
    } else {
        Ok(false)
    }
}

fn setup_autocomplete() -> Result<bool, LarpshellError> {
    let bash_added = setup_bash_autocomplete()?;
    let zsh_added = setup_zsh_autocomplete()?;
    let fish_added = setup_fish_autocomplete()?;
    Ok(bash_added || zsh_added || fish_added)
}

fn setup_bash_autocomplete() -> Result<bool, LarpshellError> {
    let home = home_dir();
    let completion_dir = home.join(".local/share/bash-completion/completions");
    let completion_path = completion_dir.join("larpshell");

    if completion_path.exists() {
        return Ok(false); // already handled by verify_and_fix_bash_autocomplete
    }

    fs::create_dir_all(&completion_dir)?;

    let mut file = OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(true)
        .open(&completion_path)?;

    writeln!(file, "# larpshell bash autocomplete")?;
    writeln!(file, "{}", generate_bash_autocomplete())?;

    Ok(true)
}

fn setup_zsh_autocomplete() -> Result<bool, LarpshellError> {
    let home = home_dir();
    let zsh_config = home.join(".zshrc");
    if !zsh_config.exists() {
        return Ok(false);
    }

    let completion_dir = home.join(".local/share/zsh/site-functions");
    let completion_path = completion_dir.join("_larpshell");

    if completion_path.exists() {
        return Ok(false); // already handled by verify_and_fix_zsh_autocomplete
    }

    fs::create_dir_all(&completion_dir)?;

    let mut file = OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(true)
        .open(&completion_path)?;

    writeln!(file, "# larpshell zsh autocomplete")?;
    writeln!(file, "{}", generate_zsh_autocomplete())?;

    let zshrc_content = fs::read_to_string(&zsh_config)?;
    if !zshrc_content.contains(".local/share/zsh/site-functions") {
        let mut file = OpenOptions::new().append(true).open(&zsh_config)?;
        writeln!(file, "\n# larpshell autocomplete")?;
        writeln!(file, "fpath=(~/.local/share/zsh/site-functions $fpath)")?;
        writeln!(file, "autoload -Uz compinit && compinit")?;
    }

    Ok(true)
}

fn setup_fish_autocomplete() -> Result<bool, LarpshellError> {
    let home = home_dir();
    let fish_config_dir = home.join(".config/fish");
    if !fish_config_dir.exists() {
        return Ok(false);
    }

    let completion_dir = home.join(".config/fish/completions");
    let completion_path = completion_dir.join("larpshell.fish");

    if completion_path.exists() {
        return Ok(false); // already handled by verify_and_fix_fish_autocomplete
    }

    fs::create_dir_all(&completion_dir)?;

    let mut file = OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(true)
        .open(&completion_path)?;

    writeln!(file, "{}", generate_fish_autocomplete())?;

    Ok(true)
}

fn remove_bash_autocomplete() -> Result<bool, LarpshellError> {
    let home = home_dir();
    let completion_path = home.join(".local/share/bash-completion/completions/larpshell");

    if completion_path.exists() {
        fs::remove_file(&completion_path)?;
        Ok(true)
    } else {
        Ok(false)
    }
}

fn remove_zsh_completion_file() -> Result<bool, LarpshellError> {
    let home = home_dir();
    let completion_path = home.join(".local/share/zsh/site-functions/_larpshell");

    if completion_path.exists() {
        fs::remove_file(&completion_path)?;
        Ok(true)
    } else {
        Ok(false)
    }
}

fn remove_zsh_fpath_block(zshrc: &std::path::Path, marker: &str) -> Result<bool, LarpshellError> {
    if !zshrc.exists() {
        return Ok(false);
    }
    let content = fs::read_to_string(zshrc)?;
    if !content.contains(marker) {
        return Ok(false);
    }

    let lines: Vec<&str> = content.lines().collect();
    let mut new_lines = Vec::new();
    let mut skip = false;
    let mut removed = false;

    for line in lines {
        if line.trim() == marker {
            skip = true;
            removed = true;
            continue;
        }
        if skip {
            if line.contains(".local/share/zsh/site-functions")
                || line.contains("autoload -Uz compinit")
            {
                continue;
            }
            skip = false;
        }
        new_lines.push(line);
    }

    if removed {
        while new_lines.last().is_some_and(|l| l.trim().is_empty()) {
            new_lines.pop();
        }
        fs::write(zshrc, new_lines.join("\n") + "\n")?;
    }

    Ok(removed)
}

fn remove_zsh_fpath_from_zshrc() -> Result<bool, LarpshellError> {
    let home = home_dir();
    remove_zsh_fpath_block(&home.join(".zshrc"), "# larpshell autocomplete")
}

fn remove_zsh_autocomplete() -> Result<bool, LarpshellError> {
    let file_removed = remove_zsh_completion_file()?;
    let zshrc_cleaned = remove_zsh_fpath_from_zshrc()?;
    Ok(file_removed || zshrc_cleaned)
}

fn remove_fish_autocomplete() -> Result<bool, LarpshellError> {
    let home = home_dir();
    let completion_path = home.join(".config/fish/completions/larpshell.fish");

    if completion_path.exists() {
        fs::remove_file(&completion_path)?;
        Ok(true)
    } else {
        Ok(false)
    }
}

fn remove_autocomplete() -> Result<bool, LarpshellError> {
    let bash_removed = remove_bash_autocomplete()?;
    let zsh_removed = remove_zsh_autocomplete()?;
    let fish_removed = remove_fish_autocomplete()?;
    Ok(bash_removed || zsh_removed || fish_removed)
}

pub fn remove_shell_integration() -> Result<bool, LarpshellError> {
    let bash_removed = remove_bash_integration()?;
    let fish_removed = remove_fish_integration()?;
    let autocomplete_removed = remove_autocomplete()?;
    Ok(bash_removed || fish_removed || autocomplete_removed)
}

// ── nlsh-rs → larpshell migration ──────────────────────────────────────────

/// Removes all shell artifacts left behind by the old `nlsh-rs` binary.
/// Called once at startup; safe to call when nothing is present.
pub fn migrate_nlsh_rs_shell() -> Result<bool, LarpshellError> {
    let bash = migrate_nlsh_rs_bash()?;
    let fish = migrate_nlsh_rs_fish_fn()?;
    let completions = migrate_nlsh_rs_completions()?;
    let zsh = migrate_nlsh_rs_zsh_comment()?;
    Ok(bash || fish || completions || zsh)
}

fn migrate_nlsh_rs_bash() -> Result<bool, LarpshellError> {
    let home = home_dir();
    let bashrc = home.join(".bashrc");
    if !bashrc.exists() {
        return Ok(false);
    }
    let content = fs::read_to_string(&bashrc)?;
    if !content.contains("nlsh-rs()") && !content.contains("# nlsh-rs shell integration") {
        return Ok(false);
    }
    let (new_content, found) =
        remove_marked_function_block(&content, "# nlsh-rs shell integration", "nlsh-rs()");
    if found {
        fs::write(&bashrc, new_content)?;
    }
    Ok(found)
}

fn migrate_nlsh_rs_fish_fn() -> Result<bool, LarpshellError> {
    let home = home_dir();
    let path = home.join(".config/fish/functions/nlsh-rs.fish");
    if path.exists() {
        fs::remove_file(&path)?;
        Ok(true)
    } else {
        Ok(false)
    }
}

fn migrate_nlsh_rs_completions() -> Result<bool, LarpshellError> {
    let home = home_dir();
    let mut removed = false;
    for path in [
        home.join(".local/share/bash-completion/completions/nlsh-rs"),
        home.join(".local/share/zsh/site-functions/_nlsh-rs"),
        home.join(".config/fish/completions/nlsh-rs.fish"),
    ] {
        if path.exists() {
            fs::remove_file(&path)?;
            removed = true;
        }
    }
    Ok(removed)
}

fn migrate_nlsh_rs_zsh_comment() -> Result<bool, LarpshellError> {
    let home = home_dir();
    remove_zsh_fpath_block(&home.join(".zshrc"), "# nlsh-rs autocomplete")
}