Go to the first, previous, next, last section, table of contents.


Automated Option Processing

AutoOpts 11.0 is bundled with AutoGen. It is a tool that virtually eliminates the hassle of processing options and keeping man pages, info docs and usage text up to date. This package allows you to specify several program attributes, up to a hundred option types and many option attributes. From this, it then produces all the code necessary to parse and handle the command line and initialization file options, and the documentation that should go with your program as well.

AutoOpts is distributed under The GNU General Public License with the Library extentions (LGPL). It is in no way a "lesser" license. You have greater license with it.

AutoOpts Features

AutoOpts supports option processing; option state saving; and program documentation with innumerable features. Here, we list a few obvious ones and some important ones, but the full list is really defined by all the attributes defined in the section Option Definitions section.

  1. POSIX-compliant short (flag) option processing.
  2. GNU-style long options processing. Long options are recognized without case sensitivity, and they may be abbreviated.
  3. Environment variable initializations.
  4. Initialization from RC or INI files, and saving the option state back into one.
  5. Options may be marked as dis-abled with a disablement prefix. Such options may default to either an enabled or a disabled state. You may also provide an enablement prifix, too, e.g., --allow-mumble and --prevent-mumble.
  6. Verify that required options are present between the minimum and maximum number of times on the command line.
  7. Verify that conflicting options do not appear together, and that options that require the presence of other options are, in fact, used in the presence of other options.
  8. Provides a callable routine to parse a text string as if it were from one of the RC/INI files.
  9. --help and --version are automatically supported. --more-help will page the generated help.
  10. By adding a `doc' and `arg-name' attributes to each option, AutoGen will also be able to produce a man page and the `invoking' section of a texinfo document.
  11. Insert the option processing state into Scheme-defined variables. Thus, Guile based applications that are linked with private main() routines can take advantage of all of AutoOpts' functionality.
  12. If test-main is defined, the output `.c' file will contain a main routine that will be compiled when TEST_<prog-name>_OPTS is defined. See section AutoOpts for Shell Scripts. If you choose to compile this program, it is currently capable of producing one of three results:
    1. A program that processes the arguments and writes to standard out portable shell commands containing the digested options.
    2. A program that will generate portable shell commands to parse the defined options. The expectation is that this result will be copied into a shell script and used there.
    3. test-main may specify a routine that will be called with a pointer to the option descriptions as the single argument. You must supply this routine and, obviously, you can cause it to do whatever you wish it to do.
  13. There are facilities in place to allow libraries to intermingle their command line and initialization options with client program options.

Explanatory details:

loading rc files

Initialization files are enabled by specifying the program attribute homerc (see section Program Description Attributes). The initialization values are identified by the long option name followed by white space and any associated value. The value, if any, will continue through the end of the last line not continued with a backslash. Leading and trailing white space is stripped.

Initialization files are selected both by the homerc entries and, optionally, via an automatically supplied command line option. The first component of the homerc entry may be an environment variable such as $HOME, or it may also be $$ (two dollar sign characters) to specify the directory of the executable. For example:

homerc = "$$/../share/autogen";

The initialization files are processed in the order they are specified by the homerc attribute, so that each new file will normally override the settings of the previous files. A few options may be marked for immediate action (see section Immediate Action Attributes). Any such options are acted upon in reverse order. The disabled load-opts (--no-load-opts) option, for example, is an immediate action option. Its presence in the last homerc file will prevent the processing of any prior homerc files.

Further initialization file processing can be suppressed by specifying --no-load-opts on the command line, or PROGRAM_LOAD_OPTS=no in the environment, or no-load-opts in any of the specified homerc files.

will cause the AutoOpts library to look in the normal autogen datadir for an initialization file.

saving rc files

When initialization files are enabled for an application, the user is also provided with an automatically supplied --save-opts option. All of the known option state will be written to either the specified output file or, if it is not specified, then to the last specified homerc file.

process a text string for options

The optionLoadLine takes two arguments:

  1. The pointer to the option descriptor.
  2. A pointer to a NUL-terminated string that contains a long option name followed, optionally, by a string value.

Leading and trailing white space is trimmed from the value, but otherwise new lines are not discarded. The caller is expected to have NUL terminated the string at the correct point.

Competitive Feature Analysis

Here is a feature comparison of AutoOpts and five other command line parser generators. They all share a number of similarities:

The 6 parsers compared are:

  1. AutoOpts is a component of AutoGen. AutoGen has many capabilities, but here we concentrate on the portion called AutoOpts. AutoOpts is the most general of these programs, and has the most extensive documentation. It is the only one that supports shell and Scheme scripts as well as C programs.
  2. clig can generate either C or Tcl option parsing code. It can also process multiple arguments per single option.
  3. genparse generates a wrapper around getopts_long() to parse the command line options.
  4. gaa supports option input from a configuration file as well as the command line. NOTE HOWEVER: gaa is not maintained.
  5. gengetopt generates a C function that uses getopt_long function to parse the command line options, to validate them and fills a struct.
  6. wyg uses flex and bison to generate a configuration file parser, but uses getopt_long to parse the command line options.

Comparative Analysis of Differentiating Features
If a feature is present (or absent) in only one or two implementations, then the "yes" or "no" is upper cased for emphasis.

Feature \ Package # shell script app Scheme app config file input environment input config file output callback functions multiple occurrence parameter types enumeration opts optional argument default values range checks consistency checks standard opts man page texinfo invoking developer dependencies user dependencies
1 2 3 4 5 6
YES no no no no no
YES no no no no no
yes no no yes no yes
YES no no no no no
YES no no no no no
yes NO yes yes yes NO
YES YES no no no no
[1] 4 5 5 11 4
YES no no no no no
YES YES no no no no
yes yes yes yes NO yes
yes yes yes no no no
YES no no no no no
YES no no no no no
YES YES no no no no
YES no no no no no
Guile tcl none none none bison,flex
[2] none none none none none
"multiple occurrence" options may appear multiple times on the command line. Some of the parsers constrain options to appearing once only. "optional argument" refers to the argument to an option. POSIX and most command line parsers require an option to either not have an argument or else the argument must be supplied on the command line. GNU's getopt_long and some of these parsers support the notion of letting the option argument be "optional". "consistency checks" verify that conflicting options do not appear together, and options that require other options are allowed only if those other options are present. "standard options" are pre-defined options that can be trivially incorporated into a user's set of options. They can also thereby be used for standardizing on the flag character and option name. [1] See the list of features, section Option Argument Specification. [2] There is a user-visible dependency iff the developer does a dynamic link to the libopts.so library. Developers are free to either link statically or ship libopts.so with their product. A Debian package would need only a dependency on the package supplying libopts (libopts11, at present).

The Guile library is now generally pre-installed on all GNU/Linux systems.
-- James R. Van Zandt
-- Bruce Korb

Quick Start

Since it is generally easier to start with a simple example than it is to look at the options that AutoGen uses itself, here is a very simple AutoOpts example. You can copy this example out of the Info file and into a source file to try it. You can then embellish it into what you really need.

Assume you have a program named check that takes two options:

  1. A list of directories to check over for whatever it is check does. You want this option available as a POSIX-style flag option and a GNU long option. You want to allow as many of these as the user wishes.
  2. An option to show or not show the definition tree being used. Only one occurrence is to be allowed, specifying one or the other.

First, specify your program attributes and its options to AutoOpts, as with the following example.

AutoGen Definitions options;
prog-name     = check;
prog-title    = "Checkout Automated Options";
long-opts;
test_main;

flag = {
    name      = check_dirs;
    value     = L;        /* flag style option character */
    arg_type  = string;   /* option argument indication  */
    max       = NOLIMIT;  /* occurrence limit (none)     */
    stack_arg;            /* save opt args in a stack    */
    descrip   = "Checkout directory list";
};

flag = {
    name      = show_defs;
    descrip   = "Show the definition tree";
    disable   = dont;     /* mark as enable/disable type */
                          /* option.  Disable as `dont-' */
};

Then perform the following steps:

  1. autogen -L $prefix/share/autogen checkopt.def
  2. cc -o check -DTEST_CHECK_OPTS -g checkopt.c -L $prefix/lib -lopts

And now, ./check --help yields:

check - Checkout Automated Options
USAGE:  check [-<flag> [<val>]]... [--<name>[{=| }<val>]]...
  Flg Arg Option-Name    Description
   -L YES check-dirs     Checkout directory list
                                - may appear without limit
      no  show-defs      Show the definition tree
                                - disabled as --dont-show-defs
   -? no  help           Display usage information and exit
   -! no  more-help      Extended usage information passed thru pager

Options may be specified by doubled markers and their name
or by a single marker and the flag character/option value.

Normally, however, you would compile `checkopt.c' as in:

cc -o checkopt.o -I$prefix/include -c checkopt.c

and link `checkopt.o' with the rest of your program. The main program causes the options to be processed by calling optionProcess:

main( int argc, char** argv )
{
  {
    int optct = optionProcess( &checkOptions, argc, argv );
    argc -= optct;
    argv += optct;
  }

The options are tested and used as in the following fragment:

  if (HAVE_OPT( SHOW_DEFS ) && HAVE_OPT( CHECK_DIRS )) {
    int    dirct = STACKCT_OPT( CHECK_DIRS );
    char** dirs  = STACKLST_OPT( CHECK_DIRS );
    while (dirct-- > 0) {
      char* dir = *dirs++;
      ...

A lot of magic happens to make this happen. The rest of this chapter will describe the myriad of option attributes supported by AutoOpts. However, keep in mind that, in general, you won't need much more than what was described in this "quick start" section.

Option Definitions

AutoOpts uses an AutoGen definitions file for the definitions of the program options and overall configuration attributes. The complete list of program and option attributes is quite extensive, so if you are reading to understand how to use AutoOpts, I recommend reading the "Quick Start" section (see section Quick Start) and paying attention to the following:

  1. prog-name, prog-title, and argument, program attributes, See section Program Description Attributes.
  2. name and descrip option attributes, See section Required Attributes.
  3. value (flag character) and min (occurrence counts) option attributes, See section Common Option Attributes.
  4. arg-type from the option argument specification section, See section Option Argument Specification.
  5. Read the overall how to, See section Using AutoOpts.
  6. Highly recommended, but not required, are the several "man" and "info" documentation attributes, See section Man and Info doc Attributes.

Keep in mind that the majority are rarely used and can be safely ignored. However, when you have special option processing requirements, the flexibility is there.

Program Description Attributes

The following global option definitions are used to define attributes of the entire program. The first two are required of every program. The rest have been alphabetized. Except as noted, there may be only one copy of each of these definitions:

`prog-name'
This attribute is required. Variable names derived from this name are derived using string->c_name! (see section `string->c-name!' - map non-name chars to underscore).
`prog-title'
This attribute is required and may be any descriptive text.
`prog-desc and'
`opts-ptr'
These define global pointer variables that point to the program descriptor and the first option descriptor for a library option. This is intended for use by certain libraries that need command line and/or initialization file option processing. These definitions have no effect on the option template output, but are used for creating a library interface file. Normally, the first "option" for a library will be a documentation option that cannot be specified on the command line, but is marked as settable. The library client program will invoke the SET_OPTION macro which will invoke a handler function that will finally set these global variables.
`allow-errors'
The presence of this attribute indicates ignoring any command line option errors. This may also be turned on and off by invoking the macros ERRSKIP_OPTERR and ERRSTOP_OPTERR from the generated interface file.
`argument'
Specifies the syntax of the arguments that follow the options. It may not be empty, but if it is not supplied, then option processing must consume all the arguments. If it is supplied and starts with an open bracket ([), then there is no requirement on the presence or absence of command line argument following the options. Lastly, if it is supplied and does not start with an open bracket, then option processing must not consume all of the command line arguments.
`before-guile-boot'
If guile-main has been specified and if this is specified as well, then this code will be inserted into the actual main() procedure before gh_enter() is called.
`copyright'
The copyright is a structured value containing three to five values. If copyright is used, then the first three are required.
  1. `date' - the list of applicable dates for the copyright.
  2. `owner' - the name of the copyright holder.
  3. `type' - specifies the type of distribution license. AutoOpts/AutoGen will automatically support the text of the GNU Public License (`GPL'), the GNU Public License with Library extensions (`LGPL'), the Free BSD license (`BSD'), and a write-it-yourself copyright notice (`NOTE'). Only these values are recognized.
  4. `text' - the text of the copyright notice. It is only needed if `type' is set to `NOTE'.
  5. `author' - in case the author name is to appear in the documentation and is different from the copyright owner.
  6. `eaddr' - email address of the author or copyright holder.

An example of this might be:
copyright = {
    date  = "1992-2001";
    owner = "Bruce Korb";
    eaddr = '[email protected]';
    type  = GPL;
};
`detail'
This string is added to the usage output when the HELP option is selected.
`environrc'
Indicates looking in the environment for values of variables named
PROGRAM_OPTNAME.
where PROGRAM is the upper cased C-name of the program and OPTNAME is the upper cased C-name of the option. The C-names are the regular names with all special characters converted to underscores (_). If a particular option may be disabled, then its disabled state is indicated by setting the value to the disablement prefix. So, for example, if the disablement prefix were dont, then you can disable the optname option by setting the PROGRAM_OPTNAME environment variable to `dont'. See section Common Option Attributes.
`explain'
Gives additional information whenever the usage routine is invoked..
`export'
This string is inserted into the .h interface file. Generally used for global variables or #include directives required by flag_code text and shared with other program text.
`guile-main'
Creates a guile-style main and inner-main procedures. The inner main procedure will call optionProcess() and will invoke any code specified by this attribute. If this attribute does not specify any code, then calls to the AutoOpts library procedure export_options_to_guile() and then scm_shell() will be inserted into inner_main().
`homerc'
Specifies either a directory or a file using a specific path (like . or `/usr/local/share/progname') or an environment variable (like `$HOME/rc/' or `$PREFIX/share/progname') or the directory where the executable was found (`$$[/...]') to use to try to find the rcfile. Use as many as you like. The presence of this attribute activates the --save-opts and --load-opts options. See section loading rc files.
`include'
This string is inserted into the .c file. Generally used for global variables required only by flag_code program text.
`long-opts'
Presence indicates GNU-standard long option processing. If any options do not have an option value (flag character) specified, and least one does specify such a value, then you must specify long-opts. If none of your options specify an option value (flag character) and you do not specify long-opts, then command line arguments are processed in "named option mode". This means that:
`prefix'
This value is inserted into all global names. This will disambiguate them if more than one set of options are to be compiled into a single program.
`rcfile'
Specifies the initialization file name. This is only useful if you have provided at least one homerc attribute. default: .<prog-name>rc
`preserve-case'
This attribute will not change anything except appearance. Normally, the option names are all documented in lower case. However, if you specify this attribute, then they will display in the case used in their specification. Command line options will still be matched without case sensitivity.
`rcsection'
If you have a collection of option descriptions that are intended to use the same RC/ini files, then you will likely want to partition that file. That will be possible by specifying this attribute with AutoOpts version 9.2 and later. Every RC file will be considered partitioned by lines that commence with the square open bracket ([). All text before such a line is always processed. Once such a line is found, the upper-cased c-variable-syntax program name will be compared against the text following that bracket. If there is a match and the next character after that is a square close bracket (]), then the section is processed and the file closed. Otherwise, the section is ignored and a matching section is searched for. For exampe, if the foo-bar options had a sectioned RC file, then a line containing [FOO_BAR] would be searched for.
`test-main'
Creates a test main procedure for testing option processing. The resulting program may also be used for several purposes.
  1. If the text of test-main is short (3 or fewer characters), the generated main() will call putBourneShell. That routine will emit Bourne shell commands that can be eval-ed by a Bourne-derived shell to incorporate the digested options into the shell's environment, See section AutoOpts for Shell Scripts. You would use it thus:
    eval `./programopts $@`
    if [ -z "${OPTION_CT}" ] ; then exit 1 ; fi
    shift ${OPTION_CT}
    
  2. If the text of test-main contains putShellParse, the program will generate portable Bourne shell commands that will parse the command line options. The expectation is that this result will be copied into a shell script and used there, See section AutoOpts for Shell Scripts.
  3. Any other text must be the name of a routine that you will write yourself. That routine will be called after processing the command line options and it will be passed the option processing descriptor pointer as its sole argument.
`usage'
Optionally names the usage procedure, if the library routine optionUsage() does not work for you. If you specify gnu_usage as the value of this attribute, for example, you will use a procedure by that name for displaying usage. Of course, you will need to provide that procedure.
`version'
Specifies the program version and activates the VERSION option.

Option Attributes

For each option you wish to specify, you must have a block macro named flag defined. It MUST contain at least two defined text values named name and descrip. If any options do not have a value macro, then the long-opts global text macro must be defined. As a special exception, if no options have a value and long-opts is not defined and argument is not defined, then all arguments to the program are named. In this case, the - and -- command line option markers are optional.

There are four categories of option attributes. The fifth section below describes what data are available for writing option processing code.

Required Attributes

Every option must have exactly one copy of both of these attributes.

`name'
Long name for the option. Even if you are not accepting long options and are only accepting flags, it must be provided. AutoOpts generates private, named storage that require this name.
`descrip'
Except for documentation options, a very brief description of the option. About 40 characters on one line, maximum. It appears on the usage() output next to the option name. Documentation options appear on one or more lines by themselves, visually separating the usage options.

Common Option Attributes

These option attributes are optional. Any that do appear in the definition of a flag, may appear only once.

`value'
The flag character to specify for traditional option flags. e.g. -L.
`min'
Minimum occurrence count. If present, then the option must appear on the command line. Preset values do not count towards the minimum occurrence count.
`max'
Maximum occurrence count (invalid if disable present).
`enable'
Long-name prefix for enabling the option (invalid if disable not present). Only useful if long option names are being processed.
`disable'
Prefix for disabling (inverting sense of) the option. Only useful if long option names are being processed.
`enabled'
If default is for option being enabled. (Otherwise, the OPTST_DISABLED bit is set at compile time.) Only useful if the option can be disabled.
`ifdef'
`ifndef'
If an option is relevant on certain platforms or when certain features are enabled or disabled, you can specify the compile time flag used to indicate when the option should be compiled in or out. For example, if you have a configurable feature, mumble that is indicated with the compile time define, WITH_MUMBLING, then add:
ifdef = WITH_MUMBLING;
Note that case and spelling must match whatever you are using. Do not confuse these attributes with the AutoGen directives of the same names, See section Controlling What Gets Processed. These cause C pre-processing directives to be inserted into the generated C text.

Special Option Handling

These option attributes do not fit well with other categories.

`no-preset'
If presetting this option is not allowed. (Thus, environment variables and values set in rc/ini files will be ignored.)
`settable'
If the option can be set outside of option processing. If this attribute is defined, special macros for setting this particular option will be inserted into the interface file. For example, TEMPL_DIRS is a settable option for AutoGen, so a macro named SET_OPT_TEMPL_DIRS(a) appears in the interface file. This attribute interacts with the documentation attribute.
`equivalence'
Generally, when several options are mutually exclusive and basically serve the purpose of selecting one of several processing modes, these options can be considered an equivalence class. Sometimes, it is just easier to deal with them as such. For an option equivalence class, there is a single occurrence counter for all the members of the class. All members of the equivalence class must contain the same equivalenced-to option, including the equivalenced-to option itself. Thus, it must be a member. As an example, cpio(1) has three options -o, -i, and -p that define the operational mode of the program (create, extract and pass-through, respectively). They form an equivalence class from which one and only one member must appear on the command line. If cpio were an AutoOpt-ed program, then each of these option definitions would contain:
equivalence = create;
and the program would be able to determine the operating mode with code that worked something like this:
switch (WHICH_IDX_CREATE) {
case INDEX_OPT_CREATE:       ...
case INDEX_OPT_EXTRACT:      ...
case INDEX_OPT_PASS_THROUGH: ...
default:    /* cannot happen */
}
`documentation'
This attribute means the option exists for the purpose of separating option description text in the usage output. Libraries may choose to make it settable so that the library can determine which command options is the first one that pertains to the library. If present, this option disables all other attributes except settable, call_proc and flag_code. settable must be and is only specified if call_proc or flag_code has been specified. When present, the descrip attribute will be displayed only when the --help option has been specified. It will be displayed flush to the left hand margin and may consist of one or more lines of text. The name of the option will not be printed.

Immediate Action Attributes

Certain options may need to be processed early. For example, in order to suppress the processing of RC files, it is necessary to process the command line option --no-load-opts before the RC files are processed. To accommodate this, certain options may have their enabled or disabled forms marked for immediate processing. The consequence of this is that they are processed ahead of all other options in the reverse of normal order.

Normally, the first options processed are the options specified in the first homerc file, followed by then next homerc file through to the end of RC file processing. Next, environment variables are processed and finally, the command line options. The later options override settings processed earlier. That actually gives them higher priority. Command line immediate action options actually have the lowest priority of all. They would be used only if they are to have an effect on the processing of subsequent options.

`immediate'
Use this option attribute to specify that the enabled form of the option is to be processed immediately. The help and more-help options are so specified. They will also call exit() upon completion, so they do have an effect on the processing of the remaining options :-).
`immed_disable'
Use this option attribute to specify that the disabled form of the option is to be processed immediately. The load-opts option is so specified so that the --no-load-opts command line option will suppress the processing of RC files and environment variables.

Option Conflict Attributes

These attributes may be used as many times as you need. They are used at the end of the option processing to verify that the context within which each option is found does not conflict with the presence or absence of other options.

This is not a complete cover of all possible conflicts and requirements, but it simple to implement and covers the more common situations.

`flags-must'
one entry for every option that must be present when this option is present
`flags-cant'
one entry for every option that cannot be present when this option is present

Option Argument Specification

Several attributes relate to the handling of arguments to options. Each may appear only once, except for the arg-range attribute. It may appear as often as may be needed.

`arg-type'
This specifies the type of argument the option will take. If not present, the option cannot take an argument. If present, it must be one of the following four. The bracketed part of the name is optional.
`str[ing]'
The argument may be any arbitrary string.
`num[ber]'
The argument must be a correctly formed integer, without any trailing U's or L's. If you specify your own callback validation routine, read the arg-range section below for some considerations. AutoOpts contains a library procedure to convert the string to a number. If you specify range checking with arg-range, then AutoOpts produces a special purpose procedure for this option.
`bool[ean]'
The argument will be interpreted and always yield either AG_TRUE or AG_FALSE. False values are the empty string, the number zero, or a string that starts with f, F, n or N (representing False or No). Anything else will be interpreted as True.
`key[word]'
The argument must match a specified list of strings. Assuming you have named the option, opt-name, the strings will be converted into an enumeration of type te_Opt_Name with the values OPT_NAME_KEYWORD. If you have not specified a default value, the value OPT_NAME_UNDEFINED will be inserted with the value zero. The option will be initialized to that value. You may now use this in your code as follows:
te_Opt_Name opt = OPT_VALUE_OPT_NAME;
switch (opt) {
case OPT_NAME_UNDEFINED:  /* undefined things */ break;
case OPT_NAME_KEYWORD:    /* `keyword' things */ break;
default: /* utterly impossible */ ;
}
AutoOpts produces a special purpose procedure for this option.
`keyword'
If the arg-type is keyword, then you must specify the list of keywords by a series of keyword entries. The interface file will contain an enumeration of <OPT_NAME>_<KEYWORD> for each keyword entry.
`arg-optional'
This attribute indicates that the user does not have to supply an argument for the option. This is only valid if the arg-type is string or keyword. If it is keyword, then this attribute may also specify the default keyword to assume when the argument is not supplied. Without such a specification, the default keyword will be the zero-valued keyword.
`arg-default'
This specifies the default value to be used when the option is not specified or preset.
`default'
If your program processes its arguments in named option mode (See "long-opts" in section Program Description Attributes), then you may select one of your options to be the default option. Do so with this attribute. The option so specified must have an arg-type specified, but not the arg-optional attribute. That is to say, the option argument must be required. If you have done this, then any arguments that do not match an option name and do not contain an equal sign (=) will be interpreted as an option argument to the default option.
`arg-range'
If the arg-type is number, then arg-ranges may be specified, too. If you specify one or more of these option attributes, then AutoOpts will create a callback procedure for handling it. The argument value supplied for the option must match one of the range entries. Each arg-range should consist of either an integer by itself or an integer range. The integer range is specified by one or two integers separated by the two character sequence, ->. The generated procedure imposes some constraints: The usage procedure displays these ranges by calling the callback with the pOptDesc pointer set to NULL. Therefore, all callback procedures designed to handle options with numeric arguments must be prepared to handle a call with that pointer set NULL.

Option Argument Handling

AutoOpts will automatically generate a callback procedure for options with enumerated keyword arguments and numeric arguments with range checking. If you have specified such an option, you may not specify any of the attributes listed here.

Otherwise, you may pick zero or one of the following attributes. The first two attributes interact with the documentation and settable attributes, See section Special Option Handling.

`flag_code'
statements to execute when the option is encountered. The generated procedure will look like this:
static void
doOpt<name>( tOptions* pOptions, tOptDesc* pOptDesc )
{
<flag_code>
}
Only certain fields within the tOptions and tOptDesc structures may be accessed. See section Data for Option Processing.
`extract_code'
This is effectively identical to flag_code, except that the source is kept in the output file instead of the definitions file. A long comment is used to demarcate the code. You must not modify that marker. Before regenerating the option code file, the old file is renamed from MUMBLE.c to MUMBLE.c.save. The template will be looking there for the text to copy into the new output file.
`call_proc'
external procedure to call when option is encountered. The calling sequence must conform to the sequence defined above for the generated procedure, doOpt<name>. It has the same restrictions regarding the fields within the structures passed in as arguments. See section Data for Option Processing.
`flag_proc'
Name of another option whose flag_code can be executed when this option is encountered.
`stack_arg'
Call a special library routine to stack the option's arguments. Special macros in the interface file are provided for determining how many of the options were found (STACKCT_OPT(NAME)) and to obtain a pointer to a list of pointers to the argument values (STACKLST_OPT(NAME)).

Man and Info doc Attributes

AutoOpts includes AutoGen templates for producing abbreviated man pages and for producing the invoking section of an info document. To take advantage of these templates, you must add several attributes to your option definitions.

`doc'
First, every flag definition must have a doc attribute defined and many will need an arg-name attribute as well. The doc text should be in plain sentences with minimal formatting. The Texinfo commands @code, and @var will have its enclosed text made into \fB entries in the man page, and the @file text will be made into \fI entries. The arg-name attribute is used to display the option's argument in the man page.
`arg-name'
If an option has an argument, the argument should have a name for documentation purposes. It will default to arg-type, but it will likely be clearer with something else like, file-name instead of string (the type).
`prog-man-descrip'
`prog-info-descrip'
Then, you need to supply a brief description of what your program does. If you already have a detail definition, this may be sufficient. If not, or if you need special formatting for one of the manual formats, then you will need either a definition for prog-man-descrip or prog-info-descrip or both. These will be inserted verbatim in the man page document and the info document, respectively.
`man-doc'
Finally, if you need to add man page sections like SEE ALSO or USAGE or other, put that text in a man-doc definition. This text will be inserted verbatim in the man page after the OPTIONS section and before the AUTHOR section.

Automatically Supported Options

AutoOpts provides automated support for five options. help and more-help are always provided. version is provided if version is defined in the option definitions. save-opts and load-opts are provided if at least one homerc is defined.

Below are the option names and flag values. The flags are activated if and only if at least one user-defined option also uses a flag value. These flags may be deleted or changed to characters of your choosing by specifying xxx-value = "y";, where xxx is one of the five names below and y is either empty or the character of your choice. For example, to change the help flag from ? to h, specify help-value = "h";; and to require that save-opts be specified only with its long option name, specify save-opts-value = "";.

`help -?'
This option will immediately invoke the USAGE() procedure and display the usage line, a description of each option with its description and option usage information. This is followed by the contents of the definition of the detail text macro.
`more-help -!'
This option is identical to the help option, except that it also includes the contents of the detail-file file (if provided and found), plus the output is passed through a pager program. (more by default, or the program identified by the PAGER environment variable.)
`version -v'
This will print the program name, title and version. If it is followed by the letter c and a value for copyright and owner have been provided, then the copyright will be printed, too. If it is followed by the letter n, then the full copyright notice (if available) will be printed.
`save-opts ->'
This option will cause the option state to be printed in RC/INI file format when option processing is done but not yet verified for consistency. The program will terminate successfully without running when this has completed. Note that for most shells you will have to quote or escape the flag character to restrict special meanings to the shell. The output file will be the RC/INI file name (default or provided by rcfile) in the last directory named in a homerc definition
`load-opts -<'
This option will load options from the named file. They will be treated exactly as if they were loaded from the normally found RC/INI files, but will not be loaded until the option is actually processed. This can also be used within an RC/INI file causing them to nest. It is ultimately intended that specifying the option, no-load-opts will suppress the processing of rc/ini files and environment variables. To do this, AutoOpts must first implement pre-scanning of the options, environment and rc files.

Library of Standard Options

AutoOpts has developed a set of standardized options. You may incorporate these options in your program simply by adding a #define for the options you want, and the line,

#include stdoptions.def

in your option definitions. The supported options are specified thus:

#define DEBUG
#define DIRECTORY
#define DRY_RUN
#define INPUT
#define INTERACTIVE
#define OUTPUT
#define WARN

#define SILENT
#define QUIET
#define BRIEF
#define VERBOSE

By default, only the long form of the option will be available. To specify the short (flag) form, suffix these names with _FLAG. e.g.,

#define DEBUG_FLAG

--silent, --quiet, --brief and --verbose are related in that they all indicate some level of diagnostic output. These options are all designed to conflict with each other. Instead of four different options, however, several levels can be incorporated by #define-ing VERBOSE_ENUM. In conjunction with VERBOSE, it incorporates the notion of 5 levels in an enumeration: silent, quiet, brief, informative and verbose; with the default being brief.

Programmatic Interface

The user interface for access to the argument information is completely defined in the generated header file and in the portions of the distributed file "options.h" that are marked "public".

In the following macros, text marked <OPT_NAME> or optname is the name of the option in upper case and segmented with underscores _. The macros and enumerations defined in the options header (interface) file are used as follows:

To see how these #define macros are used in a program, the reader is referred to the several `opts.h' files included with the AutoGen sources.

Data for Option Processing

This section describes the data that may be accessed from within the option processing callback routines. The following fields may be used in the following ways and may be used for read only. The first set is addressed from the tOptDesc* pointer:

`optIndex'
`optValue'
These may be used by option procedures to determine which option they are working on (in case they handle several options).
`optActualIndex'
`optActualValue'
These may be used by option procedures to determine which option was used to set the current option. This may be different from the above if the options are members of an equivalence class.
`optOccCt'
If AutoOpts is processing command line arguments, then this value will contain the current occurrence count. During the option preset phase (reading rc/ini files and examining environment variables), the value is zero.
`fOptState'
The field may be tested for the following bit values (prefix each name with OPTST_, e.g. OPTST_INIT):
`INIT'
Initial compiled value. As a bit test, it will always yield FALSE.
`SET'
The option was set via the SET_OPT() macro.
`PRESET'
The option was set via an RC/INI file, or a call to the optionLoadLine() routine.
`DEFINED'
The option was set via a command line option.
`SET_MASK'
This is a mask of flags that show the set state, one of the above four values.
`EQUIVALENCE'
This bit is set when the option was selected by an equivalenced option.
`DISABLED'
This bit is set if the option is to be disabled. (Meaning it was a long option prefixed by the disablement prefix, or the option has not been specified yet and initializes as disabled.)
As an example of how this might be used, in AutoGen I want to allow template writers to specify that the template output can be left in a writable or read-only state. To support this, there is a Guile function named set-writable (see section `set-writable' - Make the output file be writable). Also, I provide for command options --writable and --not-writable. I give precedence to command line and RC file options, thus:
switch (STATE_OPT( WRITABLE )) {
case OPTST_DEFINED:
case OPTST_PRESET:
    fprintf( stderr, zOverrideWarn, pCurTemplate->pzFileName,
             pCurMacro->lineNo );
    break;

default:
    if (gh_boolean_p( set ) && (set == SCM_BOOL_F))
        CLEAR_OPT( WRITABLE );
    else
        SET_OPT_WRITABLE;
}
`pzLastArg'
Pointer to the latest argument string. BEWARE If the argument type is numeric or an enumeration, then this will be the argument value and not a pointer to a string.

The following two fields are addressed from the tOptions* pointer:

`pzProgName'
Points to a NUL-terminated string containing the current program name, as retrieved from the argument vector.
`pzProgPath'
Points to a NUL-terminated string containing the full path of the current program, as retrieved from the argument vector. (If available on your system.)

Note these fields get filled in during the first call to optionProcess(). All other fields are private, for the exclusive use of AutoOpts code and is subject to change.

CLEAR_OPT( <NAME> ) - Clear Option Markings

Make as if the option had never been specified. HAVE_OPT(<NAME>) will yield FALSE after invoking this macro.

COUNT_OPT( <NAME> ) - Definition Count

This macro will tell you how many times the option was specified on the command line. It does not include counts of preset options.

if (COUNT_OPT( NAME ) != desired-count) {
    make-an-undesirable-message.
}

DESC( <NAME> ) - Option Descriptor

This macro is used internally by other AutoOpt macros. It is not for general use. It is used to obtain the option description corresponding to its UPPER CASED option name argument. This is primarily used in other macro definitions.

DISABLE_OPT_name - Disable an option

This macro is emitted if it is both settable and it can be disabled. If it cannot be disabled, it may always be CLEAR-ed (see above).

The form of the macro will actually depend on whether the option is equivalenced to another, and/or has an assigned handler procedure. Unlike the SET_OPT macro, this macro does not allow an option argument.

DISABLE_OPT_NAME;

ENABLED( <NAME> ) - Is Option Enabled?

Yields true if the option defaults to disabled and ISUNUSED_OPT() would yield true. It also yields true if the option has been specified with a disablement prefix, disablement value or the DISABLE_OPT_NAME macro was invoked.

ERRSKIP_OPTERR - Ignore Option Errors

When it is necessary to continue (return to caller) on option errors, invoke this option. It is reversible. See section ERRSTOP_OPTERR - Stop on Errors.

ERRSTOP_OPTERR - Stop on Errors

After invoking this macro, if optionProcess() encounters an error, it will call exit(1) rather than return. This is the default processing mode. It can be overridden by specifying allow-errors in the definitions file, or invoking the macro See section ERRSKIP_OPTERR - Ignore Option Errors.

HAVE_OPT( <NAME> ) - Have this option?

This macro yields true if the option has been specified in any fashion at all. It is used thus:

if (HAVE_OPT( NAME )) {
    <do-things-associated-with-opt-name>;
}

ISSEL_OPT( <NAME> ) - Is Option Selected?

This macro yields true if the option has been specified either on the command line or via a SET/DISABLE macro.

ISUNUSED_OPT( <NAME> ) - Never Specified?

This macro yields true if the option has never been specified, or has been cleared via the CLEAR_OPT() macro.

OPTION_CT - Full Count of Options

The full count of all options, both those defined and those generated automatically by AutoOpts. This is primarily used to initialize the program option descriptor structure.

OPT_ARG( <NAME> ) - Option Argument String

The option argument value as a pointer to string. Note that argument values that have been specified as numbers are stored as numbers or keywords. For such options, use instead the OPT_VALUE_name define. It is used thus:

if (HAVE_OPT( NAME )) {
    char* p = OPT_ARG( NAME );
    <do-things-with-opt-name-argument-string>;
}

OPT_VALUE_name - Option Argument Value

This macro gets emitted only for options that take numeric or keyword arguments. The macro yields a word-sized integer containing the enumeration or numeric value of the option argument.

int opt_val = OPT_VALUE_NAME;

RESTART_OPT( n ) - Resume Option Processing

If option processing has stopped (either because of an error or something was encountered that looked like a program argument), it can be resumed by providing this macro with the index n of the next option to process and calling optionProcess() again.

SET_OPT_name - Force an option to be set

This macro gets emitted only when the given option has the settable attribute specified.

The form of the macro will actually depend on whether the option is equivalenced to another, has an option argument and/or has an assigned handler procedure. If the option has an argument, then this macro will too. Beware that the argument is not reallocated, so the value must not be on the stack or deallocated in any other way for as long as the value might get referenced.

SET_OPT_NAME( "string-value" );

STACKCT_OPT( <NAME> ) - Stacked Arg Count

When the option handling attribute is specified as stack_arg, this macro may be used to determine how many of them actually got stacked.

Do not use this on options that have not been stacked or has not been specified (the stack_arg attribute must have been specified, and HAVE_OPT(<NAME>) must yield TRUE). Otherwise, you will likely page fault.

if (HAVE_OPT( NAME )) {
    int     ct = STACKCT_OPT(  NAME );
    char**  pp = STACKLST_OPT( NAME );

    do  {
        char* p = *pp++;
        do-things-with-p;
    } while (--ct > 0);
}

STACKLST_OPT( <NAME> ) - Argument Stack

The address of the list of pointers to the option arguments. The pointers are ordered by the order in which they were encountered in the option presets and command line processing.

Do not use this on options that have not been stacked or has not been specified (the stack_arg attribute must have been specified, and HAVE_OPT(<OPTION>) must yield TRUE). Otherwise, you will likely page fault.

if (HAVE_OPT( NAME )) {
    int     ct = STACKCT_OPT(  NAME );
    char**  pp = STACKLST_OPT( NAME );

    do  {
        char* p = *pp++;
        do-things-with-p;
    } while (--ct > 0);
}

START_OPT - Restart Option Processing

This is just a shortcut for RESTART_OPT(1) (See section RESTART_OPT( n ) - Resume Option Processing.)

STATE_OPT( <NAME> ) - Option State

If you need to know if an option was set because of presetting actions (RC/INI processing or environment variables), versus a command line entry versus one of the SET/DISABLE macros, then use this macro. It will yield one of four values: OPTST_INIT, OPTST_SET, OPTST_PRESET or OPTST_DEFINED. It is used thus:

switch (STATE_OPT( NAME )) {
    case OPTST_INIT:
        not-preset, set or on the command line.  (unless CLEAR-ed)

    case OPTST_SET:
        option set via the SET_OPT_NAME() macro.

    case OPTST_PRESET:
        option set via an RC/INI file or environment variable

    case OPTST_DEFINED:
        option set via a command line option.

    default:
        cannot happen :)
}

USAGE( exit-code ) - Usage invocation macro

This macro invokes the procedure registered to display the usage text. Normally, this will be optionUsage from the AutoOpts library, but you may select another procedure by specifying usage = "proc_name" program attribute. This procedure must take two arguments first, a pointer to the option descriptor, and second the exit code. The macro supplies the option descriptor automatically. This routine is expected to call exit(3) with the provided exit code.

The optionUsage routine also behaves differently depending on the exit code. If the exit code is zero, it is assumed that assistance has been requested. Consequently, a little more information is provided than when displaying usage and exiting with a non-zero exit code.

VALUE_OPT_name - Option Flag Value

This is a #define for the flag character used to specify an option on the command line. If value was not specified for the option, then it is a unique number associated with the option. option value refers to this value, option argument refers to the (optional) argument to the option.

switch (WHICH_OPT_OTHER_OPT) {
case VALUE_OPT_NAME:
    this-option-was-really-opt-name;
case VALUE_OPT_OTHER_OPT:
    this-option-was-really-other-opt;
}

VERSION - Version and Full Version

If the version attribute is defined for the program, then a stringified version will be #defined as PROGRAM_VERSION and PROGRAM_FULL_VERSION. PROGRAM_FULL_VERSION is used for printing the program version in response to the version option. The version option is automatically supplied in response to this attribute, too.

You may access PROGRAM_VERSION via programOptions.pzFullVersion.

WHICH_IDX_name - Which Equivalenced Index

This macro gets emitted only for equivalenced-to options. It is used to obtain the index for the one of the several equivalence class members set the equivalenced-to option.

switch (WHICH_IDX_OTHER_OPT) {
case INDEX_OPT_NAME:
    this-option-was-really-opt-name;
case INDEX_OPT_OTHER_OPT:
    this-option-was-really-other-opt;
}

WHICH_OPT_name - Which Equivalenced Option

This macro gets emitted only for equivalenced-to options. It is used to obtain the value code for the one of the several equivalence class members set the equivalenced-to option.

switch (WHICH_OPT_OTHER_OPT) {
case VALUE_OPT_NAME:
    this-option-was-really-opt-name;
case VALUE_OPT_OTHER_OPT:
    this-option-was-really-other-opt;
}

teOptIndex - Option Index and Enumeration

This enum defines the complete set of options, both user specified and automatically provided. This can be used, for example, to distinguish which of the equivalenced options was actually used.

switch (pOptDesc->optActualIndex) {
case INDEX_OPT_FIRST:
    stuff;
case INDEX_OPT_DIFFERENT:
    different-stuff;
default:
    unknown-things;
}

OPTIONS_STRUCT_VERSION - active version

You will not actually need to reference this value, but you need to be aware that it is there. It is the first value in the option descriptor that you pass to optionProcess. It contains a magic number and version information. Normally, you should be able to work with a more recent option library than the one you compiled with. However, if the library is changed incompatibly, then the library will detect the out of date magic marker, explain the difficulty and exit. You will then need to rebuild and recompile your option definitions. This has rarely been necessary.

libopts procedures

These are the publicly exported procedures from the libopts library.

`optionProcess'
This is the main entry point for processing options. It is intended that this procedure be called once at the beginning of the execution of a program. Depending on options selected earlier, it is sometimes necessary to stop and restart option processing, or to select completely different sets of options. This can be done easily, but you generally do not want to do this.
`optionVersion'
Returns the full version string compiled into the library.
`optionLoadLine'
When passed a pointer to the option struct and a string, it will find the option named by the first token on the string and set the option argument to the remainder of the string. The caller must NUL terminate the string. Any embedded new lines will be included in the option argument.
`putBourneShell'
This routine will write to stdout the state of the options as encoded in the option structure. It will also write out the number of arguments consumed by option processing. The output result can be eval-ed by a shell in the following manner:
eval "`handle-prog-opts ${1+\"$@\"}`"
[ -z "$OPTION_CT" ] && exit 1
shift $OPTION_CT
This routine is normally specified by specifying test-main = yes; in the option definitions file.
`putShellParse'
This routine will write to stdout a series of shell commands that will parse the command line options. This routine will be called when you specify test-main = putShellParse; and the result is compiled with -DTEST_xxx_OPTS defined. This is the only way it should ever be invoked.
`all the rest'
The remaining routines are for the exclusive use of the generated option processing code. You should not be using them directly.

Option Descriptor File

This is the module that is to be compiled and linked with your program. It contains internal data and procedures subject to change. Basically, it contains a single global data structure containing all the information provided in the option definitions, plus a number of static strings and any callout procedures that are specified or required. You should never have need for looking at this, except, perhaps, to examine the code generated for implementing the flag_code construct.

Using AutoOpts

To use AutoOpts in your application:

AutoOpts for Shell Scripts

AutoOpts may be used with shell scripts by automatically creating a complete program that will process command line options and pass back the results to the invoking shell by issuing shell variable assignment commands. It may also be used to generate portable shell code that can be inserted into your script.

The functionality of these features, of course, is somewhat constrained compared with the normal program facilities. Specifically, you cannot invoke callout procedures with either of these methods. Additionally, if you generate a shell script:

  1. You cannot obtain options from RC/INI files.
  2. You cannot obtain options from environment variables.
  3. You cannot save the option state to an option file.
  4. Option conflict/requirement verification is disabled.

Both of these methods are enabled by running AutoGen on the definitions file with the additional global attribute:

test-main [ = proc-to-call ] ;

If you do not supply a proc-to-call, it will default to putBourneShell. That will produce a program that will process the options and generate shell text for the invoking shell to interpret. If you supply the name, putShellParse, then you will have a program that will generate a shell script that can parse the options. If you supply a different procedure name, you will have to provide that routine and it may do whatever you like.

In summary, you will need to issue approximately the following two commands to have a working program:

autogen -L <opt-template-dir> program.def
cc -o progopts -L <opt-lib-dir> -I <opt-include-dir> \
        -DTEST_program_OPTS program.c -lopts

The resulting program can be used within your shell script as follows:

eval `./progopts $@`
if [ -z "${OPTION_CT}" ] ; then exit 1 ; fi
shift ${OPTION_CT}

If you had used "test-main = putShellParse" instead, then you can, at this point, merely run the program and it will write the parsing script to standard out. You may also provide this program with command line options to specify the shell script file to create or edit, and you may specify the shell program to use on the first shell script line. That program's usage text would look something like this:

genshellopt - Generate Shell Option Processing Script - Ver. 1
USAGE:  genshellopt [ -<flag> [<val>] | --<name>[{=| }<val>] ]...
  Flg Arg Option-Name    Description
   -o YES script         Output Script File
   -s YES shell          Shell name (follows "#!" magic)
                                - disabled as --no-shell
                                - enabled by default
   -v opt version        Output version information and exit
   -? no  help           Display usage information and exit
   -! no  more-help      Extended usage information passed thru pager

Options may be specified by doubled hyphens and their name
or by a single hyphen and the flag character (option value).

Note that `shell' is only useful if the output file does not already
exist.  If it does, then the shell name and optional first argument
will be extracted from the script file.

If the script file already exists and contains Automated Option Processing
text, the second line of the file through the ending tag will be replaced
by the newly generated text.  The first `#!' line will be regenerated.

= = = = = = = =

This incarnation of genshell will produce
a shell script to parse the options for getdefs:

getdefs - AutoGen Definition Extraction Tool - Ver. 1.2
USAGE:  getdefs { <option-name>[{=| }<val>] }...
   Arg Option-Name   Req?  Description
   YES defs-to-get    opt  Regexp to look for after the "/*="
   opt ordering       opt  Alphabetize or use named file
   Num first-index    opt  The first index to apply to groups
   YES input          YES  Input file to search for defs
   YES subblock       opt  subblock definition names
   opt filelist       opt  Insert source file names into defs
   YES assign         opt  Global assignments
   YES common-assign  opt  Assignments common to all blocks
   YES copy           opt  File(s) to copy into definitions
   opt srcfile        opt  Insert source file name into each def
   opt linenum        opt  Insert source line number into each def
   YES output         opt  Output file to open
   opt autogen        opt  Invoke AutoGen with defs
   YES template       opt  Template Name
   YES agarg          opt  AutoGen Argument
   YES base-name      opt  Base name for output file(s)
   opt version        opt  Output version information and exit
   no  help           opt  Display usage information and exit
   no  more-help      opt  Extended usage information passed thru pager

All arguments are named options.

Automated `Invoking Info' Doc

Using the option definitions for an AutoOpt client program, the `aginfo.tpl' template will produce texinfo text that documents the invocation of your program. The text emitted is designed to be included in the full texinfo document for your product. It is not a stand-alone document. The usage text for the section autogen usage help (-?), section getdefs usage help and section columns usage help (-?) programs, are included in this document and are all generated using this template.

Two files will be produced, a `.texi' file and a `.menu' file. You should include the `.menu' file in your document where you wish to reference the `invoking' chapter, section or subsection. The documentation level is selected by passing a `-DLEVEL=<level-name>' argument to AutoGen when you build the document. (See the example invocation below.)

The `.texi' file will contain an introductory paragraph, a menu and a subordinate section for the invocation usage and for each documented option. The introductory paragraph is normally the boiler plate text:

This chapter documents the @file{AutoOpts} generated usage text
and option meanings for the @file{your-program} program.

However, if your program's option definitions include a `prog-info-descrip' section, then that is what will be used instead.

These files are produced by invoking the following command:

AutoGen -L ${prefix}/share/autogen -T aginfo.tpl \
        -DLEVEL=section your-opts.def

Where `${prefix}' is the AutoGen installation prefix and `your-opts.def' is the name of your product's option definition file.

Automated Man Pages

Using the option definitions for an AutoOpt client program, the `agman1.tpl' template will produce an nroff document suitable for use as a `man(1)' page document for a command line command. The description section of the document is either the `prog-man-descrip' text, if present, or the `detail' text.

Each option in the option definitions file is fully documented in its usage. This includes all the information documented above for each option (see section Option Attributes), plus the `doc' attribute is appended. Since the `doc' text is presumed to be designed for texinfo documentation, sed is used to convert some constructs from texi to nroff-for-man-pages. Specifically,

convert @code, @var and @samp into \fB...\fP phrases
convert @file into \fI...\fP phrases
Remove the '@' prefix from curly braces
Indent example regions
Delete the example commands
Replace `end example' command with ".br"
Replace the `@*' command with ".br"

This document is produced by invoking the following command:

AutoGen -L ${prefix}/share/autogen -T agman1.tpl options.def

Where `${prefix}' is the AutoGen installation prefix and `options.def' is the name of your product's option definition file. I do not use this very much, so any feedback or improvements would be greatly appreciated.


Go to the first, previous, next, last section, table of contents.