Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | RSS feed

  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 drepper@gnu.org
  4.    before changing it!
  5.  
  6.    Copyright (C) 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
  7.    1996, 1997, 1998, 2005 Free Software Foundation, Inc.
  8.  
  9.    NOTE: This source is derived from an old version taken from the GNU C
  10.    Library (glibc).
  11.  
  12.    This program is free software; you can redistribute it and/or modify it
  13.    under the terms of the GNU General Public License as published by the
  14.    Free Software Foundation; either version 2, or (at your option) any
  15.    later version.
  16.  
  17.    This program 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 General Public License for more details.
  21.  
  22.    You should have received a copy of the GNU General Public License
  23.    along with this program; if not, write to the Free Software
  24.    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301,
  25.    USA.  */
  26. /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
  27.    Ditto for AIX 3.2 and <stdlib.h>.  */
  28. #ifndef _NO_PROTO
  29. # define _NO_PROTO
  30. #endif
  31.  
  32. #ifdef HAVE_CONFIG_H
  33. # include <config.h>
  34. #endif
  35.  
  36. #if !defined __STDC__ || !__STDC__
  37. /* This is a separate conditional since some stdc systems
  38.    reject `defined (const)'.  */
  39. # ifndef const
  40. #  define const
  41. # endif
  42. #endif
  43.  
  44. #include "ansidecl.h"
  45. #include <stdio.h>
  46.  
  47. /* Comment out all this code if we are using the GNU C Library, and are not
  48.    actually compiling the library itself.  This code is part of the GNU C
  49.    Library, but also included in many other GNU distributions.  Compiling
  50.    and linking in this code is a waste when using the GNU C library
  51.    (especially if it is a shared library).  Rather than having every GNU
  52.    program understand `configure --with-gnu-libc' and omit the object files,
  53.    it is simpler to just do this in the source for each such file.  */
  54.  
  55. #define GETOPT_INTERFACE_VERSION 2
  56. #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
  57. # include <gnu-versions.h>
  58. # if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
  59. #  define ELIDE_CODE
  60. # endif
  61. #endif
  62.  
  63. #ifndef ELIDE_CODE
  64.  
  65.  
  66. /* This needs to come after some library #include
  67.    to get __GNU_LIBRARY__ defined.  */
  68. #ifdef  __GNU_LIBRARY__
  69. /* Don't include stdlib.h for non-GNU C libraries because some of them
  70.    contain conflicting prototypes for getopt.  */
  71. # include <stdlib.h>
  72. # include <unistd.h>
  73. #endif  /* GNU C library.  */
  74.  
  75. #ifdef VMS
  76. # include <unixlib.h>
  77. # if HAVE_STRING_H - 0
  78. #  include <string.h>
  79. # endif
  80. #endif
  81.  
  82.  
  83. #  define _(msgid)  (msgid)
  84.  
  85. /* This version of `getopt' appears to the caller like standard Unix `getopt'
  86.    but it behaves differently for the user, since it allows the user
  87.    to intersperse the options with the other arguments.
  88.  
  89.    As `getopt' works, it permutes the elements of ARGV so that,
  90.    when it is done, all the options precede everything else.  Thus
  91.    all application programs are extended to handle flexible argument order.
  92.  
  93.    Setting the environment variable POSIXLY_CORRECT disables permutation.
  94.    Then the behavior is completely standard.
  95.  
  96.    GNU application programs can use a third alternative mode in which
  97.    they can distinguish the relative order of options and other arguments.  */
  98.  
  99. #include "getopt.h"
  100.  
  101. /* For communication from `getopt' to the caller.
  102.    When `getopt' finds an option that takes an argument,
  103.    the argument value is returned here.
  104.    Also, when `ordering' is RETURN_IN_ORDER,
  105.    each non-option ARGV-element is returned here.  */
  106.  
  107. char *optarg = NULL;
  108.  
  109. /* Index in ARGV of the next element to be scanned.
  110.    This is used for communication to and from the caller
  111.    and for communication between successive calls to `getopt'.
  112.  
  113.    On entry to `getopt', zero means this is the first call; initialize.
  114.  
  115.    When `getopt' returns -1, this is the index of the first of the
  116.    non-option elements that the caller should itself scan.
  117.  
  118.    Otherwise, `optind' communicates from one call to the next
  119.    how much of ARGV has been scanned so far.  */
  120.  
  121. /* 1003.2 says this must be 1 before any call.  */
  122. int optind = 1;
  123.  
  124. /* Formerly, initialization of getopt depended on optind==0, which
  125.    causes problems with re-calling getopt as programs generally don't
  126.    know that. */
  127.  
  128. int __getopt_initialized = 0;
  129.  
  130. /* The next char to be scanned in the option-element
  131.    in which the last option character we returned was found.
  132.    This allows us to pick up the scan where we left off.
  133.  
  134.    If this is zero, or a null string, it means resume the scan
  135.    by advancing to the next ARGV-element.  */
  136.  
  137. static char *nextchar;
  138.  
  139. /* Callers store zero here to inhibit the error message
  140.    for unrecognized options.  */
  141.  
  142. int opterr = 1;
  143.  
  144. /* Set to an option character which was unrecognized.
  145.    This must be initialized on some systems to avoid linking in the
  146.    system's own getopt implementation.  */
  147.  
  148. int optopt = '?';
  149.  
  150. /* Describe how to deal with options that follow non-option ARGV-elements.
  151.  
  152.    If the caller did not specify anything,
  153.    the default is REQUIRE_ORDER if the environment variable
  154.    POSIXLY_CORRECT is defined, PERMUTE otherwise.
  155.  
  156.    REQUIRE_ORDER means don't recognize them as options;
  157.    stop option processing when the first non-option is seen.
  158.    This is what Unix does.
  159.    This mode of operation is selected by either setting the environment
  160.    variable POSIXLY_CORRECT, or using `+' as the first character
  161.    of the list of option characters.
  162.  
  163.    PERMUTE is the default.  We permute the contents of ARGV as we scan,
  164.    so that eventually all the non-options are at the end.  This allows options
  165.    to be given in any order, even with programs that were not written to
  166.    expect this.
  167.  
  168.    RETURN_IN_ORDER is an option available to programs that were written
  169.    to expect options and other ARGV-elements in any order and that care about
  170.    the ordering of the two.  We describe each non-option ARGV-element
  171.    as if it were the argument of an option with character code 1.
  172.    Using `-' as the first character of the list of option characters
  173.    selects this mode of operation.
  174.  
  175.    The special argument `--' forces an end of option-scanning regardless
  176.    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
  177.    `--' can cause `getopt' to return -1 with `optind' != ARGC.  */
  178.  
  179. static enum
  180. {
  181.   REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
  182. } ordering;
  183.  
  184. /* Value of POSIXLY_CORRECT environment variable.  */
  185. static char *posixly_correct;
  186. #ifdef  __GNU_LIBRARY__
  187. /* We want to avoid inclusion of string.h with non-GNU libraries
  188.    because there are many ways it can cause trouble.
  189.    On some systems, it contains special magic macros that don't work
  190.    in GCC.  */
  191. # include <string.h>
  192. # define my_index       strchr
  193. #else
  194.  
  195. # if HAVE_STRING_H
  196. #  include <string.h>
  197. # else
  198. #  if HAVE_STRINGS_H
  199. #   include <strings.h>
  200. #  endif
  201. # endif
  202.  
  203. /* Avoid depending on library functions or files
  204.    whose names are inconsistent.  */
  205.  
  206. #if HAVE_STDLIB_H && HAVE_DECL_GETENV
  207. #  include <stdlib.h>
  208. #elif !defined(getenv)
  209. #  ifdef __cplusplus
  210. extern "C" {
  211. #  endif /* __cplusplus */
  212. extern char *getenv (const char *);
  213. #  ifdef __cplusplus
  214. }
  215. #  endif /* __cplusplus */
  216. #endif
  217.  
  218. static char *
  219. my_index (const char *str, int chr)
  220. {
  221.   while (*str)
  222.     {
  223.       if (*str == chr)
  224.         return (char *) str;
  225.       str++;
  226.     }
  227.   return 0;
  228. }
  229.  
  230. /* If using GCC, we can safely declare strlen this way.
  231.    If not using GCC, it is ok not to declare it.  */
  232. #ifdef __GNUC__
  233. /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
  234.    That was relevant to code that was here before.  */
  235. # if (!defined __STDC__ || !__STDC__) && !defined strlen
  236. /* gcc with -traditional declares the built-in strlen to return int,
  237.    and has done so at least since version 2.4.5. -- rms.  */
  238. extern int strlen (const char *);
  239. # endif /* not __STDC__ */
  240. #endif /* __GNUC__ */
  241.  
  242. #endif /* not __GNU_LIBRARY__ */
  243. /* Handle permutation of arguments.  */
  244.  
  245. /* Describe the part of ARGV that contains non-options that have
  246.    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
  247.    `last_nonopt' is the index after the last of them.  */
  248.  
  249. static int first_nonopt;
  250. static int last_nonopt;
  251.  
  252. #ifdef _LIBC
  253. /* Bash 2.0 gives us an environment variable containing flags
  254.    indicating ARGV elements that should not be considered arguments.  */
  255.  
  256. /* Defined in getopt_init.c  */
  257. extern char *__getopt_nonoption_flags;
  258.  
  259. static int nonoption_flags_max_len;
  260. static int nonoption_flags_len;
  261.  
  262. static int original_argc;
  263. static char *const *original_argv;
  264.  
  265. /* Make sure the environment variable bash 2.0 puts in the environment
  266.    is valid for the getopt call we must make sure that the ARGV passed
  267.    to getopt is that one passed to the process.  */
  268. static void
  269. __attribute__ ((unused))
  270. store_args_and_env (int argc, char *const *argv)
  271. {
  272.   /* XXX This is no good solution.  We should rather copy the args so
  273.      that we can compare them later.  But we must not use malloc(3).  */
  274.   original_argc = argc;
  275.   original_argv = argv;
  276. }
  277. # ifdef text_set_element
  278. text_set_element (__libc_subinit, store_args_and_env);
  279. # endif /* text_set_element */
  280.  
  281. # define SWAP_FLAGS(ch1, ch2) \
  282.   if (nonoption_flags_len > 0)                                                \
  283.     {                                                                         \
  284.       char __tmp = __getopt_nonoption_flags[ch1];                             \
  285.       __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2];          \
  286.       __getopt_nonoption_flags[ch2] = __tmp;                                  \
  287.     }
  288. #else   /* !_LIBC */
  289. # define SWAP_FLAGS(ch1, ch2)
  290. #endif  /* _LIBC */
  291.  
  292. /* Exchange two adjacent subsequences of ARGV.
  293.    One subsequence is elements [first_nonopt,last_nonopt)
  294.    which contains all the non-options that have been skipped so far.
  295.    The other is elements [last_nonopt,optind), which contains all
  296.    the options processed since those non-options were skipped.
  297.  
  298.    `first_nonopt' and `last_nonopt' are relocated so that they describe
  299.    the new indices of the non-options in ARGV after they are moved.  */
  300.  
  301. #if defined __STDC__ && __STDC__
  302. static void exchange (char **);
  303. #endif
  304.  
  305. static void
  306. exchange (char **argv)
  307. {
  308.   int bottom = first_nonopt;
  309.   int middle = last_nonopt;
  310.   int top = optind;
  311.   char *tem;
  312.  
  313.   /* Exchange the shorter segment with the far end of the longer segment.
  314.      That puts the shorter segment into the right place.
  315.      It leaves the longer segment in the right place overall,
  316.      but it consists of two parts that need to be swapped next.  */
  317.  
  318. #ifdef _LIBC
  319.   /* First make sure the handling of the `__getopt_nonoption_flags'
  320.      string can work normally.  Our top argument must be in the range
  321.      of the string.  */
  322.   if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
  323.     {
  324.       /* We must extend the array.  The user plays games with us and
  325.          presents new arguments.  */
  326.       char *new_str = (char *) malloc (top + 1);
  327.       if (new_str == NULL)
  328.         nonoption_flags_len = nonoption_flags_max_len = 0;
  329.       else
  330.         {
  331.           memset (mempcpy (new_str, __getopt_nonoption_flags,
  332.                            nonoption_flags_max_len),
  333.                   '\0', top + 1 - nonoption_flags_max_len);
  334.           nonoption_flags_max_len = top + 1;
  335.           __getopt_nonoption_flags = new_str;
  336.         }
  337.     }
  338. #endif
  339.  
  340.   while (top > middle && middle > bottom)
  341.     {
  342.       if (top - middle > middle - bottom)
  343.         {
  344.           /* Bottom segment is the short one.  */
  345.           int len = middle - bottom;
  346.           register int i;
  347.  
  348.           /* Swap it with the top part of the top segment.  */
  349.           for (i = 0; i < len; i++)
  350.             {
  351.               tem = argv[bottom + i];
  352.               argv[bottom + i] = argv[top - (middle - bottom) + i];
  353.               argv[top - (middle - bottom) + i] = tem;
  354.               SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
  355.             }
  356.           /* Exclude the moved bottom segment from further swapping.  */
  357.           top -= len;
  358.         }
  359.       else
  360.         {
  361.           /* Top segment is the short one.  */
  362.           int len = top - middle;
  363.           register int i;
  364.  
  365.           /* Swap it with the bottom part of the bottom segment.  */
  366.           for (i = 0; i < len; i++)
  367.             {
  368.               tem = argv[bottom + i];
  369.               argv[bottom + i] = argv[middle + i];
  370.               argv[middle + i] = tem;
  371.               SWAP_FLAGS (bottom + i, middle + i);
  372.             }
  373.           /* Exclude the moved top segment from further swapping.  */
  374.           bottom += len;
  375.         }
  376.     }
  377.  
  378.   /* Update records for the slots the non-options now occupy.  */
  379.  
  380.   first_nonopt += (optind - last_nonopt);
  381.   last_nonopt = optind;
  382. }
  383.  
  384. /* Initialize the internal data when the first call is made.  */
  385.  
  386. #if defined __STDC__ && __STDC__
  387. static const char *_getopt_initialize (int, char *const *, const char *);
  388. #endif
  389. static const char *
  390. _getopt_initialize (int argc ATTRIBUTE_UNUSED,
  391.                     char *const *argv ATTRIBUTE_UNUSED,
  392.                     const char *optstring)
  393. {
  394.   /* Start processing options with ARGV-element 1 (since ARGV-element 0
  395.      is the program name); the sequence of previously skipped
  396.      non-option ARGV-elements is empty.  */
  397.  
  398.   first_nonopt = last_nonopt = optind;
  399.  
  400.   nextchar = NULL;
  401.  
  402.   posixly_correct = getenv ("POSIXLY_CORRECT");
  403.  
  404.   /* Determine how to handle the ordering of options and nonoptions.  */
  405.  
  406.   if (optstring[0] == '-')
  407.     {
  408.       ordering = RETURN_IN_ORDER;
  409.       ++optstring;
  410.     }
  411.   else if (optstring[0] == '+')
  412.     {
  413.       ordering = REQUIRE_ORDER;
  414.       ++optstring;
  415.     }
  416.   else if (posixly_correct != NULL)
  417.     ordering = REQUIRE_ORDER;
  418.   else
  419.     ordering = PERMUTE;
  420.  
  421. #ifdef _LIBC
  422.   if (posixly_correct == NULL
  423.       && argc == original_argc && argv == original_argv)
  424.     {
  425.       if (nonoption_flags_max_len == 0)
  426.         {
  427.           if (__getopt_nonoption_flags == NULL
  428.               || __getopt_nonoption_flags[0] == '\0')
  429.             nonoption_flags_max_len = -1;
  430.           else
  431.             {
  432.               const char *orig_str = __getopt_nonoption_flags;
  433.               int len = nonoption_flags_max_len = strlen (orig_str);
  434.               if (nonoption_flags_max_len < argc)
  435.                 nonoption_flags_max_len = argc;
  436.               __getopt_nonoption_flags =
  437.                 (char *) malloc (nonoption_flags_max_len);
  438.               if (__getopt_nonoption_flags == NULL)
  439.                 nonoption_flags_max_len = -1;
  440.               else
  441.                 memset (mempcpy (__getopt_nonoption_flags, orig_str, len),
  442.                         '\0', nonoption_flags_max_len - len);
  443.             }
  444.         }
  445.       nonoption_flags_len = nonoption_flags_max_len;
  446.     }
  447.   else
  448.     nonoption_flags_len = 0;
  449. #endif
  450.  
  451.   return optstring;
  452. }
  453. /* Scan elements of ARGV (whose length is ARGC) for option characters
  454.    given in OPTSTRING.
  455.  
  456.    If an element of ARGV starts with '-', and is not exactly "-" or "--",
  457.    then it is an option element.  The characters of this element
  458.    (aside from the initial '-') are option characters.  If `getopt'
  459.    is called repeatedly, it returns successively each of the option characters
  460.    from each of the option elements.
  461.  
  462.    If `getopt' finds another option character, it returns that character,
  463.    updating `optind' and `nextchar' so that the next call to `getopt' can
  464.    resume the scan with the following option character or ARGV-element.
  465.  
  466.    If there are no more option characters, `getopt' returns -1.
  467.    Then `optind' is the index in ARGV of the first ARGV-element
  468.    that is not an option.  (The ARGV-elements have been permuted
  469.    so that those that are not options now come last.)
  470.  
  471.    OPTSTRING is a string containing the legitimate option characters.
  472.    If an option character is seen that is not listed in OPTSTRING,
  473.    return '?' after printing an error message.  If you set `opterr' to
  474.    zero, the error message is suppressed but we still return '?'.
  475.  
  476.    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
  477.    so the following text in the same ARGV-element, or the text of the following
  478.    ARGV-element, is returned in `optarg'.  Two colons mean an option that
  479.    wants an optional arg; if there is text in the current ARGV-element,
  480.    it is returned in `optarg', otherwise `optarg' is set to zero.
  481.  
  482.    If OPTSTRING starts with `-' or `+', it requests different methods of
  483.    handling the non-option ARGV-elements.
  484.    See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
  485.  
  486.    Long-named options begin with `--' instead of `-'.
  487.    Their names may be abbreviated as long as the abbreviation is unique
  488.    or is an exact match for some defined option.  If they have an
  489.    argument, it follows the option name in the same ARGV-element, separated
  490.    from the option name by a `=', or else the in next ARGV-element.
  491.    When `getopt' finds a long-named option, it returns 0 if that option's
  492.    `flag' field is nonzero, the value of the option's `val' field
  493.    if the `flag' field is zero.
  494.  
  495.    The elements of ARGV aren't really const, because we permute them.
  496.    But we pretend they're const in the prototype to be compatible
  497.    with other systems.
  498.  
  499.    LONGOPTS is a vector of `struct option' terminated by an
  500.    element containing a name which is zero.
  501.  
  502.    LONGIND returns the index in LONGOPT of the long-named option found.
  503.    It is only valid when a long-named option has been found by the most
  504.    recent call.
  505.  
  506.    If LONG_ONLY is nonzero, '-' as well as '--' can introduce
  507.    long-named options.  */
  508.  
  509. int
  510. _getopt_internal (int argc, char *const *argv, const char *optstring,
  511.                   const struct option *longopts,
  512.                   int *longind, int long_only)
  513. {
  514.   optarg = NULL;
  515.  
  516.   if (optind == 0 || !__getopt_initialized)
  517.     {
  518.       if (optind == 0)
  519.         optind = 1;     /* Don't scan ARGV[0], the program name.  */
  520.       optstring = _getopt_initialize (argc, argv, optstring);
  521.       __getopt_initialized = 1;
  522.     }
  523.  
  524.   /* Test whether ARGV[optind] points to a non-option argument.
  525.      Either it does not have option syntax, or there is an environment flag
  526.      from the shell indicating it is not an option.  The later information
  527.      is only used when the used in the GNU libc.  */
  528. #ifdef _LIBC
  529. # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0'       \
  530.                       || (optind < nonoption_flags_len                        \
  531.                           && __getopt_nonoption_flags[optind] == '1'))
  532. #else
  533. # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
  534. #endif
  535.  
  536.   if (nextchar == NULL || *nextchar == '\0')
  537.     {
  538.       /* Advance to the next ARGV-element.  */
  539.  
  540.       /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
  541.          moved back by the user (who may also have changed the arguments).  */
  542.       if (last_nonopt > optind)
  543.         last_nonopt = optind;
  544.       if (first_nonopt > optind)
  545.         first_nonopt = optind;
  546.  
  547.       if (ordering == PERMUTE)
  548.         {
  549.           /* If we have just processed some options following some non-options,
  550.              exchange them so that the options come first.  */
  551.  
  552.           if (first_nonopt != last_nonopt && last_nonopt != optind)
  553.             exchange ((char **) argv);
  554.           else if (last_nonopt != optind)
  555.             first_nonopt = optind;
  556.  
  557.           /* Skip any additional non-options
  558.              and extend the range of non-options previously skipped.  */
  559.  
  560.           while (optind < argc && NONOPTION_P)
  561.             optind++;
  562.           last_nonopt = optind;
  563.         }
  564.  
  565.       /* The special ARGV-element `--' means premature end of options.
  566.          Skip it like a null option,
  567.          then exchange with previous non-options as if it were an option,
  568.          then skip everything else like a non-option.  */
  569.  
  570.       if (optind != argc && !strcmp (argv[optind], "--"))
  571.         {
  572.           optind++;
  573.  
  574.           if (first_nonopt != last_nonopt && last_nonopt != optind)
  575.             exchange ((char **) argv);
  576.           else if (first_nonopt == last_nonopt)
  577.             first_nonopt = optind;
  578.           last_nonopt = argc;
  579.  
  580.           optind = argc;
  581.         }
  582.  
  583.       /* If we have done all the ARGV-elements, stop the scan
  584.          and back over any non-options that we skipped and permuted.  */
  585.  
  586.       if (optind == argc)
  587.         {
  588.           /* Set the next-arg-index to point at the non-options
  589.              that we previously skipped, so the caller will digest them.  */
  590.           if (first_nonopt != last_nonopt)
  591.             optind = first_nonopt;
  592.           return -1;
  593.         }
  594.  
  595.       /* If we have come to a non-option and did not permute it,
  596.          either stop the scan or describe it to the caller and pass it by.  */
  597.  
  598.       if (NONOPTION_P)
  599.         {
  600.           if (ordering == REQUIRE_ORDER)
  601.             return -1;
  602.           optarg = argv[optind++];
  603.           return 1;
  604.         }
  605.  
  606.       /* We have found another option-ARGV-element.
  607.          Skip the initial punctuation.  */
  608.  
  609.       nextchar = (argv[optind] + 1
  610.                   + (longopts != NULL && argv[optind][1] == '-'));
  611.     }
  612.  
  613.   /* Decode the current option-ARGV-element.  */
  614.  
  615.   /* Check whether the ARGV-element is a long option.
  616.  
  617.      If long_only and the ARGV-element has the form "-f", where f is
  618.      a valid short option, don't consider it an abbreviated form of
  619.      a long option that starts with f.  Otherwise there would be no
  620.      way to give the -f short option.
  621.  
  622.      On the other hand, if there's a long option "fubar" and
  623.      the ARGV-element is "-fu", do consider that an abbreviation of
  624.      the long option, just like "--fu", and not "-f" with arg "u".
  625.  
  626.      This distinction seems to be the most useful approach.  */
  627.  
  628.   if (longopts != NULL
  629.       && (argv[optind][1] == '-'
  630.           || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
  631.     {
  632.       char *nameend;
  633.       const struct option *p;
  634.       const struct option *pfound = NULL;
  635.       int exact = 0;
  636.       int ambig = 0;
  637.       int indfound = -1;
  638.       int option_index;
  639.  
  640.       for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
  641.         /* Do nothing.  */ ;
  642.  
  643.       /* Test all long options for either exact match
  644.          or abbreviated matches.  */
  645.       for (p = longopts, option_index = 0; p->name; p++, option_index++)
  646.         if (!strncmp (p->name, nextchar, nameend - nextchar))
  647.           {
  648.             if ((unsigned int) (nameend - nextchar)
  649.                 == (unsigned int) strlen (p->name))
  650.               {
  651.                 /* Exact match found.  */
  652.                 pfound = p;
  653.                 indfound = option_index;
  654.                 exact = 1;
  655.                 break;
  656.               }
  657.             else if (pfound == NULL)
  658.               {
  659.                 /* First nonexact match found.  */
  660.                 pfound = p;
  661.                 indfound = option_index;
  662.               }
  663.             else
  664.               /* Second or later nonexact match found.  */
  665.               ambig = 1;
  666.           }
  667.  
  668.       if (ambig && !exact)
  669.         {
  670.           if (opterr)
  671.             fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
  672.                      argv[0], argv[optind]);
  673.           nextchar += strlen (nextchar);
  674.           optind++;
  675.           optopt = 0;
  676.           return '?';
  677.         }
  678.  
  679.       if (pfound != NULL)
  680.         {
  681.           option_index = indfound;
  682.           optind++;
  683.           if (*nameend)
  684.             {
  685.               /* Don't test has_arg with >, because some C compilers don't
  686.                  allow it to be used on enums.  */
  687.               if (pfound->has_arg)
  688.                 optarg = nameend + 1;
  689.               else
  690.                 {
  691.                   if (opterr)
  692.                     {
  693.                       if (argv[optind - 1][1] == '-')
  694.                         /* --option */
  695.                         fprintf (stderr,
  696.                                  _("%s: option `--%s' doesn't allow an argument\n"),
  697.                                  argv[0], pfound->name);
  698.                       else
  699.                         /* +option or -option */
  700.                         fprintf (stderr,
  701.                                  _("%s: option `%c%s' doesn't allow an argument\n"),
  702.                                  argv[0], argv[optind - 1][0], pfound->name);
  703.  
  704.                       nextchar += strlen (nextchar);
  705.  
  706.                       optopt = pfound->val;
  707.                       return '?';
  708.                     }
  709.                 }
  710.             }
  711.           else if (pfound->has_arg == 1)
  712.             {
  713.               if (optind < argc)
  714.                 optarg = argv[optind++];
  715.               else
  716.                 {
  717.                   if (opterr)
  718.                     fprintf (stderr,
  719.                            _("%s: option `%s' requires an argument\n"),
  720.                            argv[0], argv[optind - 1]);
  721.                   nextchar += strlen (nextchar);
  722.                   optopt = pfound->val;
  723.                   return optstring[0] == ':' ? ':' : '?';
  724.                 }
  725.             }
  726.           nextchar += strlen (nextchar);
  727.           if (longind != NULL)
  728.             *longind = option_index;
  729.           if (pfound->flag)
  730.             {
  731.               *(pfound->flag) = pfound->val;
  732.               return 0;
  733.             }
  734.           return pfound->val;
  735.         }
  736.  
  737.       /* Can't find it as a long option.  If this is not getopt_long_only,
  738.          or the option starts with '--' or is not a valid short
  739.          option, then it's an error.
  740.          Otherwise interpret it as a short option.  */
  741.       if (!long_only || argv[optind][1] == '-'
  742.           || my_index (optstring, *nextchar) == NULL)
  743.         {
  744.           if (opterr)
  745.             {
  746.               if (argv[optind][1] == '-')
  747.                 /* --option */
  748.                 fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
  749.                          argv[0], nextchar);
  750.               else
  751.                 /* +option or -option */
  752.                 fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
  753.                          argv[0], argv[optind][0], nextchar);
  754.             }
  755.           nextchar = (char *) "";
  756.           optind++;
  757.           optopt = 0;
  758.           return '?';
  759.         }
  760.     }
  761.  
  762.   /* Look at and handle the next short option-character.  */
  763.  
  764.   {
  765.     char c = *nextchar++;
  766.     char *temp = my_index (optstring, c);
  767.  
  768.     /* Increment `optind' when we start to process its last character.  */
  769.     if (*nextchar == '\0')
  770.       ++optind;
  771.  
  772.     if (temp == NULL || c == ':')
  773.       {
  774.         if (opterr)
  775.           {
  776.             if (posixly_correct)
  777.               /* 1003.2 specifies the format of this message.  */
  778.               fprintf (stderr, _("%s: illegal option -- %c\n"),
  779.                        argv[0], c);
  780.             else
  781.               fprintf (stderr, _("%s: invalid option -- %c\n"),
  782.                        argv[0], c);
  783.           }
  784.         optopt = c;
  785.         return '?';
  786.       }
  787.     /* Convenience. Treat POSIX -W foo same as long option --foo */
  788.     if (temp[0] == 'W' && temp[1] == ';')
  789.       {
  790.         char *nameend;
  791.         const struct option *p;
  792.         const struct option *pfound = NULL;
  793.         int exact = 0;
  794.         int ambig = 0;
  795.         int indfound = 0;
  796.         int option_index;
  797.  
  798.         /* This is an option that requires an argument.  */
  799.         if (*nextchar != '\0')
  800.           {
  801.             optarg = nextchar;
  802.             /* If we end this ARGV-element by taking the rest as an arg,
  803.                we must advance to the next element now.  */
  804.             optind++;
  805.           }
  806.         else if (optind == argc)
  807.           {
  808.             if (opterr)
  809.               {
  810.                 /* 1003.2 specifies the format of this message.  */
  811.                 fprintf (stderr, _("%s: option requires an argument -- %c\n"),
  812.                          argv[0], c);
  813.               }
  814.             optopt = c;
  815.             if (optstring[0] == ':')
  816.               c = ':';
  817.             else
  818.               c = '?';
  819.             return c;
  820.           }
  821.         else
  822.           /* We already incremented `optind' once;
  823.              increment it again when taking next ARGV-elt as argument.  */
  824.           optarg = argv[optind++];
  825.  
  826.         /* optarg is now the argument, see if it's in the
  827.            table of longopts.  */
  828.  
  829.         for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
  830.           /* Do nothing.  */ ;
  831.  
  832.         /* Test all long options for either exact match
  833.            or abbreviated matches.  */
  834.         for (p = longopts, option_index = 0; p->name; p++, option_index++)
  835.           if (!strncmp (p->name, nextchar, nameend - nextchar))
  836.             {
  837.               if ((unsigned int) (nameend - nextchar) == strlen (p->name))
  838.                 {
  839.                   /* Exact match found.  */
  840.                   pfound = p;
  841.                   indfound = option_index;
  842.                   exact = 1;
  843.                   break;
  844.                 }
  845.               else if (pfound == NULL)
  846.                 {
  847.                   /* First nonexact match found.  */
  848.                   pfound = p;
  849.                   indfound = option_index;
  850.                 }
  851.               else
  852.                 /* Second or later nonexact match found.  */
  853.                 ambig = 1;
  854.             }
  855.         if (ambig && !exact)
  856.           {
  857.             if (opterr)
  858.               fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
  859.                        argv[0], argv[optind]);
  860.             nextchar += strlen (nextchar);
  861.             optind++;
  862.             return '?';
  863.           }
  864.         if (pfound != NULL)
  865.           {
  866.             option_index = indfound;
  867.             if (*nameend)
  868.               {
  869.                 /* Don't test has_arg with >, because some C compilers don't
  870.                    allow it to be used on enums.  */
  871.                 if (pfound->has_arg)
  872.                   optarg = nameend + 1;
  873.                 else
  874.                   {
  875.                     if (opterr)
  876.                       fprintf (stderr, _("\
  877. %s: option `-W %s' doesn't allow an argument\n"),
  878.                                argv[0], pfound->name);
  879.  
  880.                     nextchar += strlen (nextchar);
  881.                     return '?';
  882.                   }
  883.               }
  884.             else if (pfound->has_arg == 1)
  885.               {
  886.                 if (optind < argc)
  887.                   optarg = argv[optind++];
  888.                 else
  889.                   {
  890.                     if (opterr)
  891.                       fprintf (stderr,
  892.                                _("%s: option `%s' requires an argument\n"),
  893.                                argv[0], argv[optind - 1]);
  894.                     nextchar += strlen (nextchar);
  895.                     return optstring[0] == ':' ? ':' : '?';
  896.                   }
  897.               }
  898.             nextchar += strlen (nextchar);
  899.             if (longind != NULL)
  900.               *longind = option_index;
  901.             if (pfound->flag)
  902.               {
  903.                 *(pfound->flag) = pfound->val;
  904.                 return 0;
  905.               }
  906.             return pfound->val;
  907.           }
  908.           nextchar = NULL;
  909.           return 'W';   /* Let the application handle it.   */
  910.       }
  911.     if (temp[1] == ':')
  912.       {
  913.         if (temp[2] == ':')
  914.           {
  915.             /* This is an option that accepts an argument optionally.  */
  916.             if (*nextchar != '\0')
  917.               {
  918.                 optarg = nextchar;
  919.                 optind++;
  920.               }
  921.             else
  922.               optarg = NULL;
  923.             nextchar = NULL;
  924.           }
  925.         else
  926.           {
  927.             /* This is an option that requires an argument.  */
  928.             if (*nextchar != '\0')
  929.               {
  930.                 optarg = nextchar;
  931.                 /* If we end this ARGV-element by taking the rest as an arg,
  932.                    we must advance to the next element now.  */
  933.                 optind++;
  934.               }
  935.             else if (optind == argc)
  936.               {
  937.                 if (opterr)
  938.                   {
  939.                     /* 1003.2 specifies the format of this message.  */
  940.                     fprintf (stderr,
  941.                            _("%s: option requires an argument -- %c\n"),
  942.                            argv[0], c);
  943.                   }
  944.                 optopt = c;
  945.                 if (optstring[0] == ':')
  946.                   c = ':';
  947.                 else
  948.                   c = '?';
  949.               }
  950.             else
  951.               /* We already incremented `optind' once;
  952.                  increment it again when taking next ARGV-elt as argument.  */
  953.               optarg = argv[optind++];
  954.             nextchar = NULL;
  955.           }
  956.       }
  957.     return c;
  958.   }
  959. }
  960.  
  961. int
  962. getopt (int argc, char *const *argv, const char *optstring)
  963. {
  964.   return _getopt_internal (argc, argv, optstring,
  965.                            (const struct option *) 0,
  966.                            (int *) 0,
  967.                            0);
  968. }
  969.  
  970. #endif  /* Not ELIDE_CODE.  */
  971. #ifdef TEST
  972.  
  973. /* Compile with -DTEST to make an executable for use in testing
  974.    the above definition of `getopt'.  */
  975.  
  976. int
  977. main (int argc, char **argv)
  978. {
  979.   int c;
  980.   int digit_optind = 0;
  981.  
  982.   while (1)
  983.     {
  984.       int this_option_optind = optind ? optind : 1;
  985.  
  986.       c = getopt (argc, argv, "abc:d:0123456789");
  987.       if (c == -1)
  988.         break;
  989.  
  990.       switch (c)
  991.         {
  992.         case '0':
  993.         case '1':
  994.         case '2':
  995.         case '3':
  996.         case '4':
  997.         case '5':
  998.         case '6':
  999.         case '7':
  1000.         case '8':
  1001.         case '9':
  1002.           if (digit_optind != 0 && digit_optind != this_option_optind)
  1003.             printf ("digits occur in two different argv-elements.\n");
  1004.           digit_optind = this_option_optind;
  1005.           printf ("option %c\n", c);
  1006.           break;
  1007.  
  1008.         case 'a':
  1009.           printf ("option a\n");
  1010.           break;
  1011.  
  1012.         case 'b':
  1013.           printf ("option b\n");
  1014.           break;
  1015.  
  1016.         case 'c':
  1017.           printf ("option c with value `%s'\n", optarg);
  1018.           break;
  1019.  
  1020.         case '?':
  1021.           break;
  1022.  
  1023.         default:
  1024.           printf ("?? getopt returned character code 0%o ??\n", c);
  1025.         }
  1026.     }
  1027.  
  1028.   if (optind < argc)
  1029.     {
  1030.       printf ("non-option ARGV-elements: ");
  1031.       while (optind < argc)
  1032.         printf ("%s ", argv[optind++]);
  1033.       printf ("\n");
  1034.     }
  1035.  
  1036.   exit (0);
  1037. }
  1038.  
  1039. #endif /* TEST */
  1040.