dvitomp fix from Akira
[mplib] / src / texk / kpathsea / tex-file.c
1 /* tex-file.c: high-level file searching by format.
2
3    Copyright 1993, 1994, 1995, 1996, 1997, 2007, 2008 Karl Berry.
4    Copyright 1998-2005 Olaf Weber.
5
6    This library is free software; you can redistribute it and/or
7    modify it under the terms of the GNU Lesser General Public
8    License as published by the Free Software Foundation; either
9    version 2.1 of the License, or (at your option) any later version.
10
11    This library is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14    Lesser General Public License for more details.
15
16    You should have received a copy of the GNU Lesser General Public License
17    along with this library; if not, see <http://www.gnu.org/licenses/>.  */
18
19 #include <kpathsea/config.h>
20
21 #include <kpathsea/c-fopen.h>
22 #include <kpathsea/c-pathch.h>
23 #include <kpathsea/c-vararg.h>
24 #include <kpathsea/cnf.h>
25 #include <kpathsea/concatn.h>
26 #include <kpathsea/default.h>
27 #include <kpathsea/expand.h>
28 #include <kpathsea/fontmap.h>
29 #include <kpathsea/paths.h>
30 #include <kpathsea/pathsearch.h>
31 #include <kpathsea/tex-file.h>
32 #include <kpathsea/tex-make.h>
33 #include <kpathsea/variable.h>
34
35
36 /* See tex-file.h.  */
37 const_string kpse_fallback_font = NULL;
38 const_string kpse_fallback_resolutions_string = NULL;
39 unsigned *kpse_fallback_resolutions = NULL;
40 kpse_format_info_type kpse_format_info[kpse_last_format];
41
42 /* These are not in the structure
43    because it's annoying to initialize lists in C.  */
44 #define GF_ENVS "GFFONTS", GLYPH_ENVS
45 #define PK_ENVS "PKFONTS", "TEXPKS", GLYPH_ENVS
46 #define GLYPH_ENVS "GLYPHFONTS", "TEXFONTS"
47 #define TFM_ENVS "TFMFONTS", "TEXFONTS"
48 #define AFM_ENVS "AFMFONTS", "TEXFONTS"
49 #define BASE_ENVS "MFBASES", "TEXMFINI"
50 #define BIB_ENVS "BIBINPUTS", "TEXBIB"
51 #define BST_ENVS "BSTINPUTS"
52 #define CNF_ENVS "TEXMFCNF"
53 #define DB_ENVS "TEXMFDBS"
54 #define FMT_ENVS "TEXFORMATS", "TEXMFINI"
55 #define FONTMAP_ENVS "TEXFONTMAPS", "TEXFONTS"
56 #define MEM_ENVS "MPMEMS", "TEXMFINI"
57 #define MF_ENVS "MFINPUTS"
58 #define MFPOOL_ENVS "MFPOOL", "TEXMFINI"
59 #define MFT_ENVS "MFTINPUTS"
60 #define MP_ENVS "MPINPUTS"
61 #define MPPOOL_ENVS "MPPOOL", "TEXMFINI" 
62 #define MPSUPPORT_ENVS "MPSUPPORT"
63 #define OCP_ENVS "OCPINPUTS"
64 #define OFM_ENVS "OFMFONTS", "TEXFONTS"
65 #define OPL_ENVS "OPLFONTS", "TEXFONTS"
66 #define OTP_ENVS "OTPINPUTS"
67 #define OVF_ENVS "OVFFONTS", "TEXFONTS"
68 #define OVP_ENVS "OVPFONTS", "TEXFONTS"
69 #define PICT_ENVS "TEXPICTS", TEX_ENVS
70 #define TEX_ENVS "TEXINPUTS"
71 #define TEXDOC_ENVS "TEXDOCS"
72 #define TEXPOOL_ENVS "TEXPOOL", "TEXMFINI"
73 #define TEXSOURCE_ENVS "TEXSOURCES"
74 #define TEX_PS_HEADER_ENVS "TEXPSHEADERS", "PSHEADERS"
75 #define TROFF_FONT_ENVS "TRFONTS"
76 #define TYPE1_ENVS "T1FONTS", "T1INPUTS", "TEXFONTS", TEX_PS_HEADER_ENVS
77 #define VF_ENVS "VFFONTS", "TEXFONTS"
78 #define DVIPS_CONFIG_ENVS "TEXCONFIG"
79 #define IST_ENVS "TEXINDEXSTYLE", "INDEXSTYLE"
80 #define TRUETYPE_ENVS "TTFONTS", "TEXFONTS"
81 #define TYPE42_ENVS "T42FONTS", "TEXFONTS"
82 #define WEB2C_ENVS "WEB2C"
83 #define MISCFONTS_ENVS "MISCFONTS", "TEXFONTS"
84 #define WEB_ENVS "WEBINPUTS"
85 #define CWEB_ENVS "CWEBINPUTS"
86 #define ENC_ENVS "ENCFONTS", "TEXFONTS"
87 #define CMAP_ENVS "CMAPFONTS", "TEXFONTS"
88 #define SFD_ENVS "SFDFONTS", "TEXFONTS"
89 #define OPENTYPE_ENVS "OPENTYPEFONTS", "TEXFONTS"
90 #define PDFTEXCONFIG_ENVS "PDFTEXCONFIG"
91 #define LIG_ENVS "LIGFONTS", "TEXFONTS"
92 #define TEXMFSCRIPTS_ENVS "TEXMFSCRIPTS"
93 #define LUA_ENVS "LUAINPUTS"
94 \f
95 /* The compiled-in default list, DEFAULT_FONT_SIZES, is intended to be
96    set from the command line (presumably via the Makefile).  */
97
98 #ifndef DEFAULT_FONT_SIZES
99 #define DEFAULT_FONT_SIZES ""
100 #endif
101
102 void
103 kpse_init_fallback_resolutions P1C(string, envvar)
104 {
105   string size;
106   const_string size_var = ENVVAR (envvar, "TEXSIZES");
107   string size_str = getenv (size_var);
108   unsigned *last_resort_sizes = NULL;
109   unsigned size_count = 0;
110   const_string default_sizes = kpse_fallback_resolutions_string
111                          ? kpse_fallback_resolutions_string
112                          : DEFAULT_FONT_SIZES; 
113   string size_list = kpse_expand_default (size_str, default_sizes);
114   
115   /* Initialize the list of last-resort sizes.  */
116   for (size = kpse_path_element (size_list); size != NULL;
117        size = kpse_path_element (NULL))
118     {
119       unsigned s;
120       if (! *size) /* Skip empty elements.  */
121         continue;
122       
123       s = atoi (size);
124       if (size_count && s < last_resort_sizes[size_count - 1]) {
125     WARNING1 ("kpathsea: last resort size %s not in ascending order, ignored",
126           size);
127       } else {
128         size_count++;
129         XRETALLOC (last_resort_sizes, size_count, unsigned);
130         last_resort_sizes[size_count - 1] = atoi (size);
131       }
132     }
133
134   /* Add a zero to mark the end of the list.  */
135   size_count++;
136   XRETALLOC (last_resort_sizes, size_count, unsigned);
137   last_resort_sizes[size_count - 1] = 0;
138
139   free (size_list);
140     
141   kpse_fallback_resolutions = last_resort_sizes;
142 }
143 \f
144 /* We should be able to set the program arguments in the same way.  Not
145    to mention the path values themselves.  */
146
147 void
148 kpse_set_program_enabled P3C(kpse_file_format_type, fmt,  boolean, value,
149                              kpse_src_type, level)
150 {
151   kpse_format_info_type *f = &kpse_format_info[fmt];
152   if (level >= f->program_enable_level) {
153     f->program_enabled_p = value;
154     f->program_enable_level = level;
155   }
156 }
157
158
159 /* Web2c and kpsewhich have command-line options to set this stuff.  May
160    as well have a common place.  */
161
162 void
163 kpse_maketex_option P2C(const_string, fmtname,  boolean, value)
164 {
165   kpse_file_format_type fmt = kpse_last_format;
166   
167   /* Trying to match up with the suffix lists unfortunately doesn't work
168      well, since that would require initializing the formats.  */
169   /* FIXME: Currently the function silently ignores unrecognized arguments.*/
170   if (FILESTRCASEEQ (fmtname, "pk")) {
171     fmt = kpse_pk_format;
172   } else if (FILESTRCASEEQ (fmtname, "mf")) {
173     fmt = kpse_mf_format;
174   } else if (FILESTRCASEEQ (fmtname, "tex")) {
175     fmt = kpse_tex_format;
176   } else if (FILESTRCASEEQ (fmtname, "tfm")) {
177     fmt = kpse_tfm_format;
178   } else if (FILESTRCASEEQ (fmtname, "fmt")) {
179     fmt = kpse_fmt_format;
180   } else if (FILESTRCASEEQ (fmtname, "ofm")) {
181     fmt = kpse_ofm_format;
182   } else if (FILESTRCASEEQ (fmtname, "ocp")) {
183     fmt = kpse_ocp_format;
184   }
185   if (fmt != kpse_last_format) {
186     kpse_set_program_enabled (fmt, value, kpse_src_cmdline);
187   }
188 }
189 \f
190 /* Macro subroutines for `init_path'.  TRY_ENV checks if an envvar ENAME
191    is set and non-null, and sets var to ENAME if so.  */
192 #define TRY_ENV(ename) do { \
193   string evar = ename; \
194 } while (0)
195
196 /* And EXPAND_DEFAULT calls kpse_expand_default on try_path and the
197    present info->path.  */
198 #define EXPAND_DEFAULT(try_path, source_string)                 \
199   if (try_path) {                                               \
200     info->raw_path = try_path;                                  \
201     info->path = kpse_expand_default (try_path, info->path);    \
202     info->path_source = source_string;                          \
203   }
204
205 /* Find the final search path to use for the format entry INFO, given
206    the compile-time default (DEFAULT_PATH), and the environment
207    variables to check (the remaining arguments, terminated with NULL).
208    We set the `path' and `path_source' members of INFO.  The
209    `client_path' member must already be set upon entry.  */
210
211 static void
212 init_path PVAR2C(kpse_format_info_type *, info, const_string, default_path, ap)
213 {
214   string env_name;
215   string env_value = NULL;
216   string var = NULL;
217   
218   info->default_path = default_path;
219
220   /* First envvar that's set to a nonempty value will exit the loop.  If
221      none are set, we want the first cnf entry that matches.  Find the
222      cnf entries simultaneously, to avoid having to go through envvar
223      list twice -- because of the PVAR?C macro, that would mean having
224      to create a str_list and then use it twice.  Yuck.  */
225   while ((env_name = va_arg (ap, string)) != NULL) {
226     /* Since sh doesn't like envvar names with `.', check PATH_prog
227        as well as PATH.prog.  */
228     if (!var) { /* Try PATH.prog. */
229       string evar = concat3 (env_name, ".", kpse_program_name);
230       env_value = getenv (evar);
231       if (env_value && *env_value) {
232         var = evar;
233       } else { /* Try PATH_prog. */
234         free (evar);
235         evar = concat3 (env_name, "_", kpse_program_name);
236         env_value = getenv (evar);
237         if (env_value && *env_value) {
238           var = evar;
239         } else { /* Try simply PATH.  */
240           free (evar);
241           env_value = getenv (env_name);
242           if (env_value && *env_value) {
243             var = env_name;        
244           }
245         }
246       }
247     }
248     
249     /* If we are initializing the cnf path, don't try to get any
250        values from the cnf files; that's infinite loop time.  */
251     if (!info->cnf_path && info != &kpse_format_info[kpse_cnf_format])
252       info->cnf_path = kpse_cnf_get (env_name);
253       
254     if (var && info->cnf_path)
255       break;
256   }
257   va_end (ap);
258   
259   /* Expand any extra :'s.  For each level, we replace an extra : with
260      the path at the next lower level.  For example, an extra : in a
261      user-set envvar should be replaced with the path from the cnf file.
262      things are complicated because none of the levels above the very
263      bottom are guaranteed to exist.  */
264
265   /* Assume we can reliably start with the compile-time default.  */
266   info->path = info->raw_path = info->default_path;
267   info->path_source = "compile-time paths.h";
268
269   EXPAND_DEFAULT (info->cnf_path, "texmf.cnf");
270   EXPAND_DEFAULT (info->client_path, "program config file");
271
272   if (var) {
273     /* Translate `;' in the envvar into `:' if that's our ENV_SEP. */
274     if (IS_ENV_SEP (':')) {
275       string loc;
276       env_value = xstrdup (env_value);  /* Freed below. */
277       for (loc = env_value; *loc; loc++) {
278         if (*loc == ';')
279           *loc = ':';
280       }
281     }
282     EXPAND_DEFAULT (env_value, concat (var, " environment variable"));
283     /* Do not free the copied env_value, because EXPAND_DEFAULT set
284        raw_path to point to it.  If it gets overwritten again, tough.  */
285   }
286
287   EXPAND_DEFAULT (info->override_path, "application override variable");
288   info->path = kpse_brace_expand (info->path);
289 }}
290
291
292 /* Some file types have more than one suffix, and sometimes it is
293    convenient to modify the list of searched suffixes.  */ 
294
295 void
296 kpse_set_suffixes PVAR2C(kpse_file_format_type, format,
297   boolean, alternate,  ap)
298 {
299   const_string **list;
300   const_string s;
301   int count = 0;
302
303   if (alternate) {
304     list = &kpse_format_info[format].alt_suffix;
305   } else {
306     list = &kpse_format_info[format].suffix;
307   }
308
309   while ((s = va_arg (ap, string)) != NULL) {
310     count++;
311     XRETALLOC (*list, count + 1, const_string);
312     (*list)[count - 1] = s;
313   }
314   va_end (ap);
315   (*list)[count] = NULL;
316 }}
317
318 /* The path spec we are defining, one element of the global array.  */
319 #define FMT_INFO kpse_format_info[format]
320 /* Call kpse_set_add_suffixes.  */
321 #define SUFFIXES(args) kpse_set_suffixes(format, false, args, NULL)
322 #define ALT_SUFFIXES(args) kpse_set_suffixes(format, true, args, NULL)
323
324 /* Call `init_path', including appending the trailing NULL to the envvar
325    list. Also initialize the fields not needed in setting the path.  */
326 #define INIT_FORMAT(text, default_path, envs) \
327   FMT_INFO.type = text; \
328   init_path (&FMT_INFO, default_path, envs, NULL); \
329   envvar_list = concatn_with_spaces (envs, NULL);
330
331
332 /* A few file types allow for runtime generation by an external program.
333    kpse_init_prog may have already initialized it (the `program'
334    member).  Here we allow people to turn it off or on in the config
335    file, by setting the variable whose name is the uppercasified program
336    name to 0 or 1.  */
337
338 static void
339 init_maketex PVAR2C(kpse_file_format_type, fmt,  const_string, dflt_prog, ap)
340 {
341   kpse_format_info_type *f = &kpse_format_info[fmt];
342   const_string prog = f->program ? f->program : dflt_prog; /* mktexpk */
343   string PROG = uppercasify (prog);             /* MKTEXPK */
344   string progval = kpse_var_value (PROG);       /* ENV/cnf{"MKTEXPK"} */
345   const_string arg;
346
347   /* Doesn't hurt to always set this info.  */
348   f->program = prog;
349
350   /* Set up the argument vector. */
351   f->argc = 0;
352   f->argv = XTALLOC(2, const_string);
353   f->argv[f->argc++] = dflt_prog;
354   while ((arg = va_arg (ap, string)) != NULL) {
355     f->argc++;
356     XRETALLOC (f->argv, f->argc + 1, const_string);
357     f->argv[f->argc - 1] = arg;
358   }
359   f->argv[f->argc] = NULL;
360
361   if (progval && *progval) {
362     /* This might actually be from an environment variable value, but in
363        that case, we'll have previously set it from kpse_init_prog.  */
364     kpse_set_program_enabled (fmt, *progval == '1', kpse_src_client_cnf);
365   }
366   
367   free (PROG);
368 }}
369
370 /* We need this twice, so ... */
371 #define MKTEXPK_ARGS \
372   "--mfmode","$MAKETEX_MODE",\
373   "--bdpi","$MAKETEX_BASE_DPI",\
374   "--mag","$MAKETEX_MAG",\
375   "--dpi","$KPATHSEA_DPI",\
376   NULL
377
378 static string
379 remove_dbonly P1C(const_string, path)
380 {
381   string ret = XTALLOC(strlen (path) + 1, char), q=ret;
382   const_string p=path;
383   boolean new_elt=true;
384
385   while (*p) {
386     if (new_elt && *p && *p == '!' && *(p+1) == '!')
387       p += 2;
388     else {
389       new_elt = (*p == ENV_SEP);
390       *q++ = *p++;
391     }
392   }
393   *q = '\0';
394   return(ret);
395 }
396
397 /* Same as concatn but puts a space between each element.  All this just
398    for nice debugging output.  But it's useful.  */
399
400 static string
401 concatn_with_spaces PVAR1C(const_string, str1,  ap)
402 {
403   string arg;
404   string ret;
405
406   if (!str1)
407     return NULL;
408   
409   ret = xstrdup (str1);
410   
411   while ((arg = va_arg (ap, string)) != NULL)
412     {
413       string temp = concat3 (ret, " ", arg);
414       free (ret);
415       ret = temp;
416     }
417   va_end (ap);
418   
419   return ret;
420 }}
421
422 \f
423 /* Initialize everything for FORMAT.  */
424
425 const_string
426 kpse_init_format P1C(kpse_file_format_type, format)
427 {
428   string envvar_list;  /* only for debug output, set in INIT_FORMAT */
429
430   /* If we get called twice, don't redo all the work.  */
431   if (FMT_INFO.path)
432     return FMT_INFO.path;
433     
434   switch (format)
435     { /* We might be able to avoid repeating `gf' or whatever so many
436          times with token pasting, but it doesn't seem worth it.  */
437     case kpse_gf_format:
438       INIT_FORMAT ("gf", DEFAULT_GFFONTS, GF_ENVS);
439       SUFFIXES ("gf");
440       FMT_INFO.suffix_search_only = true;
441       FMT_INFO.binmode = true;
442       break;
443     case kpse_pk_format:
444       init_maketex (format, "mktexpk", MKTEXPK_ARGS);
445       INIT_FORMAT ("pk", DEFAULT_PKFONTS, PK_ENVS);
446       SUFFIXES ("pk");
447       FMT_INFO.suffix_search_only = true;
448       FMT_INFO.binmode = true;
449       break;
450     case kpse_any_glyph_format:
451       init_maketex (format, "mktexpk", MKTEXPK_ARGS);
452       INIT_FORMAT ("bitmap font", DEFAULT_GLYPHFONTS, GLYPH_ENVS);
453       FMT_INFO.suffix_search_only = true;
454       FMT_INFO.binmode = true;
455       break;
456     case kpse_tfm_format:
457       /* Must come before kpse_ofm_format. */
458       init_maketex (format, "mktextfm", NULL);
459       INIT_FORMAT ("tfm", DEFAULT_TFMFONTS, TFM_ENVS);
460       SUFFIXES (".tfm");
461       FMT_INFO.suffix_search_only = true;
462       FMT_INFO.binmode = true;
463       break;
464     case kpse_afm_format:
465       INIT_FORMAT ("afm", DEFAULT_AFMFONTS, AFM_ENVS);
466       SUFFIXES (".afm");
467       break;
468     case kpse_base_format:
469       init_maketex (format, "mktexfmt", NULL);
470       INIT_FORMAT ("base", DEFAULT_MFBASES, BASE_ENVS);
471       SUFFIXES (".base");
472       FMT_INFO.binmode = true;
473       break;
474     case kpse_bib_format:
475       INIT_FORMAT ("bib", DEFAULT_BIBINPUTS, BIB_ENVS);
476       SUFFIXES (".bib");
477       FMT_INFO.suffix_search_only = true;
478       break;
479     case kpse_bst_format:
480       INIT_FORMAT ("bst", DEFAULT_BSTINPUTS, BST_ENVS);
481       SUFFIXES (".bst");
482       break;
483     case kpse_cnf_format:
484       INIT_FORMAT ("cnf", DEFAULT_TEXMFCNF, CNF_ENVS);
485       SUFFIXES (".cnf");
486       break;
487     case kpse_db_format:
488       INIT_FORMAT ("ls-R", DEFAULT_TEXMFDBS, DB_ENVS);
489 #define LSR_SUFFIXES "ls-R", "ls-r"
490       SUFFIXES (LSR_SUFFIXES);
491       FMT_INFO.path = remove_dbonly (FMT_INFO.path);
492       break;
493     case kpse_fmt_format:
494       init_maketex (format, "mktexfmt", NULL);
495       INIT_FORMAT ("fmt", DEFAULT_TEXFORMATS, FMT_ENVS);
496       SUFFIXES (".fmt");
497       FMT_INFO.binmode = true;
498       break;
499     case kpse_fontmap_format:
500       INIT_FORMAT ("map", DEFAULT_TEXFONTMAPS, FONTMAP_ENVS);
501       SUFFIXES (".map");
502       break;
503     case kpse_mem_format:
504       init_maketex (format, "mktexfmt", NULL);
505       INIT_FORMAT ("mem", DEFAULT_MPMEMS, MEM_ENVS);
506       SUFFIXES (".mem");
507       FMT_INFO.binmode = true;
508       break;
509     case kpse_mf_format:
510       init_maketex (format, "mktexmf", NULL);
511       INIT_FORMAT ("mf", DEFAULT_MFINPUTS, MF_ENVS);
512       SUFFIXES (".mf");
513       break;
514     case kpse_mft_format:
515       INIT_FORMAT ("mft", DEFAULT_MFTINPUTS, MFT_ENVS);
516       SUFFIXES (".mft");
517       break;
518     case kpse_mfpool_format:
519       INIT_FORMAT ("mfpool", DEFAULT_MFPOOL, MFPOOL_ENVS);
520       SUFFIXES (".pool");
521       break;
522     case kpse_mp_format:
523       INIT_FORMAT ("mp", DEFAULT_MPINPUTS, MP_ENVS);
524       SUFFIXES (".mp");
525       break;
526     case kpse_mppool_format:
527       INIT_FORMAT ("mppool", DEFAULT_MPPOOL, MPPOOL_ENVS);
528       SUFFIXES (".pool");
529       break;
530     case kpse_mpsupport_format:
531       INIT_FORMAT ("MetaPost support", DEFAULT_MPSUPPORT, MPSUPPORT_ENVS);
532       break;
533     case kpse_ocp_format:
534       init_maketex (format, "mkocp", NULL);
535       INIT_FORMAT ("ocp", DEFAULT_OCPINPUTS, OCP_ENVS);
536       SUFFIXES (".ocp");
537       FMT_INFO.suffix_search_only = true;
538       FMT_INFO.binmode = true;
539       break;
540     case kpse_ofm_format:
541       init_maketex (format, "mkofm", NULL);
542       INIT_FORMAT ("ofm", DEFAULT_OFMFONTS, OFM_ENVS);
543 #define OFM_SUFFIXES ".ofm", ".tfm"
544       SUFFIXES (OFM_SUFFIXES);
545       FMT_INFO.suffix_search_only = true;
546       FMT_INFO.binmode = true;
547       break;
548     case kpse_opl_format:
549       INIT_FORMAT ("opl", DEFAULT_OPLFONTS, OPL_ENVS);
550       SUFFIXES (".opl");
551       FMT_INFO.suffix_search_only = true;
552       break;
553     case kpse_otp_format:
554       INIT_FORMAT ("otp", DEFAULT_OTPINPUTS, OTP_ENVS);
555       SUFFIXES (".otp");
556       FMT_INFO.suffix_search_only = true;
557       break;
558     case kpse_ovf_format:
559       INIT_FORMAT ("ovf", DEFAULT_OVFFONTS, OVF_ENVS);
560       SUFFIXES (".ovf");
561       FMT_INFO.suffix_search_only = true;
562       FMT_INFO.binmode = true;
563       break;
564     case kpse_ovp_format:
565       INIT_FORMAT ("ovp", DEFAULT_OVPFONTS, OVP_ENVS);
566       SUFFIXES (".ovp");
567       FMT_INFO.suffix_search_only = true;
568       break;
569     case kpse_pict_format:
570       INIT_FORMAT ("graphic/figure", DEFAULT_TEXINPUTS, PICT_ENVS);
571 #define ALT_PICT_SUFFIXES ".eps", ".epsi"
572       ALT_SUFFIXES (ALT_PICT_SUFFIXES);
573       FMT_INFO.binmode = true;
574       break;
575     case kpse_tex_format:
576       init_maketex (format, "mktextex", NULL);
577       INIT_FORMAT ("tex", DEFAULT_TEXINPUTS, TEX_ENVS);
578       SUFFIXES (".tex");
579       /* TeX files can have any obscure suffix in the world (or none at
580          all).  Only check for the most common ones.  */
581 #define ALT_TEX_SUFFIXES ".sty", ".cls", ".fd", ".aux", ".bbl", ".def", ".clo", ".ldf"
582       ALT_SUFFIXES (ALT_TEX_SUFFIXES);
583       break;
584     case kpse_tex_ps_header_format:
585       INIT_FORMAT ("PostScript header", DEFAULT_TEXPSHEADERS,
586                    TEX_PS_HEADER_ENVS);
587 /* Unfortunately, at one time dvips used this format for type1 fonts.  */
588 #define ALT_TEXPSHEADER_SUFFIXES ".pro"
589       ALT_SUFFIXES (ALT_TEXPSHEADER_SUFFIXES);
590       FMT_INFO.binmode = true;
591       break;
592     case kpse_texdoc_format:
593       INIT_FORMAT ("TeX system documentation", DEFAULT_TEXDOCS, TEXDOC_ENVS);
594       break;
595     case kpse_texpool_format:
596       INIT_FORMAT ("texpool", DEFAULT_TEXPOOL, TEXPOOL_ENVS);
597       SUFFIXES (".pool");
598       break;
599     case kpse_texsource_format:
600       INIT_FORMAT ("TeX system sources", DEFAULT_TEXSOURCES, TEXSOURCE_ENVS);
601 #define ALT_SOURCES_SUFFIXES ".dtx", ".ins"
602       ALT_SUFFIXES (ALT_SOURCES_SUFFIXES);
603       break;
604     case kpse_troff_font_format:
605       INIT_FORMAT ("Troff fonts", DEFAULT_TRFONTS, TROFF_FONT_ENVS);
606       FMT_INFO.binmode = true;
607       break;
608     case kpse_type1_format:
609       INIT_FORMAT ("type1 fonts", DEFAULT_T1FONTS, TYPE1_ENVS);
610 #define TYPE1_SUFFIXES ".pfa", ".pfb"
611       SUFFIXES (TYPE1_SUFFIXES);
612       FMT_INFO.binmode = true;
613       break;
614     case kpse_vf_format:
615       INIT_FORMAT ("vf", DEFAULT_VFFONTS, VF_ENVS);
616       SUFFIXES (".vf");
617       FMT_INFO.suffix_search_only = true;
618       FMT_INFO.binmode = true;
619       break;
620     case kpse_dvips_config_format:
621       INIT_FORMAT ("dvips config", DEFAULT_TEXCONFIG, DVIPS_CONFIG_ENVS);
622       break;
623     case kpse_ist_format:
624       INIT_FORMAT ("ist", DEFAULT_INDEXSTYLE, IST_ENVS);
625       SUFFIXES (".ist");
626       break;
627     case kpse_truetype_format:
628       INIT_FORMAT ("truetype fonts", DEFAULT_TTFONTS, TRUETYPE_ENVS);
629 #define TRUETYPE_SUFFIXES ".ttf", ".ttc", ".TTF", ".TTC"
630       SUFFIXES (TRUETYPE_SUFFIXES);
631       FMT_INFO.suffix_search_only = false;
632       FMT_INFO.binmode = true;
633       break;
634     case kpse_type42_format:
635       INIT_FORMAT ("type42 fonts", DEFAULT_T42FONTS, TYPE42_ENVS);
636 #define TYPE42_SUFFIXES ".t42", ".T42"
637       SUFFIXES (TYPE42_SUFFIXES);
638       FMT_INFO.binmode = true;
639       break;
640     case kpse_web2c_format:
641       INIT_FORMAT ("web2c files", DEFAULT_WEB2C, WEB2C_ENVS);
642       break;
643     case kpse_program_text_format:
644       INIT_FORMAT ("other text files",
645                    concatn (".", ENV_SEP_STRING, "$TEXMF/",
646                             kpse_program_name, "//", NULL),
647                    concat (uppercasify (kpse_program_name), "INPUTS"));
648       break;
649     case kpse_program_binary_format:
650       INIT_FORMAT ("other binary files",
651                    concatn (".", ENV_SEP_STRING, "$TEXMF/",
652                             kpse_program_name, "//", NULL),
653                    concat (uppercasify (kpse_program_name), "INPUTS"));
654       FMT_INFO.binmode = true;
655       break;
656     case kpse_miscfonts_format:
657       INIT_FORMAT ("misc fonts", DEFAULT_MISCFONTS, MISCFONTS_ENVS);
658       FMT_INFO.binmode = true;
659       break;
660     case kpse_web_format:
661       INIT_FORMAT ("web", DEFAULT_WEBINPUTS, WEB_ENVS);
662       SUFFIXES (".web");
663       ALT_SUFFIXES (".ch");
664       break;
665     case kpse_cweb_format:
666       INIT_FORMAT ("cweb", DEFAULT_CWEBINPUTS, CWEB_ENVS);
667 #define CWEB_SUFFIXES ".w", ".web"
668       SUFFIXES (CWEB_SUFFIXES);
669       ALT_SUFFIXES (".ch");
670       break;
671     case kpse_enc_format:
672       INIT_FORMAT ("enc files", DEFAULT_ENCFONTS, ENC_ENVS);
673       SUFFIXES (".enc");
674       break;
675     case kpse_cmap_format:
676       INIT_FORMAT ("cmap files", DEFAULT_CMAPFONTS, CMAP_ENVS);
677       break;
678     case kpse_sfd_format:
679       INIT_FORMAT ("subfont definition files", DEFAULT_SFDFONTS, SFD_ENVS);
680       SUFFIXES (".sfd");
681       break;
682     case kpse_opentype_format:
683       INIT_FORMAT ("opentype fonts", DEFAULT_OPENTYPEFONTS, OPENTYPE_ENVS);
684       SUFFIXES (".otf");
685       FMT_INFO.binmode = true;
686       break;
687     case kpse_pdftex_config_format:
688       INIT_FORMAT ("pdftex config", DEFAULT_PDFTEXCONFIG, PDFTEXCONFIG_ENVS);
689       break;
690     case kpse_lig_format:
691       INIT_FORMAT ("lig files", DEFAULT_LIGFONTS, LIG_ENVS);
692       SUFFIXES (".lig");
693       break;
694     case kpse_texmfscripts_format:
695       INIT_FORMAT ("texmfscripts", DEFAULT_TEXMFSCRIPTS, TEXMFSCRIPTS_ENVS);
696       break;
697     case kpse_lua_format:
698       INIT_FORMAT ("lua", DEFAULT_LUAINPUTS, LUA_ENVS);
699 #define LUA_SUFFIXES ".luc", ".luctex", ".texluc", ".lua", ".luatex", ".texlua"
700       SUFFIXES (LUA_SUFFIXES);
701       FMT_INFO.suffix_search_only = true;
702       break;
703     default:
704       FATAL1 ("kpse_init_format: Unknown format %d", format);
705     }
706
707 #ifdef KPSE_DEBUG
708 #define MAYBE(member) (FMT_INFO.member ? FMT_INFO.member : "(none)")
709
710   /* Describe the monster we've created.  */
711   if (KPSE_DEBUG_P (KPSE_DEBUG_PATHS))
712     {
713       DEBUGF2 ("Search path for %s files (from %s)\n",
714               FMT_INFO.type, FMT_INFO.path_source);
715       DEBUGF1 ("  = %s\n", FMT_INFO.path);
716       DEBUGF1 ("  before expansion = %s\n", FMT_INFO.raw_path);
717       DEBUGF1 ("  application override path = %s\n", MAYBE (override_path));
718       DEBUGF1 ("  application config file path = %s\n", MAYBE (client_path));
719       DEBUGF1 ("  texmf.cnf path = %s\n", MAYBE (cnf_path));
720       DEBUGF1 ("  compile-time path = %s\n", MAYBE (default_path));
721       DEBUGF1 ("  environment variables = %s\n", envvar_list);
722       DEBUGF  ("  default suffixes =");
723       if (FMT_INFO.suffix) {
724         const_string *ext;
725         for (ext = FMT_INFO.suffix; ext && *ext; ext++) {
726           fprintf (stderr, " %s", *ext);
727         }
728         putc ('\n', stderr);
729       } else {
730         fputs (" (none)\n", stderr);
731       }
732       DEBUGF  ("  other suffixes =");
733       if (FMT_INFO.alt_suffix) {
734         const_string *alt;
735         for (alt = FMT_INFO.alt_suffix; alt && *alt; alt++) {
736           fprintf (stderr, " %s", *alt);
737         }
738         putc ('\n', stderr);
739       } else {
740         fputs (" (none)\n", stderr);
741       }
742       DEBUGF1 ("  search only with suffix = %d\n",FMT_INFO.suffix_search_only);
743       DEBUGF1 ("  numeric format value = %d\n", format);
744       DEBUGF1 ("  runtime generation program = %s\n", MAYBE (program));
745       DEBUGF  ("  runtime generation command =");
746       if (FMT_INFO.argv) {
747         const_string *arg;
748         for (arg = FMT_INFO.argv; *arg; arg++) {
749           fprintf (stderr, " %s", *arg);
750         }
751         putc ('\n', stderr);
752       } else {
753           fputs(" (none)\n", stderr);
754       }
755       DEBUGF1 ("  program enabled = %d\n", FMT_INFO.program_enabled_p);
756       DEBUGF1 ("  program enable level = %d\n", FMT_INFO.program_enable_level);
757     }
758 #endif /* KPSE_DEBUG */
759
760   return FMT_INFO.path;
761 }
762 \f
763 /* These are subroutines called twice when finding file, to construct
764    the list of names to search for.  */
765    
766 /* We don't even use fontmaps any more in practice, they were for things
767    like the lcircle10/lcirc10 name change many years ago, but let's keep
768    the support working nonetheless.  */
769
770 static void
771 target_fontmaps (const_string **target, unsigned *count, const_string name)
772 {
773   string *mapped_names = kpse_fontmap_lookup (name);
774   
775   if (mapped_names != NULL) {
776     string mapped_name;
777     /* We leak mapped_names and its elements, some of the time.  */
778     while ((mapped_name = *mapped_names++) != NULL) {
779       (*target)[(*count)] = xstrdup (mapped_name);
780       (*count)++;
781       XRETALLOC ((*target), (*count)+1, const_string);
782     }
783   }
784 }
785
786
787 /* Possibly add NAME (and any fontmap equivalents) to the string list
788    in TARGET, depending on the various other parameters.  */
789
790 static void
791 target_asis_name (const_string **target, unsigned *count,
792     kpse_file_format_type format,
793     const_string name, boolean use_fontmaps, boolean has_potential_suffix,
794     string has_any_suffix)
795 {
796   /* Look for the name we've been given, provided non-suffix
797      searches are allowed or the name already includes a suffix. */
798   if (has_potential_suffix || !FMT_INFO.suffix_search_only) {
799     (*target)[(*count)] = xstrdup (name);
800     (*count)++;
801     XRETALLOC ((*target), (*count)+1, const_string);
802
803     if (use_fontmaps) {
804       target_fontmaps (target, count, name);
805     }
806   }
807 }
808
809
810 /* Possibly add NAME (and any fontmap equivalents), with any suffixes
811    for this FORMAT appended, to TARGET -- if it doesn't already have one
812    of the potential suffixes for FORMAT.  */
813
814 static void
815 target_suffixed_names (const_string **target, unsigned *count,
816     kpse_file_format_type format,
817     const_string name, boolean use_fontmaps, boolean has_potential_suffix)
818 {
819   const_string *ext;
820   if (has_potential_suffix || !FMT_INFO.suffix) {
821     return;
822   }
823   
824   for (ext = FMT_INFO.suffix; *ext; ext++) {
825     string name_with_suffix = concat (name, *ext);
826     (*target)[(*count)] = name_with_suffix;
827     (*count)++;
828     XRETALLOC ((*target), (*count)+1, const_string);
829     
830     if (use_fontmaps) {
831       target_fontmaps (target, count, name_with_suffix);
832     }    
833   }
834 }
835 \f
836 /* Look up a file NAME of type FORMAT, and the given MUST_EXIST.  This
837    initializes the path spec for FORMAT if it's the first lookup of that
838    type.  Return the filename found, or NULL.  This is the most likely
839    thing for clients to call.  */
840    
841 string
842 kpse_find_file P3C(const_string, name,  kpse_file_format_type, format,
843                    boolean, must_exist)
844 {
845   string *ret_list = kpse_find_file_generic (name, format, must_exist, false);
846   string ret = *ret_list;
847   free (ret_list);
848   return ret;
849 }
850
851 /* As with `kpse_find_file', but also allow passing ALL for the search,
852    hence we always return a NULL-terminated list.  */
853
854 string *
855 kpse_find_file_generic P4C(const_string, name,  kpse_file_format_type, format,
856                            boolean, must_exist,  boolean, all)
857 {
858   const_string *target;
859   const_string *ext;
860   unsigned count;
861   unsigned name_len = 0;
862   boolean has_potential_suffix = false;
863   string has_any_suffix = NULL;
864   string try_std_extension_first = NULL;
865   boolean use_fontmaps = (format == kpse_tfm_format
866                           || format == kpse_gf_format
867                           || format == kpse_pk_format
868                           || format == kpse_ofm_format);
869   string *ret = NULL;
870
871   /* NAME being NULL is a programming bug somewhere.  NAME can be empty,
872      though; this happens with constructs like `\input\relax'.  */
873   assert (name);
874   
875   if (FMT_INFO.path == NULL)
876     kpse_init_format (format);
877
878   if (KPSE_DEBUG_P (KPSE_DEBUG_SEARCH))
879     DEBUGF3 ("kpse_find_file: searching for %s of type %s (from %s)\n",
880              name, FMT_INFO.type, FMT_INFO.path_source);
881
882   /* Do variable and tilde expansion. */
883   name = kpse_expand (name);
884    
885   try_std_extension_first = kpse_var_value ("try_std_extension_first");
886   has_any_suffix = strrchr (name, '.');
887   if (has_any_suffix) {
888     string p = strchr (has_any_suffix, DIR_SEP);
889     if (p) {
890       has_any_suffix = NULL;
891     }
892   }
893
894   /* Does NAME already end in a possible suffix?  */
895   name_len = strlen (name);
896   if (FMT_INFO.suffix) {
897     for (ext = FMT_INFO.suffix; !has_potential_suffix && *ext; ext++) {
898       unsigned suffix_len = strlen (*ext);
899       has_potential_suffix = (name_len >= suffix_len
900           && FILESTRCASEEQ (*ext, name + name_len - suffix_len));
901     }
902   }
903   if (!has_potential_suffix && FMT_INFO.alt_suffix) {
904     for (ext = FMT_INFO.alt_suffix; !has_potential_suffix && *ext; ext++) {
905       unsigned suffix_len = strlen (*ext);
906       has_potential_suffix = (name_len >= suffix_len
907           && FILESTRCASEEQ (*ext, name + name_len - suffix_len));
908     }
909   }
910
911   /* Set up list of target names to search for, the order depending on
912      try_std_extension_first.  */
913   count = 0;
914   target = XTALLOC1 (const_string);
915
916   if (has_any_suffix
917       && (try_std_extension_first == NULL || *try_std_extension_first == 'f'
918           || *try_std_extension_first == '0')) {
919     target_asis_name (&target, &count, format, name, use_fontmaps,
920                            has_potential_suffix, has_any_suffix);
921     target_suffixed_names (&target, &count, format, name, use_fontmaps,
922                            has_potential_suffix);
923   } else {
924     target_suffixed_names (&target, &count, format, name, use_fontmaps,
925                            has_potential_suffix);
926     target_asis_name (&target, &count, format, name, use_fontmaps,
927                            has_potential_suffix, has_any_suffix );
928   }
929
930   /* Terminate list. */
931   target[count] = NULL;
932
933   if (try_std_extension_first) {
934     free (try_std_extension_first);
935   }
936
937   /* Search, trying to minimize disk-pounding.  */
938   ret = kpse_path_search_list_generic (FMT_INFO.path, target, false, all);
939   /* Do we need to pound the disk? */
940   if (! *ret && must_exist) {
941     for (count = 0; target[count]; count++)
942       free ((void *) target[count]);
943     count = 0;
944     /* We look for a subset of the previous set of names, so the
945        target array is large enough.  In particular, we don't pound
946        the disk for alternate names from the fontmaps.  */
947     if (!has_potential_suffix && FMT_INFO.suffix_search_only) {
948       for (ext = FMT_INFO.suffix; *ext; ext++)
949         target[count++] = concat (name, *ext);
950     }
951     if (has_potential_suffix || !FMT_INFO.suffix_search_only) {
952       target[count++] = xstrdup (name);
953     }
954     target[count] = NULL;
955     ret = kpse_path_search_list_generic (FMT_INFO.path, target, true, all);
956   }
957   
958   /* Free the list we created. */
959   for (count = 0; target[count]; count++)
960     free ((void *) target[count]);
961   free (target);
962   
963   /* If nothing was found, call mktex* to create a missing file.  Since
964      this returns a single string, morph it into a list.  */
965   if (! *ret && must_exist) {
966     ret = XTALLOC (2, string);
967     ret[0] = kpse_make_tex (format, name);
968     if (ret[0]) {
969       ret[1] = NULL;
970     }
971   }
972
973   free ((void *) name);
974
975   return ret;
976 }
977
978
979 \f
980 /* Open NAME along the search path for TYPE for reading and return the
981    resulting file, or exit with an error message.  */
982
983 FILE *
984 kpse_open_file P2C(const_string, name,  kpse_file_format_type, type)
985 {
986   string fullname = kpse_find_file (name, type, true);
987   const_string mode = kpse_format_info[type].binmode
988                       ? FOPEN_RBIN_MODE
989                       : FOPEN_R_MODE;
990   FILE *f = fullname ? fopen (fullname, mode) : NULL;
991   if (!f) {
992     if (fullname) {
993       perror (fullname);
994       exit (1);
995     } else {
996       FATAL2 ("%s file `%s' not found", kpse_format_info[type].type, name);
997     }
998   }
999   
1000   return f;
1001 }
1002 \f
1003 /* When using the %&<format> construct, we'd like to use the paths for
1004    that format, rather than those for the name we were called with.
1005    Of course this happens after various initializations have been
1006    performed, so we have this function to force the issue.  Note that
1007    the paths for kpse_cnf_format and kpse_db_format are not cleared.
1008
1009    This function is defined here, and not in progname.c, because it
1010    need kpse_format_info, and would cause all of tex-file to be pulled
1011    in by programs that do not need it. */
1012 void
1013 kpse_reset_program_name P1C(const_string, progname)
1014 {
1015   int i;
1016
1017   /* It is a fatal error for either of these to be NULL. */
1018   assert (progname && kpse_program_name);
1019   /* Do nothing if the name is unchanged. */
1020   if (STREQ(kpse_program_name, progname))
1021     return;
1022
1023   free (kpse_program_name);
1024   kpse_program_name = xstrdup (progname);
1025   xputenv("progname", kpse_program_name);
1026   
1027   /* Clear paths -- do we want the db path to be cleared? */
1028   for (i = 0; i != kpse_last_format; ++i) {
1029     /* Do not erase the cnf of db paths.  This means that the filename
1030        database is not rebuilt, nor are different configuration files
1031        searched.  The alternative is to tolerate a memory leak of up
1032        to 100k if this function is called. */
1033     if (i == kpse_cnf_format || i == kpse_db_format)
1034       continue;
1035     /* Wipe the path (it is tested) and the cnf_path and because their
1036        values may differ with the new program name.  */
1037     if (kpse_format_info[i].path != NULL) {
1038       free ((string)kpse_format_info[i].path);
1039       kpse_format_info[i].path = NULL;
1040     }
1041     /* We cannot free the cnf_path: it points into the cnf hash, which
1042        means all hell will break loose if we did. */
1043     if (kpse_format_info[i].cnf_path != NULL) {
1044       kpse_format_info[i].cnf_path = NULL;
1045     }
1046     /* We do not wipe the override_path at this point, though arguably
1047        we should provide new values.  It is not likely to matter for
1048        the programs that call this function. */
1049   }
1050 }