Remove unused variable declarations
[ctxopt.git] / ctxopt.rst
blobd44c3150f1cb89fd6aeb489175d1c46df22a8ef6
1 ======
2 ctxopt
3 ======
5 -----------------------------------------
6 An advanced command line options manager.
7 -----------------------------------------
9 :Author: Pierre Gentile p.gen.progs@gmail.com
10 :Date: 2020
11 :Copyright: MPLv2.0
12 :Manual section: 3
14 DESCRIPTION
15 ===========
17 **ctxopt** provides an advanced way to parse and evaluate complex command
18 line parameters and arguments.
20 Only two files **ctxopt.h** and **ctxopt.c** are needed to use **ctxopt**
21 in your projects.
23 CONCEPTS
24 --------
26 The command line can be considered as a tree of contexts.
27 This offers the possibility of having a hierarchy of option groups.
29 Each option has a set of parameters which must start with a single dash
30 and may appear in the command line.
32 In order not to change habits, the double dash notation popularized by
33 the GNU **getopt_long** function for long options is also accepted and
34 automatically and silently converted to notation with a single dash.
36 These parameters are not limited to a dash followed by single letter.
37 In what follows, I will consider for simplicity that these are the options
38 which are visible in the command line and not one of their parameters.
40 Unless explicitly stated, the options are processed in the same order
41 as they appear in the command line, from left to right.
43 Any option may have the ability to modify the current context.
44 If such an option is seen in the command line, then the next option will
45 be looked for in this new context.
47 Initially the default context is the first created one in the program.
49 Exiting a context can be explicit, see below, or implicit if the current
50 option is not supported in this context.
51 The previous context in the hierarchy then becomes the current context
52 if it is not already the highest one.
54 An option which is unknown in the current context will be automatically
55 reevaluated in the previous one in the hierarchy.
56 If there is no such context, then a fatal error occurs.
58 A context can be explicitly delimited by a pair of symbols ``{`` and
59 ``}``.
60 The symbol ``{`` car appear just before or after the option responsible
61 of the context change.
63 The symbol ``}`` forces the end of a context.
65 The presence of ``{`` and ``}`` is purely optional and rarely necessary
66 but can help readability.
68 FUNCTIONS
69 ---------
71 The API consists in the following functions:
73 * **void ctxopt_init(char *** \
74   *prog_name*\
75   **, char *** \
76   *flags*\
77   **);**
79   This function initializes the internal structures uses by **ctxopt**.
80   It is mandatory and must me called first.
82   Its first argument (*prog_name*) is typically the content of ``argv[0]``
83   which nearly always contains the name of the program.
85   *prog_name* is used by the error system.
87   Its second argument (*flags*) will be read as a set of parameters
88   using the syntax ``flag=value``, each flag being separated from
89   its neighbor by spaces.
91   Flags may be missing in this argument, in this case the missing flags
92   will be given their default value which is given below.
93   An empty string is of course allowed but must be given anyway.
95   For now, only two flags are understood: **stop_if_non_option** and
96   **allow_abbreviations**.
98   Their value can be **yes** or **no**, **1** and **0** and also accepted.
100   stop_if_non_option
101     Instructs **ctxopt** to stop processing arguments as soon as it
102     encounters a non-option word in the command line, even if other
103     parameters remain to be processed. The default value of this flag
104     is **0** or **no**.
106   allow_abbreviations
107     Tells **ctxopt** to try to guess a parameter name even if only its
108     beginning is given. The default value of this flag is **1** or
109     **yes**.
111   Example of content of the *flags* parameter:
113   .. code-block:: c
115     "stop_if_non_option=1 allow_abbreviations=No"
119 * **void ctxopt_new_ctx(char *** \
120   *name*\
121   **, char *** \
122   *opts_specs*\
123   **);**
125   The next thing to do after having called **ctxopt_new_ctx** is to
126   define the contexts and its associated options.
128   Using this function, you can name the new context and its authorized
129   options and determine their main characteristics with a syntax easy
130   to understand.
131   If they already exist in another context, then they must have the same
132   signature (described below) as in their previous appearance.
134   *name* is the name of the new context and *opts_specs* must contain a
135   description of the options allowed in this context.
137   *opts_specs* is a string containing various components separated by
138   spaces according to the syntax below:
140   opt
141     A mandatory option named opt without parameter usable only one type in
142     the context
144   opt1 opt2
145       Two mandatory option named **opt1** and **opt2** without argument.
147   opt...
148       Same as above but can appear multiple time in the context.
150   [opt...]
151       Same as above but the option is optional
153   opt1 [opt2...]
154       One mandatory and one optional option named **opt1** and **opt2**
155       without argument. **opt2** can appear multiple times in the context.
157   opt #
158       One mandatory option named **opt*** taking one mandatory argument.
160   opt #tag
161       One mandatory option named **opt** taking one mandatory argument.
162       **tag** is ignored but can be used to improve the readability.
164   opt [#]
165       One mandatory option named **opt** taking one optional argument.
167   opt #...
168       One mandatory option named **opt** taking one or more mandatory
169       arguments.
171   opt>ctx... [#<value>]
172       The mandatory multiple option named **opt** will switch to the
173       context named **cxt** which will become the new current context.
175       It takes an optional argument with a tag named **<value>**.
177   [opt... [#...]]
178       One optional option named **opt** taking multiple optional
179       arguments.
181   The number of options/arguments allowed can be restricted by adding
182   an operator and an integer just after the dots like in the following
183   example:
185     opt...<3 #...=3
186         Here, the mandatory option **opt** is restricted to only appear
187         one or two times in the context.
188         The number of its mandatory arguments must be exactly three.
190         Valid operators are **<**, **=** and **>**.
192   The multiplicity or not of the options and argument, their mandatory or
193   optional characteristics constitutes their signatures.s
195   As said above, an option can appear in more than one context but must
196   have the same signature.
198   Example:
200   .. code-block:: c
202     ctxopt_new_ctx("context1",
203                    "[opt1>context2...] #arg1... [opt3]");
205     ctxopt_new_ctx("context2",
206                    "[opt2 [#arg2]] [opt3]");
208   In the previous example, three options **opt1**, **opt2** and **opt3**
209   are defined.
211     :opt1:
212       is mandatory and can appear more than one time and take multiple
213       mandatory arguments.
215     :opt2:
216       is optional and take an optional argument.
218     :opt3:
219       is optional and take no argument.
220       Note that **opt3** is legal in both contexts.
222     |
224     **opt2**, if present in the command line, will be evaluated in the
225     context **context2**.
226     Note that, in this example, the **context2** can only be entered if
227     **opt1** has previously been seen in the command line.
228     Hence, **opt2** is only legal if **opt1** is present first.
230     **opt3** does not have this limitation.
231     In fact, as **opt3** is optional in **context2** and if its action
232     function is not interested in the name of the current context,
233     then it could have been omitted from the second setting thanks to
234     the backtracking: an option which is illegal in a context is retried
235     in the previous context in the hierarchy.
239 * **void ctxopt_ctx_disp_usage(char *** \
240   *ctx_name*\
241   **, usage_behaviour** \
242   *action*\
243   **);**
245   This function builds and prints an usage help text for the
246   specific context *ctx_name*.
247   The symbols used in this text are the same as those used when defining
248   options in **ctxopt_new_ctx**.
250   The parameter *action* can take the following values:
252   continue_after
253     The program is not stopped when this function returns.
255   exit_after
256     The program is stopped with a non zero return code (typically 1)
257     when this function returns.
259   The usage text is followed by a legend explaining the symbols meanings.
260   This function is useful when associated with a **help** or **usage**
261   option.
265 * **void ctxopt_disp_usage(usage_behaviour** \
266   *action*\
267   **);**
269   This function is similar to the preceding one but displays the usage
270   help text for all the defined contexts.
271   It is useful when associated with a general **help** or **usage**
272   option.
274   The parameter *action* can take the following values:
276   continue_after
277     The program is not stopped when this function returns.
279   exit_after
280     The program is stopped with a non zero return code (typically 1)
281     when this function returns.
285 * **void ctxopt_add_global_settings(settings** \
286   *s*\
287   **,** \
288   *...*\
289   **);**
291   This function allows to set general **ctxopt** settings.
292   As for now, the only possible setting for *s* is **error_functions**.
294   This setting tells **ctxopt_add_global_settings** to use the rest of
295   its arguments in order to replace the built-in error functions with
296   custom ones.
298   When the value of the first parameter is **error_functions**,
299   then the second one must be one of the following constants:
301   :CTXOPTMISPAR:
302     A mandatory parameter is missing.
304   :CTXOPTUNKPAR:
305     A given parameter is unknown in the current context.
307   :CTXOPTDUPOPT:
308      An option has been seen more than once but has not been declared as
309      multiple in the context.
311   :CTXOPTINCOPT:
312     An option is incompatible with an option already given in the context.
314   :CTXOPTMISARG:
315     A mandatory argument is missing.
317   :CTXOPTCNTEOPT, CTXOPTCNTLOPT and CTXOPTCNTGOPT:
318     The number of occurrences is not equal, lower or greater than a
319     given value.
321   :CTXOPTCNTEARG, CTXOPTCNTLARG and CTXOPTCNTGARG:
322     The number of arguments of an option is not equal, lower or greater
323     than a given value.
325   and the third parameter is a function pointer with the following
326   prototype:
328   .. code-block:: c
330     void (*) (errors err, state_t * state);
332   *state* will point to the publicly available analysis state structure.
333   This structure contains a snapshot of variables related to the command
334   line analysis so far.
335   They and can be used to give the user clues about errors.
337   This structure available in **ctxopt.h** is:
339   .. code-block:: c
341     typedef struct
342     {
343       char * prog_name;        /* base name of the program name.         */
344       char * ctx_name;         /* current context name.                  */
345       char * ctx_par_name;     /* parameter which led to this context.   */
346       char * opt_name;         /* current option name.                   */
347       char * opt_params;       /* all parameters of the current option.  */
348       int    opts_count;       /* limit of the number of occurrences of  *
349                                |  the current option.                    */
350       int opt_args_count;      /* limit of the number of parameters of   *
351                                |  the current option.                    */
352       char * pre_opt_par_name; /* parameter just before the current one. */
353       char * cur_opt_par_name; /* current parameter.                     */
354     } state_t;
356   All these pointers can be equal to the **NULL** pointer.
358   Example:
360   .. code-block:: c
362     ctxopt_add_global_settings(error_functions, CTXOPTMISPAR, error);
366 * **void ctxopt_add_ctx_settings(settings** \
367   *s*\
368   **,** \
369   *...*\
370   **);**
372   This function manages some settings for a given context.
373   Its first parameter *s* determines the setting and the signification
374   of the remaining arguments.
376   Its possible values are:
378   incompatibilities:
379     This setting allows to declare a set of options incompatible with
380     each other.
382     In this case the second argument must be a context name and the
383     third argument must be a string containing option names separated
384     by a space.
386     Example of **incompatibilities** setting:
388     .. code-block:: c
390       void ctxopt_add_ctx_settings(incompatibilities,
391                                    "context1",
392                                    "opt1 opt2 opt3");
394     The three options named **opt1**, **opt2** and **opt3** will be
395     marked as mutually incompatibles in each instance of the context
396     **context1**.
398   requirements:
399     This setting allows options in a context to require the presence of
400     sets of other options of which at least one must be present.
401     Using this setting, the user can impose dependencies between options.
403     The option that imposes the requirement must be the first in the
404     list of options listed in the third arguments.
406     Example of **requirements** setting:
408     .. code-block:: c
410       void ctxopt_add_ctx_settings(requirements;
411                                    "context1",
412                                    "opt1 opt2 opt3");
414     At least one of the two options named **opt2** and **opt3** must
415     be present in the same context instance as **opt1** which is
416     **context1** in this case
418     There may be multiple requirements via multiple calls to
419     **ctxopt_add_ctx_settings** for the same first option (**opt1**
420     in the previous example) and the same context.
421     Each of them is considered in order.
423   actions:
424     This setting allows to associate a function to the context.
426     The second argument (called *f* below) will be called as soon as the
427     context is entered or exited during the evaluation phase.
429     Note that *f* will NOT be called if the context is empty
430     (does not contain any option).
432     The next parameters must be pointers to arbitrary data which may
433     be used by *f*.
435     In this setting, the last parameter must be **NULL**.
437     *f* must have the following prototype:
439     .. code-block:: c
441       int (*) (char     * name1,   /* Context name */
442                direction  status,  /* entering or exiting */
443                char     * name2,   /* previous or next context */
444                int        nb_data, /* Number of data */
445                void    ** data     /* Data */);
447     This function *f* will be called when entering **AND** exiting
448     the context.
449     Its arguments will then be set to:
451     *name1*
452       the name of the context.
454     *status*
455       will be **entering** when entering the context and **exiting**
456       when exiting the context.
458     *name2*
459       according to the content of *status*, the name of the context we
460       are coming from or the name of the context we are returning to.
462       *name2* can be **NULL** if we are entering in the main context or
463       are leaving it.
465     *nb_data*
466       The number of data pointers passed to the **ctxopt_add_ctx_settings**
467       function after the *s* parameter.
469     *data*
470       The data pointers passed to the **ctxopt_add_ctx_settings** function
471       after the *s* parameter and arranged in an array of *nb_data*
473     Example of **actions** setting:
475     .. code-block:: c
477       void ctxopt_add_ctx_settings(actions,
478                                    "context1",
479                                    action,
480                                    &data_1, &data_2, &data_3,
481                                    NULL);
483     This function call registers the **action** function to the context
484     named **context1**.
486     The action function will be called **after** entering to and
487     **before** exiting from each instance of the context
488     named **context1**.
490     The optional *data_X* pointers will be passed to **action** through
491     its data pointer to allow it to manipulate them if needed.
492     The count of these pointers (3 here) will also be passed to action
493     through its *nb_data* parameter.
495     The ending **NULL** is mandatory.
499 * **void ctxopt_add_opt_settings(settings** \
500   *s*\
501   **, char *** \
502   *opt*\
503   **,** \
504   *...*\
505   **);**
507   This function manages some settings for an option whose name is given in
508   *opt*.
510   The first parameter *s* determines the exact setting and the
511   signification of the remaining arguments.
512   Its possible values are:
514   parameters
515     This setting allows to associate command line parameters with *opt*.
516     The set of parameters must be given in the third argument as a string
517     containing words separated by blanks.
519     Each appearance of one of these parameters in the command line will
520     trigger the action associated with the named option.
522     Each of these words must start with one and exactly one dash.
524     Example of **parameters** setting:
526     .. code-block:: c
528       ctxopt_add_opt_settings(parameters,
529                               "opt1",
530                               "-p -parm -p1");
532     In this example, **opt1** is the name of a previously defined option and
533     **-p**, **-parm** and **-p1** will be three valid command line
534     parameters for the option **opt1**.
536   actions
537     This setting allows to associate a function to this options.
538     As said above, this function will be called each time the option will be
539     recognized when evaluating the command line.
541     The function pointer must be given as the third argument.
543     Following the function pointer, it is possible to add a bunch of
544     other parameters which must be pointers to some pre-allocated arbitrary
545     data.
547     These pointers will be passed to the function when called.
548     The last parameter must be **NULL** to end the sequence.
550     The function needs to be given as the third argument and must
551     match the following prototype:
553     .. code-block:: c
555       void (*) (char  * ctx_name,     /* Context name */
556                 char  * opt_name,     /* Option name  */
557                 char  * param,        /* Parameter name */
558                 int     nb_values,    /* Number of arguments */
559                 char ** values,       /* Arguments */
560                 int     nb_opt_data,  /* Number of option data passed */
561                 void ** opt_data,     /* Array of option data passed */
562                 int     nb_ctx_data,  /* Number of context data passed */
563                 void ** ctx_data      /* Array of context data passed */)
565     *ctx_name*
566       is the name of the current context.
568     *opt_name*
569       is the name of the option.
571     *param*
572       is the name of the parameter that triggered the option *opt_name*.
574     *nb_values*
575       is the number of arguments immediately following this option in
576       the command line.
578     *values*
579       is an array of stings containing the arguments following this
580       option in the command line.
582     *nb_opt_data*
583       is the number of data pointers which were given after the third
584       arguments of **ctxopt_add_opt_settings**.
586     *opt_data*
587       The data pointers passed after the third arguments of
588       **ctxopt_add_opt_settings** and reorganized as an array of
589       *nb_opt_data* elements.
591       The aim is to be able to consult/alter options specific data.
593     *nb_ctx_data*
594        Same as *nb_opt_data* but referencing to the number of data
595        pointers given to **ctxopt_add_ctx_settings** for the current
596        context after its third argument.
598     *ctx_data*
599       are the data pointers given to **ctxopt_add_ctx_settings** for the
600       current context after its third argument.
602       The aim is to be able to consult/alter contexts specific data.
604     Example of **actions** setting:
606     .. code-block:: c
608       void action(char * ctx_name,
609                   char * opt_name,
610                   char * param,
611                   int    nb_values,   char ** values,
612                   int    nb_opt_data, void ** opt_data,
613                   int    nb_ctx_data, void ** ctx_data)
614       {
615         ...
616       }
618       ...
620       void ctxopt_add_opt_settings(actions, "opt1", action,
621                                    &data_1, &data_2, &data_3,
622                                    NULL);
624     This example associates the function *action* to the option **opt1**.
626     Here, the *data_** pointers will be accessible to the function
627     *action* when called through its argument *opt_data* and their number
628     (3 here) through its argument *nb_opt_data* as mentioned above.
630     *action* will also have access to the current context data in the
631     same way through its arguments *ctx_data* and *nb_ctx_data*.
633     The *action* argument *param* will receive the value of the specific
634     parameter which triggered it - one of the parameters registered with
635     **ctxopt_add_opt_settings**.
637   constraints
638     This setting registers a function whose responsibility is to validate
639     that the arguments of the option respect some constraints.
641     To do that the third argument must be a function pointer and the fourth
642     argument must be some arbitrary parameter to this function needed
643     to validate the constraint.
645     The constraint function must match the following prototype:
647     .. code-block:: c
649        int (*) (int nb_args, char ** args, char * value, char * parameter);
651     Where:
653       *nb_args*
654         is the number which will be set to the number of arguments fol-
655         lowing the command line parameter.
657       *args*
658         is an array of nb_args strings containing theses arguments.
660       *value*
661         is an arbitrary string containing the constraints which must be
662         respected by args.
664       *parameter*
665         is the parameter of which *value* is an argument.
667     Three constraint functions are built-in and are described below.
668     They give examples on how to build them.
670     Example of constraint function using the built-it regular expression
671     constraint checker function:
673     .. code-block:: c
675       ctxopt_add_opt_settings(constraints,
676                               "opt1",
677                               ctxopt_re_constraint,
678                               "[^:]+:.+");
681     In this example all the arguments of the option **opt1** must match
682     the extended regular expression::
684       [^:]+:.+
686     See below for details about the function **ctxopt_re_constraint**.
688   before or after
689     These settings allow to tell ctxopt than some options must be
690     evaluated **before** or **after** a given option in a context.
691     This can be useful, for example, if an action triggered by the
692     evaluation of a option is required to be executed before the action
693     of another option.
695     Example of **before** setting:
697     .. code-block:: c
699       ctxopt_add_opt_settings(before,
700                               "opt1",
701                               "opt2 opt3");
703     In this example, **opt2** and **opt3** will be evaluated *before*
704     **opt1**.
705     The relative order of **opt2** and **opt3** evaluations will still
706     follow their order of appearance in the command line.
708     Example of **after** setting:
710     .. code-block:: c
712       ctxopt_add_opt_settings(after,
713                               "opt2",
714                               "opt3 opt4");
716     In this example, **opt3** and **opt4** will be evaluated *after*
717     **opt2**.
718     This example shows than we can combine multiple settings reusing
719     options previously mentioned.
721     Incompatible setting combinations are not checked and will be ignored
722     or lead to undefined behaviors.
726 * **int ctxopt_format_constraint(int** \
727   *nb_args*\
728   **, char **** \
729   *args*\
730   **, char *** \
731   *value*\
732   **, char *** \
733   *parameter*\
734   **);**
736   This pre-defined constraint function checks whether the arguments
737   in *args* respect a C printf format given in value, `%2d` by e.g.
738   It returns 1 if the checking is successful and 0 if not.
742 * **int ctxopt_re_constraint(int** \
743   *nb_args*\
744   **, char **** \
745   *args*\
746   **, char *** \
747   *value*\
748   **, char *** \
749   *parameter*\
750   **);**
752   Another pre-defined constraint function which checks if the arguments
753   of an option respects the extended regular expression given in *value*.
755   It returns 1 if the arguments respects the constraint and 0 if this
756   is not the case.
760 * **int ctxopt_range_constraint(int** \
761   *nb_args*\
762   **, char **** \
763   *args*\
764   **, char *** \
765   *value*\
766   **, char *** \
767   *parameter*\
768   **);**
770   Yet another pre-defined constraint function. This one checks if the
771   arguments of an option are in in a specified ranges.
773   *value* must contain a string made of a maximum of 2 long integers
774   separated by spaces.
776   The first or the second of these numbers can be replaced with the
777   character '`.`'. In this case only the minimum or maximum is checked
778   and the '`.`' equals to plus or minus infinity depending of this
779   place in the string.
781   It returns 1 if the arguments respects the constraint and 0 if this
782   is not the case.
786 * **void ctxopt_analyze(int** \
787   *nb_words*\
788   **, char **** \
789   *words*\
790   **, int *** \
791   *rem_count*\
792   **, char ***** \
793   *rem_args*\
794   **);**
796   This function processes the registered contexts instances tree, detects
797   errors and possibly reorganizes the options order according
798   to given priorities.
800   The first two arguments are similar to the *argc* and *argv* arguments
801   of the main function but without counting `argv[0]`.
802   Therefore, in many cases, *nb_words* will have the value of `argc-1`
803   and *words* will have the value of `argv+1`.
805   The last two will receive the number of remaining (non analyzed)
806   command line words and the array of these remaining words.
807   Remaining words can be words appearing after ``--`` per example.
809   All errors are fatal and terminates the program with a return code
810   greater then 0.
812   Example:
814   .. code-block:: c
816     int     res_argc;
817     char ** res_argv;
818     ...
819     ctxopt_analyze(argc-1, argv+1, &res_argc, &res_argv);
823 * **void ctxopt_evaluate(void);**
825   This function walks through the tree of context instances previously
826   built by **ctxopt_analyze** and launches the action attached to
827   each options, if any, one after the other.
829 * **ctxopt_free_memory(void)**
831   This function frees the memory used internally by **ctxopt**.
833 ENVIRONMENT
834 ===========
836 **ctxopt** is able to switch to debug mode if the variable CTXOPT_DEBUG
837 is set to any not-empty value.
839 If this is the case, informational messages about how **ctxopt**
840 analyses the command line are printed on the error output.
842 Each of them are prefixed with "CTXOPT_DEBUG: ".