xref: /openbsd/usr.bin/vi/ex/ex.c (revision 07ea8d15)
1 /*-
2  * Copyright (c) 1992, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1992, 1993, 1994, 1995, 1996
5  *	Keith Bostic.  All rights reserved.
6  *
7  * See the LICENSE file for redistribution information.
8  */
9 
10 #include "config.h"
11 
12 #ifndef lint
13 static const char sccsid[] = "@(#)ex.c	10.55 (Berkeley) 9/24/96";
14 #endif /* not lint */
15 
16 #include <sys/types.h>
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/time.h>
20 
21 #include <bitstring.h>
22 #include <ctype.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <limits.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30 
31 #include "../common/common.h"
32 #include "../vi/vi.h"
33 
34 #if defined(DEBUG) && defined(COMLOG)
35 static void	ex_comlog __P((SCR *, EXCMD *));
36 #endif
37 static EXCMDLIST const *
38 		ex_comm_search __P((char *, size_t));
39 static int	ex_discard __P((SCR *));
40 static int	ex_line __P((SCR *, EXCMD *, MARK *, int *, int *));
41 static int	ex_load __P((SCR *));
42 static void	ex_unknown __P((SCR *, char *, size_t));
43 
44 /*
45  * ex --
46  *	Main ex loop.
47  *
48  * PUBLIC: int ex __P((SCR **));
49  */
50 int
51 ex(spp)
52 	SCR **spp;
53 {
54 	EX_PRIVATE *exp;
55 	GS *gp;
56 	MSGS *mp;
57 	SCR *sp;
58 	TEXT *tp;
59 	u_int32_t flags;
60 
61 	sp = *spp;
62 	gp = sp->gp;
63 	exp = EXP(sp);
64 
65 	/* Start the ex screen. */
66 	if (ex_init(sp))
67 		return (1);
68 
69 	/* Flush any saved messages. */
70 	while ((mp = gp->msgq.lh_first) != NULL) {
71 		gp->scr_msg(sp, mp->mtype, mp->buf, mp->len);
72 		LIST_REMOVE(mp, q);
73 		free(mp->buf);
74 		free(mp);
75 	}
76 
77 	/* If reading from a file, errors should have name and line info. */
78 	if (F_ISSET(gp, G_SCRIPTED)) {
79 		gp->excmd.if_lno = 1;
80 		gp->excmd.if_name = "script";
81 	}
82 
83 	/*
84 	 * !!!
85 	 * Initialize the text flags.  The beautify edit option historically
86 	 * applied to ex command input read from a file.  In addition, the
87 	 * first time a ^H was discarded from the input, there was a message,
88 	 * "^H discarded", that was displayed.  We don't bother.
89 	 */
90 	LF_INIT(TXT_BACKSLASH | TXT_CNTRLD | TXT_CR);
91 	for (;; ++gp->excmd.if_lno) {
92 		/* Display status line and flush. */
93 		if (F_ISSET(sp, SC_STATUS)) {
94 			if (!F_ISSET(sp, SC_EX_SILENT))
95 				msgq_status(sp, sp->lno, 0);
96 			F_CLR(sp, SC_STATUS);
97 		}
98 		(void)ex_fflush(sp);
99 
100 		/* Set the flags the user can reset. */
101 		if (O_ISSET(sp, O_BEAUTIFY))
102 			LF_SET(TXT_BEAUTIFY);
103 		if (O_ISSET(sp, O_PROMPT))
104 			LF_SET(TXT_PROMPT);
105 
106 		/* Clear any current interrupts, and get a command. */
107 		CLR_INTERRUPT(sp);
108 		if (ex_txt(sp, &sp->tiq, ':', flags))
109 			return (1);
110 		if (INTERRUPTED(sp)) {
111 			(void)ex_puts(sp, "\n");
112 			(void)ex_fflush(sp);
113 			continue;
114 		}
115 
116 		/* Initialize the command structure. */
117 		CLEAR_EX_PARSER(&gp->excmd);
118 
119 		/*
120 		 * If the user entered a single carriage return, send
121 		 * ex_cmd() a separator -- it discards single newlines.
122 		 */
123 		tp = sp->tiq.cqh_first;
124 		if (tp->len == 0) {
125 			gp->excmd.cp = " ";	/* __TK__ why not |? */
126 			gp->excmd.clen = 1;
127 		} else {
128 			gp->excmd.cp = tp->lb;
129 			gp->excmd.clen = tp->len;
130 		}
131 		F_INIT(&gp->excmd, E_NRSEP);
132 
133 		if (ex_cmd(sp) && F_ISSET(gp, G_SCRIPTED))
134 			return (1);
135 
136 		if (INTERRUPTED(sp)) {
137 			CLR_INTERRUPT(sp);
138 			msgq(sp, M_ERR, "170|Interrupted");
139 		}
140 
141 		/*
142 		 * If the last command caused a restart, or switched screens
143 		 * or into vi, return.
144 		 */
145 		if (F_ISSET(gp, G_SRESTART) || F_ISSET(sp, SC_SSWITCH | SC_VI)) {
146 			*spp = sp;
147 			break;
148 		}
149 
150 		/* If the last command switched files, we don't care. */
151 		F_CLR(sp, SC_FSWITCH);
152 
153 		/*
154 		 * If we're exiting this screen, move to the next one.  By
155 		 * definition, this means returning into vi, so return to the
156 		 * main editor loop.  The ordering is careful, don't discard
157 		 * the contents of sp until the end.
158 		 */
159 		if (F_ISSET(sp, SC_EXIT | SC_EXIT_FORCE)) {
160 			if (file_end(sp, NULL, F_ISSET(sp, SC_EXIT_FORCE)))
161 				return (1);
162 			*spp = screen_next(sp);
163 			return (screen_end(sp));
164 		}
165 	}
166 	return (0);
167 }
168 
169 /*
170  * ex_cmd --
171  *	The guts of the ex parser: parse and execute a string containing
172  *	ex commands.
173  *
174  * !!!
175  * This code MODIFIES the string that gets passed in, to delete quoting
176  * characters, etc.  The string cannot be readonly/text space, nor should
177  * you expect to use it again after ex_cmd() returns.
178  *
179  * !!!
180  * For the fun of it, if you want to see if a vi clone got the ex argument
181  * parsing right, try:
182  *
183  *	echo 'foo|bar' > file1; echo 'foo/bar' > file2;
184  *	vi
185  *	:edit +1|s/|/PIPE/|w file1| e file2|1 | s/\//SLASH/|wq
186  *
187  * or:	vi
188  *	:set|file|append|set|file
189  *
190  * For extra credit, try them in a startup .exrc file.
191  *
192  * PUBLIC: int ex_cmd __P((SCR *));
193  */
194 int
195 ex_cmd(sp)
196 	SCR *sp;
197 {
198 	enum nresult nret;
199 	EX_PRIVATE *exp;
200 	EXCMD *ecp;
201 	GS *gp;
202 	MARK cur;
203 	recno_t lno;
204 	size_t arg1_len, len;
205 	u_int32_t flags;
206 	long ltmp;
207 	int at_found, gv_found;
208 	int ch, cnt, delim, isaddr, namelen;
209 	int newscreen, notempty, tmp, vi_address;
210 	char *arg1, *p, *s, *t;
211 
212 	gp = sp->gp;
213 	exp = EXP(sp);
214 
215 	/*
216 	 * We always start running the command on the top of the stack.
217 	 * This means that *everything* must be resolved when we leave
218 	 * this function for any reason.
219 	 */
220 loop:	ecp = gp->ecq.lh_first;
221 
222 	/* If we're reading a command from a file, set up error information. */
223 	if (ecp->if_name != NULL) {
224 		gp->if_lno = ecp->if_lno;
225 		gp->if_name = ecp->if_name;
226 	}
227 
228 	/*
229 	 * If a move to the end of the file is scheduled for this command,
230 	 * do it now.
231 	 */
232 	if (F_ISSET(ecp, E_MOVETOEND)) {
233 		if (db_last(sp, &sp->lno))
234 			goto rfail;
235 		sp->cno = 0;
236 		F_CLR(ecp, E_MOVETOEND);
237 	}
238 
239 	/* If we found a newline, increment the count now. */
240 	if (F_ISSET(ecp, E_NEWLINE)) {
241 		++gp->if_lno;
242 		++ecp->if_lno;
243 		F_CLR(ecp, E_NEWLINE);
244 	}
245 
246 	/* (Re)initialize the EXCMD structure, preserving some flags. */
247 	CLEAR_EX_CMD(ecp);
248 
249 	/* Initialize the argument structures. */
250 	if (argv_init(sp, ecp))
251 		goto err;
252 
253 	/* Initialize +cmd, saved command information. */
254 	arg1 = NULL;
255 	ecp->save_cmdlen = 0;
256 
257 	/* Skip <blank>s, empty lines.  */
258 	for (notempty = 0; ecp->clen > 0; ++ecp->cp, --ecp->clen)
259 		if ((ch = *ecp->cp) == '\n') {
260 			++gp->if_lno;
261 			++ecp->if_lno;
262 		} else if (isblank(ch))
263 			notempty = 1;
264 		else
265 			break;
266 
267 	/*
268 	 * !!!
269 	 * Permit extra colons at the start of the line.  Historically,
270 	 * ex/vi allowed a single extra one.  It's simpler not to count.
271 	 * The stripping is done here because, historically, any command
272 	 * could have preceding colons, e.g. ":g/pattern/:p" worked.
273 	 */
274 	if (ecp->clen != 0 && ch == ':') {
275 		notempty = 1;
276 		while (--ecp->clen > 0 && (ch = *++ecp->cp) == ':');
277 	}
278 
279 	/*
280 	 * Command lines that start with a double-quote are comments.
281 	 *
282 	 * !!!
283 	 * Historically, there was no escape or delimiter for a comment, e.g.
284 	 * :"foo|set was a single comment and nothing was output.  Since nvi
285 	 * permits users to escape <newline> characters into command lines, we
286 	 * have to check for that case.
287 	 */
288 	if (ecp->clen != 0 && ch == '"') {
289 		while (--ecp->clen > 0 && *++ecp->cp != '\n');
290 		if (*ecp->cp == '\n') {
291 			F_SET(ecp, E_NEWLINE);
292 			++ecp->cp;
293 			--ecp->clen;
294 		}
295 		goto loop;
296 	}
297 
298 	/* Skip whitespace. */
299 	for (; ecp->clen > 0; ++ecp->cp, --ecp->clen) {
300 		ch = *ecp->cp;
301 		if (!isblank(ch))
302 			break;
303 	}
304 
305 	/*
306 	 * The last point at which an empty line can mean do nothing.
307 	 *
308 	 * !!!
309 	 * Historically, in ex mode, lines containing only <blank> characters
310 	 * were the same as a single <carriage-return>, i.e. a default command.
311 	 * In vi mode, they were ignored.  In .exrc files this was a serious
312 	 * annoyance, as vi kept trying to treat them as print commands.  We
313 	 * ignore backward compatibility in this case, discarding lines that
314 	 * contain only <blank> characters from .exrc files.
315 	 *
316 	 * !!!
317 	 * This is where you end up when you're done a command, i.e. clen has
318 	 * gone to zero.  Continue if there are more commands to run.
319 	 */
320 	if (ecp->clen == 0 &&
321 	    (!notempty || F_ISSET(sp, SC_VI) || F_ISSET(ecp, E_BLIGNORE))) {
322 		if (ex_load(sp))
323 			goto rfail;
324 		ecp = gp->ecq.lh_first;
325 		if (ecp->clen == 0)
326 			goto rsuccess;
327 		goto loop;
328 	}
329 
330 	/*
331 	 * Check to see if this is a command for which we may want to move
332 	 * the cursor back up to the previous line.  (The command :1<CR>
333 	 * wants a <newline> separator, but the command :<CR> wants to erase
334 	 * the command line.)  If the line is empty except for <blank>s,
335 	 * <carriage-return> or <eof>, we'll probably want to move up.  I
336 	 * don't think there's any way to get <blank> characters *after* the
337 	 * command character, but this is the ex parser, and I've been wrong
338 	 * before.
339 	 */
340 	if (F_ISSET(ecp, E_NRSEP) &&
341 	    ecp->clen != 0 && (ecp->clen != 1 || ecp->cp[0] != '\004'))
342 		F_CLR(ecp, E_NRSEP);
343 
344 	/* Parse command addresses. */
345 	if (ex_range(sp, ecp, &tmp))
346 		goto rfail;
347 	if (tmp)
348 		goto err;
349 
350 	/*
351 	 * Skip <blank>s and any more colons (the command :3,5:print
352 	 * worked, historically).
353 	 */
354 	for (; ecp->clen > 0; ++ecp->cp, --ecp->clen) {
355 		ch = *ecp->cp;
356 		if (!isblank(ch) && ch != ':')
357 			break;
358 	}
359 
360 	/*
361 	 * If no command, ex does the last specified of p, l, or #, and vi
362 	 * moves to the line.  Otherwise, determine the length of the command
363 	 * name by looking for the first non-alphabetic character.  (There
364 	 * are a few non-alphabetic characters in command names, but they're
365 	 * all single character commands.)  This isn't a great test, because
366 	 * it means that, for the command ":e +cut.c file", we'll report that
367 	 * the command "cut" wasn't known.  However, it makes ":e+35 file" work
368 	 * correctly.
369 	 *
370 	 * !!!
371 	 * Historically, lines with multiple adjacent (or <blank> separated)
372 	 * command separators were very strange.  For example, the command
373 	 * |||<carriage-return>, when the cursor was on line 1, displayed
374 	 * lines 2, 3 and 5 of the file.  In addition, the command "   |  "
375 	 * would only display the line after the next line, instead of the
376 	 * next two lines.  No ideas why.  It worked reasonably when executed
377 	 * from vi mode, and displayed lines 2, 3, and 4, so we do a default
378 	 * command for each separator.
379 	 */
380 #define	SINGLE_CHAR_COMMANDS	"\004!#&*<=>@~"
381 	newscreen = 0;
382 	if (ecp->clen != 0 && ecp->cp[0] != '|' && ecp->cp[0] != '\n') {
383 		if (strchr(SINGLE_CHAR_COMMANDS, *ecp->cp)) {
384 			p = ecp->cp;
385 			++ecp->cp;
386 			--ecp->clen;
387 			namelen = 1;
388 		} else {
389 			for (p = ecp->cp;
390 			    ecp->clen > 0; --ecp->clen, ++ecp->cp)
391 				if (!isalpha(*ecp->cp))
392 					break;
393 			if ((namelen = ecp->cp - p) == 0) {
394 				msgq(sp, M_ERR, "080|Unknown command name");
395 				goto err;
396 			}
397 		}
398 
399 		/*
400 		 * !!!
401 		 * Historic vi permitted flags to immediately follow any
402 		 * subset of the 'delete' command, but then did not permit
403 		 * further arguments (flag, buffer, count).  Make it work.
404 		 * Permit further arguments for the few shreds of dignity
405 		 * it offers.
406 		 *
407 		 * Adding commands that start with 'd', and match "delete"
408 		 * up to a l, p, +, - or # character can break this code.
409 		 *
410 		 * !!!
411 		 * Capital letters beginning the command names ex, edit,
412 		 * next, previous, tag and visual (in vi mode) indicate the
413 		 * command should happen in a new screen.
414 		 */
415 		switch (p[0]) {
416 		case 'd':
417 			for (s = p,
418 			    t = cmds[C_DELETE].name; *s == *t; ++s, ++t);
419 			if (s[0] == 'l' || s[0] == 'p' || s[0] == '+' ||
420 			    s[0] == '-' || s[0] == '^' || s[0] == '#') {
421 				len = (ecp->cp - p) - (s - p);
422 				ecp->cp -= len;
423 				ecp->clen += len;
424 				ecp->rcmd = cmds[C_DELETE];
425 				ecp->rcmd.syntax = "1bca1";
426 				ecp->cmd = &ecp->rcmd;
427 				goto skip_srch;
428 			}
429 			break;
430 		case 'E': case 'F': case 'N': case 'P': case 'T': case 'V':
431 			newscreen = 1;
432 			p[0] = tolower(p[0]);
433 			break;
434 		}
435 
436 		/*
437 		 * Search the table for the command.
438 		 *
439 		 * !!!
440 		 * Historic vi permitted the mark to immediately follow the
441 		 * 'k' in the 'k' command.  Make it work.
442 		 *
443 		 * !!!
444 		 * Historic vi permitted any flag to follow the s command, e.g.
445 		 * "s/e/E/|s|sgc3p" was legal.  Make the command "sgc" work.
446 		 * Since the following characters all have to be flags, i.e.
447 		 * alphabetics, we can let the s command routine return errors
448 		 * if it was some illegal command string.  This code will break
449 		 * if an "sg" or similar command is ever added.  The substitute
450 		 * code doesn't care if it's a "cgr" flag or a "#lp" flag that
451 		 * follows the 's', but we limit the choices here to "cgr" so
452 		 * that we get unknown command messages for wrong combinations.
453 		 */
454 		if ((ecp->cmd = ex_comm_search(p, namelen)) == NULL)
455 			switch (p[0]) {
456 			case 'k':
457 				if (p[1] && !p[2]) {
458 					ecp->cp -= namelen - 1;
459 					ecp->clen += namelen - 1;
460 					ecp->cmd = &cmds[C_K];
461 					break;
462 				}
463 				goto unknown;
464 			case 's':
465 				for (s = p + 1, cnt = namelen; --cnt; ++s)
466 					if (s[0] != 'c' &&
467 					    s[0] != 'g' && s[0] != 'r')
468 						break;
469 				if (cnt == 0) {
470 					ecp->cp -= namelen - 1;
471 					ecp->clen += namelen - 1;
472 					ecp->rcmd = cmds[C_SUBSTITUTE];
473 					ecp->rcmd.fn = ex_subagain;
474 					ecp->cmd = &ecp->rcmd;
475 					break;
476 				}
477 				/* FALLTHROUGH */
478 			default:
479 unknown:			if (newscreen)
480 					p[0] = toupper(p[0]);
481 				ex_unknown(sp, p, namelen);
482 				goto err;
483 			}
484 
485 		/*
486 		 * The visual command has a different syntax when called
487 		 * from ex than when called from a vi colon command.  FMH.
488 		 * Make the change now, before we test for the newscreen
489 		 * semantic, so that we're testing the right one.
490 		 */
491 skip_srch:	if (ecp->cmd == &cmds[C_VISUAL_EX] && F_ISSET(sp, SC_VI))
492 			ecp->cmd = &cmds[C_VISUAL_VI];
493 
494 		/*
495 		 * !!!
496 		 * Historic vi permitted a capital 'P' at the beginning of
497 		 * any command that started with 'p'.  Probably wanted the
498 		 * P[rint] command for backward compatibility, and the code
499 		 * just made Preserve and Put work by accident.  Nvi uses
500 		 * Previous to mean previous-in-a-new-screen, so be careful.
501 		 */
502 		if (newscreen && !F_ISSET(ecp->cmd, E_NEWSCREEN) &&
503 		    (ecp->cmd == &cmds[C_PRINT] ||
504 		    ecp->cmd == &cmds[C_PRESERVE]))
505 			newscreen = 0;
506 
507 		/* Test for a newscreen associated with this command. */
508 		if (newscreen && !F_ISSET(ecp->cmd, E_NEWSCREEN))
509 			goto unknown;
510 
511 		/* Secure means no shell access. */
512 		if (F_ISSET(ecp->cmd, E_SECURE) && O_ISSET(sp, O_SECURE)) {
513 			ex_emsg(sp, ecp->cmd->name, EXM_SECURE);
514 			goto err;
515 		}
516 
517 		/*
518 		 * Multiple < and > characters; another "feature".  Note,
519 		 * The string passed to the underlying function may not be
520 		 * nul terminated in this case.
521 		 */
522 		if ((ecp->cmd == &cmds[C_SHIFTL] && *p == '<') ||
523 		    (ecp->cmd == &cmds[C_SHIFTR] && *p == '>')) {
524 			for (ch = *p;
525 			    ecp->clen > 0; --ecp->clen, ++ecp->cp)
526 				if (*ecp->cp != ch)
527 					break;
528 			if (argv_exp0(sp, ecp, p, ecp->cp - p))
529 				goto err;
530 		}
531 
532 		/* Set the format style flags for the next command. */
533 		if (ecp->cmd == &cmds[C_HASH])
534 			exp->fdef = E_C_HASH;
535 		else if (ecp->cmd == &cmds[C_LIST])
536 			exp->fdef = E_C_LIST;
537 		else if (ecp->cmd == &cmds[C_PRINT])
538 			exp->fdef = E_C_PRINT;
539 		F_CLR(ecp, E_USELASTCMD);
540 	} else {
541 		/* Print is the default command. */
542 		ecp->cmd = &cmds[C_PRINT];
543 
544 		/* Set the saved format flags. */
545 		F_SET(ecp, exp->fdef);
546 
547 		/*
548 		 * !!!
549 		 * If no address was specified, and it's not a global command,
550 		 * we up the address by one.  (I have no idea why globals are
551 		 * exempted, but it's (ahem) historic practice.)
552 		 */
553 		if (ecp->addrcnt == 0 && !F_ISSET(sp, SC_EX_GLOBAL)) {
554 			ecp->addrcnt = 1;
555 			ecp->addr1.lno = sp->lno + 1;
556 			ecp->addr1.cno = sp->cno;
557 		}
558 
559 		F_SET(ecp, E_USELASTCMD);
560 	}
561 
562 	/*
563 	 * !!!
564 	 * Historically, the number option applied to both ex and vi.  One
565 	 * strangeness was that ex didn't switch display formats until a
566 	 * command was entered, e.g. <CR>'s after the set didn't change to
567 	 * the new format, but :1p would.
568 	 */
569 	if (O_ISSET(sp, O_NUMBER)) {
570 		F_SET(ecp, E_OPTNUM);
571 		FL_SET(ecp->iflags, E_C_HASH);
572 	} else
573 		F_CLR(ecp, E_OPTNUM);
574 
575 	/* Check for ex mode legality. */
576 	if (F_ISSET(sp, SC_EX) && (F_ISSET(ecp->cmd, E_VIONLY) || newscreen)) {
577 		msgq(sp, M_ERR,
578 		    "082|%s: command not available in ex mode", ecp->cmd->name);
579 		goto err;
580 	}
581 
582 	/* Add standard command flags. */
583 	F_SET(ecp, ecp->cmd->flags);
584 	if (!newscreen)
585 		F_CLR(ecp, E_NEWSCREEN);
586 
587 	/*
588 	 * There are three normal termination cases for an ex command.  They
589 	 * are the end of the string (ecp->clen), or unescaped (by <literal
590 	 * next> characters) <newline> or '|' characters.  As we're now past
591 	 * possible addresses, we can determine how long the command is, so we
592 	 * don't have to look for all the possible terminations.  Naturally,
593 	 * there are some exciting special cases:
594 	 *
595 	 * 1: The bang, global, v and the filter versions of the read and
596 	 *    write commands are delimited by <newline>s (they can contain
597 	 *    shell pipes).
598 	 * 2: The ex, edit, next and visual in vi mode commands all take ex
599 	 *    commands as their first arguments.
600 	 * 3: The s command takes an RE as its first argument, and wants it
601 	 *    to be specially delimited.
602 	 *
603 	 * Historically, '|' characters in the first argument of the ex, edit,
604 	 * next, vi visual, and s commands didn't delimit the command.  And,
605 	 * in the filter cases for read and write, and the bang, global and v
606 	 * commands, they did not delimit the command at all.
607 	 *
608 	 * For example, the following commands were legal:
609 	 *
610 	 *	:edit +25|s/abc/ABC/ file.c
611 	 *	:s/|/PIPE/
612 	 *	:read !spell % | columnate
613 	 *	:global/pattern/p|l
614 	 *
615 	 * It's not quite as simple as it sounds, however.  The command:
616 	 *
617 	 *	:s/a/b/|s/c/d|set
618 	 *
619 	 * was also legal, i.e. the historic ex parser (using the word loosely,
620 	 * since "parser" implies some regularity of syntax) delimited the RE's
621 	 * based on its delimiter and not anything so irretrievably vulgar as a
622 	 * command syntax.
623 	 *
624 	 * Anyhow, the following code makes this all work.  First, for the
625 	 * special cases we move past their special argument(s).  Then, we
626 	 * do normal command processing on whatever is left.  Barf-O-Rama.
627 	 */
628 	arg1_len = 0;
629 	ecp->save_cmd = ecp->cp;
630 	if (ecp->cmd == &cmds[C_EDIT] || ecp->cmd == &cmds[C_EX] ||
631 	    ecp->cmd == &cmds[C_NEXT] || ecp->cmd == &cmds[C_VISUAL_VI]) {
632 		/*
633 		 * Move to the next non-whitespace character.  A '!'
634 		 * immediately following the command is eaten as a
635 		 * force flag.
636 		 */
637 		if (ecp->clen > 0 && *ecp->cp == '!') {
638 			++ecp->cp;
639 			--ecp->clen;
640 			FL_SET(ecp->iflags, E_C_FORCE);
641 
642 			/* Reset, don't reparse. */
643 			ecp->save_cmd = ecp->cp;
644 		}
645 		for (; ecp->clen > 0; --ecp->clen, ++ecp->cp)
646 			if (!isblank(*ecp->cp))
647 				break;
648 		/*
649 		 * QUOTING NOTE:
650 		 *
651 		 * The historic implementation ignored all escape characters
652 		 * so there was no way to put a space or newline into the +cmd
653 		 * field.  We do a simplistic job of fixing it by moving to the
654 		 * first whitespace character that isn't escaped.  The escaping
655 		 * characters are stripped as no longer useful.
656 		 */
657 		if (ecp->clen > 0 && *ecp->cp == '+') {
658 			++ecp->cp;
659 			--ecp->clen;
660 			for (arg1 = p = ecp->cp;
661 			    ecp->clen > 0; --ecp->clen, ++ecp->cp) {
662 				ch = *ecp->cp;
663 				if (IS_ESCAPE(sp, ecp, ch) &&
664 				    ecp->clen > 1) {
665 					--ecp->clen;
666 					ch = *++ecp->cp;
667 				} else if (isblank(ch))
668 					break;
669 				*p++ = ch;
670 			}
671 			arg1_len = ecp->cp - arg1;
672 
673 			/* Reset, so the first argument isn't reparsed. */
674 			ecp->save_cmd = ecp->cp;
675 		}
676 	} else if (ecp->cmd == &cmds[C_BANG] ||
677 	    ecp->cmd == &cmds[C_GLOBAL] || ecp->cmd == &cmds[C_V]) {
678 		for (; ecp->clen > 0; --ecp->clen, ++ecp->cp)
679 			if (ecp->cp[0] == '\n')
680 				break;
681 	} else if (ecp->cmd == &cmds[C_READ] || ecp->cmd == &cmds[C_WRITE]) {
682 		/*
683 		 * For write commands, if the next character is a <blank>, and
684 		 * the next non-blank character is a '!', it's a filter command
685 		 * and we want to eat everything up to the <newline>.  For read
686 		 * commands, if the next non-blank character is a '!', it's a
687 		 * filter command and we want to eat everything up to the next
688 		 * <newline>.  Otherwise, we're done.
689 		 */
690 		for (tmp = 0; ecp->clen > 0; --ecp->clen, ++ecp->cp) {
691 			ch = *ecp->cp;
692 			if (isblank(ch))
693 				tmp = 1;
694 			else
695 				break;
696 		}
697 		if (ecp->clen > 0 && ch == '!' &&
698 		    (ecp->cmd == &cmds[C_READ] || tmp))
699 			for (; ecp->clen > 0; --ecp->clen, ++ecp->cp)
700 				if (ecp->cp[0] == '\n')
701 					break;
702 	} else if (ecp->cmd == &cmds[C_SUBSTITUTE]) {
703 		/*
704 		 * Move to the next non-whitespace character, we'll use it as
705 		 * the delimiter.  If the character isn't an alphanumeric or
706 		 * a '|', it's the delimiter, so parse it.  Otherwise, we're
707 		 * into something like ":s g", so use the special s command.
708 		 */
709 		for (; ecp->clen > 0; --ecp->clen, ++ecp->cp)
710 			if (!isblank(ecp->cp[0]))
711 				break;
712 
713 		if (isalnum(ecp->cp[0]) || ecp->cp[0] == '|') {
714 			ecp->rcmd = cmds[C_SUBSTITUTE];
715 			ecp->rcmd.fn = ex_subagain;
716 			ecp->cmd = &ecp->rcmd;
717 		} else if (ecp->clen > 0) {
718 			/*
719 			 * QUOTING NOTE:
720 			 *
721 			 * Backslashes quote delimiter characters for RE's.
722 			 * The backslashes are NOT removed since they'll be
723 			 * used by the RE code.  Move to the third delimiter
724 			 * that's not escaped (or the end of the command).
725 			 */
726 			delim = *ecp->cp;
727 			++ecp->cp;
728 			--ecp->clen;
729 			for (cnt = 2; ecp->clen > 0 &&
730 			    cnt != 0; --ecp->clen, ++ecp->cp)
731 				if (ecp->cp[0] == '\\' &&
732 				    ecp->clen > 1) {
733 					++ecp->cp;
734 					--ecp->clen;
735 				} else if (ecp->cp[0] == delim)
736 					--cnt;
737 		}
738 	}
739 
740 	/*
741 	 * Use normal quoting and termination rules to find the end of this
742 	 * command.
743 	 *
744 	 * QUOTING NOTE:
745 	 *
746 	 * Historically, vi permitted ^V's to escape <newline>'s in the .exrc
747 	 * file.  It was almost certainly a bug, but that's what bug-for-bug
748 	 * compatibility means, Grasshopper.  Also, ^V's escape the command
749 	 * delimiters.  Literal next quote characters in front of the newlines,
750 	 * '|' characters or literal next characters are stripped as they're
751 	 * no longer useful.
752 	 */
753 	vi_address = ecp->clen != 0 && ecp->cp[0] != '\n';
754 	for (cnt = 0, p = ecp->cp; ecp->clen > 0; --ecp->clen, ++ecp->cp) {
755 		ch = ecp->cp[0];
756 		if (IS_ESCAPE(sp, ecp, ch) && ecp->clen > 1) {
757 			tmp = ecp->cp[1];
758 			if (tmp == '\n' || tmp == '|') {
759 				if (tmp == '\n') {
760 					++gp->if_lno;
761 					++ecp->if_lno;
762 				}
763 				--ecp->clen;
764 				++ecp->cp;
765 				++cnt;
766 				ch = tmp;
767 			}
768 		} else if (ch == '\n' || ch == '|') {
769 			if (ch == '\n')
770 				F_SET(ecp, E_NEWLINE);
771 			--ecp->clen;
772 			break;
773 		}
774 		*p++ = ch;
775 	}
776 
777 	/*
778 	 * Save off the next command information, go back to the
779 	 * original start of the command.
780 	 */
781 	p = ecp->cp + 1;
782 	ecp->cp = ecp->save_cmd;
783 	ecp->save_cmd = p;
784 	ecp->save_cmdlen = ecp->clen;
785 	ecp->clen = ((ecp->save_cmd - ecp->cp) - 1) - cnt;
786 
787 	/*
788 	 * QUOTING NOTE:
789 	 *
790 	 * The "set tags" command historically used a backslash, not the
791 	 * user's literal next character, to escape whitespace.  Handle
792 	 * it here instead of complicating the argv_exp3() code.  Note,
793 	 * this isn't a particularly complex trap, and if backslashes were
794 	 * legal in set commands, this would have to be much more complicated.
795 	 */
796 	if (ecp->cmd == &cmds[C_SET])
797 		for (p = ecp->cp, len = ecp->clen; len > 0; --len, ++p)
798 			if (*p == '\\')
799 				*p = CH_LITERAL;
800 
801 	/*
802 	 * Set the default addresses.  It's an error to specify an address for
803 	 * a command that doesn't take them.  If two addresses are specified
804 	 * for a command that only takes one, lose the first one.  Two special
805 	 * cases here, some commands take 0 or 2 addresses.  For most of them
806 	 * (the E_ADDR2_ALL flag), 0 defaults to the entire file.  For one
807 	 * (the `!' command, the E_ADDR2_NONE flag), 0 defaults to no lines.
808 	 *
809 	 * Also, if the file is empty, some commands want to use an address of
810 	 * 0, i.e. the entire file is 0 to 0, and the default first address is
811 	 * 0.  Otherwise, an entire file is 1 to N and the default line is 1.
812 	 * Note, we also add the E_ADDR_ZERO flag to the command flags, for the
813 	 * case where the 0 address is only valid if it's a default address.
814 	 *
815 	 * Also, set a flag if we set the default addresses.  Some commands
816 	 * (ex: z) care if the user specified an address or if we just used
817 	 * the current cursor.
818 	 */
819 	switch (F_ISSET(ecp, E_ADDR1 | E_ADDR2 | E_ADDR2_ALL | E_ADDR2_NONE)) {
820 	case E_ADDR1:				/* One address: */
821 		switch (ecp->addrcnt) {
822 		case 0:				/* Default cursor/empty file. */
823 			ecp->addrcnt = 1;
824 			F_SET(ecp, E_ADDR_DEF);
825 			if (F_ISSET(ecp, E_ADDR_ZERODEF)) {
826 				if (db_last(sp, &lno))
827 					goto err;
828 				if (lno == 0) {
829 					ecp->addr1.lno = 0;
830 					F_SET(ecp, E_ADDR_ZERO);
831 				} else
832 					ecp->addr1.lno = sp->lno;
833 			} else
834 				ecp->addr1.lno = sp->lno;
835 			ecp->addr1.cno = sp->cno;
836 			break;
837 		case 1:
838 			break;
839 		case 2:				/* Lose the first address. */
840 			ecp->addrcnt = 1;
841 			ecp->addr1 = ecp->addr2;
842 		}
843 		break;
844 	case E_ADDR2_NONE:			/* Zero/two addresses: */
845 		if (ecp->addrcnt == 0)		/* Default to nothing. */
846 			break;
847 		goto two_addr;
848 	case E_ADDR2_ALL:			/* Zero/two addresses: */
849 		if (ecp->addrcnt == 0) {	/* Default entire/empty file. */
850 			F_SET(ecp, E_ADDR_DEF);
851 			ecp->addrcnt = 2;
852 			if (sp->ep == NULL)
853 				ecp->addr2.lno = 0;
854 			else if (db_last(sp, &ecp->addr2.lno))
855 				goto err;
856 			if (F_ISSET(ecp, E_ADDR_ZERODEF) &&
857 			    ecp->addr2.lno == 0) {
858 				ecp->addr1.lno = 0;
859 				F_SET(ecp, E_ADDR_ZERO);
860 			} else
861 				ecp->addr1.lno = 1;
862 			ecp->addr1.cno = ecp->addr2.cno = 0;
863 			F_SET(ecp, E_ADDR2_ALL);
864 			break;
865 		}
866 		/* FALLTHROUGH */
867 	case E_ADDR2:				/* Two addresses: */
868 two_addr:	switch (ecp->addrcnt) {
869 		case 0:				/* Default cursor/empty file. */
870 			ecp->addrcnt = 2;
871 			F_SET(ecp, E_ADDR_DEF);
872 			if (sp->lno == 1 &&
873 			    F_ISSET(ecp, E_ADDR_ZERODEF)) {
874 				if (db_last(sp, &lno))
875 					goto err;
876 				if (lno == 0) {
877 					ecp->addr1.lno = ecp->addr2.lno = 0;
878 					F_SET(ecp, E_ADDR_ZERO);
879 				} else
880 					ecp->addr1.lno =
881 					    ecp->addr2.lno = sp->lno;
882 			} else
883 				ecp->addr1.lno = ecp->addr2.lno = sp->lno;
884 			ecp->addr1.cno = ecp->addr2.cno = sp->cno;
885 			break;
886 		case 1:				/* Default to first address. */
887 			ecp->addrcnt = 2;
888 			ecp->addr2 = ecp->addr1;
889 			break;
890 		case 2:
891 			break;
892 		}
893 		break;
894 	default:
895 		if (ecp->addrcnt)		/* Error. */
896 			goto usage;
897 	}
898 
899 	/*
900 	 * !!!
901 	 * The ^D scroll command historically scrolled the value of the scroll
902 	 * option or to EOF.  It was an error if the cursor was already at EOF.
903 	 * (Leading addresses were permitted, but were then ignored.)
904 	 */
905 	if (ecp->cmd == &cmds[C_SCROLL]) {
906 		ecp->addrcnt = 2;
907 		ecp->addr1.lno = sp->lno + 1;
908 		ecp->addr2.lno = sp->lno + O_VAL(sp, O_SCROLL);
909 		ecp->addr1.cno = ecp->addr2.cno = sp->cno;
910 		if (db_last(sp, &lno))
911 			goto err;
912 		if (lno != 0 && lno > sp->lno && ecp->addr2.lno > lno)
913 			ecp->addr2.lno = lno;
914 	}
915 
916 	ecp->flagoff = 0;
917 	for (p = ecp->cmd->syntax; *p != '\0'; ++p) {
918 		/*
919 		 * The force flag is sensitive to leading whitespace, i.e.
920 		 * "next !" is different from "next!".  Handle it before
921 		 * skipping leading <blank>s.
922 		 */
923 		if (*p == '!') {
924 			if (ecp->clen > 0 && *ecp->cp == '!') {
925 				++ecp->cp;
926 				--ecp->clen;
927 				FL_SET(ecp->iflags, E_C_FORCE);
928 			}
929 			continue;
930 		}
931 
932 		/* Skip leading <blank>s. */
933 		for (; ecp->clen > 0; --ecp->clen, ++ecp->cp)
934 			if (!isblank(*ecp->cp))
935 				break;
936 		if (ecp->clen == 0)
937 			break;
938 
939 		switch (*p) {
940 		case '1':				/* +, -, #, l, p */
941 			/*
942 			 * !!!
943 			 * Historically, some flags were ignored depending
944 			 * on where they occurred in the command line.  For
945 			 * example, in the command, ":3+++p--#", historic vi
946 			 * acted on the '#' flag, but ignored the '-' flags.
947 			 * It's unambiguous what the flags mean, so we just
948 			 * handle them regardless of the stupidity of their
949 			 * location.
950 			 */
951 			for (; ecp->clen; --ecp->clen, ++ecp->cp)
952 				switch (*ecp->cp) {
953 				case '+':
954 					++ecp->flagoff;
955 					break;
956 				case '-':
957 				case '^':
958 					--ecp->flagoff;
959 					break;
960 				case '#':
961 					F_CLR(ecp, E_OPTNUM);
962 					FL_SET(ecp->iflags, E_C_HASH);
963 					exp->fdef |= E_C_HASH;
964 					break;
965 				case 'l':
966 					FL_SET(ecp->iflags, E_C_LIST);
967 					exp->fdef |= E_C_LIST;
968 					break;
969 				case 'p':
970 					FL_SET(ecp->iflags, E_C_PRINT);
971 					exp->fdef |= E_C_PRINT;
972 					break;
973 				default:
974 					goto end_case1;
975 				}
976 end_case1:		break;
977 		case '2':				/* -, ., +, ^ */
978 		case '3':				/* -, ., +, ^, = */
979 			for (; ecp->clen; --ecp->clen, ++ecp->cp)
980 				switch (*ecp->cp) {
981 				case '-':
982 					FL_SET(ecp->iflags, E_C_DASH);
983 					break;
984 				case '.':
985 					FL_SET(ecp->iflags, E_C_DOT);
986 					break;
987 				case '+':
988 					FL_SET(ecp->iflags, E_C_PLUS);
989 					break;
990 				case '^':
991 					FL_SET(ecp->iflags, E_C_CARAT);
992 					break;
993 				case '=':
994 					if (*p == '3') {
995 						FL_SET(ecp->iflags, E_C_EQUAL);
996 						break;
997 					}
998 					/* FALLTHROUGH */
999 				default:
1000 					goto end_case23;
1001 				}
1002 end_case23:		break;
1003 		case 'b':				/* buffer */
1004 			/*
1005 			 * !!!
1006 			 * Historically, "d #" was a delete with a flag, not a
1007 			 * delete into the '#' buffer.  If the current command
1008 			 * permits a flag, don't use one as a buffer.  However,
1009 			 * the 'l' and 'p' flags were legal buffer names in the
1010 			 * historic ex, and were used as buffers, not flags.
1011 			 */
1012 			if ((ecp->cp[0] == '+' || ecp->cp[0] == '-' ||
1013 			    ecp->cp[0] == '^' || ecp->cp[0] == '#') &&
1014 			    strchr(p, '1') != NULL)
1015 				break;
1016 			/*
1017 			 * !!!
1018 			 * Digits can't be buffer names in ex commands, or the
1019 			 * command "d2" would be a delete into buffer '2', and
1020 			 * not a two-line deletion.
1021 			 */
1022 			if (!isdigit(ecp->cp[0])) {
1023 				ecp->buffer = *ecp->cp;
1024 				++ecp->cp;
1025 				--ecp->clen;
1026 				FL_SET(ecp->iflags, E_C_BUFFER);
1027 			}
1028 			break;
1029 		case 'c':				/* count [01+a] */
1030 			++p;
1031 			/* Validate any signed value. */
1032 			if (!isdigit(*ecp->cp) && (*p != '+' ||
1033 			    (*ecp->cp != '+' && *ecp->cp != '-')))
1034 				break;
1035 			/* If a signed value, set appropriate flags. */
1036 			if (*ecp->cp == '-')
1037 				FL_SET(ecp->iflags, E_C_COUNT_NEG);
1038 			else if (*ecp->cp == '+')
1039 				FL_SET(ecp->iflags, E_C_COUNT_POS);
1040 			if ((nret =
1041 			    nget_slong(&ltmp, ecp->cp, &t, 10)) != NUM_OK) {
1042 				ex_badaddr(sp, NULL, A_NOTSET, nret);
1043 				goto err;
1044 			}
1045 			if (ltmp == 0 && *p != '0') {
1046 				msgq(sp, M_ERR, "083|Count may not be zero");
1047 				goto err;
1048 			}
1049 			ecp->clen -= (t - ecp->cp);
1050 			ecp->cp = t;
1051 
1052 			/*
1053 			 * Counts as address offsets occur in commands taking
1054 			 * two addresses.  Historic vi practice was to use
1055 			 * the count as an offset from the *second* address.
1056 			 *
1057 			 * Set a count flag; some underlying commands (see
1058 			 * join) do different things with counts than with
1059 			 * line addresses.
1060 			 */
1061 			if (*p == 'a') {
1062 				ecp->addr1 = ecp->addr2;
1063 				ecp->addr2.lno = ecp->addr1.lno + ltmp - 1;
1064 			} else
1065 				ecp->count = ltmp;
1066 			FL_SET(ecp->iflags, E_C_COUNT);
1067 			break;
1068 		case 'f':				/* file */
1069 			if (argv_exp2(sp, ecp, ecp->cp, ecp->clen))
1070 				goto err;
1071 			goto arg_cnt_chk;
1072 		case 'l':				/* line */
1073 			/*
1074 			 * Get a line specification.
1075 			 *
1076 			 * If the line was a search expression, we may have
1077 			 * changed state during the call, and we're now
1078 			 * searching the file.  Push ourselves onto the state
1079 			 * stack.
1080 			 */
1081 			if (ex_line(sp, ecp, &cur, &isaddr, &tmp))
1082 				goto rfail;
1083 			if (tmp)
1084 				goto err;
1085 
1086 			/* Line specifications are always required. */
1087 			if (!isaddr) {
1088 				msgq_str(sp, M_ERR, ecp->cp,
1089 				     "084|%s: bad line specification");
1090 				goto err;
1091 			}
1092 			/*
1093 			 * The target line should exist for these commands,
1094 			 * but 0 is legal for them as well.
1095 			 */
1096 			if (cur.lno != 0 && !db_exist(sp, cur.lno)) {
1097 				ex_badaddr(sp, NULL, A_EOF, NUM_OK);
1098 				goto err;
1099 			}
1100 			ecp->lineno = cur.lno;
1101 			break;
1102 		case 'S':				/* string, file exp. */
1103 			if (ecp->clen != 0) {
1104 				if (argv_exp1(sp, ecp, ecp->cp,
1105 				    ecp->clen, ecp->cmd == &cmds[C_BANG]))
1106 					goto err;
1107 				goto addr_verify;
1108 			}
1109 			/* FALLTHROUGH */
1110 		case 's':				/* string */
1111 			if (argv_exp0(sp, ecp, ecp->cp, ecp->clen))
1112 				goto err;
1113 			goto addr_verify;
1114 		case 'W':				/* word string */
1115 			/*
1116 			 * QUOTING NOTE:
1117 			 *
1118 			 * Literal next characters escape the following
1119 			 * character.  Quoting characters are stripped here
1120 			 * since they are no longer useful.
1121 			 *
1122 			 * First there was the word.
1123 			 */
1124 			for (p = t = ecp->cp;
1125 			    ecp->clen > 0; --ecp->clen, ++ecp->cp) {
1126 				ch = *ecp->cp;
1127 				if (IS_ESCAPE(sp,
1128 				    ecp, ch) && ecp->clen > 1) {
1129 					--ecp->clen;
1130 					*p++ = *++ecp->cp;
1131 				} else if (isblank(ch)) {
1132 					++ecp->cp;
1133 					--ecp->clen;
1134 					break;
1135 				} else
1136 					*p++ = ch;
1137 			}
1138 			if (argv_exp0(sp, ecp, t, p - t))
1139 				goto err;
1140 
1141 			/* Delete intervening whitespace. */
1142 			for (; ecp->clen > 0;
1143 			    --ecp->clen, ++ecp->cp) {
1144 				ch = *ecp->cp;
1145 				if (!isblank(ch))
1146 					break;
1147 			}
1148 			if (ecp->clen == 0)
1149 				goto usage;
1150 
1151 			/* Followed by the string. */
1152 			for (p = t = ecp->cp; ecp->clen > 0;
1153 			    --ecp->clen, ++ecp->cp, ++p) {
1154 				ch = *ecp->cp;
1155 				if (IS_ESCAPE(sp,
1156 				    ecp, ch) && ecp->clen > 1) {
1157 					--ecp->clen;
1158 					*p = *++ecp->cp;
1159 				} else
1160 					*p = ch;
1161 			}
1162 			if (argv_exp0(sp, ecp, t, p - t))
1163 				goto err;
1164 			goto addr_verify;
1165 		case 'w':				/* word */
1166 			if (argv_exp3(sp, ecp, ecp->cp, ecp->clen))
1167 				goto err;
1168 arg_cnt_chk:		if (*++p != 'N') {		/* N */
1169 				/*
1170 				 * If a number is specified, must either be
1171 				 * 0 or that number, if optional, and that
1172 				 * number, if required.
1173 				 */
1174 				tmp = *p - '0';
1175 				if ((*++p != 'o' || exp->argsoff != 0) &&
1176 				    exp->argsoff != tmp)
1177 					goto usage;
1178 			}
1179 			goto addr_verify;
1180 		default:
1181 			msgq(sp, M_ERR,
1182 			    "085|Internal syntax table error (%s: %s)",
1183 			    ecp->cmd->name, KEY_NAME(sp, *p));
1184 		}
1185 	}
1186 
1187 	/* Skip trailing whitespace. */
1188 	for (; ecp->clen > 0; --ecp->clen) {
1189 		ch = *ecp->cp++;
1190 		if (!isblank(ch))
1191 			break;
1192 	}
1193 
1194 	/*
1195 	 * There shouldn't be anything left, and no more required fields,
1196 	 * i.e neither 'l' or 'r' in the syntax string.
1197 	 */
1198 	if (ecp->clen != 0 || strpbrk(p, "lr")) {
1199 usage:		msgq(sp, M_ERR, "086|Usage: %s", ecp->cmd->usage);
1200 		goto err;
1201 	}
1202 
1203 	/*
1204 	 * Verify that the addresses are legal.  Check the addresses here,
1205 	 * because this is a place where all ex addresses pass through.
1206 	 * (They don't all pass through ex_line(), for instance.)  We're
1207 	 * assuming that any non-existent line doesn't exist because it's
1208 	 * past the end-of-file.  That's a pretty good guess.
1209 	 *
1210 	 * If it's a "default vi command", an address of zero is okay.
1211 	 */
1212 addr_verify:
1213 	switch (ecp->addrcnt) {
1214 	case 2:
1215 		/*
1216 		 * Historic ex/vi permitted commands with counts to go past
1217 		 * EOF.  So, for example, if the file only had 5 lines, the
1218 		 * ex command "1,6>" would fail, but the command ">300"
1219 		 * would succeed.  Since we don't want to have to make all
1220 		 * of the underlying commands handle random line numbers,
1221 		 * fix it here.
1222 		 */
1223 		if (ecp->addr2.lno == 0) {
1224 			if (!F_ISSET(ecp, E_ADDR_ZERO) &&
1225 			    (F_ISSET(sp, SC_EX) ||
1226 			    !F_ISSET(ecp, E_USELASTCMD))) {
1227 				ex_badaddr(sp, ecp->cmd, A_ZERO, NUM_OK);
1228 				goto err;
1229 			}
1230 		} else if (!db_exist(sp, ecp->addr2.lno))
1231 			if (FL_ISSET(ecp->iflags, E_C_COUNT)) {
1232 				if (db_last(sp, &lno))
1233 					goto err;
1234 				ecp->addr2.lno = lno;
1235 			} else {
1236 				ex_badaddr(sp, NULL, A_EOF, NUM_OK);
1237 				goto err;
1238 			}
1239 		/* FALLTHROUGH */
1240 	case 1:
1241 		if (ecp->addr1.lno == 0) {
1242 			if (!F_ISSET(ecp, E_ADDR_ZERO) &&
1243 			    (F_ISSET(sp, SC_EX) ||
1244 			    !F_ISSET(ecp, E_USELASTCMD))) {
1245 				ex_badaddr(sp, ecp->cmd, A_ZERO, NUM_OK);
1246 				goto err;
1247 			}
1248 		} else if (!db_exist(sp, ecp->addr1.lno)) {
1249 			ex_badaddr(sp, NULL, A_EOF, NUM_OK);
1250 			goto err;
1251 		}
1252 		break;
1253 	}
1254 
1255 	/*
1256 	 * If doing a default command and there's nothing left on the line,
1257 	 * vi just moves to the line.  For example, ":3" and ":'a,'b" just
1258 	 * move to line 3 and line 'b, respectively, but ":3|" prints line 3.
1259 	 *
1260 	 * !!!
1261 	 * In addition, IF THE LINE CHANGES, move to the first nonblank of
1262 	 * the line.
1263 	 *
1264 	 * !!!
1265 	 * This is done before the absolute mark gets set; historically,
1266 	 * "/a/,/b/" did NOT set vi's absolute mark, but "/a/,/b/d" did.
1267 	 */
1268 	if ((F_ISSET(sp, SC_VI) || F_ISSET(ecp, E_NOPRDEF)) &&
1269 	    F_ISSET(ecp, E_USELASTCMD) && vi_address == 0) {
1270 		switch (ecp->addrcnt) {
1271 		case 2:
1272 			if (sp->lno !=
1273 			    (ecp->addr2.lno ? ecp->addr2.lno : 1)) {
1274 				sp->lno =
1275 				    ecp->addr2.lno ? ecp->addr2.lno : 1;
1276 				sp->cno = 0;
1277 				(void)nonblank(sp, sp->lno, &sp->cno);
1278 			}
1279 			break;
1280 		case 1:
1281 			if (sp->lno !=
1282 			    (ecp->addr1.lno ? ecp->addr1.lno : 1)) {
1283 				sp->lno =
1284 				    ecp->addr1.lno ? ecp->addr1.lno : 1;
1285 				sp->cno = 0;
1286 				(void)nonblank(sp, sp->lno, &sp->cno);
1287 			}
1288 			break;
1289 		}
1290 		ecp->cp = ecp->save_cmd;
1291 		ecp->clen = ecp->save_cmdlen;
1292 		goto loop;
1293 	}
1294 
1295 	/*
1296 	 * Set the absolute mark -- we have to set it for vi here, in case
1297 	 * it's a compound command, e.g. ":5p|6" should set the absolute
1298 	 * mark for vi.
1299 	 */
1300 	if (F_ISSET(ecp, E_ABSMARK)) {
1301 		cur.lno = sp->lno;
1302 		cur.cno = sp->cno;
1303 		F_CLR(ecp, E_ABSMARK);
1304 		if (mark_set(sp, ABSMARK1, &cur, 1))
1305 			goto err;
1306 	}
1307 
1308 #if defined(DEBUG) && defined(COMLOG)
1309 	ex_comlog(sp, ecp);
1310 #endif
1311 	/* Increment the command count if not called from vi. */
1312 	if (F_ISSET(sp, SC_EX))
1313 		++sp->ccnt;
1314 
1315 	/*
1316 	 * If file state available, and not doing a global command,
1317 	 * log the start of an action.
1318 	 */
1319 	if (sp->ep != NULL && !F_ISSET(sp, SC_EX_GLOBAL))
1320 		(void)log_cursor(sp);
1321 
1322 	/*
1323 	 * !!!
1324 	 * There are two special commands for the purposes of this code: the
1325 	 * default command (<carriage-return>) or the scrolling commands (^D
1326 	 * and <EOF>) as the first non-<blank> characters  in the line.
1327 	 *
1328 	 * If this is the first command in the command line, we received the
1329 	 * command from the ex command loop and we're talking to a tty, and
1330 	 * and there's nothing else on the command line, and it's one of the
1331 	 * special commands, we move back up to the previous line, and erase
1332 	 * the prompt character with the output.  Since ex runs in canonical
1333 	 * mode, we don't have to do anything else, a <newline> has already
1334 	 * been echoed by the tty driver.  It's OK if vi calls us -- we won't
1335 	 * be in ex mode so we'll do nothing.
1336 	 */
1337 	if (F_ISSET(ecp, E_NRSEP)) {
1338 		if (sp->ep != NULL &&
1339 		    F_ISSET(sp, SC_EX) && !F_ISSET(gp, G_SCRIPTED) &&
1340 		    (F_ISSET(ecp, E_USELASTCMD) || ecp->cmd == &cmds[C_SCROLL]))
1341 			gp->scr_ex_adjust(sp, EX_TERM_SCROLL);
1342 		F_CLR(ecp, E_NRSEP);
1343 	}
1344 
1345 	/*
1346 	 * Call the underlying function for the ex command.
1347 	 *
1348 	 * XXX
1349 	 * Interrupts behave like errors, for now.
1350 	 */
1351 	if (ecp->cmd->fn(sp, ecp) || INTERRUPTED(sp)) {
1352 		if (F_ISSET(gp, G_SCRIPTED))
1353 			F_SET(sp, SC_EXIT_FORCE);
1354 		goto err;
1355 	}
1356 
1357 #ifdef DEBUG
1358 	/* Make sure no function left global temporary space locked. */
1359 	if (F_ISSET(gp, G_TMP_INUSE)) {
1360 		F_CLR(gp, G_TMP_INUSE);
1361 		msgq(sp, M_ERR, "087|%s: temporary buffer not released",
1362 		    ecp->cmd->name);
1363 	}
1364 #endif
1365 	/*
1366 	 * Ex displayed the number of lines modified immediately after each
1367 	 * command, so the command "1,10d|1,10d" would display:
1368 	 *
1369 	 *	10 lines deleted
1370 	 *	10 lines deleted
1371 	 *	<autoprint line>
1372 	 *
1373 	 * Executing ex commands from vi only reported the final modified
1374 	 * lines message -- that's wrong enough that we don't match it.
1375 	 */
1376 	if (F_ISSET(sp, SC_EX))
1377 		mod_rpt(sp);
1378 
1379 	/*
1380 	 * Integrate any offset parsed by the underlying command, and make
1381 	 * sure the referenced line exists.
1382 	 *
1383 	 * XXX
1384 	 * May not match historic practice (which I've never been able to
1385 	 * completely figure out.)  For example, the '=' command from vi
1386 	 * mode often got the offset wrong, and complained it was too large,
1387 	 * but didn't seem to have a problem with the cursor.  If anyone
1388 	 * complains, ask them how it's supposed to work, they might know.
1389 	 */
1390 	if (sp->ep != NULL && ecp->flagoff) {
1391 		if (ecp->flagoff < 0) {
1392 			if (sp->lno <= -ecp->flagoff) {
1393 				msgq(sp, M_ERR,
1394 				    "088|Flag offset to before line 1");
1395 				goto err;
1396 			}
1397 		} else {
1398 			if (!NPFITS(MAX_REC_NUMBER, sp->lno, ecp->flagoff)) {
1399 				ex_badaddr(sp, NULL, A_NOTSET, NUM_OVER);
1400 				goto err;
1401 			}
1402 			if (!db_exist(sp, sp->lno + ecp->flagoff)) {
1403 				msgq(sp, M_ERR,
1404 				    "089|Flag offset past end-of-file");
1405 				goto err;
1406 			}
1407 		}
1408 		sp->lno += ecp->flagoff;
1409 	}
1410 
1411 	/*
1412 	 * If the command executed successfully, we may want to display a line
1413 	 * based on the autoprint option or an explicit print flag.  (Make sure
1414 	 * that there's a line to display.)  Also, the autoprint edit option is
1415 	 * turned off for the duration of global commands.
1416 	 */
1417 	if (F_ISSET(sp, SC_EX) && sp->ep != NULL && sp->lno != 0) {
1418 		/*
1419 		 * The print commands have already handled the `print' flags.
1420 		 * If so, clear them.
1421 		 */
1422 		if (FL_ISSET(ecp->iflags, E_CLRFLAG))
1423 			FL_CLR(ecp->iflags, E_C_HASH | E_C_LIST | E_C_PRINT);
1424 
1425 		/* If hash set only because of the number option, discard it. */
1426 		if (F_ISSET(ecp, E_OPTNUM))
1427 			FL_CLR(ecp->iflags, E_C_HASH);
1428 
1429 		/*
1430 		 * If there was an explicit flag to display the new cursor line,
1431 		 * or autoprint is set and a change was made, display the line.
1432 		 * If any print flags were set use them, else default to print.
1433 		 */
1434 		LF_INIT(FL_ISSET(ecp->iflags, E_C_HASH | E_C_LIST | E_C_PRINT));
1435 		if (!LF_ISSET(E_C_HASH | E_C_LIST | E_C_PRINT | E_NOAUTO) &&
1436 		    !F_ISSET(sp, SC_EX_GLOBAL) &&
1437 		    O_ISSET(sp, O_AUTOPRINT) && F_ISSET(ecp, E_AUTOPRINT))
1438 			LF_INIT(E_C_PRINT);
1439 
1440 		if (LF_ISSET(E_C_HASH | E_C_LIST | E_C_PRINT)) {
1441 			cur.lno = sp->lno;
1442 			cur.cno = 0;
1443 			(void)ex_print(sp, ecp, &cur, &cur, flags);
1444 		}
1445 	}
1446 
1447 	/*
1448 	 * If the command had an associated "+cmd", it has to be executed
1449 	 * before we finish executing any more of this ex command.  For
1450 	 * example, consider a .exrc file that contains the following lines:
1451 	 *
1452 	 *	:set all
1453 	 *	:edit +25 file.c|s/abc/ABC/|1
1454 	 *	:3,5 print
1455 	 *
1456 	 * This can happen more than once -- the historic vi simply hung or
1457 	 * dropped core, of course.  Prepend the + command back into the
1458 	 * current command and continue.  We may have to add an additional
1459 	 * <literal next> character.  We know that it will fit because we
1460 	 * discarded at least one space and the + character.
1461 	 */
1462 	if (arg1_len != 0) {
1463 		/*
1464 		 * If the last character of the + command was a <literal next>
1465 		 * character, it would be treated differently because of the
1466 		 * append.  Quote it, if necessary.
1467 		 */
1468 		if (IS_ESCAPE(sp, ecp, arg1[arg1_len - 1])) {
1469 			*--ecp->save_cmd = CH_LITERAL;
1470 			++ecp->save_cmdlen;
1471 		}
1472 
1473 		ecp->save_cmd -= arg1_len;
1474 		ecp->save_cmdlen += arg1_len;
1475 		memcpy(ecp->save_cmd, arg1, arg1_len);
1476 
1477 		/*
1478 		 * Any commands executed from a +cmd are executed starting at
1479 		 * the first column of the last line of the file -- NOT the
1480 		 * first nonblank.)  The main file startup code doesn't know
1481 		 * that a +cmd was set, however, so it may have put us at the
1482 		 * top of the file.  (Note, this is safe because we must have
1483 		 * switched files to get here.)
1484 		 */
1485 		F_SET(ecp, E_MOVETOEND);
1486 	}
1487 
1488 	/* Update the current command. */
1489 	ecp->cp = ecp->save_cmd;
1490 	ecp->clen = ecp->save_cmdlen;
1491 
1492 	/*
1493 	 * !!!
1494 	 * If we've changed screens or underlying files, any pending global or
1495 	 * v command, or @ buffer that has associated addresses, has to be
1496 	 * discarded.  This is historic practice for globals, and necessary for
1497 	 * @ buffers that had associated addresses.
1498 	 *
1499 	 * Otherwise, if we've changed underlying files, it's not a problem,
1500 	 * we continue with the rest of the ex command(s), operating on the
1501 	 * new file.  However, if we switch screens (either by exiting or by
1502 	 * an explicit command), we have no way of knowing where to put output
1503 	 * messages, and, since we don't control screens here, we could screw
1504 	 * up the upper layers, (e.g. we could exit/reenter a screen multiple
1505 	 * times).  So, return and continue after we've got a new screen.
1506 	 */
1507 	if (F_ISSET(sp, SC_EXIT | SC_EXIT_FORCE | SC_FSWITCH | SC_SSWITCH)) {
1508 		at_found = gv_found = 0;
1509 		for (ecp = sp->gp->ecq.lh_first;
1510 		    ecp != NULL; ecp = ecp->q.le_next)
1511 			switch (ecp->agv_flags) {
1512 			case 0:
1513 			case AGV_AT_NORANGE:
1514 				break;
1515 			case AGV_AT:
1516 				if (!at_found) {
1517 					at_found = 1;
1518 					msgq(sp, M_ERR,
1519 		"090|@ with range running when the file/screen changed");
1520 				}
1521 				break;
1522 			case AGV_GLOBAL:
1523 			case AGV_V:
1524 				if (!gv_found) {
1525 					gv_found = 1;
1526 					msgq(sp, M_ERR,
1527 		"091|Global/v command running when the file/screen changed");
1528 				}
1529 				break;
1530 			default:
1531 				abort();
1532 			}
1533 		if (at_found || gv_found)
1534 			goto discard;
1535 		if (F_ISSET(sp, SC_EXIT | SC_EXIT_FORCE | SC_SSWITCH))
1536 			goto rsuccess;
1537 	}
1538 
1539 	goto loop;
1540 	/* NOTREACHED */
1541 
1542 err:	/*
1543 	 * On command failure, we discard keys and pending commands remaining,
1544 	 * as well as any keys that were mapped and waiting.  The save_cmdlen
1545 	 * test is not necessarily correct.  If we fail early enough we don't
1546 	 * know if the entire string was a single command or not.  Guess, as
1547 	 * it's useful to know if commands other than the current one are being
1548 	 * discarded.
1549 	 */
1550 	if (ecp->save_cmdlen == 0)
1551 		for (; ecp->clen; --ecp->clen) {
1552 			ch = *ecp->cp++;
1553 			if (IS_ESCAPE(sp, ecp, ch) && ecp->clen > 1) {
1554 				--ecp->clen;
1555 				++ecp->cp;
1556 			} else if (ch == '\n' || ch == '|') {
1557 				if (ecp->clen > 1)
1558 					ecp->save_cmdlen = 1;
1559 				break;
1560 			}
1561 		}
1562 	if (ecp->save_cmdlen != 0 || gp->ecq.lh_first != &gp->excmd) {
1563 discard:	msgq(sp, M_BERR,
1564 		    "092|Ex command failed: pending commands discarded");
1565 		ex_discard(sp);
1566 	}
1567 	if (v_event_flush(sp, CH_MAPPED))
1568 		msgq(sp, M_BERR,
1569 		    "093|Ex command failed: mapped keys discarded");
1570 
1571 rfail:	tmp = 1;
1572 	if (0)
1573 rsuccess:	tmp = 0;
1574 
1575 	/* Turn off any file name error information. */
1576 	gp->if_name = NULL;
1577 
1578 	/* Turn off the global bit. */
1579 	F_CLR(sp, SC_EX_GLOBAL);
1580 
1581 	return (tmp);
1582 }
1583 
1584 /*
1585  * ex_range --
1586  *	Get a line range for ex commands, or perform a vi ex address search.
1587  *
1588  * PUBLIC: int ex_range __P((SCR *, EXCMD *, int *));
1589  */
1590 int
1591 ex_range(sp, ecp, errp)
1592 	SCR *sp;
1593 	EXCMD *ecp;
1594 	int *errp;
1595 {
1596 	enum { ADDR_FOUND, ADDR_NEED, ADDR_NONE } addr;
1597 	GS *gp;
1598 	EX_PRIVATE *exp;
1599 	MARK m;
1600 	int isaddr;
1601 
1602 	*errp = 0;
1603 
1604 	/*
1605 	 * Parse comma or semi-colon delimited line specs.
1606 	 *
1607 	 * Semi-colon delimiters update the current address to be the last
1608 	 * address.  For example, the command
1609 	 *
1610 	 *	:3;/pattern/ecp->cp
1611 	 *
1612 	 * will search for pattern from line 3.  In addition, if ecp->cp
1613 	 * is not a valid command, the current line will be left at 3, not
1614 	 * at the original address.
1615 	 *
1616 	 * Extra addresses are discarded, starting with the first.
1617 	 *
1618 	 * !!!
1619 	 * If any addresses are missing, they default to the current line.
1620 	 * This was historically true for both leading and trailing comma
1621 	 * delimited addresses as well as for trailing semicolon delimited
1622 	 * addresses.  For consistency, we make it true for leading semicolon
1623 	 * addresses as well.
1624 	 */
1625 	gp = sp->gp;
1626 	exp = EXP(sp);
1627 	for (addr = ADDR_NONE, ecp->addrcnt = 0; ecp->clen > 0;)
1628 		switch (*ecp->cp) {
1629 		case '%':		/* Entire file. */
1630 			/* Vi ex address searches didn't permit % signs. */
1631 			if (F_ISSET(ecp, E_VISEARCH))
1632 				goto ret;
1633 
1634 			/* It's an error if the file is empty. */
1635 			if (sp->ep == NULL) {
1636 				ex_badaddr(sp, NULL, A_EMPTY, NUM_OK);
1637 				*errp = 1;
1638 				return (0);
1639 			}
1640 			/*
1641 			 * !!!
1642 			 * A percent character addresses all of the lines in
1643 			 * the file.  Historically, it couldn't be followed by
1644 			 * any other address.  We do it as a text substitution
1645 			 * for simplicity.  POSIX 1003.2 is expected to follow
1646 			 * this practice.
1647 			 *
1648 			 * If it's an empty file, the first line is 0, not 1.
1649 			 */
1650 			if (addr == ADDR_FOUND) {
1651 				ex_badaddr(sp, NULL, A_COMBO, NUM_OK);
1652 				*errp = 1;
1653 				return (0);
1654 			}
1655 			if (db_last(sp, &ecp->addr2.lno))
1656 				return (1);
1657 			ecp->addr1.lno = ecp->addr2.lno == 0 ? 0 : 1;
1658 			ecp->addr1.cno = ecp->addr2.cno = 0;
1659 			ecp->addrcnt = 2;
1660 			addr = ADDR_FOUND;
1661 			++ecp->cp;
1662 			--ecp->clen;
1663 			break;
1664 		case ',':               /* Comma delimiter. */
1665 			/* Vi ex address searches didn't permit commas. */
1666 			if (F_ISSET(ecp, E_VISEARCH))
1667 				goto ret;
1668 			/* FALLTHROUGH */
1669 		case ';':               /* Semi-colon delimiter. */
1670 			if (sp->ep == NULL) {
1671 				ex_badaddr(sp, NULL, A_EMPTY, NUM_OK);
1672 				*errp = 1;
1673 				return (0);
1674 			}
1675 			if (addr != ADDR_FOUND)
1676 				switch (ecp->addrcnt) {
1677 				case 0:
1678 					ecp->addr1.lno = sp->lno;
1679 					ecp->addr1.cno = sp->cno;
1680 					ecp->addrcnt = 1;
1681 					break;
1682 				case 2:
1683 					ecp->addr1 = ecp->addr2;
1684 					/* FALLTHROUGH */
1685 				case 1:
1686 					ecp->addr2.lno = sp->lno;
1687 					ecp->addr2.cno = sp->cno;
1688 					ecp->addrcnt = 2;
1689 					break;
1690 				}
1691 			if (*ecp->cp == ';')
1692 				switch (ecp->addrcnt) {
1693 				case 0:
1694 					abort();
1695 					/* NOTREACHED */
1696 				case 1:
1697 					sp->lno = ecp->addr1.lno;
1698 					sp->cno = ecp->addr1.cno;
1699 					break;
1700 				case 2:
1701 					sp->lno = ecp->addr2.lno;
1702 					sp->cno = ecp->addr2.cno;
1703 					break;
1704 				}
1705 			addr = ADDR_NEED;
1706 			/* FALLTHROUGH */
1707 		case ' ':		/* Whitespace. */
1708 		case '\t':		/* Whitespace. */
1709 			++ecp->cp;
1710 			--ecp->clen;
1711 			break;
1712 		default:
1713 			/* Get a line specification. */
1714 			if (ex_line(sp, ecp, &m, &isaddr, errp))
1715 				return (1);
1716 			if (*errp)
1717 				return (0);
1718 			if (!isaddr)
1719 				goto ret;
1720 			if (addr == ADDR_FOUND) {
1721 				ex_badaddr(sp, NULL, A_COMBO, NUM_OK);
1722 				*errp = 1;
1723 				return (0);
1724 			}
1725 			switch (ecp->addrcnt) {
1726 			case 0:
1727 				ecp->addr1 = m;
1728 				ecp->addrcnt = 1;
1729 				break;
1730 			case 1:
1731 				ecp->addr2 = m;
1732 				ecp->addrcnt = 2;
1733 				break;
1734 			case 2:
1735 				ecp->addr1 = ecp->addr2;
1736 				ecp->addr2 = m;
1737 				break;
1738 			}
1739 			addr = ADDR_FOUND;
1740 			break;
1741 		}
1742 
1743 	/*
1744 	 * !!!
1745 	 * Vi ex address searches are indifferent to order or trailing
1746 	 * semi-colons.
1747 	 */
1748 ret:	if (F_ISSET(ecp, E_VISEARCH))
1749 		return (0);
1750 
1751 	if (addr == ADDR_NEED)
1752 		switch (ecp->addrcnt) {
1753 		case 0:
1754 			ecp->addr1.lno = sp->lno;
1755 			ecp->addr1.cno = sp->cno;
1756 			ecp->addrcnt = 1;
1757 			break;
1758 		case 2:
1759 			ecp->addr1 = ecp->addr2;
1760 			/* FALLTHROUGH */
1761 		case 1:
1762 			ecp->addr2.lno = sp->lno;
1763 			ecp->addr2.cno = sp->cno;
1764 			ecp->addrcnt = 2;
1765 			break;
1766 		}
1767 
1768 	if (ecp->addrcnt == 2 && ecp->addr2.lno < ecp->addr1.lno) {
1769 		msgq(sp, M_ERR,
1770 		    "094|The second address is smaller than the first");
1771 		*errp = 1;
1772 	}
1773 	return (0);
1774 }
1775 
1776 /*
1777  * ex_line --
1778  *	Get a single line address specifier.
1779  *
1780  * The way the "previous context" mark worked was that any "non-relative"
1781  * motion set it.  While ex/vi wasn't totally consistent about this, ANY
1782  * numeric address, search pattern, '$', or mark reference in an address
1783  * was considered non-relative, and set the value.  Which should explain
1784  * why we're hacking marks down here.  The problem was that the mark was
1785  * only set if the command was called, i.e. we have to set a flag and test
1786  * it later.
1787  *
1788  * XXX
1789  * This is probably still not exactly historic practice, although I think
1790  * it's fairly close.
1791  */
1792 static int
1793 ex_line(sp, ecp, mp, isaddrp, errp)
1794 	SCR *sp;
1795 	EXCMD *ecp;
1796 	MARK *mp;
1797 	int *isaddrp, *errp;
1798 {
1799 	enum nresult nret;
1800 	EX_PRIVATE *exp;
1801 	GS *gp;
1802 	long total, val;
1803 	int isneg;
1804 	int (*sf) __P((SCR *, MARK *, MARK *, char *, size_t, char **, u_int));
1805 	char *endp;
1806 
1807 	gp = sp->gp;
1808 	exp = EXP(sp);
1809 
1810 	*isaddrp = *errp = 0;
1811 	F_CLR(ecp, E_DELTA);
1812 
1813 	/* No addresses permitted until a file has been read in. */
1814 	if (sp->ep == NULL && strchr("$0123456789'\\/?.+-^", *ecp->cp)) {
1815 		ex_badaddr(sp, NULL, A_EMPTY, NUM_OK);
1816 		*errp = 1;
1817 		return (0);
1818 	}
1819 
1820 	switch (*ecp->cp) {
1821 	case '$':				/* Last line in the file. */
1822 		*isaddrp = 1;
1823 		F_SET(ecp, E_ABSMARK);
1824 
1825 		mp->cno = 0;
1826 		if (db_last(sp, &mp->lno))
1827 			return (1);
1828 		++ecp->cp;
1829 		--ecp->clen;
1830 		break;				/* Absolute line number. */
1831 	case '0': case '1': case '2': case '3': case '4':
1832 	case '5': case '6': case '7': case '8': case '9':
1833 		*isaddrp = 1;
1834 		F_SET(ecp, E_ABSMARK);
1835 
1836 		if ((nret = nget_slong(&val, ecp->cp, &endp, 10)) != NUM_OK) {
1837 			ex_badaddr(sp, NULL, A_NOTSET, nret);
1838 			*errp = 1;
1839 			return (0);
1840 		}
1841 		if (!NPFITS(MAX_REC_NUMBER, 0, val)) {
1842 			ex_badaddr(sp, NULL, A_NOTSET, NUM_OVER);
1843 			*errp = 1;
1844 			return (0);
1845 		}
1846 		mp->lno = val;
1847 		mp->cno = 0;
1848 		ecp->clen -= (endp - ecp->cp);
1849 		ecp->cp = endp;
1850 		break;
1851 	case '\'':				/* Use a mark. */
1852 		*isaddrp = 1;
1853 		F_SET(ecp, E_ABSMARK);
1854 
1855 		if (ecp->clen == 1) {
1856 			msgq(sp, M_ERR, "095|No mark name supplied");
1857 			*errp = 1;
1858 			return (0);
1859 		}
1860 		if (mark_get(sp, ecp->cp[1], mp, M_ERR)) {
1861 			*errp = 1;
1862 			return (0);
1863 		}
1864 		ecp->cp += 2;
1865 		ecp->clen -= 2;
1866 		break;
1867 	case '\\':				/* Search: forward/backward. */
1868 		/*
1869 		 * !!!
1870 		 * I can't find any difference between // and \/ or between
1871 		 * ?? and \?.  Mark Horton doesn't remember there being any
1872 		 * difference.  C'est la vie.
1873 		 */
1874 		if (ecp->clen < 2 ||
1875 		    ecp->cp[1] != '/' && ecp->cp[1] != '?') {
1876 			msgq(sp, M_ERR, "096|\\ not followed by / or ?");
1877 			*errp = 1;
1878 			return (0);
1879 		}
1880 		++ecp->cp;
1881 		--ecp->clen;
1882 		sf = ecp->cp[0] == '/' ? f_search : b_search;
1883 		goto search;
1884 	case '/':				/* Search forward. */
1885 		sf = f_search;
1886 		goto search;
1887 	case '?':				/* Search backward. */
1888 		sf = b_search;
1889 
1890 search:		mp->lno = sp->lno;
1891 		mp->cno = sp->cno;
1892 		if (sf(sp, mp, mp, ecp->cp, ecp->clen, &endp,
1893 		    SEARCH_MSG | SEARCH_PARSE | SEARCH_SET |
1894 		    (F_ISSET(ecp, E_SEARCH_WMSG) ? SEARCH_WMSG : 0))) {
1895 			*errp = 1;
1896 			return (0);
1897 		}
1898 
1899 		/* Fix up the command pointers. */
1900 		ecp->clen -= (endp - ecp->cp);
1901 		ecp->cp = endp;
1902 
1903 		*isaddrp = 1;
1904 		F_SET(ecp, E_ABSMARK);
1905 		break;
1906 	case '.':				/* Current position. */
1907 		*isaddrp = 1;
1908 		mp->cno = sp->cno;
1909 
1910 		/* If an empty file, then '.' is 0, not 1. */
1911 		if (sp->lno == 1) {
1912 			if (db_last(sp, &mp->lno))
1913 				return (1);
1914 			if (mp->lno != 0)
1915 				mp->lno = 1;
1916 		} else
1917 			mp->lno = sp->lno;
1918 
1919 		/*
1920 		 * !!!
1921 		 * Historically, .<number> was the same as .+<number>, i.e.
1922 		 * the '+' could be omitted.  (This feature is found in ed
1923 		 * as well.)
1924 		 */
1925 		if (ecp->clen > 1 && isdigit(ecp->cp[1]))
1926 			*ecp->cp = '+';
1927 		else {
1928 			++ecp->cp;
1929 			--ecp->clen;
1930 		}
1931 		break;
1932 	}
1933 
1934 	/* Skip trailing <blank>s. */
1935 	for (; ecp->clen > 0 &&
1936 	    isblank(ecp->cp[0]); ++ecp->cp, --ecp->clen);
1937 
1938 	/*
1939 	 * Evaluate any offset.  If no address yet found, the offset
1940 	 * is relative to ".".
1941 	 */
1942 	total = 0;
1943 	if (ecp->clen != 0 && (isdigit(ecp->cp[0]) ||
1944 	    ecp->cp[0] == '+' || ecp->cp[0] == '-' ||
1945 	    ecp->cp[0] == '^')) {
1946 		if (!*isaddrp) {
1947 			*isaddrp = 1;
1948 			mp->lno = sp->lno;
1949 			mp->cno = sp->cno;
1950 		}
1951 		/*
1952 		 * Evaluate an offset, defined as:
1953 		 *
1954 		 *		[+-^<blank>]*[<blank>]*[0-9]*
1955 		 *
1956 		 * The rough translation is any number of signs, optionally
1957 		 * followed by numbers, or a number by itself, all <blank>
1958 		 * separated.
1959 		 *
1960 		 * !!!
1961 		 * All address offsets were additive, e.g. "2 2 3p" was the
1962 		 * same as "7p", or, "/ZZZ/ 2" was the same as "/ZZZ/+2".
1963 		 * Note, however, "2 /ZZZ/" was an error.  It was also legal
1964 		 * to insert signs without numbers, so "3 - 2" was legal, and
1965 		 * equal to 4.
1966 		 *
1967 		 * !!!
1968 		 * Offsets were historically permitted for any line address,
1969 		 * e.g. the command "1,2 copy 2 2 2 2" copied lines 1,2 after
1970 		 * line 8.
1971 		 *
1972 		 * !!!
1973 		 * Offsets were historically permitted for search commands,
1974 		 * and handled as addresses: "/pattern/2 2 2" was legal, and
1975 		 * referenced the 6th line after pattern.
1976 		 */
1977 		F_SET(ecp, E_DELTA);
1978 		for (;;) {
1979 			for (; ecp->clen > 0 && isblank(ecp->cp[0]);
1980 			    ++ecp->cp, --ecp->clen);
1981 			if (ecp->clen == 0 || !isdigit(ecp->cp[0]) &&
1982 			    ecp->cp[0] != '+' && ecp->cp[0] != '-' &&
1983 			    ecp->cp[0] != '^')
1984 				break;
1985 			if (!isdigit(ecp->cp[0]) &&
1986 			    !isdigit(ecp->cp[1])) {
1987 				total += ecp->cp[0] == '+' ? 1 : -1;
1988 				--ecp->clen;
1989 				++ecp->cp;
1990 			} else {
1991 				if (ecp->cp[0] == '-' ||
1992 				    ecp->cp[0] == '^') {
1993 					++ecp->cp;
1994 					--ecp->clen;
1995 					isneg = 1;
1996 				} else
1997 					isneg = 0;
1998 
1999 				/* Get a signed long, add it to the total. */
2000 				if ((nret = nget_slong(&val,
2001 				    ecp->cp, &endp, 10)) != NUM_OK ||
2002 				    (nret = NADD_SLONG(sp,
2003 				    total, val)) != NUM_OK) {
2004 					ex_badaddr(sp, NULL, A_NOTSET, nret);
2005 					*errp = 1;
2006 					return (0);
2007 				}
2008 				total += isneg ? -val : val;
2009 				ecp->clen -= (endp - ecp->cp);
2010 				ecp->cp = endp;
2011 			}
2012 		}
2013 	}
2014 
2015 	/*
2016 	 * Any value less than 0 is an error.  Make sure that the new value
2017 	 * will fit into a recno_t.
2018 	 */
2019 	if (*isaddrp && total != 0) {
2020 		if (total < 0) {
2021 			if (-total > mp->lno) {
2022 				msgq(sp, M_ERR,
2023 			    "097|Reference to a line number less than 0");
2024 				*errp = 1;
2025 				return (0);
2026 			}
2027 		} else
2028 			if (!NPFITS(MAX_REC_NUMBER, mp->lno, total)) {
2029 				ex_badaddr(sp, NULL, A_NOTSET, NUM_OVER);
2030 				*errp = 1;
2031 				return (0);
2032 			}
2033 		mp->lno += total;
2034 	}
2035 	return (0);
2036 }
2037 
2038 
2039 /*
2040  * ex_load --
2041  *	Load up the next command, which may be an @ buffer or global command.
2042  */
2043 static int
2044 ex_load(sp)
2045 	SCR *sp;
2046 {
2047 	GS *gp;
2048 	EXCMD *ecp;
2049 	RANGE *rp;
2050 
2051 	F_CLR(sp, SC_EX_GLOBAL);
2052 
2053 	/*
2054 	 * Lose any exhausted commands.  We know that the first command
2055 	 * can't be an AGV command, which makes things a bit easier.
2056 	 */
2057 	for (gp = sp->gp;;) {
2058 		/*
2059 		 * If we're back to the original structure, leave it around,
2060 		 * but discard any allocated source name, we've returned to
2061 		 * the beginning of the command stack.
2062 		 */
2063 		if ((ecp = gp->ecq.lh_first) == &gp->excmd) {
2064 			if (F_ISSET(ecp, E_NAMEDISCARD)) {
2065 				free(ecp->if_name);
2066 				ecp->if_name = NULL;
2067 			}
2068 			return (0);
2069 		}
2070 
2071 		/*
2072 		 * ecp->clen will be 0 for the first discarded command, but
2073 		 * may not be 0 for subsequent ones, e.g. if the original
2074 		 * command was ":g/xx/@a|s/b/c/", then when we discard the
2075 		 * command pushed on the stack by the @a, we have to resume
2076 		 * the global command which included the substitute command.
2077 		 */
2078 		if (ecp->clen != 0)
2079 			return (0);
2080 
2081 		/*
2082 		 * If it's an @, global or v command, we may need to continue
2083 		 * the command on a different line.
2084 		 */
2085 		if (FL_ISSET(ecp->agv_flags, AGV_ALL)) {
2086 			/* Discard any exhausted ranges. */
2087 			while ((rp = ecp->rq.cqh_first) != (void *)&ecp->rq)
2088 				if (rp->start > rp->stop) {
2089 					CIRCLEQ_REMOVE(&ecp->rq, rp, q);
2090 					free(rp);
2091 				} else
2092 					break;
2093 
2094 			/* If there's another range, continue with it. */
2095 			if (rp != (void *)&ecp->rq)
2096 				break;
2097 
2098 			/* If it's a global/v command, fix up the last line. */
2099 			if (FL_ISSET(ecp->agv_flags,
2100 			    AGV_GLOBAL | AGV_V) && ecp->range_lno != OOBLNO)
2101 				if (db_exist(sp, ecp->range_lno))
2102 					sp->lno = ecp->range_lno;
2103 				else {
2104 					if (db_last(sp, &sp->lno))
2105 						return (1);
2106 					if (sp->lno == 0)
2107 						sp->lno = 1;
2108 				}
2109 			free(ecp->o_cp);
2110 		}
2111 
2112 		/* Discard the EXCMD. */
2113 		LIST_REMOVE(ecp, q);
2114 		free(ecp);
2115 	}
2116 
2117 	/*
2118 	 * We only get here if it's an active @, global or v command.  Set
2119 	 * the current line number, and get a new copy of the command for
2120 	 * the parser.  Note, the original pointer almost certainly moved,
2121 	 * so we have play games.
2122 	 */
2123 	ecp->cp = ecp->o_cp;
2124 	memcpy(ecp->cp, ecp->cp + ecp->o_clen, ecp->o_clen);
2125 	ecp->clen = ecp->o_clen;
2126 	ecp->range_lno = sp->lno = rp->start++;
2127 
2128 	if (FL_ISSET(ecp->agv_flags, AGV_GLOBAL | AGV_V))
2129 		F_SET(sp, SC_EX_GLOBAL);
2130 	return (0);
2131 }
2132 
2133 /*
2134  * ex_discard --
2135  *	Discard any pending ex commands.
2136  */
2137 static int
2138 ex_discard(sp)
2139 	SCR *sp;
2140 {
2141 	GS *gp;
2142 	EXCMD *ecp;
2143 	RANGE *rp;
2144 
2145 	/*
2146 	 * We know the first command can't be an AGV command, so we don't
2147 	 * process it specially.  We do, however, nail the command itself.
2148 	 */
2149 	for (gp = sp->gp; (ecp = gp->ecq.lh_first) != &gp->excmd;) {
2150 		if (FL_ISSET(ecp->agv_flags, AGV_ALL)) {
2151 			while ((rp = ecp->rq.cqh_first) != (void *)&ecp->rq) {
2152 				CIRCLEQ_REMOVE(&ecp->rq, rp, q);
2153 				free(rp);
2154 			}
2155 			free(ecp->o_cp);
2156 		}
2157 		LIST_REMOVE(ecp, q);
2158 		free(ecp);
2159 	}
2160 	gp->ecq.lh_first->clen = 0;
2161 	return (0);
2162 }
2163 
2164 /*
2165  * ex_unknown --
2166  *	Display an unknown command name.
2167  */
2168 static void
2169 ex_unknown(sp, cmd, len)
2170 	SCR *sp;
2171 	char *cmd;
2172 	size_t len;
2173 {
2174 	size_t blen;
2175 	char *bp;
2176 
2177 	GET_SPACE_GOTO(sp, bp, blen, len + 1);
2178 	bp[len] = '\0';
2179 	memcpy(bp, cmd, len);
2180 	msgq_str(sp, M_ERR, bp, "098|The %s command is unknown");
2181 	FREE_SPACE(sp, bp, blen);
2182 
2183 alloc_err:
2184 	return;
2185 }
2186 
2187 /*
2188  * ex_is_abbrev -
2189  *	The vi text input routine needs to know if ex thinks this is an
2190  *	[un]abbreviate command, so it can turn off abbreviations.  See
2191  *	the usual ranting in the vi/v_txt_ev.c:txt_abbrev() routine.
2192  *
2193  * PUBLIC: int ex_is_abbrev __P((char *, size_t));
2194  */
2195 int
2196 ex_is_abbrev(name, len)
2197 	char *name;
2198 	size_t len;
2199 {
2200 	EXCMDLIST const *cp;
2201 
2202 	return ((cp = ex_comm_search(name, len)) != NULL &&
2203 	    (cp == &cmds[C_ABBR] || cp == &cmds[C_UNABBREVIATE]));
2204 }
2205 
2206 /*
2207  * ex_is_unmap -
2208  *	The vi text input routine needs to know if ex thinks this is an
2209  *	unmap command, so it can turn off input mapping.  See the usual
2210  *	ranting in the vi/v_txt_ev.c:txt_unmap() routine.
2211  *
2212  * PUBLIC: int ex_is_unmap __P((char *, size_t));
2213  */
2214 int
2215 ex_is_unmap(name, len)
2216 	char *name;
2217 	size_t len;
2218 {
2219 	EXCMDLIST const *cp;
2220 
2221 	/*
2222 	 * The command the vi input routines are really interested in
2223 	 * is "unmap!", not just unmap.
2224 	 */
2225 	if (name[len - 1] != '!')
2226 		return (0);
2227 	--len;
2228 	return ((cp = ex_comm_search(name, len)) != NULL &&
2229 	    cp == &cmds[C_UNMAP]);
2230 }
2231 
2232 /*
2233  * ex_comm_search --
2234  *	Search for a command name.
2235  */
2236 static EXCMDLIST const *
2237 ex_comm_search(name, len)
2238 	char *name;
2239 	size_t len;
2240 {
2241 	EXCMDLIST const *cp;
2242 
2243 	for (cp = cmds; cp->name != NULL; ++cp) {
2244 		if (cp->name[0] > name[0])
2245 			return (NULL);
2246 		if (cp->name[0] != name[0])
2247 			continue;
2248 		if (!memcmp(name, cp->name, len))
2249 			return (cp);
2250 	}
2251 	return (NULL);
2252 }
2253 
2254 /*
2255  * ex_badaddr --
2256  *	Display a bad address message.
2257  *
2258  * PUBLIC: void ex_badaddr
2259  * PUBLIC:    __P((SCR *, EXCMDLIST const *, enum badaddr, enum nresult));
2260  */
2261 void
2262 ex_badaddr(sp, cp, ba, nret)
2263 	SCR *sp;
2264 	EXCMDLIST const *cp;
2265 	enum badaddr ba;
2266 	enum nresult nret;
2267 {
2268 	recno_t lno;
2269 
2270 	switch (nret) {
2271 	case NUM_OK:
2272 		break;
2273 	case NUM_ERR:
2274 		msgq(sp, M_SYSERR, NULL);
2275 		return;
2276 	case NUM_OVER:
2277 		msgq(sp, M_ERR, "099|Address value overflow");
2278 		return;
2279 	case NUM_UNDER:
2280 		msgq(sp, M_ERR, "100|Address value underflow");
2281 		return;
2282 	}
2283 
2284 	/*
2285 	 * When encountering an address error, tell the user if there's no
2286 	 * underlying file, that's the real problem.
2287 	 */
2288 	if (sp->ep == NULL) {
2289 		ex_emsg(sp, cp->name, EXM_NOFILEYET);
2290 		return;
2291 	}
2292 
2293 	switch (ba) {
2294 	case A_COMBO:
2295 		msgq(sp, M_ERR, "101|Illegal address combination");
2296 		break;
2297 	case A_EOF:
2298 		if (db_last(sp, &lno))
2299 			return;
2300 		if (lno != 0) {
2301 			msgq(sp, M_ERR,
2302 			    "102|Illegal address: only %lu lines in the file",
2303 			    lno);
2304 			break;
2305 		}
2306 		/* FALLTHROUGH */
2307 	case A_EMPTY:
2308 		msgq(sp, M_ERR, "103|Illegal address: the file is empty");
2309 		break;
2310 	case A_NOTSET:
2311 		abort();
2312 		/* NOTREACHED */
2313 	case A_ZERO:
2314 		msgq(sp, M_ERR,
2315 		    "104|The %s command doesn't permit an address of 0",
2316 		    cp->name);
2317 		break;
2318 	}
2319 	return;
2320 }
2321 
2322 #if defined(DEBUG) && defined(COMLOG)
2323 /*
2324  * ex_comlog --
2325  *	Log ex commands.
2326  */
2327 static void
2328 ex_comlog(sp, ecp)
2329 	SCR *sp;
2330 	EXCMD *ecp;
2331 {
2332 	TRACE(sp, "ecmd: %s", ecp->cmd->name);
2333 	if (ecp->addrcnt > 0) {
2334 		TRACE(sp, " a1 %d", ecp->addr1.lno);
2335 		if (ecp->addrcnt > 1)
2336 			TRACE(sp, " a2: %d", ecp->addr2.lno);
2337 	}
2338 	if (ecp->lineno)
2339 		TRACE(sp, " line %d", ecp->lineno);
2340 	if (ecp->flags)
2341 		TRACE(sp, " flags 0x%x", ecp->flags);
2342 	if (F_ISSET(&exc, E_BUFFER))
2343 		TRACE(sp, " buffer %c", ecp->buffer);
2344 	if (ecp->argc)
2345 		for (cnt = 0; cnt < ecp->argc; ++cnt)
2346 			TRACE(sp, " arg %d: {%s}", cnt, ecp->argv[cnt]->bp);
2347 	TRACE(sp, "\n");
2348 }
2349 #endif
2350