home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Professional / OS2PRO194.ISO / os2 / editor / sed / sed.c < prev    next >
C/C++ Source or Header  |  1994-01-31  |  42KB  |  1,850 lines

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