1 /* See LICENSE for licence details. */
14 #include <sys/ioctl.h>
15 #include <sys/select.h>
18 #include <sys/types.h>
23 #include <X11/Xatom.h>
25 #include <X11/Xutil.h>
26 #include <X11/cursorfont.h>
27 #include <X11/keysym.h>
28 #include <X11/Xft/Xft.h>
29 #include <fontconfig/fontconfig.h>
38 #define Draw XftDraw *
39 #define Colour XftColor
40 #define Colourmap Colormap
41 #define Rectangle XRectangle
45 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
47 #elif defined(__FreeBSD__) || defined(__DragonFly__)
53 #define XEMBED_FOCUS_IN 4
54 #define XEMBED_FOCUS_OUT 5
58 #define ESC_BUF_SIZ (128*UTF_SIZ)
59 #define ESC_ARG_SIZ 16
60 #define STR_BUF_SIZ ESC_BUF_SIZ
61 #define STR_ARG_SIZ ESC_ARG_SIZ
62 #define DRAW_BUF_SIZ 20*1024
63 #define XK_ANY_MOD UINT_MAX
65 #define XK_SWITCH_MOD (1<<13)
67 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
70 #define SERRNO strerror(errno)
71 #define MIN(a, b) ((a) < (b) ? (a) : (b))
72 #define MAX(a, b) ((a) < (b) ? (b) : (a))
73 #define LEN(a) (sizeof(a) / sizeof(a[0]))
74 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
75 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
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 || (a).bg != (b).bg)
78 #define IS_SET(flag) ((term.mode & (flag)) != 0)
79 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
80 #define CEIL(x) (((x) != (int) (x)) ? (x) + 1 : (x))
82 #define TRUECOLOR(r,g,b) (1 << 24 | (r) << 16 | (g) << 8 | (b))
83 #define IS_TRUECOL(x) (1 << 24 & (x))
84 #define TRUERED(x) (((x) & 0xff0000) >> 8)
85 #define TRUEGREEN(x) (((x) & 0xff00))
86 #define TRUEBLUE(x) (((x) & 0xff) << 8)
89 #define VT102ID "\033[?6c"
91 enum glyph_attribute {
104 enum cursor_movement {
122 MODE_MOUSEMOTION = 64,
127 MODE_APPCURSOR = 2048,
128 MODE_MOUSESGR = 4096,
133 MODE_MOUSEX10 = 131072,
134 MODE_MOUSEMANY = 262144,
135 MODE_BRCKTPASTE = 524288,
136 MODE_MOUSE = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
153 ESC_STR = 4, /* DSC, OSC, PM, APC */
155 ESC_STR_END = 16, /* a final string was encountered */
156 ESC_TEST = 32, /* Enter in test mode */
165 enum selection_type {
170 enum selection_snap {
175 typedef unsigned char uchar;
176 typedef unsigned int uint;
177 typedef unsigned long ulong;
178 typedef unsigned short ushort;
181 char c[UTF_SIZ]; /* character code */
182 ushort mode; /* attribute flags */
183 ulong fg; /* foreground */
184 ulong bg; /* background */
190 Glyph attr; /* current char attributes */
196 /* CSI Escape sequence structs */
197 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
199 char buf[ESC_BUF_SIZ]; /* raw string */
200 int len; /* raw string length */
202 int arg[ESC_ARG_SIZ];
203 int narg; /* nb of args */
207 /* STR Escape sequence structs */
208 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
210 char type; /* ESC type ... */
211 char buf[STR_BUF_SIZ]; /* raw string */
212 int len; /* raw string length */
213 char *args[STR_ARG_SIZ];
214 int narg; /* nb of args */
217 /* Internal representation of the screen */
219 int row; /* nb row */
220 int col; /* nb col */
221 Line *line; /* screen */
222 Line *alt; /* alternate screen */
223 bool *dirty; /* dirtyness of lines */
224 TCursor c; /* cursor */
225 int top; /* top scroll limit */
226 int bot; /* bottom scroll limit */
227 int mode; /* terminal mode flags */
228 int esc; /* escape state flags */
229 char trantbl[4]; /* charset table translation */
230 int charset; /* current charset */
231 int icharset; /* selected charset for sequence */
232 bool numlock; /* lock numbers in keyboard */
236 /* Purely graphic info */
242 Atom xembed, wmdeletewin;
247 XSetWindowAttributes attrs;
249 bool isfixed; /* is fixed geometry? */
250 int fx, fy, fw, fh; /* fixed geometry */
251 int tw, th; /* tty width and height */
252 int w, h; /* window width and height */
253 int ch; /* char height */
254 int cw; /* char width */
255 char state; /* focus, redraw, visible */
268 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
269 signed char appkey; /* application keypad */
270 signed char appcursor; /* application cursor */
271 signed char crlf; /* crlf mode */
279 * Selection variables:
280 * nb – normalized coordinates of the beginning of the selection
281 * ne – normalized coordinates of the end of the selection
282 * ob – original coordinates of the beginning of the selection
283 * oe – original coordinates of the end of the selection
292 struct timeval tclick1;
293 struct timeval tclick2;
306 void (*func)(const Arg *);
310 /* function definitions used in config.h */
311 static void clippaste(const Arg *);
312 static void numlock(const Arg *);
313 static void selpaste(const Arg *);
314 static void xzoom(const Arg *);
316 /* Config.h for applying patches and the configuration. */
332 /* Drawing Context */
334 Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
335 Font font, bfont, ifont, ibfont;
339 static void die(const char *, ...);
340 static void draw(void);
341 static void redraw(int);
342 static void drawregion(int, int, int, int);
343 static void execsh(void);
344 static void sigchld(int);
345 static void run(void);
347 static void csidump(void);
348 static void csihandle(void);
349 static void csiparse(void);
350 static void csireset(void);
351 static void strdump(void);
352 static void strhandle(void);
353 static void strparse(void);
354 static void strreset(void);
356 static int tattrset(int);
357 static void tclearregion(int, int, int, int);
358 static void tcursor(int);
359 static void tdeletechar(int);
360 static void tdeleteline(int);
361 static void tinsertblank(int);
362 static void tinsertblankline(int);
363 static void tmoveto(int, int);
364 static void tmoveato(int x, int y);
365 static void tnew(int, int);
366 static void tnewline(int);
367 static void tputtab(bool);
368 static void tputc(char *, int);
369 static void treset(void);
370 static int tresize(int, int);
371 static void tscrollup(int, int);
372 static void tscrolldown(int, int);
373 static void tsetattr(int*, int);
374 static void tsetchar(char *, Glyph *, int, int);
375 static void tsetscroll(int, int);
376 static void tswapscreen(void);
377 static void tsetdirt(int, int);
378 static void tsetdirtattr(int);
379 static void tsetmode(bool, bool, int *, int);
380 static void tfulldirt(void);
381 static void techo(char *, int);
382 static long tdefcolor(int *, int *, int);
383 static void tselcs(void);
384 static void tdeftran(char);
385 static inline bool match(uint, uint);
386 static void ttynew(void);
387 static void ttyread(void);
388 static void ttyresize(void);
389 static void ttywrite(const char *, size_t);
391 static void xdraws(char *, Glyph, int, int, int, int);
392 static void xhints(void);
393 static void xclear(int, int, int, int);
394 static void xdrawcursor(void);
395 static void xinit(void);
396 static void xloadcols(void);
397 static int xsetcolorname(int, const char *);
398 static int xloadfont(Font *, FcPattern *);
399 static void xloadfonts(char *, int);
400 static int xloadfontset(Font *);
401 static void xsettitle(char *);
402 static void xresettitle(void);
403 static void xsetpointermotion(int);
404 static void xseturgency(int);
405 static void xsetsel(char*);
406 static void xtermclear(int, int, int, int);
407 static void xunloadfont(Font *f);
408 static void xunloadfonts(void);
409 static void xresize(int, int);
411 static void expose(XEvent *);
412 static void visibility(XEvent *);
413 static void unmap(XEvent *);
414 static char *kmap(KeySym, uint);
415 static void kpress(XEvent *);
416 static void cmessage(XEvent *);
417 static void cresize(int, int);
418 static void resize(XEvent *);
419 static void focus(XEvent *);
420 static void brelease(XEvent *);
421 static void bpress(XEvent *);
422 static void bmotion(XEvent *);
423 static void selnotify(XEvent *);
424 static void selclear(XEvent *);
425 static void selrequest(XEvent *);
427 static void selinit(void);
428 static void selsort(void);
429 static inline bool selected(int, int);
430 static void selcopy(void);
431 static void selscroll(int, int);
432 static void selsnap(int, int *, int *, int);
434 static int utf8decode(char *, long *);
435 static int utf8encode(long *, char *);
436 static int utf8size(char *);
437 static int isfullutf8(char *, int);
439 static ssize_t xwrite(int, char *, size_t);
440 static void *xmalloc(size_t);
441 static void *xrealloc(void *, size_t);
443 static void (*handler[LASTEvent])(XEvent *) = {
445 [ClientMessage] = cmessage,
446 [ConfigureNotify] = resize,
447 [VisibilityNotify] = visibility,
448 [UnmapNotify] = unmap,
452 [MotionNotify] = bmotion,
453 [ButtonPress] = bpress,
454 [ButtonRelease] = brelease,
455 [SelectionClear] = selclear,
456 [SelectionNotify] = selnotify,
457 [SelectionRequest] = selrequest,
464 static CSIEscape csiescseq;
465 static STREscape strescseq;
468 static Selection sel;
469 static int iofd = -1;
470 static char **opt_cmd = NULL;
471 static char *opt_io = NULL;
472 static char *opt_title = NULL;
473 static char *opt_embed = NULL;
474 static char *opt_class = NULL;
475 static char *opt_font = NULL;
476 static int oldbutton = 3; /* button event on startup: 3 = release */
478 static char *usedfont = NULL;
479 static int usedfontsize = 0;
481 /* Font Ring Cache */
494 /* Fontcache is an array now. A new font will be appended to the array. */
495 static Fontcache frc[16];
496 static int frclen = 0;
499 xwrite(int fd, char *s, size_t len) {
503 ssize_t r = write(fd, s, len);
513 xmalloc(size_t len) {
514 void *p = malloc(len);
517 die("Out of memory\n");
523 xrealloc(void *p, size_t len) {
524 if((p = realloc(p, len)) == NULL)
525 die("Out of memory\n");
531 utf8decode(char *s, long *u) {
537 if(~c & 0x80) { /* 0xxxxxxx */
540 } else if((c & 0xE0) == 0xC0) { /* 110xxxxx */
543 } else if((c & 0xF0) == 0xE0) { /* 1110xxxx */
546 } else if((c & 0xF8) == 0xF0) { /* 11110xxx */
553 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
555 if((c & 0xC0) != 0x80) /* 10xxxxxx */
561 if((n == 1 && *u < 0x80) ||
562 (n == 2 && *u < 0x800) ||
563 (n == 3 && *u < 0x10000) ||
564 (*u >= 0xD800 && *u <= 0xDFFF)) {
576 utf8encode(long *u, char *s) {
584 *sp = uc; /* 0xxxxxxx */
586 } else if(*u < 0x800) {
587 *sp = (uc >> 6) | 0xC0; /* 110xxxxx */
589 } else if(uc < 0x10000) {
590 *sp = (uc >> 12) | 0xE0; /* 1110xxxx */
592 } else if(uc <= 0x10FFFF) {
593 *sp = (uc >> 18) | 0xF0; /* 11110xxx */
599 for(i=n,++sp; i>0; --i,++sp)
600 *sp = ((uc >> 6*(i-1)) & 0x3F) | 0x80; /* 10xxxxxx */
612 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
613 UTF-8 otherwise return 0 */
615 isfullutf8(char *s, int b) {
623 } else if((*c1 & 0xE0) == 0xC0 && b == 1) {
625 } else if((*c1 & 0xF0) == 0xE0 &&
627 ((b == 2) && (*c2 & 0xC0) == 0x80))) {
629 } else if((*c1 & 0xF8) == 0xF0 &&
631 ((b == 2) && (*c2 & 0xC0) == 0x80) ||
632 ((b == 3) && (*c2 & 0xC0) == 0x80 && (*c3 & 0xC0) == 0x80))) {
645 } else if((c & 0xE0) == 0xC0) {
647 } else if((c & 0xF0) == 0xE0) {
656 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
657 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
661 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
662 if(sel.xtarget == None)
663 sel.xtarget = XA_STRING;
671 return LIMIT(x, 0, term.col-1);
679 return LIMIT(y, 0, term.row-1);
684 if(sel.ob.y == sel.oe.y) {
685 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
686 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
688 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
689 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
691 sel.nb.y = MIN(sel.ob.y, sel.oe.y);
692 sel.ne.y = MAX(sel.ob.y, sel.oe.y);
696 selected(int x, int y) {
697 if(sel.ne.y == y && sel.nb.y == y)
698 return BETWEEN(x, sel.nb.x, sel.ne.x);
700 if(sel.type == SEL_RECTANGULAR) {
701 return ((sel.nb.y <= y && y <= sel.ne.y)
702 && (sel.nb.x <= x && x <= sel.ne.x));
705 return ((sel.nb.y < y && y < sel.ne.y)
706 || (y == sel.ne.y && x <= sel.ne.x))
707 || (y == sel.nb.y && x >= sel.nb.x
708 && (x <= sel.ne.x || sel.nb.y != sel.ne.y));
712 selsnap(int mode, int *x, int *y, int direction) {
718 * Snap around if the word wraps around at the end or
719 * beginning of a line.
722 if(direction < 0 && *x <= 0) {
723 if(*y > 0 && term.line[*y - 1][term.col-1].mode
731 if(direction > 0 && *x >= term.col-1) {
732 if(*y < term.row-1 && term.line[*y][*x].mode
741 if(term.line[*y][*x+direction].mode & ATTR_WDUMMY) {
746 if(strchr(worddelimiters,
747 term.line[*y][*x+direction].c[0])) {
756 * Snap around if the the previous line or the current one
757 * has set ATTR_WRAP at its end. Then the whole next or
758 * previous line will be selected.
760 *x = (direction < 0) ? 0 : term.col - 1;
761 if(direction < 0 && *y > 0) {
762 for(; *y > 0; *y += direction) {
763 if(!(term.line[*y-1][term.col-1].mode
768 } else if(direction > 0 && *y < term.row-1) {
769 for(; *y < term.row; *y += direction) {
770 if(!(term.line[*y][term.col-1].mode
779 * Select the whole line when the end of line is reached.
783 while(--i > 0 && term.line[*y][i].c[0] == ' ')
793 getbuttoninfo(XEvent *e) {
795 uint state = e->xbutton.state &~Button1Mask;
797 sel.alt = IS_SET(MODE_ALTSCREEN);
799 sel.oe.x = x2col(e->xbutton.x);
800 sel.oe.y = y2row(e->xbutton.y);
802 if(sel.ob.y < sel.oe.y
803 || (sel.ob.y == sel.oe.y && sel.ob.x < sel.oe.x)) {
804 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
805 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
807 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, -1);
808 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, +1);
812 sel.type = SEL_REGULAR;
813 for(type = 1; type < LEN(selmasks); ++type) {
814 if(match(selmasks[type], state)) {
822 mousereport(XEvent *e) {
823 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
824 button = e->xbutton.button, state = e->xbutton.state,
830 if(e->xbutton.type == MotionNotify) {
831 if(x == ox && y == oy)
833 if(!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
835 /* MOUSE_MOTION: no reporting if no button is pressed */
836 if(IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
839 button = oldbutton + 32;
843 if(!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
850 if(e->xbutton.type == ButtonPress) {
854 } else if(e->xbutton.type == ButtonRelease) {
856 /* MODE_MOUSEX10: no button release reporting */
857 if(IS_SET(MODE_MOUSEX10))
862 if(!IS_SET(MODE_MOUSEX10)) {
863 button += (state & ShiftMask ? 4 : 0)
864 + (state & Mod4Mask ? 8 : 0)
865 + (state & ControlMask ? 16 : 0);
869 if(IS_SET(MODE_MOUSESGR)) {
870 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
872 e->xbutton.type == ButtonRelease ? 'm' : 'M');
873 } else if(x < 223 && y < 223) {
874 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
875 32+button, 32+x+1, 32+y+1);
888 if(IS_SET(MODE_MOUSE)) {
893 for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
894 if(e->xbutton.button == mk->b
895 && match(mk->mask, e->xbutton.state)) {
896 ttywrite(mk->s, strlen(mk->s));
897 if(IS_SET(MODE_ECHO))
898 techo(mk->s, strlen(mk->s));
903 if(e->xbutton.button == Button1) {
904 gettimeofday(&now, NULL);
906 /* Clear previous selection, logically and visually. */
909 sel.type = SEL_REGULAR;
910 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
911 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
914 * If the user clicks below predefined timeouts specific
915 * snapping behaviour is exposed.
917 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
918 sel.snap = SNAP_LINE;
919 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
920 sel.snap = SNAP_WORD;
924 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
925 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
929 * Draw selection, unless it's regular and we don't want to
930 * make clicks visible
934 tsetdirt(sel.nb.y, sel.ne.y);
936 sel.tclick2 = sel.tclick1;
944 int x, y, bufsize, size, i, ex;
950 bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
951 ptr = str = xmalloc(bufsize);
953 /* append every set & selected glyph to the selection */
954 for(y = sel.nb.y; y < sel.ne.y + 1; y++) {
955 gp = &term.line[y][0];
956 last = gp + term.col;
958 while(--last >= gp && !(selected(last - gp, y) && \
959 strcmp(last->c, " ") != 0))
962 for(x = 0; gp <= last; x++, ++gp) {
963 if(!selected(x, y) || (gp->mode & ATTR_WDUMMY))
966 size = utf8size(gp->c);
967 memcpy(ptr, gp->c, size);
972 * Copy and pasting of line endings is inconsistent
973 * in the inconsistent terminal and GUI world.
974 * The best solution seems like to produce '\n' when
975 * something is copied from st and convert '\n' to
976 * '\r', when something to be pasted is received by
978 * FIXME: Fix the computer world.
980 if(y < sel.ne.y && x > 0 && !((gp-1)->mode & ATTR_WRAP))
984 * If the last selected line expands in the selection
985 * after the visible text '\n' is appended.
989 while(--i > 0 && term.line[y][i].c[0] == ' ')
992 if(sel.nb.y == sel.ne.y && sel.ne.x < sel.nb.x)
1004 selnotify(XEvent *e) {
1005 ulong nitems, ofs, rem;
1007 uchar *data, *last, *repl;
1012 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
1013 False, AnyPropertyType, &type, &format,
1014 &nitems, &rem, &data)) {
1015 fprintf(stderr, "Clipboard allocation failed\n");
1020 * As seen in selcopy:
1021 * Line endings are inconsistent in the terminal and GUI world
1022 * copy and pasting. When receiving some selection data,
1023 * replace all '\n' with '\r'.
1024 * FIXME: Fix the computer world.
1027 last = data + nitems * format / 8;
1028 while((repl = memchr(repl, '\n', last - repl))) {
1032 if(IS_SET(MODE_BRCKTPASTE))
1033 ttywrite("\033[200~", 6);
1034 ttywrite((const char *)data, nitems * format / 8);
1035 if(IS_SET(MODE_BRCKTPASTE))
1036 ttywrite("\033[201~", 6);
1038 /* number of 32-bit chunks returned */
1039 ofs += nitems * format / 32;
1044 selpaste(const Arg *dummy) {
1045 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1046 xw.win, CurrentTime);
1050 clippaste(const Arg *dummy) {
1053 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1054 XConvertSelection(xw.dpy, clipboard, sel.xtarget, XA_PRIMARY,
1055 xw.win, CurrentTime);
1059 selclear(XEvent *e) {
1063 tsetdirt(sel.nb.y, sel.ne.y);
1067 selrequest(XEvent *e) {
1068 XSelectionRequestEvent *xsre;
1069 XSelectionEvent xev;
1070 Atom xa_targets, string;
1072 xsre = (XSelectionRequestEvent *) e;
1073 xev.type = SelectionNotify;
1074 xev.requestor = xsre->requestor;
1075 xev.selection = xsre->selection;
1076 xev.target = xsre->target;
1077 xev.time = xsre->time;
1079 xev.property = None;
1081 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1082 if(xsre->target == xa_targets) {
1083 /* respond with the supported type */
1084 string = sel.xtarget;
1085 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1086 XA_ATOM, 32, PropModeReplace,
1087 (uchar *) &string, 1);
1088 xev.property = xsre->property;
1089 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
1090 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1091 xsre->target, 8, PropModeReplace,
1092 (uchar *) sel.clip, strlen(sel.clip));
1093 xev.property = xsre->property;
1096 /* all done, send a notification to the listener */
1097 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
1098 fprintf(stderr, "Error sending SelectionNotify event\n");
1102 xsetsel(char *str) {
1103 /* register the selection for both the clipboard and the primary */
1109 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
1111 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1112 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1116 brelease(XEvent *e) {
1117 if(IS_SET(MODE_MOUSE)) {
1122 if(e->xbutton.button == Button2) {
1124 } else if(e->xbutton.button == Button1) {
1132 tsetdirt(sel.nb.y, sel.ne.y);
1137 bmotion(XEvent *e) {
1138 int oldey, oldex, oldsby, oldsey;
1140 if(IS_SET(MODE_MOUSE)) {
1155 if(oldey != sel.oe.y || oldex != sel.oe.x)
1156 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1160 die(const char *errstr, ...) {
1163 va_start(ap, errstr);
1164 vfprintf(stderr, errstr, ap);
1172 char *envshell = getenv("SHELL");
1173 const struct passwd *pass = getpwuid(getuid());
1174 char buf[sizeof(long) * 8 + 1];
1176 unsetenv("COLUMNS");
1178 unsetenv("TERMCAP");
1181 setenv("LOGNAME", pass->pw_name, 1);
1182 setenv("USER", pass->pw_name, 1);
1183 setenv("SHELL", pass->pw_shell, 0);
1184 setenv("HOME", pass->pw_dir, 0);
1187 snprintf(buf, sizeof(buf), "%lu", xw.win);
1188 setenv("WINDOWID", buf, 1);
1190 signal(SIGCHLD, SIG_DFL);
1191 signal(SIGHUP, SIG_DFL);
1192 signal(SIGINT, SIG_DFL);
1193 signal(SIGQUIT, SIG_DFL);
1194 signal(SIGTERM, SIG_DFL);
1195 signal(SIGALRM, SIG_DFL);
1197 DEFAULT(envshell, shell);
1198 setenv("TERM", termname, 1);
1199 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
1200 execvp(args[0], args);
1208 if(waitpid(pid, &stat, 0) < 0)
1209 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
1211 if(WIFEXITED(stat)) {
1212 exit(WEXITSTATUS(stat));
1221 struct winsize w = {term.row, term.col, 0, 0};
1223 /* seems to work fine on linux, openbsd and freebsd */
1224 if(openpty(&m, &s, NULL, NULL, &w) < 0)
1225 die("openpty failed: %s\n", SERRNO);
1227 switch(pid = fork()) {
1229 die("fork failed\n");
1232 setsid(); /* create a new process group */
1233 dup2(s, STDIN_FILENO);
1234 dup2(s, STDOUT_FILENO);
1235 dup2(s, STDERR_FILENO);
1236 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1237 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
1245 signal(SIGCHLD, sigchld);
1247 iofd = (!strcmp(opt_io, "-")) ?
1249 open(opt_io, O_WRONLY | O_CREAT, 0666);
1251 fprintf(stderr, "Error opening %s:%s\n",
1252 opt_io, strerror(errno));
1262 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1264 fprintf(stderr, "\n");
1269 static char buf[BUFSIZ];
1270 static int buflen = 0;
1273 int charsize; /* size of utf8 char in bytes */
1277 /* append read bytes to unprocessed bytes */
1278 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1279 die("Couldn't read from shell: %s\n", SERRNO);
1281 /* process every complete utf8 char */
1284 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1285 charsize = utf8decode(ptr, &utf8c);
1286 utf8encode(&utf8c, s);
1292 /* keep any uncomplete utf8 char for the next call */
1293 memmove(buf, ptr, buflen);
1297 ttywrite(const char *s, size_t n) {
1298 if(write(cmdfd, s, n) == -1)
1299 die("write error on tty: %s\n", SERRNO);
1306 w.ws_row = term.row;
1307 w.ws_col = term.col;
1308 w.ws_xpixel = xw.tw;
1309 w.ws_ypixel = xw.th;
1310 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1311 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1315 tattrset(int attr) {
1318 for(i = 0; i < term.row-1; i++) {
1319 for(j = 0; j < term.col-1; j++) {
1320 if(term.line[i][j].mode & attr)
1329 tsetdirt(int top, int bot) {
1332 LIMIT(top, 0, term.row-1);
1333 LIMIT(bot, 0, term.row-1);
1335 for(i = top; i <= bot; i++)
1340 tsetdirtattr(int attr) {
1343 for(i = 0; i < term.row-1; i++) {
1344 for(j = 0; j < term.col-1; j++) {
1345 if(term.line[i][j].mode & attr) {
1355 tsetdirt(0, term.row-1);
1360 static TCursor c[2];
1361 bool alt = IS_SET(MODE_ALTSCREEN);
1363 if(mode == CURSOR_SAVE) {
1365 } else if(mode == CURSOR_LOAD) {
1367 tmoveto(c[alt].x, c[alt].y);
1375 term.c = (TCursor){{
1379 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1381 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1382 for(i = tabspaces; i < term.col; i += tabspaces)
1385 term.bot = term.row - 1;
1386 term.mode = MODE_WRAP;
1387 memset(term.trantbl, sizeof(term.trantbl), CS_USA);
1390 tclearregion(0, 0, term.col-1, term.row-1);
1392 tcursor(CURSOR_SAVE);
1396 tnew(int col, int row) {
1397 term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
1406 Line *tmp = term.line;
1408 term.line = term.alt;
1410 term.mode ^= MODE_ALTSCREEN;
1415 tscrolldown(int orig, int n) {
1419 LIMIT(n, 0, term.bot-orig+1);
1421 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1423 for(i = term.bot; i >= orig+n; i--) {
1424 temp = term.line[i];
1425 term.line[i] = term.line[i-n];
1426 term.line[i-n] = temp;
1429 term.dirty[i-n] = 1;
1436 tscrollup(int orig, int n) {
1439 LIMIT(n, 0, term.bot-orig+1);
1441 tclearregion(0, orig, term.col-1, orig+n-1);
1443 for(i = orig; i <= term.bot-n; i++) {
1444 temp = term.line[i];
1445 term.line[i] = term.line[i+n];
1446 term.line[i+n] = temp;
1449 term.dirty[i+n] = 1;
1452 selscroll(orig, -n);
1456 selscroll(int orig, int n) {
1460 if(BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1461 if((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1465 if(sel.type == SEL_RECTANGULAR) {
1466 if(sel.ob.y < term.top)
1467 sel.ob.y = term.top;
1468 if(sel.oe.y > term.bot)
1469 sel.oe.y = term.bot;
1471 if(sel.ob.y < term.top) {
1472 sel.ob.y = term.top;
1475 if(sel.oe.y > term.bot) {
1476 sel.oe.y = term.bot;
1477 sel.oe.x = term.col;
1485 tnewline(int first_col) {
1489 tscrollup(term.top, 1);
1493 tmoveto(first_col ? 0 : term.c.x, y);
1498 char *p = csiescseq.buf, *np;
1507 csiescseq.buf[csiescseq.len] = '\0';
1508 while(p < csiescseq.buf+csiescseq.len) {
1510 v = strtol(p, &np, 10);
1513 if(v == LONG_MAX || v == LONG_MIN)
1515 csiescseq.arg[csiescseq.narg++] = v;
1517 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1521 csiescseq.mode = *p;
1524 /* for absolute user moves, when decom is set */
1526 tmoveato(int x, int y) {
1527 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1531 tmoveto(int x, int y) {
1534 if(term.c.state & CURSOR_ORIGIN) {
1539 maxy = term.row - 1;
1541 LIMIT(x, 0, term.col-1);
1542 LIMIT(y, miny, maxy);
1543 term.c.state &= ~CURSOR_WRAPNEXT;
1549 tsetchar(char *c, Glyph *attr, int x, int y) {
1550 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1551 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1552 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1553 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1554 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1555 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1556 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1557 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1558 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1562 * The table is proudly stolen from rxvt.
1564 if(attr->mode & ATTR_GFX) {
1565 if(c[0] >= 0x41 && c[0] <= 0x7e
1566 && vt100_0[c[0] - 0x41]) {
1567 c = vt100_0[c[0] - 0x41];
1571 if(term.line[y][x].mode & ATTR_WIDE) {
1572 if(x+1 < term.col) {
1573 term.line[y][x+1].c[0] = ' ';
1574 term.line[y][x+1].mode &= ~ATTR_WDUMMY;
1576 } else if(term.line[y][x].mode & ATTR_WDUMMY) {
1577 term.line[y][x-1].c[0] = ' ';
1578 term.line[y][x-1].mode &= ~ATTR_WIDE;
1582 term.line[y][x] = *attr;
1583 memcpy(term.line[y][x].c, c, UTF_SIZ);
1587 tclearregion(int x1, int y1, int x2, int y2) {
1591 temp = x1, x1 = x2, x2 = temp;
1593 temp = y1, y1 = y2, y2 = temp;
1595 LIMIT(x1, 0, term.col-1);
1596 LIMIT(x2, 0, term.col-1);
1597 LIMIT(y1, 0, term.row-1);
1598 LIMIT(y2, 0, term.row-1);
1600 for(y = y1; y <= y2; y++) {
1602 for(x = x1; x <= x2; x++) {
1605 term.line[y][x] = term.c.attr;
1606 memcpy(term.line[y][x].c, " ", 2);
1612 tdeletechar(int n) {
1613 int src = term.c.x + n;
1615 int size = term.col - src;
1617 term.dirty[term.c.y] = 1;
1619 if(src >= term.col) {
1620 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1624 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1625 size * sizeof(Glyph));
1626 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1630 tinsertblank(int n) {
1633 int size = term.col - dst;
1635 term.dirty[term.c.y] = 1;
1637 if(dst >= term.col) {
1638 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1642 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1643 size * sizeof(Glyph));
1644 tclearregion(src, term.c.y, dst - 1, term.c.y);
1648 tinsertblankline(int n) {
1649 if(term.c.y < term.top || term.c.y > term.bot)
1652 tscrolldown(term.c.y, n);
1656 tdeleteline(int n) {
1657 if(term.c.y < term.top || term.c.y > term.bot)
1660 tscrollup(term.c.y, n);
1664 tdefcolor(int *attr, int *npar, int l) {
1668 switch (attr[*npar + 1]) {
1669 case 2: /* direct colour in RGB space */
1670 if (*npar + 4 >= l) {
1672 "erresc(38): Incorrect number of parameters (%d)\n",
1676 r = attr[*npar + 2];
1677 g = attr[*npar + 3];
1678 b = attr[*npar + 4];
1680 if(!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1681 fprintf(stderr, "erresc: bad rgb color (%d,%d,%d)\n",
1684 idx = TRUECOLOR(r, g, b);
1686 case 5: /* indexed colour */
1687 if (*npar + 2 >= l) {
1689 "erresc(38): Incorrect number of parameters (%d)\n",
1694 if(!BETWEEN(attr[*npar], 0, 255))
1695 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
1699 case 0: /* implemented defined (only foreground) */
1700 case 1: /* transparent */
1701 case 3: /* direct colour in CMY space */
1702 case 4: /* direct colour in CMYK space */
1705 "erresc(38): gfx attr %d unknown\n", attr[*npar]);
1712 tsetattr(int *attr, int l) {
1716 for(i = 0; i < l; i++) {
1719 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE \
1720 | ATTR_BOLD | ATTR_ITALIC \
1722 term.c.attr.fg = defaultfg;
1723 term.c.attr.bg = defaultbg;
1726 term.c.attr.mode |= ATTR_BOLD;
1729 term.c.attr.mode |= ATTR_ITALIC;
1732 term.c.attr.mode |= ATTR_UNDERLINE;
1734 case 5: /* slow blink */
1735 case 6: /* rapid blink */
1736 term.c.attr.mode |= ATTR_BLINK;
1739 term.c.attr.mode |= ATTR_REVERSE;
1743 term.c.attr.mode &= ~ATTR_BOLD;
1746 term.c.attr.mode &= ~ATTR_ITALIC;
1749 term.c.attr.mode &= ~ATTR_UNDERLINE;
1753 term.c.attr.mode &= ~ATTR_BLINK;
1756 term.c.attr.mode &= ~ATTR_REVERSE;
1759 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1760 term.c.attr.fg = idx;
1763 term.c.attr.fg = defaultfg;
1766 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1767 term.c.attr.bg = idx;
1770 term.c.attr.bg = defaultbg;
1773 if(BETWEEN(attr[i], 30, 37)) {
1774 term.c.attr.fg = attr[i] - 30;
1775 } else if(BETWEEN(attr[i], 40, 47)) {
1776 term.c.attr.bg = attr[i] - 40;
1777 } else if(BETWEEN(attr[i], 90, 97)) {
1778 term.c.attr.fg = attr[i] - 90 + 8;
1779 } else if(BETWEEN(attr[i], 100, 107)) {
1780 term.c.attr.bg = attr[i] - 100 + 8;
1783 "erresc(default): gfx attr %d unknown\n",
1784 attr[i]), csidump();
1792 tsetscroll(int t, int b) {
1795 LIMIT(t, 0, term.row-1);
1796 LIMIT(b, 0, term.row-1);
1806 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1809 tsetmode(bool priv, bool set, int *args, int narg) {
1813 for(lim = args + narg; args < lim; ++args) {
1817 case 1: /* DECCKM -- Cursor key */
1818 MODBIT(term.mode, set, MODE_APPCURSOR);
1820 case 5: /* DECSCNM -- Reverse video */
1822 MODBIT(term.mode, set, MODE_REVERSE);
1823 if(mode != term.mode)
1824 redraw(REDRAW_TIMEOUT);
1826 case 6: /* DECOM -- Origin */
1827 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1830 case 7: /* DECAWM -- Auto wrap */
1831 MODBIT(term.mode, set, MODE_WRAP);
1833 case 0: /* Error (IGNORED) */
1834 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1835 case 3: /* DECCOLM -- Column (IGNORED) */
1836 case 4: /* DECSCLM -- Scroll (IGNORED) */
1837 case 8: /* DECARM -- Auto repeat (IGNORED) */
1838 case 18: /* DECPFF -- Printer feed (IGNORED) */
1839 case 19: /* DECPEX -- Printer extent (IGNORED) */
1840 case 42: /* DECNRCM -- National characters (IGNORED) */
1841 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1843 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1844 MODBIT(term.mode, !set, MODE_HIDE);
1846 case 9: /* X10 mouse compatibility mode */
1847 xsetpointermotion(0);
1848 MODBIT(term.mode, 0, MODE_MOUSE);
1849 MODBIT(term.mode, set, MODE_MOUSEX10);
1851 case 1000: /* 1000: report button press */
1852 xsetpointermotion(0);
1853 MODBIT(term.mode, 0, MODE_MOUSE);
1854 MODBIT(term.mode, set, MODE_MOUSEBTN);
1856 case 1002: /* 1002: report motion on button press */
1857 xsetpointermotion(0);
1858 MODBIT(term.mode, 0, MODE_MOUSE);
1859 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1861 case 1003: /* 1003: enable all mouse motions */
1862 xsetpointermotion(set);
1863 MODBIT(term.mode, 0, MODE_MOUSE);
1864 MODBIT(term.mode, set, MODE_MOUSEMANY);
1866 case 1004: /* 1004: send focus events to tty */
1867 MODBIT(term.mode, set, MODE_FOCUS);
1869 case 1006: /* 1006: extended reporting mode */
1870 MODBIT(term.mode, set, MODE_MOUSESGR);
1873 MODBIT(term.mode, set, MODE_8BIT);
1875 case 1049: /* swap screen & set/restore cursor as xterm */
1876 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1877 case 47: /* swap screen */
1879 if (!allowaltscreen)
1881 alt = IS_SET(MODE_ALTSCREEN);
1883 tclearregion(0, 0, term.col-1,
1886 if(set ^ alt) /* set is always 1 or 0 */
1892 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1894 case 2004: /* 2004: bracketed paste mode */
1895 MODBIT(term.mode, set, MODE_BRCKTPASTE);
1897 /* Not implemented mouse modes. See comments there. */
1898 case 1001: /* mouse highlight mode; can hang the
1899 terminal by design when implemented. */
1900 case 1005: /* UTF-8 mouse mode; will confuse
1901 applications not supporting UTF-8
1903 case 1015: /* urxvt mangled mouse mode; incompatible
1904 and can be mistaken for other control
1908 "erresc: unknown private set/reset mode %d\n",
1914 case 0: /* Error (IGNORED) */
1916 case 2: /* KAM -- keyboard action */
1917 MODBIT(term.mode, set, MODE_KBDLOCK);
1919 case 4: /* IRM -- Insertion-replacement */
1920 MODBIT(term.mode, set, MODE_INSERT);
1922 case 12: /* SRM -- Send/Receive */
1923 MODBIT(term.mode, !set, MODE_ECHO);
1925 case 20: /* LNM -- Linefeed/new line */
1926 MODBIT(term.mode, set, MODE_CRLF);
1930 "erresc: unknown set/reset mode %d\n",
1943 switch(csiescseq.mode) {
1946 fprintf(stderr, "erresc: unknown csi ");
1950 case '@': /* ICH -- Insert <n> blank char */
1951 DEFAULT(csiescseq.arg[0], 1);
1952 tinsertblank(csiescseq.arg[0]);
1954 case 'A': /* CUU -- Cursor <n> Up */
1955 DEFAULT(csiescseq.arg[0], 1);
1956 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1958 case 'B': /* CUD -- Cursor <n> Down */
1959 case 'e': /* VPR --Cursor <n> Down */
1960 DEFAULT(csiescseq.arg[0], 1);
1961 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1963 case 'c': /* DA -- Device Attributes */
1964 if(csiescseq.arg[0] == 0)
1965 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1967 case 'C': /* CUF -- Cursor <n> Forward */
1968 case 'a': /* HPR -- Cursor <n> Forward */
1969 DEFAULT(csiescseq.arg[0], 1);
1970 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1972 case 'D': /* CUB -- Cursor <n> Backward */
1973 DEFAULT(csiescseq.arg[0], 1);
1974 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1976 case 'E': /* CNL -- Cursor <n> Down and first col */
1977 DEFAULT(csiescseq.arg[0], 1);
1978 tmoveto(0, term.c.y+csiescseq.arg[0]);
1980 case 'F': /* CPL -- Cursor <n> Up and first col */
1981 DEFAULT(csiescseq.arg[0], 1);
1982 tmoveto(0, term.c.y-csiescseq.arg[0]);
1984 case 'g': /* TBC -- Tabulation clear */
1985 switch(csiescseq.arg[0]) {
1986 case 0: /* clear current tab stop */
1987 term.tabs[term.c.x] = 0;
1989 case 3: /* clear all the tabs */
1990 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1996 case 'G': /* CHA -- Move to <col> */
1998 DEFAULT(csiescseq.arg[0], 1);
1999 tmoveto(csiescseq.arg[0]-1, term.c.y);
2001 case 'H': /* CUP -- Move to <row> <col> */
2003 DEFAULT(csiescseq.arg[0], 1);
2004 DEFAULT(csiescseq.arg[1], 1);
2005 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
2007 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
2008 DEFAULT(csiescseq.arg[0], 1);
2009 while(csiescseq.arg[0]--)
2012 case 'J': /* ED -- Clear screen */
2014 switch(csiescseq.arg[0]) {
2016 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
2017 if(term.c.y < term.row-1) {
2018 tclearregion(0, term.c.y+1, term.col-1,
2024 tclearregion(0, 0, term.col-1, term.c.y-1);
2025 tclearregion(0, term.c.y, term.c.x, term.c.y);
2028 tclearregion(0, 0, term.col-1, term.row-1);
2034 case 'K': /* EL -- Clear line */
2035 switch(csiescseq.arg[0]) {
2037 tclearregion(term.c.x, term.c.y, term.col-1,
2041 tclearregion(0, term.c.y, term.c.x, term.c.y);
2044 tclearregion(0, term.c.y, term.col-1, term.c.y);
2048 case 'S': /* SU -- Scroll <n> line up */
2049 DEFAULT(csiescseq.arg[0], 1);
2050 tscrollup(term.top, csiescseq.arg[0]);
2052 case 'T': /* SD -- Scroll <n> line down */
2053 DEFAULT(csiescseq.arg[0], 1);
2054 tscrolldown(term.top, csiescseq.arg[0]);
2056 case 'L': /* IL -- Insert <n> blank lines */
2057 DEFAULT(csiescseq.arg[0], 1);
2058 tinsertblankline(csiescseq.arg[0]);
2060 case 'l': /* RM -- Reset Mode */
2061 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2063 case 'M': /* DL -- Delete <n> lines */
2064 DEFAULT(csiescseq.arg[0], 1);
2065 tdeleteline(csiescseq.arg[0]);
2067 case 'X': /* ECH -- Erase <n> char */
2068 DEFAULT(csiescseq.arg[0], 1);
2069 tclearregion(term.c.x, term.c.y,
2070 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2072 case 'P': /* DCH -- Delete <n> char */
2073 DEFAULT(csiescseq.arg[0], 1);
2074 tdeletechar(csiescseq.arg[0]);
2076 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2077 DEFAULT(csiescseq.arg[0], 1);
2078 while(csiescseq.arg[0]--)
2081 case 'd': /* VPA -- Move to <row> */
2082 DEFAULT(csiescseq.arg[0], 1);
2083 tmoveato(term.c.x, csiescseq.arg[0]-1);
2085 case 'h': /* SM -- Set terminal mode */
2086 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2088 case 'm': /* SGR -- Terminal attribute (color) */
2089 tsetattr(csiescseq.arg, csiescseq.narg);
2091 case 'n': /* DSR – Device Status Report (cursor position) */
2092 if (csiescseq.arg[0] == 6) {
2093 len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
2094 term.c.y+1, term.c.x+1);
2098 case 'r': /* DECSTBM -- Set Scrolling Region */
2099 if(csiescseq.priv) {
2102 DEFAULT(csiescseq.arg[0], 1);
2103 DEFAULT(csiescseq.arg[1], term.row);
2104 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2108 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2109 tcursor(CURSOR_SAVE);
2111 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2112 tcursor(CURSOR_LOAD);
2123 for(i = 0; i < csiescseq.len; i++) {
2124 c = csiescseq.buf[i] & 0xff;
2127 } else if(c == '\n') {
2129 } else if(c == '\r') {
2131 } else if(c == 0x1b) {
2134 printf("(%02x)", c);
2142 memset(&csiescseq, 0, sizeof(csiescseq));
2151 narg = strescseq.narg;
2153 switch(strescseq.type) {
2154 case ']': /* OSC -- Operating System Command */
2155 switch(i = atoi(strescseq.args[0])) {
2160 xsettitle(strescseq.args[1]);
2162 case 4: /* color set */
2165 p = strescseq.args[2];
2167 case 104: /* color reset, here p = NULL */
2168 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2169 if (!xsetcolorname(j, p)) {
2170 fprintf(stderr, "erresc: invalid color %s\n", p);
2173 * TODO if defaultbg color is changed, borders
2180 fprintf(stderr, "erresc: unknown str ");
2185 case 'k': /* old title set compatibility */
2186 xsettitle(strescseq.args[0]);
2188 case 'P': /* DSC -- Device Control String */
2189 case '_': /* APC -- Application Program Command */
2190 case '^': /* PM -- Privacy Message */
2192 fprintf(stderr, "erresc: unknown str ");
2201 char *p = strescseq.buf;
2204 strescseq.buf[strescseq.len] = '\0';
2205 while(p && strescseq.narg < STR_ARG_SIZ)
2206 strescseq.args[strescseq.narg++] = strsep(&p, ";");
2214 printf("ESC%c", strescseq.type);
2215 for(i = 0; i < strescseq.len; i++) {
2216 c = strescseq.buf[i] & 0xff;
2219 } else if(isprint(c)) {
2221 } else if(c == '\n') {
2223 } else if(c == '\r') {
2225 } else if(c == 0x1b) {
2228 printf("(%02x)", c);
2236 memset(&strescseq, 0, sizeof(strescseq));
2240 tputtab(bool forward) {
2246 for(++x; x < term.col && !term.tabs[x]; ++x)
2251 for(--x; x > 0 && !term.tabs[x]; --x)
2254 tmoveto(x, term.c.y);
2258 techo(char *buf, int len) {
2259 for(; len > 0; buf++, len--) {
2262 if(c == '\033') { /* escape */
2265 } else if(c < '\x20') { /* control code */
2266 if(c != '\n' && c != '\r' && c != '\t') {
2280 tdeftran(char ascii) {
2282 static char tbl[][2] = {
2283 {'0', CS_GRAPHIC0}, {'1', CS_GRAPHIC1}, {'A', CS_UK},
2284 {'B', CS_USA}, {'<', CS_MULTI}, {'K', CS_GER},
2285 {'5', CS_FIN}, {'C', CS_FIN},
2289 for (bp = &tbl[0]; (c = (*bp)[0]) && c != ascii; ++bp)
2293 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2295 term.trantbl[term.icharset] = (*bp)[1];
2300 if (term.trantbl[term.charset] == CS_GRAPHIC0)
2301 term.c.attr.mode |= ATTR_GFX;
2303 term.c.attr.mode &= ~ATTR_GFX;
2307 tputc(char *c, int len) {
2309 bool control = ascii < '\x20' || ascii == 0177;
2316 utf8decode(c, &u8char);
2317 width = wcwidth(u8char);
2321 if(xwrite(iofd, c, len) < 0) {
2322 fprintf(stderr, "Error writing in %s:%s\n",
2323 opt_io, strerror(errno));
2330 * STR sequences must be checked before anything else
2331 * because it can use some control codes as part of the sequence.
2333 if(term.esc & ESC_STR) {
2336 term.esc = ESC_START | ESC_STR_END;
2338 case '\a': /* backwards compatibility to xterm */
2343 if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2344 memmove(&strescseq.buf[strescseq.len], c, len);
2345 strescseq.len += len;
2348 * Here is a bug in terminals. If the user never sends
2349 * some code to stop the str or esc command, then st
2350 * will stop responding. But this is better than
2351 * silently failing with unknown characters. At least
2352 * then users will report back.
2354 * In the case users ever get fixed, here is the code:
2366 * Actions of control codes must be performed as soon they arrive
2367 * because they can be embedded inside a control sequence, and
2368 * they must not cause conflicts with sequences.
2376 tmoveto(term.c.x-1, term.c.y);
2379 tmoveto(0, term.c.y);
2384 /* go to first col if the mode is set */
2385 tnewline(IS_SET(MODE_CRLF));
2387 case '\a': /* BEL */
2388 if(!(xw.state & WIN_FOCUSED))
2391 XBell(xw.dpy, bellvolume);
2393 case '\033': /* ESC */
2395 term.esc = ESC_START;
2397 case '\016': /* SO */
2401 case '\017': /* SI */
2405 case '\032': /* SUB */
2406 case '\030': /* CAN */
2409 case '\005': /* ENQ (IGNORED) */
2410 case '\000': /* NUL (IGNORED) */
2411 case '\021': /* XON (IGNORED) */
2412 case '\023': /* XOFF (IGNORED) */
2413 case 0177: /* DEL (IGNORED) */
2416 } else if(term.esc & ESC_START) {
2417 if(term.esc & ESC_CSI) {
2418 csiescseq.buf[csiescseq.len++] = ascii;
2419 if(BETWEEN(ascii, 0x40, 0x7E)
2420 || csiescseq.len >= \
2421 sizeof(csiescseq.buf)-1) {
2426 } else if(term.esc & ESC_STR_END) {
2430 } else if(term.esc & ESC_ALTCHARSET) {
2434 } else if(term.esc & ESC_TEST) {
2435 if(ascii == '8') { /* DEC screen alignment test. */
2436 char E[UTF_SIZ] = "E";
2439 for(x = 0; x < term.col; ++x) {
2440 for(y = 0; y < term.row; ++y)
2441 tsetchar(E, &term.c.attr, x, y);
2448 term.esc |= ESC_CSI;
2451 term.esc |= ESC_TEST;
2453 case 'P': /* DCS -- Device Control String */
2454 case '_': /* APC -- Application Program Command */
2455 case '^': /* PM -- Privacy Message */
2456 case ']': /* OSC -- Operating System Command */
2457 case 'k': /* old title set compatibility */
2459 strescseq.type = ascii;
2460 term.esc |= ESC_STR;
2462 case '(': /* set primary charset G0 */
2463 case ')': /* set secondary charset G1 */
2464 case '*': /* set tertiary charset G2 */
2465 case '+': /* set quaternary charset G3 */
2466 term.icharset = ascii - '(';
2467 term.esc |= ESC_ALTCHARSET;
2469 case 'D': /* IND -- Linefeed */
2470 if(term.c.y == term.bot) {
2471 tscrollup(term.top, 1);
2473 tmoveto(term.c.x, term.c.y+1);
2477 case 'E': /* NEL -- Next line */
2478 tnewline(1); /* always go to first col */
2481 case 'H': /* HTS -- Horizontal tab stop */
2482 term.tabs[term.c.x] = 1;
2485 case 'M': /* RI -- Reverse index */
2486 if(term.c.y == term.top) {
2487 tscrolldown(term.top, 1);
2489 tmoveto(term.c.x, term.c.y-1);
2493 case 'Z': /* DECID -- Identify Terminal */
2494 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2497 case 'c': /* RIS -- Reset to inital state */
2503 case '=': /* DECPAM -- Application keypad */
2504 term.mode |= MODE_APPKEYPAD;
2507 case '>': /* DECPNM -- Normal keypad */
2508 term.mode &= ~MODE_APPKEYPAD;
2511 case '7': /* DECSC -- Save Cursor */
2512 tcursor(CURSOR_SAVE);
2515 case '8': /* DECRC -- Restore Cursor */
2516 tcursor(CURSOR_LOAD);
2519 case '\\': /* ST -- Stop */
2523 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2524 (uchar) ascii, isprint(ascii)? ascii:'.');
2529 * All characters which form part of a sequence are not
2535 * Display control codes only if we are in graphic mode
2537 if(control && !(term.c.attr.mode & ATTR_GFX))
2539 if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2541 if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2542 term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
2546 if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2547 memmove(&term.line[term.c.y][term.c.x+1],
2548 &term.line[term.c.y][term.c.x],
2549 (term.col - term.c.x - 1) * sizeof(Glyph));
2552 if(term.c.x+width > term.col)
2555 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2558 term.line[term.c.y][term.c.x].mode |= ATTR_WIDE;
2559 if(term.c.x+1 < term.col) {
2560 term.line[term.c.y][term.c.x+1].c[0] = '\0';
2561 term.line[term.c.y][term.c.x+1].mode = ATTR_WDUMMY;
2564 if(term.c.x+width < term.col) {
2565 tmoveto(term.c.x+width, term.c.y);
2567 term.c.state |= CURSOR_WRAPNEXT;
2572 tresize(int col, int row) {
2574 int minrow = MIN(row, term.row);
2575 int mincol = MIN(col, term.col);
2576 int slide = term.c.y - row + 1;
2580 if(col < 1 || row < 1)
2583 /* free unneeded rows */
2587 * slide screen to keep cursor where we expect it -
2588 * tscrollup would work here, but we can optimize to
2589 * memmove because we're freeing the earlier lines
2591 for(/* i = 0 */; i < slide; i++) {
2595 memmove(term.line, term.line + slide, row * sizeof(Line));
2596 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2598 for(i += row; i < term.row; i++) {
2603 /* resize to new height */
2604 term.line = xrealloc(term.line, row * sizeof(Line));
2605 term.alt = xrealloc(term.alt, row * sizeof(Line));
2606 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2607 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2609 /* resize each row to new width, zero-pad if needed */
2610 for(i = 0; i < minrow; i++) {
2612 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2613 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2616 /* allocate any new rows */
2617 for(/* i == minrow */; i < row; i++) {
2619 term.line[i] = xmalloc(col * sizeof(Glyph));
2620 term.alt[i] = xmalloc(col * sizeof(Glyph));
2622 if(col > term.col) {
2623 bp = term.tabs + term.col;
2625 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2626 while(--bp > term.tabs && !*bp)
2628 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2631 /* update terminal size */
2634 /* reset scrolling region */
2635 tsetscroll(0, row-1);
2636 /* make use of the LIMIT in tmoveto */
2637 tmoveto(term.c.x, term.c.y);
2638 /* Clearing both screens */
2641 if(mincol < col && 0 < minrow) {
2642 tclearregion(mincol, 0, col - 1, minrow - 1);
2644 if(0 < col && minrow < row) {
2645 tclearregion(0, minrow, col - 1, row - 1);
2648 } while(orig != term.line);
2654 xresize(int col, int row) {
2655 xw.tw = MAX(1, col * xw.cw);
2656 xw.th = MAX(1, row * xw.ch);
2658 XFreePixmap(xw.dpy, xw.buf);
2659 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2660 DefaultDepth(xw.dpy, xw.scr));
2661 XftDrawChange(xw.draw, xw.buf);
2662 xclear(0, 0, xw.w, xw.h);
2665 static inline ushort
2666 sixd_to_16bit(int x) {
2667 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2673 XRenderColor color = { .alpha = 0xffff };
2678 for (cp = dc.col; cp < dc.col + LEN(dc.col); ++cp)
2679 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
2682 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2683 for(i = 0; i < LEN(colorname); i++) {
2686 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2687 die("Could not allocate color '%s'\n", colorname[i]);
2691 /* load colors [16-255] ; same colors as xterm */
2692 for(i = 16, r = 0; r < 6; r++) {
2693 for(g = 0; g < 6; g++) {
2694 for(b = 0; b < 6; b++) {
2695 color.red = sixd_to_16bit(r);
2696 color.green = sixd_to_16bit(g);
2697 color.blue = sixd_to_16bit(b);
2698 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2699 die("Could not allocate color %d\n", i);
2706 for(r = 0; r < 24; r++, i++) {
2707 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2708 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2710 die("Could not allocate color %d\n", i);
2717 xsetcolorname(int x, const char *name) {
2718 XRenderColor color = { .alpha = 0xffff };
2720 if (x < 0 || x > LEN(colorname))
2723 if(16 <= x && x < 16 + 216) {
2724 int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2725 color.red = sixd_to_16bit(r);
2726 color.green = sixd_to_16bit(g);
2727 color.blue = sixd_to_16bit(b);
2728 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2729 return 0; /* something went wrong */
2732 } else if (16 + 216 <= x && x < 256) {
2733 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2734 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2735 return 0; /* something went wrong */
2739 name = colorname[x];
2742 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2749 xtermclear(int col1, int row1, int col2, int row2) {
2750 XftDrawRect(xw.draw,
2751 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2752 borderpx + col1 * xw.cw,
2753 borderpx + row1 * xw.ch,
2754 (col2-col1+1) * xw.cw,
2755 (row2-row1+1) * xw.ch);
2759 * Absolute coordinates.
2762 xclear(int x1, int y1, int x2, int y2) {
2763 XftDrawRect(xw.draw,
2764 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2765 x1, y1, x2-x1, y2-y1);
2770 XClassHint class = {opt_class ? opt_class : termname, termname};
2771 XWMHints wm = {.flags = InputHint, .input = 1};
2772 XSizeHints *sizeh = NULL;
2774 sizeh = XAllocSizeHints();
2775 if(xw.isfixed == False) {
2776 sizeh->flags = PSize | PResizeInc | PBaseSize;
2777 sizeh->height = xw.h;
2778 sizeh->width = xw.w;
2779 sizeh->height_inc = xw.ch;
2780 sizeh->width_inc = xw.cw;
2781 sizeh->base_height = 2 * borderpx;
2782 sizeh->base_width = 2 * borderpx;
2784 sizeh->flags = PMaxSize | PMinSize;
2785 sizeh->min_width = sizeh->max_width = xw.fw;
2786 sizeh->min_height = sizeh->max_height = xw.fh;
2789 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2794 xloadfont(Font *f, FcPattern *pattern) {
2798 match = FcFontMatch(NULL, pattern, &result);
2802 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2803 FcPatternDestroy(match);
2808 f->pattern = FcPatternDuplicate(pattern);
2810 f->ascent = f->match->ascent;
2811 f->descent = f->match->descent;
2813 f->rbearing = f->match->max_advance_width;
2815 f->height = f->ascent + f->descent;
2816 f->width = f->lbearing + f->rbearing;
2822 xloadfonts(char *fontstr, int fontsize) {
2827 if(fontstr[0] == '-') {
2828 pattern = XftXlfdParse(fontstr, False, False);
2830 pattern = FcNameParse((FcChar8 *)fontstr);
2834 die("st: can't open font %s\n", fontstr);
2837 FcPatternDel(pattern, FC_PIXEL_SIZE);
2838 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2839 usedfontsize = fontsize;
2841 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2842 if(result == FcResultMatch) {
2843 usedfontsize = (int)fontval;
2846 * Default font size is 12, if none given. This is to
2847 * have a known usedfontsize value.
2849 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2854 FcConfigSubstitute(0, pattern, FcMatchPattern);
2855 FcDefaultSubstitute(pattern);
2857 if(xloadfont(&dc.font, pattern))
2858 die("st: can't open font %s\n", fontstr);
2860 /* Setting character width and height. */
2861 xw.cw = CEIL(dc.font.width * cwscale);
2862 xw.ch = CEIL(dc.font.height * chscale);
2864 FcPatternDel(pattern, FC_SLANT);
2865 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2866 if(xloadfont(&dc.ifont, pattern))
2867 die("st: can't open font %s\n", fontstr);
2869 FcPatternDel(pattern, FC_WEIGHT);
2870 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2871 if(xloadfont(&dc.ibfont, pattern))
2872 die("st: can't open font %s\n", fontstr);
2874 FcPatternDel(pattern, FC_SLANT);
2875 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2876 if(xloadfont(&dc.bfont, pattern))
2877 die("st: can't open font %s\n", fontstr);
2879 FcPatternDestroy(pattern);
2883 xloadfontset(Font *f) {
2886 if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
2892 xunloadfont(Font *f) {
2893 XftFontClose(xw.dpy, f->match);
2894 FcPatternDestroy(f->pattern);
2896 FcFontSetDestroy(f->set);
2900 xunloadfonts(void) {
2903 /* Free the loaded fonts in the font cache. */
2904 for(i = 0; i < frclen; i++) {
2905 XftFontClose(xw.dpy, frc[i].font);
2909 xunloadfont(&dc.font);
2910 xunloadfont(&dc.bfont);
2911 xunloadfont(&dc.ifont);
2912 xunloadfont(&dc.ibfont);
2916 xzoom(const Arg *arg) {
2918 xloadfonts(usedfont, usedfontsize + arg->i);
2930 if(!(xw.dpy = XOpenDisplay(NULL)))
2931 die("Can't open display\n");
2932 xw.scr = XDefaultScreen(xw.dpy);
2933 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2937 die("Could not init fontconfig.\n");
2939 usedfont = (opt_font == NULL)? font : opt_font;
2940 xloadfonts(usedfont, 0);
2943 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2946 /* adjust fixed window geometry */
2948 sw = DisplayWidth(xw.dpy, xw.scr);
2949 sh = DisplayHeight(xw.dpy, xw.scr);
2951 xw.fx = sw + xw.fx - xw.fw - 1;
2953 xw.fy = sh + xw.fy - xw.fh - 1;
2958 /* window - default size */
2959 xw.h = 2 * borderpx + term.row * xw.ch;
2960 xw.w = 2 * borderpx + term.col * xw.cw;
2966 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
2967 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
2968 xw.attrs.bit_gravity = NorthWestGravity;
2969 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
2970 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2971 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2972 xw.attrs.colormap = xw.cmap;
2974 parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2975 XRootWindow(xw.dpy, xw.scr);
2976 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2977 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2978 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
2979 | CWEventMask | CWColormap, &xw.attrs);
2981 memset(&gcvalues, 0, sizeof(gcvalues));
2982 gcvalues.graphics_exposures = False;
2983 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2985 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2986 DefaultDepth(xw.dpy, xw.scr));
2987 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
2988 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2990 /* Xft rendering context */
2991 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2994 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2995 XSetLocaleModifiers("@im=local");
2996 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2997 XSetLocaleModifiers("@im=");
2998 if((xw.xim = XOpenIM(xw.dpy,
2999 NULL, NULL, NULL)) == NULL) {
3000 die("XOpenIM failed. Could not open input"
3005 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
3006 | XIMStatusNothing, XNClientWindow, xw.win,
3007 XNFocusWindow, xw.win, NULL);
3009 die("XCreateIC failed. Could not obtain input method.\n");
3011 /* white cursor, black outline */
3012 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
3013 XDefineCursor(xw.dpy, xw.win, cursor);
3014 XRecolorCursor(xw.dpy, cursor,
3015 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
3016 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
3018 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
3019 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
3020 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
3023 XMapWindow(xw.dpy, xw.win);
3029 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
3030 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
3031 width = charlen * xw.cw, xp, i;
3033 int u8fl, u8fblen, u8cblen, doesexist;
3036 Font *font = &dc.font;
3038 FcPattern *fcpattern, *fontpattern;
3039 FcFontSet *fcsets[] = { NULL };
3040 FcCharSet *fccharset;
3041 Colour *fg, *bg, *temp, revfg, revbg, truefg, truebg;
3042 XRenderColor colfg, colbg;
3046 frcflags = FRC_NORMAL;
3048 if(base.mode & ATTR_ITALIC) {
3049 if(base.fg == defaultfg)
3050 base.fg = defaultitalic;
3052 frcflags = FRC_ITALIC;
3053 } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
3054 if(base.fg == defaultfg)
3055 base.fg = defaultitalic;
3057 frcflags = FRC_ITALICBOLD;
3058 } else if(base.mode & ATTR_UNDERLINE) {
3059 if(base.fg == defaultfg)
3060 base.fg = defaultunderline;
3062 if(IS_TRUECOL(base.fg)) {
3063 colfg.red = TRUERED(base.fg);
3064 colfg.green = TRUEGREEN(base.fg);
3065 colfg.blue = TRUEBLUE(base.fg);
3066 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
3069 fg = &dc.col[base.fg];
3072 if(IS_TRUECOL(base.bg)) {
3073 colbg.green = TRUEGREEN(base.bg);
3074 colbg.red = TRUERED(base.bg);
3075 colbg.blue = TRUEBLUE(base.bg);
3076 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
3079 bg = &dc.col[base.bg];
3084 if(base.mode & ATTR_BOLD) {
3085 if(BETWEEN(base.fg, 0, 7)) {
3086 /* basic system colors */
3087 fg = &dc.col[base.fg + 8];
3088 } else if(BETWEEN(base.fg, 16, 195)) {
3090 fg = &dc.col[base.fg + 36];
3091 } else if(BETWEEN(base.fg, 232, 251)) {
3093 fg = &dc.col[base.fg + 4];
3096 * Those ranges will not be brightened:
3097 * 8 - 15 – bright system colors
3098 * 196 - 231 – highest 256 color cube
3099 * 252 - 255 – brightest colors in greyscale
3102 frcflags = FRC_BOLD;
3105 if(IS_SET(MODE_REVERSE)) {
3106 if(fg == &dc.col[defaultfg]) {
3107 fg = &dc.col[defaultbg];
3109 colfg.red = ~fg->color.red;
3110 colfg.green = ~fg->color.green;
3111 colfg.blue = ~fg->color.blue;
3112 colfg.alpha = fg->color.alpha;
3113 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
3117 if(bg == &dc.col[defaultbg]) {
3118 bg = &dc.col[defaultfg];
3120 colbg.red = ~bg->color.red;
3121 colbg.green = ~bg->color.green;
3122 colbg.blue = ~bg->color.blue;
3123 colbg.alpha = bg->color.alpha;
3124 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
3129 if(base.mode & ATTR_REVERSE) {
3135 if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3138 /* Intelligent cleaning up of the borders. */
3140 xclear(0, (y == 0)? 0 : winy, borderpx,
3141 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3143 if(x + charlen >= term.col) {
3144 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3145 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3148 xclear(winx, 0, winx + width, borderpx);
3150 xclear(winx, winy + xw.ch, winx + width, xw.h);
3152 /* Clean up the region we want to draw to. */
3153 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3155 /* Set the clip region because Xft is sometimes dirty. */
3160 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3162 for(xp = winx; bytelen > 0;) {
3164 * Search for the range in the to be printed string of glyphs
3165 * that are in the main font. Then print that range. If
3166 * some glyph is found that is not in the font, do the
3172 oneatatime = font->width != xw.cw;
3175 u8cblen = utf8decode(s, &u8char);
3179 doesexist = XftCharExists(xw.dpy, font->match, u8char);
3180 if(oneatatime || !doesexist || bytelen <= 0) {
3181 if(oneatatime || bytelen <= 0) {
3189 XftDrawStringUtf8(xw.draw, fg,
3191 winy + font->ascent,
3209 /* Search the font cache. */
3210 for(i = 0; i < frclen; i++) {
3211 if(XftCharExists(xw.dpy, frc[i].font, u8char)
3212 && frc[i].flags == frcflags) {
3217 /* Nothing was found. */
3221 fcsets[0] = font->set;
3224 * Nothing was found in the cache. Now use
3225 * some dozen of Fontconfig calls to get the
3226 * font for one single character.
3228 fcpattern = FcPatternDuplicate(font->pattern);
3229 fccharset = FcCharSetCreate();
3231 FcCharSetAddChar(fccharset, u8char);
3232 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3234 FcPatternAddBool(fcpattern, FC_SCALABLE,
3237 FcConfigSubstitute(0, fcpattern,
3239 FcDefaultSubstitute(fcpattern);
3241 fontpattern = FcFontSetMatch(0, fcsets,
3242 FcTrue, fcpattern, &fcres);
3245 * Overwrite or create the new cache entry.
3247 if(frclen >= LEN(frc)) {
3248 frclen = LEN(frc) - 1;
3249 XftFontClose(xw.dpy, frc[frclen].font);
3252 frc[frclen].font = XftFontOpenPattern(xw.dpy,
3254 frc[frclen].flags = frcflags;
3259 FcPatternDestroy(fcpattern);
3260 FcCharSetDestroy(fccharset);
3263 XftDrawStringUtf8(xw.draw, fg, frc[i].font,
3264 xp, winy + frc[i].font->ascent,
3265 (FcChar8 *)u8c, u8cblen);
3267 xp += xw.cw * wcwidth(u8char);
3271 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
3272 winy + font->ascent, (FcChar8 *)s, bytelen);
3275 if(base.mode & ATTR_UNDERLINE) {
3276 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
3280 /* Reset clip to none. */
3281 XftDrawSetClip(xw.draw, 0);
3286 static int oldx = 0, oldy = 0;
3287 int sl, width, curx;
3288 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
3290 LIMIT(oldx, 0, term.col-1);
3291 LIMIT(oldy, 0, term.row-1);
3295 /* adjust position if in dummy */
3296 if(term.line[oldy][oldx].mode & ATTR_WDUMMY)
3298 if(term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3301 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
3303 /* remove the old cursor */
3304 sl = utf8size(term.line[oldy][oldx].c);
3305 width = (term.line[oldy][oldx].mode & ATTR_WIDE)? 2 : 1;
3306 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
3309 /* draw the new one */
3310 if(!(IS_SET(MODE_HIDE))) {
3311 if(xw.state & WIN_FOCUSED) {
3312 if(IS_SET(MODE_REVERSE)) {
3313 g.mode |= ATTR_REVERSE;
3319 width = (term.line[term.c.y][curx].mode & ATTR_WIDE)\
3321 xdraws(g.c, g, term.c.x, term.c.y, width, sl);
3323 XftDrawRect(xw.draw, &dc.col[defaultcs],
3324 borderpx + curx * xw.cw,
3325 borderpx + term.c.y * xw.ch,
3327 XftDrawRect(xw.draw, &dc.col[defaultcs],
3328 borderpx + curx * xw.cw,
3329 borderpx + term.c.y * xw.ch,
3331 XftDrawRect(xw.draw, &dc.col[defaultcs],
3332 borderpx + (curx + 1) * xw.cw - 1,
3333 borderpx + term.c.y * xw.ch,
3335 XftDrawRect(xw.draw, &dc.col[defaultcs],
3336 borderpx + curx * xw.cw,
3337 borderpx + (term.c.y + 1) * xw.ch - 1,
3340 oldx = curx, oldy = term.c.y;
3346 xsettitle(char *p) {
3349 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3351 XSetWMName(xw.dpy, xw.win, &prop);
3357 xsettitle(opt_title ? opt_title : "st");
3361 redraw(int timeout) {
3362 struct timespec tv = {0, timeout * 1000};
3368 nanosleep(&tv, NULL);
3369 XSync(xw.dpy, False); /* necessary for a good tput flash */
3375 drawregion(0, 0, term.col, term.row);
3376 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3378 XSetForeground(xw.dpy, dc.gc,
3379 dc.col[IS_SET(MODE_REVERSE)?
3380 defaultfg : defaultbg].pixel);
3384 drawregion(int x1, int y1, int x2, int y2) {
3385 int ic, ib, x, y, ox, sl;
3387 char buf[DRAW_BUF_SIZ];
3388 bool ena_sel = sel.ob.x != -1;
3391 if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3394 if(!(xw.state & WIN_VISIBLE))
3397 for(y = y1; y < y2; y++) {
3401 xtermclear(0, y, term.col, y);
3403 base = term.line[y][0];
3405 for(x = x1; x < x2; x++) {
3406 new = term.line[y][x];
3407 if(new.mode == ATTR_WDUMMY)
3409 if(ena_sel && selected(x, y))
3410 new.mode ^= ATTR_REVERSE;
3411 if(ib > 0 && (ATTRCMP(base, new)
3412 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3413 xdraws(buf, base, ox, y, ic, ib);
3421 sl = utf8decode(new.c, &u8char);
3422 memcpy(buf+ib, new.c, sl);
3424 ic += (new.mode & ATTR_WIDE)? 2 : 1;
3427 xdraws(buf, base, ox, y, ic, ib);
3433 expose(XEvent *ev) {
3434 XExposeEvent *e = &ev->xexpose;
3436 if(xw.state & WIN_REDRAW) {
3438 xw.state &= ~WIN_REDRAW;
3444 visibility(XEvent *ev) {
3445 XVisibilityEvent *e = &ev->xvisibility;
3447 if(e->state == VisibilityFullyObscured) {
3448 xw.state &= ~WIN_VISIBLE;
3449 } else if(!(xw.state & WIN_VISIBLE)) {
3450 /* need a full redraw for next Expose, not just a buf copy */
3451 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3457 xw.state &= ~WIN_VISIBLE;
3461 xsetpointermotion(int set) {
3462 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3463 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3467 xseturgency(int add) {
3468 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3470 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3471 XSetWMHints(xw.dpy, xw.win, h);
3477 XFocusChangeEvent *e = &ev->xfocus;
3479 if(e->mode == NotifyGrab)
3482 if(ev->type == FocusIn) {
3483 XSetICFocus(xw.xic);
3484 xw.state |= WIN_FOCUSED;
3486 if(IS_SET(MODE_FOCUS))
3487 ttywrite("\033[I", 3);
3489 XUnsetICFocus(xw.xic);
3490 xw.state &= ~WIN_FOCUSED;
3491 if(IS_SET(MODE_FOCUS))
3492 ttywrite("\033[O", 3);
3497 match(uint mask, uint state) {
3498 state &= ~ignoremod;
3500 if(mask == XK_NO_MOD && state)
3502 if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
3504 if(mask == XK_ANY_MOD)
3506 return state == mask;
3510 numlock(const Arg *dummy) {
3515 kmap(KeySym k, uint state) {
3519 /* Check for mapped keys out of X11 function keys. */
3520 for(i = 0; i < LEN(mappedkeys); i++) {
3521 if(mappedkeys[i] == k)
3524 if(i == LEN(mappedkeys)) {
3525 if((k & 0xFFFF) < 0xFD00)
3529 for(kp = key; kp < key + LEN(key); kp++) {
3533 if(!match(kp->mask, state))
3536 if(kp->appkey > 0) {
3537 if(!IS_SET(MODE_APPKEYPAD))
3539 if(term.numlock && kp->appkey == 2)
3541 } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
3545 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
3547 && !IS_SET(MODE_APPCURSOR))) {
3551 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
3552 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
3563 kpress(XEvent *ev) {
3564 XKeyEvent *e = &ev->xkey;
3566 char buf[32], *customkey;
3572 if(IS_SET(MODE_KBDLOCK))
3575 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
3576 e->state &= ~Mod2Mask;
3578 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3579 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3580 bp->func(&(bp->arg));
3585 /* 2. custom keys from config.h */
3586 if((customkey = kmap(ksym, e->state))) {
3587 len = strlen(customkey);
3588 ttywrite(customkey, len);
3589 if(IS_SET(MODE_ECHO))
3590 techo(customkey, len);
3594 /* 3. composed string from input method */
3597 if(len == 1 && e->state & Mod1Mask) {
3598 if(IS_SET(MODE_8BIT)) {
3601 len = utf8encode(&c, buf);
3610 if(IS_SET(MODE_ECHO))
3616 cmessage(XEvent *e) {
3619 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3621 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3622 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3623 xw.state |= WIN_FOCUSED;
3625 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3626 xw.state &= ~WIN_FOCUSED;
3628 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3629 /* Send SIGHUP to shell */
3636 cresize(int width, int height) {
3644 col = (xw.w - 2 * borderpx) / xw.cw;
3645 row = (xw.h - 2 * borderpx) / xw.ch;
3654 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3657 cresize(e->xconfigure.width, e->xconfigure.height);
3663 int w = xw.w, h = xw.h;
3665 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3666 struct timeval drawtimeout, *tv = NULL, now, last, lastblink;
3668 /* Waiting for window mapping */
3670 XNextEvent(xw.dpy, &ev);
3671 if(ev.type == ConfigureNotify) {
3672 w = ev.xconfigure.width;
3673 h = ev.xconfigure.height;
3674 } else if(ev.type == MapNotify) {
3682 cresize(xw.fw, xw.fh);
3685 gettimeofday(&lastblink, NULL);
3686 gettimeofday(&last, NULL);
3688 for(xev = actionfps;;) {
3690 FD_SET(cmdfd, &rfd);
3693 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3696 die("select failed: %s\n", SERRNO);
3698 if(FD_ISSET(cmdfd, &rfd)) {
3701 blinkset = tattrset(ATTR_BLINK);
3703 MODBIT(term.mode, 0, MODE_BLINK);
3707 if(FD_ISSET(xfd, &rfd))
3710 gettimeofday(&now, NULL);
3711 drawtimeout.tv_sec = 0;
3712 drawtimeout.tv_usec = (1000/xfps) * 1000;
3716 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3717 tsetdirtattr(ATTR_BLINK);
3718 term.mode ^= MODE_BLINK;
3719 gettimeofday(&lastblink, NULL);
3722 if(TIMEDIFF(now, last) \
3723 > (xev? (1000/xfps) : (1000/actionfps))) {
3729 while(XPending(xw.dpy)) {
3730 XNextEvent(xw.dpy, &ev);
3731 if(XFilterEvent(&ev, None))
3733 if(handler[ev.type])
3734 (handler[ev.type])(&ev);
3740 if(xev && !FD_ISSET(xfd, &rfd))
3742 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3744 if(TIMEDIFF(now, lastblink) \
3746 drawtimeout.tv_usec = 1;
3748 drawtimeout.tv_usec = (1000 * \
3763 die("%s " VERSION " (c) 2010-2013 st engineers\n" \
3764 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
3765 " [-t title] [-w windowid] [-e command ...]\n", argv0);
3769 main(int argc, char *argv[]) {
3774 xw.fw = xw.fh = xw.fx = xw.fy = 0;
3779 allowaltscreen = false;
3782 opt_class = EARGF(usage());
3785 /* eat all remaining arguments */
3788 if(argv[1] != NULL && opt_title == NULL) {
3789 titles = strdup(argv[1]);
3790 opt_title = basename(titles);
3795 opt_font = EARGF(usage());
3798 bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
3803 if(bitm & WidthValue)
3805 if(bitm & HeightValue)
3807 if(bitm & XNegative && xw.fx == 0)
3809 if(bitm & YNegative && xw.fy == 0)
3812 if(xw.fh != 0 && xw.fw != 0)
3816 opt_io = EARGF(usage());
3819 opt_title = EARGF(usage());
3822 opt_embed = EARGF(usage());
3830 setlocale(LC_CTYPE, "");
3831 XSetLocaleModifiers("");