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 UNUSED_PARAM, 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, 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");
198 fileName = xstrdup(cp);
207 if ((*cp < 'a') || (*cp > 'z') || cp[1]) {
208 bb_error_msg("bad mark name");
211 marks[*cp - 'a'] = num2;
215 printLines(num1, num2, TRUE);
219 printLines(num1, num2, FALSE);
225 bb_error_msg("bad quit command");
230 len = read_line_input("Really quit? ", buf, 16, NULL);
231 /* read error/EOF - no way to continue */
234 cp = skip_blank(buf);
235 if ((*cp | 0x20) == 'y') /* Y or y */
240 if (*cp && !isblank(*cp)) {
241 bb_error_msg("bad read command");
246 bb_error_msg("no file name");
251 if (readLines(cp, num1 + 1))
253 if (fileName == NULL)
254 fileName = xstrdup(cp);
258 subCommand(cp, num1, num2);
262 if (*cp && !isblank(*cp)) {
263 bb_error_msg("bad write command");
274 bb_error_msg("no file name specified");
277 writeLines(cp, num1, num2);
283 printLines(curNum - 21, curNum, FALSE);
286 printLines(curNum - 11, curNum + 10, FALSE);
289 printLines(curNum, curNum + 21, FALSE);
296 bb_error_msg("no arguments allowed");
299 printLines(curNum, curNum, FALSE);
303 if (setCurNum(curNum - 1))
304 printLines(curNum, curNum, FALSE);
308 printf("%d\n", num1);
312 printLines(num2, num2, FALSE);
315 if (setCurNum(curNum + 1))
316 printLines(curNum, curNum, FALSE);
320 bb_error_msg("unimplemented command");
328 * Do the substitute command.
329 * The current line is set to the last substitution done.
331 static void subCommand(const char *cmd, int num1, int num2)
333 char *cp, *oldStr, *newStr, buf[USERSIZE];
334 int delim, oldLen, newLen, deltaLen, offset;
336 int globalFlag, printFlag, didSub, needPrint;
338 if (bad_nums(num1, num2, "substitute"))
347 * Copy the command so we can modify it.
352 if (isblank(*cp) || (*cp == '\0')) {
353 bb_error_msg("bad delimiter for substitute");
360 cp = strchr(cp, delim);
362 bb_error_msg("missing 2nd delimiter for substitute");
369 cp = strchr(cp, delim);
376 while (*cp) switch (*cp++) {
384 bb_error_msg("unknown option for substitute");
388 if (*oldStr == '\0') {
389 if (searchString[0] == '\0') {
390 bb_error_msg("no previous search string");
393 oldStr = searchString;
396 if (oldStr != searchString)
397 strcpy(searchString, oldStr);
403 oldLen = strlen(oldStr);
404 newLen = strlen(newStr);
405 deltaLen = newLen - oldLen;
409 while (num1 <= num2) {
410 offset = findString(lp, oldStr, oldLen, offset);
414 printLines(num1, num1, FALSE);
423 needPrint = printFlag;
428 * If the replacement string is the same size or shorter
429 * than the old string, then the substitution is easy.
432 memcpy(&lp->data[offset], newStr, newLen);
434 memcpy(&lp->data[offset + newLen],
435 &lp->data[offset + oldLen],
436 lp->len - offset - oldLen);
444 printLines(num1, num1, FALSE);
453 * The new string is larger, so allocate a new line
454 * structure and use that. Link it in in place of
455 * the old line structure.
457 nlp = malloc(sizeof(LINE) + lp->len + deltaLen);
459 bb_error_msg("cannot get memory for line");
463 nlp->len = lp->len + deltaLen;
465 memcpy(nlp->data, lp->data, offset);
466 memcpy(&nlp->data[offset], newStr, newLen);
467 memcpy(&nlp->data[offset + newLen],
468 &lp->data[offset + oldLen],
469 lp->len - offset - oldLen);
471 nlp->next = lp->next;
472 nlp->prev = lp->prev;
473 nlp->prev->next = nlp;
474 nlp->next->prev = nlp;
488 printLines(num1, num1, FALSE);
497 bb_error_msg("no substitutions found for \"%s\"", oldStr);
502 * Search a line for the specified string starting at the specified
503 * offset in the line. Returns the offset of the found string, or -1.
505 static int findString(const LINE *lp, const char *str, int len, int offset)
508 const char *cp, *ncp;
510 cp = &lp->data[offset];
511 left = lp->len - offset;
513 while (left >= len) {
514 ncp = memchr(cp, *str, left);
521 if (memcmp(cp, str, len) == 0)
522 return (cp - lp->data);
532 * Add lines which are typed in by the user.
533 * The lines are inserted just before the specified line number.
534 * The lines are terminated by a line containing a single dot (ugly!),
535 * or by an end of file.
537 static void addLines(int num)
540 char buf[USERSIZE + 1];
544 * -1 on read errors or EOF, or on bare Ctrl-D.
546 * >0 length of input string, including terminating '\n'
548 len = read_line_input("", buf, sizeof(buf), NULL);
550 /* Previously, ctrl-C was exiting to shell.
551 * Now we exit to ed prompt. Is in important? */
554 if ((buf[0] == '.') && (buf[1] == '\n') && (buf[2] == '\0'))
556 if (!insertLine(num++, buf, len))
563 * Parse a line number argument if it is present. This is a sum
564 * or difference of numbers, '.', '$', 'x, or a search string.
565 * Returns TRUE if successful (whether or not there was a number).
566 * Returns FALSE if there was a parsing error, with a message output.
567 * Whether there was a number is returned indirectly, as is the number.
568 * The character pointer which stopped the scan is also returned.
570 static int getNum(const char **retcp, smallint *retHaveNum, int *retNum)
573 char *endStr, str[USERSIZE];
575 smallint haveNum, minus;
600 if ((*cp < 'a') || (*cp > 'z')) {
601 bb_error_msg("bad mark name");
605 num = marks[*cp++ - 'a'];
610 endStr = strchr(str, '/');
613 cp += (endStr - str);
616 num = searchLines(str, curNum, lastNum);
625 *retHaveNum = haveNum;
631 num = num * 10 + *cp++ - '0';
636 value += (minus ? -num : num);
653 *retHaveNum = haveNum;
662 * Read lines from a file at the specified line number.
663 * Returns TRUE if the file was successfully read.
665 static int readLines(const char *file, int num)
668 int len, lineCount, charCount;
671 if ((num < 1) || (num > lastNum + 1)) {
672 bb_error_msg("bad line for read");
688 printf("\"%s\", ", file);
692 cp = memchr(bufPtr, '\n', bufUsed);
695 len = (cp - bufPtr) + 1;
696 if (!insertLine(num, bufPtr, len)) {
708 if (bufPtr != bufBase) {
709 memcpy(bufBase, bufPtr, bufUsed);
710 bufPtr = bufBase + bufUsed;
713 if (bufUsed >= bufSize) {
714 len = (bufSize * 3) / 2;
715 cp = realloc(bufBase, len);
717 bb_error_msg("no memory for buffer");
722 bufPtr = bufBase + bufUsed;
726 cc = safe_read(fd, bufPtr, bufSize - bufUsed);
739 if (!insertLine(num, bufPtr, bufUsed)) {
744 charCount += bufUsed;
749 printf("%d lines%s, %d chars\n", lineCount,
750 (bufUsed ? " (incomplete)" : ""), charCount);
757 * Write the specified lines out to the specified file.
758 * Returns TRUE if successful, or FALSE on an error with a message output.
760 static int writeLines(const char *file, int num1, int num2)
763 int fd, lineCount, charCount;
765 if (bad_nums(num1, num2, "write"))
771 fd = creat(file, 0666);
777 printf("\"%s\", ", file);
786 while (num1++ <= num2) {
787 if (full_write(fd, lp->data, lp->len) != lp->len) {
792 charCount += lp->len;
802 printf("%d lines, %d chars\n", lineCount, charCount);
808 * Print lines in a specified range.
809 * The last line printed becomes the current line.
810 * If expandFlag is TRUE, then the line is printed specially to
811 * show magic characters.
813 static int printLines(int num1, int num2, int expandFlag)
819 if (bad_nums(num1, num2, "print"))
826 while (num1 <= num2) {
828 write(STDOUT_FILENO, lp->data, lp->len);
835 * Show control characters and characters with the
836 * high bit set specially.
841 if ((count > 0) && (cp[count - 1] == '\n'))
844 while (count-- > 0) {
845 ch = (unsigned char) *cp++;
846 fputc_printable(ch | PRINTABLE_META, stdout);
849 fputs("$\n", stdout);
860 * Insert a new line with the specified text.
861 * The line is inserted so as to become the specified line,
862 * thus pushing any existing and further lines down one.
863 * The inserted line is also set to become the current line.
864 * Returns TRUE if successful.
866 static int insertLine(int num, const char *data, int len)
870 if ((num < 1) || (num > lastNum + 1)) {
871 bb_error_msg("inserting at bad line number");
875 newLp = malloc(sizeof(LINE) + len - 1);
877 bb_error_msg("failed to allocate memory for line");
881 memcpy(newLp->data, data, len);
889 free((char *) newLp);
895 newLp->prev = lp->prev;
896 lp->prev->next = newLp;
901 return setCurNum(num);
906 * Delete lines from the given range.
908 static void deleteLines(int num1, int num2)
910 LINE *lp, *nlp, *plp;
913 if (bad_nums(num1, num2, "delete"))
920 if ((curNum >= num1) && (curNum <= num2)) {
929 count = num2 - num1 + 1;
934 while (count-- > 0) {
948 * Search for a line which contains the specified string.
949 * If the string is "", then the previously searched for string
950 * is used. The currently searched for string is saved for future use.
951 * Returns the line number which matches, or 0 if there was no match
952 * with an error printed.
954 static int searchLines(const char *str, int num1, int num2)
959 if (bad_nums(num1, num2, "search"))
963 if (searchString[0] == '\0') {
964 bb_error_msg("no previous search string");
970 if (str != searchString)
971 strcpy(searchString, str);
979 while (num1 <= num2) {
980 if (findString(lp, str, len, 0) >= 0)
986 bb_error_msg("cannot find string \"%s\"", str);
992 * Return a pointer to the specified line number.
994 static LINE *findLine(int num)
999 if ((num < 1) || (num > lastNum)) {
1000 bb_error_msg("line number %d does not exist", num);
1006 curLine = lines.next;
1014 if (num < (curNum / 2)) {
1017 } else if (num > ((curNum + lastNum) / 2)) {
1022 while (lnum < num) {
1027 while (lnum > num) {
1036 * Set the current line number.
1037 * Returns TRUE if successful.
1039 static int setCurNum(int num)