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 tclearregion(int, int, int, int);
362 static void tcursor(int);
363 static void tdeletechar(int);
364 static void tdeleteline(int);
365 static void tinsertblank(int);
366 static void tinsertblankline(int);
367 static void tmoveto(int, int);
368 static void tmoveato(int x, int y);
369 static void tnew(int, int);
370 static void tnewline(int);
371 static void tputtab(bool);
372 static void tputc(char *, int);
373 static void treset(void);
374 static int tresize(int, int);
375 static void tscrollup(int, int);
376 static void tscrolldown(int, int);
377 static void tsetattr(int*, int);
378 static void tsetchar(char *, Glyph *, int, int);
379 static void tsetscroll(int, int);
380 static void tswapscreen(void);
381 static void tsetdirt(int, int);
382 static void tsetdirtattr(int);
383 static void tsetmode(bool, bool, int *, int);
384 static void tfulldirt(void);
385 static void techo(char *, int);
386 static int32_t tdefcolor(int *, int *, int);
387 static void tselcs(void);
388 static void tdeftran(char);
389 static inline bool match(uint, uint);
390 static void ttynew(void);
391 static void ttyread(void);
392 static void ttyresize(void);
393 static void ttysend(char *, size_t);
394 static void ttywrite(const char *, size_t);
396 static void xdraws(char *, Glyph, int, int, int, int);
397 static void xhints(void);
398 static void xclear(int, int, int, int);
399 static void xdrawcursor(void);
400 static void xinit(void);
401 static void xloadcols(void);
402 static int xsetcolorname(int, const char *);
403 static int xloadfont(Font *, FcPattern *);
404 static void xloadfonts(char *, double);
405 static int xloadfontset(Font *);
406 static void xsettitle(char *);
407 static void xresettitle(void);
408 static void xsetpointermotion(int);
409 static void xseturgency(int);
410 static void xsetsel(char*);
411 static void xtermclear(int, int, int, int);
412 static void xunloadfont(Font *f);
413 static void xunloadfonts(void);
414 static void xresize(int, int);
416 static void expose(XEvent *);
417 static void visibility(XEvent *);
418 static void unmap(XEvent *);
419 static char *kmap(KeySym, uint);
420 static void kpress(XEvent *);
421 static void cmessage(XEvent *);
422 static void cresize(int, int);
423 static void resize(XEvent *);
424 static void focus(XEvent *);
425 static void brelease(XEvent *);
426 static void bpress(XEvent *);
427 static void bmotion(XEvent *);
428 static void selnotify(XEvent *);
429 static void selclear(XEvent *);
430 static void selrequest(XEvent *);
432 static void selinit(void);
433 static void selsort(void);
434 static inline bool selected(int, int);
435 static void selcopy(void);
436 static void selscroll(int, int);
437 static void selsnap(int, int *, int *, int);
439 static int utf8decode(char *, long *);
440 static int utf8encode(long *, char *);
441 static int utf8size(char *);
442 static int isfullutf8(char *, int);
444 static ssize_t xwrite(int, char *, size_t);
445 static void *xmalloc(size_t);
446 static void *xrealloc(void *, size_t);
447 static char *xstrdup(char *s);
449 static void (*handler[LASTEvent])(XEvent *) = {
451 [ClientMessage] = cmessage,
452 [ConfigureNotify] = resize,
453 [VisibilityNotify] = visibility,
454 [UnmapNotify] = unmap,
458 [MotionNotify] = bmotion,
459 [ButtonPress] = bpress,
460 [ButtonRelease] = brelease,
461 [SelectionClear] = selclear,
462 [SelectionNotify] = selnotify,
463 [SelectionRequest] = selrequest,
470 static CSIEscape csiescseq;
471 static STREscape strescseq;
474 static Selection sel;
475 static int iofd = STDOUT_FILENO;
476 static char **opt_cmd = NULL;
477 static char *opt_io = NULL;
478 static char *opt_title = NULL;
479 static char *opt_embed = NULL;
480 static char *opt_class = NULL;
481 static char *opt_font = NULL;
482 static int oldbutton = 3; /* button event on startup: 3 = release */
484 static char *usedfont = NULL;
485 static double usedfontsize = 0;
487 /* Font Ring Cache */
500 /* Fontcache is an array now. A new font will be appended to the array. */
501 static Fontcache frc[16];
502 static int frclen = 0;
505 xwrite(int fd, char *s, size_t len) {
509 ssize_t r = write(fd, s, len);
519 xmalloc(size_t len) {
520 void *p = malloc(len);
523 die("Out of memory\n");
529 xrealloc(void *p, size_t len) {
530 if((p = realloc(p, len)) == NULL)
531 die("Out of memory\n");
541 die("Out of memory\n");
547 utf8decode(char *s, long *u) {
553 if(~c & 0x80) { /* 0xxxxxxx */
556 } else if((c & 0xE0) == 0xC0) { /* 110xxxxx */
559 } else if((c & 0xF0) == 0xE0) { /* 1110xxxx */
562 } else if((c & 0xF8) == 0xF0) { /* 11110xxx */
569 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
571 if((c & 0xC0) != 0x80) /* 10xxxxxx */
577 if((n == 1 && *u < 0x80) ||
578 (n == 2 && *u < 0x800) ||
579 (n == 3 && *u < 0x10000) ||
580 (*u >= 0xD800 && *u <= 0xDFFF)) {
592 utf8encode(long *u, char *s) {
600 *sp = uc; /* 0xxxxxxx */
602 } else if(*u < 0x800) {
603 *sp = (uc >> 6) | 0xC0; /* 110xxxxx */
605 } else if(uc < 0x10000) {
606 *sp = (uc >> 12) | 0xE0; /* 1110xxxx */
608 } else if(uc <= 0x10FFFF) {
609 *sp = (uc >> 18) | 0xF0; /* 11110xxx */
615 for(i=n,++sp; i>0; --i,++sp)
616 *sp = ((uc >> 6*(i-1)) & 0x3F) | 0x80; /* 10xxxxxx */
628 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
629 UTF-8 otherwise return 0 */
631 isfullutf8(char *s, int b) {
639 } else if((*c1 & 0xE0) == 0xC0 && b == 1) {
641 } else if((*c1 & 0xF0) == 0xE0 &&
643 ((b == 2) && (*c2 & 0xC0) == 0x80))) {
645 } else if((*c1 & 0xF8) == 0xF0 &&
647 ((b == 2) && (*c2 & 0xC0) == 0x80) ||
648 ((b == 3) && (*c2 & 0xC0) == 0x80 && (*c3 & 0xC0) == 0x80))) {
661 } else if((c & 0xE0) == 0xC0) {
663 } else if((c & 0xF0) == 0xE0) {
672 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
673 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
677 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
678 if(sel.xtarget == None)
679 sel.xtarget = XA_STRING;
687 return LIMIT(x, 0, term.col-1);
695 return LIMIT(y, 0, term.row-1);
700 if(sel.ob.y == sel.oe.y) {
701 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
702 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
704 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
705 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
707 sel.nb.y = MIN(sel.ob.y, sel.oe.y);
708 sel.ne.y = MAX(sel.ob.y, sel.oe.y);
712 selected(int x, int y) {
713 if(sel.ne.y == y && sel.nb.y == y)
714 return BETWEEN(x, sel.nb.x, sel.ne.x);
716 if(sel.type == SEL_RECTANGULAR) {
717 return ((sel.nb.y <= y && y <= sel.ne.y)
718 && (sel.nb.x <= x && x <= sel.ne.x));
721 return ((sel.nb.y < y && y < sel.ne.y)
722 || (y == sel.ne.y && x <= sel.ne.x))
723 || (y == sel.nb.y && x >= sel.nb.x
724 && (x <= sel.ne.x || sel.nb.y != sel.ne.y));
728 selsnap(int mode, int *x, int *y, int direction) {
734 * Snap around if the word wraps around at the end or
735 * beginning of a line.
738 if(direction < 0 && *x <= 0) {
739 if(*y > 0 && term.line[*y - 1][term.col-1].mode
747 if(direction > 0 && *x >= term.col-1) {
748 if(*y < term.row-1 && term.line[*y][*x].mode
757 if(term.line[*y][*x+direction].mode & ATTR_WDUMMY) {
762 if(strchr(worddelimiters,
763 term.line[*y][*x+direction].c[0])) {
772 * Snap around if the the previous line or the current one
773 * has set ATTR_WRAP at its end. Then the whole next or
774 * previous line will be selected.
776 *x = (direction < 0) ? 0 : term.col - 1;
777 if(direction < 0 && *y > 0) {
778 for(; *y > 0; *y += direction) {
779 if(!(term.line[*y-1][term.col-1].mode
784 } else if(direction > 0 && *y < term.row-1) {
785 for(; *y < term.row; *y += direction) {
786 if(!(term.line[*y][term.col-1].mode
795 * Select the whole line when the end of line is reached.
799 while(--i > 0 && term.line[*y][i].c[0] == ' ')
809 getbuttoninfo(XEvent *e) {
811 uint state = e->xbutton.state &~Button1Mask;
813 sel.alt = IS_SET(MODE_ALTSCREEN);
815 sel.oe.x = x2col(e->xbutton.x);
816 sel.oe.y = y2row(e->xbutton.y);
818 if(sel.ob.y < sel.oe.y
819 || (sel.ob.y == sel.oe.y && sel.ob.x < sel.oe.x)) {
820 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
821 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
823 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, -1);
824 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, +1);
828 sel.type = SEL_REGULAR;
829 for(type = 1; type < LEN(selmasks); ++type) {
830 if(match(selmasks[type], state)) {
838 mousereport(XEvent *e) {
839 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
840 button = e->xbutton.button, state = e->xbutton.state,
846 if(e->xbutton.type == MotionNotify) {
847 if(x == ox && y == oy)
849 if(!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
851 /* MOUSE_MOTION: no reporting if no button is pressed */
852 if(IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
855 button = oldbutton + 32;
859 if(!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
866 if(e->xbutton.type == ButtonPress) {
870 } else if(e->xbutton.type == ButtonRelease) {
872 /* MODE_MOUSEX10: no button release reporting */
873 if(IS_SET(MODE_MOUSEX10))
878 if(!IS_SET(MODE_MOUSEX10)) {
879 button += (state & ShiftMask ? 4 : 0)
880 + (state & Mod4Mask ? 8 : 0)
881 + (state & ControlMask ? 16 : 0);
885 if(IS_SET(MODE_MOUSESGR)) {
886 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
888 e->xbutton.type == ButtonRelease ? 'm' : 'M');
889 } else if(x < 223 && y < 223) {
890 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
891 32+button, 32+x+1, 32+y+1);
904 if(IS_SET(MODE_MOUSE)) {
909 for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
910 if(e->xbutton.button == mk->b
911 && match(mk->mask, e->xbutton.state)) {
912 ttysend(mk->s, strlen(mk->s));
917 if(e->xbutton.button == Button1) {
918 gettimeofday(&now, NULL);
920 /* Clear previous selection, logically and visually. */
923 sel.type = SEL_REGULAR;
924 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
925 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
928 * If the user clicks below predefined timeouts specific
929 * snapping behaviour is exposed.
931 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
932 sel.snap = SNAP_LINE;
933 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
934 sel.snap = SNAP_WORD;
938 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
939 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
943 * Draw selection, unless it's regular and we don't want to
944 * make clicks visible
948 tsetdirt(sel.nb.y, sel.ne.y);
950 sel.tclick2 = sel.tclick1;
958 int x, y, bufsize, size, i, ex;
964 bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
965 ptr = str = xmalloc(bufsize);
967 /* append every set & selected glyph to the selection */
968 for(y = sel.nb.y; y < sel.ne.y + 1; y++) {
969 gp = &term.line[y][0];
970 last = &gp[term.col-1];
972 while(last >= gp && !(selected(last - gp, y) &&
973 strcmp(last->c, " ") != 0)) {
977 for(x = 0; gp <= last; x++, ++gp) {
978 if(!selected(x, y) || (gp->mode & ATTR_WDUMMY))
981 size = utf8size(gp->c);
982 memcpy(ptr, gp->c, size);
987 * Copy and pasting of line endings is inconsistent
988 * in the inconsistent terminal and GUI world.
989 * The best solution seems like to produce '\n' when
990 * something is copied from st and convert '\n' to
991 * '\r', when something to be pasted is received by
993 * FIXME: Fix the computer world.
995 if(y < sel.ne.y && x > 0 && !((gp-1)->mode & ATTR_WRAP))
999 * If the last selected line expands in the selection
1000 * after the visible text '\n' is appended.
1004 while(--i > 0 && term.line[y][i].c[0] == ' ')
1007 if(sel.nb.y == sel.ne.y && sel.ne.x < sel.nb.x)
1019 selnotify(XEvent *e) {
1020 ulong nitems, ofs, rem;
1022 uchar *data, *last, *repl;
1027 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
1028 False, AnyPropertyType, &type, &format,
1029 &nitems, &rem, &data)) {
1030 fprintf(stderr, "Clipboard allocation failed\n");
1035 * As seen in selcopy:
1036 * Line endings are inconsistent in the terminal and GUI world
1037 * copy and pasting. When receiving some selection data,
1038 * replace all '\n' with '\r'.
1039 * FIXME: Fix the computer world.
1042 last = data + nitems * format / 8;
1043 while((repl = memchr(repl, '\n', last - repl))) {
1047 if(IS_SET(MODE_BRCKTPASTE))
1048 ttywrite("\033[200~", 6);
1049 ttysend((char *)data, nitems * format / 8);
1050 if(IS_SET(MODE_BRCKTPASTE))
1051 ttywrite("\033[201~", 6);
1053 /* number of 32-bit chunks returned */
1054 ofs += nitems * format / 32;
1059 selpaste(const Arg *dummy) {
1060 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1061 xw.win, CurrentTime);
1065 clippaste(const Arg *dummy) {
1068 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1069 XConvertSelection(xw.dpy, clipboard, sel.xtarget, XA_PRIMARY,
1070 xw.win, CurrentTime);
1074 selclear(XEvent *e) {
1078 tsetdirt(sel.nb.y, sel.ne.y);
1082 selrequest(XEvent *e) {
1083 XSelectionRequestEvent *xsre;
1084 XSelectionEvent xev;
1085 Atom xa_targets, string;
1087 xsre = (XSelectionRequestEvent *) e;
1088 xev.type = SelectionNotify;
1089 xev.requestor = xsre->requestor;
1090 xev.selection = xsre->selection;
1091 xev.target = xsre->target;
1092 xev.time = xsre->time;
1094 xev.property = None;
1096 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1097 if(xsre->target == xa_targets) {
1098 /* respond with the supported type */
1099 string = sel.xtarget;
1100 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1101 XA_ATOM, 32, PropModeReplace,
1102 (uchar *) &string, 1);
1103 xev.property = xsre->property;
1104 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
1105 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1106 xsre->target, 8, PropModeReplace,
1107 (uchar *) sel.clip, strlen(sel.clip));
1108 xev.property = xsre->property;
1111 /* all done, send a notification to the listener */
1112 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
1113 fprintf(stderr, "Error sending SelectionNotify event\n");
1117 xsetsel(char *str) {
1118 /* register the selection for both the clipboard and the primary */
1124 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
1126 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1127 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1131 brelease(XEvent *e) {
1132 if(IS_SET(MODE_MOUSE)) {
1137 if(e->xbutton.button == Button2) {
1139 } else if(e->xbutton.button == Button1) {
1147 tsetdirt(sel.nb.y, sel.ne.y);
1152 bmotion(XEvent *e) {
1153 int oldey, oldex, oldsby, oldsey;
1155 if(IS_SET(MODE_MOUSE)) {
1170 if(oldey != sel.oe.y || oldex != sel.oe.x)
1171 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1175 die(const char *errstr, ...) {
1178 va_start(ap, errstr);
1179 vfprintf(stderr, errstr, ap);
1187 char *envshell = getenv("SHELL");
1188 const struct passwd *pass = getpwuid(getuid());
1189 char buf[sizeof(long) * 8 + 1];
1191 unsetenv("COLUMNS");
1193 unsetenv("TERMCAP");
1196 setenv("LOGNAME", pass->pw_name, 1);
1197 setenv("USER", pass->pw_name, 1);
1198 setenv("SHELL", pass->pw_shell, 0);
1199 setenv("HOME", pass->pw_dir, 0);
1202 snprintf(buf, sizeof(buf), "%lu", xw.win);
1203 setenv("WINDOWID", buf, 1);
1205 signal(SIGCHLD, SIG_DFL);
1206 signal(SIGHUP, SIG_DFL);
1207 signal(SIGINT, SIG_DFL);
1208 signal(SIGQUIT, SIG_DFL);
1209 signal(SIGTERM, SIG_DFL);
1210 signal(SIGALRM, SIG_DFL);
1212 DEFAULT(envshell, shell);
1213 setenv("TERM", termname, 1);
1214 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
1215 execvp(args[0], args);
1223 if(waitpid(pid, &stat, 0) < 0)
1224 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
1226 if(WIFEXITED(stat)) {
1227 exit(WEXITSTATUS(stat));
1236 struct winsize w = {term.row, term.col, 0, 0};
1238 /* seems to work fine on linux, openbsd and freebsd */
1239 if(openpty(&m, &s, NULL, NULL, &w) < 0)
1240 die("openpty failed: %s\n", SERRNO);
1242 switch(pid = fork()) {
1244 die("fork failed\n");
1247 setsid(); /* create a new process group */
1248 dup2(s, STDIN_FILENO);
1249 dup2(s, STDOUT_FILENO);
1250 dup2(s, STDERR_FILENO);
1251 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1252 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
1260 signal(SIGCHLD, sigchld);
1262 term.mode |= MODE_PRINT;
1263 iofd = (!strcmp(opt_io, "-")) ?
1265 open(opt_io, O_WRONLY | O_CREAT, 0666);
1267 fprintf(stderr, "Error opening %s:%s\n",
1268 opt_io, strerror(errno));
1278 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1280 fprintf(stderr, "\n");
1285 static char buf[BUFSIZ];
1286 static int buflen = 0;
1289 int charsize; /* size of utf8 char in bytes */
1293 /* append read bytes to unprocessed bytes */
1294 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1295 die("Couldn't read from shell: %s\n", SERRNO);
1297 /* process every complete utf8 char */
1300 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1301 charsize = utf8decode(ptr, &utf8c);
1302 utf8encode(&utf8c, s);
1308 /* keep any uncomplete utf8 char for the next call */
1309 memmove(buf, ptr, buflen);
1313 ttywrite(const char *s, size_t n) {
1314 if(write(cmdfd, s, n) == -1)
1315 die("write error on tty: %s\n", SERRNO);
1319 ttysend(char *s, size_t n) {
1321 if(IS_SET(MODE_ECHO))
1329 w.ws_row = term.row;
1330 w.ws_col = term.col;
1331 w.ws_xpixel = xw.tw;
1332 w.ws_ypixel = xw.th;
1333 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1334 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1338 tattrset(int attr) {
1341 for(i = 0; i < term.row-1; i++) {
1342 for(j = 0; j < term.col-1; j++) {
1343 if(term.line[i][j].mode & attr)
1352 tsetdirt(int top, int bot) {
1355 LIMIT(top, 0, term.row-1);
1356 LIMIT(bot, 0, term.row-1);
1358 for(i = top; i <= bot; i++)
1363 tsetdirtattr(int attr) {
1366 for(i = 0; i < term.row-1; i++) {
1367 for(j = 0; j < term.col-1; j++) {
1368 if(term.line[i][j].mode & attr) {
1378 tsetdirt(0, term.row-1);
1383 static TCursor c[2];
1384 bool alt = IS_SET(MODE_ALTSCREEN);
1386 if(mode == CURSOR_SAVE) {
1388 } else if(mode == CURSOR_LOAD) {
1390 tmoveto(c[alt].x, c[alt].y);
1398 term.c = (TCursor){{
1402 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1404 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1405 for(i = tabspaces; i < term.col; i += tabspaces)
1408 term.bot = term.row - 1;
1409 term.mode = MODE_WRAP;
1410 memset(term.trantbl, sizeof(term.trantbl), CS_USA);
1413 tclearregion(0, 0, term.col-1, term.row-1);
1415 tcursor(CURSOR_SAVE);
1419 tnew(int col, int row) {
1420 term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
1429 Line *tmp = term.line;
1431 term.line = term.alt;
1433 term.mode ^= MODE_ALTSCREEN;
1438 tscrolldown(int orig, int n) {
1442 LIMIT(n, 0, term.bot-orig+1);
1444 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1446 for(i = term.bot; i >= orig+n; i--) {
1447 temp = term.line[i];
1448 term.line[i] = term.line[i-n];
1449 term.line[i-n] = temp;
1452 term.dirty[i-n] = 1;
1459 tscrollup(int orig, int n) {
1462 LIMIT(n, 0, term.bot-orig+1);
1464 tclearregion(0, orig, term.col-1, orig+n-1);
1466 for(i = orig; i <= term.bot-n; i++) {
1467 temp = term.line[i];
1468 term.line[i] = term.line[i+n];
1469 term.line[i+n] = temp;
1472 term.dirty[i+n] = 1;
1475 selscroll(orig, -n);
1479 selscroll(int orig, int n) {
1483 if(BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1484 if((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1488 if(sel.type == SEL_RECTANGULAR) {
1489 if(sel.ob.y < term.top)
1490 sel.ob.y = term.top;
1491 if(sel.oe.y > term.bot)
1492 sel.oe.y = term.bot;
1494 if(sel.ob.y < term.top) {
1495 sel.ob.y = term.top;
1498 if(sel.oe.y > term.bot) {
1499 sel.oe.y = term.bot;
1500 sel.oe.x = term.col;
1508 tnewline(int first_col) {
1512 tscrollup(term.top, 1);
1516 tmoveto(first_col ? 0 : term.c.x, y);
1521 char *p = csiescseq.buf, *np;
1530 csiescseq.buf[csiescseq.len] = '\0';
1531 while(p < csiescseq.buf+csiescseq.len) {
1533 v = strtol(p, &np, 10);
1536 if(v == LONG_MAX || v == LONG_MIN)
1538 csiescseq.arg[csiescseq.narg++] = v;
1540 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1544 csiescseq.mode = *p;
1547 /* for absolute user moves, when decom is set */
1549 tmoveato(int x, int y) {
1550 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1554 tmoveto(int x, int y) {
1557 if(term.c.state & CURSOR_ORIGIN) {
1562 maxy = term.row - 1;
1564 LIMIT(x, 0, term.col-1);
1565 LIMIT(y, miny, maxy);
1566 term.c.state &= ~CURSOR_WRAPNEXT;
1572 tsetchar(char *c, Glyph *attr, int x, int y) {
1573 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1574 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1575 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1576 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1577 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1578 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1579 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1580 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1581 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1585 * The table is proudly stolen from rxvt.
1587 if(attr->mode & ATTR_GFX) {
1588 if(c[0] >= 0x41 && c[0] <= 0x7e
1589 && vt100_0[c[0] - 0x41]) {
1590 c = vt100_0[c[0] - 0x41];
1594 if(term.line[y][x].mode & ATTR_WIDE) {
1595 if(x+1 < term.col) {
1596 term.line[y][x+1].c[0] = ' ';
1597 term.line[y][x+1].mode &= ~ATTR_WDUMMY;
1599 } else if(term.line[y][x].mode & ATTR_WDUMMY) {
1600 term.line[y][x-1].c[0] = ' ';
1601 term.line[y][x-1].mode &= ~ATTR_WIDE;
1605 term.line[y][x] = *attr;
1606 memcpy(term.line[y][x].c, c, UTF_SIZ);
1610 tclearregion(int x1, int y1, int x2, int y2) {
1614 temp = x1, x1 = x2, x2 = temp;
1616 temp = y1, y1 = y2, y2 = temp;
1618 LIMIT(x1, 0, term.col-1);
1619 LIMIT(x2, 0, term.col-1);
1620 LIMIT(y1, 0, term.row-1);
1621 LIMIT(y2, 0, term.row-1);
1623 for(y = y1; y <= y2; y++) {
1625 for(x = x1; x <= x2; x++) {
1628 term.line[y][x] = term.c.attr;
1629 memcpy(term.line[y][x].c, " ", 2);
1635 tdeletechar(int n) {
1636 int src = term.c.x + n;
1638 int size = term.col - src;
1640 term.dirty[term.c.y] = 1;
1642 if(src >= term.col) {
1643 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1647 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1648 size * sizeof(Glyph));
1649 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1653 tinsertblank(int n) {
1656 int size = term.col - dst;
1658 term.dirty[term.c.y] = 1;
1660 if(dst >= term.col) {
1661 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1665 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1666 size * sizeof(Glyph));
1667 tclearregion(src, term.c.y, dst - 1, term.c.y);
1671 tinsertblankline(int n) {
1672 if(term.c.y < term.top || term.c.y > term.bot)
1675 tscrolldown(term.c.y, n);
1679 tdeleteline(int n) {
1680 if(term.c.y < term.top || term.c.y > term.bot)
1683 tscrollup(term.c.y, n);
1687 tdefcolor(int *attr, int *npar, int l) {
1691 switch (attr[*npar + 1]) {
1692 case 2: /* direct colour in RGB space */
1693 if (*npar + 4 >= l) {
1695 "erresc(38): Incorrect number of parameters (%d)\n",
1699 r = attr[*npar + 2];
1700 g = attr[*npar + 3];
1701 b = attr[*npar + 4];
1703 if(!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1704 fprintf(stderr, "erresc: bad rgb color (%d,%d,%d)\n",
1707 idx = TRUECOLOR(r, g, b);
1709 case 5: /* indexed colour */
1710 if (*npar + 2 >= l) {
1712 "erresc(38): Incorrect number of parameters (%d)\n",
1717 if(!BETWEEN(attr[*npar], 0, 255))
1718 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
1722 case 0: /* implemented defined (only foreground) */
1723 case 1: /* transparent */
1724 case 3: /* direct colour in CMY space */
1725 case 4: /* direct colour in CMYK space */
1728 "erresc(38): gfx attr %d unknown\n", attr[*npar]);
1735 tsetattr(int *attr, int l) {
1739 for(i = 0; i < l; i++) {
1742 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE \
1743 | ATTR_BOLD | ATTR_ITALIC \
1745 term.c.attr.fg = defaultfg;
1746 term.c.attr.bg = defaultbg;
1749 term.c.attr.mode |= ATTR_BOLD;
1752 term.c.attr.mode |= ATTR_ITALIC;
1755 term.c.attr.mode |= ATTR_UNDERLINE;
1757 case 5: /* slow blink */
1758 case 6: /* rapid blink */
1759 term.c.attr.mode |= ATTR_BLINK;
1762 term.c.attr.mode |= ATTR_REVERSE;
1766 term.c.attr.mode &= ~ATTR_BOLD;
1769 term.c.attr.mode &= ~ATTR_ITALIC;
1772 term.c.attr.mode &= ~ATTR_UNDERLINE;
1776 term.c.attr.mode &= ~ATTR_BLINK;
1779 term.c.attr.mode &= ~ATTR_REVERSE;
1782 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1783 term.c.attr.fg = idx;
1786 term.c.attr.fg = defaultfg;
1789 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1790 term.c.attr.bg = idx;
1793 term.c.attr.bg = defaultbg;
1796 if(BETWEEN(attr[i], 30, 37)) {
1797 term.c.attr.fg = attr[i] - 30;
1798 } else if(BETWEEN(attr[i], 40, 47)) {
1799 term.c.attr.bg = attr[i] - 40;
1800 } else if(BETWEEN(attr[i], 90, 97)) {
1801 term.c.attr.fg = attr[i] - 90 + 8;
1802 } else if(BETWEEN(attr[i], 100, 107)) {
1803 term.c.attr.bg = attr[i] - 100 + 8;
1806 "erresc(default): gfx attr %d unknown\n",
1807 attr[i]), csidump();
1815 tsetscroll(int t, int b) {
1818 LIMIT(t, 0, term.row-1);
1819 LIMIT(b, 0, term.row-1);
1829 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1832 tsetmode(bool priv, bool set, int *args, int narg) {
1836 for(lim = args + narg; args < lim; ++args) {
1840 case 1: /* DECCKM -- Cursor key */
1841 MODBIT(term.mode, set, MODE_APPCURSOR);
1843 case 5: /* DECSCNM -- Reverse video */
1845 MODBIT(term.mode, set, MODE_REVERSE);
1846 if(mode != term.mode)
1847 redraw(REDRAW_TIMEOUT);
1849 case 6: /* DECOM -- Origin */
1850 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1853 case 7: /* DECAWM -- Auto wrap */
1854 MODBIT(term.mode, set, MODE_WRAP);
1856 case 0: /* Error (IGNORED) */
1857 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1858 case 3: /* DECCOLM -- Column (IGNORED) */
1859 case 4: /* DECSCLM -- Scroll (IGNORED) */
1860 case 8: /* DECARM -- Auto repeat (IGNORED) */
1861 case 18: /* DECPFF -- Printer feed (IGNORED) */
1862 case 19: /* DECPEX -- Printer extent (IGNORED) */
1863 case 42: /* DECNRCM -- National characters (IGNORED) */
1864 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1866 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1867 MODBIT(term.mode, !set, MODE_HIDE);
1869 case 9: /* X10 mouse compatibility mode */
1870 xsetpointermotion(0);
1871 MODBIT(term.mode, 0, MODE_MOUSE);
1872 MODBIT(term.mode, set, MODE_MOUSEX10);
1874 case 1000: /* 1000: report button press */
1875 xsetpointermotion(0);
1876 MODBIT(term.mode, 0, MODE_MOUSE);
1877 MODBIT(term.mode, set, MODE_MOUSEBTN);
1879 case 1002: /* 1002: report motion on button press */
1880 xsetpointermotion(0);
1881 MODBIT(term.mode, 0, MODE_MOUSE);
1882 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1884 case 1003: /* 1003: enable all mouse motions */
1885 xsetpointermotion(set);
1886 MODBIT(term.mode, 0, MODE_MOUSE);
1887 MODBIT(term.mode, set, MODE_MOUSEMANY);
1889 case 1004: /* 1004: send focus events to tty */
1890 MODBIT(term.mode, set, MODE_FOCUS);
1892 case 1006: /* 1006: extended reporting mode */
1893 MODBIT(term.mode, set, MODE_MOUSESGR);
1896 MODBIT(term.mode, set, MODE_8BIT);
1898 case 1049: /* swap screen & set/restore cursor as xterm */
1899 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1900 case 47: /* swap screen */
1902 if (!allowaltscreen)
1904 alt = IS_SET(MODE_ALTSCREEN);
1906 tclearregion(0, 0, term.col-1,
1909 if(set ^ alt) /* set is always 1 or 0 */
1915 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1917 case 2004: /* 2004: bracketed paste mode */
1918 MODBIT(term.mode, set, MODE_BRCKTPASTE);
1920 /* Not implemented mouse modes. See comments there. */
1921 case 1001: /* mouse highlight mode; can hang the
1922 terminal by design when implemented. */
1923 case 1005: /* UTF-8 mouse mode; will confuse
1924 applications not supporting UTF-8
1926 case 1015: /* urxvt mangled mouse mode; incompatible
1927 and can be mistaken for other control
1931 "erresc: unknown private set/reset mode %d\n",
1937 case 0: /* Error (IGNORED) */
1939 case 2: /* KAM -- keyboard action */
1940 MODBIT(term.mode, set, MODE_KBDLOCK);
1942 case 4: /* IRM -- Insertion-replacement */
1943 MODBIT(term.mode, set, MODE_INSERT);
1945 case 12: /* SRM -- Send/Receive */
1946 MODBIT(term.mode, !set, MODE_ECHO);
1948 case 20: /* LNM -- Linefeed/new line */
1949 MODBIT(term.mode, set, MODE_CRLF);
1953 "erresc: unknown set/reset mode %d\n",
1966 switch(csiescseq.mode) {
1969 fprintf(stderr, "erresc: unknown csi ");
1973 case '@': /* ICH -- Insert <n> blank char */
1974 DEFAULT(csiescseq.arg[0], 1);
1975 tinsertblank(csiescseq.arg[0]);
1977 case 'A': /* CUU -- Cursor <n> Up */
1978 DEFAULT(csiescseq.arg[0], 1);
1979 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1981 case 'B': /* CUD -- Cursor <n> Down */
1982 case 'e': /* VPR --Cursor <n> Down */
1983 DEFAULT(csiescseq.arg[0], 1);
1984 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1986 case 'i': /* MC -- Media Copy */
1987 switch(csiescseq.arg[0]) {
1990 tdumpline(term.c.y);
1993 term.mode &= ~MODE_PRINT;
1996 term.mode |= MODE_PRINT;
2000 case 'c': /* DA -- Device Attributes */
2001 if(csiescseq.arg[0] == 0)
2002 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2004 case 'C': /* CUF -- Cursor <n> Forward */
2005 case 'a': /* HPR -- Cursor <n> Forward */
2006 DEFAULT(csiescseq.arg[0], 1);
2007 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
2009 case 'D': /* CUB -- Cursor <n> Backward */
2010 DEFAULT(csiescseq.arg[0], 1);
2011 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
2013 case 'E': /* CNL -- Cursor <n> Down and first col */
2014 DEFAULT(csiescseq.arg[0], 1);
2015 tmoveto(0, term.c.y+csiescseq.arg[0]);
2017 case 'F': /* CPL -- Cursor <n> Up and first col */
2018 DEFAULT(csiescseq.arg[0], 1);
2019 tmoveto(0, term.c.y-csiescseq.arg[0]);
2021 case 'g': /* TBC -- Tabulation clear */
2022 switch(csiescseq.arg[0]) {
2023 case 0: /* clear current tab stop */
2024 term.tabs[term.c.x] = 0;
2026 case 3: /* clear all the tabs */
2027 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
2033 case 'G': /* CHA -- Move to <col> */
2035 DEFAULT(csiescseq.arg[0], 1);
2036 tmoveto(csiescseq.arg[0]-1, term.c.y);
2038 case 'H': /* CUP -- Move to <row> <col> */
2040 DEFAULT(csiescseq.arg[0], 1);
2041 DEFAULT(csiescseq.arg[1], 1);
2042 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
2044 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
2045 DEFAULT(csiescseq.arg[0], 1);
2046 while(csiescseq.arg[0]--)
2049 case 'J': /* ED -- Clear screen */
2051 switch(csiescseq.arg[0]) {
2053 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
2054 if(term.c.y < term.row-1) {
2055 tclearregion(0, term.c.y+1, term.col-1,
2061 tclearregion(0, 0, term.col-1, term.c.y-1);
2062 tclearregion(0, term.c.y, term.c.x, term.c.y);
2065 tclearregion(0, 0, term.col-1, term.row-1);
2071 case 'K': /* EL -- Clear line */
2072 switch(csiescseq.arg[0]) {
2074 tclearregion(term.c.x, term.c.y, term.col-1,
2078 tclearregion(0, term.c.y, term.c.x, term.c.y);
2081 tclearregion(0, term.c.y, term.col-1, term.c.y);
2085 case 'S': /* SU -- Scroll <n> line up */
2086 DEFAULT(csiescseq.arg[0], 1);
2087 tscrollup(term.top, csiescseq.arg[0]);
2089 case 'T': /* SD -- Scroll <n> line down */
2090 DEFAULT(csiescseq.arg[0], 1);
2091 tscrolldown(term.top, csiescseq.arg[0]);
2093 case 'L': /* IL -- Insert <n> blank lines */
2094 DEFAULT(csiescseq.arg[0], 1);
2095 tinsertblankline(csiescseq.arg[0]);
2097 case 'l': /* RM -- Reset Mode */
2098 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2100 case 'M': /* DL -- Delete <n> lines */
2101 DEFAULT(csiescseq.arg[0], 1);
2102 tdeleteline(csiescseq.arg[0]);
2104 case 'X': /* ECH -- Erase <n> char */
2105 DEFAULT(csiescseq.arg[0], 1);
2106 tclearregion(term.c.x, term.c.y,
2107 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2109 case 'P': /* DCH -- Delete <n> char */
2110 DEFAULT(csiescseq.arg[0], 1);
2111 tdeletechar(csiescseq.arg[0]);
2113 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2114 DEFAULT(csiescseq.arg[0], 1);
2115 while(csiescseq.arg[0]--)
2118 case 'd': /* VPA -- Move to <row> */
2119 DEFAULT(csiescseq.arg[0], 1);
2120 tmoveato(term.c.x, csiescseq.arg[0]-1);
2122 case 'h': /* SM -- Set terminal mode */
2123 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2125 case 'm': /* SGR -- Terminal attribute (color) */
2126 tsetattr(csiescseq.arg, csiescseq.narg);
2128 case 'n': /* DSR – Device Status Report (cursor position) */
2129 if (csiescseq.arg[0] == 6) {
2130 len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
2131 term.c.y+1, term.c.x+1);
2135 case 'r': /* DECSTBM -- Set Scrolling Region */
2136 if(csiescseq.priv) {
2139 DEFAULT(csiescseq.arg[0], 1);
2140 DEFAULT(csiescseq.arg[1], term.row);
2141 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2145 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2146 tcursor(CURSOR_SAVE);
2148 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2149 tcursor(CURSOR_LOAD);
2160 for(i = 0; i < csiescseq.len; i++) {
2161 c = csiescseq.buf[i] & 0xff;
2164 } else if(c == '\n') {
2166 } else if(c == '\r') {
2168 } else if(c == 0x1b) {
2171 printf("(%02x)", c);
2179 memset(&csiescseq, 0, sizeof(csiescseq));
2188 narg = strescseq.narg;
2189 par = atoi(strescseq.args[0]);
2191 switch(strescseq.type) {
2192 case ']': /* OSC -- Operating System Command */
2198 xsettitle(strescseq.args[1]);
2200 case 4: /* color set */
2203 p = strescseq.args[2];
2205 case 104: /* color reset, here p = NULL */
2206 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2207 if (!xsetcolorname(j, p)) {
2208 fprintf(stderr, "erresc: invalid color %s\n", p);
2211 * TODO if defaultbg color is changed, borders
2219 case 'k': /* old title set compatibility */
2220 xsettitle(strescseq.args[0]);
2222 case 'P': /* DSC -- Device Control String */
2223 case '_': /* APC -- Application Program Command */
2224 case '^': /* PM -- Privacy Message */
2228 fprintf(stderr, "erresc: unknown str ");
2234 char *p = strescseq.buf;
2237 strescseq.buf[strescseq.len] = '\0';
2238 while(p && strescseq.narg < STR_ARG_SIZ)
2239 strescseq.args[strescseq.narg++] = strsep(&p, ";");
2247 printf("ESC%c", strescseq.type);
2248 for(i = 0; i < strescseq.len; i++) {
2249 c = strescseq.buf[i] & 0xff;
2252 } else if(isprint(c)) {
2254 } else if(c == '\n') {
2256 } else if(c == '\r') {
2258 } else if(c == 0x1b) {
2261 printf("(%02x)", c);
2269 memset(&strescseq, 0, sizeof(strescseq));
2273 tprinter(char *s, size_t len) {
2274 if(iofd != -1 && xwrite(iofd, s, len) < 0) {
2275 fprintf(stderr, "Error writing in %s:%s\n",
2276 opt_io, strerror(errno));
2286 bp = &term.line[n][0];
2287 end = &bp[term.col-1];
2288 while(end > bp && !strcmp(" ", end->c))
2290 if(bp != end || strcmp(bp->c, " ")) {
2291 for( ;bp <= end; ++bp)
2292 tprinter(bp->c, strlen(bp->c));
2298 tputtab(bool forward) {
2304 for(++x; x < term.col && !term.tabs[x]; ++x)
2309 for(--x; x > 0 && !term.tabs[x]; --x)
2312 tmoveto(x, term.c.y);
2316 techo(char *buf, int len) {
2317 for(; len > 0; buf++, len--) {
2320 if(c == '\033') { /* escape */
2323 } else if(c < '\x20') { /* control code */
2324 if(c != '\n' && c != '\r' && c != '\t') {
2338 tdeftran(char ascii) {
2340 static char tbl[][2] = {
2341 {'0', CS_GRAPHIC0}, {'1', CS_GRAPHIC1}, {'A', CS_UK},
2342 {'B', CS_USA}, {'<', CS_MULTI}, {'K', CS_GER},
2343 {'5', CS_FIN}, {'C', CS_FIN},
2347 for (bp = &tbl[0]; (c = (*bp)[0]) && c != ascii; ++bp)
2351 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2353 term.trantbl[term.icharset] = (*bp)[1];
2358 if (term.trantbl[term.charset] == CS_GRAPHIC0)
2359 term.c.attr.mode |= ATTR_GFX;
2361 term.c.attr.mode &= ~ATTR_GFX;
2365 tputc(char *c, int len) {
2367 bool control = ascii < '\x20' || ascii == 0177;
2374 utf8decode(c, &u8char);
2375 width = wcwidth(u8char);
2378 if(IS_SET(MODE_PRINT))
2382 * STR sequences must be checked before anything else
2383 * because it can use some control codes as part of the sequence.
2385 if(term.esc & ESC_STR) {
2388 term.esc = ESC_START | ESC_STR_END;
2390 case '\a': /* backwards compatibility to xterm */
2395 if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2396 memmove(&strescseq.buf[strescseq.len], c, len);
2397 strescseq.len += len;
2400 * Here is a bug in terminals. If the user never sends
2401 * some code to stop the str or esc command, then st
2402 * will stop responding. But this is better than
2403 * silently failing with unknown characters. At least
2404 * then users will report back.
2406 * In the case users ever get fixed, here is the code:
2418 * Actions of control codes must be performed as soon they arrive
2419 * because they can be embedded inside a control sequence, and
2420 * they must not cause conflicts with sequences.
2428 tmoveto(term.c.x-1, term.c.y);
2431 tmoveto(0, term.c.y);
2436 /* go to first col if the mode is set */
2437 tnewline(IS_SET(MODE_CRLF));
2439 case '\a': /* BEL */
2440 if(!(xw.state & WIN_FOCUSED))
2443 XBell(xw.dpy, bellvolume);
2445 case '\033': /* ESC */
2447 term.esc = ESC_START;
2449 case '\016': /* SO */
2453 case '\017': /* SI */
2457 case '\032': /* SUB */
2458 case '\030': /* CAN */
2461 case '\005': /* ENQ (IGNORED) */
2462 case '\000': /* NUL (IGNORED) */
2463 case '\021': /* XON (IGNORED) */
2464 case '\023': /* XOFF (IGNORED) */
2465 case 0177: /* DEL (IGNORED) */
2468 } else if(term.esc & ESC_START) {
2469 if(term.esc & ESC_CSI) {
2470 csiescseq.buf[csiescseq.len++] = ascii;
2471 if(BETWEEN(ascii, 0x40, 0x7E)
2472 || csiescseq.len >= \
2473 sizeof(csiescseq.buf)-1) {
2478 } else if(term.esc & ESC_STR_END) {
2482 } else if(term.esc & ESC_ALTCHARSET) {
2486 } else if(term.esc & ESC_TEST) {
2487 if(ascii == '8') { /* DEC screen alignment test. */
2488 char E[UTF_SIZ] = "E";
2491 for(x = 0; x < term.col; ++x) {
2492 for(y = 0; y < term.row; ++y)
2493 tsetchar(E, &term.c.attr, x, y);
2500 term.esc |= ESC_CSI;
2503 term.esc |= ESC_TEST;
2505 case 'P': /* DCS -- Device Control String */
2506 case '_': /* APC -- Application Program Command */
2507 case '^': /* PM -- Privacy Message */
2508 case ']': /* OSC -- Operating System Command */
2509 case 'k': /* old title set compatibility */
2511 strescseq.type = ascii;
2512 term.esc |= ESC_STR;
2514 case '(': /* set primary charset G0 */
2515 case ')': /* set secondary charset G1 */
2516 case '*': /* set tertiary charset G2 */
2517 case '+': /* set quaternary charset G3 */
2518 term.icharset = ascii - '(';
2519 term.esc |= ESC_ALTCHARSET;
2521 case 'D': /* IND -- Linefeed */
2522 if(term.c.y == term.bot) {
2523 tscrollup(term.top, 1);
2525 tmoveto(term.c.x, term.c.y+1);
2529 case 'E': /* NEL -- Next line */
2530 tnewline(1); /* always go to first col */
2533 case 'H': /* HTS -- Horizontal tab stop */
2534 term.tabs[term.c.x] = 1;
2537 case 'M': /* RI -- Reverse index */
2538 if(term.c.y == term.top) {
2539 tscrolldown(term.top, 1);
2541 tmoveto(term.c.x, term.c.y-1);
2545 case 'Z': /* DECID -- Identify Terminal */
2546 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2549 case 'c': /* RIS -- Reset to inital state */
2555 case '=': /* DECPAM -- Application keypad */
2556 term.mode |= MODE_APPKEYPAD;
2559 case '>': /* DECPNM -- Normal keypad */
2560 term.mode &= ~MODE_APPKEYPAD;
2563 case '7': /* DECSC -- Save Cursor */
2564 tcursor(CURSOR_SAVE);
2567 case '8': /* DECRC -- Restore Cursor */
2568 tcursor(CURSOR_LOAD);
2571 case '\\': /* ST -- Stop */
2575 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2576 (uchar) ascii, isprint(ascii)? ascii:'.');
2581 * All characters which form part of a sequence are not
2587 * Display control codes only if we are in graphic mode
2589 if(control && !(term.c.attr.mode & ATTR_GFX))
2591 if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2593 if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2594 term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
2598 if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2599 memmove(&term.line[term.c.y][term.c.x+1],
2600 &term.line[term.c.y][term.c.x],
2601 (term.col - term.c.x - 1) * sizeof(Glyph));
2604 if(term.c.x+width > term.col)
2607 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2610 term.line[term.c.y][term.c.x].mode |= ATTR_WIDE;
2611 if(term.c.x+1 < term.col) {
2612 term.line[term.c.y][term.c.x+1].c[0] = '\0';
2613 term.line[term.c.y][term.c.x+1].mode = ATTR_WDUMMY;
2616 if(term.c.x+width < term.col) {
2617 tmoveto(term.c.x+width, term.c.y);
2619 term.c.state |= CURSOR_WRAPNEXT;
2624 tresize(int col, int row) {
2626 int minrow = MIN(row, term.row);
2627 int mincol = MIN(col, term.col);
2628 int slide = term.c.y - row + 1;
2632 if(col < 1 || row < 1)
2635 /* free unneeded rows */
2639 * slide screen to keep cursor where we expect it -
2640 * tscrollup would work here, but we can optimize to
2641 * memmove because we're freeing the earlier lines
2643 for(/* i = 0 */; i < slide; i++) {
2647 memmove(term.line, term.line + slide, row * sizeof(Line));
2648 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2650 for(i += row; i < term.row; i++) {
2655 /* resize to new height */
2656 term.line = xrealloc(term.line, row * sizeof(Line));
2657 term.alt = xrealloc(term.alt, row * sizeof(Line));
2658 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2659 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2661 /* resize each row to new width, zero-pad if needed */
2662 for(i = 0; i < minrow; i++) {
2664 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2665 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2668 /* allocate any new rows */
2669 for(/* i == minrow */; i < row; i++) {
2671 term.line[i] = xmalloc(col * sizeof(Glyph));
2672 term.alt[i] = xmalloc(col * sizeof(Glyph));
2674 if(col > term.col) {
2675 bp = term.tabs + term.col;
2677 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2678 while(--bp > term.tabs && !*bp)
2680 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2683 /* update terminal size */
2686 /* reset scrolling region */
2687 tsetscroll(0, row-1);
2688 /* make use of the LIMIT in tmoveto */
2689 tmoveto(term.c.x, term.c.y);
2690 /* Clearing both screens */
2693 if(mincol < col && 0 < minrow) {
2694 tclearregion(mincol, 0, col - 1, minrow - 1);
2696 if(0 < col && minrow < row) {
2697 tclearregion(0, minrow, col - 1, row - 1);
2700 } while(orig != term.line);
2706 xresize(int col, int row) {
2707 xw.tw = MAX(1, col * xw.cw);
2708 xw.th = MAX(1, row * xw.ch);
2710 XFreePixmap(xw.dpy, xw.buf);
2711 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2712 DefaultDepth(xw.dpy, xw.scr));
2713 XftDrawChange(xw.draw, xw.buf);
2714 xclear(0, 0, xw.w, xw.h);
2717 static inline ushort
2718 sixd_to_16bit(int x) {
2719 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2725 XRenderColor color = { .alpha = 0xffff };
2730 for (cp = dc.col; cp < dc.col + LEN(dc.col); ++cp)
2731 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
2734 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2735 for(i = 0; i < LEN(colorname); i++) {
2738 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2739 die("Could not allocate color '%s'\n", colorname[i]);
2743 /* load colors [16-255] ; same colors as xterm */
2744 for(i = 16, r = 0; r < 6; r++) {
2745 for(g = 0; g < 6; g++) {
2746 for(b = 0; b < 6; b++) {
2747 color.red = sixd_to_16bit(r);
2748 color.green = sixd_to_16bit(g);
2749 color.blue = sixd_to_16bit(b);
2750 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2751 die("Could not allocate color %d\n", i);
2758 for(r = 0; r < 24; r++, i++) {
2759 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2760 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2762 die("Could not allocate color %d\n", i);
2769 xsetcolorname(int x, const char *name) {
2770 XRenderColor color = { .alpha = 0xffff };
2772 if (x < 0 || x > LEN(colorname))
2775 if(16 <= x && x < 16 + 216) {
2776 int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2777 color.red = sixd_to_16bit(r);
2778 color.green = sixd_to_16bit(g);
2779 color.blue = sixd_to_16bit(b);
2780 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2781 return 0; /* something went wrong */
2784 } else if (16 + 216 <= x && x < 256) {
2785 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2786 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2787 return 0; /* something went wrong */
2791 name = colorname[x];
2794 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2801 xtermclear(int col1, int row1, int col2, int row2) {
2802 XftDrawRect(xw.draw,
2803 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2804 borderpx + col1 * xw.cw,
2805 borderpx + row1 * xw.ch,
2806 (col2-col1+1) * xw.cw,
2807 (row2-row1+1) * xw.ch);
2811 * Absolute coordinates.
2814 xclear(int x1, int y1, int x2, int y2) {
2815 XftDrawRect(xw.draw,
2816 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2817 x1, y1, x2-x1, y2-y1);
2822 XClassHint class = {opt_class ? opt_class : termname, termname};
2823 XWMHints wm = {.flags = InputHint, .input = 1};
2824 XSizeHints *sizeh = NULL;
2826 sizeh = XAllocSizeHints();
2827 if(xw.isfixed == False) {
2828 sizeh->flags = PSize | PResizeInc | PBaseSize;
2829 sizeh->height = xw.h;
2830 sizeh->width = xw.w;
2831 sizeh->height_inc = xw.ch;
2832 sizeh->width_inc = xw.cw;
2833 sizeh->base_height = 2 * borderpx;
2834 sizeh->base_width = 2 * borderpx;
2836 sizeh->flags = PMaxSize | PMinSize;
2837 sizeh->min_width = sizeh->max_width = xw.fw;
2838 sizeh->min_height = sizeh->max_height = xw.fh;
2841 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2846 xloadfont(Font *f, FcPattern *pattern) {
2850 match = FcFontMatch(NULL, pattern, &result);
2854 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2855 FcPatternDestroy(match);
2860 f->pattern = FcPatternDuplicate(pattern);
2862 f->ascent = f->match->ascent;
2863 f->descent = f->match->descent;
2865 f->rbearing = f->match->max_advance_width;
2867 f->height = f->ascent + f->descent;
2868 f->width = f->lbearing + f->rbearing;
2874 xloadfonts(char *fontstr, double fontsize) {
2876 FcResult r_sz, r_psz;
2879 if(fontstr[0] == '-') {
2880 pattern = XftXlfdParse(fontstr, False, False);
2882 pattern = FcNameParse((FcChar8 *)fontstr);
2886 die("st: can't open font %s\n", fontstr);
2889 FcPatternDel(pattern, FC_PIXEL_SIZE);
2890 FcPatternDel(pattern, FC_SIZE);
2891 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2892 usedfontsize = fontsize;
2894 r_psz = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2895 r_sz = FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval);
2896 if(r_psz == FcResultMatch) {
2897 usedfontsize = fontval;
2898 } else if(r_sz == FcResultMatch) {
2902 * Default font size is 12, if none given. This is to
2903 * have a known usedfontsize value.
2905 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2910 FcConfigSubstitute(0, pattern, FcMatchPattern);
2911 FcDefaultSubstitute(pattern);
2913 if(xloadfont(&dc.font, pattern))
2914 die("st: can't open font %s\n", fontstr);
2916 if(usedfontsize < 0) {
2917 FcPatternGetDouble(dc.font.match->pattern,
2918 FC_PIXEL_SIZE, 0, &fontval);
2919 usedfontsize = fontval;
2922 /* Setting character width and height. */
2923 xw.cw = CEIL(dc.font.width * cwscale);
2924 xw.ch = CEIL(dc.font.height * chscale);
2926 FcPatternDel(pattern, FC_SLANT);
2927 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2928 if(xloadfont(&dc.ifont, pattern))
2929 die("st: can't open font %s\n", fontstr);
2931 FcPatternDel(pattern, FC_WEIGHT);
2932 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2933 if(xloadfont(&dc.ibfont, pattern))
2934 die("st: can't open font %s\n", fontstr);
2936 FcPatternDel(pattern, FC_SLANT);
2937 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2938 if(xloadfont(&dc.bfont, pattern))
2939 die("st: can't open font %s\n", fontstr);
2941 FcPatternDestroy(pattern);
2945 xloadfontset(Font *f) {
2948 if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
2954 xunloadfont(Font *f) {
2955 XftFontClose(xw.dpy, f->match);
2956 FcPatternDestroy(f->pattern);
2958 FcFontSetDestroy(f->set);
2962 xunloadfonts(void) {
2965 /* Free the loaded fonts in the font cache. */
2966 for(i = 0; i < frclen; i++) {
2967 XftFontClose(xw.dpy, frc[i].font);
2971 xunloadfont(&dc.font);
2972 xunloadfont(&dc.bfont);
2973 xunloadfont(&dc.ifont);
2974 xunloadfont(&dc.ibfont);
2978 xzoom(const Arg *arg) {
2980 xloadfonts(usedfont, usedfontsize + arg->i);
2991 pid_t thispid = getpid();
2993 if(!(xw.dpy = XOpenDisplay(NULL)))
2994 die("Can't open display\n");
2995 xw.scr = XDefaultScreen(xw.dpy);
2996 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
3000 die("Could not init fontconfig.\n");
3002 usedfont = (opt_font == NULL)? font : opt_font;
3003 xloadfonts(usedfont, 0);
3006 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
3009 /* adjust fixed window geometry */
3011 sw = DisplayWidth(xw.dpy, xw.scr);
3012 sh = DisplayHeight(xw.dpy, xw.scr);
3014 xw.fx = sw + xw.fx - xw.fw - 1;
3016 xw.fy = sh + xw.fy - xw.fh - 1;
3021 /* window - default size */
3022 xw.h = 2 * borderpx + term.row * xw.ch;
3023 xw.w = 2 * borderpx + term.col * xw.cw;
3029 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
3030 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
3031 xw.attrs.bit_gravity = NorthWestGravity;
3032 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
3033 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
3034 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
3035 xw.attrs.colormap = xw.cmap;
3037 parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
3038 XRootWindow(xw.dpy, xw.scr);
3039 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
3040 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
3041 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
3042 | CWEventMask | CWColormap, &xw.attrs);
3044 memset(&gcvalues, 0, sizeof(gcvalues));
3045 gcvalues.graphics_exposures = False;
3046 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
3048 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3049 DefaultDepth(xw.dpy, xw.scr));
3050 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
3051 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
3053 /* Xft rendering context */
3054 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
3057 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3058 XSetLocaleModifiers("@im=local");
3059 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3060 XSetLocaleModifiers("@im=");
3061 if((xw.xim = XOpenIM(xw.dpy,
3062 NULL, NULL, NULL)) == NULL) {
3063 die("XOpenIM failed. Could not open input"
3068 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
3069 | XIMStatusNothing, XNClientWindow, xw.win,
3070 XNFocusWindow, xw.win, NULL);
3072 die("XCreateIC failed. Could not obtain input method.\n");
3074 /* white cursor, black outline */
3075 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
3076 XDefineCursor(xw.dpy, xw.win, cursor);
3077 XRecolorCursor(xw.dpy, cursor,
3078 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
3079 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
3081 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
3082 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
3083 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
3084 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
3086 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
3087 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
3088 PropModeReplace, (unsigned char *)&thispid, 1);
3091 XMapWindow(xw.dpy, xw.win);
3097 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
3098 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
3099 width = charlen * xw.cw, xp, i;
3101 int u8fl, u8fblen, u8cblen, doesexist;
3104 Font *font = &dc.font;
3106 FcPattern *fcpattern, *fontpattern;
3107 FcFontSet *fcsets[] = { NULL };
3108 FcCharSet *fccharset;
3109 Colour *fg, *bg, *temp, revfg, revbg, truefg, truebg;
3110 XRenderColor colfg, colbg;
3114 frcflags = FRC_NORMAL;
3116 if(base.mode & ATTR_ITALIC) {
3117 if(base.fg == defaultfg)
3118 base.fg = defaultitalic;
3120 frcflags = FRC_ITALIC;
3121 } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
3122 if(base.fg == defaultfg)
3123 base.fg = defaultitalic;
3125 frcflags = FRC_ITALICBOLD;
3126 } else if(base.mode & ATTR_UNDERLINE) {
3127 if(base.fg == defaultfg)
3128 base.fg = defaultunderline;
3130 if(IS_TRUECOL(base.fg)) {
3131 colfg.alpha = 0xffff;
3132 colfg.red = TRUERED(base.fg);
3133 colfg.green = TRUEGREEN(base.fg);
3134 colfg.blue = TRUEBLUE(base.fg);
3135 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
3138 fg = &dc.col[base.fg];
3141 if(IS_TRUECOL(base.bg)) {
3142 colbg.alpha = 0xffff;
3143 colbg.green = TRUEGREEN(base.bg);
3144 colbg.red = TRUERED(base.bg);
3145 colbg.blue = TRUEBLUE(base.bg);
3146 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
3149 bg = &dc.col[base.bg];
3154 if(base.mode & ATTR_BOLD) {
3155 if(BETWEEN(base.fg, 0, 7)) {
3156 /* basic system colors */
3157 fg = &dc.col[base.fg + 8];
3158 } else if(BETWEEN(base.fg, 16, 195)) {
3160 fg = &dc.col[base.fg + 36];
3161 } else if(BETWEEN(base.fg, 232, 251)) {
3163 fg = &dc.col[base.fg + 4];
3166 * Those ranges will not be brightened:
3167 * 8 - 15 – bright system colors
3168 * 196 - 231 – highest 256 color cube
3169 * 252 - 255 – brightest colors in greyscale
3172 frcflags = FRC_BOLD;
3175 if(IS_SET(MODE_REVERSE)) {
3176 if(fg == &dc.col[defaultfg]) {
3177 fg = &dc.col[defaultbg];
3179 colfg.red = ~fg->color.red;
3180 colfg.green = ~fg->color.green;
3181 colfg.blue = ~fg->color.blue;
3182 colfg.alpha = fg->color.alpha;
3183 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
3187 if(bg == &dc.col[defaultbg]) {
3188 bg = &dc.col[defaultfg];
3190 colbg.red = ~bg->color.red;
3191 colbg.green = ~bg->color.green;
3192 colbg.blue = ~bg->color.blue;
3193 colbg.alpha = bg->color.alpha;
3194 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
3199 if(base.mode & ATTR_REVERSE) {
3205 if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3208 /* Intelligent cleaning up of the borders. */
3210 xclear(0, (y == 0)? 0 : winy, borderpx,
3211 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3213 if(x + charlen >= term.col) {
3214 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3215 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3218 xclear(winx, 0, winx + width, borderpx);
3220 xclear(winx, winy + xw.ch, winx + width, xw.h);
3222 /* Clean up the region we want to draw to. */
3223 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3225 /* Set the clip region because Xft is sometimes dirty. */
3230 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3232 for(xp = winx; bytelen > 0;) {
3234 * Search for the range in the to be printed string of glyphs
3235 * that are in the main font. Then print that range. If
3236 * some glyph is found that is not in the font, do the
3242 oneatatime = font->width != xw.cw;
3245 u8cblen = utf8decode(s, &u8char);
3249 doesexist = XftCharExists(xw.dpy, font->match, u8char);
3250 if(oneatatime || !doesexist || bytelen <= 0) {
3251 if(oneatatime || bytelen <= 0) {
3259 XftDrawStringUtf8(xw.draw, fg,
3261 winy + font->ascent,
3279 /* Search the font cache. */
3280 for(i = 0; i < frclen; i++) {
3281 if(XftCharExists(xw.dpy, frc[i].font, u8char)
3282 && frc[i].flags == frcflags) {
3287 /* Nothing was found. */
3291 fcsets[0] = font->set;
3294 * Nothing was found in the cache. Now use
3295 * some dozen of Fontconfig calls to get the
3296 * font for one single character.
3298 fcpattern = FcPatternDuplicate(font->pattern);
3299 fccharset = FcCharSetCreate();
3301 FcCharSetAddChar(fccharset, u8char);
3302 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3304 FcPatternAddBool(fcpattern, FC_SCALABLE,
3307 FcConfigSubstitute(0, fcpattern,
3309 FcDefaultSubstitute(fcpattern);
3311 fontpattern = FcFontSetMatch(0, fcsets,
3312 FcTrue, fcpattern, &fcres);
3315 * Overwrite or create the new cache entry.
3317 if(frclen >= LEN(frc)) {
3318 frclen = LEN(frc) - 1;
3319 XftFontClose(xw.dpy, frc[frclen].font);
3322 frc[frclen].font = XftFontOpenPattern(xw.dpy,
3324 frc[frclen].flags = frcflags;
3329 FcPatternDestroy(fcpattern);
3330 FcCharSetDestroy(fccharset);
3333 XftDrawStringUtf8(xw.draw, fg, frc[i].font,
3334 xp, winy + frc[i].font->ascent,
3335 (FcChar8 *)u8c, u8cblen);
3337 xp += xw.cw * wcwidth(u8char);
3341 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
3342 winy + font->ascent, (FcChar8 *)s, bytelen);
3345 if(base.mode & ATTR_UNDERLINE) {
3346 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
3350 /* Reset clip to none. */
3351 XftDrawSetClip(xw.draw, 0);
3356 static int oldx = 0, oldy = 0;
3357 int sl, width, curx;
3358 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
3360 LIMIT(oldx, 0, term.col-1);
3361 LIMIT(oldy, 0, term.row-1);
3365 /* adjust position if in dummy */
3366 if(term.line[oldy][oldx].mode & ATTR_WDUMMY)
3368 if(term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3371 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
3373 /* remove the old cursor */
3374 sl = utf8size(term.line[oldy][oldx].c);
3375 width = (term.line[oldy][oldx].mode & ATTR_WIDE)? 2 : 1;
3376 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
3379 /* draw the new one */
3380 if(!(IS_SET(MODE_HIDE))) {
3381 if(xw.state & WIN_FOCUSED) {
3382 if(IS_SET(MODE_REVERSE)) {
3383 g.mode |= ATTR_REVERSE;
3389 width = (term.line[term.c.y][curx].mode & ATTR_WIDE)\
3391 xdraws(g.c, g, term.c.x, term.c.y, width, sl);
3393 XftDrawRect(xw.draw, &dc.col[defaultcs],
3394 borderpx + curx * xw.cw,
3395 borderpx + term.c.y * xw.ch,
3397 XftDrawRect(xw.draw, &dc.col[defaultcs],
3398 borderpx + curx * xw.cw,
3399 borderpx + term.c.y * xw.ch,
3401 XftDrawRect(xw.draw, &dc.col[defaultcs],
3402 borderpx + (curx + 1) * xw.cw - 1,
3403 borderpx + term.c.y * xw.ch,
3405 XftDrawRect(xw.draw, &dc.col[defaultcs],
3406 borderpx + curx * xw.cw,
3407 borderpx + (term.c.y + 1) * xw.ch - 1,
3410 oldx = curx, oldy = term.c.y;
3416 xsettitle(char *p) {
3419 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3421 XSetWMName(xw.dpy, xw.win, &prop);
3422 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
3428 xsettitle(opt_title ? opt_title : "st");
3432 redraw(int timeout) {
3433 struct timespec tv = {0, timeout * 1000};
3439 nanosleep(&tv, NULL);
3440 XSync(xw.dpy, False); /* necessary for a good tput flash */
3446 drawregion(0, 0, term.col, term.row);
3447 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3449 XSetForeground(xw.dpy, dc.gc,
3450 dc.col[IS_SET(MODE_REVERSE)?
3451 defaultfg : defaultbg].pixel);
3455 drawregion(int x1, int y1, int x2, int y2) {
3456 int ic, ib, x, y, ox, sl;
3458 char buf[DRAW_BUF_SIZ];
3459 bool ena_sel = sel.ob.x != -1;
3462 if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3465 if(!(xw.state & WIN_VISIBLE))
3468 for(y = y1; y < y2; y++) {
3472 xtermclear(0, y, term.col, y);
3474 base = term.line[y][0];
3476 for(x = x1; x < x2; x++) {
3477 new = term.line[y][x];
3478 if(new.mode == ATTR_WDUMMY)
3480 if(ena_sel && selected(x, y))
3481 new.mode ^= ATTR_REVERSE;
3482 if(ib > 0 && (ATTRCMP(base, new)
3483 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3484 xdraws(buf, base, ox, y, ic, ib);
3492 sl = utf8decode(new.c, &u8char);
3493 memcpy(buf+ib, new.c, sl);
3495 ic += (new.mode & ATTR_WIDE)? 2 : 1;
3498 xdraws(buf, base, ox, y, ic, ib);
3504 expose(XEvent *ev) {
3505 XExposeEvent *e = &ev->xexpose;
3507 if(xw.state & WIN_REDRAW) {
3509 xw.state &= ~WIN_REDRAW;
3515 visibility(XEvent *ev) {
3516 XVisibilityEvent *e = &ev->xvisibility;
3518 if(e->state == VisibilityFullyObscured) {
3519 xw.state &= ~WIN_VISIBLE;
3520 } else if(!(xw.state & WIN_VISIBLE)) {
3521 /* need a full redraw for next Expose, not just a buf copy */
3522 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3528 xw.state &= ~WIN_VISIBLE;
3532 xsetpointermotion(int set) {
3533 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3534 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3538 xseturgency(int add) {
3539 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3541 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3542 XSetWMHints(xw.dpy, xw.win, h);
3548 XFocusChangeEvent *e = &ev->xfocus;
3550 if(e->mode == NotifyGrab)
3553 if(ev->type == FocusIn) {
3554 XSetICFocus(xw.xic);
3555 xw.state |= WIN_FOCUSED;
3557 if(IS_SET(MODE_FOCUS))
3558 ttywrite("\033[I", 3);
3560 XUnsetICFocus(xw.xic);
3561 xw.state &= ~WIN_FOCUSED;
3562 if(IS_SET(MODE_FOCUS))
3563 ttywrite("\033[O", 3);
3568 match(uint mask, uint state) {
3569 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
3573 numlock(const Arg *dummy) {
3578 kmap(KeySym k, uint state) {
3582 /* Check for mapped keys out of X11 function keys. */
3583 for(i = 0; i < LEN(mappedkeys); i++) {
3584 if(mappedkeys[i] == k)
3587 if(i == LEN(mappedkeys)) {
3588 if((k & 0xFFFF) < 0xFD00)
3592 for(kp = key; kp < key + LEN(key); kp++) {
3596 if(!match(kp->mask, state))
3599 if(IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
3601 if(term.numlock && kp->appkey == 2)
3604 if(IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
3607 if(IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
3617 kpress(XEvent *ev) {
3618 XKeyEvent *e = &ev->xkey;
3620 char buf[32], *customkey;
3626 if(IS_SET(MODE_KBDLOCK))
3629 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
3631 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3632 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3633 bp->func(&(bp->arg));
3638 /* 2. custom keys from config.h */
3639 if((customkey = kmap(ksym, e->state))) {
3640 ttysend(customkey, strlen(customkey));
3644 /* 3. composed string from input method */
3647 if(len == 1 && e->state & Mod1Mask) {
3648 if(IS_SET(MODE_8BIT)) {
3651 len = utf8encode(&c, buf);
3664 cmessage(XEvent *e) {
3667 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3669 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3670 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3671 xw.state |= WIN_FOCUSED;
3673 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3674 xw.state &= ~WIN_FOCUSED;
3676 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3677 /* Send SIGHUP to shell */
3684 cresize(int width, int height) {
3692 col = (xw.w - 2 * borderpx) / xw.cw;
3693 row = (xw.h - 2 * borderpx) / xw.ch;
3702 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3705 cresize(e->xconfigure.width, e->xconfigure.height);
3711 int w = xw.w, h = xw.h;
3713 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3714 struct timeval drawtimeout, *tv = NULL, now, last, lastblink;
3716 /* Waiting for window mapping */
3718 XNextEvent(xw.dpy, &ev);
3719 if(ev.type == ConfigureNotify) {
3720 w = ev.xconfigure.width;
3721 h = ev.xconfigure.height;
3722 } else if(ev.type == MapNotify) {
3731 cresize(xw.fw, xw.fh);
3733 gettimeofday(&lastblink, NULL);
3734 gettimeofday(&last, NULL);
3736 for(xev = actionfps;;) {
3740 FD_SET(cmdfd, &rfd);
3743 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3746 die("select failed: %s\n", SERRNO);
3748 if(FD_ISSET(cmdfd, &rfd)) {
3751 blinkset = tattrset(ATTR_BLINK);
3753 MODBIT(term.mode, 0, MODE_BLINK);
3757 if(FD_ISSET(xfd, &rfd))
3760 gettimeofday(&now, NULL);
3761 drawtimeout.tv_sec = 0;
3762 drawtimeout.tv_usec = (1000/xfps) * 1000;
3766 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3767 tsetdirtattr(ATTR_BLINK);
3768 term.mode ^= MODE_BLINK;
3769 gettimeofday(&lastblink, NULL);
3772 deltatime = TIMEDIFF(now, last);
3773 if(deltatime > (xev? (1000/xfps) : (1000/actionfps))
3780 while(XPending(xw.dpy)) {
3781 XNextEvent(xw.dpy, &ev);
3782 if(XFilterEvent(&ev, None))
3784 if(handler[ev.type])
3785 (handler[ev.type])(&ev);
3791 if(xev && !FD_ISSET(xfd, &rfd))
3793 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3795 if(TIMEDIFF(now, lastblink) \
3797 drawtimeout.tv_usec = 1;
3799 drawtimeout.tv_usec = (1000 * \
3814 die("%s " VERSION " (c) 2010-2013 st engineers\n" \
3815 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
3816 " [-t title] [-w windowid] [-e command ...]\n", argv0);
3820 main(int argc, char *argv[]) {
3825 xw.fw = xw.fh = xw.fx = xw.fy = 0;
3830 allowaltscreen = false;
3833 opt_class = EARGF(usage());
3836 /* eat all remaining arguments */
3839 if(argv[1] != NULL && opt_title == NULL) {
3840 titles = xstrdup(argv[1]);
3841 opt_title = basename(titles);
3846 opt_font = EARGF(usage());
3849 bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
3854 if(bitm & WidthValue)
3856 if(bitm & HeightValue)
3858 if(bitm & XNegative && xw.fx == 0)
3860 if(bitm & YNegative && xw.fy == 0)
3863 if(xw.fh != 0 && xw.fw != 0)
3867 opt_io = EARGF(usage());
3870 opt_title = EARGF(usage());
3873 opt_embed = EARGF(usage());
3881 setlocale(LC_CTYPE, "");
3882 XSetLocaleModifiers("");