home *** CD-ROM | disk | FTP | other *** search
/ Monster Media 1994 #1 / monster.zip / monster / WIN_NT / SED.ZIP / SED.C < prev    next >
C/C++ Source or Header  |  1993-05-28  |  42KB  |  1,878 lines

  1. /*  GNU SED, a batch stream editor.
  2.     Copyright (C) 1989, 1990, 1991 Free Software Foundation, Inc.
  3.  
  4.     This program is free software; you can redistribute it and/or modify
  5.     it under the terms of the GNU General Public License as published by
  6.     the Free Software Foundation; either version 2, or (at your option)
  7.     any later version.
  8.  
  9.     This program is distributed in the hope that it will be useful,
  10.     but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.     GNU General Public License for more details.
  13.  
  14.     You should have received a copy of the GNU General Public License
  15.     along with this program; if not, write to the Free Software
  16.     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. #ifdef __STDC__
  19. #define VOID void
  20. #else
  21. #define VOID char
  22. #endif
  23.  
  24.  
  25. #define _GNU_SOURCE
  26. #include <ctype.h>
  27. #ifndef isblank
  28. #define isblank(c) ((c) == ' ' || (c) == '\t')
  29. #endif
  30. #include <stdio.h>
  31. #include <sys/types.h>
  32. #include "regex.h"
  33. #include "getopt.h"
  34. #if defined(STDC_HEADERS)
  35. #include <stdlib.h>
  36. #endif
  37. #if HAVE_STRING_H || defined(STDC_HEADERS)
  38. #include <string.h>
  39. #if !defined(STDC_HEADERS)
  40. #include <memory.h>
  41. #endif
  42. #else
  43. #include <strings.h>
  44. #endif
  45.  
  46. #ifndef HAVE_BCOPY
  47. #ifdef HAVE_MEMCPY
  48. #define bcopy(FROM,TO,LEN)  memcpy(TO,FROM,LEN)
  49. #else
  50. void
  51. bcopy (from, to, len)
  52.      char *from;
  53.      char *to;
  54.      int len;
  55. {
  56.   if (from < to)
  57.     {
  58.       from += len - 1;
  59.       to += len - 1;
  60.       while (len--)
  61.     *to-- = *from--;
  62.     }
  63.   else
  64.     while (len--)
  65.       *to++ = *from++;
  66. }
  67.  
  68. #endif
  69. #endif
  70.  
  71. char *version_string = "GNU sed version 1.18";
  72.  
  73. /* Struct vector is used to describe a chunk of a compiled sed program.  
  74.  * There is one vector for the main program, and one for each { } pair,
  75.  * and one for the entire program.  For {} blocks, RETURN_[VI] tells where
  76.  * to continue execution after this VECTOR.
  77.  */
  78.  
  79. struct vector
  80. {
  81.   struct sed_cmd *v;
  82.   int v_length;
  83.   int v_allocated;
  84.   struct vector *return_v;
  85.   int return_i;
  86. };
  87.  
  88.  
  89. /* Goto structure is used to hold both GOTO's and labels.  There are two
  90.  * separate lists, one of goto's, called 'jumps', and one of labels, called
  91.  * 'labels'.
  92.  * the V element points to the descriptor for the program-chunk in which the
  93.  * goto was encountered.
  94.  * the v_index element counts which element of the vector actually IS the
  95.  * goto/label.  The first element of the vector is zero.
  96.  * the NAME element is the null-terminated name of the label.
  97.  * next is the next goto/label in the list. 
  98.  */
  99.  
  100. struct sed_label
  101. {
  102.   struct vector *v;
  103.   int v_index;
  104.   char *name;
  105.   struct sed_label *next;
  106. };
  107.  
  108. /* ADDR_TYPE is zero for a null address,
  109.  *  one if addr_number is valid, or
  110.  * two if addr_regex is valid,
  111.  * three, if the address is '$'
  112.  * Other values are undefined.
  113.  */
  114.  
  115. enum addr_types
  116. {
  117.   addr_is_null = 0,
  118.   addr_is_num = 1,
  119.   addr_is_regex = 2,
  120.   addr_is_last = 3
  121. };
  122.  
  123. struct addr
  124. {
  125.   int addr_type;
  126.   struct re_pattern_buffer *addr_regex;
  127.   int addr_number;
  128. };
  129.  
  130.  
  131. /* Aflags:  If the low order bit is set, a1 has been
  132.  * matched; apply this command until a2 matches.
  133.  * If the next bit is set, apply this command to all
  134.  * lines that DON'T match the address(es).
  135.  */
  136.  
  137. #define A1_MATCHED_BIT    01
  138. #define ADDR_BANG_BIT    02
  139.  
  140. struct sed_cmd
  141. {
  142.   struct addr a1, a2;
  143.   int aflags;
  144.   
  145.   char cmd;
  146.   
  147.   union
  148.     {
  149.       /* This structure is used for a, i, and c commands */
  150.       struct
  151.     {
  152.       char *text;
  153.       int text_len;
  154.     }
  155.       cmd_txt;
  156.       
  157.       /* This is used for b and t commands */
  158.       struct sed_cmd *label;
  159.       
  160.       /* This for r and w commands */
  161.       FILE *io_file;
  162.       
  163.       /* This for the hairy s command */
  164.       /* For the flags var:
  165.      low order bit means the 'g' option was given,
  166.      next bit means the 'p' option was given,
  167.      and the next bit means a 'w' option was given,
  168.      and wio_file contains the file to write to. */
  169.       
  170. #define S_GLOBAL_BIT    01
  171. #define S_PRINT_BIT    02
  172. #define S_WRITE_BIT    04
  173. #define S_NUM_BIT    010
  174.       
  175.       struct
  176.     {
  177.       struct re_pattern_buffer *regx;
  178.       char *replacement;
  179.       int replace_length;
  180.       int flags;
  181.       int numb;
  182.       FILE *wio_file;
  183.     }
  184.       cmd_regex;
  185.       
  186.       /* This for the y command */
  187.       unsigned char *translate;
  188.       
  189.       /* For { */
  190.       struct vector *sub;
  191.       
  192.       /* for t and b */
  193.       struct sed_label *jump;
  194.     } x;
  195. };
  196.  
  197. /* Sed operates a line at a time. */
  198. struct line
  199. {
  200.   char *text;            /* Pointer to line allocated by malloc. */
  201.   int length;            /* Length of text. */
  202.   int alloc;            /* Allocated space for text. */
  203. };
  204.  
  205. /* This structure holds information about files opend by the 'r', 'w',
  206.    and 's///w' commands.  In paticular, it holds the FILE pointer to
  207.    use, the file's name, a flag that is non-zero if the file is being
  208.    read instead of written. */
  209.  
  210. #define NUM_FPS    32
  211. struct
  212.   {
  213.     FILE *phile;
  214.     char *name;
  215.     int readit;
  216.   }
  217.  
  218. file_ptrs[NUM_FPS];
  219.  
  220.  
  221. #if defined(__STDC__)
  222. # define P_(s) s
  223. #else
  224. # define P_(s) ()
  225. #endif
  226.  
  227. void close_files ();
  228. void panic P_ ((char *str,...));
  229. char *__fp_name P_ ((FILE * fp));
  230. FILE *ck_fopen P_ ((char *name, char *mode));
  231. void ck_fwrite P_ ((char *ptr, int size, int nmemb, FILE * stream));
  232. void ck_fclose P_ ((FILE * stream));
  233. VOID *ck_malloc P_ ((int size));
  234. VOID *ck_realloc P_ ((VOID * ptr, int size));
  235. char *ck_strdup P_ ((char *str));
  236. VOID *init_buffer P_ ((void));
  237. void flush_buffer P_ ((VOID * bb));
  238. int size_buffer P_ ((VOID * b));
  239. void add_buffer P_ ((VOID * bb, char *p, int n));
  240. void add1_buffer P_ ((VOID * bb, int ch));
  241. char *get_buffer P_ ((VOID * bb));
  242.  
  243. void compile_string P_ ((char *str));
  244. void compile_file P_ ((char *str));
  245. struct vector *compile_program P_ ((struct vector * vector, int));
  246. void bad_prog P_ ((char *why));
  247. int inchar P_ ((void));
  248. void savchar P_ ((int ch));
  249. int compile_address P_ ((struct addr * addr));
  250. void compile_regex P_ ((int slash));
  251. struct sed_label *setup_jump P_ ((struct sed_label * list, struct sed_cmd * cmd, struct vector * vec));
  252. FILE *compile_filename P_ ((int readit));
  253. void read_file P_ ((char *name));
  254. void execute_program P_ ((struct vector * vec));
  255. int match_address P_ ((struct addr * addr));
  256. int read_pattern_space P_ ((void));
  257. void append_pattern_space P_ ((void));
  258. void line_copy P_ ((struct line * from, struct line * to));
  259. void line_append P_ ((struct line * from, struct line * to));
  260. void str_append P_ ((struct line * to, char *string, int length));
  261. void usage P_ ((int));
  262.  
  263. extern char *myname;
  264.  
  265. /* If set, don't write out the line unless explictly told to */
  266. int no_default_output = 0;
  267.  
  268. /* Current input line # */
  269. int input_line_number = 0;
  270.  
  271. /* Are we on the last input file? */
  272. int last_input_file = 0;
  273.  
  274. /* Have we hit EOF on the last input file?  This is used to decide if we
  275.    have hit the '$' address yet. */
  276. int input_EOF = 0;
  277.  
  278. /* non-zero if a quit command has been executed. */
  279. int quit_cmd = 0;
  280.  
  281. /* Have we done any replacements lately?  This is used by the 't' command. */
  282. int replaced = 0;
  283.  
  284. /* How many '{'s are we executing at the moment */
  285. int program_depth = 0;
  286.  
  287. /* The complete compiled SED program that we are going to run */
  288. struct vector *the_program = 0;
  289.  
  290. /* information about labels and jumps-to-labels.  This is used to do
  291.    the required backpatching after we have compiled all the scripts. */
  292. struct sed_label *jumps = 0;
  293. struct sed_label *labels = 0;
  294.  
  295. /* The 'current' input line. */
  296. struct line line;
  297.  
  298. /* An input line that's been stored by later use by the program */
  299. struct line hold;
  300.  
  301. /* A 'line' to append to the current line when it comes time to write it out */
  302. struct line append;
  303.  
  304.  
  305. /* When we're reading a script command from a string, 'prog_start' and
  306.    'prog_end' point to the beginning and end of the string.  This
  307.    would allow us to compile script strings that contain nulls, except
  308.    that script strings are only read from the command line, which is
  309.    null-terminated */
  310. unsigned char *prog_start;
  311. unsigned char *prog_end;
  312.  
  313. /* When we're reading a script command from a string, 'prog_cur' points
  314.    to the current character in the string */
  315. unsigned char *prog_cur;
  316.  
  317. /* This is the name of the current script file.
  318.    It is used for error messages. */
  319. char *prog_name;
  320.  
  321. /* This is the current script file.  If it is zero, we are reading
  322.    from a string stored in 'prog_start' instead.  If both 'prog_file'
  323.    and 'prog_start' are zero, we're in trouble! */
  324. FILE *prog_file;
  325.  
  326. /* this is the number of the current script line that we're compiling.  It is
  327.    used to give out useful and informative error messages. */
  328. int prog_line = 1;
  329.  
  330. /* This is the file pointer that we're currently reading data from.  It may
  331.    be stdin */
  332. FILE *input_file;
  333.  
  334. /* If this variable is non-zero at exit, one or more of the input
  335.    files couldn't be opened. */
  336.  
  337. int bad_input = 0;
  338.  
  339. /* 'an empty regular expression is equivalent to the last regular
  340.    expression read' so we have to keep track of the last regex used.
  341.    Here's where we store a pointer to it (it is only malloc()'d once) */
  342. struct re_pattern_buffer *last_regex;
  343.  
  344. /* Various error messages we may want to print */
  345. static char ONE_ADDR[] = "Command only uses one address";
  346. static char NO_ADDR[] = "Command doesn't take any addresses";
  347. static char LINE_JUNK[] = "Extra characters after command";
  348. static char BAD_EOF[] = "Unexpected End-of-file";
  349. static char NO_REGEX[] = "No previous regular expression";
  350. static char NO_COMMAND[] = "Missing command";
  351.  
  352. static struct option longopts[] =
  353. {
  354.   {"expression", 1, NULL, 'e'},
  355.   {"file", 1, NULL, 'f'},
  356.   {"quiet", 0, NULL, 'n'},
  357.   {"silent", 0, NULL, 'n'},
  358.   {"version", 0, NULL, 'V'},
  359.   {"help", 0, NULL, 'h'},
  360.   {NULL, 0, NULL, 0}
  361. };
  362.  
  363. void
  364. main (argc, argv)
  365.      int argc;
  366.      char **argv;
  367. {
  368.   int opt;
  369.   char *e_strings = NULL;
  370.   int compiled = 0;
  371.   struct sed_label *go, *lbl;
  372.  
  373.   /* see regex.h */
  374.   re_set_syntax (RE_SYNTAX_POSIX_BASIC);
  375.  
  376.   myname = argv[0];
  377.   while ((opt = getopt_long (argc, argv, "hne:f:V", longopts, (int *) 0))
  378.      != EOF)
  379.     {
  380.       switch (opt)
  381.     {
  382.     case 'n':
  383.       no_default_output = 1;
  384.       break;
  385.     case 'e':
  386.       if (e_strings == NULL)
  387.         {
  388.           e_strings = ck_malloc (strlen (optarg) + 2);
  389.           strcpy (e_strings, optarg);
  390.         }
  391.       else
  392.         {
  393.           e_strings = ck_realloc (e_strings, strlen (e_strings) + strlen (optarg) + 2);
  394.           strcat (e_strings, optarg);
  395.         }
  396.       strcat (e_strings, "\n");
  397.       compiled = 1;
  398.       break;
  399.     case 'f':
  400.       compile_file (optarg);
  401.       compiled = 1;
  402.       break;
  403.     case 'V':
  404.       fprintf (stderr, "%s\n", version_string);
  405.       exit (0);
  406.       break;
  407.     case 'h':
  408.       usage (0);
  409.       break;
  410.     default:
  411.       usage (4);
  412.       break;
  413.     }
  414.     }
  415.   if (e_strings)
  416.     {
  417.       compile_string (e_strings);
  418.       free (e_strings);
  419.     }
  420.   if (!compiled)
  421.     {
  422.       if (optind == argc)
  423.     usage (4);
  424.       compile_string (argv[optind++]);
  425.     }
  426.  
  427.   for (go = jumps; go; go = go->next)
  428.     {
  429.       for (lbl = labels; lbl; lbl = lbl->next)
  430.     if (!strcmp (lbl->name, go->name))
  431.       break;
  432.       if (*go->name && !lbl)
  433.     panic ("Can't find label for jump to '%s'", go->name);
  434.       go->v->v[go->v_index].x.jump = lbl;
  435.     }
  436.  
  437.   line.length = 0;
  438.   line.alloc = 50;
  439.   line.text = ck_malloc (50);
  440.  
  441.   append.length = 0;
  442.   append.alloc = 50;
  443.   append.text = ck_malloc (50);
  444.  
  445.   hold.length = 1;
  446.   hold.alloc = 50;
  447.   hold.text = ck_malloc (50);
  448.   hold.text[0] = '\n';
  449.  
  450.   if (argc <= optind)
  451.     {
  452.       last_input_file++;
  453.       read_file ("-");
  454.     }
  455.   else
  456.     while (optind < argc)
  457.       {
  458.     if (optind == argc - 1)
  459.       last_input_file++;
  460.     read_file (argv[optind]);
  461.     optind++;
  462.     if (quit_cmd)
  463.       break;
  464.       }
  465.   close_files ();
  466.   if (bad_input)
  467.     exit (2);
  468.   exit (0);
  469. }
  470.  
  471. void
  472. close_files ()
  473. {
  474.   int nf;
  475.  
  476.   for (nf = 0; nf < NUM_FPS; nf++)
  477.     {
  478.       if (file_ptrs[nf].phile)
  479.     fclose (file_ptrs[nf].phile);
  480.     }
  481. }
  482.  
  483. /* 'str' is a string (from the command line) that contains a sed command.
  484.    Compile the command, and add it to the end of 'the_program' */
  485. void
  486. compile_string (str)
  487.      char *str;
  488. {
  489.   prog_file = 0;
  490.   prog_line = 0;
  491.   prog_start = prog_cur = (unsigned char *)str;
  492.   prog_end = (unsigned char *)str + strlen (str);
  493.   the_program = compile_program (the_program, prog_line);
  494. }
  495.  
  496. /* 'str' is the name of a file containing sed commands.  Read them in
  497.    and add them to the end of 'the_program' */
  498. void
  499. compile_file (str)
  500.      char *str;
  501. {
  502.   int ch;
  503.  
  504.   prog_start = prog_cur = prog_end = 0;
  505.   prog_name = str;
  506.   prog_line = 1;
  507.   if (str[0] == '-' && str[1] == '\0')
  508.     prog_file = stdin;
  509.   else
  510.     prog_file = ck_fopen (str, "r");
  511.   ch = getc (prog_file);
  512.   if (ch == '#')
  513.     {
  514.       ch = getc (prog_file);
  515.       if (ch == 'n')
  516.     no_default_output++;
  517.       while (ch != EOF && ch != '\n')
  518.     ch = getc (prog_file);
  519.       ++prog_line;
  520.     }
  521.   else if (ch != EOF)
  522.     ungetc (ch, prog_file);
  523.   the_program = compile_program (the_program, prog_line);
  524. }
  525.  
  526. #define MORE_CMDS 40
  527.  
  528. /* Read a program (or a subprogram within '{' '}' pairs) in and store
  529.    the compiled form in *'vector'  Return a pointer to the new vector.  */
  530. struct vector *
  531. compile_program (vector, open_line)
  532.      struct vector *vector;
  533.      int open_line;
  534. {
  535.   struct sed_cmd *cur_cmd;
  536.   int ch = 0;
  537.   int pch;
  538.   int slash;
  539.   VOID *b;
  540.   unsigned char *string;
  541.   int num;
  542.  
  543.   if (!vector)
  544.     {
  545.       vector = (struct vector *) ck_malloc (sizeof (struct vector));
  546.       vector->v = (struct sed_cmd *) ck_malloc (MORE_CMDS * sizeof (struct sed_cmd));
  547.       vector->v_allocated = MORE_CMDS;
  548.       vector->v_length = 0;
  549.       vector->return_v = 0;
  550.       vector->return_i = 0;
  551.     }
  552.   for (;;)
  553.     {
  554.     skip_comment:
  555.       do
  556.     {
  557.       pch = ch;
  558.       ch = inchar ();
  559.       if ((pch == '\\') && (ch == '\n'))
  560.         ch = inchar ();
  561.     }
  562.       while (ch != EOF && (isblank (ch) || ch == '\n' || ch == ';'));
  563.       if (ch == EOF)
  564.     break;
  565.       savchar (ch);
  566.  
  567.       if (vector->v_length == vector->v_allocated)
  568.     {
  569.       vector->v = ((struct sed_cmd *)
  570.                ck_realloc ((VOID *) vector->v,
  571.                    ((vector->v_length + MORE_CMDS)
  572.                     * sizeof (struct sed_cmd))));
  573.       vector->v_allocated += MORE_CMDS;
  574.     }
  575.       cur_cmd = vector->v + vector->v_length;
  576.       vector->v_length++;
  577.  
  578.       cur_cmd->a1.addr_type = 0;
  579.       cur_cmd->a2.addr_type = 0;
  580.       cur_cmd->aflags = 0;
  581.       cur_cmd->cmd = 0;
  582.  
  583.       if (compile_address (&(cur_cmd->a1)))
  584.     {
  585.       ch = inchar ();
  586.       if (ch == ',')
  587.         {
  588.           do
  589.         ch = inchar ();
  590.           while (ch != EOF && isblank (ch));
  591.           savchar (ch);
  592.           if (compile_address (&(cur_cmd->a2)))
  593.         ;
  594.           else
  595.         bad_prog ("Unexpected ','");
  596.         }
  597.       else
  598.         savchar (ch);
  599.     }
  600.       if (cur_cmd->a1.addr_type == addr_is_num
  601.       && cur_cmd->a2.addr_type == addr_is_num
  602.       && cur_cmd->a2.addr_number < cur_cmd->a1.addr_number)
  603.     cur_cmd->a2.addr_number = cur_cmd->a1.addr_number;
  604.  
  605.       ch = inchar ();
  606.       if (ch == EOF)
  607.     bad_prog (NO_COMMAND);
  608.     new_cmd:
  609.       switch (ch)
  610.     {
  611.     case '#':
  612.       if (cur_cmd->a1.addr_type != 0)
  613.         bad_prog (NO_ADDR);
  614.       do
  615.         ch = inchar ();
  616.       while (ch != EOF && ch != '\n');
  617.       vector->v_length--;
  618.       goto skip_comment;
  619.     case '!':
  620.       if (cur_cmd->aflags & ADDR_BANG_BIT)
  621.         bad_prog ("Multiple '!'s");
  622.       cur_cmd->aflags |= ADDR_BANG_BIT;
  623.       do
  624.         ch = inchar ();
  625.       while (ch != EOF && isblank (ch));
  626.       if (ch == EOF)
  627.         bad_prog (NO_COMMAND);
  628. #if 0
  629.       savchar (ch);
  630. #endif
  631.       goto new_cmd;
  632.     case 'a':
  633.     case 'i':
  634.       if (cur_cmd->a2.addr_type != 0)
  635.         bad_prog (ONE_ADDR);
  636.       /* Fall Through */
  637.     case 'c':
  638.       cur_cmd->cmd = ch;
  639.       if (inchar () != '\\' || inchar () != '\n')
  640.         bad_prog (LINE_JUNK);
  641.       b = init_buffer ();
  642.       while ((ch = inchar ()) != EOF && ch != '\n')
  643.         {
  644.           if (ch == '\\')
  645.         ch = inchar ();
  646.           add1_buffer (b, ch);
  647.         }
  648.       if (ch != EOF)
  649.         add1_buffer (b, ch);
  650.       num = size_buffer (b);
  651.       string = (unsigned char *) ck_malloc (num);
  652.       bcopy (get_buffer (b), string, num);
  653.       flush_buffer (b);
  654.       cur_cmd->x.cmd_txt.text_len = num;
  655.       cur_cmd->x.cmd_txt.text = (char *) string;
  656.       break;
  657.     case '{':
  658.       cur_cmd->cmd = ch;
  659.       program_depth++;
  660. #if 0
  661.       while ((ch = inchar ()) != EOF && ch != '\n')
  662.         if (!isblank (ch))
  663.           bad_prog (LINE_JUNK);
  664. #endif
  665.       cur_cmd->x.sub = compile_program ((struct vector *) 0, prog_line);
  666.       /* FOO JF is this the right thing to do?
  667.                almost.  don't forget a return addr.  -t */
  668.       cur_cmd->x.sub->return_v = vector;
  669.       cur_cmd->x.sub->return_i = vector->v_length - 1;
  670.       break;
  671.     case '}':
  672.       if (!program_depth)
  673.         bad_prog ("Unexpected '}'");
  674.       --program_depth;
  675.       /* a return insn for subprograms -t */
  676.       cur_cmd->cmd = ch;
  677.       if (cur_cmd->a1.addr_type != 0)
  678.         bad_prog ("} doesn't want any addresses");
  679.       while ((ch = inchar ()) != EOF && ch != '\n' && ch != ';')
  680.         if (!isblank (ch))
  681.           bad_prog (LINE_JUNK);
  682.       return vector;
  683.     case ':':
  684.       cur_cmd->cmd = ch;
  685.       if (cur_cmd->a1.addr_type != 0)
  686.         bad_prog (": doesn't want any addresses");
  687.       labels = setup_jump (labels, cur_cmd, vector);
  688.       break;
  689.     case 'b':
  690.     case 't':
  691.       cur_cmd->cmd = ch;
  692.       jumps = setup_jump (jumps, cur_cmd, vector);
  693.       break;
  694.     case 'q':
  695.     case '=':
  696.       if (cur_cmd->a2.addr_type)
  697.         bad_prog (ONE_ADDR);
  698.       /* Fall Through */
  699.     case 'd':
  700.     case 'D':
  701.     case 'g':
  702.     case 'G':
  703.     case 'h':
  704.     case 'H':
  705.     case 'l':
  706.     case 'n':
  707.     case 'N':
  708.     case 'p':
  709.     case 'P':
  710.     case 'x':
  711.       cur_cmd->cmd = ch;
  712.       do
  713.         ch = inchar ();
  714.       while (ch != EOF && isblank (ch) && ch != '\n' && ch != ';');
  715.       if (ch != '\n' && ch != ';' && ch != EOF)
  716.         bad_prog (LINE_JUNK);
  717.       break;
  718.  
  719.     case 'r':
  720.       if (cur_cmd->a2.addr_type != 0)
  721.         bad_prog (ONE_ADDR);
  722.       /* FALL THROUGH */
  723.     case 'w':
  724.       cur_cmd->cmd = ch;
  725.       cur_cmd->x.io_file = compile_filename (ch == 'r');
  726.       break;
  727.  
  728.     case 's':
  729.       cur_cmd->cmd = ch;
  730.       slash = inchar ();
  731.       compile_regex (slash);
  732.  
  733.       cur_cmd->x.cmd_regex.regx = last_regex;
  734.  
  735.       b = init_buffer ();
  736.       while (((ch = inchar ()) != EOF) && (ch != slash) && (ch != '\n'))
  737.         {
  738.           if (ch == '\\')
  739.         {
  740.           int ci;
  741.  
  742.           ci = inchar ();
  743.           if (ci != EOF)
  744.             {
  745.               if (ci != '\n')
  746.             add1_buffer (b, ch);
  747.               add1_buffer (b, ci);
  748.             }
  749.         }
  750.           else
  751.         add1_buffer (b, ch);
  752.         }
  753.       if (ch != slash)
  754.         {
  755.           if (ch == '\n' && prog_line > 1)
  756.         --prog_line;
  757.           bad_prog ("Unterminated `s' command");
  758.         }
  759.       cur_cmd->x.cmd_regex.replace_length = size_buffer (b);
  760.       cur_cmd->x.cmd_regex.replacement = ck_malloc (cur_cmd->x.cmd_regex.replace_length);
  761.       bcopy (get_buffer (b), cur_cmd->x.cmd_regex.replacement, cur_cmd->x.cmd_regex.replace_length);
  762.       flush_buffer (b);
  763.  
  764.       cur_cmd->x.cmd_regex.flags = 0;
  765.       cur_cmd->x.cmd_regex.numb = 0;
  766.  
  767.       if (ch == EOF)
  768.         break;
  769.       do
  770.         {
  771.           ch = inchar ();
  772.           switch (ch)
  773.         {
  774.         case 'p':
  775.           if (cur_cmd->x.cmd_regex.flags & S_PRINT_BIT)
  776.             bad_prog ("multiple 'p' options to 's' command");
  777.           cur_cmd->x.cmd_regex.flags |= S_PRINT_BIT;
  778.           break;
  779.         case 'g':
  780.           if (cur_cmd->x.cmd_regex.flags & S_NUM_BIT)
  781.             cur_cmd->x.cmd_regex.flags &= ~S_NUM_BIT;
  782.           if (cur_cmd->x.cmd_regex.flags & S_GLOBAL_BIT)
  783.             bad_prog ("multiple 'g' options to 's' command");
  784.           cur_cmd->x.cmd_regex.flags |= S_GLOBAL_BIT;
  785.           break;
  786.         case 'w':
  787.           cur_cmd->x.cmd_regex.flags |= S_WRITE_BIT;
  788.           cur_cmd->x.cmd_regex.wio_file = compile_filename (0);
  789.           ch = '\n';
  790.           break;
  791.         case '0':
  792.         case '1':
  793.         case '2':
  794.         case '3':
  795.         case '4':
  796.         case '5':
  797.         case '6':
  798.         case '7':
  799.         case '8':
  800.         case '9':
  801.           if (cur_cmd->x.cmd_regex.flags & S_NUM_BIT)
  802.             bad_prog ("multiple number options to 's' command");
  803.           if ((cur_cmd->x.cmd_regex.flags & S_GLOBAL_BIT) == 0)
  804.             cur_cmd->x.cmd_regex.flags |= S_NUM_BIT;
  805.           num = 0;
  806.           while (isdigit (ch))
  807.             {
  808.               num = num * 10 + ch - '0';
  809.               ch = inchar ();
  810.             }
  811.           savchar (ch);
  812.           cur_cmd->x.cmd_regex.numb = num;
  813.           break;
  814.         case '\n':
  815.         case ';':
  816.         case EOF:
  817.           break;
  818.         default:
  819.           bad_prog ("Unknown option to 's'");
  820.           break;
  821.         }
  822.         }
  823.       while (ch != EOF && ch != '\n' && ch != ';');
  824.       if (ch == EOF)
  825.         break;
  826.       break;
  827.  
  828.     case 'y':
  829.       cur_cmd->cmd = ch;
  830.       string = (unsigned char *) ck_malloc (256);
  831.       for (num = 0; num < 256; num++)
  832.         string[num] = num;
  833.       b = init_buffer ();
  834.       slash = inchar ();
  835.       while ((ch = inchar ()) != EOF && ch != slash)
  836.         add1_buffer (b, ch);
  837.       cur_cmd->x.translate = string;
  838.       string = (unsigned char *) get_buffer (b);
  839.       for (num = size_buffer (b); num; --num)
  840.         {
  841.           ch = inchar ();
  842.           if (ch == EOF)
  843.         bad_prog (BAD_EOF);
  844.           if (ch == slash)
  845.         bad_prog ("strings for y command are different lengths");
  846.           cur_cmd->x.translate[*string++] = ch;
  847.         }
  848.       flush_buffer (b);
  849.       if (inchar () != slash || ((ch = inchar ()) != EOF && ch != '\n' && ch != ';'))
  850.         bad_prog (LINE_JUNK);
  851.       break;
  852.  
  853.     default:
  854.       bad_prog ("Unknown command");
  855.     }
  856.     }
  857.   if (program_depth)
  858.     {
  859.       prog_line = open_line;
  860.       bad_prog ("Unmatched `{'");
  861.     }
  862.   return vector;
  863. }
  864.  
  865. /* Complain about a programming error and exit. */
  866. void
  867. bad_prog (why)
  868.      char *why;
  869. {
  870.   if (prog_line > 0)
  871.     fprintf (stderr, "%s: file %s line %d: %s\n",
  872.          myname, prog_name, prog_line, why);
  873.   else
  874.     fprintf (stderr, "%s: %s\n", myname, why);
  875.   exit (1);
  876. }
  877.  
  878. /* Read the next character from the program.  Return EOF if there isn't
  879.    anything to read.  Keep prog_line up to date, so error messages can
  880.    be meaningful. */
  881. int
  882. inchar ()
  883. {
  884.   int ch;
  885.   if (prog_file)
  886.     {
  887.       if (feof (prog_file))
  888.     return EOF;
  889.       else
  890.     ch = getc (prog_file);
  891.     }
  892.   else
  893.     {
  894.       if (!prog_cur)
  895.     return EOF;
  896.       else if (prog_cur == prog_end)
  897.     {
  898.       ch = EOF;
  899.       prog_cur = 0;
  900.     }
  901.       else
  902.     ch = *prog_cur++;
  903.     }
  904.   if ((ch == '\n') && prog_line)
  905.     prog_line++;
  906.   return ch;
  907. }
  908.  
  909. /* unget 'ch' so the next call to inchar will return it.  'ch' must not be
  910.    EOF or anything nasty like that. */
  911. void
  912. savchar (ch)
  913.      int ch;
  914. {
  915.   if (ch == EOF)
  916.     return;
  917.   if (ch == '\n' && prog_line > 1)
  918.     --prog_line;
  919.   if (prog_file)
  920.     ungetc (ch, prog_file);
  921.   else
  922.     *--prog_cur = ch;
  923. }
  924.  
  925.  
  926. /* Try to read an address for a sed command.  If it succeeeds,
  927.    return non-zero and store the resulting address in *'addr'.
  928.    If the input doesn't look like an address read nothing
  929.    and return zero. */
  930. int
  931. compile_address (addr)
  932.      struct addr *addr;
  933. {
  934.   int ch;
  935.   int num;
  936.  
  937.   ch = inchar ();
  938.  
  939.   if (isdigit (ch))
  940.     {
  941.       num = ch - '0';
  942.       while ((ch = inchar ()) != EOF && isdigit (ch))
  943.     num = num * 10 + ch - '0';
  944.       while (ch != EOF && isblank (ch))
  945.     ch = inchar ();
  946.       savchar (ch);
  947.       addr->addr_type = addr_is_num;
  948.       addr->addr_number = num;
  949.       return 1;
  950.     }
  951.   else if (ch == '/' || ch == '\\')
  952.     {
  953.       addr->addr_type = addr_is_regex;
  954.       if (ch == '\\')
  955.     ch = inchar ();
  956.       compile_regex (ch);
  957.       addr->addr_regex = last_regex;
  958.       do
  959.     ch = inchar ();
  960.       while (ch != EOF && isblank (ch));
  961.       savchar (ch);
  962.       return 1;
  963.     }
  964.   else if (ch == '$')
  965.     {
  966.       addr->addr_type = addr_is_last;
  967.       do
  968.     ch = inchar ();
  969.       while (ch != EOF && isblank (ch));
  970.       savchar (ch);
  971.       return 1;
  972.     }
  973.   else
  974.     savchar (ch);
  975.   return 0;
  976. }
  977.  
  978. void
  979. compile_regex (slash)
  980.      int slash;
  981. {
  982.   VOID *b;
  983.   int ch;
  984.   int char_class_pos = -1;
  985.  
  986.   b = init_buffer ();
  987.   while ((ch = inchar ()) != EOF && (ch != slash || (char_class_pos >= 0)))
  988.     {
  989.       if (ch == '^')
  990.     {
  991.       if (size_buffer (b) == 0)
  992.         {
  993.           add1_buffer (b, '\\');
  994.           add1_buffer (b, '`');
  995.         }
  996.       else
  997.         add1_buffer (b, ch);
  998.       continue;
  999.     }
  1000.       else if (ch == '$')
  1001.     {
  1002.       ch = inchar ();
  1003.       savchar (ch);
  1004.       if (ch == slash)
  1005.         {
  1006.           add1_buffer (b, '\\');
  1007.           add1_buffer (b, '\'');
  1008.         }
  1009.       else
  1010.         add1_buffer (b, '$');
  1011.       continue;
  1012.     }
  1013.       else if (ch == '[')
  1014.     {
  1015.       if (char_class_pos < 0)
  1016.         char_class_pos = size_buffer (b);
  1017.       add1_buffer (b, ch);
  1018.       continue;
  1019.     }
  1020.       else if (ch == ']')
  1021.     {
  1022.       add1_buffer (b, ch);
  1023.       {
  1024.         char * regexp = get_buffer (b);
  1025.         int pos = size_buffer (b) - 1;
  1026.         if (!(   (char_class_pos >= 0)
  1027.           && (   (pos == char_class_pos + 1)
  1028.               || (   (pos == char_class_pos + 2)
  1029.               && (regexp[char_class_pos + 1] == '^')))))
  1030.           char_class_pos = -1;
  1031.         continue;
  1032.       }
  1033.     }
  1034.       else if (ch != '\\' || (char_class_pos >= 0))
  1035.     {
  1036.       add1_buffer (b, ch);
  1037.       continue;
  1038.     }
  1039.       ch = inchar ();
  1040.       switch (ch)
  1041.     {
  1042.     case 'n':
  1043.       add1_buffer (b, '\n');
  1044.       break;
  1045. #if 0
  1046.     case 'b':
  1047.       add1_buffer (b, '\b');
  1048.       break;
  1049.     case 'f':
  1050.       add1_buffer (b, '\f');
  1051.       break;
  1052.     case 'r':
  1053.       add1_buffer (b, '\r');
  1054.       break;
  1055.     case 't':
  1056.       add1_buffer (b, '\t');
  1057.       break;
  1058. #endif /* 0 */
  1059.     case EOF:
  1060.       break;
  1061.     default:
  1062.       add1_buffer (b, '\\');
  1063.       add1_buffer (b, ch);
  1064.       break;
  1065.     }
  1066.     }
  1067.   if (ch == EOF)
  1068.     bad_prog (BAD_EOF);
  1069.   if (size_buffer (b))
  1070.     {
  1071.       last_regex = (struct re_pattern_buffer *) ck_malloc (sizeof (struct re_pattern_buffer));
  1072.       last_regex->allocated = size_buffer (b) + 10;
  1073.       last_regex->buffer =
  1074.     (unsigned char *) ck_malloc (last_regex->allocated);
  1075.       last_regex->fastmap = ck_malloc (256);
  1076.       last_regex->translate = 0;
  1077.       re_compile_pattern (get_buffer (b), size_buffer (b), last_regex);
  1078.     }
  1079.   else if (!last_regex)
  1080.     bad_prog (NO_REGEX);
  1081.   flush_buffer (b);
  1082. }
  1083.  
  1084. /* Store a label (or label reference) created by a ':', 'b', or 't'
  1085.    comand so that the jump to/from the lable can be backpatched after
  1086.    compilation is complete */
  1087. struct sed_label *
  1088. setup_jump (list, cmd, vec)
  1089.      struct sed_label *list;
  1090.      struct sed_cmd *cmd;
  1091.      struct vector *vec;
  1092. {
  1093.   struct sed_label *tmp;
  1094.   VOID *b;
  1095.   int ch;
  1096.  
  1097.   b = init_buffer ();
  1098.   while ((ch = inchar ()) != EOF && isblank (ch))
  1099.     ;
  1100.   /* Possible non posixicity. */
  1101.   while (ch != EOF && ch != '\n' && (!isblank (ch)) && ch != ';' && ch != '}')
  1102.     {
  1103.       add1_buffer (b, ch);
  1104.       ch = inchar ();
  1105.     }
  1106.   savchar (ch);
  1107.   add1_buffer (b, '\0');
  1108.   tmp = (struct sed_label *) ck_malloc (sizeof (struct sed_label));
  1109.   tmp->v = vec;
  1110.   tmp->v_index = cmd - vec->v;
  1111.   tmp->name = ck_strdup (get_buffer (b));
  1112.   tmp->next = list;
  1113.   flush_buffer (b);
  1114.   return tmp;
  1115. }
  1116.  
  1117. /* read in a filename for a 'r', 'w', or 's///w' command, and
  1118.    update the internal structure about files.  The file is
  1119.    opened if it isn't already open. */
  1120. FILE *
  1121. compile_filename (readit)
  1122.      int readit;
  1123. {
  1124.   char *file_name;
  1125.   int n;
  1126.   VOID *b;
  1127.   int ch;
  1128.  
  1129.   if (inchar () != ' ')
  1130.     bad_prog ("missing ' ' before filename");
  1131.   b = init_buffer ();
  1132.   while ((ch = inchar ()) != EOF && ch != '\n')
  1133.     add1_buffer (b, ch);
  1134.   add1_buffer (b, '\0');
  1135.   file_name = get_buffer (b);
  1136.   for (n = 0; n < NUM_FPS; n++)
  1137.     {
  1138.       if (!file_ptrs[n].name)
  1139.     break;
  1140.       if (!strcmp (file_ptrs[n].name, file_name))
  1141.     {
  1142.       if (file_ptrs[n].readit != readit)
  1143.         bad_prog ("Can't open file for both reading and writing");
  1144.       flush_buffer (b);
  1145.       return file_ptrs[n].phile;
  1146.     }
  1147.     }
  1148.   if (n < NUM_FPS)
  1149.     {
  1150.       file_ptrs[n].name = ck_strdup (file_name);
  1151.       file_ptrs[n].readit = readit;
  1152.       if (!readit)
  1153.     file_ptrs[n].phile = ck_fopen (file_name, "w");
  1154.       else
  1155.     {
  1156.       file_ptrs[n].phile = ck_fopen (file_name, "r");
  1157.     }
  1158.       flush_buffer (b);
  1159.       return file_ptrs[n].phile;
  1160.     }
  1161.   else
  1162.     {
  1163.       bad_prog ("Hopelessely evil compiled in limit on number of open files.  re-compile sed");
  1164.       return 0;
  1165.     }
  1166. }
  1167.  
  1168. /* Read a file and apply the compiled script to it. */
  1169. void
  1170. read_file (name)
  1171.      char *name;
  1172. {
  1173.   if (*name == '-' && name[1] == '\0')
  1174.     input_file = stdin;
  1175.   else
  1176.     {
  1177.       input_file = fopen (name, "r");
  1178.       if (input_file == 0)
  1179.     {
  1180.       extern int errno;
  1181.       extern char *sys_errlist[];
  1182.       extern int sys_nerr;
  1183.  
  1184.       char *ptr;
  1185.  
  1186.       ptr = ((errno >= 0 && errno < sys_nerr)
  1187.          ? sys_errlist[errno] : "Unknown error code");
  1188.       bad_input++;
  1189.       fprintf (stderr, "%s: can't read %s: %s\n", myname, name, ptr);
  1190.       return;
  1191.     }
  1192.     }
  1193.   while (read_pattern_space ())
  1194.     {
  1195.       execute_program (the_program);
  1196.       if (!no_default_output)
  1197.     ck_fwrite (line.text, 1, line.length, stdout);
  1198.       if (append.length)
  1199.     {
  1200.       ck_fwrite (append.text, 1, append.length, stdout);
  1201.       append.length = 0;
  1202.     }
  1203.       if (quit_cmd)
  1204.     break;
  1205.     }
  1206.   ck_fclose (input_file);
  1207. }
  1208.  
  1209. static char *
  1210. eol_pos (str, len)
  1211.      char *str;
  1212.      int len;
  1213. {
  1214.   while (len--)
  1215.     if (*str++ == '\n')
  1216.       return --str;
  1217.   return --str;
  1218. }
  1219.  
  1220. static void
  1221. chr_copy (dest, src, len)
  1222.      char *dest;
  1223.      char *src;
  1224.      int len;
  1225. {
  1226.   while (len--)
  1227.     *dest++ = *src++;
  1228. }
  1229.  
  1230. /* Execute the program 'vec' on the current input line. */
  1231. static struct re_registers regs =
  1232. {0, 0, 0};
  1233.  
  1234. void
  1235. execute_program (vec)
  1236.      struct vector *vec;
  1237. {
  1238.   struct sed_cmd *cur_cmd;
  1239.   int n;
  1240.   int addr_matched;
  1241.   static int end_cycle;
  1242.  
  1243.   int start;
  1244.   int remain;
  1245.   int offset;
  1246.  
  1247.   static struct line tmp;
  1248.   struct line t;
  1249.   char *rep, *rep_end, *rep_next, *rep_cur;
  1250.  
  1251.   int count;
  1252.   struct vector *restart_vec = vec;
  1253.  
  1254. restart:
  1255.   vec = restart_vec;
  1256.   count = 0;
  1257.  
  1258.   end_cycle = 0;
  1259.  
  1260.   for (cur_cmd = vec->v, n = vec->v_length; n; cur_cmd++, n--)
  1261.     {
  1262.     exe_loop:
  1263.       addr_matched = 0;
  1264.       if (cur_cmd->aflags & A1_MATCHED_BIT)
  1265.     {
  1266.       addr_matched = 1;
  1267.       if (match_address (&(cur_cmd->a2)))
  1268.         cur_cmd->aflags &= ~A1_MATCHED_BIT;
  1269.     }
  1270.       else if (match_address (&(cur_cmd->a1)))
  1271.     {
  1272.       addr_matched = 1;
  1273.       if (cur_cmd->a2.addr_type != addr_is_null)
  1274.         if (   (cur_cmd->a2.addr_type == addr_is_regex)
  1275.         || !match_address (&(cur_cmd->a2)))
  1276.           cur_cmd->aflags |= A1_MATCHED_BIT;
  1277.  
  1278.     }
  1279.       if (cur_cmd->aflags & ADDR_BANG_BIT)
  1280.     addr_matched = !addr_matched;
  1281.       if (!addr_matched)
  1282.     continue;
  1283.       switch (cur_cmd->cmd)
  1284.     {
  1285.     case '{':        /* Execute sub-program */
  1286.       if (cur_cmd->x.sub->v_length)
  1287.         {
  1288.           vec = cur_cmd->x.sub;
  1289.           cur_cmd = vec->v;
  1290.           n = vec->v_length;
  1291.           goto exe_loop;
  1292.         }
  1293.       break;
  1294.  
  1295.     case '}':
  1296.       cur_cmd = vec->return_v->v + vec->return_i;
  1297.       n = vec->return_v->v_length - vec->return_i;
  1298.       vec = vec->return_v;
  1299.       break;
  1300.  
  1301.     case ':':        /* Executing labels is easy. */
  1302.       break;
  1303.  
  1304.     case '=':
  1305.       printf ("%d\n", input_line_number);
  1306.       break;
  1307.  
  1308.     case 'a':
  1309.       while (append.alloc - append.length < cur_cmd->x.cmd_txt.text_len)
  1310.         {
  1311.           append.alloc *= 2;
  1312.           append.text = ck_realloc (append.text, append.alloc);
  1313.         }
  1314.       bcopy (cur_cmd->x.cmd_txt.text,
  1315.          append.text + append.length, cur_cmd->x.cmd_txt.text_len);
  1316.       append.length += cur_cmd->x.cmd_txt.text_len;
  1317.       break;
  1318.  
  1319.     case 'b':
  1320.       if (!cur_cmd->x.jump)
  1321.         end_cycle++;
  1322.       else
  1323.         {
  1324.           struct sed_label *j = cur_cmd->x.jump;
  1325.  
  1326.           n = j->v->v_length - j->v_index;
  1327.           cur_cmd = j->v->v + j->v_index;
  1328.           goto exe_loop;
  1329.         }
  1330.       break;
  1331.  
  1332.     case 'c':
  1333.       line.length = 0;
  1334.       if (!((cur_cmd->aflags & A1_MATCHED_BIT)))
  1335.         ck_fwrite (cur_cmd->x.cmd_txt.text,
  1336.                1, cur_cmd->x.cmd_txt.text_len, stdout);
  1337.       end_cycle++;
  1338.       break;
  1339.  
  1340.     case 'd':
  1341.       line.length = 0;
  1342.       end_cycle++;
  1343.       break;
  1344.  
  1345.     case 'D':
  1346.       {
  1347.         char *tmp;
  1348.         int newlength;
  1349.  
  1350.         tmp = eol_pos (line.text, line.length);
  1351.         newlength = line.length - (tmp - line.text) - 1;
  1352.         if (newlength)
  1353.           {
  1354.         chr_copy (line.text, tmp + 1, newlength);
  1355.         line.length = newlength;
  1356.         goto restart;
  1357.           }
  1358.         line.length = 0;
  1359.         end_cycle++;
  1360.       }
  1361.       break;
  1362.  
  1363.     case 'g':
  1364.       line_copy (&hold, &line);
  1365.       break;
  1366.  
  1367.     case 'G':
  1368.       line_append (&hold, &line);
  1369.       break;
  1370.  
  1371.     case 'h':
  1372.       line_copy (&line, &hold);
  1373.       break;
  1374.  
  1375.     case 'H':
  1376.       line_append (&line, &hold);
  1377.       break;
  1378.  
  1379.     case 'i':
  1380.       ck_fwrite (cur_cmd->x.cmd_txt.text, 1,
  1381.              cur_cmd->x.cmd_txt.text_len, stdout);
  1382.       break;
  1383.  
  1384.     case 'l':
  1385.       {
  1386.         char *tmp;
  1387.         int n;
  1388.         int width = 0;
  1389.  
  1390.         n = line.length;
  1391.         tmp = line.text;
  1392.         while (n--)
  1393.           {
  1394.         /* Skip the trailing newline, if there is one */
  1395.         if (!n && (*tmp == '\n'))
  1396.           break;
  1397.         if (width > 77)
  1398.           {
  1399.             width = 0;
  1400.             putchar ('\n');
  1401.           }
  1402.         if (*tmp == '\\')
  1403.           {
  1404.             printf ("\\\\");
  1405.             width += 2;
  1406.           }
  1407.         else if (isprint (*tmp))
  1408.           {
  1409.             putchar (*tmp);
  1410.             width++;
  1411.           }
  1412.         else
  1413.           switch (*tmp)
  1414.             {
  1415. #if 0
  1416.               /* Should print \00 instead of \0 because (a) POSIX */
  1417.               /* requires it, and (b) this way \01 is unambiguous.  */
  1418.             case '\0':
  1419.               printf ("\\0");
  1420.               width += 2;
  1421.               break;
  1422. #endif
  1423.             case 007:
  1424.               printf ("\\a");
  1425.               width += 2;
  1426.               break;
  1427.             case '\b':
  1428.               printf ("\\b");
  1429.               width += 2;
  1430.               break;
  1431.             case '\f':
  1432.               printf ("\\f");
  1433.               width += 2;
  1434.               break;
  1435.             case '\n':
  1436.               printf ("\\n");
  1437.               width += 2;
  1438.               break;
  1439.             case '\r':
  1440.               printf ("\\r");
  1441.               width += 2;
  1442.               break;
  1443.             case '\t':
  1444.               printf ("\\t");
  1445.               width += 2;
  1446.               break;
  1447.             case '\v':
  1448.               printf ("\\v");
  1449.               width += 2;
  1450.               break;
  1451.             default:
  1452.               printf ("\\%02x", (*tmp) & 0xFF);
  1453.               width += 2;
  1454.               break;
  1455.             }
  1456.         tmp++;
  1457.           }
  1458.         putchar ('\n');
  1459.       }
  1460.       break;
  1461.  
  1462.     case 'n':
  1463.       if (feof (input_file))
  1464.         goto quit;
  1465.       if (!no_default_output)
  1466.         ck_fwrite (line.text, 1, line.length, stdout);
  1467.       read_pattern_space ();
  1468.       break;
  1469.  
  1470.     case 'N':
  1471.       if (feof (input_file))
  1472.         {
  1473.           line.length = 0;
  1474.           goto quit;
  1475.         }
  1476.       append_pattern_space ();
  1477.       break;
  1478.  
  1479.     case 'p':
  1480.       ck_fwrite (line.text, 1, line.length, stdout);
  1481.       break;
  1482.  
  1483.     case 'P':
  1484.       {
  1485.         char *tmp;
  1486.  
  1487.         tmp = eol_pos (line.text, line.length);
  1488.         ck_fwrite (line.text, 1,
  1489.                tmp ? tmp - line.text + 1
  1490.                : line.length, stdout);
  1491.       }
  1492.       break;
  1493.  
  1494.     case 'q':
  1495.     quit:
  1496.       quit_cmd++;
  1497.       end_cycle++;
  1498.       break;
  1499.  
  1500.     case 'r':
  1501.       {
  1502.         int n = 0;
  1503.  
  1504.         if (cur_cmd->x.io_file)
  1505.           {
  1506.         rewind (cur_cmd->x.io_file);
  1507.         do
  1508.           {
  1509.             append.length += n;
  1510.             if (append.length == append.alloc)
  1511.               {
  1512.             append.alloc *= 2;
  1513.             append.text = ck_realloc (append.text, append.alloc);
  1514.               }
  1515.             n = fread (append.text + append.length, sizeof (char),
  1516.                    append.alloc - append.length,
  1517.                    cur_cmd->x.io_file);
  1518.           }
  1519.         while (n > 0);
  1520.         if (ferror (cur_cmd->x.io_file))
  1521.           panic ("Read error on input file to 'r' command");
  1522.           }
  1523.       }
  1524.       break;
  1525.  
  1526.     case 's':
  1527.       {
  1528.         int trail_nl_p = line.text [line.length - 1] == '\n';
  1529.         if (!tmp.alloc)
  1530.           {
  1531.         tmp.alloc = 50;
  1532.         tmp.text = ck_malloc (50);
  1533.           }
  1534.         count = 0;
  1535.         start = 0;
  1536.         remain = line.length - trail_nl_p;
  1537.         tmp.length = 0;
  1538.         rep = cur_cmd->x.cmd_regex.replacement;
  1539.         rep_end = rep + cur_cmd->x.cmd_regex.replace_length;
  1540.         
  1541.         while ((offset = re_search (cur_cmd->x.cmd_regex.regx,
  1542.                     line.text,
  1543.                     line.length - trail_nl_p,
  1544.                     start,
  1545.                     remain,
  1546.                     ®s)) >= 0)
  1547.           {
  1548.         count++;
  1549.         if (offset - start)
  1550.           str_append (&tmp, line.text + start, offset - start);
  1551.         
  1552.         if (cur_cmd->x.cmd_regex.flags & S_NUM_BIT)
  1553.           {
  1554.             if (count != cur_cmd->x.cmd_regex.numb)
  1555.               {
  1556.             int matched = regs.end[0] - regs.start[0];
  1557.             if (!matched) matched = 1;
  1558.             str_append (&tmp, line.text + regs.start[0], matched);
  1559.             start = (offset == regs.end[0]
  1560.                  ? offset + 1 : regs.end[0]);
  1561.             remain = (line.length - trail_nl_p) - start;
  1562.             continue;
  1563.               }
  1564.           }
  1565.         
  1566.         for (rep_next = rep_cur = rep; rep_next < rep_end; rep_next++)
  1567.           {
  1568.             if (*rep_next == '&')
  1569.               {
  1570.             if (rep_next - rep_cur)
  1571.               str_append (&tmp, rep_cur, rep_next - rep_cur);
  1572.             str_append (&tmp, line.text + regs.start[0], regs.end[0] - regs.start[0]);
  1573.             rep_cur = rep_next + 1;
  1574.               }
  1575.             else if (*rep_next == '\\')
  1576.               {
  1577.             if (rep_next - rep_cur)
  1578.               str_append (&tmp, rep_cur, rep_next - rep_cur);
  1579.             rep_next++;
  1580.             if (rep_next != rep_end)
  1581.               {
  1582.                 int n;
  1583.                 
  1584.                 if (*rep_next >= '0' && *rep_next <= '9')
  1585.                   {
  1586.                 n = *rep_next - '0';
  1587.                 str_append (&tmp, line.text + regs.start[n], regs.end[n] - regs.start[n]);
  1588.                   }
  1589.                 else
  1590.                   str_append (&tmp, rep_next, 1);
  1591.               }
  1592.             rep_cur = rep_next + 1;
  1593.               }
  1594.           }
  1595.         if (rep_next - rep_cur)
  1596.           str_append (&tmp, rep_cur, rep_next - rep_cur);
  1597.         if (offset == regs.end[0])
  1598.           {
  1599.             str_append (&tmp, line.text + offset, 1);
  1600.             ++regs.end[0];
  1601.           }
  1602.         start = regs.end[0];
  1603.         
  1604.         remain = (line.length - trail_nl_p) - start;
  1605.         if (remain < 0)
  1606.           break;
  1607.         if (!(cur_cmd->x.cmd_regex.flags & S_GLOBAL_BIT))
  1608.           break;
  1609.           }
  1610.         if (!count)
  1611.           break;
  1612.         replaced = 1;
  1613.         str_append (&tmp, line.text + start, remain + trail_nl_p);
  1614.         t.text = line.text;
  1615.         t.length = line.length;
  1616.         t.alloc = line.alloc;
  1617.         line.text = tmp.text;
  1618.         line.length = tmp.length;
  1619.         line.alloc = tmp.alloc;
  1620.         tmp.text = t.text;
  1621.         tmp.length = t.length;
  1622.         tmp.alloc = t.alloc;
  1623.         if ((cur_cmd->x.cmd_regex.flags & S_WRITE_BIT)
  1624.         && cur_cmd->x.cmd_regex.wio_file)
  1625.           ck_fwrite (line.text, 1, line.length,
  1626.              cur_cmd->x.cmd_regex.wio_file);
  1627.         if (cur_cmd->x.cmd_regex.flags & S_PRINT_BIT)
  1628.           ck_fwrite (line.text, 1, line.length, stdout);
  1629.         break;
  1630.       }
  1631.         
  1632.     case 't':
  1633.       if (replaced)
  1634.         {
  1635.           replaced = 0;
  1636.           if (!cur_cmd->x.jump)
  1637.         end_cycle++;
  1638.           else
  1639.         {
  1640.           struct sed_label *j = cur_cmd->x.jump;
  1641.  
  1642.           n = j->v->v_length - j->v_index;
  1643.           cur_cmd = j->v->v + j->v_index;
  1644.           goto exe_loop;
  1645.         }
  1646.         }
  1647.       break;
  1648.  
  1649.     case 'w':
  1650.       if (cur_cmd->x.io_file)
  1651.         ck_fwrite (line.text, 1, line.length, cur_cmd->x.io_file);
  1652.       break;
  1653.  
  1654.     case 'x':
  1655.       {
  1656.         struct line tmp;
  1657.  
  1658.         tmp = line;
  1659.         line = hold;
  1660.         hold = tmp;
  1661.       }
  1662.       break;
  1663.  
  1664.     case 'y':
  1665.       {
  1666.         unsigned char *p, *e;
  1667.  
  1668.         for (p = (unsigned char *) (line.text), e = p + line.length; p < e; p++)
  1669.           *p = cur_cmd->x.translate[*p];
  1670.       }
  1671.       break;
  1672.  
  1673.     default:
  1674.       panic ("INTERNAL ERROR: Bad cmd %c", cur_cmd->cmd);
  1675.     }
  1676.       if (end_cycle)
  1677.     break;
  1678.     }
  1679. }
  1680.  
  1681.  
  1682. /* Return non-zero if the current line matches the address
  1683.    pointed to by 'addr'. */
  1684. int
  1685. match_address (addr)
  1686.      struct addr *addr;
  1687. {
  1688.   switch (addr->addr_type)
  1689.     {
  1690.     case addr_is_null:
  1691.       return 1;
  1692.     case addr_is_num:
  1693.       return (input_line_number == addr->addr_number);
  1694.  
  1695.     case addr_is_regex:
  1696.       {
  1697.     int trail_nl_p = line.text [line.length - 1] == '\n';
  1698.     return (re_search (addr->addr_regex,
  1699.                line.text,
  1700.                line.length - trail_nl_p,
  1701.                0,
  1702.                line.length - trail_nl_p,
  1703.                (struct re_registers *) 0) >= 0) ? 1 : 0;
  1704.       }
  1705.     case addr_is_last:
  1706.       return (input_EOF) ? 1 : 0;
  1707.  
  1708.     default:
  1709.       panic ("INTERNAL ERROR: bad address type");
  1710.       break;
  1711.     }
  1712.   return -1;
  1713. }
  1714.  
  1715. /* Read in the next line of input, and store it in the
  1716.    pattern space.  Return non-zero if this is the last line of input */
  1717.  
  1718. int
  1719. read_pattern_space ()
  1720. {
  1721.   int n;
  1722.   char *p;
  1723.   int ch;
  1724.  
  1725.   p = line.text;
  1726.   n = line.alloc;
  1727.  
  1728.   if (feof (input_file))
  1729.     return 0;
  1730.   input_line_number++;
  1731.   replaced = 0;
  1732.   for (;;)
  1733.     {
  1734.       if (n == 0)
  1735.     {
  1736.       line.text = ck_realloc (line.text, line.alloc * 2);
  1737.       p = line.text + line.alloc;
  1738.       n = line.alloc;
  1739.       line.alloc *= 2;
  1740.     }
  1741.       ch = getc (input_file);
  1742.       if (ch == EOF)
  1743.     {
  1744.       if (n == line.alloc)
  1745.         return 0;
  1746.       /* *p++ = '\n'; */
  1747.       /* --n; */
  1748.       line.length = line.alloc - n;
  1749.       if (last_input_file)
  1750.         input_EOF++;
  1751.       return 1;
  1752.     }
  1753.       *p++ = ch;
  1754.       --n;
  1755.       if (ch == '\n')
  1756.     {
  1757.       line.length = line.alloc - n;
  1758.       break;
  1759.     }
  1760.     }
  1761.   ch = getc (input_file);
  1762.   if (ch != EOF)
  1763.     ungetc (ch, input_file);
  1764.   else if (last_input_file)
  1765.     input_EOF++;
  1766.   return 1;
  1767. }
  1768.  
  1769. /* Inplement the 'N' command, which appends the next line of input to
  1770.    the pattern space. */
  1771. void
  1772. append_pattern_space ()
  1773. {
  1774.   char *p;
  1775.   int n;
  1776.   int ch;
  1777.  
  1778.   p = line.text + line.length;
  1779.   n = line.alloc - line.length;
  1780.  
  1781.   input_line_number++;
  1782.   replaced = 0;
  1783.   for (;;)
  1784.     {
  1785.       ch = getc (input_file);
  1786.       if (ch == EOF)
  1787.     {
  1788.       if (n == line.alloc)
  1789.         return;
  1790.       /* *p++ = '\n'; */
  1791.       /* --n; */
  1792.       line.length = line.alloc - n;
  1793.       if (last_input_file)
  1794.         input_EOF++;
  1795.       return;
  1796.     }
  1797.       if (n == 0)
  1798.     {
  1799.       line.text = ck_realloc (line.text, line.alloc * 2);
  1800.       p = line.text + line.alloc;
  1801.       n = line.alloc;
  1802.       line.alloc *= 2;
  1803.     }
  1804.       *p++ = ch;
  1805.       --n;
  1806.       if (ch == '\n')
  1807.     {
  1808.       line.length = line.alloc - n;
  1809.       break;
  1810.     }
  1811.     }
  1812.   ch = getc (input_file);
  1813.   if (ch != EOF)
  1814.     ungetc (ch, input_file);
  1815.   else if (last_input_file)
  1816.     input_EOF++;
  1817. }
  1818.  
  1819. /* Copy the contents of the line 'from' into the line 'to'.
  1820.    This destroys the old contents of 'to'.  It will still work
  1821.    if the line 'from' contains nulls. */
  1822. void
  1823. line_copy (from, to)
  1824.      struct line *from, *to;
  1825. {
  1826.   if (from->length > to->alloc)
  1827.     {
  1828.       to->alloc = from->length;
  1829.       to->text = ck_realloc (to->text, to->alloc);
  1830.     }
  1831.   bcopy (from->text, to->text, from->length);
  1832.   to->length = from->length;
  1833. }
  1834.  
  1835. /* Append the contents of the line 'from' to the line 'to'.
  1836.    This routine will work even if the line 'from' contains nulls */
  1837. void
  1838. line_append (from, to)
  1839.      struct line *from, *to;
  1840. {
  1841.   if (from->length > (to->alloc - to->length))
  1842.     {
  1843.       to->alloc += from->length;
  1844.       to->text = ck_realloc (to->text, to->alloc);
  1845.     }
  1846.   bcopy (from->text, to->text + to->length, from->length);
  1847.   to->length += from->length;
  1848. }
  1849.  
  1850. /* Append 'length' bytes from 'string' to the line 'to'
  1851.    This routine *will* append bytes with nulls in them, without
  1852.    failing. */
  1853. void
  1854. str_append (to, string, length)
  1855.      struct line *to;
  1856.      char *string;
  1857.      int length;
  1858. {
  1859.   if (length > to->alloc - to->length)
  1860.     {
  1861.       to->alloc += length;
  1862.       to->text = ck_realloc (to->text, to->alloc);
  1863.     }
  1864.   bcopy (string, to->text + to->length, length);
  1865.   to->length += length;
  1866. }
  1867.  
  1868. void
  1869. usage (status)
  1870.      int status;
  1871. {
  1872.   fprintf (status ? stderr : stdout, "\
  1873. Usage: %s [-nV] [--quiet] [--silent] [--version] [-e script]\n\
  1874.         [-f script-file] [--expression=script] [--file=script-file] [file...]\n",
  1875.        myname);
  1876.   exit (status);
  1877. }
  1878.