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));
444 buffer_uninit (&fname);
450 add_media (char *name, int w, int h, int llx, int lly, int urx, int ury)
456 "add_media: name=%s, w=%d, h=%d, llx=%d, lly=%d, urx=%d, ury=%d\n",
457 name, w, h, llx, lly, urx, ury));
459 entry = xcalloc (1, sizeof (*entry));
460 entry->name = xmalloc (strlen (name) + 1);
462 strcpy (entry->name, name);
470 entry->next = media_names;
476 do_list_missing_characters (int *array)
481 for (i = 0; i < 256; i++)
484 fprintf (stderr, "%3d ", i);
487 fprintf (stderr, "\n");
491 fprintf (stderr, "\n");
496 file_existsp (char *name, char *suffix)
502 ctx.suffix = suffix ? suffix : "";
503 ctx.fullname = buffer_alloc ();
505 result = pathwalk (libpath, file_lookup, &ctx);
507 buffer_free (ctx.fullname);
514 paste_file (char *name, char *suffix)
520 int pending_comment = 0;
524 ctx.suffix = suffix ? suffix : "";
525 ctx.fullname = buffer_alloc ();
527 if (!pathwalk (libpath, file_lookup, &ctx))
529 buffer_free (ctx.fullname);
532 fp = fopen (buffer_ptr (ctx.fullname), "r");
535 buffer_free (ctx.fullname);
539 /* Find the end of the header. */
540 #define HDR_TAG "% -- code follows this line --"
541 while ((fgets (buf, sizeof (buf), fp)))
544 if (strncmp (buf, HDR_TAG, strlen (HDR_TAG)) == 0)
548 /* Dump rest of file. */
549 while ((fgets (buf, sizeof (buf), fp)))
554 * Document needed resources?
556 #define RESOURCE_DSC "%%DocumentNeededResources:"
557 #define CONT_DSC "%%+"
558 if (strncmp (buf, RESOURCE_DSC, strlen (RESOURCE_DSC)) == 0)
562 strcpy (resources, buf + strlen (RESOURCE_DSC));
566 /* Register needed resources. */
567 cp = GET_TOKEN (resources);
569 /* Get the next line. */
572 if (MATCH (cp, "font"))
574 for (cp = GET_TOKEN (NULL); cp; cp = GET_TOKEN (NULL))
575 /* Is this font already known? */
576 if (!strhash_get (res_fonts, cp, strlen (cp) + 1,
579 /* Not it is not, we must include this resource. */
580 fprintf (ofp, "%%%%IncludeResource: font %s\n", cp);
583 * And register that this resource is needed in
586 strhash_put (res_fonts, cp, strlen (cp) + 1, NULL, NULL);
589 /* Do not pass this DSC row to the output. */
593 /* Unknown resource, ignore. */
596 else if (pending_comment
597 && strncmp (buf, CONT_DSC, strlen (CONT_DSC)) == 0)
599 strcpy (resources, buf + strlen (CONT_DSC));
600 goto parse_resources;
606 * `%Format' directive?
608 #define DIRECTIVE_FORMAT "%Format:"
609 if (strncmp (buf, DIRECTIVE_FORMAT, strlen (DIRECTIVE_FORMAT)) == 0)
616 /* Skip the leading whitespace. */
617 for (i = strlen (DIRECTIVE_FORMAT); buf[i] && isspace (buf[i]); i++)
620 FATAL ((stderr, _("%s:%d: %%Format: no name"),
621 buffer_ptr (ctx.fullname), line));
625 j < sizeof (name) - 1 && buf[i] && !isspace (buf[i]);
630 if (j >= sizeof (name) - 1)
631 FATAL ((stderr, _("%s:%d: %%Format: too long name, maxlen=%d"),
632 buffer_ptr (ctx.fullname), line, sizeof (name) - 1));
634 /* Find the start of the format string. */
635 for (; buf[i] && isspace (buf[i]); i++)
640 for (j--; isspace (buf[j]) && j > i; j--)
644 MESSAGE (2, (stderr, "%%Format: %s %.*s\n", name, j - i, buf + i));
646 cp = xmalloc (j - i + 1);
647 memcpy (cp, buf + i, j - i);
650 strhash_put (user_strings, name, strlen (name) + 1, cp,
654 _("%s:%d: %%Format: name \"%s\" is already defined"),
655 buffer_ptr (ctx.fullname), line, name));
657 /* All done with the `%Format' directive. */
662 * `%HeaderHeight' directive?
664 #define DIRECTIVE_HEADERHEIGHT "%HeaderHeight:"
665 if (strncmp (buf, DIRECTIVE_HEADERHEIGHT,
666 strlen (DIRECTIVE_HEADERHEIGHT)) == 0)
670 /* Find the start of the pts argument. */
671 for (i = strlen (DIRECTIVE_HEADERHEIGHT);
672 buf[i] && !isspace (buf[i]); i++)
675 FATAL ((stderr, _("%s:%d: %%HeaderHeight: no argument"),
676 buffer_ptr (ctx.fullname), line));
678 d_header_h = atoi (buf + i);
679 MESSAGE (2, (stderr, "%%HeaderHeight: %d\n", d_header_h));
684 * `%FooterHeight' directive?
686 #define DIRECTIVE_FOOTERHEIGHT "%FooterHeight:"
687 if (strncmp (buf, DIRECTIVE_FOOTERHEIGHT,
688 strlen (DIRECTIVE_FOOTERHEIGHT)) == 0)
692 /* Find the start of the pts argument. */
693 for (i = strlen (DIRECTIVE_FOOTERHEIGHT);
694 buf[i] && !isspace (buf[i]); i++)
697 FATAL ((stderr, _("%s:%d: %%FooterHeight: no argument"),
698 buffer_ptr (ctx.fullname), line));
700 d_footer_h = atoi (buf + i);
701 MESSAGE (2, (stderr, "%%FooterHeight: %d\n", d_footer_h));
705 /* Nothing special, just copy it to the output. */
710 buffer_free (ctx.fullname);
717 parse_font_spec (char *spec_a, char **name_return, FontPoint *size_return,
718 InputEncoding *encoding_return)
725 spec = xstrdup (spec_a);
727 /* Check for the `namesize:encoding' format. */
728 encp = strrchr (spec, ':');
735 /* The `name@ptsize' format? */
736 cp = strchr (spec, '@');
742 /* No ptsize after '@'. */
750 /* The old `nameptsize' format. */
751 i = strlen (spec) - 1;
752 if (i <= 0 || !ISNUMBERDIGIT (spec[i]))
758 for (i--; i >= 0 && ISNUMBERDIGIT (spec[i]); i--)
767 /* We accept one slash for the `pt/pt' format. */
768 for (i--; i >= 0 && ISNUMBERDIGIT (spec[i]); i--)
778 /* Now, <i> points to the end of the name. Let's set the <cp>
779 to the beginning of the point size and share a little code
780 with the other format. */
784 /* Check the font point size. */
785 cp2 = strchr (cp, '/');
789 size_return->w = atof (cp);
790 size_return->h = atof (cp2);
793 size_return->w = size_return->h = atof (cp);
795 /* Extract the font name. */
796 *name_return = (char *) xcalloc (1, i + 1);
797 strncpy (*name_return, spec, i);
799 /* Check the input encoding. */
804 if (encoding_return == NULL)
806 /* We don't allow it here. */
811 for (i = 0; !found && encodings[i].names[0]; i++)
812 for (j = 0; j < 3; j++)
813 if (encodings[i].names[j] != NULL && MATCH (encodings[i].names[j],
817 *encoding_return = encodings[i].encoding;
818 encp = encodings[i].names[0];
831 /* The spec didn't contain the encoding part. Use our global default. */
832 encp = encoding_name;
834 *encoding_return = encoding;
839 "parse_font_spec(): name=%.*s, size=%g/%g, encoding=%s\n", i,
840 *name_return, size_return->w, size_return->h,
843 if (size_return->w < 0.0 && size_return->h < 0.0)
844 MESSAGE (0, (stderr, _("%s: warning: font size is negative\n"), program));
845 else if (size_return->w < 0.0)
846 MESSAGE (0, (stderr, _("%s: warning: font width is negative\n"), program));
847 else if (size_return->h < 0.0)
848 MESSAGE (0, (stderr, _("%s: warning: font height is negative\n"),
856 read_font_info (void)
858 CachedFontInfo *font_info;
860 int font_info_cached = 1;
863 unsigned int enc_flags = 0;
867 MESSAGE (2, (stderr, _("reading AFM info for font \"%s\"\n"), Fname));
869 if (accept_composites)
870 enc_flags = AFM_ENCODE_ACCEPT_COMPOSITES;
876 buffer_append (&fkey, Fname);
877 sprintf (buf, "@%f:%d", Fpt.w, encoding);
878 buffer_append (&fkey, buf);
880 if (!strhash_get (afm_info_cache, buffer_ptr (&fkey),
881 strlen (buffer_ptr (&fkey)), (void **) &font_info))
885 /* Couldn't find it from our cache, open open AFM file. */
886 if (!strhash_get (afm_cache, Fname, strlen (Fname), (void **) &font))
888 /* AFM file was not cached, open it from disk. */
889 error = afm_open_font (afm, AFM_I_COMPOSITES, Fname, &font);
890 if (error != AFM_SUCCESS)
892 #define COUR "Courier"
894 * Do not report failures for "Courier*" fonts because
895 * AFM library's default font will fix them.
897 if (strncmp (Fname, COUR, strlen (COUR)) != 0)
900 _("couldn't open AFM file for font \"%s\", using default\n"),
902 error = afm_open_default_font (afm, &font);
903 if (error != AFM_SUCCESS)
905 afm_error_to_string (error, buf);
907 _("couldn't open AFM file for the default font: %s"),
912 /* Apply encoding. */
916 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_1,
921 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_2,
926 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_3,
931 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_4,
936 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_5,
941 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_7,
946 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_9,
950 case ENC_ISO_8859_10:
951 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_10,
956 (void) afm_font_encoding (font, AFM_ENCODING_ASCII, enc_flags);
960 /* First apply standard 7bit ASCII encoding. */
961 (void) afm_font_encoding (font, AFM_ENCODING_ASCII, enc_flags);
963 /* Then add those scand characters. */
964 for (i = 0; enc_7bit_ascii_fise[i].name; i++)
965 (void) afm_font_encode (font, enc_7bit_ascii_fise[i].code,
966 enc_7bit_ascii_fise[i].name,
971 /* First apply standard 7bit ASCII encoding. */
972 (void) afm_font_encoding (font, AFM_ENCODING_ASCII, enc_flags);
974 /* Then add those scand characters. */
975 for (i = 0; enc_7bit_ascii_dkno[i].name; i++)
976 (void) afm_font_encode (font, enc_7bit_ascii_dkno[i].code,
977 enc_7bit_ascii_dkno[i].name,
982 (void) afm_font_encoding (font, AFM_ENCODING_IBMPC, enc_flags);
986 (void) afm_font_encoding (font, AFM_ENCODING_MAC, enc_flags);
990 (void) afm_font_encoding (font, AFM_ENCODING_VMS, enc_flags);
994 (void) afm_font_encoding (font, AFM_ENCODING_HP8, enc_flags);
998 (void) afm_font_encoding (font, AFM_ENCODING_KOI8, enc_flags);
1002 /* Let's use font's default encoding -- nothing here. */
1006 /* Put it to the AFM cache. */
1007 if (!strhash_put (afm_cache, Fname, strlen (Fname), font, NULL))
1011 font_info = (CachedFontInfo *) xcalloc (1, sizeof (*font_info));
1012 /* Read character widths and types. */
1013 for (i = 0; i < 256; i++)
1017 (void) afm_font_charwidth (font, Fpt.w, i, &w0x, &w0y);
1018 font_info->font_widths[i] = w0x;
1020 if (font->encoding[i] == AFM_ENC_NONE)
1021 font_info->font_ctype[i] = ' ';
1022 else if (font->encoding[i] == AFM_ENC_NON_EXISTENT)
1023 font_info->font_ctype[i] = '.';
1025 font_info->font_ctype[i] = '*';
1028 font_info->font_is_fixed
1029 = font->writing_direction_metrics[0].IsFixedPitch;
1030 font_info->font_bbox_lly = font->global_info.FontBBox_lly;
1033 (void) afm_close_font (font);
1035 /* Store font information to the AFM information cache. */
1036 if (!strhash_put (afm_info_cache, buffer_ptr (&fkey),
1037 strlen (buffer_ptr (&fkey)), font_info, NULL))
1038 font_info_cached = 0;
1041 /* Select character widths and types. */
1042 memcpy (font_widths, font_info->font_widths, 256 * sizeof (double));
1043 memcpy (font_ctype, font_info->font_ctype, 256);
1045 font_is_fixed = font_info->font_is_fixed;
1046 font_bbox_lly = font_info->font_bbox_lly;
1048 if (!font_info_cached)
1051 buffer_uninit (&fkey);
1056 download_font (char *name)
1060 struct stat stat_st;
1062 unsigned char buf[4096];
1067 /* Get font prefix. */
1068 error = afm_font_prefix (afm, name, &prefix);
1069 if (error != AFM_SUCCESS)
1070 /* Font is unknown, nothing to download. */
1073 /* Check if we have a font description file. */
1075 buffer_init (&fname);
1078 buffer_append (&fname, prefix);
1079 buffer_append (&fname, ".pfa");
1080 if (stat (buffer_ptr (&fname), &stat_st) != 0)
1083 buffer_clear (&fname);
1084 buffer_append (&fname, prefix);
1085 buffer_append (&fname, ".pfb");
1086 if (stat (buffer_ptr (&fname), &stat_st) != 0)
1088 /* Couldn't find font description file, nothing to download. */
1089 buffer_uninit (&fname);
1094 /* Ok, fine. Font was found. */
1096 MESSAGE (1, (stderr, _("downloading font \"%s\"\n"), name));
1097 fp = fopen (buffer_ptr (&fname), "rb");
1100 MESSAGE (0, (stderr,
1101 _("couldn't open font description file \"%s\": %s\n"),
1102 buffer_ptr (&fname), strerror (errno)));
1103 buffer_uninit (&fname);
1106 buffer_uninit (&fname);
1109 fprintf (ofp, "%%%%BeginResource: font %s\n", name);
1111 /* Check file type. */
1115 /* Not much to do here. */
1122 unsigned int to_read;
1132 /* Read 6-byte long header. */
1133 i = fread (buf, 1, 6, fp);
1137 chunk = buf[2] | (buf[3] << 8) | (buf[4] << 16) | (buf[5] << 24);
1139 /* Check chunk type. */
1146 to_read = sizeof (buf) < chunk ? sizeof (buf) : chunk;
1147 i = fread (buf, 1, to_read, fp);
1154 /* Check and fix Mac-newlines. */
1155 for (j = 0; j < i; j++)
1157 if (j == 0 && last_was_cr && buf[0] != '\n')
1160 fputc (buf[0], ofp);
1162 else if (buf[j] == '\r' && j + 1 < i
1163 && buf[j + 1] != '\n')
1167 else if (buf[j] != '\r')
1168 fputc (buf[j], ofp);
1172 last_was_cr = (buf[i - 1] == '\r');
1176 case 2: /* binary data */
1179 to_read = sizeof (buf) < chunk ? sizeof (buf) : chunk;
1180 i = fread (buf, 1, to_read, fp);
1187 for (j = 0; j < i; j++)
1189 fprintf (ofp, "%02X", buf[j]);
1190 if ((j + 1) % 32 == 0)
1191 fprintf (ofp, "\n");
1202 /* Force a linebreak after each chunk. */
1203 fprintf (ofp, "\n");
1210 while ((i = fread (buf, 1, sizeof (buf), fp)) != 0)
1211 fwrite (buf, 1, i, ofp);
1214 fprintf (ofp, "%%%%EndResource\n");
1216 /* Remove font from needed resources. */
1217 (void) strhash_delete (res_fonts, name, strlen (name) + 1, (void **) &cp);
1224 escape_string (char *string)
1230 /* Count the length of the result string. */
1231 for (len = 0, i = 0; string[i]; i++)
1244 /* Create result. */
1245 cp = xmalloc (len + 1);
1248 for (i = 0, j = 0; string[i]; i++)
1258 cp[j++] = string[i];
1269 * Help macros for the format_user_string() function.
1272 #define NEED_NBYTES(n) \
1274 if (rbufpos + (n) >= rbuflen) \
1276 rbuflen += (n) + 1024; \
1277 rbuf = xrealloc (rbuf, rbuflen); \
1281 #define APPEND_CH(ch) \
1284 NEED_NBYTES (width); \
1285 if (width && justification < 0) \
1286 rbuf[rbufpos++] = (ch); \
1287 for (a = 0; a < width - 1; a++) \
1288 rbuf[rbufpos++] = ' '; \
1289 if (!width || justification > 0) \
1290 rbuf[rbufpos++] = (ch); \
1293 #define APPEND_STR(str) \
1295 int len = strlen ((str)); \
1301 nspace = width - len; \
1303 NEED_NBYTES (nspace + len); \
1304 if (width && justification > 0) \
1305 for (; nspace; nspace--) \
1306 rbuf[rbufpos++] = ' '; \
1308 memcpy (rbuf + rbufpos, str, len); \
1311 if (width && justification < 0) \
1312 for (; nspace; nspace--) \
1313 rbuf[rbufpos++] = ' '; \
1317 format_user_string (char *context_name, char *str)
1328 int justification = 1;
1330 /* Format string. */
1331 for (i = 0; str[i] != '\0'; i++)
1337 if (type == '%' || type == '$')
1343 /* Get optional width and justification. */
1349 while (isdigit (str[i]))
1350 width = width * 10 + str[i++] - '0';
1352 /* Handle escapes. */
1355 /* General state related %-escapes. */
1358 case '%': /* `%%' character `%' */
1362 case 'c': /* `%c' trailing component of pwd. */
1363 getcwd (buf, sizeof (buf));
1364 cp = strrchr (buf, '/');
1372 case 'C': /* `%C' runtime in `hh:mm:ss' format */
1373 sprintf (buf, "%02d:%02d:%02d", run_tm.tm_hour,
1374 run_tm.tm_min, run_tm.tm_sec);
1378 case 'd': /* `%d' current working directory */
1379 getcwd (buf, sizeof (buf));
1384 if (str[i + 1] == '{')
1386 /* `%D{}' format run date with strftime() */
1388 j < sizeof (buf2) && str[i] && str[i] != '}';
1393 _("%s: too long format for %%D{} escape"),
1397 strftime (buf, sizeof (buf), buf2, &run_tm);
1401 /* `%D' run date in `yy-mm-dd' format */
1402 sprintf (buf, "%02d-%02d-%02d", run_tm.tm_year % 100,
1403 run_tm.tm_mon + 1, run_tm.tm_mday);
1408 case 'E': /* `%E' run date in `yy/mm/dd' format */
1409 sprintf (buf, "%02d/%02d/%02d", run_tm.tm_year % 100,
1410 run_tm.tm_mon + 1, run_tm.tm_mday);
1414 case 'F': /* `%F' run date in `dd.mm.yyyy' format */
1415 sprintf (buf, "%d.%d.%d",
1418 run_tm.tm_year + 1900);
1422 case 'H': /* `%H' document title */
1426 case 'm': /* `%m' the hostname up to the first `.' */
1427 (void) gethostname (buf, sizeof (buf));
1428 cp = strchr (buf, '.');
1434 case 'M': /* `%M' the full hostname */
1435 (void) gethostname (buf, sizeof (buf));
1439 case 'n': /* `%n' username */
1440 APPEND_STR (passwd->pw_name);
1443 case 'N': /* `%N' pw_gecos up to the first `,' char */
1444 strcpy (buf, passwd->pw_gecos);
1445 cp = strchr (buf, ',');
1451 case 't': /* `%t' runtime in 12-hour am/pm format */
1452 sprintf (buf, "%d:%d%s",
1454 ? run_tm.tm_hour - 12 : run_tm.tm_hour,
1456 run_tm.tm_hour > 12 ? "pm" : "am");
1460 case 'T': /* `%T' runtime in 24-hour format */
1461 sprintf (buf, "%d:%d", run_tm.tm_hour, run_tm.tm_min);
1465 case '*': /* `%*' runtime in 24-hour format with secs */
1466 sprintf (buf, "%d:%d:%d", run_tm.tm_hour, run_tm.tm_min,
1471 case 'W': /* `%W' run date in `mm/dd/yy' format */
1472 sprintf (buf, "%02d/%02d/%02d", run_tm.tm_mon + 1,
1473 run_tm.tm_mday, run_tm.tm_year % 100);
1478 FATAL ((stderr, _("%s: unknown `%%' escape `%c' (%d)"),
1479 context_name, str[i], str[i]));
1485 /* Input file related $-escapes. */
1488 case '$': /* `$$' character `$' */
1492 case '%': /* `$%' current page number */
1494 sprintf (buf, "%d%c", current_pagenum, slice - 1 + 'A');
1496 sprintf (buf, "%d", current_pagenum);
1500 case '=': /* `$=' number of pages in this file */
1504 case 'p': /* `$p' number of pages processed so far */
1505 sprintf (buf, "%d", total_pages);
1509 case '(': /* $(ENVVAR) */
1511 str[i] && str[i] != ')' && j < sizeof (buf) - 1;
1516 FATAL ((stderr, _("%s: no closing ')' for $() escape"),
1519 FATAL ((stderr, _("%s: too long variable name for $() escape"),
1530 case 'C': /* `$C' modtime in `hh:mm:ss' format */
1531 sprintf (buf, "%02d:%02d:%02d", mod_tm.tm_hour,
1532 mod_tm.tm_min, mod_tm.tm_sec);
1537 if (str[i + 1] == '{')
1539 /* `$D{}' format modification date with strftime() */
1541 j < sizeof (buf2) && str[i] && str[i] != '}';
1546 _("%s: too long format for $D{} escape"),
1550 strftime (buf, sizeof (buf), buf2, &mod_tm);
1554 /* `$D' mod date in `yy-mm-dd' format */
1555 sprintf (buf, "%02d-%02d-%02d", mod_tm.tm_year % 100,
1556 mod_tm.tm_mon + 1, mod_tm.tm_mday);
1561 case 'E': /* `$E' mod date in `yy/mm/dd' format */
1562 sprintf (buf, "%02d/%02d/%02d", mod_tm.tm_year % 100,
1563 mod_tm.tm_mon + 1, mod_tm.tm_mday);
1567 case 'F': /* `$F' run date in `dd.mm.yyyy' format */
1568 sprintf (buf, "%d.%d.%d",
1571 mod_tm.tm_year + 1900);
1575 case 't': /* `$t' runtime in 12-hour am/pm format */
1576 sprintf (buf, "%d:%d%s",
1578 ? mod_tm.tm_hour - 12 : mod_tm.tm_hour,
1580 mod_tm.tm_hour > 12 ? "pm" : "am");
1584 case 'T': /* `$T' runtime in 24-hour format */
1585 sprintf (buf, "%d:%d", mod_tm.tm_hour, mod_tm.tm_min);
1589 case '*': /* `$*' runtime in 24-hour format with secs */
1590 sprintf (buf, "%d:%d:%d", mod_tm.tm_hour, mod_tm.tm_min,
1595 case 'v': /* `$v': input file number */
1596 sprintf (buf, "%d", input_filenum);
1600 case 'V': /* `$V': input file number in --toc format */
1603 sprintf (buf, "%d-", input_filenum);
1608 case 'W': /* `$W' run date in `mm/dd/yy' format */
1609 sprintf (buf, "%02d/%02d/%02d", mod_tm.tm_mon + 1,
1610 mod_tm.tm_mday, mod_tm.tm_year % 100);
1614 case 'N': /* `$N' the full name of the printed file */
1618 case 'n': /* `$n' input file name without directory */
1619 cp = strrchr (fname, '/');
1627 case 'L': /* `$L' number of lines in this file. */
1628 /* This is valid only for TOC-strings. */
1629 sprintf (buf, "%d", current_file_linenum - 1);
1634 FATAL ((stderr, _("%s: unknown `$' escape `%c' (%d)"),
1635 context_name, str[i], str[i]));
1639 /* Reset width so the else-arm goes ok at the next round. */
1648 /* Escape PS specials. */
1649 cp = escape_string (rbuf);
1657 parse_key_value_pair (StringHashPtr set, char *kv)
1662 cp = strchr (kv, ':');
1665 if (strhash_delete (set, kv, strlen (kv) + 1, (void **) &cp))
1671 buffer_append_len (&key, kv, cp - kv);
1673 strhash_put (set, buffer_ptr (&key), strlen (buffer_ptr (&key)) + 1,
1674 xstrdup (cp + 1), (void **) &cp);
1678 buffer_uninit (&key);
1684 count_key_value_set (StringHashPtr set)
1690 for (got = strhash_get_first (set, &cp, &j, &value); got;
1691 got = strhash_get_next (set, &cp, &j, &value))
1699 pathwalk (char *path, PathWalkProc proc, void *context)
1706 for (cp = path; cp; cp = strchr (cp, PATH_SEPARATOR))
1711 cp2 = strchr (cp, PATH_SEPARATOR);
1717 memcpy (buf, cp, len);
1720 i = (*proc) (buf, context);
1730 file_lookup (char *path, void *context)
1733 FileLookupCtx *ctx = context;
1734 struct stat stat_st;
1737 MESSAGE (2, (stderr, "file_lookup(): %s/%s%s\t", path, ctx->name,
1740 len = strlen (path);
1741 if (len && path[len - 1] == '/')
1744 buffer_clear (ctx->fullname);
1745 buffer_append_len (ctx->fullname, path, len);
1746 buffer_append (ctx->fullname, "/");
1747 buffer_append (ctx->fullname, ctx->name);
1748 buffer_append (ctx->fullname, ctx->suffix);
1750 i = stat (buffer_ptr (ctx->fullname), &stat_st) == 0;
1752 MESSAGE (2, (stderr, "#%c\n", i ? 't' : 'f'));
1759 tilde_subst (char *fname)
1763 struct passwd *pswd;
1767 if (fname[0] != '~')
1768 return xstrdup (fname);
1770 if (fname[1] == '/' || fname[1] == '\0')
1772 /* The the user's home directory from the `HOME' environment
1774 cp = getenv ("HOME");
1776 return xstrdup (fname);
1778 buffer_init (&buffer);
1779 buffer_append (&buffer, cp);
1780 buffer_append (&buffer, fname + 1);
1782 result = buffer_copy (&buffer);
1783 buffer_uninit (&buffer);
1788 /* Get user's login name. */
1789 for (i = 1; fname[i] && fname[i] != '/'; i++)
1792 buffer_init (&buffer);
1793 buffer_append_len (&buffer, fname + 1, i - 1);
1795 pswd = getpwnam (buffer_ptr (&buffer));
1796 buffer_uninit (&buffer);
1800 /* Found passwd entry. */
1801 buffer_init (&buffer);
1802 buffer_append (&buffer, pswd->pw_dir);
1803 buffer_append (&buffer, fname + i);
1805 result = buffer_copy (&buffer);
1806 buffer_uninit (&buffer);
1811 /* No match found. */
1812 return xstrdup (fname);
1817 parse_float (char *string, int units, int horizontal)
1822 val = strtod (string, &end);
1825 ERROR ((stderr, _("malformed float dimension: \"%s\""), string));
1847 val *= CHAR_WIDTH ('m');
1853 goto malformed_float;
1860 goto malformed_float;
1868 * InputStream functions.
1872 is_open (InputStream *is, FILE *fp, char *fname, char *input_filter)
1874 /* Init stream variables. */
1875 is->data_in_buf = 0;
1878 is->unget_ch = NULL;
1880 is->unget_alloc = 0;
1893 fname = input_filter_stdin;
1896 * Count the initial command length, this will grow dynamically
1897 * when file specifier `%s' is encountered from <input_filter>.
1899 cmdlen = strlen (input_filter) + 1;
1900 cmd = xmalloc (cmdlen);
1902 /* Create filter command. */
1904 for (i = 0; input_filter[i]; i++)
1906 if (input_filter[i] == '%')
1908 switch (input_filter[i + 1])
1911 /* Expand cmd-buffer. */
1912 if ((cp = shell_escape (fname)) != NULL)
1914 cmdlen += strlen (cp);
1915 cmd = xrealloc (cmd, cmdlen);
1917 /* Paste filename. */
1918 strcpy (cmd + pos, cp);
1932 cmd[pos++] = input_filter[i];
1937 cmd[pos++] = input_filter[i];
1941 is->fp = popen (cmd, "r");
1947 _("couldn't open input filter \"%s\" for file \"%s\": %s"),
1948 input_filter, fname ? fname : "(stdin)",
1955 /* Just open the stream. */
1961 is->fp = fopen (fname, "rb");
1964 ERROR ((stderr, _("couldn't open input file \"%s\": %s"), fname,
1976 is_close (InputStream *is)
1984 xfree (is->unget_ch);
1989 is_getc (InputStream *is)
1993 if (is->unget_pos > 0)
1995 ch = is->unget_ch[--is->unget_pos];
2001 /* Do we have any data left? */
2002 if (is->bufpos >= is->data_in_buf)
2005 if (is->nreads > 0 && is->data_in_buf < sizeof (is->buf))
2009 /* Read more data. */
2010 is->data_in_buf = fread (is->buf, 1, sizeof (is->buf), is->fp);
2017 return is->buf[is->bufpos++];
2022 is_ungetc (int ch, InputStream *is)
2024 if (is->unget_pos >= is->unget_alloc)
2026 is->unget_alloc += 1024;
2027 is->unget_ch = xrealloc (is->unget_ch, is->unget_alloc);
2030 is->unget_ch[is->unget_pos++] = ch;
2041 buffer_init (Buffer *buffer)
2043 buffer->allocated = 128;
2044 buffer->data = xmalloc (buffer->allocated);
2045 buffer->data[0] = '\0';
2051 buffer_uninit (Buffer *buffer)
2053 xfree (buffer->data);
2060 Buffer *buffer = (Buffer *) xcalloc (1, sizeof (Buffer));
2062 buffer_init (buffer);
2069 buffer_free (Buffer *buffer)
2071 buffer_uninit (buffer);
2077 buffer_append (Buffer *buffer, const char *data)
2079 buffer_append_len (buffer, data, strlen (data));
2084 buffer_append_len (Buffer *buffer, const char *data, size_t len)
2086 if (buffer->len + len + 1 >= buffer->allocated)
2088 buffer->allocated = buffer->len + len + 1024;
2089 buffer->data = xrealloc (buffer->data, buffer->allocated);
2092 memcpy (buffer->data + buffer->len, data, len);
2095 buffer->data[buffer->len] = '\0';
2100 buffer_copy (Buffer *buffer)
2102 char *copy = xmalloc (buffer->len + 1);
2104 memcpy (copy, buffer->data, buffer->len + 1);
2111 buffer_clear (Buffer *buffer)
2114 buffer->data[0] = '\0';
2119 buffer_ptr (Buffer *buffer)
2121 return buffer->data;
2126 buffer_len (Buffer *buffer)
2132 * Escapes the name of a file so that the shell groks it in 'single'
2133 * quotation marks. The resulting pointer has to be free()ed when not
2137 shell_escape(const char *fn)
2141 char *retval, *outp;
2143 for(inp = fn; *inp; ++inp)
2146 case '\'': len += 4; break;
2147 default: len += 1; break;
2150 outp = retval = malloc(len + 1);
2152 return NULL; /* perhaps one should do better error handling here */
2153 for(inp = fn; *inp; ++inp)
2156 case '\'': *outp++ = '\''; *outp++ = '\\'; *outp++ = '\'', *outp++ = '\''; break;
2157 default: *outp++ = *inp; break;