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