/* Vio-Pad - a small word processor for Violyx.
   Documents with bold, italic, underlined and struck out letters in nine sizes, two typefaces and
   eight colours, paragraphs left, centred, right or justified, on pages as they would be printed.
   The page is drawn in pixel cells with smooth letters (DejaVu Sans and Serif, see
   viopad-font.h). Documents are saved as .vpd; text files open too, and a document can be
   exported as text or as a web page (HTML) for other computers.

   Copyright (c) 2026, Merecete. BSD-3-Clause licence, see the Info window or LICENSE. The letters
   come from the DejaVu fonts, Bitstream Vera and Arev licences, see LICENSE-FONTS. */
#include "violyx.h"
#include "viopad-font.h"

typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;

/* ---------------------------------------------------------------- small helpers */
static int slen(const char *s) {
    int n = 0;
    while (s[n])
        n++;
    return n;
}
static void scpy(char *d, const char *s, int n) {
    int i = 0;
    for (; s[i] && i < n - 1; i++)
        d[i] = s[i];
    d[i] = 0;
}
static void scat(char *d, const char *s, int n) {
    int l = slen(d);
    scpy(d + l, s, n - l);
}
static void snum(char *d, long v, int n) {
    char t[24];
    int i = 0, neg = v < 0;
    unsigned long u = neg ? (unsigned long)-v : (unsigned long)v;
    do {
        t[i++] = (char)('0' + u % 10);
        u /= 10;
    } while (u);
    if (neg)
        t[i++] = '-';
    int k = slen(d);
    while (i && k < n - 1)
        d[k++] = t[--i];
    d[k] = 0;
}
static int lower(int c) {
    if (c >= 'A' && c <= 'Z')
        return c + 32;
    if (c == 0x8E) /* the umlauts of CP437 */
        return 0x84;
    if (c == 0x99)
        return 0x94;
    if (c == 0x9A)
        return 0x81;
    return c;
}
static int ends_with(const char *s, const char *e) {
    int a = slen(s), b = slen(e);
    if (a < b)
        return 0;
    for (int i = 0; i < b; i++)
        if (lower((u8)s[a - b + i]) != lower((u8)e[i]))
            return 0;
    return 1;
}
static const char *base_name(const char *p) {
    const char *b = p;
    for (; *p; p++)
        if (*p == '/')
            b = p + 1;
    return b;
}
static int lang_en;
#define T(de, en) (lang_en ? (en) : (de))
#ifndef HOME_DIR
#define HOME_DIR "/home/"
#endif

/* ---------------------------------------------------------------- inflate (RFC 1951) */
typedef struct {
    u16 cnt[16], sym[288];
} huff_t;
static const u8 *zi;
static long zn, zp;
static u32 zbits, zcnt;
static int zbit(void) {
    if (!zcnt) {
        zbits = zp < zn ? zi[zp++] : 0;
        zcnt = 8;
    }
    int b = (int)(zbits & 1);
    zbits >>= 1;
    zcnt--;
    return b;
}
static int zget(int n) {
    int v = 0;
    for (int i = 0; i < n; i++)
        v |= zbit() << i;
    return v;
}
static void zbuild(huff_t *h, const u8 *len, int n) {
    u16 offs[16];
    for (int i = 0; i < 16; i++)
        h->cnt[i] = 0;
    for (int i = 0; i < n; i++)
        h->cnt[len[i]]++;
    h->cnt[0] = 0;
    offs[1] = 0;
    for (int i = 1; i < 15; i++)
        offs[i + 1] = (u16)(offs[i] + h->cnt[i]);
    for (int i = 0; i < n; i++)
        if (len[i])
            h->sym[offs[len[i]]++] = (u16)i;
}
static int zdecode(const huff_t *h) {
    int code = 0, first = 0, index = 0;
    for (int len = 1; len < 16; len++) {
        code |= zbit();
        int count = h->cnt[len];
        if (code - count < first)
            return h->sym[index + (code - first)];
        index += count;
        first += count;
        first <<= 1;
        code <<= 1;
    }
    return -1;
}
static const u16 lbase[29] = {3,  4,  5,  6,  7,  8,  9,  10, 11,  13,  15,  17,  19,  23, 27,
                              31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
static const u8 lext[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
static const u16 dbase[30] = {1,   2,   3,   4,   5,   7,    9,    13,   17,   25,   33,   49,   65,    97,    129,
                              193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
static const u8 dext[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
/* a zlib stream into out; returns the bytes written or -1 */
static long inflate_z(const u8 *in, long n, u8 *out, long cap) {
    static huff_t hl, hd;
    zi = in;
    zn = n;
    zp = 2; /* the zlib header */
    zcnt = 0;
    long o = 0;
    int last;
    do {
        last = zbit();
        int type = zget(2);
        if (type == 0) {
            zcnt = 0;
            if (zp + 4 > zn)
                return -1;
            int len = zi[zp] | zi[zp + 1] << 8;
            zp += 4;
            if (zp + len > zn || o + len > cap)
                return -1;
            for (int i = 0; i < len; i++)
                out[o++] = zi[zp++];
            continue;
        }
        if (type == 3)
            return -1;
        u8 lens[320];
        if (type == 1) {
            int i = 0;
            for (; i < 144; i++)
                lens[i] = 8;
            for (; i < 256; i++)
                lens[i] = 9;
            for (; i < 280; i++)
                lens[i] = 7;
            for (; i < 288; i++)
                lens[i] = 8;
            zbuild(&hl, lens, 288);
            for (i = 0; i < 30; i++)
                lens[i] = 5;
            zbuild(&hd, lens, 30);
        } else {
            static const u8 ord[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
            int nl = zget(5) + 257, nd = zget(5) + 1, nc = zget(4) + 4;
            u8 cl[19];
            for (int i = 0; i < 19; i++)
                cl[i] = 0;
            for (int i = 0; i < nc; i++)
                cl[ord[i]] = (u8)zget(3);
            huff_t hc;
            zbuild(&hc, cl, 19);
            int i = 0;
            while (i < nl + nd) {
                int s = zdecode(&hc);
                if (s < 0)
                    return -1;
                if (s < 16)
                    lens[i++] = (u8)s;
                else {
                    int rep, v = 0;
                    if (s == 16) {
                        if (!i)
                            return -1;
                        v = lens[i - 1];
                        rep = 3 + zget(2);
                    } else if (s == 17)
                        rep = 3 + zget(3);
                    else
                        rep = 11 + zget(7);
                    if (i + rep > nl + nd)
                        return -1;
                    while (rep--)
                        lens[i++] = (u8)v;
                }
            }
            zbuild(&hl, lens, nl);
            zbuild(&hd, lens + nl, nd);
        }
        for (;;) {
            int s = zdecode(&hl);
            if (s < 0)
                return -1;
            if (s < 256) {
                if (o >= cap)
                    return -1;
                out[o++] = (u8)s;
            } else if (s == 256)
                break;
            else {
                s -= 257;
                if (s >= 29)
                    return -1;
                int len = lbase[s] + zget(lext[s]), d = zdecode(&hd);
                if (d < 0 || d >= 30)
                    return -1;
                int dist = dbase[d] + zget(dext[d]);
                if (dist > o || o + len > cap)
                    return -1;
                for (int k = 0; k < len; k++, o++)
                    out[o] = out[o - dist];
            }
        }
    } while (!last);
    return o;
}

/* ---------------------------------------------------------------- the letters */
#define NSIZE 9
#define NFACE 8 /* Sans, Sans bold, Sans italic, Sans bold italic, then the same in Serif */
typedef struct {
    u8 adv;
    signed char x0, y0; /* left and top of the picture from the pen on the base line */
    u8 w, h;
    u32 off;
} glyph_t;
typedef struct {
    int asc, desc;
    glyph_t g[256];
} face_t;
static face_t faces[NFACE * NSIZE];
static const u8 *fpx; /* coverage 0-3 of all pictures */
static int sizes[NSIZE];
static int font_ok;
static void load_fonts(void) {
    u8 *raw = vx_alloc(FONT_RAW + 16);
    if (!raw || inflate_z(font_z, (long)sizeof font_z, raw, FONT_RAW + 16) != FONT_RAW)
        return;
    if (raw[0] != 'V' || raw[1] != 'P' || raw[2] != 'F' || raw[3] != '1' || raw[4] != NSIZE || raw[5] != NFACE)
        return;
    const u8 *p = raw + 6;
    for (int i = 0; i < NSIZE; i++)
        sizes[i] = *p++;
    for (int f = 0; f < NFACE * NSIZE; f++) {
        faces[f].asc = *p++;
        faces[f].desc = *p++;
        for (int c = 0; c < 256; c++, p += 9) {
            glyph_t *g = &faces[f].g[c];
            g->adv = p[0];
            g->x0 = (signed char)p[1];
            g->y0 = (signed char)p[2];
            g->w = p[3];
            g->h = p[4];
            g->off = (u32)p[5] | (u32)p[6] << 8 | (u32)p[7] << 16 | (u32)p[8] << 24;
        }
    }
    fpx = raw + FONT_TAB;
    font_ok = 1;
}

/* ---------------------------------------------------------------- the document */
/* a style: size 0-8, bold, italic, underlined, struck out, colour 0-7, serif; for the end of a
   paragraph also how it is aligned */
#define S_SIZE   0x000F
#define S_BOLD   0x0010
#define S_ITAL   0x0020
#define S_UNDER  0x0040
#define S_STRIKE 0x0080
#define S_COLSH  8
#define S_COL    0x0700
#define S_SERIF  0x0800
#define S_ALSH   12
#define S_ALIGN  0x3000 /* 0 left, 1 centre, 2 right, 3 justified */
#define S_SYS    0x4000 /* the Violyx system font */
#define S_CHAR   (S_SIZE | S_BOLD | S_ITAL | S_UNDER | S_STRIKE | S_COL | S_SERIF | S_SYS)
#define S_DEFAULT (S_SYS | 1) /* System, 10, black, left */
typedef struct {
    u8 c, pad;
    u16 s;
} ch_t;
#define DOC_CAP (1024 * 1024)
static ch_t *doc, *clip;
static int len, cur, anc = -1, clip_n; /* the text always ends with an end of paragraph */
static u16 tstyle = S_DEFAULT;          /* the style typed letters get */
static int dirty, changed, saved_once;
static char path[256];

static const struct {
    const char *de, *en;
    u32 rgb;
} colours[8] = {{"Schwarz", "Black", 0x000000}, {"Grau", "Grey", 0x6E6E6E},   {"Rot", "Red", 0xC81E1E},
                {"Orange", "Orange", 0xE07000}, {"Gr\x81n", "Green", 0x1E8C32}, {"Blau", "Blue", 0x1E50C8},
                {"Violett", "Violet", 0x7A2DC8}, {"Pink", "Pink", 0xD21E8C}};

static int face_of(u16 s) {
    return ((s & S_SERIF) ? 4 : 0) + ((s & S_BOLD) ? 1 : 0) + ((s & S_ITAL) ? 2 : 0);
}
static const face_t *ff(u16 s) {
    int z = s & S_SIZE;
    if (z >= NSIZE)
        z = NSIZE - 1;
    return &faces[face_of(s) * NSIZE + z];
}
/* the system font comes in three sizes: one text cell (8-14 pt), 2 x 2 cells (16-24), 4 x 4 (32-40) */
static int sys_m(u16 s) {
    int z = s & S_SIZE;
    return z <= 3 ? 1 : z <= 6 ? 2 : 4;
}
static const glyph_t *glyph(const face_t *f, u8 c) {
    const glyph_t *g = &f->g[c];
    if (!g->adv && c != ' ')
        g = &f->g['?'];
    return g;
}
#define TABW 48
static int char_w(int i, int x) { /* the width of letter i, when it starts at x on the line */
    u8 c = doc[i].c;
    if (c == '\n')
        return 0;
    if (c == '\t')
        return (x / TABW + 1) * TABW - x;
    if (doc[i].s & S_SYS) /* on the grid of the text cells: 4 dots each */
        return (4 - (x & 3)) % 4 + 4 * sys_m(doc[i].s);
    return glyph(ff(doc[i].s), c)->adv;
}
static int asc_of(u16 s) {
    return (s & S_SYS) ? 6 * sys_m(s) : ff(s)->asc;
}
static int desc_of(u16 s) {
    return (s & S_SYS) ? 2 * sys_m(s) : ff(s)->desc;
}
static int para_end(int i) {
    while (i < len - 1 && doc[i].c != '\n')
        i++;
    return i;
}
static int para_start(int i) {
    while (i > 0 && doc[i - 1].c != '\n')
        i--;
    return i;
}

/* undo: copies of the whole text in a ring of memory, newest last */
#define UNDO_MEM (24 * 1024 * 1024)
#define NUNDO    120
typedef struct {
    long off, n;
    int len, cur, anc;
} snap_t;
static u8 *umem;
static snap_t us[NUNDO + 1];
static int un, up; /* entries, position */
static int typing; /* letters typed one after the other share one undo step */
static void undo_drop_front(void) {
    for (int i = 1; i < un; i++)
        us[i - 1] = us[i];
    un--;
    up--;
}
static int undo_put(int at) { /* the current text as entry 'at' */
    long n = (long)len * (long)sizeof(ch_t), o = 0;
    if (!umem || n > UNDO_MEM)
        return 0;
    if (at > 0) {
        o = us[at - 1].off + us[at - 1].n;
        if (o + n > UNDO_MEM)
            o = 0;
    }
    for (;;) { /* older entries that lie where this one goes are forgotten */
        int hit = -1;
        for (int i = 0; i < at; i++)
            if (us[i].off < o + n && o < us[i].off + us[i].n)
                hit = i;
        if (hit < 0)
            break;
        for (int k = 0; k <= hit; k++) {
            undo_drop_front();
            at--;
        }
    }
    memcpy(umem + o, doc, (size_t)n);
    us[at].off = o;
    us[at].n = n;
    us[at].len = len;
    us[at].cur = cur;
    us[at].anc = anc;
    return at + 1;
}
static void snap(void) { /* before a change */
    if (up >= NUNDO)
        undo_drop_front();
    if (up < 0)
        up = 0;
    int k = undo_put(up);
    up = un = k;
}
static void restore(int i) {
    memcpy(doc, umem + us[i].off, (size_t)us[i].n);
    len = us[i].len;
    cur = us[i].cur;
    anc = us[i].anc;
    if (cur >= len)
        cur = len - 1;
    if (anc >= len)
        anc = -1;
}
static void pick_style(void);
static void undo(void) {
    if (up <= 0)
        return;
    if (up == un) { /* keep the newest state too, for redo */
        if (un >= NUNDO + 1)
            return;
        int k = undo_put(un);
        if (!k)
            return;
        un = k;
        up = k - 1;
        if (up <= 0)
            return;
    }
    up--;
    restore(up);
    typing = 0;
    dirty = changed = 1;
    pick_style();
}
static void redo(void) {
    if (up + 1 >= un)
        return;
    up++;
    restore(up);
    typing = 0;
    dirty = changed = 1;
    pick_style();
}
static void undo_clear(void) {
    un = up = 0;
    typing = 0;
}

static void doc_new(void) {
    len = 1;
    doc[0].c = '\n';
    doc[0].s = S_DEFAULT;
    cur = 0;
    anc = -1;
    tstyle = S_DEFAULT;
    undo_clear();
}
static int ins(int at, const ch_t *src, int n) {
    if (n <= 0 || len + n > DOC_CAP)
        return 0;
    memmove(doc + at + n, doc + at, (size_t)(len - at) * sizeof(ch_t));
    memcpy(doc + at, src, (size_t)n * sizeof(ch_t));
    len += n;
    changed = dirty = 1;
    return n;
}
static void del(int a, int b) { /* removes [a, b), never the last end of paragraph */
    if (b > len - 1)
        b = len - 1;
    if (a >= b)
        return;
    /* a joined paragraph keeps how the first of them was aligned */
    int lastnl = -1;
    for (int i = a; i < b; i++)
        if (doc[i].c == '\n')
            lastnl = i;
    if (lastnl >= 0) {
        int e = para_end(b);
        u16 al = doc[para_end(a)].s & S_ALIGN;
        doc[e].s = (u16)((doc[e].s & ~S_ALIGN) | al);
    }
    memmove(doc + a, doc + b, (size_t)(len - b) * sizeof(ch_t));
    len -= b - a;
    changed = dirty = 1;
}
static int has_sel(void) {
    return anc >= 0 && anc != cur;
}
static int sel_a(void) {
    return anc < cur ? anc : cur;
}
static int sel_b(void) {
    return anc < cur ? cur : anc;
}
static void del_sel(void) {
    if (!has_sel())
        return;
    int a = sel_a(), b = sel_b();
    del(a, b);
    cur = a;
    anc = -1;
}
static void pick_style(void) { /* typing goes on in the style of the letter before */
    if (cur > 0 && doc[cur - 1].c != '\n')
        tstyle = doc[cur - 1].s & S_CHAR;
    else
        tstyle = doc[cur].s & S_CHAR;
}

/* ---------------------------------------------------------------- pages and lines */
#define CW    256 /* width of the text on the page, in dots of the picture (64 text cells) */
#define ML    16  /* margin left and right */
#define PWID  (CW + 2 * ML)
#define PCH   360 /* height of the text on a page; all of these on the grid of the cells */
#define MT    16  /* margin above and below */
#define PBH   (PCH + 2 * MT)
#define GAP   16  /* between the pages */
#define TOP0  8
typedef struct {
    int a, e, ne;   /* letters [a, e); up to ne without the spaces at the end */
    int sys;        /* letters of the system font in it: on the grid of the cells */
    int y, h, base; /* top, height and base line on the long strip of all pages */
    int x0, page;
    float sp;       /* justified: extra width of each space */
} line_t;
#define MAXL 200000
static line_t *ln;
static int nl, npages, words;
static void layout(void) {
    nl = 0;
    int page = 0, yin = 0, i = 0;
    words = 0;
    for (int k = 0, inw = 0; k < len; k++) {
        u8 c = doc[k].c;
        int w = c > ' ';
        if (w && !inw)
            words++;
        inw = w;
    }
    while (i < len && nl < MAXL) {
        int b = para_end(i), al = (doc[b].s & S_ALIGN) >> S_ALSH, a = i;
        do {
            int x = 0, j = a, brk = -1, e;
            for (;;) {
                u8 c = doc[j].c;
                if (c == '\n' || j >= b) {
                    e = j + 1;
                    break;
                }
                int w = char_w(j, x);
                if (c == ' ') { /* spaces may hang over the edge */
                    x += w;
                    brk = j;
                    j++;
                    continue;
                }
                if (x + w > CW && j > a) {
                    e = brk >= 0 ? brk + 1 : j;
                    break;
                }
                x += w;
                if (c == '\t')
                    brk = j;
                j++;
            }
            /* how high: the largest letters of the line */
            int ma = 0, md = 0, mz = 0, ne = e, nsp = 0, sys = 0, other = 0;
            while (ne > a && (doc[ne - 1].c == ' ' || doc[ne - 1].c == '\n'))
                ne--;
            for (int k = a; k < e; k++) {
                if (doc[k].c == '\n' && e - a > 1)
                    continue;
                u16 st = doc[k].s;
                if (asc_of(st) > ma)
                    ma = asc_of(st);
                if (desc_of(st) > md)
                    md = desc_of(st);
                if (st & S_SYS)
                    sys = 1;
                else
                    other = 1;
                int z = sizes[st & S_SIZE];
                if (z > mz)
                    mz = z;
            }
            int w = 0;
            for (int k = a; k < ne; k++) {
                w += char_w(k, w);
                if (doc[k].c == ' ')
                    nsp++;
            }
            line_t *L = &ln[nl++];
            L->a = a;
            L->e = e;
            L->ne = ne;
            L->sp = 0;
            L->x0 = (al == 1 ? (CW - w) / 2 : al == 2 ? CW - w : 0) & ~3; /* on the grid of the cells */
            if (L->x0 < 0)
                L->x0 = 0;
            L->sys = sys;
            if (al == 3 && e <= b && nsp && w < CW)
                L->sp = (float)(CW - w) / (float)nsp;
            int lead = other ? mz / 5 + 1 : 0, lh = ma + md + lead;
            if (sys) { /* lines with the system font stand on the rows of the cells */
                lh = (lh + 7) & ~7;
                yin = (yin + 7) & ~7;
            }
            if (yin + lh > PCH && yin > 0) {
                page++;
                yin = 0;
            }
            L->page = page;
            L->y = TOP0 + page * (PBH + GAP) + MT + yin;
            L->h = lh;
            L->base = sys ? L->y + lh - md : L->y + lead / 2 + ma;
            yin += lh;
            a = e;
        } while (a <= b && nl < MAXL);
        i = b + 1;
    }
    npages = page + 1;
}
static int line_of(int pos) {
    int lo = 0, hi = nl - 1;
    while (lo < hi) {
        int m = (lo + hi + 1) / 2;
        if (ln[m].a <= pos)
            lo = m;
        else
            hi = m - 1;
    }
    return lo;
}
static float x_of(int k, int pos) { /* where letter pos starts on line k */
    line_t *L = &ln[k];
    float x = (float)L->x0;
    int raw = 0;
    for (int i = L->a; i < pos && i < L->e; i++) {
        int w = char_w(i, raw);
        raw += w;
        x += (float)w;
        if (L->sp > 0 && doc[i].c == ' ' && i < L->ne)
            x += L->sp;
    }
    return x;
}
static int pos_at(int k, float gx) { /* the letter nearest to x on line k */
    line_t *L = &ln[k];
    float x = (float)L->x0;
    int raw = 0, last = L->e - 1;
    for (int i = L->a; i < last; i++) {
        float w = (float)char_w(i, raw);
        if (L->sp > 0 && doc[i].c == ' ' && i < L->ne)
            w += L->sp;
        if (gx < x + w / 2)
            return i;
        raw += char_w(i, raw);
        x += w;
    }
    return last;
}

/* ---------------------------------------------------------------- the picture */
#define IMW 960
#define IMH 800
static u8 img[IMW * IMH];
static int AW, AH, W, H; /* picture of the page area; window in cells */
static int vy, hx;       /* scrolled down, and to the side when the window is narrow */
static u8 lut[8][2][8];  /* colour, on paper or selected, coverage */
static u8 c_desk, c_shadow, c_paper, c_sel, c_caret, c_pnum, c_edge, c_mark;
static u8 col_ix[8]; /* the colours of the letters */
static int caret_on = 1;
/* the nearest of the 240 fixed colours (16-255): the 16 colours of Violyx below are tinted */
static u8 rgb_ix(int r, int g, int b) {
    static const int L[6] = {0, 95, 135, 175, 215, 255};
    int best = 16, bd = 1 << 30;
    for (int i = 16; i < 256; i++) {
        int cr, cg, cb;
        if (i < 232) {
            cr = L[(i - 16) / 36];
            cg = L[(i - 16) / 6 % 6];
            cb = L[(i - 16) % 6];
        } else
            cr = cg = cb = 8 + 10 * (i - 232);
        int d = (cr - r) * (cr - r) * 3 + (cg - g) * (cg - g) * 4 + (cb - b) * (cb - b) * 2;
        if (d < bd) {
            bd = d;
            best = i;
        }
    }
    return (u8)best;
}
#define vx_rgb rgb_ix
static void init_colours(void) {
    c_desk = vx_rgb(30, 20, 52);
    c_shadow = vx_rgb(12, 8, 22);
    c_paper = vx_rgb(255, 255, 255);
    c_sel = vx_rgb(205, 190, 255);
    c_caret = vx_rgb(20, 0, 60);
    c_pnum = vx_rgb(150, 150, 150);
    c_edge = vx_rgb(215, 205, 235);
    c_mark = vx_rgb(235, 230, 255);
    for (int c = 0; c < 8; c++)
        col_ix[c] = vx_rgb((int)(colours[c].rgb >> 16 & 255), (int)(colours[c].rgb >> 8 & 255), (int)(colours[c].rgb & 255));
    for (int c = 0; c < 8; c++)
        for (int b = 0; b < 2; b++)
            for (int l = 0; l < 8; l++) {
                u32 fg = colours[c].rgb, bg = b ? 0xCDBEFF : 0xFFFFFF;
                int r = ((int)(bg >> 16 & 255) * (7 - l) + (int)(fg >> 16 & 255) * l) / 7,
                    g = ((int)(bg >> 8 & 255) * (7 - l) + (int)(fg >> 8 & 255) * l) / 7,
                    bl = ((int)(bg & 255) * (7 - l) + (int)(fg & 255) * l) / 7;
                lut[c][b][l] = vx_rgb(r, g, bl);
            }
}
static void rect(int x, int y, int w, int h, u8 c) {
    int x1 = x + w, y1 = y + h;
    if (x < 0)
        x = 0;
    if (y < 0)
        y = 0;
    if (x1 > AW)
        x1 = AW;
    if (y1 > AH)
        y1 = AH;
    for (int j = y; j < y1; j++)
        for (int i = x; i < x1; i++)
            img[j * AW + i] = c;
}
static void put_glyph(int x, int yb, const glyph_t *g, const u8 *lt) {
    int x0 = x + g->x0, y0 = yb + g->y0;
    const u8 *p = fpx + g->off;
    for (int j = 0; j < g->h; j++, p += g->w) {
        int yy = y0 + j;
        if (yy < 0 || yy >= AH)
            continue;
        u8 *row = img + yy * AW;
        for (int i = 0; i < g->w; i++) {
            int xx = x0 + i;
            if (p[i] && xx >= 0 && xx < AW)
                row[xx] = lt[p[i]];
        }
    }
}
static int str_px(const char *s, u16 st) {
    int w = 0;
    for (; *s; s++)
        w += glyph(ff(st), (u8)*s)->adv;
    return w;
}
static void draw_str(const char *s, int x, int yb, u16 st, const u8 *lt) {
    for (; *s; s++) {
        const glyph_t *g = glyph(ff(st), (u8)*s);
        put_glyph(x, yb, g, lt);
        x += g->adv;
    }
}
static int paper_x(void) { /* on the grid of the cells, so the system font fits its cells */
    return AW >= PWID + 8 ? ((AW - PWID) / 2) & ~3 : 4 - hx;
}
/* letters of the system font in one text cell: drawn by Violyx itself, sharp */
typedef struct {
    short x, y;
    u8 c, fg, bg;
} tcell_t;
#define MAXTC 24000
static tcell_t tcells[MAXTC];
static int ntc;
static void tcell(int x, int y, u8 c, u8 fg, u8 bg) { /* x, y in dots of the picture */
    if (x < 0 || y < 0 || x + 4 > AW || y + 8 > AH || (x & 3) || (y & 7) || ntc >= MAXTC)
        return;
    tcell_t *t = &tcells[ntc++];
    t->x = (short)(x / 4);
    t->y = (short)(y / 8);
    t->c = c;
    t->fg = fg;
    t->bg = bg;
}
/* a letter of the system font drawn bigger into the picture: m = 2 or 4 cells */
static void put_sys(int x, int top, u8 c, u16 st, const u8 *lt) {
    int k = sys_m(st) / 2, bold = (st & S_BOLD) != 0;
    const u8 *g = sysfont + c * 16;
    for (int r = 0; r < 16; r++) {
        int sh = (st & S_ITAL) ? (15 - r) * k / 5 : 0;
        for (int b = 0; b < 8; b++) {
            if (!(g[r] >> (7 - b) & 1))
                continue;
            for (int dy = 0; dy < k; dy++)
                for (int dx = 0; dx < k + bold; dx++) {
                    int xx = x + b * k + dx + sh, yy = top + r * k + dy;
                    if (xx >= 0 && xx < AW && yy >= 0 && yy < AH)
                        img[yy * AW + xx] = lt[7];
                }
        }
    }
}
static void draw_page(void) {
    ntc = 0;
    for (int i = 0; i < AW * AH; i++)
        img[i] = c_desk;
    int px0 = paper_x();
    for (int k = 0; k < npages; k++) {
        int py = TOP0 + k * (PBH + GAP) - vy;
        if (py > AH || py + PBH < 0)
            continue;
        rect(px0 + 3, py + 3, PWID, PBH, c_shadow);
        rect(px0, py, PWID, PBH, c_paper);
        /* the corners of the text area, as word processors show them */
        int cx[2] = {px0 + ML - 2, px0 + ML + CW + 1}, cy[2] = {py + MT - 2, py + MT + PCH + 1};
        for (int a = 0; a < 2; a++)
            for (int b = 0; b < 2; b++) {
                rect(cx[a] - (a ? 0 : 6), cy[b], 7, 1, c_edge);
                rect(cx[a], cy[b] - (b ? 0 : 6), 1, 7, c_edge);
            }
        char t[12] = "";
        snum(t, k + 1, 12);
        u8 pl[8] = {0, lut[1][0][1], lut[1][0][2], lut[1][0][3], lut[1][0][4], lut[1][0][5], lut[1][0][6], c_pnum};
        draw_str(t, px0 + PWID / 2 - str_px(t, 0) / 2, py + PBH - 5, 0, pl);
    }
    /* the lines that show */
    int lo = 0, hi = nl - 1;
    while (lo < hi) {
        int m = (lo + hi) / 2;
        if (ln[m].y + ln[m].h < vy)
            lo = m + 1;
        else
            hi = m;
    }
    int sa = has_sel() ? sel_a() : -1, sb = has_sel() ? sel_b() : -1;
    for (int k = lo; k < nl && ln[k].y - vy < AH; k++) {
        line_t *L = &ln[k];
        int top = L->y - vy, yb = L->base - vy, raw = 0;
        float x = (float)(px0 + ML + L->x0);
        for (int i = L->a; i < L->e; i++) {
            u8 c = doc[i].c;
            u16 s = doc[i].s;
            int w = char_w(i, raw);
            raw += w;
            float fw = (float)w;
            if (L->sp > 0 && c == ' ' && i < L->ne)
                fw += L->sp;
            int sel = i >= sa && i < sb;
            if (sel)
                rect((int)x, top, c == '\n' ? 5 : (int)(x + fw) - (int)x, L->h, c_sel);
            const u8 *lt = lut[(s & S_COL) >> S_COLSH][sel];
            if (s & S_SYS) {
                int m = sys_m(s), gx = ((int)x + w - 4 * m) & ~3, gt = L->y + L->h - 8 * m - vy;
                if (m == 1) { /* one text cell; what Violyx cannot draw in it is marked */
                    if (c > ' ' && c != '\n')
                        tcell(gx, gt, c, col_ix[(s & S_COL) >> S_COLSH],
                              sel ? c_sel : (s & (S_BOLD | S_ITAL | S_UNDER | S_STRIKE)) ? c_mark : c_paper);
                } else if (c > ' ')
                    put_sys(gx, gt, c, s, lt);
                if (m > 1 && (s & (S_UNDER | S_STRIKE)) && c != '\n' && i < L->ne) {
                    if (s & S_UNDER)
                        rect((int)x, gt + 14 * m / 2, (int)(x + fw) - (int)x, m / 2, lt[7]);
                    if (s & S_STRIKE)
                        rect((int)x, gt + 9 * m / 2, (int)(x + fw) - (int)x, m / 2, lt[7]);
                }
                x += fw;
                continue;
            }
            if (c > ' ')
                put_glyph((int)x, yb, glyph(ff(s), c), lt);
            if ((s & (S_UNDER | S_STRIKE)) && c != '\n' && i < L->ne) {
                int z = sizes[s & S_SIZE], t = z >= 24 ? 2 : 1;
                if (s & S_UNDER)
                    rect((int)x, yb + 1 + z / 10, (int)(x + fw) - (int)x, t, lt[7]);
                if (s & S_STRIKE)
                    rect((int)x, yb - ff(s)->asc * 3 / 10 - (t > 1), (int)(x + fw) - (int)x, t, lt[7]);
            }
            x += fw;
        }
    }
    /* the caret */
    if (caret_on && !has_sel()) {
        int k = line_of(cur);
        line_t *L = &ln[k];
        int x = px0 + ML + (int)x_of(k, cur), yb = L->base - vy, z = sizes[tstyle & S_SIZE];
        if ((tstyle & S_SYS) && sys_m(tstyle) == 1) { /* a block on the cell, like in Write */
            int gx = (doc[cur].s & S_SYS) ? (x + 3) & ~3 : x & ~3, gt = L->y + L->h - 8 - vy;
            int found = 0;
            for (int i = 0; i < ntc; i++)
                if (tcells[i].x == gx / 4 && tcells[i].y == gt / 8) {
                    tcells[i].fg = c_paper;
                    tcells[i].bg = c_caret;
                    found = 1;
                }
            if (!found)
                tcell(gx, gt, ' ', c_paper, c_caret);
        } else if (tstyle & S_SYS) {
            int m = sys_m(tstyle);
            rect(x, L->y + L->h - 8 * m - vy, m / 2 + 1, 8 * m, c_caret);
        } else {
            const face_t *f = ff(tstyle);
            rect(x, yb - f->asc + 1, z >= 24 ? 2 : 1, f->asc + f->desc - 1, c_caret);
        }
    }
}

/* ---------------------------------------------------------------- formatting */
enum { OP_BOLD, OP_ITAL, OP_UNDER, OP_STRIKE, OP_BIGGER, OP_SMALLER, OP_SIZE, OP_COLOUR, OP_FACE, OP_PLAIN };
static u16 st_op(u16 s, int op, int arg, int set) {
    u16 al = s & S_ALIGN;
    s &= S_CHAR;
    int z = s & S_SIZE;
    switch (op) {
        case OP_BOLD:
            s = set ? (u16)(s | S_BOLD) : (u16)(s & ~S_BOLD);
            break;
        case OP_ITAL:
            s = set ? (u16)(s | S_ITAL) : (u16)(s & ~S_ITAL);
            break;
        case OP_UNDER:
            s = set ? (u16)(s | S_UNDER) : (u16)(s & ~S_UNDER);
            break;
        case OP_STRIKE:
            s = set ? (u16)(s | S_STRIKE) : (u16)(s & ~S_STRIKE);
            break;
        case OP_FACE: /* 0 System, 1 Sans, 2 Serif */
            s = (u16)((s & ~(S_SERIF | S_SYS)) | (arg == 0 ? S_SYS : arg == 2 ? S_SERIF : 0));
            break;
        case OP_BIGGER: /* the system font has three sizes: 10, 20 and 40 */
            if (s & S_SYS)
                z = z <= 3 ? 5 : 8;
            else if (z < NSIZE - 1)
                z++;
            s = (u16)((s & ~S_SIZE) | z);
            break;
        case OP_SMALLER:
            if (s & S_SYS)
                z = z >= 7 ? 5 : 1;
            else if (z > 0)
                z--;
            s = (u16)((s & ~S_SIZE) | z);
            break;
        case OP_SIZE:
            s = (u16)((s & ~S_SIZE) | arg);
            break;
        case OP_COLOUR:
            s = (u16)((s & ~S_COL) | arg << S_COLSH);
            break;
        case OP_PLAIN: /* the typeface and size stay */
            s = (u16)(s & (S_SERIF | S_SYS | S_SIZE));
            break;
    }
    return (u16)(s | al);
}
static u16 op_flag(int op) {
    return op == OP_BOLD ? S_BOLD : op == OP_ITAL ? S_ITAL : op == OP_UNDER ? S_UNDER : op == OP_STRIKE ? S_STRIKE : 0;
}
static void format(int op, int arg) {
    u16 fl = op_flag(op);
    if (has_sel()) {
        snap();
        typing = 0;
        int a = sel_a(), b = sel_b(), all = 1;
        if (fl)
            for (int i = a; i < b; i++)
                if (doc[i].c != '\n' && !(doc[i].s & fl))
                    all = 0;
        for (int i = a; i < b; i++)
            doc[i].s = st_op(doc[i].s, op, arg, !all);
        changed = dirty = 1;
        int keep = anc;
        pick_style();
        anc = keep;
        return;
    }
    tstyle = st_op(tstyle, op, arg, fl ? !(tstyle & fl) : 1) & S_CHAR;
    if (doc[cur].c == '\n' && (cur == 0 || doc[cur - 1].c == '\n')) { /* an empty paragraph shows it at once */
        doc[cur].s = (u16)((doc[cur].s & S_ALIGN) | tstyle);
        changed = dirty = 1;
    }
}
static void align(int al) {
    int a = has_sel() ? sel_a() : cur, b = has_sel() ? sel_b() - 1 : cur;
    if (b < a)
        b = a;
    snap();
    typing = 0;
    for (int i = para_end(a);; i = para_end(i + 1)) {
        doc[i].s = (u16)((doc[i].s & ~S_ALIGN) | al << S_ALSH);
        if (i >= b || i >= len - 1)
            break;
    }
    changed = dirty = 1;
}

/* ---------------------------------------------------------------- moving and editing */
static float goal = -1; /* where up and down aim to */
static void ensure_visible(void) {
    int k = line_of(cur);
    line_t *L = &ln[k];
    if (L->y < vy + 4) { /* up: at the top of a page the page shows from its edge */
        int first = k == 0 || ln[k - 1].page != L->page;
        vy = first ? TOP0 + L->page * (PBH + GAP) - 6 : L->y - 4;
    }
    if (L->y + L->h > vy + AH - 4)
        vy = L->y + L->h - AH + 4;
    int bottom = TOP0 + npages * (PBH + GAP);
    if (vy > bottom - AH / 2)
        vy = bottom - AH / 2;
    if (vy < 0)
        vy = 0;
    /* on the rows of the cells, so the system font stays in its cells */
    if (vy & 7)
        vy = L->y + L->h > vy + AH - 4 ? (vy + 7) & ~7 : vy & ~7;
    if (AW < PWID + 8) { /* narrow window: the page moves to the side, by whole cells */
        int cx = 4 - hx + ML + (int)x_of(k, cur);
        if (cx < 10)
            hx -= 10 - cx;
        if (cx > AW - 10)
            hx += cx - (AW - 10);
        if (hx < 0)
            hx = 0;
        if (hx > PWID + 8 - AW)
            hx = PWID + 8 - AW;
        hx &= ~3;
    } else
        hx = 0;
}
static void move_to(int p, int shift) {
    if (p < 0)
        p = 0;
    if (p > len - 1)
        p = len - 1;
    if (shift) {
        if (anc < 0)
            anc = cur;
    } else
        anc = -1;
    cur = p;
    typing = 0;
    pick_style();
}
static int is_word(u8 c) {
    return c > ' ' && c != '.' && c != ',' && c != ';' && c != ':' && c != '!' && c != '?' && c != '(' && c != ')' && c != '"';
}
static int word_left(int p) {
    while (p > 0 && !is_word(doc[p - 1].c))
        p--;
    while (p > 0 && is_word(doc[p - 1].c))
        p--;
    return p;
}
static int word_right(int p) {
    while (p < len - 1 && is_word(doc[p].c))
        p++;
    while (p < len - 1 && !is_word(doc[p].c))
        p++;
    return p;
}
static void vertical(int lines, int shift) {
    int k = line_of(cur);
    if (goal < 0)
        goal = x_of(k, cur);
    float g = goal;
    k += lines;
    if (k < 0) {
        move_to(0, shift);
        goal = g;
        return;
    }
    if (k >= nl) {
        move_to(len - 1, shift);
        goal = g;
        return;
    }
    move_to(pos_at(k, g), shift);
    goal = g;
}
static void page_move(int dir, int shift) {
    int k = line_of(cur), y = ln[k].y + dir * (AH - 24), n = 0;
    if (dir > 0)
        while (k + n + 1 < nl && ln[k + n + 1].y <= y)
            n++;
    else
        while (k + n - 1 >= 0 && ln[k + n - 1].y >= y)
            n--;
    if (!n)
        n = dir;
    vertical(n, shift);
    vy += dir * (AH - 24);
    if (vy < 0)
        vy = 0;
}
static void type_char(u8 c) {
    if (!typing || has_sel())
        snap();
    del_sel();
    ch_t ch = {c, 0, tstyle};
    if (c == '\n')
        ch.s = (u16)(tstyle | (doc[para_end(cur)].s & S_ALIGN));
    if (ins(cur, &ch, 1))
        cur++;
    anc = -1;
    typing = c != '\n' && c != ' ';
}
static int last_del; /* backspaces one after the other share one undo step */
static void backspace(int word) {
    if (has_sel()) {
        snap();
        del_sel();
    } else if (cur > 0) {
        if (last_del != 1)
            snap();
        int a = word ? word_left(cur) : cur - 1;
        del(a, cur);
        cur = a;
    }
    typing = 0;
    last_del = 1;
    pick_style();
}
static void delete_fwd(int word) {
    if (has_sel()) {
        snap();
        del_sel();
    } else if (cur < len - 1) {
        if (last_del != 2)
            snap();
        del(cur, word ? word_right(cur) : cur + 1);
    }
    typing = 0;
    last_del = 2;
    pick_style();
}
static void save_clip(void) {
    static u8 b[16];
    b[0] = 'V';
    b[1] = 'P';
    b[2] = 'C';
    b[3] = '1';
    if (vx_write("clip", b, 4) >= 0)
        vx_append("clip", clip, (size_t)clip_n * sizeof(ch_t));
}
static void copy_sel(void) {
    if (!has_sel())
        return;
    clip_n = sel_b() - sel_a();
    memcpy(clip, doc + sel_a(), (size_t)clip_n * sizeof(ch_t));
    save_clip();
}
static void paste(void) {
    if (!clip_n)
        return;
    snap();
    typing = 0;
    del_sel();
    if (ins(cur, clip, clip_n))
        cur += clip_n;
    pick_style();
}
static char find_s[64];
static int find_next(void) {
    int n = slen(find_s);
    if (!n)
        return 0;
    int start = has_sel() ? sel_a() + 1 : cur;
    for (int k = 0; k < len; k++) {
        int p = (start + k) % len, i = 0;
        while (i < n && p + i < len && lower(doc[p + i].c) == lower((u8)find_s[i]))
            i++;
        if (i == n) {
            anc = p;
            cur = p + n;
            typing = 0;
            return 1;
        }
    }
    return 0;
}

/* ---------------------------------------------------------------- files */
static u8 *iob; /* for reading and writing */
#define IOB (4 * 1024 * 1024)
static long iob_n;
static char out_path[256];
static int out_first, out_err;
static void out_flush(void) {
    if (!iob_n || out_err)
        return;
    long r = out_first ? vx_write(out_path, iob, (size_t)iob_n) : vx_append(out_path, iob, (size_t)iob_n);
    if (r < 0)
        out_err = 1;
    out_first = 0;
    iob_n = 0;
}
static void out_begin(const char *p) {
    scpy(out_path, p, sizeof out_path);
    out_first = 1;
    out_err = 0;
    iob_n = 0;
}
static void out_b(u8 c) {
    if (iob_n >= 1024 * 1024)
        out_flush();
    iob[iob_n++] = c;
}
static void out_s(const char *s) {
    while (*s)
        out_b((u8)*s++);
}
static int out_end(void) {
    if (out_first) { /* nothing at all: still an empty file */
        if (vx_write(out_path, iob, (size_t)iob_n) < 0)
            out_err = 1;
        out_first = 0;
        iob_n = 0;
    } else
        out_flush();
    return !out_err;
}
static long read_file(const char *p) { /* into iob; the length or -1 */
    vx_stat_t st;
    if (vx_stat(p, &st) < 0 || st.dir)
        return -1;
    if (st.size > IOB)
        return -2;
    long n = 0;
    while ((unsigned long)n < st.size) {
        long r = vx_read_at(p, iob + n, (unsigned long)n, (size_t)(st.size - (unsigned long)n) > 512 * 1024 ? 512 * 1024 : (size_t)(st.size - (unsigned long)n));
        if (r <= 0)
            break;
        n += r;
    }
    return n;
}
static int write_vpd(const char *p) {
    out_begin(p);
    out_s("VPD1");
    for (int i = 0; i < 4; i++)
        out_b((u8)((u32)len >> (8 * i)));
    for (int i = 0; i < len; i++) {
        out_b(doc[i].c);
        out_b((u8)doc[i].s);
        out_b((u8)(doc[i].s >> 8));
    }
    return out_end();
}
static void fix_doc(void) { /* a text ends with an end of paragraph, styles stay in range */
    if (!len || doc[len - 1].c != '\n') {
        doc[len].c = '\n';
        doc[len].s = len ? (u16)(doc[len - 1].s & S_CHAR) : S_DEFAULT;
        len++;
    }
    for (int i = 0; i < len; i++)
        if ((doc[i].s & S_SIZE) >= NSIZE)
            doc[i].s = (u16)((doc[i].s & ~S_SIZE) | (S_DEFAULT & S_SIZE));
}
static int load_vpd(long n) {
    if (n < 8 || iob[0] != 'V' || iob[1] != 'P' || iob[2] != 'D' || iob[3] != '1')
        return 0;
    long m = (long)((u32)iob[4] | (u32)iob[5] << 8 | (u32)iob[6] << 16 | (u32)iob[7] << 24);
    if (m < 0 || m > DOC_CAP - 1 || 8 + 3 * m > n)
        return 0;
    for (long i = 0; i < m; i++) {
        doc[i].c = iob[8 + 3 * i];
        doc[i].s = (u16)(iob[9 + 3 * i] | iob[10 + 3 * i] << 8);
    }
    len = (int)m;
    fix_doc();
    return 1;
}
static int uni_to_cp(u32 u) {
    if (u < 128)
        return (int)u;
    for (int i = 128; i < 256; i++)
        if (cp437_uni[i] == u)
            return i;
    return '?';
}
static void load_text(long n) {
    /* UTF-8 when there are its sequences and nothing that breaks them */
    int utf = 0, bad = 0;
    for (long i = 0; i < n; i++) {
        u8 c = iob[i];
        if (c >= 0xC2 && c <= 0xF4) {
            int k = c >= 0xF0 ? 3 : c >= 0xE0 ? 2 : 1, ok = i + k < n;
            for (int j = 1; j <= k && ok; j++)
                ok = (iob[i + j] & 0xC0) == 0x80;
            if (ok) {
                utf = 1;
                i += k;
            } else
                bad = 1;
        } else if (c >= 0x80)
            bad = 1;
    }
    utf = utf && !bad;
    len = 0;
    for (long i = 0; i < n && len < DOC_CAP - 2; i++) {
        u32 c = iob[i];
        if (utf && c >= 0xC0) {
            int k = c >= 0xF0 ? 3 : c >= 0xE0 ? 2 : 1;
            u32 u = c & (k == 1 ? 0x1F : k == 2 ? 0x0F : 0x07);
            for (int j = 1; j <= k && i + j < n; j++)
                u = u << 6 | (iob[i + j] & 0x3F);
            i += k;
            if (u == 0xFEFF)
                continue;
            if (u == 0x20AC && len < DOC_CAP - 4) { /* the euro sign is not in CP437 */
                for (int j = 0; j < 3; j++) {
                    doc[len].c = (u8)"EUR"[j];
                    doc[len++].s = S_DEFAULT;
                }
                continue;
            }
            c = (u32)uni_to_cp(u);
        }
        if (c == '\r')
            continue;
        if (c < 32 && c != '\n' && c != '\t' && c != 0x14 && c != 0x15)
            continue;
        doc[len].c = (u8)c;
        doc[len].s = S_DEFAULT;
        len++;
    }
    fix_doc();
}
static int export_text(const char *p) {
    out_begin(p);
    for (int i = 0; i < len - 1; i++)
        out_b(doc[i].c);
    return out_end();
}
static void out_utf8(u32 u) {
    if (u < 0x80)
        out_b((u8)u);
    else if (u < 0x800) {
        out_b((u8)(0xC0 | u >> 6));
        out_b((u8)(0x80 | (u & 63)));
    } else {
        out_b((u8)(0xE0 | u >> 12));
        out_b((u8)(0x80 | (u >> 6 & 63)));
        out_b((u8)(0x80 | (u & 63)));
    }
}
static void out_hex(u32 v) {
    const char *h = "0123456789abcdef";
    out_b('#');
    for (int i = 20; i >= 0; i -= 4)
        out_b((u8)h[v >> i & 15]);
}
static void out_num(long v) {
    char t[24] = "";
    snum(t, v, 24);
    out_s(t);
}
static int export_html(const char *p) {
    static const char *al[4] = {"left", "center", "right", "justify"};
    out_begin(p);
    out_s("<!DOCTYPE html>\n<html><head><meta charset=\"utf-8\"><title>");
    const char *t = path[0] ? base_name(path) : "Vio-Pad";
    for (; *t; t++)
        out_utf8(cp437_uni[(u8)*t]);
    out_s("</title>\n<style>body{max-width:40em;margin:2em auto;padding:0 1em;font-family:'DejaVu Sans',sans-serif}"
          "p{margin:0;min-height:1em}.s{font-family:'DejaVu Serif',serif}.m{font-family:monospace}</style></head><body>\n");
    int i = 0;
    while (i < len) {
        int b = para_end(i);
        out_s("<p style=\"text-align:");
        out_s(al[(doc[b].s & S_ALIGN) >> S_ALSH]);
        out_s("\">");
        if (i == b)
            out_s("&nbsp;");
        while (i < b) {
            u16 s = doc[i].s & S_CHAR;
            out_s("<span");
            if (s & S_SERIF)
                out_s(" class=\"s\"");
            if (s & S_SYS)
                out_s(" class=\"m\"");
            out_s(" style=\"font-size:");
            out_num(sizes[s & S_SIZE]);
            out_s("pt");
            if (s & S_BOLD)
                out_s(";font-weight:bold");
            if (s & S_ITAL)
                out_s(";font-style:italic");
            if (s & (S_UNDER | S_STRIKE)) {
                out_s(";text-decoration:");
                if (s & S_UNDER)
                    out_s("underline ");
                if (s & S_STRIKE)
                    out_s("line-through");
            }
            if (s & S_COL) {
                out_s(";color:");
                out_hex(colours[(s & S_COL) >> S_COLSH].rgb);
            }
            out_s("\">");
            for (; i < b && (doc[i].s & S_CHAR) == s; i++) {
                u8 c = doc[i].c;
                if (c == '<')
                    out_s("&lt;");
                else if (c == '>')
                    out_s("&gt;");
                else if (c == '&')
                    out_s("&amp;");
                else if (c == '\t')
                    out_s("&emsp;&emsp;");
                else if (c == ' ' && (i == 0 || doc[i - 1].c == ' '))
                    out_s("&nbsp;");
                else
                    out_utf8(cp437_uni[c]);
            }
            out_s("</span>");
        }
        out_s("</p>\n");
        i = b + 1;
    }
    out_s("</body></html>\n");
    return out_end();
}

/* ---------------------------------------------------------------- licences */
static const char *const lic[] = {
    "Vio-Pad",
    "Copyright (c) 2026, Merecete",
    "",
    "Redistribution and use in source and binary forms, with or without",
    "modification, are permitted provided that the following conditions",
    "are met:",
    "",
    "1. Redistributions of source code must retain the above copyright",
    "   notice, this list of conditions and the following disclaimer.",
    "",
    "2. Redistributions in binary form must reproduce the above copyright",
    "   notice, this list of conditions and the following disclaimer in the",
    "   documentation and/or other materials provided with the distribution.",
    "",
    "3. Neither the name of the copyright holder nor the names of its",
    "   contributors may be used to endorse or promote products derived from",
    "   this software without specific prior written permission.",
    "",
    "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS",
    "IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED",
    "TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A",
    "PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT",
    "HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,",
    "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED",
    "TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR",
    "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF",
    "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING",
    "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS",
    "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
        "",
    "",
    "The letters: DejaVu Sans and DejaVu Serif",
    "Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved.",
    "Bitstream Vera is a trademark of Bitstream, Inc.",
    "DejaVu changes are in public domain.",
    "Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below).",
    "",
    "Permission is hereby granted, free of charge, to any person obtaining",
    "a copy of the fonts accompanying this license (\"Fonts\") and associated",
    "documentation files (the \"Font Software\"), to reproduce and distribute",
    "the Font Software, including without limitation the rights to use, copy,",
    "merge, publish, distribute, and/or sell copies of the Font Software, and",
    "to permit persons to whom the Font Software is furnished to do so,",
    "subject to the following conditions:",
    "",
    "The above copyright and trademark notices and this permission notice",
    "shall be included in all copies of one or more of the Font Software",
    "typefaces.",
    "",
    "The Font Software may be modified, altered, or added to, and in",
    "particular the designs of glyphs or characters in the Fonts may be",
    "modified and additional glyphs or characters may be added to the Fonts,",
    "only if the fonts are renamed to names not containing either the words",
    "\"Bitstream\" or the word \"Vera\".",
    "",
    "This License becomes null and void to the extent applicable to Fonts or",
    "Font Software that has been modified and is distributed under the",
    "\"Bitstream Vera\" names.",
    "",
    "The Font Software may be sold as part of a larger software package but",
    "no copy of one or more of the Font Software typefaces may be sold by",
    "itself.",
    "",
    "THE FONT SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
    "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF",
    "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF",
    "COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL",
    "BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR",
    "OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL,",
    "OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
    "OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT",
    "SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.",
    "",
    "Except as contained in this notice, the names of Gnome, the Gnome",
    "Foundation, and Bitstream Inc., shall not be used in advertising or",
    "otherwise to promote the sale, use or other dealings in this Font",
    "Software without prior written authorization from the Gnome Foundation",
    "or Bitstream Inc., respectively. For further information, contact:",
    "fonts at gnome dot org.",
    "",
    "",
    "Arev Fonts Copyright",
    "Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved.",
    "",
    "Permission is hereby granted, free of charge, to any person obtaining",
    "a copy of the fonts accompanying this license (\"Fonts\") and",
    "associated documentation files (the \"Font Software\"), to reproduce",
    "and distribute the modifications to the Bitstream Vera Font Software,",
    "including without limitation the rights to use, copy, merge, publish,",
    "distribute, and/or sell copies of the Font Software, and to permit",
    "persons to whom the Font Software is furnished to do so, subject to",
    "the following conditions:",
    "",
    "The above copyright and trademark notices and this permission notice",
    "shall be included in all copies of one or more of the Font Software",
    "typefaces.",
    "",
    "The Font Software may be modified, altered, or added to, and in",
    "particular the designs of glyphs or characters in the Fonts may be",
    "modified and additional glyphs or characters may be added to the",
    "Fonts, only if the fonts are renamed to names not containing either",
    "the words \"Tavmjong Bah\" or the word \"Arev\".",
    "",
    "This License becomes null and void to the extent applicable to Fonts",
    "or Font Software that has been modified and is distributed under the",
    "\"Tavmjong Bah Arev\" names.",
    "",
    "The Font Software may be sold as part of a larger software package but",
    "no copy of one or more of the Font Software typefaces may be sold by",
    "itself.",
    "",
    "THE FONT SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
    "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF",
    "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT",
    "OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL",
    "TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,",
    "INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL",
    "DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
    "FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM",
    "OTHER DEALINGS IN THE FONT SOFTWARE.",
    "",
    "Except as contained in this notice, the name of Tavmjong Bah shall not",
    "be used in advertising or otherwise to promote the sale, use or other",
    "dealings in this Font Software without prior written authorization",
    "from Tavmjong Bah. For further information, contact: tavmjong @ free",
    ". fr.",
    "",
    "",
    "The system font: Spleen 8x16",
    "Copyright (c) 2018-2026, Frederic Cambus",
    "All rights reserved.",
    "",
    "Redistribution and use in source and binary forms, with or without",
    "modification, are permitted provided that the following conditions",
    "are met:",
    "",
    "  * Redistributions of source code must retain the above copyright",
    "    notice, this list of conditions and the following disclaimer.",
    "",
    "  * Redistributions in binary form must reproduce the above copyright",
    "    notice, this list of conditions and the following disclaimer in the",
    "    documentation and/or other materials provided with the distribution.",
    "",
    "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS",
    "IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED",
    "TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A",
    "PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT",
    "HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,",
    "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED",
    "TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR",
    "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF",
    "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING",
    "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS",
    "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
    0};

/* ---------------------------------------------------------------- around the page */
static int panel, lic_top; /* 1 format, 2 keys, 3 info, 4 licences */
static char msg[96];
static long msg_until;
static void say(const char *s) {
    scpy(msg, s, sizeof msg);
    msg_until = vx_ms() + 3500;
}
#define A_BAR  VX_ATTR(VC_PANEL, VC_SOFT)
#define A_BTN  VX_ATTR(VC_RAISE, VC_SOFT)
#define A_ON   VX_ATTR(VC_SEL, VC_GLOW)
#define A_DIM  VX_ATTR(VC_PANEL, VC_MID)
#define A_HOT  VX_ATTR(VC_PANEL, VC_HOT)
#define A_BOX  VX_ATTR(VC_PANEL, VC_GLOW)
static void text_clip(int x, int y, const char *s, u8 a) {
    for (; *s && x < W; s++, x++)
        if (x >= 0)
            vx_put(x, y, *s, a);
}
static int button(int x, const char *s, int on) {
    u8 a = on ? A_ON : A_BTN;
    text_clip(x, 0, " ", a);
    text_clip(x + 1, 0, s, a);
    text_clip(x + 1 + slen(s), 0, " ", a);
    return x + slen(s) + 3;
}
static u16 shown_style(void) { /* the style the bar shows: of the selection or of typing */
    return has_sel() ? (u16)(doc[sel_a()].s & S_CHAR) : tstyle;
}
static int face_ix(u16 s) {
    return (s & S_SYS) ? 0 : (s & S_SERIF) ? 2 : 1;
}
static const char *face_name[3] = {"System", "Sans", "Serif"};
static const char *al_de[4] = {"Links", "Mitte", "Rechts", "Block"}, *al_en[4] = {"Left", "Centre", "Right", "Justify"};
static void draw_bar(void) {
    for (int x = 0; x < W; x++)
        vx_put(x, 0, ' ', A_BAR);
    u16 s = shown_style();
    int x = 1;
    x = button(x, T("F", "B"), s & S_BOLD) - 1;
    x = button(x, T("K", "I"), s & S_ITAL) - 1;
    x = button(x, "U", s & S_UNDER) - 1;
    x = button(x, T("D", "S"), s & S_STRIKE) + 1;
    char t[24];
    scpy(t, face_name[face_ix(s)], 24);
    scat(t, " ", 24);
    snum(t, sizes[s & S_SIZE], 24);
    scat(t, " pt", 24);
    x = button(x, t, 0) + 1;
    int al = (doc[para_end(cur)].s & S_ALIGN) >> S_ALSH;
    x = button(x, lang_en ? al_en[al] : al_de[al], 0) + 1;
    int c = (s & S_COL) >> S_COLSH;
    u32 rgb = c ? colours[c].rgb : 0xEBEBEB; /* black shows as white on the dark bar */
    if (x < W)
        vx_paint(x, 0, (char)0xFE, vx_rgb((int)(rgb >> 16 & 255), (int)(rgb >> 8 & 255), (int)(rgb & 255)), VC_PANEL);
    text_clip(x + 2, 0, lang_en ? colours[c].en : colours[c].de, A_BAR);
    x += 3 + slen(lang_en ? colours[c].en : colours[c].de);
    /* the name of the file at the right */
    char n[64];
    scpy(n, path[0] ? base_name(path) : T("Unbenannt", "Untitled"), 60);
    if (dirty)
        scat(n, " *", 64);
    int nx = W - 1 - slen(n);
    if (nx > x + 1)
        text_clip(nx, 0, n, dirty ? A_HOT : A_BAR);
}
static void draw_status(void) {
    int y = H - 1;
    for (int x = 0; x < W; x++)
        vx_put(x, y, ' ', A_BAR);
    char t[120] = " ";
    if (msg[0] && vx_ms() < msg_until) {
        scat(t, msg, 120);
        text_clip(0, y, t, A_HOT);
        return;
    }
    int k = line_of(cur);
    scat(t, T("Seite ", "Page "), 120);
    snum(t, ln[k].page + 1, 120);
    scat(t, T(" von ", " of "), 120);
    snum(t, npages, 120);
    scat(t, T("   Zeile ", "   Line "), 120);
    snum(t, k + 1, 120);
    scat(t, T("   W\x94rter ", "   Words "), 120);
    snum(t, words, 120);
    if (has_sel()) {
        scat(t, T("   markiert ", "   selected "), 120);
        snum(t, sel_b() - sel_a(), 120);
    }
    text_clip(0, y, t, A_BAR);
    const char *h = T("F8 Format  F1 Tasten ", "F8 Format  F1 Keys ");
    if (slen(t) + slen(h) + 2 < W)
        text_clip(W - slen(h), y, h, A_DIM);
}
static void box(int x, int y, int w, int h) {
    for (int j = 0; j < h; j++)
        for (int i = 0; i < w; i++)
            if (x + i >= 0 && x + i < W && y + j >= 0 && y + j < H)
                vx_put(x + i, y + j, ' ', A_BOX);
}
/* the format panel: arrows choose, left and right or Enter change, Esc closes */
static int fsel, esel;
#define NFROW 10
static void draw_format(void) {
    u16 s = shown_style();
    int al = (doc[para_end(cur)].s & S_ALIGN) >> S_ALSH, c = (s & S_COL) >> S_COLSH;
    static const char *lde[NFROW] = {"Schriftart", "Gr\x94\xE1" "e", "Farbe", "Fett", "Kursiv", "Unterstrichen", "Durchgestrichen", "Ausrichtung", "Formatierung entfernen", "Fertig"};
    static const char *len_[NFROW] = {"Typeface", "Size", "Colour", "Bold", "Italic", "Underlined", "Struck out", "Alignment", "Remove formatting", "Done"};
    static const char *kde[NFROW] = {"S", "+ -", "", "F", "K", "U", "D", "L M R B", "N", ""};
    static const char *ken[NFROW] = {"F", "+ -", "", "B", "I", "U", "S", "L C R J", "N", ""};
    int bw = 46, bh = NFROW + 5, x = W - bw - 1, y = 2;
    if (x < 0)
        x = 0;
    if (y + bh > H - 1)
        y = H - 1 - bh > 1 ? H - 1 - bh : 1;
    box(x, y, bw, bh);
    text_clip(x + 2, y, T("FORMAT", "FORMAT"), A_HOT);
    for (int i = 0; i < NFROW; i++) {
        int yy = y + 1 + i + (i >= 8);
        u8 a = i == fsel ? A_ON : A_BOX;
        for (int k = 1; k < bw - 1; k++)
            text_clip(x + k, yy, " ", a);
        text_clip(x + 2, yy, lang_en ? len_[i] : lde[i], a);
        char v[32] = "";
        if (i == 0)
            scpy(v, face_name[face_ix(s)], 32);
        else if (i == 1) {
            snum(v, sizes[s & S_SIZE], 32);
            scat(v, " pt", 32);
        } else if (i == 2)
            scpy(v, lang_en ? colours[c].en : colours[c].de, 32);
        else if (i >= 3 && i <= 6) {
            static const u16 fl[4] = {S_BOLD, S_ITAL, S_UNDER, S_STRIKE};
            scpy(v, (s & fl[i - 3]) ? "[\xFB]" : "[ ]", 32);
        } else if (i == 7)
            scpy(v, lang_en ? al_en[al] : al_de[al], 32);
        if (v[0]) {
            int vx = x + 20;
            if (i <= 2 || i == 7) {
                text_clip(vx, yy, "\x11 ", a);
                vx += 2;
            }
            if (i == 2) {
                u32 rgb = c ? colours[c].rgb : 0xEBEBEB;
                vx_paint(vx, yy, (char)0xFE, vx_rgb((int)(rgb >> 16 & 255), (int)(rgb >> 8 & 255), (int)(rgb & 255)), i == fsel ? VC_SEL : VC_PANEL);
                vx += 2;
            }
            text_clip(vx, yy, v, a);
            vx += slen(v);
            if (i <= 2 || i == 7)
                text_clip(vx, yy, " \x10", a);
        }
        const char *k = lang_en ? ken[i] : kde[i];
        if (k[0])
            text_clip(x + bw - 2 - slen(k), yy, k, i == fsel ? A_ON : A_DIM);
    }
    text_clip(x + 2, y + bh - 2, T("\x18\x19 w\x84hlen  \x1B\x1A \x84ndern  Enter umschalten", "\x18\x19 choose  \x1B\x1A change  Enter toggle"), A_DIM);
    text_clip(x + 2, y + bh - 1, T("Gilt f\x81r Markiertes oder das Weiterschreiben", "For the selection or what you type next"), A_DIM);
}
static void draw_export(void) {
    const char *l[3] = {T("Als Webseite (.html), mit Formatierung", "As a web page (.html), with formatting"),
                        T("Als reiner Text (.txt)", "As plain text (.txt)"), T("Abbrechen", "Cancel")};
    int bw = 46, bh = 7, x = (W - bw) / 2, y = (H - bh) / 2;
    box(x, y, bw, bh);
    text_clip(x + 2, y, T("EXPORTIEREN", "EXPORT"), A_HOT);
    for (int i = 0; i < 3; i++) {
        u8 a = i == esel ? A_ON : A_BOX;
        for (int k = 1; k < bw - 1; k++)
            text_clip(x + k, y + 2 + i, " ", a);
        text_clip(x + 2, y + 2 + i, l[i], a);
    }
    text_clip(x + 2, y + bh - 1, T("\x18\x19 w\x84hlen  Enter ausf\x81hren  Esc zur\x81" "ck", "\x18\x19 choose  Enter go  Esc back"), A_DIM);
}
static const char *const keys_de[] = {
    "TASTEN",
    "Strg+N Neu   Strg+O \x99" "ffnen   Strg+S Speichern   Strg+F Suchen",
    "Strg+Z R\x81" "ckg\x84ngig   Strg+Y Wiederholen   Strg+A Alles markieren",
    "Strg+C / X / V  Kopieren / Ausschneiden / Einf\x81gen",
    "Umschalt+Pfeile markieren, Strg+Pfeile springen wortweise",
    "Strg+B Fett  Strg+I Kursiv  Strg+U Unterstr.  Strg+D Durchgestr.",
    "Strg+Plus / Minus  Gr\x94\xE1" "er / kleiner (auch F12 / F11)",
    "Strg+L / E / R / J  links, mittig, rechts, Blocksatz",
    "Strg+Leertaste  Formatierung entfernen",
    "F8 Format: Schriftart, Gr\x94\xE1" "e, Farbe ... mit Pfeilen und Enter",
    "Schriftarten: System (scharf, wie Violyx), Sans und Serif.",
    "In System 10 pt sind Fett usw. hell hinterlegt, ab 20 pt sichtbar.",
    "Esc schlie\xE1t und fragt vorher nach dem Speichern.",
    0};
static const char *const keys_en[] = {
    "KEYS",
    "Ctrl+N New   Ctrl+O Open   Ctrl+S Save   Ctrl+F Find",
    "Ctrl+Z Undo   Ctrl+Y Redo   Ctrl+A Select all",
    "Ctrl+C / X / V  Copy / Cut / Paste",
    "Shift+arrows select, Ctrl+arrows jump by words",
    "Ctrl+B Bold  Ctrl+I Italic  Ctrl+U Underlined  Ctrl+D Struck out",
    "Ctrl+Plus / Minus  bigger / smaller (also F12 / F11)",
    "Ctrl+L / E / R / J  left, centred, right, justified",
    "Ctrl+Space  remove formatting",
    "F8 Format: typeface, size, colour ... with arrows and Enter",
    "Typefaces: System (sharp, like Violyx), Sans and Serif.",
    "In System 10 pt bold etc. are marked light, from 20 pt they show.",
    "Esc closes and asks first about saving.",
    0};
static void draw_keys(void) {
    const char *const *k = lang_en ? keys_en : keys_de;
    int n = 0;
    while (k[n])
        n++;
    int bw = W - 2 < 72 ? W - 2 : 72, bh = n + 3, x = (W - bw) / 2, y = (H - bh) / 2;
    if (y < 1)
        y = 1;
    box(x, y, bw, bh);
    for (int i = 0; i < n && y + 1 + i < H; i++)
        text_clip(x + 2, y + 1 + i, k[i], i ? A_BOX : A_HOT);
    text_clip(x + 2, y + bh - 1, T("Enter zur\x81" "ck", "Enter back"), A_DIM);
}
static void draw_info(void) {
    if (panel == 3) {
        int bw = 44, bh = 13, x = (W - bw) / 2, y = (H - bh) / 2;
        box(x, y, bw, bh);
        const char *l[] = {"Vio-Pad", "Version 1.0", "(c) 2026 Merecete", T("Lizenz: BSD-3-Clause", "Licence: BSD-3-Clause"),
                           T("Schriften: DejaVu (Bitstream Vera, Arev),", "Letters: DejaVu (Bitstream Vera, Arev),"),
                           T("Spleen (BSD-2-Clause)", "Spleen (BSD-2-Clause)")};
        int ly[] = {1, 3, 5, 6, 8, 9};
        for (int i = 0; i < 6; i++)
            text_clip(x + (bw - slen(l[i])) / 2, y + ly[i], l[i], i ? A_BOX : A_HOT);
        const char *h = T("L Lizenzen  T Tasten  Enter zur\x81" "ck", "L licences  K keys  Enter back");
        text_clip(x + (bw - slen(h)) / 2, y + bh - 2, h, A_DIM);
        return;
    }
    int bw = W - 2 < 76 ? W - 2 : 76, bh = H - 2, x = (W - bw) / 2, y = 1, n = 0, rows = bh - 2;
    while (lic[n])
        n++;
    if (lic_top > n - rows)
        lic_top = n - rows;
    if (lic_top < 0)
        lic_top = 0;
    box(x, y, bw, bh);
    for (int r = 0; r < rows && lic_top + r < n; r++)
        text_clip(x + 2, y + r, lic[lic_top + r], lic_top + r ? A_BOX : A_HOT);
    text_clip(x + 2, y + bh - 1, T("Hoch/Runter bl\x84ttern   Enter zur\x81" "ck", "Up/Down scroll   Enter back"), A_DIM);
}
static void draw(void) {
    W = vx_cols();
    H = vx_rows();
    if (W < 24 || H < 6 || !font_ok) {
        vx_clear(VX_ATTR(VC_BLACK, VC_GLOW));
        if (!font_ok)
            vx_text(1, 1, T("Die Schriften fehlen.", "The letters are missing."), VX_ATTR(VC_BLACK, VC_HOT));
        vx_show();
        return;
    }
    int cw = W > 240 ? 240 : W, rh = H - 2 > 100 ? 100 : H - 2;
    AW = cw * 4;
    AH = rh * 8;
    ensure_visible();
    draw_page();
    vx_image(img, AW, AH);
    vx_clear(A_BAR);
    for (int y = 0; y < rh; y++)
        for (int x = 0; x < cw; x++)
            vx_pixcell(x, y + 1, x, y);
    for (int i = 0; i < ntc; i++)
        vx_paint(tcells[i].x, tcells[i].y + 1, (char)tcells[i].c, tcells[i].fg, tcells[i].bg);
    draw_bar();
    draw_status();
    if (panel == 1)
        draw_format();
    else if (panel == 2)
        draw_keys();
    else if (panel == 5)
        draw_export();
    else if (panel >= 3)
        draw_info();
    char t[40] = "";
    if (dirty)
        scat(t, "* ", 40);
    scat(t, path[0] ? base_name(path) : T("Unbenannt", "Untitled"), 30);
    scat(t, " - Vio-Pad", 40);
    vx_title(t);
    vx_show();
}

/* ---------------------------------------------------------------- open, save, close */
static void autosave_clear(void) {
    vx_remove("autosave.vpd");
    vx_remove("autosave.pth");
}
static int save_to(const char *p) {
    if (!write_vpd(p)) {
        vx_message(T("Speichern", "Save"), T("Das Dokument lie\xE1 sich dort nicht speichern.", "The document could not be saved there."));
        return 0;
    }
    if (path != p)
        scpy(path, p, sizeof path);
    dirty = 0;
    autosave_clear();
    char m[96];
    scpy(m, T("Gespeichert: ", "Saved: "), 96);
    scat(m, p, 96);
    say(m);
    return 1;
}
static void suggest(char *b, int n, const char *ext) { /* the name of the document with another ending */
    scpy(b, path[0] ? path : T("/home/Dokument", "/home/Document"), n - 8);
    int l = slen(b);
    for (int i = l - 1; i >= 0 && b[i] != '/'; i--)
        if (b[i] == '.') {
            b[i] = 0;
            break;
        }
    scat(b, ext, n);
}
static int ask_path(const char *title, const char *ext, char *full, int n) {
    char b[200];
    suggest(b, sizeof b, ext);
    if (!vx_input(title, T("Name oder Pfad (ohne Pfad: im Ordner /home):", "Name or path (without a path: in /home):"), b, sizeof b))
        return 0;
    if (!b[0])
        return 0;
    full[0] = 0;
    int slash = 0;
    for (int i = 0; b[i]; i++)
        slash |= b[i] == '/';
    if (!slash)
        scpy(full, HOME_DIR, n);
    scat(full, b, n);
    if (!ends_with(full, ext))
        scat(full, ext, n);
    vx_stat_t st;
    if (vx_stat(full, &st) >= 0) {
        if (st.dir)
            return 0;
        char m[200];
        scpy(m, base_name(full), 200);
        scat(m, T(" gibt es schon. \x9A" "berschreiben?", " exists already. Replace it?"), 200);
        if (!vx_ask(title, m))
            return 0;
    }
    return 1;
}
static int save_as(void) {
    char p[256];
    if (!ask_path(T("Speichern unter", "Save as"), ".vpd", p, sizeof p))
        return 0;
    return save_to(p);
}
static int save(void) {
    if (path[0] && ends_with(path, ".vpd"))
        return save_to(path);
    if (path[0]) { /* a text file was opened */
        if (!vx_ask(T("Speichern", "Save"), T("Das ist eine Textdatei. Als Vio-Pad-Dokument (.vpd) mit Formatierung speichern? Nein speichert als reinen Text ohne Formatierung.",
                                              "This is a text file. Save as a Vio-Pad document (.vpd) with its formatting? No saves plain text without formatting."))) {
            if (!export_text(path)) {
                vx_message(T("Speichern", "Save"), T("Die Datei lie\xE1 sich nicht schreiben.", "The file could not be written."));
                return 0;
            }
            dirty = 0;
            autosave_clear();
            say(T("Als Text gespeichert.", "Saved as text."));
            return 1;
        }
    }
    return save_as();
}
static int may_drop(void) { /* before the document goes: saved, or the user lets it go */
    if (!dirty)
        return 1;
    if (vx_ask(T("Ge\x84ndertes Dokument", "Changed document"), T("Das Dokument wurde ge\x84ndert. Jetzt speichern?", "The document was changed. Save it now?")))
        return save();
    return vx_ask(T("Nicht speichern", "Don't save"), T("Die \x8E" "nderungen gehen verloren. Trotzdem weiter?", "The changes will be lost. Go on anyway?"));
}
static int open_path(const char *p) {
    long n = read_file(p);
    if (n < 0) {
        vx_message(T("\x99" "ffnen", "Open"), n == -2 ? T("Die Datei ist zu gro\xE1.", "The file is too big.") : T("Die Datei lie\xE1 sich nicht lesen.", "The file could not be read."));
        return 0;
    }
    if (ends_with(p, ".vpd")) {
        if (!load_vpd(n)) {
            vx_message(T("\x99" "ffnen", "Open"), T("Das ist kein Vio-Pad-Dokument.", "This is not a Vio-Pad document."));
            doc_new();
            return 0;
        }
    } else
        load_text(n);
    scpy(path, p, sizeof path);
    cur = 0;
    anc = -1;
    vy = 0;
    dirty = 0;
    changed = 1;
    undo_clear();
    pick_style();
    autosave_clear();
    return 1;
}
static void cmd_new(void) {
    if (!may_drop())
        return;
    doc_new();
    path[0] = 0;
    dirty = 0;
    changed = 1;
    vy = 0;
    autosave_clear();
}
static void cmd_open(void) {
    if (!may_drop())
        return;
    char p[256] = "";
    if (vx_choose_file(T("Dokument \x94" "ffnen (.vpd oder Text)", "Open a document (.vpd or text)"), p, sizeof p))
        open_path(p);
}
static void cmd_export(int html) {
    char p[256];
    if (!ask_path(html ? T("Als Webseite exportieren", "Export as web page") : T("Als Text exportieren", "Export as text"), html ? ".html" : ".txt", p, sizeof p))
        return;
    if (!(html ? export_html(p) : export_text(p))) {
        vx_message(T("Exportieren", "Export"), T("Die Datei lie\xE1 sich nicht schreiben.", "The file could not be written."));
        return;
    }
    char m[96];
    scpy(m, T("Exportiert: ", "Exported: "), 96);
    scat(m, p, 96);
    say(m);
}
static long last_auto;
static int auto_dirty; /* changed since the last safety copy */
static void autosave(int now) {
    if (!dirty || !auto_dirty || (!now && vx_ms() - last_auto < 20000))
        return;
    last_auto = vx_ms();
    if (write_vpd("autosave.vpd")) {
        vx_write("autosave.pth", path, (size_t)slen(path) + 1);
        auto_dirty = 0;
    }
}

/* ---------------------------------------------------------------- keys */
#define M_SHIFT 1
#define M_CTRL  2
#define M_ALT   4
#define M_OFF   8 /* Violyx switches off */
static void close_app(void) {
    if (!may_drop())
        return;
    autosave_clear();
    vx_exit();
}
static void menu_cmd(int n) {
    switch (n) {
        case 0: cmd_new(); break;
        case 1: cmd_open(); break;
        case 2: save(); break;
        case 3: save_as(); break;
        case 4:
            panel = panel == 1 ? 0 : 1;
            break;
        case 5:
            if (vx_input(T("Suchen", "Find"), T("Text:", "Text:"), find_s, sizeof find_s) && !find_next())
                say(T("Nicht gefunden.", "Not found."));
            break;
        case 6:
            panel = 5;
            esel = 0;
            break;
        case 7: panel = 3; break;
    }
}
static void fmt_change(int row, int dir) { /* a row of the format panel, left (-1) or right (+1) */
    u16 s = shown_style();
    switch (row) {
        case 0: format(OP_FACE, (face_ix(s) + (dir > 0 ? 1 : 2)) % 3); break;
        case 1: format(dir > 0 ? OP_BIGGER : OP_SMALLER, 0); break;
        case 2: format(OP_COLOUR, ((int)((s & S_COL) >> S_COLSH) + (dir > 0 ? 1 : 7)) % 8); break;
        case 3: format(OP_BOLD, 0); break;
        case 4: format(OP_ITAL, 0); break;
        case 5: format(OP_UNDER, 0); break;
        case 6: format(OP_STRIKE, 0); break;
        case 7: align((((int)(doc[para_end(cur)].s & S_ALIGN) >> S_ALSH) + (dir > 0 ? 1 : 3)) % 4); break;
        case 8: format(OP_PLAIN, 0); break;
        case 9: panel = 0; break;
    }
}
static int panel_key(int k) { /* 1 when the panel took the key */
    if (panel == 2) {
        panel = 0;
        return 1;
    }
    if (panel == 5) { /* export */
        if (k == VK_UP)
            esel = (esel + 2) % 3;
        else if (k == VK_DOWN)
            esel = (esel + 1) % 3;
        else if (k == VK_ENTER) {
            panel = 0;
            if (esel < 2)
                cmd_export(esel == 0);
        } else if (k == VK_ESC || k == VK_BS)
            panel = 0;
        return 1;
    }
    if (panel >= 3) {
        if (panel == 3 && lower(k) == 'l')
            panel = 4;
        else if (panel == 3 && (lower(k) == 't' || lower(k) == 'k'))
            panel = 2;
        else if (panel == 4 && k == VK_UP)
            lic_top--;
        else if (panel == 4 && k == VK_DOWN)
            lic_top++;
        else if (panel == 4 && k == VK_PGUP)
            lic_top -= 10;
        else if (panel == 4 && k == VK_PGDN)
            lic_top += 10;
        else if (k == VK_ENTER || k == VK_ESC || k == VK_BS)
            panel = panel == 4 ? 3 : 0;
        return 1;
    }
    /* the format panel */
    int c = lower(k);
    if (k == VK_ESC || k == VK_F8) {
        panel = 0;
        return 1;
    }
    if (k == VK_UP || k == VK_DOWN) {
        fsel = (fsel + (k == VK_DOWN ? 1 : NFROW - 1)) % NFROW;
        return 1;
    }
    if (k == VK_LEFT || k == VK_RIGHT) {
        if (fsel <= 2 || fsel == 7)
            fmt_change(fsel, k == VK_RIGHT ? 1 : -1);
        return 1;
    }
    if (k == VK_ENTER) {
        fmt_change(fsel, 1);
        return 1;
    }
    if (k >= '1' && k <= '9') {
        format(OP_SIZE, k - '1');
        return 1;
    }
    if (k == '+' || k == '-') {
        format(k == '+' ? OP_BIGGER : OP_SMALLER, 0);
        return 1;
    }
    static const char rows_de[] = "Sxx" "FKUD" "x" "N", rows_en[] = "Fxx" "BIUS" "x" "N";
    const char *r = lang_en ? rows_en : rows_de;
    for (int i = 0; r[i]; i++)
        if (r[i] != 'x' && c == lower(r[i])) {
            fsel = i == 7 ? 8 : i;
            fmt_change(fsel, 1);
            return 1;
        }
    int al = lang_en ? (c == 'l' ? 0 : c == 'c' ? 1 : c == 'r' ? 2 : c == 'j' ? 3 : -1)
                     : (c == 'l' ? 0 : c == 'm' ? 1 : c == 'r' ? 2 : c == 'b' ? 3 : -1);
    if (al >= 0) {
        fsel = 7;
        align(al);
        return 1;
    }
    return 1; /* everything else waits until the panel is closed */
}
static void key(int k, int mods) {
    int shift = mods & M_SHIFT, ctrl = mods & M_CTRL;
    if (k != VK_UP && k != VK_DOWN && k != VK_PGUP && k != VK_PGDN)
        goal = -1;
    if (k != VK_BS && k != VK_DEL)
        last_del = 0;
    if (k == VK_ESC) {
        if (mods & M_OFF) { /* switching off: keep a copy, no questions */
            if (dirty) {
                auto_dirty = 1;
                autosave(1);
            }
            vx_exit();
        }
        if (panel) {
            panel = panel == 4 ? 3 : 0;
            return;
        }
        close_app();
        return;
    }
    if (k >= VK_MENU && k < VK_MENU + 16) {
        menu_cmd(k - VK_MENU);
        return;
    }
    if (k == VK_F1) {
        panel = panel == 2 ? 0 : 2;
        return;
    }
    if (k == VK_F8) {
        panel = panel == 1 ? 0 : 1;
        return;
    }
    if (panel && !ctrl && panel_key(k))
        return;
    if (ctrl) {
        int c = lower(k);
        if (shift && c == 's')
            save_as();
        else if (c == 's')
            save();
        else if (c == 'o')
            cmd_open();
        else if (c == 'n')
            cmd_new();
        else if (c == 'z')
            undo();
        else if (c == 'y')
            redo();
        else if (c == 'a') {
            anc = 0;
            cur = len - 1;
            typing = 0;
        } else if (c == 'c')
            copy_sel();
        else if (c == 'x') {
            if (has_sel()) {
                copy_sel();
                snap();
                del_sel();
                pick_style();
            }
        } else if (c == 'v')
            paste();
        else if (c == 'f')
            menu_cmd(5);
        else if (c == 'b' || (shift && c == 'f'))
            format(OP_BOLD, 0);
        else if (c == 'i' || (shift && c == 'k'))
            format(OP_ITAL, 0);
        else if (c == 'u')
            format(OP_UNDER, 0);
        else if (c == 'd')
            format(OP_STRIKE, 0);
        else if (c == '+' || c == '>' || c == '*')
            format(OP_BIGGER, 0);
        else if (c == '-' || c == '<' || c == '_')
            format(OP_SMALLER, 0);
        else if (c == ' ')
            format(OP_PLAIN, 0);
        else if (c == 'l')
            align(0);
        else if (c == 'e')
            align(1);
        else if (c == 'r')
            align(2);
        else if (c == 'j')
            align(3);
        else if (k == VK_LEFT)
            move_to(word_left(cur), shift);
        else if (k == VK_RIGHT)
            move_to(word_right(cur), shift);
        else if (k == VK_HOME)
            move_to(0, shift);
        else if (k == VK_END)
            move_to(len - 1, shift);
        else if (k == VK_BS)
            backspace(1);
        else if (k == VK_DEL)
            delete_fwd(1);
        else if (k == VK_UP)
            vertical(-1, shift);
        else if (k == VK_DOWN)
            vertical(1, shift);
        return;
    }
    switch (k) {
        case VK_LEFT:
            if (has_sel() && !shift)
                move_to(sel_a(), 0);
            else
                move_to(cur - 1, shift);
            return;
        case VK_RIGHT:
            if (has_sel() && !shift)
                move_to(sel_b(), 0);
            else
                move_to(cur + 1, shift);
            return;
        case VK_UP:
            vertical(-1, shift);
            return;
        case VK_DOWN:
            vertical(1, shift);
            return;
        case VK_PGUP:
            page_move(-1, shift);
            return;
        case VK_PGDN:
            page_move(1, shift);
            return;
        case VK_HOME:
            move_to(ln[line_of(cur)].a, shift);
            return;
        case VK_END: {
            line_t *L = &ln[line_of(cur)];
            move_to(L->e - 1, shift);
            return;
        }
        case VK_BS:
            backspace(0);
            return;
        case VK_DEL:
            delete_fwd(0);
            return;
        case VK_ENTER:
            type_char('\n');
            return;
        case VK_TAB:
            type_char('\t');
            return;
        case VK_F11:
            format(OP_SMALLER, 0);
            return;
        case VK_F12:
            format(OP_BIGGER, 0);
            return;
    }
    if (k >= 32 && k < 256 && k != 127 && !(mods & M_ALT))
        type_char((u8)k);
}

/* ---------------------------------------------------------------- main */
int main(void) {
    lang_en = vx_english();
    vx_title("Vio-Pad");
    vx_menu(T("Neu|Oeffnen|Speichern|Speichern unter|Format|Suchen|Exportieren|Info", "New|Open|Save|Save as|Format|Find|Export|Info"));
    vx_sys(23, 3, 2, 0); /* Esc comes as a key: unsaved changes are asked for first */
    vx_sys(23, 8, 1, 0); /* F1 too */
    doc = vx_alloc((size_t)DOC_CAP * sizeof(ch_t));
    clip = vx_alloc((size_t)DOC_CAP * sizeof(ch_t));
    ln = vx_alloc((size_t)MAXL * sizeof(line_t));
    iob = vx_alloc(IOB);
    umem = vx_alloc(UNDO_MEM);
    load_fonts();
    if (!doc || !clip || !ln || !iob)
        font_ok = 0;
    init_colours();
    if (font_ok) {
        doc_new();
        long n = read_file("clip"); /* what was copied last time */
        if (n > 4 && iob[0] == 'V' && iob[1] == 'P' && iob[2] == 'C' && iob[3] == '1' && (n - 4) % (long)sizeof(ch_t) == 0) {
            clip_n = (int)((n - 4) / (long)sizeof(ch_t));
            if (clip_n > DOC_CAP)
                clip_n = 0;
            else
                memcpy(clip, iob + 4, (size_t)clip_n * sizeof(ch_t));
        }
        vx_stat_t st;
        if (vx_stat("autosave.vpd", &st) >= 0 &&
            vx_ask("Vio-Pad", T("Beim letzten Mal blieb ein Dokument ungespeichert. Wiederherstellen?", "Last time a document was left unsaved. Restore it?"))) {
            long m = read_file("autosave.vpd");
            if (m > 0 && load_vpd(m)) {
                char p[256] = "";
                if (vx_read("autosave.pth", p, sizeof p - 1) > 0) {
                    p[sizeof p - 1] = 0;
                    scpy(path, p, sizeof path);
                }
                dirty = auto_dirty = 1;
                cur = 0;
                pick_style();
            }
        } else
            autosave_clear();
        layout();
    }
    long blink = vx_ms();
    for (;;) {
        int any = 0;
        for (;;) {
            long r = vx_sys(3, 0, 0, 0);
            if (r < 0)
                break;
            int k = (int)(r & 0xFFFF), mods = (int)(r >> 16 & 0xFF);
            if (!k)
                continue;
            if (font_ok)
                key(k, mods);
            else if (k == VK_ESC)
                vx_exit();
            any = 1;
            if (changed) {
                layout();
                changed = 0;
                auto_dirty = 1;
            }
        }
        long now = vx_ms();
        if (any) {
            caret_on = 1;
            blink = now;
        } else if (now - blink >= 530) {
            caret_on = !caret_on;
            blink = now;
        }
        if (font_ok)
            autosave(0);
        draw();
        vx_wait(530 - (vx_ms() - blink) > 20 ? 530 - (vx_ms() - blink) : 20);
    }
}
