echo x - Makefile
sed '/^X/s///' > Makefile << '/'
X# Makefile for mined
X
XCFLAGS	= -O -wo -D_POSIX_SOURCE
XO=o
X
XOBJ = mined1.$O mined2.$O
X
Xmined:	$(OBJ)
X	@rm -rf mined
X	@echo Start linking mined
X	@$(CC) -i -o $@ $(OBJ) >/dev/null
X	@chmem =64000 mined
X
X$(OBJ):	mined.h
X
Xclean:
X	@rm -f mined *.o *.s core *.bak
/
echo x - mined.h
sed '/^X/s///' > mined.h << '/'
X/*========================================================================*
X *				Mined.h					  *
X *========================================================================*/
X
X#include <minix/config.h>
X#include <sys/types.h>
X#include <fcntl.h>
X#include <stdlib.h>
X#include <unistd.h>
X#include <limits.h>
X
X#ifndef YMAX
X#ifdef UNIX
X#include <stdio.h>
X#undef putchar
X#undef getchar
X#undef NULL
X#undef EOF
Xextern char *CE, *VS, *SO, *SE, *CL, *AL, *CM;
X#define YMAX		49
X#else
X#define YMAX		24		/* Maximum y coordinate starting at 0 */
X/* Escape sequences. */
Xextern char *enter_string;	/* String printed on entering mined */
Xextern char *rev_video;		/* String for starting reverse video */
Xextern char *normal_video;	/* String for leaving reverse video */
Xextern char *rev_scroll;	/* String for reverse scrolling */
Xextern char *pos_string;	/* Absolute cursor positioning */
X#define X_PLUS	' '		/* To be added to x for cursor sequence */
X#define Y_PLUS	' '		/* To be added to y for cursor sequence */
X#endif /* UNIX */
X
X#define XMAX		79		/* Maximum x coordinate starting at 0*/
X#define SCREENMAX	(YMAX - 1)	/* Number of lines displayed */
X#define XBREAK		(XMAX - 0)	/* Line shift at this coordinate */
X#define SHIFT_SIZE	25		/* Number of chars to shift */
X#define SHIFT_MARK	'!'		/* Char indicating line continues */
X#define MAX_CHARS	1024		/* Maximum chars on one line */
X
X/* LINE_START must be rounded up to the lowest SHIFT_SIZE */
X#define LINE_START	(((-MAX_CHARS - 1) / SHIFT_SIZE) * SHIFT_SIZE \
X  				   - SHIFT_SIZE)
X#define LINE_END	(MAX_CHARS + 1)	/* Highest x-coordinate for line */
X
X#define LINE_LEN	(XMAX + 1)	/* Number of characters on line */
X#define SCREEN_SIZE	(XMAX * YMAX)	/* Size of I/O buffering */
X#define BLOCK_SIZE	1024
X
X/* Return values of functions */
X#define ERRORS		-1
X#define NO_LINE		(ERRORS - 1)	/* Must be < 0 */
X#define FINE	 	(ERRORS + 1)
X#define NO_INPUT	(ERRORS + 2)
X
X#define STD_OUT	 	1		/* File descriptor for terminal */
X
X#if (CHIP == INTEL)
X#define MEMORY_SIZE	(50 * 1024)	/* Size of data space to malloc */
X#endif
X
X#define REPORT	2			/* Report change of lines on # lines */
X
Xtypedef int FLAG;
X
X/* General flags */
X#define	FALSE		0
X#define	TRUE		1
X#define	NOT_VALID	2
X#define	VALID		3
X#define	OFF		4
X#define	ON		5
X
X/* Expression flags */
X#define	FORWARD		6
X#define	REVERSE		7
X
X/* Yank flags */
X#define	SMALLER		8
X#define	BIGGER		9
X#define	SAME		10
X#define	EMPTY		11
X#define	NO_DELETE	12
X#define	DELETE		13
X#define	READ		14
X#define	WRITE		15
X
X/*
X * The Line structure.  Each line entry contains a pointer to the next line,
X * a pointer to the previous line, a pointer to the text and an unsigned char
X * telling at which offset of the line printing should start (usually 0).
X */
Xstruct Line {
X  struct Line *next;
X  struct Line *prev;
X  char *text;
X  unsigned char shift_count;
X};
X
Xtypedef struct Line LINE;
X
X/* Dummy line indicator */
X#define DUMMY		0x80
X#define DUMMY_MASK	0x7F
X
X/* Expression definitions */
X#define NO_MATCH	0
X#define MATCH		1
X#define REG_ERROR	2
X
X#define BEGIN_LINE	(2 * REG_ERROR)
X#define END_LINE	(2 * BEGIN_LINE)
X
X/*
X * The regex structure. Status can be any of 0, BEGIN_LINE or REG_ERROR. In
X * the last case, the result.err_mess field is assigned. Start_ptr and end_ptr
X * point to the match found. For more details see the documentation file.
X */
Xstruct regex {
X  union {
X  	char *err_mess;
X  	int *expression;
X  } result;
X  char status;
X  char *start_ptr;
X  char *end_ptr;
X};
X
Xtypedef struct regex REGEX;
X
X/* NULL definitions */
X#define NIL_PTR		((char *) 0)
X#define NIL_LINE	((LINE *) 0)
X#define NIL_REG		((REGEX *) 0)
X#define NIL_INT		((int *) 0)
X
X/*
X * Forward declarations
X */
Xextern int nlines;		/* Number of lines in file */
Xextern LINE *header;		/* Head of line list */
Xextern LINE *tail;		/* Last line in line list */
Xextern LINE *top_line;		/* First line of screen */
Xextern LINE *bot_line;		/* Last line of screen */
Xextern LINE *cur_line;		/* Current line in use */
Xextern char *cur_text;		/* Pointer to char on current line in use */
Xextern int last_y;		/* Last y of screen. Usually SCREENMAX */
Xextern int ymax;
Xextern int screenmax;
Xextern char screen[SCREEN_SIZE];/* Output buffer for "writes" and "reads" */
X
Xextern int x, y;			/* x, y coordinates on screen */
Xextern FLAG modified;			/* Set when file is modified */
Xextern FLAG stat_visible;		/* Set if status_line is visible */
Xextern FLAG writable;			/* Set if file cannot be written */
Xextern FLAG quit;			/* Set when quit character is typed */
Xextern FLAG rpipe;		/* Set if file should be read from stdin */
Xextern int input_fd;			/* Fd for command input */
Xextern FLAG loading;			/* Set if we're loading a file */
Xextern int out_count;			/* Index in output buffer */
Xextern char file_name[LINE_LEN];	/* Name of file in use */
Xextern char text_buffer[MAX_CHARS];	/* Buffer for modifying text */
Xextern char *blank_line;		/* Clear line to end */
X
Xextern char yank_file[];		/* Temp file for buffer */
Xextern FLAG yank_status;		/* Status of yank_file */
Xextern long chars_saved;		/* Nr of chars saved in buffer */
X
X/*
X * Empty output buffer
X */
X#define clear_buffer()			(out_count = 0)
X
X/*
X * Print character on terminal
X */
X#define putchar(c)			(void) write_char(STD_OUT, (c))
X
X/*
X * Ring bell on terminal
X */
X#define ring_bell()			putchar('\07')
X
X/*
X * Print string on terminal
X */
X#define string_print(str)		(void) writeline(STD_OUT, (str))
X
X/*
X * Flush output buffer
X */
X#define flush()				(void) flush_buffer(STD_OUT)
X
X/*
X * Convert cnt to nearest tab position
X */
X#define tab(cnt)			(((cnt) + 8) & ~07)
X#define is_tab(c)			((c) == '\t')
X
X/*
X * Word defenitions
X */
X#define white_space(c)	((c) == ' ' || (c) == '\t')
X#define alpha(c)	((c) != ' ' && (c) != '\t' && (c) != '\n')
X
X/*
X * Print line on terminal at offset 0 and clear tail of line
X */
X#define line_print(line)		put_line(line, 0, TRUE)
X
X/*
X * Move to coordinates and set textp. (Don't use address)
X */
X#define move_to(nx, ny)			move((nx), NIL_PTR, (ny))
X
X/*
X * Move to coordinates on screen as indicated by textp.
X */
X#define move_address(address)		move(0, (address), y)
X
X/*
X * Functions handling status_line. ON means in reverse video.
X */
X#define status_line(str1, str2)	(void) bottom_line(ON, (str1), \
X						    (str2), NIL_PTR, FALSE)
X#define error(str1, str2)	(void) bottom_line(ON, (str1), \
X						    (str2), NIL_PTR, FALSE)
X#define get_string(str1,str2, fl) bottom_line(ON, (str1), NIL_PTR, (str2), fl)
X#define clear_status()		(void) bottom_line(OFF, NIL_PTR, NIL_PTR, \
X						    NIL_PTR, FALSE)
X
X/*
X * Print info about current file and buffer.
X */
X#define fstatus(mess, cnt)	file_status((mess), (cnt), file_name, \
X					     nlines, writable, modified)
X
X/*
X * Get real shift value.
X */
X#define get_shift(cnt)		((cnt) & DUMMY_MASK)
X
X#endif /* YMAX */
X
X/* mined1.c */
X
X_PROTOTYPE(void FS, (void));
X_PROTOTYPE(void VI, (void));
X_PROTOTYPE(int WT, (void));
X_PROTOTYPE(void XWT, (void));
X_PROTOTYPE(void SH, (void));
X_PROTOTYPE(LINE *proceed, (LINE *line, int count ));
X_PROTOTYPE(int bottom_line, (FLAG revfl, char *s1, char *s2, char *inbuf, FLAG statfl ));
X_PROTOTYPE(int count_chars, (LINE *line ));
X_PROTOTYPE(void move, (int new_x, char *new_address, int new_y ));
X_PROTOTYPE(int find_x, (LINE *line, char *address ));
X_PROTOTYPE(char *find_address, (LINE *line, int x_coord, int *old_x ));
X_PROTOTYPE(int length_of, (char *string ));
X_PROTOTYPE(void copy_string, (char *to, char *from ));
X_PROTOTYPE(void reset, (LINE *head_line, int screen_y ));
X_PROTOTYPE(void set_cursor, (int nx, int ny ));
X_PROTOTYPE(void open_device, (void));
X_PROTOTYPE(int getchar, (void));
X_PROTOTYPE(void display, (int x_coord, int y_coord, LINE *line, int count ));
X_PROTOTYPE(int write_char, (int fd, int c ));
X_PROTOTYPE(int writeline, (int fd, char *text ));
X_PROTOTYPE(void put_line, (LINE *line, int offset, FLAG clear_line ));
X_PROTOTYPE(int flush_buffer, (int fd ));
X_PROTOTYPE(void bad_write, (int fd ));
X_PROTOTYPE(void catch, (int sig ));
X_PROTOTYPE(void abort_mined, (void));
X_PROTOTYPE(void raw_mode, (FLAG state ));
X_PROTOTYPE(void panic, (char *message ));
X_PROTOTYPE(char *alloc, (int bytes ));
X_PROTOTYPE(void free_space, (char *p ));
X/*
X#ifdef UNIX
X_PROTOTYPE(void (*key_map [128]), (void));
X#else
X_PROTOTYPE(void (*key_map [256]), (void));
X#endif
X*/
X_PROTOTYPE(void initialize, (void));
X_PROTOTYPE(char *basename, (char *path ));
X_PROTOTYPE(void load_file, (char *file ));
X_PROTOTYPE(int get_line, (int fd, char *buffer ));
X_PROTOTYPE(LINE *install_line, (char *buffer, int length ));
X_PROTOTYPE(void main, (int argc, char *argv []));
X_PROTOTYPE(void RD, (void));
X_PROTOTYPE(void I, (void));
X_PROTOTYPE(void XT, (void));
X_PROTOTYPE(void ESC, (void));
X_PROTOTYPE(int ask_save, (void));
X_PROTOTYPE(int line_number, (void));
X_PROTOTYPE(void file_status, (char *message, long count, char *file, int lines,
X						 FLAG writefl, FLAG changed ));
Xvoid build_string();		/* varargs :-(  */
X
X_PROTOTYPE(char *num_out, (long number ));
X_PROTOTYPE(int get_number, (char *message, int *result ));
X_PROTOTYPE(int input, (char *inbuf, FLAG clearfl ));
X_PROTOTYPE(int get_file, (char *message, char *file ));
X_PROTOTYPE(int _getchar, (void));
X_PROTOTYPE(void _flush, (void));
X_PROTOTYPE(void _putchar, (int c ));
X_PROTOTYPE(void get_term, (void));
X
X/* mined2.c */
X
X_PROTOTYPE(void UP, (void));
X_PROTOTYPE(void DN, (void));
X_PROTOTYPE(void LF, (void));
X_PROTOTYPE(void RT, (void));
X_PROTOTYPE(void HIGH, (void));
X_PROTOTYPE(void LOW, (void));
X_PROTOTYPE(void BL, (void));
X_PROTOTYPE(void EL, (void));
X_PROTOTYPE(void GOTO, (void));
X_PROTOTYPE(void PD, (void));
X_PROTOTYPE(void PU, (void));
X_PROTOTYPE(void HO, (void));
X_PROTOTYPE(void EF, (void));
X_PROTOTYPE(void SU, (void));
X_PROTOTYPE(void SD, (void));
X_PROTOTYPE(int forward_scroll, (void));
X_PROTOTYPE(int reverse_scroll, (void));
X_PROTOTYPE(void MP, (void));
X_PROTOTYPE(void move_previous_word, (FLAG remove ));
X_PROTOTYPE(void MN, (void));
X_PROTOTYPE(void move_next_word, (FLAG remove ));
X_PROTOTYPE(void DCC, (void));
X_PROTOTYPE(void DPC, (void));
X_PROTOTYPE(void DLN, (void));
X_PROTOTYPE(void DNW, (void));
X_PROTOTYPE(void DPW, (void));
X_PROTOTYPE(void S, (int character ));
X_PROTOTYPE(void CTL, (void));
X_PROTOTYPE(void LIB, (void));
X_PROTOTYPE(LINE *line_insert, (LINE *line, char *string, int len ));
X_PROTOTYPE(int insert, (LINE *line, char *location, char *string ));
X_PROTOTYPE(LINE *line_delete, (LINE *line ));
X_PROTOTYPE(void delete, (LINE *start_line, char *start_textp, LINE *end_line, char *end_textp ));
X_PROTOTYPE(void PT, (void));
X_PROTOTYPE(void IF, (void));
X_PROTOTYPE(void file_insert, (int fd, FLAG old_pos ));
X_PROTOTYPE(void WB, (void));
X_PROTOTYPE(void MA, (void));
X_PROTOTYPE(void YA, (void));
X_PROTOTYPE(void DT, (void));
X_PROTOTYPE(void set_up, (FLAG remove ));
X_PROTOTYPE(FLAG checkmark, (void));
X_PROTOTYPE(int legal, (void));
X_PROTOTYPE(void yank, (LINE *start_line, char *start_textp, LINE *end_line, char *end_textp, FLAG remove ));
X_PROTOTYPE(int scratch_file, (FLAG mode ));
X_PROTOTYPE(void SF, (void));
X_PROTOTYPE(void SR, (void));
X_PROTOTYPE(REGEX *get_expression, (char *message ));
X_PROTOTYPE(void GR, (void));
X_PROTOTYPE(void LR, (void));
X_PROTOTYPE(void change, (char *message, FLAG file ));
X_PROTOTYPE(char *substitute, (LINE *line, REGEX *program, char *replacement ));
X_PROTOTYPE(void search, (char *message, FLAG method ));
X_PROTOTYPE(int find_y, (LINE *match_line ));
X_PROTOTYPE(void finished, (REGEX *program, int *last_exp ));
X_PROTOTYPE(void compile, (char *pattern, REGEX *program ));
X_PROTOTYPE(LINE *match, (REGEX *program, char *string, FLAG method ));
X_PROTOTYPE(int line_check, (REGEX *program, char *string, FLAG method ));
X_PROTOTYPE(int check_string, (REGEX *program, char *string, int *expression ));
X_PROTOTYPE(int star, (REGEX *program, char *end_position, char *string, int *expression ));
X_PROTOTYPE(int in_list, (int *list, int c, int list_length, int opcode ));
X_PROTOTYPE(void dummy_line, (void));
/
echo x - mined1.c
sed '/^X/s///' > mined1.c << '/'
X/*
X * Part one of the mined editor.
X */
X
X/*
X * Author: Michiel Huisjes.
X * 
X * 1. General remarks.
X * 
X *   Mined is a screen editor designed for the MINIX operating system.
X *   It is meant to be used on files not larger than 50K and to be fast.
X *   When mined starts up, it reads the file into its memory to minimize
X *   disk access. The only time that disk access is needed is when certain
X *   save, write or copy commands are given.
X * 
X *   Mined has the style of Emacs or Jove, that means that there are no modes.
X *   Each character has its own entry in an 256 pointer to function array,
X *   which is called when that character is typed. Only ASCII characters are
X *   connected with a function that inserts that character at the current
X *   location in the file. Two execptions are <linefeed> and <tab> which are
X *   inserted as well. Note that the mapping between commands and functions
X *   called is implicit in the table. Changing the mapping just implies
X *   changing the pointers in this table.
X * 
X *   The display consists of SCREENMAX + 1 lines and XMAX + 1 characters. When
X *   a line is larger (or gets larger during editing) than XBREAK characters,
X *   the line is either shifted SHIFT_SIZE characters to the left (which means
X *   that the first SHIFT_SIZE characters are not printed) or the end of the
X *   line is marked with the SHIFT_MARK character and the rest of the line is
X *   not printed.  A line can never exceed MAX_CHARS characters. Mined will
X *   always try to keep the cursor on the same line and same (relative)
X *   x-coordinate if nothing changed. So if you scroll one line up, the cursor
X *   stays on the same line, or when you move one line down, the cursor will
X *   move to the same place on the line as it was on the previous.
X *   Every character on the line is available for editing including the
X *   linefeed at the the of the line. When the linefeed is deleted, the current
X *   line and the next line are joined. The last character of the file (which
X *   is always a linefeed) can never be deleted.
X *   The bottomline (as indicated by YMAX + 1) is used as a status line during
X *   editing. This line is usually blank or contains information mined needs
X *   during editing. This information (or rather questions) is displayed in
X *   reverse video.
X * 
X *   The terminal modes are changed completely. All signals like start/stop,
X *   interrupt etc. are unset. The only signal that remains is the quit signal.
X *   The quit signal (^\) is the general abort signal for mined. Typing a ^\
X *   during searching or when mined is asking for filenames, etc. will abort
X *   the function and mined will return to the main loop.  Sending a quit
X *   signal during the main loop will abort the session (after confirmation)
X *   and the file is not (!) saved.
X *   The session will also be aborted when an unrecoverable error occurs. E.g
X *   when there is no more memory available. If the file has been modified,
X *   mined will ask if the file has to be saved or not.
X *   If there is no more space left on the disk, mined will just give an error 
X *   message and continue.
X * 
X *   The number of system calls are minized. This is done to keep the editor
X *   as fast as possible. I/O is done in SCREEN_SIZE reads/writes. Accumulated
X *   output is also flushed at the end of each character typed.
X * 
X * 2. Regular expressions
X *   
X *   Mined has a build in regular expression matcher, which is used for
X *   searching and replace routines. A regular expression consists of a
X *   sequence of:
X * 
X *      1. A normal character matching that character.
X *      2. A . matching any character.
X *      3. A ^ matching the begin of a line.
X *      4. A $ (as last character of the pattern) mathing the end of a line.
X *      5. A \<character> matching <character>.
X *      6. A number of characters enclosed in [] pairs matching any of these
X *        characters. A list of characters can be indicated by a '-'. So
X *        [a-z] matches any letter of the alphabet. If the first character
X *        after the '[' is a '^' then the set is negated (matching none of
X *        the characters). 
X *        A ']', '^' or '-' can be escaped by putting a '\' in front of it.
X *        Of course this means that a \ must be represented by \\.
X *      7. If one of the expressions as described in 1-6 is followed by a
X *        '*' than that expressions matches a sequence of 0 or more of
X *        that expression.
X * 
X *   Parsing of regular expression is done in two phases. In the first phase
X *   the expression is compiled into a more comprehensible form. In the second
X *   phase the actual matching is done. For more details see 3.6.
X * 
X * 
X * 3. Implementation of mined.
X * 
X *   3.1 Data structures.
X * 
X *      The main data structures are as follows. The whole file is kept in a
X *      double linked list of lines. The LINE structure looks like this:
X * 
X *         typedef struct Line {
X *              struct Line *next;
X *              struct Line *prev;
X *              char *text;
X *              unsigned char shift_count;
X *         } LINE;
X * 
X *      Each line entry contains a pointer to the next line, a pointer to the
X *      previous line and a pointer to the text of that line. A special field
X *      shift_count contains the number of shifts (in units of SHIFT_SIZE)
X *      that is performed on that line. The total size of the structure is 7
X *      bytes so a file consisting of 1000 empty lines will waste a lot of
X *      memory. A LINE structure is allocated for each line in the file. After
X *      that the number of characters of the line is counted and sufficient
X *      space is allocated to store them (including a linefeed and a '\0').
X *      The resulting address is assigned to the text field in the structure.
X * 
X *      A special structure is allocated and its address is assigned to the
X *      variable header as well as the variable tail. The text field of this
X *      structure is set to NIL_PTR. The tail->prev of this structure points
X *      to the last LINE of the file and the header->next to the first LINE.
X *      Other LINE *variables are top_line and bot_line which point to the
X *      first line resp. the last line on the screen.
X *      Two other variables are important as well. First the LINE *cur_line,
X *      which points to the LINE currently in use and the char *cur_text,
X *      which points to the character at which the cursor stands.
X *      Whenever an ASCII character is typed, a new line is build with this
X *      character inserted. Then the old data space (pointed to by
X *      cur_line->text) is freed, data space for the new line is allocated and
X *      assigned to cur_line->text.
X * 
X *      Two global variables called x and y represent the x and y coordinates
X *      from the cursor. The global variable nlines contains the number of
X *      lines in the file. Last_y indicates the maximum y coordinate of the
X *      screen (which is usually SCREENMAX).
X * 
X *      A few strings must be initialized by hand before compiling mined.
X *      These string are enter_string, which is printed upon entering mined,
X *      rev_video (turn on reverse video), normal_video, rev_scroll (perform a
X *      reverse scroll) and pos_string. The last string should hold the
X *      absolute position string to be printed for cursor motion. The #define
X *      X_PLUS and Y_PLUS should contain the characters to be added to the
X *      coordinates x and y (both starting at 0) to finish cursor positioning.
X * 
X *   3.2 Starting up.
X *      
X *      Mined can be called with or without argument and the function
X *      load_file () is called with these arguments. load_file () checks
X *      if the file exists if it can be read and if it is writable and
X *      sets the writable flag accordingly. If the file can be read, 
X *      load_file () reads a line from the file and stores this line into
X *      a structure by calling install_line () and line_insert () which
X *      installs the line into the double linked list, until the end of the
X *      file is reached.
X *      Lines are read by the function get_line (), which buffers the
X *      reading in blocks of SCREEN_SIZE. Load_file () also initializes the
X *      LINE *variables described above.
X * 
X *   3.3 Moving around.
X * 
X *      Several commands are implemented for moving through the file.
X *      Moving up (UP), down (DN) left (LF) and right (RT) are done by the
X *      arrow keys. Moving one line below the screen scrolls the screen one
X *      line up. Moving one line above the screen scrolls the screen one line
X *      down. The functions forward_scroll () and reverse_scroll () take care
X *      of that.
X *      Several other move functions exist: move to begin of line (BL), end of
X *      line (EL) top of screen (HIGH), bottom of screen (LOW), top of file
X *      (HO), end of file (EF), scroll one page down (PD), scroll one page up
X *      (PU), scroll one line down (SD), scroll one line up (SU) and move to a
X *      certain line number (GOTO).
X *      Two functions called MN () and MP () each move one word further or 
X *      backwards. A word is a number of non-blanks seperated by a space, a
X *      tab or a linefeed.
X * 
X *   3.4 Modifying text.
X * 
X *      The modifying commands can be separated into two modes. The first
X *      being inserting text, and the other deleting text. Two functions are
X *      created for these purposes: insert () and delete (). Both are capable
X *      of deleting or inserting large amounts of text as well as one
X *      character. Insert () must be given the line and location at which
X *      the text must be inserted. Is doesn't make any difference whether this
X *      text contains linefeeds or not. Delete () must be given a pointer to
X *      the start line, a pointer from where deleting should start on that
X *      line and the same information about the end position. The last
X *      character of the file will never be deleted. Delete () will make the
X *      necessary changes to the screen after deleting, but insert () won't.
X *      The functions for modifying text are: insert one char (S), insert a
X *      file (file_insert (fd)), insert a linefeed and put cursor back to
X *      end of line (LIB), delete character under the cursor (DCC), delete
X *      before cursor (even linefeed) (DPC), delete next word (DNW), delete
X *      previous word (DPC) and delete to end of line (if the cursor is at
X *      a linefeed delete line) (DLN).
X * 
X *   3.5 Yanking.
X * 
X *      A few utilities are provided for yanking pieces of text. The function
X *      MA () marks the current position in the file. This is done by setting 
X *      LINE *mark_line and char *mark_text to the current position. Yanking
X *      of text can be done in two modes. The first mode just copies the text
X *      from the mark to the current position (or visa versa) into a buffer
X *      (YA) and the second also deletes the text (DT). Both functions call
X *      the function set_up () with the delete flag on or off. Set_up ()
X *      checks if the marked position is still a valid one (by using
X *      check_mark () and legal ()), and then calls the function yank () with
X *      a start and end position in the file. This function copies the text
X *      into a scratch_file as indicated by the variable yank_file. This
X *      scratch_file is made uniq by the function scratch_file (). At the end
X *      of copying yank will (if necessary) delete the text. A global flag
X *      called yank_status keeps track of the buffer (or file) status. It is
X *      initialized on NOT_VALID and set to EMPTY (by set_up ()) or VALID (by
X *      yank ()). Several things can be done with the buffer. It can be
X *      inserted somewhere else in the file (PT) or it can be copied into
X *      another file (WB), which will be prompted for.
X * 
X *   3.6 Search and replace routines.
X * 
X *      Searching for strings and replacing strings are done by regular
X *      expressions. For any expression the function compile () is called
X *      with as argument the expression to compile. Compile () returns a
X *      pointer to a structure which looks like this:
X * 
X *         typedef struct regex {
X *              union {
X *                    char *err_mess;
X *                    int *expression;
X *              } result;
X *              char status;
X *              char *start_ptr;
X *              char *end_ptr;
X *         } REGEX;
X *      
X *    If something went wrong during compiling (e.g. an illegal expression
X *    was given), the function reg_error () is called, which sets the status
X *    field to REG_ERROR and the err_mess field to the error message. If the
X *    match must be anchored at the beginning of the line (end of line), the
X *    status field is set to BEGIN_LINE (END_LINE). If none of these special
X *    cases are true, the field is set to 0 and the function finished () is
X *    called.  Finished () allocates space to hold the compiled expression
X *    and copies this expression into the expression field of the union
X *    (bcopy ()). Matching is done by the routines match() and line_check().
X *    Match () takes as argument the REGEX *program, a pointer to the
X *    startposition on the current line, and a flag indicating FORWARD or
X *    REVERSE search.  Match () checks out the whole file until a match is
X *    found. If match is found it returns a pointer to the line in which the
X *    match was found else it returns a NIL_LINE. Line_check () takes the
X *    same arguments, but return either MATCH or NO_MATCH.
X *    During checking, the start_ptr and end_ptr fields of the REGEX
X *    structure are assigned to the start and end of the match. 
X *    Both functions try to find a match by walking through the line
X *    character by character. For each possibility, the function
X *    check_string () is called with as arguments the REGEX *program and the
X *    string to search in. It starts walking through the expression until
X *    the end of the expression or the end of the string is reached.
X *    Whenever a * is encountered, this position of the string is marked,
X *    the maximum number of matches are performed and the function star ()
X *    is called in order to try to find the longest match possible. Star ()
X *    takes as arguments the REGEX program, the current position of the
X *    string, the marked position and the current position of the expression
X *    Star () walks from the current position of the string back to the
X *    marked position, and calls string_check () in order to find a match.
X *    It returns MATCH or NO_MATCH, just as string_check () does.
X *    Searching is now easy. Both search routines (forward (SF) and
X *    backwards search (SR)) call search () with an apropiate message and a
X *    flag indicating FORWARD or REVERSE search. Search () will get an
X *    expression from the user by calling get_expression(). Get_expression()
X *    returns a pointer to a REGEX structure or NIL_REG upon errors and
X *    prompts for the expression. If no expression if given, the previous is
X *    used instead. After that search will call match (), and if a match is
X *    found, we can move to that place in the file by the functions find_x()
X *    and find_y () which will find display the match on the screen.
X *    Replacing can be done in two ways. A global replace (GR) or a line
X *    replace (LR). Both functions call change () with a message an a flag
X *    indicating global or line replacement. Change () will prompt for the
X *    expression and for the replacement. Every & in the replacement pattern
X *    means substitute the match instead. An & can be escaped by a \. When
X *    a match is found, the function substitute () will perform the
X *    substitution.
X * 
X *  3.6 Miscellaneous commands.
X * 
X *    A few commands haven't be discussed yet. These are redraw the screen
X *    (RD) fork a shell (SH), print file status (FS), write file to disc
X *    (WT), insert a file at current position (IF), leave editor (XT) and
X *    visit another file (VI). The last two functions will check if the file
X *    has been modified. If it has, they will ask if you want to save the
X *    file by calling ask_save ().
X *    The function ESC () will repeat a command n times. It will prompt for
X *    the number. Aborting the loop can be done by sending the ^\ signal.
X * 
X *  3.7 Utility functions.
X * 
X *    Several functions exists for internal use. First allocation routines:
X *    alloc (bytes) and newline () will return a pointer to free data space
X *    if the given size. If there is no more memory available, the function
X *    panic () is called.
X *    Signal handling: The only signal that can be send to mined is the 
X *    SIGQUIT signal. This signal, functions as a general abort command.
X *    Mined will abort if the signal is given during the main loop. The 
X *    function abort_mined () takes care of that.
X *    Panic () is a function with as argument a error message. It will print
X *    the message and the error number set by the kernel (errno) and will
X *    ask if the file must be saved or not. It resets the terminal
X *    (raw_mode ()) and exits.
X *    String handling routines like copy_string(to, from), length_of(string)
X *    and build_string (buffer, format, arg1, arg2, ...). The latter takes
X *    a description of the string out out the format field and puts the
X *    result in the buffer. (It works like printf (3), but then into a
X *    string). The functions status_line (string1, string2), error (string1,
X *    string2), clear_status () and bottom_line () all print information on
X *    the status line.
X *    Get_string (message, buffer) reads a string and getchar () reads one
X *    character from the terminal.
X *    Num_out ((long) number) prints the number into a 11 digit field
X *    without leading zero's. It returns a pointer to the resulting string.
X *    File_status () prints all file information on the status line.
X *    Set_cursor (x, y) prints the string to put the cursor at coordinates
X *    x and y.
X *    Output is done by four functions: writeline(fd,string), clear_buffer()
X *    write_char (fd, c) and flush_buffer (fd). Three defines are provided
X *    to write on filedescriptor STD_OUT (terminal) which is used normally:
X *    string_print (string), putchar (c) and flush (). All these functions
X *    use the global I/O buffer screen and the global index for this array
X *    called out_count. In this way I/O can be buffered, so that reads or
X *    writes can be done in blocks of SCREEN_SIZE size.
X *    The following functions all handle internal line maintenance. The
X *    function proceed (start_line, count) returns the count'th line after
X *    start_line.  If count is negative, the count'th line before the
X *    start_line is returned. If header or tail is encountered then that
X *    will be returned. Display (x, y, start_line, count) displays count
X *    lines starting at coordinates [x, y] and beginning at start_line. If
X *    the header or tail is encountered, empty lines are displayed instead.
X *    The function reset (head_line, ny) reset top_line, last_y, bot_line,
X *    cur_line and y-coordinate. This is not a neat way to do the
X *    maintenance, but it sure saves a lot of code. It is usually used in
X *    combination with display ().
X *    Put_line(line, offset, clear_line), prints a line (skipping characters
X *    according to the line->shift_size field) until XBREAK - offset
X *    characters are printed or a '\n' is encountered. If clear_line is
X *	  TRUE, spaces are printed until XBREAK - offset characters.
X *	  Line_print (line) is a #define from put_line (line, 0, TRUE).
X *    Moving is done by the functions move_to (x, y), move_addres (address)
X *    and move (x, adress, y). This function is the most important one in
X *    mined. New_y must be between 0 and last_y, new_x can be about
X *    anything, address must be a pointer to an character on the current
X *    line (or y). Move_to () first adjust the y coordinate together with
X *    cur_line. If an address is given, it finds the corresponding
X *    x-coordinate. If an new x-coordinate was given, it will try to locate
X *    the corresponding character. After that it sets the shift_count field
X *    of cur_line to an apropiate number according to new_x. The only thing
X *    left to do now is to assign the new values to cur_line, cur_text, x
X *    and y.
X * 
X * 4. Summary of commands.
X *  
X *  CURSOR MOTION
X *    up-arrow  Move cursor 1 line up.  At top of screen, reverse scroll
X *    down-arrow  Move cursor 1 line down.  At bottom, scroll forward.
X *    left-arrow  Move cursor 1 character left or to end of previous line
X *    right-arrow Move cursor 1 character right or to start of next line
X *    CTRL-A   Move cursor to start of current line
X *    CTRL-Z   Move cursor to end of current line
X *    CTRL-^   Move cursor to top of screen
X *    CTRL-_   Move cursor to bottom of screen
X *    CTRL-F   Forward to start of next word (even to next line)
X *    CTRL-B   Backward to first character of previous word
X *   
X *  SCREEN MOTION
X *    Home key  Move cursor to first character of file
X *    End key   Move cursor to last character of file
X *    PgUp    Scroll backward 1 page. Bottom line becomes top line
X *    PgD    Scroll backward 1 page. Top line becomes bottom line
X *    CTRL-D   Scroll screen down one line (reverse scroll)
X *    CTRL-U   Scroll screen up one line (forward scroll)
X *   
X *  MODIFYING TEXT
X *    ASCII char  Self insert character at cursor
X *    tab    Insert tab at cursor
X *    backspace  Delete the previous char (left of cursor), even line feed
X *    Del    Delete the character under the cursor
X *    CTRL-N   Delete next word
X *    CTRL-P   Delete previous word
X *    CTRL-O   Insert line feed at cursor and back up 1 character
X *    CTRL-T   Delete tail of line (cursor to end); if empty, delete line
X *    CTRL-@   Set the mark (remember the current location)
X *    CTRL-K   Delete text from the mark to current position save on file
X *    CTRL-C   Save the text from the mark to the current position
X *    CTRL-Y   Insert the contents of the save file at current position
X *    CTRL-Q   Insert the contents of the save file into a new file
X *    CTRL-G   Insert a file at the current position
X *   
X *  MISCELLANEOUS
X *    CTRL-E   Erase and redraw the screen
X *    CTRL-V   Visit file (read a new file); complain if old one changed
X *    CTRL-W   Write the current file back to the disk
X *    numeric +  Search forward (prompt for regular expression)
X *    numeric -  Search backward (prompt for regular expression)
X *    numeric 5  Print the current status of the file
X *    CTRL-R   (Global) Replace str1 by str2 (prompts for each string)
X *    CTRL-L   (Line) Replace string1 by string2
X *    CTRL-S   Fork off a shell and wait for it to finish
X *    CTRL-X   EXIT (prompt if file modified)
X *    CTRL-]   Go to a line. Prompts for linenumber
X *    CTRL-\   Abort whatever editor was doing and start again
X *    escape key  Repeat a command count times; (prompts for count)
X */
X
X/*  ========================================================================  *
X *				Utilities				      *	
X *  ========================================================================  */
X
X#include "mined.h"
X#include <signal.h>
X#include <sgtty.h>
X#include <limits.h>
X#include <errno.h>
X#include <sys/wait.h>
X
Xextern int errno;
Xint ymax = YMAX;
Xint screenmax = SCREENMAX;
X
X
X/*
X * Print file status.
X */
Xvoid FS()
X{
X  fstatus(file_name[0] ? "" : "[buffer]", -1L);
X}
X
X/*
X * Visit (edit) another file. If the file has been modified, ask the user if
X * he wants to save it.
X */
Xvoid VI()
X{
X  char new_file[LINE_LEN];	/* Buffer to hold new file name */
X
X  if (modified == TRUE && ask_save() == ERRORS)
X  	return;
X  
X/* Get new file name */
X  if (get_file("Visit file:", new_file) == ERRORS)
X  	return;
X
X/* Free old linked list, initialize global variables and load new file */
X  initialize();
X#ifdef UNIX
X  tputs(CL, 0, _putchar);
X#else
X  string_print (enter_string);
X#endif /* UNIX */
X  load_file(new_file[0] == '\0' ? NIL_PTR : new_file);
X}
X
X/*
X * Write file in core to disc.
X */
Xint WT()
X{
X  register LINE *line;
X  register long count = 0L;	/* Nr of chars written */
X  char file[LINE_LEN];		/* Buffer for new file name */
X  int fd;				/* Filedescriptor of file */
X
X  if (modified == FALSE) {
X	error ("Write not necessary.", NIL_PTR);
X	return FINE;
X  }
X
X/* Check if file_name is valid and if file can be written */
X  if (file_name[0] == '\0' || writable == FALSE) {
X  	if (get_file("Enter file name:", file) != FINE)
X  		return ERRORS;
X  	copy_string(file_name, file);		/* Save file name */
X  }
X  if ((fd = creat(file_name, 0644)) < 0) {	/* Empty file */
X  	error("Cannot create ", file_name);
X  	writable = FALSE;
X  	return ERRORS;
X  }
X  else
X  	writable = TRUE;
X
X  clear_buffer();
X
X  status_line("Writing ", file_name);
X  for (line = header->next; line != tail; line = line->next) {
X	if (line->shift_count & DUMMY) {
X		if (line->next == tail && line->text[0] == '\n')
X			continue;
X	}
X  	if (writeline(fd, line->text) == ERRORS) {
X  		count = -1L;
X  		break;
X  	}
X  	count += (long) length_of(line->text);
X  }
X
X  if (count > 0L && flush_buffer(fd) == ERRORS)
X  	count = -1L;
X
X  (void) close(fd);
X
X  if (count == -1L)
X  	return ERRORS;
X
X  modified = FALSE;
X  rpipe = FALSE;		/* File name is now assigned */
X
X/* Display how many chars (and lines) were written */
X  fstatus("Wrote", count);
X  return FINE;
X}
X
X/* Call WT and discard value returned. */
Xvoid XWT()
X{
X  (void) WT();
X}
X
X
X
X/*
X * Call an interactive shell.
X */
Xvoid SH()
X{
X  register int w;
X  int pid, status;
X
X  switch (pid = fork()) {
X  	case -1:			/* Error */
X  		error("Cannot fork.", NIL_PTR);
X  		return;
X  	case 0:				/* This is the child */
X  		set_cursor(0, ymax);
X  		putchar('\n');
X  		flush();
X  		raw_mode(OFF);
X		if (rpipe) {			/* Fix stdin */
X			close (0);
X			if (open("/dev/tty", 0) < 0)
X				exit (126);
X		}
X  		execl("/bin/sh", "sh", "-i", (char *) 0);
X  		exit(127);			/* Exit with 127 */
X  	default :				/* This is the parent */
X  		signal(SIGINT, SIG_IGN);
X  		signal(SIGQUIT, SIG_IGN);
X  		do {
X  			w = wait(&status);
X  		} while (w != -1 && w != pid);
X  }
X
X  raw_mode(ON);
X  RD();
X
X  if ((status >> 8) == 127)		/* Child died with 127 */
X  	error("Cannot exec /bin/sh (possibly not enough memory)", NIL_PTR);
X  else if ((status >> 8) == 126)
X  	error("Cannot open /dev/tty as fd #0", NIL_PTR);
X}
X
X/*
X * Proceed returns the count'th line after `line'. When count is negative
X * it returns the count'th line before `line'. When the next (previous)
X * line is the tail (header) indicating EOF (tof) it stops.
X */
XLINE *proceed(line, count)
Xregister LINE *line;
Xregister int count;
X{
X  if (count < 0)
X  	while (count++ < 0 && line != header)
X  		line = line->prev;
X  else
X  	while (count-- > 0 && line != tail)
X  		line = line->next;
X  return line;
X}
X
X/*
X * Show concatenation of s1 and s2 on the status line (bottom of screen)
X * If revfl is TRUE, turn on reverse video on both strings. Set stat_visible
X * only if bottom_line is visible.
X */
Xint bottom_line(revfl, s1, s2, inbuf, statfl)
XFLAG revfl;
Xchar *s1, *s2;
Xchar *inbuf;
XFLAG statfl;
X{
X  int ret = FINE;
X  char buf[LINE_LEN];
X  register char *p = buf;
X
X  *p++ = ' ';
X  if (s1 != NIL_PTR)
X	while (*p = *s1++)
X		p++;
X  if (s2 != NIL_PTR)
X	while (*p = *s2++)
X		p++;
X  *p++ = ' ';
X  *p++ = 0;
X
X  if (revfl == ON && stat_visible == TRUE)
X	clear_status ();
X  set_cursor(0, ymax);
X  if (revfl == ON) {		/* Print rev. start sequence */
X#ifdef UNIX
X  	tputs(SO, 0, _putchar);
X#else
X  	string_print(rev_video);
X#endif /* UNIX */
X  	stat_visible = TRUE;
X  }
X  else				/* Used as clear_status() */
X  	stat_visible = FALSE;
X
X  string_print(buf);
X  
X  if (inbuf != NIL_PTR)
X  	ret = input(inbuf, statfl);
X
X  /* Print normal video */
X#ifdef UNIX
X  tputs(SE, 0, _putchar);
X  tputs(CE, 0, _putchar);
X#else
X  string_print(normal_video);
X  string_print(blank_line);	/* Clear the rest of the line */
X#endif /* UNIX */
X  if (inbuf != NIL_PTR)
X  	set_cursor(0, ymax);
X  else
X  	set_cursor(x, y);	/* Set cursor back to old position */
X  flush();			/* Perform the actual write */
X  if (ret != FINE)
X  	clear_status();
X  return ret;
X}
X
X/*
X * Count_chars() count the number of chars that the line would occupy on the
X * screen. Counting starts at the real x-coordinate of the line.
X */
Xint count_chars(line)
XLINE *line;
X{
X  register int cnt = get_shift(line->shift_count) * -SHIFT_SIZE;
X  register char *textp = line->text;
X
X/* Find begin of line on screen */
X  while (cnt < 0) {
X  	if (is_tab(*textp++))
X  		cnt = tab(cnt);
X  	else
X  		cnt++;
X  }
X
X/* Count number of chars left */
X  cnt = 0;
X  while (*textp != '\n') {
X  	if (is_tab(*textp++))
X  		 cnt = tab(cnt);
X  	else
X  		cnt++;
X  }
X  return cnt;
X}
X
X/*
X * Move to coordinates nx, ny at screen.  The caller must check that scrolling
X * is not needed.
X * If new_x is lower than 0 or higher than XBREAK, move_to() will check if
X * the line can be shifted. If it can it sets(or resets) the shift_count field
X * of the current line accordingly.
X * Move also sets cur_text to the right char.
X * If we're moving to the same x coordinate, try to move the the x-coordinate
X * used on the other previous call.
X */
Xvoid move(new_x, new_address, new_y)
Xregister int new_x;
Xint new_y;
Xchar *new_address;
X{
X  register LINE *line = cur_line;	/* For building new cur_line */
X  int shift = 0;			/* How many shifts to make */
X  static int rel_x = 0;		/* Remember relative x position */
X  int tx = x;
X
X/* Check for illegal values */
X  if (new_y < 0 || new_y > last_y)
X  	return;
X
X/* Adjust y-coordinate and cur_line */
X  if (new_y < y)
X  	while (y != new_y) {
X  		y--;
X  		line = line->prev;
X  	}
X  else
X  	while (y != new_y) {
X  		y++;
X  		line = line->next;
X  	}
X
X/* Set or unset relative x-coordinate */
X  if (new_address == NIL_PTR) {
X  	new_address = find_address(line, (new_x == x) ? rel_x : new_x , &tx);
X	if (new_x != x)
X		rel_x = tx;
X  	new_x = tx;
X  }
X  else
X  	rel_x = new_x = find_x(line, new_address);
X
X/* Adjust shift_count if new_x lower than 0 or higher than XBREAK */
X  if (new_x < 0 || new_x >= XBREAK) {
X  	if (new_x > XBREAK || (new_x == XBREAK && *new_address != '\n'))
X  		shift = (new_x - XBREAK) / SHIFT_SIZE + 1;
X  	else {
X  		shift = new_x / SHIFT_SIZE;
X		if (new_x % SHIFT_SIZE)
X			shift--;
X  	}
X
X  	if (shift != 0) {
X  		line->shift_count += shift;
X  		new_x = find_x(line, new_address);
X  		set_cursor(0, y);
X  		line_print(line);
X  		rel_x = new_x;
X  	}
X  }
X
X/* Assign and position cursor */
X  x = new_x;
X  cur_text = new_address;
X  cur_line = line;
X  set_cursor(x, y);
X}
X
X/*
X * Find_x() returns the x coordinate belonging to address.
X * (Tabs are expanded).
X */
Xint find_x(line, address)
XLINE *line;
Xchar *address;
X{
X  register char *textp = line->text;
X  register int nx = get_shift(line->shift_count) * -SHIFT_SIZE;
X
X  while (textp != address && *textp != '\0') {
X  	if (is_tab(*textp++)) 	/* Expand tabs */
X  		nx = tab(nx);
X  	else
X  		nx++;
X  }
X  return nx;
X}
X
X/*
X * Find_address() returns the pointer in the line with offset x_coord.
X * (Tabs are expanded).
X */
Xchar *find_address(line, x_coord, old_x)
XLINE *line;
Xint x_coord;
Xint *old_x;
X{
X  register char *textp = line->text;
X  register int tx = get_shift(line->shift_count) * -SHIFT_SIZE;
X
X  while (tx < x_coord && *textp != '\n') {
X  	if (is_tab(*textp)) {
X  		if (*old_x - x_coord == 1 && tab(tx) > x_coord)
X  			break;		/* Moving left over tab */
X  		else
X  			tx = tab(tx);
X  	}
X  	else
X  		tx++;
X  	textp++;
X  }
X  
X  *old_x = tx;
X  return textp;
X}
X
X/*
X * Length_of() returns the number of characters int the string `string'
X * excluding the '\0'.
X */
Xint length_of(string)
Xregister char *string;
X{
X  register int count = 0;
X
X  if (string != NIL_PTR) {
X  	while (*string++ != '\0')
X  		count++;
X  }
X  return count;
X}
X
X/*
X * Copy_string() copies the string `from' into the string `to'. `To' must be
X * long enough to hold `from'.
X */
Xvoid copy_string(to, from)
Xregister char *to;
Xregister char *from;
X{
X  while (*to++ = *from++)
X  	;
X}
X
X/*
X * Reset assigns bot_line, top_line and cur_line according to `head_line'
X * which must be the first line of the screen, and an y-coordinate,
X * which will be the current y-coordinate (if it isn't larger than last_y)
X */
Xvoid reset(head_line, screen_y)
XLINE *head_line;
Xint screen_y;
X{
X  register LINE *line;
X
X  top_line = line = head_line;
X
X/* Search for bot_line (might be last line in file) */
X  for (last_y = 0; last_y < nlines - 1 && last_y < screenmax
X						&& line->next != tail; last_y++)
X  	line = line->next;
X
X  bot_line = line;
X  y = (screen_y > last_y) ? last_y : screen_y;
X
X/* Set cur_line according to the new y value */
X  cur_line = proceed(top_line, y);
X}
X
X/*
X * Set cursor at coordinates x, y.
X */
Xvoid set_cursor(nx, ny)
Xint nx, ny;
X{
X#ifdef UNIX
X  extern char *tgoto();
X
X  tputs(tgoto(CM, nx, ny), 0, _putchar);
X#else
X  char text_buffer[10];
X
X  build_string(text_buffer, pos_string, ny+1, nx+1);
X  string_print(text_buffer);
X#endif /* UNIX */
X}
X
X/*
X * Routine to open terminal when mined is used in a pipeline.
X */
Xvoid open_device()
X{
X  if ((input_fd = open("/dev/tty", 0)) < 0)
X	panic("Cannot open /dev/tty for read");
X}
X
X/*
X * Getchar() reads one character from the terminal. The character must be
X * masked with 0377 to avoid sign extension.
X */
Xint getchar()
X{
X#ifdef UNIX
X  return (_getchar() & 0177);
X#else
X  char c;
X
X  if (read(input_fd, &c, 1) != 1 && quit == FALSE)
X  	panic("Can't read one char from fd #0");
X
X  return c & 0377;
X#endif /* UNIX */
X}
X
X/*
X * Display() shows count lines on the terminal starting at the given
X * coordinates. When the tail of the list is encountered it will fill the
X * rest of the screen with blank_line's.
X * When count is negative, a backwards print from `line' will be done.
X */
Xvoid display(x_coord, y_coord, line, count)
Xint x_coord, y_coord;
Xregister LINE *line;
Xregister int count;
X{
X  set_cursor(x_coord, y_coord);
X
X/* Find new startline if count is negative */
X  if (count < 0) {
X  	line = proceed(line, count);
X  	count = -count;
X  }
X
X/* Print the lines */
X  while (line != tail && count-- >= 0) {
X  	line_print(line);
X  	line = line->next;
X  }
X
X/* Print the blank lines (if any) */
X  if (loading == FALSE) {
X	while (count-- >= 0) {
X#ifdef UNIX
X		tputs(CE, 0, _putchar);
X#else
X		string_print(blank_line);
X#endif /* UNIX */
X		putchar('\n');
X	}
X  }
X}
X
X/*
X * Write_char does a buffered output. 
X */
Xint write_char(fd, c)
Xint fd;
Xchar c;
X{
X  screen [out_count++] = c;
X  if (out_count == SCREEN_SIZE)		/* Flush on SCREEN_SIZE chars */
X  	return flush_buffer(fd);
X  return FINE;
X}
X
X/*
X * Writeline writes the given string on the given filedescriptor.
X */
Xint writeline(fd, text)
Xregister int fd;
Xregister char *text;
X{
X  while(*text)
X  	 if (write_char(fd, *text++) == ERRORS)
X  		return ERRORS;
X  return FINE;
X}
X
X/*
X * Put_line print the given line on the standard output. If offset is not zero
X * printing will start at that x-coordinate. If the FLAG clear_line is TRUE,
X * then (screen) line will be cleared when the end of the line has been
X * reached.
X */
Xvoid put_line(line, offset, clear_line)
XLINE *line;				/* Line to print */
Xint offset;				/* Offset to start */
XFLAG clear_line;			/* Clear to eoln if TRUE */
X{
X  register char *textp = line->text;
X  register int count = get_shift(line->shift_count) * -SHIFT_SIZE;
X  int tab_count;			/* Used in tab expansion */
X
X/* Skip all chars as indicated by the offset and the shift_count field */
X  while (count < offset) {
X  	if (is_tab(*textp++))
X  		count = tab(count);
X  	else
X  		count++;
X  }
X
X  while (*textp != '\n' && count < XBREAK) {
X  	if (is_tab(*textp)) {		/* Expand tabs to spaces */
X  		tab_count = tab(count);
X  		while (count < XBREAK && count < tab_count) {
X  			count++;
X  			putchar(' ');
X  		}
X  		textp++;
X  	}
X  	else {
X		if (*textp >= '\01' && *textp <= '\037') {
X#ifdef UNIX
X			tputs(SO, 0, _putchar);
X#else
X			string_print (rev_video);
X#endif /* UNIX */
X  			putchar(*textp++ + '\100');
X#ifdef UNIX
X			tputs(SE, 0, _putchar);
X#else
X			string_print (normal_video);
X#endif /* UNIX */
X		}
X		else
X  			putchar(*textp++);
X  		count++;
X  	}
X  }
X
X/* If line is longer than XBREAK chars, print the shift_mark */
X  if (count == XBREAK && *textp != '\n')
X  	putchar(textp[1]=='\n' ? *textp : SHIFT_MARK);
X
X/* Clear the rest of the line is clear_line is TRUE */
X  if (clear_line == TRUE) {
X#ifdef	UNIX
X  	tputs(CE, 0, _putchar);
X#else
X	string_print(blank_line);
X#endif /* UNIX */
X  	putchar('\n');
X  }
X}
X
X/*
X * Flush the I/O buffer on filedescriptor fd.
X */
Xint flush_buffer(fd)
Xint fd;
X{
X  if (out_count <= 0)		/* There is nothing to flush */
X  	return FINE;
X#ifdef UNIX
X  if (fd == STD_OUT) {
X  	printf("%.*s", out_count, screen);
X  	_flush();
X  }
X  else
X#endif /* UNIX */
X  if (write(fd, screen, out_count) != out_count) {
X  	bad_write(fd);
X  	return ERRORS;
X  }
X  clear_buffer();		/* Empty buffer */
X  return FINE;
X}
X
X/*
X * Bad_write() is called when a write failed. Notify the user.
X */
Xvoid bad_write(fd)
Xint fd;
X{
X  if (fd == STD_OUT)		/* Cannot write to terminal? */
X  	exit(1);
X  
X  clear_buffer();
X  build_string(text_buffer, "Command aborted: %s (File incomplete)",
X  		            (errno == ENOSPC || errno == -ENOSPC) ?
X  			    "No space on device" : "Write error");
X  error(text_buffer, NIL_PTR);
X}
X
X/*
X * Catch the SIGQUIT signal (^\) send to mined. It turns on the quitflag.
X */
Xvoid catch(sig)
Xint sig;
X{
X/* Reset the signal */
X  signal(SIGQUIT, catch);
X  quit = TRUE;
X}
X
X/*
X * Abort_mined() will leave mined. Confirmation is asked first.
X */
Xvoid abort_mined()
X{
X  quit = FALSE;
X
X/* Ask for confirmation */
X  status_line("Really abort? ", NIL_PTR);
X  if (getchar() != 'y') {
X  	clear_status();
X  	return;
X  }
X
X/* Reset terminal */
X  raw_mode(OFF);
X  set_cursor(0, ymax);
X  putchar('\n');
X  flush();
X#ifdef UNIX
X  abort();
X#else
X  exit(1);
X#endif /* UNIX */
X}
X
X#define UNDEF	-1
X
X/*
X * Set and reset tty into CBREAK or old mode according to argument `state'. It
X * also sets all signal characters (except for ^\) to UNDEF. ^\ is caught.
X */
Xvoid raw_mode(state)
XFLAG state;
X{
X  static struct sgttyb old_tty;
X  static struct sgttyb new_tty;
X  static struct tchars old_tchars;
X  static struct tchars new_tchars = {UNDEF, '\034', UNDEF, UNDEF, UNDEF, UNDEF};
X#ifdef NTTYDISC
X  int ldisc;
X#endif /* NTTYDISC */
X
X  if (state == OFF) {
X  	ioctl(input_fd, TIOCSETP, &old_tty);
X  	ioctl(input_fd, TIOCSETC, (struct sgttyb *) &old_tchars);
X#ifdef NTTYDISC
X  	ldisc = NTTYDISC;
X  	ioctl(input_fd, TIOCSETD, &ldisc);
X#endif /* NTTYDISC */
X  	return;
X  }
X
X/* Save old tty settings */
X  ioctl(input_fd, TIOCGETC, (struct sgttyb *) &old_tchars);
X  ioctl(input_fd, TIOCGETP, &old_tty);
X
X#ifdef NTTYDISC
X  ldisc = OTTYDISC;
X  ioctl(input_fd, TIOCSETD, &ldisc);
X#endif /* NTTYDISC */
X
X/* Set tty to CBREAK mode */
X  ioctl(input_fd, TIOCGETP, &new_tty);
X  new_tty.sg_flags |= CBREAK;
X  new_tty.sg_flags &= ~ECHO;
X  ioctl(input_fd, TIOCSETP, &new_tty);
X
X/* Unset signal chars, leav only ^\ */
X  ioctl(input_fd, TIOCSETC, (struct sgttyb *) &new_tchars);
X  signal(SIGQUIT, catch);		/* Which is caught */
X}
X
X/*
X * Panic() is called with an error number and a message. It is called when
X * something unrecoverable has happened.
X * It writes the message to the terminal, resets the tty and exits.
X * Ask the user if he wants to save his file.
X */
Xvoid panic(message)
Xregister char *message;
X{
X  extern char yank_file[];
X
X#ifdef UNIX
X  tputs(CL, 0, _putchar);
X  build_string(text_buffer, "%s\nError code %d\n", message, errno);
X#else
X  build_string(text_buffer, "%s%s\nError code %d\n", enter_string, message, errno);
X#endif /* UNIX */
X  (void) write(STD_OUT, text_buffer, length_of(text_buffer));
X
X  if (loading == FALSE)
X  	XT();			/* Check if file can be saved */
X  else
X  	(void) unlink(yank_file);
X  raw_mode(OFF);
X
X#ifdef UNIX
X  abort();
X#else
X  exit(1);
X#endif /* UNIX */
X}
X
Xchar *alloc(bytes)
Xint bytes;
X{
X  char *p;
X
X  p = malloc((unsigned) bytes);
X  if (p == NIL_PTR) {
X	if (loading == TRUE)
X		panic("File too big.");
X	panic("Out of memory.");
X  }
X  return(p);
X}
X
Xvoid free_space(p)
Xchar *p;
X{
X  free(p);
X}
X
X/*  ========================================================================  *
X *				Main loops				      *
X *  ========================================================================  */
X
X/* The mapping between input codes and functions. */
X
X#ifdef UNIX
Xvoid     (*key_map[128])() = {	       /* map ASCII characters to functions */
X   /* 000-017 */ MA, BL, MP, YA, SD, RD, MN, IF, DPC, S, S, DT, LR, S, DNW,LIB,
X   /* 020-037 */ DPW, WB, GR, SH, DLN, SU, VI, XWT, XT, PT, EL, ESC, I, GOTO,
X		 HIGH, LOW,
X   /* 040-057 */ S, S, S, S, S, S, S, S, S, S, S, PD, S, PU, S, S,
X   /* 060-077 */ S, S, DN, S, LF, FS, RT, S, UP, S, S, S, S, S, S, S,
X   /* 100-117 */ S, S, S, CTL, S, EF, SF, S, HO, S, S, S, S, S, S, S,
X   /* 120-137 */ S, S, SR, S, S, S, S, S, S, S, S, S, S, S, S, S,
X   /* 140-157 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S,
X   /* 160-177 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, DCC
X};
X#else
Xvoid (*key_map[256])() = {       /* map ASCII characters to functions */
X   /* 000-017 */ MA, BL, MP, YA, SD, RD, MN, IF, DPC, S, S, DT, LR, S, DNW,LIB,
X   /* 020-037 */ DPW, WB, GR, SH, DLN, SU, VI, XWT, XT, PT, EL, ESC, I, GOTO,
X		 HIGH, LOW,
X   /* 040-057 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S,
X   /* 060-077 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S,
X   /* 100-117 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S,
X   /* 120-137 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S,
X   /* 140-157 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S,
X   /* 160-177 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, DCC,
X   /* 200-217 */ I, I, I, I, I, I, I, I, I, SR, I, I, SF, I, I, I,
X   /* 220-237 */ MA, I, I, I, I, I, I, I, I, I, I, CTL, I, I, I, I,
X   /* 240-257 */ I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I,
X   /* 260-277 */ I, EF, DN, PD, LF, FS, RT, HO, UP, PU, I, I, I, I, I, I,
X   /* 300-317 */ I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I,
X   /* 320-337 */ I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I,
X   /* 340-357 */ I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I,
X   /* 360-377 */ I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I
X};
X#endif /* UNIX */
X
Xint nlines;			/* Number of lines in file */
XLINE *header;			/* Head of line list */
XLINE *tail;			/* Last line in line list */
XLINE *cur_line;			/* Current line in use */
XLINE *top_line;			/* First line of screen */
XLINE *bot_line;			/* Last line of screen */
Xchar *cur_text;			/* Current char on current line in use */
Xint last_y;			/* Last y of screen. Usually SCREENMAX */
Xchar screen[SCREEN_SIZE];	/* Output buffer for "writes" and "reads" */
X
Xint x, y;			/* x, y coordinates on screen */
XFLAG modified = FALSE;		/* Set when file is modified */
XFLAG stat_visible;		/* Set if status_line is visible */
XFLAG writable;			/* Set if file cannot be written */
XFLAG loading;			/* Set if we are loading a file. */
XFLAG quit = FALSE;		/* Set when quit character is typed */
XFLAG rpipe = FALSE;		/* Set if file should be read from stdin */
Xint input_fd = 0;		/* Fd for command input */
Xint out_count;			/* Index in output buffer */
Xchar file_name[LINE_LEN];	/* Name of file in use */
Xchar text_buffer[MAX_CHARS];	/* Buffer for modifying text */
X
X/* Escape sequences. */
X#ifdef UNIX
Xchar *CE, *VS, *SO, *SE, *CL, *AL, *CM;
X#else
Xchar   *enter_string = "\033[H\033[J";	/* String printed on entering mined */
Xchar   *pos_string = "\033[%d;%dH";	/* Absolute cursor position */
Xchar   *rev_scroll = "\033M";		/* String for reverse scrolling */
Xchar   *rev_video = "\033[7m";		/* String for starting reverse video */
Xchar   *normal_video = "\033[m";	/* String for leaving reverse video */
Xchar   *blank_line = "\033[K";		/* Clear line to end */
X#endif /* UNIX */
X
X/* 
X * Yank variables.
X */
XFLAG yank_status = NOT_VALID;		/* Status of yank_file */
Xchar yank_file[] = "/tmp/mined.XXXXXX";
Xlong chars_saved;			/* Nr of chars in buffer */
X
X/*
X * Initialize is called when a another file is edited. It free's the allocated
X * space and sets modified back to FALSE and fixes the header/tail pointer.
X */
Xvoid initialize()
X{
X  register LINE *line, *next_line;
X
X/* Delete the whole list */
X  for (line = header->next; line != tail; line = next_line) {
X  	next_line = line->next;
X  	free_space(line->text);
X  	free_space((char*)line);
X  }
X
X/* header and tail should point to itself */
X  line->next = line->prev = line;
X  x = y = 0;
X  rpipe = modified = FALSE;
X}
X
X/*
X * Basename() finds the absolute name of the file out of a given path_name.
X */
Xchar *basename(path)
Xchar *path;
X{
X  register char *ptr = path;
X  register char *last = NIL_PTR;
X
X  while (*ptr != '\0') {
X  	if (*ptr == '/')
X  		last = ptr;
X  	ptr++;
X  }
X  if (last == NIL_PTR)
X  	return path;
X  if (*(last + 1) == '\0') {	/* E.g. /usr/tmp/pipo/ */
X  	*last = '\0';
X  	return basename(path);/* Try again */
X  }
X  return last + 1;
X}
X
X/*
X * Load_file loads the file `file' into core. If file is a NIL_PTR or the file
X * couldn't be opened, just some initializations are done, and a line consisting
X * of a `\n' is installed.
X */
Xvoid load_file(file)
Xchar *file;
X{
X  register LINE *line = header;
X  register int len;
X  long nr_of_chars = 0L;
X  int fd = -1;			/* Filedescriptor for file */
X
X  nlines = 0;			/* Zero lines to start with */
X
X/* Open file */
X  writable = TRUE;		/* Benefit of the doubt */
X  if (file == NIL_PTR) {
X	if (rpipe == FALSE)
X  		status_line("No file.", NIL_PTR);
X	else {
X		fd = 0;
X		file = "standard input";
X	}
X	file_name[0] = '\0';
X  }
X  else {
X  	copy_string(file_name, file);	/* Save file name */
X  	if (access(file, 0) < 0)	/* Cannot access file. */
X  		status_line("New file ", file);
X  	else if ((fd = open(file, 0)) < 0)
X  		status_line("Cannot open ", file);
X  	else if (access(file, 2) != 0)	/* Set write flag */
X  		writable = FALSE;
X  }
X
X/* Read file */
X  loading = TRUE;				/* Loading file, so set flag */
X
X  if (fd >= 0) {
X  	status_line("Reading ", file);
X  	while ((len = get_line(fd, text_buffer)) != ERRORS) {
X  		line = line_insert(line, text_buffer, len);
X  		nr_of_chars += (long) len;
X  	}
X  	if (nlines == 0)		/* The file was empty! */
X  		line = line_insert(line, "\n", 1);
X  	clear_buffer();		/* Clear output buffer */
X  	cur_line = header->next;
X  	fstatus("Read", nr_of_chars);
X  	(void) close(fd);		/* Close file */
X  }
X  else					/* Just install a "\n" */
X  	(void) line_insert(line, "\n", 1);
X
X  reset(header->next, 0);		/* Initialize pointers */
X
X/* Print screen */
X  display (0, 0, header->next, last_y);
X  move_to (0, 0);
X  flush();				/* Flush buffer */
X  loading = FALSE;			/* Stop loading, reset flag */
X}
X
X
X/*
X * Get_line reads one line from filedescriptor fd. If EOF is reached on fd,
X * get_line() returns ERRORS, else it returns the length of the string.
X */
Xint get_line(fd, buffer)
Xint fd;
Xregister char *buffer;
X{
X  static char *last = NIL_PTR;
X  static char *current = NIL_PTR;
X  static int read_chars;
X  register char *cur_pos = current;
X  char *begin = buffer;
X
X  do {
X  	if (cur_pos == last) {
X  		if ((read_chars = read(fd, screen, SCREEN_SIZE)) <= 0)
X  			break;
X  		last = &screen[read_chars];
X  		cur_pos = screen;
X  	}
X	if ((unsigned char) *cur_pos >= 0177 || *cur_pos == '\0')
X		panic ("File contains non-ascii characters");
X  } while ((*buffer++ = *cur_pos++) != '\n');
X
X  current = cur_pos;
X  if (read_chars <= 0) {
X  	if (buffer == begin)
X  		return ERRORS;
X  	if (*(buffer - 1) != '\n')
X  		if (loading == TRUE) /* Add '\n' to last line of file */
X  			*buffer++ = '\n';
X  		else {
X  			*buffer = '\0';
X  			return NO_LINE;
X  		}
X  }
X
X  *buffer = '\0';
X  return buffer - begin;
X}
X
X/*
X * Install_line installs the buffer into a LINE structure It returns a pointer
X * to the allocated structure.
X */
XLINE *install_line(buffer, length)
Xchar *buffer;
Xint length;
X{
X  register LINE *new_line = (LINE *) alloc(sizeof(LINE));
X
X  new_line->text = alloc(length + 1);
X  new_line->shift_count = 0;
X  copy_string(new_line->text, buffer);
X
X  return new_line;
X}
X
Xvoid main(argc, argv)
Xint argc;
Xchar *argv[];
X{
X/* mined is the Minix editor. */
X
X  register int index;		/* Index in key table */
X
X#ifdef UNIX
X  get_term();
X  tputs(VS, 0, _putchar);
X  tputs(CL, 0, _putchar);
X#else
X  string_print(enter_string);			/* Hello world */
X#endif /* UNIX */
X
X  if (!isatty(0)) {		/* Reading from pipe */
X	if (argc != 1) {
X		write(2, "Cannot find terminal.\n", 22);
X		exit (1);
X	}
X	rpipe = TRUE;
X	modified = TRUE;	/* Set modified so he can write */
X	open_device();
X  }
X
X  raw_mode(ON);			/* Set tty to appropriate mode */
X
X  header = tail = (LINE *) alloc(sizeof(LINE));	/* Make header of list*/
X  header->text = NIL_PTR;
X  header->next = tail->prev = header;
X
X/* Load the file (if any) */
X  if (argc < 2)
X  	load_file(NIL_PTR);
X  else {
X  	(void) get_file(NIL_PTR, argv[1]);	/* Truncate filename */
X  	load_file(argv[1]);
X  }
X
X /* Main loop of the editor. */
X  for (;;) {
X  	index = getchar();
X  	if (stat_visible == TRUE)
X  		clear_status();
X  	if (quit == TRUE)
X  		abort_mined();
X  	else {			/* Call the function for this key */
X  		(*key_map[index])(index);
X  		flush();       /* Flush output (if any) */
X  		if (quit == TRUE)
X  			quit = FALSE;
X  	}
X  }
X  /* NOTREACHED */
X}
X
X/*  ========================================================================  *
X *				Miscellaneous				      *
X *  ========================================================================  */
X
X/*
X * Redraw the screen
X */
Xvoid RD()
X{
X/* Clear screen */
X#ifdef UNIX
X  tputs(VS, 0, _putchar);
X  tputs(CL, 0, _putchar);
X#else
X  string_print(enter_string);
X#endif /* UNIX */
X
X/* Print first page */
X  display(0, 0, top_line, last_y);
X
X/* Clear last line */
X  set_cursor(0, ymax);
X#ifdef UNIX
X  tputs(CE, 0, _putchar);
X#else
X  string_print(blank_line);
X#endif /* UNIX */
X  move_to(x, y);
X}
X
X/*
X * Ignore this keystroke.
X */
Xvoid I()
X{
X}
X
X/*
X * Leave editor. If the file has changed, ask if the user wants to save it.
X */
Xvoid XT()
X{
X  if (modified == TRUE && ask_save() == ERRORS)
X  	return;
X
X  raw_mode(OFF);
X  set_cursor(0, ymax);
X  putchar('\n');
X  flush();
X  (void) unlink(yank_file);		/* Might not be necessary */
X  exit(0);
X}
X
Xvoid (*escfunc(c))()
Xint c;
X{
X#if (CHIP == M68000)
X#ifndef COMPAT
X  int ch;
X#endif
X#endif
X  if (c == '[') {
X	/* Start of ASCII escape sequence. */
X	c = getchar();
X#if (CHIP == M68000)
X#ifndef COMPAT
X	if ((c >= '0') && (c <= '9')) ch = getchar();
X	/* ch is either a tilde or a second digit */
X#endif
X#endif
X	switch (c) {
X	case 'H': return(HO);
X	case 'A': return(UP);
X	case 'B': return(DN);
X	case 'C': return(RT);
X	case 'D': return(LF);
X#if (CHIP == M68000)
X#ifndef COMPAT
X	/* F1 = ESC [ 1 ~ */
X	/* F2 = ESC [ 2 ~ */
X	/* F3 = ESC [ 3 ~ */
X	/* F4 = ESC [ 4 ~ */
X	/* F5 = ESC [ 5 ~ */
X	/* F6 = ESC [ 6 ~ */
X	/* F7 = ESC [ 17 ~ */
X	/* F8 = ESC [ 18 ~ */
X	case '1': 
X	 	  switch (ch) {
X		  case '~': return(SF);
X		  case '7': (void) getchar(); return(MA);
X		  case '8': (void) getchar(); return(CTL);
X                  }
X	case '2': return(SR);
X	case '3': return(PD);
X	case '4': return(PU);
X	case '5': return(FS);
X	case '6': return(EF);
X#endif
X#endif
X#if (CHIP == INTEL)
X	case 'G': return(FS);
X	case 'S': return(SR);
X	case 'T': return(SF);
X	case 'U': return(PD);
X	case 'V': return(PU);
X	case 'Y': return(EF);
X#endif
X	}
X	return(I);
X  }
X#if (CHIP == M68000)
X#ifdef COMPAT
X  if (c == 'O') {
X	/* Start of ASCII function key escape sequence. */
X	switch (getchar()) {
X	case 'P': return(SF);
X	case 'Q': return(SR);
X	case 'R': return(PD);
X	case 'S': return(PU);
X	case 'T': return(FS);
X	case 'U': return(EF);
X	case 'V': return(MA);
X	case 'W': return(CTL);
X	}
X    }
X#endif
X#endif
X  return(I);
X}
X
X/*
X * ESC() wants a count and a command after that. It repeats the 
X * command count times. If a ^\ is given during repeating, stop looping and
X * return to main loop.
X */
Xvoid ESC()
X{
X  register int count = 0;
X  register void (*func)();
X  int index;
X
X  index = getchar();
X  while (index >= '0' && index <= '9' && quit == FALSE) {
X  	count *= 10;
X  	count += index - '0';
X  	index = getchar();
X  }
X  if (count == 0) {
X	count = 1;
X	func = escfunc(index);
X  } else {
X	func = key_map[index];
X	if (func == ESC)
X		func = escfunc(getchar());
X  }
X
X  if (func == I) {	/* Function assigned? */
X  	clear_status();
X  	return;
X  }
X
X  while (count-- > 0 && quit == FALSE) {
X  	if (stat_visible == TRUE)
X  		clear_status();
X  	(*func)(index);
X  	flush();
X  }
X
X  if (quit == TRUE)		/* Abort has been given */
X  	error("Aborted", NIL_PTR);
X}
X
X/*
X * Ask the user if he wants to save his file or not.
X */
Xint ask_save()
X{
X  register int c;
X
X  status_line(file_name[0] ? basename(file_name) : "[buffer]" ,
X					     " has been modified. Save? (y/n)");
X
X  while((c = getchar()) != 'y' && c != 'n' && quit == FALSE) {
X  	ring_bell();
X  	flush();
X  }
X
X  clear_status();
X
X  if (c == 'y')
X  	return WT();
X
X  if (c == 'n')
X  	return FINE;
X
X  quit = FALSE;	/* Abort character has been given */
X  return ERRORS;
X}
X
X/*
X * Line_number() finds the line number we're on.
X */
Xint line_number()
X{
X  register LINE *line = header->next;
X  register int count = 1;
X
X  while (line != cur_line) {
X  	count++;
X  	line = line->next;
X  }
X  
X  return count;
X}
X  
X/*
X * Display a line telling how many chars and lines the file contains. Also tell
X * whether the file is readonly and/or modified.
X */
Xvoid file_status(message, count, file, lines, writefl, changed)
Xchar *message;
Xregister long count;		/* Contains number of characters in file */
Xchar *file;
Xint lines;
XFLAG writefl, changed;
X{
X  register LINE *line;
X  char msg[LINE_LEN + 40];/* Buffer to hold line */
X  char yank_msg[LINE_LEN];/* Buffer for msg of yank_file */
X
X  if (count < 0)		/* Not valid. Count chars in file */
X  	for (line = header->next; line != tail; line = line->next)
X  		count += length_of(line->text);
X
X  if (yank_status != NOT_VALID)	/* Append buffer info */
X  	build_string(yank_msg, " Buffer: %D char%s.", chars_saved,
X						(chars_saved == 1L) ? "" : "s");
X  else
X  	yank_msg[0] = '\0';
X
X  build_string(msg, "%s %s%s%s %d line%s %D char%s.%s Line %d", message,
X  		    (rpipe == TRUE && *message != '[') ? "standard input" : basename(file),
X  		    (changed == TRUE) ? "*" : "",
X  		    (writefl == FALSE) ? " (Readonly)" : "",
X  		    lines, (lines == 1) ? "" : "s", 
X		    count, (count == 1L) ? "" : "s",
X		    yank_msg, line_number());
X
X  if (length_of(msg) + 1 > LINE_LEN - 4) {
X  	msg[LINE_LEN - 4] = SHIFT_MARK;	/* Overflow on status line */
X  	msg[LINE_LEN - 3] = '\0';
X  }
X  status_line(msg, NIL_PTR);		/* Print the information */
X}
X
X/*
X * Build_string() prints the arguments as described in fmt, into the buffer.
X * %s indicates an argument string, %d indicated an argument number.
X */
X/* VARARGS */
Xvoid build_string(buf, fmt, args)
Xregister char *buf, *fmt;
Xint args;
X{
X  char *argptr = (char *) &args;
X  char *scanp;
X
X  while (*fmt) {
X  	if (*fmt == '%') {
X  		fmt++;
X  		switch (*fmt++) {
X  		case 's' :
X  			scanp = (char *) *((char **)argptr);
X			argptr += sizeof(char *);
X  			break;
X  		case 'd' :
X  			scanp = num_out((long) *((int *)argptr));
X			argptr += sizeof(int);
X  			break;
X  		case 'D' :
X  			scanp = num_out((long) *((long *) argptr));
X			argptr += sizeof(long);
X  			break;
X  		default :
X  			scanp = "";
X  		}
X  		while (*buf++ = *scanp++)
X  			;
X  		buf--;
X  	}
X  	else
X  		*buf++ = *fmt++;
X  }
X  *buf = '\0';
X}
X
X/*
X * Output an (unsigned) long in a 10 digit field without leading zeros.
X * It returns a pointer to the first digit in the buffer.
X */
Xchar *num_out(number)
Xlong number;
X{
X  static char num_buf[11];		/* Buffer to build number */
X  register long digit;			/* Next digit of number */
X  register long pow = 1000000000L;	/* Highest ten power of long */
X  FLAG digit_seen = FALSE;
X  int i;
X
X  for (i = 0; i < 10; i++) {
X  	digit = number / pow;		/* Get next digit */
X  	if (digit == 0L && digit_seen == FALSE && i != 9)
X  		num_buf[i] = ' ';
X  	else {
X  		num_buf[i] = '0' + (char) digit;
X  		number -= digit * pow;	/* Erase digit */
X  		digit_seen = TRUE;
X  	}
X  	pow /= 10L;			/* Get next digit */
X  }
X  for (i = 0; num_buf[i] == ' '; i++)	/* Skip leading spaces */
X  	;
X  return (&num_buf[i]);
X}
X
X/*
X * Get_number() read a number from the terminal. The last character typed in is
X * returned.  ERRORS is returned on a bad number. The resulting number is put
X * into the integer the arguments points to.
X */
Xint get_number(message, result)
Xchar *message;
Xint *result;
X{
X  register int index;
X  register int count = 0;
X
X  status_line(message, NIL_PTR);
X
X  index = getchar();
X  if (quit == FALSE && (index < '0' || index > '9')) {
X  	error("Bad count", NIL_PTR);
X  	return ERRORS;
X  }
X
X/* Convert input to a decimal number */
X  while (index >= '0' && index <= '9' && quit == FALSE) {
X  	count *= 10;
X  	count += index - '0';
X  	index = getchar();
X  }
X
X  if (quit == TRUE) {
X  	clear_status();
X  	return ERRORS;
X  }
X
X  *result = count;
X  return index;
X}
X
X/*
X * Input() reads a string from the terminal.  When the KILL character is typed,
X * it returns ERRORS.
X */
Xint input(inbuf, clearfl)
Xchar *inbuf;
XFLAG clearfl;
X{
X  register char *ptr;
X  register char c;			/* Character read */
X
X  ptr = inbuf;
X
X  *ptr = '\0';
X  while (quit == FALSE) {
X  	flush();
X  	switch (c = getchar()) {
X  		case '\b' :		/* Erase previous char */
X  			if (ptr > inbuf) {
X  				ptr--;
X#ifdef UNIX
X  				tputs(SE, 0, _putchar);
X#else
X  				string_print(normal_video);
X#endif /* UNIX */
X  				if (is_tab(*ptr))
X  					string_print(" \b\b\b  \b\b");
X  				else
X  					string_print(" \b\b \b");
X#ifdef UNIX
X  				tputs(SO, 0, _putchar);
X#else
X  				string_print(rev_video);
X#endif /* UNIX */
X  				string_print(" \b");
X  				*ptr = '\0';
X  			}
X  			else
X  				ring_bell();
X  			break;
X  		case '\n' :		/* End of input */
X  			/* If inbuf is empty clear status_line */
X  			return (ptr == inbuf && clearfl == TRUE) ? NO_INPUT :FINE;
X  		default :		/* Only read ASCII chars */
X  			if ((c >= ' ' && c <= '~') || c == '\t') {
X  				*ptr++ = c;
X  				*ptr = '\0';
X  				if (c == '\t')
X  					string_print("^I");
X  				else
X  					putchar(c);
X  				string_print(" \b");
X  			}
X  			else
X  				ring_bell();
X  	}
X  }
X  quit = FALSE;
X  return ERRORS;
X}
X
X/*
X * Get_file() reads a filename from the terminal. Filenames longer than 
X * FILE_LENGHT chars are truncated.
X */
Xint get_file(message, file)
Xchar *message, *file;
X{
X  char *ptr;
X  int ret;
X
X  if (message == NIL_PTR || (ret = get_string(message, file, TRUE)) == FINE) {
X  	if (length_of((ptr = basename(file))) > NAME_MAX)
X  		ptr[NAME_MAX] = '\0';
X  }
X  return ret;
X}
X
X/*  ========================================================================  *
X *				UNIX I/O Routines			      *
X *  ========================================================================  */
X
X#ifdef UNIX
X#undef putchar
X
Xint _getchar()
X{
X  char c;
X
X  if (read(input_fd, &c, 1) != 1 && quit == FALSE)
X	panic ("Cannot read 1 byte from input");
X  return c & 0177;
X}
X
Xvoid _flush()
X{
X  (void) fflush(stdout);
X}
X
Xvoid _putchar(c)
Xchar c;
X{
X  (void) write_char(STD_OUT, c);
X}
X
Xvoid get_term()
X{
X  static char termbuf[50];
X  extern char *tgetstr(), *getenv();
X  char *loc = termbuf;
X  char entry[1024];
X
X  if (tgetent(entry, getenv("TERM")) <= 0) {
X  	printf("Unknown terminal.\n");
X  	exit(1);
X  }
X
X  AL = tgetstr("al", &loc);
X  CE = tgetstr("ce", &loc);
X  VS = tgetstr("vs", &loc);
X  CL = tgetstr("cl", &loc);
X  SO = tgetstr("so", &loc);
X  SE = tgetstr("se", &loc);
X  CM = tgetstr("cm", &loc);
X  ymax = tgetnum("li") - 1;
X  screenmax = ymax - 1;
X
X  if (!CE || !SO || !SE || !CL || !AL || !CM) {
X  	printf("Sorry, no mined on this type of terminal\n");
X  	exit(1);
X  }
X}
X#endif /* UNIX */
/
echo x - mined2.c
sed '/^X/s///' > mined2.c << '/'
X/*
X * Part 2 of the mined editor.
X */
X
X/*  ========================================================================  *
X *				Move Commands				      *	
X *  ========================================================================  */
X
X#include "mined.h"
X#include <string.h>
X
X/*
X * Move one line up.
X */
Xvoid UP()
X{
X  if (y == 0) {		/* Top line of screen. Scroll one line */
X  	(void) reverse_scroll();
X  	move_to(x, y);
X  }
X  else			/* Move to previous line */
X  	move_to(x, y - 1);
X}
X
X/*
X * Move one line down.
X */
Xvoid DN()
X{
X  if (y == last_y) {	/* Last line of screen. Scroll one line */
X	if (bot_line->next == tail && bot_line->text[0] != '\n') {
X		dummy_line();		/* Create new empty line */
X		DN();
X		return;
X	}
X	else {
X		(void) forward_scroll();
X		move_to(x, y);
X	}
X  }
X  else			/* Move to next line */
X  	move_to(x, y + 1);
X}
X
X/*
X * Move left one position.
X */
Xvoid LF()
X{
X  if (x == 0 && get_shift(cur_line->shift_count) == 0) {/* Begin of line */
X	if (cur_line->prev != header) {
X		UP();					/* Move one line up */
X		move_to(LINE_END, y);
X	}
X  }
X  else
X  	move_to(x - 1, y);
X}
X
X/*
X * Move right one position.
X */
Xvoid RT()
X{
X  if (*cur_text == '\n') {
X  	if (cur_line->next != tail) {		/* Last char of file */
X		DN();				/* Move one line down */
X		move_to(LINE_START, y);
X	}
X  }
X  else
X  	move_to(x + 1, y);
X}
X
X/*
X * Move to coordinates [0, 0] on screen.
X */
Xvoid HIGH()
X{
X  move_to(0, 0);
X}
X
X/*
X * Move to coordinates [0, YMAX] on screen.
X */
Xvoid LOW()
X{
X  move_to(0, last_y);
X}
X
X/*
X * Move to begin of line.
X */
Xvoid BL()
X{
X  move_to(LINE_START, y);
X}
X
X/*
X * Move to end of line.
X */
Xvoid EL()
X{
X  move_to(LINE_END, y);
X}
X
X/*
X * GOTO() prompts for a linenumber and moves to that line.
X */
Xvoid GOTO()
X{
X  int number;
X  LINE *line;
X
X  if (get_number("Please enter line number.", &number) == ERRORS)
X  	return;
X
X  if (number <= 0 || (line = proceed(header->next, number - 1)) == tail)
X  	error("Illegal line number: ", num_out((long) number));
X  else
X  	move_to(x, find_y(line));
X}
X
X/*
X * Scroll forward one page or to eof, whatever comes first. (Bot_line becomes 
X * top_line of display.) Try to leave the cursor on the same line. If this is
X * not possible, leave cursor on the line halfway the page.
X */
Xvoid PD()
X{
X  register int i;
X
X  for (i = 0; i < screenmax; i++)
X  	if (forward_scroll() == ERRORS)
X  		break;			/* EOF reached */
X  if (y - i < 0)				/* Line no longer on screen */
X  	move_to(0, screenmax >> 1);
X  else
X  	move_to(0, y - i);
X}
X
X
X/*
X * Scroll backwards one page or to top of file, whatever comes first. (Top_line
X * becomes bot_line of display).  The very bottom line (YMAX) is always blank.
X * Try to leave the cursor on the same line. If this is not possible, leave
X * cursor on the line halfway the page.
X */
Xvoid PU()
X{
X  register int i;
X
X  for (i = 0; i < screenmax; i++)
X  	if (reverse_scroll() == ERRORS)
X  		break;			/* Top of file reached */
X  set_cursor(0, ymax);			/* Erase very bottom line */
X#ifdef UNIX
X  tputs(CE, 0, _putchar);
X#else
X  string_print(blank_line);
X#endif /* UNIX */
X  if (y + i > screenmax)			/* line no longer on screen */
X  	move_to(0, screenmax >> 1);
X  else
X  	move_to(0, y + i);
X}
X
X/*
X * Go to top of file, scrolling if possible, else redrawing screen.
X */
Xvoid HO()
X{
X  if (proceed(top_line, -screenmax) == header)
X  	PU();			/* It fits. Let PU do it */
X  else {
X  	reset(header->next, 0);/* Reset top_line, etc. */
X  	RD();			/* Display full page */
X  }
X  move_to(LINE_START, 0);
X}
X
X/*
X * Go to last line of file, scrolling if possible, else redrawing screen
X */
Xvoid EF()
X{
X  if (tail->prev->text[0] != '\n')
X	dummy_line();
X  if (proceed(bot_line, screenmax) == tail)
X  	PD();			/* It fits. Let PD do it */
X  else {
X  	reset(proceed(tail->prev, -screenmax), screenmax);
X  	RD();			/* Display full page */
X  }
X  move_to(LINE_START, last_y);
X}
X
X/*
X * Scroll one line up. Leave the cursor on the same line (if possible).
X */
Xvoid SU()
X{
X  if (top_line->prev == header)	/* Top of file. Can't scroll */
X  	return;
X
X  (void) reverse_scroll();
X  set_cursor(0, ymax);		/* Erase very bottom line */
X#ifdef UNIX
X  tputs(CE, 0, _putchar);
X#else
X  string_print(blank_line);
X#endif /* UNIX */
X  move_to(x, (y == screenmax) ? screenmax : y + 1);
X}
X
X/*
X * Scroll one line down. Leave the cursor on the same line (if possible).
X */
Xvoid SD()
X{
X  if (forward_scroll() != ERRORS) 
X  	move_to(x, (y == 0) ? 0 : y - 1);
X  else
X  	set_cursor(x, y);
X}
X
X/*
X * Perform a forward scroll. It returns ERRORS if we're at the last line of the
X * file.
X */
Xint forward_scroll()
X{
X  if (bot_line->next == tail)		/* Last line of file. No dice */
X  	return ERRORS;
X  top_line = top_line->next;
X  bot_line = bot_line->next;
X  cur_line = cur_line->next;
X  set_cursor(0, ymax);
X  line_print(bot_line);
X
X  return FINE;
X}
X
X/*
X * Perform a backwards scroll. It returns ERRORS if we're at the first line
X * of the file.
X */
Xint reverse_scroll()
X{
X  if (top_line->prev == header)
X  	return ERRORS;		/* Top of file. Can't scroll */
X
X  if (last_y != screenmax)	/* Reset last_y if necessary */
X  	last_y++;
X  else
X  	bot_line = bot_line->prev;	/* Else adjust bot_line */
X  top_line = top_line->prev;
X  cur_line = cur_line->prev;
X
X/* Perform the scroll */
X  set_cursor(0, 0);
X#ifdef UNIX
X  tputs(AL, 0, _putchar);
X#else
X  string_print(rev_scroll);
X#endif /* UNIX */
X  set_cursor(0, 0);
X  line_print(top_line);
X
X  return FINE;
X}
X
X/*
X * A word is defined as a number of non-blank characters separated by tabs
X * spaces or linefeeds.
X */
X
X/*
X * MP() moves to the start of the previous word. A word is defined as a
X * number of non-blank characters separated by tabs spaces or linefeeds.
X */
Xvoid MP()
X{
X  move_previous_word(NO_DELETE);
X}
X
Xvoid move_previous_word(remove)
XFLAG remove;
X{
X  register char *begin_line;
X  register char *textp;
X  char start_char = *cur_text;
X  char *start_pos = cur_text;
X
X/* Fist check if we're at the beginning of line. */
X  if (cur_text == cur_line->text) {
X  	if (cur_line->prev == header)
X  		return;
X  	start_char = '\0';
X  }
X
X  LF();
X
X  begin_line = cur_line->text;
X  textp = cur_text;
X
X/* Check if we're in the middle of a word. */
X  if (!alpha(*textp) || !alpha(start_char)) {
X  	while (textp != begin_line && (white_space(*textp) || *textp == '\n'))
X  		textp--;
X  }
X
X/* Now we're at the end of previous word. Skip non-blanks until a blank comes */
X  while (textp != begin_line && alpha(*textp))
X  	textp--;
X
X/* Go to the next char if we're not at the beginning of the line */
X  if (textp != begin_line && *textp != '\n')
X  	textp++;
X
X/* Find the x-coordinate of this address, and move to it */
X  move_address(textp);
X  if (remove == DELETE)
X  	delete(cur_line, textp, cur_line, start_pos);
X}
X
X/*
X * MN() moves to the start of the next word. A word is defined as a number of
X * non-blank characters separated by tabs spaces or linefeeds. Always keep in
X * mind that the pointer shouldn't pass the '\n'.
X */
Xvoid MN()
X{
X  move_next_word(NO_DELETE);
X}
X
Xvoid move_next_word(remove)
XFLAG remove;
X{
X  register char *textp = cur_text;
X
X/* Move to the end of the current word. */
X  while (*textp != '\n' && alpha(*textp))
X  	textp++;
X
X/* Skip all white spaces */
X  while (*textp != '\n' && white_space(*textp))
X  	textp++;
X/* If we're deleting. delete the text in between */
X  if (remove == DELETE) {
X  	delete(cur_line, cur_text, cur_line, textp);
X  	return;
X  }
X
X/* If we're at end of line. move to the first word on the next line. */
X  if (*textp == '\n' && cur_line->next != tail) {
X  	DN();
X  	move_to(LINE_START, y);
X  	textp = cur_text;
X  	while (*textp != '\n' && white_space(*textp))
X  		textp++;
X  }
X  move_address(textp);
X}
X
X/*  ========================================================================  *
X *				Modify Commands				      *
X *  ========================================================================  */
X
X/*
X * DCC deletes the character under the cursor.  If this character is a '\n' the
X * current line is joined with the next one.
X * If this character is the only character of the line, the current line will
X * be deleted.
X */
Xvoid DCC()
X{
X  if (*cur_text == '\n')
X  	delete(cur_line,cur_text, cur_line->next,cur_line->next->text);
X  else
X  	delete(cur_line, cur_text, cur_line, cur_text + 1);
X}
X
X/*
X * DPC deletes the character on the left side of the cursor.  If the cursor is
X * at the beginning of the line, the last character if the previous line is
X * deleted. 
X */
Xvoid DPC()
X{
X  if (x == 0 && cur_line->prev == header)
X  	return;			/* Top of file */
X  
X  LF();				/* Move one left */
X  DCC();				/* Delete character under cursor */
X}
X
X/*
X * DLN deletes all characters until the end of the line. If the current
X * character is a '\n', then delete that char.
X */
Xvoid DLN()
X{
X  if (*cur_text == '\n')
X  	DCC();
X  else
X  	delete(cur_line, cur_text, cur_line, cur_text + length_of(cur_text) -1);
X}
X
X/*
X * DNW() deletes the next word (as described in MN())
X */
Xvoid DNW()
X{
X  if (*cur_text == '\n')
X  	DCC();
X  else
X  	move_next_word(DELETE);
X}
X
X/*
X * DPW() deletes the next word (as described in MP())
X */
Xvoid DPW()
X{
X  if (cur_text == cur_line->text)
X  	DPC();
X  else
X  	move_previous_word(DELETE);
X}
X
X/*
X * Insert character `character' at current location.
X */
Xvoid S(character)
Xregister char character;
X{
X  static char buffer[2];
X
X  buffer[0] = character;
X/* Insert the character */
X  if (insert(cur_line, cur_text, buffer) == ERRORS)
X  	return;
X
X/* Fix screen */
X  if (character == '\n') {
X  	set_cursor(0, y);
X  	if (y == screenmax) {		/* Can't use display */
X  		line_print(cur_line);
X  		(void) forward_scroll();
X  	}
X  	else {
X  		reset(top_line, y);	/* Reset pointers */
X  		display(0, y, cur_line, last_y - y);
X  	}
X  	move_to(0, (y == screenmax) ? y : y + 1);
X  }
X  else if (x + 1 == XBREAK)/* If line must be shifted, just call move_to*/
X  	move_to(x + 1, y);
X  else {			 /* else display rest of line */
X  	put_line(cur_line, x, FALSE);
X  	move_to(x + 1, y);
X  }
X}
X
X/*
X * CTL inserts a control-char at the current location. A message that this
X * function is called is displayed at the status line.
X */
Xvoid CTL()
X{
X  register char ctrl;
X
X  status_line("Enter control character.", NIL_PTR);
X  if ((ctrl = getchar()) >= '\01' && ctrl <= '\037') {
X  	S(ctrl);		/* Insert the char */
X	clear_status();
X  }
X  else
X	error ("Unknown control character", NIL_PTR);
X}
X
X/*
X * LIB insert a line at the current position and moves back to the end of
X * the previous line.
X */
Xvoid LIB()
X{
X  S('\n');	  		/* Insert the line */
X  UP();				/* Move one line up */
X  move_to(LINE_END, y);		/* Move to end of this line */
X}
X
X/*
X * Line_insert() inserts a new line with text pointed to by `string'.
X * It returns the address of the new line.
X */
XLINE *line_insert(line, string, len)
Xregister LINE *line;
Xchar *string;
Xint len;
X{
X  register LINE *new_line;
X
X/* Allocate space for LINE structure and text */
X  new_line = install_line(string, len);
X
X/* Install the line into the double linked list */
X  new_line->prev = line;
X  new_line->next = line->next;
X  line->next = new_line;
X  new_line->next->prev = new_line;
X
X/* Increment nlines */
X  nlines++;
X
X  return new_line;
X}
X
X/*
X * Insert() insert the string `string' at the given line and location.
X */
Xint insert(line, location, string)
Xregister LINE *line;
Xchar *location, *string;
X{
X  register char *bufp = text_buffer;	/* Buffer for building line */
X  register char *textp = line->text;
X
X  if (length_of(textp) + length_of(string) >= MAX_CHARS) {
X  	error("Line too long", NIL_PTR);
X  	return ERRORS;
X  }
X
X  modified = TRUE;			/* File has been modified */
X
X/* Copy part of line until `location' has been reached */
X  while (textp != location)
X  	*bufp++ = *textp++;
X  
X/* Insert string at this location */
X  while (*string != '\0')
X  	*bufp++ = *string++;
X  *bufp = '\0';
X  
X  if (*(string - 1) == '\n')		/* Insert a new line */
X  	(void) line_insert(line, location, length_of(location));
X  else					/* Append last part of line */
X  	copy_string(bufp, location);
X
X/* Install the new text in this line */
X  free_space(line->text);
X  line->text = alloc(length_of(text_buffer) + 1);
X  copy_string(line->text, text_buffer);
X
X  return FINE;
X}
X
X/*
X * Line_delete() deletes the argument line out of the line list. The pointer to
X * the next line is returned.
X */
XLINE *line_delete(line)
Xregister LINE *line;
X{
X  register LINE *next_line = line->next;
X
X/* Delete the line */
X  line->prev->next = line->next;
X  line->next->prev = line->prev;
X
X/* Free allocated space */
X  free_space(line->text);
X  free_space((char*)line);
X
X/* Decrement nlines */
X  nlines--;
X
X  return next_line;
X}
X
X/*
X * Delete() deletes all the characters (including newlines) between the
X * startposition and endposition and fixes the screen accordingly. It
X * returns the number of lines deleted.
X */
Xvoid delete(start_line, start_textp, end_line, end_textp)
Xregister LINE *start_line;
XLINE *end_line;
Xchar *start_textp, *end_textp;
X{
X  register char *textp = start_line->text;
X  register char *bufp = text_buffer;	/* Storage for new line->text */
X  LINE *line, *stop;
X  int line_cnt = 0;			/* Nr of lines deleted */
X  int count = 0;
X  int shift = 0;				/* Used in shift calculation */
X  int nx = x;
X
X  modified = TRUE;			/* File has been modified */
X
X/* Set up new line. Copy first part of start line until start_position. */
X  while (textp < start_textp) {
X  	*bufp++ = *textp++;
X  	count++;
X  }
X
X/* Check if line doesn't exceed MAX_CHARS */
X  if (count + length_of(end_textp) >= MAX_CHARS) {
X  	error("Line too long", NIL_PTR);
X  	return;
X  }
X
X/* Copy last part of end_line if end_line is not tail */
X  copy_string(bufp, (end_textp != NIL_PTR) ? end_textp : "\n");
X
X/* Delete all lines between start and end_position (including end_line) */
X  line = start_line->next;
X  stop = end_line->next;
X  while (line != stop && line != tail) {
X  	line = line_delete(line);
X  	line_cnt++;
X  }
X
X/* Check if last line of file should be deleted */
X  if (end_textp == NIL_PTR && length_of(start_line->text) == 1 && nlines > 1) {
X  	start_line = start_line->prev;
X  	(void) line_delete(start_line->next);
X  	line_cnt++;
X  }
X  else {	/* Install new text */
X  	free_space(start_line->text);
X  	start_line->text = alloc(length_of(text_buffer) + 1);
X  	copy_string(start_line->text, text_buffer);
X  }
X
X/* Fix screen. First check if line is shifted. Perhaps we should shift it back*/
X  if (get_shift(start_line->shift_count)) {
X  	shift = (XBREAK - count_chars(start_line)) / SHIFT_SIZE;
X  	if (shift > 0) {		/* Shift line `shift' back */
X  		if (shift >= get_shift(start_line->shift_count))
X  			start_line->shift_count = 0;
X  		else
X  			start_line->shift_count -= shift;
X  		nx += shift * SHIFT_SIZE;/* Reset x value */
X  	}
X  }
X
X  if (line_cnt == 0) {		    /* Check if only one line changed */
X  	if (shift > 0) {	    /* Reprint whole line */
X  		set_cursor(0, y);
X  		line_print(start_line);
X  	}
X  	else {			    /* Just display last part of line */
X  		set_cursor(x, y);
X  		put_line(start_line, x, TRUE);
X  	}
X  	move_to(nx, y);	   /* Reset cur_text */
X  	return;
X  }
X
X  shift = last_y;	   /* Save value */
X  reset(top_line, y);
X  display(0, y, start_line, shift - y);
X  move_to((line_cnt == 1) ? nx : 0, y);
X}
X
X/*  ========================================================================  *
X *				Yank Commands				      *	
X *  ========================================================================  */
X
XLINE *mark_line;			/* For marking position. */
Xchar *mark_text;
Xint lines_saved;			/* Nr of lines in buffer */
X
X/*
X * PT() inserts the buffer at the current location.
X */
Xvoid PT()
X{
X  register int fd;		/* File descriptor for buffer */
X
X  if ((fd = scratch_file(READ)) == ERRORS)
X  	error("Buffer is empty.", NIL_PTR);
X  else {
X  	file_insert(fd, FALSE);/* Insert the buffer */
X  	(void) close(fd);
X  }
X}
X
X/*
X * IF() prompt for a filename and inserts the file at the current location 
X * in the file.
X */
Xvoid IF()
X{
X  register int fd;		/* File descriptor of file */
X  char name[LINE_LEN];		/* Buffer for file name */
X
X/* Get the file name */
X  if (get_file("Get and insert file:", name) != FINE)
X  	return;
X  
X  if ((fd = open(name, 0)) < 0)
X  	error("Cannot open ", name);
X  else {
X  	file_insert(fd, TRUE);	/* Insert the file */
X  	(void) close(fd);
X  }
X}
X
X/*
X * File_insert() inserts a an opened file (as given by filedescriptor fd)
X * at the current location.
X */
Xvoid file_insert(fd, old_pos)
Xint fd;
XFLAG old_pos;
X{
X  char line_buffer[MAX_CHARS];		/* Buffer for next line */
X  register LINE *line = cur_line;
X  register int line_count = nlines;	/* Nr of lines inserted */
X  LINE *page = cur_line;
X  int ret = ERRORS;
X  
X/* Get the first piece of text (might be ended with a '\n') from fd */
X  if (get_line(fd, line_buffer) == ERRORS)
X  	return;				/* Empty file */
X
X/* Insert this text at the current location. */
X  if (insert(line, cur_text, line_buffer) == ERRORS)
X  	return;
X
X/* Repeat getting lines (and inserting lines) until EOF is reached */
X  while ((ret = get_line(fd, line_buffer)) != ERRORS && ret != NO_LINE)
X  	line = line_insert(line, line_buffer, ret);
X  
X  if (ret == NO_LINE) {		/* Last line read not ended by a '\n' */
X  	line = line->next;
X  	(void) insert(line, line->text, line_buffer);
X  }
X
X/* Calculate nr of lines added */
X  line_count = nlines - line_count;
X
X/* Fix the screen */
X  if (line_count == 0) {		/* Only one line changed */
X  	set_cursor(0, y);
X  	line_print(line);
X  	move_to((old_pos == TRUE) ? x : x + length_of(line_buffer), y);
X  }
X  else {				/* Several lines changed */
X  	reset(top_line, y);	/* Reset pointers */
X  	while (page != line && page != bot_line->next)
X  		page = page->next;
X  	if (page != bot_line->next || old_pos == TRUE)
X  		display(0, y, cur_line, screenmax - y);
X  	if (old_pos == TRUE)
X  		move_to(x, y);
X  	else if (ret == NO_LINE)
X		move_to(length_of(line_buffer), find_y(line));
X	else 
X		move_to(0, find_y(line->next));
X  }
X
X/* If nr of added line >= REPORT, print the count */
X  if (line_count >= REPORT)
X  	status_line(num_out((long) line_count), " lines added.");
X}
X
X/*
X * WB() writes the buffer (yank_file) into another file, which
X * is prompted for.
X */
Xvoid WB()
X{
X  register int new_fd;		/* Filedescriptor to copy file */
X  int yank_fd;			/* Filedescriptor to buffer */
X  register int cnt;		/* Count check for read/write */
X  int ret = 0;			/* Error check for write */
X  char file[LINE_LEN];		/* Output file */
X  
X/* Checkout the buffer */
X  if ((yank_fd = scratch_file(READ)) == ERRORS) {
X  	error("Buffer is empty.", NIL_PTR);
X  	return;
X  }
X
X/* Get file name */
X  if (get_file("Write buffer to file:", file) != FINE)
X  	return;
X  
X/* Creat the new file */
X  if ((new_fd = creat(file, 0644)) < 0) {
X  	error("Cannot create ", file);
X  	return;
X  }
X
X  status_line("Writing ", file);
X  
X/* Copy buffer into file */
X  while ((cnt = read(yank_fd, text_buffer, sizeof(text_buffer))) > 0)
X  	if (write(new_fd, text_buffer, cnt) != cnt) {
X  		bad_write(new_fd);
X  		ret = ERRORS;
X  		break;
X  	}
X
X/* Clean up open files and status_line */
X  (void) close(new_fd);
X  (void) close(yank_fd);
X
X  if (ret != ERRORS)			/* Bad write */
X  	file_status("Wrote", chars_saved, file, lines_saved, TRUE, FALSE);
X}
X
X/*
X * MA sets mark_line (mark_text) to the current line (text pointer). 
X */
Xvoid MA()
X{
X  mark_line = cur_line;
X  mark_text = cur_text;
X  status_line("Mark set", NIL_PTR);
X}
X
X/*
X * YA() puts the text between the marked position and the current
X * in the buffer.
X */
Xvoid YA()
X{
X  set_up(NO_DELETE);
X}
X
X/*
X * DT() is essentially the same as YA(), but in DT() the text is deleted.
X */
Xvoid DT()
X{
X  set_up(DELETE);
X}
X
X/*
X * Set_up is an interface to the actual yank. It calls checkmark () to check
X * if the marked position is still valid. If it is, yank is called with the
X * arguments in the right order.
X */
Xvoid set_up(remove)
XFLAG remove;				/* DELETE if text should be deleted */
X{
X  switch (checkmark()) {
X  	case NOT_VALID :
X  		error("Mark not set.", NIL_PTR);
X  		return;
X  	case SMALLER :
X  		yank(mark_line, mark_text, cur_line, cur_text, remove);
X  		break;
X  	case BIGGER :
X  		yank(cur_line, cur_text, mark_line, mark_text, remove);
X  		break;
X  	case SAME :		/* Ignore stupid behaviour */
X  		yank_status = EMPTY;
X  		chars_saved = 0L;
X  		status_line("0 characters saved in buffer.", NIL_PTR);
X  		break;
X  }
X}
X
X/*
X * Check_mark() checks if mark_line and mark_text are still valid pointers. If
X * they are it returns SMALLER if the marked position is before the current,
X * BIGGER if it isn't or SAME if somebody didn't get the point.
X * NOT_VALID is returned when mark_line and/or mark_text are no longer valid.
X * Legal() checks if mark_text is valid on the mark_line.
X */
XFLAG checkmark()
X{
X  register LINE *line;
X  FLAG cur_seen = FALSE;
X
X/* Special case: check is mark_line and cur_line are the same. */
X  if (mark_line == cur_line) {
X  	if (mark_text == cur_text)	/* Even same place */
X  		return SAME;
X  	if (legal() == ERRORS)		/* mark_text out of range */
X  		return NOT_VALID;
X  	return (mark_text < cur_text) ? SMALLER : BIGGER;
X  }
X
X/* Start looking for mark_line in the line structure */
X  for (line = header->next; line != tail; line = line->next) {
X  	if (line == cur_line)
X  		cur_seen = TRUE;
X  	else if (line == mark_line)
X  		break;
X  }
X
X/* If we found mark_line (line != tail) check for legality of mark_text */
X  if (line == tail || legal() == ERRORS)
X  	return NOT_VALID;
X
X/* cur_seen is TRUE if cur_line is before mark_line */
X  return (cur_seen == TRUE) ? BIGGER : SMALLER;
X}
X
X/*
X * Legal() checks if mark_text is still a valid pointer.
X */
Xint legal()
X{
X  register char *textp = mark_line->text;
X
X/* Locate mark_text on mark_line */
X  while (textp != mark_text && *textp++ != '\0')
X  	;
X  return (*textp == '\0') ? ERRORS : FINE;
X}
X
X/*
X * Yank puts all the text between start_position and end_position into
X * the buffer.
X * The caller must check that the arguments to yank() are valid. (E.g. in
X * the right order)
X */
Xvoid yank(start_line, start_textp, end_line, end_textp, remove)
XLINE *start_line, *end_line;
Xchar *start_textp, *end_textp;
XFLAG remove;				/* DELETE if text should be deleted */
X{
X  register LINE *line = start_line;
X  register char *textp = start_textp;
X  int fd;
X
X/* Creat file to hold buffer */
X  if ((fd = scratch_file(WRITE)) == ERRORS)
X  	return;
X  
X  chars_saved = 0L;
X  lines_saved = 0;
X  status_line("Saving text.", NIL_PTR);
X
X/* Keep writing chars until the end_location is reached. */
X  while (textp != end_textp) {
X  	if (write_char(fd, *textp) == ERRORS) {
X  		(void) close(fd);
X  		return;
X  	}
X  	if (*textp++ == '\n') {	/* Move to the next line */
X  		line = line->next;
X  		textp = line->text;
X  		lines_saved++;
X  	}
X  	chars_saved++;
X  }
X
X/* Flush the I/O buffer and close file */
X  if (flush_buffer(fd) == ERRORS) {
X  	(void) close(fd);
X  	return;
X  }
X  (void) close(fd);
X  yank_status = VALID;
X
X/*
X * Check if the text should be deleted as well. If it should, the following
X * hack is used to save a lot of code. First move back to the start_position.
X * (This might be the location we're on now!) and them delete the text.
X * It might be a bit confusing the first time somebody uses it.
X * Delete() will fix the screen.
X */
X  if (remove == DELETE) {
X  	move_to(find_x(start_line, start_textp), find_y(start_line));
X  	delete(start_line, start_textp, end_line, end_textp);
X  }
X
X  status_line(num_out(chars_saved), " characters saved in buffer.");
X}
X
X/*
X * Scratch_file() creates a uniq file in /usr/tmp. If the file couldn't
X * be created other combinations of files are tried until a maximum
X * of MAXTRAILS times. After MAXTRAILS times, an error message is given
X * and ERRORS is returned.
X */
X
X#define MAXTRAILS	26
X
Xint scratch_file(mode)
XFLAG mode;				/* Can be READ or WRITE permission */
X{
X  static int trials = 0;		/* Keep track of trails */
X  register char *y_ptr, *n_ptr;
X  int fd;				/* Filedescriptor to buffer */
X
X/* If yank_status == NOT_VALID, scratch_file is called for the first time */
X  if (yank_status == NOT_VALID && mode == WRITE) { /* Create new file */
X  	/* Generate file name. */
X	y_ptr = &yank_file[11];
X	n_ptr = num_out((long) getpid());
X	while ((*y_ptr = *n_ptr++) != '\0')
X		y_ptr++;
X	*y_ptr++ = 'a' + trials;
X	*y_ptr = '\0';
X  	/* Check file existence */
X  	if (access(yank_file, 0) == 0 || (fd = creat(yank_file, 0644)) < 0) {
X  		if (trials++ >= MAXTRAILS) {
X  			error("Unable to creat scratchfile.", NIL_PTR);
X  			return ERRORS;
X  		}
X  		else
X  			return scratch_file(mode);/* Have another go */
X  	}
X  }
X  else if ((mode == READ && (fd = open(yank_file, 0)) < 0) ||
X			(mode == WRITE && (fd = creat(yank_file, 0644)) < 0)) {
X  	yank_status = NOT_VALID;
X  	return ERRORS;
X  }
X
X  clear_buffer();
X  return fd;
X}
X
X/*  ========================================================================  *
X *				Search Routines				      *	
X *  ========================================================================  */
X
X/*
X * A regular expression consists of a sequence of:
X * 	1. A normal character matching that character.
X * 	2. A . matching any character.
X * 	3. A ^ matching the begin of a line.
X * 	4. A $ (as last character of the pattern) mathing the end of a line.
X * 	5. A \<character> matching <character>.
X * 	6. A number of characters enclosed in [] pairs matching any of these
X * 	   characters. A list of characters can be indicated by a '-'. So
X * 	   [a-z] matches any letter of the alphabet. If the first character
X * 	   after the '[' is a '^' then the set is negated (matching none of
X * 	   the characters). 
X * 	   A ']', '^' or '-' can be escaped by putting a '\' in front of it.
X * 	7. If one of the expressions as described in 1-6 is followed by a
X * 	   '*' than that expressions matches a sequence of 0 or more of
X * 	   that expression.
X */
X
Xchar typed_expression[LINE_LEN];	/* Holds previous expr. */
X
X/*
X * SF searches forward for an expression.
X */
Xvoid SF()
X{
X  search("Search forward:", FORWARD);
X}
X
X/*
X * SF searches backwards for an expression.
X */
Xvoid SR()
X{
X  search("Search reverse:", REVERSE);
X}
X
X/*
X * Get_expression() prompts for an expression. If just a return is typed, the
X * old expression is used. If the expression changed, compile() is called and
X * the returning REGEX structure is returned. It returns NIL_REG upon error.
X * The save flag indicates whether the expression should be appended at the
X * message pointer.
X */
XREGEX *get_expression(message)
Xchar *message;
X{
X  static REGEX program;			/* Program of expression */
X  char exp_buf[LINE_LEN];			/* Buffer for new expr. */
X
X  if (get_string(message, exp_buf, FALSE) == ERRORS)
X  	return NIL_REG;
X  
X  if (exp_buf[0] == '\0' && typed_expression[0] == '\0') {
X  	error("No previous expression.", NIL_PTR);
X  	return NIL_REG;
X  }
X
X  if (exp_buf[0] != '\0') {		/* A new expr. is typed */
X  	copy_string(typed_expression, exp_buf);/* Save expr. */
X  	compile(exp_buf, &program);	/* Compile new expression */
X  }
X
X  if (program.status == REG_ERROR) {	/* Error during compiling */
X  	error(program.result.err_mess, NIL_PTR);
X  	return NIL_REG;
X  }
X  return &program;
X}
X
X/*
X * GR() a replaces all matches from the current position until the end
X * of the file.
X */
Xvoid GR()
X{
X  change("Global replace:", VALID);
X}
X
X/*
X * LR() replaces all matches on the current line.
X */
Xvoid LR()
X{
X  change("Line replace:", NOT_VALID);
X}
X
X/*
X * Change() prompts for an expression and a substitution pattern and changes
X * all matches of the expression into the substitution. change() start looking
X * for expressions at the current line and continues until the end of the file
X * if the FLAG file is VALID.
X */
Xvoid change(message, file)
Xchar *message;				/* Message to prompt for expression */
XFLAG file;
X{
X  char mess_buf[LINE_LEN];	/* Buffer to hold message */
X  char replacement[LINE_LEN];	/* Buffer to hold subst. pattern */
X  REGEX *program;			/* Program resulting from compilation */
X  register LINE *line = cur_line;
X  register char *textp;
X  long lines = 0L;		/* Nr of lines on which subs occurred */
X  long subs = 0L;			/* Nr of subs made */
X  int page = y;			/* Index to check if line is on screen*/
X
X/* Save message and get expression */
X  copy_string(mess_buf, message);
X  if ((program = get_expression(mess_buf)) == NIL_REG)
X  	return;
X  
X/* Get substitution pattern */
X  build_string(mess_buf, "%s %s by:", mess_buf, typed_expression);
X  if (get_string(mess_buf, replacement, FALSE) == ERRORS)
X  	return;
X  
X  set_cursor(0, ymax);
X  flush();
X/* Substitute until end of file */
X  do {
X  	if (line_check(program, line->text, FORWARD)) {
X  		lines++;
X  		/* Repeat sub. on this line as long as we find a match*/
X  		do {
X  			subs++;	/* Increment subs */
X  			if ((textp = substitute(line, program,replacement))
X								     == NIL_PTR)
X  				return;	/* Line too long */
X  		} while ((program->status & BEGIN_LINE) != BEGIN_LINE &&
X			 (program->status & END_LINE) != END_LINE &&
X					  line_check(program, textp, FORWARD));
X  		/* Check to see if we can print the result */
X  		if (page <= screenmax) {
X  			set_cursor(0, page);
X  			line_print(line);
X  		}
X  	}
X  	if (page <= screenmax)
X  		page++;
X  	line = line->next;
X  } while (line != tail && file == VALID && quit == FALSE);
X
X  copy_string(mess_buf, (quit == TRUE) ? "(Aborted) " : "");
X/* Fix the status line */
X  if (subs == 0L && quit == FALSE)
X  	error("Pattern not found.", NIL_PTR);
X  else if (lines >= REPORT || quit == TRUE) {
X  	build_string(mess_buf, "%s %D substitutions on %D lines.", mess_buf,
X								   subs, lines);
X  	status_line(mess_buf, NIL_PTR);
X  }
X  else if (file == NOT_VALID && subs >= REPORT)
X  	status_line(num_out(subs), " substitutions.");
X  else
X  	clear_status();
X  move_to (x, y);
X}
X
X/*
X * Substitute() replaces the match on this line by the substitute pattern
X * as indicated by the program. Every '&' in the replacement is replaced by 
X * the original match. A \ in the replacement escapes the next character.
X */
Xchar *substitute(line, program, replacement)
XLINE *line;
XREGEX *program;
Xchar *replacement;		/* Contains replacement pattern */
X{
X  register char *textp = text_buffer;
X  register char *subp = replacement;
X  char *linep = line->text;
X  char *amp;
X
X  modified = TRUE;
X
X/* Copy part of line until the beginning of the match */
X  while (linep != program->start_ptr)
X  	*textp++ = *linep++;
X  
X/*
X * Replace the match by the substitution pattern. Each occurrence of '&' is
X * replaced by the original match. A \ escapes the next character.
X */
X  while (*subp != '\0' && textp < &text_buffer[MAX_CHARS]) {
X  	if (*subp == '&') {		/* Replace the original match */
X  		amp = program->start_ptr;
X  		while (amp < program->end_ptr && textp<&text_buffer[MAX_CHARS])
X  			*textp++ = *amp++;
X  		subp++;
X  	}
X  	else {
X  		if (*subp == '\\' && *(subp + 1) != '\0')
X  			subp++;
X  		*textp++ = *subp++;
X  	}
X  }
X
X/* Check for line length not exceeding MAX_CHARS */
X  if (length_of(text_buffer) + length_of(program->end_ptr) >= MAX_CHARS) {
X  	error("Substitution result: line too big", NIL_PTR);
X  	return NIL_PTR;
X  }
X
X/* Append last part of line to the new build line */
X  copy_string(textp, program->end_ptr);
X
X/* Free old line and install new one */
X  free_space(line->text);
X  line->text = alloc(length_of(text_buffer) + 1);
X  copy_string(line->text, text_buffer);
X
X  return(line->text + (textp - text_buffer));
X}
X
X/*
X * Search() calls get_expression to fetch the expression. If this went well,
X * the function match() is called which returns the line with the next match.
X * If this line is the NIL_LINE, it means that a match could not be found.
X * Find_x() and find_y() display the right page on the screen, and return
X * the right coordinates for x and y. These coordinates are passed to move_to()
X */
Xvoid search(message, method)
Xchar *message;
XFLAG method;
X{
X  register REGEX *program;
X  register LINE *match_line;
X
X/* Get the expression */
X  if ((program = get_expression(message)) == NIL_REG)
X  	return;
X
X  set_cursor(0, ymax);
X  flush();
X/* Find the match */
X  if ((match_line = match(program, cur_text, method)) == NIL_LINE) {
X  	if (quit == TRUE)
X  		status_line("Aborted", NIL_PTR);
X  	else
X  		status_line("Pattern not found.", NIL_PTR);
X  	return;
X  }
X
X  move(0, program->start_ptr, find_y(match_line));
X  clear_status();
X}
X
X/*
X * find_y() checks if the matched line is on the current page.  If it is, it
X * returns the new y coordinate, else it displays the correct page with the
X * matched line in the middle and returns the new y value;
X */
Xint find_y(match_line)
XLINE *match_line;
X{
X  register LINE *line;
X  register int count = 0;
X
X/* Check if match_line is on the same page as currently displayed. */
X  for (line = top_line; line != match_line && line != bot_line->next;
X  						      line = line->next)
X  	count++;
X  if (line != bot_line->next)
X  	return count;
X
X/* Display new page, with match_line in center. */
X  if ((line = proceed(match_line, -(screenmax >> 1))) == header) {
X  /* Can't display in the middle. Make first line of file top_line */
X  	count = 0;
X  	for (line = header->next; line != match_line; line = line->next)
X  		count++;
X  	line = header->next;
X  }
X  else	/* New page is displayed. Set cursor to middle of page */
X  	count = screenmax >> 1;
X
X/* Reset pointers and redraw the screen */
X  reset(line, 0);
X  RD();
X
X  return count;
X}
X
X/* Opcodes for characters */
X#define	NORMAL		0x0200
X#define DOT		0x0400
X#define EOLN		0x0800
X#define STAR		0x1000
X#define BRACKET		0x2000
X#define NEGATE		0x0100
X#define DONE		0x4000
X
X/* Mask for opcodes and characters */
X#define LOW_BYTE	0x00FF
X#define HIGH_BYTE	0xFF00
X
X/* Previous is the contents of the previous address (ptr) points to */
X#define previous(ptr)		(*((ptr) - 1))
X
X/* Buffer to store outcome of compilation */
Xint exp_buffer[BLOCK_SIZE];
X
X/* Errors often used */
Xchar *too_long = "Regular expression too long";
X
X/*
X * Reg_error() is called by compile() is something went wrong. It set the
X * status of the structure to error, and assigns the error field of the union.
X */
X#define reg_error(str)	program->status = REG_ERROR, \
X  					program->result.err_mess = (str)
X/*
X * Finished() is called when everything went right during compilation. It
X * allocates space for the expression, and copies the expression buffer into
X * this field.
X */
Xvoid finished(program, last_exp)
Xregister REGEX *program;
Xint *last_exp;
X{
X  register int length = (last_exp - exp_buffer) * sizeof(int);
X
X/* Allocate space */
X  program->result.expression = (int *) alloc(length);
X/* Copy expression. (expression consists of ints!) */
X  bcopy(exp_buffer, program->result.expression, length);
X}
X
X/*
X * Compile compiles the pattern into a more comprehensible form and returns a 
X * REGEX structure. If something went wrong, the status field of the structure
X * is set to REG_ERROR and an error message is set into the err_mess field of
X * the union. If all went well the expression is saved and the expression
X * pointer is set to the saved (and compiled) expression.
X */
Xvoid compile(pattern, program)
Xregister char *pattern;			/* Pointer to pattern */
XREGEX *program;
X{
X  register int *expression = exp_buffer;
X  int *prev_char;			/* Pointer to previous compiled atom */
X  int *acct_field;		/* Pointer to last BRACKET start */
X  FLAG negate;			/* Negate flag for BRACKET */
X  char low_char;			/* Index for chars in BRACKET */
X  char c;
X
X/* Check for begin of line */
X  if (*pattern == '^') {
X  	program->status = BEGIN_LINE;
X  	pattern++;
X  }
X  else {
X  	program->status = 0;
X/* If the first character is a '*' we have to assign it here. */
X  	if (*pattern == '*') {
X  		*expression++ = '*' + NORMAL;
X  		pattern++;
X  	}
X  }
X
X  for (; ;) {
X  	switch (c = *pattern++) {
X  	case '.' :
X  		*expression++ = DOT;
X  		break;
X  	case '$' :
X  		/*
X  		 * Only means EOLN if it is the last char of the pattern
X  		 */
X  		if (*pattern == '\0') {
X  			*expression++ = EOLN | DONE;
X  			program->status |= END_LINE;
X  			finished(program, expression);
X  			return;
X  		}
X  		else
X  			*expression++ = NORMAL + '$';
X  		break;
X  	case '\0' :
X  		*expression++ = DONE;
X  		finished(program, expression);
X  		return;
X  	case '\\' :
X  		/* If last char, it must! mean a normal '\' */
X  		if (*pattern == '\0')
X  			*expression++ = NORMAL + '\\';
X  		else
X  			*expression++ = NORMAL + *pattern++;
X  		break;
X  	case '*' :
X  		/*
X  		 * If the previous expression was a [] find out the
X  		 * begin of the list, and adjust the opcode.
X  		 */
X  		prev_char = expression - 1;
X  		if (*prev_char & BRACKET)
X  			*(expression - (*acct_field & LOW_BYTE))|= STAR;
X  		else
X  			*prev_char |= STAR;
X  		break;
X  	case '[' :
X  		/*
X  		 * First field in expression gives information about
X  		 * the list.
X  		 * The opcode consists of BRACKET and if necessary
X  		 * NEGATE to indicate that the list should be negated
X  		 * and/or STAR to indicate a number of sequence of this 
X  		 * list.
X  		 * The lower byte contains the length of the list.
X  		 */
X  		acct_field = expression++;
X  		if (*pattern == '^') {	/* List must be negated */
X  			pattern++;
X  			negate = TRUE;
X  		}
X  		else
X  			negate = FALSE;
X  		while (*pattern != ']') {
X  			if (*pattern == '\0') {
X  				reg_error("Missing ]");
X  				return;
X  			}
X  			if (*pattern == '\\')
X  				pattern++;
X  			*expression++ = *pattern++;
X  			if (*pattern == '-') {
X  						/* Make list of chars */
X  				low_char = previous(pattern);
X  				pattern++;	/* Skip '-' */
X  				if (low_char++ > *pattern) {
X  					reg_error("Bad range in [a-z]");
X  					return;
X  				}
X  				/* Build list */
X  				while (low_char <= *pattern)
X  					*expression++ = low_char++;
X  				pattern++;
X  			}
X  			if (expression >= &exp_buffer[BLOCK_SIZE]) {
X  				reg_error(too_long);
X  				return;
X  			}
X  		}
X  		pattern++;			/* Skip ']' */
X  		/* Assign length of list in acct field */
X  		if ((*acct_field = (expression - acct_field)) == 1) {
X  			reg_error("Empty []");
X  			return;
X  		}
X  		/* Assign negate and bracket field */
X  		*acct_field |= BRACKET;
X  		if (negate == TRUE)
X  			*acct_field |= NEGATE;
X  		/*
X  		 * Add BRACKET to opcode of last char in field because
X  		 * a '*' may be following the list.
X  		 */
X  		previous(expression) |= BRACKET;
X  		break;
X  	default :
X  		*expression++ = c + NORMAL;
X  	}
X  	if (expression == &exp_buffer[BLOCK_SIZE]) {
X  		reg_error(too_long);
X  		return;
X  	}
X  }
X  /* NOTREACHED */
X}
X
X/*
X * Match gets as argument the program, pointer to place in current line to 
X * start from and the method to search for (either FORWARD or REVERSE).
X * Match() will look through the whole file until a match is found.
X * NIL_LINE is returned if no match could be found.
X */
XLINE *match(program, string, method)
XREGEX *program;
Xchar *string;
Xregister FLAG method;
X{
X  register LINE *line = cur_line;
X  char old_char;				/* For saving chars */
X
X/* Corrupted program */
X  if (program->status == REG_ERROR)
X  	return NIL_LINE;
X
X/* Check part of text first */
X  if (!(program->status & BEGIN_LINE)) {
X  	if (method == FORWARD) {
X  		if (line_check(program, string + 1, method) == MATCH)
X  			return cur_line;	/* Match found */
X  	}
X  	else if (!(program->status & END_LINE)) {
X  		old_char = *string;	/* Save char and */
X  		*string = '\n';		/* Assign '\n' for line_check */
X  		if (line_check(program, line->text, method) == MATCH) {
X  			*string = old_char; /* Restore char */
X  			return cur_line;    /* Found match */
X  		}
X  		*string = old_char;	/* No match, but restore char */
X  	}
X  }
X
X/* No match in last (or first) part of line. Check out rest of file */
X  do {
X  	line = (method == FORWARD) ? line->next : line->prev;
X  	if (line->text == NIL_PTR)	/* Header/tail */
X  		continue;
X  	if (line_check(program, line->text, method) == MATCH)
X  		return line;
X  } while (line != cur_line && quit == FALSE);
X
X/* No match found. */
X  return NIL_LINE;
X}
X
X/*
X * Line_check() checks the line (or rather string) for a match. Method
X * indicates FORWARD or REVERSE search. It scans through the whole string
X * until a match is found, or the end of the string is reached.
X */
Xint line_check(program, string, method)
Xregister REGEX *program;
Xchar *string;
XFLAG method;
X{
X  register char *textp = string;
X
X/* Assign start_ptr field. We might find a match right away! */
X  program->start_ptr = textp;
X
X/* If the match must be anchored, just check the string. */
X  if (program->status & BEGIN_LINE)
X  	return check_string(program, string, NIL_INT);
X  
X  if (method == REVERSE) {
X  	/* First move to the end of the string */
X  	for (textp = string; *textp != '\n'; textp++)
X  		;
X  	/* Start checking string until the begin of the string is met */
X  	while (textp >= string) {
X  		program->start_ptr = textp;
X  		if (check_string(program, textp--, NIL_INT))
X  			return MATCH;
X  	}
X  }
X  else {
X  	/* Move through the string until the end of is found */
X	while (quit == FALSE && *textp != '\0') {
X  		program->start_ptr = textp;
X  		if (check_string(program, textp, NIL_INT))
X  			return MATCH;
X		if (*textp == '\n')
X			break;
X		textp++;
X  	}
X  }
X
X  return NO_MATCH;
X}
X
X/*
X * Check() checks of a match can be found in the given string. Whenever a STAR
X * is found during matching, then the begin position of the string is marked
X * and the maximum number of matches is performed. Then the function star()
X * is called which starts to finish the match from this position of the string
X * (and expression). Check() return MATCH for a match, NO_MATCH is the string 
X * couldn't be matched or REG_ERROR for an illegal opcode in expression.
X */
Xint check_string(program, string, expression)
XREGEX *program;
Xregister char *string;
Xint *expression;
X{
X  register int opcode;		/* Holds opcode of next expr. atom */
X  char c;				/* Char that must be matched */
X  char *mark;			/* For marking position */
X  int star_fl;			/* A star has been born */
X
X  if (expression == NIL_INT)
X  	expression = program->result.expression;
X
X/* Loop until end of string or end of expression */
X  while (quit == FALSE && !(*expression & DONE) &&
X					   *string != '\0' && *string != '\n') {
X  	c = *expression & LOW_BYTE;	  /* Extract match char */
X  	opcode = *expression & HIGH_BYTE; /* Extract opcode */
X  	if (star_fl = (opcode & STAR)) {  /* Check star occurrence */
X  		opcode &= ~STAR;	  /* Strip opcode */
X  		mark = string;		  /* Mark current position */
X  	}
X  	expression++;		/* Increment expr. */
X  	switch (opcode) {
X  	case NORMAL :
X  		if (star_fl)
X  			while (*string++ == c)	/* Skip all matches */
X  				;
X  		else if (*string++ != c)
X  			return NO_MATCH;
X  		break;
X  	case DOT :
X  		string++;
X  		if (star_fl)			/* Skip to eoln */
X  			while (*string != '\0' && *string++ != '\n')
X  				;
X  		break;
X  	case NEGATE | BRACKET:
X  	case BRACKET :
X  		if (star_fl)
X  			while (in_list(expression, *string++, c, opcode)
X								       == MATCH)
X  				;
X  		else if (in_list(expression, *string++, c, opcode) == NO_MATCH)
X  			return NO_MATCH;
X  		expression += c - 1;	/* Add length of list */
X  		break;
X  	default :
X  		panic("Corrupted program in check_string()");
X  	}
X  	if (star_fl) 
X  		return star(program, mark, string, expression);
X  }
X  if (*expression & DONE) {
X  	program->end_ptr = string;	/* Match ends here */
X  	/*
X  	 * We might have found a match. The last thing to do is check
X  	 * whether a '$' was given at the end of the expression, or
X  	 * the match was found on a null string. (E.g. [a-z]* always
X  	 * matches) unless a ^ or $ was included in the pattern.
X  	 */
X  	if ((*expression & EOLN) && *string != '\n' && *string != '\0')
X  		return NO_MATCH;
X	if (string == program->start_ptr && !(program->status & BEGIN_LINE)
X					 && !(*expression & EOLN))
X  		return NO_MATCH;
X  	return MATCH;
X  }
X  return NO_MATCH;
X}
X
X/*
X * Star() calls check_string() to find out the longest match possible.
X * It searches backwards until the (in check_string()) marked position
X * is reached, or a match is found.
X */
Xint star(program, end_position, string, expression)
XREGEX *program;
Xregister char *end_position;
Xregister char *string;
Xint *expression;
X{
X  do {
X  	string--;
X  	if (check_string(program, string, expression))
X  		return MATCH;
X  } while (string != end_position);
X
X  return NO_MATCH;
X}
X
X/*
X * In_list() checks if the given character is in the list of []. If it is
X * it returns MATCH. if it isn't it returns NO_MATCH. These returns values
X * are reversed when the NEGATE field in the opcode is present.
X */
Xint in_list(list, c, list_length, opcode)
Xregister int *list;
Xchar c;
Xregister int list_length;
Xint opcode;
X{
X  if (c == '\0' || c == '\n')	/* End of string, never matches */
X  	return NO_MATCH;
X  while (list_length-- > 1) {	/* > 1, don't check acct_field */
X  	if ((*list & LOW_BYTE) == c)
X  		return (opcode & NEGATE) ? NO_MATCH : MATCH;
X  	list++;
X  }
X  return (opcode & NEGATE) ? MATCH : NO_MATCH;
X}
X
X/*
X * Dummy_line() adds an empty line at the end of the file. This is sometimes
X * useful in combination with the EF and DN command in combination with the
X * Yank command set.
X */
Xvoid dummy_line()
X{
X	(void) line_insert(tail->prev, "\n", 1);
X	tail->prev->shift_count = DUMMY;
X	if (last_y != screenmax) {
X		last_y++;
X		bot_line = bot_line->next;
X	}
X}
/
