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