1 /* See LICENSE for license details. */
14 #include <sys/ioctl.h>
15 #include <sys/select.h>
18 #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 DIVCEIL(n, d) (((n) + ((d) - 1)) / (d))
72 #define ISCONTROLC0(c) (BETWEEN(c, 0, 0x1f) || (c) == '\177')
73 #define ISCONTROLC1(c) (BETWEEN(c, 0x80, 0x9f))
74 #define ISCONTROL(c) (ISCONTROLC0(c) || ISCONTROLC1(c))
75 #define ISDELIM(u) (utf8strchr(worddelimiters, u) != NULL)
76 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
77 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || \
79 #define IS_SET(flag) ((term.mode & (flag)) != 0)
80 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + \
81 (t1.tv_nsec-t2.tv_nsec)/1E6)
82 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
84 #define TRUECOLOR(r,g,b) (1 << 24 | (r) << 16 | (g) << 8 | (b))
85 #define IS_TRUECOL(x) (1 << 24 & (x))
86 #define TRUERED(x) (((x) & 0xff0000) >> 8)
87 #define TRUEGREEN(x) (((x) & 0xff00))
88 #define TRUEBLUE(x) (((x) & 0xff) << 8)
91 enum glyph_attribute {
96 ATTR_UNDERLINE = 1 << 3,
98 ATTR_REVERSE = 1 << 5,
99 ATTR_INVISIBLE = 1 << 6,
100 ATTR_STRUCK = 1 << 7,
103 ATTR_WDUMMY = 1 << 10,
104 ATTR_BOLD_FAINT = ATTR_BOLD | ATTR_FAINT,
107 enum cursor_movement {
120 MODE_INSERT = 1 << 1,
121 MODE_APPKEYPAD = 1 << 2,
122 MODE_ALTSCREEN = 1 << 3,
124 MODE_MOUSEBTN = 1 << 5,
125 MODE_MOUSEMOTION = 1 << 6,
126 MODE_REVERSE = 1 << 7,
127 MODE_KBDLOCK = 1 << 8,
130 MODE_APPCURSOR = 1 << 11,
131 MODE_MOUSESGR = 1 << 12,
133 MODE_BLINK = 1 << 14,
134 MODE_FBLINK = 1 << 15,
135 MODE_FOCUS = 1 << 16,
136 MODE_MOUSEX10 = 1 << 17,
137 MODE_MOUSEMANY = 1 << 18,
138 MODE_BRCKTPASTE = 1 << 19,
139 MODE_PRINT = 1 << 20,
141 MODE_MOUSE = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
158 ESC_STR = 4, /* DCS, OSC, PM, APC */
160 ESC_STR_END = 16, /* a final string was encountered */
161 ESC_TEST = 32, /* Enter in test mode */
170 enum selection_mode {
176 enum selection_type {
181 enum selection_snap {
186 typedef unsigned char uchar;
187 typedef unsigned int uint;
188 typedef unsigned long ulong;
189 typedef unsigned short ushort;
191 typedef uint_least32_t Rune;
193 typedef XftDraw *Draw;
194 typedef XftColor Color;
197 Rune u; /* character code */
198 ushort mode; /* attribute flags */
199 uint32_t fg; /* foreground */
200 uint32_t bg; /* background */
206 Glyph attr; /* current char attributes */
212 /* CSI Escape sequence structs */
213 /* ESC '[' [[ [<priv>] <arg> [;]] <mode> [<mode>]] */
215 char buf[ESC_BUF_SIZ]; /* raw string */
216 int len; /* raw string length */
218 int arg[ESC_ARG_SIZ];
219 int narg; /* nb of args */
223 /* STR Escape sequence structs */
224 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
226 char type; /* ESC type ... */
227 char buf[STR_BUF_SIZ]; /* raw string */
228 int len; /* raw string length */
229 char *args[STR_ARG_SIZ];
230 int narg; /* nb of args */
233 /* Internal representation of the screen */
235 int row; /* nb row */
236 int col; /* nb col */
237 Line *line; /* screen */
238 Line *alt; /* alternate screen */
239 int *dirty; /* dirtyness of lines */
240 XftGlyphFontSpec *specbuf; /* font spec buffer used for rendering */
241 TCursor c; /* cursor */
242 int top; /* top scroll limit */
243 int bot; /* bottom scroll limit */
244 int mode; /* terminal mode flags */
245 int esc; /* escape state flags */
246 char trantbl[4]; /* charset table translation */
247 int charset; /* current charset */
248 int icharset; /* selected charset for sequence */
249 int numlock; /* lock numbers in keyboard */
253 /* Purely graphic info */
259 Atom xembed, wmdeletewin, netwmname, netwmpid;
264 XSetWindowAttributes attrs;
266 int isfixed; /* is fixed geometry? */
267 int l, t; /* left and top offset */
268 int gm; /* geometry mask */
269 int tw, th; /* tty width and height */
270 int w, h; /* window width and height */
271 int ch; /* char height */
272 int cw; /* char width */
273 char state; /* focus, redraw, visible */
274 int cursor; /* cursor style */
287 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
288 signed char appkey; /* application keypad */
289 signed char appcursor; /* application cursor */
290 signed char crlf; /* crlf mode */
298 * Selection variables:
299 * nb – normalized coordinates of the beginning of the selection
300 * ne – normalized coordinates of the end of the selection
301 * ob – original coordinates of the beginning of the selection
302 * oe – original coordinates of the end of the selection
308 char *primary, *clipboard;
311 struct timespec tclick1;
312 struct timespec tclick2;
325 void (*func)(const Arg *);
329 /* function definitions used in config.h */
330 static void clipcopy(const Arg *);
331 static void clippaste(const Arg *);
332 static void numlock(const Arg *);
333 static void selpaste(const Arg *);
334 static void xzoom(const Arg *);
335 static void xzoomabs(const Arg *);
336 static void xzoomreset(const Arg *);
337 static void printsel(const Arg *);
338 static void printscreen(const Arg *) ;
339 static void toggleprinter(const Arg *);
340 static void sendbreak(const Arg *);
342 /* Config.h for applying patches and the configuration. */
358 /* Drawing Context */
360 Color col[MAX(LEN(colorname), 256)];
361 Font font, bfont, ifont, ibfont;
365 static void die(const char *, ...);
366 static void draw(void);
367 static void redraw(void);
368 static void drawregion(int, int, int, int);
369 static void execsh(void);
370 static void stty(void);
371 static void sigchld(int);
372 static void run(void);
374 static void csidump(void);
375 static void csihandle(void);
376 static void csiparse(void);
377 static void csireset(void);
378 static int eschandle(uchar);
379 static void strdump(void);
380 static void strhandle(void);
381 static void strparse(void);
382 static void strreset(void);
384 static int tattrset(int);
385 static void tprinter(char *, size_t);
386 static void tdumpsel(void);
387 static void tdumpline(int);
388 static void tdump(void);
389 static void tclearregion(int, int, int, int);
390 static void tcursor(int);
391 static void tdeletechar(int);
392 static void tdeleteline(int);
393 static void tinsertblank(int);
394 static void tinsertblankline(int);
395 static int tlinelen(int);
396 static void tmoveto(int, int);
397 static void tmoveato(int, int);
398 static void tnew(int, int);
399 static void tnewline(int);
400 static void tputtab(int);
401 static void tputc(Rune);
402 static void treset(void);
403 static void tresize(int, int);
404 static void tscrollup(int, int);
405 static void tscrolldown(int, int);
406 static void tsetattr(int *, int);
407 static void tsetchar(Rune, Glyph *, int, int);
408 static void tsetscroll(int, int);
409 static void tswapscreen(void);
410 static void tsetdirt(int, int);
411 static void tsetdirtattr(int);
412 static void tsetmode(int, int, int *, int);
413 static void tfulldirt(void);
414 static void techo(Rune);
415 static void tcontrolcode(uchar );
416 static void tdectest(char );
417 static void tdefutf8(char);
418 static int32_t tdefcolor(int *, int *, int);
419 static void tdeftran(char);
420 static inline int match(uint, uint);
421 static void ttynew(void);
422 static size_t ttyread(void);
423 static void ttyresize(void);
424 static void ttysend(char *, size_t);
425 static void ttywrite(const char *, size_t);
426 static void tstrsequence(uchar);
428 static inline ushort sixd_to_16bit(int);
429 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
430 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
431 static void xdrawglyph(Glyph, int, int);
432 static void xhints(void);
433 static void xclear(int, int, int, int);
434 static void xdrawcursor(void);
435 static void xinit(void);
436 static void xloadcols(void);
437 static int xsetcolorname(int, const char *);
438 static int xgeommasktogravity(int);
439 static int xloadfont(Font *, FcPattern *);
440 static void xloadfonts(char *, double);
441 static void xsettitle(char *);
442 static void xresettitle(void);
443 static void xsetpointermotion(int);
444 static void xseturgency(int);
445 static void xsetsel(char *, Time);
446 static void xunloadfont(Font *);
447 static void xunloadfonts(void);
448 static void xresize(int, int);
450 static void expose(XEvent *);
451 static void visibility(XEvent *);
452 static void unmap(XEvent *);
453 static char *kmap(KeySym, uint);
454 static void kpress(XEvent *);
455 static void cmessage(XEvent *);
456 static void cresize(int, int);
457 static void resize(XEvent *);
458 static void focus(XEvent *);
459 static void brelease(XEvent *);
460 static void bpress(XEvent *);
461 static void bmotion(XEvent *);
462 static void propnotify(XEvent *);
463 static void selnotify(XEvent *);
464 static void selclear(XEvent *);
465 static void selrequest(XEvent *);
467 static void selinit(void);
468 static void selnormalize(void);
469 static inline int selected(int, int);
470 static char *getsel(void);
471 static void selcopy(Time);
472 static void selscroll(int, int);
473 static void selsnap(int *, int *, int);
474 static int x2col(int);
475 static int y2row(int);
476 static void getbuttoninfo(XEvent *);
477 static void mousereport(XEvent *);
479 static size_t utf8decode(char *, Rune *, size_t);
480 static Rune utf8decodebyte(char, size_t *);
481 static size_t utf8encode(Rune, char *);
482 static char utf8encodebyte(Rune, size_t);
483 static char *utf8strchr(char *s, Rune u);
484 static size_t utf8validate(Rune *, size_t);
486 static ssize_t xwrite(int, const char *, size_t);
487 static void *xmalloc(size_t);
488 static void *xrealloc(void *, size_t);
489 static char *xstrdup(char *);
491 static void usage(void);
493 static void (*handler[LASTEvent])(XEvent *) = {
495 [ClientMessage] = cmessage,
496 [ConfigureNotify] = resize,
497 [VisibilityNotify] = visibility,
498 [UnmapNotify] = unmap,
502 [MotionNotify] = bmotion,
503 [ButtonPress] = bpress,
504 [ButtonRelease] = brelease,
506 * Uncomment if you want the selection to disappear when you select something
507 * different in another window.
509 /* [SelectionClear] = selclear, */
510 [SelectionNotify] = selnotify,
512 * PropertyNotify is only turned on when there is some INCR transfer happening
513 * for the selection retrieval.
515 [PropertyNotify] = propnotify,
516 [SelectionRequest] = selrequest,
523 static CSIEscape csiescseq;
524 static STREscape strescseq;
527 static Selection sel;
529 static char **opt_cmd = NULL;
530 static char *opt_class = NULL;
531 static char *opt_embed = NULL;
532 static char *opt_font = NULL;
533 static char *opt_io = NULL;
534 static char *opt_line = NULL;
535 static char *opt_name = NULL;
536 static char *opt_title = NULL;
537 static int oldbutton = 3; /* button event on startup: 3 = release */
539 static char *usedfont = NULL;
540 static double usedfontsize = 0;
541 static double defaultfontsize = 0;
543 static uchar utfbyte[UTF_SIZ + 1] = {0x80, 0, 0xC0, 0xE0, 0xF0};
544 static uchar utfmask[UTF_SIZ + 1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
545 static Rune utfmin[UTF_SIZ + 1] = { 0, 0, 0x80, 0x800, 0x10000};
546 static Rune utfmax[UTF_SIZ + 1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
548 /* Font Ring Cache */
562 /* Fontcache is an array now. A new font will be appended to the array. */
563 static Fontcache frc[16];
564 static int frclen = 0;
567 xwrite(int fd, const char *s, size_t len)
573 r = write(fd, s, len);
586 void *p = malloc(len);
589 die("Out of memory\n");
595 xrealloc(void *p, size_t len)
597 if ((p = realloc(p, len)) == NULL)
598 die("Out of memory\n");
606 if ((s = strdup(s)) == NULL)
607 die("Out of memory\n");
613 utf8decode(char *c, Rune *u, size_t clen)
615 size_t i, j, len, type;
621 udecoded = utf8decodebyte(c[0], &len);
622 if (!BETWEEN(len, 1, UTF_SIZ))
624 for (i = 1, j = 1; i < clen && j < len; ++i, ++j) {
625 udecoded = (udecoded << 6) | utf8decodebyte(c[i], &type);
632 utf8validate(u, len);
638 utf8decodebyte(char c, size_t *i)
640 for (*i = 0; *i < LEN(utfmask); ++(*i))
641 if (((uchar)c & utfmask[*i]) == utfbyte[*i])
642 return (uchar)c & ~utfmask[*i];
648 utf8encode(Rune u, char *c)
652 len = utf8validate(&u, 0);
656 for (i = len - 1; i != 0; --i) {
657 c[i] = utf8encodebyte(u, 0);
660 c[0] = utf8encodebyte(u, len);
666 utf8encodebyte(Rune u, size_t i)
668 return utfbyte[i] | (u & ~utfmask[i]);
672 utf8strchr(char *s, Rune u)
678 for (i = 0, j = 0; i < len; i += j) {
679 if (!(j = utf8decode(&s[i], &r, len - i)))
689 utf8validate(Rune *u, size_t i)
691 if (!BETWEEN(*u, utfmin[i], utfmax[i]) || BETWEEN(*u, 0xD800, 0xDFFF))
693 for (i = 1; *u > utfmax[i]; ++i)
702 clock_gettime(CLOCK_MONOTONIC, &sel.tclick1);
703 clock_gettime(CLOCK_MONOTONIC, &sel.tclick2);
708 sel.clipboard = NULL;
709 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
710 if (sel.xtarget == None)
711 sel.xtarget = XA_STRING;
720 return LIMIT(x, 0, term.col-1);
729 return LIMIT(y, 0, term.row-1);
737 if (term.line[y][i - 1].mode & ATTR_WRAP)
740 while (i > 0 && term.line[y][i - 1].u == ' ')
751 if (sel.type == SEL_REGULAR && sel.ob.y != sel.oe.y) {
752 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
753 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
755 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
756 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
758 sel.nb.y = MIN(sel.ob.y, sel.oe.y);
759 sel.ne.y = MAX(sel.ob.y, sel.oe.y);
761 selsnap(&sel.nb.x, &sel.nb.y, -1);
762 selsnap(&sel.ne.x, &sel.ne.y, +1);
764 /* expand selection over line breaks */
765 if (sel.type == SEL_RECTANGULAR)
767 i = tlinelen(sel.nb.y);
770 if (tlinelen(sel.ne.y) <= sel.ne.x)
771 sel.ne.x = term.col - 1;
775 selected(int x, int y)
777 if (sel.mode == SEL_EMPTY)
780 if (sel.type == SEL_RECTANGULAR)
781 return BETWEEN(y, sel.nb.y, sel.ne.y)
782 && BETWEEN(x, sel.nb.x, sel.ne.x);
784 return BETWEEN(y, sel.nb.y, sel.ne.y)
785 && (y != sel.nb.y || x >= sel.nb.x)
786 && (y != sel.ne.y || x <= sel.ne.x);
790 selsnap(int *x, int *y, int direction)
792 int newx, newy, xt, yt;
793 int delim, prevdelim;
799 * Snap around if the word wraps around at the end or
800 * beginning of a line.
802 prevgp = &term.line[*y][*x];
803 prevdelim = ISDELIM(prevgp->u);
805 newx = *x + direction;
807 if (!BETWEEN(newx, 0, term.col - 1)) {
809 newx = (newx + term.col) % term.col;
810 if (!BETWEEN(newy, 0, term.row - 1))
816 yt = newy, xt = newx;
817 if (!(term.line[yt][xt].mode & ATTR_WRAP))
821 if (newx >= tlinelen(newy))
824 gp = &term.line[newy][newx];
825 delim = ISDELIM(gp->u);
826 if (!(gp->mode & ATTR_WDUMMY) && (delim != prevdelim
827 || (delim && gp->u != prevgp->u)))
838 * Snap around if the the previous line or the current one
839 * has set ATTR_WRAP at its end. Then the whole next or
840 * previous line will be selected.
842 *x = (direction < 0) ? 0 : term.col - 1;
844 for (; *y > 0; *y += direction) {
845 if (!(term.line[*y-1][term.col-1].mode
850 } else if (direction > 0) {
851 for (; *y < term.row-1; *y += direction) {
852 if (!(term.line[*y][term.col-1].mode
863 getbuttoninfo(XEvent *e)
866 uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
868 sel.alt = IS_SET(MODE_ALTSCREEN);
870 sel.oe.x = x2col(e->xbutton.x);
871 sel.oe.y = y2row(e->xbutton.y);
874 sel.type = SEL_REGULAR;
875 for (type = 1; type < LEN(selmasks); ++type) {
876 if (match(selmasks[type], state)) {
884 mousereport(XEvent *e)
886 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
887 button = e->xbutton.button, state = e->xbutton.state,
893 if (e->xbutton.type == MotionNotify) {
894 if (x == ox && y == oy)
896 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
898 /* MOUSE_MOTION: no reporting if no button is pressed */
899 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
902 button = oldbutton + 32;
906 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
913 if (e->xbutton.type == ButtonPress) {
917 } else if (e->xbutton.type == ButtonRelease) {
919 /* MODE_MOUSEX10: no button release reporting */
920 if (IS_SET(MODE_MOUSEX10))
922 if (button == 64 || button == 65)
927 if (!IS_SET(MODE_MOUSEX10)) {
928 button += ((state & ShiftMask ) ? 4 : 0)
929 + ((state & Mod4Mask ) ? 8 : 0)
930 + ((state & ControlMask) ? 16 : 0);
933 if (IS_SET(MODE_MOUSESGR)) {
934 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
936 e->xbutton.type == ButtonRelease ? 'm' : 'M');
937 } else if (x < 223 && y < 223) {
938 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
939 32+button, 32+x+1, 32+y+1);
953 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
958 for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
959 if (e->xbutton.button == ms->b
960 && match(ms->mask, e->xbutton.state)) {
961 ttysend(ms->s, strlen(ms->s));
966 if (e->xbutton.button == Button1) {
967 clock_gettime(CLOCK_MONOTONIC, &now);
969 /* Clear previous selection, logically and visually. */
971 sel.mode = SEL_EMPTY;
972 sel.type = SEL_REGULAR;
973 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
974 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
977 * If the user clicks below predefined timeouts specific
978 * snapping behaviour is exposed.
980 if (TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
981 sel.snap = SNAP_LINE;
982 } else if (TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
983 sel.snap = SNAP_WORD;
990 sel.mode = SEL_READY;
991 tsetdirt(sel.nb.y, sel.ne.y);
992 sel.tclick2 = sel.tclick1;
1001 int y, bufsize, lastx, linelen;
1007 bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
1008 ptr = str = xmalloc(bufsize);
1010 /* append every set & selected glyph to the selection */
1011 for (y = sel.nb.y; y <= sel.ne.y; y++) {
1012 if ((linelen = tlinelen(y)) == 0) {
1017 if (sel.type == SEL_RECTANGULAR) {
1018 gp = &term.line[y][sel.nb.x];
1021 gp = &term.line[y][sel.nb.y == y ? sel.nb.x : 0];
1022 lastx = (sel.ne.y == y) ? sel.ne.x : term.col-1;
1024 last = &term.line[y][MIN(lastx, linelen-1)];
1025 while (last >= gp && last->u == ' ')
1028 for ( ; gp <= last; ++gp) {
1029 if (gp->mode & ATTR_WDUMMY)
1032 ptr += utf8encode(gp->u, ptr);
1036 * Copy and pasting of line endings is inconsistent
1037 * in the inconsistent terminal and GUI world.
1038 * The best solution seems like to produce '\n' when
1039 * something is copied from st and convert '\n' to
1040 * '\r', when something to be pasted is received by
1042 * FIXME: Fix the computer world.
1044 if ((y < sel.ne.y || lastx >= linelen) && !(last->mode & ATTR_WRAP))
1054 xsetsel(getsel(), t);
1058 propnotify(XEvent *e)
1060 XPropertyEvent *xpev;
1061 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1063 xpev = &e->xproperty;
1064 if (xpev->state == PropertyNewValue &&
1065 (xpev->atom == XA_PRIMARY ||
1066 xpev->atom == clipboard)) {
1072 selnotify(XEvent *e)
1074 ulong nitems, ofs, rem;
1076 uchar *data, *last, *repl;
1077 Atom type, incratom, property;
1079 incratom = XInternAtom(xw.dpy, "INCR", 0);
1082 if (e->type == SelectionNotify) {
1083 property = e->xselection.property;
1084 } else if(e->type == PropertyNotify) {
1085 property = e->xproperty.atom;
1089 if (property == None)
1093 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
1094 BUFSIZ/4, False, AnyPropertyType,
1095 &type, &format, &nitems, &rem,
1097 fprintf(stderr, "Clipboard allocation failed\n");
1101 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
1103 * If there is some PropertyNotify with no data, then
1104 * this is the signal of the selection owner that all
1105 * data has been transferred. We won't need to receive
1106 * PropertyNotify events anymore.
1108 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
1109 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
1113 if (type == incratom) {
1115 * Activate the PropertyNotify events so we receive
1116 * when the selection owner does send us the next
1119 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
1120 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
1124 * Deleting the property is the transfer start signal.
1126 XDeleteProperty(xw.dpy, xw.win, (int)property);
1131 * As seen in getsel:
1132 * Line endings are inconsistent in the terminal and GUI world
1133 * copy and pasting. When receiving some selection data,
1134 * replace all '\n' with '\r'.
1135 * FIXME: Fix the computer world.
1138 last = data + nitems * format / 8;
1139 while ((repl = memchr(repl, '\n', last - repl))) {
1143 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
1144 ttywrite("\033[200~", 6);
1145 ttysend((char *)data, nitems * format / 8);
1146 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
1147 ttywrite("\033[201~", 6);
1149 /* number of 32-bit chunks returned */
1150 ofs += nitems * format / 32;
1154 * Deleting the property again tells the selection owner to send the
1155 * next data chunk in the property.
1157 XDeleteProperty(xw.dpy, xw.win, (int)property);
1161 selpaste(const Arg *dummy)
1163 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1164 xw.win, CurrentTime);
1168 clipcopy(const Arg *dummy)
1172 if (sel.clipboard != NULL)
1173 free(sel.clipboard);
1175 if (sel.primary != NULL) {
1176 sel.clipboard = xstrdup(sel.primary);
1177 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1178 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1183 clippaste(const Arg *dummy)
1187 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1188 XConvertSelection(xw.dpy, clipboard, sel.xtarget, clipboard,
1189 xw.win, CurrentTime);
1197 sel.mode = SEL_IDLE;
1199 tsetdirt(sel.nb.y, sel.ne.y);
1203 selrequest(XEvent *e)
1205 XSelectionRequestEvent *xsre;
1206 XSelectionEvent xev;
1207 Atom xa_targets, string, clipboard;
1210 xsre = (XSelectionRequestEvent *) e;
1211 xev.type = SelectionNotify;
1212 xev.requestor = xsre->requestor;
1213 xev.selection = xsre->selection;
1214 xev.target = xsre->target;
1215 xev.time = xsre->time;
1216 if (xsre->property == None)
1217 xsre->property = xsre->target;
1220 xev.property = None;
1222 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1223 if (xsre->target == xa_targets) {
1224 /* respond with the supported type */
1225 string = sel.xtarget;
1226 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1227 XA_ATOM, 32, PropModeReplace,
1228 (uchar *) &string, 1);
1229 xev.property = xsre->property;
1230 } else if (xsre->target == sel.xtarget || xsre->target == XA_STRING) {
1232 * xith XA_STRING non ascii characters may be incorrect in the
1233 * requestor. It is not our problem, use utf8.
1235 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1236 if (xsre->selection == XA_PRIMARY) {
1237 seltext = sel.primary;
1238 } else if (xsre->selection == clipboard) {
1239 seltext = sel.clipboard;
1242 "Unhandled clipboard selection 0x%lx\n",
1246 if (seltext != NULL) {
1247 XChangeProperty(xsre->display, xsre->requestor,
1248 xsre->property, xsre->target,
1250 (uchar *)seltext, strlen(seltext));
1251 xev.property = xsre->property;
1255 /* all done, send a notification to the listener */
1256 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
1257 fprintf(stderr, "Error sending SelectionNotify event\n");
1261 xsetsel(char *str, Time t)
1266 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
1267 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
1274 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
1279 if (e->xbutton.button == Button2) {
1281 } else if (e->xbutton.button == Button1) {
1282 if (sel.mode == SEL_READY) {
1284 selcopy(e->xbutton.time);
1287 sel.mode = SEL_IDLE;
1288 tsetdirt(sel.nb.y, sel.ne.y);
1295 int oldey, oldex, oldsby, oldsey;
1297 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
1305 sel.mode = SEL_READY;
1312 if (oldey != sel.oe.y || oldex != sel.oe.x)
1313 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1317 die(const char *errstr, ...)
1321 va_start(ap, errstr);
1322 vfprintf(stderr, errstr, ap);
1330 char **args, *sh, *prog;
1331 const struct passwd *pw;
1332 char buf[sizeof(long) * 8 + 1];
1335 if ((pw = getpwuid(getuid())) == NULL) {
1337 die("getpwuid:%s\n", strerror(errno));
1339 die("who are you?\n");
1342 if ((sh = getenv("SHELL")) == NULL)
1343 sh = (pw->pw_shell[0]) ? pw->pw_shell : shell;
1351 args = (opt_cmd) ? opt_cmd : (char *[]) {prog, NULL};
1353 snprintf(buf, sizeof(buf), "%lu", xw.win);
1355 unsetenv("COLUMNS");
1357 unsetenv("TERMCAP");
1358 setenv("LOGNAME", pw->pw_name, 1);
1359 setenv("USER", pw->pw_name, 1);
1360 setenv("SHELL", sh, 1);
1361 setenv("HOME", pw->pw_dir, 1);
1362 setenv("TERM", termname, 1);
1363 setenv("WINDOWID", buf, 1);
1365 signal(SIGCHLD, SIG_DFL);
1366 signal(SIGHUP, SIG_DFL);
1367 signal(SIGINT, SIG_DFL);
1368 signal(SIGQUIT, SIG_DFL);
1369 signal(SIGTERM, SIG_DFL);
1370 signal(SIGALRM, SIG_DFL);
1382 if ((p = waitpid(pid, &stat, WNOHANG)) < 0)
1383 die("Waiting for pid %hd failed: %s\n", pid, strerror(errno));
1388 if (!WIFEXITED(stat) || WEXITSTATUS(stat))
1389 die("child finished with error '%d'\n", stat);
1397 char cmd[_POSIX_ARG_MAX], **p, *q, *s;
1400 if ((n = strlen(stty_args)) > sizeof(cmd)-1)
1401 die("incorrect stty parameters\n");
1402 memcpy(cmd, stty_args, n);
1404 siz = sizeof(cmd) - n;
1405 for (p = opt_cmd; p && (s = *p); ++p) {
1406 if ((n = strlen(s)) > siz-1)
1407 die("stty parameter length too long\n");
1414 if (system(cmd) != 0)
1415 perror("Couldn't call stty");
1422 struct winsize w = {term.row, term.col, 0, 0};
1425 term.mode |= MODE_PRINT;
1426 iofd = (!strcmp(opt_io, "-")) ?
1427 1 : open(opt_io, O_WRONLY | O_CREAT, 0666);
1429 fprintf(stderr, "Error opening %s:%s\n",
1430 opt_io, strerror(errno));
1435 if ((cmdfd = open(opt_line, O_RDWR)) < 0)
1436 die("open line failed: %s\n", strerror(errno));
1442 /* seems to work fine on linux, openbsd and freebsd */
1443 if (openpty(&m, &s, NULL, NULL, &w) < 0)
1444 die("openpty failed: %s\n", strerror(errno));
1446 switch (pid = fork()) {
1448 die("fork failed\n");
1452 setsid(); /* create a new process group */
1456 if (ioctl(s, TIOCSCTTY, NULL) < 0)
1457 die("ioctl TIOCSCTTY failed: %s\n", strerror(errno));
1465 signal(SIGCHLD, sigchld);
1473 static char buf[BUFSIZ];
1474 static int buflen = 0;
1476 int charsize; /* size of utf8 char in bytes */
1480 /* append read bytes to unprocessed bytes */
1481 if ((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1482 die("Couldn't read from shell: %s\n", strerror(errno));
1488 if (IS_SET(MODE_UTF8)) {
1489 /* process a complete utf8 char */
1490 charsize = utf8decode(ptr, &unicodep, buflen);
1500 tputc(*ptr++ & 0xFF);
1504 /* keep any uncomplete utf8 char for the next call */
1506 memmove(buf, ptr, buflen);
1512 ttywrite(const char *s, size_t n)
1519 * Remember that we are using a pty, which might be a modem line.
1520 * Writing too much will clog the line. That's why we are doing this
1522 * FIXME: Migrate the world to Plan 9.
1527 FD_SET(cmdfd, &wfd);
1528 FD_SET(cmdfd, &rfd);
1530 /* Check if we can write. */
1531 if (pselect(cmdfd+1, &rfd, &wfd, NULL, NULL, NULL) < 0) {
1534 die("select failed: %s\n", strerror(errno));
1536 if (FD_ISSET(cmdfd, &wfd)) {
1538 * Only write the bytes written by ttywrite() or the
1539 * default of 256. This seems to be a reasonable value
1540 * for a serial line. Bigger values might clog the I/O.
1542 if ((r = write(cmdfd, s, (n < lim)? n : lim)) < 0)
1546 * We weren't able to write out everything.
1547 * This means the buffer is getting full
1555 /* All bytes have been written. */
1559 if (FD_ISSET(cmdfd, &rfd))
1565 die("write error on tty: %s\n", strerror(errno));
1569 ttysend(char *s, size_t n)
1576 if (!IS_SET(MODE_ECHO))
1580 for (t = s; t < lim; t += len) {
1581 if (IS_SET(MODE_UTF8)) {
1582 len = utf8decode(t, &u, n);
1599 w.ws_row = term.row;
1600 w.ws_col = term.col;
1601 w.ws_xpixel = xw.tw;
1602 w.ws_ypixel = xw.th;
1603 if (ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1604 fprintf(stderr, "Couldn't set window size: %s\n", strerror(errno));
1612 for (i = 0; i < term.row-1; i++) {
1613 for (j = 0; j < term.col-1; j++) {
1614 if (term.line[i][j].mode & attr)
1623 tsetdirt(int top, int bot)
1627 LIMIT(top, 0, term.row-1);
1628 LIMIT(bot, 0, term.row-1);
1630 for (i = top; i <= bot; i++)
1635 tsetdirtattr(int attr)
1639 for (i = 0; i < term.row-1; i++) {
1640 for (j = 0; j < term.col-1; j++) {
1641 if (term.line[i][j].mode & attr) {
1652 tsetdirt(0, term.row-1);
1658 static TCursor c[2];
1659 int alt = IS_SET(MODE_ALTSCREEN);
1661 if (mode == CURSOR_SAVE) {
1663 } else if (mode == CURSOR_LOAD) {
1665 tmoveto(c[alt].x, c[alt].y);
1674 term.c = (TCursor){{
1678 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1680 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1681 for (i = tabspaces; i < term.col; i += tabspaces)
1684 term.bot = term.row - 1;
1685 term.mode = MODE_WRAP|MODE_UTF8;
1686 memset(term.trantbl, CS_USA, sizeof(term.trantbl));
1689 for (i = 0; i < 2; i++) {
1691 tcursor(CURSOR_SAVE);
1692 tclearregion(0, 0, term.col-1, term.row-1);
1698 tnew(int col, int row)
1700 term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
1710 Line *tmp = term.line;
1712 term.line = term.alt;
1714 term.mode ^= MODE_ALTSCREEN;
1719 tscrolldown(int orig, int n)
1724 LIMIT(n, 0, term.bot-orig+1);
1726 tsetdirt(orig, term.bot-n);
1727 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1729 for (i = term.bot; i >= orig+n; i--) {
1730 temp = term.line[i];
1731 term.line[i] = term.line[i-n];
1732 term.line[i-n] = temp;
1739 tscrollup(int orig, int n)
1744 LIMIT(n, 0, term.bot-orig+1);
1746 tclearregion(0, orig, term.col-1, orig+n-1);
1747 tsetdirt(orig+n, term.bot);
1749 for (i = orig; i <= term.bot-n; i++) {
1750 temp = term.line[i];
1751 term.line[i] = term.line[i+n];
1752 term.line[i+n] = temp;
1755 selscroll(orig, -n);
1759 selscroll(int orig, int n)
1764 if (BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1765 if ((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1769 if (sel.type == SEL_RECTANGULAR) {
1770 if (sel.ob.y < term.top)
1771 sel.ob.y = term.top;
1772 if (sel.oe.y > term.bot)
1773 sel.oe.y = term.bot;
1775 if (sel.ob.y < term.top) {
1776 sel.ob.y = term.top;
1779 if (sel.oe.y > term.bot) {
1780 sel.oe.y = term.bot;
1781 sel.oe.x = term.col;
1789 tnewline(int first_col)
1793 if (y == term.bot) {
1794 tscrollup(term.top, 1);
1798 tmoveto(first_col ? 0 : term.c.x, y);
1804 char *p = csiescseq.buf, *np;
1813 csiescseq.buf[csiescseq.len] = '\0';
1814 while (p < csiescseq.buf+csiescseq.len) {
1816 v = strtol(p, &np, 10);
1819 if (v == LONG_MAX || v == LONG_MIN)
1821 csiescseq.arg[csiescseq.narg++] = v;
1823 if (*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1827 csiescseq.mode[0] = *p++;
1828 csiescseq.mode[1] = (p < csiescseq.buf+csiescseq.len) ? *p : '\0';
1831 /* for absolute user moves, when decom is set */
1833 tmoveato(int x, int y)
1835 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1839 tmoveto(int x, int y)
1843 if (term.c.state & CURSOR_ORIGIN) {
1848 maxy = term.row - 1;
1850 term.c.state &= ~CURSOR_WRAPNEXT;
1851 term.c.x = LIMIT(x, 0, term.col-1);
1852 term.c.y = LIMIT(y, miny, maxy);
1856 tsetchar(Rune u, Glyph *attr, int x, int y)
1858 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1859 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1860 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1861 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1862 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1863 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1864 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1865 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1866 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1870 * The table is proudly stolen from rxvt.
1872 if (term.trantbl[term.charset] == CS_GRAPHIC0 &&
1873 BETWEEN(u, 0x41, 0x7e) && vt100_0[u - 0x41])
1874 utf8decode(vt100_0[u - 0x41], &u, UTF_SIZ);
1876 if (term.line[y][x].mode & ATTR_WIDE) {
1877 if (x+1 < term.col) {
1878 term.line[y][x+1].u = ' ';
1879 term.line[y][x+1].mode &= ~ATTR_WDUMMY;
1881 } else if (term.line[y][x].mode & ATTR_WDUMMY) {
1882 term.line[y][x-1].u = ' ';
1883 term.line[y][x-1].mode &= ~ATTR_WIDE;
1887 term.line[y][x] = *attr;
1888 term.line[y][x].u = u;
1892 tclearregion(int x1, int y1, int x2, int y2)
1898 temp = x1, x1 = x2, x2 = temp;
1900 temp = y1, y1 = y2, y2 = temp;
1902 LIMIT(x1, 0, term.col-1);
1903 LIMIT(x2, 0, term.col-1);
1904 LIMIT(y1, 0, term.row-1);
1905 LIMIT(y2, 0, term.row-1);
1907 for (y = y1; y <= y2; y++) {
1909 for (x = x1; x <= x2; x++) {
1910 gp = &term.line[y][x];
1913 gp->fg = term.c.attr.fg;
1914 gp->bg = term.c.attr.bg;
1927 LIMIT(n, 0, term.col - term.c.x);
1931 size = term.col - src;
1932 line = term.line[term.c.y];
1934 memmove(&line[dst], &line[src], size * sizeof(Glyph));
1935 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1944 LIMIT(n, 0, term.col - term.c.x);
1948 size = term.col - dst;
1949 line = term.line[term.c.y];
1951 memmove(&line[dst], &line[src], size * sizeof(Glyph));
1952 tclearregion(src, term.c.y, dst - 1, term.c.y);
1956 tinsertblankline(int n)
1958 if (BETWEEN(term.c.y, term.top, term.bot))
1959 tscrolldown(term.c.y, n);
1965 if (BETWEEN(term.c.y, term.top, term.bot))
1966 tscrollup(term.c.y, n);
1970 tdefcolor(int *attr, int *npar, int l)
1975 switch (attr[*npar + 1]) {
1976 case 2: /* direct color in RGB space */
1977 if (*npar + 4 >= l) {
1979 "erresc(38): Incorrect number of parameters (%d)\n",
1983 r = attr[*npar + 2];
1984 g = attr[*npar + 3];
1985 b = attr[*npar + 4];
1987 if (!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1988 fprintf(stderr, "erresc: bad rgb color (%u,%u,%u)\n",
1991 idx = TRUECOLOR(r, g, b);
1993 case 5: /* indexed color */
1994 if (*npar + 2 >= l) {
1996 "erresc(38): Incorrect number of parameters (%d)\n",
2001 if (!BETWEEN(attr[*npar], 0, 255))
2002 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
2006 case 0: /* implemented defined (only foreground) */
2007 case 1: /* transparent */
2008 case 3: /* direct color in CMY space */
2009 case 4: /* direct color in CMYK space */
2012 "erresc(38): gfx attr %d unknown\n", attr[*npar]);
2020 tsetattr(int *attr, int l)
2025 for (i = 0; i < l; i++) {
2028 term.c.attr.mode &= ~(
2037 term.c.attr.fg = defaultfg;
2038 term.c.attr.bg = defaultbg;
2041 term.c.attr.mode |= ATTR_BOLD;
2044 term.c.attr.mode |= ATTR_FAINT;
2047 term.c.attr.mode |= ATTR_ITALIC;
2050 term.c.attr.mode |= ATTR_UNDERLINE;
2052 case 5: /* slow blink */
2054 case 6: /* rapid blink */
2055 term.c.attr.mode |= ATTR_BLINK;
2058 term.c.attr.mode |= ATTR_REVERSE;
2061 term.c.attr.mode |= ATTR_INVISIBLE;
2064 term.c.attr.mode |= ATTR_STRUCK;
2067 term.c.attr.mode &= ~(ATTR_BOLD | ATTR_FAINT);
2070 term.c.attr.mode &= ~ATTR_ITALIC;
2073 term.c.attr.mode &= ~ATTR_UNDERLINE;
2076 term.c.attr.mode &= ~ATTR_BLINK;
2079 term.c.attr.mode &= ~ATTR_REVERSE;
2082 term.c.attr.mode &= ~ATTR_INVISIBLE;
2085 term.c.attr.mode &= ~ATTR_STRUCK;
2088 if ((idx = tdefcolor(attr, &i, l)) >= 0)
2089 term.c.attr.fg = idx;
2092 term.c.attr.fg = defaultfg;
2095 if ((idx = tdefcolor(attr, &i, l)) >= 0)
2096 term.c.attr.bg = idx;
2099 term.c.attr.bg = defaultbg;
2102 if (BETWEEN(attr[i], 30, 37)) {
2103 term.c.attr.fg = attr[i] - 30;
2104 } else if (BETWEEN(attr[i], 40, 47)) {
2105 term.c.attr.bg = attr[i] - 40;
2106 } else if (BETWEEN(attr[i], 90, 97)) {
2107 term.c.attr.fg = attr[i] - 90 + 8;
2108 } else if (BETWEEN(attr[i], 100, 107)) {
2109 term.c.attr.bg = attr[i] - 100 + 8;
2112 "erresc(default): gfx attr %d unknown\n",
2113 attr[i]), csidump();
2121 tsetscroll(int t, int b)
2125 LIMIT(t, 0, term.row-1);
2126 LIMIT(b, 0, term.row-1);
2137 tsetmode(int priv, int set, int *args, int narg)
2142 for (lim = args + narg; args < lim; ++args) {
2145 case 1: /* DECCKM -- Cursor key */
2146 MODBIT(term.mode, set, MODE_APPCURSOR);
2148 case 5: /* DECSCNM -- Reverse video */
2150 MODBIT(term.mode, set, MODE_REVERSE);
2151 if (mode != term.mode)
2154 case 6: /* DECOM -- Origin */
2155 MODBIT(term.c.state, set, CURSOR_ORIGIN);
2158 case 7: /* DECAWM -- Auto wrap */
2159 MODBIT(term.mode, set, MODE_WRAP);
2161 case 0: /* Error (IGNORED) */
2162 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
2163 case 3: /* DECCOLM -- Column (IGNORED) */
2164 case 4: /* DECSCLM -- Scroll (IGNORED) */
2165 case 8: /* DECARM -- Auto repeat (IGNORED) */
2166 case 18: /* DECPFF -- Printer feed (IGNORED) */
2167 case 19: /* DECPEX -- Printer extent (IGNORED) */
2168 case 42: /* DECNRCM -- National characters (IGNORED) */
2169 case 12: /* att610 -- Start blinking cursor (IGNORED) */
2171 case 25: /* DECTCEM -- Text Cursor Enable Mode */
2172 MODBIT(term.mode, !set, MODE_HIDE);
2174 case 9: /* X10 mouse compatibility mode */
2175 xsetpointermotion(0);
2176 MODBIT(term.mode, 0, MODE_MOUSE);
2177 MODBIT(term.mode, set, MODE_MOUSEX10);
2179 case 1000: /* 1000: report button press */
2180 xsetpointermotion(0);
2181 MODBIT(term.mode, 0, MODE_MOUSE);
2182 MODBIT(term.mode, set, MODE_MOUSEBTN);
2184 case 1002: /* 1002: report motion on button press */
2185 xsetpointermotion(0);
2186 MODBIT(term.mode, 0, MODE_MOUSE);
2187 MODBIT(term.mode, set, MODE_MOUSEMOTION);
2189 case 1003: /* 1003: enable all mouse motions */
2190 xsetpointermotion(set);
2191 MODBIT(term.mode, 0, MODE_MOUSE);
2192 MODBIT(term.mode, set, MODE_MOUSEMANY);
2194 case 1004: /* 1004: send focus events to tty */
2195 MODBIT(term.mode, set, MODE_FOCUS);
2197 case 1006: /* 1006: extended reporting mode */
2198 MODBIT(term.mode, set, MODE_MOUSESGR);
2201 MODBIT(term.mode, set, MODE_8BIT);
2203 case 1049: /* swap screen & set/restore cursor as xterm */
2204 if (!allowaltscreen)
2206 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
2208 case 47: /* swap screen */
2210 if (!allowaltscreen)
2212 alt = IS_SET(MODE_ALTSCREEN);
2214 tclearregion(0, 0, term.col-1,
2217 if (set ^ alt) /* set is always 1 or 0 */
2223 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
2225 case 2004: /* 2004: bracketed paste mode */
2226 MODBIT(term.mode, set, MODE_BRCKTPASTE);
2228 /* Not implemented mouse modes. See comments there. */
2229 case 1001: /* mouse highlight mode; can hang the
2230 terminal by design when implemented. */
2231 case 1005: /* UTF-8 mouse mode; will confuse
2232 applications not supporting UTF-8
2234 case 1015: /* urxvt mangled mouse mode; incompatible
2235 and can be mistaken for other control
2239 "erresc: unknown private set/reset mode %d\n",
2245 case 0: /* Error (IGNORED) */
2247 case 2: /* KAM -- keyboard action */
2248 MODBIT(term.mode, set, MODE_KBDLOCK);
2250 case 4: /* IRM -- Insertion-replacement */
2251 MODBIT(term.mode, set, MODE_INSERT);
2253 case 12: /* SRM -- Send/Receive */
2254 MODBIT(term.mode, !set, MODE_ECHO);
2256 case 20: /* LNM -- Linefeed/new line */
2257 MODBIT(term.mode, set, MODE_CRLF);
2261 "erresc: unknown set/reset mode %d\n",
2275 switch (csiescseq.mode[0]) {
2278 fprintf(stderr, "erresc: unknown csi ");
2282 case '@': /* ICH -- Insert <n> blank char */
2283 DEFAULT(csiescseq.arg[0], 1);
2284 tinsertblank(csiescseq.arg[0]);
2286 case 'A': /* CUU -- Cursor <n> Up */
2287 DEFAULT(csiescseq.arg[0], 1);
2288 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
2290 case 'B': /* CUD -- Cursor <n> Down */
2291 case 'e': /* VPR --Cursor <n> Down */
2292 DEFAULT(csiescseq.arg[0], 1);
2293 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
2295 case 'i': /* MC -- Media Copy */
2296 switch (csiescseq.arg[0]) {
2301 tdumpline(term.c.y);
2307 term.mode &= ~MODE_PRINT;
2310 term.mode |= MODE_PRINT;
2314 case 'c': /* DA -- Device Attributes */
2315 if (csiescseq.arg[0] == 0)
2316 ttywrite(vtiden, sizeof(vtiden) - 1);
2318 case 'C': /* CUF -- Cursor <n> Forward */
2319 case 'a': /* HPR -- Cursor <n> Forward */
2320 DEFAULT(csiescseq.arg[0], 1);
2321 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
2323 case 'D': /* CUB -- Cursor <n> Backward */
2324 DEFAULT(csiescseq.arg[0], 1);
2325 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
2327 case 'E': /* CNL -- Cursor <n> Down and first col */
2328 DEFAULT(csiescseq.arg[0], 1);
2329 tmoveto(0, term.c.y+csiescseq.arg[0]);
2331 case 'F': /* CPL -- Cursor <n> Up and first col */
2332 DEFAULT(csiescseq.arg[0], 1);
2333 tmoveto(0, term.c.y-csiescseq.arg[0]);
2335 case 'g': /* TBC -- Tabulation clear */
2336 switch (csiescseq.arg[0]) {
2337 case 0: /* clear current tab stop */
2338 term.tabs[term.c.x] = 0;
2340 case 3: /* clear all the tabs */
2341 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
2347 case 'G': /* CHA -- Move to <col> */
2349 DEFAULT(csiescseq.arg[0], 1);
2350 tmoveto(csiescseq.arg[0]-1, term.c.y);
2352 case 'H': /* CUP -- Move to <row> <col> */
2354 DEFAULT(csiescseq.arg[0], 1);
2355 DEFAULT(csiescseq.arg[1], 1);
2356 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
2358 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
2359 DEFAULT(csiescseq.arg[0], 1);
2360 tputtab(csiescseq.arg[0]);
2362 case 'J': /* ED -- Clear screen */
2364 switch (csiescseq.arg[0]) {
2366 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
2367 if (term.c.y < term.row-1) {
2368 tclearregion(0, term.c.y+1, term.col-1,
2374 tclearregion(0, 0, term.col-1, term.c.y-1);
2375 tclearregion(0, term.c.y, term.c.x, term.c.y);
2378 tclearregion(0, 0, term.col-1, term.row-1);
2384 case 'K': /* EL -- Clear line */
2385 switch (csiescseq.arg[0]) {
2387 tclearregion(term.c.x, term.c.y, term.col-1,
2391 tclearregion(0, term.c.y, term.c.x, term.c.y);
2394 tclearregion(0, term.c.y, term.col-1, term.c.y);
2398 case 'S': /* SU -- Scroll <n> line up */
2399 DEFAULT(csiescseq.arg[0], 1);
2400 tscrollup(term.top, csiescseq.arg[0]);
2402 case 'T': /* SD -- Scroll <n> line down */
2403 DEFAULT(csiescseq.arg[0], 1);
2404 tscrolldown(term.top, csiescseq.arg[0]);
2406 case 'L': /* IL -- Insert <n> blank lines */
2407 DEFAULT(csiescseq.arg[0], 1);
2408 tinsertblankline(csiescseq.arg[0]);
2410 case 'l': /* RM -- Reset Mode */
2411 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2413 case 'M': /* DL -- Delete <n> lines */
2414 DEFAULT(csiescseq.arg[0], 1);
2415 tdeleteline(csiescseq.arg[0]);
2417 case 'X': /* ECH -- Erase <n> char */
2418 DEFAULT(csiescseq.arg[0], 1);
2419 tclearregion(term.c.x, term.c.y,
2420 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2422 case 'P': /* DCH -- Delete <n> char */
2423 DEFAULT(csiescseq.arg[0], 1);
2424 tdeletechar(csiescseq.arg[0]);
2426 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2427 DEFAULT(csiescseq.arg[0], 1);
2428 tputtab(-csiescseq.arg[0]);
2430 case 'd': /* VPA -- Move to <row> */
2431 DEFAULT(csiescseq.arg[0], 1);
2432 tmoveato(term.c.x, csiescseq.arg[0]-1);
2434 case 'h': /* SM -- Set terminal mode */
2435 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2437 case 'm': /* SGR -- Terminal attribute (color) */
2438 tsetattr(csiescseq.arg, csiescseq.narg);
2440 case 'n': /* DSR – Device Status Report (cursor position) */
2441 if (csiescseq.arg[0] == 6) {
2442 len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
2443 term.c.y+1, term.c.x+1);
2447 case 'r': /* DECSTBM -- Set Scrolling Region */
2448 if (csiescseq.priv) {
2451 DEFAULT(csiescseq.arg[0], 1);
2452 DEFAULT(csiescseq.arg[1], term.row);
2453 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2457 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2458 tcursor(CURSOR_SAVE);
2460 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2461 tcursor(CURSOR_LOAD);
2464 switch (csiescseq.mode[1]) {
2465 case 'q': /* DECSCUSR -- Set Cursor Style */
2466 DEFAULT(csiescseq.arg[0], 1);
2467 if (!BETWEEN(csiescseq.arg[0], 0, 6)) {
2470 xw.cursor = csiescseq.arg[0];
2486 for (i = 0; i < csiescseq.len; i++) {
2487 c = csiescseq.buf[i] & 0xff;
2490 } else if (c == '\n') {
2492 } else if (c == '\r') {
2494 } else if (c == 0x1b) {
2497 printf("(%02x)", c);
2506 memset(&csiescseq, 0, sizeof(csiescseq));
2515 term.esc &= ~(ESC_STR_END|ESC_STR);
2517 par = (narg = strescseq.narg) ? atoi(strescseq.args[0]) : 0;
2519 switch (strescseq.type) {
2520 case ']': /* OSC -- Operating System Command */
2526 xsettitle(strescseq.args[1]);
2528 case 4: /* color set */
2531 p = strescseq.args[2];
2533 case 104: /* color reset, here p = NULL */
2534 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2535 if (xsetcolorname(j, p)) {
2536 fprintf(stderr, "erresc: invalid color %s\n", p);
2539 * TODO if defaultbg color is changed, borders
2547 case 'k': /* old title set compatibility */
2548 xsettitle(strescseq.args[0]);
2550 case 'P': /* DCS -- Device Control String */
2551 case '_': /* APC -- Application Program Command */
2552 case '^': /* PM -- Privacy Message */
2556 fprintf(stderr, "erresc: unknown str ");
2564 char *p = strescseq.buf;
2567 strescseq.buf[strescseq.len] = '\0';
2572 while (strescseq.narg < STR_ARG_SIZ) {
2573 strescseq.args[strescseq.narg++] = p;
2574 while ((c = *p) != ';' && c != '\0')
2588 printf("ESC%c", strescseq.type);
2589 for (i = 0; i < strescseq.len; i++) {
2590 c = strescseq.buf[i] & 0xff;
2593 } else if (isprint(c)) {
2595 } else if (c == '\n') {
2597 } else if (c == '\r') {
2599 } else if (c == 0x1b) {
2602 printf("(%02x)", c);
2611 memset(&strescseq, 0, sizeof(strescseq));
2615 sendbreak(const Arg *arg)
2617 if (tcsendbreak(cmdfd, 0))
2618 perror("Error sending break");
2622 tprinter(char *s, size_t len)
2624 if (iofd != -1 && xwrite(iofd, s, len) < 0) {
2625 fprintf(stderr, "Error writing in %s:%s\n",
2626 opt_io, strerror(errno));
2633 toggleprinter(const Arg *arg)
2635 term.mode ^= MODE_PRINT;
2639 printscreen(const Arg *arg)
2645 printsel(const Arg *arg)
2655 if ((ptr = getsel())) {
2656 tprinter(ptr, strlen(ptr));
2667 bp = &term.line[n][0];
2668 end = &bp[MIN(tlinelen(n), term.col) - 1];
2669 if (bp != end || bp->u != ' ') {
2670 for ( ;bp <= end; ++bp)
2671 tprinter(buf, utf8encode(bp->u, buf));
2681 for (i = 0; i < term.row; ++i)
2691 while (x < term.col && n--)
2692 for (++x; x < term.col && !term.tabs[x]; ++x)
2695 while (x > 0 && n++)
2696 for (--x; x > 0 && !term.tabs[x]; --x)
2699 term.c.x = LIMIT(x, 0, term.col-1);
2705 if (ISCONTROL(u)) { /* control code */
2710 } else if (u != '\n' && u != '\r' && u != '\t') {
2719 tdefutf8(char ascii)
2722 term.mode |= MODE_UTF8;
2723 else if (ascii == '@')
2724 term.mode &= ~MODE_UTF8;
2728 tdeftran(char ascii)
2730 static char cs[] = "0B";
2731 static int vcs[] = {CS_GRAPHIC0, CS_USA};
2734 if ((p = strchr(cs, ascii)) == NULL) {
2735 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2737 term.trantbl[term.icharset] = vcs[p - cs];
2746 if (c == '8') { /* DEC screen alignment test. */
2747 for (x = 0; x < term.col; ++x) {
2748 for (y = 0; y < term.row; ++y)
2749 tsetchar('E', &term.c.attr, x, y);
2755 tstrsequence(uchar c)
2758 case 0x90: /* DCS -- Device Control String */
2761 case 0x9f: /* APC -- Application Program Command */
2764 case 0x9e: /* PM -- Privacy Message */
2767 case 0x9d: /* OSC -- Operating System Command */
2773 term.esc |= ESC_STR;
2777 tcontrolcode(uchar ascii)
2784 tmoveto(term.c.x-1, term.c.y);
2787 tmoveto(0, term.c.y);
2792 /* go to first col if the mode is set */
2793 tnewline(IS_SET(MODE_CRLF));
2795 case '\a': /* BEL */
2796 if (term.esc & ESC_STR_END) {
2797 /* backwards compatibility to xterm */
2800 if (!(xw.state & WIN_FOCUSED))
2803 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
2806 case '\033': /* ESC */
2808 term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
2809 term.esc |= ESC_START;
2811 case '\016': /* SO (LS1 -- Locking shift 1) */
2812 case '\017': /* SI (LS0 -- Locking shift 0) */
2813 term.charset = 1 - (ascii - '\016');
2815 case '\032': /* SUB */
2816 tsetchar('?', &term.c.attr, term.c.x, term.c.y);
2817 case '\030': /* CAN */
2820 case '\005': /* ENQ (IGNORED) */
2821 case '\000': /* NUL (IGNORED) */
2822 case '\021': /* XON (IGNORED) */
2823 case '\023': /* XOFF (IGNORED) */
2824 case 0177: /* DEL (IGNORED) */
2826 case 0x80: /* TODO: PAD */
2827 case 0x81: /* TODO: HOP */
2828 case 0x82: /* TODO: BPH */
2829 case 0x83: /* TODO: NBH */
2830 case 0x84: /* TODO: IND */
2832 case 0x85: /* NEL -- Next line */
2833 tnewline(1); /* always go to first col */
2835 case 0x86: /* TODO: SSA */
2836 case 0x87: /* TODO: ESA */
2838 case 0x88: /* HTS -- Horizontal tab stop */
2839 term.tabs[term.c.x] = 1;
2841 case 0x89: /* TODO: HTJ */
2842 case 0x8a: /* TODO: VTS */
2843 case 0x8b: /* TODO: PLD */
2844 case 0x8c: /* TODO: PLU */
2845 case 0x8d: /* TODO: RI */
2846 case 0x8e: /* TODO: SS2 */
2847 case 0x8f: /* TODO: SS3 */
2848 case 0x91: /* TODO: PU1 */
2849 case 0x92: /* TODO: PU2 */
2850 case 0x93: /* TODO: STS */
2851 case 0x94: /* TODO: CCH */
2852 case 0x95: /* TODO: MW */
2853 case 0x96: /* TODO: SPA */
2854 case 0x97: /* TODO: EPA */
2855 case 0x98: /* TODO: SOS */
2856 case 0x99: /* TODO: SGCI */
2858 case 0x9a: /* DECID -- Identify Terminal */
2859 ttywrite(vtiden, sizeof(vtiden) - 1);
2861 case 0x9b: /* TODO: CSI */
2862 case 0x9c: /* TODO: ST */
2864 case 0x90: /* DCS -- Device Control String */
2865 case 0x9d: /* OSC -- Operating System Command */
2866 case 0x9e: /* PM -- Privacy Message */
2867 case 0x9f: /* APC -- Application Program Command */
2868 tstrsequence(ascii);
2871 /* only CAN, SUB, \a and C1 chars interrupt a sequence */
2872 term.esc &= ~(ESC_STR_END|ESC_STR);
2876 * returns 1 when the sequence is finished and it hasn't to read
2877 * more characters for this sequence, otherwise 0
2880 eschandle(uchar ascii)
2884 term.esc |= ESC_CSI;
2887 term.esc |= ESC_TEST;
2890 term.esc |= ESC_UTF8;
2892 case 'P': /* DCS -- Device Control String */
2893 case '_': /* APC -- Application Program Command */
2894 case '^': /* PM -- Privacy Message */
2895 case ']': /* OSC -- Operating System Command */
2896 case 'k': /* old title set compatibility */
2897 tstrsequence(ascii);
2899 case 'n': /* LS2 -- Locking shift 2 */
2900 case 'o': /* LS3 -- Locking shift 3 */
2901 term.charset = 2 + (ascii - 'n');
2903 case '(': /* GZD4 -- set primary charset G0 */
2904 case ')': /* G1D4 -- set secondary charset G1 */
2905 case '*': /* G2D4 -- set tertiary charset G2 */
2906 case '+': /* G3D4 -- set quaternary charset G3 */
2907 term.icharset = ascii - '(';
2908 term.esc |= ESC_ALTCHARSET;
2910 case 'D': /* IND -- Linefeed */
2911 if (term.c.y == term.bot) {
2912 tscrollup(term.top, 1);
2914 tmoveto(term.c.x, term.c.y+1);
2917 case 'E': /* NEL -- Next line */
2918 tnewline(1); /* always go to first col */
2920 case 'H': /* HTS -- Horizontal tab stop */
2921 term.tabs[term.c.x] = 1;
2923 case 'M': /* RI -- Reverse index */
2924 if (term.c.y == term.top) {
2925 tscrolldown(term.top, 1);
2927 tmoveto(term.c.x, term.c.y-1);
2930 case 'Z': /* DECID -- Identify Terminal */
2931 ttywrite(vtiden, sizeof(vtiden) - 1);
2933 case 'c': /* RIS -- Reset to inital state */
2938 case '=': /* DECPAM -- Application keypad */
2939 term.mode |= MODE_APPKEYPAD;
2941 case '>': /* DECPNM -- Normal keypad */
2942 term.mode &= ~MODE_APPKEYPAD;
2944 case '7': /* DECSC -- Save Cursor */
2945 tcursor(CURSOR_SAVE);
2947 case '8': /* DECRC -- Restore Cursor */
2948 tcursor(CURSOR_LOAD);
2950 case '\\': /* ST -- String Terminator */
2951 if (term.esc & ESC_STR_END)
2955 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2956 (uchar) ascii, isprint(ascii)? ascii:'.');
2970 control = ISCONTROL(u);
2971 if (!IS_SET(MODE_UTF8)) {
2975 len = utf8encode(u, c);
2976 if (!control && (width = wcwidth(u)) == -1) {
2977 memcpy(c, "\357\277\275", 4); /* UTF_INVALID */
2982 if (IS_SET(MODE_PRINT))
2986 * STR sequence must be checked before anything else
2987 * because it uses all following characters until it
2988 * receives a ESC, a SUB, a ST or any other C1 control
2991 if (term.esc & ESC_STR) {
2992 if (u == '\a' || u == 030 || u == 032 || u == 033 ||
2994 term.esc &= ~(ESC_START|ESC_STR);
2995 term.esc |= ESC_STR_END;
2996 } else if (strescseq.len + len < sizeof(strescseq.buf) - 1) {
2997 memmove(&strescseq.buf[strescseq.len], c, len);
2998 strescseq.len += len;
3002 * Here is a bug in terminals. If the user never sends
3003 * some code to stop the str or esc command, then st
3004 * will stop responding. But this is better than
3005 * silently failing with unknown characters. At least
3006 * then users will report back.
3008 * In the case users ever get fixed, here is the code:
3019 * Actions of control codes must be performed as soon they arrive
3020 * because they can be embedded inside a control sequence, and
3021 * they must not cause conflicts with sequences.
3026 * control codes are not shown ever
3029 } else if (term.esc & ESC_START) {
3030 if (term.esc & ESC_CSI) {
3031 csiescseq.buf[csiescseq.len++] = u;
3032 if (BETWEEN(u, 0x40, 0x7E)
3033 || csiescseq.len >= \
3034 sizeof(csiescseq.buf)-1) {
3040 } else if (term.esc & ESC_UTF8) {
3042 } else if (term.esc & ESC_ALTCHARSET) {
3044 } else if (term.esc & ESC_TEST) {
3049 /* sequence already finished */
3053 * All characters which form part of a sequence are not
3058 if (sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
3061 gp = &term.line[term.c.y][term.c.x];
3062 if (IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
3063 gp->mode |= ATTR_WRAP;
3065 gp = &term.line[term.c.y][term.c.x];
3068 if (IS_SET(MODE_INSERT) && term.c.x+width < term.col)
3069 memmove(gp+width, gp, (term.col - term.c.x - width) * sizeof(Glyph));
3071 if (term.c.x+width > term.col) {
3073 gp = &term.line[term.c.y][term.c.x];
3076 tsetchar(u, &term.c.attr, term.c.x, term.c.y);
3079 gp->mode |= ATTR_WIDE;
3080 if (term.c.x+1 < term.col) {
3082 gp[1].mode = ATTR_WDUMMY;
3085 if (term.c.x+width < term.col) {
3086 tmoveto(term.c.x+width, term.c.y);
3088 term.c.state |= CURSOR_WRAPNEXT;
3093 tresize(int col, int row)
3096 int minrow = MIN(row, term.row);
3097 int mincol = MIN(col, term.col);
3101 if (col < 1 || row < 1) {
3103 "tresize: error resizing to %dx%d\n", col, row);
3108 * slide screen to keep cursor where we expect it -
3109 * tscrollup would work here, but we can optimize to
3110 * memmove because we're freeing the earlier lines
3112 for (i = 0; i <= term.c.y - row; i++) {
3116 /* ensure that both src and dst are not NULL */
3118 memmove(term.line, term.line + i, row * sizeof(Line));
3119 memmove(term.alt, term.alt + i, row * sizeof(Line));
3121 for (i += row; i < term.row; i++) {
3126 /* resize to new width */
3127 term.specbuf = xrealloc(term.specbuf, col * sizeof(XftGlyphFontSpec));
3129 /* resize to new height */
3130 term.line = xrealloc(term.line, row * sizeof(Line));
3131 term.alt = xrealloc(term.alt, row * sizeof(Line));
3132 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
3133 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
3135 /* resize each row to new width, zero-pad if needed */
3136 for (i = 0; i < minrow; i++) {
3137 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
3138 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
3141 /* allocate any new rows */
3142 for (/* i == minrow */; i < row; i++) {
3143 term.line[i] = xmalloc(col * sizeof(Glyph));
3144 term.alt[i] = xmalloc(col * sizeof(Glyph));
3146 if (col > term.col) {
3147 bp = term.tabs + term.col;
3149 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
3150 while (--bp > term.tabs && !*bp)
3152 for (bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
3155 /* update terminal size */
3158 /* reset scrolling region */
3159 tsetscroll(0, row-1);
3160 /* make use of the LIMIT in tmoveto */
3161 tmoveto(term.c.x, term.c.y);
3162 /* Clearing both screens (it makes dirty all lines) */
3164 for (i = 0; i < 2; i++) {
3165 if (mincol < col && 0 < minrow) {
3166 tclearregion(mincol, 0, col - 1, minrow - 1);
3168 if (0 < col && minrow < row) {
3169 tclearregion(0, minrow, col - 1, row - 1);
3172 tcursor(CURSOR_LOAD);
3178 xresize(int col, int row)
3180 xw.tw = MAX(1, col * xw.cw);
3181 xw.th = MAX(1, row * xw.ch);
3183 XFreePixmap(xw.dpy, xw.buf);
3184 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3185 DefaultDepth(xw.dpy, xw.scr));
3186 XftDrawChange(xw.draw, xw.buf);
3187 xclear(0, 0, xw.w, xw.h);
3191 sixd_to_16bit(int x)
3193 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
3197 xloadcolor(int i, const char *name, Color *ncolor)
3199 XRenderColor color = { .alpha = 0xffff };
3202 if (BETWEEN(i, 16, 255)) { /* 256 color */
3203 if (i < 6*6*6+16) { /* same colors as xterm */
3204 color.red = sixd_to_16bit( ((i-16)/36)%6 );
3205 color.green = sixd_to_16bit( ((i-16)/6) %6 );
3206 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
3207 } else { /* greyscale */
3208 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
3209 color.green = color.blue = color.red;
3211 return XftColorAllocValue(xw.dpy, xw.vis,
3212 xw.cmap, &color, ncolor);
3214 name = colorname[i];
3217 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
3228 for (cp = dc.col; cp < &dc.col[LEN(dc.col)]; ++cp)
3229 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
3232 for (i = 0; i < LEN(dc.col); i++)
3233 if (!xloadcolor(i, NULL, &dc.col[i])) {
3235 die("Could not allocate color '%s'\n", colorname[i]);
3237 die("Could not allocate color %d\n", i);
3243 xsetcolorname(int x, const char *name)
3247 if (!BETWEEN(x, 0, LEN(dc.col)))
3251 if (!xloadcolor(x, name, &ncolor))
3254 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
3261 * Absolute coordinates.
3264 xclear(int x1, int y1, int x2, int y2)
3266 XftDrawRect(xw.draw,
3267 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
3268 x1, y1, x2-x1, y2-y1);
3274 XClassHint class = {opt_name ? opt_name : termname,
3275 opt_class ? opt_class : termname};
3276 XWMHints wm = {.flags = InputHint, .input = 1};
3277 XSizeHints *sizeh = NULL;
3279 sizeh = XAllocSizeHints();
3281 sizeh->flags = PSize | PResizeInc | PBaseSize;
3282 sizeh->height = xw.h;
3283 sizeh->width = xw.w;
3284 sizeh->height_inc = xw.ch;
3285 sizeh->width_inc = xw.cw;
3286 sizeh->base_height = 2 * borderpx;
3287 sizeh->base_width = 2 * borderpx;
3289 sizeh->flags |= PMaxSize | PMinSize;
3290 sizeh->min_width = sizeh->max_width = xw.w;
3291 sizeh->min_height = sizeh->max_height = xw.h;
3293 if (xw.gm & (XValue|YValue)) {
3294 sizeh->flags |= USPosition | PWinGravity;
3297 sizeh->win_gravity = xgeommasktogravity(xw.gm);
3300 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
3306 xgeommasktogravity(int mask)
3308 switch (mask & (XNegative|YNegative)) {
3310 return NorthWestGravity;
3312 return NorthEastGravity;
3314 return SouthWestGravity;
3317 return SouthEastGravity;
3321 xloadfont(Font *f, FcPattern *pattern)
3327 match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
3331 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
3332 FcPatternDestroy(match);
3336 XftTextExtentsUtf8(xw.dpy, f->match,
3337 (const FcChar8 *) ascii_printable,
3338 strlen(ascii_printable), &extents);
3341 f->pattern = FcPatternDuplicate(pattern);
3343 f->ascent = f->match->ascent;
3344 f->descent = f->match->descent;
3346 f->rbearing = f->match->max_advance_width;
3348 f->height = f->ascent + f->descent;
3349 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
3355 xloadfonts(char *fontstr, double fontsize)
3361 if (fontstr[0] == '-') {
3362 pattern = XftXlfdParse(fontstr, False, False);
3364 pattern = FcNameParse((FcChar8 *)fontstr);
3368 die("st: can't open font %s\n", fontstr);
3371 FcPatternDel(pattern, FC_PIXEL_SIZE);
3372 FcPatternDel(pattern, FC_SIZE);
3373 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
3374 usedfontsize = fontsize;
3376 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
3378 usedfontsize = fontval;
3379 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
3384 * Default font size is 12, if none given. This is to
3385 * have a known usedfontsize value.
3387 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
3390 defaultfontsize = usedfontsize;
3393 if (xloadfont(&dc.font, pattern))
3394 die("st: can't open font %s\n", fontstr);
3396 if (usedfontsize < 0) {
3397 FcPatternGetDouble(dc.font.match->pattern,
3398 FC_PIXEL_SIZE, 0, &fontval);
3399 usedfontsize = fontval;
3401 defaultfontsize = fontval;
3404 /* Setting character width and height. */
3405 xw.cw = ceilf(dc.font.width * cwscale);
3406 xw.ch = ceilf(dc.font.height * chscale);
3408 FcPatternDel(pattern, FC_SLANT);
3409 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
3410 if (xloadfont(&dc.ifont, pattern))
3411 die("st: can't open font %s\n", fontstr);
3413 FcPatternDel(pattern, FC_WEIGHT);
3414 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
3415 if (xloadfont(&dc.ibfont, pattern))
3416 die("st: can't open font %s\n", fontstr);
3418 FcPatternDel(pattern, FC_SLANT);
3419 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
3420 if (xloadfont(&dc.bfont, pattern))
3421 die("st: can't open font %s\n", fontstr);
3423 FcPatternDestroy(pattern);
3427 xunloadfont(Font *f)
3429 XftFontClose(xw.dpy, f->match);
3430 FcPatternDestroy(f->pattern);
3432 FcFontSetDestroy(f->set);
3438 /* Free the loaded fonts in the font cache. */
3440 XftFontClose(xw.dpy, frc[--frclen].font);
3442 xunloadfont(&dc.font);
3443 xunloadfont(&dc.bfont);
3444 xunloadfont(&dc.ifont);
3445 xunloadfont(&dc.ibfont);
3449 xzoom(const Arg *arg)
3453 larg.f = usedfontsize + arg->f;
3458 xzoomabs(const Arg *arg)
3461 xloadfonts(usedfont, arg->f);
3469 xzoomreset(const Arg *arg)
3473 if (defaultfontsize > 0) {
3474 larg.f = defaultfontsize;
3485 pid_t thispid = getpid();
3486 XColor xmousefg, xmousebg;
3488 if (!(xw.dpy = XOpenDisplay(NULL)))
3489 die("Can't open display\n");
3490 xw.scr = XDefaultScreen(xw.dpy);
3491 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
3495 die("Could not init fontconfig.\n");
3497 usedfont = (opt_font == NULL)? font : opt_font;
3498 xloadfonts(usedfont, 0);
3501 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
3504 /* adjust fixed window geometry */
3505 xw.w = 2 * borderpx + term.col * xw.cw;
3506 xw.h = 2 * borderpx + term.row * xw.ch;
3507 if (xw.gm & XNegative)
3508 xw.l += DisplayWidth(xw.dpy, xw.scr) - xw.w - 2;
3509 if (xw.gm & YNegative)
3510 xw.t += DisplayHeight(xw.dpy, xw.scr) - xw.h - 2;
3513 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
3514 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
3515 xw.attrs.bit_gravity = NorthWestGravity;
3516 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
3517 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
3518 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
3519 xw.attrs.colormap = xw.cmap;
3521 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
3522 parent = XRootWindow(xw.dpy, xw.scr);
3523 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
3524 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
3525 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
3526 | CWEventMask | CWColormap, &xw.attrs);
3528 memset(&gcvalues, 0, sizeof(gcvalues));
3529 gcvalues.graphics_exposures = False;
3530 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
3532 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3533 DefaultDepth(xw.dpy, xw.scr));
3534 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
3535 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
3537 /* Xft rendering context */
3538 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
3541 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3542 XSetLocaleModifiers("@im=local");
3543 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3544 XSetLocaleModifiers("@im=");
3545 if ((xw.xim = XOpenIM(xw.dpy,
3546 NULL, NULL, NULL)) == NULL) {
3547 die("XOpenIM failed. Could not open input"
3552 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
3553 | XIMStatusNothing, XNClientWindow, xw.win,
3554 XNFocusWindow, xw.win, NULL);
3556 die("XCreateIC failed. Could not obtain input method.\n");
3558 /* white cursor, black outline */
3559 cursor = XCreateFontCursor(xw.dpy, mouseshape);
3560 XDefineCursor(xw.dpy, xw.win, cursor);
3562 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
3563 xmousefg.red = 0xffff;
3564 xmousefg.green = 0xffff;
3565 xmousefg.blue = 0xffff;
3568 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
3569 xmousebg.red = 0x0000;
3570 xmousebg.green = 0x0000;
3571 xmousebg.blue = 0x0000;
3574 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
3576 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
3577 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
3578 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
3579 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
3581 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
3582 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
3583 PropModeReplace, (uchar *)&thispid, 1);
3586 XMapWindow(xw.dpy, xw.win);
3588 XSync(xw.dpy, False);
3592 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
3594 float winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch, xp, yp;
3595 ushort mode, prevmode = USHRT_MAX;
3596 Font *font = &dc.font;
3597 int frcflags = FRC_NORMAL;
3598 float runewidth = xw.cw;
3602 FcPattern *fcpattern, *fontpattern;
3603 FcFontSet *fcsets[] = { NULL };
3604 FcCharSet *fccharset;
3605 int i, f, numspecs = 0;
3607 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
3608 /* Fetch rune and mode for current glyph. */
3610 mode = glyphs[i].mode;
3612 /* Skip dummy wide-character spacing. */
3613 if (mode == ATTR_WDUMMY)
3616 /* Determine font for glyph if different from previous glyph. */
3617 if (prevmode != mode) {
3620 frcflags = FRC_NORMAL;
3621 runewidth = xw.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
3622 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
3624 frcflags = FRC_ITALICBOLD;
3625 } else if (mode & ATTR_ITALIC) {
3627 frcflags = FRC_ITALIC;
3628 } else if (mode & ATTR_BOLD) {
3630 frcflags = FRC_BOLD;
3632 yp = winy + font->ascent;
3635 /* Lookup character index with default font. */
3636 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
3638 specs[numspecs].font = font->match;
3639 specs[numspecs].glyph = glyphidx;
3640 specs[numspecs].x = (short)xp;
3641 specs[numspecs].y = (short)yp;
3647 /* Fallback on font cache, search the font cache for match. */
3648 for (f = 0; f < frclen; f++) {
3649 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
3650 /* Everything correct. */
3651 if (glyphidx && frc[f].flags == frcflags)
3653 /* We got a default font for a not found glyph. */
3654 if (!glyphidx && frc[f].flags == frcflags
3655 && frc[f].unicodep == rune) {
3660 /* Nothing was found. Use fontconfig to find matching font. */
3663 font->set = FcFontSort(0, font->pattern,
3665 fcsets[0] = font->set;
3668 * Nothing was found in the cache. Now use
3669 * some dozen of Fontconfig calls to get the
3670 * font for one single character.
3672 * Xft and fontconfig are design failures.
3674 fcpattern = FcPatternDuplicate(font->pattern);
3675 fccharset = FcCharSetCreate();
3677 FcCharSetAddChar(fccharset, rune);
3678 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3680 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
3682 FcConfigSubstitute(0, fcpattern,
3684 FcDefaultSubstitute(fcpattern);
3686 fontpattern = FcFontSetMatch(0, fcsets, 1,
3690 * Overwrite or create the new cache entry.
3692 if (frclen >= LEN(frc)) {
3693 frclen = LEN(frc) - 1;
3694 XftFontClose(xw.dpy, frc[frclen].font);
3695 frc[frclen].unicodep = 0;
3698 frc[frclen].font = XftFontOpenPattern(xw.dpy,
3700 frc[frclen].flags = frcflags;
3701 frc[frclen].unicodep = rune;
3703 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
3708 FcPatternDestroy(fcpattern);
3709 FcCharSetDestroy(fccharset);
3712 specs[numspecs].font = frc[f].font;
3713 specs[numspecs].glyph = glyphidx;
3714 specs[numspecs].x = (short)xp;
3715 specs[numspecs].y = (short)yp;
3724 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
3726 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
3727 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
3728 width = charlen * xw.cw;
3729 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
3730 XRenderColor colfg, colbg;
3733 /* Determine foreground and background colors based on mode. */
3734 if (base.fg == defaultfg) {
3735 if (base.mode & ATTR_ITALIC)
3736 base.fg = defaultitalic;
3737 else if ((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD))
3738 base.fg = defaultitalic;
3739 else if (base.mode & ATTR_UNDERLINE)
3740 base.fg = defaultunderline;
3743 if (IS_TRUECOL(base.fg)) {
3744 colfg.alpha = 0xffff;
3745 colfg.red = TRUERED(base.fg);
3746 colfg.green = TRUEGREEN(base.fg);
3747 colfg.blue = TRUEBLUE(base.fg);
3748 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
3751 fg = &dc.col[base.fg];
3754 if (IS_TRUECOL(base.bg)) {
3755 colbg.alpha = 0xffff;
3756 colbg.green = TRUEGREEN(base.bg);
3757 colbg.red = TRUERED(base.bg);
3758 colbg.blue = TRUEBLUE(base.bg);
3759 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
3762 bg = &dc.col[base.bg];
3765 /* Change basic system colors [0-7] to bright system colors [8-15] */
3766 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
3767 fg = &dc.col[base.fg + 8];
3769 if (IS_SET(MODE_REVERSE)) {
3770 if (fg == &dc.col[defaultfg]) {
3771 fg = &dc.col[defaultbg];
3773 colfg.red = ~fg->color.red;
3774 colfg.green = ~fg->color.green;
3775 colfg.blue = ~fg->color.blue;
3776 colfg.alpha = fg->color.alpha;
3777 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
3782 if (bg == &dc.col[defaultbg]) {
3783 bg = &dc.col[defaultfg];
3785 colbg.red = ~bg->color.red;
3786 colbg.green = ~bg->color.green;
3787 colbg.blue = ~bg->color.blue;
3788 colbg.alpha = bg->color.alpha;
3789 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
3795 if (base.mode & ATTR_REVERSE) {
3801 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
3802 colfg.red = fg->color.red / 2;
3803 colfg.green = fg->color.green / 2;
3804 colfg.blue = fg->color.blue / 2;
3805 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
3809 if (base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3812 if (base.mode & ATTR_INVISIBLE)
3815 /* Intelligent cleaning up of the borders. */
3817 xclear(0, (y == 0)? 0 : winy, borderpx,
3818 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3820 if (x + charlen >= term.col) {
3821 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3822 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3825 xclear(winx, 0, winx + width, borderpx);
3826 if (y == term.row-1)
3827 xclear(winx, winy + xw.ch, winx + width, xw.h);
3829 /* Clean up the region we want to draw to. */
3830 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3832 /* Set the clip region because Xft is sometimes dirty. */
3837 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3839 /* Render the glyphs. */
3840 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
3842 /* Render underline and strikethrough. */
3843 if (base.mode & ATTR_UNDERLINE) {
3844 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
3848 if (base.mode & ATTR_STRUCK) {
3849 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
3853 /* Reset clip to none. */
3854 XftDrawSetClip(xw.draw, 0);
3858 xdrawglyph(Glyph g, int x, int y)
3861 XftGlyphFontSpec spec;
3863 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
3864 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
3870 static int oldx = 0, oldy = 0;
3872 Glyph g = {' ', ATTR_NULL, defaultbg, defaultcs}, og;
3873 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
3876 LIMIT(oldx, 0, term.col-1);
3877 LIMIT(oldy, 0, term.row-1);
3881 /* adjust position if in dummy */
3882 if (term.line[oldy][oldx].mode & ATTR_WDUMMY)
3884 if (term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3887 /* remove the old cursor */
3888 og = term.line[oldy][oldx];
3889 if (ena_sel && selected(oldx, oldy))
3890 og.mode ^= ATTR_REVERSE;
3891 xdrawglyph(og, oldx, oldy);
3893 g.u = term.line[term.c.y][term.c.x].u;
3896 * Select the right color for the right mode.
3898 if (IS_SET(MODE_REVERSE)) {
3899 g.mode |= ATTR_REVERSE;
3901 if (ena_sel && selected(term.c.x, term.c.y)) {
3902 drawcol = dc.col[defaultcs];
3905 drawcol = dc.col[defaultrcs];
3909 if (ena_sel && selected(term.c.x, term.c.y)) {
3910 drawcol = dc.col[defaultrcs];
3914 drawcol = dc.col[defaultcs];
3918 if (IS_SET(MODE_HIDE))
3921 /* draw the new one */
3922 if (xw.state & WIN_FOCUSED) {
3923 switch (xw.cursor) {
3924 case 7: /* st extension: snowman */
3925 utf8decode("☃", &g.u, UTF_SIZ);
3926 case 0: /* Blinking Block */
3927 case 1: /* Blinking Block (Default) */
3928 case 2: /* Steady Block */
3929 g.mode |= term.line[term.c.y][curx].mode & ATTR_WIDE;
3930 xdrawglyph(g, term.c.x, term.c.y);
3932 case 3: /* Blinking Underline */
3933 case 4: /* Steady Underline */
3934 XftDrawRect(xw.draw, &drawcol,
3935 borderpx + curx * xw.cw,
3936 borderpx + (term.c.y + 1) * xw.ch - \
3938 xw.cw, cursorthickness);
3940 case 5: /* Blinking bar */
3941 case 6: /* Steady bar */
3942 XftDrawRect(xw.draw, &drawcol,
3943 borderpx + curx * xw.cw,
3944 borderpx + term.c.y * xw.ch,
3945 cursorthickness, xw.ch);
3949 XftDrawRect(xw.draw, &drawcol,
3950 borderpx + curx * xw.cw,
3951 borderpx + term.c.y * xw.ch,
3953 XftDrawRect(xw.draw, &drawcol,
3954 borderpx + curx * xw.cw,
3955 borderpx + term.c.y * xw.ch,
3957 XftDrawRect(xw.draw, &drawcol,
3958 borderpx + (curx + 1) * xw.cw - 1,
3959 borderpx + term.c.y * xw.ch,
3961 XftDrawRect(xw.draw, &drawcol,
3962 borderpx + curx * xw.cw,
3963 borderpx + (term.c.y + 1) * xw.ch - 1,
3966 oldx = curx, oldy = term.c.y;
3975 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3977 XSetWMName(xw.dpy, xw.win, &prop);
3978 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
3985 xsettitle(opt_title ? opt_title : "st");
3998 drawregion(0, 0, term.col, term.row);
3999 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
4001 XSetForeground(xw.dpy, dc.gc,
4002 dc.col[IS_SET(MODE_REVERSE)?
4003 defaultfg : defaultbg].pixel);
4007 drawregion(int x1, int y1, int x2, int y2)
4009 int i, x, y, ox, numspecs;
4011 XftGlyphFontSpec *specs;
4012 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
4014 if (!(xw.state & WIN_VISIBLE))
4017 for (y = y1; y < y2; y++) {
4023 specs = term.specbuf;
4024 numspecs = xmakeglyphfontspecs(specs, &term.line[y][x1], x2 - x1, x1, y);
4027 for (x = x1; x < x2 && i < numspecs; x++) {
4028 new = term.line[y][x];
4029 if (new.mode == ATTR_WDUMMY)
4031 if (ena_sel && selected(x, y))
4032 new.mode ^= ATTR_REVERSE;
4033 if (i > 0 && ATTRCMP(base, new)) {
4034 xdrawglyphfontspecs(specs, base, i, ox, y);
4046 xdrawglyphfontspecs(specs, base, i, ox, y);
4058 visibility(XEvent *ev)
4060 XVisibilityEvent *e = &ev->xvisibility;
4062 MODBIT(xw.state, e->state != VisibilityFullyObscured, WIN_VISIBLE);
4068 xw.state &= ~WIN_VISIBLE;
4072 xsetpointermotion(int set)
4074 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
4075 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
4079 xseturgency(int add)
4081 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
4083 MODBIT(h->flags, add, XUrgencyHint);
4084 XSetWMHints(xw.dpy, xw.win, h);
4091 XFocusChangeEvent *e = &ev->xfocus;
4093 if (e->mode == NotifyGrab)
4096 if (ev->type == FocusIn) {
4097 XSetICFocus(xw.xic);
4098 xw.state |= WIN_FOCUSED;
4100 if (IS_SET(MODE_FOCUS))
4101 ttywrite("\033[I", 3);
4103 XUnsetICFocus(xw.xic);
4104 xw.state &= ~WIN_FOCUSED;
4105 if (IS_SET(MODE_FOCUS))
4106 ttywrite("\033[O", 3);
4111 match(uint mask, uint state)
4113 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
4117 numlock(const Arg *dummy)
4123 kmap(KeySym k, uint state)
4128 /* Check for mapped keys out of X11 function keys. */
4129 for (i = 0; i < LEN(mappedkeys); i++) {
4130 if (mappedkeys[i] == k)
4133 if (i == LEN(mappedkeys)) {
4134 if ((k & 0xFFFF) < 0xFD00)
4138 for (kp = key; kp < key + LEN(key); kp++) {
4142 if (!match(kp->mask, state))
4145 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
4147 if (term.numlock && kp->appkey == 2)
4150 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
4153 if (IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
4165 XKeyEvent *e = &ev->xkey;
4167 char buf[32], *customkey;
4173 if (IS_SET(MODE_KBDLOCK))
4176 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
4178 for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
4179 if (ksym == bp->keysym && match(bp->mod, e->state)) {
4180 bp->func(&(bp->arg));
4185 /* 2. custom keys from config.h */
4186 if ((customkey = kmap(ksym, e->state))) {
4187 ttysend(customkey, strlen(customkey));
4191 /* 3. composed string from input method */
4194 if (len == 1 && e->state & Mod1Mask) {
4195 if (IS_SET(MODE_8BIT)) {
4198 len = utf8encode(c, buf);
4215 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
4217 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
4218 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
4219 xw.state |= WIN_FOCUSED;
4221 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
4222 xw.state &= ~WIN_FOCUSED;
4224 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
4225 /* Send SIGHUP to shell */
4232 cresize(int width, int height)
4241 col = (xw.w - 2 * borderpx) / xw.cw;
4242 row = (xw.h - 2 * borderpx) / xw.ch;
4251 if (e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
4254 cresize(e->xconfigure.width, e->xconfigure.height);
4262 int w = xw.w, h = xw.h;
4264 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
4265 struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
4268 /* Waiting for window mapping */
4270 XNextEvent(xw.dpy, &ev);
4272 * This XFilterEvent call is required because of XOpenIM. It
4273 * does filter out the key event and some client message for
4274 * the input method too.
4276 if (XFilterEvent(&ev, None))
4278 if (ev.type == ConfigureNotify) {
4279 w = ev.xconfigure.width;
4280 h = ev.xconfigure.height;
4282 } while (ev.type != MapNotify);
4288 clock_gettime(CLOCK_MONOTONIC, &last);
4291 for (xev = actionfps;;) {
4293 FD_SET(cmdfd, &rfd);
4296 if (pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
4299 die("select failed: %s\n", strerror(errno));
4301 if (FD_ISSET(cmdfd, &rfd)) {
4304 blinkset = tattrset(ATTR_BLINK);
4306 MODBIT(term.mode, 0, MODE_BLINK);
4310 if (FD_ISSET(xfd, &rfd))
4313 clock_gettime(CLOCK_MONOTONIC, &now);
4314 drawtimeout.tv_sec = 0;
4315 drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
4319 if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
4320 tsetdirtattr(ATTR_BLINK);
4321 term.mode ^= MODE_BLINK;
4325 deltatime = TIMEDIFF(now, last);
4326 if (deltatime > 1000 / (xev ? xfps : actionfps)) {
4332 while (XPending(xw.dpy)) {
4333 XNextEvent(xw.dpy, &ev);
4334 if (XFilterEvent(&ev, None))
4336 if (handler[ev.type])
4337 (handler[ev.type])(&ev);
4343 if (xev && !FD_ISSET(xfd, &rfd))
4345 if (!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
4347 if (TIMEDIFF(now, lastblink) \
4349 drawtimeout.tv_nsec = 1000;
4351 drawtimeout.tv_nsec = (1E6 * \
4356 drawtimeout.tv_sec = \
4357 drawtimeout.tv_nsec / 1E9;
4358 drawtimeout.tv_nsec %= (long)1E9;
4370 die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
4371 " [-n name] [-o file]\n"
4372 " [-T title] [-t title] [-w windowid]"
4373 " [[-e] command [args ...]]\n"
4374 " %s [-aiv] [-c class] [-f font] [-g geometry]"
4375 " [-n name] [-o file]\n"
4376 " [-T title] [-t title] [-w windowid] -l line"
4377 " [stty_args ...]\n", argv0, argv0);
4381 main(int argc, char *argv[])
4383 uint cols = 80, rows = 24;
4387 xw.cursor = cursorshape;
4394 opt_class = EARGF(usage());
4401 opt_font = EARGF(usage());
4404 xw.gm = XParseGeometry(EARGF(usage()),
4405 &xw.l, &xw.t, &cols, &rows);
4411 opt_io = EARGF(usage());
4414 opt_line = EARGF(usage());
4417 opt_name = EARGF(usage());
4421 opt_title = EARGF(usage());
4424 opt_embed = EARGF(usage());
4427 die("%s " VERSION " (c) 2010-2016 st engineers\n", argv0);
4435 /* eat all remaining arguments */
4437 if (!opt_title && !opt_line)
4438 opt_title = basename(xstrdup(argv[0]));
4440 setlocale(LC_CTYPE, "");
4441 XSetLocaleModifiers("");
4442 tnew(MAX(cols, 1), MAX(rows, 1));