Rewrite expression code.
[pspp-builds.git] / src / print.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3    Written by Ben Pfaff <blp@gnu.org>.
4
5    This program is free software; you can redistribute it and/or
6    modify it under the terms of the GNU General Public License as
7    published by the Free Software Foundation; either version 2 of the
8    License, or (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
18    02111-1307, USA. */
19
20 /* FIXME: seems like a lot of code duplication with data-list.c. */
21
22 #include <config.h>
23 #include "error.h"
24 #include <stdlib.h>
25 #include "alloc.h"
26 #include "case.h"
27 #include "command.h"
28 #include "dfm-write.h"
29 #include "error.h"
30 #include "expressions/public.h"
31 #include "file-handle.h"
32 #include "lexer.h"
33 #include "misc.h"
34 #include "som.h"
35 #include "tab.h"
36 #include "var.h"
37
38 /* Describes what to do when an output field is encountered. */
39 enum
40   {
41     PRT_ERROR,                  /* Invalid value. */
42     PRT_NEWLINE,                /* Newline. */
43     PRT_CONST,                  /* Constant string. */
44     PRT_VAR,                    /* Variable. */
45     PRT_SPACE                   /* A single space. */
46   };
47
48 /* Describes how to output one field. */
49 struct prt_out_spec
50   {
51     struct prt_out_spec *next;
52     int type;                   /* PRT_* constant. */
53     int fc;                     /* 0-based first column. */
54     union
55       {
56         char *c;                /* PRT_CONST: Associated string. */
57         struct
58           {
59             struct variable *v; /* PRT_VAR: Associated variable. */
60             struct fmt_spec f;  /* PRT_VAR: Output spec. */
61           }
62         v;
63       }
64     u;
65   };
66
67 /* Enums for use with print_trns's `options' field. */
68 enum
69   {
70     PRT_CMD_MASK = 1,           /* Command type mask. */
71     PRT_PRINT = 0,              /* PRINT transformation identifier. */
72     PRT_WRITE = 1,              /* WRITE transformation identifier. */
73     PRT_EJECT = 002,            /* Can be combined with CMD_PRINT only. */
74     PRT_BINARY = 004            /* File is binary, omit newlines. */
75   };
76
77 /* PRINT, PRINT EJECT, WRITE private data structure. */
78 struct print_trns
79   {
80     struct trns_header h;
81     struct dfm_writer *writer;  /* Output file, NULL=listing file. */
82     int options;                /* PRT_* bitmapped field. */
83     struct prt_out_spec *spec;  /* Output specifications. */
84     int max_width;              /* Maximum line width including null. */
85     char *line;                 /* Buffer for sticking lines in. */
86   };
87
88 /* PRT_PRINT or PRT_WRITE. */
89 int which_cmd;
90
91 /* Holds information on parsing the data file. */
92 static struct print_trns prt;
93
94 /* Last prt_out_spec in the chain.  Used for building the linked-list. */
95 static struct prt_out_spec *next;
96
97 /* Number of records. */
98 static int nrec;
99
100 static int internal_cmd_print (int flags);
101 static trns_proc_func print_trns_proc;
102 static trns_free_func print_trns_free;
103 static int parse_specs (void);
104 static void dump_table (const struct file_handle *);
105 static void append_var_spec (struct prt_out_spec *);
106 static void alloc_line (void);
107 \f
108 /* Basic parsing. */
109
110 /* Parses PRINT command. */
111 int
112 cmd_print (void)
113 {
114   return internal_cmd_print (PRT_PRINT);
115 }
116
117 /* Parses PRINT EJECT command. */
118 int
119 cmd_print_eject (void)
120 {
121   return internal_cmd_print (PRT_PRINT | PRT_EJECT);
122 }
123
124 /* Parses WRITE command. */
125 int
126 cmd_write (void)
127 {
128   return internal_cmd_print (PRT_WRITE);
129 }
130
131 /* Parses the output commands.  F is PRT_PRINT, PRT_WRITE, or
132    PRT_PRINT|PRT_EJECT. */
133 static int
134 internal_cmd_print (int f)
135 {
136   int table = 0;                /* Print table? */
137   struct print_trns *trns;      /* malloc()'d transformation. */
138   struct file_handle *fh = NULL;
139
140   /* Fill in prt to facilitate error-handling. */
141   prt.h.proc = print_trns_proc;
142   prt.h.free = print_trns_free;
143   prt.writer = NULL;
144   prt.options = f;
145   prt.spec = NULL;
146   prt.line = NULL;
147   next = NULL;
148   nrec = 0;
149
150   which_cmd = f & PRT_CMD_MASK;
151
152   /* Parse the command options. */
153   while (!lex_match ('/'))
154     {
155       if (lex_match_id ("OUTFILE"))
156         {
157           lex_match ('=');
158
159           fh = fh_parse ();
160           if (fh == NULL)
161             goto error;
162         }
163       else if (lex_match_id ("RECORDS"))
164         {
165           lex_match ('=');
166           lex_match ('(');
167           if (!lex_force_int ())
168             goto error;
169           nrec = lex_integer ();
170           lex_get ();
171           lex_match (')');
172         }
173       else if (lex_match_id ("TABLE"))
174         table = 1;
175       else if (lex_match_id ("NOTABLE"))
176         table = 0;
177       else
178         {
179           lex_error (_("expecting a valid subcommand"));
180           goto error;
181         }
182     }
183
184   /* Parse variables and strings. */
185   if (!parse_specs ())
186     goto error;
187
188   if (fh != NULL)
189     {
190       prt.writer = dfm_open_writer (fh);
191       if (prt.writer == NULL)
192         goto error;
193
194       if (handle_get_mode (fh) == MODE_BINARY)
195         prt.options |= PRT_BINARY;
196     }
197
198   /* Output the variable table if requested. */
199   if (table)
200     dump_table (fh);
201
202   /* Count the maximum line width.  Allocate linebuffer if
203      applicable. */
204   alloc_line ();
205
206   /* Put the transformation in the queue. */
207   trns = xmalloc (sizeof *trns);
208   memcpy (trns, &prt, sizeof *trns);
209   add_transformation ((struct trns_header *) trns);
210
211   return CMD_SUCCESS;
212
213  error:
214   print_trns_free ((struct trns_header *) & prt);
215   return CMD_FAILURE;
216 }
217
218 /* Appends the field output specification SPEC to the list maintained
219    in prt. */
220 static void
221 append_var_spec (struct prt_out_spec *spec)
222 {
223   if (next == 0)
224     prt.spec = next = xmalloc (sizeof *spec);
225   else
226     next = next->next = xmalloc (sizeof *spec);
227
228   memcpy (next, spec, sizeof *spec);
229   next->next = NULL;
230 }
231 \f
232 /* Field parsing.  Mostly stolen from data-list.c. */
233
234 /* Used for chaining together fortran-like format specifiers. */
235 struct fmt_list
236 {
237   struct fmt_list *next;
238   int count;
239   struct fmt_spec f;
240   struct fmt_list *down;
241 };
242
243 /* Used as "local" variables among the fixed-format parsing funcs.  If
244    it were guaranteed that PSPP were going to be compiled by gcc,
245    I'd make all these functions a single set of nested functions. */
246 static struct
247   {
248     struct variable **v;                /* variable list */
249     int nv;                     /* number of variables in list */
250     int cv;                     /* number of variables from list used up so far
251                                    by the FORTRAN-like format specifiers */
252
253     int recno;                  /* current 1-based record number */
254     int sc;                     /* 1-based starting column for next variable */
255
256     struct prt_out_spec spec;           /* next format spec to append to list */
257     int fc, lc;                 /* first, last 1-based column number of current
258                                    var */
259
260     int level;                  /* recursion level for FORTRAN-like format
261                                    specifiers */
262   }
263 fx;
264
265 static int fixed_parse_compatible (void);
266 static struct fmt_list *fixed_parse_fortran (void);
267
268 static int parse_string_argument (void);
269 static int parse_variable_argument (void);
270
271 /* Parses all the variable and string specifications on a single
272    PRINT, PRINT EJECT, or WRITE command into the prt structure.
273    Returns success. */
274 static int
275 parse_specs (void)
276 {
277   /* Return code from called function. */
278   int code;
279
280   fx.recno = 1;
281   fx.sc = 1;
282
283   while (token != '.')
284     {
285       while (lex_match ('/'))
286         {
287           int prev_recno = fx.recno;
288
289           fx.recno++;
290           if (token == T_NUM)
291             {
292               if (!lex_force_int ())
293                 return 0;
294               if (lex_integer () < fx.recno)
295                 {
296                   msg (SE, _("The record number specified, %ld, is "
297                              "before the previous record, %d.  Data "
298                              "fields must be listed in order of "
299                              "increasing record number."),
300                        lex_integer (), fx.recno - 1);
301                   return 0;
302                 }
303               fx.recno = lex_integer ();
304               lex_get ();
305             }
306
307           fx.spec.type = PRT_NEWLINE;
308           while (prev_recno++ < fx.recno)
309             append_var_spec (&fx.spec);
310
311           fx.sc = 1;
312         }
313
314       if (token == T_STRING)
315         code = parse_string_argument ();
316       else
317         code = parse_variable_argument ();
318       if (!code)
319         return 0;
320     }
321   fx.spec.type = PRT_NEWLINE;
322   append_var_spec (&fx.spec);
323
324   if (!nrec)
325     nrec = fx.recno;
326   else if (fx.recno > nrec)
327     {
328       msg (SE, _("Variables are specified on records that "
329                  "should not exist according to RECORDS subcommand."));
330       return 0;
331     }
332       
333   if (token != '.')
334     {
335       lex_error (_("expecting end of command"));
336       return 0;
337     }
338   
339   return 1;
340 }
341
342 /* Parses a string argument to the PRINT commands.  Returns success. */
343 static int
344 parse_string_argument (void)
345 {
346   fx.spec.type = PRT_CONST;
347   fx.spec.fc = fx.sc - 1;
348   fx.spec.u.c = xstrdup (ds_c_str (&tokstr));
349   lex_get ();
350
351   /* Parse the included column range. */
352   if (token == T_NUM)
353     {
354       /* Width of column range in characters. */
355       int c_len;
356
357       /* Width of constant string in characters. */
358       int s_len;
359
360       /* 1-based index of last column in range. */
361       int lc;
362
363       if (!lex_integer_p () || lex_integer () <= 0)
364         {
365           msg (SE, _("%g is not a valid column location."), tokval);
366           goto fail;
367         }
368       fx.spec.fc = lex_integer () - 1;
369
370       lex_get ();
371       lex_negative_to_dash ();
372       if (lex_match ('-'))
373         {
374           if (!lex_integer_p ())
375             {
376               msg (SE, _("Column location expected following `%d-'."),
377                    fx.spec.fc + 1);
378               goto fail;
379             }
380           if (lex_integer () <= 0)
381             {
382               msg (SE, _("%g is not a valid column location."), tokval);
383               goto fail;
384             }
385           if (lex_integer () < fx.spec.fc + 1)
386             {
387               msg (SE, _("%d-%ld is not a valid column range.  The second "
388                    "column must be greater than or equal to the first."),
389                    fx.spec.fc + 1, lex_integer ());
390               goto fail;
391             }
392           lc = lex_integer () - 1;
393
394           lex_get ();
395         }
396       else
397         /* If only a starting location is specified then the field is
398            the width of the provided string. */
399         lc = fx.spec.fc + strlen (fx.spec.u.c) - 1;
400
401       /* Apply the range. */
402       c_len = lc - fx.spec.fc + 1;
403       s_len = strlen (fx.spec.u.c);
404       if (s_len > c_len)
405         fx.spec.u.c[c_len] = 0;
406       else if (s_len < c_len)
407         {
408           fx.spec.u.c = xrealloc (fx.spec.u.c, c_len + 1);
409           memset (&fx.spec.u.c[s_len], ' ', c_len - s_len);
410           fx.spec.u.c[c_len] = 0;
411         }
412
413       fx.sc = lc + 1;
414     }
415   else
416     /* If nothing is provided then the field is the width of the
417        provided string. */
418     fx.sc += strlen (fx.spec.u.c);
419
420   append_var_spec (&fx.spec);
421   return 1;
422
423 fail:
424   free (fx.spec.u.c);
425   return 0;
426 }
427
428 /* Parses a variable argument to the PRINT commands by passing it off
429    to fixed_parse_compatible() or fixed_parse_fortran() as appropriate.
430    Returns success. */
431 static int
432 parse_variable_argument (void)
433 {
434   if (!parse_variables (default_dict, &fx.v, &fx.nv, PV_DUPLICATE))
435     return 0;
436
437   if (token == T_NUM)
438     {
439       if (!fixed_parse_compatible ())
440         goto fail;
441     }
442   else if (token == '(')
443     {
444       fx.level = 0;
445       fx.cv = 0;
446       if (!fixed_parse_fortran ())
447         goto fail;
448     }
449   else
450     {
451       /* User wants dictionary format specifiers. */
452       int i;
453
454       lex_match ('*');
455       for (i = 0; i < fx.nv; i++)
456         {
457           /* Variable. */
458           fx.spec.type = PRT_VAR;
459           fx.spec.fc = fx.sc - 1;
460           fx.spec.u.v.v = fx.v[i];
461           fx.spec.u.v.f = fx.v[i]->print;
462           append_var_spec (&fx.spec);
463           fx.sc += fx.v[i]->print.w;
464
465           /* Space. */
466           fx.spec.type = PRT_SPACE;
467           fx.spec.fc = fx.sc - 1;
468           append_var_spec (&fx.spec);
469           fx.sc++;
470         }
471     }
472
473   free (fx.v);
474   return 1;
475
476 fail:
477   free (fx.v);
478   return 0;
479 }
480
481 /* Parses a column specification for parse_specs(). */
482 static int
483 fixed_parse_compatible (void)
484 {
485   int dividend;
486   int type;
487   int i;
488
489   type = fx.v[0]->type;
490   for (i = 1; i < fx.nv; i++)
491     if (type != fx.v[i]->type)
492       {
493         msg (SE, _("%s is not of the same type as %s.  To specify "
494                    "variables of different types in the same variable "
495                    "list, use a FORTRAN-like format specifier."),
496              fx.v[i]->name, fx.v[0]->name);
497         return 0;
498       }
499
500   if (!lex_force_int ())
501     return 0;
502   fx.fc = lex_integer () - 1;
503   if (fx.fc < 0)
504     {
505       msg (SE, _("Column positions for fields must be positive."));
506       return 0;
507     }
508   lex_get ();
509
510   lex_negative_to_dash ();
511   if (lex_match ('-'))
512     {
513       if (!lex_force_int ())
514         return 0;
515       fx.lc = lex_integer () - 1;
516       if (fx.lc < 0)
517         {
518           msg (SE, _("Column positions for fields must be positive."));
519           return 0;
520         }
521       else if (fx.lc < fx.fc)
522         {
523           msg (SE, _("The ending column for a field must not "
524                      "be less than the starting column."));
525           return 0;
526         }
527       lex_get ();
528     }
529   else
530     fx.lc = fx.fc;
531
532   fx.spec.u.v.f.w = fx.lc - fx.fc + 1;
533   if (lex_match ('('))
534     {
535       struct fmt_desc *fdp;
536
537       if (token == T_ID)
538         {
539           const char *cp;
540
541           fx.spec.u.v.f.type = parse_format_specifier_name (&cp, 0);
542           if (fx.spec.u.v.f.type == -1)
543             return 0;
544           if (*cp)
545             {
546               msg (SE, _("A format specifier on this line "
547                          "has extra characters on the end."));
548               return 0;
549             }
550           lex_get ();
551           lex_match (',');
552         }
553       else
554         fx.spec.u.v.f.type = FMT_F;
555
556       if (token == T_NUM)
557         {
558           if (!lex_force_int ())
559             return 0;
560           if (lex_integer () < 1)
561             {
562               msg (SE, _("The value for number of decimal places "
563                          "must be at least 1."));
564               return 0;
565             }
566           fx.spec.u.v.f.d = lex_integer ();
567           lex_get ();
568         }
569       else
570         fx.spec.u.v.f.d = 0;
571
572       fdp = &formats[fx.spec.u.v.f.type];
573       if (fdp->n_args < 2 && fx.spec.u.v.f.d)
574         {
575           msg (SE, _("Input format %s doesn't accept decimal places."),
576                fdp->name);
577           return 0;
578         }
579       if (fx.spec.u.v.f.d > 16)
580         fx.spec.u.v.f.d = 16;
581
582       if (!lex_force_match (')'))
583         return 0;
584     }
585   else
586     {
587       fx.spec.u.v.f.type = FMT_F;
588       fx.spec.u.v.f.d = 0;
589     }
590
591   fx.sc = fx.lc + 1;
592
593   if ((fx.lc - fx.fc + 1) % fx.nv)
594     {
595       msg (SE, _("The %d columns %d-%d can't be evenly divided into %d "
596                  "fields."), fx.lc - fx.fc + 1, fx.fc + 1, fx.lc + 1, fx.nv);
597       return 0;
598     }
599
600   dividend = (fx.lc - fx.fc + 1) / fx.nv;
601   fx.spec.u.v.f.w = dividend;
602   if (!check_output_specifier (&fx.spec.u.v.f, 1))
603     return 0;
604   if ((type == ALPHA) ^ (formats[fx.spec.u.v.f.type].cat & FCAT_STRING))
605     {
606       msg (SE, _("%s variables cannot be displayed with format %s."),
607            type == ALPHA ? _("String") : _("Numeric"),
608            fmt_to_string (&fx.spec.u.v.f));
609       return 0;
610     }
611
612   /* Check that, for string variables, the user didn't specify a width
613      longer than an actual string width. */
614   if (type == ALPHA)
615     {
616       /* Minimum width of all the string variables specified. */
617       int min_len = fx.v[0]->width;
618
619       for (i = 1; i < fx.nv; i++)
620         min_len = min (min_len, fx.v[i]->width);
621       if (!check_string_specifier (&fx.spec.u.v.f, min_len))
622         return 0;
623     }
624
625   fx.spec.type = PRT_VAR;
626   for (i = 0; i < fx.nv; i++)
627     {
628       fx.spec.fc = fx.fc + dividend * i;
629       fx.spec.u.v.v = fx.v[i];
630       append_var_spec (&fx.spec);
631     }
632   return 1;
633 }
634
635 /* Destroy a format list and, optionally, all its sublists. */
636 static void
637 destroy_fmt_list (struct fmt_list * f, int recurse)
638 {
639   struct fmt_list *next;
640
641   for (; f; f = next)
642     {
643       next = f->next;
644       if (recurse && f->f.type == FMT_DESCEND)
645         destroy_fmt_list (f->down, 1);
646       free (f);
647     }
648 }
649
650 /* Recursively puts the format list F (which represents a set of
651    FORTRAN-like format specifications, like 4(F10,2X)) into the
652    structure prt. */
653 static int
654 dump_fmt_list (struct fmt_list * f)
655 {
656   int i;
657
658   for (; f; f = f->next)
659     if (f->f.type == FMT_X)
660       fx.sc += f->count;
661     else if (f->f.type == FMT_T)
662       fx.sc = f->f.w;
663     else if (f->f.type == FMT_NEWREC)
664       {
665         fx.recno += f->count;
666         fx.sc = 1;
667         fx.spec.type = PRT_NEWLINE;
668         for (i = 0; i < f->count; i++)
669           append_var_spec (&fx.spec);
670       }
671     else
672       for (i = 0; i < f->count; i++)
673         if (f->f.type == FMT_DESCEND)
674           {
675             if (!dump_fmt_list (f->down))
676               return 0;
677           }
678         else
679           {
680             struct variable *v;
681
682             if (fx.cv >= fx.nv)
683               {
684                 msg (SE, _("The number of format "
685                            "specifications exceeds the number of variable "
686                            "names given."));
687                 return 0;
688               }
689
690             v = fx.v[fx.cv++];
691             if ((v->type == ALPHA) ^ (formats[f->f.type].cat & FCAT_STRING))
692               {
693                 msg (SE, _("Display format %s may not be used with a "
694                            "%s variable."), fmt_to_string (&f->f),
695                      v->type == ALPHA ? _("string") : _("numeric"));
696                 return 0;
697               }
698             if (!check_string_specifier (&f->f, v->width))
699               return 0;
700
701             fx.spec.type = PRT_VAR;
702             fx.spec.u.v.v = v;
703             fx.spec.u.v.f = f->f;
704             fx.spec.fc = fx.sc - 1;
705             append_var_spec (&fx.spec);
706
707             fx.sc += f->f.w;
708           }
709   return 1;
710 }
711
712 /* Recursively parses a list of FORTRAN-like format specifiers.  Calls
713    itself to parse nested levels of parentheses.  Returns to its
714    original caller NULL, to indicate error, non-NULL, but nothing
715    useful, to indicate success (it returns a free()'d block). */
716 static struct fmt_list *
717 fixed_parse_fortran (void)
718 {
719   struct fmt_list *head = NULL;
720   struct fmt_list *fl = NULL;
721
722   lex_get ();                   /* skip opening parenthesis */
723   while (token != ')')
724     {
725       if (fl)
726         fl = fl->next = xmalloc (sizeof *fl);
727       else
728         head = fl = xmalloc (sizeof *fl);
729
730       if (token == T_NUM)
731         {
732           if (!lex_integer_p ())
733             goto fail;
734           fl->count = lex_integer ();
735           lex_get ();
736         }
737       else
738         fl->count = 1;
739
740       if (token == '(')
741         {
742           fl->f.type = FMT_DESCEND;
743           fx.level++;
744           fl->down = fixed_parse_fortran ();
745           fx.level--;
746           if (!fl->down)
747             goto fail;
748         }
749       else if (lex_match ('/'))
750         fl->f.type = FMT_NEWREC;
751       else if (!parse_format_specifier (&fl->f, FMTP_ALLOW_XT)
752                || !check_output_specifier (&fl->f, 1))
753         goto fail;
754
755       lex_match (',');
756     }
757   fl->next = NULL;
758   lex_get ();
759
760   if (fx.level)
761     return head;
762
763   fl->next = NULL;
764   dump_fmt_list (head);
765   destroy_fmt_list (head, 1);
766   if (fx.cv < fx.nv)
767     {
768       msg (SE, _("There aren't enough format specifications "
769            "to match the number of variable names given."));
770       goto fail;
771     }
772   return head;
773
774 fail:
775   fl->next = NULL;
776   destroy_fmt_list (head, 0);
777
778   return NULL;
779 }
780
781 /* Prints the table produced by the TABLE subcommand to the listing
782    file. */
783 static void
784 dump_table (const struct file_handle *fh)
785 {
786   struct prt_out_spec *spec;
787   struct tab_table *t;
788   int recno;
789   int nspec;
790
791   for (nspec = 0, spec = prt.spec; spec; spec = spec->next)
792     if (spec->type == PRT_CONST || spec->type == PRT_VAR)
793       nspec++;
794   t = tab_create (4, nspec + 1, 0);
795   tab_columns (t, TAB_COL_DOWN, 1);
796   tab_box (t, TAL_1, TAL_1, TAL_0, TAL_1, 0, 0, 3, nspec);
797   tab_hline (t, TAL_2, 0, 3, 1);
798   tab_headers (t, 0, 0, 1, 0);
799   tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Variable"));
800   tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Record"));
801   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Columns"));
802   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Format"));
803   tab_dim (t, tab_natural_dimensions);
804   for (nspec = recno = 0, spec = prt.spec; spec; spec = spec->next)
805     switch (spec->type)
806       {
807       case PRT_NEWLINE:
808         recno++;
809         break;
810       case PRT_CONST:
811         {
812           int len = strlen (spec->u.c);
813           nspec++;
814           tab_text (t, 0, nspec, TAB_LEFT | TAT_FIX | TAT_PRINTF,
815                         "\"%s\"", spec->u.c);
816           tab_text (t, 1, nspec, TAT_PRINTF, "%d", recno + 1);
817           tab_text (t, 2, nspec, TAT_PRINTF, "%3d-%3d",
818                         spec->fc + 1, spec->fc + len);
819           tab_text (t, 3, nspec, TAB_LEFT | TAT_FIX | TAT_PRINTF,
820                         "A%d", len);
821           break;
822         }
823       case PRT_VAR:
824         {
825           nspec++;
826           tab_text (t, 0, nspec, TAB_LEFT, spec->u.v.v->name);
827           tab_text (t, 1, nspec, TAT_PRINTF, "%d", recno + 1);
828           tab_text (t, 2, nspec, TAT_PRINTF, "%3d-%3d",
829                         spec->fc + 1, spec->fc + spec->u.v.f.w);
830           tab_text (t, 3, nspec, TAB_LEFT | TAT_FIX,
831                         fmt_to_string (&spec->u.v.f));
832           break;
833         }
834       case PRT_SPACE:
835         break;
836       case PRT_ERROR:
837         assert (0);
838       }
839
840   if (fh != NULL)
841     tab_title (t, 1, _("Writing %d record(s) to file %s."),
842                recno, handle_get_filename (fh));
843   else
844     tab_title (t, 1, _("Writing %d record(s) to the listing file."), recno);
845   tab_submit (t);
846 }
847
848 /* PORTME: The number of characters in a line terminator. */
849 #ifdef __MSDOS__ 
850 #define LINE_END_WIDTH 2        /* \r\n */
851 #else
852 #define LINE_END_WIDTH 1        /* \n */
853 #endif
854
855 /* Calculates the maximum possible line width and allocates a buffer
856    big enough to contain it */
857 static void
858 alloc_line (void)
859 {
860   /* Cumulative maximum line width (excluding null terminator) so far. */
861   int w = 0;
862
863   /* Width required by current this prt_out_spec. */
864   int pot_w;                    /* Potential w. */
865
866   /* Iterator. */
867   struct prt_out_spec *i;
868
869   for (i = prt.spec; i; i = i->next)
870     {
871       switch (i->type)
872         {
873         case PRT_NEWLINE:
874           pot_w = 0;
875           break;
876         case PRT_CONST:
877           pot_w = i->fc + strlen (i->u.c);
878           break;
879         case PRT_VAR:
880           pot_w = i->fc + i->u.v.f.w;
881           break;
882         case PRT_SPACE:
883           pot_w = i->fc + 1;
884           break;
885         case PRT_ERROR:
886         default:
887           assert (0);
888           abort ();
889         }
890       if (pot_w > w)
891         w = pot_w;
892     }
893   prt.max_width = w + LINE_END_WIDTH + 1;
894   prt.line = xmalloc (prt.max_width);
895 }
896 \f
897 /* Transformation. */
898
899 /* Performs the transformation inside print_trns T on case C. */
900 static int
901 print_trns_proc (struct trns_header * trns, struct ccase * c,
902                  int case_num UNUSED)
903 {
904   /* Transformation. */
905   struct print_trns *t = (struct print_trns *) trns;
906
907   /* Iterator. */
908   struct prt_out_spec *i;
909
910   /* Line buffer. */
911   char *buf = t->line;
912
913   /* Length of the line in buf. */
914   int len = 0;
915   memset (buf, ' ', t->max_width);
916
917   if (t->options & PRT_EJECT)
918     som_eject_page ();
919
920   /* Note that a field written to a place where a field has
921      already been written truncates the record.  `PRINT /A B
922      (T10,F8,T1,F8).' only outputs B.  */
923   for (i = t->spec; i; i = i->next)
924     switch (i->type)
925       {
926       case PRT_NEWLINE:
927         if (t->writer == NULL)
928           {
929             buf[len] = 0;
930             tab_output_text (TAT_FIX | TAT_NOWRAP, buf);
931           }
932         else
933           {
934             if ((t->options & PRT_CMD_MASK) == PRT_PRINT
935                 || !(t->options & PRT_BINARY))
936               {
937                 /* PORTME: Line ends. */
938 #ifdef __MSDOS__
939                 buf[len++] = '\r';
940 #endif
941                 buf[len++] = '\n';
942               }
943
944             dfm_put_record (t->writer, buf, len);
945           }
946
947         memset (buf, ' ', t->max_width);
948         len = 0;
949         break;
950
951       case PRT_CONST:
952         /* FIXME: Should be revised to keep track of the string's
953            length outside the loop, probably in i->u.c[0]. */
954         memcpy (&buf[i->fc], i->u.c, strlen (i->u.c));
955         len = i->fc + strlen (i->u.c);
956         break;
957
958       case PRT_VAR:
959         data_out (&buf[i->fc], &i->u.v.f, case_data (c, i->u.v.v->fv));
960         len = i->fc + i->u.v.f.w;
961         break;
962
963       case PRT_SPACE:
964         /* PRT_SPACE always immediately follows PRT_VAR. */
965         buf[len++] = ' ';
966         break;
967
968       case PRT_ERROR:
969         assert (0);
970         break;
971       }
972
973   return -1;
974 }
975
976 /* Frees all the data inside print_trns T.  Does not free T. */
977 static void
978 print_trns_free (struct trns_header * t)
979 {
980   struct print_trns *prt = (struct print_trns *) t;
981   struct prt_out_spec *i, *n;
982
983   for (i = prt->spec; i; i = n)
984     {
985       switch (i->type)
986         {
987         case PRT_CONST:
988           free (i->u.c);
989           /* fall through */
990         case PRT_NEWLINE:
991         case PRT_VAR:
992         case PRT_SPACE:
993           /* nothing to do */
994           break;
995         case PRT_ERROR:
996           assert (0);
997           break;
998         }
999       n = i->next;
1000       free (i);
1001     }
1002   if (prt->writer != NULL)
1003     dfm_close_writer (prt->writer);
1004   free (prt->line);
1005 }
1006 \f
1007 /* PRINT SPACE. */
1008
1009 /* PRINT SPACE transformation. */
1010 struct print_space_trns
1011 {
1012   struct trns_header h;
1013
1014   struct dfm_writer *writer;    /* Output data file. */
1015   struct expression *e;         /* Number of lines; NULL=1. */
1016 }
1017 print_space_trns;
1018
1019 static trns_proc_func print_space_trns_proc;
1020 static trns_free_func print_space_trns_free;
1021
1022 int
1023 cmd_print_space (void)
1024 {
1025   struct print_space_trns *t;
1026   struct file_handle *fh;
1027   struct expression *e;
1028   struct dfm_writer *writer;
1029
1030   if (lex_match_id ("OUTFILE"))
1031     {
1032       lex_match ('=');
1033
1034       fh = fh_parse ();
1035       if (fh == NULL)
1036         return CMD_FAILURE;
1037       lex_get ();
1038     }
1039   else
1040     fh = NULL;
1041
1042   if (token != '.')
1043     {
1044       e = expr_parse (default_dict, EXPR_NUMBER);
1045       if (token != '.')
1046         {
1047           expr_free (e);
1048           lex_error (_("expecting end of command"));
1049           return CMD_FAILURE;
1050         }
1051     }
1052   else
1053     e = NULL;
1054
1055   if (fh != NULL)
1056     {
1057       writer = dfm_open_writer (fh);
1058       if (writer == NULL) 
1059         {
1060           expr_free (e);
1061           return CMD_FAILURE;
1062         } 
1063     }
1064   else
1065     writer = NULL;
1066   
1067   t = xmalloc (sizeof *t);
1068   t->h.proc = print_space_trns_proc;
1069   if (e)
1070     t->h.free = print_space_trns_free;
1071   else
1072     t->h.free = NULL;
1073   t->writer = writer;
1074   t->e = e;
1075
1076   add_transformation ((struct trns_header *) t);
1077   return CMD_SUCCESS;
1078 }
1079
1080 static int
1081 print_space_trns_proc (struct trns_header * trns, struct ccase * c,
1082                        int case_num UNUSED)
1083 {
1084   struct print_space_trns *t = (struct print_space_trns *) trns;
1085   double n = 1.;
1086
1087   if (t->e)
1088     {
1089       n = expr_evaluate_num (t->e, c, case_num);
1090       if (n == SYSMIS) 
1091         msg (SW, _("The expression on PRINT SPACE evaluated to the "
1092                    "system-missing value."));
1093       else if (n < 0)
1094         msg (SW, _("The expression on PRINT SPACE evaluated to %g."), n);
1095       n = 1.;
1096     }
1097
1098   if (t->writer == NULL)
1099     while (n--)
1100       som_blank_line ();
1101   else
1102     {
1103       char buf[LINE_END_WIDTH];
1104
1105       /* PORTME: Line ends. */
1106 #ifdef __MSDOS__
1107       buf[0] = '\r';
1108       buf[1] = '\n';
1109 #else
1110       buf[0] = '\n';
1111 #endif
1112       while (n--)
1113         dfm_put_record (t->writer, buf, LINE_END_WIDTH);
1114     }
1115
1116   return -1;
1117 }
1118
1119 static void
1120 print_space_trns_free (struct trns_header * trns)
1121 {
1122   expr_free (((struct print_space_trns *) trns)->e);
1123 }