7.4.2 How to Write an Option Specification

An option specification is an association list (see Association Lists) with one list element for each supported option. The key of each list element is a symbol that names the option, while the value is a list of option properties:

OPTION-SPEC ::=  '( (OPT-NAME1 (PROP-NAME PROP-VALUE) ...)
                    (OPT-NAME2 (PROP-NAME PROP-VALUE) ...)
                    (OPT-NAME3 (PROP-NAME PROP-VALUE) ...)
                    ...
                  )

Each opt-name specifies the long option name for that option. For example, a list element with opt-name background specifies an option that can be specified on the command line using the long option --background. Further information about the option — whether it takes a value, whether it is required to be present in the command line, and so on — is specified by the option properties.

In the example of the preceding section, we already saw that a long option name can have a equivalent short option character. The equivalent short option character can be set for an option by specifying a single-char property in that option’s property list. For example, a list element like '(output (single-char #\o) …) specifies an option with long name --output that can also be specified by the equivalent short name -o.

The value property specifies whether an option requires or accepts a value. If the value property is set to #t, the option requires a value: getopt-long will signal an error if the option name is present without a corresponding value. If set to #f, the option does not take a value; in this case, a non-option word that follows the option name in the command line will be treated as a non-option argument. If set to the symbol optional, the option accepts a value but does not require one: a non-option word that follows the option name in the command line will be interpreted as that option’s value. If the option name for an option with '(value optional) is immediately followed in the command line by another option name, the value for the first option is implicitly #t.

The required? property indicates whether an option is required to be present in the command line. If the required? property is set to #t, getopt-long will signal an error if the option is not specified.

Finally, the predicate property can be used to constrain the possible values of an option. If used, the predicate property should be set to a procedure that takes one argument — the proposed option value as a string — and returns either #t or #f according as the proposed value is or is not acceptable. If the predicate procedure returns #f, getopt-long will signal an error.

By default, options do not have single-character equivalents, are not required, and do not take values. Where the list element for an option includes a value property but no predicate property, the option values are unconstrained.