65566c4e3a624a2ba5b02589438b019e52624e0c
[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 "data/file-handle-def.h"
24 #include "libpspp/assertion.h"
25 #include "libpspp/compiler.h"
26 #include "libpspp/message.h"
27 #include "libpspp/str.h"
28 #include "libpspp/string-map.h"
29 #include "output/text-item.h"
30 #include "output/driver-provider.h"
31 #include "output/options.h"
32 #include "output/message-item.h"
33 #include "output/table-item.h"
34 #include "output/table-provider.h"
35
36 #include "gl/minmax.h"
37 #include "gl/xalloc.h"
38 #include "gl/xvasprintf.h"
39
40 #include "gettext.h"
41 #define _(msgid) gettext (msgid)
42
43 /* Comma-separated value output driver. */
44 struct csv_driver
45   {
46     struct output_driver driver;
47
48     char *separator;            /* Field separator (usually comma or tab). */
49     int quote;                  /* Quote character (usually ' or ") or 0. */
50     char *quote_set;            /* Characters that force quoting. */
51     bool titles;                /* Print table titles? */
52     bool captions;              /* Print table captions? */
53
54     struct file_handle *handle;
55     FILE *file;                 /* Output file. */
56     int n_items;                /* Number of items output so far. */
57   };
58
59 static const struct output_driver_class csv_driver_class;
60
61 static struct csv_driver *
62 csv_driver_cast (struct output_driver *driver)
63 {
64   assert (driver->class == &csv_driver_class);
65   return UP_CAST (driver, struct csv_driver, driver);
66 }
67
68 static struct driver_option *
69 opt (struct output_driver *d, struct string_map *options, const char *key,
70      const char *default_value)
71 {
72   return driver_option_get (d, options, key, default_value);
73 }
74
75 static struct output_driver *
76 csv_create (struct file_handle *fh, enum settings_output_devices device_type,
77             struct string_map *o)
78 {
79   struct output_driver *d;
80   struct csv_driver *csv;
81   char *quote;
82
83   csv = xzalloc (sizeof *csv);
84   d = &csv->driver;
85   output_driver_init (&csv->driver, &csv_driver_class, fh_get_file_name (fh), device_type);
86
87   csv->separator = parse_string (opt (d, o, "separator", ","));
88   quote = parse_string (opt (d, o, "quote", "\""));
89   csv->quote = quote[0];
90   free (quote);
91   csv->quote_set = xasprintf ("\n\r\t%s%c", csv->separator, csv->quote);
92   csv->titles = parse_boolean (opt (d, o, "titles", "true"));
93   csv->captions = parse_boolean (opt (d, o, "captions", "true"));
94   csv->handle = fh;
95   csv->file = fn_open (fh, "w");
96   csv->n_items = 0;
97
98   if (csv->file == NULL)
99     {
100       msg_error (errno, _("error opening output file `%s'"), fh_get_file_name (fh));
101       output_driver_destroy (d);
102       return NULL;
103     }
104
105   return d;
106 }
107
108 static void
109 csv_destroy (struct output_driver *driver)
110 {
111   struct csv_driver *csv = csv_driver_cast (driver);
112
113   if (csv->file != NULL)
114     fn_close (csv->handle, csv->file);
115
116   free (csv->separator);
117   free (csv->quote_set);
118   fh_unref (csv->handle);
119   free (csv);
120 }
121
122 static void
123 csv_flush (struct output_driver *driver)
124 {
125   struct csv_driver *csv = csv_driver_cast (driver);
126   if (csv->file != NULL)
127     fflush (csv->file);
128 }
129
130 static void
131 csv_output_field__ (struct csv_driver *csv, struct substring field)
132 {
133   ss_ltrim (&field, ss_cstr (" "));
134
135   if (csv->quote && ss_cspan (field, ss_cstr (csv->quote_set)) < field.length)
136     {
137       putc (csv->quote, csv->file);
138       for (size_t i = 0; i < field.length; i++)
139         {
140           if (field.string[i] == csv->quote)
141             putc (csv->quote, csv->file);
142           putc (field.string[i], csv->file);
143         }
144       putc (csv->quote, csv->file);
145     }
146   else
147     fwrite (field.string, field.length, 1, csv->file);
148 }
149
150 static void
151 csv_output_field (struct csv_driver *csv, const char *field)
152 {
153   csv_output_field__ (csv, ss_cstr (field));
154 }
155
156 static void
157 csv_put_separator (struct csv_driver *csv)
158 {
159   if (csv->n_items++ > 0)
160     putc ('\n', csv->file);
161 }
162
163 static void
164 csv_output_lines (struct csv_driver *csv, const char *text_)
165 {
166   struct substring text = ss_cstr (text_);
167   struct substring line;
168   size_t save_idx = 0;
169   while (ss_separate (text, ss_cstr ("\n"), &save_idx, &line))
170     {
171       csv_output_field__ (csv, line);
172       putc ('\n', csv->file);
173     }
174 }
175
176 static void
177 csv_format_footnotes (const struct footnote **f, size_t n, struct string *s)
178 {
179   for (size_t i = 0; i < n; i++)
180     ds_put_format (s, "[%s]", f[i]->marker);
181 }
182
183 static void
184 csv_output_table_item_text (struct csv_driver *csv,
185                             const struct table_item_text *text,
186                             const char *leader)
187 {
188   if (!text)
189     return;
190
191   struct string s = DS_EMPTY_INITIALIZER;
192   ds_put_format (&s, "%s: %s", leader, text->content);
193   csv_format_footnotes (text->footnotes, text->n_footnotes, &s);
194   csv_output_field (csv, ds_cstr (&s));
195   ds_destroy (&s);
196   putc ('\n', csv->file);
197 }
198
199 static void
200 csv_submit (struct output_driver *driver,
201             const struct output_item *output_item)
202 {
203   struct csv_driver *csv = csv_driver_cast (driver);
204
205   if (is_table_item (output_item))
206     {
207       struct table_item *table_item = to_table_item (output_item);
208       const struct table *t = table_item_get_table (table_item);
209       int x, y;
210
211       csv_put_separator (csv);
212
213       if (csv->titles)
214         csv_output_table_item_text (csv, table_item_get_title (table_item),
215                                     "Table");
216
217       for (y = 0; y < table_nr (t); y++)
218         {
219           for (x = 0; x < table_nc (t); x++)
220             {
221               struct table_cell cell;
222
223               table_get_cell (t, x, y, &cell);
224
225               if (x > 0)
226                 fputs (csv->separator, csv->file);
227
228               if (x != cell.d[TABLE_HORZ][0] || y != cell.d[TABLE_VERT][0])
229                 csv_output_field (csv, "");
230               else if (!(cell.options & TAB_MARKUP) && !cell.n_footnotes)
231                 csv_output_field (csv, cell.text);
232               else
233                 {
234                   struct string s = DS_EMPTY_INITIALIZER;
235
236                   if (cell.options & TAB_MARKUP)
237                     {
238                       char *t = output_get_text_from_markup (cell.text);
239                       ds_put_cstr (&s, t);
240                       free (t);
241                     }
242                   else
243                     ds_put_cstr (&s, cell.text);
244
245                   csv_format_footnotes (cell.footnotes, cell.n_footnotes, &s);
246                   csv_output_field (csv, ds_cstr (&s));
247                   ds_destroy (&s);
248                 }
249
250               table_cell_free (&cell);
251             }
252           putc ('\n', csv->file);
253         }
254
255       if (csv->captions)
256         csv_output_table_item_text (csv, table_item_get_caption (table_item),
257                                     "Caption");
258
259       const struct footnote **f;
260       size_t n_footnotes = table_collect_footnotes (table_item, &f);
261       if (n_footnotes)
262         {
263           fputs ("\nFootnotes:\n", csv->file);
264
265           for (size_t i = 0; i < n_footnotes; i++)
266             if (f[i])
267               {
268                 csv_output_field (csv, f[i]->marker);
269                 fputs (csv->separator, csv->file);
270                 csv_output_field (csv, f[i]->content);
271                 putc ('\n', csv->file);
272               }
273
274           free (f);
275         }
276     }
277   else if (is_text_item (output_item))
278     {
279       const struct text_item *text_item = to_text_item (output_item);
280       enum text_item_type type = text_item_get_type (text_item);
281       const char *text = text_item_get_text (text_item);
282
283       if (type == TEXT_ITEM_SYNTAX || type == TEXT_ITEM_PAGE_TITLE)
284         return;
285
286       csv_put_separator (csv);
287
288       if (text_item->markup)
289         {
290           char *plain_text = output_get_text_from_markup (text);
291           csv_output_lines (csv, plain_text);
292           free (plain_text);
293         }
294       else
295         csv_output_lines (csv, text);
296     }
297   else if (is_message_item (output_item))
298     {
299       const struct message_item *message_item = to_message_item (output_item);
300       char *s = msg_to_string (message_item_get_msg (message_item));
301       csv_put_separator (csv);
302       csv_output_field (csv, s);
303       free (s);
304       putc ('\n', csv->file);
305     }
306 }
307
308 struct output_driver_factory csv_driver_factory = { "csv", "-", csv_create };
309
310 static const struct output_driver_class csv_driver_class =
311   {
312     "csv",
313     csv_destroy,
314     csv_submit,
315     csv_flush,
316   };