Debian Codegraph @

texk/chktex/chktex-src/ChkTeX.c

raw
1 /*
2 * ChkTeX, finds typographic errors in (La)TeX files.
3 * Copyright (C) 1995-96 Jens T. Berger Thielemann
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 *
19 * Contact the author at:
20 * Jens Berger
21 * Spektrumvn. 4
22 * N-0666 Oslo
23 * Norway
24 * E-mail: <[email protected]>
25 *
26 *
27 */
28
29
30 #include "ChkTeX.h"
31 #ifdef KPATHSEA
32 #include <kpathsea/getopt.h>
33 #else
34 #include <getopt.h>
35 #endif
36 #include "OpSys.h"
37 #include "Utility.h"
38 #include "FindErrs.h"
39 #include "Resource.h"
40 #include <string.h>
41
42 #undef MSG
43 #define MSG(num, type, inuse, ctxt, text) {(enum ErrNum)num, type, inuse, ctxt, text},
44
45 struct ErrMsg PrgMsgs[pmMaxFault + 1] = {
46 PRGMSGS {(enum ErrNum)pmMaxFault, etErr, TRUE, 0, INTERNFAULT}
47 };
48
49 struct Stack CharStack = {0L};
50 struct Stack InputStack = {0L};
51 struct Stack EnvStack = {0L};
52 struct Stack ConTeXtStack = {0L};
53 struct Stack FileSuppStack = {0L};
54 struct Stack UserFileSuppStack = {0L};
55 struct Stack MathModeStack = {0L};
56
57 /************************************************************************/
58
59 const char BrOrder[NUMBRACKETS + 1] = "()[]{}";
60
61 unsigned long Brackets[NUMBRACKETS];
62
63 /************************************************************************/
64
65
66 /*
67 * Have to do things this way, to ease some checking throughout the
68 * program.
69 */
70
71
72 NEWBUF(TmpBuffer, BUFFER_SIZE);
73 NEWBUF(ReadBuffer, BUFFER_SIZE);
74
75 static const char *Banner =
76 "ChkTeX v" PACKAGE_VERSION " - Copyright 1995-96 Jens T. Berger Thielemann.\n"
77 #ifdef __OS2__
78 "OS/2 port generated with emx compiler, by Wolfgang Fritsch, <[email protected]>\n"
79 #elif defined(__MSDOS__)
80 "MS-DOS port by Bj\\o rn Ove Thue, <[email protected]>\n"
81 #endif
82 #if HAVE_PCRE
83 "Compiled with PCRE regex support."
84 #else
85 #if HAVE_POSIX_ERE
86 "Compiled with POSIX extended regex support."
87 #else
88 "Compiled with no regex support."
89 #endif
90 #endif
91 "\n";
92
93 static const char *BigBanner =
94 "ChkTeX comes with ABSOLUTELY NO WARRANTY; details on this and\n"
95 "distribution conditions in the GNU General Public License file.\n"
96 "Type \"ChkTeX -h\" for help, \"ChkTeX -i\" for distribution info.\n"
97 "Author: Jens Berger.\n"
98 "Bug reports: https://savannah.nongnu.org/bugs/?group=chktex\n"
99 " or [email protected]\n"
100 "Press " STDIN_BREAK " to terminate stdin input.\n";
101
102 static const char *Distrib =
103 "\n"
104 "This program is free software; you can redistribute it and/or modify\n"
105 "it under the terms of the GNU General Public License as published by\n"
106 "the Free Software Foundation; either version 2 of the License, or\n"
107 "(at your option) any later version.\n"
108 "\n"
109 "This program is distributed in the hope that it will be useful,\n"
110 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
111 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
112 "GNU General Public License for more details.\n"
113 "\n"
114 "You should have received a copy of the GNU General Public License\n"
115 "along with this program; if not, write to the Free Software\n"
116 "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n";
117
118 static const char *OnText = "On";
119
120 static const char *OffText = "Off";
121
122 static const char *HowHelp =
123 "-h or --help gives usage information. See also ChkTeX.{ps,dvi}.\n";
124
125 static const char *HelpText =
126 "\n"
127 "\n"
128 " Usage of ChkTeX v" PACKAGE_VERSION "\n"
129 " ~~~~~~~~~~~~~~~~~~~~~~\n"
130 "\n"
131 " Template\n"
132 " ~~~~~~~~\n"
133 "chktex [-hiqrW] [-v[0-...]] [-l <rcfile>] [-[wemn] <[1-42]|all>]\n"
134 " [-d[0-...]] [-p <name>] [-o <outfile>] [-[btxgI][0|1]]\n"
135 " file1 file2 ...\n"
136 "\n"
137 "----------------------------------------------------------------------\n"
138 " Description of options:\n"
139 " ~~~~~~~~~~~~~~~~~~~~~~~\n"
140 "Misc. options\n"
141 "~~~~~~~~~~~~~\n"
142 " -h --help : This text.\n"
143 " -i --license : Show distribution information\n"
144 " -l --localrc : Read local .chktexrc formatted file.\n"
145 " -d --debug : Debug information. A bit field with 5 bits.\n"
146 " Each bit shows a different type of information.\n"
147 " -r --reset : Reset settings to default.\n"
148 " -S --set : Read it's argument as if from chktexrc.\n"
149 " e.g., -S TabSize=8 will override the TabSize.\n"
150 "\n"
151 "Muting warning messages:\n"
152 "~~~~~~~~~~~~~~~~~~~~~~~~\n"
153 " -w --warnon : Makes msg # given a warning and turns it on.\n"
154 " -e --erroron : Makes msg # given an error and turns it on.\n"
155 " -m --msgon : Makes msg # given a message and turns it on.\n"
156 " -n --nowarn : Mutes msg # given.\n"
157 " -L --nolinesupp: Disables per-line and per-file suppressions.\n"
158 "\n"
159 "Output control flags:\n"
160 "~~~~~~~~~~~~~~~~~~~~~\n"
161 " -v --verbosity : How errors are displayed.\n"
162 " Default 1, 0=Less, 2=Fancy, 3=lacheck.\n"
163 " -V --pipeverb : How errors are displayed when stdout != tty.\n"
164 " Defaults to the same as -v.\n"
165 " -s --splitchar : String used to split fields when doing -v0\n"
166 " -o --output : Redirect error report to a file.\n"
167 " -q --quiet : Shuts up about version information.\n"
168 " -p --pseudoname: Input file-name when reporting.\n"
169 " -f --format : Format to use for output\n"
170 "\n"
171 "Boolean switches (1 -> enables / 0 -> disables):\n"
172 "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
173 " -b --backup : Backup output file.\n"
174 " -x --wipeverb : Ignore contents of `\\verb' commands.\n"
175 " -g --globalrc : Read global .chktexrc file.\n"
176 " -I --inputfiles: Execute \\input statements.\n"
177 " -H --headererr : Show errors found before \\begin{document}\n"
178 "\n"
179 "Miscellaneous switches:\n"
180 "~~~~~~~~~~~~~~~~~~~~~~~\n"
181 " -W --version : Version information\n"
182 "\n"
183 "----------------------------------------------------------------------\n"
184 "If no LaTeX files are specified on the command line, we will read from\n"
185 "stdin. For explanation of warning/error messages, please consult the\n"
186 "main documentation ChkTeX.dvi, ChkTeX.ps or ChkTeX.pdf:\n"
187 " http://www.nongnu.org/chktex/ChkTeX.pdf\n"
188 "\n"
189 "Any of the above arguments can be made permanent by setting them in the\n"
190 "chktexrc file "
191 #if defined(__unix__)
192 "(~/.chktexrc).\n"
193 #else
194 "(see documentation for location).\n"
195 #endif
196 ;
197
198
199
200
201 /*
202 * Options we will set.
203 *
204 */
205
206 enum Quote Quote;
207
208 enum CmdSpace CmdSpace;
209
210 char VerbNormal[] = "%k %n in %f line %l: %m\n" "%r%s%t\n" "%u\n";
211
212 #define DEF(type, name, value) type name = value
213 OPTION_DEFAULTS;
214 STATE_VARS;
215 #undef DEF
216 FILE *OutputFile = NULL;
217
218 char *PrgName;
219
220 int StdInTTY, StdOutTTY;
221
222 /*
223 * End of config params.
224 */
225
226 static int ParseArgs(int argc, char **argv);
227 static void ShowIntStatus(void);
228 static int OpenOut(void);
229 static int ShiftArg(char **Argument);
230
231
232 /*
233 * Duplicates all arguments, and appends an asterix to each of them.
234 */
235
236 static void AddStars(struct WordList *wl)
237 {
238 unsigned long Count, CmdLen;
239 char *Data;
240
241 FORWL(Count, *wl)
242 {
243 Data = wl->Stack.Data[Count];
244 CmdLen = strlen(Data);
245 if (Data[CmdLen - 1] != '*')
246 {
247 strcpy(TmpBuffer, Data);
248 strcat(TmpBuffer, "*");
249 InsertWord(TmpBuffer, wl);
250 }
251 }
252 }
253
254 /*
255 * Sets up all the lists.
256 *
257 */
258
259 static void SetupLists(void)
260 {
261 unsigned long i;
262
263 AddStars(&VerbEnvir);
264 AddStars(&MathEnvir);
265
266 MakeLower(&UserWarnCase);
267
268 ListRep(&WipeArg, ':', 0);
269 ListRep(&NoCharNext, ':', 0);
270
271 #define ThisItem ((char *) AbbrevCase.Stack.Data[i])
272
273 FORWL(i, AbbrevCase)
274 {
275 if (isalpha((unsigned char)ThisItem[0]))
276 {
277 ThisItem[0] = toupper((unsigned char)ThisItem[0]);
278 InsertWord(ThisItem, &Abbrev);
279 ThisItem[0] = tolower((unsigned char)ThisItem[0]);
280 }
281 InsertWord(ThisItem, &Abbrev);
282 }
283 }
284
285 #define NOCOMMON(a,b) NoCommon(&a,#a,&b,#b)
286
287 /*
288 * Checks that two lists don't have any common element.
289 */
290
291 static void
292 NoCommon(struct WordList *a, const char *aName,
293 struct WordList *b, const char *bName)
294 {
295 unsigned long i;
296
297 FORWL(i, *a)
298 {
299 if (HasWord((char *) a->Stack.Data[i], b))
300 PrintPrgErr(pmNoCommon, a->Stack.Data[i], aName, bName);
301 }
302 }
303
304 /*
305 * Expands the tabs in a string to regular intervals sized
306 * TSize.
307 */
308
309 static void ExpandTabs(char *From, char *To, long TSize, long MaxDiff)
310 {
311 char *Next;
312 char *Orig;
313 unsigned long Diff;
314 static short HasExpandedTooLong = 0;
315
316 Next = From;
317 Orig = To;
318
319 while ((Next = strchr(From, '\t')))
320 {
321 if ((Diff = Next - From))
322 {
323 strncpy(To, From, Diff);
324 To += Diff;
325 Diff = TSize - ((To - Orig) % TSize);
326 }
327 else
328 Diff = TSize;
329
330 /* Make sure we don't expand this buffer out of the memory we
331 * have allocated for it. */
332 if ( Diff > MaxDiff+1 )
333 {
334 Diff = MaxDiff+1;
335 if ( !HasExpandedTooLong )
336 {
337 PrintPrgErr(pmTabExpands, BUFFER_SIZE);
338 }
339 HasExpandedTooLong = 1;
340 }
341 MaxDiff -= (Diff-1);
342
343 memset(To, ' ', Diff);
344 To += Diff;
345
346 From = ++Next;
347 }
348 strcpy(To, From);
349 }
350
351 void ReadRcFiles(void)
352 {
353 unsigned long i;
354 while (SetupVars())
355 {
356 InsertWord(ConfigFile, &ConfigFiles);
357 }
358 FORWL(i, ConfigFiles)
359 {
360 ReadRC(ConfigFiles.Stack.Data[i]);
361 }
362 }
363
364
365 int main(int argc, char **argv)
366 {
367 int retval = EXIT_FAILURE, ret, CurArg;
368 unsigned long Count;
369 int StdInUse = FALSE;
370 long Tab = 8;
371
372 #ifdef __LOCALIZED
373
374 InitStrings();
375 #endif
376
377 OutputFile = stdout;
378 #ifdef KPATHSEA
379 kpse_set_program_name(argv[0], "chktex");
380 PrgName = kpse_program_name;
381 #ifdef WIN32
382 setmode(fileno(stdout), _O_BINARY);
383 #endif
384 #else
385 PrgName = argv[0];
386 #endif
387
388 #undef KEY
389 #undef LCASE
390 #undef LIST
391 #undef LNEMPTY
392 #define KEY(a, def)
393 #define LCASE(a)
394 #define LIST(a)
395 #define LNEMPTY(a) InsertWord("", &a);
396
397 RESOURCE_INFO
398
399 ReadRcFiles();
400
401 if (CmdLine.Stack.Used)
402 {
403 ParseArgs(CmdLine.Stack.Used, (char **) CmdLine.Stack.Data);
404 CmdLine.Stack.Used = 1L;
405 }
406
407 if ((CurArg = ParseArgs((unsigned long) argc, argv)))
408 {
409 retval = EXIT_SUCCESS;
410 if (CmdLine.Stack.Used)
411 {
412 ParseArgs(CmdLine.Stack.Used, (char **) CmdLine.Stack.Data);
413 CmdLine.Stack.Used = 1L;
414 }
415
416 if (!Quiet || LicenseOnly)
417 fprintf(stderr, "%s", Banner);
418
419 if (CurArg == argc)
420 UsingStdIn = TRUE;
421
422 #if defined(HAVE_FILENO) && defined(HAVE_ISATTY)
423
424 StdInTTY = isatty(fileno(stdin));
425 StdOutTTY = isatty(fileno(stdout));
426 #else
427
428 StdInTTY = StdOutTTY = TRUE;
429 #endif
430
431 SetupTerm();
432
433 if ((UsingStdIn && StdInTTY && !Quiet) || LicenseOnly)
434 {
435 fprintf(stderr, "%s", BigBanner);
436 }
437
438 if (!StdOutTTY && PipeOutputFormat)
439 OutputFormat = PipeOutputFormat;
440
441 if (LicenseOnly)
442 {
443 fprintf(stderr, "%s", Distrib);
444 }
445 else
446 {
447 SetupLists();
448 if (QuoteStyle)
449 {
450 if (!strcasecmp(QuoteStyle, "LOGICAL"))
451 Quote = quLogic;
452 else if (!strcasecmp(QuoteStyle, "TRADITIONAL"))
453 Quote = quTrad;
454 else
455 {
456 PrintPrgErr(pmQuoteStyle, QuoteStyle);
457 Quote = quTrad;
458 }
459 }
460 if (CmdSpaceStyle)
461 {
462 if (!strcasecmp(CmdSpaceStyle, "IGNORE"))
463 CmdSpace = csIgnore;
464 else if (!strcasecmp(CmdSpaceStyle, "INTERWORD"))
465 CmdSpace = csInterWord;
466 else if (!strcasecmp(CmdSpaceStyle, "INTERSENTENCE"))
467 CmdSpace = csInterSentence;
468 else if (!strcasecmp(CmdSpaceStyle, "BOTH"))
469 CmdSpace = csBoth;
470 else
471 {
472 PrintPrgErr(pmCmdSpaceStyle, CmdSpaceStyle);
473 CmdSpace = csIgnore;
474 }
475 }
476
477 if (DebugLevel)
478 ShowIntStatus();
479
480 NOCOMMON(Italic, NonItalic);
481 NOCOMMON(Italic, ItalCmd);
482 NOCOMMON(LowDots, CenterDots);
483
484 if (TabSize && isdigit((unsigned char)*TabSize))
485 Tab = strtol(TabSize, NULL, 10);
486
487 if (OpenOut())
488 {
489 for (;;)
490 {
491 for (Count = 0; Count < NUMBRACKETS; Count++)
492 Brackets[Count] = 0L;
493
494 #define DEF(type, name, value) name = value
495 STATE_VARS;
496 #undef DEF
497 if (UsingStdIn)
498 {
499 if (StdInUse)
500 break;
501 else
502 {
503 StdInUse = TRUE;
504 PushFile("stdin", stdin, &InputStack);
505 }
506 }
507 else
508 {
509 if (CurArg <= argc)
510 {
511 const char *filename = NULL;
512 if (CurArg < argc)
513 filename = argv[CurArg++];
514
515 AddDirectoryFromRelativeFile(filename,&TeXInputs);
516 if (!PushFileName(filename, &InputStack))
517 break;
518 }
519 }
520
521 if (StkTop(&InputStack) && OutputFile)
522 {
523 while (!ferror(OutputFile)
524 && StkTop(&InputStack)
525 && !ferror(CurStkFile(&InputStack))
526 && FGetsStk(ReadBuffer, BUFFER_SIZE - 1,
527 &InputStack))
528 {
529
530 /* Make all spaces ordinary spaces */
531
532 strrep(ReadBuffer, '\n', ' ');
533 strrep(ReadBuffer, '\r', ' ');
534 ExpandTabs(ReadBuffer, TmpBuffer, Tab,
535 BUFFER_SIZE - 1 - strlen(ReadBuffer));
536 strcpy(ReadBuffer, TmpBuffer);
537
538 strcat(ReadBuffer, " ");
539 ret = FindErr(ReadBuffer, CurStkLine(&InputStack));
540 if ( ret != EXIT_SUCCESS ) {
541 retval = ret;
542 }
543 }
544
545 PrintStatus(CurStkLine(&InputStack));
546 }
547 }
548 }
549 }
550 }
551 return retval;
552 }
553
554 /*
555 * Opens the output file handle & possibly renames
556 */
557
558 static int OpenOut(void)
559 {
560 int Success = TRUE;
561
562 if (*OutputName)
563 {
564 if (BackupOut && fexists(OutputName))
565 {
566 strcpy(TmpBuffer, OutputName);
567 AddAppendix(TmpBuffer, BAKAPPENDIX);
568
569 if (fexists(TmpBuffer))
570 remove(TmpBuffer);
571
572 if (!rename(OutputName, TmpBuffer))
573 PrintPrgErr(pmRename, OutputName, TmpBuffer);
574 else
575 {
576 PrintPrgErr(pmRenameErr, OutputName, TmpBuffer);
577 Success = FALSE;
578 }
579
580 }
581
582 if (Success)
583 {
584 #ifdef KPATHSEA
585 if (!(OutputFile = fopen(OutputName, "wb")))
586 #else
587 if (!(OutputFile = fopen(OutputName, "w")))
588 #endif
589 {
590 PrintPrgErr(pmOutOpen);
591 Success = FALSE;
592 }
593 }
594 }
595 else
596 OutputFile = stdout;
597
598 return (Success);
599 }
600
601 #ifndef STRIP_DEBUG
602 static void ShowWL(const char *Name, const struct WordList *wl)
603 {
604 unsigned long i, j, percent;
605
606 fprintf(stderr, "Name: %12s", Name);
607
608 if (DebugLevel & FLG_DbgListInfo)
609 {
610 fprintf(stderr, ", MaxLen: %3ld, Entries: %3ld, ",
611 wl->MaxLen, wl->Stack.Used);
612
613 if (wl->Hash.Index && wl->Stack.Used)
614 {
615 for (i = j = 0; i < HASH_SIZE; i++)
616 {
617 if (wl->Hash.Index[i])
618 j++;
619 }
620 percent = (j * 10000) / wl->Stack.Used;
621
622
623 fprintf(stderr, "Hash usage: %3ld.%02ld%%",
624 percent / 100, percent % 100);
625 }
626 else
627 fprintf(stderr, "No hash table.");
628 }
629
630 fputc('\n', stderr);
631
632 if (DebugLevel & FLG_DbgListCont)
633 {
634 FORWL(i, *wl) fprintf(stderr, "\t%s\n", (char *) wl->Stack.Data[i]);
635 }
636 }
637 #endif
638
639 #define BOOLDISP(var) ((var)? OnText : OffText)
640 #define SHOWSTAT(text, arg) fprintf(stderr, "\t" text ": %s\n", arg)
641 #define BOOLSTAT(name, var) SHOWSTAT(name, BOOLDISP(var))
642 #define SHOWSTR(text, arg) fprintf(stderr, "%s:\n\t%s\n", text, arg);
643
644
645 /*
646 * Prints some of the internal flags; mainly for debugging purposes
647 */
648
649 static void ShowIntStatus(void)
650 {
651 #ifndef STRIP_DEBUG
652 unsigned long Cnt;
653 const char *String;
654 const char *iuStr = "";
655
656 if (DebugLevel & FLG_DbgMsgs)
657 {
658 fprintf(stderr, "There are %d warnings/error messages available:\n",
659 emMaxFault - emMinFault - 1);
660
661 for (Cnt = emMinFault + 1; Cnt < emMaxFault; Cnt++)
662 {
663 switch (LaTeXMsgs[Cnt].Type)
664 {
665 case etWarn:
666 String = "Warning";
667 break;
668 case etErr:
669 String = "Error";
670 break;
671 case etMsg:
672 String = "Message";
673 break;
674 default:
675 String = "";
676 break;
677 }
678
679 switch (LaTeXMsgs[Cnt].InUse)
680 {
681 case iuOK:
682 iuStr = "In use";
683 break;
684 case iuNotUser:
685 iuStr = "User muted";
686 break;
687 case iuNotSys:
688 iuStr = "System muted";
689 break;
690 }
691
692 fprintf(stderr, "Number: %2ld, Type: %s, Status: %s\n"
693 "\tText: %s\n\n",
694 Cnt, String, iuStr, LaTeXMsgs[Cnt].Message);
695 }
696 }
697
698 #undef KEY
699 #undef LCASE
700 #undef LNEMPTY
701 #undef LIST
702
703 #define LNEMPTY LIST
704 #define LIST(a) ShowWL(#a, &a);
705 #define LCASE(a) LIST(a); LIST(a ## Case);
706 #define KEY(a,def) SHOWSTR(#a, a);
707
708
709 if (DebugLevel & (FLG_DbgListInfo | FLG_DbgListCont))
710 {
711 ShowWL("ConfigFilesRead", &ConfigFiles);
712 RESOURCE_INFO
713 }
714
715 if (DebugLevel & FLG_DbgOtherInfo)
716 {
717 SHOWSTR("Outputformat", OutputFormat);
718
719 fprintf(stderr, "Current flags include:\n");
720
721 BOOLSTAT("Read global resource", GlobalRC);
722 BOOLSTAT("Wipe verbose commands", WipeVerb);
723 BOOLSTAT("Backup outfile", BackupOut);
724 BOOLSTAT("Quiet mode", Quiet);
725 BOOLSTAT("Show license", LicenseOnly);
726 BOOLSTAT("Use stdin", UsingStdIn);
727 BOOLSTAT("\\input files", InputFiles);
728 BOOLSTAT("Output header errors", HeadErrOut);
729 BOOLSTAT("No line suppressions", NoLineSupp);
730 }
731 #endif
732 }
733
734 /*
735 * Resets all stacks.
736 *
737 */
738
739 #undef KEY
740 #undef LCASE
741 #undef LNEMPTY
742 #undef LIST
743
744 #define LNEMPTY LIST
745 #define LIST(a) ClearWord(&a);
746 #define LCASE(a) LIST(a); LIST(a ## Case);
747 #define KEY(a,def) a = def;
748
749 static void ResetStacks(void)
750 {
751 RESOURCE_INFO
752 }
753
754 /*
755 * Resets all flags (not wordlists) to their default values. Sets
756 * Outputfile to stdout.
757 *
758 */
759
760 static void ResetSettings(void)
761 {
762
763 #define DEF(type, name, value) name = value
764 OPTION_DEFAULTS;
765 #undef DEF
766 if (OutputFile != stdout)
767 {
768 fclose(OutputFile);
769 OutputFile = stdout;
770 }
771 }
772
773 /*
774 * Reads a numerical argument from the argument. Supports concatenation
775 * of arguments (main purpose)
776 */
777
778 static int ParseNumArg(long *Dest, /* Where to put the value */
779 long Default, /* Value to put in if no in argue */
780 char **Argument) /* optarg or similar */
781 {
782 if (Argument && *Argument && isdigit((unsigned char)**Argument))
783 *Dest = strtol(*Argument, Argument, 10);
784 else
785 *Dest = Default;
786
787 return (ShiftArg(Argument));
788 }
789
790 /*
791 * Same as above; however, will toggle the boolean if user doesn't
792 * supply value
793 */
794
795 static int ParseBoolArg(int *Dest, /* Boolean value */
796 char **Argument) /* optarg or similar */
797 {
798 long D = *Dest ? 1L : 0L;
799 int Retval;
800
801 Retval = ParseNumArg(&D, *Dest ? 0L : 1L, Argument);
802
803 *Dest = D ? TRUE : FALSE;
804
805 return (Retval);
806 }
807
808 /*
809 * Returns the first character in the string passed, updates the
810 * string pointer, if the string is non-empty.
811 *
812 * 0 if the string is empty.
813 */
814
815 static int ShiftArg(char **Argument) /* optarg or similar */
816 {
817 if (Argument && *Argument && **Argument)
818 return (*((char *) (*Argument)++));
819 else
820 return 0;
821 }
822
823 /*
824 * Parses an argv similar array.
825 */
826
827 static int ParseArgs(int argc, char **argv)
828 {
829 /* Needed for option parsing. */
830
831 static const struct option long_options[] = {
832 {"help", no_argument, 0L, 'h'},
833 {"localrc", required_argument, 0L, 'l'},
834 {"output", required_argument, 0L, 'o'},
835 {"warnon", required_argument, 0L, 'w'},
836 {"erroron", required_argument, 0L, 'e'},
837 {"msgon", required_argument, 0L, 'm'},
838 {"nowarn", required_argument, 0L, 'n'},
839 {"nolinesupp", no_argument, 0L, 'L'},
840 {"verbosity", optional_argument, 0L, 'v'},
841 {"pipeverb", optional_argument, 0L, 'V'},
842 {"debug", required_argument, 0L, 'd'},
843 {"reset", no_argument, 0L, 'r'},
844 {"set", required_argument, 0L, 'S'},
845 {"quiet", no_argument, 0L, 'q'},
846 {"license", no_argument, 0L, 'i'},
847 {"splitchar", required_argument, 0L, 's'},
848 {"format", required_argument, 0L, 'f'},
849 {"pseudoname", required_argument, 0L, 'p'},
850
851 {"inputfiles", optional_argument, 0L, 'I'},
852 {"backup", optional_argument, 0L, 'b'},
853 {"globalrc", optional_argument, 0L, 'g'},
854 {"wipeverb", optional_argument, 0L, 'x'},
855 {"tictoc", optional_argument, 0L, 't'},
856 {"headererr", optional_argument, 0L, 'H'},
857 {"version", no_argument, 0L, 'W'},
858
859 {0L, 0L, 0L, 0L}
860 };
861
862 int option_index = 0L, c, i, nextc, ErrType;
863
864 int Retval = FALSE, InUse;
865 int Success, Foo;
866 long Err, Verb = 1, PipeVerb = 1;
867
868 enum
869 {
870 aeNoErr = 0,
871 aeArg, /* missing/bad required argument */
872 aeOpt, /* unknown option returned */
873 aeHelp, /* just a call for help */
874 aeMem /* no memory */
875 } ArgErr = aeNoErr;
876
877 optind = 0;
878
879 while (!ArgErr &&
880 ((c = getopt_long((int) argc, argv,
881 "b::d:e:f:g::hH::I::il:m:n:Lo:p:qrs:S:t::v::V::w:Wx::",
882 long_options, &option_index)) != EOF))
883 {
884 while (c)
885 {
886 nextc = 0;
887 switch (c)
888 {
889 case 'S':
890 ReadRCFromCmdLine(optarg);
891 break;
892
893 case 's':
894 if (!(Delimit = strdup(optarg)))
895 {
896 PrintPrgErr(pmStrDupErr);
897 ArgErr = aeMem;
898 }
899
900 break;
901 case 'p':
902 if (!(PseudoInName = strdup(optarg)))
903 {
904 PrintPrgErr(pmStrDupErr);
905 ArgErr = aeMem;
906 }
907
908 break;
909
910 case 'd':
911 #ifdef STRIP_DEBUG
912
913 PrintPrgErr(pmNoDebugFlag);
914 #else
915
916 nextc = ParseNumArg(&DebugLevel, 0xffff, &optarg);
917 #endif
918
919 break;
920 case 'i':
921 LicenseOnly = TRUE;
922
923 nextc = ShiftArg(&optarg);
924 break;
925 case 'L':
926 NoLineSupp = TRUE;
927
928 nextc = ShiftArg(&optarg);
929 break;
930 case 'q':
931 Quiet = TRUE;
932
933 nextc = ShiftArg(&optarg);
934 break;
935
936 LOOP(warntype,
937 case 'w': ErrType = etWarn; InUse = iuOK; LAST(warntype);
938 case 'e': ErrType = etErr; InUse = iuOK; LAST(warntype);
939 case 'm': ErrType = etMsg; InUse = iuOK; LAST(warntype);
940 case 'n': ErrType = etMsg; InUse = iuNotUser; LAST(warntype);
941 )
942 if (isdigit((unsigned char)*optarg))
943 {
944 nextc = ParseNumArg(&Err, -1, &optarg);
945 if (betw(emMinFault, Err, emMaxFault))
946 {
947 LaTeXMsgs[Err].Type = ErrType;
948 LaTeXMsgs[Err].InUse = InUse;
949 }
950 else
951 {
952 ArgErr = aeOpt;
953 PrintPrgErr(pmWarnNumErr);
954 }
955 }
956 else if (!strcasecmp(optarg, "all"))
957 {
958 for (i = emMinFault + 1; i < emMaxFault; i++)
959 {
960 LaTeXMsgs[i].Type = ErrType;
961 LaTeXMsgs[i].InUse = InUse;
962 }
963 }
964 else
965 {
966 ArgErr = aeOpt;
967 PrintPrgErr(pmWarnNumErr);
968 }
969
970 break;
971
972 case 'g':
973 nextc = ParseBoolArg(&GlobalRC, &optarg);
974 if (!GlobalRC)
975 {
976 ResetStacks();
977 }
978 break;
979
980 case 'r':
981 ResetSettings();
982 nextc = ShiftArg(&optarg);
983 break;
984
985 case 'l':
986 if (optarg)
987 ReadRC(optarg);
988 break;
989
990 case 'f':
991 if (!(OutputFormat = strdup(optarg)))
992 {
993 PrintPrgErr(pmStrDupErr);
994 ArgErr = aeMem;
995 }
996 break;
997
998 case 'v':
999 nextc = ParseNumArg(&Verb, 2, &optarg);
1000
1001 if (Verb < (long) OutFormat.Stack.Used)
1002 OutputFormat = strdup(OutFormat.Stack.Data[Verb]);
1003 else
1004 {
1005 PrintPrgErr(pmVerbLevErr);
1006 ArgErr = aeArg;
1007 }
1008 break;
1009 case 'V':
1010 nextc = ParseNumArg(&PipeVerb, 1, &optarg);
1011
1012 if (PipeVerb < (long) OutFormat.Stack.Used)
1013 PipeOutputFormat = strdup(OutFormat.Stack.Data[PipeVerb]);
1014 else
1015 {
1016 PrintPrgErr(pmVerbLevErr);
1017 ArgErr = aeArg;
1018 }
1019 break;
1020
1021 case 'o':
1022 if (optarg)
1023 {
1024 if (*OutputName)
1025 {
1026 PrintPrgErr(pmOutTwice);
1027 ArgErr = aeOpt;
1028 }
1029 else
1030 {
1031 if (!(OutputName = strdup(optarg)))
1032 {
1033 PrintPrgErr(pmStrDupErr);
1034 ArgErr = aeMem;
1035 }
1036 }
1037 }
1038
1039 break;
1040
1041 case 't':
1042 nextc = ParseBoolArg(&Foo, &optarg);
1043 break;
1044 case 'x':
1045 nextc = ParseBoolArg(&WipeVerb, &optarg);
1046 break;
1047 case 'b':
1048 nextc = ParseBoolArg(&BackupOut, &optarg);
1049 break;
1050 case 'I':
1051 nextc = ParseBoolArg(&InputFiles, &optarg);
1052 break;
1053 case 'H':
1054 nextc = ParseBoolArg(&HeadErrOut, &optarg);
1055 break;
1056 case 'W':
1057 printf("%s", Banner);
1058 exit(EXIT_SUCCESS);
1059 case '?':
1060 default:
1061 fputs(Banner, stderr);
1062 fputs(HowHelp, stderr);
1063 exit(EXIT_FAILURE);
1064 break;
1065 case 'h':
1066 ArgErr = aeHelp;
1067 break;
1068 }
1069 c = nextc;
1070 }
1071 }
1072
1073 if ((argc > optind) && !strcmp(argv[optind], "?"))
1074 ArgErr = aeHelp;
1075
1076 if (ArgErr)
1077 {
1078 fputs(Banner, stderr);
1079 fputs(BigBanner, stderr);
1080 fputs(HelpText, stderr);
1081 Success = FALSE;
1082 }
1083 else
1084 Success = TRUE;
1085
1086 if (Success)
1087 Retval = optind;
1088
1089 return (Retval);
1090 }
1091
1092 /*
1093 * Outputs a program error.
1094 */
1095
1096
1097 void PrintPrgErr(enum PrgErrNum Error, ...)
1098 {
1099 const char *Type;
1100 va_list MsgArgs;
1101
1102 if (betw(pmMinFault, Error, pmMaxFault))
1103 {
1104 switch (PrgMsgs[Error].Type)
1105 {
1106 case etWarn:
1107 Type = "WARNING";
1108 break;
1109 case etMsg:
1110 Type = "NOTE";
1111 break;
1112 default:
1113 case etErr:
1114 Type = "ERROR";
1115 break;
1116 }
1117 fprintf(stderr, "%s: %s -- ", PrgName, Type);
1118
1119 va_start(MsgArgs, Error);
1120 vfprintf(stderr, PrgMsgs[Error].Message, MsgArgs);
1121 va_end(MsgArgs);
1122 fputc('\n', stderr);
1123
1124 if (PrgMsgs[Error].Type == etErr)
1125 exit(EXIT_FAILURE);
1126 }
1127 }
1128
1129 void ErrPrintf(const char *fmt, ...)
1130 {
1131 va_list MsgArgs;
1132
1133 va_start(MsgArgs, fmt);
1134 vfprintf(stderr, fmt, MsgArgs);
1135 va_end(MsgArgs);
1136 }