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