cast: New macro NULL_SENTINEL.
[pspp] / src / output / ascii.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2007, 2009, 2010 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include <ctype.h>
20 #include <errno.h>
21 #include <limits.h>
22 #include <stdint.h>
23 #include <stdlib.h>
24
25 #include "data/file-name.h"
26 #include "data/settings.h"
27 #include "libpspp/assertion.h"
28 #include "libpspp/cast.h"
29 #include "libpspp/compiler.h"
30 #include "libpspp/message.h"
31 #include "libpspp/start-date.h"
32 #include "libpspp/string-map.h"
33 #include "libpspp/version.h"
34 #include "output/cairo.h"
35 #include "output/chart-item-provider.h"
36 #include "output/driver-provider.h"
37 #include "output/message-item.h"
38 #include "output/options.h"
39 #include "output/render.h"
40 #include "output/tab.h"
41 #include "output/table-item.h"
42 #include "output/text-item.h"
43
44 #include "gl/error.h"
45 #include "gl/minmax.h"
46 #include "gl/xalloc.h"
47
48 #include "gettext.h"
49 #define _(msgid) gettext (msgid)
50
51 /* This file uses TABLE_HORZ and TABLE_VERT enough to warrant abbreviating. */
52 #define H TABLE_HORZ
53 #define V TABLE_VERT
54
55 /* Line styles bit shifts. */
56 enum
57   {
58     LNS_TOP = 0,
59     LNS_LEFT = 2,
60     LNS_BOTTOM = 4,
61     LNS_RIGHT = 6,
62
63     LNS_COUNT = 256
64   };
65
66 static inline int
67 make_box_index (int left, int right, int top, int bottom)
68 {
69   return ((left << LNS_LEFT) | (right << LNS_RIGHT)
70           | (top << LNS_TOP) | (bottom << LNS_BOTTOM));
71 }
72
73 /* Character attributes. */
74 #define ATTR_EMPHASIS   0x100   /* Bold-face. */
75 #define ATTR_BOX        0x200   /* Line drawing character. */
76
77 /* A line of text. */
78 struct ascii_line
79   {
80     unsigned short *chars;      /* Characters and attributes. */
81     int n_chars;                /* Length. */
82     int allocated_chars;        /* Allocated "chars" elements. */
83   };
84
85 /* How to emphasize text. */
86 enum emphasis_style
87   {
88     EMPH_BOLD,                  /* Overstrike for bold. */
89     EMPH_UNDERLINE,             /* Overstrike for underlining. */
90     EMPH_NONE                   /* No emphasis. */
91   };
92
93 /* ASCII output driver. */
94 struct ascii_driver
95   {
96     struct output_driver driver;
97
98     /* User parameters. */
99     bool append;                /* Append if output file already exists? */
100     bool headers;               /* Print headers at top of page? */
101     bool paginate;              /* Insert formfeeds? */
102     bool squeeze_blank_lines;   /* Squeeze multiple blank lines into one? */
103     enum emphasis_style emphasis; /* How to emphasize text. */
104     char *chart_file_name;      /* Name of files used for charts. */
105
106     int width;                  /* Page width. */
107     int length;                 /* Page length minus margins and header. */
108     bool auto_width;            /* Use viewwidth as page width? */
109     bool auto_length;           /* Use viewlength as page width? */
110
111     int top_margin;             /* Top margin in lines. */
112     int bottom_margin;          /* Bottom margin in lines. */
113
114     char *box[LNS_COUNT];       /* Line & box drawing characters. */
115     char *init;                 /* Device initialization string. */
116
117     /* Internal state. */
118     char *command_name;
119     char *title;
120     char *subtitle;
121     char *file_name;            /* Output file name. */
122     FILE *file;                 /* Output file. */
123     bool error;                 /* Output error? */
124     int page_number;            /* Current page number. */
125     struct ascii_line *lines;   /* Page content. */
126     int allocated_lines;        /* Number of lines allocated. */
127     int chart_cnt;              /* Number of charts so far. */
128     int y;
129   };
130
131 static const struct output_driver_class ascii_driver_class;
132
133 static void ascii_submit (struct output_driver *, const struct output_item *);
134
135 static int vertical_margins (const struct ascii_driver *);
136
137 static const char *get_default_box (int right, int bottom, int left, int top);
138 static bool update_page_size (struct ascii_driver *, bool issue_error);
139 static int parse_page_size (struct driver_option *);
140
141 static void ascii_close_page (struct ascii_driver *);
142 static bool ascii_open_page (struct ascii_driver *);
143
144 static void ascii_draw_line (void *, int bb[TABLE_N_AXES][2],
145                              enum render_line_style styles[TABLE_N_AXES][2]);
146 static void ascii_measure_cell_width (void *, const struct table_cell *,
147                                       int *min, int *max);
148 static int ascii_measure_cell_height (void *, const struct table_cell *,
149                                       int width);
150 static void ascii_draw_cell (void *, const struct table_cell *,
151                              int bb[TABLE_N_AXES][2],
152                              int clip[TABLE_N_AXES][2]);
153
154 static struct ascii_driver *
155 ascii_driver_cast (struct output_driver *driver)
156 {
157   assert (driver->class == &ascii_driver_class);
158   return UP_CAST (driver, struct ascii_driver, driver);
159 }
160
161 static struct driver_option *
162 opt (struct output_driver *d, struct string_map *options, const char *key,
163      const char *default_value)
164 {
165   return driver_option_get (d, options, key, default_value);
166 }
167
168 static struct output_driver *
169 ascii_create (const char *file_name, enum settings_output_devices device_type,
170               struct string_map *o)
171 {
172   struct output_driver *d;
173   struct ascii_driver *a;
174   int paper_length;
175   int right, bottom, left, top;
176
177   a = xzalloc (sizeof *a);
178   d = &a->driver;
179   output_driver_init (&a->driver, &ascii_driver_class, file_name, device_type);
180   a->append = parse_boolean (opt (d, o, "append", "false"));
181   a->headers = parse_boolean (opt (d, o, "headers", "false"));
182   a->paginate = parse_boolean (opt (d, o, "paginate", "false"));
183   a->squeeze_blank_lines = parse_boolean (opt (d, o, "squeeze", "true"));
184   a->emphasis = parse_enum (opt (d, o, "emphasis", "none"),
185                             "bold", EMPH_BOLD,
186                             "underline", EMPH_UNDERLINE,
187                             "none", EMPH_NONE,
188                             NULL_SENTINEL);
189
190   a->chart_file_name = parse_chart_file_name (opt (d, o, "charts", file_name));
191
192   a->top_margin = parse_int (opt (d, o, "top-margin", "0"), 0, INT_MAX);
193   a->bottom_margin = parse_int (opt (d, o, "bottom-margin", "0"), 0, INT_MAX);
194
195   a->width = parse_page_size (opt (d, o, "width", "79"));
196   paper_length = parse_page_size (opt (d, o, "length", "66"));
197   a->auto_width = a->width < 0;
198   a->auto_length = paper_length < 0;
199   a->length = paper_length - vertical_margins (a);
200
201   for (right = 0; right < 4; right++)
202     for (bottom = 0; bottom < 4; bottom++)
203       for (left = 0; left < 4; left++)
204         for (top = 0; top < 4; top++)
205           {
206             int indx = make_box_index (left, right, top, bottom);
207             const char *default_value;
208             char name[16];
209
210             sprintf (name, "box[%d%d%d%d]", right, bottom, left, top);
211             default_value = get_default_box (right, bottom, left, top);
212             a->box[indx] = parse_string (opt (d, o, name, default_value));
213           }
214   a->init = parse_string (opt (d, o, "init", ""));
215
216   a->command_name = NULL;
217   a->title = xstrdup ("");
218   a->subtitle = xstrdup ("");
219   a->file_name = xstrdup (file_name);
220   a->file = NULL;
221   a->error = false;
222   a->page_number = 0;
223   a->lines = NULL;
224   a->allocated_lines = 0;
225   a->chart_cnt = 1;
226
227   if (!update_page_size (a, true))
228     goto error;
229
230   return d;
231
232 error:
233   output_driver_destroy (d);
234   return NULL;
235 }
236
237 static const char *
238 get_default_box (int right, int bottom, int left, int top)
239 {
240   switch ((top << 12) | (left << 8) | (bottom << 4) | (right << 0))
241     {
242     case 0x0000:
243       return " ";
244
245     case 0x0100: case 0x0101: case 0x0001:
246       return "-";
247
248     case 0x1000: case 0x1010: case 0x0010:
249       return "|";
250
251     case 0x0300: case 0x0303: case 0x0003:
252     case 0x0200: case 0x0202: case 0x0002:
253       return "=";
254
255     default:
256       return left > 1 || top > 1 || right > 1 || bottom > 1 ? "#" : "+";
257     }
258 }
259
260 static int
261 parse_page_size (struct driver_option *option)
262 {
263   int dim = atol (option->default_value);
264
265   if (option->value != NULL)
266     {
267       if (!strcmp (option->value, "auto"))
268         dim = -1;
269       else
270         {
271           int value;
272           char *tail;
273
274           errno = 0;
275           value = strtol (option->value, &tail, 0);
276           if (dim >= 1 && errno != ERANGE && *tail == '\0')
277             dim = value;
278           else
279             error (0, 0, _("%s: %s must be positive integer or `auto'"),
280                    option->driver_name, option->name);
281         }
282     }
283
284   driver_option_destroy (option);
285
286   return dim;
287 }
288
289 static int
290 vertical_margins (const struct ascii_driver *a)
291 {
292   return a->top_margin + a->bottom_margin + (a->headers ? 3 : 0);
293 }
294
295 /* Re-calculates the page width and length based on settings,
296    margins, and, if "auto" is set, the size of the user's
297    terminal window or GUI output window. */
298 static bool
299 update_page_size (struct ascii_driver *a, bool issue_error)
300 {
301   enum { MIN_WIDTH = 6, MIN_LENGTH = 6 };
302
303   if (a->auto_width)
304     a->width = settings_get_viewwidth ();
305   if (a->auto_length)
306     a->length = settings_get_viewlength () - vertical_margins (a);
307
308   if (a->width < MIN_WIDTH || a->length < MIN_LENGTH)
309     {
310       if (issue_error)
311         error (0, 0,
312                _("ascii: page excluding margins and headers "
313                  "must be at least %d characters wide by %d lines long, but "
314                  "as configured is only %d characters by %d lines"),
315                MIN_WIDTH, MIN_LENGTH,
316                a->width, a->length);
317       if (a->width < MIN_WIDTH)
318         a->width = MIN_WIDTH;
319       if (a->length < MIN_LENGTH)
320         a->length = MIN_LENGTH;
321       return false;
322     }
323
324   return true;
325 }
326
327 static void
328 ascii_destroy (struct output_driver *driver)
329 {
330   struct ascii_driver *a = ascii_driver_cast (driver);
331   int i;
332
333   if (a->y > 0)
334     ascii_close_page (a);
335
336   if (a->file != NULL)
337     fn_close (a->file_name, a->file);
338   free (a->command_name);
339   free (a->title);
340   free (a->subtitle);
341   free (a->file_name);
342   free (a->chart_file_name);
343   for (i = 0; i < LNS_COUNT; i++)
344     free (a->box[i]);
345   free (a->init);
346   for (i = 0; i < a->allocated_lines; i++)
347     free (a->lines[i].chars);
348   free (a->lines);
349   free (a);
350 }
351
352 static void
353 ascii_flush (struct output_driver *driver)
354 {
355   struct ascii_driver *a = ascii_driver_cast (driver);
356   if (a->y > 0)
357     {
358       ascii_close_page (a);
359
360       if (fn_close (a->file_name, a->file) != 0)
361         error (0, errno, _("ascii: closing output file `%s'"),
362                a->file_name);
363       a->file = NULL;
364     }
365 }
366
367 static void
368 ascii_init_caption_cell (const char *caption, struct table_cell *cell)
369 {
370   cell->contents = caption;
371   cell->options = TAB_LEFT;
372   cell->destructor = NULL;
373 }
374
375 static void
376 ascii_output_table_item (struct ascii_driver *a,
377                          const struct table_item *table_item)
378 {
379   const char *caption = table_item_get_caption (table_item);
380   struct render_params params;
381   struct render_page *page;
382   struct render_break x_break;
383   int caption_height;
384   int i;
385
386   update_page_size (a, false);
387
388   if (caption != NULL)
389     {
390       /* XXX doesn't do well with very large captions */
391       struct table_cell cell;
392       ascii_init_caption_cell (caption, &cell);
393       caption_height = ascii_measure_cell_height (a, &cell, a->width);
394     }
395   else
396     caption_height = 0;
397
398   params.draw_line = ascii_draw_line;
399   params.measure_cell_width = ascii_measure_cell_width;
400   params.measure_cell_height = ascii_measure_cell_height;
401   params.draw_cell = ascii_draw_cell,
402     params.aux = a;
403   params.size[H] = a->width;
404   params.size[V] = a->length - caption_height;
405   params.font_size[H] = 1;
406   params.font_size[V] = 1;
407   for (i = 0; i < RENDER_N_LINES; i++)
408     {
409       int width = i == RENDER_LINE_NONE ? 0 : 1;
410       params.line_widths[H][i] = width;
411       params.line_widths[V][i] = width;
412     }
413
414   if (a->file == NULL && !ascii_open_page (a))
415     return;
416
417   page = render_page_create (&params, table_item_get_table (table_item));
418   for (render_break_init (&x_break, page, H);
419        render_break_has_next (&x_break); )
420     {
421       struct render_page *x_slice;
422       struct render_break y_break;
423
424       x_slice = render_break_next (&x_break, a->width);
425       for (render_break_init (&y_break, x_slice, V);
426            render_break_has_next (&y_break); )
427         {
428           struct render_page *y_slice;
429           int space;
430
431           if (a->y > 0)
432             a->y++;
433
434           space = a->length - a->y - caption_height;
435           if (render_break_next_size (&y_break) > space)
436             {
437               assert (a->y > 0);
438               ascii_close_page (a);
439               if (!ascii_open_page (a))
440                 return;
441               continue;
442             }
443
444           y_slice = render_break_next (&y_break, space);
445           if (caption_height)
446             {
447               struct table_cell cell;
448               int bb[TABLE_N_AXES][2];
449
450               ascii_init_caption_cell (caption, &cell);
451               bb[H][0] = 0;
452               bb[H][1] = a->width;
453               bb[V][0] = 0;
454               bb[V][1] = caption_height;
455               ascii_draw_cell (a, &cell, bb, bb);
456               a->y += caption_height;
457               caption_height = 0;
458             }
459           render_page_draw (y_slice);
460           a->y += render_page_get_size (y_slice, V);
461           render_page_unref (y_slice);
462         }
463       render_break_destroy (&y_break);
464     }
465   render_break_destroy (&x_break);
466 }
467
468 static void
469 ascii_output_text (struct ascii_driver *a, const char *text)
470 {
471   struct table_item *table_item;
472
473   table_item = table_item_create (table_from_string (TAB_LEFT, text), NULL);
474   ascii_output_table_item (a, table_item);
475   table_item_unref (table_item);
476 }
477
478 static void
479 ascii_submit (struct output_driver *driver,
480               const struct output_item *output_item)
481 {
482   struct ascii_driver *a = ascii_driver_cast (driver);
483
484   output_driver_track_current_command (output_item, &a->command_name);
485
486   if (a->error)
487     return;
488
489   if (is_table_item (output_item))
490     ascii_output_table_item (a, to_table_item (output_item));
491 #ifdef HAVE_CAIRO
492   else if (is_chart_item (output_item) && a->chart_file_name != NULL)
493     {
494       struct chart_item *chart_item = to_chart_item (output_item);
495       char *file_name;
496
497       file_name = xr_draw_png_chart (chart_item, a->chart_file_name,
498                                      a->chart_cnt++);
499       if (file_name != NULL)
500         {
501           struct text_item *text_item;
502
503           text_item = text_item_create_format (
504             TEXT_ITEM_PARAGRAPH, _("See %s for a chart."), file_name);
505
506           ascii_submit (driver, &text_item->output_item);
507           text_item_unref (text_item);
508           free (file_name);
509         }
510     }
511 #endif  /* HAVE_CAIRO */
512   else if (is_text_item (output_item))
513     {
514       const struct text_item *text_item = to_text_item (output_item);
515       enum text_item_type type = text_item_get_type (text_item);
516       const char *text = text_item_get_text (text_item);
517
518       switch (type)
519         {
520         case TEXT_ITEM_TITLE:
521           free (a->title);
522           a->title = xstrdup (text);
523           break;
524
525         case TEXT_ITEM_SUBTITLE:
526           free (a->subtitle);
527           a->subtitle = xstrdup (text);
528           break;
529
530         case TEXT_ITEM_COMMAND_CLOSE:
531           break;
532
533         case TEXT_ITEM_BLANK_LINE:
534           if (a->y > 0)
535             a->y++;
536           break;
537
538         case TEXT_ITEM_EJECT_PAGE:
539           if (a->y > 0)
540             ascii_close_page (a);
541           break;
542
543         default:
544           ascii_output_text (a, text);
545           break;
546         }
547     }
548   else if (is_message_item (output_item))
549     {
550       const struct message_item *message_item = to_message_item (output_item);
551       const struct msg *msg = message_item_get_msg (message_item);
552       char *s = msg_to_string (msg, a->command_name);
553       ascii_output_text (a, s);
554       free (s);
555     }
556 }
557
558 const struct output_driver_factory txt_driver_factory =
559   { "txt", ascii_create };
560 const struct output_driver_factory list_driver_factory =
561   { "list", ascii_create };
562
563 static const struct output_driver_class ascii_driver_class =
564   {
565     "text",
566     ascii_destroy,
567     ascii_submit,
568     ascii_flush,
569   };
570 \f
571 enum wrap_mode
572   {
573     WRAP_WORD,
574     WRAP_CHAR,
575     WRAP_WORD_CHAR
576   };
577
578 static void ascii_expand_line (struct ascii_driver *, int y, int length);
579 static void ascii_layout_cell (struct ascii_driver *,
580                                const struct table_cell *,
581                                int bb[TABLE_N_AXES][2],
582                                int clip[TABLE_N_AXES][2], enum wrap_mode wrap,
583                                int *width, int *height);
584
585 static void
586 ascii_draw_line (void *a_, int bb[TABLE_N_AXES][2],
587                  enum render_line_style styles[TABLE_N_AXES][2])
588 {
589   struct ascii_driver *a = a_;
590   unsigned short int value;
591   int x1, y1;
592   int x, y;
593
594   /* Clip to the page. */
595   if (bb[H][0] >= a->width || bb[V][0] + a->y >= a->length)
596     return;
597   x1 = MIN (bb[H][1], a->width);
598   y1 = MIN (bb[V][1] + a->y, a->length);
599
600   /* Draw. */
601   value = ATTR_BOX | make_box_index (styles[V][0], styles[V][1],
602                                      styles[H][0], styles[H][1]);
603   for (y = bb[V][0] + a->y; y < y1; y++)
604     {
605       ascii_expand_line (a, y, x1);
606       for (x = bb[H][0]; x < x1; x++)
607         a->lines[y].chars[x] = value;
608     }
609 }
610
611 static void
612 ascii_measure_cell_width (void *a_, const struct table_cell *cell,
613                           int *min_width, int *max_width)
614 {
615   struct ascii_driver *a = a_;
616   int bb[TABLE_N_AXES][2];
617   int clip[TABLE_N_AXES][2];
618   int h;
619
620   bb[H][0] = 0;
621   bb[H][1] = INT_MAX;
622   bb[V][0] = 0;
623   bb[V][1] = INT_MAX;
624   clip[H][0] = clip[H][1] = clip[V][0] = clip[V][1] = 0;
625   ascii_layout_cell (a, cell, bb, clip, WRAP_WORD, max_width, &h);
626
627   if (strchr (cell->contents, ' '))
628     {
629       bb[H][1] = 1;
630       ascii_layout_cell (a, cell, bb, clip, WRAP_WORD, min_width, &h);
631     }
632   else
633     *min_width = *max_width;
634 }
635
636 static int
637 ascii_measure_cell_height (void *a_, const struct table_cell *cell, int width)
638 {
639   struct ascii_driver *a = a_;
640   int bb[TABLE_N_AXES][2];
641   int clip[TABLE_N_AXES][2];
642   int w, h;
643
644   bb[H][0] = 0;
645   bb[H][1] = width;
646   bb[V][0] = 0;
647   bb[V][1] = INT_MAX;
648   clip[H][0] = clip[H][1] = clip[V][0] = clip[V][1] = 0;
649   ascii_layout_cell (a, cell, bb, clip, WRAP_WORD, &w, &h);
650   return h;
651 }
652
653 static void
654 ascii_draw_cell (void *a_, const struct table_cell *cell,
655                  int bb[TABLE_N_AXES][2], int clip[TABLE_N_AXES][2])
656 {
657   struct ascii_driver *a = a_;
658   int w, h;
659
660   ascii_layout_cell (a, cell, bb, clip, WRAP_WORD, &w, &h);
661 }
662
663 /* Ensures that at least the first LENGTH characters of line Y in
664    ascii driver A have been cleared out. */
665 static void
666 ascii_expand_line (struct ascii_driver *a, int y, int length)
667 {
668   struct ascii_line *line = &a->lines[y];
669   if (line->n_chars < length)
670     {
671       int x;
672       if (line->allocated_chars < length)
673         {
674           line->allocated_chars = MAX (length, MIN (length * 2, a->width));
675           line->chars = xnrealloc (line->chars, line->allocated_chars,
676                                    sizeof *line->chars);
677         }
678       for (x = line->n_chars; x < length; x++)
679         line->chars[x] = ' ';
680       line->n_chars = length;
681     }
682 }
683
684 static void
685 text_draw (struct ascii_driver *a, const struct table_cell *cell,
686            int bb[TABLE_N_AXES][2], int clip[TABLE_N_AXES][2],
687            int y, const char *string, int n)
688 {
689   int x0 = MAX (0, clip[H][0]);
690   int y0 = MAX (0, clip[V][0] + a->y);
691   int x1 = clip[H][1];
692   int y1 = MIN (a->length, clip[V][1] + a->y);
693   int x;
694
695   y += a->y;
696   if (y < y0 || y >= y1)
697     return;
698
699   switch (cell->options & TAB_ALIGNMENT)
700     {
701     case TAB_LEFT:
702       x = bb[H][0];
703       break;
704     case TAB_CENTER:
705       x = (bb[H][0] + bb[H][1] - n + 1) / 2;
706       break;
707     case TAB_RIGHT:
708       x = bb[H][1] - n;
709       break;
710     default:
711       NOT_REACHED ();
712     }
713
714   if (x0 > x)
715     {
716       n -= x0 - x;
717       if (n <= 0)
718         return;
719       string += x0 - x;
720       x = x0;
721     }
722   if (x + n >= x1)
723     n = x1 - x;
724
725   if (n > 0)
726     {
727       int attr = cell->options & TAB_EMPH ? ATTR_EMPHASIS : 0;
728       size_t i;
729
730       ascii_expand_line (a, y, x + n);
731       for (i = 0; i < n; i++)
732         a->lines[y].chars[x + i] = string[i] | attr;
733     }
734 }
735
736 static void
737 ascii_layout_cell (struct ascii_driver *a, const struct table_cell *cell,
738                    int bb[TABLE_N_AXES][2], int clip[TABLE_N_AXES][2],
739                    enum wrap_mode wrap, int *width, int *height)
740 {
741   size_t length = strlen (cell->contents);
742   int y, pos;
743
744   *width = 0;
745   pos = 0;
746   for (y = bb[V][0]; y < bb[V][1] && pos < length; y++)
747     {
748       const char *line = &cell->contents[pos];
749       const char *new_line;
750       size_t line_len;
751
752       /* Find line length without considering word wrap. */
753       line_len = MIN (bb[H][1] - bb[H][0], length - pos);
754       new_line = memchr (line, '\n', line_len);
755       if (new_line != NULL)
756         line_len = new_line - line;
757
758       /* Word wrap. */
759       if (pos + line_len < length && wrap != WRAP_CHAR)
760         {
761           size_t space_len = line_len;
762           while (space_len > 0 && !isspace ((unsigned char) line[space_len]))
763             space_len--;
764           if (space_len > 0)
765             line_len = space_len;
766           else if (wrap == WRAP_WORD)
767             {
768               while (pos + line_len < length
769                      && !isspace ((unsigned char) line[line_len]))
770                 line_len++;
771             }
772         }
773       if (line_len > *width)
774         *width = line_len;
775
776       /* Draw text. */
777       text_draw (a, cell, bb, clip, y, line, line_len);
778
779       /* Next line. */
780       pos += line_len;
781       if (pos < length && isspace ((unsigned char) cell->contents[pos]))
782         pos++;
783     }
784   *height = y - bb[V][0];
785 }
786 \f
787 /* ascii_close_page () and support routines. */
788
789 static bool
790 ascii_open_page (struct ascii_driver *a)
791 {
792   int i;
793
794   if (a->error)
795     return false;
796
797   if (a->file == NULL)
798     {
799       a->file = fn_open (a->file_name, a->append ? "a" : "w");
800       if (a->file != NULL)
801         {
802           if (a->init != NULL)
803             fputs (a->init, a->file);
804         }
805       else
806         {
807           error (0, errno, _("ascii: opening output file `%s'"),
808                  a->file_name);
809           a->error = true;
810           return false;
811         }
812     }
813
814   a->page_number++;
815
816   if (a->length > a->allocated_lines)
817     {
818       a->lines = xnrealloc (a->lines, a->length, sizeof *a->lines);
819       for (i = a->allocated_lines; i < a->length; i++)
820         {
821           struct ascii_line *line = &a->lines[i];
822           line->chars = NULL;
823           line->allocated_chars = 0;
824         }
825       a->allocated_lines = a->length;
826     }
827
828   for (i = 0; i < a->length; i++)
829     a->lines[i].n_chars = 0;
830
831   return true;
832 }
833
834 /* Writes LINE to A's output file.  */
835 static void
836 output_line (struct ascii_driver *a, const struct ascii_line *line)
837 {
838   size_t length;
839   size_t i;
840
841   length = line->n_chars;
842   while (length > 0 && line->chars[length - 1] == ' ')
843     length--;
844
845   for (i = 0; i < length; i++)
846     {
847       int attribute = line->chars[i] & (ATTR_BOX | ATTR_EMPHASIS);
848       int ch = line->chars[i] & ~(ATTR_BOX | ATTR_EMPHASIS);
849
850       switch (attribute)
851         {
852         case ATTR_BOX:
853           fputs (a->box[ch], a->file);
854           break;
855
856         case ATTR_EMPHASIS:
857           if (a->emphasis == EMPH_BOLD)
858             fprintf (a->file, "%c\b%c", ch, ch);
859           else if (a->emphasis == EMPH_UNDERLINE)
860             fprintf (a->file, "_\b%c", ch);
861           else
862             putc (ch, a->file);
863           break;
864
865         default:
866           putc (ch, a->file);
867           break;
868         }
869     }
870
871   putc ('\n', a->file);
872 }
873
874 static void
875 output_title_line (FILE *out, int width, const char *left, const char *right)
876 {
877   struct string s = DS_EMPTY_INITIALIZER;
878   ds_put_char_multiple (&s, ' ', width);
879   if (left != NULL)
880     {
881       size_t length = MIN (strlen (left), width);
882       memcpy (ds_end (&s) - width, left, length);
883     }
884   if (right != NULL)
885     {
886       size_t length = MIN (strlen (right), width);
887       memcpy (ds_end (&s) - length, right, length);
888     }
889   ds_put_char (&s, '\n');
890   fputs (ds_cstr (&s), out);
891   ds_destroy (&s);
892 }
893
894 static void
895 ascii_close_page (struct ascii_driver *a)
896 {
897   bool any_blank;
898   int i, y;
899
900   a->y = 0;
901   if (a->file == NULL)
902     return;
903
904   if (!a->top_margin && !a->bottom_margin && a->squeeze_blank_lines
905       && !a->paginate && a->page_number > 1)
906     putc ('\n', a->file);
907
908   for (i = 0; i < a->top_margin; i++)
909     putc ('\n', a->file);
910   if (a->headers)
911     {
912       char *r1, *r2;
913
914       r1 = xasprintf (_("%s - Page %d"), get_start_date (), a->page_number);
915       r2 = xasprintf ("%s - %s" , version, host_system);
916
917       output_title_line (a->file, a->width, a->title, r1);
918       output_title_line (a->file, a->width, a->subtitle, r2);
919       putc ('\n', a->file);
920
921       free (r1);
922       free (r2);
923     }
924
925   any_blank = false;
926   for (y = 0; y < a->allocated_lines; y++)
927     {
928       struct ascii_line *line = &a->lines[y];
929
930       if (a->squeeze_blank_lines && y > 0 && line->n_chars == 0)
931         any_blank = true;
932       else
933         {
934           if (any_blank)
935             {
936               putc ('\n', a->file);
937               any_blank = false;
938             }
939
940           output_line (a, line);
941         }
942     }
943   if (!a->squeeze_blank_lines)
944     for (y = a->allocated_lines; y < a->length; y++)
945       putc ('\n', a->file);
946
947   for (i = 0; i < a->bottom_margin; i++)
948     putc ('\n', a->file);
949   if (a->paginate)
950     putc ('\f', a->file);
951 }