]> git.lizzy.rs Git - micro.git/blob - cmd/micro/autocomplete.go
Add much better autocompletion for commands
[micro.git] / cmd / micro / autocomplete.go
1 package main
2
3 import (
4         "io/ioutil"
5         "os"
6         "strings"
7 )
8
9 func FileComplete(input string) (string, []string) {
10         dirs := strings.Split(input, "/")
11         var files []os.FileInfo
12         var err error
13         if len(dirs) > 1 {
14                 files, err = ioutil.ReadDir(strings.Join(dirs[:len(dirs)-1], "/"))
15         } else {
16                 files, err = ioutil.ReadDir(".")
17         }
18         var suggestions []string
19         if err != nil {
20                 return "", suggestions
21         }
22         for _, f := range files {
23                 name := f.Name()
24                 if f.IsDir() {
25                         name += "/"
26                 }
27                 if strings.HasPrefix(name, dirs[len(dirs)-1]) {
28                         suggestions = append(suggestions, name)
29                 }
30         }
31
32         var chosen string
33         if len(suggestions) == 1 {
34                 if len(dirs) > 1 {
35                         chosen = strings.Join(dirs[:len(dirs)-1], "/") + "/" + suggestions[0]
36                 } else {
37                         chosen = suggestions[0]
38                 }
39         }
40
41         return chosen, suggestions
42 }
43
44 func CommandComplete(input string) (string, []string) {
45         var suggestions []string
46         for cmd := range commands {
47                 if strings.HasPrefix(cmd, input) {
48                         suggestions = append(suggestions, cmd)
49                 }
50         }
51
52         var chosen string
53         if len(suggestions) == 1 {
54                 chosen = suggestions[0]
55         }
56         return chosen, suggestions
57 }
58
59 func HelpComplete(input string) (string, []string) {
60         var suggestions []string
61
62         for _, topic := range helpFiles {
63                 if strings.HasPrefix(topic, input) {
64
65                         suggestions = append(suggestions, topic)
66                 }
67         }
68
69         var chosen string
70         if len(suggestions) == 1 {
71                 chosen = suggestions[0]
72         }
73         return chosen, suggestions
74 }
75
76 func OptionComplete(input string) (string, []string) {
77         var suggestions []string
78         for option := range settings {
79                 if strings.HasPrefix(option, input) {
80                         suggestions = append(suggestions, option)
81                 }
82         }
83
84         var chosen string
85         if len(suggestions) == 1 {
86                 chosen = suggestions[0]
87         }
88         return chosen, suggestions
89 }