JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Support the DECSCUSR CSI escape sequence
[st.git] / st.c
1 /* See LICENSE for licence details. */
2 #include <ctype.h>
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <limits.h>
6 #include <locale.h>
7 #include <pwd.h>
8 #include <stdarg.h>
9 #include <stdbool.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <signal.h>
14 #include <stdint.h>
15 #include <sys/ioctl.h>
16 #include <sys/select.h>
17 #include <sys/stat.h>
18 #include <sys/time.h>
19 #include <sys/types.h>
20 #include <sys/wait.h>
21 #include <time.h>
22 #include <unistd.h>
23 #include <libgen.h>
24 #include <X11/Xatom.h>
25 #include <X11/Xlib.h>
26 #include <X11/Xutil.h>
27 #include <X11/cursorfont.h>
28 #include <X11/keysym.h>
29 #include <X11/Xft/Xft.h>
30 #include <X11/XKBlib.h>
31 #include <fontconfig/fontconfig.h>
32 #include <wchar.h>
33
34 #include "arg.h"
35
36 char *argv0;
37
38 #define Glyph Glyph_
39 #define Font Font_
40
41 #if   defined(__linux)
42  #include <pty.h>
43 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
44  #include <util.h>
45 #elif defined(__FreeBSD__) || defined(__DragonFly__)
46  #include <libutil.h>
47 #endif
48
49
50 /* XEMBED messages */
51 #define XEMBED_FOCUS_IN  4
52 #define XEMBED_FOCUS_OUT 5
53
54 /* Arbitrary sizes */
55 #define UTF_INVALID   0xFFFD
56 #define UTF_SIZ       4
57 #define ESC_BUF_SIZ   (128*UTF_SIZ)
58 #define ESC_ARG_SIZ   16
59 #define STR_BUF_SIZ   ESC_BUF_SIZ
60 #define STR_ARG_SIZ   ESC_ARG_SIZ
61 #define DRAW_BUF_SIZ  20*1024
62 #define XK_ANY_MOD    UINT_MAX
63 #define XK_NO_MOD     0
64 #define XK_SWITCH_MOD (1<<13)
65
66 /* macros */
67 #define MIN(a, b)  ((a) < (b) ? (a) : (b))
68 #define MAX(a, b)  ((a) < (b) ? (b) : (a))
69 #define LEN(a)     (sizeof(a) / sizeof(a)[0])
70 #define DEFAULT(a, b)     (a) = (a) ? (a) : (b)
71 #define BETWEEN(x, a, b)  ((a) <= (x) && (x) <= (b))
72 #define ISCONTROLC0(c) (BETWEEN(c, 0, 0x1f) || (c) == '\177')
73 #define ISCONTROLC1(c) (BETWEEN(c, 0x80, 0x9f))
74 #define ISCONTROL(c) (ISCONTROLC0(c) || ISCONTROLC1(c))
75 #define LIMIT(x, a, b)    (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
76 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
77 #define IS_SET(flag) ((term.mode & (flag)) != 0)
78 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_nsec-t2.tv_nsec)/1E6)
79 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
80
81 #define TRUECOLOR(r,g,b) (1 << 24 | (r) << 16 | (g) << 8 | (b))
82 #define IS_TRUECOL(x)    (1 << 24 & (x))
83 #define TRUERED(x)       (((x) & 0xff0000) >> 8)
84 #define TRUEGREEN(x)     (((x) & 0xff00))
85 #define TRUEBLUE(x)      (((x) & 0xff) << 8)
86
87
88 enum glyph_attribute {
89         ATTR_NULL      = 0,
90         ATTR_BOLD      = 1 << 0,
91         ATTR_FAINT     = 1 << 1,
92         ATTR_ITALIC    = 1 << 2,
93         ATTR_UNDERLINE = 1 << 3,
94         ATTR_BLINK     = 1 << 4,
95         ATTR_REVERSE   = 1 << 5,
96         ATTR_INVISIBLE = 1 << 6,
97         ATTR_STRUCK    = 1 << 7,
98         ATTR_WRAP      = 1 << 8,
99         ATTR_WIDE      = 1 << 9,
100         ATTR_WDUMMY    = 1 << 10,
101 };
102
103 enum cursor_movement {
104         CURSOR_SAVE,
105         CURSOR_LOAD
106 };
107
108 enum cursor_state {
109         CURSOR_DEFAULT  = 0,
110         CURSOR_WRAPNEXT = 1,
111         CURSOR_ORIGIN   = 2
112 };
113
114 enum term_mode {
115         MODE_WRAP        = 1 << 0,
116         MODE_INSERT      = 1 << 1,
117         MODE_APPKEYPAD   = 1 << 2,
118         MODE_ALTSCREEN   = 1 << 3,
119         MODE_CRLF        = 1 << 4,
120         MODE_MOUSEBTN    = 1 << 5,
121         MODE_MOUSEMOTION = 1 << 6,
122         MODE_REVERSE     = 1 << 7,
123         MODE_KBDLOCK     = 1 << 8,
124         MODE_HIDE        = 1 << 9,
125         MODE_ECHO        = 1 << 10,
126         MODE_APPCURSOR   = 1 << 11,
127         MODE_MOUSESGR    = 1 << 12,
128         MODE_8BIT        = 1 << 13,
129         MODE_BLINK       = 1 << 14,
130         MODE_FBLINK      = 1 << 15,
131         MODE_FOCUS       = 1 << 16,
132         MODE_MOUSEX10    = 1 << 17,
133         MODE_MOUSEMANY   = 1 << 18,
134         MODE_BRCKTPASTE  = 1 << 19,
135         MODE_PRINT       = 1 << 20,
136         MODE_MOUSE       = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
137                           |MODE_MOUSEMANY,
138 };
139
140 enum charset {
141         CS_GRAPHIC0,
142         CS_GRAPHIC1,
143         CS_UK,
144         CS_USA,
145         CS_MULTI,
146         CS_GER,
147         CS_FIN
148 };
149
150 enum escape_state {
151         ESC_START      = 1,
152         ESC_CSI        = 2,
153         ESC_STR        = 4,  /* DCS, OSC, PM, APC */
154         ESC_ALTCHARSET = 8,
155         ESC_STR_END    = 16, /* a final string was encountered */
156         ESC_TEST       = 32, /* Enter in test mode */
157 };
158
159 enum window_state {
160         WIN_VISIBLE = 1,
161         WIN_REDRAW  = 2,
162         WIN_FOCUSED = 4
163 };
164
165 enum selection_type {
166         SEL_REGULAR = 1,
167         SEL_RECTANGULAR = 2
168 };
169
170 enum selection_snap {
171         SNAP_WORD = 1,
172         SNAP_LINE = 2
173 };
174
175 typedef unsigned char uchar;
176 typedef unsigned int uint;
177 typedef unsigned long ulong;
178 typedef unsigned short ushort;
179
180 typedef XftDraw *Draw;
181 typedef XftColor Color;
182
183 typedef struct {
184         char c[UTF_SIZ]; /* character code */
185         ushort mode;      /* attribute flags */
186         uint32_t fg;      /* foreground  */
187         uint32_t bg;      /* background  */
188 } Glyph;
189
190 typedef Glyph *Line;
191
192 typedef struct {
193         Glyph attr; /* current char attributes */
194         int x;
195         int y;
196         char state;
197 } TCursor;
198
199 /* CSI Escape sequence structs */
200 /* ESC '[' [[ [<priv>] <arg> [;]] <mode> [<mode>]] */
201 typedef struct {
202         char buf[ESC_BUF_SIZ]; /* raw string */
203         int len;               /* raw string length */
204         char priv;
205         int arg[ESC_ARG_SIZ];
206         int narg;              /* nb of args */
207         char mode[2];
208 } CSIEscape;
209
210 /* STR Escape sequence structs */
211 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
212 typedef struct {
213         char type;             /* ESC type ... */
214         char buf[STR_BUF_SIZ]; /* raw string */
215         int len;               /* raw string length */
216         char *args[STR_ARG_SIZ];
217         int narg;              /* nb of args */
218 } STREscape;
219
220 /* Internal representation of the screen */
221 typedef struct {
222         int row;      /* nb row */
223         int col;      /* nb col */
224         Line *line;   /* screen */
225         Line *alt;    /* alternate screen */
226         bool *dirty;  /* dirtyness of lines */
227         TCursor c;    /* cursor */
228         int top;      /* top    scroll limit */
229         int bot;      /* bottom scroll limit */
230         int mode;     /* terminal mode flags */
231         int esc;      /* escape state flags */
232         char trantbl[4]; /* charset table translation */
233         int charset;  /* current charset */
234         int icharset; /* selected charset for sequence */
235         bool numlock; /* lock numbers in keyboard */
236         bool *tabs;
237 } Term;
238
239 /* Purely graphic info */
240 typedef struct {
241         Display *dpy;
242         Colormap cmap;
243         Window win;
244         Drawable buf;
245         Atom xembed, wmdeletewin, netwmname, netwmpid;
246         XIM xim;
247         XIC xic;
248         Draw draw;
249         Visual *vis;
250         XSetWindowAttributes attrs;
251         int scr;
252         bool isfixed; /* is fixed geometry? */
253         int l, t; /* left and top offset */
254         int gm; /* geometry mask */
255         int tw, th; /* tty width and height */
256         int w, h; /* window width and height */
257         int ch; /* char height */
258         int cw; /* char width  */
259         char state; /* focus, redraw, visible */
260         int cursor; /* cursor style */
261 } XWindow;
262
263 typedef struct {
264         uint b;
265         uint mask;
266         char *s;
267 } Mousekey;
268
269 typedef struct {
270         KeySym k;
271         uint mask;
272         char *s;
273         /* three valued logic variables: 0 indifferent, 1 on, -1 off */
274         signed char appkey;    /* application keypad */
275         signed char appcursor; /* application cursor */
276         signed char crlf;      /* crlf mode          */
277 } Key;
278
279 typedef struct {
280         int mode;
281         int type;
282         int snap;
283         /*
284          * Selection variables:
285          * nb – normalized coordinates of the beginning of the selection
286          * ne – normalized coordinates of the end of the selection
287          * ob – original coordinates of the beginning of the selection
288          * oe – original coordinates of the end of the selection
289          */
290         struct {
291                 int x, y;
292         } nb, ne, ob, oe;
293
294         char *primary, *clipboard;
295         Atom xtarget;
296         bool alt;
297         struct timespec tclick1;
298         struct timespec tclick2;
299 } Selection;
300
301 typedef union {
302         int i;
303         uint ui;
304         float f;
305         const void *v;
306 } Arg;
307
308 typedef struct {
309         uint mod;
310         KeySym keysym;
311         void (*func)(const Arg *);
312         const Arg arg;
313 } Shortcut;
314
315 /* function definitions used in config.h */
316 static void clipcopy(const Arg *);
317 static void clippaste(const Arg *);
318 static void numlock(const Arg *);
319 static void selpaste(const Arg *);
320 static void xzoom(const Arg *);
321 static void xzoomabs(const Arg *);
322 static void xzoomreset(const Arg *);
323 static void printsel(const Arg *);
324 static void printscreen(const Arg *) ;
325 static void toggleprinter(const Arg *);
326
327 /* Config.h for applying patches and the configuration. */
328 #include "config.h"
329
330 /* Font structure */
331 typedef struct {
332         int height;
333         int width;
334         int ascent;
335         int descent;
336         short lbearing;
337         short rbearing;
338         XftFont *match;
339         FcFontSet *set;
340         FcPattern *pattern;
341 } Font;
342
343 /* Drawing Context */
344 typedef struct {
345         Color col[MAX(LEN(colorname), 256)];
346         Font font, bfont, ifont, ibfont;
347         GC gc;
348 } DC;
349
350 static void die(const char *, ...);
351 static void draw(void);
352 static void redraw(void);
353 static void drawregion(int, int, int, int);
354 static void execsh(void);
355 static void sigchld(int);
356 static void run(void);
357
358 static void csidump(void);
359 static void csihandle(void);
360 static void csiparse(void);
361 static void csireset(void);
362 static int eschandle(uchar ascii);
363 static void strdump(void);
364 static void strhandle(void);
365 static void strparse(void);
366 static void strreset(void);
367
368 static int tattrset(int);
369 static void tprinter(char *, size_t);
370 static void tdumpsel(void);
371 static void tdumpline(int);
372 static void tdump(void);
373 static void tclearregion(int, int, int, int);
374 static void tcursor(int);
375 static void tdeletechar(int);
376 static void tdeleteline(int);
377 static void tinsertblank(int);
378 static void tinsertblankline(int);
379 static int tlinelen(int);
380 static void tmoveto(int, int);
381 static void tmoveato(int, int);
382 static void tnew(int, int);
383 static void tnewline(int);
384 static void tputtab(int);
385 static void tputc(char *, int);
386 static void treset(void);
387 static void tresize(int, int);
388 static void tscrollup(int, int);
389 static void tscrolldown(int, int);
390 static void tsetattr(int *, int);
391 static void tsetchar(char *, Glyph *, int, int);
392 static void tsetscroll(int, int);
393 static void tswapscreen(void);
394 static void tsetdirt(int, int);
395 static void tsetdirtattr(int);
396 static void tsetmode(bool, bool, int *, int);
397 static void tfulldirt(void);
398 static void techo(char *, int);
399 static void tcontrolcode(uchar );
400 static void tdectest(char );
401 static int32_t tdefcolor(int *, int *, int);
402 static void tdeftran(char);
403 static inline bool match(uint, uint);
404 static void ttynew(void);
405 static void ttyread(void);
406 static void ttyresize(void);
407 static void ttysend(char *, size_t);
408 static void ttywrite(const char *, size_t);
409 static void tstrsequence(uchar c);
410
411 static void xdraws(char *, Glyph, int, int, int, int);
412 static void xhints(void);
413 static void xclear(int, int, int, int);
414 static void xdrawcursor(void);
415 static void xinit(void);
416 static void xloadcols(void);
417 static int xsetcolorname(int, const char *);
418 static int xgeommasktogravity(int);
419 static int xloadfont(Font *, FcPattern *);
420 static void xloadfonts(char *, double);
421 static int xloadfontset(Font *);
422 static void xsettitle(char *);
423 static void xresettitle(void);
424 static void xsetpointermotion(int);
425 static void xseturgency(int);
426 static void xsetsel(char *);
427 static void xtermclear(int, int, int, int);
428 static void xunloadfont(Font *);
429 static void xunloadfonts(void);
430 static void xresize(int, int);
431
432 static void expose(XEvent *);
433 static void visibility(XEvent *);
434 static void unmap(XEvent *);
435 static char *kmap(KeySym, uint);
436 static void kpress(XEvent *);
437 static void cmessage(XEvent *);
438 static void cresize(int, int);
439 static void resize(XEvent *);
440 static void focus(XEvent *);
441 static void brelease(XEvent *);
442 static void bpress(XEvent *);
443 static void bmotion(XEvent *);
444 static void selnotify(XEvent *);
445 static void selclear(XEvent *);
446 static void selrequest(XEvent *);
447
448 static void selinit(void);
449 static void selnormalize(void);
450 static inline bool selected(int, int);
451 static char *getsel(void);
452 static void selcopy(void);
453 static void selscroll(int, int);
454 static void selsnap(int, int *, int *, int);
455 static void getbuttoninfo(XEvent *);
456 static void mousereport(XEvent *);
457
458 static size_t utf8decode(char *, long *, size_t);
459 static long utf8decodebyte(char, size_t *);
460 static size_t utf8encode(long, char *, size_t);
461 static char utf8encodebyte(long, size_t);
462 static size_t utf8len(char *);
463 static size_t utf8validate(long *, size_t);
464
465 static ssize_t xwrite(int, const char *, size_t);
466 static void *xmalloc(size_t);
467 static void *xrealloc(void *, size_t);
468 static char *xstrdup(char *);
469
470 static void usage(void);
471
472 static void (*handler[LASTEvent])(XEvent *) = {
473         [KeyPress] = kpress,
474         [ClientMessage] = cmessage,
475         [ConfigureNotify] = resize,
476         [VisibilityNotify] = visibility,
477         [UnmapNotify] = unmap,
478         [Expose] = expose,
479         [FocusIn] = focus,
480         [FocusOut] = focus,
481         [MotionNotify] = bmotion,
482         [ButtonPress] = bpress,
483         [ButtonRelease] = brelease,
484 /*
485  * Uncomment if you want the selection to disappear when you select something
486  * different in another window.
487  */
488 /*      [SelectionClear] = selclear, */
489         [SelectionNotify] = selnotify,
490         [SelectionRequest] = selrequest,
491 };
492
493 /* Globals */
494 static DC dc;
495 static XWindow xw;
496 static Term term;
497 static CSIEscape csiescseq;
498 static STREscape strescseq;
499 static int cmdfd;
500 static pid_t pid;
501 static Selection sel;
502 static int iofd = STDOUT_FILENO;
503 static char **opt_cmd = NULL;
504 static char *opt_io = NULL;
505 static char *opt_title = NULL;
506 static char *opt_embed = NULL;
507 static char *opt_class = NULL;
508 static char *opt_font = NULL;
509 static int oldbutton = 3; /* button event on startup: 3 = release */
510
511 static char *usedfont = NULL;
512 static double usedfontsize = 0;
513 static double defaultfontsize = 0;
514
515 static uchar utfbyte[UTF_SIZ + 1] = {0x80,    0, 0xC0, 0xE0, 0xF0};
516 static uchar utfmask[UTF_SIZ + 1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
517 static long utfmin[UTF_SIZ + 1] = {       0,    0,  0x80,  0x800,  0x10000};
518 static long utfmax[UTF_SIZ + 1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
519
520 /* Font Ring Cache */
521 enum {
522         FRC_NORMAL,
523         FRC_ITALIC,
524         FRC_BOLD,
525         FRC_ITALICBOLD
526 };
527
528 typedef struct {
529         XftFont *font;
530         int flags;
531         long unicodep;
532 } Fontcache;
533
534 /* Fontcache is an array now. A new font will be appended to the array. */
535 static Fontcache frc[16];
536 static int frclen = 0;
537
538 ssize_t
539 xwrite(int fd, const char *s, size_t len) {
540         size_t aux = len;
541
542         while(len > 0) {
543                 ssize_t r = write(fd, s, len);
544                 if(r < 0)
545                         return r;
546                 len -= r;
547                 s += r;
548         }
549         return aux;
550 }
551
552 void *
553 xmalloc(size_t len) {
554         void *p = malloc(len);
555
556         if(!p)
557                 die("Out of memory\n");
558
559         return p;
560 }
561
562 void *
563 xrealloc(void *p, size_t len) {
564         if((p = realloc(p, len)) == NULL)
565                 die("Out of memory\n");
566
567         return p;
568 }
569
570 char *
571 xstrdup(char *s) {
572         if((s = strdup(s)) == NULL)
573                 die("Out of memory\n");
574
575         return s;
576 }
577
578 size_t
579 utf8decode(char *c, long *u, size_t clen) {
580         size_t i, j, len, type;
581         long udecoded;
582
583         *u = UTF_INVALID;
584         if(!clen)
585                 return 0;
586         udecoded = utf8decodebyte(c[0], &len);
587         if(!BETWEEN(len, 1, UTF_SIZ))
588                 return 1;
589         for(i = 1, j = 1; i < clen && j < len; ++i, ++j) {
590                 udecoded = (udecoded << 6) | utf8decodebyte(c[i], &type);
591                 if(type != 0)
592                         return j;
593         }
594         if(j < len)
595                 return 0;
596         *u = udecoded;
597         utf8validate(u, len);
598         return len;
599 }
600
601 long
602 utf8decodebyte(char c, size_t *i) {
603         for(*i = 0; *i < LEN(utfmask); ++(*i))
604                 if(((uchar)c & utfmask[*i]) == utfbyte[*i])
605                         return (uchar)c & ~utfmask[*i];
606         return 0;
607 }
608
609 size_t
610 utf8encode(long u, char *c, size_t clen) {
611         size_t len, i;
612
613         len = utf8validate(&u, 0);
614         if(clen < len)
615                 return 0;
616         for(i = len - 1; i != 0; --i) {
617                 c[i] = utf8encodebyte(u, 0);
618                 u >>= 6;
619         }
620         c[0] = utf8encodebyte(u, len);
621         return len;
622 }
623
624 char
625 utf8encodebyte(long u, size_t i) {
626         return utfbyte[i] | (u & ~utfmask[i]);
627 }
628
629 size_t
630 utf8len(char *c) {
631         return utf8decode(c, &(long){0}, UTF_SIZ);
632 }
633
634 size_t
635 utf8validate(long *u, size_t i) {
636         if(!BETWEEN(*u, utfmin[i], utfmax[i]) || BETWEEN(*u, 0xD800, 0xDFFF))
637                 *u = UTF_INVALID;
638         for(i = 1; *u > utfmax[i]; ++i)
639                 ;
640         return i;
641 }
642
643 static void
644 selinit(void) {
645         memset(&sel.tclick1, 0, sizeof(sel.tclick1));
646         memset(&sel.tclick2, 0, sizeof(sel.tclick2));
647         sel.mode = 0;
648         sel.ob.x = -1;
649         sel.primary = NULL;
650         sel.clipboard = NULL;
651         sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
652         if(sel.xtarget == None)
653                 sel.xtarget = XA_STRING;
654 }
655
656 static int
657 x2col(int x) {
658         x -= borderpx;
659         x /= xw.cw;
660
661         return LIMIT(x, 0, term.col-1);
662 }
663
664 static int
665 y2row(int y) {
666         y -= borderpx;
667         y /= xw.ch;
668
669         return LIMIT(y, 0, term.row-1);
670 }
671
672 static int tlinelen(int y) {
673         int i = term.col;
674
675         if(term.line[y][i - 1].mode & ATTR_WRAP)
676                 return i;
677
678         while(i > 0 && term.line[y][i - 1].c[0] == ' ')
679                 --i;
680
681         return i;
682 }
683
684 static void
685 selnormalize(void) {
686         int i;
687
688         if(sel.ob.y == sel.oe.y || sel.type == SEL_RECTANGULAR) {
689                 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
690                 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
691         } else {
692                 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
693                 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
694         }
695         sel.nb.y = MIN(sel.ob.y, sel.oe.y);
696         sel.ne.y = MAX(sel.ob.y, sel.oe.y);
697
698         selsnap(sel.snap, &sel.nb.x, &sel.nb.y, -1);
699         selsnap(sel.snap, &sel.ne.x, &sel.ne.y, +1);
700
701         /* expand selection over line breaks */
702         if (sel.type == SEL_RECTANGULAR)
703                 return;
704         i = tlinelen(sel.nb.y);
705         if (i < sel.nb.x)
706                 sel.nb.x = i;
707         if (tlinelen(sel.ne.y) <= sel.ne.x)
708                 sel.ne.x = term.col - 1;
709 }
710
711 static inline bool
712 selected(int x, int y) {
713         if(sel.type == SEL_RECTANGULAR)
714                 return BETWEEN(y, sel.nb.y, sel.ne.y)
715                     && BETWEEN(x, sel.nb.x, sel.ne.x);
716
717         return BETWEEN(y, sel.nb.y, sel.ne.y)
718             && (y != sel.nb.y || x >= sel.nb.x)
719             && (y != sel.ne.y || x <= sel.ne.x);
720 }
721
722 void
723 selsnap(int mode, int *x, int *y, int direction) {
724         int newx, newy, xt, yt;
725         bool delim, prevdelim;
726         Glyph *gp, *prevgp;
727
728         switch(mode) {
729         case SNAP_WORD:
730                 /*
731                  * Snap around if the word wraps around at the end or
732                  * beginning of a line.
733                  */
734                 prevgp = &term.line[*y][*x];
735                 prevdelim = strchr(worddelimiters, prevgp->c[0]) != NULL;
736                 for(;;) {
737                         newx = *x + direction;
738                         newy = *y;
739                         if(!BETWEEN(newx, 0, term.col - 1)) {
740                                 newy += direction;
741                                 newx = (newx + term.col) % term.col;
742                                 if (!BETWEEN(newy, 0, term.row - 1))
743                                         break;
744
745                                 if(direction > 0)
746                                         yt = *y, xt = *x;
747                                 else
748                                         yt = newy, xt = newx;
749                                 if(!(term.line[yt][xt].mode & ATTR_WRAP))
750                                         break;
751                         }
752
753                         if (newx >= tlinelen(newy))
754                                 break;
755
756                         gp = &term.line[newy][newx];
757                         delim = strchr(worddelimiters, gp->c[0]) != NULL;
758                         if(!(gp->mode & ATTR_WDUMMY) && (delim != prevdelim
759                                         || (delim && gp->c[0] != prevgp->c[0])))
760                                 break;
761
762                         *x = newx;
763                         *y = newy;
764                         prevgp = gp;
765                         prevdelim = delim;
766                 }
767                 break;
768         case SNAP_LINE:
769                 /*
770                  * Snap around if the the previous line or the current one
771                  * has set ATTR_WRAP at its end. Then the whole next or
772                  * previous line will be selected.
773                  */
774                 *x = (direction < 0) ? 0 : term.col - 1;
775                 if(direction < 0 && *y > 0) {
776                         for(; *y > 0; *y += direction) {
777                                 if(!(term.line[*y-1][term.col-1].mode
778                                                 & ATTR_WRAP)) {
779                                         break;
780                                 }
781                         }
782                 } else if(direction > 0 && *y < term.row-1) {
783                         for(; *y < term.row; *y += direction) {
784                                 if(!(term.line[*y][term.col-1].mode
785                                                 & ATTR_WRAP)) {
786                                         break;
787                                 }
788                         }
789                 }
790                 break;
791         }
792 }
793
794 void
795 getbuttoninfo(XEvent *e) {
796         int type;
797         uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
798
799         sel.alt = IS_SET(MODE_ALTSCREEN);
800
801         sel.oe.x = x2col(e->xbutton.x);
802         sel.oe.y = y2row(e->xbutton.y);
803         selnormalize();
804
805         sel.type = SEL_REGULAR;
806         for(type = 1; type < LEN(selmasks); ++type) {
807                 if(match(selmasks[type], state)) {
808                         sel.type = type;
809                         break;
810                 }
811         }
812 }
813
814 void
815 mousereport(XEvent *e) {
816         int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
817             button = e->xbutton.button, state = e->xbutton.state,
818             len;
819         char buf[40];
820         static int ox, oy;
821
822         /* from urxvt */
823         if(e->xbutton.type == MotionNotify) {
824                 if(x == ox && y == oy)
825                         return;
826                 if(!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
827                         return;
828                 /* MOUSE_MOTION: no reporting if no button is pressed */
829                 if(IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
830                         return;
831
832                 button = oldbutton + 32;
833                 ox = x;
834                 oy = y;
835         } else {
836                 if(!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
837                         button = 3;
838                 } else {
839                         button -= Button1;
840                         if(button >= 3)
841                                 button += 64 - 3;
842                 }
843                 if(e->xbutton.type == ButtonPress) {
844                         oldbutton = button;
845                         ox = x;
846                         oy = y;
847                 } else if(e->xbutton.type == ButtonRelease) {
848                         oldbutton = 3;
849                         /* MODE_MOUSEX10: no button release reporting */
850                         if(IS_SET(MODE_MOUSEX10))
851                                 return;
852                         if (button == 64 || button == 65)
853                                 return;
854                 }
855         }
856
857         if(!IS_SET(MODE_MOUSEX10)) {
858                 button += (state & ShiftMask   ? 4  : 0)
859                         + (state & Mod4Mask    ? 8  : 0)
860                         + (state & ControlMask ? 16 : 0);
861         }
862
863         len = 0;
864         if(IS_SET(MODE_MOUSESGR)) {
865                 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
866                                 button, x+1, y+1,
867                                 e->xbutton.type == ButtonRelease ? 'm' : 'M');
868         } else if(x < 223 && y < 223) {
869                 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
870                                 32+button, 32+x+1, 32+y+1);
871         } else {
872                 return;
873         }
874
875         ttywrite(buf, len);
876 }
877
878 void
879 bpress(XEvent *e) {
880         struct timespec now;
881         Mousekey *mk;
882
883         if(IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
884                 mousereport(e);
885                 return;
886         }
887
888         for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
889                 if(e->xbutton.button == mk->b
890                                 && match(mk->mask, e->xbutton.state)) {
891                         ttysend(mk->s, strlen(mk->s));
892                         return;
893                 }
894         }
895
896         if(e->xbutton.button == Button1) {
897                 clock_gettime(CLOCK_MONOTONIC, &now);
898
899                 /* Clear previous selection, logically and visually. */
900                 selclear(NULL);
901                 sel.mode = 1;
902                 sel.type = SEL_REGULAR;
903                 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
904                 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
905
906                 /*
907                  * If the user clicks below predefined timeouts specific
908                  * snapping behaviour is exposed.
909                  */
910                 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
911                         sel.snap = SNAP_LINE;
912                 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
913                         sel.snap = SNAP_WORD;
914                 } else {
915                         sel.snap = 0;
916                 }
917                 selnormalize();
918
919                 /*
920                  * Draw selection, unless it's regular and we don't want to
921                  * make clicks visible
922                  */
923                 if(sel.snap != 0) {
924                         sel.mode++;
925                         tsetdirt(sel.nb.y, sel.ne.y);
926                 }
927                 sel.tclick2 = sel.tclick1;
928                 sel.tclick1 = now;
929         }
930 }
931
932 char *
933 getsel(void) {
934         char *str, *ptr;
935         int y, bufsize, size, lastx, linelen;
936         Glyph *gp, *last;
937
938         if(sel.ob.x == -1)
939                 return NULL;
940
941         bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
942         ptr = str = xmalloc(bufsize);
943
944         /* append every set & selected glyph to the selection */
945         for(y = sel.nb.y; y < sel.ne.y + 1; y++) {
946                 linelen = tlinelen(y);
947
948                 if(sel.type == SEL_RECTANGULAR) {
949                         gp = &term.line[y][sel.nb.x];
950                         lastx = sel.ne.x;
951                 } else {
952                         gp = &term.line[y][sel.nb.y == y ? sel.nb.x : 0];
953                         lastx = (sel.ne.y == y) ? sel.ne.x : term.col-1;
954                 }
955                 last = &term.line[y][MIN(lastx, linelen-1)];
956                 while(last >= gp && last->c[0] == ' ')
957                         --last;
958
959                 for( ; gp <= last; ++gp) {
960                         if(gp->mode & ATTR_WDUMMY)
961                                 continue;
962
963                         size = utf8len(gp->c);
964                         memcpy(ptr, gp->c, size);
965                         ptr += size;
966                 }
967
968                 /*
969                  * Copy and pasting of line endings is inconsistent
970                  * in the inconsistent terminal and GUI world.
971                  * The best solution seems like to produce '\n' when
972                  * something is copied from st and convert '\n' to
973                  * '\r', when something to be pasted is received by
974                  * st.
975                  * FIXME: Fix the computer world.
976                  */
977                 if((y < sel.ne.y || lastx >= linelen) && !(last->mode & ATTR_WRAP))
978                         *ptr++ = '\n';
979         }
980         *ptr = 0;
981         return str;
982 }
983
984 void
985 selcopy(void) {
986         xsetsel(getsel());
987 }
988
989 void
990 selnotify(XEvent *e) {
991         ulong nitems, ofs, rem;
992         int format;
993         uchar *data, *last, *repl;
994         Atom type;
995         XSelectionEvent *xsev;
996
997         ofs = 0;
998         xsev = (XSelectionEvent *)e;
999         do {
1000                 if(XGetWindowProperty(xw.dpy, xw.win, xsev->property, ofs,
1001                                         BUFSIZ/4, False, AnyPropertyType,
1002                                         &type, &format, &nitems, &rem,
1003                                         &data)) {
1004                         fprintf(stderr, "Clipboard allocation failed\n");
1005                         return;
1006                 }
1007
1008                 /*
1009                  * As seen in getsel:
1010                  * Line endings are inconsistent in the terminal and GUI world
1011                  * copy and pasting. When receiving some selection data,
1012                  * replace all '\n' with '\r'.
1013                  * FIXME: Fix the computer world.
1014                  */
1015                 repl = data;
1016                 last = data + nitems * format / 8;
1017                 while((repl = memchr(repl, '\n', last - repl))) {
1018                         *repl++ = '\r';
1019                 }
1020
1021                 if(IS_SET(MODE_BRCKTPASTE))
1022                         ttywrite("\033[200~", 6);
1023                 ttysend((char *)data, nitems * format / 8);
1024                 if(IS_SET(MODE_BRCKTPASTE))
1025                         ttywrite("\033[201~", 6);
1026                 XFree(data);
1027                 /* number of 32-bit chunks returned */
1028                 ofs += nitems * format / 32;
1029         } while(rem > 0);
1030 }
1031
1032 void
1033 selpaste(const Arg *dummy) {
1034         XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1035                         xw.win, CurrentTime);
1036 }
1037
1038 void
1039 clipcopy(const Arg *dummy) {
1040         Atom clipboard;
1041
1042         if(sel.clipboard != NULL)
1043                 free(sel.clipboard);
1044
1045         if(sel.primary != NULL) {
1046                 sel.clipboard = xstrdup(sel.primary);
1047                 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1048                 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1049         }
1050 }
1051
1052 void
1053 clippaste(const Arg *dummy) {
1054         Atom clipboard;
1055
1056         clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1057         XConvertSelection(xw.dpy, clipboard, sel.xtarget, clipboard,
1058                         xw.win, CurrentTime);
1059 }
1060
1061 void
1062 selclear(XEvent *e) {
1063         if(sel.ob.x == -1)
1064                 return;
1065         sel.ob.x = -1;
1066         tsetdirt(sel.nb.y, sel.ne.y);
1067 }
1068
1069 void
1070 selrequest(XEvent *e) {
1071         XSelectionRequestEvent *xsre;
1072         XSelectionEvent xev;
1073         Atom xa_targets, string, clipboard;
1074         char *seltext;
1075
1076         xsre = (XSelectionRequestEvent *) e;
1077         xev.type = SelectionNotify;
1078         xev.requestor = xsre->requestor;
1079         xev.selection = xsre->selection;
1080         xev.target = xsre->target;
1081         xev.time = xsre->time;
1082         /* reject */
1083         xev.property = None;
1084
1085         xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1086         if(xsre->target == xa_targets) {
1087                 /* respond with the supported type */
1088                 string = sel.xtarget;
1089                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1090                                 XA_ATOM, 32, PropModeReplace,
1091                                 (uchar *) &string, 1);
1092                 xev.property = xsre->property;
1093         } else if(xsre->target == sel.xtarget || xsre->target == XA_STRING) {
1094                 /*
1095                  * xith XA_STRING non ascii characters may be incorrect in the
1096                  * requestor. It is not our problem, use utf8.
1097                  */
1098                 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1099                 if(xsre->selection == XA_PRIMARY) {
1100                         seltext = sel.primary;
1101                 } else if(xsre->selection == clipboard) {
1102                         seltext = sel.clipboard;
1103                 } else {
1104                         fprintf(stderr,
1105                                 "Unhandled clipboard selection 0x%lx\n",
1106                                 xsre->selection);
1107                         return;
1108                 }
1109                 if(seltext != NULL) {
1110                         XChangeProperty(xsre->display, xsre->requestor,
1111                                         xsre->property, xsre->target,
1112                                         8, PropModeReplace,
1113                                         (uchar *)seltext, strlen(seltext));
1114                         xev.property = xsre->property;
1115                 }
1116         }
1117
1118         /* all done, send a notification to the listener */
1119         if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
1120                 fprintf(stderr, "Error sending SelectionNotify event\n");
1121 }
1122
1123 void
1124 xsetsel(char *str) {
1125         free(sel.primary);
1126         sel.primary = str;
1127
1128         XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
1129 }
1130
1131 void
1132 brelease(XEvent *e) {
1133         if(IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
1134                 mousereport(e);
1135                 return;
1136         }
1137
1138         if(e->xbutton.button == Button2) {
1139                 selpaste(NULL);
1140         } else if(e->xbutton.button == Button1) {
1141                 if(sel.mode < 2) {
1142                         selclear(NULL);
1143                 } else {
1144                         getbuttoninfo(e);
1145                         selcopy();
1146                 }
1147                 sel.mode = 0;
1148                 tsetdirt(sel.nb.y, sel.ne.y);
1149         }
1150 }
1151
1152 void
1153 bmotion(XEvent *e) {
1154         int oldey, oldex, oldsby, oldsey;
1155
1156         if(IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
1157                 mousereport(e);
1158                 return;
1159         }
1160
1161         if(!sel.mode)
1162                 return;
1163
1164         sel.mode++;
1165         oldey = sel.oe.y;
1166         oldex = sel.oe.x;
1167         oldsby = sel.nb.y;
1168         oldsey = sel.ne.y;
1169         getbuttoninfo(e);
1170
1171         if(oldey != sel.oe.y || oldex != sel.oe.x)
1172                 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1173 }
1174
1175 void
1176 die(const char *errstr, ...) {
1177         va_list ap;
1178
1179         va_start(ap, errstr);
1180         vfprintf(stderr, errstr, ap);
1181         va_end(ap);
1182         exit(EXIT_FAILURE);
1183 }
1184
1185 void
1186 execsh(void) {
1187         char **args, *sh, *prog;
1188         const struct passwd *pw;
1189         char buf[sizeof(long) * 8 + 1];
1190
1191         errno = 0;
1192         if((pw = getpwuid(getuid())) == NULL) {
1193                 if(errno)
1194                         die("getpwuid:%s\n", strerror(errno));
1195                 else
1196                         die("who are you?\n");
1197         }
1198
1199         if (!(sh = getenv("SHELL"))) {
1200                 sh = (pw->pw_shell[0]) ? pw->pw_shell : shell;
1201         }
1202
1203         if(opt_cmd)
1204                 prog = opt_cmd[0];
1205         else if(utmp)
1206                 prog = utmp;
1207         else
1208                 prog = sh;
1209         args = (opt_cmd) ? opt_cmd : (char *[]) {prog, NULL};
1210
1211         snprintf(buf, sizeof(buf), "%lu", xw.win);
1212
1213         unsetenv("COLUMNS");
1214         unsetenv("LINES");
1215         unsetenv("TERMCAP");
1216         setenv("LOGNAME", pw->pw_name, 1);
1217         setenv("USER", pw->pw_name, 1);
1218         setenv("SHELL", sh, 1);
1219         setenv("HOME", pw->pw_dir, 1);
1220         setenv("TERM", termname, 1);
1221         setenv("WINDOWID", buf, 1);
1222
1223         signal(SIGCHLD, SIG_DFL);
1224         signal(SIGHUP, SIG_DFL);
1225         signal(SIGINT, SIG_DFL);
1226         signal(SIGQUIT, SIG_DFL);
1227         signal(SIGTERM, SIG_DFL);
1228         signal(SIGALRM, SIG_DFL);
1229
1230         execvp(prog, args);
1231         _exit(EXIT_FAILURE);
1232 }
1233
1234 void
1235 sigchld(int a) {
1236         int stat, ret;
1237
1238         if(waitpid(pid, &stat, 0) < 0)
1239                 die("Waiting for pid %hd failed: %s\n", pid, strerror(errno));
1240
1241         ret = WIFEXITED(stat) ? WEXITSTATUS(stat) : EXIT_FAILURE;
1242         if (ret != EXIT_SUCCESS)
1243                 die("child finished with error '%d'\n", stat);
1244         exit(EXIT_SUCCESS);
1245 }
1246
1247 void
1248 ttynew(void) {
1249         int m, s;
1250         struct winsize w = {term.row, term.col, 0, 0};
1251
1252         /* seems to work fine on linux, openbsd and freebsd */
1253         if(openpty(&m, &s, NULL, NULL, &w) < 0)
1254                 die("openpty failed: %s\n", strerror(errno));
1255
1256         switch(pid = fork()) {
1257         case -1:
1258                 die("fork failed\n");
1259                 break;
1260         case 0:
1261                 setsid(); /* create a new process group */
1262                 dup2(s, STDIN_FILENO);
1263                 dup2(s, STDOUT_FILENO);
1264                 dup2(s, STDERR_FILENO);
1265                 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1266                         die("ioctl TIOCSCTTY failed: %s\n", strerror(errno));
1267                 close(s);
1268                 close(m);
1269                 execsh();
1270                 break;
1271         default:
1272                 close(s);
1273                 cmdfd = m;
1274                 signal(SIGCHLD, sigchld);
1275                 if(opt_io) {
1276                         term.mode |= MODE_PRINT;
1277                         iofd = (!strcmp(opt_io, "-")) ?
1278                                   STDOUT_FILENO :
1279                                   open(opt_io, O_WRONLY | O_CREAT, 0666);
1280                         if(iofd < 0) {
1281                                 fprintf(stderr, "Error opening %s:%s\n",
1282                                         opt_io, strerror(errno));
1283                         }
1284                 }
1285                 break;
1286         }
1287 }
1288
1289 void
1290 ttyread(void) {
1291         static char buf[BUFSIZ];
1292         static int buflen = 0;
1293         char *ptr;
1294         char s[UTF_SIZ];
1295         int charsize; /* size of utf8 char in bytes */
1296         long unicodep;
1297         int ret;
1298
1299         /* append read bytes to unprocessed bytes */
1300         if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1301                 die("Couldn't read from shell: %s\n", strerror(errno));
1302
1303         /* process every complete utf8 char */
1304         buflen += ret;
1305         ptr = buf;
1306         while((charsize = utf8decode(ptr, &unicodep, buflen))) {
1307                 utf8encode(unicodep, s, UTF_SIZ);
1308                 tputc(s, charsize);
1309                 ptr += charsize;
1310                 buflen -= charsize;
1311         }
1312
1313         /* keep any uncomplete utf8 char for the next call */
1314         memmove(buf, ptr, buflen);
1315 }
1316
1317 void
1318 ttywrite(const char *s, size_t n) {
1319         if(xwrite(cmdfd, s, n) == -1)
1320                 die("write error on tty: %s\n", strerror(errno));
1321 }
1322
1323 void
1324 ttysend(char *s, size_t n) {
1325         ttywrite(s, n);
1326         if(IS_SET(MODE_ECHO))
1327                 techo(s, n);
1328 }
1329
1330 void
1331 ttyresize(void) {
1332         struct winsize w;
1333
1334         w.ws_row = term.row;
1335         w.ws_col = term.col;
1336         w.ws_xpixel = xw.tw;
1337         w.ws_ypixel = xw.th;
1338         if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1339                 fprintf(stderr, "Couldn't set window size: %s\n", strerror(errno));
1340 }
1341
1342 int
1343 tattrset(int attr) {
1344         int i, j;
1345
1346         for(i = 0; i < term.row-1; i++) {
1347                 for(j = 0; j < term.col-1; j++) {
1348                         if(term.line[i][j].mode & attr)
1349                                 return 1;
1350                 }
1351         }
1352
1353         return 0;
1354 }
1355
1356 void
1357 tsetdirt(int top, int bot) {
1358         int i;
1359
1360         LIMIT(top, 0, term.row-1);
1361         LIMIT(bot, 0, term.row-1);
1362
1363         for(i = top; i <= bot; i++)
1364                 term.dirty[i] = 1;
1365 }
1366
1367 void
1368 tsetdirtattr(int attr) {
1369         int i, j;
1370
1371         for(i = 0; i < term.row-1; i++) {
1372                 for(j = 0; j < term.col-1; j++) {
1373                         if(term.line[i][j].mode & attr) {
1374                                 tsetdirt(i, i);
1375                                 break;
1376                         }
1377                 }
1378         }
1379 }
1380
1381 void
1382 tfulldirt(void) {
1383         tsetdirt(0, term.row-1);
1384 }
1385
1386 void
1387 tcursor(int mode) {
1388         static TCursor c[2];
1389         bool alt = IS_SET(MODE_ALTSCREEN);
1390
1391         if(mode == CURSOR_SAVE) {
1392                 c[alt] = term.c;
1393         } else if(mode == CURSOR_LOAD) {
1394                 term.c = c[alt];
1395                 tmoveto(c[alt].x, c[alt].y);
1396         }
1397 }
1398
1399 void
1400 treset(void) {
1401         uint i;
1402
1403         term.c = (TCursor){{
1404                 .mode = ATTR_NULL,
1405                 .fg = defaultfg,
1406                 .bg = defaultbg
1407         }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1408
1409         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1410         for(i = tabspaces; i < term.col; i += tabspaces)
1411                 term.tabs[i] = 1;
1412         term.top = 0;
1413         term.bot = term.row - 1;
1414         term.mode = MODE_WRAP;
1415         memset(term.trantbl, sizeof(term.trantbl), CS_USA);
1416         term.charset = 0;
1417
1418         for(i = 0; i < 2; i++) {
1419                 tmoveto(0, 0);
1420                 tcursor(CURSOR_SAVE);
1421                 tclearregion(0, 0, term.col-1, term.row-1);
1422                 tswapscreen();
1423         }
1424 }
1425
1426 void
1427 tnew(int col, int row) {
1428         term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
1429         tresize(col, row);
1430         term.numlock = 1;
1431
1432         treset();
1433 }
1434
1435 void
1436 tswapscreen(void) {
1437         Line *tmp = term.line;
1438
1439         term.line = term.alt;
1440         term.alt = tmp;
1441         term.mode ^= MODE_ALTSCREEN;
1442         tfulldirt();
1443 }
1444
1445 void
1446 tscrolldown(int orig, int n) {
1447         int i;
1448         Line temp;
1449
1450         LIMIT(n, 0, term.bot-orig+1);
1451
1452         tsetdirt(orig, term.bot-n);
1453         tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1454
1455         for(i = term.bot; i >= orig+n; i--) {
1456                 temp = term.line[i];
1457                 term.line[i] = term.line[i-n];
1458                 term.line[i-n] = temp;
1459         }
1460
1461         selscroll(orig, n);
1462 }
1463
1464 void
1465 tscrollup(int orig, int n) {
1466         int i;
1467         Line temp;
1468
1469         LIMIT(n, 0, term.bot-orig+1);
1470
1471         tclearregion(0, orig, term.col-1, orig+n-1);
1472         tsetdirt(orig+n, term.bot);
1473
1474         for(i = orig; i <= term.bot-n; i++) {
1475                 temp = term.line[i];
1476                 term.line[i] = term.line[i+n];
1477                 term.line[i+n] = temp;
1478         }
1479
1480         selscroll(orig, -n);
1481 }
1482
1483 void
1484 selscroll(int orig, int n) {
1485         if(sel.ob.x == -1)
1486                 return;
1487
1488         if(BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1489                 if((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1490                         selclear(NULL);
1491                         return;
1492                 }
1493                 if(sel.type == SEL_RECTANGULAR) {
1494                         if(sel.ob.y < term.top)
1495                                 sel.ob.y = term.top;
1496                         if(sel.oe.y > term.bot)
1497                                 sel.oe.y = term.bot;
1498                 } else {
1499                         if(sel.ob.y < term.top) {
1500                                 sel.ob.y = term.top;
1501                                 sel.ob.x = 0;
1502                         }
1503                         if(sel.oe.y > term.bot) {
1504                                 sel.oe.y = term.bot;
1505                                 sel.oe.x = term.col;
1506                         }
1507                 }
1508                 selnormalize();
1509         }
1510 }
1511
1512 void
1513 tnewline(int first_col) {
1514         int y = term.c.y;
1515
1516         if(y == term.bot) {
1517                 tscrollup(term.top, 1);
1518         } else {
1519                 y++;
1520         }
1521         tmoveto(first_col ? 0 : term.c.x, y);
1522 }
1523
1524 void
1525 csiparse(void) {
1526         char *p = csiescseq.buf, *np;
1527         long int v;
1528
1529         csiescseq.narg = 0;
1530         if(*p == '?') {
1531                 csiescseq.priv = 1;
1532                 p++;
1533         }
1534
1535         csiescseq.buf[csiescseq.len] = '\0';
1536         while(p < csiescseq.buf+csiescseq.len) {
1537                 np = NULL;
1538                 v = strtol(p, &np, 10);
1539                 if(np == p)
1540                         v = 0;
1541                 if(v == LONG_MAX || v == LONG_MIN)
1542                         v = -1;
1543                 csiescseq.arg[csiescseq.narg++] = v;
1544                 p = np;
1545                 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1546                         break;
1547                 p++;
1548         }
1549         csiescseq.mode[0] = *p++;
1550         csiescseq.mode[1] = (p < csiescseq.buf+csiescseq.len) ? *p : '\0';
1551 }
1552
1553 /* for absolute user moves, when decom is set */
1554 void
1555 tmoveato(int x, int y) {
1556         tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1557 }
1558
1559 void
1560 tmoveto(int x, int y) {
1561         int miny, maxy;
1562
1563         if(term.c.state & CURSOR_ORIGIN) {
1564                 miny = term.top;
1565                 maxy = term.bot;
1566         } else {
1567                 miny = 0;
1568                 maxy = term.row - 1;
1569         }
1570         LIMIT(x, 0, term.col-1);
1571         LIMIT(y, miny, maxy);
1572         term.c.state &= ~CURSOR_WRAPNEXT;
1573         term.c.x = x;
1574         term.c.y = y;
1575 }
1576
1577 void
1578 tsetchar(char *c, Glyph *attr, int x, int y) {
1579         static char *vt100_0[62] = { /* 0x41 - 0x7e */
1580                 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1581                 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1582                 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1583                 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1584                 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1585                 "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1586                 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1587                 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1588         };
1589
1590         /*
1591          * The table is proudly stolen from rxvt.
1592          */
1593         if(term.trantbl[term.charset] == CS_GRAPHIC0) {
1594                 if(BETWEEN(c[0], 0x41, 0x7e) && vt100_0[c[0] - 0x41]) {
1595                         c = vt100_0[c[0] - 0x41];
1596                 }
1597         }
1598
1599         if(term.line[y][x].mode & ATTR_WIDE) {
1600                 if(x+1 < term.col) {
1601                         term.line[y][x+1].c[0] = ' ';
1602                         term.line[y][x+1].mode &= ~ATTR_WDUMMY;
1603                 }
1604         } else if(term.line[y][x].mode & ATTR_WDUMMY) {
1605                 term.line[y][x-1].c[0] = ' ';
1606                 term.line[y][x-1].mode &= ~ATTR_WIDE;
1607         }
1608
1609         term.dirty[y] = 1;
1610         term.line[y][x] = *attr;
1611         memcpy(term.line[y][x].c, c, UTF_SIZ);
1612 }
1613
1614 void
1615 tclearregion(int x1, int y1, int x2, int y2) {
1616         int x, y, temp;
1617         Glyph *gp;
1618
1619         if(x1 > x2)
1620                 temp = x1, x1 = x2, x2 = temp;
1621         if(y1 > y2)
1622                 temp = y1, y1 = y2, y2 = temp;
1623
1624         LIMIT(x1, 0, term.col-1);
1625         LIMIT(x2, 0, term.col-1);
1626         LIMIT(y1, 0, term.row-1);
1627         LIMIT(y2, 0, term.row-1);
1628
1629         for(y = y1; y <= y2; y++) {
1630                 term.dirty[y] = 1;
1631                 for(x = x1; x <= x2; x++) {
1632                         gp = &term.line[y][x];
1633                         if(selected(x, y))
1634                                 selclear(NULL);
1635                         gp->fg = term.c.attr.fg;
1636                         gp->bg = term.c.attr.bg;
1637                         gp->mode = 0;
1638                         memcpy(gp->c, " ", 2);
1639                 }
1640         }
1641 }
1642
1643 void
1644 tdeletechar(int n) {
1645         int dst, src, size;
1646         Glyph *line;
1647
1648         LIMIT(n, 0, term.col - term.c.x);
1649
1650         dst = term.c.x;
1651         src = term.c.x + n;
1652         size = term.col - src;
1653         line = term.line[term.c.y];
1654
1655         memmove(&line[dst], &line[src], size * sizeof(Glyph));
1656         tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1657 }
1658
1659 void
1660 tinsertblank(int n) {
1661         int dst, src, size;
1662         Glyph *line;
1663
1664         LIMIT(n, 0, term.col - term.c.x);
1665
1666         dst = term.c.x + n;
1667         src = term.c.x;
1668         size = term.col - dst;
1669         line = term.line[term.c.y];
1670
1671         memmove(&line[dst], &line[src], size * sizeof(Glyph));
1672         tclearregion(src, term.c.y, dst - 1, term.c.y);
1673 }
1674
1675 void
1676 tinsertblankline(int n) {
1677         if(BETWEEN(term.c.y, term.top, term.bot))
1678                 tscrolldown(term.c.y, n);
1679 }
1680
1681 void
1682 tdeleteline(int n) {
1683         if(BETWEEN(term.c.y, term.top, term.bot))
1684                 tscrollup(term.c.y, n);
1685 }
1686
1687 int32_t
1688 tdefcolor(int *attr, int *npar, int l) {
1689         int32_t idx = -1;
1690         uint r, g, b;
1691
1692         switch (attr[*npar + 1]) {
1693         case 2: /* direct color in RGB space */
1694                 if (*npar + 4 >= l) {
1695                         fprintf(stderr,
1696                                 "erresc(38): Incorrect number of parameters (%d)\n",
1697                                 *npar);
1698                         break;
1699                 }
1700                 r = attr[*npar + 2];
1701                 g = attr[*npar + 3];
1702                 b = attr[*npar + 4];
1703                 *npar += 4;
1704                 if(!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1705                         fprintf(stderr, "erresc: bad rgb color (%d,%d,%d)\n",
1706                                 r, g, b);
1707                 else
1708                         idx = TRUECOLOR(r, g, b);
1709                 break;
1710         case 5: /* indexed color */
1711                 if (*npar + 2 >= l) {
1712                         fprintf(stderr,
1713                                 "erresc(38): Incorrect number of parameters (%d)\n",
1714                                 *npar);
1715                         break;
1716                 }
1717                 *npar += 2;
1718                 if(!BETWEEN(attr[*npar], 0, 255))
1719                         fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
1720                 else
1721                         idx = attr[*npar];
1722                 break;
1723         case 0: /* implemented defined (only foreground) */
1724         case 1: /* transparent */
1725         case 3: /* direct color in CMY space */
1726         case 4: /* direct color in CMYK space */
1727         default:
1728                 fprintf(stderr,
1729                         "erresc(38): gfx attr %d unknown\n", attr[*npar]);
1730                 break;
1731         }
1732
1733         return idx;
1734 }
1735
1736 void
1737 tsetattr(int *attr, int l) {
1738         int i;
1739         int32_t idx;
1740
1741         for(i = 0; i < l; i++) {
1742                 switch(attr[i]) {
1743                 case 0:
1744                         term.c.attr.mode &= ~(
1745                                 ATTR_BOLD       |
1746                                 ATTR_FAINT      |
1747                                 ATTR_ITALIC     |
1748                                 ATTR_UNDERLINE  |
1749                                 ATTR_BLINK      |
1750                                 ATTR_REVERSE    |
1751                                 ATTR_INVISIBLE  |
1752                                 ATTR_STRUCK     );
1753                         term.c.attr.fg = defaultfg;
1754                         term.c.attr.bg = defaultbg;
1755                         break;
1756                 case 1:
1757                         term.c.attr.mode |= ATTR_BOLD;
1758                         break;
1759                 case 2:
1760                         term.c.attr.mode |= ATTR_FAINT;
1761                         break;
1762                 case 3:
1763                         term.c.attr.mode |= ATTR_ITALIC;
1764                         break;
1765                 case 4:
1766                         term.c.attr.mode |= ATTR_UNDERLINE;
1767                         break;
1768                 case 5: /* slow blink */
1769                         /* FALLTHROUGH */
1770                 case 6: /* rapid blink */
1771                         term.c.attr.mode |= ATTR_BLINK;
1772                         break;
1773                 case 7:
1774                         term.c.attr.mode |= ATTR_REVERSE;
1775                         break;
1776                 case 8:
1777                         term.c.attr.mode |= ATTR_INVISIBLE;
1778                         break;
1779                 case 9:
1780                         term.c.attr.mode |= ATTR_STRUCK;
1781                         break;
1782                 case 22:
1783                         term.c.attr.mode &= ~(ATTR_BOLD | ATTR_FAINT);
1784                         break;
1785                 case 23:
1786                         term.c.attr.mode &= ~ATTR_ITALIC;
1787                         break;
1788                 case 24:
1789                         term.c.attr.mode &= ~ATTR_UNDERLINE;
1790                         break;
1791                 case 25:
1792                         term.c.attr.mode &= ~ATTR_BLINK;
1793                         break;
1794                 case 27:
1795                         term.c.attr.mode &= ~ATTR_REVERSE;
1796                         break;
1797                 case 28:
1798                         term.c.attr.mode &= ~ATTR_INVISIBLE;
1799                         break;
1800                 case 29:
1801                         term.c.attr.mode &= ~ATTR_STRUCK;
1802                         break;
1803                 case 38:
1804                         if ((idx = tdefcolor(attr, &i, l)) >= 0)
1805                                 term.c.attr.fg = idx;
1806                         break;
1807                 case 39:
1808                         term.c.attr.fg = defaultfg;
1809                         break;
1810                 case 48:
1811                         if ((idx = tdefcolor(attr, &i, l)) >= 0)
1812                                 term.c.attr.bg = idx;
1813                         break;
1814                 case 49:
1815                         term.c.attr.bg = defaultbg;
1816                         break;
1817                 default:
1818                         if(BETWEEN(attr[i], 30, 37)) {
1819                                 term.c.attr.fg = attr[i] - 30;
1820                         } else if(BETWEEN(attr[i], 40, 47)) {
1821                                 term.c.attr.bg = attr[i] - 40;
1822                         } else if(BETWEEN(attr[i], 90, 97)) {
1823                                 term.c.attr.fg = attr[i] - 90 + 8;
1824                         } else if(BETWEEN(attr[i], 100, 107)) {
1825                                 term.c.attr.bg = attr[i] - 100 + 8;
1826                         } else {
1827                                 fprintf(stderr,
1828                                         "erresc(default): gfx attr %d unknown\n",
1829                                         attr[i]), csidump();
1830                         }
1831                         break;
1832                 }
1833         }
1834 }
1835
1836 void
1837 tsetscroll(int t, int b) {
1838         int temp;
1839
1840         LIMIT(t, 0, term.row-1);
1841         LIMIT(b, 0, term.row-1);
1842         if(t > b) {
1843                 temp = t;
1844                 t = b;
1845                 b = temp;
1846         }
1847         term.top = t;
1848         term.bot = b;
1849 }
1850
1851 void
1852 tsetmode(bool priv, bool set, int *args, int narg) {
1853         int *lim, mode;
1854         bool alt;
1855
1856         for(lim = args + narg; args < lim; ++args) {
1857                 if(priv) {
1858                         switch(*args) {
1859                         case 1: /* DECCKM -- Cursor key */
1860                                 MODBIT(term.mode, set, MODE_APPCURSOR);
1861                                 break;
1862                         case 5: /* DECSCNM -- Reverse video */
1863                                 mode = term.mode;
1864                                 MODBIT(term.mode, set, MODE_REVERSE);
1865                                 if(mode != term.mode)
1866                                         redraw();
1867                                 break;
1868                         case 6: /* DECOM -- Origin */
1869                                 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1870                                 tmoveato(0, 0);
1871                                 break;
1872                         case 7: /* DECAWM -- Auto wrap */
1873                                 MODBIT(term.mode, set, MODE_WRAP);
1874                                 break;
1875                         case 0:  /* Error (IGNORED) */
1876                         case 2:  /* DECANM -- ANSI/VT52 (IGNORED) */
1877                         case 3:  /* DECCOLM -- Column  (IGNORED) */
1878                         case 4:  /* DECSCLM -- Scroll (IGNORED) */
1879                         case 8:  /* DECARM -- Auto repeat (IGNORED) */
1880                         case 18: /* DECPFF -- Printer feed (IGNORED) */
1881                         case 19: /* DECPEX -- Printer extent (IGNORED) */
1882                         case 42: /* DECNRCM -- National characters (IGNORED) */
1883                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
1884                                 break;
1885                         case 25: /* DECTCEM -- Text Cursor Enable Mode */
1886                                 MODBIT(term.mode, !set, MODE_HIDE);
1887                                 break;
1888                         case 9:    /* X10 mouse compatibility mode */
1889                                 xsetpointermotion(0);
1890                                 MODBIT(term.mode, 0, MODE_MOUSE);
1891                                 MODBIT(term.mode, set, MODE_MOUSEX10);
1892                                 break;
1893                         case 1000: /* 1000: report button press */
1894                                 xsetpointermotion(0);
1895                                 MODBIT(term.mode, 0, MODE_MOUSE);
1896                                 MODBIT(term.mode, set, MODE_MOUSEBTN);
1897                                 break;
1898                         case 1002: /* 1002: report motion on button press */
1899                                 xsetpointermotion(0);
1900                                 MODBIT(term.mode, 0, MODE_MOUSE);
1901                                 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1902                                 break;
1903                         case 1003: /* 1003: enable all mouse motions */
1904                                 xsetpointermotion(set);
1905                                 MODBIT(term.mode, 0, MODE_MOUSE);
1906                                 MODBIT(term.mode, set, MODE_MOUSEMANY);
1907                                 break;
1908                         case 1004: /* 1004: send focus events to tty */
1909                                 MODBIT(term.mode, set, MODE_FOCUS);
1910                                 break;
1911                         case 1006: /* 1006: extended reporting mode */
1912                                 MODBIT(term.mode, set, MODE_MOUSESGR);
1913                                 break;
1914                         case 1034:
1915                                 MODBIT(term.mode, set, MODE_8BIT);
1916                                 break;
1917                         case 1049: /* swap screen & set/restore cursor as xterm */
1918                                 if (!allowaltscreen)
1919                                         break;
1920                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1921                                 /* FALLTHROUGH */
1922                         case 47: /* swap screen */
1923                         case 1047:
1924                                 if (!allowaltscreen)
1925                                         break;
1926                                 alt = IS_SET(MODE_ALTSCREEN);
1927                                 if(alt) {
1928                                         tclearregion(0, 0, term.col-1,
1929                                                         term.row-1);
1930                                 }
1931                                 if(set ^ alt) /* set is always 1 or 0 */
1932                                         tswapscreen();
1933                                 if(*args != 1049)
1934                                         break;
1935                                 /* FALLTHROUGH */
1936                         case 1048:
1937                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1938                                 break;
1939                         case 2004: /* 2004: bracketed paste mode */
1940                                 MODBIT(term.mode, set, MODE_BRCKTPASTE);
1941                                 break;
1942                         /* Not implemented mouse modes. See comments there. */
1943                         case 1001: /* mouse highlight mode; can hang the
1944                                       terminal by design when implemented. */
1945                         case 1005: /* UTF-8 mouse mode; will confuse
1946                                       applications not supporting UTF-8
1947                                       and luit. */
1948                         case 1015: /* urxvt mangled mouse mode; incompatible
1949                                       and can be mistaken for other control
1950                                       codes. */
1951                         default:
1952                                 fprintf(stderr,
1953                                         "erresc: unknown private set/reset mode %d\n",
1954                                         *args);
1955                                 break;
1956                         }
1957                 } else {
1958                         switch(*args) {
1959                         case 0:  /* Error (IGNORED) */
1960                                 break;
1961                         case 2:  /* KAM -- keyboard action */
1962                                 MODBIT(term.mode, set, MODE_KBDLOCK);
1963                                 break;
1964                         case 4:  /* IRM -- Insertion-replacement */
1965                                 MODBIT(term.mode, set, MODE_INSERT);
1966                                 break;
1967                         case 12: /* SRM -- Send/Receive */
1968                                 MODBIT(term.mode, !set, MODE_ECHO);
1969                                 break;
1970                         case 20: /* LNM -- Linefeed/new line */
1971                                 MODBIT(term.mode, set, MODE_CRLF);
1972                                 break;
1973                         default:
1974                                 fprintf(stderr,
1975                                         "erresc: unknown set/reset mode %d\n",
1976                                         *args);
1977                                 break;
1978                         }
1979                 }
1980         }
1981 }
1982
1983 void
1984 csihandle(void) {
1985         char buf[40];
1986         int len;
1987
1988         switch(csiescseq.mode[0]) {
1989         default:
1990         unknown:
1991                 fprintf(stderr, "erresc: unknown csi ");
1992                 csidump();
1993                 /* die(""); */
1994                 break;
1995         case '@': /* ICH -- Insert <n> blank char */
1996                 DEFAULT(csiescseq.arg[0], 1);
1997                 tinsertblank(csiescseq.arg[0]);
1998                 break;
1999         case 'A': /* CUU -- Cursor <n> Up */
2000                 DEFAULT(csiescseq.arg[0], 1);
2001                 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
2002                 break;
2003         case 'B': /* CUD -- Cursor <n> Down */
2004         case 'e': /* VPR --Cursor <n> Down */
2005                 DEFAULT(csiescseq.arg[0], 1);
2006                 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
2007                 break;
2008         case 'i': /* MC -- Media Copy */
2009                 switch(csiescseq.arg[0]) {
2010                 case 0:
2011                         tdump();
2012                         break;
2013                 case 1:
2014                         tdumpline(term.c.y);
2015                         break;
2016                 case 2:
2017                         tdumpsel();
2018                         break;
2019                 case 4:
2020                         term.mode &= ~MODE_PRINT;
2021                         break;
2022                 case 5:
2023                         term.mode |= MODE_PRINT;
2024                         break;
2025                 }
2026                 break;
2027         case 'c': /* DA -- Device Attributes */
2028                 if(csiescseq.arg[0] == 0)
2029                         ttywrite(vtiden, sizeof(vtiden) - 1);
2030                 break;
2031         case 'C': /* CUF -- Cursor <n> Forward */
2032         case 'a': /* HPR -- Cursor <n> Forward */
2033                 DEFAULT(csiescseq.arg[0], 1);
2034                 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
2035                 break;
2036         case 'D': /* CUB -- Cursor <n> Backward */
2037                 DEFAULT(csiescseq.arg[0], 1);
2038                 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
2039                 break;
2040         case 'E': /* CNL -- Cursor <n> Down and first col */
2041                 DEFAULT(csiescseq.arg[0], 1);
2042                 tmoveto(0, term.c.y+csiescseq.arg[0]);
2043                 break;
2044         case 'F': /* CPL -- Cursor <n> Up and first col */
2045                 DEFAULT(csiescseq.arg[0], 1);
2046                 tmoveto(0, term.c.y-csiescseq.arg[0]);
2047                 break;
2048         case 'g': /* TBC -- Tabulation clear */
2049                 switch(csiescseq.arg[0]) {
2050                 case 0: /* clear current tab stop */
2051                         term.tabs[term.c.x] = 0;
2052                         break;
2053                 case 3: /* clear all the tabs */
2054                         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
2055                         break;
2056                 default:
2057                         goto unknown;
2058                 }
2059                 break;
2060         case 'G': /* CHA -- Move to <col> */
2061         case '`': /* HPA */
2062                 DEFAULT(csiescseq.arg[0], 1);
2063                 tmoveto(csiescseq.arg[0]-1, term.c.y);
2064                 break;
2065         case 'H': /* CUP -- Move to <row> <col> */
2066         case 'f': /* HVP */
2067                 DEFAULT(csiescseq.arg[0], 1);
2068                 DEFAULT(csiescseq.arg[1], 1);
2069                 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
2070                 break;
2071         case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
2072                 DEFAULT(csiescseq.arg[0], 1);
2073                 tputtab(csiescseq.arg[0]);
2074                 break;
2075         case 'J': /* ED -- Clear screen */
2076                 selclear(NULL);
2077                 switch(csiescseq.arg[0]) {
2078                 case 0: /* below */
2079                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
2080                         if(term.c.y < term.row-1) {
2081                                 tclearregion(0, term.c.y+1, term.col-1,
2082                                                 term.row-1);
2083                         }
2084                         break;
2085                 case 1: /* above */
2086                         if(term.c.y > 1)
2087                                 tclearregion(0, 0, term.col-1, term.c.y-1);
2088                         tclearregion(0, term.c.y, term.c.x, term.c.y);
2089                         break;
2090                 case 2: /* all */
2091                         tclearregion(0, 0, term.col-1, term.row-1);
2092                         break;
2093                 default:
2094                         goto unknown;
2095                 }
2096                 break;
2097         case 'K': /* EL -- Clear line */
2098                 switch(csiescseq.arg[0]) {
2099                 case 0: /* right */
2100                         tclearregion(term.c.x, term.c.y, term.col-1,
2101                                         term.c.y);
2102                         break;
2103                 case 1: /* left */
2104                         tclearregion(0, term.c.y, term.c.x, term.c.y);
2105                         break;
2106                 case 2: /* all */
2107                         tclearregion(0, term.c.y, term.col-1, term.c.y);
2108                         break;
2109                 }
2110                 break;
2111         case 'S': /* SU -- Scroll <n> line up */
2112                 DEFAULT(csiescseq.arg[0], 1);
2113                 tscrollup(term.top, csiescseq.arg[0]);
2114                 break;
2115         case 'T': /* SD -- Scroll <n> line down */
2116                 DEFAULT(csiescseq.arg[0], 1);
2117                 tscrolldown(term.top, csiescseq.arg[0]);
2118                 break;
2119         case 'L': /* IL -- Insert <n> blank lines */
2120                 DEFAULT(csiescseq.arg[0], 1);
2121                 tinsertblankline(csiescseq.arg[0]);
2122                 break;
2123         case 'l': /* RM -- Reset Mode */
2124                 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2125                 break;
2126         case 'M': /* DL -- Delete <n> lines */
2127                 DEFAULT(csiescseq.arg[0], 1);
2128                 tdeleteline(csiescseq.arg[0]);
2129                 break;
2130         case 'X': /* ECH -- Erase <n> char */
2131                 DEFAULT(csiescseq.arg[0], 1);
2132                 tclearregion(term.c.x, term.c.y,
2133                                 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2134                 break;
2135         case 'P': /* DCH -- Delete <n> char */
2136                 DEFAULT(csiescseq.arg[0], 1);
2137                 tdeletechar(csiescseq.arg[0]);
2138                 break;
2139         case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2140                 DEFAULT(csiescseq.arg[0], 1);
2141                 tputtab(-csiescseq.arg[0]);
2142                 break;
2143         case 'd': /* VPA -- Move to <row> */
2144                 DEFAULT(csiescseq.arg[0], 1);
2145                 tmoveato(term.c.x, csiescseq.arg[0]-1);
2146                 break;
2147         case 'h': /* SM -- Set terminal mode */
2148                 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2149                 break;
2150         case 'm': /* SGR -- Terminal attribute (color) */
2151                 tsetattr(csiescseq.arg, csiescseq.narg);
2152                 break;
2153         case 'n': /* DSR – Device Status Report (cursor position) */
2154                 if (csiescseq.arg[0] == 6) {
2155                         len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
2156                                         term.c.y+1, term.c.x+1);
2157                         ttywrite(buf, len);
2158                 }
2159                 break;
2160         case 'r': /* DECSTBM -- Set Scrolling Region */
2161                 if(csiescseq.priv) {
2162                         goto unknown;
2163                 } else {
2164                         DEFAULT(csiescseq.arg[0], 1);
2165                         DEFAULT(csiescseq.arg[1], term.row);
2166                         tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2167                         tmoveato(0, 0);
2168                 }
2169                 break;
2170         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2171                 tcursor(CURSOR_SAVE);
2172                 break;
2173         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2174                 tcursor(CURSOR_LOAD);
2175                 break;
2176         case ' ':
2177                 switch (csiescseq.mode[1]) {
2178                         case 'q': /* DECSCUSR -- Set Cursor Style */
2179                                 DEFAULT(csiescseq.arg[0], 1);
2180                                 if (!BETWEEN(csiescseq.arg[0], 0, 6)) {
2181                                         goto unknown;
2182                                 }
2183                                 xw.cursor = csiescseq.arg[0];
2184                                 break;
2185                         default:
2186                                 goto unknown;
2187                 }
2188                 break;
2189         }
2190 }
2191
2192 void
2193 csidump(void) {
2194         int i;
2195         uint c;
2196
2197         printf("ESC[");
2198         for(i = 0; i < csiescseq.len; i++) {
2199                 c = csiescseq.buf[i] & 0xff;
2200                 if(isprint(c)) {
2201                         putchar(c);
2202                 } else if(c == '\n') {
2203                         printf("(\\n)");
2204                 } else if(c == '\r') {
2205                         printf("(\\r)");
2206                 } else if(c == 0x1b) {
2207                         printf("(\\e)");
2208                 } else {
2209                         printf("(%02x)", c);
2210                 }
2211         }
2212         putchar('\n');
2213 }
2214
2215 void
2216 csireset(void) {
2217         memset(&csiescseq, 0, sizeof(csiescseq));
2218 }
2219
2220 void
2221 strhandle(void) {
2222         char *p = NULL;
2223         int j, narg, par;
2224
2225         term.esc &= ~(ESC_STR_END|ESC_STR);
2226         strparse();
2227         narg = strescseq.narg;
2228         par = atoi(strescseq.args[0]);
2229
2230         switch(strescseq.type) {
2231         case ']': /* OSC -- Operating System Command */
2232                 switch(par) {
2233                 case 0:
2234                 case 1:
2235                 case 2:
2236                         if(narg > 1)
2237                                 xsettitle(strescseq.args[1]);
2238                         return;
2239                 case 4: /* color set */
2240                         if(narg < 3)
2241                                 break;
2242                         p = strescseq.args[2];
2243                         /* FALLTHROUGH */
2244                 case 104: /* color reset, here p = NULL */
2245                         j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2246                         if(xsetcolorname(j, p)) {
2247                                 fprintf(stderr, "erresc: invalid color %s\n", p);
2248                         } else {
2249                                 /*
2250                                  * TODO if defaultbg color is changed, borders
2251                                  * are dirty
2252                                  */
2253                                 redraw();
2254                         }
2255                         return;
2256                 }
2257                 break;
2258         case 'k': /* old title set compatibility */
2259                 xsettitle(strescseq.args[0]);
2260                 return;
2261         case 'P': /* DCS -- Device Control String */
2262         case '_': /* APC -- Application Program Command */
2263         case '^': /* PM -- Privacy Message */
2264                 return;
2265         }
2266
2267         fprintf(stderr, "erresc: unknown str ");
2268         strdump();
2269 }
2270
2271 void
2272 strparse(void) {
2273         char *p = strescseq.buf;
2274
2275         strescseq.narg = 0;
2276         strescseq.buf[strescseq.len] = '\0';
2277         while(p && strescseq.narg < STR_ARG_SIZ)
2278                 strescseq.args[strescseq.narg++] = strsep(&p, ";");
2279 }
2280
2281 void
2282 strdump(void) {
2283         int i;
2284         uint c;
2285
2286         printf("ESC%c", strescseq.type);
2287         for(i = 0; i < strescseq.len; i++) {
2288                 c = strescseq.buf[i] & 0xff;
2289                 if(c == '\0') {
2290                         return;
2291                 } else if(isprint(c)) {
2292                         putchar(c);
2293                 } else if(c == '\n') {
2294                         printf("(\\n)");
2295                 } else if(c == '\r') {
2296                         printf("(\\r)");
2297                 } else if(c == 0x1b) {
2298                         printf("(\\e)");
2299                 } else {
2300                         printf("(%02x)", c);
2301                 }
2302         }
2303         printf("ESC\\\n");
2304 }
2305
2306 void
2307 strreset(void) {
2308         memset(&strescseq, 0, sizeof(strescseq));
2309 }
2310
2311 void
2312 tprinter(char *s, size_t len) {
2313         if(iofd != -1 && xwrite(iofd, s, len) < 0) {
2314                 fprintf(stderr, "Error writing in %s:%s\n",
2315                         opt_io, strerror(errno));
2316                 close(iofd);
2317                 iofd = -1;
2318         }
2319 }
2320
2321 void
2322 toggleprinter(const Arg *arg) {
2323         term.mode ^= MODE_PRINT;
2324 }
2325
2326 void
2327 printscreen(const Arg *arg) {
2328         tdump();
2329 }
2330
2331 void
2332 printsel(const Arg *arg) {
2333         tdumpsel();
2334 }
2335
2336 void
2337 tdumpsel(void) {
2338         char *ptr;
2339
2340         if((ptr = getsel())) {
2341                 tprinter(ptr, strlen(ptr));
2342                 free(ptr);
2343         }
2344 }
2345
2346 void
2347 tdumpline(int n) {
2348         Glyph *bp, *end;
2349
2350         bp = &term.line[n][0];
2351         end = &bp[MIN(tlinelen(n), term.col) - 1];
2352         if(bp != end || bp->c[0] != ' ') {
2353                 for( ;bp <= end; ++bp)
2354                         tprinter(bp->c, utf8len(bp->c));
2355         }
2356         tprinter("\n", 1);
2357 }
2358
2359 void
2360 tdump(void) {
2361         int i;
2362
2363         for(i = 0; i < term.row; ++i)
2364                 tdumpline(i);
2365 }
2366
2367 void
2368 tputtab(int n) {
2369         uint x = term.c.x;
2370
2371         if(n > 0) {
2372                 while(x < term.col && n--)
2373                         for(++x; x < term.col && !term.tabs[x]; ++x)
2374                                 /* nothing */ ;
2375         } else if(n < 0) {
2376                 while(x > 0 && n++)
2377                         for(--x; x > 0 && !term.tabs[x]; --x)
2378                                 /* nothing */ ;
2379         }
2380         tmoveto(x, term.c.y);
2381 }
2382
2383 void
2384 techo(char *buf, int len) {
2385         for(; len > 0; buf++, len--) {
2386                 char c = *buf;
2387
2388                 if(ISCONTROL((uchar) c)) { /* control code */
2389                         if(c & 0x80) {
2390                                 c &= 0x7f;
2391                                 tputc("^", 1);
2392                                 tputc("[", 1);
2393                         } else if(c != '\n' && c != '\r' && c != '\t') {
2394                                 c ^= 0x40;
2395                                 tputc("^", 1);
2396                         }
2397                         tputc(&c, 1);
2398                 } else {
2399                         break;
2400                 }
2401         }
2402         if(len)
2403                 tputc(buf, len);
2404 }
2405
2406 void
2407 tdeftran(char ascii) {
2408         static char cs[] = "0B";
2409         static int vcs[] = {CS_GRAPHIC0, CS_USA};
2410         char *p;
2411
2412         if((p = strchr(cs, ascii)) == NULL) {
2413                 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2414         } else {
2415                 term.trantbl[term.icharset] = vcs[p - cs];
2416         }
2417 }
2418
2419 void
2420 tdectest(char c) {
2421         static char E[UTF_SIZ] = "E";
2422         int x, y;
2423
2424         if(c == '8') { /* DEC screen alignment test. */
2425                 for(x = 0; x < term.col; ++x) {
2426                         for(y = 0; y < term.row; ++y)
2427                                 tsetchar(E, &term.c.attr, x, y);
2428                 }
2429         }
2430 }
2431
2432 void
2433 tstrsequence(uchar c) {
2434         if (c & 0x80) {
2435                 switch (c) {
2436                 case 0x90:   /* DCS -- Device Control String */
2437                         c = 'P';
2438                         break;
2439                 case 0x9f:   /* APC -- Application Program Command */
2440                         c = '_';
2441                         break;
2442                 case 0x9e:   /* PM -- Privacy Message */
2443                         c = '^';
2444                         break;
2445                 case 0x9d:   /* OSC -- Operating System Command */
2446                         c = ']';
2447                         break;
2448                 }
2449         }
2450         strreset();
2451         strescseq.type = c;
2452         term.esc |= ESC_STR;
2453         return;
2454 }
2455
2456 void
2457 tcontrolcode(uchar ascii) {
2458         static char question[UTF_SIZ] = "?";
2459
2460         switch(ascii) {
2461         case '\t':   /* HT */
2462                 tputtab(1);
2463                 return;
2464         case '\b':   /* BS */
2465                 tmoveto(term.c.x-1, term.c.y);
2466                 return;
2467         case '\r':   /* CR */
2468                 tmoveto(0, term.c.y);
2469                 return;
2470         case '\f':   /* LF */
2471         case '\v':   /* VT */
2472         case '\n':   /* LF */
2473                 /* go to first col if the mode is set */
2474                 tnewline(IS_SET(MODE_CRLF));
2475                 return;
2476         case '\a':   /* BEL */
2477                 if(term.esc & ESC_STR_END) {
2478                         /* backwards compatibility to xterm */
2479                         strhandle();
2480                 } else {
2481                         if(!(xw.state & WIN_FOCUSED))
2482                                 xseturgency(1);
2483                         if (bellvolume)
2484                                 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
2485                 }
2486                 break;
2487         case '\033': /* ESC */
2488                 csireset();
2489                 term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
2490                 term.esc |= ESC_START;
2491                 return;
2492         case '\016': /* SO (LS1 -- Locking shift 1) */
2493         case '\017': /* SI (LS0 -- Locking shift 0) */
2494                 term.charset = 1 - (ascii - '\016');
2495                 return;
2496         case '\032': /* SUB */
2497                 tsetchar(question, &term.c.attr, term.c.x, term.c.y);
2498         case '\030': /* CAN */
2499                 csireset();
2500                 break;
2501         case '\005': /* ENQ (IGNORED) */
2502         case '\000': /* NUL (IGNORED) */
2503         case '\021': /* XON (IGNORED) */
2504         case '\023': /* XOFF (IGNORED) */
2505         case 0177:   /* DEL (IGNORED) */
2506                 return;
2507         case 0x84:   /* TODO: IND */
2508                 break;
2509         case 0x85:   /* NEL -- Next line */
2510                 tnewline(1); /* always go to first col */
2511                 break;
2512         case 0x88:   /* HTS -- Horizontal tab stop */
2513                 term.tabs[term.c.x] = 1;
2514                 break;
2515         case 0x8d:   /* TODO: RI */
2516         case 0x8e:   /* TODO: SS2 */
2517         case 0x8f:   /* TODO: SS3 */
2518         case 0x98:   /* TODO: SOS */
2519                 break;
2520         case 0x9a:   /* DECID -- Identify Terminal */
2521                 ttywrite(vtiden, sizeof(vtiden) - 1);
2522                 break;
2523         case 0x9b:   /* TODO: CSI */
2524         case 0x9c:   /* TODO: ST */
2525                 break;
2526         case 0x90:   /* DCS -- Device Control String */
2527         case 0x9f:   /* APC -- Application Program Command */
2528         case 0x9e:   /* PM -- Privacy Message */
2529         case 0x9d:   /* OSC -- Operating System Command */
2530                 tstrsequence(ascii);
2531                 return;
2532         }
2533         /* only CAN, SUB, \a and C1 chars interrupt a sequence */
2534         term.esc &= ~(ESC_STR_END|ESC_STR);
2535         return;
2536 }
2537
2538 /*
2539  * returns 1 when the sequence is finished and it hasn't to read
2540  * more characters for this sequence, otherwise 0
2541  */
2542 int
2543 eschandle(uchar ascii) {
2544         switch(ascii) {
2545         case '[':
2546                 term.esc |= ESC_CSI;
2547                 return 0;
2548         case '#':
2549                 term.esc |= ESC_TEST;
2550                 return 0;
2551         case 'P': /* DCS -- Device Control String */
2552         case '_': /* APC -- Application Program Command */
2553         case '^': /* PM -- Privacy Message */
2554         case ']': /* OSC -- Operating System Command */
2555         case 'k': /* old title set compatibility */
2556                 tstrsequence(ascii);
2557                 return 0;
2558         case 'n': /* LS2 -- Locking shift 2 */
2559         case 'o': /* LS3 -- Locking shift 3 */
2560                 term.charset = 2 + (ascii - 'n');
2561                 break;
2562         case '(': /* GZD4 -- set primary charset G0 */
2563         case ')': /* G1D4 -- set secondary charset G1 */
2564         case '*': /* G2D4 -- set tertiary charset G2 */
2565         case '+': /* G3D4 -- set quaternary charset G3 */
2566                 term.icharset = ascii - '(';
2567                 term.esc |= ESC_ALTCHARSET;
2568                 return 0;
2569         case 'D': /* IND -- Linefeed */
2570                 if(term.c.y == term.bot) {
2571                         tscrollup(term.top, 1);
2572                 } else {
2573                         tmoveto(term.c.x, term.c.y+1);
2574                 }
2575                 break;
2576         case 'E': /* NEL -- Next line */
2577                 tnewline(1); /* always go to first col */
2578                 break;
2579         case 'H': /* HTS -- Horizontal tab stop */
2580                 term.tabs[term.c.x] = 1;
2581                 break;
2582         case 'M': /* RI -- Reverse index */
2583                 if(term.c.y == term.top) {
2584                         tscrolldown(term.top, 1);
2585                 } else {
2586                         tmoveto(term.c.x, term.c.y-1);
2587                 }
2588                 break;
2589         case 'Z': /* DECID -- Identify Terminal */
2590                 ttywrite(vtiden, sizeof(vtiden) - 1);
2591                 break;
2592         case 'c': /* RIS -- Reset to inital state */
2593                 treset();
2594                 xresettitle();
2595                 xloadcols();
2596                 break;
2597         case '=': /* DECPAM -- Application keypad */
2598                 term.mode |= MODE_APPKEYPAD;
2599                 break;
2600         case '>': /* DECPNM -- Normal keypad */
2601                 term.mode &= ~MODE_APPKEYPAD;
2602                 break;
2603         case '7': /* DECSC -- Save Cursor */
2604                 tcursor(CURSOR_SAVE);
2605                 break;
2606         case '8': /* DECRC -- Restore Cursor */
2607                 tcursor(CURSOR_LOAD);
2608                 break;
2609         case '\\': /* ST -- String Terminator */
2610                 if(term.esc & ESC_STR_END)
2611                         strhandle();
2612                 break;
2613         default:
2614                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2615                         (uchar) ascii, isprint(ascii)? ascii:'.');
2616                 break;
2617         }
2618         return 1;
2619 }
2620
2621 void
2622 tputc(char *c, int len) {
2623         uchar ascii;
2624         bool control;
2625         long unicodep;
2626         int width;
2627         Glyph *gp;
2628
2629         if(len == 1) {
2630                 width = 1;
2631                 unicodep = ascii = *c;
2632         } else {
2633                 utf8decode(c, &unicodep, UTF_SIZ);
2634                 if ((width = wcwidth(unicodep)) == -1) {
2635                         c = "\357\277\275";     /* UTF_INVALID */
2636                         width = 1;
2637                 }
2638                 control = ISCONTROLC1(unicodep);
2639                 ascii = unicodep;
2640         }
2641
2642         if(IS_SET(MODE_PRINT))
2643                 tprinter(c, len);
2644         control = ISCONTROL(unicodep);
2645
2646         /*
2647          * STR sequence must be checked before anything else
2648          * because it uses all following characters until it
2649          * receives a ESC, a SUB, a ST or any other C1 control
2650          * character.
2651          */
2652         if(term.esc & ESC_STR) {
2653                 if(width == 1 &&
2654                    (ascii == '\a' || ascii == 030 ||
2655                     ascii == 032  || ascii == 033 ||
2656                     ISCONTROLC1(unicodep))) {
2657                         term.esc &= ~(ESC_START|ESC_STR);
2658                         term.esc |= ESC_STR_END;
2659                 } else if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2660                         memmove(&strescseq.buf[strescseq.len], c, len);
2661                         strescseq.len += len;
2662                         return;
2663                 } else {
2664                 /*
2665                  * Here is a bug in terminals. If the user never sends
2666                  * some code to stop the str or esc command, then st
2667                  * will stop responding. But this is better than
2668                  * silently failing with unknown characters. At least
2669                  * then users will report back.
2670                  *
2671                  * In the case users ever get fixed, here is the code:
2672                  */
2673                 /*
2674                  * term.esc = 0;
2675                  * strhandle();
2676                  */
2677                         return;
2678                 }
2679         }
2680
2681         /*
2682          * Actions of control codes must be performed as soon they arrive
2683          * because they can be embedded inside a control sequence, and
2684          * they must not cause conflicts with sequences.
2685          */
2686         if(control) {
2687                 tcontrolcode(ascii);
2688                 /*
2689                  * control codes are not shown ever
2690                  */
2691                 return;
2692         } else if(term.esc & ESC_START) {
2693                 if(term.esc & ESC_CSI) {
2694                         csiescseq.buf[csiescseq.len++] = ascii;
2695                         if(BETWEEN(ascii, 0x40, 0x7E)
2696                                         || csiescseq.len >= \
2697                                         sizeof(csiescseq.buf)-1) {
2698                                 term.esc = 0;
2699                                 csiparse();
2700                                 csihandle();
2701                         }
2702                         return;
2703                 } else if(term.esc & ESC_ALTCHARSET) {
2704                         tdeftran(ascii);
2705                 } else if(term.esc & ESC_TEST) {
2706                         tdectest(ascii);
2707                 } else {
2708                         if (!eschandle(ascii))
2709                                 return;
2710                         /* sequence already finished */
2711                 }
2712                 term.esc = 0;
2713                 /*
2714                  * All characters which form part of a sequence are not
2715                  * printed
2716                  */
2717                 return;
2718         }
2719         if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2720                 selclear(NULL);
2721
2722         gp = &term.line[term.c.y][term.c.x];
2723         if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2724                 gp->mode |= ATTR_WRAP;
2725                 tnewline(1);
2726                 gp = &term.line[term.c.y][term.c.x];
2727         }
2728
2729         if(IS_SET(MODE_INSERT) && term.c.x+width < term.col)
2730                 memmove(gp+width, gp, (term.col - term.c.x - width) * sizeof(Glyph));
2731
2732         if(term.c.x+width > term.col) {
2733                 tnewline(1);
2734                 gp = &term.line[term.c.y][term.c.x];
2735         }
2736
2737         tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2738
2739         if(width == 2) {
2740                 gp->mode |= ATTR_WIDE;
2741                 if(term.c.x+1 < term.col) {
2742                         gp[1].c[0] = '\0';
2743                         gp[1].mode = ATTR_WDUMMY;
2744                 }
2745         }
2746         if(term.c.x+width < term.col) {
2747                 tmoveto(term.c.x+width, term.c.y);
2748         } else {
2749                 term.c.state |= CURSOR_WRAPNEXT;
2750         }
2751 }
2752
2753 void
2754 tresize(int col, int row) {
2755         int i;
2756         int minrow = MIN(row, term.row);
2757         int mincol = MIN(col, term.col);
2758         int slide = term.c.y - row + 1;
2759         bool *bp;
2760         TCursor c;
2761
2762         if(col < 1 || row < 1) {
2763                 fprintf(stderr,
2764                         "tresize: error resizing to %dx%d\n", col, row);
2765                 return;
2766         }
2767
2768         /* free unneeded rows */
2769         i = 0;
2770         if(slide > 0) {
2771                 /*
2772                  * slide screen to keep cursor where we expect it -
2773                  * tscrollup would work here, but we can optimize to
2774                  * memmove because we're freeing the earlier lines
2775                  */
2776                 for(/* i = 0 */; i < slide; i++) {
2777                         free(term.line[i]);
2778                         free(term.alt[i]);
2779                 }
2780                 memmove(term.line, term.line + slide, row * sizeof(Line));
2781                 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2782         }
2783         for(i += row; i < term.row; i++) {
2784                 free(term.line[i]);
2785                 free(term.alt[i]);
2786         }
2787
2788         /* resize to new height */
2789         term.line = xrealloc(term.line, row * sizeof(Line));
2790         term.alt  = xrealloc(term.alt,  row * sizeof(Line));
2791         term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2792         term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2793
2794         /* resize each row to new width, zero-pad if needed */
2795         for(i = 0; i < minrow; i++) {
2796                 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2797                 term.alt[i]  = xrealloc(term.alt[i],  col * sizeof(Glyph));
2798         }
2799
2800         /* allocate any new rows */
2801         for(/* i == minrow */; i < row; i++) {
2802                 term.line[i] = xmalloc(col * sizeof(Glyph));
2803                 term.alt[i] = xmalloc(col * sizeof(Glyph));
2804         }
2805         if(col > term.col) {
2806                 bp = term.tabs + term.col;
2807
2808                 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2809                 while(--bp > term.tabs && !*bp)
2810                         /* nothing */ ;
2811                 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2812                         *bp = 1;
2813         }
2814         /* update terminal size */
2815         term.col = col;
2816         term.row = row;
2817         /* reset scrolling region */
2818         tsetscroll(0, row-1);
2819         /* make use of the LIMIT in tmoveto */
2820         tmoveto(term.c.x, term.c.y);
2821         /* Clearing both screens (it makes dirty all lines) */
2822         c = term.c;
2823         for(i = 0; i < 2; i++) {
2824                 if(mincol < col && 0 < minrow) {
2825                         tclearregion(mincol, 0, col - 1, minrow - 1);
2826                 }
2827                 if(0 < col && minrow < row) {
2828                         tclearregion(0, minrow, col - 1, row - 1);
2829                 }
2830                 tswapscreen();
2831                 tcursor(CURSOR_LOAD);
2832         }
2833         term.c = c;
2834 }
2835
2836 void
2837 xresize(int col, int row) {
2838         xw.tw = MAX(1, col * xw.cw);
2839         xw.th = MAX(1, row * xw.ch);
2840
2841         XFreePixmap(xw.dpy, xw.buf);
2842         xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2843                         DefaultDepth(xw.dpy, xw.scr));
2844         XftDrawChange(xw.draw, xw.buf);
2845         xclear(0, 0, xw.w, xw.h);
2846 }
2847
2848 static inline ushort
2849 sixd_to_16bit(int x) {
2850         return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2851 }
2852
2853 void
2854 xloadcols(void) {
2855         int i;
2856         XRenderColor color = { .alpha = 0xffff };
2857         static bool loaded;
2858         Color *cp;
2859
2860         if(loaded) {
2861                 for (cp = dc.col; cp < dc.col + LEN(dc.col); ++cp)
2862                         XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
2863         }
2864
2865         /* load colors [0-15] and [256-LEN(colorname)] (config.h) */
2866         for(i = 0; i < LEN(colorname); i++) {
2867                 if(!colorname[i])
2868                         continue;
2869                 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2870                         die("Could not allocate color '%s'\n", colorname[i]);
2871                 }
2872         }
2873
2874         /* load colors [16-231] ; same colors as xterm */
2875         for(i = 16; i < 6*6*6+16; i++) {
2876                 color.red   = sixd_to_16bit( ((i-16)/36)%6 );
2877                 color.green = sixd_to_16bit( ((i-16)/6) %6 );
2878                 color.blue  = sixd_to_16bit( ((i-16)/1) %6 );
2879                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i]))
2880                         die("Could not allocate color %d\n", i);
2881         }
2882
2883         /* load colors [232-255] ; grayscale */
2884         for(; i < 256; i++) {
2885                 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (i-(6*6*6+16));
2886                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i]))
2887                         die("Could not allocate color %d\n", i);
2888         }
2889         loaded = true;
2890 }
2891
2892 int
2893 xsetcolorname(int x, const char *name) {
2894         XRenderColor color = { .alpha = 0xffff };
2895         Color ncolor;
2896
2897         if(!BETWEEN(x, 0, LEN(colorname)))
2898                 return 1;
2899
2900         if(!name) {
2901                 if(BETWEEN(x, 16, 16 + 215)) { /* 256 color */
2902                         color.red   = sixd_to_16bit( ((x-16)/36)%6 );
2903                         color.green = sixd_to_16bit( ((x-16)/6) %6 );
2904                         color.blue  = sixd_to_16bit( ((x-16)/1) %6 );
2905                         if(!XftColorAllocValue(xw.dpy, xw.vis,
2906                                                 xw.cmap, &color, &ncolor)) {
2907                                 return 1;
2908                         }
2909
2910                         XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
2911                         dc.col[x] = ncolor;
2912                         return 0;
2913                 } else if(BETWEEN(x, 16 + 216, 255)) { /* greyscale */
2914                         color.red = color.green = color.blue = \
2915                                     0x0808 + 0x0a0a * (x - (16 + 216));
2916                         if(!XftColorAllocValue(xw.dpy, xw.vis,
2917                                                 xw.cmap, &color, &ncolor)) {
2918                                 return 1;
2919                         }
2920
2921                         XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
2922                         dc.col[x] = ncolor;
2923                         return 0;
2924                 } else { /* system colors */
2925                         name = colorname[x];
2926                 }
2927         }
2928         if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &ncolor))
2929                 return 1;
2930
2931         XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
2932         dc.col[x] = ncolor;
2933         return 0;
2934 }
2935
2936 void
2937 xtermclear(int col1, int row1, int col2, int row2) {
2938         XftDrawRect(xw.draw,
2939                         &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2940                         borderpx + col1 * xw.cw,
2941                         borderpx + row1 * xw.ch,
2942                         (col2-col1+1) * xw.cw,
2943                         (row2-row1+1) * xw.ch);
2944 }
2945
2946 /*
2947  * Absolute coordinates.
2948  */
2949 void
2950 xclear(int x1, int y1, int x2, int y2) {
2951         XftDrawRect(xw.draw,
2952                         &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2953                         x1, y1, x2-x1, y2-y1);
2954 }
2955
2956 void
2957 xhints(void) {
2958         XClassHint class = {opt_class ? opt_class : termname, termname};
2959         XWMHints wm = {.flags = InputHint, .input = 1};
2960         XSizeHints *sizeh = NULL;
2961
2962         sizeh = XAllocSizeHints();
2963
2964         sizeh->flags = PSize | PResizeInc | PBaseSize;
2965         sizeh->height = xw.h;
2966         sizeh->width = xw.w;
2967         sizeh->height_inc = xw.ch;
2968         sizeh->width_inc = xw.cw;
2969         sizeh->base_height = 2 * borderpx;
2970         sizeh->base_width = 2 * borderpx;
2971         if(xw.isfixed == True) {
2972                 sizeh->flags |= PMaxSize | PMinSize;
2973                 sizeh->min_width = sizeh->max_width = xw.w;
2974                 sizeh->min_height = sizeh->max_height = xw.h;
2975         }
2976         if(xw.gm & (XValue|YValue)) {
2977                 sizeh->flags |= USPosition | PWinGravity;
2978                 sizeh->x = xw.l;
2979                 sizeh->y = xw.t;
2980                 sizeh->win_gravity = xgeommasktogravity(xw.gm);
2981         }
2982
2983         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
2984                         &class);
2985         XFree(sizeh);
2986 }
2987
2988 int
2989 xgeommasktogravity(int mask) {
2990         switch(mask & (XNegative|YNegative)) {
2991         case 0:
2992                 return NorthWestGravity;
2993         case XNegative:
2994                 return NorthEastGravity;
2995         case YNegative:
2996                 return SouthWestGravity;
2997         }
2998         return SouthEastGravity;
2999 }
3000
3001 int
3002 xloadfont(Font *f, FcPattern *pattern) {
3003         FcPattern *match;
3004         FcResult result;
3005
3006         match = FcFontMatch(NULL, pattern, &result);
3007         if(!match)
3008                 return 1;
3009
3010         if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
3011                 FcPatternDestroy(match);
3012                 return 1;
3013         }
3014
3015         f->set = NULL;
3016         f->pattern = FcPatternDuplicate(pattern);
3017
3018         f->ascent = f->match->ascent;
3019         f->descent = f->match->descent;
3020         f->lbearing = 0;
3021         f->rbearing = f->match->max_advance_width;
3022
3023         f->height = f->ascent + f->descent;
3024         f->width = f->lbearing + f->rbearing;
3025
3026         return 0;
3027 }
3028
3029 void
3030 xloadfonts(char *fontstr, double fontsize) {
3031         FcPattern *pattern;
3032         FcResult r_sz, r_psz;
3033         double fontval;
3034         float ceilf(float);
3035
3036         if(fontstr[0] == '-') {
3037                 pattern = XftXlfdParse(fontstr, False, False);
3038         } else {
3039                 pattern = FcNameParse((FcChar8 *)fontstr);
3040         }
3041
3042         if(!pattern)
3043                 die("st: can't open font %s\n", fontstr);
3044
3045         if(fontsize > 1) {
3046                 FcPatternDel(pattern, FC_PIXEL_SIZE);
3047                 FcPatternDel(pattern, FC_SIZE);
3048                 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
3049                 usedfontsize = fontsize;
3050         } else {
3051                 r_psz = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
3052                 r_sz = FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval);
3053                 if(r_psz == FcResultMatch) {
3054                         usedfontsize = fontval;
3055                 } else if(r_sz == FcResultMatch) {
3056                         usedfontsize = -1;
3057                 } else {
3058                         /*
3059                          * Default font size is 12, if none given. This is to
3060                          * have a known usedfontsize value.
3061                          */
3062                         FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
3063                         usedfontsize = 12;
3064                 }
3065                 defaultfontsize = usedfontsize;
3066         }
3067
3068         FcConfigSubstitute(0, pattern, FcMatchPattern);
3069         FcDefaultSubstitute(pattern);
3070
3071         if(xloadfont(&dc.font, pattern))
3072                 die("st: can't open font %s\n", fontstr);
3073
3074         if(usedfontsize < 0) {
3075                 FcPatternGetDouble(dc.font.match->pattern,
3076                                    FC_PIXEL_SIZE, 0, &fontval);
3077                 usedfontsize = fontval;
3078                 if(fontsize == 0)
3079                         defaultfontsize = fontval;
3080         }
3081
3082         /* Setting character width and height. */
3083         xw.cw = ceilf(dc.font.width * cwscale);
3084         xw.ch = ceilf(dc.font.height * chscale);
3085
3086         FcPatternDel(pattern, FC_SLANT);
3087         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
3088         if(xloadfont(&dc.ifont, pattern))
3089                 die("st: can't open font %s\n", fontstr);
3090
3091         FcPatternDel(pattern, FC_WEIGHT);
3092         FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
3093         if(xloadfont(&dc.ibfont, pattern))
3094                 die("st: can't open font %s\n", fontstr);
3095
3096         FcPatternDel(pattern, FC_SLANT);
3097         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
3098         if(xloadfont(&dc.bfont, pattern))
3099                 die("st: can't open font %s\n", fontstr);
3100
3101         FcPatternDestroy(pattern);
3102 }
3103
3104 int
3105 xloadfontset(Font *f) {
3106         FcResult result;
3107
3108         if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
3109                 return 1;
3110         return 0;
3111 }
3112
3113 void
3114 xunloadfont(Font *f) {
3115         XftFontClose(xw.dpy, f->match);
3116         FcPatternDestroy(f->pattern);
3117         if(f->set)
3118                 FcFontSetDestroy(f->set);
3119 }
3120
3121 void
3122 xunloadfonts(void) {
3123         /* Free the loaded fonts in the font cache.  */
3124         while(frclen > 0)
3125                 XftFontClose(xw.dpy, frc[--frclen].font);
3126
3127         xunloadfont(&dc.font);
3128         xunloadfont(&dc.bfont);
3129         xunloadfont(&dc.ifont);
3130         xunloadfont(&dc.ibfont);
3131 }
3132
3133 void
3134 xzoom(const Arg *arg) {
3135         Arg larg;
3136
3137         larg.i = usedfontsize + arg->i;
3138         xzoomabs(&larg);
3139 }
3140
3141 void
3142 xzoomabs(const Arg *arg) {
3143         xunloadfonts();
3144         xloadfonts(usedfont, arg->i);
3145         cresize(0, 0);
3146         redraw();
3147         xhints();
3148 }
3149
3150 void
3151 xzoomreset(const Arg *arg) {
3152         Arg larg;
3153
3154         if(defaultfontsize > 0) {
3155                 larg.i = defaultfontsize;
3156                 xzoomabs(&larg);
3157         }
3158 }
3159
3160 void
3161 xinit(void) {
3162         XGCValues gcvalues;
3163         Cursor cursor;
3164         Window parent;
3165         pid_t thispid = getpid();
3166
3167         if(!(xw.dpy = XOpenDisplay(NULL)))
3168                 die("Can't open display\n");
3169         xw.scr = XDefaultScreen(xw.dpy);
3170         xw.vis = XDefaultVisual(xw.dpy, xw.scr);
3171
3172         /* font */
3173         if(!FcInit())
3174                 die("Could not init fontconfig.\n");
3175
3176         usedfont = (opt_font == NULL)? font : opt_font;
3177         xloadfonts(usedfont, 0);
3178
3179         /* colors */
3180         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
3181         xloadcols();
3182
3183         /* adjust fixed window geometry */
3184         xw.w = 2 * borderpx + term.col * xw.cw;
3185         xw.h = 2 * borderpx + term.row * xw.ch;
3186         if(xw.gm & XNegative)
3187                 xw.l += DisplayWidth(xw.dpy, xw.scr) - xw.w - 2;
3188         if(xw.gm & YNegative)
3189                 xw.t += DisplayWidth(xw.dpy, xw.scr) - xw.h - 2;
3190
3191         /* Events */
3192         xw.attrs.background_pixel = dc.col[defaultbg].pixel;
3193         xw.attrs.border_pixel = dc.col[defaultbg].pixel;
3194         xw.attrs.bit_gravity = NorthWestGravity;
3195         xw.attrs.event_mask = FocusChangeMask | KeyPressMask
3196                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
3197                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
3198         xw.attrs.colormap = xw.cmap;
3199
3200         if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
3201                 parent = XRootWindow(xw.dpy, xw.scr);
3202         xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
3203                         xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
3204                         xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
3205                         | CWEventMask | CWColormap, &xw.attrs);
3206
3207         memset(&gcvalues, 0, sizeof(gcvalues));
3208         gcvalues.graphics_exposures = False;
3209         dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
3210                         &gcvalues);
3211         xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3212                         DefaultDepth(xw.dpy, xw.scr));
3213         XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
3214         XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
3215
3216         /* Xft rendering context */
3217         xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
3218
3219         /* input methods */
3220         if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3221                 XSetLocaleModifiers("@im=local");
3222                 if((xw.xim =  XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3223                         XSetLocaleModifiers("@im=");
3224                         if((xw.xim = XOpenIM(xw.dpy,
3225                                         NULL, NULL, NULL)) == NULL) {
3226                                 die("XOpenIM failed. Could not open input"
3227                                         " device.\n");
3228                         }
3229                 }
3230         }
3231         xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
3232                                            | XIMStatusNothing, XNClientWindow, xw.win,
3233                                            XNFocusWindow, xw.win, NULL);
3234         if(xw.xic == NULL)
3235                 die("XCreateIC failed. Could not obtain input method.\n");
3236
3237         /* white cursor, black outline */
3238         cursor = XCreateFontCursor(xw.dpy, XC_xterm);
3239         XDefineCursor(xw.dpy, xw.win, cursor);
3240         XRecolorCursor(xw.dpy, cursor,
3241                 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
3242                 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
3243
3244         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
3245         xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
3246         xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
3247         XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
3248
3249         xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
3250         XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
3251                         PropModeReplace, (uchar *)&thispid, 1);
3252
3253         xresettitle();
3254         XMapWindow(xw.dpy, xw.win);
3255         xhints();
3256         XSync(xw.dpy, False);
3257 }
3258
3259 void
3260 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
3261         int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
3262             width = charlen * xw.cw, xp, i;
3263         int frcflags, charexists;
3264         int u8fl, u8fblen, u8cblen, doesexist;
3265         char *u8c, *u8fs;
3266         long unicodep;
3267         Font *font = &dc.font;
3268         FcResult fcres;
3269         FcPattern *fcpattern, *fontpattern;
3270         FcFontSet *fcsets[] = { NULL };
3271         FcCharSet *fccharset;
3272         Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
3273         XRenderColor colfg, colbg;
3274         XRectangle r;
3275         int oneatatime;
3276
3277         frcflags = FRC_NORMAL;
3278
3279         if(base.mode & ATTR_ITALIC) {
3280                 if(base.fg == defaultfg)
3281                         base.fg = defaultitalic;
3282                 font = &dc.ifont;
3283                 frcflags = FRC_ITALIC;
3284         } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
3285                 if(base.fg == defaultfg)
3286                         base.fg = defaultitalic;
3287                 font = &dc.ibfont;
3288                 frcflags = FRC_ITALICBOLD;
3289         } else if(base.mode & ATTR_UNDERLINE) {
3290                 if(base.fg == defaultfg)
3291                         base.fg = defaultunderline;
3292         }
3293
3294         if(IS_TRUECOL(base.fg)) {
3295                 colfg.alpha = 0xffff;
3296                 colfg.red = TRUERED(base.fg);
3297                 colfg.green = TRUEGREEN(base.fg);
3298                 colfg.blue = TRUEBLUE(base.fg);
3299                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
3300                 fg = &truefg;
3301         } else {
3302                 fg = &dc.col[base.fg];
3303         }
3304
3305         if(IS_TRUECOL(base.bg)) {
3306                 colbg.alpha = 0xffff;
3307                 colbg.green = TRUEGREEN(base.bg);
3308                 colbg.red = TRUERED(base.bg);
3309                 colbg.blue = TRUEBLUE(base.bg);
3310                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
3311                 bg = &truebg;
3312         } else {
3313                 bg = &dc.col[base.bg];
3314         }
3315
3316         if(base.mode & ATTR_BOLD) {
3317                 /*
3318                  * change basic system colors [0-7]
3319                  * to bright system colors [8-15]
3320                  */
3321                 if(BETWEEN(base.fg, 0, 7) && !(base.mode & ATTR_FAINT))
3322                         fg = &dc.col[base.fg + 8];
3323
3324                 if(base.mode & ATTR_ITALIC) {
3325                         font = &dc.ibfont;
3326                         frcflags = FRC_ITALICBOLD;
3327                 } else {
3328                         font = &dc.bfont;
3329                         frcflags = FRC_BOLD;
3330                 }
3331         }
3332
3333         if(IS_SET(MODE_REVERSE)) {
3334                 if(fg == &dc.col[defaultfg]) {
3335                         fg = &dc.col[defaultbg];
3336                 } else {
3337                         colfg.red = ~fg->color.red;
3338                         colfg.green = ~fg->color.green;
3339                         colfg.blue = ~fg->color.blue;
3340                         colfg.alpha = fg->color.alpha;
3341                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
3342                                         &revfg);
3343                         fg = &revfg;
3344                 }
3345
3346                 if(bg == &dc.col[defaultbg]) {
3347                         bg = &dc.col[defaultfg];
3348                 } else {
3349                         colbg.red = ~bg->color.red;
3350                         colbg.green = ~bg->color.green;
3351                         colbg.blue = ~bg->color.blue;
3352                         colbg.alpha = bg->color.alpha;
3353                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
3354                                         &revbg);
3355                         bg = &revbg;
3356                 }
3357         }
3358
3359         if(base.mode & ATTR_REVERSE) {
3360                 temp = fg;
3361                 fg = bg;
3362                 bg = temp;
3363         }
3364
3365         if(base.mode & ATTR_FAINT && !(base.mode & ATTR_BOLD)) {
3366                 colfg.red = fg->color.red / 2;
3367                 colfg.green = fg->color.green / 2;
3368                 colfg.blue = fg->color.blue / 2;
3369                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
3370                 fg = &revfg;
3371         }
3372
3373         if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3374                 fg = bg;
3375
3376         if(base.mode & ATTR_INVISIBLE)
3377                 fg = bg;
3378
3379         /* Intelligent cleaning up of the borders. */
3380         if(x == 0) {
3381                 xclear(0, (y == 0)? 0 : winy, borderpx,
3382                         winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3383         }
3384         if(x + charlen >= term.col) {
3385                 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3386                         ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3387         }
3388         if(y == 0)
3389                 xclear(winx, 0, winx + width, borderpx);
3390         if(y == term.row-1)
3391                 xclear(winx, winy + xw.ch, winx + width, xw.h);
3392
3393         /* Clean up the region we want to draw to. */
3394         XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3395
3396         /* Set the clip region because Xft is sometimes dirty. */
3397         r.x = 0;
3398         r.y = 0;
3399         r.height = xw.ch;
3400         r.width = width;
3401         XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3402
3403         for(xp = winx; bytelen > 0;) {
3404                 /*
3405                  * Search for the range in the to be printed string of glyphs
3406                  * that are in the main font. Then print that range. If
3407                  * some glyph is found that is not in the font, do the
3408                  * fallback dance.
3409                  */
3410                 u8fs = s;
3411                 u8fblen = 0;
3412                 u8fl = 0;
3413                 oneatatime = font->width != xw.cw;
3414                 for(;;) {
3415                         u8c = s;
3416                         u8cblen = utf8decode(s, &unicodep, UTF_SIZ);
3417                         s += u8cblen;
3418                         bytelen -= u8cblen;
3419
3420                         doesexist = XftCharExists(xw.dpy, font->match, unicodep);
3421                         if(doesexist) {
3422                                         u8fl++;
3423                                         u8fblen += u8cblen;
3424                                         if(!oneatatime && bytelen > 0)
3425                                                         continue;
3426                         }
3427
3428                         if(u8fl > 0) {
3429                                 XftDrawStringUtf8(xw.draw, fg,
3430                                                 font->match, xp,
3431                                                 winy + font->ascent,
3432                                                 (FcChar8 *)u8fs,
3433                                                 u8fblen);
3434                                 xp += xw.cw * u8fl;
3435                         }
3436                         break;
3437                 }
3438                 if(doesexist) {
3439                         if(oneatatime)
3440                                 continue;
3441                         break;
3442                 }
3443
3444                 /* Search the font cache. */
3445                 for(i = 0; i < frclen; i++) {
3446                         charexists = XftCharExists(xw.dpy, frc[i].font, unicodep);
3447                         /* Everything correct. */
3448                         if(charexists && frc[i].flags == frcflags)
3449                                 break;
3450                         /* We got a default font for a not found glyph. */
3451                         if(!charexists && frc[i].flags == frcflags \
3452                                         && frc[i].unicodep == unicodep) {
3453                                 break;
3454                         }
3455                 }
3456
3457                 /* Nothing was found. */
3458                 if(i >= frclen) {
3459                         if(!font->set)
3460                                 xloadfontset(font);
3461                         fcsets[0] = font->set;
3462
3463                         /*
3464                          * Nothing was found in the cache. Now use
3465                          * some dozen of Fontconfig calls to get the
3466                          * font for one single character.
3467                          *
3468                          * Xft and fontconfig are design failures.
3469                          */
3470                         fcpattern = FcPatternDuplicate(font->pattern);
3471                         fccharset = FcCharSetCreate();
3472
3473                         FcCharSetAddChar(fccharset, unicodep);
3474                         FcPatternAddCharSet(fcpattern, FC_CHARSET,
3475                                         fccharset);
3476                         FcPatternAddBool(fcpattern, FC_SCALABLE,
3477                                         FcTrue);
3478
3479                         FcConfigSubstitute(0, fcpattern,
3480                                         FcMatchPattern);
3481                         FcDefaultSubstitute(fcpattern);
3482
3483                         fontpattern = FcFontSetMatch(0, fcsets, 1,
3484                                         fcpattern, &fcres);
3485
3486                         /*
3487                          * Overwrite or create the new cache entry.
3488                          */
3489                         if(frclen >= LEN(frc)) {
3490                                 frclen = LEN(frc) - 1;
3491                                 XftFontClose(xw.dpy, frc[frclen].font);
3492                                 frc[frclen].unicodep = 0;
3493                         }
3494
3495                         frc[frclen].font = XftFontOpenPattern(xw.dpy,
3496                                         fontpattern);
3497                         frc[frclen].flags = frcflags;
3498                         frc[frclen].unicodep = unicodep;
3499
3500                         i = frclen;
3501                         frclen++;
3502
3503                         FcPatternDestroy(fcpattern);
3504                         FcCharSetDestroy(fccharset);
3505                 }
3506
3507                 XftDrawStringUtf8(xw.draw, fg, frc[i].font,
3508                                 xp, winy + frc[i].font->ascent,
3509                                 (FcChar8 *)u8c, u8cblen);
3510
3511                 xp += xw.cw * wcwidth(unicodep);
3512         }
3513
3514         /*
3515          * This is how the loop above actually should be. Why does the
3516          * application have to care about font details?
3517          *
3518          * I have to repeat: Xft and Fontconfig are design failures.
3519          */
3520         /*
3521         XftDrawStringUtf8(xw.draw, fg, font->set, winx,
3522                         winy + font->ascent, (FcChar8 *)s, bytelen);
3523         */
3524
3525         if(base.mode & ATTR_UNDERLINE) {
3526                 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
3527                                 width, 1);
3528         }
3529
3530         if(base.mode & ATTR_STRUCK) {
3531                 XftDrawRect(xw.draw, fg, winx, winy + 2 * font->ascent / 3,
3532                                 width, 1);
3533         }
3534
3535         /* Reset clip to none. */
3536         XftDrawSetClip(xw.draw, 0);
3537 }
3538
3539 void
3540 xdrawcursor(void) {
3541         static int oldx = 0, oldy = 0;
3542         int sl, width, curx;
3543         Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
3544
3545         LIMIT(oldx, 0, term.col-1);
3546         LIMIT(oldy, 0, term.row-1);
3547
3548         curx = term.c.x;
3549
3550         /* adjust position if in dummy */
3551         if(term.line[oldy][oldx].mode & ATTR_WDUMMY)
3552                 oldx--;
3553         if(term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3554                 curx--;
3555
3556         memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
3557
3558         /* remove the old cursor */
3559         sl = utf8len(term.line[oldy][oldx].c);
3560         width = (term.line[oldy][oldx].mode & ATTR_WIDE)? 2 : 1;
3561         xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
3562                         oldy, width, sl);
3563
3564         if(IS_SET(MODE_HIDE))
3565                 return;
3566
3567         /* draw the new one */
3568         if(xw.state & WIN_FOCUSED) {
3569                 switch (xw.cursor) {
3570                         case 0: /* Blinking Block */
3571                         case 1: /* Blinking Block (Default) */
3572                         case 2: /* Steady Block */
3573                                 if(IS_SET(MODE_REVERSE)) {
3574                                                 g.mode |= ATTR_REVERSE;
3575                                                 g.fg = defaultcs;
3576                                                 g.bg = defaultfg;
3577                                         }
3578
3579                                 sl = utf8len(g.c);
3580                                 width = (term.line[term.c.y][curx].mode & ATTR_WIDE)\
3581                                         ? 2 : 1;
3582                                 xdraws(g.c, g, term.c.x, term.c.y, width, sl);
3583                                 break;
3584                         case 3: /* Blinking Underline */
3585                         case 4: /* Steady Underline */
3586                                 XftDrawRect(xw.draw, &dc.col[defaultcs],
3587                                                 borderpx + curx * xw.cw,
3588                                                 borderpx + (term.c.y + 1) * xw.ch - 1,
3589                                                 xw.cw, 1);
3590                                 break;
3591                         case 5: /* Blinking bar */
3592                         case 6: /* Steady bar */
3593                                 XftDrawRect(xw.draw, &dc.col[defaultcs],
3594                                                                 borderpx + curx * xw.cw,
3595                                                                 borderpx + term.c.y * xw.ch,
3596                                                                 1, xw.ch);
3597                                 break;
3598                 }
3599         } else {
3600                 XftDrawRect(xw.draw, &dc.col[defaultcs],
3601                                 borderpx + curx * xw.cw,
3602                                 borderpx + term.c.y * xw.ch,
3603                                 xw.cw - 1, 1);
3604                 XftDrawRect(xw.draw, &dc.col[defaultcs],
3605                                 borderpx + curx * xw.cw,
3606                                 borderpx + term.c.y * xw.ch,
3607                                 1, xw.ch - 1);
3608                 XftDrawRect(xw.draw, &dc.col[defaultcs],
3609                                 borderpx + (curx + 1) * xw.cw - 1,
3610                                 borderpx + term.c.y * xw.ch,
3611                                 1, xw.ch - 1);
3612                 XftDrawRect(xw.draw, &dc.col[defaultcs],
3613                                 borderpx + curx * xw.cw,
3614                                 borderpx + (term.c.y + 1) * xw.ch - 1,
3615                                 xw.cw, 1);
3616         }
3617         oldx = curx, oldy = term.c.y;
3618 }
3619
3620
3621 void
3622 xsettitle(char *p) {
3623         XTextProperty prop;
3624
3625         Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3626                         &prop);
3627         XSetWMName(xw.dpy, xw.win, &prop);
3628         XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
3629         XFree(prop.value);
3630 }
3631
3632 void
3633 xresettitle(void) {
3634         xsettitle(opt_title ? opt_title : "st");
3635 }
3636
3637 void
3638 redraw(void) {
3639         tfulldirt();
3640         draw();
3641 }
3642
3643 void
3644 draw(void) {
3645         drawregion(0, 0, term.col, term.row);
3646         XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3647                         xw.h, 0, 0);
3648         XSetForeground(xw.dpy, dc.gc,
3649                         dc.col[IS_SET(MODE_REVERSE)?
3650                                 defaultfg : defaultbg].pixel);
3651 }
3652
3653 void
3654 drawregion(int x1, int y1, int x2, int y2) {
3655         int ic, ib, x, y, ox, sl;
3656         Glyph base, new;
3657         char buf[DRAW_BUF_SIZ];
3658         bool ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
3659         long unicodep;
3660
3661         if(!(xw.state & WIN_VISIBLE))
3662                 return;
3663
3664         for(y = y1; y < y2; y++) {
3665                 if(!term.dirty[y])
3666                         continue;
3667
3668                 xtermclear(0, y, term.col, y);
3669                 term.dirty[y] = 0;
3670                 base = term.line[y][0];
3671                 ic = ib = ox = 0;
3672                 for(x = x1; x < x2; x++) {
3673                         new = term.line[y][x];
3674                         if(new.mode == ATTR_WDUMMY)
3675                                 continue;
3676                         if(ena_sel && selected(x, y))
3677                                 new.mode ^= ATTR_REVERSE;
3678                         if(ib > 0 && (ATTRCMP(base, new)
3679                                         || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3680                                 xdraws(buf, base, ox, y, ic, ib);
3681                                 ic = ib = 0;
3682                         }
3683                         if(ib == 0) {
3684                                 ox = x;
3685                                 base = new;
3686                         }
3687
3688                         sl = utf8decode(new.c, &unicodep, UTF_SIZ);
3689                         memcpy(buf+ib, new.c, sl);
3690                         ib += sl;
3691                         ic += (new.mode & ATTR_WIDE)? 2 : 1;
3692                 }
3693                 if(ib > 0)
3694                         xdraws(buf, base, ox, y, ic, ib);
3695         }
3696         xdrawcursor();
3697 }
3698
3699 void
3700 expose(XEvent *ev) {
3701         XExposeEvent *e = &ev->xexpose;
3702
3703         if(xw.state & WIN_REDRAW) {
3704                 if(!e->count)
3705                         xw.state &= ~WIN_REDRAW;
3706         }
3707         redraw();
3708 }
3709
3710 void
3711 visibility(XEvent *ev) {
3712         XVisibilityEvent *e = &ev->xvisibility;
3713
3714         if(e->state == VisibilityFullyObscured) {
3715                 xw.state &= ~WIN_VISIBLE;
3716         } else if(!(xw.state & WIN_VISIBLE)) {
3717                 /* need a full redraw for next Expose, not just a buf copy */
3718                 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3719         }
3720 }
3721
3722 void
3723 unmap(XEvent *ev) {
3724         xw.state &= ~WIN_VISIBLE;
3725 }
3726
3727 void
3728 xsetpointermotion(int set) {
3729         MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3730         XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3731 }
3732
3733 void
3734 xseturgency(int add) {
3735         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3736
3737         MODBIT(h->flags, add, XUrgencyHint);
3738         XSetWMHints(xw.dpy, xw.win, h);
3739         XFree(h);
3740 }
3741
3742 void
3743 focus(XEvent *ev) {
3744         XFocusChangeEvent *e = &ev->xfocus;
3745
3746         if(e->mode == NotifyGrab)
3747                 return;
3748
3749         if(ev->type == FocusIn) {
3750                 XSetICFocus(xw.xic);
3751                 xw.state |= WIN_FOCUSED;
3752                 xseturgency(0);
3753                 if(IS_SET(MODE_FOCUS))
3754                         ttywrite("\033[I", 3);
3755         } else {
3756                 XUnsetICFocus(xw.xic);
3757                 xw.state &= ~WIN_FOCUSED;
3758                 if(IS_SET(MODE_FOCUS))
3759                         ttywrite("\033[O", 3);
3760         }
3761 }
3762
3763 static inline bool
3764 match(uint mask, uint state) {
3765         return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
3766 }
3767
3768 void
3769 numlock(const Arg *dummy) {
3770         term.numlock ^= 1;
3771 }
3772
3773 char*
3774 kmap(KeySym k, uint state) {
3775         Key *kp;
3776         int i;
3777
3778         /* Check for mapped keys out of X11 function keys. */
3779         for(i = 0; i < LEN(mappedkeys); i++) {
3780                 if(mappedkeys[i] == k)
3781                         break;
3782         }
3783         if(i == LEN(mappedkeys)) {
3784                 if((k & 0xFFFF) < 0xFD00)
3785                         return NULL;
3786         }
3787
3788         for(kp = key; kp < key + LEN(key); kp++) {
3789                 if(kp->k != k)
3790                         continue;
3791
3792                 if(!match(kp->mask, state))
3793                         continue;
3794
3795                 if(IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
3796                         continue;
3797                 if(term.numlock && kp->appkey == 2)
3798                         continue;
3799
3800                 if(IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
3801                         continue;
3802
3803                 if(IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
3804                         continue;
3805
3806                 return kp->s;
3807         }
3808
3809         return NULL;
3810 }
3811
3812 void
3813 kpress(XEvent *ev) {
3814         XKeyEvent *e = &ev->xkey;
3815         KeySym ksym;
3816         char buf[32], *customkey;
3817         int len;
3818         long c;
3819         Status status;
3820         Shortcut *bp;
3821
3822         if(IS_SET(MODE_KBDLOCK))
3823                 return;
3824
3825         len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
3826         /* 1. shortcuts */
3827         for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3828                 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3829                         bp->func(&(bp->arg));
3830                         return;
3831                 }
3832         }
3833
3834         /* 2. custom keys from config.h */
3835         if((customkey = kmap(ksym, e->state))) {
3836                 ttysend(customkey, strlen(customkey));
3837                 return;
3838         }
3839
3840         /* 3. composed string from input method */
3841         if(len == 0)
3842                 return;
3843         if(len == 1 && e->state & Mod1Mask) {
3844                 if(IS_SET(MODE_8BIT)) {
3845                         if(*buf < 0177) {
3846                                 c = *buf | 0x80;
3847                                 len = utf8encode(c, buf, UTF_SIZ);
3848                         }
3849                 } else {
3850                         buf[1] = buf[0];
3851                         buf[0] = '\033';
3852                         len = 2;
3853                 }
3854         }
3855         ttysend(buf, len);
3856 }
3857
3858
3859 void
3860 cmessage(XEvent *e) {
3861         /*
3862          * See xembed specs
3863          *  http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3864          */
3865         if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3866                 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3867                         xw.state |= WIN_FOCUSED;
3868                         xseturgency(0);
3869                 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3870                         xw.state &= ~WIN_FOCUSED;
3871                 }
3872         } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3873                 /* Send SIGHUP to shell */
3874                 kill(pid, SIGHUP);
3875                 exit(EXIT_SUCCESS);
3876         }
3877 }
3878
3879 void
3880 cresize(int width, int height) {
3881         int col, row;
3882
3883         if(width != 0)
3884                 xw.w = width;
3885         if(height != 0)
3886                 xw.h = height;
3887
3888         col = (xw.w - 2 * borderpx) / xw.cw;
3889         row = (xw.h - 2 * borderpx) / xw.ch;
3890
3891         tresize(col, row);
3892         xresize(col, row);
3893         ttyresize();
3894 }
3895
3896 void
3897 resize(XEvent *e) {
3898         if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3899                 return;
3900
3901         cresize(e->xconfigure.width, e->xconfigure.height);
3902 }
3903
3904 void
3905 run(void) {
3906         XEvent ev;
3907         int w = xw.w, h = xw.h;
3908         fd_set rfd;
3909         int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3910         struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
3911         long deltatime;
3912
3913         /* Waiting for window mapping */
3914         while(1) {
3915                 XNextEvent(xw.dpy, &ev);
3916                 if(XFilterEvent(&ev, None))
3917                         continue;
3918                 if(ev.type == ConfigureNotify) {
3919                         w = ev.xconfigure.width;
3920                         h = ev.xconfigure.height;
3921                 } else if(ev.type == MapNotify) {
3922                         break;
3923                 }
3924         }
3925
3926         ttynew();
3927         cresize(w, h);
3928
3929         clock_gettime(CLOCK_MONOTONIC, &last);
3930         lastblink = last;
3931
3932         for(xev = actionfps;;) {
3933                 FD_ZERO(&rfd);
3934                 FD_SET(cmdfd, &rfd);
3935                 FD_SET(xfd, &rfd);
3936
3937                 if(pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
3938                         if(errno == EINTR)
3939                                 continue;
3940                         die("select failed: %s\n", strerror(errno));
3941                 }
3942                 if(FD_ISSET(cmdfd, &rfd)) {
3943                         ttyread();
3944                         if(blinktimeout) {
3945                                 blinkset = tattrset(ATTR_BLINK);
3946                                 if(!blinkset)
3947                                         MODBIT(term.mode, 0, MODE_BLINK);
3948                         }
3949                 }
3950
3951                 if(FD_ISSET(xfd, &rfd))
3952                         xev = actionfps;
3953
3954                 clock_gettime(CLOCK_MONOTONIC, &now);
3955                 drawtimeout.tv_sec = 0;
3956                 drawtimeout.tv_nsec = (1000/xfps) * 1E6;
3957                 tv = &drawtimeout;
3958
3959                 dodraw = 0;
3960                 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3961                         tsetdirtattr(ATTR_BLINK);
3962                         term.mode ^= MODE_BLINK;
3963                         lastblink = now;
3964                         dodraw = 1;
3965                 }
3966                 deltatime = TIMEDIFF(now, last);
3967                 if(deltatime > (xev? (1000/xfps) : (1000/actionfps))
3968                                 || deltatime < 0) {
3969                         dodraw = 1;
3970                         last = now;
3971                 }
3972
3973                 if(dodraw) {
3974                         while(XPending(xw.dpy)) {
3975                                 XNextEvent(xw.dpy, &ev);
3976                                 if(XFilterEvent(&ev, None))
3977                                         continue;
3978                                 if(handler[ev.type])
3979                                         (handler[ev.type])(&ev);
3980                         }
3981
3982                         draw();
3983                         XFlush(xw.dpy);
3984
3985                         if(xev && !FD_ISSET(xfd, &rfd))
3986                                 xev--;
3987                         if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3988                                 if(blinkset) {
3989                                         if(TIMEDIFF(now, lastblink) \
3990                                                         > blinktimeout) {
3991                                                 drawtimeout.tv_nsec = 1000;
3992                                         } else {
3993                                                 drawtimeout.tv_nsec = (1E6 * \
3994                                                         (blinktimeout - \
3995                                                         TIMEDIFF(now,
3996                                                                 lastblink)));
3997                                         }
3998                                         drawtimeout.tv_sec = \
3999                                             drawtimeout.tv_nsec / 1E9;
4000                                         drawtimeout.tv_nsec %= (long)1E9;
4001                                 } else {
4002                                         tv = NULL;
4003                                 }
4004                         }
4005                 }
4006         }
4007 }
4008
4009 void
4010 usage(void) {
4011         die("%s " VERSION " (c) 2010-2015 st engineers\n" \
4012         "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]\n"
4013         "          [-i] [-t title] [-w windowid] [-e command ...]\n", argv0);
4014 }
4015
4016 int
4017 main(int argc, char *argv[]) {
4018         char *titles;
4019         uint cols = 80, rows = 24;
4020
4021         xw.l = xw.t = 0;
4022         xw.isfixed = False;
4023         xw.cursor = 0;
4024
4025         ARGBEGIN {
4026         case 'a':
4027                 allowaltscreen = false;
4028                 break;
4029         case 'c':
4030                 opt_class = EARGF(usage());
4031                 break;
4032         case 'e':
4033                 /* eat all remaining arguments */
4034                 if(argc > 1) {
4035                         opt_cmd = &argv[1];
4036                         if(argv[1] != NULL && opt_title == NULL) {
4037                                 titles = xstrdup(argv[1]);
4038                                 opt_title = basename(titles);
4039                         }
4040                 }
4041                 goto run;
4042         case 'f':
4043                 opt_font = EARGF(usage());
4044                 break;
4045         case 'g':
4046                 xw.gm = XParseGeometry(EARGF(usage()),
4047                                 &xw.l, &xw.t, &cols, &rows);
4048                 break;
4049         case 'i':
4050                 xw.isfixed = True;
4051                 break;
4052         case 'o':
4053                 opt_io = EARGF(usage());
4054                 break;
4055         case 't':
4056                 opt_title = EARGF(usage());
4057                 break;
4058         case 'w':
4059                 opt_embed = EARGF(usage());
4060                 break;
4061         case 'v':
4062         default:
4063                 usage();
4064         } ARGEND;
4065
4066 run:
4067         setlocale(LC_CTYPE, "");
4068         XSetLocaleModifiers("");
4069         tnew(cols? cols : 1, rows? rows : 1);
4070         xinit();
4071         selinit();
4072         run();
4073
4074         return 0;
4075 }
4076