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