1 /* See LICENSE for license details. */
14 #include <sys/ioctl.h>
15 #include <sys/select.h>
18 #include <sys/types.h>
23 #include <X11/Xatom.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>
42 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
44 #elif defined(__FreeBSD__) || defined(__DragonFly__)
50 #define XEMBED_FOCUS_IN 4
51 #define XEMBED_FOCUS_OUT 5
54 #define UTF_INVALID 0xFFFD
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
62 #define XK_SWITCH_MOD (1<<13)
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)))
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)
87 enum glyph_attribute {
92 ATTR_UNDERLINE = 1 << 3,
94 ATTR_REVERSE = 1 << 5,
95 ATTR_INVISIBLE = 1 << 6,
99 ATTR_WDUMMY = 1 << 10,
100 ATTR_BOLD_FAINT = ATTR_BOLD | ATTR_FAINT,
103 enum cursor_movement {
116 MODE_INSERT = 1 << 1,
117 MODE_APPKEYPAD = 1 << 2,
118 MODE_ALTSCREEN = 1 << 3,
120 MODE_MOUSEBTN = 1 << 5,
121 MODE_MOUSEMOTION = 1 << 6,
122 MODE_REVERSE = 1 << 7,
123 MODE_KBDLOCK = 1 << 8,
126 MODE_APPCURSOR = 1 << 11,
127 MODE_MOUSESGR = 1 << 12,
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\
153 ESC_STR = 4, /* DCS, OSC, PM, APC */
155 ESC_STR_END = 16, /* a final string was encountered */
156 ESC_TEST = 32, /* Enter in test mode */
164 enum selection_mode {
170 enum selection_type {
175 enum selection_snap {
180 typedef unsigned char uchar;
181 typedef unsigned int uint;
182 typedef unsigned long ulong;
183 typedef unsigned short ushort;
185 typedef uint_least32_t Rune;
187 typedef XftDraw *Draw;
188 typedef XftColor Color;
191 Rune u; /* character code */
192 ushort mode; /* attribute flags */
193 uint32_t fg; /* foreground */
194 uint32_t bg; /* background */
200 Glyph attr; /* current char attributes */
206 /* CSI Escape sequence structs */
207 /* ESC '[' [[ [<priv>] <arg> [;]] <mode> [<mode>]] */
209 char buf[ESC_BUF_SIZ]; /* raw string */
210 int len; /* raw string length */
212 int arg[ESC_ARG_SIZ];
213 int narg; /* nb of args */
217 /* STR Escape sequence structs */
218 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
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 */
227 /* Internal representation of the screen */
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 */
247 /* Purely graphic info */
253 Atom xembed, wmdeletewin, netwmname, netwmpid;
258 XSetWindowAttributes attrs;
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 */
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 */
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
302 char *primary, *clipboard;
305 struct timespec tclick1;
306 struct timespec tclick2;
319 void (*func)(const Arg *);
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 *);
335 /* Config.h for applying patches and the configuration. */
351 /* Drawing Context */
353 Color col[MAX(LEN(colorname), 256)];
354 Font font, bfont, ifont, ibfont;
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);
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);
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);
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);
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 *);
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 *);
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);
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 *);
483 static void usage(void);
485 static void (*handler[LASTEvent])(XEvent *) = {
487 [ClientMessage] = cmessage,
488 [ConfigureNotify] = resize,
489 [VisibilityNotify] = visibility,
490 [UnmapNotify] = unmap,
494 [MotionNotify] = bmotion,
495 [ButtonPress] = bpress,
496 [ButtonRelease] = brelease,
498 * Uncomment if you want the selection to disappear when you select something
499 * different in another window.
501 /* [SelectionClear] = selclear, */
502 [SelectionNotify] = selnotify,
503 [SelectionRequest] = selrequest,
510 static CSIEscape csiescseq;
511 static STREscape strescseq;
514 static Selection sel;
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 */
525 static char *usedfont = NULL;
526 static double usedfontsize = 0;
527 static double defaultfontsize = 0;
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};
534 /* Font Ring Cache */
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;
553 xwrite(int fd, const char *s, size_t len) {
557 ssize_t r = write(fd, s, len);
567 xmalloc(size_t len) {
568 void *p = malloc(len);
571 die("Out of memory\n");
577 xrealloc(void *p, size_t len) {
578 if((p = realloc(p, len)) == NULL)
579 die("Out of memory\n");
586 if((s = strdup(s)) == NULL)
587 die("Out of memory\n");
593 utf8decode(char *c, Rune *u, size_t clen) {
594 size_t i, j, len, type;
600 udecoded = utf8decodebyte(c[0], &len);
601 if(!BETWEEN(len, 1, UTF_SIZ))
603 for(i = 1, j = 1; i < clen && j < len; ++i, ++j) {
604 udecoded = (udecoded << 6) | utf8decodebyte(c[i], &type);
611 utf8validate(u, len);
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];
624 utf8encode(Rune u, char *c) {
627 len = utf8validate(&u, 0);
630 for(i = len - 1; i != 0; --i) {
631 c[i] = utf8encodebyte(u, 0);
634 c[0] = utf8encodebyte(u, len);
639 utf8encodebyte(Rune u, size_t i) {
640 return utfbyte[i] | (u & ~utfmask[i]);
644 utf8strchr(char *s, Rune u) {
649 for(i = 0, j = 0; i < len; i += j) {
650 if(!(j = utf8decode(&s[i], &r, len - i)))
659 utf8validate(Rune *u, size_t i) {
660 if(!BETWEEN(*u, utfmin[i], utfmax[i]) || BETWEEN(*u, 0xD800, 0xDFFF))
662 for(i = 1; *u > utfmax[i]; ++i)
669 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
670 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
674 sel.clipboard = NULL;
675 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
676 if(sel.xtarget == None)
677 sel.xtarget = XA_STRING;
685 return LIMIT(x, 0, term.col-1);
693 return LIMIT(y, 0, term.row-1);
700 if(term.line[y][i - 1].mode & ATTR_WRAP)
703 while(i > 0 && term.line[y][i - 1].u == ' ')
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;
717 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
718 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
720 sel.nb.y = MIN(sel.ob.y, sel.oe.y);
721 sel.ne.y = MAX(sel.ob.y, sel.oe.y);
723 selsnap(&sel.nb.x, &sel.nb.y, -1);
724 selsnap(&sel.ne.x, &sel.ne.y, +1);
726 /* expand selection over line breaks */
727 if (sel.type == SEL_RECTANGULAR)
729 i = tlinelen(sel.nb.y);
732 if (tlinelen(sel.ne.y) <= sel.ne.x)
733 sel.ne.x = term.col - 1;
737 selected(int x, int y) {
738 if(sel.mode == SEL_EMPTY)
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);
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);
751 selsnap(int *x, int *y, int direction) {
752 int newx, newy, xt, yt;
753 int delim, prevdelim;
759 * Snap around if the word wraps around at the end or
760 * beginning of a line.
762 prevgp = &term.line[*y][*x];
763 prevdelim = ISDELIM(prevgp->u);
765 newx = *x + direction;
767 if(!BETWEEN(newx, 0, term.col - 1)) {
769 newx = (newx + term.col) % term.col;
770 if (!BETWEEN(newy, 0, term.row - 1))
776 yt = newy, xt = newx;
777 if(!(term.line[yt][xt].mode & ATTR_WRAP))
781 if (newx >= tlinelen(newy))
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)))
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.
802 *x = (direction < 0) ? 0 : term.col - 1;
804 for(; *y > 0; *y += direction) {
805 if(!(term.line[*y-1][term.col-1].mode
810 } else if(direction > 0) {
811 for(; *y < term.row-1; *y += direction) {
812 if(!(term.line[*y][term.col-1].mode
823 getbuttoninfo(XEvent *e) {
825 uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
827 sel.alt = IS_SET(MODE_ALTSCREEN);
829 sel.oe.x = x2col(e->xbutton.x);
830 sel.oe.y = y2row(e->xbutton.y);
833 sel.type = SEL_REGULAR;
834 for(type = 1; type < LEN(selmasks); ++type) {
835 if(match(selmasks[type], state)) {
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,
851 if(e->xbutton.type == MotionNotify) {
852 if(x == ox && y == oy)
854 if(!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
856 /* MOUSE_MOTION: no reporting if no button is pressed */
857 if(IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
860 button = oldbutton + 32;
864 if(!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
871 if(e->xbutton.type == ButtonPress) {
875 } else if(e->xbutton.type == ButtonRelease) {
877 /* MODE_MOUSEX10: no button release reporting */
878 if(IS_SET(MODE_MOUSEX10))
880 if (button == 64 || button == 65)
885 if(!IS_SET(MODE_MOUSEX10)) {
886 button += ((state & ShiftMask ) ? 4 : 0)
887 + ((state & Mod4Mask ) ? 8 : 0)
888 + ((state & ControlMask) ? 16 : 0);
891 if(IS_SET(MODE_MOUSESGR)) {
892 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
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);
910 if(IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
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));
923 if(e->xbutton.button == Button1) {
924 clock_gettime(CLOCK_MONOTONIC, &now);
926 /* Clear previous selection, logically and visually. */
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);
934 * If the user clicks below predefined timeouts specific
935 * snapping behaviour is exposed.
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;
947 sel.mode = SEL_READY;
948 tsetdirt(sel.nb.y, sel.ne.y);
949 sel.tclick2 = sel.tclick1;
957 int y, bufsize, lastx, linelen;
963 bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
964 ptr = str = xmalloc(bufsize);
966 /* append every set & selected glyph to the selection */
967 for(y = sel.nb.y; y <= sel.ne.y; y++) {
968 linelen = tlinelen(y);
970 if(sel.type == SEL_RECTANGULAR) {
971 gp = &term.line[y][sel.nb.x];
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;
977 last = &term.line[y][MIN(lastx, linelen-1)];
978 while(last >= gp && last->u == ' ')
981 for( ; gp <= last; ++gp) {
982 if(gp->mode & ATTR_WDUMMY)
985 ptr += utf8encode(gp->u, ptr);
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
995 * FIXME: Fix the computer world.
997 if((y < sel.ne.y || lastx >= linelen) && !(last->mode & ATTR_WRAP))
1006 xsetsel(getsel(), t);
1010 selnotify(XEvent *e) {
1011 ulong nitems, ofs, rem;
1013 uchar *data, *last, *repl;
1015 XSelectionEvent *xsev;
1018 xsev = &e->xselection;
1019 if (xsev->property == None)
1022 if(XGetWindowProperty(xw.dpy, xw.win, xsev->property, ofs,
1023 BUFSIZ/4, False, AnyPropertyType,
1024 &type, &format, &nitems, &rem,
1026 fprintf(stderr, "Clipboard allocation failed\n");
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.
1038 last = data + nitems * format / 8;
1039 while((repl = memchr(repl, '\n', last - repl))) {
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);
1049 /* number of 32-bit chunks returned */
1050 ofs += nitems * format / 32;
1055 selpaste(const Arg *dummy) {
1056 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1057 xw.win, CurrentTime);
1061 clipcopy(const Arg *dummy) {
1064 if(sel.clipboard != NULL)
1065 free(sel.clipboard);
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);
1075 clippaste(const Arg *dummy) {
1078 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1079 XConvertSelection(xw.dpy, clipboard, sel.xtarget, clipboard,
1080 xw.win, CurrentTime);
1084 selclear(XEvent *e) {
1087 sel.mode = SEL_IDLE;
1089 tsetdirt(sel.nb.y, sel.ne.y);
1093 selrequest(XEvent *e) {
1094 XSelectionRequestEvent *xsre;
1095 XSelectionEvent xev;
1096 Atom xa_targets, string, clipboard;
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;
1109 xev.property = None;
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) {
1121 * xith XA_STRING non ascii characters may be incorrect in the
1122 * requestor. It is not our problem, use utf8.
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;
1131 "Unhandled clipboard selection 0x%lx\n",
1135 if(seltext != NULL) {
1136 XChangeProperty(xsre->display, xsre->requestor,
1137 xsre->property, xsre->target,
1139 (uchar *)seltext, strlen(seltext));
1140 xev.property = xsre->property;
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");
1150 xsetsel(char *str, Time t) {
1154 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
1155 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
1160 brelease(XEvent *e) {
1161 if(IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
1166 if(e->xbutton.button == Button2) {
1168 } else if(e->xbutton.button == Button1) {
1169 if(sel.mode == SEL_READY) {
1171 selcopy(e->xbutton.time);
1174 sel.mode = SEL_IDLE;
1175 tsetdirt(sel.nb.y, sel.ne.y);
1180 bmotion(XEvent *e) {
1181 int oldey, oldex, oldsby, oldsey;
1183 if(IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
1191 sel.mode = SEL_READY;
1198 if(oldey != sel.oe.y || oldex != sel.oe.x)
1199 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1203 die(const char *errstr, ...) {
1206 va_start(ap, errstr);
1207 vfprintf(stderr, errstr, ap);
1214 char **args, *sh, *prog;
1215 const struct passwd *pw;
1216 char buf[sizeof(long) * 8 + 1];
1219 if((pw = getpwuid(getuid())) == NULL) {
1221 die("getpwuid:%s\n", strerror(errno));
1223 die("who are you?\n");
1226 if (!(sh = getenv("SHELL"))) {
1227 sh = (pw->pw_shell[0]) ? pw->pw_shell : shell;
1236 args = (opt_cmd) ? opt_cmd : (char *[]) {prog, NULL};
1238 snprintf(buf, sizeof(buf), "%lu", xw.win);
1240 unsetenv("COLUMNS");
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);
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);
1266 if((p = waitpid(pid, &stat, WNOHANG)) < 0)
1267 die("Waiting for pid %hd failed: %s\n", pid, strerror(errno));
1272 if (!WIFEXITED(stat) || WEXITSTATUS(stat))
1273 die("child finished with error '%d'\n", stat);
1281 char cmd[_POSIX_ARG_MAX], **p, *q, *s;
1284 if((n = strlen(stty_args)) > sizeof(cmd)-1)
1285 die("incorrect stty parameters\n");
1286 memcpy(cmd, stty_args, 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");
1293 q = memcpy(q, s, n);
1298 if (system(cmd) != 0)
1299 perror("Couldn't call stty");
1305 struct winsize w = {term.row, term.col, 0, 0};
1308 term.mode |= MODE_PRINT;
1309 iofd = (!strcmp(opt_io, "-")) ?
1310 1 : open(opt_io, O_WRONLY | O_CREAT, 0666);
1312 fprintf(stderr, "Error opening %s:%s\n",
1313 opt_io, strerror(errno));
1318 if((cmdfd = open(opt_line, O_RDWR)) < 0)
1319 die("open line failed: %s\n", strerror(errno));
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));
1330 switch(pid = fork()) {
1332 die("fork failed\n");
1336 setsid(); /* create a new process group */
1340 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1341 die("ioctl TIOCSCTTY failed: %s\n", strerror(errno));
1349 signal(SIGCHLD, sigchld);
1356 static char buf[BUFSIZ];
1357 static int buflen = 0;
1359 int charsize; /* size of utf8 char in bytes */
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));
1367 /* process every complete utf8 char */
1370 while((charsize = utf8decode(ptr, &unicodep, buflen))) {
1376 /* keep any uncomplete utf8 char for the next call */
1377 memmove(buf, ptr, buflen);
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));
1387 ttysend(char *s, size_t n) {
1392 if(IS_SET(MODE_ECHO))
1393 while((len = utf8decode(s, &u, n)) > 0) {
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));
1413 tattrset(int attr) {
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)
1427 tsetdirt(int top, int bot) {
1430 LIMIT(top, 0, term.row-1);
1431 LIMIT(bot, 0, term.row-1);
1433 for(i = top; i <= bot; i++)
1438 tsetdirtattr(int attr) {
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) {
1453 tsetdirt(0, term.row-1);
1458 static TCursor c[2];
1459 int alt = IS_SET(MODE_ALTSCREEN);
1461 if(mode == CURSOR_SAVE) {
1463 } else if(mode == CURSOR_LOAD) {
1465 tmoveto(c[alt].x, c[alt].y);
1473 term.c = (TCursor){{
1477 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1479 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1480 for(i = tabspaces; i < term.col; i += tabspaces)
1483 term.bot = term.row - 1;
1484 term.mode = MODE_WRAP;
1485 memset(term.trantbl, CS_USA, sizeof(term.trantbl));
1488 for(i = 0; i < 2; i++) {
1490 tcursor(CURSOR_SAVE);
1491 tclearregion(0, 0, term.col-1, term.row-1);
1497 tnew(int col, int row) {
1498 term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
1507 Line *tmp = term.line;
1509 term.line = term.alt;
1511 term.mode ^= MODE_ALTSCREEN;
1516 tscrolldown(int orig, int n) {
1520 LIMIT(n, 0, term.bot-orig+1);
1522 tsetdirt(orig, term.bot-n);
1523 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
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;
1535 tscrollup(int orig, int n) {
1539 LIMIT(n, 0, term.bot-orig+1);
1541 tclearregion(0, orig, term.col-1, orig+n-1);
1542 tsetdirt(orig+n, term.bot);
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;
1550 selscroll(orig, -n);
1554 selscroll(int orig, int n) {
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) {
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;
1569 if(sel.ob.y < term.top) {
1570 sel.ob.y = term.top;
1573 if(sel.oe.y > term.bot) {
1574 sel.oe.y = term.bot;
1575 sel.oe.x = term.col;
1583 tnewline(int first_col) {
1587 tscrollup(term.top, 1);
1591 tmoveto(first_col ? 0 : term.c.x, y);
1596 char *p = csiescseq.buf, *np;
1605 csiescseq.buf[csiescseq.len] = '\0';
1606 while(p < csiescseq.buf+csiescseq.len) {
1608 v = strtol(p, &np, 10);
1611 if(v == LONG_MAX || v == LONG_MIN)
1613 csiescseq.arg[csiescseq.narg++] = v;
1615 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1619 csiescseq.mode[0] = *p++;
1620 csiescseq.mode[1] = (p < csiescseq.buf+csiescseq.len) ? *p : '\0';
1623 /* for absolute user moves, when decom is set */
1625 tmoveato(int x, int y) {
1626 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1630 tmoveto(int x, int y) {
1633 if(term.c.state & CURSOR_ORIGIN) {
1638 maxy = term.row - 1;
1640 term.c.state &= ~CURSOR_WRAPNEXT;
1641 term.c.x = LIMIT(x, 0, term.col-1);
1642 term.c.y = LIMIT(y, miny, maxy);
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 - ~ */
1659 * The table is proudly stolen from rxvt.
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);
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;
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;
1676 term.line[y][x] = *attr;
1677 term.line[y][x].u = u;
1681 tclearregion(int x1, int y1, int x2, int y2) {
1686 temp = x1, x1 = x2, x2 = temp;
1688 temp = y1, y1 = y2, y2 = temp;
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);
1695 for(y = y1; y <= y2; y++) {
1697 for(x = x1; x <= x2; x++) {
1698 gp = &term.line[y][x];
1701 gp->fg = term.c.attr.fg;
1702 gp->bg = term.c.attr.bg;
1710 tdeletechar(int n) {
1714 LIMIT(n, 0, term.col - term.c.x);
1718 size = term.col - src;
1719 line = term.line[term.c.y];
1721 memmove(&line[dst], &line[src], size * sizeof(Glyph));
1722 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1726 tinsertblank(int n) {
1730 LIMIT(n, 0, term.col - term.c.x);
1734 size = term.col - dst;
1735 line = term.line[term.c.y];
1737 memmove(&line[dst], &line[src], size * sizeof(Glyph));
1738 tclearregion(src, term.c.y, dst - 1, term.c.y);
1742 tinsertblankline(int n) {
1743 if(BETWEEN(term.c.y, term.top, term.bot))
1744 tscrolldown(term.c.y, n);
1748 tdeleteline(int n) {
1749 if(BETWEEN(term.c.y, term.top, term.bot))
1750 tscrollup(term.c.y, n);
1754 tdefcolor(int *attr, int *npar, int l) {
1758 switch (attr[*npar + 1]) {
1759 case 2: /* direct color in RGB space */
1760 if (*npar + 4 >= l) {
1762 "erresc(38): Incorrect number of parameters (%d)\n",
1766 r = attr[*npar + 2];
1767 g = attr[*npar + 3];
1768 b = attr[*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",
1774 idx = TRUECOLOR(r, g, b);
1776 case 5: /* indexed color */
1777 if (*npar + 2 >= l) {
1779 "erresc(38): Incorrect number of parameters (%d)\n",
1784 if(!BETWEEN(attr[*npar], 0, 255))
1785 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
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 */
1795 "erresc(38): gfx attr %d unknown\n", attr[*npar]);
1803 tsetattr(int *attr, int l) {
1807 for(i = 0; i < l; i++) {
1810 term.c.attr.mode &= ~(
1819 term.c.attr.fg = defaultfg;
1820 term.c.attr.bg = defaultbg;
1823 term.c.attr.mode |= ATTR_BOLD;
1826 term.c.attr.mode |= ATTR_FAINT;
1829 term.c.attr.mode |= ATTR_ITALIC;
1832 term.c.attr.mode |= ATTR_UNDERLINE;
1834 case 5: /* slow blink */
1836 case 6: /* rapid blink */
1837 term.c.attr.mode |= ATTR_BLINK;
1840 term.c.attr.mode |= ATTR_REVERSE;
1843 term.c.attr.mode |= ATTR_INVISIBLE;
1846 term.c.attr.mode |= ATTR_STRUCK;
1849 term.c.attr.mode &= ~(ATTR_BOLD | ATTR_FAINT);
1852 term.c.attr.mode &= ~ATTR_ITALIC;
1855 term.c.attr.mode &= ~ATTR_UNDERLINE;
1858 term.c.attr.mode &= ~ATTR_BLINK;
1861 term.c.attr.mode &= ~ATTR_REVERSE;
1864 term.c.attr.mode &= ~ATTR_INVISIBLE;
1867 term.c.attr.mode &= ~ATTR_STRUCK;
1870 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1871 term.c.attr.fg = idx;
1874 term.c.attr.fg = defaultfg;
1877 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1878 term.c.attr.bg = idx;
1881 term.c.attr.bg = defaultbg;
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;
1894 "erresc(default): gfx attr %d unknown\n",
1895 attr[i]), csidump();
1903 tsetscroll(int t, int b) {
1906 LIMIT(t, 0, term.row-1);
1907 LIMIT(b, 0, term.row-1);
1918 tsetmode(int priv, int set, int *args, int narg) {
1922 for(lim = args + narg; args < lim; ++args) {
1925 case 1: /* DECCKM -- Cursor key */
1926 MODBIT(term.mode, set, MODE_APPCURSOR);
1928 case 5: /* DECSCNM -- Reverse video */
1930 MODBIT(term.mode, set, MODE_REVERSE);
1931 if(mode != term.mode)
1934 case 6: /* DECOM -- Origin */
1935 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1938 case 7: /* DECAWM -- Auto wrap */
1939 MODBIT(term.mode, set, MODE_WRAP);
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) */
1951 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1952 MODBIT(term.mode, !set, MODE_HIDE);
1954 case 9: /* X10 mouse compatibility mode */
1955 xsetpointermotion(0);
1956 MODBIT(term.mode, 0, MODE_MOUSE);
1957 MODBIT(term.mode, set, MODE_MOUSEX10);
1959 case 1000: /* 1000: report button press */
1960 xsetpointermotion(0);
1961 MODBIT(term.mode, 0, MODE_MOUSE);
1962 MODBIT(term.mode, set, MODE_MOUSEBTN);
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);
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);
1974 case 1004: /* 1004: send focus events to tty */
1975 MODBIT(term.mode, set, MODE_FOCUS);
1977 case 1006: /* 1006: extended reporting mode */
1978 MODBIT(term.mode, set, MODE_MOUSESGR);
1981 MODBIT(term.mode, set, MODE_8BIT);
1983 case 1049: /* swap screen & set/restore cursor as xterm */
1984 if (!allowaltscreen)
1986 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1988 case 47: /* swap screen */
1990 if (!allowaltscreen)
1992 alt = IS_SET(MODE_ALTSCREEN);
1994 tclearregion(0, 0, term.col-1,
1997 if(set ^ alt) /* set is always 1 or 0 */
2003 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
2005 case 2004: /* 2004: bracketed paste mode */
2006 MODBIT(term.mode, set, MODE_BRCKTPASTE);
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
2014 case 1015: /* urxvt mangled mouse mode; incompatible
2015 and can be mistaken for other control
2019 "erresc: unknown private set/reset mode %d\n",
2025 case 0: /* Error (IGNORED) */
2027 case 2: /* KAM -- keyboard action */
2028 MODBIT(term.mode, set, MODE_KBDLOCK);
2030 case 4: /* IRM -- Insertion-replacement */
2031 MODBIT(term.mode, set, MODE_INSERT);
2033 case 12: /* SRM -- Send/Receive */
2034 MODBIT(term.mode, !set, MODE_ECHO);
2036 case 20: /* LNM -- Linefeed/new line */
2037 MODBIT(term.mode, set, MODE_CRLF);
2041 "erresc: unknown set/reset mode %d\n",
2054 switch(csiescseq.mode[0]) {
2057 fprintf(stderr, "erresc: unknown csi ");
2061 case '@': /* ICH -- Insert <n> blank char */
2062 DEFAULT(csiescseq.arg[0], 1);
2063 tinsertblank(csiescseq.arg[0]);
2065 case 'A': /* CUU -- Cursor <n> Up */
2066 DEFAULT(csiescseq.arg[0], 1);
2067 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
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]);
2074 case 'i': /* MC -- Media Copy */
2075 switch(csiescseq.arg[0]) {
2080 tdumpline(term.c.y);
2086 term.mode &= ~MODE_PRINT;
2089 term.mode |= MODE_PRINT;
2093 case 'c': /* DA -- Device Attributes */
2094 if(csiescseq.arg[0] == 0)
2095 ttywrite(vtiden, sizeof(vtiden) - 1);
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);
2102 case 'D': /* CUB -- Cursor <n> Backward */
2103 DEFAULT(csiescseq.arg[0], 1);
2104 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
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]);
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]);
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;
2119 case 3: /* clear all the tabs */
2120 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
2126 case 'G': /* CHA -- Move to <col> */
2128 DEFAULT(csiescseq.arg[0], 1);
2129 tmoveto(csiescseq.arg[0]-1, term.c.y);
2131 case 'H': /* CUP -- Move to <row> <col> */
2133 DEFAULT(csiescseq.arg[0], 1);
2134 DEFAULT(csiescseq.arg[1], 1);
2135 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
2137 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
2138 DEFAULT(csiescseq.arg[0], 1);
2139 tputtab(csiescseq.arg[0]);
2141 case 'J': /* ED -- Clear screen */
2143 switch(csiescseq.arg[0]) {
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,
2153 tclearregion(0, 0, term.col-1, term.c.y-1);
2154 tclearregion(0, term.c.y, term.c.x, term.c.y);
2157 tclearregion(0, 0, term.col-1, term.row-1);
2163 case 'K': /* EL -- Clear line */
2164 switch(csiescseq.arg[0]) {
2166 tclearregion(term.c.x, term.c.y, term.col-1,
2170 tclearregion(0, term.c.y, term.c.x, term.c.y);
2173 tclearregion(0, term.c.y, term.col-1, term.c.y);
2177 case 'S': /* SU -- Scroll <n> line up */
2178 DEFAULT(csiescseq.arg[0], 1);
2179 tscrollup(term.top, csiescseq.arg[0]);
2181 case 'T': /* SD -- Scroll <n> line down */
2182 DEFAULT(csiescseq.arg[0], 1);
2183 tscrolldown(term.top, csiescseq.arg[0]);
2185 case 'L': /* IL -- Insert <n> blank lines */
2186 DEFAULT(csiescseq.arg[0], 1);
2187 tinsertblankline(csiescseq.arg[0]);
2189 case 'l': /* RM -- Reset Mode */
2190 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2192 case 'M': /* DL -- Delete <n> lines */
2193 DEFAULT(csiescseq.arg[0], 1);
2194 tdeleteline(csiescseq.arg[0]);
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);
2201 case 'P': /* DCH -- Delete <n> char */
2202 DEFAULT(csiescseq.arg[0], 1);
2203 tdeletechar(csiescseq.arg[0]);
2205 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2206 DEFAULT(csiescseq.arg[0], 1);
2207 tputtab(-csiescseq.arg[0]);
2209 case 'd': /* VPA -- Move to <row> */
2210 DEFAULT(csiescseq.arg[0], 1);
2211 tmoveato(term.c.x, csiescseq.arg[0]-1);
2213 case 'h': /* SM -- Set terminal mode */
2214 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2216 case 'm': /* SGR -- Terminal attribute (color) */
2217 tsetattr(csiescseq.arg, csiescseq.narg);
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);
2226 case 'r': /* DECSTBM -- Set Scrolling Region */
2227 if(csiescseq.priv) {
2230 DEFAULT(csiescseq.arg[0], 1);
2231 DEFAULT(csiescseq.arg[1], term.row);
2232 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2236 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2237 tcursor(CURSOR_SAVE);
2239 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2240 tcursor(CURSOR_LOAD);
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)) {
2249 xw.cursor = csiescseq.arg[0];
2264 for(i = 0; i < csiescseq.len; i++) {
2265 c = csiescseq.buf[i] & 0xff;
2268 } else if(c == '\n') {
2270 } else if(c == '\r') {
2272 } else if(c == 0x1b) {
2275 printf("(%02x)", c);
2283 memset(&csiescseq, 0, sizeof(csiescseq));
2291 term.esc &= ~(ESC_STR_END|ESC_STR);
2293 par = (narg = strescseq.narg) ? atoi(strescseq.args[0]) : 0;
2295 switch(strescseq.type) {
2296 case ']': /* OSC -- Operating System Command */
2302 xsettitle(strescseq.args[1]);
2304 case 4: /* color set */
2307 p = strescseq.args[2];
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);
2315 * TODO if defaultbg color is changed, borders
2323 case 'k': /* old title set compatibility */
2324 xsettitle(strescseq.args[0]);
2326 case 'P': /* DCS -- Device Control String */
2327 case '_': /* APC -- Application Program Command */
2328 case '^': /* PM -- Privacy Message */
2332 fprintf(stderr, "erresc: unknown str ");
2339 char *p = strescseq.buf;
2342 strescseq.buf[strescseq.len] = '\0';
2347 while(strescseq.narg < STR_ARG_SIZ) {
2348 strescseq.args[strescseq.narg++] = p;
2349 while((c = *p) != ';' && c != '\0')
2362 printf("ESC%c", strescseq.type);
2363 for(i = 0; i < strescseq.len; i++) {
2364 c = strescseq.buf[i] & 0xff;
2367 } else if(isprint(c)) {
2369 } else if(c == '\n') {
2371 } else if(c == '\r') {
2373 } else if(c == 0x1b) {
2376 printf("(%02x)", c);
2384 memset(&strescseq, 0, sizeof(strescseq));
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));
2398 toggleprinter(const Arg *arg) {
2399 term.mode ^= MODE_PRINT;
2403 printscreen(const Arg *arg) {
2408 printsel(const Arg *arg) {
2416 if((ptr = getsel())) {
2417 tprinter(ptr, strlen(ptr));
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));
2440 for(i = 0; i < term.row; ++i)
2449 while(x < term.col && n--)
2450 for(++x; x < term.col && !term.tabs[x]; ++x)
2454 for(--x; x > 0 && !term.tabs[x]; --x)
2457 term.c.x = LIMIT(x, 0, term.col-1);
2462 if(ISCONTROL(u)) { /* control code */
2467 } else if(u != '\n' && u != '\r' && u != '\t') {
2476 tdeftran(char ascii) {
2477 static char cs[] = "0B";
2478 static int vcs[] = {CS_GRAPHIC0, CS_USA};
2481 if((p = strchr(cs, ascii)) == NULL) {
2482 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2484 term.trantbl[term.icharset] = vcs[p - cs];
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);
2501 tstrsequence(uchar c) {
2503 case 0x90: /* DCS -- Device Control String */
2506 case 0x9f: /* APC -- Application Program Command */
2509 case 0x9e: /* PM -- Privacy Message */
2512 case 0x9d: /* OSC -- Operating System Command */
2518 term.esc |= ESC_STR;
2522 tcontrolcode(uchar ascii) {
2528 tmoveto(term.c.x-1, term.c.y);
2531 tmoveto(0, term.c.y);
2536 /* go to first col if the mode is set */
2537 tnewline(IS_SET(MODE_CRLF));
2539 case '\a': /* BEL */
2540 if(term.esc & ESC_STR_END) {
2541 /* backwards compatibility to xterm */
2544 if(!(xw.state & WIN_FOCUSED))
2547 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
2550 case '\033': /* ESC */
2552 term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
2553 term.esc |= ESC_START;
2555 case '\016': /* SO (LS1 -- Locking shift 1) */
2556 case '\017': /* SI (LS0 -- Locking shift 0) */
2557 term.charset = 1 - (ascii - '\016');
2559 case '\032': /* SUB */
2560 tsetchar('?', &term.c.attr, term.c.x, term.c.y);
2561 case '\030': /* CAN */
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) */
2570 case 0x84: /* TODO: IND */
2572 case 0x85: /* NEL -- Next line */
2573 tnewline(1); /* always go to first col */
2575 case 0x88: /* HTS -- Horizontal tab stop */
2576 term.tabs[term.c.x] = 1;
2578 case 0x8d: /* TODO: RI */
2579 case 0x8e: /* TODO: SS2 */
2580 case 0x8f: /* TODO: SS3 */
2581 case 0x98: /* TODO: SOS */
2583 case 0x9a: /* DECID -- Identify Terminal */
2584 ttywrite(vtiden, sizeof(vtiden) - 1);
2586 case 0x9b: /* TODO: CSI */
2587 case 0x9c: /* TODO: ST */
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);
2596 /* only CAN, SUB, \a and C1 chars interrupt a sequence */
2597 term.esc &= ~(ESC_STR_END|ESC_STR);
2601 * returns 1 when the sequence is finished and it hasn't to read
2602 * more characters for this sequence, otherwise 0
2605 eschandle(uchar ascii) {
2608 term.esc |= ESC_CSI;
2611 term.esc |= ESC_TEST;
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);
2620 case 'n': /* LS2 -- Locking shift 2 */
2621 case 'o': /* LS3 -- Locking shift 3 */
2622 term.charset = 2 + (ascii - 'n');
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;
2631 case 'D': /* IND -- Linefeed */
2632 if(term.c.y == term.bot) {
2633 tscrollup(term.top, 1);
2635 tmoveto(term.c.x, term.c.y+1);
2638 case 'E': /* NEL -- Next line */
2639 tnewline(1); /* always go to first col */
2641 case 'H': /* HTS -- Horizontal tab stop */
2642 term.tabs[term.c.x] = 1;
2644 case 'M': /* RI -- Reverse index */
2645 if(term.c.y == term.top) {
2646 tscrolldown(term.top, 1);
2648 tmoveto(term.c.x, term.c.y-1);
2651 case 'Z': /* DECID -- Identify Terminal */
2652 ttywrite(vtiden, sizeof(vtiden) - 1);
2654 case 'c': /* RIS -- Reset to inital state */
2659 case '=': /* DECPAM -- Application keypad */
2660 term.mode |= MODE_APPKEYPAD;
2662 case '>': /* DECPNM -- Normal keypad */
2663 term.mode &= ~MODE_APPKEYPAD;
2665 case '7': /* DECSC -- Save Cursor */
2666 tcursor(CURSOR_SAVE);
2668 case '8': /* DECRC -- Restore Cursor */
2669 tcursor(CURSOR_LOAD);
2671 case '\\': /* ST -- String Terminator */
2672 if(term.esc & ESC_STR_END)
2676 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2677 (uchar) ascii, isprint(ascii)? ascii:'.');
2690 len = utf8encode(u, c);
2691 if((width = wcwidth(u)) == -1) {
2692 memcpy(c, "\357\277\275", 4); /* UTF_INVALID */
2696 if(IS_SET(MODE_PRINT))
2698 control = ISCONTROL(u);
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
2706 if(term.esc & ESC_STR) {
2707 if(u == '\a' || u == 030 || u == 032 || u == 033 ||
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;
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.
2723 * In the case users ever get fixed, here is the code:
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.
2741 * control codes are not shown ever
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) {
2755 } else if(term.esc & ESC_ALTCHARSET) {
2757 } else if(term.esc & ESC_TEST) {
2762 /* sequence already finished */
2766 * All characters which form part of a sequence are not
2771 if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
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;
2778 gp = &term.line[term.c.y][term.c.x];
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));
2784 if(term.c.x+width > term.col) {
2786 gp = &term.line[term.c.y][term.c.x];
2789 tsetchar(u, &term.c.attr, term.c.x, term.c.y);
2792 gp->mode |= ATTR_WIDE;
2793 if(term.c.x+1 < term.col) {
2795 gp[1].mode = ATTR_WDUMMY;
2798 if(term.c.x+width < term.col) {
2799 tmoveto(term.c.x+width, term.c.y);
2801 term.c.state |= CURSOR_WRAPNEXT;
2806 tresize(int col, int row) {
2808 int minrow = MIN(row, term.row);
2809 int mincol = MIN(col, term.col);
2813 if(col < 1 || row < 1) {
2815 "tresize: error resizing to %dx%d\n", col, row);
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
2824 for(i = 0; i <= term.c.y - row; i++) {
2828 /* ensure that both src and dst are not NULL */
2830 memmove(term.line, term.line + i, row * sizeof(Line));
2831 memmove(term.alt, term.alt + i, row * sizeof(Line));
2833 for(i += row; i < term.row; i++) {
2838 /* resize to new width */
2839 term.specbuf = xrealloc(term.specbuf, col * sizeof(XftGlyphFontSpec));
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));
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));
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));
2858 if(col > term.col) {
2859 bp = term.tabs + term.col;
2861 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2862 while(--bp > term.tabs && !*bp)
2864 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2867 /* update terminal size */
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) */
2876 for(i = 0; i < 2; i++) {
2877 if(mincol < col && 0 < minrow) {
2878 tclearregion(mincol, 0, col - 1, minrow - 1);
2880 if(0 < col && minrow < row) {
2881 tclearregion(0, minrow, col - 1, row - 1);
2884 tcursor(CURSOR_LOAD);
2890 xresize(int col, int row) {
2891 xw.tw = MAX(1, col * xw.cw);
2892 xw.th = MAX(1, row * xw.ch);
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);
2902 sixd_to_16bit(int x) {
2903 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2907 xloadcolor(int i, const char *name, Color *ncolor) {
2908 XRenderColor color = { .alpha = 0xffff };
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;
2920 return XftColorAllocValue(xw.dpy, xw.vis,
2921 xw.cmap, &color, ncolor);
2923 name = colorname[i];
2925 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
2935 for (cp = dc.col; cp < &dc.col[LEN(dc.col)]; ++cp)
2936 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
2939 for(i = 0; i < LEN(dc.col); i++)
2940 if(!xloadcolor(i, NULL, &dc.col[i])) {
2942 die("Could not allocate color '%s'\n", colorname[i]);
2944 die("Could not allocate color %d\n", i);
2950 xsetcolorname(int x, const char *name) {
2953 if(!BETWEEN(x, 0, LEN(dc.col)))
2957 if(!xloadcolor(x, name, &ncolor))
2960 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
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);
2976 * Absolute coordinates.
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);
2987 XClassHint class = {opt_class ? opt_class : termname, termname};
2988 XWMHints wm = {.flags = InputHint, .input = 1};
2989 XSizeHints *sizeh = NULL;
2991 sizeh = XAllocSizeHints();
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;
3001 sizeh->flags |= PMaxSize | PMinSize;
3002 sizeh->min_width = sizeh->max_width = xw.w;
3003 sizeh->min_height = sizeh->max_height = xw.h;
3005 if(xw.gm & (XValue|YValue)) {
3006 sizeh->flags |= USPosition | PWinGravity;
3009 sizeh->win_gravity = xgeommasktogravity(xw.gm);
3012 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
3018 xgeommasktogravity(int mask) {
3019 switch(mask & (XNegative|YNegative)) {
3021 return NorthWestGravity;
3023 return NorthEastGravity;
3025 return SouthWestGravity;
3027 return SouthEastGravity;
3031 xloadfont(Font *f, FcPattern *pattern) {
3035 match = FcFontMatch(NULL, pattern, &result);
3039 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
3040 FcPatternDestroy(match);
3045 f->pattern = FcPatternDuplicate(pattern);
3047 f->ascent = f->match->ascent;
3048 f->descent = f->match->descent;
3050 f->rbearing = f->match->max_advance_width;
3052 f->height = f->ascent + f->descent;
3053 f->width = f->lbearing + f->rbearing;
3059 xloadfonts(char *fontstr, double fontsize) {
3064 if(fontstr[0] == '-') {
3065 pattern = XftXlfdParse(fontstr, False, False);
3067 pattern = FcNameParse((FcChar8 *)fontstr);
3071 die("st: can't open font %s\n", fontstr);
3074 FcPatternDel(pattern, FC_PIXEL_SIZE);
3075 FcPatternDel(pattern, FC_SIZE);
3076 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
3077 usedfontsize = fontsize;
3079 if(FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
3081 usedfontsize = fontval;
3082 } else if(FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
3087 * Default font size is 12, if none given. This is to
3088 * have a known usedfontsize value.
3090 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
3093 defaultfontsize = usedfontsize;
3096 FcConfigSubstitute(0, pattern, FcMatchPattern);
3097 FcDefaultSubstitute(pattern);
3099 if(xloadfont(&dc.font, pattern))
3100 die("st: can't open font %s\n", fontstr);
3102 if(usedfontsize < 0) {
3103 FcPatternGetDouble(dc.font.match->pattern,
3104 FC_PIXEL_SIZE, 0, &fontval);
3105 usedfontsize = fontval;
3107 defaultfontsize = fontval;
3110 /* Setting character width and height. */
3111 xw.cw = ceilf(dc.font.width * cwscale);
3112 xw.ch = ceilf(dc.font.height * chscale);
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);
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);
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);
3129 FcPatternDestroy(pattern);
3133 xunloadfont(Font *f) {
3134 XftFontClose(xw.dpy, f->match);
3135 FcPatternDestroy(f->pattern);
3137 FcFontSetDestroy(f->set);
3141 xunloadfonts(void) {
3142 /* Free the loaded fonts in the font cache. */
3144 XftFontClose(xw.dpy, frc[--frclen].font);
3146 xunloadfont(&dc.font);
3147 xunloadfont(&dc.bfont);
3148 xunloadfont(&dc.ifont);
3149 xunloadfont(&dc.ibfont);
3153 xzoom(const Arg *arg) {
3156 larg.f = usedfontsize + arg->f;
3161 xzoomabs(const Arg *arg) {
3163 xloadfonts(usedfont, arg->f);
3170 xzoomreset(const Arg *arg) {
3173 if(defaultfontsize > 0) {
3174 larg.f = defaultfontsize;
3184 pid_t thispid = getpid();
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);
3193 die("Could not init fontconfig.\n");
3195 usedfont = (opt_font == NULL)? font : opt_font;
3196 xloadfonts(usedfont, 0);
3199 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
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;
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;
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);
3226 memset(&gcvalues, 0, sizeof(gcvalues));
3227 gcvalues.graphics_exposures = False;
3228 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
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);
3235 /* Xft rendering context */
3236 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
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"
3250 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
3251 | XIMStatusNothing, XNClientWindow, xw.win,
3252 XNFocusWindow, xw.win, NULL);
3254 die("XCreateIC failed. Could not obtain input method.\n");
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});
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);
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);
3273 XMapWindow(xw.dpy, xw.win);
3275 XSync(xw.dpy, False);
3279 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
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;
3289 FcPattern *fcpattern, *fontpattern;
3290 FcFontSet *fcsets[] = { NULL };
3291 FcCharSet *fccharset;
3292 int i, f, numspecs = 0;
3294 for(i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
3295 /* Fetch rune and mode for current glyph. */
3297 mode = glyphs[i].mode;
3299 /* Skip dummy wide-character spacing. */
3300 if(mode == ATTR_WDUMMY)
3303 /* Determine font for glyph if different from previous glyph. */
3304 if(prevmode != mode) {
3307 frcflags = FRC_NORMAL;
3308 runewidth = xw.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
3309 if((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
3311 frcflags = FRC_ITALICBOLD;
3312 } else if(mode & ATTR_ITALIC) {
3314 frcflags = FRC_ITALIC;
3315 } else if(mode & ATTR_BOLD) {
3317 frcflags = FRC_BOLD;
3319 yp = winy + font->ascent;
3322 /* Lookup character index with default font. */
3323 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
3325 specs[numspecs].font = font->match;
3326 specs[numspecs].glyph = glyphidx;
3327 specs[numspecs].x = (short)xp;
3328 specs[numspecs].y = (short)yp;
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)
3340 /* We got a default font for a not found glyph. */
3341 if(!glyphidx && frc[f].flags == frcflags
3342 && frc[f].unicodep == rune) {
3347 /* Nothing was found. Use fontconfig to find matching font. */
3350 font->set = FcFontSort(0, font->pattern,
3352 fcsets[0] = font->set;
3355 * Nothing was found in the cache. Now use
3356 * some dozen of Fontconfig calls to get the
3357 * font for one single character.
3359 * Xft and fontconfig are design failures.
3361 fcpattern = FcPatternDuplicate(font->pattern);
3362 fccharset = FcCharSetCreate();
3364 FcCharSetAddChar(fccharset, rune);
3365 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3367 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
3369 FcConfigSubstitute(0, fcpattern,
3371 FcDefaultSubstitute(fcpattern);
3373 fontpattern = FcFontSetMatch(0, fcsets, 1,
3377 * Overwrite or create the new cache entry.
3379 if(frclen >= LEN(frc)) {
3380 frclen = LEN(frc) - 1;
3381 XftFontClose(xw.dpy, frc[frclen].font);
3382 frc[frclen].unicodep = 0;
3385 frc[frclen].font = XftFontOpenPattern(xw.dpy,
3387 frc[frclen].flags = frcflags;
3388 frc[frclen].unicodep = rune;
3390 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
3395 FcPatternDestroy(fcpattern);
3396 FcCharSetDestroy(fccharset);
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);
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;
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;
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);
3437 fg = &dc.col[base.fg];
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);
3448 bg = &dc.col[base.bg];
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];
3455 if(IS_SET(MODE_REVERSE)) {
3456 if(fg == &dc.col[defaultfg]) {
3457 fg = &dc.col[defaultbg];
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,
3468 if(bg == &dc.col[defaultbg]) {
3469 bg = &dc.col[defaultfg];
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,
3481 if(base.mode & ATTR_REVERSE) {
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);
3495 if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3498 if(base.mode & ATTR_INVISIBLE)
3501 /* Intelligent cleaning up of the borders. */
3503 xclear(0, (y == 0)? 0 : winy, borderpx,
3504 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
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)));
3511 xclear(winx, 0, winx + width, borderpx);
3513 xclear(winx, winy + xw.ch, winx + width, xw.h);
3515 /* Clean up the region we want to draw to. */
3516 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3518 /* Set the clip region because Xft is sometimes dirty. */
3523 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3525 /* Render the glyphs. */
3526 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
3528 /* Render underline and strikethrough. */
3529 if(base.mode & ATTR_UNDERLINE) {
3530 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
3534 if(base.mode & ATTR_STRUCK) {
3535 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
3539 /* Reset clip to none. */
3540 XftDrawSetClip(xw.draw, 0);
3544 xdrawglyph(Glyph g, int x, int y) {
3546 XftGlyphFontSpec spec;
3547 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
3548 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
3553 static int oldx = 0, oldy = 0;
3555 Glyph g = {' ', ATTR_NULL, defaultbg, defaultcs};
3557 LIMIT(oldx, 0, term.col-1);
3558 LIMIT(oldy, 0, term.row-1);
3562 /* adjust position if in dummy */
3563 if(term.line[oldy][oldx].mode & ATTR_WDUMMY)
3565 if(term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3568 g.u = term.line[term.c.y][term.c.x].u;
3570 /* remove the old cursor */
3571 xdrawglyph(term.line[oldy][oldx], oldx, oldy);
3573 if(IS_SET(MODE_HIDE))
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;
3588 g.mode |= term.line[term.c.y][curx].mode & ATTR_WIDE;
3589 xdrawglyph(g, term.c.x, term.c.y);
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);
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);
3607 XftDrawRect(xw.draw, &dc.col[defaultcs],
3608 borderpx + curx * xw.cw,
3609 borderpx + term.c.y * xw.ch,
3611 XftDrawRect(xw.draw, &dc.col[defaultcs],
3612 borderpx + curx * xw.cw,
3613 borderpx + term.c.y * xw.ch,
3615 XftDrawRect(xw.draw, &dc.col[defaultcs],
3616 borderpx + (curx + 1) * xw.cw - 1,
3617 borderpx + term.c.y * xw.ch,
3619 XftDrawRect(xw.draw, &dc.col[defaultcs],
3620 borderpx + curx * xw.cw,
3621 borderpx + (term.c.y + 1) * xw.ch - 1,
3624 oldx = curx, oldy = term.c.y;
3629 xsettitle(char *p) {
3632 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3634 XSetWMName(xw.dpy, xw.win, &prop);
3635 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
3641 xsettitle(opt_title ? opt_title : "st");
3652 drawregion(0, 0, term.col, term.row);
3653 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3655 XSetForeground(xw.dpy, dc.gc,
3656 dc.col[IS_SET(MODE_REVERSE)?
3657 defaultfg : defaultbg].pixel);
3661 drawregion(int x1, int y1, int x2, int y2) {
3662 int i, x, y, ox, numspecs;
3664 XftGlyphFontSpec* specs;
3665 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
3667 if(!(xw.state & WIN_VISIBLE))
3670 for(y = y1; y < y2; y++) {
3674 xtermclear(0, y, term.col, y);
3677 specs = term.specbuf;
3678 numspecs = xmakeglyphfontspecs(specs, &term.line[y][x1], x2 - x1, x1, y);
3681 for(x = x1; x < x2 && i < numspecs; x++) {
3682 new = term.line[y][x];
3683 if(new.mode == ATTR_WDUMMY)
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);
3700 xdrawglyphfontspecs(specs, base, i, ox, y);
3706 expose(XEvent *ev) {
3711 visibility(XEvent *ev) {
3712 XVisibilityEvent *e = &ev->xvisibility;
3714 MODBIT(xw.state, e->state != VisibilityFullyObscured, WIN_VISIBLE);
3719 xw.state &= ~WIN_VISIBLE;
3723 xsetpointermotion(int set) {
3724 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3725 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3729 xseturgency(int add) {
3730 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3732 MODBIT(h->flags, add, XUrgencyHint);
3733 XSetWMHints(xw.dpy, xw.win, h);
3739 XFocusChangeEvent *e = &ev->xfocus;
3741 if(e->mode == NotifyGrab)
3744 if(ev->type == FocusIn) {
3745 XSetICFocus(xw.xic);
3746 xw.state |= WIN_FOCUSED;
3748 if(IS_SET(MODE_FOCUS))
3749 ttywrite("\033[I", 3);
3751 XUnsetICFocus(xw.xic);
3752 xw.state &= ~WIN_FOCUSED;
3753 if(IS_SET(MODE_FOCUS))
3754 ttywrite("\033[O", 3);
3759 match(uint mask, uint state) {
3760 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
3764 numlock(const Arg *dummy) {
3769 kmap(KeySym k, uint state) {
3773 /* Check for mapped keys out of X11 function keys. */
3774 for(i = 0; i < LEN(mappedkeys); i++) {
3775 if(mappedkeys[i] == k)
3778 if(i == LEN(mappedkeys)) {
3779 if((k & 0xFFFF) < 0xFD00)
3783 for(kp = key; kp < key + LEN(key); kp++) {
3787 if(!match(kp->mask, state))
3790 if(IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
3792 if(term.numlock && kp->appkey == 2)
3795 if(IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
3798 if(IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
3808 kpress(XEvent *ev) {
3809 XKeyEvent *e = &ev->xkey;
3811 char buf[32], *customkey;
3817 if(IS_SET(MODE_KBDLOCK))
3820 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
3822 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3823 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3824 bp->func(&(bp->arg));
3829 /* 2. custom keys from config.h */
3830 if((customkey = kmap(ksym, e->state))) {
3831 ttysend(customkey, strlen(customkey));
3835 /* 3. composed string from input method */
3838 if(len == 1 && e->state & Mod1Mask) {
3839 if(IS_SET(MODE_8BIT)) {
3842 len = utf8encode(c, buf);
3855 cmessage(XEvent *e) {
3858 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
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;
3864 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3865 xw.state &= ~WIN_FOCUSED;
3867 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3868 /* Send SIGHUP to shell */
3875 cresize(int width, int height) {
3883 col = (xw.w - 2 * borderpx) / xw.cw;
3884 row = (xw.h - 2 * borderpx) / xw.ch;
3893 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3896 cresize(e->xconfigure.width, e->xconfigure.height);
3902 int w = xw.w, h = xw.h;
3904 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3905 struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
3908 /* Waiting for window mapping */
3910 XNextEvent(xw.dpy, &ev);
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.
3916 if(XFilterEvent(&ev, None))
3918 if(ev.type == ConfigureNotify) {
3919 w = ev.xconfigure.width;
3920 h = ev.xconfigure.height;
3922 } while(ev.type != MapNotify);
3927 clock_gettime(CLOCK_MONOTONIC, &last);
3930 for(xev = actionfps;;) {
3932 FD_SET(cmdfd, &rfd);
3935 if(pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
3938 die("select failed: %s\n", strerror(errno));
3940 if(FD_ISSET(cmdfd, &rfd)) {
3943 blinkset = tattrset(ATTR_BLINK);
3945 MODBIT(term.mode, 0, MODE_BLINK);
3949 if(FD_ISSET(xfd, &rfd))
3952 clock_gettime(CLOCK_MONOTONIC, &now);
3953 drawtimeout.tv_sec = 0;
3954 drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
3958 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3959 tsetdirtattr(ATTR_BLINK);
3960 term.mode ^= MODE_BLINK;
3964 deltatime = TIMEDIFF(now, last);
3965 if(deltatime > 1000 / (xev ? xfps : actionfps)) {
3971 while(XPending(xw.dpy)) {
3972 XNextEvent(xw.dpy, &ev);
3973 if(XFilterEvent(&ev, None))
3975 if(handler[ev.type])
3976 (handler[ev.type])(&ev);
3982 if(xev && !FD_ISSET(xfd, &rfd))
3984 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3986 if(TIMEDIFF(now, lastblink) \
3988 drawtimeout.tv_nsec = 1000;
3990 drawtimeout.tv_nsec = (1E6 * \
3995 drawtimeout.tv_sec = \
3996 drawtimeout.tv_nsec / 1E9;
3997 drawtimeout.tv_nsec %= (long)1E9;
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",
4017 main(int argc, char *argv[]) {
4018 uint cols = 80, rows = 24;
4029 opt_class = EARGF(usage());
4036 opt_font = EARGF(usage());
4039 xw.gm = XParseGeometry(EARGF(usage()),
4040 &xw.l, &xw.t, &cols, &rows);
4046 opt_io = EARGF(usage());
4049 opt_line = EARGF(usage());
4052 opt_title = EARGF(usage());
4055 opt_embed = EARGF(usage());
4064 /* eat all remaining arguments */
4066 if(!opt_title && !opt_line)
4067 opt_title = basename(xstrdup(argv[0]));
4069 setlocale(LC_CTYPE, "");
4070 XSetLocaleModifiers("");
4071 tnew(MAX(cols, 1), MAX(rows, 1));