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, 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 buffer_uninit (&fname);
116 while (fgets (buf, sizeof (buf), fp))
123 token = GET_TOKEN (buf);
128 if (MATCH (token, "AcceptCompositeCharacters:"))
130 token2 = GET_TOKEN (NULL);
132 accept_composites = atoi (token2);
134 else if (MATCH (token, "AFMPath:"))
136 token2 = GET_TOKEN (NULL);
139 afm_path = xstrdup (token2);
141 else if (MATCH (token, "AppendCtrlD:"))
143 token2 = GET_TOKEN (NULL);
145 append_ctrl_D = atoi (token2);
147 else if (MATCH (token, "Clean7Bit:"))
149 token2 = GET_TOKEN (NULL);
151 clean_7bit = atoi (token2);
153 else if (MATCH (token, "DefaultEncoding:"))
155 token2 = GET_TOKEN (NULL);
157 xfree (encoding_name);
158 encoding_name = xstrdup (token2);
160 else if (MATCH (token, "DefaultFancyHeader:"))
162 token2 = GET_TOKEN (NULL);
164 xfree (fancy_header_default);
165 fancy_header_default = xstrdup (token2);
167 else if (MATCH (token, "DefaultMedia:"))
169 token2 = GET_TOKEN (NULL);
172 media_name = xstrdup (token2);
174 else if (MATCH (token, "DefaultOutputMethod:"))
176 token2 = GET_TOKEN (NULL);
178 if (MATCH (token2, "printer"))
179 output_file = OUTPUT_FILE_NONE;
180 else if (MATCH (token2, "stdout"))
181 output_file = OUTPUT_FILE_STDOUT;
183 CFG_FATAL ((stderr, _("illegal value \"%s\" for option %s"),
186 else if (MATCH (token, "DownloadFont:"))
188 token2 = GET_TOKEN (NULL);
190 strhash_put (download_fonts, token2, strlen (token2) + 1, NULL,
193 else if (MATCH (token, "EscapeChar:"))
195 token2 = GET_TOKEN (NULL);
197 escape_char = atoi (token2);
198 if (escape_char < 0 || escape_char > 255)
199 CFG_FATAL ((stderr, _("invalid value \"%s\" for option %s"),
202 else if (MATCH (token, "FormFeedType:"))
204 token2 = GET_TOKEN (NULL);
206 if (MATCH (token2, "column"))
207 formfeed_type = FORMFEED_COLUMN;
208 else if (MATCH (token2, "page"))
209 formfeed_type = FORMFEED_PAGE;
211 CFG_FATAL ((stderr, _("illegal value \"%s\" for option %s"),
214 else if (MATCH (token, "GeneratePageSize:"))
216 token2 = GET_TOKEN (NULL);
218 generate_PageSize = atoi (token2);
220 else if (MATCH (token, "HighlightBarGray:"))
222 token2 = GET_TOKEN (NULL);
224 highlight_bar_gray = atof (token2);
226 else if (MATCH (token, "HighlightBars:"))
228 token2 = GET_TOKEN (NULL);
230 highlight_bars = atoi (token2);
232 else if (MATCH (token, "LibraryPath:"))
234 token2 = GET_TOKEN (NULL);
237 libpath = xstrdup (token2);
239 else if (MATCH (token, "MarkWrappedLines:"))
241 token2 = GET_TOKEN (NULL);
243 xfree (mark_wrapped_lines_style_name);
244 mark_wrapped_lines_style_name = xstrdup (token2);
246 else if (MATCH (token, "Media:"))
249 int w, h, llx, lly, urx, ury;
251 token2 = GET_TOKEN (NULL);
255 token2 = GET_TOKEN (NULL);
259 token2 = GET_TOKEN (NULL);
263 token2 = GET_TOKEN (NULL);
267 token2 = GET_TOKEN (NULL);
271 token2 = GET_TOKEN (NULL);
275 token2 = GET_TOKEN (NULL);
279 add_media (name, w, h, llx, lly, urx, ury);
281 else if (MATCH (token, "NoJobHeaderSwitch:"))
283 token2 = GET_LINE_TOKEN (NULL);
285 xfree (no_job_header_switch);
286 no_job_header_switch = xstrdup (token2);
288 else if (MATCH (token, "NonPrintableFormat:"))
290 token2 = GET_TOKEN (NULL);
293 npf_name = xstrdup (token2);
295 else if (MATCH (token, "OutputFirstLine:"))
297 token2 = GET_LINE_TOKEN (NULL);
299 xfree (output_first_line);
300 output_first_line = xstrdup (token2);
302 else if (MATCH (token, "PageLabelFormat:"))
304 token2 = GET_TOKEN (NULL);
306 xfree (page_label_format);
307 page_label_format = xstrdup (token2);
309 else if (MATCH (token, "PagePrefeed:"))
311 token2 = GET_TOKEN (NULL);
313 page_prefeed = atoi (token2);
315 else if (MATCH (token, "PostScriptLevel:"))
317 token2 = GET_TOKEN (NULL);
319 pslevel = atoi (token2);
321 else if (MATCH (token, "Printer:"))
323 token2 = GET_TOKEN (NULL);
326 printer = xstrdup (token2);
328 else if (MATCH (token, "QueueParam:"))
330 token2 = GET_LINE_TOKEN (NULL);
333 queue_param = xstrdup (token2);
335 else if (MATCH (token, "SetPageDevice:"))
337 token2 = GET_LINE_TOKEN (NULL);
339 parse_key_value_pair (pagedevice, token2);
341 else if (MATCH (token, "Spooler:"))
343 token2 = GET_TOKEN (NULL);
345 xfree (spooler_command);
346 spooler_command = xstrdup (token2);
348 else if (MATCH (token, "StatesBinary:"))
350 token2 = GET_TOKEN (NULL);
352 xfree (states_binary);
353 states_binary = xstrdup (token2);
355 else if (MATCH (token, "StatesColor:"))
357 token2 = GET_TOKEN (NULL);
359 states_color = atoi (token2);
361 else if (MATCH (token, "StatesConfigFile:"))
363 token2 = GET_LINE_TOKEN (NULL);
365 xfree (states_config_file);
366 states_config_file = xstrdup (token2);
368 else if (MATCH (token, "StatesHighlightStyle:"))
370 token2 = GET_TOKEN (NULL);
372 xfree (states_highlight_style);
373 states_highlight_style = xstrdup (token2);
375 else if (MATCH (token, "StatesPath:"))
377 token2 = GET_LINE_TOKEN (NULL);
380 states_path = xstrdup (token2);
382 else if (MATCH (token, "StatusDict:"))
384 token2 = GET_TOKEN (NULL);
386 parse_key_value_pair (statusdict, token2);
388 else if (MATCH (token, "TOCFormat:"))
390 token2 = GET_LINE_TOKEN (NULL);
392 toc_fmt_string = xstrdup (token2);
394 else if (MATCH (token, "Underlay:"))
396 token2 = GET_LINE_TOKEN (NULL);
398 underlay = xmalloc (strlen (token2) + 1);
399 strcpy (underlay, token2);
401 else if (MATCH (token, "UnderlayAngle:"))
403 token2 = GET_TOKEN (NULL);
405 ul_angle = atof (token2);
408 else if (MATCH (token, "UnderlayFont:"))
410 token2 = GET_TOKEN (NULL);
412 if (!parse_font_spec (token2, &ul_font, &ul_ptsize, NULL))
413 CFG_FATAL ((stderr, _("malformed font spec: %s"), token2));
415 else if (MATCH (token, "UnderlayGray:"))
417 token2 = GET_TOKEN (NULL);
419 ul_gray = atof (token2);
421 else if (MATCH (token, "UnderlayPosition:"))
423 token2 = GET_TOKEN (NULL);
426 ul_position = xstrdup (token2);
429 else if (MATCH (token, "UnderlayStyle:"))
431 token2 = GET_TOKEN (NULL);
433 xfree (ul_style_str);
434 ul_style_str = xstrdup (token2);
437 CFG_FATAL ((stderr, _("illegal option: %s"), token));
444 add_media (char *name, int w, int h, int llx, int lly, int urx, int ury)
450 "add_media: name=%s, w=%d, h=%d, llx=%d, lly=%d, urx=%d, ury=%d\n",
451 name, w, h, llx, lly, urx, ury));
453 entry = xcalloc (1, sizeof (*entry));
454 entry->name = xmalloc (strlen (name) + 1);
456 strcpy (entry->name, name);
464 entry->next = media_names;
470 do_list_missing_characters (int *array)
475 for (i = 0; i < 256; i++)
478 fprintf (stderr, "%3d ", i);
481 fprintf (stderr, "\n");
485 fprintf (stderr, "\n");
490 file_existsp (char *name, char *suffix)
496 ctx.suffix = suffix ? suffix : "";
497 ctx.fullname = buffer_alloc ();
499 result = pathwalk (libpath, file_lookup, &ctx);
501 buffer_free (ctx.fullname);
508 paste_file (char *name, char *suffix)
514 int pending_comment = 0;
518 ctx.suffix = suffix ? suffix : "";
519 ctx.fullname = buffer_alloc ();
521 if (!pathwalk (libpath, file_lookup, &ctx))
523 buffer_free (ctx.fullname);
526 fp = fopen (buffer_ptr (ctx.fullname), "r");
529 buffer_free (ctx.fullname);
533 /* Find the end of the header. */
534 #define HDR_TAG "% -- code follows this line --"
535 while ((fgets (buf, sizeof (buf), fp)))
538 if (strncmp (buf, HDR_TAG, strlen (HDR_TAG)) == 0)
542 /* Dump rest of file. */
543 while ((fgets (buf, sizeof (buf), fp)))
548 * Document needed resources?
550 #define RESOURCE_DSC "%%DocumentNeededResources:"
551 #define CONT_DSC "%%+"
552 if (strncmp (buf, RESOURCE_DSC, strlen (RESOURCE_DSC)) == 0)
556 strcpy (resources, buf + strlen (RESOURCE_DSC));
560 /* Register needed resources. */
561 cp = GET_TOKEN (resources);
563 /* Get the next line. */
566 if (MATCH (cp, "font"))
568 for (cp = GET_TOKEN (NULL); cp; cp = GET_TOKEN (NULL))
569 /* Is this font already known? */
570 if (!strhash_get (res_fonts, cp, strlen (cp) + 1,
573 /* Not it is not, we must include this resource. */
574 fprintf (ofp, "%%%%IncludeResource: font %s\n", cp);
577 * And register that this resource is needed in
580 strhash_put (res_fonts, cp, strlen (cp) + 1, NULL, NULL);
583 /* Do not pass this DSC row to the output. */
587 /* Unknown resource, ignore. */
590 else if (pending_comment
591 && strncmp (buf, CONT_DSC, strlen (CONT_DSC)) == 0)
593 strcpy (resources, buf + strlen (CONT_DSC));
594 goto parse_resources;
600 * `%Format' directive?
602 #define DIRECTIVE_FORMAT "%Format:"
603 if (strncmp (buf, DIRECTIVE_FORMAT, strlen (DIRECTIVE_FORMAT)) == 0)
610 /* Skip the leading whitespace. */
611 for (i = strlen (DIRECTIVE_FORMAT); buf[i] && isspace (buf[i]); i++)
614 FATAL ((stderr, _("%s:%d: %%Format: no name"),
615 buffer_ptr (ctx.fullname), line));
619 j < sizeof (name) - 1 && buf[i] && !isspace (buf[i]);
624 if (j >= sizeof (name) - 1)
625 FATAL ((stderr, _("%s:%d: %%Format: too long name, maxlen=%d"),
626 buffer_ptr (ctx.fullname), line, sizeof (name) - 1));
628 /* Find the start of the format string. */
629 for (; buf[i] && isspace (buf[i]); i++)
634 for (j--; isspace (buf[j]) && j > i; j--)
638 MESSAGE (2, (stderr, "%%Format: %s %.*s\n", name, j - i, buf + i));
640 cp = xmalloc (j - i + 1);
641 memcpy (cp, buf + i, j - i);
644 strhash_put (user_strings, name, strlen (name) + 1, cp,
648 _("%s:%d: %%Format: name \"%s\" is already defined"),
649 buffer_ptr (ctx.fullname), line, name));
651 /* All done with the `%Format' directive. */
656 * `%HeaderHeight' directive?
658 #define DIRECTIVE_HEADERHEIGHT "%HeaderHeight:"
659 if (strncmp (buf, DIRECTIVE_HEADERHEIGHT,
660 strlen (DIRECTIVE_HEADERHEIGHT)) == 0)
664 /* Find the start of the pts argument. */
665 for (i = strlen (DIRECTIVE_HEADERHEIGHT);
666 buf[i] && !isspace (buf[i]); i++)
669 FATAL ((stderr, _("%s:%d: %%HeaderHeight: no argument"),
670 buffer_ptr (ctx.fullname), line));
672 d_header_h = atoi (buf + i);
673 MESSAGE (2, (stderr, "%%HeaderHeight: %d\n", d_header_h));
678 * `%FooterHeight' directive?
680 #define DIRECTIVE_FOOTERHEIGHT "%FooterHeight:"
681 if (strncmp (buf, DIRECTIVE_FOOTERHEIGHT,
682 strlen (DIRECTIVE_FOOTERHEIGHT)) == 0)
686 /* Find the start of the pts argument. */
687 for (i = strlen (DIRECTIVE_FOOTERHEIGHT);
688 buf[i] && !isspace (buf[i]); i++)
691 FATAL ((stderr, _("%s:%d: %%FooterHeight: no argument"),
692 buffer_ptr (ctx.fullname), line));
694 d_footer_h = atoi (buf + i);
695 MESSAGE (2, (stderr, "%%FooterHeight: %d\n", d_footer_h));
699 /* Nothing special, just copy it to the output. */
704 buffer_free (ctx.fullname);
711 parse_font_spec (char *spec_a, char **name_return, FontPoint *size_return,
712 InputEncoding *encoding_return)
719 spec = xstrdup (spec_a);
721 /* Check for the `namesize:encoding' format. */
722 encp = strrchr (spec, ':');
729 /* The `name@ptsize' format? */
730 cp = strchr (spec, '@');
736 /* No ptsize after '@'. */
744 /* The old `nameptsize' format. */
745 i = strlen (spec) - 1;
746 if (i <= 0 || !ISNUMBERDIGIT (spec[i]))
752 for (i--; i >= 0 && ISNUMBERDIGIT (spec[i]); i--)
761 /* We accept one slash for the `pt/pt' format. */
762 for (i--; i >= 0 && ISNUMBERDIGIT (spec[i]); i--)
772 /* Now, <i> points to the end of the name. Let's set the <cp>
773 to the beginning of the point size and share a little code
774 with the other format. */
778 /* Check the font point size. */
779 cp2 = strchr (cp, '/');
783 size_return->w = atof (cp);
784 size_return->h = atof (cp2);
787 size_return->w = size_return->h = atof (cp);
789 /* Extract the font name. */
790 *name_return = (char *) xcalloc (1, i + 1);
791 strncpy (*name_return, spec, i);
793 /* Check the input encoding. */
798 if (encoding_return == NULL)
800 /* We don't allow it here. */
805 for (i = 0; !found && encodings[i].names[0]; i++)
806 for (j = 0; j < 3; j++)
807 if (encodings[i].names[j] != NULL && MATCH (encodings[i].names[j],
811 *encoding_return = encodings[i].encoding;
812 encp = encodings[i].names[0];
825 /* The spec didn't contain the encoding part. Use our global default. */
826 encp = encoding_name;
828 *encoding_return = encoding;
833 "parse_font_spec(): name=%.*s, size=%g/%g, encoding=%s\n", i,
834 *name_return, size_return->w, size_return->h,
837 if (size_return->w < 0.0 && size_return->h < 0.0)
838 MESSAGE (0, (stderr, _("%s: warning: font size is negative\n"), program));
839 else if (size_return->w < 0.0)
840 MESSAGE (0, (stderr, _("%s: warning: font width is negative\n"), program));
841 else if (size_return->h < 0.0)
842 MESSAGE (0, (stderr, _("%s: warning: font height is negative\n"),
850 read_font_info (void)
852 CachedFontInfo *font_info;
854 int font_info_cached = 1;
857 unsigned int enc_flags = 0;
861 MESSAGE (2, (stderr, _("reading AFM info for font \"%s\"\n"), Fname));
863 if (accept_composites)
864 enc_flags = AFM_ENCODE_ACCEPT_COMPOSITES;
870 buffer_append (&fkey, Fname);
871 sprintf (buf, "@%f:%d", Fpt.w, encoding);
872 buffer_append (&fkey, buf);
874 if (!strhash_get (afm_info_cache, buffer_ptr (&fkey),
875 strlen (buffer_ptr (&fkey)), (void **) &font_info))
879 /* Couldn't find it from our cache, open open AFM file. */
880 if (!strhash_get (afm_cache, Fname, strlen (Fname), (void **) &font))
882 /* AFM file was not cached, open it from disk. */
883 error = afm_open_font (afm, AFM_I_COMPOSITES, Fname, &font);
884 if (error != AFM_SUCCESS)
886 #define COUR "Courier"
888 * Do not report failures for "Courier*" fonts because
889 * AFM library's default font will fix them.
891 if (strncmp (Fname, COUR, strlen (COUR)) != 0)
894 _("couldn't open AFM file for font \"%s\", using default\n"),
896 error = afm_open_default_font (afm, &font);
897 if (error != AFM_SUCCESS)
899 afm_error_to_string (error, buf);
901 _("couldn't open AFM file for the default font: %s"),
906 /* Apply encoding. */
910 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_1,
915 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_2,
920 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_3,
925 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_4,
930 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_5,
935 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_7,
940 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_9,
944 case ENC_ISO_8859_10:
945 (void) afm_font_encoding (font, AFM_ENCODING_ISO_8859_10,
950 (void) afm_font_encoding (font, AFM_ENCODING_ASCII, enc_flags);
954 /* First apply standard 7bit ASCII encoding. */
955 (void) afm_font_encoding (font, AFM_ENCODING_ASCII, enc_flags);
957 /* Then add those scand characters. */
958 for (i = 0; enc_7bit_ascii_fise[i].name; i++)
959 (void) afm_font_encode (font, enc_7bit_ascii_fise[i].code,
960 enc_7bit_ascii_fise[i].name,
965 /* First apply standard 7bit ASCII encoding. */
966 (void) afm_font_encoding (font, AFM_ENCODING_ASCII, enc_flags);
968 /* Then add those scand characters. */
969 for (i = 0; enc_7bit_ascii_dkno[i].name; i++)
970 (void) afm_font_encode (font, enc_7bit_ascii_dkno[i].code,
971 enc_7bit_ascii_dkno[i].name,
976 (void) afm_font_encoding (font, AFM_ENCODING_IBMPC, enc_flags);
980 (void) afm_font_encoding (font, AFM_ENCODING_MAC, enc_flags);
984 (void) afm_font_encoding (font, AFM_ENCODING_VMS, enc_flags);
988 (void) afm_font_encoding (font, AFM_ENCODING_HP8, enc_flags);
992 (void) afm_font_encoding (font, AFM_ENCODING_KOI8, enc_flags);
996 /* Let's use font's default encoding -- nothing here. */
1000 /* Put it to the AFM cache. */
1001 if (!strhash_put (afm_cache, Fname, strlen (Fname), font, NULL))
1005 font_info = (CachedFontInfo *) xcalloc (1, sizeof (*font_info));
1006 /* Read character widths and types. */
1007 for (i = 0; i < 256; i++)
1011 (void) afm_font_charwidth (font, Fpt.w, i, &w0x, &w0y);
1012 font_info->font_widths[i] = w0x;
1014 if (font->encoding[i] == AFM_ENC_NONE)
1015 font_info->font_ctype[i] = ' ';
1016 else if (font->encoding[i] == AFM_ENC_NON_EXISTENT)
1017 font_info->font_ctype[i] = '.';
1019 font_info->font_ctype[i] = '*';
1022 font_info->font_is_fixed
1023 = font->writing_direction_metrics[0].IsFixedPitch;
1024 font_info->font_bbox_lly = font->global_info.FontBBox_lly;
1027 (void) afm_close_font (font);
1029 /* Store font information to the AFM information cache. */
1030 if (!strhash_put (afm_info_cache, buffer_ptr (&fkey),
1031 strlen (buffer_ptr (&fkey)), font_info, NULL))
1032 font_info_cached = 0;
1035 /* Select character widths and types. */
1036 memcpy (font_widths, font_info->font_widths, 256 * sizeof (double));
1037 memcpy (font_ctype, font_info->font_ctype, 256);
1039 font_is_fixed = font_info->font_is_fixed;
1040 font_bbox_lly = font_info->font_bbox_lly;
1042 if (!font_info_cached)
1045 buffer_uninit (&fkey);
1050 download_font (char *name)
1054 struct stat stat_st;
1056 unsigned char buf[4096];
1061 /* Get font prefix. */
1062 error = afm_font_prefix (afm, name, &prefix);
1063 if (error != AFM_SUCCESS)
1064 /* Font is unknown, nothing to download. */
1067 /* Check if we have a font description file. */
1069 buffer_init (&fname);
1072 buffer_append (&fname, prefix);
1073 buffer_append (&fname, ".pfa");
1074 if (stat (buffer_ptr (&fname), &stat_st) != 0)
1077 buffer_clear (&fname);
1078 buffer_append (&fname, prefix);
1079 buffer_append (&fname, ".pfb");
1080 if (stat (buffer_ptr (&fname), &stat_st) != 0)
1082 /* Couldn't find font description file, nothing to download. */
1083 buffer_uninit (&fname);
1088 /* Ok, fine. Font was found. */
1090 MESSAGE (1, (stderr, _("downloading font \"%s\"\n"), name));
1091 fp = fopen (buffer_ptr (&fname), "rb");
1094 MESSAGE (0, (stderr,
1095 _("couldn't open font description file \"%s\": %s\n"),
1096 buffer_ptr (&fname), strerror (errno)));
1097 buffer_uninit (&fname);
1100 buffer_uninit (&fname);
1103 fprintf (ofp, "%%%%BeginResource: font %s\n", name);
1105 /* Check file type. */
1109 /* Not much to do here. */
1116 unsigned int to_read;
1126 /* Read 6-byte long header. */
1127 i = fread (buf, 1, 6, fp);
1131 chunk = buf[2] | (buf[3] << 8) | (buf[4] << 16) | (buf[5] << 24);
1133 /* Check chunk type. */
1140 to_read = sizeof (buf) < chunk ? sizeof (buf) : chunk;
1141 i = fread (buf, 1, to_read, fp);
1148 /* Check and fix Mac-newlines. */
1149 for (j = 0; j < i; j++)
1151 if (j == 0 && last_was_cr && buf[0] != '\n')
1154 fputc (buf[0], ofp);
1156 else if (buf[j] == '\r' && j + 1 < i
1157 && buf[j + 1] != '\n')
1161 else if (buf[j] != '\r')
1162 fputc (buf[j], ofp);
1166 last_was_cr = (buf[i - 1] == '\r');
1170 case 2: /* binary data */
1173 to_read = sizeof (buf) < chunk ? sizeof (buf) : chunk;
1174 i = fread (buf, 1, to_read, fp);
1181 for (j = 0; j < i; j++)
1183 fprintf (ofp, "%02X", buf[j]);
1184 if ((j + 1) % 32 == 0)
1185 fprintf (ofp, "\n");
1196 /* Force a linebreak after each chunk. */
1197 fprintf (ofp, "\n");
1204 while ((i = fread (buf, 1, sizeof (buf), fp)) != 0)
1205 fwrite (buf, 1, i, ofp);
1208 fprintf (ofp, "%%%%EndResource\n");
1210 /* Remove font from needed resources. */
1211 (void) strhash_delete (res_fonts, name, strlen (name) + 1, (void **) &cp);
1218 escape_string (char *string)
1224 /* Count the length of the result string. */
1225 for (len = 0, i = 0; string[i]; i++)
1238 /* Create result. */
1239 cp = xmalloc (len + 1);
1240 for (i = 0, j = 0; string[i]; i++)
1250 cp[j++] = string[i];
1261 * Help macros for the format_user_string() function.
1264 #define NEED_NBYTES(n) \
1266 if (rbufpos + (n) >= rbuflen) \
1268 rbuflen += (n) + 1024; \
1269 rbuf = xrealloc (rbuf, rbuflen); \
1273 #define APPEND_CH(ch) \
1276 NEED_NBYTES (width); \
1277 if (width && justification < 0) \
1278 rbuf[rbufpos++] = (ch); \
1279 for (a = 0; a < width - 1; a++) \
1280 rbuf[rbufpos++] = ' '; \
1281 if (!width || justification > 0) \
1282 rbuf[rbufpos++] = (ch); \
1285 #define APPEND_STR(str) \
1287 int len = strlen ((str)); \
1293 nspace = width - len; \
1295 NEED_NBYTES (nspace + len); \
1296 if (width && justification > 0) \
1297 for (; nspace; nspace--) \
1298 rbuf[rbufpos++] = ' '; \
1300 memcpy (rbuf + rbufpos, str, len); \
1303 if (width && justification < 0) \
1304 for (; nspace; nspace--) \
1305 rbuf[rbufpos++] = ' '; \
1309 format_user_string (char *context_name, char *str)
1320 int justification = 1;
1322 /* Format string. */
1323 for (i = 0; str[i] != '\0'; i++)
1329 if (type == '%' || type == '$')
1335 /* Get optional width and justification. */
1341 while (isdigit (str[i]))
1342 width = width * 10 + str[i++] - '0';
1344 /* Handle escapes. */
1347 /* General state related %-escapes. */
1350 case '%': /* `%%' character `%' */
1354 case 'c': /* `%c' trailing component of pwd. */
1355 getcwd (buf, sizeof (buf));
1356 cp = strrchr (buf, '/');
1364 case 'C': /* `%C' runtime in `hh:mm:ss' format */
1365 sprintf (buf, "%02d:%02d:%02d", run_tm.tm_hour,
1366 run_tm.tm_min, run_tm.tm_sec);
1370 case 'd': /* `%d' current working directory */
1371 getcwd (buf, sizeof (buf));
1376 if (str[i + 1] == '{')
1378 /* `%D{}' format run date with strftime() */
1380 j < sizeof (buf2) && str[i] && str[i] != '}';
1385 _("%s: too long format for %%D{} escape"),
1389 strftime (buf, sizeof (buf), buf2, &run_tm);
1393 /* `%D' run date in `yy-mm-dd' format */
1394 sprintf (buf, "%02d-%02d-%02d", run_tm.tm_year % 100,
1395 run_tm.tm_mon + 1, run_tm.tm_mday);
1400 case 'E': /* `%E' 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);
1406 case 'F': /* `%F' run date in `dd.mm.yyyy' format */
1407 sprintf (buf, "%d.%d.%d",
1410 run_tm.tm_year + 1900);
1414 case 'H': /* `%H' document title */
1418 case 'm': /* `%m' the hostname up to the first `.' */
1419 (void) gethostname (buf, sizeof (buf));
1420 cp = strchr (buf, '.');
1426 case 'M': /* `%M' the full hostname */
1427 (void) gethostname (buf, sizeof (buf));
1431 case 'n': /* `%n' username */
1432 APPEND_STR (passwd->pw_name);
1435 case 'N': /* `%N' pw_gecos up to the first `,' char */
1436 strcpy (buf, passwd->pw_gecos);
1437 cp = strchr (buf, ',');
1443 case 't': /* `%t' runtime in 12-hour am/pm format */
1444 sprintf (buf, "%d:%d%s",
1446 ? run_tm.tm_hour - 12 : run_tm.tm_hour,
1448 run_tm.tm_hour > 12 ? "pm" : "am");
1452 case 'T': /* `%T' runtime in 24-hour format */
1453 sprintf (buf, "%d:%d", run_tm.tm_hour, run_tm.tm_min);
1457 case '*': /* `%*' runtime in 24-hour format with secs */
1458 sprintf (buf, "%d:%d:%d", run_tm.tm_hour, run_tm.tm_min,
1463 case 'W': /* `%W' run date in `mm/dd/yy' format */
1464 sprintf (buf, "%02d/%02d/%02d", run_tm.tm_mon + 1,
1465 run_tm.tm_mday, run_tm.tm_year % 100);
1470 FATAL ((stderr, _("%s: unknown `%%' escape `%c' (%d)"),
1471 context_name, str[i], str[i]));
1477 /* Input file related $-escapes. */
1480 case '$': /* `$$' character `$' */
1484 case '%': /* `$%' current page number */
1486 sprintf (buf, "%d%c", current_pagenum, slice - 1 + 'A');
1488 sprintf (buf, "%d", current_pagenum);
1492 case '=': /* `$=' number of pages in this file */
1496 case 'p': /* `$p' number of pages processed so far */
1497 sprintf (buf, "%d", total_pages);
1501 case '(': /* $(ENVVAR) */
1503 str[i] && str[i] != ')' && j < sizeof (buf) - 1;
1508 FATAL ((stderr, _("%s: no closing ')' for $() escape"),
1511 FATAL ((stderr, _("%s: too long variable name for $() escape"),
1522 case 'C': /* `$C' modtime in `hh:mm:ss' format */
1523 sprintf (buf, "%02d:%02d:%02d", mod_tm.tm_hour,
1524 mod_tm.tm_min, mod_tm.tm_sec);
1529 if (str[i + 1] == '{')
1531 /* `$D{}' format modification date with strftime() */
1533 j < sizeof (buf2) && str[i] && str[i] != '}';
1538 _("%s: too long format for $D{} escape"),
1542 strftime (buf, sizeof (buf), buf2, &mod_tm);
1546 /* `$D' mod date in `yy-mm-dd' format */
1547 sprintf (buf, "%02d-%02d-%02d", mod_tm.tm_year % 100,
1548 mod_tm.tm_mon + 1, mod_tm.tm_mday);
1553 case 'E': /* `$E' 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);
1559 case 'F': /* `$F' run date in `dd.mm.yyyy' format */
1560 sprintf (buf, "%d.%d.%d",
1563 mod_tm.tm_year + 1900);
1567 case 't': /* `$t' runtime in 12-hour am/pm format */
1568 sprintf (buf, "%d:%d%s",
1570 ? mod_tm.tm_hour - 12 : mod_tm.tm_hour,
1572 mod_tm.tm_hour > 12 ? "pm" : "am");
1576 case 'T': /* `$T' runtime in 24-hour format */
1577 sprintf (buf, "%d:%d", mod_tm.tm_hour, mod_tm.tm_min);
1581 case '*': /* `$*' runtime in 24-hour format with secs */
1582 sprintf (buf, "%d:%d:%d", mod_tm.tm_hour, mod_tm.tm_min,
1587 case 'v': /* `$v': input file number */
1588 sprintf (buf, "%d", input_filenum);
1592 case 'V': /* `$V': input file number in --toc format */
1595 sprintf (buf, "%d-", input_filenum);
1600 case 'W': /* `$W' run date in `mm/dd/yy' format */
1601 sprintf (buf, "%02d/%02d/%02d", mod_tm.tm_mon + 1,
1602 mod_tm.tm_mday, mod_tm.tm_year % 100);
1606 case 'N': /* `$N' the full name of the printed file */
1610 case 'n': /* `$n' input file name without directory */
1611 cp = strrchr (fname, '/');
1619 case 'L': /* `$L' number of lines in this file. */
1620 /* This is valid only for TOC-strings. */
1621 sprintf (buf, "%d", current_file_linenum - 1);
1626 FATAL ((stderr, _("%s: unknown `$' escape `%c' (%d)"),
1627 context_name, str[i], str[i]));
1631 /* Reset width so the else-arm goes ok at the next round. */
1640 /* Escape PS specials. */
1641 cp = escape_string (rbuf);
1649 parse_key_value_pair (StringHashPtr set, char *kv)
1654 cp = strchr (kv, ':');
1657 if (strhash_delete (set, kv, strlen (kv) + 1, (void **) &cp))
1663 buffer_append_len (&key, kv, cp - kv);
1665 strhash_put (set, buffer_ptr (&key), strlen (buffer_ptr (&key)) + 1,
1666 xstrdup (cp + 1), (void **) &cp);
1670 buffer_uninit (&key);
1676 count_key_value_set (StringHashPtr set)
1682 for (got = strhash_get_first (set, &cp, &j, &value); got;
1683 got = strhash_get_next (set, &cp, &j, &value))
1691 pathwalk (char *path, PathWalkProc proc, void *context)
1698 for (cp = path; cp; cp = strchr (cp, PATH_SEPARATOR))
1703 cp2 = strchr (cp, PATH_SEPARATOR);
1709 memcpy (buf, cp, len);
1712 i = (*proc) (buf, context);
1722 file_lookup (char *path, void *context)
1725 FileLookupCtx *ctx = context;
1726 struct stat stat_st;
1729 MESSAGE (2, (stderr, "file_lookup(): %s/%s%s\t", path, ctx->name,
1732 len = strlen (path);
1733 if (len && path[len - 1] == '/')
1736 buffer_clear (ctx->fullname);
1737 buffer_append_len (ctx->fullname, path, len);
1738 buffer_append (ctx->fullname, "/");
1739 buffer_append (ctx->fullname, ctx->name);
1740 buffer_append (ctx->fullname, ctx->suffix);
1742 i = stat (buffer_ptr (ctx->fullname), &stat_st) == 0;
1744 MESSAGE (2, (stderr, "#%c\n", i ? 't' : 'f'));
1751 tilde_subst (char *fname)
1755 struct passwd *pswd;
1759 if (fname[0] != '~')
1760 return xstrdup (fname);
1762 if (fname[1] == '/' || fname[1] == '\0')
1764 /* The the user's home directory from the `HOME' environment
1766 cp = getenv ("HOME");
1768 return xstrdup (fname);
1770 buffer_init (&buffer);
1771 buffer_append (&buffer, cp);
1772 buffer_append (&buffer, fname + 1);
1774 result = buffer_copy (&buffer);
1775 buffer_uninit (&buffer);
1780 /* Get user's login name. */
1781 for (i = 1; fname[i] && fname[i] != '/'; i++)
1784 buffer_init (&buffer);
1785 buffer_append_len (&buffer, fname + 1, i - 1);
1787 pswd = getpwnam (buffer_ptr (&buffer));
1788 buffer_uninit (&buffer);
1792 /* Found passwd entry. */
1793 buffer_init (&buffer);
1794 buffer_append (&buffer, pswd->pw_dir);
1795 buffer_append (&buffer, fname + i);
1797 result = buffer_copy (&buffer);
1798 buffer_uninit (&buffer);
1803 /* No match found. */
1804 return xstrdup (fname);
1809 parse_float (char *string, int units, int horizontal)
1814 val = strtod (string, &end);
1817 ERROR ((stderr, _("malformed float dimension: \"%s\""), string));
1839 val *= CHAR_WIDTH ('m');
1845 goto malformed_float;
1852 goto malformed_float;
1860 * InputStream functions.
1864 is_open (InputStream *is, FILE *fp, char *fname, char *input_filter)
1866 /* Init stream variables. */
1867 is->data_in_buf = 0;
1870 is->unget_ch = NULL;
1872 is->unget_alloc = 0;
1884 fname = input_filter_stdin;
1887 * Count the initial command length, this will grow dynamically
1888 * when file specifier `%s' is encountered from <input_filter>.
1890 cmdlen = strlen (input_filter) + 1;
1891 cmd = xmalloc (cmdlen);
1893 /* Create filter command. */
1895 for (i = 0; input_filter[i]; i++)
1897 if (input_filter[i] == '%')
1899 switch (input_filter[i + 1])
1902 /* Expand cmd-buffer. */
1903 cmdlen += strlen (fname);
1904 cmd = xrealloc (cmd, cmdlen);
1906 /* Paste filename. */
1907 strcpy (cmd + pos, fname);
1908 pos += strlen (fname);
1919 cmd[pos++] = input_filter[i];
1924 cmd[pos++] = input_filter[i];
1928 is->fp = popen (cmd, "r");
1934 _("couldn't open input filter \"%s\" for file \"%s\": %s"),
1935 input_filter, fname ? fname : "(stdin)",
1942 /* Just open the stream. */
1948 is->fp = fopen (fname, "rb");
1951 ERROR ((stderr, _("couldn't open input file \"%s\": %s"), fname,
1963 is_close (InputStream *is)
1971 xfree (is->unget_ch);
1976 is_getc (InputStream *is)
1980 if (is->unget_pos > 0)
1982 ch = is->unget_ch[--is->unget_pos];
1988 /* Do we have any data left? */
1989 if (is->bufpos >= is->data_in_buf)
1992 if (is->nreads > 0 && is->data_in_buf < sizeof (is->buf))
1996 /* Read more data. */
1997 is->data_in_buf = fread (is->buf, 1, sizeof (is->buf), is->fp);
2004 return is->buf[is->bufpos++];
2009 is_ungetc (int ch, InputStream *is)
2011 if (is->unget_pos >= is->unget_alloc)
2013 is->unget_alloc += 1024;
2014 is->unget_ch = xrealloc (is->unget_ch, is->unget_alloc);
2017 is->unget_ch[is->unget_pos++] = ch;
2028 buffer_init (Buffer *buffer)
2030 buffer->allocated = 128;
2031 buffer->data = xmalloc (buffer->allocated);
2032 buffer->data[0] = '\0';
2038 buffer_uninit (Buffer *buffer)
2040 xfree (buffer->data);
2047 Buffer *buffer = (Buffer *) xcalloc (1, sizeof (Buffer));
2049 buffer_init (buffer);
2056 buffer_free (Buffer *buffer)
2058 buffer_uninit (buffer);
2064 buffer_append (Buffer *buffer, const char *data)
2066 buffer_append_len (buffer, data, strlen (data));
2071 buffer_append_len (Buffer *buffer, const char *data, size_t len)
2073 if (buffer->len + len + 1 >= buffer->allocated)
2075 buffer->allocated = buffer->len + len + 1024;
2076 buffer->data = xrealloc (buffer->data, buffer->allocated);
2079 memcpy (buffer->data + buffer->len, data, len);
2082 buffer->data[buffer->len] = '\0';
2087 buffer_copy (Buffer *buffer)
2089 char *copy = xmalloc (buffer->len + 1);
2091 memcpy (copy, buffer->data, buffer->len + 1);
2098 buffer_clear (Buffer *buffer)
2101 buffer->data[0] = '\0';
2106 buffer_ptr (Buffer *buffer)
2108 return buffer->data;
2113 buffer_len (Buffer *buffer)