chiark / gitweb /
Initial revision
[cfd] / mdwopt.h
1 /* -*-c-*-
2  *
3  * $Id: mdwopt.h,v 1.1 1999/05/05 19:23:47 mdw Exp $
4  *
5  * Options parsing, similar to GNU @getopt_long@
6  *
7  * (c) 1996 Mark Wooding
8  */
9
10 /*----- Licensing notice --------------------------------------------------*
11  *
12  * This file is part of many programs.
13  *
14  * `mdwopt' is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU Library General Public License as
16  * published by the Free Software Foundation; either version 2 of the
17  * License, or (at your option) any later version.
18  *
19  * `mdwopt' is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU Library General Public License for more details.
23  *
24  * You should have received a copy of the GNU Library General Public
25  * License along with `mdwopt'; if not, write to the Free Software
26  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27  */
28
29 /*----- Revision history --------------------------------------------------*
30  *
31  * $Log: mdwopt.h,v $
32  * Revision 1.1  1999/05/05 19:23:47  mdw
33  * Initial revision
34  *
35  * --- Previous lives ---
36  *
37  * %Log: mdwopt.h,v %
38  * Revision 1.5  1997/08/09 20:27:59  mdw
39  * Fix spelling of `Licensing'.
40  *
41  * Revision 1.4  1997/07/29 21:11:49  mdw
42  * Fixed address of the FSF.
43  *
44  * Revision 1.3  1996/12/31 19:41:33  mdw
45  * Formatting changes.
46  *
47  * Revision 1.2  1996/11/23 00:47:25  mdw
48  * Added `MdwOpt' object from the `anagram' source code.
49  *
50  * Revision 1.1  1996/09/24 18:01:43  mdw
51  * Initial revision
52  *
53  */
54
55 #ifndef MDWOPT_H
56 #define MDWOPT_H
57
58 /*----- Options handling structures ---------------------------------------*/
59
60 #ifdef __cplusplus
61   extern "C" {
62 #endif
63
64 /* --- @mdwopt_data@ --- *
65  *
66  * Contains all the information needed by the @mdwopt@ routine to do its
67  * work.
68  */
69
70 typedef struct {
71   /* --- Public variables --- */
72
73   char *arg;                            /* Arg of current option, or 0 */
74   int opt;                              /* Value of current option */
75   int ind;                              /* 0 for init, index when done */
76   int err;                              /* Set nonzero for error messages */
77   char *prog;                           /* Program name (from @argv[0]@) */
78
79   /* --- Private variables --- *
80    *
81    * Don't play with these, please.
82    */
83
84   char *list;                           /* Current short options pointer */
85   int next;                             /* Next argument, unpermuted */
86   int order;                            /* Ordering of options, flags */
87   char *env;                            /* Where we are in the env var */
88   char *estart;                         /* Pointer to env var buffer */
89 }
90 mdwopt_data;
91
92 /*----- Global variables --------------------------------------------------*/
93
94 extern mdwopt_data mdwopt_global;       /* The default global data */
95
96 /* --- For compatibility with older programs (and prettiness) --- *
97  *
98  * The macros here access the global structure defined above.  I consider it
99  * to be perfectly acceptable to use these macros in new code, because it
100  * looks nicer than playing with @mdwopt_global@.
101  */
102
103 #define optarg (mdwopt_global.arg)      /* Argument of current option */
104 #define optopt (mdwopt_global.opt)      /* Code of current option */
105 #define opterr (mdwopt_global.err)      /* Zero to report error messages */
106 #define optind (mdwopt_global.ind)      /* Index of first non-option */
107 #define optprog (mdwopt_global.prog)    /* Pointer to program name */
108
109 /*----- Type definitions --------------------------------------------------*/
110
111 /* --- Long options definition table --- */
112
113 struct option {
114   const char *name;                     /* Name of the long option */
115   int has_arg;                          /* Does it have an argument? */
116   int *flag;                            /* Address of flag variable */
117   int val;                              /* Value to store/return */
118 };
119
120 /* --- Old-style names for argument flags in long options table --- */
121
122 enum {
123   no_argument,                          /* No argument required */
124   required_argument,                    /* User must specify argument */
125   optional_argument                     /* Argument is optional */
126 };
127
128 /* --- New style flag names --- */
129
130 enum {
131   gFlag_argReq = 1,                     /* Required argument */
132   gFlag_argOpt = 2,                     /* Optional argument */
133   gFlag_switch = 4,                     /* OR val into flag, don't store */
134   gFlag_negate = 8,                     /* Allow long option to be negated */
135   gFlag__last_long_opt_flag = 0         /* Dummy value */
136 };
137
138 enum {
139   gFlag_noLongs = 1,                    /* Don't read long options */
140   gFlag_noShorts = 2,                   /* Don't read short options */
141   gFlag_numbers = 4,                    /* Read numeric options */
142   gFlag_negation = 8,                   /* Allow `%|+|%' for negations */
143   gFlag_envVar = 16,                    /* Parse options from env var */
144   gFlag_noProgName = 32,                /* Don't set @optprog@  */
145   gFlag_negNumber = 64,                 /* Allow negated number options */
146   gFlag__last_mdwopt_flag = 0           /* Dummy value */
147 };
148
149 enum {
150   gFlag_negated = 256,                  /* Option flag was negated by user */
151   gFlag__last_return_flag = 0           /* Dummy value */
152 };
153
154 /*----- Main code ---------------------------------------------------------*/
155
156 /* --- @mdwopt@ --- *
157  *
158  * Arguments:   @int argc@ = number of command line arguments
159  *              @char * const *argv@ = pointer to command line arguments
160  *              @const char *shortopt@ = pointer to short options information
161  *              @const struct option *longopts@ = pointer to long opts info
162  *              @int *longind@ = where to store matched longopt
163  *              @mdwopt_data *data@ = persistent state for the parser
164  *              @int flags@ = various useful flags
165  *
166  * Returns:     Value of option found next, or an error character, or
167  *              @EOF@ for the last thing.
168  *
169  * Use:         Reads options.  The routine should be more-or-less compatible
170  *              with standard getopts, although it provides many more
171  *              features even than the standard GNU implementation.
172  *
173  *              The precise manner of options parsing is determined by
174  *              various flag settings, which are described below.  By setting
175  *              flag values appropriately, you can achieve behaviour very
176  *              similar to most other getopt routines.
177  *
178  *
179  *          How options parsing appears to users
180  *
181  *              A command line consists of a number of `words' (which may
182  *              contain spaces, according to various shell quoting
183  *              conventions).  A word may be an option, an argument to an
184  *              option, or a non-option.  An option begins with a special
185  *              character, usually `%|-|%', although `%|+|%' is also used
186  *              sometimes.  As special exceptions, the word containing only a
187  *              `%|-|%' is considered to be a non-option, since it usually
188  *              represents standard input or output as a filename, and the
189  *              word containing a double-dash `%|--|%' is used to mark all
190  *              following words as being non-options regardless of their
191  *              initial character.
192  *
193  *              Traditionally, all words after the first non-option have been
194  *              considered to be non-options automatically, so that options
195  *              must be specified before filenames.  However, this
196  *              implementation can extract all the options from the command
197  *              line regardless of their position.  This can usually be
198  *              disabled by setting one of the environment variables
199  *              `%|POSIXLY_CORRECT|%' or `%|_POSIX_OPTION_ORDER|%'.
200  *
201  *              There are two different styles of options: `short' and
202  *              `long'.
203  *
204  *              Short options are the sort which Unix has known for ages: an
205  *              option is a single letter, preceded by a `%|-|%'.  Short
206  *              options can be joined together to save space (and possibly to
207  *              make silly words): e.g., instead of giving options
208  *              `%|-x.-y|%', a user could write `%|-xy|%'.  Some short
209  *              options can have arguments, which appear after the option
210  *              letter, either immediately following, or in the next `word'
211  *              (so an option with an argument could be written as
212  *              `%|-o foo|%' or as `%|-ofoo|%').  Note that options with
213  *              optional arguments must be written in the second style.
214  *
215  *              When a short option controls a flag setting, it is sometimes
216  *              possible to explicitly turn the flag off, as well as turning
217  *              it on, (usually to override default options).  This is
218  *              usually done by using a `%|+|%' instead of a `%|-|%' to
219  *              introduce the option.
220  *
221  *              Long options, as popularised by the GNU utilities, are given
222  *              long-ish memorable names, preceded by a double-dash `%|--|%'.
223  *              Since their names are more than a single character, long
224  *              options can't be combined in the same way as short options.
225  *              Arguments to long options may be given either in the same
226  *              `word', separated from the option name by an equals sign, or
227  *              in the following `word'.
228  *
229  *              Long option names can be abbreviated if necessary, as long
230  *              as the abbreviation is unique.  This means that options can
231  *              have sensible and memorable names but still not require much
232  *              typing from an experienced user.
233  *
234  *              Like short options, long options can control flag settings.
235  *              The options to manipulate these settings come in pairs: an
236  *              option of the form `%|--set-flag|%' might set the flag, while
237  *              an option of the form `%|--no-set-flag|%' might clear it.
238  *
239  *              It is usual for applications to provide both short and long
240  *              options with identical behaviour.  Some applications with
241  *              lots of options may only provide long options (although they
242  *              will often be only two or three characters long).  In this
243  *              case, long options can be preceded with a single `%|-|%'
244  *              character, and negated by a `%|+|%' character.
245  *
246  *              Finally, some (older) programs accept arguments of the form
247  *              `%%@.{"-"<number>}%%', to set some numerical parameter,
248  *              typically a line count of some kind.
249  *
250  *
251  *          How programs parse options
252  *
253  *              An application parses its options by calling mdwopt
254  *              repeatedly.  Each time it is called, mdwopt returns a value
255  *              describing the option just read, and stores information about
256  *              the option in a data block.  The value %$-1$% is returned
257  *              when there are no more options to be read.  The `%|?|%'
258  *              character is returned when an error is encountered.
259  *
260  *              Before starting to parse options, the value @data->ind@ must
261  *              be set to 0 or 1. The value of @data->err@ can also be set,
262  *              to choose whether errors are reported by mdwopt.
263  *
264  *              The program's `@argc@' and `@argv@' arguments are passed to
265  *              the options parser, so that it can read the command line.  A
266  *              flags word is also passed, allowing the program fine control
267  *              over parsing.  The flags are described above.
268  *
269  *              Short options are described by a string, which once upon a
270  *              time just contained the permitted option characters.  Now the
271  *              options string begins with a collection of flag characters,
272  *              and various flag characters can be put after options
273  *              characters to change their properties.
274  *
275  *              If the first character of the short options string is
276  *              `%|+|%', `%|-|%' or `%|!|%', the order in which options are
277  *              read is modified, as follows:
278  *
279  *              `%|+|%' forces the POSIX order to be used. As soon as a non-
280  *                      option is found, mdwopt returns %$-1$%.
281  *
282  *              `%|-|%' makes mdwopt treat non-options as being `special'
283  *                      sorts of option. When a non-option word is found, the
284  *                      value 0 is returned, and the actual text of the word
285  *                      is stored as being the option's argument.
286  *
287  *              `%|!|%' forces the default order to be used.  The entire
288  *                      command line is scanned for options, which are
289  *                      returned in order.  However, during this process,
290  *                      the options are moved in the @argv@ array, so that
291  *                      they appear before the non- options.
292  *
293  *              A `%|:|%' character may be placed after the ordering flag (or
294  *              at the very beginning if no ordering flag is given) which
295  *              indicates that the character `%|:|%', rather than `%|?|%',
296  *              should be returned if a missing argument error is detected.
297  *
298  *              Each option in the string can be followed by a `%|+|%' sign,
299  *              indicating that it can be negated, a `%|:|%' sign indicating
300  *              that it requires an argument, or a `%|::|%' string,
301  *              indicating an optional argument.  Both `%|+|%' and `%|:|%' or
302  *              `%|::|%' may be given, although the `%|+|%' must come first.
303  *
304  *              If an option is found, the option character is returned to
305  *              the caller.  A pointer to an argument is stored in
306  *              @data->arg@, or @NULL@ is stored if there was no argument.
307  *              If a negated option was found, the option character is
308  *              returned ORred with @gFlag_negated@ (bit 8 set).
309  *
310  *              Long options are described in a table.  Each entry in the
311  *              table is of type @struct option@, and the table is terminated
312  *              by an entry whose @name@ field is null.  Each option has
313  *              a flags word which, due to historical reasons, is called
314  *              @has_arg@.  This describes various properties of the option,
315  *              such as what sort of argument it takes, and whether it can
316  *              be negated.
317  *
318  *              When mdwopt finds a long option, it looks the name up in the
319  *              table. The index of the matching entry is stored in the
320  *              @longind@ variable, passed to mdwopt (unless @longind@ is 0):
321  *              a value of %$-1$% indicates that no long option was
322  *              found. The behaviour is then dependent on the values in the
323  *              table entry.  If @flag@ is nonzero, it points to an integer
324  *              to be modified by mdwopt.  Usually the value in the @val@
325  *              field is simply stored in the @flag@ variable. If the flag
326  *              @gFlag_switch@ is set, however, the value is combined with
327  *              the existing value of the flags using a bitwise OR.  If
328  *              @gFlag_negate@ is set, then the flag bit will be cleared if a
329  *              matching negated long option is found.  The value 0 is
330  *              returned.
331  *
332  *              If @flag@ is zero, the value in @val@ is returned by mdwopt,
333  *              possibly with bit 8 set if the option was negated.
334  *
335  *              Arguments for long options are stored in @data->arg@, as
336  *              before.
337  *
338  *              Numeric options, if enabled, cause the value `%|#|%' to be
339  *              returned, and the numeric value to be stored in @data->opt@.
340  *
341  *              If the flag @gFlag_envVar@ is set on entry, options will be
342  *              extracted from an environment variable whose name is built by
343  *              capitalising all the letters of the program's name.  (This
344  *              allows a user to have different default settings for a
345  *              program, by calling it through different symbolic links.)  */
346
347 extern int mdwopt(int /*argc*/, char *const */*argv*/,
348                   const char */*shortopt*/,
349                   const struct option */*longopts*/, int */*longind*/,
350                   mdwopt_data */*data*/, int /*flags*/);
351
352 /* --- Macros for more commonly used routines --- */
353
354 #define getopt(c, v, o) mdwopt(c, v, o, 0, 0, 0, gFlag_noLongs)
355 #define getopt_long(c, v, o, l, li) mdwopt(c, v, o, l, li, 0, 0)
356 #define getopt_long_only(c, v, o, l, li)                                \
357   mdwopt(c, v, o, l, li, 0, gFlag_noShorts)
358
359 #ifdef __cplusplus
360 }
361 #endif
362
363 /*----- C++ wrapper class -------------------------------------------------*/
364
365 #ifdef __cplusplus
366
367 /* --- Class: @MdwOpt@ --- *
368  *
369  * Parent:      ---
370  *
371  * Methods:     @MdwOpt@ -- construct a new mdwopt object with the given
372  *                      arguments.  These are remembered for later use.
373  *              @arg@ -- return the argument of the current option
374  *                      arguments.  These are remembered for later use.
375  *              @arg@ -- return the argument of the current option
376  *              @opt@ -- return the value of the current option
377  *              @ind@ -- return the index of the next unread argument
378  *              @longind@ -- return index of current long option in table
379  *              @errors@ -- return or set whether we report errors to the
380  *                      user
381  *              @prog@ -- return program name from @argv[0]@
382  *              @next@ -- return next option read from the table
383  *
384  * Use:         A simple C++ class for encapsulating the options parser.
385  *              The methods are all nice and simple, and extremely similar
386  *              to the normal C interface described above.
387  */
388
389 class MdwOpt {
390   protected:
391     int argc;
392     char * const *argv;
393     const char *shortopts;
394     const struct option *longopts;
395     int long_ind;
396     int flags;
397
398     mdwopt_data data;
399
400   public:
401     MdwOpt(int c, char * const *v, const char *so,
402            const struct option *lo, int f=0) :
403       argc(c), argv(v), shortopts(so), longopts(lo), flags(f) {
404         data.ind = 0;
405         data.err = 1;
406     }
407
408     const char *arg(void) const { return (data.arg); }
409     int opt(void) const { return (data.opt); }
410     int errors(void) const { return (data.err); }
411     int errors(int e) { int oe = data.err; data.err = e; return (oe); }
412     int ind(void) const { return (data.ind); }
413     int longind(void) const { return (long_ind); }
414     const char *prog(void) const { return (data.prog); }
415
416     int next(void) {
417       return (mdwopt(argc, argv, shortopts,
418                      longopts, &long_ind, &data, flags));
419     }
420 };
421
422 #endif
423
424 /*----- That's all, folks -------------------------------------------------*/
425
426 #endif