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