1 /* See LICENSE for license details. */
15 #include <sys/ioctl.h>
16 #include <sys/select.h>
19 #include <sys/types.h>
24 #include <X11/Xatom.h>
26 #include <X11/Xutil.h>
27 #include <X11/cursorfont.h>
28 #include <X11/keysym.h>
29 #include <X11/Xft/Xft.h>
30 #include <X11/XKBlib.h>
31 #include <fontconfig/fontconfig.h>
43 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
45 #elif defined(__FreeBSD__) || defined(__DragonFly__)
51 #define XEMBED_FOCUS_IN 4
52 #define XEMBED_FOCUS_OUT 5
55 #define UTF_INVALID 0xFFFD
57 #define ESC_BUF_SIZ (128*UTF_SIZ)
58 #define ESC_ARG_SIZ 16
59 #define STR_BUF_SIZ ESC_BUF_SIZ
60 #define STR_ARG_SIZ ESC_ARG_SIZ
61 #define XK_ANY_MOD UINT_MAX
63 #define XK_SWITCH_MOD (1<<13)
66 #define MIN(a, b) ((a) < (b) ? (a) : (b))
67 #define MAX(a, b) ((a) < (b) ? (b) : (a))
68 #define LEN(a) (sizeof(a) / sizeof(a)[0])
69 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
70 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
71 #define ISCONTROLC0(c) (BETWEEN(c, 0, 0x1f) || (c) == '\177')
72 #define ISCONTROLC1(c) (BETWEEN(c, 0x80, 0x9f))
73 #define ISCONTROL(c) (ISCONTROLC0(c) || ISCONTROLC1(c))
74 #define ISDELIM(u) (utf8strchr(worddelimiters, u) != NULL)
75 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
76 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
77 #define IS_SET(flag) ((term.mode & (flag)) != 0)
78 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_nsec-t2.tv_nsec)/1E6)
79 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
81 #define TRUECOLOR(r,g,b) (1 << 24 | (r) << 16 | (g) << 8 | (b))
82 #define IS_TRUECOL(x) (1 << 24 & (x))
83 #define TRUERED(x) (((x) & 0xff0000) >> 8)
84 #define TRUEGREEN(x) (((x) & 0xff00))
85 #define TRUEBLUE(x) (((x) & 0xff) << 8)
88 enum glyph_attribute {
93 ATTR_UNDERLINE = 1 << 3,
95 ATTR_REVERSE = 1 << 5,
96 ATTR_INVISIBLE = 1 << 6,
100 ATTR_WDUMMY = 1 << 10,
101 ATTR_BOLD_FAINT = ATTR_BOLD | ATTR_FAINT,
104 enum cursor_movement {
117 MODE_INSERT = 1 << 1,
118 MODE_APPKEYPAD = 1 << 2,
119 MODE_ALTSCREEN = 1 << 3,
121 MODE_MOUSEBTN = 1 << 5,
122 MODE_MOUSEMOTION = 1 << 6,
123 MODE_REVERSE = 1 << 7,
124 MODE_KBDLOCK = 1 << 8,
127 MODE_APPCURSOR = 1 << 11,
128 MODE_MOUSESGR = 1 << 12,
130 MODE_BLINK = 1 << 14,
131 MODE_FBLINK = 1 << 15,
132 MODE_FOCUS = 1 << 16,
133 MODE_MOUSEX10 = 1 << 17,
134 MODE_MOUSEMANY = 1 << 18,
135 MODE_BRCKTPASTE = 1 << 19,
136 MODE_PRINT = 1 << 20,
137 MODE_MOUSE = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
154 ESC_STR = 4, /* DCS, OSC, PM, APC */
156 ESC_STR_END = 16, /* a final string was encountered */
157 ESC_TEST = 32, /* Enter in test mode */
165 enum selection_mode {
171 enum selection_type {
176 enum selection_snap {
181 typedef unsigned char uchar;
182 typedef unsigned int uint;
183 typedef unsigned long ulong;
184 typedef unsigned short ushort;
186 typedef uint_least32_t Rune;
188 typedef XftDraw *Draw;
189 typedef XftColor Color;
192 Rune u; /* character code */
193 ushort mode; /* attribute flags */
194 uint32_t fg; /* foreground */
195 uint32_t bg; /* background */
201 Glyph attr; /* current char attributes */
207 /* CSI Escape sequence structs */
208 /* ESC '[' [[ [<priv>] <arg> [;]] <mode> [<mode>]] */
210 char buf[ESC_BUF_SIZ]; /* raw string */
211 int len; /* raw string length */
213 int arg[ESC_ARG_SIZ];
214 int narg; /* nb of args */
218 /* STR Escape sequence structs */
219 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
221 char type; /* ESC type ... */
222 char buf[STR_BUF_SIZ]; /* raw string */
223 int len; /* raw string length */
224 char *args[STR_ARG_SIZ];
225 int narg; /* nb of args */
228 /* Internal representation of the screen */
230 int row; /* nb row */
231 int col; /* nb col */
232 Line *line; /* screen */
233 Line *alt; /* alternate screen */
234 bool *dirty; /* dirtyness of lines */
235 XftGlyphFontSpec *specbuf; /* font spec buffer used for rendering */
236 TCursor c; /* cursor */
237 int top; /* top scroll limit */
238 int bot; /* bottom scroll limit */
239 int mode; /* terminal mode flags */
240 int esc; /* escape state flags */
241 char trantbl[4]; /* charset table translation */
242 int charset; /* current charset */
243 int icharset; /* selected charset for sequence */
244 bool numlock; /* lock numbers in keyboard */
248 /* Purely graphic info */
254 Atom xembed, wmdeletewin, netwmname, netwmpid;
259 XSetWindowAttributes attrs;
261 bool isfixed; /* is fixed geometry? */
262 int l, t; /* left and top offset */
263 int gm; /* geometry mask */
264 int tw, th; /* tty width and height */
265 int w, h; /* window width and height */
266 int ch; /* char height */
267 int cw; /* char width */
268 char state; /* focus, redraw, visible */
269 int cursor; /* cursor style */
282 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
283 signed char appkey; /* application keypad */
284 signed char appcursor; /* application cursor */
285 signed char crlf; /* crlf mode */
293 * Selection variables:
294 * nb – normalized coordinates of the beginning of the selection
295 * ne – normalized coordinates of the end of the selection
296 * ob – original coordinates of the beginning of the selection
297 * oe – original coordinates of the end of the selection
303 char *primary, *clipboard;
306 struct timespec tclick1;
307 struct timespec tclick2;
320 void (*func)(const Arg *);
324 /* function definitions used in config.h */
325 static void clipcopy(const Arg *);
326 static void clippaste(const Arg *);
327 static void numlock(const Arg *);
328 static void selpaste(const Arg *);
329 static void xzoom(const Arg *);
330 static void xzoomabs(const Arg *);
331 static void xzoomreset(const Arg *);
332 static void printsel(const Arg *);
333 static void printscreen(const Arg *) ;
334 static void toggleprinter(const Arg *);
336 /* Config.h for applying patches and the configuration. */
352 /* Drawing Context */
354 Color col[MAX(LEN(colorname), 256)];
355 Font font, bfont, ifont, ibfont;
359 static void die(const char *, ...);
360 static void draw(void);
361 static void redraw(void);
362 static void drawregion(int, int, int, int);
363 static void execsh(void);
364 static void stty(void);
365 static void sigchld(int);
366 static void run(void);
368 static void csidump(void);
369 static void csihandle(void);
370 static void csiparse(void);
371 static void csireset(void);
372 static int eschandle(uchar);
373 static void strdump(void);
374 static void strhandle(void);
375 static void strparse(void);
376 static void strreset(void);
378 static int tattrset(int);
379 static void tprinter(char *, size_t);
380 static void tdumpsel(void);
381 static void tdumpline(int);
382 static void tdump(void);
383 static void tclearregion(int, int, int, int);
384 static void tcursor(int);
385 static void tdeletechar(int);
386 static void tdeleteline(int);
387 static void tinsertblank(int);
388 static void tinsertblankline(int);
389 static int tlinelen(int);
390 static void tmoveto(int, int);
391 static void tmoveato(int, int);
392 static void tnew(int, int);
393 static void tnewline(int);
394 static void tputtab(int);
395 static void tputc(Rune);
396 static void treset(void);
397 static void tresize(int, int);
398 static void tscrollup(int, int);
399 static void tscrolldown(int, int);
400 static void tsetattr(int *, int);
401 static void tsetchar(Rune, Glyph *, int, int);
402 static void tsetscroll(int, int);
403 static void tswapscreen(void);
404 static void tsetdirt(int, int);
405 static void tsetdirtattr(int);
406 static void tsetmode(bool, bool, int *, int);
407 static void tfulldirt(void);
408 static void techo(Rune);
409 static void tcontrolcode(uchar );
410 static void tdectest(char );
411 static int32_t tdefcolor(int *, int *, int);
412 static void tdeftran(char);
413 static inline bool match(uint, uint);
414 static void ttynew(void);
415 static void ttyread(void);
416 static void ttyresize(void);
417 static void ttysend(char *, size_t);
418 static void ttywrite(const char *, size_t);
419 static void tstrsequence(uchar);
421 static inline ushort sixd_to_16bit(int);
422 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
423 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
424 static void xdrawglyph(Glyph, int, int);
425 static void xhints(void);
426 static void xclear(int, int, int, int);
427 static void xdrawcursor(void);
428 static void xinit(void);
429 static void xloadcols(void);
430 static int xsetcolorname(int, const char *);
431 static int xgeommasktogravity(int);
432 static int xloadfont(Font *, FcPattern *);
433 static void xloadfonts(char *, double);
434 static void xsettitle(char *);
435 static void xresettitle(void);
436 static void xsetpointermotion(int);
437 static void xseturgency(int);
438 static void xsetsel(char *, Time);
439 static void xtermclear(int, int, int, int);
440 static void xunloadfont(Font *);
441 static void xunloadfonts(void);
442 static void xresize(int, int);
444 static void expose(XEvent *);
445 static void visibility(XEvent *);
446 static void unmap(XEvent *);
447 static char *kmap(KeySym, uint);
448 static void kpress(XEvent *);
449 static void cmessage(XEvent *);
450 static void cresize(int, int);
451 static void resize(XEvent *);
452 static void focus(XEvent *);
453 static void brelease(XEvent *);
454 static void bpress(XEvent *);
455 static void bmotion(XEvent *);
456 static void selnotify(XEvent *);
457 static void selclear(XEvent *);
458 static void selrequest(XEvent *);
460 static void selinit(void);
461 static void selnormalize(void);
462 static inline bool selected(int, int);
463 static char *getsel(void);
464 static void selcopy(Time);
465 static void selscroll(int, int);
466 static void selsnap(int *, int *, int);
467 static int x2col(int);
468 static int y2row(int);
469 static void getbuttoninfo(XEvent *);
470 static void mousereport(XEvent *);
472 static size_t utf8decode(char *, Rune *, size_t);
473 static Rune utf8decodebyte(char, size_t *);
474 static size_t utf8encode(Rune, char *);
475 static char utf8encodebyte(Rune, size_t);
476 static char *utf8strchr(char *s, Rune u);
477 static size_t utf8validate(Rune *, size_t);
479 static ssize_t xwrite(int, const char *, size_t);
480 static void *xmalloc(size_t);
481 static void *xrealloc(void *, size_t);
482 static char *xstrdup(char *);
484 static void usage(void);
486 static void (*handler[LASTEvent])(XEvent *) = {
488 [ClientMessage] = cmessage,
489 [ConfigureNotify] = resize,
490 [VisibilityNotify] = visibility,
491 [UnmapNotify] = unmap,
495 [MotionNotify] = bmotion,
496 [ButtonPress] = bpress,
497 [ButtonRelease] = brelease,
499 * Uncomment if you want the selection to disappear when you select something
500 * different in another window.
502 /* [SelectionClear] = selclear, */
503 [SelectionNotify] = selnotify,
504 [SelectionRequest] = selrequest,
511 static CSIEscape csiescseq;
512 static STREscape strescseq;
515 static Selection sel;
517 static char **opt_cmd = NULL;
518 static char *opt_io = NULL;
519 static char *opt_title = NULL;
520 static char *opt_embed = NULL;
521 static char *opt_class = NULL;
522 static char *opt_font = NULL;
523 static char *opt_line = NULL;
524 static int oldbutton = 3; /* button event on startup: 3 = release */
526 static char *usedfont = NULL;
527 static double usedfontsize = 0;
528 static double defaultfontsize = 0;
530 static uchar utfbyte[UTF_SIZ + 1] = {0x80, 0, 0xC0, 0xE0, 0xF0};
531 static uchar utfmask[UTF_SIZ + 1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
532 static Rune utfmin[UTF_SIZ + 1] = { 0, 0, 0x80, 0x800, 0x10000};
533 static Rune utfmax[UTF_SIZ + 1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
535 /* Font Ring Cache */
549 /* Fontcache is an array now. A new font will be appended to the array. */
550 static Fontcache frc[16];
551 static int frclen = 0;
554 xwrite(int fd, const char *s, size_t len) {
558 ssize_t r = write(fd, s, len);
568 xmalloc(size_t len) {
569 void *p = malloc(len);
572 die("Out of memory\n");
578 xrealloc(void *p, size_t len) {
579 if((p = realloc(p, len)) == NULL)
580 die("Out of memory\n");
587 if((s = strdup(s)) == NULL)
588 die("Out of memory\n");
594 utf8decode(char *c, Rune *u, size_t clen) {
595 size_t i, j, len, type;
601 udecoded = utf8decodebyte(c[0], &len);
602 if(!BETWEEN(len, 1, UTF_SIZ))
604 for(i = 1, j = 1; i < clen && j < len; ++i, ++j) {
605 udecoded = (udecoded << 6) | utf8decodebyte(c[i], &type);
612 utf8validate(u, len);
617 utf8decodebyte(char c, size_t *i) {
618 for(*i = 0; *i < LEN(utfmask); ++(*i))
619 if(((uchar)c & utfmask[*i]) == utfbyte[*i])
620 return (uchar)c & ~utfmask[*i];
625 utf8encode(Rune u, char *c) {
628 len = utf8validate(&u, 0);
631 for(i = len - 1; i != 0; --i) {
632 c[i] = utf8encodebyte(u, 0);
635 c[0] = utf8encodebyte(u, len);
640 utf8encodebyte(Rune u, size_t i) {
641 return utfbyte[i] | (u & ~utfmask[i]);
645 utf8strchr(char *s, Rune u) {
650 for(i = 0, j = 0; i < len; i += j) {
651 if(!(j = utf8decode(&s[i], &r, len - i)))
660 utf8validate(Rune *u, size_t i) {
661 if(!BETWEEN(*u, utfmin[i], utfmax[i]) || BETWEEN(*u, 0xD800, 0xDFFF))
663 for(i = 1; *u > utfmax[i]; ++i)
670 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
671 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
675 sel.clipboard = NULL;
676 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
677 if(sel.xtarget == None)
678 sel.xtarget = XA_STRING;
686 return LIMIT(x, 0, term.col-1);
694 return LIMIT(y, 0, term.row-1);
701 if(term.line[y][i - 1].mode & ATTR_WRAP)
704 while(i > 0 && term.line[y][i - 1].u == ' ')
714 if(sel.type == SEL_REGULAR && sel.ob.y != sel.oe.y) {
715 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
716 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
718 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
719 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
721 sel.nb.y = MIN(sel.ob.y, sel.oe.y);
722 sel.ne.y = MAX(sel.ob.y, sel.oe.y);
724 selsnap(&sel.nb.x, &sel.nb.y, -1);
725 selsnap(&sel.ne.x, &sel.ne.y, +1);
727 /* expand selection over line breaks */
728 if (sel.type == SEL_RECTANGULAR)
730 i = tlinelen(sel.nb.y);
733 if (tlinelen(sel.ne.y) <= sel.ne.x)
734 sel.ne.x = term.col - 1;
738 selected(int x, int y) {
739 if(sel.mode == SEL_EMPTY)
742 if(sel.type == SEL_RECTANGULAR)
743 return BETWEEN(y, sel.nb.y, sel.ne.y)
744 && BETWEEN(x, sel.nb.x, sel.ne.x);
746 return BETWEEN(y, sel.nb.y, sel.ne.y)
747 && (y != sel.nb.y || x >= sel.nb.x)
748 && (y != sel.ne.y || x <= sel.ne.x);
752 selsnap(int *x, int *y, int direction) {
753 int newx, newy, xt, yt;
754 bool delim, prevdelim;
760 * Snap around if the word wraps around at the end or
761 * beginning of a line.
763 prevgp = &term.line[*y][*x];
764 prevdelim = ISDELIM(prevgp->u);
766 newx = *x + direction;
768 if(!BETWEEN(newx, 0, term.col - 1)) {
770 newx = (newx + term.col) % term.col;
771 if (!BETWEEN(newy, 0, term.row - 1))
777 yt = newy, xt = newx;
778 if(!(term.line[yt][xt].mode & ATTR_WRAP))
782 if (newx >= tlinelen(newy))
785 gp = &term.line[newy][newx];
786 delim = ISDELIM(gp->u);
787 if(!(gp->mode & ATTR_WDUMMY) && (delim != prevdelim
788 || (delim && gp->u != prevgp->u)))
799 * Snap around if the the previous line or the current one
800 * has set ATTR_WRAP at its end. Then the whole next or
801 * previous line will be selected.
803 *x = (direction < 0) ? 0 : term.col - 1;
805 for(; *y > 0; *y += direction) {
806 if(!(term.line[*y-1][term.col-1].mode
811 } else if(direction > 0) {
812 for(; *y < term.row-1; *y += direction) {
813 if(!(term.line[*y][term.col-1].mode
824 getbuttoninfo(XEvent *e) {
826 uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
828 sel.alt = IS_SET(MODE_ALTSCREEN);
830 sel.oe.x = x2col(e->xbutton.x);
831 sel.oe.y = y2row(e->xbutton.y);
834 sel.type = SEL_REGULAR;
835 for(type = 1; type < LEN(selmasks); ++type) {
836 if(match(selmasks[type], state)) {
844 mousereport(XEvent *e) {
845 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
846 button = e->xbutton.button, state = e->xbutton.state,
852 if(e->xbutton.type == MotionNotify) {
853 if(x == ox && y == oy)
855 if(!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
857 /* MOUSE_MOTION: no reporting if no button is pressed */
858 if(IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
861 button = oldbutton + 32;
865 if(!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
872 if(e->xbutton.type == ButtonPress) {
876 } else if(e->xbutton.type == ButtonRelease) {
878 /* MODE_MOUSEX10: no button release reporting */
879 if(IS_SET(MODE_MOUSEX10))
881 if (button == 64 || button == 65)
886 if(!IS_SET(MODE_MOUSEX10)) {
887 button += ((state & ShiftMask ) ? 4 : 0)
888 + ((state & Mod4Mask ) ? 8 : 0)
889 + ((state & ControlMask) ? 16 : 0);
892 if(IS_SET(MODE_MOUSESGR)) {
893 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
895 e->xbutton.type == ButtonRelease ? 'm' : 'M');
896 } else if(x < 223 && y < 223) {
897 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
898 32+button, 32+x+1, 32+y+1);
911 if(IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
916 for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
917 if(e->xbutton.button == mk->b
918 && match(mk->mask, e->xbutton.state)) {
919 ttysend(mk->s, strlen(mk->s));
924 if(e->xbutton.button == Button1) {
925 clock_gettime(CLOCK_MONOTONIC, &now);
927 /* Clear previous selection, logically and visually. */
929 sel.mode = SEL_EMPTY;
930 sel.type = SEL_REGULAR;
931 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
932 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
935 * If the user clicks below predefined timeouts specific
936 * snapping behaviour is exposed.
938 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
939 sel.snap = SNAP_LINE;
940 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
941 sel.snap = SNAP_WORD;
948 sel.mode = SEL_READY;
949 tsetdirt(sel.nb.y, sel.ne.y);
950 sel.tclick2 = sel.tclick1;
958 int y, bufsize, lastx, linelen;
964 bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
965 ptr = str = xmalloc(bufsize);
967 /* append every set & selected glyph to the selection */
968 for(y = sel.nb.y; y <= sel.ne.y; y++) {
969 linelen = tlinelen(y);
971 if(sel.type == SEL_RECTANGULAR) {
972 gp = &term.line[y][sel.nb.x];
975 gp = &term.line[y][sel.nb.y == y ? sel.nb.x : 0];
976 lastx = (sel.ne.y == y) ? sel.ne.x : term.col-1;
978 last = &term.line[y][MIN(lastx, linelen-1)];
979 while(last >= gp && last->u == ' ')
982 for( ; gp <= last; ++gp) {
983 if(gp->mode & ATTR_WDUMMY)
986 ptr += utf8encode(gp->u, ptr);
990 * Copy and pasting of line endings is inconsistent
991 * in the inconsistent terminal and GUI world.
992 * The best solution seems like to produce '\n' when
993 * something is copied from st and convert '\n' to
994 * '\r', when something to be pasted is received by
996 * FIXME: Fix the computer world.
998 if((y < sel.ne.y || lastx >= linelen) && !(last->mode & ATTR_WRAP))
1007 xsetsel(getsel(), t);
1011 selnotify(XEvent *e) {
1012 ulong nitems, ofs, rem;
1014 uchar *data, *last, *repl;
1016 XSelectionEvent *xsev;
1019 xsev = &e->xselection;
1020 if (xsev->property == None)
1023 if(XGetWindowProperty(xw.dpy, xw.win, xsev->property, ofs,
1024 BUFSIZ/4, False, AnyPropertyType,
1025 &type, &format, &nitems, &rem,
1027 fprintf(stderr, "Clipboard allocation failed\n");
1032 * As seen in getsel:
1033 * Line endings are inconsistent in the terminal and GUI world
1034 * copy and pasting. When receiving some selection data,
1035 * replace all '\n' with '\r'.
1036 * FIXME: Fix the computer world.
1039 last = data + nitems * format / 8;
1040 while((repl = memchr(repl, '\n', last - repl))) {
1044 if(IS_SET(MODE_BRCKTPASTE))
1045 ttywrite("\033[200~", 6);
1046 ttysend((char *)data, nitems * format / 8);
1047 if(IS_SET(MODE_BRCKTPASTE))
1048 ttywrite("\033[201~", 6);
1050 /* number of 32-bit chunks returned */
1051 ofs += nitems * format / 32;
1056 selpaste(const Arg *dummy) {
1057 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1058 xw.win, CurrentTime);
1062 clipcopy(const Arg *dummy) {
1065 if(sel.clipboard != NULL)
1066 free(sel.clipboard);
1068 if(sel.primary != NULL) {
1069 sel.clipboard = xstrdup(sel.primary);
1070 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1071 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1076 clippaste(const Arg *dummy) {
1079 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1080 XConvertSelection(xw.dpy, clipboard, sel.xtarget, clipboard,
1081 xw.win, CurrentTime);
1085 selclear(XEvent *e) {
1088 sel.mode = SEL_IDLE;
1090 tsetdirt(sel.nb.y, sel.ne.y);
1094 selrequest(XEvent *e) {
1095 XSelectionRequestEvent *xsre;
1096 XSelectionEvent xev;
1097 Atom xa_targets, string, clipboard;
1100 xsre = (XSelectionRequestEvent *) e;
1101 xev.type = SelectionNotify;
1102 xev.requestor = xsre->requestor;
1103 xev.selection = xsre->selection;
1104 xev.target = xsre->target;
1105 xev.time = xsre->time;
1106 if (xsre->property == None)
1107 xsre->property = xsre->target;
1110 xev.property = None;
1112 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1113 if(xsre->target == xa_targets) {
1114 /* respond with the supported type */
1115 string = sel.xtarget;
1116 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1117 XA_ATOM, 32, PropModeReplace,
1118 (uchar *) &string, 1);
1119 xev.property = xsre->property;
1120 } else if(xsre->target == sel.xtarget || xsre->target == XA_STRING) {
1122 * xith XA_STRING non ascii characters may be incorrect in the
1123 * requestor. It is not our problem, use utf8.
1125 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1126 if(xsre->selection == XA_PRIMARY) {
1127 seltext = sel.primary;
1128 } else if(xsre->selection == clipboard) {
1129 seltext = sel.clipboard;
1132 "Unhandled clipboard selection 0x%lx\n",
1136 if(seltext != NULL) {
1137 XChangeProperty(xsre->display, xsre->requestor,
1138 xsre->property, xsre->target,
1140 (uchar *)seltext, strlen(seltext));
1141 xev.property = xsre->property;
1145 /* all done, send a notification to the listener */
1146 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
1147 fprintf(stderr, "Error sending SelectionNotify event\n");
1151 xsetsel(char *str, Time t) {
1155 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
1156 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
1161 brelease(XEvent *e) {
1162 if(IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
1167 if(e->xbutton.button == Button2) {
1169 } else if(e->xbutton.button == Button1) {
1170 if(sel.mode == SEL_READY) {
1172 selcopy(e->xbutton.time);
1175 sel.mode = SEL_IDLE;
1176 tsetdirt(sel.nb.y, sel.ne.y);
1181 bmotion(XEvent *e) {
1182 int oldey, oldex, oldsby, oldsey;
1184 if(IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
1192 sel.mode = SEL_READY;
1199 if(oldey != sel.oe.y || oldex != sel.oe.x)
1200 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1204 die(const char *errstr, ...) {
1207 va_start(ap, errstr);
1208 vfprintf(stderr, errstr, ap);
1215 char **args, *sh, *prog;
1216 const struct passwd *pw;
1217 char buf[sizeof(long) * 8 + 1];
1220 if((pw = getpwuid(getuid())) == NULL) {
1222 die("getpwuid:%s\n", strerror(errno));
1224 die("who are you?\n");
1227 if (!(sh = getenv("SHELL"))) {
1228 sh = (pw->pw_shell[0]) ? pw->pw_shell : shell;
1237 args = (opt_cmd) ? opt_cmd : (char *[]) {prog, NULL};
1239 snprintf(buf, sizeof(buf), "%lu", xw.win);
1241 unsetenv("COLUMNS");
1243 unsetenv("TERMCAP");
1244 setenv("LOGNAME", pw->pw_name, 1);
1245 setenv("USER", pw->pw_name, 1);
1246 setenv("SHELL", sh, 1);
1247 setenv("HOME", pw->pw_dir, 1);
1248 setenv("TERM", termname, 1);
1249 setenv("WINDOWID", buf, 1);
1251 signal(SIGCHLD, SIG_DFL);
1252 signal(SIGHUP, SIG_DFL);
1253 signal(SIGINT, SIG_DFL);
1254 signal(SIGQUIT, SIG_DFL);
1255 signal(SIGTERM, SIG_DFL);
1256 signal(SIGALRM, SIG_DFL);
1267 if((p = waitpid(pid, &stat, WNOHANG)) < 0)
1268 die("Waiting for pid %hd failed: %s\n", pid, strerror(errno));
1273 if (!WIFEXITED(stat) || WEXITSTATUS(stat))
1274 die("child finished with error '%d'\n", stat);
1282 char cmd[_POSIX_ARG_MAX], **p, *q, *s;
1285 if((n = strlen(stty_args)) > sizeof(cmd)-1)
1286 die("incorrect stty parameters\n");
1287 memcpy(cmd, stty_args, n);
1289 siz = sizeof(cmd) - n;
1290 for(p = opt_cmd; p && (s = *p); ++p) {
1291 if((n = strlen(s)) > siz-1)
1292 die("stty parameter length too long\n");
1294 q = memcpy(q, s, n);
1299 if (system(cmd) != 0)
1300 perror("Couldn't call stty");
1306 struct winsize w = {term.row, term.col, 0, 0};
1309 term.mode |= MODE_PRINT;
1310 iofd = (!strcmp(opt_io, "-")) ?
1311 1 : open(opt_io, O_WRONLY | O_CREAT, 0666);
1313 fprintf(stderr, "Error opening %s:%s\n",
1314 opt_io, strerror(errno));
1319 if((cmdfd = open(opt_line, O_RDWR)) < 0)
1320 die("open line failed: %s\n", strerror(errno));
1327 /* seems to work fine on linux, openbsd and freebsd */
1328 if(openpty(&m, &s, NULL, NULL, &w) < 0)
1329 die("openpty failed: %s\n", strerror(errno));
1331 switch(pid = fork()) {
1333 die("fork failed\n");
1337 setsid(); /* create a new process group */
1341 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1342 die("ioctl TIOCSCTTY failed: %s\n", strerror(errno));
1350 signal(SIGCHLD, sigchld);
1357 static char buf[BUFSIZ];
1358 static int buflen = 0;
1360 int charsize; /* size of utf8 char in bytes */
1364 /* append read bytes to unprocessed bytes */
1365 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1366 die("Couldn't read from shell: %s\n", strerror(errno));
1368 /* process every complete utf8 char */
1371 while((charsize = utf8decode(ptr, &unicodep, buflen))) {
1377 /* keep any uncomplete utf8 char for the next call */
1378 memmove(buf, ptr, buflen);
1382 ttywrite(const char *s, size_t n) {
1383 if(xwrite(cmdfd, s, n) == -1)
1384 die("write error on tty: %s\n", strerror(errno));
1388 ttysend(char *s, size_t n) {
1393 if(IS_SET(MODE_ECHO))
1394 while((len = utf8decode(s, &u, n)) > 0) {
1405 w.ws_row = term.row;
1406 w.ws_col = term.col;
1407 w.ws_xpixel = xw.tw;
1408 w.ws_ypixel = xw.th;
1409 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1410 fprintf(stderr, "Couldn't set window size: %s\n", strerror(errno));
1414 tattrset(int attr) {
1417 for(i = 0; i < term.row-1; i++) {
1418 for(j = 0; j < term.col-1; j++) {
1419 if(term.line[i][j].mode & attr)
1428 tsetdirt(int top, int bot) {
1431 LIMIT(top, 0, term.row-1);
1432 LIMIT(bot, 0, term.row-1);
1434 for(i = top; i <= bot; i++)
1439 tsetdirtattr(int attr) {
1442 for(i = 0; i < term.row-1; i++) {
1443 for(j = 0; j < term.col-1; j++) {
1444 if(term.line[i][j].mode & attr) {
1454 tsetdirt(0, term.row-1);
1459 static TCursor c[2];
1460 bool alt = IS_SET(MODE_ALTSCREEN);
1462 if(mode == CURSOR_SAVE) {
1464 } else if(mode == CURSOR_LOAD) {
1466 tmoveto(c[alt].x, c[alt].y);
1474 term.c = (TCursor){{
1478 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1480 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1481 for(i = tabspaces; i < term.col; i += tabspaces)
1484 term.bot = term.row - 1;
1485 term.mode = MODE_WRAP;
1486 memset(term.trantbl, CS_USA, sizeof(term.trantbl));
1489 for(i = 0; i < 2; i++) {
1491 tcursor(CURSOR_SAVE);
1492 tclearregion(0, 0, term.col-1, term.row-1);
1498 tnew(int col, int row) {
1499 term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
1508 Line *tmp = term.line;
1510 term.line = term.alt;
1512 term.mode ^= MODE_ALTSCREEN;
1517 tscrolldown(int orig, int n) {
1521 LIMIT(n, 0, term.bot-orig+1);
1523 tsetdirt(orig, term.bot-n);
1524 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1526 for(i = term.bot; i >= orig+n; i--) {
1527 temp = term.line[i];
1528 term.line[i] = term.line[i-n];
1529 term.line[i-n] = temp;
1536 tscrollup(int orig, int n) {
1540 LIMIT(n, 0, term.bot-orig+1);
1542 tclearregion(0, orig, term.col-1, orig+n-1);
1543 tsetdirt(orig+n, term.bot);
1545 for(i = orig; i <= term.bot-n; i++) {
1546 temp = term.line[i];
1547 term.line[i] = term.line[i+n];
1548 term.line[i+n] = temp;
1551 selscroll(orig, -n);
1555 selscroll(int orig, int n) {
1559 if(BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1560 if((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1564 if(sel.type == SEL_RECTANGULAR) {
1565 if(sel.ob.y < term.top)
1566 sel.ob.y = term.top;
1567 if(sel.oe.y > term.bot)
1568 sel.oe.y = term.bot;
1570 if(sel.ob.y < term.top) {
1571 sel.ob.y = term.top;
1574 if(sel.oe.y > term.bot) {
1575 sel.oe.y = term.bot;
1576 sel.oe.x = term.col;
1584 tnewline(int first_col) {
1588 tscrollup(term.top, 1);
1592 tmoveto(first_col ? 0 : term.c.x, y);
1597 char *p = csiescseq.buf, *np;
1606 csiescseq.buf[csiescseq.len] = '\0';
1607 while(p < csiescseq.buf+csiescseq.len) {
1609 v = strtol(p, &np, 10);
1612 if(v == LONG_MAX || v == LONG_MIN)
1614 csiescseq.arg[csiescseq.narg++] = v;
1616 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1620 csiescseq.mode[0] = *p++;
1621 csiescseq.mode[1] = (p < csiescseq.buf+csiescseq.len) ? *p : '\0';
1624 /* for absolute user moves, when decom is set */
1626 tmoveato(int x, int y) {
1627 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1631 tmoveto(int x, int y) {
1634 if(term.c.state & CURSOR_ORIGIN) {
1639 maxy = term.row - 1;
1641 term.c.state &= ~CURSOR_WRAPNEXT;
1642 term.c.x = LIMIT(x, 0, term.col-1);
1643 term.c.y = LIMIT(y, miny, maxy);
1647 tsetchar(Rune u, Glyph *attr, int x, int y) {
1648 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1649 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1650 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1651 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1652 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1653 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1654 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1655 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1656 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1660 * The table is proudly stolen from rxvt.
1662 if(term.trantbl[term.charset] == CS_GRAPHIC0 &&
1663 BETWEEN(u, 0x41, 0x7e) && vt100_0[u - 0x41])
1664 utf8decode(vt100_0[u - 0x41], &u, UTF_SIZ);
1666 if(term.line[y][x].mode & ATTR_WIDE) {
1667 if(x+1 < term.col) {
1668 term.line[y][x+1].u = ' ';
1669 term.line[y][x+1].mode &= ~ATTR_WDUMMY;
1671 } else if(term.line[y][x].mode & ATTR_WDUMMY) {
1672 term.line[y][x-1].u = ' ';
1673 term.line[y][x-1].mode &= ~ATTR_WIDE;
1677 term.line[y][x] = *attr;
1678 term.line[y][x].u = u;
1682 tclearregion(int x1, int y1, int x2, int y2) {
1687 temp = x1, x1 = x2, x2 = temp;
1689 temp = y1, y1 = y2, y2 = temp;
1691 LIMIT(x1, 0, term.col-1);
1692 LIMIT(x2, 0, term.col-1);
1693 LIMIT(y1, 0, term.row-1);
1694 LIMIT(y2, 0, term.row-1);
1696 for(y = y1; y <= y2; y++) {
1698 for(x = x1; x <= x2; x++) {
1699 gp = &term.line[y][x];
1702 gp->fg = term.c.attr.fg;
1703 gp->bg = term.c.attr.bg;
1711 tdeletechar(int n) {
1715 LIMIT(n, 0, term.col - term.c.x);
1719 size = term.col - src;
1720 line = term.line[term.c.y];
1722 memmove(&line[dst], &line[src], size * sizeof(Glyph));
1723 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1727 tinsertblank(int n) {
1731 LIMIT(n, 0, term.col - term.c.x);
1735 size = term.col - dst;
1736 line = term.line[term.c.y];
1738 memmove(&line[dst], &line[src], size * sizeof(Glyph));
1739 tclearregion(src, term.c.y, dst - 1, term.c.y);
1743 tinsertblankline(int n) {
1744 if(BETWEEN(term.c.y, term.top, term.bot))
1745 tscrolldown(term.c.y, n);
1749 tdeleteline(int n) {
1750 if(BETWEEN(term.c.y, term.top, term.bot))
1751 tscrollup(term.c.y, n);
1755 tdefcolor(int *attr, int *npar, int l) {
1759 switch (attr[*npar + 1]) {
1760 case 2: /* direct color in RGB space */
1761 if (*npar + 4 >= l) {
1763 "erresc(38): Incorrect number of parameters (%d)\n",
1767 r = attr[*npar + 2];
1768 g = attr[*npar + 3];
1769 b = attr[*npar + 4];
1771 if(!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1772 fprintf(stderr, "erresc: bad rgb color (%u,%u,%u)\n",
1775 idx = TRUECOLOR(r, g, b);
1777 case 5: /* indexed color */
1778 if (*npar + 2 >= l) {
1780 "erresc(38): Incorrect number of parameters (%d)\n",
1785 if(!BETWEEN(attr[*npar], 0, 255))
1786 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
1790 case 0: /* implemented defined (only foreground) */
1791 case 1: /* transparent */
1792 case 3: /* direct color in CMY space */
1793 case 4: /* direct color in CMYK space */
1796 "erresc(38): gfx attr %d unknown\n", attr[*npar]);
1804 tsetattr(int *attr, int l) {
1808 for(i = 0; i < l; i++) {
1811 term.c.attr.mode &= ~(
1820 term.c.attr.fg = defaultfg;
1821 term.c.attr.bg = defaultbg;
1824 term.c.attr.mode |= ATTR_BOLD;
1827 term.c.attr.mode |= ATTR_FAINT;
1830 term.c.attr.mode |= ATTR_ITALIC;
1833 term.c.attr.mode |= ATTR_UNDERLINE;
1835 case 5: /* slow blink */
1837 case 6: /* rapid blink */
1838 term.c.attr.mode |= ATTR_BLINK;
1841 term.c.attr.mode |= ATTR_REVERSE;
1844 term.c.attr.mode |= ATTR_INVISIBLE;
1847 term.c.attr.mode |= ATTR_STRUCK;
1850 term.c.attr.mode &= ~(ATTR_BOLD | ATTR_FAINT);
1853 term.c.attr.mode &= ~ATTR_ITALIC;
1856 term.c.attr.mode &= ~ATTR_UNDERLINE;
1859 term.c.attr.mode &= ~ATTR_BLINK;
1862 term.c.attr.mode &= ~ATTR_REVERSE;
1865 term.c.attr.mode &= ~ATTR_INVISIBLE;
1868 term.c.attr.mode &= ~ATTR_STRUCK;
1871 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1872 term.c.attr.fg = idx;
1875 term.c.attr.fg = defaultfg;
1878 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1879 term.c.attr.bg = idx;
1882 term.c.attr.bg = defaultbg;
1885 if(BETWEEN(attr[i], 30, 37)) {
1886 term.c.attr.fg = attr[i] - 30;
1887 } else if(BETWEEN(attr[i], 40, 47)) {
1888 term.c.attr.bg = attr[i] - 40;
1889 } else if(BETWEEN(attr[i], 90, 97)) {
1890 term.c.attr.fg = attr[i] - 90 + 8;
1891 } else if(BETWEEN(attr[i], 100, 107)) {
1892 term.c.attr.bg = attr[i] - 100 + 8;
1895 "erresc(default): gfx attr %d unknown\n",
1896 attr[i]), csidump();
1904 tsetscroll(int t, int b) {
1907 LIMIT(t, 0, term.row-1);
1908 LIMIT(b, 0, term.row-1);
1919 tsetmode(bool priv, bool set, int *args, int narg) {
1923 for(lim = args + narg; args < lim; ++args) {
1926 case 1: /* DECCKM -- Cursor key */
1927 MODBIT(term.mode, set, MODE_APPCURSOR);
1929 case 5: /* DECSCNM -- Reverse video */
1931 MODBIT(term.mode, set, MODE_REVERSE);
1932 if(mode != term.mode)
1935 case 6: /* DECOM -- Origin */
1936 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1939 case 7: /* DECAWM -- Auto wrap */
1940 MODBIT(term.mode, set, MODE_WRAP);
1942 case 0: /* Error (IGNORED) */
1943 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1944 case 3: /* DECCOLM -- Column (IGNORED) */
1945 case 4: /* DECSCLM -- Scroll (IGNORED) */
1946 case 8: /* DECARM -- Auto repeat (IGNORED) */
1947 case 18: /* DECPFF -- Printer feed (IGNORED) */
1948 case 19: /* DECPEX -- Printer extent (IGNORED) */
1949 case 42: /* DECNRCM -- National characters (IGNORED) */
1950 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1952 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1953 MODBIT(term.mode, !set, MODE_HIDE);
1955 case 9: /* X10 mouse compatibility mode */
1956 xsetpointermotion(0);
1957 MODBIT(term.mode, 0, MODE_MOUSE);
1958 MODBIT(term.mode, set, MODE_MOUSEX10);
1960 case 1000: /* 1000: report button press */
1961 xsetpointermotion(0);
1962 MODBIT(term.mode, 0, MODE_MOUSE);
1963 MODBIT(term.mode, set, MODE_MOUSEBTN);
1965 case 1002: /* 1002: report motion on button press */
1966 xsetpointermotion(0);
1967 MODBIT(term.mode, 0, MODE_MOUSE);
1968 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1970 case 1003: /* 1003: enable all mouse motions */
1971 xsetpointermotion(set);
1972 MODBIT(term.mode, 0, MODE_MOUSE);
1973 MODBIT(term.mode, set, MODE_MOUSEMANY);
1975 case 1004: /* 1004: send focus events to tty */
1976 MODBIT(term.mode, set, MODE_FOCUS);
1978 case 1006: /* 1006: extended reporting mode */
1979 MODBIT(term.mode, set, MODE_MOUSESGR);
1982 MODBIT(term.mode, set, MODE_8BIT);
1984 case 1049: /* swap screen & set/restore cursor as xterm */
1985 if (!allowaltscreen)
1987 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1989 case 47: /* swap screen */
1991 if (!allowaltscreen)
1993 alt = IS_SET(MODE_ALTSCREEN);
1995 tclearregion(0, 0, term.col-1,
1998 if(set ^ alt) /* set is always 1 or 0 */
2004 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
2006 case 2004: /* 2004: bracketed paste mode */
2007 MODBIT(term.mode, set, MODE_BRCKTPASTE);
2009 /* Not implemented mouse modes. See comments there. */
2010 case 1001: /* mouse highlight mode; can hang the
2011 terminal by design when implemented. */
2012 case 1005: /* UTF-8 mouse mode; will confuse
2013 applications not supporting UTF-8
2015 case 1015: /* urxvt mangled mouse mode; incompatible
2016 and can be mistaken for other control
2020 "erresc: unknown private set/reset mode %d\n",
2026 case 0: /* Error (IGNORED) */
2028 case 2: /* KAM -- keyboard action */
2029 MODBIT(term.mode, set, MODE_KBDLOCK);
2031 case 4: /* IRM -- Insertion-replacement */
2032 MODBIT(term.mode, set, MODE_INSERT);
2034 case 12: /* SRM -- Send/Receive */
2035 MODBIT(term.mode, !set, MODE_ECHO);
2037 case 20: /* LNM -- Linefeed/new line */
2038 MODBIT(term.mode, set, MODE_CRLF);
2042 "erresc: unknown set/reset mode %d\n",
2055 switch(csiescseq.mode[0]) {
2058 fprintf(stderr, "erresc: unknown csi ");
2062 case '@': /* ICH -- Insert <n> blank char */
2063 DEFAULT(csiescseq.arg[0], 1);
2064 tinsertblank(csiescseq.arg[0]);
2066 case 'A': /* CUU -- Cursor <n> Up */
2067 DEFAULT(csiescseq.arg[0], 1);
2068 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
2070 case 'B': /* CUD -- Cursor <n> Down */
2071 case 'e': /* VPR --Cursor <n> Down */
2072 DEFAULT(csiescseq.arg[0], 1);
2073 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
2075 case 'i': /* MC -- Media Copy */
2076 switch(csiescseq.arg[0]) {
2081 tdumpline(term.c.y);
2087 term.mode &= ~MODE_PRINT;
2090 term.mode |= MODE_PRINT;
2094 case 'c': /* DA -- Device Attributes */
2095 if(csiescseq.arg[0] == 0)
2096 ttywrite(vtiden, sizeof(vtiden) - 1);
2098 case 'C': /* CUF -- Cursor <n> Forward */
2099 case 'a': /* HPR -- Cursor <n> Forward */
2100 DEFAULT(csiescseq.arg[0], 1);
2101 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
2103 case 'D': /* CUB -- Cursor <n> Backward */
2104 DEFAULT(csiescseq.arg[0], 1);
2105 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
2107 case 'E': /* CNL -- Cursor <n> Down and first col */
2108 DEFAULT(csiescseq.arg[0], 1);
2109 tmoveto(0, term.c.y+csiescseq.arg[0]);
2111 case 'F': /* CPL -- Cursor <n> Up and first col */
2112 DEFAULT(csiescseq.arg[0], 1);
2113 tmoveto(0, term.c.y-csiescseq.arg[0]);
2115 case 'g': /* TBC -- Tabulation clear */
2116 switch(csiescseq.arg[0]) {
2117 case 0: /* clear current tab stop */
2118 term.tabs[term.c.x] = 0;
2120 case 3: /* clear all the tabs */
2121 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
2127 case 'G': /* CHA -- Move to <col> */
2129 DEFAULT(csiescseq.arg[0], 1);
2130 tmoveto(csiescseq.arg[0]-1, term.c.y);
2132 case 'H': /* CUP -- Move to <row> <col> */
2134 DEFAULT(csiescseq.arg[0], 1);
2135 DEFAULT(csiescseq.arg[1], 1);
2136 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
2138 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
2139 DEFAULT(csiescseq.arg[0], 1);
2140 tputtab(csiescseq.arg[0]);
2142 case 'J': /* ED -- Clear screen */
2144 switch(csiescseq.arg[0]) {
2146 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
2147 if(term.c.y < term.row-1) {
2148 tclearregion(0, term.c.y+1, term.col-1,
2154 tclearregion(0, 0, term.col-1, term.c.y-1);
2155 tclearregion(0, term.c.y, term.c.x, term.c.y);
2158 tclearregion(0, 0, term.col-1, term.row-1);
2164 case 'K': /* EL -- Clear line */
2165 switch(csiescseq.arg[0]) {
2167 tclearregion(term.c.x, term.c.y, term.col-1,
2171 tclearregion(0, term.c.y, term.c.x, term.c.y);
2174 tclearregion(0, term.c.y, term.col-1, term.c.y);
2178 case 'S': /* SU -- Scroll <n> line up */
2179 DEFAULT(csiescseq.arg[0], 1);
2180 tscrollup(term.top, csiescseq.arg[0]);
2182 case 'T': /* SD -- Scroll <n> line down */
2183 DEFAULT(csiescseq.arg[0], 1);
2184 tscrolldown(term.top, csiescseq.arg[0]);
2186 case 'L': /* IL -- Insert <n> blank lines */
2187 DEFAULT(csiescseq.arg[0], 1);
2188 tinsertblankline(csiescseq.arg[0]);
2190 case 'l': /* RM -- Reset Mode */
2191 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2193 case 'M': /* DL -- Delete <n> lines */
2194 DEFAULT(csiescseq.arg[0], 1);
2195 tdeleteline(csiescseq.arg[0]);
2197 case 'X': /* ECH -- Erase <n> char */
2198 DEFAULT(csiescseq.arg[0], 1);
2199 tclearregion(term.c.x, term.c.y,
2200 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2202 case 'P': /* DCH -- Delete <n> char */
2203 DEFAULT(csiescseq.arg[0], 1);
2204 tdeletechar(csiescseq.arg[0]);
2206 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2207 DEFAULT(csiescseq.arg[0], 1);
2208 tputtab(-csiescseq.arg[0]);
2210 case 'd': /* VPA -- Move to <row> */
2211 DEFAULT(csiescseq.arg[0], 1);
2212 tmoveato(term.c.x, csiescseq.arg[0]-1);
2214 case 'h': /* SM -- Set terminal mode */
2215 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2217 case 'm': /* SGR -- Terminal attribute (color) */
2218 tsetattr(csiescseq.arg, csiescseq.narg);
2220 case 'n': /* DSR – Device Status Report (cursor position) */
2221 if (csiescseq.arg[0] == 6) {
2222 len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
2223 term.c.y+1, term.c.x+1);
2227 case 'r': /* DECSTBM -- Set Scrolling Region */
2228 if(csiescseq.priv) {
2231 DEFAULT(csiescseq.arg[0], 1);
2232 DEFAULT(csiescseq.arg[1], term.row);
2233 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2237 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2238 tcursor(CURSOR_SAVE);
2240 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2241 tcursor(CURSOR_LOAD);
2244 switch (csiescseq.mode[1]) {
2245 case 'q': /* DECSCUSR -- Set Cursor Style */
2246 DEFAULT(csiescseq.arg[0], 1);
2247 if (!BETWEEN(csiescseq.arg[0], 0, 6)) {
2250 xw.cursor = csiescseq.arg[0];
2265 for(i = 0; i < csiescseq.len; i++) {
2266 c = csiescseq.buf[i] & 0xff;
2269 } else if(c == '\n') {
2271 } else if(c == '\r') {
2273 } else if(c == 0x1b) {
2276 printf("(%02x)", c);
2284 memset(&csiescseq, 0, sizeof(csiescseq));
2292 term.esc &= ~(ESC_STR_END|ESC_STR);
2294 par = (narg = strescseq.narg) ? atoi(strescseq.args[0]) : 0;
2296 switch(strescseq.type) {
2297 case ']': /* OSC -- Operating System Command */
2303 xsettitle(strescseq.args[1]);
2305 case 4: /* color set */
2308 p = strescseq.args[2];
2310 case 104: /* color reset, here p = NULL */
2311 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2312 if(xsetcolorname(j, p)) {
2313 fprintf(stderr, "erresc: invalid color %s\n", p);
2316 * TODO if defaultbg color is changed, borders
2324 case 'k': /* old title set compatibility */
2325 xsettitle(strescseq.args[0]);
2327 case 'P': /* DCS -- Device Control String */
2328 case '_': /* APC -- Application Program Command */
2329 case '^': /* PM -- Privacy Message */
2333 fprintf(stderr, "erresc: unknown str ");
2340 char *p = strescseq.buf;
2343 strescseq.buf[strescseq.len] = '\0';
2348 while(strescseq.narg < STR_ARG_SIZ) {
2349 strescseq.args[strescseq.narg++] = p;
2350 while((c = *p) != ';' && c != '\0')
2363 printf("ESC%c", strescseq.type);
2364 for(i = 0; i < strescseq.len; i++) {
2365 c = strescseq.buf[i] & 0xff;
2368 } else if(isprint(c)) {
2370 } else if(c == '\n') {
2372 } else if(c == '\r') {
2374 } else if(c == 0x1b) {
2377 printf("(%02x)", c);
2385 memset(&strescseq, 0, sizeof(strescseq));
2389 tprinter(char *s, size_t len) {
2390 if(iofd != -1 && xwrite(iofd, s, len) < 0) {
2391 fprintf(stderr, "Error writing in %s:%s\n",
2392 opt_io, strerror(errno));
2399 toggleprinter(const Arg *arg) {
2400 term.mode ^= MODE_PRINT;
2404 printscreen(const Arg *arg) {
2409 printsel(const Arg *arg) {
2417 if((ptr = getsel())) {
2418 tprinter(ptr, strlen(ptr));
2428 bp = &term.line[n][0];
2429 end = &bp[MIN(tlinelen(n), term.col) - 1];
2430 if(bp != end || bp->u != ' ') {
2431 for( ;bp <= end; ++bp)
2432 tprinter(buf, utf8encode(bp->u, buf));
2441 for(i = 0; i < term.row; ++i)
2450 while(x < term.col && n--)
2451 for(++x; x < term.col && !term.tabs[x]; ++x)
2455 for(--x; x > 0 && !term.tabs[x]; --x)
2458 term.c.x = LIMIT(x, 0, term.col-1);
2463 if(ISCONTROL(u)) { /* control code */
2468 } else if(u != '\n' && u != '\r' && u != '\t') {
2477 tdeftran(char ascii) {
2478 static char cs[] = "0B";
2479 static int vcs[] = {CS_GRAPHIC0, CS_USA};
2482 if((p = strchr(cs, ascii)) == NULL) {
2483 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2485 term.trantbl[term.icharset] = vcs[p - cs];
2493 if(c == '8') { /* DEC screen alignment test. */
2494 for(x = 0; x < term.col; ++x) {
2495 for(y = 0; y < term.row; ++y)
2496 tsetchar('E', &term.c.attr, x, y);
2502 tstrsequence(uchar c) {
2504 case 0x90: /* DCS -- Device Control String */
2507 case 0x9f: /* APC -- Application Program Command */
2510 case 0x9e: /* PM -- Privacy Message */
2513 case 0x9d: /* OSC -- Operating System Command */
2519 term.esc |= ESC_STR;
2523 tcontrolcode(uchar ascii) {
2529 tmoveto(term.c.x-1, term.c.y);
2532 tmoveto(0, term.c.y);
2537 /* go to first col if the mode is set */
2538 tnewline(IS_SET(MODE_CRLF));
2540 case '\a': /* BEL */
2541 if(term.esc & ESC_STR_END) {
2542 /* backwards compatibility to xterm */
2545 if(!(xw.state & WIN_FOCUSED))
2548 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
2551 case '\033': /* ESC */
2553 term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
2554 term.esc |= ESC_START;
2556 case '\016': /* SO (LS1 -- Locking shift 1) */
2557 case '\017': /* SI (LS0 -- Locking shift 0) */
2558 term.charset = 1 - (ascii - '\016');
2560 case '\032': /* SUB */
2561 tsetchar('?', &term.c.attr, term.c.x, term.c.y);
2562 case '\030': /* CAN */
2565 case '\005': /* ENQ (IGNORED) */
2566 case '\000': /* NUL (IGNORED) */
2567 case '\021': /* XON (IGNORED) */
2568 case '\023': /* XOFF (IGNORED) */
2569 case 0177: /* DEL (IGNORED) */
2571 case 0x84: /* TODO: IND */
2573 case 0x85: /* NEL -- Next line */
2574 tnewline(1); /* always go to first col */
2576 case 0x88: /* HTS -- Horizontal tab stop */
2577 term.tabs[term.c.x] = 1;
2579 case 0x8d: /* TODO: RI */
2580 case 0x8e: /* TODO: SS2 */
2581 case 0x8f: /* TODO: SS3 */
2582 case 0x98: /* TODO: SOS */
2584 case 0x9a: /* DECID -- Identify Terminal */
2585 ttywrite(vtiden, sizeof(vtiden) - 1);
2587 case 0x9b: /* TODO: CSI */
2588 case 0x9c: /* TODO: ST */
2590 case 0x90: /* DCS -- Device Control String */
2591 case 0x9f: /* APC -- Application Program Command */
2592 case 0x9e: /* PM -- Privacy Message */
2593 case 0x9d: /* OSC -- Operating System Command */
2594 tstrsequence(ascii);
2597 /* only CAN, SUB, \a and C1 chars interrupt a sequence */
2598 term.esc &= ~(ESC_STR_END|ESC_STR);
2602 * returns 1 when the sequence is finished and it hasn't to read
2603 * more characters for this sequence, otherwise 0
2606 eschandle(uchar ascii) {
2609 term.esc |= ESC_CSI;
2612 term.esc |= ESC_TEST;
2614 case 'P': /* DCS -- Device Control String */
2615 case '_': /* APC -- Application Program Command */
2616 case '^': /* PM -- Privacy Message */
2617 case ']': /* OSC -- Operating System Command */
2618 case 'k': /* old title set compatibility */
2619 tstrsequence(ascii);
2621 case 'n': /* LS2 -- Locking shift 2 */
2622 case 'o': /* LS3 -- Locking shift 3 */
2623 term.charset = 2 + (ascii - 'n');
2625 case '(': /* GZD4 -- set primary charset G0 */
2626 case ')': /* G1D4 -- set secondary charset G1 */
2627 case '*': /* G2D4 -- set tertiary charset G2 */
2628 case '+': /* G3D4 -- set quaternary charset G3 */
2629 term.icharset = ascii - '(';
2630 term.esc |= ESC_ALTCHARSET;
2632 case 'D': /* IND -- Linefeed */
2633 if(term.c.y == term.bot) {
2634 tscrollup(term.top, 1);
2636 tmoveto(term.c.x, term.c.y+1);
2639 case 'E': /* NEL -- Next line */
2640 tnewline(1); /* always go to first col */
2642 case 'H': /* HTS -- Horizontal tab stop */
2643 term.tabs[term.c.x] = 1;
2645 case 'M': /* RI -- Reverse index */
2646 if(term.c.y == term.top) {
2647 tscrolldown(term.top, 1);
2649 tmoveto(term.c.x, term.c.y-1);
2652 case 'Z': /* DECID -- Identify Terminal */
2653 ttywrite(vtiden, sizeof(vtiden) - 1);
2655 case 'c': /* RIS -- Reset to inital state */
2660 case '=': /* DECPAM -- Application keypad */
2661 term.mode |= MODE_APPKEYPAD;
2663 case '>': /* DECPNM -- Normal keypad */
2664 term.mode &= ~MODE_APPKEYPAD;
2666 case '7': /* DECSC -- Save Cursor */
2667 tcursor(CURSOR_SAVE);
2669 case '8': /* DECRC -- Restore Cursor */
2670 tcursor(CURSOR_LOAD);
2672 case '\\': /* ST -- String Terminator */
2673 if(term.esc & ESC_STR_END)
2677 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2678 (uchar) ascii, isprint(ascii)? ascii:'.');
2691 len = utf8encode(u, c);
2692 if((width = wcwidth(u)) == -1) {
2693 memcpy(c, "\357\277\275", 4); /* UTF_INVALID */
2697 if(IS_SET(MODE_PRINT))
2699 control = ISCONTROL(u);
2702 * STR sequence must be checked before anything else
2703 * because it uses all following characters until it
2704 * receives a ESC, a SUB, a ST or any other C1 control
2707 if(term.esc & ESC_STR) {
2708 if(u == '\a' || u == 030 || u == 032 || u == 033 ||
2710 term.esc &= ~(ESC_START|ESC_STR);
2711 term.esc |= ESC_STR_END;
2712 } else if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2713 memmove(&strescseq.buf[strescseq.len], c, len);
2714 strescseq.len += len;
2718 * Here is a bug in terminals. If the user never sends
2719 * some code to stop the str or esc command, then st
2720 * will stop responding. But this is better than
2721 * silently failing with unknown characters. At least
2722 * then users will report back.
2724 * In the case users ever get fixed, here is the code:
2735 * Actions of control codes must be performed as soon they arrive
2736 * because they can be embedded inside a control sequence, and
2737 * they must not cause conflicts with sequences.
2742 * control codes are not shown ever
2745 } else if(term.esc & ESC_START) {
2746 if(term.esc & ESC_CSI) {
2747 csiescseq.buf[csiescseq.len++] = u;
2748 if(BETWEEN(u, 0x40, 0x7E)
2749 || csiescseq.len >= \
2750 sizeof(csiescseq.buf)-1) {
2756 } else if(term.esc & ESC_ALTCHARSET) {
2758 } else if(term.esc & ESC_TEST) {
2763 /* sequence already finished */
2767 * All characters which form part of a sequence are not
2772 if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2775 gp = &term.line[term.c.y][term.c.x];
2776 if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2777 gp->mode |= ATTR_WRAP;
2779 gp = &term.line[term.c.y][term.c.x];
2782 if(IS_SET(MODE_INSERT) && term.c.x+width < term.col)
2783 memmove(gp+width, gp, (term.col - term.c.x - width) * sizeof(Glyph));
2785 if(term.c.x+width > term.col) {
2787 gp = &term.line[term.c.y][term.c.x];
2790 tsetchar(u, &term.c.attr, term.c.x, term.c.y);
2793 gp->mode |= ATTR_WIDE;
2794 if(term.c.x+1 < term.col) {
2796 gp[1].mode = ATTR_WDUMMY;
2799 if(term.c.x+width < term.col) {
2800 tmoveto(term.c.x+width, term.c.y);
2802 term.c.state |= CURSOR_WRAPNEXT;
2807 tresize(int col, int row) {
2809 int minrow = MIN(row, term.row);
2810 int mincol = MIN(col, term.col);
2814 if(col < 1 || row < 1) {
2816 "tresize: error resizing to %dx%d\n", col, row);
2821 * slide screen to keep cursor where we expect it -
2822 * tscrollup would work here, but we can optimize to
2823 * memmove because we're freeing the earlier lines
2825 for(i = 0; i <= term.c.y - row; i++) {
2829 /* ensure that both src and dst are not NULL */
2831 memmove(term.line, term.line + i, row * sizeof(Line));
2832 memmove(term.alt, term.alt + i, row * sizeof(Line));
2834 for(i += row; i < term.row; i++) {
2839 /* resize to new width */
2840 term.specbuf = xrealloc(term.specbuf, col * sizeof(XftGlyphFontSpec));
2842 /* resize to new height */
2843 term.line = xrealloc(term.line, row * sizeof(Line));
2844 term.alt = xrealloc(term.alt, row * sizeof(Line));
2845 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2846 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2848 /* resize each row to new width, zero-pad if needed */
2849 for(i = 0; i < minrow; i++) {
2850 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2851 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2854 /* allocate any new rows */
2855 for(/* i == minrow */; i < row; i++) {
2856 term.line[i] = xmalloc(col * sizeof(Glyph));
2857 term.alt[i] = xmalloc(col * sizeof(Glyph));
2859 if(col > term.col) {
2860 bp = term.tabs + term.col;
2862 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2863 while(--bp > term.tabs && !*bp)
2865 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2868 /* update terminal size */
2871 /* reset scrolling region */
2872 tsetscroll(0, row-1);
2873 /* make use of the LIMIT in tmoveto */
2874 tmoveto(term.c.x, term.c.y);
2875 /* Clearing both screens (it makes dirty all lines) */
2877 for(i = 0; i < 2; i++) {
2878 if(mincol < col && 0 < minrow) {
2879 tclearregion(mincol, 0, col - 1, minrow - 1);
2881 if(0 < col && minrow < row) {
2882 tclearregion(0, minrow, col - 1, row - 1);
2885 tcursor(CURSOR_LOAD);
2891 xresize(int col, int row) {
2892 xw.tw = MAX(1, col * xw.cw);
2893 xw.th = MAX(1, row * xw.ch);
2895 XFreePixmap(xw.dpy, xw.buf);
2896 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2897 DefaultDepth(xw.dpy, xw.scr));
2898 XftDrawChange(xw.draw, xw.buf);
2899 xclear(0, 0, xw.w, xw.h);
2903 sixd_to_16bit(int x) {
2904 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2908 xloadcolor(int i, const char *name, Color *ncolor) {
2909 XRenderColor color = { .alpha = 0xffff };
2912 if(BETWEEN(i, 16, 255)) { /* 256 color */
2913 if(i < 6*6*6+16) { /* same colors as xterm */
2914 color.red = sixd_to_16bit( ((i-16)/36)%6 );
2915 color.green = sixd_to_16bit( ((i-16)/6) %6 );
2916 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
2917 } else { /* greyscale */
2918 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
2919 color.green = color.blue = color.red;
2921 return XftColorAllocValue(xw.dpy, xw.vis,
2922 xw.cmap, &color, ncolor);
2924 name = colorname[i];
2926 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
2936 for (cp = dc.col; cp < &dc.col[LEN(dc.col)]; ++cp)
2937 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
2940 for(i = 0; i < LEN(dc.col); i++)
2941 if(!xloadcolor(i, NULL, &dc.col[i])) {
2943 die("Could not allocate color '%s'\n", colorname[i]);
2945 die("Could not allocate color %d\n", i);
2951 xsetcolorname(int x, const char *name) {
2954 if(!BETWEEN(x, 0, LEN(dc.col)))
2958 if(!xloadcolor(x, name, &ncolor))
2961 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
2967 xtermclear(int col1, int row1, int col2, int row2) {
2968 XftDrawRect(xw.draw,
2969 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2970 borderpx + col1 * xw.cw,
2971 borderpx + row1 * xw.ch,
2972 (col2-col1+1) * xw.cw,
2973 (row2-row1+1) * xw.ch);
2977 * Absolute coordinates.
2980 xclear(int x1, int y1, int x2, int y2) {
2981 XftDrawRect(xw.draw,
2982 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2983 x1, y1, x2-x1, y2-y1);
2988 XClassHint class = {opt_class ? opt_class : termname, termname};
2989 XWMHints wm = {.flags = InputHint, .input = 1};
2990 XSizeHints *sizeh = NULL;
2992 sizeh = XAllocSizeHints();
2994 sizeh->flags = PSize | PResizeInc | PBaseSize;
2995 sizeh->height = xw.h;
2996 sizeh->width = xw.w;
2997 sizeh->height_inc = xw.ch;
2998 sizeh->width_inc = xw.cw;
2999 sizeh->base_height = 2 * borderpx;
3000 sizeh->base_width = 2 * borderpx;
3001 if(xw.isfixed == True) {
3002 sizeh->flags |= PMaxSize | PMinSize;
3003 sizeh->min_width = sizeh->max_width = xw.w;
3004 sizeh->min_height = sizeh->max_height = xw.h;
3006 if(xw.gm & (XValue|YValue)) {
3007 sizeh->flags |= USPosition | PWinGravity;
3010 sizeh->win_gravity = xgeommasktogravity(xw.gm);
3013 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
3019 xgeommasktogravity(int mask) {
3020 switch(mask & (XNegative|YNegative)) {
3022 return NorthWestGravity;
3024 return NorthEastGravity;
3026 return SouthWestGravity;
3028 return SouthEastGravity;
3032 xloadfont(Font *f, FcPattern *pattern) {
3036 match = FcFontMatch(NULL, pattern, &result);
3040 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
3041 FcPatternDestroy(match);
3046 f->pattern = FcPatternDuplicate(pattern);
3048 f->ascent = f->match->ascent;
3049 f->descent = f->match->descent;
3051 f->rbearing = f->match->max_advance_width;
3053 f->height = f->ascent + f->descent;
3054 f->width = f->lbearing + f->rbearing;
3060 xloadfonts(char *fontstr, double fontsize) {
3065 if(fontstr[0] == '-') {
3066 pattern = XftXlfdParse(fontstr, False, False);
3068 pattern = FcNameParse((FcChar8 *)fontstr);
3072 die("st: can't open font %s\n", fontstr);
3075 FcPatternDel(pattern, FC_PIXEL_SIZE);
3076 FcPatternDel(pattern, FC_SIZE);
3077 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
3078 usedfontsize = fontsize;
3080 if(FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
3082 usedfontsize = fontval;
3083 } else if(FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
3088 * Default font size is 12, if none given. This is to
3089 * have a known usedfontsize value.
3091 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
3094 defaultfontsize = usedfontsize;
3097 FcConfigSubstitute(0, pattern, FcMatchPattern);
3098 FcDefaultSubstitute(pattern);
3100 if(xloadfont(&dc.font, pattern))
3101 die("st: can't open font %s\n", fontstr);
3103 if(usedfontsize < 0) {
3104 FcPatternGetDouble(dc.font.match->pattern,
3105 FC_PIXEL_SIZE, 0, &fontval);
3106 usedfontsize = fontval;
3108 defaultfontsize = fontval;
3111 /* Setting character width and height. */
3112 xw.cw = ceilf(dc.font.width * cwscale);
3113 xw.ch = ceilf(dc.font.height * chscale);
3115 FcPatternDel(pattern, FC_SLANT);
3116 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
3117 if(xloadfont(&dc.ifont, pattern))
3118 die("st: can't open font %s\n", fontstr);
3120 FcPatternDel(pattern, FC_WEIGHT);
3121 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
3122 if(xloadfont(&dc.ibfont, pattern))
3123 die("st: can't open font %s\n", fontstr);
3125 FcPatternDel(pattern, FC_SLANT);
3126 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
3127 if(xloadfont(&dc.bfont, pattern))
3128 die("st: can't open font %s\n", fontstr);
3130 FcPatternDestroy(pattern);
3134 xunloadfont(Font *f) {
3135 XftFontClose(xw.dpy, f->match);
3136 FcPatternDestroy(f->pattern);
3138 FcFontSetDestroy(f->set);
3142 xunloadfonts(void) {
3143 /* Free the loaded fonts in the font cache. */
3145 XftFontClose(xw.dpy, frc[--frclen].font);
3147 xunloadfont(&dc.font);
3148 xunloadfont(&dc.bfont);
3149 xunloadfont(&dc.ifont);
3150 xunloadfont(&dc.ibfont);
3154 xzoom(const Arg *arg) {
3157 larg.f = usedfontsize + arg->f;
3162 xzoomabs(const Arg *arg) {
3164 xloadfonts(usedfont, arg->f);
3171 xzoomreset(const Arg *arg) {
3174 if(defaultfontsize > 0) {
3175 larg.f = defaultfontsize;
3185 pid_t thispid = getpid();
3187 if(!(xw.dpy = XOpenDisplay(NULL)))
3188 die("Can't open display\n");
3189 xw.scr = XDefaultScreen(xw.dpy);
3190 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
3194 die("Could not init fontconfig.\n");
3196 usedfont = (opt_font == NULL)? font : opt_font;
3197 xloadfonts(usedfont, 0);
3200 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
3203 /* adjust fixed window geometry */
3204 xw.w = 2 * borderpx + term.col * xw.cw;
3205 xw.h = 2 * borderpx + term.row * xw.ch;
3206 if(xw.gm & XNegative)
3207 xw.l += DisplayWidth(xw.dpy, xw.scr) - xw.w - 2;
3208 if(xw.gm & YNegative)
3209 xw.t += DisplayWidth(xw.dpy, xw.scr) - xw.h - 2;
3212 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
3213 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
3214 xw.attrs.bit_gravity = NorthWestGravity;
3215 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
3216 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
3217 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
3218 xw.attrs.colormap = xw.cmap;
3220 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
3221 parent = XRootWindow(xw.dpy, xw.scr);
3222 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
3223 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
3224 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
3225 | CWEventMask | CWColormap, &xw.attrs);
3227 memset(&gcvalues, 0, sizeof(gcvalues));
3228 gcvalues.graphics_exposures = False;
3229 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
3231 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3232 DefaultDepth(xw.dpy, xw.scr));
3233 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
3234 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
3236 /* Xft rendering context */
3237 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
3240 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3241 XSetLocaleModifiers("@im=local");
3242 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3243 XSetLocaleModifiers("@im=");
3244 if((xw.xim = XOpenIM(xw.dpy,
3245 NULL, NULL, NULL)) == NULL) {
3246 die("XOpenIM failed. Could not open input"
3251 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
3252 | XIMStatusNothing, XNClientWindow, xw.win,
3253 XNFocusWindow, xw.win, NULL);
3255 die("XCreateIC failed. Could not obtain input method.\n");
3257 /* white cursor, black outline */
3258 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
3259 XDefineCursor(xw.dpy, xw.win, cursor);
3260 XRecolorCursor(xw.dpy, cursor,
3261 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
3262 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
3264 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
3265 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
3266 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
3267 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
3269 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
3270 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
3271 PropModeReplace, (uchar *)&thispid, 1);
3274 XMapWindow(xw.dpy, xw.win);
3276 XSync(xw.dpy, False);
3280 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
3282 float winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch, xp, yp;
3283 ushort mode, prevmode = USHRT_MAX;
3284 Font *font = &dc.font;
3285 int frcflags = FRC_NORMAL;
3286 float runewidth = xw.cw;
3290 FcPattern *fcpattern, *fontpattern;
3291 FcFontSet *fcsets[] = { NULL };
3292 FcCharSet *fccharset;
3293 int i, f, numspecs = 0;
3295 for(i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
3296 /* Fetch rune and mode for current glyph. */
3298 mode = glyphs[i].mode;
3300 /* Skip dummy wide-character spacing. */
3301 if(mode == ATTR_WDUMMY)
3304 /* Determine font for glyph if different from previous glyph. */
3305 if(prevmode != mode) {
3308 frcflags = FRC_NORMAL;
3309 runewidth = xw.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
3310 if((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
3312 frcflags = FRC_ITALICBOLD;
3313 } else if(mode & ATTR_ITALIC) {
3315 frcflags = FRC_ITALIC;
3316 } else if(mode & ATTR_BOLD) {
3318 frcflags = FRC_BOLD;
3320 yp = winy + font->ascent;
3323 /* Lookup character index with default font. */
3324 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
3326 specs[numspecs].font = font->match;
3327 specs[numspecs].glyph = glyphidx;
3328 specs[numspecs].x = (short)xp;
3329 specs[numspecs].y = (short)yp;
3335 /* Fallback on font cache, search the font cache for match. */
3336 for(f = 0; f < frclen; f++) {
3337 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
3338 /* Everything correct. */
3339 if(glyphidx && frc[f].flags == frcflags)
3341 /* We got a default font for a not found glyph. */
3342 if(!glyphidx && frc[f].flags == frcflags
3343 && frc[f].unicodep == rune) {
3348 /* Nothing was found. Use fontconfig to find matching font. */
3351 font->set = FcFontSort(0, font->pattern,
3353 fcsets[0] = font->set;
3356 * Nothing was found in the cache. Now use
3357 * some dozen of Fontconfig calls to get the
3358 * font for one single character.
3360 * Xft and fontconfig are design failures.
3362 fcpattern = FcPatternDuplicate(font->pattern);
3363 fccharset = FcCharSetCreate();
3365 FcCharSetAddChar(fccharset, rune);
3366 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3368 FcPatternAddBool(fcpattern, FC_SCALABLE,
3371 FcConfigSubstitute(0, fcpattern,
3373 FcDefaultSubstitute(fcpattern);
3375 fontpattern = FcFontSetMatch(0, fcsets, 1,
3379 * Overwrite or create the new cache entry.
3381 if(frclen >= LEN(frc)) {
3382 frclen = LEN(frc) - 1;
3383 XftFontClose(xw.dpy, frc[frclen].font);
3384 frc[frclen].unicodep = 0;
3387 frc[frclen].font = XftFontOpenPattern(xw.dpy,
3389 frc[frclen].flags = frcflags;
3390 frc[frclen].unicodep = rune;
3392 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
3397 FcPatternDestroy(fcpattern);
3398 FcCharSetDestroy(fccharset);
3401 specs[numspecs].font = frc[f].font;
3402 specs[numspecs].glyph = glyphidx;
3403 specs[numspecs].x = (short)xp;
3404 specs[numspecs].y = (short)(winy + frc[f].font->ascent);
3413 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y) {
3414 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
3415 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
3416 width = charlen * xw.cw;
3417 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
3418 XRenderColor colfg, colbg;
3421 /* Determine foreground and background colors based on mode. */
3422 if(base.fg == defaultfg) {
3423 if(base.mode & ATTR_ITALIC)
3424 base.fg = defaultitalic;
3425 else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD))
3426 base.fg = defaultitalic;
3427 else if(base.mode & ATTR_UNDERLINE)
3428 base.fg = defaultunderline;
3431 if(IS_TRUECOL(base.fg)) {
3432 colfg.alpha = 0xffff;
3433 colfg.red = TRUERED(base.fg);
3434 colfg.green = TRUEGREEN(base.fg);
3435 colfg.blue = TRUEBLUE(base.fg);
3436 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
3439 fg = &dc.col[base.fg];
3442 if(IS_TRUECOL(base.bg)) {
3443 colbg.alpha = 0xffff;
3444 colbg.green = TRUEGREEN(base.bg);
3445 colbg.red = TRUERED(base.bg);
3446 colbg.blue = TRUEBLUE(base.bg);
3447 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
3450 bg = &dc.col[base.bg];
3453 /* Change basic system colors [0-7] to bright system colors [8-15] */
3454 if((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
3455 fg = &dc.col[base.fg + 8];
3457 if(IS_SET(MODE_REVERSE)) {
3458 if(fg == &dc.col[defaultfg]) {
3459 fg = &dc.col[defaultbg];
3461 colfg.red = ~fg->color.red;
3462 colfg.green = ~fg->color.green;
3463 colfg.blue = ~fg->color.blue;
3464 colfg.alpha = fg->color.alpha;
3465 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
3470 if(bg == &dc.col[defaultbg]) {
3471 bg = &dc.col[defaultfg];
3473 colbg.red = ~bg->color.red;
3474 colbg.green = ~bg->color.green;
3475 colbg.blue = ~bg->color.blue;
3476 colbg.alpha = bg->color.alpha;
3477 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
3483 if(base.mode & ATTR_REVERSE) {
3489 if((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
3490 colfg.red = fg->color.red / 2;
3491 colfg.green = fg->color.green / 2;
3492 colfg.blue = fg->color.blue / 2;
3493 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
3497 if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3500 if(base.mode & ATTR_INVISIBLE)
3503 /* Intelligent cleaning up of the borders. */
3505 xclear(0, (y == 0)? 0 : winy, borderpx,
3506 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3508 if(x + charlen >= term.col) {
3509 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3510 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3513 xclear(winx, 0, winx + width, borderpx);
3515 xclear(winx, winy + xw.ch, winx + width, xw.h);
3517 /* Clean up the region we want to draw to. */
3518 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3520 /* Set the clip region because Xft is sometimes dirty. */
3525 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3527 /* Render the glyphs. */
3528 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
3530 /* Render underline and strikethrough. */
3531 if(base.mode & ATTR_UNDERLINE) {
3532 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
3536 if(base.mode & ATTR_STRUCK) {
3537 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
3541 /* Reset clip to none. */
3542 XftDrawSetClip(xw.draw, 0);
3546 xdrawglyph(Glyph g, int x, int y) {
3548 XftGlyphFontSpec spec;
3549 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
3550 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
3555 static int oldx = 0, oldy = 0;
3557 Glyph g = {' ', ATTR_NULL, defaultbg, defaultcs};
3559 LIMIT(oldx, 0, term.col-1);
3560 LIMIT(oldy, 0, term.row-1);
3564 /* adjust position if in dummy */
3565 if(term.line[oldy][oldx].mode & ATTR_WDUMMY)
3567 if(term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3570 g.u = term.line[term.c.y][term.c.x].u;
3572 /* remove the old cursor */
3573 xdrawglyph(term.line[oldy][oldx], oldx, oldy);
3575 if(IS_SET(MODE_HIDE))
3578 /* draw the new one */
3579 if(xw.state & WIN_FOCUSED) {
3580 switch (xw.cursor) {
3581 case 0: /* Blinking Block */
3582 case 1: /* Blinking Block (Default) */
3583 case 2: /* Steady Block */
3584 if(IS_SET(MODE_REVERSE)) {
3585 g.mode |= ATTR_REVERSE;
3590 g.mode |= term.line[term.c.y][curx].mode & ATTR_WIDE;
3591 xdrawglyph(g, term.c.x, term.c.y);
3593 case 3: /* Blinking Underline */
3594 case 4: /* Steady Underline */
3595 XftDrawRect(xw.draw, &dc.col[defaultcs],
3596 borderpx + curx * xw.cw,
3597 borderpx + (term.c.y + 1) * xw.ch - cursorthickness,
3598 xw.cw, cursorthickness);
3600 case 5: /* Blinking bar */
3601 case 6: /* Steady bar */
3602 XftDrawRect(xw.draw, &dc.col[defaultcs],
3603 borderpx + curx * xw.cw,
3604 borderpx + term.c.y * xw.ch,
3605 cursorthickness, xw.ch);
3609 XftDrawRect(xw.draw, &dc.col[defaultcs],
3610 borderpx + curx * xw.cw,
3611 borderpx + term.c.y * xw.ch,
3613 XftDrawRect(xw.draw, &dc.col[defaultcs],
3614 borderpx + curx * xw.cw,
3615 borderpx + term.c.y * xw.ch,
3617 XftDrawRect(xw.draw, &dc.col[defaultcs],
3618 borderpx + (curx + 1) * xw.cw - 1,
3619 borderpx + term.c.y * xw.ch,
3621 XftDrawRect(xw.draw, &dc.col[defaultcs],
3622 borderpx + curx * xw.cw,
3623 borderpx + (term.c.y + 1) * xw.ch - 1,
3626 oldx = curx, oldy = term.c.y;
3631 xsettitle(char *p) {
3634 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3636 XSetWMName(xw.dpy, xw.win, &prop);
3637 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
3643 xsettitle(opt_title ? opt_title : "st");
3654 drawregion(0, 0, term.col, term.row);
3655 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3657 XSetForeground(xw.dpy, dc.gc,
3658 dc.col[IS_SET(MODE_REVERSE)?
3659 defaultfg : defaultbg].pixel);
3663 drawregion(int x1, int y1, int x2, int y2) {
3664 int i, x, y, ox, numspecs;
3666 XftGlyphFontSpec* specs;
3667 bool ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
3669 if(!(xw.state & WIN_VISIBLE))
3672 for(y = y1; y < y2; y++) {
3676 xtermclear(0, y, term.col, y);
3679 specs = term.specbuf;
3680 numspecs = xmakeglyphfontspecs(specs, &term.line[y][x1], x2 - x1, x1, y);
3683 for(x = x1; x < x2 && i < numspecs; x++) {
3684 new = term.line[y][x];
3685 if(new.mode == ATTR_WDUMMY)
3687 if(ena_sel && selected(x, y))
3688 new.mode ^= ATTR_REVERSE;
3689 if(i > 0 && ATTRCMP(base, new)) {
3690 xdrawglyphfontspecs(specs, base, i, ox, y);
3702 xdrawglyphfontspecs(specs, base, i, ox, y);
3708 expose(XEvent *ev) {
3713 visibility(XEvent *ev) {
3714 XVisibilityEvent *e = &ev->xvisibility;
3716 MODBIT(xw.state, e->state != VisibilityFullyObscured, WIN_VISIBLE);
3721 xw.state &= ~WIN_VISIBLE;
3725 xsetpointermotion(int set) {
3726 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3727 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3731 xseturgency(int add) {
3732 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3734 MODBIT(h->flags, add, XUrgencyHint);
3735 XSetWMHints(xw.dpy, xw.win, h);
3741 XFocusChangeEvent *e = &ev->xfocus;
3743 if(e->mode == NotifyGrab)
3746 if(ev->type == FocusIn) {
3747 XSetICFocus(xw.xic);
3748 xw.state |= WIN_FOCUSED;
3750 if(IS_SET(MODE_FOCUS))
3751 ttywrite("\033[I", 3);
3753 XUnsetICFocus(xw.xic);
3754 xw.state &= ~WIN_FOCUSED;
3755 if(IS_SET(MODE_FOCUS))
3756 ttywrite("\033[O", 3);
3761 match(uint mask, uint state) {
3762 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
3766 numlock(const Arg *dummy) {
3771 kmap(KeySym k, uint state) {
3775 /* Check for mapped keys out of X11 function keys. */
3776 for(i = 0; i < LEN(mappedkeys); i++) {
3777 if(mappedkeys[i] == k)
3780 if(i == LEN(mappedkeys)) {
3781 if((k & 0xFFFF) < 0xFD00)
3785 for(kp = key; kp < key + LEN(key); kp++) {
3789 if(!match(kp->mask, state))
3792 if(IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
3794 if(term.numlock && kp->appkey == 2)
3797 if(IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
3800 if(IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
3810 kpress(XEvent *ev) {
3811 XKeyEvent *e = &ev->xkey;
3813 char buf[32], *customkey;
3819 if(IS_SET(MODE_KBDLOCK))
3822 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
3824 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3825 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3826 bp->func(&(bp->arg));
3831 /* 2. custom keys from config.h */
3832 if((customkey = kmap(ksym, e->state))) {
3833 ttysend(customkey, strlen(customkey));
3837 /* 3. composed string from input method */
3840 if(len == 1 && e->state & Mod1Mask) {
3841 if(IS_SET(MODE_8BIT)) {
3844 len = utf8encode(c, buf);
3857 cmessage(XEvent *e) {
3860 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3862 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3863 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3864 xw.state |= WIN_FOCUSED;
3866 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3867 xw.state &= ~WIN_FOCUSED;
3869 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3870 /* Send SIGHUP to shell */
3877 cresize(int width, int height) {
3885 col = (xw.w - 2 * borderpx) / xw.cw;
3886 row = (xw.h - 2 * borderpx) / xw.ch;
3895 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3898 cresize(e->xconfigure.width, e->xconfigure.height);
3904 int w = xw.w, h = xw.h;
3906 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3907 struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
3910 /* Waiting for window mapping */
3912 XNextEvent(xw.dpy, &ev);
3914 * XFilterEvent is required to be called after you using XOpenIM,
3915 * this is not unnecessary.It does not only filter the key event,
3916 * but some clientmessage for input method as well.
3918 if(XFilterEvent(&ev, None))
3920 if(ev.type == ConfigureNotify) {
3921 w = ev.xconfigure.width;
3922 h = ev.xconfigure.height;
3924 } while(ev.type != MapNotify);
3929 clock_gettime(CLOCK_MONOTONIC, &last);
3932 for(xev = actionfps;;) {
3934 FD_SET(cmdfd, &rfd);
3937 if(pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
3940 die("select failed: %s\n", strerror(errno));
3942 if(FD_ISSET(cmdfd, &rfd)) {
3945 blinkset = tattrset(ATTR_BLINK);
3947 MODBIT(term.mode, 0, MODE_BLINK);
3951 if(FD_ISSET(xfd, &rfd))
3954 clock_gettime(CLOCK_MONOTONIC, &now);
3955 drawtimeout.tv_sec = 0;
3956 drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
3960 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3961 tsetdirtattr(ATTR_BLINK);
3962 term.mode ^= MODE_BLINK;
3966 deltatime = TIMEDIFF(now, last);
3967 if(deltatime > 1000 / (xev ? xfps : actionfps)) {
3973 while(XPending(xw.dpy)) {
3974 XNextEvent(xw.dpy, &ev);
3975 if(XFilterEvent(&ev, None))
3977 if(handler[ev.type])
3978 (handler[ev.type])(&ev);
3984 if(xev && !FD_ISSET(xfd, &rfd))
3986 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3988 if(TIMEDIFF(now, lastblink) \
3990 drawtimeout.tv_nsec = 1000;
3992 drawtimeout.tv_nsec = (1E6 * \
3997 drawtimeout.tv_sec = \
3998 drawtimeout.tv_nsec / 1E9;
3999 drawtimeout.tv_nsec %= (long)1E9;
4010 die("%s " VERSION " (c) 2010-2015 st engineers\n"
4011 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]\n"
4012 " [-i] [-t title] [-w windowid] [-e command ...] [command ...]\n"
4013 " st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]\n"
4014 " [-i] [-t title] [-w windowid] [-l line] [stty_args ...]\n",
4019 main(int argc, char *argv[]) {
4020 uint cols = 80, rows = 24;
4028 allowaltscreen = false;
4031 opt_class = EARGF(usage());
4038 opt_font = EARGF(usage());
4041 xw.gm = XParseGeometry(EARGF(usage()),
4042 &xw.l, &xw.t, &cols, &rows);
4048 opt_io = EARGF(usage());
4051 opt_line = EARGF(usage());
4054 opt_title = EARGF(usage());
4057 opt_embed = EARGF(usage());
4066 /* eat all remaining arguments */
4068 if(!opt_title && !opt_line)
4069 opt_title = basename(xstrdup(argv[0]));
4071 setlocale(LC_CTYPE, "");
4072 XSetLocaleModifiers("");
4073 tnew(MAX(cols, 1), MAX(rows, 1));