Skip to main content

rmut_core/
config.rs

1//! TOML configuration from $RMUT_CONFIG or ~/.config/rmut/config.toml.
2//!
3//! ```toml
4//! [identity]
5//! name = "Jane Doe"
6//! email = "jane@example.com"
7//! reverse_name = false  # reply From = the address the mail came to
8//!
9//! [[identities]]        # conditional identity (folder-/send-hook)
10//! folder = "*work*"     # glob on the open mailbox, and/or:
11//! recipient = "*@work.example.com"   # glob on a draft recipient
12//! name = "Jane Work"
13//! email = "jane@work.example.com"
14//!
15//! [mail]
16//! alternates = ["jane@old\\.example\\.com"]  # my other addresses
17//! my_hdr = ["Organization: Acme"]        # on every draft
18//! mailboxes = ["~/Maildir", "~/Maildir/.Sent"]
19//! sent = "~/Maildir/.Sent"
20//! postponed = "~/Maildir/.Drafts"
21//! sendmail = "/usr/sbin/sendmail"
22//! editor = "vim"
23//! poll_seconds = 5
24//! print = "lpr"
25//!
26//! [index]
27//! format = "%4C %Z %-6d %-15.15L (%?l?%4l&%4c?) %s"
28//!
29//! [ui]
30//! theme = "default"   # or "mono"
31//!
32//! [colors]            # overrides: status_fg status_bg deleted flagged header
33//! deleted = "red"
34//!
35//! [keys.index]        # action = key, e.g. sync = "w", delete = "ctrl+d"
36//! [keys.pager]
37//!
38//! [[accounts]]        # remote account, opened as imap:name/FOLDER
39//! name = "work"
40//! user = "jane@example.com"
41//! password_command = "pass show mail/work"   # or: password = "..."
42//! imap_host = "imap.example.com"   # imap_port = 993, imap_tls = true
43//! smtp_host = "smtp.example.com"   # smtp_port = 587, smtp_tls = true
44//! sent_folder = "Sent"             # Fcc target via IMAP APPEND
45//!
46//! [[folder_hooks]]      # mutt's folder-hook, any `:` command line
47//! folder = "*work*"
48//! command = "set index_format=\"%4C %Z %-6d %-20.20F %s\""
49//!
50//! [[message_hooks]]     # applied while the message is selected
51//! pattern = "~f boss@example.com"
52//! command = "set pager_context=5"
53//!
54//! [[reply_hooks]]       # applied while a reply to it is built
55//! pattern = "~t @work.example.com"
56//! command = "set from=jane@work.example.com"
57//!
58//! [[fcc_hooks]]         # where the sent copy goes
59//! pattern = "~t @work.example.com"
60//! mailbox = "~/Maildir/.WorkSent"
61//!
62//! [[crypt_hooks]]       # encrypt to this key for this recipient
63//! address = "boss@example.com"
64//! key = "0xDEADBEEF"
65//!
66//! [pgp]
67//! command = "gpg"              # runs via $PATH; passphrases come from
68//! sign_key = "jane@example.com"  # the gpg agent, never from rmut
69//! sign_by_default = false
70//! encrypt_by_default = false
71//! ```
72
73use std::collections::HashMap;
74use std::path::PathBuf;
75
76use anyhow::{Context, Result, ensure};
77use serde::Deserialize;
78
79#[derive(Debug, Clone, Default, Deserialize)]
80#[serde(default)]
81pub struct Config {
82    pub identity: Identity,
83    pub mail: Mail,
84    pub index: Index,
85    pub pager: Pager,
86    pub ui: Ui,
87    pub gui: Gui,
88    pub net: Net,
89    pub sidebar: Sidebar,
90    pub colors: HashMap<String, String>,
91    /// Pattern → color rules for index lines, evaluated in order.
92    pub color_index: Vec<ColorRule>,
93    /// Regex → color rules for pager body spans (mutt's `color body`),
94    /// applied in order; `pattern` here is a plain regex, not a
95    /// message pattern.
96    pub color_body: Vec<ColorRule>,
97    /// MIME type → shell command that renders the part (stdin → stdout),
98    /// e.g. "text/html" = "w3m -dump -T text/html", mutt's auto_view.
99    /// Applied to matching parts wherever they sit in the message,
100    /// preferred in multipart/alternative, and used in the attachment
101    /// viewer. An empty command means mutt's arrangement: the command
102    /// comes from mailcap, from the first `copiousoutput` entry for
103    /// the type; a type with no such entry simply does not autoview.
104    pub filters: HashMap<String, String>,
105    pub keys: Keys,
106    /// Macros: a key that replays a sequence of keys, per menu:
107    /// [macros.index] / [macros.pager], `key = "sequence"`. The
108    /// sequence is literal characters plus `<enter>`/`<esc>`/
109    /// `<ctrl+x>`/... names in angle brackets; it feeds the input
110    /// queue, so it can drive prompts.
111    pub macros: Keys,
112    pub accounts: Vec<Account>,
113    /// Conditional identities, applied in order over `identity` when
114    /// their globs match: the minimal folder-hook / send-hook.
115    pub identities: Vec<IdentityRule>,
116    /// mutt's folder-hook with an arbitrary command: enter-command
117    /// lines run when a matching mailbox is opened.
118    pub folder_hooks: Vec<FolderHook>,
119    /// mutt's message-hook: lines applied while a matching message is
120    /// the selected one, and taken back off when it stops matching.
121    pub message_hooks: Vec<MessageHook>,
122    /// mutt's reply-hook: lines applied while a reply to a matching
123    /// message is built.
124    pub reply_hooks: Vec<MessageHook>,
125    /// mutt's fcc-hook: where a matching outgoing message's copy goes.
126    pub fcc_hooks: Vec<FccHook>,
127    /// mutt's crypt-hook: the PGP key to encrypt to for a recipient.
128    pub crypt_hooks: Vec<CryptHook>,
129    pub pgp: Pgp,
130}
131
132/// One `[[folder_hooks]]` entry: mutt's folder-hook. Like mutt, a
133/// folder-hook is not undone when you leave the mailbox, so a
134/// catch-all entry (`folder = "*"`) is the way to put a setting back.
135#[derive(Debug, Clone, Default, Deserialize)]
136#[serde(default)]
137pub struct FolderHook {
138    /// Glob (`*`) on the opened mailbox: a path or an `imap:` spec.
139    pub folder: String,
140    /// One enter-command line, e.g. `set index_format="%s"`.
141    pub command: String,
142}
143
144/// One `[[message_hooks]]` or `[[reply_hooks]]` entry: a message
145/// pattern and the enter-command line it runs.
146#[derive(Debug, Clone, Default, Deserialize)]
147#[serde(default)]
148pub struct MessageHook {
149    pub pattern: String,
150    pub command: String,
151}
152
153/// One `[[fcc_hooks]]` entry: the mailbox a matching outgoing
154/// message's copy goes to (a local maildir path).
155#[derive(Debug, Clone, Default, Deserialize)]
156#[serde(default)]
157pub struct FccHook {
158    /// Message pattern matched against the draft being sent.
159    pub pattern: String,
160    pub mailbox: String,
161}
162
163/// One `[[crypt_hooks]]` entry: encrypt to `key` for any recipient
164/// address matching `address` (a case-insensitive regex).
165#[derive(Debug, Clone, Default, Deserialize)]
166#[serde(default)]
167pub struct CryptHook {
168    pub address: String,
169    pub key: String,
170}
171
172#[derive(Debug, Clone, Default, Deserialize)]
173#[serde(default)]
174pub struct Identity {
175    pub name: Option<String>,
176    pub email: Option<String>,
177    /// mutt's reverse_name: a reply's From becomes whichever of your
178    /// addresses the original was sent to.
179    pub reverse_name: bool,
180    /// mutt's $reverse_realname: the display name comes over with the
181    /// address reverse_name found. True unless set otherwise, as in
182    /// mutt; false keeps the configured name and takes the address
183    /// alone.
184    pub reverse_realname: Option<bool>,
185}
186
187/// One `[[identities]]` entry. With both globs set, both must match;
188/// with neither, it always applies. Unset name/email keep the value
189/// from the layer below.
190#[derive(Debug, Clone, Default, Deserialize)]
191#[serde(default)]
192pub struct IdentityRule {
193    /// Glob (`*`) on the open mailbox: a path or an `imap:` spec.
194    pub folder: Option<String>,
195    /// Glob (`*`) on any recipient address of the draft.
196    pub recipient: Option<String>,
197    pub name: Option<String>,
198    pub email: Option<String>,
199}
200
201#[derive(Debug, Clone, Default, Deserialize)]
202#[serde(default)]
203pub struct Mail {
204    /// mutt's $folder: where mailboxes live, so `=x` and `+x` name a
205    /// mailbox under it, at a prompt or in a macro. An IMAP account
206    /// spec works too ("imap:work"), making `=Archive` mean
207    /// imap:work/Archive.
208    pub folder: Option<String>,
209    pub mailboxes: Vec<String>,
210    pub sent: Option<String>,
211    pub postponed: Option<String>,
212    pub sendmail: Option<String>,
213    pub editor: Option<String>,
214    /// mutt's $ispell: the spell checker the compose menu's `i` runs
215    /// over the draft, as `ispell -x FILE`. "ispell" when unset.
216    pub ispell: Option<String>,
217    pub poll_seconds: Option<u64>,
218    /// Shell command the printed message is piped to (default lpr).
219    pub print: Option<String>,
220    /// mutt's $pipe_decode: pipe the decoded message (brief headers,
221    /// decoded body) rather than the raw one. Off by default.
222    pub pipe_decode: Option<bool>,
223    /// mutt's $print_decode: print the decoded message. On by
224    /// default, as in mutt.
225    pub print_decode: Option<bool>,
226    /// mutt's $pipe_split / $print_split: run the command once per
227    /// tagged message instead of once over them all. Off by default.
228    pub pipe_split: Option<bool>,
229    pub print_split: Option<bool>,
230    /// mutt's $pipe_sep: what separates concatenated messages in one
231    /// pipe run. Newline by default.
232    pub pipe_sep: Option<String>,
233    /// Default target offered by `s` (save message to a mailbox).
234    pub save: Option<String>,
235    /// "inline" (quoted text, the default) or "attach" (the original
236    /// goes along as a message/rfc822 part, mutt's mime_forward).
237    pub forward: Option<String>,
238    /// mutt's query_command: external address lookup for Tab
239    /// completion at the To prompt (`%s` = the word, or appended),
240    /// e.g. "khard email --parsable %s".
241    pub query_command: Option<String>,
242    /// mutt's $trash: purged messages move here (a maildir path, or
243    /// `imap:account/folder` of the open account) instead of being
244    /// erased; purging inside the trash itself deletes for real.
245    pub trash: Option<String>,
246    /// mutt's edit_headers (default false, like mutt): true puts the
247    /// draft's header block (From/To/Cc/Subject, Attach: lines) into
248    /// the editor buffer. Off, the prompts set To/Subject and
249    /// attachments go through the compose menu's a.
250    pub edit_headers: Option<bool>,
251    /// notmuch(1) search (`X`): false disables the key; unset/true
252    /// leaves it on (notmuch itself must be installed; keep the
253    /// database fresh with `notmuch new` in a hook or cron).
254    pub notmuch: Option<bool>,
255    /// mutt's $fast_reply: replies skip the To and Subject prompts,
256    /// forwards skip Subject (the ask-yes questions still run).
257    pub fast_reply: bool,
258    /// mutt's $quit: "yes" (the default) leaves at once, "no"
259    /// refuses, "ask-yes" and "ask-no" ask first.
260    pub quit: Option<String>,
261    /// mutt's $postpone: leaving a draft. "ask-yes" (the default) and
262    /// "ask-no" ask whether to postpone (else discard); "yes"
263    /// postpones without asking, "no" discards without asking.
264    pub postpone: Option<String>,
265    /// mutt's $recall: composing when postponed drafts exist. "no"
266    /// never offers to recall (always a new message); "yes" recalls
267    /// the newest without asking; "ask-yes" / "ask-no" (the default
268    /// is to ask) offer the new/recall choice.
269    pub recall: Option<String>,
270    /// mutt's $confirmappend: ask before adding messages to a mailbox
271    /// that already exists. Off by default, where mutt asks: rmut has
272    /// never asked, and a save is one keystroke either way.
273    pub confirmappend: bool,
274    /// mutt's $save_name: the default save target is the sender's
275    /// local part under $folder, when such a mailbox exists.
276    pub save_name: bool,
277    /// mutt's $force_name: the same, whether or not it exists.
278    pub force_name: bool,
279    /// mutt's $mark_old: unread mail left behind in the mailbox ages
280    /// to old (O in the index, out of the new count) when you leave.
281    /// True unless set otherwise, as in mutt.
282    pub mark_old: Option<bool>,
283    /// mutt's $delete_untag: marking a tagged message for deletion
284    /// (d, or a save) takes its tag off. True unless set otherwise,
285    /// as in mutt.
286    pub delete_untag: Option<bool>,
287    /// mutt's $flag_safe: a flagged message cannot be marked for
288    /// deletion, by any of the ways of doing so. Off by default.
289    pub flag_safe: bool,
290    /// mutt's $maildir_trash: a purge gives deleted messages the
291    /// maildir T flag instead of unlinking them; they stay in the
292    /// index marked D. Maildir only. Off by default.
293    pub maildir_trash: bool,
294    /// mutt's $mail_check_recent: "new mail in X" only when X has
295    /// grown since the last look. False announces any mailbox holding
296    /// new mail, once, until it empties. True unless set otherwise.
297    pub mail_check_recent: Option<bool>,
298    /// mutt's $sort_alias: the order address completion offers alias
299    /// expansions in: "address" (by the expansion, the default here),
300    /// "alias" (by nick). "unsorted" reads as "alias": the alias file
301    /// is a map. A "reverse-" prefix flips it.
302    pub sort_alias: Option<String>,
303    /// mutt's $shell: what a bare `!` (an empty shell command) runs
304    /// interactively. $SHELL, then sh, when unset.
305    pub shell: Option<String>,
306    /// mutt's $tmpdir: where temporary files go (drafts on their way
307    /// to the editor, parts on their way to a viewer). $TMPDIR, then
308    /// /tmp, when unset.
309    pub tmpdir: Option<String>,
310    /// mutt's $check_new: look for mail delivered to the open maildir
311    /// while it is open. False stops the rescan (IMAP is unaffected,
312    /// as in mutt). True unless set otherwise.
313    pub check_new: Option<bool>,
314    /// mutt's $print: what `p` does. "ask-no" (the default) asks with
315    /// Enter declining, "ask-yes" asks with Enter printing, "yes"
316    /// prints without asking and "no" refuses to print at all.
317    pub print_confirm: Option<String>,
318    /// mutt's $alias_file: where aliases are read from and where
319    /// create-alias appends. $RMUT_ALIASES, then
320    /// ~/.config/rmut/aliases, when unset.
321    pub alias_file: Option<String>,
322    /// mutt's $attribution: the line a quoted reply opens with, over
323    /// the message being replied to (%a address, %n name, %f the From
324    /// header, %s subject, %i message-id, %d date, %{...} strftime).
325    pub attribution: Option<String>,
326    /// mutt's $indent_string: what each quoted line is prefixed with,
327    /// `"> "` by default.
328    pub indent_string: Option<String>,
329    /// mutt's $forward_format: the subject a forward carries, the
330    /// same format string over the message being forwarded.
331    pub forward_format: Option<String>,
332    /// mutt's $wrap_search: `n` wraps around the ends of the index.
333    /// True by default, as in mutt; false stops at the last / first
334    /// match instead.
335    pub wrap_search: Option<bool>,
336    /// mutt's $simple_search: the template a bare-word search expands
337    /// to, `%s` the word. Default `~f %s | ~s %s` (from or subject),
338    /// which is what a bare word already did; set it to add `~b %s`
339    /// for the body, say. Only a single word with no `~` expands.
340    pub simple_search: Option<String>,
341    /// mutt's $reply_regexp: what a reply's subject may already start
342    /// with ("Re:" with an optional [n], by default). Replying takes
343    /// it off and puts "Re: " on, so prefixes never pile up; a
344    /// locale's own prefixes go in as `^(re|aw|sv):[ \t]*`.
345    /// Case-insensitive unless the regex has an uppercase letter, as
346    /// mutt compiles it.
347    pub reply_regexp: Option<String>,
348    /// mutt's $include: quote the original in a reply? "ask-yes" (the
349    /// default) and "ask-no" ask, "yes" and "no" decide it.
350    pub include: Option<String>,
351    /// mutt's $forward_quote: the forwarded text inside the
352    /// "----- Forwarded message" markers is quoted with
353    /// $indent_string, the way a reply is.
354    pub forward_quote: bool,
355    /// mutt's $signature: a file whose contents end every new draft,
356    /// or, when the name ends in `|`, a command whose output does.
357    /// `~` is expanded. Unset (the default) appends nothing.
358    pub signature: Option<String>,
359    /// mutt's $sig_dashes: the signature is introduced by a line
360    /// holding "-- ". True unless set otherwise, as in mutt.
361    pub sig_dashes: Option<bool>,
362    /// mutt's $sig_on_top: the signature goes above the quoted
363    /// original rather than below it. Off by default, as in mutt.
364    pub sig_on_top: Option<bool>,
365    /// mutt's $hostname: the host in a generated Message-ID. The
366    /// system hostname when unset.
367    pub hostname: Option<String>,
368    /// mutt's $user_agent: add a `User-Agent: rmut/VERSION` header to
369    /// outgoing mail. Off by default, as neomutt has it.
370    pub user_agent: Option<bool>,
371    /// mutt's $abort_nosubject: a draft with an empty subject.
372    /// "ask-yes" (the default) asks with Enter aborting, "ask-no"
373    /// asks with Enter sending it on, "yes" aborts without asking,
374    /// "no" never asks.
375    pub abort_nosubject: Option<String>,
376    /// mutt's $abort_unmodified: the first editor pass came back with
377    /// the body untouched, so the draft is dropped. True unless set
378    /// otherwise, as in mutt; only the first edit is checked.
379    pub abort_unmodified: Option<bool>,
380    /// mutt's $askcc / $askbcc: ask for those recipients when a draft
381    /// is started, prefilled with what a group reply worked out.
382    pub ask_cc: bool,
383    pub ask_bcc: bool,
384    /// mutt's $autoedit (needs edit_headers): skip every initial
385    /// prompt and question, straight into the editor; the compose
386    /// menu follows as usual.
387    pub autoedit: bool,
388    /// mutt's $copy: false skips the sent copy (Fcc) entirely; an
389    /// Fcc set in the compose menu still wins.
390    pub copy: Option<bool>,
391    /// mutt's `lists`: address patterns naming mailing lists you know
392    /// of. They drive `~l`, the `L` list-reply target, and the
393    /// Mail-Followup-To rmut sets on mail to a list.
394    pub lists: Vec<String>,
395    /// mutt's `subscribe`: lists you are on. Subscribed lists count as
396    /// known lists too, and a reply to one leaves your own address out
397    /// of Mail-Followup-To, so the list copy is the only one you get.
398    pub subscribed: Vec<String>,
399    /// mutt's `alternates`: regexes matching your other addresses
400    /// (aliases, an old domain, a role address). They join the
401    /// identity addresses everywhere rmut asks "is this me?": `~p`
402    /// and `~P`, the `+`/`T`/`C`/`F` index marks, reverse_name, the
403    /// group-reply dedup, and Mail-Followup-To.
404    pub alternates: Vec<String>,
405    /// mutt's `my_hdr`: header lines added to every draft, e.g.
406    /// "Organization: Acme" or "Bcc: me@example.com". One naming a
407    /// header rmut already wrote replaces it (so `From:` and
408    /// `Reply-To:` win); To/Cc/Bcc gain the address instead.
409    pub my_hdr: Vec<String>,
410    /// mutt's $metoo: keep your own address among a group reply's
411    /// recipients instead of dropping it.
412    pub metoo: bool,
413    /// mutt's $text_flowed: outgoing text/plain is declared
414    /// `format=flowed` and space-stuffed (RFC 3676), so a reader can
415    /// rewrap it. The paragraphs themselves come from your editor,
416    /// which has to leave a trailing space on a line that continues.
417    pub text_flowed: bool,
418    /// Shell command run when new mail arrives (neomutt's
419    /// new_mail_command): `%f` = the mailbox, `%n` = how many, e.g.
420    /// "notify-send 'rmut: %n new in %f'". Fire-and-forget.
421    pub new_mail_command: Option<String>,
422    /// mutt's $delete (a quadoption): what `$` and quitting do with
423    /// messages marked for deletion. "ask" (the default) asks, with
424    /// Enter taking the yes; "yes" purges them without asking; "no"
425    /// never purges, so the marks stay for a later change of mind.
426    pub delete: Option<String>,
427    /// neomutt's $abort_noattach: what to do when the body mentions
428    /// an attachment and none is attached. "no" (the default) never
429    /// checks, "ask" asks before sending, "yes" refuses the send.
430    /// neomutt's ask-yes / ask-no both import as "ask".
431    pub abort_noattach: Option<String>,
432    /// neomutt's $abort_noattach_regex: what counts as mentioning one.
433    /// Case-insensitive; the default is
434    /// `\b(attach|attached|attaching|attachment|attachments)\b`.
435    pub attach_keyword: Option<String>,
436    /// Seconds a sent message waits before it actually goes out, so
437    /// `z` can take it back (rmut's own; mutt sends at once). 0 is
438    /// off. A held message is sent when the timer runs out or when
439    /// rmut exits; batch sends (-s and friends) never hold.
440    pub undo_send: u64,
441    /// mutt's $use_envelope_from: tell sendmail the envelope sender
442    /// (`-f`), which is `envelope_from_address` when set and the
443    /// message's From otherwise. Over SMTP the envelope sender is
444    /// always given; this only decides whether it is the From.
445    pub use_envelope_from: bool,
446    /// mutt's $envelope_from_address: the envelope sender (bounces
447    /// go there) when `use_envelope_from` is on.
448    pub envelope_from_address: Option<String>,
449    /// mutt's $dsn_notify: when delivery status notifications come
450    /// back, e.g. "failure,delay" (or "never"). Passed to sendmail as
451    /// `-N`, and to an SMTP server that offers DSN as NOTIFY=.
452    pub dsn_notify: Option<String>,
453    /// mutt's $dsn_return: how much of the message a notification
454    /// carries back, "hdrs" or "full". sendmail's `-R`, SMTP's RET=.
455    pub dsn_return: Option<String>,
456    /// mutt's $reply_self: a reply to a message I sent goes to me.
457    /// Off (mutt's default), it goes to that message's recipients.
458    pub reply_self: bool,
459    /// mutt's $fcc_attach (a quadoption, "yes" by default): whether
460    /// the sent copy keeps the attachments. "no" keeps the text
461    /// alone; "ask-yes" / "ask-no" ask at send time.
462    pub fcc_attach: Option<String>,
463    /// mutt's $fcc_clear: the sent copy of a signed or encrypted
464    /// message is kept in the clear.
465    pub fcc_clear: bool,
466    /// mutt's $forward_edit (a quadoption, "yes" by default): whether
467    /// a forward opens the editor before the compose menu.
468    pub forward_edit: Option<String>,
469    /// mutt's $mime_forward_rest (on by default): forwarding a part
470    /// that does not read as text from the attachment menu attaches
471    /// it; off, such a part is not forwarded.
472    pub mime_forward_rest: Option<bool>,
473    /// Markdown compose (rmut's own, off by default): a draft goes out
474    /// as multipart/alternative, the text/plain as typed and a
475    /// text/html rendered from it as markdown. The compose menu's `M`
476    /// turns it on or off for the one draft.
477    pub markdown: bool,
478}
479
480impl Mail {
481    /// The envelope a submission carries: the sender sendmail is told
482    /// about, and the DSN requests.
483    pub fn envelope(&self, from: &str) -> crate::smtp::Envelope {
484        let sender = self.use_envelope_from.then(|| {
485            self.envelope_from_address
486                .clone()
487                .filter(|a| !a.trim().is_empty())
488                .map(|a| crate::compose::bare_address(&a).unwrap_or(a))
489                .unwrap_or_else(|| from.to_string())
490        });
491        crate::smtp::Envelope {
492            sender,
493            notify: self.dsn_notify.clone().filter(|v| !v.trim().is_empty()),
494            ret: self.dsn_return.clone().filter(|v| !v.trim().is_empty()),
495        }
496    }
497}
498
499#[derive(Debug, Clone, Default, Deserialize)]
500#[serde(default)]
501pub struct Index {
502    pub format: Option<String>,
503    /// Initial sort: date/from/subject/size/threads, "reverse-" prefix
504    /// allowed (the `o` menu can still change it at runtime).
505    pub sort: Option<String>,
506    /// "last-date-sent" orders threads by their newest message instead
507    /// of the default oldest-first.
508    pub sort_aux: Option<String>,
509    /// chrono strftime string for the index date column (mutt's
510    /// date_format), e.g. "%d.%m.%Y"; default "%b %e", like mutt's
511    /// index date.
512    pub date_format: Option<String>,
513    /// mutt's $collapse_unread (default true, as in mutt): a thread
514    /// holding unread mail folds like any other. False leaves those
515    /// threads open when everything else folds.
516    pub collapse_unread: Option<bool>,
517    /// mutt's $uncollapse_jump: unfolding a thread puts the cursor on
518    /// its first unread message.
519    pub uncollapse_jump: bool,
520    /// mutt's $hide_thread_subject: a thread reply whose subject
521    /// matches its parent's shows a blank subject (just the tree
522    /// arrow). Off by default here, where mutt has it on, so rmut's
523    /// look is unchanged unless asked.
524    pub hide_thread_subject: Option<bool>,
525    /// mutt's $uncollapse_new: a collapsed thread that receives a new
526    /// message unfolds. True unless set otherwise, as in mutt.
527    pub uncollapse_new: Option<bool>,
528    /// mutt's $strict_threads: thread by In-Reply-To and References
529    /// only. False (the default, as in mutt) also groups a root whose
530    /// subject repeats one already in the mailbox, which is what
531    /// threads mail that arrives without those headers at all.
532    pub strict_threads: Option<bool>,
533    /// mutt's $sort_re: the subject grouping only takes a root whose
534    /// subject carries the $reply_regexp prefix. True by default, as
535    /// in mutt; false groups any equal subject, unrelated "hi" mail
536    /// included.
537    pub sort_re: Option<bool>,
538}
539
540#[derive(Debug, Clone, Default, Deserialize)]
541#[serde(default)]
542pub struct Pager {
543    /// Lines of the message index kept visible above the pager.
544    pub index_lines: u16,
545    /// Lines of overlap when paging (mutt's pager_context).
546    pub context: usize,
547    /// mutt's $search_context: lines of context kept above a pager
548    /// search hit scrolled toward the top. Default 0.
549    pub search_context: usize,
550    /// text/html with no auto_view filter renders through the
551    /// built-in html-to-text (not mutt's; links keep their targets,
552    /// blockquotes become `> `). `"raw"` restores mutt's literal
553    /// source view.
554    pub html: Option<String>,
555    /// mutt's $quote_regexp: classifies quoted body lines (depth =
556    /// quote characters in the match). Default `^([ \t]*[|>:}#])+`.
557    pub quote_regexp: Option<String>,
558    /// mutt's ignore list: header-name prefixes hidden from the brief
559    /// view (`*` = all). Unset keeps the classic view (everything
560    /// hidden except Date/From/To/Cc/Subject).
561    pub ignore: Option<Vec<String>>,
562    /// mutt's unignore list: prefixes shown even when ignored.
563    pub unignore: Option<Vec<String>>,
564    /// mutt's hdr_order: name prefixes sorting the brief view;
565    /// unlisted headers follow in message order.
566    pub hdr_order: Option<Vec<String>>,
567    /// mutt's $pager_format for the pager's bottom line; the default
568    /// reproduces the classic "---Message n/m: subject -- NN%".
569    pub format: Option<String>,
570    /// mutt's $wrap: wrap body text at N columns (negative = a right
571    /// margin of |N|); unset wraps at the window width.
572    pub wrap: Option<i64>,
573    /// mutt's $tilde: pad the rows below end-of-message with ~.
574    pub tilde: bool,
575    /// mutt's $pager_stop: paging past the end of a message stays
576    /// put instead of opening the next one.
577    pub pager_stop: bool,
578    /// mutt's $markers (default true, as in mutt): the `+` at the
579    /// start of a wrapped continuation line.
580    pub markers: Option<bool>,
581    /// mutt's $smart_wrap (default true, as in mutt): wrapped lines
582    /// break at a word boundary rather than at the column.
583    pub smart_wrap: Option<bool>,
584    /// mutt's $reflow_text (default true): a `format=flowed` part is
585    /// put back into paragraphs and wrapped at the display width
586    /// instead of keeping the sender's line breaks.
587    pub reflow_text: Option<bool>,
588    /// mutt's alternative_order: MIME types, most wanted first, that
589    /// decide which part of a multipart/alternative shows. `text/*`
590    /// wildcards allowed; consulted before the auto_view filters and
591    /// the built-in text ranking.
592    pub alternative_order: Vec<String>,
593}
594
595/// How long to wait on the network before saying so. A mail client
596/// that blocks has nothing to draw and no keys to read, so these are
597/// short by default: an unreachable server should cost seconds, not
598/// the OS default of about two minutes.
599#[derive(Debug, Clone, Deserialize)]
600#[serde(default)]
601pub struct Net {
602    /// Seconds to wait for a connection (mutt's $connect_timeout).
603    /// 0 waits as long as the OS does.
604    pub connect_timeout: u64,
605    /// Seconds to wait for data on a live connection. Never off:
606    /// IMAP IDLE uses it as its heartbeat, and anything under five
607    /// seconds is treated as five.
608    pub timeout: u64,
609    /// mutt's $ssl_usesystemcerts: trust the OS certificate store on
610    /// top of the built-in Mozilla roots. On by default, as in mutt.
611    pub system_cas: bool,
612    /// mutt's $certificate_file: a PEM file of extra roots to trust
613    /// (a private CA, a self-signed server's own cert). Added to the
614    /// Mozilla roots, never replacing them.
615    pub certificate_file: Option<String>,
616}
617
618impl Default for Net {
619    fn default() -> Self {
620        Net {
621            connect_timeout: 10,
622            timeout: 30,
623            system_cas: true,
624            certificate_file: None,
625        }
626    }
627}
628
629#[derive(Debug, Clone, Deserialize)]
630#[serde(default)]
631pub struct Ui {
632    pub theme: Option<String>,
633    /// mutt's status_format for the bottom line (see
634    /// format::DEFAULT_STATUS_FORMAT for the specifiers).
635    pub status_format: Option<String>,
636    /// Ring the terminal bell on error statuses (mutt's $beep).
637    pub beep: bool,
638    /// mutt's $beep_new: ring it when mail arrives, too. Off by
639    /// default, as in mutt.
640    pub beep_new: bool,
641    /// mutt's $wait_key: a shell escape ends with "Press Enter to
642    /// continue", so whatever it printed can be read before the
643    /// index paints over it. True unless set otherwise, as in mutt.
644    pub wait_key: Option<bool>,
645    /// mutt's $ts_enabled: set the terminal title (and icon) while
646    /// running. Off by default, as in mutt.
647    pub set_title: Option<bool>,
648    /// mutt's $ts_status_format: the title's format, the same
649    /// specifiers as status_format. Defaults to "rmut: %f".
650    pub title_format: Option<String>,
651    /// mutt's $history_file: where prompt history persists across
652    /// sessions. Unset means in-memory only, as rmut was before.
653    pub history_file: Option<String>,
654    /// mutt's $status_on_top: the status bar (and message line) sit at
655    /// the top, under the help bar, rather than the bottom. Off by
656    /// default, as in mutt.
657    pub status_on_top: Option<bool>,
658    /// mutt's $arrow_cursor: mark the selected row with an arrow
659    /// instead of reverse video. Off by default, as in mutt.
660    pub arrow_cursor: Option<bool>,
661    /// mutt's $menu_scroll: the index scrolls a line at a time when
662    /// the cursor leaves the screen; false shows the next page
663    /// instead. On by default here (rmut always scrolled), where mutt
664    /// pages.
665    pub menu_scroll: Option<bool>,
666    /// mutt's $menu_context: lines kept in view beyond the cursor
667    /// when the index scrolls or pages. 0 by default.
668    pub menu_context: usize,
669    /// mutt's $menu_move_off: the last message may scroll up past
670    /// the bottom of the screen; false keeps the index bottom-stuck
671    /// once it fills the screen. True unless set otherwise.
672    pub menu_move_off: Option<bool>,
673    /// mutt's $help: the key-help bar on the top line. True unless
674    /// set otherwise.
675    pub help: Option<bool>,
676    /// mutt's $sort_browser: the folder browser's order: "alpha" (the
677    /// default), "count" / "unread" (by new-mail count), "date" (by
678    /// the maildir's change time), "unsorted" (as configured, then as
679    /// found). A "reverse-" prefix flips it. "size" reads as alpha.
680    pub sort_browser: Option<String>,
681    /// mutt's $error_history: how many past errors error-history
682    /// shows. 0 disables it. 30 by default, as in mutt.
683    pub error_history: usize,
684    /// mutt's $status_chars: the characters `%r` shows for the
685    /// mailbox state: [0] unchanged, [1] changed (needs sync), [2]
686    /// read-only. Unset keeps rmut's own (nothing / `*` / `%`).
687    pub status_chars: Option<String>,
688    /// mutt's $save_history: entries kept per history bucket in the
689    /// file. Defaults to 100 (rmut's in-memory cap).
690    pub save_history: Option<usize>,
691    /// The terminal pager's URLs as OSC 8 hyperlinks, which a terminal
692    /// that knows them opens on a click (rmut's own; on by default).
693    /// false for a terminal that shows the sequence instead.
694    pub hyperlinks: Option<bool>,
695    /// What opens a URL from the URL list, the URL as its argument:
696    /// "xdg-open" by default ("open" on macOS).
697    pub url_command: Option<String>,
698}
699
700impl Default for Ui {
701    fn default() -> Self {
702        Ui {
703            theme: None,
704            status_format: None,
705            beep: true,
706            beep_new: false,
707            wait_key: None,
708            set_title: None,
709            title_format: None,
710            history_file: None,
711            save_history: None,
712            status_on_top: None,
713            arrow_cursor: None,
714            menu_scroll: None,
715            menu_context: 0,
716            menu_move_off: None,
717            help: None,
718            sort_browser: None,
719            error_history: 30,
720            status_chars: None,
721            hyperlinks: None,
722            url_command: None,
723        }
724    }
725}
726
727/// One `[[color_index]]` rule (mutt's `color index FG BG PATTERN`):
728/// index lines whose message matches `pattern` take these colors.
729/// First matching rule wins; rules are checked in config order.
730#[derive(Debug, Clone, Default, Deserialize)]
731#[serde(default)]
732pub struct ColorRule {
733    pub pattern: String,
734    pub fg: Option<String>,
735    pub bg: Option<String>,
736}
737
738/// The window front end (rmut-egui). The terminal front end never
739/// reads these.
740#[derive(Debug, Clone, Default, Deserialize)]
741#[serde(default)]
742pub struct Gui {
743    /// Text size in points (14 when unset). Ctrl+= / Ctrl+- / Ctrl+0
744    /// zoom the whole window at runtime on top of this.
745    pub size: Option<f32>,
746    /// Path to a .ttf/.otf file used as the window's monospace face
747    /// (egui's built-in face when unset).
748    pub font: Option<String>,
749    /// The terminal emulator that hosts $EDITOR and `!` commands
750    /// ($TERMINAL, then foot/alacritty/kitty/xterm, when unset).
751    pub terminal: Option<String>,
752    /// The window canvas: what the text sits on and its default ink
753    /// (named colors or `#rrggbb`; a dark gray on off-white unset).
754    pub background: Option<String>,
755    pub foreground: Option<String>,
756    /// "builtin" opens drafts in the window's own text editor, "nvim"
757    /// embeds Neovim in the window; anything else ("external", the
758    /// default) hosts $EDITOR in the terminal.
759    pub editor: Option<String>,
760    /// The message body in a proportional face; the index, headers
761    /// and indented (preformatted) lines stay monospace.
762    pub proportional: Option<bool>,
763    /// image/* parts drawn in the message body under their
764    /// `[-- Type: image/... --]` markers (on unless turned off).
765    pub inline_images: Option<bool>,
766    /// The window's own say over `[pager] html` (the Preferences
767    /// checkbox writes it here), so the terminal can keep raw while
768    /// the window renders, or the other way around.
769    pub html: Option<String>,
770    /// Window-only overrides of `[colors]`, same keys and values
771    /// (plus `#rrggbb`): the window can wear its own palette while
772    /// the terminal keeps the shared one.
773    pub colors: HashMap<String, String>,
774}
775
776/// The optional left pane listing `mail.mailboxes` with new-mail
777/// counts (toggle with B at runtime).
778#[derive(Debug, Clone, Deserialize)]
779#[serde(default)]
780pub struct Sidebar {
781    pub visible: bool,
782    pub width: u16,
783}
784
785impl Default for Sidebar {
786    fn default() -> Self {
787        Sidebar {
788            visible: false,
789            width: 24,
790        }
791    }
792}
793
794#[derive(Debug, Clone, Default, Deserialize)]
795#[serde(default)]
796pub struct Keys {
797    pub index: HashMap<String, String>,
798    pub pager: HashMap<String, String>,
799}
800
801/// One remote account: IMAP for reading, SMTP for sending. The
802/// password comes from `password_command` (preferred) or, when you
803/// accept a secret sitting in the config file, a literal `password`.
804#[derive(Debug, Clone, Deserialize)]
805pub struct Account {
806    pub name: String,
807    pub user: String,
808    /// Shell command whose first stdout line is the password
809    /// (pass(1)-style). Wins over `password` when both are set.
810    pub password_command: Option<String>,
811    /// Plaintext password. Convenient, but anyone who can read the
812    /// config can read your mail, so keep it at mode 600.
813    pub password: Option<String>,
814    pub imap_host: Option<String>,
815    #[serde(default = "default_imap_port")]
816    pub imap_port: u16,
817    /// Encrypt IMAP (default): TLS from the first byte on port 993,
818    /// STARTTLS on any other port. Disabling is for tests only.
819    #[serde(default = "default_true")]
820    pub imap_tls: bool,
821    pub smtp_host: Option<String>,
822    #[serde(default = "default_smtp_port")]
823    pub smtp_port: u16,
824    /// Encrypt SMTP (default): implicit TLS on port 465, STARTTLS
825    /// otherwise. Disabling is for tests only.
826    #[serde(default = "default_true")]
827    pub smtp_tls: bool,
828    /// "password" (default), "xoauth2", or "oauthbearer". The OAuth
829    /// mechanisms authenticate with an access token from
830    /// `token_command` instead of a password.
831    pub auth: Option<String>,
832    /// Shell command whose first stdout line is a *fresh* OAuth access
833    /// token (refresh is its business: oauth2ms, mutt_oauth2.py, ...).
834    /// Run for every connection; tokens expire, so it is never cached.
835    pub token_command: Option<String>,
836    /// IMAP folder that receives the Fcc copy of sent mail.
837    #[serde(default = "default_sent_folder")]
838    pub sent_folder: String,
839    /// From identity when composing from this account's mailboxes,
840    /// e.g. identity = { name = "Jane Work", email = "jane@work.example.com" }.
841    pub identity: Option<Identity>,
842}
843
844/// PGP via gpg(1). Decrypt/verify happens automatically when a viewed
845/// message is PGP; signing and encrypting are chosen at the send
846/// prompt. Passphrases are gpg-agent's business; rmut never sees them.
847#[derive(Debug, Clone, Deserialize)]
848#[serde(default)]
849pub struct Pgp {
850    /// The gpg executable (a name looked up in $PATH or a full path).
851    pub command: String,
852    /// Signing key for --local-user; gpg's default key when unset.
853    pub sign_key: Option<String>,
854    /// Preselect signing / encrypting for new drafts (the compose menu's
855    /// security menu can still change it per message).
856    pub sign_by_default: bool,
857    pub encrypt_by_default: bool,
858    /// mutt's $crypt_replysign: a reply to a signed message defaults
859    /// to signed. $crypt_replyencrypt: a reply to an encrypted one
860    /// defaults to encrypted (on in mutt, off here until asked).
861    /// $crypt_replysignencrypted: a reply to signed-and-encrypted
862    /// mail defaults to signed too. All off by default.
863    pub reply_sign: bool,
864    pub reply_encrypt: bool,
865    pub reply_sign_encrypted: bool,
866}
867
868impl Default for Pgp {
869    fn default() -> Self {
870        Pgp {
871            command: "gpg".into(),
872            sign_key: None,
873            sign_by_default: false,
874            encrypt_by_default: false,
875            reply_sign: false,
876            reply_encrypt: false,
877            reply_sign_encrypted: false,
878        }
879    }
880}
881
882fn default_imap_port() -> u16 {
883    993
884}
885
886fn default_smtp_port() -> u16 {
887    587
888}
889
890fn default_true() -> bool {
891    true
892}
893
894fn default_sent_folder() -> String {
895    "Sent".into()
896}
897
898/// How an account authenticates, from its `auth` key.
899#[derive(Clone, Copy, PartialEq, Eq, Debug)]
900pub enum AuthKind {
901    Password,
902    XOAuth2,
903    OAuthBearer,
904}
905
906impl AuthKind {
907    pub fn sasl_name(self) -> &'static str {
908        match self {
909            AuthKind::Password => "PLAIN",
910            AuthKind::XOAuth2 => "XOAUTH2",
911            AuthKind::OAuthBearer => "OAUTHBEARER",
912        }
913    }
914
915    /// The SASL initial response (before base64): RFC 7628 for
916    /// OAUTHBEARER, the Google shape for XOAUTH2.
917    pub fn initial_response(self, user: &str, token: &str, host: &str, port: u16) -> String {
918        match self {
919            AuthKind::XOAuth2 => format!("user={user}\x01auth=Bearer {token}\x01\x01"),
920            AuthKind::OAuthBearer => {
921                format!("n,a={user},\x01host={host}\x01port={port}\x01auth=Bearer {token}\x01\x01")
922            }
923            AuthKind::Password => String::new(),
924        }
925    }
926}
927
928/// First stdout line of a credential command.
929fn first_line_of(command: &str, what: &str, name: &str) -> Result<String> {
930    let out = std::process::Command::new("sh")
931        .arg("-c")
932        .arg(command)
933        .output()
934        .with_context(|| format!("running {what} for account {name}"))?;
935    ensure!(
936        out.status.success(),
937        "{what} for account {name} exited with {}",
938        out.status
939    );
940    let secret = String::from_utf8_lossy(&out.stdout)
941        .lines()
942        .next()
943        .unwrap_or("")
944        .to_string();
945    ensure!(
946        !secret.is_empty(),
947        "{what} for account {name} printed nothing"
948    );
949    Ok(secret)
950}
951
952impl Account {
953    /// First stdout line of `password_command`, or the stored
954    /// `password` when no command is configured.
955    pub fn password(&self) -> Result<String> {
956        let Some(command) = &self.password_command else {
957            return self
958                .password
959                .clone()
960                .filter(|p| !p.is_empty())
961                .with_context(|| {
962                    format!(
963                        "account {} has neither password_command nor password",
964                        self.name
965                    )
966                });
967        };
968        first_line_of(command, "password command", &self.name)
969    }
970
971    pub fn auth_kind(&self) -> Result<AuthKind> {
972        match self.auth.as_deref() {
973            None | Some("password") => Ok(AuthKind::Password),
974            Some("xoauth2") => Ok(AuthKind::XOAuth2),
975            Some("oauthbearer") => Ok(AuthKind::OAuthBearer),
976            Some(other) => anyhow::bail!("unknown auth {other:?} for account {}", self.name),
977        }
978    }
979
980    /// The credential matching `auth_kind`: the password, or a fresh
981    /// access token from `token_command`.
982    pub fn secret(&self) -> Result<String> {
983        match self.auth_kind()? {
984            AuthKind::Password => self.password(),
985            _ => {
986                let command = self.token_command.as_deref().with_context(|| {
987                    format!(
988                        "account {} has auth = oauth but no token_command",
989                        self.name
990                    )
991                })?;
992                first_line_of(command, "token command", &self.name)
993            }
994        }
995    }
996}
997
998impl Config {
999    pub fn account(&self, name: &str) -> Option<&Account> {
1000        self.accounts.iter().find(|a| a.name == name)
1001    }
1002
1003    /// The identity for a draft, layered like mutt hooks: `[identity]`,
1004    /// then the account's, then every matching `[[identities]]` rule in
1005    /// order (a later rule overrides an earlier one; unset fields keep
1006    /// the value below). `rcpts` are the draft's bare recipient
1007    /// addresses, empty when they are not known yet, which makes
1008    /// recipient rules not match.
1009    /// Every known mailing-list pattern (`lists` plus `subscribed`),
1010    /// compiled for matching against addresses.
1011    pub fn list_matchers(&self) -> Vec<crate::pattern::Matcher> {
1012        self.mail
1013            .lists
1014            .iter()
1015            .chain(&self.mail.subscribed)
1016            .map(|spec| crate::pattern::Matcher::new(spec))
1017            .collect()
1018    }
1019
1020    /// The `subscribed` half on its own, for the Mail-Followup-To rule.
1021    pub fn subscribed_matchers(&self) -> Vec<crate::pattern::Matcher> {
1022        self.mail
1023            .subscribed
1024            .iter()
1025            .map(|spec| crate::pattern::Matcher::new(spec))
1026            .collect()
1027    }
1028
1029    /// mutt's `alternates`, compiled for matching against a bare
1030    /// address.
1031    pub fn alternate_matchers(&self) -> Vec<crate::pattern::Matcher> {
1032        self.mail
1033            .alternates
1034            .iter()
1035            .map(|spec| crate::pattern::Matcher::new(spec))
1036            .collect()
1037    }
1038
1039    pub fn identity_for(
1040        &self,
1041        folder: &str,
1042        rcpts: &[String],
1043        account: Option<&Account>,
1044    ) -> Identity {
1045        let mut id = self.identity.clone();
1046        let mut overlay = |name: &Option<String>, email: &Option<String>| {
1047            if name.is_some() {
1048                id.name = name.clone();
1049            }
1050            if email.is_some() {
1051                id.email = email.clone();
1052            }
1053        };
1054        if let Some(acct) = account.and_then(|a| a.identity.as_ref()) {
1055            overlay(&acct.name, &acct.email);
1056        }
1057        for rule in &self.identities {
1058            let folder_ok = rule.folder.as_deref().is_none_or(|g| glob_match(g, folder));
1059            let recipient_ok = rule
1060                .recipient
1061                .as_deref()
1062                .is_none_or(|g| rcpts.iter().any(|r| glob_match(g, r)));
1063            if folder_ok && recipient_ok {
1064                overlay(&rule.name, &rule.email);
1065            }
1066        }
1067        id
1068    }
1069}
1070
1071/// Glob match: `*` spans anything, everything else is literal;
1072/// case-insensitive, anchored at both ends.
1073pub fn glob_match(pattern: &str, text: &str) -> bool {
1074    let p: Vec<char> = pattern.to_lowercase().chars().collect();
1075    let t: Vec<char> = text.to_lowercase().chars().collect();
1076    let (mut pi, mut ti) = (0usize, 0usize);
1077    let mut star: Option<(usize, usize)> = None;
1078    while ti < t.len() {
1079        if pi < p.len() && p[pi] == '*' {
1080            star = Some((pi, ti));
1081            pi += 1;
1082        } else if pi < p.len() && p[pi] == t[ti] {
1083            pi += 1;
1084            ti += 1;
1085        } else if let Some((sp, st)) = star {
1086            // Backtrack: let the last * swallow one more character.
1087            pi = sp + 1;
1088            ti = st + 1;
1089            star = Some((sp, st + 1));
1090        } else {
1091            return false;
1092        }
1093    }
1094    while pi < p.len() && p[pi] == '*' {
1095        pi += 1;
1096    }
1097    pi == p.len()
1098}
1099
1100/// mutt's `+x` / `=x`: a mailbox named under $folder. `=` or `+`
1101/// alone is $folder itself; anything else, and any name at all when
1102/// no folder is configured, comes back untouched. This runs on every
1103/// mailbox rmut is handed, typed or configured, before anything
1104/// tries to read it as a path or an imap: spec.
1105pub fn expand_folder(spec: &str, folder: Option<&str>) -> String {
1106    let Some(rest) = spec.strip_prefix(['=', '+']) else {
1107        return spec.to_string();
1108    };
1109    let Some(folder) = folder
1110        .map(|f| f.trim_end_matches('/'))
1111        .filter(|f| !f.is_empty())
1112    else {
1113        return spec.to_string();
1114    };
1115    match rest.is_empty() {
1116        true => folder.to_string(),
1117        false => format!("{folder}/{rest}"),
1118    }
1119}
1120
1121impl Config {
1122    /// Expand `=x` / `+x` in every mailbox the config names, so the
1123    /// rest of the program only ever sees real paths and imap: specs.
1124    /// Idempotent: an expanded name no longer starts with = or +.
1125    pub fn expand_folders(&mut self) {
1126        let folder = self.mail.folder.clone();
1127        let folder = folder.as_deref();
1128        let one = |slot: &mut Option<String>| {
1129            if let Some(v) = slot {
1130                *v = expand_folder(v, folder);
1131            }
1132        };
1133        one(&mut self.mail.sent);
1134        one(&mut self.mail.postponed);
1135        one(&mut self.mail.trash);
1136        one(&mut self.mail.save);
1137        for m in &mut self.mail.mailboxes {
1138            *m = expand_folder(m, folder);
1139        }
1140        for hook in &mut self.fcc_hooks {
1141            hook.mailbox = expand_folder(&hook.mailbox, folder);
1142        }
1143    }
1144}
1145
1146pub fn path() -> Option<PathBuf> {
1147    if let Ok(p) = std::env::var("RMUT_CONFIG") {
1148        return Some(PathBuf::from(p));
1149    }
1150    std::env::var("HOME")
1151        .ok()
1152        .map(|h| PathBuf::from(h).join(".config/rmut/config.toml"))
1153}
1154
1155/// Load the config; a missing file is fine (defaults), a broken file
1156/// returns defaults plus a warning to show the user.
1157pub fn load_default() -> (Config, Option<String>) {
1158    let Some(p) = path() else {
1159        return (Config::default(), None);
1160    };
1161    let Ok(text) = std::fs::read_to_string(&p) else {
1162        return (Config::default(), None);
1163    };
1164    match toml::from_str::<Config>(&text) {
1165        Ok(cfg) => {
1166            let warning = secret_exposed(&cfg, &p);
1167            (cfg, warning)
1168        }
1169        Err(err) => {
1170            let first = err
1171                .to_string()
1172                .lines()
1173                .next()
1174                .unwrap_or("parse error")
1175                .to_string();
1176            (
1177                Config::default(),
1178                Some(format!("config ignored ({}): {first}", p.display())),
1179            )
1180        }
1181    }
1182}
1183
1184/// A plaintext `password` in a config anyone can read is the one
1185/// mistake worth interrupting for: the file holds the keys to the
1186/// mail. Says so once at startup, and only when the bits are
1187/// actually open, so a 600 config stays quiet.
1188fn secret_exposed(cfg: &Config, path: &std::path::Path) -> Option<String> {
1189    use std::os::unix::fs::PermissionsExt;
1190    let holds_password = cfg
1191        .accounts
1192        .iter()
1193        .any(|a| a.password.as_ref().is_some_and(|p| !p.is_empty()));
1194    if !holds_password {
1195        return None;
1196    }
1197    let mode = std::fs::metadata(path).ok()?.permissions().mode();
1198    if mode & 0o077 == 0 {
1199        return None;
1200    }
1201    // The imperative first: the message line clips at the window
1202    // edge, and the path is usually the long part.
1203    Some(format!(
1204        "chmod 600 {} (it holds a password and others can read it)",
1205        path.display()
1206    ))
1207}
1208
1209impl Identity {
1210    /// "Name <email>" / "email" for the From header, if configured.
1211    pub fn from_line(&self) -> Option<String> {
1212        match (&self.name, &self.email) {
1213            (Some(n), Some(e)) => Some(format!("{n} <{e}>")),
1214            (None, Some(e)) => Some(e.clone()),
1215            _ => None,
1216        }
1217    }
1218}
1219
1220#[cfg(test)]
1221mod tests {
1222    use super::*;
1223
1224    #[test]
1225    fn a_readable_config_holding_a_password_warns() {
1226        use std::os::unix::fs::PermissionsExt;
1227        let tmp = tempfile::tempdir().unwrap();
1228        let path = tmp.path().join("config.toml");
1229        std::fs::write(&path, "").unwrap();
1230        let with_password: Config = toml::from_str(
1231            r#"
1232            [[accounts]]
1233            name = "work"
1234            user = "jane"
1235            password = "hunter2"
1236            "#,
1237        )
1238        .unwrap();
1239        let with_command: Config = toml::from_str(
1240            r#"
1241            [[accounts]]
1242            name = "work"
1243            user = "jane"
1244            password_command = "gpg -q -d ~/.config/rmut/imap.gpg"
1245            "#,
1246        )
1247        .unwrap();
1248
1249        let mode =
1250            |m: u32| std::fs::set_permissions(&path, std::fs::Permissions::from_mode(m)).unwrap();
1251        mode(0o644);
1252        let warning = secret_exposed(&with_password, &path).expect("a warning");
1253        assert!(warning.starts_with("chmod 600 "), "{warning}");
1254        // Shut when the bits are shut, and when there is no secret to
1255        // expose in the first place.
1256        mode(0o600);
1257        assert!(secret_exposed(&with_password, &path).is_none());
1258        mode(0o644);
1259        assert!(secret_exposed(&with_command, &path).is_none());
1260        assert!(secret_exposed(&Config::default(), &path).is_none());
1261    }
1262
1263    #[test]
1264    fn folder_shorthand_expands_everywhere_a_mailbox_is_named() {
1265        assert_eq!(expand_folder("=archive", Some("~/Mail")), "~/Mail/archive");
1266        assert_eq!(expand_folder("+archive", Some("~/Mail/")), "~/Mail/archive");
1267        // = or + alone is $folder itself.
1268        assert_eq!(expand_folder("=", Some("~/Mail")), "~/Mail");
1269        // An IMAP account works as $folder, so =x is one of its folders.
1270        assert_eq!(
1271            expand_folder("=Archive", Some("imap:work")),
1272            "imap:work/Archive"
1273        );
1274        // Nothing to expand, or nowhere to expand to: untouched.
1275        assert_eq!(expand_folder("~/other", Some("~/Mail")), "~/other");
1276        assert_eq!(expand_folder("=archive", None), "=archive");
1277        assert_eq!(expand_folder("=archive", Some("")), "=archive");
1278
1279        let mut cfg: Config = toml::from_str(
1280            r#"
1281            [mail]
1282            folder = "~/Mail"
1283            mailboxes = ["=inbox", "~/elsewhere"]
1284            sent = "+sent"
1285            trash = "=Trash"
1286            [[fcc_hooks]]
1287            pattern = "~A"
1288            mailbox = "=work"
1289            "#,
1290        )
1291        .unwrap();
1292        cfg.expand_folders();
1293        assert_eq!(cfg.mail.mailboxes, ["~/Mail/inbox", "~/elsewhere"]);
1294        assert_eq!(cfg.mail.sent.as_deref(), Some("~/Mail/sent"));
1295        assert_eq!(cfg.mail.trash.as_deref(), Some("~/Mail/Trash"));
1296        assert_eq!(cfg.fcc_hooks[0].mailbox, "~/Mail/work");
1297        // Idempotent: an expanded name no longer starts with = or +.
1298        cfg.expand_folders();
1299        assert_eq!(cfg.mail.trash.as_deref(), Some("~/Mail/Trash"));
1300    }
1301
1302    #[test]
1303    fn parses_partial_config() {
1304        let cfg: Config = toml::from_str(
1305            r#"
1306            [identity]
1307            name = "Jane"
1308            email = "jane@x"
1309            [mail]
1310            mailboxes = ["~/Maildir"]
1311            sendmail = "/bin/true"
1312            [keys.index]
1313            sync = "w"
1314            "#,
1315        )
1316        .unwrap();
1317        assert_eq!(cfg.identity.from_line().as_deref(), Some("Jane <jane@x>"));
1318        assert_eq!(cfg.mail.mailboxes, vec!["~/Maildir"]);
1319        assert_eq!(cfg.mail.sendmail.as_deref(), Some("/bin/true"));
1320        assert_eq!(cfg.keys.index.get("sync").map(String::as_str), Some("w"));
1321        assert!(cfg.ui.theme.is_none());
1322    }
1323
1324    #[test]
1325    fn empty_and_unknown_keys_are_fine() {
1326        let cfg: Config = toml::from_str("").unwrap();
1327        assert!(cfg.identity.from_line().is_none());
1328        let cfg: Config = toml::from_str("[future]\nx = 1\n").unwrap();
1329        assert!(cfg.mail.mailboxes.is_empty());
1330        assert!(cfg.accounts.is_empty());
1331    }
1332
1333    #[test]
1334    fn parses_accounts_with_defaults() {
1335        let cfg: Config = toml::from_str(
1336            r#"
1337            [[accounts]]
1338            name = "work"
1339            user = "jane@example.com"
1340            password_command = "pass show mail/work"
1341            imap_host = "imap.example.com"
1342            smtp_host = "smtp.example.com"
1343
1344            [[accounts]]
1345            name = "test"
1346            user = "u"
1347            password_command = "true"
1348            imap_host = "localhost"
1349            imap_port = 10143
1350            imap_tls = false
1351            smtp_port = 465
1352            sent_folder = "INBOX/Sent"
1353            "#,
1354        )
1355        .unwrap();
1356        let work = cfg.account("work").unwrap();
1357        assert_eq!(work.imap_port, 993);
1358        assert_eq!(work.smtp_port, 587);
1359        assert!(work.imap_tls && work.smtp_tls);
1360        assert_eq!(work.sent_folder, "Sent");
1361        let test = cfg.account("test").unwrap();
1362        assert_eq!(test.imap_port, 10143);
1363        assert!(!test.imap_tls);
1364        assert!(test.smtp_host.is_none());
1365        assert_eq!(test.sent_folder, "INBOX/Sent");
1366        assert!(cfg.account("nope").is_none());
1367    }
1368
1369    #[test]
1370    fn pgp_section_defaults_and_overrides() {
1371        let cfg: Config = toml::from_str("").unwrap();
1372        assert_eq!(cfg.pgp.command, "gpg");
1373        assert!(cfg.pgp.sign_key.is_none());
1374        assert!(!cfg.pgp.sign_by_default && !cfg.pgp.encrypt_by_default);
1375        let cfg: Config = toml::from_str(
1376            "[pgp]\ncommand = \"gpg2\"\nsign_key = \"jane@x\"\nsign_by_default = true\n",
1377        )
1378        .unwrap();
1379        assert_eq!(cfg.pgp.command, "gpg2");
1380        assert_eq!(cfg.pgp.sign_key.as_deref(), Some("jane@x"));
1381        assert!(cfg.pgp.sign_by_default && !cfg.pgp.encrypt_by_default);
1382    }
1383
1384    #[test]
1385    fn account_missing_required_field_fails_parse() {
1386        assert!(toml::from_str::<Config>("[[accounts]]\nname = \"x\"\n").is_err());
1387    }
1388
1389    fn test_account() -> Account {
1390        Account {
1391            name: "t".into(),
1392            user: "u".into(),
1393            password_command: None,
1394            password: None,
1395            imap_host: None,
1396            imap_port: 993,
1397            imap_tls: true,
1398            smtp_host: None,
1399            smtp_port: 587,
1400            smtp_tls: true,
1401            auth: None,
1402            token_command: None,
1403            sent_folder: "Sent".into(),
1404            identity: None,
1405        }
1406    }
1407
1408    #[test]
1409    fn glob_match_star_and_case() {
1410        assert!(glob_match("*", "anything"));
1411        assert!(glob_match("*work*", "/home/jane/Maildir/work-stuff"));
1412        assert!(glob_match("*@work.example.com", "Jane@Work.Example.Com"));
1413        assert!(glob_match("imap:work/*", "imap:work/INBOX"));
1414        assert!(!glob_match("*@work.example.com", "jane@example.com"));
1415        assert!(!glob_match("work", "workplace")); // anchored
1416        assert!(glob_match("a*b*c", "aXbYc"));
1417        assert!(!glob_match("a*b*c", "aXcYb"));
1418    }
1419
1420    #[test]
1421    fn identity_layers_like_hooks() {
1422        let cfg: Config = toml::from_str(
1423            r#"
1424            [identity]
1425            name = "Jane"
1426            email = "jane@example.com"
1427            reverse_name = true
1428
1429            [[identities]]
1430            folder = "*work*"
1431            email = "jane@work.example.com"
1432
1433            [[identities]]
1434            recipient = "*@club.example.com"
1435            name = "Jenny"
1436
1437            [[accounts]]
1438            name = "acct"
1439            user = "u"
1440            imap_host = "h"
1441            identity = { name = "Jane Acct", email = "acct@example.com" }
1442            "#,
1443        )
1444        .unwrap();
1445        assert!(cfg.identity.reverse_name);
1446        // No match: the global identity as-is.
1447        let id = cfg.identity_for("~/Maildir", &[], None);
1448        assert_eq!(id.from_line().as_deref(), Some("Jane <jane@example.com>"));
1449        // Folder rule overrides the email, keeps the name.
1450        let id = cfg.identity_for("~/Maildir/work", &[], None);
1451        assert_eq!(
1452            id.from_line().as_deref(),
1453            Some("Jane <jane@work.example.com>")
1454        );
1455        // Recipient rule overlays the name; needs a matching recipient.
1456        let rcpts = vec!["bob@club.example.com".to_string()];
1457        let id = cfg.identity_for("~/Maildir", &rcpts, None);
1458        assert_eq!(id.from_line().as_deref(), Some("Jenny <jane@example.com>"));
1459        let id = cfg.identity_for("~/Maildir", &[], None);
1460        assert_eq!(id.name.as_deref(), Some("Jane"));
1461        // The account identity sits between global and the rules.
1462        let account = cfg.account("acct").unwrap();
1463        let id = cfg.identity_for("imap:acct/INBOX", &[], Some(account));
1464        assert_eq!(
1465            id.from_line().as_deref(),
1466            Some("Jane Acct <acct@example.com>")
1467        );
1468        let id = cfg.identity_for("imap:acct/work", &[], Some(account));
1469        assert_eq!(
1470            id.from_line().as_deref(),
1471            Some("Jane Acct <jane@work.example.com>")
1472        );
1473    }
1474
1475    #[test]
1476    fn password_command_takes_first_line() {
1477        let account = |cmd: &str| Account {
1478            password_command: Some(cmd.into()),
1479            ..test_account()
1480        };
1481        assert_eq!(
1482            account("printf 'secret\\nrest\\n'").password().unwrap(),
1483            "secret"
1484        );
1485        assert!(account("false").password().is_err());
1486        assert!(account("true").password().is_err()); // empty output
1487    }
1488
1489    #[test]
1490    fn auth_kinds_and_token_command() {
1491        let acct = test_account();
1492        assert_eq!(acct.auth_kind().unwrap(), AuthKind::Password);
1493        let oauth = Account {
1494            auth: Some("oauthbearer".into()),
1495            token_command: Some("printf 'tok123\\nrest\\n'".into()),
1496            ..test_account()
1497        };
1498        assert_eq!(oauth.auth_kind().unwrap(), AuthKind::OAuthBearer);
1499        assert_eq!(oauth.secret().unwrap(), "tok123");
1500        let no_command = Account {
1501            auth: Some("xoauth2".into()),
1502            ..test_account()
1503        };
1504        assert!(
1505            no_command
1506                .secret()
1507                .unwrap_err()
1508                .to_string()
1509                .contains("no token_command")
1510        );
1511        let bad = Account {
1512            auth: Some("kerberos".into()),
1513            ..test_account()
1514        };
1515        assert!(bad.auth_kind().is_err());
1516        // "password" is an explicit spelling of the default.
1517        let explicit = Account {
1518            auth: Some("password".into()),
1519            password: Some("pw".into()),
1520            ..test_account()
1521        };
1522        assert_eq!(explicit.secret().unwrap(), "pw");
1523    }
1524
1525    #[test]
1526    fn oauth_initial_responses() {
1527        assert_eq!(
1528            AuthKind::XOAuth2.initial_response("jane", "tok", "imap.example.com", 993),
1529            "user=jane\x01auth=Bearer tok\x01\x01"
1530        );
1531        assert_eq!(
1532            AuthKind::OAuthBearer.initial_response("jane", "tok", "imap.example.com", 993),
1533            "n,a=jane,\x01host=imap.example.com\x01port=993\x01auth=Bearer tok\x01\x01"
1534        );
1535    }
1536
1537    #[test]
1538    fn stored_password_and_precedence() {
1539        let stored = Account {
1540            password: Some("hunter2".into()),
1541            ..test_account()
1542        };
1543        assert_eq!(stored.password().unwrap(), "hunter2");
1544        // A configured command wins over the stored password.
1545        let both = Account {
1546            password_command: Some("echo from-command".into()),
1547            password: Some("hunter2".into()),
1548            ..test_account()
1549        };
1550        assert_eq!(both.password().unwrap(), "from-command");
1551        let neither = test_account();
1552        assert!(neither.password().is_err());
1553        let cfg: Config = toml::from_str(
1554            "[[accounts]]\nname = \"x\"\nuser = \"u\"\npassword = \"pw\"\nimap_host = \"h\"\n",
1555        )
1556        .unwrap();
1557        assert_eq!(cfg.account("x").unwrap().password().unwrap(), "pw");
1558    }
1559}