Debian Codegraph @

commands/commands.go

raw
1 package commands
2
3 import (
4 "bytes"
5 "errors"
6 "path"
7 "reflect"
8 "slices"
9 "strings"
10 "unicode"
11
12 "git.sr.ht/~rjarry/go-opt/v2"
13
14 "git.sr.ht/~rjarry/aerc/app"
15 "git.sr.ht/~rjarry/aerc/config"
16 "git.sr.ht/~rjarry/aerc/lib/log"
17 "git.sr.ht/~rjarry/aerc/lib/state"
18 "git.sr.ht/~rjarry/aerc/lib/templates"
19 "git.sr.ht/~rjarry/aerc/models"
20 )
21
22 type CommandContext uint32
23
24 const (
25 NONE = 1 << iota
26 // available everywhere
27 GLOBAL
28 // only when a message list is focused
29 MESSAGE_LIST
30 // only when a message viewer is focused
31 MESSAGE_VIEWER
32 // only when a message composer editor is focused
33 COMPOSE_EDIT
34 // only when a message composer review screen is focused
35 COMPOSE_REVIEW
36 // only when a terminal
37 TERMINAL
38 )
39
40 func CurrentContext() CommandContext {
41 var context CommandContext = GLOBAL
42
43 switch tab := app.SelectedTabContent().(type) {
44 case *app.AccountView:
45 context |= MESSAGE_LIST
46 case *app.Composer:
47 if tab.Bindings() == "compose::review" {
48 context |= COMPOSE_REVIEW
49 } else {
50 context |= COMPOSE_EDIT
51 }
52 case *app.MessageViewer:
53 context |= MESSAGE_VIEWER
54 case *app.Terminal:
55 context |= TERMINAL
56 }
57
58 return context
59 }
60
61 type Command interface {
62 Description() string
63 Context() CommandContext
64 Aliases() []string
65 Execute([]string) error
66 }
67
68 var allCommands map[string]Command
69
70 func Register(cmd Command) {
71 if reflect.TypeOf(cmd).Kind() == reflect.Ptr {
72 panic("programming error: commands must be registered by value, not by pointer")
73 }
74 if allCommands == nil {
75 allCommands = make(map[string]Command)
76 }
77 for _, alias := range cmd.Aliases() {
78 if allCommands[alias] != nil {
79 panic("duplicate command alias: " + alias)
80 }
81 allCommands[alias] = cmd
82 }
83 }
84
85 func ActiveCommands() []Command {
86 var cmds []Command
87 context := CurrentContext()
88 seen := make(map[reflect.Type]bool)
89
90 for _, cmd := range allCommands {
91 t := reflect.TypeOf(cmd)
92 if seen[t] {
93 continue
94 }
95 seen[t] = true
96 if cmd.Context()&context != 0 {
97 cmds = append(cmds, cmd)
98 }
99 }
100
101 return cmds
102 }
103
104 func ActiveCommandNames() []string {
105 var names []string
106 context := CurrentContext()
107
108 for alias, cmd := range allCommands {
109 if cmd.Context()&context != 0 {
110 names = append(names, alias)
111 }
112 }
113
114 return names
115 }
116
117 type NoSuchCommand string
118
119 func (err NoSuchCommand) Error() string {
120 return "Unknown command " + string(err)
121 }
122
123 // Expand non-ambiguous command abbreviations.
124 //
125 // q --> quit
126 // ar --> archive
127 // im --> import-mbox
128 func ExpandAbbreviations(name string) (string, Command, error) {
129 context := CurrentContext()
130 name = strings.TrimLeft(name, ": \t")
131
132 cmd, found := allCommands[name]
133 if found && cmd.Context()&context != 0 {
134 return name, cmd, nil
135 }
136
137 var candidate Command
138 var candidateName string
139
140 for alias, cmd := range allCommands {
141 if cmd.Context()&context == 0 || !strings.HasPrefix(alias, name) {
142 continue
143 }
144 if candidate != nil {
145 // We have more than one command partially
146 // matching the input.
147 return name, nil, NoSuchCommand(name)
148 }
149 // We have a partial match.
150 candidate = cmd
151 candidateName = alias
152 }
153
154 if candidate == nil {
155 return name, nil, NoSuchCommand(name)
156 }
157
158 return candidateName, candidate, nil
159 }
160
161 func ResolveCommand(
162 cmdline string, acct *config.AccountConfig, msg *models.MessageInfo,
163 ) (string, Command, error) {
164 cmdline, err := ExpandTemplates(cmdline, acct, msg)
165 if err != nil {
166 return "", nil, err
167 }
168 name, rest, didCut := strings.Cut(cmdline, " ")
169 name, cmd, err := ExpandAbbreviations(name)
170 if err != nil {
171 return "", nil, err
172 }
173 cmdline = name
174 if didCut {
175 cmdline += " " + rest
176 }
177 return cmdline, cmd, nil
178 }
179
180 func templateData(
181 cfg *config.AccountConfig,
182 msg *models.MessageInfo,
183 ) models.TemplateData {
184 var folder *models.Directory
185
186 acct := app.SelectedAccount()
187 if acct != nil {
188 folder = acct.Directories().SelectedDirectory()
189 }
190 if cfg == nil && acct != nil {
191 cfg = acct.AccountConfig()
192 }
193 if msg == nil && acct != nil {
194 msg, _ = acct.SelectedMessage()
195 }
196
197 data := state.NewDataSetter()
198 data.SetAccount(cfg)
199 data.SetFolder(folder)
200 data.SetInfo(msg, 0, false)
201 if acct != nil {
202 acct.SetStatus(func(s *state.AccountState, _ string) {
203 data.SetState(s)
204 })
205 }
206
207 return data.Data()
208 }
209
210 func ExecuteCommand(cmd Command, cmdline string) error {
211 args := opt.LexArgs(cmdline)
212 if args.Count() == 0 {
213 return errors.New("No arguments")
214 }
215 log.Tracef("executing command %s", args.String())
216 // copy zeroed struct
217 tmp := reflect.New(reflect.TypeOf(cmd)).Interface().(Command)
218 if err := opt.ArgsToStruct(args.Clone(), tmp); err != nil {
219 return err
220 }
221 return tmp.Execute(args.Args())
222 }
223
224 // expand template expressions
225 func ExpandTemplates(
226 s string, cfg *config.AccountConfig, msg *models.MessageInfo,
227 ) (string, error) {
228 if strings.Contains(s, "{{") && strings.Contains(s, "}}") {
229 t, err := templates.ParseTemplate("execute", s)
230 if err != nil {
231 return "", err
232 }
233
234 data := templateData(cfg, msg)
235
236 var buf bytes.Buffer
237 err = templates.Render(t, &buf, data)
238 if err != nil {
239 return "", err
240 }
241
242 s = buf.String()
243 }
244
245 return s, nil
246 }
247
248 func GetTemplateCompletion(
249 cmd string,
250 ) ([]string, string, bool) {
251 countLeft := strings.Count(cmd, "{{")
252 if countLeft == 0 {
253 return nil, "", false
254 }
255 countRight := strings.Count(cmd, "}}")
256
257 switch {
258 case countLeft > countRight:
259 // complete template terms
260 var i int
261 for i = len(cmd) - 1; i >= 0; i-- {
262 if strings.ContainsRune("{()| ", rune(cmd[i])) {
263 break
264 }
265 }
266 search, prefix := cmd[i+1:], cmd[:i+1]
267 padding := strings.Repeat(" ",
268 len(search)-len(strings.TrimLeft(search, " ")))
269 options := FilterList(
270 templates.Terms(),
271 strings.TrimSpace(search),
272 nil,
273 )
274 return options, prefix + padding, true
275 case countLeft == countRight:
276 // expand template
277 s, err := ExpandTemplates(cmd, nil, nil)
278 if err != nil {
279 log.Warnf("template rendering failed: %v", err)
280 return nil, "", false
281 }
282 return []string{s}, "", true
283 }
284
285 return nil, "", false
286 }
287
288 // GetCompletions returns the completion options and the command prefix
289 func GetCompletions(
290 cmd Command, args *opt.Args,
291 ) (options []opt.Completion, prefix string) {
292 // copy zeroed struct
293 tmp := reflect.New(reflect.TypeOf(cmd)).Interface().(Command)
294 s, err := args.ArgSafe(0)
295 if err != nil {
296 log.Errorf("completions error: %v", err)
297 return options, prefix
298 }
299 spec := opt.NewCmdSpec(s, tmp)
300 return spec.GetCompletions(args)
301 }
302
303 func GetFolders(arg string) []string {
304 acct := app.SelectedAccount()
305 if acct == nil {
306 return make([]string, 0)
307 }
308 return FilterList(acct.Directories().List(), arg, nil)
309 }
310
311 func GetTemplates(arg string) []string {
312 templates := make(map[string]bool)
313 for _, dir := range config.Templates().TemplateDirs {
314 for _, f := range listDir(dir, false) {
315 if !isDir(path.Join(dir, f)) {
316 templates[f] = true
317 }
318 }
319 }
320 names := make([]string, 0, len(templates))
321 for n := range templates {
322 names = append(names, n)
323 }
324 slices.Sort(names)
325 return FilterList(names, arg, nil)
326 }
327
328 func GetLabels(arg string) []string {
329 acct := app.SelectedAccount()
330 if acct == nil {
331 return make([]string, 0)
332 }
333 var prefix string
334 if arg != "" {
335 // + and - are used to denote tag addition / removal and need to
336 // be striped only the last tag should be completed, so that
337 // multiple labels can be selected
338 switch arg[0] {
339 case '+':
340 prefix = "+"
341 case '-':
342 prefix = "-"
343 }
344 arg = strings.TrimLeft(arg, "+-")
345 }
346 return FilterList(acct.Labels(), arg, func(s string) string {
347 return opt.QuoteArg(prefix+s) + " "
348 })
349 }
350
351 // hasCaseSmartPrefix checks whether s starts with prefix, using a case
352 // sensitive match if and only if prefix contains upper case letters.
353 func hasCaseSmartPrefix(s, prefix string) bool {
354 if hasUpper(prefix) {
355 return strings.HasPrefix(s, prefix)
356 }
357 return strings.HasPrefix(strings.ToLower(s), strings.ToLower(prefix))
358 }
359
360 func hasUpper(s string) bool {
361 for _, r := range s {
362 if unicode.IsUpper(r) {
363 return true
364 }
365 }
366 return false
367 }