MH-FORMAT(5)
π NAME π
mh-format β formatting language for nmh message system
Okay so bestie, welcome to mh-format(5), straight from the File Formats Manual, and itβs all about the formatting language for the nmh message system. Itβs giving βtiny programming language but make it mail,β and honestly? iconic. π
β¨ DESCRIPTION β¨
Several nmh commands utilize either a format string or a format file during their execution. For example, scan uses a format string to generate its listing of messages; repl uses a format file to generate message replies, and so on.
There are a number of scan listing formats available, including nmh/etc/scan.time, nmh/etc/scan.size, and nmh/etc/scan.timely. Look in /etc/nmh for other scan and repl format files which may have been written at your site.
You can have your local nmh expert write new format commands or modify existing ones, or you can try your hand at it yourself. This manual section explains how to do that.
Note: some familiarity with the C printf routine is assumed.
A format string consists of ordinary text combined with special, multi-character, escape sequences which begin with %. When specifying a format string, the usual C backslash characters are honored: \b, \f, \n, \r, and \t. Continuation lines in format files end with \ followed by the newline character. A literal % can be inserted into a format file by using the sequence %%.
π§ SYNTAX π§
Format strings are built around escape sequences. There are three types of escape sequence: header components, built-in functions, and flow control. Comments may be inserted in most places where a function argument is not expected. A comment begins with %; and ends with a (non-escaped) newline.
π Component escapes π
A component escape is specified as %{component}, and exists for each header in the message being processed. For example, %{date} refers to the βDate:β field of the message. All component escapes have a string value. Such values are usually compressed by converting any control characters (tab and newline included) to spaces, then eliding any leading or multiple spaces. Some commands, however, may interpret some component escapes differently; be sure to refer to each command's manual entry for details. Some commands (such as ap(8) and mhl(1)) use a special component %{text} to refer to the text being processed; see their respective man pages for details and examples.
πΈ Function escapes πΈ
A function escape is specified as %(function). All functions are built-in, and most have a string or integer value. A function escape may take an argument. The argument follows the function escape (and any separating whitespace is discarded) as in the following example:
%(function argument)
In addition to literal numbers or strings, the argument to a function escape can be another function, or a component, or a control escape. When the argument is a function or a component, the argument is specified without a leading %. When the argument is a control escape, it is specified with a leading %.
π Control escapes π
A control escape is one of: %<, %?, %|, or %>. These are combined into the conditional execution construct:
%< condition format-text
%? condition format-text
...
%| format-text
%>
(Extra white space is shown here only for clarity.) These constructs, which may be nested without ambiguity, form a general if-elseif-else-endif block where only one of the format-texts is interpreted. In other words, %< is like the "if", %? is like the "elseif", %| is like "else", and %> is like "endif".
A %< or %? control escape causes its condition to be evaluated. This condition is a component or function. For components and functions whose value is an integer, the condition is true if it is non-zero, and false if zero. For components and functions whose value is a string, the condition is true if it is a non-empty string, and false if an empty string.
The %? control escape is optional, and can be used multiple times in a conditional block. The %| control escape is also optional, but may only be used once.
π¦ Function escapes π¦
Functions expecting an argument generally require an argument of a particular type. In addition to the integer and string types, these include:
literalβ A literal number or string β example syntax:%(func 1234),%(func text string)compβ Any component β example syntax:%(func{in-reply-to})dateβ A date component β example syntax:%(func{date})addrβ An address component β example syntax:%(func{from})exprβ Nothing, or a subexpression, or a control escape β example syntax:%(func),%(func(func2)),%(func %<{reply-to}%|%{from}%>)
The date and addr types have the same syntax as the component type, comp, but require a header component which is a date, or address, string, respectively.
Most arguments not of type expr are required. When escapes are nested (via expr arguments), evaluation is done from innermost to outermost. As noted above, for the expr argument type, functions and components are written without a leading %. Control escape arguments must use a leading %, preceded by a space.
For example,
%<(mymbox{from}) To: %{to}%>
writes the value of the header component βFrom:β to the internal register named str; then (mymbox) reads str and writes its result to the internal register named num; then the control escape, %<, evaluates num. If num is non-zero, the string βTo:β is printed followed by the value of the header component βTo:β.
π Evaluation π
The evaluation of format strings is performed by a small virtual machine. The machine is capable of evaluating nested expressions (as described above) and, in addition, has an integer register num, and a text string register str. When a function escape that accepts an optional argument is processed, and the argument is not present, the current value of either num or str is substituted as the argument: the register used depends on the function, as listed below.
Component escapes write the value of their message header in str. Function escapes write their return value in num for functions returning integer or boolean values, and in str for functions returning string values. (The boolean type is a subset of integers, with usual values 0=false and 1=true.) Control escapes return a boolean value, setting num to 1 if the last explicit condition evaluated by a %< or %? control escape succeeded, and 0 otherwise.
All component escapes, and those function escapes which return an integer or string value, evaluate to their value as well as setting str or num. Outermost escape expressions in these forms will print their value, but outermost escapes which return a boolean value do not result in printed output.
π Functions π
The function escapes may be roughly grouped into a few categories.
msgβ integer β message numbercurβ integer β is this message the current one? (0 or 1)unseenβ integer β is this message unseen? (0 or 1)sizeβ integer β size of the messagestrlenβ integer β length ofstrwidthβ integer β column width of the terminalcharleftβ integer β bytes left in the output buffertimenowβ integer β seconds since the Unix epochmeβ string β the user's mailbox (username)myhostβ string β the user's local hostnamemynameβ string β the user's namelocalmboxβ string β the complete local mailboxeq(literal) β boolean βnum == argne(literal) β boolean βnum != arggt(literal) β boolean βnum > argmatch(literal) β boolean βstrcontainsargamatch(literal) β boolean βstrstarts withargplus(literal) β integer βargplusnumminus(literal) β integer βargminusnummultiply(literal) β integer βnummultiplied byargdivide(literal) β integer βnumdivided byargmodulo(literal) β integer βnummoduloargnum(literal) β integer β setnumtoarg.numβ integer β setnumto zero.lit(literal) β string β setstrtoarg.litβ string β clearstr.getenv(literal) β string β setstrto the environment value ofargprofile(literal) β string β setstrto the profile or context componentargvaluenonzero(expr) β boolean βnumis non-zerozero(expr) β boolean βnumis zeronull(expr) β boolean βstris emptynonnull(expr) β boolean βstris non-emptyvoid(expr) β setstrornumcomp(comp) β string β setstrto component textcompval(comp) β integer β setnumto "atoi(comp)"decode(expr) β string β decodestras an RFC 2047 (MIME-encoded) componentunquote(expr) β string β remove RFC 2822 quotes fromstrtrim(expr) β trim trailing whitespace fromstrtrimr(expr) β string β like%(trim), but also returns the stringkilo(expr) β string β express in SI units:15.9K,2.3M, etc.%(kilo)scales by factors of 1000,kibi(expr) β string β express in IEC units:15.5Ki,2.2Mi.%(kibi)scales by factors of 1024.ordinal(expr) β string β output the ordinal suffix based on the value ofnum(st, nd, rd, th)putstr(expr) β printstrputstrf(expr) β printstrin a fixed widthputnum(expr) β printnumputnumf(expr) β printnumin a fixed widthputlit(expr) β printstrwithout space compressionzputlit(expr) β printstrwithout space compression;strmust occupy no width on displayboldβ string β set terminal bold modeunderlineβ string β set terminal underlined modestandoutβ string β set terminal standout moderesettermβ string β reset all terminal attributeshascolorβ boolean β does the terminal support colorfgcolor(literal) β string β set terminal foreground colorbgcolor(literal) β string β set terminal background colorformataddr(expr) β appendargtostras a (comma separated) address listconcataddr(expr) β appendargtostras a (comma separated) address list, including duplicates, see Special Handlingputaddr(literal) β printstraddress list withargas optional label; get line width fromnum
The (me) function hands you the username of the current user. Iconic, simple, no notes.
The (myhost) function gives you back the localname entry from mts.conf, or if localname isn't configured it just returns the local hostname instead. Either way you're covered bestie.
The (myname) function will return the value of the SIGNATURE environment variable if it's set, and if it's not set it'll give you the passwd GECOS field for the current user instead β truncated at the first comma if that field happens to contain one. π
The (localmbox) function returns the complete form of the local mailbox, all ready to go in a "From" header. If there's a "Local-Mailbox" profile entry it returns that; if there isn't, it's equivalent to:
%(myname) <%(me)@%(myhost)>
ποΈ date functions, they need a date component as their argument
sec(date) β integer β seconds of the minutemin(date) β integer β minutes of the hourhour(date) β integer β hours of the day (0-23)wday(date) β integer β day of the week (Sun=0)day(date) β string β day of the week (abbrev.)weekday(date) β string β day of the weeksday(date) β integer β day of the week known? (1=explicit, 0=implicit, -1=unknown)mday(date) β integer β day of the monthyday(date) β integer β day of the yearmon(date) β integer β month of the yearmonth(date) β string β month of the year (abbrev.)lmonth(date) β string β month of the yearyear(date) β integer β year (may be > 100)zone(date) β integer β timezone in minutestzone(date) β string β timezone stringszone(date) β integer β timezone explicit? (1=explicit, 0=implicit, -1=unknown)date2local(date) β coerce date to local timezonedate2gmt(date) β coerce date to GMTdst(date) β integer β daylight savings in effect? (0 or 1)clock(date) β integer β seconds since the Unix epochrclock(date) β integer β seconds prior to current timetws(date) β string β official RFC 822 renderingpretty(date) β string β user-friendly renderingnodate(date) β integer β returns 1 if the date is invalid
π¬ address functions, these ones want an address component as their argument
Heads up: any function marked with * computes its return value from the first address present in the header component. iykyk
proper(addr) β string β official RFC 822 renderingfriendly(addr) β string β user-friendly renderingaddr(addr) β string βmbox@hostorhost!mboxrendering*pers(addr) β string β the personal name*note(addr) β string β commentary text*mbox(addr) β string β the local mailbox*mymbox(addr) β integer β does the list have the user's address? (0 or 1)getmymbox(addr) β string β the user's (first) address, with personal namegetmyaddr(addr) β string β the user's (first) address, without personal namehost(addr) β string β the host domain*nohost(addr) β integer β no host was present (0 or 1)*type(addr) β integer β host type* (0=local, 1=network, -1=uucp, 2=unknown)path(addr) β string β any leading host route*ingrp(addr) β integer β address was inside a group (0 or 1)*gname(addr) β string β name of group*
Okay so a little clarification on (mymbox{comp}) is genuinely in order, don't @ me. This function checks each of the addresses in the header component comp against the user's mailbox name and any "Alternate-Mailboxes". It returns true if any address matches. But wait, there's more: it also returns true if the comp header isn't present in the message at all. π If you need to, you can use the (null) function to explicitly test for that exact case.
And the friendly{comp} call will return any double-quoted "personal name" (that is, anything before <>), and then it'll return that. If there's no personal name but there is a "note" (a comments string after an email address), it'll return that instead. And if there's neither of those? It just returns the bare email address. Simple as.
β¨ Formatting β¨
When a function or component escape gets interpreted and the result is going to be printed immediately, you can specify an optional field width to print that field in exactly a given number of characters. Slay.
So for example, a numeric escape like %4(size) will print at most 4 digits of the message size β and if it overflows, that's flagged with a ? in the first position, like ?234. A string escape like %4(me) will print the first 4 characters and truncate at the end. Short fields get padded on the right with the fill character (normally, a blank). And if the field width argument starts with a leading zero, then the fill character is set to a zero. π
The functions (putnumf) and (putstrf) print their result in exactly the number of characters specified by their leading field width argument. For example, %06(putnumf(size)) will print the message size in a field six characters wide, filled with leading zeros. And %14(putstrf{from}) will print the "From:" header component in fourteen characters, with trailing spaces added as needed.
Using a negative value for the field width causes right-justification within the field, with padding on the left up to the field width. Padding is with spaces, except for a left-padded putnumf when the width starts with zero.
The functions (putnum) and (putstr) are somewhat special: they print their result in the minimum number of characters required, and they ignore any leading field width argument. Just straight up ignoring you, no cap.
The (putlit) function outputs the exact contents of the str register without any changes β so no duplicate space removal, no control character conversion, none of that. Similarly, the (zputlit) function outputs the exact contents of the str register, but it requires that those contents not occupy any output width. Which means it can therefore be used for outputting terminal escape sequences. π
okay so there are only a limited number of function escapes that spit out terminal escape sequences, and they get pulled straight out of the terminfo(5) database based on whatever your current terminal setting is π
here's the whole lineup:
(bold),(underline),(standout)β these set bold mode, underline mode, and standout mode respectively. one job each, and they ate π«Ά(hascolor)β use this to find out if your current terminal supports color at all π(fgcolor)and(bgcolor)β set the foreground and background colors respectively. both of these escapes take one literal argument, the color name, and the color name can be one of:black,red,green,yellow,blue,magenta,cyan,white. that's the whole palette bestie, no custom hex codes here π(resetterm)β resets all terminal attributes back to their default setting β¨
and listen, these terminal escapes should be used together with (zputlit) (that's the preferred one π) or (putlit), because the normal (putstr) function will strip out control characters. it's giving "why is my color gone" energy otherwise π
the available output width lives in an internal register, and any output that goes over that width is going to get truncated. the one exception to this whole situation? (zputlit) functions will still be executed if a terminal reset code is being placed at the end of a line. iconic behavior, honestly.
π Special Handling π
some functions straight up act different depending on which command they got invoked from. main character energy, but make it conditional.
in repl the (formataddr) function stores every email address it encounters into an internal cache, and then uses that cache to suppress duplicate addresses π so if you need to build an address list that includes previously-seen addresses, you can use the (concataddr) function instead β it's identical to (formataddr) in all other respects. just know that (concataddr) does not add addresses to the duplicate-suppression cache. noted. periodt.
πΈ Other Hints and Tips πΈ
sometimes the writer of a format function is sitting there so confused because their output is duplicated π΅βπ« the general rule to remember is simple, and it's this:
if a function or component escape begins with a %, it will generate text in the output file. otherwise, it will not.
a good example is a simple attempt to generate a To: header based on the From: and Reply-To: headers:
%(formataddr %<{reply-to}%|%{from})%(putaddr To: )
unfortunately, if the Reply-to: header is not present, the output line will be something like:
My From User <from@example.com>To: My From User <from@example.com>
so what went wrong?? let's break it down π
when performing the test for the if clause (%<), the component is not output because it is considered an argument to the if statement (so the rule about not starting with % applies). but the component escape in our else statement (everything after the %|) is not an argument to anything; it begins with a %, and thus the value of that component is output. this also has the side effect of setting the str register, which is later picked up by the (formataddr) function and then output by (putaddr).
and the example format string above has another bug, bestie: there should always be a valid width value in the num register when (putaddr) is called, otherwise bad formatting can take place π¬
the solution is to use the (void) function β this will prevent the function or component from outputting any text. with this in place (and using (width) to set the num register for the width) a better implementation would look like:
%(formataddr %<{reply-to}%|%(void{from})%(void(width))%(putaddr To: )
it should be noted here that the side effects of function and component escapes are still in force and, as a result, each component test in the if-elseif-else-endif clause sets the str register. the side quests never stop π§
as an additional note, the (formataddr) and (concataddr) functions have special behavior when it comes to the str register. the starting point of the register is saved and is used to build up entries in the address list.
and fr fr, you will find the fmttest(1) utility invaluable when debugging problems with format strings. that's your bestie for format string drama π©·
π¦ Examples π¦
with all the above in mind, here is a breakdown of the default format string for scan. the first part is:
%4(msg)%<(cur)+%| %>%<{replied}-%?{encrypted}E%| %>
which says that the message number should be printed in four digits. if the message is the current message then a +, else a space, should be printed; if a βReplied:β field is present then a -, else if an βEncrypted:β field is present then an E, otherwise a space, should be printed. okay we love a conditional moment β¨
next:
%02(mon{date})/%02(mday{date})
the month and date are printed in two digits (zero filled) separated by a slash. cute, formatted, done.
next,
%<{date} %|*%>
if a βDate:β field is present it is printed, followed by a space; otherwise a * is printed.
next,
%<(mymbox{from})%<{to}To:%14(decode(friendly{to}))%>%>
if the message is from me, and there is a βTo:β header, print βTo:β followed by a βuser-friendlyβ rendering of the first address in the βTo:β field; any MIME-encoded characters are decoded into the actual characters. the way that nested escape eats, truly π
continuing,
%<(zero)%17(decode(friendly{from}))%>
if either of the above two tests failed, then the βFrom:β address is printed in a mime-decoded, βuser-friendlyβ format.
and finally,
%(decode{subject})%<{body}<<%{body}>>%>
the mime-decoded subject and initial body (if any) are printed. slay, that's the whole scan format π
for a more complicated example, consider a possible replcomps format file π
%(lit)%(formataddr %<{reply-to}
this clears str and formats the βReply-To:β header if present. if not present, the else-if clause is executed.
%?{from}%?{sender}%?{return-path}%>)\
this formats the βFrom:β, βSender:β and βReturn-Path:β headers, stopping as soon as one of them is present. first one to show up wins, no cap.
next:
%<(nonnull)%(void(width))%(putaddr To: )\n%>\
if the formataddr result is non-null, it is printed as an address (with line folding if needed) in a field width wide, with a leading label of βTo:β.
%(lit)%(formataddr{to})%(formataddr{cc})%(formataddr(me))\
str is cleared, and the βTo:β and βCc:β headers, along with the user's address (depending on what was specified with the β-ccβ switch to repl) are formatted.
%<(nonnull)%(void(width))%(putaddr cc: )\n%>\
if the result is non-null, it is printed as above with a leading label of βcc:β.
%<{fcc}Fcc: %{fcc}\n%>\
if a -fcc folder switch was given to repl (see repl(1) for more details about %{fcc}), an βFcc:β header is output.
%<{subject}Subject: Re: %{subject}\n%>\
if a subject component was present, a suitable reply subject is output.
%<{message-id}In-Reply-To: %{message-id}\n%>\
%<{message-id}References: %<{references} %{references}%>\
%{message-id}\n%>
--------
if a message-id component was present, an βIn-Reply-To:β header is output including the message-id, followed by a βReferences:β header with references, if present, and the message-id. and as with all plain-text, the row of dashes are output as-is π
this last part is a good example for a little more elaboration. here's that part again in pseudo-code:
if (comp_exists(message-id)) then
print (βIn-reply-to: β)
print (message-id.value)
print (β\nβ)
endif
if (comp_exists(message-id)) then
print (βReferences: β)
if (comp_exists(references)) then
print(references.value);
endif
print (message-id.value)
print (β\nβ)
endif
one more example for you bestie: currently, nmh supports very large message numbers, and it is not uncommon for a folder to have far more than 10000 messages. nonetheless (as noted above) the various scan format strings, inherited from older MH versions, are generally hard-coded to 4 digits for the message number. thereafter, formatting problems occur π the nmh format strings can be modified to behave more sensibly with larger message numbers:
%(void(msg))%<(gt 9999)%(msg)%|%4(msg)%>
the current message number is placed in num. (note that (msg) is a function escape which returns an integer, it is not a component.) the (gt) conditional is used to test whether the message number has 5 or more digits. if so, it is printed at full width, otherwise at 4 digits. adaptive formatting, we love to see it π
π SEE ALSO π
π«§ CONTEXT π«§
None.
and that's a wrap on the whole page, bestie π this was nmh-1.8, dated 2015-01-10, and you just read MH-FORMAT(5) in full. go forth and format, you absolute icon πβ¨
π¦ where this page comes from
- alpine 3.24: nmh-doc 1.8-r3 Β· BSD-3-Clause
- epel 10: nmh 1.8-3.el10_1 Β· BSD
- epel 9: nmh 1.8-1.el9 Β· BSD
- fedora 43: nmh 1.8-9.fc43 Β· LicenseRef-Callaway-BSD
- fedora 44: nmh 1.8-10.fc44 Β· LicenseRef-Callaway-BSD
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms