dictionary.c: Remove the var_resized and var_display_width_changed callbacks
[pspp] / src / data / variable.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include "data/variable.h"
20
21 #include <stdlib.h>
22
23 #include "data/attributes.h"
24 #include "data/data-out.h"
25 #include "data/dictionary.h"
26 #include "data/format.h"
27 #include "data/identifier.h"
28 #include "data/missing-values.h"
29 #include "data/settings.h"
30 #include "data/value-labels.h"
31 #include "data/vardict.h"
32 #include "libpspp/assertion.h"
33 #include "libpspp/compiler.h"
34 #include "libpspp/hash-functions.h"
35 #include "libpspp/i18n.h"
36 #include "libpspp/message.h"
37 #include "libpspp/misc.h"
38 #include "libpspp/str.h"
39
40 #include "gl/minmax.h"
41 #include "gl/xalloc.h"
42
43 #include "gettext.h"
44 #define _(msgid) gettext (msgid)
45
46 /* A variable. */
47 struct variable
48   {
49     /* Dictionary information. */
50     char *name;                 /* Variable name.  Mixed case. */
51     int width;                  /* 0 for numeric, otherwise string width. */
52     struct missing_values miss; /* Missing values. */
53     struct fmt_spec print;      /* Default format for PRINT. */
54     struct fmt_spec write;      /* Default format for WRITE. */
55     struct val_labs *val_labs;  /* Value labels. */
56     char *label;                /* Variable label. */
57     struct string name_and_label; /* The name and label in the same string */
58
59     /* GUI information. */
60     enum measure measure;       /* Nominal, ordinal, or continuous. */
61     int display_width;          /* Width of data editor column. */
62     enum alignment alignment;   /* Alignment of data in GUI. */
63
64     /* Case information. */
65     bool leave;                 /* Leave value from case to case? */
66
67     /* Data for use by containing dictionary. */
68     struct vardict_info *vardict;
69
70     /* Used only for system and portable file input and output.
71        See short-names.h. */
72     char **short_names;
73     size_t short_name_cnt;
74
75     /* Custom attributes. */
76     struct attrset attributes;
77   };
78 \f
79
80 static bool var_set_label_quiet (struct variable *v, const char *label, bool issue_warning);
81 static void var_set_name_quiet (struct variable *v, const char *name);
82
83 /* Creates and returns a new variable with the given NAME and
84    WIDTH and other fields initialized to default values.  The
85    variable is not added to a dictionary; for that, use
86    dict_create_var instead. */
87 struct variable *
88 var_create (const char *name, int width)
89 {
90   struct variable *v;
91   enum val_type type;
92
93   assert (width >= 0 && width <= MAX_STRING);
94
95   v = xzalloc (sizeof *v);
96   var_set_name_quiet (v, name);
97   v->width = width;
98   mv_init (&v->miss, width);
99   v->leave = var_must_leave (v);
100   type = val_type_from_width (width);
101   v->alignment = var_default_alignment (type);
102   v->measure = var_default_measure (type);
103   v->display_width = var_default_display_width (width);
104   v->print = v->write = var_default_formats (width);
105   attrset_init (&v->attributes);
106   ds_init_empty (&v->name_and_label);
107
108   return v;
109 }
110
111 /* Destroys variable V.
112    V must not belong to a dictionary.  If it does, use
113    dict_delete_var instead. */
114 void
115 var_destroy (struct variable *v)
116 {
117   if (v != NULL)
118     {
119       assert (!var_has_vardict (v));
120       mv_destroy (&v->miss);
121       var_clear_short_names (v);
122       val_labs_destroy (v->val_labs);
123       var_set_label_quiet (v, NULL, false);
124       attrset_destroy (var_get_attributes (v));
125       free (v->name);
126       ds_destroy (&v->name_and_label);
127       free (v);
128     }
129 }
130 \f
131 /* Variable names. */
132
133 /* Return variable V's name, as a UTF-8 encoded string. */
134 const char *
135 var_get_name (const struct variable *v)
136 {
137   return v->name;
138 }
139
140
141
142 /* Sets V's name to NAME, a UTF-8 encoded string.
143    Do not use this function for a variable in a dictionary.  Use
144    dict_rename_var instead. */
145 static void
146 var_set_name_quiet (struct variable *v, const char *name)
147 {
148   assert (!var_has_vardict (v));
149   assert (id_is_plausible (name, false));
150
151   free (v->name);
152   v->name = xstrdup (name);
153   ds_destroy (&v->name_and_label);
154   ds_init_empty (&v->name_and_label);
155 }
156
157 /* Sets V's name to NAME, a UTF-8 encoded string.
158    Do not use this function for a variable in a dictionary.  Use
159    dict_rename_var instead. */
160 void
161 var_set_name (struct variable *v, const char *name)
162 {
163   struct variable *ov = var_clone (v);
164   var_set_name_quiet (v, name);
165   dict_var_changed (v, VAR_TRAIT_NAME, ov);
166 }
167
168 /* Returns VAR's dictionary class. */
169 enum dict_class
170 var_get_dict_class (const struct variable *var)
171 {
172   return dict_class_from_id (var->name);
173 }
174
175 /* A hsh_compare_func that orders variables A and B by their
176    names. */
177 int
178 compare_vars_by_name (const void *a_, const void *b_, const void *aux UNUSED)
179 {
180   const struct variable *a = a_;
181   const struct variable *b = b_;
182
183   return utf8_strcasecmp (a->name, b->name);
184 }
185
186 /* A hsh_hash_func that hashes variable V based on its name. */
187 unsigned
188 hash_var_by_name (const void *v_, const void *aux UNUSED)
189 {
190   const struct variable *v = v_;
191
192   return utf8_hash_case_string (v->name, 0);
193 }
194
195 /* A hsh_compare_func that orders pointers to variables A and B
196    by their names. */
197 int
198 compare_var_ptrs_by_name (const void *a_, const void *b_,
199                           const void *aux UNUSED)
200 {
201   struct variable *const *a = a_;
202   struct variable *const *b = b_;
203
204   return utf8_strcasecmp (var_get_name (*a), var_get_name (*b));
205 }
206
207 /* A hsh_compare_func that orders pointers to variables A and B
208    by their dictionary indexes. */
209 int
210 compare_var_ptrs_by_dict_index (const void *a_, const void *b_,
211                                 const void *aux UNUSED)
212 {
213   struct variable *const *a = a_;
214   struct variable *const *b = b_;
215   size_t a_index = var_get_dict_index (*a);
216   size_t b_index = var_get_dict_index (*b);
217
218   return a_index < b_index ? -1 : a_index > b_index;
219 }
220
221 /* A hsh_hash_func that hashes pointer to variable V based on its
222    name. */
223 unsigned
224 hash_var_ptr_by_name (const void *v_, const void *aux UNUSED)
225 {
226   struct variable *const *v = v_;
227
228   return utf8_hash_case_string (var_get_name (*v), 0);
229 }
230 \f
231 /* Returns the type of variable V. */
232 enum val_type
233 var_get_type (const struct variable *v)
234 {
235   return val_type_from_width (v->width);
236 }
237
238 /* Returns the width of variable V. */
239 int
240 var_get_width (const struct variable *v)
241 {
242   return v->width;
243 }
244
245 /* Changes the width of V to NEW_WIDTH.
246    This function should be used cautiously. */
247 void
248 var_set_width (struct variable *v, int new_width)
249 {
250   struct variable *ov;
251   const int old_width = v->width;
252
253   if (old_width == new_width)
254     return;
255
256   ov = var_clone (v);
257
258   if (mv_is_resizable (&v->miss, new_width))
259     mv_resize (&v->miss, new_width);
260   else
261     {
262       mv_destroy (&v->miss);
263       mv_init (&v->miss, new_width);
264     }
265
266   if (v->val_labs != NULL)
267     {
268       if (val_labs_can_set_width (v->val_labs, new_width))
269         val_labs_set_width (v->val_labs, new_width);
270       else
271         {
272           val_labs_destroy (v->val_labs);
273           v->val_labs = NULL;
274         }
275     }
276
277   fmt_resize (&v->print, new_width);
278   fmt_resize (&v->write, new_width);
279
280   v->width = new_width;
281   dict_var_changed (v, VAR_TRAIT_WIDTH, ov);
282 }
283
284 /* Returns true if variable V is numeric, false otherwise. */
285 bool
286 var_is_numeric (const struct variable *v)
287 {
288   return var_get_type (v) == VAL_NUMERIC;
289 }
290
291 /* Returns true if variable V is a string variable, false
292    otherwise. */
293 bool
294 var_is_alpha (const struct variable *v)
295 {
296   return var_get_type (v) == VAL_STRING;
297 }
298 \f
299 /* Returns variable V's missing values. */
300 const struct missing_values *
301 var_get_missing_values (const struct variable *v)
302 {
303   return &v->miss;
304 }
305
306 /* Sets variable V's missing values to MISS, which must be of V's
307    width or at least resizable to V's width.
308    If MISS is null, then V's missing values, if any, are
309    cleared. */
310 static void
311 var_set_missing_values_quiet (struct variable *v, const struct missing_values *miss)
312 {
313   if (miss != NULL)
314     {
315       assert (mv_is_resizable (miss, v->width));
316       mv_destroy (&v->miss);
317       mv_copy (&v->miss, miss);
318       mv_resize (&v->miss, v->width);
319     }
320   else
321     mv_clear (&v->miss);
322 }
323
324 /* Sets variable V's missing values to MISS, which must be of V's
325    width or at least resizable to V's width.
326    If MISS is null, then V's missing values, if any, are
327    cleared. */
328 void
329 var_set_missing_values (struct variable *v, const struct missing_values *miss)
330 {
331   struct variable *ov = var_clone (v);
332   var_set_missing_values_quiet (v, miss);
333   dict_var_changed (v, VAR_TRAIT_MISSING_VALUES, ov);
334 }
335
336 /* Sets variable V to have no user-missing values. */
337 void
338 var_clear_missing_values (struct variable *v)
339 {
340   var_set_missing_values (v, NULL);
341 }
342
343 /* Returns true if V has any user-missing values,
344    false otherwise. */
345 bool
346 var_has_missing_values (const struct variable *v)
347 {
348   return !mv_is_empty (&v->miss);
349 }
350
351 /* Returns true if VALUE is in the given CLASS of missing values
352    in V, false otherwise. */
353 bool
354 var_is_value_missing (const struct variable *v, const union value *value,
355                       enum mv_class class)
356 {
357   return mv_is_value_missing (&v->miss, value, class);
358 }
359
360 /* Returns true if D is in the given CLASS of missing values in
361    V, false otherwise.
362    V must be a numeric variable. */
363 bool
364 var_is_num_missing (const struct variable *v, double d, enum mv_class class)
365 {
366   return mv_is_num_missing (&v->miss, d, class);
367 }
368
369 /* Returns true if S[] is a missing value for V, false otherwise.
370    S[] must contain exactly as many characters as V's width.
371    V must be a string variable. */
372 bool
373 var_is_str_missing (const struct variable *v, const uint8_t s[],
374                     enum mv_class class)
375 {
376   return mv_is_str_missing (&v->miss, s, class);
377 }
378 \f
379 /* Returns variable V's value labels,
380    possibly a null pointer if it has none. */
381 const struct val_labs *
382 var_get_value_labels (const struct variable *v)
383 {
384   return v->val_labs;
385 }
386
387 /* Returns true if variable V has at least one value label. */
388 bool
389 var_has_value_labels (const struct variable *v)
390 {
391   return val_labs_count (v->val_labs) > 0;
392 }
393
394 /* Sets variable V's value labels to a copy of VLS,
395    which must have a width equal to V's width or one that can be
396    changed to V's width.
397    If VLS is null, then V's value labels, if any, are removed. */
398 static void
399 var_set_value_labels_quiet (struct variable *v, const struct val_labs *vls)
400 {
401   val_labs_destroy (v->val_labs);
402   v->val_labs = NULL;
403
404   if (vls != NULL)
405     {
406       assert (val_labs_can_set_width (vls, v->width));
407       v->val_labs = val_labs_clone (vls);
408       val_labs_set_width (v->val_labs, v->width);
409     }
410 }
411
412
413 /* Sets variable V's value labels to a copy of VLS,
414    which must have a width equal to V's width or one that can be
415    changed to V's width.
416    If VLS is null, then V's value labels, if any, are removed. */
417 void
418 var_set_value_labels (struct variable *v, const struct val_labs *vls)
419 {
420   struct variable *ov = var_clone (v);
421   var_set_value_labels_quiet (v, vls);
422   dict_var_changed (v, VAR_TRAIT_LABEL, ov);  
423 }
424
425
426 /* Makes sure that V has a set of value labels,
427    by assigning one to it if necessary. */
428 static void
429 alloc_value_labels (struct variable *v)
430 {
431   if (v->val_labs == NULL)
432     v->val_labs = val_labs_create (v->width);
433 }
434
435 /* Attempts to add a value label with the given VALUE and UTF-8 encoded LABEL
436    to V.  Returns true if successful, false otherwise (probably due to an
437    existing label).
438
439    In LABEL, the two-byte sequence "\\n" is interpreted as a new-line. */
440 bool
441 var_add_value_label (struct variable *v,
442                      const union value *value, const char *label)
443 {
444   alloc_value_labels (v);
445   return val_labs_add (v->val_labs, value, label);
446 }
447
448 /* Adds or replaces a value label with the given VALUE and UTF-8 encoded LABEL
449    to V.
450
451    In LABEL, the two-byte sequence "\\n" is interpreted as a new-line. */
452 void
453 var_replace_value_label (struct variable *v,
454                          const union value *value, const char *label)
455 {
456   alloc_value_labels (v);
457   val_labs_replace (v->val_labs, value, label);
458 }
459
460 /* Removes V's value labels, if any. */
461 void
462 var_clear_value_labels (struct variable *v)
463 {
464   var_set_value_labels (v, NULL);
465 }
466
467 /* Returns the label associated with VALUE for variable V, as a UTF-8 string in
468    a format suitable for output, or a null pointer if none. */
469 const char *
470 var_lookup_value_label (const struct variable *v, const union value *value)
471 {
472   return val_labs_find (v->val_labs, value);
473 }
474
475 /*
476    Append to STR the string representation of VALUE for variable V.
477    STR must be a pointer to an initialised struct string.
478 */
479 static void
480 append_value (const struct variable *v, const union value *value,
481               struct string *str)
482 {
483   char *s = data_out (value, var_get_encoding (v), &v->print);
484   ds_put_cstr (str, s);
485   free (s);
486 }
487
488 /* Append STR with a string representing VALUE for variable V.
489    That is, if VALUE has a label, append that label,
490    otherwise format VALUE and append the formatted string.
491    STR must be a pointer to an initialised struct string.
492 */
493 void
494 var_append_value_name (const struct variable *v, const union value *value,
495                        struct string *str)
496 {
497   enum settings_value_style style = settings_get_value_style ();
498   const char *name = var_lookup_value_label (v, value);
499
500   switch (style)
501     {
502     case SETTINGS_VAL_STYLE_VALUES:
503       append_value (v, value, str);
504       break;
505       
506     case SETTINGS_VAL_STYLE_LABELS:
507       if (name == NULL)
508         append_value (v, value, str);
509       else
510         ds_put_cstr (str, name);
511       break;
512
513     case SETTINGS_VAL_STYLE_BOTH:
514     default:
515       append_value (v, value, str);
516       if (name != NULL)
517         {
518           ds_put_cstr (str, " (");
519           ds_put_cstr (str, name);
520           ds_put_cstr (str, ")");
521         }
522       break;
523     };
524 }
525 \f
526 /* Print and write formats. */
527
528 /* Returns V's print format specification. */
529 const struct fmt_spec *
530 var_get_print_format (const struct variable *v)
531 {
532   return &v->print;
533 }
534
535 /* Sets V's print format specification to PRINT, which must be a
536    valid format specification for a variable of V's width
537    (ordinarily an output format, but input formats are not
538    rejected). */
539 static void
540 var_set_print_format_quiet (struct variable *v, const struct fmt_spec *print)
541 {
542   if (!fmt_equal (&v->print, print))
543     {
544       assert (fmt_check_width_compat (print, v->width));
545       v->print = *print;
546     }
547 }
548
549 /* Sets V's print format specification to PRINT, which must be a
550    valid format specification for a variable of V's width
551    (ordinarily an output format, but input formats are not
552    rejected). */
553 void
554 var_set_print_format (struct variable *v, const struct fmt_spec *print)
555 {
556   struct variable *ov = var_clone (v);
557   var_set_print_format_quiet (v, print);
558   dict_var_changed (v, VAR_TRAIT_FORMAT, ov);
559 }
560
561 /* Returns V's write format specification. */
562 const struct fmt_spec *
563 var_get_write_format (const struct variable *v)
564 {
565   return &v->write;
566 }
567
568 /* Sets V's write format specification to WRITE, which must be a
569    valid format specification for a variable of V's width
570    (ordinarily an output format, but input formats are not
571    rejected). */
572 static void
573 var_set_write_format_quiet (struct variable *v, const struct fmt_spec *write)
574 {
575   if (!fmt_equal (&v->write, write))
576     {
577       assert (fmt_check_width_compat (write, v->width));
578       v->write = *write;
579     }
580 }
581
582 /* Sets V's write format specification to WRITE, which must be a
583    valid format specification for a variable of V's width
584    (ordinarily an output format, but input formats are not
585    rejected). */
586 void
587 var_set_write_format (struct variable *v, const struct fmt_spec *write)
588 {
589   struct variable *ov = var_clone (v);
590   var_set_write_format_quiet (v, write);
591   dict_var_changed (v, VAR_TRAIT_FORMAT, ov);
592 }
593
594
595 /* Sets V's print and write format specifications to FORMAT,
596    which must be a valid format specification for a variable of
597    V's width (ordinarily an output format, but input formats are
598    not rejected). */
599 void
600 var_set_both_formats (struct variable *v, const struct fmt_spec *format)
601 {
602   struct variable *ov = var_clone (v);
603   var_set_print_format_quiet (v, format);
604   var_set_write_format_quiet (v, format);
605   dict_var_changed (v, VAR_TRAIT_FORMAT, ov);
606 }
607
608 /* Returns the default print and write format for a variable of
609    the given TYPE, as set by var_create.  The return value can be
610    used to reset a variable's print and write formats to the
611    default. */
612 struct fmt_spec
613 var_default_formats (int width)
614 {
615   return (width == 0
616           ? fmt_for_output (FMT_F, 8, 2)
617           : fmt_for_output (FMT_A, width, 0));
618 }
619
620
621 \f
622
623 /* Update the combined name and label string if necessary */
624 static void
625 update_vl_string (const struct variable *v)
626 {
627   /* Cast away const! */
628   struct string *str = (struct string *) &v->name_and_label;
629
630   if (ds_is_empty (str))
631     {
632       if (v->label)
633         ds_put_format (str, _("%s (%s)"), v->label, v->name);
634       else
635         ds_put_cstr (str, v->name);
636     }
637 }
638
639
640 /* Return a string representing this variable, in the form most
641    appropriate from a human factors perspective, that is, its
642    variable label if it has one, otherwise its name. */
643 const char *
644 var_to_string (const struct variable *v)
645 {
646   enum settings_var_style style = settings_get_var_style ();
647
648   switch (style)
649   {
650     case SETTINGS_VAR_STYLE_NAMES:
651       return v->name;
652       break;
653     case SETTINGS_VAR_STYLE_LABELS:
654       return v->label != NULL ? v->label : v->name;
655       break;
656     case SETTINGS_VAR_STYLE_BOTH:
657       update_vl_string (v);
658       return ds_cstr (&v->name_and_label);
659       break;
660     default:
661       NOT_REACHED ();
662       break;
663   };
664 }
665
666 /* Returns V's variable label, or a null pointer if it has none. */
667 const char *
668 var_get_label (const struct variable *v)
669 {
670   return v->label;
671 }
672
673 /* Sets V's variable label to UTF-8 encoded string LABEL, stripping off leading
674    and trailing white space.  If LABEL is a null pointer or if LABEL is an
675    empty string (after stripping white space), then V's variable label (if any)
676    is removed.
677
678    Variable labels are limited to 255 bytes in V's encoding (as returned by
679    var_get_encoding()).  If LABEL fits within this limit, this function returns
680    true.  Otherwise, the variable label is set to a truncated value, this
681    function returns false and, if ISSUE_WARNING is true, issues a warning.  */
682 static bool
683 var_set_label_quiet (struct variable *v, const char *label, bool issue_warning)
684 {
685   bool truncated = false;
686
687   free (v->label);
688   v->label = NULL;
689
690   if (label != NULL && label[strspn (label, CC_SPACES)])
691     {
692       const char *dict_encoding = var_get_encoding (v);
693       struct substring s = ss_cstr (label);
694       size_t trunc_len;
695
696       if (dict_encoding != NULL)
697         {
698           enum { MAX_LABEL_LEN = 255 };
699
700           trunc_len = utf8_encoding_trunc_len (label, dict_encoding,
701                                                MAX_LABEL_LEN);
702           if (ss_length (s) > trunc_len)
703             {
704               if (issue_warning)
705                 msg (SW, _("Truncating variable label for variable `%s' to %d "
706                            "bytes."), var_get_name (v), MAX_LABEL_LEN);
707               ss_truncate (&s, trunc_len);
708               truncated = true;
709             }
710         }
711
712         v->label = ss_xstrdup (s);
713     }
714
715   ds_destroy (&v->name_and_label);
716   ds_init_empty (&v->name_and_label);
717
718   return truncated;
719 }
720
721
722
723 /* Sets V's variable label to UTF-8 encoded string LABEL, stripping off leading
724    and trailing white space.  If LABEL is a null pointer or if LABEL is an
725    empty string (after stripping white space), then V's variable label (if any)
726    is removed.
727
728    Variable labels are limited to 255 bytes in V's encoding (as returned by
729    var_get_encoding()).  If LABEL fits within this limit, this function returns
730    true.  Otherwise, the variable label is set to a truncated value, this
731    function returns false and, if ISSUE_WARNING is true, issues a warning.  */
732 bool
733 var_set_label (struct variable *v, const char *label, bool issue_warning)
734 {
735   struct variable *ov = var_clone (v);
736   bool truncated = var_set_label_quiet (v, label, issue_warning);
737
738   dict_var_changed (v, VAR_TRAIT_LABEL, ov);
739
740   return truncated;
741 }
742
743
744 /* Removes any variable label from V. */
745 void
746 var_clear_label (struct variable *v)
747 {
748   var_set_label (v, NULL, false);
749 }
750
751 /* Returns true if V has a variable V,
752    false otherwise. */
753 bool
754 var_has_label (const struct variable *v)
755 {
756   return v->label != NULL;
757 }
758 \f
759 /* Returns true if M is a valid variable measurement level,
760    false otherwise. */
761 bool
762 measure_is_valid (enum measure m)
763 {
764   return m == MEASURE_NOMINAL || m == MEASURE_ORDINAL || m == MEASURE_SCALE;
765 }
766
767 /* Returns a string version of measurement level M, for display to a user. */
768 const char *
769 measure_to_string (enum measure m)
770 {
771   switch (m)
772     {
773     case MEASURE_NOMINAL:
774       return _("Nominal");
775
776     case MEASURE_ORDINAL:
777       return _("Ordinal");
778
779     case MEASURE_SCALE:
780       return _("Scale");
781
782     default:
783       return "Invalid";
784     }
785 }
786
787 /* Returns V's measurement level. */
788 enum measure
789 var_get_measure (const struct variable *v)
790 {
791   return v->measure;
792 }
793
794 /* Sets V's measurement level to MEASURE. */
795 static void
796 var_set_measure_quiet (struct variable *v, enum measure measure)
797 {
798   assert (measure_is_valid (measure));
799   v->measure = measure;
800 }
801
802
803 /* Sets V's measurement level to MEASURE. */
804 void
805 var_set_measure (struct variable *v, enum measure measure)
806 {
807   struct variable *ov = var_clone (v);
808   var_set_measure_quiet (v, measure);
809   dict_var_changed (v, VAR_TRAIT_MEASURE, ov);
810 }
811
812
813 /* Returns the default measurement level for a variable of the
814    given TYPE, as set by var_create.  The return value can be
815    used to reset a variable's measurement level to the
816    default. */
817 enum measure
818 var_default_measure (enum val_type type)
819 {
820   return type == VAL_NUMERIC ? MEASURE_SCALE : MEASURE_NOMINAL;
821 }
822 \f
823 /* Returns V's display width, which applies only to GUIs. */
824 int
825 var_get_display_width (const struct variable *v)
826 {
827   return v->display_width;
828 }
829
830 /* Sets V's display width to DISPLAY_WIDTH. */
831 static void
832 var_set_display_width_quiet (struct variable *v, int new_width)
833 {
834   if (v->display_width != new_width)
835     {
836       v->display_width = new_width;
837     }
838 }
839
840 void
841 var_set_display_width (struct variable *v, int new_width)
842 {
843   struct variable *ov = var_clone (v);
844   var_set_display_width_quiet (v, new_width);
845   dict_var_changed (v, VAR_TRAIT_DISPLAY_WIDTH, ov);
846 }
847
848
849 /* Returns the default display width for a variable of the given
850    WIDTH, as set by var_create.  The return value can be used to
851    reset a variable's display width to the default. */
852 int
853 var_default_display_width (int width)
854 {
855   return width == 0 ? 8 : MIN (width, 32);
856 }
857 \f
858 /* Returns true if A is a valid alignment,
859    false otherwise. */
860 bool
861 alignment_is_valid (enum alignment a)
862 {
863   return a == ALIGN_LEFT || a == ALIGN_RIGHT || a == ALIGN_CENTRE;
864 }
865
866 /* Returns a string version of alignment A, for display to a user. */
867 const char *
868 alignment_to_string (enum alignment a)
869 {
870   switch (a)
871     {
872     case ALIGN_LEFT:
873       return _("Left");
874
875     case ALIGN_RIGHT:
876       return _("Right");
877
878     case ALIGN_CENTRE:
879       return _("Center");
880
881     default:
882       return "Invalid";
883     }
884 }
885
886 /* Returns V's display alignment, which applies only to GUIs. */
887 enum alignment
888 var_get_alignment (const struct variable *v)
889 {
890   return v->alignment;
891 }
892
893 /* Sets V's display alignment to ALIGNMENT. */
894 static void
895 var_set_alignment_quiet (struct variable *v, enum alignment alignment)
896 {
897   assert (alignment_is_valid (alignment));
898   v->alignment = alignment;
899 }
900
901 /* Sets V's display alignment to ALIGNMENT. */
902 void
903 var_set_alignment (struct variable *v, enum alignment alignment)
904 {
905   struct variable *ov = var_clone (v);
906   var_set_alignment_quiet (v, alignment);
907   dict_var_changed (v, VAR_TRAIT_ALIGNMENT, ov);
908 }
909
910
911 /* Returns the default display alignment for a variable of the
912    given TYPE, as set by var_create.  The return value can be
913    used to reset a variable's display alignment to the default. */
914 enum alignment
915 var_default_alignment (enum val_type type)
916 {
917   return type == VAL_NUMERIC ? ALIGN_RIGHT : ALIGN_LEFT;
918 }
919 \f
920 /* Whether variables' values should be preserved from case to
921    case. */
922
923 /* Returns true if variable V's value should be left from case to
924    case, instead of being reset to system-missing or blanks. */
925 bool
926 var_get_leave (const struct variable *v)
927 {
928   return v->leave;
929 }
930
931 /* Sets V's leave setting to LEAVE. */
932 static void
933 var_set_leave_quiet (struct variable *v, bool leave)
934 {
935   assert (leave || !var_must_leave (v));
936   v->leave = leave;
937 }
938
939
940 /* Sets V's leave setting to LEAVE. */
941 void
942 var_set_leave (struct variable *v, bool leave)
943 {
944   struct variable *ov = var_clone (v);
945   var_set_leave_quiet (v, leave);
946   dict_var_changed (v, VAR_TRAIT_LEAVE, ov);
947 }
948
949
950 /* Returns true if V must be left from case to case,
951    false if it can be set either way. */
952 bool
953 var_must_leave (const struct variable *v)
954 {
955   return var_get_dict_class (v) == DC_SCRATCH;
956 }
957 \f
958 /* Returns the number of short names stored in VAR.
959
960    Short names are used only for system and portable file input
961    and output.  They are upper-case only, not necessarily unique,
962    and limited to SHORT_NAME_LEN characters (plus a null
963    terminator).  Ordinarily a variable has at most one short
964    name, but very long string variables (longer than 255 bytes)
965    may have more.  A variable might not have any short name at
966    all if it hasn't been saved to or read from a system or
967    portable file. */
968 size_t
969 var_get_short_name_cnt (const struct variable *var) 
970 {
971   return var->short_name_cnt;
972 }
973
974 /* Returns VAR's short name with the given IDX, if it has one
975    with that index, or a null pointer otherwise.  Short names may
976    be sparse: even if IDX is less than the number of short names
977    in VAR, this function may return a null pointer. */
978 const char *
979 var_get_short_name (const struct variable *var, size_t idx)
980 {
981   return idx < var->short_name_cnt ? var->short_names[idx] : NULL;
982 }
983
984 /* Sets VAR's short name with the given IDX to the UTF-8 string SHORT_NAME.
985    The caller must already have checked that, in the dictionary encoding,
986    SHORT_NAME is no more than SHORT_NAME_LEN bytes long.  The new short name
987    will be converted to uppercase.
988
989    Specifying a null pointer for SHORT_NAME clears the specified short name. */
990 void
991 var_set_short_name (struct variable *var, size_t idx, const char *short_name)
992 {
993   struct variable *ov = var_clone (var);
994
995   assert (short_name == NULL || id_is_plausible (short_name, false));
996
997   /* Clear old short name numbered IDX, if any. */
998   if (idx < var->short_name_cnt) 
999     {
1000       free (var->short_names[idx]);
1001       var->short_names[idx] = NULL; 
1002     }
1003
1004   /* Install new short name for IDX. */
1005   if (short_name != NULL) 
1006     {
1007       if (idx >= var->short_name_cnt)
1008         {
1009           size_t old_cnt = var->short_name_cnt;
1010           size_t i;
1011           var->short_name_cnt = MAX (idx * 2, 1);
1012           var->short_names = xnrealloc (var->short_names, var->short_name_cnt,
1013                                         sizeof *var->short_names);
1014           for (i = old_cnt; i < var->short_name_cnt; i++)
1015             var->short_names[i] = NULL;
1016         }
1017       var->short_names[idx] = utf8_to_upper (short_name);
1018     }
1019
1020   dict_var_changed (var, VAR_TRAIT_NAME, ov);
1021 }
1022
1023 /* Clears V's short names. */
1024 void
1025 var_clear_short_names (struct variable *v)
1026 {
1027   size_t i;
1028
1029   for (i = 0; i < v->short_name_cnt; i++)
1030     free (v->short_names[i]);
1031   free (v->short_names);
1032   v->short_names = NULL;
1033   v->short_name_cnt = 0;
1034 }
1035 \f
1036 /* Relationship with dictionary. */
1037
1038 /* Returns V's index within its dictionary, the value
1039    for which "dict_get_var (dict, index)" will return V.
1040    V must be in a dictionary. */
1041 size_t
1042 var_get_dict_index (const struct variable *v)
1043 {
1044   assert (var_has_vardict (v));
1045   return vardict_get_dict_index (v->vardict);
1046 }
1047
1048 /* Returns V's index within the case represented by its
1049    dictionary, that is, the value for which "case_data_idx (case,
1050    index)" will return the data for V in that case.
1051    V must be in a dictionary. */
1052 size_t
1053 var_get_case_index (const struct variable *v)
1054 {
1055   assert (var_has_vardict (v));
1056   return vardict_get_case_index (v->vardict);
1057 }
1058 \f
1059 /* Returns variable V's attribute set.  The caller may examine or
1060    modify the attribute set, but must not destroy it.  Destroying
1061    V, or calling var_set_attributes() on V, will also destroy its
1062    attribute set. */
1063 struct attrset *
1064 var_get_attributes (const struct variable *v) 
1065 {
1066   return CONST_CAST (struct attrset *, &v->attributes);
1067 }
1068
1069 /* Replaces variable V's attributes set by a copy of ATTRS. */
1070 static void
1071 var_set_attributes_quiet (struct variable *v, const struct attrset *attrs) 
1072 {
1073   attrset_destroy (&v->attributes);
1074   attrset_clone (&v->attributes, attrs);
1075 }
1076
1077 /* Replaces variable V's attributes set by a copy of ATTRS. */
1078 void
1079 var_set_attributes (struct variable *v, const struct attrset *attrs) 
1080 {
1081   struct variable *ov = var_clone (v);
1082   var_set_attributes_quiet (v, attrs);
1083   dict_var_changed (v, VAR_TRAIT_ATTRIBUTES, ov);
1084 }
1085
1086
1087 /* Returns true if V has any custom attributes, false if it has none. */
1088 bool
1089 var_has_attributes (const struct variable *v)
1090 {
1091   return attrset_count (&v->attributes) > 0;
1092 }
1093 \f
1094
1095 /* Creates and returns a clone of OLD_VAR.  Most properties of
1096    the new variable are copied from OLD_VAR, except:
1097
1098     - The variable's short name is not copied, because there is
1099       no reason to give a new variable with potentially a new
1100       name the same short name.
1101
1102     - The new variable is not added to OLD_VAR's dictionary by
1103       default.  Use dict_clone_var, instead, to do that.
1104 */
1105 struct variable *
1106 var_clone (const struct variable *old_var)
1107 {
1108   struct variable *new_var = var_create (var_get_name (old_var),
1109                                          var_get_width (old_var));
1110
1111   var_set_missing_values_quiet (new_var, var_get_missing_values (old_var));
1112   var_set_print_format_quiet (new_var, var_get_print_format (old_var));
1113   var_set_write_format_quiet (new_var, var_get_write_format (old_var));
1114   var_set_value_labels_quiet (new_var, var_get_value_labels (old_var));
1115   var_set_label_quiet (new_var, var_get_label (old_var), false);
1116   var_set_measure_quiet (new_var, var_get_measure (old_var));
1117   var_set_display_width_quiet (new_var, var_get_display_width (old_var));
1118   var_set_alignment_quiet (new_var, var_get_alignment (old_var));
1119   var_set_leave_quiet (new_var, var_get_leave (old_var));
1120   var_set_attributes_quiet (new_var, var_get_attributes (old_var));
1121
1122   return new_var;
1123 }
1124
1125
1126
1127 /* Returns the encoding of values of variable VAR.  (This is actually a
1128    property of the dictionary.)  Returns null if no specific encoding has been
1129    set.  */
1130 const char *
1131 var_get_encoding (const struct variable *var)
1132 {
1133   return (var_has_vardict (var)
1134           ? dict_get_encoding (vardict_get_dictionary (var->vardict))
1135           : NULL);
1136 }
1137 \f
1138 /* Returns V's vardict structure. */
1139 struct vardict_info *
1140 var_get_vardict (const struct variable *v)
1141 {
1142   return CONST_CAST (struct vardict_info *, v->vardict);
1143 }
1144
1145 /* Sets V's vardict data to VARDICT. */
1146 void
1147 var_set_vardict (struct variable *v, struct vardict_info *vardict)
1148 {
1149   v->vardict = vardict;
1150 }
1151
1152 /* Returns true if V has vardict data. */
1153 bool
1154 var_has_vardict (const struct variable *v)
1155 {
1156   return v->vardict != NULL;
1157 }
1158
1159 /* Clears V's vardict data. */
1160 void
1161 var_clear_vardict (struct variable *v)
1162 {
1163   v->vardict = NULL;
1164 }