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 media_name = xstrdup (token2);
177 else if (MATCH (token, "DefaultOutputMethod:"))
179 token2 = GET_TOKEN (NULL);
181 if (MATCH (token2, "printer"))
182 output_file = OUTPUT_FILE_NONE;
183 else if (MATCH (token2, "stdout"))
184 output_file = OUTPUT_FILE_STDOUT;
186 CFG_FATAL ((stderr, _("illegal value \"%s\" for option %s"),
189 else if (MATCH (token, "DownloadFont:"))
191 token2 = GET_TOKEN (NULL);
193 strhash_put (download_fonts, token2, strlen (token2) + 1, NULL,
196 else if (MATCH (token, "EscapeChar:"))
198 token2 = GET_TOKEN (NULL);
200 escape_char = atoi (token2);
201 if (escape_char < 0 || escape_char > 255)
202 CFG_FATAL ((stderr, _("invalid value \"%s\" for option %s"),
205 else if (MATCH (token, "FormFeedType:"))
207 token2 = GET_TOKEN (NULL);
209 if (MATCH (token2, "column"))
210 formfeed_type = FORMFEED_COLUMN;
211 else if (MATCH (token2, "page"))
212 formfeed_type = FORMFEED_PAGE;
214 CFG_FATAL ((stderr, _("illegal value \"%s\" for option %s"),
217 else if (MATCH (token, "GeneratePageSize:"))
219 token2 = GET_TOKEN (NULL);
221 generate_PageSize = atoi (token2);
223 else if (MATCH (token, "HighlightBarGray:"))
225 token2 = GET_TOKEN (NULL);
227 highlight_bar_gray = atof (token2);
229 else if (MATCH (token, "HighlightBars:"))
231 token2 = GET_TOKEN (NULL);
233 highlight_bars = atoi (token2);
235 else if (MATCH (token, "LibraryPath:"))
237 token2 = GET_TOKEN (NULL);
240 libpath = xstrdup (token2);
242 else if (MATCH (token, "MarkWrappedLines:"))
244 token2 = GET_TOKEN (NULL);
246 xfree (mark_wrapped_lines_style_name);
247 mark_wrapped_lines_style_name = xstrdup (token2);
249 else if (MATCH (token, "Media:"))
252 int w, h, llx, lly, urx, ury;
254 token2 = GET_TOKEN (NULL);
258 token2 = GET_TOKEN (NULL);
262 token2 = GET_TOKEN (NULL);
266 token2 = GET_TOKEN (NULL);
270 token2 = GET_TOKEN (NULL);
274 token2 = GET_TOKEN (NULL);
278 token2 = GET_TOKEN (NULL);
282 add_media (name, w, h, llx, lly, urx, ury);
284 else if (MATCH (token, "NoJobHeaderSwitch:"))
286 token2 = GET_LINE_TOKEN (NULL);
288 xfree (no_job_header_switch);
289 no_job_header_switch = xstrdup (token2);
291 else if (MATCH (token, "NonPrintableFormat:"))
293 token2 = GET_TOKEN (NULL);
296 npf_name = xstrdup (token2);
298 else if (MATCH (token, "OutputFirstLine:"))
300 token2 = GET_LINE_TOKEN (NULL);
302 xfree (output_first_line);
303 output_first_line = xstrdup (token2);
305 else if (MATCH (token, "PageLabelFormat:"))
307 token2 = GET_TOKEN (NULL);
309 xfree (page_label_format);
310 page_label_format = xstrdup (token2);
312 else if (MATCH (token, "PagePrefeed:"))
314 token2 = GET_TOKEN (NULL);
316 page_prefeed = atoi (token2);
318 else if (MATCH (token, "PostScriptLevel:"))
320 token2 = GET_TOKEN (NULL);
322 pslevel = atoi (token2);
324 else if (MATCH (token, "Printer:"))
326 token2 = GET_TOKEN (NULL);
329 printer = xstrdup (token2);
331 else if (MATCH (token, "QueueParam:"))
333 token2 = GET_LINE_TOKEN (NULL);
336 queue_param = xstrdup (token2);
338 else if (MATCH (token, "SetPageDevice:"))
340 token2 = GET_LINE_TOKEN (NULL);
342 parse_key_value_pair (pagedevice, token2);
344 else if (MATCH (token, "Spooler:"))
346 token2 = GET_TOKEN (NULL);
348 xfree (spooler_command);
349 spooler_command = xstrdup (token2);
351 else if (MATCH (token, "StatesBinary:"))
353 token2 = GET_TOKEN (NULL);
355 xfree (states_binary);
356 states_binary = xstrdup (token2);
358 else if (MATCH (token, "StatesColor:"))
360 token2 = GET_TOKEN (NULL);
362 states_color = atoi (token2);
364 else if (MATCH (token, "StatesConfigFile:"))
366 token2 = GET_LINE_TOKEN (NULL);
368 xfree (states_config_file);
369 states_config_file = xstrdup (token2);
371 else if (MATCH (token, "StatesHighlightStyle:"))
373 token2 = GET_TOKEN (NULL);
375 xfree (states_highlight_style);
376 states_highlight_style = xstrdup (token2);
378 else if (MATCH (token, "StatesPath:"))
380 token2 = GET_LINE_TOKEN (NULL);
383 states_path = xstrdup (token2);
385 else if (MATCH (token, "StatusDict:"))
387 token2 = GET_TOKEN (NULL);
389 parse_key_value_pair (statusdict, token2);
391 else if (MATCH (token, "TOCFormat:"))
393 token2 = GET_LINE_TOKEN (NULL);
395 toc_fmt_string = xstrdup (token2);
397 else if (MATCH (token, "Underlay:"))
399 token2 = GET_LINE_TOKEN (NULL);
401 underlay = xmalloc (strlen (token2) + 1);
402 strcpy (underlay, token2);
404 else if (MATCH (token, "UnderlayAngle:"))
406 token2 = GET_TOKEN (NULL);
408 ul_angle = atof (token2);
411 else if (MATCH (token, "UnderlayFont:"))
413 token2 = GET_TOKEN (NULL);
415 if (!parse_font_spec (token2, &ul_font, &ul_ptsize, NULL))
416 CFG_FATAL ((stderr, _("malformed font spec: %s"), token2));
418 else if (MATCH (token, "UnderlayGray:"))
420 token2 = GET_TOKEN (NULL);
422 ul_gray = atof (token2);
424 else if (MATCH (token, "UnderlayPosition:"))
426 token2 = GET_TOKEN (NULL);
429 ul_position = xstrdup (token2);
432 else if (MATCH (token, "UnderlayStyle:"))
434 token2 = GET_TOKEN (NULL);
436 xfree (ul_style_str);
437 ul_style_str = xstrdup (token2);
440 CFG_FATAL ((stderr, _("illegal option: %s"), token));
443 buffer_uninit (&fname);
449 add_media (char *name, int w, int h, int llx, int lly, int urx, int ury)
455 "add_media: name=%s, w=%d, h=%d, llx=%d, lly=%d, urx=%d, ury=%d\n",
456 name, w, h, llx, lly, urx, ury));
458 entry = xcalloc (1, sizeof (*entry));
459 entry->name = xmalloc (strlen (name) + 1);
461 strcpy (entry->name, name);
469 entry->next = media_names;
475 do_list_missing_characters (int *array)
480 for (i = 0; i < 256; i++)
483 fprintf (stderr, "%3d ", i);
486 fprintf (stderr, "\n");
490 fprintf (stderr, "\n");
495 file_existsp (char *name, char *suffix)
501 ctx.suffix = suffix ? suffix : "";
502 ctx.fullname = buffer_alloc ();
504 result = pathwalk (libpath, file_lookup, &ctx);
506 buffer_free (ctx.fullname);
513 paste_file (char *name, char *suffix)
519 int pending_comment = 0;
523 ctx.suffix = suffix ? suffix : "";
524 ctx.fullname = buffer_alloc ();
526 if (!pathwalk (libpath, file_lookup, &ctx))
528 buffer_free (ctx.fullname);
531 fp = fopen (buffer_ptr (ctx.fullname), "r");
534 buffer_free (ctx.fullname);
538 /* Find the end of the header. */
539 #define HDR_TAG "% -- code follows this line --"
540 while ((fgets (buf, sizeof (buf), fp)))
543 if (strncmp (buf, HDR_TAG, strlen (HDR_TAG)) == 0)
547 /* Dump rest of file. */
548 while ((fgets (buf, sizeof (buf), fp)))
553 * Document needed resources?
555 #define RESOURCE_DSC "%%DocumentNeededResources:"
556 #define CONT_DSC "%%+"
557 if (strncmp (buf, RESOURCE_DSC, strlen (RESOURCE_DSC)) == 0)
561 strcpy (resources, buf + strlen (RESOURCE_DSC));
565 /* Register needed resources. */
566 cp = GET_TOKEN (resources);
568 /* Get the next line. */
571 if (MATCH (cp, "font"))
573 for (cp = GET_TOKEN (NULL); cp; cp = GET_TOKEN (NULL))
574 /* Is this font already known? */
575 if (!strhash_get (res_fonts, cp, strlen (cp) + 1,
578 /* Not it is not, we must include this resource. */
579 fprintf (ofp, "%%%%IncludeResource: font %s\n", cp);
582 * And register that this resource is needed in
585 strhash_put (res_fonts, cp, strlen (cp) + 1, NULL, NULL);
588 /* Do not pass this DSC row to the output. */
592 /* Unknown resource, ignore. */
595 else if (pending_comment
596 && strncmp (buf, CONT_DSC, strlen (CONT_DSC)) == 0)
598 strcpy (resources, buf + strlen (CONT_DSC));
599 goto parse_resources;
605 * `%Format' directive?
607 #define DIRECTIVE_FORMAT "%Format:"
608 if (strncmp (buf, DIRECTIVE_FORMAT, strlen (DIRECTIVE_FORMAT)) == 0)
615 /* Skip the leading whitespace. */
616 for (i = strlen (DIRECTIVE_FORMAT); buf[i] && isspace (buf[i]); i++)
619 FATAL ((stderr, _("%s:%d: %%Format: no name"),
620 buffer_ptr (ctx.fullname), line));
624 j < sizeof (name) - 1 && buf[i] && !isspace (buf[i]);
629 if (j >= sizeof (name) - 1)
630 FATAL ((stderr, _("%s:%d: %%Format: too long name, maxlen=%d"),
631 buffer_ptr (ctx.fullname), line, sizeof (name) - 1));
633 /* Find the start of the format string. */
634 for (; buf[i] && isspace (buf[i]); i++)
639 for (j--; isspace (buf[j]) && j > i; j--)
643 MESSAGE (2, (stderr, "%%Format: %s %.*s\n", name, j - i, buf + i));
645 cp = xmalloc (j - i + 1);
646 memcpy (cp, buf + i, j - i);
649 strhash_put (user_strings, name, strlen (name) + 1, cp,
653 _("%s:%d: %%Format: name \"%s\" is already defined"),
654 buffer_ptr (ctx.fullname), line, name));
656 /* All done with the `%Format' directive. */
661 * `%HeaderHeight' directive?
663 #define DIRECTIVE_HEADERHEIGHT "%HeaderHeight:"
664 if (strncmp (buf, DIRECTIVE_HEADERHEIGHT,
665 strlen (DIRECTIVE_HEADERHEIGHT)) == 0)
669 /* Find the start of the pts argument. */
670 for (i = strlen (DIRECTIVE_HEADERHEIGHT);
671 buf[i] && !isspace (buf[i]); i++)
674 FATAL ((stderr, _("%s:%d: %%HeaderHeight: no argument"),
675 buffer_ptr (ctx.fullname), line));
677 d_header_h = atoi (buf + i);
678 MESSAGE (2, (stderr, "%%HeaderHeight: %d\n", d_header_h));
683 * `%FooterHeight' directive?
685 #define DIRECTIVE_FOOTERHEIGHT "%FooterHeight:"
686 if (strncmp (buf, DIRECTIVE_FOOTERHEIGHT,
687 strlen (DIRECTIVE_FOOTERHEIGHT)) == 0)
691 /* Find the start of the pts argument. */
692 for (i = strlen (DIRECTIVE_FOOTERHEIGHT);
693 buf[i] && !isspace (buf[i]); i++)
696 FATAL ((stderr, _("%s:%d: %%FooterHeight: no argument"),
697 buffer_ptr (ctx.fullname), line));
699 d_footer_h = atoi (buf + i);
700 MESSAGE (2, (stderr, "%%FooterHeight: %d\n", d_footer_h));
704 /* Nothing special, just copy it to the output. */
709 buffer_free (ctx.fullname);
716 parse_font_spec (char *spec_a, char **name_return, FontPoint *size_return,
717 InputEncoding *encoding_return)
724 spec = xstrdup (spec_a);
726 /* Check for the `namesize:encoding' format. */
727 encp = strrchr (spec, ':');
734 /* The `name@ptsize' format? */
735 cp = strchr (spec, '@');
741 /* No ptsize after '@'. */
749 /* The old `nameptsize' format. */
750 i = strlen (spec) - 1;
751 if (i <= 0 || !ISNUMBERDIGIT (spec[i]))
757 for (i--; i >= 0 && ISNUMBERDIGIT (spec[i]); i--)
766 /* We accept one slash for the `pt/pt' format. */
767 for (i--; i >= 0 && ISNUMBERDIGIT (spec[i]); i--)
777 /* Now, <i> points to the end of the name. Let's set the <cp>
778 to the beginning of the point size and share a little code
779 with the other format. */
783 /* Check the font point size. */
784 cp2 = strchr (cp, '/');
788 size_return->w = atof (cp);
789 size_return->h = atof (cp2);
792 size_return->w = size_return->h = atof (cp);
794 /* Extract the font name. */
795 *name_return = (char *) xcalloc (1, i + 1);
796 strncpy (*name_return, spec, i);
798 /* Check the input encoding. */
803 if (encoding_return == NULL)
805 /* We don't allow it here. */
810 for (i = 0; !found && encodings[i].names[0]; i++)
811 for (j = 0; j < 3; j++)
812 if (encodings[i].names[j] != NULL && MATCH (encodings[i].names[j],
816 *encoding_return = encodings[i].encoding;
817 encp = encodings[i].names[0];
830 /* The spec didn't contain the encoding part. Use our global default. */
831 encp = encoding_name;
833 *encoding_return = encoding;
838 "parse_font_spec(): name=%.*s, size=%g/%g, encoding=%s\n", i,
839 *name_return, size_return->w, size_return->h,
842 if (size_return->w < 0.0 && size_return->h < 0.0)
843 MESSAGE (0, (stderr, _("%s: warning: font size is negative\n"), program));
844 else if (size_return->w < 0.0)
845 MESSAGE (0, (stderr, _("%s: warning: font width is negative\n"), program));
846 else if (size_return->h < 0.0)
847 MESSAGE (0, (stderr, _("%s: warning: font height is negative\n"),
855 read_font_info (void)
857 CachedFontInfo *font_info;
859 int font_info_cached = 1;
862 unsigned int enc_flags = 0;
866 MESSAGE (2, (stderr, _("reading AFM info for font \"%s\"\n"), Fname));
868 if (accept_composites)
869 enc_flags = AFM_ENCODE_ACCEPT_COMPOSITES;
875 buffer_append (&fkey, Fname);
876 sprintf (buf, "@%f:%d", Fpt.w, encoding);
877 buffer_append (&fkey, buf);
879 if (!strhash_get (afm_info_cache, buffer_ptr (&fkey),
880 strlen (buffer_ptr (&fkey)), (void **) &font_info))
884 /* Couldn't find it from our cache, open open AFM file. */
885 if (!strhash_get (afm_cache, Fname, strlen (Fname), (void **) &font))
887 /* AFM file was not cached, open it from disk. */
888 error = afm_open_font (afm, AFM_I_COMPOSITES, Fname, &font);
889 if (error != AFM_SUCCESS)
891 #define COUR "Courier"
893 * Do not report failures for "Courier*" fonts because
894 * AFM library's default font will fix them.
896 if (strncmp (Fname, COUR, strlen (COUR)) != 0)
899 _("couldn't open AFM file for font \"%s\", using default\n"),
901 error = afm_open_default_font (afm, &font);
902 if (error != AFM_SUCCESS)
904 afm_error_to_string (error, buf);
906 _("couldn't open AFM file for the default font: %s"),
911 /* Apply encoding. */
915 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_1,
920 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_2,
925 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_3,
930 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_4,
935 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_5,
940 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_7,
945 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_9,
949 case ENC_ISO_8859_10:
950 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_10,
955 (void) afm_font_encoding (font, AFM_ENCODING_ASCII, enc_flags);
959 /* First apply standard 7bit ASCII encoding. */
960 (void) afm_font_encoding (font, AFM_ENCODING_ASCII, enc_flags);
962 /* Then add those scand characters. */
963 for (i = 0; enc_7bit_ascii_fise[i].name; i++)
964 (void) afm_font_encode (font, enc_7bit_ascii_fise[i].code,
965 enc_7bit_ascii_fise[i].name,
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_dkno[i].name; i++)
975 (void) afm_font_encode (font, enc_7bit_ascii_dkno[i].code,
976 enc_7bit_ascii_dkno[i].name,
981 (void) afm_font_encoding (font, AFM_ENCODING_IBMPC, enc_flags);
985 (void) afm_font_encoding (font, AFM_ENCODING_MAC, enc_flags);
989 (void) afm_font_encoding (font, AFM_ENCODING_VMS, enc_flags);
993 (void) afm_font_encoding (font, AFM_ENCODING_HP8, enc_flags);
997 (void) afm_font_encoding (font, AFM_ENCODING_KOI8, enc_flags);
1001 /* Let's use font's default encoding -- nothing here. */
1005 /* Put it to the AFM cache. */
1006 if (!strhash_put (afm_cache, Fname, strlen (Fname), font, NULL))
1010 font_info = (CachedFontInfo *) xcalloc (1, sizeof (*font_info));
1011 /* Read character widths and types. */
1012 for (i = 0; i < 256; i++)
1016 (void) afm_font_charwidth (font, Fpt.w, i, &w0x, &w0y);
1017 font_info->font_widths[i] = w0x;
1019 if (font->encoding[i] == AFM_ENC_NONE)
1020 font_info->font_ctype[i] = ' ';
1021 else if (font->encoding[i] == AFM_ENC_NON_EXISTENT)
1022 font_info->font_ctype[i] = '.';
1024 font_info->font_ctype[i] = '*';
1027 font_info->font_is_fixed
1028 = font->writing_direction_metrics[0].IsFixedPitch;
1029 font_info->font_bbox_lly = font->global_info.FontBBox_lly;
1032 (void) afm_close_font (font);
1034 /* Store font information to the AFM information cache. */
1035 if (!strhash_put (afm_info_cache, buffer_ptr (&fkey),
1036 strlen (buffer_ptr (&fkey)), font_info, NULL))
1037 font_info_cached = 0;
1040 /* Select character widths and types. */
1041 memcpy (font_widths, font_info->font_widths, 256 * sizeof (double));
1042 memcpy (font_ctype, font_info->font_ctype, 256);
1044 font_is_fixed = font_info->font_is_fixed;
1045 font_bbox_lly = font_info->font_bbox_lly;
1047 if (!font_info_cached)
1050 buffer_uninit (&fkey);
1055 download_font (char *name)
1059 struct stat stat_st;
1061 unsigned char buf[4096];
1066 /* Get font prefix. */
1067 error = afm_font_prefix (afm, name, &prefix);
1068 if (error != AFM_SUCCESS)
1069 /* Font is unknown, nothing to download. */
1072 /* Check if we have a font description file. */
1074 buffer_init (&fname);
1077 buffer_append (&fname, prefix);
1078 buffer_append (&fname, ".pfa");
1079 if (stat (buffer_ptr (&fname), &stat_st) != 0)
1082 buffer_clear (&fname);
1083 buffer_append (&fname, prefix);
1084 buffer_append (&fname, ".pfb");
1085 if (stat (buffer_ptr (&fname), &stat_st) != 0)
1087 /* Couldn't find font description file, nothing to download. */
1088 buffer_uninit (&fname);
1093 /* Ok, fine. Font was found. */
1095 MESSAGE (1, (stderr, _("downloading font \"%s\"\n"), name));
1096 fp = fopen (buffer_ptr (&fname), "rb");
1099 MESSAGE (0, (stderr,
1100 _("couldn't open font description file \"%s\": %s\n"),
1101 buffer_ptr (&fname), strerror (errno)));
1102 buffer_uninit (&fname);
1105 buffer_uninit (&fname);
1108 fprintf (ofp, "%%%%BeginResource: font %s\n", name);
1110 /* Check file type. */
1114 /* Not much to do here. */
1121 unsigned int to_read;
1131 /* Read 6-byte long header. */
1132 i = fread (buf, 1, 6, fp);
1136 chunk = buf[2] | (buf[3] << 8) | (buf[4] << 16) | (buf[5] << 24);
1138 /* Check chunk type. */
1145 to_read = sizeof (buf) < chunk ? sizeof (buf) : chunk;
1146 i = fread (buf, 1, to_read, fp);
1153 /* Check and fix Mac-newlines. */
1154 for (j = 0; j < i; j++)
1156 if (j == 0 && last_was_cr && buf[0] != '\n')
1159 fputc (buf[0], ofp);
1161 else if (buf[j] == '\r' && j + 1 < i
1162 && buf[j + 1] != '\n')
1166 else if (buf[j] != '\r')
1167 fputc (buf[j], ofp);
1171 last_was_cr = (buf[i - 1] == '\r');
1175 case 2: /* binary data */
1178 to_read = sizeof (buf) < chunk ? sizeof (buf) : chunk;
1179 i = fread (buf, 1, to_read, fp);
1186 for (j = 0; j < i; j++)
1188 fprintf (ofp, "%02X", buf[j]);
1189 if ((j + 1) % 32 == 0)
1190 fprintf (ofp, "\n");
1201 /* Force a linebreak after each chunk. */
1202 fprintf (ofp, "\n");
1209 while ((i = fread (buf, 1, sizeof (buf), fp)) != 0)
1210 fwrite (buf, 1, i, ofp);
1213 fprintf (ofp, "%%%%EndResource\n");
1215 /* Remove font from needed resources. */
1216 (void) strhash_delete (res_fonts, name, strlen (name) + 1, (void **) &cp);
1223 escape_string (char *string)
1229 /* Count the length of the result string. */
1230 for (len = 0, i = 0; string[i]; i++)
1243 /* Create result. */
1244 cp = xmalloc (len + 1);
1247 for (i = 0, j = 0; string[i]; i++)
1257 cp[j++] = string[i];
1268 * Help macros for the format_user_string() function.
1271 #define NEED_NBYTES(n) \
1273 if (rbufpos + (n) >= rbuflen) \
1275 rbuflen += (n) + 1024; \
1276 rbuf = xrealloc (rbuf, rbuflen); \
1280 #define APPEND_CH(ch) \
1283 NEED_NBYTES (width); \
1284 if (width && justification < 0) \
1285 rbuf[rbufpos++] = (ch); \
1286 for (a = 0; a < width - 1; a++) \
1287 rbuf[rbufpos++] = ' '; \
1288 if (!width || justification > 0) \
1289 rbuf[rbufpos++] = (ch); \
1292 #define APPEND_STR(str) \
1294 int len = strlen ((str)); \
1300 nspace = width - len; \
1302 NEED_NBYTES (nspace + len); \
1303 if (width && justification > 0) \
1304 for (; nspace; nspace--) \
1305 rbuf[rbufpos++] = ' '; \
1307 memcpy (rbuf + rbufpos, str, len); \
1310 if (width && justification < 0) \
1311 for (; nspace; nspace--) \
1312 rbuf[rbufpos++] = ' '; \
1316 format_user_string (char *context_name, char *str)
1327 int justification = 1;
1329 /* Format string. */
1330 for (i = 0; str[i] != '\0'; i++)
1336 if (type == '%' || type == '$')
1342 /* Get optional width and justification. */
1348 while (isdigit (str[i]))
1349 width = width * 10 + str[i++] - '0';
1351 /* Handle escapes. */
1354 /* General state related %-escapes. */
1357 case '%': /* `%%' character `%' */
1361 case 'c': /* `%c' trailing component of pwd. */
1362 getcwd (buf, sizeof (buf));
1363 cp = strrchr (buf, '/');
1371 case 'C': /* `%C' runtime in `hh:mm:ss' format */
1372 sprintf (buf, "%02d:%02d:%02d", run_tm.tm_hour,
1373 run_tm.tm_min, run_tm.tm_sec);
1377 case 'd': /* `%d' current working directory */
1378 getcwd (buf, sizeof (buf));
1383 if (str[i + 1] == '{')
1385 /* `%D{}' format run date with strftime() */
1387 j < sizeof (buf2) && str[i] && str[i] != '}';
1392 _("%s: too long format for %%D{} escape"),
1396 strftime (buf, sizeof (buf), buf2, &run_tm);
1400 /* `%D' run date in `yy-mm-dd' format */
1401 sprintf (buf, "%02d-%02d-%02d", run_tm.tm_year % 100,
1402 run_tm.tm_mon + 1, run_tm.tm_mday);
1407 case 'E': /* `%E' run date in `yy/mm/dd' format */
1408 sprintf (buf, "%02d/%02d/%02d", run_tm.tm_year % 100,
1409 run_tm.tm_mon + 1, run_tm.tm_mday);
1413 case 'F': /* `%F' run date in `dd.mm.yyyy' format */
1414 sprintf (buf, "%d.%d.%d",
1417 run_tm.tm_year + 1900);
1421 case 'H': /* `%H' document title */
1425 case 'm': /* `%m' the hostname up to the first `.' */
1426 (void) gethostname (buf, sizeof (buf));
1427 cp = strchr (buf, '.');
1433 case 'M': /* `%M' the full hostname */
1434 (void) gethostname (buf, sizeof (buf));
1438 case 'n': /* `%n' username */
1439 APPEND_STR (passwd->pw_name);
1442 case 'N': /* `%N' pw_gecos up to the first `,' char */
1443 strcpy (buf, passwd->pw_gecos);
1444 cp = strchr (buf, ',');
1450 case 't': /* `%t' runtime in 12-hour am/pm format */
1451 sprintf (buf, "%d:%d%s",
1453 ? run_tm.tm_hour - 12 : run_tm.tm_hour,
1455 run_tm.tm_hour > 12 ? "pm" : "am");
1459 case 'T': /* `%T' runtime in 24-hour format */
1460 sprintf (buf, "%d:%d", run_tm.tm_hour, run_tm.tm_min);
1464 case '*': /* `%*' runtime in 24-hour format with secs */
1465 sprintf (buf, "%d:%d:%d", run_tm.tm_hour, run_tm.tm_min,
1470 case 'W': /* `%W' run date in `mm/dd/yy' format */
1471 sprintf (buf, "%02d/%02d/%02d", run_tm.tm_mon + 1,
1472 run_tm.tm_mday, run_tm.tm_year % 100);
1477 FATAL ((stderr, _("%s: unknown `%%' escape `%c' (%d)"),
1478 context_name, str[i], str[i]));
1484 /* Input file related $-escapes. */
1487 case '$': /* `$$' character `$' */
1491 case '%': /* `$%' current page number */
1493 sprintf (buf, "%d%c", current_pagenum, slice - 1 + 'A');
1495 sprintf (buf, "%d", current_pagenum);
1499 case '=': /* `$=' number of pages in this file */
1503 case 'p': /* `$p' number of pages processed so far */
1504 sprintf (buf, "%d", total_pages);
1508 case '(': /* $(ENVVAR) */
1510 str[i] && str[i] != ')' && j < sizeof (buf) - 1;
1515 FATAL ((stderr, _("%s: no closing ')' for $() escape"),
1518 FATAL ((stderr, _("%s: too long variable name for $() escape"),
1529 case 'C': /* `$C' modtime in `hh:mm:ss' format */
1530 sprintf (buf, "%02d:%02d:%02d", mod_tm.tm_hour,
1531 mod_tm.tm_min, mod_tm.tm_sec);
1536 if (str[i + 1] == '{')
1538 /* `$D{}' format modification date with strftime() */
1540 j < sizeof (buf2) && str[i] && str[i] != '}';
1545 _("%s: too long format for $D{} escape"),
1549 strftime (buf, sizeof (buf), buf2, &mod_tm);
1553 /* `$D' mod date in `yy-mm-dd' format */
1554 sprintf (buf, "%02d-%02d-%02d", mod_tm.tm_year % 100,
1555 mod_tm.tm_mon + 1, mod_tm.tm_mday);
1560 case 'E': /* `$E' mod date in `yy/mm/dd' format */
1561 sprintf (buf, "%02d/%02d/%02d", mod_tm.tm_year % 100,
1562 mod_tm.tm_mon + 1, mod_tm.tm_mday);
1566 case 'F': /* `$F' run date in `dd.mm.yyyy' format */
1567 sprintf (buf, "%d.%d.%d",
1570 mod_tm.tm_year + 1900);
1574 case 't': /* `$t' runtime in 12-hour am/pm format */
1575 sprintf (buf, "%d:%d%s",
1577 ? mod_tm.tm_hour - 12 : mod_tm.tm_hour,
1579 mod_tm.tm_hour > 12 ? "pm" : "am");
1583 case 'T': /* `$T' runtime in 24-hour format */
1584 sprintf (buf, "%d:%d", mod_tm.tm_hour, mod_tm.tm_min);
1588 case '*': /* `$*' runtime in 24-hour format with secs */
1589 sprintf (buf, "%d:%d:%d", mod_tm.tm_hour, mod_tm.tm_min,
1594 case 'v': /* `$v': input file number */
1595 sprintf (buf, "%d", input_filenum);
1599 case 'V': /* `$V': input file number in --toc format */
1602 sprintf (buf, "%d-", input_filenum);
1607 case 'W': /* `$W' run date in `mm/dd/yy' format */
1608 sprintf (buf, "%02d/%02d/%02d", mod_tm.tm_mon + 1,
1609 mod_tm.tm_mday, mod_tm.tm_year % 100);
1613 case 'N': /* `$N' the full name of the printed file */
1617 case 'n': /* `$n' input file name without directory */
1618 cp = strrchr (fname, '/');
1626 case 'L': /* `$L' number of lines in this file. */
1627 /* This is valid only for TOC-strings. */
1628 sprintf (buf, "%d", current_file_linenum - 1);
1633 FATAL ((stderr, _("%s: unknown `$' escape `%c' (%d)"),
1634 context_name, str[i], str[i]));
1638 /* Reset width so the else-arm goes ok at the next round. */
1647 /* Escape PS specials. */
1648 cp = escape_string (rbuf);
1656 parse_key_value_pair (StringHashPtr set, char *kv)
1661 cp = strchr (kv, ':');
1664 if (strhash_delete (set, kv, strlen (kv) + 1, (void **) &cp))
1670 buffer_append_len (&key, kv, cp - kv);
1672 strhash_put (set, buffer_ptr (&key), strlen (buffer_ptr (&key)) + 1,
1673 xstrdup (cp + 1), (void **) &cp);
1677 buffer_uninit (&key);
1683 count_key_value_set (StringHashPtr set)
1689 for (got = strhash_get_first (set, &cp, &j, &value); got;
1690 got = strhash_get_next (set, &cp, &j, &value))
1698 pathwalk (char *path, PathWalkProc proc, void *context)
1705 for (cp = path; cp; cp = strchr (cp, PATH_SEPARATOR))
1710 cp2 = strchr (cp, PATH_SEPARATOR);
1716 memcpy (buf, cp, len);
1719 i = (*proc) (buf, context);
1729 file_lookup (char *path, void *context)
1732 FileLookupCtx *ctx = context;
1733 struct stat stat_st;
1736 MESSAGE (2, (stderr, "file_lookup(): %s/%s%s\t", path, ctx->name,
1739 len = strlen (path);
1740 if (len && path[len - 1] == '/')
1743 buffer_clear (ctx->fullname);
1744 buffer_append_len (ctx->fullname, path, len);
1745 buffer_append (ctx->fullname, "/");
1746 buffer_append (ctx->fullname, ctx->name);
1747 buffer_append (ctx->fullname, ctx->suffix);
1749 i = stat (buffer_ptr (ctx->fullname), &stat_st) == 0;
1751 MESSAGE (2, (stderr, "#%c\n", i ? 't' : 'f'));
1758 tilde_subst (char *fname)
1762 struct passwd *pswd;
1766 if (fname[0] != '~')
1767 return xstrdup (fname);
1769 if (fname[1] == '/' || fname[1] == '\0')
1771 /* The the user's home directory from the `HOME' environment
1773 cp = getenv ("HOME");
1775 return xstrdup (fname);
1777 buffer_init (&buffer);
1778 buffer_append (&buffer, cp);
1779 buffer_append (&buffer, fname + 1);
1781 result = buffer_copy (&buffer);
1782 buffer_uninit (&buffer);
1787 /* Get user's login name. */
1788 for (i = 1; fname[i] && fname[i] != '/'; i++)
1791 buffer_init (&buffer);
1792 buffer_append_len (&buffer, fname + 1, i - 1);
1794 pswd = getpwnam (buffer_ptr (&buffer));
1795 buffer_uninit (&buffer);
1799 /* Found passwd entry. */
1800 buffer_init (&buffer);
1801 buffer_append (&buffer, pswd->pw_dir);
1802 buffer_append (&buffer, fname + i);
1804 result = buffer_copy (&buffer);
1805 buffer_uninit (&buffer);
1810 /* No match found. */
1811 return xstrdup (fname);
1816 parse_float (char *string, int units, int horizontal)
1821 val = strtod (string, &end);
1824 ERROR ((stderr, _("malformed float dimension: \"%s\""), string));
1846 val *= CHAR_WIDTH ('m');
1852 goto malformed_float;
1859 goto malformed_float;
1867 * InputStream functions.
1871 is_open (InputStream *is, FILE *fp, char *fname, char *input_filter)
1873 /* Init stream variables. */
1874 is->data_in_buf = 0;
1877 is->unget_ch = NULL;
1879 is->unget_alloc = 0;
1892 fname = input_filter_stdin;
1895 * Count the initial command length, this will grow dynamically
1896 * when file specifier `%s' is encountered from <input_filter>.
1898 cmdlen = strlen (input_filter) + 1;
1899 cmd = xmalloc (cmdlen);
1901 /* Create filter command. */
1903 for (i = 0; input_filter[i]; i++)
1905 if (input_filter[i] == '%')
1907 switch (input_filter[i + 1])
1910 /* Expand cmd-buffer. */
1911 if ((cp = shell_escape (fname)) != NULL)
1913 cmdlen += strlen (cp);
1914 cmd = xrealloc (cmd, cmdlen);
1916 /* Paste filename. */
1917 strcpy (cmd + pos, cp);
1931 cmd[pos++] = input_filter[i];
1936 cmd[pos++] = input_filter[i];
1940 is->fp = popen (cmd, "r");
1946 _("couldn't open input filter \"%s\" for file \"%s\": %s"),
1947 input_filter, fname ? fname : "(stdin)",
1954 /* Just open the stream. */
1960 is->fp = fopen (fname, "rb");
1963 ERROR ((stderr, _("couldn't open input file \"%s\": %s"), fname,
1975 is_close (InputStream *is)
1983 xfree (is->unget_ch);
1988 is_getc (InputStream *is)
1992 if (is->unget_pos > 0)
1994 ch = is->unget_ch[--is->unget_pos];
2000 /* Do we have any data left? */
2001 if (is->bufpos >= is->data_in_buf)
2004 if (is->nreads > 0 && is->data_in_buf < sizeof (is->buf))
2008 /* Read more data. */
2009 is->data_in_buf = fread (is->buf, 1, sizeof (is->buf), is->fp);
2016 return is->buf[is->bufpos++];
2021 is_ungetc (int ch, InputStream *is)
2023 if (is->unget_pos >= is->unget_alloc)
2025 is->unget_alloc += 1024;
2026 is->unget_ch = xrealloc (is->unget_ch, is->unget_alloc);
2029 is->unget_ch[is->unget_pos++] = ch;
2040 buffer_init (Buffer *buffer)
2042 buffer->allocated = 128;
2043 buffer->data = xmalloc (buffer->allocated);
2044 buffer->data[0] = '\0';
2050 buffer_uninit (Buffer *buffer)
2052 xfree (buffer->data);
2059 Buffer *buffer = (Buffer *) xcalloc (1, sizeof (Buffer));
2061 buffer_init (buffer);
2068 buffer_free (Buffer *buffer)
2070 buffer_uninit (buffer);
2076 buffer_append (Buffer *buffer, const char *data)
2078 buffer_append_len (buffer, data, strlen (data));
2083 buffer_append_len (Buffer *buffer, const char *data, size_t len)
2085 if (buffer->len + len + 1 >= buffer->allocated)
2087 buffer->allocated = buffer->len + len + 1024;
2088 buffer->data = xrealloc (buffer->data, buffer->allocated);
2091 memcpy (buffer->data + buffer->len, data, len);
2094 buffer->data[buffer->len] = '\0';
2099 buffer_copy (Buffer *buffer)
2101 char *copy = xmalloc (buffer->len + 1);
2103 memcpy (copy, buffer->data, buffer->len + 1);
2110 buffer_clear (Buffer *buffer)
2113 buffer->data[0] = '\0';
2118 buffer_ptr (Buffer *buffer)
2120 return buffer->data;
2125 buffer_len (Buffer *buffer)
2131 * Escapes the name of a file so that the shell groks it in 'single'
2132 * quotation marks. The resulting pointer has to be free()ed when not
2136 shell_escape(const char *fn)
2140 char *retval, *outp;
2142 for(inp = fn; *inp; ++inp)
2145 case '\'': len += 4; break;
2146 default: len += 1; break;
2149 outp = retval = malloc(len + 1);
2151 return NULL; /* perhaps one should do better error handling here */
2152 for(inp = fn; *inp; ++inp)
2155 case '\'': *outp++ = '\''; *outp++ = '\\'; *outp++ = '\'', *outp++ = '\''; break;
2156 default: *outp++ = *inp; break;