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