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