# phpman > man > mh-format(5)

[MH-FORMAT(5mh)](https://www.chedong.com/phpMan.php/man/MH-FORMAT/5mh/markdown)                                                                        [MH-FORMAT(5mh)](https://www.chedong.com/phpMan.php/man/MH-FORMAT/5mh/markdown)



## NAME
       mh-format - formatting language for nmh message system

## 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  for‐
       mat 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 se‐
       quences which begin with `%'.  When specifying a format string, the usual C backslash charac‐
       ters  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)](https://www.chedong.com/phpMan.php/man/ap/8/markdown) and [_mhl_(1)](https://www.chedong.com/phpMan.php/man/mhl/1/markdown)_)_
       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  compo‐
       nent,  the  argument  is specified without a leading `%'.  When the argument is a control es‐
       cape, it is specified with a leading `%'.

### Control escapes
       A _control_ escape is one of: `%<', `%?', `%|', or `%>'.  These are combined  into  the  condi‐
       tional 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 _com__‐
       _ponent_ 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 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 addi‐
       tion to the integer and string types, these include:

            _Argument_ _Description_            _Example_ _Syntax_
            literal  A literal number       %(_func_ 1234)
                     or string              %(_func_ text string)
            comp     Any component          %(_func_{_in-reply-to_})
            date     A date component       %(_func_{_date_})
            addr     An address component   %(_func_{_from_})
            expr     Nothing                %(_func_)
                     or a subexpression     %(_func_(_func2_))
                     or control escape      %(_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 ca‐
       pable  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  op‐
       tional  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 other‐
       wise.

       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  re‐
       sult in printed output.

### Functions
       The function escapes may be roughly grouped into a few categories.

            _Function_    _Argument_ _Return_   _Description_
            msg                  integer  message number
            cur                  integer  message is current (0 or 1)
            unseen               integer  message is unseen (0 or 1)
            size                 integer  size of message
            strlen               integer  length of _str_
            width                integer  column width of terminal
            charleft             integer  bytes left in output buffer
            timenow              integer  seconds since the Unix epoch
            me                   string   the user's mailbox (username)
            myhost               string   the user's local hostname
            myname               string   the user's name
            localmbox            string   the complete local mailbox
            eq          literal  boolean  _num_ == _arg_
            ne          literal  boolean  _num_ != _arg_
            gt          literal  boolean  _num_ > _arg_
            match       literal  boolean  _str_ contains _arg_
            amatch      literal  boolean  _str_ starts with _arg_
            plus        literal  integer  _arg_ plus _num_
            minus       literal  integer  _arg_ minus _num_
            multiply    literal  integer  _num_ multiplied by _arg_
            divide      literal  integer  _num_ divided by _arg_
            modulo      literal  integer  _num_ modulo _arg_
            num         literal  integer  Set _num_ to _arg_.
            num                  integer  Set _num_ to zero.
            lit         literal  string   Set _str_ to _arg_.
            lit                  string   Clear _str_.
            getenv      literal  string   Set _str_ to environment value of _arg_
            profile     literal  string   Set _str_ to profile component _arg_
                                          value
            nonzero     expr     boolean  _num_ is non-zero
            zero        expr     boolean  _num_ is zero
            null        expr     boolean  _str_ is empty
            nonnull     expr     boolean  _str_ is non-empty
            void        expr              Set _str_ or _num_
            comp        comp     string   Set _str_ to component text
            compval     comp     integer  Set _num_ to “**atoi**(_comp_)”
            decode      expr     string   decode _str_ as RFC 2047 (MIME-encoded)
                                          component
            unquote     expr     string   remove RFC 2822 quotes from _str_
            trim        expr              trim trailing whitespace from _str_
            kilo        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.
            putstr      expr              print _str_
            putstrf     expr              print _str_ in a fixed width
            putnum      expr              print _num_
            putnumf     expr              print _num_ in a fixed width
            putlit      expr              print _str_ without space compression
            zputlit     expr              print _str_ without space compression;
                                          _str_ must occupy no width on display
            bold                 string   set terminal bold mode
            underline            string   set terminal underlined mode
            standout             string   set terminal standout mode
            resetterm            string   reset all terminal attributes
            hascolor             boolean  terminal supports color
            fgcolor     literal  string   set terminal foreground color
            bgcolor     literal  string   set terminal background color
            formataddr  expr              append _arg_ to _str_ as a
                                          (comma separated) address list
            concataddr  expr              append _arg_ to _str_ as a
                                          (comma separated) address list,
                                          including duplicates,
                                          see Special Handling
            putaddr     literal           print _str_ address list with
                                          _arg_ as optional label;
                                          get line width from _num_

       The  (_me_)  function  returns the username of the current user.  The (_myhost_) function returns
       the **localname** entry in _mts.conf_, or the local hostname if **localname** is not  configured.   The
       (_myname_)  function will return the value of the **SIGNATURE** environment variable if set, other‐
       wise it will return the passwd GECOS field (truncated at the first comma if it contains  one)
       for  the  current  user.  The (_localmbox_) function will return the complete form of the local
       mailbox, suitable for use in a “From” header.  It will return the “_Local-Mailbox_” profile en‐
       try if there is one; if not, it will be equivalent to:

            %(myname) <%(me)@%(myhost)>

       The following functions require a date component as an argument:

            _Function_    _Argument_ _Return_   _Description_
            sec         date     integer  seconds of the minute
            min         date     integer  minutes of the hour
            hour        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 week
            sday        date     integer  day of the week known?
                                          (1=explicit,0=implicit,-1=unknown)
            mday        date     integer  day of the month
            yday        date     integer  day of the year
            mon         date     integer  month of the year
            month       date     string   month of the year (abbrev.)
            lmonth      date     string   month of the year
            year        date     integer  year (may be > 100)
            zone        date     integer  timezone in minutes
            tzone       date     string   timezone string
            szone       date     integer  timezone explicit?
                                          (1=explicit,0=implicit,-1=unknown)
            date2local  date              coerce date to local timezone
            date2gmt    date              coerce date to GMT
            dst         date     integer  daylight savings in effect? (0 or 1)
            clock       date     integer  seconds since the Unix epoch
            rclock      date     integer  seconds prior to current time
            tws         date     string   official RFC 822 rendering
            pretty      date     string   user-friendly rendering
            nodate      date     integer  returns 1 if date is invalid

       The  following  functions  require  an address component as an argument.  The return value of
       functions noted with `*' is computed from the first address present in the header component.

            _Function_    _Argument_ _Return_   _Description_
            proper      addr     string   official RFC 822 rendering
            friendly    addr     string   user-friendly rendering
            addr        addr     string   mbox@host or host!mbox rendering*
            pers        addr     string   the personal name*
            note        addr     string   commentary text*
            mbox        addr     string   the local mailbox*
            mymbox      addr     integer  list has the user's address? (0 or 1)
            getmymbox   addr     string   the user's (first) address,
                                          with personal name
            getmyaddr   addr     string   the user's (first) address,
                                          without personal name
            host        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*

       (A clarification on (_mymbox_{_comp_}) is in order.  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. However, it also returns true if the “_comp_” header is
       not  present  in  the message.  If needed, the (_null_) function can be used to explicitly test
       for this case.)

### Formatting
       When a function or component escape is interpreted and the result  will  be  printed  immedi‐
       ately,  an optional field width can be specified to print the field in exactly a given number
       of characters.  For example, a numeric escape like %4(_size_) will print at most  4  digits  of
       the message size; overflow will be indicated by 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  are  padded  at  the right with the fill character (normally, a blank).  If the field
       width argument begins 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; %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
       ignore any leading field width argument.  The (_putlit_) function outputs the exact contents of
       the  str  register  without  any changes such as duplicate space removal or control character
       conversion.  Similarly, the (_zputlit_) function outputs the exact contents of the  str  regis‐
       ter,  but requires that those contents not occupy any output width.  It can therefore be used
       for outputting terminal escape sequences.

       There are a limited number of function escapes to output terminal  escape  sequences.   These
       sequences  are retrieved from the [_terminfo_(5)](https://www.chedong.com/phpMan.php/man/terminfo/5/markdown) database according to the current terminal set‐
       ting.  The (_bold_), (_underline_), and (_standout_) escapes set bold  mode,  underline  mode,  and
       standout mode respectively.  (_hascolor_) can be used to determine if the current terminal sup‐
       ports color.  (_fgcolor_) and (_bgcolor_) set the foreground and background colors  respectively.
       Both  of these escapes take one literal argument, the color name, which can be one of: black,
       red, green, yellow, blue, magenta, cyan, white.  (_resetterm_) resets all  terminal  attributes
       to  their  default setting.  These terminal escapes should be used in conjunction with (_zput__‐
       _lit_) (preferred) or (_putlit_), as the normal (_putstr_) function will strip out control  charac‐
       ters.

       The  available  output width is kept in an internal register; any output exceeding this width
       will be truncated.  The one exception to this is that (_zputlit_) functions will still be  exe‐
       cuted if a terminal reset code is being placed at the end of a line.

### Special Handling
       Some functions have different behavior depending on the command they are invoked from.

       In  **repl**  the  (_formataddr_)  function stores all email addresses encountered into an internal
       cache and will use this cache to suppress duplicate addresses.  If you need to create an  ad‐
       dress  list  that  includes  previously-seen addresses you may use the (_concataddr_) function,
       which is identical to (_formataddr_) in all other respects.  Note that  (_concataddr_)  does  _not_
       add addresses to the duplicate-suppression cache.

### Other Hints and Tips
       Sometimes,  the  writer  of  a format function is confused because output is duplicated.  The
       general rule to remember is simple: 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>>

       What  went wrong?  When performing the test for the **if** clause (%<), the component is not out‐
       put 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_).  The example format  string  above
       has  another  bug:  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.

       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.

       You will find the [_fmttest_(1)](https://www.chedong.com/phpMan.php/man/fmttest/1/markdown) utility invaluable when debugging problems with format strings.

### 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.  Next:

              %02(mon{date})/%02(mday{date})

       the month and date are printed in two digits (zero filled) separated by a slash.  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.  Continuing,

            %<(zero)%17(decode(friendly{from}))%>

       if  either  of  the above two tests failed, then the “From:” address is printed in a mime-de‐
       coded, “user-friendly” format.  And finally,

            %(decode{subject})%<{body}<<%{body}>>%>

       the mime-decoded subject and initial body (if any) are printed.

       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.  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)](https://www.chedong.com/phpMan.php/man/repl/1/markdown) 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 mes‐
       sage-id, followed by a “References:” header with references, if present, and the  message-id.
       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: 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 re‐
       turns  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 dig‐
       its.

## SEE ALSO
       [_scan_(1)](https://www.chedong.com/phpMan.php/man/scan/1/markdown), [_repl_(1)](https://www.chedong.com/phpMan.php/man/repl/1/markdown), [_fmttest_(1)](https://www.chedong.com/phpMan.php/man/fmttest/1/markdown),

## CONTEXT
       None



nmh-1.7.1                                    2015-01-10                               [MH-FORMAT(5mh)](https://www.chedong.com/phpMan.php/man/MH-FORMAT/5mh/markdown)
