1 /* vi: set sw=4 ts=4: */
3 * Copyright (c) 2002 by David I. Bell
4 * Permission is granted to use, distribute, or modify this source,
5 * provided that this copyright notice remains intact.
7 * The "ed" built-in command (much simplified)
20 #define searchString bb_common_bufsiz1
23 USERSIZE = sizeof(searchString) > 1024 ? 1024
24 : sizeof(searchString) - 1, /* max line length typed in by user */
25 INITBUF_SIZE = 1024, /* initial buffer size */
41 #define G (*ptr_to_globals)
42 #define curLine (G.curLine )
43 #define bufBase (G.bufBase )
44 #define bufPtr (G.bufPtr )
45 #define fileName (G.fileName )
46 #define curNum (G.curNum )
47 #define lastNum (G.lastNum )
48 #define bufUsed (G.bufUsed )
49 #define bufSize (G.bufSize )
50 #define dirty (G.dirty )
51 #define lines (G.lines )
52 #define marks (G.marks )
53 #define INIT_G() do { \
54 PTR_TO_GLOBALS = xzalloc(sizeof(G)); \
58 static void doCommands(void);
59 static void subCommand(const char *cmd, int num1, int num2);
60 static int getNum(const char **retcp, smallint *retHaveNum, int *retNum);
61 static int setCurNum(int num);
62 static void addLines(int num);
63 static int insertLine(int num, const char *data, int len);
64 static void deleteLines(int num1, int num2);
65 static int printLines(int num1, int num2, int expandFlag);
66 static int writeLines(const char *file, int num1, int num2);
67 static int readLines(const char *file, int num);
68 static int searchLines(const char *str, int num1, int num2);
69 static LINE *findLine(int num);
70 static int findString(const LINE *lp, const char * str, int len, int offset);
73 static int bad_nums(int num1, int num2, const char *for_what)
75 if ((num1 < 1) || (num2 > lastNum) || (num1 > num2)) {
76 bb_error_msg("bad line range for %s", for_what);
83 static char *skip_blank(const char *cp)
85 // NB: fix comment in skip_whitespace!
92 int ed_main(int argc, char **argv);
93 int ed_main(int argc, char **argv)
97 bufSize = INITBUF_SIZE;
98 bufBase = xmalloc(bufSize);
104 fileName = xstrdup(argv[1]);
105 if (!readLines(fileName, 1)) {
118 * Read commands until we are told to stop.
120 static void doCommands(void)
123 char *endbuf, *newname, buf[USERSIZE];
125 smallint have1, have2;
128 // NB: fix comment in lineedit.c!
130 * -1 on read errors or EOF, or on bare Ctrl-D.
132 * >0 length of input string, including terminating '\n'
134 len = read_line_input(": ", buf, sizeof(buf), NULL);
137 endbuf = &buf[len - 1];
138 while ((endbuf > buf) && isblank(endbuf[-1]))
142 cp = skip_blank(buf);
146 if ((curNum == 0) && (lastNum > 0)) {
148 curLine = lines.next;
151 if (!getNum(&cp, &have1, &num1))
158 if (!getNum(&cp, &have2, &num2))
178 deleteLines(num1, num2);
183 deleteLines(num1, num2);
187 if (*cp && !isblank(*cp)) {
188 bb_error_msg("bad file command");
194 printf("\"%s\"\n", fileName);
196 printf("No file name\n");
199 newname = strdup(cp);
200 if (newname == NULL) {
201 bb_error_msg("no memory for file name");
214 if ((*cp < 'a') || (*cp > 'z') || cp[1]) {
215 bb_error_msg("bad mark name");
218 marks[*cp - 'a'] = num2;
222 printLines(num1, num2, TRUE);
226 printLines(num1, num2, FALSE);
232 bb_error_msg("bad quit command");
237 len = read_line_input("Really quit? ", buf, 16, NULL);
238 /* read error/EOF - no way to continue */
241 cp = skip_blank(buf);
242 if ((*cp | 0x20) == 'y') /* Y or y */
247 if (*cp && !isblank(*cp)) {
248 bb_error_msg("bad read command");
253 bb_error_msg("no file name");
258 if (readLines(cp, num1 + 1))
260 if (fileName == NULL)
261 fileName = strdup(cp);
265 subCommand(cp, num1, num2);
269 if (*cp && !isblank(*cp)) {
270 bb_error_msg("bad write command");
281 bb_error_msg("no file name specified");
284 writeLines(cp, num1, num2);
290 printLines(curNum - 21, curNum, FALSE);
293 printLines(curNum - 11, curNum + 10, FALSE);
296 printLines(curNum, curNum + 21, FALSE);
303 bb_error_msg("no arguments allowed");
306 printLines(curNum, curNum, FALSE);
310 if (setCurNum(curNum - 1))
311 printLines(curNum, curNum, FALSE);
315 printf("%d\n", num1);
319 printLines(num2, num2, FALSE);
322 if (setCurNum(curNum + 1))
323 printLines(curNum, curNum, FALSE);
327 bb_error_msg("unimplemented command");
335 * Do the substitute command.
336 * The current line is set to the last substitution done.
338 static void subCommand(const char *cmd, int num1, int num2)
340 char *cp, *oldStr, *newStr, buf[USERSIZE];
341 int delim, oldLen, newLen, deltaLen, offset;
343 int globalFlag, printFlag, didSub, needPrint;
345 if (bad_nums(num1, num2, "substitute"))
354 * Copy the command so we can modify it.
359 if (isblank(*cp) || (*cp == '\0')) {
360 bb_error_msg("bad delimiter for substitute");
367 cp = strchr(cp, delim);
369 bb_error_msg("missing 2nd delimiter for substitute");
376 cp = strchr(cp, delim);
383 while (*cp) switch (*cp++) {
391 bb_error_msg("unknown option for substitute");
395 if (*oldStr == '\0') {
396 if (searchString[0] == '\0') {
397 bb_error_msg("no previous search string");
400 oldStr = searchString;
403 if (oldStr != searchString)
404 strcpy(searchString, oldStr);
410 oldLen = strlen(oldStr);
411 newLen = strlen(newStr);
412 deltaLen = newLen - oldLen;
416 while (num1 <= num2) {
417 offset = findString(lp, oldStr, oldLen, offset);
421 printLines(num1, num1, FALSE);
430 needPrint = printFlag;
435 * If the replacement string is the same size or shorter
436 * than the old string, then the substitution is easy.
439 memcpy(&lp->data[offset], newStr, newLen);
441 memcpy(&lp->data[offset + newLen],
442 &lp->data[offset + oldLen],
443 lp->len - offset - oldLen);
451 printLines(num1, num1, FALSE);
460 * The new string is larger, so allocate a new line
461 * structure and use that. Link it in in place of
462 * the old line structure.
464 nlp = malloc(sizeof(LINE) + lp->len + deltaLen);
466 bb_error_msg("cannot get memory for line");
470 nlp->len = lp->len + deltaLen;
472 memcpy(nlp->data, lp->data, offset);
473 memcpy(&nlp->data[offset], newStr, newLen);
474 memcpy(&nlp->data[offset + newLen],
475 &lp->data[offset + oldLen],
476 lp->len - offset - oldLen);
478 nlp->next = lp->next;
479 nlp->prev = lp->prev;
480 nlp->prev->next = nlp;
481 nlp->next->prev = nlp;
495 printLines(num1, num1, FALSE);
504 bb_error_msg("no substitutions found for \"%s\"", oldStr);
509 * Search a line for the specified string starting at the specified
510 * offset in the line. Returns the offset of the found string, or -1.
512 static int findString(const LINE *lp, const char *str, int len, int offset)
515 const char *cp, *ncp;
517 cp = &lp->data[offset];
518 left = lp->len - offset;
520 while (left >= len) {
521 ncp = memchr(cp, *str, left);
528 if (memcmp(cp, str, len) == 0)
529 return (cp - lp->data);
539 * Add lines which are typed in by the user.
540 * The lines are inserted just before the specified line number.
541 * The lines are terminated by a line containing a single dot (ugly!),
542 * or by an end of file.
544 static void addLines(int num)
547 char buf[USERSIZE + 1];
551 * -1 on read errors or EOF, or on bare Ctrl-D.
553 * >0 length of input string, including terminating '\n'
555 len = read_line_input("", buf, sizeof(buf), NULL);
557 /* Previously, ctrl-C was exiting to shell.
558 * Now we exit to ed prompt. Is in important? */
561 if ((buf[0] == '.') && (buf[1] == '\n') && (buf[2] == '\0'))
563 if (!insertLine(num++, buf, len))
570 * Parse a line number argument if it is present. This is a sum
571 * or difference of numbers, '.', '$', 'x, or a search string.
572 * Returns TRUE if successful (whether or not there was a number).
573 * Returns FALSE if there was a parsing error, with a message output.
574 * Whether there was a number is returned indirectly, as is the number.
575 * The character pointer which stopped the scan is also returned.
577 static int getNum(const char **retcp, smallint *retHaveNum, int *retNum)
580 char *endStr, str[USERSIZE];
582 smallint haveNum, minus;
607 if ((*cp < 'a') || (*cp > 'z')) {
608 bb_error_msg("bad mark name");
612 num = marks[*cp++ - 'a'];
617 endStr = strchr(str, '/');
620 cp += (endStr - str);
623 num = searchLines(str, curNum, lastNum);
632 *retHaveNum = haveNum;
638 num = num * 10 + *cp++ - '0';
643 value += (minus ? -num : num);
660 *retHaveNum = haveNum;
669 * Read lines from a file at the specified line number.
670 * Returns TRUE if the file was successfully read.
672 static int readLines(const char *file, int num)
675 int len, lineCount, charCount;
678 if ((num < 1) || (num > lastNum + 1)) {
679 bb_error_msg("bad line for read");
695 printf("\"%s\", ", file);
699 cp = memchr(bufPtr, '\n', bufUsed);
702 len = (cp - bufPtr) + 1;
703 if (!insertLine(num, bufPtr, len)) {
715 if (bufPtr != bufBase) {
716 memcpy(bufBase, bufPtr, bufUsed);
717 bufPtr = bufBase + bufUsed;
720 if (bufUsed >= bufSize) {
721 len = (bufSize * 3) / 2;
722 cp = realloc(bufBase, len);
724 bb_error_msg("no memory for buffer");
729 bufPtr = bufBase + bufUsed;
733 cc = safe_read(fd, bufPtr, bufSize - bufUsed);
746 if (!insertLine(num, bufPtr, bufUsed)) {
751 charCount += bufUsed;
756 printf("%d lines%s, %d chars\n", lineCount,
757 (bufUsed ? " (incomplete)" : ""), charCount);
764 * Write the specified lines out to the specified file.
765 * Returns TRUE if successful, or FALSE on an error with a message output.
767 static int writeLines(const char *file, int num1, int num2)
770 int fd, lineCount, charCount;
772 if (bad_nums(num1, num2, "write"))
778 fd = creat(file, 0666);
784 printf("\"%s\", ", file);
793 while (num1++ <= num2) {
794 if (full_write(fd, lp->data, lp->len) != lp->len) {
799 charCount += lp->len;
809 printf("%d lines, %d chars\n", lineCount, charCount);
815 * Print lines in a specified range.
816 * The last line printed becomes the current line.
817 * If expandFlag is TRUE, then the line is printed specially to
818 * show magic characters.
820 static int printLines(int num1, int num2, int expandFlag)
826 if (bad_nums(num1, num2, "print"))
833 while (num1 <= num2) {
835 write(1, lp->data, lp->len);
842 * Show control characters and characters with the
843 * high bit set specially.
848 if ((count > 0) && (cp[count - 1] == '\n'))
851 while (count-- > 0) {
868 fputs("$\n", stdout);
879 * Insert a new line with the specified text.
880 * The line is inserted so as to become the specified line,
881 * thus pushing any existing and further lines down one.
882 * The inserted line is also set to become the current line.
883 * Returns TRUE if successful.
885 static int insertLine(int num, const char *data, int len)
889 if ((num < 1) || (num > lastNum + 1)) {
890 bb_error_msg("inserting at bad line number");
894 newLp = malloc(sizeof(LINE) + len - 1);
896 bb_error_msg("failed to allocate memory for line");
900 memcpy(newLp->data, data, len);
908 free((char *) newLp);
914 newLp->prev = lp->prev;
915 lp->prev->next = newLp;
920 return setCurNum(num);
925 * Delete lines from the given range.
927 static void deleteLines(int num1, int num2)
929 LINE *lp, *nlp, *plp;
932 if (bad_nums(num1, num2, "delete"))
939 if ((curNum >= num1) && (curNum <= num2)) {
948 count = num2 - num1 + 1;
953 while (count-- > 0) {
967 * Search for a line which contains the specified string.
968 * If the string is "", then the previously searched for string
969 * is used. The currently searched for string is saved for future use.
970 * Returns the line number which matches, or 0 if there was no match
971 * with an error printed.
973 static int searchLines(const char *str, int num1, int num2)
978 if (bad_nums(num1, num2, "search"))
982 if (searchString[0] == '\0') {
983 bb_error_msg("no previous search string");
989 if (str != searchString)
990 strcpy(searchString, str);
998 while (num1 <= num2) {
999 if (findString(lp, str, len, 0) >= 0)
1005 bb_error_msg("cannot find string \"%s\"", str);
1011 * Return a pointer to the specified line number.
1013 static LINE *findLine(int num)
1018 if ((num < 1) || (num > lastNum)) {
1019 bb_error_msg("line number %d does not exist", num);
1025 curLine = lines.next;
1033 if (num < (curNum / 2)) {
1036 } else if (num > ((curNum + lastNum) / 2)) {
1041 while (lnum < num) {
1046 while (lnum > num) {
1055 * Set the current line number.
1056 * Returns TRUE if successful.
1058 static int setCurNum(int num)