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)
558 ssize_t r = write(fd, s, len);
570 void *p = malloc(len);
573 die("Out of memory\n");
579 xrealloc(void *p, size_t len)
581 if ((p = realloc(p, len)) == NULL)
582 die("Out of memory\n");
590 if ((s = strdup(s)) == NULL)
591 die("Out of memory\n");
597 utf8decode(char *c, Rune *u, size_t clen)
599 size_t i, j, len, type;
605 udecoded = utf8decodebyte(c[0], &len);
606 if (!BETWEEN(len, 1, UTF_SIZ))
608 for (i = 1, j = 1; i < clen && j < len; ++i, ++j) {
609 udecoded = (udecoded << 6) | utf8decodebyte(c[i], &type);
616 utf8validate(u, len);
621 utf8decodebyte(char c, size_t *i)
623 for (*i = 0; *i < LEN(utfmask); ++(*i))
624 if (((uchar)c & utfmask[*i]) == utfbyte[*i])
625 return (uchar)c & ~utfmask[*i];
630 utf8encode(Rune u, char *c)
634 len = utf8validate(&u, 0);
637 for (i = len - 1; i != 0; --i) {
638 c[i] = utf8encodebyte(u, 0);
641 c[0] = utf8encodebyte(u, len);
646 utf8encodebyte(Rune u, size_t i)
648 return utfbyte[i] | (u & ~utfmask[i]);
652 utf8strchr(char *s, Rune u)
658 for (i = 0, j = 0; i < len; i += j) {
659 if (!(j = utf8decode(&s[i], &r, len - i)))
668 utf8validate(Rune *u, size_t i)
670 if (!BETWEEN(*u, utfmin[i], utfmax[i]) || BETWEEN(*u, 0xD800, 0xDFFF))
672 for (i = 1; *u > utfmax[i]; ++i)
680 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
681 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
685 sel.clipboard = NULL;
686 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
687 if (sel.xtarget == None)
688 sel.xtarget = XA_STRING;
697 return LIMIT(x, 0, term.col-1);
706 return LIMIT(y, 0, term.row-1);
714 if (term.line[y][i - 1].mode & ATTR_WRAP)
717 while (i > 0 && term.line[y][i - 1].u == ' ')
728 if (sel.type == SEL_REGULAR && sel.ob.y != sel.oe.y) {
729 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
730 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
732 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
733 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
735 sel.nb.y = MIN(sel.ob.y, sel.oe.y);
736 sel.ne.y = MAX(sel.ob.y, sel.oe.y);
738 selsnap(&sel.nb.x, &sel.nb.y, -1);
739 selsnap(&sel.ne.x, &sel.ne.y, +1);
741 /* expand selection over line breaks */
742 if (sel.type == SEL_RECTANGULAR)
744 i = tlinelen(sel.nb.y);
747 if (tlinelen(sel.ne.y) <= sel.ne.x)
748 sel.ne.x = term.col - 1;
752 selected(int x, int y)
754 if (sel.mode == SEL_EMPTY)
757 if (sel.type == SEL_RECTANGULAR)
758 return BETWEEN(y, sel.nb.y, sel.ne.y)
759 && BETWEEN(x, sel.nb.x, sel.ne.x);
761 return BETWEEN(y, sel.nb.y, sel.ne.y)
762 && (y != sel.nb.y || x >= sel.nb.x)
763 && (y != sel.ne.y || x <= sel.ne.x);
767 selsnap(int *x, int *y, int direction)
769 int newx, newy, xt, yt;
770 int delim, prevdelim;
776 * Snap around if the word wraps around at the end or
777 * beginning of a line.
779 prevgp = &term.line[*y][*x];
780 prevdelim = ISDELIM(prevgp->u);
782 newx = *x + direction;
784 if (!BETWEEN(newx, 0, term.col - 1)) {
786 newx = (newx + term.col) % term.col;
787 if (!BETWEEN(newy, 0, term.row - 1))
793 yt = newy, xt = newx;
794 if (!(term.line[yt][xt].mode & ATTR_WRAP))
798 if (newx >= tlinelen(newy))
801 gp = &term.line[newy][newx];
802 delim = ISDELIM(gp->u);
803 if (!(gp->mode & ATTR_WDUMMY) && (delim != prevdelim
804 || (delim && gp->u != prevgp->u)))
815 * Snap around if the the previous line or the current one
816 * has set ATTR_WRAP at its end. Then the whole next or
817 * previous line will be selected.
819 *x = (direction < 0) ? 0 : term.col - 1;
821 for (; *y > 0; *y += direction) {
822 if (!(term.line[*y-1][term.col-1].mode
827 } else if (direction > 0) {
828 for (; *y < term.row-1; *y += direction) {
829 if (!(term.line[*y][term.col-1].mode
840 getbuttoninfo(XEvent *e)
843 uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
845 sel.alt = IS_SET(MODE_ALTSCREEN);
847 sel.oe.x = x2col(e->xbutton.x);
848 sel.oe.y = y2row(e->xbutton.y);
851 sel.type = SEL_REGULAR;
852 for (type = 1; type < LEN(selmasks); ++type) {
853 if (match(selmasks[type], state)) {
861 mousereport(XEvent *e)
863 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
864 button = e->xbutton.button, state = e->xbutton.state,
870 if (e->xbutton.type == MotionNotify) {
871 if (x == ox && y == oy)
873 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
875 /* MOUSE_MOTION: no reporting if no button is pressed */
876 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
879 button = oldbutton + 32;
883 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
890 if (e->xbutton.type == ButtonPress) {
894 } else if (e->xbutton.type == ButtonRelease) {
896 /* MODE_MOUSEX10: no button release reporting */
897 if (IS_SET(MODE_MOUSEX10))
899 if (button == 64 || button == 65)
904 if (!IS_SET(MODE_MOUSEX10)) {
905 button += ((state & ShiftMask ) ? 4 : 0)
906 + ((state & Mod4Mask ) ? 8 : 0)
907 + ((state & ControlMask) ? 16 : 0);
910 if (IS_SET(MODE_MOUSESGR)) {
911 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
913 e->xbutton.type == ButtonRelease ? 'm' : 'M');
914 } else if (x < 223 && y < 223) {
915 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
916 32+button, 32+x+1, 32+y+1);
930 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
935 for (mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
936 if (e->xbutton.button == mk->b
937 && match(mk->mask, e->xbutton.state)) {
938 ttysend(mk->s, strlen(mk->s));
943 if (e->xbutton.button == Button1) {
944 clock_gettime(CLOCK_MONOTONIC, &now);
946 /* Clear previous selection, logically and visually. */
948 sel.mode = SEL_EMPTY;
949 sel.type = SEL_REGULAR;
950 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
951 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
954 * If the user clicks below predefined timeouts specific
955 * snapping behaviour is exposed.
957 if (TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
958 sel.snap = SNAP_LINE;
959 } else if (TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
960 sel.snap = SNAP_WORD;
967 sel.mode = SEL_READY;
968 tsetdirt(sel.nb.y, sel.ne.y);
969 sel.tclick2 = sel.tclick1;
978 int y, bufsize, lastx, linelen;
984 bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
985 ptr = str = xmalloc(bufsize);
987 /* append every set & selected glyph to the selection */
988 for (y = sel.nb.y; y <= sel.ne.y; y++) {
989 linelen = tlinelen(y);
991 if (sel.type == SEL_RECTANGULAR) {
992 gp = &term.line[y][sel.nb.x];
995 gp = &term.line[y][sel.nb.y == y ? sel.nb.x : 0];
996 lastx = (sel.ne.y == y) ? sel.ne.x : term.col-1;
998 last = &term.line[y][MIN(lastx, linelen-1)];
999 while (last >= gp && last->u == ' ')
1002 for ( ; gp <= last; ++gp) {
1003 if (gp->mode & ATTR_WDUMMY)
1006 ptr += utf8encode(gp->u, ptr);
1010 * Copy and pasting of line endings is inconsistent
1011 * in the inconsistent terminal and GUI world.
1012 * The best solution seems like to produce '\n' when
1013 * something is copied from st and convert '\n' to
1014 * '\r', when something to be pasted is received by
1016 * FIXME: Fix the computer world.
1018 if ((y < sel.ne.y || lastx >= linelen) && !(last->mode & ATTR_WRAP))
1028 xsetsel(getsel(), t);
1032 selnotify(XEvent *e)
1034 ulong nitems, ofs, rem;
1036 uchar *data, *last, *repl;
1038 XSelectionEvent *xsev;
1041 xsev = &e->xselection;
1042 if (xsev->property == None)
1045 if (XGetWindowProperty(xw.dpy, xw.win, xsev->property, ofs,
1046 BUFSIZ/4, False, AnyPropertyType,
1047 &type, &format, &nitems, &rem,
1049 fprintf(stderr, "Clipboard allocation failed\n");
1054 * As seen in getsel:
1055 * Line endings are inconsistent in the terminal and GUI world
1056 * copy and pasting. When receiving some selection data,
1057 * replace all '\n' with '\r'.
1058 * FIXME: Fix the computer world.
1061 last = data + nitems * format / 8;
1062 while ((repl = memchr(repl, '\n', last - repl))) {
1066 if (IS_SET(MODE_BRCKTPASTE))
1067 ttywrite("\033[200~", 6);
1068 ttysend((char *)data, nitems * format / 8);
1069 if (IS_SET(MODE_BRCKTPASTE))
1070 ttywrite("\033[201~", 6);
1072 /* number of 32-bit chunks returned */
1073 ofs += nitems * format / 32;
1078 selpaste(const Arg *dummy)
1080 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1081 xw.win, CurrentTime);
1085 clipcopy(const Arg *dummy)
1089 if (sel.clipboard != NULL)
1090 free(sel.clipboard);
1092 if (sel.primary != NULL) {
1093 sel.clipboard = xstrdup(sel.primary);
1094 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1095 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1100 clippaste(const Arg *dummy)
1104 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1105 XConvertSelection(xw.dpy, clipboard, sel.xtarget, clipboard,
1106 xw.win, CurrentTime);
1114 sel.mode = SEL_IDLE;
1116 tsetdirt(sel.nb.y, sel.ne.y);
1120 selrequest(XEvent *e)
1122 XSelectionRequestEvent *xsre;
1123 XSelectionEvent xev;
1124 Atom xa_targets, string, clipboard;
1127 xsre = (XSelectionRequestEvent *) e;
1128 xev.type = SelectionNotify;
1129 xev.requestor = xsre->requestor;
1130 xev.selection = xsre->selection;
1131 xev.target = xsre->target;
1132 xev.time = xsre->time;
1133 if (xsre->property == None)
1134 xsre->property = xsre->target;
1137 xev.property = None;
1139 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1140 if (xsre->target == xa_targets) {
1141 /* respond with the supported type */
1142 string = sel.xtarget;
1143 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1144 XA_ATOM, 32, PropModeReplace,
1145 (uchar *) &string, 1);
1146 xev.property = xsre->property;
1147 } else if (xsre->target == sel.xtarget || xsre->target == XA_STRING) {
1149 * xith XA_STRING non ascii characters may be incorrect in the
1150 * requestor. It is not our problem, use utf8.
1152 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1153 if (xsre->selection == XA_PRIMARY) {
1154 seltext = sel.primary;
1155 } else if (xsre->selection == clipboard) {
1156 seltext = sel.clipboard;
1159 "Unhandled clipboard selection 0x%lx\n",
1163 if (seltext != NULL) {
1164 XChangeProperty(xsre->display, xsre->requestor,
1165 xsre->property, xsre->target,
1167 (uchar *)seltext, strlen(seltext));
1168 xev.property = xsre->property;
1172 /* all done, send a notification to the listener */
1173 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
1174 fprintf(stderr, "Error sending SelectionNotify event\n");
1178 xsetsel(char *str, Time t)
1183 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
1184 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
1191 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
1196 if (e->xbutton.button == Button2) {
1198 } else if (e->xbutton.button == Button1) {
1199 if (sel.mode == SEL_READY) {
1201 selcopy(e->xbutton.time);
1204 sel.mode = SEL_IDLE;
1205 tsetdirt(sel.nb.y, sel.ne.y);
1212 int oldey, oldex, oldsby, oldsey;
1214 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
1222 sel.mode = SEL_READY;
1229 if (oldey != sel.oe.y || oldex != sel.oe.x)
1230 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1234 die(const char *errstr, ...)
1238 va_start(ap, errstr);
1239 vfprintf(stderr, errstr, ap);
1247 char **args, *sh, *prog;
1248 const struct passwd *pw;
1249 char buf[sizeof(long) * 8 + 1];
1252 if ((pw = getpwuid(getuid())) == NULL) {
1254 die("getpwuid:%s\n", strerror(errno));
1256 die("who are you?\n");
1259 if (!(sh = getenv("SHELL"))) {
1260 sh = (pw->pw_shell[0]) ? pw->pw_shell : shell;
1269 args = (opt_cmd) ? opt_cmd : (char *[]) {prog, NULL};
1271 snprintf(buf, sizeof(buf), "%lu", xw.win);
1273 unsetenv("COLUMNS");
1275 unsetenv("TERMCAP");
1276 setenv("LOGNAME", pw->pw_name, 1);
1277 setenv("USER", pw->pw_name, 1);
1278 setenv("SHELL", sh, 1);
1279 setenv("HOME", pw->pw_dir, 1);
1280 setenv("TERM", termname, 1);
1281 setenv("WINDOWID", buf, 1);
1283 signal(SIGCHLD, SIG_DFL);
1284 signal(SIGHUP, SIG_DFL);
1285 signal(SIGINT, SIG_DFL);
1286 signal(SIGQUIT, SIG_DFL);
1287 signal(SIGTERM, SIG_DFL);
1288 signal(SIGALRM, SIG_DFL);
1300 if ((p = waitpid(pid, &stat, WNOHANG)) < 0)
1301 die("Waiting for pid %hd failed: %s\n", pid, strerror(errno));
1306 if (!WIFEXITED(stat) || WEXITSTATUS(stat))
1307 die("child finished with error '%d'\n", stat);
1315 char cmd[_POSIX_ARG_MAX], **p, *q, *s;
1318 if ((n = strlen(stty_args)) > sizeof(cmd)-1)
1319 die("incorrect stty parameters\n");
1320 memcpy(cmd, stty_args, n);
1322 siz = sizeof(cmd) - n;
1323 for (p = opt_cmd; p && (s = *p); ++p) {
1324 if ((n = strlen(s)) > siz-1)
1325 die("stty parameter length too long\n");
1327 q = memcpy(q, s, n);
1332 if (system(cmd) != 0)
1333 perror("Couldn't call stty");
1340 struct winsize w = {term.row, term.col, 0, 0};
1343 term.mode |= MODE_PRINT;
1344 iofd = (!strcmp(opt_io, "-")) ?
1345 1 : open(opt_io, O_WRONLY | O_CREAT, 0666);
1347 fprintf(stderr, "Error opening %s:%s\n",
1348 opt_io, strerror(errno));
1353 if ((cmdfd = open(opt_line, O_RDWR)) < 0)
1354 die("open line failed: %s\n", strerror(errno));
1361 /* seems to work fine on linux, openbsd and freebsd */
1362 if (openpty(&m, &s, NULL, NULL, &w) < 0)
1363 die("openpty failed: %s\n", strerror(errno));
1365 switch (pid = fork()) {
1367 die("fork failed\n");
1371 setsid(); /* create a new process group */
1375 if (ioctl(s, TIOCSCTTY, NULL) < 0)
1376 die("ioctl TIOCSCTTY failed: %s\n", strerror(errno));
1384 signal(SIGCHLD, sigchld);
1392 static char buf[BUFSIZ];
1393 static int buflen = 0;
1395 int charsize; /* size of utf8 char in bytes */
1399 /* append read bytes to unprocessed bytes */
1400 if ((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1401 die("Couldn't read from shell: %s\n", strerror(errno));
1403 /* process every complete utf8 char */
1406 while ((charsize = utf8decode(ptr, &unicodep, buflen))) {
1412 /* keep any uncomplete utf8 char for the next call */
1413 memmove(buf, ptr, buflen);
1417 ttywrite(const char *s, size_t n)
1419 if (xwrite(cmdfd, s, n) == -1)
1420 die("write error on tty: %s\n", strerror(errno));
1424 ttysend(char *s, size_t n)
1430 if (IS_SET(MODE_ECHO))
1431 while ((len = utf8decode(s, &u, n)) > 0) {
1443 w.ws_row = term.row;
1444 w.ws_col = term.col;
1445 w.ws_xpixel = xw.tw;
1446 w.ws_ypixel = xw.th;
1447 if (ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1448 fprintf(stderr, "Couldn't set window size: %s\n", strerror(errno));
1456 for (i = 0; i < term.row-1; i++) {
1457 for (j = 0; j < term.col-1; j++) {
1458 if (term.line[i][j].mode & attr)
1467 tsetdirt(int top, int bot)
1471 LIMIT(top, 0, term.row-1);
1472 LIMIT(bot, 0, term.row-1);
1474 for (i = top; i <= bot; i++)
1479 tsetdirtattr(int attr)
1483 for (i = 0; i < term.row-1; i++) {
1484 for (j = 0; j < term.col-1; j++) {
1485 if (term.line[i][j].mode & attr) {
1496 tsetdirt(0, term.row-1);
1502 static TCursor c[2];
1503 int alt = IS_SET(MODE_ALTSCREEN);
1505 if (mode == CURSOR_SAVE) {
1507 } else if (mode == CURSOR_LOAD) {
1509 tmoveto(c[alt].x, c[alt].y);
1518 term.c = (TCursor){{
1522 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1524 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1525 for (i = tabspaces; i < term.col; i += tabspaces)
1528 term.bot = term.row - 1;
1529 term.mode = MODE_WRAP;
1530 memset(term.trantbl, CS_USA, sizeof(term.trantbl));
1533 for (i = 0; i < 2; i++) {
1535 tcursor(CURSOR_SAVE);
1536 tclearregion(0, 0, term.col-1, term.row-1);
1542 tnew(int col, int row)
1544 term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
1554 Line *tmp = term.line;
1556 term.line = term.alt;
1558 term.mode ^= MODE_ALTSCREEN;
1563 tscrolldown(int orig, int n)
1568 LIMIT(n, 0, term.bot-orig+1);
1570 tsetdirt(orig, term.bot-n);
1571 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1573 for (i = term.bot; i >= orig+n; i--) {
1574 temp = term.line[i];
1575 term.line[i] = term.line[i-n];
1576 term.line[i-n] = temp;
1583 tscrollup(int orig, int n)
1588 LIMIT(n, 0, term.bot-orig+1);
1590 tclearregion(0, orig, term.col-1, orig+n-1);
1591 tsetdirt(orig+n, term.bot);
1593 for (i = orig; i <= term.bot-n; i++) {
1594 temp = term.line[i];
1595 term.line[i] = term.line[i+n];
1596 term.line[i+n] = temp;
1599 selscroll(orig, -n);
1603 selscroll(int orig, int n)
1608 if (BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1609 if ((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1613 if (sel.type == SEL_RECTANGULAR) {
1614 if (sel.ob.y < term.top)
1615 sel.ob.y = term.top;
1616 if (sel.oe.y > term.bot)
1617 sel.oe.y = term.bot;
1619 if (sel.ob.y < term.top) {
1620 sel.ob.y = term.top;
1623 if (sel.oe.y > term.bot) {
1624 sel.oe.y = term.bot;
1625 sel.oe.x = term.col;
1633 tnewline(int first_col)
1637 if (y == term.bot) {
1638 tscrollup(term.top, 1);
1642 tmoveto(first_col ? 0 : term.c.x, y);
1648 char *p = csiescseq.buf, *np;
1657 csiescseq.buf[csiescseq.len] = '\0';
1658 while (p < csiescseq.buf+csiescseq.len) {
1660 v = strtol(p, &np, 10);
1663 if (v == LONG_MAX || v == LONG_MIN)
1665 csiescseq.arg[csiescseq.narg++] = v;
1667 if (*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1671 csiescseq.mode[0] = *p++;
1672 csiescseq.mode[1] = (p < csiescseq.buf+csiescseq.len) ? *p : '\0';
1675 /* for absolute user moves, when decom is set */
1677 tmoveato(int x, int y)
1679 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1683 tmoveto(int x, int y)
1687 if (term.c.state & CURSOR_ORIGIN) {
1692 maxy = term.row - 1;
1694 term.c.state &= ~CURSOR_WRAPNEXT;
1695 term.c.x = LIMIT(x, 0, term.col-1);
1696 term.c.y = LIMIT(y, miny, maxy);
1700 tsetchar(Rune u, Glyph *attr, int x, int y)
1702 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1703 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1704 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1705 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1706 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1707 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1708 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1709 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1710 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1714 * The table is proudly stolen from rxvt.
1716 if (term.trantbl[term.charset] == CS_GRAPHIC0 &&
1717 BETWEEN(u, 0x41, 0x7e) && vt100_0[u - 0x41])
1718 utf8decode(vt100_0[u - 0x41], &u, UTF_SIZ);
1720 if (term.line[y][x].mode & ATTR_WIDE) {
1721 if (x+1 < term.col) {
1722 term.line[y][x+1].u = ' ';
1723 term.line[y][x+1].mode &= ~ATTR_WDUMMY;
1725 } else if (term.line[y][x].mode & ATTR_WDUMMY) {
1726 term.line[y][x-1].u = ' ';
1727 term.line[y][x-1].mode &= ~ATTR_WIDE;
1731 term.line[y][x] = *attr;
1732 term.line[y][x].u = u;
1736 tclearregion(int x1, int y1, int x2, int y2)
1742 temp = x1, x1 = x2, x2 = temp;
1744 temp = y1, y1 = y2, y2 = temp;
1746 LIMIT(x1, 0, term.col-1);
1747 LIMIT(x2, 0, term.col-1);
1748 LIMIT(y1, 0, term.row-1);
1749 LIMIT(y2, 0, term.row-1);
1751 for (y = y1; y <= y2; y++) {
1753 for (x = x1; x <= x2; x++) {
1754 gp = &term.line[y][x];
1757 gp->fg = term.c.attr.fg;
1758 gp->bg = term.c.attr.bg;
1771 LIMIT(n, 0, term.col - term.c.x);
1775 size = term.col - src;
1776 line = term.line[term.c.y];
1778 memmove(&line[dst], &line[src], size * sizeof(Glyph));
1779 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1788 LIMIT(n, 0, term.col - term.c.x);
1792 size = term.col - dst;
1793 line = term.line[term.c.y];
1795 memmove(&line[dst], &line[src], size * sizeof(Glyph));
1796 tclearregion(src, term.c.y, dst - 1, term.c.y);
1800 tinsertblankline(int n)
1802 if (BETWEEN(term.c.y, term.top, term.bot))
1803 tscrolldown(term.c.y, n);
1809 if (BETWEEN(term.c.y, term.top, term.bot))
1810 tscrollup(term.c.y, n);
1814 tdefcolor(int *attr, int *npar, int l)
1819 switch (attr[*npar + 1]) {
1820 case 2: /* direct color in RGB space */
1821 if (*npar + 4 >= l) {
1823 "erresc(38): Incorrect number of parameters (%d)\n",
1827 r = attr[*npar + 2];
1828 g = attr[*npar + 3];
1829 b = attr[*npar + 4];
1831 if (!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1832 fprintf(stderr, "erresc: bad rgb color (%u,%u,%u)\n",
1835 idx = TRUECOLOR(r, g, b);
1837 case 5: /* indexed color */
1838 if (*npar + 2 >= l) {
1840 "erresc(38): Incorrect number of parameters (%d)\n",
1845 if (!BETWEEN(attr[*npar], 0, 255))
1846 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
1850 case 0: /* implemented defined (only foreground) */
1851 case 1: /* transparent */
1852 case 3: /* direct color in CMY space */
1853 case 4: /* direct color in CMYK space */
1856 "erresc(38): gfx attr %d unknown\n", attr[*npar]);
1864 tsetattr(int *attr, int l)
1869 for (i = 0; i < l; i++) {
1872 term.c.attr.mode &= ~(
1881 term.c.attr.fg = defaultfg;
1882 term.c.attr.bg = defaultbg;
1885 term.c.attr.mode |= ATTR_BOLD;
1888 term.c.attr.mode |= ATTR_FAINT;
1891 term.c.attr.mode |= ATTR_ITALIC;
1894 term.c.attr.mode |= ATTR_UNDERLINE;
1896 case 5: /* slow blink */
1898 case 6: /* rapid blink */
1899 term.c.attr.mode |= ATTR_BLINK;
1902 term.c.attr.mode |= ATTR_REVERSE;
1905 term.c.attr.mode |= ATTR_INVISIBLE;
1908 term.c.attr.mode |= ATTR_STRUCK;
1911 term.c.attr.mode &= ~(ATTR_BOLD | ATTR_FAINT);
1914 term.c.attr.mode &= ~ATTR_ITALIC;
1917 term.c.attr.mode &= ~ATTR_UNDERLINE;
1920 term.c.attr.mode &= ~ATTR_BLINK;
1923 term.c.attr.mode &= ~ATTR_REVERSE;
1926 term.c.attr.mode &= ~ATTR_INVISIBLE;
1929 term.c.attr.mode &= ~ATTR_STRUCK;
1932 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1933 term.c.attr.fg = idx;
1936 term.c.attr.fg = defaultfg;
1939 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1940 term.c.attr.bg = idx;
1943 term.c.attr.bg = defaultbg;
1946 if (BETWEEN(attr[i], 30, 37)) {
1947 term.c.attr.fg = attr[i] - 30;
1948 } else if (BETWEEN(attr[i], 40, 47)) {
1949 term.c.attr.bg = attr[i] - 40;
1950 } else if (BETWEEN(attr[i], 90, 97)) {
1951 term.c.attr.fg = attr[i] - 90 + 8;
1952 } else if (BETWEEN(attr[i], 100, 107)) {
1953 term.c.attr.bg = attr[i] - 100 + 8;
1956 "erresc(default): gfx attr %d unknown\n",
1957 attr[i]), csidump();
1965 tsetscroll(int t, int b)
1969 LIMIT(t, 0, term.row-1);
1970 LIMIT(b, 0, term.row-1);
1981 tsetmode(int priv, int set, int *args, int narg)
1986 for (lim = args + narg; args < lim; ++args) {
1989 case 1: /* DECCKM -- Cursor key */
1990 MODBIT(term.mode, set, MODE_APPCURSOR);
1992 case 5: /* DECSCNM -- Reverse video */
1994 MODBIT(term.mode, set, MODE_REVERSE);
1995 if (mode != term.mode)
1998 case 6: /* DECOM -- Origin */
1999 MODBIT(term.c.state, set, CURSOR_ORIGIN);
2002 case 7: /* DECAWM -- Auto wrap */
2003 MODBIT(term.mode, set, MODE_WRAP);
2005 case 0: /* Error (IGNORED) */
2006 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
2007 case 3: /* DECCOLM -- Column (IGNORED) */
2008 case 4: /* DECSCLM -- Scroll (IGNORED) */
2009 case 8: /* DECARM -- Auto repeat (IGNORED) */
2010 case 18: /* DECPFF -- Printer feed (IGNORED) */
2011 case 19: /* DECPEX -- Printer extent (IGNORED) */
2012 case 42: /* DECNRCM -- National characters (IGNORED) */
2013 case 12: /* att610 -- Start blinking cursor (IGNORED) */
2015 case 25: /* DECTCEM -- Text Cursor Enable Mode */
2016 MODBIT(term.mode, !set, MODE_HIDE);
2018 case 9: /* X10 mouse compatibility mode */
2019 xsetpointermotion(0);
2020 MODBIT(term.mode, 0, MODE_MOUSE);
2021 MODBIT(term.mode, set, MODE_MOUSEX10);
2023 case 1000: /* 1000: report button press */
2024 xsetpointermotion(0);
2025 MODBIT(term.mode, 0, MODE_MOUSE);
2026 MODBIT(term.mode, set, MODE_MOUSEBTN);
2028 case 1002: /* 1002: report motion on button press */
2029 xsetpointermotion(0);
2030 MODBIT(term.mode, 0, MODE_MOUSE);
2031 MODBIT(term.mode, set, MODE_MOUSEMOTION);
2033 case 1003: /* 1003: enable all mouse motions */
2034 xsetpointermotion(set);
2035 MODBIT(term.mode, 0, MODE_MOUSE);
2036 MODBIT(term.mode, set, MODE_MOUSEMANY);
2038 case 1004: /* 1004: send focus events to tty */
2039 MODBIT(term.mode, set, MODE_FOCUS);
2041 case 1006: /* 1006: extended reporting mode */
2042 MODBIT(term.mode, set, MODE_MOUSESGR);
2045 MODBIT(term.mode, set, MODE_8BIT);
2047 case 1049: /* swap screen & set/restore cursor as xterm */
2048 if (!allowaltscreen)
2050 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
2052 case 47: /* swap screen */
2054 if (!allowaltscreen)
2056 alt = IS_SET(MODE_ALTSCREEN);
2058 tclearregion(0, 0, term.col-1,
2061 if (set ^ alt) /* set is always 1 or 0 */
2067 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
2069 case 2004: /* 2004: bracketed paste mode */
2070 MODBIT(term.mode, set, MODE_BRCKTPASTE);
2072 /* Not implemented mouse modes. See comments there. */
2073 case 1001: /* mouse highlight mode; can hang the
2074 terminal by design when implemented. */
2075 case 1005: /* UTF-8 mouse mode; will confuse
2076 applications not supporting UTF-8
2078 case 1015: /* urxvt mangled mouse mode; incompatible
2079 and can be mistaken for other control
2083 "erresc: unknown private set/reset mode %d\n",
2089 case 0: /* Error (IGNORED) */
2091 case 2: /* KAM -- keyboard action */
2092 MODBIT(term.mode, set, MODE_KBDLOCK);
2094 case 4: /* IRM -- Insertion-replacement */
2095 MODBIT(term.mode, set, MODE_INSERT);
2097 case 12: /* SRM -- Send/Receive */
2098 MODBIT(term.mode, !set, MODE_ECHO);
2100 case 20: /* LNM -- Linefeed/new line */
2101 MODBIT(term.mode, set, MODE_CRLF);
2105 "erresc: unknown set/reset mode %d\n",
2119 switch (csiescseq.mode[0]) {
2122 fprintf(stderr, "erresc: unknown csi ");
2126 case '@': /* ICH -- Insert <n> blank char */
2127 DEFAULT(csiescseq.arg[0], 1);
2128 tinsertblank(csiescseq.arg[0]);
2130 case 'A': /* CUU -- Cursor <n> Up */
2131 DEFAULT(csiescseq.arg[0], 1);
2132 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
2134 case 'B': /* CUD -- Cursor <n> Down */
2135 case 'e': /* VPR --Cursor <n> Down */
2136 DEFAULT(csiescseq.arg[0], 1);
2137 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
2139 case 'i': /* MC -- Media Copy */
2140 switch (csiescseq.arg[0]) {
2145 tdumpline(term.c.y);
2151 term.mode &= ~MODE_PRINT;
2154 term.mode |= MODE_PRINT;
2158 case 'c': /* DA -- Device Attributes */
2159 if (csiescseq.arg[0] == 0)
2160 ttywrite(vtiden, sizeof(vtiden) - 1);
2162 case 'C': /* CUF -- Cursor <n> Forward */
2163 case 'a': /* HPR -- Cursor <n> Forward */
2164 DEFAULT(csiescseq.arg[0], 1);
2165 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
2167 case 'D': /* CUB -- Cursor <n> Backward */
2168 DEFAULT(csiescseq.arg[0], 1);
2169 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
2171 case 'E': /* CNL -- Cursor <n> Down and first col */
2172 DEFAULT(csiescseq.arg[0], 1);
2173 tmoveto(0, term.c.y+csiescseq.arg[0]);
2175 case 'F': /* CPL -- Cursor <n> Up and first col */
2176 DEFAULT(csiescseq.arg[0], 1);
2177 tmoveto(0, term.c.y-csiescseq.arg[0]);
2179 case 'g': /* TBC -- Tabulation clear */
2180 switch (csiescseq.arg[0]) {
2181 case 0: /* clear current tab stop */
2182 term.tabs[term.c.x] = 0;
2184 case 3: /* clear all the tabs */
2185 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
2191 case 'G': /* CHA -- Move to <col> */
2193 DEFAULT(csiescseq.arg[0], 1);
2194 tmoveto(csiescseq.arg[0]-1, term.c.y);
2196 case 'H': /* CUP -- Move to <row> <col> */
2198 DEFAULT(csiescseq.arg[0], 1);
2199 DEFAULT(csiescseq.arg[1], 1);
2200 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
2202 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
2203 DEFAULT(csiescseq.arg[0], 1);
2204 tputtab(csiescseq.arg[0]);
2206 case 'J': /* ED -- Clear screen */
2208 switch (csiescseq.arg[0]) {
2210 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
2211 if (term.c.y < term.row-1) {
2212 tclearregion(0, term.c.y+1, term.col-1,
2218 tclearregion(0, 0, term.col-1, term.c.y-1);
2219 tclearregion(0, term.c.y, term.c.x, term.c.y);
2222 tclearregion(0, 0, term.col-1, term.row-1);
2228 case 'K': /* EL -- Clear line */
2229 switch (csiescseq.arg[0]) {
2231 tclearregion(term.c.x, term.c.y, term.col-1,
2235 tclearregion(0, term.c.y, term.c.x, term.c.y);
2238 tclearregion(0, term.c.y, term.col-1, term.c.y);
2242 case 'S': /* SU -- Scroll <n> line up */
2243 DEFAULT(csiescseq.arg[0], 1);
2244 tscrollup(term.top, csiescseq.arg[0]);
2246 case 'T': /* SD -- Scroll <n> line down */
2247 DEFAULT(csiescseq.arg[0], 1);
2248 tscrolldown(term.top, csiescseq.arg[0]);
2250 case 'L': /* IL -- Insert <n> blank lines */
2251 DEFAULT(csiescseq.arg[0], 1);
2252 tinsertblankline(csiescseq.arg[0]);
2254 case 'l': /* RM -- Reset Mode */
2255 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2257 case 'M': /* DL -- Delete <n> lines */
2258 DEFAULT(csiescseq.arg[0], 1);
2259 tdeleteline(csiescseq.arg[0]);
2261 case 'X': /* ECH -- Erase <n> char */
2262 DEFAULT(csiescseq.arg[0], 1);
2263 tclearregion(term.c.x, term.c.y,
2264 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2266 case 'P': /* DCH -- Delete <n> char */
2267 DEFAULT(csiescseq.arg[0], 1);
2268 tdeletechar(csiescseq.arg[0]);
2270 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2271 DEFAULT(csiescseq.arg[0], 1);
2272 tputtab(-csiescseq.arg[0]);
2274 case 'd': /* VPA -- Move to <row> */
2275 DEFAULT(csiescseq.arg[0], 1);
2276 tmoveato(term.c.x, csiescseq.arg[0]-1);
2278 case 'h': /* SM -- Set terminal mode */
2279 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2281 case 'm': /* SGR -- Terminal attribute (color) */
2282 tsetattr(csiescseq.arg, csiescseq.narg);
2284 case 'n': /* DSR – Device Status Report (cursor position) */
2285 if (csiescseq.arg[0] == 6) {
2286 len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
2287 term.c.y+1, term.c.x+1);
2291 case 'r': /* DECSTBM -- Set Scrolling Region */
2292 if (csiescseq.priv) {
2295 DEFAULT(csiescseq.arg[0], 1);
2296 DEFAULT(csiescseq.arg[1], term.row);
2297 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2301 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2302 tcursor(CURSOR_SAVE);
2304 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2305 tcursor(CURSOR_LOAD);
2308 switch (csiescseq.mode[1]) {
2309 case 'q': /* DECSCUSR -- Set Cursor Style */
2310 DEFAULT(csiescseq.arg[0], 1);
2311 if (!BETWEEN(csiescseq.arg[0], 0, 6)) {
2314 xw.cursor = csiescseq.arg[0];
2330 for (i = 0; i < csiescseq.len; i++) {
2331 c = csiescseq.buf[i] & 0xff;
2334 } else if (c == '\n') {
2336 } else if (c == '\r') {
2338 } else if (c == 0x1b) {
2341 printf("(%02x)", c);
2350 memset(&csiescseq, 0, sizeof(csiescseq));
2359 term.esc &= ~(ESC_STR_END|ESC_STR);
2361 par = (narg = strescseq.narg) ? atoi(strescseq.args[0]) : 0;
2363 switch (strescseq.type) {
2364 case ']': /* OSC -- Operating System Command */
2370 xsettitle(strescseq.args[1]);
2372 case 4: /* color set */
2375 p = strescseq.args[2];
2377 case 104: /* color reset, here p = NULL */
2378 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2379 if (xsetcolorname(j, p)) {
2380 fprintf(stderr, "erresc: invalid color %s\n", p);
2383 * TODO if defaultbg color is changed, borders
2391 case 'k': /* old title set compatibility */
2392 xsettitle(strescseq.args[0]);
2394 case 'P': /* DCS -- Device Control String */
2395 case '_': /* APC -- Application Program Command */
2396 case '^': /* PM -- Privacy Message */
2400 fprintf(stderr, "erresc: unknown str ");
2408 char *p = strescseq.buf;
2411 strescseq.buf[strescseq.len] = '\0';
2416 while (strescseq.narg < STR_ARG_SIZ) {
2417 strescseq.args[strescseq.narg++] = p;
2418 while ((c = *p) != ';' && c != '\0')
2432 printf("ESC%c", strescseq.type);
2433 for (i = 0; i < strescseq.len; i++) {
2434 c = strescseq.buf[i] & 0xff;
2437 } else if (isprint(c)) {
2439 } else if (c == '\n') {
2441 } else if (c == '\r') {
2443 } else if (c == 0x1b) {
2446 printf("(%02x)", c);
2455 memset(&strescseq, 0, sizeof(strescseq));
2459 tprinter(char *s, size_t len)
2461 if (iofd != -1 && xwrite(iofd, s, len) < 0) {
2462 fprintf(stderr, "Error writing in %s:%s\n",
2463 opt_io, strerror(errno));
2470 toggleprinter(const Arg *arg)
2472 term.mode ^= MODE_PRINT;
2476 printscreen(const Arg *arg)
2482 printsel(const Arg *arg)
2492 if ((ptr = getsel())) {
2493 tprinter(ptr, strlen(ptr));
2504 bp = &term.line[n][0];
2505 end = &bp[MIN(tlinelen(n), term.col) - 1];
2506 if (bp != end || bp->u != ' ') {
2507 for ( ;bp <= end; ++bp)
2508 tprinter(buf, utf8encode(bp->u, buf));
2518 for (i = 0; i < term.row; ++i)
2528 while (x < term.col && n--)
2529 for (++x; x < term.col && !term.tabs[x]; ++x)
2532 while (x > 0 && n++)
2533 for (--x; x > 0 && !term.tabs[x]; --x)
2536 term.c.x = LIMIT(x, 0, term.col-1);
2542 if (ISCONTROL(u)) { /* control code */
2547 } else if (u != '\n' && u != '\r' && u != '\t') {
2556 tdeftran(char ascii)
2558 static char cs[] = "0B";
2559 static int vcs[] = {CS_GRAPHIC0, CS_USA};
2562 if ((p = strchr(cs, ascii)) == NULL) {
2563 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2565 term.trantbl[term.icharset] = vcs[p - cs];
2574 if (c == '8') { /* DEC screen alignment test. */
2575 for (x = 0; x < term.col; ++x) {
2576 for (y = 0; y < term.row; ++y)
2577 tsetchar('E', &term.c.attr, x, y);
2583 tstrsequence(uchar c)
2586 case 0x90: /* DCS -- Device Control String */
2589 case 0x9f: /* APC -- Application Program Command */
2592 case 0x9e: /* PM -- Privacy Message */
2595 case 0x9d: /* OSC -- Operating System Command */
2601 term.esc |= ESC_STR;
2605 tcontrolcode(uchar ascii)
2612 tmoveto(term.c.x-1, term.c.y);
2615 tmoveto(0, term.c.y);
2620 /* go to first col if the mode is set */
2621 tnewline(IS_SET(MODE_CRLF));
2623 case '\a': /* BEL */
2624 if (term.esc & ESC_STR_END) {
2625 /* backwards compatibility to xterm */
2628 if (!(xw.state & WIN_FOCUSED))
2631 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
2634 case '\033': /* ESC */
2636 term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
2637 term.esc |= ESC_START;
2639 case '\016': /* SO (LS1 -- Locking shift 1) */
2640 case '\017': /* SI (LS0 -- Locking shift 0) */
2641 term.charset = 1 - (ascii - '\016');
2643 case '\032': /* SUB */
2644 tsetchar('?', &term.c.attr, term.c.x, term.c.y);
2645 case '\030': /* CAN */
2648 case '\005': /* ENQ (IGNORED) */
2649 case '\000': /* NUL (IGNORED) */
2650 case '\021': /* XON (IGNORED) */
2651 case '\023': /* XOFF (IGNORED) */
2652 case 0177: /* DEL (IGNORED) */
2654 case 0x84: /* TODO: IND */
2656 case 0x85: /* NEL -- Next line */
2657 tnewline(1); /* always go to first col */
2659 case 0x88: /* HTS -- Horizontal tab stop */
2660 term.tabs[term.c.x] = 1;
2662 case 0x8d: /* TODO: RI */
2663 case 0x8e: /* TODO: SS2 */
2664 case 0x8f: /* TODO: SS3 */
2665 case 0x98: /* TODO: SOS */
2667 case 0x9a: /* DECID -- Identify Terminal */
2668 ttywrite(vtiden, sizeof(vtiden) - 1);
2670 case 0x9b: /* TODO: CSI */
2671 case 0x9c: /* TODO: ST */
2673 case 0x90: /* DCS -- Device Control String */
2674 case 0x9f: /* APC -- Application Program Command */
2675 case 0x9e: /* PM -- Privacy Message */
2676 case 0x9d: /* OSC -- Operating System Command */
2677 tstrsequence(ascii);
2680 /* only CAN, SUB, \a and C1 chars interrupt a sequence */
2681 term.esc &= ~(ESC_STR_END|ESC_STR);
2685 * returns 1 when the sequence is finished and it hasn't to read
2686 * more characters for this sequence, otherwise 0
2689 eschandle(uchar ascii)
2693 term.esc |= ESC_CSI;
2696 term.esc |= ESC_TEST;
2698 case 'P': /* DCS -- Device Control String */
2699 case '_': /* APC -- Application Program Command */
2700 case '^': /* PM -- Privacy Message */
2701 case ']': /* OSC -- Operating System Command */
2702 case 'k': /* old title set compatibility */
2703 tstrsequence(ascii);
2705 case 'n': /* LS2 -- Locking shift 2 */
2706 case 'o': /* LS3 -- Locking shift 3 */
2707 term.charset = 2 + (ascii - 'n');
2709 case '(': /* GZD4 -- set primary charset G0 */
2710 case ')': /* G1D4 -- set secondary charset G1 */
2711 case '*': /* G2D4 -- set tertiary charset G2 */
2712 case '+': /* G3D4 -- set quaternary charset G3 */
2713 term.icharset = ascii - '(';
2714 term.esc |= ESC_ALTCHARSET;
2716 case 'D': /* IND -- Linefeed */
2717 if (term.c.y == term.bot) {
2718 tscrollup(term.top, 1);
2720 tmoveto(term.c.x, term.c.y+1);
2723 case 'E': /* NEL -- Next line */
2724 tnewline(1); /* always go to first col */
2726 case 'H': /* HTS -- Horizontal tab stop */
2727 term.tabs[term.c.x] = 1;
2729 case 'M': /* RI -- Reverse index */
2730 if (term.c.y == term.top) {
2731 tscrolldown(term.top, 1);
2733 tmoveto(term.c.x, term.c.y-1);
2736 case 'Z': /* DECID -- Identify Terminal */
2737 ttywrite(vtiden, sizeof(vtiden) - 1);
2739 case 'c': /* RIS -- Reset to inital state */
2744 case '=': /* DECPAM -- Application keypad */
2745 term.mode |= MODE_APPKEYPAD;
2747 case '>': /* DECPNM -- Normal keypad */
2748 term.mode &= ~MODE_APPKEYPAD;
2750 case '7': /* DECSC -- Save Cursor */
2751 tcursor(CURSOR_SAVE);
2753 case '8': /* DECRC -- Restore Cursor */
2754 tcursor(CURSOR_LOAD);
2756 case '\\': /* ST -- String Terminator */
2757 if (term.esc & ESC_STR_END)
2761 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2762 (uchar) ascii, isprint(ascii)? ascii:'.');
2776 len = utf8encode(u, c);
2777 if ((width = wcwidth(u)) == -1) {
2778 memcpy(c, "\357\277\275", 4); /* UTF_INVALID */
2782 if (IS_SET(MODE_PRINT))
2784 control = ISCONTROL(u);
2787 * STR sequence must be checked before anything else
2788 * because it uses all following characters until it
2789 * receives a ESC, a SUB, a ST or any other C1 control
2792 if (term.esc & ESC_STR) {
2793 if (u == '\a' || u == 030 || u == 032 || u == 033 ||
2795 term.esc &= ~(ESC_START|ESC_STR);
2796 term.esc |= ESC_STR_END;
2797 } else if (strescseq.len + len < sizeof(strescseq.buf) - 1) {
2798 memmove(&strescseq.buf[strescseq.len], c, len);
2799 strescseq.len += len;
2803 * Here is a bug in terminals. If the user never sends
2804 * some code to stop the str or esc command, then st
2805 * will stop responding. But this is better than
2806 * silently failing with unknown characters. At least
2807 * then users will report back.
2809 * In the case users ever get fixed, here is the code:
2820 * Actions of control codes must be performed as soon they arrive
2821 * because they can be embedded inside a control sequence, and
2822 * they must not cause conflicts with sequences.
2827 * control codes are not shown ever
2830 } else if (term.esc & ESC_START) {
2831 if (term.esc & ESC_CSI) {
2832 csiescseq.buf[csiescseq.len++] = u;
2833 if (BETWEEN(u, 0x40, 0x7E)
2834 || csiescseq.len >= \
2835 sizeof(csiescseq.buf)-1) {
2841 } else if (term.esc & ESC_ALTCHARSET) {
2843 } else if (term.esc & ESC_TEST) {
2848 /* sequence already finished */
2852 * All characters which form part of a sequence are not
2857 if (sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2860 gp = &term.line[term.c.y][term.c.x];
2861 if (IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2862 gp->mode |= ATTR_WRAP;
2864 gp = &term.line[term.c.y][term.c.x];
2867 if (IS_SET(MODE_INSERT) && term.c.x+width < term.col)
2868 memmove(gp+width, gp, (term.col - term.c.x - width) * sizeof(Glyph));
2870 if (term.c.x+width > term.col) {
2872 gp = &term.line[term.c.y][term.c.x];
2875 tsetchar(u, &term.c.attr, term.c.x, term.c.y);
2878 gp->mode |= ATTR_WIDE;
2879 if (term.c.x+1 < term.col) {
2881 gp[1].mode = ATTR_WDUMMY;
2884 if (term.c.x+width < term.col) {
2885 tmoveto(term.c.x+width, term.c.y);
2887 term.c.state |= CURSOR_WRAPNEXT;
2892 tresize(int col, int row)
2895 int minrow = MIN(row, term.row);
2896 int mincol = MIN(col, term.col);
2900 if (col < 1 || row < 1) {
2902 "tresize: error resizing to %dx%d\n", col, row);
2907 * slide screen to keep cursor where we expect it -
2908 * tscrollup would work here, but we can optimize to
2909 * memmove because we're freeing the earlier lines
2911 for (i = 0; i <= term.c.y - row; i++) {
2915 /* ensure that both src and dst are not NULL */
2917 memmove(term.line, term.line + i, row * sizeof(Line));
2918 memmove(term.alt, term.alt + i, row * sizeof(Line));
2920 for (i += row; i < term.row; i++) {
2925 /* resize to new width */
2926 term.specbuf = xrealloc(term.specbuf, col * sizeof(XftGlyphFontSpec));
2928 /* resize to new height */
2929 term.line = xrealloc(term.line, row * sizeof(Line));
2930 term.alt = xrealloc(term.alt, row * sizeof(Line));
2931 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2932 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2934 /* resize each row to new width, zero-pad if needed */
2935 for (i = 0; i < minrow; i++) {
2936 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2937 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2940 /* allocate any new rows */
2941 for (/* i == minrow */; i < row; i++) {
2942 term.line[i] = xmalloc(col * sizeof(Glyph));
2943 term.alt[i] = xmalloc(col * sizeof(Glyph));
2945 if (col > term.col) {
2946 bp = term.tabs + term.col;
2948 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2949 while (--bp > term.tabs && !*bp)
2951 for (bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2954 /* update terminal size */
2957 /* reset scrolling region */
2958 tsetscroll(0, row-1);
2959 /* make use of the LIMIT in tmoveto */
2960 tmoveto(term.c.x, term.c.y);
2961 /* Clearing both screens (it makes dirty all lines) */
2963 for (i = 0; i < 2; i++) {
2964 if (mincol < col && 0 < minrow) {
2965 tclearregion(mincol, 0, col - 1, minrow - 1);
2967 if (0 < col && minrow < row) {
2968 tclearregion(0, minrow, col - 1, row - 1);
2971 tcursor(CURSOR_LOAD);
2977 xresize(int col, int row)
2979 xw.tw = MAX(1, col * xw.cw);
2980 xw.th = MAX(1, row * xw.ch);
2982 XFreePixmap(xw.dpy, xw.buf);
2983 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2984 DefaultDepth(xw.dpy, xw.scr));
2985 XftDrawChange(xw.draw, xw.buf);
2986 xclear(0, 0, xw.w, xw.h);
2990 sixd_to_16bit(int x)
2992 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2996 xloadcolor(int i, const char *name, Color *ncolor)
2998 XRenderColor color = { .alpha = 0xffff };
3001 if (BETWEEN(i, 16, 255)) { /* 256 color */
3002 if (i < 6*6*6+16) { /* same colors as xterm */
3003 color.red = sixd_to_16bit( ((i-16)/36)%6 );
3004 color.green = sixd_to_16bit( ((i-16)/6) %6 );
3005 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
3006 } else { /* greyscale */
3007 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
3008 color.green = color.blue = color.red;
3010 return XftColorAllocValue(xw.dpy, xw.vis,
3011 xw.cmap, &color, ncolor);
3013 name = colorname[i];
3015 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
3026 for (cp = dc.col; cp < &dc.col[LEN(dc.col)]; ++cp)
3027 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
3030 for (i = 0; i < LEN(dc.col); i++)
3031 if (!xloadcolor(i, NULL, &dc.col[i])) {
3033 die("Could not allocate color '%s'\n", colorname[i]);
3035 die("Could not allocate color %d\n", i);
3041 xsetcolorname(int x, const char *name)
3045 if (!BETWEEN(x, 0, LEN(dc.col)))
3049 if (!xloadcolor(x, name, &ncolor))
3052 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
3058 xtermclear(int col1, int row1, int col2, int row2)
3060 XftDrawRect(xw.draw,
3061 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
3062 borderpx + col1 * xw.cw,
3063 borderpx + row1 * xw.ch,
3064 (col2-col1+1) * xw.cw,
3065 (row2-row1+1) * xw.ch);
3069 * Absolute coordinates.
3072 xclear(int x1, int y1, int x2, int y2)
3074 XftDrawRect(xw.draw,
3075 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
3076 x1, y1, x2-x1, y2-y1);
3082 XClassHint class = {opt_class ? opt_class : termname, termname};
3083 XWMHints wm = {.flags = InputHint, .input = 1};
3084 XSizeHints *sizeh = NULL;
3086 sizeh = XAllocSizeHints();
3088 sizeh->flags = PSize | PResizeInc | PBaseSize;
3089 sizeh->height = xw.h;
3090 sizeh->width = xw.w;
3091 sizeh->height_inc = xw.ch;
3092 sizeh->width_inc = xw.cw;
3093 sizeh->base_height = 2 * borderpx;
3094 sizeh->base_width = 2 * borderpx;
3096 sizeh->flags |= PMaxSize | PMinSize;
3097 sizeh->min_width = sizeh->max_width = xw.w;
3098 sizeh->min_height = sizeh->max_height = xw.h;
3100 if (xw.gm & (XValue|YValue)) {
3101 sizeh->flags |= USPosition | PWinGravity;
3104 sizeh->win_gravity = xgeommasktogravity(xw.gm);
3107 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
3113 xgeommasktogravity(int mask)
3115 switch (mask & (XNegative|YNegative)) {
3117 return NorthWestGravity;
3119 return NorthEastGravity;
3121 return SouthWestGravity;
3123 return SouthEastGravity;
3127 xloadfont(Font *f, FcPattern *pattern)
3132 match = FcFontMatch(NULL, pattern, &result);
3136 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
3137 FcPatternDestroy(match);
3142 f->pattern = FcPatternDuplicate(pattern);
3144 f->ascent = f->match->ascent;
3145 f->descent = f->match->descent;
3147 f->rbearing = f->match->max_advance_width;
3149 f->height = f->ascent + f->descent;
3150 f->width = f->lbearing + f->rbearing;
3156 xloadfonts(char *fontstr, double fontsize)
3162 if (fontstr[0] == '-') {
3163 pattern = XftXlfdParse(fontstr, False, False);
3165 pattern = FcNameParse((FcChar8 *)fontstr);
3169 die("st: can't open font %s\n", fontstr);
3172 FcPatternDel(pattern, FC_PIXEL_SIZE);
3173 FcPatternDel(pattern, FC_SIZE);
3174 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
3175 usedfontsize = fontsize;
3177 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
3179 usedfontsize = fontval;
3180 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
3185 * Default font size is 12, if none given. This is to
3186 * have a known usedfontsize value.
3188 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
3191 defaultfontsize = usedfontsize;
3194 FcConfigSubstitute(0, pattern, FcMatchPattern);
3195 FcDefaultSubstitute(pattern);
3197 if (xloadfont(&dc.font, pattern))
3198 die("st: can't open font %s\n", fontstr);
3200 if (usedfontsize < 0) {
3201 FcPatternGetDouble(dc.font.match->pattern,
3202 FC_PIXEL_SIZE, 0, &fontval);
3203 usedfontsize = fontval;
3205 defaultfontsize = fontval;
3208 /* Setting character width and height. */
3209 xw.cw = ceilf(dc.font.width * cwscale);
3210 xw.ch = ceilf(dc.font.height * chscale);
3212 FcPatternDel(pattern, FC_SLANT);
3213 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
3214 if (xloadfont(&dc.ifont, pattern))
3215 die("st: can't open font %s\n", fontstr);
3217 FcPatternDel(pattern, FC_WEIGHT);
3218 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
3219 if (xloadfont(&dc.ibfont, pattern))
3220 die("st: can't open font %s\n", fontstr);
3222 FcPatternDel(pattern, FC_SLANT);
3223 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
3224 if (xloadfont(&dc.bfont, pattern))
3225 die("st: can't open font %s\n", fontstr);
3227 FcPatternDestroy(pattern);
3231 xunloadfont(Font *f)
3233 XftFontClose(xw.dpy, f->match);
3234 FcPatternDestroy(f->pattern);
3236 FcFontSetDestroy(f->set);
3242 /* Free the loaded fonts in the font cache. */
3244 XftFontClose(xw.dpy, frc[--frclen].font);
3246 xunloadfont(&dc.font);
3247 xunloadfont(&dc.bfont);
3248 xunloadfont(&dc.ifont);
3249 xunloadfont(&dc.ibfont);
3253 xzoom(const Arg *arg)
3257 larg.f = usedfontsize + arg->f;
3262 xzoomabs(const Arg *arg)
3265 xloadfonts(usedfont, arg->f);
3272 xzoomreset(const Arg *arg)
3276 if (defaultfontsize > 0) {
3277 larg.f = defaultfontsize;
3288 pid_t thispid = getpid();
3290 if (!(xw.dpy = XOpenDisplay(NULL)))
3291 die("Can't open display\n");
3292 xw.scr = XDefaultScreen(xw.dpy);
3293 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
3297 die("Could not init fontconfig.\n");
3299 usedfont = (opt_font == NULL)? font : opt_font;
3300 xloadfonts(usedfont, 0);
3303 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
3306 /* adjust fixed window geometry */
3307 xw.w = 2 * borderpx + term.col * xw.cw;
3308 xw.h = 2 * borderpx + term.row * xw.ch;
3309 if (xw.gm & XNegative)
3310 xw.l += DisplayWidth(xw.dpy, xw.scr) - xw.w - 2;
3311 if (xw.gm & YNegative)
3312 xw.t += DisplayWidth(xw.dpy, xw.scr) - xw.h - 2;
3315 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
3316 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
3317 xw.attrs.bit_gravity = NorthWestGravity;
3318 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
3319 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
3320 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
3321 xw.attrs.colormap = xw.cmap;
3323 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
3324 parent = XRootWindow(xw.dpy, xw.scr);
3325 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
3326 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
3327 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
3328 | CWEventMask | CWColormap, &xw.attrs);
3330 memset(&gcvalues, 0, sizeof(gcvalues));
3331 gcvalues.graphics_exposures = False;
3332 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
3334 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3335 DefaultDepth(xw.dpy, xw.scr));
3336 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
3337 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
3339 /* Xft rendering context */
3340 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
3343 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3344 XSetLocaleModifiers("@im=local");
3345 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3346 XSetLocaleModifiers("@im=");
3347 if ((xw.xim = XOpenIM(xw.dpy,
3348 NULL, NULL, NULL)) == NULL) {
3349 die("XOpenIM failed. Could not open input"
3354 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
3355 | XIMStatusNothing, XNClientWindow, xw.win,
3356 XNFocusWindow, xw.win, NULL);
3358 die("XCreateIC failed. Could not obtain input method.\n");
3360 /* white cursor, black outline */
3361 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
3362 XDefineCursor(xw.dpy, xw.win, cursor);
3363 XRecolorCursor(xw.dpy, cursor,
3364 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
3365 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
3367 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
3368 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
3369 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
3370 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
3372 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
3373 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
3374 PropModeReplace, (uchar *)&thispid, 1);
3377 XMapWindow(xw.dpy, xw.win);
3379 XSync(xw.dpy, False);
3383 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
3385 float winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch, xp, yp;
3386 ushort mode, prevmode = USHRT_MAX;
3387 Font *font = &dc.font;
3388 int frcflags = FRC_NORMAL;
3389 float runewidth = xw.cw;
3393 FcPattern *fcpattern, *fontpattern;
3394 FcFontSet *fcsets[] = { NULL };
3395 FcCharSet *fccharset;
3396 int i, f, numspecs = 0;
3398 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
3399 /* Fetch rune and mode for current glyph. */
3401 mode = glyphs[i].mode;
3403 /* Skip dummy wide-character spacing. */
3404 if (mode == ATTR_WDUMMY)
3407 /* Determine font for glyph if different from previous glyph. */
3408 if (prevmode != mode) {
3411 frcflags = FRC_NORMAL;
3412 runewidth = xw.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
3413 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
3415 frcflags = FRC_ITALICBOLD;
3416 } else if (mode & ATTR_ITALIC) {
3418 frcflags = FRC_ITALIC;
3419 } else if (mode & ATTR_BOLD) {
3421 frcflags = FRC_BOLD;
3423 yp = winy + font->ascent;
3426 /* Lookup character index with default font. */
3427 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
3429 specs[numspecs].font = font->match;
3430 specs[numspecs].glyph = glyphidx;
3431 specs[numspecs].x = (short)xp;
3432 specs[numspecs].y = (short)yp;
3438 /* Fallback on font cache, search the font cache for match. */
3439 for (f = 0; f < frclen; f++) {
3440 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
3441 /* Everything correct. */
3442 if (glyphidx && frc[f].flags == frcflags)
3444 /* We got a default font for a not found glyph. */
3445 if (!glyphidx && frc[f].flags == frcflags
3446 && frc[f].unicodep == rune) {
3451 /* Nothing was found. Use fontconfig to find matching font. */
3454 font->set = FcFontSort(0, font->pattern,
3456 fcsets[0] = font->set;
3459 * Nothing was found in the cache. Now use
3460 * some dozen of Fontconfig calls to get the
3461 * font for one single character.
3463 * Xft and fontconfig are design failures.
3465 fcpattern = FcPatternDuplicate(font->pattern);
3466 fccharset = FcCharSetCreate();
3468 FcCharSetAddChar(fccharset, rune);
3469 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3471 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
3473 FcConfigSubstitute(0, fcpattern,
3475 FcDefaultSubstitute(fcpattern);
3477 fontpattern = FcFontSetMatch(0, fcsets, 1,
3481 * Overwrite or create the new cache entry.
3483 if (frclen >= LEN(frc)) {
3484 frclen = LEN(frc) - 1;
3485 XftFontClose(xw.dpy, frc[frclen].font);
3486 frc[frclen].unicodep = 0;
3489 frc[frclen].font = XftFontOpenPattern(xw.dpy,
3491 frc[frclen].flags = frcflags;
3492 frc[frclen].unicodep = rune;
3494 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
3499 FcPatternDestroy(fcpattern);
3500 FcCharSetDestroy(fccharset);
3503 specs[numspecs].font = frc[f].font;
3504 specs[numspecs].glyph = glyphidx;
3505 specs[numspecs].x = (short)xp;
3506 specs[numspecs].y = (short)(winy + frc[f].font->ascent);
3515 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
3517 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
3518 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
3519 width = charlen * xw.cw;
3520 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
3521 XRenderColor colfg, colbg;
3524 /* Determine foreground and background colors based on mode. */
3525 if (base.fg == defaultfg) {
3526 if (base.mode & ATTR_ITALIC)
3527 base.fg = defaultitalic;
3528 else if ((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD))
3529 base.fg = defaultitalic;
3530 else if (base.mode & ATTR_UNDERLINE)
3531 base.fg = defaultunderline;
3534 if (IS_TRUECOL(base.fg)) {
3535 colfg.alpha = 0xffff;
3536 colfg.red = TRUERED(base.fg);
3537 colfg.green = TRUEGREEN(base.fg);
3538 colfg.blue = TRUEBLUE(base.fg);
3539 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
3542 fg = &dc.col[base.fg];
3545 if (IS_TRUECOL(base.bg)) {
3546 colbg.alpha = 0xffff;
3547 colbg.green = TRUEGREEN(base.bg);
3548 colbg.red = TRUERED(base.bg);
3549 colbg.blue = TRUEBLUE(base.bg);
3550 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
3553 bg = &dc.col[base.bg];
3556 /* Change basic system colors [0-7] to bright system colors [8-15] */
3557 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
3558 fg = &dc.col[base.fg + 8];
3560 if (IS_SET(MODE_REVERSE)) {
3561 if (fg == &dc.col[defaultfg]) {
3562 fg = &dc.col[defaultbg];
3564 colfg.red = ~fg->color.red;
3565 colfg.green = ~fg->color.green;
3566 colfg.blue = ~fg->color.blue;
3567 colfg.alpha = fg->color.alpha;
3568 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
3573 if (bg == &dc.col[defaultbg]) {
3574 bg = &dc.col[defaultfg];
3576 colbg.red = ~bg->color.red;
3577 colbg.green = ~bg->color.green;
3578 colbg.blue = ~bg->color.blue;
3579 colbg.alpha = bg->color.alpha;
3580 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
3586 if (base.mode & ATTR_REVERSE) {
3592 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
3593 colfg.red = fg->color.red / 2;
3594 colfg.green = fg->color.green / 2;
3595 colfg.blue = fg->color.blue / 2;
3596 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
3600 if (base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3603 if (base.mode & ATTR_INVISIBLE)
3606 /* Intelligent cleaning up of the borders. */
3608 xclear(0, (y == 0)? 0 : winy, borderpx,
3609 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3611 if (x + charlen >= term.col) {
3612 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3613 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3616 xclear(winx, 0, winx + width, borderpx);
3617 if (y == term.row-1)
3618 xclear(winx, winy + xw.ch, winx + width, xw.h);
3620 /* Clean up the region we want to draw to. */
3621 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3623 /* Set the clip region because Xft is sometimes dirty. */
3628 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3630 /* Render the glyphs. */
3631 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
3633 /* Render underline and strikethrough. */
3634 if (base.mode & ATTR_UNDERLINE) {
3635 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
3639 if (base.mode & ATTR_STRUCK) {
3640 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
3644 /* Reset clip to none. */
3645 XftDrawSetClip(xw.draw, 0);
3649 xdrawglyph(Glyph g, int x, int y)
3652 XftGlyphFontSpec spec;
3653 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
3654 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
3660 static int oldx = 0, oldy = 0;
3662 Glyph g = {' ', ATTR_NULL, defaultbg, defaultcs};
3664 LIMIT(oldx, 0, term.col-1);
3665 LIMIT(oldy, 0, term.row-1);
3669 /* adjust position if in dummy */
3670 if (term.line[oldy][oldx].mode & ATTR_WDUMMY)
3672 if (term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3675 g.u = term.line[term.c.y][term.c.x].u;
3677 /* remove the old cursor */
3678 xdrawglyph(term.line[oldy][oldx], oldx, oldy);
3680 if (IS_SET(MODE_HIDE))
3683 /* draw the new one */
3684 if (xw.state & WIN_FOCUSED) {
3685 switch (xw.cursor) {
3686 case 0: /* Blinking Block */
3687 case 1: /* Blinking Block (Default) */
3688 case 2: /* Steady Block */
3689 if (IS_SET(MODE_REVERSE)) {
3690 g.mode |= ATTR_REVERSE;
3695 g.mode |= term.line[term.c.y][curx].mode & ATTR_WIDE;
3696 xdrawglyph(g, term.c.x, term.c.y);
3698 case 3: /* Blinking Underline */
3699 case 4: /* Steady Underline */
3700 XftDrawRect(xw.draw, &dc.col[defaultcs],
3701 borderpx + curx * xw.cw,
3702 borderpx + (term.c.y + 1) * xw.ch - cursorthickness,
3703 xw.cw, cursorthickness);
3705 case 5: /* Blinking bar */
3706 case 6: /* Steady bar */
3707 XftDrawRect(xw.draw, &dc.col[defaultcs],
3708 borderpx + curx * xw.cw,
3709 borderpx + term.c.y * xw.ch,
3710 cursorthickness, xw.ch);
3714 XftDrawRect(xw.draw, &dc.col[defaultcs],
3715 borderpx + curx * xw.cw,
3716 borderpx + term.c.y * xw.ch,
3718 XftDrawRect(xw.draw, &dc.col[defaultcs],
3719 borderpx + curx * xw.cw,
3720 borderpx + term.c.y * xw.ch,
3722 XftDrawRect(xw.draw, &dc.col[defaultcs],
3723 borderpx + (curx + 1) * xw.cw - 1,
3724 borderpx + term.c.y * xw.ch,
3726 XftDrawRect(xw.draw, &dc.col[defaultcs],
3727 borderpx + curx * xw.cw,
3728 borderpx + (term.c.y + 1) * xw.ch - 1,
3731 oldx = curx, oldy = term.c.y;
3740 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3742 XSetWMName(xw.dpy, xw.win, &prop);
3743 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
3750 xsettitle(opt_title ? opt_title : "st");
3763 drawregion(0, 0, term.col, term.row);
3764 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3766 XSetForeground(xw.dpy, dc.gc,
3767 dc.col[IS_SET(MODE_REVERSE)?
3768 defaultfg : defaultbg].pixel);
3772 drawregion(int x1, int y1, int x2, int y2)
3774 int i, x, y, ox, numspecs;
3776 XftGlyphFontSpec* specs;
3777 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
3779 if (!(xw.state & WIN_VISIBLE))
3782 for (y = y1; y < y2; y++) {
3786 xtermclear(0, y, term.col, y);
3789 specs = term.specbuf;
3790 numspecs = xmakeglyphfontspecs(specs, &term.line[y][x1], x2 - x1, x1, y);
3793 for (x = x1; x < x2 && i < numspecs; x++) {
3794 new = term.line[y][x];
3795 if (new.mode == ATTR_WDUMMY)
3797 if (ena_sel && selected(x, y))
3798 new.mode ^= ATTR_REVERSE;
3799 if (i > 0 && ATTRCMP(base, new)) {
3800 xdrawglyphfontspecs(specs, base, i, ox, y);
3812 xdrawglyphfontspecs(specs, base, i, ox, y);
3824 visibility(XEvent *ev)
3826 XVisibilityEvent *e = &ev->xvisibility;
3828 MODBIT(xw.state, e->state != VisibilityFullyObscured, WIN_VISIBLE);
3834 xw.state &= ~WIN_VISIBLE;
3838 xsetpointermotion(int set)
3840 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3841 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3845 xseturgency(int add)
3847 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3849 MODBIT(h->flags, add, XUrgencyHint);
3850 XSetWMHints(xw.dpy, xw.win, h);
3857 XFocusChangeEvent *e = &ev->xfocus;
3859 if (e->mode == NotifyGrab)
3862 if (ev->type == FocusIn) {
3863 XSetICFocus(xw.xic);
3864 xw.state |= WIN_FOCUSED;
3866 if (IS_SET(MODE_FOCUS))
3867 ttywrite("\033[I", 3);
3869 XUnsetICFocus(xw.xic);
3870 xw.state &= ~WIN_FOCUSED;
3871 if (IS_SET(MODE_FOCUS))
3872 ttywrite("\033[O", 3);
3877 match(uint mask, uint state)
3879 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
3883 numlock(const Arg *dummy)
3889 kmap(KeySym k, uint state)
3894 /* Check for mapped keys out of X11 function keys. */
3895 for (i = 0; i < LEN(mappedkeys); i++) {
3896 if (mappedkeys[i] == k)
3899 if (i == LEN(mappedkeys)) {
3900 if ((k & 0xFFFF) < 0xFD00)
3904 for (kp = key; kp < key + LEN(key); kp++) {
3908 if (!match(kp->mask, state))
3911 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
3913 if (term.numlock && kp->appkey == 2)
3916 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
3919 if (IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
3931 XKeyEvent *e = &ev->xkey;
3933 char buf[32], *customkey;
3939 if (IS_SET(MODE_KBDLOCK))
3942 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
3944 for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3945 if (ksym == bp->keysym && match(bp->mod, e->state)) {
3946 bp->func(&(bp->arg));
3951 /* 2. custom keys from config.h */
3952 if ((customkey = kmap(ksym, e->state))) {
3953 ttysend(customkey, strlen(customkey));
3957 /* 3. composed string from input method */
3960 if (len == 1 && e->state & Mod1Mask) {
3961 if (IS_SET(MODE_8BIT)) {
3964 len = utf8encode(c, buf);
3981 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3983 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3984 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3985 xw.state |= WIN_FOCUSED;
3987 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3988 xw.state &= ~WIN_FOCUSED;
3990 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
3991 /* Send SIGHUP to shell */
3998 cresize(int width, int height)
4007 col = (xw.w - 2 * borderpx) / xw.cw;
4008 row = (xw.h - 2 * borderpx) / xw.ch;
4018 if (e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
4021 cresize(e->xconfigure.width, e->xconfigure.height);
4028 int w = xw.w, h = xw.h;
4030 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
4031 struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
4034 /* Waiting for window mapping */
4036 XNextEvent(xw.dpy, &ev);
4038 * XFilterEvent is required to be called after you using XOpenIM,
4039 * this is not unnecessary.It does not only filter the key event,
4040 * but some clientmessage for input method as well.
4042 if (XFilterEvent(&ev, None))
4044 if (ev.type == ConfigureNotify) {
4045 w = ev.xconfigure.width;
4046 h = ev.xconfigure.height;
4048 } while (ev.type != MapNotify);
4053 clock_gettime(CLOCK_MONOTONIC, &last);
4056 for (xev = actionfps;;) {
4058 FD_SET(cmdfd, &rfd);
4061 if (pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
4064 die("select failed: %s\n", strerror(errno));
4066 if (FD_ISSET(cmdfd, &rfd)) {
4069 blinkset = tattrset(ATTR_BLINK);
4071 MODBIT(term.mode, 0, MODE_BLINK);
4075 if (FD_ISSET(xfd, &rfd))
4078 clock_gettime(CLOCK_MONOTONIC, &now);
4079 drawtimeout.tv_sec = 0;
4080 drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
4084 if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
4085 tsetdirtattr(ATTR_BLINK);
4086 term.mode ^= MODE_BLINK;
4090 deltatime = TIMEDIFF(now, last);
4091 if (deltatime > 1000 / (xev ? xfps : actionfps)) {
4097 while (XPending(xw.dpy)) {
4098 XNextEvent(xw.dpy, &ev);
4099 if (XFilterEvent(&ev, None))
4101 if (handler[ev.type])
4102 (handler[ev.type])(&ev);
4108 if (xev && !FD_ISSET(xfd, &rfd))
4110 if (!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
4112 if (TIMEDIFF(now, lastblink) \
4114 drawtimeout.tv_nsec = 1000;
4116 drawtimeout.tv_nsec = (1E6 * \
4121 drawtimeout.tv_sec = \
4122 drawtimeout.tv_nsec / 1E9;
4123 drawtimeout.tv_nsec %= (long)1E9;
4135 die("%s " VERSION " (c) 2010-2015 st engineers\n"
4136 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]\n"
4137 " [-i] [-t title] [-w windowid] [-e command ...] [command ...]\n"
4138 " st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]\n"
4139 " [-i] [-t title] [-w windowid] [-l line] [stty_args ...]\n",
4144 main(int argc, char *argv[])
4146 uint cols = 80, rows = 24;
4157 opt_class = EARGF(usage());
4164 opt_font = EARGF(usage());
4167 xw.gm = XParseGeometry(EARGF(usage()),
4168 &xw.l, &xw.t, &cols, &rows);
4174 opt_io = EARGF(usage());
4177 opt_line = EARGF(usage());
4180 opt_title = EARGF(usage());
4183 opt_embed = EARGF(usage());
4192 /* eat all remaining arguments */
4194 if (!opt_title && !opt_line)
4195 opt_title = basename(xstrdup(argv[0]));
4197 setlocale(LC_CTYPE, "");
4198 XSetLocaleModifiers("");
4199 tnew(MAX(cols, 1), MAX(rows, 1));