2 * Copyright (c) 1987,1997, Prentice Hall
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
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]
36 * $DragonFly: src/bin/mined/mined2.c,v 1.6 2005/11/06 11:44:02 swildner Exp $*
39 * Part 2 of the mined editor.
42 /* ======================================================================== *
44 * ======================================================================== */
56 if (y
== 0) { /* Top line of screen. Scroll one line */
60 else /* Move to previous line */
64 static const char *help_string
=
65 " Mined (Minix Editor), DragonFly version.\n"
66 "------------------------+-------------------------------+---------------------\n"
67 " CURSOR MOTION | EDITING | MISC\n"
68 " Up | ^N Delete next word | ^L Erase & redraw\n"
69 " Down cursor keys | ^P Delete prev. word | screen\n"
70 " Left | ^T Delete to EOL | ^\\ Abort current\n"
71 " Right +-------------------------------+ operation\n"
72 " ^A start of line | BLOCKS | Esc repeat last\n"
73 " ^E end of line | ^@ Set mark | cmd # times\n"
74 " ^^ screen top | ^K Delete mark <--> cursor | F2 file status\n"
75 " ^_ screen bottom | ^C Save mark <--> cursor +=====================\n"
76 " ^F word fwd. | ^Y Insert the contents of | ^X EXIT\n"
77 " ^B word back | the save file at cursor | ^S run shell\n"
78 "------------------------+ ^Q Insert the contents of +=====================\n"
79 " SCREEN MOTION | the save file into new | SEARCH & REPLACE\n"
80 " Home file top | file | F3 fwd. search\n"
81 " End file bottom +-------------------------------+ SF3 bck. search\n"
82 " PgUp page up | FILES | F4 Global replace\n"
83 " PgD page down | ^G Insert a file at cursor | SF4 Line replace\n"
84 " ^D rev. scroll | ^V Visit another file +---------------------\n"
85 " ^U fwd. scroll | ^W Write current file | F1 HELP\n"
86 " ^] goto line # | |\n"
87 "------------------------+-------------------------------+---------------------\n"
88 "Press any key to continue...";
95 string_print(enter_string
);
96 string_print(help_string
);
107 kill(getpid(), SIGTSTP
);
113 * Move one line down.
118 if (y
== last_y
) { /* Last line of screen. Scroll one line */
119 if (bot_line
->next
== tail
&& bot_line
->text
[0] != '\n') {
120 dummy_line(); /* Create new empty line */
129 else /* Move to next line */
134 * Move left one position.
139 if (x
== 0 && get_shift(cur_line
->shift_count
) == 0) {/* Begin of line */
140 if (cur_line
->prev
!= header
) {
141 UP(0); /* Move one line up */
142 move_to(LINE_END
, y
);
150 * Move right one position.
155 if (*cur_text
== '\n') {
156 if (cur_line
->next
!= tail
) { /* Last char of file */
157 DN(0); /* Move one line down */
158 move_to(LINE_START
, y
);
166 * Move to coordinates [0, 0] on screen.
175 * Move to coordinates [0, YMAX] on screen.
184 * Move to begin of line.
189 move_to(LINE_START
, y
);
193 * Move to end of line.
198 move_to(LINE_END
, y
);
202 * GOTO() prompts for a linenumber and moves to that line.
210 if (get_number("Please enter line number.", &number
) == ERRORS
)
213 if (number
<= 0 || (line
= proceed(header
->next
, number
- 1)) == tail
)
214 error("Illegal line number: ", num_out((long) number
));
216 move_to(x
, find_y(line
));
220 * Scroll forward one page or to eof, whatever comes first. (Bot_line becomes
221 * top_line of display.) Try to leave the cursor on the same line. If this is
222 * not possible, leave cursor on the line halfway the page.
229 for (i
= 0; i
< screenmax
; i
++)
230 if (forward_scroll() == ERRORS
)
231 break; /* EOF reached */
232 if (y
- i
< 0) /* Line no longer on screen */
233 move_to(0, screenmax
>> 1);
240 * Scroll backwards one page or to top of file, whatever comes first. (Top_line
241 * becomes bot_line of display). The very bottom line (YMAX) is always blank.
242 * Try to leave the cursor on the same line. If this is not possible, leave
243 * cursor on the line halfway the page.
250 for (i
= 0; i
< screenmax
; i
++)
251 if (reverse_scroll() == ERRORS
)
252 break; /* Top of file reached */
253 set_cursor(0, ymax
); /* Erase very bottom line */
255 tputs(CE
, 0, _putchar
);
257 string_print(blank_line
);
259 if (y
+ i
> screenmax
) /* line no longer on screen */
260 move_to(0, screenmax
>> 1);
266 * Go to top of file, scrolling if possible, else redrawing screen.
271 if (proceed(top_line
, -screenmax
) == header
)
272 PU(0); /* It fits. Let PU do it */
274 reset(header
->next
, 0);/* Reset top_line, etc. */
275 RD(0); /* Display full page */
277 move_to(LINE_START
, 0);
281 * Go to last line of file, scrolling if possible, else redrawing screen
286 if (tail
->prev
->text
[0] != '\n')
288 if (proceed(bot_line
, screenmax
) == tail
)
289 PD(0); /* It fits. Let PD do it */
291 reset(proceed(tail
->prev
, -screenmax
), screenmax
);
292 RD(0); /* Display full page */
294 move_to(LINE_START
, last_y
);
298 * Scroll one line up. Leave the cursor on the same line (if possible).
303 if (top_line
->prev
== header
) /* Top of file. Can't scroll */
307 set_cursor(0, ymax
); /* Erase very bottom line */
309 tputs(CE
, 0, _putchar
);
311 string_print(blank_line
);
313 move_to(x
, (y
== screenmax
) ? screenmax
: y
+ 1);
317 * Scroll one line down. Leave the cursor on the same line (if possible).
322 if (forward_scroll() != ERRORS
)
323 move_to(x
, (y
== 0) ? 0 : y
- 1);
329 * Perform a forward scroll. It returns ERRORS if we're at the last line of the
335 if (bot_line
->next
== tail
) /* Last line of file. No dice */
337 top_line
= top_line
->next
;
338 bot_line
= bot_line
->next
;
339 cur_line
= cur_line
->next
;
341 line_print(bot_line
);
347 * Perform a backwards scroll. It returns ERRORS if we're at the first line
353 if (top_line
->prev
== header
)
354 return ERRORS
; /* Top of file. Can't scroll */
356 if (last_y
!= screenmax
) /* Reset last_y if necessary */
359 bot_line
= bot_line
->prev
; /* Else adjust bot_line */
360 top_line
= top_line
->prev
;
361 cur_line
= cur_line
->prev
;
363 /* Perform the scroll */
366 tputs(AL
, 0, _putchar
);
368 string_print(rev_scroll
);
371 line_print(top_line
);
377 * A word is defined as a number of non-blank characters separated by tabs
378 * spaces or linefeeds.
382 * MP() moves to the start of the previous word. A word is defined as a
383 * number of non-blank characters separated by tabs spaces or linefeeds.
388 move_previous_word(NO_DELETE
);
392 move_previous_word(FLAG remove
)
396 char start_char
= *cur_text
;
397 char *start_pos
= cur_text
;
399 /* Fist check if we're at the beginning of line. */
400 if (cur_text
== cur_line
->text
) {
401 if (cur_line
->prev
== header
)
408 begin_line
= cur_line
->text
;
411 /* Check if we're in the middle of a word. */
412 if (!alpha(*textp
) || !alpha(start_char
)) {
413 while (textp
!= begin_line
&& (white_space(*textp
) || *textp
== '\n'))
417 /* Now we're at the end of previous word. Skip non-blanks until a blank comes */
418 while (textp
!= begin_line
&& alpha(*textp
))
421 /* Go to the next char if we're not at the beginning of the line */
422 if (textp
!= begin_line
&& *textp
!= '\n')
425 /* Find the x-coordinate of this address, and move to it */
427 if (remove
== DELETE
)
428 delete(cur_line
, textp
, cur_line
, start_pos
);
432 * MN() moves to the start of the next word. A word is defined as a number of
433 * non-blank characters separated by tabs spaces or linefeeds. Always keep in
434 * mind that the pointer shouldn't pass the '\n'.
439 move_next_word(NO_DELETE
);
443 move_next_word(FLAG remove
)
445 char *textp
= cur_text
;
447 /* Move to the end of the current word. */
448 while (*textp
!= '\n' && alpha(*textp
))
451 /* Skip all white spaces */
452 while (*textp
!= '\n' && white_space(*textp
))
454 /* If we're deleting. delete the text in between */
455 if (remove
== DELETE
) {
456 delete(cur_line
, cur_text
, cur_line
, textp
);
460 /* If we're at end of line. move to the first word on the next line. */
461 if (*textp
== '\n' && cur_line
->next
!= tail
) {
463 move_to(LINE_START
, y
);
465 while (*textp
!= '\n' && white_space(*textp
))
471 /* ======================================================================== *
473 * ======================================================================== */
476 * DCC deletes the character under the cursor. If this character is a '\n' the
477 * current line is joined with the next one.
478 * If this character is the only character of the line, the current line will
484 if (*cur_text
== '\n')
485 delete(cur_line
,cur_text
, cur_line
->next
,cur_line
->next
->text
);
487 delete(cur_line
, cur_text
, cur_line
, cur_text
+ 1);
491 * DPC deletes the character on the left side of the cursor. If the cursor is
492 * at the beginning of the line, the last character if the previous line is
498 if (x
== 0 && cur_line
->prev
== header
)
499 return; /* Top of file */
501 LF(0); /* Move one left */
502 DCC(0); /* Delete character under cursor */
506 * DLN deletes all characters until the end of the line. If the current
507 * character is a '\n', then delete that char.
512 if (*cur_text
== '\n')
515 delete(cur_line
, cur_text
, cur_line
, cur_text
+ length_of(cur_text
) -1);
519 * DNW() deletes the next word (as described in MN())
524 if (*cur_text
== '\n')
527 move_next_word(DELETE
);
531 * DPW() deletes the next word (as described in MP())
536 if (cur_text
== cur_line
->text
)
539 move_previous_word(DELETE
);
543 * Insert character `character' at current location.
548 static char buffer
[2];
550 buffer
[0] = character
;
551 /* Insert the character */
552 if (insert(cur_line
, cur_text
, buffer
) == ERRORS
)
556 if (character
== '\n') {
558 if (y
== screenmax
) { /* Can't use display */
559 line_print(cur_line
);
563 reset(top_line
, y
); /* Reset pointers */
564 display(0, y
, cur_line
, last_y
- y
);
566 move_to(0, (y
== screenmax
) ? y
: y
+ 1);
568 else if (x
+ 1 == XBREAK
)/* If line must be shifted, just call move_to*/
570 else { /* else display rest of line */
571 put_line(cur_line
, x
, FALSE
);
577 * CTL inserts a control-char at the current location. A message that this
578 * function is called is displayed at the status line.
585 status_line("Enter control character.", NIL_PTR
);
586 if ((ctrl
= getchar()) >= '\01' && ctrl
<= '\037') {
587 S(ctrl
); /* Insert the char */
591 error ("Unknown control character", NIL_PTR
);
595 * LIB insert a line at the current position and moves back to the end of
601 S('\n'); /* Insert the line */
602 UP(0); /* Move one line up */
603 move_to(LINE_END
, y
); /* Move to end of this line */
607 * Line_insert() inserts a new line with text pointed to by `string'.
608 * It returns the address of the new line.
611 line_insert(LINE
*line
, const char *string
, int len
)
615 /* Allocate space for LINE structure and text */
616 new_line
= install_line(string
, len
);
618 /* Install the line into the double linked list */
619 new_line
->prev
= line
;
620 new_line
->next
= line
->next
;
621 line
->next
= new_line
;
622 new_line
->next
->prev
= new_line
;
624 /* Increment nlines */
631 * Insert() insert the string `string' at the given line and location.
634 insert(LINE
*line
, char *location
, char *string
)
636 char *bufp
= text_buffer
; /* Buffer for building line */
637 char *textp
= line
->text
;
639 if (length_of(textp
) + length_of(string
) >= MAX_CHARS
) {
640 error("Line too long", NIL_PTR
);
644 modified
= TRUE
; /* File has been modified */
646 /* Copy part of line until `location' has been reached */
647 while (textp
!= location
)
650 /* Insert string at this location */
651 while (*string
!= '\0')
655 if (*(string
- 1) == '\n') /* Insert a new line */
656 line_insert(line
, location
, length_of(location
));
657 else /* Append last part of line */
658 copy_string(bufp
, location
);
660 /* Install the new text in this line */
661 free_space(line
->text
);
662 line
->text
= alloc(length_of(text_buffer
) + 1);
663 copy_string(line
->text
, text_buffer
);
669 * Line_delete() deletes the argument line out of the line list. The pointer to
670 * the next line is returned.
673 line_delete(LINE
*line
)
675 LINE
*next_line
= line
->next
;
677 /* Delete the line */
678 line
->prev
->next
= line
->next
;
679 line
->next
->prev
= line
->prev
;
681 /* Free allocated space */
682 free_space(line
->text
);
683 free_space((char*)line
);
685 /* Decrement nlines */
692 * Delete() deletes all the characters (including newlines) between the
693 * startposition and endposition and fixes the screen accordingly. It
694 * returns the number of lines deleted.
697 delete(LINE
*start_line
, char *start_textp
,
698 LINE
*end_line
, char *end_textp
)
700 char *textp
= start_line
->text
;
701 char *bufp
= text_buffer
; /* Storage for new line->text */
703 int line_cnt
= 0; /* Nr of lines deleted */
705 int shift
= 0; /* Used in shift calculation */
708 modified
= TRUE
; /* File has been modified */
710 /* Set up new line. Copy first part of start line until start_position. */
711 while (textp
< start_textp
) {
716 /* Check if line doesn't exceed MAX_CHARS */
717 if (count
+ length_of(end_textp
) >= MAX_CHARS
) {
718 error("Line too long", NIL_PTR
);
722 /* Copy last part of end_line if end_line is not tail */
723 copy_string(bufp
, (end_textp
!= NIL_PTR
) ? end_textp
: "\n");
725 /* Delete all lines between start and end_position (including end_line) */
726 line
= start_line
->next
;
727 stop
= end_line
->next
;
728 while (line
!= stop
&& line
!= tail
) {
729 line
= line_delete(line
);
733 /* Check if last line of file should be deleted */
734 if (end_textp
== NIL_PTR
&& length_of(start_line
->text
) == 1 && nlines
> 1) {
735 start_line
= start_line
->prev
;
736 line_delete(start_line
->next
);
739 else { /* Install new text */
740 free_space(start_line
->text
);
741 start_line
->text
= alloc(length_of(text_buffer
) + 1);
742 copy_string(start_line
->text
, text_buffer
);
745 /* Fix screen. First check if line is shifted. Perhaps we should shift it back*/
746 if (get_shift(start_line
->shift_count
)) {
747 shift
= (XBREAK
- count_chars(start_line
)) / SHIFT_SIZE
;
748 if (shift
> 0) { /* Shift line `shift' back */
749 if (shift
>= get_shift(start_line
->shift_count
))
750 start_line
->shift_count
= 0;
752 start_line
->shift_count
-= shift
;
753 nx
+= shift
* SHIFT_SIZE
;/* Reset x value */
757 if (line_cnt
== 0) { /* Check if only one line changed */
758 if (shift
> 0) { /* Reprint whole line */
760 line_print(start_line
);
762 else { /* Just display last part of line */
764 put_line(start_line
, x
, TRUE
);
766 move_to(nx
, y
); /* Reset cur_text */
770 shift
= last_y
; /* Save value */
772 display(0, y
, start_line
, shift
- y
);
773 move_to((line_cnt
== 1) ? nx
: 0, y
);
776 /* ======================================================================== *
778 * ======================================================================== */
780 LINE
*mark_line
; /* For marking position. */
782 int lines_saved
; /* Nr of lines in buffer */
785 * PT() inserts the buffer at the current location.
790 int fd
; /* File descriptor for buffer */
792 if ((fd
= scratch_file(READ
)) == ERRORS
)
793 error("Buffer is empty.", NIL_PTR
);
795 file_insert(fd
, FALSE
);/* Insert the buffer */
801 * IF() prompt for a filename and inserts the file at the current location
807 int fd
; /* File descriptor of file */
808 char name
[LINE_LEN
]; /* Buffer for file name */
810 /* Get the file name */
811 if (get_file("Get and insert file:", name
) != FINE
)
814 if ((fd
= open(name
, 0)) < 0)
815 error("Cannot open ", name
);
817 file_insert(fd
, TRUE
); /* Insert the file */
823 * File_insert() inserts a an opened file (as given by filedescriptor fd)
824 * at the current location.
827 file_insert(int fd
, FLAG old_pos
)
829 char line_buffer
[MAX_CHARS
]; /* Buffer for next line */
830 LINE
*line
= cur_line
;
831 int line_count
= nlines
; /* Nr of lines inserted */
832 LINE
*page
= cur_line
;
835 /* Get the first piece of text (might be ended with a '\n') from fd */
836 if (get_line(fd
, line_buffer
) == ERRORS
)
837 return; /* Empty file */
839 /* Insert this text at the current location. */
840 if (insert(line
, cur_text
, line_buffer
) == ERRORS
)
843 /* Repeat getting lines (and inserting lines) until EOF is reached */
844 while ((ret
= get_line(fd
, line_buffer
)) != ERRORS
&& ret
!= NO_LINE
)
845 line
= line_insert(line
, line_buffer
, ret
);
847 if (ret
== NO_LINE
) { /* Last line read not ended by a '\n' */
849 insert(line
, line
->text
, line_buffer
);
852 /* Calculate nr of lines added */
853 line_count
= nlines
- line_count
;
856 if (line_count
== 0) { /* Only one line changed */
859 move_to((old_pos
== TRUE
) ? x
: x
+ length_of(line_buffer
), y
);
861 else { /* Several lines changed */
862 reset(top_line
, y
); /* Reset pointers */
863 while (page
!= line
&& page
!= bot_line
->next
)
865 if (page
!= bot_line
->next
|| old_pos
== TRUE
)
866 display(0, y
, cur_line
, screenmax
- y
);
869 else if (ret
== NO_LINE
)
870 move_to(length_of(line_buffer
), find_y(line
));
872 move_to(0, find_y(line
->next
));
875 /* If nr of added line >= REPORT, print the count */
876 if (line_count
>= REPORT
)
877 status_line(num_out((long) line_count
), " lines added.");
881 * WB() writes the buffer (yank_file) into another file, which
887 int new_fd
; /* Filedescriptor to copy file */
888 int yank_fd
; /* Filedescriptor to buffer */
889 int cnt
; /* Count check for read/write */
890 int ret
= 0; /* Error check for write */
891 char file
[LINE_LEN
]; /* Output file */
893 /* Checkout the buffer */
894 if ((yank_fd
= scratch_file(READ
)) == ERRORS
) {
895 error("Buffer is empty.", NIL_PTR
);
900 if (get_file("Write buffer to file:", file
) != FINE
)
903 /* Creat the new file */
904 if ((new_fd
= creat(file
, 0644)) < 0) {
905 error("Cannot create ", file
);
909 status_line("Writing ", file
);
911 /* Copy buffer into file */
912 while ((cnt
= read(yank_fd
, text_buffer
, sizeof(text_buffer
))) > 0)
913 if (write(new_fd
, text_buffer
, cnt
) != cnt
) {
919 /* Clean up open files and status_line */
923 if (ret
!= ERRORS
) /* Bad write */
924 file_status("Wrote", chars_saved
, file
, lines_saved
, TRUE
, FALSE
);
928 * MA sets mark_line (mark_text) to the current line (text pointer).
933 mark_line
= cur_line
;
934 mark_text
= cur_text
;
935 status_line("Mark set", NIL_PTR
);
939 * YA() puts the text between the marked position and the current
949 * DT() is essentially the same as YA(), but in DT() the text is deleted.
958 * Set_up is an interface to the actual yank. It calls checkmark () to check
959 * if the marked position is still valid. If it is, yank is called with the
960 * arguments in the right order.
963 * remove: DELETE if text should be deleted
968 switch (checkmark()) {
970 error("Mark not set.", NIL_PTR
);
973 yank(mark_line
, mark_text
, cur_line
, cur_text
, remove
);
976 yank(cur_line
, cur_text
, mark_line
, mark_text
, remove
);
978 case SAME
: /* Ignore stupid behaviour */
981 status_line("0 characters saved in buffer.", NIL_PTR
);
987 * Check_mark() checks if mark_line and mark_text are still valid pointers. If
988 * they are it returns SMALLER if the marked position is before the current,
989 * BIGGER if it isn't or SAME if somebody didn't get the point.
990 * NOT_VALID is returned when mark_line and/or mark_text are no longer valid.
991 * Legal() checks if mark_text is valid on the mark_line.
997 FLAG cur_seen
= FALSE
;
999 /* Special case: check is mark_line and cur_line are the same. */
1000 if (mark_line
== cur_line
) {
1001 if (mark_text
== cur_text
) /* Even same place */
1003 if (legal() == ERRORS
) /* mark_text out of range */
1005 return (mark_text
< cur_text
) ? SMALLER
: BIGGER
;
1008 /* Start looking for mark_line in the line structure */
1009 for (line
= header
->next
; line
!= tail
; line
= line
->next
) {
1010 if (line
== cur_line
)
1012 else if (line
== mark_line
)
1016 /* If we found mark_line (line != tail) check for legality of mark_text */
1017 if (line
== tail
|| legal() == ERRORS
)
1020 /* cur_seen is TRUE if cur_line is before mark_line */
1021 return (cur_seen
== TRUE
) ? BIGGER
: SMALLER
;
1025 * Legal() checks if mark_text is still a valid pointer.
1030 char *textp
= mark_line
->text
;
1032 /* Locate mark_text on mark_line */
1033 while (textp
!= mark_text
&& *textp
++ != '\0')
1035 return (*textp
== '\0') ? ERRORS
: FINE
;
1039 * Yank puts all the text between start_position and end_position into
1041 * The caller must check that the arguments to yank() are valid. (E.g. in
1045 * remove: DELETE if text should be deleted
1048 yank(LINE
*start_line
, char *start_textp
, LINE
*end_line
, char *end_textp
,
1051 LINE
*line
= start_line
;
1052 char *textp
= start_textp
;
1055 /* Creat file to hold buffer */
1056 if ((fd
= scratch_file(WRITE
)) == ERRORS
)
1061 status_line("Saving text.", NIL_PTR
);
1063 /* Keep writing chars until the end_location is reached. */
1064 while (textp
!= end_textp
) {
1065 if (write_char(fd
, *textp
) == ERRORS
) {
1069 if (*textp
++ == '\n') { /* Move to the next line */
1077 /* Flush the I/O buffer and close file */
1078 if (flush_buffer(fd
) == ERRORS
) {
1083 yank_status
= VALID
;
1086 * Check if the text should be deleted as well. If it should, the following
1087 * hack is used to save a lot of code. First move back to the start_position.
1088 * (This might be the location we're on now!) and them delete the text.
1089 * It might be a bit confusing the first time somebody uses it.
1090 * Delete() will fix the screen.
1092 if (remove
== DELETE
) {
1093 move_to(find_x(start_line
, start_textp
), find_y(start_line
));
1094 delete(start_line
, start_textp
, end_line
, end_textp
);
1097 status_line(num_out(chars_saved
), " characters saved in buffer.");
1101 * Scratch_file() creates a uniq file in /usr/tmp. If the file couldn't
1102 * be created other combinations of files are tried until a maximum
1103 * of MAXTRAILS times. After MAXTRAILS times, an error message is given
1104 * and ERRORS is returned.
1107 #define MAXTRAILS 26
1111 * mode: Can be READ or WRITE permission
1114 scratch_file(FLAG mode
)
1116 static int trials
= 0; /* Keep track of trails */
1117 char *y_ptr
, *n_ptr
;
1118 int fd
= ERRORS
; /* Filedescriptor to buffer */
1120 /* If yank_status == NOT_VALID, scratch_file is called for the first time */
1121 if (yank_status
== NOT_VALID
&& mode
== WRITE
) { /* Create new file */
1122 /* Generate file name. */
1123 y_ptr
= &yank_file
[11];
1124 n_ptr
= num_out((long) getpid());
1125 while ((*y_ptr
= *n_ptr
++) != '\0')
1127 *y_ptr
++ = 'a' + trials
;
1129 /* Check file existence */
1130 if (access(yank_file
, 0) == 0 || (fd
= creat(yank_file
, 0644)) < 0) {
1131 if (trials
++ >= MAXTRAILS
) {
1132 error("Unable to creat scratchfile.", NIL_PTR
);
1136 return scratch_file(mode
);/* Have another go */
1139 else if ((mode
== READ
&& (fd
= open(yank_file
, 0)) < 0) ||
1140 (mode
== WRITE
&& (fd
= creat(yank_file
, 0644)) < 0)) {
1141 yank_status
= NOT_VALID
;
1149 /* ======================================================================== *
1151 * ======================================================================== */
1154 * A regular expression consists of a sequence of:
1155 * 1. A normal character matching that character.
1156 * 2. A . matching any character.
1157 * 3. A ^ matching the begin of a line.
1158 * 4. A $ (as last character of the pattern) mathing the end of a line.
1159 * 5. A \<character> matching <character>.
1160 * 6. A number of characters enclosed in [] pairs matching any of these
1161 * characters. A list of characters can be indicated by a '-'. So
1162 * [a-z] matches any letter of the alphabet. If the first character
1163 * after the '[' is a '^' then the set is negated (matching none of
1165 * A ']', '^' or '-' can be escaped by putting a '\' in front of it.
1166 * 7. If one of the expressions as described in 1-6 is followed by a
1167 * '*' than that expressions matches a sequence of 0 or more of
1171 char typed_expression
[LINE_LEN
]; /* Holds previous expr. */
1174 * SF searches forward for an expression.
1179 search("Search forward:", FORWARD
);
1183 * SF searches backwards for an expression.
1188 search("Search reverse:", REVERSE
);
1192 * Get_expression() prompts for an expression. If just a return is typed, the
1193 * old expression is used. If the expression changed, compile() is called and
1194 * the returning REGEX structure is returned. It returns NIL_REG upon error.
1195 * The save flag indicates whether the expression should be appended at the
1199 get_expression(const char *message
)
1201 static REGEX program
; /* Program of expression */
1202 char exp_buf
[LINE_LEN
]; /* Buffer for new expr. */
1204 if (get_string(message
, exp_buf
, FALSE
) == ERRORS
)
1207 if (exp_buf
[0] == '\0' && typed_expression
[0] == '\0') {
1208 error("No previous expression.", NIL_PTR
);
1212 if (exp_buf
[0] != '\0') { /* A new expr. is typed */
1213 copy_string(typed_expression
, exp_buf
);/* Save expr. */
1214 compile(exp_buf
, &program
); /* Compile new expression */
1217 if (program
.status
== REG_ERROR
) { /* Error during compiling */
1218 error(program
.result
.err_mess
, NIL_PTR
);
1225 * GR() a replaces all matches from the current position until the end
1231 change("Global replace:", VALID
);
1235 * LR() replaces all matches on the current line.
1240 change("Line replace:", NOT_VALID
);
1244 * Change() prompts for an expression and a substitution pattern and changes
1245 * all matches of the expression into the substitution. change() start looking
1246 * for expressions at the current line and continues until the end of the file
1247 * if the FLAG file is VALID.
1250 * message: Message to prompt for expression
1253 change(const char *message
, FLAG file
)
1255 char mess_buf
[LINE_LEN
]; /* Buffer to hold message */
1256 char replacement
[LINE_LEN
]; /* Buffer to hold subst. pattern */
1257 REGEX
*program
; /* Program resulting from compilation */
1258 LINE
*line
= cur_line
;
1260 long lines
= 0L; /* Nr of lines on which subs occurred */
1261 long subs
= 0L; /* Nr of subs made */
1262 int page
= y
; /* Index to check if line is on screen*/
1264 /* Save message and get expression */
1265 copy_string(mess_buf
, message
);
1266 if ((program
= get_expression(mess_buf
)) == NIL_REG
)
1269 /* Get substitution pattern */
1270 build_string(mess_buf
, "%s %s by:", mess_buf
, typed_expression
);
1271 if (get_string(mess_buf
, replacement
, FALSE
) == ERRORS
)
1274 set_cursor(0, ymax
);
1276 /* Substitute until end of file */
1278 if (line_check(program
, line
->text
, FORWARD
)) {
1280 /* Repeat sub. on this line as long as we find a match*/
1282 subs
++; /* Increment subs */
1283 if ((textp
= substitute(line
, program
,replacement
))
1285 return; /* Line too long */
1286 } while ((program
->status
& BEGIN_LINE
) != BEGIN_LINE
&&
1287 (program
->status
& END_LINE
) != END_LINE
&&
1288 line_check(program
, textp
, FORWARD
));
1289 /* Check to see if we can print the result */
1290 if (page
<= screenmax
) {
1291 set_cursor(0, page
);
1295 if (page
<= screenmax
)
1298 } while (line
!= tail
&& file
== VALID
&& quit
== FALSE
);
1300 copy_string(mess_buf
, (quit
== TRUE
) ? "(Aborted) " : "");
1301 /* Fix the status line */
1302 if (subs
== 0L && quit
== FALSE
)
1303 error("Pattern not found.", NIL_PTR
);
1304 else if (lines
>= REPORT
|| quit
== TRUE
) {
1305 build_string(mess_buf
, "%s %D substitutions on %D lines.", mess_buf
,
1307 status_line(mess_buf
, NIL_PTR
);
1309 else if (file
== NOT_VALID
&& subs
>= REPORT
)
1310 status_line(num_out(subs
), " substitutions.");
1317 * Substitute() replaces the match on this line by the substitute pattern
1318 * as indicated by the program. Every '&' in the replacement is replaced by
1319 * the original match. A \ in the replacement escapes the next character.
1322 * replacement: Contains replacement pattern
1325 substitute(LINE
*line
, REGEX
*program
, char *replacement
)
1327 char *textp
= text_buffer
;
1328 char *subp
= replacement
;
1329 char *linep
= line
->text
;
1334 /* Copy part of line until the beginning of the match */
1335 while (linep
!= program
->start_ptr
)
1336 *textp
++ = *linep
++;
1339 * Replace the match by the substitution pattern. Each occurrence of '&' is
1340 * replaced by the original match. A \ escapes the next character.
1342 while (*subp
!= '\0' && textp
< &text_buffer
[MAX_CHARS
]) {
1343 if (*subp
== '&') { /* Replace the original match */
1344 amp
= program
->start_ptr
;
1345 while (amp
< program
->end_ptr
&& textp
<&text_buffer
[MAX_CHARS
])
1350 if (*subp
== '\\' && *(subp
+ 1) != '\0')
1356 /* Check for line length not exceeding MAX_CHARS */
1357 if (length_of(text_buffer
) + length_of(program
->end_ptr
) >= MAX_CHARS
) {
1358 error("Substitution result: line too big", NIL_PTR
);
1362 /* Append last part of line to the new build line */
1363 copy_string(textp
, program
->end_ptr
);
1365 /* Free old line and install new one */
1366 free_space(line
->text
);
1367 line
->text
= alloc(length_of(text_buffer
) + 1);
1368 copy_string(line
->text
, text_buffer
);
1370 return(line
->text
+ (textp
- text_buffer
));
1374 * Search() calls get_expression to fetch the expression. If this went well,
1375 * the function match() is called which returns the line with the next match.
1376 * If this line is the NIL_LINE, it means that a match could not be found.
1377 * Find_x() and find_y() display the right page on the screen, and return
1378 * the right coordinates for x and y. These coordinates are passed to move_to()
1381 search(const char *message
, FLAG method
)
1386 /* Get the expression */
1387 if ((program
= get_expression(message
)) == NIL_REG
)
1390 set_cursor(0, ymax
);
1392 /* Find the match */
1393 if ((match_line
= match(program
, cur_text
, method
)) == NIL_LINE
) {
1395 status_line("Aborted", NIL_PTR
);
1397 status_line("Pattern not found.", NIL_PTR
);
1401 move(0, program
->start_ptr
, find_y(match_line
));
1406 * find_y() checks if the matched line is on the current page. If it is, it
1407 * returns the new y coordinate, else it displays the correct page with the
1408 * matched line in the middle and returns the new y value;
1411 find_y(LINE
*match_line
)
1416 /* Check if match_line is on the same page as currently displayed. */
1417 for (line
= top_line
; line
!= match_line
&& line
!= bot_line
->next
;
1420 if (line
!= bot_line
->next
)
1423 /* Display new page, with match_line in center. */
1424 if ((line
= proceed(match_line
, -(screenmax
>> 1))) == header
) {
1425 /* Can't display in the middle. Make first line of file top_line */
1427 for (line
= header
->next
; line
!= match_line
; line
= line
->next
)
1429 line
= header
->next
;
1431 else /* New page is displayed. Set cursor to middle of page */
1432 count
= screenmax
>> 1;
1434 /* Reset pointers and redraw the screen */
1441 /* Opcodes for characters */
1442 #define NORMAL 0x0200
1446 #define BRACKET 0x2000
1447 #define NEGATE 0x0100
1450 /* Mask for opcodes and characters */
1451 #define LOW_BYTE 0x00FF
1452 #define HIGH_BYTE 0xFF00
1454 /* Previous is the contents of the previous address (ptr) points to */
1455 #define previous(ptr) (*((ptr) - 1))
1457 /* Buffer to store outcome of compilation */
1458 int exp_buffer
[BLOCK_SIZE
];
1460 /* Errors often used */
1461 static const char *too_long
= "Regular expression too long";
1464 * Reg_error() is called by compile() is something went wrong. It set the
1465 * status of the structure to error, and assigns the error field of the union.
1467 #define reg_error(str) program->status = REG_ERROR, \
1468 program->result.err_mess = (str)
1470 * Finished() is called when everything went right during compilation. It
1471 * allocates space for the expression, and copies the expression buffer into
1475 finished(REGEX
*program
, int *last_exp
)
1477 int length
= (last_exp
- exp_buffer
) * sizeof(int);
1479 /* Allocate space */
1480 program
->result
.expression
= (int *) alloc(length
);
1481 /* Copy expression. (expression consists of ints!) */
1482 bcopy(exp_buffer
, program
->result
.expression
, length
);
1486 * Compile compiles the pattern into a more comprehensible form and returns a
1487 * REGEX structure. If something went wrong, the status field of the structure
1488 * is set to REG_ERROR and an error message is set into the err_mess field of
1489 * the union. If all went well the expression is saved and the expression
1490 * pointer is set to the saved (and compiled) expression.
1493 * pattern: Pointer to pattern
1496 compile(char *pattern
, REGEX
*program
)
1498 int *expression
= exp_buffer
;
1499 int *prev_char
; /* Pointer to previous compiled atom */
1500 int *acct_field
= NULL
; /* Pointer to last BRACKET start */
1501 FLAG negate
; /* Negate flag for BRACKET */
1502 char low_char
; /* Index for chars in BRACKET */
1505 /* Check for begin of line */
1506 if (*pattern
== '^') {
1507 program
->status
= BEGIN_LINE
;
1511 program
->status
= 0;
1512 /* If the first character is a '*' we have to assign it here. */
1513 if (*pattern
== '*') {
1514 *expression
++ = '*' + NORMAL
;
1520 switch (c
= *pattern
++) {
1522 *expression
++ = DOT
;
1526 * Only means EOLN if it is the last char of the pattern
1528 if (*pattern
== '\0') {
1529 *expression
++ = EOLN
| DONE
;
1530 program
->status
|= END_LINE
;
1531 finished(program
, expression
);
1535 *expression
++ = NORMAL
+ '$';
1538 *expression
++ = DONE
;
1539 finished(program
, expression
);
1542 /* If last char, it must! mean a normal '\' */
1543 if (*pattern
== '\0')
1544 *expression
++ = NORMAL
+ '\\';
1546 *expression
++ = NORMAL
+ *pattern
++;
1550 * If the previous expression was a [] find out the
1551 * begin of the list, and adjust the opcode.
1553 prev_char
= expression
- 1;
1554 if (*prev_char
& BRACKET
)
1555 *(expression
- (*acct_field
& LOW_BYTE
))|= STAR
;
1561 * First field in expression gives information about
1563 * The opcode consists of BRACKET and if necessary
1564 * NEGATE to indicate that the list should be negated
1565 * and/or STAR to indicate a number of sequence of this
1567 * The lower byte contains the length of the list.
1569 acct_field
= expression
++;
1570 if (*pattern
== '^') { /* List must be negated */
1576 while (*pattern
!= ']') {
1577 if (*pattern
== '\0') {
1578 reg_error("Missing ]");
1581 if (*pattern
== '\\')
1583 *expression
++ = *pattern
++;
1584 if (*pattern
== '-') {
1585 /* Make list of chars */
1586 low_char
= previous(pattern
);
1587 pattern
++; /* Skip '-' */
1588 if (low_char
++ > *pattern
) {
1589 reg_error("Bad range in [a-z]");
1593 while (low_char
<= *pattern
)
1594 *expression
++ = low_char
++;
1597 if (expression
>= &exp_buffer
[BLOCK_SIZE
]) {
1598 reg_error(too_long
);
1602 pattern
++; /* Skip ']' */
1603 /* Assign length of list in acct field */
1604 if ((*acct_field
= (expression
- acct_field
)) == 1) {
1605 reg_error("Empty []");
1608 /* Assign negate and bracket field */
1609 *acct_field
|= BRACKET
;
1611 *acct_field
|= NEGATE
;
1613 * Add BRACKET to opcode of last char in field because
1614 * a '*' may be following the list.
1616 previous(expression
) |= BRACKET
;
1619 *expression
++ = c
+ NORMAL
;
1621 if (expression
== &exp_buffer
[BLOCK_SIZE
]) {
1622 reg_error(too_long
);
1630 * Match gets as argument the program, pointer to place in current line to
1631 * start from and the method to search for (either FORWARD or REVERSE).
1632 * Match() will look through the whole file until a match is found.
1633 * NIL_LINE is returned if no match could be found.
1636 match(REGEX
*program
, char *string
, FLAG method
)
1638 LINE
*line
= cur_line
;
1639 char old_char
; /* For saving chars */
1641 /* Corrupted program */
1642 if (program
->status
== REG_ERROR
)
1645 /* Check part of text first */
1646 if (!(program
->status
& BEGIN_LINE
)) {
1647 if (method
== FORWARD
) {
1648 if (line_check(program
, string
+ 1, method
) == MATCH
)
1649 return cur_line
; /* Match found */
1651 else if (!(program
->status
& END_LINE
)) {
1652 old_char
= *string
; /* Save char and */
1653 *string
= '\n'; /* Assign '\n' for line_check */
1654 if (line_check(program
, line
->text
, method
) == MATCH
) {
1655 *string
= old_char
; /* Restore char */
1656 return cur_line
; /* Found match */
1658 *string
= old_char
; /* No match, but restore char */
1662 /* No match in last (or first) part of line. Check out rest of file */
1664 line
= (method
== FORWARD
) ? line
->next
: line
->prev
;
1665 if (line
->text
== NIL_PTR
) /* Header/tail */
1667 if (line_check(program
, line
->text
, method
) == MATCH
)
1669 } while (line
!= cur_line
&& quit
== FALSE
);
1671 /* No match found. */
1676 * Line_check() checks the line (or rather string) for a match. Method
1677 * indicates FORWARD or REVERSE search. It scans through the whole string
1678 * until a match is found, or the end of the string is reached.
1681 line_check(REGEX
*program
, char *string
, FLAG method
)
1683 char *textp
= string
;
1685 /* Assign start_ptr field. We might find a match right away! */
1686 program
->start_ptr
= textp
;
1688 /* If the match must be anchored, just check the string. */
1689 if (program
->status
& BEGIN_LINE
)
1690 return check_string(program
, string
, NIL_INT
);
1692 if (method
== REVERSE
) {
1693 /* First move to the end of the string */
1694 for (textp
= string
; *textp
!= '\n'; textp
++)
1696 /* Start checking string until the begin of the string is met */
1697 while (textp
>= string
) {
1698 program
->start_ptr
= textp
;
1699 if (check_string(program
, textp
--, NIL_INT
))
1704 /* Move through the string until the end of is found */
1705 while (quit
== FALSE
&& *textp
!= '\0') {
1706 program
->start_ptr
= textp
;
1707 if (check_string(program
, textp
, NIL_INT
))
1719 * Check() checks of a match can be found in the given string. Whenever a STAR
1720 * is found during matching, then the begin position of the string is marked
1721 * and the maximum number of matches is performed. Then the function star()
1722 * is called which starts to finish the match from this position of the string
1723 * (and expression). Check() return MATCH for a match, NO_MATCH is the string
1724 * couldn't be matched or REG_ERROR for an illegal opcode in expression.
1727 check_string(REGEX
*program
, char *string
, int *expression
)
1729 int opcode
; /* Holds opcode of next expr. atom */
1730 char c
; /* Char that must be matched */
1731 char *mark
= NULL
; /* For marking position */
1732 int star_fl
; /* A star has been born */
1734 if (expression
== NIL_INT
)
1735 expression
= program
->result
.expression
;
1737 /* Loop until end of string or end of expression */
1738 while (quit
== FALSE
&& !(*expression
& DONE
) &&
1739 *string
!= '\0' && *string
!= '\n') {
1740 c
= *expression
& LOW_BYTE
; /* Extract match char */
1741 opcode
= *expression
& HIGH_BYTE
; /* Extract opcode */
1742 if ((star_fl
= (opcode
& STAR
)) != 0) { /* Check star occurrence */
1743 opcode
&= ~STAR
; /* Strip opcode */
1744 mark
= string
; /* Mark current position */
1746 expression
++; /* Increment expr. */
1750 while (*string
++ == c
) /* Skip all matches */
1752 else if (*string
++ != c
)
1757 if (star_fl
) /* Skip to eoln */
1758 while (*string
!= '\0' && *string
++ != '\n')
1761 case NEGATE
| BRACKET
:
1764 while (in_list(expression
, *string
++, c
, opcode
)
1767 else if (in_list(expression
, *string
++, c
, opcode
) == NO_MATCH
)
1769 expression
+= c
- 1; /* Add length of list */
1772 panic("Corrupted program in check_string()");
1775 return star(program
, mark
, string
, expression
);
1777 if (*expression
& DONE
) {
1778 program
->end_ptr
= string
; /* Match ends here */
1780 * We might have found a match. The last thing to do is check
1781 * whether a '$' was given at the end of the expression, or
1782 * the match was found on a null string. (E.g. [a-z]* always
1783 * matches) unless a ^ or $ was included in the pattern.
1785 if ((*expression
& EOLN
) && *string
!= '\n' && *string
!= '\0')
1787 if (string
== program
->start_ptr
&& !(program
->status
& BEGIN_LINE
)
1788 && !(*expression
& EOLN
))
1796 * Star() calls check_string() to find out the longest match possible.
1797 * It searches backwards until the (in check_string()) marked position
1798 * is reached, or a match is found.
1801 star(REGEX
*program
, char *end_position
, char *string
, int *expression
)
1805 if (check_string(program
, string
, expression
))
1807 } while (string
!= end_position
);
1813 * In_list() checks if the given character is in the list of []. If it is
1814 * it returns MATCH. if it isn't it returns NO_MATCH. These returns values
1815 * are reversed when the NEGATE field in the opcode is present.
1818 in_list(int *list
, char c
, int list_length
, int opcode
)
1820 if (c
== '\0' || c
== '\n') /* End of string, never matches */
1822 while (list_length
-- > 1) { /* > 1, don't check acct_field */
1823 if ((*list
& LOW_BYTE
) == c
)
1824 return (opcode
& NEGATE
) ? NO_MATCH
: MATCH
;
1827 return (opcode
& NEGATE
) ? MATCH
: NO_MATCH
;
1831 * Dummy_line() adds an empty line at the end of the file. This is sometimes
1832 * useful in combination with the EF and DN command in combination with the
1838 line_insert(tail
->prev
, "\n", 1);
1839 tail
->prev
->shift_count
= DUMMY
;
1840 if (last_y
!= screenmax
) {
1842 bot_line
= bot_line
->next
;