aboutsummaryrefslogtreecommitdiffstats
path: root/commands/account/compose.go
blob: fe86a1794557984f27721b69dd1ad321b6d90d3a (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
82
83
package account

import (
	"errors"
	"fmt"
	"io"
	gomail "net/mail"
	"regexp"
	"strings"

	"github.com/emersion/go-message/mail"

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

type Compose struct {
	Headers  string `opt:"-H" action:"ParseHeader"`
	Template string `opt:"-T" complete:"CompleteTemplate"`
	Edit     bool   `opt:"-e"`
	NoEdit   bool   `opt:"-E"`
	Body     string `opt:"..." required:"false"`
}

func init() {
	register(Compose{})
}

func (c *Compose) ParseHeader(arg string) error {
	if strings.Contains(arg, ":") {
		// ensure first colon is followed by a single space
		re := regexp.MustCompile(`^(.*?):\s*(.*)`)
		c.Headers += re.ReplaceAllString(arg, "$1: $2\r\n")
	} else {
		c.Headers += arg + ":\r\n"
	}
	return nil
}

func (*Compose) CompleteTemplate(arg string) []string {
	return commands.GetTemplates(arg)
}

func (Compose) Aliases() []string {
	return []string{"compose"}
}

func (c Compose) Execute(args []string) error {
	if c.Headers != "" {
		if c.Body != "" {
			c.Body = c.Headers + "\r\n" + c.Body
		} else {
			c.Body = c.Headers + "\r\n\r\n"
		}
	}
	if c.Template == "" {
		c.Template = config.Templates.NewMessage
	}
	editHeaders := (config.Compose.EditHeaders || c.Edit) && !c.NoEdit

	acct := app.SelectedAccount()
	if acct == nil {
		return errors.New("No account selected")
	}

	msg, err := gomail.ReadMessage(strings.NewReader(c.Body))
	if errors.Is(err, io.EOF) { // completely empty
		msg = &gomail.Message{Body: strings.NewReader("")}
	} else if err != nil {
		return fmt.Errorf("mail.ReadMessage: %w", err)
	}
	headers := mail.HeaderFromMap(msg.Header)

	composer, err := app.NewComposer(acct,
		acct.AccountConfig(), acct.Worker(), editHeaders,
		c.Template, &headers, nil, msg.Body)
	if err != nil {
		return err
	}
	composer.Tab = app.NewTab(composer, "New email")
	return nil
}