Change to the linux kernel coding style
[wmaker-crm.git] / plugins / libwmfun / getopt.c
1 /* Getopt for GNU.
2 NOTE: getopt is now part of the C library, so if you don't know what
3 "Keep this file name-space clean" means, talk to roland@gnu.ai.mit.edu
4 before changing it!
5
6 Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94
7 Free Software Foundation, Inc.
8
9 This program is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option) any
12 later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details. */
18 \f
19 /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
20 Ditto for AIX 3.2 and <stdlib.h>. */
21 #ifndef _NO_PROTO
22 #define _NO_PROTO
23 #endif
24
25 #ifndef __STDC__
26 /* This is a separate conditional since some stdc systems
27 reject `defined (const)'. */
28 #ifndef const
29 #define const
30 #endif
31 #endif
32
33 #include <stdio.h>
34
35 #ifdef HAVE_STRING_H
36 #include <string.h>
37 #endif
38
39 /* Comment out all this code if we are using the GNU C Library, and are not
40 actually compiling the library itself. This code is part of the GNU C
41 Library, but also included in many other GNU distributions. Compiling
42 and linking in this code is a waste when using the GNU C library
43 (especially if it is a shared library). Rather than having every GNU
44 program understand `configure --with-gnu-libc' and omit the object files,
45 it is simpler to just do this in the source for each such file. */
46
47 #if defined (_LIBC) || !defined (__GNU_LIBRARY__)
48
49 /* This needs to come after some library #include
50 to get __GNU_LIBRARY__ defined. */
51 #ifdef __GNU_LIBRARY__
52 /* Don't include stdlib.h for non-GNU C libraries because some of them
53 contain conflicting prototypes for getopt. */
54 #include <stdlib.h>
55 #endif /* GNU C library. */
56
57 /* This version of `getopt' appears to the caller like standard Unix `getopt'
58 but it behaves differently for the user, since it allows the user
59 to intersperse the options with the other arguments.
60
61 As `getopt' works, it permutes the elements of ARGV so that,
62 when it is done, all the options precede everything else. Thus
63 all application programs are extended to handle flexible argument order.
64
65 Setting the environment variable POSIXLY_CORRECT disables permutation.
66 Then the behavior is completely standard.
67
68 GNU application programs can use a third alternative mode in which
69 they can distinguish the relative order of options and other arguments. */
70
71 #include "getopt.h"
72
73 /* For communication from `getopt' to the caller.
74 When `getopt' finds an option that takes an argument,
75 the argument value is returned here.
76 Also, when `ordering' is RETURN_IN_ORDER,
77 each non-option ARGV-element is returned here. */
78
79 char *optarg = NULL;
80
81 /* Index in ARGV of the next element to be scanned.
82 This is used for communication to and from the caller
83 and for communication between successive calls to `getopt'.
84
85 On entry to `getopt', zero means this is the first call; initialize.
86
87 When `getopt' returns EOF, this is the index of the first of the
88 non-option elements that the caller should itself scan.
89
90 Otherwise, `optind' communicates from one call to the next
91 how much of ARGV has been scanned so far. */
92
93 /* XXX 1003.2 says this must be 1 before any call. */
94 int optind = 0;
95
96 /* The next char to be scanned in the option-element
97 in which the last option character we returned was found.
98 This allows us to pick up the scan where we left off.
99
100 If this is zero, or a null string, it means resume the scan
101 by advancing to the next ARGV-element. */
102
103 static char *nextchar;
104
105 /* Callers store zero here to inhibit the error message
106 for unrecognized options. */
107
108 int opterr = 1;
109
110 /* Set to an option character which was unrecognized.
111 This must be initialized on some systems to avoid linking in the
112 system's own getopt implementation. */
113
114 int optopt = '?';
115
116 /* Describe how to deal with options that follow non-option ARGV-elements.
117
118 If the caller did not specify anything,
119 the default is REQUIRE_ORDER if the environment variable
120 POSIXLY_CORRECT is defined, PERMUTE otherwise.
121
122 REQUIRE_ORDER means don't recognize them as options;
123 stop option processing when the first non-option is seen.
124 This is what Unix does.
125 This mode of operation is selected by either setting the environment
126 variable POSIXLY_CORRECT, or using `+' as the first character
127 of the list of option characters.
128
129 PERMUTE is the default. We permute the contents of ARGV as we scan,
130 so that eventually all the non-options are at the end. This allows options
131 to be given in any order, even with programs that were not written to
132 expect this.
133
134 RETURN_IN_ORDER is an option available to programs that were written
135 to expect options and other ARGV-elements in any order and that care about
136 the ordering of the two. We describe each non-option ARGV-element
137 as if it were the argument of an option with character code 1.
138 Using `-' as the first character of the list of option characters
139 selects this mode of operation.
140
141 The special argument `--' forces an end of option-scanning regardless
142 of the value of `ordering'. In the case of RETURN_IN_ORDER, only
143 `--' can cause `getopt' to return EOF with `optind' != ARGC. */
144
145 static enum {
146 REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
147 } ordering;
148
149 /* Value of POSIXLY_CORRECT environment variable. */
150 static char *posixly_correct;
151 \f
152 #ifdef __GNU_LIBRARY__
153 /* We want to avoid inclusion of string.h with non-GNU libraries
154 because there are many ways it can cause trouble.
155 On some systems, it contains special magic macros that don't work
156 in GCC. */
157 #include <string.h>
158 #define my_index strchr
159 #else
160
161 /* Avoid depending on library functions or files
162 whose names are inconsistent. */
163
164 char *getenv();
165
166 static char *my_index(str, chr)
167 const char *str;
168 int chr;
169 {
170 while (*str) {
171 if (*str == chr)
172 return (char *)str;
173 str++;
174 }
175 return 0;
176 }
177
178 /* If using GCC, we can safely declare strlen this way.
179 If not using GCC, it is ok not to declare it. */
180 #ifdef __GNUC__
181 /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
182 That was relevant to code that was here before. */
183 #ifndef __STDC__
184 /* gcc with -traditional declares the built-in strlen to return int,
185 and has done so at least since version 2.4.5. -- rms. */
186 extern int strlen(const char *);
187 #endif /* not __STDC__ */
188 #endif /* __GNUC__ */
189
190 #endif /* not __GNU_LIBRARY__ */
191 \f
192 /* Handle permutation of arguments. */
193
194 /* Describe the part of ARGV that contains non-options that have
195 been skipped. `first_nonopt' is the index in ARGV of the first of them;
196 `last_nonopt' is the index after the last of them. */
197
198 static int first_nonopt;
199 static int last_nonopt;
200
201 /* Exchange two adjacent subsequences of ARGV.
202 One subsequence is elements [first_nonopt,last_nonopt)
203 which contains all the non-options that have been skipped so far.
204 The other is elements [last_nonopt,optind), which contains all
205 the options processed since those non-options were skipped.
206
207 `first_nonopt' and `last_nonopt' are relocated so that they describe
208 the new indices of the non-options in ARGV after they are moved. */
209
210 static void exchange(argv)
211 char **argv;
212 {
213 int bottom = first_nonopt;
214 int middle = last_nonopt;
215 int top = optind;
216 char *tem;
217
218 /* Exchange the shorter segment with the far end of the longer segment.
219 That puts the shorter segment into the right place.
220 It leaves the longer segment in the right place overall,
221 but it consists of two parts that need to be swapped next. */
222
223 while (top > middle && middle > bottom) {
224 if (top - middle > middle - bottom) {
225 /* Bottom segment is the short one. */
226 int len = middle - bottom;
227 register int i;
228
229 /* Swap it with the top part of the top segment. */
230 for (i = 0; i < len; i++) {
231 tem = argv[bottom + i];
232 argv[bottom + i] = argv[top - (middle - bottom) + i];
233 argv[top - (middle - bottom) + i] = tem;
234 }
235 /* Exclude the moved bottom segment from further swapping. */
236 top -= len;
237 } else {
238 /* Top segment is the short one. */
239 int len = top - middle;
240 register int i;
241
242 /* Swap it with the bottom part of the bottom segment. */
243 for (i = 0; i < len; i++) {
244 tem = argv[bottom + i];
245 argv[bottom + i] = argv[middle + i];
246 argv[middle + i] = tem;
247 }
248 /* Exclude the moved top segment from further swapping. */
249 bottom += len;
250 }
251 }
252
253 /* Update records for the slots the non-options now occupy. */
254
255 first_nonopt += (optind - last_nonopt);
256 last_nonopt = optind;
257 }
258
259 /* Initialize the internal data when the first call is made. */
260
261 static const char *_getopt_initialize(optstring)
262 const char *optstring;
263 {
264 /* Start processing options with ARGV-element 1 (since ARGV-element 0
265 is the program name); the sequence of previously skipped
266 non-option ARGV-elements is empty. */
267
268 first_nonopt = last_nonopt = optind = 1;
269
270 nextchar = NULL;
271
272 posixly_correct = getenv("POSIXLY_CORRECT");
273
274 /* Determine how to handle the ordering of options and nonoptions. */
275
276 if (optstring[0] == '-') {
277 ordering = RETURN_IN_ORDER;
278 ++optstring;
279 } else if (optstring[0] == '+') {
280 ordering = REQUIRE_ORDER;
281 ++optstring;
282 } else if (posixly_correct != NULL)
283 ordering = REQUIRE_ORDER;
284 else
285 ordering = PERMUTE;
286
287 return optstring;
288 }
289 \f
290 /* Scan elements of ARGV (whose length is ARGC) for option characters
291 given in OPTSTRING.
292
293 If an element of ARGV starts with '-', and is not exactly "-" or "--",
294 then it is an option element. The characters of this element
295 (aside from the initial '-') are option characters. If `getopt'
296 is called repeatedly, it returns successively each of the option characters
297 from each of the option elements.
298
299 If `getopt' finds another option character, it returns that character,
300 updating `optind' and `nextchar' so that the next call to `getopt' can
301 resume the scan with the following option character or ARGV-element.
302
303 If there are no more option characters, `getopt' returns `EOF'.
304 Then `optind' is the index in ARGV of the first ARGV-element
305 that is not an option. (The ARGV-elements have been permuted
306 so that those that are not options now come last.)
307
308 OPTSTRING is a string containing the legitimate option characters.
309 If an option character is seen that is not listed in OPTSTRING,
310 return '?' after printing an error message. If you set `opterr' to
311 zero, the error message is suppressed but we still return '?'.
312
313 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
314 so the following text in the same ARGV-element, or the text of the following
315 ARGV-element, is returned in `optarg'. Two colons mean an option that
316 wants an optional arg; if there is text in the current ARGV-element,
317 it is returned in `optarg', otherwise `optarg' is set to zero.
318
319 If OPTSTRING starts with `-' or `+', it requests different methods of
320 handling the non-option ARGV-elements.
321 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
322
323 Long-named options begin with `--' instead of `-'.
324 Their names may be abbreviated as long as the abbreviation is unique
325 or is an exact match for some defined option. If they have an
326 argument, it follows the option name in the same ARGV-element, separated
327 from the option name by a `=', or else the in next ARGV-element.
328 When `getopt' finds a long-named option, it returns 0 if that option's
329 `flag' field is nonzero, the value of the option's `val' field
330 if the `flag' field is zero.
331
332 The elements of ARGV aren't really const, because we permute them.
333 But we pretend they're const in the prototype to be compatible
334 with other systems.
335
336 LONGOPTS is a vector of `struct option' terminated by an
337 element containing a name which is zero.
338
339 LONGIND returns the index in LONGOPT of the long-named option found.
340 It is only valid when a long-named option has been found by the most
341 recent call.
342
343 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
344 long-named options. */
345
346 int _getopt_internal(argc, argv, optstring, longopts, longind, long_only)
347 int argc;
348 char *const *argv;
349 const char *optstring;
350 const struct option *longopts;
351 int *longind;
352 int long_only;
353 {
354 optarg = NULL;
355
356 if (optind == 0)
357 optstring = _getopt_initialize(optstring);
358
359 if (nextchar == NULL || *nextchar == '\0') {
360 /* Advance to the next ARGV-element. */
361
362 if (ordering == PERMUTE) {
363 /* If we have just processed some options following some non-options,
364 exchange them so that the options come first. */
365
366 if (first_nonopt != last_nonopt && last_nonopt != optind)
367 exchange((char **)argv);
368 else if (last_nonopt != optind)
369 first_nonopt = optind;
370
371 /* Skip any additional non-options
372 and extend the range of non-options previously skipped. */
373
374 while (optind < argc && (argv[optind][0] != '-' || argv[optind][1] == '\0'))
375 optind++;
376 last_nonopt = optind;
377 }
378
379 /* The special ARGV-element `--' means premature end of options.
380 Skip it like a null option,
381 then exchange with previous non-options as if it were an option,
382 then skip everything else like a non-option. */
383
384 if (optind != argc && !strcmp(argv[optind], "--")) {
385 optind++;
386
387 if (first_nonopt != last_nonopt && last_nonopt != optind)
388 exchange((char **)argv);
389 else if (first_nonopt == last_nonopt)
390 first_nonopt = optind;
391 last_nonopt = argc;
392
393 optind = argc;
394 }
395
396 /* If we have done all the ARGV-elements, stop the scan
397 and back over any non-options that we skipped and permuted. */
398
399 if (optind == argc) {
400 /* Set the next-arg-index to point at the non-options
401 that we previously skipped, so the caller will digest them. */
402 if (first_nonopt != last_nonopt)
403 optind = first_nonopt;
404 return EOF;
405 }
406
407 /* If we have come to a non-option and did not permute it,
408 either stop the scan or describe it to the caller and pass it by. */
409
410 if ((argv[optind][0] != '-' || argv[optind][1] == '\0')) {
411 if (ordering == REQUIRE_ORDER)
412 return EOF;
413 optarg = argv[optind++];
414 return 1;
415 }
416
417 /* We have found another option-ARGV-element.
418 Skip the initial punctuation. */
419
420 nextchar = (argv[optind] + 1 + (longopts != NULL && argv[optind][1] == '-'));
421 }
422
423 /* Decode the current option-ARGV-element. */
424
425 /* Check whether the ARGV-element is a long option.
426
427 If long_only and the ARGV-element has the form "-f", where f is
428 a valid short option, don't consider it an abbreviated form of
429 a long option that starts with f. Otherwise there would be no
430 way to give the -f short option.
431
432 On the other hand, if there's a long option "fubar" and
433 the ARGV-element is "-fu", do consider that an abbreviation of
434 the long option, just like "--fu", and not "-f" with arg "u".
435
436 This distinction seems to be the most useful approach. */
437
438 if (longopts != NULL
439 && (argv[optind][1] == '-'
440 || (long_only && (argv[optind][2] || !my_index(optstring, argv[optind][1]))))) {
441 char *nameend;
442 const struct option *p;
443 const struct option *pfound = NULL;
444 int exact = 0;
445 int ambig = 0;
446 int indfound;
447 int option_index;
448
449 for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
450 /* Do nothing. */ ;
451
452 /* Test all long options for either exact match
453 or abbreviated matches. */
454 for (p = longopts, option_index = 0; p->name; p++, option_index++)
455 if (!strncmp(p->name, nextchar, nameend - nextchar)) {
456 if (nameend - nextchar == (int)strlen(p->name)) {
457 /* Exact match found. */
458 pfound = p;
459 indfound = option_index;
460 exact = 1;
461 break;
462 } else if (pfound == NULL) {
463 /* First nonexact match found. */
464 pfound = p;
465 indfound = option_index;
466 } else
467 /* Second or later nonexact match found. */
468 ambig = 1;
469 }
470
471 if (ambig && !exact) {
472 if (opterr)
473 fprintf(stderr, "%s: option `%s' is ambiguous\n", argv[0], argv[optind]);
474 nextchar += strlen(nextchar);
475 optind++;
476 return '?';
477 }
478
479 if (pfound != NULL) {
480 option_index = indfound;
481 optind++;
482 if (*nameend) {
483 /* Don't test has_arg with >, because some C compilers don't
484 allow it to be used on enums. */
485 if (pfound->has_arg)
486 optarg = nameend + 1;
487 else {
488 if (opterr) {
489 if (argv[optind - 1][1] == '-')
490 /* --option */
491 fprintf(stderr,
492 "%s: option `--%s' doesn't allow an argument\n",
493 argv[0], pfound->name);
494 else
495 /* +option or -option */
496 fprintf(stderr,
497 "%s: option `%c%s' doesn't allow an argument\n",
498 argv[0], argv[optind - 1][0], pfound->name);
499 }
500 nextchar += strlen(nextchar);
501 return '?';
502 }
503 } else if (pfound->has_arg == 1) {
504 if (optind < argc)
505 optarg = argv[optind++];
506 else {
507 if (opterr)
508 fprintf(stderr, "%s: option `%s' requires an argument\n",
509 argv[0], argv[optind - 1]);
510 nextchar += strlen(nextchar);
511 return optstring[0] == ':' ? ':' : '?';
512 }
513 }
514 nextchar += strlen(nextchar);
515 if (longind != NULL)
516 *longind = option_index;
517 if (pfound->flag) {
518 *(pfound->flag) = pfound->val;
519 return 0;
520 }
521 return pfound->val;
522 }
523
524 /* Can't find it as a long option. If this is not getopt_long_only,
525 or the option starts with '--' or is not a valid short
526 option, then it's an error.
527 Otherwise interpret it as a short option. */
528 if (!long_only || argv[optind][1] == '-' || my_index(optstring, *nextchar) == NULL) {
529 if (opterr) {
530 if (argv[optind][1] == '-')
531 /* --option */
532 fprintf(stderr, "%s: unrecognized option `--%s'\n", argv[0], nextchar);
533 else
534 /* +option or -option */
535 fprintf(stderr, "%s: unrecognized option `%c%s'\n",
536 argv[0], argv[optind][0], nextchar);
537 }
538 nextchar = (char *)"";
539 optind++;
540 return '?';
541 }
542 }
543
544 /* Look at and handle the next short option-character. */
545
546 {
547 char c = *nextchar++;
548 char *temp = my_index(optstring, c);
549
550 /* Increment `optind' when we start to process its last character. */
551 if (*nextchar == '\0')
552 ++optind;
553
554 if (temp == NULL || c == ':') {
555 if (opterr) {
556 if (posixly_correct)
557 /* 1003.2 specifies the format of this message. */
558 fprintf(stderr, "%s: illegal option -- %c\n", argv[0], c);
559 else
560 fprintf(stderr, "%s: invalid option -- %c\n", argv[0], c);
561 }
562 optopt = c;
563 return '?';
564 }
565 if (temp[1] == ':') {
566 if (temp[2] == ':') {
567 /* This is an option that accepts an argument optionally. */
568 if (*nextchar != '\0') {
569 optarg = nextchar;
570 optind++;
571 } else
572 optarg = NULL;
573 nextchar = NULL;
574 } else {
575 /* This is an option that requires an argument. */
576 if (*nextchar != '\0') {
577 optarg = nextchar;
578 /* If we end this ARGV-element by taking the rest as an arg,
579 we must advance to the next element now. */
580 optind++;
581 } else if (optind == argc) {
582 if (opterr) {
583 /* 1003.2 specifies the format of this message. */
584 fprintf(stderr, "%s: option requires an argument -- %c\n",
585 argv[0], c);
586 }
587 optopt = c;
588 if (optstring[0] == ':')
589 c = ':';
590 else
591 c = '?';
592 } else
593 /* We already incremented `optind' once;
594 increment it again when taking next ARGV-elt as argument. */
595 optarg = argv[optind++];
596 nextchar = NULL;
597 }
598 }
599 return c;
600 }
601 }
602
603 int getopt(argc, argv, optstring)
604 int argc;
605 char *const *argv;
606 const char *optstring;
607 {
608 return _getopt_internal(argc, argv, optstring, (const struct option *)0, (int *)0, 0);
609 }
610
611 #endif /* _LIBC or not __GNU_LIBRARY__. */
612 \f
613 #ifdef TEST
614
615 /* Compile with -DTEST to make an executable for use in testing
616 the above definition of `getopt'. */
617
618 int main(argc, argv)
619 int argc;
620 char **argv;
621 {
622 int c;
623 int digit_optind = 0;
624
625 while (1) {
626 int this_option_optind = optind ? optind : 1;
627
628 c = getopt(argc, argv, "abc:d:0123456789");
629 if (c == EOF)
630 break;
631
632 switch (c) {
633 case '0':
634 case '1':
635 case '2':
636 case '3':
637 case '4':
638 case '5':
639 case '6':
640 case '7':
641 case '8':
642 case '9':
643 if (digit_optind != 0 && digit_optind != this_option_optind)
644 printf("digits occur in two different argv-elements.\n");
645 digit_optind = this_option_optind;
646 printf("option %c\n", c);
647 break;
648
649 case 'a':
650 printf("option a\n");
651 break;
652
653 case 'b':
654 printf("option b\n");
655 break;
656
657 case 'c':
658 printf("option c with value `%s'\n", optarg);
659 break;
660
661 case '?':
662 break;
663
664 default:
665 printf("?? getopt returned character code 0%o ??\n", c);
666 }
667 }
668
669 if (optind < argc) {
670 printf("non-option ARGV-elements: ");
671 while (optind < argc)
672 printf("%s ", argv[optind++]);
673 printf("\n");
674 }
675
676 exit(0);
677 }
678
679 #endif /* TEST */