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 = xmalloc(sizeof(LINE) + lp->len + deltaLen);
459 nlp->len = lp->len + deltaLen;
461 memcpy(nlp->data, lp->data, offset);
462 memcpy(&nlp->data[offset], newStr, newLen);
463 memcpy(&nlp->data[offset + newLen],
464 &lp->data[offset + oldLen],
465 lp->len - offset - oldLen);
467 nlp->next = lp->next;
468 nlp->prev = lp->prev;
469 nlp->prev->next = nlp;
470 nlp->next->prev = nlp;
484 printLines(num1, num1, FALSE);
493 bb_error_msg("no substitutions found for \"%s\"", oldStr);
498 * Search a line for the specified string starting at the specified
499 * offset in the line. Returns the offset of the found string, or -1.
501 static int findString(const LINE *lp, const char *str, int len, int offset)
504 const char *cp, *ncp;
506 cp = &lp->data[offset];
507 left = lp->len - offset;
509 while (left >= len) {
510 ncp = memchr(cp, *str, left);
517 if (memcmp(cp, str, len) == 0)
518 return (cp - lp->data);
528 * Add lines which are typed in by the user.
529 * The lines are inserted just before the specified line number.
530 * The lines are terminated by a line containing a single dot (ugly!),
531 * or by an end of file.
533 static void addLines(int num)
536 char buf[USERSIZE + 1];
540 * -1 on read errors or EOF, or on bare Ctrl-D.
542 * >0 length of input string, including terminating '\n'
544 len = read_line_input("", buf, sizeof(buf), NULL);
546 /* Previously, ctrl-C was exiting to shell.
547 * Now we exit to ed prompt. Is in important? */
550 if ((buf[0] == '.') && (buf[1] == '\n') && (buf[2] == '\0'))
552 if (!insertLine(num++, buf, len))
559 * Parse a line number argument if it is present. This is a sum
560 * or difference of numbers, '.', '$', 'x, or a search string.
561 * Returns TRUE if successful (whether or not there was a number).
562 * Returns FALSE if there was a parsing error, with a message output.
563 * Whether there was a number is returned indirectly, as is the number.
564 * The character pointer which stopped the scan is also returned.
566 static int getNum(const char **retcp, smallint *retHaveNum, int *retNum)
569 char *endStr, str[USERSIZE];
571 smallint haveNum, minus;
596 if ((*cp < 'a') || (*cp > 'z')) {
597 bb_error_msg("bad mark name");
601 num = marks[*cp++ - 'a'];
606 endStr = strchr(str, '/');
609 cp += (endStr - str);
612 num = searchLines(str, curNum, lastNum);
621 *retHaveNum = haveNum;
627 num = num * 10 + *cp++ - '0';
632 value += (minus ? -num : num);
649 *retHaveNum = haveNum;
658 * Read lines from a file at the specified line number.
659 * Returns TRUE if the file was successfully read.
661 static int readLines(const char *file, int num)
664 int len, lineCount, charCount;
667 if ((num < 1) || (num > lastNum + 1)) {
668 bb_error_msg("bad line for read");
684 printf("\"%s\", ", file);
688 cp = memchr(bufPtr, '\n', bufUsed);
691 len = (cp - bufPtr) + 1;
692 if (!insertLine(num, bufPtr, len)) {
704 if (bufPtr != bufBase) {
705 memcpy(bufBase, bufPtr, bufUsed);
706 bufPtr = bufBase + bufUsed;
709 if (bufUsed >= bufSize) {
710 len = (bufSize * 3) / 2;
711 cp = xrealloc(bufBase, len);
713 bufPtr = bufBase + bufUsed;
717 cc = safe_read(fd, bufPtr, bufSize - bufUsed);
730 if (!insertLine(num, bufPtr, bufUsed)) {
735 charCount += bufUsed;
740 printf("%d lines%s, %d chars\n", lineCount,
741 (bufUsed ? " (incomplete)" : ""), charCount);
748 * Write the specified lines out to the specified file.
749 * Returns TRUE if successful, or FALSE on an error with a message output.
751 static int writeLines(const char *file, int num1, int num2)
754 int fd, lineCount, charCount;
756 if (bad_nums(num1, num2, "write"))
762 fd = creat(file, 0666);
768 printf("\"%s\", ", file);
777 while (num1++ <= num2) {
778 if (full_write(fd, lp->data, lp->len) != lp->len) {
783 charCount += lp->len;
793 printf("%d lines, %d chars\n", lineCount, charCount);
799 * Print lines in a specified range.
800 * The last line printed becomes the current line.
801 * If expandFlag is TRUE, then the line is printed specially to
802 * show magic characters.
804 static int printLines(int num1, int num2, int expandFlag)
810 if (bad_nums(num1, num2, "print"))
817 while (num1 <= num2) {
819 write(STDOUT_FILENO, lp->data, lp->len);
826 * Show control characters and characters with the
827 * high bit set specially.
832 if ((count > 0) && (cp[count - 1] == '\n'))
835 while (count-- > 0) {
836 ch = (unsigned char) *cp++;
837 fputc_printable(ch | PRINTABLE_META, stdout);
840 fputs("$\n", stdout);
851 * Insert a new line with the specified text.
852 * The line is inserted so as to become the specified line,
853 * thus pushing any existing and further lines down one.
854 * The inserted line is also set to become the current line.
855 * Returns TRUE if successful.
857 static int insertLine(int num, const char *data, int len)
861 if ((num < 1) || (num > lastNum + 1)) {
862 bb_error_msg("inserting at bad line number");
866 newLp = xmalloc(sizeof(LINE) + len - 1);
868 memcpy(newLp->data, data, len);
876 free((char *) newLp);
882 newLp->prev = lp->prev;
883 lp->prev->next = newLp;
888 return setCurNum(num);
893 * Delete lines from the given range.
895 static void deleteLines(int num1, int num2)
897 LINE *lp, *nlp, *plp;
900 if (bad_nums(num1, num2, "delete"))
907 if ((curNum >= num1) && (curNum <= num2)) {
916 count = num2 - num1 + 1;
921 while (count-- > 0) {
935 * Search for a line which contains the specified string.
936 * If the string is "", then the previously searched for string
937 * is used. The currently searched for string is saved for future use.
938 * Returns the line number which matches, or 0 if there was no match
939 * with an error printed.
941 static NOINLINE int searchLines(const char *str, int num1, int num2)
946 if (bad_nums(num1, num2, "search"))
950 if (searchString[0] == '\0') {
951 bb_error_msg("no previous search string");
957 if (str != searchString)
958 strcpy(searchString, str);
966 while (num1 <= num2) {
967 if (findString(lp, str, len, 0) >= 0)
973 bb_error_msg("can't find string \"%s\"", str);
979 * Return a pointer to the specified line number.
981 static LINE *findLine(int num)
986 if ((num < 1) || (num > lastNum)) {
987 bb_error_msg("line number %d does not exist", num);
993 curLine = lines.next;
1001 if (num < (curNum / 2)) {
1004 } else if (num > ((curNum + lastNum) / 2)) {
1009 while (lnum < num) {
1014 while (lnum > num) {
1023 * Set the current line number.
1024 * Returns TRUE if successful.
1026 static int setCurNum(int num)