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/>.
28 * Types and definitions.
31 #define CFG_FATAL(body) \
33 fprintf (stderr, "%s:%s:%d: ", program, buffer_ptr(&fname), line); \
35 fprintf (stderr, "\n"); \
46 * 7bit ASCII fi(nland), se (sweden) scand encodings (additions to 7bit ASCII
53 } enc_7bit_ascii_fise[] =
65 * 7bit ASCII dk (denmark), no(rway) scand encodings (additions to 7bit ASCII
72 } enc_7bit_ascii_dkno[] =
88 #define GET_TOKEN(from) (strtok ((from), " \t\n"))
89 #define GET_LINE_TOKEN(from) (strtok ((from), "\n"))
91 #define CHECK_TOKEN() \
93 CFG_FATAL ((stderr, _("missing argument: %s"), token));
96 read_config (char *path, char *file)
101 char *token, *token2;
104 buffer_init (&fname);
105 buffer_append (&fname, path);
106 buffer_append (&fname, "/");
107 buffer_append (&fname, file);
109 fp = fopen (buffer_ptr (&fname), "r");
111 /* We wait to uninit the buffer so that CFG_FATAL can use it. */
115 buffer_uninit (&fname);
119 while (fgets (buf, sizeof (buf), fp))
126 token = GET_TOKEN (buf);
131 if (MATCH (token, "AcceptCompositeCharacters:"))
133 token2 = GET_TOKEN (NULL);
135 accept_composites = atoi (token2);
137 else if (MATCH (token, "AFMPath:"))
139 token2 = GET_TOKEN (NULL);
142 afm_path = xstrdup (token2);
144 else if (MATCH (token, "AppendCtrlD:"))
146 token2 = GET_TOKEN (NULL);
148 append_ctrl_D = atoi (token2);
150 else if (MATCH (token, "Clean7Bit:"))
152 token2 = GET_TOKEN (NULL);
154 clean_7bit = atoi (token2);
156 else if (MATCH (token, "DefaultEncoding:"))
158 token2 = GET_TOKEN (NULL);
160 xfree (encoding_name);
161 encoding_name = xstrdup (token2);
163 else if (MATCH (token, "DefaultFancyHeader:"))
165 token2 = GET_TOKEN (NULL);
167 xfree (fancy_header_default);
168 fancy_header_default = xstrdup (token2);
170 else if (MATCH (token, "DefaultMedia:"))
172 token2 = GET_TOKEN (NULL);
175 if (!strcasecmp("LC_PAPER", token2))
177 unsigned int paperheight = (unsigned int)nl_langinfo(_NL_PAPER_HEIGHT);
178 if (paperheight && paperheight == 279)
185 media_name = xstrdup (token2);
187 else if (MATCH (token, "DefaultOutputMethod:"))
189 token2 = GET_TOKEN (NULL);
191 if (MATCH (token2, "printer"))
192 output_file = OUTPUT_FILE_NONE;
193 else if (MATCH (token2, "stdout"))
194 output_file = OUTPUT_FILE_STDOUT;
196 CFG_FATAL ((stderr, _("illegal value \"%s\" for option %s"),
199 else if (MATCH (token, "DownloadFont:"))
201 token2 = GET_TOKEN (NULL);
203 strhash_put (download_fonts, token2, strlen (token2) + 1, NULL,
206 else if (MATCH (token, "EscapeChar:"))
208 token2 = GET_TOKEN (NULL);
210 escape_char = atoi (token2);
211 if (escape_char < 0 || escape_char > 255)
212 CFG_FATAL ((stderr, _("invalid value \"%s\" for option %s"),
215 else if (MATCH (token, "FormFeedType:"))
217 token2 = GET_TOKEN (NULL);
219 if (MATCH (token2, "column"))
220 formfeed_type = FORMFEED_COLUMN;
221 else if (MATCH (token2, "page"))
222 formfeed_type = FORMFEED_PAGE;
224 CFG_FATAL ((stderr, _("illegal value \"%s\" for option %s"),
227 else if (MATCH (token, "GeneratePageSize:"))
229 token2 = GET_TOKEN (NULL);
231 generate_PageSize = atoi (token2);
233 else if (MATCH (token, "HighlightBarGray:"))
235 token2 = GET_TOKEN (NULL);
237 highlight_bar_gray = atof (token2);
239 else if (MATCH (token, "HighlightBars:"))
241 token2 = GET_TOKEN (NULL);
243 highlight_bars = atoi (token2);
245 else if (MATCH (token, "LibraryPath:"))
247 token2 = GET_TOKEN (NULL);
250 libpath = xstrdup (token2);
252 else if (MATCH (token, "MarkWrappedLines:"))
254 token2 = GET_TOKEN (NULL);
256 xfree (mark_wrapped_lines_style_name);
257 mark_wrapped_lines_style_name = xstrdup (token2);
259 else if (MATCH (token, "Media:"))
262 int w, h, llx, lly, urx, ury;
264 token2 = GET_TOKEN (NULL);
268 token2 = GET_TOKEN (NULL);
272 token2 = GET_TOKEN (NULL);
276 token2 = GET_TOKEN (NULL);
280 token2 = GET_TOKEN (NULL);
284 token2 = GET_TOKEN (NULL);
288 token2 = GET_TOKEN (NULL);
292 add_media (name, w, h, llx, lly, urx, ury);
294 else if (MATCH (token, "NoJobHeaderSwitch:"))
296 token2 = GET_LINE_TOKEN (NULL);
298 xfree (no_job_header_switch);
299 no_job_header_switch = xstrdup (token2);
301 else if (MATCH (token, "NonPrintableFormat:"))
303 token2 = GET_TOKEN (NULL);
306 npf_name = xstrdup (token2);
308 else if (MATCH (token, "OutputFirstLine:"))
310 token2 = GET_LINE_TOKEN (NULL);
312 xfree (output_first_line);
313 output_first_line = xstrdup (token2);
315 else if (MATCH (token, "PageLabelFormat:"))
317 token2 = GET_TOKEN (NULL);
319 xfree (page_label_format);
320 page_label_format = xstrdup (token2);
322 else if (MATCH (token, "PagePrefeed:"))
324 token2 = GET_TOKEN (NULL);
326 page_prefeed = atoi (token2);
328 else if (MATCH (token, "PostScriptLevel:"))
330 token2 = GET_TOKEN (NULL);
332 pslevel = atoi (token2);
334 else if (MATCH (token, "Printer:"))
336 token2 = GET_TOKEN (NULL);
339 printer = xstrdup (token2);
341 else if (MATCH (token, "QueueParam:"))
343 token2 = GET_LINE_TOKEN (NULL);
346 queue_param = xstrdup (token2);
348 else if (MATCH (token, "SetPageDevice:"))
350 token2 = GET_LINE_TOKEN (NULL);
352 parse_key_value_pair (pagedevice, token2);
354 else if (MATCH (token, "Spooler:"))
356 token2 = GET_TOKEN (NULL);
358 xfree (spooler_command);
359 spooler_command = xstrdup (token2);
361 else if (MATCH (token, "StatesBinary:"))
363 token2 = GET_TOKEN (NULL);
365 xfree (states_binary);
366 states_binary = xstrdup (token2);
368 else if (MATCH (token, "StatesColor:"))
370 token2 = GET_TOKEN (NULL);
372 states_color = atoi (token2);
374 else if (MATCH (token, "StatesConfigFile:"))
376 token2 = GET_LINE_TOKEN (NULL);
378 xfree (states_config_file);
379 states_config_file = xstrdup (token2);
381 else if (MATCH (token, "StatesHighlightStyle:"))
383 token2 = GET_TOKEN (NULL);
385 xfree (states_highlight_style);
386 states_highlight_style = xstrdup (token2);
388 else if (MATCH (token, "StatesPath:"))
390 token2 = GET_LINE_TOKEN (NULL);
393 states_path = xstrdup (token2);
395 else if (MATCH (token, "StatusDict:"))
397 token2 = GET_TOKEN (NULL);
399 parse_key_value_pair (statusdict, token2);
401 else if (MATCH (token, "TOCFormat:"))
403 token2 = GET_LINE_TOKEN (NULL);
405 toc_fmt_string = xstrdup (token2);
407 else if (MATCH (token, "Underlay:"))
409 token2 = GET_LINE_TOKEN (NULL);
411 underlay = xmalloc (strlen (token2) + 1);
412 strcpy (underlay, token2);
414 else if (MATCH (token, "UnderlayAngle:"))
416 token2 = GET_TOKEN (NULL);
418 ul_angle = atof (token2);
421 else if (MATCH (token, "UnderlayFont:"))
423 token2 = GET_TOKEN (NULL);
425 if (!parse_font_spec (token2, &ul_font, &ul_ptsize, NULL))
426 CFG_FATAL ((stderr, _("malformed font spec: %s"), token2));
428 else if (MATCH (token, "UnderlayGray:"))
430 token2 = GET_TOKEN (NULL);
432 ul_gray = atof (token2);
434 else if (MATCH (token, "UnderlayPosition:"))
436 token2 = GET_TOKEN (NULL);
439 ul_position = xstrdup (token2);
442 else if (MATCH (token, "UnderlayStyle:"))
444 token2 = GET_TOKEN (NULL);
446 xfree (ul_style_str);
447 ul_style_str = xstrdup (token2);
450 CFG_FATAL ((stderr, _("illegal option: %s"), token));
454 buffer_uninit (&fname);
460 add_media (char *name, int w, int h, int llx, int lly, int urx, int ury)
466 "add_media: name=%s, w=%d, h=%d, llx=%d, lly=%d, urx=%d, ury=%d\n",
467 name, w, h, llx, lly, urx, ury));
469 entry = xcalloc (1, sizeof (*entry));
470 entry->name = xmalloc (strlen (name) + 1);
472 strcpy (entry->name, name);
480 entry->next = media_names;
486 do_list_missing_characters (int *array)
491 for (i = 0; i < 256; i++)
494 fprintf (stderr, "%3d ", i);
497 fprintf (stderr, "\n");
501 fprintf (stderr, "\n");
506 file_existsp (char *name, char *suffix)
512 ctx.suffix = suffix ? suffix : "";
513 ctx.fullname = buffer_alloc ();
515 result = pathwalk (libpath, file_lookup, &ctx);
517 buffer_free (ctx.fullname);
524 paste_file (char *name, char *suffix)
530 int pending_comment = 0;
534 ctx.suffix = suffix ? suffix : "";
535 ctx.fullname = buffer_alloc ();
537 if (!pathwalk (libpath, file_lookup, &ctx))
539 buffer_free (ctx.fullname);
542 fp = fopen (buffer_ptr (ctx.fullname), "r");
545 buffer_free (ctx.fullname);
549 /* Find the end of the header. */
550 #define HDR_TAG "% -- code follows this line --"
551 while ((fgets (buf, sizeof (buf), fp)))
554 if (strncmp (buf, HDR_TAG, strlen (HDR_TAG)) == 0)
558 /* Dump rest of file. */
559 while ((fgets (buf, sizeof (buf), fp)))
564 * Document needed resources?
566 #define RESOURCE_DSC "%%DocumentNeededResources:"
567 #define CONT_DSC "%%+"
568 if (strncmp (buf, RESOURCE_DSC, strlen (RESOURCE_DSC)) == 0)
572 strcpy (resources, buf + strlen (RESOURCE_DSC));
576 /* Register needed resources. */
577 cp = GET_TOKEN (resources);
579 /* Get the next line. */
582 if (MATCH (cp, "font"))
584 for (cp = GET_TOKEN (NULL); cp; cp = GET_TOKEN (NULL))
585 /* Is this font already known? */
586 if (!strhash_get (res_fonts, cp, strlen (cp) + 1,
589 /* Not it is not, we must include this resource. */
590 fprintf (ofp, "%%%%IncludeResource: font %s\n", cp);
593 * And register that this resource is needed in
596 strhash_put (res_fonts, cp, strlen (cp) + 1, NULL, NULL);
599 /* Do not pass this DSC row to the output. */
603 /* Unknown resource, ignore. */
606 else if (pending_comment
607 && strncmp (buf, CONT_DSC, strlen (CONT_DSC)) == 0)
609 strcpy (resources, buf + strlen (CONT_DSC));
610 goto parse_resources;
616 * `%Format' directive?
618 #define DIRECTIVE_FORMAT "%Format:"
619 if (strncmp (buf, DIRECTIVE_FORMAT, strlen (DIRECTIVE_FORMAT)) == 0)
626 /* Skip the leading whitespace. */
627 for (i = strlen (DIRECTIVE_FORMAT); buf[i] && isspace (buf[i]); i++)
630 FATAL ((stderr, _("%s:%d: %%Format: no name"),
631 buffer_ptr (ctx.fullname), line));
635 j < sizeof (name) - 1 && buf[i] && !isspace (buf[i]);
640 if (j >= sizeof (name) - 1)
641 FATAL ((stderr, _("%s:%d: %%Format: too long name, maxlen=%d"),
642 buffer_ptr (ctx.fullname), line, sizeof (name) - 1));
644 /* Find the start of the format string. */
645 for (; buf[i] && isspace (buf[i]); i++)
650 for (j--; isspace (buf[j]) && j > i; j--)
654 MESSAGE (2, (stderr, "%%Format: %s %.*s\n", name, j - i, buf + i));
656 cp = xmalloc (j - i + 1);
657 memcpy (cp, buf + i, j - i);
660 strhash_put (user_strings, name, strlen (name) + 1, cp,
664 _("%s:%d: %%Format: name \"%s\" is already defined"),
665 buffer_ptr (ctx.fullname), line, name));
667 /* All done with the `%Format' directive. */
672 * `%HeaderHeight' directive?
674 #define DIRECTIVE_HEADERHEIGHT "%HeaderHeight:"
675 if (strncmp (buf, DIRECTIVE_HEADERHEIGHT,
676 strlen (DIRECTIVE_HEADERHEIGHT)) == 0)
680 /* Find the start of the pts argument. */
681 for (i = strlen (DIRECTIVE_HEADERHEIGHT);
682 buf[i] && !isspace (buf[i]); i++)
685 FATAL ((stderr, _("%s:%d: %%HeaderHeight: no argument"),
686 buffer_ptr (ctx.fullname), line));
688 d_header_h = atoi (buf + i);
689 MESSAGE (2, (stderr, "%%HeaderHeight: %d\n", d_header_h));
694 * `%FooterHeight' directive?
696 #define DIRECTIVE_FOOTERHEIGHT "%FooterHeight:"
697 if (strncmp (buf, DIRECTIVE_FOOTERHEIGHT,
698 strlen (DIRECTIVE_FOOTERHEIGHT)) == 0)
702 /* Find the start of the pts argument. */
703 for (i = strlen (DIRECTIVE_FOOTERHEIGHT);
704 buf[i] && !isspace (buf[i]); i++)
707 FATAL ((stderr, _("%s:%d: %%FooterHeight: no argument"),
708 buffer_ptr (ctx.fullname), line));
710 d_footer_h = atoi (buf + i);
711 MESSAGE (2, (stderr, "%%FooterHeight: %d\n", d_footer_h));
715 /* Nothing special, just copy it to the output. */
720 buffer_free (ctx.fullname);
727 parse_font_spec (char *spec_a, char **name_return, FontPoint *size_return,
728 InputEncoding *encoding_return)
735 spec = xstrdup (spec_a);
737 /* Check for the `namesize:encoding' format. */
738 encp = strrchr (spec, ':');
745 /* The `name@ptsize' format? */
746 cp = strchr (spec, '@');
752 /* No ptsize after '@'. */
760 /* The old `nameptsize' format. */
761 i = strlen (spec) - 1;
762 if (i <= 0 || !ISNUMBERDIGIT (spec[i]))
768 for (i--; i >= 0 && ISNUMBERDIGIT (spec[i]); i--)
777 /* We accept one slash for the `pt/pt' format. */
778 for (i--; i >= 0 && ISNUMBERDIGIT (spec[i]); i--)
788 /* Now, <i> points to the end of the name. Let's set the <cp>
789 to the beginning of the point size and share a little code
790 with the other format. */
794 /* Check the font point size. */
795 cp2 = strchr (cp, '/');
799 size_return->w = atof (cp);
800 size_return->h = atof (cp2);
803 size_return->w = size_return->h = atof (cp);
805 /* Extract the font name. */
806 *name_return = (char *) xcalloc (1, i + 1);
807 strncpy (*name_return, spec, i);
809 /* Check the input encoding. */
814 if (encoding_return == NULL)
816 /* We don't allow it here. */
821 for (i = 0; !found && encodings[i].names[0]; i++)
822 for (j = 0; j < 3; j++)
823 if (encodings[i].names[j] != NULL && MATCH (encodings[i].names[j],
827 *encoding_return = encodings[i].encoding;
828 encp = encodings[i].names[0];
841 /* The spec didn't contain the encoding part. Use our global default. */
842 encp = encoding_name;
844 *encoding_return = encoding;
849 "parse_font_spec(): name=%.*s, size=%g/%g, encoding=%s\n", i,
850 *name_return, size_return->w, size_return->h,
853 if (size_return->w < 0.0 && size_return->h < 0.0)
854 MESSAGE (0, (stderr, _("%s: warning: font size is negative\n"), program));
855 else if (size_return->w < 0.0)
856 MESSAGE (0, (stderr, _("%s: warning: font width is negative\n"), program));
857 else if (size_return->h < 0.0)
858 MESSAGE (0, (stderr, _("%s: warning: font height is negative\n"),
866 read_font_info (void)
868 CachedFontInfo *font_info;
870 int font_info_cached = 1;
873 unsigned int enc_flags = 0;
877 MESSAGE (2, (stderr, _("reading AFM info for font \"%s\"\n"), Fname));
879 if (accept_composites)
880 enc_flags = AFM_ENCODE_ACCEPT_COMPOSITES;
886 buffer_append (&fkey, Fname);
887 sprintf (buf, "@%f:%d", Fpt.w, encoding);
888 buffer_append (&fkey, buf);
890 if (!strhash_get (afm_info_cache, buffer_ptr (&fkey),
891 strlen (buffer_ptr (&fkey)), (void **) &font_info))
895 /* Couldn't find it from our cache, open open AFM file. */
896 if (!strhash_get (afm_cache, Fname, strlen (Fname), (void **) &font))
898 /* AFM file was not cached, open it from disk. */
899 error = afm_open_font (afm, AFM_I_COMPOSITES, Fname, &font);
900 if (error != AFM_SUCCESS)
902 #define COUR "Courier"
904 * Do not report failures for "Courier*" fonts because
905 * AFM library's default font will fix them.
907 if (strncmp (Fname, COUR, strlen (COUR)) != 0)
910 _("couldn't open AFM file for font \"%s\", using default\n"),
912 error = afm_open_default_font (afm, &font);
913 if (error != AFM_SUCCESS)
915 afm_error_to_string (error, buf);
917 _("couldn't open AFM file for the default font: %s"),
922 /* Apply encoding. */
926 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_1,
931 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_2,
936 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_3,
941 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_4,
946 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_5,
951 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_7,
956 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_9,
960 case ENC_ISO_8859_10:
961 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_10,
966 (void) afm_font_encoding (font, AFM_ENCODING_ASCII, enc_flags);
970 /* First apply standard 7bit ASCII encoding. */
971 (void) afm_font_encoding (font, AFM_ENCODING_ASCII, enc_flags);
973 /* Then add those scand characters. */
974 for (i = 0; enc_7bit_ascii_fise[i].name; i++)
975 (void) afm_font_encode (font, enc_7bit_ascii_fise[i].code,
976 enc_7bit_ascii_fise[i].name,
981 /* First apply standard 7bit ASCII encoding. */
982 (void) afm_font_encoding (font, AFM_ENCODING_ASCII, enc_flags);
984 /* Then add those scand characters. */
985 for (i = 0; enc_7bit_ascii_dkno[i].name; i++)
986 (void) afm_font_encode (font, enc_7bit_ascii_dkno[i].code,
987 enc_7bit_ascii_dkno[i].name,
992 (void) afm_font_encoding (font, AFM_ENCODING_IBMPC, enc_flags);
996 (void) afm_font_encoding (font, AFM_ENCODING_MAC, enc_flags);
1000 (void) afm_font_encoding (font, AFM_ENCODING_VMS, enc_flags);
1004 (void) afm_font_encoding (font, AFM_ENCODING_HP8, enc_flags);
1008 (void) afm_font_encoding (font, AFM_ENCODING_KOI8, enc_flags);
1012 /* Let's use font's default encoding -- nothing here. */
1016 /* Put it to the AFM cache. */
1017 if (!strhash_put (afm_cache, Fname, strlen (Fname), font, NULL))
1021 font_info = (CachedFontInfo *) xcalloc (1, sizeof (*font_info));
1022 /* Read character widths and types. */
1023 for (i = 0; i < 256; i++)
1027 (void) afm_font_charwidth (font, Fpt.w, i, &w0x, &w0y);
1028 font_info->font_widths[i] = w0x;
1030 if (font->encoding[i] == AFM_ENC_NONE)
1031 font_info->font_ctype[i] = ' ';
1032 else if (font->encoding[i] == AFM_ENC_NON_EXISTENT)
1033 font_info->font_ctype[i] = '.';
1035 font_info->font_ctype[i] = '*';
1038 font_info->font_is_fixed
1039 = font->writing_direction_metrics[0].IsFixedPitch;
1040 font_info->font_bbox_lly = font->global_info.FontBBox_lly;
1043 (void) afm_close_font (font);
1045 /* Store font information to the AFM information cache. */
1046 if (!strhash_put (afm_info_cache, buffer_ptr (&fkey),
1047 strlen (buffer_ptr (&fkey)), font_info, NULL))
1048 font_info_cached = 0;
1051 /* Select character widths and types. */
1052 memcpy (font_widths, font_info->font_widths, 256 * sizeof (double));
1053 memcpy (font_ctype, font_info->font_ctype, 256);
1055 font_is_fixed = font_info->font_is_fixed;
1056 font_bbox_lly = font_info->font_bbox_lly;
1058 if (!font_info_cached)
1061 buffer_uninit (&fkey);
1066 download_font (char *name)
1070 struct stat stat_st;
1072 unsigned char buf[4096];
1077 /* Get font prefix. */
1078 error = afm_font_prefix (afm, name, &prefix);
1079 if (error != AFM_SUCCESS)
1080 /* Font is unknown, nothing to download. */
1083 /* Check if we have a font description file. */
1085 buffer_init (&fname);
1088 buffer_append (&fname, prefix);
1089 buffer_append (&fname, ".pfa");
1090 if (stat (buffer_ptr (&fname), &stat_st) != 0)
1093 buffer_clear (&fname);
1094 buffer_append (&fname, prefix);
1095 buffer_append (&fname, ".pfb");
1096 if (stat (buffer_ptr (&fname), &stat_st) != 0)
1098 /* Couldn't find font description file, nothing to download. */
1099 buffer_uninit (&fname);
1104 /* Ok, fine. Font was found. */
1106 MESSAGE (1, (stderr, _("downloading font \"%s\"\n"), name));
1107 fp = fopen (buffer_ptr (&fname), "rb");
1110 MESSAGE (0, (stderr,
1111 _("couldn't open font description file \"%s\": %s\n"),
1112 buffer_ptr (&fname), strerror (errno)));
1113 buffer_uninit (&fname);
1116 buffer_uninit (&fname);
1119 fprintf (ofp, "%%%%BeginResource: font %s\n", name);
1121 /* Check file type. */
1125 /* Not much to do here. */
1132 unsigned int to_read;
1142 /* Read 6-byte long header. */
1143 i = fread (buf, 1, 6, fp);
1147 chunk = buf[2] | (buf[3] << 8) | (buf[4] << 16) | (buf[5] << 24);
1149 /* Check chunk type. */
1156 to_read = sizeof (buf) < chunk ? sizeof (buf) : chunk;
1157 i = fread (buf, 1, to_read, fp);
1164 /* Check and fix Mac-newlines. */
1165 for (j = 0; j < i; j++)
1167 if (j == 0 && last_was_cr && buf[0] != '\n')
1170 fputc (buf[0], ofp);
1172 else if (buf[j] == '\r' && j + 1 < i
1173 && buf[j + 1] != '\n')
1177 else if (buf[j] != '\r')
1178 fputc (buf[j], ofp);
1182 last_was_cr = (buf[i - 1] == '\r');
1186 case 2: /* binary data */
1189 to_read = sizeof (buf) < chunk ? sizeof (buf) : chunk;
1190 i = fread (buf, 1, to_read, fp);
1197 for (j = 0; j < i; j++)
1199 fprintf (ofp, "%02X", buf[j]);
1200 if ((j + 1) % 32 == 0)
1201 fprintf (ofp, "\n");
1212 /* Force a linebreak after each chunk. */
1213 fprintf (ofp, "\n");
1220 while ((i = fread (buf, 1, sizeof (buf), fp)) != 0)
1221 fwrite (buf, 1, i, ofp);
1224 fprintf (ofp, "%%%%EndResource\n");
1226 /* Remove font from needed resources. */
1227 (void) strhash_delete (res_fonts, name, strlen (name) + 1, (void **) &cp);
1234 escape_string (char *string)
1240 /* Count the length of the result string. */
1241 for (len = 0, i = 0; string[i]; i++)
1254 /* Create result. */
1255 cp = xmalloc (len + 1);
1258 for (i = 0, j = 0; string[i]; i++)
1268 cp[j++] = string[i];
1279 * Help macros for the format_user_string() function.
1282 #define NEED_NBYTES(n) \
1284 if (rbufpos + (n) >= rbuflen) \
1286 rbuflen += (n) + 1024; \
1287 rbuf = xrealloc (rbuf, rbuflen); \
1291 #define APPEND_CH(ch) \
1294 NEED_NBYTES (width); \
1295 if (width && justification < 0) \
1296 rbuf[rbufpos++] = (ch); \
1297 for (a = 0; a < width - 1; a++) \
1298 rbuf[rbufpos++] = ' '; \
1299 if (!width || justification > 0) \
1300 rbuf[rbufpos++] = (ch); \
1303 #define APPEND_STR(str) \
1305 int len = strlen ((str)); \
1311 nspace = width - len; \
1313 NEED_NBYTES (nspace + len); \
1314 if (width && justification > 0) \
1315 for (; nspace; nspace--) \
1316 rbuf[rbufpos++] = ' '; \
1318 memcpy (rbuf + rbufpos, str, len); \
1321 if (width && justification < 0) \
1322 for (; nspace; nspace--) \
1323 rbuf[rbufpos++] = ' '; \
1327 format_user_string (char *context_name, char *str)
1338 int justification = 1;
1340 /* Format string. */
1341 for (i = 0; str[i] != '\0'; i++)
1347 if (type == '%' || type == '$')
1353 /* Get optional width and justification. */
1359 while (isdigit (str[i]))
1360 width = width * 10 + str[i++] - '0';
1362 /* Handle escapes. */
1365 /* General state related %-escapes. */
1368 case '%': /* `%%' character `%' */
1372 case 'c': /* `%c' trailing component of pwd. */
1373 getcwd (buf, sizeof (buf));
1374 cp = strrchr (buf, '/');
1382 case 'C': /* `%C' runtime in `hh:mm:ss' format */
1383 sprintf (buf, "%02d:%02d:%02d", run_tm.tm_hour,
1384 run_tm.tm_min, run_tm.tm_sec);
1388 case 'd': /* `%d' current working directory */
1389 getcwd (buf, sizeof (buf));
1394 if (str[i + 1] == '{')
1396 /* `%D{}' format run date with strftime() */
1398 j < sizeof (buf2) && str[i] && str[i] != '}';
1403 _("%s: too long format for %%D{} escape"),
1407 strftime (buf, sizeof (buf), buf2, &run_tm);
1411 /* `%D' run date in `yy-mm-dd' format */
1412 sprintf (buf, "%02d-%02d-%02d", run_tm.tm_year % 100,
1413 run_tm.tm_mon + 1, run_tm.tm_mday);
1418 case 'E': /* `%E' run date in `yy/mm/dd' format */
1419 sprintf (buf, "%02d/%02d/%02d", run_tm.tm_year % 100,
1420 run_tm.tm_mon + 1, run_tm.tm_mday);
1424 case 'F': /* `%F' run date in `dd.mm.yyyy' format */
1425 sprintf (buf, "%d.%d.%d",
1428 run_tm.tm_year + 1900);
1432 case 'H': /* `%H' document title */
1436 case 'm': /* `%m' the hostname up to the first `.' */
1437 (void) gethostname (buf, sizeof (buf));
1438 cp = strchr (buf, '.');
1444 case 'M': /* `%M' the full hostname */
1445 (void) gethostname (buf, sizeof (buf));
1449 case 'n': /* `%n' username */
1450 APPEND_STR (passwd->pw_name);
1453 case 'N': /* `%N' pw_gecos up to the first `,' char */
1454 strcpy (buf, passwd->pw_gecos);
1455 cp = strchr (buf, ',');
1461 case 't': /* `%t' runtime in 12-hour am/pm format */
1462 sprintf (buf, "%d:%d%s",
1464 ? run_tm.tm_hour - 12 : run_tm.tm_hour,
1466 run_tm.tm_hour > 12 ? "pm" : "am");
1470 case 'T': /* `%T' runtime in 24-hour format */
1471 sprintf (buf, "%d:%d", run_tm.tm_hour, run_tm.tm_min);
1475 case '*': /* `%*' runtime in 24-hour format with secs */
1476 sprintf (buf, "%d:%d:%d", run_tm.tm_hour, run_tm.tm_min,
1481 case 'W': /* `%W' run date in `mm/dd/yy' format */
1482 sprintf (buf, "%02d/%02d/%02d", run_tm.tm_mon + 1,
1483 run_tm.tm_mday, run_tm.tm_year % 100);
1488 FATAL ((stderr, _("%s: unknown `%%' escape `%c' (%d)"),
1489 context_name, str[i], str[i]));
1495 /* Input file related $-escapes. */
1498 case '$': /* `$$' character `$' */
1502 case '%': /* `$%' current page number */
1504 sprintf (buf, "%d%c", current_pagenum, slice - 1 + 'A');
1506 sprintf (buf, "%d", current_pagenum);
1510 case '=': /* `$=' number of pages in this file */
1514 case 'p': /* `$p' number of pages processed so far */
1515 sprintf (buf, "%d", total_pages);
1519 case '(': /* $(ENVVAR) */
1521 str[i] && str[i] != ')' && j < sizeof (buf) - 1;
1526 FATAL ((stderr, _("%s: no closing ')' for $() escape"),
1529 FATAL ((stderr, _("%s: too long variable name for $() escape"),
1540 case 'C': /* `$C' modtime in `hh:mm:ss' format */
1541 sprintf (buf, "%02d:%02d:%02d", mod_tm.tm_hour,
1542 mod_tm.tm_min, mod_tm.tm_sec);
1547 if (str[i + 1] == '{')
1549 /* `$D{}' format modification date with strftime() */
1551 j < sizeof (buf2) && str[i] && str[i] != '}';
1556 _("%s: too long format for $D{} escape"),
1560 strftime (buf, sizeof (buf), buf2, &mod_tm);
1564 /* `$D' mod date in `yy-mm-dd' format */
1565 sprintf (buf, "%02d-%02d-%02d", mod_tm.tm_year % 100,
1566 mod_tm.tm_mon + 1, mod_tm.tm_mday);
1571 case 'E': /* `$E' mod date in `yy/mm/dd' format */
1572 sprintf (buf, "%02d/%02d/%02d", mod_tm.tm_year % 100,
1573 mod_tm.tm_mon + 1, mod_tm.tm_mday);
1577 case 'F': /* `$F' run date in `dd.mm.yyyy' format */
1578 sprintf (buf, "%d.%d.%d",
1581 mod_tm.tm_year + 1900);
1585 case 't': /* `$t' runtime in 12-hour am/pm format */
1586 sprintf (buf, "%d:%d%s",
1588 ? mod_tm.tm_hour - 12 : mod_tm.tm_hour,
1590 mod_tm.tm_hour > 12 ? "pm" : "am");
1594 case 'T': /* `$T' runtime in 24-hour format */
1595 sprintf (buf, "%d:%d", mod_tm.tm_hour, mod_tm.tm_min);
1599 case '*': /* `$*' runtime in 24-hour format with secs */
1600 sprintf (buf, "%d:%d:%d", mod_tm.tm_hour, mod_tm.tm_min,
1605 case 'v': /* `$v': input file number */
1606 sprintf (buf, "%d", input_filenum);
1610 case 'V': /* `$V': input file number in --toc format */
1613 sprintf (buf, "%d-", input_filenum);
1618 case 'W': /* `$W' run date in `mm/dd/yy' format */
1619 sprintf (buf, "%02d/%02d/%02d", mod_tm.tm_mon + 1,
1620 mod_tm.tm_mday, mod_tm.tm_year % 100);
1624 case 'N': /* `$N' the full name of the printed file */
1628 case 'n': /* `$n' input file name without directory */
1629 cp = strrchr (fname, '/');
1637 case 'L': /* `$L' number of lines in this file. */
1638 /* This is valid only for TOC-strings. */
1639 sprintf (buf, "%d", current_file_linenum - 1);
1644 FATAL ((stderr, _("%s: unknown `$' escape `%c' (%d)"),
1645 context_name, str[i], str[i]));
1649 /* Reset width so the else-arm goes ok at the next round. */
1658 /* Escape PS specials. */
1659 cp = escape_string (rbuf);
1667 parse_key_value_pair (StringHashPtr set, char *kv)
1672 cp = strchr (kv, ':');
1675 if (strhash_delete (set, kv, strlen (kv) + 1, (void **) &cp))
1681 buffer_append_len (&key, kv, cp - kv);
1683 strhash_put (set, buffer_ptr (&key), strlen (buffer_ptr (&key)) + 1,
1684 xstrdup (cp + 1), (void **) &cp);
1688 buffer_uninit (&key);
1694 count_key_value_set (StringHashPtr set)
1700 for (got = strhash_get_first (set, &cp, &j, &value); got;
1701 got = strhash_get_next (set, &cp, &j, &value))
1709 pathwalk (char *path, PathWalkProc proc, void *context)
1716 for (cp = path; cp; cp = strchr (cp, PATH_SEPARATOR))
1721 cp2 = strchr (cp, PATH_SEPARATOR);
1727 memcpy (buf, cp, len);
1730 i = (*proc) (buf, context);
1740 file_lookup (char *path, void *context)
1743 FileLookupCtx *ctx = context;
1744 struct stat stat_st;
1747 MESSAGE (2, (stderr, "file_lookup(): %s/%s%s\t", path, ctx->name,
1750 len = strlen (path);
1751 if (len && path[len - 1] == '/')
1754 buffer_clear (ctx->fullname);
1755 buffer_append_len (ctx->fullname, path, len);
1756 buffer_append (ctx->fullname, "/");
1757 buffer_append (ctx->fullname, ctx->name);
1758 buffer_append (ctx->fullname, ctx->suffix);
1760 i = stat (buffer_ptr (ctx->fullname), &stat_st) == 0;
1762 MESSAGE (2, (stderr, "#%c\n", i ? 't' : 'f'));
1769 tilde_subst (char *fname)
1773 struct passwd *pswd;
1777 if (fname[0] != '~')
1778 return xstrdup (fname);
1780 if (fname[1] == '/' || fname[1] == '\0')
1782 /* The the user's home directory from the `HOME' environment
1784 cp = getenv ("HOME");
1786 return xstrdup (fname);
1788 buffer_init (&buffer);
1789 buffer_append (&buffer, cp);
1790 buffer_append (&buffer, fname + 1);
1792 result = buffer_copy (&buffer);
1793 buffer_uninit (&buffer);
1798 /* Get user's login name. */
1799 for (i = 1; fname[i] && fname[i] != '/'; i++)
1802 buffer_init (&buffer);
1803 buffer_append_len (&buffer, fname + 1, i - 1);
1805 pswd = getpwnam (buffer_ptr (&buffer));
1806 buffer_uninit (&buffer);
1810 /* Found passwd entry. */
1811 buffer_init (&buffer);
1812 buffer_append (&buffer, pswd->pw_dir);
1813 buffer_append (&buffer, fname + i);
1815 result = buffer_copy (&buffer);
1816 buffer_uninit (&buffer);
1821 /* No match found. */
1822 return xstrdup (fname);
1827 parse_float (char *string, int units, int horizontal)
1832 val = strtod (string, &end);
1835 ERROR ((stderr, _("malformed float dimension: \"%s\""), string));
1857 val *= CHAR_WIDTH ('m');
1863 goto malformed_float;
1870 goto malformed_float;
1878 * InputStream functions.
1882 is_open (InputStream *is, FILE *fp, char *fname, char *input_filter)
1884 /* Init stream variables. */
1885 is->data_in_buf = 0;
1888 is->unget_ch = NULL;
1890 is->unget_alloc = 0;
1903 fname = input_filter_stdin;
1906 * Count the initial command length, this will grow dynamically
1907 * when file specifier `%s' is encountered from <input_filter>.
1909 cmdlen = strlen (input_filter) + 1;
1910 cmd = xmalloc (cmdlen);
1912 /* Create filter command. */
1914 for (i = 0; input_filter[i]; i++)
1916 if (input_filter[i] == '%')
1918 switch (input_filter[i + 1])
1921 /* Expand cmd-buffer. */
1922 if ((cp = shell_escape (fname)) != NULL)
1924 cmdlen += strlen (cp);
1925 cmd = xrealloc (cmd, cmdlen);
1927 /* Paste filename. */
1928 strcpy (cmd + pos, cp);
1942 cmd[pos++] = input_filter[i];
1947 cmd[pos++] = input_filter[i];
1951 is->fp = popen (cmd, "r");
1957 _("couldn't open input filter \"%s\" for file \"%s\": %s"),
1958 input_filter, fname ? fname : "(stdin)",
1965 /* Just open the stream. */
1971 is->fp = fopen (fname, "rb");
1974 ERROR ((stderr, _("couldn't open input file \"%s\": %s"), fname,
1986 is_close (InputStream *is)
1994 xfree (is->unget_ch);
1999 is_getc (InputStream *is)
2003 if (is->unget_pos > 0)
2005 ch = is->unget_ch[--is->unget_pos];
2011 /* Do we have any data left? */
2012 if (is->bufpos >= is->data_in_buf)
2015 if (is->nreads > 0 && is->data_in_buf < sizeof (is->buf))
2019 /* Read more data. */
2020 is->data_in_buf = fread (is->buf, 1, sizeof (is->buf), is->fp);
2027 return is->buf[is->bufpos++];
2032 is_ungetc (int ch, InputStream *is)
2034 if (is->unget_pos >= is->unget_alloc)
2036 is->unget_alloc += 1024;
2037 is->unget_ch = xrealloc (is->unget_ch, is->unget_alloc);
2040 is->unget_ch[is->unget_pos++] = ch;
2051 buffer_init (Buffer *buffer)
2053 buffer->allocated = 128;
2054 buffer->data = xmalloc (buffer->allocated);
2055 buffer->data[0] = '\0';
2061 buffer_uninit (Buffer *buffer)
2063 xfree (buffer->data);
2070 Buffer *buffer = (Buffer *) xcalloc (1, sizeof (Buffer));
2072 buffer_init (buffer);
2079 buffer_free (Buffer *buffer)
2081 buffer_uninit (buffer);
2087 buffer_append (Buffer *buffer, const char *data)
2089 buffer_append_len (buffer, data, strlen (data));
2094 buffer_append_len (Buffer *buffer, const char *data, size_t len)
2096 if (buffer->len + len + 1 >= buffer->allocated)
2098 buffer->allocated = buffer->len + len + 1024;
2099 buffer->data = xrealloc (buffer->data, buffer->allocated);
2102 memcpy (buffer->data + buffer->len, data, len);
2105 buffer->data[buffer->len] = '\0';
2110 buffer_copy (Buffer *buffer)
2112 char *copy = xmalloc (buffer->len + 1);
2114 memcpy (copy, buffer->data, buffer->len + 1);
2121 buffer_clear (Buffer *buffer)
2124 buffer->data[0] = '\0';
2129 buffer_ptr (Buffer *buffer)
2131 return buffer->data;
2136 buffer_len (Buffer *buffer)
2142 * Escapes the name of a file so that the shell groks it in 'single'
2143 * quotation marks. The resulting pointer has to be free()ed when not
2147 shell_escape(const char *fn)
2151 char *retval, *outp;
2153 for(inp = fn; *inp; ++inp)
2156 case '\'': len += 4; break;
2157 default: len += 1; break;
2160 outp = retval = malloc(len + 1);
2162 return NULL; /* perhaps one should do better error handling here */
2163 for(inp = fn; *inp; ++inp)
2166 case '\'': *outp++ = '\''; *outp++ = '\\'; *outp++ = '\'', *outp++ = '\''; break;
2167 default: *outp++ = *inp; break;