3 * Options parsing, similar to GNU @getopt_long@
5 * (c) 1996 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of many programs.
12 * `mdwopt' is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU Library General Public License as
14 * published by the Free Software Foundation; either version 2 of the
15 * License, or (at your option) any later version.
17 * `mdwopt' is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU Library General Public License for more details.
22 * You should have received a copy of the GNU Library General Public
23 * License along with `mdwopt'; if not, write to the Free
24 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
28 /*----- External dependencies ---------------------------------------------*/
37 /*----- Configuration things ----------------------------------------------*/
41 #elif defined(__OS2__) || defined(__MSDOS__) || defined(__WINNT__)
43 #else /* Assume a sane filing system */
47 /*----- Global variables --------------------------------------------------*/
49 mdwopt_data mdwopt_global
= {0, 0, 0, 1, 0, 0, 0, 0, 0};
52 ORD_PERMUTE
= 0, /* Permute the options (default) */
53 ORD_RETURN
= 1, /* Return non-option things */
54 ORD_POSIX
= 2, /* Do POSIX-type hacking */
55 ORD_NEGATE
= 4 /* Magic negate-next-thing flag */
58 /*----- Word splitting ----------------------------------------------------*/
62 # define qword str_qword
67 * Arguments: @char **pp@ = address of pointer into string
68 * @unsigned f@ = various flags
70 * Returns: Pointer to the next space-separated possibly-quoted word from
71 * the string, or null.
73 * Use: Fetches the next word from a string. If the flag
74 * @STRF_QUOTE@ is set, the `\' character acts as an escape, and
75 * single and double quotes protect whitespace.
80 static char *qword(char **pp
, unsigned f
)
82 char *p
= *pp
, *q
, *qq
;
85 /* --- Preliminaries --- */
89 while (isspace((unsigned char)*p
))
96 /* --- Main work --- */
98 for (q
= qq
= p
; *q
; q
++) {
114 if (isspace((unsigned char)*q
)) {
115 do q
++; while (*q
&& isspace((unsigned char)*q
));
117 } else if (!(f
& STRF_QUOTE
))
135 /* --- Finished --- */
145 /*----- Main code ---------------------------------------------------------*/
147 /* --- @nextword@ --- *
149 * Arguments: @int argc@ = number of command line options
150 * @char *argv[]@ = pointer to command line options
151 * @mdwopt_data *data@ = pointer to persistent state
153 * Returns: Pointer to the next word to handle, or 0
155 * Use: Extracts the next word from the command line or environment
159 static char *nextword(int argc
, char *const *argv
, mdwopt_data
*data
)
161 if (data
->ind
== -1) {
163 if ((p
= qword(&data
->env
, STRF_QUOTE
)) != 0)
168 if (data
->next
== argc
)
170 return (argv
[data
->next
++]);
173 /* --- @permute@ --- *
175 * Arguments: @char *argv[]@ = pointer to command line arguments
176 * @mdwopt_data *data@ = pointer to persistent data
180 * Use: Moves a command line option into the right place.
183 static void permute(char *const *argv
, mdwopt_data
*data
)
185 char **v
= (char **)argv
;
186 if (data
->ind
!= -1) {
187 int i
= data
->next
- 1;
189 while (i
> data
->ind
) {
198 /* --- @findOpt@ --- *
200 * Arguments: @int o@ = which option to search for
201 * @const char *shortopt@ = short options string to search
202 * @mdwopt_data *data@ = pointer to persistant state
204 * Returns: Pointer to rest of short options string (including magic
207 * Use: Looks up a short option in the given string.
210 static const char *findOpt(int o
, const char *shortopt
,
213 const char *p
= shortopt
;
218 if (o
!= *p
|| (p
[1] != '+' && data
->order
& ORD_NEGATE
)) {
230 /* --- @mdwopt@ --- *
232 * Arguments: @int argc@ = number of command line arguments
233 * @char * const *argv@ = pointer to command line arguments
234 * @const char *shortopt@ = pointer to short options information
235 * @const struct option *longopts@ = pointer to long opts info
236 * @int *longind@ = where to store matched longopt
237 * @mdwopt_data *data@ = persistent state for the parser
238 * @int flags@ = various useful flags
240 * Returns: Value of option found next, or an error character, or
241 * @EOF@ for the last thing.
243 * Use: Reads options. The routine should be more-or-less compatible
244 * with standard getopts, although it provides many more
245 * features even than the standard GNU implementation.
247 * The precise manner of options parsing is determined by
248 * various flag settings, which are described below. By setting
249 * flag values appropriately, you can achieve behaviour very
250 * similar to most other getopt routines.
253 * How options parsing appears to users
255 * A command line consists of a number of `words' (which may
256 * contain spaces, according to various shell quoting
257 * conventions). A word may be an option, an argument to an
258 * option, or a non-option. An option begins with a special
259 * character, usually `%|-|%', although `%|+|%' is also used
260 * sometimes. As special exceptions, the word containing only a
261 * `%|-|%' is considered to be a non-option, since it usually
262 * represents standard input or output as a filename, and the
263 * word containing a double-dash `%|--|%' is used to mark all
264 * following words as being non-options regardless of their
267 * Traditionally, all words after the first non-option have been
268 * considered to be non-options automatically, so that options
269 * must be specified before filenames. However, this
270 * implementation can extract all the options from the command
271 * line regardless of their position. This can usually be
272 * disabled by setting one of the environment variables
273 * `%|POSIXLY_CORRECT|%' or `%|_POSIX_OPTION_ORDER|%'.
275 * There are two different styles of options: `short' and
278 * Short options are the sort which Unix has known for ages: an
279 * option is a single letter, preceded by a `%|-|%'. Short
280 * options can be joined together to save space (and possibly to
281 * make silly words): e.g., instead of giving options
282 * `%|-x -y|%', a user could write `%|-xy|%'. Some short
283 * options can have arguments, which appear after the option
284 * letter, either immediately following, or in the next `word'
285 * (so an option with an argument could be written as
286 * `%|-o foo|%' or as `%|-ofoo|%'). Note that options with
287 * optional arguments must be written in the second style.
289 * When a short option controls a flag setting, it is sometimes
290 * possible to explicitly turn the flag off, as well as turning
291 * it on, (usually to override default options). This is
292 * usually done by using a `%|+|%' instead of a `%|-|%' to
293 * introduce the option.
295 * Long options, as popularized by the GNU utilities, are given
296 * long-ish memorable names, preceded by a double-dash `%|--|%'.
297 * Since their names are more than a single character, long
298 * options can't be combined in the same way as short options.
299 * Arguments to long options may be given either in the same
300 * `word', separated from the option name by an equals sign, or
301 * in the following `word'.
303 * Long option names can be abbreviated if necessary, as long
304 * as the abbreviation is unique. This means that options can
305 * have sensible and memorable names but still not require much
306 * typing from an experienced user.
308 * Like short options, long options can control flag settings.
309 * The options to manipulate these settings come in pairs: an
310 * option of the form `%|--set-flag|%' might set the flag, while
311 * an option of the form `%|--no-set-flag|%' might clear it.
313 * It is usual for applications to provide both short and long
314 * options with identical behaviour. Some applications with
315 * lots of options may only provide long options (although they
316 * will often be only two or three characters long). In this
317 * case, long options can be preceded with a single `%|-|%'
318 * character, and negated by a `%|+|%' character.
320 * Finally, some (older) programs accept arguments of the form
321 * `%%@.{"-"<number>}%%', to set some numerical parameter,
322 * typically a line count of some kind.
325 * How programs parse options
327 * An application parses its options by calling mdwopt
328 * repeatedly. Each time it is called, mdwopt returns a value
329 * describing the option just read, and stores information about
330 * the option in a data block. The value %$-1$% is returned
331 * when there are no more options to be read. The `%|?|%'
332 * character is returned when an error is encountered.
334 * Before starting to parse options, the value @data->ind@ must
335 * be set to 0 or 1. The value of @data->err@ can also be set,
336 * to choose whether errors are reported by mdwopt.
338 * The program's `@argc@' and `@argv@' arguments are passed to
339 * the options parser, so that it can read the command line. A
340 * flags word is also passed, allowing the program fine control
341 * over parsing. The flags are described above.
343 * Short options are described by a string, which once upon a
344 * time just contained the permitted option characters. Now the
345 * options string begins with a collection of flag characters,
346 * and various flag characters can be put after options
347 * characters to change their properties.
349 * If the first character of the short options string is
350 * `%|+|%', `%|-|%' or `%|!|%', the order in which options are
351 * read is modified, as follows:
353 * `%|+|%' forces the POSIX order to be used. As soon as a non-
354 * option is found, mdwopt returns %$-1$%.
356 * `%|-|%' makes mdwopt treat non-options as being `special'
357 * sorts of option. When a non-option word is found, the
358 * value 0 is returned, and the actual text of the word
359 * is stored as being the option's argument.
361 * `%|!|%' forces the default order to be used. The entire
362 * command line is scanned for options, which are
363 * returned in order. However, during this process,
364 * the options are moved in the @argv@ array, so that
365 * they appear before the non- options.
367 * A `%|:|%' character may be placed after the ordering flag (or
368 * at the very beginning if no ordering flag is given) which
369 * indicates that the character `%|:|%', rather than `%|?|%',
370 * should be returned if a missing argument error is detected.
372 * Each option in the string can be followed by a `%|+|%' sign,
373 * indicating that it can be negated, a `%|:|%' sign indicating
374 * that it requires an argument, or a `%|::|%' string,
375 * indicating an optional argument. Both `%|+|%' and `%|:|%' or
376 * `%|::|%' may be given, although the `%|+|%' must come first.
378 * If an option is found, the option character is returned to
379 * the caller. A pointer to an argument is stored in
380 * @data->arg@, or @NULL@ is stored if there was no argument.
381 * If a negated option was found, the option character is
382 * returned ORred with @OPTF_NEGATED@ (bit 8 set).
384 * Long options are described in a table. Each entry in the
385 * table is of type @struct option@, and the table is terminated
386 * by an entry whose @name@ field is null. Each option has
387 * a flags word which, due to historical reasons, is called
388 * @has_arg@. This describes various properties of the option,
389 * such as what sort of argument it takes, and whether it can
392 * When mdwopt finds a long option, it looks the name up in the
393 * table. The index of the matching entry is stored in the
394 * @longind@ variable, passed to mdwopt (unless @longind@ is 0):
395 * a value of %$-1$% indicates that no long option was
396 * found. The behaviour is then dependent on the values in the
397 * table entry. If @flag@ is nonzero, it points to an integer
398 * to be modified by mdwopt. Usually the value in the @val@
399 * field is simply stored in the @flag@ variable. If the flag
400 * @OPTF_SWITCH@ is set, however, the value is combined with
401 * the existing value of the flags using a bitwise OR. If
402 * @OPTF_NEGATE@ is set, then the flag bit will be cleared if a
403 * matching negated long option is found. The value 0 is
406 * If @flag@ is zero, the value in @val@ is returned by mdwopt,
407 * possibly with bit 8 set if the option was negated.
409 * Arguments for long options are stored in @data->arg@, as
412 * Numeric options, if enabled, cause the value `%|#|%' to be
413 * returned, and the numeric value to be stored in @data->opt@.
415 * If the flag @OPTF_ENVVAR@ is set on entry, options will be
416 * extracted from an environment variable whose name is built by
417 * capitalizing all the letters of the program's name. (This
418 * allows a user to have different default settings for a
419 * program, by calling it through different symbolic links.)
422 int mdwopt(int argc
, char *const *argv
,
423 const char *shortopt
,
424 const struct option
*longopts
, int *longind
,
425 mdwopt_data
*data
, int flags
)
427 /* --- Local variables --- */
434 /* --- Sort out our data --- */
437 data
= &mdwopt_global
;
439 /* --- See if this is the first time --- */
441 if (data
->ind
== 0 || (data
->ind
== 1 && ~flags
& OPTF_NOPROGNAME
)) {
443 /* --- Sort out default returning order --- */
445 if (getenv("_POSIX_OPTION_ORDER") ||
446 getenv("POSIXLY_CORRECT"))
447 data
->order
= ORD_POSIX
;
449 data
->order
= ORD_PERMUTE
;
451 /* --- Now see what the caller actually wants --- */
453 switch (shortopt
[0]) {
455 data
->order
= ORD_RETURN
;
458 data
->order
= ORD_POSIX
;
461 data
->order
= ORD_PERMUTE
;
465 /* --- Now decide on the program's name --- */
467 if (~flags
& OPTF_NOPROGNAME
) {
468 p
= q
= (char *)argv
[0];
475 data
->ind
= data
->next
= 1;
478 /* --- See about environment variables --- *
480 * Be careful. The program may be setuid, and an attacker might have
481 * given us a long name in @argv[0]@. If the name is very long, don't
482 * support this option.
485 if (flags
& OPTF_ENVVAR
&& strlen(data
->prog
) < 48) {
489 /* --- For RISC OS, support a different format --- *
491 * Acorn's RISC OS tends to put settings in variables named
492 * `App$Options' rather than `APP'. Under RISC OS, I'll support
493 * both methods, just to avoid confuddlement.
497 sprintf(buf
, "%s$Options", data
->prog
);
505 *p
++ = toupper(*q
++);
513 /* --- Copy the options string into a buffer --- */
516 q
= malloc(strlen(p
) + 1);
519 "%s: Not enough memory to read settings in "
520 "environment variable\n",
525 data
->env
= data
->estart
= q
;
532 data
->ind
= data
->next
= 0;
535 /* --- Do some initial bodgery --- *
537 * The @shortopt@ string can have some interesting characters at the
538 * beginning. We'll skip past them.
541 switch (shortopt
[0]) {
549 if (shortopt
[0] == ':') {
559 /* --- Now go off and search for an option --- */
561 if (!data
->list
|| !*data
->list
) {
562 data
->order
&= 3; /* Clear negation flag */
564 /* --- Now we need to find the next option --- *
566 * Exactly how we do this depends on the settings of the order variable.
567 * We identify options as being things starting with `%|-|%', and which
568 * aren't equal to `%|-|%' or `%|--|%'. We'll look for options until:
570 * * We find something which isn't an option AND @order == ORD_POSIX@
571 * * We find a `%|--|%'
572 * * We reach the end of the list
574 * There are some added little wrinkles, which we'll meet as we go.
578 p
= nextword(argc
, argv
, data
);
582 /* --- See if we've found an option --- */
584 if ((p
[0] == '-' || (p
[0] == '+' && flags
& OPTF_NEGATION
)) &&
586 if (strcmp(p
, "--") == 0) {
593 /* --- Figure out how to proceed --- */
595 switch (data
->order
& 3) {
608 /* --- We found an option --- */
612 /* --- Check for a numeric option --- *
614 * We only check the first character (or the second if the first is a
615 * sign). This ought to be enough.
618 if (flags
& OPTF_NUMBERS
&& (p
[0] == '-' || flags
& OPTF_NEGNUMBER
)) {
619 if (((p
[1] == '+' || p
[1] == '-') && isdigit((unsigned char)p
[2])) ||
620 isdigit((unsigned char)p
[1])) {
621 data
->opt
= strtol(p
+ 1, &data
->arg
, 10);
622 while (isspace((unsigned char)data
->arg
[0]))
626 return (p
[0] == '-' ?
'#' : '#' | OPTF_NEGATED
);
630 /* --- Check for a long option --- */
633 data
->order
|= ORD_NEGATE
;
635 if (((p
[0] == '-' && p
[1] == '-') ||
636 (flags
& OPTF_NOSHORTS
&& !findOpt(p
[1], shortopt
, data
))) &&
637 (~flags
& OPTF_NOLONGS
))
642 data
->order
|= ORD_NEGATE
;
645 } else if (p
[1] == '-') {
646 if ((flags
& OPTF_NEGATION
) && strncmp(p
+ 2, "no-", 3) == 0) {
649 data
->order
|= ORD_NEGATE
;
655 if ((flags
& OPTF_NEGATION
) && strncmp(p
+ 1, "no-", 3) == 0) {
658 data
->order
|= ORD_NEGATE
;
665 for (i
= 0; longopts
[i
].name
; i
++) {
666 if ((data
->order
& ORD_NEGATE
) &&
667 (~longopts
[i
].has_arg
& OPTF_NEGATE
))
670 r
= (char *) longopts
[i
].name
;
673 if (*q
== 0 || *q
== '=') {
695 fprintf(stderr
, "%s: unrecognized option `%s%s'\n",
705 /* --- Handle argument behaviour --- */
707 while (*p
!= 0 && *p
!= '=')
709 p
= (*p ? p
+ 1 : 0);
710 q
= (char *) longopts
[match
].name
;
712 switch (longopts
[match
].has_arg
& OPTF_ARG
) {
717 "%s: option `%s%s' does not accept arguments\n",
727 p
= nextword(argc
, argv
, data
);
731 fprintf(stderr
, "%s: option `%s%s' requires an argument\n",
748 /* --- Do correct things now we have a match --- */
750 if (longopts
[match
].flag
) {
751 if (longopts
[match
].has_arg
& OPTF_SWITCH
) {
752 if (data
->order
& ORD_NEGATE
)
753 *longopts
[match
].flag
&= ~longopts
[match
].val
;
755 *longopts
[match
].flag
|= longopts
[match
].val
;
757 if (data
->order
& ORD_NEGATE
)
758 *longopts
[match
].flag
= 0;
760 *longopts
[match
].flag
= longopts
[match
].val
;
764 if (data
->order
& ORD_NEGATE
)
765 return (longopts
[match
].val
| OPTF_NEGATED
);
767 return (longopts
[match
].val
);
771 /* --- Do short options things --- */
775 data
->order
|= ORD_NEGATE
;
780 /* --- Now process the short options --- */
785 p
= (char *) findOpt(i
, shortopt
, data
);
788 fprintf(stderr
, "%s: unknown option `%c%c'\n",
790 data
->order
& ORD_NEGATE ?
'+' : '-',
798 /* --- Sort out an argument, if we expect one --- */
801 q
= (data
->list
[0] ? data
->list
: 0);
803 if (p
[1] != ':' && !q
) {
805 /* --- Same code as before --- */
807 q
= nextword(argc
, argv
, data
);
810 fprintf(stderr
, "%s: option `%c%c' requires an argument\n",
812 data
->order
& ORD_NEGATE ?
'+' : '-',
822 return ((data
->order
& ORD_NEGATE
) ? i
| OPTF_NEGATED
: i
);
825 /*----- That's all, folks -------------------------------------------------*/