table: Get rid of TAL_GAP.
[pspp] / src / language / dictionary / sys-file-info.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2009, 2010, 2011, 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 #include <config.h>
17
18 #include <ctype.h>
19 #include <errno.h>
20 #include <float.h>
21 #include <stdlib.h>
22
23 #include "data/any-reader.h"
24 #include "data/attributes.h"
25 #include "data/casereader.h"
26 #include "data/dataset.h"
27 #include "data/dictionary.h"
28 #include "data/file-handle-def.h"
29 #include "data/format.h"
30 #include "data/missing-values.h"
31 #include "data/value-labels.h"
32 #include "data/variable.h"
33 #include "data/vector.h"
34 #include "language/command.h"
35 #include "language/data-io/file-handle.h"
36 #include "language/lexer/lexer.h"
37 #include "language/lexer/variable-parser.h"
38 #include "libpspp/array.h"
39 #include "libpspp/hash-functions.h"
40 #include "libpspp/i18n.h"
41 #include "libpspp/message.h"
42 #include "libpspp/misc.h"
43 #include "libpspp/pool.h"
44 #include "libpspp/string-array.h"
45 #include "output/tab.h"
46 #include "output/text-item.h"
47 #include "output/table-item.h"
48
49 #include "gl/count-one-bits.h"
50 #include "gl/localcharset.h"
51 #include "gl/intprops.h"
52 #include "gl/minmax.h"
53 #include "gl/xalloc.h"
54
55 #include "gettext.h"
56 #define _(msgid) gettext (msgid)
57 #define N_(msgid) (msgid)
58
59 /* Information to include in displaying a dictionary. */
60 enum
61   {
62     /* Variable table. */
63     DF_NAME              = 1 << 0,
64     DF_POSITION          = 1 << 1,
65     DF_LABEL             = 1 << 2,
66     DF_MEASUREMENT_LEVEL = 1 << 3,
67     DF_ROLE              = 1 << 4,
68     DF_WIDTH             = 1 << 5,
69     DF_ALIGNMENT         = 1 << 6,
70     DF_PRINT_FORMAT      = 1 << 7,
71     DF_WRITE_FORMAT      = 1 << 8,
72     DF_MISSING_VALUES    = 1 << 9,
73 #define DF_ALL_VARIABLE ((1 << 10) - 1)
74
75     /* Value labels table. */
76     DF_VALUE_LABELS      = 1 << 10,
77
78     /* Attribute table. */
79     DF_AT_ATTRIBUTES     = 1 << 11, /* Attributes whose names begin with @. */
80     DF_ATTRIBUTES        = 1 << 12, /* All other attributes. */
81   };
82
83 static void display_variables (const struct variable **, size_t, int flags);
84 static void display_value_labels (const struct variable **, size_t);
85 static void display_attributes (const struct attrset *,
86                                 const struct variable **, size_t, int flags);
87
88 static void report_encodings (const struct file_handle *, struct pool *,
89                               char **titles, bool *ids,
90                               char **strings, size_t n_strings);
91
92 /* SYSFILE INFO utility. */
93 int
94 cmd_sysfile_info (struct lexer *lexer, struct dataset *ds UNUSED)
95 {
96   struct any_reader *any_reader;
97   struct file_handle *h;
98   struct dictionary *d;
99   struct tab_table *t;
100   struct casereader *reader;
101   struct any_read_info info;
102   char *encoding;
103   int r;
104
105   h = NULL;
106   encoding = NULL;
107   for (;;)
108     {
109       lex_match (lexer, T_SLASH);
110
111       if (lex_match_id (lexer, "FILE") || lex_is_string (lexer))
112         {
113           lex_match (lexer, T_EQUALS);
114
115           fh_unref (h);
116           h = fh_parse (lexer, FH_REF_FILE, NULL);
117           if (h == NULL)
118             goto error;
119         }
120       else if (lex_match_id (lexer, "ENCODING"))
121         {
122           lex_match (lexer, T_EQUALS);
123
124           if (!lex_force_string (lexer))
125             goto error;
126
127           free (encoding);
128           encoding = ss_xstrdup (lex_tokss (lexer));
129
130           lex_get (lexer);
131         }
132       else
133         break;
134     }
135
136   if (h == NULL)
137     {
138       lex_sbc_missing ("FILE");
139       goto error;
140     }
141
142   any_reader = any_reader_open (h);
143   if (!any_reader)
144     {
145       free (encoding);
146       return CMD_FAILURE;
147     }
148
149   if (encoding && !strcasecmp (encoding, "detect"))
150     {
151       char **titles, **strings;
152       struct pool *pool;
153       size_t n_strings;
154       bool *ids;
155
156       pool = pool_create ();
157       n_strings = any_reader_get_strings (any_reader, pool,
158                                           &titles, &ids, &strings);
159       any_reader_close (any_reader);
160
161       report_encodings (h, pool, titles, ids, strings, n_strings);
162       fh_unref (h);
163       pool_destroy (pool);
164       free (encoding);
165
166       return CMD_SUCCESS;
167     }
168
169   reader = any_reader_decode (any_reader, encoding, &d, &info);
170   if (!reader)
171     goto error;
172   casereader_destroy (reader);
173
174   t = tab_create (2, 11 + (info.product_ext != NULL));
175   r = 0;
176   
177   tab_text (t, 0, r, TAB_LEFT, _("File:"));
178   tab_text (t, 1, r++, TAB_LEFT, fh_get_file_name (h));
179
180   tab_text (t, 0, r, TAB_LEFT, _("Label:"));
181   {
182     const char *label = dict_get_label (d);
183     if (label == NULL)
184       label = _("No label.");
185     tab_text (t, 1, r++, TAB_LEFT, label);
186   }
187
188   tab_text (t, 0, r, TAB_LEFT, _("Created:"));
189   tab_text_format (t, 1, r++, TAB_LEFT, "%s %s by %s",
190                    info.creation_date, info.creation_time, info.product);
191
192   if (info.product_ext)
193     {
194       tab_text (t, 0, r, TAB_LEFT, _("Product:"));
195       tab_text (t, 1, r++, TAB_LEFT, info.product_ext);
196     }
197
198   tab_text (t, 0, r, TAB_LEFT, _("Integer Format:"));
199   tab_text (t, 1, r++, TAB_LEFT,
200             info.integer_format == INTEGER_MSB_FIRST ? _("Big Endian")
201             : info.integer_format == INTEGER_LSB_FIRST ? _("Little Endian")
202             : _("Unknown"));
203
204   tab_text (t, 0, r, TAB_LEFT, _("Real Format:"));
205   tab_text (t, 1, r++, TAB_LEFT,
206             info.float_format == FLOAT_IEEE_DOUBLE_LE ? _("IEEE 754 LE.")
207             : info.float_format == FLOAT_IEEE_DOUBLE_BE ? _("IEEE 754 BE.")
208             : info.float_format == FLOAT_VAX_D ? _("VAX D.")
209             : info.float_format == FLOAT_VAX_G ? _("VAX G.")
210             : info.float_format == FLOAT_Z_LONG ? _("IBM 390 Hex Long.")
211             : _("Unknown"));
212
213   tab_text (t, 0, r, TAB_LEFT, _("Variables:"));
214   tab_text_format (t, 1, r++, TAB_LEFT, "%zu", dict_get_var_cnt (d));
215
216   tab_text (t, 0, r, TAB_LEFT, _("Cases:"));
217   if (info.case_cnt == -1)
218     tab_text (t, 1, r, TAB_LEFT, _("Unknown"));
219   else
220     tab_text_format (t, 1, r, TAB_LEFT, "%ld", (long int) info.case_cnt);
221   r++;
222
223   tab_text (t, 0, r, TAB_LEFT, _("Type:"));
224   tab_text (t, 1, r++, TAB_LEFT, gettext (info.klass->name));
225
226   tab_text (t, 0, r, TAB_LEFT, _("Weight:"));
227   {
228     struct variable *weight_var = dict_get_weight (d);
229     tab_text (t, 1, r++, TAB_LEFT,
230               (weight_var != NULL
231                ? var_get_name (weight_var) : _("Not weighted.")));
232   }
233
234   tab_text (t, 0, r, TAB_LEFT, _("Compression:"));
235   tab_text_format (t, 1, r++, TAB_LEFT,
236                    info.compression == ANY_COMP_NONE ? _("None")
237                    : info.compression == ANY_COMP_SIMPLE ? "SAV"
238                    : "ZSAV");
239
240   tab_text (t, 0, r, TAB_LEFT, _("Encoding:"));
241   tab_text (t, 1, r++, TAB_LEFT, dict_get_encoding (d));
242
243   tab_submit (t);
244
245   size_t n_vars = dict_get_var_cnt (d);
246   const struct variable **vars = xnmalloc (n_vars, sizeof *vars);
247   for (size_t i = 0; i < dict_get_var_cnt (d); i++)
248     vars[i] = dict_get_var (d, i);
249   display_variables (vars, n_vars, DF_ALL_VARIABLE);
250   display_value_labels (vars, n_vars);
251   display_attributes (dict_get_attributes (dataset_dict (ds)),
252                       vars, n_vars, DF_ATTRIBUTES);
253
254   dict_unref (d);
255
256   fh_unref (h);
257   free (encoding);
258   any_read_info_destroy (&info);
259   return CMD_SUCCESS;
260
261 error:
262   fh_unref (h);
263   free (encoding);
264   return CMD_FAILURE;
265 }
266 \f
267 /* DISPLAY utility. */
268
269 static void display_macros (void);
270 static void display_documents (const struct dictionary *dict);
271 static void display_vectors (const struct dictionary *dict, int sorted);
272
273 int
274 cmd_display (struct lexer *lexer, struct dataset *ds)
275 {
276   /* Whether to sort the list of variables alphabetically. */
277   int sorted;
278
279   /* Variables to display. */
280   size_t n;
281   const struct variable **vl;
282
283   if (lex_match_id (lexer, "MACROS"))
284     display_macros ();
285   else if (lex_match_id (lexer, "DOCUMENTS"))
286     display_documents (dataset_dict (ds));
287   else if (lex_match_id (lexer, "FILE"))
288     {
289       if (!lex_force_match_id (lexer, "LABEL"))
290         return CMD_FAILURE;
291       if (dict_get_label (dataset_dict (ds)) == NULL)
292         tab_output_text (TAB_LEFT,
293                          _("The active dataset does not have a file label."));
294       else
295         tab_output_text_format (TAB_LEFT, _("File label: %s"),
296                                 dict_get_label (dataset_dict (ds)));
297     }
298   else
299     {
300       int flags;
301
302       sorted = lex_match_id (lexer, "SORTED");
303
304       if (lex_match_id (lexer, "VECTORS"))
305         {
306           display_vectors (dataset_dict(ds), sorted);
307           return CMD_SUCCESS;
308         }
309       else if (lex_match_id (lexer, "SCRATCH"))
310         {
311           dict_get_vars (dataset_dict (ds), &vl, &n, DC_ORDINARY);
312           flags = DF_NAME;
313         }
314       else
315         {
316           struct subcommand
317             {
318               const char *name;
319               int flags;
320             };
321           static const struct subcommand subcommands[] =
322             {
323               {"@ATTRIBUTES", DF_ATTRIBUTES | DF_AT_ATTRIBUTES},
324               {"ATTRIBUTES", DF_ATTRIBUTES},
325               {"DICTIONARY", (DF_NAME | DF_POSITION | DF_LABEL
326                               | DF_MEASUREMENT_LEVEL | DF_ROLE | DF_WIDTH
327                               | DF_ALIGNMENT | DF_PRINT_FORMAT
328                               | DF_WRITE_FORMAT | DF_MISSING_VALUES
329                               | DF_VALUE_LABELS)},
330               {"INDEX", DF_NAME | DF_POSITION},
331               {"LABELS", DF_NAME | DF_POSITION | DF_LABEL},
332               {"NAMES", DF_NAME},
333               {"VARIABLES", (DF_NAME | DF_POSITION | DF_PRINT_FORMAT
334                              | DF_WRITE_FORMAT | DF_MISSING_VALUES)},
335               {NULL, 0},
336             };
337           const struct subcommand *sbc;
338           struct dictionary *dict = dataset_dict (ds);
339
340           flags = 0;
341           for (sbc = subcommands; sbc->name != NULL; sbc++)
342             if (lex_match_id (lexer, sbc->name))
343               {
344                 flags = sbc->flags;
345                 break;
346               }
347
348           lex_match (lexer, T_SLASH);
349           lex_match_id (lexer, "VARIABLES");
350           lex_match (lexer, T_EQUALS);
351
352           if (lex_token (lexer) != T_ENDCMD)
353             {
354               if (!parse_variables_const (lexer, dict, &vl, &n, PV_NONE))
355                 {
356                   free (vl);
357                   return CMD_FAILURE;
358                 }
359             }
360           else
361             dict_get_vars (dict, &vl, &n, 0);
362         }
363
364       if (n > 0)
365         {
366           sort (vl, n, sizeof *vl, (sorted
367                                     ? compare_var_ptrs_by_name
368                                     : compare_var_ptrs_by_dict_index), NULL);
369
370           int variable_flags = flags & DF_ALL_VARIABLE;
371           if (variable_flags)
372             display_variables (vl, n, variable_flags);
373
374           if (flags & DF_VALUE_LABELS)
375             display_value_labels (vl, n);
376
377           int attribute_flags = flags & (DF_ATTRIBUTES | DF_AT_ATTRIBUTES);
378           if (attribute_flags)
379             display_attributes (dict_get_attributes (dataset_dict (ds)),
380                                 vl, n, attribute_flags);
381         }
382       else
383         msg (SW, _("No variables to display."));
384
385       free (vl);
386     }
387
388   return CMD_SUCCESS;
389 }
390
391 static void
392 display_macros (void)
393 {
394   tab_output_text (TAB_LEFT, _("Macros not supported."));
395 }
396
397 static void
398 display_documents (const struct dictionary *dict)
399 {
400   const struct string_array *documents = dict_get_documents (dict);
401
402   if (string_array_is_empty (documents))
403     tab_output_text (TAB_LEFT, _("The active dataset dictionary does not "
404                                  "contain any documents."));
405   else
406     {
407       size_t i;
408
409       tab_output_text (TAB_LEFT | TAT_TITLE,
410                        _("Documents in the active dataset:"));
411       for (i = 0; i < dict_get_document_line_cnt (dict); i++)
412         tab_output_text (TAB_LEFT | TAB_FIX, dict_get_document_line (dict, i));
413     }
414 }
415
416 static void
417 display_variables (const struct variable **vl, size_t n, int flags)
418 {
419   int nc = count_one_bits (flags);
420   struct tab_table *t = tab_create (nc, n + 1);
421   tab_title (t, "%s", _("Variables"));
422   tab_headers (t, 0, 0, 1, 0);
423   tab_hline (t, TAL_2, 0, nc - 1, 1);
424
425   struct heading
426     {
427       int flag;
428       const char *title;
429     };
430   static const struct heading headings[] = {
431     { DF_NAME, N_("Name") },
432     { DF_POSITION, N_("Position") },
433     { DF_LABEL, N_("Label") },
434     { DF_MEASUREMENT_LEVEL, N_("Measurement Level") },
435     { DF_ROLE, N_("Role") },
436     { DF_WIDTH, N_("Width") },
437     { DF_ALIGNMENT, N_("Alignment") },
438     { DF_PRINT_FORMAT, N_("Print Format") },
439     { DF_WRITE_FORMAT, N_("Write Format") },
440     { DF_MISSING_VALUES, N_("Missing Values") },
441   };
442   for (size_t i = 0, x = 0; i < sizeof headings / sizeof *headings; i++)
443     if (flags & headings[i].flag)
444       tab_text (t, x++, 0, TAB_LEFT | TAT_TITLE, gettext (headings[i].title));
445
446   for (size_t i = 0; i < n; i++)
447     {
448       const struct variable *v = vl[i];
449       size_t y = i + 1;
450       size_t x = 0;
451       if (flags & DF_NAME)
452         tab_text (t, x++, y, TAB_LEFT, var_get_name (v));
453       if (flags & DF_POSITION)
454         {
455           char s[INT_BUFSIZE_BOUND (size_t)];
456
457           sprintf (s, "%zu", var_get_dict_index (v) + 1);
458           tab_text (t, x++, y, TAB_LEFT, s);
459         }
460       if (flags & DF_LABEL)
461         {
462           const char *label = var_get_label (v);
463           if (label)
464             tab_text (t, x, y, TAB_LEFT, label);
465           x++;
466         }
467       if (flags & DF_MEASUREMENT_LEVEL)
468         tab_text (t, x++, y, TAB_LEFT,
469                   measure_to_string (var_get_measure (v)));
470       if (flags & DF_ROLE)
471         tab_text (t, x++, y, TAB_LEFT,
472                   var_role_to_string (var_get_role (v)));
473       if (flags & DF_WIDTH)
474         {
475           char s[INT_BUFSIZE_BOUND (int)];
476           sprintf (s, "%d", var_get_display_width (v));
477           tab_text (t, x++, y, TAB_RIGHT, s);
478         }
479       if (flags & DF_ALIGNMENT)
480         tab_text (t, x++, y, TAB_LEFT,
481                   alignment_to_string (var_get_alignment (v)));
482       if (flags & DF_PRINT_FORMAT)
483         {
484           const struct fmt_spec *print = var_get_print_format (v);
485           char s[FMT_STRING_LEN_MAX + 1];
486
487           tab_text (t, x++, y, TAB_LEFT, fmt_to_string (print, s));
488         }
489       if (flags & DF_WRITE_FORMAT)
490         {
491           const struct fmt_spec *write = var_get_write_format (v);
492           char s[FMT_STRING_LEN_MAX + 1];
493
494           tab_text (t, x++, y, TAB_LEFT, fmt_to_string (write, s));
495         }
496       if (flags & DF_MISSING_VALUES)
497         {
498           const struct missing_values *mv = var_get_missing_values (v);
499
500           struct string s = DS_EMPTY_INITIALIZER;
501           if (mv_has_range (mv))
502             {
503               double x, y;
504               mv_get_range (mv, &x, &y);
505               if (x == LOWEST)
506                 ds_put_format (&s, "LOWEST THRU %.*g", DBL_DIG + 1, y);
507               else if (y == HIGHEST)
508                 ds_put_format (&s, "%.*g THRU HIGHEST", DBL_DIG + 1, x);
509               else
510                 ds_put_format (&s, "%.*g THRU %.*g",
511                                DBL_DIG + 1, x,
512                                DBL_DIG + 1, y);
513             }
514           for (size_t j = 0; j < mv_n_values (mv); j++)
515             {
516               const union value *value = mv_get_value (mv, j);
517               if (!ds_is_empty (&s))
518                 ds_put_cstr (&s, "; ");
519               if (var_is_numeric (v))
520                 ds_put_format (&s, "%.*g", DBL_DIG + 1, value->f);
521               else
522                 {
523                   int width = var_get_width (v);
524                   int mv_width = MIN (width, MV_MAX_STRING);
525
526                   ds_put_byte (&s, '"');
527                   memcpy (ds_put_uninit (&s, mv_width),
528                           value_str (value, width), mv_width);
529                   ds_put_byte (&s, '"');
530                 }
531             }
532           if (!ds_is_empty (&s))
533             tab_text (t, x, y, TAB_LEFT, ds_cstr (&s));
534           ds_destroy (&s);
535           x++;
536
537           assert (x == nc);
538         }
539     }
540
541   tab_submit (t);
542 }
543
544 static void
545 display_value_labels (const struct variable **vars, size_t n_vars)
546 {
547   size_t n_value_labels = 0;
548   for (size_t i = 0; i < n_vars; i++)
549     n_value_labels += val_labs_count (var_get_value_labels (vars[i]));
550   if (!n_value_labels)
551     return;
552
553   struct tab_table *t = tab_create (3, n_value_labels + 1);
554   tab_title (t, "%s", _("Value Labels"));
555   tab_headers (t, 0, 0, 1, 0);
556   tab_hline (t, TAL_2, 0, 2, 1);
557   tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("Variable"));
558   tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Value"));
559   tab_text (t, 2, 0, TAB_LEFT | TAT_TITLE, _("Label"));
560
561   int y = 1;
562   for (size_t i = 0; i < n_vars; i++)
563     {
564       const struct val_labs *val_labs = var_get_value_labels (vars[i]);
565       size_t n_labels = val_labs_count (val_labs);
566       if (!n_labels)
567         continue;
568
569       tab_joint_text (t, 0, y, 0, y + (n_labels - 1), TAB_LEFT,
570                       var_get_name (vars[i]));
571
572       const struct val_lab **labels = val_labs_sorted (val_labs);
573       for (size_t j = 0; j < n_labels; j++)
574         {
575           const struct val_lab *vl = labels[j];
576
577           tab_value (t, 1, y, TAB_NONE, &vl->value, vars[i], NULL);
578           tab_text (t, 2, y, TAB_LEFT, val_lab_get_escaped_label (vl));
579           y++;
580         }
581       free (labels);
582     }
583   tab_submit (t);
584 }
585 \f
586 static bool
587 is_at_name (const char *name)
588 {
589   return name[0] == '@' || (name[0] == '$' && name[1] == '@');
590 }
591
592 static size_t
593 count_attributes (const struct attrset *set, int flags)
594 {
595   struct attrset_iterator i;
596   struct attribute *attr;
597   size_t n_attrs;
598
599   n_attrs = 0;
600   for (attr = attrset_first (set, &i); attr != NULL;
601        attr = attrset_next (set, &i))
602     if (flags & DF_AT_ATTRIBUTES || !is_at_name (attribute_get_name (attr)))
603       n_attrs += attribute_get_n_values (attr);
604   return n_attrs;
605 }
606
607 static int
608 display_attrset (const char *name, const struct attrset *set, int flags,
609                  struct tab_table *t, int y)
610 {
611   size_t n_total = count_attributes (set, flags);
612   if (!n_total)
613     return y;
614
615   tab_joint_text (t, 0, y, 0, y + (n_total - 1), TAB_LEFT, name);
616
617   size_t n_attrs = attrset_count (set);
618   struct attribute **attrs = attrset_sorted (set);
619   for (size_t i = 0; i < n_attrs; i++)
620     {
621       const struct attribute *attr = attrs[i];
622       const char *name = attribute_get_name (attr);
623
624       if (!(flags & DF_AT_ATTRIBUTES) && is_at_name (name))
625         continue;
626
627       size_t n_values = attribute_get_n_values (attr);
628       for (size_t j = 0; j < n_values; j++)
629         {
630           if (n_values > 1)
631             tab_text_format (t, 1, y, TAB_LEFT, "%s[%zu]", name, j + 1);
632           else
633             tab_text (t, 1, y, TAB_LEFT, name);
634           tab_text (t, 2, y, TAB_LEFT, attribute_get_value (attr, j));
635           y++;
636         }
637     }
638   free (attrs);
639
640   return y;
641 }
642
643 static void
644 display_attributes (const struct attrset *dict_attrset,
645                     const struct variable **vars, size_t n_vars, int flags)
646 {
647   size_t n_attributes = count_attributes (dict_attrset, flags);
648   for (size_t i = 0; i < n_vars; i++)
649     n_attributes += count_attributes (var_get_attributes (vars[i]), flags);
650   if (!n_attributes)
651     return;
652
653   struct tab_table *t = tab_create (3, n_attributes + 1);
654   tab_title (t, "%s", _("Variable and Dataset Attributes"));
655   tab_headers (t, 0, 0, 1, 0);
656   tab_hline (t, TAL_2, 0, 2, 1);
657   tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("Variable"));
658   tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Name"));
659   tab_text (t, 2, 0, TAB_LEFT | TAT_TITLE, _("Value"));
660
661   int y = display_attrset (_("(dataset)"), dict_attrset, flags, t, 1);
662   for (size_t i = 0; i < n_vars; i++)
663     y = display_attrset (var_get_name (vars[i]), var_get_attributes (vars[i]),
664                          flags, t, y);
665
666   tab_submit (t);
667 }
668
669 /* Display a list of vectors.  If SORTED is nonzero then they are
670    sorted alphabetically. */
671 static void
672 display_vectors (const struct dictionary *dict, int sorted)
673 {
674   const struct vector **vl;
675   int i;
676   struct tab_table *t;
677   size_t nvec;
678   size_t nrow;
679   size_t row;
680
681   nvec = dict_get_vector_cnt (dict);
682   if (nvec == 0)
683     {
684       msg (SW, _("No vectors defined."));
685       return;
686     }
687
688   vl = xnmalloc (nvec, sizeof *vl);
689   nrow = 0;
690   for (i = 0; i < nvec; i++)
691     {
692       vl[i] = dict_get_vector (dict, i);
693       nrow += vector_get_var_cnt (vl[i]);
694     }
695   if (sorted)
696     qsort (vl, nvec, sizeof *vl, compare_vector_ptrs_by_name);
697
698   t = tab_create (4, nrow + 1);
699   tab_headers (t, 0, 0, 1, 0);
700   tab_box (t, TAL_1, TAL_1, -1, -1, 0, 0, 3, nrow);
701   tab_box (t, -1, -1, -1, TAL_1, 0, 0, 3, nrow);
702   tab_hline (t, TAL_2, 0, 3, 1);
703   tab_text (t, 0, 0, TAT_TITLE | TAB_LEFT, _("Vector"));
704   tab_text (t, 1, 0, TAT_TITLE | TAB_LEFT, _("Position"));
705   tab_text (t, 2, 0, TAT_TITLE | TAB_LEFT, _("Variable"));
706   tab_text (t, 3, 0, TAT_TITLE | TAB_LEFT, _("Print Format"));
707
708   row = 1;
709   for (i = 0; i < nvec; i++)
710     {
711       const struct vector *vec = vl[i];
712       size_t j;
713
714       tab_joint_text (t, 0, row, 0, row + vector_get_var_cnt (vec) - 1,
715                       TAB_LEFT, vector_get_name (vl[i]));
716
717       for (j = 0; j < vector_get_var_cnt (vec); j++)
718         {
719           struct variable *var = vector_get_var (vec, j);
720           char fmt_string[FMT_STRING_LEN_MAX + 1];
721           fmt_to_string (var_get_print_format (var), fmt_string);
722
723           tab_text_format (t, 1, row, TAB_RIGHT, "%zu", j + 1);
724           tab_text (t, 2, row, TAB_LEFT, var_get_name (var));
725           tab_text (t, 3, row, TAB_LEFT, fmt_string);
726           row++;
727         }
728       tab_hline (t, TAL_1, 0, 3, row);
729     }
730
731   tab_submit (t);
732
733   free (vl);
734 }
735 \f
736 /* Encoding analysis. */
737
738 static const char *encoding_names[] = {
739   /* These encodings are from http://encoding.spec.whatwg.org/, as retrieved
740      February 2014.  Encodings not supported by glibc and encodings relevant
741      only to HTML have been removed. */
742   "utf-8",
743   "windows-1252",
744   "iso-8859-2",
745   "iso-8859-3",
746   "iso-8859-4",
747   "iso-8859-5",
748   "iso-8859-6",
749   "iso-8859-7",
750   "iso-8859-8",
751   "iso-8859-10",
752   "iso-8859-13",
753   "iso-8859-14",
754   "iso-8859-16",
755   "macintosh",
756   "windows-874",
757   "windows-1250",
758   "windows-1251",
759   "windows-1253",
760   "windows-1254",
761   "windows-1255",
762   "windows-1256",
763   "windows-1257",
764   "windows-1258",
765   "koi8-r",
766   "koi8-u",
767   "ibm866",
768   "gb18030",
769   "big5",
770   "euc-jp",
771   "iso-2022-jp",
772   "shift_jis",
773   "euc-kr",
774
775   /* Added by user request. */
776   "ibm850",
777   "din_66003",
778 };
779 #define N_ENCODING_NAMES (sizeof encoding_names / sizeof *encoding_names)
780
781 struct encoding
782   {
783     uint64_t encodings;
784     char **utf8_strings;
785     unsigned int hash;
786   };
787
788 static char **
789 recode_strings (struct pool *pool,
790                 char **strings, bool *ids, size_t n,
791                 const char *encoding)
792 {
793   char **utf8_strings;
794   size_t i;
795
796   utf8_strings = pool_alloc (pool, n * sizeof *utf8_strings);
797   for (i = 0; i < n; i++)
798     {
799       struct substring utf8;
800       int error;
801
802       error = recode_pedantically ("UTF-8", encoding, ss_cstr (strings[i]),
803                                    pool, &utf8);
804       if (!error)
805         {
806           ss_rtrim (&utf8, ss_cstr (" "));
807           utf8.string[utf8.length] = '\0';
808
809           if (ids[i] && !id_is_plausible (utf8.string, false))
810             error = EINVAL;
811         }
812
813       if (error)
814         return NULL;
815
816       utf8_strings[i] = utf8.string;
817     }
818
819   return utf8_strings;
820 }
821
822 static struct encoding *
823 find_duplicate_encoding (struct encoding *encodings, size_t n_encodings,
824                          char **utf8_strings, size_t n_strings,
825                          unsigned int hash)
826 {
827   struct encoding *e;
828
829   for (e = encodings; e < &encodings[n_encodings]; e++)
830     {
831       int i;
832
833       if (e->hash != hash)
834         goto next_encoding;
835
836       for (i = 0; i < n_strings; i++)
837         if (strcmp (utf8_strings[i], e->utf8_strings[i]))
838           goto next_encoding;
839
840       return e;
841     next_encoding:;
842     }
843
844   return NULL;
845 }
846
847 static bool
848 all_equal (const struct encoding *encodings, size_t n_encodings,
849            size_t string_idx)
850 {
851   const char *s0;
852   size_t i;
853
854   s0 = encodings[0].utf8_strings[string_idx];
855   for (i = 1; i < n_encodings; i++)
856     if (strcmp (s0, encodings[i].utf8_strings[string_idx]))
857       return false;
858
859   return true;
860 }
861
862 static int
863 equal_prefix (const struct encoding *encodings, size_t n_encodings,
864               size_t string_idx)
865 {
866   const char *s0;
867   size_t prefix;
868   size_t i;
869
870   s0 = encodings[0].utf8_strings[string_idx];
871   prefix = strlen (s0);
872   for (i = 1; i < n_encodings; i++)
873     {
874       const char *si = encodings[i].utf8_strings[string_idx];
875       size_t j;
876
877       for (j = 0; j < prefix; j++)
878         if (s0[j] != si[j])
879           {
880             prefix = j;
881             if (!prefix)
882               return 0;
883             break;
884           }
885     }
886
887   while (prefix > 0 && s0[prefix - 1] != ' ')
888     prefix--;
889   return prefix;
890 }
891
892 static int
893 equal_suffix (const struct encoding *encodings, size_t n_encodings,
894               size_t string_idx)
895 {
896   const char *s0;
897   size_t s0_len;
898   size_t suffix;
899   size_t i;
900
901   s0 = encodings[0].utf8_strings[string_idx];
902   s0_len = strlen (s0);
903   suffix = s0_len;
904   for (i = 1; i < n_encodings; i++)
905     {
906       const char *si = encodings[i].utf8_strings[string_idx];
907       size_t si_len = strlen (si);
908       size_t j;
909
910       if (si_len < suffix)
911         suffix = si_len;
912       for (j = 0; j < suffix; j++)
913         if (s0[s0_len - j - 1] != si[si_len - j - 1])
914           {
915             suffix = j;
916             if (!suffix)
917               return 0;
918             break;
919           }
920     }
921
922   while (suffix > 0 && s0[s0_len - suffix] != ' ')
923     suffix--;
924   return suffix;
925 }
926
927 static void
928 report_encodings (const struct file_handle *h, struct pool *pool,
929                   char **titles, bool *ids, char **strings, size_t n_strings)
930 {
931   struct encoding encodings[N_ENCODING_NAMES];
932   size_t n_encodings, n_unique_strings;
933   size_t i, j;
934   struct tab_table *t;
935   size_t row;
936
937   n_encodings = 0;
938   for (i = 0; i < N_ENCODING_NAMES; i++)
939     {
940       char **utf8_strings;
941       struct encoding *e;
942       unsigned int hash;
943
944       utf8_strings = recode_strings (pool, strings, ids, n_strings,
945                                      encoding_names[i]);
946       if (!utf8_strings)
947         continue;
948
949       /* Hash utf8_strings. */
950       hash = 0;
951       for (j = 0; j < n_strings; j++)
952         hash = hash_string (utf8_strings[j], hash);
953
954       /* If there's a duplicate encoding, just mark it. */
955       e = find_duplicate_encoding (encodings, n_encodings,
956                                    utf8_strings, n_strings, hash);
957       if (e)
958         {
959           e->encodings |= UINT64_C (1) << i;
960           continue;
961         }
962
963       e = &encodings[n_encodings++];
964       e->encodings = UINT64_C (1) << i;
965       e->utf8_strings = utf8_strings;
966       e->hash = hash;
967     }
968   if (!n_encodings)
969     {
970       msg (SW, _("No valid encodings found."));
971       return;
972     }
973
974   t = tab_create (2, n_encodings + 1);
975   tab_title (t, _("Usable encodings for %s."), fh_get_name (h));
976   tab_caption (t, _("Encodings that can successfully read %s (by specifying "
977                     "the encoding name on the GET command's ENCODING "
978                     "subcommand).  Encodings that yield identical text are "
979                     "listed together."), fh_get_name (h));
980   tab_headers (t, 1, 0, 1, 0);
981   tab_box (t, TAL_1, TAL_1, -1, -1, 0, 0, 1, n_encodings);
982   tab_hline (t, TAL_1, 0, 1, 1);
983   tab_text (t, 0, 0, TAB_RIGHT, "#");
984   tab_text (t, 1, 0, TAB_LEFT, _("Encodings"));
985   for (i = 0; i < n_encodings; i++)
986     {
987       struct string s;
988
989       ds_init_empty (&s);
990       for (j = 0; j < 64; j++)
991         if (encodings[i].encodings & (UINT64_C (1) << j))
992           ds_put_format (&s, "%s, ", encoding_names[j]);
993       ds_chomp (&s, ss_cstr (", "));
994
995       tab_text_format (t, 0, i + 1, TAB_RIGHT, "%zu", i + 1);
996       tab_text (t, 1, i + 1, TAB_LEFT, ds_cstr (&s));
997       ds_destroy (&s);
998     }
999   tab_submit (t);
1000
1001   n_unique_strings = 0;
1002   for (i = 0; i < n_strings; i++)
1003     if (!all_equal (encodings, n_encodings, i))
1004       n_unique_strings++;
1005   if (!n_unique_strings)
1006     return;
1007
1008   t = tab_create (3, (n_encodings * n_unique_strings) + 1);
1009   tab_title (t, _("%s encoded text strings."), fh_get_name (h));
1010   tab_caption (t, _("Text strings in the file dictionary that the previously "
1011                     "listed encodings interpret differently, along with the "
1012                     "interpretations."));
1013   tab_headers (t, 1, 0, 1, 0);
1014   tab_box (t, TAL_1, TAL_1, -1, -1, 0, 0, 2, n_encodings * n_unique_strings);
1015   tab_hline (t, TAL_1, 0, 2, 1);
1016
1017   tab_text (t, 0, 0, TAB_LEFT, _("Purpose"));
1018   tab_text (t, 1, 0, TAB_RIGHT, "#");
1019   tab_text (t, 2, 0, TAB_LEFT, _("Text"));
1020
1021   row = 1;
1022   for (i = 0; i < n_strings; i++)
1023     if (!all_equal (encodings, n_encodings, i))
1024       {
1025         int prefix = equal_prefix (encodings, n_encodings, i);
1026         int suffix = equal_suffix (encodings, n_encodings, i);
1027
1028         tab_joint_text (t, 0, row, 0, row + n_encodings - 1,
1029                         TAB_LEFT, titles[i]);
1030         tab_hline (t, TAL_1, 0, 2, row);
1031         for (j = 0; j < n_encodings; j++)
1032           {
1033             const char *s = encodings[j].utf8_strings[i] + prefix;
1034
1035             tab_text_format (t, 1, row, TAB_RIGHT, "%zu", j + 1);
1036             if (prefix || suffix)
1037               {
1038                 size_t len = strlen (s) - suffix;
1039                 struct string entry;
1040
1041                 ds_init_empty (&entry);
1042                 if (prefix)
1043                   ds_put_cstr (&entry, "...");
1044                 ds_put_substring (&entry, ss_buffer (s, len));
1045                 if (suffix)
1046                   ds_put_cstr (&entry, "...");
1047                 tab_text (t, 2, row, TAB_LEFT, ds_cstr (&entry));
1048               }
1049             else
1050               tab_text (t, 2, row, TAB_LEFT, s);
1051             row++;
1052           }
1053       }
1054   tab_submit (t);
1055 }