about summary refs log tree commit diff stats
path: root/edit/008-sandbox-test.mu
Commit message (Expand)AuthorAgeFilesLines
* 2954 - bugfix: $systemKartik K. Agaram2016-05-111-1/+6
* 2864 - replace all address:shared with just addressKartik K. Agaram2016-04-241-18/+18
* 2861 - 'maybe-convert' no longer returns addressKartik K. Agaram2016-04-231-2/+2
* 2853 - purge get-address from edit/ appKartik K. Agaram2016-04-221-14/+13
* 2782 - directly use string literals everywhereKartik K. Agaram2016-03-141-1/+1
* 2735 - define recipes using 'def'Kartik K. Agaram2016-03-081-6/+6
* 2624Kartik K. Agaram2016-02-011-6/+21
* 2623 - bugfix: editing sandboxesKartik K. Agaram2016-02-011-0/+13
* 2590 - support scrolling through sandboxesKartik K. Agaram2016-01-221-1/+1
* 2585 - label sandboxes with a numberKartik K. Agaram2016-01-221-2/+2
* 2576 - distinguish allocated addresses from othersKartik K. Agaram2016-01-191-16/+16
* 2548 - teach 'print' to print integersKartik K. Agaram2015-12-281-1/+2
* 2474 - overload 'copy' and 'equal' for textKartik K. Agaram2015-11-221-1/+1
* 2468 - overload print-character as just 'print'Kartik K. Agaram2015-11-211-1/+1
* 2467 - rename 'string' to 'text' everywhereKartik K. Agaram2015-11-211-3/+3
* 2417 - support mutable ingredients in headersKartik K. Agaram2015-11-101-5/+5
* 2374 - now edit works until layer 8Kartik K. Agaram2015-11-051-6/+4
* 2309Kartik K. Agaram2015-10-281-5/+5
* 2260 - start tracing by depth rather than labelKartik K. Agaram2015-10-061-1/+1
* 2183 - environment + external editor using tmuxKartik K. Agaram2015-09-121-1/+1
* 2160Kartik K. Agaram2015-09-051-0/+173
adding-right: 5px; } .highlight .hll { background-color: #ffffcc } .highlight .c { color: #888888 } /* Comment */ .highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ .highlight .k { color: #008800; font-weight: bold } /* Keyword */ .highlight .ch { color: #888888 } /* Comment.Hashbang */ .highlight .cm { color: #888888 } /* Comment.Multiline */ .highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */ .highlight .cpf { color: #888888 } /* Comment.PreprocFile */ .highlight .c1 { color: #888888 } /* Comment.Single */ .highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */ .highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */ .highlight .ge { font-style: italic } /* Generic.Emph */ .highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */ .highlight .gr { color: #aa0000 } /* Generic.Error */ .highlight .gh { color: #333333 } /* Generic.Heading */ .highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ .highlight .go { color: #888888 } /* Generic.Output */ .highlight .gp { color: #555555 } /* Generic.Prompt */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #666666 } /* Generic.Subheading */ .highlight .gt { color: #aa0000 } /* Generic.Traceback */ .highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #008800 } /* Keyword.Pseudo */ .highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */ .highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */ .highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */ .highlight .na { color: #336699 } /* Name.Attribute */ .highlight .nb { color: #003388 } /* Name.Builtin */ .highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */ .highlight .no { color: #003366; font-weight: bold } /* Name.Constant */ .highlight .nd { color: #555555 } /* Name.Decorator */ .highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */ .highlight .nl { color: #336699; font-style: italic } /* Name.Label */ .highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #336699; font-weight: bold } /* Name.Property */ .highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #336699 } /* Name.Variable */ .highlight .ow { color: #008800 } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */ .highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */ .highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */ .highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */ .highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */ .highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */ .highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
package msg

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

	"git.sr.ht/~sircmpwn/getopt"
	"github.com/emersion/go-imap"
	"github.com/emersion/go-message"
	_ "github.com/emersion/go-message/charset"
	"github.com/emersion/go-message/mail"

	"git.sr.ht/~sircmpwn/aerc/lib"
	"git.sr.ht/~sircmpwn/aerc/widgets"
)

func init() {
	register("reply", Reply)
	register("forward", Reply)
}

func Reply(aerc *widgets.Aerc, args []string) error {
	opts, optind, err := getopt.Getopts(args[1:], "aq")
	if err != nil {
		return err
	}
	if optind != len(args)-1 {
		return errors.New("Usage: reply [-aq]")
	}
	var (
		quote    bool
		replyAll bool
	)
	for _, opt := range opts {
		switch opt.Option {
		case 'a':
			replyAll = true
		case 'q':
			quote = true
		}
	}

	widget := aerc.SelectedTab().(widgets.ProvidesMessage)
	acct := widget.SelectedAccount()
	if acct == nil {
		return errors.New("No account selected")
	}
	conf := acct.AccountConfig()
	us, _ := gomail.ParseAddress(conf.From)
	store := widget.Store()
	msg := widget.SelectedMessage()
	acct.Logger().Println("Replying to email " + msg.Envelope.MessageId)

	var (
		to     []string
		cc     []string
		toList []*imap.Address
	)
	if args[0] == "reply" {
		if len(msg.Envelope.ReplyTo) != 0 {
			toList = msg.Envelope.ReplyTo
		} else {
			toList = msg.Envelope.From
		}
		for _, addr := range toList {
			if addr.PersonalName != "" {
				to = append(to, fmt.Sprintf("%s <%s@%s>",
					addr.PersonalName, addr.MailboxName, addr.HostName))
			} else {
				to = append(to, fmt.Sprintf("<%s@%s>",
					addr.MailboxName, addr.HostName))
			}
		}
		if replyAll {
			for _, addr := range msg.Envelope.Cc {
				cc = append(cc, lib.FormatAddress(addr))
			}
			for _, addr := range msg.Envelope.To {
				address := fmt.Sprintf("%s@%s", addr.MailboxName, addr.HostName)
				if address == us.Address {
					continue
				}
				to = append(to, lib.FormatAddress(addr))
			}
		}
	}

	var subject string
	if args[0] == "forward" {
		subject = "Fwd: " + msg.Envelope.Subject
	} else {
		if !strings.HasPrefix(msg.Envelope.Subject, "Re: ") {
			subject = "Re: " + msg.Envelope.Subject
		} else {
			subject = msg.Envelope.Subject
		}
	}

	composer := widgets.NewComposer(
		aerc.Config(), acct.AccountConfig(), acct.Worker()).
		Defaults(map[string]string{
			"To":          strings.Join(to, ", "),
			"Cc":          strings.Join(cc, ", "),
			"Subject":     subject,
			"In-Reply-To": msg.Envelope.MessageId,
		})

	if args[0] == "reply" {
		composer.FocusTerminal()
	}

	addTab := func() {
		tab := aerc.NewTab(composer, subject)
		composer.OnSubjectChange(func(subject string) {
			if subject == "" {
				tab.Name = "New email"
			} else {
				tab.Name = subject
			}
			tab.Content.Invalidate()
		})
	}

	if args[0] == "forward" {
		// TODO: something more intelligent than fetching the 1st part
		// TODO: add attachments!
		store.FetchBodyPart(msg.Uid, []int{1}, func(reader io.Reader) {
			header := message.Header{}
			header.SetText(
				"Content-Transfer-Encoding", msg.BodyStructure.Encoding)
			header.SetContentType(
				msg.BodyStructure.MIMEType, msg.BodyStructure.Params)
			header.SetText("Content-Description", msg.BodyStructure.Description)
			entity, err := message.New(header, reader)
			if err != nil {
				// TODO: Do something with the error
				addTab()
				return
			}
			mreader := mail.NewReader(entity)
			part, err := mreader.NextPart()
			if err != nil {
				// TODO: Do something with the error
				addTab()
				return
			}

			pipeout, pipein := io.Pipe()
			scanner := bufio.NewScanner(part.Body)
			go composer.SetContents(pipeout)
			// TODO: Let user customize the date format used here
			io.WriteString(pipein, fmt.Sprintf("Forwarded message from %s on %s:\n\n",
				msg.Envelope.From[0].PersonalName,
				msg.Envelope.Date.Format("Mon Jan 2, 2006 at 3:04 PM")))
			for scanner.Scan() {
				io.WriteString(pipein, fmt.Sprintf("%s\n", scanner.Text()))
			}
			pipein.Close()
			pipeout.Close()
			addTab()
		})
	} else {
		if quote {
			var (
				path []int
				part *imap.BodyStructure
			)
			if len(msg.BodyStructure.Parts) != 0 {
				part, path = findPlaintext(msg.BodyStructure, path)
			}
			if part == nil {
				part = msg.BodyStructure
				path = []int{1}
			}

			store.FetchBodyPart(msg.Uid, path, func(reader io.Reader) {
				header := message.Header{}
				header.SetText(
					"Content-Transfer-Encoding", part.Encoding)
				header.SetContentType(part.MIMEType, part.Params)
				header.SetText("Content-Description", part.Description)
				entity, err := message.New(header, reader)
				if err != nil {
					// TODO: Do something with the error
					addTab()
					return
				}
				mreader := mail.NewReader(entity)
				part, err := mreader.NextPart()
				if err != nil {
					// TODO: Do something with the error
					addTab()
					return
				}

				pipeout, pipein := io.Pipe()
				scanner := bufio.NewScanner(part.Body)
				go composer.SetContents(pipeout)
				// TODO: Let user customize the date format used here
				io.WriteString(pipein, fmt.Sprintf("On %s %s wrote:\n",
					msg.Envelope.Date.Format("Mon Jan 2, 2006 at 3:04 PM"),
					msg.Envelope.From[0].PersonalName))
				for scanner.Scan() {
					io.WriteString(pipein, fmt.Sprintf("> %s\n", scanner.Text()))
				}
				pipein.Close()
				pipeout.Close()
				addTab()
			})
		} else {
			addTab()
		}
	}

	return nil
}

func findPlaintext(bs *imap.BodyStructure,
	path []int) (*imap.BodyStructure, []int) {

	for i, part := range bs.Parts {
		cur := append(path, i+1)
		if part.MIMEType == "text" && part.MIMESubType == "plain" {
			return part, cur
		}
		if part.MIMEType == "multipart" {
			if part, path := findPlaintext(part, cur); path != nil {
				return part, path
			}
		}
	}

	return nil, nil
}