xref: /dragonfly/bin/mined/mined1.c (revision 0de61e28)
1 /*
2  *      Copyright (c) 1987,1997, Prentice Hall
3  *      All rights reserved.
4  *
5  *      Redistribution and use of the MINIX operating system in source and
6  *      binary forms, with or without modification, are permitted provided
7  *      that the following conditions are met:
8  *
9  *         * Redistributions of source code must retain the above copyright
10  *           notice, this list of conditions and the following disclaimer.
11  *
12  *         * Redistributions in binary form must reproduce the above
13  *           copyright notice, this list of conditions and the following
14  *           disclaimer in the documentation and/or other materials provided
15  *           with the distribution.
16  *
17  *         * Neither the name of Prentice Hall nor the names of the software
18  *           authors or contributors may be used to endorse or promote
19  *           products derived from this software without specific prior
20  *           written permission.
21  *
22  *      THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, AND
23  *      CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
24  *      INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25  *      MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26  *      IN NO EVENT SHALL PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE
27  *      LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  *      CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  *      SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
30  *      BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
31  *      WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
32  *      OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
33  *      EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  *
35  * [original code from minix codebase]
36  */
37 /*
38  * Part one of the mined editor.
39  */
40 
41 /*
42  * Ported to FreeBSD by Andrzej Bialecki <abial@freebsd.org>, Oct 1998
43  *
44  * Added a help screen, and remapped some of the wildest keybindings...
45  */
46 
47 /*
48  * Author: Michiel Huisjes.
49  *
50  * 1. General remarks.
51  *
52  *   Mined is a screen editor designed for the MINIX operating system.
53  *   It is meant to be used on files not larger than 50K and to be fast.
54  *   When mined starts up, it reads the file into its memory to minimize
55  *   disk access. The only time that disk access is needed is when certain
56  *   save, write or copy commands are given.
57  *
58  *   Mined has the style of Emacs or Jove, that means that there are no modes.
59  *   Each character has its own entry in an 256 pointer to function array,
60  *   which is called when that character is typed. Only ASCII characters are
61  *   connected with a function that inserts that character at the current
62  *   location in the file. Two execptions are <linefeed> and <tab> which are
63  *   inserted as well. Note that the mapping between commands and functions
64  *   called is implicit in the table. Changing the mapping just implies
65  *   changing the pointers in this table.
66  *
67  *   The display consists of SCREENMAX + 1 lines and XMAX + 1 characters. When
68  *   a line is larger (or gets larger during editing) than XBREAK characters,
69  *   the line is either shifted SHIFT_SIZE characters to the left (which means
70  *   that the first SHIFT_SIZE characters are not printed) or the end of the
71  *   line is marked with the SHIFT_MARK character and the rest of the line is
72  *   not printed.  A line can never exceed MAX_CHARS characters. Mined will
73  *   always try to keep the cursor on the same line and same (relative)
74  *   x-coordinate if nothing changed. So if you scroll one line up, the cursor
75  *   stays on the same line, or when you move one line down, the cursor will
76  *   move to the same place on the line as it was on the previous.
77  *   Every character on the line is available for editing including the
78  *   linefeed at the the of the line. When the linefeed is deleted, the current
79  *   line and the next line are joined. The last character of the file (which
80  *   is always a linefeed) can never be deleted.
81  *   The bottomline (as indicated by YMAX + 1) is used as a status line during
82  *   editing. This line is usually blank or contains information mined needs
83  *   during editing. This information (or rather questions) is displayed in
84  *   reverse video.
85  *
86  *   The terminal modes are changed completely. All signals like start/stop,
87  *   interrupt etc. are unset. The only signal that remains is the quit signal.
88  *   The quit signal (^\) is the general abort signal for mined. Typing a ^\
89  *   during searching or when mined is asking for filenames, etc. will abort
90  *   the function and mined will return to the main loop.  Sending a quit
91  *   signal during the main loop will abort the session (after confirmation)
92  *   and the file is not (!) saved.
93  *   The session will also be aborted when an unrecoverable error occurs. E.g
94  *   when there is no more memory available. If the file has been modified,
95  *   mined will ask if the file has to be saved or not.
96  *   If there is no more space left on the disk, mined will just give an error
97  *   message and continue.
98  *
99  *   The number of system calls are minized. This is done to keep the editor
100  *   as fast as possible. I/O is done in SCREEN_SIZE reads/writes. Accumulated
101  *   output is also flushed at the end of each character typed.
102  *
103  * 2. Regular expressions
104  *
105  *   Mined has a build in regular expression matcher, which is used for
106  *   searching and replace routines. A regular expression consists of a
107  *   sequence of:
108  *
109  *      1. A normal character matching that character.
110  *      2. A . matching any character.
111  *      3. A ^ matching the begin of a line.
112  *      4. A $ (as last character of the pattern) mathing the end of a line.
113  *      5. A \<character> matching <character>.
114  *      6. A number of characters enclosed in [] pairs matching any of these
115  *        characters. A list of characters can be indicated by a '-'. So
116  *        [a-z] matches any letter of the alphabet. If the first character
117  *        after the '[' is a '^' then the set is negated (matching none of
118  *        the characters).
119  *        A ']', '^' or '-' can be escaped by putting a '\' in front of it.
120  *        Of course this means that a \ must be represented by \\.
121  *      7. If one of the expressions as described in 1-6 is followed by a
122  *        '*' than that expressions matches a sequence of 0 or more of
123  *        that expression.
124  *
125  *   Parsing of regular expression is done in two phases. In the first phase
126  *   the expression is compiled into a more comprehensible form. In the second
127  *   phase the actual matching is done. For more details see 3.6.
128  *
129  *
130  * 3. Implementation of mined.
131  *
132  *   3.1 Data structures.
133  *
134  *      The main data structures are as follows. The whole file is kept in a
135  *      double linked list of lines. The LINE structure looks like this:
136  *
137  *         typedef struct Line {
138  *              struct Line *next;
139  *              struct Line *prev;
140  *              char *text;
141  *              unsigned char shift_count;
142  *         } LINE;
143  *
144  *      Each line entry contains a pointer to the next line, a pointer to the
145  *      previous line and a pointer to the text of that line. A special field
146  *      shift_count contains the number of shifts (in units of SHIFT_SIZE)
147  *      that is performed on that line. The total size of the structure is 7
148  *      bytes so a file consisting of 1000 empty lines will waste a lot of
149  *      memory. A LINE structure is allocated for each line in the file. After
150  *      that the number of characters of the line is counted and sufficient
151  *      space is allocated to store them (including a linefeed and a '\0').
152  *      The resulting address is assigned to the text field in the structure.
153  *
154  *      A special structure is allocated and its address is assigned to the
155  *      variable header as well as the variable tail. The text field of this
156  *      structure is set to NIL_PTR. The tail->prev of this structure points
157  *      to the last LINE of the file and the header->next to the first LINE.
158  *      Other LINE *variables are top_line and bot_line which point to the
159  *      first line resp. the last line on the screen.
160  *      Two other variables are important as well. First the LINE *cur_line,
161  *      which points to the LINE currently in use and the char *cur_text,
162  *      which points to the character at which the cursor stands.
163  *      Whenever an ASCII character is typed, a new line is build with this
164  *      character inserted. Then the old data space (pointed to by
165  *      cur_line->text) is freed, data space for the new line is allocated and
166  *      assigned to cur_line->text.
167  *
168  *      Two global variables called x and y represent the x and y coordinates
169  *      from the cursor. The global variable nlines contains the number of
170  *      lines in the file. Last_y indicates the maximum y coordinate of the
171  *      screen (which is usually SCREENMAX).
172  *
173  *      A few strings must be initialized by hand before compiling mined.
174  *      These string are enter_string, which is printed upon entering mined,
175  *      rev_video (turn on reverse video), normal_video, rev_scroll (perform a
176  *      reverse scroll) and pos_string. The last string should hold the
177  *      absolute position string to be printed for cursor motion. The #define
178  *      X_PLUS and Y_PLUS should contain the characters to be added to the
179  *      coordinates x and y (both starting at 0) to finish cursor positioning.
180  *
181  *   3.2 Starting up.
182  *
183  *      Mined can be called with or without argument and the function
184  *      load_file () is called with these arguments. load_file () checks
185  *      if the file exists if it can be read and if it is writable and
186  *      sets the writable flag accordingly. If the file can be read,
187  *      load_file () reads a line from the file and stores this line into
188  *      a structure by calling install_line () and line_insert () which
189  *      installs the line into the double linked list, until the end of the
190  *      file is reached.
191  *      Lines are read by the function get_line (), which buffers the
192  *      reading in blocks of SCREEN_SIZE. Load_file () also initializes the
193  *      LINE *variables described above.
194  *
195  *   3.3 Moving around.
196  *
197  *      Several commands are implemented for moving through the file.
198  *      Moving up (UP), down (DN) left (LF) and right (RT) are done by the
199  *      arrow keys. Moving one line below the screen scrolls the screen one
200  *      line up. Moving one line above the screen scrolls the screen one line
201  *      down. The functions forward_scroll () and reverse_scroll () take care
202  *      of that.
203  *      Several other move functions exist: move to begin of line (BL), end of
204  *      line (EL) top of screen (HIGH), bottom of screen (LOW), top of file
205  *      (HO), end of file (EF), scroll one page down (PD), scroll one page up
206  *      (PU), scroll one line down (SD), scroll one line up (SU) and move to a
207  *      certain line number (GOTO).
208  *      Two functions called MN () and MP () each move one word further or
209  *      backwards. A word is a number of non-blanks seperated by a space, a
210  *      tab or a linefeed.
211  *
212  *   3.4 Modifying text.
213  *
214  *      The modifying commands can be separated into two modes. The first
215  *      being inserting text, and the other deleting text. Two functions are
216  *      created for these purposes: insert () and delete (). Both are capable
217  *      of deleting or inserting large amounts of text as well as one
218  *      character. Insert () must be given the line and location at which
219  *      the text must be inserted. Is doesn't make any difference whether this
220  *      text contains linefeeds or not. Delete () must be given a pointer to
221  *      the start line, a pointer from where deleting should start on that
222  *      line and the same information about the end position. The last
223  *      character of the file will never be deleted. Delete () will make the
224  *      necessary changes to the screen after deleting, but insert () won't.
225  *      The functions for modifying text are: insert one char (S), insert a
226  *      file (file_insert (fd)), insert a linefeed and put cursor back to
227  *      end of line (LIB), delete character under the cursor (DCC), delete
228  *      before cursor (even linefeed) (DPC), delete next word (DNW), delete
229  *      previous word (DPC) and delete to end of line (if the cursor is at
230  *      a linefeed delete line) (DLN).
231  *
232  *   3.5 Yanking.
233  *
234  *      A few utilities are provided for yanking pieces of text. The function
235  *      MA () marks the current position in the file. This is done by setting
236  *      LINE *mark_line and char *mark_text to the current position. Yanking
237  *      of text can be done in two modes. The first mode just copies the text
238  *      from the mark to the current position (or visa versa) into a buffer
239  *      (YA) and the second also deletes the text (DT). Both functions call
240  *      the function set_up () with the delete flag on or off. Set_up ()
241  *      checks if the marked position is still a valid one (by using
242  *      check_mark () and legal ()), and then calls the function yank () with
243  *      a start and end position in the file. This function copies the text
244  *      into a scratch_file as indicated by the variable yank_file. This
245  *      scratch_file is made uniq by the function scratch_file (). At the end
246  *      of copying yank will (if necessary) delete the text. A global flag
247  *      called yank_status keeps track of the buffer (or file) status. It is
248  *      initialized on NOT_VALID and set to EMPTY (by set_up ()) or VALID (by
249  *      yank ()). Several things can be done with the buffer. It can be
250  *      inserted somewhere else in the file (PT) or it can be copied into
251  *      another file (WB), which will be prompted for.
252  *
253  *   3.6 Search and replace routines.
254  *
255  *      Searching for strings and replacing strings are done by regular
256  *      expressions. For any expression the function compile () is called
257  *      with as argument the expression to compile. Compile () returns a
258  *      pointer to a structure which looks like this:
259  *
260  *         typedef struct regex {
261  *              union {
262  *                    char *err_mess;
263  *                    int *expression;
264  *              } result;
265  *              char status;
266  *              char *start_ptr;
267  *              char *end_ptr;
268  *         } REGEX;
269  *
270  *    If something went wrong during compiling (e.g. an illegal expression
271  *    was given), the function reg_error () is called, which sets the status
272  *    field to REG_ERROR and the err_mess field to the error message. If the
273  *    match must be anchored at the beginning of the line (end of line), the
274  *    status field is set to BEGIN_LINE (END_LINE). If none of these special
275  *    cases are true, the field is set to 0 and the function finished () is
276  *    called.  Finished () allocates space to hold the compiled expression
277  *    and copies this expression into the expression field of the union
278  *    (bcopy ()). Matching is done by the routines match() and line_check().
279  *    Match () takes as argument the REGEX *program, a pointer to the
280  *    startposition on the current line, and a flag indicating FORWARD or
281  *    REVERSE search.  Match () checks out the whole file until a match is
282  *    found. If match is found it returns a pointer to the line in which the
283  *    match was found else it returns a NIL_LINE. Line_check () takes the
284  *    same arguments, but return either MATCH or NO_MATCH.
285  *    During checking, the start_ptr and end_ptr fields of the REGEX
286  *    structure are assigned to the start and end of the match.
287  *    Both functions try to find a match by walking through the line
288  *    character by character. For each possibility, the function
289  *    check_string () is called with as arguments the REGEX *program and the
290  *    string to search in. It starts walking through the expression until
291  *    the end of the expression or the end of the string is reached.
292  *    Whenever a * is encountered, this position of the string is marked,
293  *    the maximum number of matches are performed and the function star ()
294  *    is called in order to try to find the longest match possible. Star ()
295  *    takes as arguments the REGEX program, the current position of the
296  *    string, the marked position and the current position of the expression
297  *    Star () walks from the current position of the string back to the
298  *    marked position, and calls string_check () in order to find a match.
299  *    It returns MATCH or NO_MATCH, just as string_check () does.
300  *    Searching is now easy. Both search routines (forward (SF) and
301  *    backwards search (SR)) call search () with an apropiate message and a
302  *    flag indicating FORWARD or REVERSE search. Search () will get an
303  *    expression from the user by calling get_expression(). Get_expression()
304  *    returns a pointer to a REGEX structure or NIL_REG upon errors and
305  *    prompts for the expression. If no expression if given, the previous is
306  *    used instead. After that search will call match (), and if a match is
307  *    found, we can move to that place in the file by the functions find_x()
308  *    and find_y () which will find display the match on the screen.
309  *    Replacing can be done in two ways. A global replace (GR) or a line
310  *    replace (LR). Both functions call change () with a message an a flag
311  *    indicating global or line replacement. Change () will prompt for the
312  *    expression and for the replacement. Every & in the replacement pattern
313  *    means substitute the match instead. An & can be escaped by a \. When
314  *    a match is found, the function substitute () will perform the
315  *    substitution.
316  *
317  *  3.6 Miscellaneous commands.
318  *
319  *    A few commands haven't be discussed yet. These are redraw the screen
320  *    (RD) fork a shell (SH), print file status (FS), write file to disc
321  *    (WT), insert a file at current position (IF), leave editor (XT) and
322  *    visit another file (VI). The last two functions will check if the file
323  *    has been modified. If it has, they will ask if you want to save the
324  *    file by calling ask_save ().
325  *    The function ESC () will repeat a command n times. It will prompt for
326  *    the number. Aborting the loop can be done by sending the ^\ signal.
327  *
328  *  3.7 Utility functions.
329  *
330  *    Several functions exists for internal use. First allocation routines:
331  *    alloc (bytes) and newline () will return a pointer to free data space
332  *    if the given size. If there is no more memory available, the function
333  *    panic () is called.
334  *    Signal handling: The only signal that can be send to mined is the
335  *    SIGQUIT signal. This signal, functions as a general abort command.
336  *    Mined will abort if the signal is given during the main loop. The
337  *    function abort_mined () takes care of that.
338  *    Panic () is a function with as argument a error message. It will print
339  *    the message and the error number set by the kernel (errno) and will
340  *    ask if the file must be saved or not. It resets the terminal
341  *    (raw_mode ()) and exits.
342  *    String handling routines like copy_string(to, from), length_of(string)
343  *    and build_string (buffer, format, arg1, arg2, ...). The latter takes
344  *    a description of the string out out the format field and puts the
345  *    result in the buffer. (It works like printf (3), but then into a
346  *    string). The functions status_line (string1, string2), error (string1,
347  *    string2), clear_status () and bottom_line () all print information on
348  *    the status line.
349  *    Get_string (message, buffer) reads a string and getchar () reads one
350  *    character from the terminal.
351  *    Num_out ((long) number) prints the number into a 11 digit field
352  *    without leading zero's. It returns a pointer to the resulting string.
353  *    File_status () prints all file information on the status line.
354  *    Set_cursor (x, y) prints the string to put the cursor at coordinates
355  *    x and y.
356  *    Output is done by four functions: writeline(fd,string), clear_buffer()
357  *    write_char (fd, c) and flush_buffer (fd). Three defines are provided
358  *    to write on filedescriptor STD_OUT (terminal) which is used normally:
359  *    string_print (string), putchar (c) and flush (). All these functions
360  *    use the global I/O buffer screen and the global index for this array
361  *    called out_count. In this way I/O can be buffered, so that reads or
362  *    writes can be done in blocks of SCREEN_SIZE size.
363  *    The following functions all handle internal line maintenance. The
364  *    function proceed (start_line, count) returns the count'th line after
365  *    start_line.  If count is negative, the count'th line before the
366  *    start_line is returned. If header or tail is encountered then that
367  *    will be returned. Display (x, y, start_line, count) displays count
368  *    lines starting at coordinates [x, y] and beginning at start_line. If
369  *    the header or tail is encountered, empty lines are displayed instead.
370  *    The function reset (head_line, ny) reset top_line, last_y, bot_line,
371  *    cur_line and y-coordinate. This is not a neat way to do the
372  *    maintenance, but it sure saves a lot of code. It is usually used in
373  *    combination with display ().
374  *    Put_line(line, offset, clear_line), prints a line (skipping characters
375  *    according to the line->shift_size field) until XBREAK - offset
376  *    characters are printed or a '\n' is encountered. If clear_line is
377  *	  TRUE, spaces are printed until XBREAK - offset characters.
378  *	  Line_print (line) is a #define from put_line (line, 0, TRUE).
379  *    Moving is done by the functions move_to (x, y), move_addres (address)
380  *    and move (x, adress, y). This function is the most important one in
381  *    mined. New_y must be between 0 and last_y, new_x can be about
382  *    anything, address must be a pointer to an character on the current
383  *    line (or y). Move_to () first adjust the y coordinate together with
384  *    cur_line. If an address is given, it finds the corresponding
385  *    x-coordinate. If an new x-coordinate was given, it will try to locate
386  *    the corresponding character. After that it sets the shift_count field
387  *    of cur_line to an apropiate number according to new_x. The only thing
388  *    left to do now is to assign the new values to cur_line, cur_text, x
389  *    and y.
390  *
391  * 4. Summary of commands.
392  *
393  *  CURSOR MOTION
394  *    up-arrow  Move cursor 1 line up.  At top of screen, reverse scroll
395  *    down-arrow  Move cursor 1 line down.  At bottom, scroll forward.
396  *    left-arrow  Move cursor 1 character left or to end of previous line
397  *    right-arrow Move cursor 1 character right or to start of next line
398  *    CTRL-A   Move cursor to start of current line
399  *    CTRL-Z   Move cursor to end of current line
400  *    CTRL-^   Move cursor to top of screen
401  *    CTRL-_   Move cursor to bottom of screen
402  *    CTRL-F   Forward to start of next word (even to next line)
403  *    CTRL-B   Backward to first character of previous word
404  *
405  *  SCREEN MOTION
406  *    Home key  Move cursor to first character of file
407  *    End key   Move cursor to last character of file
408  *    PgUp    Scroll backward 1 page. Bottom line becomes top line
409  *    PgD    Scroll backward 1 page. Top line becomes bottom line
410  *    CTRL-D   Scroll screen down one line (reverse scroll)
411  *    CTRL-U   Scroll screen up one line (forward scroll)
412  *
413  *  MODIFYING TEXT
414  *    ASCII char  Self insert character at cursor
415  *    tab    Insert tab at cursor
416  *    backspace  Delete the previous char (left of cursor), even line feed
417  *    Del    Delete the character under the cursor
418  *    CTRL-N   Delete next word
419  *    CTRL-P   Delete previous word
420  *    CTRL-O   Insert line feed at cursor and back up 1 character
421  *    CTRL-T   Delete tail of line (cursor to end); if empty, delete line
422  *    CTRL-@   Set the mark (remember the current location)
423  *    CTRL-K   Delete text from the mark to current position save on file
424  *    CTRL-C   Save the text from the mark to the current position
425  *    CTRL-Y   Insert the contents of the save file at current position
426  *    CTRL-Q   Insert the contents of the save file into a new file
427  *    CTRL-G   Insert a file at the current position
428  *
429  *  MISCELLANEOUS
430  *    CTRL-L   Erase and redraw the screen
431  *    CTRL-V   Visit file (read a new file); complain if old one changed
432  *    CTRL-W   Write the current file back to the disk
433  *    numeric +  Search forward (prompt for regular expression)
434  *    numeric -  Search backward (prompt for regular expression)
435  *    numeric 5  Print the current status of the file
436  *    CTRL-R   (Global) Replace str1 by str2 (prompts for each string)
437  *    [UNASS]  (Line) Replace string1 by string2
438  *    CTRL-S   Fork off a shell and wait for it to finish
439  *    CTRL-X   EXIT (prompt if file modified)
440  *    CTRL-]   Go to a line. Prompts for linenumber
441  *    CTRL-\   Abort whatever editor was doing and start again
442  *    escape key  Repeat a command count times; (prompts for count)
443  */
444 
445 /*  ========================================================================  *
446  *				Utilities				      *
447  *  ========================================================================  */
448 
449 #include "mined.h"
450 #include <signal.h>
451 #include <termios.h>
452 #include <limits.h>
453 #include <errno.h>
454 #include <sys/wait.h>
455 #include <sys/ioctl.h>
456 #include <stdarg.h>
457 #include <stdlib.h>
458 
459 int ymax = YMAX;
460 int screenmax = SCREENMAX;
461 
462 
463 /*
464  * Print file status.
465  */
466 void
467 FS(int u __unused)
468 {
469   fstatus(file_name[0] ? "" : "[buffer]", -1L);
470 }
471 
472 /*
473  * Visit (edit) another file. If the file has been modified, ask the user if
474  * he wants to save it.
475  */
476 void
477 VI(int u __unused)
478 {
479   char new_file[LINE_LEN];	/* Buffer to hold new file name */
480 
481   if (modified == TRUE && ask_save() == ERRORS)
482 	return;
483 
484 /* Get new file name */
485   if (get_file("Visit file:", new_file) == ERRORS)
486 	return;
487 
488 /* Free old linked list, initialize global variables and load new file */
489   initialize();
490 #ifdef UNIX
491   tputs(CL, 0, _putchar);
492 #else
493   string_print (enter_string);
494 #endif /* UNIX */
495   load_file(new_file[0] == '\0' ? NIL_PTR : new_file);
496 }
497 
498 /*
499  * Write file in core to disc.
500  */
501 int
502 WT(void)
503 {
504   LINE *line;
505   long count = 0L;	/* Nr of chars written */
506   char file[LINE_LEN];		/* Buffer for new file name */
507   int fd;				/* Filedescriptor of file */
508 
509   if (modified == FALSE) {
510 	error ("Write not necessary.", NIL_PTR);
511 	return FINE;
512   }
513 
514 /* Check if file_name is valid and if file can be written */
515   if (file_name[0] == '\0' || writable == FALSE) {
516 	if (get_file("Enter file name:", file) != FINE)
517 		return ERRORS;
518 	copy_string(file_name, file);		/* Save file name */
519   }
520   if ((fd = creat(file_name, 0644)) < 0) {	/* Empty file */
521 	error("Cannot create ", file_name);
522 	writable = FALSE;
523 	return ERRORS;
524   }
525   else
526 	writable = TRUE;
527 
528   clear_buffer();
529 
530   status_line("Writing ", file_name);
531   for (line = header->next; line != tail; line = line->next) {
532 	if (line->shift_count & DUMMY) {
533 		if (line->next == tail && line->text[0] == '\n')
534 			continue;
535 	}
536 	if (writeline(fd, line->text) == ERRORS) {
537 		count = -1L;
538 		break;
539 	}
540 	count += (long) length_of(line->text);
541   }
542 
543   if (count > 0L && flush_buffer(fd) == ERRORS)
544 	count = -1L;
545 
546   close(fd);
547 
548   if (count == -1L)
549 	return ERRORS;
550 
551   modified = FALSE;
552   rpipe = FALSE;		/* File name is now assigned */
553 
554 /* Display how many chars (and lines) were written */
555   fstatus("Wrote", count);
556   return FINE;
557 }
558 
559 /* Call WT and discard value returned. */
560 void
561 XWT(int u __unused)
562 {
563   WT();
564 }
565 
566 
567 
568 /*
569  * Call an interactive shell.
570  */
571 void
572 SH(int u __unused)
573 {
574   int w;
575   int pid, status;
576   const char *shell;
577 
578   if ((shell = getenv("SHELL")) == NIL_PTR) shell = "/bin/sh";
579 
580   switch (pid = fork()) {
581 	case -1:			/* Error */
582 		error("Cannot fork.", NIL_PTR);
583 		return;
584 	case 0:				/* This is the child */
585 		set_cursor(0, ymax);
586 		putchar('\n');
587 		flush();
588 		raw_mode(OFF);
589 		if (rpipe) {			/* Fix stdin */
590 			close (0);
591 			if (open("/dev/tty", 0) < 0)
592 				exit (126);
593 		}
594 		execl(shell, shell, NULL);
595 		exit(127);			/* Exit with 127 */
596 	default :				/* This is the parent */
597 		signal(SIGINT, SIG_IGN);
598 		signal(SIGQUIT, SIG_IGN);
599 		do {
600 			w = wait(&status);
601 		} while (w != -1 && w != pid);
602   }
603 
604   raw_mode(ON);
605   RD(0);
606 
607   if ((status >> 8) == 127)		/* Child died with 127 */
608 	error("Cannot exec ", shell);
609   else if ((status >> 8) == 126)
610 	error("Cannot open /dev/tty as fd #0", NIL_PTR);
611 }
612 
613 /*
614  * Proceed returns the count'th line after `line'. When count is negative
615  * it returns the count'th line before `line'. When the next (previous)
616  * line is the tail (header) indicating EOF (tof) it stops.
617  */
618 LINE *
619 proceed(LINE *line, int count)
620 {
621   if (count < 0)
622 	while (count++ < 0 && line != header)
623 		line = line->prev;
624   else
625 	while (count-- > 0 && line != tail)
626 		line = line->next;
627   return line;
628 }
629 
630 /*
631  * Show concatenation of s1 and s2 on the status line (bottom of screen)
632  * If revfl is TRUE, turn on reverse video on both strings. Set stat_visible
633  * only if bottom_line is visible.
634  */
635 int
636 bottom_line(FLAG revfl, const char *s1, const char *s2, char *inbuf,
637 	    FLAG statfl)
638 {
639   int ret = FINE;
640   char buf[LINE_LEN];
641   char *p = buf;
642 
643   *p++ = ' ';
644   if (s1 != NIL_PTR)
645 	while ((*p = *s1++) != 0)
646 		p++;
647   if (s2 != NIL_PTR)
648 	while ((*p = *s2++) != 0)
649 		p++;
650   *p++ = ' ';
651   *p++ = 0;
652 
653   if (revfl == ON && stat_visible == TRUE)
654 	clear_status ();
655   set_cursor(0, ymax);
656   if (revfl == ON) {		/* Print rev. start sequence */
657 #ifdef UNIX
658 	tputs(SO, 0, _putchar);
659 #else
660 	string_print(rev_video);
661 #endif /* UNIX */
662 	stat_visible = TRUE;
663   }
664   else				/* Used as clear_status() */
665 	stat_visible = FALSE;
666 
667   string_print(buf);
668 
669   if (inbuf != NIL_PTR)
670 	ret = input(inbuf, statfl);
671 
672   /* Print normal video */
673 #ifdef UNIX
674   tputs(SE, 0, _putchar);
675   tputs(CE, 0, _putchar);
676 #else
677   string_print(normal_video);
678   string_print(blank_line);	/* Clear the rest of the line */
679 #endif /* UNIX */
680   if (inbuf != NIL_PTR)
681 	set_cursor(0, ymax);
682   else
683 	set_cursor(x, y);	/* Set cursor back to old position */
684   flush();			/* Perform the actual write */
685   if (ret != FINE)
686 	clear_status();
687   return ret;
688 }
689 
690 /*
691  * Count_chars() count the number of chars that the line would occupy on the
692  * screen. Counting starts at the real x-coordinate of the line.
693  */
694 int
695 count_chars(LINE *line)
696 {
697   int cnt = get_shift(line->shift_count) * -SHIFT_SIZE;
698   char *textp = line->text;
699 
700 /* Find begin of line on screen */
701   while (cnt < 0) {
702 	if (is_tab(*textp++))
703 		cnt = tab(cnt);
704 	else
705 		cnt++;
706   }
707 
708 /* Count number of chars left */
709   cnt = 0;
710   while (*textp != '\n') {
711 	if (is_tab(*textp++))
712 		 cnt = tab(cnt);
713 	else
714 		cnt++;
715   }
716   return cnt;
717 }
718 
719 /*
720  * Move to coordinates nx, ny at screen.  The caller must check that scrolling
721  * is not needed.
722  * If new_x is lower than 0 or higher than XBREAK, move_to() will check if
723  * the line can be shifted. If it can it sets(or resets) the shift_count field
724  * of the current line accordingly.
725  * Move also sets cur_text to the right char.
726  * If we're moving to the same x coordinate, try to move the the x-coordinate
727  * used on the other previous call.
728  */
729 void
730 move(int new_x, char *new_address, int new_y)
731 {
732   LINE *line = cur_line;	/* For building new cur_line */
733   int shift = 0;			/* How many shifts to make */
734   static int rel_x = 0;		/* Remember relative x position */
735   int tx = x;
736 
737 /* Check for illegal values */
738   if (new_y < 0 || new_y > last_y)
739 	return;
740 
741 /* Adjust y-coordinate and cur_line */
742   if (new_y < y)
743 	while (y != new_y) {
744 		if(line->shift_count>0) {
745 			line->shift_count=0;
746 			move_to(0,y);
747 			string_print(blank_line);
748 			line_print(line);
749 		}
750 		y--;
751 		line = line->prev;
752 	}
753   else
754 	while (y != new_y) {
755 		if(line->shift_count>0) {
756 			line->shift_count=0;
757 			move_to(0,y);
758 			string_print(blank_line);
759 			line_print(line);
760 		}
761 		y++;
762 		line = line->next;
763 	}
764 
765 /* Set or unset relative x-coordinate */
766   if (new_address == NIL_PTR) {
767 	new_address = find_address(line, (new_x == x) ? rel_x : new_x , &tx);
768 	if (new_x != x)
769 		rel_x = tx;
770 	new_x = tx;
771   }
772   else {
773 	rel_x = new_x = find_x(line, new_address);
774   }
775 
776 /* Adjust shift_count if new_x lower than 0 or higher than XBREAK */
777   if (new_x < 0 || new_x >= XBREAK) {
778 	if (new_x > XBREAK || (new_x == XBREAK && *new_address != '\n'))
779 		shift = (new_x - XBREAK) / SHIFT_SIZE + 1;
780 	else {
781 		shift = new_x / SHIFT_SIZE;
782 		if (new_x % SHIFT_SIZE)
783 			shift--;
784 	}
785 
786 	if (shift != 0) {
787 		line->shift_count += shift;
788 		new_x = find_x(line, new_address);
789 		set_cursor(0, y);
790 		line_print(line);
791 		rel_x = new_x;
792 	}
793   }
794 
795 /* Assign and position cursor */
796   x = new_x;
797   cur_text = new_address;
798   cur_line = line;
799   set_cursor(x, y);
800 }
801 
802 /*
803  * Find_x() returns the x coordinate belonging to address.
804  * (Tabs are expanded).
805  */
806 int
807 find_x(LINE *line, char *address)
808 {
809   char *textp = line->text;
810   int nx = get_shift(line->shift_count) * -SHIFT_SIZE;
811 
812   while (textp != address && *textp != '\0') {
813 	if (is_tab(*textp++))	/* Expand tabs */
814 		nx = tab(nx);
815 	else
816 		nx++;
817   }
818   return nx;
819 }
820 
821 /*
822  * Find_address() returns the pointer in the line with offset x_coord.
823  * (Tabs are expanded).
824  */
825 char *
826 find_address(LINE *line, int x_coord, int *old_x)
827 {
828   char *textp = line->text;
829   int tx = get_shift(line->shift_count) * -SHIFT_SIZE;
830 
831   while (tx < x_coord && *textp != '\n') {
832 	if (is_tab(*textp)) {
833 		if (*old_x - x_coord == 1 && tab(tx) > x_coord)
834 			break;		/* Moving left over tab */
835 		else
836 			tx = tab(tx);
837 	}
838 	else
839 		tx++;
840 	textp++;
841   }
842 
843   *old_x = tx;
844   return textp;
845 }
846 
847 /*
848  * Length_of() returns the number of characters int the string `string'
849  * excluding the '\0'.
850  */
851 int
852 length_of(char *string)
853 {
854   int count = 0;
855 
856   if (string != NIL_PTR) {
857 	while (*string++ != '\0')
858 		count++;
859   }
860   return count;
861 }
862 
863 /*
864  * Copy_string() copies the string `from' into the string `to'. `To' must be
865  * long enough to hold `from'.
866  */
867 void
868 copy_string(char *to, const char *from)
869 {
870   while ((*to++ = *from++) != 0)
871 	;
872 }
873 
874 /*
875  * Reset assigns bot_line, top_line and cur_line according to `head_line'
876  * which must be the first line of the screen, and an y-coordinate,
877  * which will be the current y-coordinate (if it isn't larger than last_y)
878  */
879 void
880 reset(LINE *head_line, int screen_y)
881 {
882   LINE *line;
883 
884   top_line = line = head_line;
885 
886 /* Search for bot_line (might be last line in file) */
887   for (last_y = 0; last_y < nlines - 1 && last_y < screenmax
888 						&& line->next != tail; last_y++)
889 	line = line->next;
890 
891   bot_line = line;
892   y = (screen_y > last_y) ? last_y : screen_y;
893 
894 /* Set cur_line according to the new y value */
895   cur_line = proceed(top_line, y);
896 }
897 
898 /*
899  * Set cursor at coordinates x, y.
900  */
901 void
902 set_cursor(int nx, int ny)
903 {
904 #ifdef UNIX
905   tputs(tgoto(CM, nx, ny), 0, _putchar);
906 #else
907   char text_buf[10];
908 
909   build_string(text_buf, pos_string, ny+1, nx+1);
910   string_print(text_buf);
911 #endif /* UNIX */
912 }
913 
914 /*
915  * Routine to open terminal when mined is used in a pipeline.
916  */
917 void
918 open_device(void)
919 {
920   if ((input_fd = open("/dev/tty", 0)) < 0)
921 	panic("Cannot open /dev/tty for read");
922 }
923 
924 /*
925  * Getchar() reads one character from the terminal. The character must be
926  * masked with 0377 to avoid sign extension.
927  */
928 int
929 getchar(void)
930 {
931 #ifdef UNIX
932   return (_getchar() & 0377);
933 #else
934   char c;
935 
936   if (read(input_fd, &c, 1) != 1 && quit == FALSE)
937 	panic("Can't read one char from fd #0");
938 
939   return c & 0377;
940 #endif /* UNIX */
941 }
942 
943 /*
944  * Display() shows count lines on the terminal starting at the given
945  * coordinates. When the tail of the list is encountered it will fill the
946  * rest of the screen with blank_line's.
947  * When count is negative, a backwards print from `line' will be done.
948  */
949 void
950 display(int x_coord, int y_coord, LINE *line, int count)
951 {
952   set_cursor(x_coord, y_coord);
953 
954 /* Find new startline if count is negative */
955   if (count < 0) {
956 	line = proceed(line, count);
957 	count = -count;
958   }
959 
960 /* Print the lines */
961   while (line != tail && count-- >= 0) {
962 	line->shift_count=0;
963 	line_print(line);
964 	line = line->next;
965   }
966 
967 /* Print the blank lines (if any) */
968   if (loading == FALSE) {
969 	while (count-- >= 0) {
970 #ifdef UNIX
971 		tputs(CE, 0, _putchar);
972 #else
973 		string_print(blank_line);
974 #endif /* UNIX */
975 		putchar('\n');
976 	}
977   }
978 }
979 
980 /*
981  * Write_char does a buffered output.
982  */
983 int
984 write_char(int fd, char c)
985 {
986   screen [out_count++] = c;
987   if (out_count == SCREEN_SIZE)		/* Flush on SCREEN_SIZE chars */
988 	return flush_buffer(fd);
989   return FINE;
990 }
991 
992 /*
993  * Writeline writes the given string on the given filedescriptor.
994  */
995 int
996 writeline(int fd, const char *text)
997 {
998   while(*text)
999 	 if (write_char(fd, *text++) == ERRORS)
1000 		return ERRORS;
1001   return FINE;
1002 }
1003 
1004 /*
1005  * Put_line print the given line on the standard output. If offset is not zero
1006  * printing will start at that x-coordinate. If the FLAG clear_line is TRUE,
1007  * then (screen) line will be cleared when the end of the line has been
1008  * reached.
1009  *
1010  * parameter
1011  * line:	Line to print
1012  * offset:	Offset to start
1013  * clear_line:	Clear to eoln if TRUE
1014  */
1015 void
1016 put_line(LINE *line, int offset, FLAG clear_line)
1017 {
1018   char *textp = line->text;
1019   int count = get_shift(line->shift_count) * -SHIFT_SIZE;
1020   int tab_count;			/* Used in tab expansion */
1021 
1022 /* Skip all chars as indicated by the offset and the shift_count field */
1023   while (count < offset) {
1024 	if (is_tab(*textp++))
1025 		count = tab(count);
1026 	else
1027 		count++;
1028   }
1029 
1030   while (*textp != '\n' && count < XBREAK) {
1031 	if (is_tab(*textp)) {		/* Expand tabs to spaces */
1032 		tab_count = tab(count);
1033 		while (count < XBREAK && count < tab_count) {
1034 			count++;
1035 			putchar(' ');
1036 		}
1037 		textp++;
1038 	}
1039 	else {
1040 		if (*textp >= '\01' && *textp <= '\037') {
1041 #ifdef UNIX
1042 			tputs(SO, 0, _putchar);
1043 #else
1044 			string_print (rev_video);
1045 #endif /* UNIX */
1046 			putchar(*textp++ + '\100');
1047 #ifdef UNIX
1048 			tputs(SE, 0, _putchar);
1049 #else
1050 			string_print (normal_video);
1051 #endif /* UNIX */
1052 		}
1053 		else
1054 			putchar(*textp++);
1055 		count++;
1056 	}
1057   }
1058 
1059 /* If line is longer than XBREAK chars, print the shift_mark */
1060   if (count == XBREAK && *textp != '\n')
1061 	putchar(textp[1]=='\n' ? *textp : SHIFT_MARK);
1062 
1063 /* Clear the rest of the line is clear_line is TRUE */
1064   if (clear_line == TRUE) {
1065 #ifdef	UNIX
1066 	tputs(CE, 0, _putchar);
1067 #else
1068 	string_print(blank_line);
1069 #endif /* UNIX */
1070 	putchar('\n');
1071   }
1072 }
1073 
1074 /*
1075  * Flush the I/O buffer on filedescriptor fd.
1076  */
1077 int
1078 flush_buffer(int fd)
1079 {
1080   if (out_count <= 0)		/* There is nothing to flush */
1081 	return FINE;
1082 #ifdef UNIX
1083   if (fd == STD_OUT) {
1084 	printf("%.*s", out_count, screen);
1085 	_flush();
1086   }
1087   else
1088 #endif /* UNIX */
1089   if (write(fd, screen, out_count) != out_count) {
1090 	bad_write(fd);
1091 	return ERRORS;
1092   }
1093   clear_buffer();		/* Empty buffer */
1094   return FINE;
1095 }
1096 
1097 /*
1098  * Bad_write() is called when a write failed. Notify the user.
1099  */
1100 void
1101 bad_write(int fd)
1102 {
1103   if (fd == STD_OUT)		/* Cannot write to terminal? */
1104 	exit(1);
1105 
1106   clear_buffer();
1107   build_string(text_buffer, "Command aborted: %s (File incomplete)",
1108 		            (errno == ENOSPC || errno == -ENOSPC) ?
1109 			    "No space on device" : "Write error");
1110   error(text_buffer, NIL_PTR);
1111 }
1112 
1113 /*
1114  * Catch the SIGQUIT signal (^\) send to mined. It turns on the quitflag.
1115  */
1116 void
1117 catch(int sig __unused)
1118 {
1119 /* Reset the signal */
1120   signal(SIGQUIT, catch);
1121   quit = TRUE;
1122 }
1123 
1124 /*
1125  * Abort_mined() will leave mined. Confirmation is asked first.
1126  */
1127 void
1128 abort_mined(void)
1129 {
1130   quit = FALSE;
1131 
1132 /* Ask for confirmation */
1133   status_line("Really abort? ", NIL_PTR);
1134   if (getchar() != 'y') {
1135 	clear_status();
1136 	return;
1137   }
1138 
1139 /* Reset terminal */
1140   raw_mode(OFF);
1141   set_cursor(0, ymax);
1142   putchar('\n');
1143   flush();
1144 #ifdef UNIX
1145   abort();
1146 #else
1147   exit(1);
1148 #endif /* UNIX */
1149 }
1150 
1151 #define UNDEF	_POSIX_VDISABLE
1152 
1153 /*
1154  * Set and reset tty into CBREAK or old mode according to argument `state'. It
1155  * also sets all signal characters (except for ^\) to UNDEF. ^\ is caught.
1156  */
1157 void
1158 raw_mode(FLAG state)
1159 {
1160   static struct termios old_tty;
1161   static struct termios new_tty;
1162 
1163   if (state == OFF) {
1164 	tcsetattr(input_fd, TCSANOW, &old_tty);
1165 	return;
1166   }
1167 
1168 /* Save old tty settings */
1169   tcgetattr(input_fd, &old_tty);
1170 
1171 /* Set tty to CBREAK mode */
1172   tcgetattr(input_fd, &new_tty);
1173   new_tty.c_lflag &= ~(ICANON|ECHO|ECHONL);
1174   new_tty.c_iflag &= ~(IXON|IXOFF|ISIG);
1175 
1176 /* Unset remaining signal chars, leave only SIGQUIT set to ^\ */
1177   new_tty.c_cc[VINTR] = new_tty.c_cc[VSUSP] = UNDEF;
1178   new_tty.c_cc[VQUIT] = '\\' & 037;
1179   signal(SIGQUIT, catch);		/* Which is caught */
1180 
1181   tcsetattr(input_fd, TCSANOW, &new_tty);
1182 }
1183 
1184 /*
1185  * Panic() is called with an error number and a message. It is called when
1186  * something unrecoverable has happened.
1187  * It writes the message to the terminal, resets the tty and exits.
1188  * Ask the user if he wants to save his file.
1189  */
1190 void
1191 panic(const char *message)
1192 {
1193 #ifdef UNIX
1194   tputs(CL, 0, _putchar);
1195   build_string(text_buffer, "%s\nError code %d\n", message, errno);
1196 #else
1197   build_string(text_buffer, "%s%s\nError code %d\n", enter_string, message, errno);
1198 #endif /* UNIX */
1199   write(STD_OUT, text_buffer, length_of(text_buffer));
1200 
1201   if (loading == FALSE)
1202 	XT(0);			/* Check if file can be saved */
1203   else
1204 	unlink(yank_file);
1205   raw_mode(OFF);
1206 
1207 #ifdef UNIX
1208   abort();
1209 #else
1210   exit(1);
1211 #endif /* UNIX */
1212 }
1213 
1214 void *
1215 alloc(int bytes)
1216 {
1217   char *p;
1218 
1219   p = malloc((unsigned) bytes);
1220   if (p == NIL_PTR) {
1221 	if (loading == TRUE)
1222 		panic("File too big.");
1223 	panic("Out of memory.");
1224   }
1225   return(p);
1226 }
1227 
1228 void
1229 free_space(char *p)
1230 {
1231   free(p);
1232 }
1233 
1234 /*  ========================================================================  *
1235  *				Main loops				      *
1236  *  ========================================================================  */
1237 
1238 /* The mapping between input codes and functions. */
1239 
1240 void (*key_map[256])(int) = {       /* map ASCII characters to functions */
1241    /* 000-017 */ MA, BL, MP, YA, SD, EL, MN, IF, DPC, S, S, DT, RD, S, DNW,LIB,
1242    /* 020-037 */ DPW, WB, GR, SH, DLN, SU, VI, XWT, XT, PT, ST, ESC, I, GOTO,
1243 		 HIGH, LOW,
1244    /* 040-057 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S,
1245    /* 060-077 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S,
1246    /* 100-117 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S,
1247    /* 120-137 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S,
1248    /* 140-157 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S,
1249    /* 160-177 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, DCC,
1250    /* 200-217 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S,
1251    /* 220-237 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S,
1252    /* 240-257 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S,
1253    /* 260-277 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S,
1254    /* 300-317 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S,
1255    /* 320-337 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S,
1256    /* 340-357 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S,
1257    /* 360-377 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S,
1258 };
1259 
1260 int nlines;			/* Number of lines in file */
1261 LINE *header;			/* Head of line list */
1262 LINE *tail;			/* Last line in line list */
1263 LINE *cur_line;			/* Current line in use */
1264 LINE *top_line;			/* First line of screen */
1265 LINE *bot_line;			/* Last line of screen */
1266 char *cur_text;			/* Current char on current line in use */
1267 int last_y;			/* Last y of screen. Usually SCREENMAX */
1268 char screen[SCREEN_SIZE];	/* Output buffer for "writes" and "reads" */
1269 
1270 int x, y;			/* x, y coordinates on screen */
1271 FLAG modified = FALSE;		/* Set when file is modified */
1272 FLAG stat_visible;		/* Set if status_line is visible */
1273 FLAG writable;			/* Set if file cannot be written */
1274 FLAG loading;			/* Set if we are loading a file. */
1275 FLAG quit = FALSE;		/* Set when quit character is typed */
1276 FLAG rpipe = FALSE;		/* Set if file should be read from stdin */
1277 int input_fd = 0;		/* Fd for command input */
1278 int out_count;			/* Index in output buffer */
1279 char file_name[LINE_LEN];	/* Name of file in use */
1280 char text_buffer[MAX_CHARS];	/* Buffer for modifying text */
1281 
1282 /* Escape sequences. */
1283 #ifdef UNIX
1284 char *CE, *VS, *SO, *SE, *CL, *AL, *CM;
1285 #else
1286 const char	*enter_string = "\033[H\033[J";	/* String printed on entering mined */
1287 const char	*pos_string = "\033[%d;%dH";	/* Absolute cursor position */
1288 const char	*rev_scroll = "\033M";		/* String for reverse scrolling */
1289 const char	*rev_video = "\033[7m";		/* String for starting reverse video */
1290 const char	*normal_video = "\033[m";	/* String for leaving reverse video */
1291 const char	*blank_line = "\033[K";		/* Clear line to end */
1292 #endif /* UNIX */
1293 
1294 /*
1295  * Yank variables.
1296  */
1297 FLAG yank_status = NOT_VALID;		/* Status of yank_file */
1298 char yank_file[] = "/tmp/mined.XXXXXX";
1299 long chars_saved;			/* Nr of chars in buffer */
1300 
1301 /*
1302  * Initialize is called when a another file is edited. It free's the allocated
1303  * space and sets modified back to FALSE and fixes the header/tail pointer.
1304  */
1305 void
1306 initialize(void)
1307 {
1308   LINE *line, *next_line;
1309 
1310 /* Delete the whole list */
1311   for (line = header->next; line != tail; line = next_line) {
1312 	next_line = line->next;
1313 	free_space(line->text);
1314 	free_space((char*)line);
1315   }
1316 
1317 /* header and tail should point to itself */
1318   line->next = line->prev = line;
1319   x = y = 0;
1320   rpipe = modified = FALSE;
1321 }
1322 
1323 /*
1324  * Basename() finds the absolute name of the file out of a given path_name.
1325  */
1326 char *
1327 basename(char *path)
1328 {
1329   char *ptr = path;
1330   char *last = NIL_PTR;
1331 
1332   while (*ptr != '\0') {
1333 	if (*ptr == '/')
1334 		last = ptr;
1335 	ptr++;
1336   }
1337   if (last == NIL_PTR)
1338 	return path;
1339   if (*(last + 1) == '\0') {	/* E.g. /usr/tmp/pipo/ */
1340 	*last = '\0';
1341 	return basename(path);/* Try again */
1342   }
1343   return last + 1;
1344 }
1345 
1346 /*
1347  * Load_file loads the file `file' into core. If file is a NIL_PTR or the file
1348  * couldn't be opened, just some initializations are done, and a line consisting
1349  * of a `\n' is installed.
1350  */
1351 void
1352 load_file(const char *file)
1353 {
1354   LINE *line = header;
1355   int len;
1356   long nr_of_chars = 0L;
1357   int fd = -1;			/* Filedescriptor for file */
1358 
1359   nlines = 0;			/* Zero lines to start with */
1360 
1361 /* Open file */
1362   writable = TRUE;		/* Benefit of the doubt */
1363   if (file == NIL_PTR) {
1364 	if (rpipe == FALSE)
1365 		status_line("No file.", NIL_PTR);
1366 	else {
1367 		fd = 0;
1368 		file = "standard input";
1369 	}
1370 	file_name[0] = '\0';
1371   }
1372   else {
1373 	copy_string(file_name, file);	/* Save file name */
1374 	if (access(file, 0) < 0)	/* Cannot access file. */
1375 		status_line("New file ", file);
1376 	else if ((fd = open(file, 0)) < 0)
1377 		status_line("Cannot open ", file);
1378 	else if (access(file, 2) != 0)	/* Set write flag */
1379 		writable = FALSE;
1380   }
1381 
1382 /* Read file */
1383   loading = TRUE;				/* Loading file, so set flag */
1384 
1385   if (fd >= 0) {
1386 	status_line("Reading ", file);
1387 	while ((len = get_line(fd, text_buffer)) != ERRORS) {
1388 		line = line_insert(line, text_buffer, len);
1389 		nr_of_chars += (long) len;
1390 	}
1391 	if (nlines == 0)		/* The file was empty! */
1392 		line = line_insert(line, "\n", 1);
1393 	clear_buffer();		/* Clear output buffer */
1394 	cur_line = header->next;
1395 	fstatus("Read", nr_of_chars);
1396 	close(fd);		/* Close file */
1397   }
1398   else					/* Just install a "\n" */
1399 	line_insert(line, "\n", 1);
1400 
1401   reset(header->next, 0);		/* Initialize pointers */
1402 
1403 /* Print screen */
1404   display (0, 0, header->next, last_y);
1405   move_to (0, 0);
1406   flush();				/* Flush buffer */
1407   loading = FALSE;			/* Stop loading, reset flag */
1408 }
1409 
1410 
1411 /*
1412  * Get_line reads one line from filedescriptor fd. If EOF is reached on fd,
1413  * get_line() returns ERRORS, else it returns the length of the string.
1414  */
1415 int
1416 get_line(int fd, char *buffer)
1417 {
1418   static char *last = NIL_PTR;
1419   static char *current = NIL_PTR;
1420   static int read_chars;
1421   char *cur_pos = current;
1422   char *begin = buffer;
1423 
1424   do {
1425 	if (cur_pos == last) {
1426 		if ((read_chars = read(fd, screen, SCREEN_SIZE)) <= 0)
1427 			break;
1428 		last = &screen[read_chars];
1429 		cur_pos = screen;
1430 	}
1431 	if (*cur_pos == '\0')
1432 		*cur_pos = ' ';
1433   } while ((*buffer++ = *cur_pos++) != '\n');
1434 
1435   current = cur_pos;
1436   if (read_chars <= 0) {
1437 	if (buffer == begin)
1438 		return ERRORS;
1439 	if (*(buffer - 1) != '\n') {
1440 		if (loading == TRUE) /* Add '\n' to last line of file */
1441 			*buffer++ = '\n';
1442 		else {
1443 			*buffer = '\0';
1444 			return NO_LINE;
1445 		}
1446 	}
1447   }
1448 
1449   *buffer = '\0';
1450   return buffer - begin;
1451 }
1452 
1453 /*
1454  * Install_line installs the buffer into a LINE structure It returns a pointer
1455  * to the allocated structure.
1456  */
1457 LINE *
1458 install_line(const char *buffer, int length)
1459 {
1460   LINE *new_line = (LINE *) alloc(sizeof(LINE));
1461 
1462   new_line->text = alloc(length + 1);
1463   new_line->shift_count = 0;
1464   copy_string(new_line->text, buffer);
1465 
1466   return new_line;
1467 }
1468 
1469 int
1470 main(int argc, char *argv[])
1471 {
1472 /* mined is the Minix editor. */
1473 
1474   int index;		/* Index in key table */
1475   struct winsize winsize;
1476 
1477 #ifdef UNIX
1478   get_term();
1479   tputs(VS, 0, _putchar);
1480   tputs(CL, 0, _putchar);
1481 #else
1482   string_print(enter_string);			/* Hello world */
1483 #endif /* UNIX */
1484   if (ioctl(STD_OUT, TIOCGWINSZ, &winsize) == 0 && winsize.ws_row != 0) {
1485 	ymax = winsize.ws_row - 1;
1486 	screenmax = ymax - 1;
1487   }
1488 
1489   if (!isatty(0)) {		/* Reading from pipe */
1490 	if (argc != 1) {
1491 		write(2, "Cannot find terminal.\n", 22);
1492 		exit (1);
1493 	}
1494 	rpipe = TRUE;
1495 	modified = TRUE;	/* Set modified so he can write */
1496 	open_device();
1497   }
1498 
1499   raw_mode(ON);			/* Set tty to appropriate mode */
1500 
1501   header = tail = (LINE *) alloc(sizeof(LINE));	/* Make header of list*/
1502   header->text = NIL_PTR;
1503   header->next = tail->prev = header;
1504 
1505 /* Load the file (if any) */
1506   if (argc < 2)
1507 	load_file(NIL_PTR);
1508   else {
1509 	get_file(NIL_PTR, argv[1]);	/* Truncate filename */
1510 	load_file(argv[1]);
1511   }
1512 
1513  /* Main loop of the editor. */
1514   for (;;) {
1515 	index = getchar();
1516 	if (stat_visible == TRUE)
1517 		clear_status();
1518 	if (quit == TRUE)
1519 		abort_mined();
1520 	else {			/* Call the function for this key */
1521 		(*key_map[index])(index);
1522 		flush();       /* Flush output (if any) */
1523 		if (quit == TRUE)
1524 			quit = FALSE;
1525 	}
1526   }
1527   /* NOTREACHED */
1528 }
1529 
1530 /*  ========================================================================  *
1531  *				Miscellaneous				      *
1532  *  ========================================================================  */
1533 
1534 /*
1535  * Redraw the screen
1536  */
1537 void
1538 RD(int u __unused)
1539 {
1540 /* Clear screen */
1541 #ifdef UNIX
1542   tputs(VS, 0, _putchar);
1543   tputs(CL, 0, _putchar);
1544 #else
1545   string_print(enter_string);
1546 #endif /* UNIX */
1547 
1548 /* Print first page */
1549   display(0, 0, top_line, last_y);
1550 
1551 /* Clear last line */
1552   set_cursor(0, ymax);
1553 #ifdef UNIX
1554   tputs(CE, 0, _putchar);
1555 #else
1556   string_print(blank_line);
1557 #endif /* UNIX */
1558   move_to(x, y);
1559 }
1560 
1561 /*
1562  * Ignore this keystroke.
1563  */
1564 void
1565 I(int u __unused)
1566 {
1567 }
1568 
1569 /*
1570  * Leave editor. If the file has changed, ask if the user wants to save it.
1571  */
1572 void
1573 XT(int u __unused)
1574 {
1575   if (modified == TRUE && ask_save() == ERRORS)
1576 	return;
1577 
1578   raw_mode(OFF);
1579   set_cursor(0, ymax);
1580   putchar('\n');
1581   flush();
1582   unlink(yank_file);		/* Might not be necessary */
1583   exit(0);
1584 }
1585 
1586 static void
1587 (*escfunc(int c))(int)
1588 {
1589   if (c == '[') {
1590 	/* Start of ASCII escape sequence. */
1591 	c = getchar();
1592 	switch (c) {
1593 	case 'H': return(HO);
1594 	case 'A': return(UP);
1595 	case 'B': return(DN);
1596 	case 'C': return(RT);
1597 	case 'D': return(LF);
1598 #ifdef ASSUME_CONS25
1599 	case 'G': return(PD);
1600 	case 'I': return(PU);
1601 	case 'F': return(EF);
1602 	/* F1 - help */
1603 	case 'M': return(HLP);
1604 	/* F2 - file status */
1605 	case 'N': return(FS);
1606 	/* F3 - search fwd */
1607 	case 'O': return(SF);
1608 	/* Shift-F3 - search back */
1609 	case 'a':return(SR);
1610 	/* F4 - global replace */
1611 	case 'P': return(GR);
1612 	/* Shift-F4 - line replace */
1613 	case 'b': return(LR);
1614 #else
1615 	case 'G': return(FS);
1616 	case 'S': return(SR);
1617 	case 'T': return(SF);
1618 	case 'U': return(PD);
1619 	case 'V': return(PU);
1620 	case 'Y': return(EF);
1621 #endif
1622 	}
1623 	return(I);
1624   }
1625 #ifdef ASSUME_XTERM
1626   if (c == 'O') {
1627 	/* Start of ASCII function key escape sequence. */
1628 	switch (getchar()) {
1629 	case 'P': return(HLP);		/* F1 */
1630 	case 'Q': return(FS);		/* F2 */
1631 	case 'R': return(SF);		/* F3 */
1632 	case 'S': return(GR);		/* F4 */
1633 	case '2':
1634 		switch (getchar()) {
1635 		case 'R': return(SR);	/* shift-F3 */
1636 		}
1637 		break;
1638 	}
1639     }
1640 #endif
1641   return(I);
1642 }
1643 
1644 /*
1645  * ESC() wants a count and a command after that. It repeats the
1646  * command count times. If a ^\ is given during repeating, stop looping and
1647  * return to main loop.
1648  */
1649 void
1650 ESC(int u __unused)
1651 {
1652   int count = 0;
1653   void (*func)(int);
1654   int index;
1655 
1656   index = getchar();
1657   while (index >= '0' && index <= '9' && quit == FALSE) {
1658 	count *= 10;
1659 	count += index - '0';
1660 	index = getchar();
1661   }
1662   if (count == 0) {
1663 	count = 1;
1664 	func = escfunc(index);
1665   } else {
1666 	func = key_map[index];
1667 	if (func == ESC)
1668 		func = escfunc(getchar());
1669   }
1670 
1671   if (func == I) {	/* Function assigned? */
1672 	clear_status();
1673 	return;
1674   }
1675 
1676   while (count-- > 0 && quit == FALSE) {
1677 	if (stat_visible == TRUE)
1678 		clear_status();
1679 	(*func)(index);
1680 	flush();
1681   }
1682 
1683   if (quit == TRUE)		/* Abort has been given */
1684 	error("Aborted", NIL_PTR);
1685 }
1686 
1687 /*
1688  * Ask the user if he wants to save his file or not.
1689  */
1690 int
1691 ask_save(void)
1692 {
1693   int c;
1694 
1695   status_line(file_name[0] ? basename(file_name) : "[buffer]" ,
1696 					     " has been modified. Save? (y/n)");
1697 
1698   while((c = getchar()) != 'y' && c != 'n' && quit == FALSE) {
1699 	ring_bell();
1700 	flush();
1701   }
1702 
1703   clear_status();
1704 
1705   if (c == 'y')
1706 	return WT();
1707 
1708   if (c == 'n')
1709 	return FINE;
1710 
1711   quit = FALSE;	/* Abort character has been given */
1712   return ERRORS;
1713 }
1714 
1715 /*
1716  * Line_number() finds the line number we're on.
1717  */
1718 int
1719 line_number(void)
1720 {
1721   LINE *line = header->next;
1722   int count = 1;
1723 
1724   while (line != cur_line) {
1725 	count++;
1726 	line = line->next;
1727   }
1728 
1729   return count;
1730 }
1731 
1732 /*
1733  * Display a line telling how many chars and lines the file contains. Also tell
1734  * whether the file is readonly and/or modified.
1735  *
1736  * parameter
1737  * count:	Contains number of characters in file
1738  */
1739 void
1740 file_status(const char *message, long count, char *file, int lines,
1741 	    FLAG writefl, FLAG changed)
1742 {
1743   LINE *line;
1744   char msg[LINE_LEN + 40];/* Buffer to hold line */
1745   char yank_msg[LINE_LEN];/* Buffer for msg of yank_file */
1746 
1747   if (count < 0)		/* Not valid. Count chars in file */
1748 	for (line = header->next; line != tail; line = line->next)
1749 		count += length_of(line->text);
1750 
1751   if (yank_status != NOT_VALID)	/* Append buffer info */
1752 	build_string(yank_msg, " Buffer: %D char%s.", chars_saved,
1753 						(chars_saved == 1L) ? "" : "s");
1754   else
1755 	yank_msg[0] = '\0';
1756 
1757   build_string(msg, "%s %s%s%s %d line%s %D char%s.%s Line %d", message,
1758 		    (rpipe == TRUE && *message != '[') ? "standard input" : basename(file),
1759 		    (changed == TRUE) ? "*" : "",
1760 		    (writefl == FALSE) ? " (Readonly)" : "",
1761 		    lines, (lines == 1) ? "" : "s",
1762 		    count, (count == 1L) ? "" : "s",
1763 		    yank_msg, line_number());
1764 
1765   if (length_of(msg) + 1 > LINE_LEN - 4) {
1766 	msg[LINE_LEN - 4] = SHIFT_MARK;	/* Overflow on status line */
1767 	msg[LINE_LEN - 3] = '\0';
1768   }
1769   status_line(msg, NIL_PTR);		/* Print the information */
1770 }
1771 
1772 /*
1773  * Build_string() prints the arguments as described in fmt, into the buffer.
1774  * %s indicates an argument string, %d indicated an argument number.
1775  */
1776 void
1777 build_string(char *buf, const char *fmt, ...)
1778 {
1779   va_list argptr;
1780   const char *scanp;
1781 
1782   va_start(argptr, fmt);
1783 
1784   while (*fmt) {
1785 	if (*fmt == '%') {
1786 		fmt++;
1787 		switch (*fmt++) {
1788 		case 's' :
1789 			scanp = va_arg(argptr, char *);
1790 			break;
1791 		case 'd' :
1792 			scanp = num_out((long) va_arg(argptr, int));
1793 			break;
1794 		case 'D' :
1795 			scanp = num_out((long) va_arg(argptr, long));
1796 			break;
1797 		default :
1798 			scanp = "";
1799 		}
1800 		while ((*buf++ = *scanp++) != 0)
1801 			;
1802 		buf--;
1803 	}
1804 	else
1805 		*buf++ = *fmt++;
1806   }
1807   va_end(argptr);
1808   *buf = '\0';
1809 }
1810 
1811 /*
1812  * Output an (unsigned) long in a 10 digit field without leading zeros.
1813  * It returns a pointer to the first digit in the buffer.
1814  */
1815 char *
1816 num_out(long number)
1817 {
1818   static char num_buf[11];		/* Buffer to build number */
1819   long digit;			/* Next digit of number */
1820   long pow = 1000000000L;	/* Highest ten power of long */
1821   FLAG digit_seen = FALSE;
1822   int i;
1823 
1824   for (i = 0; i < 10; i++) {
1825 	digit = number / pow;		/* Get next digit */
1826 	if (digit == 0L && digit_seen == FALSE && i != 9)
1827 		num_buf[i] = ' ';
1828 	else {
1829 		num_buf[i] = '0' + (char) digit;
1830 		number -= digit * pow;	/* Erase digit */
1831 		digit_seen = TRUE;
1832 	}
1833 	pow /= 10L;			/* Get next digit */
1834   }
1835   for (i = 0; num_buf[i] == ' '; i++)	/* Skip leading spaces */
1836 	;
1837   return (&num_buf[i]);
1838 }
1839 
1840 /*
1841  * Get_number() read a number from the terminal. The last character typed in is
1842  * returned.  ERRORS is returned on a bad number. The resulting number is put
1843  * into the integer the arguments points to.
1844  */
1845 int
1846 get_number(const char *message, int *result)
1847 {
1848   int index;
1849   int count = 0;
1850 
1851   status_line(message, NIL_PTR);
1852 
1853   index = getchar();
1854   if (quit == FALSE && (index < '0' || index > '9')) {
1855 	error("Bad count", NIL_PTR);
1856 	return ERRORS;
1857   }
1858 
1859 /* Convert input to a decimal number */
1860   while (index >= '0' && index <= '9' && quit == FALSE) {
1861 	count *= 10;
1862 	count += index - '0';
1863 	index = getchar();
1864   }
1865 
1866   if (quit == TRUE) {
1867 	clear_status();
1868 	return ERRORS;
1869   }
1870 
1871   *result = count;
1872   return index;
1873 }
1874 
1875 /*
1876  * Input() reads a string from the terminal.  When the KILL character is typed,
1877  * it returns ERRORS.
1878  */
1879 int
1880 input(char *inbuf, FLAG clearfl)
1881 {
1882   char *ptr;
1883   char c;			/* Character read */
1884 
1885   ptr = inbuf;
1886 
1887   *ptr = '\0';
1888   while (quit == FALSE) {
1889 	flush();
1890 	switch (c = getchar()) {
1891 		case '\b' :		/* Erase previous char */
1892 			if (ptr > inbuf) {
1893 				ptr--;
1894 #ifdef UNIX
1895 				tputs(SE, 0, _putchar);
1896 #else
1897 				string_print(normal_video);
1898 #endif /* UNIX */
1899 				if (is_tab(*ptr))
1900 					string_print(" \b\b\b  \b\b");
1901 				else
1902 					string_print(" \b\b \b");
1903 #ifdef UNIX
1904 				tputs(SO, 0, _putchar);
1905 #else
1906 				string_print(rev_video);
1907 #endif /* UNIX */
1908 				string_print(" \b");
1909 				*ptr = '\0';
1910 			}
1911 			else
1912 				ring_bell();
1913 			break;
1914 		case '\n' :		/* End of input */
1915 			/* If inbuf is empty clear status_line */
1916 			return (ptr == inbuf && clearfl == TRUE) ? NO_INPUT :FINE;
1917 		default :		/* Only read ASCII chars */
1918 			if ((c >= ' ' && c <= '~') || c == '\t') {
1919 				*ptr++ = c;
1920 				*ptr = '\0';
1921 				if (c == '\t')
1922 					string_print("^I");
1923 				else
1924 					putchar(c);
1925 				string_print(" \b");
1926 			}
1927 			else
1928 				ring_bell();
1929 	}
1930   }
1931   quit = FALSE;
1932   return ERRORS;
1933 }
1934 
1935 /*
1936  * Get_file() reads a filename from the terminal. Filenames longer than
1937  * FILE_LENGHT chars are truncated.
1938  */
1939 int
1940 get_file(const char *message, char *file)
1941 {
1942   char *ptr;
1943   int ret = FINE;
1944 
1945   if (message == NIL_PTR || (ret = get_string(message, file, TRUE)) == FINE) {
1946 	if (length_of((ptr = basename(file))) > NAME_MAX)
1947 		ptr[NAME_MAX] = '\0';
1948   }
1949   return ret;
1950 }
1951 
1952 /*  ========================================================================  *
1953  *				UNIX I/O Routines			      *
1954  *  ========================================================================  */
1955 
1956 #ifdef UNIX
1957 #undef putchar
1958 
1959 int
1960 _getchar(void)
1961 {
1962   char c;
1963 
1964   if (read(input_fd, &c, 1) != 1 && quit == FALSE)
1965 	panic ("Cannot read 1 byte from input");
1966   return c & 0377;
1967 }
1968 
1969 void
1970 _flush(void)
1971 {
1972   fflush(stdout);
1973 }
1974 
1975 void
1976 _putchar(char c)
1977 {
1978   write_char(STD_OUT, c);
1979 }
1980 
1981 void
1982 get_term(void)
1983 {
1984   static char termbuf[50];
1985   char *loc = termbuf;
1986   char entry[1024];
1987 
1988   if (tgetent(entry, getenv("TERM")) <= 0) {
1989 	printf("Unknown terminal.\n");
1990 	exit(1);
1991   }
1992 
1993   AL = tgetstr("al", &loc);
1994   CE = tgetstr("ce", &loc);
1995   VS = tgetstr("vs", &loc);
1996   CL = tgetstr("cl", &loc);
1997   SO = tgetstr("so", &loc);
1998   SE = tgetstr("se", &loc);
1999   CM = tgetstr("cm", &loc);
2000   ymax = tgetnum("li") - 1;
2001   screenmax = ymax - 1;
2002 
2003   if (!CE || !SO || !SE || !CL || !AL || !CM) {
2004 	printf("Sorry, no mined on this type of terminal\n");
2005 	exit(1);
2006   }
2007 }
2008 #endif /* UNIX */
2009