#ifdef TIOCGWINSZ usage on TIOCGWINSZ
[nvi.git] / ex / ex.c
blob31fec84c94a26f415ee2501965b9556af4fd1ddd
1 /*-
2 * Copyright (c) 1992, 1993
3 * The Regents of the University of California. All rights reserved.
5 * %sccs.include.redist.c%
6 */
8 #ifndef lint
9 static char sccsid[] = "$Id: ex.c,v 8.85 1993/12/23 11:30:03 bostic Exp $ (Berkeley) $Date: 1993/12/23 11:30:03 $";
10 #endif /* not lint */
12 #include <sys/types.h>
13 #include <sys/stat.h>
15 #include <ctype.h>
16 #include <errno.h>
17 #include <fcntl.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <unistd.h>
22 #include "vi.h"
23 #include "excmd.h"
25 static inline EXCMDLIST const *
26 ex_comm_search __P((char *, size_t));
27 static int ep_line __P((SCR *, EXF *, MARK *, char **, size_t *, int *));
28 static int ep_range __P((SCR *, EXF *, EXCMDARG *, char **, size_t *));
30 #define DEFCOM ".+1"
33 * ex --
34 * Read an ex command and execute it.
36 int
37 ex(sp, ep)
38 SCR *sp;
39 EXF *ep;
41 TEXT *tp;
42 u_int saved_mode;
43 int eval;
44 char defcom[sizeof(DEFCOM)];
46 if (ex_init(sp, ep))
47 return (1);
49 if (sp->s_refresh(sp, ep))
50 return (ex_end(sp));
52 /* If reading from a file, messages should have line info. */
53 if (!F_ISSET(sp->gp, G_ISFROMTTY)) {
54 sp->if_lno = 1;
55 sp->if_name = strdup("input");
57 for (eval = 0;; ++sp->if_lno) {
58 /* Get the next command. */
59 switch (sp->s_get(sp, ep, &sp->tiq, ':', TXT_CR | TXT_PROMPT)) {
60 case INP_OK:
61 break;
62 case INP_EOF:
63 F_SET(sp, S_EXIT_FORCE);
64 goto ret;
65 case INP_ERR:
66 continue;
69 saved_mode = F_ISSET(sp, S_SCREENS | S_MAJOR_CHANGE);
70 tp = sp->tiq.cqh_first;
71 if (tp->len == 0) {
72 if (F_ISSET(sp->gp, G_ISFROMTTY)) {
73 (void)fputc('\r', stdout);
74 (void)fflush(stdout);
76 memmove(defcom, DEFCOM, sizeof(DEFCOM));
77 (void)ex_icmd(sp, ep, defcom, sizeof(DEFCOM) - 1);
78 } else {
79 if (F_ISSET(sp->gp, G_ISFROMTTY))
80 (void)fputc('\n', stdout);
81 (void)ex_icmd(sp, ep, tp->lb, tp->len);
83 (void)msg_rpt(sp, 0);
85 if (saved_mode != F_ISSET(sp, S_SCREENS | S_MAJOR_CHANGE))
86 break;
88 if (sp->s_refresh(sp, ep)) {
89 eval = 1;
90 break;
93 ret: if (sp->if_name != NULL) {
94 FREE(sp->if_name, strlen(sp->if_name) + 1);
95 sp->if_name = NULL;
97 return (ex_end(sp) || eval);
101 * ex_cfile --
102 * Execute ex commands from a file.
105 ex_cfile(sp, ep, filename)
106 SCR *sp;
107 EXF *ep;
108 char *filename;
110 struct stat sb;
111 int fd, len, rval;
112 char *bp;
114 bp = NULL;
115 if ((fd = open(filename, O_RDONLY, 0)) < 0 || fstat(fd, &sb))
116 goto err;
119 * XXX
120 * We'd like to test if the file is too big to malloc. Since we don't
121 * know what size or type off_t's or size_t's are, what the largest
122 * unsigned integral type is, or what random insanity the local C
123 * compiler will perpetrate, doing the comparison in a portable way
124 * is flatly impossible. Hope that malloc fails if the file is too
125 * large.
127 MALLOC(sp, bp, char *, (size_t)sb.st_size + 1);
128 if (bp == NULL)
129 goto err;
131 len = read(fd, bp, (int)sb.st_size);
132 if (len == -1 || len != sb.st_size) {
133 if (len != sb.st_size)
134 errno = EIO;
135 err: rval = 1;
136 msgq(sp, M_SYSERR, filename);
137 } else {
138 bp[sb.st_size] = '\0'; /* XXX */
140 /* Run the command. Messages include file/line information. */
141 sp->if_lno = 1;
142 sp->if_name = strdup(filename);
143 rval = ex_icmd(sp, ep, bp, len);
144 FREE(sp->if_name, strlen(sp->if_name) + 1);
145 sp->if_name = NULL;
149 * !!!
150 * THE UNDERLYING EXF MAY HAVE CHANGED.
152 if (bp != NULL)
153 FREE(bp, sb.st_size);
154 if (fd >= 0)
155 (void)close(fd);
156 return (rval);
160 * ex_icmd --
161 * Call ex_cmd() after turning off interruptible bits.
164 ex_icmd(sp, ep, cmd, len)
165 SCR *sp;
166 EXF *ep;
167 char *cmd;
168 size_t len;
171 * Ex goes through here for each vi :colon command and for each ex
172 * command, however, globally executed commands don't go through
173 * here, instead, they call ex_cmd directly. So, reset all of the
174 * interruptible flags now.
176 F_CLR(sp, S_INTERRUPTED | S_INTERRUPTIBLE);
178 return (ex_cmd(sp, ep, cmd, len));
181 /* Special command structure for :s as a repeat substitution command. */
182 static EXCMDLIST const cmd_subagain =
183 {"s", ex_subagain, E_ADDR2|E_NORC,
184 "s",
185 "[line [,line]] s [cgr] [count] [#lp]",
186 "repeat the last subsitution"};
189 * ex_cmd --
190 * Parse and execute a string containing ex commands.
193 ex_cmd(sp, ep, cmd, cmdlen)
194 SCR *sp;
195 EXF *ep;
196 char *cmd;
197 size_t cmdlen;
199 CHAR_T vlit;
200 EX_PRIVATE *exp;
201 EXCMDARG exc;
202 EXCMDLIST const *cp;
203 MARK cur;
204 recno_t lno, num;
205 size_t arg1_len, len, save_cmdlen;
206 long flagoff;
207 u_int saved_mode;
208 int ch, cnt, delim, flags, namelen, nl, uselastcmd, tmp;
209 char *arg1, *save_cmd, *p, *t;
211 /* Init. */
212 nl = 0;
213 loop: if (nl) {
214 nl = 0;
215 ++sp->if_lno;
217 arg1 = NULL;
218 save_cmdlen = 0;
220 /* Skip whitespace, separators, newlines. */
221 for (; cmdlen > 0; ++cmd, --cmdlen)
222 if ((ch = *cmd) == '\n')
223 ++sp->if_lno;
224 else if (!isblank(ch))
225 break;
226 if (cmdlen == 0)
227 return (0);
229 /* Command lines that start with a double-quote are comments. */
230 if (ch == '"') {
231 while (--cmdlen > 0 && *++cmd != '\n');
232 if (*cmd == '\n') {
233 ++cmd;
234 --cmdlen;
235 ++sp->if_lno;
237 goto loop;
241 * !!!
242 * Permit extra colons at the start of the line. Historically,
243 * ex/vi allowed a single extra one. It's simpler not to count.
244 * The stripping is done here because, historically, any command
245 * could have preceding colons, e.g. ":g/pattern/:p" worked.
247 if (ch == ':')
248 while (--cmdlen > 0 && *++cmd == ':');
250 /* Skip whitespace. */
251 for (; cmdlen > 0; ++cmd, --cmdlen) {
252 ch = *cmd;
253 if (!isblank(ch))
254 break;
257 /* The last point at which an empty line means do nothing. */
258 if (cmdlen == 0)
259 return (0);
261 /* Initialize the structure passed to underlying functions. */
262 memset(&exc, 0, sizeof(EXCMDARG));
263 exp = EXP(sp);
264 if (argv_init(sp, ep, &exc))
265 goto err;
267 /* Parse command addresses. */
268 if (ep_range(sp, ep, &exc, &cmd, &cmdlen))
269 goto err;
271 /* Skip whitespace. */
272 for (; cmdlen > 0; ++cmd, --cmdlen) {
273 ch = *cmd;
274 if (!isblank(ch))
275 break;
279 * If no command, ex does the last specified of p, l, or #, and vi
280 * moves to the line. Otherwise, determine the length of the command
281 * name by looking for the first non-alphabetic character. (There
282 * are a few non-alphabetic characters in command names, but they're
283 * all single character commands.) This isn't a great test, because
284 * it means that, for the command ":e +cut.c file", we'll report that
285 * the command "cut" wasn't known. However, it makes ":e+35 file" work
286 * correctly.
288 #define SINGLE_CHAR_COMMANDS "!#&<=>@~"
289 if (cmdlen != 0 && cmd[0] != '|' && cmd[0] != '\n') {
290 if (strchr(SINGLE_CHAR_COMMANDS, *cmd)) {
291 p = cmd;
292 ++cmd;
293 --cmdlen;
294 namelen = 1;
295 } else {
296 for (p = cmd; cmdlen > 0; --cmdlen, ++cmd)
297 if (!isalpha(*cmd))
298 break;
299 if ((namelen = cmd - p) == 0) {
300 msgq(sp, M_ERR, "Unknown command name.");
301 goto err;
306 * Search the table for the command.
308 * !!!
309 * Historic vi permitted the mark to immediately follow the
310 * 'k' in the 'k' command. Make it work.
312 * !!!
313 * Historic vi permitted pretty much anything to follow the
314 * substitute command, e.g. "s/e/E/|s|sgc3p" was fine. Make
315 * it work.
317 * Use of msgq below is safe, command names are all alphabetics.
319 if ((cp = ex_comm_search(p, namelen)) == NULL)
320 if (p[0] == 'k' && p[1] && !p[2]) {
321 cmd -= namelen - 1;
322 cmdlen += namelen - 1;
323 cp = &cmds[C_K];
324 } else if (p[0] == 's') {
325 cmd -= namelen - 1;
326 cmdlen += namelen - 1;
327 cp = &cmd_subagain;
328 } else {
329 msgq(sp, M_ERR,
330 "The %.*s command is unknown.", namelen, p);
331 goto err;
334 /* Some commands are either not implemented or turned off. */
335 if (F_ISSET(cp, E_NOPERM)) {
336 msgq(sp, M_ERR,
337 "The %s command is not currently supported.",
338 cp->name);
339 goto err;
342 /* Some commands aren't okay in globals. */
343 if (F_ISSET(sp, S_GLOBAL) && F_ISSET(cp, E_NOGLOBAL)) {
344 msgq(sp, M_ERR,
345 "The %s command can't be used as part of a global command.",
346 cp->name);
347 goto err;
351 * Multiple < and > characters; another "feature". Note,
352 * The string passed to the underlying function may not be
353 * nul terminated in this case.
355 if ((cp == &cmds[C_SHIFTL] && *p == '<') ||
356 (cp == &cmds[C_SHIFTR] && *p == '>')) {
357 for (ch = *p; cmdlen > 0; --cmdlen, ++cmd)
358 if (*cmd != ch)
359 break;
360 if (argv_exp0(sp, ep, &exc, p, cmd - p))
361 goto err;
365 * The visual command has a different syntax when called
366 * from ex than when called from a vi colon command. FMH.
368 if (cp == &cmds[C_VISUAL_EX] && IN_VI_MODE(sp))
369 cp = &cmds[C_VISUAL_VI];
371 uselastcmd = 0;
372 } else {
373 cp = exp->lastcmd;
374 uselastcmd = 1;
377 /* Initialize local flags to the command flags. */
378 LF_INIT(cp->flags);
381 * File state must be checked throughout this code, because it is
382 * called when reading the .exrc file and similar things. There's
383 * this little chicken and egg problem -- if we read the file first,
384 * we won't know how to display it. If we read/set the exrc stuff
385 * first, we can't allow any command that requires file state.
386 * Historic vi generally took the easy way out and dropped core.
388 if (LF_ISSET(E_NORC) && ep == NULL) {
389 msgq(sp, M_ERR,
390 "The %s command requires that a file already have been read in.",
391 cp->name);
392 goto err;
396 * There are three normal termination cases for an ex command. They
397 * are the end of the string (cmdlen), or unescaped (by literal next
398 * characters) newline or '|' characters. As we're past any addresses,
399 * we can now determine how long the command is, so we don't have to
400 * look for all the possible terminations. There are three exciting
401 * special cases:
403 * 1: The bang, global, vglobal and the filter versions of the read and
404 * write commands are delimited by newlines (they can contain shell
405 * pipes).
406 * 2: The ex, edit and visual in vi mode commands take ex commands as
407 * their first arguments.
408 * 3: The substitute command takes an RE as its first argument, and
409 * wants it to be specially delimited.
411 * Historically, '|' characters in the first argument of the ex, edit,
412 * and substitute commands did not delimit the command. And, in the
413 * filter cases for read and write, and the bang, global and vglobal
414 * commands, they did not delimit the command at all.
416 * For example, the following commands were legal:
418 * :edit +25|s/abc/ABC/ file.c
419 * :substitute s/|/PIPE/
420 * :read !spell % | columnate
421 * :global/pattern/p|l
423 * It's not quite as simple as it sounds, however. The command:
425 * :substitute s/a/b/|s/c/d|set
427 * was also legal, i.e. the historic ex parser (using the word loosely,
428 * since "parser" implies some regularity) delimited the RE's based on
429 * its delimiter and not anything so irretrievably vulgar as a command
430 * syntax.
432 * One thing that makes this easier is that we can ignore most of the
433 * command termination conditions for the commands that want to take
434 * the command up to the next newline. None of them are legal in .exrc
435 * files, so if we're here, we only dealing with a single line, and we
436 * can just eat it.
438 * Anyhow, the following code makes this all work. First, for the
439 * special cases we move past their special argument. Then, we do
440 * normal command processing on whatever is left. Barf-O-Rama.
442 save_cmd = cmd;
443 (void)term_key_ch(sp, K_VLNEXT, &vlit);
444 if (cp == &cmds[C_EDIT] ||
445 cp == &cmds[C_EX] || cp == &cmds[C_VISUAL_VI]) {
447 * Move to the next non-whitespace character. As '+' must
448 * be the character after the command name, if there isn't
449 * one, we're done.
451 for (; cmdlen > 0; --cmdlen, ++cmd) {
452 ch = *cmd;
453 if (!isblank(ch))
454 break;
457 * QUOTING NOTE:
459 * The historic implementation ignored all escape characters
460 * so there was no way to put a space or newline into the +cmd
461 * field. We do a simplistic job of fixing it by moving to the
462 * first whitespace character that isn't escaped by a literal
463 * next character. The literal next characters are stripped
464 * as they're no longer useful.
466 if (cmdlen > 0 && ch == '+') {
467 ++cmd;
468 --cmdlen;
469 for (arg1 = p = cmd; cmdlen > 0; --cmdlen, ++cmd) {
470 if ((ch = *cmd) == vlit && cmdlen > 1) {
471 --cmdlen;
472 ch = *++cmd;
473 } else if (isblank(ch))
474 break;
475 *p++ = ch;
477 arg1_len = cmd - arg1;
479 /* Reset, so the first argument isn't reparsed. */
480 save_cmd = cmd;
482 } else if (cp == &cmds[C_BANG] ||
483 cp == &cmds[C_GLOBAL] || cp == &cmds[C_VGLOBAL]) {
484 cmd += cmdlen;
485 cmdlen = 0;
486 } else if (cp == &cmds[C_READ] || cp == &cmds[C_WRITE]) {
488 * Move to the next character. If it's a '!', it's a filter
489 * command and we want to eat it all, otherwise, we're done.
491 for (; cmdlen > 0; --cmdlen, ++cmd) {
492 ch = *cmd;
493 if (!isblank(ch))
494 break;
496 if (cmdlen > 0 && ch == '!') {
497 cmd += cmdlen;
498 cmdlen = 0;
500 } else if (cp == &cmds[C_SUBSTITUTE]) {
502 * Move to the next non-whitespace character, we'll use it as
503 * the delimiter. If the character isn't an alphanumeric or
504 * a '|', it's the delimiter, so parse it. Otherwise, we're
505 * into something like ":s g", so use the special substitute
506 * command.
508 for (; cmdlen > 0; --cmdlen, ++cmd)
509 if (!isblank(cmd[0]))
510 break;
512 if (isalnum(cmd[0]) || cmd[0] == '|')
513 cp = &cmd_subagain;
514 else if (cmdlen > 0) {
516 * QUOTING NOTE:
518 * Backslashes quote delimiter characters for RE's.
519 * The backslashes are NOT removed since they'll be
520 * used by the RE code. Move to the third delimiter
521 * that's not escaped (or the end of the command).
523 delim = *cmd;
524 ++cmd;
525 --cmdlen;
526 for (cnt = 2; cmdlen > 0 && cnt; --cmdlen, ++cmd)
527 if (cmd[0] == '\\' && cmdlen > 1) {
528 ++cmd;
529 --cmdlen;
530 } else if (cmd[0] == delim)
531 --cnt;
535 * Use normal quoting and termination rules to find the end
536 * of this command.
538 * QUOTING NOTE:
540 * Historically, vi permitted ^V's to escape <newline>'s in the .exrc
541 * file. It was almost certainly a bug, but that's what bug-for-bug
542 * compatibility means, Grasshopper. Also, ^V's escape the command
543 * delimiters. Literal next quote characters in front of the newlines,
544 * '|' characters or literal next characters are stripped as as they're
545 * no longer useful.
547 for (p = cmd, cnt = 0; cmdlen > 0; --cmdlen, ++cmd) {
548 if ((ch = cmd[0]) == vlit && cmdlen > 1) {
549 ch = cmd[1];
550 if (ch == '\n' || ch == '|') {
551 if (ch == '\n')
552 ++sp->if_lno;
553 --cmdlen;
554 ++cmd;
555 ++cnt;
556 } else
557 ch = vlit;
558 } else if (ch == '\n' || ch == '|') {
559 if (ch == '\n')
560 nl = 1;
561 --cmdlen;
562 break;
564 *p++ = ch;
568 * Save off the next command information, go back to the
569 * original start of the command.
571 p = cmd + 1;
572 cmd = save_cmd;
573 save_cmd = p;
574 save_cmdlen = cmdlen;
575 cmdlen = ((save_cmd - cmd) - 1) - cnt;
578 * !!!
579 * The "set tags" command historically used a backslash, not the
580 * user's literal next character, to escape whitespace. Handle
581 * it here instead of complicating the argv_exp3() code. Note,
582 * this isn't a particularly complex trap, and if backslashes were
583 * legal in set commands, this would have to be much more complicated.
585 if (cp == &cmds[C_SET])
586 for (p = cmd, len = cmdlen; len > 0; --len, ++p)
587 if (*p == '\\')
588 *p = vlit;
591 * Set the default addresses. It's an error to specify an address for
592 * a command that doesn't take them. If two addresses are specified
593 * for a command that only takes one, lose the first one. Two special
594 * cases here, some commands take 0 or 2 addresses. For most of them
595 * (the E_ADDR2_ALL flag), 0 defaults to the entire file. For one
596 * (the `!' command, the E_ADDR2_NONE flag), 0 defaults to no lines.
598 * Also, if the file is empty, some commands want to use an address of
599 * 0, i.e. the entire file is 0 to 0, and the default first address is
600 * 0. Otherwise, an entire file is 1 to N and the default line is 1.
601 * Note, we also add the E_ZERO flag to the command flags, for the case
602 * where the 0 address is only valid if it's a default address.
604 * Also, set a flag if we set the default addresses. Some commands
605 * (ex: z) care if the user specified an address of if we just used
606 * the current cursor.
608 switch (LF_ISSET(E_ADDR1|E_ADDR2|E_ADDR2_ALL|E_ADDR2_NONE)) {
609 case E_ADDR1: /* One address: */
610 switch (exc.addrcnt) {
611 case 0: /* Default cursor/empty file. */
612 exc.addrcnt = 1;
613 F_SET(&exc, E_ADDRDEF);
614 if (LF_ISSET(E_ZERODEF)) {
615 if (file_lline(sp, ep, &lno))
616 goto err;
617 if (lno == 0) {
618 exc.addr1.lno = 0;
619 LF_SET(E_ZERO);
620 } else
621 exc.addr1.lno = sp->lno;
622 } else
623 exc.addr1.lno = sp->lno;
624 exc.addr1.cno = sp->cno;
625 break;
626 case 1:
627 break;
628 case 2: /* Lose the first address. */
629 exc.addrcnt = 1;
630 exc.addr1 = exc.addr2;
632 break;
633 case E_ADDR2_NONE: /* Zero/two addresses: */
634 if (exc.addrcnt == 0) /* Default to nothing. */
635 break;
636 goto two;
637 case E_ADDR2_ALL: /* Zero/two addresses: */
638 if (exc.addrcnt == 0) { /* Default entire/empty file. */
639 exc.addrcnt = 2;
640 F_SET(&exc, E_ADDRDEF);
641 if (file_lline(sp, ep, &exc.addr2.lno))
642 goto err;
643 if (LF_ISSET(E_ZERODEF) && exc.addr2.lno == 0) {
644 exc.addr1.lno = 0;
645 LF_SET(E_ZERO);
646 } else
647 exc.addr1.lno = 1;
648 exc.addr1.cno = exc.addr2.cno = 0;
649 F_SET(&exc, E_ADDR2_ALL);
650 break;
652 /* FALLTHROUGH */
653 case E_ADDR2: /* Two addresses: */
654 two: switch (exc.addrcnt) {
655 case 0: /* Default cursor/empty file. */
656 exc.addrcnt = 2;
657 F_SET(&exc, E_ADDRDEF);
658 if (LF_ISSET(E_ZERODEF) && sp->lno == 1) {
659 if (file_lline(sp, ep, &lno))
660 goto err;
661 if (lno == 0) {
662 exc.addr1.lno = exc.addr2.lno = 0;
663 LF_SET(E_ZERO);
664 } else
665 exc.addr1.lno = exc.addr2.lno = sp->lno;
666 } else
667 exc.addr1.lno = exc.addr2.lno = sp->lno;
668 exc.addr1.cno = exc.addr2.cno = sp->cno;
669 break;
670 case 1: /* Default to first address. */
671 exc.addrcnt = 2;
672 exc.addr2 = exc.addr1;
673 break;
674 case 2:
675 break;
677 break;
678 default:
679 if (exc.addrcnt) /* Error. */
680 goto usage;
683 flagoff = 0;
684 for (p = cp->syntax; *p != '\0'; ++p) {
686 * The write command is sensitive to leading whitespace, e.g.
687 * "write !" is different from "write!". If not the write
688 * command, skip leading whitespace.
690 if (cp != &cmds[C_WRITE])
691 for (; cmdlen > 0; --cmdlen, ++cmd) {
692 ch = *cmd;
693 if (!isblank(ch))
694 break;
698 * Quit when reach the end of the command, unless it's a
699 * command that does its own parsing, in which case we want
700 * to build a reasonable argv for it. This code guarantees
701 * that there will be an argv when the function gets called,
702 * so the correct test is for a length of 0, not for the
703 * argc > 0.
705 if (cmdlen == 0 && *p != '!' && *p != 'S' && *p != 's')
706 break;
708 switch (*p) {
709 case '!': /* ! */
710 if (*cmd == '!') {
711 ++cmd;
712 --cmdlen;
713 F_SET(&exc, E_FORCE);
715 break;
716 case '1': /* +, -, #, l, p */
718 * !!!
719 * Historically, some flags were ignored depending
720 * on where they occurred in the command line. For
721 * example, in the command, ":3+++p--#", historic vi
722 * acted on the '#' flag, but ignored the '-' flags.
723 * It's unambiguous what the flags mean, so we just
724 * handle them regardless of the stupidity of their
725 * location.
727 for (; cmdlen; --cmdlen, ++cmd)
728 switch (*cmd) {
729 case '+':
730 ++flagoff;
731 break;
732 case '-':
733 --flagoff;
734 break;
735 case '#':
736 F_SET(&exc, E_F_HASH);
737 break;
738 case 'l':
739 F_SET(&exc, E_F_LIST);
740 break;
741 case 'p':
742 F_SET(&exc, E_F_PRINT);
743 break;
744 default:
745 goto end1;
747 end1: break;
748 case '2': /* -, ., +, ^ */
749 case '3': /* -, ., +, ^, = */
750 for (; cmdlen; --cmdlen, ++cmd)
751 switch (*cmd) {
752 case '-':
753 F_SET(&exc, E_F_DASH);
754 break;
755 case '.':
756 F_SET(&exc, E_F_DOT);
757 break;
758 case '+':
759 F_SET(&exc, E_F_PLUS);
760 break;
761 case '^':
762 F_SET(&exc, E_F_CARAT);
763 break;
764 case '=':
765 if (*p == '3') {
766 F_SET(&exc, E_F_EQUAL);
767 break;
769 /* FALLTHROUGH */
770 default:
771 goto end2;
773 end2: break;
774 case 'b': /* buffer */
775 exc.buffer = *cmd;
776 ++cmd;
777 --cmdlen;
778 F_SET(&exc, E_BUFFER);
779 break;
780 case 'c': /* count [01+a] */
781 ++p;
782 if (!isdigit(*cmd) &&
783 (*p != '+' || (*cmd != '+' && *cmd != '-')))
784 break;
785 /* 8-bit XXX */ if ((lno = strtol(cmd, &t, 10)) == 0 && *p != '0') {
786 msgq(sp, M_ERR, "Count may not be zero.");
787 goto err;
789 cmdlen -= (t - cmd);
790 cmd = t;
792 * Count as address offsets occur in commands taking
793 * two addresses. Historic vi practice was to use
794 * the count as an offset from the *second* address.
796 * Set a count flag; some underlying commands (see
797 * join) do different things with counts than with
798 * line addresses.
800 if (*p == 'a') {
801 exc.addr1 = exc.addr2;
802 exc.addr2.lno = exc.addr1.lno + lno - 1;
803 } else
804 exc.count = lno;
805 F_SET(&exc, E_COUNT);
806 break;
807 case 'f': /* file */
808 if (argv_exp2(sp, ep,
809 &exc, cmd, cmdlen, cp == &cmds[C_BANG]))
810 goto err;
811 goto countchk;
812 case 'l': /* line */
813 if (ep_line(sp, ep, &cur, &cmd, &cmdlen, &tmp))
814 goto err;
815 /* Line specifications are always required. */
816 if (!tmp) {
817 msgq(sp, M_ERR,
818 "%s: bad line specification", cmd);
819 goto err;
821 exc.lineno = cur.lno;
822 break;
823 case 'S': /* string, file exp. */
824 if (argv_exp1(sp, ep,
825 &exc, cmd, cmdlen, cp == &cmds[C_BANG]))
826 goto err;
827 goto addr2;
828 case 's': /* string */
829 if (argv_exp0(sp, ep, &exc, cmd, cmdlen))
830 goto err;
831 goto addr2;
832 case 'W': /* word string */
834 * QUOTING NOTE:
836 * Literal next characters escape the following
837 * character. Quoting characters are stripped
838 * here since they are no longer useful.
840 * First there was the word.
842 for (p = t = cmd; cmdlen > 0; --cmdlen, ++cmd) {
843 if ((ch = *cmd) == vlit && cmdlen > 1) {
844 --cmdlen;
845 *p++ = *++cmd;
846 } else if (isblank(ch)) {
847 ++cmd;
848 --cmdlen;
849 break;
850 } else
851 *p++ = ch;
853 if (argv_exp0(sp, ep, &exc, t, p - t))
854 goto err;
856 /* Delete intervening whitespace. */
857 for (; cmdlen > 0; --cmdlen, ++cmd) {
858 ch = *cmd;
859 if (!isblank(ch))
860 break;
862 if (cmdlen == 0)
863 goto usage;
865 /* Followed by the string. */
866 for (p = t = cmd; cmdlen > 0; --cmdlen, ++cmd, ++p)
867 if ((ch = *cmd) == vlit && cmdlen > 1) {
868 --cmdlen;
869 *p = *++cmd;
870 } else
871 *p = ch;
872 if (argv_exp0(sp, ep, &exc, t, p - t))
873 goto err;
874 goto addr2;
875 case 'w': /* word */
876 if (argv_exp3(sp, ep, &exc, cmd, cmdlen))
877 goto err;
878 countchk: if (*++p != 'N') { /* N */
880 * If a number is specified, must either be
881 * 0 or that number, if optional, and that
882 * number, if required.
884 num = *p - '0';
885 if ((*++p != 'o' || exp->argsoff != 0) &&
886 exp->argsoff != num)
887 goto usage;
889 goto addr2;
890 default:
891 msgq(sp, M_ERR,
892 "Internal syntax table error (%s: %c).",
893 cp->name, *p);
897 /* Skip trailing whitespace. */
898 for (; cmdlen; --cmdlen) {
899 ch = *cmd++;
900 if (!isblank(ch))
901 break;
905 * There shouldn't be anything left, and no more required
906 * fields, i.e neither 'l' or 'r' in the syntax string.
908 if (cmdlen || strpbrk(p, "lr")) {
909 usage: msgq(sp, M_ERR, "Usage: %s.", cp->usage);
910 goto err;
913 /* Verify that the addresses are legal. */
914 addr2: switch (exc.addrcnt) {
915 case 2:
916 if (file_lline(sp, ep, &lno))
917 goto err;
919 * Historic ex/vi permitted commands with counts to go past
920 * EOF. So, for example, if the file only had 5 lines, the
921 * ex command "1,6>" would fail, but the command ">300"
922 * would succeed. Since we don't want to have to make all
923 * of the underlying commands handle random line numbers,
924 * fix it here.
926 if (exc.addr2.lno > lno)
927 if (F_ISSET(&exc, E_COUNT))
928 exc.addr2.lno = lno;
929 else {
930 if (lno == 0)
931 msgq(sp, M_ERR, "The file is empty.");
932 else
933 msgq(sp, M_ERR,
934 "Only %lu line%s in the file",
935 lno, lno > 1 ? "s" : "");
936 goto err;
938 /* FALLTHROUGH */
939 case 1:
940 num = exc.addr1.lno;
942 * If it's a "default vi command", zero is okay. Historic
943 * vi allowed this, note, it's also the hack that allows
944 * "vi + nonexistent_file" to work.
946 if (num == 0 && (!IN_VI_MODE(sp) || uselastcmd != 1) &&
947 !LF_ISSET(E_ZERO)) {
948 msgq(sp, M_ERR,
949 "The %s command doesn't permit an address of 0.",
950 cp->name);
951 goto err;
953 if (file_lline(sp, ep, &lno))
954 goto err;
955 if (num > lno) {
956 if (lno == 0)
957 msgq(sp, M_ERR, "The file is empty.");
958 else
959 msgq(sp, M_ERR, "Only %lu line%s in the file",
960 lno, lno > 1 ? "s" : "");
961 goto err;
963 break;
966 /* If doing a default command, vi just moves to the line. */
967 if (IN_VI_MODE(sp) && uselastcmd) {
968 switch (exc.addrcnt) {
969 case 2:
970 sp->lno = exc.addr2.lno ? exc.addr2.lno : 1;
971 sp->cno = exc.addr2.cno;
972 break;
973 case 1:
974 sp->lno = exc.addr1.lno ? exc.addr1.lno : 1;
975 sp->cno = exc.addr1.cno;
976 break;
978 cmd = save_cmd;
979 cmdlen = save_cmdlen;
980 goto loop;
983 /* Reset "last" command. */
984 if (LF_ISSET(E_SETLAST))
985 exp->lastcmd = cp;
987 /* Final setup for the command. */
988 exc.cmd = cp;
990 #if defined(DEBUG) && 0
991 TRACE(sp, "ex_cmd: %s", exc.cmd->name);
992 if (exc.addrcnt > 0) {
993 TRACE(sp, "\taddr1 %d", exc.addr1.lno);
994 if (exc.addrcnt > 1)
995 TRACE(sp, " addr2: %d", exc.addr2.lno);
996 TRACE(sp, "\n");
998 if (exc.lineno)
999 TRACE(sp, "\tlineno %d", exc.lineno);
1000 if (exc.flags)
1001 TRACE(sp, "\tflags %0x", exc.flags);
1002 if (F_ISSET(&exc, E_BUFFER))
1003 TRACE(sp, "\tbuffer %c", exc.buffer);
1004 TRACE(sp, "\n");
1005 if (exc.argc) {
1006 for (cnt = 0; cnt < exc.argc; ++cnt)
1007 TRACE(sp, "\targ %d: {%s}", cnt, exc.argv[cnt]);
1008 TRACE(sp, "\n");
1010 #endif
1011 /* Clear autoprint. */
1012 F_CLR(sp, S_AUTOPRINT);
1014 /* Increment the command count if not called from vi. */
1015 if (!IN_VI_MODE(sp))
1016 ++sp->ccnt;
1019 * If file state and not doing a global command, log the start of
1020 * an action.
1022 if (ep != NULL && !F_ISSET(sp, S_GLOBAL))
1023 (void)log_cursor(sp, ep);
1025 /* Save the current mode. */
1026 saved_mode = F_ISSET(sp, S_SCREENS | S_MAJOR_CHANGE);
1028 /* Do the command. */
1029 if ((cp->fn)(sp, ep, &exc))
1030 goto err;
1032 #ifdef DEBUG
1033 /* Make sure no function left the temporary space locked. */
1034 if (F_ISSET(sp->gp, G_TMP_INUSE)) {
1035 F_CLR(sp->gp, G_TMP_INUSE);
1036 msgq(sp, M_ERR, "Error: ex: temporary buffer not released.");
1037 goto err;
1039 #endif
1040 if (saved_mode != F_ISSET(sp, S_SCREENS | S_MAJOR_CHANGE)) {
1042 * Only here if the mode of the underlying file changed, e.g.
1043 * the user switched files or is exiting. There are two things
1044 * that we might have to save. First, any "+cmd" field set up
1045 * for an ex/edit command will have to be saved for later, also,
1046 * any not yet executed part of the current ex command.
1048 * :edit +25 file.c|s/abc/ABC/|1
1050 * for example.
1052 * The historic vi just hung, of course; we handle by
1053 * pushing the keys onto the tty queue. If we're
1054 * switching modes to vi, since the commands are intended
1055 * as ex commands, add the extra characters to make it
1056 * work.
1058 * For the fun of it, if you want to see if a vi clone got
1059 * the ex argument parsing right, try:
1061 * echo 'foo|bar' > file1; echo 'foo/bar' > file2;
1062 * vi
1063 * :edit +1|s/|/PIPE/|w file1| e file2|1 | s/\//SLASH/|wq
1065 if (arg1_len == NULL && save_cmdlen == 0)
1066 return (0);
1067 if (IN_VI_MODE(sp) && term_push(sp, "\n", 1, 0, 0))
1068 goto err;
1069 if (save_cmdlen != 0)
1070 if (term_push(sp, save_cmd, save_cmdlen, 0, 0))
1071 goto err;
1072 if (arg1 != NULL) {
1073 if (IN_VI_MODE(sp) && save_cmdlen != 0 &&
1074 term_push(sp, "|", 1, 0, 0))
1075 goto err;
1076 if (term_push(sp, arg1, arg1_len, 0, 0))
1077 goto err;
1079 if (IN_VI_MODE(sp) && term_push(sp, ":", 1, 0, 0))
1080 goto err;
1081 return (0);
1084 if (IN_EX_MODE(sp) && ep != NULL) {
1086 * The print commands have already handled the `print' flags.
1087 * If so, clear them. Don't return, autoprint may still have
1088 * stuff to print out.
1090 if (LF_ISSET(E_F_PRCLEAR))
1091 F_CLR(&exc, E_F_HASH | E_F_LIST | E_F_PRINT);
1094 * If the command was successful, and there was an explicit
1095 * flag to display the new cursor line, or we're in ex mode,
1096 * autoprint is set, and a change was made, display the line.
1098 if (flagoff) {
1099 if (flagoff < 0) {
1100 if (sp->lno < -flagoff) {
1101 msgq(sp, M_ERR,
1102 "Flag offset before line 1.");
1103 goto err;
1105 } else {
1106 if (file_lline(sp, ep, &lno))
1107 goto err;
1108 if (sp->lno + flagoff > lno) {
1109 msgq(sp, M_ERR,
1110 "Flag offset past end-of-file.");
1111 goto err;
1114 sp->lno += flagoff;
1117 if (F_ISSET(sp, S_AUTOPRINT) && O_ISSET(sp, O_AUTOPRINT))
1118 LF_INIT(E_F_PRINT);
1119 else
1120 LF_INIT(F_ISSET(&exc, E_F_HASH | E_F_LIST | E_F_PRINT));
1122 memset(&exc, 0, sizeof(EXCMDARG));
1123 exc.addrcnt = 2;
1124 exc.addr1.lno = exc.addr2.lno = sp->lno;
1125 exc.addr1.cno = exc.addr2.cno = sp->cno;
1126 switch (LF_ISSET(E_F_HASH | E_F_LIST | E_F_PRINT)) {
1127 case E_F_HASH:
1128 exc.cmd = &cmds[C_HASH];
1129 ex_number(sp, ep, &exc);
1130 break;
1131 case E_F_LIST:
1132 exc.cmd = &cmds[C_LIST];
1133 ex_list(sp, ep, &exc);
1134 break;
1135 case E_F_PRINT:
1136 exc.cmd = &cmds[C_PRINT];
1137 ex_pr(sp, ep, &exc);
1138 break;
1142 cmd = save_cmd;
1143 cmdlen = save_cmdlen;
1144 goto loop;
1145 /* NOTREACHED */
1148 * On error, we discard any keys we have left, as well as any keys
1149 * that were mapped. The test of save_cmdlen isn't necessarily
1150 * correct. If we fail early enough we don't know if the entire
1151 * string was a single command or not. Try and guess, it's useful
1152 * to know if part of the command was discarded.
1154 if (save_cmdlen == 0)
1155 for (; cmdlen; --cmdlen)
1156 if ((ch = *cmd++) == vlit && cmdlen > 1) {
1157 --cmdlen;
1158 ++cmd;
1159 } else if (ch == '\n' || ch == '|') {
1160 if (cmdlen > 1)
1161 save_cmdlen = 1;
1162 break;
1164 if (save_cmdlen != 0)
1165 msgq(sp, M_ERR,
1166 "Ex command failed: remaining command input discarded.");
1167 err: term_map_flush(sp, "Ex command failed");
1168 return (1);
1172 * ep_range --
1173 * Get a line range for ex commands.
1175 static int
1176 ep_range(sp, ep, excp, cmdp, cmdlenp)
1177 SCR *sp;
1178 EXF *ep;
1179 EXCMDARG *excp;
1180 char **cmdp;
1181 size_t *cmdlenp;
1183 MARK cur, savecursor;
1184 size_t cmdlen;
1185 int savecursor_set, tmp;
1186 char *cmd;
1188 /* Percent character is all lines in the file. */
1189 cmd = *cmdp;
1190 cmdlen = *cmdlenp;
1191 if (*cmd == '%') {
1192 excp->addr1.lno = 1;
1193 if (file_lline(sp, ep, &excp->addr2.lno))
1194 return (1);
1196 /* If an empty file, then the first line is 0, not 1. */
1197 if (excp->addr2.lno == 0)
1198 excp->addr1.lno = 0;
1199 excp->addr1.cno = excp->addr2.cno = 0;
1200 excp->addrcnt = 2;
1202 ++*cmdp;
1203 --*cmdlenp;
1204 return (0);
1207 /* Parse comma or semi-colon delimited line specs. */
1208 for (savecursor_set = 0, excp->addrcnt = 0; cmdlen > 0;)
1209 switch (*cmd) {
1210 case ';': /* Semi-colon delimiter. */
1212 * Comma delimiters delimit; semi-colon delimiters
1213 * change the current address for the 2nd address
1214 * to be the first address. Trailing or multiple
1215 * delimiters are discarded.
1217 if (excp->addrcnt == 0)
1218 goto done;
1219 if (!savecursor_set) {
1220 savecursor.lno = sp->lno;
1221 savecursor.cno = sp->cno;
1222 sp->lno = excp->addr1.lno;
1223 sp->cno = excp->addr1.cno;
1224 savecursor_set = 1;
1226 ++cmd;
1227 --cmdlen;
1228 break;
1229 case ',': /* Comma delimiter. */
1230 /* If no addresses yet, defaults to ".". */
1231 if (excp->addrcnt == 0) {
1232 excp->addr1.lno = sp->lno;
1233 excp->addr1.cno = sp->cno;
1234 excp->addrcnt = 1;
1236 /* FALLTHROUGH */
1237 case ' ': /* Whitespace. */
1238 case '\t': /* Whitespace. */
1239 ++cmd;
1240 --cmdlen;
1241 break;
1242 default:
1243 if (ep_line(sp, ep, &cur, &cmd, &cmdlen, &tmp))
1244 return (1);
1245 if (!tmp)
1246 goto done;
1249 * Extra addresses are discarded, starting with
1250 * the first.
1252 switch (excp->addrcnt) {
1253 case 0:
1254 excp->addr1 = cur;
1255 excp->addrcnt = 1;
1256 break;
1257 case 1:
1258 excp->addr2 = cur;
1259 excp->addrcnt = 2;
1260 break;
1261 case 2:
1262 excp->addr1 = excp->addr2;
1263 excp->addr2 = cur;
1264 break;
1266 break;
1270 * XXX
1271 * This is probably not right behavior for savecursor -- need
1272 * to figure out what the historical ex did for ";,;,;5p" or
1273 * similar stupidity.
1275 done: if (savecursor_set) {
1276 sp->lno = savecursor.lno;
1277 sp->cno = savecursor.cno;
1279 if (excp->addrcnt == 2 &&
1280 (excp->addr2.lno < excp->addr1.lno ||
1281 excp->addr2.lno == excp->addr1.lno &&
1282 excp->addr2.cno < excp->addr1.cno)) {
1283 msgq(sp, M_ERR,
1284 "The second address is smaller than the first.");
1285 return (1);
1287 *cmdp = cmd;
1288 *cmdlenp = cmdlen;
1289 return (0);
1293 * Get a single line address specifier.
1295 static int
1296 ep_line(sp, ep, cur, cmdp, cmdlenp, addr_found)
1297 SCR *sp;
1298 EXF *ep;
1299 MARK *cur;
1300 char **cmdp;
1301 size_t *cmdlenp;
1302 int *addr_found;
1304 MARK m, *mp;
1305 long total;
1306 u_int flags;
1307 size_t cmdlen;
1308 char *cmd, *endp;
1310 *addr_found = 0;
1312 cmd = *cmdp;
1313 cmdlen = *cmdlenp;
1314 switch (*cmd) {
1315 case '$': /* Last line in the file. */
1316 *addr_found = 1;
1317 cur->cno = 0;
1318 if (file_lline(sp, ep, &cur->lno))
1319 return (1);
1320 ++cmd;
1321 --cmdlen;
1322 break; /* Absolute line number. */
1323 case '0': case '1': case '2': case '3': case '4':
1324 case '5': case '6': case '7': case '8': case '9':
1325 *addr_found = 1;
1327 * The way the vi "previous context" mark worked was that
1328 * "non-relative" motions set it. While vi wasn't totally
1329 * consistent about this, ANY numeric address was considered
1330 * non-relative, and set the value. Which is why we're
1331 * hacking marks down here.
1333 if (IN_VI_MODE(sp)) {
1334 m.lno = sp->lno;
1335 m.cno = sp->cno;
1336 if (mark_set(sp, ep, ABSMARK1, &m, 1))
1337 return (1);
1339 cur->cno = 0;
1340 /* 8-bit XXX */ cur->lno = strtol(cmd, &endp, 10);
1341 cmdlen -= (endp - cmd);
1342 cmd = endp;
1343 break;
1344 case '\'': /* Use a mark. */
1345 *addr_found = 1;
1346 if (cmdlen == 1) {
1347 msgq(sp, M_ERR, "No mark name supplied.");
1348 return (1);
1350 if ((mp = mark_get(sp, ep, cmd[1])) == NULL)
1351 return (1);
1352 *cur = *mp;
1353 cmd += 2;
1354 cmdlen -= 2;
1355 break;
1356 case '\\': /* Search: forward/backward. */
1358 * !!!
1359 * I can't find any difference between // and \/ or
1360 * between ?? and \?. Mark Horton doesn't remember
1361 * there being any difference. C'est la vie.
1363 if (cmdlen < 2 || cmd[1] != '/' && cmd[1] != '?') {
1364 msgq(sp, M_ERR, "\\ not followed by / or ?.");
1365 return (1);
1367 ++cmd;
1368 --cmdlen;
1369 if (cmd[0] == '/')
1370 goto forward;
1371 if (cmd[0] == '?')
1372 goto backward;
1373 /* NOTREACHED */
1374 case '/': /* Search forward. */
1375 forward: *addr_found = 1;
1376 m.lno = sp->lno;
1377 m.cno = sp->cno;
1378 flags = SEARCH_MSG | SEARCH_PARSE | SEARCH_SET;
1379 if (f_search(sp, ep, &m, &m, cmd, &endp, &flags))
1380 return (1);
1381 cur->lno = m.lno;
1382 cur->cno = m.cno;
1383 cmdlen -= (endp - cmd);
1384 cmd = endp;
1385 break;
1386 case '?': /* Search backward. */
1387 backward: *addr_found = 1;
1388 m.lno = sp->lno;
1389 m.cno = sp->cno;
1390 flags = SEARCH_MSG | SEARCH_PARSE | SEARCH_SET;
1391 if (b_search(sp, ep, &m, &m, cmd, &endp, &flags))
1392 return (1);
1393 cur->lno = m.lno;
1394 cur->cno = m.cno;
1395 cmdlen -= (endp - cmd);
1396 cmd = endp;
1397 break;
1398 case '.': /* Current position. */
1399 *addr_found = 1;
1400 cur->cno = sp->cno;
1402 /* If an empty file, then '.' is 0, not 1. */
1403 if (sp->lno == 1) {
1404 if (file_lline(sp, ep, &cur->lno))
1405 return (1);
1406 if (cur->lno != 0)
1407 cur->lno = 1;
1408 } else
1409 cur->lno = sp->lno;
1410 ++cmd;
1411 --cmdlen;
1412 break;
1416 * Evaluate any offset. Offsets are +/- any number, or any number
1417 * of +/- signs, or any combination thereof. If no address found
1418 * yet, offset is relative to ".".
1420 for (total = 0; cmdlen > 0 && (cmd[0] == '-' || cmd[0] == '+');) {
1421 if (!*addr_found) {
1422 cur->lno = sp->lno;
1423 cur->cno = sp->cno;
1424 *addr_found = 1;
1427 if (cmdlen > 1 && isdigit(cmd[1])) {
1428 /* 8-bit XXX */ total += strtol(cmd, &endp, 10);
1429 cmdlen -= (endp - cmd);
1430 cmd = endp;
1431 } else {
1432 total += cmd[0] == '-' ? -1 : 1;
1433 --cmdlen;
1434 ++cmd;
1437 if (total < 0 && -total > cur->lno) {
1438 msgq(sp, M_ERR, "Reference to a line number less than 0.");
1439 return (1);
1441 cur->lno += total;
1443 *cmdp = cmd;
1444 *cmdlenp = cmdlen;
1445 return (0);
1449 * ex_is_abbrev -
1450 * The vi text input routine needs to know if ex thinks this is
1451 * an [un]abbreviate command, so it can turn off abbreviations.
1452 * Usual ranting in the vi/v_ntext:txt_abbrev() routine.
1455 ex_is_abbrev(name, len)
1456 char *name;
1457 size_t len;
1459 EXCMDLIST const *cp;
1461 return ((cp = ex_comm_search(name, len)) != NULL &&
1462 (cp == &cmds[C_ABBR] || cp == &cmds[C_UNABBREVIATE]));
1465 static inline EXCMDLIST const *
1466 ex_comm_search(name, len)
1467 char *name;
1468 size_t len;
1470 EXCMDLIST const *cp;
1472 for (cp = cmds; cp->name != NULL; ++cp) {
1473 if (cp->name[0] > name[0])
1474 return (NULL);
1475 if (cp->name[0] != name[0])
1476 continue;
1477 if (!memcmp(name, cp->name, len))
1478 return (cp);
1480 return (NULL);