variable.c: (var_set_width) traits other than width may also be set
[pspp] / src / data / variable.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2009, 2010, 2011, 2012, 2013 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   unsigned int traits = 0;
253
254   if (old_width == new_width)
255     return;
256
257   ov = var_clone (v);
258
259   if (var_has_missing_values (v))
260     {
261       if (mv_is_resizable (&v->miss, new_width))
262         mv_resize (&v->miss, new_width);
263       else
264         {
265           mv_destroy (&v->miss);
266           mv_init (&v->miss, new_width);
267         }
268       traits |= VAR_TRAIT_MISSING_VALUES;
269     }
270
271   if (v->val_labs != NULL)
272     {
273       if (val_labs_can_set_width (v->val_labs, new_width))
274         val_labs_set_width (v->val_labs, new_width);
275       else
276         {
277           val_labs_destroy (v->val_labs);
278           v->val_labs = NULL;
279         }
280       traits |= VAR_TRAIT_VALUE_LABELS;
281     }
282
283   if (fmt_resize (&v->print, new_width))
284     traits |= VAR_TRAIT_PRINT_FORMAT;
285
286   if (fmt_resize (&v->write, new_width))
287     traits |= VAR_TRAIT_WRITE_FORMAT;
288
289   v->width = new_width;
290   traits |= VAR_TRAIT_WIDTH;
291   dict_var_changed (v, traits, ov);
292 }
293
294 /* Returns true if variable V is numeric, false otherwise. */
295 bool
296 var_is_numeric (const struct variable *v)
297 {
298   return var_get_type (v) == VAL_NUMERIC;
299 }
300
301 /* Returns true if variable V is a string variable, false
302    otherwise. */
303 bool
304 var_is_alpha (const struct variable *v)
305 {
306   return var_get_type (v) == VAL_STRING;
307 }
308 \f
309 /* Returns variable V's missing values. */
310 const struct missing_values *
311 var_get_missing_values (const struct variable *v)
312 {
313   return &v->miss;
314 }
315
316 /* Sets variable V's missing values to MISS, which must be of V's
317    width or at least resizable to V's width.
318    If MISS is null, then V's missing values, if any, are
319    cleared. */
320 static void
321 var_set_missing_values_quiet (struct variable *v, const struct missing_values *miss)
322 {
323   if (miss != NULL)
324     {
325       assert (mv_is_resizable (miss, v->width));
326       mv_destroy (&v->miss);
327       mv_copy (&v->miss, miss);
328       mv_resize (&v->miss, v->width);
329     }
330   else
331     mv_clear (&v->miss);
332 }
333
334 /* Sets variable V's missing values to MISS, which must be of V's
335    width or at least resizable to V's width.
336    If MISS is null, then V's missing values, if any, are
337    cleared. */
338 void
339 var_set_missing_values (struct variable *v, const struct missing_values *miss)
340 {
341   struct variable *ov = var_clone (v);
342   var_set_missing_values_quiet (v, miss);
343   dict_var_changed (v, VAR_TRAIT_MISSING_VALUES, ov);
344 }
345
346 /* Sets variable V to have no user-missing values. */
347 void
348 var_clear_missing_values (struct variable *v)
349 {
350   var_set_missing_values (v, NULL);
351 }
352
353 /* Returns true if V has any user-missing values,
354    false otherwise. */
355 bool
356 var_has_missing_values (const struct variable *v)
357 {
358   return !mv_is_empty (&v->miss);
359 }
360
361 /* Returns true if VALUE is in the given CLASS of missing values
362    in V, false otherwise. */
363 bool
364 var_is_value_missing (const struct variable *v, const union value *value,
365                       enum mv_class class)
366 {
367   return mv_is_value_missing (&v->miss, value, class);
368 }
369
370 /* Returns true if D is in the given CLASS of missing values in
371    V, false otherwise.
372    V must be a numeric variable. */
373 bool
374 var_is_num_missing (const struct variable *v, double d, enum mv_class class)
375 {
376   return mv_is_num_missing (&v->miss, d, class);
377 }
378
379 /* Returns true if S[] is a missing value for V, false otherwise.
380    S[] must contain exactly as many characters as V's width.
381    V must be a string variable. */
382 bool
383 var_is_str_missing (const struct variable *v, const uint8_t s[],
384                     enum mv_class class)
385 {
386   return mv_is_str_missing (&v->miss, s, class);
387 }
388 \f
389 /* Returns variable V's value labels,
390    possibly a null pointer if it has none. */
391 const struct val_labs *
392 var_get_value_labels (const struct variable *v)
393 {
394   return v->val_labs;
395 }
396
397 /* Returns true if variable V has at least one value label. */
398 bool
399 var_has_value_labels (const struct variable *v)
400 {
401   return val_labs_count (v->val_labs) > 0;
402 }
403
404 /* Sets variable V's value labels to a copy of VLS,
405    which must have a width equal to V's width or one that can be
406    changed to V's width.
407    If VLS is null, then V's value labels, if any, are removed. */
408 static void
409 var_set_value_labels_quiet (struct variable *v, const struct val_labs *vls)
410 {
411   val_labs_destroy (v->val_labs);
412   v->val_labs = NULL;
413
414   if (vls != NULL)
415     {
416       assert (val_labs_can_set_width (vls, v->width));
417       v->val_labs = val_labs_clone (vls);
418       val_labs_set_width (v->val_labs, v->width);
419     }
420 }
421
422
423 /* Sets variable V's value labels to a copy of VLS,
424    which must have a width equal to V's width or one that can be
425    changed to V's width.
426    If VLS is null, then V's value labels, if any, are removed. */
427 void
428 var_set_value_labels (struct variable *v, const struct val_labs *vls)
429 {
430   struct variable *ov = var_clone (v);
431   var_set_value_labels_quiet (v, vls);
432   dict_var_changed (v, VAR_TRAIT_LABEL, ov);  
433 }
434
435
436 /* Makes sure that V has a set of value labels,
437    by assigning one to it if necessary. */
438 static void
439 alloc_value_labels (struct variable *v)
440 {
441   if (v->val_labs == NULL)
442     v->val_labs = val_labs_create (v->width);
443 }
444
445 /* Attempts to add a value label with the given VALUE and UTF-8 encoded LABEL
446    to V.  Returns true if successful, false otherwise (probably due to an
447    existing label).
448
449    In LABEL, the two-byte sequence "\\n" is interpreted as a new-line. */
450 bool
451 var_add_value_label (struct variable *v,
452                      const union value *value, const char *label)
453 {
454   alloc_value_labels (v);
455   return val_labs_add (v->val_labs, value, label);
456 }
457
458 /* Adds or replaces a value label with the given VALUE and UTF-8 encoded LABEL
459    to V.
460
461    In LABEL, the two-byte sequence "\\n" is interpreted as a new-line. */
462 void
463 var_replace_value_label (struct variable *v,
464                          const union value *value, const char *label)
465 {
466   alloc_value_labels (v);
467   val_labs_replace (v->val_labs, value, label);
468 }
469
470 /* Removes V's value labels, if any. */
471 void
472 var_clear_value_labels (struct variable *v)
473 {
474   var_set_value_labels (v, NULL);
475 }
476
477 /* Returns the label associated with VALUE for variable V, as a UTF-8 string in
478    a format suitable for output, or a null pointer if none. */
479 const char *
480 var_lookup_value_label (const struct variable *v, const union value *value)
481 {
482   return val_labs_find (v->val_labs, value);
483 }
484
485 /*
486    Append to STR the string representation of VALUE for variable V.
487    STR must be a pointer to an initialised struct string.
488 */
489 static void
490 append_value (const struct variable *v, const union value *value,
491               struct string *str)
492 {
493   char *s = data_out (value, var_get_encoding (v), &v->print);
494   ds_put_cstr (str, s);
495   free (s);
496 }
497
498 /* Append STR with a string representing VALUE for variable V.
499    That is, if VALUE has a label, append that label,
500    otherwise format VALUE and append the formatted string.
501    STR must be a pointer to an initialised struct string.
502 */
503 void
504 var_append_value_name (const struct variable *v, const union value *value,
505                        struct string *str)
506 {
507   enum settings_value_style style = settings_get_value_style ();
508   const char *name = var_lookup_value_label (v, value);
509
510   switch (style)
511     {
512     case SETTINGS_VAL_STYLE_VALUES:
513       append_value (v, value, str);
514       break;
515       
516     case SETTINGS_VAL_STYLE_LABELS:
517       if (name == NULL)
518         append_value (v, value, str);
519       else
520         ds_put_cstr (str, name);
521       break;
522
523     case SETTINGS_VAL_STYLE_BOTH:
524     default:
525       append_value (v, value, str);
526       if (name != NULL)
527         {
528           ds_put_cstr (str, " (");
529           ds_put_cstr (str, name);
530           ds_put_cstr (str, ")");
531         }
532       break;
533     };
534 }
535 \f
536 /* Print and write formats. */
537
538 /* Returns V's print format specification. */
539 const struct fmt_spec *
540 var_get_print_format (const struct variable *v)
541 {
542   return &v->print;
543 }
544
545 /* Sets V's print format specification to PRINT, which must be a
546    valid format specification for a variable of V's width
547    (ordinarily an output format, but input formats are not
548    rejected). */
549 static void
550 var_set_print_format_quiet (struct variable *v, const struct fmt_spec *print)
551 {
552   if (!fmt_equal (&v->print, print))
553     {
554       assert (fmt_check_width_compat (print, v->width));
555       v->print = *print;
556     }
557 }
558
559 /* Sets V's print format specification to PRINT, which must be a
560    valid format specification for a variable of V's width
561    (ordinarily an output format, but input formats are not
562    rejected). */
563 void
564 var_set_print_format (struct variable *v, const struct fmt_spec *print)
565 {
566   struct variable *ov = var_clone (v);
567   var_set_print_format_quiet (v, print);
568   dict_var_changed (v, VAR_TRAIT_PRINT_FORMAT, ov);
569 }
570
571 /* Returns V's write format specification. */
572 const struct fmt_spec *
573 var_get_write_format (const struct variable *v)
574 {
575   return &v->write;
576 }
577
578 /* Sets V's write format specification to WRITE, which must be a
579    valid format specification for a variable of V's width
580    (ordinarily an output format, but input formats are not
581    rejected). */
582 static void
583 var_set_write_format_quiet (struct variable *v, const struct fmt_spec *write)
584 {
585   if (!fmt_equal (&v->write, write))
586     {
587       assert (fmt_check_width_compat (write, v->width));
588       v->write = *write;
589     }
590 }
591
592 /* Sets V's write format specification to WRITE, which must be a
593    valid format specification for a variable of V's width
594    (ordinarily an output format, but input formats are not
595    rejected). */
596 void
597 var_set_write_format (struct variable *v, const struct fmt_spec *write)
598 {
599   struct variable *ov = var_clone (v);
600   var_set_write_format_quiet (v, write);
601   dict_var_changed (v, VAR_TRAIT_WRITE_FORMAT, ov);
602 }
603
604
605 /* Sets V's print and write format specifications to FORMAT,
606    which must be a valid format specification for a variable of
607    V's width (ordinarily an output format, but input formats are
608    not rejected). */
609 void
610 var_set_both_formats (struct variable *v, const struct fmt_spec *format)
611 {
612   struct variable *ov = var_clone (v);
613   var_set_print_format_quiet (v, format);
614   var_set_write_format_quiet (v, format);
615   dict_var_changed (v, VAR_TRAIT_PRINT_FORMAT | VAR_TRAIT_WRITE_FORMAT, ov);
616 }
617
618 /* Returns the default print and write format for a variable of
619    the given TYPE, as set by var_create.  The return value can be
620    used to reset a variable's print and write formats to the
621    default. */
622 struct fmt_spec
623 var_default_formats (int width)
624 {
625   return (width == 0
626           ? fmt_for_output (FMT_F, 8, 2)
627           : fmt_for_output (FMT_A, width, 0));
628 }
629
630
631 \f
632
633 /* Update the combined name and label string if necessary */
634 static void
635 update_vl_string (const struct variable *v)
636 {
637   /* Cast away const! */
638   struct string *str = (struct string *) &v->name_and_label;
639
640   if (ds_is_empty (str))
641     {
642       if (v->label)
643         ds_put_format (str, _("%s (%s)"), v->label, v->name);
644       else
645         ds_put_cstr (str, v->name);
646     }
647 }
648
649
650 /* Return a string representing this variable, in the form most
651    appropriate from a human factors perspective, that is, its
652    variable label if it has one, otherwise its name. */
653 const char *
654 var_to_string (const struct variable *v)
655 {
656   enum settings_var_style style = settings_get_var_style ();
657
658   switch (style)
659   {
660     case SETTINGS_VAR_STYLE_NAMES:
661       return v->name;
662       break;
663     case SETTINGS_VAR_STYLE_LABELS:
664       return v->label != NULL ? v->label : v->name;
665       break;
666     case SETTINGS_VAR_STYLE_BOTH:
667       update_vl_string (v);
668       return ds_cstr (&v->name_and_label);
669       break;
670     default:
671       NOT_REACHED ();
672       break;
673   };
674 }
675
676 /* Returns V's variable label, or a null pointer if it has none. */
677 const char *
678 var_get_label (const struct variable *v)
679 {
680   return v->label;
681 }
682
683 /* Sets V's variable label to UTF-8 encoded string LABEL, stripping off leading
684    and trailing white space.  If LABEL is a null pointer or if LABEL is an
685    empty string (after stripping white space), then V's variable label (if any)
686    is removed.
687
688    Variable labels are limited to 255 bytes in V's encoding (as returned by
689    var_get_encoding()).  If LABEL fits within this limit, this function returns
690    true.  Otherwise, the variable label is set to a truncated value, this
691    function returns false and, if ISSUE_WARNING is true, issues a warning.  */
692 static bool
693 var_set_label_quiet (struct variable *v, const char *label, bool issue_warning)
694 {
695   bool truncated = false;
696
697   free (v->label);
698   v->label = NULL;
699
700   if (label != NULL && label[strspn (label, CC_SPACES)])
701     {
702       const char *dict_encoding = var_get_encoding (v);
703       struct substring s = ss_cstr (label);
704       size_t trunc_len;
705
706       if (dict_encoding != NULL)
707         {
708           enum { MAX_LABEL_LEN = 255 };
709
710           trunc_len = utf8_encoding_trunc_len (label, dict_encoding,
711                                                MAX_LABEL_LEN);
712           if (ss_length (s) > trunc_len)
713             {
714               if (issue_warning)
715                 msg (SW, _("Truncating variable label for variable `%s' to %d "
716                            "bytes."), var_get_name (v), MAX_LABEL_LEN);
717               ss_truncate (&s, trunc_len);
718               truncated = true;
719             }
720         }
721
722         v->label = ss_xstrdup (s);
723     }
724
725   ds_destroy (&v->name_and_label);
726   ds_init_empty (&v->name_and_label);
727
728   return truncated;
729 }
730
731
732
733 /* Sets V's variable label to UTF-8 encoded string LABEL, stripping off leading
734    and trailing white space.  If LABEL is a null pointer or if LABEL is an
735    empty string (after stripping white space), then V's variable label (if any)
736    is removed.
737
738    Variable labels are limited to 255 bytes in V's encoding (as returned by
739    var_get_encoding()).  If LABEL fits within this limit, this function returns
740    true.  Otherwise, the variable label is set to a truncated value, this
741    function returns false and, if ISSUE_WARNING is true, issues a warning.  */
742 bool
743 var_set_label (struct variable *v, const char *label, bool issue_warning)
744 {
745   struct variable *ov = var_clone (v);
746   bool truncated = var_set_label_quiet (v, label, issue_warning);
747
748   dict_var_changed (v, VAR_TRAIT_LABEL, ov);
749
750   return truncated;
751 }
752
753
754 /* Removes any variable label from V. */
755 void
756 var_clear_label (struct variable *v)
757 {
758   var_set_label (v, NULL, false);
759 }
760
761 /* Returns true if V has a variable V,
762    false otherwise. */
763 bool
764 var_has_label (const struct variable *v)
765 {
766   return v->label != NULL;
767 }
768 \f
769 /* Returns true if M is a valid variable measurement level,
770    false otherwise. */
771 bool
772 measure_is_valid (enum measure m)
773 {
774   return m == MEASURE_NOMINAL || m == MEASURE_ORDINAL || m == MEASURE_SCALE;
775 }
776
777 /* Returns a string version of measurement level M, for display to a user. */
778 const char *
779 measure_to_string (enum measure m)
780 {
781   switch (m)
782     {
783     case MEASURE_NOMINAL:
784       return _("Nominal");
785
786     case MEASURE_ORDINAL:
787       return _("Ordinal");
788
789     case MEASURE_SCALE:
790       return _("Scale");
791
792     default:
793       return "Invalid";
794     }
795 }
796
797 /* Returns V's measurement level. */
798 enum measure
799 var_get_measure (const struct variable *v)
800 {
801   return v->measure;
802 }
803
804 /* Sets V's measurement level to MEASURE. */
805 static void
806 var_set_measure_quiet (struct variable *v, enum measure measure)
807 {
808   assert (measure_is_valid (measure));
809   v->measure = measure;
810 }
811
812
813 /* Sets V's measurement level to MEASURE. */
814 void
815 var_set_measure (struct variable *v, enum measure measure)
816 {
817   struct variable *ov = var_clone (v);
818   var_set_measure_quiet (v, measure);
819   dict_var_changed (v, VAR_TRAIT_MEASURE, ov);
820 }
821
822
823 /* Returns the default measurement level for a variable of the
824    given TYPE, as set by var_create.  The return value can be
825    used to reset a variable's measurement level to the
826    default. */
827 enum measure
828 var_default_measure (enum val_type type)
829 {
830   return type == VAL_NUMERIC ? MEASURE_SCALE : MEASURE_NOMINAL;
831 }
832 \f
833 /* Returns V's display width, which applies only to GUIs. */
834 int
835 var_get_display_width (const struct variable *v)
836 {
837   return v->display_width;
838 }
839
840 /* Sets V's display width to DISPLAY_WIDTH. */
841 static void
842 var_set_display_width_quiet (struct variable *v, int new_width)
843 {
844   if (v->display_width != new_width)
845     {
846       v->display_width = new_width;
847     }
848 }
849
850 void
851 var_set_display_width (struct variable *v, int new_width)
852 {
853   struct variable *ov = var_clone (v);
854   var_set_display_width_quiet (v, new_width);
855   dict_var_changed (v, VAR_TRAIT_DISPLAY_WIDTH, ov);
856 }
857
858
859 /* Returns the default display width for a variable of the given
860    WIDTH, as set by var_create.  The return value can be used to
861    reset a variable's display width to the default. */
862 int
863 var_default_display_width (int width)
864 {
865   return width == 0 ? 8 : MIN (width, 32);
866 }
867 \f
868 /* Returns true if A is a valid alignment,
869    false otherwise. */
870 bool
871 alignment_is_valid (enum alignment a)
872 {
873   return a == ALIGN_LEFT || a == ALIGN_RIGHT || a == ALIGN_CENTRE;
874 }
875
876 /* Returns a string version of alignment A, for display to a user. */
877 const char *
878 alignment_to_string (enum alignment a)
879 {
880   switch (a)
881     {
882     case ALIGN_LEFT:
883       return _("Left");
884
885     case ALIGN_RIGHT:
886       return _("Right");
887
888     case ALIGN_CENTRE:
889       return _("Center");
890
891     default:
892       return "Invalid";
893     }
894 }
895
896 /* Returns V's display alignment, which applies only to GUIs. */
897 enum alignment
898 var_get_alignment (const struct variable *v)
899 {
900   return v->alignment;
901 }
902
903 /* Sets V's display alignment to ALIGNMENT. */
904 static void
905 var_set_alignment_quiet (struct variable *v, enum alignment alignment)
906 {
907   assert (alignment_is_valid (alignment));
908   v->alignment = alignment;
909 }
910
911 /* Sets V's display alignment to ALIGNMENT. */
912 void
913 var_set_alignment (struct variable *v, enum alignment alignment)
914 {
915   struct variable *ov = var_clone (v);
916   var_set_alignment_quiet (v, alignment);
917   dict_var_changed (v, VAR_TRAIT_ALIGNMENT, ov);
918 }
919
920
921 /* Returns the default display alignment for a variable of the
922    given TYPE, as set by var_create.  The return value can be
923    used to reset a variable's display alignment to the default. */
924 enum alignment
925 var_default_alignment (enum val_type type)
926 {
927   return type == VAL_NUMERIC ? ALIGN_RIGHT : ALIGN_LEFT;
928 }
929 \f
930 /* Whether variables' values should be preserved from case to
931    case. */
932
933 /* Returns true if variable V's value should be left from case to
934    case, instead of being reset to system-missing or blanks. */
935 bool
936 var_get_leave (const struct variable *v)
937 {
938   return v->leave;
939 }
940
941 /* Sets V's leave setting to LEAVE. */
942 static void
943 var_set_leave_quiet (struct variable *v, bool leave)
944 {
945   assert (leave || !var_must_leave (v));
946   v->leave = leave;
947 }
948
949
950 /* Sets V's leave setting to LEAVE. */
951 void
952 var_set_leave (struct variable *v, bool leave)
953 {
954   struct variable *ov = var_clone (v);
955   var_set_leave_quiet (v, leave);
956   dict_var_changed (v, VAR_TRAIT_LEAVE, ov);
957 }
958
959
960 /* Returns true if V must be left from case to case,
961    false if it can be set either way. */
962 bool
963 var_must_leave (const struct variable *v)
964 {
965   return var_get_dict_class (v) == DC_SCRATCH;
966 }
967 \f
968 /* Returns the number of short names stored in VAR.
969
970    Short names are used only for system and portable file input
971    and output.  They are upper-case only, not necessarily unique,
972    and limited to SHORT_NAME_LEN characters (plus a null
973    terminator).  Ordinarily a variable has at most one short
974    name, but very long string variables (longer than 255 bytes)
975    may have more.  A variable might not have any short name at
976    all if it hasn't been saved to or read from a system or
977    portable file. */
978 size_t
979 var_get_short_name_cnt (const struct variable *var) 
980 {
981   return var->short_name_cnt;
982 }
983
984 /* Returns VAR's short name with the given IDX, if it has one
985    with that index, or a null pointer otherwise.  Short names may
986    be sparse: even if IDX is less than the number of short names
987    in VAR, this function may return a null pointer. */
988 const char *
989 var_get_short_name (const struct variable *var, size_t idx)
990 {
991   return idx < var->short_name_cnt ? var->short_names[idx] : NULL;
992 }
993
994 /* Sets VAR's short name with the given IDX to the UTF-8 string SHORT_NAME.
995    The caller must already have checked that, in the dictionary encoding,
996    SHORT_NAME is no more than SHORT_NAME_LEN bytes long.  The new short name
997    will be converted to uppercase.
998
999    Specifying a null pointer for SHORT_NAME clears the specified short name. */
1000 void
1001 var_set_short_name (struct variable *var, size_t idx, const char *short_name)
1002 {
1003   struct variable *ov = var_clone (var);
1004
1005   assert (short_name == NULL || id_is_plausible (short_name, false));
1006
1007   /* Clear old short name numbered IDX, if any. */
1008   if (idx < var->short_name_cnt) 
1009     {
1010       free (var->short_names[idx]);
1011       var->short_names[idx] = NULL; 
1012     }
1013
1014   /* Install new short name for IDX. */
1015   if (short_name != NULL) 
1016     {
1017       if (idx >= var->short_name_cnt)
1018         {
1019           size_t old_cnt = var->short_name_cnt;
1020           size_t i;
1021           var->short_name_cnt = MAX (idx * 2, 1);
1022           var->short_names = xnrealloc (var->short_names, var->short_name_cnt,
1023                                         sizeof *var->short_names);
1024           for (i = old_cnt; i < var->short_name_cnt; i++)
1025             var->short_names[i] = NULL;
1026         }
1027       var->short_names[idx] = utf8_to_upper (short_name);
1028     }
1029
1030   dict_var_changed (var, VAR_TRAIT_NAME, ov);
1031 }
1032
1033 /* Clears V's short names. */
1034 void
1035 var_clear_short_names (struct variable *v)
1036 {
1037   size_t i;
1038
1039   for (i = 0; i < v->short_name_cnt; i++)
1040     free (v->short_names[i]);
1041   free (v->short_names);
1042   v->short_names = NULL;
1043   v->short_name_cnt = 0;
1044 }
1045 \f
1046 /* Relationship with dictionary. */
1047
1048 /* Returns V's index within its dictionary, the value
1049    for which "dict_get_var (dict, index)" will return V.
1050    V must be in a dictionary. */
1051 size_t
1052 var_get_dict_index (const struct variable *v)
1053 {
1054   assert (var_has_vardict (v));
1055   return vardict_get_dict_index (v->vardict);
1056 }
1057
1058 /* Returns V's index within the case represented by its
1059    dictionary, that is, the value for which "case_data_idx (case,
1060    index)" will return the data for V in that case.
1061    V must be in a dictionary. */
1062 size_t
1063 var_get_case_index (const struct variable *v)
1064 {
1065   assert (var_has_vardict (v));
1066   return vardict_get_case_index (v->vardict);
1067 }
1068 \f
1069 /* Returns variable V's attribute set.  The caller may examine or
1070    modify the attribute set, but must not destroy it.  Destroying
1071    V, or calling var_set_attributes() on V, will also destroy its
1072    attribute set. */
1073 struct attrset *
1074 var_get_attributes (const struct variable *v) 
1075 {
1076   return CONST_CAST (struct attrset *, &v->attributes);
1077 }
1078
1079 /* Replaces variable V's attributes set by a copy of ATTRS. */
1080 static void
1081 var_set_attributes_quiet (struct variable *v, const struct attrset *attrs) 
1082 {
1083   attrset_destroy (&v->attributes);
1084   attrset_clone (&v->attributes, attrs);
1085 }
1086
1087 /* Replaces variable V's attributes set by a copy of ATTRS. */
1088 void
1089 var_set_attributes (struct variable *v, const struct attrset *attrs) 
1090 {
1091   struct variable *ov = var_clone (v);
1092   var_set_attributes_quiet (v, attrs);
1093   dict_var_changed (v, VAR_TRAIT_ATTRIBUTES, ov);
1094 }
1095
1096
1097 /* Returns true if V has any custom attributes, false if it has none. */
1098 bool
1099 var_has_attributes (const struct variable *v)
1100 {
1101   return attrset_count (&v->attributes) > 0;
1102 }
1103 \f
1104
1105 /* Creates and returns a clone of OLD_VAR.  Most properties of
1106    the new variable are copied from OLD_VAR, except:
1107
1108     - The variable's short name is not copied, because there is
1109       no reason to give a new variable with potentially a new
1110       name the same short name.
1111
1112     - The new variable is not added to OLD_VAR's dictionary by
1113       default.  Use dict_clone_var, instead, to do that.
1114 */
1115 struct variable *
1116 var_clone (const struct variable *old_var)
1117 {
1118   struct variable *new_var = var_create (var_get_name (old_var),
1119                                          var_get_width (old_var));
1120
1121   var_set_missing_values_quiet (new_var, var_get_missing_values (old_var));
1122   var_set_print_format_quiet (new_var, var_get_print_format (old_var));
1123   var_set_write_format_quiet (new_var, var_get_write_format (old_var));
1124   var_set_value_labels_quiet (new_var, var_get_value_labels (old_var));
1125   var_set_label_quiet (new_var, var_get_label (old_var), false);
1126   var_set_measure_quiet (new_var, var_get_measure (old_var));
1127   var_set_display_width_quiet (new_var, var_get_display_width (old_var));
1128   var_set_alignment_quiet (new_var, var_get_alignment (old_var));
1129   var_set_leave_quiet (new_var, var_get_leave (old_var));
1130   var_set_attributes_quiet (new_var, var_get_attributes (old_var));
1131
1132   return new_var;
1133 }
1134
1135
1136
1137 /* Returns the encoding of values of variable VAR.  (This is actually a
1138    property of the dictionary.)  Returns null if no specific encoding has been
1139    set.  */
1140 const char *
1141 var_get_encoding (const struct variable *var)
1142 {
1143   return (var_has_vardict (var)
1144           ? dict_get_encoding (vardict_get_dictionary (var->vardict))
1145           : NULL);
1146 }
1147 \f
1148 /* Returns V's vardict structure. */
1149 struct vardict_info *
1150 var_get_vardict (const struct variable *v)
1151 {
1152   return CONST_CAST (struct vardict_info *, v->vardict);
1153 }
1154
1155 /* Sets V's vardict data to VARDICT. */
1156 void
1157 var_set_vardict (struct variable *v, struct vardict_info *vardict)
1158 {
1159   v->vardict = vardict;
1160 }
1161
1162 /* Returns true if V has vardict data. */
1163 bool
1164 var_has_vardict (const struct variable *v)
1165 {
1166   return v->vardict != NULL;
1167 }
1168
1169 /* Clears V's vardict data. */
1170 void
1171 var_clear_vardict (struct variable *v)
1172 {
1173   v->vardict = NULL;
1174 }