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