[comp.sources.misc] v03i030: mg 2a part 6 of 15

BLARSON@ECLA.USC.EDU (Bob Larson) (05/26/88)

comp.sources.misc: Volume 3, Issue 30
Submitted-By: "Bob Larson" <BLARSON@ECLA.USC.EDU>
Archive-Name: mg2a/Part06

#	This is a shell archive.
#	Remove everything above and including the cut line.
#	Then run the rest of the file through sh.
#----cut here-----cut here-----cut here-----cut here----#
#!/bin/sh
# shar:    Shell Archiver
#	Run the following text with /bin/sh to create:
#	mgprog.doc
#	buffer.c
#	def.h
#	echo.c
#	help.c
# This archive created: Wed May 25 19:21:13 1988
# By:	blarson
cat << \SHAR_EOF > mgprog.doc
This documentation covers mg 2a.

I do want feedback from other mg developers on what they think of my
changes, documentation, and what needs to be done to make mg better.
This document is not complete, it mainly covers the areas I have
recently changed.

Possible future changes:

Rearange file contents along more rational lines.  Further split the
monolithic def.h file.

Changing the echo line stuff to use a minibuffer keymap.

Making the kill buffer a linked list of lines.

Variables.

Allow for backspace, ^s, etc. to be changed in some reasonable manner.
(Probably using variables or a simulation thereof.)  I do not think an
input keymap is the correct solution, even if it is frequently used in
Gnu emacs.  (Besides the extra overhead, keynames come out wrong.)

Make long lines wrap like they do in GNU emacs.

Fix known (and unknown :-) bugs.

Have the keymaps and associated tables generated by a program.


Known bugs/limitations:

Binding a key in a named keymap may or may not change the binding of
other keys pointing to the same keymap.	 (i.e. if ^H and ^_ are bound
to help, rebinding ^Hb may not (or may) change ^_b.  This can be cured
by rebinding ^_ to help.)

Overwrite mode does not work in macros.	 (Characters are inserted
rather than overwriting.)

Dired mode has some problems:  Rename does not update the buffer.
Doing a dired again will update the buffer (whether it needs it or
not) and will lose any marks for deletion.  .. and . are not
recognized as special cases.



New implementation oddities:

insert and define-key are new commands corresponding to the mocklisp
functions in Gnu Emacs.	 (Mg does not have non-command functions.)
(Mg's insert will only insert one string.)

The display wrap code does not work at all like that of GNU emacs.



Adding command functions to mg:

Command functions take two integer aguments and return an integer.
The first argument, f, is a set of flags.  (f&FFARG) is non-zero if a
numeric arguement was passed to the function.  (There are bits
indicating how the agument was specified, but they are not fully
impleminted.)  (f&FFRAND) is non-zero if the function is being called
by another function and that possibly slightly different action should
be taken.  (No error checking, supress output, etc.)  The second
argument, n, is the numeric agument passed or one if there was no
numeric arugment.  The fuction should return TRUE if it executes
correctly, FALSE if it could not, and ABORT if the user typed the
keyboard quit character at a prompt.

The function must be added to the functnames table in keymap.c.	 This
table must be kept in assending ascii sequence.



Key maps:

Key maps are structures containing information on what action should
be taken corresponding to an individual keypress.  That action could
be an indication that this is a prefix key and the next kepress should
be looked up in another keymap.

	Example keymap:

	static	struct	KEYMAPE(6+IMAPEXT)	cXmap = {
		6,
		6+IMAPEXT,
		rescan,
		{
			{CCHR('B'),CCHR('G'),	cXcB,	(KEYMAP *)NULL},
			{CCHR('L'),CCHR('X'),	cXcL,	(KEYMAP *)NULL},
			{'(',	')',		cXlp,	(KEYMAP *)NULL},
			{'0',	'4',		cX0,	(KEYMAP *)&cX4map},
			{'=',	'=',		cXeq,	(KEYMAP *)NULL},
			{'^',	's',		cXcar,	(KEYMAP *)NULL},
		}
	};

(Note: this example is a simplified example of a real keymap in keymap.c.)

Since C does not directly support structures containing undementioned
arrays, the macro KEYMAPE is used to create a structure with an array
of the proper size.  6 is the current size of the array, and IMAPEXT
is the number of extra elements left for future groth (by rebinding
keys) before the map must be reallocated.  rescan is the function to
be executed if a specific entry for the key is not found.  (rescan is
a special function that searches for something else to do -- first by
trying lowercasing the last character in the keymap, then by trying
the other modes in effect.)

The array elements must be in order by the keys they define.  Each
covers a range of characters.  Numeric values should not be used for
characters, they make porting mg to some other systems harder.	The
CCHR macro may be used to specify control characters, including DEL
(CCHR('?')).  cXcB, cXcL, etc. are arrays of pointers to functions
returning int.	One of these fuction pointers per element may be to
the pseuto-function prefix.  cX4map is the keymap coresponding to the
prefix function bound to '4' in this keymap.  Having several keys in
an element bound to the default function is better than increasing the
number of elements.



Modes:

Modes are named key maps that are scanned for key bindings before the
global keymap is.  There are functions in modes.c to toggle modes on
or off for individual buffers.  Note that the "major"/"minor" mode
distiction is different than in Gnu Emacs.  Dired is currently the
only major mode available, buffers are put into dired mode on creation
by the dired code.  (The distiction in mg is the major mode replaces
the default keymap instead of being an overlay.) Some modes (overwrite
and no-tab) also trigger per-buffer flags that should be convered to
per-buffer variables when we add variables.  Keymaps for the modes are
kept in keymap.c with the other keymaps.



System dependent files:

Fileio.c:
	Contains file i/o routines:
		ffputbuf(BUFFER *):
Write all lines of buffer to the file.	The last line of the buffer does
NOT have the normally implied newline.	(One may be added if
nessisary, but don't write out the last line if it is zero characters
long.)

		ffgetline(char *buf, int nbuf, int *nbytes):
Read a line from the file up to the length specified by the second
argument in to the buffer pointed to by the first.  If a newline is
not found after reading nbuf characters, return FIOLONG and on the
next call to ffgetline return the remaining portion (or nbuf more
characters and return FIOLONG).	 If a newline is found, set *nbytes to
the number of characters read and return FIOSUC.  If the end of file
is descovered, set *nbytes and return FIOEOF.  (If the file ends in a
newline, the call returning FIOEOF will set *nbytes to 0.)  If any
other error occurs, return FIOERR.

		char *adjustname(char *fname)
Standardize filename.  On mono-case systems, lowercase the file name.
If NO_DIR is not defined, make fully qualified.	 (not relitive to the
current directory, which may change.)

		fncmp(char *fna, char *fnb) 
Return 0 if both arguments refer to the same file or buffer.  #define
it to be strcmp on mono-case or case sensitive systems, use a non-case
sensitive compareison otherwise.  (Borrow it from the osk fileio.c)
Both arguments have been through adjustname already. 

	routines needed for dired:

		rename(char *fromname, char *toname)
rename file.  BSD systems have this as a system call.  return -1 on
error.

		copy(char *fromname, char *toname)
copy file.  return -1 on error.

		unlinkdir(char *name)
Delete directory.  return -1 on error.  (possibly including non-empty
directory.)

		BUFFER *dired_(char *name)
Create dired buffer for named directory.  See example from osk or bsd.

		d_makename(LINE *l, char *fname)
Concatinate directory name associated with the current dired BUFFER
with file name in line.  Return ABORT if no file name on line, FALSE
if it is an ordinary file, or TRUE if there is a directory.  Name made
should be the same as if it were run through adjustname. 


Converting system & terminal dependent files from mg1b:

All command functions will have to be rewritten to use the new two
argument calling sequence.  (Some compilers will let you get away
without doing this for testing purposes.  Problems, if any, will show
up at run-time.)

Key binding is completly different.  See extend.c if your code needs
to do rebinding.

I have attempted make mg less dependant on ascii character values.
Keymap.c depends on ascii sorting order.  Cinfo.c depends on character
values and contains a function to convert from a character value
to a key name.  Several modules assume 3 octal digits are enough for
any character value.

Names of most compile time options have changed.  Whatever is most
GNU-emacs like is now the default.

sysdef.h:
	The type KEY should not be defined.  The type KCHAR should be defined.
	All posible key inputs must be positive in type KCHAR.	short is
	recomended.

spawn.c:
	Update to the new function calling conventions.

Makefile:
	Needs complete rewrite.	 You can probably figure out the dependencies
	from the bsd or osk one.  Compile time options have changed.

Fileio.c:
	Remove function ffputline.  Add function ffputbuf (described above).
	Rewrite ffgetline to conform to the new way of doing things.  (see
	above.)  These routines can probably be borrowed intact from the
	OSK system dependant fileio.c for unix systems.
	Replace adjustcase with adjustname.  Add fncmp either here or
	as a #define in sysdef.h.  Add functions needed by dired.




Compile time options:

extentions not directly in gnu emacs

BSMAP		input mapping exchanging ^H and DEL.
		1 for defaulting to this, 0 for normal default.
NOTAB		for systems that don't like tabs
CVMVAS		arguments to ^V in screens not lines
PREFIXREGION	prefix region
PREVWIND	previous window
GOSREC		Gossling style recenter
STARTUPFILE	(unix & OSK) system-wide startup file
XKEYS		(Termcap) Put kepad in alternate mode, use
		terminal-dependent startup file.

Features removeable to save space

NO_HELP		help, descibe-bindings, describe-key-briefly, apropos
NO_MACRO	keyboard macros.  If defined, NO_STARTUP must be also.
NO_STARTUP	startup files, load, etc.
NO_BACKUP	backup files when writing
NO_DPROMPT	Delayed prompt on multi-key sequences
NO_DIR		Dir change functions.  If defined, NO_DIRED must be also.
NO_DIRED	Dired mode
REGEX		Regular expressions.  Not default, since the code is rather
		unportable and has the GNU copywrite on it.

System dependant garbage (avoid where practical)

VMS		VMS
AMIGA		AMIGA


Things that may be defined in system dependant code:

XCHAR		XCHAR and XSHORT	(char and short for space savings)
BDC2		more special characters for filenames
BDC3		dito.
METABIT		Bit of KCHAR set on meta keys
OFFSET		macro to calculate offset of member from start of structure
NBLOCK		line growth amount
KBLOCK		kill buffer growth amount
MALLOCROUND	macro to predict malloc allocations stratagy
SYSINIT		system dependant initialization
NO_VOID_TYPE	compiler dosen't have type void
ZEROARRAY	zero length arrays are allowed
BINDKEY		include bindkey routine for use by system & terminal
		dependent code.

Terminal dependant

DO_METAKEY	meta key
METABIT		Which bit in a KCHAR is used by the meta key (default 0x80)
STANDOUT_GLITCH standout (may) take character position(s)
GOSLING		optimize redisplay
MEMMAP		memory mapped display
MOVE_STANDOUT	cursor addressing may be done in standout mode
FKEYS		function keys do not fit in type char.
		Not for use where function keys send multiple characters.
SHAR_EOF
cat << \SHAR_EOF > buffer.c
/*
 *		Buffer handling.
 */
#include	"def.h"
#include	"kbd.h"			/* needed for modes */

static RSIZE	itor();

/*
 * Attach a buffer to a window. The values of dot and mark come
 * from the buffer if the use count is 0. Otherwise, they come
 * from some other window.  *scratch* is the default alternate
 * buffer.
 */
/*ARGSUSED*/
usebuffer(f, n)
{
	register BUFFER *bp;
	register int	s;
	char		bufn[NBUFN];

	/* Get buffer to use from user */
	if ((curbp->b_altb == NULL)
	    && ((curbp->b_altb = bfind("*scratch*", TRUE)) == NULL))
		s=eread("Switch to buffer: ", bufn, NBUFN, EFNEW|EFBUF);
	else
		s=eread("Switch to buffer: (default %s) ", bufn, NBUFN,
			 EFNEW|EFBUF, curbp->b_altb->b_bname);

	if (s == ABORT) return s;
	if (s == FALSE && curbp->b_altb != NULL) bp = curbp->b_altb ;
	else if ((bp=bfind(bufn, TRUE)) == NULL) return FALSE;

	/* and put it in current window */
	curbp = bp;
	return showbuffer(bp, curwp, WFFORCE|WFHARD);
}

/*
 * pop to buffer asked for by the user.
 */
/*ARGSUSED*/
poptobuffer(f, n)
{
	register BUFFER *bp;
	register WINDOW *wp;
	register int	s;
	char		bufn[NBUFN];
	WINDOW	*popbuf();

	/* Get buffer to use from user */
	if ((curbp->b_altb == NULL)
	    && ((curbp->b_altb = bfind("*scratch*", TRUE)) == NULL))
		s=eread("Switch to buffer in other window: ", bufn, NBUFN,
			EFNEW|EFBUF);
	else
		s=eread("Switch to buffer in other window: (default %s) ",
			 bufn, NBUFN, EFNEW|EFBUF, curbp->b_altb->b_bname);
	if (s == ABORT) return s;
	if (s == FALSE && curbp->b_altb != NULL) bp = curbp->b_altb ;
	else if ((bp=bfind(bufn, TRUE)) == NULL) return FALSE;

	/* and put it in a new window */
	if ((wp = popbuf(bp)) == NULL) return FALSE;
	curbp = bp;
	curwp = wp;
	return TRUE;
}

/*
 * Dispose of a buffer, by name.
 * Ask for the name. Look it up (don't get too
 * upset if it isn't there at all!). Clear the buffer (ask
 * if the buffer has been changed). Then free the header
 * line and the buffer header. Bound to "C-X K".
 */
/*ARGSUSED*/
killbuffer(f, n)
{
	register BUFFER *bp;
	register BUFFER *bp1;
	register BUFFER *bp2;
	WINDOW		*wp;
	register int	s;
	char		bufn[NBUFN];

	if ((s=eread("Kill buffer: (default %s) ", bufn, NBUFN, EFNEW|EFBUF,
		    curbp->b_bname)) == ABORT) return (s);
	else if (s == FALSE) bp = curbp;
	else if ((bp=bfind(bufn, FALSE)) == NULL) return FALSE;

	/* find some other buffer to display. try the alternate buffer,
	 * then the first different buffer in the buffer list.	if
	 * there's only one buffer, create buffer *scratch* and make
	 * it the alternate buffer.  return if *scratch* is only buffer
	 */
	if ((bp1 = bp->b_altb) == NULL) {
		bp1 = (bp == bheadp) ? bp->b_bufp : bheadp;
		if (bp1 == NULL) {
			/* only one buffer. see if it's *scratch* */
			if (bp == bfind("*scratch*",FALSE))
				return FALSE;
			/* create *scratch* for alternate buffer */
			if ((bp1 = bfind("*scratch*",TRUE)) == NULL)
				return FALSE;
		}
	}
	if (bclear(bp) != TRUE) return TRUE;
	for (wp = wheadp; bp->b_nwnd > 0; wp = wp->w_wndp) {
	    if (wp->w_bufp == bp) {
		bp2 = bp1->b_altb;		/* save alternate buffer */
		if(showbuffer(bp1, wp, WFMODE|WFFORCE|WFHARD) != NULL)
			bp1->b_altb = bp2;
		else	bp1 = bp2;
	    }
	}
	if (bp == curbp) curbp = bp1;
	free((char *) bp->b_linep);		/* Release header line. */
	bp2 = NULL;				/* Find the header.	*/
	bp1 = bheadp;
	while (bp1 != bp) {
		if (bp1->b_altb == bp)
			bp1->b_altb = (bp->b_altb == bp1) ? NULL : bp->b_altb;
		bp2 = bp1;
		bp1 = bp1->b_bufp;
	}
	bp1 = bp1->b_bufp;			/* Next one in chain.	*/
	if (bp2 == NULL)			/* Unlink it.		*/
		bheadp = bp1;
	else
		bp2->b_bufp = bp1;
	while (bp1 != NULL) {			/* Finish with altb's	*/
		if (bp1->b_altb == bp)
			bp1->b_altb = (bp->b_altb == bp1) ? NULL : bp->b_altb;
		bp1 = bp1->b_bufp;
	}
	free(bp->b_bname);			/* Release name block	*/
	free((char *) bp);			/* Release buffer block */
	return TRUE;
}

/*
 * Save some buffers - just call anycb with the arg flag.
 */
/*ARGSUSED*/
savebuffers(f, n)
{
	if (anycb(f) == ABORT) return ABORT;
	return TRUE;
}

/*
 * Display the buffer list. This is done
 * in two parts. The "makelist" routine figures out
 * the text, and puts it in a buffer. "popbuf"
 * then pops the data onto the screen. Bound to
 * "C-X C-B".
 */
/*ARGSUSED*/
listbuffers(f, n)
{
	register BUFFER *bp;
	register WINDOW *wp;
	BUFFER		*makelist();
	WINDOW		*popbuf();

	if ((bp=makelist()) == NULL || (wp=popbuf(bp)) == NULL)
		return FALSE;
	wp->w_dotp = bp->b_dotp;	/* fix up if window already on screen */
	wp->w_doto = bp->b_doto;
	return TRUE;
}

/*
 * This routine rebuilds the text for the
 * list buffers command. Return TRUE if
 * everything works. Return FALSE if there
 * is an error (if there is no memory).
 */
BUFFER *
makelist() {
	register char	*cp1;
	register char	*cp2;
	register int	c;
	register BUFFER *bp;
	LINE		*lp;
	register RSIZE	nbytes;
	BUFFER		*blp;
	char		b[6+1];
	char		line[128];

	if ((blp = bfind("*Buffer List*", TRUE)) == NULL) return NULL;
	if (bclear(blp) != TRUE) return NULL;
	blp->b_flag &= ~BFCHG;			/* Blow away old.	*/

	(VOID) strcpy(line, " MR Buffer");
	cp1 = line + 10;
	while(cp1 < line + 4 + NBUFN + 1) *cp1++ = ' ';
	(VOID) strcpy(cp1, "Size   File");
	if (addline(blp, line) == FALSE) return NULL;
	(VOID) strcpy(line, " -- ------");
	cp1 = line + 10;
	while(cp1 < line + 4 + NBUFN + 1) *cp1++ = ' ';
	(VOID) strcpy(cp1, "----   ----");
	if (addline(blp, line) == FALSE) return NULL;
	bp = bheadp;				/* For all buffers	*/
	while (bp != NULL) {
		cp1 = &line[0];			/* Start at left edge	*/
		*cp1++ = (bp == curbp) ? '.' : ' ';
		*cp1++ = ((bp->b_flag&BFCHG) != 0) ? '*' : ' ';
		*cp1++ = ' ';			/* Gap.			*/
		*cp1++ = ' ';
		cp2 = &bp->b_bname[0];		/* Buffer name		*/
		while ((c = *cp2++) != 0)
			*cp1++ = c;
		while (cp1 < &line[4+NBUFN+1])
			*cp1++ = ' ';
		nbytes = 0;			/* Count bytes in buf.	*/
		if (bp != blp) {
			lp = lforw(bp->b_linep);
			while (lp != bp->b_linep) {
				nbytes += llength(lp)+1;
				lp = lforw(lp);
			}
			if(nbytes) nbytes--;	/* no bonus newline	*/
		}
		(VOID) itor(b, 6, nbytes);	/* 6 digit buffer size. */
		cp2 = &b[0];
		while ((c = *cp2++) != 0)
			*cp1++ = c;
		*cp1++ = ' ';			/* Gap..			*/
		cp2 = &bp->b_fname[0];		/* File name		*/
		if (*cp2 != 0) {
			while ((c = *cp2++) != 0) {
				if (cp1 < &line[128-1])
					*cp1++ = c;
			}
		}
		*cp1 = 0;			/* Add to the buffer.	*/
		if (addline(blp, line) == FALSE)
			return NULL;
		bp = bp->b_bufp;
	}
	blp->b_dotp = lforw(blp->b_linep);	/* put dot at beginning of buffer */
	blp->b_doto = 0;
	return blp;				/* All done		*/
}

/*
 * Used above.
 */
static RSIZE itor(buf, width, num)
register char buf[]; register int width; register RSIZE num; {
	register RSIZE r;

	if (num / 10 == 0) {
		buf[0] = (num % 10) + '0';
		for (r = 1; r < width; buf[r++] = ' ')
			;
		buf[width] = '\0';
		return 1;
	} else {
		buf[r = itor(buf, width, num / (RSIZE)10)] =
				(num % (RSIZE)10) + '0';
		return r + 1;
	}
	/*NOTREACHED*/
}

/*
 * The argument "text" points to
 * a string. Append this line to the
 * buffer. Handcraft the EOL
 * on the end. Return TRUE if it worked and
 * FALSE if you ran out of room.
 */
addline(bp, text) register BUFFER *bp; char *text; {
	register LINE	*lp;
	register int	i;
	register int	ntext;

	ntext = strlen(text);
	if ((lp=lalloc(ntext)) == NULL)
		return FALSE;
	for (i=0; i<ntext; ++i)
		lputc(lp, i, text[i]);
	bp->b_linep->l_bp->l_fp = lp;		/* Hook onto the end	*/
	lp->l_bp = bp->b_linep->l_bp;
	bp->b_linep->l_bp = lp;
	lp->l_fp = bp->b_linep;
#ifdef CANTHAPPEN
	if (bp->b_dotp == bp->b_linep)		/* If "." is at the end	*/
		bp->b_dotp = lp;		/* move it to new line	*/
	if (bp->b_markp == bp->b_linep)		/* ditto for mark	*/
		bp->b_markp = lp;
#endif
	return TRUE;
}

/*
 * Look through the list of buffers, giving the user
 * a chance to save them.  Return TRUE if there are
 * any changed buffers afterwards. Buffers that don't
 * have an associated file don't count. Return FALSE
 * if there are no changed buffers.
 */
anycb(f) {
	register BUFFER *bp;
	register int	s = FALSE, save = FALSE;
	char		prompt[NFILEN + 11];
	VOID		upmodes();

	for (bp = bheadp; bp != NULL; bp = bp->b_bufp) {
		if (*(bp->b_fname) != '\0'
		&&  (bp->b_flag&BFCHG) != 0) {
			(VOID) strcpy(prompt, "Save file ");
			(VOID) strcpy(prompt + 10, bp->b_fname);
			if ((f == TRUE || (save = eyorn(prompt)) == TRUE)
			&&  buffsave(bp) == TRUE) {
				bp->b_flag &= ~BFCHG;
				upmodes(bp);
			} else s = TRUE;
			if (save == ABORT) return (save);
			save = TRUE;
		}
	}
	if (save == FALSE /* && kbdmop == NULL */ )	/* experimental */
		ewprintf("(No files need saving)");
	return s;
}

/*
 * Search for a buffer, by name.
 * If not found, and the "cflag" is TRUE,
 * create a buffer and put it in the list of
 * all buffers. Return pointer to the BUFFER
 * block for the buffer.
 */
BUFFER	*
bfind(bname, cflag) register char *bname; {
	register BUFFER *bp;
	char		*malloc();
	register LINE	*lp;
	int i;
	extern int defb_nmodes;
	extern MAPS *defb_modes[PBMODES];
	extern int defb_flag;

	bp = bheadp;
	while (bp != NULL) {
		if (fncmp(bname, bp->b_bname) == 0)
			return bp;
		bp = bp->b_bufp;
	}
	if (cflag!=TRUE) return NULL;
	/*NOSTRICT*/
	if ((bp=(BUFFER *)malloc(sizeof(BUFFER))) == NULL) {
		ewprintf("Can't get %d bytes", sizeof(BUFFER));
		return NULL;
	}
	if ((bp->b_bname=malloc((unsigned)(strlen(bname)+1))) == NULL) {
		ewprintf("Can't get %d bytes", strlen(bname)+1);
		free((char *) bp);
		return NULL;
	}
	if ((lp = lalloc(0)) == NULL) {
		free(bp->b_bname);
		free((char *) bp);
		return NULL;
	}
	bp->b_altb = bp->b_bufp	 = NULL;
	bp->b_dotp  = lp;
	bp->b_doto  = 0;
	bp->b_markp = NULL;
	bp->b_marko = 0;
	bp->b_flag  = defb_flag;
	bp->b_nwnd  = 0;
	bp->b_linep = lp;
	bp->b_nmodes = defb_nmodes;
	i = 0;
	do {
	    bp->b_modes[i] = defb_modes[i];
	} while(i++ < defb_nmodes);
	bp->b_fname[0] = '\0';
	(VOID) strcpy(bp->b_bname, bname);
	lp->l_fp = lp;
	lp->l_bp = lp;
	bp->b_bufp = bheadp;
	bheadp = bp;
	return bp;
}

/*
 * This routine blows away all of the text
 * in a buffer. If the buffer is marked as changed
 * then we ask if it is ok to blow it away; this is
 * to save the user the grief of losing text. The
 * window chain is nearly always wrong if this gets
 * called; the caller must arrange for the updates
 * that are required. Return TRUE if everything
 * looks good.
 */
bclear(bp) register BUFFER *bp; {
	register LINE	*lp;
	register int	s;
	VOID		lfree();

	if ((bp->b_flag&BFCHG) != 0		/* Changed.		*/
	&& (s=eyesno("Buffer modified; kill anyway")) != TRUE)
		return (s);
	bp->b_flag  &= ~BFCHG;			/* Not changed		*/
	while ((lp=lforw(bp->b_linep)) != bp->b_linep)
		lfree(lp);
	bp->b_dotp  = bp->b_linep;		/* Fix "."		*/
	bp->b_doto  = 0;
	bp->b_markp = NULL;			/* Invalidate "mark"	*/
	bp->b_marko = 0;
	return TRUE;
}

/*
 * Display the given buffer in the given window. Flags indicated
 * action on redisplay.
 */
showbuffer(bp, wp, flags) register BUFFER *bp; register WINDOW *wp; {
	register BUFFER *obp;
	WINDOW		*owp;

	if (wp->w_bufp == bp) {			/* Easy case!	*/
		wp->w_flag |= flags;
		return TRUE;
	}

	/* First, dettach the old buffer from the window */
	if ((bp->b_altb = obp = wp->w_bufp) != NULL) {
		if (--obp->b_nwnd == 0) {
			obp->b_dotp  = wp->w_dotp;
			obp->b_doto  = wp->w_doto;
			obp->b_markp = wp->w_markp;
			obp->b_marko = wp->w_marko;
		}
	}

	/* Now, attach the new buffer to the window */
	wp->w_bufp = bp;

	if (bp->b_nwnd++ == 0) {		/* First use.		*/
		wp->w_dotp  = bp->b_dotp;
		wp->w_doto  = bp->b_doto;
		wp->w_markp = bp->b_markp;
		wp->w_marko = bp->b_marko;
	} else
	/* already on screen, steal values from other window */
		for (owp = wheadp; owp != NULL; owp = wp->w_wndp)
			if (wp->w_bufp == bp && owp != wp) {
				wp->w_dotp  = owp->w_dotp;
				wp->w_doto  = owp->w_doto;
				wp->w_markp = owp->w_markp;
				wp->w_marko = owp->w_marko;
				break;
			}
	wp->w_flag |= WFMODE|flags;
	return TRUE;
}

/*
 * Pop the buffer we got passed onto the screen.
 * Returns a status.
 */
WINDOW *
popbuf(bp) register BUFFER *bp; {
	register WINDOW *wp;

	if (bp->b_nwnd == 0) {		/* Not on screen yet.	*/
		if ((wp=wpopup()) == NULL) return NULL;
	} else
		for (wp = wheadp; wp != NULL; wp = wp->w_wndp)
			if (wp->w_bufp == bp) {
				wp->w_flag |= WFHARD|WFFORCE;
				return wp ;
			}
	if (showbuffer(bp, wp, WFHARD) != TRUE) return NULL;
	return wp;
}

/*
 * Insert another buffer at dot.  Very useful.
 */
/*ARGSUSED*/
bufferinsert(f, n)
{
	register BUFFER *bp;
	register LINE	*clp;
	register int	clo;
	register int	nline;
	int		s;
	char		bufn[NBUFN];

	/* Get buffer to use from user */
	if (curbp->b_altb != NULL)
		s=eread("Insert buffer: (default %s) ", bufn, NBUFN,
			 EFNEW|EFBUF, &(curbp->b_altb->b_bname),
			 (char *) NULL) ;
	else
		s=eread("Insert buffer: ", bufn, NBUFN, EFNEW|EFBUF,
			 (char *) NULL) ;
	if (s == ABORT) return (s);
	if (s == FALSE && curbp->b_altb != NULL) bp = curbp->b_altb;
	else if ((bp=bfind(bufn, FALSE)) == NULL) return FALSE;

	if (bp==curbp) {
		ewprintf("Cannot insert buffer into self");
		return FALSE;
	}

	/* insert the buffer */
	nline = 0;
	clp = lforw(bp->b_linep);
	for(;;) {
		for (clo = 0; clo < llength(clp); clo++)
			if (linsert(1, lgetc(clp, clo)) == FALSE)
				return FALSE;
		if((clp = lforw(clp)) == bp->b_linep) break;
		if (newline(FFRAND, 1) == FALSE) /* fake newline */
			return FALSE;
		nline++;
	}
	if (nline == 1) ewprintf("[Inserted 1 line]");
	else	ewprintf("[Inserted %d lines]", nline);

	clp = curwp->w_linep;			/* cosmetic adjustment */
	if (curwp->w_dotp == clp) {		/* for offscreen insert */
		while (nline-- && lback(clp)!=curbp->b_linep)
			clp = lback(clp);
		curwp->w_linep = clp;		/* adjust framing.	*/
		curwp->w_flag |= WFHARD;
	}
	return (TRUE);
}

/*
 * Turn off the dirty bit on this buffer.
 */
/*ARGSUSED*/
notmodified(f, n)
{
	register WINDOW *wp;

	curbp->b_flag &= ~BFCHG;
	wp = wheadp;				/* Update mode lines.	*/
	while (wp != NULL) {
		if (wp->w_bufp == curbp)
			wp->w_flag |= WFMODE;
		wp = wp->w_wndp;
	}
	ewprintf("Modification-flag cleared");
	return TRUE;
}

#ifndef NO_HELP
/*
 * Popbuf and set all windows to top of buffer.	 Currently only used by
 * help functions.
 */

popbuftop(bp)
register BUFFER *bp;
{
    register WINDOW *wp;

    bp->b_dotp = lforw(bp->b_linep);
    bp->b_doto = 0;
    if(bp->b_nwnd != 0) {
	for(wp = wheadp; wp!=NULL; wp = wp->w_wndp)
	    if(wp->w_bufp == bp) {
		wp->w_dotp = bp->b_dotp;
		wp->w_doto = 0;
		wp->w_flag |= WFHARD;
	    }
    }
    return popbuf(bp) != NULL;
}
#endif
SHAR_EOF
cat << \SHAR_EOF > def.h
/*
 * This file is the general header file for all parts
 * of the MicroEMACS display editor. It contains all of the
 * general definitions and macros. It also contains some
 * conditional compilation flags. All of the per-system and
 * per-terminal definitions are in special header files.
 * The most common reason to edit this file would be to zap
 * the definition of CVMVAS or BACKUP.
 */
#include	"sysdef.h"		/* Order is critical.		*/
#include	"ttydef.h"
#include	"chrdef.h"

/*
 * If your system and/or compiler does not support the "void" type
 * then define NO_VOID_TYPE in sysdef.h.  In the absence of some
 * other definition for VOID, the default in that case will be to
 * turn it into an int, which works with most compilers that don't
 * support void.  In the absence of any definition of VOID or
 * NO_VOID_TYPE, the default is to assume void is supported, which
 * should be the case for most modern C compilers.
 */

#ifdef NO_VOID_TYPE
#  undef VOID
#  define VOID int			/* Default for no void is int */
#else
#ifndef VOID
#  define VOID void			/* Just use normal void */
#endif /* VOID */
#endif /* NO_VOID_TYPE */

#ifdef	NO_MACRO
#ifndef NO_STARTUP
#define NO_STARTUP			/* NO_MACRO implies NO_STARTUP */
#endif
#endif

typedef int (*PF)();			/* generaly useful type */

/*
 * Table sizes, etc.
 */
#define NFILEN	80			/* Length, file name.		*/
#define NBUFN	24			/* Length, buffer name.		*/
#define NLINE	256			/* Length, line.		*/
#define PBMODES 4			/* modes per buffer		*/
#define NKBDM	256			/* Length, keyboard macro.	*/
#define NPAT	80			/* Length, pattern.		*/
#define HUGE	1000			/* A rather large number.	*/
#define NSRCH	128			/* Undoable search commands.	*/
#define NXNAME	64			/* Length, extended command.	*/
#define NKNAME	20			/* Length, key names		*/
/*
 * Universal.
 */
#define FALSE	0			/* False, no, bad, etc.		*/
#define TRUE	1			/* True, yes, good, etc.	*/
#define ABORT	2			/* Death, ^G, abort, etc.	*/

#define KPROMPT 2			/* keyboard prompt		*/

/*
 * These flag bits keep track of
 * some aspects of the last command. The CFCPCN
 * flag controls goal column setting. The CFKILL
 * flag controls the clearing versus appending
 * of data in the kill buffer.
 */
#define CFCPCN	0x0001			/* Last command was C-P, C-N	*/
#define CFKILL	0x0002			/* Last command was a kill	*/
#define CFINS	0x0004			/* Last command was self-insert */

/*
 * File I/O.
 */
#define FIOSUC	0			/* Success.			*/
#define FIOFNF	1			/* File not found.		*/
#define FIOEOF	2			/* End of file.			*/
#define FIOERR	3			/* Error.			*/
#define FIOLONG 4			/* long line partially read	*/

/*
 * Directory I/O.
 */
#define DIOSUC	0			/* Success.			*/
#define DIOEOF	1			/* End of file.			*/
#define DIOERR	2			/* Error.			*/

/*
 * Display colors.
 */
#define CNONE	0			/* Unknown color.		*/
#define CTEXT	1			/* Text color.			*/
#define CMODE	2			/* Mode line color.		*/

/* Flags for keyboard involked functions */

#define FFUNIV		1		/* universal argument		*/
#define FFNEGARG	2		/* negitive only argument	*/
#define FFOTHARG	4		/* other argument		*/
#define FFARG		7		/* any argument			*/
#define FFRAND		8		/* Called by other function	*/

/*
 * Flags for "eread".
 */
#define EFFUNC	0x0001			/* Autocomplete functions.	*/
#define EFBUF	0x0002			/* Autocomplete buffers.	*/
#define EFFILE	0x0004			/* " files (maybe someday)	*/
#define EFAUTO	0x0007			/* Some autocompleteion on	*/
#define EFNEW	0x0008			/* New prompt.			*/
#define EFCR	0x0010			/* Echo CR at end; last read.	*/

/*
 * Flags for "ldelete"/"kinsert"
 */

#define KNONE	0
#define KFORW	1
#define KBACK	2

/*
 * All text is kept in circularly linked
 * lists of "LINE" structures. These begin at the
 * header line (which is the blank line beyond the
 * end of the buffer). This line is pointed to by
 * the "BUFFER". Each line contains a the number of
 * bytes in the line (the "used" size), the size
 * of the text array, and the text. The end of line
 * is not stored as a byte; it's implied. Future
 * additions will include update hints, and a
 * list of marks into the line.
 */
typedef struct	LINE {
	struct	LINE *l_fp;		/* Link to the next line	*/
	struct	LINE *l_bp;		/* Link to the previous line	*/
	short	l_size;			/* Allocated size		*/
	short	l_used;			/* Used size			*/
#ifndef ZEROARRAY
	char	l_text[1];		/* A bunch of characters.	*/
#else
	char	l_text[];		/* A bunch of characters.	*/
#endif
}	LINE;

/*
 * The rationale behind these macros is that you
 * could (with some editing, like changing the type of a line
 * link from a "LINE *" to a "REFLINE", and fixing the commands
 * like file reading that break the rules) change the actual
 * storage representation of lines to use something fancy on
 * machines with small address spaces.
 */
#define lforw(lp)	((lp)->l_fp)
#define lback(lp)	((lp)->l_bp)
#define lgetc(lp, n)	(CHARMASK((lp)->l_text[(n)]))
#define lputc(lp, n, c) ((lp)->l_text[(n)]=(c))
#define llength(lp)	((lp)->l_used)
#define ltext(lp)	((lp)->l_text)

/*
 * All repeated structures are kept as linked lists of structures.
 * All of these start with a LIST structure (except lines, which
 * have their own abstraction). This will allow for
 * later conversion to generic list manipulation routines should
 * I decide to do that. it does mean that there are four extra
 * bytes per window. I feel that this is an acceptable price,
 * considering that there are usually only one or two windows.
 */
typedef struct LIST {
	union {
		struct WINDOW	*l_wp;
		struct BUFFER	*x_bp;	/* l_bp is used by LINE */
		struct LIST	*l_nxt;
	} l_p;
	char	*l_name;
} LIST;
/*
 * Usual hack - to keep from uglifying the code with lotsa
 * references through the union, we #define something for it.
 */
#define l_next	l_p.l_nxt

/*
 * There is a window structure allocated for
 * every active display window. The windows are kept in a
 * big list, in top to bottom screen order, with the listhead at
 * "wheadp". Each window contains its own values of dot and mark.
 * The flag field contains some bits that are set by commands
 * to guide redisplay; although this is a bit of a compromise in
 * terms of decoupling, the full blown redisplay is just too
 * expensive to run for every input character.
 */
typedef struct	WINDOW {
	LIST	w_list;			/* List header		       */
	struct	BUFFER *w_bufp;		/* Buffer displayed in window	*/
	struct	LINE *w_linep;		/* Top line in the window	*/
	struct	LINE *w_dotp;		/* Line containing "."		*/
	struct	LINE *w_markp;		/* Line containing "mark"	*/
	short	w_doto;			/* Byte offset for "."		*/
	short	w_marko;		/* Byte offset for "mark"	*/
	char	w_toprow;		/* Origin 0 top row of window	*/
	char	w_ntrows;		/* # of rows of text in window	*/
	char	w_force;		/* If NZ, forcing row.		*/
	char	w_flag;			/* Flags.			*/
}	WINDOW;
#define w_wndp	w_list.l_p.l_wp
#define w_name	w_list.l_name

/*
 * Window flags are set by command processors to
 * tell the display system what has happened to the buffer
 * mapped by the window. Setting "WFHARD" is always a safe thing
 * to do, but it may do more work than is necessary. Always try
 * to set the simplest action that achieves the required update.
 * Because commands set bits in the "w_flag", update will see
 * all change flags, and do the most general one.
 */
#define WFFORCE 0x01			/* Force reframe.		*/
#define WFMOVE	0x02			/* Movement from line to line.	*/
#define WFEDIT	0x04			/* Editing within a line.	*/
#define WFHARD	0x08			/* Better to a full display.	*/
#define WFMODE	0x10			/* Update mode line.		*/

/*
 * Text is kept in buffers. A buffer header, described
 * below, exists for every buffer in the system. The buffers are
 * kept in a big list, so that commands that search for a buffer by
 * name can find the buffer header. There is a safe store for the
 * dot and mark in the header, but this is only valid if the buffer
 * is not being displayed (that is, if "b_nwnd" is 0). The text for
 * the buffer is kept in a circularly linked list of lines, with
 * a pointer to the header line in "b_linep".
 */
typedef struct	BUFFER {
	LIST	b_list;			/* buffer list pointer		*/
	struct	BUFFER *b_altb;		/* Link to alternate buffer	*/
	struct	LINE *b_dotp;		/* Link to "." LINE structure	*/
	struct	LINE *b_markp;		/* ditto for mark		*/
	struct	LINE *b_linep;		/* Link to the header LINE	*/
	struct	MAPS_S *b_modes[PBMODES]; /* buffer modes		*/
	short	b_doto;			/* Offset of "." in above LINE	*/
	short	b_marko;		/* ditto for the "mark"		*/
	short	b_nmodes;		/* number of non-fundamental modes */
	char	b_nwnd;			/* Count of windows on buffer	*/
	char	b_flag;			/* Flags			*/
	char	b_fname[NFILEN];	/* File name			*/
}	BUFFER;
#define b_bufp	b_list.l_p.x_bp
#define b_bname b_list.l_name

#define BFCHG	0x01			/* Changed.			*/
#define BFBAK	0x02			/* Need to make a backup.	*/
#ifdef	NOTAB
#define BFNOTAB 0x04			/* no tab mode			*/
#endif
#define BFOVERWRITE 0x08		/* overwrite mode		*/

/*
 * This structure holds the starting position
 * (as a line/offset pair) and the number of characters in a
 * region of a buffer. This makes passing the specification
 * of a region around a little bit easier.
 */
typedef struct	{
	struct	LINE *r_linep;		/* Origin LINE address.		*/
	short	r_offset;		/* Origin LINE offset.		*/
	RSIZE	r_size;			/* Length in characters.	*/
}	REGION;

/*
 * Externals.
 */
extern	int	thisflag;
extern	int	lastflag;
extern	int	curgoal;
extern	int	epresf;
extern	int	sgarbf;
extern	int	mode;
extern	WINDOW	*curwp;
extern	BUFFER	*curbp;
extern	WINDOW	*wheadp;
extern	BUFFER	*bheadp;
extern	char	pat[];
extern	BUFFER	*bfind();
extern	WINDOW	*popbuf();
extern	WINDOW	*wpopup();
extern	LINE	*lalloc();
extern	LINE	*lallocx();
extern	VOID	ewprintf();
extern	int	nrow;
extern	int	ncol;
extern	int	ttrow;
extern	int	ttcol;
extern	int	tceeol;
extern	int	tcinsl;
extern	int	tcdell;
extern	char	cinfo[];
extern	char	*keystrings[];
extern	VOID	update();
extern	char	*keyname();
extern	char	*adjustname();
extern	VOID	kdelete();
extern	VOID	lchange();
/*
 * Standard I/O.
 */
extern	char	*strcpy();
extern	char	*strcat();
extern	char	*malloc();
SHAR_EOF
cat << \SHAR_EOF > echo.c
/*
 *		Echo line reading and writing.
 *
 * Common routines for reading
 * and writing characters in the echo line area
 * of the display screen. Used by the entire
 * known universe.
 */
/*
 * The varargs lint directive comments are 0 an attempt to get lint to shup
 * up about CORRECT usage of varargs.h.  It won't.
 */
#include	"def.h"
#include	"key.h"
#ifdef	LOCAL_VARARGS
#include	"varargs.h"
#else
#include	<varargs.h>
#endif
#ifndef NO_MACRO
#  include	"macro.h"
#endif

static int	veread();
VOID		ewprintf();
static VOID	eformat();
static VOID	eputi();
static VOID	eputl();
static VOID	eputs();
static VOID	eputc();
static int	complt();

int	epresf	= FALSE;		/* Stuff in echo line flag.	*/
/*
 * Erase the echo line.
 */
VOID
eerase() {
	ttcolor(CTEXT);
	ttmove(nrow-1, 0);
	tteeol();
	ttflush();
	epresf = FALSE;
}

/*
 * Ask "yes" or "no" question.
 * Return ABORT if the user answers the question
 * with the abort ("^G") character. Return FALSE
 * for "no" and TRUE for "yes". No formatting
 * services are available. No newline required.
 */
eyorn(sp) char *sp; {
	register int	s;

#ifndef NO_MACRO
	if(inmacro) return TRUE;
#endif
	ewprintf("%s? (y or n) ", sp);
	for (;;) {
		s = getkey(FALSE);
		if (s == 'y' || s == 'Y') return TRUE;
		if (s == 'n' || s == 'N') return FALSE;
		if (s == CCHR('G')) return ctrlg(FFRAND, 1);
		ewprintf("Please answer y or n.  %s? (y or n) ", sp);
	}
	/*NOTREACHED*/
}

/*
 * Like eyorn, but for more important question. User must type either all of
 * "yes" or "no", and the trainling newline.
 */
eyesno(sp) char *sp; {
	register int	s;
	char		buf[64];

#ifndef NO_MACRO
	if(inmacro) return TRUE;
#endif
	s = ereply("%s? (yes or no) ", buf, sizeof(buf), sp);
	for (;;) {
		if (s == ABORT) return ABORT;
		if (s != FALSE) {
#ifndef NO_MACRO
			if (macrodef) {
			    LINE *lp = maclcur;

			    maclcur = lp->l_bp;
			    maclcur->l_fp = lp->l_fp;
			    free((char *)lp);
			}
#endif
			if ((buf[0] == 'y' || buf[0] == 'Y')
			    &&	(buf[1] == 'e' || buf[1] == 'E')
			    &&	(buf[2] == 's' || buf[2] == 'S')
			    &&	(buf[3] == '\0')) return TRUE;
			if ((buf[0] == 'n' || buf[0] == 'N')
			    &&	(buf[1] == 'o' || buf[0] == 'O')
			    &&	(buf[2] == '\0')) return FALSE;
		}
		s = ereply("Please answer yes or no.  %s? (yes or no) ",
			   buf, sizeof(buf), sp);
	}
	/*NOTREACHED*/
}
/*
 * Write out a prompt, and read back a
 * reply. The prompt is now written out with full "ewprintf"
 * formatting, although the arguments are in a rather strange
 * place. This is always a new message, there is no auto
 * completion, and the return is echoed as such.
 */
/*VARARGS 0*/
ereply(va_alist)
va_dcl
{
	va_list pvar;
	register char *fp, *buf;
	register int nbuf;
	register int i;

	va_start(pvar);
	fp = va_arg(pvar, char *);
	buf = va_arg(pvar, char *);
	nbuf = va_arg(pvar, int);
	i = veread(fp, buf, nbuf, EFNEW|EFCR, &pvar);
	va_end(pvar);
	return i;
}

/*
 * This is the general "read input from the
 * echo line" routine. The basic idea is that the prompt
 * string "prompt" is written to the echo line, and a one
 * line reply is read back into the supplied "buf" (with
 * maximum length "len"). The "flag" contains EFNEW (a
 * new prompt), an EFFUNC (autocomplete), or EFCR (echo
 * the carriage return as CR).
 */
/* VARARGS 0 */
eread(va_alist)
va_dcl
{
	va_list pvar;
	char *fp, *buf;
	int nbuf, flag, i;
	va_start(pvar);
	fp   = va_arg(pvar, char *);
	buf  = va_arg(pvar, char *);
	nbuf = va_arg(pvar, int);
	flag = va_arg(pvar, int);
	i = veread(fp, buf, nbuf, flag, &pvar);
	va_end(pvar);
	return i;
}

static veread(fp, buf, nbuf, flag, ap) char *fp; char *buf; va_list *ap; {
	register int	cpos;
	register int	i;
	register int	c;

#ifndef NO_MACRO
	if(inmacro) {
	    bcopy(maclcur->l_text, buf, maclcur->l_used);
	    buf[maclcur->l_used] = '\0';
	    maclcur = maclcur->l_fp;
	    return TRUE;
	}
#endif
	cpos = 0;
	if ((flag&EFNEW)!=0 || ttrow!=nrow-1) {
		ttcolor(CTEXT);
		ttmove(nrow-1, 0);
		epresf = TRUE;
	} else
		eputc(' ');
	eformat(fp, ap);
	tteeol();
	ttflush();
	for (;;) {
		c = getkey(FALSE);
		if ((flag&EFAUTO) != 0 && (c == ' ' || c == CCHR('I'))) {
			cpos += complt(flag, c, buf, cpos);
			continue;
		}
		switch (c) {
		    case CCHR('J'):
			c = CCHR('M');		/* and continue		*/
		    case CCHR('M'):		/* Return, done.	*/
			if ((flag&EFFUNC) != 0) {
				if ((i = complt(flag, c, buf, cpos)) == 0)
					continue;
				if (i > 0) cpos += i;
			}
			buf[cpos] = '\0';
			if ((flag&EFCR) != 0) {
				ttputc(CCHR('M'));
				ttflush();
			}
#ifndef NO_MACRO
			if(macrodef) {
			    LINE *lp;

			    if((lp = lalloc(cpos)) == NULL) return FALSE;
			    lp->l_fp = maclcur->l_fp;
			    maclcur->l_fp = lp;
			    lp->l_bp = maclcur;
			    maclcur = lp;
			    bcopy(buf, lp->l_text, cpos);
			}
#endif
			goto done;

		    case CCHR('G'):		/* Bell, abort.		*/
			eputc(CCHR('G'));
			(VOID) ctrlg(FFRAND, 0);
			ttflush();
			return ABORT;

		    case CCHR('H'):
		    case CCHR('?'):		/* Rubout, erase.	*/
			if (cpos != 0) {
				ttputc('\b');
				ttputc(' ');
				ttputc('\b');
				--ttcol;
				if (ISCTRL(buf[--cpos]) != FALSE) {
					ttputc('\b');
					ttputc(' ');
					ttputc('\b');
					--ttcol;
				}
				ttflush();
			}
			break;

		    case CCHR('X'):		/* C-X			*/
		    case CCHR('U'):		/* C-U, kill line.	*/
			while (cpos != 0) {
				ttputc('\b');
				ttputc(' ');
				ttputc('\b');
				--ttcol;
				if (ISCTRL(buf[--cpos]) != FALSE) {
					ttputc('\b');
					ttputc(' ');
					ttputc('\b');
					--ttcol;
				}
			}
			ttflush();
			break;

		    case CCHR('W'):		/* C-W, kill to beginning of */
						/* previous word	*/
			/* back up to first word character or beginning */
			while ((cpos > 0) && !ISWORD(buf[cpos - 1])) {
				ttputc('\b');
				ttputc(' ');
				ttputc('\b');
				--ttcol;
				if (ISCTRL(buf[--cpos]) != FALSE) {
					ttputc('\b');
					ttputc(' ');
					ttputc('\b');
					--ttcol;
				}
			}
			while ((cpos > 0) && ISWORD(buf[cpos - 1])) {
				ttputc('\b');
				ttputc(' ');
				ttputc('\b');
				--ttcol;
				if (ISCTRL(buf[--cpos]) != FALSE) {
					ttputc('\b');
					ttputc(' ');
					ttputc('\b');
					--ttcol;
				}
			}
			ttflush();
			break;

		    case CCHR('\\'):
		    case CCHR('Q'):		/* C-Q, quote next	*/
			c = getkey(FALSE);	/* and continue		*/
		    default:			/* All the rest.	*/
			if (cpos < nbuf-1) {
				buf[cpos++] = (char) c;
				eputc((char) c);
				ttflush();
			}
		}
	}
done:	return buf[0] != '\0';
}

/*
 * do completion on a list of objects.
 */
static int complt(flags, c, buf, cpos)
register char *buf;
register int cpos;
{
	register LIST	*lh, *lh2;
	int		i, nxtra;
	int		nhits, bxtra;
	int		wflag = FALSE;
	int		msglen, nshown;
	char		*msg;

	if ((flags&EFFUNC) != 0) {
	    buf[cpos] = '\0';
	    i = complete_function(buf, c);
	    if(i>0) {
		eputs(&buf[cpos]);
		ttflush();
		return i;
	    }
	    switch(i) {
		case -3:
		    msg = " [Ambiguous]";
		    break;
		case -2:
		    i=0;
		    msg = " [No match]";
		    break;
		case -1:
		case 0:
		    return i;
		default:
		    msg = " [Internal error]";
		    break;
	    }
	} else {
	    if ((flags&EFBUF) != 0) lh = &(bheadp->b_list);
	    else panic("broken complt call: flags");

	    if (c == ' ') wflag = TRUE;
	    else if (c != '\t' && c != CCHR('M')) panic("broken complt call: c");

	    nhits = 0;
	    nxtra = HUGE;

	    while (lh != NULL) {
		for (i=0; i<cpos; ++i) {
			if (buf[i] != lh->l_name[i])
				break;
		}
		if (i == cpos) {
			if (nhits == 0)
				lh2 = lh;
			++nhits;
			if (lh->l_name[i] == '\0') nxtra = -1;
			else {
				bxtra = getxtra(lh, lh2, cpos, wflag);
				if (bxtra < nxtra) nxtra = bxtra;
				lh2 = lh;
			}
		}
		lh = lh->l_next;
	    }
	    if (nhits == 0)
		msg = " [No match]";
	    else if (nhits > 1 && nxtra == 0)
		msg = " [Ambiguous]";
	    else {		/* Got a match, do it to it */
		/*
		 * Being lazy - ought to check length, but all things
		 * autocompleted have known types/lengths.
		 */
		if (nxtra < 0 && nhits > 1 && c == ' ') nxtra = 1;
		for (i = 0; i < nxtra; ++i) {
			buf[cpos] = lh2->l_name[cpos];
			eputc(buf[cpos++]);
		}
		ttflush();
		if (nxtra < 0 && c != CCHR('M')) return 0;
		return nxtra;
	    }
	}
	/* Set up backspaces, etc., being mindful of echo line limit */
	msglen = strlen(msg);
	nshown = (ttcol + msglen + 2 > ncol) ?
			ncol - ttcol - 2 : msglen;
	eputs(msg);
	ttcol -= (i = nshown);		/* update ttcol!		*/
	while (i--)			/* move back before msg		*/
		ttputc('\b');
	ttflush();			/* display to user		*/
	i = nshown;
	while (i--)			/* blank out	on next flush	*/
		eputc(' ');
	ttcol -= (i = nshown);		/* update ttcol on BS's		*/
	while (i--)
		ttputc('\b');		/* update ttcol again!		*/
	return 0;
}

/*
 * The "lp1" and "lp2" point to list structures. The
 * "cpos" is a horizontal position in the name.
 * Return the longest block of characters that can be
 * autocompleted at this point. Sometimes the two
 * symbols are the same, but this is normal.
  */
getxtra(lp1, lp2, cpos, wflag) register LIST *lp1, *lp2; register int wflag; {
	register int	i;

	i = cpos;
	for (;;) {
		if (lp1->l_name[i] != lp2->l_name[i]) break;
		if (lp1->l_name[i] == '\0') break;
		++i;
		if (wflag && !ISWORD(lp1->l_name[i-1])) break;
	}
	return (i - cpos);
}

/*
 * Special "printf" for the echo line.
 * Each call to "ewprintf" starts a new line in the
 * echo area, and ends with an erase to end of the
 * echo line. The formatting is done by a call
 * to the standard formatting routine.
 */
/*VARARGS 0 */
VOID
ewprintf(va_alist)
va_dcl
{
	va_list pvar;
	register char *fp;

#ifndef NO_MACRO
	if(inmacro) return;
#endif
	va_start(pvar);
	fp = va_arg(pvar, char *);
	ttcolor(CTEXT);
	ttmove(nrow-1, 0);
	eformat(fp, &pvar);
	va_end(pvar);
	tteeol();
	ttflush();
	epresf = TRUE;
}

/*
 * Printf style formatting. This is
 * called by both "ewprintf" and "ereply" to provide
 * formatting services to their clients. The move to the
 * start of the echo line, and the erase to the end of
 * the echo line, is done by the caller.
 * Note: %c works, and prints the "name" of the character.
 * %k prints the name of a key (and takes no arguments).
 */
static VOID
eformat(fp, ap)
register char *fp;
register va_list *ap;
{
	register int c;
	char	kname[NKNAME];
	char	*keyname();
	char	*cp;

	while ((c = *fp++) != '\0') {
		if (c != '%')
			eputc(c);
		else {
			c = *fp++;
			switch (c) {
			case 'c':
				(VOID) keyname(kname, va_arg(*ap, int));
				eputs(kname);
				break;

			case 'k':
				cp = kname;
				for(c=0; c < key.k_count; c++) {
				    cp = keyname(cp, key.k_chars[c]);
				    *cp++ = ' ';
				}
				*--cp = '\0';
				eputs(kname);
				break;

			case 'd':
				eputi(va_arg(*ap, int), 10);
				break;

			case 'o':
				eputi(va_arg(*ap, int), 8);
				break;

			case 's':
				eputs(va_arg(*ap, char *));
				break;

			case 'l':/* explicit longword */
				c = *fp++;
				switch(c) {
				case 'd':
					eputl((long)va_arg(*ap, long), 10);
					break;
				default:
					eputc(c);
					break;
				}
				break;

			default:
				eputc(c);
			}
		}
	}
}

/*
 * Put integer, in radix "r".
 */
static VOID
eputi(i, r)
register int i;
register int r;
{
	register int	q;

	if(i<0) {
	    eputc('-');
	    i = -i;
	}
	if ((q=i/r) != 0)
		eputi(q, r);
	eputc(i%r+'0');
}

/*
 * Put long, in radix "r".
 */
static VOID
eputl(l, r)
register long l;
register int  r;
{
	register long	q;

	if(l < 0) {
	    eputc('-');
	    l = -l;
	}
	if ((q=l/r) != 0)
		eputl(q, r);
	eputc((int)(l%r)+'0');
}

/*
 * Put string.
 */
static VOID
eputs(s)
register char *s;
{
	register int	c;

	while ((c = *s++) != '\0')
		eputc(c);
}

/*
 * Put character. Watch for
 * control characters, and for the line
 * getting too long.
 */
static VOID
eputc(c)
register char c;
{
	if (ttcol+2 < ncol) {
		if (ISCTRL(c)) {
			eputc('^');
			c = CCHR(c);
		}
		ttputc(c);
		++ttcol;
	}
}

SHAR_EOF
cat << \SHAR_EOF > help.c
/* Help functions for MicroGnuEmacs 2 */

#include "def.h"

#ifndef NO_HELP
#include "kbd.h"
#include "key.h"
#ifndef NO_MACRO
#include "macro.h"
#endif
extern int rescan();

/*
 * Read a key from the keyboard, and look it
 * up in the keymap.  Display the name of the function
 * currently bound to the key.
 */
/*ARGSUSED*/
desckey(f, n)
{
    register KEYMAP *curmap;
    register PF funct;
    register char *pep;
    char prompt[80];
    int c;
    int m;
    int i;

#ifndef NO_MACRO
    if(inmacro) return TRUE;		/* ignore inside keyboard macro */
#endif
    (VOID) strcpy(prompt, "Describe key briefly: ");
    pep = prompt + strlen(prompt);
    key.k_count = 0;
    m = curbp->b_nmodes;
    curmap = curbp->b_modes[m]->p_map;
    for(;;) {
	for(;;) {
	    ewprintf("%s", prompt);
	    pep[-1] = ' ';
	    pep = keyname(pep, key.k_chars[key.k_count++] = c = getkey(FALSE));
	    if((funct = doscan(curmap, c)) != prefix) break;
	    *pep++ = '-';
	    *pep = '\0';
	    curmap = ele->k_prefmap;
	}
	if(funct != rescan) break;
	if(ISUPPER(key.k_chars[key.k_count-1])) {
	    funct = doscan(curmap, TOLOWER(key.k_chars[key.k_count-1]));
	    if(funct == prefix) {
		*pep++ = '-';
		*pep = '\0';
		curmap = ele->k_prefmap;
		continue;
	    }
	    if(funct != rescan) break;
	}
nextmode:
	if(--m < 0) break;
	curmap = curbp->b_modes[m]->p_map;
	for(i=0; i < key.k_count; i++) {
	    funct = doscan(curmap, key.k_chars[i]);
	    if(funct != prefix) {
		if(i == key.k_count - 1 && funct != rescan) goto found;
		funct = rescan;
		goto nextmode;
	    }
	    curmap = ele->k_prefmap;
	}
	*pep++ = '-';
	*pep = '\0';
    }
found:
    if(funct == rescan) ewprintf("%k is not bound to any function");
    else if((pep = function_name(funct)) != NULL)
	    ewprintf("%k runs the command %s", pep);
    else    ewprintf("%k is bound to an unnamed function");
    return TRUE;
}

/*
 * This function creates a table, listing all
 * of the command keys and their current bindings, and stores
 * the table in the *help* pop-up buffer.  This
 * lets MicroGnuEMACS produce it's own wall chart.
 */
static BUFFER	*bp;
static char buf[80];	/* used by showall and findbind */

/*ARGSUSED*/
wallchart(f, n)
{
	int m;
	static char locbind[80] = "Local keybindings for mode ";
	static int showall();

	bp = bfind("*help*", TRUE);
	if (bclear(bp) != TRUE) return FALSE;	/* Clear it out.	*/
	for(m=curbp->b_nmodes; m > 0; m--) {
	    (VOID) strcpy(&locbind[27], curbp->b_modes[m]->p_name);
	    (VOID) strcat(&locbind[27], ":");
	    if((addline(bp, locbind) == FALSE) ||
		(showall(buf, curbp->b_modes[m]->p_map) == FALSE) ||
		(addline(bp, "") == FALSE)) return FALSE;
	}
	if((addline(bp, "Global bindings:") == FALSE) ||
	    (showall(buf, map_table[0].p_map) == FALSE)) return FALSE;
	return popbuftop(bp);
}

static	int showall(ind, map)
char	*ind;
KEYMAP	*map;
{
	register MAP_ELEMENT *ele;
	register int i;
	PF	functp;
	char	*cp;
	char	*cp2;
	int	last;

	if(addline(bp, "") == FALSE) return FALSE;
	last = -1;
	for(ele = &map->map_element[0]; ele < &map->map_element[map->map_num] ; ele++) {
	    if(map->map_default != rescan && ++last < ele->k_base) {
		cp = keyname(ind, last);
		if(last < ele->k_base - 1) {
		    (VOID) strcpy(cp, " .. ");
		    cp = keyname(cp + 4, ele->k_base - 1);
		}
		do { *cp++ = ' '; } while(cp < &buf[16]);
		(VOID) strcpy(cp, function_name(map->map_default));
		if(addline(bp, buf) == FALSE) return FALSE;
	    }
	    last = ele->k_num;
	    for(i=ele->k_base; i <= last; i++) {
		functp = ele->k_funcp[i - ele->k_base];
		if(functp != rescan) {
		    if(functp != prefix) cp2 = function_name(functp);
		    else cp2 = map_name(ele->k_prefmap);
		    if(cp2 != NULL) {
			cp = keyname(ind, i);
			do { *cp++ = ' '; } while(cp < &buf[16]);
			(VOID) strcpy(cp, cp2);
			if (addline(bp, buf) == FALSE) return FALSE;
		    }
		}
	    }
	}
	for(ele = &map->map_element[0]; ele < &map->map_element[map->map_num]; ele++) {
	    if(ele->k_prefmap != NULL) {
		for(i = ele->k_base; ele->k_funcp[i - ele->k_base] != prefix; i++) {
		    if(i >= ele->k_num)  /* damaged map */
			return FALSE;
		}
		cp = keyname(ind, i);
		*cp++ = ' ';
		if(showall(cp, ele->k_prefmap) == FALSE) return FALSE;
	    }
	}
	return TRUE;
}

help_help(f, n)
int f, n;
{
    KEYMAP *kp;
    PF	funct;

    if((kp = name_map("help")) == NULL) return FALSE;
    ewprintf("a b c: ");
    do {
	funct = doscan(kp, getkey(FALSE));
    } while(funct==NULL || funct==help_help);
#ifndef NO_MACRO
    if(macrodef && macrocount < MAXMACRO) macro[macrocount-1].m_funct = funct;
#endif
    return (*funct)(f, n);
}

static char buf2[128];
static char *buf2p;

/*ARGSUSED*/
apropos_command(f, n)
int f, n;
{
    register char *cp1, *cp2;
    char string[32];
    FUNCTNAMES *fnp;
    BUFFER *bp;
    static VOID findbind();

    if(eread("apropos: ", string, sizeof(string), EFNEW) == ABORT) return ABORT;
	/* FALSE means we got a 0 character string, which is fine */
    bp = bfind("*help*", TRUE);
    if(bclear(bp) == FALSE) return FALSE;
    for(fnp = &functnames[0]; fnp < &functnames[nfunct]; fnp++) {
	for(cp1 = fnp->n_name; *cp1; cp1++) {
	    cp2 = string;
	    while(*cp2 && *cp1 == *cp2)
		cp1++, cp2++;
	    if(!*cp2) {
		(VOID) strcpy(buf2, fnp->n_name);
		buf2p = &buf2[strlen(buf2)];
		findbind(fnp->n_funct, buf, map_table[0].p_map);
		if(addline(bp, buf2) == FALSE) return FALSE;
		break;
	    } else cp1 -= cp2 - string;
	}
    }
    return popbuftop(bp);
}

static VOID findbind(funct, ind, map)
PF funct;
char *ind;
KEYMAP	*map;
{
    register MAP_ELEMENT *ele;
    register int i;
    char	*cp;
    int		last;
    static VOID	bindfound();

    last = -1;
    for(ele = &map->map_element[0]; ele < &map->map_element[map->map_num]; ele++) {
	if(map->map_default == funct && ++last < ele->k_base) {
	    cp = keyname(ind, last);
	    if(last < ele->k_base - 1) {
		(VOID) strcpy(cp, " .. ");
		(VOID) keyname(cp + 4, ele->k_base - 1);
	    }
	    bindfound();
	}
	last = ele->k_num;
	for(i=ele->k_base; i <= last; i++) {
	    if(funct == ele->k_funcp[i - ele->k_base]) {
		if(funct == prefix) {
		    cp = map_name(ele->k_prefmap);
		    if(strncmp(cp, buf2, strlen(cp)) != 0) continue;
		}
		(VOID) keyname(ind, i);
		bindfound();
	    }
	}
    }
    for(ele = &map->map_element[0]; ele < &map->map_element[map->map_num]; ele++) {
	if(ele->k_prefmap != NULL) {
	    for(i = ele->k_base; ele->k_funcp[i - ele->k_base] != prefix; i++) {
		if(i >= ele->k_num) return; /* damaged */
	    }
	    cp = keyname(ind, i);
	    *cp++ = ' ';
	    findbind(funct, cp, ele->k_prefmap);
	}
    }
}

static VOID bindfound() {
    if(buf2p < &buf2[32]) {
	do { *buf2p++ = ' '; } while(buf2p < &buf2[32]);
    } else {
	*buf2p++ = ',';
	*buf2p++ = ' ';
    }
    (VOID) strcpy(buf2p, buf);
    buf2p += strlen(buf);
}
#endif
SHAR_EOF
#	End of shell archive
exit 0
-------