3 * Copyright (c) 1995-1999 Markku Rossi.
5 * Author: Markku Rossi <mtr@iki.fi>
9 * This file is part of GNU Enscript.
11 * Enscript is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * Enscript is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with Enscript. If not, see <http://www.gnu.org/licenses/>.
29 * Types and definitions.
32 #define CFG_FATAL(body) \
34 fprintf (stderr, "%s:%s:%d: ", program, buffer_ptr(&fname), line); \
36 fprintf (stderr, "\n"); \
47 * 7bit ASCII fi(nland), se (sweden) scand encodings (additions to 7bit ASCII
54 } enc_7bit_ascii_fise[] =
66 * 7bit ASCII dk (denmark), no(rway) scand encodings (additions to 7bit ASCII
73 } enc_7bit_ascii_dkno[] =
89 #define GET_TOKEN(from) (strtok ((from), " \t\n"))
90 #define GET_LINE_TOKEN(from) (strtok ((from), "\n"))
92 #define CHECK_TOKEN() \
94 CFG_FATAL ((stderr, _("missing argument: %s"), token));
96 void search_and_replace(char *str, char *search, char *replace) {
98 int search_len = strlen(search);
99 int replace_len = strlen(replace);
101 while ((pos = strstr(str, search)) != NULL) {
102 char tmp[strlen(str) + 1];
103 strcpy(tmp, pos + search_len);
104 strcpy(pos, replace);
105 strcpy(pos + replace_len, tmp);
106 str = pos + replace_len;
110 read_config (char *path, char *file)
115 char *token, *token2;
118 buffer_init (&fname);
119 buffer_append (&fname, path);
120 buffer_append (&fname, "/");
121 buffer_append (&fname, file);
123 fp = fopen (buffer_ptr (&fname), "r");
125 /* We wait to uninit the buffer so that CFG_FATAL can use it. */
129 buffer_uninit (&fname);
133 while (fgets (buf, sizeof (buf), fp))
140 token = GET_TOKEN (buf);
145 if (MATCH (token, "AcceptCompositeCharacters:"))
147 token2 = GET_TOKEN (NULL);
149 accept_composites = atoi (token2);
151 else if (MATCH (token, "AFMPath:"))
153 token2 = GET_TOKEN (NULL);
155 search_and_replace(token2,"$HOME",getenv("HOME"));
157 afm_path = xstrdup (token2);
159 else if (MATCH (token, "AppendCtrlD:"))
161 token2 = GET_TOKEN (NULL);
163 append_ctrl_D = atoi (token2);
165 else if (MATCH (token, "Clean7Bit:"))
167 token2 = GET_TOKEN (NULL);
169 clean_7bit = atoi (token2);
171 else if (MATCH (token, "DefaultEncoding:"))
173 token2 = GET_TOKEN (NULL);
175 xfree (encoding_name);
176 encoding_name = xstrdup (token2);
178 else if (MATCH (token, "DefaultFancyHeader:"))
180 token2 = GET_TOKEN (NULL);
182 xfree (fancy_header_default);
183 fancy_header_default = xstrdup (token2);
185 else if (MATCH (token, "DefaultMedia:"))
187 token2 = GET_TOKEN (NULL);
190 if (!strcasecmp("LC_PAPER", token2))
192 unsigned int paperheight = (unsigned int)nl_langinfo(_NL_PAPER_HEIGHT);
193 if (paperheight && paperheight == 279)
200 media_name = xstrdup (token2);
202 else if (MATCH (token, "DefaultOutputMethod:"))
204 token2 = GET_TOKEN (NULL);
206 if (MATCH (token2, "printer"))
207 output_file = OUTPUT_FILE_NONE;
208 else if (MATCH (token2, "stdout"))
209 output_file = OUTPUT_FILE_STDOUT;
211 CFG_FATAL ((stderr, _("illegal value \"%s\" for option %s"),
214 else if (MATCH (token, "DownloadFont:"))
216 token2 = GET_TOKEN (NULL);
218 strhash_put (download_fonts, token2, strlen (token2) + 1, NULL,
221 else if (MATCH (token, "EscapeChar:"))
223 token2 = GET_TOKEN (NULL);
225 escape_char = atoi (token2);
226 if (escape_char < 0 || escape_char > 255)
227 CFG_FATAL ((stderr, _("invalid value \"%s\" for option %s"),
230 else if (MATCH (token, "FormFeedType:"))
232 token2 = GET_TOKEN (NULL);
234 if (MATCH (token2, "column"))
235 formfeed_type = FORMFEED_COLUMN;
236 else if (MATCH (token2, "page"))
237 formfeed_type = FORMFEED_PAGE;
239 CFG_FATAL ((stderr, _("illegal value \"%s\" for option %s"),
242 else if (MATCH (token, "GeneratePageSize:"))
244 token2 = GET_TOKEN (NULL);
246 generate_PageSize = atoi (token2);
248 else if (MATCH (token, "HighlightBarGray:"))
250 token2 = GET_TOKEN (NULL);
252 highlight_bar_gray = atof (token2);
254 else if (MATCH (token, "HighlightBars:"))
256 token2 = GET_TOKEN (NULL);
258 highlight_bars = atoi (token2);
260 else if (MATCH (token, "LibraryPath:"))
262 token2 = GET_TOKEN (NULL);
265 libpath = xstrdup (token2);
267 else if (MATCH (token, "MarkWrappedLines:"))
269 token2 = GET_TOKEN (NULL);
271 xfree (mark_wrapped_lines_style_name);
272 mark_wrapped_lines_style_name = xstrdup (token2);
274 else if (MATCH (token, "Media:"))
277 int w, h, llx, lly, urx, ury;
279 token2 = GET_TOKEN (NULL);
283 token2 = GET_TOKEN (NULL);
287 token2 = GET_TOKEN (NULL);
291 token2 = GET_TOKEN (NULL);
295 token2 = GET_TOKEN (NULL);
299 token2 = GET_TOKEN (NULL);
303 token2 = GET_TOKEN (NULL);
307 add_media (name, w, h, llx, lly, urx, ury);
309 else if (MATCH (token, "NoJobHeaderSwitch:"))
311 token2 = GET_LINE_TOKEN (NULL);
313 xfree (no_job_header_switch);
314 no_job_header_switch = xstrdup (token2);
316 else if (MATCH (token, "NonPrintableFormat:"))
318 token2 = GET_TOKEN (NULL);
321 npf_name = xstrdup (token2);
323 else if (MATCH (token, "OutputFirstLine:"))
325 token2 = GET_LINE_TOKEN (NULL);
327 xfree (output_first_line);
328 output_first_line = xstrdup (token2);
330 else if (MATCH (token, "PageLabelFormat:"))
332 token2 = GET_TOKEN (NULL);
334 xfree (page_label_format);
335 page_label_format = xstrdup (token2);
337 else if (MATCH (token, "PagePrefeed:"))
339 token2 = GET_TOKEN (NULL);
341 page_prefeed = atoi (token2);
343 else if (MATCH (token, "PostScriptLevel:"))
345 token2 = GET_TOKEN (NULL);
347 pslevel = atoi (token2);
349 else if (MATCH (token, "Printer:"))
351 token2 = GET_TOKEN (NULL);
354 printer = xstrdup (token2);
356 else if (MATCH (token, "QueueParam:"))
358 token2 = GET_LINE_TOKEN (NULL);
361 queue_param = xstrdup (token2);
363 else if (MATCH (token, "SetPageDevice:"))
365 token2 = GET_LINE_TOKEN (NULL);
367 parse_key_value_pair (pagedevice, token2);
369 else if (MATCH (token, "Spooler:"))
371 token2 = GET_TOKEN (NULL);
373 xfree (spooler_command);
374 spooler_command = xstrdup (token2);
376 else if (MATCH (token, "StatesBinary:"))
378 token2 = GET_TOKEN (NULL);
380 xfree (states_binary);
381 states_binary = xstrdup (token2);
383 else if (MATCH (token, "StatesColor:"))
385 token2 = GET_TOKEN (NULL);
387 states_color = atoi (token2);
389 else if (MATCH (token, "StatesConfigFile:"))
391 token2 = GET_LINE_TOKEN (NULL);
393 xfree (states_config_file);
394 states_config_file = xstrdup (token2);
396 else if (MATCH (token, "StatesHighlightStyle:"))
398 token2 = GET_TOKEN (NULL);
400 xfree (states_highlight_style);
401 states_highlight_style = xstrdup (token2);
403 else if (MATCH (token, "StatesPath:"))
405 token2 = GET_LINE_TOKEN (NULL);
408 states_path = xstrdup (token2);
410 else if (MATCH (token, "StatusDict:"))
412 token2 = GET_TOKEN (NULL);
414 parse_key_value_pair (statusdict, token2);
416 else if (MATCH (token, "TOCFormat:"))
418 token2 = GET_LINE_TOKEN (NULL);
420 toc_fmt_string = xstrdup (token2);
422 else if (MATCH (token, "Underlay:"))
424 token2 = GET_LINE_TOKEN (NULL);
426 underlay = xmalloc (strlen (token2) + 1);
427 strcpy (underlay, token2);
429 else if (MATCH (token, "UnderlayAngle:"))
431 token2 = GET_TOKEN (NULL);
433 ul_angle = atof (token2);
436 else if (MATCH (token, "UnderlayFont:"))
438 token2 = GET_TOKEN (NULL);
440 if (!parse_font_spec (token2, &ul_font, &ul_ptsize, NULL))
441 CFG_FATAL ((stderr, _("malformed font spec: %s"), token2));
443 else if (MATCH (token, "UnderlayGray:"))
445 token2 = GET_TOKEN (NULL);
447 ul_gray = atof (token2);
449 else if (MATCH (token, "UnderlayPosition:"))
451 token2 = GET_TOKEN (NULL);
454 ul_position = xstrdup (token2);
457 else if (MATCH (token, "UnderlayStyle:"))
459 token2 = GET_TOKEN (NULL);
461 xfree (ul_style_str);
462 ul_style_str = xstrdup (token2);
465 CFG_FATAL ((stderr, _("illegal option: %s"), token));
469 buffer_uninit (&fname);
475 add_media (char *name, int w, int h, int llx, int lly, int urx, int ury)
481 "add_media: name=%s, w=%d, h=%d, llx=%d, lly=%d, urx=%d, ury=%d\n",
482 name, w, h, llx, lly, urx, ury));
484 entry = xcalloc (1, sizeof (*entry));
485 entry->name = xmalloc (strlen (name) + 1);
487 strcpy (entry->name, name);
495 entry->next = media_names;
501 do_list_missing_characters (int *array)
506 for (i = 0; i < 256; i++)
509 fprintf (stderr, "%3d ", i);
512 fprintf (stderr, "\n");
516 fprintf (stderr, "\n");
521 file_existsp (char *name, char *suffix)
527 ctx.suffix = suffix ? suffix : "";
528 ctx.fullname = buffer_alloc ();
530 result = pathwalk (libpath, file_lookup, &ctx);
532 buffer_free (ctx.fullname);
539 paste_file (char *name, char *suffix)
545 int pending_comment = 0;
549 ctx.suffix = suffix ? suffix : "";
550 ctx.fullname = buffer_alloc ();
552 if (!pathwalk (libpath, file_lookup, &ctx))
554 buffer_free (ctx.fullname);
557 fp = fopen (buffer_ptr (ctx.fullname), "r");
560 buffer_free (ctx.fullname);
564 /* Find the end of the header. */
565 #define HDR_TAG "% -- code follows this line --"
566 while ((fgets (buf, sizeof (buf), fp)))
569 if (strncmp (buf, HDR_TAG, strlen (HDR_TAG)) == 0)
573 /* Dump rest of file. */
574 while ((fgets (buf, sizeof (buf), fp)))
579 * Document needed resources?
581 #define RESOURCE_DSC "%%DocumentNeededResources:"
582 #define CONT_DSC "%%+"
583 if (strncmp (buf, RESOURCE_DSC, strlen (RESOURCE_DSC)) == 0)
587 strcpy (resources, buf + strlen (RESOURCE_DSC));
591 /* Register needed resources. */
592 cp = GET_TOKEN (resources);
594 /* Get the next line. */
597 if (MATCH (cp, "font"))
599 for (cp = GET_TOKEN (NULL); cp; cp = GET_TOKEN (NULL))
600 /* Is this font already known? */
601 if (!strhash_get (res_fonts, cp, strlen (cp) + 1,
604 /* Not it is not, we must include this resource. */
606 fprintf (ofp, "%%%%IncludeResource: font %s\n", cp);
609 * And register that this resource is needed in
612 strhash_put (res_fonts, cp, strlen (cp) + 1, NULL, NULL);
615 /* Do not pass this DSC row to the output. */
619 /* Unknown resource, ignore. */
622 else if (pending_comment
623 && strncmp (buf, CONT_DSC, strlen (CONT_DSC)) == 0)
625 strcpy (resources, buf + strlen (CONT_DSC));
626 goto parse_resources;
632 * `%Format' directive?
634 #define DIRECTIVE_FORMAT "%Format:"
635 if (strncmp (buf, DIRECTIVE_FORMAT, strlen (DIRECTIVE_FORMAT)) == 0)
642 /* Skip the leading whitespace. */
643 for (i = strlen (DIRECTIVE_FORMAT); buf[i] && isspace (buf[i]); i++)
646 FATAL ((stderr, _("%s:%d: %%Format: no name"),
647 buffer_ptr (ctx.fullname), line));
651 j < sizeof (name) - 1 && buf[i] && !isspace (buf[i]);
656 if (j >= sizeof (name) - 1)
657 FATAL ((stderr, _("%s:%d: %%Format: too long name, maxlen=%d"),
658 buffer_ptr (ctx.fullname), line, (int)(sizeof (name) - 1)));
660 /* Find the start of the format string. */
661 for (; buf[i] && isspace (buf[i]); i++)
666 for (j--; isspace (buf[j]) && j > i; j--)
670 MESSAGE (2, (stderr, "%%Format: %s %.*s\n", name, j - i, buf + i));
672 cp = xmalloc (j - i + 1);
673 memcpy (cp, buf + i, j - i);
676 strhash_put (user_strings, name, strlen (name) + 1, cp,
680 _("%s:%d: %%Format: name \"%s\" is already defined"),
681 buffer_ptr (ctx.fullname), line, name));
683 /* All done with the `%Format' directive. */
688 * `%HeaderHeight' directive?
690 #define DIRECTIVE_HEADERHEIGHT "%HeaderHeight:"
691 if (strncmp (buf, DIRECTIVE_HEADERHEIGHT,
692 strlen (DIRECTIVE_HEADERHEIGHT)) == 0)
696 /* Find the start of the pts argument. */
697 for (i = strlen (DIRECTIVE_HEADERHEIGHT);
698 buf[i] && !isspace (buf[i]); i++)
701 FATAL ((stderr, _("%s:%d: %%HeaderHeight: no argument"),
702 buffer_ptr (ctx.fullname), line));
704 d_header_h = atoi (buf + i);
705 MESSAGE (2, (stderr, "%%HeaderHeight: %d\n", d_header_h));
710 * `%FooterHeight' directive?
712 #define DIRECTIVE_FOOTERHEIGHT "%FooterHeight:"
713 if (strncmp (buf, DIRECTIVE_FOOTERHEIGHT,
714 strlen (DIRECTIVE_FOOTERHEIGHT)) == 0)
718 /* Find the start of the pts argument. */
719 for (i = strlen (DIRECTIVE_FOOTERHEIGHT);
720 buf[i] && !isspace (buf[i]); i++)
723 FATAL ((stderr, _("%s:%d: %%FooterHeight: no argument"),
724 buffer_ptr (ctx.fullname), line));
726 d_footer_h = atoi (buf + i);
727 MESSAGE (2, (stderr, "%%FooterHeight: %d\n", d_footer_h));
731 /* Nothing special, just copy it to the output. */
736 buffer_free (ctx.fullname);
743 parse_font_spec (char *spec_a, char **name_return, FontPoint *size_return,
744 InputEncoding *encoding_return)
751 spec = xstrdup (spec_a);
753 /* Check for the `namesize:encoding' format. */
754 encp = strrchr (spec, ':');
761 /* The `name@ptsize' format? */
762 cp = strchr (spec, '@');
768 /* No ptsize after '@'. */
776 /* The old `nameptsize' format. */
777 i = strlen (spec) - 1;
778 if (i <= 0 || !ISNUMBERDIGIT (spec[i]))
784 for (i--; i >= 0 && ISNUMBERDIGIT (spec[i]); i--)
793 /* We accept one slash for the `pt/pt' format. */
794 for (i--; i >= 0 && ISNUMBERDIGIT (spec[i]); i--)
804 /* Now, <i> points to the end of the name. Let's set the <cp>
805 to the beginning of the point size and share a little code
806 with the other format. */
810 /* Check the font point size. */
811 cp2 = strchr (cp, '/');
815 size_return->w = atof (cp);
816 size_return->h = atof (cp2);
819 size_return->w = size_return->h = atof (cp);
821 /* Extract the font name. */
822 *name_return = (char *) xcalloc (1, i + 1);
823 strncpy (*name_return, spec, i);
825 /* Check the input encoding. */
830 if (encoding_return == NULL)
832 /* We don't allow it here. */
837 for (i = 0; !found && encodings[i].names[0]; i++)
838 for (j = 0; j < 3; j++)
839 if (encodings[i].names[j] != NULL && MATCH (encodings[i].names[j],
843 *encoding_return = encodings[i].encoding;
844 encp = encodings[i].names[0];
857 /* The spec didn't contain the encoding part. Use our global default. */
858 encp = encoding_name;
860 *encoding_return = encoding;
865 "parse_font_spec(): name=%.*s, size=%g/%g, encoding=%s\n", i,
866 *name_return, size_return->w, size_return->h,
869 if (size_return->w < 0.0 && size_return->h < 0.0)
870 MESSAGE (0, (stderr, _("%s: warning: font size is negative\n"), program));
871 else if (size_return->w < 0.0)
872 MESSAGE (0, (stderr, _("%s: warning: font width is negative\n"), program));
873 else if (size_return->h < 0.0)
874 MESSAGE (0, (stderr, _("%s: warning: font height is negative\n"),
882 read_font_info (void)
884 CachedFontInfo *font_info;
886 int font_info_cached = 1;
889 unsigned int enc_flags = 0;
893 MESSAGE (2, (stderr, _("reading AFM info for font \"%s\"\n"), Fname));
895 if (accept_composites)
896 enc_flags = AFM_ENCODE_ACCEPT_COMPOSITES;
902 buffer_append (&fkey, Fname);
903 sprintf (buf, "@%f:%d", Fpt.w, encoding);
904 buffer_append (&fkey, buf);
906 if (!strhash_get (afm_info_cache, buffer_ptr (&fkey),
907 strlen (buffer_ptr (&fkey)), (void **) &font_info))
911 /* Couldn't find it from our cache, open open AFM file. */
912 if (!strhash_get (afm_cache, Fname, strlen (Fname), (void **) &font))
914 /* AFM file was not cached, open it from disk. */
915 error = afm_open_font (afm, AFM_I_COMPOSITES, Fname, &font);
916 if (error != AFM_SUCCESS)
918 #define COUR "Courier"
920 * Do not report failures for "Courier*" fonts because
921 * AFM library's default font will fix them.
923 if (strncmp (Fname, COUR, strlen (COUR)) != 0)
926 _("couldn't open AFM file for font \"%s\", using default\n"),
928 error = afm_open_default_font (afm, &font);
929 if (error != AFM_SUCCESS)
931 afm_error_to_string (error, buf);
933 _("couldn't open AFM file for the default font: %s"),
938 /* Apply encoding. */
942 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_1,
947 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_2,
952 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_3,
957 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_4,
962 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_5,
967 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_7,
972 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_9,
976 case ENC_ISO_8859_10:
977 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_10,
982 (void) afm_font_encoding (font, AFM_ENCODING_ASCII, enc_flags);
986 /* First apply standard 7bit ASCII encoding. */
987 (void) afm_font_encoding (font, AFM_ENCODING_ASCII, enc_flags);
989 /* Then add those scand characters. */
990 for (i = 0; enc_7bit_ascii_fise[i].name; i++)
991 (void) afm_font_encode (font, enc_7bit_ascii_fise[i].code,
992 enc_7bit_ascii_fise[i].name,
997 /* First apply standard 7bit ASCII encoding. */
998 (void) afm_font_encoding (font, AFM_ENCODING_ASCII, enc_flags);
1000 /* Then add those scand characters. */
1001 for (i = 0; enc_7bit_ascii_dkno[i].name; i++)
1002 (void) afm_font_encode (font, enc_7bit_ascii_dkno[i].code,
1003 enc_7bit_ascii_dkno[i].name,
1008 (void) afm_font_encoding (font, AFM_ENCODING_IBMPC, enc_flags);
1012 (void) afm_font_encoding (font, AFM_ENCODING_MAC, enc_flags);
1016 (void) afm_font_encoding (font, AFM_ENCODING_VMS, enc_flags);
1020 (void) afm_font_encoding (font, AFM_ENCODING_HP8, enc_flags);
1024 (void) afm_font_encoding (font, AFM_ENCODING_KOI8, enc_flags);
1028 /* Let's use font's default encoding -- nothing here. */
1032 /* Put it to the AFM cache. */
1033 if (!strhash_put (afm_cache, Fname, strlen (Fname), font, NULL))
1037 font_info = (CachedFontInfo *) xcalloc (1, sizeof (*font_info));
1038 /* Read character widths and types. */
1039 for (i = 0; i < 256; i++)
1043 (void) afm_font_charwidth (font, Fpt.w, i, &w0x, &w0y);
1044 font_info->font_widths[i] = w0x;
1046 if (font->encoding[i] == AFM_ENC_NONE)
1047 font_info->font_ctype[i] = ' ';
1048 else if (font->encoding[i] == AFM_ENC_NON_EXISTENT)
1049 font_info->font_ctype[i] = '.';
1051 font_info->font_ctype[i] = '*';
1054 font_info->font_is_fixed
1055 = font->writing_direction_metrics[0].IsFixedPitch;
1056 font_info->font_bbox_lly = font->global_info.FontBBox_lly;
1059 (void) afm_close_font (font);
1061 /* Store font information to the AFM information cache. */
1062 if (!strhash_put (afm_info_cache, buffer_ptr (&fkey),
1063 strlen (buffer_ptr (&fkey)), font_info, NULL))
1064 font_info_cached = 0;
1067 /* Select character widths and types. */
1068 memcpy (font_widths, font_info->font_widths, 256 * sizeof (double));
1069 memcpy (font_ctype, font_info->font_ctype, 256);
1071 font_is_fixed = font_info->font_is_fixed;
1072 font_bbox_lly = font_info->font_bbox_lly;
1074 if (!font_info_cached)
1077 buffer_uninit (&fkey);
1082 download_font (char *name)
1086 struct stat stat_st;
1088 unsigned char buf[4096];
1093 /* Get font prefix. */
1094 error = afm_font_prefix (afm, name, &prefix);
1095 if (error != AFM_SUCCESS)
1096 /* Font is unknown, nothing to download. */
1099 /* Check if we have a font description file. */
1101 buffer_init (&fname);
1104 buffer_append (&fname, prefix);
1105 buffer_append (&fname, ".pfa");
1106 if (stat (buffer_ptr (&fname), &stat_st) != 0)
1109 buffer_clear (&fname);
1110 buffer_append (&fname, prefix);
1111 buffer_append (&fname, ".pfb");
1112 if (stat (buffer_ptr (&fname), &stat_st) != 0)
1114 /* Couldn't find font description file, nothing to download. */
1115 buffer_uninit (&fname);
1120 /* Ok, fine. Font was found. */
1122 MESSAGE (1, (stderr, _("downloading font \"%s\"\n"), name));
1123 fp = fopen (buffer_ptr (&fname), "rb");
1126 MESSAGE (0, (stderr,
1127 _("couldn't open font description file \"%s\": %s\n"),
1128 buffer_ptr (&fname), strerror (errno)));
1129 buffer_uninit (&fname);
1132 buffer_uninit (&fname);
1135 fprintf (ofp, "%%%%BeginResource: font %s\n", name);
1137 /* Check file type. */
1141 /* Not much to do here. */
1148 unsigned int to_read;
1158 /* Read 6-byte long header. */
1159 i = fread (buf, 1, 6, fp);
1163 chunk = buf[2] | (buf[3] << 8) | (buf[4] << 16) | (buf[5] << 24);
1165 /* Check chunk type. */
1172 to_read = sizeof (buf) < chunk ? sizeof (buf) : chunk;
1173 i = fread (buf, 1, to_read, fp);
1180 /* Check and fix Mac-newlines. */
1181 for (j = 0; j < i; j++)
1183 if (j == 0 && last_was_cr && buf[0] != '\n')
1186 fputc (buf[0], ofp);
1188 else if (buf[j] == '\r' && j + 1 < i
1189 && buf[j + 1] != '\n')
1193 else if (buf[j] != '\r')
1194 fputc (buf[j], ofp);
1198 last_was_cr = (buf[i - 1] == '\r');
1202 case 2: /* binary data */
1205 to_read = sizeof (buf) < chunk ? sizeof (buf) : chunk;
1206 i = fread (buf, 1, to_read, fp);
1213 for (j = 0; j < i; j++)
1215 fprintf (ofp, "%02X", buf[j]);
1216 if ((j + 1) % 32 == 0)
1217 fprintf (ofp, "\n");
1228 /* Force a linebreak after each chunk. */
1229 fprintf (ofp, "\n");
1236 while ((i = fread (buf, 1, sizeof (buf), fp)) != 0)
1237 fwrite (buf, 1, i, ofp);
1240 fprintf (ofp, "%%%%EndResource\n");
1242 /* Remove font from needed resources. */
1243 (void) strhash_delete (res_fonts, name, strlen (name) + 1, (void **) &cp);
1250 escape_string (char *string)
1256 /* Count the length of the result string. */
1257 for (len = 0, i = 0; string[i]; i++)
1270 /* Create result. */
1271 cp = xmalloc (len + 1);
1274 for (i = 0, j = 0; string[i]; i++)
1284 cp[j++] = string[i];
1295 * Help macros for the format_user_string() function.
1298 #define NEED_NBYTES(n) \
1300 if (rbufpos + (n) >= rbuflen) \
1302 rbuflen += (n) + 1024; \
1303 rbuf = xrealloc (rbuf, rbuflen); \
1307 #define APPEND_CH(ch) \
1310 NEED_NBYTES (width); \
1311 if (width && justification < 0) \
1312 rbuf[rbufpos++] = (ch); \
1313 for (a = 0; a < width - 1; a++) \
1314 rbuf[rbufpos++] = ' '; \
1315 if (!width || justification > 0) \
1316 rbuf[rbufpos++] = (ch); \
1319 #define APPEND_STR(str) \
1321 int len = strlen ((str)); \
1327 nspace = width - len; \
1329 NEED_NBYTES (nspace + len); \
1330 if (width && justification > 0) \
1331 for (; nspace; nspace--) \
1332 rbuf[rbufpos++] = ' '; \
1334 memcpy (rbuf + rbufpos, str, len); \
1337 if (width && justification < 0) \
1338 for (; nspace; nspace--) \
1339 rbuf[rbufpos++] = ' '; \
1343 format_user_string (char *context_name, char *str)
1354 int justification = 1;
1356 /* Format string. */
1357 for (i = 0; str[i] != '\0'; i++)
1363 if (type == '%' || type == '$')
1369 /* Get optional width and justification. */
1375 while (isdigit (str[i]))
1376 width = width * 10 + str[i++] - '0';
1378 /* Handle escapes. */
1381 /* General state related %-escapes. */
1384 case '%': /* `%%' character `%' */
1388 case 'c': /* `%c' trailing component of pwd. */
1389 if (!getcwd (buf, sizeof (buf)))
1391 cp = strrchr (buf, '/');
1399 case 'C': /* `%C' runtime in `hh:mm:ss' format */
1400 sprintf (buf, "%02d:%02d:%02d", run_tm.tm_hour,
1401 run_tm.tm_min, run_tm.tm_sec);
1405 case 'd': /* `%d' current working directory */
1406 if (!getcwd (buf, sizeof (buf)))
1412 if (str[i + 1] == '{')
1414 /* `%D{}' format run date with strftime() */
1416 j < sizeof (buf2) && str[i] && str[i] != '}';
1421 _("%s: too long format for %%D{} escape"),
1425 strftime (buf, sizeof (buf), buf2, &run_tm);
1429 /* `%D' run date in `yy-mm-dd' format */
1430 sprintf (buf, "%02d-%02d-%02d", run_tm.tm_year % 100,
1431 run_tm.tm_mon + 1, run_tm.tm_mday);
1436 case 'E': /* `%E' run date in `yy/mm/dd' format */
1437 sprintf (buf, "%02d/%02d/%02d", run_tm.tm_year % 100,
1438 run_tm.tm_mon + 1, run_tm.tm_mday);
1442 case 'F': /* `%F' run date in `dd.mm.yyyy' format */
1443 sprintf (buf, "%d.%d.%d",
1446 run_tm.tm_year + 1900);
1450 case 'H': /* `%H' document title */
1454 case 'm': /* `%m' the hostname up to the first `.' */
1455 (void) gethostname (buf, sizeof (buf));
1456 cp = strchr (buf, '.');
1462 case 'M': /* `%M' the full hostname */
1463 (void) gethostname (buf, sizeof (buf));
1467 case 'n': /* `%n' username */
1468 APPEND_STR (passwd->pw_name);
1471 case 'N': /* `%N' pw_gecos up to the first `,' char */
1472 strcpy (buf, passwd->pw_gecos);
1473 cp = strchr (buf, ',');
1479 case 't': /* `%t' runtime in 12-hour am/pm format */
1480 sprintf (buf, "%d:%d%s",
1482 ? run_tm.tm_hour - 12 : run_tm.tm_hour,
1484 run_tm.tm_hour > 12 ? "pm" : "am");
1488 case 'T': /* `%T' runtime in 24-hour format */
1489 sprintf (buf, "%d:%d", run_tm.tm_hour, run_tm.tm_min);
1493 case '*': /* `%*' runtime in 24-hour format with secs */
1494 sprintf (buf, "%d:%d:%d", run_tm.tm_hour, run_tm.tm_min,
1499 case 'W': /* `%W' run date in `mm/dd/yy' format */
1500 sprintf (buf, "%02d/%02d/%02d", run_tm.tm_mon + 1,
1501 run_tm.tm_mday, run_tm.tm_year % 100);
1506 FATAL ((stderr, _("%s: unknown `%%' escape `%c' (%d)"),
1507 context_name, str[i], str[i]));
1513 /* Input file related $-escapes. */
1516 case '$': /* `$$' character `$' */
1520 case '%': /* `$%' current page number */
1522 sprintf (buf, "%d%c", current_pagenum, slice - 1 + 'A');
1524 sprintf (buf, "%d", current_pagenum);
1528 case '=': /* `$=' number of pages in this file */
1532 case 'p': /* `$p' number of pages processed so far */
1533 sprintf (buf, "%d", total_pages);
1537 case '(': /* $(ENVVAR) */
1539 str[i] && str[i] != ')' && j < sizeof (buf) - 1;
1544 FATAL ((stderr, _("%s: no closing ')' for $() escape"),
1547 FATAL ((stderr, _("%s: too long variable name for $() escape"),
1558 case 'C': /* `$C' modtime in `hh:mm:ss' format */
1559 sprintf (buf, "%02d:%02d:%02d", mod_tm.tm_hour,
1560 mod_tm.tm_min, mod_tm.tm_sec);
1565 if (str[i + 1] == '{')
1567 /* `$D{}' format modification date with strftime() */
1569 j < sizeof (buf2) && str[i] && str[i] != '}';
1574 _("%s: too long format for $D{} escape"),
1578 strftime (buf, sizeof (buf), buf2, &mod_tm);
1582 /* `$D' mod date in `yy-mm-dd' format */
1583 sprintf (buf, "%02d-%02d-%02d", mod_tm.tm_year % 100,
1584 mod_tm.tm_mon + 1, mod_tm.tm_mday);
1589 case 'E': /* `$E' mod date in `yy/mm/dd' format */
1590 sprintf (buf, "%02d/%02d/%02d", mod_tm.tm_year % 100,
1591 mod_tm.tm_mon + 1, mod_tm.tm_mday);
1595 case 'F': /* `$F' run date in `dd.mm.yyyy' format */
1596 sprintf (buf, "%d.%d.%d",
1599 mod_tm.tm_year + 1900);
1603 case 't': /* `$t' runtime in 12-hour am/pm format */
1604 sprintf (buf, "%d:%d%s",
1606 ? mod_tm.tm_hour - 12 : mod_tm.tm_hour,
1608 mod_tm.tm_hour > 12 ? "pm" : "am");
1612 case 'T': /* `$T' runtime in 24-hour format */
1613 sprintf (buf, "%d:%d", mod_tm.tm_hour, mod_tm.tm_min);
1617 case '*': /* `$*' runtime in 24-hour format with secs */
1618 sprintf (buf, "%d:%d:%d", mod_tm.tm_hour, mod_tm.tm_min,
1623 case 'v': /* `$v': input file number */
1624 sprintf (buf, "%d", input_filenum);
1628 case 'V': /* `$V': input file number in --toc format */
1631 sprintf (buf, "%d-", input_filenum);
1636 case 'W': /* `$W' run date in `mm/dd/yy' format */
1637 sprintf (buf, "%02d/%02d/%02d", mod_tm.tm_mon + 1,
1638 mod_tm.tm_mday, mod_tm.tm_year % 100);
1642 case 'N': /* `$N' the full name of the printed file */
1646 case 'n': /* `$n' input file name without directory */
1647 cp = strrchr (fname, '/');
1655 case 'L': /* `$L' number of lines in this file. */
1656 /* This is valid only for TOC-strings. */
1657 sprintf (buf, "%d", current_file_linenum - 1);
1662 FATAL ((stderr, _("%s: unknown `$' escape `%c' (%d)"),
1663 context_name, str[i], str[i]));
1667 /* Reset width so the else-arm goes ok at the next round. */
1676 /* Escape PS specials. */
1677 cp = escape_string (rbuf);
1685 parse_key_value_pair (StringHashPtr set, char *kv)
1690 cp = strchr (kv, ':');
1693 if (strhash_delete (set, kv, strlen (kv) + 1, (void **) &cp))
1699 buffer_append_len (&key, kv, cp - kv);
1701 strhash_put (set, buffer_ptr (&key), strlen (buffer_ptr (&key)) + 1,
1702 xstrdup (cp + 1), (void **) &cp);
1706 buffer_uninit (&key);
1712 count_key_value_set (StringHashPtr set)
1718 for (got = strhash_get_first (set, &cp, &j, &value); got;
1719 got = strhash_get_next (set, &cp, &j, &value))
1727 pathwalk (char *path, PathWalkProc proc, void *context)
1734 for (cp = path; cp; cp = strchr (cp, PATH_SEPARATOR))
1739 cp2 = strchr (cp, PATH_SEPARATOR);
1745 memcpy (buf, cp, len);
1748 i = (*proc) (buf, context);
1758 file_lookup (char *path, void *context)
1761 FileLookupCtx *ctx = context;
1762 struct stat stat_st;
1765 MESSAGE (2, (stderr, "file_lookup(): %s/%s%s\t", path, ctx->name,
1768 len = strlen (path);
1769 if (len && path[len - 1] == '/')
1772 buffer_clear (ctx->fullname);
1773 buffer_append_len (ctx->fullname, path, len);
1774 buffer_append (ctx->fullname, "/");
1775 buffer_append (ctx->fullname, ctx->name);
1776 buffer_append (ctx->fullname, ctx->suffix);
1778 i = stat (buffer_ptr (ctx->fullname), &stat_st) == 0;
1780 MESSAGE (2, (stderr, "#%c\n", i ? 't' : 'f'));
1787 tilde_subst (char *fname)
1791 struct passwd *pswd;
1795 if (fname[0] != '~')
1796 return xstrdup (fname);
1798 if (fname[1] == '/' || fname[1] == '\0')
1800 /* The the user's home directory from the `HOME' environment
1802 cp = getenv ("HOME");
1804 return xstrdup (fname);
1806 buffer_init (&buffer);
1807 buffer_append (&buffer, cp);
1808 buffer_append (&buffer, fname + 1);
1810 result = buffer_copy (&buffer);
1811 buffer_uninit (&buffer);
1816 /* Get user's login name. */
1817 for (i = 1; fname[i] && fname[i] != '/'; i++)
1820 buffer_init (&buffer);
1821 buffer_append_len (&buffer, fname + 1, i - 1);
1823 pswd = getpwnam (buffer_ptr (&buffer));
1824 buffer_uninit (&buffer);
1828 /* Found passwd entry. */
1829 buffer_init (&buffer);
1830 buffer_append (&buffer, pswd->pw_dir);
1831 buffer_append (&buffer, fname + i);
1833 result = buffer_copy (&buffer);
1834 buffer_uninit (&buffer);
1839 /* No match found. */
1840 return xstrdup (fname);
1845 parse_float (char *string, int units, int horizontal)
1850 val = strtod (string, &end);
1853 ERROR ((stderr, _("malformed float dimension: \"%s\""), string));
1875 val *= FNT_CHAR_WIDTH ('m');
1881 goto malformed_float;
1888 goto malformed_float;
1896 * InputStream functions.
1900 is_open (InputStream *is, FILE *fp, char *fname, char *input_filter)
1902 /* Init stream variables. */
1903 is->data_in_buf = 0;
1906 is->unget_ch = NULL;
1908 is->unget_alloc = 0;
1921 fname = input_filter_stdin;
1924 * Count the initial command length, this will grow dynamically
1925 * when file specifier `%s' is encountered from <input_filter>.
1927 cmdlen = strlen (input_filter) + 1;
1928 cmd = xmalloc (cmdlen);
1930 /* Create filter command. */
1932 for (i = 0; input_filter[i]; i++)
1934 if (input_filter[i] == '%')
1936 switch (input_filter[i + 1])
1939 /* Expand cmd-buffer. */
1940 if ((cp = shell_escape (fname)) != NULL)
1942 cmdlen += strlen (cp);
1943 cmd = xrealloc (cmd, cmdlen);
1945 /* Paste filename. */
1946 strcpy (cmd + pos, cp);
1960 cmd[pos++] = input_filter[i];
1965 cmd[pos++] = input_filter[i];
1969 is->fp = popen (cmd, "r");
1975 _("couldn't open input filter \"%s\" for file \"%s\": %s"),
1976 input_filter, fname ? fname : "(stdin)",
1983 /* Just open the stream. */
1989 is->fp = fopen (fname, "rb");
1992 ERROR ((stderr, _("couldn't open input file \"%s\": %s"), fname,
2004 is_close (InputStream *is)
2012 xfree (is->unget_ch);
2017 is_getc (InputStream *is)
2021 if (is->unget_pos > 0)
2023 ch = is->unget_ch[--is->unget_pos];
2029 /* Do we have any data left? */
2030 if (is->bufpos >= is->data_in_buf)
2033 if (is->nreads > 0 && is->data_in_buf < sizeof (is->buf))
2037 /* Read more data. */
2038 is->data_in_buf = fread (is->buf, 1, sizeof (is->buf), is->fp);
2045 return is->buf[is->bufpos++];
2050 is_ungetc (int ch, InputStream *is)
2052 if (is->unget_pos >= is->unget_alloc)
2054 is->unget_alloc += 1024;
2055 is->unget_ch = xrealloc (is->unget_ch, is->unget_alloc);
2058 is->unget_ch[is->unget_pos++] = ch;
2069 buffer_init (Buffer *buffer)
2071 buffer->allocated = 128;
2072 buffer->data = xmalloc (buffer->allocated);
2073 buffer->data[0] = '\0';
2079 buffer_uninit (Buffer *buffer)
2081 xfree (buffer->data);
2088 Buffer *buffer = (Buffer *) xcalloc (1, sizeof (Buffer));
2090 buffer_init (buffer);
2097 buffer_free (Buffer *buffer)
2099 buffer_uninit (buffer);
2105 buffer_append (Buffer *buffer, const char *data)
2107 buffer_append_len (buffer, data, strlen (data));
2112 buffer_append_len (Buffer *buffer, const char *data, size_t len)
2114 if (buffer->len + len + 1 >= buffer->allocated)
2116 buffer->allocated = buffer->len + len + 1024;
2117 buffer->data = xrealloc (buffer->data, buffer->allocated);
2120 memcpy (buffer->data + buffer->len, data, len);
2123 buffer->data[buffer->len] = '\0';
2128 buffer_copy (Buffer *buffer)
2130 char *copy = xmalloc (buffer->len + 1);
2132 memcpy (copy, buffer->data, buffer->len + 1);
2139 buffer_clear (Buffer *buffer)
2142 buffer->data[0] = '\0';
2147 buffer_ptr (Buffer *buffer)
2149 return buffer->data;
2154 buffer_len (Buffer *buffer)
2160 * Escapes the name of a file so that the shell groks it in 'single'
2161 * quotation marks. The resulting pointer has to be free()ed when not
2165 shell_escape(const char *fn)
2169 char *retval, *outp;
2171 for(inp = fn; *inp; ++inp)
2174 case '\'': len += 4; break;
2175 default: len += 1; break;
2178 outp = retval = malloc(len + 1);
2180 return NULL; /* perhaps one should do better error handling here */
2181 for(inp = fn; *inp; ++inp)
2184 case '\'': *outp++ = '\''; *outp++ = '\\'; *outp++ = '\'', *outp++ = '\''; break;
2185 default: *outp++ = *inp; break;