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)
12 #define searchString bb_common_bufsiz1
15 USERSIZE = sizeof(searchString) > 1024 ? 1024
16 : sizeof(searchString) - 1, /* max line length typed in by user */
17 INITBUF_SIZE = 1024, /* initial buffer size */
27 static LINE lines, *curLine;
28 static int curNum, lastNum, marks[26], dirty;
29 static char *bufBase, *bufPtr, *fileName;
30 static int bufUsed, bufSize;
32 static void doCommands(void);
33 static void subCommand(const char *cmd, int num1, int num2);
34 static int getNum(const char **retcp, int *retHaveNum, int *retNum);
35 static int setCurNum(int num);
36 static int initEdit(void);
37 static void termEdit(void);
38 static void addLines(int num);
39 static int insertLine(int num, const char *data, int len);
40 static int deleteLines(int num1, int num2);
41 static int printLines(int num1, int num2, int expandFlag);
42 static int writeLines(const char *file, int num1, int num2);
43 static int readLines(const char *file, int num);
44 static int searchLines(const char *str, int num1, int num2);
45 static LINE *findLine(int num);
47 static int findString(const LINE *lp, const char * str, int len, int offset);
49 int ed_main(int argc, char **argv);
50 int ed_main(int argc, char **argv)
56 fileName = strdup(argv[1]);
58 if (fileName == NULL) {
59 bb_error_msg("no memory");
64 if (!readLines(fileName, 1)) {
82 * Read commands until we are told to stop.
84 static void doCommands(void)
87 char *endbuf, *newname, buf[USERSIZE];
88 int len, num1, num2, have1, have2;
94 if (fgets(buf, sizeof(buf), stdin) == NULL)
102 endbuf = &buf[len - 1];
104 if (*endbuf != '\n') {
105 bb_error_msg("command line too long");
109 } while ((len != EOF) && (len != '\n'));
114 while ((endbuf > buf) && isblank(endbuf[-1]))
127 if ((curNum == 0) && (lastNum > 0)) {
129 curLine = lines.next;
132 if (!getNum(&cp, &have1, &num1))
141 if (!getNum(&cp, &have2, &num2))
166 deleteLines(num1, num2);
171 deleteLines(num1, num2);
175 if (*cp && !isblank(*cp)) {
176 bb_error_msg("bad file command");
185 printf("\"%s\"\n", fileName);
187 printf("No file name\n");
191 newname = strdup(cp);
193 if (newname == NULL) {
194 bb_error_msg("no memory for file name");
212 if ((*cp < 'a') || (*cp > 'a') || cp[1]) {
213 bb_error_msg("bad mark name");
217 marks[*cp - 'a'] = num2;
221 printLines(num1, num2, TRUE);
225 printLines(num1, num2, FALSE);
233 bb_error_msg("bad quit command");
240 printf("Really quit? ");
244 fgets(buf, sizeof(buf), stdin);
250 if ((*cp == 'y') || (*cp == 'Y'))
256 if (*cp && !isblank(*cp)) {
257 bb_error_msg("bad read command");
265 bb_error_msg("no file name");
272 if (readLines(cp, num1 + 1))
275 if (fileName == NULL)
276 fileName = strdup(cp);
281 subCommand(cp, num1, num2);
285 if (*cp && !isblank(*cp)) {
286 bb_error_msg("bad write command");
302 bb_error_msg("no file name specified");
306 writeLines(cp, num1, num2);
312 printLines(curNum-21, curNum, FALSE);
315 printLines(curNum-11, curNum+10, FALSE);
318 printLines(curNum, curNum+21, FALSE);
325 bb_error_msg("no arguments allowed");
329 printLines(curNum, curNum, FALSE);
333 if (setCurNum(curNum - 1))
334 printLines(curNum, curNum, FALSE);
339 printf("%d\n", num1);
344 printLines(num2, num2, FALSE);
348 if (setCurNum(curNum + 1))
349 printLines(curNum, curNum, FALSE);
354 bb_error_msg("unimplemented command");
362 * Do the substitute command.
363 * The current line is set to the last substitution done.
365 static void subCommand(const char * cmd, int num1, int num2)
367 char *cp, *oldStr, *newStr, buf[USERSIZE];
368 int delim, oldLen, newLen, deltaLen, offset;
370 int globalFlag, printFlag, didSub, needPrint;
372 if ((num1 < 1) || (num2 > lastNum) || (num1 > num2)) {
373 bb_error_msg("bad line range for substitute");
383 * Copy the command so we can modify it.
388 if (isblank(*cp) || (*cp == '\0')) {
389 bb_error_msg("bad delimiter for substitute");
396 cp = strchr(cp, delim);
399 bb_error_msg("missing 2nd delimiter for substitute");
406 cp = strchr(cp, delim);
413 while (*cp) switch (*cp++) {
423 bb_error_msg("unknown option for substitute");
427 if (*oldStr == '\0') {
428 if (searchString[0] == '\0') {
429 bb_error_msg("no previous search string");
433 oldStr = searchString;
436 if (oldStr != searchString)
437 strcpy(searchString, oldStr);
444 oldLen = strlen(oldStr);
445 newLen = strlen(newStr);
446 deltaLen = newLen - oldLen;
450 while (num1 <= num2) {
451 offset = findString(lp, oldStr, oldLen, offset);
455 printLines(num1, num1, FALSE);
466 needPrint = printFlag;
471 * If the replacement string is the same size or shorter
472 * than the old string, then the substitution is easy.
475 memcpy(&lp->data[offset], newStr, newLen);
478 memcpy(&lp->data[offset + newLen],
479 &lp->data[offset + oldLen],
480 lp->len - offset - oldLen);
491 printLines(num1, num1, FALSE);
502 * The new string is larger, so allocate a new line
503 * structure and use that. Link it in in place of
504 * the old line structure.
506 nlp = (LINE *) malloc(sizeof(LINE) + lp->len + deltaLen);
509 bb_error_msg("cannot get memory for line");
513 nlp->len = lp->len + deltaLen;
515 memcpy(nlp->data, lp->data, offset);
517 memcpy(&nlp->data[offset], newStr, newLen);
519 memcpy(&nlp->data[offset + newLen],
520 &lp->data[offset + oldLen],
521 lp->len - offset - oldLen);
523 nlp->next = lp->next;
524 nlp->prev = lp->prev;
525 nlp->prev->next = nlp;
526 nlp->next->prev = nlp;
540 printLines(num1, num1, FALSE);
549 bb_error_msg("no substitutions found for \"%s\"", oldStr);
554 * Search a line for the specified string starting at the specified
555 * offset in the line. Returns the offset of the found string, or -1.
557 static int findString( const LINE * lp, const char * str, int len, int offset)
560 const char *cp, *ncp;
562 cp = &lp->data[offset];
563 left = lp->len - offset;
565 while (left >= len) {
566 ncp = memchr(cp, *str, left);
578 if (memcmp(cp, str, len) == 0)
579 return (cp - lp->data);
590 * Add lines which are typed in by the user.
591 * The lines are inserted just before the specified line number.
592 * The lines are terminated by a line containing a single dot (ugly!),
593 * or by an end of file.
595 static void addLines(int num)
598 char buf[USERSIZE + 1];
600 while (fgets(buf, sizeof(buf), stdin)) {
601 if ((buf[0] == '.') && (buf[1] == '\n') && (buf[2] == '\0'))
609 if (buf[len - 1] != '\n') {
610 bb_error_msg("line too long");
613 } while ((len != EOF) && (len != '\n'));
617 if (!insertLine(num++, buf, len))
624 * Parse a line number argument if it is present. This is a sum
625 * or difference of numbers, '.', '$', 'x, or a search string.
626 * Returns TRUE if successful (whether or not there was a number).
627 * Returns FALSE if there was a parsing error, with a message output.
628 * Whether there was a number is returned indirectly, as is the number.
629 * The character pointer which stopped the scan is also returned.
631 static int getNum(const char **retcp, int *retHaveNum, int *retNum)
634 char *endStr, str[USERSIZE];
635 int haveNum, value, num, sign;
662 if ((*cp < 'a') || (*cp > 'z')) {
663 bb_error_msg("bad mark name");
668 num = marks[*cp++ - 'a'];
673 endStr = strchr(str, '/');
677 cp += (endStr - str);
682 num = searchLines(str, curNum, lastNum);
693 *retHaveNum = haveNum;
701 num = num * 10 + *cp++ - '0';
725 *retHaveNum = haveNum;
734 * Initialize everything for editing.
736 static int initEdit(void)
740 bufSize = INITBUF_SIZE;
741 bufBase = malloc(bufSize);
743 if (bufBase == NULL) {
744 bb_error_msg("no memory for buffer");
759 searchString[0] = '\0';
761 for (i = 0; i < 26; i++)
771 static void termEdit(void)
786 searchString[0] = '\0';
789 deleteLines(1, lastNum);
798 * Read lines from a file at the specified line number.
799 * Returns TRUE if the file was successfully read.
801 static int readLines(const char * file, int num)
804 int len, lineCount, charCount;
807 if ((num < 1) || (num > lastNum + 1)) {
808 bb_error_msg("bad line for read");
825 printf("\"%s\", ", file);
829 cp = memchr(bufPtr, '\n', bufUsed);
832 len = (cp - bufPtr) + 1;
834 if (!insertLine(num, bufPtr, len)) {
848 if (bufPtr != bufBase) {
849 memcpy(bufBase, bufPtr, bufUsed);
850 bufPtr = bufBase + bufUsed;
853 if (bufUsed >= bufSize) {
854 len = (bufSize * 3) / 2;
855 cp = realloc(bufBase, len);
858 bb_error_msg("no memory for buffer");
864 bufPtr = bufBase + bufUsed;
868 cc = read(fd, bufPtr, bufSize - bufUsed);
881 if (!insertLine(num, bufPtr, bufUsed)) {
887 charCount += bufUsed;
892 printf("%d lines%s, %d chars\n", lineCount,
893 (bufUsed ? " (incomplete)" : ""), charCount);
900 * Write the specified lines out to the specified file.
901 * Returns TRUE if successful, or FALSE on an error with a message output.
903 static int writeLines(const char * file, int num1, int num2)
906 int fd, lineCount, charCount;
908 if ((num1 < 1) || (num2 > lastNum) || (num1 > num2)) {
909 bb_error_msg("bad line range for write");
916 fd = creat(file, 0666);
923 printf("\"%s\", ", file);
933 while (num1++ <= num2) {
934 if (write(fd, lp->data, lp->len) != lp->len) {
940 charCount += lp->len;
950 printf("%d lines, %d chars\n", lineCount, charCount);
956 * Print lines in a specified range.
957 * The last line printed becomes the current line.
958 * If expandFlag is TRUE, then the line is printed specially to
959 * show magic characters.
961 static int printLines(int num1, int num2, int expandFlag)
967 if ((num1 < 1) || (num2 > lastNum) || (num1 > num2)) {
968 bb_error_msg("bad line range for print");
977 while (num1 <= num2) {
979 write(1, lp->data, lp->len);
987 * Show control characters and characters with the
988 * high bit set specially.
993 if ((count > 0) && (cp[count - 1] == '\n'))
996 while (count-- > 0) {
1000 fputs("M-", stdout);
1017 fputs("$\n", stdout);
1028 * Insert a new line with the specified text.
1029 * The line is inserted so as to become the specified line,
1030 * thus pushing any existing and further lines down one.
1031 * The inserted line is also set to become the current line.
1032 * Returns TRUE if successful.
1034 static int insertLine(int num, const char * data, int len)
1038 if ((num < 1) || (num > lastNum + 1)) {
1039 bb_error_msg("inserting at bad line number");
1043 newLp = malloc(sizeof(LINE) + len - 1);
1045 if (newLp == NULL) {
1046 bb_error_msg("failed to allocate memory for line");
1050 memcpy(newLp->data, data, len);
1059 free((char *) newLp);
1065 newLp->prev = lp->prev;
1066 lp->prev->next = newLp;
1071 return setCurNum(num);
1076 * Delete lines from the given range.
1078 static int deleteLines(int num1, int num2)
1080 LINE *lp, *nlp, *plp;
1083 if ((num1 < 1) || (num2 > lastNum) || (num1 > num2)) {
1084 bb_error_msg("bad line numbers for delete");
1088 lp = findLine(num1);
1093 if ((curNum >= num1) && (curNum <= num2)) {
1095 setCurNum(num2 + 1);
1097 setCurNum(num1 - 1);
1102 count = num2 - num1 + 1;
1109 while (count-- > 0) {
1128 * Search for a line which contains the specified string.
1129 * If the string is NULL, then the previously searched for string
1130 * is used. The currently searched for string is saved for future use.
1131 * Returns the line number which matches, or 0 if there was no match
1132 * with an error printed.
1134 static int searchLines(const char *str, int num1, int num2)
1139 if ((num1 < 1) || (num2 > lastNum) || (num1 > num2)) {
1140 bb_error_msg("bad line numbers for search");
1145 if (searchString[0] == '\0') {
1146 bb_error_msg("no previous search string");
1153 if (str != searchString)
1154 strcpy(searchString, str);
1158 lp = findLine(num1);
1163 while (num1 <= num2) {
1164 if (findString(lp, str, len, 0) >= 0)
1171 bb_error_msg("cannot find string \"%s\"", str);
1177 * Return a pointer to the specified line number.
1179 static LINE *findLine(int num)
1184 if ((num < 1) || (num > lastNum)) {
1185 bb_error_msg("line number %d does not exist", num);
1191 curLine = lines.next;
1200 if (num < (curNum / 2)) {
1204 else if (num > ((curNum + lastNum) / 2)) {
1209 while (lnum < num) {
1214 while (lnum > num) {
1223 * Set the current line number.
1224 * Returns TRUE if successful.
1226 static int setCurNum(int num)