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