Debian Codegraph @

texk/detex/detex-src/detex.l

raw
1 %option never-interactive
2 %option nounput
3
4 %top{
5 /*
6 * Copyright (c) 1986-2007 Purdue University
7 * All rights reserved.
8 *
9 * Developed by: Daniel Trinkle
10 * Department of Computer Science, Purdue University
11 * http://www.cs.purdue.edu/
12 *
13 * Permission is hereby granted, free of charge, to any person obtaining
14 * a copy of this software and associated documentation files (the
15 * "Software"), to deal with the Software without restriction, including
16 * without limitation the rights to use, copy, modify, merge, publish,
17 * distribute, sublicense, and/or sell copies of the Software, and to
18 * permit persons to whom the Software is furnished to do so, subject to
19 * the following conditions:
20 *
21 * o Redistributions of source code must retain the above copyright
22 * notice, this list of conditions and the following disclaimers.
23 *
24 * o Redistributions in binary form must reproduce the above copyright
25 * notice, this list of conditions and the following disclaimers in the
26 * documentation and/or other materials provided with the distribution.
27 *
28 * o Neither the names of Daniel Trinkle, Purdue University, nor the
29 * names of its contributors may be used to endorse or promote products
30 * derived from this Software without specific prior written
31 * permission.
32 *
33 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
34 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
35 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
36 * IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR
37 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
38 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
39 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE SOFTWARE.
40 */
41
42
43 /*
44 * detex [-e environment-list] [-c] [-l] [-n] [-s] [-t] [-w] [-1] [file[.tex] ]
45 *
46 * This program is used to remove TeX or LaTeX constructs from a text
47 * file.
48 */
49
50 #include "detex.h"
51
52 #ifdef KPATHSEA
53
54 #include <c-auto.h>
55 #include <kpathsea/c-auto.h>
56 #include <kpathsea/config.h>
57 #include <kpathsea/c-memstr.h>
58 #include <kpathsea/c-pathmx.h>
59 #include <kpathsea/c-std.h>
60 #include <kpathsea/tex-file.h>
61
62 #ifdef HAVE_SYS_PARAM_H
63 #include <sys/param.h>
64 #endif
65
66 #else /* KPATHSEA */
67
68 #ifdef HAVE_STRING_H
69 #include <string.h>
70 #else
71 #include <strings.h>
72 #define strrchr rindex
73 #endif
74
75 #ifdef HAVE_LIMITS_H
76 #include <limits.h>
77 #else
78 #include <sys/param.h>
79 #ifndef PATH_MAX /* for old BSD */
80 #define PATH_MAX MAXPATHLEN
81 #endif
82 #endif /* HAVE_LIMITS_H */
83
84 #ifdef OS2
85 #include <stdlib.h>
86 #endif
87
88 #ifdef WIN32
89 #include <fcntl.h>
90 #include <io.h>
91 #endif
92
93 #endif /* KPATHSEA */
94 }
95
96 %{
97 #undef IGNORE
98 #undef ECHO
99
100 #define LaBEGIN if (fLatex) BEGIN
101 #define IGNORE Ignore()
102 #define INCRLINENO IncrLineNo()
103 #define ECHO Echo()
104 #define NOUN if (fSpace && !fWord && !fReplace) putchar(' '); else {if (fReplace) printf("noun");}
105 #define VERBNOUN if (fReplace) printf(" verbs noun"); /* puts a verb and a noun to make grammar checking work */
106 #define SPACE if (!fWord) putchar(' ')
107 #define NEWLINE LineBreak()
108 #define LATEX fLatex=!fForcetex
109 #define KILLARGS(x) cArgs=x; LaBEGIN LaMacro
110 #define STRIPARGS(x) cArgs=x; LaBEGIN LaMacro2
111 #define CITE(x) if (fLatex && !fCite) KILLARGS(x)
112
113 /* avoid gratuitous gcc warning from passing -D for this on command line */
114 #ifndef NO_MALLOC_DECL
115 #define NO_MALLOC_DECL
116 #endif
117
118 void LineBreak();
119 void Ignore();
120 void IncrLineNo();
121 void Echo();
122 void AddInclude(char *sbFile);
123 void ErrorExit(const char *sb1);
124 void UsageExit(void);
125 void VersionExit(void);
126 void IncludeFile(char *sbFile);
127 void InputFile(char *sbFile);
128 void SetEnvIgnore(const char *sbEnvList);
129 #ifndef KPATHSEA
130 void SetInputPaths(void);
131 #endif
132 void Warning(const char *sb1, const char *sb2);
133 int BeginEnv(const char *sbEnv);
134 int EndEnv(const char *sbEnv);
135 int InList(char *sbFile);
136 int SeparateList(char *sbList, char *rgsbList[] ,char chSep, int csbMax);
137 FILE *TexOpen(char *sbFile);
138 char *SafeMalloc(int cch, const char *sbMessage);
139 #ifndef KPATHSEA
140 char *getenv(const char *);
141 #ifndef NO_MALLOC_DECL
142 char *malloc();
143 #endif
144 #ifdef OS2
145 void yyless(int);
146 void OS2UsageExit(void);
147 #endif
148 #endif /* KPATHSEA */
149
150 char *rgsbEnvIgnore[MAXENVS]; /* list of environments ignored */
151 char *rgsbIncList[MAXINCLIST]; /* list of includeonly files */
152 char *rgsbInputPaths[MAXINPUTPATHS]; /* list of input paths in order */
153 char sbCurrentIgnoredEnv[CCHMAXENV]; /* current environment being ignored */
154 char *sbProgName; /* name we were invoked with */
155 #ifndef NOFILE /* might be defined in <sys/param.h> */
156 #define NOFILE 256
157 #endif
158 FILE *rgfp[NOFILE+1]; /* stack of input/include files */
159 int cfp = 0; /* count of files in stack */
160 int cOpenBrace = 0; /* count of `{' in <LaMacro> and <LaMacro2> */
161 int cArgs = 0; /* argument connt in <LaArgs> */
162 int csbEnvIgnore; /* count of environments ignored */
163 int csbIncList = 0; /* count of includeonly files */
164 int csbInputPaths; /* count of input paths */
165 int fLatex = 0; /* flag to indicated delatex */
166 int fWord = 0; /* flag for -w option */
167 int fFollow = 1; /* flag to follow input/include */
168 int fCite = 0; /* flag to echo \cite and \ref args */
169 int fSpace = 0; /* flag to replace \cs with space */
170 int fForcetex = 0; /* flag to inhibit latex mode */
171 int fSrcLoc = 0; /* flag to display source location of original file */
172 int fShowPictures = 0; /* flag to show picture names */
173 int fReplace = 0; /* flag to replace envirnments with "noun" */
174
175 int currBracesLevel = 0;
176 int footnoteLevel = -100;
177
178 #ifdef FLEX_SCANNER
179 /* flex has contexts for buffers that need to be switched when file changes
180 * otherwise output contains imported files in reverse order. Weird, but
181 * true.
182 */
183 YY_BUFFER_STATE rgsb[NOFILE + 1]; /* flex context stack */
184 char* fFileNames[NOFILE + 1]; /* names of the buffers in context stack */
185 int fFileLines[NOFILE + 1]; /* line number in each of the context files */
186 int fIsColumn0 = 1; /* Are we at the begining of a line? */
187 int csb = 0; /* depth of flex context stack */
188 #endif /* FLEX_SCANNER */
189
190 %}
191
192 S [ \t\n]*
193 W [a-zA-Z]+
194 N [+-]?(([0-9]+(\.[0-9]+)?)|(\.[0-9]+))
195 U pt|pc|in|bp|cm|mm|dd|cc|sp
196 P [a-zA-Z!]+
197 HU {U}|em
198 HD {S}(({N}{S}{HU})|(\\{W})){S}
199 HG {HD}(plus{HD})?(minus{HD})?
200 VU {U}|ex
201 VD {S}(({N}{S}{VU})|(\\{W})){S}
202 VG {VD}(plus{VD})?(minus{VD})?
203 Z \*?
204 VERBSYMBOL =|\\leq|\\geq|\\in|>|<|\\subseteq|\subseteq|\\subset|\\supset|\\sim|\\neq|\\mapsto
205
206 %Start Define Display IncludeOnly Input Math Normal Control
207 %Start LaBegin LaDisplay LaEnd LaEnv LaFormula LaInclude LaSubfile
208 %Start LaMacro LaOptArg LaMacro2 LaOptArg2 LaVerbatim
209 %start LaBreak LaPicture
210
211 %%
212 <Normal>"%".* /* ignore comments */ {INCRLINENO;}
213
214 <Normal>"\\begin"{S}"{"{S}"document"{S}"}""\n"* {LATEX; IGNORE;}
215
216 <Normal>"\\begin" /* environment start */ {LaBEGIN LaBegin; IGNORE;}
217
218 <LaBegin>{S}"{"{S}"verbatim"{S}"}" { if (BeginEnv("verbatim"))
219 BEGIN LaEnv;
220 else
221 BEGIN LaVerbatim;
222 IGNORE;
223 }
224
225 <LaVerbatim>"\\end"{S}"{"{S}"verbatim"{S}"}" /* verbatim mode */ {BEGIN Normal; IGNORE;}
226 <LaVerbatim>[^\\]+ ECHO;
227 <LaVerbatim>. ECHO;
228
229 <LaBegin>{S}"{"{S}"minipage"{S}"}" { KILLARGS(1);
230 if (BeginEnv("minipage"))
231 BEGIN LaEnv;
232 else
233 BEGIN LaMacro; /* Normal; */
234 IGNORE;
235 }
236
237 <LaBegin>{S}"{"{S}"table"{S}"}"{S}"["{P}"]" {
238 if (BeginEnv("table"))
239 BEGIN LaEnv;
240 else
241 BEGIN Normal;
242 IGNORE;
243 }
244
245 <LaBegin>{S}"{"{S}"figure"{S}"}"{S}"["{P}"]" {
246 if (BeginEnv("figure"))
247 BEGIN LaEnv;
248 else
249 BEGIN Normal;
250 IGNORE;
251 }
252
253 <LaBegin>{W} { if (BeginEnv(yytext))
254 BEGIN LaEnv;
255 else
256 BEGIN Normal;
257 IGNORE;
258 }
259 /*<LaBegin>"\n" NEWLINE;*/
260 <LaBegin>. {INCRLINENO;}
261
262 <LaEnv>"\\end" /* absorb some environments */ {LaBEGIN LaEnd; IGNORE;}
263 <LaEnv>"\n"+ ;/*NEWLINE;*/
264 <LaEnv>. {INCRLINENO;}
265
266 <LaEnd>{W} /* end environment */ { if (EndEnv(yytext))
267 BEGIN Normal;
268 IGNORE;
269 }
270 <LaEnd>"}" {BEGIN LaEnv; IGNORE;}
271 /*<LaEnd>"\n" NEWLINE;*/
272 <LaEnd>. {INCRLINENO;}
273
274 <Normal>"\\kern"{HD} ;
275 <Normal>"\\vskip"{VG} ;
276 <Normal>"\\vspace"{Z}{S}"{"{VG}"}" ;
277 <Normal>"\\hskip"{HG} ;
278 <Normal>"\\hspace"{Z}{S}"{"{HG}"}" ;
279 <Normal>"\\addvspace"{S}"{"{VG}"}" ;
280 <Normal>"{"{N}"pt}" ; /* hack to fix \begin{minipage}{300pt} */
281
282 <Normal>"\\newlength" { KILLARGS(1); }
283 <Normal>"\\setlength" { KILLARGS(2); }
284 <Normal>"\\addtolength" { KILLARGS(2); }
285 <Normal>"\\settowidth" { KILLARGS(2); }
286 <Normal>"\\settoheight" { KILLARGS(2); }
287 <Normal>"\\settodepth" { KILLARGS(2); }
288 <Normal>"\\newsavebox" { KILLARGS(1); }
289 <Normal>"\\sbox" { KILLARGS(1); }
290 <Normal>"\\savebox" { KILLARGS(2); }
291 <Normal>"\\usebox" { KILLARGS(1); }
292 <Normal>"\\raisebox" { STRIPARGS(2); }
293 <Normal>"\\parbox" { KILLARGS(1); }
294 <Normal>"\\scalebox" { STRIPARGS(2); }
295 <Normal>"\\resizebox"{Z} { KILLARGS(2); }
296 <Normal>"\\reflectbox" ;
297 <Normal>"\\rotatebox" { KILLARGS(1); }
298 <Normal>"\\includegraphics"[^{]* { LaBEGIN LaPicture; }
299
300 <LaPicture>"{" ;
301 <LaPicture>[^{}]+ { if(fShowPictures) { printf("<Picture %s>", yytext); } }
302 <LaPicture>"\}"{S}"\n"+ { BEGIN Normal; INCRLINENO; }
303 <LaPicture>"\}" BEGIN Normal;
304
305 <Normal>"\\definecolor" { KILLARGS(3); }
306 <Normal>"\\color" { KILLARGS(1); }
307 <Normal>"\\textcolor" { KILLARGS(2); }
308 <Normal>"\\colorbox" { KILLARGS(2); }
309 <Normal>"\\fcolorbox" { KILLARGS(3); }
310 <Normal>"\\pagecolor" { KILLARGS(1); }
311 <Normal>"\\foilhead" { STRIPARGS(1); }
312 <Normal>"\\addfontfeature" { KILLARGS(1); }
313 <Normal>"\\thispagestyle" { KILLARGS(1); }
314 <Normal>"\\addcontentsline" { KILLARGS(3); }
315
316 <Normal>"\\part"{Z} ;/*NEWLINE;*/
317 <Normal>"\\chapter"{Z} ;/*NEWLINE;*/
318 <Normal>"\\section"{Z} ;/*NEWLINE;*/
319 <Normal>"\\subsection"{Z} ;/*NEWLINE;*/
320 <Normal>"\\subsubsection"{Z} ;/*NEWLINE;*/
321 <Normal>"\\paragraph"{Z} ;/*NEWLINE;*/
322 <Normal>"\\subparagraph"{Z} ;/*NEWLINE;*/
323
324 <Normal>"\\bibitem" /* ignore args */ {KILLARGS(1); IGNORE;}
325 <Normal>"\\bibliography" /* of these \cs */ {KILLARGS(1); IGNORE;}
326 <Normal>"\\bibstyle" {KILLARGS(1); IGNORE;}
327 <Normal>" "?"\\cite" {KILLARGS(1);} /* kill space before */
328 <Normal>"\\documentstyle" {LATEX; KILLARGS(1); IGNORE;}
329 <Normal>"\\documentclass" {LATEX; KILLARGS(1); IGNORE;}
330 <Normal>"\\usepackage" {KILLARGS(1); IGNORE;}
331 <Normal>"\\end" {KILLARGS(1); IGNORE;}
332 <Normal>"\\hypersetup" {KILLARGS(1);}
333 <Normal>"\\index" {KILLARGS(1);}
334 /*<Normal>"\\footnote" {KILLARGS(1); SPACE;}*/
335 <Normal>"\\label" {KILLARGS(1); IGNORE;}
336 <Normal>"\\nameref" {CITE(1); IGNORE;}
337 <Normal>"\\pageref" {CITE(1); IGNORE;}
338 <Normal>"\\pagestyle" {KILLARGS(1); IGNORE;}
339 <Normal>"\\ref" {CITE(1); IGNORE;}
340 <Normal>"\\setcounter" {KILLARGS(2); IGNORE;}
341 <Normal>"\\addtocounter" {KILLARGS(2); IGNORE;}
342 <Normal>"\\newcounter" { KILLARGS(1); }
343 <Normal>"\\stepcounter" { KILLARGS(2); }
344
345 <Normal>"\\fontspec" {KILLARGS(1);}
346
347 <Normal>"\\footnote"(\[([^\]])+\])?"{" {
348 putchar('(');
349 footnoteLevel = currBracesLevel;
350 ++currBracesLevel;
351 }
352 <Normal>"\\verb" /* ignore \verb<ch>...<ch> */ {
353 if (fLatex) {
354 int verbchar, c;
355 verbchar = input();
356 if (verbchar < ' ') {
357 /* would be nice to include input filenames and line numbers */
358 ErrorExit("\\verb not complete before eof");
359 }
360 while ((c = input()) != verbchar && c != '\n' && c != EOF && c != 0) {
361 putchar(c);
362 }
363 if (c != verbchar) {
364 ErrorExit("\\verb not complete before eof");
365 }
366 }
367 }
368
369 <Normal>"\\newcommand" { LATEX; KILLARGS(2); }
370 <Normal>"\\renewcommand" { LATEX; KILLARGS(2); }
371 <Normal>"\\newenvironment" { LATEX; KILLARGS(3); }
372
373 <Normal>"\\def" /* ignore def begin */ {BEGIN Define; IGNORE;}
374 <Define>"{" BEGIN Normal;
375 <Define>"\n" NEWLINE;
376 <Define>. ;
377
378 <Normal>"\\(" /* formula mode */ {LaBEGIN LaFormula; NOUN;}
379 <LaFormula>"\\)" BEGIN Normal;
380 <LaFormula>"\n" NEWLINE;
381 <LaFormula>{VERBSYMBOL} VERBNOUN;
382 <LaFormula>. ;
383
384 <Normal>"\\[" /* display mode */ {LaBEGIN LaDisplay; NOUN;}
385 <LaDisplay>"\\]" BEGIN Normal;
386 <LaDisplay>"\n" NEWLINE;
387 <LaDisplay>{VERBSYMBOL} VERBNOUN;
388 <LaDisplay>. ;
389
390 <Normal>"$$" /* display mode */ {BEGIN Display; NOUN;}
391 <Display>"$$" BEGIN Normal;
392 <Display>"\n" NEWLINE;
393 <Display>{VERBSYMBOL} VERBNOUN;
394 <Display>. ;
395
396 <Normal>"$" /* math mode */ {BEGIN Math; NOUN;}
397 <Math>"$" BEGIN Normal;
398 <Math>"\n" ;
399 <Math>"\\$" ;
400 <Math>{VERBSYMBOL} VERBNOUN;
401 <Math>. ;
402
403 <Normal>"\\include" /* process files */ {LaBEGIN LaInclude; IGNORE;}
404 <LaInclude>[^{ \t\n}]+ { IncludeFile(yytext);
405 BEGIN Normal;
406 }
407 <LaInclude>"\n"+ NEWLINE;
408 <LaInclude>. ;
409
410 <Normal>"\\includeonly" {BEGIN IncludeOnly; IGNORE;}
411 <IncludeOnly>[^{ \t,\n}]+ AddInclude(yytext);
412 <IncludeOnly>"}" { if (csbIncList == 0)
413 *rgsbIncList[csbIncList++] = '\0';
414 BEGIN Normal;
415 }
416 <IncludeOnly>"\n"+ NEWLINE;
417 <IncludeOnly>. ;
418
419 <Normal>"\\subfile" /* process files */ {LaBEGIN LaSubfile; IGNORE;}
420 <LaSubfile>[^{ \t\n}]+ { IncludeFile(yytext);
421 BEGIN Normal;
422 }
423 <LaSubfile>"\n"+ NEWLINE;
424 <LaSubfile>. ;
425
426 <Normal>"\\input" {BEGIN Input; IGNORE;}
427 <Input>[^{ \t\n}]+ { InputFile(yytext);
428 BEGIN Normal;
429 }
430 <Input>"\n"+ NEWLINE;
431 <Input>. ;
432
433 /* escaping commands */
434 <Normal>"\\slash" putchar('/');
435 <Normal>"\\%" putchar('%');
436
437 <Normal>\\(aa|AA|ae|AE|oe|OE|ss)[ \t]*[ \t\n}] /* handle ligatures */ {(void)printf("%.2s", yytext+1);}
438 <Normal>\\[OoijLl][ \t]*[ \t\n}] {(void)printf("%.1s", yytext+1);}
439 <Normal>"\\linebreak"(\[[0-4]\])? {NEWLINE;} /*BEGIN LaBreak;*/
440
441 <Normal>\\[a-zA-Z@]+ /* ignore other \cs */ {BEGIN Control; IGNORE;}
442 <Normal>"\\ " SPACE;
443 <Normal>"\\\\"{Z}(\[[^\]]*\])? NEWLINE;
444 <Normal>\\. IGNORE;
445 <LaBreak>[0-4]? { if (yytext==NULL || strlen(yytext)==0
446 || atoi(yytext)>=0)
447 NEWLINE;
448 BEGIN Normal;
449 }
450
451 <Control>\\[a-zA-Z@]+ IGNORE;
452 <Control>[a-zA-Z@0-9]*[-'=`][^ \t\n{]* IGNORE;
453 <Control>"\n" {BEGIN Normal; /*NEWLINE;*/}
454 <Control>[ \t]*[{]+ {++currBracesLevel;BEGIN Normal; IGNORE;}
455 <Control>[ \t]* {BEGIN Normal; IGNORE;}
456 <Control>. {yyless(0);BEGIN Normal;}
457
458 <Normal>[\\|] /* special characters */ IGNORE;
459 <Normal>[!?]"`" IGNORE;
460 <Normal>~ SPACE;
461 <Normal>-{2,3} putchar('-');
462 <Normal>`` putchar('"');
463 <Normal>` putchar('\'');
464 <Normal>'' putchar('"');
465 <Normal>,, putchar('"');
466
467 /* braces */
468 <Normal>"{" { ++currBracesLevel;
469 }
470 <Normal>"}" {
471 --currBracesLevel;
472 if (currBracesLevel == footnoteLevel) {
473 putchar(')');
474 footnoteLevel = -100;
475 }
476 }
477 <Normal>{W}[']*{W} { if (fWord)
478 (void)printf("%s\n", yytext);
479 else
480 ECHO;
481 }
482 <Normal>[0-9]+ if (!fWord) ECHO;
483 <Normal>. { INCRLINENO; if (!fWord) ECHO; }
484 <Normal>"\n" { if (!fWord) NEWLINE; }
485 <Normal>("\t")+ if (!fWord) putchar('\t');
486
487 <LaMacro>"\[" { BEGIN LaOptArg; }
488 <LaMacro>"{" { cOpenBrace++; }
489 <LaMacro>"}""\n"{0,1} { cOpenBrace--; INCRLINENO;
490 if (cOpenBrace == 0)
491 {
492 if (--cArgs==0)
493 BEGIN Normal;
494 }
495 }
496 <LaMacro>. ;
497 <LaOptArg>"\]" BEGIN LaMacro;
498 <LaOptArg>[^\]]* ;
499
500 <LaMacro2>"\[" { BEGIN LaOptArg2; }
501 <LaMacro2>"{" { if (cOpenBrace == 0)
502 {
503 if (--cArgs==0)
504 {
505 BEGIN Normal;
506 cOpenBrace--;
507 }
508 }
509 cOpenBrace++;
510 }
511 <LaMacro2>"}" { cOpenBrace--; }
512 <LaMacro2>. ;
513 <LaOptArg2>"\]" BEGIN LaMacro2;
514 <LaOptArg2>. ;
515 %%
516
517 /******
518 ** main --
519 ** Set sbProgName to the base of arg 0.
520 ** Set the input paths.
521 ** Check for options
522 ** -c echo LaTeX \cite, \ref, and \pageref values
523 ** -e <env-list> list of LaTeX environments to ignore
524 ** -l force latex mode
525 ** -n do not follow \input and \include
526 ** -s replace control sequences with space
527 ** -t force tex mode
528 ** -w word only output
529 ** -1 output some location information
530 ** Set the list of LaTeX environments to ignore.
531 ** Process each input file.
532 ** If no input files are specified on the command line, process stdin.
533 ******/
534
535 int
536 main(int cArgs, char *rgsbArgs[])
537 {
538 char *pch, sbBadOpt[2];
539 const char *sbEnvList = DEFAULTENV;
540 int fSawFile = 0, iArgs = 1;
541
542 /* get base name and decide what we are doing, detex or delatex */
543 #ifdef OS2
544 char drive[_MAX_DRIVE], dir[_MAX_DIR];
545 char fname[_MAX_FNAME], ext[_MAX_EXT];
546 #ifdef __EMX__
547 _wildcard(&cArgs, &rgsbArgs);
548 _response(&cArgs, &rgsbArgs);
549 #endif
550 _splitpath (rgsbArgs[0], drive, dir, fname, ext);
551 sbProgName = strlwr(fname);
552 #elif defined(KPATHSEA)
553 kpse_set_program_name (rgsbArgs[0], NULL);
554 sbProgName = kpse_program_name;
555 #else
556 if ((sbProgName = strrchr(rgsbArgs[0], '/')) != NULL)
557 sbProgName++;
558 else
559 sbProgName = rgsbArgs[0];
560 #endif
561 if (strcmp("delatex",sbProgName) == 0)
562 fLatex = 1;
563
564 #ifndef KPATHSEA
565 /* set rgsbInputPaths for use with TexOpen() */
566 SetInputPaths();
567 #endif
568
569 /* process command line options */
570 while (iArgs < cArgs && *(pch = rgsbArgs[iArgs]) == CHOPT) {
571 while (*++pch)
572 switch (*pch) {
573 case CHCITEOPT:
574 fCite = 1;
575 break;
576 case CHENVOPT:
577 if (++iArgs >= cArgs) {
578 ErrorExit("-e option requires an argument");
579 }
580 sbEnvList = rgsbArgs[iArgs];
581 break;
582 case CHLATEXOPT:
583 fLatex = 1;
584 break;
585 case CHNOFOLLOWOPT:
586 fFollow = 0;
587 break;
588 case CHSPACEOPT:
589 fSpace = 1;
590 break;
591 case CHTEXOPT:
592 fForcetex = 1;
593 break;
594 case CHWORDOPT:
595 fWord = 1;
596 break;
597 case CHREPLACE:
598 fReplace = 1;
599 break;
600 case CHVERSIONOPT:
601 VersionExit();
602 break;
603 case CHSRCLOC:
604 fSrcLoc = 1;
605 break;
606 default:
607 sbBadOpt[0] = *pch;
608 sbBadOpt[1] = '\0';
609 Warning("unknown option ignored -", sbBadOpt);
610 UsageExit();
611 }
612 iArgs++;
613 }
614 SetEnvIgnore(sbEnvList);
615
616 #ifdef WIN32
617 _setmode(fileno(stdout), _O_BINARY);
618 #endif
619
620 /* process input files */
621 for (; iArgs < cArgs; iArgs++) {
622 fSawFile++;
623 if ((yyin = TexOpen(rgsbArgs[iArgs])) == NULL) {
624 Warning("can't open file", rgsbArgs[iArgs]);
625 continue;;
626 }
627 fFileNames[csb] = rgsbArgs[iArgs];
628 fFileLines[csb] = 1;
629 BEGIN Normal;
630 (void)yylex();
631 }
632
633 /* if there were no input files, assume stdin */
634 if (!fSawFile) {
635 yyin = stdin;
636 #ifdef OS2
637 if (isatty(fileno(stdin)))
638 OS2UsageExit();
639 #endif
640 BEGIN Normal;
641 (void)yylex();
642 }
643 #ifndef FLEX_SCANNER
644 if (YYSTATE != Normal)
645 ErrorExit("input contains an unterminated mode or environment");
646 #endif
647 return(0);
648 }
649
650 #ifdef FLEX_SCANNER
651 #undef yywrap
652 #endif
653
654 /******
655 ** yywrap -- handles EOF for lex. Check to see if the stack of open files
656 ** has anything on it. If it does, set yyin to the to value. If not
657 ** return the termination signal for lex.
658 ******/
659
660 int
661 yywrap(void)
662 {
663 (void)fclose(yyin);
664 #ifdef FLEX_SCANNER
665 /* Pop context state */
666 if (csb > 0) {
667 free(fFileNames[csb]);
668 yy_delete_buffer( YY_CURRENT_BUFFER );
669 yy_switch_to_buffer( rgsb[--csb] );
670 }
671 #endif /* FLEX_SCANNER */
672 if (cfp > 0) {
673 yyin = rgfp[--cfp];
674 return(0);
675 }
676 return(1);
677 }
678
679 #ifdef OS2
680
681 /******
682 ** yyless -- return characters to the input stream. Some systems don't have
683 ** a yyless routine
684 ******/
685
686 void
687 yyless(int n)
688 {
689 int i = strlen(yytext);
690
691 while (i > n) unput(yytext[--i]);
692 yytext[yyleng = n] = '\0';
693 }
694 #endif
695
696 /******
697 ** PrintPrefix -- In case fSrcLoc is 1 and we are about to
698 ** print the first column of a line, we want to output the location of
699 ** that line in the original LaTeX document it came from.
700 ******/
701
702 void
703 PrintPrefix()
704 {
705 if (fSrcLoc && fIsColumn0) {
706 printf("%s:%d: ", fFileNames[csb], fFileLines[csb]);
707 fIsColumn0 = 0;
708 }
709 }
710
711 /******
712 ** LineBreak -- choses the proper way to break a line. If '-1' option is
713 ** enabled we also want to output some source location information.
714 ******/
715
716 void
717 LineBreak()
718 {
719 if (fWord) return;
720 PrintPrefix();
721 putchar('\n');
722 fFileLines[csb]++; fIsColumn0=1;
723 }
724
725 /******
726 ** Echo -- If we are at column 0 and have specified '-1'; output
727 ** the source location information.
728 ******/
729
730 void
731 Echo()
732 {
733 PrintPrefix();
734 fprintf(yyout, "%s", yytext);
735 }
736
737 /******
738 ** IncrLineNo -- Increase the correct linenumber counter and
739 ** reset the the 'fIsColumn0' to true.
740 ******/
741
742 void
743 IncrLineNo()
744 {
745 char *c;
746 for (c=yytext; *c != '\0'; c++) {
747 if (*c == '\n') {
748 fFileLines[csb]++; fIsColumn0=1;
749 }
750 }
751 }
752
753 /******
754 ** Ignore -- Since we might need to track source location information we
755 ** cannot just ignore text. We must at least increase the linenumber counter.
756 ******/
757
758 void
759 Ignore()
760 {
761 IncrLineNo();
762 if (fSpace && !fWord) putchar(' ');
763 }
764
765 /******
766 ** SetEnvIgnore -- sets rgsbEnvIgnore to the values indicated by the
767 ** sbEnvList.
768 ******/
769
770 void
771 SetEnvIgnore(const char *sbEnvList)
772 {
773 char *sb;
774 sb = SafeMalloc(strlen(sbEnvList) + 1, "malloc for SetEnvIgnore failed");
775 (void) strcpy(sb, sbEnvList);
776
777
778 csbEnvIgnore = SeparateList(sb, rgsbEnvIgnore, CHENVSEP, MAXENVS);
779 if (csbEnvIgnore == my_ERROR)
780 ErrorExit("The environment list contains too many environments");
781 }
782
783 /******
784 ** BeginEnv -- checks to see if sbEnv is in the list rgsbEnvIgnore. If it
785 ** is, sbCurrentIgnoredEnv is set to sbEnv.
786 ******/
787
788 int
789 BeginEnv(const char *sbEnv)
790 {
791 int i;
792
793 if (!fLatex) return(0);
794 for (i = 0; i < csbEnvIgnore; ++i)
795 if (strcmp(sbEnv, rgsbEnvIgnore[i]) == 0) {
796 (void)strcpy(sbCurrentIgnoredEnv, sbEnv);
797 return(1);
798 }
799 return(0);
800 }
801
802 /******
803 ** EndEnv -- checks to see if sbEnv is the current environment being ignored.
804 ******/
805
806 int
807 EndEnv(const char *sbEnv)
808 {
809 if (!fLatex) return(0);
810 if (strcmp(sbEnv, sbCurrentIgnoredEnv) == 0)
811 return(1);
812 return(0);
813 }
814
815 /******
816 ** InputFile -- push the current yyin and open sbFile. If the open fails,
817 ** the sbFile is ignored.
818 ******/
819
820
821 void
822 InputFile(char *sbFile)
823 {
824 if (!fFollow)
825 return;
826 rgfp[cfp++] = yyin;
827 if ((yyin = TexOpen(sbFile)) == NULL) {
828 Warning("can't open \\input file", sbFile);
829 yyin = rgfp[--cfp];
830 return;
831 }
832 #ifdef FLEX_SCANNER
833 rgsb[csb++] = YY_CURRENT_BUFFER;
834 fFileLines[csb] = 1;
835 fFileNames[csb] = strdup(sbFile);
836 yy_switch_to_buffer(yy_create_buffer( yyin, YY_BUF_SIZE ) );
837 #endif /* FLEX_SCANNER */
838 }
839
840 /******
841 ** IncludeFile -- if sbFile is not in the rgsbIncList, push current yyin
842 ** and open sbFile. If the open fails, the sbFile is ignored.
843 ******/
844
845 void
846 IncludeFile(char *sbFile)
847 {
848 if (!fFollow)
849 return;
850 if (!InList(sbFile))
851 return;
852 rgfp[cfp++] = yyin;
853 if ((yyin = TexOpen(sbFile)) == NULL) {
854 Warning("can't open \\include file", sbFile);
855 yyin = rgfp[--cfp];
856 return;
857 }
858 #ifdef FLEX_SCANNER
859 rgsb[csb++] = YY_CURRENT_BUFFER;
860 fFileLines[csb] = 1;
861 fFileNames[csb] = strdup(sbFile);
862 yy_switch_to_buffer(yy_create_buffer( yyin, YY_BUF_SIZE ) );
863 #endif /* FLEX_SCANNER */
864 }
865
866 /******
867 ** AddInclude -- adds sbFile to the rgsbIncList and increments csbIncList.
868 ** If the include list is too long, sbFile is ignored.
869 ******/
870
871 void
872 AddInclude(char *sbFile)
873 {
874 if (!fFollow)
875 return;
876 if (csbIncList >= MAXINCLIST)
877 Warning("\\includeonly list is too long, ignoring", sbFile);
878 rgsbIncList[csbIncList] = SafeMalloc(strlen(sbFile) + 1, "malloc for AddInclude failed");
879 (void)strcpy(rgsbIncList[csbIncList++], sbFile);
880 }
881
882 /******
883 ** InList -- checks to see if sbFile is in the rgsbIncList. If there is
884 ** no list, all files are assumed to be "in the list".
885 ******/
886
887 int
888 InList(char *sbFile)
889 {
890 char *pch, sbBase[PATH_MAX];
891 int i;
892
893 if (csbIncList == 0) /* no list */
894 return(1);
895 (void)strcpy(sbBase, sbFile);
896 if ((pch = strrchr(sbBase, '.')) != NULL)
897 *pch = '\0';
898 i = 0;
899 while ((i < csbIncList) && rgsbIncList[i])
900 if (strcmp(rgsbIncList[i++], sbBase) == 0)
901 return(1);
902 return(0);
903 }
904
905 #ifndef KPATHSEA
906 /******
907 ** SetInputPaths -- sets rgsbInputPaths to the values indicated by the
908 ** TEXINPUTS environment variable if set or else DEFAULTINPUTS. If
909 ** the user's TEXINPUTS has a leading ':' prepend the DEFAULTINPUTS
910 ** to the path, if there is a trailing ':' append the DEFAULTINPUTS.
911 ** This is consistent with the most recent TeX. However, this
912 ** routine does not honor the '//' construct (expand subdirs).
913 ******/
914
915 void
916 SetInputPaths(void)
917 {
918 const char *sb;
919 char *sbPaths;
920 int cchDefaults, cchPaths;
921
922 cchDefaults = strlen(DEFAULTINPUTS);
923 #ifdef OS2
924 if ((sb = getenv("TEXINPUT")) == NULL)
925 #endif
926 if ((sb = getenv("TEXINPUTS")) == NULL)
927 sb = DEFAULTINPUTS;
928 cchPaths = strlen(sb);
929 if (sb[0] == CHPATHSEP)
930 cchPaths += cchDefaults;
931 if (sb[strlen(sb) - 1] == CHPATHSEP)
932 cchPaths += cchDefaults;
933 sbPaths = SafeMalloc(cchPaths + 1, "malloc for SetInputPaths failed");
934 sbPaths[0] = '\0';
935 if (sb[0] == CHPATHSEP)
936 (void)strcat(sbPaths, DEFAULTINPUTS);
937 (void)strcat(sbPaths, sb);
938 if (sb[strlen(sb) - 1] == CHPATHSEP)
939 (void)strcat(sbPaths, DEFAULTINPUTS);
940
941 csbInputPaths = SeparateList(sbPaths, rgsbInputPaths, CHPATHSEP, MAXINPUTPATHS);
942 if (csbInputPaths == my_ERROR)
943 #ifdef OS2
944 ErrorExit("TEXINPUT(S) environment variable has too many paths");
945 #else
946 ErrorExit("TEXINPUTS environment variable has too many paths");
947 #endif
948 }
949 #endif
950
951 /******
952 ** SeparateList -- takes a chSep separated list sbList, replaces the
953 ** chSep's with NULLs and sets rgsbList[i] to the beginning of
954 ** the ith word in sbList. The number of words is returned. A
955 ** my_ERROR is returned if there are more than csbMax words.
956 ******/
957
958 int
959 SeparateList(char *sbList, char *rgsbList[], char chSep, int csbMax)
960 {
961 int csbList = 0;
962
963 while (sbList && *sbList && csbList < csbMax) {
964 rgsbList[csbList++] = sbList;
965 if ((sbList = strchr(sbList, chSep))) {
966 *sbList++ = '\0';
967 }
968 }
969 return(sbList && *sbList ? my_ERROR : csbList);
970 }
971
972 /******
973 ** TexOpen -- tries to open sbFile in each of the rgsbInputPaths in turn.
974 ** For each input path the following order is used:
975 ** file.tex - must be as named, if not there go to the next path
976 ** file.ext - random extension, try it
977 ** file - base name, add .tex and try it
978 ** file - try it as is
979 ** Notice that if file exists in the first path and file.tex exists in
980 ** one of the other paths, file in the first path is what is opened.
981 ** If the sbFile begins with a '/', no paths are searched.
982 ******/
983
984 FILE *
985 TexOpen(char *sbFile)
986 {
987 char *sbNew;
988 #ifndef KPATHSEA
989 char *pch;
990 FILE *fp;
991 int iPath;
992 static char sbFullPath[PATH_MAX];
993
994 for (iPath = 0; iPath < csbInputPaths; iPath++) {
995 #ifdef OS2
996 if (*sbFile == '/' || *sbFile == '\\' || strchr(sbFile, ':')) { /* absolute path */
997 #else
998 if (*sbFile == '/') { /* absolute path */
999 #endif
1000 (void)snprintf(sbFullPath, PATH_MAX-1, "%s", sbFile);
1001 iPath = csbInputPaths; /* only check once */
1002 } else {
1003 (void)snprintf(sbFullPath, PATH_MAX-1, "%s/%s", rgsbInputPaths[iPath], sbFile);
1004 }
1005 #ifdef OS2
1006 pch = sbFullPath;
1007 while (pch = strchr(pch, '\\')) {
1008 *pch = '/';
1009 }
1010 #endif
1011
1012 /* If sbFile ends in .tex then it must be there */
1013 if ((pch = strrchr(sbFullPath, '.')) != NULL
1014 && (strcmp(pch, ".tex") == 0)) {
1015 if ((fp = fopen(sbFullPath, "r")) != NULL)
1016 return(fp);
1017 else
1018 continue;
1019 }
1020
1021 /* if .<ext> then try to open it. the '.' represents */
1022 /* the beginning of an extension if it is not the first */
1023 /* character and it does not follow a '.' or a '/' */
1024 if (pch != NULL && pch > &(sbFullPath[0])
1025 && *(pch - 1) != '.' && *(pch - 1) != '/'
1026 && (fp = fopen(sbFullPath, "r")) != NULL) {
1027 return(fp);
1028 }
1029
1030 /* just base name, add .tex to the name */
1031 sbNew = SafeMalloc(strlen(sbFullPath) + 5, "malloc for TexOpen failed");
1032 (void)strcpy(sbNew, sbFullPath);
1033 (void)strcat(sbNew, ".tex");
1034 if ((fp = fopen(sbNew, "r")) != NULL) {
1035 free(sbNew);
1036 return(fp);
1037 }
1038 free(sbNew);
1039
1040 /* try sbFile regardless */
1041 if ((fp = fopen(sbFullPath, "r")) != NULL)
1042 return(fp);
1043 }
1044 return NULL;
1045 #else
1046 sbNew = kpse_find_file (sbFile, kpse_tex_format, false);
1047
1048 if (sbNew == NULL)
1049 return NULL;
1050
1051 return fopen (sbNew, "r");
1052 #endif
1053 }
1054
1055 /******
1056 ** SafeMalloc -- wrapper around malloc() to check for failure.
1057 ******/
1058
1059 char *
1060 SafeMalloc(int cch, const char *sbMessage)
1061 {
1062 char *sb;
1063
1064 if ((sb = (char *)malloc((unsigned)cch)) == NULL)
1065 ErrorExit(sbMessage);
1066 return(sb);
1067 }
1068
1069 /******
1070 ** Warning -- print a warning message preceded by the program name.
1071 ******/
1072
1073 void
1074 Warning(const char *sb1, const char *sb2)
1075 {
1076 (void)fprintf(stderr, "%s: warning: %s %s\n", sbProgName, sb1, sb2);
1077 }
1078
1079 /******
1080 ** ErrorExit -- print an error message preceded by the program name.
1081 ** Stdout is flushed and detex exits.
1082 ******/
1083
1084 void
1085 ErrorExit(const char *sb1)
1086 {
1087 (void)fflush(stdout);
1088 (void)fprintf(stderr, "%s: error: %s\n", sbProgName, sb1);
1089 exit(1);
1090 }
1091
1092 /******
1093 ** UsageExit -- print usage message and exit.
1094 ******/
1095
1096 void
1097 UsageExit(void)
1098 {
1099 (void)printf("\n%s [ -clnrstw1 ] [ -e environment-list ] [ filename[.tex] ... ]\n",
1100 sbProgName);
1101 puts("Strip (La)TeX commands from the input.\n\n \
1102 -c echo LaTeX \\cite, \\ref, and \\pageref values\n \
1103 -e <env-list> list of LaTeX environments to ignore\n \
1104 -l force latex mode\n \
1105 -n do not follow \\input, \\include and \\subfile\n \
1106 -r replace math with \"noun\" and \"noun verbs noun\" to preserve grammar\n \
1107 -s replace control sequences with space\n \
1108 -t force tex mode\n \
1109 -w word only output\n \
1110 -1 outputs the original file name and line number in the beginning of each line\n \
1111 -v show program version and exit\n\
1112 \n\
1113 opendetex home page: https://github.com/pkubowicz/opendetex");
1114 exit(0);
1115 }
1116
1117 /******
1118 ** VersionExit -- print version and exit.
1119 ******/
1120
1121 void
1122 VersionExit(void)
1123 {
1124 (void)printf("\nOpenDetex version %s\nhttps://github.com/pkubowicz/opendetex\n",
1125 VERSION);
1126 exit(0);
1127 }