69a5e032477864aee304b9192d61fbc0c9c372e0
[oweals/busybox.git] / editors / sed.c
1 /*
2  * sed.c - very minimalist version of sed
3  *
4  * Copyright (C) 1999,2000 by Lineo, inc.
5  * Written by Mark Whitley <markw@lineo.com>, <markw@enol.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  *
21  */
22
23 /*
24         Supported features and commands in this version of sed:
25
26          - comments ('#')
27          - address matching: num|/matchstr/[,num|/matchstr/|$]command
28          - commands: (p)rint, (d)elete, (s)ubstitue (with g & I flags)
29          - edit commands: (a)ppend, (i)nsert, (c)hange
30          - backreferences in substitution expressions (\1, \2...\9)
31          
32          (Note: Specifying an address (range) to match is *optional*; commands
33          default to the whole pattern space if no specific address match was
34          requested.)
35
36         Unsupported features:
37
38          - transliteration (y/source-chars/dest-chars/) (use 'tr')
39          - no support for characters other than the '/' character for regex matches
40          - no pattern space hold space storing / swapping (x, etc.)
41          - no labels / branching (: label, b, t, and friends)
42          - and lots, lots more.
43
44 */
45
46 #include <stdio.h>
47 #include <stdlib.h> /* for realloc() */
48 #include <unistd.h> /* for getopt() */
49 #include <regex.h>
50 #include <string.h> /* for strdup() */
51 #include <errno.h>
52 #include <ctype.h> /* for isspace() */
53 #include "internal.h"
54
55 #define bb_need_full_version
56 #define BB_DECLARE_EXTERN
57 #include "messages.c"
58
59 /* externs */
60 extern int optind; /* in unistd.h */
61 extern char *optarg; /* ditto */
62
63 /* options */
64 static int be_quiet = 0;
65
66 struct sed_cmd {
67
68         /* address storage */
69         int beg_line; /* 'sed 1p'   0 == no begining line, apply commands to all lines */
70         int end_line; /* 'sed 1,3p' 0 == no end line, use only beginning. -1 == $ */
71         regex_t *beg_match; /* sed -e '/match/cmd' */
72         regex_t *end_match; /* sed -e '/match/,/end_match/cmd' */
73
74         /* the command */
75         char cmd; /* p,d,s (add more at your leisure :-) */
76
77         /* substitution command specific fields */
78         regex_t *sub_match; /* sed -e 's/sub_match/replace/' */
79         char *replace; /* sed -e 's/sub_match/replace/' XXX: who will hold the \1 \2 \3s? */
80         unsigned int num_backrefs:4; /* how many back references (\1..\9) */
81                         /* Note:  GNU/POSIX sed does not save more than nine backrefs, so
82                          * we only use 4 bits to hold the number */
83         unsigned int sub_g:1; /* sed -e 's/foo/bar/g' (global) */
84
85         /* edit command (a,i,c) speicific field */
86         char *editline;
87 };
88
89 /* globals */
90 static struct sed_cmd *sed_cmds = NULL; /* growable arrary holding a sequence of sed cmds */
91 static int ncmds = 0; /* number of sed commands */
92
93 /*static char *cur_file = NULL;*/ /* file currently being processed XXX: do I need this? */
94
95 #ifdef BB_FEATURE_CLEAN_UP
96 static void destroy_cmd_strs()
97 {
98         if (sed_cmds == NULL)
99                 return;
100
101         /* destroy all the elements in the array */
102         while (--ncmds >= 0) {
103
104                 if (sed_cmds[ncmds].beg_match) {
105                         regfree(sed_cmds[ncmds].beg_match);
106                         free(sed_cmds[ncmds].beg_match);
107                 }
108                 if (sed_cmds[ncmds].end_match) {
109                         regfree(sed_cmds[ncmds].end_match);
110                         free(sed_cmds[ncmds].end_match);
111                 }
112                 if (sed_cmds[ncmds].sub_match) {
113                         regfree(sed_cmds[ncmds].sub_match);
114                         free(sed_cmds[ncmds].sub_match);
115                 }
116                 if (sed_cmds[ncmds].replace)
117                         free(sed_cmds[ncmds].replace);
118         }
119
120         /* destroy the array */
121         free(sed_cmds);
122         sed_cmds = NULL;
123 }
124 #endif
125
126 #if 0
127 /*
128  * trim_str - trims leading and trailing space from a string
129  * 
130  * Note: This returns a malloc'ed string so you must store and free it
131  * XXX: This should be in the utility.c file.
132  * XXX: This is now obsolete. Maybe it belongs nowhere.
133  */
134 static char *trim_str(const char *str)
135 {
136         int i;
137         char *retstr = strdup(str);
138
139         /* trim leading whitespace */
140         memmove(retstr, &retstr[strspn(retstr, " \n\t\v")], strlen(retstr));
141
142         /* trim trailing whitespace */
143         i = strlen(retstr) - 1;
144         while (isspace(retstr[i]))
145                 i--;
146         retstr[++i] = 0;
147
148         /* Aside: 
149          *
150          * you know, a strrspn() would really be nice cuz then we could say:
151          * 
152          * retstr[strrspn(retstr, " \n\t\v") + 1] = 0;
153          */
154         
155         return retstr;
156 }
157 #endif
158
159 #if 0
160 /*
161  * strrspn - works just like strspn() but goes from right to left instead of
162  * left to right
163  */
164 static size_t strrspn(const char *s, const char *accept)
165 {
166         size_t i = strlen(s);
167
168         while (strchr(accept, s[--i]))
169                 ;
170
171         return i;
172 }
173 #endif
174
175 /*
176  * index_of_next_unescaped_slash - walks left to right through a string
177  * beginning at a specified index and returns the index of the next forward
178  * slash ('/') not preceeded by a backslash ('\').
179  */
180 static int index_of_next_unescaped_slash(const char *str, int idx)
181 {
182         for ( ; str[idx]; idx++) {
183                 if (str[idx] == '/' && str[idx-1] != '\\')
184                         return idx;
185         }
186
187         /* if we make it to here, we've hit the end of the string */
188         return -1;
189 }
190
191 /*
192  * returns the index in the string just past where the address ends.
193  */
194 static int get_address(const char *str, int *line, regex_t **regex)
195 {
196         char *my_str = strdup(str);
197         int idx = 0;
198
199         if (isdigit(my_str[idx])) {
200                 do {
201                         idx++;
202                 } while (isdigit(my_str[idx]));
203                 my_str[idx] = 0;
204                 *line = atoi(my_str);
205         }
206         else if (my_str[idx] == '$') {
207                 *line = -1;
208                 idx++;
209         }
210         else if (my_str[idx] == '/') {
211                 idx = index_of_next_unescaped_slash(my_str, ++idx);
212                 if (idx == -1)
213                         fatalError("unterminated match expression\n");
214                 my_str[idx] = '\0';
215                 *regex = (regex_t *)xmalloc(sizeof(regex_t));
216                 xregcomp(*regex, my_str+1, REG_NEWLINE);
217                 idx++; /* so it points to the next character after the last '/' */
218         }
219         else {
220                 errorMsg("get_address: no address found in string\n"
221                                 "\t(you probably didn't check the string you passed me)\n");
222                 idx = -1;
223         }
224
225         free(my_str);
226         return idx;
227 }
228
229 static char *strdup_substr(const char *str, int start, int end)
230 {
231         int size = end - start + 1;
232         char *newstr = xmalloc(size);
233         memcpy(newstr, str+start, size-1);
234         newstr[size-1] = '\0';
235         return newstr;
236 }
237
238 static int parse_subst_cmd(struct sed_cmd *sed_cmd, const char *substr)
239 {
240         int oldidx, cflags = REG_NEWLINE;
241         char *match;
242         int idx = 0;
243         int j;
244
245         /*
246          * the string that gets passed to this function should look like this:
247          *    s/match/replace/gI
248          *    ||     |        ||
249          *    mandatory       optional
250          *
251          *    (all three of the '/' slashes are mandatory)
252          */
253
254         /* verify that the 's' is followed by a 'slash' */
255         if (substr[++idx] != '/')
256                 fatalError("bad format in substitution expression\n");
257
258         /* save the match string */
259         oldidx = idx+1;
260         idx = index_of_next_unescaped_slash(substr, ++idx);
261         if (idx == -1)
262                 fatalError("bad format in substitution expression\n");
263         match = strdup_substr(substr, oldidx, idx);
264
265         /* determine the number of back references in the match string */
266         /* Note: we compute this here rather than in the do_subst_command()
267          * function to save processor time, at the expense of a little more memory
268          * (4 bits) per sed_cmd */
269         
270         /* sed_cmd->num_backrefs = 0; */ /* XXX: not needed? --apparently not */ 
271         for (j = 0; match[j]; j++) {
272                 /* GNU/POSIX sed does not save more than nine backrefs */
273                 if (match[j] == '\\' && match[j+1] == '(' && sed_cmd->num_backrefs < 9)
274                         sed_cmd->num_backrefs++;
275         }
276
277         /* save the replacement string */
278         oldidx = idx+1;
279         idx = index_of_next_unescaped_slash(substr, ++idx);
280         if (idx == -1)
281                 fatalError("bad format in substitution expression\n");
282         sed_cmd->replace = strdup_substr(substr, oldidx, idx);
283
284         /* process the flags */
285         while (substr[++idx]) {
286                 switch (substr[idx]) {
287                         case 'g':
288                                 sed_cmd->sub_g = 1;
289                                 break;
290                         case 'I':
291                                 cflags |= REG_ICASE;
292                                 break;
293                         default:
294                                 /* any whitespace or semicolon trailing after a s/// is ok */
295                                 if (strchr("; \t\v\n\r", substr[idx]))
296                                         goto out;
297                                 /* else */
298                                 fatalError("bad option in substitution expression\n");
299                 }
300         }
301
302 out:    
303         /* compile the match string into a regex */
304         sed_cmd->sub_match = (regex_t *)xmalloc(sizeof(regex_t));
305         xregcomp(sed_cmd->sub_match, match, cflags);
306         free(match);
307
308         return idx;
309 }
310
311 static int parse_edit_cmd(struct sed_cmd *sed_cmd, const char *editstr)
312 {
313         int idx = 0;
314         int slashes_eaten = 0;
315         char *ptr; /* shorthand */
316
317         /*
318          * the string that gets passed to this function should look like this:
319          *
320          *    need one of these 
321          *    |
322          *    |    this backslash (immediately following the edit command) is mandatory
323          *    |    |
324          *    [aic]\
325          *    TEXT1\
326          *    TEXT2\
327          *    TEXTN
328          *
329          * as soon as we hit a TEXT line that has no trailing '\', we're done.
330          * this means a command like:
331          *
332          * i\
333          * INSERTME
334          *
335          * is a-ok.
336          *
337          */
338
339         if (editstr[1] != '\\' && (editstr[2] != '\n' || editstr[2] != '\r'))
340                 fatalError("bad format in edit expression\n");
341
342         /* store the edit line text */
343         /* make editline big enough to accomodate the extra '\n' we will tack on
344          * to the end */
345         sed_cmd->editline = xmalloc(strlen(&editstr[3]) + 2);
346         strcpy(sed_cmd->editline, &editstr[3]);
347         ptr = sed_cmd->editline;
348
349         /* now we need to go through * and: s/\\[\r\n]$/\n/g on the edit line */
350         while (ptr[idx]) {
351                 while (ptr[idx] != '\\' && (ptr[idx+1] != '\n' || ptr[idx+1] != '\r')) {
352                         idx++;
353                         if (!ptr[idx]) {
354                                 goto out;
355                         }
356                 }
357                 /* move the newline over the '\' before it (effectively eats the '\') */
358                 memmove(&ptr[idx], &ptr[idx+1], strlen(&ptr[idx+1]));
359                 ptr[strlen(ptr)-1] = 0;
360                 slashes_eaten++;
361                 /* substitue \r for \n if needed */
362                 if (ptr[idx] == '\r')
363                         ptr[idx] = '\n';
364         }
365
366 out:
367         ptr[idx] = '\n';
368         ptr[idx+1] = 0;
369
370         /* this accounts for discrepancies between the modified string and the
371          * original string passed in to this function */
372         idx += slashes_eaten;
373
374         /* this accounts for the fact that A) we started at index 3, not at index
375          * 0  and B) that we added an extra '\n' at the end (if you think the next
376          * line should read 'idx += 4' remember, arrays are zero-based) */
377
378         idx += 3;
379
380         return idx;
381 }
382
383 static char *parse_cmd_str(struct sed_cmd *sed_cmd, const char *cmdstr)
384 {
385         int idx = 0;
386
387         /* parse the command
388          * format is: [addr][,addr]cmd
389          *            |----||-----||-|
390          *            part1 part2  part3
391          */
392
393
394         /* first part (if present) is an address: either a number or a /regex/ */
395         if (isdigit(cmdstr[idx]) || cmdstr[idx] == '/')
396                 idx = get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
397
398         /* second part (if present) will begin with a comma */
399         if (cmdstr[idx] == ',')
400                 idx += get_address(&cmdstr[++idx], &sed_cmd->end_line, &sed_cmd->end_match);
401
402         /* last part (mandatory) will be a command */
403         if (cmdstr[idx] == '\0')
404                 fatalError("missing command\n");
405         if (!strchr("pdsaic", cmdstr[idx])) /* <-- XXX add new commands here */
406                 fatalError("invalid command\n");
407         sed_cmd->cmd = cmdstr[idx];
408
409         /* special-case handling for (s)ubstitution */
410         if (sed_cmd->cmd == 's') {
411                 idx += parse_subst_cmd(sed_cmd, &cmdstr[idx]);
412         }
413         /* special-case handling for (a)ppend, (i)nsert, and (c)hange */
414         else if (strchr("aic", cmdstr[idx])) {
415                 if (sed_cmd->end_line || sed_cmd->end_match)
416                         fatalError("only a beginning address can be specified for edit commands\n");
417                 idx += parse_edit_cmd(sed_cmd, &cmdstr[idx]);
418         }
419         /* if it was a single-letter command (such as 'p' or 'd') we need to
420          * increment the index past that command */
421         else
422                 idx++;
423
424         /* give back whatever's left over */
425         return (char *)&cmdstr[idx];
426 }
427
428 static void add_cmd_str(const char *cmdstr)
429 {
430         char *mystr = (char *)cmdstr;
431
432         do {
433
434                 /* trim leading whitespace and semicolons */
435                 memmove(mystr, &mystr[strspn(mystr, "; \n\r\t\v")], strlen(mystr));
436                 /* if we ate the whole thing, that means there was just trailing
437                  * whitespace or a final / no-op semicolon. either way, get out */
438                 if (strlen(mystr) == 0)
439                         return;
440                 /* if this is a comment, jump past it and keep going */
441                 if (mystr[0] == '#') {
442                         mystr = strpbrk(mystr, ";\n\r");
443                         continue;
444                 }
445                 /* grow the array */
446                 sed_cmds = realloc(sed_cmds, sizeof(struct sed_cmd) * (++ncmds));
447                 /* zero new element */
448                 memset(&sed_cmds[ncmds-1], 0, sizeof(struct sed_cmd));
449                 /* load command string into new array element, get remainder */
450                 mystr = parse_cmd_str(&sed_cmds[ncmds-1], mystr);
451
452         } while (mystr && strlen(mystr));
453 }
454
455
456 static void load_cmd_file(char *filename)
457 {
458         FILE *cmdfile;
459         char *line;
460         char *nextline;
461
462         cmdfile = fopen(filename, "r");
463         if (cmdfile == NULL)
464                 fatalError(strerror(errno));
465
466         while ((line = get_line_from_file(cmdfile)) != NULL) {
467                 /* if a line ends with '\' it needs the next line appended to it */
468                 while (line[strlen(line)-2] == '\\' &&
469                                 (nextline = get_line_from_file(cmdfile)) != NULL) {
470                         line = realloc(line, strlen(line) + strlen(nextline) + 1);
471                         strcat(line, nextline);
472                         free(nextline);
473                 }
474                 /* eat trailing newline (if any) --if I don't do this, edit commands
475                  * (aic) will print an extra newline */
476                 if (line[strlen(line)-1] == '\n')
477                         line[strlen(line)-1] = 0;
478                 add_cmd_str(line);
479                 free(line);
480         }
481 }
482
483 static void print_subst_w_backrefs(const char *line, const char *replace, regmatch_t *regmatch)
484 {
485         int i;
486
487         /* go through the replacement string */
488         for (i = 0; replace[i]; i++) {
489                 /* if we find a backreference (\1, \2, etc.) print the backref'ed * text */
490                 if (replace[i] == '\\' && isdigit(replace[i+1])) {
491                         int j;
492                         char tmpstr[2];
493                         int backref;
494                         ++i; /* i now indexes the backref number, instead of the leading slash */
495                         tmpstr[0] = replace[i];
496                         tmpstr[1] = 0;
497                         backref = atoi(tmpstr);
498                         /* print out the text held in regmatch[backref] */
499                         for (j = regmatch[backref].rm_so; j < regmatch[backref].rm_eo; j++)
500                                 fputc(line[j], stdout);
501                 }
502
503                 /* if we find an unescaped '&' print out the whole matched text.
504                  * fortunately, regmatch[0] contains the indicies to the whole matched
505                  * expression (kinda seems like it was designed for just such a
506                  * purpose...) */
507                 else if (replace[i] == '&' && replace[i-1] != '\\') {
508                         int j;
509                         for (j = regmatch[0].rm_so; j < regmatch[0].rm_eo; j++)
510                                 fputc(line[j], stdout);
511                 }
512                 /* nothing special, just print this char of the replacement string to stdout */
513                 else
514                         fputc(replace[i], stdout);
515         }
516 }
517
518 static int do_subst_command(const struct sed_cmd *sed_cmd, const char *line)
519 {
520         int altered = 0;
521
522         /* we only substitute if the substitution 'search' expression matches */
523         if (regexec(sed_cmd->sub_match, line, 0, NULL, 0) == 0) {
524                 regmatch_t *regmatch = xmalloc(sizeof(regmatch_t) * (sed_cmd->num_backrefs+1));
525                 int i;
526                 char *ptr = (char *)line;
527
528                 while (*ptr) {
529                         /* if we can match the search string... */
530                         if (regexec(sed_cmd->sub_match, ptr, sed_cmd->num_backrefs+1, regmatch, 0) == 0) {
531                                 /* print everything before the match, */
532                                 for (i = 0; i < regmatch[0].rm_so; i++)
533                                         fputc(ptr[i], stdout);
534
535                                 /* then print the substitution in its place */
536                                 print_subst_w_backrefs(ptr, sed_cmd->replace, regmatch);
537
538                                 /* then advance past the match */
539                                 ptr += regmatch[0].rm_eo;
540
541                                 /* and flag that something has changed */
542                                 altered++;
543
544                                 /* if we're not doing this globally... */
545                                 if (!sed_cmd->sub_g)
546                                         break;
547                         }
548                         /* if we COULD NOT match the search string (meaning we've gone past
549                          * all previous instances), get out */
550                         else
551                                 break;
552                 }
553
554                 /* is there anything left to print? */
555                 if (*ptr) 
556                         fputs(ptr, stdout);
557
558                 /* cleanup */
559                 free(regmatch);
560         }
561
562         return altered;
563 }
564
565 static int do_sed_command(const struct sed_cmd *sed_cmd, const char *line) 
566 {
567         int altered = 0;
568
569         switch (sed_cmd->cmd) {
570
571                 case 'p':
572                         fputs(line, stdout);
573                         break;
574
575                 case 'd':
576                         altered++;
577                         break;
578
579                 case 's':
580                         altered = do_subst_command(sed_cmd, line);
581                         break;
582
583                 case 'a':
584                         fputs(line, stdout);
585                         fputs(sed_cmd->editline, stdout);
586                         altered++;
587                         break;
588
589                 case 'i':
590                         fputs(sed_cmd->editline, stdout);
591                         break;
592
593                 case 'c':
594                         fputs(sed_cmd->editline, stdout);
595                         altered++;
596                         break;
597         }
598
599         return altered;
600 }
601
602 static void process_file(FILE *file)
603 {
604         char *line = NULL;
605         static int linenum = 0; /* GNU sed does not restart counting lines at EOF */
606         unsigned int still_in_range = 0;
607         int line_altered;
608         int i;
609
610         /* go through every line in the file */
611         while ((line = get_line_from_file(file)) != NULL) {
612
613                 linenum++;
614                 line_altered = 0;
615
616                 /* for every line, go through all the commands */
617                 for (i = 0; i < ncmds; i++) {
618
619                         /* are we acting on a range of matched lines? */
620                         if (sed_cmds[i].beg_match && sed_cmds[i].end_match) {
621                                 if (still_in_range || regexec(sed_cmds[i].beg_match, line, 0, NULL, 0) == 0) {
622                                         line_altered += do_sed_command(&sed_cmds[i], line);
623                                         still_in_range = 1; 
624                                         if (regexec(sed_cmds[i].end_match, line, 0, NULL, 0) == 0)
625                                                 still_in_range = 0;
626                                 }
627                         }
628
629                         /* are we trying to match a single line? */
630                         else if (sed_cmds[i].beg_match) {
631                                 if (regexec(sed_cmds[i].beg_match, line, 0, NULL, 0) == 0)
632                                         line_altered += do_sed_command(&sed_cmds[i], line);
633                         }
634
635                         /* are we acting on a range of line numbers? */
636                         else if (sed_cmds[i].beg_line > 0 && sed_cmds[i].end_line > 0) {
637                                 if (linenum >= sed_cmds[i].beg_line && linenum <= sed_cmds[i].end_line)
638                                         line_altered += do_sed_command(&sed_cmds[i], line);
639                         }
640
641                         /* are we acting on a specified line number */
642                         else if (sed_cmds[i].beg_line > 0) {
643                                 if (linenum == sed_cmds[i].beg_line)
644                                         line_altered += do_sed_command(&sed_cmds[i], line);
645                         }
646
647                         /* not acting on matches or line numbers. act on every line */
648                         else 
649                                 line_altered += do_sed_command(&sed_cmds[i], line);
650
651                 }
652
653                 /* we will print the line unless we were told to be quiet or if the
654                  * line was altered (via a 'd'elete or 's'ubstitution) */
655                 if (!be_quiet && !line_altered)
656                         fputs(line, stdout);
657
658                 free(line);
659         }
660 }
661
662 extern int sed_main(int argc, char **argv)
663 {
664         int opt;
665
666 #ifdef BB_FEATURE_CLEAN_UP
667         /* destroy command strings on exit */
668         if (atexit(destroy_cmd_strs) == -1) {
669                 perror("sed");
670                 exit(1);
671         }
672 #endif
673
674         /* do normal option parsing */
675         while ((opt = getopt(argc, argv, "hne:f:")) > 0) {
676                 switch (opt) {
677                         case 'h':
678                                 usage(sed_usage);
679                                 break;
680                         case 'n':
681                                 be_quiet++;
682                                 break;
683                         case 'e':
684                                 add_cmd_str(optarg);
685                                 break;
686                         case 'f': 
687                                 load_cmd_file(optarg);
688                                 break;
689                 }
690         }
691
692         /* if we didn't get a pattern from a -e and no command file was specified,
693          * argv[optind] should be the pattern. no pattern, no worky */
694         if (ncmds == 0) {
695                 if (argv[optind] == NULL)
696                         usage(sed_usage);
697                 else {
698                         add_cmd_str(argv[optind]);
699                         optind++;
700                 }
701         }
702
703
704         /* argv[(optind)..(argc-1)] should be names of file to process. If no
705          * files were specified or '-' was specified, take input from stdin.
706          * Otherwise, we process all the files specified. */
707         if (argv[optind] == NULL || (strcmp(argv[optind], "-") == 0)) {
708                 process_file(stdin);
709         }
710         else {
711                 int i;
712                 FILE *file;
713                 for (i = optind; i < argc; i++) {
714                         file = fopen(argv[i], "r");
715                         if (file == NULL) {
716                                 errorMsg("%s: %s\n", argv[i], strerror(errno));
717                         } else {
718                                 process_file(file);
719                                 fclose(file);
720                         }
721                 }
722         }
723         
724         return 0;
725 }