head	1.17;
access;
symbols
	perseant-exfatfs-base-20250801:1.17
	perseant-exfatfs-base-20240630:1.17
	perseant-exfatfs:1.17.0.36
	perseant-exfatfs-base:1.17
	cjep_sun2x:1.17.0.34
	cjep_sun2x-base:1.17
	cjep_staticlib_x-base1:1.17
	cjep_staticlib_x:1.17.0.32
	cjep_staticlib_x-base:1.17
	phil-wifi-20200421:1.17
	phil-wifi-20200411:1.17
	phil-wifi-20200406:1.17
	pgoyette-compat-merge-20190127:1.17
	pgoyette-compat-20190127:1.17
	pgoyette-compat-20190118:1.17
	pgoyette-compat-1226:1.17
	pgoyette-compat-1126:1.17
	pgoyette-compat-1020:1.17
	pgoyette-compat-0930:1.17
	pgoyette-compat-0906:1.17
	pgoyette-compat-0728:1.17
	pgoyette-compat-0625:1.17
	pgoyette-compat-0521:1.17
	pgoyette-compat-0502:1.17
	pgoyette-compat-0422:1.17
	pgoyette-compat-0415:1.17
	pgoyette-compat-0407:1.17
	pgoyette-compat-0330:1.17
	pgoyette-compat-0322:1.17
	pgoyette-compat-0315:1.17
	pgoyette-compat:1.17.0.30
	pgoyette-compat-base:1.17
	perseant-stdc-iso10646:1.17.0.28
	perseant-stdc-iso10646-base:1.17
	prg-localcount2-base3:1.17
	prg-localcount2-base2:1.17
	prg-localcount2-base1:1.17
	prg-localcount2:1.17.0.26
	prg-localcount2-base:1.17
	pgoyette-localcount-20170426:1.17
	bouyer-socketcan-base1:1.17
	pgoyette-localcount-20170320:1.17
	bouyer-socketcan:1.17.0.24
	bouyer-socketcan-base:1.17
	pgoyette-localcount-20170107:1.17
	pgoyette-localcount-20161104:1.17
	localcount-20160914:1.17
	pgoyette-localcount-20160806:1.17
	pgoyette-localcount-20160726:1.17
	pgoyette-localcount:1.17.0.22
	pgoyette-localcount-base:1.17
	netbsd-5-2-3-RELEASE:1.17
	netbsd-5-1-5-RELEASE:1.17
	yamt-pagecache-base9:1.17
	yamt-pagecache-tag8:1.17
	tls-earlyentropy:1.17.0.18
	tls-earlyentropy-base:1.17
	riastradh-xf86-video-intel-2-7-1-pre-2-21-15:1.17
	riastradh-drm2-base3:1.17
	netbsd-5-2-2-RELEASE:1.17
	netbsd-5-1-4-RELEASE:1.17
	netbsd-5-2-1-RELEASE:1.17
	netbsd-5-1-3-RELEASE:1.17
	agc-symver:1.17.0.20
	agc-symver-base:1.17
	tls-maxphys-base:1.17
	yamt-pagecache-base8:1.17
	netbsd-5-2:1.17.0.16
	yamt-pagecache-base7:1.17
	netbsd-5-2-RELEASE:1.17
	netbsd-5-2-RC1:1.17
	yamt-pagecache-base6:1.17
	yamt-pagecache-base5:1.17
	yamt-pagecache-base4:1.17
	netbsd-5-1-2-RELEASE:1.17
	netbsd-5-1-1-RELEASE:1.17
	yamt-pagecache-base3:1.17
	yamt-pagecache-base2:1.17
	yamt-pagecache:1.17.0.14
	yamt-pagecache-base:1.17
	bouyer-quota2-nbase:1.17
	bouyer-quota2:1.17.0.12
	bouyer-quota2-base:1.17
	matt-nb5-pq3:1.17.0.10
	matt-nb5-pq3-base:1.17
	netbsd-5-1:1.17.0.8
	netbsd-5-1-RELEASE:1.17
	netbsd-5-1-RC4:1.17
	netbsd-5-1-RC3:1.17
	netbsd-5-1-RC2:1.17
	netbsd-5-1-RC1:1.17
	netbsd-5-0-2-RELEASE:1.17
	netbsd-5-0-1-RELEASE:1.17
	jym-xensuspend-nbase:1.17
	netbsd-5-0:1.17.0.6
	netbsd-5-0-RELEASE:1.17
	netbsd-5-0-RC4:1.17
	netbsd-5-0-RC3:1.17
	netbsd-5-0-RC2:1.17
	jym-xensuspend:1.17.0.4
	jym-xensuspend-base:1.17
	netbsd-5-0-RC1:1.17
	netbsd-5:1.17.0.2
	netbsd-5-base:1.17
	matt-mips64-base2:1.16
	matt-mips64:1.16.0.26
	mjf-devfs2:1.16.0.24
	mjf-devfs2-base:1.16
	netbsd-4-0-1-RELEASE:1.16
	wrstuden-revivesa-base-3:1.16
	wrstuden-revivesa-base-2:1.16
	wrstuden-fixsa-newbase:1.16
	wrstuden-revivesa-base-1:1.16
	yamt-pf42-base4:1.16
	yamt-pf42-base3:1.16
	hpcarm-cleanup-nbase:1.16
	yamt-pf42-baseX:1.16
	yamt-pf42-base2:1.16
	wrstuden-revivesa:1.16.0.22
	wrstuden-revivesa-base:1.16
	yamt-pf42:1.16.0.20
	yamt-pf42-base:1.16
	keiichi-mipv6-nbase:1.16
	keiichi-mipv6:1.16.0.18
	keiichi-mipv6-base:1.16
	matt-armv6-nbase:1.16
	matt-armv6-prevmlocking:1.16
	wrstuden-fixsa-base-1:1.16
	netbsd-4-0:1.16.0.16
	netbsd-4-0-RELEASE:1.16
	cube-autoconf:1.16.0.14
	cube-autoconf-base:1.16
	netbsd-4-0-RC5:1.16
	netbsd-4-0-RC4:1.16
	netbsd-4-0-RC3:1.16
	netbsd-4-0-RC2:1.16
	netbsd-4-0-RC1:1.16
	matt-armv6:1.16.0.12
	matt-armv6-base:1.16
	matt-mips64-base:1.16
	hpcarm-cleanup:1.16.0.10
	hpcarm-cleanup-base:1.16
	netbsd-3-1-1-RELEASE:1.14.2.1
	netbsd-3-0-3-RELEASE:1.14.2.1
	wrstuden-fixsa:1.16.0.8
	wrstuden-fixsa-base:1.16
	abandoned-netbsd-4-base:1.16
	abandoned-netbsd-4:1.16.0.4
	netbsd-3-1:1.14.2.1.0.4
	netbsd-3-1-RELEASE:1.14.2.1
	netbsd-3-0-2-RELEASE:1.14.2.1
	netbsd-3-1-RC4:1.14.2.1
	netbsd-3-1-RC3:1.14.2.1
	netbsd-3-1-RC2:1.14.2.1
	netbsd-3-1-RC1:1.14.2.1
	netbsd-4:1.16.0.6
	netbsd-4-base:1.16
	chap-midi-nbase:1.16
	netbsd-3-0-1-RELEASE:1.14.2.1
	chap-midi:1.16.0.2
	chap-midi-base:1.16
	netbsd-3-0:1.14.2.1.0.2
	netbsd-3-0-RELEASE:1.14.2.1
	netbsd-3-0-RC6:1.14.2.1
	netbsd-3-0-RC5:1.14.2.1
	netbsd-3-0-RC4:1.14.2.1
	netbsd-3-0-RC3:1.14.2.1
	netbsd-3-0-RC2:1.14.2.1
	netbsd-3-0-RC1:1.14.2.1
	netbsd-2-0-3-RELEASE:1.12.4.2
	netbsd-2-1:1.12.6.1.0.2
	netbsd-2-1-RELEASE:1.12.6.1
	netbsd-2-1-RC6:1.12.6.1
	netbsd-2-1-RC5:1.12.6.1
	netbsd-2-1-RC4:1.12.6.1
	netbsd-2-1-RC3:1.12.6.1
	netbsd-2-1-RC2:1.12.6.1
	netbsd-2-1-RC1:1.12.6.1
	netbsd-2-0-2-RELEASE:1.12.4.2
	netbsd-3:1.14.0.2
	netbsd-3-base:1.14
	netbsd-2-0-1-RELEASE:1.12
	netbsd-2:1.12.0.6
	netbsd-2-base:1.12
	netbsd-2-0-RELEASE:1.12
	netbsd-2-0-RC5:1.12
	netbsd-2-0-RC4:1.12
	netbsd-2-0-RC3:1.12
	netbsd-2-0-RC2:1.12
	netbsd-2-0-RC1:1.12
	netbsd-2-0:1.12.0.4
	netbsd-2-0-base:1.12
	netbsd-1-6-PATCH002-RELEASE:1.12
	netbsd-1-6-PATCH002:1.12
	netbsd-1-6-PATCH002-RC4:1.12
	netbsd-1-6-PATCH002-RC3:1.12
	netbsd-1-6-PATCH002-RC2:1.12
	netbsd-1-6-PATCH002-RC1:1.12
	netbsd-1-6-PATCH001:1.12
	netbsd-1-6-PATCH001-RELEASE:1.12
	netbsd-1-6-PATCH001-RC3:1.12
	netbsd-1-6-PATCH001-RC2:1.12
	netbsd-1-6-PATCH001-RC1:1.12
	fvdl_fs64_base:1.12
	netbsd-1-6-RELEASE:1.12
	netbsd-1-6-RC3:1.12
	netbsd-1-6-RC2:1.12
	netbsd-1-6-RC1:1.12
	netbsd-1-6:1.12.0.2
	netbsd-1-6-base:1.12
	netbsd-1-5-PATCH003:1.8.10.1
	netbsd-1-5-PATCH002:1.8.10.1
	netbsd-1-5-PATCH001:1.8.10.1
	nvi_1_79:1.1.1.6
	netbsd-1-5-RELEASE:1.8.10.1
	netbsd-1-5-BETA2:1.8.10.1
	netbsd-1-5-BETA:1.8.10.1
	netbsd-1-4-PATCH003:1.8
	netbsd-1-5-ALPHA2:1.8
	netbsd-1-5:1.8.0.10
	netbsd-1-5-base:1.8
	minoura-xpg4dl-base:1.8
	minoura-xpg4dl:1.8.0.8
	netbsd-1-4-PATCH002:1.8
	wrstuden-devbsize-19991221:1.8
	wrstuden-devbsize:1.8.0.6
	wrstuden-devbsize-base:1.8
	comdex-fall-1999:1.8.0.4
	comdex-fall-1999-base:1.8
	netbsd-1-4-PATCH001:1.8
	netbsd-1-4-RELEASE:1.8
	netbsd-1-4:1.8.0.2
	netbsd-1-4-base:1.8
	netbsd-1-3-PATCH003:1.7
	netbsd-1-3-PATCH003-CANDIDATE2:1.7
	netbsd-1-3-PATCH003-CANDIDATE1:1.7
	netbsd-1-3-PATCH003-CANDIDATE0:1.7
	netbsd-1-3-PATCH002:1.7
	netbsd-1-3-PATCH001:1.7
	netbsd-1-3-RELEASE:1.7
	netbsd-1-3-BETA:1.7
	netbsd-1-3:1.7.0.2
	netbsd-1-3-base:1.7
	netbsd-1-2-PATCH001:1.6.4.1
	netbsd-1-2-RELEASE:1.6.4.1
	netbsd-1-2-BETA:1.6.4.1
	netbsd-1-2:1.6.0.4
	netbsd-1-2-base:1.6
	nvi_1_66:1.1.1.5
	BOSTIC:1.1.1
	netbsd-1-1-PATCH001:1.5
	netbsd-1-1-RELEASE:1.5
	netbsd-1-1:1.5.0.4
	netbsd-1-1-base:1.5
	netbsd-1-0-PATCH06:1.5
	netbsd-1-0-PATCH05:1.5
	netbsd-1-0-PATCH04:1.5
	netbsd-1-0-PATCH03:1.5
	netbsd-1-0-PATCH02:1.5
	netbsd-1-0-PATCH1:1.5
	netbsd-1-0-PATCH0:1.5
	netbsd-1-0-RELEASE:1.5
	netbsd-1-0:1.5.0.2
	nvi-1-34b:1.1.1.4
	nvi-1-33b:1.1.1.3
	netbsd-1-0-base:1.3
	nvi-1-11b:1.1.1.2
	nvi-1-03:1.1.1.1
	bostic-nvi:1.1.1;
locks; strict;
comment	@ * @;


1.17
date	2008.10.29.16.49.36;	author christos;	state dead;
branches;
next	1.16;

1.16
date	2005.10.08.12.38.45;	author aymeric;	state Exp;
branches;
next	1.15;

1.15
date	2005.06.02.05.06.40;	author lukem;	state Exp;
branches;
next	1.14;

1.14
date	2005.02.12.12.53.22;	author aymeric;	state Exp;
branches
	1.14.2.1;
next	1.13;

1.13
date	2004.11.05.19.50.12;	author dsl;	state Exp;
branches;
next	1.12;

1.12
date	2002.04.09.01.47.32;	author thorpej;	state Exp;
branches
	1.12.4.1
	1.12.6.1;
next	1.11;

1.11
date	2001.03.31.11.37.49;	author aymeric;	state Exp;
branches;
next	1.10;

1.10
date	2001.01.14.02.22.29;	author aymeric;	state Exp;
branches;
next	1.9;

1.9
date	2000.10.11.19.28.43;	author thorpej;	state Exp;
branches;
next	1.8;

1.8
date	98.01.09.08.07.36;	author perry;	state Exp;
branches
	1.8.10.1;
next	1.7;

1.7
date	96.06.10.12.37.00;	author mrg;	state Exp;
branches;
next	1.6;

1.6
date	96.05.20.03.47.17;	author mrg;	state Exp;
branches
	1.6.4.1;
next	1.5;

1.5
date	94.08.17.20.12.04;	author cgd;	state Exp;
branches
	1.5.2.1;
next	1.4;

1.4
date	94.08.17.16.35.35;	author cgd;	state Exp;
branches;
next	1.3;

1.3
date	94.03.28.04.28.58;	author cgd;	state Exp;
branches;
next	1.2;

1.2
date	94.01.24.06.40.03;	author cgd;	state Exp;
branches;
next	1.1;

1.1
date	94.01.24.05.53.01;	author cgd;	state Exp;
branches
	1.1.1.1;
next	;

1.14.2.1
date	2005.10.15.15.41.12;	author riz;	state Exp;
branches;
next	;

1.12.4.1
date	2005.02.12.12.24.12;	author aymeric;	state Exp;
branches;
next	1.12.4.2;

1.12.4.2
date	2005.02.12.12.46.26;	author aymeric;	state Exp;
branches;
next	;

1.12.6.1
date	2005.05.06.14.42.13;	author riz;	state Exp;
branches;
next	;

1.8.10.1
date	2000.10.18.01.45.25;	author tv;	state Exp;
branches;
next	;

1.6.4.1
date	96.06.10.12.50.26;	author mrg;	state Exp;
branches;
next	;

1.5.2.1
date	94.08.17.20.12.04;	author cgd;	state dead;
branches;
next	1.5.2.2;

1.5.2.2
date	94.08.17.20.12.05;	author cgd;	state Exp;
branches;
next	;

1.1.1.1
date	94.01.24.05.53.02;	author cgd;	state Exp;
branches;
next	1.1.1.2;

1.1.1.2
date	94.03.28.02.52.55;	author cgd;	state Exp;
branches;
next	1.1.1.3;

1.1.1.3
date	94.08.17.16.16.13;	author cgd;	state Exp;
branches;
next	1.1.1.4;

1.1.1.4
date	94.08.17.19.16.46;	author cgd;	state Exp;
branches;
next	1.1.1.5;

1.1.1.5
date	96.05.20.01.53.34;	author mrg;	state Exp;
branches;
next	1.1.1.6;

1.1.1.6
date	2001.03.31.11.29.45;	author aymeric;	state Exp;
branches;
next	;


desc
@@


1.17
log
@bye old vi!
@
text
@/*	$NetBSD: ex.c,v 1.16 2005/10/08 12:38:45 aymeric Exp $	*/

/*-
 * Copyright (c) 1992, 1993, 1994
 *	The Regents of the University of California.  All rights reserved.
 * Copyright (c) 1992, 1993, 1994, 1995, 1996
 *	Keith Bostic.  All rights reserved.
 *
 * See the LICENSE file for redistribution information.
 */

#include "config.h"

#include <sys/cdefs.h>
#ifndef lint
#if 0
static const char sccsid[] = "@@(#)ex.c	10.57 (Berkeley) 10/10/96";
#else
__RCSID("$NetBSD: ex.c,v 1.16 2005/10/08 12:38:45 aymeric Exp $");
#endif
#endif /* not lint */

#include <sys/types.h>
#include <sys/queue.h>
#include <sys/stat.h>
#include <sys/time.h>

#include <bitstring.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "../common/common.h"
#include "../vi/vi.h"

#if defined(DEBUG) && defined(COMLOG)
static void	ex_comlog __P((SCR *, EXCMD *));
#endif
static EXCMDLIST const *
		ex_comm_search __P((char *, size_t));
static int	ex_discard __P((SCR *));
static int	ex_line __P((SCR *, EXCMD *, MARK *, int *, int *));
static int	ex_load __P((SCR *));
static void	ex_unknown __P((SCR *, char *, size_t));

/*
 * ex --
 *	Main ex loop.
 *
 * PUBLIC: int ex __P((SCR **));
 */
int
ex(spp)
	SCR **spp;
{
	EX_PRIVATE *exp;
	GS *gp;
	MSGS *mp;
	SCR *sp;
	TEXT *tp;
	u_int32_t flags;

	sp = *spp;
	gp = sp->gp;
	exp = EXP(sp);

	/* Start the ex screen. */
	if (ex_init(sp))
		return (1);

	/* Flush any saved messages. */
	while ((mp = gp->msgq.lh_first) != NULL) {
		gp->scr_msg(sp, mp->mtype, mp->buf, mp->len);
		LIST_REMOVE(mp, q);
		free(mp->buf);
		free(mp);
	}

	/* If reading from a file, errors should have name and line info. */
	if (F_ISSET(gp, G_SCRIPTED)) {
		gp->excmd.if_lno = 1;
		gp->excmd.if_name = "script";
	}

	/*
	 * !!!
	 * Initialize the text flags.  The beautify edit option historically
	 * applied to ex command input read from a file.  In addition, the
	 * first time a ^H was discarded from the input, there was a message,
	 * "^H discarded", that was displayed.  We don't bother.
	 */
	LF_INIT(TXT_BACKSLASH | TXT_CNTRLD | TXT_CR);
	for (;; ++gp->excmd.if_lno) {
		/* Display status line and flush. */
		if (F_ISSET(sp, SC_STATUS)) {
			if (!F_ISSET(sp, SC_EX_SILENT))
				msgq_status(sp, sp->lno, 0);
			F_CLR(sp, SC_STATUS);
		}
		(void)ex_fflush(sp);

		/* Set the flags the user can reset. */
		if (O_ISSET(sp, O_BEAUTIFY))
			LF_SET(TXT_BEAUTIFY);
		if (O_ISSET(sp, O_PROMPT))
			LF_SET(TXT_PROMPT);

		/* Clear any current interrupts, and get a command. */
		CLR_INTERRUPT(sp);
		if (ex_txt(sp, &sp->tiq, ':', flags))
			return (1);
		if (INTERRUPTED(sp)) {
			(void)ex_puts(sp, "\n");
			(void)ex_fflush(sp);
			continue;
		}

		/* Initialize the command structure. */
		CLEAR_EX_PARSER(&gp->excmd);

		/*
		 * If the user entered a single carriage return, send
		 * ex_cmd() a separator -- it discards single newlines.
		 */
		tp = sp->tiq.cqh_first;
		if (tp->len == 0) {
			gp->excmd.cp = " ";	/* __TK__ why not |? */
			gp->excmd.clen = 1;
		} else {
			gp->excmd.cp = tp->lb;
			gp->excmd.clen = tp->len;
		}
		F_INIT(&gp->excmd, E_NRSEP);

		if (ex_cmd(sp) && F_ISSET(gp, G_SCRIPTED))
			return (1);

		if (INTERRUPTED(sp)) {
			CLR_INTERRUPT(sp);
			msgq(sp, M_ERR, "170|Interrupted");
		}

		/*
		 * If the last command caused a restart, or switched screens
		 * or into vi, return.
		 */
		if (F_ISSET(gp, G_SRESTART) || F_ISSET(sp, SC_SSWITCH | SC_VI)) {
			*spp = sp;
			break;
		}

		/* If the last command switched files, we don't care. */
		F_CLR(sp, SC_FSWITCH);

		/*
		 * If we're exiting this screen, move to the next one.  By
		 * definition, this means returning into vi, so return to the
		 * main editor loop.  The ordering is careful, don't discard
		 * the contents of sp until the end.
		 */
		if (F_ISSET(sp, SC_EXIT | SC_EXIT_FORCE)) {
			if (file_end(sp, NULL, F_ISSET(sp, SC_EXIT_FORCE)))
				return (1);
			*spp = screen_next(sp);
			return (screen_end(sp));
		}
	}
	return (0);
}

/*
 * ex_cmd --
 *	The guts of the ex parser: parse and execute a string containing
 *	ex commands.
 *
 * !!!
 * This code MODIFIES the string that gets passed in, to delete quoting
 * characters, etc.  The string cannot be readonly/text space, nor should
 * you expect to use it again after ex_cmd() returns.
 *
 * !!!
 * For the fun of it, if you want to see if a vi clone got the ex argument
 * parsing right, try:
 *
 *	echo 'foo|bar' > file1; echo 'foo/bar' > file2;
 *	vi
 *	:edit +1|s/|/PIPE/|w file1| e file2|1 | s/\//SLASH/|wq
 *
 * or:	vi
 *	:set|file|append|set|file
 *
 * For extra credit, try them in a startup .exrc file.
 *
 * PUBLIC: int ex_cmd __P((SCR *));
 */
int
ex_cmd(sp)
	SCR *sp;
{
	enum nresult nret;
	EX_PRIVATE *exp;
	EXCMD *ecp;
	GS *gp;
	MARK cur;
	recno_t lno;
	size_t arg1_len, discard, len;
	u_int32_t flags;
	long ltmp;
	int at_found, gv_found;
	int ch, cnt, delim, isaddr, namelen;
	int newscreen, notempty, tmp, vi_address;
	char *arg1, *p, *s, *t;

	gp = sp->gp;
	exp = EXP(sp);
	ch = 0;		/* XXXGCC -Wuninitialized */

	/*
	 * We always start running the command on the top of the stack.
	 * This means that *everything* must be resolved when we leave
	 * this function for any reason.
	 */
loop:	ecp = gp->ecq.lh_first;

	/* If we're reading a command from a file, set up error information. */
	if (ecp->if_name != NULL) {
		gp->if_lno = ecp->if_lno;
		gp->if_name = ecp->if_name;
	}

	/*
	 * If a move to the end of the file is scheduled for this command,
	 * do it now.
	 */
	if (F_ISSET(ecp, E_MOVETOEND)) {
		if (db_last(sp, &sp->lno))
			goto rfail;
		sp->cno = 0;
		F_CLR(ecp, E_MOVETOEND);
	}

	/* If we found a newline, increment the count now. */
	if (F_ISSET(ecp, E_NEWLINE)) {
		++gp->if_lno;
		++ecp->if_lno;
		F_CLR(ecp, E_NEWLINE);
	}

	/* (Re)initialize the EXCMD structure, preserving some flags. */
	CLEAR_EX_CMD(ecp);

	/* Initialize the argument structures. */
	if (argv_init(sp, ecp))
		goto err;

	/* Initialize +cmd, saved command information. */
	arg1 = NULL;
	ecp->save_cmdlen = 0;

	/* Skip <blank>s, empty lines.  */
	for (notempty = 0; ecp->clen > 0; ++ecp->cp, --ecp->clen)
		if ((ch = *ecp->cp) == '\n') {
			++gp->if_lno;
			++ecp->if_lno;
		} else if (isblank(ch))
			notempty = 1;
		else
			break;

	/*
	 * !!!
	 * Permit extra colons at the start of the line.  Historically,
	 * ex/vi allowed a single extra one.  It's simpler not to count.
	 * The stripping is done here because, historically, any command
	 * could have preceding colons, e.g. ":g/pattern/:p" worked.
	 */
	if (ecp->clen != 0 && ch == ':') {
		notempty = 1;
		while (--ecp->clen > 0 && (ch = *++ecp->cp) == ':');
	}

	/*
	 * Command lines that start with a double-quote are comments.
	 *
	 * !!!
	 * Historically, there was no escape or delimiter for a comment, e.g.
	 * :"foo|set was a single comment and nothing was output.  Since nvi
	 * permits users to escape <newline> characters into command lines, we
	 * have to check for that case.
	 */
	if (ecp->clen != 0 && ch == '"') {
		while (--ecp->clen > 0 && *++ecp->cp != '\n');
		if (*ecp->cp == '\n') {
			F_SET(ecp, E_NEWLINE);
			++ecp->cp;
			--ecp->clen;
		}
		goto loop;
	}

	/* Skip whitespace. */
	for (; ecp->clen > 0; ++ecp->cp, --ecp->clen) {
		ch = *ecp->cp;
		if (!isblank(ch))
			break;
	}

	/*
	 * The last point at which an empty line can mean do nothing.
	 *
	 * !!!
	 * Historically, in ex mode, lines containing only <blank> characters
	 * were the same as a single <carriage-return>, i.e. a default command.
	 * In vi mode, they were ignored.  In .exrc files this was a serious
	 * annoyance, as vi kept trying to treat them as print commands.  We
	 * ignore backward compatibility in this case, discarding lines that
	 * contain only <blank> characters from .exrc files.
	 *
	 * !!!
	 * This is where you end up when you're done a command, i.e. clen has
	 * gone to zero.  Continue if there are more commands to run.
	 */
	if (ecp->clen == 0 &&
	    (!notempty || F_ISSET(sp, SC_VI) || F_ISSET(ecp, E_BLIGNORE))) {
		if (ex_load(sp))
			goto rfail;
		ecp = gp->ecq.lh_first;
		if (ecp->clen == 0)
			goto rsuccess;
		goto loop;
	}

	/*
	 * Check to see if this is a command for which we may want to move
	 * the cursor back up to the previous line.  (The command :1<CR>
	 * wants a <newline> separator, but the command :<CR> wants to erase
	 * the command line.)  If the line is empty except for <blank>s,
	 * <carriage-return> or <eof>, we'll probably want to move up.  I
	 * don't think there's any way to get <blank> characters *after* the
	 * command character, but this is the ex parser, and I've been wrong
	 * before.
	 */
	if (F_ISSET(ecp, E_NRSEP) &&
	    ecp->clen != 0 && (ecp->clen != 1 || ecp->cp[0] != '\004'))
		F_CLR(ecp, E_NRSEP);

	/* Parse command addresses. */
	if (ex_range(sp, ecp, &tmp))
		goto rfail;
	if (tmp)
		goto err;

	/*
	 * Skip <blank>s and any more colons (the command :3,5:print
	 * worked, historically).
	 */
	for (; ecp->clen > 0; ++ecp->cp, --ecp->clen) {
		ch = *ecp->cp;
		if (!isblank(ch) && ch != ':')
			break;
	}

	/*
	 * If no command, ex does the last specified of p, l, or #, and vi
	 * moves to the line.  Otherwise, determine the length of the command
	 * name by looking for the first non-alphabetic character.  (There
	 * are a few non-alphabetic characters in command names, but they're
	 * all single character commands.)  This isn't a great test, because
	 * it means that, for the command ":e +cut.c file", we'll report that
	 * the command "cut" wasn't known.  However, it makes ":e+35 file" work
	 * correctly.
	 *
	 * !!!
	 * Historically, lines with multiple adjacent (or <blank> separated)
	 * command separators were very strange.  For example, the command
	 * |||<carriage-return>, when the cursor was on line 1, displayed
	 * lines 2, 3 and 5 of the file.  In addition, the command "   |  "
	 * would only display the line after the next line, instead of the
	 * next two lines.  No ideas why.  It worked reasonably when executed
	 * from vi mode, and displayed lines 2, 3, and 4, so we do a default
	 * command for each separator.
	 */
#define	SINGLE_CHAR_COMMANDS	"\004!#&*<=>@@~"
	newscreen = 0;
	if (ecp->clen != 0 && ecp->cp[0] != '|' && ecp->cp[0] != '\n') {
		if (strchr(SINGLE_CHAR_COMMANDS, *ecp->cp)) {
			p = ecp->cp;
			++ecp->cp;
			--ecp->clen;
			namelen = 1;
		} else {
			for (p = ecp->cp;
			    ecp->clen > 0; --ecp->clen, ++ecp->cp)
				if (!isalpha((unsigned char)*ecp->cp))
					break;
			if ((namelen = ecp->cp - p) == 0) {
				msgq(sp, M_ERR, "080|Unknown command name");
				goto err;
			}
		}

		/*
		 * !!!
		 * Historic vi permitted flags to immediately follow any
		 * subset of the 'delete' command, but then did not permit
		 * further arguments (flag, buffer, count).  Make it work.
		 * Permit further arguments for the few shreds of dignity
		 * it offers.
		 *
		 * Adding commands that start with 'd', and match "delete"
		 * up to a l, p, +, - or # character can break this code.
		 *
		 * !!!
		 * Capital letters beginning the command names ex, edit,
		 * next, previous, tag and visual (in vi mode) indicate the
		 * command should happen in a new screen.
		 */
		switch (p[0]) {
		case 'd':
			for (s = p,
			    t = cmds[C_DELETE].name; *s == *t; ++s, ++t);
			if (s[0] == 'l' || s[0] == 'p' || s[0] == '+' ||
			    s[0] == '-' || s[0] == '^' || s[0] == '#') {
				len = (ecp->cp - p) - (s - p);
				ecp->cp -= len;
				ecp->clen += len;
				ecp->rcmd = cmds[C_DELETE];
				ecp->rcmd.syntax = "1bca1";
				ecp->cmd = &ecp->rcmd;
				goto skip_srch;
			}
			break;
		case 'E': case 'F': case 'N': case 'P': case 'T': case 'V':
			newscreen = 1;
			p[0] = tolower((unsigned char)p[0]);
			break;
		}

		/*
		 * Search the table for the command.
		 *
		 * !!!
		 * Historic vi permitted the mark to immediately follow the
		 * 'k' in the 'k' command.  Make it work.
		 *
		 * !!!
		 * Historic vi permitted any flag to follow the s command, e.g.
		 * "s/e/E/|s|sgc3p" was legal.  Make the command "sgc" work.
		 * Since the following characters all have to be flags, i.e.
		 * alphabetics, we can let the s command routine return errors
		 * if it was some illegal command string.  This code will break
		 * if an "sg" or similar command is ever added.  The substitute
		 * code doesn't care if it's a "cgr" flag or a "#lp" flag that
		 * follows the 's', but we limit the choices here to "cgr" so
		 * that we get unknown command messages for wrong combinations.
		 */
		if ((ecp->cmd = ex_comm_search(p, namelen)) == NULL)
			switch (p[0]) {
			case 'k':
				if (namelen == 2) {
					ecp->cp -= namelen - 1;
					ecp->clen += namelen - 1;
					ecp->cmd = &cmds[C_K];
					break;
				}
				goto unknown;
			case 's':
				for (s = p + 1, cnt = namelen; --cnt; ++s)
					if (s[0] != 'c' &&
					    s[0] != 'g' && s[0] != 'r')
						break;
				if (cnt == 0) {
					ecp->cp -= namelen - 1;
					ecp->clen += namelen - 1;
					ecp->rcmd = cmds[C_SUBSTITUTE];
					ecp->rcmd.fn = ex_subagain;
					ecp->cmd = &ecp->rcmd;
					break;
				}
				/* FALLTHROUGH */
			default:
unknown:			if (newscreen)
					p[0] = toupper((unsigned char)p[0]);
				ex_unknown(sp, p, namelen);
				goto err;
			}

		/*
		 * The visual command has a different syntax when called
		 * from ex than when called from a vi colon command.  FMH.
		 * Make the change now, before we test for the newscreen
		 * semantic, so that we're testing the right one.
		 */
skip_srch:	if (ecp->cmd == &cmds[C_VISUAL_EX] && F_ISSET(sp, SC_VI))
			ecp->cmd = &cmds[C_VISUAL_VI];

		/*
		 * !!!
		 * Historic vi permitted a capital 'P' at the beginning of
		 * any command that started with 'p'.  Probably wanted the
		 * P[rint] command for backward compatibility, and the code
		 * just made Preserve and Put work by accident.  Nvi uses
		 * Previous to mean previous-in-a-new-screen, so be careful.
		 */
		if (newscreen && !F_ISSET(ecp->cmd, E_NEWSCREEN) &&
		    (ecp->cmd == &cmds[C_PRINT] ||
		    ecp->cmd == &cmds[C_PRESERVE]))
			newscreen = 0;

		/* Test for a newscreen associated with this command. */
		if (newscreen && !F_ISSET(ecp->cmd, E_NEWSCREEN))
			goto unknown;

		/* Secure means no shell access. */
		if (F_ISSET(ecp->cmd, E_SECURE) && O_ISSET(sp, O_SECURE)) {
			ex_emsg(sp, ecp->cmd->name, EXM_SECURE);
			goto err;
		}

		/*
		 * Multiple < and > characters; another "feature".  Note,
		 * The string passed to the underlying function may not be
		 * nul terminated in this case.
		 */
		if ((ecp->cmd == &cmds[C_SHIFTL] && *p == '<') ||
		    (ecp->cmd == &cmds[C_SHIFTR] && *p == '>')) {
			for (ch = *p;
			    ecp->clen > 0; --ecp->clen, ++ecp->cp)
				if (*ecp->cp != ch)
					break;
			if (argv_exp0(sp, ecp, p, ecp->cp - p))
				goto err;
		}

		/* Set the format style flags for the next command. */
		if (ecp->cmd == &cmds[C_HASH])
			exp->fdef = E_C_HASH;
		else if (ecp->cmd == &cmds[C_LIST])
			exp->fdef = E_C_LIST;
		else if (ecp->cmd == &cmds[C_PRINT])
			exp->fdef = E_C_PRINT;
		F_CLR(ecp, E_USELASTCMD);
	} else {
		/* Print is the default command. */
		ecp->cmd = &cmds[C_PRINT];

		/* Set the saved format flags. */
		F_SET(ecp, exp->fdef);

		/*
		 * !!!
		 * If no address was specified, and it's not a global command,
		 * we up the address by one.  (I have no idea why globals are
		 * exempted, but it's (ahem) historic practice.)
		 */
		if (ecp->addrcnt == 0 && !F_ISSET(sp, SC_EX_GLOBAL)) {
			ecp->addrcnt = 1;
			ecp->addr1.lno = sp->lno + 1;
			ecp->addr1.cno = sp->cno;
		}

		F_SET(ecp, E_USELASTCMD);
	}

	/*
	 * !!!
	 * Historically, the number option applied to both ex and vi.  One
	 * strangeness was that ex didn't switch display formats until a
	 * command was entered, e.g. <CR>'s after the set didn't change to
	 * the new format, but :1p would.
	 */
	if (O_ISSET(sp, O_NUMBER)) {
		F_SET(ecp, E_OPTNUM);
		FL_SET(ecp->iflags, E_C_HASH);
	} else
		F_CLR(ecp, E_OPTNUM);

	/* Check for ex mode legality. */
	if (F_ISSET(sp, SC_EX) && (F_ISSET(ecp->cmd, E_VIONLY) || newscreen)) {
		msgq(sp, M_ERR,
		    "082|%s: command not available in ex mode", ecp->cmd->name);
		goto err;
	}

	/* Add standard command flags. */
	F_SET(ecp, ecp->cmd->flags);
	if (!newscreen)
		F_CLR(ecp, E_NEWSCREEN);

	/*
	 * There are three normal termination cases for an ex command.  They
	 * are the end of the string (ecp->clen), or unescaped (by <literal
	 * next> characters) <newline> or '|' characters.  As we're now past
	 * possible addresses, we can determine how long the command is, so we
	 * don't have to look for all the possible terminations.  Naturally,
	 * there are some exciting special cases:
	 *
	 * 1: The bang, global, v and the filter versions of the read and
	 *    write commands are delimited by <newline>s (they can contain
	 *    shell pipes).
	 * 2: The ex, edit, next and visual in vi mode commands all take ex
	 *    commands as their first arguments.
	 * 3: The s command takes an RE as its first argument, and wants it
	 *    to be specially delimited.
	 *
	 * Historically, '|' characters in the first argument of the ex, edit,
	 * next, vi visual, and s commands didn't delimit the command.  And,
	 * in the filter cases for read and write, and the bang, global and v
	 * commands, they did not delimit the command at all.
	 *
	 * For example, the following commands were legal:
	 *
	 *	:edit +25|s/abc/ABC/ file.c
	 *	:s/|/PIPE/
	 *	:read !spell % | columnate
	 *	:global/pattern/p|l
	 *
	 * It's not quite as simple as it sounds, however.  The command:
	 *
	 *	:s/a/b/|s/c/d|set
	 *
	 * was also legal, i.e. the historic ex parser (using the word loosely,
	 * since "parser" implies some regularity of syntax) delimited the RE's
	 * based on its delimiter and not anything so irretrievably vulgar as a
	 * command syntax.
	 *
	 * Anyhow, the following code makes this all work.  First, for the
	 * special cases we move past their special argument(s).  Then, we
	 * do normal command processing on whatever is left.  Barf-O-Rama.
	 */
	discard = 0;		/* Characters discarded from the command. */
	arg1_len = 0;
	ecp->save_cmd = ecp->cp;
	if (ecp->cmd == &cmds[C_EDIT] || ecp->cmd == &cmds[C_EX] ||
	    ecp->cmd == &cmds[C_NEXT] || ecp->cmd == &cmds[C_VISUAL_VI]) {
		/*
		 * Move to the next non-whitespace character.  A '!'
		 * immediately following the command is eaten as a
		 * force flag.
		 */
		if (ecp->clen > 0 && *ecp->cp == '!') {
			++ecp->cp;
			--ecp->clen;
			FL_SET(ecp->iflags, E_C_FORCE);

			/* Reset, don't reparse. */
			ecp->save_cmd = ecp->cp;
		}
		for (; ecp->clen > 0; --ecp->clen, ++ecp->cp)
			if (!isblank(*ecp->cp))
				break;
		/*
		 * QUOTING NOTE:
		 *
		 * The historic implementation ignored all escape characters
		 * so there was no way to put a space or newline into the +cmd
		 * field.  We do a simplistic job of fixing it by moving to the
		 * first whitespace character that isn't escaped.  The escaping
		 * characters are stripped as no longer useful.
		 */
		if (ecp->clen > 0 && *ecp->cp == '+') {
			++ecp->cp;
			--ecp->clen;
			for (arg1 = p = ecp->cp;
			    ecp->clen > 0; --ecp->clen, ++ecp->cp) {
				ch = *ecp->cp;
				if (IS_ESCAPE(sp, ecp, ch) &&
				    ecp->clen > 1) {
					++discard;
					--ecp->clen;
					ch = *++ecp->cp;
				} else if (isblank(ch))
					break;
				*p++ = ch;
			}
			arg1_len = ecp->cp - arg1;

			/* Reset, so the first argument isn't reparsed. */
			ecp->save_cmd = ecp->cp;
		}
	} else if (ecp->cmd == &cmds[C_BANG] ||
	    ecp->cmd == &cmds[C_GLOBAL] || ecp->cmd == &cmds[C_V]) {
		/*
		 * QUOTING NOTE:
		 *
		 * We use backslashes to escape <newline> characters, although
		 * this wasn't historic practice for the bang command.  It was
		 * for the global and v commands, and it's common usage when
		 * doing text insert during the command.  Escaping characters
		 * are stripped as no longer useful.
		 */
		for (p = ecp->cp; ecp->clen > 0; --ecp->clen, ++ecp->cp) {
			ch = *ecp->cp;
			if (ch == '\\' && ecp->clen > 1 && ecp->cp[1] == '\n') {
				++discard;
				--ecp->clen;
				ch = *++ecp->cp;

				++gp->if_lno;
				++ecp->if_lno;
			} else if (ch == '\n')
				break;
			*p++ = ch;
		}
	} else if (ecp->cmd == &cmds[C_READ] || ecp->cmd == &cmds[C_WRITE]) {
		/*
		 * For write commands, if the next character is a <blank>, and
		 * the next non-blank character is a '!', it's a filter command
		 * and we want to eat everything up to the <newline>.  For read
		 * commands, if the next non-blank character is a '!', it's a
		 * filter command and we want to eat everything up to the next
		 * <newline>.  Otherwise, we're done.
		 */
		for (tmp = 0; ecp->clen > 0; --ecp->clen, ++ecp->cp) {
			ch = *ecp->cp;
			if (isblank(ch))
				tmp = 1;
			else
				break;
		}
		if (ecp->clen > 0 && ch == '!' &&
		    (ecp->cmd == &cmds[C_READ] || tmp))
			for (; ecp->clen > 0; --ecp->clen, ++ecp->cp)
				if (ecp->cp[0] == '\n')
					break;
	} else if (ecp->cmd == &cmds[C_SUBSTITUTE]) {
		/*
		 * Move to the next non-whitespace character, we'll use it as
		 * the delimiter.  If the character isn't an alphanumeric or
		 * a '|', it's the delimiter, so parse it.  Otherwise, we're
		 * into something like ":s g", so use the special s command.
		 */
		for (; ecp->clen > 0; --ecp->clen, ++ecp->cp)
			if (!isblank(ecp->cp[0]))
				break;

		if (isalnum((unsigned char)ecp->cp[0]) || ecp->cp[0] == '|') {
			ecp->rcmd = cmds[C_SUBSTITUTE];
			ecp->rcmd.fn = ex_subagain;
			ecp->cmd = &ecp->rcmd;
		} else if (ecp->clen > 0) {
			/*
			 * QUOTING NOTE:
			 *
			 * Backslashes quote delimiter characters for RE's.
			 * The backslashes are NOT removed since they'll be
			 * used by the RE code.  Move to the third delimiter
			 * that's not escaped (or the end of the command).
			 */
			delim = *ecp->cp;
			++ecp->cp;
			--ecp->clen;
			for (cnt = 2; ecp->clen > 0 &&
			    cnt != 0; --ecp->clen, ++ecp->cp)
				if (ecp->cp[0] == '\\' &&
				    ecp->clen > 1) {
					++ecp->cp;
					--ecp->clen;
				} else if (ecp->cp[0] == delim)
					--cnt;
		}
	}

	/*
	 * Use normal quoting and termination rules to find the end of this
	 * command.
	 *
	 * QUOTING NOTE:
	 *
	 * Historically, vi permitted ^V's to escape <newline>'s in the .exrc
	 * file.  It was almost certainly a bug, but that's what bug-for-bug
	 * compatibility means, Grasshopper.  Also, ^V's escape the command
	 * delimiters.  Literal next quote characters in front of the newlines,
	 * '|' characters or literal next characters are stripped as they're
	 * no longer useful.
	 */
	vi_address = ecp->clen != 0 && ecp->cp[0] != '\n';
	for (p = ecp->cp; ecp->clen > 0; --ecp->clen, ++ecp->cp) {
		ch = ecp->cp[0];
		if (IS_ESCAPE(sp, ecp, ch) && ecp->clen > 1) {
			tmp = ecp->cp[1];
			if (tmp == '\n' || tmp == '|') {
				if (tmp == '\n') {
					++gp->if_lno;
					++ecp->if_lno;
				}
				++discard;
				--ecp->clen;
				++ecp->cp;
				ch = tmp;
			}
		} else if (ch == '\n' || ch == '|') {
			if (ch == '\n')
				F_SET(ecp, E_NEWLINE);
			--ecp->clen;
			break;
		}
		*p++ = ch;
	}

	/*
	 * Save off the next command information, go back to the
	 * original start of the command.
	 */
	p = ecp->cp + 1;
	ecp->cp = ecp->save_cmd;
	ecp->save_cmd = p;
	ecp->save_cmdlen = ecp->clen;
	ecp->clen = ((ecp->save_cmd - ecp->cp) - 1) - discard;

	/*
	 * Set the default addresses.  It's an error to specify an address for
	 * a command that doesn't take them.  If two addresses are specified
	 * for a command that only takes one, lose the first one.  Two special
	 * cases here, some commands take 0 or 2 addresses.  For most of them
	 * (the E_ADDR2_ALL flag), 0 defaults to the entire file.  For one
	 * (the `!' command, the E_ADDR2_NONE flag), 0 defaults to no lines.
	 *
	 * Also, if the file is empty, some commands want to use an address of
	 * 0, i.e. the entire file is 0 to 0, and the default first address is
	 * 0.  Otherwise, an entire file is 1 to N and the default line is 1.
	 * Note, we also add the E_ADDR_ZERO flag to the command flags, for the
	 * case where the 0 address is only valid if it's a default address.
	 *
	 * Also, set a flag if we set the default addresses.  Some commands
	 * (ex: z) care if the user specified an address or if we just used
	 * the current cursor.
	 */
	switch (F_ISSET(ecp, E_ADDR1 | E_ADDR2 | E_ADDR2_ALL | E_ADDR2_NONE)) {
	case E_ADDR1:				/* One address: */
		switch (ecp->addrcnt) {
		case 0:				/* Default cursor/empty file. */
			ecp->addrcnt = 1;
			F_SET(ecp, E_ADDR_DEF);
			if (F_ISSET(ecp, E_ADDR_ZERODEF)) {
				if (db_last(sp, &lno))
					goto err;
				if (lno == 0) {
					ecp->addr1.lno = 0;
					F_SET(ecp, E_ADDR_ZERO);
				} else
					ecp->addr1.lno = sp->lno;
			} else
				ecp->addr1.lno = sp->lno;
			ecp->addr1.cno = sp->cno;
			break;
		case 1:
			break;
		case 2:				/* Lose the first address. */
			ecp->addrcnt = 1;
			ecp->addr1 = ecp->addr2;
		}
		break;
	case E_ADDR2_NONE:			/* Zero/two addresses: */
		if (ecp->addrcnt == 0)		/* Default to nothing. */
			break;
		goto two_addr;
	case E_ADDR2_ALL:			/* Zero/two addresses: */
		if (ecp->addrcnt == 0) {	/* Default entire/empty file. */
			F_SET(ecp, E_ADDR_DEF);
			ecp->addrcnt = 2;
			if (sp->ep == NULL)
				ecp->addr2.lno = 0;
			else if (db_last(sp, &ecp->addr2.lno))
				goto err;
			if (F_ISSET(ecp, E_ADDR_ZERODEF) &&
			    ecp->addr2.lno == 0) {
				ecp->addr1.lno = 0;
				F_SET(ecp, E_ADDR_ZERO);
			} else
				ecp->addr1.lno = 1;
			ecp->addr1.cno = ecp->addr2.cno = 0;
			F_SET(ecp, E_ADDR2_ALL);
			break;
		}
		/* FALLTHROUGH */
	case E_ADDR2:				/* Two addresses: */
two_addr:	switch (ecp->addrcnt) {
		case 0:				/* Default cursor/empty file. */
			ecp->addrcnt = 2;
			F_SET(ecp, E_ADDR_DEF);
			if (sp->lno == 1 &&
			    F_ISSET(ecp, E_ADDR_ZERODEF)) {
				if (db_last(sp, &lno))
					goto err;
				if (lno == 0) {
					ecp->addr1.lno = ecp->addr2.lno = 0;
					F_SET(ecp, E_ADDR_ZERO);
				} else
					ecp->addr1.lno =
					    ecp->addr2.lno = sp->lno;
			} else
				ecp->addr1.lno = ecp->addr2.lno = sp->lno;
			ecp->addr1.cno = ecp->addr2.cno = sp->cno;
			break;
		case 1:				/* Default to first address. */
			ecp->addrcnt = 2;
			ecp->addr2 = ecp->addr1;
			break;
		case 2:
			break;
		}
		break;
	default:
		if (ecp->addrcnt)		/* Error. */
			goto usage;
	}

	/*
	 * !!!
	 * The ^D scroll command historically scrolled the value of the scroll
	 * option or to EOF.  It was an error if the cursor was already at EOF.
	 * (Leading addresses were permitted, but were then ignored.)
	 */
	if (ecp->cmd == &cmds[C_SCROLL]) {
		ecp->addrcnt = 2;
		ecp->addr1.lno = sp->lno + 1;
		ecp->addr2.lno = sp->lno + O_VAL(sp, O_SCROLL);
		ecp->addr1.cno = ecp->addr2.cno = sp->cno;
		if (db_last(sp, &lno))
			goto err;
		if (lno != 0 && lno > sp->lno && ecp->addr2.lno > lno)
			ecp->addr2.lno = lno;
	}

	ecp->flagoff = 0;
	for (p = ecp->cmd->syntax; *p != '\0'; ++p) {
		/*
		 * The force flag is sensitive to leading whitespace, i.e.
		 * "next !" is different from "next!".  Handle it before
		 * skipping leading <blank>s.
		 */
		if (*p == '!') {
			if (ecp->clen > 0 && *ecp->cp == '!') {
				++ecp->cp;
				--ecp->clen;
				FL_SET(ecp->iflags, E_C_FORCE);
			}
			continue;
		}

		/* Skip leading <blank>s. */
		for (; ecp->clen > 0; --ecp->clen, ++ecp->cp)
			if (!isblank(*ecp->cp))
				break;
		if (ecp->clen == 0)
			break;

		switch (*p) {
		case '1':				/* +, -, #, l, p */
			/*
			 * !!!
			 * Historically, some flags were ignored depending
			 * on where they occurred in the command line.  For
			 * example, in the command, ":3+++p--#", historic vi
			 * acted on the '#' flag, but ignored the '-' flags.
			 * It's unambiguous what the flags mean, so we just
			 * handle them regardless of the stupidity of their
			 * location.
			 */
			for (; ecp->clen; --ecp->clen, ++ecp->cp)
				switch (*ecp->cp) {
				case '+':
					++ecp->flagoff;
					break;
				case '-':
				case '^':
					--ecp->flagoff;
					break;
				case '#':
					F_CLR(ecp, E_OPTNUM);
					FL_SET(ecp->iflags, E_C_HASH);
					exp->fdef |= E_C_HASH;
					break;
				case 'l':
					FL_SET(ecp->iflags, E_C_LIST);
					exp->fdef |= E_C_LIST;
					break;
				case 'p':
					FL_SET(ecp->iflags, E_C_PRINT);
					exp->fdef |= E_C_PRINT;
					break;
				default:
					goto end_case1;
				}
end_case1:		break;
		case '2':				/* -, ., +, ^ */
		case '3':				/* -, ., +, ^, = */
			for (; ecp->clen; --ecp->clen, ++ecp->cp)
				switch (*ecp->cp) {
				case '-':
					FL_SET(ecp->iflags, E_C_DASH);
					break;
				case '.':
					FL_SET(ecp->iflags, E_C_DOT);
					break;
				case '+':
					FL_SET(ecp->iflags, E_C_PLUS);
					break;
				case '^':
					FL_SET(ecp->iflags, E_C_CARAT);
					break;
				case '=':
					if (*p == '3') {
						FL_SET(ecp->iflags, E_C_EQUAL);
						break;
					}
					/* FALLTHROUGH */
				default:
					goto end_case23;
				}
end_case23:		break;
		case 'b':				/* buffer */
			/*
			 * !!!
			 * Historically, "d #" was a delete with a flag, not a
			 * delete into the '#' buffer.  If the current command
			 * permits a flag, don't use one as a buffer.  However,
			 * the 'l' and 'p' flags were legal buffer names in the
			 * historic ex, and were used as buffers, not flags.
			 */
			if ((ecp->cp[0] == '+' || ecp->cp[0] == '-' ||
			    ecp->cp[0] == '^' || ecp->cp[0] == '#') &&
			    strchr(p, '1') != NULL)
				break;
			/*
			 * !!!
			 * Digits can't be buffer names in ex commands, or the
			 * command "d2" would be a delete into buffer '2', and
			 * not a two-line deletion.
			 */
			if (!isdigit((unsigned char)ecp->cp[0])) {
				ecp->buffer = *ecp->cp;
				++ecp->cp;
				--ecp->clen;
				FL_SET(ecp->iflags, E_C_BUFFER);
			}
			break;
		case 'c':				/* count [01+a] */
			++p;
			/* Validate any signed value. */
			if (!isdigit((unsigned char)*ecp->cp) && (*p != '+' ||
			    (*ecp->cp != '+' && *ecp->cp != '-')))
				break;
			/* If a signed value, set appropriate flags. */
			if (*ecp->cp == '-')
				FL_SET(ecp->iflags, E_C_COUNT_NEG);
			else if (*ecp->cp == '+')
				FL_SET(ecp->iflags, E_C_COUNT_POS);
			if ((nret =
			    nget_slong(&ltmp, ecp->cp, &t, 10)) != NUM_OK) {
				ex_badaddr(sp, NULL, A_NOTSET, nret);
				goto err;
			}
			if (ltmp == 0 && *p != '0') {
				msgq(sp, M_ERR, "083|Count may not be zero");
				goto err;
			}
			ecp->clen -= (t - ecp->cp);
			ecp->cp = t;

			/*
			 * Counts as address offsets occur in commands taking
			 * two addresses.  Historic vi practice was to use
			 * the count as an offset from the *second* address.
			 *
			 * Set a count flag; some underlying commands (see
			 * join) do different things with counts than with
			 * line addresses.
			 */
			if (*p == 'a') {
				ecp->addr1 = ecp->addr2;
				ecp->addr2.lno = ecp->addr1.lno + ltmp - 1;
			} else
				ecp->count = ltmp;
			FL_SET(ecp->iflags, E_C_COUNT);
			break;
		case 'f':				/* file */
			if (argv_exp2(sp, ecp, ecp->cp, ecp->clen))
				goto err;
			goto arg_cnt_chk;
		case 'l':				/* line */
			/*
			 * Get a line specification.
			 *
			 * If the line was a search expression, we may have
			 * changed state during the call, and we're now
			 * searching the file.  Push ourselves onto the state
			 * stack.
			 */
			if (ex_line(sp, ecp, &cur, &isaddr, &tmp))
				goto rfail;
			if (tmp)
				goto err;

			/* Line specifications are always required. */
			if (!isaddr) {
				msgq_str(sp, M_ERR, ecp->cp,
				     "084|%s: bad line specification");
				goto err;
			}
			/*
			 * The target line should exist for these commands,
			 * but 0 is legal for them as well.
			 */
			if (cur.lno != 0 && !db_exist(sp, cur.lno)) {
				ex_badaddr(sp, NULL, A_EOF, NUM_OK);
				goto err;
			}
			ecp->lineno = cur.lno;
			break;
		case 'S':				/* string, file exp. */
			if (ecp->clen != 0) {
				if (argv_exp1(sp, ecp, ecp->cp,
				    ecp->clen, ecp->cmd == &cmds[C_BANG]))
					goto err;
				goto addr_verify;
			}
			/* FALLTHROUGH */
		case 's':				/* string */
			if (argv_exp0(sp, ecp, ecp->cp, ecp->clen))
				goto err;
			goto addr_verify;
		case 'W':				/* word string */
			/*
			 * QUOTING NOTE:
			 *
			 * Literal next characters escape the following
			 * character.  Quoting characters are stripped here
			 * since they are no longer useful.
			 *
			 * First there was the word.
			 */
			for (p = t = ecp->cp;
			    ecp->clen > 0; --ecp->clen, ++ecp->cp) {
				ch = *ecp->cp;
				if (IS_ESCAPE(sp,
				    ecp, ch) && ecp->clen > 1) {
					--ecp->clen;
					*p++ = *++ecp->cp;
				} else if (isblank(ch)) {
					++ecp->cp;
					--ecp->clen;
					break;
				} else
					*p++ = ch;
			}
			if (argv_exp0(sp, ecp, t, p - t))
				goto err;

			/* Delete intervening whitespace. */
			for (; ecp->clen > 0;
			    --ecp->clen, ++ecp->cp) {
				ch = *ecp->cp;
				if (!isblank(ch))
					break;
			}
			if (ecp->clen == 0)
				goto usage;

			/* Followed by the string. */
			for (p = t = ecp->cp; ecp->clen > 0;
			    --ecp->clen, ++ecp->cp, ++p) {
				ch = *ecp->cp;
				if (IS_ESCAPE(sp,
				    ecp, ch) && ecp->clen > 1) {
					--ecp->clen;
					*p = *++ecp->cp;
				} else
					*p = ch;
			}
			if (argv_exp0(sp, ecp, t, p - t))
				goto err;
			goto addr_verify;
		case 'w':				/* word */
			if (argv_exp3(sp, ecp, ecp->cp, ecp->clen))
				goto err;
arg_cnt_chk:		if (*++p != 'N') {		/* N */
				/*
				 * If a number is specified, must either be
				 * 0 or that number, if optional, and that
				 * number, if required.
				 */
				tmp = *p - '0';
				if ((*++p != 'o' || exp->argsoff != 0) &&
				    exp->argsoff != tmp)
					goto usage;
			}
			goto addr_verify;
		default:
			msgq(sp, M_ERR,
			    "085|Internal syntax table error (%s: %s)",
			    ecp->cmd->name, KEY_NAME(sp, *p));
		}
	}

	/* Skip trailing whitespace. */
	for (; ecp->clen > 0; --ecp->clen) {
		ch = *ecp->cp++;
		if (!isblank(ch))
			break;
	}

	/*
	 * There shouldn't be anything left, and no more required fields,
	 * i.e neither 'l' or 'r' in the syntax string.
	 */
	if (ecp->clen != 0 || strpbrk(p, "lr")) {
usage:		msgq(sp, M_ERR, "086|Usage: %s", ecp->cmd->usage);
		goto err;
	}

	/*
	 * Verify that the addresses are legal.  Check the addresses here,
	 * because this is a place where all ex addresses pass through.
	 * (They don't all pass through ex_line(), for instance.)  We're
	 * assuming that any non-existent line doesn't exist because it's
	 * past the end-of-file.  That's a pretty good guess.
	 *
	 * If it's a "default vi command", an address of zero is okay.
	 */
addr_verify:
	switch (ecp->addrcnt) {
	case 2:
		/*
		 * Historic ex/vi permitted commands with counts to go past
		 * EOF.  So, for example, if the file only had 5 lines, the
		 * ex command "1,6>" would fail, but the command ">300"
		 * would succeed.  Since we don't want to have to make all
		 * of the underlying commands handle random line numbers,
		 * fix it here.
		 */
		if (ecp->addr2.lno == 0) {
			if (!F_ISSET(ecp, E_ADDR_ZERO) &&
			    (F_ISSET(sp, SC_EX) ||
			    !F_ISSET(ecp, E_USELASTCMD))) {
				ex_badaddr(sp, ecp->cmd, A_ZERO, NUM_OK);
				goto err;
			}
		} else if (!db_exist(sp, ecp->addr2.lno))
			if (FL_ISSET(ecp->iflags, E_C_COUNT)) {
				if (db_last(sp, &lno))
					goto err;
				ecp->addr2.lno = lno;
			} else {
				ex_badaddr(sp, NULL, A_EOF, NUM_OK);
				goto err;
			}
		/* FALLTHROUGH */
	case 1:
		if (ecp->addr1.lno == 0) {
			if (!F_ISSET(ecp, E_ADDR_ZERO) &&
			    (F_ISSET(sp, SC_EX) ||
			    !F_ISSET(ecp, E_USELASTCMD))) {
				ex_badaddr(sp, ecp->cmd, A_ZERO, NUM_OK);
				goto err;
			}
		} else if (!db_exist(sp, ecp->addr1.lno)) {
			ex_badaddr(sp, NULL, A_EOF, NUM_OK);
			goto err;
		}
		break;
	}

	/*
	 * If doing a default command and there's nothing left on the line,
	 * vi just moves to the line.  For example, ":3" and ":'a,'b" just
	 * move to line 3 and line 'b, respectively, but ":3|" prints line 3.
	 *
	 * !!!
	 * In addition, IF THE LINE CHANGES, move to the first nonblank of
	 * the line.
	 *
	 * !!!
	 * This is done before the absolute mark gets set; historically,
	 * "/a/,/b/" did NOT set vi's absolute mark, but "/a/,/b/d" did.
	 */
	if ((F_ISSET(sp, SC_VI) || F_ISSET(ecp, E_NOPRDEF)) &&
	    F_ISSET(ecp, E_USELASTCMD) && vi_address == 0) {
		switch (ecp->addrcnt) {
		case 2:
			if (sp->lno !=
			    (ecp->addr2.lno ? ecp->addr2.lno : 1)) {
				sp->lno =
				    ecp->addr2.lno ? ecp->addr2.lno : 1;
				sp->cno = 0;
				(void)nonblank(sp, sp->lno, &sp->cno);
			}
			break;
		case 1:
			if (sp->lno !=
			    (ecp->addr1.lno ? ecp->addr1.lno : 1)) {
				sp->lno =
				    ecp->addr1.lno ? ecp->addr1.lno : 1;
				sp->cno = 0;
				(void)nonblank(sp, sp->lno, &sp->cno);
			}
			break;
		}
		ecp->cp = ecp->save_cmd;
		ecp->clen = ecp->save_cmdlen;
		goto loop;
	}

	/*
	 * Set the absolute mark -- we have to set it for vi here, in case
	 * it's a compound command, e.g. ":5p|6" should set the absolute
	 * mark for vi.
	 */
	if (F_ISSET(ecp, E_ABSMARK)) {
		cur.lno = sp->lno;
		cur.cno = sp->cno;
		F_CLR(ecp, E_ABSMARK);
		if (mark_set(sp, ABSMARK1, &cur, 1))
			goto err;
	}

#if defined(DEBUG) && defined(COMLOG)
	ex_comlog(sp, ecp);
#endif
	/* Increment the command count if not called from vi. */
	if (F_ISSET(sp, SC_EX))
		++sp->ccnt;

	/*
	 * If file state available, and not doing a global command,
	 * log the start of an action.
	 */
	if (sp->ep != NULL && !F_ISSET(sp, SC_EX_GLOBAL))
		(void)log_cursor(sp);

	/*
	 * !!!
	 * There are two special commands for the purposes of this code: the
	 * default command (<carriage-return>) or the scrolling commands (^D
	 * and <EOF>) as the first non-<blank> characters  in the line.
	 *
	 * If this is the first command in the command line, we received the
	 * command from the ex command loop and we're talking to a tty, and
	 * and there's nothing else on the command line, and it's one of the
	 * special commands, we move back up to the previous line, and erase
	 * the prompt character with the output.  Since ex runs in canonical
	 * mode, we don't have to do anything else, a <newline> has already
	 * been echoed by the tty driver.  It's OK if vi calls us -- we won't
	 * be in ex mode so we'll do nothing.
	 */
	if (F_ISSET(ecp, E_NRSEP)) {
		if (sp->ep != NULL &&
		    F_ISSET(sp, SC_EX) && !F_ISSET(gp, G_SCRIPTED) &&
		    (F_ISSET(ecp, E_USELASTCMD) || ecp->cmd == &cmds[C_SCROLL]))
			gp->scr_ex_adjust(sp, EX_TERM_SCROLL);
		F_CLR(ecp, E_NRSEP);
	}

	/*
	 * Call the underlying function for the ex command.
	 *
	 * XXX
	 * Interrupts behave like errors, for now.
	 */
	if (ecp->cmd->fn(sp, ecp) || INTERRUPTED(sp)) {
		if (F_ISSET(gp, G_SCRIPTED))
			F_SET(sp, SC_EXIT_FORCE);
		goto err;
	}

#ifdef DEBUG
	/* Make sure no function left global temporary space locked. */
	if (F_ISSET(gp, G_TMP_INUSE)) {
		F_CLR(gp, G_TMP_INUSE);
		msgq(sp, M_ERR, "087|%s: temporary buffer not released",
		    ecp->cmd->name);
	}
#endif
	/*
	 * Ex displayed the number of lines modified immediately after each
	 * command, so the command "1,10d|1,10d" would display:
	 *
	 *	10 lines deleted
	 *	10 lines deleted
	 *	<autoprint line>
	 *
	 * Executing ex commands from vi only reported the final modified
	 * lines message -- that's wrong enough that we don't match it.
	 */
	if (F_ISSET(sp, SC_EX))
		mod_rpt(sp);

	/*
	 * Integrate any offset parsed by the underlying command, and make
	 * sure the referenced line exists.
	 *
	 * XXX
	 * May not match historic practice (which I've never been able to
	 * completely figure out.)  For example, the '=' command from vi
	 * mode often got the offset wrong, and complained it was too large,
	 * but didn't seem to have a problem with the cursor.  If anyone
	 * complains, ask them how it's supposed to work, they might know.
	 */
	if (sp->ep != NULL && ecp->flagoff) {
		if (ecp->flagoff < 0) {
			if (sp->lno <= -ecp->flagoff) {
				msgq(sp, M_ERR,
				    "088|Flag offset to before line 1");
				goto err;
			}
		} else {
			if (!NPFITS(MAX_REC_NUMBER, sp->lno, ecp->flagoff)) {
				ex_badaddr(sp, NULL, A_NOTSET, NUM_OVER);
				goto err;
			}
			if (!db_exist(sp, sp->lno + ecp->flagoff)) {
				msgq(sp, M_ERR,
				    "089|Flag offset past end-of-file");
				goto err;
			}
		}
		sp->lno += ecp->flagoff;
	}

	/*
	 * If the command executed successfully, we may want to display a line
	 * based on the autoprint option or an explicit print flag.  (Make sure
	 * that there's a line to display.)  Also, the autoprint edit option is
	 * turned off for the duration of global commands.
	 */
	if (F_ISSET(sp, SC_EX) && sp->ep != NULL && sp->lno != 0) {
		/*
		 * The print commands have already handled the `print' flags.
		 * If so, clear them.
		 */
		if (FL_ISSET(ecp->iflags, E_CLRFLAG))
			FL_CLR(ecp->iflags, E_C_HASH | E_C_LIST | E_C_PRINT);

		/* If hash set only because of the number option, discard it. */
		if (F_ISSET(ecp, E_OPTNUM))
			FL_CLR(ecp->iflags, E_C_HASH);

		/*
		 * If there was an explicit flag to display the new cursor line,
		 * or autoprint is set and a change was made, display the line.
		 * If any print flags were set use them, else default to print.
		 */
		LF_INIT(FL_ISSET(ecp->iflags, E_C_HASH | E_C_LIST | E_C_PRINT));
		if (!LF_ISSET(E_C_HASH | E_C_LIST | E_C_PRINT | E_NOAUTO) &&
		    !F_ISSET(sp, SC_EX_GLOBAL) &&
		    O_ISSET(sp, O_AUTOPRINT) && F_ISSET(ecp, E_AUTOPRINT))
			LF_INIT(E_C_PRINT);

		if (LF_ISSET(E_C_HASH | E_C_LIST | E_C_PRINT)) {
			cur.lno = sp->lno;
			cur.cno = 0;
			(void)ex_print(sp, ecp, &cur, &cur, flags);
		}
	}

	/*
	 * If the command had an associated "+cmd", it has to be executed
	 * before we finish executing any more of this ex command.  For
	 * example, consider a .exrc file that contains the following lines:
	 *
	 *	:set all
	 *	:edit +25 file.c|s/abc/ABC/|1
	 *	:3,5 print
	 *
	 * This can happen more than once -- the historic vi simply hung or
	 * dropped core, of course.  Prepend the + command back into the
	 * current command and continue.  We may have to add an additional
	 * <literal next> character.  We know that it will fit because we
	 * discarded at least one space and the + character.
	 */
	if (arg1_len != 0) {
		/*
		 * If the last character of the + command was a <literal next>
		 * character, it would be treated differently because of the
		 * append.  Quote it, if necessary.
		 */
		if (IS_ESCAPE(sp, ecp, arg1[arg1_len - 1])) {
			*--ecp->save_cmd = CH_LITERAL;
			++ecp->save_cmdlen;
		}

		ecp->save_cmd -= arg1_len;
		ecp->save_cmdlen += arg1_len;
		memcpy(ecp->save_cmd, arg1, arg1_len);

		/*
		 * Any commands executed from a +cmd are executed starting at
		 * the first column of the last line of the file -- NOT the
		 * first nonblank.)  The main file startup code doesn't know
		 * that a +cmd was set, however, so it may have put us at the
		 * top of the file.  (Note, this is safe because we must have
		 * switched files to get here.)
		 */
		F_SET(ecp, E_MOVETOEND);
	}

	/* Update the current command. */
	ecp->cp = ecp->save_cmd;
	ecp->clen = ecp->save_cmdlen;

	/*
	 * !!!
	 * If we've changed screens or underlying files, any pending global or
	 * v command, or @@ buffer that has associated addresses, has to be
	 * discarded.  This is historic practice for globals, and necessary for
	 * @@ buffers that had associated addresses.
	 *
	 * Otherwise, if we've changed underlying files, it's not a problem,
	 * we continue with the rest of the ex command(s), operating on the
	 * new file.  However, if we switch screens (either by exiting or by
	 * an explicit command), we have no way of knowing where to put output
	 * messages, and, since we don't control screens here, we could screw
	 * up the upper layers, (e.g. we could exit/reenter a screen multiple
	 * times).  So, return and continue after we've got a new screen.
	 */
	if (F_ISSET(sp, SC_EXIT | SC_EXIT_FORCE | SC_FSWITCH | SC_SSWITCH)) {
		at_found = gv_found = 0;
		for (ecp = sp->gp->ecq.lh_first;
		    ecp != NULL; ecp = ecp->q.le_next)
			switch (ecp->agv_flags) {
			case 0:
			case AGV_AT_NORANGE:
				break;
			case AGV_AT:
				if (!at_found) {
					at_found = 1;
					msgq(sp, M_ERR,
		"090|@@ with range running when the file/screen changed");
				}
				break;
			case AGV_GLOBAL:
			case AGV_V:
				if (!gv_found) {
					gv_found = 1;
					msgq(sp, M_ERR,
		"091|Global/v command running when the file/screen changed");
				}
				break;
			default:
				abort();
			}
		if (at_found || gv_found)
			goto discard;
		if (F_ISSET(sp, SC_EXIT | SC_EXIT_FORCE | SC_SSWITCH))
			goto rsuccess;
	}

	goto loop;
	/* NOTREACHED */

err:	/*
	 * On command failure, we discard keys and pending commands remaining,
	 * as well as any keys that were mapped and waiting.  The save_cmdlen
	 * test is not necessarily correct.  If we fail early enough we don't
	 * know if the entire string was a single command or not.  Guess, as
	 * it's useful to know if commands other than the current one are being
	 * discarded.
	 */
	if (ecp->save_cmdlen == 0)
		for (; ecp->clen; --ecp->clen) {
			ch = *ecp->cp++;
			if (IS_ESCAPE(sp, ecp, ch) && ecp->clen > 1) {
				--ecp->clen;
				++ecp->cp;
			} else if (ch == '\n' || ch == '|') {
				if (ecp->clen > 1)
					ecp->save_cmdlen = 1;
				break;
			}
		}
	if (ecp->save_cmdlen != 0 || gp->ecq.lh_first != &gp->excmd) {
discard:	msgq(sp, M_BERR,
		    "092|Ex command failed: pending commands discarded");
		ex_discard(sp);
	}
	if (v_event_flush(sp, CH_MAPPED))
		msgq(sp, M_BERR,
		    "093|Ex command failed: mapped keys discarded");

rfail:	tmp = 1;
	if (0)
rsuccess:	tmp = 0;

	/* Turn off any file name error information. */
	gp->if_name = NULL;

	/* Turn off the global bit. */
	F_CLR(sp, SC_EX_GLOBAL);

	return (tmp);
}

/*
 * ex_range --
 *	Get a line range for ex commands, or perform a vi ex address search.
 *
 * PUBLIC: int ex_range __P((SCR *, EXCMD *, int *));
 */
int
ex_range(sp, ecp, errp)
	SCR *sp;
	EXCMD *ecp;
	int *errp;
{
	enum { ADDR_FOUND, ADDR_NEED, ADDR_NONE } addr;
	GS *gp;
	EX_PRIVATE *exp;
	MARK m;
	int isaddr;

	*errp = 0;

	/*
	 * Parse comma or semi-colon delimited line specs.
	 *
	 * Semi-colon delimiters update the current address to be the last
	 * address.  For example, the command
	 *
	 *	:3;/pattern/ecp->cp
	 *
	 * will search for pattern from line 3.  In addition, if ecp->cp
	 * is not a valid command, the current line will be left at 3, not
	 * at the original address.
	 *
	 * Extra addresses are discarded, starting with the first.
	 *
	 * !!!
	 * If any addresses are missing, they default to the current line.
	 * This was historically true for both leading and trailing comma
	 * delimited addresses as well as for trailing semicolon delimited
	 * addresses.  For consistency, we make it true for leading semicolon
	 * addresses as well.
	 */
	gp = sp->gp;
	exp = EXP(sp);
	for (addr = ADDR_NONE, ecp->addrcnt = 0; ecp->clen > 0;)
		switch (*ecp->cp) {
		case '%':		/* Entire file. */
			/* Vi ex address searches didn't permit % signs. */
			if (F_ISSET(ecp, E_VISEARCH))
				goto ret;

			/* It's an error if the file is empty. */
			if (sp->ep == NULL) {
				ex_badaddr(sp, NULL, A_EMPTY, NUM_OK);
				*errp = 1;
				return (0);
			}
			/*
			 * !!!
			 * A percent character addresses all of the lines in
			 * the file.  Historically, it couldn't be followed by
			 * any other address.  We do it as a text substitution
			 * for simplicity.  POSIX 1003.2 is expected to follow
			 * this practice.
			 *
			 * If it's an empty file, the first line is 0, not 1.
			 */
			if (addr == ADDR_FOUND) {
				ex_badaddr(sp, NULL, A_COMBO, NUM_OK);
				*errp = 1;
				return (0);
			}
			if (db_last(sp, &ecp->addr2.lno))
				return (1);
			ecp->addr1.lno = ecp->addr2.lno == 0 ? 0 : 1;
			ecp->addr1.cno = ecp->addr2.cno = 0;
			ecp->addrcnt = 2;
			addr = ADDR_FOUND;
			++ecp->cp;
			--ecp->clen;
			break;
		case ',':               /* Comma delimiter. */
			/* Vi ex address searches didn't permit commas. */
			if (F_ISSET(ecp, E_VISEARCH))
				goto ret;
			/* FALLTHROUGH */
		case ';':               /* Semi-colon delimiter. */
			if (sp->ep == NULL) {
				ex_badaddr(sp, NULL, A_EMPTY, NUM_OK);
				*errp = 1;
				return (0);
			}
			if (addr != ADDR_FOUND)
				switch (ecp->addrcnt) {
				case 0:
					ecp->addr1.lno = sp->lno;
					ecp->addr1.cno = sp->cno;
					ecp->addrcnt = 1;
					break;
				case 2:
					ecp->addr1 = ecp->addr2;
					/* FALLTHROUGH */
				case 1:
					ecp->addr2.lno = sp->lno;
					ecp->addr2.cno = sp->cno;
					ecp->addrcnt = 2;
					break;
				}
			if (*ecp->cp == ';')
				switch (ecp->addrcnt) {
				case 0:
					abort();
					/* NOTREACHED */
				case 1:
					sp->lno = ecp->addr1.lno;
					sp->cno = ecp->addr1.cno;
					break;
				case 2:
					sp->lno = ecp->addr2.lno;
					sp->cno = ecp->addr2.cno;
					break;
				}
			addr = ADDR_NEED;
			/* FALLTHROUGH */
		case ' ':		/* Whitespace. */
		case '\t':		/* Whitespace. */
			++ecp->cp;
			--ecp->clen;
			break;
		default:
			/* Get a line specification. */
			if (ex_line(sp, ecp, &m, &isaddr, errp))
				return (1);
			if (*errp)
				return (0);
			if (!isaddr)
				goto ret;
			if (addr == ADDR_FOUND) {
				ex_badaddr(sp, NULL, A_COMBO, NUM_OK);
				*errp = 1;
				return (0);
			}
			switch (ecp->addrcnt) {
			case 0:
				ecp->addr1 = m;
				ecp->addrcnt = 1;
				break;
			case 1:
				ecp->addr2 = m;
				ecp->addrcnt = 2;
				break;
			case 2:
				ecp->addr1 = ecp->addr2;
				ecp->addr2 = m;
				break;
			}
			addr = ADDR_FOUND;
			break;
		}

	/*
	 * !!!
	 * Vi ex address searches are indifferent to order or trailing
	 * semi-colons.
	 */
ret:	if (F_ISSET(ecp, E_VISEARCH))
		return (0);

	if (addr == ADDR_NEED)
		switch (ecp->addrcnt) {
		case 0:
			ecp->addr1.lno = sp->lno;
			ecp->addr1.cno = sp->cno;
			ecp->addrcnt = 1;
			break;
		case 2:
			ecp->addr1 = ecp->addr2;
			/* FALLTHROUGH */
		case 1:
			ecp->addr2.lno = sp->lno;
			ecp->addr2.cno = sp->cno;
			ecp->addrcnt = 2;
			break;
		}

	if (ecp->addrcnt == 2 && ecp->addr2.lno < ecp->addr1.lno) {
		msgq(sp, M_ERR,
		    "094|The second address is smaller than the first");
		*errp = 1;
	}
	return (0);
}

/*
 * ex_line --
 *	Get a single line address specifier.
 *
 * The way the "previous context" mark worked was that any "non-relative"
 * motion set it.  While ex/vi wasn't totally consistent about this, ANY
 * numeric address, search pattern, '$', or mark reference in an address
 * was considered non-relative, and set the value.  Which should explain
 * why we're hacking marks down here.  The problem was that the mark was
 * only set if the command was called, i.e. we have to set a flag and test
 * it later.
 *
 * XXX
 * This is probably still not exactly historic practice, although I think
 * it's fairly close.
 */
static int
ex_line(sp, ecp, mp, isaddrp, errp)
	SCR *sp;
	EXCMD *ecp;
	MARK *mp;
	int *isaddrp, *errp;
{
	enum nresult nret;
	EX_PRIVATE *exp;
	GS *gp;
	long total, val;
	int isneg;
	int (*sf) __P((SCR *, MARK *, MARK *, char *, size_t, char **, u_int));
	char *endp;

	gp = sp->gp;
	exp = EXP(sp);

	*isaddrp = *errp = 0;
	F_CLR(ecp, E_DELTA);

	/* No addresses permitted until a file has been read in. */
	if (sp->ep == NULL && strchr("$0123456789'\\/?.+-^", *ecp->cp)) {
		ex_badaddr(sp, NULL, A_EMPTY, NUM_OK);
		*errp = 1;
		return (0);
	}

	switch (*ecp->cp) {
	case '$':				/* Last line in the file. */
		*isaddrp = 1;
		F_SET(ecp, E_ABSMARK);

		mp->cno = 0;
		if (db_last(sp, &mp->lno))
			return (1);
		++ecp->cp;
		--ecp->clen;
		break;				/* Absolute line number. */
	case '0': case '1': case '2': case '3': case '4':
	case '5': case '6': case '7': case '8': case '9':
		*isaddrp = 1;
		F_SET(ecp, E_ABSMARK);

		if ((nret = nget_slong(&val, ecp->cp, &endp, 10)) != NUM_OK) {
			ex_badaddr(sp, NULL, A_NOTSET, nret);
			*errp = 1;
			return (0);
		}
		if (!NPFITS(MAX_REC_NUMBER, 0, val)) {
			ex_badaddr(sp, NULL, A_NOTSET, NUM_OVER);
			*errp = 1;
			return (0);
		}
		mp->lno = val;
		mp->cno = 0;
		ecp->clen -= (endp - ecp->cp);
		ecp->cp = endp;
		break;
	case '\'':				/* Use a mark. */
		*isaddrp = 1;
		F_SET(ecp, E_ABSMARK);

		if (ecp->clen == 1) {
			msgq(sp, M_ERR, "095|No mark name supplied");
			*errp = 1;
			return (0);
		}
		if (mark_get(sp, ecp->cp[1], mp, M_ERR)) {
			*errp = 1;
			return (0);
		}
		ecp->cp += 2;
		ecp->clen -= 2;
		break;
	case '\\':				/* Search: forward/backward. */
		/*
		 * !!!
		 * I can't find any difference between // and \/ or between
		 * ?? and \?.  Mark Horton doesn't remember there being any
		 * difference.  C'est la vie.
		 */
		if (ecp->clen < 2 ||
		    ecp->cp[1] != '/' && ecp->cp[1] != '?') {
			msgq(sp, M_ERR, "096|\\ not followed by / or ?");
			*errp = 1;
			return (0);
		}
		++ecp->cp;
		--ecp->clen;
		sf = ecp->cp[0] == '/' ? f_search : b_search;
		goto search;
	case '/':				/* Search forward. */
		sf = f_search;
		goto search;
	case '?':				/* Search backward. */
		sf = b_search;

search:		mp->lno = sp->lno;
		mp->cno = sp->cno;
		if (sf(sp, mp, mp, ecp->cp, ecp->clen, &endp,
		    SEARCH_MSG | SEARCH_PARSE | SEARCH_SET |
		    (F_ISSET(ecp, E_SEARCH_WMSG) ? SEARCH_WMSG : 0))) {
			*errp = 1;
			return (0);
		}

		/* Fix up the command pointers. */
		ecp->clen -= (endp - ecp->cp);
		ecp->cp = endp;

		*isaddrp = 1;
		F_SET(ecp, E_ABSMARK);
		break;
	case '.':				/* Current position. */
		*isaddrp = 1;
		mp->cno = sp->cno;

		/* If an empty file, then '.' is 0, not 1. */
		if (sp->lno == 1) {
			if (db_last(sp, &mp->lno))
				return (1);
			if (mp->lno != 0)
				mp->lno = 1;
		} else
			mp->lno = sp->lno;

		/*
		 * !!!
		 * Historically, .<number> was the same as .+<number>, i.e.
		 * the '+' could be omitted.  (This feature is found in ed
		 * as well.)
		 */
		if (ecp->clen > 1 && isdigit((unsigned char)ecp->cp[1]))
			*ecp->cp = '+';
		else {
			++ecp->cp;
			--ecp->clen;
		}
		break;
	}

	/* Skip trailing <blank>s. */
	for (; ecp->clen > 0 &&
	    isblank(ecp->cp[0]); ++ecp->cp, --ecp->clen);

	/*
	 * Evaluate any offset.  If no address yet found, the offset
	 * is relative to ".".
	 */
	total = 0;
	if (ecp->clen != 0 && (isdigit((unsigned char)ecp->cp[0]) ||
	    ecp->cp[0] == '+' || ecp->cp[0] == '-' ||
	    ecp->cp[0] == '^')) {
		if (!*isaddrp) {
			*isaddrp = 1;
			mp->lno = sp->lno;
			mp->cno = sp->cno;
		}
		/*
		 * Evaluate an offset, defined as:
		 *
		 *		[+-^<blank>]*[<blank>]*[0-9]*
		 *
		 * The rough translation is any number of signs, optionally
		 * followed by numbers, or a number by itself, all <blank>
		 * separated.
		 *
		 * !!!
		 * All address offsets were additive, e.g. "2 2 3p" was the
		 * same as "7p", or, "/ZZZ/ 2" was the same as "/ZZZ/+2".
		 * Note, however, "2 /ZZZ/" was an error.  It was also legal
		 * to insert signs without numbers, so "3 - 2" was legal, and
		 * equal to 4.
		 *
		 * !!!
		 * Offsets were historically permitted for any line address,
		 * e.g. the command "1,2 copy 2 2 2 2" copied lines 1,2 after
		 * line 8.
		 *
		 * !!!
		 * Offsets were historically permitted for search commands,
		 * and handled as addresses: "/pattern/2 2 2" was legal, and
		 * referenced the 6th line after pattern.
		 */
		F_SET(ecp, E_DELTA);
		for (;;) {
			for (; ecp->clen > 0 && isblank(ecp->cp[0]);
			    ++ecp->cp, --ecp->clen);
			if (ecp->clen == 0 || !isdigit((unsigned char)ecp->cp[0]) &&
			    ecp->cp[0] != '+' && ecp->cp[0] != '-' &&
			    ecp->cp[0] != '^')
				break;
			if (!isdigit((unsigned char)ecp->cp[0]) &&
			    !isdigit((unsigned char)ecp->cp[1])) {
				total += ecp->cp[0] == '+' ? 1 : -1;
				--ecp->clen;
				++ecp->cp;
			} else {
				if (ecp->cp[0] == '-' ||
				    ecp->cp[0] == '^') {
					++ecp->cp;
					--ecp->clen;
					isneg = 1;
				} else
					isneg = 0;

				/* Get a signed long, add it to the total. */
				if ((nret = nget_slong(&val,
				    ecp->cp, &endp, 10)) != NUM_OK ||
				    (nret = NADD_SLONG(sp,
				    total, val)) != NUM_OK) {
					ex_badaddr(sp, NULL, A_NOTSET, nret);
					*errp = 1;
					return (0);
				}
				total += isneg ? -val : val;
				ecp->clen -= (endp - ecp->cp);
				ecp->cp = endp;
			}
		}
	}

	/*
	 * Any value less than 0 is an error.  Make sure that the new value
	 * will fit into a recno_t.
	 */
	if (*isaddrp && total != 0) {
		if (total < 0) {
			if (-total > mp->lno) {
				msgq(sp, M_ERR,
			    "097|Reference to a line number less than 0");
				*errp = 1;
				return (0);
			}
		} else
			if (!NPFITS(MAX_REC_NUMBER, mp->lno, total)) {
				ex_badaddr(sp, NULL, A_NOTSET, NUM_OVER);
				*errp = 1;
				return (0);
			}
		mp->lno += total;
	}
	return (0);
}


/*
 * ex_load --
 *	Load up the next command, which may be an @@ buffer or global command.
 */
static int
ex_load(sp)
	SCR *sp;
{
	GS *gp;
	EXCMD *ecp;
	RANGE *rp;

	F_CLR(sp, SC_EX_GLOBAL);

	/*
	 * Lose any exhausted commands.  We know that the first command
	 * can't be an AGV command, which makes things a bit easier.
	 */
	for (gp = sp->gp;;) {
		/*
		 * If we're back to the original structure, leave it around,
		 * but discard any allocated source name, we've returned to
		 * the beginning of the command stack.
		 */
		if ((ecp = gp->ecq.lh_first) == &gp->excmd) {
			if (F_ISSET(ecp, E_NAMEDISCARD)) {
				free(ecp->if_name);
				ecp->if_name = NULL;
			}
			return (0);
		}

		/*
		 * ecp->clen will be 0 for the first discarded command, but
		 * may not be 0 for subsequent ones, e.g. if the original
		 * command was ":g/xx/@@a|s/b/c/", then when we discard the
		 * command pushed on the stack by the @@a, we have to resume
		 * the global command which included the substitute command.
		 */
		if (ecp->clen != 0)
			return (0);

		/*
		 * If it's an @@, global or v command, we may need to continue
		 * the command on a different line.
		 */
		if (FL_ISSET(ecp->agv_flags, AGV_ALL)) {
			/* Discard any exhausted ranges. */
			while ((rp = ecp->rq.cqh_first) != (void *)&ecp->rq)
				if (rp->start > rp->stop) {
					CIRCLEQ_REMOVE(&ecp->rq, rp, q);
					free(rp);
				} else
					break;

			/* If there's another range, continue with it. */
			if (rp != (void *)&ecp->rq)
				break;

			/* If it's a global/v command, fix up the last line. */
			if (FL_ISSET(ecp->agv_flags,
			    AGV_GLOBAL | AGV_V) && ecp->range_lno != OOBLNO)
				if (db_exist(sp, ecp->range_lno))
					sp->lno = ecp->range_lno;
				else {
					if (db_last(sp, &sp->lno))
						return (1);
					if (sp->lno == 0)
						sp->lno = 1;
				}
			free(ecp->o_cp);
		}

		/* Discard the EXCMD. */
		LIST_REMOVE(ecp, q);
		free(ecp);
	}

	/*
	 * We only get here if it's an active @@, global or v command.  Set
	 * the current line number, and get a new copy of the command for
	 * the parser.  Note, the original pointer almost certainly moved,
	 * so we have play games.
	 */
	ecp->cp = ecp->o_cp;
	memcpy(ecp->cp, ecp->cp + ecp->o_clen, ecp->o_clen);
	ecp->clen = ecp->o_clen;
	ecp->range_lno = sp->lno = rp->start++;

	if (FL_ISSET(ecp->agv_flags, AGV_GLOBAL | AGV_V))
		F_SET(sp, SC_EX_GLOBAL);
	return (0);
}

/*
 * ex_discard --
 *	Discard any pending ex commands.
 */
static int
ex_discard(sp)
	SCR *sp;
{
	GS *gp;
	EXCMD *ecp;
	RANGE *rp;

	/*
	 * We know the first command can't be an AGV command, so we don't
	 * process it specially.  We do, however, nail the command itself.
	 */
	for (gp = sp->gp; (ecp = gp->ecq.lh_first) != &gp->excmd;) {
		if (FL_ISSET(ecp->agv_flags, AGV_ALL)) {
			while ((rp = ecp->rq.cqh_first) != (void *)&ecp->rq) {
				CIRCLEQ_REMOVE(&ecp->rq, rp, q);
				free(rp);
			}
			free(ecp->o_cp);
		}
		LIST_REMOVE(ecp, q);
		free(ecp);
	}
	gp->ecq.lh_first->clen = 0;
	return (0);
}

/*
 * ex_unknown --
 *	Display an unknown command name.
 */
static void
ex_unknown(sp, cmd, len)
	SCR *sp;
	char *cmd;
	size_t len;
{
	size_t blen;
	char *bp;

	GET_SPACE_GOTO(sp, bp, blen, len + 1);
	bp[len] = '\0';
	memcpy(bp, cmd, len);
	msgq_str(sp, M_ERR, bp, "098|The %s command is unknown");
	FREE_SPACE(sp, bp, blen);

alloc_err:
	return;
}

/*
 * ex_is_abbrev -
 *	The vi text input routine needs to know if ex thinks this is an
 *	[un]abbreviate command, so it can turn off abbreviations.  See
 *	the usual ranting in the vi/v_txt_ev.c:txt_abbrev() routine.
 *
 * PUBLIC: int ex_is_abbrev __P((char *, size_t));
 */
int
ex_is_abbrev(name, len)
	char *name;
	size_t len;
{
	EXCMDLIST const *cp;

	return ((cp = ex_comm_search(name, len)) != NULL &&
	    (cp == &cmds[C_ABBR] || cp == &cmds[C_UNABBREVIATE]));
}

/*
 * ex_is_unmap -
 *	The vi text input routine needs to know if ex thinks this is an
 *	unmap command, so it can turn off input mapping.  See the usual
 *	ranting in the vi/v_txt_ev.c:txt_unmap() routine.
 *
 * PUBLIC: int ex_is_unmap __P((char *, size_t));
 */
int
ex_is_unmap(name, len)
	char *name;
	size_t len;
{
	EXCMDLIST const *cp;

	/*
	 * The command the vi input routines are really interested in
	 * is "unmap!", not just unmap.
	 */
	if (name[len - 1] != '!')
		return (0);
	--len;
	return ((cp = ex_comm_search(name, len)) != NULL &&
	    cp == &cmds[C_UNMAP]);
}

/*
 * ex_comm_search --
 *	Search for a command name.
 */
static EXCMDLIST const *
ex_comm_search(name, len)
	char *name;
	size_t len;
{
	EXCMDLIST const *cp;

	for (cp = cmds; cp->name != NULL; ++cp) {
		if (cp->name[0] > name[0])
			return (NULL);
		if (cp->name[0] != name[0])
			continue;
		if (!memcmp(name, cp->name, len))
			return (cp);
	}
	return (NULL);
}

/*
 * ex_badaddr --
 *	Display a bad address message.
 *
 * PUBLIC: void ex_badaddr
 * PUBLIC:    __P((SCR *, EXCMDLIST const *, enum badaddr, enum nresult));
 */
void
ex_badaddr(sp, cp, ba, nret)
	SCR *sp;
	EXCMDLIST const *cp;
	enum badaddr ba;
	enum nresult nret;
{
	recno_t lno;

	switch (nret) {
	case NUM_OK:
		break;
	case NUM_ERR:
		msgq(sp, M_SYSERR, NULL);
		return;
	case NUM_OVER:
		msgq(sp, M_ERR, "099|Address value overflow");
		return;
	case NUM_UNDER:
		msgq(sp, M_ERR, "100|Address value underflow");
		return;
	}

	/*
	 * When encountering an address error, tell the user if there's no
	 * underlying file, that's the real problem.
	 */
	if (sp->ep == NULL) {
		ex_emsg(sp, cp != NULL? cp->name : NULL, EXM_NOFILEYET);
		return;
	}

	switch (ba) {
	case A_COMBO:
		msgq(sp, M_ERR, "101|Illegal address combination");
		break;
	case A_EOF:
		if (db_last(sp, &lno))
			return;
		if (lno != 0) {
			msgq(sp, M_ERR,
			    "102|Illegal address: only %lu lines in the file",
			    (u_long) lno);
			break;
		}
		/* FALLTHROUGH */
	case A_EMPTY:
		msgq(sp, M_ERR, "103|Illegal address: the file is empty");
		break;
	case A_NOTSET:
		abort();
		/* NOTREACHED */
	case A_ZERO:
		msgq(sp, M_ERR,
		    "104|The %s command doesn't permit an address of 0",
		    cp->name);
		break;
	}
	return;
}

#if defined(DEBUG) && defined(COMLOG)
/*
 * ex_comlog --
 *	Log ex commands.
 */
static void
ex_comlog(sp, ecp)
	SCR *sp;
	EXCMD *ecp;
{
	TRACE(sp, "ecmd: %s", ecp->cmd->name);
	if (ecp->addrcnt > 0) {
		TRACE(sp, " a1 %d", ecp->addr1.lno);
		if (ecp->addrcnt > 1)
			TRACE(sp, " a2: %d", ecp->addr2.lno);
	}
	if (ecp->lineno)
		TRACE(sp, " line %d", ecp->lineno);
	if (ecp->flags)
		TRACE(sp, " flags 0x%x", ecp->flags);
	if (F_ISSET(&exc, E_BUFFER))
		TRACE(sp, " buffer %c", ecp->buffer);
	if (ecp->argc)
		for (cnt = 0; cnt < ecp->argc; ++cnt)
			TRACE(sp, " arg %d: {%s}", cnt, ecp->argv[cnt]->bp);
	TRACE(sp, "\n");
}
#endif
@


1.16
log
@remove the hack that changed backslaches to ^V's when the command is "set" (!).
Now backslashes are understood by argv_exp3().
@
text
@d1 1
a1 1
/*	$NetBSD: ex.c,v 1.15 2005/06/02 05:06:40 lukem Exp $	*/
d19 1
a19 1
__RCSID("$NetBSD: ex.c,v 1.15 2005/06/02 05:06:40 lukem Exp $");
@


1.15
log
@appease gcc -Wuninitialized
@
text
@d1 1
a1 1
/*	$NetBSD: ex.c,v 1.14 2005/02/12 12:53:22 aymeric Exp $	*/
d19 1
a19 1
__RCSID("$NetBSD: ex.c,v 1.14 2005/02/12 12:53:22 aymeric Exp $");
a816 14
	 * QUOTING NOTE:
	 *
	 * The "set tags" command historically used a backslash, not the
	 * user's literal next character, to escape whitespace.  Handle
	 * it here instead of complicating the argv_exp3() code.  Note,
	 * this isn't a particularly complex trap, and if backslashes were
	 * legal in set commands, this would have to be much more complicated.
	 */
	if (ecp->cmd == &cmds[C_SET])
		for (p = ecp->cp, len = ecp->clen; len > 0; --len, ++p)
			if (*p == '\\')
				*p = CH_LITERAL;

	/*
@


1.14
log
@Fix the RCSID's to be $NetBSD$ instead of $NetBSD
@
text
@d1 1
a1 1
/*	$NetBSD: ex.c,v 1.13 2004/11/05 19:50:12 dsl Exp $	*/
d19 1
a19 1
__RCSID("$NetBSD$");
d221 1
@


1.14.2.1
log
@Pull up following revision(s) (requested by aymeric in ticket #878):
	usr.bin/vi/ex/ex.c: revision 1.16
remove the hack that changed backslaches to ^V's when the command is
"set" (!).
Now backslashes are understood by argv_exp3().
@
text
@d1 1
a1 1
/*	$NetBSD: ex.c,v 1.14 2005/02/12 12:53:22 aymeric Exp $	*/
d19 1
a19 1
__RCSID("$NetBSD: ex.c,v 1.14 2005/02/12 12:53:22 aymeric Exp $");
d816 14
@


1.13
log
@Add (unsigned char) cast to ctype functions
@
text
@d1 1
a1 1
/*	$NetBSD: ex.c,v 1.12 2002/04/09 01:47:32 thorpej Exp $	*/
d19 1
a19 1
__RCSID("$NetBSD");
@


1.12
log
@Use __RCSID() and __COPYRIGHT().
@
text
@d1 1
a1 1
/*	$NetBSD: ex.c,v 1.11 2001/03/31 11:37:49 aymeric Exp $	*/
d398 1
a398 1
				if (!isalpha(*ecp->cp))
d439 1
a439 1
			p[0] = tolower(p[0]);
d487 1
a487 1
					p[0] = toupper(p[0]);
d741 1
a741 1
		if (isalnum(ecp->cp[0]) || ecp->cp[0] == '|') {
d1050 1
a1050 1
			if (!isdigit(ecp->cp[0])) {
d1060 1
a1060 1
			if (!isdigit(*ecp->cp) && (*p != '+' ||
d1953 1
a1953 1
		if (ecp->clen > 1 && isdigit(ecp->cp[1]))
d1971 1
a1971 1
	if (ecp->clen != 0 && (isdigit(ecp->cp[0]) ||
d2009 1
a2009 1
			if (ecp->clen == 0 || !isdigit(ecp->cp[0]) &&
d2013 2
a2014 2
			if (!isdigit(ecp->cp[0]) &&
			    !isdigit(ecp->cp[1])) {
@


1.12.6.1
log
@Pull up revision 1.14 (requested by aymeric in ticket #1195):
Fix the RCSID's to be $NetBSD$ instead of $NetBSD
@
text
@d1 1
a1 1
/*	$NetBSD: ex.c,v 1.12 2002/04/09 01:47:32 thorpej Exp $	*/
d19 1
a19 1
__RCSID("$NetBSD$");
@


1.12.4.1
log
@Fix the RCSID's to be $NetBSD$ instead of $NetBSD
@
text
@d1 1
a1 1
/*	$NetBSD: ex.c,v 1.12 2002/04/09 01:47:32 thorpej Exp $	*/
d19 1
a19 1
__RCSID("$NetBSD$");
@


1.12.4.2
log
@Backout previous. Sorry.
@
text
@d19 1
a19 1
__RCSID("$NetBSD");
@


1.11
log
@merge changes after import of nvi 1.79
@
text
@d1 1
a1 1
/*	$NetBSD: ex.c,v 1.10 2001/01/14 02:22:29 aymeric Exp $	*/
d14 1
d16 1
d18 3
@


1.10
log
@Don't dump core when a ``bad address'' error occurs and there is neither
a file nor a command underlying it.
This fixes PR #11543.
@
text
@d1 1
a1 1
/*	$NetBSD: ex.c,v 1.9 2000/10/11 19:28:43 thorpej Exp $	*/
d15 1
a15 1
static const char sccsid[] = "@@(#)ex.c	10.46 (Berkeley) 5/15/96";
d80 1
a80 1
	if (!F_ISSET(gp, G_STDIN_TTY)) {
d135 1
a135 1
		if (ex_cmd(sp) && !F_ISSET(gp, G_STDIN_TTY))
d206 1
a206 1
	size_t arg1_len, len;
d432 1
a432 1
		case 'E': case 'N': case 'P': case 'T': case 'V':
d459 1
a459 1
				if (p[1] && !p[2]) {
d622 3
a624 9
	 * since "parser" implies some regularity) delimited the RE's based on
	 * its delimiter and not anything so irretrievably vulgar as a command
	 * syntax.
	 *
	 * One thing that makes this easier is that we can ignore most of the
	 * command termination conditions for the commands that want to take
	 * the command up to the next newline.  None of them are legal in .exrc
	 * files, so if we're here, we only dealing with a single line, and we
	 * can just eat it.
d630 1
d657 2
a658 3
		 * first whitespace character that isn't escaped by a literal
		 * next character.  The literal next characters are stripped
		 * as they're no longer useful.
d666 3
a668 2
				if (IS_ESCAPE(sp,
				    ecp, ch) && ecp->clen > 1) {
d682 22
a703 2
		ecp->cp += ecp->clen;
		ecp->clen = 0;
d706 6
a711 2
		 * Move to the next character.  If it's a '!', it's a filter
		 * command and we want to eat it all, otherwise, we're done.
d713 1
a713 1
		for (; ecp->clen > 0; --ecp->clen, ++ecp->cp) {
d715 3
a717 1
			if (!isblank(ch))
d720 5
a724 4
		if (ecp->clen > 0 && ch == '!') {
			ecp->cp += ecp->clen;
			ecp->clen = 0;
		}
d777 1
a777 1
	for (cnt = 0, p = ecp->cp; ecp->clen > 0; --ecp->clen, ++ecp->cp) {
d786 1
a788 1
				++cnt;
d808 1
a808 1
	ecp->clen = ((ecp->save_cmd - ecp->cp) - 1) - cnt;
d839 1
a839 1
	 * (ex: z) care if the user specified an address of if we just used
d1229 1
a1229 1
	 * (They don't all pass through ep_line(), for instance.)  We're
d1362 1
a1362 1
		    F_ISSET(sp, SC_EX) && F_ISSET(gp, G_STDIN_TTY) &&
d1375 1
a1375 1
		if (!F_ISSET(gp, G_STDIN_TTY))
d1400 1
a1400 1
		msgq_rpt(sp);
d1435 3
a1437 3
	 * If the command was successful may want to display a line based on
	 * the autoprint option or an explicit print flag.  (Make sure that
	 * there's a line to display.)  Also, the autoprint edit option is
d1481 3
a1483 4
	 * current command and continue.  We may have to add up to two more
	 * characters, a <literal next> and a command separator.  We know
	 * that it will still fit because we discarded at least one space
	 * and the + character.
a1485 4
		/* Add in a command separator. */
		*--ecp->save_cmd = '\n';
		++ecp->save_cmdlen;

d1498 1
a1498 1
		memmove(ecp->save_cmd, arg1, arg1_len);
d1502 5
a1506 5
		 * the last line, first column of the file -- NOT the first
		 * nonblank.)  The main file startup code doesn't know that a
		 * +cmd was set, however, so it may have put us at the top of
		 * the file.  (Note, this is safe because we must have switched
		 * files to get here.)
d1827 1
a1827 1
	int (*sf) __P((SCR *, MARK *, MARK *, char *, char **, u_int));
d1915 3
a1917 2
		if (sf(sp, mp, mp,
		    ecp->cp, &endp, SEARCH_MSG | SEARCH_PARSE | SEARCH_SET)) {
a2144 2
	 *
	 * See ex.h for a discussion of SEARCH_TERMINATION.
d2147 1
a2147 2
	memmove(ecp->cp,
	    ecp->cp + ecp->o_clen + SEARCH_TERMINATION, ecp->o_clen);
d2202 1
a2202 1
	memmove(bp, cmd, len);
@


1.9
log
@Fix a format string goof.
@
text
@d1 1
a1 1
/*	$NetBSD: ex.c,v 1.8 1998/01/09 08:07:36 perry Exp $	*/
d2297 1
a2297 1
		ex_emsg(sp, cp->name, EXM_NOFILEYET);
@


1.8
log
@RCS Id Police.
@
text
@d1 1
a1 1
/*	$NetBSD$	*/
d2311 1
a2311 1
			    lno);
@


1.8.10.1
log
@Pullup 1.9 [releng]:
Fix %l[du] formats that have int arguments on ILP32; might break LP64.
@
text
@d1 1
a1 1
/*	$NetBSD: ex.c,v 1.9 2000/10/11 19:28:43 thorpej Exp $	*/
d2311 1
a2311 1
			    (u_long) lno);
@


1.7
log
@make "ex -s" work.  massaged by bostic from pr#2518
@
text
@d1 2
@


1.6
log
@merge in nvi 1.66
@
text
@d94 2
a96 1
			msgq_status(sp, sp->lno, 0);
@


1.6.4.1
log
@pull up "ex -s" fix from bostic (from pr#2518)
@
text
@a93 2
			if (!F_ISSET(sp, SC_EX_SILENT))
				msgq_status(sp, sp->lno, 0);
d95 1
@


1.5
log
@clean up import.
@
text
@d4 2
d7 1
a7 27
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
d10 2
d13 1
a13 1
static char sccsid[] = "@@(#)ex.c	8.157 (Berkeley) 8/17/94";
a25 1
#include <signal.h>
a28 1
#include <termios.h>
d31 2
a32 3
#include "compat.h"
#include <db.h>
#include <regex.h>
d34 4
a37 5
#include "vi.h"
#include "excmd.h"

static void	badlno __P((SCR *, recno_t));
static __inline EXCMDLIST const *
d39 4
a42 2
static int	ep_line __P((SCR *, EXF *, MARK *, char **, size_t *, int *));
static int	ep_range __P((SCR *, EXF *, EXCMDARG *, char **, size_t *));
d46 3
a48 1
 *	Read an ex command and execute it.
d51 6
a56 1
ex(sp, ep)
a57 3
	EXF *ep;
{
	enum input irval;
d59 5
a63 2
	u_int flags, saved_mode;
	int eval;
d65 2
a66 1
	if (ex_init(sp, ep))
d69 7
a75 2
	if (sp->s_refresh(sp, ep))
		return (ex_end(sp));
d77 4
a80 4
	/* If reading from a file, messages should have line info. */
	if (!F_ISSET(sp->gp, G_STDIN_TTY)) {
		sp->if_lno = 1;
		sp->if_name = strdup("input");
d85 13
a97 5
	 * Historically, the beautify option applies to ex command input read
	 * from a file.  In addition, the first time a ^H was discarded from
	 * the input, a message "^H discarded" was displayed.  We don't bother.
	 */
	LF_INIT(TXT_BACKSLASH | TXT_CNTRLD | TXT_CR | TXT_EXSUSPEND);
d99 1
a99 2
	for (eval = 0;; ++sp->if_lno) {
		/* Set the flags that the user can change. */
a101 2
		else
			LF_CLR(TXT_BEAUTIFY);
a103 2
		else
			LF_CLR(TXT_PROMPT);
d105 1
a105 4
		/*
		 * Get the next command.  Interrupt flag manipulation is
		 * safe because ex_icmd clears them all.
		 */
d107 2
a108 2
		F_SET(sp, S_INTERRUPTIBLE);
		irval = sp->s_get(sp, ep, sp->tiqp, ':', flags);
d110 3
a112 13
			(void)fputc('\n', stdout);
			(void)fflush(stdout);
			goto refresh;
		}
		switch (irval) {
		case INP_OK:
			break;
		case INP_EOF:
		case INP_ERR:
			F_SET(sp, S_EXIT_FORCE);
			/* FALLTHROUGH */
		case INP_INTR:
			goto ret;
d115 3
d119 2
a120 2
		 * If the user entered a carriage return, send ex_cmd()
		 * a separator -- it discards single newlines.
d122 1
a122 1
		tp = sp->tiqp->cqh_first;
d124 5
a128 2
			tp->len = 1;
			tp->lb[0] = ' ';
d130 4
d135 11
a145 6
		saved_mode = F_ISSET(sp, S_SCREENS | S_MAJOR_CHANGE);
		if (ex_icmd(sp, ep,
		    tp->lb, tp->len, 1) && !F_ISSET(sp->gp, G_STDIN_TTY))
			F_SET(sp, S_EXIT_FORCE);
		(void)msg_rpt(sp, 0);
		if (saved_mode != F_ISSET(sp, S_SCREENS | S_MAJOR_CHANGE))
d147 1
d149 14
a162 3
refresh:	if (sp->s_refresh(sp, ep)) {
			eval = 1;
			break;
d165 1
a165 5
ret:	if (sp->if_name != NULL) {
		FREE(sp->if_name, strlen(sp->if_name) + 1);
		sp->if_name = NULL;
	}
	return (ex_end(sp) || eval);
d169 23
a191 2
 * ex_cfile --
 *	Execute ex commands from a file.
d194 1
a194 1
ex_cfile(sp, ep, filename, needsep)
a195 3
	EXF *ep;
	char *filename;
	int needsep;
d197 13
a209 3
	struct stat sb;
	int fd, len, rval;
	char *bp;
d211 2
a212 3
	bp = NULL;
	if ((fd = open(filename, O_RDONLY, 0)) < 0 || fstat(fd, &sb))
		goto err;
d215 3
a217 7
	 * XXX
	 * We'd like to test if the file is too big to malloc.  Since we don't
	 * know what size or type off_t's or size_t's are, what the largest
	 * unsigned integral type is, or what random insanity the local C
	 * compiler will perpetrate, doing the comparison in a portable way
	 * is flatly impossible.  Hope that malloc fails if the file is too
	 * large.
d219 1
a219 3
	MALLOC(sp, bp, char *, (size_t)sb.st_size + 1);
	if (bp == NULL)
		goto err;
d221 4
a224 20
	len = read(fd, bp, (int)sb.st_size);
	if (len == -1 || len != sb.st_size) {
		if (len != sb.st_size)
			errno = EIO;
err:		rval = 1;
		msgq(sp, M_SYSERR, filename);
	} else {
		bp[sb.st_size] = '\0';		/* XXX */

		/*
		 * Run the command.  Messages include file/line information,
		 * but we don't care if we can't get space.
		 */
		sp->if_lno = 1;
		sp->if_name = strdup(filename);
		F_SET(sp, S_VLITONLY);
		rval = ex_icmd(sp, ep, bp, len, needsep);
		F_CLR(sp, S_VLITONLY);
		free(sp->if_name);
		sp->if_name = NULL;
d228 2
a229 2
	 * !!!
	 * THE UNDERLYING EXF MAY HAVE CHANGED.
d231 13
a243 6
	if (bp != NULL)
		FREE(bp, sb.st_size);
	if (fd >= 0)
		(void)close(fd);
	return (rval);
}
d245 2
a246 26
/*
 * ex_icmd --
 *	Call ex_cmd() after turning off interruptible bits.
 */
int
ex_icmd(sp, ep, cmd, len, needsep)
	SCR *sp;
	EXF *ep;
	char *cmd;
	size_t len;
	int needsep;
{
	/*
	 * Ex goes through here for each vi :colon command and for each ex
	 * command, however, globally executed commands don't go through
	 * here, instead, they call ex_cmd directly.  So, reset all of the
	 * interruptible flags now.
	 *
	 * !!!
	 * Previous versions of nvi cleared mapped characters on error.  This
	 * feature was removed when users complained that it wasn't historic
	 * practice.
	 */
	CLR_INTERRUPT(sp);
	return (ex_cmd(sp, ep, cmd, len, needsep));
}
d248 3
a250 13
/* Special command structure for :s as a repeat substitution command. */
static EXCMDLIST const cmd_subagain =
	{"s",		ex_subagain,	E_ADDR2|E_NORC,
	    "s",
	    "[line [,line]] s [cgr] [count] [#lp]",
	    "repeat the last subsitution"};

/* Special command structure for :d[flags]. */
static EXCMDLIST const cmd_del2 = 
	{"delete",	ex_delete,	E_ADDR2|E_AUTOPRINT|E_NORC,
	    "1bca1",
	    "[line [,line]] d[elete][flags] [buffer] [count] [flags]",
	    "delete lines from the file"};
d252 1
a252 32
/*
 * ex_cmd --
 *	Parse and execute a string containing ex commands.
 */
int
ex_cmd(sp, ep, cmd, cmdlen, needsep)
	SCR *sp;
	EXF *ep;
	char *cmd;
	size_t cmdlen;
	int needsep;
{
	enum { NOTSET, NEEDSEP_N, NEEDSEP_NR, NONE } sep;
	EX_PRIVATE *exp;
	EXCMDARG exc;
	EXCMDLIST const *cp;
	MARK cur;
	recno_t lno, num;
	size_t arg1_len, len, save_cmdlen;
	long flagoff;
	u_int saved_mode;
	int blank, ch, cnt, delim, flags, namelen, nl;
	int optnum, uselastcmd, tmp, vi_address;
	char *arg1, *save_cmd, *p, *s, *t;

	/* Init. */
	nl = 0;
	sep = needsep ? NOTSET : NONE;
loop:	if (nl) {
		nl = 0;
		++sp->if_lno;
	}
d254 1
a254 5
	save_cmdlen = 0;

	/* It's possible that we've been interrupted during a command. */
	if (INTERRUPTED(sp))
		return (0);
d257 6
a262 5
	for (blank = 0; cmdlen > 0; ++cmd, --cmdlen)
		if ((ch = *cmd) == '\n')
			++sp->if_lno;
		else if (isblank(ch))
			blank = 1;
d273 3
a275 4
	if (cmdlen != 0 && ch == ':') {
		if (sep == NOTSET)
			sep = NEEDSEP_N;
		while (--cmdlen > 0 && (ch = *++cmd) == ':');
d282 11
a292 11
	 * Historically, there was no escape or delimiter for a comment,
	 * e.g. :"foo|set was a single comment and nothing was output.
	 * Since nvi permits users to escape <newline> characters into
	 * command lines, we have to check for that case.
	 */
	if (cmdlen != 0 && ch == '"') {
		while (--cmdlen > 0 && *++cmd != '\n');
		if (*cmd == '\n') {
			nl = 1;
			++cmd;
			--cmdlen;
d298 2
a299 2
	for (; cmdlen > 0; ++cmd, --cmdlen) {
		ch = *cmd;
d310 4
a313 1
	 * In vi mode, they were ignored.
d315 3
a317 4
	 * In .exrc files this was a serious annoyance, as vi kept trying to
	 * treat them as print commands.  We ignore backward compatibility in
	 * this case, and discard lines containing only <blank> characters from
	 * .exrc files.
d319 9
a327 8
	if (cmdlen == 0 && (!IN_EX_MODE(sp) || ep == NULL || !blank))
		return (0);
		
	/* Initialize the structure passed to underlying functions. */
	memset(&exc, 0, sizeof(EXCMDARG));
	exp = EXP(sp);
	if (argv_init(sp, ep, &exc))
		goto err;
d330 12
a341 11
	 * Check to see if this is a command for which we may want to output
	 * a \r separator instead of a \n.  (The command :1<CR> puts out a \n,
	 * but the command :<CR> puts out a \r.)  If the line is empty except
	 * for <blank>s, <carriage-return> or <eof>, we'll probably want to
	 * output \r.  I don't think there's any way to get <blank> characters
	 * *after* the command character, but this is the ex parser, and I've
	 * been wrong before.
	 */
	if (sep == NOTSET)
		sep = cmdlen == 0 || cmdlen == 1 && cmd[0] == '\004' ?
		    NEEDSEP_NR : NEEDSEP_N;
d344 3
a346 1
	if (ep_range(sp, ep, &exc, &cmd, &cmdlen))
d349 7
a355 4
	/* Skip whitespace. */
	for (; cmdlen > 0; ++cmd, --cmdlen) {
		ch = *cmd;
		if (!isblank(ch))
d380 6
a385 5
	if (cmdlen != 0 && cmd[0] != '|' && cmd[0] != '\n') {
		if (strchr(SINGLE_CHAR_COMMANDS, *cmd)) {
			p = cmd;
			++cmd;
			--cmdlen;
d388 3
a390 2
			for (p = cmd; cmdlen > 0; --cmdlen, ++cmd)
				if (!isalpha(*cmd))
d392 2
a393 2
			if ((namelen = cmd - p) == 0) {
				msgq(sp, M_ERR, "Unknown command name");
d406 3
d410 3
a412 3
		 * Note, adding commands that start with 'd', and match
		 * "delete" up to a l, p, +, - or # character can break
		 * this code.
d414 2
a415 1
		if (p[0] == 'd') {
d418 9
a426 7
			if (s[0] == 'l' || s[0] == 'p' ||
			    s[0] == '+' || s[0] == '-' || s[0] == '#') {
				len = (cmd - p) - (s - p);
				cmd -= len;
				cmdlen += len;
				cp = &cmd_del2;
				goto skip;
d428 5
d443 9
a451 3
		 * Historic vi permitted pretty much anything to follow the
		 * substitute command, e.g. "s/e/E/|s|sgc3p" was fine.  Make
		 * the command "sgc" work.
d453 1
a453 1
		if ((cp = ex_comm_search(p, namelen)) == NULL)
a454 5
			case 's':
				cmd -= namelen - 1;
				cmdlen += namelen - 1;
				cp = &cmd_subagain;
				break;
d457 17
a473 3
					cmd -= namelen - 1;
					cmdlen += namelen - 1;
					cp = &cmds[C_K];
d478 3
a480 2
				msgq(sp, M_ERR,
				    "The %.*s command is unknown", namelen, p);
d484 8
a491 7
		/* Some commands are either not implemented or turned off. */
skip:		if (F_ISSET(cp, E_NOPERM)) {
			msgq(sp, M_ERR,
			    "The %s command is not currently supported",
			    cp->name);
			goto err;
		}
d493 20
a512 5
		/* Some commands aren't okay in globals. */
		if (F_ISSET(sp, S_GLOBAL) && F_ISSET(cp, E_NOGLOBAL)) {
			msgq(sp, M_ERR,
		"The %s command can't be used as part of a global command",
			    cp->name);
d521 5
a525 4
		if ((cp == &cmds[C_SHIFTL] && *p == '<') ||
		    (cp == &cmds[C_SHIFTR] && *p == '>')) {
			for (ch = *p; cmdlen > 0; --cmdlen, ++cmd)
				if (*cmd != ch)
d527 1
a527 1
			if (argv_exp0(sp, ep, &exc, p, cmd - p))
a530 7
		/*
		 * The visual command has a different syntax when called
		 * from ex than when called from a vi colon command.  FMH.
		 */
		if (cp == &cmds[C_VISUAL_EX] && IN_VI_MODE(sp))
			cp = &cmds[C_VISUAL_VI];

d532 7
a538 7
		if (cp == &cmds[C_HASH])
			exp->fdef = E_F_HASH;
		else if (cp == &cmds[C_LIST])
			exp->fdef = E_F_LIST;
		else if (cp == &cmds[C_PRINT])
			exp->fdef = E_F_PRINT;
		uselastcmd = 0;
d541 1
a541 1
		cp = &cmds[C_PRINT];
d544 1
a544 1
		F_SET(&exc, exp->fdef);
d549 2
a550 2
		 * we up the address by one.  (I have not an idea why global
		 * commands are exempted, but it's (ahem) historic practice.
d552 4
a555 4
		if (exc.addrcnt == 0 && !F_ISSET(sp, S_GLOBAL)) {
			exc.addrcnt = 1;
			exc.addr1.lno = sp->lno + 1;
			exc.addr1.cno = sp->cno;
d558 1
a558 1
		uselastcmd = 1;
d569 2
a570 2
		optnum = 1;
		F_SET(&exc, E_F_HASH);
d572 1
a572 4
		optnum = 0;

	/* Initialize local flags to the command flags. */
	LF_INIT(cp->flags);
d574 2
a575 11
	/*
	 * File state must be checked throughout this code, because it is
	 * called when reading the .exrc file and similar things.  There's
	 * this little chicken and egg problem -- if we read the file first,
	 * we won't know how to display it.  If we read/set the exrc stuff
	 * first, we can't allow any command that requires file state.  We
	 * don't have a "reading an rc" bit, because we want the commands
	 * to work when the user source's the rc file later.  Historic vi
	 * generally took the easy way out and dropped core.
 	 */
	if (LF_ISSET(E_NORC) && ep == NULL) {
d577 1
a577 2
	"The %s command requires that a file have already been read in",
		    cp->name);
d581 5
d588 9
a596 9
	 * are the end of the string (cmdlen), or unescaped (by literal next
	 * characters) newline or '|' characters.  As we're past any addresses,
	 * we can now determine how long the command is, so we don't have to
	 * look for all the possible terminations.  There are three exciting
	 * special cases:
	 *
	 * 1: The bang, global, vglobal and the filter versions of the read and
	 *    write commands are delimited by newlines (they can contain shell
	 *    pipes).
d599 2
a600 2
	 * 3: The substitute command takes an RE as its first argument, and
	 *    wants it to be specially delimited.
d603 3
a605 3
	 * next, vi visual, and substitute commands didn't delimit the command.
	 * And, in the filter cases for read and write, and the bang, global
	 * and vglobal commands, they did not delimit the command at all.
d610 1
a610 1
	 *	:substitute s/|/PIPE/
d616 1
a616 1
	 *	:substitute s/a/b/|s/c/d|set
d634 3
a636 3
	save_cmd = cmd;
	if (cp == &cmds[C_EDIT] || cp == &cmds[C_EX] ||
	    cp == &cmds[C_NEXT] || cp == &cmds[C_VISUAL_VI]) {
d642 4
a645 4
		if (cmdlen > 0 && *cmd == '!') {
			++cmd;
			--cmdlen;
			F_SET(&exc, E_FORCE);
d648 1
a648 1
			save_cmd = cmd;
d650 2
a651 2
		for (tmp = 0; cmdlen > 0; --cmdlen, ++cmd)
			if (!isblank(*cmd))
d663 10
a672 8
		if (cmdlen > 0 && *cmd == '+') {
			++cmd;
			--cmdlen;
			for (arg1 = p = cmd; cmdlen > 0; --cmdlen, ++cmd) {
				ch = *cmd;
				if (IS_ESCAPE(sp, ch) && cmdlen > 1) {
					--cmdlen;
					ch = *++cmd;
d677 1
a677 1
			arg1_len = cmd - arg1;
d680 1
a680 1
			save_cmd = cmd;
d682 5
a686 5
	} else if (cp == &cmds[C_BANG] ||
	    cp == &cmds[C_GLOBAL] || cp == &cmds[C_VGLOBAL]) {
		cmd += cmdlen;
		cmdlen = 0;
	} else if (cp == &cmds[C_READ] || cp == &cmds[C_WRITE]) {
d691 2
a692 2
		for (; cmdlen > 0; --cmdlen, ++cmd) {
			ch = *cmd;
d696 3
a698 3
		if (cmdlen > 0 && ch == '!') {
			cmd += cmdlen;
			cmdlen = 0;
d700 1
a700 1
	} else if (cp == &cmds[C_SUBSTITUTE]) {
d705 1
a705 2
		 * into something like ":s g", so use the special substitute
		 * command.
d707 2
a708 2
		for (; cmdlen > 0; --cmdlen, ++cmd)
			if (!isblank(cmd[0]))
d711 5
a715 3
		if (isalnum(cmd[0]) || cmd[0] == '|')
			cp = &cmd_subagain;
		else if (cmdlen > 0) {
d724 10
a733 8
			delim = *cmd;
			++cmd;
			--cmdlen;
			for (cnt = 2; cmdlen > 0 && cnt; --cmdlen, ++cmd)
				if (cmd[0] == '\\' && cmdlen > 1) {
					++cmd;
					--cmdlen;
				} else if (cmd[0] == delim)
d737 1
d748 1
a748 1
	 * '|' characters or literal next characters are stripped as as they're
d751 5
a755 5
	vi_address = cmdlen != 0 && cmd[0] != '\n';
	for (p = cmd, cnt = 0; cmdlen > 0; --cmdlen, ++cmd) {
		ch = cmd[0];
		if (IS_ESCAPE(sp, ch) && cmdlen > 1) {
			tmp = cmd[1];
d757 6
a762 4
				if (tmp == '\n')
					++sp->if_lno;
				--cmdlen;
				++cmd;
d768 2
a769 2
				nl = 1;
			--cmdlen;
d779 5
a783 5
	p = cmd + 1;
	cmd = save_cmd;
	save_cmd = p;
	save_cmdlen = cmdlen;
	cmdlen = ((save_cmd - cmd) - 1) - cnt;
d786 2
a787 1
	 * !!!
d794 2
a795 2
	if (cp == &cmds[C_SET])
		for (p = cmd, len = cmdlen; len > 0; --len, ++p)
d810 2
a811 2
	 * Note, we also add the E_ZERO flag to the command flags, for the case
	 * where the 0 address is only valid if it's a default address.
d817 1
a817 1
	switch (LF_ISSET(E_ADDR1|E_ADDR2|E_ADDR2_ALL|E_ADDR2_NONE)) {
d819 1
a819 1
		switch (exc.addrcnt) {
d821 4
a824 4
			exc.addrcnt = 1;
			F_SET(&exc, E_ADDRDEF);
			if (LF_ISSET(E_ZERODEF)) {
				if (file_lline(sp, ep, &lno))
d827 2
a828 2
					exc.addr1.lno = 0;
					LF_SET(E_ZERO);
d830 1
a830 1
					exc.addr1.lno = sp->lno;
d832 2
a833 2
				exc.addr1.lno = sp->lno;
			exc.addr1.cno = sp->cno;
d838 2
a839 2
			exc.addrcnt = 1;
			exc.addr1 = exc.addr2;
d843 1
a843 1
		if (exc.addrcnt == 0)		/* Default to nothing. */
d845 1
a845 1
		goto two;
d847 11
a857 8
		if (exc.addrcnt == 0) {		/* Default entire/empty file. */
			exc.addrcnt = 2;
			F_SET(&exc, E_ADDRDEF);
			if (file_lline(sp, ep, &exc.addr2.lno))
				goto err;
			if (LF_ISSET(E_ZERODEF) && exc.addr2.lno == 0) {
				exc.addr1.lno = 0;
				LF_SET(E_ZERO);
d859 3
a861 3
				exc.addr1.lno = 1;
			exc.addr1.cno = exc.addr2.cno = 0;
			F_SET(&exc, E_ADDR2_ALL);
d866 1
a866 1
two:		switch (exc.addrcnt) {
d868 5
a872 4
			exc.addrcnt = 2;
			F_SET(&exc, E_ADDRDEF);
			if (LF_ISSET(E_ZERODEF) && sp->lno == 1) {
				if (file_lline(sp, ep, &lno))
d875 2
a876 2
					exc.addr1.lno = exc.addr2.lno = 0;
					LF_SET(E_ZERO);
d878 2
a879 1
					exc.addr1.lno = exc.addr2.lno = sp->lno;
d881 2
a882 2
				exc.addr1.lno = exc.addr2.lno = sp->lno;
			exc.addr1.cno = exc.addr2.cno = sp->cno;
d885 2
a886 2
			exc.addrcnt = 2;
			exc.addr2 = exc.addr1;
d893 1
a893 1
		if (exc.addrcnt)		/* Error. */
d903 6
a908 6
	if (cp == &cmds[C_SCROLL]) {
		exc.addrcnt = 2;
		exc.addr1.lno = sp->lno + 1;
		exc.addr2.lno = sp->lno + O_VAL(sp, O_SCROLL);
		exc.addr1.cno = exc.addr2.cno = sp->cno;
		if (file_lline(sp, ep, &lno))
d910 2
a911 2
		if (lno != 0 && lno > sp->lno && exc.addr2.lno > lno)
			exc.addr2.lno = lno;
d914 2
a915 2
	flagoff = 0;
	for (p = cp->syntax; *p != '\0'; ++p) {
d922 4
a925 4
			if (cmdlen > 0 && *cmd == '!') {
				++cmd;
				--cmdlen;
				F_SET(&exc, E_FORCE);
d931 2
a932 2
		for (; cmdlen > 0; --cmdlen, ++cmd)
			if (!isblank(*cmd))
d934 1
a934 11

		/*
		 * Quit when reach the end of the command, unless it's a
		 * command that does its own parsing, in which case we want
		 * to build a reasonable argv for it.  This code guarantees
		 * that there will be an argv when the function gets called,
		 * so the correct test is for a length of 0, not for the
		 * argc > 0.  Since '!' can precede commands that do their
		 * own parsing, we have to have already handled it.
		 */
		if (cmdlen == 0 && *p != 'S' && *p != 's')
d949 2
a950 2
			for (; cmdlen; --cmdlen, ++cmd)
				switch (*cmd) {
d952 1
a952 1
					++flagoff;
d955 2
a956 1
					--flagoff;
d959 3
a961 3
					optnum = 0;
					F_SET(&exc, E_F_HASH);
					exp->fdef |= E_F_HASH;
d964 2
a965 2
					F_SET(&exc, E_F_LIST);
					exp->fdef |= E_F_LIST;
d968 2
a969 2
					F_SET(&exc, E_F_PRINT);
					exp->fdef |= E_F_PRINT;
d972 1
a972 1
					goto end1;
d974 1
a974 1
end1:			break;
d977 2
a978 2
			for (; cmdlen; --cmdlen, ++cmd)
				switch (*cmd) {
d980 1
a980 1
					F_SET(&exc, E_F_DASH);
d983 1
a983 1
					F_SET(&exc, E_F_DOT);
d986 1
a986 1
					F_SET(&exc, E_F_PLUS);
d989 1
a989 1
					F_SET(&exc, E_F_CARAT);
d993 1
a993 1
						F_SET(&exc, E_F_EQUAL);
d998 1
a998 1
					goto end2;
d1000 1
a1000 1
end2:			break;
d1010 2
a1011 1
			if ((cmd[0] == '+' || cmd[0] == '-' || cmd[0] == '#') &&
d1020 5
a1024 5
			if (!isdigit(cmd[0])) {
				exc.buffer = *cmd;
				++cmd;
				--cmdlen;
				F_SET(&exc, E_BUFFER);
d1030 2
a1031 2
			if (!isdigit(*cmd) &&
			    (*p != '+' || (*cmd != '+' && *cmd != '-')))
d1034 11
a1044 6
			if (*cmd == '-')
				F_SET(&exc, E_COUNT_NEG);
			else if (*cmd == '+')
				F_SET(&exc, E_COUNT_POS);
/* 8-bit XXX */		if ((lno = strtol(cmd, &t, 10)) == 0 && *p != '0') {
				msgq(sp, M_ERR, "Count may not be zero");
d1047 3
a1049 2
			cmdlen -= (t - cmd);
			cmd = t;
d1051 1
a1051 1
			 * Count as address offsets occur in commands taking
d1060 2
a1061 2
				exc.addr1 = exc.addr2;
				exc.addr2.lno = exc.addr1.lno + lno - 1;
d1063 2
a1064 2
				exc.count = lno;
			F_SET(&exc, E_COUNT);
d1067 1
a1067 2
			if (argv_exp2(sp, ep,
			    &exc, cmd, cmdlen, cp == &cmds[C_BANG]))
d1069 1
a1069 1
			goto countchk;
d1071 11
a1081 1
			if (ep_line(sp, ep, &cur, &cmd, &cmdlen, &tmp))
d1083 1
d1085 3
a1087 3
			if (!tmp) {
				msgq(sp, M_ERR,
				     "%s: bad line specification", cmd);
d1090 6
a1095 5
			/* The line must exist for these commands. */
			if (file_lline(sp, ep, &lno))
				goto err;
			if (cur.lno > lno) {
				badlno(sp, lno);
d1098 1
a1098 1
			exc.lineno = cur.lno;
d1101 7
a1107 4
			if (argv_exp1(sp, ep,
			    &exc, cmd, cmdlen, cp == &cmds[C_BANG]))
				goto err;
			goto addr2;
d1109 1
a1109 1
			if (argv_exp0(sp, ep, &exc, cmd, cmdlen))
d1111 1
a1111 1
			goto addr2;
d1117 2
a1118 2
			 * character.  Quoting characters are stripped
			 * here since they are no longer useful.
d1122 7
a1128 5
			for (p = t = cmd; cmdlen > 0; --cmdlen, ++cmd) {
				ch = *cmd;
				if (IS_ESCAPE(sp, ch) && cmdlen > 1) {
					--cmdlen;
					*p++ = *++cmd;
d1130 2
a1131 2
					++cmd;
					--cmdlen;
d1136 1
a1136 1
			if (argv_exp0(sp, ep, &exc, t, p - t))
d1140 3
a1142 2
			for (; cmdlen > 0; --cmdlen, ++cmd) {
				ch = *cmd;
d1146 1
a1146 1
			if (cmdlen == 0)
d1150 7
a1156 5
			for (p = t = cmd; cmdlen > 0; --cmdlen, ++cmd, ++p) {
				ch = *cmd;
				if (IS_ESCAPE(sp, ch) && cmdlen > 1) {
					--cmdlen;
					*p = *++cmd;
d1160 1
a1160 1
			if (argv_exp0(sp, ep, &exc, t, p - t))
d1162 1
a1162 1
			goto addr2;
d1164 1
a1164 1
			if (argv_exp3(sp, ep, &exc, cmd, cmdlen))
d1166 1
a1166 1
countchk:		if (*++p != 'N') {		/* N */
d1172 1
a1172 1
				num = *p - '0';
d1174 1
a1174 1
				    exp->argsoff != num)
d1177 1
a1177 1
			goto addr2;
d1180 2
a1181 2
			    "Internal syntax table error (%s: %c)",
			    cp->name, *p);
d1186 2
a1187 2
	for (; cmdlen; --cmdlen) {
		ch = *cmd++;
d1193 2
a1194 2
	 * There shouldn't be anything left, and no more required
	 * fields, i.e neither 'l' or 'r' in the syntax string.
d1196 2
a1197 2
	if (cmdlen || strpbrk(p, "lr")) {
usage:		msgq(sp, M_ERR, "Usage: %s", cp->usage);
d1201 11
a1211 2
	/* Verify that the addresses are legal. */
addr2:	switch (exc.addrcnt) {
a1212 2
		if (file_lline(sp, ep, &lno))
			goto err;
d1221 14
a1234 5
		if (exc.addr2.lno > lno)
			if (F_ISSET(&exc, E_COUNT))
				exc.addr2.lno = lno;
			else {
				badlno(sp, lno);
d1239 9
a1247 17
		num = exc.addr1.lno;
		/*
		 * If it's a "default vi command", zero is okay.  Historic
		 * vi allowed this, note, it's also the hack that allows
		 * "vi +100 nonexistent_file" to work.
		 */
		if (num == 0 && (IN_EX_MODE(sp) || uselastcmd != 1) &&
		    !LF_ISSET(E_ZERO)) {
			msgq(sp, M_ERR,
			    "The %s command doesn't permit an address of 0",
			    cp->name);
			goto err;
		}
		if (file_lline(sp, ep, &lno))
			goto err;
		if (num > lno) {
			badlno(sp, lno);
d1259 4
d1266 3
a1268 2
	if (IN_VI_MODE(sp) && uselastcmd && vi_address == 0) {
		switch (exc.addrcnt) {
d1270 7
a1276 2
			sp->lno = exc.addr2.lno ? exc.addr2.lno : 1;
			sp->cno = exc.addr2.cno;
d1279 7
a1285 2
			sp->lno = exc.addr1.lno ? exc.addr1.lno : 1;
			sp->cno = exc.addr1.cno;
d1288 2
a1289 2
		cmd = save_cmd;
		cmdlen = save_cmdlen;
d1298 1
a1298 1
	if (F_ISSET(exp, EX_ABSMARK)) {
d1301 2
a1302 2
		F_CLR(exp, EX_ABSMARK);
		if (mark_set(sp, ep, ABSMARK1, &cur, 1))
d1306 2
a1307 23
	/* Final setup for the command. */
	exc.cmd = cp;

#if defined(DEBUG) && 0
	TRACE(sp, "ex_cmd: %s", exc.cmd->name);
	if (exc.addrcnt > 0) {
		TRACE(sp, "\taddr1 %d", exc.addr1.lno);
		if (exc.addrcnt > 1)
			TRACE(sp, " addr2: %d", exc.addr2.lno);
		TRACE(sp, "\n");
	}
	if (exc.lineno)
		TRACE(sp, "\tlineno %d", exc.lineno);
	if (exc.flags)
		TRACE(sp, "\tflags %0x", exc.flags);
	if (F_ISSET(&exc, E_BUFFER))
		TRACE(sp, "\tbuffer %c", exc.buffer);
	TRACE(sp, "\n");
	if (exc.argc) {
		for (cnt = 0; cnt < exc.argc; ++cnt)
			TRACE(sp, "\targ %d: {%s}", cnt, exc.argv[cnt]);
		TRACE(sp, "\n");
	}
a1308 3
	/* Clear autoprint flag. */
	F_CLR(exp, EX_AUTOPRINT);

d1310 1
a1310 1
	if (IN_EX_MODE(sp))
d1317 2
a1318 2
	if (ep != NULL && !F_ISSET(sp, S_GLOBAL))
		(void)log_cursor(sp, ep);
d1329 12
a1340 29
	 * special commands, we erase the prompt character with a '\r'.  Else,
	 * we put out a newline character to separate the command from the
	 * output from the command.  It's OK if vi calls us -- we won't be in
	 * ex mode so we'll do nothing.
	 *
	 * !!!
	 * Historically, ex only put out a \r, so, if the displayed line was
	 * only a single character long, and <eof> was represented as ^D, the
	 * output wouldn't overwrite the user's input.  Sex currently doesn't
	 * display the <eof> character if it's going to be the scroll command,
	 * i.e. if it's the first non-<blank> character in the line.  If sex
	 * is changed to run in cooked mode, i.e. <eof> is displayed, this code
	 * will have to overwrite it.  We also don't treat lines with extra
	 * prompt characters as empty -- it's not worth the effort since we'd
	 * have to overwrite some indeterminate number of columns with spaces
	 * to clean up.  For now, put out enough spaces to overwrite the prompt.
	 */
	if (sep != NONE) {
		if (ep != NULL &&
		    IN_EX_MODE(sp) && F_ISSET(sp->gp, G_STDIN_TTY))
			if (sep == NEEDSEP_NR &&
			    (uselastcmd || cp == &cmds[C_SCROLL])) {
				(void)putchar('\r');
				for (len = KEY_LEN(sp, PROMPTCHAR); len--;)
					(void)putchar(' ');
				(void)putchar('\r');
			} else
				(void)putchar('\n');
		sep = NONE;
d1343 9
a1351 5
	/* Save the current mode. */
	saved_mode = F_ISSET(sp, S_SCREENS | S_MAJOR_CHANGE);

	/* Do the command. */
	if (cp->fn(sp, ep, &exc))
d1353 1
d1356 5
a1360 5
	/* Make sure no function left the temporary space locked. */
	if (F_ISSET(sp->gp, G_TMP_INUSE)) {
		F_CLR(sp->gp, G_TMP_INUSE);
		msgq(sp, M_ERR, "Error: ex: temporary buffer not released");
		goto err;
d1363 13
a1375 47
	if (saved_mode != F_ISSET(sp, S_SCREENS | S_MAJOR_CHANGE)) {
		/*
		 * Only here if the mode of the underlying file changed, e.g.
		 * the user switched files or is exiting.  Two things that we
		 * might have to save: first, any "+cmd" field set up for an
		 * ex/edit command will have to be saved for later, also, any
		 * part of the current ex command that hasn't been executed
		 * yet.  For example:
		 *
		 *	:edit +25 file.c|s/abc/ABC/|1
		 *
		 * !!!
		 * The historic vi just hung, of course; nvi handles it by
		 * pushing the keys onto the tty queue.  Since the commands
		 * are intended as ex commands, add additional characters
		 * to make it all work if we're switching modes to vi.  Also,
		 * + commands were oriented to the last line in the file,
		 * historically, make the cursor start out there.
		 *
		 * For the fun of it, if you want to see if a vi clone got the
		 * ex argument parsing right, try:
 		 *
		 *	echo 'foo|bar' > file1; echo 'foo/bar' > file2;
		 *	vi
		 *	:edit +1|s/|/PIPE/|w file1| e file2|1 | s/\//SLASH/|wq
		 */
		if (arg1_len == 0 && save_cmdlen == 0)
			return (0);
		if (term_push(sp, "\n", 1, 0))
			goto err;
		if (save_cmdlen != 0)
			if (term_push(sp, save_cmd, save_cmdlen, 0))
				goto err;
		if (arg1 != NULL) {
			if (IN_VI_MODE(sp) && save_cmdlen != 0 &&
			    term_push(sp, "|", 1, 0))
				goto err;
			if (term_push(sp, arg1, arg1_len, 0))
				goto err;
			if (file_lline(sp, ep, &sp->frp->lno))
				goto err;
			F_SET(sp->frp, FR_CURSORSET);
		}
		if (IN_VI_MODE(sp) && term_push(sp, ":", 1, 0))
			goto err;
		return (0);
	}
d1382 11
a1392 10
	 * May not match historic practice (I've never been able to completely
	 * figure it out.)  For example, the '=' command from vi mode often
	 * got the offset wrong, and complained it was too large, but didn't
	 * seem to have a problem with the cursor.  If anyone complains, ask
	 * them how it's supposed to work, they probably know.
	 */
	if (ep != NULL && (flagoff += exc.flagoff)) {
		if (flagoff < 0) {
			if (sp->lno <= -flagoff) {
				msgq(sp, M_ERR, "Flag offset before line 1");
d1396 2
a1397 1
			if (file_lline(sp, ep, &lno))
d1399 4
a1402 2
			if (sp->lno + flagoff > lno) {
				msgq(sp, M_ERR, "Flag offset past end-of-file");
d1406 1
a1406 1
		sp->lno += flagoff;
d1410 4
a1413 2
	 * If the command was successful and we're in ex command mode, we
	 * may want to display a line.  Make sure there's a line to display.
d1415 1
a1415 2
	if (ep != NULL &&
	    IN_EX_MODE(sp) && !F_ISSET(sp, S_GLOBAL) && sp->lno != 0) {
d1420 2
a1421 2
		if (LF_ISSET(E_F_PRCLEAR))
			F_CLR(&exc, E_F_HASH | E_F_LIST | E_F_PRINT);
d1423 3
a1425 3
		/* If hash only set because of the number option, discard it. */
		if (optnum)
			F_CLR(&exc, E_F_HASH);
d1428 3
a1430 4
		 * If there was an explicit flag to display the new cursor
		 * line, or we're in ex mode, autoprint is set, and a change
		 * was made, display the line.  If any print flags set use
		 * them, otherwise default to print.
d1432 12
a1443 5
		LF_INIT(F_ISSET(&exc, E_F_HASH | E_F_LIST | E_F_PRINT));
		if (!LF_ISSET(E_F_HASH | E_F_LIST | E_F_PRINT) &&
		    O_ISSET(sp, O_AUTOPRINT) &&
		    (F_ISSET(exp, EX_AUTOPRINT) || F_ISSET(cp, E_AUTOPRINT)))
			LF_INIT(E_F_PRINT);
d1445 29
a1473 6
		if (LF_ISSET(E_F_HASH | E_F_LIST | E_F_PRINT)) {
			memset(&exc, 0, sizeof(EXCMDARG));
			exc.addrcnt = 2;
			exc.addr1.lno = exc.addr2.lno = sp->lno;
			exc.addr1.cno = exc.addr2.cno = sp->cno;
			(void)ex_print(sp, ep, &exc.addr1, &exc.addr2, flags);
d1475 65
a1541 2
	cmd = save_cmd;
	cmdlen = save_cmdlen;
d1545 14
a1558 20
	/*
	 * If we haven't put out a separator line, do it now.  For more
	 * detailed comments, see above.
	 */
err:	if (sep != NONE &&
	    ep != NULL && IN_EX_MODE(sp) && F_ISSET(sp->gp, G_STDIN_TTY))
		(void)fputc('\n', stdout);
	/*
	 * On error, we discard any keys we have left, as well as any keys
	 * that were mapped.  The test of save_cmdlen isn't necessarily
	 * correct.  If we fail early enough we don't know if the entire
	 * string was a single command or not.  Try and guess, it's useful
	 * to know if part of the command was discarded.
	 */
	if (save_cmdlen == 0)
		for (; cmdlen; --cmdlen) {
			ch = *cmd++;
			if (IS_ESCAPE(sp, ch) && cmdlen > 1) {
				--cmdlen;
				++cmd;
d1560 2
a1561 2
				if (cmdlen > 1)
					save_cmdlen = 1;
d1565 20
a1584 10
	if (save_cmdlen != 0)
		msgq(sp, M_ERR,
		    "Ex command failed: remaining command input discarded");
	/*
	 * !!!
	 * Previous versions of nvi cleared mapped characters on error.  This
	 * feature was removed when users complained that it wasn't historic
	 * practice.
	 */
	return (1);
d1588 4
a1591 2
 * ep_range --
 *	Get a line range for ex commands.
d1593 2
a1594 2
static int
ep_range(sp, ep, excp, cmdp, cmdlenp)
d1596 2
a1597 4
	EXF *ep;
	EXCMDARG *excp;
	char **cmdp;
	size_t *cmdlenp;
d1599 5
a1603 4
	MARK cur, savecursor;
	size_t cmdlen;
	int savecursor_set, tmp;
	char *cmd;
d1605 1
a1605 7
	/* Percent character is all lines in the file. */
	cmd = *cmdp;
	cmdlen = *cmdlenp;
	if (*cmd == '%') {
		excp->addr1.lno = 1;
		if (file_lline(sp, ep, &excp->addr2.lno))
			return (1);
d1607 36
a1642 15
		/* If an empty file, then the first line is 0, not 1. */
		if (excp->addr2.lno == 0)
			excp->addr1.lno = 0;
		excp->addr1.cno = excp->addr2.cno = 0;
		excp->addrcnt = 2;

		++*cmdp;
		--*cmdlenp;
		return (0);
	}

	/* Parse comma or semi-colon delimited line specs. */
	for (savecursor_set = 0, excp->addrcnt = 0; cmdlen > 0;)
		switch (*cmd) {
		case ';':		/* Semi-colon delimiter. */
d1644 8
a1651 4
			 * Comma delimiters delimit; semi-colon delimiters
			 * change the current address for the 2nd address
			 * to be the first address.  Trailing or multiple
			 * delimiters are discarded.
d1653 4
a1656 18
			if (excp->addrcnt == 0)
				goto done;
			if (!savecursor_set) {
				savecursor.lno = sp->lno;
				savecursor.cno = sp->cno;
				sp->lno = excp->addr1.lno;
				sp->cno = excp->addr1.cno;
				savecursor_set = 1;
			}
			++cmd;
			--cmdlen;
			break;
		case ',':		/* Comma delimiter. */
			/* If no addresses yet, defaults to ".". */
			if (excp->addrcnt == 0) {
				excp->addr1.lno = sp->lno;
				excp->addr1.cno = sp->cno;
				excp->addrcnt = 1;
d1658 51
d1712 2
a1713 2
			++cmd;
			--cmdlen;
d1716 2
a1717 1
			if (ep_line(sp, ep, &cur, &cmd, &cmdlen, &tmp))
d1719 10
a1728 8
			if (!tmp)
				goto done;

			/*
			 * Extra addresses are discarded, starting with
			 * the first.
			 */
			switch (excp->addrcnt) {
d1730 2
a1731 2
				excp->addr1 = cur;
				excp->addrcnt = 1;
d1734 2
a1735 2
				excp->addr2 = cur;
				excp->addrcnt = 2;
d1738 2
a1739 2
				excp->addr1 = excp->addr2;
				excp->addr2 = cur;
d1742 1
d1747 25
a1771 10
	 * XXX
	 * This is probably not the right behavior for savecursor --
	 * need to figure out what the historical ex did for ";,;,;5p"
	 * or similar stupidity.
	 */
done:	if (savecursor_set) {
		sp->lno = savecursor.lno;
		sp->cno = savecursor.cno;
	}
	if (excp->addrcnt == 2 && excp->addr2.lno < excp->addr1.lno) {
d1773 2
a1774 2
		    "The second address is smaller than the first");
		return (1);
a1775 2
	*cmdp = cmd;
	*cmdlenp = cmdlen;
d1780 2
a1781 1
 * Get a single line address specifier.
d1792 2
a1793 1
 * This is not exactly historic practice, although it's fairly close.
d1796 1
a1796 1
ep_line(sp, ep, cur, cmdp, cmdlenp, addr_found)
d1798 3
a1800 5
	EXF *ep;
	MARK *cur;
	char **cmdp;
	size_t *cmdlenp;
	int *addr_found;
d1802 1
d1804 5
a1808 6
	MARK m;
	long total;
	u_int flags;
	size_t cmdlen;
	int (*sf) __P((SCR *, EXF *, MARK *, MARK *, char *, char **, u_int *));
	char *cmd, *endp;
d1810 1
a1811 1
	*addr_found = 0;
d1813 11
a1823 3
	cmd = *cmdp;
	cmdlen = *cmdlenp;
	switch (*cmd) {
d1825 2
a1826 2
		*addr_found = 1;
		F_SET(exp, EX_ABSMARK);
d1828 2
a1829 2
		cur->cno = 0;
		if (file_lline(sp, ep, &cur->lno))
d1831 2
a1832 2
		++cmd;
		--cmdlen;
d1836 2
a1837 2
		*addr_found = 1;
		F_SET(exp, EX_ABSMARK);
d1839 14
a1852 4
		cur->cno = 0;
/* 8-bit XXX */	cur->lno = strtol(cmd, &endp, 10);
		cmdlen -= (endp - cmd);
		cmd = endp;
d1855 2
a1856 2
		*addr_found = 1;
		F_SET(exp, EX_ABSMARK);
d1858 8
a1865 3
		if (cmdlen == 1) {
			msgq(sp, M_ERR, "No mark name supplied");
			return (1);
d1867 2
a1868 4
		if (mark_get(sp, ep, cmd[1], cur))
			return (1);
		cmd += 2;
		cmdlen -= 2;
d1877 5
a1881 3
		if (cmdlen < 2 || cmd[1] != '/' && cmd[1] != '?') {
			msgq(sp, M_ERR, "\\ not followed by / or ?");
			return (1);
d1883 3
a1885 3
		++cmd;
		--cmdlen;
		sf = cmd[0] == '/' ? f_search : b_search;
a1891 1
search:		F_SET(exp, EX_ABSMARK);
d1893 6
a1898 4
		if (ep == NULL) {
			msgq(sp, M_ERR,
	"A search address requires that a file have already been read in");
			return (1);
d1900 7
a1906 10
		*addr_found = 1;
		m.lno = sp->lno;
		m.cno = sp->cno;
		flags = SEARCH_MSG | SEARCH_PARSE | SEARCH_SET;
		if (sf(sp, ep, &m, &m, cmd, &endp, &flags))
			return (1);
		cur->lno = m.lno;
		cur->cno = m.cno;
		cmdlen -= (endp - cmd);
		cmd = endp;
d1909 2
a1910 2
		*addr_found = 1;
		cur->cno = sp->cno;
d1914 1
a1914 1
			if (file_lline(sp, ep, &cur->lno))
d1916 2
a1917 2
			if (cur->lno != 0)
				cur->lno = 1;
d1919 14
a1932 3
			cur->lno = sp->lno;
		++cmd;
		--cmdlen;
d1936 119
d2056 15
a2070 9
	 * Evaluate any offset.  Offsets are +/- any number, or any number
	 * of +/- signs, or any combination thereof.  If no address found
	 * yet, offset is relative to ".".
	 */
	for (total = 0; cmdlen > 0 && (cmd[0] == '-' || cmd[0] == '+');) {
		if (!*addr_found) {
			cur->lno = sp->lno;
			cur->cno = sp->cno;
			*addr_found = 1;
d2073 39
a2111 8
		if (cmdlen > 1 && isdigit(cmd[1])) {
/* 8-bit XXX */		total += strtol(cmd, &endp, 10);
			cmdlen -= (endp - cmd);
			cmd = endp;
		} else {
			total += cmd[0] == '-' ? -1 : 1;
			--cmdlen;
			++cmd;
d2113 4
d2119 42
a2160 5
	if (*addr_found) {
		if (total < 0 && -total > cur->lno) {
			msgq(sp, M_ERR,
			    "Reference to a line number less than 0");
			return (1);
d2162 2
a2163 4
		cur->lno += total;

		*cmdp = cmd;
		*cmdlenp = cmdlen;
d2165 1
d2170 23
d2194 5
a2198 3
 *	The vi text input routine needs to know if ex thinks this is
 *	an [un]abbreviate command, so it can turn off abbreviations.
 *	Usual ranting in the vi/v_ntext:txt_abbrev() routine.
d2213 5
a2217 3
 *	The vi text input routine needs to know if ex thinks this is
 *	an unmap command, so it can turn off input mapping.  Usual
 *	ranting in the vi/v_ntext:txt_unmap() routine.
d2237 5
a2241 1
static __inline EXCMDLIST const *
d2259 73
d2333 1
a2333 1
badlno(sp, lno)
d2335 1
a2335 1
	recno_t lno;
d2337 16
a2352 5
	if (lno == 0)
		msgq(sp, M_ERR, "Illegal address: the file is empty");
	else
		msgq(sp, M_ERR, "Illegal address: only %lu line%s in the file",
		    lno, lno > 1 ? "s" : "");
d2354 1
@


1.5.2.1
log
@file ex.c was added on branch netbsd-1-0 on 1994-08-17 20:12:05 +0000
@
text
@d1 1866
@


1.5.2.2
log
@clean up import.
@
text
@a0 1866
/*-
 * Copyright (c) 1992, 1993, 1994
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef lint
static char sccsid[] = "@@(#)ex.c	8.157 (Berkeley) 8/17/94";
#endif /* not lint */

#include <sys/types.h>
#include <sys/queue.h>
#include <sys/stat.h>
#include <sys/time.h>

#include <bitstring.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>

#include "compat.h"
#include <db.h>
#include <regex.h>

#include "vi.h"
#include "excmd.h"

static void	badlno __P((SCR *, recno_t));
static __inline EXCMDLIST const *
		ex_comm_search __P((char *, size_t));
static int	ep_line __P((SCR *, EXF *, MARK *, char **, size_t *, int *));
static int	ep_range __P((SCR *, EXF *, EXCMDARG *, char **, size_t *));

/*
 * ex --
 *	Read an ex command and execute it.
 */
int
ex(sp, ep)
	SCR *sp;
	EXF *ep;
{
	enum input irval;
	TEXT *tp;
	u_int flags, saved_mode;
	int eval;

	if (ex_init(sp, ep))
		return (1);

	if (sp->s_refresh(sp, ep))
		return (ex_end(sp));

	/* If reading from a file, messages should have line info. */
	if (!F_ISSET(sp->gp, G_STDIN_TTY)) {
		sp->if_lno = 1;
		sp->if_name = strdup("input");
	}

	/*
	 * !!!
	 * Historically, the beautify option applies to ex command input read
	 * from a file.  In addition, the first time a ^H was discarded from
	 * the input, a message "^H discarded" was displayed.  We don't bother.
	 */
	LF_INIT(TXT_BACKSLASH | TXT_CNTRLD | TXT_CR | TXT_EXSUSPEND);

	for (eval = 0;; ++sp->if_lno) {
		/* Set the flags that the user can change. */
		if (O_ISSET(sp, O_BEAUTIFY))
			LF_SET(TXT_BEAUTIFY);
		else
			LF_CLR(TXT_BEAUTIFY);
		if (O_ISSET(sp, O_PROMPT))
			LF_SET(TXT_PROMPT);
		else
			LF_CLR(TXT_PROMPT);

		/*
		 * Get the next command.  Interrupt flag manipulation is
		 * safe because ex_icmd clears them all.
		 */
		CLR_INTERRUPT(sp);
		F_SET(sp, S_INTERRUPTIBLE);
		irval = sp->s_get(sp, ep, sp->tiqp, ':', flags);
		if (INTERRUPTED(sp)) {
			(void)fputc('\n', stdout);
			(void)fflush(stdout);
			goto refresh;
		}
		switch (irval) {
		case INP_OK:
			break;
		case INP_EOF:
		case INP_ERR:
			F_SET(sp, S_EXIT_FORCE);
			/* FALLTHROUGH */
		case INP_INTR:
			goto ret;
		}

		/*
		 * If the user entered a carriage return, send ex_cmd()
		 * a separator -- it discards single newlines.
		 */
		tp = sp->tiqp->cqh_first;
		if (tp->len == 0) {
			tp->len = 1;
			tp->lb[0] = ' ';
		}

		saved_mode = F_ISSET(sp, S_SCREENS | S_MAJOR_CHANGE);
		if (ex_icmd(sp, ep,
		    tp->lb, tp->len, 1) && !F_ISSET(sp->gp, G_STDIN_TTY))
			F_SET(sp, S_EXIT_FORCE);
		(void)msg_rpt(sp, 0);
		if (saved_mode != F_ISSET(sp, S_SCREENS | S_MAJOR_CHANGE))
			break;

refresh:	if (sp->s_refresh(sp, ep)) {
			eval = 1;
			break;
		}
	}
ret:	if (sp->if_name != NULL) {
		FREE(sp->if_name, strlen(sp->if_name) + 1);
		sp->if_name = NULL;
	}
	return (ex_end(sp) || eval);
}

/*
 * ex_cfile --
 *	Execute ex commands from a file.
 */
int
ex_cfile(sp, ep, filename, needsep)
	SCR *sp;
	EXF *ep;
	char *filename;
	int needsep;
{
	struct stat sb;
	int fd, len, rval;
	char *bp;

	bp = NULL;
	if ((fd = open(filename, O_RDONLY, 0)) < 0 || fstat(fd, &sb))
		goto err;

	/*
	 * XXX
	 * We'd like to test if the file is too big to malloc.  Since we don't
	 * know what size or type off_t's or size_t's are, what the largest
	 * unsigned integral type is, or what random insanity the local C
	 * compiler will perpetrate, doing the comparison in a portable way
	 * is flatly impossible.  Hope that malloc fails if the file is too
	 * large.
	 */
	MALLOC(sp, bp, char *, (size_t)sb.st_size + 1);
	if (bp == NULL)
		goto err;

	len = read(fd, bp, (int)sb.st_size);
	if (len == -1 || len != sb.st_size) {
		if (len != sb.st_size)
			errno = EIO;
err:		rval = 1;
		msgq(sp, M_SYSERR, filename);
	} else {
		bp[sb.st_size] = '\0';		/* XXX */

		/*
		 * Run the command.  Messages include file/line information,
		 * but we don't care if we can't get space.
		 */
		sp->if_lno = 1;
		sp->if_name = strdup(filename);
		F_SET(sp, S_VLITONLY);
		rval = ex_icmd(sp, ep, bp, len, needsep);
		F_CLR(sp, S_VLITONLY);
		free(sp->if_name);
		sp->if_name = NULL;
	}

	/*
	 * !!!
	 * THE UNDERLYING EXF MAY HAVE CHANGED.
	 */
	if (bp != NULL)
		FREE(bp, sb.st_size);
	if (fd >= 0)
		(void)close(fd);
	return (rval);
}

/*
 * ex_icmd --
 *	Call ex_cmd() after turning off interruptible bits.
 */
int
ex_icmd(sp, ep, cmd, len, needsep)
	SCR *sp;
	EXF *ep;
	char *cmd;
	size_t len;
	int needsep;
{
	/*
	 * Ex goes through here for each vi :colon command and for each ex
	 * command, however, globally executed commands don't go through
	 * here, instead, they call ex_cmd directly.  So, reset all of the
	 * interruptible flags now.
	 *
	 * !!!
	 * Previous versions of nvi cleared mapped characters on error.  This
	 * feature was removed when users complained that it wasn't historic
	 * practice.
	 */
	CLR_INTERRUPT(sp);
	return (ex_cmd(sp, ep, cmd, len, needsep));
}

/* Special command structure for :s as a repeat substitution command. */
static EXCMDLIST const cmd_subagain =
	{"s",		ex_subagain,	E_ADDR2|E_NORC,
	    "s",
	    "[line [,line]] s [cgr] [count] [#lp]",
	    "repeat the last subsitution"};

/* Special command structure for :d[flags]. */
static EXCMDLIST const cmd_del2 = 
	{"delete",	ex_delete,	E_ADDR2|E_AUTOPRINT|E_NORC,
	    "1bca1",
	    "[line [,line]] d[elete][flags] [buffer] [count] [flags]",
	    "delete lines from the file"};

/*
 * ex_cmd --
 *	Parse and execute a string containing ex commands.
 */
int
ex_cmd(sp, ep, cmd, cmdlen, needsep)
	SCR *sp;
	EXF *ep;
	char *cmd;
	size_t cmdlen;
	int needsep;
{
	enum { NOTSET, NEEDSEP_N, NEEDSEP_NR, NONE } sep;
	EX_PRIVATE *exp;
	EXCMDARG exc;
	EXCMDLIST const *cp;
	MARK cur;
	recno_t lno, num;
	size_t arg1_len, len, save_cmdlen;
	long flagoff;
	u_int saved_mode;
	int blank, ch, cnt, delim, flags, namelen, nl;
	int optnum, uselastcmd, tmp, vi_address;
	char *arg1, *save_cmd, *p, *s, *t;

	/* Init. */
	nl = 0;
	sep = needsep ? NOTSET : NONE;
loop:	if (nl) {
		nl = 0;
		++sp->if_lno;
	}
	arg1 = NULL;
	save_cmdlen = 0;

	/* It's possible that we've been interrupted during a command. */
	if (INTERRUPTED(sp))
		return (0);

	/* Skip <blank>s, empty lines.  */
	for (blank = 0; cmdlen > 0; ++cmd, --cmdlen)
		if ((ch = *cmd) == '\n')
			++sp->if_lno;
		else if (isblank(ch))
			blank = 1;
		else
			break;

	/*
	 * !!!
	 * Permit extra colons at the start of the line.  Historically,
	 * ex/vi allowed a single extra one.  It's simpler not to count.
	 * The stripping is done here because, historically, any command
	 * could have preceding colons, e.g. ":g/pattern/:p" worked.
	 */
	if (cmdlen != 0 && ch == ':') {
		if (sep == NOTSET)
			sep = NEEDSEP_N;
		while (--cmdlen > 0 && (ch = *++cmd) == ':');
	}

	/*
	 * Command lines that start with a double-quote are comments.
	 *
	 * !!!
	 * Historically, there was no escape or delimiter for a comment,
	 * e.g. :"foo|set was a single comment and nothing was output.
	 * Since nvi permits users to escape <newline> characters into
	 * command lines, we have to check for that case.
	 */
	if (cmdlen != 0 && ch == '"') {
		while (--cmdlen > 0 && *++cmd != '\n');
		if (*cmd == '\n') {
			nl = 1;
			++cmd;
			--cmdlen;
		}
		goto loop;
	}

	/* Skip whitespace. */
	for (; cmdlen > 0; ++cmd, --cmdlen) {
		ch = *cmd;
		if (!isblank(ch))
			break;
	}

	/*
	 * The last point at which an empty line can mean do nothing.
	 *
	 * !!!
	 * Historically, in ex mode, lines containing only <blank> characters
	 * were the same as a single <carriage-return>, i.e. a default command.
	 * In vi mode, they were ignored.
	 *
	 * In .exrc files this was a serious annoyance, as vi kept trying to
	 * treat them as print commands.  We ignore backward compatibility in
	 * this case, and discard lines containing only <blank> characters from
	 * .exrc files.
	 */
	if (cmdlen == 0 && (!IN_EX_MODE(sp) || ep == NULL || !blank))
		return (0);
		
	/* Initialize the structure passed to underlying functions. */
	memset(&exc, 0, sizeof(EXCMDARG));
	exp = EXP(sp);
	if (argv_init(sp, ep, &exc))
		goto err;

	/*
	 * Check to see if this is a command for which we may want to output
	 * a \r separator instead of a \n.  (The command :1<CR> puts out a \n,
	 * but the command :<CR> puts out a \r.)  If the line is empty except
	 * for <blank>s, <carriage-return> or <eof>, we'll probably want to
	 * output \r.  I don't think there's any way to get <blank> characters
	 * *after* the command character, but this is the ex parser, and I've
	 * been wrong before.
	 */
	if (sep == NOTSET)
		sep = cmdlen == 0 || cmdlen == 1 && cmd[0] == '\004' ?
		    NEEDSEP_NR : NEEDSEP_N;

	/* Parse command addresses. */
	if (ep_range(sp, ep, &exc, &cmd, &cmdlen))
		goto err;

	/* Skip whitespace. */
	for (; cmdlen > 0; ++cmd, --cmdlen) {
		ch = *cmd;
		if (!isblank(ch))
			break;
	}

	/*
	 * If no command, ex does the last specified of p, l, or #, and vi
	 * moves to the line.  Otherwise, determine the length of the command
	 * name by looking for the first non-alphabetic character.  (There
	 * are a few non-alphabetic characters in command names, but they're
	 * all single character commands.)  This isn't a great test, because
	 * it means that, for the command ":e +cut.c file", we'll report that
	 * the command "cut" wasn't known.  However, it makes ":e+35 file" work
	 * correctly.
	 *
	 * !!!
	 * Historically, lines with multiple adjacent (or <blank> separated)
	 * command separators were very strange.  For example, the command
	 * |||<carriage-return>, when the cursor was on line 1, displayed
	 * lines 2, 3 and 5 of the file.  In addition, the command "   |  "
	 * would only display the line after the next line, instead of the
	 * next two lines.  No ideas why.  It worked reasonably when executed
	 * from vi mode, and displayed lines 2, 3, and 4, so we do a default
	 * command for each separator.
	 */
#define	SINGLE_CHAR_COMMANDS	"\004!#&*<=>@@~"
	if (cmdlen != 0 && cmd[0] != '|' && cmd[0] != '\n') {
		if (strchr(SINGLE_CHAR_COMMANDS, *cmd)) {
			p = cmd;
			++cmd;
			--cmdlen;
			namelen = 1;
		} else {
			for (p = cmd; cmdlen > 0; --cmdlen, ++cmd)
				if (!isalpha(*cmd))
					break;
			if ((namelen = cmd - p) == 0) {
				msgq(sp, M_ERR, "Unknown command name");
				goto err;
			}
		}

		/*
		 * !!!
		 * Historic vi permitted flags to immediately follow any
		 * subset of the 'delete' command, but then did not permit
		 * further arguments (flag, buffer, count).  Make it work.
		 * Permit further arguments for the few shreds of dignity
		 * it offers.
		 *
		 * !!!
		 * Note, adding commands that start with 'd', and match
		 * "delete" up to a l, p, +, - or # character can break
		 * this code.
		 */
		if (p[0] == 'd') {
			for (s = p,
			    t = cmds[C_DELETE].name; *s == *t; ++s, ++t);
			if (s[0] == 'l' || s[0] == 'p' ||
			    s[0] == '+' || s[0] == '-' || s[0] == '#') {
				len = (cmd - p) - (s - p);
				cmd -= len;
				cmdlen += len;
				cp = &cmd_del2;
				goto skip;
			}
		}

		/*
		 * Search the table for the command.
		 *
		 * !!!
		 * Historic vi permitted the mark to immediately follow the
		 * 'k' in the 'k' command.  Make it work.
		 *
		 * !!!
		 * Historic vi permitted pretty much anything to follow the
		 * substitute command, e.g. "s/e/E/|s|sgc3p" was fine.  Make
		 * the command "sgc" work.
		 */
		if ((cp = ex_comm_search(p, namelen)) == NULL)
			switch (p[0]) {
			case 's':
				cmd -= namelen - 1;
				cmdlen += namelen - 1;
				cp = &cmd_subagain;
				break;
			case 'k':
				if (p[1] && !p[2]) {
					cmd -= namelen - 1;
					cmdlen += namelen - 1;
					cp = &cmds[C_K];
					break;
				}
				/* FALLTHROUGH */
			default:
				msgq(sp, M_ERR,
				    "The %.*s command is unknown", namelen, p);
				goto err;
			}

		/* Some commands are either not implemented or turned off. */
skip:		if (F_ISSET(cp, E_NOPERM)) {
			msgq(sp, M_ERR,
			    "The %s command is not currently supported",
			    cp->name);
			goto err;
		}

		/* Some commands aren't okay in globals. */
		if (F_ISSET(sp, S_GLOBAL) && F_ISSET(cp, E_NOGLOBAL)) {
			msgq(sp, M_ERR,
		"The %s command can't be used as part of a global command",
			    cp->name);
			goto err;
		}

		/*
		 * Multiple < and > characters; another "feature".  Note,
		 * The string passed to the underlying function may not be
		 * nul terminated in this case.
		 */
		if ((cp == &cmds[C_SHIFTL] && *p == '<') ||
		    (cp == &cmds[C_SHIFTR] && *p == '>')) {
			for (ch = *p; cmdlen > 0; --cmdlen, ++cmd)
				if (*cmd != ch)
					break;
			if (argv_exp0(sp, ep, &exc, p, cmd - p))
				goto err;
		}

		/*
		 * The visual command has a different syntax when called
		 * from ex than when called from a vi colon command.  FMH.
		 */
		if (cp == &cmds[C_VISUAL_EX] && IN_VI_MODE(sp))
			cp = &cmds[C_VISUAL_VI];

		/* Set the format style flags for the next command. */
		if (cp == &cmds[C_HASH])
			exp->fdef = E_F_HASH;
		else if (cp == &cmds[C_LIST])
			exp->fdef = E_F_LIST;
		else if (cp == &cmds[C_PRINT])
			exp->fdef = E_F_PRINT;
		uselastcmd = 0;
	} else {
		/* Print is the default command. */
		cp = &cmds[C_PRINT];

		/* Set the saved format flags. */
		F_SET(&exc, exp->fdef);

		/*
		 * !!!
		 * If no address was specified, and it's not a global command,
		 * we up the address by one.  (I have not an idea why global
		 * commands are exempted, but it's (ahem) historic practice.
		 */
		if (exc.addrcnt == 0 && !F_ISSET(sp, S_GLOBAL)) {
			exc.addrcnt = 1;
			exc.addr1.lno = sp->lno + 1;
			exc.addr1.cno = sp->cno;
		}

		uselastcmd = 1;
	}

	/*
	 * !!!
	 * Historically, the number option applied to both ex and vi.  One
	 * strangeness was that ex didn't switch display formats until a
	 * command was entered, e.g. <CR>'s after the set didn't change to
	 * the new format, but :1p would.
	 */
	if (O_ISSET(sp, O_NUMBER)) {
		optnum = 1;
		F_SET(&exc, E_F_HASH);
	} else
		optnum = 0;

	/* Initialize local flags to the command flags. */
	LF_INIT(cp->flags);

	/*
	 * File state must be checked throughout this code, because it is
	 * called when reading the .exrc file and similar things.  There's
	 * this little chicken and egg problem -- if we read the file first,
	 * we won't know how to display it.  If we read/set the exrc stuff
	 * first, we can't allow any command that requires file state.  We
	 * don't have a "reading an rc" bit, because we want the commands
	 * to work when the user source's the rc file later.  Historic vi
	 * generally took the easy way out and dropped core.
 	 */
	if (LF_ISSET(E_NORC) && ep == NULL) {
		msgq(sp, M_ERR,
	"The %s command requires that a file have already been read in",
		    cp->name);
		goto err;
	}

	/*
	 * There are three normal termination cases for an ex command.  They
	 * are the end of the string (cmdlen), or unescaped (by literal next
	 * characters) newline or '|' characters.  As we're past any addresses,
	 * we can now determine how long the command is, so we don't have to
	 * look for all the possible terminations.  There are three exciting
	 * special cases:
	 *
	 * 1: The bang, global, vglobal and the filter versions of the read and
	 *    write commands are delimited by newlines (they can contain shell
	 *    pipes).
	 * 2: The ex, edit, next and visual in vi mode commands all take ex
	 *    commands as their first arguments.
	 * 3: The substitute command takes an RE as its first argument, and
	 *    wants it to be specially delimited.
	 *
	 * Historically, '|' characters in the first argument of the ex, edit,
	 * next, vi visual, and substitute commands didn't delimit the command.
	 * And, in the filter cases for read and write, and the bang, global
	 * and vglobal commands, they did not delimit the command at all.
	 *
	 * For example, the following commands were legal:
	 *
	 *	:edit +25|s/abc/ABC/ file.c
	 *	:substitute s/|/PIPE/
	 *	:read !spell % | columnate
	 *	:global/pattern/p|l
	 *
	 * It's not quite as simple as it sounds, however.  The command:
	 *
	 *	:substitute s/a/b/|s/c/d|set
	 *
	 * was also legal, i.e. the historic ex parser (using the word loosely,
	 * since "parser" implies some regularity) delimited the RE's based on
	 * its delimiter and not anything so irretrievably vulgar as a command
	 * syntax.
	 *
	 * One thing that makes this easier is that we can ignore most of the
	 * command termination conditions for the commands that want to take
	 * the command up to the next newline.  None of them are legal in .exrc
	 * files, so if we're here, we only dealing with a single line, and we
	 * can just eat it.
	 *
	 * Anyhow, the following code makes this all work.  First, for the
	 * special cases we move past their special argument(s).  Then, we
	 * do normal command processing on whatever is left.  Barf-O-Rama.
	 */
	arg1_len = 0;
	save_cmd = cmd;
	if (cp == &cmds[C_EDIT] || cp == &cmds[C_EX] ||
	    cp == &cmds[C_NEXT] || cp == &cmds[C_VISUAL_VI]) {
		/*
		 * Move to the next non-whitespace character.  A '!'
		 * immediately following the command is eaten as a
		 * force flag.
		 */
		if (cmdlen > 0 && *cmd == '!') {
			++cmd;
			--cmdlen;
			F_SET(&exc, E_FORCE);

			/* Reset, don't reparse. */
			save_cmd = cmd;
		}
		for (tmp = 0; cmdlen > 0; --cmdlen, ++cmd)
			if (!isblank(*cmd))
				break;
		/*
		 * QUOTING NOTE:
		 *
		 * The historic implementation ignored all escape characters
		 * so there was no way to put a space or newline into the +cmd
		 * field.  We do a simplistic job of fixing it by moving to the
		 * first whitespace character that isn't escaped by a literal
		 * next character.  The literal next characters are stripped
		 * as they're no longer useful.
		 */
		if (cmdlen > 0 && *cmd == '+') {
			++cmd;
			--cmdlen;
			for (arg1 = p = cmd; cmdlen > 0; --cmdlen, ++cmd) {
				ch = *cmd;
				if (IS_ESCAPE(sp, ch) && cmdlen > 1) {
					--cmdlen;
					ch = *++cmd;
				} else if (isblank(ch))
					break;
				*p++ = ch;
			}
			arg1_len = cmd - arg1;

			/* Reset, so the first argument isn't reparsed. */
			save_cmd = cmd;
		}
	} else if (cp == &cmds[C_BANG] ||
	    cp == &cmds[C_GLOBAL] || cp == &cmds[C_VGLOBAL]) {
		cmd += cmdlen;
		cmdlen = 0;
	} else if (cp == &cmds[C_READ] || cp == &cmds[C_WRITE]) {
		/*
		 * Move to the next character.  If it's a '!', it's a filter
		 * command and we want to eat it all, otherwise, we're done.
		 */
		for (; cmdlen > 0; --cmdlen, ++cmd) {
			ch = *cmd;
			if (!isblank(ch))
				break;
		}
		if (cmdlen > 0 && ch == '!') {
			cmd += cmdlen;
			cmdlen = 0;
		}
	} else if (cp == &cmds[C_SUBSTITUTE]) {
		/*
		 * Move to the next non-whitespace character, we'll use it as
		 * the delimiter.  If the character isn't an alphanumeric or
		 * a '|', it's the delimiter, so parse it.  Otherwise, we're
		 * into something like ":s g", so use the special substitute
		 * command.
		 */
		for (; cmdlen > 0; --cmdlen, ++cmd)
			if (!isblank(cmd[0]))
				break;

		if (isalnum(cmd[0]) || cmd[0] == '|')
			cp = &cmd_subagain;
		else if (cmdlen > 0) {
			/*
			 * QUOTING NOTE:
			 *
			 * Backslashes quote delimiter characters for RE's.
			 * The backslashes are NOT removed since they'll be
			 * used by the RE code.  Move to the third delimiter
			 * that's not escaped (or the end of the command).
			 */
			delim = *cmd;
			++cmd;
			--cmdlen;
			for (cnt = 2; cmdlen > 0 && cnt; --cmdlen, ++cmd)
				if (cmd[0] == '\\' && cmdlen > 1) {
					++cmd;
					--cmdlen;
				} else if (cmd[0] == delim)
					--cnt;
		}
	}
	/*
	 * Use normal quoting and termination rules to find the end of this
	 * command.
	 *
	 * QUOTING NOTE:
	 *
	 * Historically, vi permitted ^V's to escape <newline>'s in the .exrc
	 * file.  It was almost certainly a bug, but that's what bug-for-bug
	 * compatibility means, Grasshopper.  Also, ^V's escape the command
	 * delimiters.  Literal next quote characters in front of the newlines,
	 * '|' characters or literal next characters are stripped as as they're
	 * no longer useful.
	 */
	vi_address = cmdlen != 0 && cmd[0] != '\n';
	for (p = cmd, cnt = 0; cmdlen > 0; --cmdlen, ++cmd) {
		ch = cmd[0];
		if (IS_ESCAPE(sp, ch) && cmdlen > 1) {
			tmp = cmd[1];
			if (tmp == '\n' || tmp == '|') {
				if (tmp == '\n')
					++sp->if_lno;
				--cmdlen;
				++cmd;
				++cnt;
				ch = tmp;
			}
		} else if (ch == '\n' || ch == '|') {
			if (ch == '\n')
				nl = 1;
			--cmdlen;
			break;
		}
		*p++ = ch;
	}

	/*
	 * Save off the next command information, go back to the
	 * original start of the command.
	 */
	p = cmd + 1;
	cmd = save_cmd;
	save_cmd = p;
	save_cmdlen = cmdlen;
	cmdlen = ((save_cmd - cmd) - 1) - cnt;

	/*
	 * !!!
	 * The "set tags" command historically used a backslash, not the
	 * user's literal next character, to escape whitespace.  Handle
	 * it here instead of complicating the argv_exp3() code.  Note,
	 * this isn't a particularly complex trap, and if backslashes were
	 * legal in set commands, this would have to be much more complicated.
	 */
	if (cp == &cmds[C_SET])
		for (p = cmd, len = cmdlen; len > 0; --len, ++p)
			if (*p == '\\')
				*p = CH_LITERAL;

	/*
	 * Set the default addresses.  It's an error to specify an address for
	 * a command that doesn't take them.  If two addresses are specified
	 * for a command that only takes one, lose the first one.  Two special
	 * cases here, some commands take 0 or 2 addresses.  For most of them
	 * (the E_ADDR2_ALL flag), 0 defaults to the entire file.  For one
	 * (the `!' command, the E_ADDR2_NONE flag), 0 defaults to no lines.
	 *
	 * Also, if the file is empty, some commands want to use an address of
	 * 0, i.e. the entire file is 0 to 0, and the default first address is
	 * 0.  Otherwise, an entire file is 1 to N and the default line is 1.
	 * Note, we also add the E_ZERO flag to the command flags, for the case
	 * where the 0 address is only valid if it's a default address.
	 *
	 * Also, set a flag if we set the default addresses.  Some commands
	 * (ex: z) care if the user specified an address of if we just used
	 * the current cursor.
	 */
	switch (LF_ISSET(E_ADDR1|E_ADDR2|E_ADDR2_ALL|E_ADDR2_NONE)) {
	case E_ADDR1:				/* One address: */
		switch (exc.addrcnt) {
		case 0:				/* Default cursor/empty file. */
			exc.addrcnt = 1;
			F_SET(&exc, E_ADDRDEF);
			if (LF_ISSET(E_ZERODEF)) {
				if (file_lline(sp, ep, &lno))
					goto err;
				if (lno == 0) {
					exc.addr1.lno = 0;
					LF_SET(E_ZERO);
				} else
					exc.addr1.lno = sp->lno;
			} else
				exc.addr1.lno = sp->lno;
			exc.addr1.cno = sp->cno;
			break;
		case 1:
			break;
		case 2:				/* Lose the first address. */
			exc.addrcnt = 1;
			exc.addr1 = exc.addr2;
		}
		break;
	case E_ADDR2_NONE:			/* Zero/two addresses: */
		if (exc.addrcnt == 0)		/* Default to nothing. */
			break;
		goto two;
	case E_ADDR2_ALL:			/* Zero/two addresses: */
		if (exc.addrcnt == 0) {		/* Default entire/empty file. */
			exc.addrcnt = 2;
			F_SET(&exc, E_ADDRDEF);
			if (file_lline(sp, ep, &exc.addr2.lno))
				goto err;
			if (LF_ISSET(E_ZERODEF) && exc.addr2.lno == 0) {
				exc.addr1.lno = 0;
				LF_SET(E_ZERO);
			} else
				exc.addr1.lno = 1;
			exc.addr1.cno = exc.addr2.cno = 0;
			F_SET(&exc, E_ADDR2_ALL);
			break;
		}
		/* FALLTHROUGH */
	case E_ADDR2:				/* Two addresses: */
two:		switch (exc.addrcnt) {
		case 0:				/* Default cursor/empty file. */
			exc.addrcnt = 2;
			F_SET(&exc, E_ADDRDEF);
			if (LF_ISSET(E_ZERODEF) && sp->lno == 1) {
				if (file_lline(sp, ep, &lno))
					goto err;
				if (lno == 0) {
					exc.addr1.lno = exc.addr2.lno = 0;
					LF_SET(E_ZERO);
				} else
					exc.addr1.lno = exc.addr2.lno = sp->lno;
			} else
				exc.addr1.lno = exc.addr2.lno = sp->lno;
			exc.addr1.cno = exc.addr2.cno = sp->cno;
			break;
		case 1:				/* Default to first address. */
			exc.addrcnt = 2;
			exc.addr2 = exc.addr1;
			break;
		case 2:
			break;
		}
		break;
	default:
		if (exc.addrcnt)		/* Error. */
			goto usage;
	}

	/*
	 * !!!
	 * The ^D scroll command historically scrolled the value of the scroll
	 * option or to EOF.  It was an error if the cursor was already at EOF.
	 * (Leading addresses were permitted, but were then ignored.)
	 */
	if (cp == &cmds[C_SCROLL]) {
		exc.addrcnt = 2;
		exc.addr1.lno = sp->lno + 1;
		exc.addr2.lno = sp->lno + O_VAL(sp, O_SCROLL);
		exc.addr1.cno = exc.addr2.cno = sp->cno;
		if (file_lline(sp, ep, &lno))
			goto err;
		if (lno != 0 && lno > sp->lno && exc.addr2.lno > lno)
			exc.addr2.lno = lno;
	}

	flagoff = 0;
	for (p = cp->syntax; *p != '\0'; ++p) {
		/*
		 * The force flag is sensitive to leading whitespace, i.e.
		 * "next !" is different from "next!".  Handle it before
		 * skipping leading <blank>s.
		 */
		if (*p == '!') {
			if (cmdlen > 0 && *cmd == '!') {
				++cmd;
				--cmdlen;
				F_SET(&exc, E_FORCE);
			}
			continue;
		}

		/* Skip leading <blank>s. */
		for (; cmdlen > 0; --cmdlen, ++cmd)
			if (!isblank(*cmd))
				break;

		/*
		 * Quit when reach the end of the command, unless it's a
		 * command that does its own parsing, in which case we want
		 * to build a reasonable argv for it.  This code guarantees
		 * that there will be an argv when the function gets called,
		 * so the correct test is for a length of 0, not for the
		 * argc > 0.  Since '!' can precede commands that do their
		 * own parsing, we have to have already handled it.
		 */
		if (cmdlen == 0 && *p != 'S' && *p != 's')
			break;

		switch (*p) {
		case '1':				/* +, -, #, l, p */
			/*
			 * !!!
			 * Historically, some flags were ignored depending
			 * on where they occurred in the command line.  For
			 * example, in the command, ":3+++p--#", historic vi
			 * acted on the '#' flag, but ignored the '-' flags.
			 * It's unambiguous what the flags mean, so we just
			 * handle them regardless of the stupidity of their
			 * location.
			 */
			for (; cmdlen; --cmdlen, ++cmd)
				switch (*cmd) {
				case '+':
					++flagoff;
					break;
				case '-':
					--flagoff;
					break;
				case '#':
					optnum = 0;
					F_SET(&exc, E_F_HASH);
					exp->fdef |= E_F_HASH;
					break;
				case 'l':
					F_SET(&exc, E_F_LIST);
					exp->fdef |= E_F_LIST;
					break;
				case 'p':
					F_SET(&exc, E_F_PRINT);
					exp->fdef |= E_F_PRINT;
					break;
				default:
					goto end1;
				}
end1:			break;
		case '2':				/* -, ., +, ^ */
		case '3':				/* -, ., +, ^, = */
			for (; cmdlen; --cmdlen, ++cmd)
				switch (*cmd) {
				case '-':
					F_SET(&exc, E_F_DASH);
					break;
				case '.':
					F_SET(&exc, E_F_DOT);
					break;
				case '+':
					F_SET(&exc, E_F_PLUS);
					break;
				case '^':
					F_SET(&exc, E_F_CARAT);
					break;
				case '=':
					if (*p == '3') {
						F_SET(&exc, E_F_EQUAL);
						break;
					}
					/* FALLTHROUGH */
				default:
					goto end2;
				}
end2:			break;
		case 'b':				/* buffer */
			/*
			 * !!!
			 * Historically, "d #" was a delete with a flag, not a
			 * delete into the '#' buffer.  If the current command
			 * permits a flag, don't use one as a buffer.  However,
			 * the 'l' and 'p' flags were legal buffer names in the
			 * historic ex, and were used as buffers, not flags.
			 */
			if ((cmd[0] == '+' || cmd[0] == '-' || cmd[0] == '#') &&
			    strchr(p, '1') != NULL)
				break;
			/*
			 * !!!
			 * Digits can't be buffer names in ex commands, or the
			 * command "d2" would be a delete into buffer '2', and
			 * not a two-line deletion.
			 */
			if (!isdigit(cmd[0])) {
				exc.buffer = *cmd;
				++cmd;
				--cmdlen;
				F_SET(&exc, E_BUFFER);
			}
			break;
		case 'c':				/* count [01+a] */
			++p;
			/* Validate any signed value. */
			if (!isdigit(*cmd) &&
			    (*p != '+' || (*cmd != '+' && *cmd != '-')))
				break;
			/* If a signed value, set appropriate flags. */
			if (*cmd == '-')
				F_SET(&exc, E_COUNT_NEG);
			else if (*cmd == '+')
				F_SET(&exc, E_COUNT_POS);
/* 8-bit XXX */		if ((lno = strtol(cmd, &t, 10)) == 0 && *p != '0') {
				msgq(sp, M_ERR, "Count may not be zero");
				goto err;
			}
			cmdlen -= (t - cmd);
			cmd = t;
			/*
			 * Count as address offsets occur in commands taking
			 * two addresses.  Historic vi practice was to use
			 * the count as an offset from the *second* address.
			 *
			 * Set a count flag; some underlying commands (see
			 * join) do different things with counts than with
			 * line addresses.
			 */
			if (*p == 'a') {
				exc.addr1 = exc.addr2;
				exc.addr2.lno = exc.addr1.lno + lno - 1;
			} else
				exc.count = lno;
			F_SET(&exc, E_COUNT);
			break;
		case 'f':				/* file */
			if (argv_exp2(sp, ep,
			    &exc, cmd, cmdlen, cp == &cmds[C_BANG]))
				goto err;
			goto countchk;
		case 'l':				/* line */
			if (ep_line(sp, ep, &cur, &cmd, &cmdlen, &tmp))
				goto err;
			/* Line specifications are always required. */
			if (!tmp) {
				msgq(sp, M_ERR,
				     "%s: bad line specification", cmd);
				goto err;
			}
			/* The line must exist for these commands. */
			if (file_lline(sp, ep, &lno))
				goto err;
			if (cur.lno > lno) {
				badlno(sp, lno);
				goto err;
			}
			exc.lineno = cur.lno;
			break;
		case 'S':				/* string, file exp. */
			if (argv_exp1(sp, ep,
			    &exc, cmd, cmdlen, cp == &cmds[C_BANG]))
				goto err;
			goto addr2;
		case 's':				/* string */
			if (argv_exp0(sp, ep, &exc, cmd, cmdlen))
				goto err;
			goto addr2;
		case 'W':				/* word string */
			/*
			 * QUOTING NOTE:
			 *
			 * Literal next characters escape the following
			 * character.  Quoting characters are stripped
			 * here since they are no longer useful.
			 *
			 * First there was the word.
			 */
			for (p = t = cmd; cmdlen > 0; --cmdlen, ++cmd) {
				ch = *cmd;
				if (IS_ESCAPE(sp, ch) && cmdlen > 1) {
					--cmdlen;
					*p++ = *++cmd;
				} else if (isblank(ch)) {
					++cmd;
					--cmdlen;
					break;
				} else
					*p++ = ch;
			}
			if (argv_exp0(sp, ep, &exc, t, p - t))
				goto err;

			/* Delete intervening whitespace. */
			for (; cmdlen > 0; --cmdlen, ++cmd) {
				ch = *cmd;
				if (!isblank(ch))
					break;
			}
			if (cmdlen == 0)
				goto usage;

			/* Followed by the string. */
			for (p = t = cmd; cmdlen > 0; --cmdlen, ++cmd, ++p) {
				ch = *cmd;
				if (IS_ESCAPE(sp, ch) && cmdlen > 1) {
					--cmdlen;
					*p = *++cmd;
				} else
					*p = ch;
			}
			if (argv_exp0(sp, ep, &exc, t, p - t))
				goto err;
			goto addr2;
		case 'w':				/* word */
			if (argv_exp3(sp, ep, &exc, cmd, cmdlen))
				goto err;
countchk:		if (*++p != 'N') {		/* N */
				/*
				 * If a number is specified, must either be
				 * 0 or that number, if optional, and that
				 * number, if required.
				 */
				num = *p - '0';
				if ((*++p != 'o' || exp->argsoff != 0) &&
				    exp->argsoff != num)
					goto usage;
			}
			goto addr2;
		default:
			msgq(sp, M_ERR,
			    "Internal syntax table error (%s: %c)",
			    cp->name, *p);
		}
	}

	/* Skip trailing whitespace. */
	for (; cmdlen; --cmdlen) {
		ch = *cmd++;
		if (!isblank(ch))
			break;
	}

	/*
	 * There shouldn't be anything left, and no more required
	 * fields, i.e neither 'l' or 'r' in the syntax string.
	 */
	if (cmdlen || strpbrk(p, "lr")) {
usage:		msgq(sp, M_ERR, "Usage: %s", cp->usage);
		goto err;
	}

	/* Verify that the addresses are legal. */
addr2:	switch (exc.addrcnt) {
	case 2:
		if (file_lline(sp, ep, &lno))
			goto err;
		/*
		 * Historic ex/vi permitted commands with counts to go past
		 * EOF.  So, for example, if the file only had 5 lines, the
		 * ex command "1,6>" would fail, but the command ">300"
		 * would succeed.  Since we don't want to have to make all
		 * of the underlying commands handle random line numbers,
		 * fix it here.
		 */
		if (exc.addr2.lno > lno)
			if (F_ISSET(&exc, E_COUNT))
				exc.addr2.lno = lno;
			else {
				badlno(sp, lno);
				goto err;
			}
		/* FALLTHROUGH */
	case 1:
		num = exc.addr1.lno;
		/*
		 * If it's a "default vi command", zero is okay.  Historic
		 * vi allowed this, note, it's also the hack that allows
		 * "vi +100 nonexistent_file" to work.
		 */
		if (num == 0 && (IN_EX_MODE(sp) || uselastcmd != 1) &&
		    !LF_ISSET(E_ZERO)) {
			msgq(sp, M_ERR,
			    "The %s command doesn't permit an address of 0",
			    cp->name);
			goto err;
		}
		if (file_lline(sp, ep, &lno))
			goto err;
		if (num > lno) {
			badlno(sp, lno);
			goto err;
		}
		break;
	}

	/*
	 * If doing a default command and there's nothing left on the line,
	 * vi just moves to the line.  For example, ":3" and ":'a,'b" just
	 * move to line 3 and line 'b, respectively, but ":3|" prints line 3.
	 *
	 * !!!
	 * This is done before the absolute mark gets set; historically,
	 * "/a/,/b/" did NOT set vi's absolute mark, but "/a/,/b/d" did.
	 */
	if (IN_VI_MODE(sp) && uselastcmd && vi_address == 0) {
		switch (exc.addrcnt) {
		case 2:
			sp->lno = exc.addr2.lno ? exc.addr2.lno : 1;
			sp->cno = exc.addr2.cno;
			break;
		case 1:
			sp->lno = exc.addr1.lno ? exc.addr1.lno : 1;
			sp->cno = exc.addr1.cno;
			break;
		}
		cmd = save_cmd;
		cmdlen = save_cmdlen;
		goto loop;
	}

	/*
	 * Set the absolute mark -- we have to set it for vi here, in case
	 * it's a compound command, e.g. ":5p|6" should set the absolute
	 * mark for vi.
	 */
	if (F_ISSET(exp, EX_ABSMARK)) {
		cur.lno = sp->lno;
		cur.cno = sp->cno;
		F_CLR(exp, EX_ABSMARK);
		if (mark_set(sp, ep, ABSMARK1, &cur, 1))
			goto err;
	}

	/* Final setup for the command. */
	exc.cmd = cp;

#if defined(DEBUG) && 0
	TRACE(sp, "ex_cmd: %s", exc.cmd->name);
	if (exc.addrcnt > 0) {
		TRACE(sp, "\taddr1 %d", exc.addr1.lno);
		if (exc.addrcnt > 1)
			TRACE(sp, " addr2: %d", exc.addr2.lno);
		TRACE(sp, "\n");
	}
	if (exc.lineno)
		TRACE(sp, "\tlineno %d", exc.lineno);
	if (exc.flags)
		TRACE(sp, "\tflags %0x", exc.flags);
	if (F_ISSET(&exc, E_BUFFER))
		TRACE(sp, "\tbuffer %c", exc.buffer);
	TRACE(sp, "\n");
	if (exc.argc) {
		for (cnt = 0; cnt < exc.argc; ++cnt)
			TRACE(sp, "\targ %d: {%s}", cnt, exc.argv[cnt]);
		TRACE(sp, "\n");
	}
#endif
	/* Clear autoprint flag. */
	F_CLR(exp, EX_AUTOPRINT);

	/* Increment the command count if not called from vi. */
	if (IN_EX_MODE(sp))
		++sp->ccnt;

	/*
	 * If file state available, and not doing a global command,
	 * log the start of an action.
	 */
	if (ep != NULL && !F_ISSET(sp, S_GLOBAL))
		(void)log_cursor(sp, ep);

	/*
	 * !!!
	 * There are two special commands for the purposes of this code: the
	 * default command (<carriage-return>) or the scrolling commands (^D
	 * and <EOF>) as the first non-<blank> characters  in the line.
	 *
	 * If this is the first command in the command line, we received the
	 * command from the ex command loop and we're talking to a tty, and
	 * and there's nothing else on the command line, and it's one of the
	 * special commands, we erase the prompt character with a '\r'.  Else,
	 * we put out a newline character to separate the command from the
	 * output from the command.  It's OK if vi calls us -- we won't be in
	 * ex mode so we'll do nothing.
	 *
	 * !!!
	 * Historically, ex only put out a \r, so, if the displayed line was
	 * only a single character long, and <eof> was represented as ^D, the
	 * output wouldn't overwrite the user's input.  Sex currently doesn't
	 * display the <eof> character if it's going to be the scroll command,
	 * i.e. if it's the first non-<blank> character in the line.  If sex
	 * is changed to run in cooked mode, i.e. <eof> is displayed, this code
	 * will have to overwrite it.  We also don't treat lines with extra
	 * prompt characters as empty -- it's not worth the effort since we'd
	 * have to overwrite some indeterminate number of columns with spaces
	 * to clean up.  For now, put out enough spaces to overwrite the prompt.
	 */
	if (sep != NONE) {
		if (ep != NULL &&
		    IN_EX_MODE(sp) && F_ISSET(sp->gp, G_STDIN_TTY))
			if (sep == NEEDSEP_NR &&
			    (uselastcmd || cp == &cmds[C_SCROLL])) {
				(void)putchar('\r');
				for (len = KEY_LEN(sp, PROMPTCHAR); len--;)
					(void)putchar(' ');
				(void)putchar('\r');
			} else
				(void)putchar('\n');
		sep = NONE;
	}

	/* Save the current mode. */
	saved_mode = F_ISSET(sp, S_SCREENS | S_MAJOR_CHANGE);

	/* Do the command. */
	if (cp->fn(sp, ep, &exc))
		goto err;

#ifdef DEBUG
	/* Make sure no function left the temporary space locked. */
	if (F_ISSET(sp->gp, G_TMP_INUSE)) {
		F_CLR(sp->gp, G_TMP_INUSE);
		msgq(sp, M_ERR, "Error: ex: temporary buffer not released");
		goto err;
	}
#endif
	if (saved_mode != F_ISSET(sp, S_SCREENS | S_MAJOR_CHANGE)) {
		/*
		 * Only here if the mode of the underlying file changed, e.g.
		 * the user switched files or is exiting.  Two things that we
		 * might have to save: first, any "+cmd" field set up for an
		 * ex/edit command will have to be saved for later, also, any
		 * part of the current ex command that hasn't been executed
		 * yet.  For example:
		 *
		 *	:edit +25 file.c|s/abc/ABC/|1
		 *
		 * !!!
		 * The historic vi just hung, of course; nvi handles it by
		 * pushing the keys onto the tty queue.  Since the commands
		 * are intended as ex commands, add additional characters
		 * to make it all work if we're switching modes to vi.  Also,
		 * + commands were oriented to the last line in the file,
		 * historically, make the cursor start out there.
		 *
		 * For the fun of it, if you want to see if a vi clone got the
		 * ex argument parsing right, try:
 		 *
		 *	echo 'foo|bar' > file1; echo 'foo/bar' > file2;
		 *	vi
		 *	:edit +1|s/|/PIPE/|w file1| e file2|1 | s/\//SLASH/|wq
		 */
		if (arg1_len == 0 && save_cmdlen == 0)
			return (0);
		if (term_push(sp, "\n", 1, 0))
			goto err;
		if (save_cmdlen != 0)
			if (term_push(sp, save_cmd, save_cmdlen, 0))
				goto err;
		if (arg1 != NULL) {
			if (IN_VI_MODE(sp) && save_cmdlen != 0 &&
			    term_push(sp, "|", 1, 0))
				goto err;
			if (term_push(sp, arg1, arg1_len, 0))
				goto err;
			if (file_lline(sp, ep, &sp->frp->lno))
				goto err;
			F_SET(sp->frp, FR_CURSORSET);
		}
		if (IN_VI_MODE(sp) && term_push(sp, ":", 1, 0))
			goto err;
		return (0);
	}

	/*
	 * Integrate any offset parsed by the underlying command, and make
	 * sure the referenced line exists.
	 *
	 * XXX
	 * May not match historic practice (I've never been able to completely
	 * figure it out.)  For example, the '=' command from vi mode often
	 * got the offset wrong, and complained it was too large, but didn't
	 * seem to have a problem with the cursor.  If anyone complains, ask
	 * them how it's supposed to work, they probably know.
	 */
	if (ep != NULL && (flagoff += exc.flagoff)) {
		if (flagoff < 0) {
			if (sp->lno <= -flagoff) {
				msgq(sp, M_ERR, "Flag offset before line 1");
				goto err;
			}
		} else {
			if (file_lline(sp, ep, &lno))
				goto err;
			if (sp->lno + flagoff > lno) {
				msgq(sp, M_ERR, "Flag offset past end-of-file");
				goto err;
			}
		}
		sp->lno += flagoff;
	}

	/*
	 * If the command was successful and we're in ex command mode, we
	 * may want to display a line.  Make sure there's a line to display.
	 */
	if (ep != NULL &&
	    IN_EX_MODE(sp) && !F_ISSET(sp, S_GLOBAL) && sp->lno != 0) {
		/*
		 * The print commands have already handled the `print' flags.
		 * If so, clear them.
		 */
		if (LF_ISSET(E_F_PRCLEAR))
			F_CLR(&exc, E_F_HASH | E_F_LIST | E_F_PRINT);

		/* If hash only set because of the number option, discard it. */
		if (optnum)
			F_CLR(&exc, E_F_HASH);

		/*
		 * If there was an explicit flag to display the new cursor
		 * line, or we're in ex mode, autoprint is set, and a change
		 * was made, display the line.  If any print flags set use
		 * them, otherwise default to print.
		 */
		LF_INIT(F_ISSET(&exc, E_F_HASH | E_F_LIST | E_F_PRINT));
		if (!LF_ISSET(E_F_HASH | E_F_LIST | E_F_PRINT) &&
		    O_ISSET(sp, O_AUTOPRINT) &&
		    (F_ISSET(exp, EX_AUTOPRINT) || F_ISSET(cp, E_AUTOPRINT)))
			LF_INIT(E_F_PRINT);

		if (LF_ISSET(E_F_HASH | E_F_LIST | E_F_PRINT)) {
			memset(&exc, 0, sizeof(EXCMDARG));
			exc.addrcnt = 2;
			exc.addr1.lno = exc.addr2.lno = sp->lno;
			exc.addr1.cno = exc.addr2.cno = sp->cno;
			(void)ex_print(sp, ep, &exc.addr1, &exc.addr2, flags);
		}
	}

	cmd = save_cmd;
	cmdlen = save_cmdlen;
	goto loop;
	/* NOTREACHED */

	/*
	 * If we haven't put out a separator line, do it now.  For more
	 * detailed comments, see above.
	 */
err:	if (sep != NONE &&
	    ep != NULL && IN_EX_MODE(sp) && F_ISSET(sp->gp, G_STDIN_TTY))
		(void)fputc('\n', stdout);
	/*
	 * On error, we discard any keys we have left, as well as any keys
	 * that were mapped.  The test of save_cmdlen isn't necessarily
	 * correct.  If we fail early enough we don't know if the entire
	 * string was a single command or not.  Try and guess, it's useful
	 * to know if part of the command was discarded.
	 */
	if (save_cmdlen == 0)
		for (; cmdlen; --cmdlen) {
			ch = *cmd++;
			if (IS_ESCAPE(sp, ch) && cmdlen > 1) {
				--cmdlen;
				++cmd;
			} else if (ch == '\n' || ch == '|') {
				if (cmdlen > 1)
					save_cmdlen = 1;
				break;
			}
		}
	if (save_cmdlen != 0)
		msgq(sp, M_ERR,
		    "Ex command failed: remaining command input discarded");
	/*
	 * !!!
	 * Previous versions of nvi cleared mapped characters on error.  This
	 * feature was removed when users complained that it wasn't historic
	 * practice.
	 */
	return (1);
}

/*
 * ep_range --
 *	Get a line range for ex commands.
 */
static int
ep_range(sp, ep, excp, cmdp, cmdlenp)
	SCR *sp;
	EXF *ep;
	EXCMDARG *excp;
	char **cmdp;
	size_t *cmdlenp;
{
	MARK cur, savecursor;
	size_t cmdlen;
	int savecursor_set, tmp;
	char *cmd;

	/* Percent character is all lines in the file. */
	cmd = *cmdp;
	cmdlen = *cmdlenp;
	if (*cmd == '%') {
		excp->addr1.lno = 1;
		if (file_lline(sp, ep, &excp->addr2.lno))
			return (1);

		/* If an empty file, then the first line is 0, not 1. */
		if (excp->addr2.lno == 0)
			excp->addr1.lno = 0;
		excp->addr1.cno = excp->addr2.cno = 0;
		excp->addrcnt = 2;

		++*cmdp;
		--*cmdlenp;
		return (0);
	}

	/* Parse comma or semi-colon delimited line specs. */
	for (savecursor_set = 0, excp->addrcnt = 0; cmdlen > 0;)
		switch (*cmd) {
		case ';':		/* Semi-colon delimiter. */
			/*
			 * Comma delimiters delimit; semi-colon delimiters
			 * change the current address for the 2nd address
			 * to be the first address.  Trailing or multiple
			 * delimiters are discarded.
			 */
			if (excp->addrcnt == 0)
				goto done;
			if (!savecursor_set) {
				savecursor.lno = sp->lno;
				savecursor.cno = sp->cno;
				sp->lno = excp->addr1.lno;
				sp->cno = excp->addr1.cno;
				savecursor_set = 1;
			}
			++cmd;
			--cmdlen;
			break;
		case ',':		/* Comma delimiter. */
			/* If no addresses yet, defaults to ".". */
			if (excp->addrcnt == 0) {
				excp->addr1.lno = sp->lno;
				excp->addr1.cno = sp->cno;
				excp->addrcnt = 1;
			}
			/* FALLTHROUGH */
		case ' ':		/* Whitespace. */
		case '\t':		/* Whitespace. */
			++cmd;
			--cmdlen;
			break;
		default:
			if (ep_line(sp, ep, &cur, &cmd, &cmdlen, &tmp))
				return (1);
			if (!tmp)
				goto done;

			/*
			 * Extra addresses are discarded, starting with
			 * the first.
			 */
			switch (excp->addrcnt) {
			case 0:
				excp->addr1 = cur;
				excp->addrcnt = 1;
				break;
			case 1:
				excp->addr2 = cur;
				excp->addrcnt = 2;
				break;
			case 2:
				excp->addr1 = excp->addr2;
				excp->addr2 = cur;
				break;
			}
			break;
		}

	/*
	 * XXX
	 * This is probably not the right behavior for savecursor --
	 * need to figure out what the historical ex did for ";,;,;5p"
	 * or similar stupidity.
	 */
done:	if (savecursor_set) {
		sp->lno = savecursor.lno;
		sp->cno = savecursor.cno;
	}
	if (excp->addrcnt == 2 && excp->addr2.lno < excp->addr1.lno) {
		msgq(sp, M_ERR,
		    "The second address is smaller than the first");
		return (1);
	}
	*cmdp = cmd;
	*cmdlenp = cmdlen;
	return (0);
}

/*
 * Get a single line address specifier.
 *
 * The way the "previous context" mark worked was that any "non-relative"
 * motion set it.  While ex/vi wasn't totally consistent about this, ANY
 * numeric address, search pattern, '$', or mark reference in an address
 * was considered non-relative, and set the value.  Which should explain
 * why we're hacking marks down here.  The problem was that the mark was
 * only set if the command was called, i.e. we have to set a flag and test
 * it later.
 *
 * XXX
 * This is not exactly historic practice, although it's fairly close.
 */
static int
ep_line(sp, ep, cur, cmdp, cmdlenp, addr_found)
	SCR *sp;
	EXF *ep;
	MARK *cur;
	char **cmdp;
	size_t *cmdlenp;
	int *addr_found;
{
	EX_PRIVATE *exp;
	MARK m;
	long total;
	u_int flags;
	size_t cmdlen;
	int (*sf) __P((SCR *, EXF *, MARK *, MARK *, char *, char **, u_int *));
	char *cmd, *endp;

	exp = EXP(sp);
	*addr_found = 0;

	cmd = *cmdp;
	cmdlen = *cmdlenp;
	switch (*cmd) {
	case '$':				/* Last line in the file. */
		*addr_found = 1;
		F_SET(exp, EX_ABSMARK);

		cur->cno = 0;
		if (file_lline(sp, ep, &cur->lno))
			return (1);
		++cmd;
		--cmdlen;
		break;				/* Absolute line number. */
	case '0': case '1': case '2': case '3': case '4':
	case '5': case '6': case '7': case '8': case '9':
		*addr_found = 1;
		F_SET(exp, EX_ABSMARK);

		cur->cno = 0;
/* 8-bit XXX */	cur->lno = strtol(cmd, &endp, 10);
		cmdlen -= (endp - cmd);
		cmd = endp;
		break;
	case '\'':				/* Use a mark. */
		*addr_found = 1;
		F_SET(exp, EX_ABSMARK);

		if (cmdlen == 1) {
			msgq(sp, M_ERR, "No mark name supplied");
			return (1);
		}
		if (mark_get(sp, ep, cmd[1], cur))
			return (1);
		cmd += 2;
		cmdlen -= 2;
		break;
	case '\\':				/* Search: forward/backward. */
		/*
		 * !!!
		 * I can't find any difference between // and \/ or between
		 * ?? and \?.  Mark Horton doesn't remember there being any
		 * difference.  C'est la vie.
		 */
		if (cmdlen < 2 || cmd[1] != '/' && cmd[1] != '?') {
			msgq(sp, M_ERR, "\\ not followed by / or ?");
			return (1);
		}
		++cmd;
		--cmdlen;
		sf = cmd[0] == '/' ? f_search : b_search;
		goto search;
	case '/':				/* Search forward. */
		sf = f_search;
		goto search;
	case '?':				/* Search backward. */
		sf = b_search;
search:		F_SET(exp, EX_ABSMARK);

		if (ep == NULL) {
			msgq(sp, M_ERR,
	"A search address requires that a file have already been read in");
			return (1);
		}
		*addr_found = 1;
		m.lno = sp->lno;
		m.cno = sp->cno;
		flags = SEARCH_MSG | SEARCH_PARSE | SEARCH_SET;
		if (sf(sp, ep, &m, &m, cmd, &endp, &flags))
			return (1);
		cur->lno = m.lno;
		cur->cno = m.cno;
		cmdlen -= (endp - cmd);
		cmd = endp;
		break;
	case '.':				/* Current position. */
		*addr_found = 1;
		cur->cno = sp->cno;

		/* If an empty file, then '.' is 0, not 1. */
		if (sp->lno == 1) {
			if (file_lline(sp, ep, &cur->lno))
				return (1);
			if (cur->lno != 0)
				cur->lno = 1;
		} else
			cur->lno = sp->lno;
		++cmd;
		--cmdlen;
		break;
	}

	/*
	 * Evaluate any offset.  Offsets are +/- any number, or any number
	 * of +/- signs, or any combination thereof.  If no address found
	 * yet, offset is relative to ".".
	 */
	for (total = 0; cmdlen > 0 && (cmd[0] == '-' || cmd[0] == '+');) {
		if (!*addr_found) {
			cur->lno = sp->lno;
			cur->cno = sp->cno;
			*addr_found = 1;
		}

		if (cmdlen > 1 && isdigit(cmd[1])) {
/* 8-bit XXX */		total += strtol(cmd, &endp, 10);
			cmdlen -= (endp - cmd);
			cmd = endp;
		} else {
			total += cmd[0] == '-' ? -1 : 1;
			--cmdlen;
			++cmd;
		}
	}

	if (*addr_found) {
		if (total < 0 && -total > cur->lno) {
			msgq(sp, M_ERR,
			    "Reference to a line number less than 0");
			return (1);
		}
		cur->lno += total;

		*cmdp = cmd;
		*cmdlenp = cmdlen;
	}
	return (0);
}

/*
 * ex_is_abbrev -
 *	The vi text input routine needs to know if ex thinks this is
 *	an [un]abbreviate command, so it can turn off abbreviations.
 *	Usual ranting in the vi/v_ntext:txt_abbrev() routine.
 */
int
ex_is_abbrev(name, len)
	char *name;
	size_t len;
{
	EXCMDLIST const *cp;

	return ((cp = ex_comm_search(name, len)) != NULL &&
	    (cp == &cmds[C_ABBR] || cp == &cmds[C_UNABBREVIATE]));
}

/*
 * ex_is_unmap -
 *	The vi text input routine needs to know if ex thinks this is
 *	an unmap command, so it can turn off input mapping.  Usual
 *	ranting in the vi/v_ntext:txt_unmap() routine.
 */
int
ex_is_unmap(name, len)
	char *name;
	size_t len;
{
	EXCMDLIST const *cp;

	/*
	 * The command the vi input routines are really interested in
	 * is "unmap!", not just unmap.
	 */
	if (name[len - 1] != '!')
		return (0);
	--len;
	return ((cp = ex_comm_search(name, len)) != NULL &&
	    cp == &cmds[C_UNMAP]);
}

static __inline EXCMDLIST const *
ex_comm_search(name, len)
	char *name;
	size_t len;
{
	EXCMDLIST const *cp;

	for (cp = cmds; cp->name != NULL; ++cp) {
		if (cp->name[0] > name[0])
			return (NULL);
		if (cp->name[0] != name[0])
			continue;
		if (!memcmp(name, cp->name, len))
			return (cp);
	}
	return (NULL);
}

static void
badlno(sp, lno)
	SCR *sp;
	recno_t lno;
{
	if (lno == 0)
		msgq(sp, M_ERR, "Illegal address: the file is empty");
	else
		msgq(sp, M_ERR, "Illegal address: only %lu line%s in the file",
		    lno, lno > 1 ? "s" : "");
}
@


1.4
log
@clean up import.  still have to hack some things.
@
text
@d35 1
a35 1
static const char sccsid[] = "@@(#)ex.c	8.156 (Berkeley) 8/17/94";
@


1.3
log
@nvi 1.11(beta) from bostic.  reconcile conflicts/kill rcsids.
@
text
@d35 1
a35 1
static char sccsid[] = "@@(#)ex.c	8.106 (Berkeley) 3/23/94";
d62 2
a63 1
static inline EXCMDLIST const *
a67 2
#define	DEFCOM	".+1"

d77 1
a80 1
	char defcom[sizeof(DEFCOM)];
d100 1
a100 3
	LF_INIT(TXT_CNTRLD | TXT_CR | TXT_PROMPT);
	if (O_ISSET(sp, O_BEAUTIFY))
		LF_SET(TXT_BEAUTIFY);
d103 23
a125 2
		/* Get the next command. */
		switch (sp->s_get(sp, ep, &sp->tiq, ':', flags)) {
d131 2
d136 5
a140 2
		saved_mode = F_ISSET(sp, S_SCREENS | S_MAJOR_CHANGE);
		tp = sp->tiq.cqh_first;
d142 2
a143 20
			if (F_ISSET(sp->gp, G_STDIN_TTY)) {
				/* Special case \r command. */
				(void)fputc('\r', stdout);
				(void)fflush(stdout);
			}
			memmove(defcom, DEFCOM, sizeof(DEFCOM));
			if (ex_icmd(sp, ep, defcom, sizeof(DEFCOM) - 1) &&
			    !F_ISSET(sp->gp, G_STDIN_TTY))
				F_SET(sp, S_EXIT_FORCE);
		} else {
			if (F_ISSET(sp->gp, G_STDIN_TTY))
				/* Special case ^D command. */
				if (tp->len == 1 && tp->lb[0] == '\004') {
					(void)fputc('\r', stdout);
					(void)fflush(stdout);
				} else
					(void)fputc('\n', stdout);
			if (ex_icmd(sp, ep, tp->lb, tp->len) &&
			    !F_ISSET(sp->gp, G_STDIN_TTY))
				F_SET(sp, S_EXIT_FORCE);
d145 5
d154 1
a154 1
		if (sp->s_refresh(sp, ep)) {
d171 1
a171 1
ex_cfile(sp, ep, filename)
d175 1
d214 1
a214 1
		rval = ex_icmd(sp, ep, bp, len);
d236 1
a236 1
ex_icmd(sp, ep, cmd, len)
d241 1
d248 5
d254 2
a255 3
	F_CLR(sp, S_INTERRUPTED | S_INTERRUPTIBLE);

	return (ex_cmd(sp, ep, cmd, len));
d265 7
d277 1
a277 1
ex_cmd(sp, ep, cmd, cmdlen)
d282 1
d284 1
d293 3
a295 2
	int ch, cnt, delim, flags, namelen, nl, uselastcmd, tmp;
	char *arg1, *save_cmd, *p, *t;
d299 1
d307 2
a308 5
	/*
	 * It's possible that we've been interrupted during a
	 * command.
	 */
	if (F_ISSET(sp, S_INTERRUPTED))
d311 2
a312 2
	/* Skip whitespace, separators, newlines. */
	for (; cmdlen > 0; ++cmd, --cmdlen)
d315 3
a317 1
		else if (!isblank(ch))
a318 2
	if (cmdlen == 0)
		return (0);
d320 23
a342 2
	/* Command lines that start with a double-quote are comments. */
	if (ch == '"') {
d345 1
a347 1
			++sp->if_lno;
a351 10
	/*
	 * !!!
	 * Permit extra colons at the start of the line.  Historically,
	 * ex/vi allowed a single extra one.  It's simpler not to count.
	 * The stripping is done here because, historically, any command
	 * could have preceding colons, e.g. ":g/pattern/:p" worked.
	 */
	if (ch == ':')
		while (--cmdlen > 0 && *++cmd == ':');

d359 14
a372 2
	/* The last point at which an empty line means do nothing. */
	if (cmdlen == 0)
d374 1
a374 1

d381 13
d414 10
d425 1
a425 1
#define	SINGLE_CHAR_COMMANDS	"\004!#&<=>@@~"
d437 1
a437 1
				msgq(sp, M_ERR, "Unknown command name.");
d443 26
d478 1
a478 1
		 * it work.
d481 2
a482 5
			if (p[0] == 'k' && p[1] && !p[2]) {
				cmd -= namelen - 1;
				cmdlen += namelen - 1;
				cp = &cmds[C_K];
			} else if (p[0] == 's') {
d486 10
a495 1
			} else {
d497 1
a497 1
				    "The %.*s command is unknown.", namelen, p);
d502 1
a502 1
		if (F_ISSET(cp, E_NOPERM)) {
d504 1
a504 1
			    "The %s command is not currently supported.",
d512 1
a512 1
		"The %s command can't be used as part of a global command.",
d538 7
d547 18
a564 1
		cp = exp->lastcmd;
d568 13
d596 1
a596 1
	"The %s command requires that a file have already been read in.",
d612 2
a613 2
	 * 2: The ex, edit and visual in vi mode commands take ex commands as
	 *    their first arguments.
d618 3
a620 3
	 * and substitute commands did not delimit the command.  And, in the
	 * filter cases for read and write, and the bang, global and vglobal
	 * commands, they did not delimit the command at all.
d645 2
a646 2
	 * special cases we move past their special argument.  Then, we do
	 * normal command processing on whatever is left.  Barf-O-Rama.
d650 2
a651 2
	if (cp == &cmds[C_EDIT] ||
	    cp == &cmds[C_EX] || cp == &cmds[C_VISUAL_VI]) {
d653 3
a655 3
		 * Move to the next non-whitespace character.  As '+' must
		 * be the character after the command name, if there isn't
		 * one, we're done.
d657 10
a666 3
		for (; cmdlen > 0; --cmdlen, ++cmd) {
			ch = *cmd;
			if (!isblank(ch))
a667 1
		}
d678 1
a678 1
		if (cmdlen > 0 && ch == '+') {
d748 2
a749 2
	 * Use normal quoting and termination rules to find the end
	 * of this command.
d760 1
d803 1
a803 1
				*p = LITERAL_CH;
d900 3
a902 4
	 * The ^D scroll command historically scrolled half the screen size
	 * rows down, rounded down, or to EOF.  It was an error if the cursor
	 * was already at EOF.  (Leading addresses were permitted, but were
	 * then ignored.)
d907 1
a907 1
		exc.addr2.lno = sp->lno + 1 + (O_VAL(sp, O_LINES) + 1) / 2;
d918 3
a920 3
		 * The write command is sensitive to leading whitespace, e.g.
		 * "write !" is different from "write!".  If not the write
		 * command, skip leading whitespace.
d922 5
a926 5
		if (cp != &cmds[C_WRITE])
			for (; cmdlen > 0; --cmdlen, ++cmd) {
				ch = *cmd;
				if (!isblank(ch))
					break;
d928 7
d942 2
a943 1
		 * argc > 0.
d945 1
a945 1
		if (cmdlen == 0 && *p != '!' && *p != 'S' && *p != 's')
a948 7
		case '!':				/* ! */
			if (*cmd == '!') {
				++cmd;
				--cmdlen;
				F_SET(&exc, E_FORCE);
			}
			break;
d969 1
d971 1
d975 1
d979 1
d1013 12
d1048 1
a1048 1
				msgq(sp, M_ERR, "Count may not be zero.");
d1083 7
d1164 1
a1164 1
			    "Internal syntax table error (%s: %c).",
d1181 1
a1181 1
usage:		msgq(sp, M_ERR, "Usage: %s.", cp->usage);
d1202 1
a1202 6
				if (lno == 0)
					msgq(sp, M_ERR, "The file is empty.");
				else
					msgq(sp, M_ERR,
					    "Only %lu line%s in the file",
					    lno, lno > 1 ? "s" : "");
d1211 1
a1211 1
		 * "vi + nonexistent_file" to work.
d1213 1
a1213 1
		if (num == 0 && (!IN_VI_MODE(sp) || uselastcmd != 1) &&
d1216 1
a1216 1
			    "The %s command doesn't permit an address of 0.",
d1223 1
a1223 5
			if (lno == 0)
				msgq(sp, M_ERR, "The file is empty.");
			else
				msgq(sp, M_ERR, "Only %lu line%s in the file",
				    lno, lno > 1 ? "s" : "");
d1229 10
a1238 2
	/* If doing a default command, vi just moves to the line. */
	if (IN_VI_MODE(sp) && uselastcmd) {
d1254 12
a1265 3
	/* Reset "last" command. */
	if (LF_ISSET(E_SETLAST))
		exp->lastcmd = cp;
d1295 1
a1295 1
	if (!IN_VI_MODE(sp))
d1299 2
a1300 2
	 * If file state and not doing a global command, log the start of
	 * an action.
d1305 40
d1349 1
a1349 1
	if ((cp->fn)(sp, ep, &exc))
d1356 1
a1356 1
		msgq(sp, M_ERR, "Error: ex: temporary buffer not released.");
d1363 5
a1367 4
		 * the user switched files or is exiting.  There are two things
		 * that we might have to save.  First, any "+cmd" field set up
		 * for an ex/edit command will have to be saved for later, also,
		 * any not yet executed part of the current ex command.
d1371 7
a1377 1
		 * for example.
d1379 2
a1380 8
		 * The historic vi just hung, of course; we handle by
		 * pushing the keys onto the tty queue.  If we're
		 * switching modes to vi, since the commands are intended
		 * as ex commands, add the extra characters to make it
		 * work.
		 *
		 * For the fun of it, if you want to see if a vi clone got
		 * the ex argument parsing right, try:
d1386 1
a1386 1
		if (arg1_len == NULL && save_cmdlen == 0)
d1388 1
a1388 1
		if (IN_VI_MODE(sp) && term_push(sp, "\n", 1, 0, 0))
d1391 1
a1391 1
			if (term_push(sp, save_cmd, save_cmdlen, 0, 0))
d1395 3
a1397 1
			    term_push(sp, "|", 1, 0, 0))
d1399 1
a1399 1
			if (term_push(sp, arg1, arg1_len, 0, 0))
d1401 1
d1403 1
a1403 1
		if (IN_VI_MODE(sp) && term_push(sp, ":", 1, 0, 0))
d1408 34
a1441 1
	if (IN_EX_MODE(sp) && ep != NULL) {
d1444 1
a1444 2
		 * If so, clear them.  Don't return, autoprint may still have
		 * stuff to print out.
d1446 1
a1446 1
		 if (LF_ISSET(E_F_PRCLEAR))
d1449 4
d1454 4
a1457 3
		 * If the command was successful, and there was an explicit
		 * flag to display the new cursor line, or we're in ex mode,
		 * autoprint is set, and a change was made, display the line.
d1459 3
a1461 20
		if (flagoff) {
			if (flagoff < 0) {
				if (sp->lno < -flagoff) {
					msgq(sp, M_ERR,
					    "Flag offset before line 1.");
					goto err;
				}
			} else {
				if (file_lline(sp, ep, &lno))
					goto err;
				if (sp->lno + flagoff > lno) {
					msgq(sp, M_ERR,
					    "Flag offset past end-of-file.");
					goto err;
				}
			}
			sp->lno += flagoff;
		}

		if (O_ISSET(sp, O_AUTOPRINT) &&
a1463 2
		else
			LF_INIT(F_ISSET(&exc, E_F_HASH | E_F_LIST | E_F_PRINT));
d1465 6
a1470 17
		memset(&exc, 0, sizeof(EXCMDARG));
		exc.addrcnt = 2;
		exc.addr1.lno = exc.addr2.lno = sp->lno;
		exc.addr1.cno = exc.addr2.cno = sp->cno;
		switch (LF_ISSET(E_F_HASH | E_F_LIST | E_F_PRINT)) {
		case E_F_HASH:
			exc.cmd = &cmds[C_HASH];
			ex_number(sp, ep, &exc);
			break;
		case E_F_LIST:
			exc.cmd = &cmds[C_LIST];
			ex_list(sp, ep, &exc);
			break;
		case E_F_PRINT:
			exc.cmd = &cmds[C_PRINT];
			ex_pr(sp, ep, &exc);
			break;
d1480 7
d1493 1
a1493 1
err:	if (save_cmdlen == 0)
d1507 7
a1513 2
		    "Ex command failed: remaining command input discarded.");
	term_map_flush(sp, "Ex command failed");
d1617 3
a1619 3
	 * This is probably not right behavior for savecursor -- need
	 * to figure out what the historical ex did for ";,;,;5p" or
	 * similar stupidity.
d1625 1
a1625 4
	if (excp->addrcnt == 2 &&
	    (excp->addr2.lno < excp->addr1.lno ||
	    excp->addr2.lno == excp->addr1.lno &&
	    excp->addr2.cno < excp->addr1.cno)) {
d1627 1
a1627 1
		    "The second address is smaller than the first.");
d1637 11
d1658 1
d1666 1
d1674 2
d1685 2
a1686 13
		/*
		 * The way the vi "previous context" mark worked was that
		 * "non-relative" motions set it.  While vi wasn't totally
		 * consistent about this, ANY numeric address was considered
		 * non-relative, and set the value.  Which is why we're
		 * hacking marks down here.
		 */
		if (IN_VI_MODE(sp)) {
			m.lno = sp->lno;
			m.cno = sp->cno;
			if (mark_set(sp, ep, ABSMARK1, &m, 1))
				return (1);
		}
d1694 2
d1697 1
a1697 1
			msgq(sp, M_ERR, "No mark name supplied.");
d1708 3
a1710 3
		 * I can't find any difference between // and \/ or
		 * between ?? and \?.  Mark Horton doesn't remember
		 * there being any difference.  C'est la vie.
d1713 1
a1713 1
			msgq(sp, M_ERR, "\\ not followed by / or ?.");
d1725 3
a1727 1
search:		if (ep == NULL) {
d1729 1
a1729 1
	"A search address requires that a file have already been read in.");
d1786 1
a1786 1
			    "Reference to a line number less than 0.");
d1838 1
a1838 1
static inline EXCMDLIST const *
d1854 12
@


1.2
log
@more Ids than you'll ever want.
@
text
@d2 1
a2 1
 * Copyright (c) 1992, 1993
d35 1
a35 2
/* from: static char sccsid[] = "@@(#)ex.c	8.90 (Berkeley) 1/23/94"; */
static char *rcsid = "$Id$";
d39 1
d41 1
d43 1
d47 3
d52 1
d55 4
d79 1
a79 1
	u_int saved_mode;
d90 1
a90 1
	if (!F_ISSET(sp->gp, G_ISFROMTTY)) {
d94 11
d107 1
a107 1
		switch (sp->s_get(sp, ep, &sp->tiq, ':', TXT_CR | TXT_PROMPT)) {
d111 1
a113 2
		case INP_ERR:
			continue;
d119 2
a120 1
			if (F_ISSET(sp->gp, G_ISFROMTTY)) {
d125 3
a127 1
			(void)ex_icmd(sp, ep, defcom, sizeof(DEFCOM) - 1);
d129 10
a138 3
			if (F_ISSET(sp->gp, G_ISFROMTTY))
				(void)fputc('\n', stdout);
			(void)ex_icmd(sp, ep, tp->lb, tp->len);
a140 1

d196 4
a199 1
		/* Run the command.  Messages include file/line information. */
d202 1
d204 2
a205 1
		FREE(sp->if_name, strlen(sp->if_name) + 1);
d243 1
a243 1
static EXCMDLIST const cmd_subagain = 
a259 1
	CHAR_T vlit;
d355 1
a355 1
#define	SINGLE_CHAR_COMMANDS	"!#&<=>@@~"
a382 2
		 *
		 * Use of msgq below is safe, command names are all alphabetics.
d450 4
a453 2
	 * first, we can't allow any command that requires file state.
	 * Historic vi generally took the easy way out and dropped core.
d457 1
a457 1
	"The %s command requires that a file already have been read in.",
a510 1
	(void)term_key_ch(sp, K_VLNEXT, &vlit);
d537 2
a538 1
				if ((ch = *cmd) == vlit && cmdlen > 1) {
d610 1
a610 1
	 * compatibility means, Grasshopper.  Also, ^V's escape the command 
d616 5
a620 4
		if ((ch = cmd[0]) == vlit && cmdlen > 1) {
			ch = cmd[1];
			if (ch == '\n' || ch == '|') {
				if (ch == '\n')
d625 2
a626 2
			} else
				ch = vlit;
d657 1
a657 1
				*p = vlit;
d733 1
a733 1
				} else 
d752 18
d876 1
d880 5
d917 1
a917 1
				msgq(sp, M_ERR, 
d943 2
a944 1
				if ((ch = *cmd) == vlit && cmdlen > 1) {
d956 1
a956 1
				
d967 3
a969 2
			for (p = t = cmd; cmdlen > 0; --cmdlen, ++cmd, ++p)
				if ((ch = *cmd) == vlit && cmdlen > 1) {
d974 1
d1259 3
a1261 2
		for (; cmdlen; --cmdlen)
			if ((ch = *cmd++) == vlit && cmdlen > 1) {
d1269 1
d1410 1
a1410 1
	MARK m, *mp;
d1414 1
d1457 1
a1457 1
		if ((mp = mark_get(sp, ep, cmd[1])) == NULL)
a1458 1
		*cur = *mp;
d1475 2
a1476 5
		if (cmd[0] == '/')
			goto forward;
		if (cmd[0] == '?')
			goto backward;
		/* NOTREACHED */
d1478 7
a1484 5
forward:	*addr_found = 1;
		m.lno = sp->lno;
		m.cno = sp->cno;
		flags = SEARCH_MSG | SEARCH_PARSE | SEARCH_SET;
		if (f_search(sp, ep, &m, &m, cmd, &endp, &flags))
d1486 2
a1487 7
		cur->lno = m.lno;
		cur->cno = m.cno;
		cmdlen -= (endp - cmd);
		cmd = endp;
		break;
	case '?':				/* Search backward. */
backward:	*addr_found = 1;
d1491 1
a1491 1
		if (b_search(sp, ep, &m, &m, cmd, &endp, &flags))
d1537 11
a1547 3
	if (total < 0 && -total > cur->lno) {
		msgq(sp, M_ERR, "Reference to a line number less than 0.");
		return (1);
a1548 4
	cur->lno += total;

	*cmdp = cmd;
	*cmdlenp = cmdlen;
d1567 24
@


1.1
log
@Initial revision
@
text
@d35 2
a36 1
static char sccsid[] = "@@(#)ex.c	8.90 (Berkeley) 1/23/94";
@


1.1.1.1
log
@nvi 1.03, from ftp.cs.berkeley.edu, per keith bostic's permission.
@
text
@@


1.1.1.2
log
@nvi/nex 1.11beta from bostic.
@
text
@d2 1
a2 1
 * Copyright (c) 1992, 1993, 1994
d35 1
a35 1
static char sccsid[] = "@@(#)ex.c	8.106 (Berkeley) 3/23/94";
a38 1
#include <sys/queue.h>
a39 1
#include <sys/time.h>
a40 1
#include <bitstring.h>
a43 3
#include <limits.h>
#include <signal.h>
#include <stdio.h>
a45 1
#include <termios.h>
a47 4
#include "compat.h"
#include <db.h>
#include <regex.h>

d68 1
a68 1
	u_int flags, saved_mode;
d79 1
a79 1
	if (!F_ISSET(sp->gp, G_STDIN_TTY)) {
a82 11

	/*
	 * !!!
	 * Historically, the beautify option applies to ex command input read
	 * from a file.  In addition, the first time a ^H was discarded from
	 * the input, a message "^H discarded" was displayed.  We don't bother.
	 */
	LF_INIT(TXT_CNTRLD | TXT_CR | TXT_PROMPT);
	if (O_ISSET(sp, O_BEAUTIFY))
		LF_SET(TXT_BEAUTIFY);

d85 1
a85 1
		switch (sp->s_get(sp, ep, &sp->tiq, ':', flags)) {
a88 1
		case INP_ERR:
d91 2
d98 1
a98 2
			if (F_ISSET(sp->gp, G_STDIN_TTY)) {
				/* Special case \r command. */
d103 1
a103 3
			if (ex_icmd(sp, ep, defcom, sizeof(DEFCOM) - 1) &&
			    !F_ISSET(sp->gp, G_STDIN_TTY))
				F_SET(sp, S_EXIT_FORCE);
d105 3
a107 10
			if (F_ISSET(sp->gp, G_STDIN_TTY))
				/* Special case ^D command. */
				if (tp->len == 1 && tp->lb[0] == '\004') {
					(void)fputc('\r', stdout);
					(void)fflush(stdout);
				} else
					(void)fputc('\n', stdout);
			if (ex_icmd(sp, ep, tp->lb, tp->len) &&
			    !F_ISSET(sp->gp, G_STDIN_TTY))
				F_SET(sp, S_EXIT_FORCE);
d110 1
d166 1
a166 4
		/*
		 * Run the command.  Messages include file/line information,
		 * but we don't care if we can't get space.
		 */
a168 1
		F_SET(sp, S_VLITONLY);
d170 1
a170 2
		F_CLR(sp, S_VLITONLY);
		free(sp->if_name);
d208 1
a208 1
static EXCMDLIST const cmd_subagain =
d225 1
d321 1
a321 1
#define	SINGLE_CHAR_COMMANDS	"\004!#&<=>@@~"
d349 2
d418 2
a419 4
	 * first, we can't allow any command that requires file state.  We
	 * don't have a "reading an rc" bit, because we want the commands
	 * to work when the user source's the rc file later.  Historic vi
	 * generally took the easy way out and dropped core.
d423 1
a423 1
	"The %s command requires that a file have already been read in.",
d477 1
d504 1
a504 2
				ch = *cmd;
				if (IS_ESCAPE(sp, ch) && cmdlen > 1) {
d576 1
a576 1
	 * compatibility means, Grasshopper.  Also, ^V's escape the command
d582 4
a585 5
		ch = cmd[0];
		if (IS_ESCAPE(sp, ch) && cmdlen > 1) {
			tmp = cmd[1];
			if (tmp == '\n' || tmp == '|') {
				if (tmp == '\n')
d590 2
a591 2
				ch = tmp;
			}
d622 1
a622 1
				*p = LITERAL_CH;
d698 1
a698 1
				} else
a716 18
	/*
	 * !!!
	 * The ^D scroll command historically scrolled half the screen size
	 * rows down, rounded down, or to EOF.  It was an error if the cursor
	 * was already at EOF.  (Leading addresses were permitted, but were
	 * then ignored.)
	 */
	if (cp == &cmds[C_SCROLL]) {
		exc.addrcnt = 2;
		exc.addr1.lno = sp->lno + 1;
		exc.addr2.lno = sp->lno + 1 + (O_VAL(sp, O_LINES) + 1) / 2;
		exc.addr1.cno = exc.addr2.cno = sp->cno;
		if (file_lline(sp, ep, &lno))
			goto err;
		if (lno != 0 && lno > sp->lno && exc.addr2.lno > lno)
			exc.addr2.lno = lno;
	}

a822 1
			/* Validate any signed value. */
a825 5
			/* If a signed value, set appropriate flags. */
			if (*cmd == '-')
				F_SET(&exc, E_COUNT_NEG);
			else if (*cmd == '+')
				F_SET(&exc, E_COUNT_POS);
d858 1
a858 1
				msgq(sp, M_ERR,
d884 1
a884 2
				ch = *cmd;
				if (IS_ESCAPE(sp, ch) && cmdlen > 1) {
d896 1
a896 1

d907 2
a908 3
			for (p = t = cmd; cmdlen > 0; --cmdlen, ++cmd, ++p) {
				ch = *cmd;
				if (IS_ESCAPE(sp, ch) && cmdlen > 1) {
a912 1
			}
d1197 2
a1198 3
		for (; cmdlen; --cmdlen) {
			ch = *cmd++;
			if (IS_ESCAPE(sp, ch) && cmdlen > 1) {
a1205 1
		}
d1346 1
a1346 1
	MARK m;
a1349 1
	int (*sf) __P((SCR *, EXF *, MARK *, MARK *, char *, char **, u_int *));
d1392 1
a1392 1
		if (mark_get(sp, ep, cmd[1], cur))
d1394 1
d1411 5
a1415 2
		sf = cmd[0] == '/' ? f_search : b_search;
		goto search;
d1417 11
a1427 2
		sf = f_search;
		goto search;
d1429 1
a1429 7
		sf = b_search;
search:		if (ep == NULL) {
			msgq(sp, M_ERR,
	"A search address requires that a file have already been read in.");
			return (1);
		}
		*addr_found = 1;
d1433 1
a1433 1
		if (sf(sp, ep, &m, &m, cmd, &endp, &flags))
d1479 5
d1485 2
a1486 11
	if (*addr_found) {
		if (total < 0 && -total > cur->lno) {
			msgq(sp, M_ERR,
			    "Reference to a line number less than 0.");
			return (1);
		}
		cur->lno += total;

		*cmdp = cmd;
		*cmdlenp = cmdlen;
	}
a1504 24
}

/*
 * ex_is_unmap -
 *	The vi text input routine needs to know if ex thinks this is
 *	an unmap command, so it can turn off input mapping.  Usual
 *	ranting in the vi/v_ntext:txt_unmap() routine.
 */
int
ex_is_unmap(name, len)
	char *name;
	size_t len;
{
	EXCMDLIST const *cp;

	/*
	 * The command the vi input routines are really interested in
	 * is "unmap!", not just unmap.
	 */
	if (name[len - 1] != '!')
		return (0);
	--len;
	return ((cp = ex_comm_search(name, len)) != NULL &&
	    cp == &cmds[C_UNMAP]);
@


1.1.1.3
log
@new public version of nvi
@
text
@d35 1
a35 1
static const char sccsid[] = "@@(#)ex.c	8.156 (Berkeley) 8/17/94";
d62 1
a62 2
static void	badlno __P((SCR *, recno_t));
static __inline EXCMDLIST const *
d67 2
a77 1
	enum input irval;
d81 1
d101 3
a103 1
	LF_INIT(TXT_BACKSLASH | TXT_CNTRLD | TXT_CR | TXT_EXSUSPEND);
d106 2
a107 23
		/* Set the flags that the user can change. */
		if (O_ISSET(sp, O_BEAUTIFY))
			LF_SET(TXT_BEAUTIFY);
		else
			LF_CLR(TXT_BEAUTIFY);
		if (O_ISSET(sp, O_PROMPT))
			LF_SET(TXT_PROMPT);
		else
			LF_CLR(TXT_PROMPT);

		/*
		 * Get the next command.  Interrupt flag manipulation is
		 * safe because ex_icmd clears them all.
		 */
		CLR_INTERRUPT(sp);
		F_SET(sp, S_INTERRUPTIBLE);
		irval = sp->s_get(sp, ep, sp->tiqp, ':', flags);
		if (INTERRUPTED(sp)) {
			(void)fputc('\n', stdout);
			(void)fflush(stdout);
			goto refresh;
		}
		switch (irval) {
a112 2
			/* FALLTHROUGH */
		case INP_INTR:
d116 2
a117 5
		/*
		 * If the user entered a carriage return, send ex_cmd()
		 * a separator -- it discards single newlines.
		 */
		tp = sp->tiqp->cqh_first;
d119 20
a138 2
			tp->len = 1;
			tp->lb[0] = ' ';
a139 5

		saved_mode = F_ISSET(sp, S_SCREENS | S_MAJOR_CHANGE);
		if (ex_icmd(sp, ep,
		    tp->lb, tp->len, 1) && !F_ISSET(sp->gp, G_STDIN_TTY))
			F_SET(sp, S_EXIT_FORCE);
d144 1
a144 1
refresh:	if (sp->s_refresh(sp, ep)) {
d161 1
a161 1
ex_cfile(sp, ep, filename, needsep)
a164 1
	int needsep;
d203 1
a203 1
		rval = ex_icmd(sp, ep, bp, len, needsep);
d225 1
a225 1
ex_icmd(sp, ep, cmd, len, needsep)
a229 1
	int needsep;
a235 5
	 *
	 * !!!
	 * Previous versions of nvi cleared mapped characters on error.  This
	 * feature was removed when users complained that it wasn't historic
	 * practice.
d237 3
a239 2
	CLR_INTERRUPT(sp);
	return (ex_cmd(sp, ep, cmd, len, needsep));
a248 7
/* Special command structure for :d[flags]. */
static EXCMDLIST const cmd_del2 = 
	{"delete",	ex_delete,	E_ADDR2|E_AUTOPRINT|E_NORC,
	    "1bca1",
	    "[line [,line]] d[elete][flags] [buffer] [count] [flags]",
	    "delete lines from the file"};

d254 1
a254 1
ex_cmd(sp, ep, cmd, cmdlen, needsep)
a258 1
	int needsep;
a259 1
	enum { NOTSET, NEEDSEP_N, NEEDSEP_NR, NONE } sep;
d268 2
a269 3
	int blank, ch, cnt, delim, flags, namelen, nl;
	int optnum, uselastcmd, tmp, vi_address;
	char *arg1, *save_cmd, *p, *s, *t;
a272 1
	sep = needsep ? NOTSET : NONE;
d280 5
a284 2
	/* It's possible that we've been interrupted during a command. */
	if (INTERRUPTED(sp))
d287 2
a288 2
	/* Skip <blank>s, empty lines.  */
	for (blank = 0; cmdlen > 0; ++cmd, --cmdlen)
d291 1
a291 3
		else if (isblank(ch))
			blank = 1;
		else
d293 13
d314 2
a315 24
	if (cmdlen != 0 && ch == ':') {
		if (sep == NOTSET)
			sep = NEEDSEP_N;
		while (--cmdlen > 0 && (ch = *++cmd) == ':');
	}

	/*
	 * Command lines that start with a double-quote are comments.
	 *
	 * !!!
	 * Historically, there was no escape or delimiter for a comment,
	 * e.g. :"foo|set was a single comment and nothing was output.
	 * Since nvi permits users to escape <newline> characters into
	 * command lines, we have to check for that case.
	 */
	if (cmdlen != 0 && ch == '"') {
		while (--cmdlen > 0 && *++cmd != '\n');
		if (*cmd == '\n') {
			nl = 1;
			++cmd;
			--cmdlen;
		}
		goto loop;
	}
d324 2
a325 14
	/*
	 * The last point at which an empty line can mean do nothing.
	 *
	 * !!!
	 * Historically, in ex mode, lines containing only <blank> characters
	 * were the same as a single <carriage-return>, i.e. a default command.
	 * In vi mode, they were ignored.
	 *
	 * In .exrc files this was a serious annoyance, as vi kept trying to
	 * treat them as print commands.  We ignore backward compatibility in
	 * this case, and discard lines containing only <blank> characters from
	 * .exrc files.
	 */
	if (cmdlen == 0 && (!IN_EX_MODE(sp) || ep == NULL || !blank))
d327 1
a327 1
		
a333 13
	/*
	 * Check to see if this is a command for which we may want to output
	 * a \r separator instead of a \n.  (The command :1<CR> puts out a \n,
	 * but the command :<CR> puts out a \r.)  If the line is empty except
	 * for <blank>s, <carriage-return> or <eof>, we'll probably want to
	 * output \r.  I don't think there's any way to get <blank> characters
	 * *after* the command character, but this is the ex parser, and I've
	 * been wrong before.
	 */
	if (sep == NOTSET)
		sep = cmdlen == 0 || cmdlen == 1 && cmd[0] == '\004' ?
		    NEEDSEP_NR : NEEDSEP_N;

a353 10
	 *
	 * !!!
	 * Historically, lines with multiple adjacent (or <blank> separated)
	 * command separators were very strange.  For example, the command
	 * |||<carriage-return>, when the cursor was on line 1, displayed
	 * lines 2, 3 and 5 of the file.  In addition, the command "   |  "
	 * would only display the line after the next line, instead of the
	 * next two lines.  No ideas why.  It worked reasonably when executed
	 * from vi mode, and displayed lines 2, 3, and 4, so we do a default
	 * command for each separator.
d355 1
a355 1
#define	SINGLE_CHAR_COMMANDS	"\004!#&*<=>@@~"
d367 1
a367 1
				msgq(sp, M_ERR, "Unknown command name");
a372 26
		 * !!!
		 * Historic vi permitted flags to immediately follow any
		 * subset of the 'delete' command, but then did not permit
		 * further arguments (flag, buffer, count).  Make it work.
		 * Permit further arguments for the few shreds of dignity
		 * it offers.
		 *
		 * !!!
		 * Note, adding commands that start with 'd', and match
		 * "delete" up to a l, p, +, - or # character can break
		 * this code.
		 */
		if (p[0] == 'd') {
			for (s = p,
			    t = cmds[C_DELETE].name; *s == *t; ++s, ++t);
			if (s[0] == 'l' || s[0] == 'p' ||
			    s[0] == '+' || s[0] == '-' || s[0] == '#') {
				len = (cmd - p) - (s - p);
				cmd -= len;
				cmdlen += len;
				cp = &cmd_del2;
				goto skip;
			}
		}

		/*
d382 1
a382 1
		 * the command "sgc" work.
d385 5
a389 2
			switch (p[0]) {
			case 's':
d393 1
a393 10
				break;
			case 'k':
				if (p[1] && !p[2]) {
					cmd -= namelen - 1;
					cmdlen += namelen - 1;
					cp = &cmds[C_K];
					break;
				}
				/* FALLTHROUGH */
			default:
d395 1
a395 1
				    "The %.*s command is unknown", namelen, p);
d400 1
a400 1
skip:		if (F_ISSET(cp, E_NOPERM)) {
d402 1
a402 1
			    "The %s command is not currently supported",
d410 1
a410 1
		"The %s command can't be used as part of a global command",
a435 7
		/* Set the format style flags for the next command. */
		if (cp == &cmds[C_HASH])
			exp->fdef = E_F_HASH;
		else if (cp == &cmds[C_LIST])
			exp->fdef = E_F_LIST;
		else if (cp == &cmds[C_PRINT])
			exp->fdef = E_F_PRINT;
d438 1
a438 18
		/* Print is the default command. */
		cp = &cmds[C_PRINT];

		/* Set the saved format flags. */
		F_SET(&exc, exp->fdef);

		/*
		 * !!!
		 * If no address was specified, and it's not a global command,
		 * we up the address by one.  (I have not an idea why global
		 * commands are exempted, but it's (ahem) historic practice.
		 */
		if (exc.addrcnt == 0 && !F_ISSET(sp, S_GLOBAL)) {
			exc.addrcnt = 1;
			exc.addr1.lno = sp->lno + 1;
			exc.addr1.cno = sp->cno;
		}

a441 13
	/*
	 * !!!
	 * Historically, the number option applied to both ex and vi.  One
	 * strangeness was that ex didn't switch display formats until a
	 * command was entered, e.g. <CR>'s after the set didn't change to
	 * the new format, but :1p would.
	 */
	if (O_ISSET(sp, O_NUMBER)) {
		optnum = 1;
		F_SET(&exc, E_F_HASH);
	} else
		optnum = 0;

d457 1
a457 1
	"The %s command requires that a file have already been read in",
d473 2
a474 2
	 * 2: The ex, edit, next and visual in vi mode commands all take ex
	 *    commands as their first arguments.
d479 3
a481 3
	 * next, vi visual, and substitute commands didn't delimit the command.
	 * And, in the filter cases for read and write, and the bang, global
	 * and vglobal commands, they did not delimit the command at all.
d506 2
a507 2
	 * special cases we move past their special argument(s).  Then, we
	 * do normal command processing on whatever is left.  Barf-O-Rama.
d511 2
a512 2
	if (cp == &cmds[C_EDIT] || cp == &cmds[C_EX] ||
	    cp == &cmds[C_NEXT] || cp == &cmds[C_VISUAL_VI]) {
d514 3
a516 3
		 * Move to the next non-whitespace character.  A '!'
		 * immediately following the command is eaten as a
		 * force flag.
d518 4
a521 7
		if (cmdlen > 0 && *cmd == '!') {
			++cmd;
			--cmdlen;
			F_SET(&exc, E_FORCE);

			/* Reset, don't reparse. */
			save_cmd = cmd;
a522 3
		for (tmp = 0; cmdlen > 0; --cmdlen, ++cmd)
			if (!isblank(*cmd))
				break;
d533 1
a533 1
		if (cmdlen > 0 && *cmd == '+') {
d603 2
a604 2
	 * Use normal quoting and termination rules to find the end of this
	 * command.
a614 1
	vi_address = cmdlen != 0 && cmd[0] != '\n';
d657 1
a657 1
				*p = CH_LITERAL;
d754 4
a757 3
	 * The ^D scroll command historically scrolled the value of the scroll
	 * option or to EOF.  It was an error if the cursor was already at EOF.
	 * (Leading addresses were permitted, but were then ignored.)
d762 1
a762 1
		exc.addr2.lno = sp->lno + O_VAL(sp, O_SCROLL);
d773 3
a775 3
		 * The force flag is sensitive to leading whitespace, i.e.
		 * "next !" is different from "next!".  Handle it before
		 * skipping leading <blank>s.
d777 5
a781 5
		if (*p == '!') {
			if (cmdlen > 0 && *cmd == '!') {
				++cmd;
				--cmdlen;
				F_SET(&exc, E_FORCE);
a782 7
			continue;
		}

		/* Skip leading <blank>s. */
		for (; cmdlen > 0; --cmdlen, ++cmd)
			if (!isblank(*cmd))
				break;
d790 1
a790 2
		 * argc > 0.  Since '!' can precede commands that do their
		 * own parsing, we have to have already handled it.
d792 1
a792 1
		if (cmdlen == 0 && *p != 'S' && *p != 's')
d796 7
a822 1
					optnum = 0;
a823 1
					exp->fdef |= E_F_HASH;
a826 1
					exp->fdef |= E_F_LIST;
a829 1
					exp->fdef |= E_F_PRINT;
a862 12
			 * !!!
			 * Historically, "d #" was a delete with a flag, not a
			 * delete into the '#' buffer.  If the current command
			 * permits a flag, don't use one as a buffer.  However,
			 * the 'l' and 'p' flags were legal buffer names in the
			 * historic ex, and were used as buffers, not flags.
			 */
			if ((cmd[0] == '+' || cmd[0] == '-' || cmd[0] == '#') &&
			    strchr(p, '1') != NULL)
				break;
			/*
			 * !!!
d886 1
a886 1
				msgq(sp, M_ERR, "Count may not be zero");
a920 7
			/* The line must exist for these commands. */
			if (file_lline(sp, ep, &lno))
				goto err;
			if (cur.lno > lno) {
				badlno(sp, lno);
				goto err;
			}
d995 1
a995 1
			    "Internal syntax table error (%s: %c)",
d1012 1
a1012 1
usage:		msgq(sp, M_ERR, "Usage: %s", cp->usage);
d1033 6
a1038 1
				badlno(sp, lno);
d1047 1
a1047 1
		 * "vi +100 nonexistent_file" to work.
d1049 1
a1049 1
		if (num == 0 && (IN_EX_MODE(sp) || uselastcmd != 1) &&
d1052 1
a1052 1
			    "The %s command doesn't permit an address of 0",
d1059 5
a1063 1
			badlno(sp, lno);
d1069 2
a1070 10
	/*
	 * If doing a default command and there's nothing left on the line,
	 * vi just moves to the line.  For example, ":3" and ":'a,'b" just
	 * move to line 3 and line 'b, respectively, but ":3|" prints line 3.
	 *
	 * !!!
	 * This is done before the absolute mark gets set; historically,
	 * "/a/,/b/" did NOT set vi's absolute mark, but "/a/,/b/d" did.
	 */
	if (IN_VI_MODE(sp) && uselastcmd && vi_address == 0) {
d1086 3
a1088 12
	/*
	 * Set the absolute mark -- we have to set it for vi here, in case
	 * it's a compound command, e.g. ":5p|6" should set the absolute
	 * mark for vi.
	 */
	if (F_ISSET(exp, EX_ABSMARK)) {
		cur.lno = sp->lno;
		cur.cno = sp->cno;
		F_CLR(exp, EX_ABSMARK);
		if (mark_set(sp, ep, ABSMARK1, &cur, 1))
			goto err;
	}
d1118 1
a1118 1
	if (IN_EX_MODE(sp))
d1122 2
a1123 2
	 * If file state available, and not doing a global command,
	 * log the start of an action.
a1127 40
	/*
	 * !!!
	 * There are two special commands for the purposes of this code: the
	 * default command (<carriage-return>) or the scrolling commands (^D
	 * and <EOF>) as the first non-<blank> characters  in the line.
	 *
	 * If this is the first command in the command line, we received the
	 * command from the ex command loop and we're talking to a tty, and
	 * and there's nothing else on the command line, and it's one of the
	 * special commands, we erase the prompt character with a '\r'.  Else,
	 * we put out a newline character to separate the command from the
	 * output from the command.  It's OK if vi calls us -- we won't be in
	 * ex mode so we'll do nothing.
	 *
	 * !!!
	 * Historically, ex only put out a \r, so, if the displayed line was
	 * only a single character long, and <eof> was represented as ^D, the
	 * output wouldn't overwrite the user's input.  Sex currently doesn't
	 * display the <eof> character if it's going to be the scroll command,
	 * i.e. if it's the first non-<blank> character in the line.  If sex
	 * is changed to run in cooked mode, i.e. <eof> is displayed, this code
	 * will have to overwrite it.  We also don't treat lines with extra
	 * prompt characters as empty -- it's not worth the effort since we'd
	 * have to overwrite some indeterminate number of columns with spaces
	 * to clean up.  For now, put out enough spaces to overwrite the prompt.
	 */
	if (sep != NONE) {
		if (ep != NULL &&
		    IN_EX_MODE(sp) && F_ISSET(sp->gp, G_STDIN_TTY))
			if (sep == NEEDSEP_NR &&
			    (uselastcmd || cp == &cmds[C_SCROLL])) {
				(void)putchar('\r');
				for (len = KEY_LEN(sp, PROMPTCHAR); len--;)
					(void)putchar(' ');
				(void)putchar('\r');
			} else
				(void)putchar('\n');
		sep = NONE;
	}

d1132 1
a1132 1
	if (cp->fn(sp, ep, &exc))
d1139 1
a1139 1
		msgq(sp, M_ERR, "Error: ex: temporary buffer not released");
d1146 4
a1149 5
		 * the user switched files or is exiting.  Two things that we
		 * might have to save: first, any "+cmd" field set up for an
		 * ex/edit command will have to be saved for later, also, any
		 * part of the current ex command that hasn't been executed
		 * yet.  For example:
d1153 7
a1159 7
		 * !!!
		 * The historic vi just hung, of course; nvi handles it by
		 * pushing the keys onto the tty queue.  Since the commands
		 * are intended as ex commands, add additional characters
		 * to make it all work if we're switching modes to vi.  Also,
		 * + commands were oriented to the last line in the file,
		 * historically, make the cursor start out there.
d1161 2
a1162 2
		 * For the fun of it, if you want to see if a vi clone got the
		 * ex argument parsing right, try:
d1168 1
a1168 1
		if (arg1_len == 0 && save_cmdlen == 0)
d1170 1
a1170 1
		if (term_push(sp, "\n", 1, 0))
d1173 1
a1173 1
			if (term_push(sp, save_cmd, save_cmdlen, 0))
d1177 1
a1177 3
			    term_push(sp, "|", 1, 0))
				goto err;
			if (term_push(sp, arg1, arg1_len, 0))
d1179 1
a1179 1
			if (file_lline(sp, ep, &sp->frp->lno))
a1180 1
			F_SET(sp->frp, FR_CURSORSET);
d1182 1
a1182 1
		if (IN_VI_MODE(sp) && term_push(sp, ":", 1, 0))
d1187 1
a1187 34
	/*
	 * Integrate any offset parsed by the underlying command, and make
	 * sure the referenced line exists.
	 *
	 * XXX
	 * May not match historic practice (I've never been able to completely
	 * figure it out.)  For example, the '=' command from vi mode often
	 * got the offset wrong, and complained it was too large, but didn't
	 * seem to have a problem with the cursor.  If anyone complains, ask
	 * them how it's supposed to work, they probably know.
	 */
	if (ep != NULL && (flagoff += exc.flagoff)) {
		if (flagoff < 0) {
			if (sp->lno <= -flagoff) {
				msgq(sp, M_ERR, "Flag offset before line 1");
				goto err;
			}
		} else {
			if (file_lline(sp, ep, &lno))
				goto err;
			if (sp->lno + flagoff > lno) {
				msgq(sp, M_ERR, "Flag offset past end-of-file");
				goto err;
			}
		}
		sp->lno += flagoff;
	}

	/*
	 * If the command was successful and we're in ex command mode, we
	 * may want to display a line.  Make sure there's a line to display.
	 */
	if (ep != NULL &&
	    IN_EX_MODE(sp) && !F_ISSET(sp, S_GLOBAL) && sp->lno != 0) {
d1190 2
a1191 1
		 * If so, clear them.
d1193 1
a1193 1
		if (LF_ISSET(E_F_PRCLEAR))
a1195 4
		/* If hash only set because of the number option, discard it. */
		if (optnum)
			F_CLR(&exc, E_F_HASH);

d1197 3
a1199 4
		 * If there was an explicit flag to display the new cursor
		 * line, or we're in ex mode, autoprint is set, and a change
		 * was made, display the line.  If any print flags set use
		 * them, otherwise default to print.
d1201 20
a1220 3
		LF_INIT(F_ISSET(&exc, E_F_HASH | E_F_LIST | E_F_PRINT));
		if (!LF_ISSET(E_F_HASH | E_F_LIST | E_F_PRINT) &&
		    O_ISSET(sp, O_AUTOPRINT) &&
d1223 2
d1226 17
a1242 6
		if (LF_ISSET(E_F_HASH | E_F_LIST | E_F_PRINT)) {
			memset(&exc, 0, sizeof(EXCMDARG));
			exc.addrcnt = 2;
			exc.addr1.lno = exc.addr2.lno = sp->lno;
			exc.addr1.cno = exc.addr2.cno = sp->cno;
			(void)ex_print(sp, ep, &exc.addr1, &exc.addr2, flags);
a1251 7
	 * If we haven't put out a separator line, do it now.  For more
	 * detailed comments, see above.
	 */
err:	if (sep != NONE &&
	    ep != NULL && IN_EX_MODE(sp) && F_ISSET(sp->gp, G_STDIN_TTY))
		(void)fputc('\n', stdout);
	/*
d1258 1
a1258 1
	if (save_cmdlen == 0)
d1272 2
a1273 7
		    "Ex command failed: remaining command input discarded");
	/*
	 * !!!
	 * Previous versions of nvi cleared mapped characters on error.  This
	 * feature was removed when users complained that it wasn't historic
	 * practice.
	 */
d1377 3
a1379 3
	 * This is probably not the right behavior for savecursor --
	 * need to figure out what the historical ex did for ";,;,;5p"
	 * or similar stupidity.
d1385 4
a1388 1
	if (excp->addrcnt == 2 && excp->addr2.lno < excp->addr1.lno) {
d1390 1
a1390 1
		    "The second address is smaller than the first");
a1399 11
 *
 * The way the "previous context" mark worked was that any "non-relative"
 * motion set it.  While ex/vi wasn't totally consistent about this, ANY
 * numeric address, search pattern, '$', or mark reference in an address
 * was considered non-relative, and set the value.  Which should explain
 * why we're hacking marks down here.  The problem was that the mark was
 * only set if the command was called, i.e. we have to set a flag and test
 * it later.
 *
 * XXX
 * This is not exactly historic practice, although it's fairly close.
a1409 1
	EX_PRIVATE *exp;
a1416 1
	exp = EXP(sp);
a1423 2
		F_SET(exp, EX_ABSMARK);

d1433 13
a1445 2
		F_SET(exp, EX_ABSMARK);

a1452 2
		F_SET(exp, EX_ABSMARK);

d1454 1
a1454 1
			msgq(sp, M_ERR, "No mark name supplied");
d1465 3
a1467 3
		 * I can't find any difference between // and \/ or between
		 * ?? and \?.  Mark Horton doesn't remember there being any
		 * difference.  C'est la vie.
d1470 1
a1470 1
			msgq(sp, M_ERR, "\\ not followed by / or ?");
d1482 1
a1482 3
search:		F_SET(exp, EX_ABSMARK);

		if (ep == NULL) {
d1484 1
a1484 1
	"A search address requires that a file have already been read in");
d1541 1
a1541 1
			    "Reference to a line number less than 0");
d1593 1
a1593 1
static __inline EXCMDLIST const *
a1608 12
}

static void
badlno(sp, lno)
	SCR *sp;
	recno_t lno;
{
	if (lno == 0)
		msgq(sp, M_ERR, "Illegal address: the file is empty");
	else
		msgq(sp, M_ERR, "Illegal address: only %lu line%s in the file",
		    lno, lno > 1 ? "s" : "");
@


1.1.1.4
log
@new public version of nvi
@
text
@d35 1
a35 1
static char sccsid[] = "@@(#)ex.c	8.157 (Berkeley) 8/17/94";
@


1.1.1.5
log
@import of nvi 1.66
@
text
@a3 2
 * Copyright (c) 1992, 1993, 1994, 1995, 1996
 *	Keith Bostic.  All rights reserved.
d5 27
a31 1
 * See the LICENSE file for redistribution information.
a33 2
#include "config.h"

d35 1
a35 1
static const char sccsid[] = "@@(#)ex.c	10.46 (Berkeley) 5/15/96";
d48 1
d52 1
d55 3
a57 2
#include "../common/common.h"
#include "../vi/vi.h"
d59 5
a63 4
#if defined(DEBUG) && defined(COMLOG)
static void	ex_comlog __P((SCR *, EXCMD *));
#endif
static EXCMDLIST const *
d65 2
a66 4
static int	ex_discard __P((SCR *));
static int	ex_line __P((SCR *, EXCMD *, MARK *, int *, int *));
static int	ex_load __P((SCR *));
static void	ex_unknown __P((SCR *, char *, size_t));
d70 1
a70 3
 *	Main ex loop.
 *
 * PUBLIC: int ex __P((SCR **));
d73 3
a75 2
ex(spp)
	SCR **spp;
d77 1
a77 4
	EX_PRIVATE *exp;
	GS *gp;
	MSGS *mp;
	SCR *sp;
d79 2
a80 5
	u_int32_t flags;

	sp = *spp;
	gp = sp->gp;
	exp = EXP(sp);
d82 1
a82 2
	/* Start the ex screen. */
	if (ex_init(sp))
d85 2
a86 7
	/* Flush any saved messages. */
	while ((mp = gp->msgq.lh_first) != NULL) {
		gp->scr_msg(sp, mp->mtype, mp->buf, mp->len);
		LIST_REMOVE(mp, q);
		free(mp->buf);
		free(mp);
	}
d88 4
a91 4
	/* If reading from a file, errors should have name and line info. */
	if (!F_ISSET(gp, G_STDIN_TTY)) {
		gp->excmd.if_lno = 1;
		gp->excmd.if_name = "script";
d96 5
a100 13
	 * Initialize the text flags.  The beautify edit option historically
	 * applied to ex command input read from a file.  In addition, the
	 * first time a ^H was discarded from the input, there was a message,
	 * "^H discarded", that was displayed.  We don't bother.
	 */
	LF_INIT(TXT_BACKSLASH | TXT_CNTRLD | TXT_CR);
	for (;; ++gp->excmd.if_lno) {
		/* Display status line and flush. */
		if (F_ISSET(sp, SC_STATUS)) {
			F_CLR(sp, SC_STATUS);
			msgq_status(sp, sp->lno, 0);
		}
		(void)ex_fflush(sp);
d102 2
a103 1
		/* Set the flags the user can reset. */
d106 2
d110 2
d113 4
a116 1
		/* Clear any current interrupts, and get a command. */
d118 2
a119 2
		if (ex_txt(sp, &sp->tiq, ':', flags))
			return (1);
d121 13
a133 3
			(void)ex_puts(sp, "\n");
			(void)ex_fflush(sp);
			continue;
a135 3
		/* Initialize the command structure. */
		CLEAR_EX_PARSER(&gp->excmd);

d137 2
a138 2
		 * If the user entered a single carriage return, send
		 * ex_cmd() a separator -- it discards single newlines.
d140 1
a140 1
		tp = sp->tiq.cqh_first;
d142 2
a143 5
			gp->excmd.cp = " ";	/* __TK__ why not |? */
			gp->excmd.clen = 1;
		} else {
			gp->excmd.cp = tp->lb;
			gp->excmd.clen = tp->len;
a144 1
		F_INIT(&gp->excmd, E_NRSEP);
d146 7
a152 2
		if (ex_cmd(sp) && !F_ISSET(gp, G_STDIN_TTY))
			return (1);
d154 2
a155 11
		if (INTERRUPTED(sp)) {
			CLR_INTERRUPT(sp);
			msgq(sp, M_ERR, "170|Interrupted");
		}

		/*
		 * If the last command caused a restart, or switched screens
		 * or into vi, return.
		 */
		if (F_ISSET(gp, G_SRESTART) || F_ISSET(sp, SC_SSWITCH | SC_VI)) {
			*spp = sp;
a157 16

		/* If the last command switched files, we don't care. */
		F_CLR(sp, SC_FSWITCH);

		/*
		 * If we're exiting this screen, move to the next one.  By
		 * definition, this means returning into vi, so return to the
		 * main editor loop.  The ordering is careful, don't discard
		 * the contents of sp until the end.
		 */
		if (F_ISSET(sp, SC_EXIT | SC_EXIT_FORCE)) {
			if (file_end(sp, NULL, F_ISSET(sp, SC_EXIT_FORCE)))
				return (1);
			*spp = screen_next(sp);
			return (screen_end(sp));
		}
d159 5
a163 1
	return (0);
d167 2
a168 23
 * ex_cmd --
 *	The guts of the ex parser: parse and execute a string containing
 *	ex commands.
 *
 * !!!
 * This code MODIFIES the string that gets passed in, to delete quoting
 * characters, etc.  The string cannot be readonly/text space, nor should
 * you expect to use it again after ex_cmd() returns.
 *
 * !!!
 * For the fun of it, if you want to see if a vi clone got the ex argument
 * parsing right, try:
 *
 *	echo 'foo|bar' > file1; echo 'foo/bar' > file2;
 *	vi
 *	:edit +1|s/|/PIPE/|w file1| e file2|1 | s/\//SLASH/|wq
 *
 * or:	vi
 *	:set|file|append|set|file
 *
 * For extra credit, try them in a startup .exrc file.
 *
 * PUBLIC: int ex_cmd __P((SCR *));
d171 1
a171 1
ex_cmd(sp)
d173 3
d177 3
a179 13
	enum nresult nret;
	EX_PRIVATE *exp;
	EXCMD *ecp;
	GS *gp;
	MARK cur;
	recno_t lno;
	size_t arg1_len, len;
	u_int32_t flags;
	long ltmp;
	int at_found, gv_found;
	int ch, cnt, delim, isaddr, namelen;
	int newscreen, notempty, tmp, vi_address;
	char *arg1, *p, *s, *t;
d181 3
a183 2
	gp = sp->gp;
	exp = EXP(sp);
d186 7
a192 3
	 * We always start running the command on the top of the stack.
	 * This means that *everything* must be resolved when we leave
	 * this function for any reason.
d194 3
a196 1
loop:	ecp = gp->ecq.lh_first;
d198 20
a217 4
	/* If we're reading a command from a file, set up error information. */
	if (ecp->if_name != NULL) {
		gp->if_lno = ecp->if_lno;
		gp->if_name = ecp->if_name;
d221 2
a222 2
	 * If a move to the end of the file is scheduled for this command,
	 * do it now.
d224 6
a229 6
	if (F_ISSET(ecp, E_MOVETOEND)) {
		if (db_last(sp, &sp->lno))
			goto rfail;
		sp->cno = 0;
		F_CLR(ecp, E_MOVETOEND);
	}
d231 26
a256 6
	/* If we found a newline, increment the count now. */
	if (F_ISSET(ecp, E_NEWLINE)) {
		++gp->if_lno;
		++ecp->if_lno;
		F_CLR(ecp, E_NEWLINE);
	}
d258 13
a270 2
	/* (Re)initialize the EXCMD structure, preserving some flags. */
	CLEAR_EX_CMD(ecp);
d272 34
a305 3
	/* Initialize the argument structures. */
	if (argv_init(sp, ecp))
		goto err;
d307 3
a309 3
	/* Initialize +cmd, saved command information. */
	arg1 = NULL;
	ecp->save_cmdlen = 0;
d312 5
a316 6
	for (notempty = 0; ecp->clen > 0; ++ecp->cp, --ecp->clen)
		if ((ch = *ecp->cp) == '\n') {
			++gp->if_lno;
			++ecp->if_lno;
		} else if (isblank(ch))
			notempty = 1;
d327 4
a330 3
	if (ecp->clen != 0 && ch == ':') {
		notempty = 1;
		while (--ecp->clen > 0 && (ch = *++ecp->cp) == ':');
d337 11
a347 11
	 * Historically, there was no escape or delimiter for a comment, e.g.
	 * :"foo|set was a single comment and nothing was output.  Since nvi
	 * permits users to escape <newline> characters into command lines, we
	 * have to check for that case.
	 */
	if (ecp->clen != 0 && ch == '"') {
		while (--ecp->clen > 0 && *++ecp->cp != '\n');
		if (*ecp->cp == '\n') {
			F_SET(ecp, E_NEWLINE);
			++ecp->cp;
			--ecp->clen;
d353 2
a354 2
	for (; ecp->clen > 0; ++ecp->cp, --ecp->clen) {
		ch = *ecp->cp;
d365 1
a365 4
	 * In vi mode, they were ignored.  In .exrc files this was a serious
	 * annoyance, as vi kept trying to treat them as print commands.  We
	 * ignore backward compatibility in this case, discarding lines that
	 * contain only <blank> characters from .exrc files.
d367 4
a370 3
	 * !!!
	 * This is where you end up when you're done a command, i.e. clen has
	 * gone to zero.  Continue if there are more commands to run.
d372 8
a379 9
	if (ecp->clen == 0 &&
	    (!notempty || F_ISSET(sp, SC_VI) || F_ISSET(ecp, E_BLIGNORE))) {
		if (ex_load(sp))
			goto rfail;
		ecp = gp->ecq.lh_first;
		if (ecp->clen == 0)
			goto rsuccess;
		goto loop;
	}
d382 11
a392 12
	 * Check to see if this is a command for which we may want to move
	 * the cursor back up to the previous line.  (The command :1<CR>
	 * wants a <newline> separator, but the command :<CR> wants to erase
	 * the command line.)  If the line is empty except for <blank>s,
	 * <carriage-return> or <eof>, we'll probably want to move up.  I
	 * don't think there's any way to get <blank> characters *after* the
	 * command character, but this is the ex parser, and I've been wrong
	 * before.
	 */
	if (F_ISSET(ecp, E_NRSEP) &&
	    ecp->clen != 0 && (ecp->clen != 1 || ecp->cp[0] != '\004'))
		F_CLR(ecp, E_NRSEP);
d395 1
a395 3
	if (ex_range(sp, ecp, &tmp))
		goto rfail;
	if (tmp)
d398 4
a401 7
	/*
	 * Skip <blank>s and any more colons (the command :3,5:print
	 * worked, historically).
	 */
	for (; ecp->clen > 0; ++ecp->cp, --ecp->clen) {
		ch = *ecp->cp;
		if (!isblank(ch) && ch != ':')
d426 5
a430 6
	newscreen = 0;
	if (ecp->clen != 0 && ecp->cp[0] != '|' && ecp->cp[0] != '\n') {
		if (strchr(SINGLE_CHAR_COMMANDS, *ecp->cp)) {
			p = ecp->cp;
			++ecp->cp;
			--ecp->clen;
d433 2
a434 3
			for (p = ecp->cp;
			    ecp->clen > 0; --ecp->clen, ++ecp->cp)
				if (!isalpha(*ecp->cp))
d436 2
a437 2
			if ((namelen = ecp->cp - p) == 0) {
				msgq(sp, M_ERR, "080|Unknown command name");
a449 3
		 * Adding commands that start with 'd', and match "delete"
		 * up to a l, p, +, - or # character can break this code.
		 *
d451 3
a453 3
		 * Capital letters beginning the command names ex, edit,
		 * next, previous, tag and visual (in vi mode) indicate the
		 * command should happen in a new screen.
d455 1
a455 2
		switch (p[0]) {
		case 'd':
d458 7
a464 9
			if (s[0] == 'l' || s[0] == 'p' || s[0] == '+' ||
			    s[0] == '-' || s[0] == '^' || s[0] == '#') {
				len = (ecp->cp - p) - (s - p);
				ecp->cp -= len;
				ecp->clen += len;
				ecp->rcmd = cmds[C_DELETE];
				ecp->rcmd.syntax = "1bca1";
				ecp->cmd = &ecp->rcmd;
				goto skip_srch;
a465 5
			break;
		case 'E': case 'N': case 'P': case 'T': case 'V':
			newscreen = 1;
			p[0] = tolower(p[0]);
			break;
d476 3
a478 9
		 * Historic vi permitted any flag to follow the s command, e.g.
		 * "s/e/E/|s|sgc3p" was legal.  Make the command "sgc" work.
		 * Since the following characters all have to be flags, i.e.
		 * alphabetics, we can let the s command routine return errors
		 * if it was some illegal command string.  This code will break
		 * if an "sg" or similar command is ever added.  The substitute
		 * code doesn't care if it's a "cgr" flag or a "#lp" flag that
		 * follows the 's', but we limit the choices here to "cgr" so
		 * that we get unknown command messages for wrong combinations.
d480 1
a480 1
		if ((ecp->cmd = ex_comm_search(p, namelen)) == NULL)
d482 5
d489 3
a491 17
					ecp->cp -= namelen - 1;
					ecp->clen += namelen - 1;
					ecp->cmd = &cmds[C_K];
					break;
				}
				goto unknown;
			case 's':
				for (s = p + 1, cnt = namelen; --cnt; ++s)
					if (s[0] != 'c' &&
					    s[0] != 'g' && s[0] != 'r')
						break;
				if (cnt == 0) {
					ecp->cp -= namelen - 1;
					ecp->clen += namelen - 1;
					ecp->rcmd = cmds[C_SUBSTITUTE];
					ecp->rcmd.fn = ex_subagain;
					ecp->cmd = &ecp->rcmd;
d496 2
a497 3
unknown:			if (newscreen)
					p[0] = toupper(p[0]);
				ex_unknown(sp, p, namelen);
d501 7
a507 8
		/*
		 * The visual command has a different syntax when called
		 * from ex than when called from a vi colon command.  FMH.
		 * Make the change now, before we test for the newscreen
		 * semantic, so that we're testing the right one.
		 */
skip_srch:	if (ecp->cmd == &cmds[C_VISUAL_EX] && F_ISSET(sp, SC_VI))
			ecp->cmd = &cmds[C_VISUAL_VI];
d509 5
a513 20
		/*
		 * !!!
		 * Historic vi permitted a capital 'P' at the beginning of
		 * any command that started with 'p'.  Probably wanted the
		 * P[rint] command for backward compatibility, and the code
		 * just made Preserve and Put work by accident.  Nvi uses
		 * Previous to mean previous-in-a-new-screen, so be careful.
		 */
		if (newscreen && !F_ISSET(ecp->cmd, E_NEWSCREEN) &&
		    (ecp->cmd == &cmds[C_PRINT] ||
		    ecp->cmd == &cmds[C_PRESERVE]))
			newscreen = 0;

		/* Test for a newscreen associated with this command. */
		if (newscreen && !F_ISSET(ecp->cmd, E_NEWSCREEN))
			goto unknown;

		/* Secure means no shell access. */
		if (F_ISSET(ecp->cmd, E_SECURE) && O_ISSET(sp, O_SECURE)) {
			ex_emsg(sp, ecp->cmd->name, EXM_SECURE);
d522 4
a525 5
		if ((ecp->cmd == &cmds[C_SHIFTL] && *p == '<') ||
		    (ecp->cmd == &cmds[C_SHIFTR] && *p == '>')) {
			for (ch = *p;
			    ecp->clen > 0; --ecp->clen, ++ecp->cp)
				if (*ecp->cp != ch)
d527 1
a527 1
			if (argv_exp0(sp, ecp, p, ecp->cp - p))
d531 7
d539 7
a545 7
		if (ecp->cmd == &cmds[C_HASH])
			exp->fdef = E_C_HASH;
		else if (ecp->cmd == &cmds[C_LIST])
			exp->fdef = E_C_LIST;
		else if (ecp->cmd == &cmds[C_PRINT])
			exp->fdef = E_C_PRINT;
		F_CLR(ecp, E_USELASTCMD);
d548 1
a548 1
		ecp->cmd = &cmds[C_PRINT];
d551 1
a551 1
		F_SET(ecp, exp->fdef);
d556 2
a557 2
		 * we up the address by one.  (I have no idea why globals are
		 * exempted, but it's (ahem) historic practice.)
d559 4
a562 4
		if (ecp->addrcnt == 0 && !F_ISSET(sp, SC_EX_GLOBAL)) {
			ecp->addrcnt = 1;
			ecp->addr1.lno = sp->lno + 1;
			ecp->addr1.cno = sp->cno;
d565 1
a565 1
		F_SET(ecp, E_USELASTCMD);
d576 2
a577 2
		F_SET(ecp, E_OPTNUM);
		FL_SET(ecp->iflags, E_C_HASH);
d579 4
a582 1
		F_CLR(ecp, E_OPTNUM);
d584 11
a594 2
	/* Check for ex mode legality. */
	if (F_ISSET(sp, SC_EX) && (F_ISSET(ecp->cmd, E_VIONLY) || newscreen)) {
d596 2
a597 1
		    "082|%s: command not available in ex mode", ecp->cmd->name);
a600 5
	/* Add standard command flags. */
	F_SET(ecp, ecp->cmd->flags);
	if (!newscreen)
		F_CLR(ecp, E_NEWSCREEN);

d603 9
a611 9
	 * are the end of the string (ecp->clen), or unescaped (by <literal
	 * next> characters) <newline> or '|' characters.  As we're now past
	 * possible addresses, we can determine how long the command is, so we
	 * don't have to look for all the possible terminations.  Naturally,
	 * there are some exciting special cases:
	 *
	 * 1: The bang, global, v and the filter versions of the read and
	 *    write commands are delimited by <newline>s (they can contain
	 *    shell pipes).
d614 2
a615 2
	 * 3: The s command takes an RE as its first argument, and wants it
	 *    to be specially delimited.
d618 3
a620 3
	 * next, vi visual, and s commands didn't delimit the command.  And,
	 * in the filter cases for read and write, and the bang, global and v
	 * commands, they did not delimit the command at all.
d625 1
a625 1
	 *	:s/|/PIPE/
d631 1
a631 1
	 *	:s/a/b/|s/c/d|set
d649 3
a651 3
	ecp->save_cmd = ecp->cp;
	if (ecp->cmd == &cmds[C_EDIT] || ecp->cmd == &cmds[C_EX] ||
	    ecp->cmd == &cmds[C_NEXT] || ecp->cmd == &cmds[C_VISUAL_VI]) {
d657 4
a660 4
		if (ecp->clen > 0 && *ecp->cp == '!') {
			++ecp->cp;
			--ecp->clen;
			FL_SET(ecp->iflags, E_C_FORCE);
d663 1
a663 1
			ecp->save_cmd = ecp->cp;
d665 2
a666 2
		for (; ecp->clen > 0; --ecp->clen, ++ecp->cp)
			if (!isblank(*ecp->cp))
d678 8
a685 10
		if (ecp->clen > 0 && *ecp->cp == '+') {
			++ecp->cp;
			--ecp->clen;
			for (arg1 = p = ecp->cp;
			    ecp->clen > 0; --ecp->clen, ++ecp->cp) {
				ch = *ecp->cp;
				if (IS_ESCAPE(sp,
				    ecp, ch) && ecp->clen > 1) {
					--ecp->clen;
					ch = *++ecp->cp;
d690 1
a690 1
			arg1_len = ecp->cp - arg1;
d693 1
a693 1
			ecp->save_cmd = ecp->cp;
d695 5
a699 5
	} else if (ecp->cmd == &cmds[C_BANG] ||
	    ecp->cmd == &cmds[C_GLOBAL] || ecp->cmd == &cmds[C_V]) {
		ecp->cp += ecp->clen;
		ecp->clen = 0;
	} else if (ecp->cmd == &cmds[C_READ] || ecp->cmd == &cmds[C_WRITE]) {
d704 2
a705 2
		for (; ecp->clen > 0; --ecp->clen, ++ecp->cp) {
			ch = *ecp->cp;
d709 3
a711 3
		if (ecp->clen > 0 && ch == '!') {
			ecp->cp += ecp->clen;
			ecp->clen = 0;
d713 1
a713 1
	} else if (ecp->cmd == &cmds[C_SUBSTITUTE]) {
d718 2
a719 1
		 * into something like ":s g", so use the special s command.
d721 2
a722 2
		for (; ecp->clen > 0; --ecp->clen, ++ecp->cp)
			if (!isblank(ecp->cp[0]))
d725 3
a727 5
		if (isalnum(ecp->cp[0]) || ecp->cp[0] == '|') {
			ecp->rcmd = cmds[C_SUBSTITUTE];
			ecp->rcmd.fn = ex_subagain;
			ecp->cmd = &ecp->rcmd;
		} else if (ecp->clen > 0) {
d736 8
a743 10
			delim = *ecp->cp;
			++ecp->cp;
			--ecp->clen;
			for (cnt = 2; ecp->clen > 0 &&
			    cnt != 0; --ecp->clen, ++ecp->cp)
				if (ecp->cp[0] == '\\' &&
				    ecp->clen > 1) {
					++ecp->cp;
					--ecp->clen;
				} else if (ecp->cp[0] == delim)
a746 1

d757 1
a757 1
	 * '|' characters or literal next characters are stripped as they're
d760 5
a764 5
	vi_address = ecp->clen != 0 && ecp->cp[0] != '\n';
	for (cnt = 0, p = ecp->cp; ecp->clen > 0; --ecp->clen, ++ecp->cp) {
		ch = ecp->cp[0];
		if (IS_ESCAPE(sp, ecp, ch) && ecp->clen > 1) {
			tmp = ecp->cp[1];
d766 4
a769 6
				if (tmp == '\n') {
					++gp->if_lno;
					++ecp->if_lno;
				}
				--ecp->clen;
				++ecp->cp;
d775 2
a776 2
				F_SET(ecp, E_NEWLINE);
			--ecp->clen;
d786 5
a790 5
	p = ecp->cp + 1;
	ecp->cp = ecp->save_cmd;
	ecp->save_cmd = p;
	ecp->save_cmdlen = ecp->clen;
	ecp->clen = ((ecp->save_cmd - ecp->cp) - 1) - cnt;
d793 1
a793 2
	 * QUOTING NOTE:
	 *
d800 2
a801 2
	if (ecp->cmd == &cmds[C_SET])
		for (p = ecp->cp, len = ecp->clen; len > 0; --len, ++p)
d816 2
a817 2
	 * Note, we also add the E_ADDR_ZERO flag to the command flags, for the
	 * case where the 0 address is only valid if it's a default address.
d823 1
a823 1
	switch (F_ISSET(ecp, E_ADDR1 | E_ADDR2 | E_ADDR2_ALL | E_ADDR2_NONE)) {
d825 1
a825 1
		switch (ecp->addrcnt) {
d827 4
a830 4
			ecp->addrcnt = 1;
			F_SET(ecp, E_ADDR_DEF);
			if (F_ISSET(ecp, E_ADDR_ZERODEF)) {
				if (db_last(sp, &lno))
d833 2
a834 2
					ecp->addr1.lno = 0;
					F_SET(ecp, E_ADDR_ZERO);
d836 1
a836 1
					ecp->addr1.lno = sp->lno;
d838 2
a839 2
				ecp->addr1.lno = sp->lno;
			ecp->addr1.cno = sp->cno;
d844 2
a845 2
			ecp->addrcnt = 1;
			ecp->addr1 = ecp->addr2;
d849 1
a849 1
		if (ecp->addrcnt == 0)		/* Default to nothing. */
d851 1
a851 1
		goto two_addr;
d853 8
a860 11
		if (ecp->addrcnt == 0) {	/* Default entire/empty file. */
			F_SET(ecp, E_ADDR_DEF);
			ecp->addrcnt = 2;
			if (sp->ep == NULL)
				ecp->addr2.lno = 0;
			else if (db_last(sp, &ecp->addr2.lno))
				goto err;
			if (F_ISSET(ecp, E_ADDR_ZERODEF) &&
			    ecp->addr2.lno == 0) {
				ecp->addr1.lno = 0;
				F_SET(ecp, E_ADDR_ZERO);
d862 3
a864 3
				ecp->addr1.lno = 1;
			ecp->addr1.cno = ecp->addr2.cno = 0;
			F_SET(ecp, E_ADDR2_ALL);
d869 1
a869 1
two_addr:	switch (ecp->addrcnt) {
d871 4
a874 5
			ecp->addrcnt = 2;
			F_SET(ecp, E_ADDR_DEF);
			if (sp->lno == 1 &&
			    F_ISSET(ecp, E_ADDR_ZERODEF)) {
				if (db_last(sp, &lno))
d877 2
a878 2
					ecp->addr1.lno = ecp->addr2.lno = 0;
					F_SET(ecp, E_ADDR_ZERO);
d880 1
a880 2
					ecp->addr1.lno =
					    ecp->addr2.lno = sp->lno;
d882 2
a883 2
				ecp->addr1.lno = ecp->addr2.lno = sp->lno;
			ecp->addr1.cno = ecp->addr2.cno = sp->cno;
d886 2
a887 2
			ecp->addrcnt = 2;
			ecp->addr2 = ecp->addr1;
d894 1
a894 1
		if (ecp->addrcnt)		/* Error. */
d904 6
a909 6
	if (ecp->cmd == &cmds[C_SCROLL]) {
		ecp->addrcnt = 2;
		ecp->addr1.lno = sp->lno + 1;
		ecp->addr2.lno = sp->lno + O_VAL(sp, O_SCROLL);
		ecp->addr1.cno = ecp->addr2.cno = sp->cno;
		if (db_last(sp, &lno))
d911 2
a912 2
		if (lno != 0 && lno > sp->lno && ecp->addr2.lno > lno)
			ecp->addr2.lno = lno;
d915 2
a916 2
	ecp->flagoff = 0;
	for (p = ecp->cmd->syntax; *p != '\0'; ++p) {
d923 4
a926 4
			if (ecp->clen > 0 && *ecp->cp == '!') {
				++ecp->cp;
				--ecp->clen;
				FL_SET(ecp->iflags, E_C_FORCE);
d932 2
a933 2
		for (; ecp->clen > 0; --ecp->clen, ++ecp->cp)
			if (!isblank(*ecp->cp))
d935 11
a945 1
		if (ecp->clen == 0)
d960 2
a961 2
			for (; ecp->clen; --ecp->clen, ++ecp->cp)
				switch (*ecp->cp) {
d963 1
a963 1
					++ecp->flagoff;
d966 1
a966 2
				case '^':
					--ecp->flagoff;
d969 3
a971 3
					F_CLR(ecp, E_OPTNUM);
					FL_SET(ecp->iflags, E_C_HASH);
					exp->fdef |= E_C_HASH;
d974 2
a975 2
					FL_SET(ecp->iflags, E_C_LIST);
					exp->fdef |= E_C_LIST;
d978 2
a979 2
					FL_SET(ecp->iflags, E_C_PRINT);
					exp->fdef |= E_C_PRINT;
d982 1
a982 1
					goto end_case1;
d984 1
a984 1
end_case1:		break;
d987 2
a988 2
			for (; ecp->clen; --ecp->clen, ++ecp->cp)
				switch (*ecp->cp) {
d990 1
a990 1
					FL_SET(ecp->iflags, E_C_DASH);
d993 1
a993 1
					FL_SET(ecp->iflags, E_C_DOT);
d996 1
a996 1
					FL_SET(ecp->iflags, E_C_PLUS);
d999 1
a999 1
					FL_SET(ecp->iflags, E_C_CARAT);
d1003 1
a1003 1
						FL_SET(ecp->iflags, E_C_EQUAL);
d1008 1
a1008 1
					goto end_case23;
d1010 1
a1010 1
end_case23:		break;
d1020 1
a1020 2
			if ((ecp->cp[0] == '+' || ecp->cp[0] == '-' ||
			    ecp->cp[0] == '^' || ecp->cp[0] == '#') &&
d1029 5
a1033 5
			if (!isdigit(ecp->cp[0])) {
				ecp->buffer = *ecp->cp;
				++ecp->cp;
				--ecp->clen;
				FL_SET(ecp->iflags, E_C_BUFFER);
d1039 2
a1040 2
			if (!isdigit(*ecp->cp) && (*p != '+' ||
			    (*ecp->cp != '+' && *ecp->cp != '-')))
d1043 6
a1048 11
			if (*ecp->cp == '-')
				FL_SET(ecp->iflags, E_C_COUNT_NEG);
			else if (*ecp->cp == '+')
				FL_SET(ecp->iflags, E_C_COUNT_POS);
			if ((nret =
			    nget_slong(&ltmp, ecp->cp, &t, 10)) != NUM_OK) {
				ex_badaddr(sp, NULL, A_NOTSET, nret);
				goto err;
			}
			if (ltmp == 0 && *p != '0') {
				msgq(sp, M_ERR, "083|Count may not be zero");
d1051 2
a1052 3
			ecp->clen -= (t - ecp->cp);
			ecp->cp = t;

d1054 1
a1054 1
			 * Counts as address offsets occur in commands taking
d1063 2
a1064 2
				ecp->addr1 = ecp->addr2;
				ecp->addr2.lno = ecp->addr1.lno + ltmp - 1;
d1066 2
a1067 2
				ecp->count = ltmp;
			FL_SET(ecp->iflags, E_C_COUNT);
d1070 2
a1071 1
			if (argv_exp2(sp, ecp, ecp->cp, ecp->clen))
d1073 1
a1073 1
			goto arg_cnt_chk;
d1075 1
a1075 11
			/*
			 * Get a line specification.
			 *
			 * If the line was a search expression, we may have
			 * changed state during the call, and we're now
			 * searching the file.  Push ourselves onto the state
			 * stack.
			 */
			if (ex_line(sp, ecp, &cur, &isaddr, &tmp))
				goto rfail;
			if (tmp)
a1076 1

d1078 3
a1080 3
			if (!isaddr) {
				msgq_str(sp, M_ERR, ecp->cp,
				     "084|%s: bad line specification");
d1083 5
a1087 6
			/*
			 * The target line should exist for these commands,
			 * but 0 is legal for them as well.
			 */
			if (cur.lno != 0 && !db_exist(sp, cur.lno)) {
				ex_badaddr(sp, NULL, A_EOF, NUM_OK);
d1090 1
a1090 1
			ecp->lineno = cur.lno;
d1093 4
a1096 7
			if (ecp->clen != 0) {
				if (argv_exp1(sp, ecp, ecp->cp,
				    ecp->clen, ecp->cmd == &cmds[C_BANG]))
					goto err;
				goto addr_verify;
			}
			/* FALLTHROUGH */
d1098 1
a1098 1
			if (argv_exp0(sp, ecp, ecp->cp, ecp->clen))
d1100 1
a1100 1
			goto addr_verify;
d1106 2
a1107 2
			 * character.  Quoting characters are stripped here
			 * since they are no longer useful.
d1111 5
a1115 7
			for (p = t = ecp->cp;
			    ecp->clen > 0; --ecp->clen, ++ecp->cp) {
				ch = *ecp->cp;
				if (IS_ESCAPE(sp,
				    ecp, ch) && ecp->clen > 1) {
					--ecp->clen;
					*p++ = *++ecp->cp;
d1117 2
a1118 2
					++ecp->cp;
					--ecp->clen;
d1123 1
a1123 1
			if (argv_exp0(sp, ecp, t, p - t))
d1127 2
a1128 3
			for (; ecp->clen > 0;
			    --ecp->clen, ++ecp->cp) {
				ch = *ecp->cp;
d1132 1
a1132 1
			if (ecp->clen == 0)
d1136 5
a1140 7
			for (p = t = ecp->cp; ecp->clen > 0;
			    --ecp->clen, ++ecp->cp, ++p) {
				ch = *ecp->cp;
				if (IS_ESCAPE(sp,
				    ecp, ch) && ecp->clen > 1) {
					--ecp->clen;
					*p = *++ecp->cp;
d1144 1
a1144 1
			if (argv_exp0(sp, ecp, t, p - t))
d1146 1
a1146 1
			goto addr_verify;
d1148 1
a1148 1
			if (argv_exp3(sp, ecp, ecp->cp, ecp->clen))
d1150 1
a1150 1
arg_cnt_chk:		if (*++p != 'N') {		/* N */
d1156 1
a1156 1
				tmp = *p - '0';
d1158 1
a1158 1
				    exp->argsoff != tmp)
d1161 1
a1161 1
			goto addr_verify;
d1164 2
a1165 2
			    "085|Internal syntax table error (%s: %s)",
			    ecp->cmd->name, KEY_NAME(sp, *p));
d1170 2
a1171 2
	for (; ecp->clen > 0; --ecp->clen) {
		ch = *ecp->cp++;
d1177 2
a1178 2
	 * There shouldn't be anything left, and no more required fields,
	 * i.e neither 'l' or 'r' in the syntax string.
d1180 2
a1181 2
	if (ecp->clen != 0 || strpbrk(p, "lr")) {
usage:		msgq(sp, M_ERR, "086|Usage: %s", ecp->cmd->usage);
d1185 2
a1186 11
	/*
	 * Verify that the addresses are legal.  Check the addresses here,
	 * because this is a place where all ex addresses pass through.
	 * (They don't all pass through ep_line(), for instance.)  We're
	 * assuming that any non-existent line doesn't exist because it's
	 * past the end-of-file.  That's a pretty good guess.
	 *
	 * If it's a "default vi command", an address of zero is okay.
	 */
addr_verify:
	switch (ecp->addrcnt) {
d1188 2
d1198 5
a1202 14
		if (ecp->addr2.lno == 0) {
			if (!F_ISSET(ecp, E_ADDR_ZERO) &&
			    (F_ISSET(sp, SC_EX) ||
			    !F_ISSET(ecp, E_USELASTCMD))) {
				ex_badaddr(sp, ecp->cmd, A_ZERO, NUM_OK);
				goto err;
			}
		} else if (!db_exist(sp, ecp->addr2.lno))
			if (FL_ISSET(ecp->iflags, E_C_COUNT)) {
				if (db_last(sp, &lno))
					goto err;
				ecp->addr2.lno = lno;
			} else {
				ex_badaddr(sp, NULL, A_EOF, NUM_OK);
d1207 17
a1223 9
		if (ecp->addr1.lno == 0) {
			if (!F_ISSET(ecp, E_ADDR_ZERO) &&
			    (F_ISSET(sp, SC_EX) ||
			    !F_ISSET(ecp, E_USELASTCMD))) {
				ex_badaddr(sp, ecp->cmd, A_ZERO, NUM_OK);
				goto err;
			}
		} else if (!db_exist(sp, ecp->addr1.lno)) {
			ex_badaddr(sp, NULL, A_EOF, NUM_OK);
a1234 4
	 * In addition, IF THE LINE CHANGES, move to the first nonblank of
	 * the line.
	 *
	 * !!!
d1238 2
a1239 3
	if ((F_ISSET(sp, SC_VI) || F_ISSET(ecp, E_NOPRDEF)) &&
	    F_ISSET(ecp, E_USELASTCMD) && vi_address == 0) {
		switch (ecp->addrcnt) {
d1241 2
a1242 7
			if (sp->lno !=
			    (ecp->addr2.lno ? ecp->addr2.lno : 1)) {
				sp->lno =
				    ecp->addr2.lno ? ecp->addr2.lno : 1;
				sp->cno = 0;
				(void)nonblank(sp, sp->lno, &sp->cno);
			}
d1245 2
a1246 7
			if (sp->lno !=
			    (ecp->addr1.lno ? ecp->addr1.lno : 1)) {
				sp->lno =
				    ecp->addr1.lno ? ecp->addr1.lno : 1;
				sp->cno = 0;
				(void)nonblank(sp, sp->lno, &sp->cno);
			}
d1249 2
a1250 2
		ecp->cp = ecp->save_cmd;
		ecp->clen = ecp->save_cmdlen;
d1259 1
a1259 1
	if (F_ISSET(ecp, E_ABSMARK)) {
d1262 2
a1263 2
		F_CLR(ecp, E_ABSMARK);
		if (mark_set(sp, ABSMARK1, &cur, 1))
d1267 23
a1289 2
#if defined(DEBUG) && defined(COMLOG)
	ex_comlog(sp, ecp);
d1291 3
d1295 1
a1295 1
	if (F_ISSET(sp, SC_EX))
d1302 2
a1303 2
	if (sp->ep != NULL && !F_ISSET(sp, SC_EX_GLOBAL))
		(void)log_cursor(sp);
d1314 29
a1342 12
	 * special commands, we move back up to the previous line, and erase
	 * the prompt character with the output.  Since ex runs in canonical
	 * mode, we don't have to do anything else, a <newline> has already
	 * been echoed by the tty driver.  It's OK if vi calls us -- we won't
	 * be in ex mode so we'll do nothing.
	 */
	if (F_ISSET(ecp, E_NRSEP)) {
		if (sp->ep != NULL &&
		    F_ISSET(sp, SC_EX) && F_ISSET(gp, G_STDIN_TTY) &&
		    (F_ISSET(ecp, E_USELASTCMD) || ecp->cmd == &cmds[C_SCROLL]))
			gp->scr_ex_adjust(sp, EX_TERM_SCROLL);
		F_CLR(ecp, E_NRSEP);
d1345 5
a1349 9
	/*
	 * Call the underlying function for the ex command.
	 *
	 * XXX
	 * Interrupts behave like errors, for now.
	 */
	if (ecp->cmd->fn(sp, ecp) || INTERRUPTED(sp)) {
		if (!F_ISSET(gp, G_STDIN_TTY))
			F_SET(sp, SC_EXIT_FORCE);
a1350 1
	}
d1353 5
a1357 5
	/* Make sure no function left global temporary space locked. */
	if (F_ISSET(gp, G_TMP_INUSE)) {
		F_CLR(gp, G_TMP_INUSE);
		msgq(sp, M_ERR, "087|%s: temporary buffer not released",
		    ecp->cmd->name);
d1360 47
a1406 13
	/*
	 * Ex displayed the number of lines modified immediately after each
	 * command, so the command "1,10d|1,10d" would display:
	 *
	 *	10 lines deleted
	 *	10 lines deleted
	 *	<autoprint line>
	 *
	 * Executing ex commands from vi only reported the final modified
	 * lines message -- that's wrong enough that we don't match it.
	 */
	if (F_ISSET(sp, SC_EX))
		msgq_rpt(sp);
d1413 10
a1422 11
	 * May not match historic practice (which I've never been able to
	 * completely figure out.)  For example, the '=' command from vi
	 * mode often got the offset wrong, and complained it was too large,
	 * but didn't seem to have a problem with the cursor.  If anyone
	 * complains, ask them how it's supposed to work, they might know.
	 */
	if (sp->ep != NULL && ecp->flagoff) {
		if (ecp->flagoff < 0) {
			if (sp->lno <= -ecp->flagoff) {
				msgq(sp, M_ERR,
				    "088|Flag offset to before line 1");
d1426 1
a1426 2
			if (!NPFITS(MAX_REC_NUMBER, sp->lno, ecp->flagoff)) {
				ex_badaddr(sp, NULL, A_NOTSET, NUM_OVER);
d1428 2
a1429 4
			}
			if (!db_exist(sp, sp->lno + ecp->flagoff)) {
				msgq(sp, M_ERR,
				    "089|Flag offset past end-of-file");
d1433 1
a1433 1
		sp->lno += ecp->flagoff;
d1437 2
a1438 4
	 * If the command was successful may want to display a line based on
	 * the autoprint option or an explicit print flag.  (Make sure that
	 * there's a line to display.)  Also, the autoprint edit option is
	 * turned off for the duration of global commands.
d1440 2
a1441 1
	if (F_ISSET(sp, SC_EX) && sp->ep != NULL && sp->lno != 0) {
d1446 2
a1447 2
		if (FL_ISSET(ecp->iflags, E_CLRFLAG))
			FL_CLR(ecp->iflags, E_C_HASH | E_C_LIST | E_C_PRINT);
d1449 3
a1451 3
		/* If hash set only because of the number option, discard it. */
		if (F_ISSET(ecp, E_OPTNUM))
			FL_CLR(ecp->iflags, E_C_HASH);
d1454 4
a1457 3
		 * If there was an explicit flag to display the new cursor line,
		 * or autoprint is set and a change was made, display the line.
		 * If any print flags were set use them, else default to print.
d1459 5
a1463 12
		LF_INIT(FL_ISSET(ecp->iflags, E_C_HASH | E_C_LIST | E_C_PRINT));
		if (!LF_ISSET(E_C_HASH | E_C_LIST | E_C_PRINT | E_NOAUTO) &&
		    !F_ISSET(sp, SC_EX_GLOBAL) &&
		    O_ISSET(sp, O_AUTOPRINT) && F_ISSET(ecp, E_AUTOPRINT))
			LF_INIT(E_C_PRINT);

		if (LF_ISSET(E_C_HASH | E_C_LIST | E_C_PRINT)) {
			cur.lno = sp->lno;
			cur.cno = 0;
			(void)ex_print(sp, ecp, &cur, &cur, flags);
		}
	}
d1465 6
a1470 29
	/*
	 * If the command had an associated "+cmd", it has to be executed
	 * before we finish executing any more of this ex command.  For
	 * example, consider a .exrc file that contains the following lines:
	 *
	 *	:set all
	 *	:edit +25 file.c|s/abc/ABC/|1
	 *	:3,5 print
	 *
	 * This can happen more than once -- the historic vi simply hung or
	 * dropped core, of course.  Prepend the + command back into the
	 * current command and continue.  We may have to add up to two more
	 * characters, a <literal next> and a command separator.  We know
	 * that it will still fit because we discarded at least one space
	 * and the + character.
	 */
	if (arg1_len != 0) {
		/* Add in a command separator. */
		*--ecp->save_cmd = '\n';
		++ecp->save_cmdlen;

		/*
		 * If the last character of the + command was a <literal next>
		 * character, it would be treated differently because of the
		 * append.  Quote it, if necessary.
		 */
		if (IS_ESCAPE(sp, ecp, arg1[arg1_len - 1])) {
			*--ecp->save_cmd = CH_LITERAL;
			++ecp->save_cmdlen;
a1471 65

		ecp->save_cmd -= arg1_len;
		ecp->save_cmdlen += arg1_len;
		memmove(ecp->save_cmd, arg1, arg1_len);

		/*
		 * Any commands executed from a +cmd are executed starting at
		 * the last line, first column of the file -- NOT the first
		 * nonblank.)  The main file startup code doesn't know that a
		 * +cmd was set, however, so it may have put us at the top of
		 * the file.  (Note, this is safe because we must have switched
		 * files to get here.)
		 */
		F_SET(ecp, E_MOVETOEND);
	}

	/* Update the current command. */
	ecp->cp = ecp->save_cmd;
	ecp->clen = ecp->save_cmdlen;

	/*
	 * !!!
	 * If we've changed screens or underlying files, any pending global or
	 * v command, or @@ buffer that has associated addresses, has to be
	 * discarded.  This is historic practice for globals, and necessary for
	 * @@ buffers that had associated addresses.
	 *
	 * Otherwise, if we've changed underlying files, it's not a problem,
	 * we continue with the rest of the ex command(s), operating on the
	 * new file.  However, if we switch screens (either by exiting or by
	 * an explicit command), we have no way of knowing where to put output
	 * messages, and, since we don't control screens here, we could screw
	 * up the upper layers, (e.g. we could exit/reenter a screen multiple
	 * times).  So, return and continue after we've got a new screen.
	 */
	if (F_ISSET(sp, SC_EXIT | SC_EXIT_FORCE | SC_FSWITCH | SC_SSWITCH)) {
		at_found = gv_found = 0;
		for (ecp = sp->gp->ecq.lh_first;
		    ecp != NULL; ecp = ecp->q.le_next)
			switch (ecp->agv_flags) {
			case 0:
			case AGV_AT_NORANGE:
				break;
			case AGV_AT:
				if (!at_found) {
					at_found = 1;
					msgq(sp, M_ERR,
		"090|@@ with range running when the file/screen changed");
				}
				break;
			case AGV_GLOBAL:
			case AGV_V:
				if (!gv_found) {
					gv_found = 1;
					msgq(sp, M_ERR,
		"091|Global/v command running when the file/screen changed");
				}
				break;
			default:
				abort();
			}
		if (at_found || gv_found)
			goto discard;
		if (F_ISSET(sp, SC_EXIT | SC_EXIT_FORCE | SC_SSWITCH))
			goto rsuccess;
d1474 2
d1479 20
a1498 14
err:	/*
	 * On command failure, we discard keys and pending commands remaining,
	 * as well as any keys that were mapped and waiting.  The save_cmdlen
	 * test is not necessarily correct.  If we fail early enough we don't
	 * know if the entire string was a single command or not.  Guess, as
	 * it's useful to know if commands other than the current one are being
	 * discarded.
	 */
	if (ecp->save_cmdlen == 0)
		for (; ecp->clen; --ecp->clen) {
			ch = *ecp->cp++;
			if (IS_ESCAPE(sp, ecp, ch) && ecp->clen > 1) {
				--ecp->clen;
				++ecp->cp;
d1500 2
a1501 2
				if (ecp->clen > 1)
					ecp->save_cmdlen = 1;
d1505 10
a1514 20
	if (ecp->save_cmdlen != 0 || gp->ecq.lh_first != &gp->excmd) {
discard:	msgq(sp, M_BERR,
		    "092|Ex command failed: pending commands discarded");
		ex_discard(sp);
	}
	if (v_event_flush(sp, CH_MAPPED))
		msgq(sp, M_BERR,
		    "093|Ex command failed: mapped keys discarded");

rfail:	tmp = 1;
	if (0)
rsuccess:	tmp = 0;

	/* Turn off any file name error information. */
	gp->if_name = NULL;

	/* Turn off the global bit. */
	F_CLR(sp, SC_EX_GLOBAL);

	return (tmp);
d1518 2
a1519 4
 * ex_range --
 *	Get a line range for ex commands, or perform a vi ex address search.
 *
 * PUBLIC: int ex_range __P((SCR *, EXCMD *, int *));
d1521 2
a1522 2
int
ex_range(sp, ecp, errp)
d1524 4
a1527 2
	EXCMD *ecp;
	int *errp;
d1529 18
a1546 5
	enum { ADDR_FOUND, ADDR_NEED, ADDR_NONE } addr;
	GS *gp;
	EX_PRIVATE *exp;
	MARK m;
	int isaddr;
d1548 4
a1551 1
	*errp = 0;
d1553 4
a1556 36
	/*
	 * Parse comma or semi-colon delimited line specs.
	 *
	 * Semi-colon delimiters update the current address to be the last
	 * address.  For example, the command
	 *
	 *	:3;/pattern/ecp->cp
	 *
	 * will search for pattern from line 3.  In addition, if ecp->cp
	 * is not a valid command, the current line will be left at 3, not
	 * at the original address.
	 *
	 * Extra addresses are discarded, starting with the first.
	 *
	 * !!!
	 * If any addresses are missing, they default to the current line.
	 * This was historically true for both leading and trailing comma
	 * delimited addresses as well as for trailing semicolon delimited
	 * addresses.  For consistency, we make it true for leading semicolon
	 * addresses as well.
	 */
	gp = sp->gp;
	exp = EXP(sp);
	for (addr = ADDR_NONE, ecp->addrcnt = 0; ecp->clen > 0;)
		switch (*ecp->cp) {
		case '%':		/* Entire file. */
			/* Vi ex address searches didn't permit % signs. */
			if (F_ISSET(ecp, E_VISEARCH))
				goto ret;

			/* It's an error if the file is empty. */
			if (sp->ep == NULL) {
				ex_badaddr(sp, NULL, A_EMPTY, NUM_OK);
				*errp = 1;
				return (0);
			}
d1558 4
a1561 8
			 * !!!
			 * A percent character addresses all of the lines in
			 * the file.  Historically, it couldn't be followed by
			 * any other address.  We do it as a text substitution
			 * for simplicity.  POSIX 1003.2 is expected to follow
			 * this practice.
			 *
			 * If it's an empty file, the first line is 0, not 1.
d1563 18
a1580 4
			if (addr == ADDR_FOUND) {
				ex_badaddr(sp, NULL, A_COMBO, NUM_OK);
				*errp = 1;
				return (0);
a1581 51
			if (db_last(sp, &ecp->addr2.lno))
				return (1);
			ecp->addr1.lno = ecp->addr2.lno == 0 ? 0 : 1;
			ecp->addr1.cno = ecp->addr2.cno = 0;
			ecp->addrcnt = 2;
			addr = ADDR_FOUND;
			++ecp->cp;
			--ecp->clen;
			break;
		case ',':               /* Comma delimiter. */
			/* Vi ex address searches didn't permit commas. */
			if (F_ISSET(ecp, E_VISEARCH))
				goto ret;
			/* FALLTHROUGH */
		case ';':               /* Semi-colon delimiter. */
			if (sp->ep == NULL) {
				ex_badaddr(sp, NULL, A_EMPTY, NUM_OK);
				*errp = 1;
				return (0);
			}
			if (addr != ADDR_FOUND)
				switch (ecp->addrcnt) {
				case 0:
					ecp->addr1.lno = sp->lno;
					ecp->addr1.cno = sp->cno;
					ecp->addrcnt = 1;
					break;
				case 2:
					ecp->addr1 = ecp->addr2;
					/* FALLTHROUGH */
				case 1:
					ecp->addr2.lno = sp->lno;
					ecp->addr2.cno = sp->cno;
					ecp->addrcnt = 2;
					break;
				}
			if (*ecp->cp == ';')
				switch (ecp->addrcnt) {
				case 0:
					abort();
					/* NOTREACHED */
				case 1:
					sp->lno = ecp->addr1.lno;
					sp->cno = ecp->addr1.cno;
					break;
				case 2:
					sp->lno = ecp->addr2.lno;
					sp->cno = ecp->addr2.cno;
					break;
				}
			addr = ADDR_NEED;
d1585 2
a1586 2
			++ecp->cp;
			--ecp->clen;
d1589 1
a1589 2
			/* Get a line specification. */
			if (ex_line(sp, ecp, &m, &isaddr, errp))
d1591 8
a1598 10
			if (*errp)
				return (0);
			if (!isaddr)
				goto ret;
			if (addr == ADDR_FOUND) {
				ex_badaddr(sp, NULL, A_COMBO, NUM_OK);
				*errp = 1;
				return (0);
			}
			switch (ecp->addrcnt) {
d1600 2
a1601 2
				ecp->addr1 = m;
				ecp->addrcnt = 1;
d1604 2
a1605 2
				ecp->addr2 = m;
				ecp->addrcnt = 2;
d1608 2
a1609 2
				ecp->addr1 = ecp->addr2;
				ecp->addr2 = m;
a1611 1
			addr = ADDR_FOUND;
d1616 10
a1625 25
	 * !!!
	 * Vi ex address searches are indifferent to order or trailing
	 * semi-colons.
	 */
ret:	if (F_ISSET(ecp, E_VISEARCH))
		return (0);

	if (addr == ADDR_NEED)
		switch (ecp->addrcnt) {
		case 0:
			ecp->addr1.lno = sp->lno;
			ecp->addr1.cno = sp->cno;
			ecp->addrcnt = 1;
			break;
		case 2:
			ecp->addr1 = ecp->addr2;
			/* FALLTHROUGH */
		case 1:
			ecp->addr2.lno = sp->lno;
			ecp->addr2.cno = sp->cno;
			ecp->addrcnt = 2;
			break;
		}

	if (ecp->addrcnt == 2 && ecp->addr2.lno < ecp->addr1.lno) {
d1627 2
a1628 2
		    "094|The second address is smaller than the first");
		*errp = 1;
d1630 2
d1636 1
a1636 2
 * ex_line --
 *	Get a single line address specifier.
d1647 1
a1647 2
 * This is probably still not exactly historic practice, although I think
 * it's fairly close.
d1650 1
a1650 1
ex_line(sp, ecp, mp, isaddrp, errp)
d1652 5
a1656 3
	EXCMD *ecp;
	MARK *mp;
	int *isaddrp, *errp;
a1657 1
	enum nresult nret;
d1659 6
a1664 5
	GS *gp;
	long total, val;
	int isneg;
	int (*sf) __P((SCR *, MARK *, MARK *, char *, char **, u_int));
	char *endp;
a1665 1
	gp = sp->gp;
d1667 1
d1669 3
a1671 11
	*isaddrp = *errp = 0;
	F_CLR(ecp, E_DELTA);

	/* No addresses permitted until a file has been read in. */
	if (sp->ep == NULL && strchr("$0123456789'\\/?.+-^", *ecp->cp)) {
		ex_badaddr(sp, NULL, A_EMPTY, NUM_OK);
		*errp = 1;
		return (0);
	}

	switch (*ecp->cp) {
d1673 2
a1674 2
		*isaddrp = 1;
		F_SET(ecp, E_ABSMARK);
d1676 2
a1677 2
		mp->cno = 0;
		if (db_last(sp, &mp->lno))
d1679 2
a1680 2
		++ecp->cp;
		--ecp->clen;
d1684 2
a1685 2
		*isaddrp = 1;
		F_SET(ecp, E_ABSMARK);
d1687 4
a1690 14
		if ((nret = nget_slong(&val, ecp->cp, &endp, 10)) != NUM_OK) {
			ex_badaddr(sp, NULL, A_NOTSET, nret);
			*errp = 1;
			return (0);
		}
		if (!NPFITS(MAX_REC_NUMBER, 0, val)) {
			ex_badaddr(sp, NULL, A_NOTSET, NUM_OVER);
			*errp = 1;
			return (0);
		}
		mp->lno = val;
		mp->cno = 0;
		ecp->clen -= (endp - ecp->cp);
		ecp->cp = endp;
d1693 2
a1694 2
		*isaddrp = 1;
		F_SET(ecp, E_ABSMARK);
d1696 3
a1698 4
		if (ecp->clen == 1) {
			msgq(sp, M_ERR, "095|No mark name supplied");
			*errp = 1;
			return (0);
d1700 4
a1703 6
		if (mark_get(sp, ecp->cp[1], mp, M_ERR)) {
			*errp = 1;
			return (0);
		}
		ecp->cp += 2;
		ecp->clen -= 2;
d1712 3
a1714 5
		if (ecp->clen < 2 ||
		    ecp->cp[1] != '/' && ecp->cp[1] != '?') {
			msgq(sp, M_ERR, "096|\\ not followed by / or ?");
			*errp = 1;
			return (0);
d1716 3
a1718 3
		++ecp->cp;
		--ecp->clen;
		sf = ecp->cp[0] == '/' ? f_search : b_search;
d1725 1
d1727 4
a1730 6
search:		mp->lno = sp->lno;
		mp->cno = sp->cno;
		if (sf(sp, mp, mp,
		    ecp->cp, &endp, SEARCH_MSG | SEARCH_PARSE | SEARCH_SET)) {
			*errp = 1;
			return (0);
d1732 10
a1741 7

		/* Fix up the command pointers. */
		ecp->clen -= (endp - ecp->cp);
		ecp->cp = endp;

		*isaddrp = 1;
		F_SET(ecp, E_ABSMARK);
d1744 2
a1745 2
		*isaddrp = 1;
		mp->cno = sp->cno;
d1749 1
a1749 1
			if (db_last(sp, &mp->lno))
d1751 2
a1752 2
			if (mp->lno != 0)
				mp->lno = 1;
d1754 3
a1756 14
			mp->lno = sp->lno;

		/*
		 * !!!
		 * Historically, .<number> was the same as .+<number>, i.e.
		 * the '+' could be omitted.  (This feature is found in ed
		 * as well.)
		 */
		if (ecp->clen > 1 && isdigit(ecp->cp[1]))
			*ecp->cp = '+';
		else {
			++ecp->cp;
			--ecp->clen;
		}
d1760 10
a1769 16
	/* Skip trailing <blank>s. */
	for (; ecp->clen > 0 &&
	    isblank(ecp->cp[0]); ++ecp->cp, --ecp->clen);

	/*
	 * Evaluate any offset.  If no address yet found, the offset
	 * is relative to ".".
	 */
	total = 0;
	if (ecp->clen != 0 && (isdigit(ecp->cp[0]) ||
	    ecp->cp[0] == '+' || ecp->cp[0] == '-' ||
	    ecp->cp[0] == '^')) {
		if (!*isaddrp) {
			*isaddrp = 1;
			mp->lno = sp->lno;
			mp->cno = sp->cno;
a1770 47
		/*
		 * Evaluate an offset, defined as:
		 *
		 *		[+-^<blank>]*[<blank>]*[0-9]*
		 *
		 * The rough translation is any number of signs, optionally
		 * followed by numbers, or a number by itself, all <blank>
		 * separated.
		 *
		 * !!!
		 * All address offsets were additive, e.g. "2 2 3p" was the
		 * same as "7p", or, "/ZZZ/ 2" was the same as "/ZZZ/+2".
		 * Note, however, "2 /ZZZ/" was an error.  It was also legal
		 * to insert signs without numbers, so "3 - 2" was legal, and
		 * equal to 4.
		 *
		 * !!!
		 * Offsets were historically permitted for any line address,
		 * e.g. the command "1,2 copy 2 2 2 2" copied lines 1,2 after
		 * line 8.
		 *
		 * !!!
		 * Offsets were historically permitted for search commands,
		 * and handled as addresses: "/pattern/2 2 2" was legal, and
		 * referenced the 6th line after pattern.
		 */
		F_SET(ecp, E_DELTA);
		for (;;) {
			for (; ecp->clen > 0 && isblank(ecp->cp[0]);
			    ++ecp->cp, --ecp->clen);
			if (ecp->clen == 0 || !isdigit(ecp->cp[0]) &&
			    ecp->cp[0] != '+' && ecp->cp[0] != '-' &&
			    ecp->cp[0] != '^')
				break;
			if (!isdigit(ecp->cp[0]) &&
			    !isdigit(ecp->cp[1])) {
				total += ecp->cp[0] == '+' ? 1 : -1;
				--ecp->clen;
				++ecp->cp;
			} else {
				if (ecp->cp[0] == '-' ||
				    ecp->cp[0] == '^') {
					++ecp->cp;
					--ecp->clen;
					isneg = 1;
				} else
					isneg = 0;
d1772 8
a1779 13
				/* Get a signed long, add it to the total. */
				if ((nret = nget_slong(&val,
				    ecp->cp, &endp, 10)) != NUM_OK ||
				    (nret = NADD_SLONG(sp,
				    total, val)) != NUM_OK) {
					ex_badaddr(sp, NULL, A_NOTSET, nret);
					*errp = 1;
					return (0);
				}
				total += isneg ? -val : val;
				ecp->clen -= (endp - ecp->cp);
				ecp->cp = endp;
			}
d1783 5
a1787 54
	/*
	 * Any value less than 0 is an error.  Make sure that the new value
	 * will fit into a recno_t.
	 */
	if (*isaddrp && total != 0) {
		if (total < 0) {
			if (-total > mp->lno) {
				msgq(sp, M_ERR,
			    "097|Reference to a line number less than 0");
				*errp = 1;
				return (0);
			}
		} else
			if (!NPFITS(MAX_REC_NUMBER, mp->lno, total)) {
				ex_badaddr(sp, NULL, A_NOTSET, NUM_OVER);
				*errp = 1;
				return (0);
			}
		mp->lno += total;
	}
	return (0);
}


/*
 * ex_load --
 *	Load up the next command, which may be an @@ buffer or global command.
 */
static int
ex_load(sp)
	SCR *sp;
{
	GS *gp;
	EXCMD *ecp;
	RANGE *rp;

	F_CLR(sp, SC_EX_GLOBAL);

	/*
	 * Lose any exhausted commands.  We know that the first command
	 * can't be an AGV command, which makes things a bit easier.
	 */
	for (gp = sp->gp;;) {
		/*
		 * If we're back to the original structure, leave it around,
		 * but discard any allocated source name, we've returned to
		 * the beginning of the command stack.
		 */
		if ((ecp = gp->ecq.lh_first) == &gp->excmd) {
			if (F_ISSET(ecp, E_NAMEDISCARD)) {
				free(ecp->if_name);
				ecp->if_name = NULL;
			}
			return (0);
d1789 1
d1791 2
a1792 91
		/*
		 * ecp->clen will be 0 for the first discarded command, but
		 * may not be 0 for subsequent ones, e.g. if the original
		 * command was ":g/xx/@@a|s/b/c/", then when we discard the
		 * command pushed on the stack by the @@a, we have to resume
		 * the global command which included the substitute command.
		 */
		if (ecp->clen != 0)
			return (0);

		/*
		 * If it's an @@, global or v command, we may need to continue
		 * the command on a different line.
		 */
		if (FL_ISSET(ecp->agv_flags, AGV_ALL)) {
			/* Discard any exhausted ranges. */
			while ((rp = ecp->rq.cqh_first) != (void *)&ecp->rq)
				if (rp->start > rp->stop) {
					CIRCLEQ_REMOVE(&ecp->rq, rp, q);
					free(rp);
				} else
					break;

			/* If there's another range, continue with it. */
			if (rp != (void *)&ecp->rq)
				break;

			/* If it's a global/v command, fix up the last line. */
			if (FL_ISSET(ecp->agv_flags,
			    AGV_GLOBAL | AGV_V) && ecp->range_lno != OOBLNO)
				if (db_exist(sp, ecp->range_lno))
					sp->lno = ecp->range_lno;
				else {
					if (db_last(sp, &sp->lno))
						return (1);
					if (sp->lno == 0)
						sp->lno = 1;
				}
			free(ecp->o_cp);
		}

		/* Discard the EXCMD. */
		LIST_REMOVE(ecp, q);
		free(ecp);
	}

	/*
	 * We only get here if it's an active @@, global or v command.  Set
	 * the current line number, and get a new copy of the command for
	 * the parser.  Note, the original pointer almost certainly moved,
	 * so we have play games.
	 *
	 * See ex.h for a discussion of SEARCH_TERMINATION.
	 */
	ecp->cp = ecp->o_cp;
	memmove(ecp->cp,
	    ecp->cp + ecp->o_clen + SEARCH_TERMINATION, ecp->o_clen);
	ecp->clen = ecp->o_clen;
	ecp->range_lno = sp->lno = rp->start++;

	if (FL_ISSET(ecp->agv_flags, AGV_GLOBAL | AGV_V))
		F_SET(sp, SC_EX_GLOBAL);
	return (0);
}

/*
 * ex_discard --
 *	Discard any pending ex commands.
 */
static int
ex_discard(sp)
	SCR *sp;
{
	GS *gp;
	EXCMD *ecp;
	RANGE *rp;

	/*
	 * We know the first command can't be an AGV command, so we don't
	 * process it specially.  We do, however, nail the command itself.
	 */
	for (gp = sp->gp; (ecp = gp->ecq.lh_first) != &gp->excmd;) {
		if (FL_ISSET(ecp->agv_flags, AGV_ALL)) {
			while ((rp = ecp->rq.cqh_first) != (void *)&ecp->rq) {
				CIRCLEQ_REMOVE(&ecp->rq, rp, q);
				free(rp);
			}
			free(ecp->o_cp);
		}
		LIST_REMOVE(ecp, q);
		free(ecp);
a1793 1
	gp->ecq.lh_first->clen = 0;
a1797 23
 * ex_unknown --
 *	Display an unknown command name.
 */
static void
ex_unknown(sp, cmd, len)
	SCR *sp;
	char *cmd;
	size_t len;
{
	size_t blen;
	char *bp;

	GET_SPACE_GOTO(sp, bp, blen, len + 1);
	bp[len] = '\0';
	memmove(bp, cmd, len);
	msgq_str(sp, M_ERR, bp, "098|The %s command is unknown");
	FREE_SPACE(sp, bp, blen);

alloc_err:
	return;
}

/*
d1799 3
a1801 5
 *	The vi text input routine needs to know if ex thinks this is an
 *	[un]abbreviate command, so it can turn off abbreviations.  See
 *	the usual ranting in the vi/v_txt_ev.c:txt_abbrev() routine.
 *
 * PUBLIC: int ex_is_abbrev __P((char *, size_t));
d1816 3
a1818 5
 *	The vi text input routine needs to know if ex thinks this is an
 *	unmap command, so it can turn off input mapping.  See the usual
 *	ranting in the vi/v_txt_ev.c:txt_unmap() routine.
 *
 * PUBLIC: int ex_is_unmap __P((char *, size_t));
d1838 1
a1838 5
/*
 * ex_comm_search --
 *	Search for a command name.
 */
static EXCMDLIST const *
d1856 2
a1857 9
/*
 * ex_badaddr --
 *	Display a bad address message.
 *
 * PUBLIC: void ex_badaddr
 * PUBLIC:    __P((SCR *, EXCMDLIST const *, enum badaddr, enum nresult));
 */
void
ex_badaddr(sp, cp, ba, nret)
a1858 4
	EXCMDLIST const *cp;
	enum badaddr ba;
	enum nresult nret;
{
a1859 62

	switch (nret) {
	case NUM_OK:
		break;
	case NUM_ERR:
		msgq(sp, M_SYSERR, NULL);
		return;
	case NUM_OVER:
		msgq(sp, M_ERR, "099|Address value overflow");
		return;
	case NUM_UNDER:
		msgq(sp, M_ERR, "100|Address value underflow");
		return;
	}

	/*
	 * When encountering an address error, tell the user if there's no
	 * underlying file, that's the real problem.
	 */
	if (sp->ep == NULL) {
		ex_emsg(sp, cp->name, EXM_NOFILEYET);
		return;
	}

	switch (ba) {
	case A_COMBO:
		msgq(sp, M_ERR, "101|Illegal address combination");
		break;
	case A_EOF:
		if (db_last(sp, &lno))
			return;
		if (lno != 0) {
			msgq(sp, M_ERR,
			    "102|Illegal address: only %lu lines in the file",
			    lno);
			break;
		}
		/* FALLTHROUGH */
	case A_EMPTY:
		msgq(sp, M_ERR, "103|Illegal address: the file is empty");
		break;
	case A_NOTSET:
		abort();
		/* NOTREACHED */
	case A_ZERO:
		msgq(sp, M_ERR,
		    "104|The %s command doesn't permit an address of 0",
		    cp->name);
		break;
	}
	return;
}

#if defined(DEBUG) && defined(COMLOG)
/*
 * ex_comlog --
 *	Log ex commands.
 */
static void
ex_comlog(sp, ecp)
	SCR *sp;
	EXCMD *ecp;
d1861 5
a1865 16
	TRACE(sp, "ecmd: %s", ecp->cmd->name);
	if (ecp->addrcnt > 0) {
		TRACE(sp, " a1 %d", ecp->addr1.lno);
		if (ecp->addrcnt > 1)
			TRACE(sp, " a2: %d", ecp->addr2.lno);
	}
	if (ecp->lineno)
		TRACE(sp, " line %d", ecp->lineno);
	if (ecp->flags)
		TRACE(sp, " flags 0x%x", ecp->flags);
	if (F_ISSET(&exc, E_BUFFER))
		TRACE(sp, " buffer %c", ecp->buffer);
	if (ecp->argc)
		for (cnt = 0; cnt < ecp->argc; ++cnt)
			TRACE(sp, " arg %d: {%s}", cnt, ecp->argv[cnt]->bp);
	TRACE(sp, "\n");
a1866 1
#endif
@


1.1.1.6
log
@import of nvi 1.79
@
text
@d13 1
a13 1
static const char sccsid[] = "@@(#)ex.c	10.57 (Berkeley) 10/10/96";
d78 1
a78 1
	if (F_ISSET(gp, G_SCRIPTED)) {
a93 2
			if (!F_ISSET(sp, SC_EX_SILENT))
				msgq_status(sp, sp->lno, 0);
d95 1
d132 1
a132 1
		if (ex_cmd(sp) && F_ISSET(gp, G_SCRIPTED))
d203 1
a203 1
	size_t arg1_len, discard, len;
d429 1
a429 1
		case 'E': case 'F': case 'N': case 'P': case 'T': case 'V':
d456 1
a456 1
				if (namelen == 2) {
d619 9
a627 3
	 * since "parser" implies some regularity of syntax) delimited the RE's
	 * based on its delimiter and not anything so irretrievably vulgar as a
	 * command syntax.
a632 1
	discard = 0;		/* Characters discarded from the command. */
d659 3
a661 2
		 * first whitespace character that isn't escaped.  The escaping
		 * characters are stripped as no longer useful.
d669 2
a670 3
				if (IS_ESCAPE(sp, ecp, ch) &&
				    ecp->clen > 1) {
					++discard;
d684 3
d688 2
a689 7
		 * QUOTING NOTE:
		 *
		 * We use backslashes to escape <newline> characters, although
		 * this wasn't historic practice for the bang command.  It was
		 * for the global and v commands, and it's common usage when
		 * doing text insert during the command.  Escaping characters
		 * are stripped as no longer useful.
d691 1
a691 1
		for (p = ecp->cp; ecp->clen > 0; --ecp->clen, ++ecp->cp) {
d693 1
a693 8
			if (ch == '\\' && ecp->clen > 1 && ecp->cp[1] == '\n') {
				++discard;
				--ecp->clen;
				ch = *++ecp->cp;

				++gp->if_lno;
				++ecp->if_lno;
			} else if (ch == '\n')
a694 1
			*p++ = ch;
d696 3
a698 15
	} else if (ecp->cmd == &cmds[C_READ] || ecp->cmd == &cmds[C_WRITE]) {
		/*
		 * For write commands, if the next character is a <blank>, and
		 * the next non-blank character is a '!', it's a filter command
		 * and we want to eat everything up to the <newline>.  For read
		 * commands, if the next non-blank character is a '!', it's a
		 * filter command and we want to eat everything up to the next
		 * <newline>.  Otherwise, we're done.
		 */
		for (tmp = 0; ecp->clen > 0; --ecp->clen, ++ecp->cp) {
			ch = *ecp->cp;
			if (isblank(ch))
				tmp = 1;
			else
				break;
a699 5
		if (ecp->clen > 0 && ch == '!' &&
		    (ecp->cmd == &cmds[C_READ] || tmp))
			for (; ecp->clen > 0; --ecp->clen, ++ecp->cp)
				if (ecp->cp[0] == '\n')
					break;
d752 1
a752 1
	for (p = ecp->cp; ecp->clen > 0; --ecp->clen, ++ecp->cp) {
a760 1
				++discard;
d763 1
d783 1
a783 1
	ecp->clen = ((ecp->save_cmd - ecp->cp) - 1) - discard;
d814 1
a814 1
	 * (ex: z) care if the user specified an address or if we just used
d1204 1
a1204 1
	 * (They don't all pass through ex_line(), for instance.)  We're
d1337 1
a1337 1
		    F_ISSET(sp, SC_EX) && !F_ISSET(gp, G_SCRIPTED) &&
d1350 1
a1350 1
		if (F_ISSET(gp, G_SCRIPTED))
d1375 1
a1375 1
		mod_rpt(sp);
d1410 3
a1412 3
	 * If the command executed successfully, we may want to display a line
	 * based on the autoprint option or an explicit print flag.  (Make sure
	 * that there's a line to display.)  Also, the autoprint edit option is
d1456 4
a1459 3
	 * current command and continue.  We may have to add an additional
	 * <literal next> character.  We know that it will fit because we
	 * discarded at least one space and the + character.
d1462 4
d1478 1
a1478 1
		memcpy(ecp->save_cmd, arg1, arg1_len);
d1482 5
a1486 5
		 * the first column of the last line of the file -- NOT the
		 * first nonblank.)  The main file startup code doesn't know
		 * that a +cmd was set, however, so it may have put us at the
		 * top of the file.  (Note, this is safe because we must have
		 * switched files to get here.)
d1807 1
a1807 1
	int (*sf) __P((SCR *, MARK *, MARK *, char *, size_t, char **, u_int));
d1895 2
a1896 3
		if (sf(sp, mp, mp, ecp->cp, ecp->clen, &endp,
		    SEARCH_MSG | SEARCH_PARSE | SEARCH_SET |
		    (F_ISSET(ecp, E_SEARCH_WMSG) ? SEARCH_WMSG : 0))) {
d2124 2
d2128 2
a2129 1
	memcpy(ecp->cp, ecp->cp + ecp->o_clen, ecp->o_clen);
d2184 1
a2184 1
	memcpy(bp, cmd, len);
@

