Imported Upstream version 1.22.2
[platform/upstream/groff.git] / src / libs / libdriver / input.cpp
1 // -*- C++ -*-
2
3 // <groff_src_dir>/src/libs/libdriver/input.cpp
4
5 /* Copyright (C) 1989-1992, 2001-2006, 2008-2011
6    Free Software Foundation, Inc.
7
8    Written by James Clark (jjc@jclark.com)
9    Major rewrite 2001 by Bernd Warken <groff-bernd.warken-72@web.de>
10
11    Last update: 9 May 2010
12
13    This file is part of groff, the GNU roff text processing system.
14
15    groff is free software; you can redistribute it and/or modify it
16    under the terms of the GNU General Public License as published by
17    the Free Software Foundation, either version 3 of the License, or
18    (at your option) any later version.
19
20    groff is distributed in the hope that it will be useful, but
21    WITHOUT ANY WARRANTY; without even the implied warranty of
22    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23    General Public License for more details.
24
25    You should have received a copy of the GNU General Public License
26    along with this program. If not, see <http://www.gnu.org/licenses/>.
27 */
28
29 /* Description
30
31    This file implements the parser for the intermediate groff output,
32    see groff_out(5), and does the printout for the given device.
33
34    All parsed information is processed within the function do_file().
35    A device postprocessor just needs to fill in the methods for the class
36    `printer' (or rather a derived class) without having to worry about
37    the syntax of the intermediate output format.  Consequently, the
38    programming of groff postprocessors is similar to the development of
39    device drivers.
40
41    The prototyping for this file is done in driver.h (and error.h).
42 */
43
44 /* Changes of the 2001 rewrite of this file.
45
46    The interface to the outside and the handling of the global
47    variables was not changed, but internally many necessary changes
48    were performed.
49
50    The main aim for this rewrite is to provide a first step towards
51    making groff fully compatible with classical troff without pain.
52
53    Bugs fixed
54    - Unknown subcommands of `D' and `x' are now ignored like in the
55      classical case, but a warning is issued.  This was also
56      implemented for the other commands.
57    - A warning is emitted if `x stop' is missing.
58    - `DC' and `DE' commands didn't position to the right end after
59      drawing (now they do), see discussion below.
60    - So far, `x stop' was ignored.  Now it terminates the processing
61      of the current intermediate output file like the classical troff.
62    - The command `c' didn't check correctly on white-space.
63    - The environment stack wasn't suitable for the color extensions
64      (replaced by a class).
65    - The old groff parser could only handle a prologue with the first
66      3 lines having a fixed structure, while classical troff specified
67      the sequence of the first 3 commands without further
68      restrictions.  Now the parser is smart about additional
69      white space, comments, and empty lines in the prologue.
70    - The old parser allowed space characters only as syntactical
71      separators, while classical troff had tab characters as well.
72      Now any sequence of tabs and/or spaces is a syntactical
73      separator between commands and/or arguments.
74    - Range checks for numbers implemented.
75
76    New and improved features
77    - The color commands `m' and `DF' are added.
78    - The old color command `Df' is now converted and delegated to `DFg'.
79    - The command `F' is implemented as `use intended file name'.  It
80      checks whether its argument agrees with the file name used so far,
81      otherwise a warning is issued.  Then the new name is remembered
82      and used for the following error messages.
83    - For the positioning after drawing commands, an alternative, easier
84      scheme is provided, but not yet activated; it can be chosen by
85      undefining the preprocessor macro STUPID_DRAWING_POSITIONING.
86      It extends the rule of the classical troff output language in a
87      logical way instead of the rather strange actual positioning.
88      For details, see the discussion below.
89    - For the `D' commands that only set the environment, the calling of
90      pr->send_draw() was removed because this doesn't make sense for
91      the `DF' commands; the (changed) environment is sent with the
92      next command anyway.
93    - Error handling was clearly separated into warnings and fatal.
94    - The error behavior on additional arguments for `D' and `x'
95      commands with a fixed number of arguments was changed from being
96      ignored (former groff) to issue a warning and ignore (now), see
97      skip_line_x().  No fatal was chosen because both string and
98      integer arguments can occur.
99    - The gtroff program issues a trailing dummy integer argument for
100      some drawing commands with an odd number of arguments to make the
101      number of arguments even, e.g. the DC and Dt commands; this is
102      honored now.
103    - All D commands with a variable number of args expect an even
104      number of trailing integer arguments, so fatal on error was
105      implemented.
106    - Disable environment stack and the commands `{' and `}' by making
107      them conditional on macro USE_ENV_STACK; actually, this is
108      undefined by default.  There isn't any known application for these
109      features.
110
111    Cosmetics
112    - Nested `switch' commands are avoided by using more functions.
113      Dangerous 'fall-through's avoided.
114    - Commands and functions are sorted alphabetically (where possible).
115    - Dynamic arrays/buffers are now implemented as container classes.
116    - Some functions had an ugly return structure; this has been
117      streamlined by using classes.
118    - Use standard C math functions for number handling, so getting rid
119      of differences to '0'.
120    - The macro `IntArg' has been created for an easier transition
121      to guaranteed 32 bits integers (`int' is enough for GNU, while
122      ANSI only guarantees `long int' to have a length of 32 bits).
123    - The many usages of type `int' are differentiated by using `Char',
124      `bool', and `IntArg' where appropriate.
125    - To ease the calls of the local utility functions, the parser
126      variables `current_file', `npages', and `current_env'
127      (formerly env) were made global to the file (formerly they were
128      local to the do_file() function)
129    - Various comments were added.
130
131    TODO
132    - Get rid of the stupid drawing positioning.
133    - Can the `Dt' command be completely handled by setting environment
134      within do_file() instead of sending to pr?
135    - Integer arguments must be >= 32 bits, use conditional #define.
136    - Add scaling facility for classical device independence and
137      non-groff devices.  Classical troff output had a quasi device
138      independence by scaling the intermediate output to the resolution
139      of the postprocessor device if different from the one specified
140      with `x T', groff have not.  So implement full quasi device
141      indepedence, including the mapping of the strange classical
142      devices to the postprocessor device (seems to be reasonably
143      easy).
144    - The external, global pointer variables are not optimally handled.
145      - The global variables `current_filename',
146        `current_source_filename', and `current_lineno' are only used for
147        error reporting.  So implement a static class `Error'
148        (`::' calls).
149      - The global `device' is the name used during the formatting
150        process; there should be a new variable for the device name used
151        during the postprocessing.
152   - Implement the B-spline drawing `D~' for all graphical devices.
153   - Make `environment' a class with an overflow check for its members
154     and a delete method to get rid of delete_current_env().
155   - Implement the `EnvStack' to use `new' instead of `malloc'.
156   - The class definitions of this document could go into a new file.
157   - The comments in this section should go to a `Changelog' or some
158     `README' file in this directory.
159 */
160
161 /*
162   Discussion of the positioning by drawing commands
163
164   There was some confusion about the positioning of the graphical
165   pointer at the printout after having executed a `D' command.
166   The classical troff manual of Ossanna & Kernighan specified,
167
168     `The position after a graphical object has been drawn is
169      at its end; for circles and ellipses, the "end" is at the
170      right side.'
171
172   From this, it follows that
173   - all open figures (args, splines, and lines) should position at their
174     final point.
175   - all circles and ellipses should position at their right-most point
176     (as if 2 halves had been drawn).
177   - all closed figures apart from circles and ellipses shouldn't change
178     the position because they return to their origin.
179   - all setting commands should not change position because they do not
180     draw any graphical object.
181
182   In the case of the open figures, this means that the horizontal
183   displacement is the sum of all odd arguments and the vertical offset
184   the sum of all even arguments, called the alternate arguments sum
185   displacement in the following.
186
187   Unfortunately, groff did not implement this simple rule.  The former
188   documentation in groff_out(5) differed from the source code, and
189   neither of them is compatible with the classical rule.
190
191   The former groff_out(5) specified to use the alternative arguments
192   sum displacement for calculating the drawing positioning of
193   non-classical commands, including the `Dt' command (setting-only)
194   and closed polygons.  Applying this to the new groff color commands
195   will lead to disaster.  For their arguments can take large values (>
196   65000).  On low resolution devices, the displacement of such large
197   values will corrupt the display or kill the printer.  So the
198   nonsense specification has come to a natural end anyway.
199
200   The groff source code, however, had no positioning for the
201   setting-only commands (esp. `Dt'), the right-end positioning for
202   outlined circles and ellipses, and the alternative argument sum
203   displacement for all other commands (including filled circles and
204   ellipses).
205
206   The reason why no one seems to have suffered from this mayhem so
207   far is that the graphical objects are usually generated by
208   preprocessors like pic that do not depend on the automatic
209   positioning.  When using the low level `\D' escape sequences or `D'
210   output commands, the strange positionings can be circumvented by
211   absolute positionings or by tricks like `\Z'.
212
213   So doing an exorcism on the strange, incompatible displacements might
214   not harm any existing documents, but will make the usage of the
215   graphical escape sequences and commands natural.
216
217   That's why the rewrite of this file returned to the reasonable,
218   classical specification with its clear end-of-drawing rule that is
219   suitable for all cases.  But a macro STUPID_DRAWING_POSITIONING is
220   provided for testing the funny former behavior.
221
222   The new rule implies the following behavior.
223   - Setting commands (`Dt', `Df', `DF') and polygons (`Dp' and `DP')
224     do not change position now.
225   - Filled circles and ellipses (`DC' and `DE') position at their
226     most right point (outlined ones `Dc' and `De' did this anyway).
227   - As before, all open graphical objects position to their final
228     drawing point (alternate sum of the command arguments).
229
230 */
231
232 #ifndef STUPID_DRAWING_POSITIONING
233 // uncomment next line if all non-classical D commands shall position
234 // to the strange alternate sum of args displacement
235 #define STUPID_DRAWING_POSITIONING
236 #endif
237
238 // Decide whether the commands `{' and `}' for different environments
239 // should be used.
240 #undef USE_ENV_STACK
241
242 #include "driver.h"
243 #include "device.h"
244
245 #include <stdlib.h>
246 #include <errno.h>
247 #include <ctype.h>
248 #include <math.h>
249
250
251 /**********************************************************************
252                            local types
253  **********************************************************************/
254
255 // integer type used in the fields of struct environment (see printer.h)
256 typedef int EnvInt;
257
258 // integer arguments of groff_out commands, must be >= 32 bits
259 typedef int IntArg;
260
261 // color components of groff_out color commands, must be >= 32 bits
262 typedef unsigned int ColorArg;
263
264 // Array for IntArg values.
265 class IntArray {
266   size_t num_allocated;
267   size_t num_stored;
268   IntArg *data;
269 public:
270   IntArray(void);
271   IntArray(const size_t);
272   ~IntArray(void);
273   IntArg operator[](const size_t i) const
274   {
275     if (i >= num_stored)
276       fatal("index out of range");
277     return (IntArg) data[i];
278   }
279   void append(IntArg);
280   IntArg *get_data(void) const { return (IntArg *)data; }
281   size_t len(void) const { return num_stored; }
282 };
283
284 // Characters read from the input queue.
285 class Char {
286   int data;
287 public:
288   Char(void) : data('\0') {}
289   Char(const int c) : data(c) {}
290   bool operator==(char c) const { return (data == c) ? true : false; }
291   bool operator==(int c) const { return (data == c) ? true : false; }
292   bool operator==(const Char c) const
293                   { return (data == c.data) ? true : false; }
294   bool operator!=(char c) const { return !(*this == c); }
295   bool operator!=(int c) const { return !(*this == c); }
296   bool operator!=(const Char c) const { return !(*this == c); }
297   operator int() const { return (int) data; }
298   operator unsigned char() const { return (unsigned char) data; }
299   operator char() const { return (char) data; }
300 };
301
302 // Buffer for string arguments (Char, not char).
303 class StringBuf {
304   size_t num_allocated;
305   size_t num_stored;
306   Char *data;                   // not terminated by '\0'
307 public:
308   StringBuf(void);              // allocate without storing
309   ~StringBuf(void);
310   void append(const Char);      // append character to `data'
311   char *make_string(void);      // return new copy of `data' with '\0'
312   bool is_empty(void) {         // true if none stored
313     return (num_stored > 0) ? false : true;
314   }
315   void reset(void);             // set `num_stored' to 0
316 };
317
318 #ifdef USE_ENV_STACK
319 class EnvStack {
320   environment **data;
321   size_t num_allocated;
322   size_t num_stored;
323 public:
324   EnvStack(void);
325   ~EnvStack(void);
326   environment *pop(void);
327   void push(environment *e);
328 };
329 #endif // USE_ENV_STACK
330
331
332 /**********************************************************************
333                           external variables
334  **********************************************************************/
335
336 // exported as extern by error.h (called from driver.h)
337 // needed for error messages (see ../libgroff/error.cpp)
338 const char *current_filename = 0; // printable name of the current file
339                                   // printable name of current source file
340 const char *current_source_filename = 0;
341 int current_lineno = 0;           // current line number of printout
342
343 // exported as extern by device.h;
344 const char *device = 0;           // cancel former init with literal
345
346 printer *pr;
347
348 // Note:
349 //
350 //   We rely on an implementation of the `new' operator which aborts
351 //   gracefully if it can't allocate memory (e.g. from libgroff/new.cpp).
352
353
354 /**********************************************************************
355                         static local variables
356  **********************************************************************/
357
358 FILE *current_file = 0;         // current input stream for parser
359
360 // npages: number of pages processed so far (including current page),
361 //         _not_ the page number in the printout (can be set with `p').
362 int npages = 0;
363
364 const ColorArg
365 COLORARG_MAX = (ColorArg) 65536U; // == 0xFFFF + 1 == 0x10000
366
367 const IntArg
368 INTARG_MAX = (IntArg) 0x7FFFFFFF; // maximal signed 32 bits number
369
370 // parser environment, created and deleted by each run of do_file()
371 environment *current_env = 0;
372
373 #ifdef USE_ENV_STACK
374 const size_t
375 envp_size = sizeof(environment *);
376 #endif // USE_ENV_STACK
377
378
379 /**********************************************************************
380                         function declarations
381  **********************************************************************/
382
383 // utility functions
384 ColorArg color_from_Df_command(IntArg);
385                                 // transform old color into new
386 void delete_current_env(void);  // delete global var current_env
387 void fatal_command(char);       // abort for invalid command
388 inline Char get_char(void);     // read next character from input stream
389 ColorArg get_color_arg(void);   // read in argument for new color cmds
390 IntArray *get_D_fixed_args(const size_t);
391                                 // read in fixed number of integer
392                                 // arguments
393 IntArray *get_D_fixed_args_odd_dummy(const size_t);
394                                 // read in a fixed number of integer
395                                 // arguments plus optional dummy
396 IntArray *get_D_variable_args(void);
397                                 // variable, even number of int args
398 char *get_extended_arg(void);   // argument for `x X' (several lines)
399 IntArg get_integer_arg(void);   // read in next integer argument
400 IntArray *get_possibly_integer_args();
401                                 // 0 or more integer arguments
402 char *get_string_arg(void);     // read in next string arg, ended by WS
403 inline bool is_space_or_tab(const Char);
404                                 // test on space/tab char
405 Char next_arg_begin(void);      // skip white space on current line
406 Char next_command(void);        // go to next command, evt. diff. line
407 inline bool odd(const int);     // test if integer is odd
408 void position_to_end_of_args(const IntArray * const);
409                                 // positioning after drawing
410 void remember_filename(const char *);
411                                 // set global current_filename
412 void remember_source_filename(const char *);
413                                 // set global current_source_filename
414 void send_draw(const Char, const IntArray * const);
415                                 // call pr->draw
416 void skip_line(void);           // unconditionally skip to next line
417 bool skip_line_checked(void);   // skip line, false if args are left
418 void skip_line_fatal(void);     // skip line, fatal if args are left
419 void skip_line_warn(void);      // skip line, warn if args are left
420 void skip_line_D(void);         // skip line in D commands
421 void skip_line_x(void);         // skip line in x commands
422 void skip_to_end_of_line(void); // skip to the end of the current line
423 inline void unget_char(const Char);
424                                 // restore character onto input
425
426 // parser subcommands
427 void parse_color_command(color *);
428                                 // color sub(sub)commands m and DF
429 void parse_D_command(void);     // graphical subcommands
430 bool parse_x_command(void);     // device controller subcommands
431
432
433 /**********************************************************************
434                          class methods
435  **********************************************************************/
436
437 #ifdef USE_ENV_STACK
438 EnvStack::EnvStack(void)
439 {
440   num_allocated = 4;
441   // allocate pointer to array of num_allocated pointers to environment
442   data = (environment **)malloc(envp_size * num_allocated);
443   if (data == 0)
444     fatal("could not allocate environment data");
445   num_stored = 0;
446 }
447
448 EnvStack::~EnvStack(void)
449 {
450   for (size_t i = 0; i < num_stored; i++)
451     delete data[i];
452   free(data);
453 }
454
455 // return top element from stack and decrease stack pointer
456 //
457 // the calling function must take care of properly deleting the result
458 environment *
459 EnvStack::pop(void)
460 {
461   num_stored--;
462   environment *result = data[num_stored];
463   data[num_stored] = 0;
464   return result;
465 }
466
467 // copy argument and push this onto the stack
468 void
469 EnvStack::push(environment *e)
470 {
471   environment *e_copy = new environment;
472   if (num_stored >= num_allocated) {
473     environment **old_data = data;
474     num_allocated *= 2;
475     data = (environment **)malloc(envp_size * num_allocated);
476     if (data == 0)
477       fatal("could not allocate data");
478     for (size_t i = 0; i < num_stored; i++)
479       data[i] = old_data[i];
480     free(old_data);
481   }
482   e_copy->col = new color;
483   e_copy->fill = new color;
484   *e_copy->col = *e->col;
485   *e_copy->fill = *e->fill;
486   e_copy->fontno = e->fontno;
487   e_copy->height = e->height;
488   e_copy->hpos = e->hpos;
489   e_copy->size = e->size;
490   e_copy->slant = e->slant;
491   e_copy->vpos = e->vpos;
492   data[num_stored] = e_copy;
493   num_stored++;
494 }
495 #endif // USE_ENV_STACK
496
497 IntArray::IntArray(void)
498 {
499   num_allocated = 4;
500   data = new IntArg[num_allocated];
501   num_stored = 0;
502 }
503
504 IntArray::IntArray(const size_t n)
505 {
506   if (n <= 0)
507     fatal("number of integers to be allocated must be > 0");
508   num_allocated = n;
509   data = new IntArg[num_allocated];
510   num_stored = 0;
511 }
512
513 IntArray::~IntArray(void)
514 {
515   a_delete data;
516 }
517
518 void
519 IntArray::append(IntArg x)
520 {
521   if (num_stored >= num_allocated) {
522     IntArg *old_data = data;
523     num_allocated *= 2;
524     data = new IntArg[num_allocated];
525     for (size_t i = 0; i < num_stored; i++)
526       data[i] = old_data[i];
527     a_delete old_data;
528   }
529   data[num_stored] = x;
530   num_stored++;
531 }
532
533 StringBuf::StringBuf(void)
534 {
535   num_stored = 0;
536   num_allocated = 128;
537   data = new Char[num_allocated];
538 }
539
540 StringBuf::~StringBuf(void)
541 {
542   a_delete data;
543 }
544
545 void
546 StringBuf::append(const Char c)
547 {
548   if (num_stored >= num_allocated) {
549     Char *old_data = data;
550     num_allocated *= 2;
551     data = new Char[num_allocated];
552     for (size_t i = 0; i < num_stored; i++)
553       data[i] = old_data[i];
554     a_delete old_data;
555   }
556   data[num_stored] = c;
557   num_stored++;
558 }
559
560 char *
561 StringBuf::make_string(void)
562 {
563   char *result = new char[num_stored + 1];
564   for (size_t i = 0; i < num_stored; i++)
565     result[i] = (char) data[i];
566   result[num_stored] = '\0';
567   return result;
568 }
569
570 void
571 StringBuf::reset(void)
572 {
573   num_stored = 0;
574 }
575
576 /**********************************************************************
577                         utility functions
578  **********************************************************************/
579
580 //////////////////////////////////////////////////////////////////////
581 /* color_from_Df_command:
582    Process the gray shade setting command Df.
583
584    Transform Df style color into DF style color.
585    Df color: 0-1000, 0 is white
586    DF color: 0-65536, 0 is black
587
588    The Df command is obsoleted by command DFg, but kept for
589    compatibility.
590 */
591 ColorArg
592 color_from_Df_command(IntArg Df_gray)
593 {
594   return ColorArg((1000-Df_gray) * COLORARG_MAX / 1000); // scaling
595 }
596
597 //////////////////////////////////////////////////////////////////////
598 /* delete_current_env():
599    Delete global variable current_env and its pointer members.
600
601    This should be a class method of environment.
602 */
603 void delete_current_env(void)
604 {
605   delete current_env->col;
606   delete current_env->fill;
607   delete current_env;
608   current_env = 0;
609 }
610
611 //////////////////////////////////////////////////////////////////////
612 /* fatal_command():
613    Emit error message about invalid command and abort.
614 */
615 void
616 fatal_command(char command)
617 {
618   fatal("`%1' command invalid before first `p' command", command);
619 }
620
621 //////////////////////////////////////////////////////////////////////
622 /* get_char():
623    Retrieve the next character from the input queue.
624
625    Return: The retrieved character (incl. EOF), converted to Char.
626 */
627 inline Char
628 get_char(void)
629 {
630   return (Char) getc(current_file);
631 }
632
633 //////////////////////////////////////////////////////////////////////
634 /* get_color_arg():
635    Retrieve an argument suitable for the color commands m and DF.
636
637    Return: The retrieved color argument.
638 */
639 ColorArg
640 get_color_arg(void)
641 {
642   IntArg x = get_integer_arg();
643   if (x < 0 || x > (IntArg)COLORARG_MAX) {
644     error("color component argument out of range");
645     x = 0;
646   }
647   return (ColorArg) x;
648 }
649
650 //////////////////////////////////////////////////////////////////////
651 /* get_D_fixed_args():
652    Get a fixed number of integer arguments for D commands.
653
654    Fatal if wrong number of arguments.
655    Too many arguments on the line raise a warning.
656    A line skip is done.
657
658    number: In-parameter, the number of arguments to be retrieved.
659    ignore: In-parameter, ignore next argument -- GNU troff always emits
660            pairs of parameters for `D' extensions added by groff.
661            Default is `false'.
662
663    Return: New IntArray containing the arguments.
664 */
665 IntArray *
666 get_D_fixed_args(const size_t number)
667 {
668   if (number <= 0)
669     fatal("requested number of arguments must be > 0");
670   IntArray *args = new IntArray(number);
671   for (size_t i = 0; i < number; i++)
672     args->append(get_integer_arg());
673   skip_line_D();
674   return args;
675 }
676
677 //////////////////////////////////////////////////////////////////////
678 /* get_D_fixed_args_odd_dummy():
679    Get a fixed number of integer arguments for D commands and optionally
680    ignore a dummy integer argument if the requested number is odd.
681
682    The gtroff program adds a dummy argument to some commands to get
683    an even number of arguments.
684    Error if the number of arguments differs from the scheme above.
685    A line skip is done.
686
687    number: In-parameter, the number of arguments to be retrieved.
688
689    Return: New IntArray containing the arguments.
690 */
691 IntArray *
692 get_D_fixed_args_odd_dummy(const size_t number)
693 {
694   if (number <= 0)
695     fatal("requested number of arguments must be > 0");
696   IntArray *args = new IntArray(number);
697   for (size_t i = 0; i < number; i++)
698     args->append(get_integer_arg());
699   if (odd(number)) {
700     IntArray *a = get_possibly_integer_args();
701     if (a->len() > 1)
702       error("too many arguments");
703     delete a;
704   }
705   skip_line_D();
706   return args;
707 }
708
709 //////////////////////////////////////////////////////////////////////
710 /* get_D_variable_args():
711    Get a variable even number of integer arguments for D commands.
712
713    Get as many integer arguments as possible from the rest of the
714    current line.
715    - The arguments are separated by an arbitrary sequence of space or
716      tab characters.
717    - A comment, a newline, or EOF indicates the end of processing.
718    - Error on non-digit characters different from these.
719    - A final line skip is performed (except for EOF).
720
721    Return: New IntArray of the retrieved arguments.
722 */
723 IntArray *
724 get_D_variable_args()
725 {
726   IntArray *args = get_possibly_integer_args();
727   size_t n = args->len();
728   if (n <= 0)
729     error("no arguments found");
730   if (odd(n))
731     error("even number of arguments expected");
732   skip_line_D();
733   return args;
734 }
735
736 //////////////////////////////////////////////////////////////////////
737 /* get_extended_arg():
738    Retrieve extended arg for `x X' command.
739
740    - Skip leading spaces and tabs, error on EOL or newline.
741    - Return everything before the next NL or EOF ('#' is not a comment);
742      as long as the following line starts with '+' this is returned
743      as well, with the '+' replaced by a newline.
744    - Final line skip is always performed.
745
746    Return: Allocated (new) string of retrieved text argument.
747 */
748 char *
749 get_extended_arg(void)
750 {
751   StringBuf buf = StringBuf();
752   Char c = next_arg_begin();
753   while ((int) c != EOF) {
754     if ((int) c == '\n') {
755       current_lineno++;
756       c = get_char();
757       if ((int) c == '+')
758         buf.append((Char) '\n');
759       else {
760         unget_char(c);          // first character of next line
761         break;
762       }
763     }
764     else
765       buf.append(c);
766     c = get_char();
767   }
768   return buf.make_string();
769 }
770
771 //////////////////////////////////////////////////////////////////////
772 /* get_integer_arg(): Retrieve integer argument.
773
774    Skip leading spaces and tabs, collect an optional '-' and all
775    following decimal digits (at least one) up to the next non-digit,
776    which is restored onto the input queue.
777
778    Fatal error on all other situations.
779
780    Return: Retrieved integer.
781 */
782 IntArg
783 get_integer_arg(void)
784 {
785   StringBuf buf = StringBuf();
786   Char c = next_arg_begin();
787   if ((int) c == '-') {
788     buf.append(c);
789     c = get_char();
790   }
791   if (!isdigit((int) c))
792     fatal("integer argument expected");
793   while (isdigit((int) c)) {
794     buf.append(c);
795     c = get_char();
796   }
797   // c is not a digit
798   unget_char(c);
799   char *s = buf.make_string();
800   errno = 0;
801   long int number = strtol(s, 0, 10);
802   if (errno != 0
803       || number > INTARG_MAX || number < -INTARG_MAX) {
804     error("integer argument too large");
805     number = 0;
806   }
807   a_delete s;
808   return (IntArg) number;
809 }
810
811 //////////////////////////////////////////////////////////////////////
812 /* get_possibly_integer_args():
813    Parse the rest of the input line as a list of integer arguments.
814
815    Get as many integer arguments as possible from the rest of the
816    current line, even none.
817    - The arguments are separated by an arbitrary sequence of space or
818      tab characters.
819    - A comment, a newline, or EOF indicates the end of processing.
820    - Error on non-digit characters different from these.
821    - No line skip is performed.
822
823    Return: New IntArray of the retrieved arguments.
824 */
825 IntArray *
826 get_possibly_integer_args()
827 {
828   bool done = false;
829   StringBuf buf = StringBuf();
830   Char c = get_char();
831   IntArray *args = new IntArray();
832   while (!done) {
833     buf.reset();
834     while (is_space_or_tab(c))
835       c = get_char();
836     if (c == '-') {
837       Char c1 = get_char();
838       if (isdigit((int) c1)) {
839         buf.append(c);
840         c = c1;
841       }
842       else
843         unget_char(c1);
844     }
845     while (isdigit((int) c)) {
846       buf.append(c);
847       c = get_char();
848     }
849     if (!buf.is_empty()) {
850       char *s = buf.make_string();
851       errno = 0;
852       long int x = strtol(s, 0, 10);
853       if (errno
854           || x > INTARG_MAX || x < -INTARG_MAX) {
855         error("invalid integer argument, set to 0");
856         x = 0;
857       }
858       args->append((IntArg) x);
859       a_delete s;
860     }
861     // Here, c is not a digit.
862     // Terminate on comment, end of line, or end of file, while
863     // space or tab indicate continuation; otherwise error.
864     switch((int) c) {
865     case '#':
866       skip_to_end_of_line();
867       done = true;
868       break;
869     case '\n':
870       done = true;
871       unget_char(c);
872       break;
873     case EOF:
874       done = true;
875       break;
876     case ' ':
877     case '\t':
878       break;
879     default:
880       error("integer argument expected");
881       done = true;
882       break;
883     }
884   }
885   return args;
886 }
887
888 //////////////////////////////////////////////////////////////////////
889 /* get_string_arg():
890    Retrieve string arg.
891
892    - Skip leading spaces and tabs; error on EOL or newline.
893    - Return all following characters before the next space, tab,
894      newline, or EOF character (in-word '#' is not a comment character).
895    - The terminating space, tab, newline, or EOF character is restored
896      onto the input queue, so no line skip.
897
898    Return: Retrieved string as char *, allocated by 'new'.
899 */
900 char *
901 get_string_arg(void)
902 {
903   StringBuf buf = StringBuf();
904   Char c = next_arg_begin();
905   while (!is_space_or_tab(c)
906          && c != Char('\n') && c != Char(EOF)) {
907     buf.append(c);
908     c = get_char();
909   }
910   unget_char(c);                // restore white space
911   return buf.make_string();
912 }
913
914 //////////////////////////////////////////////////////////////////////
915 /* is_space_or_tab():
916    Test a character if it is a space or tab.
917
918    c: In-parameter, character to be tested.
919
920    Return: True, if c is a space or tab character, false otherwise.
921 */
922 inline bool
923 is_space_or_tab(const Char c)
924 {
925   return (c == Char(' ') || c == Char('\t')) ? true : false;
926 }
927
928 //////////////////////////////////////////////////////////////////////
929 /* next_arg_begin():
930    Return first character of next argument.
931
932    Skip space and tab characters; error on newline or EOF.
933
934    Return: The first character different from these (including '#').
935 */
936 Char
937 next_arg_begin(void)
938 {
939   Char c;
940   while (1) {
941     c = get_char();
942     switch ((int) c) {
943     case ' ':
944     case '\t':
945       break;
946     case '\n':
947     case EOF:
948       error("missing argument");
949       return c;
950     default:                    // first essential character
951       return c;
952     }
953   }
954 }
955
956 //////////////////////////////////////////////////////////////////////
957 /* next_command():
958    Find the first character of the next command.
959
960    Skip spaces, tabs, comments (introduced by #), and newlines.
961
962    Return: The first character different from these (including EOF).
963 */
964 Char
965 next_command(void)
966 {
967   Char c;
968   while (1) {
969     c = get_char();
970     switch ((int) c) {
971     case ' ':
972     case '\t':
973       break;
974     case '\n':
975       current_lineno++;
976       break;
977     case '#':                   // comment
978       skip_line();
979       break;
980     default:                    // EOF or first essential character
981       return c;
982     }
983   }
984 }
985
986 //////////////////////////////////////////////////////////////////////
987 /* odd():
988    Test whether argument is an odd number.
989
990    n: In-parameter, the integer to be tested.
991
992    Return: True if odd, false otherwise.
993 */
994 inline bool
995 odd(const int n)
996 {
997   return ((n & 1) == 1) ? true : false;
998 }
999
1000 //////////////////////////////////////////////////////////////////////
1001 /* position_to_end_of_args():
1002    Move graphical pointer to end of drawn figure.
1003
1004    This is used by the D commands that draw open geometrical figures.
1005    The algorithm simply sums up all horizontal displacements (arguments
1006    with even number) for the horizontal component.  Similarly, the
1007    vertical component is the sum of the odd arguments.
1008
1009    args: In-parameter, the arguments of a former drawing command.
1010 */
1011 void
1012 position_to_end_of_args(const IntArray * const args)
1013 {
1014   size_t i;
1015   const size_t n = args->len();
1016   for (i = 0; i < n; i += 2)
1017     current_env->hpos += (*args)[i];
1018   for (i = 1; i < n; i += 2)
1019     current_env->vpos += (*args)[i];
1020 }
1021
1022 //////////////////////////////////////////////////////////////////////
1023 /* remember_filename():
1024    Set global variable current_filename.
1025
1026    The actual filename is stored in current_filename.  This is used by
1027    the postprocessors, expecting the name "<standard input>" for stdin.
1028
1029    filename: In-out-parameter; is changed to the new value also.
1030 */
1031 void
1032 remember_filename(const char *filename)
1033 {
1034   char *fname;
1035   if (strcmp(filename, "-") == 0)
1036     fname = (char *)"<standard input>";
1037   else
1038     fname = (char *)filename;
1039   size_t len = strlen(fname) + 1;
1040   if (current_filename != 0)
1041     free((char *)current_filename);
1042   current_filename = (const char *)malloc(len);
1043   if (current_filename == 0)
1044     fatal("can't malloc space for filename");
1045   strncpy((char *)current_filename, (char *)fname, len);
1046 }
1047
1048 //////////////////////////////////////////////////////////////////////
1049 /* remember_source_filename():
1050    Set global variable current_source_filename.
1051
1052    The actual filename is stored in current_filename.  This is used by
1053    the postprocessors, expecting the name "<standard input>" for stdin.
1054
1055    filename: In-out-parameter; is changed to the new value also.
1056 */
1057 void
1058 remember_source_filename(const char *filename)
1059 {
1060   char *fname;
1061   if (strcmp(filename, "-") == 0)
1062     fname = (char *)"<standard input>";
1063   else
1064     fname = (char *)filename;
1065   size_t len = strlen(fname) + 1;
1066   if (current_source_filename != 0)
1067     free((char *)current_source_filename);
1068   current_source_filename = (const char *)malloc(len);
1069   if (current_source_filename == 0)
1070     fatal("can't malloc space for filename");
1071   strncpy((char *)current_source_filename, (char *)fname, len);
1072 }
1073
1074 //////////////////////////////////////////////////////////////////////
1075 /* send_draw():
1076    Call draw method of printer class.
1077
1078    subcmd: Letter of actual D subcommand.
1079    args: Array of integer arguments of actual D subcommand.
1080 */
1081 void
1082 send_draw(const Char subcmd, const IntArray * const args)
1083 {
1084   EnvInt n = (EnvInt) args->len();
1085   pr->draw((int) subcmd, (IntArg *)args->get_data(), n, current_env);
1086 }
1087
1088 //////////////////////////////////////////////////////////////////////
1089 /* skip_line():
1090    Go to next line within the input queue.
1091
1092    Skip the rest of the current line, including the newline character.
1093    The global variable current_lineno is adjusted.
1094    No errors are raised.
1095 */
1096 void
1097 skip_line(void)
1098 {
1099   Char c = get_char();
1100   while (1) {
1101     if (c == '\n') {
1102       current_lineno++;
1103       break;
1104     }
1105     if (c == EOF)
1106       break;
1107     c = get_char();
1108   }
1109 }
1110
1111 //////////////////////////////////////////////////////////////////////
1112 /* skip_line_checked ():
1113    Check that there aren't any arguments left on the rest of the line,
1114    then skip line.
1115
1116    Spaces, tabs, and a comment are allowed before newline or EOF.
1117    All other characters raise an error.
1118 */
1119 bool
1120 skip_line_checked(void)
1121 {
1122   bool ok = true;
1123   Char c = get_char();
1124   while (is_space_or_tab(c))
1125     c = get_char();
1126   switch((int) c) {
1127   case '#':                     // comment
1128     skip_line();
1129     break;
1130   case '\n':
1131     current_lineno++;
1132     break;
1133   case EOF:
1134     break;
1135   default:
1136     ok = false;
1137     skip_line();
1138     break;
1139   }
1140   return ok;
1141 }
1142
1143 //////////////////////////////////////////////////////////////////////
1144 /* skip_line_fatal ():
1145    Fatal error if arguments left, otherwise skip line.
1146
1147    Spaces, tabs, and a comment are allowed before newline or EOF.
1148    All other characters trigger the error.
1149 */
1150 void
1151 skip_line_fatal(void)
1152 {
1153   bool ok = skip_line_checked();
1154   if (!ok) {
1155     current_lineno--;
1156     error("too many arguments");
1157     current_lineno++;
1158   }
1159 }
1160
1161 //////////////////////////////////////////////////////////////////////
1162 /* skip_line_warn ():
1163    Skip line, but warn if arguments are left on actual line.
1164
1165    Spaces, tabs, and a comment are allowed before newline or EOF.
1166    All other characters raise a warning
1167 */
1168 void
1169 skip_line_warn(void)
1170 {
1171   bool ok = skip_line_checked();
1172   if (!ok) {
1173     current_lineno--;
1174     warning("too many arguments on current line");
1175     current_lineno++;
1176   }
1177 }
1178
1179 //////////////////////////////////////////////////////////////////////
1180 /* skip_line_D ():
1181    Skip line in `D' commands.
1182
1183    Decide whether in case of an additional argument a fatal error is
1184    raised (the documented classical behavior), only a warning is
1185    issued, or the line is just skipped (former groff behavior).
1186    Actually decided for the warning.
1187 */
1188 void
1189 skip_line_D(void)
1190 {
1191   skip_line_warn();
1192   // or: skip_line_fatal();
1193   // or: skip_line();
1194 }
1195
1196 //////////////////////////////////////////////////////////////////////
1197 /* skip_line_x ():
1198    Skip line in `x' commands.
1199
1200    Decide whether in case of an additional argument a fatal error is
1201    raised (the documented classical behavior), only a warning is
1202    issued, or the line is just skipped (former groff behavior).
1203    Actually decided for the warning.
1204 */
1205 void
1206 skip_line_x(void)
1207 {
1208   skip_line_warn();
1209   // or: skip_line_fatal();
1210   // or: skip_line();
1211 }
1212
1213 //////////////////////////////////////////////////////////////////////
1214 /* skip_to_end_of_line():
1215    Go to the end of the current line.
1216
1217    Skip the rest of the current line, excluding the newline character.
1218    The global variable current_lineno is not changed.
1219    No errors are raised.
1220 */
1221 void
1222 skip_to_end_of_line(void)
1223 {
1224   Char c = get_char();
1225   while (1) {
1226     if (c == '\n') {
1227       unget_char(c);
1228       return;
1229     }
1230     if (c == EOF)
1231       return;
1232     c = get_char();
1233   }
1234 }
1235
1236 //////////////////////////////////////////////////////////////////////
1237 /* unget_char(c):
1238    Restore character c onto input queue.
1239
1240    Write a character back onto the input stream.
1241    EOF is gracefully handled.
1242
1243    c: In-parameter; character to be pushed onto the input queue.
1244 */
1245 inline void
1246 unget_char(const Char c)
1247 {
1248   if (c != EOF) {
1249     int ch = (int) c;
1250     if (ungetc(ch, current_file) == EOF)
1251       fatal("could not unget character");
1252   }
1253 }
1254
1255
1256 /**********************************************************************
1257                        parser subcommands
1258  **********************************************************************/
1259
1260 //////////////////////////////////////////////////////////////////////
1261 /* parse_color_command:
1262    Process the commands m and DF, but not Df.
1263
1264    col: In-out-parameter; the color object to be set, must have
1265         been initialized before.
1266 */
1267 void
1268 parse_color_command(color *col)
1269 {
1270   ColorArg gray = 0;
1271   ColorArg red = 0, green = 0, blue = 0;
1272   ColorArg cyan = 0, magenta = 0, yellow = 0, black = 0;
1273   Char subcmd = next_arg_begin();
1274   switch((int) subcmd) {
1275   case 'c':                     // DFc or mc: CMY
1276     cyan = get_color_arg();
1277     magenta = get_color_arg();
1278     yellow = get_color_arg();
1279     col->set_cmy(cyan, magenta, yellow);
1280     break;
1281   case 'd':                     // DFd or md: set default color
1282     col->set_default();
1283     break;
1284   case 'g':                     // DFg or mg: gray
1285     gray = get_color_arg();
1286     col->set_gray(gray);
1287     break;
1288   case 'k':                     // DFk or mk: CMYK
1289     cyan = get_color_arg();
1290     magenta = get_color_arg();
1291     yellow = get_color_arg();
1292     black = get_color_arg();
1293     col->set_cmyk(cyan, magenta, yellow, black);
1294     break;
1295   case 'r':                     // DFr or mr: RGB
1296     red = get_color_arg();
1297     green = get_color_arg();
1298     blue = get_color_arg();
1299     col->set_rgb(red, green, blue);
1300     break;
1301   default:
1302     error("invalid color scheme `%1'", (int) subcmd);
1303     break;
1304   } // end of color subcommands
1305 }
1306
1307 //////////////////////////////////////////////////////////////////////
1308 /* parse_D_command():
1309    Parse the subcommands of graphical command D.
1310
1311    This is the part of the do_file() parser that scans the graphical
1312    subcommands.
1313    - Error on lacking or wrong arguments.
1314    - Warning on too many arguments.
1315    - Line is always skipped.
1316 */
1317 void
1318 parse_D_command()
1319 {
1320   Char subcmd = next_arg_begin();
1321   switch((int) subcmd) {
1322   case '~':                     // D~: draw B-spline
1323     // actually, this isn't available for some postprocessors
1324     // fall through
1325   default:                      // unknown options are passed to device
1326     {
1327       IntArray *args = get_D_variable_args();
1328       send_draw(subcmd, args);
1329       position_to_end_of_args(args);
1330       delete args;
1331       break;
1332     }
1333   case 'a':                     // Da: draw arc
1334     {
1335       IntArray *args = get_D_fixed_args(4);
1336       send_draw(subcmd, args);
1337       position_to_end_of_args(args);
1338       delete args;
1339       break;
1340     }
1341   case 'c':                     // Dc: draw circle line
1342     {
1343       IntArray *args = get_D_fixed_args(1);
1344       send_draw(subcmd, args);
1345       // move to right end
1346       current_env->hpos += (*args)[0];
1347       delete args;
1348       break;
1349     }
1350   case 'C':                     // DC: draw solid circle
1351     {
1352       IntArray *args = get_D_fixed_args_odd_dummy(1);
1353       send_draw(subcmd, args);
1354       // move to right end
1355       current_env->hpos += (*args)[0];
1356       delete args;
1357       break;
1358     }
1359   case 'e':                     // De: draw ellipse line
1360   case 'E':                     // DE: draw solid ellipse
1361     {
1362       IntArray *args = get_D_fixed_args(2);
1363       send_draw(subcmd, args);
1364       // move to right end
1365       current_env->hpos += (*args)[0];
1366       delete args;
1367       break;
1368     }
1369   case 'f':                     // Df: set fill gray; obsoleted by DFg
1370     {
1371       IntArg arg = get_integer_arg();
1372       if ((arg >= 0) && (arg <= 1000)) {
1373         // convert arg and treat it like DFg
1374         ColorArg gray = color_from_Df_command(arg);
1375         current_env->fill->set_gray(gray);
1376       }
1377       else {
1378         // set fill color to the same value as the current outline color
1379         delete current_env->fill;
1380         current_env->fill = new color(current_env->col);
1381       }
1382       pr->change_fill_color(current_env);
1383       // skip unused `vertical' component (\D'...' always emits pairs)
1384       (void) get_integer_arg();
1385 #   ifdef STUPID_DRAWING_POSITIONING
1386       current_env->hpos += arg;
1387 #   endif
1388       skip_line_x();
1389       break;
1390     }
1391   case 'F':                     // DF: set fill color, several formats
1392     parse_color_command(current_env->fill);
1393     pr->change_fill_color(current_env);
1394     // no positioning (setting-only command)
1395     skip_line_x();
1396     break;
1397   case 'l':                     // Dl: draw line
1398     {
1399       IntArray *args = get_D_fixed_args(2);
1400       send_draw(subcmd, args);
1401       position_to_end_of_args(args);
1402       delete args;
1403       break;
1404     }
1405   case 'p':                     // Dp: draw closed polygon line
1406   case 'P':                     // DP: draw solid closed polygon
1407     {
1408       IntArray *args = get_D_variable_args();
1409       send_draw(subcmd, args);
1410 #   ifdef STUPID_DRAWING_POSITIONING
1411       // final args positioning
1412       position_to_end_of_args(args);
1413 #   endif
1414       delete args;
1415       break;
1416     }
1417   case 't':                     // Dt: set line thickness
1418     {
1419       IntArray *args = get_D_fixed_args_odd_dummy(1);
1420       send_draw(subcmd, args);
1421 #   ifdef STUPID_DRAWING_POSITIONING
1422       // final args positioning
1423       position_to_end_of_args(args);
1424 #   endif
1425       delete args;
1426       break;
1427     }
1428   } // end of D subcommands
1429 }
1430
1431 //////////////////////////////////////////////////////////////////////
1432 /* parse_x_command():
1433    Parse subcommands of the device control command x.
1434
1435    This is the part of the do_file() parser that scans the device
1436    controlling commands.
1437    - Error on duplicate prologue commands.
1438    - Error on wrong or lacking arguments.
1439    - Warning on too many arguments.
1440    - Line is always skipped.
1441
1442    Globals:
1443    - current_env: is set by many subcommands.
1444    - npages: page counting variable
1445
1446    Return: boolean in the meaning of `stopped'
1447            - true if parsing should be stopped (`x stop').
1448            - false if parsing should continue.
1449 */
1450 bool
1451 parse_x_command(void)
1452 {
1453   bool stopped = false;
1454   char *subcmd_str = get_string_arg();
1455   char subcmd = subcmd_str[0];
1456   switch (subcmd) {
1457   case 'f':                     // x font: mount font
1458     {
1459       IntArg n = get_integer_arg();
1460       char *name = get_string_arg();
1461       pr->load_font(n, name);
1462       a_delete name;
1463       skip_line_x();
1464       break;
1465     }
1466   case 'F':                     // x Filename: set filename for errors
1467     {
1468       char *str_arg = get_extended_arg();
1469       if (str_arg == 0)
1470         warning("empty argument for `x F' command");
1471       else {
1472         remember_source_filename(str_arg);
1473         a_delete str_arg;
1474       }
1475       break;
1476     }
1477   case 'H':                     // x Height: set character height
1478     current_env->height = get_integer_arg();
1479     if (current_env->height == current_env->size)
1480       current_env->height = 0;
1481     skip_line_x();
1482     break;
1483   case 'i':                     // x init: initialize device
1484     error("duplicate `x init' command");
1485     skip_line_x();
1486     break;
1487   case 'p':                     // x pause: pause device
1488     skip_line_x();
1489     break;
1490   case 'r':                     // x res: set resolution
1491     error("duplicate `x res' command");
1492     skip_line_x();
1493     break;
1494   case 's':                     // x stop: stop device
1495     stopped = true;
1496     skip_line_x();
1497     break;
1498   case 'S':                     // x Slant: set slant
1499     current_env->slant = get_integer_arg();
1500     skip_line_x();
1501     break;
1502   case 't':                     // x trailer: generate trailer info
1503     skip_line_x();
1504     break;
1505   case 'T':                     // x Typesetter: set typesetter
1506     error("duplicate `x T' command");
1507     skip_line();
1508     break;
1509   case 'u':                     // x underline: from .cu
1510     {
1511       char *str_arg = get_string_arg();
1512       pr->special(str_arg, current_env, 'u');
1513       a_delete str_arg;
1514       skip_line_x();
1515       break;
1516     }
1517   case 'X':                     // x X: send uninterpretedly to device
1518     {
1519       char *str_arg = get_extended_arg(); // includes line skip
1520       if (npages <= 0)
1521         error("`x X' command invalid before first `p' command");
1522       else if (str_arg && (strncmp(str_arg, "devtag:",
1523                                    strlen("devtag:")) == 0))
1524         pr->devtag(str_arg, current_env);
1525       else
1526         pr->special(str_arg, current_env);
1527       a_delete str_arg;
1528       break;
1529     }
1530   default:                      // ignore unknown x commands, but warn
1531     warning("unknown command `x %1'", subcmd);
1532     skip_line();
1533   }
1534   a_delete subcmd_str;
1535   return stopped;
1536 }
1537
1538
1539 /**********************************************************************
1540                      exported part (by driver.h)
1541  **********************************************************************/
1542
1543 ////////////////////////////////////////////////////////////////////////
1544 /* do_file():
1545    Parse and postprocess groff intermediate output.
1546
1547    filename: "-" for standard input, normal file name otherwise
1548 */
1549 void
1550 do_file(const char *filename)
1551 {
1552   Char command;
1553   bool stopped = false;         // terminating condition
1554
1555 #ifdef USE_ENV_STACK
1556   EnvStack env_stack = EnvStack();
1557 #endif // USE_ENV_STACK
1558
1559   // setup of global variables
1560   npages = 0;
1561   current_lineno = 1;
1562   // `pr' is initialized after the prologue.
1563   // `device' is set by the 1st prologue command.
1564
1565   if (filename[0] == '-' && filename[1] == '\0')
1566     current_file = stdin;
1567   else {
1568     errno = 0;
1569     current_file = fopen(filename, "r");
1570     if (errno != 0 || current_file == 0) {
1571       error("can't open file `%1'", filename);
1572       return;
1573     }
1574   }
1575   remember_filename(filename);
1576
1577   if (current_env != 0)
1578     delete_current_env();
1579   current_env = new environment;
1580   current_env->col = new color;
1581   current_env->fill = new color;
1582   current_env->fontno = -1;
1583   current_env->height = 0;
1584   current_env->hpos = -1;
1585   current_env->slant = 0;
1586   current_env->size = 0;
1587   current_env->vpos = -1;
1588
1589   // parsing of prologue (first 3 commands)
1590   {
1591     char *str_arg;
1592     IntArg int_arg;
1593
1594     // 1st command `x T'
1595     command = next_command();   
1596     if ((int) command == EOF)
1597       return;
1598     if ((int) command != 'x')
1599       fatal("the first command must be `x T'");
1600     str_arg = get_string_arg();
1601     if (str_arg[0] != 'T')
1602       fatal("the first command must be `x T'");
1603     a_delete str_arg;
1604     char *tmp_dev = get_string_arg();
1605     if (pr == 0) {              // note: `pr' initialized after prologue
1606       device = tmp_dev;
1607       if (!font::load_desc())
1608         fatal("couldn't load DESC file, can't continue");
1609     }
1610     else {
1611       if (device == 0 || strcmp(device, tmp_dev) != 0)
1612         fatal("all files must use the same device");
1613       a_delete tmp_dev;
1614     }
1615     skip_line_x();              // ignore further arguments
1616     current_env->size = 10 * font::sizescale;
1617
1618     // 2nd command `x res'
1619     command = next_command();
1620     if ((int) command != 'x')
1621       fatal("the second command must be `x res'");
1622     str_arg = get_string_arg();
1623     if (str_arg[0] != 'r')
1624       fatal("the second command must be `x res'");
1625     a_delete str_arg;
1626     int_arg = get_integer_arg();
1627     EnvInt font_res = font::res;
1628     if (int_arg != font_res)
1629       fatal("resolution does not match");
1630     int_arg = get_integer_arg();
1631     if (int_arg != font::hor)
1632       fatal("minimum horizontal motion does not match");
1633     int_arg = get_integer_arg();
1634     if (int_arg != font::vert)
1635       fatal("minimum vertical motion does not match");
1636     skip_line_x();              // ignore further arguments
1637
1638     // 3rd command `x init'
1639     command = next_command();
1640     if (command != 'x')
1641       fatal("the third command must be `x init'");
1642     str_arg = get_string_arg();
1643     if (str_arg[0] != 'i')
1644       fatal("the third command must be `x init'");
1645     a_delete str_arg;
1646     skip_line_x();
1647   }
1648
1649   // parsing of body
1650   if (pr == 0)
1651     pr = make_printer();
1652   while (!stopped) {
1653     command = next_command();
1654     if (command == EOF)
1655       break;
1656     // spaces, tabs, comments, and newlines are skipped here
1657     switch ((int) command) {
1658     case '#':                   // #: comment, ignore up to end of line
1659       skip_line();
1660       break;
1661 #ifdef USE_ENV_STACK
1662     case '{':                   // {: start a new environment (a copy)
1663       env_stack.push(current_env);
1664       break;
1665     case '}':                   // }: pop previous env from stack
1666       delete_current_env();
1667       current_env = env_stack.pop();
1668       break;
1669 #endif // USE_ENV_STACK
1670     case '0':                   // ddc: obsolete jump and print command
1671     case '1':
1672     case '2':
1673     case '3':
1674     case '4':
1675     case '5':
1676     case '6':
1677     case '7':
1678     case '8':
1679     case '9':
1680       {                         // expect 2 digits and a character
1681         char s[3];
1682         Char c = next_arg_begin();
1683         if (npages <= 0)
1684           fatal_command(command);
1685         if (!isdigit((int) c)) {
1686           error("digit expected");
1687           c = 0;
1688         }
1689         s[0] = (char) command;
1690         s[1] = (char) c;
1691         s[2] = '\0';
1692         errno = 0;
1693         long int x = strtol(s, 0, 10);
1694         if (errno != 0)
1695           error("couldn't convert 2 digits");
1696         EnvInt hor_pos = (EnvInt) x;
1697         current_env->hpos += hor_pos;
1698         c = next_arg_begin();
1699         if ((int) c == '\n' || (int) c == EOF)
1700           error("character argument expected");
1701         else
1702           pr->set_ascii_char((unsigned char) c, current_env);
1703         break;
1704       }
1705     case 'c':                   // c: print ascii char without moving
1706       {
1707         if (npages <= 0)
1708           fatal_command(command);
1709         Char c = next_arg_begin();
1710         if (c == '\n' || c == EOF)
1711           error("missing argument to `c' command");
1712         else
1713           pr->set_ascii_char((unsigned char) c, current_env);
1714         break;
1715       }
1716     case 'C':                   // C: print named special character
1717       {
1718         if (npages <= 0)
1719           fatal_command(command);
1720         char *str_arg = get_string_arg();
1721         pr->set_special_char(str_arg, current_env);
1722         a_delete str_arg;
1723         break;
1724       }
1725     case 'D':                   // drawing commands
1726       if (npages <= 0)
1727         fatal_command(command);
1728       parse_D_command();
1729       break;
1730     case 'f':                   // f: set font to number
1731       current_env->fontno = get_integer_arg();
1732       break;
1733     case 'F':                   // F: obsolete, replaced by `x F'
1734       {
1735         char *str_arg = get_extended_arg();
1736         remember_source_filename(str_arg);
1737         a_delete str_arg;
1738         break;
1739       }
1740     case 'h':                   // h: relative horizontal move
1741       current_env->hpos += (EnvInt) get_integer_arg();
1742       break;
1743     case 'H':                   // H: absolute horizontal positioning
1744       current_env->hpos = (EnvInt) get_integer_arg();
1745       break;
1746     case 'm':                   // m: glyph color
1747       parse_color_command(current_env->col);
1748       pr->change_color(current_env);
1749       break;
1750     case 'n':                   // n: print end of line
1751                                 // ignore two arguments (historically)
1752       if (npages <= 0)
1753         fatal_command(command);
1754       pr->end_of_line();
1755       (void) get_integer_arg();
1756       (void) get_integer_arg();
1757       break;
1758     case 'N':                   // N: print char with given int code
1759       if (npages <= 0)
1760         fatal_command(command);
1761       pr->set_numbered_char(get_integer_arg(), current_env);
1762       break;
1763     case 'p':                   // p: start new page with given number
1764       if (npages > 0)
1765         pr->end_page(current_env->vpos);
1766       npages++;                 // increment # of processed pages
1767       pr->begin_page(get_integer_arg());
1768       current_env->vpos = 0;
1769       break;
1770     case 's':                   // s: set point size
1771       current_env->size = get_integer_arg();
1772       if (current_env->height == current_env->size)
1773         current_env->height = 0;
1774       break;
1775     case 't':                   // t: print a text word
1776       {
1777         char c;
1778         if (npages <= 0)
1779           fatal_command(command);
1780         char *str_arg = get_string_arg();
1781         size_t i = 0;
1782         while ((c = str_arg[i++]) != '\0') {
1783           EnvInt w;
1784           pr->set_ascii_char((unsigned char) c, current_env, &w);
1785           current_env->hpos += w;
1786         }
1787         a_delete str_arg;
1788         break;
1789       }
1790     case 'u':                   // u: print spaced word
1791       {
1792         char c;
1793         if (npages <= 0)
1794           fatal_command(command);
1795         EnvInt kern = (EnvInt) get_integer_arg();
1796         char *str_arg = get_string_arg();
1797         size_t i = 0;
1798         while ((c = str_arg[i++]) != '\0') {
1799           EnvInt w;
1800           pr->set_ascii_char((unsigned char) c, current_env, &w);
1801           current_env->hpos += w + kern;
1802         }
1803         a_delete str_arg;
1804         break;
1805       }
1806     case 'v':                   // v: relative vertical move
1807       current_env->vpos += (EnvInt) get_integer_arg();
1808       break;
1809     case 'V':                   // V: absolute vertical positioning
1810       current_env->vpos = (EnvInt) get_integer_arg();
1811       break;
1812     case 'w':                   // w: inform about paddable space
1813       break;
1814     case 'x':                   // device controlling commands
1815       stopped = parse_x_command();
1816       break;
1817     default:
1818       warning("unrecognized command `%1'", (unsigned char) command);
1819       skip_line();
1820       break;
1821     } // end of switch
1822   } // end of while
1823
1824   // end of file reached
1825   if (npages > 0)
1826     pr->end_page(current_env->vpos);
1827   delete pr;
1828   pr = 0;
1829   fclose(current_file);
1830   // If `stopped' is not `true' here then there wasn't any `x stop'.
1831   if (!stopped)
1832     warning("no final `x stop' command");
1833   delete_current_env();
1834 }