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