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 *);
317 static void printscreen(const Arg *) ;
318 static void toggleprinter(const Arg *);
320 /* Config.h for applying patches and the configuration. */
336 /* Drawing Context */
338 Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
339 Font font, bfont, ifont, ibfont;
343 static void die(const char *, ...);
344 static void draw(void);
345 static void redraw(int);
346 static void drawregion(int, int, int, int);
347 static void execsh(void);
348 static void sigchld(int);
349 static void run(void);
351 static void csidump(void);
352 static void csihandle(void);
353 static void csiparse(void);
354 static void csireset(void);
355 static void strdump(void);
356 static void strhandle(void);
357 static void strparse(void);
358 static void strreset(void);
360 static int tattrset(int);
361 static void tprinter(char *s, size_t len);
362 static void tdumpline(int);
363 static void tdump(void);
364 static void tclearregion(int, int, int, int);
365 static void tcursor(int);
366 static void tdeletechar(int);
367 static void tdeleteline(int);
368 static void tinsertblank(int);
369 static void tinsertblankline(int);
370 static void tmoveto(int, int);
371 static void tmoveato(int x, int y);
372 static void tnew(int, int);
373 static void tnewline(int);
374 static void tputtab(bool);
375 static void tputc(char *, int);
376 static void treset(void);
377 static int tresize(int, int);
378 static void tscrollup(int, int);
379 static void tscrolldown(int, int);
380 static void tsetattr(int*, int);
381 static void tsetchar(char *, Glyph *, int, int);
382 static void tsetscroll(int, int);
383 static void tswapscreen(void);
384 static void tsetdirt(int, int);
385 static void tsetdirtattr(int);
386 static void tsetmode(bool, bool, int *, int);
387 static void tfulldirt(void);
388 static void techo(char *, int);
389 static int32_t tdefcolor(int *, int *, int);
390 static void tselcs(void);
391 static void tdeftran(char);
392 static inline bool match(uint, uint);
393 static void ttynew(void);
394 static void ttyread(void);
395 static void ttyresize(void);
396 static void ttysend(char *, size_t);
397 static void ttywrite(const char *, size_t);
399 static void xdraws(char *, Glyph, int, int, int, int);
400 static void xhints(void);
401 static void xclear(int, int, int, int);
402 static void xdrawcursor(void);
403 static void xinit(void);
404 static void xloadcols(void);
405 static int xsetcolorname(int, const char *);
406 static int xloadfont(Font *, FcPattern *);
407 static void xloadfonts(char *, double);
408 static int xloadfontset(Font *);
409 static void xsettitle(char *);
410 static void xresettitle(void);
411 static void xsetpointermotion(int);
412 static void xseturgency(int);
413 static void xsetsel(char*);
414 static void xtermclear(int, int, int, int);
415 static void xunloadfont(Font *f);
416 static void xunloadfonts(void);
417 static void xresize(int, int);
419 static void expose(XEvent *);
420 static void visibility(XEvent *);
421 static void unmap(XEvent *);
422 static char *kmap(KeySym, uint);
423 static void kpress(XEvent *);
424 static void cmessage(XEvent *);
425 static void cresize(int, int);
426 static void resize(XEvent *);
427 static void focus(XEvent *);
428 static void brelease(XEvent *);
429 static void bpress(XEvent *);
430 static void bmotion(XEvent *);
431 static void selnotify(XEvent *);
432 static void selclear(XEvent *);
433 static void selrequest(XEvent *);
435 static void selinit(void);
436 static void selsort(void);
437 static inline bool selected(int, int);
438 static void selcopy(void);
439 static void selscroll(int, int);
440 static void selsnap(int, int *, int *, int);
442 static int utf8decode(char *, long *);
443 static int utf8encode(long *, char *);
444 static int utf8size(char *);
445 static int isfullutf8(char *, int);
447 static ssize_t xwrite(int, char *, size_t);
448 static void *xmalloc(size_t);
449 static void *xrealloc(void *, size_t);
450 static char *xstrdup(char *s);
452 static void (*handler[LASTEvent])(XEvent *) = {
454 [ClientMessage] = cmessage,
455 [ConfigureNotify] = resize,
456 [VisibilityNotify] = visibility,
457 [UnmapNotify] = unmap,
461 [MotionNotify] = bmotion,
462 [ButtonPress] = bpress,
463 [ButtonRelease] = brelease,
464 [SelectionClear] = selclear,
465 [SelectionNotify] = selnotify,
466 [SelectionRequest] = selrequest,
473 static CSIEscape csiescseq;
474 static STREscape strescseq;
477 static Selection sel;
478 static int iofd = STDOUT_FILENO;
479 static char **opt_cmd = NULL;
480 static char *opt_io = NULL;
481 static char *opt_title = NULL;
482 static char *opt_embed = NULL;
483 static char *opt_class = NULL;
484 static char *opt_font = NULL;
485 static int oldbutton = 3; /* button event on startup: 3 = release */
487 static char *usedfont = NULL;
488 static double usedfontsize = 0;
490 /* Font Ring Cache */
503 /* Fontcache is an array now. A new font will be appended to the array. */
504 static Fontcache frc[16];
505 static int frclen = 0;
508 xwrite(int fd, char *s, size_t len) {
512 ssize_t r = write(fd, s, len);
522 xmalloc(size_t len) {
523 void *p = malloc(len);
526 die("Out of memory\n");
532 xrealloc(void *p, size_t len) {
533 if((p = realloc(p, len)) == NULL)
534 die("Out of memory\n");
544 die("Out of memory\n");
550 utf8decode(char *s, long *u) {
556 if(~c & 0x80) { /* 0xxxxxxx */
559 } else if((c & 0xE0) == 0xC0) { /* 110xxxxx */
562 } else if((c & 0xF0) == 0xE0) { /* 1110xxxx */
565 } else if((c & 0xF8) == 0xF0) { /* 11110xxx */
572 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
574 if((c & 0xC0) != 0x80) /* 10xxxxxx */
580 if((n == 1 && *u < 0x80) ||
581 (n == 2 && *u < 0x800) ||
582 (n == 3 && *u < 0x10000) ||
583 (*u >= 0xD800 && *u <= 0xDFFF)) {
595 utf8encode(long *u, char *s) {
603 *sp = uc; /* 0xxxxxxx */
605 } else if(*u < 0x800) {
606 *sp = (uc >> 6) | 0xC0; /* 110xxxxx */
608 } else if(uc < 0x10000) {
609 *sp = (uc >> 12) | 0xE0; /* 1110xxxx */
611 } else if(uc <= 0x10FFFF) {
612 *sp = (uc >> 18) | 0xF0; /* 11110xxx */
618 for(i=n,++sp; i>0; --i,++sp)
619 *sp = ((uc >> 6*(i-1)) & 0x3F) | 0x80; /* 10xxxxxx */
631 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
632 UTF-8 otherwise return 0 */
634 isfullutf8(char *s, int b) {
642 } else if((*c1 & 0xE0) == 0xC0 && b == 1) {
644 } else if((*c1 & 0xF0) == 0xE0 &&
646 ((b == 2) && (*c2 & 0xC0) == 0x80))) {
648 } else if((*c1 & 0xF8) == 0xF0 &&
650 ((b == 2) && (*c2 & 0xC0) == 0x80) ||
651 ((b == 3) && (*c2 & 0xC0) == 0x80 && (*c3 & 0xC0) == 0x80))) {
664 } else if((c & 0xE0) == 0xC0) {
666 } else if((c & 0xF0) == 0xE0) {
675 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
676 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
680 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
681 if(sel.xtarget == None)
682 sel.xtarget = XA_STRING;
690 return LIMIT(x, 0, term.col-1);
698 return LIMIT(y, 0, term.row-1);
703 if(sel.ob.y == sel.oe.y) {
704 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
705 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
707 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
708 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
710 sel.nb.y = MIN(sel.ob.y, sel.oe.y);
711 sel.ne.y = MAX(sel.ob.y, sel.oe.y);
715 selected(int x, int y) {
716 if(sel.ne.y == y && sel.nb.y == y)
717 return BETWEEN(x, sel.nb.x, sel.ne.x);
719 if(sel.type == SEL_RECTANGULAR) {
720 return ((sel.nb.y <= y && y <= sel.ne.y)
721 && (sel.nb.x <= x && x <= sel.ne.x));
724 return ((sel.nb.y < y && y < sel.ne.y)
725 || (y == sel.ne.y && x <= sel.ne.x))
726 || (y == sel.nb.y && x >= sel.nb.x
727 && (x <= sel.ne.x || sel.nb.y != sel.ne.y));
731 selsnap(int mode, int *x, int *y, int direction) {
737 * Snap around if the word wraps around at the end or
738 * beginning of a line.
741 if(direction < 0 && *x <= 0) {
742 if(*y > 0 && term.line[*y - 1][term.col-1].mode
750 if(direction > 0 && *x >= term.col-1) {
751 if(*y < term.row-1 && term.line[*y][*x].mode
760 if(term.line[*y][*x+direction].mode & ATTR_WDUMMY) {
765 if(strchr(worddelimiters,
766 term.line[*y][*x+direction].c[0])) {
775 * Snap around if the the previous line or the current one
776 * has set ATTR_WRAP at its end. Then the whole next or
777 * previous line will be selected.
779 *x = (direction < 0) ? 0 : term.col - 1;
780 if(direction < 0 && *y > 0) {
781 for(; *y > 0; *y += direction) {
782 if(!(term.line[*y-1][term.col-1].mode
787 } else if(direction > 0 && *y < term.row-1) {
788 for(; *y < term.row; *y += direction) {
789 if(!(term.line[*y][term.col-1].mode
798 * Select the whole line when the end of line is reached.
802 while(--i > 0 && term.line[*y][i].c[0] == ' ')
812 getbuttoninfo(XEvent *e) {
814 uint state = e->xbutton.state &~Button1Mask;
816 sel.alt = IS_SET(MODE_ALTSCREEN);
818 sel.oe.x = x2col(e->xbutton.x);
819 sel.oe.y = y2row(e->xbutton.y);
821 if(sel.ob.y < sel.oe.y
822 || (sel.ob.y == sel.oe.y && sel.ob.x < sel.oe.x)) {
823 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
824 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
826 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, -1);
827 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, +1);
831 sel.type = SEL_REGULAR;
832 for(type = 1; type < LEN(selmasks); ++type) {
833 if(match(selmasks[type], state)) {
841 mousereport(XEvent *e) {
842 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
843 button = e->xbutton.button, state = e->xbutton.state,
849 if(e->xbutton.type == MotionNotify) {
850 if(x == ox && y == oy)
852 if(!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
854 /* MOUSE_MOTION: no reporting if no button is pressed */
855 if(IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
858 button = oldbutton + 32;
862 if(!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
869 if(e->xbutton.type == ButtonPress) {
873 } else if(e->xbutton.type == ButtonRelease) {
875 /* MODE_MOUSEX10: no button release reporting */
876 if(IS_SET(MODE_MOUSEX10))
881 if(!IS_SET(MODE_MOUSEX10)) {
882 button += (state & ShiftMask ? 4 : 0)
883 + (state & Mod4Mask ? 8 : 0)
884 + (state & ControlMask ? 16 : 0);
888 if(IS_SET(MODE_MOUSESGR)) {
889 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
891 e->xbutton.type == ButtonRelease ? 'm' : 'M');
892 } else if(x < 223 && y < 223) {
893 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
894 32+button, 32+x+1, 32+y+1);
907 if(IS_SET(MODE_MOUSE)) {
912 for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
913 if(e->xbutton.button == mk->b
914 && match(mk->mask, e->xbutton.state)) {
915 ttysend(mk->s, strlen(mk->s));
920 if(e->xbutton.button == Button1) {
921 gettimeofday(&now, NULL);
923 /* Clear previous selection, logically and visually. */
926 sel.type = SEL_REGULAR;
927 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
928 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
931 * If the user clicks below predefined timeouts specific
932 * snapping behaviour is exposed.
934 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
935 sel.snap = SNAP_LINE;
936 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
937 sel.snap = SNAP_WORD;
941 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
942 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
946 * Draw selection, unless it's regular and we don't want to
947 * make clicks visible
951 tsetdirt(sel.nb.y, sel.ne.y);
953 sel.tclick2 = sel.tclick1;
961 int x, y, bufsize, size, i, ex;
967 bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
968 ptr = str = xmalloc(bufsize);
970 /* append every set & selected glyph to the selection */
971 for(y = sel.nb.y; y < sel.ne.y + 1; y++) {
972 gp = &term.line[y][0];
973 last = &gp[term.col-1];
975 while(last >= gp && !(selected(last - gp, y) &&
976 strcmp(last->c, " ") != 0)) {
980 for(x = 0; gp <= last; x++, ++gp) {
981 if(!selected(x, y) || (gp->mode & ATTR_WDUMMY))
984 size = utf8size(gp->c);
985 memcpy(ptr, gp->c, size);
990 * Copy and pasting of line endings is inconsistent
991 * in the inconsistent terminal and GUI world.
992 * The best solution seems like to produce '\n' when
993 * something is copied from st and convert '\n' to
994 * '\r', when something to be pasted is received by
996 * FIXME: Fix the computer world.
998 if(y < sel.ne.y && x > 0 && !((gp-1)->mode & ATTR_WRAP))
1002 * If the last selected line expands in the selection
1003 * after the visible text '\n' is appended.
1007 while(--i > 0 && term.line[y][i].c[0] == ' ')
1010 if(sel.nb.y == sel.ne.y && sel.ne.x < sel.nb.x)
1022 selnotify(XEvent *e) {
1023 ulong nitems, ofs, rem;
1025 uchar *data, *last, *repl;
1030 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
1031 False, AnyPropertyType, &type, &format,
1032 &nitems, &rem, &data)) {
1033 fprintf(stderr, "Clipboard allocation failed\n");
1038 * As seen in selcopy:
1039 * Line endings are inconsistent in the terminal and GUI world
1040 * copy and pasting. When receiving some selection data,
1041 * replace all '\n' with '\r'.
1042 * FIXME: Fix the computer world.
1045 last = data + nitems * format / 8;
1046 while((repl = memchr(repl, '\n', last - repl))) {
1050 if(IS_SET(MODE_BRCKTPASTE))
1051 ttywrite("\033[200~", 6);
1052 ttysend((char *)data, nitems * format / 8);
1053 if(IS_SET(MODE_BRCKTPASTE))
1054 ttywrite("\033[201~", 6);
1056 /* number of 32-bit chunks returned */
1057 ofs += nitems * format / 32;
1062 selpaste(const Arg *dummy) {
1063 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1064 xw.win, CurrentTime);
1068 clippaste(const Arg *dummy) {
1071 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1072 XConvertSelection(xw.dpy, clipboard, sel.xtarget, XA_PRIMARY,
1073 xw.win, CurrentTime);
1077 selclear(XEvent *e) {
1081 tsetdirt(sel.nb.y, sel.ne.y);
1085 selrequest(XEvent *e) {
1086 XSelectionRequestEvent *xsre;
1087 XSelectionEvent xev;
1088 Atom xa_targets, string;
1090 xsre = (XSelectionRequestEvent *) e;
1091 xev.type = SelectionNotify;
1092 xev.requestor = xsre->requestor;
1093 xev.selection = xsre->selection;
1094 xev.target = xsre->target;
1095 xev.time = xsre->time;
1097 xev.property = None;
1099 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1100 if(xsre->target == xa_targets) {
1101 /* respond with the supported type */
1102 string = sel.xtarget;
1103 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1104 XA_ATOM, 32, PropModeReplace,
1105 (uchar *) &string, 1);
1106 xev.property = xsre->property;
1107 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
1108 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1109 xsre->target, 8, PropModeReplace,
1110 (uchar *) sel.clip, strlen(sel.clip));
1111 xev.property = xsre->property;
1114 /* all done, send a notification to the listener */
1115 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
1116 fprintf(stderr, "Error sending SelectionNotify event\n");
1120 xsetsel(char *str) {
1121 /* register the selection for both the clipboard and the primary */
1127 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
1129 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1130 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1134 brelease(XEvent *e) {
1135 if(IS_SET(MODE_MOUSE)) {
1140 if(e->xbutton.button == Button2) {
1142 } else if(e->xbutton.button == Button1) {
1150 tsetdirt(sel.nb.y, sel.ne.y);
1155 bmotion(XEvent *e) {
1156 int oldey, oldex, oldsby, oldsey;
1158 if(IS_SET(MODE_MOUSE)) {
1173 if(oldey != sel.oe.y || oldex != sel.oe.x)
1174 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1178 die(const char *errstr, ...) {
1181 va_start(ap, errstr);
1182 vfprintf(stderr, errstr, ap);
1190 char *envshell = getenv("SHELL");
1191 const struct passwd *pass = getpwuid(getuid());
1192 char buf[sizeof(long) * 8 + 1];
1194 unsetenv("COLUMNS");
1196 unsetenv("TERMCAP");
1199 setenv("LOGNAME", pass->pw_name, 1);
1200 setenv("USER", pass->pw_name, 1);
1201 setenv("SHELL", pass->pw_shell, 0);
1202 setenv("HOME", pass->pw_dir, 0);
1205 snprintf(buf, sizeof(buf), "%lu", xw.win);
1206 setenv("WINDOWID", buf, 1);
1208 signal(SIGCHLD, SIG_DFL);
1209 signal(SIGHUP, SIG_DFL);
1210 signal(SIGINT, SIG_DFL);
1211 signal(SIGQUIT, SIG_DFL);
1212 signal(SIGTERM, SIG_DFL);
1213 signal(SIGALRM, SIG_DFL);
1215 DEFAULT(envshell, shell);
1216 setenv("TERM", termname, 1);
1217 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
1218 execvp(args[0], args);
1226 if(waitpid(pid, &stat, 0) < 0)
1227 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
1229 if(WIFEXITED(stat)) {
1230 exit(WEXITSTATUS(stat));
1239 struct winsize w = {term.row, term.col, 0, 0};
1241 /* seems to work fine on linux, openbsd and freebsd */
1242 if(openpty(&m, &s, NULL, NULL, &w) < 0)
1243 die("openpty failed: %s\n", SERRNO);
1245 switch(pid = fork()) {
1247 die("fork failed\n");
1250 setsid(); /* create a new process group */
1251 dup2(s, STDIN_FILENO);
1252 dup2(s, STDOUT_FILENO);
1253 dup2(s, STDERR_FILENO);
1254 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1255 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
1263 signal(SIGCHLD, sigchld);
1265 term.mode |= MODE_PRINT;
1266 iofd = (!strcmp(opt_io, "-")) ?
1268 open(opt_io, O_WRONLY | O_CREAT, 0666);
1270 fprintf(stderr, "Error opening %s:%s\n",
1271 opt_io, strerror(errno));
1281 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1283 fprintf(stderr, "\n");
1288 static char buf[BUFSIZ];
1289 static int buflen = 0;
1292 int charsize; /* size of utf8 char in bytes */
1296 /* append read bytes to unprocessed bytes */
1297 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1298 die("Couldn't read from shell: %s\n", SERRNO);
1300 /* process every complete utf8 char */
1303 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1304 charsize = utf8decode(ptr, &utf8c);
1305 utf8encode(&utf8c, s);
1311 /* keep any uncomplete utf8 char for the next call */
1312 memmove(buf, ptr, buflen);
1316 ttywrite(const char *s, size_t n) {
1317 if(write(cmdfd, s, n) == -1)
1318 die("write error on tty: %s\n", SERRNO);
1322 ttysend(char *s, size_t n) {
1324 if(IS_SET(MODE_ECHO))
1332 w.ws_row = term.row;
1333 w.ws_col = term.col;
1334 w.ws_xpixel = xw.tw;
1335 w.ws_ypixel = xw.th;
1336 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1337 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1341 tattrset(int attr) {
1344 for(i = 0; i < term.row-1; i++) {
1345 for(j = 0; j < term.col-1; j++) {
1346 if(term.line[i][j].mode & attr)
1355 tsetdirt(int top, int bot) {
1358 LIMIT(top, 0, term.row-1);
1359 LIMIT(bot, 0, term.row-1);
1361 for(i = top; i <= bot; i++)
1366 tsetdirtattr(int attr) {
1369 for(i = 0; i < term.row-1; i++) {
1370 for(j = 0; j < term.col-1; j++) {
1371 if(term.line[i][j].mode & attr) {
1381 tsetdirt(0, term.row-1);
1386 static TCursor c[2];
1387 bool alt = IS_SET(MODE_ALTSCREEN);
1389 if(mode == CURSOR_SAVE) {
1391 } else if(mode == CURSOR_LOAD) {
1393 tmoveto(c[alt].x, c[alt].y);
1401 term.c = (TCursor){{
1405 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1407 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1408 for(i = tabspaces; i < term.col; i += tabspaces)
1411 term.bot = term.row - 1;
1412 term.mode = MODE_WRAP;
1413 memset(term.trantbl, sizeof(term.trantbl), CS_USA);
1416 tclearregion(0, 0, term.col-1, term.row-1);
1418 tcursor(CURSOR_SAVE);
1422 tnew(int col, int row) {
1423 term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
1432 Line *tmp = term.line;
1434 term.line = term.alt;
1436 term.mode ^= MODE_ALTSCREEN;
1441 tscrolldown(int orig, int n) {
1445 LIMIT(n, 0, term.bot-orig+1);
1447 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1449 for(i = term.bot; i >= orig+n; i--) {
1450 temp = term.line[i];
1451 term.line[i] = term.line[i-n];
1452 term.line[i-n] = temp;
1455 term.dirty[i-n] = 1;
1462 tscrollup(int orig, int n) {
1465 LIMIT(n, 0, term.bot-orig+1);
1467 tclearregion(0, orig, term.col-1, orig+n-1);
1469 for(i = orig; i <= term.bot-n; i++) {
1470 temp = term.line[i];
1471 term.line[i] = term.line[i+n];
1472 term.line[i+n] = temp;
1475 term.dirty[i+n] = 1;
1478 selscroll(orig, -n);
1482 selscroll(int orig, int n) {
1486 if(BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1487 if((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1491 if(sel.type == SEL_RECTANGULAR) {
1492 if(sel.ob.y < term.top)
1493 sel.ob.y = term.top;
1494 if(sel.oe.y > term.bot)
1495 sel.oe.y = term.bot;
1497 if(sel.ob.y < term.top) {
1498 sel.ob.y = term.top;
1501 if(sel.oe.y > term.bot) {
1502 sel.oe.y = term.bot;
1503 sel.oe.x = term.col;
1511 tnewline(int first_col) {
1515 tscrollup(term.top, 1);
1519 tmoveto(first_col ? 0 : term.c.x, y);
1524 char *p = csiescseq.buf, *np;
1533 csiescseq.buf[csiescseq.len] = '\0';
1534 while(p < csiescseq.buf+csiescseq.len) {
1536 v = strtol(p, &np, 10);
1539 if(v == LONG_MAX || v == LONG_MIN)
1541 csiescseq.arg[csiescseq.narg++] = v;
1543 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1547 csiescseq.mode = *p;
1550 /* for absolute user moves, when decom is set */
1552 tmoveato(int x, int y) {
1553 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1557 tmoveto(int x, int y) {
1560 if(term.c.state & CURSOR_ORIGIN) {
1565 maxy = term.row - 1;
1567 LIMIT(x, 0, term.col-1);
1568 LIMIT(y, miny, maxy);
1569 term.c.state &= ~CURSOR_WRAPNEXT;
1575 tsetchar(char *c, Glyph *attr, int x, int y) {
1576 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1577 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1578 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1579 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1580 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1581 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1582 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1583 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1584 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1588 * The table is proudly stolen from rxvt.
1590 if(attr->mode & ATTR_GFX) {
1591 if(c[0] >= 0x41 && c[0] <= 0x7e
1592 && vt100_0[c[0] - 0x41]) {
1593 c = vt100_0[c[0] - 0x41];
1597 if(term.line[y][x].mode & ATTR_WIDE) {
1598 if(x+1 < term.col) {
1599 term.line[y][x+1].c[0] = ' ';
1600 term.line[y][x+1].mode &= ~ATTR_WDUMMY;
1602 } else if(term.line[y][x].mode & ATTR_WDUMMY) {
1603 term.line[y][x-1].c[0] = ' ';
1604 term.line[y][x-1].mode &= ~ATTR_WIDE;
1608 term.line[y][x] = *attr;
1609 memcpy(term.line[y][x].c, c, UTF_SIZ);
1613 tclearregion(int x1, int y1, int x2, int y2) {
1617 temp = x1, x1 = x2, x2 = temp;
1619 temp = y1, y1 = y2, y2 = temp;
1621 LIMIT(x1, 0, term.col-1);
1622 LIMIT(x2, 0, term.col-1);
1623 LIMIT(y1, 0, term.row-1);
1624 LIMIT(y2, 0, term.row-1);
1626 for(y = y1; y <= y2; y++) {
1628 for(x = x1; x <= x2; x++) {
1631 term.line[y][x] = term.c.attr;
1632 memcpy(term.line[y][x].c, " ", 2);
1638 tdeletechar(int n) {
1639 int src = term.c.x + n;
1641 int size = term.col - src;
1643 term.dirty[term.c.y] = 1;
1645 if(src >= term.col) {
1646 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1650 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1651 size * sizeof(Glyph));
1652 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1656 tinsertblank(int n) {
1659 int size = term.col - dst;
1661 term.dirty[term.c.y] = 1;
1663 if(dst >= term.col) {
1664 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1668 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1669 size * sizeof(Glyph));
1670 tclearregion(src, term.c.y, dst - 1, term.c.y);
1674 tinsertblankline(int n) {
1675 if(term.c.y < term.top || term.c.y > term.bot)
1678 tscrolldown(term.c.y, n);
1682 tdeleteline(int n) {
1683 if(term.c.y < term.top || term.c.y > term.bot)
1686 tscrollup(term.c.y, n);
1690 tdefcolor(int *attr, int *npar, int l) {
1694 switch (attr[*npar + 1]) {
1695 case 2: /* direct colour in RGB space */
1696 if (*npar + 4 >= l) {
1698 "erresc(38): Incorrect number of parameters (%d)\n",
1702 r = attr[*npar + 2];
1703 g = attr[*npar + 3];
1704 b = attr[*npar + 4];
1706 if(!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1707 fprintf(stderr, "erresc: bad rgb color (%d,%d,%d)\n",
1710 idx = TRUECOLOR(r, g, b);
1712 case 5: /* indexed colour */
1713 if (*npar + 2 >= l) {
1715 "erresc(38): Incorrect number of parameters (%d)\n",
1720 if(!BETWEEN(attr[*npar], 0, 255))
1721 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
1725 case 0: /* implemented defined (only foreground) */
1726 case 1: /* transparent */
1727 case 3: /* direct colour in CMY space */
1728 case 4: /* direct colour in CMYK space */
1731 "erresc(38): gfx attr %d unknown\n", attr[*npar]);
1738 tsetattr(int *attr, int l) {
1742 for(i = 0; i < l; i++) {
1745 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE \
1746 | ATTR_BOLD | ATTR_ITALIC \
1748 term.c.attr.fg = defaultfg;
1749 term.c.attr.bg = defaultbg;
1752 term.c.attr.mode |= ATTR_BOLD;
1755 term.c.attr.mode |= ATTR_ITALIC;
1758 term.c.attr.mode |= ATTR_UNDERLINE;
1760 case 5: /* slow blink */
1761 case 6: /* rapid blink */
1762 term.c.attr.mode |= ATTR_BLINK;
1765 term.c.attr.mode |= ATTR_REVERSE;
1769 term.c.attr.mode &= ~ATTR_BOLD;
1772 term.c.attr.mode &= ~ATTR_ITALIC;
1775 term.c.attr.mode &= ~ATTR_UNDERLINE;
1779 term.c.attr.mode &= ~ATTR_BLINK;
1782 term.c.attr.mode &= ~ATTR_REVERSE;
1785 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1786 term.c.attr.fg = idx;
1789 term.c.attr.fg = defaultfg;
1792 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1793 term.c.attr.bg = idx;
1796 term.c.attr.bg = defaultbg;
1799 if(BETWEEN(attr[i], 30, 37)) {
1800 term.c.attr.fg = attr[i] - 30;
1801 } else if(BETWEEN(attr[i], 40, 47)) {
1802 term.c.attr.bg = attr[i] - 40;
1803 } else if(BETWEEN(attr[i], 90, 97)) {
1804 term.c.attr.fg = attr[i] - 90 + 8;
1805 } else if(BETWEEN(attr[i], 100, 107)) {
1806 term.c.attr.bg = attr[i] - 100 + 8;
1809 "erresc(default): gfx attr %d unknown\n",
1810 attr[i]), csidump();
1818 tsetscroll(int t, int b) {
1821 LIMIT(t, 0, term.row-1);
1822 LIMIT(b, 0, term.row-1);
1832 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1835 tsetmode(bool priv, bool set, int *args, int narg) {
1839 for(lim = args + narg; args < lim; ++args) {
1843 case 1: /* DECCKM -- Cursor key */
1844 MODBIT(term.mode, set, MODE_APPCURSOR);
1846 case 5: /* DECSCNM -- Reverse video */
1848 MODBIT(term.mode, set, MODE_REVERSE);
1849 if(mode != term.mode)
1850 redraw(REDRAW_TIMEOUT);
1852 case 6: /* DECOM -- Origin */
1853 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1856 case 7: /* DECAWM -- Auto wrap */
1857 MODBIT(term.mode, set, MODE_WRAP);
1859 case 0: /* Error (IGNORED) */
1860 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1861 case 3: /* DECCOLM -- Column (IGNORED) */
1862 case 4: /* DECSCLM -- Scroll (IGNORED) */
1863 case 8: /* DECARM -- Auto repeat (IGNORED) */
1864 case 18: /* DECPFF -- Printer feed (IGNORED) */
1865 case 19: /* DECPEX -- Printer extent (IGNORED) */
1866 case 42: /* DECNRCM -- National characters (IGNORED) */
1867 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1869 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1870 MODBIT(term.mode, !set, MODE_HIDE);
1872 case 9: /* X10 mouse compatibility mode */
1873 xsetpointermotion(0);
1874 MODBIT(term.mode, 0, MODE_MOUSE);
1875 MODBIT(term.mode, set, MODE_MOUSEX10);
1877 case 1000: /* 1000: report button press */
1878 xsetpointermotion(0);
1879 MODBIT(term.mode, 0, MODE_MOUSE);
1880 MODBIT(term.mode, set, MODE_MOUSEBTN);
1882 case 1002: /* 1002: report motion on button press */
1883 xsetpointermotion(0);
1884 MODBIT(term.mode, 0, MODE_MOUSE);
1885 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1887 case 1003: /* 1003: enable all mouse motions */
1888 xsetpointermotion(set);
1889 MODBIT(term.mode, 0, MODE_MOUSE);
1890 MODBIT(term.mode, set, MODE_MOUSEMANY);
1892 case 1004: /* 1004: send focus events to tty */
1893 MODBIT(term.mode, set, MODE_FOCUS);
1895 case 1006: /* 1006: extended reporting mode */
1896 MODBIT(term.mode, set, MODE_MOUSESGR);
1899 MODBIT(term.mode, set, MODE_8BIT);
1901 case 1049: /* swap screen & set/restore cursor as xterm */
1902 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1903 case 47: /* swap screen */
1905 if (!allowaltscreen)
1907 alt = IS_SET(MODE_ALTSCREEN);
1909 tclearregion(0, 0, term.col-1,
1912 if(set ^ alt) /* set is always 1 or 0 */
1918 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1920 case 2004: /* 2004: bracketed paste mode */
1921 MODBIT(term.mode, set, MODE_BRCKTPASTE);
1923 /* Not implemented mouse modes. See comments there. */
1924 case 1001: /* mouse highlight mode; can hang the
1925 terminal by design when implemented. */
1926 case 1005: /* UTF-8 mouse mode; will confuse
1927 applications not supporting UTF-8
1929 case 1015: /* urxvt mangled mouse mode; incompatible
1930 and can be mistaken for other control
1934 "erresc: unknown private set/reset mode %d\n",
1940 case 0: /* Error (IGNORED) */
1942 case 2: /* KAM -- keyboard action */
1943 MODBIT(term.mode, set, MODE_KBDLOCK);
1945 case 4: /* IRM -- Insertion-replacement */
1946 MODBIT(term.mode, set, MODE_INSERT);
1948 case 12: /* SRM -- Send/Receive */
1949 MODBIT(term.mode, !set, MODE_ECHO);
1951 case 20: /* LNM -- Linefeed/new line */
1952 MODBIT(term.mode, set, MODE_CRLF);
1956 "erresc: unknown set/reset mode %d\n",
1969 switch(csiescseq.mode) {
1972 fprintf(stderr, "erresc: unknown csi ");
1976 case '@': /* ICH -- Insert <n> blank char */
1977 DEFAULT(csiescseq.arg[0], 1);
1978 tinsertblank(csiescseq.arg[0]);
1980 case 'A': /* CUU -- Cursor <n> Up */
1981 DEFAULT(csiescseq.arg[0], 1);
1982 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1984 case 'B': /* CUD -- Cursor <n> Down */
1985 case 'e': /* VPR --Cursor <n> Down */
1986 DEFAULT(csiescseq.arg[0], 1);
1987 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1989 case 'i': /* MC -- Media Copy */
1990 switch(csiescseq.arg[0]) {
1995 tdumpline(term.c.y);
1998 term.mode &= ~MODE_PRINT;
2001 term.mode |= MODE_PRINT;
2005 case 'c': /* DA -- Device Attributes */
2006 if(csiescseq.arg[0] == 0)
2007 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2009 case 'C': /* CUF -- Cursor <n> Forward */
2010 case 'a': /* HPR -- Cursor <n> Forward */
2011 DEFAULT(csiescseq.arg[0], 1);
2012 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
2014 case 'D': /* CUB -- Cursor <n> Backward */
2015 DEFAULT(csiescseq.arg[0], 1);
2016 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
2018 case 'E': /* CNL -- Cursor <n> Down and first col */
2019 DEFAULT(csiescseq.arg[0], 1);
2020 tmoveto(0, term.c.y+csiescseq.arg[0]);
2022 case 'F': /* CPL -- Cursor <n> Up and first col */
2023 DEFAULT(csiescseq.arg[0], 1);
2024 tmoveto(0, term.c.y-csiescseq.arg[0]);
2026 case 'g': /* TBC -- Tabulation clear */
2027 switch(csiescseq.arg[0]) {
2028 case 0: /* clear current tab stop */
2029 term.tabs[term.c.x] = 0;
2031 case 3: /* clear all the tabs */
2032 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
2038 case 'G': /* CHA -- Move to <col> */
2040 DEFAULT(csiescseq.arg[0], 1);
2041 tmoveto(csiescseq.arg[0]-1, term.c.y);
2043 case 'H': /* CUP -- Move to <row> <col> */
2045 DEFAULT(csiescseq.arg[0], 1);
2046 DEFAULT(csiescseq.arg[1], 1);
2047 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
2049 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
2050 DEFAULT(csiescseq.arg[0], 1);
2051 while(csiescseq.arg[0]--)
2054 case 'J': /* ED -- Clear screen */
2056 switch(csiescseq.arg[0]) {
2058 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
2059 if(term.c.y < term.row-1) {
2060 tclearregion(0, term.c.y+1, term.col-1,
2066 tclearregion(0, 0, term.col-1, term.c.y-1);
2067 tclearregion(0, term.c.y, term.c.x, term.c.y);
2070 tclearregion(0, 0, term.col-1, term.row-1);
2076 case 'K': /* EL -- Clear line */
2077 switch(csiescseq.arg[0]) {
2079 tclearregion(term.c.x, term.c.y, term.col-1,
2083 tclearregion(0, term.c.y, term.c.x, term.c.y);
2086 tclearregion(0, term.c.y, term.col-1, term.c.y);
2090 case 'S': /* SU -- Scroll <n> line up */
2091 DEFAULT(csiescseq.arg[0], 1);
2092 tscrollup(term.top, csiescseq.arg[0]);
2094 case 'T': /* SD -- Scroll <n> line down */
2095 DEFAULT(csiescseq.arg[0], 1);
2096 tscrolldown(term.top, csiescseq.arg[0]);
2098 case 'L': /* IL -- Insert <n> blank lines */
2099 DEFAULT(csiescseq.arg[0], 1);
2100 tinsertblankline(csiescseq.arg[0]);
2102 case 'l': /* RM -- Reset Mode */
2103 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2105 case 'M': /* DL -- Delete <n> lines */
2106 DEFAULT(csiescseq.arg[0], 1);
2107 tdeleteline(csiescseq.arg[0]);
2109 case 'X': /* ECH -- Erase <n> char */
2110 DEFAULT(csiescseq.arg[0], 1);
2111 tclearregion(term.c.x, term.c.y,
2112 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2114 case 'P': /* DCH -- Delete <n> char */
2115 DEFAULT(csiescseq.arg[0], 1);
2116 tdeletechar(csiescseq.arg[0]);
2118 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2119 DEFAULT(csiescseq.arg[0], 1);
2120 while(csiescseq.arg[0]--)
2123 case 'd': /* VPA -- Move to <row> */
2124 DEFAULT(csiescseq.arg[0], 1);
2125 tmoveato(term.c.x, csiescseq.arg[0]-1);
2127 case 'h': /* SM -- Set terminal mode */
2128 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2130 case 'm': /* SGR -- Terminal attribute (color) */
2131 tsetattr(csiescseq.arg, csiescseq.narg);
2133 case 'n': /* DSR – Device Status Report (cursor position) */
2134 if (csiescseq.arg[0] == 6) {
2135 len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
2136 term.c.y+1, term.c.x+1);
2140 case 'r': /* DECSTBM -- Set Scrolling Region */
2141 if(csiescseq.priv) {
2144 DEFAULT(csiescseq.arg[0], 1);
2145 DEFAULT(csiescseq.arg[1], term.row);
2146 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2150 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2151 tcursor(CURSOR_SAVE);
2153 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2154 tcursor(CURSOR_LOAD);
2165 for(i = 0; i < csiescseq.len; i++) {
2166 c = csiescseq.buf[i] & 0xff;
2169 } else if(c == '\n') {
2171 } else if(c == '\r') {
2173 } else if(c == 0x1b) {
2176 printf("(%02x)", c);
2184 memset(&csiescseq, 0, sizeof(csiescseq));
2193 narg = strescseq.narg;
2194 par = atoi(strescseq.args[0]);
2196 switch(strescseq.type) {
2197 case ']': /* OSC -- Operating System Command */
2203 xsettitle(strescseq.args[1]);
2205 case 4: /* color set */
2208 p = strescseq.args[2];
2210 case 104: /* color reset, here p = NULL */
2211 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2212 if (!xsetcolorname(j, p)) {
2213 fprintf(stderr, "erresc: invalid color %s\n", p);
2216 * TODO if defaultbg color is changed, borders
2224 case 'k': /* old title set compatibility */
2225 xsettitle(strescseq.args[0]);
2227 case 'P': /* DSC -- Device Control String */
2228 case '_': /* APC -- Application Program Command */
2229 case '^': /* PM -- Privacy Message */
2233 fprintf(stderr, "erresc: unknown str ");
2239 char *p = strescseq.buf;
2242 strescseq.buf[strescseq.len] = '\0';
2243 while(p && strescseq.narg < STR_ARG_SIZ)
2244 strescseq.args[strescseq.narg++] = strsep(&p, ";");
2252 printf("ESC%c", strescseq.type);
2253 for(i = 0; i < strescseq.len; i++) {
2254 c = strescseq.buf[i] & 0xff;
2257 } else if(isprint(c)) {
2259 } else if(c == '\n') {
2261 } else if(c == '\r') {
2263 } else if(c == 0x1b) {
2266 printf("(%02x)", c);
2274 memset(&strescseq, 0, sizeof(strescseq));
2278 tprinter(char *s, size_t len) {
2279 if(iofd != -1 && xwrite(iofd, s, len) < 0) {
2280 fprintf(stderr, "Error writing in %s:%s\n",
2281 opt_io, strerror(errno));
2288 toggleprinter(const Arg *arg) {
2289 term.mode ^= MODE_PRINT;
2293 printscreen(const Arg *arg) {
2301 bp = &term.line[n][0];
2302 end = &bp[term.col-1];
2303 while(end > bp && !strcmp(" ", end->c))
2305 if(bp != end || strcmp(bp->c, " ")) {
2306 for( ;bp <= end; ++bp)
2307 tprinter(bp->c, strlen(bp->c));
2316 for(i = 0; i < term.row; ++i)
2321 tputtab(bool forward) {
2327 for(++x; x < term.col && !term.tabs[x]; ++x)
2332 for(--x; x > 0 && !term.tabs[x]; --x)
2335 tmoveto(x, term.c.y);
2339 techo(char *buf, int len) {
2340 for(; len > 0; buf++, len--) {
2343 if(c == '\033') { /* escape */
2346 } else if(c < '\x20') { /* control code */
2347 if(c != '\n' && c != '\r' && c != '\t') {
2361 tdeftran(char ascii) {
2363 static char tbl[][2] = {
2364 {'0', CS_GRAPHIC0}, {'1', CS_GRAPHIC1}, {'A', CS_UK},
2365 {'B', CS_USA}, {'<', CS_MULTI}, {'K', CS_GER},
2366 {'5', CS_FIN}, {'C', CS_FIN},
2370 for (bp = &tbl[0]; (c = (*bp)[0]) && c != ascii; ++bp)
2374 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2376 term.trantbl[term.icharset] = (*bp)[1];
2381 if (term.trantbl[term.charset] == CS_GRAPHIC0)
2382 term.c.attr.mode |= ATTR_GFX;
2384 term.c.attr.mode &= ~ATTR_GFX;
2388 tputc(char *c, int len) {
2390 bool control = ascii < '\x20' || ascii == 0177;
2397 utf8decode(c, &u8char);
2398 width = wcwidth(u8char);
2401 if(IS_SET(MODE_PRINT))
2405 * STR sequences must be checked before anything else
2406 * because it can use some control codes as part of the sequence.
2408 if(term.esc & ESC_STR) {
2411 term.esc = ESC_START | ESC_STR_END;
2413 case '\a': /* backwards compatibility to xterm */
2418 if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2419 memmove(&strescseq.buf[strescseq.len], c, len);
2420 strescseq.len += len;
2423 * Here is a bug in terminals. If the user never sends
2424 * some code to stop the str or esc command, then st
2425 * will stop responding. But this is better than
2426 * silently failing with unknown characters. At least
2427 * then users will report back.
2429 * In the case users ever get fixed, here is the code:
2441 * Actions of control codes must be performed as soon they arrive
2442 * because they can be embedded inside a control sequence, and
2443 * they must not cause conflicts with sequences.
2451 tmoveto(term.c.x-1, term.c.y);
2454 tmoveto(0, term.c.y);
2459 /* go to first col if the mode is set */
2460 tnewline(IS_SET(MODE_CRLF));
2462 case '\a': /* BEL */
2463 if(!(xw.state & WIN_FOCUSED))
2466 XBell(xw.dpy, bellvolume);
2468 case '\033': /* ESC */
2470 term.esc = ESC_START;
2472 case '\016': /* SO */
2476 case '\017': /* SI */
2480 case '\032': /* SUB */
2481 case '\030': /* CAN */
2484 case '\005': /* ENQ (IGNORED) */
2485 case '\000': /* NUL (IGNORED) */
2486 case '\021': /* XON (IGNORED) */
2487 case '\023': /* XOFF (IGNORED) */
2488 case 0177: /* DEL (IGNORED) */
2491 } else if(term.esc & ESC_START) {
2492 if(term.esc & ESC_CSI) {
2493 csiescseq.buf[csiescseq.len++] = ascii;
2494 if(BETWEEN(ascii, 0x40, 0x7E)
2495 || csiescseq.len >= \
2496 sizeof(csiescseq.buf)-1) {
2501 } else if(term.esc & ESC_STR_END) {
2505 } else if(term.esc & ESC_ALTCHARSET) {
2509 } else if(term.esc & ESC_TEST) {
2510 if(ascii == '8') { /* DEC screen alignment test. */
2511 char E[UTF_SIZ] = "E";
2514 for(x = 0; x < term.col; ++x) {
2515 for(y = 0; y < term.row; ++y)
2516 tsetchar(E, &term.c.attr, x, y);
2523 term.esc |= ESC_CSI;
2526 term.esc |= ESC_TEST;
2528 case 'P': /* DCS -- Device Control String */
2529 case '_': /* APC -- Application Program Command */
2530 case '^': /* PM -- Privacy Message */
2531 case ']': /* OSC -- Operating System Command */
2532 case 'k': /* old title set compatibility */
2534 strescseq.type = ascii;
2535 term.esc |= ESC_STR;
2537 case '(': /* set primary charset G0 */
2538 case ')': /* set secondary charset G1 */
2539 case '*': /* set tertiary charset G2 */
2540 case '+': /* set quaternary charset G3 */
2541 term.icharset = ascii - '(';
2542 term.esc |= ESC_ALTCHARSET;
2544 case 'D': /* IND -- Linefeed */
2545 if(term.c.y == term.bot) {
2546 tscrollup(term.top, 1);
2548 tmoveto(term.c.x, term.c.y+1);
2552 case 'E': /* NEL -- Next line */
2553 tnewline(1); /* always go to first col */
2556 case 'H': /* HTS -- Horizontal tab stop */
2557 term.tabs[term.c.x] = 1;
2560 case 'M': /* RI -- Reverse index */
2561 if(term.c.y == term.top) {
2562 tscrolldown(term.top, 1);
2564 tmoveto(term.c.x, term.c.y-1);
2568 case 'Z': /* DECID -- Identify Terminal */
2569 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2572 case 'c': /* RIS -- Reset to inital state */
2578 case '=': /* DECPAM -- Application keypad */
2579 term.mode |= MODE_APPKEYPAD;
2582 case '>': /* DECPNM -- Normal keypad */
2583 term.mode &= ~MODE_APPKEYPAD;
2586 case '7': /* DECSC -- Save Cursor */
2587 tcursor(CURSOR_SAVE);
2590 case '8': /* DECRC -- Restore Cursor */
2591 tcursor(CURSOR_LOAD);
2594 case '\\': /* ST -- Stop */
2598 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2599 (uchar) ascii, isprint(ascii)? ascii:'.');
2604 * All characters which form part of a sequence are not
2610 * Display control codes only if we are in graphic mode
2612 if(control && !(term.c.attr.mode & ATTR_GFX))
2614 if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2616 if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2617 term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
2621 if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2622 memmove(&term.line[term.c.y][term.c.x+1],
2623 &term.line[term.c.y][term.c.x],
2624 (term.col - term.c.x - 1) * sizeof(Glyph));
2627 if(term.c.x+width > term.col)
2630 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2633 term.line[term.c.y][term.c.x].mode |= ATTR_WIDE;
2634 if(term.c.x+1 < term.col) {
2635 term.line[term.c.y][term.c.x+1].c[0] = '\0';
2636 term.line[term.c.y][term.c.x+1].mode = ATTR_WDUMMY;
2639 if(term.c.x+width < term.col) {
2640 tmoveto(term.c.x+width, term.c.y);
2642 term.c.state |= CURSOR_WRAPNEXT;
2647 tresize(int col, int row) {
2649 int minrow = MIN(row, term.row);
2650 int mincol = MIN(col, term.col);
2651 int slide = term.c.y - row + 1;
2655 if(col < 1 || row < 1)
2658 /* free unneeded rows */
2662 * slide screen to keep cursor where we expect it -
2663 * tscrollup would work here, but we can optimize to
2664 * memmove because we're freeing the earlier lines
2666 for(/* i = 0 */; i < slide; i++) {
2670 memmove(term.line, term.line + slide, row * sizeof(Line));
2671 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2673 for(i += row; i < term.row; i++) {
2678 /* resize to new height */
2679 term.line = xrealloc(term.line, row * sizeof(Line));
2680 term.alt = xrealloc(term.alt, row * sizeof(Line));
2681 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2682 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2684 /* resize each row to new width, zero-pad if needed */
2685 for(i = 0; i < minrow; i++) {
2687 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2688 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2691 /* allocate any new rows */
2692 for(/* i == minrow */; i < row; i++) {
2694 term.line[i] = xmalloc(col * sizeof(Glyph));
2695 term.alt[i] = xmalloc(col * sizeof(Glyph));
2697 if(col > term.col) {
2698 bp = term.tabs + term.col;
2700 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2701 while(--bp > term.tabs && !*bp)
2703 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2706 /* update terminal size */
2709 /* reset scrolling region */
2710 tsetscroll(0, row-1);
2711 /* make use of the LIMIT in tmoveto */
2712 tmoveto(term.c.x, term.c.y);
2713 /* Clearing both screens */
2716 if(mincol < col && 0 < minrow) {
2717 tclearregion(mincol, 0, col - 1, minrow - 1);
2719 if(0 < col && minrow < row) {
2720 tclearregion(0, minrow, col - 1, row - 1);
2723 } while(orig != term.line);
2729 xresize(int col, int row) {
2730 xw.tw = MAX(1, col * xw.cw);
2731 xw.th = MAX(1, row * xw.ch);
2733 XFreePixmap(xw.dpy, xw.buf);
2734 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2735 DefaultDepth(xw.dpy, xw.scr));
2736 XftDrawChange(xw.draw, xw.buf);
2737 xclear(0, 0, xw.w, xw.h);
2740 static inline ushort
2741 sixd_to_16bit(int x) {
2742 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2748 XRenderColor color = { .alpha = 0xffff };
2753 for (cp = dc.col; cp < dc.col + LEN(dc.col); ++cp)
2754 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
2757 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2758 for(i = 0; i < LEN(colorname); i++) {
2761 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2762 die("Could not allocate color '%s'\n", colorname[i]);
2766 /* load colors [16-255] ; same colors as xterm */
2767 for(i = 16, r = 0; r < 6; r++) {
2768 for(g = 0; g < 6; g++) {
2769 for(b = 0; b < 6; b++) {
2770 color.red = sixd_to_16bit(r);
2771 color.green = sixd_to_16bit(g);
2772 color.blue = sixd_to_16bit(b);
2773 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2774 die("Could not allocate color %d\n", i);
2781 for(r = 0; r < 24; r++, i++) {
2782 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2783 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2785 die("Could not allocate color %d\n", i);
2792 xsetcolorname(int x, const char *name) {
2793 XRenderColor color = { .alpha = 0xffff };
2795 if (x < 0 || x > LEN(colorname))
2798 if(16 <= x && x < 16 + 216) {
2799 int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2800 color.red = sixd_to_16bit(r);
2801 color.green = sixd_to_16bit(g);
2802 color.blue = sixd_to_16bit(b);
2803 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2804 return 0; /* something went wrong */
2807 } else if (16 + 216 <= x && x < 256) {
2808 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2809 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2810 return 0; /* something went wrong */
2814 name = colorname[x];
2817 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2824 xtermclear(int col1, int row1, int col2, int row2) {
2825 XftDrawRect(xw.draw,
2826 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2827 borderpx + col1 * xw.cw,
2828 borderpx + row1 * xw.ch,
2829 (col2-col1+1) * xw.cw,
2830 (row2-row1+1) * xw.ch);
2834 * Absolute coordinates.
2837 xclear(int x1, int y1, int x2, int y2) {
2838 XftDrawRect(xw.draw,
2839 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2840 x1, y1, x2-x1, y2-y1);
2845 XClassHint class = {opt_class ? opt_class : termname, termname};
2846 XWMHints wm = {.flags = InputHint, .input = 1};
2847 XSizeHints *sizeh = NULL;
2849 sizeh = XAllocSizeHints();
2850 if(xw.isfixed == False) {
2851 sizeh->flags = PSize | PResizeInc | PBaseSize;
2852 sizeh->height = xw.h;
2853 sizeh->width = xw.w;
2854 sizeh->height_inc = xw.ch;
2855 sizeh->width_inc = xw.cw;
2856 sizeh->base_height = 2 * borderpx;
2857 sizeh->base_width = 2 * borderpx;
2859 sizeh->flags = PMaxSize | PMinSize;
2860 sizeh->min_width = sizeh->max_width = xw.fw;
2861 sizeh->min_height = sizeh->max_height = xw.fh;
2864 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2869 xloadfont(Font *f, FcPattern *pattern) {
2873 match = FcFontMatch(NULL, pattern, &result);
2877 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2878 FcPatternDestroy(match);
2883 f->pattern = FcPatternDuplicate(pattern);
2885 f->ascent = f->match->ascent;
2886 f->descent = f->match->descent;
2888 f->rbearing = f->match->max_advance_width;
2890 f->height = f->ascent + f->descent;
2891 f->width = f->lbearing + f->rbearing;
2897 xloadfonts(char *fontstr, double fontsize) {
2899 FcResult r_sz, r_psz;
2902 if(fontstr[0] == '-') {
2903 pattern = XftXlfdParse(fontstr, False, False);
2905 pattern = FcNameParse((FcChar8 *)fontstr);
2909 die("st: can't open font %s\n", fontstr);
2912 FcPatternDel(pattern, FC_PIXEL_SIZE);
2913 FcPatternDel(pattern, FC_SIZE);
2914 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2915 usedfontsize = fontsize;
2917 r_psz = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2918 r_sz = FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval);
2919 if(r_psz == FcResultMatch) {
2920 usedfontsize = fontval;
2921 } else if(r_sz == FcResultMatch) {
2925 * Default font size is 12, if none given. This is to
2926 * have a known usedfontsize value.
2928 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2933 FcConfigSubstitute(0, pattern, FcMatchPattern);
2934 FcDefaultSubstitute(pattern);
2936 if(xloadfont(&dc.font, pattern))
2937 die("st: can't open font %s\n", fontstr);
2939 if(usedfontsize < 0) {
2940 FcPatternGetDouble(dc.font.match->pattern,
2941 FC_PIXEL_SIZE, 0, &fontval);
2942 usedfontsize = fontval;
2945 /* Setting character width and height. */
2946 xw.cw = CEIL(dc.font.width * cwscale);
2947 xw.ch = CEIL(dc.font.height * chscale);
2949 FcPatternDel(pattern, FC_SLANT);
2950 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2951 if(xloadfont(&dc.ifont, pattern))
2952 die("st: can't open font %s\n", fontstr);
2954 FcPatternDel(pattern, FC_WEIGHT);
2955 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2956 if(xloadfont(&dc.ibfont, pattern))
2957 die("st: can't open font %s\n", fontstr);
2959 FcPatternDel(pattern, FC_SLANT);
2960 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2961 if(xloadfont(&dc.bfont, pattern))
2962 die("st: can't open font %s\n", fontstr);
2964 FcPatternDestroy(pattern);
2968 xloadfontset(Font *f) {
2971 if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
2977 xunloadfont(Font *f) {
2978 XftFontClose(xw.dpy, f->match);
2979 FcPatternDestroy(f->pattern);
2981 FcFontSetDestroy(f->set);
2985 xunloadfonts(void) {
2988 /* Free the loaded fonts in the font cache. */
2989 for(i = 0; i < frclen; i++) {
2990 XftFontClose(xw.dpy, frc[i].font);
2994 xunloadfont(&dc.font);
2995 xunloadfont(&dc.bfont);
2996 xunloadfont(&dc.ifont);
2997 xunloadfont(&dc.ibfont);
3001 xzoom(const Arg *arg) {
3003 xloadfonts(usedfont, usedfontsize + arg->i);
3014 pid_t thispid = getpid();
3016 if(!(xw.dpy = XOpenDisplay(NULL)))
3017 die("Can't open display\n");
3018 xw.scr = XDefaultScreen(xw.dpy);
3019 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
3023 die("Could not init fontconfig.\n");
3025 usedfont = (opt_font == NULL)? font : opt_font;
3026 xloadfonts(usedfont, 0);
3029 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
3032 /* adjust fixed window geometry */
3034 sw = DisplayWidth(xw.dpy, xw.scr);
3035 sh = DisplayHeight(xw.dpy, xw.scr);
3037 xw.fx = sw + xw.fx - xw.fw - 1;
3039 xw.fy = sh + xw.fy - xw.fh - 1;
3044 /* window - default size */
3045 xw.h = 2 * borderpx + term.row * xw.ch;
3046 xw.w = 2 * borderpx + term.col * xw.cw;
3052 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
3053 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
3054 xw.attrs.bit_gravity = NorthWestGravity;
3055 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
3056 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
3057 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
3058 xw.attrs.colormap = xw.cmap;
3060 parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
3061 XRootWindow(xw.dpy, xw.scr);
3062 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
3063 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
3064 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
3065 | CWEventMask | CWColormap, &xw.attrs);
3067 memset(&gcvalues, 0, sizeof(gcvalues));
3068 gcvalues.graphics_exposures = False;
3069 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
3071 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3072 DefaultDepth(xw.dpy, xw.scr));
3073 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
3074 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
3076 /* Xft rendering context */
3077 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
3080 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3081 XSetLocaleModifiers("@im=local");
3082 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3083 XSetLocaleModifiers("@im=");
3084 if((xw.xim = XOpenIM(xw.dpy,
3085 NULL, NULL, NULL)) == NULL) {
3086 die("XOpenIM failed. Could not open input"
3091 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
3092 | XIMStatusNothing, XNClientWindow, xw.win,
3093 XNFocusWindow, xw.win, NULL);
3095 die("XCreateIC failed. Could not obtain input method.\n");
3097 /* white cursor, black outline */
3098 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
3099 XDefineCursor(xw.dpy, xw.win, cursor);
3100 XRecolorCursor(xw.dpy, cursor,
3101 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
3102 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
3104 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
3105 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
3106 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
3107 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
3109 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
3110 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
3111 PropModeReplace, (unsigned char *)&thispid, 1);
3114 XMapWindow(xw.dpy, xw.win);
3120 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
3121 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
3122 width = charlen * xw.cw, xp, i;
3124 int u8fl, u8fblen, u8cblen, doesexist;
3127 Font *font = &dc.font;
3129 FcPattern *fcpattern, *fontpattern;
3130 FcFontSet *fcsets[] = { NULL };
3131 FcCharSet *fccharset;
3132 Colour *fg, *bg, *temp, revfg, revbg, truefg, truebg;
3133 XRenderColor colfg, colbg;
3137 frcflags = FRC_NORMAL;
3139 if(base.mode & ATTR_ITALIC) {
3140 if(base.fg == defaultfg)
3141 base.fg = defaultitalic;
3143 frcflags = FRC_ITALIC;
3144 } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
3145 if(base.fg == defaultfg)
3146 base.fg = defaultitalic;
3148 frcflags = FRC_ITALICBOLD;
3149 } else if(base.mode & ATTR_UNDERLINE) {
3150 if(base.fg == defaultfg)
3151 base.fg = defaultunderline;
3153 if(IS_TRUECOL(base.fg)) {
3154 colfg.alpha = 0xffff;
3155 colfg.red = TRUERED(base.fg);
3156 colfg.green = TRUEGREEN(base.fg);
3157 colfg.blue = TRUEBLUE(base.fg);
3158 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
3161 fg = &dc.col[base.fg];
3164 if(IS_TRUECOL(base.bg)) {
3165 colbg.alpha = 0xffff;
3166 colbg.green = TRUEGREEN(base.bg);
3167 colbg.red = TRUERED(base.bg);
3168 colbg.blue = TRUEBLUE(base.bg);
3169 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
3172 bg = &dc.col[base.bg];
3177 if(base.mode & ATTR_BOLD) {
3178 if(BETWEEN(base.fg, 0, 7)) {
3179 /* basic system colors */
3180 fg = &dc.col[base.fg + 8];
3181 } else if(BETWEEN(base.fg, 16, 195)) {
3183 fg = &dc.col[base.fg + 36];
3184 } else if(BETWEEN(base.fg, 232, 251)) {
3186 fg = &dc.col[base.fg + 4];
3189 * Those ranges will not be brightened:
3190 * 8 - 15 – bright system colors
3191 * 196 - 231 – highest 256 color cube
3192 * 252 - 255 – brightest colors in greyscale
3195 frcflags = FRC_BOLD;
3198 if(IS_SET(MODE_REVERSE)) {
3199 if(fg == &dc.col[defaultfg]) {
3200 fg = &dc.col[defaultbg];
3202 colfg.red = ~fg->color.red;
3203 colfg.green = ~fg->color.green;
3204 colfg.blue = ~fg->color.blue;
3205 colfg.alpha = fg->color.alpha;
3206 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
3210 if(bg == &dc.col[defaultbg]) {
3211 bg = &dc.col[defaultfg];
3213 colbg.red = ~bg->color.red;
3214 colbg.green = ~bg->color.green;
3215 colbg.blue = ~bg->color.blue;
3216 colbg.alpha = bg->color.alpha;
3217 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
3222 if(base.mode & ATTR_REVERSE) {
3228 if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3231 /* Intelligent cleaning up of the borders. */
3233 xclear(0, (y == 0)? 0 : winy, borderpx,
3234 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3236 if(x + charlen >= term.col) {
3237 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3238 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3241 xclear(winx, 0, winx + width, borderpx);
3243 xclear(winx, winy + xw.ch, winx + width, xw.h);
3245 /* Clean up the region we want to draw to. */
3246 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3248 /* Set the clip region because Xft is sometimes dirty. */
3253 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3255 for(xp = winx; bytelen > 0;) {
3257 * Search for the range in the to be printed string of glyphs
3258 * that are in the main font. Then print that range. If
3259 * some glyph is found that is not in the font, do the
3265 oneatatime = font->width != xw.cw;
3268 u8cblen = utf8decode(s, &u8char);
3272 doesexist = XftCharExists(xw.dpy, font->match, u8char);
3273 if(oneatatime || !doesexist || bytelen <= 0) {
3274 if(oneatatime || bytelen <= 0) {
3282 XftDrawStringUtf8(xw.draw, fg,
3284 winy + font->ascent,
3302 /* Search the font cache. */
3303 for(i = 0; i < frclen; i++) {
3304 if(XftCharExists(xw.dpy, frc[i].font, u8char)
3305 && frc[i].flags == frcflags) {
3310 /* Nothing was found. */
3314 fcsets[0] = font->set;
3317 * Nothing was found in the cache. Now use
3318 * some dozen of Fontconfig calls to get the
3319 * font for one single character.
3321 fcpattern = FcPatternDuplicate(font->pattern);
3322 fccharset = FcCharSetCreate();
3324 FcCharSetAddChar(fccharset, u8char);
3325 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3327 FcPatternAddBool(fcpattern, FC_SCALABLE,
3330 FcConfigSubstitute(0, fcpattern,
3332 FcDefaultSubstitute(fcpattern);
3334 fontpattern = FcFontSetMatch(0, fcsets,
3335 FcTrue, fcpattern, &fcres);
3338 * Overwrite or create the new cache entry.
3340 if(frclen >= LEN(frc)) {
3341 frclen = LEN(frc) - 1;
3342 XftFontClose(xw.dpy, frc[frclen].font);
3345 frc[frclen].font = XftFontOpenPattern(xw.dpy,
3347 frc[frclen].flags = frcflags;
3352 FcPatternDestroy(fcpattern);
3353 FcCharSetDestroy(fccharset);
3356 XftDrawStringUtf8(xw.draw, fg, frc[i].font,
3357 xp, winy + frc[i].font->ascent,
3358 (FcChar8 *)u8c, u8cblen);
3360 xp += xw.cw * wcwidth(u8char);
3364 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
3365 winy + font->ascent, (FcChar8 *)s, bytelen);
3368 if(base.mode & ATTR_UNDERLINE) {
3369 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
3373 /* Reset clip to none. */
3374 XftDrawSetClip(xw.draw, 0);
3379 static int oldx = 0, oldy = 0;
3380 int sl, width, curx;
3381 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
3383 LIMIT(oldx, 0, term.col-1);
3384 LIMIT(oldy, 0, term.row-1);
3388 /* adjust position if in dummy */
3389 if(term.line[oldy][oldx].mode & ATTR_WDUMMY)
3391 if(term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3394 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
3396 /* remove the old cursor */
3397 sl = utf8size(term.line[oldy][oldx].c);
3398 width = (term.line[oldy][oldx].mode & ATTR_WIDE)? 2 : 1;
3399 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
3402 /* draw the new one */
3403 if(!(IS_SET(MODE_HIDE))) {
3404 if(xw.state & WIN_FOCUSED) {
3405 if(IS_SET(MODE_REVERSE)) {
3406 g.mode |= ATTR_REVERSE;
3412 width = (term.line[term.c.y][curx].mode & ATTR_WIDE)\
3414 xdraws(g.c, g, term.c.x, term.c.y, width, sl);
3416 XftDrawRect(xw.draw, &dc.col[defaultcs],
3417 borderpx + curx * xw.cw,
3418 borderpx + term.c.y * xw.ch,
3420 XftDrawRect(xw.draw, &dc.col[defaultcs],
3421 borderpx + curx * xw.cw,
3422 borderpx + term.c.y * xw.ch,
3424 XftDrawRect(xw.draw, &dc.col[defaultcs],
3425 borderpx + (curx + 1) * xw.cw - 1,
3426 borderpx + term.c.y * xw.ch,
3428 XftDrawRect(xw.draw, &dc.col[defaultcs],
3429 borderpx + curx * xw.cw,
3430 borderpx + (term.c.y + 1) * xw.ch - 1,
3433 oldx = curx, oldy = term.c.y;
3439 xsettitle(char *p) {
3442 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3444 XSetWMName(xw.dpy, xw.win, &prop);
3445 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
3451 xsettitle(opt_title ? opt_title : "st");
3455 redraw(int timeout) {
3456 struct timespec tv = {0, timeout * 1000};
3462 nanosleep(&tv, NULL);
3463 XSync(xw.dpy, False); /* necessary for a good tput flash */
3469 drawregion(0, 0, term.col, term.row);
3470 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3472 XSetForeground(xw.dpy, dc.gc,
3473 dc.col[IS_SET(MODE_REVERSE)?
3474 defaultfg : defaultbg].pixel);
3478 drawregion(int x1, int y1, int x2, int y2) {
3479 int ic, ib, x, y, ox, sl;
3481 char buf[DRAW_BUF_SIZ];
3482 bool ena_sel = sel.ob.x != -1;
3485 if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3488 if(!(xw.state & WIN_VISIBLE))
3491 for(y = y1; y < y2; y++) {
3495 xtermclear(0, y, term.col, y);
3497 base = term.line[y][0];
3499 for(x = x1; x < x2; x++) {
3500 new = term.line[y][x];
3501 if(new.mode == ATTR_WDUMMY)
3503 if(ena_sel && selected(x, y))
3504 new.mode ^= ATTR_REVERSE;
3505 if(ib > 0 && (ATTRCMP(base, new)
3506 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3507 xdraws(buf, base, ox, y, ic, ib);
3515 sl = utf8decode(new.c, &u8char);
3516 memcpy(buf+ib, new.c, sl);
3518 ic += (new.mode & ATTR_WIDE)? 2 : 1;
3521 xdraws(buf, base, ox, y, ic, ib);
3527 expose(XEvent *ev) {
3528 XExposeEvent *e = &ev->xexpose;
3530 if(xw.state & WIN_REDRAW) {
3532 xw.state &= ~WIN_REDRAW;
3538 visibility(XEvent *ev) {
3539 XVisibilityEvent *e = &ev->xvisibility;
3541 if(e->state == VisibilityFullyObscured) {
3542 xw.state &= ~WIN_VISIBLE;
3543 } else if(!(xw.state & WIN_VISIBLE)) {
3544 /* need a full redraw for next Expose, not just a buf copy */
3545 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3551 xw.state &= ~WIN_VISIBLE;
3555 xsetpointermotion(int set) {
3556 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3557 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3561 xseturgency(int add) {
3562 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3564 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3565 XSetWMHints(xw.dpy, xw.win, h);
3571 XFocusChangeEvent *e = &ev->xfocus;
3573 if(e->mode == NotifyGrab)
3576 if(ev->type == FocusIn) {
3577 XSetICFocus(xw.xic);
3578 xw.state |= WIN_FOCUSED;
3580 if(IS_SET(MODE_FOCUS))
3581 ttywrite("\033[I", 3);
3583 XUnsetICFocus(xw.xic);
3584 xw.state &= ~WIN_FOCUSED;
3585 if(IS_SET(MODE_FOCUS))
3586 ttywrite("\033[O", 3);
3591 match(uint mask, uint state) {
3592 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
3596 numlock(const Arg *dummy) {
3601 kmap(KeySym k, uint state) {
3605 /* Check for mapped keys out of X11 function keys. */
3606 for(i = 0; i < LEN(mappedkeys); i++) {
3607 if(mappedkeys[i] == k)
3610 if(i == LEN(mappedkeys)) {
3611 if((k & 0xFFFF) < 0xFD00)
3615 for(kp = key; kp < key + LEN(key); kp++) {
3619 if(!match(kp->mask, state))
3622 if(IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
3624 if(term.numlock && kp->appkey == 2)
3627 if(IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
3630 if(IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
3640 kpress(XEvent *ev) {
3641 XKeyEvent *e = &ev->xkey;
3643 char buf[32], *customkey;
3649 if(IS_SET(MODE_KBDLOCK))
3652 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
3654 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3655 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3656 bp->func(&(bp->arg));
3661 /* 2. custom keys from config.h */
3662 if((customkey = kmap(ksym, e->state))) {
3663 ttysend(customkey, strlen(customkey));
3667 /* 3. composed string from input method */
3670 if(len == 1 && e->state & Mod1Mask) {
3671 if(IS_SET(MODE_8BIT)) {
3674 len = utf8encode(&c, buf);
3687 cmessage(XEvent *e) {
3690 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3692 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3693 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3694 xw.state |= WIN_FOCUSED;
3696 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3697 xw.state &= ~WIN_FOCUSED;
3699 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3700 /* Send SIGHUP to shell */
3707 cresize(int width, int height) {
3715 col = (xw.w - 2 * borderpx) / xw.cw;
3716 row = (xw.h - 2 * borderpx) / xw.ch;
3725 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3728 cresize(e->xconfigure.width, e->xconfigure.height);
3734 int w = xw.w, h = xw.h;
3736 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3737 struct timeval drawtimeout, *tv = NULL, now, last, lastblink;
3739 /* Waiting for window mapping */
3741 XNextEvent(xw.dpy, &ev);
3742 if(ev.type == ConfigureNotify) {
3743 w = ev.xconfigure.width;
3744 h = ev.xconfigure.height;
3745 } else if(ev.type == MapNotify) {
3754 cresize(xw.fw, xw.fh);
3756 gettimeofday(&lastblink, NULL);
3757 gettimeofday(&last, NULL);
3759 for(xev = actionfps;;) {
3763 FD_SET(cmdfd, &rfd);
3766 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3769 die("select failed: %s\n", SERRNO);
3771 if(FD_ISSET(cmdfd, &rfd)) {
3774 blinkset = tattrset(ATTR_BLINK);
3776 MODBIT(term.mode, 0, MODE_BLINK);
3780 if(FD_ISSET(xfd, &rfd))
3783 gettimeofday(&now, NULL);
3784 drawtimeout.tv_sec = 0;
3785 drawtimeout.tv_usec = (1000/xfps) * 1000;
3789 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3790 tsetdirtattr(ATTR_BLINK);
3791 term.mode ^= MODE_BLINK;
3792 gettimeofday(&lastblink, NULL);
3795 deltatime = TIMEDIFF(now, last);
3796 if(deltatime > (xev? (1000/xfps) : (1000/actionfps))
3803 while(XPending(xw.dpy)) {
3804 XNextEvent(xw.dpy, &ev);
3805 if(XFilterEvent(&ev, None))
3807 if(handler[ev.type])
3808 (handler[ev.type])(&ev);
3814 if(xev && !FD_ISSET(xfd, &rfd))
3816 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3818 if(TIMEDIFF(now, lastblink) \
3820 drawtimeout.tv_usec = 1;
3822 drawtimeout.tv_usec = (1000 * \
3837 die("%s " VERSION " (c) 2010-2013 st engineers\n" \
3838 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
3839 " [-t title] [-w windowid] [-e command ...]\n", argv0);
3843 main(int argc, char *argv[]) {
3848 xw.fw = xw.fh = xw.fx = xw.fy = 0;
3853 allowaltscreen = false;
3856 opt_class = EARGF(usage());
3859 /* eat all remaining arguments */
3862 if(argv[1] != NULL && opt_title == NULL) {
3863 titles = xstrdup(argv[1]);
3864 opt_title = basename(titles);
3869 opt_font = EARGF(usage());
3872 bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
3877 if(bitm & WidthValue)
3879 if(bitm & HeightValue)
3881 if(bitm & XNegative && xw.fx == 0)
3883 if(bitm & YNegative && xw.fy == 0)
3886 if(xw.fh != 0 && xw.fw != 0)
3890 opt_io = EARGF(usage());
3893 opt_title = EARGF(usage());
3896 opt_embed = EARGF(usage());
3904 setlocale(LC_CTYPE, "");
3905 XSetLocaleModifiers("");