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 SET_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)
91 int ed_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
92 int ed_main(int argc ATTRIBUTE_UNUSED, char **argv)
96 bufSize = INITBUF_SIZE;
97 bufBase = xmalloc(bufSize);
103 fileName = xstrdup(argv[1]);
104 if (!readLines(fileName, 1)) {
117 * Read commands until we are told to stop.
119 static void doCommands(void)
122 char *endbuf, *newname, buf[USERSIZE];
124 smallint have1, have2;
128 * -1 on read errors or EOF, or on bare Ctrl-D.
130 * >0 length of input string, including terminating '\n'
132 len = read_line_input(": ", buf, sizeof(buf), NULL);
135 endbuf = &buf[len - 1];
136 while ((endbuf > buf) && isblank(endbuf[-1]))
140 cp = skip_blank(buf);
144 if ((curNum == 0) && (lastNum > 0)) {
146 curLine = lines.next;
149 if (!getNum(&cp, &have1, &num1))
156 if (!getNum(&cp, &have2, &num2))
176 deleteLines(num1, num2);
181 deleteLines(num1, num2);
185 if (*cp && !isblank(*cp)) {
186 bb_error_msg("bad file command");
192 printf("\"%s\"\n", fileName);
194 printf("No file name\n");
197 newname = strdup(cp);
198 if (newname == NULL) {
199 bb_error_msg("no memory for file name");
212 if ((*cp < 'a') || (*cp > 'z') || cp[1]) {
213 bb_error_msg("bad mark name");
216 marks[*cp - 'a'] = num2;
220 printLines(num1, num2, TRUE);
224 printLines(num1, num2, FALSE);
230 bb_error_msg("bad quit command");
235 len = read_line_input("Really quit? ", buf, 16, NULL);
236 /* read error/EOF - no way to continue */
239 cp = skip_blank(buf);
240 if ((*cp | 0x20) == 'y') /* Y or y */
245 if (*cp && !isblank(*cp)) {
246 bb_error_msg("bad read command");
251 bb_error_msg("no file name");
256 if (readLines(cp, num1 + 1))
258 if (fileName == NULL)
259 fileName = strdup(cp);
263 subCommand(cp, num1, num2);
267 if (*cp && !isblank(*cp)) {
268 bb_error_msg("bad write command");
279 bb_error_msg("no file name specified");
282 writeLines(cp, num1, num2);
288 printLines(curNum - 21, curNum, FALSE);
291 printLines(curNum - 11, curNum + 10, FALSE);
294 printLines(curNum, curNum + 21, FALSE);
301 bb_error_msg("no arguments allowed");
304 printLines(curNum, curNum, FALSE);
308 if (setCurNum(curNum - 1))
309 printLines(curNum, curNum, FALSE);
313 printf("%d\n", num1);
317 printLines(num2, num2, FALSE);
320 if (setCurNum(curNum + 1))
321 printLines(curNum, curNum, FALSE);
325 bb_error_msg("unimplemented command");
333 * Do the substitute command.
334 * The current line is set to the last substitution done.
336 static void subCommand(const char *cmd, int num1, int num2)
338 char *cp, *oldStr, *newStr, buf[USERSIZE];
339 int delim, oldLen, newLen, deltaLen, offset;
341 int globalFlag, printFlag, didSub, needPrint;
343 if (bad_nums(num1, num2, "substitute"))
352 * Copy the command so we can modify it.
357 if (isblank(*cp) || (*cp == '\0')) {
358 bb_error_msg("bad delimiter for substitute");
365 cp = strchr(cp, delim);
367 bb_error_msg("missing 2nd delimiter for substitute");
374 cp = strchr(cp, delim);
381 while (*cp) switch (*cp++) {
389 bb_error_msg("unknown option for substitute");
393 if (*oldStr == '\0') {
394 if (searchString[0] == '\0') {
395 bb_error_msg("no previous search string");
398 oldStr = searchString;
401 if (oldStr != searchString)
402 strcpy(searchString, oldStr);
408 oldLen = strlen(oldStr);
409 newLen = strlen(newStr);
410 deltaLen = newLen - oldLen;
414 while (num1 <= num2) {
415 offset = findString(lp, oldStr, oldLen, offset);
419 printLines(num1, num1, FALSE);
428 needPrint = printFlag;
433 * If the replacement string is the same size or shorter
434 * than the old string, then the substitution is easy.
437 memcpy(&lp->data[offset], newStr, newLen);
439 memcpy(&lp->data[offset + newLen],
440 &lp->data[offset + oldLen],
441 lp->len - offset - oldLen);
449 printLines(num1, num1, FALSE);
458 * The new string is larger, so allocate a new line
459 * structure and use that. Link it in in place of
460 * the old line structure.
462 nlp = malloc(sizeof(LINE) + lp->len + deltaLen);
464 bb_error_msg("cannot get memory for line");
468 nlp->len = lp->len + deltaLen;
470 memcpy(nlp->data, lp->data, offset);
471 memcpy(&nlp->data[offset], newStr, newLen);
472 memcpy(&nlp->data[offset + newLen],
473 &lp->data[offset + oldLen],
474 lp->len - offset - oldLen);
476 nlp->next = lp->next;
477 nlp->prev = lp->prev;
478 nlp->prev->next = nlp;
479 nlp->next->prev = nlp;
493 printLines(num1, num1, FALSE);
502 bb_error_msg("no substitutions found for \"%s\"", oldStr);
507 * Search a line for the specified string starting at the specified
508 * offset in the line. Returns the offset of the found string, or -1.
510 static int findString(const LINE *lp, const char *str, int len, int offset)
513 const char *cp, *ncp;
515 cp = &lp->data[offset];
516 left = lp->len - offset;
518 while (left >= len) {
519 ncp = memchr(cp, *str, left);
526 if (memcmp(cp, str, len) == 0)
527 return (cp - lp->data);
537 * Add lines which are typed in by the user.
538 * The lines are inserted just before the specified line number.
539 * The lines are terminated by a line containing a single dot (ugly!),
540 * or by an end of file.
542 static void addLines(int num)
545 char buf[USERSIZE + 1];
549 * -1 on read errors or EOF, or on bare Ctrl-D.
551 * >0 length of input string, including terminating '\n'
553 len = read_line_input("", buf, sizeof(buf), NULL);
555 /* Previously, ctrl-C was exiting to shell.
556 * Now we exit to ed prompt. Is in important? */
559 if ((buf[0] == '.') && (buf[1] == '\n') && (buf[2] == '\0'))
561 if (!insertLine(num++, buf, len))
568 * Parse a line number argument if it is present. This is a sum
569 * or difference of numbers, '.', '$', 'x, or a search string.
570 * Returns TRUE if successful (whether or not there was a number).
571 * Returns FALSE if there was a parsing error, with a message output.
572 * Whether there was a number is returned indirectly, as is the number.
573 * The character pointer which stopped the scan is also returned.
575 static int getNum(const char **retcp, smallint *retHaveNum, int *retNum)
578 char *endStr, str[USERSIZE];
580 smallint haveNum, minus;
605 if ((*cp < 'a') || (*cp > 'z')) {
606 bb_error_msg("bad mark name");
610 num = marks[*cp++ - 'a'];
615 endStr = strchr(str, '/');
618 cp += (endStr - str);
621 num = searchLines(str, curNum, lastNum);
630 *retHaveNum = haveNum;
636 num = num * 10 + *cp++ - '0';
641 value += (minus ? -num : num);
658 *retHaveNum = haveNum;
667 * Read lines from a file at the specified line number.
668 * Returns TRUE if the file was successfully read.
670 static int readLines(const char *file, int num)
673 int len, lineCount, charCount;
676 if ((num < 1) || (num > lastNum + 1)) {
677 bb_error_msg("bad line for read");
693 printf("\"%s\", ", file);
697 cp = memchr(bufPtr, '\n', bufUsed);
700 len = (cp - bufPtr) + 1;
701 if (!insertLine(num, bufPtr, len)) {
713 if (bufPtr != bufBase) {
714 memcpy(bufBase, bufPtr, bufUsed);
715 bufPtr = bufBase + bufUsed;
718 if (bufUsed >= bufSize) {
719 len = (bufSize * 3) / 2;
720 cp = realloc(bufBase, len);
722 bb_error_msg("no memory for buffer");
727 bufPtr = bufBase + bufUsed;
731 cc = safe_read(fd, bufPtr, bufSize - bufUsed);
744 if (!insertLine(num, bufPtr, bufUsed)) {
749 charCount += bufUsed;
754 printf("%d lines%s, %d chars\n", lineCount,
755 (bufUsed ? " (incomplete)" : ""), charCount);
762 * Write the specified lines out to the specified file.
763 * Returns TRUE if successful, or FALSE on an error with a message output.
765 static int writeLines(const char *file, int num1, int num2)
768 int fd, lineCount, charCount;
770 if (bad_nums(num1, num2, "write"))
776 fd = creat(file, 0666);
782 printf("\"%s\", ", file);
791 while (num1++ <= num2) {
792 if (full_write(fd, lp->data, lp->len) != lp->len) {
797 charCount += lp->len;
807 printf("%d lines, %d chars\n", lineCount, charCount);
813 * Print lines in a specified range.
814 * The last line printed becomes the current line.
815 * If expandFlag is TRUE, then the line is printed specially to
816 * show magic characters.
818 static int printLines(int num1, int num2, int expandFlag)
824 if (bad_nums(num1, num2, "print"))
831 while (num1 <= num2) {
833 write(1, lp->data, lp->len);
840 * Show control characters and characters with the
841 * high bit set specially.
846 if ((count > 0) && (cp[count - 1] == '\n'))
849 while (count-- > 0) {
850 ch = (unsigned char) *cp++;
851 fputc_printable(ch | PRINTABLE_META, stdout);
854 fputs("$\n", stdout);
865 * Insert a new line with the specified text.
866 * The line is inserted so as to become the specified line,
867 * thus pushing any existing and further lines down one.
868 * The inserted line is also set to become the current line.
869 * Returns TRUE if successful.
871 static int insertLine(int num, const char *data, int len)
875 if ((num < 1) || (num > lastNum + 1)) {
876 bb_error_msg("inserting at bad line number");
880 newLp = malloc(sizeof(LINE) + len - 1);
882 bb_error_msg("failed to allocate memory for line");
886 memcpy(newLp->data, data, len);
894 free((char *) newLp);
900 newLp->prev = lp->prev;
901 lp->prev->next = newLp;
906 return setCurNum(num);
911 * Delete lines from the given range.
913 static void deleteLines(int num1, int num2)
915 LINE *lp, *nlp, *plp;
918 if (bad_nums(num1, num2, "delete"))
925 if ((curNum >= num1) && (curNum <= num2)) {
934 count = num2 - num1 + 1;
939 while (count-- > 0) {
953 * Search for a line which contains the specified string.
954 * If the string is "", then the previously searched for string
955 * is used. The currently searched for string is saved for future use.
956 * Returns the line number which matches, or 0 if there was no match
957 * with an error printed.
959 static int searchLines(const char *str, int num1, int num2)
964 if (bad_nums(num1, num2, "search"))
968 if (searchString[0] == '\0') {
969 bb_error_msg("no previous search string");
975 if (str != searchString)
976 strcpy(searchString, str);
984 while (num1 <= num2) {
985 if (findString(lp, str, len, 0) >= 0)
991 bb_error_msg("cannot find string \"%s\"", str);
997 * Return a pointer to the specified line number.
999 static LINE *findLine(int num)
1004 if ((num < 1) || (num > lastNum)) {
1005 bb_error_msg("line number %d does not exist", num);
1011 curLine = lines.next;
1019 if (num < (curNum / 2)) {
1022 } else if (num > ((curNum + lastNum) / 2)) {
1027 while (lnum < num) {
1032 while (lnum > num) {
1041 * Set the current line number.
1042 * Returns TRUE if successful.
1044 static int setCurNum(int num)