/*
 * editor 0.2 - a small, single-file terminal text editor.
 * Build: cc -std=c99 -O2 -Wall -Wextra -pedantic editor.c -o editor
 * Run:   ./editor [FILE]
 *
 * Arrow keys, Home, End, Page Up/Down, Backspace, Delete, Enter and Tab
 * edit the text. Esc opens Command>; Enter executes; Esc cancels.
 * Commands: write [FILE], undo, redo, about, manual, help, quit, quit!
 * About/manual are read-only pages; q or Esc returns to editing.
 *
 * Uses libc and Unix terminal interfaces, without curses or terminfo.
 * One file, horizontal scrolling, up to 8 MiB. No configuration file.
 * Existing bytes and line endings are preserved; Enter uses the first
 * newline style in the file. New files use LF. NUL bytes are refused.
 * UTF-8 movement is by code point. Zero-width/nonprinting characters
 * are shown as escapes; complex Unicode shaping is outside this scope.
 * Undo groups consecutive typing; a paste is one change.
 *
 * Writes use a private temporary file beside the destination, then an
 * atomic replacement. Existing permissions and ownership are retained;
 * set-ID bits are cleared. External changes and multiple hard links
 * prevent replacement. Symlinks are resolved when opening a file.
 * "write FILE" will not overwrite an unrelated existing file.
 * Undo history lives in memory and lasts only for this process.
 */
#define _XOPEN_SOURCE 700
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <locale.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
#include <wchar.h>

#define LIMIT ((size_t)8 * 1024 * 1024)
#define COMMAND_SIZE 4096
#define VERSION "0.2"

static const char about_text[] =
    "editor " VERSION "\n"
    "A small, single-file terminal text editor.\n\n"
    "design by remfan1994\n"
    "published by ThatIAm.vip\n\n"
    "One file at a time. Typed commands. Undo and redo.\n"
    "Uses the system C library and Unix terminal interfaces.\n"
    "No curses, terminfo, readline, or external pager dependency.\n"
    "For VT/xterm-compatible terminals; file limit: 8 MiB.\n\n"
    "BLOODGUILT CURSE\n"
    "Cows aren't killers, and beef is the bloodshed of the innocent.  "
    "www.bloodguiltcurse.net has the Bible study\n\n"
    "Use the manual command or editor --manual for instructions.";

static const char manual_text[] =
    "EDITOR MANUAL\n"
    "editor " VERSION " - a small terminal text editor\n\n"
    "STARTING\n"
    "  editor FILE    Open a file, or begin a named new file.\n"
    "  editor         Begin an unnamed empty file.\n"
    "  editor --help  Show command-line usage.\n"
    "  editor --manual / --about / --version\n"
    "                 Print the manual, About page, or version.\n\n"
    "EDITING\n"
    "Type to insert text. Arrow keys move the cursor. Home and End move "
    "to the start and end of the current line. Page Up and Page Down "
    "move through the file. Backspace erases before the cursor; Delete "
    "erases after it. Enter inserts a newline. Tab inserts a literal "
    "tab, displayed at an eight-column tab stop.\n\n"
    "Long lines scroll horizontally. The bar shows line:column and "
    "the filename. A * immediately after the filename means the text "
    "differs from the last saved contents. Long filenames may be clipped.\n\n"
    "COMMANDS\n"
    "Press Esc to open Command>. Type a command and press Enter. Esc "
    "cancels the prompt. Left/Right, Home/End, Backspace, and Delete "
    "edit the command line. Commands are lowercase.\n\n"
    "  write          Save to the current filename.\n"
    "  write FILE     Save to a new filename and use it from then on.\n"
    "  undo           Reverse the previous editing transaction.\n"
    "  redo           Repeat an undone editing transaction.\n"
    "  about          Read the version, credits, and app information.\n"
    "  manual         Read this manual.\n"
    "  help           Show the command list.\n"
    "  quit           Exit if there are no unsaved changes.\n"
    "  quit!          Discard unsaved changes and exit.\n\n"
    "The filename after write is literal, including internal spaces. "
    "Do not add shell quotes; shell variables and ~ are not expanded. "
    "write FILE refuses an unrelated existing destination.\n\n"
    "UNDO AND PASTE\n"
    "Consecutive typing is grouped until movement or another operation. "
    "Each deletion and Enter is a separate transaction. A bracketed "
    "terminal paste is one transaction. Editing after undo discards "
    "the redo branch. Saving does not erase undo history.\n\n"
    "Undo history lasts only for this process. There is no automatic "
    "backup or crash-recovery file. A failed write retains the editing "
    "buffer so another destination can be tried.\n\n"
    "READING ABOUT AND MANUAL\n"
    "These pages are read-only. Up/Down scroll one display row; Page "
    "Up/Down scroll a page; Home/End go to the top/bottom. Text wraps "
    "to the terminal width. Press q or Esc to return to editing. "
    "Typing and pasted text do not change the document.\n\n"
    "FILES AND SAVING\n"
    "Existing bytes, indentation, and line endings are preserved. "
    "Enter uses the first newline style found in the file; new files "
    "use LF. No final newline is added automatically.\n\n"
    "Writes prepare a temporary file beside the destination, then "
    "replace the destination. The file's identity and contents are "
    "checked before replacement. If it changed or was removed, use "
    "write FILE with a new path.\n\n"
    "Permissions and ownership are retained; set-ID bits are cleared. "
    "Extended attributes and ACLs are not copied. Symbolic links are "
    "resolved on opening. Files with multiple hard links require a "
    "new save path. Saving needs access to the destination directory.\n\n"
    "LIMITS AND TERMINAL\n"
    "One regular file, up to 8 MiB; NUL bytes are refused. UTF-8 cursor "
    "movement is by code point. Invalid bytes and zero-width or "
    "nonprinting characters appear as escapes. Complex Unicode "
    "shaping and grapheme-based editing are outside this scope.\n\n"
    "Use a Unix VT/xterm-compatible terminal. Ctrl-C cancels input and "
    "opens Command>. Ctrl-Z suspends; the shell's fg resumes. Handled "
    "termination restores the terminal but does not save unsaved work.\n\n"
    "BUILD\n"
    "cc -std=c99 -O2 -Wall -Wextra -pedantic editor.c -o editor\n\n"
    "No curses, terminfo, readline, or external pager is used.\n"
    "Use about for credits and app information.";

typedef struct { char *s; size_t n, cap; } Buffer;
typedef struct Change Change;
struct Change {
    size_t at, before, after, old_n, new_n;
    char *old_s, *new_s;
    Change *prev, *next;
};
static Buffer text, saved;
static size_t cursor, top, left, goal;
static bool goal_set, group, command_mode, running = true;
static char command[COMMAND_SIZE], message[256];
static size_t command_n, command_cursor;
static char *filename;
static bool existed;
static struct stat original;
static char newline[2] = {'\n', 0};
static size_t newline_n = 1;
static Change *history, *current;
static struct termios initial_termios;
static bool terminal_active;
static int rows = 24, cols = 80;
static char **previous_rows;
static int previous_count;
static volatile sig_atomic_t resized, interrupted, suspended, terminated;
static unsigned char input[4096];
static size_t input_at, input_n;
static int discard_sequence, discard_last;
static const char *viewer_text, *viewer_title;
static size_t viewer_top;

static bool reserve(Buffer *b, size_t n)
{
    size_t cap;
    char *s;
    if (n <= b->cap) return true;
    cap = b->cap ? b->cap : 128;
    while (cap < n) {
        if (cap > SIZE_MAX / 2) { cap = n; break; }
        cap *= 2;
    }
    s = realloc(b->s, cap);
    if (!s) return false;
    b->s = s; b->cap = cap;
    return true;
}

static bool copy_buffer(Buffer *b, const char *s, size_t n)
{
    if (!reserve(b, n + 1)) return false;
    if (n) memcpy(b->s, s, n);
    b->s[n] = 0; b->n = n;
    return true;
}

static void tell(const char *format, ...)
{
    va_list ap;
    va_start(ap, format);
    vsnprintf(message, sizeof message, format, ap);
    va_end(ap);
}

static bool changed(void)
{
    return text.n != saved.n || (text.n && memcmp(text.s, saved.s, text.n));
}

static int write_all(int fd, const char *s, size_t n)
{
    while (n) {
        ssize_t k = write(fd, s, n);
        if (k < 0 && errno == EINTR) continue;
        if (k <= 0) { if (!k) errno = EIO; return -1; }
        s += k; n -= (size_t)k;
    }
    return 0;
}

static void terminal_restore(void)
{
    static const char end[] = "\033[?2004l\033[0m\033[?25h\033[?1049l";
    if (!terminal_active) return;
    (void)write_all(STDOUT_FILENO, end, sizeof end - 1);
    (void)tcsetattr(STDIN_FILENO, TCSANOW, &initial_termios);
    terminal_active = false;
}

static void die(const char *s)
{
    terminal_restore();
    fprintf(stderr, "editor: %s\n", s);
    exit(1);
}

static void add(Buffer *b, const char *s, size_t n)
{
    if (n > SIZE_MAX - b->n - 1 || !reserve(b, b->n + n + 1))
        die("out of memory while drawing the terminal");
    if (n) memcpy(b->s + b->n, s, n);
    b->n += n; b->s[b->n] = 0;
}

static void output(Buffer *b, const char *s) { add(b, s, strlen(s)); }

/* Decode one UTF-8 code point. Invalid bytes remain individual units. */
static size_t decode(const char *s, size_t n, size_t p, uint32_t *cp)
{
    unsigned char c;
    uint32_t u, minimum;
    size_t k, count;
    if (p >= n) { *cp = 0; return 0; }
    c = (unsigned char)s[p];
    if (c < 128) { *cp = c; return 1; }
    if (c >= 0xc2 && c <= 0xdf) { count = 2; u = c & 31; minimum = 0x80; }
    else if (c >= 0xe0 && c <= 0xef) { count = 3; u = c & 15; minimum = 0x800; }
    else if (c >= 0xf0 && c <= 0xf4) { count = 4; u = c & 7; minimum = 0x10000; }
    else { *cp = 0xffffffffu; return 1; }
    if (count > n - p) { *cp = 0xffffffffu; return 1; }
    for (k = 1; k < count; k++) {
        c = (unsigned char)s[p+k];
        if ((c & 0xc0) != 0x80) { *cp = 0xffffffffu; return 1; }
        u = (u << 6) | (c & 63);
    }
    if (u < minimum || u > 0x10ffff || (u >= 0xd800 && u <= 0xdfff)) {
        *cp = 0xffffffffu; return 1;
    }
    *cp = u; return count;
}

static size_t next_pos(const char *s, size_t n, size_t p)
{
    uint32_t cp;
    if (p >= n) return n;
    if (s[p] == '\r' && p + 1 < n && s[p+1] == '\n') return p + 2;
    return p + decode(s, n, p, &cp);
}

static size_t prev_pos(const char *s, size_t n, size_t p)
{
    size_t q, limit;
    uint32_t cp;
    if (!p) return 0;
    if (p >= 2 && s[p-2] == '\r' && s[p-1] == '\n') return p - 2;
    q = p - 1; limit = p > 4 ? p - 4 : 0;
    while (q > limit && ((unsigned char)s[q] & 0xc0) == 0x80) q--;
    if (q + decode(s, n, q, &cp) == p && cp != 0xffffffffu) return q;
    return p - 1;
}

static size_t line_start(size_t p)
{
    while (p && text.s[p-1] != '\n') p--;
    return p;
}

static size_t line_end(size_t p)
{
    while (p < text.n && text.s[p] != '\n') p++;
    if (p < text.n && p && text.s[p-1] == '\r') p--;
    return p;
}

static size_t next_line(size_t p)
{
    while (p < text.n && text.s[p] != '\n') p++;
    return p < text.n ? p + 1 : text.n;
}

/* Convert a unit to printable bytes and its terminal-cell width. */
static size_t representation(const char *s, size_t n, size_t p, size_t column,
                             char out[32], int *width, bool *wide)
{
    uint32_t cp;
    size_t count = decode(s, n, p, &cp);
    int w;
    *wide = false;
    if (cp == '\t') {
        *width = 8 - (int)(column % 8);
        memset(out, ' ', (size_t)*width); out[*width] = 0;
    } else if (cp < 32 || cp == 127) {
        out[0] = '^'; out[1] = cp == 127 ? '?' : (char)(cp + 64);
        out[2] = 0; *width = 2;
    } else if (cp == 0xffffffffu) {
        snprintf(out, 32, "\\x%02X", (unsigned char)s[p]); *width = 4;
    } else if (cp < 128) {
        out[0] = (char)cp; out[1] = 0; *width = 1;
    } else if ((w = wcwidth((wchar_t)cp)) > 0) {
        memcpy(out, s + p, count); out[count] = 0;
        *width = w; *wide = true;
    } else {
        snprintf(out, 32, "\\u{%lX}", (unsigned long)cp);
        *width = (int)strlen(out);
    }
    return count;
}

static size_t column_at(size_t start, size_t p)
{
    size_t column = 0;
    char rep[32]; int width; bool wide;
    while (start < p) {
        start += representation(text.s, p, start, column, rep, &width, &wide);
        column += (size_t)width;
    }
    return column;
}

static size_t position_at(size_t start, size_t column)
{
    size_t end = line_end(start), x = 0, count;
    char rep[32]; int width; bool wide;
    while (start < end) {
        count = representation(text.s, end, start, x, rep, &width, &wide);
        if (x + (size_t)width > column) break;
        x += (size_t)width; start += count;
    }
    return start;
}

static void free_changes(Change *p)
{
    while (p) {
        Change *next = p->next;
        free(p->old_s); free(p->new_s); free(p); p = next;
    }
}

static bool replace_bytes(size_t at, size_t old_n, const char *s, size_t n)
{
    size_t length;
    if (at > text.n || old_n > text.n - at || n > LIMIT - (text.n - old_n))
        return false;
    length = text.n - old_n + n;
    if (!reserve(&text, length + 1)) return false;
    memmove(text.s + at + n, text.s + at + old_n, text.n - at - old_n);
    if (n) memcpy(text.s + at, s, n);
    text.n = length; text.s[length] = 0;
    return true;
}

static bool edit(size_t at, size_t old_n, const char *s, size_t n, bool typing)
{
    Change *p;
    char *joined;
    if (!old_n && !n) return true;
    if (n > LIMIT - (text.n - old_n)) { tell("File limit: 8 MiB."); return false; }
    if (!reserve(&text, text.n - old_n + n + 1)) goto memory_error;
    /* Consecutive insertion is one undo transaction. Navigation ends it. */
    if (typing && group && current && !current->next && !old_n &&
        !current->old_n && at == current->at + current->new_n) {
        joined = realloc(current->new_s, current->new_n + n);
        if (!joined) goto memory_error;
        memcpy(joined + current->new_n, s, n);
        current->new_s = joined; current->new_n += n;
        (void)replace_bytes(at, 0, s, n);
        cursor = at + n; current->after = cursor;
    } else {
        p = calloc(1, sizeof *p);
        if (!p) goto memory_error;
        if (old_n && !(p->old_s = malloc(old_n))) { free(p); goto memory_error; }
        if (n && !(p->new_s = malloc(n))) { free(p->old_s); free(p); goto memory_error; }
        if (old_n) memcpy(p->old_s, text.s + at, old_n);
        if (n) memcpy(p->new_s, s, n);
        p->at = at; p->old_n = old_n; p->new_n = n;
        p->before = cursor; p->after = at + n; p->prev = current;
        if (current) { free_changes(current->next); current->next = p; }
        else { free_changes(history); history = p; }
        current = p;
        (void)replace_bytes(at, old_n, s, n); cursor = p->after;
    }
    group = typing; goal_set = false; message[0] = 0;
    top = line_start(top > text.n ? text.n : top);
    return true;
memory_error:
    tell("Not enough memory. Text unchanged."); return false;
}

static void undo_redo(bool redo)
{
    Change *p = redo ? (current ? current->next : history) : current;
    group = false; goal_set = false;
    if (!p) { tell(redo ? "Nothing to redo." : "Nothing to undo."); return; }
    if (!replace_bytes(p->at, redo ? p->old_n : p->new_n,
                       redo ? p->new_s : p->old_s, redo ? p->new_n : p->old_n)) {
        tell("Not enough memory. Text unchanged."); return;
    }
    cursor = redo ? p->after : p->before;
    current = redo ? p : p->prev;
    top = line_start(top > text.n ? text.n : top);
    tell(redo ? "Redone." : "Undone.");
}

/* Resolve existing links, or the parent of a not-yet-existing file. */
static char *resolve_path(const char *name)
{
    char *path = realpath(name, NULL), *copy, *slash, *parent, *result;
    const char *base;
    size_t n;
    if (path || errno != ENOENT) return path;
    copy = strdup(name);
    if (!copy) return NULL;
    slash = strrchr(copy, '/');
    base = slash ? slash + 1 : copy;
    if (!*base) { free(copy); errno = EINVAL; return NULL; }
    if (slash) {
        *slash = 0;
        parent = realpath(*copy ? copy : "/", NULL);
    } else parent = realpath(".", NULL);
    if (!parent) { free(copy); return NULL; }
    n = strlen(parent) + strlen(base) + 2;
    result = malloc(n);
    if (result) snprintf(result, n, "%s%s%s", parent,
                         !strcmp(parent, "/") ? "" : "/", base);
    free(copy); free(parent); return result;
}

static bool read_file(const char *path, Buffer *b, struct stat *st)
{
    int fd = open(path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW);
    char chunk[8192]; ssize_t n;
    bool ok = false;
    if (fd < 0) return false;
    if (fstat(fd, st) < 0) goto done;
    if (!S_ISREG(st->st_mode)) { errno = EINVAL; goto done; }
    b->n = 0;
    for (;;) {
        n = read(fd, chunk, sizeof chunk);
        if (n < 0 && errno == EINTR) continue;
        if (n < 0) goto done;
        if (!n) break;
        if ((size_t)n > LIMIT - b->n) { errno = EFBIG; goto done; }
        if (!reserve(b, b->n + (size_t)n + 1)) { errno = ENOMEM; goto done; }
        memcpy(b->s + b->n, chunk, (size_t)n); b->n += (size_t)n;
    }
    if (!reserve(b, b->n + 1)) { errno = ENOMEM; goto done; }
    b->s[b->n] = 0; ok = true;
done:
    { int error = errno; if (close(fd) < 0 && ok) return false; errno = error; }
    return ok;
}

static bool unchanged_on_disk(const char *path, struct stat *st)
{
    Buffer b = {0};
    bool ok = read_file(path, &b, st);
    if (!ok || st->st_dev != original.st_dev || st->st_ino != original.st_ino ||
        b.n != saved.n || (b.n && memcmp(b.s, saved.s, b.n))) {
        free(b.s); tell("File changed on disk. Use write FILE for a new path.");
        return false;
    }
    free(b.s); return true;
}

static int sync_fd(int fd)
{
    int r;
    do r = fsync(fd); while (r < 0 && errno == EINTR);
    return r;
}

static void save_file(const char *name)
{
    char *path = NULL, *temporary = NULL, *slash;
    Buffer snapshot = {0};
    struct stat st, check, written;
    bool present, same, committed = false;
    int fd = -1, permission_fd = -1, dir_fd = -1, error;
    mode_t mode, mask;
    if (!name || !*name) {
        if (!filename) { tell("Use write FILE to name this file."); return; }
        name = filename;
    }
    path = resolve_path(name);
    if (!path) goto failure;
    same = filename && !strcmp(filename, path);
    present = lstat(path, &st) == 0;
    if (!present && errno != ENOENT) goto failure;
    if (present) {
        if (!same || !existed) { tell("Destination exists. Choose a new filename."); goto done; }
        if (!unchanged_on_disk(path, &st)) goto done;
        if (st.st_nlink != 1) { tell("File has multiple hard links. Use write FILE for a new path."); goto done; }
        permission_fd = open(path, O_WRONLY | O_NONBLOCK | O_NOFOLLOW);
        if (permission_fd < 0) goto failure;
        if (fstat(permission_fd, &check) < 0) goto failure;
        if (check.st_ino != st.st_ino || check.st_dev != st.st_dev) {
            tell("File changed on disk. Write cancelled."); goto done;
        }
        mode = st.st_mode & 0777;
    } else {
        if (same && existed) { tell("File was removed on disk. Use write FILE for a new path."); goto done; }
        mask = umask(0); umask(mask); mode = 0666 & ~mask;
    }
    if (!copy_buffer(&snapshot, text.s, text.n)) { errno = ENOMEM; goto failure; }
    temporary = malloc(strlen(path) + 32);
    if (!temporary) goto failure;
    strcpy(temporary, path);
    slash = strrchr(temporary, '/');
    strcpy(slash + 1, ".editor.XXXXXX");
    fd = mkstemp(temporary);
    if (fd < 0) goto failure;
    if (fstat(fd, &written) < 0) goto failure;
    if (present && (written.st_uid != st.st_uid || written.st_gid != st.st_gid) &&
        fchown(fd, st.st_uid, st.st_gid) < 0) goto failure;
    if (fchmod(fd, mode) < 0 || write_all(fd, text.s, text.n) < 0 || sync_fd(fd) < 0)
        goto failure;
    if (fstat(fd, &written) < 0) goto failure;
    if (close(fd) < 0) { fd = -1; goto failure; }
    fd = -1;
    if (present) {
        if (!unchanged_on_disk(path, &check)) goto done;
        if (check.st_nlink != 1 || check.st_mode != st.st_mode ||
            check.st_uid != st.st_uid || check.st_gid != st.st_gid) {
            tell("File attributes changed. Write cancelled."); goto done;
        }
        if (rename(temporary, path) < 0) goto failure;
    } else {
        /* link() creates the name without replacing a concurrently created file. */
        if (link(temporary, path) < 0) goto failure;
        (void)unlink(temporary);
    }
    committed = true;
    free(filename); filename = path; path = NULL;
    free(saved.s); saved = snapshot; memset(&snapshot, 0, sizeof snapshot);
    original = written; existed = true;
    *slash = 0;
    dir_fd = open(*temporary ? temporary : "/", O_RDONLY);
    if (dir_fd < 0 || sync_fd(dir_fd) < 0)
        tell("Written; directory synchronization was unavailable.");
    else tell("Written.");
    goto done;
failure:
    error = errno;
    tell("Write failed: %s. Buffer retained.", strerror(error));
done:
    if (fd >= 0) (void)close(fd);
    if (permission_fd >= 0) (void)close(permission_fd);
    if (dir_fd >= 0) (void)close(dir_fd);
    if (temporary && !committed) (void)unlink(temporary);
    free(path); free(temporary); free(snapshot.s);
}

static void reset_screen(void)
{
    int i;
    for (i = 0; i < previous_count; i++) free(previous_rows[i]);
    free(previous_rows); previous_rows = NULL; previous_count = 0;
}

static void terminal_start(void)
{
    struct termios raw = initial_termios;
    static const char begin[] = "\033[?1049h\033[?2004h\033[2J";
    raw.c_iflag &= (tcflag_t)~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
    raw.c_oflag &= (tcflag_t)~OPOST;
    raw.c_cflag = (raw.c_cflag & (tcflag_t)~CSIZE) | CS8;
    raw.c_lflag &= (tcflag_t)~(ECHO | ICANON | IEXTEN);
    raw.c_lflag |= ISIG;
    raw.c_cc[VMIN] = 0; raw.c_cc[VTIME] = 0;
    if (tcsetattr(STDIN_FILENO, TCSANOW, &raw) < 0) die(strerror(errno));
    terminal_active = true;
    if (write_all(STDOUT_FILENO, begin, sizeof begin - 1) < 0) die(strerror(errno));
    reset_screen(); resized = 1;
}

static void signal_handler(int sig)
{
    if (sig == SIGWINCH) resized = 1;
    else if (sig == SIGINT) interrupted = 1;
    else if (sig == SIGTSTP) suspended = 1;
    else if (sig == SIGCONT) resized = 1;
    else terminated = sig;
}

static void install_handler(int sig, void (*handler)(int))
{
    struct sigaction action;
    memset(&action, 0, sizeof action);
    action.sa_handler = handler; sigemptyset(&action.sa_mask);
    if (sigaction(sig, &action, NULL) < 0) die(strerror(errno));
}

static void dimensions(void)
{
    struct winsize ws;
    if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0) {
        rows = ws.ws_row ? ws.ws_row : 24;
        cols = ws.ws_col ? ws.ws_col : 80;
    }
    if (rows > 1000) rows = 1000;
    if (cols > 4096) cols = 4096;
    reset_screen(); resized = 0;
}

static void visible(Buffer *b, const char *s, size_t n, size_t from, size_t width)
{
    size_t p = 0, x = 0, count, a, z, k;
    int cells; bool wide; char rep[32];
    b->n = 0;
    if (b->s) b->s[0] = 0;
    while (p < n && x < from + width) {
        count = representation(s, n, p, x, rep, &cells, &wide);
        a = x > from ? x : from;
        z = x + (size_t)cells < from + width ? x + (size_t)cells : from + width;
        if (z > a) {
            if (wide && a == x && z == x + (size_t)cells) output(b, rep);
            else if (wide) { for (k = a; k < z; k++) output(b, " "); }
            else add(b, rep + (a - x), z - a);
        }
        x += (size_t)cells; p += count;
    }
}

static void draw_row(Buffer *out, int row, Buffer *line, bool reverse)
{
    Buffer row_text = {0};
    char address[48];
    output(&row_text, reverse ? "\033[7m" : "\033[0m");
    if (line->n) add(&row_text, line->s, line->n);
    output(&row_text, "\033[0m\033[K");
    if (!previous_rows[row] || strcmp(previous_rows[row], row_text.s)) {
        snprintf(address, sizeof address, "\033[%d;1H", row + 1);
        output(out, address); add(out, row_text.s, row_text.n);
        free(previous_rows[row]); previous_rows[row] = row_text.s;
    } else free(row_text.s);
}

/* The built-in pages are ASCII. Wrap them without changing the editor buffer. */
static size_t viewer_row(size_t start, size_t width, size_t *end)
{
    size_t p = start, split;
    while (viewer_text[p] && viewer_text[p] != '\n' && p - start < width) p++;
    if (viewer_text[p] && viewer_text[p] != '\n') {
        split = p;
        while (split > start && viewer_text[split - 1] != ' ') split--;
        if (split > start) p = split;
    }
    *end = p;
    return viewer_text[p] == '\n' ? p + 1 : p;
}

static size_t viewer_rows(size_t width)
{
    size_t p = 0, end, count = 0;
    while (viewer_text[p]) { p = viewer_row(p, width, &end); count++; }
    return count ? count : 1;
}

static void draw_viewer(Buffer *out, Buffer *line)
{
    size_t p = 0, end, next, row = 0, width = (size_t)(cols - 1);
    size_t total = viewer_rows(width), body = (size_t)(rows - 2);
    size_t maximum = total > body ? total - body : 0;
    int screen_row = 1;
    char heading[96], footer[160];
    if (viewer_top > maximum) viewer_top = maximum;
    snprintf(heading, sizeof heading, "%s | editor " VERSION, viewer_title);
    visible(line, heading, strlen(heading), 0, width);
    draw_row(out, 0, line, true);
    while (viewer_text[p] && screen_row < rows - 1) {
        next = viewer_row(p, width, &end);
        if (row++ >= viewer_top) {
            visible(line, viewer_text + p, end - p, 0, width);
            draw_row(out, screen_row++, line, false);
        }
        p = next;
    }
    while (screen_row < rows - 1) {
        line->n = 0; draw_row(out, screen_row++, line, false);
    }
    snprintf(footer, sizeof footer,
             "q/Esc: back | %zu/%zu | Up/Down PgUp/PgDn Home/End",
             viewer_top + 1, total);
    visible(line, footer, strlen(footer), 0, width);
    draw_row(out, rows - 1, line, true);
}

static void draw(void)
{
    Buffer out = {0}, line = {0}, status = {0};
    size_t start, p, end, col, line_number = 1, command_column = 0;
    size_t width, name_width;
    int r, cursor_row = 0, body = rows > 2 ? rows - 2 : 1;
    bool dirty;
    const char *name;
    char info[160], address[64];
    if (resized) dimensions();
    body = rows > 2 ? rows - 2 : 1;
    if (!previous_rows) {
        previous_rows = calloc((size_t)rows, sizeof *previous_rows);
        if (!previous_rows) die("out of memory");
        previous_count = rows;
    }
    output(&out, "\033[?25l");
    if (rows < 3 || cols < 12) {
        visible(&line, "Window too small", 16, 0, (size_t)(cols > 1 ? cols - 1 : 0));
        draw_row(&out, 0, &line, false);
        output(&out, "\033[1;1H\033[?25h");
        goto finish;
    }
    if (viewer_text) { draw_viewer(&out, &line); goto finish; }
    start = line_start(cursor);
    if (top > start) top = start;
    p = top;
    for (r = 0; r < body && p < start; r++) p = next_line(p);
    if (r >= body) {
        top = start;
        for (r = 1; r < body && top; r++) top = line_start(top - 1);
    }
    col = column_at(start, cursor);
    if (col < left) left = col;
    if (col >= left + (size_t)(cols - 1)) left = col - (size_t)(cols - 2);
    p = top;
    for (r = 0; r < body; r++) {
        if (p == start) cursor_row = r;
        end = line_end(p);
        visible(&line, text.s ? text.s + p : "", end - p, left, (size_t)(cols - 1));
        draw_row(&out, r, &line, false);
        if (end < text.n) p = next_line(p);
        else {
            r++;
            for (; r < body; r++) { line.n = 0; draw_row(&out, r, &line, false); }
            break;
        }
    }
    for (p = 0; p < cursor; p++) if (text.s[p] == '\n') line_number++;
    dirty = changed(); width = (size_t)(cols - 1);
    name = filename ? strrchr(filename, '/') + 1 : "[new file]";
    snprintf(info, sizeof info, "%zu:%zu | ", line_number, col + 1);
    visible(&status, info, strlen(info), 0, width - 2);
    name_width = width - status.n - (dirty ? 1u : 0u);
    visible(&line, name, strlen(name), 0, name_width);
    add(&status, line.s, line.n);
    if (dirty) output(&status, "*");
    visible(&line, status.s, status.n, 0, (size_t)(cols - 1));
    draw_row(&out, body, &line, true);
    status.n = 0;
    if (command_mode) {
        output(&status, "Command> "); add(&status, command, command_n);
        p = 0;
        while (p < command_cursor) {
            int w; bool wide; char rep[32];
            p += representation(command, command_cursor, p, command_column + 9, rep, &w, &wide);
            command_column += (size_t)w;
        }
        command_column += 9;
        p = command_column >= (size_t)(cols - 1) ? command_column - (size_t)(cols - 2) : 0;
        visible(&line, status.s, status.n, p, (size_t)(cols - 1));
        draw_row(&out, body + 1, &line, false);
        cursor_row = body + 1; col = command_column - p;
    } else {
        visible(&line, message, strlen(message), 0, (size_t)(cols - 1));
        draw_row(&out, body + 1, &line, false); col -= left;
    }
    snprintf(address, sizeof address, "\033[%d;%zuH\033[?25h", cursor_row + 1, col + 1);
    output(&out, address);
finish:
    if (write_all(STDOUT_FILENO, out.s, out.n) < 0) terminated = SIGTERM;
    free(out.s); free(line.s); free(status.s);
}

enum { KEY_NONE = 256, KEY_ESCAPE, KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN,
       KEY_HOME, KEY_END, KEY_PAGEUP, KEY_PAGEDOWN, KEY_DELETE, KEY_PASTE,
       KEY_TOP, KEY_BOTTOM, KEY_EOF };

static int byte(int timeout)
{
    struct pollfd fd;
    ssize_t n; int r;
    if (terminated || suspended || interrupted) return -2;
    if (input_at < input_n) return input[input_at++];
    fd.fd = STDIN_FILENO; fd.events = POLLIN; fd.revents = 0;
    r = poll(&fd, 1, timeout);
    if (r < 0) return errno == EINTR ? -2 : -1;
    if (!r) return -2;
    n = read(STDIN_FILENO, input, sizeof input);
    if (n < 0) return errno == EINTR || errno == EAGAIN ? -2 : -1;
    if (!n) return -1;
    input_n = (size_t)n; input_at = 1; return input[0];
}

static int64_t milliseconds(void)
{
    struct timespec ts;
    if (clock_gettime(CLOCK_MONOTONIC, &ts) < 0) return 0;
    return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}

static int sequence_byte(int64_t deadline)
{
    int64_t remaining = deadline - milliseconds();
    if (remaining <= 0) return -2;
    return byte(remaining < 80 ? (int)remaining : 80);
}

static int key(void)
{
    int c = byte(250), first, last = 0, k;
    char sequence[64]; size_t n = 0;
    int64_t deadline;
    if (c == -1) return KEY_EOF;
    if (c < 0) return KEY_NONE;
    if (discard_sequence) {
        if (discard_sequence == 1) {
            if (c >= 0x40 && c <= 0x7e) discard_sequence = 0;
            if (c == 27) { discard_sequence = 0; return KEY_ESCAPE; }
        } else {
            if (c == 7 || (discard_last == 27 && c == '\\')) discard_sequence = 0;
            discard_last = c;
        }
        return KEY_NONE;
    }
    if (c != 27) return c;
    first = byte(80);
    if (first < 0) return KEY_ESCAPE;
    deadline = milliseconds() + 250;
    if (first == ']' || first == 'P' || first == '^' || first == '_') {
        for (k = 0; k < 4096; k++) {
            c = sequence_byte(deadline);
            if (c < 0) { discard_sequence = 2; discard_last = last; return KEY_NONE; }
            if (c == 7 || (last == 27 && c == '\\')) return KEY_NONE;
            last = c;
        }
        discard_sequence = 2; discard_last = last;
        return KEY_NONE;
    }
    if (first != '[' && first != 'O') {
        /* There are no Alt commands: quick Esc + text means Command>. */
        input_at--;
        return KEY_ESCAPE;
    }
    for (k = 0; k < 256; k++) {
        c = sequence_byte(deadline);
        if (c < 0) { discard_sequence = 1; return KEY_NONE; }
        if (n < sizeof sequence - 1) sequence[n++] = (char)c;
        if (c >= 0x40 && c <= 0x7e) {
            if (c == '[' && n == 1) continue; /* Linux console function keys. */
            break;
        }
    }
    sequence[n] = 0;
    if (k == 256) { discard_sequence = 1; return KEY_NONE; }
    if (n == sizeof sequence - 1 || sequence[0] == '[') return KEY_NONE;
    if (c == 'A') return KEY_UP;
    if (c == 'B') return KEY_DOWN;
    if (c == 'C') return KEY_RIGHT;
    if (c == 'D') return KEY_LEFT;
    if (c == 'H') return !strcmp(sequence, "1;5H") ? KEY_TOP : KEY_HOME;
    if (c == 'F') return !strcmp(sequence, "1;5F") ? KEY_BOTTOM : KEY_END;
    if (!strcmp(sequence, "1~") || !strcmp(sequence, "7~")) return KEY_HOME;
    if (!strcmp(sequence, "4~") || !strcmp(sequence, "8~")) return KEY_END;
    if (!strcmp(sequence, "3~")) return KEY_DELETE;
    if (!strcmp(sequence, "5~")) return KEY_PAGEUP;
    if (!strcmp(sequence, "6~")) return KEY_PAGEDOWN;
    if (!strcmp(sequence, "200~")) return KEY_PASTE;
    return KEY_NONE;
}

static void open_viewer(const char *title, const char *contents)
{
    viewer_title = title; viewer_text = contents; viewer_top = 0;
    message[0] = 0;
}

static void viewer_key(int c)
{
    size_t width = (size_t)(cols > 1 ? cols - 1 : 1);
    size_t page = (size_t)(rows > 2 ? rows - 2 : 1);
    size_t total = viewer_rows(width), maximum = total > page ? total - page : 0;
    if (viewer_top > maximum) viewer_top = maximum;
    if (c == KEY_ESCAPE || c == 'q') viewer_text = viewer_title = NULL;
    else if (c == KEY_UP && viewer_top) viewer_top--;
    else if (c == KEY_DOWN && viewer_top < maximum) viewer_top++;
    else if (c == KEY_PAGEUP) viewer_top = viewer_top > page ? viewer_top - page : 0;
    else if (c == KEY_PAGEDOWN)
        viewer_top = page > maximum - viewer_top ? maximum : viewer_top + page;
    else if (c == KEY_HOME || c == KEY_TOP) viewer_top = 0;
    else if (c == KEY_END || c == KEY_BOTTOM) viewer_top = maximum;
}

static void paste(void)
{
    static const char end[] = "\033[201~";
    Buffer b = {0}; bool rejected = false, ignored = viewer_text != NULL;
    size_t matched = 0; int c, idle = 0;
    group = false;
    for (;;) {
        c = byte(250);
        if (terminated || suspended || interrupted || c == -1) break;
        if (c < 0) {
            if (++idle >= 20) { tell("Paste timed out; text unchanged."); break; }
            if (resized) draw();
            continue;
        }
        idle = 0;
        if (c == end[matched]) {
            matched++;
            if (matched == sizeof end - 1) {
                if (ignored) { free(b.s); return; }
                if (rejected) tell("Paste refused: NUL byte, memory, or size limit.");
                else if (command_mode) {
                    if (b.n && (memchr(b.s, '\n', b.n) || memchr(b.s, '\r', b.n) || memchr(b.s, 27, b.n)))
                        tell("Paste one command line at a time.");
                    else if (b.n < COMMAND_SIZE - command_n) {
                        memmove(command + command_cursor + b.n, command + command_cursor,
                                command_n - command_cursor + 1);
                        if (b.n) memcpy(command + command_cursor, b.s, b.n);
                        command_cursor += b.n; command_n += b.n;
                    }
                } else (void)edit(cursor, 0, b.s, b.n, false);
                free(b.s); return;
            }
            continue;
        }
        if (matched && !rejected && !ignored) {
            if (b.n + matched > LIMIT || !reserve(&b, b.n + matched + 1)) rejected = true;
            else { memcpy(b.s + b.n, end, matched); b.n += matched; }
        }
        matched = 0;
        if (c == 27) { matched = 1; continue; }
        if (!c && !ignored) rejected = true;
        if (!rejected && !ignored) {
            if (b.n >= LIMIT || !reserve(&b, b.n + 2)) rejected = true;
            else { b.s[b.n++] = (char)c; b.s[b.n] = 0; }
        }
    }
    free(b.s);
}

static void execute(void)
{
    char *verb = command, *arg;
    while (*verb == ' ') verb++;
    arg = verb;
    while (*arg && *arg != ' ' && *arg != '\t') arg++;
    if (*arg) { *arg++ = 0; while (*arg == ' ' || *arg == '\t') arg++; }
    command_mode = false; group = false;
    if (!strcmp(verb, "write")) save_file(arg);
    else if (*arg) tell("This command takes no argument.");
    else if (!strcmp(verb, "undo")) undo_redo(false);
    else if (!strcmp(verb, "redo")) undo_redo(true);
    else if (!strcmp(verb, "about")) open_viewer("About", about_text);
    else if (!strcmp(verb, "manual")) open_viewer("Manual", manual_text);
    else if (!strcmp(verb, "quit!")) running = false;
    else if (!strcmp(verb, "quit")) {
        if (changed()) tell("Unsaved changes. Use write, or quit! to discard.");
        else running = false;
    } else if (!strcmp(verb, "help")) tell("write [FILE] | undo | redo | about | manual | help | quit | quit!");
    else if (*verb) tell("Unknown command. Type help.");
}

static void command_key(int c)
{
    size_t p;
    if (c == KEY_ESCAPE) { command_mode = false; return; }
    if (c == '\r' || c == '\n') { execute(); return; }
    if (c == KEY_LEFT) command_cursor = prev_pos(command, command_n, command_cursor);
    else if (c == KEY_RIGHT) command_cursor = next_pos(command, command_n, command_cursor);
    else if (c == KEY_HOME) command_cursor = 0;
    else if (c == KEY_END) command_cursor = command_n;
    else if ((c == 127 || c == 8) && command_cursor) {
        p = prev_pos(command, command_n, command_cursor);
        memmove(command + p, command + command_cursor, command_n - command_cursor + 1);
        command_n -= command_cursor - p; command_cursor = p;
    } else if (c == KEY_DELETE && command_cursor < command_n) {
        p = next_pos(command, command_n, command_cursor);
        memmove(command + command_cursor, command + p, command_n - p + 1);
        command_n -= p - command_cursor;
    } else if (c >= 32 && c < 256 && c != 127 && command_n < COMMAND_SIZE - 1) {
        memmove(command + command_cursor + 1, command + command_cursor,
                command_n - command_cursor + 1);
        command[command_cursor++] = (char)c; command_n++;
    }
}

static void vertical(int direction, int count)
{
    size_t start = line_start(cursor), p;
    if (!goal_set) { goal = column_at(start, cursor); goal_set = true; }
    while (count--) {
        if (direction < 0) {
            if (!start) break;
            start = line_start(start - 1);
        } else {
            p = next_line(start);
            if (p == start || (p == text.n && (!text.n || text.s[text.n-1] != '\n'))) break;
            start = p;
        }
    }
    cursor = position_at(start, goal);
}

static void text_key(int c)
{
    size_t p;
    char ch;
    if (c == KEY_ESCAPE) {
        command_mode = true; command_n = command_cursor = 0; command[0] = 0;
        group = false; message[0] = 0; return;
    }
    if (c == KEY_UP || c == KEY_DOWN || c == KEY_PAGEUP || c == KEY_PAGEDOWN) {
        group = false;
        vertical(c == KEY_UP || c == KEY_PAGEUP ? -1 : 1,
                 c == KEY_UP || c == KEY_DOWN ? 1 : (rows > 3 ? rows - 3 : 1));
        return;
    }
    goal_set = false;
    if (c == KEY_LEFT) cursor = prev_pos(text.s, text.n, cursor);
    else if (c == KEY_RIGHT) cursor = next_pos(text.s, text.n, cursor);
    else if (c == KEY_HOME) cursor = line_start(cursor);
    else if (c == KEY_END) cursor = line_end(cursor);
    else if (c == KEY_TOP) cursor = 0;
    else if (c == KEY_BOTTOM) cursor = text.n;
    else if (c == 127 || c == 8) {
        if (cursor) { p = prev_pos(text.s, text.n, cursor); (void)edit(p, cursor - p, NULL, 0, false); }
    } else if (c == KEY_DELETE) {
        if (cursor < text.n) (void)edit(cursor, next_pos(text.s, text.n, cursor) - cursor, NULL, 0, false);
    } else if (c == '\r' || c == '\n') {
        (void)edit(cursor, 0, newline, newline_n, false);
    } else if (c == '\t' || (c >= 32 && c < 256 && c != 127)) {
        ch = (char)c; (void)edit(cursor, 0, &ch, 1, true); return;
    }
    group = false;
}

static void usage(void)
{
    puts("editor " VERSION " - one-file terminal text editor\n"
         "Usage: editor [FILE]\n"
         "       editor --help | --manual | --about | --version\n\n"
         "Arrows, Home/End, Page Up/Down: move. Type to insert.\n"
         "Backspace/Delete: erase. Enter: new line. Tab: literal tab.\n"
         "Esc: Command>. Enter runs the command; Esc cancels.\n\n"
         "write [FILE]   Save; an optional filename is taken literally.\n"
         "undo / redo    Reverse or repeat an editing transaction.\n"
         "about          Read version, credits, and app information.\n"
         "manual         Read the built-in manual.\n"
         "help           Show commands.\n"
         "quit           Leave if saved.\n"
         "quit!          Discard unsaved changes and leave.\n\n"
         "8 MiB limit. Long lines scroll horizontally. UTF-8 code-point\n"
         "movement; zero-width/nonprinting text is shown as escapes.\n"
         "No automatic reformatting or final newline. Undo is in memory.\n"
         "Symlinks are resolved on open; hard-linked files need a new\n"
         "save path. Existing unrelated destinations are not overwritten.\n"
         "Unix VT/xterm-compatible terminal required; no curses libraries.\n"
         "About/manual: arrows and paging keys scroll; q or Esc returns.\n\n"
         "Build: cc -std=c99 -O2 -Wall -Wextra -pedantic editor.c -o editor");
}

int main(int argc, char **argv)
{
    int c, status = 0;
    size_t p;
    bool dirty_screen = true;
    if (argc == 2 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h"))) { usage(); return 0; }
    if (argc == 2 && !strcmp(argv[1], "--version")) { puts("editor " VERSION); return 0; }
    if (argc == 2 && !strcmp(argv[1], "--about")) { puts(about_text); return 0; }
    if (argc == 2 && !strcmp(argv[1], "--manual")) { puts(manual_text); return 0; }
    if (argc > 2) { fputs("Usage: editor [FILE]\n", stderr); return 2; }
    (void)setlocale(LC_CTYPE, "");
    if (!isatty(STDIN_FILENO) || !isatty(STDOUT_FILENO)) die("run this editor in a terminal");
    if (getenv("TERM") && !strcmp(getenv("TERM"), "dumb")) die("a VT/xterm-compatible terminal is required");
    if (argc == 2) {
        filename = resolve_path(argv[1]);
        if (!filename) die(strerror(errno));
        if (lstat(filename, &original) == 0) {
            if (!read_file(filename, &text, &original)) die(strerror(errno));
            existed = true;
        } else if (errno != ENOENT) die(strerror(errno));
    }
    if (text.n && memchr(text.s, 0, text.n)) die("NUL byte in file; this editor edits text");
    if (!copy_buffer(&saved, text.s, text.n) || !reserve(&text, text.n + 1)) die("out of memory");
    text.s[text.n] = 0;
    for (p = 0; p < text.n; p++) if (text.s[p] == '\n') {
        if (p && text.s[p-1] == '\r') { newline[0] = '\r'; newline[1] = '\n'; newline_n = 2; }
        break;
    }
    if (tcgetattr(STDIN_FILENO, &initial_termios) < 0) die(strerror(errno));
    if (atexit(terminal_restore) != 0) die("cannot register terminal cleanup");
    install_handler(SIGWINCH, signal_handler); install_handler(SIGINT, signal_handler);
    install_handler(SIGTSTP, signal_handler); install_handler(SIGCONT, signal_handler);
    install_handler(SIGTERM, signal_handler); install_handler(SIGHUP, signal_handler);
    install_handler(SIGQUIT, signal_handler);
    install_handler(SIGPIPE, SIG_IGN);
    terminal_start(); tell("editor " VERSION " | help | manual | about");
    while (running && !terminated) {
        if (suspended) {
            terminal_restore(); suspended = 0;
            install_handler(SIGTSTP, SIG_DFL); (void)raise(SIGTSTP);
            install_handler(SIGTSTP, signal_handler); terminal_start(); dirty_screen = true;
        }
        if (interrupted) {
            interrupted = 0; input_at = input_n;
            discard_sequence = 0;
            viewer_text = viewer_title = NULL;
            command_mode = true; command_n = command_cursor = 0; command[0] = 0;
            group = false; tell("Use write, quit, or quit!."); dirty_screen = true;
        }
        if (resized || (dirty_screen && input_at == input_n)) { draw(); dirty_screen = false; }
        c = key();
        if (c == KEY_EOF) { status = 1; break; }
        if (c == KEY_NONE) continue;
        if (c == KEY_PASTE) paste();
        else if (viewer_text) viewer_key(c);
        else if (command_mode) command_key(c);
        else text_key(c);
        dirty_screen = true;
    }
    if (terminated) status = 128 + terminated;
    terminal_restore(); reset_screen();
    free_changes(history); free(text.s); free(saved.s); free(filename);
    return status;
}
