/*
 * Copyright (c) 1993 by Xerox Corporation.  All rights reserved.
 *
 * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
 * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
 *
 * Permission is hereby granted to copy this code for any purpose,
 * provided the above notices are retained on all copies.
 *
 * Author: Hans-J. Boehm (boehm@parc.xerox.com)
 */
/*
 * A really dumb text editor based on cords.
 * Things it does right:
 * 	No size bounds.
 *	Infinite undo.
 *	Shouldn't crash no matter what file you invoke it on (e.g. /vmunix)
 *		(Make sure /vmunix is not writable before you try this.)
 *	Scrolls horizontally.
 * Things it does wrong:
 *	It doesn't handle tabs reasonably (use "expand" first).
 *	The command set is MUCH too small.
 *	The redisplay algorithm doesn't let curses do the scrolling.
 *	The rule for moving the window over the file is suboptimal.
 */
#include <stdio.h>
#include <curses.h>
#include "../gc.h"
#include "cord.h"

/* List of line number to position mappings, in descending order. */
typedef struct LineMapRep {
    int line;
    size_t pos;
    struct LineMapRep * previous;
} * line_map;

/* List of file versions, one per edit operation */
typedef struct HistoryRep {
    CORD file_contents;
    struct HistoryRep * previous;
    line_map map;	/* Invalid for first record "now" */
} * history;

history now = 0;
CORD current;		/* == now -> file_contents.	*/
size_t current_len;	/* Current file length.		*/
line_map current_map = 0;	/* Current line no. to pos. map	*/

/* Current display position */
int dis_line = 0;
int dis_col = 0;

# define ALL -1
# define NONE - 2
int need_redisplay = 0;	/* Line that needs to be redisplayed.	*/


/* Current cursor position. Always within file. */
int line = 0; 
int col = 0;
size_t file_pos = 0;	/* Character position corresponding to cursor.	*/

/* Invalidate line map for lines > i */
void invalidate_map(int i)
{
    while(current_map -> line > i) current_map = current_map -> previous;
}

/* Add mapping entry */
void add_map(int line, size_t pos)
{
    line_map new_map = GC_NEW(struct LineMapRep);
    
    new_map -> line = line;
    new_map -> pos = pos;
    new_map -> previous = current_map;
    current_map = new_map;
}

/* Return position of column *c of ith line in   */
/* current file. Adjust c to be within the line. */
/* A 0 pointer is taken as 0 column.		 */
/* Returns CORD_NOT_FOUND if i is too big.	 */
/* Assumes i > dis_line.			 */
size_t line_pos(int i, int *c)
{
    int j;
    size_t cur;
    size_t next;
    line_map map = current_map;
    
    while (map -> line > i) map = map -> previous; 
    for (j = map -> line, cur = map -> pos; j < i;) {
	cur = CORD_chr(current, cur, '\n');
        if (cur == current_len-1) return(CORD_NOT_FOUND);
        cur++;
        if (++j > current_map -> line) add_map(j, cur);
    }
    if (c != 0) {
        next = CORD_chr(current, cur, '\n');
        if (next == CORD_NOT_FOUND) next = current_len - 1;
        if (next < cur + *c) {
            *c = next - cur;
        }
        cur += *c;
    }
    return(cur);
}

void add_hist(CORD s)
{
    history new_file = GC_NEW(struct HistoryRep);
    
    new_file -> file_contents = current = s;
    current_len = CORD_len(s);
    new_file -> previous = now;
    if (now != 0) now -> map = current_map;
    now = new_file;
}

void del_hist(void)
{
    now = now -> previous;
    current = now -> file_contents;
    current_map = now -> map;
    current_len = CORD_len(current);
}

/* Current screen_contents; a dynamically allocated array of CORDs	*/
CORD * screen = 0;
int screen_size = 0;

/* Replace a line in the curses stdscr.	All control characters are	*/
/* displayed as upper case characters in standout mode.  This isn't	*/
/* terribly appropriate for tabs.					*/
void replace_line(int i, CORD s)
{
    register int c;
    CORD_pos p;
    
    if (screen == 0 || LINES > screen_size) {
        screen_size = LINES;
    	screen = (CORD *)GC_MALLOC(screen_size * sizeof(CORD));
    }
    if (CORD_cmp(screen[i], s) != 0) {
        move(i,0); clrtoeol();
        CORD_FOR (p, s) {
            c = CORD_pos_fetch(p) & 0x7f;
            if (iscntrl(c)) {
            	standout(); addch(c + 0x40); standend();
            } else {
    	        addch(c);
    	    }
    	}
    	screen[i] = s;
    }
}

/* Return up to COLS characters of the line of s starting at pos,	*/
/* returning only characters after the given column.			*/
CORD retrieve_line(CORD s, size_t pos, unsigned column)
{
    CORD candidate = CORD_substr(s, pos, column + COLS);
    			/* avoids scanning very long lines	*/
    int eol = CORD_chr(candidate, 0, '\n');
    int len;
    
    if (eol == CORD_NOT_FOUND) eol = CORD_len(candidate);
    len = (int)eol - (int)column;
    if (len < 0) len = 0;
    return(CORD_substr(s, pos + column, len));
}

/* Display the visible section of the current file	 */
void redisplay(void)
{
    register int i;
    
    invalidate_map(dis_line + LINES);	/* Prune search */
    for (i = 0; i < LINES; i++) {
        if (need_redisplay == ALL || need_redisplay == i) {
            register size_t pos = line_pos(dis_line + i, 0);
            
            if (pos == CORD_NOT_FOUND) break;
            replace_line(i, retrieve_line(current, pos, dis_col));
            if (need_redisplay == i) goto done;
        }
    }
    for (; i < LINES; i++) replace_line(i, CORD_EMPTY);
done:
    refresh();
    need_redisplay = NONE;
}

/* Update dis_line, dis_col, and dis_pos to make cursor visible.	*/
/* Assumes line, col, dis_line, dis_pos are in bounds.			*/
void normalize_display()
{
    int old_line = dis_line;
    int old_col = dis_col;
    int i;
    
    while (dis_line > line) dis_line -= 10;
    while (dis_col > col) dis_col -= 10;
    while (line >= dis_line + LINES) dis_line += 10;
    while (col >= dis_col + COLS) dis_col += 10;
    if (old_line != dis_line || old_col != dis_col) {
        need_redisplay = ALL;
    }
}

/* Adjust display so that cursor is visible; move cursor into position	*/
/* Update screen if necessary.						*/
void fix_cursor(void)
{
    normalize_display();
    if (need_redisplay != NONE) redisplay();
    move(line - dis_line, col - dis_col);
    refresh();
}

/* Make sure line, col, and dis_pos are somewhere inside file.	*/
/* Recompute file_pos.	Assumes dis_pos is accurate or past eof	*/
void fix_pos()
{
    int my_col = col;
    
    if (line > current_len) line = current_len;
    file_pos = line_pos(line, &my_col);
    if (file_pos == CORD_NOT_FOUND) {
        for (line = current_map -> line, file_pos = current_map -> pos;
             file_pos < current_len;
             line++, file_pos = CORD_chr(current, file_pos, '\n') + 1);
    	line--;
        file_pos = line_pos(line, &col);
    } else {
    	col = my_col;
    }
}

# define UP '\020'	/* ^P */
# define DOWN '\016'	/* ^N */
# define LEFT '\002'	/* ^B */
# define RIGHT '\006'	/* ^F */
# define DEL '\177'	/* ^? */
# define BS '\010'	/* ^H */
# define UNDO '\025'	/* ^U */
# define WRITE '\027'	/* ^W */
# define QUIT '\004'	/* ^D */
# define REPEAT '\022'	/* ^R */

main(argc, argv)
int argc;
char ** argv;
{
    FILE * f, * out;
    int c;
    CORD initial;
#   define NO_PREFIX -1
#   define BARE_PREFIX -2
    int repeat_count = NO_PREFIX;
    int i, file_len;
    int need_fix_pos; 

    
    if (argc != 2) goto usage;
    if ((f = fopen(argv[1], "r")) == NULL) {
     	initial = "\n";
    } else {
        initial = CORD_from_file(f);
        if (initial == CORD_EMPTY
            || CORD_fetch(initial, CORD_len(initial)-1) != '\n') {
            initial = CORD_cat(initial, "\n");
        }
    }
    add_map(0,0);
    add_hist(initial);
    now -> map = current_map;
    now -> previous = now;  /* Can't back up further: beginning of the world */
    GC_enable_incremental();
    setvbuf(stdout, GC_MALLOC_ATOMIC(8192), _IOFBF, 8192);
    initscr();
    noecho(); nonl(); cbreak();
    need_redisplay = ALL;
    fix_cursor();
    
    while ((c = getchar()) != QUIT) {
      if ( c == '\r') c = '\n';
      if ( c == REPEAT ) {
      	repeat_count = BARE_PREFIX; continue;
      } else if (isdigit(c)){
        if (repeat_count == BARE_PREFIX) {
          repeat_count = c - '0'; continue;
        } else if (repeat_count != NO_PREFIX) {
          repeat_count = 10 * repeat_count + c - '0'; continue;
        }
      }
      if (repeat_count == NO_PREFIX) repeat_count = 1;
      if (repeat_count == BARE_PREFIX && (c == UP || c == DOWN)) {
      	repeat_count = LINES/2;
      }
      if (repeat_count == BARE_PREFIX) repeat_count = 8;
      need_fix_pos = 0;
      for (i = 0; i < repeat_count; i++) {
        switch(c) {
     	  case UP:
     	    if (line != 0) {
     	        line--;
     	        need_fix_pos = 1;
     	    }
     	    break;
     	  case DOWN:
     	    line++;
     	    need_fix_pos = 1;
     	    break;
     	  case LEFT:
     	    if (col != 0) {
     	        col--; file_pos--;
     	    }
     	    break;
     	  case RIGHT:
     	    if (CORD_fetch(current, file_pos) == '\n') break;
     	    col++; file_pos++;
     	    break;
     	  case UNDO:
     	    del_hist();
     	    need_redisplay = ALL; need_fix_pos = 1;
     	    break;
     	  case BS:
     	    if (col == 0) break;
     	    col--; file_pos--;
     	    /* fall through: */
     	  case DEL:
     	    if (file_pos == current_len-1) break;
     	    	/* Can't delete trailing newline */
     	    if (CORD_fetch(current, file_pos) == '\n') {
     	        need_redisplay = ALL; need_fix_pos = 1;
     	    } else {
     	        need_redisplay = line - dis_line;
     	    }
     	    add_hist(CORD_cat(
     	    		CORD_substr(current, 0, file_pos),
     	    		CORD_substr(current, file_pos+1, current_len)));
     	    invalidate_map(line);
     	    break;
     	  case WRITE:
    	    if ((out = fopen(argv[1], "w")) == NULL
  	        || CORD_put(current, out) == EOF) {
        	fprintf(stderr, "Write failed\n"); sleep(2);
        	need_redisplay = ALL;
            } else {
                fclose(out);
            }
            break;
     	  default:
     	    {
     	        char * new_char = GC_MALLOC_ATOMIC(2);
     	        CORD left_part = CORD_substr(current, 0, file_pos);
     	        CORD right_part = CORD_substr(current, file_pos, current_len);
     	        
     	        new_char[0] = c; new_char[1] = '\0';
     	        add_hist(CORD_cat(CORD_cat(left_part, new_char), right_part));
     	        invalidate_map(line);
     	        if (c == '\n') {
     	            col = 0; line++; file_pos++;
     	            need_redisplay = ALL;
     	        } else {
     	            col++; file_pos++;
     	            need_redisplay = line - dis_line;
     	    	}
     	        break;
     	    }
        }
      }
      if (need_fix_pos) fix_pos();
      fix_cursor();
      repeat_count = NO_PREFIX;
    }
done:
    endwin();
    exit(0);
usage:
    fprintf(stderr, "Usage: %s file\n", argv[0]);
    fprintf(stderr, "Cursor keys: ^B(left) ^F(right) ^P(up) ^N(down)\n");
    fprintf(stderr, "Undo: ^U    Write: ^W   Quit:^D  Repeat count: ^R[n]\n");
    exit(1);
}
