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