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