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