-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompletion.go
More file actions
947 lines (820 loc) · 27 KB
/
completion.go
File metadata and controls
947 lines (820 loc) · 27 KB
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
/*
Copyright (C) 2025 Mark CLI Contributors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
// RC file paths for unified shell configuration
const (
bashRCFile = ".mark_bash_rc"
zshRCFile = ".mark_zsh_rc"
fishRCFile = ".config/fish/conf.d/mark.fish"
)
// Source line markers for shell configs
const (
sourceLineMarker = "# mark shell integration"
)
// getMarkPath returns the path to the mark binary
func getMarkPath() string {
markPath, err := os.Executable()
if err != nil {
markPath, err = exec.LookPath("mark")
if err != nil {
return "mark"
}
}
return markPath
}
// generateBashRC generates unified bash RC content with aliases and/or completions
func generateBashRC(markPath string, includeAliases, includeCompletions bool) string {
var features []string
if includeAliases {
features = append(features, "aliases")
}
if includeCompletions {
features = append(features, "completions")
}
var sb strings.Builder
sb.WriteString("#!/bin/bash\n")
sb.WriteString("# mark shell configuration\n")
sb.WriteString("# Generated by mark - do not edit manually\n")
sb.WriteString(fmt.Sprintf("# Features: %s\n", strings.Join(features, " ")))
sb.WriteString("\n")
if includeAliases {
sb.WriteString("# === ALIASES ===\n")
sb.WriteString(fmt.Sprintf("alias marks='%s -l'\n", markPath))
sb.WriteString(fmt.Sprintf("alias unmark='%s -d'\n", markPath))
sb.WriteString(fmt.Sprintf(`function jump() {
local target=$(%s -j "$@")
if [ $? -eq 0 ] && [ -n "$target" ]; then
cd "$target"
fi
}
`, markPath))
sb.WriteString("\n")
}
if includeCompletions {
sb.WriteString("# === COMPLETIONS ===\n")
sb.WriteString(`# Helper function to get bookmarks with their paths for display
_mark_list_with_paths() {
mark -l 2>/dev/null || true
}
_mark_complete() {
local cur="${COMP_WORDS[COMP_CWORD]}"
local prev="${COMP_WORDS[COMP_CWORD-1]}"
local cmd="${COMP_WORDS[0]}"
# If we're on the first argument
if [[ ${COMP_CWORD} -eq 1 ]]; then
# If user starts typing a dash, offer flags (only for 'mark' command)
if [[ "$cur" == -* && "$cmd" == "mark" ]]; then
local flags="-l -d -j -v -h --config --configure --autocomplete --alias --help --version"
COMPREPLY=($(compgen -W "$flags" -- "${cur}"))
else
# For bookmark completion, show formatted list
if [[ -d ~/.marks ]]; then
# Get bookmark names for actual completion
local marks=$(ls ~/.marks 2>/dev/null | tr '\n' ' ')
COMPREPLY=($(compgen -W "$marks" -- "${cur}"))
# Only show formatted list on double-tab (COMP_TYPE = 63)
if [[ ${#COMPREPLY[@]} -gt 1 ]] && [[ ${COMP_TYPE:-} -eq 63 ]]; then
echo >&2 # Newline before the list
_mark_list_with_paths >&2
fi
fi
fi
# If previous was -d or -j, offer bookmark names with paths
elif [[ "$prev" == "-d" || "$prev" == "-j" ]]; then
if [[ -d ~/.marks ]]; then
local marks=$(ls ~/.marks 2>/dev/null | tr '\n' ' ')
COMPREPLY=($(compgen -W "$marks" -- "${cur}"))
# Only show formatted list on double-tab (COMP_TYPE = 63)
if [[ ${#COMPREPLY[@]} -gt 1 ]] && [[ ${COMP_TYPE:-} -eq 63 ]]; then
echo >&2 # Newline before the list
_mark_list_with_paths >&2
fi
fi
fi
}
complete -F _mark_complete mark
complete -F _mark_complete marks
complete -F _mark_complete unmark
complete -F _mark_complete jump
`)
}
return sb.String()
}
// generateZshRC generates unified zsh RC content with aliases and/or completions
func generateZshRC(markPath string, includeAliases, includeCompletions bool) string {
var features []string
if includeAliases {
features = append(features, "aliases")
}
if includeCompletions {
features = append(features, "completions")
}
var sb strings.Builder
sb.WriteString("#!/bin/zsh\n")
sb.WriteString("# mark shell configuration\n")
sb.WriteString("# Generated by mark - do not edit manually\n")
sb.WriteString(fmt.Sprintf("# Features: %s\n", strings.Join(features, " ")))
sb.WriteString("\n")
if includeAliases {
sb.WriteString("# === ALIASES ===\n")
sb.WriteString(fmt.Sprintf("alias marks='%s -l'\n", markPath))
sb.WriteString(fmt.Sprintf("alias unmark='%s -d'\n", markPath))
sb.WriteString(fmt.Sprintf(`function jump() {
local target=$(%s -j "$@")
if [ $? -eq 0 ] && [ -n "$target" ]; then
cd "$target"
fi
}
`, markPath))
sb.WriteString("\n")
}
if includeCompletions {
sb.WriteString("# === COMPLETIONS ===\n")
sb.WriteString("autoload -U +X compinit && compinit\n\n")
sb.WriteString(`_mark_complete() {
local cur="${words[CURRENT]}"
local prev="${words[CURRENT-1]}"
local cmd="${words[1]}"
# If we're on the first argument
if [[ $CURRENT -eq 2 ]]; then
# If user starts typing a dash, offer flags (only for 'mark' command)
if [[ "$cur" == -* && "$cmd" == "mark" ]]; then
local flags=("-l" "-d" "-j" "-v" "-h" "--config" "--configure" "--autocomplete" "--alias" "--help" "--version")
compadd -a flags
else
# For bookmark completion, parse 'mark -l' output to get names and descriptions
if [[ -d ~/.marks ]]; then
local -a marks descriptions
local name desc
# Parse mark -l output: " name -> target" or " name -> [broken] target"
while IFS= read -r line; do
# Extract bookmark name (everything before ' ->')
name=$(echo "$line" | sed -E 's/^[[:space:]]*([^[:space:]]+)[[:space:]]*->.*/\1/')
# Extract description (everything from ' ->' onwards)
desc=$(echo "$line" | sed -E 's/^[[:space:]]*[^[:space:]]+[[:space:]]*(->.*)/\1/')
if [[ -n "$name" && -n "$desc" ]]; then
marks+=("$name")
descriptions+=("$desc")
fi
done < <(mark -l 2>/dev/null)
# Use compadd with descriptions
if [[ ${#marks[@]} -gt 0 ]]; then
compadd -d descriptions -a marks
fi
fi
fi
# If previous was -d or -j, offer bookmark names with descriptions
elif [[ "$prev" == "-d" || "$prev" == "-j" ]]; then
if [[ -d ~/.marks ]]; then
local -a marks descriptions
local name desc
# Parse mark -l output
while IFS= read -r line; do
name=$(echo "$line" | sed -E 's/^[[:space:]]*([^[:space:]]+)[[:space:]]*->.*/\1/')
desc=$(echo "$line" | sed -E 's/^[[:space:]]*[^[:space:]]+[[:space:]]*(->.*)/\1/')
if [[ -n "$name" && -n "$desc" ]]; then
marks+=("$name")
descriptions+=("$desc")
fi
done < <(mark -l 2>/dev/null)
# Use compadd with descriptions
if [[ ${#marks[@]} -gt 0 ]]; then
compadd -d descriptions -a marks
fi
fi
fi
}
compdef _mark_complete mark
compdef _mark_complete marks
compdef _mark_complete unmark
compdef _mark_complete jump
`)
}
return sb.String()
}
// generateFishRC generates unified fish RC content with aliases and/or completions
func generateFishRC(markPath string, includeAliases, includeCompletions bool) string {
var features []string
if includeAliases {
features = append(features, "aliases")
}
if includeCompletions {
features = append(features, "completions")
}
var sb strings.Builder
sb.WriteString("# mark shell configuration\n")
sb.WriteString("# Generated by mark - do not edit manually\n")
sb.WriteString(fmt.Sprintf("# Features: %s\n", strings.Join(features, " ")))
sb.WriteString("\n")
if includeAliases {
sb.WriteString("# === ALIASES ===\n")
sb.WriteString(fmt.Sprintf("alias marks '%s -l'\n", markPath))
sb.WriteString(fmt.Sprintf("alias unmark '%s -d'\n", markPath))
sb.WriteString(fmt.Sprintf(`function jump
set -l target (%s -j $argv)
if test $status -eq 0 -a -n "$target"
cd "$target"
end
end
`, markPath))
sb.WriteString("\n")
}
if includeCompletions {
sb.WriteString("# === COMPLETIONS ===\n")
sb.WriteString(`# Helper function to list bookmarks with their paths
function __fish_mark_list_bookmarks
mark -l 2>/dev/null | while read -l line
# Parse " name -> target" format into "name\t-> target" format
echo "$line" | sed -E 's/^[[:space:]]*([^[:space:]]+)[[:space:]]*(->.*)/\1\t\2/'
end
end
complete -c mark -f
complete -c mark -s l -d "List bookmarks"
complete -c mark -s d -d "Delete bookmark" -r
complete -c mark -s j -d "Jump to bookmark" -r
complete -c mark -l config -d "Run setup/reconfigure"
complete -c mark -l configure -d "Run setup/reconfigure"
complete -c mark -l autocomplete -d "Setup/update command line autocompletion"
complete -c mark -l alias -d "Setup shell aliases"
complete -c mark -s v -l version -d "Show version"
complete -c mark -s h -l help -d "Show help"
# Complete with existing bookmark names with paths for main argument
complete -c mark -n '__fish_is_first_token' -a '(__fish_mark_list_bookmarks)'
# Complete with bookmark names and paths for -d and -j flags
complete -c mark -n '__fish_seen_subcommand_from -d' -a '(__fish_mark_list_bookmarks)'
complete -c mark -n '__fish_seen_subcommand_from -j' -a '(__fish_mark_list_bookmarks)'
# Alias completions with descriptions
complete -c marks -f -a '(__fish_mark_list_bookmarks)'
complete -c unmark -f -a '(__fish_mark_list_bookmarks)'
complete -c jump -f -a '(__fish_mark_list_bookmarks)'
`)
}
return sb.String()
}
// writeShellRC writes the unified RC file for the specified shell
func writeShellRC(shell string, includeAliases, includeCompletions bool) error {
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("error getting home directory: %w", err)
}
markPath := getMarkPath()
var content string
var rcPath string
switch shell {
case "bash":
content = generateBashRC(markPath, includeAliases, includeCompletions)
rcPath = filepath.Join(homeDir, bashRCFile)
case "zsh":
content = generateZshRC(markPath, includeAliases, includeCompletions)
rcPath = filepath.Join(homeDir, zshRCFile)
case "fish":
content = generateFishRC(markPath, includeAliases, includeCompletions)
rcPath = filepath.Join(homeDir, fishRCFile)
// Create conf.d directory if needed
if err := os.MkdirAll(filepath.Dir(rcPath), 0755); err != nil {
return fmt.Errorf("error creating fish conf.d directory: %w", err)
}
default:
return fmt.Errorf("unsupported shell: %s", shell)
}
if err := os.WriteFile(rcPath, []byte(content), 0644); err != nil {
return fmt.Errorf("error writing RC file: %w", err)
}
return nil
}
// isSourceLinePresent checks if the mark source line is in the config file
func isSourceLinePresent(configPath string) bool {
file, err := os.Open(configPath)
if err != nil {
return false
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if strings.Contains(line, sourceLineMarker) {
return true
}
}
return false
}
// ensureSourceLine adds the source line to shell config if not present
func ensureSourceLine(shell string) error {
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("error getting home directory: %w", err)
}
var configPath string
var sourceLine string
switch shell {
case "bash":
configPath = filepath.Join(homeDir, ".bashrc")
sourceLine = fmt.Sprintf("\n%s\n[ -f ~/%s ] && source ~/%s\n", sourceLineMarker, bashRCFile, bashRCFile)
case "zsh":
configPath = filepath.Join(homeDir, ".zshrc")
sourceLine = fmt.Sprintf("\n%s\n[ -f ~/%s ] && source ~/%s\n", sourceLineMarker, zshRCFile, zshRCFile)
case "fish":
// Fish auto-sources files in conf.d, no source line needed
return nil
default:
return fmt.Errorf("unsupported shell: %s", shell)
}
// Check if source line already exists
if isSourceLinePresent(configPath) {
return nil
}
// Append source line
file, err := os.OpenFile(configPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
return fmt.Errorf("error opening shell config: %w", err)
}
defer file.Close()
if _, err := file.WriteString(sourceLine); err != nil {
return fmt.Errorf("error writing source line: %w", err)
}
return nil
}
// getEnabledFeatures reads the RC file header to detect current features
func getEnabledFeatures(shell string) (aliases, completions bool) {
homeDir, err := os.UserHomeDir()
if err != nil {
return false, false
}
var rcPath string
switch shell {
case "bash":
rcPath = filepath.Join(homeDir, bashRCFile)
case "zsh":
rcPath = filepath.Join(homeDir, zshRCFile)
case "fish":
rcPath = filepath.Join(homeDir, fishRCFile)
default:
return false, false
}
file, err := os.Open(rcPath)
if err != nil {
return false, false
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "# Features:") {
features := strings.TrimPrefix(line, "# Features:")
aliases = strings.Contains(features, "aliases")
completions = strings.Contains(features, "completions")
return
}
}
return false, false
}
// getRCFilePath returns the path to the RC file for the given shell
func getRCFilePath(shell string) string {
homeDir, _ := os.UserHomeDir()
switch shell {
case "bash":
return filepath.Join(homeDir, bashRCFile)
case "zsh":
return filepath.Join(homeDir, zshRCFile)
case "fish":
return filepath.Join(homeDir, fishRCFile)
default:
return ""
}
}
// SetupCompletion handles the interactive completion setup prompt
func SetupCompletion(reader *bufio.Reader) {
// Check if completion is already set up
if IsCompletionAlreadySetup() {
return
}
fmt.Println()
fmt.Print("Would you like to set up command line completion for mark? (y/N): ")
response, _ := reader.ReadString('\n')
response = strings.ToLower(strings.TrimSpace(response))
if response != "y" && response != "yes" {
fmt.Println("Skipping completion setup. You can run 'mark --config' later to set it up.")
return
}
shell := detectShell()
if shell == "" {
fmt.Println("Could not detect shell type. Skipping completion setup.")
return
}
switch shell {
case "bash":
SetupBashCompletion()
case "zsh":
SetupZshCompletion()
case "fish":
SetupFishCompletion()
default:
fmt.Printf("Shell '%s' not supported for completion. Supported shells: bash, zsh, fish\n", shell)
}
}
// IsCompletionAlreadySetup checks if command line completion is already configured
func IsCompletionAlreadySetup() bool {
shell := detectShell()
if shell == "" {
return false
}
// Check if completions are enabled in the new RC file
_, completions := getEnabledFeatures(shell)
if completions {
return true
}
// Also check legacy locations for backwards compatibility
homeDir, err := os.UserHomeDir()
if err != nil {
return false
}
switch shell {
case "bash":
// Check legacy ~/.mark.bash
bashCompletionFile := filepath.Join(homeDir, ".mark.bash")
if _, err := os.Stat(bashCompletionFile); err == nil {
bashFiles := []string{".bashrc", ".bash_profile", ".profile"}
for _, file := range bashFiles {
if CheckFileForCompletionSource(filepath.Join(homeDir, file)) {
return true
}
}
}
case "zsh":
// Check legacy ~/.mark.zsh
zshCompletionFile := filepath.Join(homeDir, ".mark.zsh")
if _, err := os.Stat(zshCompletionFile); err == nil {
if CheckFileForCompletionSource(filepath.Join(homeDir, ".zshrc")) {
return true
}
}
case "fish":
// Check legacy fish completion location
fishCompletionFile := filepath.Join(homeDir, ".config", "fish", "completions", "mark.fish")
_, err := os.Stat(fishCompletionFile)
return err == nil
}
return false
}
// CheckFileForCompletionSource checks if a file sources mark completion
func CheckFileForCompletionSource(filePath string) bool {
file, err := os.Open(filePath)
if err != nil {
return false
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
// Check for new unified RC files
if strings.Contains(line, ".mark_bash_rc") || strings.Contains(line, ".mark_zsh_rc") {
return true
}
// Check for legacy .mark.bash/.mark.zsh files
if (strings.Contains(line, "~/.mark.bash") || strings.Contains(line, "~/.mark.zsh")) &&
(strings.Contains(line, "source") || strings.Contains(line, ".")) ||
(strings.Contains(line, "mark") && (strings.Contains(line, "complete") || strings.Contains(line, "completion"))) {
return true
}
}
return false
}
// SetupBashCompletion sets up bash command completion
func SetupBashCompletion() {
homeDir, err := os.UserHomeDir()
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting home directory: %v\n", err)
return
}
// Check if aliases are already enabled (preserve them)
aliases, _ := getEnabledFeatures("bash")
// Write unified RC file with completions enabled
if err := writeShellRC("bash", aliases, true); err != nil {
fmt.Fprintf(os.Stderr, "Error writing bash RC file: %v\n", err)
return
}
// Add source line to .bashrc if not present
if err := ensureSourceLine("bash"); err != nil {
fmt.Fprintf(os.Stderr, "Error updating .bashrc: %v\n", err)
return
}
rcPath := filepath.Join(homeDir, bashRCFile)
fmt.Printf("✓ Bash completion setup complete!\n")
fmt.Printf(" Created configuration at %s\n", rcPath)
fmt.Printf(" Updated ~/.bashrc to source configuration\n")
fmt.Printf(" Run 'source ~/.bashrc' or restart your shell to activate completions\n")
}
// SetupZshCompletion sets up zsh command completion
func SetupZshCompletion() {
homeDir, err := os.UserHomeDir()
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting home directory: %v\n", err)
return
}
// Check if aliases are already enabled (preserve them)
aliases, _ := getEnabledFeatures("zsh")
// Write unified RC file with completions enabled
if err := writeShellRC("zsh", aliases, true); err != nil {
fmt.Fprintf(os.Stderr, "Error writing zsh RC file: %v\n", err)
return
}
// Add source line to .zshrc if not present
if err := ensureSourceLine("zsh"); err != nil {
fmt.Fprintf(os.Stderr, "Error updating .zshrc: %v\n", err)
return
}
rcPath := filepath.Join(homeDir, zshRCFile)
fmt.Printf("✓ Zsh completion setup complete!\n")
fmt.Printf(" Created configuration at %s\n", rcPath)
fmt.Printf(" Updated ~/.zshrc to source configuration\n")
fmt.Printf(" Restart your shell or run: source ~/.zshrc\n")
}
// SetupFishCompletion sets up fish command completion
func SetupFishCompletion() {
homeDir, err := os.UserHomeDir()
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting home directory: %v\n", err)
return
}
// Check if aliases are already enabled (preserve them)
aliases, _ := getEnabledFeatures("fish")
// Write unified RC file with completions enabled
if err := writeShellRC("fish", aliases, true); err != nil {
fmt.Fprintf(os.Stderr, "Error writing fish RC file: %v\n", err)
return
}
rcPath := filepath.Join(homeDir, fishRCFile)
fmt.Printf("✓ Fish completion setup complete!\n")
fmt.Printf(" Created configuration at %s\n", rcPath)
fmt.Printf(" Fish auto-sources files in conf.d, restart your shell to activate\n")
}
// RunAutocompleteSetup handles the main autocomplete setup flow
func RunAutocompleteSetup() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("mark - Command Line Autocompletion Setup")
fmt.Println()
fmt.Println("This will set up tab completion for the mark command, allowing you to:")
fmt.Println("• Tab-complete bookmark names")
fmt.Println("• Tab-complete command flags")
fmt.Println("• Get context-aware completions")
fmt.Println()
fmt.Print("Would you like to set up autocompletion? (y/N): ")
response, _ := reader.ReadString('\n')
response = strings.ToLower(strings.TrimSpace(response))
if response != "y" && response != "yes" {
fmt.Println("Autocompletion setup cancelled.")
return
}
shell := detectShell()
if shell == "" {
fmt.Println("Could not detect shell type. Skipping completion setup.")
fmt.Println("Supported shells: bash, zsh, fish")
return
}
fmt.Printf("Detected shell: %s\n", shell)
fmt.Println()
// Clean up any existing completion setup
fmt.Println("Cleaning up any existing completion setup...")
CleanupExistingCompletion(shell)
// Set up completion for the detected shell
fmt.Printf("Setting up %s completion...\n", shell)
switch shell {
case "bash":
SetupBashCompletion()
case "zsh":
SetupZshCompletion()
case "fish":
SetupFishCompletion()
default:
fmt.Printf("Shell '%s' not supported for completion. Supported shells: bash, zsh, fish\n", shell)
return
}
fmt.Println()
fmt.Println("✓ Autocompletion setup complete!")
fmt.Println(" To activate, run one of:")
switch shell {
case "bash":
fmt.Printf(" source ~/.bashrc\n")
fmt.Printf(" source ~/%s\n", bashRCFile)
case "zsh":
fmt.Printf(" source ~/.zshrc\n")
fmt.Printf(" source ~/%s\n", zshRCFile)
case "fish":
fmt.Println(" (restart your shell)")
}
fmt.Println(" Or simply restart your shell")
}
// CleanupExistingCompletion removes existing completion setup for the specified shell
func CleanupExistingCompletion(shell string) {
homeDir, err := os.UserHomeDir()
if err != nil {
return
}
switch shell {
case "bash":
// Remove legacy .mark.bash file
os.Remove(filepath.Join(homeDir, ".mark.bash"))
// Remove new unified RC file
os.Remove(filepath.Join(homeDir, bashRCFile))
// Clean up shell config files (removes old mark entries, preserves new source line)
cleanupShellConfigLegacy(filepath.Join(homeDir, ".bashrc"))
cleanupShellConfigLegacy(filepath.Join(homeDir, ".bash_profile"))
cleanupShellConfigLegacy(filepath.Join(homeDir, ".profile"))
case "zsh":
// Remove legacy .mark.zsh file
os.Remove(filepath.Join(homeDir, ".mark.zsh"))
// Remove new unified RC file
os.Remove(filepath.Join(homeDir, zshRCFile))
// Clean up .zshrc
cleanupShellConfigLegacy(filepath.Join(homeDir, ".zshrc"))
case "fish":
// Remove legacy fish completion file
os.Remove(filepath.Join(homeDir, ".config", "fish", "completions", "mark.fish"))
// Remove new unified RC file
os.Remove(filepath.Join(homeDir, fishRCFile))
// Clean up legacy aliases from config.fish
cleanupFishConfigLegacy(filepath.Join(homeDir, ".config", "fish", "config.fish"))
}
}
// cleanupShellConfigLegacy removes legacy mark entries from shell config files
// but preserves the new unified source line
func cleanupShellConfigLegacy(configFile string) {
file, err := os.Open(configFile)
if err != nil {
return
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
skipUntilBlank := false
inMarkAliasBlock := false
for scanner.Scan() {
line := scanner.Text()
// Skip legacy "# mark command completion" blocks
if strings.Contains(line, "# mark command completion") {
skipUntilBlank = true
continue
}
// Skip legacy "# mark command aliases" blocks
if strings.Contains(line, "# mark command aliases") {
inMarkAliasBlock = true
continue
}
// Skip lines in legacy completion blocks
if skipUntilBlank {
if strings.Contains(line, ".mark.bash") ||
strings.Contains(line, ".mark.zsh") ||
strings.Contains(line, "completions/bash/mark") ||
(strings.Contains(line, "autoload") && strings.Contains(line, "compinit")) ||
(strings.Contains(line, "mark") && strings.Contains(line, "source")) {
continue
}
if strings.TrimSpace(line) == "" {
skipUntilBlank = false
continue
}
skipUntilBlank = false
}
// Skip lines in legacy alias blocks
if inMarkAliasBlock {
if strings.Contains(line, "alias marks=") ||
strings.Contains(line, "alias unmark=") ||
strings.Contains(line, "function jump") ||
strings.Contains(line, "local target=$(") ||
strings.Contains(line, "cd \"$target\"") ||
strings.TrimSpace(line) == "}" {
continue
}
if strings.TrimSpace(line) == "" {
inMarkAliasBlock = false
continue
}
// Check for jump function body lines
trimmed := strings.TrimSpace(line)
if trimmed == "if [ $? -eq 0 ] && [ -n \"$target\" ]; then" ||
trimmed == "fi" {
continue
}
inMarkAliasBlock = false
}
lines = append(lines, line)
}
// Write the cleaned file back
outFile, err := os.Create(configFile)
if err != nil {
return
}
defer outFile.Close()
for _, line := range lines {
fmt.Fprintln(outFile, line)
}
}
// cleanupFishConfigLegacy removes legacy mark aliases from fish config.fish
func cleanupFishConfigLegacy(configFile string) {
file, err := os.Open(configFile)
if err != nil {
return
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
inMarkBlock := false
inJumpFunction := false
for scanner.Scan() {
line := scanner.Text()
// Skip "# mark command aliases" comment
if strings.Contains(line, "# mark command aliases") {
inMarkBlock = true
continue
}
if inMarkBlock {
// Skip alias lines
if strings.Contains(line, "alias marks ") ||
strings.Contains(line, "alias unmark ") {
continue
}
// Skip jump function
if strings.HasPrefix(strings.TrimSpace(line), "function jump") {
inJumpFunction = true
continue
}
if inJumpFunction {
if strings.TrimSpace(line) == "end" {
inJumpFunction = false
continue
}
continue
}
// End of mark block on blank line
if strings.TrimSpace(line) == "" {
inMarkBlock = false
continue
}
inMarkBlock = false
}
lines = append(lines, line)
}
// Write the cleaned file back
outFile, err := os.Create(configFile)
if err != nil {
return
}
defer outFile.Close()
for _, line := range lines {
fmt.Fprintln(outFile, line)
}
}
// cleanupShellConfigSourceLine removes the new mark source line from shell config
func cleanupShellConfigSourceLine(configFile string) {
file, err := os.Open(configFile)
if err != nil {
return
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
skipNext := false
for scanner.Scan() {
line := scanner.Text()
// Skip "# mark shell integration" and the following source line
if strings.Contains(line, sourceLineMarker) {
skipNext = true
continue
}
if skipNext && (strings.Contains(line, ".mark_bash_rc") ||
strings.Contains(line, ".mark_zsh_rc")) {
skipNext = false
continue
}
skipNext = false
lines = append(lines, line)
}
// Write the cleaned file back
outFile, err := os.Create(configFile)
if err != nil {
return
}
defer outFile.Close()
for _, line := range lines {
fmt.Fprintln(outFile, line)
}
}