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