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