+/* vi: set sw=4 ts=4: */
/*
* Copyright (c) 2002 by David I. Bell
* Permission is granted to use, distribute, or modify this source,
*
* The "ed" built-in command (much simplified)
*/
+//config:config ED
+//config: bool "ed (25 kb)"
+//config: default y
+//config: help
+//config: The original 1970's Unix text editor, from the days of teletypes.
+//config: Small, simple, evil. Part of SUSv3. If you're not already using
+//config: this, you don't need it.
+
+//kbuild:lib-$(CONFIG_ED) += ed.o
+
+//applet:IF_ED(APPLET(ed, BB_DIR_BIN, BB_SUID_DROP))
+
+//usage:#define ed_trivial_usage "[FILE]"
+//usage:#define ed_full_usage ""
+
+#include "libbb.h"
+#include "common_bufsiz.h"
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <string.h>
-#include <memory.h>
-#include <time.h>
-#include <ctype.h>
-#include <sys/param.h>
-#include <malloc.h>
-#include "busybox.h"
-
-#define USERSIZE 1024 /* max line length typed in by user */
-#define INITBUF_SIZE 1024 /* initial buffer size */
typedef struct LINE {
struct LINE *next;
struct LINE *prev;
char data[1];
} LINE;
-static LINE lines, *curLine;
-static int curNum, lastNum, marks[26], dirty;
-static char *bufBase, *bufPtr, *fileName, searchString[USERSIZE];
-static int bufUsed, bufSize;
-
-static void doCommands(void);
-static void subCommand(const char *cmd, int num1, int num2);
-static int getNum(const char **retcp, int *retHaveNum, int *retNum);
-static int setCurNum(int num);
-static int initEdit(void);
-static void termEdit(void);
-static void addLines(int num);
-static int insertLine(int num, const char *data, int len);
-static int deleteLines(int num1, int num2);
-static int printLines(int num1, int num2, int expandFlag);
-static int writeLines(const char *file, int num1, int num2);
-static int readLines(const char *file, int num);
-static int searchLines(const char *str, int num1, int num2);
-static LINE *findLine(int num);
-
-static int findString(const LINE *lp, const char * str, int len, int offset);
-
-int ed_main(int argc, char **argv)
+#define searchString bb_common_bufsiz1
+
+enum {
+ USERSIZE = COMMON_BUFSIZE > 1024 ? 1024
+ : COMMON_BUFSIZE - 1, /* max line length typed in by user */
+ INITBUF_SIZE = 1024, /* initial buffer size */
+};
+
+struct globals {
+ int curNum;
+ int lastNum;
+ int bufUsed;
+ int bufSize;
+ LINE *curLine;
+ char *bufBase;
+ char *bufPtr;
+ char *fileName;
+ LINE lines;
+ smallint dirty;
+ int marks[26];
+};
+#define G (*ptr_to_globals)
+#define curLine (G.curLine )
+#define bufBase (G.bufBase )
+#define bufPtr (G.bufPtr )
+#define fileName (G.fileName )
+#define curNum (G.curNum )
+#define lastNum (G.lastNum )
+#define bufUsed (G.bufUsed )
+#define bufSize (G.bufSize )
+#define dirty (G.dirty )
+#define lines (G.lines )
+#define marks (G.marks )
+#define INIT_G() do { \
+ setup_common_bufsiz(); \
+ SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
+} while (0)
+
+static int bad_nums(int num1, int num2, const char *for_what)
{
- if (!initEdit())
- return EXIT_FAILURE;
-
- if (argc > 1) {
- fileName = strdup(argv[1]);
-
- if (fileName == NULL) {
- bb_error_msg("No memory");
- termEdit();
- return EXIT_SUCCESS;
- }
-
- if (!readLines(fileName, 1)) {
- termEdit();
- return EXIT_SUCCESS;
- }
-
- if (lastNum)
- setCurNum(1);
-
- dirty = FALSE;
+ if ((num1 < 1) || (num2 > lastNum) || (num1 > num2)) {
+ bb_error_msg("bad line range for %s", for_what);
+ return 1;
}
-
- doCommands();
-
- termEdit();
- return EXIT_SUCCESS;
+ return 0;
}
/*
- * Read commands until we are told to stop.
+ * Return a pointer to the specified line number.
*/
-static void doCommands(void)
+static LINE *findLine(int num)
{
- const char *cp;
- char *endbuf, *newname, buf[USERSIZE];
- int len, num1, num2, have1, have2;
-
- while (TRUE)
- {
- printf(": ");
- fflush(stdout);
-
- if (fgets(buf, sizeof(buf), stdin) == NULL)
- return;
-
- len = strlen(buf);
-
- if (len == 0)
- return;
-
- endbuf = &buf[len - 1];
-
- if (*endbuf != '\n')
- {
- bb_error_msg("Command line too long");
-
- do
- {
- len = fgetc(stdin);
- }
- while ((len != EOF) && (len != '\n'));
-
- continue;
- }
+ LINE *lp;
+ int lnum;
- while ((endbuf > buf) && isblank(endbuf[-1]))
- endbuf--;
+ if ((num < 1) || (num > lastNum)) {
+ bb_error_msg("line number %d does not exist", num);
+ return NULL;
+ }
- *endbuf = '\0';
+ if (curNum <= 0) {
+ curNum = 1;
+ curLine = lines.next;
+ }
- cp = buf;
+ if (num == curNum)
+ return curLine;
- while (isblank(*cp))
- cp++;
+ lp = curLine;
+ lnum = curNum;
+ if (num < (curNum / 2)) {
+ lp = lines.next;
+ lnum = 1;
+ } else if (num > ((curNum + lastNum) / 2)) {
+ lp = lines.prev;
+ lnum = lastNum;
+ }
- have1 = FALSE;
- have2 = FALSE;
+ while (lnum < num) {
+ lp = lp->next;
+ lnum++;
+ }
- if ((curNum == 0) && (lastNum > 0))
- {
- curNum = 1;
- curLine = lines.next;
- }
+ while (lnum > num) {
+ lp = lp->prev;
+ lnum--;
+ }
+ return lp;
+}
- if (!getNum(&cp, &have1, &num1))
- continue;
+/*
+ * Search a line for the specified string starting at the specified
+ * offset in the line. Returns the offset of the found string, or -1.
+ */
+static int findString(const LINE *lp, const char *str, int len, int offset)
+{
+ int left;
+ const char *cp, *ncp;
- while (isblank(*cp))
- cp++;
+ cp = &lp->data[offset];
+ left = lp->len - offset - len;
- if (*cp == ',')
- {
- cp++;
+ while (left >= 0) {
+ ncp = memchr(cp, str[0], left + 1);
+ if (ncp == NULL)
+ return -1;
+ left -= (ncp - cp);
+ cp = ncp;
+ if (memcmp(cp, str, len) == 0)
+ return (cp - lp->data);
+ cp++;
+ left--;
+ }
- if (!getNum(&cp, &have2, &num2))
- continue;
+ return -1;
+}
- if (!have1)
- num1 = 1;
+/*
+ * Search for a line which contains the specified string.
+ * If the string is "", then the previously searched for string
+ * is used. The currently searched for string is saved for future use.
+ * Returns the line number which matches, or 0 if there was no match
+ * with an error printed.
+ */
+static NOINLINE int searchLines(const char *str, int num1, int num2)
+{
+ const LINE *lp;
+ int len;
- if (!have2)
- num2 = lastNum;
+ if (bad_nums(num1, num2, "search"))
+ return 0;
- have1 = TRUE;
- have2 = TRUE;
+ if (*str == '\0') {
+ if (searchString[0] == '\0') {
+ bb_error_msg("no previous search string");
+ return 0;
}
+ str = searchString;
+ }
- if (!have1)
- num1 = curNum;
-
- if (!have2)
- num2 = num1;
-
- switch (*cp++)
- {
- case 'a':
- addLines(num1 + 1);
- break;
-
- case 'c':
- deleteLines(num1, num2);
- addLines(num1);
- break;
-
- case 'd':
- deleteLines(num1, num2);
- break;
-
- case 'f':
- if (*cp && !isblank(*cp))
- {
- bb_error_msg("Bad file command");
- break;
- }
-
- while (isblank(*cp))
- cp++;
-
- if (*cp == '\0')
- {
- if (fileName)
- printf("\"%s\"\n", fileName);
- else
- printf("No file name\n");
-
- break;
- }
-
- newname = strdup(cp);
-
- if (newname == NULL)
- {
- bb_error_msg("No memory for file name");
- break;
- }
+ if (str != searchString)
+ strcpy(searchString, str);
- if (fileName)
- free(fileName);
+ len = strlen(str);
- fileName = newname;
- break;
+ lp = findLine(num1);
+ if (lp == NULL)
+ return 0;
- case 'i':
- addLines(num1);
- break;
+ while (num1 <= num2) {
+ if (findString(lp, str, len, 0) >= 0)
+ return num1;
+ num1++;
+ lp = lp->next;
+ }
- case 'k':
- while (isblank(*cp))
- cp++;
+ bb_error_msg("can't find string \"%s\"", str);
+ return 0;
+}
- if ((*cp < 'a') || (*cp > 'a') || cp[1])
- {
- bb_error_msg("Bad mark name");
- break;
- }
+/*
+ * Parse a line number argument if it is present. This is a sum
+ * or difference of numbers, ".", "$", "'c", or a search string.
+ * Returns pointer which stopped the scan if successful
+ * (whether or not there was a number).
+ * Returns NULL if there was a parsing error, with a message output.
+ * Whether there was a number is returned indirectly, as is the number.
+ */
+static const char* getNum(const char *cp, smallint *retHaveNum, int *retNum)
+{
+ char *endStr, str[USERSIZE];
+ int value, num;
+ smallint haveNum, minus;
- marks[*cp - 'a'] = num2;
- break;
+ value = 0;
+ haveNum = FALSE;
+ minus = 0;
- case 'l':
- printLines(num1, num2, TRUE);
- break;
+ while (TRUE) {
+ cp = skip_whitespace(cp);
- case 'p':
- printLines(num1, num2, FALSE);
+ switch (*cp) {
+ case '.':
+ haveNum = TRUE;
+ num = curNum;
+ cp++;
break;
- case 'q':
- while (isblank(*cp))
- cp++;
-
- if (have1 || *cp)
- {
- bb_error_msg("Bad quit command");
- break;
- }
-
- if (!dirty)
- return;
-
- printf("Really quit? ");
- fflush(stdout);
-
- buf[0] = '\0';
- fgets(buf, sizeof(buf), stdin);
- cp = buf;
-
- while (isblank(*cp))
- cp++;
-
- if ((*cp == 'y') || (*cp == 'Y'))
- return;
-
+ case '$':
+ haveNum = TRUE;
+ num = lastNum;
+ cp++;
break;
- case 'r':
- if (*cp && !isblank(*cp))
- {
- bb_error_msg("Bad read command");
- break;
- }
-
- while (isblank(*cp))
- cp++;
-
- if (*cp == '\0')
- {
- bb_error_msg("No file name");
- break;
+ case '\'':
+ cp++;
+ if ((unsigned)(*cp - 'a') >= 26) {
+ bb_error_msg("bad mark name");
+ return NULL;
}
-
- if (!have1)
- num1 = lastNum;
-
- if (readLines(cp, num1 + 1))
- break;
-
- if (fileName == NULL)
- fileName = strdup(cp);
-
+ haveNum = TRUE;
+ num = marks[(unsigned)(*cp - 'a')];
+ cp++;
break;
- case 's':
- subCommand(cp, num1, num2);
+ case '/':
+ strcpy(str, ++cp);
+ endStr = strchr(str, '/');
+ if (endStr) {
+ *endStr++ = '\0';
+ cp += (endStr - str);
+ } else
+ cp = "";
+ num = searchLines(str, curNum, lastNum);
+ if (num == 0)
+ return NULL;
+ haveNum = TRUE;
break;
- case 'w':
- if (*cp && !isblank(*cp))
- {
- bb_error_msg("Bad write command");
- break;
- }
-
- while (isblank(*cp))
- cp++;
-
- if (!have1) {
- num1 = 1;
- num2 = lastNum;
- }
-
- if (*cp == '\0')
- cp = fileName;
-
- if (cp == NULL)
- {
- bb_error_msg("No file name specified");
- break;
+ default:
+ if (!isdigit(*cp)) {
+ *retHaveNum = haveNum;
+ *retNum = value;
+ return cp;
}
-
- writeLines(cp, num1, num2);
+ num = 0;
+ while (isdigit(*cp))
+ num = num * 10 + *cp++ - '0';
+ haveNum = TRUE;
break;
+ }
- case 'z':
- switch (*cp)
- {
- case '-':
- printLines(curNum-21, curNum, FALSE);
- break;
- case '.':
- printLines(curNum-11, curNum+10, FALSE);
- break;
- default:
- printLines(curNum, curNum+21, FALSE);
- break;
- }
- break;
+ value += (minus ? -num : num);
- case '.':
- if (have1)
- {
- bb_error_msg("No arguments allowed");
- break;
- }
+ cp = skip_whitespace(cp);
- printLines(curNum, curNum, FALSE);
- break;
-
+ switch (*cp) {
case '-':
- if (setCurNum(curNum - 1))
- printLines(curNum, curNum, FALSE);
-
- break;
-
- case '=':
- printf("%d\n", num1);
+ minus = 1;
+ cp++;
break;
- case '\0':
- if (have1)
- {
- printLines(num2, num2, FALSE);
- break;
- }
-
- if (setCurNum(curNum + 1))
- printLines(curNum, curNum, FALSE);
-
+ case '+':
+ minus = 0;
+ cp++;
break;
default:
- bb_error_msg("Unimplemented command");
- break;
+ *retHaveNum = haveNum;
+ *retNum = value;
+ return cp;
}
}
}
-
/*
- * Do the substitute command.
- * The current line is set to the last substitution done.
+ * Set the current line number.
+ * Returns TRUE if successful.
*/
-static void subCommand(const char * cmd, int num1, int num2)
+static int setCurNum(int num)
{
- char *cp, *oldStr, *newStr, buf[USERSIZE];
- int delim, oldLen, newLen, deltaLen, offset;
- LINE *lp, *nlp;
- int globalFlag, printFlag, didSub, needPrint;
+ LINE *lp;
- if ((num1 < 1) || (num2 > lastNum) || (num1 > num2))
- {
- bb_error_msg("Bad line range for substitute");
+ lp = findLine(num);
+ if (lp == NULL)
+ return FALSE;
+ curNum = num;
+ curLine = lp;
+ return TRUE;
+}
- return;
- }
+/*
+ * Insert a new line with the specified text.
+ * The line is inserted so as to become the specified line,
+ * thus pushing any existing and further lines down one.
+ * The inserted line is also set to become the current line.
+ * Returns TRUE if successful.
+ */
+static int insertLine(int num, const char *data, int len)
+{
+ LINE *newLp, *lp;
- globalFlag = FALSE;
- printFlag = FALSE;
- didSub = FALSE;
- needPrint = FALSE;
+ if ((num < 1) || (num > lastNum + 1)) {
+ bb_error_msg("inserting at bad line number");
+ return FALSE;
+ }
- /*
- * Copy the command so we can modify it.
- */
- strcpy(buf, cmd);
- cp = buf;
+ newLp = xmalloc(sizeof(LINE) + len - 1);
- if (isblank(*cp) || (*cp == '\0'))
- {
- bb_error_msg("Bad delimiter for substitute");
+ memcpy(newLp->data, data, len);
+ newLp->len = len;
- return;
+ if (num > lastNum)
+ lp = &lines;
+ else {
+ lp = findLine(num);
+ if (lp == NULL) {
+ free((char *) newLp);
+ return FALSE;
+ }
}
- delim = *cp++;
- oldStr = cp;
+ newLp->next = lp;
+ newLp->prev = lp->prev;
+ lp->prev->next = newLp;
+ lp->prev = newLp;
- cp = strchr(cp, delim);
+ lastNum++;
+ dirty = TRUE;
+ return setCurNum(num);
+}
- if (cp == NULL)
- {
- bb_error_msg("Missing 2nd delimiter for substitute");
+/*
+ * Add lines which are typed in by the user.
+ * The lines are inserted just before the specified line number.
+ * The lines are terminated by a line containing a single dot (ugly!),
+ * or by an end of file.
+ */
+static void addLines(int num)
+{
+ int len;
+ char buf[USERSIZE + 1];
- return;
+ while (1) {
+ /* Returns:
+ * -1 on read errors or EOF, or on bare Ctrl-D.
+ * 0 on ctrl-C,
+ * >0 length of input string, including terminating '\n'
+ */
+ len = read_line_input(NULL, "", buf, sizeof(buf), /*timeout*/ -1);
+ if (len <= 0) {
+ /* Previously, ctrl-C was exiting to shell.
+ * Now we exit to ed prompt. Is in important? */
+ return;
+ }
+ if (buf[0] == '.' && buf[1] == '\n' && buf[2] == '\0')
+ return;
+ if (!insertLine(num++, buf, len))
+ return;
}
+}
- *cp++ = '\0';
+/*
+ * Read lines from a file at the specified line number.
+ * Returns TRUE if the file was successfully read.
+ */
+static int readLines(const char *file, int num)
+{
+ int fd, cc;
+ int len, lineCount, charCount;
+ char *cp;
- newStr = cp;
- cp = strchr(cp, delim);
+ if ((num < 1) || (num > lastNum + 1)) {
+ bb_error_msg("bad line for read");
+ return FALSE;
+ }
- if (cp)
- *cp++ = '\0';
- else
- cp = "";
+ fd = open(file, 0);
+ if (fd < 0) {
+ bb_simple_perror_msg(file);
+ return FALSE;
+ }
- while (*cp) switch (*cp++)
- {
- case 'g':
- globalFlag = TRUE;
- break;
+ bufPtr = bufBase;
+ bufUsed = 0;
+ lineCount = 0;
+ charCount = 0;
+ cc = 0;
- case 'p':
- printFlag = TRUE;
- break;
+ printf("\"%s\", ", file);
+ fflush_all();
- default:
- bb_error_msg("Unknown option for substitute");
+ do {
+ cp = memchr(bufPtr, '\n', bufUsed);
- return;
- }
+ if (cp) {
+ len = (cp - bufPtr) + 1;
+ if (!insertLine(num, bufPtr, len)) {
+ close(fd);
+ return FALSE;
+ }
+ bufPtr += len;
+ bufUsed -= len;
+ charCount += len;
+ lineCount++;
+ num++;
+ continue;
+ }
- if (*oldStr == '\0')
- {
- if (searchString[0] == '\0')
- {
- bb_error_msg("No previous search string");
+ if (bufPtr != bufBase) {
+ memcpy(bufBase, bufPtr, bufUsed);
+ bufPtr = bufBase + bufUsed;
+ }
- return;
+ if (bufUsed >= bufSize) {
+ len = (bufSize * 3) / 2;
+ cp = xrealloc(bufBase, len);
+ bufBase = cp;
+ bufPtr = bufBase + bufUsed;
+ bufSize = len;
}
- oldStr = searchString;
+ cc = safe_read(fd, bufPtr, bufSize - bufUsed);
+ bufUsed += cc;
+ bufPtr = bufBase;
+ } while (cc > 0);
+
+ if (cc < 0) {
+ bb_simple_perror_msg(file);
+ close(fd);
+ return FALSE;
}
- if (oldStr != searchString)
- strcpy(searchString, oldStr);
+ if (bufUsed) {
+ if (!insertLine(num, bufPtr, bufUsed)) {
+ close(fd);
+ return -1;
+ }
+ lineCount++;
+ charCount += bufUsed;
+ }
- lp = findLine(num1);
+ close(fd);
- if (lp == NULL)
- return;
+ printf("%d lines%s, %d chars\n", lineCount,
+ (bufUsed ? " (incomplete)" : ""), charCount);
- oldLen = strlen(oldStr);
- newLen = strlen(newStr);
- deltaLen = newLen - oldLen;
- offset = 0;
- nlp = NULL;
+ return TRUE;
+}
- while (num1 <= num2)
- {
- offset = findString(lp, oldStr, oldLen, offset);
+/*
+ * Write the specified lines out to the specified file.
+ * Returns TRUE if successful, or FALSE on an error with a message output.
+ */
+static int writeLines(const char *file, int num1, int num2)
+{
+ LINE *lp;
+ int fd, lineCount, charCount;
- if (offset < 0)
- {
- if (needPrint)
- {
- printLines(num1, num1, FALSE);
- needPrint = FALSE;
- }
+ if (bad_nums(num1, num2, "write"))
+ return FALSE;
- offset = 0;
- lp = lp->next;
- num1++;
+ lineCount = 0;
+ charCount = 0;
- continue;
- }
+ fd = creat(file, 0666);
+ if (fd < 0) {
+ bb_simple_perror_msg(file);
+ return FALSE;
+ }
- needPrint = printFlag;
- didSub = TRUE;
- dirty = TRUE;
+ printf("\"%s\", ", file);
+ fflush_all();
- /*
- * If the replacement string is the same size or shorter
- * than the old string, then the substitution is easy.
- */
- if (deltaLen <= 0)
- {
- memcpy(&lp->data[offset], newStr, newLen);
+ lp = findLine(num1);
+ if (lp == NULL) {
+ close(fd);
+ return FALSE;
+ }
- if (deltaLen)
- {
- memcpy(&lp->data[offset + newLen],
- &lp->data[offset + oldLen],
- lp->len - offset - oldLen);
+ while (num1++ <= num2) {
+ if (full_write(fd, lp->data, lp->len) != lp->len) {
+ bb_simple_perror_msg(file);
+ close(fd);
+ return FALSE;
+ }
+ charCount += lp->len;
+ lineCount++;
+ lp = lp->next;
+ }
- lp->len += deltaLen;
- }
+ if (close(fd) < 0) {
+ bb_simple_perror_msg(file);
+ return FALSE;
+ }
- offset += newLen;
+ printf("%d lines, %d chars\n", lineCount, charCount);
+ return TRUE;
+}
- if (globalFlag)
- continue;
+/*
+ * Print lines in a specified range.
+ * The last line printed becomes the current line.
+ * If expandFlag is TRUE, then the line is printed specially to
+ * show magic characters.
+ */
+static int printLines(int num1, int num2, int expandFlag)
+{
+ const LINE *lp;
+ const char *cp;
+ int ch, count;
- if (needPrint)
- {
- printLines(num1, num1, FALSE);
- needPrint = FALSE;
- }
+ if (bad_nums(num1, num2, "print"))
+ return FALSE;
- lp = lp->next;
- num1++;
+ lp = findLine(num1);
+ if (lp == NULL)
+ return FALSE;
+ while (num1 <= num2) {
+ if (!expandFlag) {
+ write(STDOUT_FILENO, lp->data, lp->len);
+ setCurNum(num1++);
+ lp = lp->next;
continue;
}
/*
- * The new string is larger, so allocate a new line
- * structure and use that. Link it in in place of
- * the old line structure.
+ * Show control characters and characters with the
+ * high bit set specially.
*/
- nlp = (LINE *) malloc(sizeof(LINE) + lp->len + deltaLen);
+ cp = lp->data;
+ count = lp->len;
- if (nlp == NULL)
- {
- bb_error_msg("Cannot get memory for line");
+ if ((count > 0) && (cp[count - 1] == '\n'))
+ count--;
- return;
+ while (count-- > 0) {
+ ch = (unsigned char) *cp++;
+ fputc_printable(ch | PRINTABLE_META, stdout);
}
- nlp->len = lp->len + deltaLen;
-
- memcpy(nlp->data, lp->data, offset);
+ fputs("$\n", stdout);
- memcpy(&nlp->data[offset], newStr, newLen);
+ setCurNum(num1++);
+ lp = lp->next;
+ }
- memcpy(&nlp->data[offset + newLen],
- &lp->data[offset + oldLen],
- lp->len - offset - oldLen);
+ return TRUE;
+}
- nlp->next = lp->next;
- nlp->prev = lp->prev;
- nlp->prev->next = nlp;
- nlp->next->prev = nlp;
+/*
+ * Delete lines from the given range.
+ */
+static void deleteLines(int num1, int num2)
+{
+ LINE *lp, *nlp, *plp;
+ int count;
- if (curLine == lp)
- curLine = nlp;
+ if (bad_nums(num1, num2, "delete"))
+ return;
- free(lp);
- lp = nlp;
+ lp = findLine(num1);
+ if (lp == NULL)
+ return;
- offset += newLen;
-
- if (globalFlag)
- continue;
+ if ((curNum >= num1) && (curNum <= num2)) {
+ if (num2 < lastNum)
+ setCurNum(num2 + 1);
+ else if (num1 > 1)
+ setCurNum(num1 - 1);
+ else
+ curNum = 0;
+ }
- if (needPrint)
- {
- printLines(num1, num1, FALSE);
- needPrint = FALSE;
- }
+ count = num2 - num1 + 1;
+ if (curNum > num2)
+ curNum -= count;
+ lastNum -= count;
- lp = lp->next;
- num1++;
+ while (count-- > 0) {
+ nlp = lp->next;
+ plp = lp->prev;
+ plp->next = nlp;
+ nlp->prev = plp;
+ free(lp);
+ lp = nlp;
}
- if (!didSub)
- bb_error_msg("No substitutions found for \"%s\"", oldStr);
+ dirty = TRUE;
}
-
/*
- * Search a line for the specified string starting at the specified
- * offset in the line. Returns the offset of the found string, or -1.
+ * Do the substitute command.
+ * The current line is set to the last substitution done.
*/
-static int findString( const LINE * lp, const char * str, int len, int offset)
+static void subCommand(const char *cmd, int num1, int num2)
{
- int left;
- const char *cp, *ncp;
-
- cp = &lp->data[offset];
- left = lp->len - offset;
-
- while (left >= len)
- {
- ncp = memchr(cp, *str, left);
-
- if (ncp == NULL)
- return -1;
-
- left -= (ncp - cp);
+ char *cp, *oldStr, *newStr, buf[USERSIZE];
+ int delim, oldLen, newLen, deltaLen, offset;
+ LINE *lp, *nlp;
+ int globalFlag, printFlag, didSub, needPrint;
- if (left < len)
- return -1;
+ if (bad_nums(num1, num2, "substitute"))
+ return;
- cp = ncp;
+ globalFlag = FALSE;
+ printFlag = FALSE;
+ didSub = FALSE;
+ needPrint = FALSE;
- if (memcmp(cp, str, len) == 0)
- return (cp - lp->data);
+ /*
+ * Copy the command so we can modify it.
+ */
+ strcpy(buf, cmd);
+ cp = buf;
- cp++;
- left--;
+ if (isblank(*cp) || (*cp == '\0')) {
+ bb_error_msg("bad delimiter for substitute");
+ return;
}
- return -1;
-}
+ delim = *cp++;
+ oldStr = cp;
+ cp = strchr(cp, delim);
+ if (cp == NULL) {
+ bb_error_msg("missing 2nd delimiter for substitute");
+ return;
+ }
-/*
- * Add lines which are typed in by the user.
- * The lines are inserted just before the specified line number.
- * The lines are terminated by a line containing a single dot (ugly!),
- * or by an end of file.
- */
-static void addLines(int num)
-{
- int len;
- char buf[USERSIZE + 1];
+ *cp++ = '\0';
- while (fgets(buf, sizeof(buf), stdin))
- {
- if ((buf[0] == '.') && (buf[1] == '\n') && (buf[2] == '\0'))
- return;
+ newStr = cp;
+ cp = strchr(cp, delim);
- len = strlen(buf);
+ if (cp)
+ *cp++ = '\0';
+ else
+ cp = (char*)"";
- if (len == 0)
+ while (*cp) switch (*cp++) {
+ case 'g':
+ globalFlag = TRUE;
+ break;
+ case 'p':
+ printFlag = TRUE;
+ break;
+ default:
+ bb_error_msg("unknown option for substitute");
return;
+ }
- if (buf[len - 1] != '\n')
- {
- bb_error_msg("Line too long");
-
- do
- {
- len = fgetc(stdin);
- }
- while ((len != EOF) && (len != '\n'));
-
+ if (*oldStr == '\0') {
+ if (searchString[0] == '\0') {
+ bb_error_msg("no previous search string");
return;
}
-
- if (!insertLine(num++, buf, len))
- return;
+ oldStr = searchString;
}
-}
-
-
-/*
- * Parse a line number argument if it is present. This is a sum
- * or difference of numbers, '.', '$', 'x, or a search string.
- * Returns TRUE if successful (whether or not there was a number).
- * Returns FALSE if there was a parsing error, with a message output.
- * Whether there was a number is returned indirectly, as is the number.
- * The character pointer which stopped the scan is also returned.
- */
-static int getNum(const char **retcp, int *retHaveNum, int *retNum)
-{
- const char *cp;
- char *endStr, str[USERSIZE];
- int haveNum, value, num, sign;
-
- cp = *retcp;
- haveNum = FALSE;
- value = 0;
- sign = 1;
- while (TRUE)
- {
- while (isblank(*cp))
- cp++;
+ if (oldStr != searchString)
+ strcpy(searchString, oldStr);
- switch (*cp)
- {
- case '.':
- haveNum = TRUE;
- num = curNum;
- cp++;
- break;
+ lp = findLine(num1);
+ if (lp == NULL)
+ return;
- case '$':
- haveNum = TRUE;
- num = lastNum;
- cp++;
- break;
+ oldLen = strlen(oldStr);
+ newLen = strlen(newStr);
+ deltaLen = newLen - oldLen;
+ offset = 0;
+ nlp = NULL;
- case '\'':
- cp++;
+ while (num1 <= num2) {
+ offset = findString(lp, oldStr, oldLen, offset);
- if ((*cp < 'a') || (*cp > 'z'))
- {
- bb_error_msg("Bad mark name");
+ if (offset < 0) {
+ if (needPrint) {
+ printLines(num1, num1, FALSE);
+ needPrint = FALSE;
+ }
+ offset = 0;
+ lp = lp->next;
+ num1++;
+ continue;
+ }
- return FALSE;
- }
+ needPrint = printFlag;
+ didSub = TRUE;
+ dirty = TRUE;
- haveNum = TRUE;
- num = marks[*cp++ - 'a'];
- break;
+ /*
+ * If the replacement string is the same size or shorter
+ * than the old string, then the substitution is easy.
+ */
+ if (deltaLen <= 0) {
+ memcpy(&lp->data[offset], newStr, newLen);
+ if (deltaLen) {
+ memcpy(&lp->data[offset + newLen],
+ &lp->data[offset + oldLen],
+ lp->len - offset - oldLen);
- case '/':
- strcpy(str, ++cp);
- endStr = strchr(str, '/');
+ lp->len += deltaLen;
+ }
+ offset += newLen;
+ if (globalFlag)
+ continue;
+ if (needPrint) {
+ printLines(num1, num1, FALSE);
+ needPrint = FALSE;
+ }
+ lp = lp->next;
+ num1++;
+ continue;
+ }
- if (endStr)
- {
- *endStr++ = '\0';
- cp += (endStr - str);
- }
- else
- cp = "";
+ /*
+ * The new string is larger, so allocate a new line
+ * structure and use that. Link it in place of
+ * the old line structure.
+ */
+ nlp = xmalloc(sizeof(LINE) + lp->len + deltaLen);
- num = searchLines(str, curNum, lastNum);
+ nlp->len = lp->len + deltaLen;
- if (num == 0)
- return FALSE;
+ memcpy(nlp->data, lp->data, offset);
+ memcpy(&nlp->data[offset], newStr, newLen);
+ memcpy(&nlp->data[offset + newLen],
+ &lp->data[offset + oldLen],
+ lp->len - offset - oldLen);
- haveNum = TRUE;
- break;
+ nlp->next = lp->next;
+ nlp->prev = lp->prev;
+ nlp->prev->next = nlp;
+ nlp->next->prev = nlp;
- default:
- if (!isdigit(*cp))
- {
- *retcp = cp;
- *retHaveNum = haveNum;
- *retNum = value;
+ if (curLine == lp)
+ curLine = nlp;
- return TRUE;
- }
+ free(lp);
+ lp = nlp;
- num = 0;
+ offset += newLen;
- while (isdigit(*cp))
- num = num * 10 + *cp++ - '0';
+ if (globalFlag)
+ continue;
- haveNum = TRUE;
- break;
+ if (needPrint) {
+ printLines(num1, num1, FALSE);
+ needPrint = FALSE;
}
- value += num * sign;
-
- while (isblank(*cp))
- cp++;
-
- switch (*cp)
- {
- case '-':
- sign = -1;
- cp++;
- break;
-
- case '+':
- sign = 1;
- cp++;
- break;
-
- default:
- *retcp = cp;
- *retHaveNum = haveNum;
- *retNum = value;
-
- return TRUE;
- }
+ lp = lp->next;
+ num1++;
}
-}
+ if (!didSub)
+ bb_error_msg("no substitutions found for \"%s\"", oldStr);
+}
/*
- * Initialize everything for editing.
+ * Read commands until we are told to stop.
*/
-static int initEdit(void)
+static void doCommands(void)
{
- int i;
-
- bufSize = INITBUF_SIZE;
- bufBase = malloc(bufSize);
-
- if (bufBase == NULL)
- {
- bb_error_msg("No memory for buffer");
-
- return FALSE;
- }
-
- bufPtr = bufBase;
- bufUsed = 0;
-
- lines.next = &lines;
- lines.prev = &lines;
-
- curLine = NULL;
- curNum = 0;
- lastNum = 0;
- dirty = FALSE;
- fileName = NULL;
- searchString[0] = '\0';
+ while (TRUE) {
+ char buf[USERSIZE];
+ const char *cp;
+ int len;
+ int n, num1, num2;
+ smallint h, have1, have2;
+
+ /* Returns:
+ * -1 on read errors or EOF, or on bare Ctrl-D.
+ * 0 on ctrl-C,
+ * >0 length of input string, including terminating '\n'
+ */
+ len = read_line_input(NULL, ": ", buf, sizeof(buf), /*timeout*/ -1);
+ if (len <= 0)
+ return;
+ while (len && isspace(buf[--len]))
+ buf[len] = '\0';
- for (i = 0; i < 26; i++)
- marks[i] = 0;
-
- return TRUE;
-}
-
-
-/*
- * Finish editing.
- */
-static void termEdit(void)
-{
- if (bufBase)
- free(bufBase);
-
- bufBase = NULL;
- bufPtr = NULL;
- bufSize = 0;
- bufUsed = 0;
-
- if (fileName)
- free(fileName);
-
- fileName = NULL;
-
- searchString[0] = '\0';
-
- if (lastNum)
- deleteLines(1, lastNum);
-
- lastNum = 0;
- curNum = 0;
- curLine = NULL;
-}
-
-
-/*
- * Read lines from a file at the specified line number.
- * Returns TRUE if the file was successfully read.
- */
-static int readLines(const char * file, int num)
-{
- int fd, cc;
- int len, lineCount, charCount;
- char *cp;
-
- if ((num < 1) || (num > lastNum + 1))
- {
- bb_error_msg("Bad line for read");
-
- return FALSE;
- }
-
- fd = open(file, 0);
-
- if (fd < 0)
- {
- perror(file);
-
- return FALSE;
- }
-
- bufPtr = bufBase;
- bufUsed = 0;
- lineCount = 0;
- charCount = 0;
- cc = 0;
-
- printf("\"%s\", ", file);
- fflush(stdout);
-
- do
- {
- cp = memchr(bufPtr, '\n', bufUsed);
-
- if (cp)
- {
- len = (cp - bufPtr) + 1;
-
- if (!insertLine(num, bufPtr, len))
- {
- close(fd);
-
- return FALSE;
- }
-
- bufPtr += len;
- bufUsed -= len;
- charCount += len;
- lineCount++;
- num++;
+ if ((curNum == 0) && (lastNum > 0)) {
+ curNum = 1;
+ curLine = lines.next;
+ }
+ have1 = FALSE;
+ have2 = FALSE;
+ /* Don't pass &haveN, &numN to getNum() since this forces
+ * compiler to keep them on stack, not in registers,
+ * which is usually quite suboptimal.
+ * Using intermediate variables shrinks code by ~150 bytes.
+ */
+ cp = getNum(skip_whitespace(buf), &h, &n);
+ if (!cp)
continue;
+ have1 = h;
+ num1 = n;
+ cp = skip_whitespace(cp);
+ if (*cp == ',') {
+ cp = getNum(cp + 1, &h, &n);
+ if (!cp)
+ continue;
+ num2 = n;
+ if (!have1)
+ num1 = 1;
+ if (!h)
+ num2 = lastNum;
+ have1 = TRUE;
+ have2 = TRUE;
}
+ if (!have1)
+ num1 = curNum;
+ if (!have2)
+ num2 = num1;
- if (bufPtr != bufBase)
- {
- memcpy(bufBase, bufPtr, bufUsed);
- bufPtr = bufBase + bufUsed;
- }
+ switch (*cp++) {
+ case 'a':
+ addLines(num1 + 1);
+ break;
- if (bufUsed >= bufSize)
- {
- len = (bufSize * 3) / 2;
- cp = realloc(bufBase, len);
+ case 'c':
+ deleteLines(num1, num2);
+ addLines(num1);
+ break;
- if (cp == NULL)
- {
- bb_error_msg("No memory for buffer");
- close(fd);
+ case 'd':
+ deleteLines(num1, num2);
+ break;
- return FALSE;
+ case 'f':
+ if (*cp != '\0' && *cp != ' ') {
+ bb_error_msg("bad file command");
+ break;
}
+ cp = skip_whitespace(cp);
+ if (*cp == '\0') {
+ if (fileName)
+ printf("\"%s\"\n", fileName);
+ else
+ puts("No file name");
+ break;
+ }
+ free(fileName);
+ fileName = xstrdup(cp);
+ break;
- bufBase = cp;
- bufPtr = bufBase + bufUsed;
- bufSize = len;
- }
-
- cc = read(fd, bufPtr, bufSize - bufUsed);
- bufUsed += cc;
- bufPtr = bufBase;
-
- }
- while (cc > 0);
-
- if (cc < 0)
- {
- perror(file);
- close(fd);
-
- return FALSE;
- }
-
- if (bufUsed)
- {
- if (!insertLine(num, bufPtr, bufUsed))
- {
- close(fd);
-
- return -1;
- }
-
- lineCount++;
- charCount += bufUsed;
- }
-
- close(fd);
-
- printf("%d lines%s, %d chars\n", lineCount,
- (bufUsed ? " (incomplete)" : ""), charCount);
-
- return TRUE;
-}
-
-
-/*
- * Write the specified lines out to the specified file.
- * Returns TRUE if successful, or FALSE on an error with a message output.
- */
-static int writeLines(const char * file, int num1, int num2)
-{
- LINE *lp;
- int fd, lineCount, charCount;
-
- if ((num1 < 1) || (num2 > lastNum) || (num1 > num2))
- {
- bb_error_msg("Bad line range for write");
-
- return FALSE;
- }
-
- lineCount = 0;
- charCount = 0;
-
- fd = creat(file, 0666);
-
- if (fd < 0) {
- perror(file);
-
- return FALSE;
- }
-
- printf("\"%s\", ", file);
- fflush(stdout);
-
- lp = findLine(num1);
-
- if (lp == NULL)
- {
- close(fd);
-
- return FALSE;
- }
-
- while (num1++ <= num2)
- {
- if (write(fd, lp->data, lp->len) != lp->len)
- {
- perror(file);
- close(fd);
-
- return FALSE;
- }
-
- charCount += lp->len;
- lineCount++;
- lp = lp->next;
- }
-
- if (close(fd) < 0)
- {
- perror(file);
-
- return FALSE;
- }
-
- printf("%d lines, %d chars\n", lineCount, charCount);
-
- return TRUE;
-}
-
-
-/*
- * Print lines in a specified range.
- * The last line printed becomes the current line.
- * If expandFlag is TRUE, then the line is printed specially to
- * show magic characters.
- */
-static int printLines(int num1, int num2, int expandFlag)
-{
- const LINE *lp;
- const char *cp;
- int ch, count;
-
- if ((num1 < 1) || (num2 > lastNum) || (num1 > num2))
- {
- bb_error_msg("Bad line range for print");
-
- return FALSE;
- }
-
- lp = findLine(num1);
-
- if (lp == NULL)
- return FALSE;
-
- while (num1 <= num2)
- {
- if (!expandFlag)
- {
- write(1, lp->data, lp->len);
- setCurNum(num1++);
- lp = lp->next;
-
- continue;
- }
+ case 'i':
+ if (!have1 && lastNum == 0)
+ num1 = 1;
+ addLines(num1);
+ break;
- /*
- * Show control characters and characters with the
- * high bit set specially.
- */
- cp = lp->data;
- count = lp->len;
+ case 'k':
+ cp = skip_whitespace(cp);
+ if ((unsigned)(*cp - 'a') >= 26 || cp[1]) {
+ bb_error_msg("bad mark name");
+ break;
+ }
+ marks[(unsigned)(*cp - 'a')] = num2;
+ break;
- if ((count > 0) && (cp[count - 1] == '\n'))
- count--;
+ case 'l':
+ printLines(num1, num2, TRUE);
+ break;
- while (count-- > 0)
- {
- ch = *cp++;
+ case 'p':
+ printLines(num1, num2, FALSE);
+ break;
- if (ch & 0x80)
- {
- fputs("M-", stdout);
- ch &= 0x7f;
+ case 'q':
+ cp = skip_whitespace(cp);
+ if (have1 || *cp) {
+ bb_error_msg("bad quit command");
+ break;
}
+ if (!dirty)
+ return;
+ len = read_line_input(NULL, "Really quit? ", buf, 16, /*timeout*/ -1);
+ /* read error/EOF - no way to continue */
+ if (len < 0)
+ return;
+ cp = skip_whitespace(buf);
+ if ((*cp | 0x20) == 'y') /* Y or y */
+ return;
+ break;
- if (ch < ' ')
- {
- fputc('^', stdout);
- ch += '@';
+ case 'r':
+ if (*cp != '\0' && *cp != ' ') {
+ bb_error_msg("bad read command");
+ break;
}
-
- if (ch == 0x7f)
- {
- fputc('^', stdout);
- ch = '?';
+ cp = skip_whitespace(cp);
+ if (*cp == '\0') {
+ bb_error_msg("no file name");
+ break;
}
+ if (!have1)
+ num1 = lastNum;
+ if (readLines(cp, num1 + 1))
+ break;
+ if (fileName == NULL)
+ fileName = xstrdup(cp);
+ break;
- fputc(ch, stdout);
- }
-
- fputs("$\n", stdout);
-
- setCurNum(num1++);
- lp = lp->next;
- }
-
- return TRUE;
-}
-
-
-/*
- * Insert a new line with the specified text.
- * The line is inserted so as to become the specified line,
- * thus pushing any existing and further lines down one.
- * The inserted line is also set to become the current line.
- * Returns TRUE if successful.
- */
-static int insertLine(int num, const char * data, int len)
-{
- LINE *newLp, *lp;
-
- if ((num < 1) || (num > lastNum + 1))
- {
- bb_error_msg("Inserting at bad line number");
-
- return FALSE;
- }
-
- newLp = (LINE *) malloc(sizeof(LINE) + len - 1);
+ case 's':
+ subCommand(cp, num1, num2);
+ break;
- if (newLp == NULL)
- {
- bb_error_msg("Failed to allocate memory for line");
+ case 'w':
+ if (*cp != '\0' && *cp != ' ') {
+ bb_error_msg("bad write command");
+ break;
+ }
+ cp = skip_whitespace(cp);
+ if (*cp == '\0') {
+ cp = fileName;
+ if (!cp) {
+ bb_error_msg("no file name specified");
+ break;
+ }
+ }
+ if (!have1) {
+ num1 = 1;
+ num2 = lastNum;
+ dirty = FALSE;
+ }
+ writeLines(cp, num1, num2);
+ break;
- return FALSE;
- }
+ case 'z':
+ switch (*cp) {
+ case '-':
+ printLines(curNum - 21, curNum, FALSE);
+ break;
+ case '.':
+ printLines(curNum - 11, curNum + 10, FALSE);
+ break;
+ default:
+ printLines(curNum, curNum + 21, FALSE);
+ break;
+ }
+ break;
- memcpy(newLp->data, data, len);
- newLp->len = len;
+ case '.':
+ if (have1) {
+ bb_error_msg("no arguments allowed");
+ break;
+ }
+ printLines(curNum, curNum, FALSE);
+ break;
- if (num > lastNum)
- lp = &lines;
- else
- {
- lp = findLine(num);
+ case '-':
+ if (setCurNum(curNum - 1))
+ printLines(curNum, curNum, FALSE);
+ break;
- if (lp == NULL)
- {
- free((char *) newLp);
+ case '=':
+ printf("%d\n", num1);
+ break;
+ case '\0':
+ if (have1) {
+ printLines(num2, num2, FALSE);
+ break;
+ }
+ if (setCurNum(curNum + 1))
+ printLines(curNum, curNum, FALSE);
+ break;
- return FALSE;
+ default:
+ bb_error_msg("unimplemented command");
+ break;
}
}
-
- newLp->next = lp;
- newLp->prev = lp->prev;
- lp->prev->next = newLp;
- lp->prev = newLp;
-
- lastNum++;
- dirty = TRUE;
-
- return setCurNum(num);
}
-
-/*
- * Delete lines from the given range.
- */
-static int deleteLines(int num1, int num2)
+int ed_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
+int ed_main(int argc UNUSED_PARAM, char **argv)
{
- LINE *lp, *nlp, *plp;
- int count;
-
- if ((num1 < 1) || (num2 > lastNum) || (num1 > num2))
- {
- bb_error_msg("Bad line numbers for delete");
-
- return FALSE;
- }
-
- lp = findLine(num1);
-
- if (lp == NULL)
- return FALSE;
-
- if ((curNum >= num1) && (curNum <= num2))
- {
- if (num2 < lastNum)
- setCurNum(num2 + 1);
- else if (num1 > 1)
- setCurNum(num1 - 1);
- else
- curNum = 0;
- }
-
- count = num2 - num1 + 1;
-
- if (curNum > num2)
- curNum -= count;
-
- lastNum -= count;
-
- while (count-- > 0)
- {
- nlp = lp->next;
- plp = lp->prev;
- plp->next = nlp;
- nlp->prev = plp;
- lp->next = NULL;
- lp->prev = NULL;
- lp->len = 0;
- free(lp);
- lp = nlp;
- }
+ INIT_G();
- dirty = TRUE;
-
- return TRUE;
-}
-
-
-/*
- * Search for a line which contains the specified string.
- * If the string is NULL, then the previously searched for string
- * is used. The currently searched for string is saved for future use.
- * Returns the line number which matches, or 0 if there was no match
- * with an error printed.
- */
-static int searchLines(const char *str, int num1, int num2)
-{
- const LINE *lp;
- int len;
-
- if ((num1 < 1) || (num2 > lastNum) || (num1 > num2))
- {
- bb_error_msg("Bad line numbers for search");
-
- return 0;
- }
-
- if (*str == '\0')
- {
- if (searchString[0] == '\0')
- {
- bb_error_msg("No previous search string");
+ bufSize = INITBUF_SIZE;
+ bufBase = xmalloc(bufSize);
+ bufPtr = bufBase;
+ lines.next = &lines;
+ lines.prev = &lines;
- return 0;
+ if (argv[1]) {
+ fileName = xstrdup(argv[1]);
+ if (!readLines(fileName, 1)) {
+ return EXIT_SUCCESS;
}
-
- str = searchString;
- }
-
- if (str != searchString)
- strcpy(searchString, str);
-
- len = strlen(str);
-
- lp = findLine(num1);
-
- if (lp == NULL)
- return 0;
-
- while (num1 <= num2)
- {
- if (findString(lp, str, len, 0) >= 0)
- return num1;
-
- num1++;
- lp = lp->next;
- }
-
- bb_error_msg("Cannot find string \"%s\"", str);
-
- return 0;
-}
-
-
-/*
- * Return a pointer to the specified line number.
- */
-static LINE *findLine(int num)
-{
- LINE *lp;
- int lnum;
-
- if ((num < 1) || (num > lastNum))
- {
- bb_error_msg("Line number %d does not exist", num);
-
- return NULL;
- }
-
- if (curNum <= 0)
- {
- curNum = 1;
- curLine = lines.next;
- }
-
- if (num == curNum)
- return curLine;
-
- lp = curLine;
- lnum = curNum;
-
- if (num < (curNum / 2))
- {
- lp = lines.next;
- lnum = 1;
- }
- else if (num > ((curNum + lastNum) / 2))
- {
- lp = lines.prev;
- lnum = lastNum;
- }
-
- while (lnum < num)
- {
- lp = lp->next;
- lnum++;
- }
-
- while (lnum > num)
- {
- lp = lp->prev;
- lnum--;
+ if (lastNum)
+ setCurNum(1);
+ dirty = FALSE;
}
- return lp;
-}
-
-
-/*
- * Set the current line number.
- * Returns TRUE if successful.
- */
-static int setCurNum(int num)
-{
- LINE *lp;
-
- lp = findLine(num);
-
- if (lp == NULL)
- return FALSE;
-
- curNum = num;
- curLine = lp;
-
- return TRUE;
+ doCommands();
+ return EXIT_SUCCESS;
}