output: Add support for captions.
[pspp] / src / output / csv.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2009, 2010, 2012, 2013, 2014 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 <errno.h>
20 #include <stdlib.h>
21
22 #include "data/file-name.h"
23 #include "libpspp/assertion.h"
24 #include "libpspp/compiler.h"
25 #include "libpspp/message.h"
26 #include "libpspp/str.h"
27 #include "libpspp/string-map.h"
28 #include "output/text-item.h"
29 #include "output/driver-provider.h"
30 #include "output/options.h"
31 #include "output/message-item.h"
32 #include "output/table-item.h"
33 #include "output/table-provider.h"
34
35 #include "gl/xalloc.h"
36 #include "gl/xvasprintf.h"
37
38 #include "gettext.h"
39 #define _(msgid) gettext (msgid)
40
41 /* Comma-separated value output driver. */
42 struct csv_driver
43   {
44     struct output_driver driver;
45
46     char *separator;            /* Field separator (usually comma or tab). */
47     int quote;                  /* Quote character (usually ' or ") or 0. */
48     char *quote_set;            /* Characters that force quoting. */
49     bool titles;                /* Print table titles? */
50     bool captions;              /* Print table captions? */
51
52     char *file_name;            /* Output file name. */
53     char *command_name;         /* Current command. */
54     FILE *file;                 /* Output file. */
55     int n_items;                /* Number of items output so far. */
56   };
57
58 static const struct output_driver_class csv_driver_class;
59
60 static struct csv_driver *
61 csv_driver_cast (struct output_driver *driver)
62 {
63   assert (driver->class == &csv_driver_class);
64   return UP_CAST (driver, struct csv_driver, driver);
65 }
66
67 static struct driver_option *
68 opt (struct output_driver *d, struct string_map *options, const char *key,
69      const char *default_value)
70 {
71   return driver_option_get (d, options, key, default_value);
72 }
73
74 static struct output_driver *
75 csv_create (const char *file_name, enum settings_output_devices device_type,
76             struct string_map *o)
77 {
78   struct output_driver *d;
79   struct csv_driver *csv;
80   char *quote;
81
82   csv = xzalloc (sizeof *csv);
83   d = &csv->driver;
84   output_driver_init (&csv->driver, &csv_driver_class, file_name, device_type);
85
86   csv->separator = parse_string (opt (d, o, "separator", ","));
87   quote = parse_string (opt (d, o, "quote", "\""));
88   csv->quote = quote[0];
89   free (quote);
90   csv->quote_set = xasprintf ("\n\r\t%s%c", csv->separator, csv->quote);
91   csv->titles = parse_boolean (opt (d, o, "titles", "true"));
92   csv->captions = parse_boolean (opt (d, o, "captions", "true"));
93   csv->file_name = xstrdup (file_name);
94   csv->file = fn_open (csv->file_name, "w");
95   csv->n_items = 0;
96
97   if (csv->file == NULL)
98     {
99       msg_error (errno, _("error opening output file `%s'"), csv->file_name);
100       output_driver_destroy (d);
101       return NULL;
102     }
103
104   return d;
105 }
106
107 static void
108 csv_destroy (struct output_driver *driver)
109 {
110   struct csv_driver *csv = csv_driver_cast (driver);
111
112   if (csv->file != NULL)
113     fn_close (csv->file_name, csv->file);
114
115   free (csv->separator);
116   free (csv->quote_set);
117   free (csv->file_name);
118   free (csv);
119 }
120
121 static void
122 csv_flush (struct output_driver *driver)
123 {
124   struct csv_driver *csv = csv_driver_cast (driver);
125   if (csv->file != NULL)
126     fflush (csv->file);
127 }
128
129 static void
130 csv_output_field (struct csv_driver *csv, const char *field)
131 {
132   while (*field == ' ')
133     field++;
134
135   if (csv->quote && field[strcspn (field, csv->quote_set)])
136     {
137       const char *p;
138
139       putc (csv->quote, csv->file);
140       for (p = field; *p != '\0'; p++)
141         {
142           if (*p == csv->quote)
143             putc (csv->quote, csv->file);
144           putc (*p, csv->file);
145         }
146       putc (csv->quote, csv->file);
147     }
148   else
149     fputs (field, csv->file);
150 }
151
152 static void PRINTF_FORMAT (2, 3)
153 csv_output_field_format (struct csv_driver *csv, const char *format, ...)
154 {
155   va_list args;
156   char *s;
157
158   va_start (args, format);
159   s = xvasprintf (format, args);
160   va_end (args);
161
162   csv_output_field (csv, s);
163   free (s);
164 }
165
166 static void
167 csv_put_field (struct csv_driver *csv, struct string *s, const char *field)
168 {
169   while (*field == ' ')
170     field++;
171
172   if (csv->quote && field[strcspn (field, csv->quote_set)])
173     {
174       const char *p;
175
176       ds_put_byte (s, csv->quote);
177       for (p = field; *p != '\0'; p++)
178         {
179           if (*p == csv->quote)
180             ds_put_byte (s, csv->quote);
181           ds_put_byte (s, *p);
182         }
183       ds_put_byte (s, csv->quote);
184     }
185   else
186     ds_put_cstr (s, field);
187 }
188
189 static void
190 csv_output_subtable (struct csv_driver *csv, struct string *s,
191                      const struct table_item *item)
192 {
193   const struct table *t = table_item_get_table (item);
194   const char *title = table_item_get_title (item);
195   const char *caption = table_item_get_caption (item);
196   int y, x;
197
198   if (csv->titles && title != NULL)
199     {
200       csv_output_field_format (csv, "Table: %s", title);
201       putc ('\n', csv->file);
202     }
203
204   for (y = 0; y < table_nr (t); y++)
205     {
206       if (y > 0)
207         ds_put_byte (s, '\n');
208
209       for (x = 0; x < table_nc (t); x++)
210         {
211           struct table_cell cell;
212
213           table_get_cell (t, x, y, &cell);
214
215           if (x > 0)
216             ds_put_cstr (s, csv->separator);
217
218           if (x != cell.d[TABLE_HORZ][0] || y != cell.d[TABLE_VERT][0])
219             csv_put_field (csv, s, "");
220           else if (cell.n_contents == 1 && cell.contents[0].text != NULL)
221             csv_put_field (csv, s, cell.contents[0].text);
222           else
223             {
224               struct string s2;
225               size_t i;
226
227               ds_init_empty (&s2);
228               for (i = 0; i < cell.n_contents; i++)
229                 {
230                   if (i > 0)
231                     ds_put_cstr (&s2, "\n\n");
232
233                   if (cell.contents[i].text != NULL)
234                     ds_put_cstr (&s2, cell.contents[i].text);
235                   else
236                     csv_output_subtable (csv, &s2, cell.contents[i].table);
237                 }
238               csv_put_field (csv, s, ds_cstr (&s2));
239               ds_destroy (&s2);
240             }
241
242           table_cell_free (&cell);
243         }
244     }
245
246   if (csv->captions && caption != NULL)
247     {
248       csv_output_field_format (csv, "Caption: %s", caption);
249       putc ('\n', csv->file);
250     }
251 }
252
253 static void
254 csv_put_separator (struct csv_driver *csv)
255 {
256   if (csv->n_items++ > 0)
257     putc ('\n', csv->file);
258 }
259
260 static void
261 csv_submit (struct output_driver *driver,
262             const struct output_item *output_item)
263 {
264   struct csv_driver *csv = csv_driver_cast (driver);
265
266   output_driver_track_current_command (output_item, &csv->command_name);
267
268   if (is_table_item (output_item))
269     {
270       struct table_item *table_item = to_table_item (output_item);
271       const char *title = table_item_get_title (table_item);
272       const char *caption = table_item_get_caption (table_item);
273       const struct table *t = table_item_get_table (table_item);
274       int footnote_idx;
275       int x, y;
276
277       csv_put_separator (csv);
278
279       if (csv->titles && title != NULL)
280         {
281           csv_output_field_format (csv, "Table: %s", title);
282           putc ('\n', csv->file);
283         }
284
285       footnote_idx = 0;
286       for (y = 0; y < table_nr (t); y++)
287         {
288           for (x = 0; x < table_nc (t); x++)
289             {
290               struct table_cell cell;
291
292               table_get_cell (t, x, y, &cell);
293
294               if (x > 0)
295                 fputs (csv->separator, csv->file);
296
297               if (x != cell.d[TABLE_HORZ][0] || y != cell.d[TABLE_VERT][0])
298                 csv_output_field (csv, "");
299               else if (cell.n_contents == 1
300                        && cell.contents[0].text != NULL
301                        && cell.contents[0].n_footnotes == 0)
302                 csv_output_field (csv, cell.contents[0].text);
303               else
304                 {
305                   struct string s;
306                   size_t i;
307
308                   ds_init_empty (&s);
309                   for (i = 0; i < cell.n_contents; i++)
310                     {
311                       const struct cell_contents *c = &cell.contents[i];
312                       int j;
313
314                       if (i > 0)
315                         ds_put_cstr (&s, "\n\n");
316
317                       if (c->text != NULL)
318                         ds_put_cstr (&s, c->text);
319                       else
320                         csv_output_subtable (csv, &s, c->table);
321
322                       for (j = 0; j < c->n_footnotes; j++)
323                         {
324                           char marker[16];
325
326                           str_format_26adic (++footnote_idx, false,
327                                              marker, sizeof marker);
328                           ds_put_format (&s, "[%s]", marker);
329                         }
330                     }
331                   csv_output_field (csv, ds_cstr (&s));
332                   ds_destroy (&s);
333                 }
334
335               table_cell_free (&cell);
336             }
337           putc ('\n', csv->file);
338         }
339
340       if (csv->captions && caption != NULL)
341         {
342           csv_output_field_format (csv, "Caption: %s", caption);
343           putc ('\n', csv->file);
344         }
345
346       if (footnote_idx)
347         {
348           size_t i;
349
350           fputs ("\nFootnotes:\n", csv->file);
351
352           footnote_idx = 0;
353           for (y = 0; y < table_nr (t); y++)
354             {
355               struct table_cell cell;
356               for (x = 0; x < table_nc (t); x = cell.d[TABLE_HORZ][1])
357                 {
358                   table_get_cell (t, x, y, &cell);
359
360                   if (x == cell.d[TABLE_HORZ][0] && y == cell.d[TABLE_VERT][0])
361                     for (i = 0; i < cell.n_contents; i++)
362                       {
363                         const struct cell_contents *c = &cell.contents[i];
364                         int j;
365
366                         for (j = 0; j < c->n_footnotes; j++)
367                           {
368                             char marker[16];
369
370                             str_format_26adic (++footnote_idx, false,
371                                                marker, sizeof marker);
372                             csv_output_field (csv, marker);
373                             fputs (csv->separator, csv->file);
374                             csv_output_field (csv, c->footnotes[j]);
375                             putc ('\n', csv->file);
376                           }
377                       }
378                   table_cell_free (&cell);
379                 }
380             }
381         }
382     }
383   else if (is_text_item (output_item))
384     {
385       const struct text_item *text_item = to_text_item (output_item);
386       enum text_item_type type = text_item_get_type (text_item);
387       const char *text = text_item_get_text (text_item);
388
389       if (type == TEXT_ITEM_COMMAND_OPEN || type == TEXT_ITEM_COMMAND_CLOSE
390           || type == TEXT_ITEM_SYNTAX)
391         return;
392
393       csv_put_separator (csv);
394       switch (type)
395         {
396         case TEXT_ITEM_TITLE:
397           csv_output_field_format (csv, "Title: %s", text);
398           break;
399
400         case TEXT_ITEM_SUBTITLE:
401           csv_output_field_format (csv, "Subtitle: %s", text);
402           break;
403
404         default:
405           csv_output_field (csv, text);
406           break;
407         }
408       putc ('\n', csv->file);
409     }
410   else if (is_message_item (output_item))
411     {
412       const struct message_item *message_item = to_message_item (output_item);
413       const struct msg *msg = message_item_get_msg (message_item);
414       char *s = msg_to_string (msg, csv->command_name);
415       csv_put_separator (csv);
416       csv_output_field (csv, s);
417       free (s);
418       putc ('\n', csv->file);
419     }
420 }
421
422 struct output_driver_factory csv_driver_factory = { "csv", "-", csv_create };
423
424 static const struct output_driver_class csv_driver_class =
425   {
426     "csv",
427     csv_destroy,
428     csv_submit,
429     csv_flush,
430   };