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