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