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