3 * $Id: mdwopt.c,v 1.8 1999/08/19 18:35:27 mdw Exp $
5 * Options parsing, similar to GNU @getopt_long@
7 * (c) 1996 Straylight/Edgeware
10 /*----- Licensing notice --------------------------------------------------*
12 * This file is part of many programs.
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.
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.
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,
30 /*----- Revision history --------------------------------------------------*
33 * Revision 1.8 1999/08/19 18:35:27 mdw
34 * Lots of reformatting. Spurious wing comments expunged.
36 * Revision 1.7 1999/06/18 21:59:46 mdw
37 * Fix stupid bug which only read one word from environment variables.
39 * Revision 1.6 1999/05/20 23:00:42 mdw
40 * Little formatting things.
42 * Revision 1.5 1999/05/19 20:23:59 mdw
43 * Change naming to match newer mLib conventions.
45 * Revision 1.4 1999/05/15 10:25:38 mdw
46 * Fix copyright information.
48 * Revision 1.3 1999/05/14 18:51:42 mdw
49 * Reformat the LGPL notice slightly.
51 * Revision 1.2 1999/05/13 22:57:23 mdw
52 * Change `-ise' to `-ize' throughout.
54 * Revision 1.1.1.1 1999/05/05 19:23:47 mdw
55 * New import. The old CVS repository was lost in a disk disaster.
57 * --- Previous lives ---
60 * Revision 1.7 1997/09/11 09:19:11 mdw
61 * (mo__nextWord): Arrrgh. Don't free the environment variable buffer!
62 * People are still using it!
64 * Revision 1.6 1997/09/11 09:05:54 mdw
65 * (mo__nextWord): Fix bug which returns too many words from environment
68 * Revision 1.5 1997/08/09 20:27:59 mdw
69 * Fix spelling of `Licensing'.
71 * Revision 1.4 1997/07/29 21:11:35 mdw
72 * Reformatted. Fixed buffer overflow when dealing with environment
73 * variables. Included NT in list of daft operating systems with `\' as a
74 * path separator. Fixed address of the FSF.
76 * Revision 1.3 1997/02/26 00:41:10 mdw
77 * Added GPL notice to the top. Slight formatting changes.
79 * Revision 1.2 1996/10/28 13:12:13 mdw
80 * Fixed calls to ctype.h routines. Arguments are cast to unsigned char
81 * to avoid invoking undefined behaviour caused by signedness of chars.
83 * Revision 1.1 1996/09/24 18:01:28 mdw
88 /*----- External dependencies ---------------------------------------------*/
97 /*----- Configuration things ----------------------------------------------*/
101 #elif defined(__OS2__) || defined(__MSDOS__) || defined(__WINNT__)
102 # define PATHSEP '\\'
103 #else /* Assume a sane filing system */
107 /*----- Global variables --------------------------------------------------*/
109 mdwopt_data mdwopt_global
= {0, 0, 0, 1, 0, 0, 0, 0, 0};
112 ORD_PERMUTE
= 0, /* Permute the options (default) */
113 ORD_RETURN
= 1, /* Return non-option things */
114 ORD_POSIX
= 2, /* Do POSIX-type hacking */
115 ORD_NEGATE
= 4 /* Magic negate-next-thing flag */
118 /*----- Main code ---------------------------------------------------------*/
120 /* --- @nextWord@ --- *
122 * Arguments: @int argc@ = number of command line options
123 * @char *argv[]@ = pointer to command line options
124 * @mdwopt_data *data@ = pointer to persistent state
126 * Returns: Pointer to the next word to handle, or 0
128 * Use: Extracts the next word from the command line or environment
132 static char *nextWord(int argc
, char *const *argv
, mdwopt_data
*data
)
134 if (data
->ind
== -1) {
137 while (isspace((unsigned char)*p
))
140 while (*p
&& !isspace((unsigned char)*p
))
151 if (data
->next
== argc
)
153 return (argv
[data
->next
++]);
156 /* --- @permute@ --- *
158 * Arguments: @char *argv[]@ = pointer to command line arguments
159 * @mdwopt_data *data@ = pointer to persistent data
163 * Use: Moves a command line option into the right place.
166 static void permute(char *const *argv
, mdwopt_data
*data
)
168 char **v
= (char **)argv
;
169 if (data
->ind
!= -1) {
170 int i
= data
->next
- 1;
172 while (i
> data
->ind
) {
181 /* --- @findOpt@ --- *
183 * Arguments: @int o@ = which option to search for
184 * @const char *shortopt@ = short options string to search
185 * @mdwopt_data *data@ = pointer to persistant state
187 * Returns: Pointer to rest of short options string (including magic
190 * Use: Looks up a short option in the given string.
193 static const char *findOpt(int o
, const char *shortopt
,
196 const char *p
= shortopt
;
201 if (o
!= *p
|| (p
[1] != '+' && data
->order
& ORD_NEGATE
)) {
213 /* --- @mdwopt@ --- *
215 * Arguments: @int argc@ = number of command line arguments
216 * @char * const *argv@ = pointer to command line arguments
217 * @const char *shortopt@ = pointer to short options information
218 * @const struct option *longopts@ = pointer to long opts info
219 * @int *longind@ = where to store matched longopt
220 * @mdwopt_data *data@ = persistent state for the parser
221 * @int flags@ = various useful flags
223 * Returns: Value of option found next, or an error character, or
224 * @EOF@ for the last thing.
226 * Use: Reads options. The routine should be more-or-less compatible
227 * with standard getopts, although it provides many more
228 * features even than the standard GNU implementation.
230 * The precise manner of options parsing is determined by
231 * various flag settings, which are described below. By setting
232 * flag values appropriately, you can achieve behaviour very
233 * similar to most other getopt routines.
236 * How options parsing appears to users
238 * A command line consists of a number of `words' (which may
239 * contain spaces, according to various shell quoting
240 * conventions). A word may be an option, an argument to an
241 * option, or a non-option. An option begins with a special
242 * character, usually `%|-|%', although `%|+|%' is also used
243 * sometimes. As special exceptions, the word containing only a
244 * `%|-|%' is considered to be a non-option, since it usually
245 * represents standard input or output as a filename, and the
246 * word containing a double-dash `%|--|%' is used to mark all
247 * following words as being non-options regardless of their
250 * Traditionally, all words after the first non-option have been
251 * considered to be non-options automatically, so that options
252 * must be specified before filenames. However, this
253 * implementation can extract all the options from the command
254 * line regardless of their position. This can usually be
255 * disabled by setting one of the environment variables
256 * `%|POSIXLY_CORRECT|%' or `%|_POSIX_OPTION_ORDER|%'.
258 * There are two different styles of options: `short' and
261 * Short options are the sort which Unix has known for ages: an
262 * option is a single letter, preceded by a `%|-|%'. Short
263 * options can be joined together to save space (and possibly to
264 * make silly words): e.g., instead of giving options
265 * `%|-x -y|%', a user could write `%|-xy|%'. Some short
266 * options can have arguments, which appear after the option
267 * letter, either immediately following, or in the next `word'
268 * (so an option with an argument could be written as
269 * `%|-o foo|%' or as `%|-ofoo|%'). Note that options with
270 * optional arguments must be written in the second style.
272 * When a short option controls a flag setting, it is sometimes
273 * possible to explicitly turn the flag off, as well as turning
274 * it on, (usually to override default options). This is
275 * usually done by using a `%|+|%' instead of a `%|-|%' to
276 * introduce the option.
278 * Long options, as popularized by the GNU utilities, are given
279 * long-ish memorable names, preceded by a double-dash `%|--|%'.
280 * Since their names are more than a single character, long
281 * options can't be combined in the same way as short options.
282 * Arguments to long options may be given either in the same
283 * `word', separated from the option name by an equals sign, or
284 * in the following `word'.
286 * Long option names can be abbreviated if necessary, as long
287 * as the abbreviation is unique. This means that options can
288 * have sensible and memorable names but still not require much
289 * typing from an experienced user.
291 * Like short options, long options can control flag settings.
292 * The options to manipulate these settings come in pairs: an
293 * option of the form `%|--set-flag|%' might set the flag, while
294 * an option of the form `%|--no-set-flag|%' might clear it.
296 * It is usual for applications to provide both short and long
297 * options with identical behaviour. Some applications with
298 * lots of options may only provide long options (although they
299 * will often be only two or three characters long). In this
300 * case, long options can be preceded with a single `%|-|%'
301 * character, and negated by a `%|+|%' character.
303 * Finally, some (older) programs accept arguments of the form
304 * `%%@.{"-"<number>}%%', to set some numerical parameter,
305 * typically a line count of some kind.
308 * How programs parse options
310 * An application parses its options by calling mdwopt
311 * repeatedly. Each time it is called, mdwopt returns a value
312 * describing the option just read, and stores information about
313 * the option in a data block. The value %$-1$% is returned
314 * when there are no more options to be read. The `%|?|%'
315 * character is returned when an error is encountered.
317 * Before starting to parse options, the value @data->ind@ must
318 * be set to 0 or 1. The value of @data->err@ can also be set,
319 * to choose whether errors are reported by mdwopt.
321 * The program's `@argc@' and `@argv@' arguments are passed to
322 * the options parser, so that it can read the command line. A
323 * flags word is also passed, allowing the program fine control
324 * over parsing. The flags are described above.
326 * Short options are described by a string, which once upon a
327 * time just contained the permitted option characters. Now the
328 * options string begins with a collection of flag characters,
329 * and various flag characters can be put after options
330 * characters to change their properties.
332 * If the first character of the short options string is
333 * `%|+|%', `%|-|%' or `%|!|%', the order in which options are
334 * read is modified, as follows:
336 * `%|+|%' forces the POSIX order to be used. As soon as a non-
337 * option is found, mdwopt returns %$-1$%.
339 * `%|-|%' makes mdwopt treat non-options as being `special'
340 * sorts of option. When a non-option word is found, the
341 * value 0 is returned, and the actual text of the word
342 * is stored as being the option's argument.
344 * `%|!|%' forces the default order to be used. The entire
345 * command line is scanned for options, which are
346 * returned in order. However, during this process,
347 * the options are moved in the @argv@ array, so that
348 * they appear before the non- options.
350 * A `%|:|%' character may be placed after the ordering flag (or
351 * at the very beginning if no ordering flag is given) which
352 * indicates that the character `%|:|%', rather than `%|?|%',
353 * should be returned if a missing argument error is detected.
355 * Each option in the string can be followed by a `%|+|%' sign,
356 * indicating that it can be negated, a `%|:|%' sign indicating
357 * that it requires an argument, or a `%|::|%' string,
358 * indicating an optional argument. Both `%|+|%' and `%|:|%' or
359 * `%|::|%' may be given, although the `%|+|%' must come first.
361 * If an option is found, the option character is returned to
362 * the caller. A pointer to an argument is stored in
363 * @data->arg@, or @NULL@ is stored if there was no argument.
364 * If a negated option was found, the option character is
365 * returned ORred with @OPTF_NEGATED@ (bit 8 set).
367 * Long options are described in a table. Each entry in the
368 * table is of type @struct option@, and the table is terminated
369 * by an entry whose @name@ field is null. Each option has
370 * a flags word which, due to historical reasons, is called
371 * @has_arg@. This describes various properties of the option,
372 * such as what sort of argument it takes, and whether it can
375 * When mdwopt finds a long option, it looks the name up in the
376 * table. The index of the matching entry is stored in the
377 * @longind@ variable, passed to mdwopt (unless @longind@ is 0):
378 * a value of %$-1$% indicates that no long option was
379 * found. The behaviour is then dependent on the values in the
380 * table entry. If @flag@ is nonzero, it points to an integer
381 * to be modified by mdwopt. Usually the value in the @val@
382 * field is simply stored in the @flag@ variable. If the flag
383 * @OPTF_SWITCH@ is set, however, the value is combined with
384 * the existing value of the flags using a bitwise OR. If
385 * @OPTF_NEGATE@ is set, then the flag bit will be cleared if a
386 * matching negated long option is found. The value 0 is
389 * If @flag@ is zero, the value in @val@ is returned by mdwopt,
390 * possibly with bit 8 set if the option was negated.
392 * Arguments for long options are stored in @data->arg@, as
395 * Numeric options, if enabled, cause the value `%|#|%' to be
396 * returned, and the numeric value to be stored in @data->opt@.
398 * If the flag @OPTF_ENVVAR@ is set on entry, options will be
399 * extracted from an environment variable whose name is built by
400 * capitalizing all the letters of the program's name. (This
401 * allows a user to have different default settings for a
402 * program, by calling it through different symbolic links.)
405 int mdwopt(int argc
, char *const *argv
,
406 const char *shortopt
,
407 const struct option
*longopts
, int *longind
,
408 mdwopt_data
*data
, int flags
)
410 /* --- Local variables --- */
417 /* --- Sort out our data --- */
420 data
= &mdwopt_global
;
422 /* --- See if this is the first time --- */
424 if (data
->ind
== 0 || (data
->ind
== 1 && ~flags
& OPTF_NOPROGNAME
)) {
426 /* --- Sort out default returning order --- */
428 if (getenv("_POSIX_OPTION_ORDER") ||
429 getenv("POSIXLY_CORRECT"))
430 data
->order
= ORD_POSIX
;
432 data
->order
= ORD_PERMUTE
;
434 /* --- Now see what the caller actually wants --- */
436 switch (shortopt
[0]) {
438 data
->order
= ORD_RETURN
;
441 data
->order
= ORD_POSIX
;
444 data
->order
= ORD_PERMUTE
;
448 /* --- Now decide on the program's name --- */
450 if (~flags
& OPTF_NOPROGNAME
) {
451 p
= q
= (char *)argv
[0];
458 data
->ind
= data
->next
= 1;
461 /* --- See about environment variables --- *
463 * Be careful. The program may be setuid, and an attacker might have
464 * given us a long name in @argv[0]@. If the name is very long, don't
465 * support this option.
468 if (flags
& OPTF_ENVVAR
&& strlen(data
->prog
) < 48) {
472 /* --- For RISC OS, support a different format --- *
474 * Acorn's RISC OS tends to put settings in variables named
475 * `App$Options' rather than `APP'. Under RISC OS, I'll support
476 * both methods, just to avoid confuddlement.
480 sprintf(buf
, "%s$Options", data
->prog
);
488 *p
++ = toupper(*q
++);
496 /* --- Copy the options string into a buffer --- */
499 q
= malloc(strlen(p
) + 1);
502 "%s: Not enough memory to read settings in "
503 "environment variable\n",
508 data
->env
= data
->estart
= q
;
515 data
->ind
= data
->next
= 0;
518 /* --- Do some initial bodgery --- *
520 * The @shortopt@ string can have some interesting characters at the
521 * beginning. We'll skip past them.
524 switch (shortopt
[0]) {
532 if (shortopt
[0] == ':') {
542 /* --- Now go off and search for an option --- */
544 if (!data
->list
|| !*data
->list
) {
545 data
->order
&= 3; /* Clear negation flag */
547 /* --- Now we need to find the next option --- *
549 * Exactly how we do this depends on the settings of the order variable.
550 * We identify options as being things starting with `%|-|%', and which
551 * aren't equal to `%|-|%' or `%|--|%'. We'll look for options until:
553 * * We find something which isn't an option AND @order == ORD_POSIX@
554 * * We find a `%|--|%'
555 * * We reach the end of the list
557 * There are some added little wrinkles, which we'll meet as we go.
561 p
= nextWord(argc
, argv
, data
);
565 /* --- See if we've found an option --- */
567 if ((p
[0] == '-' || (p
[0] == '+' && flags
& OPTF_NEGATION
)) &&
569 if (strcmp(p
, "--") == 0) {
576 /* --- Figure out how to proceed --- */
578 switch (data
->order
& 3) {
591 /* --- We found an option --- */
595 /* --- Check for a numeric option --- *
597 * We only check the first character (or the second if the first is a
598 * sign). This ought to be enough.
601 if (flags
& OPTF_NUMBERS
&& (p
[0] == '-' || flags
& OPTF_NEGNUMBER
)) {
602 if (((p
[1] == '+' || p
[1] == '-') && isdigit((unsigned char)p
[2])) ||
603 isdigit((unsigned char)p
[1])) {
604 data
->opt
= strtol(p
+ 1, &data
->arg
, 10);
605 while (isspace((unsigned char)data
->arg
[0]))
609 return (p
[0] == '-' ?
'#' : '#' | OPTF_NEGATED
);
613 /* --- Check for a long option --- */
616 data
->order
|= ORD_NEGATE
;
618 if (((p
[0] == '-' && p
[1] == '-') ||
619 (flags
& OPTF_NOSHORTS
&& !findOpt(p
[1], shortopt
, data
))) &&
620 (~flags
& OPTF_NOLONGS
))
625 data
->order
|= ORD_NEGATE
;
628 } else if (p
[1] == '-') {
629 if ((flags
& OPTF_NEGATION
) && strncmp(p
+ 2, "no-", 3) == 0) {
632 data
->order
|= ORD_NEGATE
;
638 if ((flags
& OPTF_NEGATION
) && strncmp(p
+ 1, "no-", 3) == 0) {
641 data
->order
|= ORD_NEGATE
;
648 for (i
= 0; longopts
[i
].name
; i
++) {
649 if ((data
->order
& ORD_NEGATE
) &&
650 (~longopts
[i
].has_arg
& OPTF_NEGATE
))
653 r
= (char *) longopts
[i
].name
;
656 if (*q
== 0 || *q
== '=') {
678 fprintf(stderr
, "%s: unrecognized option `%s%s'\n",
688 /* --- Handle argument behaviour --- */
690 while (*p
!= 0 && *p
!= '=')
692 p
= (*p ? p
+ 1 : 0);
693 q
= (char *) longopts
[match
].name
;
695 switch (longopts
[match
].has_arg
& OPTF_ARG
) {
700 "%s: option `%s%s' does not accept arguments\n",
710 p
= nextWord(argc
, argv
, data
);
714 fprintf(stderr
, "%s: option `%s%s' requires an argument\n",
731 /* --- Do correct things now we have a match --- */
733 if (longopts
[match
].flag
) {
734 if (longopts
[match
].has_arg
& OPTF_SWITCH
) {
735 if (data
->order
& ORD_NEGATE
)
736 *longopts
[match
].flag
&= ~longopts
[match
].val
;
738 *longopts
[match
].flag
|= longopts
[match
].val
;
740 if (data
->order
& ORD_NEGATE
)
741 *longopts
[match
].flag
= 0;
743 *longopts
[match
].flag
= longopts
[match
].val
;
747 if (data
->order
& ORD_NEGATE
)
748 return (longopts
[match
].val
| OPTF_NEGATED
);
750 return (longopts
[match
].val
);
754 /* --- Do short options things --- */
758 data
->order
|= ORD_NEGATE
;
763 /* --- Now process the short options --- */
768 p
= (char *) findOpt(i
, shortopt
, data
);
771 fprintf(stderr
, "%s: unknown option `%c%c'\n",
773 data
->order
& ORD_NEGATE ?
'+' : '-',
781 /* --- Sort out an argument, if we expect one --- */
784 q
= (data
->list
[0] ? data
->list
: 0);
786 if (p
[1] != ':' && !q
) {
788 /* --- Same code as before --- */
790 q
= nextWord(argc
, argv
, data
);
793 fprintf(stderr
, "%s: option `%c%c' requires an argument\n",
795 data
->order
& ORD_NEGATE ?
'+' : '-',
805 return ((data
->order
& ORD_NEGATE
) ? i
| OPTF_NEGATED
: i
);
808 /*----- That's all, folks -------------------------------------------------*/