a0e608623290ff3b90fde776c5f21c64d4c665a6
[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                   gettext (measure_to_string (var_get_measure (v))));
470       if (flags & DF_ROLE)
471         tab_text (t, x++, y, TAB_LEFT,
472                   gettext (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                   gettext (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           char *s = mv_to_string (mv, var_get_encoding (v));
501           if (s)
502             {
503               tab_text (t, x, y, TAB_LEFT, s);
504               free (s);
505             }
506           x++;
507
508           assert (x == nc);
509         }
510     }
511
512   tab_submit (t);
513 }
514
515 static void
516 display_value_labels (const struct variable **vars, size_t n_vars)
517 {
518   size_t n_value_labels = 0;
519   for (size_t i = 0; i < n_vars; i++)
520     n_value_labels += val_labs_count (var_get_value_labels (vars[i]));
521   if (!n_value_labels)
522     return;
523
524   struct tab_table *t = tab_create (3, n_value_labels + 1);
525   tab_title (t, "%s", _("Value Labels"));
526   tab_headers (t, 0, 0, 1, 0);
527   tab_hline (t, TAL_2, 0, 2, 1);
528   tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("Variable"));
529   tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Value"));
530   tab_text (t, 2, 0, TAB_LEFT | TAT_TITLE, _("Label"));
531
532   int y = 1;
533   for (size_t i = 0; i < n_vars; i++)
534     {
535       const struct val_labs *val_labs = var_get_value_labels (vars[i]);
536       size_t n_labels = val_labs_count (val_labs);
537       if (!n_labels)
538         continue;
539
540       tab_joint_text (t, 0, y, 0, y + (n_labels - 1), TAB_LEFT,
541                       var_get_name (vars[i]));
542
543       const struct val_lab **labels = val_labs_sorted (val_labs);
544       for (size_t j = 0; j < n_labels; j++)
545         {
546           const struct val_lab *vl = labels[j];
547
548           tab_value (t, 1, y, TAB_NONE, &vl->value, vars[i], NULL);
549           tab_text (t, 2, y, TAB_LEFT, val_lab_get_escaped_label (vl));
550           y++;
551         }
552       free (labels);
553     }
554   tab_submit (t);
555 }
556 \f
557 static bool
558 is_at_name (const char *name)
559 {
560   return name[0] == '@' || (name[0] == '$' && name[1] == '@');
561 }
562
563 static size_t
564 count_attributes (const struct attrset *set, int flags)
565 {
566   struct attrset_iterator i;
567   struct attribute *attr;
568   size_t n_attrs;
569
570   n_attrs = 0;
571   for (attr = attrset_first (set, &i); attr != NULL;
572        attr = attrset_next (set, &i))
573     if (flags & DF_AT_ATTRIBUTES || !is_at_name (attribute_get_name (attr)))
574       n_attrs += attribute_get_n_values (attr);
575   return n_attrs;
576 }
577
578 static int
579 display_attrset (const char *name, const struct attrset *set, int flags,
580                  struct tab_table *t, int y)
581 {
582   size_t n_total = count_attributes (set, flags);
583   if (!n_total)
584     return y;
585
586   tab_joint_text (t, 0, y, 0, y + (n_total - 1), TAB_LEFT, name);
587
588   size_t n_attrs = attrset_count (set);
589   struct attribute **attrs = attrset_sorted (set);
590   for (size_t i = 0; i < n_attrs; i++)
591     {
592       const struct attribute *attr = attrs[i];
593       const char *name = attribute_get_name (attr);
594
595       if (!(flags & DF_AT_ATTRIBUTES) && is_at_name (name))
596         continue;
597
598       size_t n_values = attribute_get_n_values (attr);
599       for (size_t j = 0; j < n_values; j++)
600         {
601           if (n_values > 1)
602             tab_text_format (t, 1, y, TAB_LEFT, "%s[%zu]", name, j + 1);
603           else
604             tab_text (t, 1, y, TAB_LEFT, name);
605           tab_text (t, 2, y, TAB_LEFT, attribute_get_value (attr, j));
606           y++;
607         }
608     }
609   free (attrs);
610
611   return y;
612 }
613
614 static void
615 display_attributes (const struct attrset *dict_attrset,
616                     const struct variable **vars, size_t n_vars, int flags)
617 {
618   size_t n_attributes = count_attributes (dict_attrset, flags);
619   for (size_t i = 0; i < n_vars; i++)
620     n_attributes += count_attributes (var_get_attributes (vars[i]), flags);
621   if (!n_attributes)
622     return;
623
624   struct tab_table *t = tab_create (3, n_attributes + 1);
625   tab_title (t, "%s", _("Variable and Dataset Attributes"));
626   tab_headers (t, 0, 0, 1, 0);
627   tab_hline (t, TAL_2, 0, 2, 1);
628   tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("Variable"));
629   tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Name"));
630   tab_text (t, 2, 0, TAB_LEFT | TAT_TITLE, _("Value"));
631
632   int y = display_attrset (_("(dataset)"), dict_attrset, flags, t, 1);
633   for (size_t i = 0; i < n_vars; i++)
634     y = display_attrset (var_get_name (vars[i]), var_get_attributes (vars[i]),
635                          flags, t, y);
636
637   tab_submit (t);
638 }
639
640 /* Display a list of vectors.  If SORTED is nonzero then they are
641    sorted alphabetically. */
642 static void
643 display_vectors (const struct dictionary *dict, int sorted)
644 {
645   const struct vector **vl;
646   int i;
647   struct tab_table *t;
648   size_t nvec;
649   size_t nrow;
650   size_t row;
651
652   nvec = dict_get_vector_cnt (dict);
653   if (nvec == 0)
654     {
655       msg (SW, _("No vectors defined."));
656       return;
657     }
658
659   vl = xnmalloc (nvec, sizeof *vl);
660   nrow = 0;
661   for (i = 0; i < nvec; i++)
662     {
663       vl[i] = dict_get_vector (dict, i);
664       nrow += vector_get_var_cnt (vl[i]);
665     }
666   if (sorted)
667     qsort (vl, nvec, sizeof *vl, compare_vector_ptrs_by_name);
668
669   t = tab_create (4, nrow + 1);
670   tab_headers (t, 0, 0, 1, 0);
671   tab_box (t, TAL_1, TAL_1, -1, -1, 0, 0, 3, nrow);
672   tab_box (t, -1, -1, -1, TAL_1, 0, 0, 3, nrow);
673   tab_hline (t, TAL_2, 0, 3, 1);
674   tab_text (t, 0, 0, TAT_TITLE | TAB_LEFT, _("Vector"));
675   tab_text (t, 1, 0, TAT_TITLE | TAB_LEFT, _("Position"));
676   tab_text (t, 2, 0, TAT_TITLE | TAB_LEFT, _("Variable"));
677   tab_text (t, 3, 0, TAT_TITLE | TAB_LEFT, _("Print Format"));
678
679   row = 1;
680   for (i = 0; i < nvec; i++)
681     {
682       const struct vector *vec = vl[i];
683       size_t j;
684
685       tab_joint_text (t, 0, row, 0, row + vector_get_var_cnt (vec) - 1,
686                       TAB_LEFT, vector_get_name (vl[i]));
687
688       for (j = 0; j < vector_get_var_cnt (vec); j++)
689         {
690           struct variable *var = vector_get_var (vec, j);
691           char fmt_string[FMT_STRING_LEN_MAX + 1];
692           fmt_to_string (var_get_print_format (var), fmt_string);
693
694           tab_text_format (t, 1, row, TAB_RIGHT, "%zu", j + 1);
695           tab_text (t, 2, row, TAB_LEFT, var_get_name (var));
696           tab_text (t, 3, row, TAB_LEFT, fmt_string);
697           row++;
698         }
699       tab_hline (t, TAL_1, 0, 3, row);
700     }
701
702   tab_submit (t);
703
704   free (vl);
705 }
706 \f
707 /* Encoding analysis. */
708
709 static const char *encoding_names[] = {
710   /* These encodings are from http://encoding.spec.whatwg.org/, as retrieved
711      February 2014.  Encodings not supported by glibc and encodings relevant
712      only to HTML have been removed. */
713   "utf-8",
714   "windows-1252",
715   "iso-8859-2",
716   "iso-8859-3",
717   "iso-8859-4",
718   "iso-8859-5",
719   "iso-8859-6",
720   "iso-8859-7",
721   "iso-8859-8",
722   "iso-8859-10",
723   "iso-8859-13",
724   "iso-8859-14",
725   "iso-8859-16",
726   "macintosh",
727   "windows-874",
728   "windows-1250",
729   "windows-1251",
730   "windows-1253",
731   "windows-1254",
732   "windows-1255",
733   "windows-1256",
734   "windows-1257",
735   "windows-1258",
736   "koi8-r",
737   "koi8-u",
738   "ibm866",
739   "gb18030",
740   "big5",
741   "euc-jp",
742   "iso-2022-jp",
743   "shift_jis",
744   "euc-kr",
745
746   /* Added by user request. */
747   "ibm850",
748   "din_66003",
749 };
750 #define N_ENCODING_NAMES (sizeof encoding_names / sizeof *encoding_names)
751
752 struct encoding
753   {
754     uint64_t encodings;
755     char **utf8_strings;
756     unsigned int hash;
757   };
758
759 static char **
760 recode_strings (struct pool *pool,
761                 char **strings, bool *ids, size_t n,
762                 const char *encoding)
763 {
764   char **utf8_strings;
765   size_t i;
766
767   utf8_strings = pool_alloc (pool, n * sizeof *utf8_strings);
768   for (i = 0; i < n; i++)
769     {
770       struct substring utf8;
771       int error;
772
773       error = recode_pedantically ("UTF-8", encoding, ss_cstr (strings[i]),
774                                    pool, &utf8);
775       if (!error)
776         {
777           ss_rtrim (&utf8, ss_cstr (" "));
778           utf8.string[utf8.length] = '\0';
779
780           if (ids[i] && !id_is_plausible (utf8.string, false))
781             error = EINVAL;
782         }
783
784       if (error)
785         return NULL;
786
787       utf8_strings[i] = utf8.string;
788     }
789
790   return utf8_strings;
791 }
792
793 static struct encoding *
794 find_duplicate_encoding (struct encoding *encodings, size_t n_encodings,
795                          char **utf8_strings, size_t n_strings,
796                          unsigned int hash)
797 {
798   struct encoding *e;
799
800   for (e = encodings; e < &encodings[n_encodings]; e++)
801     {
802       int i;
803
804       if (e->hash != hash)
805         goto next_encoding;
806
807       for (i = 0; i < n_strings; i++)
808         if (strcmp (utf8_strings[i], e->utf8_strings[i]))
809           goto next_encoding;
810
811       return e;
812     next_encoding:;
813     }
814
815   return NULL;
816 }
817
818 static bool
819 all_equal (const struct encoding *encodings, size_t n_encodings,
820            size_t string_idx)
821 {
822   const char *s0;
823   size_t i;
824
825   s0 = encodings[0].utf8_strings[string_idx];
826   for (i = 1; i < n_encodings; i++)
827     if (strcmp (s0, encodings[i].utf8_strings[string_idx]))
828       return false;
829
830   return true;
831 }
832
833 static int
834 equal_prefix (const struct encoding *encodings, size_t n_encodings,
835               size_t string_idx)
836 {
837   const char *s0;
838   size_t prefix;
839   size_t i;
840
841   s0 = encodings[0].utf8_strings[string_idx];
842   prefix = strlen (s0);
843   for (i = 1; i < n_encodings; i++)
844     {
845       const char *si = encodings[i].utf8_strings[string_idx];
846       size_t j;
847
848       for (j = 0; j < prefix; j++)
849         if (s0[j] != si[j])
850           {
851             prefix = j;
852             if (!prefix)
853               return 0;
854             break;
855           }
856     }
857
858   while (prefix > 0 && s0[prefix - 1] != ' ')
859     prefix--;
860   return prefix;
861 }
862
863 static int
864 equal_suffix (const struct encoding *encodings, size_t n_encodings,
865               size_t string_idx)
866 {
867   const char *s0;
868   size_t s0_len;
869   size_t suffix;
870   size_t i;
871
872   s0 = encodings[0].utf8_strings[string_idx];
873   s0_len = strlen (s0);
874   suffix = s0_len;
875   for (i = 1; i < n_encodings; i++)
876     {
877       const char *si = encodings[i].utf8_strings[string_idx];
878       size_t si_len = strlen (si);
879       size_t j;
880
881       if (si_len < suffix)
882         suffix = si_len;
883       for (j = 0; j < suffix; j++)
884         if (s0[s0_len - j - 1] != si[si_len - j - 1])
885           {
886             suffix = j;
887             if (!suffix)
888               return 0;
889             break;
890           }
891     }
892
893   while (suffix > 0 && s0[s0_len - suffix] != ' ')
894     suffix--;
895   return suffix;
896 }
897
898 static void
899 report_encodings (const struct file_handle *h, struct pool *pool,
900                   char **titles, bool *ids, char **strings, size_t n_strings)
901 {
902   struct encoding encodings[N_ENCODING_NAMES];
903   size_t n_encodings, n_unique_strings;
904   size_t i, j;
905   struct tab_table *t;
906   size_t row;
907
908   n_encodings = 0;
909   for (i = 0; i < N_ENCODING_NAMES; i++)
910     {
911       char **utf8_strings;
912       struct encoding *e;
913       unsigned int hash;
914
915       utf8_strings = recode_strings (pool, strings, ids, n_strings,
916                                      encoding_names[i]);
917       if (!utf8_strings)
918         continue;
919
920       /* Hash utf8_strings. */
921       hash = 0;
922       for (j = 0; j < n_strings; j++)
923         hash = hash_string (utf8_strings[j], hash);
924
925       /* If there's a duplicate encoding, just mark it. */
926       e = find_duplicate_encoding (encodings, n_encodings,
927                                    utf8_strings, n_strings, hash);
928       if (e)
929         {
930           e->encodings |= UINT64_C (1) << i;
931           continue;
932         }
933
934       e = &encodings[n_encodings++];
935       e->encodings = UINT64_C (1) << i;
936       e->utf8_strings = utf8_strings;
937       e->hash = hash;
938     }
939   if (!n_encodings)
940     {
941       msg (SW, _("No valid encodings found."));
942       return;
943     }
944
945   t = tab_create (2, n_encodings + 1);
946   tab_title (t, _("Usable encodings for %s."), fh_get_name (h));
947   tab_caption (t, _("Encodings that can successfully read %s (by specifying "
948                     "the encoding name on the GET command's ENCODING "
949                     "subcommand).  Encodings that yield identical text are "
950                     "listed together."), fh_get_name (h));
951   tab_headers (t, 1, 0, 1, 0);
952   tab_box (t, TAL_1, TAL_1, -1, -1, 0, 0, 1, n_encodings);
953   tab_hline (t, TAL_1, 0, 1, 1);
954   tab_text (t, 0, 0, TAB_RIGHT, "#");
955   tab_text (t, 1, 0, TAB_LEFT, _("Encodings"));
956   for (i = 0; i < n_encodings; i++)
957     {
958       struct string s;
959
960       ds_init_empty (&s);
961       for (j = 0; j < 64; j++)
962         if (encodings[i].encodings & (UINT64_C (1) << j))
963           ds_put_format (&s, "%s, ", encoding_names[j]);
964       ds_chomp (&s, ss_cstr (", "));
965
966       tab_text_format (t, 0, i + 1, TAB_RIGHT, "%zu", i + 1);
967       tab_text (t, 1, i + 1, TAB_LEFT, ds_cstr (&s));
968       ds_destroy (&s);
969     }
970   tab_submit (t);
971
972   n_unique_strings = 0;
973   for (i = 0; i < n_strings; i++)
974     if (!all_equal (encodings, n_encodings, i))
975       n_unique_strings++;
976   if (!n_unique_strings)
977     return;
978
979   t = tab_create (3, (n_encodings * n_unique_strings) + 1);
980   tab_title (t, _("%s encoded text strings."), fh_get_name (h));
981   tab_caption (t, _("Text strings in the file dictionary that the previously "
982                     "listed encodings interpret differently, along with the "
983                     "interpretations."));
984   tab_headers (t, 1, 0, 1, 0);
985   tab_box (t, TAL_1, TAL_1, -1, -1, 0, 0, 2, n_encodings * n_unique_strings);
986   tab_hline (t, TAL_1, 0, 2, 1);
987
988   tab_text (t, 0, 0, TAB_LEFT, _("Purpose"));
989   tab_text (t, 1, 0, TAB_RIGHT, "#");
990   tab_text (t, 2, 0, TAB_LEFT, _("Text"));
991
992   row = 1;
993   for (i = 0; i < n_strings; i++)
994     if (!all_equal (encodings, n_encodings, i))
995       {
996         int prefix = equal_prefix (encodings, n_encodings, i);
997         int suffix = equal_suffix (encodings, n_encodings, i);
998
999         tab_joint_text (t, 0, row, 0, row + n_encodings - 1,
1000                         TAB_LEFT, titles[i]);
1001         tab_hline (t, TAL_1, 0, 2, row);
1002         for (j = 0; j < n_encodings; j++)
1003           {
1004             const char *s = encodings[j].utf8_strings[i] + prefix;
1005
1006             tab_text_format (t, 1, row, TAB_RIGHT, "%zu", j + 1);
1007             if (prefix || suffix)
1008               {
1009                 size_t len = strlen (s) - suffix;
1010                 struct string entry;
1011
1012                 ds_init_empty (&entry);
1013                 if (prefix)
1014                   ds_put_cstr (&entry, "...");
1015                 ds_put_substring (&entry, ss_buffer (s, len));
1016                 if (suffix)
1017                   ds_put_cstr (&entry, "...");
1018                 tab_text (t, 2, row, TAB_LEFT, ds_cstr (&entry));
1019               }
1020             else
1021               tab_text (t, 2, row, TAB_LEFT, s);
1022             row++;
1023           }
1024       }
1025   tab_submit (t);
1026 }