aboutsummaryrefslogtreecommitdiffstats
path: root/commands/prompt.go
blob: f9f5fcc0957f14330a2209ea3fc091454ae873b8 (plain) (blame)
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
package commands

import (
	"fmt"
	"strings"

	"git.sr.ht/~rjarry/aerc/app"
)

type Prompt struct{}

func init() {
	register(Prompt{})
}

func (Prompt) Aliases() []string {
	return []string{"prompt"}
}

func (Prompt) Complete(args []string) []string {
	argc := len(args)
	if argc == 0 {
		return nil
	}
	hascommand := argc > 2
	if argc == 1 {
		args = append(args, "")
	}

	cmd := GlobalCommands.ByName(args[1])
	var cs []string
	if cmd != nil {
		cs = cmd.Complete(args[2:])
		hascommand = true
	} else {
		if hascommand {
			return nil
		}
		cs, _ = GlobalCommands.GetCompletions(args[1])
	}
	if cs == nil {
		return nil
	}

	var b strings.Builder
	// it seems '' quoting is enough
	// to keep quoted arguments in one piece
	b.WriteRune('\'')
	b.WriteString(args[0])
	b.WriteRune('\'')
	b.WriteRune(' ')
	if hascommand {
		b.WriteString(args[1])
		b.WriteRune(' ')
	}

	src := b.String()
	b.Reset()

	rs := make([]string, 0, len(cs))
	for _, c := range cs {
		b.WriteString(src)
		b.WriteString(c)

		rs = append(rs, b.String())
		b.Reset()
	}

	return rs
}

func (Prompt) Execute(args []string) error {
	if len(args) < 3 {
		return fmt.Errorf("Usage: %s <prompt> <cmd>", args[0])
	}

	prompt := args[1]
	cmd := args[2:]
	app.RegisterPrompt(prompt, cmd)
	return nil
}