Sync zoneinfo database with tzdata2018b from ftp://ftp.iana.org/tz/releases
[dragonfly.git] / bin / mined / mined1.c
blob7cbd1130e834ae100db42269d76495f86e0033ae
1 /*
2 * Copyright (c) 1987,1997, Prentice Hall
3 * All rights reserved.
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:
9 * * Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
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.
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.
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.
35 * [original code from minix codebase]
38 * Part one of the mined editor.
42 * Ported to FreeBSD by Andrzej Bialecki <abial@freebsd.org>, Oct 1998
44 * Added a help screen, and remapped some of the wildest keybindings...
48 * Author: Michiel Huisjes.
50 * 1. General remarks.
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.
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.
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.
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.
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.
103 * 2. Regular expressions
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:
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.
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.
130 * 3. Implementation of mined.
132 * 3.1 Data structures.
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:
137 * typedef struct Line {
138 * struct Line *next;
139 * struct Line *prev;
140 * char *text;
141 * unsigned char shift_count;
142 * } LINE;
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.
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.
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).
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.
181 * 3.2 Starting up.
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.
195 * 3.3 Moving around.
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.
212 * 3.4 Modifying text.
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).
232 * 3.5 Yanking.
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.
253 * 3.6 Search and replace routines.
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:
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;
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.
317 * 3.6 Miscellaneous commands.
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.
328 * 3.7 Utility functions.
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.
391 * 4. Summary of commands.
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
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)
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
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)
445 /* ======================================================================== *
446 * Utilities *
447 * ======================================================================== */
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>
459 int ymax = YMAX;
460 int screenmax = SCREENMAX;
464 * Print file status.
466 void
467 FS(int u __unused)
469 fstatus(file_name[0] ? "" : "[buffer]", -1L);
473 * Visit (edit) another file. If the file has been modified, ask the user if
474 * he wants to save it.
476 void
477 VI(int u __unused)
479 char new_file[LINE_LEN]; /* Buffer to hold new file name */
481 if (modified == TRUE && ask_save() == ERRORS)
482 return;
484 /* Get new file name */
485 if (get_file("Visit file:", new_file) == ERRORS)
486 return;
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);
499 * Write file in core to disc.
502 WT(void)
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 */
509 if (modified == FALSE) {
510 error ("Write not necessary.", NIL_PTR);
511 return FINE;
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 */
520 if ((fd = creat(file_name, 0644)) < 0) { /* Empty file */
521 error("Cannot create ", file_name);
522 writable = FALSE;
523 return ERRORS;
525 else
526 writable = TRUE;
528 clear_buffer();
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;
536 if (writeline(fd, line->text) == ERRORS) {
537 count = -1L;
538 break;
540 count += (long) length_of(line->text);
543 if (count > 0L && flush_buffer(fd) == ERRORS)
544 count = -1L;
546 close(fd);
548 if (count == -1L)
549 return ERRORS;
551 modified = FALSE;
552 rpipe = FALSE; /* File name is now assigned */
554 /* Display how many chars (and lines) were written */
555 fstatus("Wrote", count);
556 return FINE;
559 /* Call WT and discard value returned. */
560 void
561 XWT(int u __unused)
563 WT();
569 * Call an interactive shell.
571 void
572 SH(int u __unused)
574 int w;
575 int pid, status;
576 const char *shell;
578 if ((shell = getenv("SHELL")) == NIL_PTR) shell = "/bin/sh";
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);
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);
604 raw_mode(ON);
605 RD(0);
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);
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.
618 LINE *
619 proceed(LINE *line, int count)
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;
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.
636 bottom_line(FLAG revfl, const char *s1, const char *s2, char *inbuf,
637 FLAG statfl)
639 int ret = FINE;
640 char buf[LINE_LEN];
641 char *p = buf;
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;
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;
664 else /* Used as clear_status() */
665 stat_visible = FALSE;
667 string_print(buf);
669 if (inbuf != NIL_PTR)
670 ret = input(inbuf, statfl);
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;
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.
695 count_chars(LINE *line)
697 int cnt = get_shift(line->shift_count) * -SHIFT_SIZE;
698 char *textp = line->text;
700 /* Find begin of line on screen */
701 while (cnt < 0) {
702 if (is_tab(*textp++))
703 cnt = tab(cnt);
704 else
705 cnt++;
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++;
716 return cnt;
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.
729 void
730 move(int new_x, char *new_address, int new_y)
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;
737 /* Check for illegal values */
738 if (new_y < 0 || new_y > last_y)
739 return;
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);
750 y--;
751 line = line->prev;
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);
761 y++;
762 line = line->next;
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;
772 else {
773 rel_x = new_x = find_x(line, new_address);
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--;
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;
795 /* Assign and position cursor */
796 x = new_x;
797 cur_text = new_address;
798 cur_line = line;
799 set_cursor(x, y);
803 * Find_x() returns the x coordinate belonging to address.
804 * (Tabs are expanded).
807 find_x(LINE *line, char *address)
809 char *textp = line->text;
810 int nx = get_shift(line->shift_count) * -SHIFT_SIZE;
812 while (textp != address && *textp != '\0') {
813 if (is_tab(*textp++)) /* Expand tabs */
814 nx = tab(nx);
815 else
816 nx++;
818 return nx;
822 * Find_address() returns the pointer in the line with offset x_coord.
823 * (Tabs are expanded).
825 char *
826 find_address(LINE *line, int x_coord, int *old_x)
828 char *textp = line->text;
829 int tx = get_shift(line->shift_count) * -SHIFT_SIZE;
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);
838 else
839 tx++;
840 textp++;
843 *old_x = tx;
844 return textp;
848 * Length_of() returns the number of characters int the string `string'
849 * excluding the '\0'.
852 length_of(char *string)
854 int count = 0;
856 if (string != NIL_PTR) {
857 while (*string++ != '\0')
858 count++;
860 return count;
864 * Copy_string() copies the string `from' into the string `to'. `To' must be
865 * long enough to hold `from'.
867 void
868 copy_string(char *to, const char *from)
870 while ((*to++ = *from++) != 0)
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)
879 void
880 reset(LINE *head_line, int screen_y)
882 LINE *line;
884 top_line = line = head_line;
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;
891 bot_line = line;
892 y = (screen_y > last_y) ? last_y : screen_y;
894 /* Set cur_line according to the new y value */
895 cur_line = proceed(top_line, y);
899 * Set cursor at coordinates x, y.
901 void
902 set_cursor(int nx, int ny)
904 #ifdef UNIX
905 tputs(tgoto(CM, nx, ny), 0, _putchar);
906 #else
907 char text_buf[10];
909 build_string(text_buf, pos_string, ny+1, nx+1);
910 string_print(text_buf);
911 #endif /* UNIX */
915 * Routine to open terminal when mined is used in a pipeline.
917 void
918 open_device(void)
920 if ((input_fd = open("/dev/tty", 0)) < 0)
921 panic("Cannot open /dev/tty for read");
925 * Getchar() reads one character from the terminal. The character must be
926 * masked with 0377 to avoid sign extension.
929 getchar(void)
931 #ifdef UNIX
932 return (_getchar() & 0377);
933 #else
934 char c;
936 if (read(input_fd, &c, 1) != 1 && quit == FALSE)
937 panic("Can't read one char from fd #0");
939 return c & 0377;
940 #endif /* UNIX */
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.
949 void
950 display(int x_coord, int y_coord, LINE *line, int count)
952 set_cursor(x_coord, y_coord);
954 /* Find new startline if count is negative */
955 if (count < 0) {
956 line = proceed(line, count);
957 count = -count;
960 /* Print the lines */
961 while (line != tail && count-- >= 0) {
962 line->shift_count=0;
963 line_print(line);
964 line = line->next;
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');
981 * Write_char does a buffered output.
984 write_char(int fd, char c)
986 screen [out_count++] = c;
987 if (out_count == SCREEN_SIZE) /* Flush on SCREEN_SIZE chars */
988 return flush_buffer(fd);
989 return FINE;
993 * Writeline writes the given string on the given filedescriptor.
996 writeline(int fd, const char *text)
998 while(*text)
999 if (write_char(fd, *text++) == ERRORS)
1000 return ERRORS;
1001 return FINE;
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.
1010 * parameter
1011 * line: Line to print
1012 * offset: Offset to start
1013 * clear_line: Clear to eoln if TRUE
1015 void
1016 put_line(LINE *line, int offset, FLAG clear_line)
1018 char *textp = line->text;
1019 int count = get_shift(line->shift_count) * -SHIFT_SIZE;
1020 int tab_count; /* Used in tab expansion */
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++;
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(' ');
1037 textp++;
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 */
1053 else
1054 putchar(*textp++);
1055 count++;
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);
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');
1075 * Flush the I/O buffer on filedescriptor fd.
1078 flush_buffer(int fd)
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();
1087 else
1088 #endif /* UNIX */
1089 if (write(fd, screen, out_count) != out_count) {
1090 bad_write(fd);
1091 return ERRORS;
1093 clear_buffer(); /* Empty buffer */
1094 return FINE;
1098 * Bad_write() is called when a write failed. Notify the user.
1100 void
1101 bad_write(int fd)
1103 if (fd == STD_OUT) /* Cannot write to terminal? */
1104 exit(1);
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);
1114 * Catch the SIGQUIT signal (^\) send to mined. It turns on the quitflag.
1116 void
1117 catch(int sig __unused)
1119 /* Reset the signal */
1120 signal(SIGQUIT, catch);
1121 quit = TRUE;
1125 * Abort_mined() will leave mined. Confirmation is asked first.
1127 void
1128 abort_mined(void)
1130 quit = FALSE;
1132 /* Ask for confirmation */
1133 status_line("Really abort? ", NIL_PTR);
1134 if (getchar() != 'y') {
1135 clear_status();
1136 return;
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 */
1151 #define UNDEF _POSIX_VDISABLE
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.
1157 void
1158 raw_mode(FLAG state)
1160 static struct termios old_tty;
1161 static struct termios new_tty;
1163 if (state == OFF) {
1164 tcsetattr(input_fd, TCSANOW, &old_tty);
1165 return;
1168 /* Save old tty settings */
1169 tcgetattr(input_fd, &old_tty);
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);
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 */
1181 tcsetattr(input_fd, TCSANOW, &new_tty);
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.
1190 void
1191 panic(const char *message)
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));
1201 if (loading == FALSE)
1202 XT(0); /* Check if file can be saved */
1203 else
1204 unlink(yank_file);
1205 raw_mode(OFF);
1207 #ifdef UNIX
1208 abort();
1209 #else
1210 exit(1);
1211 #endif /* UNIX */
1214 void *
1215 alloc(int bytes)
1217 char *p;
1219 p = malloc((unsigned) bytes);
1220 if (p == NIL_PTR) {
1221 if (loading == TRUE)
1222 panic("File too big.");
1223 panic("Out of memory.");
1225 return(p);
1228 void
1229 free_space(char *p)
1231 free(p);
1234 /* ======================================================================== *
1235 * Main loops *
1236 * ======================================================================== */
1238 /* The mapping between input codes and functions. */
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,
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" */
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 */
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 */
1295 * Yank variables.
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 */
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.
1305 void
1306 initialize(void)
1308 LINE *line, *next_line;
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);
1317 /* header and tail should point to itself */
1318 line->next = line->prev = line;
1319 x = y = 0;
1320 rpipe = modified = FALSE;
1324 * Basename() finds the absolute name of the file out of a given path_name.
1326 char *
1327 basename(char *path)
1329 char *ptr = path;
1330 char *last = NIL_PTR;
1332 while (*ptr != '\0') {
1333 if (*ptr == '/')
1334 last = ptr;
1335 ptr++;
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 */
1343 return last + 1;
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.
1351 void
1352 load_file(const char *file)
1354 LINE *line = header;
1355 int len;
1356 long nr_of_chars = 0L;
1357 int fd = -1; /* Filedescriptor for file */
1359 nlines = 0; /* Zero lines to start with */
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";
1370 file_name[0] = '\0';
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;
1382 /* Read file */
1383 loading = TRUE; /* Loading file, so set flag */
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;
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 */
1398 else /* Just install a "\n" */
1399 line_insert(line, "\n", 1);
1401 reset(header->next, 0); /* Initialize pointers */
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 */
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.
1416 get_line(int fd, char *buffer)
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;
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;
1431 if (*cur_pos == '\0')
1432 *cur_pos = ' ';
1433 } while ((*buffer++ = *cur_pos++) != '\n');
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;
1449 *buffer = '\0';
1450 return buffer - begin;
1454 * Install_line installs the buffer into a LINE structure It returns a pointer
1455 * to the allocated structure.
1457 LINE *
1458 install_line(const char *buffer, int length)
1460 LINE *new_line = (LINE *) alloc(sizeof(LINE));
1462 new_line->text = alloc(length + 1);
1463 new_line->shift_count = 0;
1464 copy_string(new_line->text, buffer);
1466 return new_line;
1470 main(int argc, char *argv[])
1472 /* mined is the Minix editor. */
1474 int index; /* Index in key table */
1475 struct winsize winsize;
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;
1489 if (!isatty(0)) { /* Reading from pipe */
1490 if (argc != 1) {
1491 write(2, "Cannot find terminal.\n", 22);
1492 exit (1);
1494 rpipe = TRUE;
1495 modified = TRUE; /* Set modified so he can write */
1496 open_device();
1499 raw_mode(ON); /* Set tty to appropriate mode */
1501 header = tail = (LINE *) alloc(sizeof(LINE)); /* Make header of list*/
1502 header->text = NIL_PTR;
1503 header->next = tail->prev = header;
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]);
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;
1527 /* NOTREACHED */
1530 /* ======================================================================== *
1531 * Miscellaneous *
1532 * ======================================================================== */
1535 * Redraw the screen
1537 void
1538 RD(int u __unused)
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 */
1548 /* Print first page */
1549 display(0, 0, top_line, last_y);
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);
1562 * Ignore this keystroke.
1564 void
1565 I(int u __unused)
1570 * Leave editor. If the file has changed, ask if the user wants to save it.
1572 void
1573 XT(int u __unused)
1575 if (modified == TRUE && ask_save() == ERRORS)
1576 return;
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);
1586 static void
1587 (*escfunc(int c))(int)
1589 #if (CHIP == M68000)
1590 #ifndef COMPAT
1591 int ch;
1592 #endif
1593 #endif
1594 if (c == '[') {
1595 /* Start of ASCII escape sequence. */
1596 c = getchar();
1597 #if (CHIP == M68000)
1598 #ifndef COMPAT
1599 if ((c >= '0') && (c <= '9')) ch = getchar();
1600 /* ch is either a tilde or a second digit */
1601 #endif
1602 #endif
1603 switch (c) {
1604 case 'H': return(HO);
1605 case 'A': return(UP);
1606 case 'B': return(DN);
1607 case 'C': return(RT);
1608 case 'D': return(LF);
1609 #if (CHIP == M68000)
1610 #ifndef COMPAT
1611 /* F1 = ESC [ 1 ~ */
1612 /* F2 = ESC [ 2 ~ */
1613 /* F3 = ESC [ 3 ~ */
1614 /* F4 = ESC [ 4 ~ */
1615 /* F5 = ESC [ 5 ~ */
1616 /* F6 = ESC [ 6 ~ */
1617 /* F7 = ESC [ 17 ~ */
1618 /* F8 = ESC [ 18 ~ */
1619 case '1':
1620 switch (ch) {
1621 case '~': return(SF);
1622 case '7': getchar(); return(MA);
1623 case '8': getchar(); return(CTL);
1625 case '2': return(SR);
1626 case '3': return(PD);
1627 case '4': return(PU);
1628 case '5': return(FS);
1629 case '6': return(EF);
1630 #endif
1631 #endif
1632 #if (CHIP == INTEL)
1633 #ifdef ASSUME_CONS25
1634 case 'G': return(PD);
1635 case 'I': return(PU);
1636 case 'F': return(EF);
1637 /* F1 - help */
1638 case 'M': return(HLP);
1639 /* F2 - file status */
1640 case 'N': return(FS);
1641 /* F3 - search fwd */
1642 case 'O': return(SF);
1643 /* Shift-F3 - search back */
1644 case 'a':return(SR);
1645 /* F4 - global replace */
1646 case 'P': return(GR);
1647 /* Shift-F4 - line replace */
1648 case 'b': return(LR);
1649 #else
1650 case 'G': return(FS);
1651 case 'S': return(SR);
1652 case 'T': return(SF);
1653 case 'U': return(PD);
1654 case 'V': return(PU);
1655 case 'Y': return(EF);
1656 #endif
1657 #endif
1659 return(I);
1661 #ifdef ASSUME_XTERM
1662 if (c == 'O') {
1663 /* Start of ASCII function key escape sequence. */
1664 switch (getchar()) {
1665 case 'P': return(HLP); /* F1 */
1666 case 'Q': return(FS); /* F2 */
1667 case 'R': return(SF); /* F3 */
1668 case 'S': return(GR); /* F4 */
1669 case '2':
1670 switch (getchar()) {
1671 case 'R': return(SR); /* shift-F3 */
1673 break;
1676 #endif
1677 #if (CHIP == M68000)
1678 #ifdef COMPAT
1679 if (c == 'O') {
1680 /* Start of ASCII function key escape sequence. */
1681 switch (getchar()) {
1682 case 'P': return(SF);
1683 case 'Q': return(SR);
1684 case 'R': return(PD);
1685 case 'S': return(PU);
1686 case 'T': return(FS);
1687 case 'U': return(EF);
1688 case 'V': return(MA);
1689 case 'W': return(CTL);
1692 #endif
1693 #endif
1694 return(I);
1698 * ESC() wants a count and a command after that. It repeats the
1699 * command count times. If a ^\ is given during repeating, stop looping and
1700 * return to main loop.
1702 void
1703 ESC(int u __unused)
1705 int count = 0;
1706 void (*func)(int);
1707 int index;
1709 index = getchar();
1710 while (index >= '0' && index <= '9' && quit == FALSE) {
1711 count *= 10;
1712 count += index - '0';
1713 index = getchar();
1715 if (count == 0) {
1716 count = 1;
1717 func = escfunc(index);
1718 } else {
1719 func = key_map[index];
1720 if (func == ESC)
1721 func = escfunc(getchar());
1724 if (func == I) { /* Function assigned? */
1725 clear_status();
1726 return;
1729 while (count-- > 0 && quit == FALSE) {
1730 if (stat_visible == TRUE)
1731 clear_status();
1732 (*func)(index);
1733 flush();
1736 if (quit == TRUE) /* Abort has been given */
1737 error("Aborted", NIL_PTR);
1741 * Ask the user if he wants to save his file or not.
1744 ask_save(void)
1746 int c;
1748 status_line(file_name[0] ? basename(file_name) : "[buffer]" ,
1749 " has been modified. Save? (y/n)");
1751 while((c = getchar()) != 'y' && c != 'n' && quit == FALSE) {
1752 ring_bell();
1753 flush();
1756 clear_status();
1758 if (c == 'y')
1759 return WT();
1761 if (c == 'n')
1762 return FINE;
1764 quit = FALSE; /* Abort character has been given */
1765 return ERRORS;
1769 * Line_number() finds the line number we're on.
1772 line_number(void)
1774 LINE *line = header->next;
1775 int count = 1;
1777 while (line != cur_line) {
1778 count++;
1779 line = line->next;
1782 return count;
1786 * Display a line telling how many chars and lines the file contains. Also tell
1787 * whether the file is readonly and/or modified.
1789 * parameter
1790 * count: Contains number of characters in file
1792 void
1793 file_status(const char *message, long count, char *file, int lines,
1794 FLAG writefl, FLAG changed)
1796 LINE *line;
1797 char msg[LINE_LEN + 40];/* Buffer to hold line */
1798 char yank_msg[LINE_LEN];/* Buffer for msg of yank_file */
1800 if (count < 0) /* Not valid. Count chars in file */
1801 for (line = header->next; line != tail; line = line->next)
1802 count += length_of(line->text);
1804 if (yank_status != NOT_VALID) /* Append buffer info */
1805 build_string(yank_msg, " Buffer: %D char%s.", chars_saved,
1806 (chars_saved == 1L) ? "" : "s");
1807 else
1808 yank_msg[0] = '\0';
1810 build_string(msg, "%s %s%s%s %d line%s %D char%s.%s Line %d", message,
1811 (rpipe == TRUE && *message != '[') ? "standard input" : basename(file),
1812 (changed == TRUE) ? "*" : "",
1813 (writefl == FALSE) ? " (Readonly)" : "",
1814 lines, (lines == 1) ? "" : "s",
1815 count, (count == 1L) ? "" : "s",
1816 yank_msg, line_number());
1818 if (length_of(msg) + 1 > LINE_LEN - 4) {
1819 msg[LINE_LEN - 4] = SHIFT_MARK; /* Overflow on status line */
1820 msg[LINE_LEN - 3] = '\0';
1822 status_line(msg, NIL_PTR); /* Print the information */
1826 * Build_string() prints the arguments as described in fmt, into the buffer.
1827 * %s indicates an argument string, %d indicated an argument number.
1829 void
1830 build_string(char *buf, const char *fmt, ...)
1832 va_list argptr;
1833 const char *scanp;
1835 va_start(argptr, fmt);
1837 while (*fmt) {
1838 if (*fmt == '%') {
1839 fmt++;
1840 switch (*fmt++) {
1841 case 's' :
1842 scanp = va_arg(argptr, char *);
1843 break;
1844 case 'd' :
1845 scanp = num_out((long) va_arg(argptr, int));
1846 break;
1847 case 'D' :
1848 scanp = num_out((long) va_arg(argptr, long));
1849 break;
1850 default :
1851 scanp = "";
1853 while ((*buf++ = *scanp++) != 0)
1855 buf--;
1857 else
1858 *buf++ = *fmt++;
1860 va_end(argptr);
1861 *buf = '\0';
1865 * Output an (unsigned) long in a 10 digit field without leading zeros.
1866 * It returns a pointer to the first digit in the buffer.
1868 char *
1869 num_out(long number)
1871 static char num_buf[11]; /* Buffer to build number */
1872 long digit; /* Next digit of number */
1873 long pow = 1000000000L; /* Highest ten power of long */
1874 FLAG digit_seen = FALSE;
1875 int i;
1877 for (i = 0; i < 10; i++) {
1878 digit = number / pow; /* Get next digit */
1879 if (digit == 0L && digit_seen == FALSE && i != 9)
1880 num_buf[i] = ' ';
1881 else {
1882 num_buf[i] = '0' + (char) digit;
1883 number -= digit * pow; /* Erase digit */
1884 digit_seen = TRUE;
1886 pow /= 10L; /* Get next digit */
1888 for (i = 0; num_buf[i] == ' '; i++) /* Skip leading spaces */
1890 return (&num_buf[i]);
1894 * Get_number() read a number from the terminal. The last character typed in is
1895 * returned. ERRORS is returned on a bad number. The resulting number is put
1896 * into the integer the arguments points to.
1899 get_number(const char *message, int *result)
1901 int index;
1902 int count = 0;
1904 status_line(message, NIL_PTR);
1906 index = getchar();
1907 if (quit == FALSE && (index < '0' || index > '9')) {
1908 error("Bad count", NIL_PTR);
1909 return ERRORS;
1912 /* Convert input to a decimal number */
1913 while (index >= '0' && index <= '9' && quit == FALSE) {
1914 count *= 10;
1915 count += index - '0';
1916 index = getchar();
1919 if (quit == TRUE) {
1920 clear_status();
1921 return ERRORS;
1924 *result = count;
1925 return index;
1929 * Input() reads a string from the terminal. When the KILL character is typed,
1930 * it returns ERRORS.
1933 input(char *inbuf, FLAG clearfl)
1935 char *ptr;
1936 char c; /* Character read */
1938 ptr = inbuf;
1940 *ptr = '\0';
1941 while (quit == FALSE) {
1942 flush();
1943 switch (c = getchar()) {
1944 case '\b' : /* Erase previous char */
1945 if (ptr > inbuf) {
1946 ptr--;
1947 #ifdef UNIX
1948 tputs(SE, 0, _putchar);
1949 #else
1950 string_print(normal_video);
1951 #endif /* UNIX */
1952 if (is_tab(*ptr))
1953 string_print(" \b\b\b \b\b");
1954 else
1955 string_print(" \b\b \b");
1956 #ifdef UNIX
1957 tputs(SO, 0, _putchar);
1958 #else
1959 string_print(rev_video);
1960 #endif /* UNIX */
1961 string_print(" \b");
1962 *ptr = '\0';
1964 else
1965 ring_bell();
1966 break;
1967 case '\n' : /* End of input */
1968 /* If inbuf is empty clear status_line */
1969 return (ptr == inbuf && clearfl == TRUE) ? NO_INPUT :FINE;
1970 default : /* Only read ASCII chars */
1971 if ((c >= ' ' && c <= '~') || c == '\t') {
1972 *ptr++ = c;
1973 *ptr = '\0';
1974 if (c == '\t')
1975 string_print("^I");
1976 else
1977 putchar(c);
1978 string_print(" \b");
1980 else
1981 ring_bell();
1984 quit = FALSE;
1985 return ERRORS;
1989 * Get_file() reads a filename from the terminal. Filenames longer than
1990 * FILE_LENGHT chars are truncated.
1993 get_file(const char *message, char *file)
1995 char *ptr;
1996 int ret = FINE;
1998 if (message == NIL_PTR || (ret = get_string(message, file, TRUE)) == FINE) {
1999 if (length_of((ptr = basename(file))) > NAME_MAX)
2000 ptr[NAME_MAX] = '\0';
2002 return ret;
2005 /* ======================================================================== *
2006 * UNIX I/O Routines *
2007 * ======================================================================== */
2009 #ifdef UNIX
2010 #undef putchar
2013 _getchar(void)
2015 char c;
2017 if (read(input_fd, &c, 1) != 1 && quit == FALSE)
2018 panic ("Cannot read 1 byte from input");
2019 return c & 0377;
2022 void
2023 _flush(void)
2025 fflush(stdout);
2028 void
2029 _putchar(char c)
2031 write_char(STD_OUT, c);
2034 void
2035 get_term(void)
2037 static char termbuf[50];
2038 char *loc = termbuf;
2039 char entry[1024];
2041 if (tgetent(entry, getenv("TERM")) <= 0) {
2042 printf("Unknown terminal.\n");
2043 exit(1);
2046 AL = tgetstr("al", &loc);
2047 CE = tgetstr("ce", &loc);
2048 VS = tgetstr("vs", &loc);
2049 CL = tgetstr("cl", &loc);
2050 SO = tgetstr("so", &loc);
2051 SE = tgetstr("se", &loc);
2052 CM = tgetstr("cm", &loc);
2053 ymax = tgetnum("li") - 1;
2054 screenmax = ymax - 1;
2056 if (!CE || !SO || !SE || !CL || !AL || !CM) {
2057 printf("Sorry, no mined on this type of terminal\n");
2058 exit(1);
2061 #endif /* UNIX */