Commit e33bb733bb11c437974c210c39e0958e8b35beeb

Martin Mitas 2020-02-23T02:47:31

md2html: Migrate to cmdline.[hc] from C-Reusables. This fixes many warnings from gcc 9.2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
diff --git a/md2html/cmdline.c b/md2html/cmdline.c
index af482ae..c3fddfa 100644
--- a/md2html/cmdline.c
+++ b/md2html/cmdline.c
@@ -1,296 +1,205 @@
-/* cmdline.c: a reentrant version of getopt(). Written 2006 by Brian
- * Raiter. This code is in the public domain.
+/*
+ * C Reusables
+ * <http://github.com/mity/c-reusables>
+ *
+ * Copyright (c) 2017-2020 Martin Mitas
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
  */
 
-#include	<stdio.h>
-#include	<stdlib.h>
-#include	<string.h>
-#include	<ctype.h>
-#include	"cmdline.h"
+#include "cmdline.h"
 
-#define	docallback(opt, val) \
-	    do { if ((r = callback(opt, val, data)) != 0) return r; } while (0)
+#include <stdio.h>
+#include <string.h>
 
-/* Parse the given cmdline arguments.
- */
-int readoptions(option const* list, int argc, char **argv,
-		int (*callback)(int, char const*, void*), void *data)
-{
-    char		argstring[] = "--";
-    option const       *opt;
-    char const	       *val;
-    char const	       *p;
-    int			stop = 0;
-    int			argi, len, r;
 
-    if (!list || !callback)
-	return -1;
+#ifdef _WIN32
+    #define snprintf    _snprintf
+#endif
 
-    for (argi = 1 ; argi < argc ; ++argi)
-    {
-	/* First, check for "--", which forces all remaining arguments
-	 * to be treated as non-options.
-	 */
-	if (!stop && argv[argi][0] == '-' && argv[argi][1] == '-'
-					  && argv[argi][2] == '\0') {
-	    stop = 1;
-	    continue;
-	}
 
-	/* Arguments that do not begin with '-' (or are only "-") are
-	 * not options.
-	 */
-	if (stop || argv[argi][0] != '-' || argv[argi][1] == '\0') {
-	    docallback(0, argv[argi]);
-	    continue;
-	}
+#define CMDLINE_AUXBUF_SIZE     32
 
-	if (argv[argi][1] == '-')
-	{
-	    /* Arguments that begin with a double-dash are long
-	     * options.
-	     */
-	    p = argv[argi] + 2;
-	    val = strchr(p, '=');
-	    if (val)
-		len = val++ - p;
-	    else
-		len = strlen(p);
 
-	    /* Is it on the list of valid options? If so, does it
-	     * expect a parameter?
-	     */
-	    for (opt = list ; opt->optval ; ++opt)
-		if (opt->name && !strncmp(p, opt->name, len)
-			      && !opt->name[len])
-		    break;
-	    if (!opt->optval) {
-		docallback('?', argv[argi]);
-	    } else if (!val && opt->arg == 1) {
-		docallback(':', argv[argi]);
-	    } else if (val && opt->arg == 0) {
-		docallback('=', argv[argi]);
-	    } else {
-		docallback(opt->optval, val);
-	    }
-	}
-	else
-	{
-	    /* Arguments that begin with a single dash contain one or
-	     * more short options. Each character in the argument is
-	     * examined in turn, unless a parameter consumes the rest
-	     * of the argument (or possibly even the following
-	     * argument).
-	     */
-	    for (p = argv[argi] + 1 ; *p ; ++p) {
-		for (opt = list ; opt->optval ; ++opt)
-		    if (opt->chname == *p)
-			break;
-		if (!opt->optval) {
-		    argstring[1] = *p;
-		    docallback('?', argstring);
-		    continue;
-		} else if (opt->arg == 0) {
-		    docallback(opt->optval, NULL);
-		    continue;
-		} else if (p[1]) {
-		    docallback(opt->optval, p + 1);
-		    break;
-		} else if (argi + 1 < argc && strcmp(argv[argi + 1], "--")) {
-		    ++argi;
-		    docallback(opt->optval, argv[argi]);
-		    break;
-		} else if (opt->arg == 2) {
-		    docallback(opt->optval, NULL);
-		    continue;
-		} else {
-		    argstring[1] = *p;
-		    docallback(':', argstring);
-		    break;
-		}
-	    }
-	}
-    }
-    return 0;
-}
 
-/* Verify that str points to an ASCII zero or one (optionally with
- * whitespace) and return the value present, or -1 if str's contents
- * are anything else.
- */
-static int readboolvalue(char const *str)
+static int
+cmdline_handle_short_opt_group(const CMDLINE_OPTION* options, const char* arggroup,
+        int (*callback)(int /*optval*/, const char* /*arg*/, void* /*userdata*/),
+        void* userdata)
 {
-    char	d;
+    const CMDLINE_OPTION* opt;
+    int i;
+    int ret = 0;
+
+    for(i = 0; arggroup[i] != '\0'; i++) {
+        for(opt = options; opt->id != 0; opt++) {
+            if(arggroup[i] == opt->shortname)
+                break;
+        }
+
+        if(opt->id != 0  &&  !(opt->flags & CMDLINE_OPTFLAG_REQUIREDARG)) {
+            ret = callback(opt->id, NULL, userdata);
+        } else {
+            /* Unknown option. */
+            char badoptname[3];
+            badoptname[0] = '-';
+            badoptname[1] = arggroup[i];
+            badoptname[2] = '\0';
+            ret = callback((opt->id != 0 ? CMDLINE_OPTID_MISSINGARG : CMDLINE_OPTID_UNKNOWN),
+                            badoptname, userdata);
+        }
+
+        if(ret != 0)
+            break;
+    }
 
-    while (isspace(*str))
-	++str;
-    if (!*str)
-	return -1;
-    d = *str++;
-    while (isspace(*str))
-	++str;
-    if (*str)
-	return -1;
-    if (d == '0')
-	return 0;
-    else if (d == '1')
-	return 1;
-    else
-	return -1;
+    return ret;
 }
 
-/* Parse a configuration file.
- */
-int readcfgfile(option const* list, FILE *fp,
-		int (*callback)(int, char const*, void*), void *data)
+int
+cmdline_read(const CMDLINE_OPTION* options, int argc, char** argv,
+        int (*callback)(int /*optval*/, const char* /*arg*/, void* /*userdata*/),
+        void* userdata)
 {
-    char		buf[1024];
-    option const       *opt;
-    char	       *name, *val, *p;
-    int			len, f, r;
-
-    while (fgets(buf, sizeof buf, fp) != NULL)
-    {
-	/* Strip off the trailing newline and any leading whitespace.
-	 * If the line begins with a hash sign, skip it entirely.
-	 */
-	len = strlen(buf);
-	if (len && buf[len - 1] == '\n')
-	    buf[--len] = '\0';
-	for (p = buf ; isspace(*p) ; ++p) ;
-	if (!*p || *p == '#')
-	    continue;
-
-	/* Find the end of the option's name and the beginning of the
-	 * parameter, if any.
-	 */
-	for (name = p ; *p && *p != '=' && !isspace(*p) ; ++p) ;
-	len = p - name;
-	for ( ; *p == '=' || isspace(*p) ; ++p) ;
-	val = p;
-
-	/* Is it on the list of valid options? Does it take a
-	 * full parameter, or just an optional boolean?
-	 */
-	for (opt = list ; opt->optval ; ++opt)
-	    if (opt->name && !strncmp(name, opt->name, len)
-			  && !opt->name[len])
-		    break;
-	if (!opt->optval) {
-	    docallback('?', name);
-	} else if (!*val && opt->arg == 1) {
-	    docallback(':', name);
-	} else if (*val && opt->arg == 0) {
-	    f = readboolvalue(val);
-	    if (f < 0)
-		docallback('=', name);
-	    else if (f == 1)
-		docallback(opt->optval, NULL);
-	} else {
-	    docallback(opt->optval, val);
-	}
+    const CMDLINE_OPTION* opt;
+    char auxbuf[CMDLINE_AUXBUF_SIZE+1];
+    int fast_optarg_decision = 1;
+    int after_doubledash = 0;
+    int i = 1;
+    int ret = 0;
+
+    auxbuf[CMDLINE_AUXBUF_SIZE] = '\0';
+
+    /* Check whether there is any CMDLINE_OPTFLAG_COMPILERLIKE option with
+     * a name not starting with '-'. That would imply we can to check for
+     * non-option arguments only after refusing all such options. */
+    for(opt = options; opt->id != 0; opt++) {
+        if((opt->flags & CMDLINE_OPTFLAG_COMPILERLIKE)  &&  opt->longname[0] != '-')
+            fast_optarg_decision = 0;
     }
-    return ferror(fp) ? -1 : 0;
-}
-
-/* Turn a string containing a cmdline into an argc-argv pair.
- */
-int makecmdline(char const *cmdline, int *argcp, char ***argvp)
-{
-    char      **argv;
-    int		argc;
-    char const *s;
-    int		n, quoted;
-
-    if (!cmdline)
-	return 0;
 
-    /* Calcuate argc by counting the number of "clumps" of non-spaces.
-     */
-    for (s = cmdline ; isspace(*s) ; ++s) ;
-    if (!*s) {
-	*argcp = 1;
-	if (argvp) {
-	    *argvp = malloc(2 * sizeof(char*));
-	    if (!*argvp)
-		return 0;
-	    (*argvp)[0] = NULL;
-	    (*argvp)[1] = NULL;
-	}
-	return 1;
+    while(i < argc) {
+        if(after_doubledash  ||  strcmp(argv[i], "-") == 0) {
+            /* Non-option argument.
+             * Standalone "-" usually means "read from stdin" or "write to
+             * stdout" so treat it always as a non-option. */
+            ret = callback(CMDLINE_OPTID_NONE, argv[i], userdata);
+        } else if(strcmp(argv[i], "--") == 0) {
+            /* End of options. All the remaining tokens are non-options
+             * even if they start with a dash. */
+            after_doubledash = 1;
+        } else if(fast_optarg_decision  &&  argv[i][0] != '-') {
+            /* Non-option argument. */
+            ret = callback(CMDLINE_OPTID_NONE, argv[i], userdata);
+        } else {
+            for(opt = options; opt->id != 0; opt++) {
+                if(opt->flags & CMDLINE_OPTFLAG_COMPILERLIKE) {
+                    size_t len = strlen(opt->longname);
+                    if(strncmp(argv[i], opt->longname, len) == 0) {
+                        /* Compiler-like option. */
+                        if(argv[i][len] != '\0')
+                            ret = callback(opt->id, argv[i] + len, userdata);
+                        else if(i+1 < argc)
+                            ret = callback(opt->id, argv[++i], userdata);
+                        else
+                            ret = callback(CMDLINE_OPTID_MISSINGARG, opt->longname, userdata);
+                        break;
+                    }
+                } else if(opt->longname != NULL  &&  strncmp(argv[i], "--", 2) == 0) {
+                    size_t len = strlen(opt->longname);
+                    if(strncmp(argv[i]+2, opt->longname, len) == 0) {
+                        /* Regular long option. */
+                        if(argv[i][2+len] == '\0') {
+                            /* with no argument provided. */
+                            if(!(opt->flags & CMDLINE_OPTFLAG_REQUIREDARG))
+                                ret = callback(opt->id, NULL, userdata);
+                            else
+                                ret = callback(CMDLINE_OPTID_MISSINGARG, argv[i], userdata);
+                            break;
+                        } else if(argv[i][2+len] == '=') {
+                            /* with an argument provided. */
+                            if(opt->flags & (CMDLINE_OPTFLAG_OPTIONALARG | CMDLINE_OPTFLAG_REQUIREDARG)) {
+                                ret = callback(opt->id, argv[i]+2+len+1, userdata);
+                            } else {
+                                snprintf(auxbuf, CMDLINE_AUXBUF_SIZE, "--%s", opt->longname);
+                                ret = callback(CMDLINE_OPTID_BOGUSARG, auxbuf, userdata);
+                            }
+                            break;
+                        } else {
+                            continue;
+                        }
+                    }
+                } else if(opt->shortname != '\0'  &&  argv[i][0] == '-') {
+                    if(argv[i][1] == opt->shortname) {
+                        /* Regular short option. */
+                        if(opt->flags & CMDLINE_OPTFLAG_REQUIREDARG) {
+                            if(argv[i][2] != '\0')
+                                ret = callback(opt->id, argv[i]+2, userdata);
+                            else if(i+1 < argc)
+                                ret = callback(opt->id, argv[++i], userdata);
+                            else
+                                ret = callback(CMDLINE_OPTID_MISSINGARG, argv[i], userdata);
+                            break;
+                        } else {
+                            ret = callback(opt->id, NULL, userdata);
+
+                            /* There might be more (argument-less) short options
+                             * grouped together. */
+                            if(ret == 0  &&  argv[i][2] != '\0')
+                                ret = cmdline_handle_short_opt_group(options, argv[i]+2, callback, userdata);
+                            break;
+                        }
+                    }
+                }
+            }
+
+            if(opt->id == 0) {  /* still not handled? */
+                if(argv[i][0] != '-') {
+                    /* Non-option argument. */
+                    ret = callback(CMDLINE_OPTID_NONE, argv[i], userdata);
+                } else {
+                    /* Unknown option. */
+                    char* badoptname = argv[i];
+
+                    if(strncmp(badoptname, "--", 2) == 0) {
+                        /* Strip any argument from the long option. */
+                        char* assignment = strchr(badoptname, '=');
+                        if(assignment != NULL) {
+                            size_t len = assignment - badoptname;
+                            if(len > CMDLINE_AUXBUF_SIZE)
+                                len = CMDLINE_AUXBUF_SIZE;
+                            strncpy(auxbuf, badoptname, len);
+                            auxbuf[len] = '\0';
+                            badoptname = auxbuf;
+                        }
+                    }
+
+                    ret = callback(CMDLINE_OPTID_UNKNOWN, badoptname, userdata);
+                }
+            }
+        }
+
+        if(ret != 0)
+            return ret;
+        i++;
     }
-    for (argc = 2, quoted = 0 ; *s ; ++s) {
-	if (quoted == '"') {
-	    if (*s == '"')
-		quoted = 0;
-	    else if (*s == '\\' && s[1])
-		++s;
-	} else if (quoted == '\'') {
-	    if (*s == '\'')
-		quoted = 0;
-	} else {
-	    if (isspace(*s)) {
-		for ( ; isspace(s[1]) ; ++s) ;
-		if (!s[1])
-		    break;
-		++argc;
-	    } else if (*s == '"' || *s == '\'') {
-		quoted = *s;
-	    }
-	}
-    }
-
-    *argcp = argc;
-    if (!argvp)
-	return 1;
-
-    /* Allocate space for all the arguments and their pointers.
-     */
-    argv = malloc((argc + 1) * sizeof(char*) + strlen(cmdline) + 1);
-    *argvp = argv;
-    if (!argv)
-	return 0;
-    argv[0] = NULL;
-    argv[1] = (char*)(argv + argc + 1);
 
-    /* Copy the string into the allocated memory immediately after the
-     * argv array. Where spaces immediately follows a nonspace,
-     * replace it with a \0. Where a nonspace immediately follows
-     * spaces, store a pointer to it. (Except, of course, when the
-     * space-nonspace transitions occur within quotes.)
-     */
-    for (s = cmdline ; isspace(*s) ; ++s) ;
-    for (argc = 1, n = 0, quoted = 0 ; *s ; ++s) {
-	if (quoted == '"') {
-	    if (*s == '"') {
-		quoted = 0;
-	    } else {
-		if (*s == '\\' && s[1])
-		    ++s;
-		argv[argc][n++] = *s;
-	    }
-	} else if (quoted == '\'') {
-	    if (*s == '\'')
-		quoted = 0;
-	    else
-		argv[argc][n++] = *s;
-	} else {
-	    if (isspace(*s)) {
-		argv[argc][n] = '\0';
-		for ( ; isspace(s[1]) ; ++s) ;
-		if (!s[1])
-		    break;
-		argv[argc + 1] = argv[argc] + n + 1;
-		++argc;
-		n = 0;
-	    } else {
-		if (*s == '"' || *s == '\'')
-		    quoted = *s;
-		else
-		    argv[argc][n++] = *s;
-	    }
-	}
-    }
-    argv[argc + 1] = NULL;
-    return 1;
+    return ret;
 }
+
diff --git a/md2html/cmdline.h b/md2html/cmdline.h
index 66c97a9..5bbde47 100644
--- a/md2html/cmdline.h
+++ b/md2html/cmdline.h
@@ -1,86 +1,153 @@
-/* cmdline.h: a reentrant version of getopt(). Written 2006 by Brian
- * Raiter. This code is in the public domain.
+/*
+ * C Reusables
+ * <http://github.com/mity/c-reusables>
+ *
+ * Copyright (c) 2017 Martin Mitas
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
  */
 
-#ifndef	_cmdline_h_
-#define	_cmdline_h_
+#ifndef CRE_CMDLINE_H
+#define CRE_CMDLINE_H
 
-/* The information specifying a single cmdline option.
- */
-typedef struct option {
-    char const *name;		/* the option's long name, or "" if none */
-    char	chname;		/* a single-char name, or zero if none */
-    int		optval;		/* a unique value representing this option */
-    int		arg;		/* 0 = no arg, 1 = arg req'd, 2 = optional */
-} option;
-
-/* Parse the given cmdline arguments. list is an array of option
- * structs, each entry specifying a valid option. The last struct in
- * the array must have name set to NULL. argc and argv give the
- * cmdline to parse. callback is the function to call for each option
- * and non-option found on the cmdline. data is a pointer that is
- * passed to each invocation of callback. The return value of callback
- * should be zero to continue processing the cmdline, or any other
- * value to abort. The return value of readoptions() is the value
- * returned from the last callback, or zero if no arguments were
- * found, or -1 if an error occurred.
- *
- * When readoptions() encounters a regular cmdline argument (i.e. a
- * non-option argument), callback() is invoked with opt equal to zero
- * and val pointing to the argument. When an option is found,
- * callback() is invoked with opt equal to the optval field in the
- * option struct corresponding to that option, and val points to the
- * option's paramter, or is NULL if the option does not take a
- * parameter. If readoptions() finds an option that does not appear in
- * the list of valid options, callback() is invoked with opt equal to
- * '?'. If readoptions() encounters an option that is missing its
- * required parameter, callback() is invoked with opt equal to ':'. If
- * readoptions() finds a parameter on a long option that does not
- * admit a parameter, callback() is invoked with opt equal to '='. In
- * each of these cases, val will point to the erroneous option
- * argument.
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* The option may have an argument. (Affects only long option.) */
+#define CMDLINE_OPTFLAG_OPTIONALARG     0x0001
+
+/* The option must have an argument.
+ * Such short option cannot be grouped within single '-abc'. */
+#define CMDLINE_OPTFLAG_REQUIREDARG     0x0002
+
+/* Enable special compiler-like mode for the long option.
+ *
+ * Note ::shortname is not supported with this flag. CMDLINE_OPTION::shortname
+ * is silently ignored if the flag is used.
+ *
+ * With this flag, CMDLINE_OPTION::longname is treated differently as follows:
+ *
+ * 1. The option matches if the CMDLINE_OPTION::longname is the exact prefix
+ *   of the argv[i] from commandline.
+ *
+ * 2. Double dash ("--") is not automatically prepended to
+ *    CMDLINE_OPTION::longname. (If you desire any leading dash, include it
+ *    explicitly in CMDLINE_OPTION initialization.)
+ *
+ * 3. An argument (optionally after a whitespace) is required (the flag
+ *    CMDLINE_OPTFLAG_COMPILERLIKE implicitly implies also the flag
+ *    CMDLINE_OPTFLAG_REQUIREDARG).
+ *
+ *    But there is no delimiter expected (no "=" between the option and its
+ *    argument). Whitespace is optional between the option and its argument.
+ *
+ *    Intended use is for options similar to what many compilers accept.
+ *    For example:
+ *      -DDEBUG=0               (-D is the option, DEBUG=0 is the argument).
+ *      -Isrc/include           (-I is the option, src/include is the argument).
+ *      -isystem /usr/include   (-isystem is the option, /usr/include is the argument).
+ *      -lmath                  (-l is the option, math is the argument).
  */
-extern int readoptions(option const* list, int argc, char **argv,
-		       int (*callback)(int opt, char const *val, void *data),
-		       void *data);
-
-/* Parse the given file. list is an array of option structs, in the
- * same form as taken by readoptions(). fp is a pointer to an open
- * text file. callback is the function to call for each line found in
- * the configuration file. data is a pointer that is passed to each
- * invocation of callback. The return value of readcfgfile() is the
- * value returned from the last callback, or zero if no arguments were
- * found, or -1 if an error occurred while reading the file.
- *
- * The function will ignore lines that contain only whitespace, or
- * lines that begin with a hash sign. All other lines should be of the
- * form "OPTION=VALUE", where OPTION is one of the long options in
- * list. Whitespace around the equal sign is permitted. An option that
- * takes no arguments can either have a VALUE of 0 or 1, or omit the
- * "=VALUE" entirely. (A VALUE of 0 will behave the same as if the
- * line was not present.)
+#define CMDLINE_OPTFLAG_COMPILERLIKE    0x0004
+
+
+/* Special (reserved) option IDs. Do not use these for any CMDLINE_OPTION::id.
+ * See documentation of cmdline_read() to get info about their meaning.
  */
-extern int readcfgfile(option const* list, FILE *fp,
-		       int (*callback)(int opt, char const *val, void *data),
-		       void *data);
-
-
-/* Create an argc-argv pair from a string containing a command line.
- * cmdline is the string to be parsed. argcp points to the variable to
- * receive the argc value, and argvp points to the variable to receive
- * the argv value. argvp can be NULL if the caller just wants to get
- * argc. Zero is returned on failure. This function allocates memory
- * on behalf of the caller. The memory is allocated as a single block,
- * so it is sufficient to simply free() the pointer returned through
- * argvp. Note that argv[0] will always be initialized to NULL; the
- * first argument will be stored in argv[1]. The string is parsed by
- * separating arguments on whitespace boundaries. Space within
- * substrings enclosed in single-quotes is ignored. A substring
- * enclosed in double-quotes is treated the same, except that the
- * backslash is recognized as an escape character within such a
- * substring. Enclosing quotes and escaping backslashes are not copied
- * into the argv values.
+#define CMDLINE_OPTID_NONE              0
+#define CMDLINE_OPTID_UNKNOWN           (-0x7fffffff + 0)
+#define CMDLINE_OPTID_MISSINGARG        (-0x7fffffff + 1)
+#define CMDLINE_OPTID_BOGUSARG          (-0x7fffffff + 2)
+
+
+typedef struct CMDLINE_OPTION {
+    char shortname;         /* Short (single char) option or 0. */
+    const char* longname;   /* Long name (after "--") or NULL. */
+    int id;                 /* Non-zero ID to identify the option in the callback; or zero to denote end of options list. */
+    unsigned flags;         /* Bitmask of CMDLINE_OPTFLAG_xxxx flags. */
+} CMDLINE_OPTION;
+
+
+/* Parses all options and their arguments as specified by argc, argv accordingly
+ * with the given options (except argv[0] which is ignored).
+ *
+ * The caller must specify the list of supported options in the 1st parameter
+ * of the function. The array must end with a record whose CMDLINE_OPTION::id
+ * is zero to zero.
+ *
+ * The provided callback function is called for each option on the command
+ * line so that:
+ *
+ *   -- the "id" refers to the id of the option as specified  in options[].
+ *
+ *   -- the "arg" specifies an argument of the option or NULL if none is
+ *      provided.
+ *
+ *   -- the "userdata" just allows to pass in some caller's context into
+ *      the callback.
+ *
+ * Special cases (recognized via special "id" value) are reported to the
+ * callback as follows:
+ *
+ *   -- If id is CMDLINE_OPTID_NONE, the callback informs about a non-option
+ *      also known as a positional argument.
+ *
+ *      All argv[] tokens which are not interpreted as an options or an argument
+ *      of any option fall into this category.
+ *
+ *      Usually, programs interpret these as paths to file to process.
+ *
+ *   -- If id is CMDLINE_OPTID_UNKNOWN, the corresponding argv[] looks like an
+ *      option but it is not found in the options[] passed to cmdline_read().
+ *
+ *      The callback's parameter arg specifies the guilty command line token.
+ *      Usually, program writes down an error message and exits.
+ *
+ *   -- If id is CMDLINE_OPTID_MISSINGARG, the given option is valid but its
+ *      flag in options[] requires an argument; yet there is none on the
+ *      command line.
+ *
+ *      The callback's parameter arg specifies the guilty option name.
+ *      Usually, program writes down an error message and exits.
+ *
+ *   -- If id is CMDLINE_OPTID_BOGUSARG, the given option is valid but its
+ *      flag in options[] does not expect an argument; yet the command line
+ *      does provide one.
+ *
+ *      The callback's parameter arg specifies the guilty option name.
+ *      Usually, program writes down an error message and exits.
+ *
+ * On success, zero is returned.
+ *
+ * If the callback returns a non-zero, cmdline_read() aborts immediately and
+ * cmdline_read() propagates the same return value to the caller.
  */
-extern int makecmdline(char const *cmdline, int *argcp, char ***argvp);
 
+int cmdline_read(const CMDLINE_OPTION* options, int argc, char** argv,
+        int (*callback)(int /*id*/, const char* /*arg*/, void* /*userdata*/),
+        void* userdata);
+
+
+#ifdef __cplusplus
+}  /* extern "C" { */
 #endif
+
+#endif  /* CRE_CMDLINE_H */
diff --git a/md2html/md2html.c b/md2html/md2html.c
index a3015e6..8f887fb 100644
--- a/md2html/md2html.c
+++ b/md2html/md2html.c
@@ -2,7 +2,7 @@
  * MD4C: Markdown parser for C
  * (http://github.com/mity/md4c)
  *
- * Copyright (c) 2016-2017 Martin Mitas
+ * Copyright (c) 2016-2020 Martin Mitas
  *
  * Permission is hereby granted, free of charge, to any person obtaining a
  * copy of this software and associated documentation files (the "Software"),
@@ -183,40 +183,36 @@ out:
 }
 
 
-#define OPTION_ARG_NONE         0
-#define OPTION_ARG_REQUIRED     1
-#define OPTION_ARG_OPTIONAL     2
-
-static const option cmdline_options[] = {
-    { "output",                     'o', 'o', OPTION_ARG_REQUIRED },
-    { "full-html",                  'f', 'f', OPTION_ARG_NONE },
-    { "stat",                       's', 's', OPTION_ARG_NONE },
-    { "help",                       'h', 'h', OPTION_ARG_NONE },
-    { "version",                    'v', 'v', OPTION_ARG_NONE },
-
-    { "commonmark",                  0,  'c', OPTION_ARG_NONE },
-    { "github",                      0,  'g', OPTION_ARG_NONE },
-
-    { "fcollapse-whitespace",        0,  'W', OPTION_ARG_NONE },
-    { "flatex-math",                 0,  'L', OPTION_ARG_NONE },
-    { "fpermissive-atx-headers",     0,  'A', OPTION_ARG_NONE },
-    { "fpermissive-autolinks",       0,  'V', OPTION_ARG_NONE },
-    { "fpermissive-email-autolinks", 0,  '@', OPTION_ARG_NONE },
-    { "fpermissive-url-autolinks",   0,  'U', OPTION_ARG_NONE },
-    { "fpermissive-www-autolinks",   0,  '.', OPTION_ARG_NONE },
-    { "fstrikethrough",              0,  'S', OPTION_ARG_NONE },
-    { "ftables",                     0,  'T', OPTION_ARG_NONE },
-    { "ftasklists",                  0,  'X', OPTION_ARG_NONE },
-    { "funderline",                  0,  '_', OPTION_ARG_NONE },
-    { "fverbatim-entities",          0,  'E', OPTION_ARG_NONE },
-    { "fwiki-links",                 0,  'K', OPTION_ARG_NONE },
-
-    { "fno-html-blocks",             0,  'F', OPTION_ARG_NONE },
-    { "fno-html-spans",              0,  'G', OPTION_ARG_NONE },
-    { "fno-html",                    0,  'H', OPTION_ARG_NONE },
-    { "fno-indented-code",           0,  'I', OPTION_ARG_NONE },
-
-    { 0 }
+static const CMDLINE_OPTION cmdline_options[] = {
+    { 'o', "output",                        'o', CMDLINE_OPTFLAG_REQUIREDARG },
+    { 'f', "full-html",                     'f', 0 },
+    { 's', "stat",                          's', 0 },
+    { 'h', "help",                          'h', 0 },
+    { 'v', "version",                       'v', 0 },
+
+    {  0,  "commonmark",                    'c', 0 },
+    {  0,  "github",                        'g', 0 },
+
+    {  0,  "fcollapse-whitespace",          'W', 0 },
+    {  0,  "flatex-math",                   'L', 0 },
+    {  0,  "fpermissive-atx-headers",       'A', 0 },
+    {  0,  "fpermissive-autolinks",         'V', 0 },
+    {  0,  "fpermissive-email-autolinks",   '@', 0 },
+    {  0,  "fpermissive-url-autolinks",     'U', 0 },
+    {  0,  "fpermissive-www-autolinks",     '.', 0 },
+    {  0,  "fstrikethrough",                'S', 0 },
+    {  0,  "ftables",                       'T', 0 },
+    {  0,  "ftasklists",                    'X', 0 },
+    {  0,  "funderline",                    '_', 0 },
+    {  0,  "fverbatim-entities",            'E', 0 },
+    {  0,  "fwiki-links",                   'K', 0 },
+
+    {  0,  "fno-html-blocks",               'F', 0 },
+    {  0,  "fno-html-spans",                'G', 0 },
+    {  0,  "fno-html",                      'H', 0 },
+    {  0,  "fno-indented-code",             'I', 0 },
+
+    {  0,  NULL,                             0,  0 }
 };
 
 static void
@@ -341,7 +337,7 @@ main(int argc, char** argv)
     FILE* out = stdout;
     int ret = 0;
 
-    if(readoptions(cmdline_options, argc, argv, cmdline_callback, NULL) < 0) {
+    if(cmdline_read(cmdline_options, argc, argv, cmdline_callback, NULL) != 0) {
         usage();
         exit(1);
     }