Debian Codegraph @

texk/web2c/lib/texmfmp.c

raw
1 /* texmfmp.c: Hand-coded routines for TeX or Metafont in C. Originally
2 written by Tim Morgan, drawing from other Unix ports of TeX. This is
3 a collection of miscellany, everything that's easier (or only
4 possible) to do in C.
5
6 This file is public domain. */
7
8 /* This file is included from, e.g., texextra.c after
9 #define EXTERN
10 #include <texd.h>
11 to instantiate data from texd.h here. The ?d.h file is what
12 #defines TeX or MF, which avoids the need for a special
13 Makefile rule. */
14
15 #include <kpathsea/config.h>
16 #include <kpathsea/c-ctype.h>
17 #include <kpathsea/cnf.h>
18 #include <kpathsea/line.h>
19 #include <kpathsea/readable.h>
20 #include <kpathsea/variable.h>
21 #include <kpathsea/absolute.h>
22 #ifdef WIN32
23 #include <kpathsea/concatn.h>
24 #endif
25
26 #if defined (HAVE_SYS_TIME_H)
27 #include <sys/time.h>
28 #elif defined (HAVE_SYS_TIMEB_H)
29 #include <sys/timeb.h>
30 #endif
31 #include <time.h> /* For `struct tm'. Moved here for Visual Studio 2005. */
32
33 #if defined(__STDC__)
34 #include <locale.h>
35 #endif
36
37 #include <signal.h> /* Catch interrupts. */
38
39 #include <texmfmp-help.h>
40
41 /* {tex,mf}d.h defines TeX, MF, INI, and other such symbols.
42 Unfortunately there's no way to get the banner into this code, so
43 just repeat the text. */
44 /* We also define predicates, e.g., IS_eTeX for all e-TeX like engines, so
45 the rest of this file can remain unchanged when adding a new engine. */
46 #ifdef TeX
47 #if defined(XeTeX)
48 #define IS_eTeX 1
49 #include <xetexdir/xetexextra.h>
50 #elif defined (eTeX)
51 #define IS_eTeX 1
52 #include <etexdir/etexextra.h>
53 #elif defined (pdfTeX)
54 #define IS_eTeX 1
55 #include <pdftexdir/pdftexextra.h>
56 #include <pdftexdir/ptexlib.h>
57 #elif defined (Aleph)
58 #define IS_eTeX 1
59 #include <alephdir/alephextra.h>
60 #elif defined (pTeX)
61 #define IS_pTeX 1
62 #include <ptexdir/ptexextra.h>
63 #elif defined (epTeX)
64 #define IS_eTeX 1
65 #define IS_pTeX 1
66 #include <eptexdir/eptexextra.h>
67 #elif defined (upTeX)
68 #define IS_pTeX 1
69 #define IS_upTeX 1
70 #include <uptexdir/uptexextra.h>
71 #elif defined (eupTeX)
72 #define IS_eTeX 1
73 #define IS_pTeX 1
74 #define IS_upTeX 1
75 #include <euptexdir/euptexextra.h>
76 #else
77 #define BANNER "This is TeX, Version 3.141592653"
78 #define COPYRIGHT_HOLDER "D.E. Knuth"
79 #define AUTHOR NULL
80 #define PROGRAM_HELP TEXHELP
81 #define BUG_ADDRESS "[email protected]"
82 #define DUMP_VAR TEXformatdefault
83 #define DUMP_LENGTH_VAR formatdefaultlength
84 #define DUMP_OPTION "fmt"
85 #define DUMP_EXT ".fmt"
86 #define INPUT_FORMAT kpse_tex_format
87 #define INI_PROGRAM "initex"
88 #define VIR_PROGRAM "virtex"
89 #endif
90 #define edit_var "TEXEDIT"
91 #endif /* TeX */
92 #ifdef MF
93 #if defined(MFLua)
94 #include <mfluadir/mfluaextra.h>
95 #elif defined(MFLuaJIT)
96 #include <mfluajitdir/mfluajitextra.h>
97 #else
98 #define BANNER "This is Metafont, Version 2.71828182"
99 #define COPYRIGHT_HOLDER "D.E. Knuth"
100 #define AUTHOR NULL
101 #define PROGRAM_HELP MFHELP
102 #define BUG_ADDRESS "[email protected]"
103 #define DUMP_VAR MFbasedefault
104 #define DUMP_LENGTH_VAR basedefaultlength
105 #define DUMP_OPTION "base"
106 #ifdef DOS
107 #define DUMP_EXT ".bas"
108 #else
109 #define DUMP_EXT ".base"
110 #endif
111 #define INPUT_FORMAT kpse_mf_format
112 #define INI_PROGRAM "inimf"
113 #define VIR_PROGRAM "virmf"
114 #endif
115 #define edit_var "MFEDIT"
116 #endif /* MF */
117
118 #if !defined(IS_eTeX)
119 # define IS_eTeX 0
120 #endif
121 #if !defined(IS_pTeX)
122 # define IS_pTeX 0
123 #endif
124 #if !defined(IS_upTeX)
125 # define IS_upTeX 0
126 #endif
127
128 #if defined(__SyncTeX__)
129 /*
130 SyncTeX file name should be full path in the case where
131 --output-directory option is given.
132 Borrowed from LuaTeX.
133 */
134 #if defined(_WIN32)
135 #if defined(pdfTeX) || defined(upTeX) || defined(eupTeX) || defined(XeTeX)
136 #define W32USYNCTEX 1
137 #endif
138 #endif
139
140 char *
141 generic_synctex_get_current_name (void)
142 {
143 char *pwdbuf, *ret;
144 #if defined(W32USYNCTEX)
145 wchar_t *wpwd;
146 #endif /* W32USYNCTEX */
147 if (!fullnameoffile) {
148 ret = xstrdup("");
149 return ret;
150 }
151 if (kpse_absolute_p(fullnameoffile, false)) {
152 return xstrdup(fullnameoffile);
153 }
154 pwdbuf = xgetcwd();
155 #if defined(W32USYNCTEX)
156 if (file_system_codepage != 0 && file_system_codepage != win32_codepage) {
157 wpwd = get_wstring_from_mbstring(win32_codepage, pwdbuf, wpwd=NULL);
158 free (pwdbuf);
159 pwdbuf = get_mbstring_from_wstring(file_system_codepage, wpwd, pwdbuf=NULL);
160 free (wpwd);
161 }
162 #endif /* W32USYNCTEX */
163 ret = concat3(pwdbuf, DIR_SEP_STRING, fullnameoffile);
164 free(pwdbuf) ;
165 return ret;
166 }
167 #endif
168
169 #ifdef _WIN32
170 #if !IS_pTeX
171 FILE *Poptr;
172 #endif
173 #undef fopen
174 #undef xfopen
175 #define fopen fsyscp_fopen
176 #define xfopen fsyscp_xfopen
177 #undef stat
178 #define stat _stat
179 #include <wchar.h>
180 int
181 fsyscp_stat(const char *path, struct stat *buffer)
182 {
183 wchar_t *wpath;
184 int ret;
185 wpath = get_wstring_from_mbstring(file_system_codepage,
186 path, wpath = NULL);
187 if (wpath == NULL)
188 return -1;
189 ret = _wstat(wpath, buffer);
190 free(wpath);
191 return ret;
192 }
193 #include <sys/stat.h>
194 int
195 fsyscp_dir_p(char *path)
196 {
197 struct stat stats;
198 int ret;
199
200 ret = fsyscp_stat(path, &stats) == 0 && S_ISDIR (stats.st_mode);
201 return ret;
202 }
203 int
204 fsyscp_access(const char *path, int mode)
205 {
206 wchar_t *wpath;
207 int ret;
208 wpath = get_wstring_from_mbstring(file_system_codepage,
209 path, wpath = NULL);
210 if (wpath == NULL)
211 return -1;
212 ret = _waccess(wpath, mode);
213 free(wpath);
214 return ret;
215 }
216 #endif /* _WIN32 */
217
218 #if defined(TeX) || (defined(MF) && defined(WIN32))
219 static int
220 Isspace (char c)
221 {
222 return (c == ' ' || c == '\t');
223 }
224 #endif /* TeX || (MF && WIN32) */
225
226 #ifdef TeX
227
228 /* Shell escape.
229
230 If shellenabledp == 0, all shell escapes are forbidden.
231 If (shellenabledp == 1 && restrictedshell == 0), any command
232 is allowed for a shell escape.
233 If (shellenabledp == 1 && restrictedshell == 1), only commands
234 given in the configuration file as
235 shell_escape_commands = kpsewhich,ebb,extractbb,mpost,metafun,...
236 (no spaces between commands) in texmf.cnf are allowed for a shell
237 escape in a restricted form: command name and arguments should be
238 separated by a white space. The first word should be a command
239 name. The quotation character for an argument with spaces,
240 including a pathname, should be ". ' should not be used.
241
242 Internally, all arguments are quoted by ' (Unix) or " (Windows)
243 before calling the system() function in order to forbid execution
244 of any embedded command.
245
246 If the --shell-escape option is given, we set
247 shellenabledp = 1 and restrictedshell = 0, i.e., any command is allowed.
248 If the --shell-restricted option is given, we set
249 shellenabledp = 1 and restrictedshell = 1, i.e., only given cmds allowed.
250 If the --no-shell-escape option is given, we set
251 shellenabledp = -1 (and restrictedshell is irrelevant).
252 If none of these option are given, there are three cases:
253 (1) In the case where
254 shell_escape = y or
255 shell_escape = t or
256 shell_escape = 1
257 it becomes shellenabledp = 1 and restrictedshell = 0,
258 that is, any command is allowed.
259 (2) In the case where
260 shell_escape = p
261 it becomes shellenabledp = 1 and restrictedshell = 1,
262 that is, restricted shell escape is allowed.
263 (3) In all other cases, shellenabledp = 0, that is, shell
264 escape is forbidden. The value of restrictedshell is
265 irrelevant if shellenabledp == 0.
266 */
267
268 /* cmdlist is a list of allowed commands which are given like this:
269 shell_escape_commands = kpsewhich,ebb,extractbb,mpost,metafun
270 in texmf.cnf. */
271
272 static char **cmdlist = NULL;
273
274 static void
275 mk_shellcmdlist (char *v)
276 {
277 char **p;
278 char *q, *r;
279 size_t n;
280
281 q = v;
282 n = 1;
283
284 /* analyze the variable shell_escape_commands = foo,bar,...
285 spaces before and after (,) are not allowed. */
286
287 while ((r = strchr (q, ',')) != 0) {
288 n++;
289 q = r + 1;
290 }
291 if (*q)
292 n++;
293 cmdlist = xmalloc (n * sizeof (char *));
294 p = cmdlist;
295 q = v;
296 while ((r = strchr (q, ',')) != 0) {
297 *r = '\0';
298 *p++ = xstrdup (q);
299 q = r + 1;
300 }
301 if (*q)
302 *p++ = xstrdup (q);
303 *p = NULL;
304 }
305
306 static void
307 init_shell_escape (void)
308 {
309 if (shellenabledp < 0) { /* --no-shell-escape on cmd line */
310 shellenabledp = 0;
311
312 } else {
313 if (shellenabledp == 0) { /* no shell options on cmd line, check cnf */
314 char *v1 = kpse_var_value ("shell_escape");
315 if (v1) {
316 if (*v1 == 't' || *v1 == 'y' || *v1 == '1') {
317 shellenabledp = 1;
318 } else if (*v1 == 'p') {
319 shellenabledp = 1;
320 restrictedshell = 1;
321 }
322 free (v1);
323 }
324 }
325
326 /* If shell escapes are restricted, get allowed cmds from cnf. */
327 if (shellenabledp && restrictedshell == 1) {
328 char *v2 = kpse_var_value ("shell_escape_commands");
329 if (v2) {
330 mk_shellcmdlist (v2);
331 free (v2);
332 }
333 }
334 }
335 }
336
337 #ifdef WIN32
338 #define QUOTE '"'
339 #else
340 #define QUOTE '\''
341 #endif
342
343 #if 0
344 #ifdef WIN32
345 static int
346 char_needs_quote (int c)
347 {
348 /* special characters of cmd.exe */
349
350 return (c == '&' || c == '|' || c == '%' || c == '<' ||
351 c == '>' || c == ';' || c == ',' || c == '(' ||
352 c == ')');
353 }
354 #endif
355 #endif
356
357 /* return values:
358 -1 : invalid quotation of an argument
359 0 : command is not allowed
360 2 : restricted shell escape, CMD is allowed.
361
362 We set *SAFECMD to a safely-quoted version of *CMD; this is what
363 should get executed. And we set CMDNAME to its first word; this is
364 what is checked against the shell_escape_commands list. */
365
366 static int
367 shell_cmd_is_allowed (const char *cmd, char **safecmd, char **cmdname)
368 {
369 char **p;
370 char *buf;
371 char *c, *d;
372 const char *s;
373 int pre, spaces;
374 int allow = 0;
375
376 /* pre == 1 means that the previous character is a white space
377 pre == 0 means that the previous character is not a white space */
378 buf = xmalloc (strlen (cmd) + 1);
379 strcpy (buf, cmd);
380 c = buf;
381 while (Isspace (*c))
382 c++;
383 d = c;
384 while (!Isspace(*d) && *d)
385 d++;
386 *d = '\0';
387
388 /* *cmdname is the first word of the command line. For example,
389 *cmdname == "kpsewhich" for
390 \write18{kpsewhich --progname=dvipdfm --format="other text files" config}
391 */
392 *cmdname = xstrdup (c);
393 free (buf);
394
395 /* Is *cmdname listed in a texmf.cnf vriable as
396 shell_escape_commands = foo,bar,... ? */
397 p = cmdlist;
398 if (p) {
399 while (*p) {
400 if (strcmp (*p, *cmdname) == 0) {
401 /* *cmdname is found in the list, so restricted shell escape
402 is allowed */
403 allow = 2;
404 break;
405 }
406 p++;
407 }
408 }
409 if (allow == 2) {
410 spaces = 0;
411 for (s = cmd; *s; s++) {
412 if (Isspace (*s))
413 spaces++;
414 }
415
416 /* allocate enough memory (too much?) */
417 #ifdef WIN32
418 *safecmd = xmalloc (2 * strlen (cmd) + 3 + 2 * spaces);
419 #else
420 *safecmd = xmalloc (strlen (cmd) + 3 + 2 * spaces);
421 #endif
422
423 /* make a safe command line *safecmd */
424 s = cmd;
425 while (Isspace (*s))
426 s++;
427 d = *safecmd;
428 while (!Isspace (*s) && *s)
429 *d++ = *s++;
430
431 pre = 1;
432 while (*s) {
433 /* Quotation given by a user. " should always be used; we
434 transform it below. If ' is used, simply immediately
435 return a quotation error. */
436 if (*s == '\'') {
437 return -1;
438 }
439
440 if (*s == '"') {
441 /* All arguments are quoted as 'foo' (Unix) or "foo" (Windows)
442 before calling system(). Therefore closing QUOTE is necessary
443 if the previous character is not a white space.
444 example:
445 --format="other text files" becomes
446 '--format=''other text files' (Unix)
447 "--format"="other text files" (Windows) */
448
449 if (pre == 0) {
450 #ifdef WIN32
451 if (*(s-1) == '=') {
452 *(d-1) = QUOTE;
453 *d++ = '=';
454 } else {
455 *d++ = QUOTE;
456 }
457 #else
458 *d++ = QUOTE;
459 #endif
460 }
461 pre = 0;
462 /* output the quotation mark for the quoted argument */
463 *d++ = QUOTE;
464 s++;
465
466 while (*s != '"') {
467 /* Illegal use of ', or closing quotation mark is missing */
468 if (*s == '\'' || *s == '\0')
469 return -1;
470 #if 0
471 /*
472 The following in WIN32 may not be necessary, because
473 all arguments are quoted.
474 */
475 #ifdef WIN32
476 if (char_needs_quote (*s))
477 *d++ = '^';
478 #endif
479 #endif
480 *d++ = *s++;
481 }
482
483 /* Closing quotation mark will be output afterwards, so
484 we do nothing here */
485 s++;
486
487 /* The character after the closing quotation mark
488 should be a white space or NULL */
489 if (!Isspace (*s) && *s)
490 return -1;
491
492 /* Beginning of a usual argument */
493 } else if (pre == 1 && !Isspace (*s)) {
494 pre = 0;
495 *d++ = QUOTE;
496 #if 0
497 /*
498 The following in WIN32 may not be necessary, because
499 all arguments are quoted.
500 */
501 #ifdef WIN32
502 if (char_needs_quote (*s))
503 *d++ = '^';
504 #endif
505 #endif
506 *d++ = *s++;
507 /* Ending of a usual argument */
508
509 } else if (pre == 0 && Isspace (*s)) {
510 pre = 1;
511 /* Closing quotation mark */
512 *d++ = QUOTE;
513 *d++ = *s++;
514 } else {
515 /* Copy a character from cmd to *safecmd. */
516 #if 0
517 /*
518 The following in WIN32 may not be necessary, because
519 all arguments are quoted.
520 */
521 #ifdef WIN32
522 if (char_needs_quote (*s))
523 *d++ = '^';
524 #endif
525 #endif
526 *d++ = *s++;
527 }
528 }
529 /* End of the command line */
530 if (pre == 0) {
531 *d++ = QUOTE;
532 }
533 *d = '\0';
534 #if 0
535 #ifdef WIN32
536 {
537 char *p, *q, *r;
538 p = *safecmd;
539 if (strlen (p) > 2 && p[1] == ':' && !IS_DIR_SEP (p[2])) {
540 q = xmalloc (strlen (p) + 2);
541 q[0] = p[0];
542 q[1] = p[1];
543 q[2] = '/';
544 q[3] = '\0';
545 strcat (q, (p + 2));
546 free (*safecmd);
547 *safecmd = q;
548 } else if (!IS_DIR_SEP (p[0]) && !(p[1] == ':' && IS_DIR_SEP (p[2]))) {
549 p = kpse_var_value ("SELFAUTOLOC");
550 if (p) {
551 r = *safecmd;
552 while (*r && !Isspace(*r))
553 r++;
554 if (*r == '\0')
555 q = concatn ("\"", p, "/", *safecmd, "\"", NULL);
556 else {
557 *r = '\0';
558 r++;
559 while (*r && Isspace(*r))
560 r++;
561 if (*r)
562 q = concatn ("\"", p, "/", *safecmd, "\" ", r, NULL);
563 else
564 q = concatn ("\"", p, "/", *safecmd, "\"", NULL);
565 }
566 free (p);
567 free (*safecmd);
568 *safecmd = q;
569 }
570 }
571 }
572 #endif
573 #endif
574 }
575
576 return allow;
577 }
578
579 /* We should only be called with shellenabledp == 1.
580 Return value:
581 -1 if a quotation syntax error.
582 0 if CMD is not allowed; given shellenabledp==1, this is because
583 shell escapes are restricted and CMD is not allowed.
584 1 if shell escapes are not restricted, hence any command is allowed.
585 2 if shell escapes are restricted and CMD is allowed (possibly after
586 quoting). */
587
588 #ifdef WIN32
589 #undef system
590 #define system fsyscp_system
591 #if ENABLE_PIPES
592 #undef popen
593 #define popen fsyscp_popen
594 #endif /* ENABLE_PIPES */
595 #endif /* WIN32 */
596
597 int
598 runsystem (const char *cmd)
599 {
600 int allow = 0;
601 char *safecmd = NULL;
602 char *cmdname = NULL;
603 #if IS_pTeX && !defined(WIN32)
604 char *cmd2 = NULL;
605 #endif
606 int status = 0;
607 #if IS_pTeX && !defined(WIN32)
608 cmd2 = (char *)ptenc_from_internal_enc_string_to_utf8((unsigned char *)cmd);
609 if (!cmd2) cmd2=(char *)cmd;
610 #endif
611
612 if (shellenabledp <= 0) {
613 return 0;
614 }
615
616 /* If restrictedshell == 0, any command is allowed. */
617 if (restrictedshell == 0)
618 allow = 1;
619 else
620 #if IS_pTeX && !defined(WIN32)
621 allow = shell_cmd_is_allowed (cmd2, &safecmd, &cmdname);
622 #else
623 allow = shell_cmd_is_allowed (cmd, &safecmd, &cmdname);
624 #endif
625
626 if (allow == 1)
627 #if IS_pTeX && !defined(WIN32)
628 status = system (cmd2);
629 #else
630 status = system (cmd);
631 #endif
632 else if (allow == 2) {
633 /*
634 command including a character '|' is not allowed in
635 restricted mode for security.
636 */
637 size_t k;
638 for (k = 0; k < strlen (safecmd); k++) {
639 if (safecmd[k] == '|')
640 return 0;
641 }
642 status = system (safecmd);
643 }
644
645 /* Not really meaningful, but we have to manage the return value of system. */
646 if (status != 0)
647 fprintf(stderr,"system returned with code %d\n", status);
648
649 #if IS_pTeX && !defined(WIN32)
650 if (cmd!=cmd2) free(cmd2);
651 #endif
652 if (safecmd)
653 free (safecmd);
654 if (cmdname)
655 free (cmdname);
656
657 return allow;
658 }
659 #endif /* TeX */
660
661 #if ENABLE_PIPES
662 /* Like runsystem(), the runpopen() function is called only when
663 shellenabledp == 1. Unlike runsystem(), here we write errors to
664 stderr, since we have nowhere better to use; and of course we return
665 a file handle (or NULL) instead of a status indicator. */
666
667 static FILE *
668 runpopen (char *cmd, const char *mode)
669 {
670 FILE *f = NULL;
671 char *safecmd = NULL;
672 char *cmdname = NULL;
673 int allow;
674 #if IS_pTeX && !defined(WIN32)
675 char *cmd2 = NULL;
676 #endif
677
678 #ifdef WIN32
679 char *pp;
680
681 for (pp = cmd; *pp; pp++) {
682 if (*pp == '\'') *pp = '"';
683 }
684 #endif
685
686 #if IS_pTeX && !defined(WIN32)
687 cmd2 = (char *)ptenc_from_internal_enc_string_to_utf8((unsigned char *)cmd);
688 if (!cmd2) cmd2=(char *)cmd;
689 #endif
690
691 /* If restrictedshell == 0, any command is allowed. */
692 if (restrictedshell == 0)
693 allow = 1;
694 else
695 #if IS_pTeX && !defined(WIN32)
696 allow = shell_cmd_is_allowed (cmd2, &safecmd, &cmdname);
697 #else
698 allow = shell_cmd_is_allowed (cmd, &safecmd, &cmdname);
699 #endif
700
701 if (allow == 1)
702 #if IS_pTeX && !defined(WIN32)
703 f = popen (cmd2, mode);
704 #else
705 f = popen (cmd, mode);
706 #endif
707 else if (allow == 2)
708 f = popen (safecmd, mode);
709 else if (allow == -1)
710 fprintf (stderr, "\nrunpopen quotation error in command line: %s\n",
711 cmd);
712 else
713 fprintf (stderr, "\nrunpopen command not allowed: %s\n", cmdname);
714
715 #if IS_pTeX && !defined(WIN32)
716 if (cmd!=cmd2) free(cmd2);
717 #endif
718 if (safecmd)
719 free (safecmd);
720 if (cmdname)
721 free (cmdname);
722 return f;
723 }
724 #endif /* ENABLE_PIPES */
725
726 /* The main program, etc. */
727
728 #ifdef XeTeX
729 #include "xetexdir/XeTeX_ext.h"
730 #endif
731
732 /* What we were invoked as and with. */
733 char **argv;
734 int argc;
735
736 /* If the user overrides argv[0] with -progname. */
737 static const_string user_progname;
738
739 /* Array and count of values given with --config-line. */
740 static string *user_cnf_lines = NULL;
741 static unsigned user_cnf_nlines = 0;
742
743 /* The C version of the jobname, if given. */
744 static const_string c_job_name;
745
746 /* The filename for dynamic character translation, or NULL. */
747 string translate_filename;
748 string default_translate_filename;
749
750 #if defined(TeX)
751 /* Needed for --src-specials option. */
752 static char *last_source_name;
753 static int last_lineno;
754 static boolean srcspecialsoption = false;
755 static void parse_src_specials_option (const_string);
756 #endif
757
758 /* Parsing a first %&-line in the input file. */
759 static void parse_first_line (const_string);
760
761 /* Parse option flags. */
762 static void parse_options (int, string *);
763
764 /* Try to figure out if we have been given a filename. */
765 static string get_input_file_name (void);
766
767 /* Get a true/false value for a variable from texmf.cnf and the
768 environment. Not static because we call it from tex.ch. */
769
770 boolean
771 texmf_yesno(const_string var)
772 {
773 string value = kpse_var_value (var);
774 return value && (*value == 't' || *value == 'y' || *value == '1');
775 }
776
777 #ifdef pdfTeX
778 const char *ptexbanner = BANNER;
779 #endif
780
781 #ifdef WIN32
782 /* forward declaration */
783 static string
784 normalize_quotes (const_string name, const_string mesg);
785 #endif /* WIN32 */
786
787 /* maininit, called from main() - this is most of the main routine,
788 including our C-level option handling and concomitant kpse setup.
789 The original TeX/MF code for handling first lines is still live, and
790 we set up for that in `topenin' (which is called from the .web). */
791
792 void
793 maininit (int ac, string *av)
794 {
795 string main_input_file;
796 #if (IS_upTeX || defined(XeTeX) || defined(pdfTeX)) && defined(WIN32)
797 string enc;
798 #endif
799 /* Save to pass along to topenin. */
800 argc = ac;
801 argv = av;
802
803 /* Must be initialized before options are parsed. */
804 interactionoption = 4;
805
806 /* Have things to record as we go along. */
807 kpse_record_input = recorder_record_input;
808 kpse_record_output = recorder_record_output;
809
810 #if defined(__SyncTeX__)
811 /* 0 means "disable Synchronize TeXnology".
812 synctexoption is a *.web variable.
813 We initialize it to a weird value to catch the -synctex command line flag.
814 At runtime, if synctexoption is not INT_MAX, then it contains the
815 command line option provided; otherwise, no such option was given
816 by the user. */
817 # define SYNCTEX_NO_OPTION INT_MAX
818 synctexoption = SYNCTEX_NO_OPTION;
819 #endif
820
821 #if IS_pTeX
822 kpse_set_program_name (argv[0], NULL);
823 initkanji (); ptenc_ptex_mode(true);
824 #endif
825 #if (defined(XeTeX) || defined(pdfTeX)) && defined(WIN32)
826 kpse_set_program_name (argv[0], NULL);
827 #endif
828 #if (IS_upTeX || defined(XeTeX) || defined(pdfTeX)) && defined(WIN32)
829 /*
830 -cnf-line=command_line_encoding=value cannot give effect because
831 command_line_encoding is read here before parsing the command
832 line. So we add the following.
833 */
834 { /* support old compilers which are incompatible with C99 */
835 int n;
836 for (n = 1; n < ac; n++) {
837 if (!strncasecmp (av[n], "-cnf-line=command_line_encoding=", 32)) {
838 putenv (av[n] + 10);
839 break;
840 }
841 if (!strncasecmp (av[n], "--cnf-line=command_line_encoding=", 33)) {
842 putenv (av[n] + 11);
843 break;
844 }
845 if (n < ac - 1 && (!strncasecmp (av[n], "-cnf-line", 9) ||
846 !strncasecmp (av[n], "--cnf-line", 10)) &&
847 !strncasecmp (av[n+1], "command_line_encoding=", 22)) {
848 putenv (av[n+1]);
849 break;
850 }
851 }
852 }
853 enc = kpse_var_value("command_line_encoding");
854 get_command_line_args_utf8(enc, &argc, &argv);
855 #endif
856
857 /* If the user says --help or --version, we need to notice early. And
858 since we want the --ini option, have to do it before getting into
859 the web (which would read the base file, etc.). */
860 #if ((IS_upTeX || defined(XeTeX) || defined(pdfTeX)) && defined(WIN32))
861 parse_options (argc, argv);
862 #else
863 parse_options (ac, av);
864 #endif
865
866 #if IS_pTeX || ((defined(XeTeX) || defined(pdfTeX)) && defined(WIN32))
867 /* In pTeX and friends, or in WIN32, texmf.cnf is not recorded in
868 the case of --recorder, because parse_options() is executed
869 after the start of kpathsea due to special initializations.
870 Therefore we record texmf.cnf here. */
871 if (recorder_enabled) {
872 string *p = kpse_find_file_generic ("texmf.cnf", kpse_cnf_format, 0, 1);
873 if (p && *p) {
874 string *pp = p;
875 while (*p) {
876 recorder_record_input (*p);
877 free (*p);
878 p++;
879 }
880 free (pp);
881 }
882 }
883 #endif /* IS_pTeX || (...) */
884
885 /* If -progname was not specified, default to the dump name. */
886 if (!user_progname)
887 user_progname = dump_name;
888
889 /* Do this early so we can inspect kpse_invocation_name and
890 kpse_program_name below, and because we have to do this before
891 any path searching. */
892 #if IS_pTeX || ((defined(XeTeX) || defined(pdfTeX)) && defined(WIN32))
893 if (user_progname)
894 kpse_reset_program_name (user_progname);
895 #else
896 kpse_set_program_name (argv[0], user_progname);
897 #endif
898
899 #if defined(MF)
900 #if defined(MFLua)
901 /* Reset mf*-nowin program names. */
902 if (strncasecmp (kpse_invocation_name, "mflua-nowin", 11) == 0)
903 kpse_reset_program_name ("mflua");
904 #elif defined(MFLuaJIT)
905 if (strncasecmp (kpse_invocation_name, "mfluajit-nowin", 14) == 0)
906 kpse_reset_program_name ("mfluajit");
907 #else
908 if (strncasecmp (kpse_invocation_name, "mf-nowin", 8) == 0)
909 kpse_reset_program_name ("mf");
910 #endif
911 #endif
912
913 /* Make the given engine name available in the variable `engine'. */
914 xputenv ("engine", TEXMFENGINENAME);
915
916 if (user_cnf_lines) {
917 unsigned i;
918 for (i = 0; i < user_cnf_nlines; i++) {
919 /* debug printf ("ucnf%d: %s\n", i, user_cnf_lines[i]); */
920 kpathsea_cnf_line_env_progname (kpse_def, user_cnf_lines[i]);
921 free (user_cnf_lines[i]);
922 }
923 }
924
925 /* Were we given a simple filename? */
926 main_input_file = get_input_file_name ();
927
928 #ifdef WIN32
929 if (main_input_file == NULL) {
930 string name;
931 #ifndef XeTeX
932 boolean quoted;
933 #endif
934
935 name = argv[argc-1];
936 if (name && name[0] != '-' && name[0] != '&' && name[0] != '\\') {
937 if (strlen (name) > 2 && isalpha (name[0]) && name[1] == ':' &&
938 name[2] == '\\') {
939 string pp;
940 for (pp = name; *pp; pp++) {
941 if (IS_KANJI (pp))
942 pp++;
943 else if (*pp == '\\')
944 *pp = '/';
945 }
946 }
947 name = normalize_quotes(argv[argc-1], "argument");
948 #ifdef XeTeX
949 main_input_file = kpse_find_file(argv[argc-1], INPUT_FORMAT, false);
950 argv[argc-1] = name;
951 #else
952 quoted = (name[0] == '"');
953 if (quoted) {
954 /* Overwrite last quote and skip first quote. */
955 name[strlen(name)-1] = '\0';
956 name++;
957 }
958 main_input_file = kpse_find_file(name, INPUT_FORMAT, false);
959 if (quoted) {
960 /* Undo modifications */
961 name[strlen(name)] = '"';
962 name--;
963 }
964 argv[argc-1] = name;
965 #endif
966 }
967 }
968 #endif /* WIN32 */
969
970 /* Second chance to activate file:line:error style messages, this
971 time from texmf.cnf. */
972 if (filelineerrorstylep < 0) {
973 filelineerrorstylep = 0;
974 } else if (!filelineerrorstylep) {
975 filelineerrorstylep = texmf_yesno ("file_line_error_style");
976 }
977
978 /* If no dump default yet, and we're not doing anything special on
979 this run, we may want to look at the first line of the main input
980 file for a %&<dumpname> specifier. */
981 if (parsefirstlinep < 0) {
982 parsefirstlinep = 0;
983 } else if (!parsefirstlinep) {
984 parsefirstlinep = texmf_yesno ("parse_first_line");
985 }
986 if (parsefirstlinep && (!dump_name || !translate_filename)) {
987 parse_first_line (main_input_file);
988 }
989 /* Check whether there still is no translate_filename known. If so,
990 use the default_translate_filename. */
991 if (!translate_filename) {
992 translate_filename = default_translate_filename;
993 }
994 /* If we're preloaded, I guess everything is set up. I don't really
995 know any more, it's been so long since anyone truly preloaded. We
996 still use the word "preloaded" in the messages, though (via the
997 original .web sources), at Knuth's request. */
998 if (readyalready != 314159) {
999 /* The `ini_version' variable is declared/used in the change files. */
1000 boolean virversion = false;
1001 if (FILESTRCASEEQ (kpse_program_name, INI_PROGRAM)) {
1002 iniversion = true;
1003 } else if (FILESTRCASEEQ (kpse_program_name, VIR_PROGRAM)) {
1004 virversion = true;
1005 #ifdef TeX
1006 } else if (FILESTRCASEEQ (kpse_program_name, "initex")) {
1007 iniversion = true;
1008 } else if (FILESTRCASEEQ (kpse_program_name, "virtex")) {
1009 virversion = true;
1010 #ifndef Aleph
1011 } else if (FILESTRCASEEQ (kpse_program_name, "mltex")) {
1012 mltexp = true;
1013 #endif /* !Aleph */
1014 #endif /* TeX */
1015 }
1016
1017 /* If run like `tex \&foo', reasonable to guess "foo" as the fmt name. */
1018 if (!main_input_file) {
1019 if (argv[1] && *argv[1] == '&') {
1020 #if IS_pTeX && !defined(WIN32)
1021 string new_arg;
1022 is_terminalUTF8(); /* To call get_terminal_enc(). return value is not used */
1023 new_arg = ptenc_from_utf8_string_to_internal_enc(argv[1]);
1024 dump_name = argv[1] + 1;
1025 if (new_arg) argv[1] = new_arg;
1026 #else
1027 dump_name = argv[1] + 1;
1028 #endif
1029 }
1030 }
1031
1032 if (!dump_name) {
1033 /* If called as *vir{mf,tex,mpost} use `plain'. Otherwise, use the
1034 name we were invoked under as our best guess. */
1035 dump_name = (virversion ? "plain" : kpse_program_name);
1036 }
1037 }
1038
1039 #ifdef TeX
1040 /* Sanity check: -mltex, -enc, -etex only work in combination with -ini. */
1041 if (!iniversion) {
1042 #if !defined(Aleph)
1043 if (mltexp) {
1044 fprintf(stderr, "-mltex only works with -ini\n");
1045 }
1046 #if !defined(XeTeX) && !IS_pTeX
1047 if (enctexp) {
1048 fprintf(stderr, "-enc only works with -ini\n");
1049 }
1050 #endif
1051 #endif
1052 #if IS_eTeX
1053 if (etexp) {
1054 fprintf(stderr, "-etex only works with -ini\n");
1055 }
1056 #endif
1057 }
1058 #endif
1059
1060 /* If we've set up the fmt/base default in any of the various ways
1061 above, also set its length. */
1062 if (dump_name) {
1063 const_string with_ext = NULL;
1064 unsigned name_len = strlen (dump_name);
1065 unsigned ext_len = strlen (DUMP_EXT);
1066
1067 /* Provide extension if not there already. */
1068 #if IS_pTeX && !defined(WIN32)
1069 string new_dump_name;
1070 is_terminalUTF8(); /* To call get_terminal_enc(). return value is not used */
1071 new_dump_name = ptenc_from_utf8_string_to_internal_enc(dump_name);
1072 if (!new_dump_name) new_dump_name = (string)dump_name;
1073 if (name_len > ext_len
1074 && FILESTRCASEEQ (dump_name + name_len - ext_len, DUMP_EXT)) {
1075 with_ext = new_dump_name;
1076 } else {
1077 with_ext = concat(new_dump_name, DUMP_EXT);
1078 }
1079 #else
1080 if (name_len > ext_len
1081 && FILESTRCASEEQ (dump_name + name_len - ext_len, DUMP_EXT)) {
1082 with_ext = dump_name;
1083 } else {
1084 with_ext = concat (dump_name, DUMP_EXT);
1085 }
1086 #endif
1087 DUMP_VAR = concat (" ", with_ext); /* adjust array for Pascal */
1088 DUMP_LENGTH_VAR = strlen (DUMP_VAR + 1);
1089 } else {
1090 /* For dump_name to be NULL is a bug. */
1091 abort();
1092 }
1093
1094 /* Additional initializations. No particular reason for doing them
1095 here instead of first thing in the change file; less symbols to
1096 propagate through Webc, that's all. */
1097 #ifdef MF
1098 kpse_set_program_enabled (kpse_mf_format, MAKE_TEX_MF_BY_DEFAULT,
1099 kpse_src_compile);
1100 kpse_set_program_enabled (kpse_base_format, MAKE_TEX_FMT_BY_DEFAULT,
1101 kpse_src_compile);
1102 #endif /* MF */
1103 #ifdef TeX
1104 #if defined (Aleph)
1105 kpse_set_program_enabled (kpse_ocp_format, MAKE_OMEGA_OCP_BY_DEFAULT,
1106 kpse_src_compile);
1107 kpse_set_program_enabled (kpse_ofm_format, MAKE_OMEGA_OFM_BY_DEFAULT,
1108 kpse_src_compile);
1109 kpse_set_program_enabled (kpse_tfm_format, false, kpse_src_compile);
1110 #else /* !Aleph */
1111 kpse_set_program_enabled (kpse_tfm_format, MAKE_TEX_TFM_BY_DEFAULT,
1112 kpse_src_compile);
1113 #if (IS_upTeX)
1114 kpse_set_program_enabled (kpse_ofm_format, false, kpse_src_compile);
1115 #endif
1116 #endif /* !Aleph */
1117 kpse_set_program_enabled (kpse_tex_format, MAKE_TEX_TEX_BY_DEFAULT,
1118 kpse_src_compile);
1119 kpse_set_program_enabled (kpse_fmt_format, MAKE_TEX_FMT_BY_DEFAULT,
1120 kpse_src_compile);
1121
1122 init_shell_escape ();
1123
1124 if (!outputcomment) {
1125 outputcomment = kpse_var_value ("output_comment");
1126 }
1127 #endif /* TeX */
1128 }
1129
1130 #if defined(_MSC_VER) && _MSC_VER > 1600
1131 #include <crtdbg.h>
1132 void
1133 myInvalidParameterHandler(const wchar_t* expression,
1134 const wchar_t* function,
1135 const wchar_t* file,
1136 unsigned int line,
1137 uintptr_t pReserved)
1138 {
1139 /* After updating a compiler from Visual Studio 2010 to
1140 Visual Studio 2015, XeTeX exits with the code 0xc0000417,
1141 that means "invalid paremeter in CRT detected".
1142 Probably it is safe to ignore the error.
1143 So I use a handler which smiply return.
1144 */
1145 return;
1146 }
1147 #endif /* defined(_MSC_VER) ... */
1148
1149 /* main: Set up for reading the command line, which will happen in
1150 `maininit' and `topenin', then call the main body, plus
1151 special Windows/Kanji initializations. */
1152
1153 int
1154 #if defined(DLLPROC)
1155 DLLPROC (int ac, string *av)
1156 #else
1157 main (int ac, string *av)
1158 #endif
1159 {
1160 #ifdef __EMX__
1161 _wildcard (&ac, &av);
1162 _response (&ac, &av);
1163 #endif
1164
1165 #if defined(_MSC_VER) && _MSC_VER > 1600
1166 _invalid_parameter_handler oldHandler, newHandler;
1167 newHandler = myInvalidParameterHandler;
1168 oldHandler = _set_invalid_parameter_handler(newHandler);
1169 _CrtSetReportMode(_CRT_ASSERT, 0);
1170 #endif /* defined(_MSC_VER) ... */
1171
1172 #ifdef WIN32
1173 av[0] = kpse_program_basename (av[0]);
1174 _setmaxstdio(2048);
1175 setmode(fileno(stdin), _O_BINARY);
1176 if (ac > 1) {
1177 char *pp;
1178 if ((strlen(av[ac-1]) > 2) &&
1179 isalpha(av[ac-1][0]) &&
1180 (av[ac-1][1] == ':') &&
1181 (av[ac-1][2] == '\\')) {
1182 for (pp=av[ac-1]+2; *pp; pp++) {
1183 if (IS_KANJI(pp)) {
1184 pp++;
1185 continue;
1186 }
1187 if (*pp == '\\')
1188 *pp = '/';
1189 }
1190 }
1191 }
1192 #endif
1193
1194 maininit (ac, av);
1195
1196 /* Call the real main program. */
1197 mainbody ();
1198
1199 return EXIT_SUCCESS;
1200 }
1201
1202 /* This is supposed to ``open the terminal for input'', but what we
1203 really do is copy command line arguments into TeX's or Metafont's
1204 buffer, so they can handle them. If nothing is available, or we've
1205 been called already (and hence, argc==0), we return with
1206 `last=first'. */
1207
1208 void
1209 topenin (void)
1210 {
1211 int i;
1212
1213 #ifdef XeTeX
1214 static UFILE termin_file;
1215 if (termin == 0) {
1216 termin = &termin_file;
1217 termin->f = stdin;
1218 termin->savedChar = -1;
1219 termin->skipNextLF = 0;
1220 termin->encodingMode = UTF8;
1221 termin->conversionData = 0;
1222 inputfile[0] = termin;
1223 }
1224 #endif
1225
1226 buffer[first] = 0; /* In case there are no arguments. */
1227
1228 if (optind < argc) { /* We have command line arguments. */
1229 int k = first;
1230 for (i = optind; i < argc; i++) {
1231 #ifdef XeTeX
1232 unsigned char *ptr = (unsigned char *)&(argv[i][0]);
1233 /* need to interpret UTF8 from the command line */
1234 UInt32 rval;
1235 while ((rval = *(ptr++)) != 0) {
1236 UInt16 extraBytes = bytesFromUTF8[rval];
1237 switch (extraBytes) { /* note: code falls through cases! */
1238 case 5: rval <<= 6; if (*ptr) rval += *(ptr++);
1239 case 4: rval <<= 6; if (*ptr) rval += *(ptr++);
1240 case 3: rval <<= 6; if (*ptr) rval += *(ptr++);
1241 case 2: rval <<= 6; if (*ptr) rval += *(ptr++);
1242 case 1: rval <<= 6; if (*ptr) rval += *(ptr++);
1243 case 0: ;
1244 };
1245 rval -= offsetsFromUTF8[extraBytes];
1246 buffer[k++] = rval;
1247 }
1248 #else
1249 char *ptr = &(argv[i][0]);
1250 /* Don't use strcat, since in Aleph the buffer elements aren't
1251 single bytes. */
1252 while (*ptr) {
1253 buffer[k++] = *(ptr++);
1254 }
1255 #endif
1256 buffer[k++] = ' ';
1257 }
1258 argc = 0; /* Don't do this again. */
1259 buffer[k] = 0;
1260 }
1261
1262 /* Find the end of the buffer. */
1263 for (last = first; buffer[last]; ++last)
1264 ;
1265
1266 /* Make `last' be one past the last non-space character in `buffer',
1267 ignoring line terminators (but not, e.g., tabs). This is because
1268 we are supposed to treat this like a line of TeX input. Although
1269 there are pathological cases (SPC CR SPC CR) where this differs
1270 from input_line below, and from previous behavior of removing all
1271 whitespace, the simplicity of removing all trailing line terminators
1272 seems more in keeping with actual command line processing. */
1273 #define IS_SPC_OR_EOL(c) ((c) == ' ' || (c) == '\r' || (c) == '\n')
1274 for (--last; last >= first && IS_SPC_OR_EOL (buffer[last]); --last)
1275 ;
1276 last++;
1277
1278 /* One more time, this time converting to TeX's internal character
1279 representation. */
1280 #if !defined(Aleph) && !defined(XeTeX)
1281 for (i = first; i < last; i++)
1282 buffer[i] = xord[buffer[i]];
1283 #endif
1284 }
1285
1286 /* IPC for TeX. By Tom Rokicki for the NeXT; it makes TeX ship out the
1287 DVI file in a pipe to TeXView so that the output can be displayed
1288 incrementally. Shamim Mohamed adapted it for Web2c. */
1289 #if defined (TeX) && defined (IPC)
1290
1291 #ifdef WIN32
1292 #undef _WINSOCKAPI_
1293 #include <winsock2.h>
1294 #else
1295 #include <sys/socket.h>
1296 #include <fcntl.h>
1297 #ifndef O_NONBLOCK /* POSIX */
1298 #ifdef O_NDELAY /* BSD */
1299 #define O_NONBLOCK O_NDELAY
1300 #elif defined(O_FNDELAY) /* NeXT */
1301 #define O_NONBLOCK O_FNDELAY
1302 #else
1303 what the fcntl? cannot implement IPC without equivalent for O_NONBLOCK.
1304 #endif
1305 #endif /* no O_NONBLOCK */
1306 #endif /* !WIN32 */
1307
1308 #ifdef WIN32
1309 # define IPC_AF AF_INET
1310 # ifndef IPC_LOCAL_HOST
1311 # define IPC_LOCAL_HOST "127.0.0.1"
1312 # define FIXED_PORT (unsigned short)4242
1313 # endif
1314 #else
1315 # define IPC_AF AF_UNIX
1316 # ifndef IPC_PIPE_NAME /* $HOME is prepended to this. */
1317 # define IPC_PIPE_NAME "/.TeXview_Pipe"
1318 # endif
1319 #endif
1320 #ifndef IPC_SERVER_CMD /* Command to run to start the server. */
1321 # ifdef WIN32
1322 # define IPC_SERVER_CMD "texview.exe"
1323 # else
1324 # define IPC_SERVER_CMD "open `which TeXview`"
1325 # endif
1326 #endif
1327
1328 struct msg
1329 {
1330 int namelength; /* length of auxiliary data */
1331 int eof; /* new eof for dvi file */
1332 #if 0 /* see usage of struct msg below */
1333 char more_data[0]; /* where the rest of the stuff goes */
1334 #endif
1335 };
1336
1337 static struct sockaddr *ipc_addr;
1338 static int ipc_addr_len;
1339
1340 static int
1341 ipc_make_name (void)
1342 {
1343 if (ipc_addr_len == 0) {
1344 #ifdef WIN32
1345 unsigned long remote_addr = inet_addr(IPC_LOCAL_HOST);
1346 if (remote_addr != INADDR_NONE) {
1347 struct sockaddr_in *ipc_sin_addr = xmalloc (sizeof (struct sockaddr_in));
1348 ipc_sin_addr->sin_family = AF_INET;
1349 ipc_sin_addr->sin_addr.s_addr = remote_addr;
1350 ipc_sin_addr->sin_port = htons (FIXED_PORT);
1351 ipc_addr = ((struct sockaddr *) ipc_sin_addr);
1352 ipc_addr_len = sizeof(struct sockaddr_in);
1353 }
1354 #else
1355 string s = getenv ("HOME");
1356 if (s) {
1357 char *ipc_name;
1358 ipc_addr = xmalloc (strlen (s) + 40);
1359 ipc_addr->sa_family = 0;
1360 ipc_name = ipc_addr->sa_data;
1361 strcpy (ipc_name, s);
1362 strcat (ipc_name, IPC_PIPE_NAME);
1363 ipc_addr_len = strlen (ipc_name) + 3;
1364 }
1365 #endif
1366 }
1367 return ipc_addr_len;
1368 }
1369
1370 static int sock = -1;
1371
1372 #ifdef WIN32
1373 # define CLOSE_SOCKET(s) closesocket (s); WSACleanup ()
1374 #else
1375 # define CLOSE_SOCKET(s) close (s)
1376 #endif
1377
1378 static int
1379 ipc_is_open (void)
1380 {
1381 return sock != -1;
1382 }
1383
1384 static void
1385 ipc_open_out (void) {
1386 #ifdef WIN32
1387 struct WSAData wsaData;
1388 int nCode;
1389 unsigned long mode = 1;
1390 #endif
1391 #ifdef IPC_DEBUG
1392 fputs ("tex: Opening socket for IPC output ...\n", stderr);
1393 #endif
1394 if (sock != -1) {
1395 return;
1396 }
1397
1398 #ifdef WIN32
1399 if ((nCode = WSAStartup(MAKEWORD(1, 1), &wsaData)) != 0) {
1400 fprintf(stderr,"WSAStartup() returned error code %d.\n", nCode);
1401 return;
1402 }
1403 #endif
1404
1405 if (ipc_make_name () <= 0)
1406 return;
1407
1408 sock = socket (IPC_AF, SOCK_STREAM, 0);
1409 #ifdef IPC_DEBUG
1410 if(sock != -1)
1411 fprintf(stderr, "tex: Socket handle is %d\n", sock);
1412 else
1413 fprintf(stderr, "tex: Socket is invalid.\n");
1414 #endif
1415
1416 if (sock != -1) {
1417 if (connect (sock, ipc_addr, ipc_addr_len) != 0 ||
1418 #ifdef WIN32
1419 ioctlsocket (sock, FIONBIO, &mode) < 0
1420 #else
1421 fcntl (sock, F_SETFL, O_NONBLOCK) < 0
1422 #endif
1423 ) {
1424 CLOSE_SOCKET (sock);
1425 sock = -1;
1426 #ifdef IPC_DEBUG
1427 fputs ("tex: IPC socket cannot be connected.\n", stderr);
1428 fputs ("tex: Socket is closed.\n", stderr);
1429 #endif
1430 return;
1431 }
1432 #ifdef IPC_DEBUG
1433 fputs ("tex: Successfully opened IPC socket.\n", stderr);
1434 #endif
1435 }
1436 }
1437
1438 static void
1439 ipc_close_out (void)
1440 {
1441 #ifdef IPC_DEBUG
1442 fputs ("tex: Closing output socket ...\n", stderr);
1443 #endif
1444 if (ipc_is_open ()) {
1445 CLOSE_SOCKET (sock);
1446 sock = -1;
1447 }
1448 }
1449
1450 static void
1451 ipc_snd (int n, int is_eof, char *data)
1452 {
1453 struct
1454 {
1455 struct msg msg;
1456 char more_data[1024];
1457 } ourmsg;
1458
1459 if (!ipc_is_open ()) {
1460 return;
1461 }
1462
1463 #ifdef IPC_DEBUG
1464 fprintf(stderr, "%d\t%d\n", ourmsg.msg.namelength, ourmsg.msg.eof);
1465 fputs ("tex: Sending message to socket ...\n", stderr);
1466 #endif
1467 ourmsg.msg.namelength = n;
1468 ourmsg.msg.eof = is_eof;
1469 if (n) {
1470 strcpy (ourmsg.more_data, data);
1471 }
1472 n += sizeof (struct msg);
1473 #ifdef IPC_DEBUG
1474 fprintf(stderr, "%d\t%d\n", ourmsg.msg.namelength, ourmsg.msg.eof);
1475 fputs ("tex: Writing to socket...\n", stderr);
1476 #endif
1477 #if defined(WIN32)
1478 if (send (sock, (char *)&ourmsg, n, 0) != n) {
1479 #else
1480 if (write (sock, &ourmsg, n) != n) {
1481 #endif
1482 ipc_close_out ();
1483 }
1484 #ifdef IPC_DEBUG
1485 fputs ("tex: IPC message sent.\n", stderr);
1486 #endif
1487 }
1488
1489 /* This routine notifies the server if there is an eof, or the filename
1490 if a new DVI file is starting. This is the routine called by TeX.
1491 Aleph defines str_start(#) as str_start_ar[# - too_big_char], with
1492 too_big_char = biggest_char + 1 = 65536 (omstr.ch). */
1493
1494 void
1495 ipcpage (int is_eof)
1496 {
1497 static boolean begun = false;
1498 unsigned len = 0;
1499 string p = NULL;
1500
1501 if (!begun) {
1502 string name; /* Just the filename. */
1503 string cwd = xgetcwd ();
1504
1505 ipc_open_out ();
1506 #if !defined(Aleph)
1507 len = strstart[outputfilename + 1] - strstart[outputfilename];
1508 #else
1509 len = strstartar[outputfilename + 1 - 65536L] -
1510 strstartar[outputfilename - 65536L];
1511 #endif
1512 name = xmalloc (len + 1);
1513 #if !defined(Aleph) && !IS_pTeX
1514 strncpy (name, (string)&strpool[strstart[outputfilename]], len);
1515 #else
1516 {
1517 unsigned i;
1518 for (i=0; i<len; i++)
1519 #if IS_pTeX
1520 name[i] = 0xFF&strpool[i+strstart[outputfilename]];
1521 #else
1522 name[i] = strpool[i+strstartar[outputfilename - 65536L]];
1523 #endif
1524 }
1525 #endif
1526 name[len] = 0;
1527
1528 /* Have to pass whole filename to the other end, since it may have
1529 been started up and running as a daemon, e.g., as with the NeXT
1530 preview program. */
1531 p = concat3 (cwd, DIR_SEP_STRING, name);
1532 free (cwd);
1533 free (name);
1534
1535 #if defined (WIN32)
1536 { char *q;
1537 for (q = p; *q; q++) {
1538 if (*q == '\\')
1539 *q = '/';
1540 else if (IS_KANJI(q))
1541 q++;
1542 }
1543 }
1544 #endif
1545 len = strlen(p);
1546 begun = true;
1547 }
1548 ipc_snd (len, is_eof, p);
1549
1550 if (p)
1551 free (p);
1552 }
1553 #endif /* TeX && IPC */
1554
1555 #if defined (TeX) || defined (MF)
1556 /* TCX and Aleph&Co get along like sparks and gunpowder. */
1557 #if !defined(Aleph) && !defined(XeTeX)
1558
1559 /* Return the next number following START, setting POST to the following
1560 character, as in strtol. Issue a warning and return -1 if no number
1561 can be parsed. */
1562
1563 static int
1564 tcx_get_num (int upb,
1565 unsigned line_count,
1566 string start,
1567 string *post)
1568 {
1569 int num = strtol (start, post, 0);
1570 assert (post && *post);
1571 if (*post == start) {
1572 /* Could not get a number. If blank line, fine. Else complain. */
1573 string p = start;
1574 while (*p && ISSPACE (*p))
1575 p++;
1576 if (*p != 0)
1577 fprintf (stderr, "%s:%d: Expected numeric constant, not `%s'.\n",
1578 translate_filename, line_count, start);
1579 num = -1;
1580 } else if (num < 0 || num > upb) {
1581 fprintf (stderr, "%s:%d: Destination charcode %d <0 or >%d.\n",
1582 translate_filename, line_count, num, upb);
1583 num = -1;
1584 }
1585
1586 return num;
1587 }
1588
1589 /* Update the xchr, xord, and xprn arrays for TeX, allowing a
1590 translation table specified at runtime via an external file.
1591 Look for the character translation file FNAME along the same path as
1592 tex.pool. If no suffix in FNAME, use .tcx (don't bother trying to
1593 support extension-less names for these files). */
1594
1595 void
1596 readtcxfile (void)
1597 {
1598 string orig_filename;
1599 if (!find_suffix (translate_filename)) {
1600 translate_filename = concat (translate_filename, ".tcx");
1601 }
1602 orig_filename = translate_filename;
1603 translate_filename
1604 = kpse_find_file (translate_filename, kpse_web2c_format, true);
1605 if (translate_filename) {
1606 string line;
1607 unsigned line_count = 0;
1608 FILE *translate_file = xfopen (translate_filename, FOPEN_R_MODE);
1609 while ((line = read_line (translate_file))) {
1610 int first;
1611 string start2;
1612 string comment_loc = strchr (line, '%');
1613 if (comment_loc)
1614 *comment_loc = 0;
1615
1616 line_count++;
1617
1618 first = tcx_get_num (255, line_count, line, &start2);
1619 if (first >= 0) {
1620 string start3;
1621 int second;
1622 int printable;
1623
1624 second = tcx_get_num (255, line_count, start2, &start3);
1625 if (second >= 0) {
1626 /* I suppose we could check for nonempty junk following the
1627 "printable" code, but let's not bother. */
1628 string extra;
1629
1630 /* If they mention a second code, make that the internal number. */
1631 xord[first] = second;
1632 xchr[second] = first;
1633
1634 printable = tcx_get_num (1, line_count, start3, &extra);
1635 /* Not-a-number, may be a comment. */
1636 if (printable == -1)
1637 printable = 1;
1638 /* Don't allow the 7bit ASCII set to become unprintable. */
1639 if (32 <= second && second <= 126)
1640 printable = 1;
1641 } else {
1642 second = first; /* else make internal the same as external */
1643 /* If they mention a charcode, call it printable. */
1644 printable = 1;
1645 }
1646
1647 xprn[second] = printable;
1648 }
1649 free (line);
1650 }
1651 xfclose(translate_file, translate_filename);
1652 } else {
1653 WARNING1 ("Could not open char translation file `%s'", orig_filename);
1654 }
1655 }
1656 #endif /* !Aleph && !XeTeX */
1657 #endif /* TeX || MF [character translation] */
1658
1659 #ifdef XeTeX /* XeTeX handles this differently, and allows odd quotes within names */
1660 static string
1661 normalize_quotes (const_string name, const_string mesg)
1662 {
1663 int quote_char = 0;
1664 boolean must_quote = false;
1665 int len = strlen(name);
1666 /* Leave room for quotes and NUL. */
1667 string ret;
1668 string p;
1669 const_string q;
1670 for (q = name; *q; q++) {
1671 if (*q == ' ') {
1672 if (!must_quote) {
1673 len += 2;
1674 must_quote = true;
1675 }
1676 }
1677 else if (*q == '\"' || *q == '\'') {
1678 must_quote = true;
1679 if (quote_char == 0)
1680 quote_char = '\"' + '\'' - *q;
1681 len += 2; /* this could sometimes add length we don't need */
1682 }
1683 }
1684 ret = xmalloc(len + 1);
1685 p = ret;
1686 if (must_quote) {
1687 if (quote_char == 0)
1688 quote_char = '\"';
1689 *p++ = quote_char;
1690 }
1691 for (q = name; *q; q++) {
1692 if (*q == quote_char) {
1693 *p++ = quote_char;
1694 quote_char = '\"' + '\'' - quote_char;
1695 *p++ = quote_char;
1696 }
1697 *p++ = *q;
1698 }
1699 if (quote_char != 0)
1700 *p++ = quote_char;
1701 *p = '\0';
1702 return ret;
1703 }
1704 #else
1705 /* Normalize quoting of filename -- that is, only quote if there is a space,
1706 and always use the quote-name-quote style. */
1707 static string
1708 normalize_quotes (const_string name, const_string mesg)
1709 {
1710 boolean quoted = false;
1711 boolean must_quote = (strchr(name, ' ') != NULL);
1712 /* Leave room for quotes and NUL. */
1713 string ret = xmalloc(strlen(name)+3);
1714 string p;
1715 const_string q;
1716 p = ret;
1717 if (must_quote)
1718 *p++ = '"';
1719 for (q = name; *q; q++) {
1720 if (*q == '"')
1721 quoted = !quoted;
1722 else
1723 *p++ = *q;
1724 }
1725 if (must_quote)
1726 *p++ = '"';
1727 *p = '\0';
1728 if (quoted) {
1729 fprintf(stderr, "! Unbalanced quotes in %s %s\n", mesg, name);
1730 uexit(1);
1731 }
1732 return ret;
1733 }
1734 #endif
1735
1736 /* Getting the input filename. */
1737 string
1738 get_input_file_name (void)
1739 {
1740 string input_file_name = NULL;
1741
1742 if (argv[optind] && argv[optind][0] != '&' && argv[optind][0] != '\\') {
1743 /* Not &format, not \input, so assume simple filename. */
1744 string name;
1745 #ifndef XeTeX
1746 boolean quoted;
1747 #endif
1748
1749 #ifdef WIN32
1750 if (strlen (argv[optind]) > 2 && isalpha (argv[optind][0]) &&
1751 argv[optind][1] == ':' && argv[optind][2] == '\\') {
1752 char *pp;
1753 for (pp = argv[optind]; *pp; pp++) {
1754 if (*pp == '\\')
1755 *pp = '/';
1756 else if (IS_KANJI(pp))
1757 pp++;
1758 }
1759 }
1760 #endif
1761 name = normalize_quotes(argv[optind], "argument");
1762 #ifdef XeTeX
1763 input_file_name = kpse_find_file(argv[optind], INPUT_FORMAT, false);
1764 #else
1765 quoted = (name[0] == '"');
1766 if (quoted) {
1767 /* Overwrite last quote and skip first quote. */
1768 name[strlen(name)-1] = '\0';
1769 name++;
1770 }
1771 input_file_name = kpse_find_file(name, INPUT_FORMAT, false);
1772 if (quoted) {
1773 /* Undo modifications */
1774 name[strlen(name)] = '"';
1775 name--;
1776 }
1777 #endif
1778 argv[optind] = name;
1779 }
1780 return input_file_name;
1781 }
1782
1783 /* Reading the options. */
1784
1785 /* Test whether getopt found an option ``A''.
1786 Assumes the option index is in the variable `option_index', and the
1787 option table in a variable `long_options'. */
1788 #define ARGUMENT_IS(a) STREQ (long_options[option_index].name, a)
1789
1790 /* SunOS cc can't initialize automatic structs, so make this static. */
1791 static struct option long_options[]
1792 = { { DUMP_OPTION, 1, 0, 0 },
1793 #ifdef TeX
1794 /* Obsolete -- for backward compatibility only. */
1795 { "efmt", 1, 0, 0 },
1796 #endif
1797 { "cnf-line", 1, 0, 0 },
1798 { "help", 0, 0, 0 },
1799 { "ini", 0, &iniversion, 1 },
1800 { "interaction", 1, 0, 0 },
1801 { "halt-on-error", 0, &haltonerrorp, 1 },
1802 { "kpathsea-debug", 1, 0, 0 },
1803 { "progname", 1, 0, 0 },
1804 { "recorder", 0, &recorder_enabled, 1 },
1805 { "version", 0, 0, 0 },
1806 #ifdef TeX
1807 #ifdef IPC
1808 { "ipc", 0, &ipcon, 1 },
1809 { "ipc-start", 0, &ipcon, 2 },
1810 #endif /* IPC */
1811 #if !defined(Aleph)
1812 { "mltex", 0, &mltexp, 1 },
1813 #if !defined(XeTeX) && !IS_pTeX
1814 { "enc", 0, &enctexp, 1 },
1815 #endif
1816 #endif /* !Aleph */
1817 #if IS_eTeX
1818 { "etex", 0, &etexp, 1 },
1819 #endif
1820 { "output-comment", 1, 0, 0 },
1821 #if defined(pdfTeX)
1822 { "draftmode", 0, 0, 0 },
1823 { "output-format", 1, 0, 0 },
1824 #endif /* pdfTeX */
1825 { "shell-escape", 0, &shellenabledp, 1 },
1826 { "no-shell-escape", 0, &shellenabledp, -1 },
1827 { "enable-write18", 0, &shellenabledp, 1 },
1828 { "disable-write18", 0, &shellenabledp, -1 },
1829 { "shell-restricted", 0, 0, 0 },
1830 { "debug-format", 0, &debugformatfile, 1 },
1831 { "src-specials", 2, 0, 0 },
1832 #if defined(__SyncTeX__)
1833 /* Synchronization: just like "interaction" above */
1834 { "synctex", 1, 0, 0 },
1835 #endif
1836 #endif /* TeX */
1837 #if defined (TeX) || defined (MF)
1838 { "file-line-error-style", 0, &filelineerrorstylep, 1 },
1839 { "no-file-line-error-style", 0, &filelineerrorstylep, -1 },
1840 /* Shorter option names for the above. */
1841 { "file-line-error", 0, &filelineerrorstylep, 1 },
1842 { "no-file-line-error", 0, &filelineerrorstylep, -1 },
1843 { "jobname", 1, 0, 0 },
1844 { "output-directory", 1, 0, 0 },
1845 { "parse-first-line", 0, &parsefirstlinep, 1 },
1846 { "no-parse-first-line", 0, &parsefirstlinep, -1 },
1847 #if !defined(Aleph)
1848 { "translate-file", 1, 0, 0 },
1849 { "default-translate-file", 1, 0, 0 },
1850 { "8bit", 0, &eightbitp, 1 },
1851 #endif /* !Aleph */
1852 #if defined(XeTeX)
1853 { "no-pdf", 0, &nopdfoutput, 1 },
1854 { "output-driver", 1, 0, 0 },
1855 { "papersize", 1, 0, 0 },
1856 #endif /* XeTeX */
1857 { "mktex", 1, 0, 0 },
1858 { "no-mktex", 1, 0, 0 },
1859 #endif /* TeX or MF */
1860 #if IS_pTeX
1861 { "guess-input-enc", 0, &infile_enc_auto, 1 },
1862 { "no-guess-input-enc", 0, &infile_enc_auto, 0 },
1863 { "kanji", 1, 0, 0 },
1864 { "kanji-internal", 1, 0, 0 },
1865 #endif /* IS_pTeX */
1866 { 0, 0, 0, 0 } };
1867
1868 static void
1869 parse_options (int argc, string *argv)
1870 {
1871 int g; /* `getopt' return code. */
1872 int option_index;
1873
1874 for (;;) {
1875 g = getopt_long_only (argc, argv, "+", long_options, &option_index);
1876
1877 if (g == -1) /* End of arguments, exit the loop. */
1878 break;
1879
1880 if (g == '?') { /* Unknown option. */
1881 continue;
1882 }
1883
1884 assert (g == 0); /* We have no short option names. */
1885
1886 if (ARGUMENT_IS ("kpathsea-debug")) {
1887 kpathsea_debug |= atoi (optarg);
1888
1889 #ifdef XeTeX
1890 } else if (ARGUMENT_IS ("papersize")) {
1891 papersize = optarg;
1892 } else if (ARGUMENT_IS ("output-driver")) {
1893 outputdriver = optarg;
1894 #endif
1895
1896 } else if (ARGUMENT_IS ("progname")) {
1897 user_progname = optarg;
1898
1899 } else if (ARGUMENT_IS ("cnf-line")) {
1900 if (user_cnf_lines == NULL) {
1901 user_cnf_nlines = 1;
1902 user_cnf_lines = xmalloc (sizeof (const_string));
1903 } else {
1904 user_cnf_nlines++;
1905 user_cnf_lines = xrealloc (user_cnf_lines,
1906 user_cnf_nlines * sizeof (const_string));
1907 }
1908 user_cnf_lines[user_cnf_nlines-1] = xstrdup (optarg);
1909
1910 } else if (ARGUMENT_IS ("jobname")) {
1911 #ifdef XeTeX
1912 c_job_name = optarg;
1913 #else
1914 c_job_name = normalize_quotes (optarg, "jobname");
1915 #endif
1916
1917 } else if (ARGUMENT_IS (DUMP_OPTION)) {
1918 dump_name = optarg;
1919 dumpoption = true;
1920
1921 #ifdef TeX
1922 /* For backward compatibility only. */
1923 } else if (ARGUMENT_IS ("efmt")) {
1924 dump_name = optarg;
1925 dumpoption = true;
1926 #endif
1927
1928 } else if (ARGUMENT_IS ("output-directory")) {
1929 output_directory = optarg;
1930
1931 #ifdef TeX
1932 } else if (ARGUMENT_IS ("output-comment")) {
1933 unsigned len = strlen (optarg);
1934 if (len < 256) {
1935 outputcomment = optarg;
1936 } else {
1937 WARNING2 ("Comment truncated to 255 characters from %d. (%s)",
1938 len, optarg);
1939 outputcomment = xmalloc (256);
1940 strncpy (outputcomment, optarg, 255);
1941 outputcomment[255] = 0;
1942 }
1943
1944 #ifdef IPC
1945 } else if (ARGUMENT_IS ("ipc-start")) {
1946 ipc_open_out ();
1947 /* Try to start up the other end if it's not already. */
1948 if (!ipc_is_open ()) {
1949 #ifdef WIN32
1950 if (_spawnlp (_P_NOWAIT, IPC_SERVER_CMD, IPC_SERVER_CMD, NULL) != -1) {
1951 #else
1952 if (system (IPC_SERVER_CMD) == 0) {
1953 #endif
1954 unsigned i;
1955 for (i = 0; i < 20 && !ipc_is_open (); i++) {
1956 #ifdef WIN32
1957 Sleep (100); /* 2000ms is too long for a simple w32 example */
1958 #else
1959 sleep (2);
1960 #endif
1961 ipc_open_out ();
1962 }
1963 }
1964 }
1965 #endif /* IPC */
1966
1967 } else if (ARGUMENT_IS ("shell-restricted")) {
1968 shellenabledp = 1;
1969 restrictedshell = 1;
1970
1971 } else if (ARGUMENT_IS ("src-specials")) {
1972 last_source_name = xstrdup("");
1973 /* Option `--src" without any value means `auto' mode. */
1974 if (optarg == NULL) {
1975 insertsrcspecialeverypar = true;
1976 insertsrcspecialauto = true;
1977 srcspecialsoption = true;
1978 srcspecialsp = true;
1979 } else {
1980 parse_src_specials_option(optarg);
1981 }
1982 #endif /* TeX */
1983 #if defined(pdfTeX)
1984 } else if (ARGUMENT_IS ("output-format")) {
1985 pdfoutputoption = 1;
1986 if (strcmp(optarg, "dvi") == 0) {
1987 pdfoutputvalue = 0;
1988 } else if (strcmp(optarg, "pdf") == 0) {
1989 pdfoutputvalue = 2;
1990 } else {
1991 WARNING1 ("Ignoring unknown value `%s' for --output-format", optarg);
1992 pdfoutputoption = 0;
1993 }
1994 } else if (ARGUMENT_IS ("draftmode")) {
1995 pdfdraftmodeoption = 1;
1996 pdfdraftmodevalue = 1;
1997 #endif /* pdfTeX */
1998 #if defined (TeX) || defined (MF)
1999 #if !defined(Aleph)
2000 } else if (ARGUMENT_IS ("translate-file")) {
2001 translate_filename = optarg;
2002 } else if (ARGUMENT_IS ("default-translate-file")) {
2003 default_translate_filename = optarg;
2004 #endif /* !Aleph */
2005 } else if (ARGUMENT_IS ("mktex")) {
2006 kpse_maketex_option (optarg, true);
2007 } else if (ARGUMENT_IS ("no-mktex")) {
2008 kpse_maketex_option (optarg, false);
2009 #endif /* TeX or MF */
2010 } else if (ARGUMENT_IS ("interaction")) {
2011 /* These numbers match @d's in *.ch */
2012 if (STREQ (optarg, "batchmode")) {
2013 interactionoption = 0;
2014 } else if (STREQ (optarg, "nonstopmode")) {
2015 interactionoption = 1;
2016 } else if (STREQ (optarg, "scrollmode")) {
2017 interactionoption = 2;
2018 } else if (STREQ (optarg, "errorstopmode")) {
2019 interactionoption = 3;
2020 } else {
2021 WARNING1 ("Ignoring unknown argument `%s' to --interaction", optarg);
2022 }
2023 #if IS_pTeX
2024 } else if (ARGUMENT_IS ("kanji")) {
2025 if (!set_enc_string (optarg, NULL)) {
2026 WARNING1 ("Ignoring unknown argument `%s' to --kanji", optarg);
2027 }
2028 } else if (ARGUMENT_IS ("kanji-internal")) {
2029 if (!set_enc_string (NULL, optarg)) {
2030 WARNING1 ("Ignoring unknown argument `%s' to --kanji-internal", optarg);
2031 }
2032 #endif
2033
2034 } else if (ARGUMENT_IS ("help")) {
2035 usagehelp (PROGRAM_HELP, BUG_ADDRESS);
2036
2037 #if defined(__SyncTeX__)
2038 } else if (ARGUMENT_IS ("synctex")) {
2039 /* Synchronize TeXnology: catching the command line option as a long */
2040 synctexoption = (int) strtol(optarg, NULL, 0);
2041 #endif
2042
2043 } else if (ARGUMENT_IS ("version")) {
2044 char *versions;
2045 #if defined (pdfTeX) || defined(XeTeX)
2046 initversionstring(&versions);
2047 #else
2048 versions = NULL;
2049 #endif
2050 printversionandexit (BANNER, COPYRIGHT_HOLDER, AUTHOR, versions);
2051
2052 } /* Else it was a flag; getopt has already done the assignment. */
2053 }
2054
2055 if (output_directory) {
2056 /* If they specified --output-directory, save it in an envvar
2057 so that subprocesses called with \write18 can get the value. */
2058 xputenv ("TEXMF_OUTPUT_DIRECTORY", output_directory);
2059
2060 } else if (getenv ("TEXMF_OUTPUT_DIRECTORY")) {
2061 /* If the option wasn't specified, but the envvar is set (i.e., by
2062 the user), save the envvar value in our global variable so the
2063 rest of our code will use it. */
2064 output_directory = getenv ("TEXMF_OUTPUT_DIRECTORY");
2065
2066 } /* Else neither option nor envvar was set; do nothing. */
2067 }
2068
2069 #if defined(TeX)
2070 void
2071 parse_src_specials_option (const_string opt_list)
2072 {
2073 char * toklist = xstrdup(opt_list);
2074 char * tok;
2075 insertsrcspecialauto = false;
2076 tok = strtok (toklist, ", ");
2077 while (tok) {
2078 if (strcmp (tok, "everypar") == 0
2079 || strcmp (tok, "par") == 0
2080 || strcmp (tok, "auto") == 0) {
2081 insertsrcspecialauto = true;
2082 insertsrcspecialeverypar = true;
2083 } else if (strcmp (tok, "everyparend") == 0
2084 || strcmp (tok, "parend") == 0)
2085 insertsrcspecialeveryparend = true;
2086 else if (strcmp (tok, "everycr") == 0
2087 || strcmp (tok, "cr") == 0)
2088 insertsrcspecialeverycr = true;
2089 else if (strcmp (tok, "everymath") == 0
2090 || strcmp (tok, "math") == 0)
2091 insertsrcspecialeverymath = true;
2092 else if (strcmp (tok, "everyhbox") == 0
2093 || strcmp (tok, "hbox") == 0)
2094 insertsrcspecialeveryhbox = true;
2095 else if (strcmp (tok, "everyvbox") == 0
2096 || strcmp (tok, "vbox") == 0)
2097 insertsrcspecialeveryvbox = true;
2098 else if (strcmp (tok, "everydisplay") == 0
2099 || strcmp (tok, "display") == 0)
2100 insertsrcspecialeverydisplay = true;
2101 else if (strcmp (tok, "none") == 0) {
2102 /* This one allows to reset an option that could appear in texmf.cnf */
2103 insertsrcspecialauto = insertsrcspecialeverypar =
2104 insertsrcspecialeveryparend = insertsrcspecialeverycr =
2105 insertsrcspecialeverymath = insertsrcspecialeveryhbox =
2106 insertsrcspecialeveryvbox = insertsrcspecialeverydisplay = false;
2107 } else {
2108 WARNING1 ("Ignoring unknown argument `%s' to --src-specials", tok);
2109 }
2110 tok = strtok(0, ", ");
2111 }
2112 free(toklist);
2113 srcspecialsp=insertsrcspecialauto | insertsrcspecialeverypar |
2114 insertsrcspecialeveryparend | insertsrcspecialeverycr |
2115 insertsrcspecialeverymath | insertsrcspecialeveryhbox |
2116 insertsrcspecialeveryvbox | insertsrcspecialeverydisplay;
2117 srcspecialsoption = true;
2118 }
2119 #endif
2120
2121 /* If the first thing on the command line (we use the globals `argv' and
2122 `optind') is a normal filename (i.e., does not start with `&' or
2123 `\'), and if we can open it, and if its first line is %&FORMAT, and
2124 FORMAT is a readable dump file, then set DUMP_VAR to FORMAT.
2125 Also call kpse_reset_program_name to ensure the correct paths for the
2126 format are used. */
2127 static void
2128 parse_first_line (const_string filename)
2129 {
2130 FILE *f = filename ? fopen (filename, FOPEN_R_MODE) : NULL;
2131 if (f) {
2132 string first_line = read_line (f);
2133 xfclose (f, filename);
2134
2135 /* We deal with the general format "%&fmt --translate-file=tcx" */
2136 /* The idea of using this format came from Wlodzimierz Bzyl
2137 <[email protected]> */
2138 if (first_line && first_line[0] == '%' && first_line[1] == '&') {
2139 /* Parse the first line into at most three space-separated parts. */
2140 char *s;
2141 char *part[4];
2142 int npart;
2143 char **parse;
2144
2145 /* Here we use ISBLANK instead of IS_SPC_OR_EOL because we are
2146 parsing the whitespace-delimited %& line, not TeX input. */
2147 for (s = first_line+2; ISBLANK(*s); ++s)
2148 ;
2149 npart = 0;
2150 while (*s && npart != 3) {
2151 part[npart++] = s;
2152 while (*s && *s != ' ') s++;
2153 while (*s == ' ') *s++ = '\0';
2154 }
2155 part[npart] = NULL;
2156 parse = part;
2157 /* Look at what we've got. Very crude! */
2158 if (*parse && **parse != '-') {
2159 /* A format name */
2160 if (dump_name) {
2161 /* format already determined, do nothing. */
2162 } else {
2163 string f_name = concat (part[0], DUMP_EXT);
2164 string d_name = kpse_find_file (f_name, DUMP_FORMAT, false);
2165 if (d_name && kpse_readable_file (d_name)) {
2166 dump_name = xstrdup (part[0]);
2167 kpse_reset_program_name (dump_name);
2168 /* Tell TeX/MF/MP we have a %&name line... */
2169 dumpline = true;
2170 }
2171 free (f_name);
2172 }
2173 parse++;
2174 }
2175 /* The tcx stuff, if any. Should we support the -translate-file
2176 form as well as --translate-file? */
2177 if (*parse) {
2178 s = NULL;
2179 if (translate_filename) {
2180 /* TCX file already set, do nothing. */
2181 } else if (STREQ (*parse, "--translate-file")) {
2182 s = *(parse+1);
2183 } else if (STREQ (*parse, "-translate-file")) {
2184 s = *(parse+1);
2185 } else if (STRNEQ (*parse, "--translate-file=", 17)) {
2186 s = *parse+17;
2187 } else if (STRNEQ (*parse, "-translate-file=", 16)) {
2188 s = *parse+16;
2189 }
2190 /* Just set the name, no sanity checks here. */
2191 if (s && *s) {
2192 translate_filename = xstrdup(s);
2193 }
2194 }
2195 }
2196 if (first_line)
2197 free (first_line);
2198 }
2199 }
2200
2201 /*
2202 piped I/O
2203 */
2204
2205 /* The code that implements popen() needs an array for tracking
2206 possible pipe file pointers, because these need to be
2207 closed using pclose().
2208 */
2209
2210 #if ENABLE_PIPES
2211
2212 #define NUM_PIPES 16
2213
2214 static FILE *pipes [NUM_PIPES];
2215
2216 boolean
2217 open_in_or_pipe (FILE **f_ptr, int filefmt, const_string fopen_mode)
2218 {
2219 string fname = NULL;
2220 int i; /* iterator */
2221
2222 /* opening a read pipe is straightforward, only have to
2223 skip past the pipe symbol in the file name. filename
2224 quoting is assumed to happen elsewhere (it does :-)) */
2225
2226 if (shellenabledp && *(nameoffile+1) == '|') {
2227 /* the user requested a pipe */
2228 *f_ptr = NULL;
2229 fname = xmalloc(strlen((const_string)(nameoffile+1))+1);
2230 strcpy(fname,(const_string)(nameoffile+1));
2231 if (fullnameoffile)
2232 free(fullnameoffile);
2233 fullnameoffile = xstrdup(fname);
2234 recorder_record_input (fname + 1);
2235 *f_ptr = runpopen(fname+1,"r");
2236 free(fname);
2237 for (i=0; i<NUM_PIPES; i++) {
2238 if (pipes[i]==NULL) {
2239 pipes[i] = *f_ptr;
2240 break;
2241 }
2242 }
2243 if (*f_ptr)
2244 setvbuf (*f_ptr,NULL,_IONBF,0);
2245 #ifdef WIN32
2246 Poptr = *f_ptr;
2247 #endif
2248
2249 return *f_ptr != NULL;
2250 }
2251
2252 return open_input(f_ptr,filefmt,fopen_mode) ;
2253 }
2254
2255 #ifdef XeTeX
2256 boolean
2257 u_open_in_or_pipe(unicodefile* f, integer filefmt, const_string fopen_mode, integer mode, integer encodingData)
2258 {
2259 string fname = NULL;
2260 int i; /* iterator */
2261
2262 /* opening a read pipe is straightforward, only have to
2263 skip past the pipe symbol in the file name. filename
2264 quoting is assumed to happen elsewhere (it does :-)) */
2265
2266 if (shellenabledp && *(nameoffile+1) == '|') {
2267 /* the user requested a pipe */
2268 *f = malloc(sizeof(UFILE));
2269 (*f)->encodingMode = (mode == AUTO) ? UTF8 : mode;
2270 (*f)->conversionData = 0;
2271 (*f)->savedChar = -1;
2272 (*f)->skipNextLF = 0;
2273 (*f)->f = NULL;
2274 fname = xmalloc(strlen((const_string)(nameoffile+1))+1);
2275 strcpy(fname,(const_string)(nameoffile+1));
2276 if (fullnameoffile)
2277 free(fullnameoffile);
2278 fullnameoffile = xstrdup(fname);
2279 recorder_record_input (fname + 1);
2280 (*f)->f = runpopen(fname+1,"r");
2281 free(fname);
2282 for (i=0; i<NUM_PIPES; i++) {
2283 if (pipes[i]==NULL) {
2284 pipes[i] = (*f)->f;
2285 break;
2286 }
2287 }
2288 if ((*f)->f)
2289 setvbuf ((*f)->f,NULL,_IONBF,0);
2290 #ifdef WIN32
2291 Poptr = (*f)->f;
2292 #endif
2293
2294 return (*f)->f != NULL;
2295 }
2296
2297 return u_open_in(f, filefmt, fopen_mode, mode, encodingData);
2298 }
2299 #endif
2300
2301 boolean
2302 open_out_or_pipe (FILE **f_ptr, const_string fopen_mode)
2303 {
2304 string fname;
2305 int i; /* iterator */
2306
2307 /* opening a write pipe takes a little bit more work, because TeX
2308 will perhaps have appended ".tex". To avoid user confusion as
2309 much as possible, this extension is stripped only when the command
2310 is a bare word. Some small string trickery is needed to make
2311 sure the correct number of bytes is free()-d afterwards */
2312
2313 if (shellenabledp && *(nameoffile+1) == '|') {
2314 /* the user requested a pipe */
2315 fname = xmalloc(strlen((const_string)(nameoffile+1))+1);
2316 strcpy(fname,(const_string)(nameoffile+1));
2317 if (strchr (fname,' ')==NULL && strchr(fname,'>')==NULL) {
2318 /* mp and mf currently do not use this code, but it
2319 is better to be prepared */
2320 if (STREQ((fname+strlen(fname)-4),".tex"))
2321 *(fname+strlen(fname)-4) = 0;
2322 *f_ptr = runpopen(fname+1,"w");
2323 *(fname+strlen(fname)) = '.';
2324 } else {
2325 *f_ptr = runpopen(fname+1,"w");
2326 }
2327 recorder_record_output (fname + 1);
2328 free(fname);
2329
2330 for (i=0; i<NUM_PIPES; i++) {
2331 if (pipes[i]==NULL) {
2332 pipes[i] = *f_ptr;
2333 break;
2334 }
2335 }
2336
2337 if (*f_ptr)
2338 setvbuf(*f_ptr,NULL,_IONBF,0);
2339
2340 return *f_ptr != NULL;
2341 }
2342
2343 return open_output(f_ptr,fopen_mode);
2344 }
2345
2346
2347 void
2348 close_file_or_pipe (FILE *f)
2349 {
2350 int i; /* iterator */
2351
2352 if (shellenabledp) {
2353 /* if this file was a pipe, pclose() it and return */
2354 for (i=0; i<NUM_PIPES; i++) {
2355 if (pipes[i] == f) {
2356 if (f) {
2357 pclose (f);
2358 #ifdef WIN32
2359 Poptr = NULL;
2360 #endif
2361 }
2362 pipes[i] = NULL;
2363 return;
2364 }
2365 }
2366 }
2367 close_file(f);
2368 }
2369
2370 #ifdef XeTeX
2371
2372 #include <unicode/ucnv.h>
2373
2374 void
2375 u_close_file_or_pipe (unicodefile* f)
2376 {
2377 int i; /* iterator */
2378
2379 if (shellenabledp) {
2380 /* if this file was a pipe, pclose() it and return */
2381 for (i=0; i<NUM_PIPES; i++) {
2382 if (pipes[i] == (*f)->f) {
2383 if ((*f)->f) {
2384 pclose ((*f)->f);
2385 if (((*f)->encodingMode == ICUMAPPING) && ((*f)->conversionData != NULL))
2386 ucnv_close((*f)->conversionData);
2387 free(*f);
2388 }
2389 pipes[i] = NULL;
2390 return;
2391 }
2392 }
2393 }
2394 close_file((*f)->f);
2395 }
2396
2397 #endif
2398
2399 #endif /* ENABLE_PIPES */
2400
2401 /* All our interrupt handler has to do is set TeX's or Metafont's global
2402 variable `interrupt'; then they will do everything needed. */
2403 #ifdef WIN32
2404 /* Win32 doesn't set SIGINT ... */
2405 static BOOL WINAPI
2406 catch_interrupt (DWORD arg)
2407 {
2408 switch (arg) {
2409 case CTRL_C_EVENT:
2410 case CTRL_BREAK_EVENT:
2411 interrupt = 1;
2412 return TRUE;
2413 default:
2414 /* No need to set interrupt as we are exiting anyway */
2415 return FALSE;
2416 }
2417 }
2418 #else /* not WIN32 */
2419 static RETSIGTYPE
2420 catch_interrupt (int arg)
2421 {
2422 interrupt = 1;
2423 #ifdef OS2
2424 (void) signal (SIGINT, SIG_ACK);
2425 #else
2426 (void) signal (SIGINT, catch_interrupt);
2427 #endif /* not OS2 */
2428 }
2429 #endif /* not WIN32 */
2430
2431 #if defined(_MSC_VER)
2432 #define strtoull _strtoui64
2433 #endif
2434
2435 static boolean start_time_set = false;
2436 static time_t start_time = 0;
2437
2438 static boolean SOURCE_DATE_EPOCH_set = false;
2439 static boolean FORCE_SOURCE_DATE_set = false;
2440
2441 void init_start_time() {
2442 char *source_date_epoch;
2443 unsigned long long epoch;
2444 char *endptr;
2445 if (!start_time_set) {
2446 start_time_set = true;
2447 #ifndef onlyTeX
2448 source_date_epoch = getenv("SOURCE_DATE_EPOCH");
2449 if (source_date_epoch) {
2450 errno = 0;
2451 epoch = strtoull(source_date_epoch, &endptr, 10);
2452 if (*endptr != '\0' || errno != 0) {
2453 FATAL1 ("invalid epoch-seconds-timezone value for environment variable $SOURCE_DATE_EPOCH: %s",
2454 source_date_epoch);
2455 }
2456 #if defined(_MSC_VER)
2457 if (epoch > 32535291599ULL)
2458 epoch = 32535291599ULL;
2459 #endif
2460 start_time = epoch;
2461 SOURCE_DATE_EPOCH_set = true;
2462 } else
2463 #endif /* not onlyTeX */
2464 {
2465 start_time = time((time_t *) NULL);
2466 }
2467 }
2468 }
2469
2470 /* Besides getting the date and time here, we also set up the interrupt
2471 handler, for no particularly good reason. It's just that since the
2472 `fix_date_and_time' routine is called early on (section 1337 in TeX,
2473 ``Get the first line of input and prepare to start''), this is as
2474 good a place as any. */
2475
2476 void
2477 get_date_and_time (integer *minutes, integer *day,
2478 integer *month, integer *year)
2479 {
2480 struct tm *tmptr;
2481 #ifndef onlyTeX
2482 string sde_texprim = getenv ("FORCE_SOURCE_DATE");
2483 if (sde_texprim && STREQ (sde_texprim, "1")) {
2484 init_start_time ();
2485 tmptr = gmtime (&start_time);
2486 FORCE_SOURCE_DATE_set = true;
2487 } else
2488 #endif /* not onlyTeX */
2489 {
2490 /* whether the envvar was not set (usual case) or invalid,
2491 use current time. */
2492 time_t myclock = time ((time_t *) 0);
2493 tmptr = localtime (&myclock);
2494
2495 #ifndef onlyTeX
2496 /* warn if they gave an invalid value, empty (null string) ok. */
2497 if (sde_texprim && strlen (sde_texprim) > 0
2498 && !STREQ (sde_texprim, "0")) {
2499 WARNING1 ("invalid value (expected 0 or 1) for environment variable $FORCE_SOURCE_DATE: %s",
2500 sde_texprim);
2501 }
2502 #endif /* not onlyTeX */
2503 }
2504
2505 *minutes = tmptr->tm_hour * 60 + tmptr->tm_min;
2506 *day = tmptr->tm_mday;
2507 *month = tmptr->tm_mon + 1;
2508 *year = tmptr->tm_year + 1900;
2509
2510 {
2511 #ifdef SA_INTERRUPT
2512 /* Under SunOS 4.1.x, the default action after return from the
2513 signal handler is to restart the I/O if nothing has been
2514 transferred. The effect on TeX is that interrupts are ignored if
2515 we are waiting for input. The following tells the system to
2516 return EINTR from read() in this case. From [email protected]. */
2517
2518 struct sigaction a, oa;
2519
2520 a.sa_handler = catch_interrupt;
2521 sigemptyset (&a.sa_mask);
2522 sigaddset (&a.sa_mask, SIGINT);
2523 a.sa_flags = SA_INTERRUPT;
2524 sigaction (SIGINT, &a, &oa);
2525 if (oa.sa_handler != SIG_DFL)
2526 sigaction (SIGINT, &oa, (struct sigaction *) 0);
2527 #else /* no SA_INTERRUPT */
2528 #ifdef WIN32
2529 SetConsoleCtrlHandler(catch_interrupt, TRUE);
2530 #else /* not WIN32 */
2531 RETSIGTYPE (*old_handler)(int);
2532
2533 old_handler = signal (SIGINT, catch_interrupt);
2534 if (old_handler != SIG_DFL)
2535 signal (SIGINT, old_handler);
2536 #endif /* not WIN32 */
2537 #endif /* no SA_INTERRUPT */
2538 }
2539 }
2540
2541 #if defined(pdfTeX) || defined(epTeX) || defined(eupTeX) || defined(XeTeX)
2542 /*
2543 Getting a high resolution time.
2544 */
2545 void
2546 get_seconds_and_micros (integer *seconds, integer *micros)
2547 {
2548 #if defined (HAVE_GETTIMEOFDAY)
2549 struct timeval tv;
2550 gettimeofday(&tv, NULL);
2551 *seconds = tv.tv_sec;
2552 *micros = tv.tv_usec;
2553 #elif defined (HAVE_FTIME)
2554 struct timeb tb;
2555 ftime(&tb);
2556 *seconds = tb.time;
2557 *micros = tb.millitm*1000;
2558 #else
2559 time_t myclock = time((time_t*)NULL);
2560 *seconds = myclock;
2561 *micros = 0;
2562 #endif
2563 }
2564 #endif
2565
2566 /* Read a line of input as efficiently as possible while still looking
2567 like Pascal. We set `last' to `first' and return `false' if we get
2568 to eof. Otherwise, we return `true' and set last = first +
2569 length(line except trailing whitespace). */
2570
2571 #ifndef XeTeX /* for XeTeX, we have a replacement function in XeTeX_ext.c */
2572 boolean
2573 input_line (FILE *f)
2574 {
2575 int i = EOF;
2576
2577 /* Recognize either LF or CR as a line terminator. */
2578 #if IS_pTeX
2579 last = input_line2(f, (unsigned char *)buffer, (unsigned char *)buffer2,
2580 first, bufsize, &i);
2581 #else
2582 #ifdef WIN32
2583 if (f != Poptr && fileno (f) != fileno (stdin)) {
2584 long position = ftell (f);
2585
2586 if (position == 0L) { /* Detect and skip Byte order marks. */
2587 int k1, k2, k3, k4;
2588 k1 = getc (f);
2589
2590 if (k1 != 0xff && k1 != 0xfe && k1 != 0xef)
2591 rewind (f);
2592 else {
2593 k2 = getc (f);
2594
2595 if (k2 != 0xff && k2 != 0xfe && k2 != 0xbb)
2596 rewind (f);
2597 else if ((k1 == 0xff && k2 == 0xfe) || /* UTF-16(LE) */
2598 (k1 == 0xfe && k2 == 0xff)) /* UTF-16(BE) */
2599 ;
2600 else {
2601 k3 = getc (f);
2602 k4 = getc (f);
2603 if (k1 == 0xef && k2 == 0xbb && k3 == 0xbf &&
2604 k4 >= 0 && k4 <= 0x7e) /* UTF-8 */
2605 ungetc (k4, f);
2606 else
2607 rewind (f);
2608 }
2609 }
2610 }
2611 }
2612 #endif /* WIN32 */
2613 last = first;
2614 do {
2615 errno = 0; /* otherwise EINTR might wrongly persist */
2616 while (last < bufsize && (i = getc (f)) != EOF && i != '\n' && i != '\r')
2617 buffer[last++] = i;
2618
2619 /* The story on EINTR: because we tell libc to pass interrupts
2620 through (see SA_INTERRUPT above), we have to make sure that we
2621 check for and ignore EINTR when getc reads an EOF; hence the
2622 outer do..while loop here (and a similar loop below).
2623
2624 On the other hand, we have to make sure that we detect a real
2625 EOF. Otherwise, for example, typing CTRL-C and then CTRL-D to the
2626 ** prompt results in an infinite loop, because we
2627 (input_line) would never return false. On glibc 2.28-10 (Debian
2628 10/buster), and probably other versions, errno is evidently not
2629 cleared as a side effect of getc (and this is allowed).
2630 Therefore we clear errno before calling getc above.
2631
2632 Original report (thread following has many irrelevant diversions):
2633 https://tug.org/pipermail/tex-k/2020-August/003297.html */
2634
2635 } while (i == EOF && errno == EINTR);
2636 #endif /* not IS_pTeX */
2637
2638 if (i == EOF && last == first)
2639 return false;
2640
2641 /* We didn't get the whole line because our buffer was too small. */
2642 if (i != EOF && i != '\n' && i != '\r') {
2643 fprintf (stderr, "! Unable to read an entire line---bufsize=%u.\n",
2644 (unsigned) bufsize);
2645 fputs ("Please increase buf_size in texmf.cnf.\n", stderr);
2646 uexit (1);
2647 }
2648
2649 buffer[last] = ' ';
2650 if (last >= maxbufstack)
2651 maxbufstack = last;
2652
2653 /* If next char is LF of a CRLF, read it. */
2654 if (i == '\r') {
2655 while ((i = getc (f)) == EOF && errno == EINTR)
2656 ;
2657 if (i != '\n')
2658 ungetc (i, f);
2659 }
2660
2661 /* Trim trailing space character (but not, e.g., tabs). We can't have
2662 line terminators because we stopped reading at the first \r or \n.
2663 TeX's rule is to strip only trailing spaces (and eols). David
2664 Fuchs mentions that this stripping was done to ensure portability
2665 of TeX documents given the padding with spaces on fixed-record
2666 "lines" on some systems of the time, e.g., IBM VM/CMS and OS/360. */
2667 while (last > first && buffer[last - 1] == ' ')
2668 --last;
2669
2670 /* Don't bother using xord if we don't need to. */
2671 #if !defined(Aleph)
2672 for (i = first; i <= last; i++)
2673 buffer[i] = xord[buffer[i]];
2674 #endif
2675
2676 #if IS_pTeX
2677 for (i = last+1; (i < last + 5 && i < bufsize) ; i++)
2678 buffer[i] = '\0';
2679 #endif
2680
2681 return true;
2682 }
2683 #endif /* !XeTeX */
2684
2685 /* This string specifies what the `e' option does in response to an
2686 error message. */
2687 static const_string edit_value = EDITOR;
2688
2689 /* This procedure originally due to sjc@s1-c. TeX & Metafont call it when
2690 the user types `e' in response to an error, invoking a text editor on
2691 the erroneous source file. FNSTART is how far into FILENAME the
2692 actual filename starts; FNLENGTH is how long the filename is. */
2693
2694 void
2695 calledit (packedASCIIcode *filename,
2696 poolpointer fnstart,
2697 integer fnlength,
2698 integer linenumber)
2699 {
2700 char *temp, *command, *fullcmd;
2701 char c;
2702 int sdone, ddone;
2703
2704 #ifdef WIN32
2705 char *fp, *ffp, *env, editorname[256], buffer[256];
2706 int cnt = 0;
2707 int dontchange = 0;
2708 #endif
2709
2710 sdone = ddone = 0;
2711 filename += fnstart;
2712
2713 /* Close any open input files, since we're going to kill the job and
2714 the editor might well want to open them for writing. On Windows,
2715 at least, that would not be allowed when the file is still open.
2716
2717 Unfortunately, the input_file array contains both the open files
2718 that we want to close, and junk references to non-files for
2719 terminal interaction that we must not try to close. For example,
2720 consider this input sequence:
2721 \input test % contains a single line \bla, that is, any undefined cs
2722 i\bum x % insert another undefined control sequence
2723 e % invoke the editor
2724 At this point input_file will have an open file for test.tex,
2725 and a non-file for the insert. https://tex.stackexchange.com/q/552113
2726
2727 Therefore, we have to traverse down input_stack (not input_file),
2728 looking for large enough name_field values corresponding to open
2729 files. Then the index_field value of that entry tells us the
2730 corresponding element of input_file, which is what we need to close.
2731 Additionally we have to skip all entries with state_field 0 since these
2732 correspond to token lists and not input files.
2733
2734 We test for name_field<=255, following tex.web, because the first
2735 256 strings are static, initialized by TeX. (Well, many more
2736 strings are initialized, but we'll follow tex.web.)
2737
2738 For the record, name_field=0 means the terminal,
2739 name_field=1..16 means \openin stream n - 1,
2740 name_field=17 means an invalid stream number (for read_toks),
2741 name_field=18..19 means \scantokens pseudo-files (except for
2742 original TeX of course). But 255 suffices for us.
2743
2744 Here, we do not have to look at cur_input, the global variable
2745 which is effectively the top of input_stack, because it will always
2746 be a terminal (non-file) interaction -- the one where the user
2747 typed "e" to start the edit.
2748
2749 In addition, state_field will be zero for token lists. Skip those too.
2750 (Does not apply to Metafont.)
2751
2752 Description in modules 300--304 of tex.web: "Input stacks and states".
2753
2754 We should close any opened \openin files also. Whoever is reading
2755 this, please implement that? */
2756 {
2757 int is_ptr; /* element of input_stack, 0 < input_ptr */
2758 for (is_ptr = 0; is_ptr < inputptr; is_ptr++) {
2759 #ifdef TeX
2760 if (inputstack[is_ptr].statefield == 0 /* token list */
2761 || inputstack[is_ptr].namefield <= 255) { /* can't be filename */
2762 #elif defined(MF)
2763 if (inputstack[is_ptr].namefield <= 255) {
2764 #else
2765 #error "Unable to identify program" /* MetaPost doesn't use this file */
2766 #endif
2767 ; /* fprintf (stderr, "calledit: skipped input_stack[%d], ", is_ptr);
2768 fprintf (stderr, "namefield=%d <= 255 or statefield=%d == 0\n",
2769 inputstack[is_ptr].namefield,
2770 inputstack[is_ptr].statefield); */
2771 } else {
2772 FILE *f;
2773 /* when name_field > 17, index_field specifies the element of
2774 the input_file array, 1 <= in_open */
2775 int if_ptr = inputstack[is_ptr].indexfield;
2776 if (if_ptr < 1 || if_ptr > inopen) {
2777 fprintf (stderr, "%s:calledit: unexpected if_ptr=%d not in range 1..%d,",
2778 argv[0], if_ptr, inopen);
2779 fprintf (stderr, "from input_stack[%d].namefield=%d\n",
2780 is_ptr, inputstack[is_ptr].namefield);
2781 exit (1);
2782 }
2783
2784 #ifdef XeTeX
2785 f = inputfile[if_ptr]->f;
2786 #else
2787 f = inputfile[if_ptr];
2788 #endif
2789 /* fprintf (stderr,"calledit: input_stack #%d -> input_file #%d = %x\n",
2790 is_ptr, if_ptr, f); */
2791 /* Although it should never happen, if the file value happens to
2792 be zero, let's not gratuitously abort. */
2793 if (f) {
2794 xfclose (f, "inputfile");
2795 } else {
2796 fprintf (stderr, "%s:calledit: not closing unexpected zero", argv[0]);
2797 fprintf (stderr, " input_file[%d] from input_stack[%d].namefield=%d\n",
2798 if_ptr, is_ptr, inputstack[is_ptr].namefield);
2799 }
2800 } /* end name_field > 17 */
2801 } /* end for loop for input_stack */
2802 } /* end block for variable declarations */
2803
2804 /* Replace the default with the value of the appropriate environment
2805 variable or config file value, if it's set. */
2806 temp = kpse_var_value (edit_var);
2807 if (temp != NULL)
2808 edit_value = temp;
2809
2810 /* Construct the command string. The `11' is the maximum length an
2811 integer might be (64 bits). */
2812 command = xmalloc (strlen (edit_value) + fnlength + 11);
2813
2814 /* So we can construct it as we go. */
2815 temp = command;
2816
2817 #ifdef WIN32
2818 fp = editorname;
2819 if ((isalpha(*edit_value) && *(edit_value + 1) == ':'
2820 && IS_DIR_SEP (*(edit_value + 2)))
2821 || (*edit_value == '"' && isalpha(*(edit_value + 1))
2822 && *(edit_value + 2) == ':'
2823 && IS_DIR_SEP (*(edit_value + 3)))
2824 )
2825 dontchange = 1;
2826 #endif
2827
2828 while ((c = *edit_value++) != 0)
2829 {
2830 if (c == '%')
2831 {
2832 int i;
2833 switch (c = *edit_value++)
2834 {
2835 case 'd':
2836 if (ddone)
2837 FATAL ("call_edit: `%%d' appears twice in editor command");
2838 sprintf (temp, "%ld", (long int)linenumber);
2839 while (*temp != '\0')
2840 temp++;
2841 ddone = 1;
2842 break;
2843
2844 case 's':
2845 if (sdone)
2846 FATAL ("call_edit: `%%s' appears twice in editor command");
2847 for (i =0; i < fnlength; i++)
2848 *temp++ = Xchr (filename[i]);
2849 sdone = 1;
2850 break;
2851
2852 case '\0':
2853 *temp++ = '%';
2854 /* Back up to the null to force termination. */
2855 edit_value--;
2856 break;
2857
2858 default:
2859 *temp++ = '%';
2860 *temp++ = c;
2861 break;
2862 }
2863 }
2864 else {
2865 #ifdef WIN32
2866 if (dontchange)
2867 *temp++ = c;
2868 else { if(Isspace(c) && cnt == 0) {
2869 cnt++;
2870 temp = command;
2871 *temp++ = c;
2872 *fp = '\0';
2873 } else if(!Isspace(c) && cnt == 0) {
2874 *fp++ = c;
2875 } else {
2876 *temp++ = c;
2877 }
2878 }
2879 #else
2880 *temp++ = c;
2881 #endif
2882 }
2883 }
2884
2885 *temp = 0;
2886
2887 #ifdef WIN32
2888 if (dontchange == 0) {
2889 if(editorname[0] == '.' ||
2890 editorname[0] == '/' ||
2891 editorname[0] == '\\') {
2892 fprintf(stderr, "%s is not allowed to execute.\n", editorname);
2893 uexit(1);
2894 }
2895 env = (char *)getenv("PATH");
2896 if(SearchPath(env, editorname, ".exe", 256, buffer, &ffp)==0) {
2897 if(SearchPath(env, editorname, ".bat", 256, buffer, &ffp)==0) {
2898 fprintf(stderr, "I cannot find %s in the PATH.\n", editorname);
2899 uexit(1);
2900 }
2901 }
2902 fullcmd = (char *)xmalloc(strlen(buffer)+strlen(command)+5);
2903 strcpy(fullcmd, "\"");
2904 strcat(fullcmd, buffer);
2905 strcat(fullcmd, "\"");
2906 strcat(fullcmd, command);
2907 } else
2908 #endif
2909 fullcmd = command;
2910
2911 /* Execute the command. */
2912 if (system (fullcmd) != 0)
2913 fprintf (stderr, "! Trouble executing `%s'.\n", command);
2914
2915 /* Quit, since we found an error. */
2916 uexit (1);
2917 }
2918
2919 /* Read and write dump files. As distributed, these files are
2920 architecture dependent; specifically, BigEndian and LittleEndian
2921 architectures produce different files. These routines always output
2922 BigEndian files. This still does not guarantee them to be
2923 architecture-independent, because it is possible to make a format
2924 that dumps a glue ratio, i.e., a floating-point number. Fortunately,
2925 none of the standard formats do that. */
2926
2927 #if !defined (WORDS_BIGENDIAN) && !defined (NO_DUMP_SHARE) /* this fn */
2928
2929 /* This macro is always invoked as a statement. It assumes a variable
2930 `temp'. */
2931
2932 #define SWAP(x, y) temp = (x); (x) = (y); (y) = temp
2933
2934
2935 /* Make the NITEMS items pointed at by P, each of size SIZE, be the
2936 opposite-endianness of whatever they are now. */
2937
2938 static void
2939 swap_items (char *p, int nitems, int size)
2940 {
2941 char temp;
2942
2943 /* Since `size' does not change, we can write a while loop for each
2944 case, and avoid testing `size' for each time. */
2945 switch (size)
2946 {
2947 /* 16-byte items happen on the DEC Alpha machine when we are not
2948 doing sharable memory dumps. */
2949 case 16:
2950 while (nitems--)
2951 {
2952 SWAP (p[0], p[15]);
2953 SWAP (p[1], p[14]);
2954 SWAP (p[2], p[13]);
2955 SWAP (p[3], p[12]);
2956 SWAP (p[4], p[11]);
2957 SWAP (p[5], p[10]);
2958 SWAP (p[6], p[9]);
2959 SWAP (p[7], p[8]);
2960 p += size;
2961 }
2962 break;
2963
2964 case 8:
2965 while (nitems--)
2966 {
2967 SWAP (p[0], p[7]);
2968 SWAP (p[1], p[6]);
2969 SWAP (p[2], p[5]);
2970 SWAP (p[3], p[4]);
2971 p += size;
2972 }
2973 break;
2974
2975 case 4:
2976 while (nitems--)
2977 {
2978 SWAP (p[0], p[3]);
2979 SWAP (p[1], p[2]);
2980 p += size;
2981 }
2982 break;
2983
2984 case 2:
2985 while (nitems--)
2986 {
2987 SWAP (p[0], p[1]);
2988 p += size;
2989 }
2990 break;
2991
2992 case 1:
2993 /* Nothing to do. */
2994 break;
2995
2996 default:
2997 FATAL1 ("Can't swap a %d-byte item for (un)dumping", size);
2998 }
2999 }
3000 #endif /* not WORDS_BIGENDIAN and not NO_DUMP_SHARE */
3001
3002
3003 /* Here we write NITEMS items, each item being ITEM_SIZE bytes long.
3004 The pointer to the stuff to write is P, and we write to the file
3005 OUT_FILE. */
3006
3007 void
3008 #ifdef FMT_COMPRESS
3009 do_dump (char *p, int item_size, int nitems, gzFile out_file)
3010 #else
3011 do_dump (char *p, int item_size, int nitems, FILE *out_file)
3012 #endif
3013 {
3014 #if !defined (WORDS_BIGENDIAN) && !defined (NO_DUMP_SHARE)
3015 swap_items (p, nitems, item_size);
3016 #endif
3017
3018 #ifdef FMT_COMPRESS
3019 if (gzwrite (out_file, p, item_size * nitems) != item_size * nitems)
3020 #else
3021 if (fwrite (p, item_size, nitems, out_file) != nitems)
3022 #endif
3023 {
3024 fprintf (stderr, "! Could not write %d %d-byte item(s) to %s.\n",
3025 nitems, item_size, nameoffile+1);
3026 uexit (1);
3027 }
3028
3029 /* Have to restore the old contents of memory, since some of it might
3030 get used again. */
3031 #if !defined (WORDS_BIGENDIAN) && !defined (NO_DUMP_SHARE)
3032 swap_items (p, nitems, item_size);
3033 #endif
3034 }
3035
3036
3037 /* Here is the dual of the writing routine. */
3038
3039 void
3040 #ifdef FMT_COMPRESS
3041 do_undump (char *p, int item_size, int nitems, gzFile in_file)
3042 #else
3043 do_undump (char *p, int item_size, int nitems, FILE *in_file)
3044 #endif
3045 {
3046 #ifdef FMT_COMPRESS
3047 if (gzread (in_file, p, item_size * nitems) != item_size * nitems)
3048 #else
3049 if (fread (p, item_size, nitems, in_file) != (size_t) nitems)
3050 #endif
3051 FATAL3 ("Could not undump %d %d-byte item(s) from %s",
3052 nitems, item_size, nameoffile+1);
3053
3054 #if !defined (WORDS_BIGENDIAN) && !defined (NO_DUMP_SHARE)
3055 swap_items (p, nitems, item_size);
3056 #endif
3057 }
3058
3059 /* Some (most?) of this could be moved to the WEB side, but oh well. */
3060 #if defined(TeX) || defined(MF)
3061 #if !defined(pdfTeX)
3062 static void
3063 checkpoolpointer (poolpointer poolptr, size_t len)
3064 {
3065 if (poolptr + len >= poolsize) {
3066 fprintf (stderr, "\nstring pool overflow [%i bytes]\n",
3067 (int)poolsize); /* fixme */
3068 exit(1);
3069 }
3070 }
3071
3072 #ifndef XeTeX /* XeTeX uses this from XeTeX_ext.c */
3073 static
3074 #endif
3075 int
3076 maketexstring(const_string s)
3077 {
3078 size_t len;
3079 #ifdef XeTeX
3080 UInt32 rval;
3081 const unsigned char *cp = (const unsigned char *)s;
3082 #endif
3083 #if defined(TeX)
3084 if (s == NULL || *s == 0)
3085 return getnullstr();
3086 #else
3087 assert (s != 0);
3088 #endif
3089 len = strlen(s);
3090 checkpoolpointer (poolptr, len); /* in the XeTeX case, this may be more than enough */
3091 #ifdef XeTeX
3092 while ((rval = *(cp++)) != 0) {
3093 UInt16 extraBytes = bytesFromUTF8[rval];
3094 switch (extraBytes) { /* note: code falls through cases! */
3095 case 5: rval <<= 6; if (*cp) rval += *(cp++);
3096 case 4: rval <<= 6; if (*cp) rval += *(cp++);
3097 case 3: rval <<= 6; if (*cp) rval += *(cp++);
3098 case 2: rval <<= 6; if (*cp) rval += *(cp++);
3099 case 1: rval <<= 6; if (*cp) rval += *(cp++);
3100 case 0: ;
3101 };
3102 rval -= offsetsFromUTF8[extraBytes];
3103 if (rval > 0xffff) {
3104 rval -= 0x10000;
3105 strpool[poolptr++] = 0xd800 + rval / 0x0400;
3106 strpool[poolptr++] = 0xdc00 + rval % 0x0400;
3107 }
3108 else
3109 strpool[poolptr++] = rval;
3110 }
3111 #else /* ! XeTeX */
3112 while (len-- > 0)
3113 strpool[poolptr++] = 0xFF&(*s++);
3114 #endif /* ! XeTeX */
3115
3116 return makestring();
3117 }
3118 #endif /* !pdfTeX */
3119
3120 strnumber
3121 makefullnamestring(void)
3122 {
3123 return maketexstring(fullnameoffile);
3124 }
3125
3126 /* Get the job name to be used, which may have been set from the
3127 command line. */
3128 strnumber
3129 getjobname(strnumber name)
3130 {
3131 strnumber ret = name; int i, l, p;
3132 if (c_job_name != NULL)
3133 #if IS_pTeX && !defined(WIN32)
3134 {
3135 string new_job_name;
3136 is_terminalUTF8();
3137 new_job_name = ptenc_from_utf8_string_to_internal_enc(c_job_name);
3138 ret = maketexstring(new_job_name? new_job_name : c_job_name);
3139 }
3140 #else
3141 ret = maketexstring(c_job_name);
3142 #endif
3143 #if IS_pTeX
3144 i = strstart[ret]; l = strstart[ret+1];
3145 while (i<l)
3146 {
3147 p = multistrlenshort(strpool, l, i);
3148 if (p>1) {
3149 int j;
3150 for (j=i+p; i<j; i++) strpool[i] = (0xFF&strpool[i])+0x100;
3151 } else i++;
3152 }
3153 #endif /* IS_pTeX */
3154 return ret;
3155 }
3156 #endif
3157
3158 #if defined(TeX)
3159 static int
3160 compare_paths (const_string p1, const_string p2)
3161 {
3162 int ret;
3163 while (
3164 #ifdef MONOCASE_FILENAMES
3165 (((ret = (toupper(*p1) - toupper(*p2))) == 0) && (*p2 != 0))
3166 #else
3167 (((ret = (*p1 - *p2)) == 0) && (*p2 != 0))
3168 #endif
3169 || (IS_DIR_SEP(*p1) && IS_DIR_SEP(*p2))) {
3170 p1++, p2++;
3171 }
3172 ret = (ret < 0 ? -1 : (ret > 0 ? 1 : 0));
3173 return ret;
3174 }
3175
3176 #ifdef XeTeX /* the string pool is UTF-16 but we want a UTF-8 string */
3177
3178 string
3179 gettexstring (strnumber s)
3180 {
3181 unsigned bytesToWrite = 0;
3182 poolpointer len, i, j;
3183 string name;
3184 if (s >= 65536L)
3185 len = strstart[s + 1 - 65536L] - strstart[s - 65536L];
3186 else
3187 len = 0;
3188 name = xmalloc(len * 3 + 1); /* max UTF16->UTF8 expansion
3189 (code units, not bytes) */
3190 for (i = 0, j = 0; i < len; i++) {
3191 unsigned c = strpool[i + strstart[s - 65536L]];
3192 if (c >= 0xD800 && c <= 0xDBFF) {
3193 unsigned lo = strpool[++i + strstart[s - 65536L]];
3194 if (lo >= 0xDC00 && lo <= 0xDFFF)
3195 c = 0x10000 + (c - 0xD800) * 0x0400 + lo - 0xDC00;
3196 else
3197 c = 0xFFFD;
3198 }
3199 if (c < 0x80)
3200 bytesToWrite = 1;
3201 else if (c < 0x800)
3202 bytesToWrite = 2;
3203 else if (c < 0x10000)
3204 bytesToWrite = 3;
3205 else if (c < 0x110000)
3206 bytesToWrite = 4;
3207 else {
3208 bytesToWrite = 3;
3209 c = 0xFFFD;
3210 }
3211
3212 j += bytesToWrite;
3213 switch (bytesToWrite) { /* note: everything falls through. */
3214 case 4: name[--j] = ((c | 0x80) & 0xBF); c >>= 6;
3215 case 3: name[--j] = ((c | 0x80) & 0xBF); c >>= 6;
3216 case 2: name[--j] = ((c | 0x80) & 0xBF); c >>= 6;
3217 case 1: name[--j] = (c | firstByteMark[bytesToWrite]);
3218 }
3219 j += bytesToWrite;
3220 }
3221 name[j] = 0;
3222 return name;
3223 }
3224
3225 #else
3226
3227 string
3228 gettexstring (strnumber s)
3229 {
3230 poolpointer len;
3231 string name;
3232 #if !defined(Aleph)
3233 len = strstart[s + 1] - strstart[s];
3234 #else
3235 len = strstartar[s + 1 - 65536L] - strstartar[s - 65536L];
3236 #endif
3237 name = (string)xmalloc (len + 1);
3238 #if !defined(Aleph) && !IS_pTeX
3239 strncpy (name, (string)&strpool[strstart[s]], len);
3240 #else
3241 {
3242 poolpointer i;
3243 /* Don't use strncpy. The strpool is not made up of chars. */
3244 #if IS_pTeX
3245 for (i=0; i<len; i++) name[i] = 0xFF&strpool[i+strstart[s]];
3246 #else
3247 for (i=0; i<len; i++) name[i] = strpool[i+strstartar[s - 65536L]];
3248 #endif
3249 }
3250 #endif
3251 name[len] = 0;
3252 return name;
3253 }
3254
3255 #endif /* not XeTeX */
3256
3257 boolean
3258 isnewsource (strnumber srcfilename, int lineno)
3259 {
3260 char *name = gettexstring(srcfilename);
3261 return (compare_paths(name, last_source_name) != 0 || lineno != last_lineno);
3262 }
3263
3264 void
3265 remembersourceinfo (strnumber srcfilename, int lineno)
3266 {
3267 if (last_source_name)
3268 free(last_source_name);
3269 last_source_name = gettexstring(srcfilename);
3270 last_lineno = lineno;
3271 }
3272
3273 poolpointer
3274 makesrcspecial (strnumber srcfilename, int lineno)
3275 {
3276 poolpointer oldpoolptr = poolptr;
3277 char *filename = gettexstring(srcfilename);
3278 /* FIXME: Magic number. */
3279 char buf[40];
3280 char *s = buf;
3281
3282 /* Always put a space after the number, which makes things easier
3283 * to parse.
3284 */
3285 sprintf (buf, "src:%d ", lineno);
3286
3287 if (poolptr + strlen(buf) + strlen(filename) >= (size_t)poolsize) {
3288 fprintf (stderr, "\nstring pool overflow\n"); /* fixme */
3289 exit (1);
3290 }
3291 s = buf;
3292 while (*s)
3293 strpool[poolptr++] = *s++;
3294
3295 s = filename;
3296 while (*s)
3297 strpool[poolptr++] = *s++;
3298
3299 return (oldpoolptr);
3300 }
3301
3302 /* pdfTeX routines also used for e-pTeX, e-upTeX, and XeTeX */
3303 #if defined (pdfTeX) || defined (epTeX) || defined (eupTeX) || defined(XeTeX)
3304
3305 #include <kpathsea/c-stat.h>
3306 #include "md5.h"
3307
3308 #define check_nprintf(size_get, size_want) \
3309 if ((unsigned)(size_get) >= (unsigned)(size_want)) \
3310 pdftex_fail ("snprintf failed: file %s, line %d", __FILE__, __LINE__);
3311 # define check_buf(size, buf_size) \
3312 if ((unsigned)(size) > (unsigned)(buf_size)) \
3313 pdftex_fail("buffer overflow at file %s, line %d", __FILE__, __LINE__ )
3314 # define xfree(p) do { if (p != NULL) free(p); p = NULL; } while (0)
3315 # define MAX_CSTRING_LEN 1024 * 1024
3316
3317 #if !defined (pdfTeX)
3318 # define PRINTF_BUF_SIZE 1024
3319 static char print_buf[PRINTF_BUF_SIZE];
3320
3321 /* Helper for pdftex_fail. */
3322 static void
3323 safe_print(const char *str)
3324 {
3325 const char *c;
3326 for (c = str; *c; ++c)
3327 print(*c);
3328 }
3329 /* pdftex_fail may be called when a buffer overflow has happened/is
3330 happening, therefore may not call mktexstring. However, with the
3331 current implementation it appears that error messages are misleading,
3332 possibly because pool overflows are detected too late.
3333
3334 The output format of this fuction must be the same as pdf_error in
3335 pdftex.web! */
3336 __attribute__ ((noreturn, format(printf, 1, 2)))
3337 void pdftex_fail(const char *fmt, ...)
3338 {
3339 va_list args;
3340 va_start(args, fmt);
3341 println();
3342 safe_print("!error: ");
3343 vsnprintf(print_buf, PRINTF_BUF_SIZE, fmt, args);
3344 safe_print(print_buf);
3345 va_end(args);
3346 println();
3347 safe_print(" ==> Fatal error occurred, output file will be damaged!");
3348 println();
3349 if (kpathsea_debug) {
3350 safe_print("kpathsea_debug enabled, calling abort()...");
3351 println();
3352 abort();
3353 } else {
3354 exit(EXIT_FAILURE);
3355 }
3356 }
3357 #endif /* not pdfTeX */
3358
3359 #define TIME_STR_SIZE 30
3360 char start_time_str[TIME_STR_SIZE];
3361 static char time_str[TIME_STR_SIZE];
3362 /* minimum size for time_str is 24: "D:YYYYmmddHHMMSS+HH'MM'" */
3363
3364 static void
3365 makepdftime(time_t t, char *time_str, boolean utc)
3366 {
3367 struct tm lt, gmt;
3368 size_t size;
3369 int i, off, off_hours, off_mins;
3370
3371 /* get the time */
3372 if (utc) {
3373 lt = *gmtime(&t);
3374 }
3375 else {
3376 lt = *localtime(&t);
3377 }
3378 size = strftime(time_str, TIME_STR_SIZE, "D:%Y%m%d%H%M%S", &lt);
3379 /* expected format: "YYYYmmddHHMMSS" */
3380 if (size == 0) {
3381 /* unexpected, contents of time_str is undefined */
3382 time_str[0] = '\0';
3383 return;
3384 }
3385
3386 /* correction for seconds: %S can be in range 00..61,
3387 the PDF reference expects 00..59,
3388 therefore we map "60" and "61" to "59" */
3389 if (time_str[14] == '6') {
3390 time_str[14] = '5';
3391 time_str[15] = '9';
3392 time_str[16] = '\0'; /* for safety */
3393 }
3394
3395 /* get the time zone offset */
3396 gmt = *gmtime(&t);
3397
3398 /* this calculation method was found in exim's tod.c */
3399 off = 60 * (lt.tm_hour - gmt.tm_hour) + lt.tm_min - gmt.tm_min;
3400 if (lt.tm_year != gmt.tm_year) {
3401 off += (lt.tm_year > gmt.tm_year) ? 1440 : -1440;
3402 } else if (lt.tm_yday != gmt.tm_yday) {
3403 off += (lt.tm_yday > gmt.tm_yday) ? 1440 : -1440;
3404 }
3405
3406 if (off == 0) {
3407 time_str[size++] = 'Z';
3408 time_str[size] = 0;
3409 } else {
3410 off_hours = off / 60;
3411 off_mins = abs(off - off_hours * 60);
3412 i = snprintf(&time_str[size], 9, "%+03d'%02d'", off_hours, off_mins);
3413 check_nprintf(i, 9);
3414 }
3415 }
3416
3417 void
3418 initstarttime(void)
3419 {
3420 if (!start_time_set) {
3421 init_start_time ();
3422 if (getenv ("SOURCE_DATE_EPOCH")) {
3423 makepdftime (start_time, start_time_str, /* utc= */true);
3424 } else {
3425 makepdftime (start_time, start_time_str, /* utc= */false);
3426 }
3427 }
3428 }
3429
3430 #if defined(_WIN32)
3431 #undef access
3432 #undef dir_p
3433 #define access fsyscp_access
3434 #define dir_p fsyscp_dir_p
3435 #endif /* _WIN32 */
3436
3437 /* Search for an input file. If -output-directory is specified look
3438 there first. If that fails, do the regular kpse search. */
3439 string
3440 find_input_file(integer s)
3441 {
3442 string filename;
3443 #if IS_pTeX && !defined(WIN32)
3444 string fname0; string fname1 = NULL;
3445 #endif
3446 #if defined(XeTeX)
3447 filename = gettexstring(s);
3448 #else
3449 filename = makecfilename(s);
3450 #endif
3451 #if IS_pTeX && !defined(WIN32)
3452 fname0 = ptenc_from_internal_enc_string_to_utf8(filename);
3453 if (fname0) {
3454 fname1 = filename; filename = fname0;
3455 }
3456 #endif
3457 /* Look in -output-directory first, if the filename is not
3458 absolute. This is because we want the pdf* functions to
3459 be able to find the same files as \openin. */
3460 if (output_directory && !kpse_absolute_p (filename, false)) {
3461 string pathname = concat3(output_directory, DIR_SEP_STRING, filename);
3462 /* If there happens to be a directory by that name, never mind. */
3463 if (access(pathname, R_OK) == 0 && !dir_p (pathname)) {
3464 #if IS_pTeX && !defined(WIN32)
3465 if (fname1) free(filename);
3466 #endif
3467 return pathname;
3468 }
3469 xfree (pathname);
3470 }
3471 if (! kpse_in_name_ok(filename)) {
3472 #if IS_pTeX && !defined(WIN32)
3473 if (fname1) free(filename);
3474 #endif
3475 return NULL; /* no permission */
3476 }
3477 #if IS_pTeX && !defined(WIN32)
3478 fname0 = kpse_find_tex(filename);
3479 if (fname1) free(filename);
3480 return fname0;
3481 #else
3482 return kpse_find_tex(filename);
3483 #endif
3484 }
3485
3486 #if !defined(XeTeX)
3487 char *
3488 makecstring(integer s)
3489 {
3490 static char *cstrbuf = NULL;
3491 char *p;
3492 static int allocsize;
3493 int allocgrow, i, l = strstart[s + 1] - strstart[s];
3494 check_buf(l + 1, MAX_CSTRING_LEN);
3495 if (cstrbuf == NULL) {
3496 allocsize = l + 1;
3497 cstrbuf = xmallocarray(char, allocsize);
3498 } else if (l + 1 > allocsize) {
3499 allocgrow = allocsize * 0.2;
3500 if (l + 1 - allocgrow > allocsize)
3501 allocsize = l + 1;
3502 else if (allocsize < MAX_CSTRING_LEN - allocgrow)
3503 allocsize += allocgrow;
3504 else
3505 allocsize = MAX_CSTRING_LEN;
3506 cstrbuf = xreallocarray(cstrbuf, char, allocsize);
3507 }
3508 p = cstrbuf;
3509 for (i = 0; i < l; i++)
3510 #if IS_pTeX
3511 *p++ = 0xFF&strpool[i + strstart[s]];
3512 #else
3513 *p++ = strpool[i + strstart[s]];
3514 #endif
3515 *p = 0;
3516 return cstrbuf;
3517 }
3518
3519 /* makecfilename
3520 input/ouput same as makecstring:
3521 input: string number
3522 output: C string with quotes removed.
3523 That means, file names that are legal on some operation systems
3524 cannot any more be used since pdfTeX version 1.30.4.
3525 */
3526 char *
3527 makecfilename(integer s)
3528 {
3529 char *name = makecstring(s);
3530 char *p = name;
3531 char *q = name;
3532
3533 while (*p) {
3534 if (*p != '"')
3535 *q++ = *p;
3536 p++;
3537 }
3538 *q = '\0';
3539 return name;
3540 }
3541 #endif /* !XeTeX */
3542
3543 void
3544 getcreationdate(void)
3545 {
3546 size_t len;
3547 #if defined(XeTeX) || IS_pTeX
3548 int i;
3549 #endif
3550 initstarttime();
3551 /* put creation date on top of string pool and update poolptr */
3552 len = strlen(start_time_str);
3553
3554 /* In e-pTeX, "init len => call initstarttime()" (as pdftexdir/utils.c)
3555 yields unintentional output. */
3556
3557 if ((unsigned) (poolptr + len) >= (unsigned) (poolsize)) {
3558 poolptr = poolsize;
3559 /* error by str_toks that calls str_room(1) */
3560 return;
3561 }
3562
3563 #if defined(XeTeX) || IS_pTeX
3564 for (i = 0; i < len; i++)
3565 strpool[poolptr++] = (uint16_t)start_time_str[i];
3566 #else
3567 memcpy(&strpool[poolptr], start_time_str, len);
3568 poolptr += len;
3569 #endif
3570 }
3571
3572 void
3573 getfilemoddate(integer s)
3574 {
3575 struct stat file_data;
3576
3577 char *file_name = find_input_file(s);
3578 if (file_name == NULL) {
3579 return; /* empty string */
3580 }
3581
3582 recorder_record_input(file_name);
3583 /* get file status */
3584 #ifdef _WIN32
3585 if (fsyscp_stat(file_name, &file_data) == 0) {
3586 #else
3587 if (stat(file_name, &file_data) == 0) {
3588 #endif
3589 size_t len;
3590 boolean use_utc = FORCE_SOURCE_DATE_set && SOURCE_DATE_EPOCH_set;
3591 makepdftime(file_data.st_mtime, time_str, use_utc);
3592 len = strlen(time_str);
3593 if ((unsigned) (poolptr + len) >= (unsigned) (poolsize)) {
3594 poolptr = poolsize;
3595 /* error by str_toks that calls str_room(1) */
3596 } else {
3597 #if defined(XeTeX) || IS_pTeX
3598 int i;
3599
3600 for (i = 0; i < len; i++)
3601 strpool[poolptr++] = (uint16_t)time_str[i];
3602 #else
3603 memcpy(&strpool[poolptr], time_str, len);
3604 poolptr += len;
3605 #endif
3606 }
3607 }
3608 /* else { errno contains error code } */
3609
3610 xfree(file_name);
3611 }
3612
3613 void
3614 getfilesize(integer s)
3615 {
3616 struct stat file_data;
3617 int i;
3618
3619 char *file_name = find_input_file(s);
3620 if (file_name == NULL) {
3621 return; /* empty string */
3622 }
3623
3624 recorder_record_input(file_name);
3625 /* get file status */
3626 #ifdef _WIN32
3627 if (fsyscp_stat(file_name, &file_data) == 0) {
3628 #else
3629 if (stat(file_name, &file_data) == 0) {
3630 #endif
3631 size_t len;
3632 char buf[20];
3633
3634 /* st_size has type off_t */
3635 i = snprintf(buf, sizeof(buf),
3636 "%lu", (long unsigned int) file_data.st_size);
3637 check_nprintf(i, sizeof(buf));
3638 len = strlen(buf);
3639 if ((unsigned) (poolptr + len) >= (unsigned) (poolsize)) {
3640 poolptr = poolsize;
3641 /* error by str_toks that calls str_room(1) */
3642 } else {
3643 #if defined(XeTeX) || IS_pTeX
3644 for (i = 0; i < len; i++)
3645 strpool[poolptr++] = (uint16_t)buf[i];
3646 #else
3647 memcpy(&strpool[poolptr], buf, len);
3648 poolptr += len;
3649 #endif
3650 }
3651 }
3652 /* else { errno contains error code } */
3653
3654 xfree(file_name);
3655 }
3656
3657 void
3658 getfiledump(integer s, int offset, int length)
3659 {
3660 FILE *f;
3661 int read, i;
3662 #if defined(XeTeX) || IS_pTeX
3663 unsigned char *readbuffer;
3664 char strbuf[3];
3665 int j, k;
3666 #else
3667 poolpointer data_ptr;
3668 poolpointer data_end;
3669 #endif /* XeTeX || IS_pTeX */
3670 char *file_name;
3671
3672 if (length == 0) {
3673 /* empty result string */
3674 return;
3675 }
3676
3677 if (poolptr + 2 * length + 1 >= poolsize) {
3678 /* no place for result */
3679 poolptr = poolsize;
3680 /* error by str_toks that calls str_room(1) */
3681 return;
3682 }
3683
3684 file_name = find_input_file(s);
3685 if (file_name == NULL) {
3686 return; /* empty string */
3687 }
3688
3689 /* read file data */
3690 f = fopen(file_name, FOPEN_RBIN_MODE);
3691 if (f == NULL) {
3692 xfree(file_name);
3693 return;
3694 }
3695 recorder_record_input(file_name);
3696 if (fseek(f, offset, SEEK_SET) != 0) {
3697 xfree(file_name);
3698 return;
3699 }
3700 #if defined(XeTeX) || IS_pTeX
3701 readbuffer = (unsigned char *)xmalloc (length + 1);
3702 read = fread(readbuffer, sizeof(char), length, f);
3703 fclose(f);
3704 for (j = 0; j < read; j++) {
3705 i = snprintf (strbuf, 3, "%.2X", (unsigned int)readbuffer[j]);
3706 check_nprintf(i, 3);
3707 for (k = 0; k < i; k++)
3708 strpool[poolptr++] = (uint16_t)strbuf[k];
3709 }
3710 xfree (readbuffer);
3711 #else
3712 /* there is enough space in the string pool, the read
3713 data are put in the upper half of the result, thus
3714 the conversion to hex can be done without overwriting
3715 unconverted bytes. */
3716 data_ptr = poolptr + length;
3717 read = fread(&strpool[data_ptr], sizeof(char), length, f);
3718 fclose(f);
3719
3720 /* convert to hex */
3721 data_end = data_ptr + read;
3722 for (; data_ptr < data_end; data_ptr++) {
3723 i = snprintf((char *) &strpool[poolptr], 3,
3724 "%.2X", (unsigned int) strpool[data_ptr]);
3725 check_nprintf(i, 3);
3726 poolptr += i;
3727 }
3728 #endif /* XeTeX || IS_pTeX */
3729 xfree(file_name);
3730 }
3731
3732 /* Converts any given string in into an allowed PDF string which is
3733 * hexadecimal encoded;
3734 * sizeof(out) should be at least lin*2+1.
3735 */
3736 void
3737 convertStringToHexString(const char *in, char *out, int lin)
3738 {
3739 int i, j, k;
3740 char buf[3];
3741 j = 0;
3742 for (i = 0; i < lin; i++) {
3743 k = snprintf(buf, sizeof(buf),
3744 "%02X", (unsigned int) (unsigned char) in[i]);
3745 check_nprintf(k, sizeof(buf));
3746 out[j++] = buf[0];
3747 out[j++] = buf[1];
3748 }
3749 out[j] = '\0';
3750 }
3751
3752 #define DIGEST_SIZE 16
3753 #define FILE_BUF_SIZE 1024
3754
3755 void
3756 getmd5sum(strnumber s, boolean file)
3757 {
3758 md5_state_t state;
3759 md5_byte_t digest[DIGEST_SIZE];
3760 char outbuf[2 * DIGEST_SIZE + 1];
3761 int len = 2 * DIGEST_SIZE;
3762 #if defined(XeTeX) || IS_pTeX
3763 char *xname;
3764 int i;
3765 #endif
3766
3767 if (file) {
3768 char file_buf[FILE_BUF_SIZE];
3769 int read = 0;
3770 FILE *f;
3771 char *file_name;
3772
3773 file_name = find_input_file(s);
3774 if (file_name == NULL) {
3775 return; /* empty string */
3776 }
3777
3778 /* in case of error the empty string is returned,
3779 no need for xfopen that aborts on error.
3780 */
3781 f = fopen(file_name, FOPEN_RBIN_MODE);
3782 if (f == NULL) {
3783 xfree(file_name);
3784 return;
3785 }
3786 recorder_record_input(file_name);
3787 md5_init(&state);
3788 while ((read = fread(&file_buf, sizeof(char), FILE_BUF_SIZE, f)) > 0) {
3789 md5_append(&state, (const md5_byte_t *) file_buf, read);
3790 }
3791 md5_finish(&state, digest);
3792 fclose(f);
3793
3794 xfree(file_name);
3795 } else {
3796 /* s contains the data */
3797 md5_init(&state);
3798 #if defined(XeTeX) || IS_pTeX
3799 xname = gettexstring (s);
3800 md5_append(&state,
3801 (md5_byte_t *) xname,
3802 strlen (xname));
3803 xfree (xname);
3804 #else
3805 md5_append(&state,
3806 (md5_byte_t *) &strpool[strstart[s]],
3807 strstart[s + 1] - strstart[s]);
3808 #endif
3809 md5_finish(&state, digest);
3810 }
3811
3812 if (poolptr + len >= poolsize) {
3813 /* error by str_toks that calls str_room(1) */
3814 return;
3815 }
3816 convertStringToHexString((char *) digest, outbuf, DIGEST_SIZE);
3817 #if defined(XeTeX) || IS_pTeX
3818 for (i = 0; i < 2 * DIGEST_SIZE; i++)
3819 strpool[poolptr++] = (uint16_t)outbuf[i];
3820 #else
3821 memcpy(&strpool[poolptr], outbuf, len);
3822 poolptr += len;
3823 #endif
3824 }
3825
3826 #endif /* pdfTeX or e-pTeX or e-upTeX or XeTeX */
3827 #endif /* TeX */
3828
3829 /* Metafont/MetaPost fraction routines. Replaced either by assembler or C.
3830 The assembler syntax doesn't work on Solaris/x86. */
3831 #ifndef TeX
3832 #if defined (__sun__) || defined (__cplusplus)
3833 #define NO_MF_ASM
3834 #endif
3835 /* The assembler code is not PIC safe on i?86 so use C code. */
3836 #if defined (__PIC__) && defined (__i386__)
3837 #define NO_MF_ASM
3838 #endif
3839 #if defined(WIN32) && !defined(NO_MF_ASM) && !defined(__MINGW32__)
3840 #include "lib/mfmpw32.c"
3841 #elif defined (__i386__) && defined (__GNUC__) && !defined (NO_MF_ASM)
3842 #include "lib/mfmpi386.asm"
3843 #else
3844 /* Replace fixed-point fraction routines from mf.web and mp.web with
3845 Hobby's floating-point C code. */
3846
3847 /****************************************************************
3848 Copyright 1990 - 1995 by AT&T Bell Laboratories.
3849
3850 Permission to use, copy, modify, and distribute this software
3851 and its documentation for any purpose and without fee is hereby
3852 granted, provided that the above copyright notice appear in all
3853 copies and that both that the copyright notice and this
3854 permission notice and warranty disclaimer appear in supporting
3855 documentation, and that the names of AT&T Bell Laboratories or
3856 any of its entities not be used in advertising or publicity
3857 pertaining to distribution of the software without specific,
3858 written prior permission.
3859
3860 AT&T disclaims all warranties with regard to this software,
3861 including all implied warranties of merchantability and fitness.
3862 In no event shall AT&T be liable for any special, indirect or
3863 consequential damages or any damages whatsoever resulting from
3864 loss of use, data or profits, whether in an action of contract,
3865 negligence or other tortious action, arising out of or in
3866 connection with the use or performance of this software.
3867 ****************************************************************/
3868
3869 /**********************************************************
3870 The following is by John Hobby
3871 **********************************************************/
3872
3873 #ifndef FIXPT
3874
3875 /* These replacements for takefraction, makefraction, takescaled, makescaled
3876 run about 3 to 11 times faster than the standard versions on modern machines
3877 that have fast hardware for double-precision floating point. They should
3878 produce approximately correct results on all machines and agree exactly
3879 with the standard versions on machines that satisfy the following conditions:
3880 1. Doubles must have at least 46 mantissa bits; i.e., numbers expressible
3881 as n*2^k with abs(n)<2^46 should be representable.
3882 2. The following should hold for addition, subtraction, and multiplcation but
3883 not necessarily for division:
3884 A. If the true answer is between two representable numbers, the computed
3885 answer must be one of them.
3886 B. When the true answer is representable, this must be the computed result.
3887 3. Dividing one double by another should always produce a relative error of
3888 at most one part in 2^46. (This is why the mantissa requirement is
3889 46 bits instead of 45 bits.)
3890 3. In the absence of overflow, double-to-integer conversion should truncate
3891 toward zero and do this in an exact fashion.
3892 4. Integer-to-double convesion should produce exact results.
3893 5. Dividing one power of two by another should yield an exact result.
3894 6. ASCII to double conversion should be exact for integer values.
3895 7. Integer arithmetic must be done in the two's-complement system.
3896 */
3897 #define ELGORDO 0x7fffffff
3898 #define TWEXP31 2147483648.0
3899 #define TWEXP28 268435456.0
3900 #define TWEXP16 65536.0
3901 #define TWEXP_16 (1.0/65536.0)
3902 #define TWEXP_28 (1.0/268435456.0)
3903
3904 integer
3905 ztakefraction (integer p, integer q) /* Approximate p*q/2^28 */
3906 { register double d;
3907 register integer i;
3908 d = (double)p * (double)q * TWEXP_28;
3909 if ((p^q) >= 0) {
3910 d += 0.5;
3911 if (d>=TWEXP31) {
3912 if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
3913 aritherror = true;
3914 return ELGORDO;
3915 }
3916 i = (integer) d;
3917 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
3918 } else {
3919 d -= 0.5;
3920 if (d<= -TWEXP31) {
3921 if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
3922 aritherror = true;
3923 return -ELGORDO;
3924 }
3925 i = (integer) d;
3926 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
3927 }
3928 return i;
3929 }
3930
3931 integer
3932 ztakescaled (integer p, integer q) /* Approximate p*q/2^16 */
3933 { register double d;
3934 register integer i;
3935 d = (double)p * (double)q * TWEXP_16;
3936 if ((p^q) >= 0) {
3937 d += 0.5;
3938 if (d>=TWEXP31) {
3939 if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
3940 aritherror = true;
3941 return ELGORDO;
3942 }
3943 i = (integer) d;
3944 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
3945 } else {
3946 d -= 0.5;
3947 if (d<= -TWEXP31) {
3948 if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
3949 aritherror = true;
3950 return -ELGORDO;
3951 }
3952 i = (integer) d;
3953 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
3954 }
3955 return i;
3956 }
3957
3958 /* Note that d cannot exactly equal TWEXP31 when the overflow test is made
3959 because the exact value of p/q cannot be strictly between (2^31-1)/2^28
3960 and 8/1. No pair of integers less than 2^31 has such a ratio.
3961 */
3962 integer
3963 zmakefraction (integer p, integer q) /* Approximate 2^28*p/q */
3964 { register double d;
3965 register integer i;
3966 #ifdef DEBUG
3967 if (q==0) confusion(47);
3968 #endif /* DEBUG */
3969 d = TWEXP28 * (double)p /(double)q;
3970 if ((p^q) >= 0) {
3971 d += 0.5;
3972 if (d>=TWEXP31) {aritherror=true; return ELGORDO;}
3973 i = (integer) d;
3974 if (d==i && ( ((q>0 ? -q : q)&077777)
3975 * (((i&037777)<<1)-1) & 04000)!=0) --i;
3976 } else {
3977 d -= 0.5;
3978 if (d<= -TWEXP31) {aritherror=true; return -ELGORDO;}
3979 i = (integer) d;
3980 if (d==i && ( ((q>0 ? q : -q)&077777)
3981 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
3982 }
3983 return i;
3984 }
3985
3986 /* Note that d cannot exactly equal TWEXP31 when the overflow test is made
3987 because the exact value of p/q cannot be strictly between (2^31-1)/2^16
3988 and 2^15/1. No pair of integers less than 2^31 has such a ratio.
3989 */
3990 integer
3991 zmakescaled (integer p, integer q) /* Approximate 2^16*p/q */
3992 { register double d;
3993 register integer i;
3994 #ifdef DEBUG
3995 if (q==0) confusion(47);
3996 #endif /* DEBUG */
3997 d = TWEXP16 * (double)p /(double)q;
3998 if ((p^q) >= 0) {
3999 d += 0.5;
4000 if (d>=TWEXP31) {aritherror=true; return ELGORDO;}
4001 i = (integer) d;
4002 if (d==i && ( ((q>0 ? -q : q)&077777)
4003 * (((i&037777)<<1)-1) & 04000)!=0) --i;
4004 } else {
4005 d -= 0.5;
4006 if (d<= -TWEXP31) {aritherror=true; return -ELGORDO;}
4007 i = (integer) d;
4008 if (d==i && ( ((q>0 ? q : -q)&077777)
4009 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
4010 }
4011 return i;
4012 }
4013
4014 #endif /* not FIXPT */
4015 #endif /* not assembler */
4016 #endif /* not TeX, i.e., MF */
4017
4018 #ifdef MF
4019 /* On-line display routines for Metafont. Here we use a dispatch table
4020 indexed by the MFTERM or TERM environment variable to select the
4021 graphics routines appropriate to the user's terminal. stdout must be
4022 connected to a terminal for us to do any graphics. */
4023
4024 #ifdef MFNOWIN
4025 #undef AMIGAWIN
4026 #undef EPSFWIN
4027 #undef HP2627WIN
4028 #undef MFTALKWIN
4029 #undef NEXTWIN
4030 #undef REGISWIN
4031 #undef SUNWIN
4032 #undef TEKTRONIXWIN
4033 #undef UNITERMWIN
4034 #undef WIN32WIN
4035 #undef X11WIN
4036 #endif
4037
4038 /* Prototypes for Metafont display routines: mf_XXX_initscreen,
4039 mf_XXX_updatescreen, mf_XXX_blankrectangle, and mf_XXX_paintrow. */
4040 #include <window/mfdisplay.h>
4041
4042 /* This variable, `mfwsw', contains the dispatch tables for each
4043 terminal. We map the Pascal calls to the routines `init_screen',
4044 `update_screen', `blank_rectangle', and `paint_row' into the
4045 appropriate entry point for the specific terminal that MF is being
4046 run on. */
4047
4048 struct mfwin_sw
4049 {
4050 const char *mfwsw_type; /* Name of terminal a la TERMCAP. */
4051 int (*mfwsw_initscreen) (void);
4052 void (*mfwsw_updatescrn) (void);
4053 void (*mfwsw_blankrect) (screencol, screencol, screenrow, screenrow);
4054 void (*mfwsw_paintrow) (screenrow, pixelcolor, transspec, screencol);
4055 } mfwsw[] =
4056 {
4057 #ifdef AMIGAWIN
4058 { "amiterm", mf_amiga_initscreen, mf_amiga_updatescreen,
4059 mf_amiga_blankrectangle, mf_amiga_paintrow },
4060 #endif
4061 #ifdef EPSFWIN
4062 { "epsf", mf_epsf_initscreen, mf_epsf_updatescreen,
4063 mf_epsf_blankrectangle, mf_epsf_paintrow },
4064 #endif
4065 #ifdef HP2627WIN
4066 { "hp2627", mf_hp2627_initscreen, mf_hp2627_updatescreen,
4067 mf_hp2627_blankrectangle, mf_hp2627_paintrow },
4068 #endif
4069 #ifdef MFTALKWIN
4070 { "mftalk", mf_mftalk_initscreen, mf_mftalk_updatescreen,
4071 mf_mftalk_blankrectangle, mf_mftalk_paintrow },
4072 #endif
4073 #ifdef NEXTWIN
4074 { "next", mf_next_initscreen, mf_next_updatescreen,
4075 mf_next_blankrectangle, mf_next_paintrow },
4076 #endif
4077 #ifdef REGISWIN
4078 { "regis", mf_regis_initscreen, mf_regis_updatescreen,
4079 mf_regis_blankrectangle, mf_regis_paintrow },
4080 #endif
4081 #ifdef SUNWIN
4082 { "sun", mf_sun_initscreen, mf_sun_updatescreen,
4083 mf_sun_blankrectangle, mf_sun_paintrow },
4084 #endif
4085 #ifdef TEKTRONIXWIN
4086 { "tek", mf_tektronix_initscreen, mf_tektronix_updatescreen,
4087 mf_tektronix_blankrectangle, mf_tektronix_paintrow },
4088 #endif
4089 #ifdef UNITERMWIN
4090 { "uniterm", mf_uniterm_initscreen, mf_uniterm_updatescreen,
4091 mf_uniterm_blankrectangle, mf_uniterm_paintrow },
4092 #endif
4093 #ifdef WIN32WIN
4094 { "win32term", mf_win32_initscreen, mf_win32_updatescreen,
4095 mf_win32_blankrectangle, mf_win32_paintrow },
4096 #endif
4097 #ifdef X11WIN
4098 { "xterm", mf_x11_initscreen, mf_x11_updatescreen,
4099 mf_x11_blankrectangle, mf_x11_paintrow },
4100 #endif
4101
4102 /* Always support this. */
4103 { "trap", mf_trap_initscreen, mf_trap_updatescreen,
4104 mf_trap_blankrectangle, mf_trap_paintrow },
4105
4106 /* Finally, we must have an entry with a terminal type of NULL. */
4107 { NULL, NULL, NULL, NULL, NULL }
4108
4109 }; /* End of the array initialization. */
4110
4111
4112 /* This is a pointer to the mfwsw[] entry that we find. */
4113 static struct mfwin_sw *mfwp;
4114
4115
4116 /* The following are routines that just jump to the correct
4117 terminal-specific graphics code. If none of the routines in the
4118 dispatch table exist, or they fail, we produce trap-compatible
4119 output, i.e., the same words and punctuation that the unchanged
4120 mf.web would produce. */
4121
4122
4123 /* This returns true if we can do window operations, else false. */
4124
4125 boolean
4126 initscreen (void)
4127 {
4128 int retval;
4129 /* If MFTERM is set, use it. */
4130 const_string tty_type = kpse_var_value ("MFTERM");
4131
4132 if (tty_type == NULL)
4133 {
4134 #if defined (AMIGA)
4135 tty_type = "amiterm";
4136 #elif defined (WIN32)
4137 tty_type = "win32term";
4138 #elif defined (OS2) || defined (__DJGPP__) /* not AMIGA nor WIN32 */
4139 tty_type = "mftalk";
4140 #else /* not (OS2 or WIN32 or __DJGPP__ or AMIGA) */
4141 /* If DISPLAY is set, we are X11; otherwise, who knows. */
4142 boolean have_display = getenv ("DISPLAY") != NULL;
4143 tty_type = have_display ? "xterm" : getenv ("TERM");
4144
4145 /* If we don't know what kind of terminal this is, or if Metafont
4146 isn't being run interactively, don't do any online output. */
4147 if (tty_type == NULL
4148 || (!STREQ (tty_type, "trap") && !isatty (fileno (stdout))))
4149 return 0;
4150 #endif /* not (OS2 or WIN32 or __DJGPP__ or AMIGA) */
4151 }
4152
4153 /* Test each of the terminals given in `mfwsw' against the terminal
4154 type, and take the first one that matches, or if the user is running
4155 under Emacs, the first one. */
4156 for (mfwp = mfwsw; mfwp->mfwsw_type != NULL; mfwp++) {
4157 if (!strncmp (mfwp->mfwsw_type, tty_type, strlen (mfwp->mfwsw_type))
4158 || STREQ (tty_type, "emacs")) {
4159 if (mfwp->mfwsw_initscreen) {
4160 retval = (*mfwp->mfwsw_initscreen) ();
4161 #ifdef WIN32
4162 Sleep(1000); /* Wait for opening a window */
4163 #endif
4164 return retval;
4165 }
4166 else {
4167 fprintf (stderr, "mf: Couldn't initialize online display for `%s'.\n",
4168 tty_type);
4169 break;
4170 }
4171 }
4172 }
4173
4174 /* The current terminal type wasn't found in any of the entries, or
4175 initalization failed, so silently give up, assuming that the user
4176 isn't on a terminal that supports graphic output. */
4177 return 0;
4178 }
4179
4180
4181 /* Make sure everything is visible. */
4182
4183 void
4184 updatescreen (void)
4185 {
4186 if (mfwp->mfwsw_updatescrn)
4187 (*mfwp->mfwsw_updatescrn) ();
4188 }
4189
4190
4191 /* This sets the rectangle bounded by ([left,right], [top,bottom]) to
4192 the background color. */
4193
4194 void
4195 blankrectangle (screencol left, screencol right,
4196 screenrow top, screenrow bottom)
4197 {
4198 if (mfwp->mfwsw_blankrect)
4199 (*mfwp->mfwsw_blankrect) (left, right, top, bottom);
4200 }
4201
4202
4203 /* This paints ROW, starting with the color INIT_COLOR.
4204 TRANSITION_VECTOR then specifies the length of the run; then we
4205 switch colors. This goes on for VECTOR_SIZE transitions. */
4206
4207 void
4208 paintrow (screenrow row, pixelcolor init_color,
4209 transspec transition_vector, screencol vector_size)
4210 {
4211 if (mfwp->mfwsw_paintrow)
4212 (*mfwp->mfwsw_paintrow) (row, init_color, transition_vector, vector_size);
4213 }
4214 #endif /* MF */