1 /* See LICENSE for licence details. */
15 #include <sys/ioctl.h>
16 #include <sys/select.h>
19 #include <sys/types.h>
24 #include <X11/Xatom.h>
26 #include <X11/Xutil.h>
27 #include <X11/cursorfont.h>
28 #include <X11/keysym.h>
29 #include <X11/Xft/Xft.h>
30 #include <fontconfig/fontconfig.h>
39 #define Draw XftDraw *
40 #define Colour XftColor
41 #define Colourmap Colormap
42 #define Rectangle XRectangle
46 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
48 #elif defined(__FreeBSD__) || defined(__DragonFly__)
54 #define XEMBED_FOCUS_IN 4
55 #define XEMBED_FOCUS_OUT 5
59 #define ESC_BUF_SIZ (128*UTF_SIZ)
60 #define ESC_ARG_SIZ 16
61 #define STR_BUF_SIZ ESC_BUF_SIZ
62 #define STR_ARG_SIZ ESC_ARG_SIZ
63 #define DRAW_BUF_SIZ 20*1024
64 #define XK_ANY_MOD UINT_MAX
66 #define XK_SWITCH_MOD (1<<13)
68 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
71 #define SERRNO strerror(errno)
72 #define MIN(a, b) ((a) < (b) ? (a) : (b))
73 #define MAX(a, b) ((a) < (b) ? (b) : (a))
74 #define LEN(a) (sizeof(a) / sizeof(a[0]))
75 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
76 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
77 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
78 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
79 #define IS_SET(flag) ((term.mode & (flag)) != 0)
80 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
81 #define CEIL(x) (((x) != (int) (x)) ? (x) + 1 : (x))
83 #define TRUECOLOR(r,g,b) (1 << 24 | (r) << 16 | (g) << 8 | (b))
84 #define IS_TRUECOL(x) (1 << 24 & (x))
85 #define TRUERED(x) (((x) & 0xff0000) >> 8)
86 #define TRUEGREEN(x) (((x) & 0xff00))
87 #define TRUEBLUE(x) (((x) & 0xff) << 8)
90 #define VT102ID "\033[?6c"
92 enum glyph_attribute {
105 enum cursor_movement {
123 MODE_MOUSEMOTION = 64,
128 MODE_APPCURSOR = 2048,
129 MODE_MOUSESGR = 4096,
134 MODE_MOUSEX10 = 131072,
135 MODE_MOUSEMANY = 262144,
136 MODE_BRCKTPASTE = 524288,
137 MODE_PRINT = 1048576,
138 MODE_MOUSE = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
155 ESC_STR = 4, /* DSC, OSC, PM, APC */
157 ESC_STR_END = 16, /* a final string was encountered */
158 ESC_TEST = 32, /* Enter in test mode */
167 enum selection_type {
172 enum selection_snap {
177 typedef unsigned char uchar;
178 typedef unsigned int uint;
179 typedef unsigned long ulong;
180 typedef unsigned short ushort;
183 char c[UTF_SIZ]; /* character code */
184 ushort mode; /* attribute flags */
185 uint32_t fg; /* foreground */
186 uint32_t bg; /* background */
192 Glyph attr; /* current char attributes */
198 /* CSI Escape sequence structs */
199 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
201 char buf[ESC_BUF_SIZ]; /* raw string */
202 int len; /* raw string length */
204 int arg[ESC_ARG_SIZ];
205 int narg; /* nb of args */
209 /* STR Escape sequence structs */
210 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
212 char type; /* ESC type ... */
213 char buf[STR_BUF_SIZ]; /* raw string */
214 int len; /* raw string length */
215 char *args[STR_ARG_SIZ];
216 int narg; /* nb of args */
219 /* Internal representation of the screen */
221 int row; /* nb row */
222 int col; /* nb col */
223 Line *line; /* screen */
224 Line *alt; /* alternate screen */
225 bool *dirty; /* dirtyness of lines */
226 TCursor c; /* cursor */
227 int top; /* top scroll limit */
228 int bot; /* bottom scroll limit */
229 int mode; /* terminal mode flags */
230 int esc; /* escape state flags */
231 char trantbl[4]; /* charset table translation */
232 int charset; /* current charset */
233 int icharset; /* selected charset for sequence */
234 bool numlock; /* lock numbers in keyboard */
238 /* Purely graphic info */
244 Atom xembed, wmdeletewin, netwmname, netwmpid;
249 XSetWindowAttributes attrs;
251 bool isfixed; /* is fixed geometry? */
252 int fx, fy, fw, fh; /* fixed geometry */
253 int tw, th; /* tty width and height */
254 int w, h; /* window width and height */
255 int ch; /* char height */
256 int cw; /* char width */
257 char state; /* focus, redraw, visible */
270 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
271 signed char appkey; /* application keypad */
272 signed char appcursor; /* application cursor */
273 signed char crlf; /* crlf mode */
281 * Selection variables:
282 * nb – normalized coordinates of the beginning of the selection
283 * ne – normalized coordinates of the end of the selection
284 * ob – original coordinates of the beginning of the selection
285 * oe – original coordinates of the end of the selection
294 struct timeval tclick1;
295 struct timeval tclick2;
308 void (*func)(const Arg *);
312 /* function definitions used in config.h */
313 static void clippaste(const Arg *);
314 static void numlock(const Arg *);
315 static void selpaste(const Arg *);
316 static void xzoom(const Arg *);
318 /* Config.h for applying patches and the configuration. */
334 /* Drawing Context */
336 Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
337 Font font, bfont, ifont, ibfont;
341 static void die(const char *, ...);
342 static void draw(void);
343 static void redraw(int);
344 static void drawregion(int, int, int, int);
345 static void execsh(void);
346 static void sigchld(int);
347 static void run(void);
349 static void csidump(void);
350 static void csihandle(void);
351 static void csiparse(void);
352 static void csireset(void);
353 static void strdump(void);
354 static void strhandle(void);
355 static void strparse(void);
356 static void strreset(void);
358 static int tattrset(int);
359 static void tprinter(char *s, size_t len);
360 static void tdumpline(int);
361 static void tdump(void);
362 static void tclearregion(int, int, int, int);
363 static void tcursor(int);
364 static void tdeletechar(int);
365 static void tdeleteline(int);
366 static void tinsertblank(int);
367 static void tinsertblankline(int);
368 static void tmoveto(int, int);
369 static void tmoveato(int x, int y);
370 static void tnew(int, int);
371 static void tnewline(int);
372 static void tputtab(bool);
373 static void tputc(char *, int);
374 static void treset(void);
375 static int tresize(int, int);
376 static void tscrollup(int, int);
377 static void tscrolldown(int, int);
378 static void tsetattr(int*, int);
379 static void tsetchar(char *, Glyph *, int, int);
380 static void tsetscroll(int, int);
381 static void tswapscreen(void);
382 static void tsetdirt(int, int);
383 static void tsetdirtattr(int);
384 static void tsetmode(bool, bool, int *, int);
385 static void tfulldirt(void);
386 static void techo(char *, int);
387 static int32_t tdefcolor(int *, int *, int);
388 static void tselcs(void);
389 static void tdeftran(char);
390 static inline bool match(uint, uint);
391 static void ttynew(void);
392 static void ttyread(void);
393 static void ttyresize(void);
394 static void ttysend(char *, size_t);
395 static void ttywrite(const char *, size_t);
397 static void xdraws(char *, Glyph, int, int, int, int);
398 static void xhints(void);
399 static void xclear(int, int, int, int);
400 static void xdrawcursor(void);
401 static void xinit(void);
402 static void xloadcols(void);
403 static int xsetcolorname(int, const char *);
404 static int xloadfont(Font *, FcPattern *);
405 static void xloadfonts(char *, double);
406 static int xloadfontset(Font *);
407 static void xsettitle(char *);
408 static void xresettitle(void);
409 static void xsetpointermotion(int);
410 static void xseturgency(int);
411 static void xsetsel(char*);
412 static void xtermclear(int, int, int, int);
413 static void xunloadfont(Font *f);
414 static void xunloadfonts(void);
415 static void xresize(int, int);
417 static void expose(XEvent *);
418 static void visibility(XEvent *);
419 static void unmap(XEvent *);
420 static char *kmap(KeySym, uint);
421 static void kpress(XEvent *);
422 static void cmessage(XEvent *);
423 static void cresize(int, int);
424 static void resize(XEvent *);
425 static void focus(XEvent *);
426 static void brelease(XEvent *);
427 static void bpress(XEvent *);
428 static void bmotion(XEvent *);
429 static void selnotify(XEvent *);
430 static void selclear(XEvent *);
431 static void selrequest(XEvent *);
433 static void selinit(void);
434 static void selsort(void);
435 static inline bool selected(int, int);
436 static void selcopy(void);
437 static void selscroll(int, int);
438 static void selsnap(int, int *, int *, int);
440 static int utf8decode(char *, long *);
441 static int utf8encode(long *, char *);
442 static int utf8size(char *);
443 static int isfullutf8(char *, int);
445 static ssize_t xwrite(int, char *, size_t);
446 static void *xmalloc(size_t);
447 static void *xrealloc(void *, size_t);
448 static char *xstrdup(char *s);
450 static void (*handler[LASTEvent])(XEvent *) = {
452 [ClientMessage] = cmessage,
453 [ConfigureNotify] = resize,
454 [VisibilityNotify] = visibility,
455 [UnmapNotify] = unmap,
459 [MotionNotify] = bmotion,
460 [ButtonPress] = bpress,
461 [ButtonRelease] = brelease,
462 [SelectionClear] = selclear,
463 [SelectionNotify] = selnotify,
464 [SelectionRequest] = selrequest,
471 static CSIEscape csiescseq;
472 static STREscape strescseq;
475 static Selection sel;
476 static int iofd = STDOUT_FILENO;
477 static char **opt_cmd = NULL;
478 static char *opt_io = NULL;
479 static char *opt_title = NULL;
480 static char *opt_embed = NULL;
481 static char *opt_class = NULL;
482 static char *opt_font = NULL;
483 static int oldbutton = 3; /* button event on startup: 3 = release */
485 static char *usedfont = NULL;
486 static double usedfontsize = 0;
488 /* Font Ring Cache */
501 /* Fontcache is an array now. A new font will be appended to the array. */
502 static Fontcache frc[16];
503 static int frclen = 0;
506 xwrite(int fd, char *s, size_t len) {
510 ssize_t r = write(fd, s, len);
520 xmalloc(size_t len) {
521 void *p = malloc(len);
524 die("Out of memory\n");
530 xrealloc(void *p, size_t len) {
531 if((p = realloc(p, len)) == NULL)
532 die("Out of memory\n");
542 die("Out of memory\n");
548 utf8decode(char *s, long *u) {
554 if(~c & 0x80) { /* 0xxxxxxx */
557 } else if((c & 0xE0) == 0xC0) { /* 110xxxxx */
560 } else if((c & 0xF0) == 0xE0) { /* 1110xxxx */
563 } else if((c & 0xF8) == 0xF0) { /* 11110xxx */
570 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
572 if((c & 0xC0) != 0x80) /* 10xxxxxx */
578 if((n == 1 && *u < 0x80) ||
579 (n == 2 && *u < 0x800) ||
580 (n == 3 && *u < 0x10000) ||
581 (*u >= 0xD800 && *u <= 0xDFFF)) {
593 utf8encode(long *u, char *s) {
601 *sp = uc; /* 0xxxxxxx */
603 } else if(*u < 0x800) {
604 *sp = (uc >> 6) | 0xC0; /* 110xxxxx */
606 } else if(uc < 0x10000) {
607 *sp = (uc >> 12) | 0xE0; /* 1110xxxx */
609 } else if(uc <= 0x10FFFF) {
610 *sp = (uc >> 18) | 0xF0; /* 11110xxx */
616 for(i=n,++sp; i>0; --i,++sp)
617 *sp = ((uc >> 6*(i-1)) & 0x3F) | 0x80; /* 10xxxxxx */
629 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
630 UTF-8 otherwise return 0 */
632 isfullutf8(char *s, int b) {
640 } else if((*c1 & 0xE0) == 0xC0 && b == 1) {
642 } else if((*c1 & 0xF0) == 0xE0 &&
644 ((b == 2) && (*c2 & 0xC0) == 0x80))) {
646 } else if((*c1 & 0xF8) == 0xF0 &&
648 ((b == 2) && (*c2 & 0xC0) == 0x80) ||
649 ((b == 3) && (*c2 & 0xC0) == 0x80 && (*c3 & 0xC0) == 0x80))) {
662 } else if((c & 0xE0) == 0xC0) {
664 } else if((c & 0xF0) == 0xE0) {
673 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
674 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
678 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
679 if(sel.xtarget == None)
680 sel.xtarget = XA_STRING;
688 return LIMIT(x, 0, term.col-1);
696 return LIMIT(y, 0, term.row-1);
701 if(sel.ob.y == sel.oe.y) {
702 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
703 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
705 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
706 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
708 sel.nb.y = MIN(sel.ob.y, sel.oe.y);
709 sel.ne.y = MAX(sel.ob.y, sel.oe.y);
713 selected(int x, int y) {
714 if(sel.ne.y == y && sel.nb.y == y)
715 return BETWEEN(x, sel.nb.x, sel.ne.x);
717 if(sel.type == SEL_RECTANGULAR) {
718 return ((sel.nb.y <= y && y <= sel.ne.y)
719 && (sel.nb.x <= x && x <= sel.ne.x));
722 return ((sel.nb.y < y && y < sel.ne.y)
723 || (y == sel.ne.y && x <= sel.ne.x))
724 || (y == sel.nb.y && x >= sel.nb.x
725 && (x <= sel.ne.x || sel.nb.y != sel.ne.y));
729 selsnap(int mode, int *x, int *y, int direction) {
735 * Snap around if the word wraps around at the end or
736 * beginning of a line.
739 if(direction < 0 && *x <= 0) {
740 if(*y > 0 && term.line[*y - 1][term.col-1].mode
748 if(direction > 0 && *x >= term.col-1) {
749 if(*y < term.row-1 && term.line[*y][*x].mode
758 if(term.line[*y][*x+direction].mode & ATTR_WDUMMY) {
763 if(strchr(worddelimiters,
764 term.line[*y][*x+direction].c[0])) {
773 * Snap around if the the previous line or the current one
774 * has set ATTR_WRAP at its end. Then the whole next or
775 * previous line will be selected.
777 *x = (direction < 0) ? 0 : term.col - 1;
778 if(direction < 0 && *y > 0) {
779 for(; *y > 0; *y += direction) {
780 if(!(term.line[*y-1][term.col-1].mode
785 } else if(direction > 0 && *y < term.row-1) {
786 for(; *y < term.row; *y += direction) {
787 if(!(term.line[*y][term.col-1].mode
796 * Select the whole line when the end of line is reached.
800 while(--i > 0 && term.line[*y][i].c[0] == ' ')
810 getbuttoninfo(XEvent *e) {
812 uint state = e->xbutton.state &~Button1Mask;
814 sel.alt = IS_SET(MODE_ALTSCREEN);
816 sel.oe.x = x2col(e->xbutton.x);
817 sel.oe.y = y2row(e->xbutton.y);
819 if(sel.ob.y < sel.oe.y
820 || (sel.ob.y == sel.oe.y && sel.ob.x < sel.oe.x)) {
821 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
822 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
824 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, -1);
825 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, +1);
829 sel.type = SEL_REGULAR;
830 for(type = 1; type < LEN(selmasks); ++type) {
831 if(match(selmasks[type], state)) {
839 mousereport(XEvent *e) {
840 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
841 button = e->xbutton.button, state = e->xbutton.state,
847 if(e->xbutton.type == MotionNotify) {
848 if(x == ox && y == oy)
850 if(!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
852 /* MOUSE_MOTION: no reporting if no button is pressed */
853 if(IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
856 button = oldbutton + 32;
860 if(!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
867 if(e->xbutton.type == ButtonPress) {
871 } else if(e->xbutton.type == ButtonRelease) {
873 /* MODE_MOUSEX10: no button release reporting */
874 if(IS_SET(MODE_MOUSEX10))
879 if(!IS_SET(MODE_MOUSEX10)) {
880 button += (state & ShiftMask ? 4 : 0)
881 + (state & Mod4Mask ? 8 : 0)
882 + (state & ControlMask ? 16 : 0);
886 if(IS_SET(MODE_MOUSESGR)) {
887 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
889 e->xbutton.type == ButtonRelease ? 'm' : 'M');
890 } else if(x < 223 && y < 223) {
891 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
892 32+button, 32+x+1, 32+y+1);
905 if(IS_SET(MODE_MOUSE)) {
910 for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
911 if(e->xbutton.button == mk->b
912 && match(mk->mask, e->xbutton.state)) {
913 ttysend(mk->s, strlen(mk->s));
918 if(e->xbutton.button == Button1) {
919 gettimeofday(&now, NULL);
921 /* Clear previous selection, logically and visually. */
924 sel.type = SEL_REGULAR;
925 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
926 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
929 * If the user clicks below predefined timeouts specific
930 * snapping behaviour is exposed.
932 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
933 sel.snap = SNAP_LINE;
934 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
935 sel.snap = SNAP_WORD;
939 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
940 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
944 * Draw selection, unless it's regular and we don't want to
945 * make clicks visible
949 tsetdirt(sel.nb.y, sel.ne.y);
951 sel.tclick2 = sel.tclick1;
959 int x, y, bufsize, size, i, ex;
965 bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
966 ptr = str = xmalloc(bufsize);
968 /* append every set & selected glyph to the selection */
969 for(y = sel.nb.y; y < sel.ne.y + 1; y++) {
970 gp = &term.line[y][0];
971 last = &gp[term.col-1];
973 while(last >= gp && !(selected(last - gp, y) &&
974 strcmp(last->c, " ") != 0)) {
978 for(x = 0; gp <= last; x++, ++gp) {
979 if(!selected(x, y) || (gp->mode & ATTR_WDUMMY))
982 size = utf8size(gp->c);
983 memcpy(ptr, gp->c, size);
988 * Copy and pasting of line endings is inconsistent
989 * in the inconsistent terminal and GUI world.
990 * The best solution seems like to produce '\n' when
991 * something is copied from st and convert '\n' to
992 * '\r', when something to be pasted is received by
994 * FIXME: Fix the computer world.
996 if(y < sel.ne.y && x > 0 && !((gp-1)->mode & ATTR_WRAP))
1000 * If the last selected line expands in the selection
1001 * after the visible text '\n' is appended.
1005 while(--i > 0 && term.line[y][i].c[0] == ' ')
1008 if(sel.nb.y == sel.ne.y && sel.ne.x < sel.nb.x)
1020 selnotify(XEvent *e) {
1021 ulong nitems, ofs, rem;
1023 uchar *data, *last, *repl;
1028 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
1029 False, AnyPropertyType, &type, &format,
1030 &nitems, &rem, &data)) {
1031 fprintf(stderr, "Clipboard allocation failed\n");
1036 * As seen in selcopy:
1037 * Line endings are inconsistent in the terminal and GUI world
1038 * copy and pasting. When receiving some selection data,
1039 * replace all '\n' with '\r'.
1040 * FIXME: Fix the computer world.
1043 last = data + nitems * format / 8;
1044 while((repl = memchr(repl, '\n', last - repl))) {
1048 if(IS_SET(MODE_BRCKTPASTE))
1049 ttywrite("\033[200~", 6);
1050 ttysend((char *)data, nitems * format / 8);
1051 if(IS_SET(MODE_BRCKTPASTE))
1052 ttywrite("\033[201~", 6);
1054 /* number of 32-bit chunks returned */
1055 ofs += nitems * format / 32;
1060 selpaste(const Arg *dummy) {
1061 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1062 xw.win, CurrentTime);
1066 clippaste(const Arg *dummy) {
1069 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1070 XConvertSelection(xw.dpy, clipboard, sel.xtarget, XA_PRIMARY,
1071 xw.win, CurrentTime);
1075 selclear(XEvent *e) {
1079 tsetdirt(sel.nb.y, sel.ne.y);
1083 selrequest(XEvent *e) {
1084 XSelectionRequestEvent *xsre;
1085 XSelectionEvent xev;
1086 Atom xa_targets, string;
1088 xsre = (XSelectionRequestEvent *) e;
1089 xev.type = SelectionNotify;
1090 xev.requestor = xsre->requestor;
1091 xev.selection = xsre->selection;
1092 xev.target = xsre->target;
1093 xev.time = xsre->time;
1095 xev.property = None;
1097 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1098 if(xsre->target == xa_targets) {
1099 /* respond with the supported type */
1100 string = sel.xtarget;
1101 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1102 XA_ATOM, 32, PropModeReplace,
1103 (uchar *) &string, 1);
1104 xev.property = xsre->property;
1105 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
1106 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1107 xsre->target, 8, PropModeReplace,
1108 (uchar *) sel.clip, strlen(sel.clip));
1109 xev.property = xsre->property;
1112 /* all done, send a notification to the listener */
1113 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
1114 fprintf(stderr, "Error sending SelectionNotify event\n");
1118 xsetsel(char *str) {
1119 /* register the selection for both the clipboard and the primary */
1125 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
1127 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1128 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1132 brelease(XEvent *e) {
1133 if(IS_SET(MODE_MOUSE)) {
1138 if(e->xbutton.button == Button2) {
1140 } else if(e->xbutton.button == Button1) {
1148 tsetdirt(sel.nb.y, sel.ne.y);
1153 bmotion(XEvent *e) {
1154 int oldey, oldex, oldsby, oldsey;
1156 if(IS_SET(MODE_MOUSE)) {
1171 if(oldey != sel.oe.y || oldex != sel.oe.x)
1172 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1176 die(const char *errstr, ...) {
1179 va_start(ap, errstr);
1180 vfprintf(stderr, errstr, ap);
1188 char *envshell = getenv("SHELL");
1189 const struct passwd *pass = getpwuid(getuid());
1190 char buf[sizeof(long) * 8 + 1];
1192 unsetenv("COLUMNS");
1194 unsetenv("TERMCAP");
1197 setenv("LOGNAME", pass->pw_name, 1);
1198 setenv("USER", pass->pw_name, 1);
1199 setenv("SHELL", pass->pw_shell, 0);
1200 setenv("HOME", pass->pw_dir, 0);
1203 snprintf(buf, sizeof(buf), "%lu", xw.win);
1204 setenv("WINDOWID", buf, 1);
1206 signal(SIGCHLD, SIG_DFL);
1207 signal(SIGHUP, SIG_DFL);
1208 signal(SIGINT, SIG_DFL);
1209 signal(SIGQUIT, SIG_DFL);
1210 signal(SIGTERM, SIG_DFL);
1211 signal(SIGALRM, SIG_DFL);
1213 DEFAULT(envshell, shell);
1214 setenv("TERM", termname, 1);
1215 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
1216 execvp(args[0], args);
1224 if(waitpid(pid, &stat, 0) < 0)
1225 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
1227 if(WIFEXITED(stat)) {
1228 exit(WEXITSTATUS(stat));
1237 struct winsize w = {term.row, term.col, 0, 0};
1239 /* seems to work fine on linux, openbsd and freebsd */
1240 if(openpty(&m, &s, NULL, NULL, &w) < 0)
1241 die("openpty failed: %s\n", SERRNO);
1243 switch(pid = fork()) {
1245 die("fork failed\n");
1248 setsid(); /* create a new process group */
1249 dup2(s, STDIN_FILENO);
1250 dup2(s, STDOUT_FILENO);
1251 dup2(s, STDERR_FILENO);
1252 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1253 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
1261 signal(SIGCHLD, sigchld);
1263 term.mode |= MODE_PRINT;
1264 iofd = (!strcmp(opt_io, "-")) ?
1266 open(opt_io, O_WRONLY | O_CREAT, 0666);
1268 fprintf(stderr, "Error opening %s:%s\n",
1269 opt_io, strerror(errno));
1279 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1281 fprintf(stderr, "\n");
1286 static char buf[BUFSIZ];
1287 static int buflen = 0;
1290 int charsize; /* size of utf8 char in bytes */
1294 /* append read bytes to unprocessed bytes */
1295 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1296 die("Couldn't read from shell: %s\n", SERRNO);
1298 /* process every complete utf8 char */
1301 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1302 charsize = utf8decode(ptr, &utf8c);
1303 utf8encode(&utf8c, s);
1309 /* keep any uncomplete utf8 char for the next call */
1310 memmove(buf, ptr, buflen);
1314 ttywrite(const char *s, size_t n) {
1315 if(write(cmdfd, s, n) == -1)
1316 die("write error on tty: %s\n", SERRNO);
1320 ttysend(char *s, size_t n) {
1322 if(IS_SET(MODE_ECHO))
1330 w.ws_row = term.row;
1331 w.ws_col = term.col;
1332 w.ws_xpixel = xw.tw;
1333 w.ws_ypixel = xw.th;
1334 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1335 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1339 tattrset(int attr) {
1342 for(i = 0; i < term.row-1; i++) {
1343 for(j = 0; j < term.col-1; j++) {
1344 if(term.line[i][j].mode & attr)
1353 tsetdirt(int top, int bot) {
1356 LIMIT(top, 0, term.row-1);
1357 LIMIT(bot, 0, term.row-1);
1359 for(i = top; i <= bot; i++)
1364 tsetdirtattr(int attr) {
1367 for(i = 0; i < term.row-1; i++) {
1368 for(j = 0; j < term.col-1; j++) {
1369 if(term.line[i][j].mode & attr) {
1379 tsetdirt(0, term.row-1);
1384 static TCursor c[2];
1385 bool alt = IS_SET(MODE_ALTSCREEN);
1387 if(mode == CURSOR_SAVE) {
1389 } else if(mode == CURSOR_LOAD) {
1391 tmoveto(c[alt].x, c[alt].y);
1399 term.c = (TCursor){{
1403 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1405 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1406 for(i = tabspaces; i < term.col; i += tabspaces)
1409 term.bot = term.row - 1;
1410 term.mode = MODE_WRAP;
1411 memset(term.trantbl, sizeof(term.trantbl), CS_USA);
1414 tclearregion(0, 0, term.col-1, term.row-1);
1416 tcursor(CURSOR_SAVE);
1420 tnew(int col, int row) {
1421 term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
1430 Line *tmp = term.line;
1432 term.line = term.alt;
1434 term.mode ^= MODE_ALTSCREEN;
1439 tscrolldown(int orig, int n) {
1443 LIMIT(n, 0, term.bot-orig+1);
1445 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1447 for(i = term.bot; i >= orig+n; i--) {
1448 temp = term.line[i];
1449 term.line[i] = term.line[i-n];
1450 term.line[i-n] = temp;
1453 term.dirty[i-n] = 1;
1460 tscrollup(int orig, int n) {
1463 LIMIT(n, 0, term.bot-orig+1);
1465 tclearregion(0, orig, term.col-1, orig+n-1);
1467 for(i = orig; i <= term.bot-n; i++) {
1468 temp = term.line[i];
1469 term.line[i] = term.line[i+n];
1470 term.line[i+n] = temp;
1473 term.dirty[i+n] = 1;
1476 selscroll(orig, -n);
1480 selscroll(int orig, int n) {
1484 if(BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1485 if((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1489 if(sel.type == SEL_RECTANGULAR) {
1490 if(sel.ob.y < term.top)
1491 sel.ob.y = term.top;
1492 if(sel.oe.y > term.bot)
1493 sel.oe.y = term.bot;
1495 if(sel.ob.y < term.top) {
1496 sel.ob.y = term.top;
1499 if(sel.oe.y > term.bot) {
1500 sel.oe.y = term.bot;
1501 sel.oe.x = term.col;
1509 tnewline(int first_col) {
1513 tscrollup(term.top, 1);
1517 tmoveto(first_col ? 0 : term.c.x, y);
1522 char *p = csiescseq.buf, *np;
1531 csiescseq.buf[csiescseq.len] = '\0';
1532 while(p < csiescseq.buf+csiescseq.len) {
1534 v = strtol(p, &np, 10);
1537 if(v == LONG_MAX || v == LONG_MIN)
1539 csiescseq.arg[csiescseq.narg++] = v;
1541 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1545 csiescseq.mode = *p;
1548 /* for absolute user moves, when decom is set */
1550 tmoveato(int x, int y) {
1551 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1555 tmoveto(int x, int y) {
1558 if(term.c.state & CURSOR_ORIGIN) {
1563 maxy = term.row - 1;
1565 LIMIT(x, 0, term.col-1);
1566 LIMIT(y, miny, maxy);
1567 term.c.state &= ~CURSOR_WRAPNEXT;
1573 tsetchar(char *c, Glyph *attr, int x, int y) {
1574 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1575 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1576 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1577 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1578 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1579 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1580 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1581 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1582 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1586 * The table is proudly stolen from rxvt.
1588 if(attr->mode & ATTR_GFX) {
1589 if(c[0] >= 0x41 && c[0] <= 0x7e
1590 && vt100_0[c[0] - 0x41]) {
1591 c = vt100_0[c[0] - 0x41];
1595 if(term.line[y][x].mode & ATTR_WIDE) {
1596 if(x+1 < term.col) {
1597 term.line[y][x+1].c[0] = ' ';
1598 term.line[y][x+1].mode &= ~ATTR_WDUMMY;
1600 } else if(term.line[y][x].mode & ATTR_WDUMMY) {
1601 term.line[y][x-1].c[0] = ' ';
1602 term.line[y][x-1].mode &= ~ATTR_WIDE;
1606 term.line[y][x] = *attr;
1607 memcpy(term.line[y][x].c, c, UTF_SIZ);
1611 tclearregion(int x1, int y1, int x2, int y2) {
1615 temp = x1, x1 = x2, x2 = temp;
1617 temp = y1, y1 = y2, y2 = temp;
1619 LIMIT(x1, 0, term.col-1);
1620 LIMIT(x2, 0, term.col-1);
1621 LIMIT(y1, 0, term.row-1);
1622 LIMIT(y2, 0, term.row-1);
1624 for(y = y1; y <= y2; y++) {
1626 for(x = x1; x <= x2; x++) {
1629 term.line[y][x] = term.c.attr;
1630 memcpy(term.line[y][x].c, " ", 2);
1636 tdeletechar(int n) {
1637 int src = term.c.x + n;
1639 int size = term.col - src;
1641 term.dirty[term.c.y] = 1;
1643 if(src >= term.col) {
1644 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1648 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1649 size * sizeof(Glyph));
1650 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1654 tinsertblank(int n) {
1657 int size = term.col - dst;
1659 term.dirty[term.c.y] = 1;
1661 if(dst >= term.col) {
1662 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1666 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1667 size * sizeof(Glyph));
1668 tclearregion(src, term.c.y, dst - 1, term.c.y);
1672 tinsertblankline(int n) {
1673 if(term.c.y < term.top || term.c.y > term.bot)
1676 tscrolldown(term.c.y, n);
1680 tdeleteline(int n) {
1681 if(term.c.y < term.top || term.c.y > term.bot)
1684 tscrollup(term.c.y, n);
1688 tdefcolor(int *attr, int *npar, int l) {
1692 switch (attr[*npar + 1]) {
1693 case 2: /* direct colour in RGB space */
1694 if (*npar + 4 >= l) {
1696 "erresc(38): Incorrect number of parameters (%d)\n",
1700 r = attr[*npar + 2];
1701 g = attr[*npar + 3];
1702 b = attr[*npar + 4];
1704 if(!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1705 fprintf(stderr, "erresc: bad rgb color (%d,%d,%d)\n",
1708 idx = TRUECOLOR(r, g, b);
1710 case 5: /* indexed colour */
1711 if (*npar + 2 >= l) {
1713 "erresc(38): Incorrect number of parameters (%d)\n",
1718 if(!BETWEEN(attr[*npar], 0, 255))
1719 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
1723 case 0: /* implemented defined (only foreground) */
1724 case 1: /* transparent */
1725 case 3: /* direct colour in CMY space */
1726 case 4: /* direct colour in CMYK space */
1729 "erresc(38): gfx attr %d unknown\n", attr[*npar]);
1736 tsetattr(int *attr, int l) {
1740 for(i = 0; i < l; i++) {
1743 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE \
1744 | ATTR_BOLD | ATTR_ITALIC \
1746 term.c.attr.fg = defaultfg;
1747 term.c.attr.bg = defaultbg;
1750 term.c.attr.mode |= ATTR_BOLD;
1753 term.c.attr.mode |= ATTR_ITALIC;
1756 term.c.attr.mode |= ATTR_UNDERLINE;
1758 case 5: /* slow blink */
1759 case 6: /* rapid blink */
1760 term.c.attr.mode |= ATTR_BLINK;
1763 term.c.attr.mode |= ATTR_REVERSE;
1767 term.c.attr.mode &= ~ATTR_BOLD;
1770 term.c.attr.mode &= ~ATTR_ITALIC;
1773 term.c.attr.mode &= ~ATTR_UNDERLINE;
1777 term.c.attr.mode &= ~ATTR_BLINK;
1780 term.c.attr.mode &= ~ATTR_REVERSE;
1783 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1784 term.c.attr.fg = idx;
1787 term.c.attr.fg = defaultfg;
1790 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1791 term.c.attr.bg = idx;
1794 term.c.attr.bg = defaultbg;
1797 if(BETWEEN(attr[i], 30, 37)) {
1798 term.c.attr.fg = attr[i] - 30;
1799 } else if(BETWEEN(attr[i], 40, 47)) {
1800 term.c.attr.bg = attr[i] - 40;
1801 } else if(BETWEEN(attr[i], 90, 97)) {
1802 term.c.attr.fg = attr[i] - 90 + 8;
1803 } else if(BETWEEN(attr[i], 100, 107)) {
1804 term.c.attr.bg = attr[i] - 100 + 8;
1807 "erresc(default): gfx attr %d unknown\n",
1808 attr[i]), csidump();
1816 tsetscroll(int t, int b) {
1819 LIMIT(t, 0, term.row-1);
1820 LIMIT(b, 0, term.row-1);
1830 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1833 tsetmode(bool priv, bool set, int *args, int narg) {
1837 for(lim = args + narg; args < lim; ++args) {
1841 case 1: /* DECCKM -- Cursor key */
1842 MODBIT(term.mode, set, MODE_APPCURSOR);
1844 case 5: /* DECSCNM -- Reverse video */
1846 MODBIT(term.mode, set, MODE_REVERSE);
1847 if(mode != term.mode)
1848 redraw(REDRAW_TIMEOUT);
1850 case 6: /* DECOM -- Origin */
1851 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1854 case 7: /* DECAWM -- Auto wrap */
1855 MODBIT(term.mode, set, MODE_WRAP);
1857 case 0: /* Error (IGNORED) */
1858 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1859 case 3: /* DECCOLM -- Column (IGNORED) */
1860 case 4: /* DECSCLM -- Scroll (IGNORED) */
1861 case 8: /* DECARM -- Auto repeat (IGNORED) */
1862 case 18: /* DECPFF -- Printer feed (IGNORED) */
1863 case 19: /* DECPEX -- Printer extent (IGNORED) */
1864 case 42: /* DECNRCM -- National characters (IGNORED) */
1865 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1867 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1868 MODBIT(term.mode, !set, MODE_HIDE);
1870 case 9: /* X10 mouse compatibility mode */
1871 xsetpointermotion(0);
1872 MODBIT(term.mode, 0, MODE_MOUSE);
1873 MODBIT(term.mode, set, MODE_MOUSEX10);
1875 case 1000: /* 1000: report button press */
1876 xsetpointermotion(0);
1877 MODBIT(term.mode, 0, MODE_MOUSE);
1878 MODBIT(term.mode, set, MODE_MOUSEBTN);
1880 case 1002: /* 1002: report motion on button press */
1881 xsetpointermotion(0);
1882 MODBIT(term.mode, 0, MODE_MOUSE);
1883 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1885 case 1003: /* 1003: enable all mouse motions */
1886 xsetpointermotion(set);
1887 MODBIT(term.mode, 0, MODE_MOUSE);
1888 MODBIT(term.mode, set, MODE_MOUSEMANY);
1890 case 1004: /* 1004: send focus events to tty */
1891 MODBIT(term.mode, set, MODE_FOCUS);
1893 case 1006: /* 1006: extended reporting mode */
1894 MODBIT(term.mode, set, MODE_MOUSESGR);
1897 MODBIT(term.mode, set, MODE_8BIT);
1899 case 1049: /* swap screen & set/restore cursor as xterm */
1900 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1901 case 47: /* swap screen */
1903 if (!allowaltscreen)
1905 alt = IS_SET(MODE_ALTSCREEN);
1907 tclearregion(0, 0, term.col-1,
1910 if(set ^ alt) /* set is always 1 or 0 */
1916 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1918 case 2004: /* 2004: bracketed paste mode */
1919 MODBIT(term.mode, set, MODE_BRCKTPASTE);
1921 /* Not implemented mouse modes. See comments there. */
1922 case 1001: /* mouse highlight mode; can hang the
1923 terminal by design when implemented. */
1924 case 1005: /* UTF-8 mouse mode; will confuse
1925 applications not supporting UTF-8
1927 case 1015: /* urxvt mangled mouse mode; incompatible
1928 and can be mistaken for other control
1932 "erresc: unknown private set/reset mode %d\n",
1938 case 0: /* Error (IGNORED) */
1940 case 2: /* KAM -- keyboard action */
1941 MODBIT(term.mode, set, MODE_KBDLOCK);
1943 case 4: /* IRM -- Insertion-replacement */
1944 MODBIT(term.mode, set, MODE_INSERT);
1946 case 12: /* SRM -- Send/Receive */
1947 MODBIT(term.mode, !set, MODE_ECHO);
1949 case 20: /* LNM -- Linefeed/new line */
1950 MODBIT(term.mode, set, MODE_CRLF);
1954 "erresc: unknown set/reset mode %d\n",
1967 switch(csiescseq.mode) {
1970 fprintf(stderr, "erresc: unknown csi ");
1974 case '@': /* ICH -- Insert <n> blank char */
1975 DEFAULT(csiescseq.arg[0], 1);
1976 tinsertblank(csiescseq.arg[0]);
1978 case 'A': /* CUU -- Cursor <n> Up */
1979 DEFAULT(csiescseq.arg[0], 1);
1980 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1982 case 'B': /* CUD -- Cursor <n> Down */
1983 case 'e': /* VPR --Cursor <n> Down */
1984 DEFAULT(csiescseq.arg[0], 1);
1985 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1987 case 'i': /* MC -- Media Copy */
1988 switch(csiescseq.arg[0]) {
1993 tdumpline(term.c.y);
1996 term.mode &= ~MODE_PRINT;
1999 term.mode |= MODE_PRINT;
2003 case 'c': /* DA -- Device Attributes */
2004 if(csiescseq.arg[0] == 0)
2005 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2007 case 'C': /* CUF -- Cursor <n> Forward */
2008 case 'a': /* HPR -- Cursor <n> Forward */
2009 DEFAULT(csiescseq.arg[0], 1);
2010 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
2012 case 'D': /* CUB -- Cursor <n> Backward */
2013 DEFAULT(csiescseq.arg[0], 1);
2014 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
2016 case 'E': /* CNL -- Cursor <n> Down and first col */
2017 DEFAULT(csiescseq.arg[0], 1);
2018 tmoveto(0, term.c.y+csiescseq.arg[0]);
2020 case 'F': /* CPL -- Cursor <n> Up and first col */
2021 DEFAULT(csiescseq.arg[0], 1);
2022 tmoveto(0, term.c.y-csiescseq.arg[0]);
2024 case 'g': /* TBC -- Tabulation clear */
2025 switch(csiescseq.arg[0]) {
2026 case 0: /* clear current tab stop */
2027 term.tabs[term.c.x] = 0;
2029 case 3: /* clear all the tabs */
2030 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
2036 case 'G': /* CHA -- Move to <col> */
2038 DEFAULT(csiescseq.arg[0], 1);
2039 tmoveto(csiescseq.arg[0]-1, term.c.y);
2041 case 'H': /* CUP -- Move to <row> <col> */
2043 DEFAULT(csiescseq.arg[0], 1);
2044 DEFAULT(csiescseq.arg[1], 1);
2045 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
2047 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
2048 DEFAULT(csiescseq.arg[0], 1);
2049 while(csiescseq.arg[0]--)
2052 case 'J': /* ED -- Clear screen */
2054 switch(csiescseq.arg[0]) {
2056 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
2057 if(term.c.y < term.row-1) {
2058 tclearregion(0, term.c.y+1, term.col-1,
2064 tclearregion(0, 0, term.col-1, term.c.y-1);
2065 tclearregion(0, term.c.y, term.c.x, term.c.y);
2068 tclearregion(0, 0, term.col-1, term.row-1);
2074 case 'K': /* EL -- Clear line */
2075 switch(csiescseq.arg[0]) {
2077 tclearregion(term.c.x, term.c.y, term.col-1,
2081 tclearregion(0, term.c.y, term.c.x, term.c.y);
2084 tclearregion(0, term.c.y, term.col-1, term.c.y);
2088 case 'S': /* SU -- Scroll <n> line up */
2089 DEFAULT(csiescseq.arg[0], 1);
2090 tscrollup(term.top, csiescseq.arg[0]);
2092 case 'T': /* SD -- Scroll <n> line down */
2093 DEFAULT(csiescseq.arg[0], 1);
2094 tscrolldown(term.top, csiescseq.arg[0]);
2096 case 'L': /* IL -- Insert <n> blank lines */
2097 DEFAULT(csiescseq.arg[0], 1);
2098 tinsertblankline(csiescseq.arg[0]);
2100 case 'l': /* RM -- Reset Mode */
2101 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2103 case 'M': /* DL -- Delete <n> lines */
2104 DEFAULT(csiescseq.arg[0], 1);
2105 tdeleteline(csiescseq.arg[0]);
2107 case 'X': /* ECH -- Erase <n> char */
2108 DEFAULT(csiescseq.arg[0], 1);
2109 tclearregion(term.c.x, term.c.y,
2110 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2112 case 'P': /* DCH -- Delete <n> char */
2113 DEFAULT(csiescseq.arg[0], 1);
2114 tdeletechar(csiescseq.arg[0]);
2116 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2117 DEFAULT(csiescseq.arg[0], 1);
2118 while(csiescseq.arg[0]--)
2121 case 'd': /* VPA -- Move to <row> */
2122 DEFAULT(csiescseq.arg[0], 1);
2123 tmoveato(term.c.x, csiescseq.arg[0]-1);
2125 case 'h': /* SM -- Set terminal mode */
2126 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2128 case 'm': /* SGR -- Terminal attribute (color) */
2129 tsetattr(csiescseq.arg, csiescseq.narg);
2131 case 'n': /* DSR – Device Status Report (cursor position) */
2132 if (csiescseq.arg[0] == 6) {
2133 len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
2134 term.c.y+1, term.c.x+1);
2138 case 'r': /* DECSTBM -- Set Scrolling Region */
2139 if(csiescseq.priv) {
2142 DEFAULT(csiescseq.arg[0], 1);
2143 DEFAULT(csiescseq.arg[1], term.row);
2144 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2148 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2149 tcursor(CURSOR_SAVE);
2151 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2152 tcursor(CURSOR_LOAD);
2163 for(i = 0; i < csiescseq.len; i++) {
2164 c = csiescseq.buf[i] & 0xff;
2167 } else if(c == '\n') {
2169 } else if(c == '\r') {
2171 } else if(c == 0x1b) {
2174 printf("(%02x)", c);
2182 memset(&csiescseq, 0, sizeof(csiescseq));
2191 narg = strescseq.narg;
2192 par = atoi(strescseq.args[0]);
2194 switch(strescseq.type) {
2195 case ']': /* OSC -- Operating System Command */
2201 xsettitle(strescseq.args[1]);
2203 case 4: /* color set */
2206 p = strescseq.args[2];
2208 case 104: /* color reset, here p = NULL */
2209 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2210 if (!xsetcolorname(j, p)) {
2211 fprintf(stderr, "erresc: invalid color %s\n", p);
2214 * TODO if defaultbg color is changed, borders
2222 case 'k': /* old title set compatibility */
2223 xsettitle(strescseq.args[0]);
2225 case 'P': /* DSC -- Device Control String */
2226 case '_': /* APC -- Application Program Command */
2227 case '^': /* PM -- Privacy Message */
2231 fprintf(stderr, "erresc: unknown str ");
2237 char *p = strescseq.buf;
2240 strescseq.buf[strescseq.len] = '\0';
2241 while(p && strescseq.narg < STR_ARG_SIZ)
2242 strescseq.args[strescseq.narg++] = strsep(&p, ";");
2250 printf("ESC%c", strescseq.type);
2251 for(i = 0; i < strescseq.len; i++) {
2252 c = strescseq.buf[i] & 0xff;
2255 } else if(isprint(c)) {
2257 } else if(c == '\n') {
2259 } else if(c == '\r') {
2261 } else if(c == 0x1b) {
2264 printf("(%02x)", c);
2272 memset(&strescseq, 0, sizeof(strescseq));
2276 tprinter(char *s, size_t len) {
2277 if(iofd != -1 && xwrite(iofd, s, len) < 0) {
2278 fprintf(stderr, "Error writing in %s:%s\n",
2279 opt_io, strerror(errno));
2289 bp = &term.line[n][0];
2290 end = &bp[term.col-1];
2291 while(end > bp && !strcmp(" ", end->c))
2293 if(bp != end || strcmp(bp->c, " ")) {
2294 for( ;bp <= end; ++bp)
2295 tprinter(bp->c, strlen(bp->c));
2304 for(i = 0; i < term.row; ++i)
2309 tputtab(bool forward) {
2315 for(++x; x < term.col && !term.tabs[x]; ++x)
2320 for(--x; x > 0 && !term.tabs[x]; --x)
2323 tmoveto(x, term.c.y);
2327 techo(char *buf, int len) {
2328 for(; len > 0; buf++, len--) {
2331 if(c == '\033') { /* escape */
2334 } else if(c < '\x20') { /* control code */
2335 if(c != '\n' && c != '\r' && c != '\t') {
2349 tdeftran(char ascii) {
2351 static char tbl[][2] = {
2352 {'0', CS_GRAPHIC0}, {'1', CS_GRAPHIC1}, {'A', CS_UK},
2353 {'B', CS_USA}, {'<', CS_MULTI}, {'K', CS_GER},
2354 {'5', CS_FIN}, {'C', CS_FIN},
2358 for (bp = &tbl[0]; (c = (*bp)[0]) && c != ascii; ++bp)
2362 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2364 term.trantbl[term.icharset] = (*bp)[1];
2369 if (term.trantbl[term.charset] == CS_GRAPHIC0)
2370 term.c.attr.mode |= ATTR_GFX;
2372 term.c.attr.mode &= ~ATTR_GFX;
2376 tputc(char *c, int len) {
2378 bool control = ascii < '\x20' || ascii == 0177;
2385 utf8decode(c, &u8char);
2386 width = wcwidth(u8char);
2389 if(IS_SET(MODE_PRINT))
2393 * STR sequences must be checked before anything else
2394 * because it can use some control codes as part of the sequence.
2396 if(term.esc & ESC_STR) {
2399 term.esc = ESC_START | ESC_STR_END;
2401 case '\a': /* backwards compatibility to xterm */
2406 if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2407 memmove(&strescseq.buf[strescseq.len], c, len);
2408 strescseq.len += len;
2411 * Here is a bug in terminals. If the user never sends
2412 * some code to stop the str or esc command, then st
2413 * will stop responding. But this is better than
2414 * silently failing with unknown characters. At least
2415 * then users will report back.
2417 * In the case users ever get fixed, here is the code:
2429 * Actions of control codes must be performed as soon they arrive
2430 * because they can be embedded inside a control sequence, and
2431 * they must not cause conflicts with sequences.
2439 tmoveto(term.c.x-1, term.c.y);
2442 tmoveto(0, term.c.y);
2447 /* go to first col if the mode is set */
2448 tnewline(IS_SET(MODE_CRLF));
2450 case '\a': /* BEL */
2451 if(!(xw.state & WIN_FOCUSED))
2454 XBell(xw.dpy, bellvolume);
2456 case '\033': /* ESC */
2458 term.esc = ESC_START;
2460 case '\016': /* SO */
2464 case '\017': /* SI */
2468 case '\032': /* SUB */
2469 case '\030': /* CAN */
2472 case '\005': /* ENQ (IGNORED) */
2473 case '\000': /* NUL (IGNORED) */
2474 case '\021': /* XON (IGNORED) */
2475 case '\023': /* XOFF (IGNORED) */
2476 case 0177: /* DEL (IGNORED) */
2479 } else if(term.esc & ESC_START) {
2480 if(term.esc & ESC_CSI) {
2481 csiescseq.buf[csiescseq.len++] = ascii;
2482 if(BETWEEN(ascii, 0x40, 0x7E)
2483 || csiescseq.len >= \
2484 sizeof(csiescseq.buf)-1) {
2489 } else if(term.esc & ESC_STR_END) {
2493 } else if(term.esc & ESC_ALTCHARSET) {
2497 } else if(term.esc & ESC_TEST) {
2498 if(ascii == '8') { /* DEC screen alignment test. */
2499 char E[UTF_SIZ] = "E";
2502 for(x = 0; x < term.col; ++x) {
2503 for(y = 0; y < term.row; ++y)
2504 tsetchar(E, &term.c.attr, x, y);
2511 term.esc |= ESC_CSI;
2514 term.esc |= ESC_TEST;
2516 case 'P': /* DCS -- Device Control String */
2517 case '_': /* APC -- Application Program Command */
2518 case '^': /* PM -- Privacy Message */
2519 case ']': /* OSC -- Operating System Command */
2520 case 'k': /* old title set compatibility */
2522 strescseq.type = ascii;
2523 term.esc |= ESC_STR;
2525 case '(': /* set primary charset G0 */
2526 case ')': /* set secondary charset G1 */
2527 case '*': /* set tertiary charset G2 */
2528 case '+': /* set quaternary charset G3 */
2529 term.icharset = ascii - '(';
2530 term.esc |= ESC_ALTCHARSET;
2532 case 'D': /* IND -- Linefeed */
2533 if(term.c.y == term.bot) {
2534 tscrollup(term.top, 1);
2536 tmoveto(term.c.x, term.c.y+1);
2540 case 'E': /* NEL -- Next line */
2541 tnewline(1); /* always go to first col */
2544 case 'H': /* HTS -- Horizontal tab stop */
2545 term.tabs[term.c.x] = 1;
2548 case 'M': /* RI -- Reverse index */
2549 if(term.c.y == term.top) {
2550 tscrolldown(term.top, 1);
2552 tmoveto(term.c.x, term.c.y-1);
2556 case 'Z': /* DECID -- Identify Terminal */
2557 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2560 case 'c': /* RIS -- Reset to inital state */
2566 case '=': /* DECPAM -- Application keypad */
2567 term.mode |= MODE_APPKEYPAD;
2570 case '>': /* DECPNM -- Normal keypad */
2571 term.mode &= ~MODE_APPKEYPAD;
2574 case '7': /* DECSC -- Save Cursor */
2575 tcursor(CURSOR_SAVE);
2578 case '8': /* DECRC -- Restore Cursor */
2579 tcursor(CURSOR_LOAD);
2582 case '\\': /* ST -- Stop */
2586 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2587 (uchar) ascii, isprint(ascii)? ascii:'.');
2592 * All characters which form part of a sequence are not
2598 * Display control codes only if we are in graphic mode
2600 if(control && !(term.c.attr.mode & ATTR_GFX))
2602 if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2604 if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2605 term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
2609 if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2610 memmove(&term.line[term.c.y][term.c.x+1],
2611 &term.line[term.c.y][term.c.x],
2612 (term.col - term.c.x - 1) * sizeof(Glyph));
2615 if(term.c.x+width > term.col)
2618 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2621 term.line[term.c.y][term.c.x].mode |= ATTR_WIDE;
2622 if(term.c.x+1 < term.col) {
2623 term.line[term.c.y][term.c.x+1].c[0] = '\0';
2624 term.line[term.c.y][term.c.x+1].mode = ATTR_WDUMMY;
2627 if(term.c.x+width < term.col) {
2628 tmoveto(term.c.x+width, term.c.y);
2630 term.c.state |= CURSOR_WRAPNEXT;
2635 tresize(int col, int row) {
2637 int minrow = MIN(row, term.row);
2638 int mincol = MIN(col, term.col);
2639 int slide = term.c.y - row + 1;
2643 if(col < 1 || row < 1)
2646 /* free unneeded rows */
2650 * slide screen to keep cursor where we expect it -
2651 * tscrollup would work here, but we can optimize to
2652 * memmove because we're freeing the earlier lines
2654 for(/* i = 0 */; i < slide; i++) {
2658 memmove(term.line, term.line + slide, row * sizeof(Line));
2659 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2661 for(i += row; i < term.row; i++) {
2666 /* resize to new height */
2667 term.line = xrealloc(term.line, row * sizeof(Line));
2668 term.alt = xrealloc(term.alt, row * sizeof(Line));
2669 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2670 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2672 /* resize each row to new width, zero-pad if needed */
2673 for(i = 0; i < minrow; i++) {
2675 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2676 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2679 /* allocate any new rows */
2680 for(/* i == minrow */; i < row; i++) {
2682 term.line[i] = xmalloc(col * sizeof(Glyph));
2683 term.alt[i] = xmalloc(col * sizeof(Glyph));
2685 if(col > term.col) {
2686 bp = term.tabs + term.col;
2688 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2689 while(--bp > term.tabs && !*bp)
2691 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2694 /* update terminal size */
2697 /* reset scrolling region */
2698 tsetscroll(0, row-1);
2699 /* make use of the LIMIT in tmoveto */
2700 tmoveto(term.c.x, term.c.y);
2701 /* Clearing both screens */
2704 if(mincol < col && 0 < minrow) {
2705 tclearregion(mincol, 0, col - 1, minrow - 1);
2707 if(0 < col && minrow < row) {
2708 tclearregion(0, minrow, col - 1, row - 1);
2711 } while(orig != term.line);
2717 xresize(int col, int row) {
2718 xw.tw = MAX(1, col * xw.cw);
2719 xw.th = MAX(1, row * xw.ch);
2721 XFreePixmap(xw.dpy, xw.buf);
2722 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2723 DefaultDepth(xw.dpy, xw.scr));
2724 XftDrawChange(xw.draw, xw.buf);
2725 xclear(0, 0, xw.w, xw.h);
2728 static inline ushort
2729 sixd_to_16bit(int x) {
2730 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2736 XRenderColor color = { .alpha = 0xffff };
2741 for (cp = dc.col; cp < dc.col + LEN(dc.col); ++cp)
2742 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
2745 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2746 for(i = 0; i < LEN(colorname); i++) {
2749 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2750 die("Could not allocate color '%s'\n", colorname[i]);
2754 /* load colors [16-255] ; same colors as xterm */
2755 for(i = 16, r = 0; r < 6; r++) {
2756 for(g = 0; g < 6; g++) {
2757 for(b = 0; b < 6; b++) {
2758 color.red = sixd_to_16bit(r);
2759 color.green = sixd_to_16bit(g);
2760 color.blue = sixd_to_16bit(b);
2761 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2762 die("Could not allocate color %d\n", i);
2769 for(r = 0; r < 24; r++, i++) {
2770 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2771 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2773 die("Could not allocate color %d\n", i);
2780 xsetcolorname(int x, const char *name) {
2781 XRenderColor color = { .alpha = 0xffff };
2783 if (x < 0 || x > LEN(colorname))
2786 if(16 <= x && x < 16 + 216) {
2787 int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2788 color.red = sixd_to_16bit(r);
2789 color.green = sixd_to_16bit(g);
2790 color.blue = sixd_to_16bit(b);
2791 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2792 return 0; /* something went wrong */
2795 } else if (16 + 216 <= x && x < 256) {
2796 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2797 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2798 return 0; /* something went wrong */
2802 name = colorname[x];
2805 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2812 xtermclear(int col1, int row1, int col2, int row2) {
2813 XftDrawRect(xw.draw,
2814 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2815 borderpx + col1 * xw.cw,
2816 borderpx + row1 * xw.ch,
2817 (col2-col1+1) * xw.cw,
2818 (row2-row1+1) * xw.ch);
2822 * Absolute coordinates.
2825 xclear(int x1, int y1, int x2, int y2) {
2826 XftDrawRect(xw.draw,
2827 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2828 x1, y1, x2-x1, y2-y1);
2833 XClassHint class = {opt_class ? opt_class : termname, termname};
2834 XWMHints wm = {.flags = InputHint, .input = 1};
2835 XSizeHints *sizeh = NULL;
2837 sizeh = XAllocSizeHints();
2838 if(xw.isfixed == False) {
2839 sizeh->flags = PSize | PResizeInc | PBaseSize;
2840 sizeh->height = xw.h;
2841 sizeh->width = xw.w;
2842 sizeh->height_inc = xw.ch;
2843 sizeh->width_inc = xw.cw;
2844 sizeh->base_height = 2 * borderpx;
2845 sizeh->base_width = 2 * borderpx;
2847 sizeh->flags = PMaxSize | PMinSize;
2848 sizeh->min_width = sizeh->max_width = xw.fw;
2849 sizeh->min_height = sizeh->max_height = xw.fh;
2852 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2857 xloadfont(Font *f, FcPattern *pattern) {
2861 match = FcFontMatch(NULL, pattern, &result);
2865 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2866 FcPatternDestroy(match);
2871 f->pattern = FcPatternDuplicate(pattern);
2873 f->ascent = f->match->ascent;
2874 f->descent = f->match->descent;
2876 f->rbearing = f->match->max_advance_width;
2878 f->height = f->ascent + f->descent;
2879 f->width = f->lbearing + f->rbearing;
2885 xloadfonts(char *fontstr, double fontsize) {
2887 FcResult r_sz, r_psz;
2890 if(fontstr[0] == '-') {
2891 pattern = XftXlfdParse(fontstr, False, False);
2893 pattern = FcNameParse((FcChar8 *)fontstr);
2897 die("st: can't open font %s\n", fontstr);
2900 FcPatternDel(pattern, FC_PIXEL_SIZE);
2901 FcPatternDel(pattern, FC_SIZE);
2902 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2903 usedfontsize = fontsize;
2905 r_psz = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2906 r_sz = FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval);
2907 if(r_psz == FcResultMatch) {
2908 usedfontsize = fontval;
2909 } else if(r_sz == FcResultMatch) {
2913 * Default font size is 12, if none given. This is to
2914 * have a known usedfontsize value.
2916 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2921 FcConfigSubstitute(0, pattern, FcMatchPattern);
2922 FcDefaultSubstitute(pattern);
2924 if(xloadfont(&dc.font, pattern))
2925 die("st: can't open font %s\n", fontstr);
2927 if(usedfontsize < 0) {
2928 FcPatternGetDouble(dc.font.match->pattern,
2929 FC_PIXEL_SIZE, 0, &fontval);
2930 usedfontsize = fontval;
2933 /* Setting character width and height. */
2934 xw.cw = CEIL(dc.font.width * cwscale);
2935 xw.ch = CEIL(dc.font.height * chscale);
2937 FcPatternDel(pattern, FC_SLANT);
2938 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2939 if(xloadfont(&dc.ifont, pattern))
2940 die("st: can't open font %s\n", fontstr);
2942 FcPatternDel(pattern, FC_WEIGHT);
2943 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2944 if(xloadfont(&dc.ibfont, pattern))
2945 die("st: can't open font %s\n", fontstr);
2947 FcPatternDel(pattern, FC_SLANT);
2948 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2949 if(xloadfont(&dc.bfont, pattern))
2950 die("st: can't open font %s\n", fontstr);
2952 FcPatternDestroy(pattern);
2956 xloadfontset(Font *f) {
2959 if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
2965 xunloadfont(Font *f) {
2966 XftFontClose(xw.dpy, f->match);
2967 FcPatternDestroy(f->pattern);
2969 FcFontSetDestroy(f->set);
2973 xunloadfonts(void) {
2976 /* Free the loaded fonts in the font cache. */
2977 for(i = 0; i < frclen; i++) {
2978 XftFontClose(xw.dpy, frc[i].font);
2982 xunloadfont(&dc.font);
2983 xunloadfont(&dc.bfont);
2984 xunloadfont(&dc.ifont);
2985 xunloadfont(&dc.ibfont);
2989 xzoom(const Arg *arg) {
2991 xloadfonts(usedfont, usedfontsize + arg->i);
3002 pid_t thispid = getpid();
3004 if(!(xw.dpy = XOpenDisplay(NULL)))
3005 die("Can't open display\n");
3006 xw.scr = XDefaultScreen(xw.dpy);
3007 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
3011 die("Could not init fontconfig.\n");
3013 usedfont = (opt_font == NULL)? font : opt_font;
3014 xloadfonts(usedfont, 0);
3017 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
3020 /* adjust fixed window geometry */
3022 sw = DisplayWidth(xw.dpy, xw.scr);
3023 sh = DisplayHeight(xw.dpy, xw.scr);
3025 xw.fx = sw + xw.fx - xw.fw - 1;
3027 xw.fy = sh + xw.fy - xw.fh - 1;
3032 /* window - default size */
3033 xw.h = 2 * borderpx + term.row * xw.ch;
3034 xw.w = 2 * borderpx + term.col * xw.cw;
3040 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
3041 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
3042 xw.attrs.bit_gravity = NorthWestGravity;
3043 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
3044 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
3045 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
3046 xw.attrs.colormap = xw.cmap;
3048 parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
3049 XRootWindow(xw.dpy, xw.scr);
3050 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
3051 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
3052 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
3053 | CWEventMask | CWColormap, &xw.attrs);
3055 memset(&gcvalues, 0, sizeof(gcvalues));
3056 gcvalues.graphics_exposures = False;
3057 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
3059 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3060 DefaultDepth(xw.dpy, xw.scr));
3061 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
3062 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
3064 /* Xft rendering context */
3065 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
3068 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3069 XSetLocaleModifiers("@im=local");
3070 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3071 XSetLocaleModifiers("@im=");
3072 if((xw.xim = XOpenIM(xw.dpy,
3073 NULL, NULL, NULL)) == NULL) {
3074 die("XOpenIM failed. Could not open input"
3079 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
3080 | XIMStatusNothing, XNClientWindow, xw.win,
3081 XNFocusWindow, xw.win, NULL);
3083 die("XCreateIC failed. Could not obtain input method.\n");
3085 /* white cursor, black outline */
3086 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
3087 XDefineCursor(xw.dpy, xw.win, cursor);
3088 XRecolorCursor(xw.dpy, cursor,
3089 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
3090 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
3092 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
3093 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
3094 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
3095 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
3097 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
3098 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
3099 PropModeReplace, (unsigned char *)&thispid, 1);
3102 XMapWindow(xw.dpy, xw.win);
3108 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
3109 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
3110 width = charlen * xw.cw, xp, i;
3112 int u8fl, u8fblen, u8cblen, doesexist;
3115 Font *font = &dc.font;
3117 FcPattern *fcpattern, *fontpattern;
3118 FcFontSet *fcsets[] = { NULL };
3119 FcCharSet *fccharset;
3120 Colour *fg, *bg, *temp, revfg, revbg, truefg, truebg;
3121 XRenderColor colfg, colbg;
3125 frcflags = FRC_NORMAL;
3127 if(base.mode & ATTR_ITALIC) {
3128 if(base.fg == defaultfg)
3129 base.fg = defaultitalic;
3131 frcflags = FRC_ITALIC;
3132 } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
3133 if(base.fg == defaultfg)
3134 base.fg = defaultitalic;
3136 frcflags = FRC_ITALICBOLD;
3137 } else if(base.mode & ATTR_UNDERLINE) {
3138 if(base.fg == defaultfg)
3139 base.fg = defaultunderline;
3141 if(IS_TRUECOL(base.fg)) {
3142 colfg.alpha = 0xffff;
3143 colfg.red = TRUERED(base.fg);
3144 colfg.green = TRUEGREEN(base.fg);
3145 colfg.blue = TRUEBLUE(base.fg);
3146 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
3149 fg = &dc.col[base.fg];
3152 if(IS_TRUECOL(base.bg)) {
3153 colbg.alpha = 0xffff;
3154 colbg.green = TRUEGREEN(base.bg);
3155 colbg.red = TRUERED(base.bg);
3156 colbg.blue = TRUEBLUE(base.bg);
3157 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
3160 bg = &dc.col[base.bg];
3165 if(base.mode & ATTR_BOLD) {
3166 if(BETWEEN(base.fg, 0, 7)) {
3167 /* basic system colors */
3168 fg = &dc.col[base.fg + 8];
3169 } else if(BETWEEN(base.fg, 16, 195)) {
3171 fg = &dc.col[base.fg + 36];
3172 } else if(BETWEEN(base.fg, 232, 251)) {
3174 fg = &dc.col[base.fg + 4];
3177 * Those ranges will not be brightened:
3178 * 8 - 15 – bright system colors
3179 * 196 - 231 – highest 256 color cube
3180 * 252 - 255 – brightest colors in greyscale
3183 frcflags = FRC_BOLD;
3186 if(IS_SET(MODE_REVERSE)) {
3187 if(fg == &dc.col[defaultfg]) {
3188 fg = &dc.col[defaultbg];
3190 colfg.red = ~fg->color.red;
3191 colfg.green = ~fg->color.green;
3192 colfg.blue = ~fg->color.blue;
3193 colfg.alpha = fg->color.alpha;
3194 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
3198 if(bg == &dc.col[defaultbg]) {
3199 bg = &dc.col[defaultfg];
3201 colbg.red = ~bg->color.red;
3202 colbg.green = ~bg->color.green;
3203 colbg.blue = ~bg->color.blue;
3204 colbg.alpha = bg->color.alpha;
3205 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
3210 if(base.mode & ATTR_REVERSE) {
3216 if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3219 /* Intelligent cleaning up of the borders. */
3221 xclear(0, (y == 0)? 0 : winy, borderpx,
3222 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3224 if(x + charlen >= term.col) {
3225 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3226 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3229 xclear(winx, 0, winx + width, borderpx);
3231 xclear(winx, winy + xw.ch, winx + width, xw.h);
3233 /* Clean up the region we want to draw to. */
3234 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3236 /* Set the clip region because Xft is sometimes dirty. */
3241 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3243 for(xp = winx; bytelen > 0;) {
3245 * Search for the range in the to be printed string of glyphs
3246 * that are in the main font. Then print that range. If
3247 * some glyph is found that is not in the font, do the
3253 oneatatime = font->width != xw.cw;
3256 u8cblen = utf8decode(s, &u8char);
3260 doesexist = XftCharExists(xw.dpy, font->match, u8char);
3261 if(oneatatime || !doesexist || bytelen <= 0) {
3262 if(oneatatime || bytelen <= 0) {
3270 XftDrawStringUtf8(xw.draw, fg,
3272 winy + font->ascent,
3290 /* Search the font cache. */
3291 for(i = 0; i < frclen; i++) {
3292 if(XftCharExists(xw.dpy, frc[i].font, u8char)
3293 && frc[i].flags == frcflags) {
3298 /* Nothing was found. */
3302 fcsets[0] = font->set;
3305 * Nothing was found in the cache. Now use
3306 * some dozen of Fontconfig calls to get the
3307 * font for one single character.
3309 fcpattern = FcPatternDuplicate(font->pattern);
3310 fccharset = FcCharSetCreate();
3312 FcCharSetAddChar(fccharset, u8char);
3313 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3315 FcPatternAddBool(fcpattern, FC_SCALABLE,
3318 FcConfigSubstitute(0, fcpattern,
3320 FcDefaultSubstitute(fcpattern);
3322 fontpattern = FcFontSetMatch(0, fcsets,
3323 FcTrue, fcpattern, &fcres);
3326 * Overwrite or create the new cache entry.
3328 if(frclen >= LEN(frc)) {
3329 frclen = LEN(frc) - 1;
3330 XftFontClose(xw.dpy, frc[frclen].font);
3333 frc[frclen].font = XftFontOpenPattern(xw.dpy,
3335 frc[frclen].flags = frcflags;
3340 FcPatternDestroy(fcpattern);
3341 FcCharSetDestroy(fccharset);
3344 XftDrawStringUtf8(xw.draw, fg, frc[i].font,
3345 xp, winy + frc[i].font->ascent,
3346 (FcChar8 *)u8c, u8cblen);
3348 xp += xw.cw * wcwidth(u8char);
3352 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
3353 winy + font->ascent, (FcChar8 *)s, bytelen);
3356 if(base.mode & ATTR_UNDERLINE) {
3357 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
3361 /* Reset clip to none. */
3362 XftDrawSetClip(xw.draw, 0);
3367 static int oldx = 0, oldy = 0;
3368 int sl, width, curx;
3369 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
3371 LIMIT(oldx, 0, term.col-1);
3372 LIMIT(oldy, 0, term.row-1);
3376 /* adjust position if in dummy */
3377 if(term.line[oldy][oldx].mode & ATTR_WDUMMY)
3379 if(term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3382 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
3384 /* remove the old cursor */
3385 sl = utf8size(term.line[oldy][oldx].c);
3386 width = (term.line[oldy][oldx].mode & ATTR_WIDE)? 2 : 1;
3387 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
3390 /* draw the new one */
3391 if(!(IS_SET(MODE_HIDE))) {
3392 if(xw.state & WIN_FOCUSED) {
3393 if(IS_SET(MODE_REVERSE)) {
3394 g.mode |= ATTR_REVERSE;
3400 width = (term.line[term.c.y][curx].mode & ATTR_WIDE)\
3402 xdraws(g.c, g, term.c.x, term.c.y, width, sl);
3404 XftDrawRect(xw.draw, &dc.col[defaultcs],
3405 borderpx + curx * xw.cw,
3406 borderpx + term.c.y * xw.ch,
3408 XftDrawRect(xw.draw, &dc.col[defaultcs],
3409 borderpx + curx * xw.cw,
3410 borderpx + term.c.y * xw.ch,
3412 XftDrawRect(xw.draw, &dc.col[defaultcs],
3413 borderpx + (curx + 1) * xw.cw - 1,
3414 borderpx + term.c.y * xw.ch,
3416 XftDrawRect(xw.draw, &dc.col[defaultcs],
3417 borderpx + curx * xw.cw,
3418 borderpx + (term.c.y + 1) * xw.ch - 1,
3421 oldx = curx, oldy = term.c.y;
3427 xsettitle(char *p) {
3430 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3432 XSetWMName(xw.dpy, xw.win, &prop);
3433 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
3439 xsettitle(opt_title ? opt_title : "st");
3443 redraw(int timeout) {
3444 struct timespec tv = {0, timeout * 1000};
3450 nanosleep(&tv, NULL);
3451 XSync(xw.dpy, False); /* necessary for a good tput flash */
3457 drawregion(0, 0, term.col, term.row);
3458 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3460 XSetForeground(xw.dpy, dc.gc,
3461 dc.col[IS_SET(MODE_REVERSE)?
3462 defaultfg : defaultbg].pixel);
3466 drawregion(int x1, int y1, int x2, int y2) {
3467 int ic, ib, x, y, ox, sl;
3469 char buf[DRAW_BUF_SIZ];
3470 bool ena_sel = sel.ob.x != -1;
3473 if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3476 if(!(xw.state & WIN_VISIBLE))
3479 for(y = y1; y < y2; y++) {
3483 xtermclear(0, y, term.col, y);
3485 base = term.line[y][0];
3487 for(x = x1; x < x2; x++) {
3488 new = term.line[y][x];
3489 if(new.mode == ATTR_WDUMMY)
3491 if(ena_sel && selected(x, y))
3492 new.mode ^= ATTR_REVERSE;
3493 if(ib > 0 && (ATTRCMP(base, new)
3494 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3495 xdraws(buf, base, ox, y, ic, ib);
3503 sl = utf8decode(new.c, &u8char);
3504 memcpy(buf+ib, new.c, sl);
3506 ic += (new.mode & ATTR_WIDE)? 2 : 1;
3509 xdraws(buf, base, ox, y, ic, ib);
3515 expose(XEvent *ev) {
3516 XExposeEvent *e = &ev->xexpose;
3518 if(xw.state & WIN_REDRAW) {
3520 xw.state &= ~WIN_REDRAW;
3526 visibility(XEvent *ev) {
3527 XVisibilityEvent *e = &ev->xvisibility;
3529 if(e->state == VisibilityFullyObscured) {
3530 xw.state &= ~WIN_VISIBLE;
3531 } else if(!(xw.state & WIN_VISIBLE)) {
3532 /* need a full redraw for next Expose, not just a buf copy */
3533 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3539 xw.state &= ~WIN_VISIBLE;
3543 xsetpointermotion(int set) {
3544 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3545 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3549 xseturgency(int add) {
3550 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3552 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3553 XSetWMHints(xw.dpy, xw.win, h);
3559 XFocusChangeEvent *e = &ev->xfocus;
3561 if(e->mode == NotifyGrab)
3564 if(ev->type == FocusIn) {
3565 XSetICFocus(xw.xic);
3566 xw.state |= WIN_FOCUSED;
3568 if(IS_SET(MODE_FOCUS))
3569 ttywrite("\033[I", 3);
3571 XUnsetICFocus(xw.xic);
3572 xw.state &= ~WIN_FOCUSED;
3573 if(IS_SET(MODE_FOCUS))
3574 ttywrite("\033[O", 3);
3579 match(uint mask, uint state) {
3580 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
3584 numlock(const Arg *dummy) {
3589 kmap(KeySym k, uint state) {
3593 /* Check for mapped keys out of X11 function keys. */
3594 for(i = 0; i < LEN(mappedkeys); i++) {
3595 if(mappedkeys[i] == k)
3598 if(i == LEN(mappedkeys)) {
3599 if((k & 0xFFFF) < 0xFD00)
3603 for(kp = key; kp < key + LEN(key); kp++) {
3607 if(!match(kp->mask, state))
3610 if(IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
3612 if(term.numlock && kp->appkey == 2)
3615 if(IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
3618 if(IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
3628 kpress(XEvent *ev) {
3629 XKeyEvent *e = &ev->xkey;
3631 char buf[32], *customkey;
3637 if(IS_SET(MODE_KBDLOCK))
3640 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
3642 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3643 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3644 bp->func(&(bp->arg));
3649 /* 2. custom keys from config.h */
3650 if((customkey = kmap(ksym, e->state))) {
3651 ttysend(customkey, strlen(customkey));
3655 /* 3. composed string from input method */
3658 if(len == 1 && e->state & Mod1Mask) {
3659 if(IS_SET(MODE_8BIT)) {
3662 len = utf8encode(&c, buf);
3675 cmessage(XEvent *e) {
3678 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3680 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3681 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3682 xw.state |= WIN_FOCUSED;
3684 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3685 xw.state &= ~WIN_FOCUSED;
3687 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3688 /* Send SIGHUP to shell */
3695 cresize(int width, int height) {
3703 col = (xw.w - 2 * borderpx) / xw.cw;
3704 row = (xw.h - 2 * borderpx) / xw.ch;
3713 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3716 cresize(e->xconfigure.width, e->xconfigure.height);
3722 int w = xw.w, h = xw.h;
3724 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3725 struct timeval drawtimeout, *tv = NULL, now, last, lastblink;
3727 /* Waiting for window mapping */
3729 XNextEvent(xw.dpy, &ev);
3730 if(ev.type == ConfigureNotify) {
3731 w = ev.xconfigure.width;
3732 h = ev.xconfigure.height;
3733 } else if(ev.type == MapNotify) {
3742 cresize(xw.fw, xw.fh);
3744 gettimeofday(&lastblink, NULL);
3745 gettimeofday(&last, NULL);
3747 for(xev = actionfps;;) {
3751 FD_SET(cmdfd, &rfd);
3754 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3757 die("select failed: %s\n", SERRNO);
3759 if(FD_ISSET(cmdfd, &rfd)) {
3762 blinkset = tattrset(ATTR_BLINK);
3764 MODBIT(term.mode, 0, MODE_BLINK);
3768 if(FD_ISSET(xfd, &rfd))
3771 gettimeofday(&now, NULL);
3772 drawtimeout.tv_sec = 0;
3773 drawtimeout.tv_usec = (1000/xfps) * 1000;
3777 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3778 tsetdirtattr(ATTR_BLINK);
3779 term.mode ^= MODE_BLINK;
3780 gettimeofday(&lastblink, NULL);
3783 deltatime = TIMEDIFF(now, last);
3784 if(deltatime > (xev? (1000/xfps) : (1000/actionfps))
3791 while(XPending(xw.dpy)) {
3792 XNextEvent(xw.dpy, &ev);
3793 if(XFilterEvent(&ev, None))
3795 if(handler[ev.type])
3796 (handler[ev.type])(&ev);
3802 if(xev && !FD_ISSET(xfd, &rfd))
3804 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3806 if(TIMEDIFF(now, lastblink) \
3808 drawtimeout.tv_usec = 1;
3810 drawtimeout.tv_usec = (1000 * \
3825 die("%s " VERSION " (c) 2010-2013 st engineers\n" \
3826 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
3827 " [-t title] [-w windowid] [-e command ...]\n", argv0);
3831 main(int argc, char *argv[]) {
3836 xw.fw = xw.fh = xw.fx = xw.fy = 0;
3841 allowaltscreen = false;
3844 opt_class = EARGF(usage());
3847 /* eat all remaining arguments */
3850 if(argv[1] != NULL && opt_title == NULL) {
3851 titles = xstrdup(argv[1]);
3852 opt_title = basename(titles);
3857 opt_font = EARGF(usage());
3860 bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
3865 if(bitm & WidthValue)
3867 if(bitm & HeightValue)
3869 if(bitm & XNegative && xw.fx == 0)
3871 if(bitm & YNegative && xw.fy == 0)
3874 if(xw.fh != 0 && xw.fw != 0)
3878 opt_io = EARGF(usage());
3881 opt_title = EARGF(usage());
3884 opt_embed = EARGF(usage());
3892 setlocale(LC_CTYPE, "");
3893 XSetLocaleModifiers("");