1 /* See LICENSE for licence details. */
14 #include <sys/ioctl.h>
15 #include <sys/select.h>
18 #include <sys/types.h>
22 #include <X11/Xatom.h>
24 #include <X11/Xutil.h>
25 #include <X11/cursorfont.h>
26 #include <X11/keysym.h>
27 #include <X11/Xft/Xft.h>
28 #include <fontconfig/fontconfig.h>
36 #define Draw XftDraw *
37 #define Colour XftColor
38 #define Colourmap Colormap
39 #define Rectangle XRectangle
43 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
45 #elif defined(__FreeBSD__) || defined(__DragonFly__)
51 #define XEMBED_FOCUS_IN 4
52 #define XEMBED_FOCUS_OUT 5
56 #define ESC_BUF_SIZ (128*UTF_SIZ)
57 #define ESC_ARG_SIZ 16
58 #define STR_BUF_SIZ ESC_BUF_SIZ
59 #define STR_ARG_SIZ ESC_ARG_SIZ
60 #define DRAW_BUF_SIZ 20*1024
61 #define XK_ANY_MOD UINT_MAX
63 #define XK_SWITCH_MOD (1<<13)
65 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
68 #define SERRNO strerror(errno)
69 #define MIN(a, b) ((a) < (b) ? (a) : (b))
70 #define MAX(a, b) ((a) < (b) ? (b) : (a))
71 #define LEN(a) (sizeof(a) / sizeof(a[0]))
72 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
73 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
74 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
75 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
76 #define IS_SET(flag) ((term.mode & (flag)) != 0)
77 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
79 #define VT102ID "\033[?6c"
81 enum glyph_attribute {
92 enum cursor_movement {
110 MODE_MOUSEMOTION = 64,
116 MODE_APPCURSOR = 2048,
117 MODE_MOUSESGR = 4096,
126 ESC_STR = 4, /* DSC, OSC, PM, APC */
128 ESC_STR_END = 16, /* a final string was encountered */
129 ESC_TEST = 32, /* Enter in test mode */
138 enum selection_type {
143 enum selection_snap {
150 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
152 typedef unsigned char uchar;
153 typedef unsigned int uint;
154 typedef unsigned long ulong;
155 typedef unsigned short ushort;
158 char c[UTF_SIZ]; /* character code */
159 uchar mode; /* attribute flags */
160 ushort fg; /* foreground */
161 ushort bg; /* background */
167 Glyph attr; /* current char attributes */
173 /* CSI Escape sequence structs */
174 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
176 char buf[ESC_BUF_SIZ]; /* raw string */
177 int len; /* raw string length */
179 int arg[ESC_ARG_SIZ];
180 int narg; /* nb of args */
184 /* STR Escape sequence structs */
185 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
187 char type; /* ESC type ... */
188 char buf[STR_BUF_SIZ]; /* raw string */
189 int len; /* raw string length */
190 char *args[STR_ARG_SIZ];
191 int narg; /* nb of args */
194 /* Internal representation of the screen */
196 int row; /* nb row */
197 int col; /* nb col */
198 Line *line; /* screen */
199 Line *alt; /* alternate screen */
200 bool *dirty; /* dirtyness of lines */
201 TCursor c; /* cursor */
202 int top; /* top scroll limit */
203 int bot; /* bottom scroll limit */
204 int mode; /* terminal mode flags */
205 int esc; /* escape state flags */
206 bool numlock; /* lock numbers in keyboard */
210 /* Purely graphic info */
216 Atom xembed, wmdeletewin;
222 bool isfixed; /* is fixed geometry? */
223 int fx, fy, fw, fh; /* fixed geometry */
224 int tw, th; /* tty width and height */
225 int w, h; /* window width and height */
226 int ch; /* char height */
227 int cw; /* char width */
228 char state; /* focus, redraw, visible */
241 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
242 signed char appkey; /* application keypad */
243 signed char appcursor; /* application cursor */
244 signed char crlf; /* crlf mode */
247 /* TODO: use better name for vars... */
260 struct timeval tclick1;
261 struct timeval tclick2;
274 void (*func)(const Arg *);
278 /* function definitions used in config.h */
279 static void clippaste(const Arg *);
280 static void numlock(const Arg *);
281 static void selpaste(const Arg *);
282 static void xzoom(const Arg *);
284 /* Config.h for applying patches and the configuration. */
300 /* Drawing Context */
302 Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
303 Font font, bfont, ifont, ibfont;
307 static void die(const char *, ...);
308 static void draw(void);
309 static void redraw(int);
310 static void drawregion(int, int, int, int);
311 static void execsh(void);
312 static void sigchld(int);
313 static void run(void);
315 static void csidump(void);
316 static void csihandle(void);
317 static void csiparse(void);
318 static void csireset(void);
319 static void strdump(void);
320 static void strhandle(void);
321 static void strparse(void);
322 static void strreset(void);
324 static int tattrset(int);
325 static void tclearregion(int, int, int, int);
326 static void tcursor(int);
327 static void tdeletechar(int);
328 static void tdeleteline(int);
329 static void tinsertblank(int);
330 static void tinsertblankline(int);
331 static void tmoveto(int, int);
332 static void tmoveato(int x, int y);
333 static void tnew(int, int);
334 static void tnewline(int);
335 static void tputtab(bool);
336 static void tputc(char *, int);
337 static void treset(void);
338 static int tresize(int, int);
339 static void tscrollup(int, int);
340 static void tscrolldown(int, int);
341 static void tsetattr(int*, int);
342 static void tsetchar(char *, Glyph *, int, int);
343 static void tsetscroll(int, int);
344 static void tswapscreen(void);
345 static void tsetdirt(int, int);
346 static void tsetdirtattr(int);
347 static void tsetmode(bool, bool, int *, int);
348 static void tfulldirt(void);
349 static void techo(char *, int);
351 static inline bool match(uint, uint);
352 static void ttynew(void);
353 static void ttyread(void);
354 static void ttyresize(void);
355 static void ttywrite(const char *, size_t);
357 static void xdraws(char *, Glyph, int, int, int, int);
358 static void xhints(void);
359 static void xclear(int, int, int, int);
360 static void xdrawcursor(void);
361 static void xinit(void);
362 static void xloadcols(void);
363 static int xsetcolorname(int, const char *);
364 static int xloadfont(Font *, FcPattern *);
365 static void xloadfonts(char *, int);
366 static int xloadfontset(Font *);
367 static void xsettitle(char *);
368 static void xresettitle(void);
369 static void xseturgency(int);
370 static void xsetsel(char*);
371 static void xtermclear(int, int, int, int);
372 static void xunloadfonts(void);
373 static void xresize(int, int);
375 static void expose(XEvent *);
376 static void visibility(XEvent *);
377 static void unmap(XEvent *);
378 static char *kmap(KeySym, uint);
379 static void kpress(XEvent *);
380 static void cmessage(XEvent *);
381 static void cresize(int, int);
382 static void resize(XEvent *);
383 static void focus(XEvent *);
384 static void brelease(XEvent *);
385 static void bpress(XEvent *);
386 static void bmotion(XEvent *);
387 static void selnotify(XEvent *);
388 static void selclear(XEvent *);
389 static void selrequest(XEvent *);
391 static void selinit(void);
392 static inline bool selected(int, int);
393 static void selcopy(void);
394 static void selscroll(int, int);
395 static void selsnap(int, int *, int *, int);
397 static int utf8decode(char *, long *);
398 static int utf8encode(long *, char *);
399 static int utf8size(char *);
400 static int isfullutf8(char *, int);
402 static ssize_t xwrite(int, char *, size_t);
403 static void *xmalloc(size_t);
404 static void *xrealloc(void *, size_t);
405 static void *xcalloc(size_t, size_t);
407 static void (*handler[LASTEvent])(XEvent *) = {
409 [ClientMessage] = cmessage,
410 [ConfigureNotify] = resize,
411 [VisibilityNotify] = visibility,
412 [UnmapNotify] = unmap,
416 [MotionNotify] = bmotion,
417 [ButtonPress] = bpress,
418 [ButtonRelease] = brelease,
419 [SelectionClear] = selclear,
420 [SelectionNotify] = selnotify,
421 [SelectionRequest] = selrequest,
428 static CSIEscape csiescseq;
429 static STREscape strescseq;
432 static Selection sel;
433 static int iofd = -1;
434 static char **opt_cmd = NULL;
435 static char *opt_io = NULL;
436 static char *opt_title = NULL;
437 static char *opt_embed = NULL;
438 static char *opt_class = NULL;
439 static char *opt_font = NULL;
441 static char *usedfont = NULL;
442 static int usedfontsize = 0;
444 /* Font Ring Cache */
459 * Fontcache is a ring buffer, with frccur as current position and frclen as
460 * the current length of used elements.
463 static Fontcache frc[1024];
464 static int frccur = -1, frclen = 0;
467 xwrite(int fd, char *s, size_t len) {
471 ssize_t r = write(fd, s, len);
481 xmalloc(size_t len) {
482 void *p = malloc(len);
485 die("Out of memory\n");
491 xrealloc(void *p, size_t len) {
492 if((p = realloc(p, len)) == NULL)
493 die("Out of memory\n");
499 xcalloc(size_t nmemb, size_t size) {
500 void *p = calloc(nmemb, size);
503 die("Out of memory\n");
509 utf8decode(char *s, long *u) {
515 if(~c & B7) { /* 0xxxxxxx */
518 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
519 *u = c&(B4|B3|B2|B1|B0);
521 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
522 *u = c&(B3|B2|B1|B0);
524 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
531 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
533 if((c & (B7|B6)) != B7) /* 10xxxxxx */
536 *u |= c & (B5|B4|B3|B2|B1|B0);
539 if((n == 1 && *u < 0x80) ||
540 (n == 2 && *u < 0x800) ||
541 (n == 3 && *u < 0x10000) ||
542 (*u >= 0xD800 && *u <= 0xDFFF)) {
554 utf8encode(long *u, char *s) {
562 *sp = uc; /* 0xxxxxxx */
564 } else if(*u < 0x800) {
565 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
567 } else if(uc < 0x10000) {
568 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
570 } else if(uc <= 0x10FFFF) {
571 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
577 for(i=n,++sp; i>0; --i,++sp)
578 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
590 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
591 UTF-8 otherwise return 0 */
593 isfullutf8(char *s, int b) {
601 } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
603 } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
605 ((b == 2) && (*c2&(B7|B6)) == B7))) {
607 } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
609 ((b == 2) && (*c2&(B7|B6)) == B7) ||
610 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
623 } else if((c&(B7|B6|B5)) == (B7|B6)) {
625 } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
634 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
635 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
639 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
640 if(sel.xtarget == None)
641 sel.xtarget = XA_STRING;
649 return LIMIT(x, 0, term.col-1);
657 return LIMIT(y, 0, term.row-1);
661 selected(int x, int y) {
664 if(sel.ey == y && sel.by == y) {
665 bx = MIN(sel.bx, sel.ex);
666 ex = MAX(sel.bx, sel.ex);
668 return BETWEEN(x, bx, ex);
671 if(sel.type == SEL_RECTANGULAR) {
672 return ((sel.b.y <= y && y <= sel.e.y)
673 && (sel.b.x <= x && x <= sel.e.x));
675 return ((sel.b.y < y && y < sel.e.y)
676 || (y == sel.e.y && x <= sel.e.x))
677 || (y == sel.b.y && x >= sel.b.x
678 && (x <= sel.e.x || sel.b.y != sel.e.y));
682 selsnap(int mode, int *x, int *y, int direction) {
688 * Snap around if the word wraps around at the end or
689 * beginning of a line.
692 if(direction < 0 && *x <= 0) {
693 if(*y > 0 && term.line[*y - 1][term.col-1].mode
701 if(direction > 0 && *x >= term.col-1) {
702 if(*y < term.row-1 && term.line[*y][*x].mode
711 if(strchr(worddelimiters,
712 term.line[*y][*x + direction].c[0])) {
721 * Snap around if the the previous line or the current one
722 * has set ATTR_WRAP at its end. Then the whole next or
723 * previous line will be selected.
725 *x = (direction < 0) ? 0 : term.col - 1;
726 if(direction < 0 && *y > 0) {
727 for(; *y > 0; *y += direction) {
728 if(!(term.line[*y-1][term.col-1].mode
733 } else if(direction > 0 && *y < term.row-1) {
734 for(; *y < term.row; *y += direction) {
735 if(!(term.line[*y][term.col-1].mode
744 * Select the whole line when the end of line is reached.
748 while(--i > 0 && term.line[*y][i].c[0] == ' ')
758 getbuttoninfo(XEvent *e) {
760 uint state = e->xbutton.state &~Button1Mask;
762 sel.alt = IS_SET(MODE_ALTSCREEN);
764 sel.ex = x2col(e->xbutton.x);
765 sel.ey = y2row(e->xbutton.y);
768 || (sel.by == sel.ey && sel.bx < sel.ex)) {
769 selsnap(sel.snap, &sel.bx, &sel.by, -1);
770 selsnap(sel.snap, &sel.ex, &sel.ey, +1);
772 selsnap(sel.snap, &sel.ex, &sel.ey, -1);
773 selsnap(sel.snap, &sel.bx, &sel.by, +1);
776 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
777 sel.b.y = MIN(sel.by, sel.ey);
778 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
779 sel.e.y = MAX(sel.by, sel.ey);
781 sel.type = SEL_REGULAR;
782 for(type = 1; type < LEN(selmasks); ++type) {
783 if(match(selmasks[type], state)) {
791 mousereport(XEvent *e) {
792 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
793 button = e->xbutton.button, state = e->xbutton.state,
796 static int ob, ox, oy;
799 if(e->xbutton.type == MotionNotify) {
800 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
804 } else if(!IS_SET(MODE_MOUSESGR)
805 && (e->xbutton.type == ButtonRelease
806 || button == AnyButton)) {
812 if(e->xbutton.type == ButtonPress) {
818 button += (state & ShiftMask ? 4 : 0)
819 + (state & Mod4Mask ? 8 : 0)
820 + (state & ControlMask ? 16 : 0);
823 if(IS_SET(MODE_MOUSESGR)) {
824 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
826 e->xbutton.type == ButtonRelease ? 'm' : 'M');
827 } else if(x < 223 && y < 223) {
828 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
829 32+button, 32+x+1, 32+y+1);
842 if(IS_SET(MODE_MOUSE)) {
847 for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
848 if(e->xbutton.button == mk->b
849 && match(mk->mask, e->xbutton.state)) {
850 ttywrite(mk->s, strlen(mk->s));
851 if(IS_SET(MODE_ECHO))
852 techo(mk->s, strlen(mk->s));
857 if(e->xbutton.button == Button1) {
858 gettimeofday(&now, NULL);
860 /* Clear previous selection, logically and visually. */
863 tsetdirt(sel.b.y, sel.e.y);
867 sel.type = SEL_REGULAR;
868 sel.ex = sel.bx = x2col(e->xbutton.x);
869 sel.ey = sel.by = y2row(e->xbutton.y);
872 * If the user clicks below predefined timeouts specific
873 * snapping behaviour is exposed.
875 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
876 sel.snap = SNAP_LINE;
877 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
878 sel.snap = SNAP_WORD;
882 selsnap(sel.snap, &sel.bx, &sel.by, -1);
883 selsnap(sel.snap, &sel.ex, &sel.ey, +1);
890 * Draw selection, unless it's regular and we don't want to
891 * make clicks visible
895 tsetdirt(sel.b.y, sel.e.y);
898 sel.tclick2 = sel.tclick1;
906 int x, y, bufsize, size, i, ex;
912 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
913 ptr = str = xmalloc(bufsize);
915 /* append every set & selected glyph to the selection */
916 for(y = sel.b.y; y < sel.e.y + 1; y++) {
917 gp = &term.line[y][0];
918 last = gp + term.col;
920 while(--last >= gp && !(selected(last - gp, y) && \
921 strcmp(last->c, " ") != 0))
924 for(x = 0; gp <= last; x++, ++gp) {
928 size = utf8size(gp->c);
929 memcpy(ptr, gp->c, size);
934 * Copy and pasting of line endings is inconsistent
935 * in the inconsistent terminal and GUI world.
936 * The best solution seems like to produce '\n' when
937 * something is copied from st and convert '\n' to
938 * '\r', when something to be pasted is received by
940 * FIXME: Fix the computer world.
942 if(y < sel.e.y && !((gp-1)->mode & ATTR_WRAP))
946 * If the last selected line expands in the selection
947 * after the visible text '\n' is appended.
951 while(--i > 0 && term.line[y][i].c[0] == ' ')
954 if(sel.b.y == sel.e.y && sel.e.x < sel.b.x)
966 selnotify(XEvent *e) {
967 ulong nitems, ofs, rem;
969 uchar *data, *last, *repl;
974 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
975 False, AnyPropertyType, &type, &format,
976 &nitems, &rem, &data)) {
977 fprintf(stderr, "Clipboard allocation failed\n");
982 * As seen in selcopy:
983 * Line endings are inconsistent in the terminal and GUI world
984 * copy and pasting. When receiving some selection data,
985 * replace all '\n' with '\r'.
986 * FIXME: Fix the computer world.
989 last = data + nitems * format / 8;
990 while((repl = memchr(repl, '\n', last - repl))) {
994 ttywrite((const char *)data, nitems * format / 8);
996 /* number of 32-bit chunks returned */
997 ofs += nitems * format / 32;
1002 selpaste(const Arg *dummy) {
1003 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1004 xw.win, CurrentTime);
1008 clippaste(const Arg *dummy) {
1011 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1012 XConvertSelection(xw.dpy, clipboard, sel.xtarget, XA_PRIMARY,
1013 xw.win, CurrentTime);
1017 selclear(XEvent *e) {
1021 tsetdirt(sel.b.y, sel.e.y);
1025 selrequest(XEvent *e) {
1026 XSelectionRequestEvent *xsre;
1027 XSelectionEvent xev;
1028 Atom xa_targets, string;
1030 xsre = (XSelectionRequestEvent *) e;
1031 xev.type = SelectionNotify;
1032 xev.requestor = xsre->requestor;
1033 xev.selection = xsre->selection;
1034 xev.target = xsre->target;
1035 xev.time = xsre->time;
1037 xev.property = None;
1039 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1040 if(xsre->target == xa_targets) {
1041 /* respond with the supported type */
1042 string = sel.xtarget;
1043 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1044 XA_ATOM, 32, PropModeReplace,
1045 (uchar *) &string, 1);
1046 xev.property = xsre->property;
1047 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
1048 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1049 xsre->target, 8, PropModeReplace,
1050 (uchar *) sel.clip, strlen(sel.clip));
1051 xev.property = xsre->property;
1054 /* all done, send a notification to the listener */
1055 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
1056 fprintf(stderr, "Error sending SelectionNotify event\n");
1060 xsetsel(char *str) {
1061 /* register the selection for both the clipboard and the primary */
1067 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
1069 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1070 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1074 brelease(XEvent *e) {
1075 if(IS_SET(MODE_MOUSE)) {
1080 if(e->xbutton.button == Button2) {
1082 } else if(e->xbutton.button == Button1) {
1090 term.dirty[sel.ey] = 1;
1095 bmotion(XEvent *e) {
1096 int oldey, oldex, oldsby, oldsey;
1098 if(IS_SET(MODE_MOUSE)) {
1113 if(oldey != sel.ey || oldex != sel.ex) {
1114 tsetdirt(MIN(sel.b.y, oldsby), MAX(sel.e.y, oldsey));
1119 die(const char *errstr, ...) {
1122 va_start(ap, errstr);
1123 vfprintf(stderr, errstr, ap);
1131 char *envshell = getenv("SHELL");
1132 const struct passwd *pass = getpwuid(getuid());
1133 char buf[sizeof(long) * 8 + 1];
1135 unsetenv("COLUMNS");
1137 unsetenv("TERMCAP");
1140 setenv("LOGNAME", pass->pw_name, 1);
1141 setenv("USER", pass->pw_name, 1);
1142 setenv("SHELL", pass->pw_shell, 0);
1143 setenv("HOME", pass->pw_dir, 0);
1146 snprintf(buf, sizeof(buf), "%lu", xw.win);
1147 setenv("WINDOWID", buf, 1);
1149 signal(SIGCHLD, SIG_DFL);
1150 signal(SIGHUP, SIG_DFL);
1151 signal(SIGINT, SIG_DFL);
1152 signal(SIGQUIT, SIG_DFL);
1153 signal(SIGTERM, SIG_DFL);
1154 signal(SIGALRM, SIG_DFL);
1156 DEFAULT(envshell, shell);
1157 setenv("TERM", termname, 1);
1158 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
1159 execvp(args[0], args);
1167 if(waitpid(pid, &stat, 0) < 0)
1168 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
1170 if(WIFEXITED(stat)) {
1171 exit(WEXITSTATUS(stat));
1180 struct winsize w = {term.row, term.col, 0, 0};
1182 /* seems to work fine on linux, openbsd and freebsd */
1183 if(openpty(&m, &s, NULL, NULL, &w) < 0)
1184 die("openpty failed: %s\n", SERRNO);
1186 switch(pid = fork()) {
1188 die("fork failed\n");
1191 setsid(); /* create a new process group */
1192 dup2(s, STDIN_FILENO);
1193 dup2(s, STDOUT_FILENO);
1194 dup2(s, STDERR_FILENO);
1195 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1196 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
1204 signal(SIGCHLD, sigchld);
1206 iofd = (!strcmp(opt_io, "-")) ?
1208 open(opt_io, O_WRONLY | O_CREAT, 0666);
1210 fprintf(stderr, "Error opening %s:%s\n",
1211 opt_io, strerror(errno));
1221 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1223 fprintf(stderr, "\n");
1228 static char buf[BUFSIZ];
1229 static int buflen = 0;
1232 int charsize; /* size of utf8 char in bytes */
1236 /* append read bytes to unprocessed bytes */
1237 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1238 die("Couldn't read from shell: %s\n", SERRNO);
1240 /* process every complete utf8 char */
1243 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1244 charsize = utf8decode(ptr, &utf8c);
1245 utf8encode(&utf8c, s);
1251 /* keep any uncomplete utf8 char for the next call */
1252 memmove(buf, ptr, buflen);
1256 ttywrite(const char *s, size_t n) {
1257 if(write(cmdfd, s, n) == -1)
1258 die("write error on tty: %s\n", SERRNO);
1265 w.ws_row = term.row;
1266 w.ws_col = term.col;
1267 w.ws_xpixel = xw.tw;
1268 w.ws_ypixel = xw.th;
1269 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1270 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1274 tattrset(int attr) {
1277 for(i = 0; i < term.row-1; i++) {
1278 for(j = 0; j < term.col-1; j++) {
1279 if(term.line[i][j].mode & attr)
1288 tsetdirt(int top, int bot) {
1291 LIMIT(top, 0, term.row-1);
1292 LIMIT(bot, 0, term.row-1);
1294 for(i = top; i <= bot; i++)
1299 tsetdirtattr(int attr) {
1302 for(i = 0; i < term.row-1; i++) {
1303 for(j = 0; j < term.col-1; j++) {
1304 if(term.line[i][j].mode & attr) {
1314 tsetdirt(0, term.row-1);
1321 if(mode == CURSOR_SAVE) {
1323 } else if(mode == CURSOR_LOAD) {
1333 term.c = (TCursor){{
1337 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1339 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1340 for(i = tabspaces; i < term.col; i += tabspaces)
1343 term.bot = term.row - 1;
1344 term.mode = MODE_WRAP;
1346 tclearregion(0, 0, term.col-1, term.row-1);
1348 tcursor(CURSOR_SAVE);
1352 tnew(int col, int row) {
1353 memset(&term, 0, sizeof(Term));
1362 Line *tmp = term.line;
1364 term.line = term.alt;
1366 term.mode ^= MODE_ALTSCREEN;
1371 tscrolldown(int orig, int n) {
1375 LIMIT(n, 0, term.bot-orig+1);
1377 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1379 for(i = term.bot; i >= orig+n; i--) {
1380 temp = term.line[i];
1381 term.line[i] = term.line[i-n];
1382 term.line[i-n] = temp;
1385 term.dirty[i-n] = 1;
1392 tscrollup(int orig, int n) {
1395 LIMIT(n, 0, term.bot-orig+1);
1397 tclearregion(0, orig, term.col-1, orig+n-1);
1399 for(i = orig; i <= term.bot-n; i++) {
1400 temp = term.line[i];
1401 term.line[i] = term.line[i+n];
1402 term.line[i+n] = temp;
1405 term.dirty[i+n] = 1;
1408 selscroll(orig, -n);
1412 selscroll(int orig, int n) {
1416 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1417 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1421 if(sel.type == SEL_RECTANGULAR) {
1422 if(sel.by < term.top)
1424 if(sel.ey > term.bot)
1427 if(sel.by < term.top) {
1431 if(sel.ey > term.bot) {
1436 sel.b.y = sel.by, sel.b.x = sel.bx;
1437 sel.e.y = sel.ey, sel.e.x = sel.ex;
1442 tnewline(int first_col) {
1446 tscrollup(term.top, 1);
1450 tmoveto(first_col ? 0 : term.c.x, y);
1455 char *p = csiescseq.buf, *np;
1464 csiescseq.buf[csiescseq.len] = '\0';
1465 while(p < csiescseq.buf+csiescseq.len) {
1467 v = strtol(p, &np, 10);
1470 if(v == LONG_MAX || v == LONG_MIN)
1472 csiescseq.arg[csiescseq.narg++] = v;
1474 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1478 csiescseq.mode = *p;
1481 /* for absolute user moves, when decom is set */
1483 tmoveato(int x, int y) {
1484 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1488 tmoveto(int x, int y) {
1491 if(term.c.state & CURSOR_ORIGIN) {
1496 maxy = term.row - 1;
1498 LIMIT(x, 0, term.col-1);
1499 LIMIT(y, miny, maxy);
1500 term.c.state &= ~CURSOR_WRAPNEXT;
1506 tsetchar(char *c, Glyph *attr, int x, int y) {
1507 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1508 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1509 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1510 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1511 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1512 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1513 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1514 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1515 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1519 * The table is proudly stolen from rxvt.
1521 if(attr->mode & ATTR_GFX) {
1522 if(c[0] >= 0x41 && c[0] <= 0x7e
1523 && vt100_0[c[0] - 0x41]) {
1524 c = vt100_0[c[0] - 0x41];
1529 term.line[y][x] = *attr;
1530 memcpy(term.line[y][x].c, c, UTF_SIZ);
1534 tclearregion(int x1, int y1, int x2, int y2) {
1538 temp = x1, x1 = x2, x2 = temp;
1540 temp = y1, y1 = y2, y2 = temp;
1542 LIMIT(x1, 0, term.col-1);
1543 LIMIT(x2, 0, term.col-1);
1544 LIMIT(y1, 0, term.row-1);
1545 LIMIT(y2, 0, term.row-1);
1547 for(y = y1; y <= y2; y++) {
1549 for(x = x1; x <= x2; x++) {
1552 term.line[y][x] = term.c.attr;
1553 memcpy(term.line[y][x].c, " ", 2);
1559 tdeletechar(int n) {
1560 int src = term.c.x + n;
1562 int size = term.col - src;
1564 term.dirty[term.c.y] = 1;
1566 if(src >= term.col) {
1567 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1571 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1572 size * sizeof(Glyph));
1573 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1577 tinsertblank(int n) {
1580 int size = term.col - dst;
1582 term.dirty[term.c.y] = 1;
1584 if(dst >= term.col) {
1585 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1589 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1590 size * sizeof(Glyph));
1591 tclearregion(src, term.c.y, dst - 1, term.c.y);
1595 tinsertblankline(int n) {
1596 if(term.c.y < term.top || term.c.y > term.bot)
1599 tscrolldown(term.c.y, n);
1603 tdeleteline(int n) {
1604 if(term.c.y < term.top || term.c.y > term.bot)
1607 tscrollup(term.c.y, n);
1611 tsetattr(int *attr, int l) {
1614 for(i = 0; i < l; i++) {
1617 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE \
1618 | ATTR_BOLD | ATTR_ITALIC \
1620 term.c.attr.fg = defaultfg;
1621 term.c.attr.bg = defaultbg;
1624 term.c.attr.mode |= ATTR_BOLD;
1627 term.c.attr.mode |= ATTR_ITALIC;
1630 term.c.attr.mode |= ATTR_UNDERLINE;
1632 case 5: /* slow blink */
1633 case 6: /* rapid blink */
1634 term.c.attr.mode |= ATTR_BLINK;
1637 term.c.attr.mode |= ATTR_REVERSE;
1641 term.c.attr.mode &= ~ATTR_BOLD;
1644 term.c.attr.mode &= ~ATTR_ITALIC;
1647 term.c.attr.mode &= ~ATTR_UNDERLINE;
1651 term.c.attr.mode &= ~ATTR_BLINK;
1654 term.c.attr.mode &= ~ATTR_REVERSE;
1657 if(i + 2 < l && attr[i + 1] == 5) {
1659 if(BETWEEN(attr[i], 0, 255)) {
1660 term.c.attr.fg = attr[i];
1663 "erresc: bad fgcolor %d\n",
1668 "erresc(38): gfx attr %d unknown\n",
1673 term.c.attr.fg = defaultfg;
1676 if(i + 2 < l && attr[i + 1] == 5) {
1678 if(BETWEEN(attr[i], 0, 255)) {
1679 term.c.attr.bg = attr[i];
1682 "erresc: bad bgcolor %d\n",
1687 "erresc(48): gfx attr %d unknown\n",
1692 term.c.attr.bg = defaultbg;
1695 if(BETWEEN(attr[i], 30, 37)) {
1696 term.c.attr.fg = attr[i] - 30;
1697 } else if(BETWEEN(attr[i], 40, 47)) {
1698 term.c.attr.bg = attr[i] - 40;
1699 } else if(BETWEEN(attr[i], 90, 97)) {
1700 term.c.attr.fg = attr[i] - 90 + 8;
1701 } else if(BETWEEN(attr[i], 100, 107)) {
1702 term.c.attr.bg = attr[i] - 100 + 8;
1705 "erresc(default): gfx attr %d unknown\n",
1706 attr[i]), csidump();
1714 tsetscroll(int t, int b) {
1717 LIMIT(t, 0, term.row-1);
1718 LIMIT(b, 0, term.row-1);
1728 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1731 tsetmode(bool priv, bool set, int *args, int narg) {
1735 for(lim = args + narg; args < lim; ++args) {
1739 case 1: /* DECCKM -- Cursor key */
1740 MODBIT(term.mode, set, MODE_APPCURSOR);
1742 case 5: /* DECSCNM -- Reverse video */
1744 MODBIT(term.mode, set, MODE_REVERSE);
1745 if(mode != term.mode)
1746 redraw(REDRAW_TIMEOUT);
1748 case 6: /* DECOM -- Origin */
1749 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1752 case 7: /* DECAWM -- Auto wrap */
1753 MODBIT(term.mode, set, MODE_WRAP);
1755 case 0: /* Error (IGNORED) */
1756 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1757 case 3: /* DECCOLM -- Column (IGNORED) */
1758 case 4: /* DECSCLM -- Scroll (IGNORED) */
1759 case 8: /* DECARM -- Auto repeat (IGNORED) */
1760 case 18: /* DECPFF -- Printer feed (IGNORED) */
1761 case 19: /* DECPEX -- Printer extent (IGNORED) */
1762 case 42: /* DECNRCM -- National characters (IGNORED) */
1763 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1765 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1766 MODBIT(term.mode, !set, MODE_HIDE);
1768 case 1000: /* 1000,1002: enable xterm mouse report */
1769 MODBIT(term.mode, set, MODE_MOUSEBTN);
1770 MODBIT(term.mode, 0, MODE_MOUSEMOTION);
1773 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1774 MODBIT(term.mode, 0, MODE_MOUSEBTN);
1777 MODBIT(term.mode, set, MODE_MOUSESGR);
1780 MODBIT(term.mode, set, MODE_8BIT);
1782 case 1049: /* = 1047 and 1048 */
1785 if (!allowaltscreen)
1788 alt = IS_SET(MODE_ALTSCREEN);
1790 tclearregion(0, 0, term.col-1,
1793 if(set ^ alt) /* set is always 1 or 0 */
1799 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1803 "erresc: unknown private set/reset mode %d\n",
1809 case 0: /* Error (IGNORED) */
1811 case 2: /* KAM -- keyboard action */
1812 MODBIT(term.mode, set, MODE_KBDLOCK);
1814 case 4: /* IRM -- Insertion-replacement */
1815 MODBIT(term.mode, set, MODE_INSERT);
1817 case 12: /* SRM -- Send/Receive */
1818 MODBIT(term.mode, !set, MODE_ECHO);
1820 case 20: /* LNM -- Linefeed/new line */
1821 MODBIT(term.mode, set, MODE_CRLF);
1825 "erresc: unknown set/reset mode %d\n",
1837 switch(csiescseq.mode) {
1840 fprintf(stderr, "erresc: unknown csi ");
1844 case '@': /* ICH -- Insert <n> blank char */
1845 DEFAULT(csiescseq.arg[0], 1);
1846 tinsertblank(csiescseq.arg[0]);
1848 case 'A': /* CUU -- Cursor <n> Up */
1849 DEFAULT(csiescseq.arg[0], 1);
1850 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1852 case 'B': /* CUD -- Cursor <n> Down */
1853 case 'e': /* VPR --Cursor <n> Down */
1854 DEFAULT(csiescseq.arg[0], 1);
1855 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1857 case 'c': /* DA -- Device Attributes */
1858 if(csiescseq.arg[0] == 0)
1859 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1861 case 'C': /* CUF -- Cursor <n> Forward */
1862 case 'a': /* HPR -- Cursor <n> Forward */
1863 DEFAULT(csiescseq.arg[0], 1);
1864 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1866 case 'D': /* CUB -- Cursor <n> Backward */
1867 DEFAULT(csiescseq.arg[0], 1);
1868 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1870 case 'E': /* CNL -- Cursor <n> Down and first col */
1871 DEFAULT(csiescseq.arg[0], 1);
1872 tmoveto(0, term.c.y+csiescseq.arg[0]);
1874 case 'F': /* CPL -- Cursor <n> Up and first col */
1875 DEFAULT(csiescseq.arg[0], 1);
1876 tmoveto(0, term.c.y-csiescseq.arg[0]);
1878 case 'g': /* TBC -- Tabulation clear */
1879 switch(csiescseq.arg[0]) {
1880 case 0: /* clear current tab stop */
1881 term.tabs[term.c.x] = 0;
1883 case 3: /* clear all the tabs */
1884 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1890 case 'G': /* CHA -- Move to <col> */
1892 DEFAULT(csiescseq.arg[0], 1);
1893 tmoveto(csiescseq.arg[0]-1, term.c.y);
1895 case 'H': /* CUP -- Move to <row> <col> */
1897 DEFAULT(csiescseq.arg[0], 1);
1898 DEFAULT(csiescseq.arg[1], 1);
1899 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1901 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1902 DEFAULT(csiescseq.arg[0], 1);
1903 while(csiescseq.arg[0]--)
1906 case 'J': /* ED -- Clear screen */
1908 switch(csiescseq.arg[0]) {
1910 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1911 if(term.c.y < term.row-1) {
1912 tclearregion(0, term.c.y+1, term.col-1,
1918 tclearregion(0, 0, term.col-1, term.c.y-1);
1919 tclearregion(0, term.c.y, term.c.x, term.c.y);
1922 tclearregion(0, 0, term.col-1, term.row-1);
1928 case 'K': /* EL -- Clear line */
1929 switch(csiescseq.arg[0]) {
1931 tclearregion(term.c.x, term.c.y, term.col-1,
1935 tclearregion(0, term.c.y, term.c.x, term.c.y);
1938 tclearregion(0, term.c.y, term.col-1, term.c.y);
1942 case 'S': /* SU -- Scroll <n> line up */
1943 DEFAULT(csiescseq.arg[0], 1);
1944 tscrollup(term.top, csiescseq.arg[0]);
1946 case 'T': /* SD -- Scroll <n> line down */
1947 DEFAULT(csiescseq.arg[0], 1);
1948 tscrolldown(term.top, csiescseq.arg[0]);
1950 case 'L': /* IL -- Insert <n> blank lines */
1951 DEFAULT(csiescseq.arg[0], 1);
1952 tinsertblankline(csiescseq.arg[0]);
1954 case 'l': /* RM -- Reset Mode */
1955 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1957 case 'M': /* DL -- Delete <n> lines */
1958 DEFAULT(csiescseq.arg[0], 1);
1959 tdeleteline(csiescseq.arg[0]);
1961 case 'X': /* ECH -- Erase <n> char */
1962 DEFAULT(csiescseq.arg[0], 1);
1963 tclearregion(term.c.x, term.c.y,
1964 term.c.x + csiescseq.arg[0] - 1, term.c.y);
1966 case 'P': /* DCH -- Delete <n> char */
1967 DEFAULT(csiescseq.arg[0], 1);
1968 tdeletechar(csiescseq.arg[0]);
1970 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1971 DEFAULT(csiescseq.arg[0], 1);
1972 while(csiescseq.arg[0]--)
1975 case 'd': /* VPA -- Move to <row> */
1976 DEFAULT(csiescseq.arg[0], 1);
1977 tmoveato(term.c.x, csiescseq.arg[0]-1);
1979 case 'h': /* SM -- Set terminal mode */
1980 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1982 case 'm': /* SGR -- Terminal attribute (color) */
1983 tsetattr(csiescseq.arg, csiescseq.narg);
1985 case 'r': /* DECSTBM -- Set Scrolling Region */
1986 if(csiescseq.priv) {
1989 DEFAULT(csiescseq.arg[0], 1);
1990 DEFAULT(csiescseq.arg[1], term.row);
1991 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1995 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1996 tcursor(CURSOR_SAVE);
1998 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1999 tcursor(CURSOR_LOAD);
2010 for(i = 0; i < csiescseq.len; i++) {
2011 c = csiescseq.buf[i] & 0xff;
2014 } else if(c == '\n') {
2016 } else if(c == '\r') {
2018 } else if(c == 0x1b) {
2021 printf("(%02x)", c);
2029 memset(&csiescseq, 0, sizeof(csiescseq));
2038 narg = strescseq.narg;
2040 switch(strescseq.type) {
2041 case ']': /* OSC -- Operating System Command */
2042 switch(i = atoi(strescseq.args[0])) {
2047 xsettitle(strescseq.args[1]);
2049 case 4: /* color set */
2052 p = strescseq.args[2];
2054 case 104: /* color reset, here p = NULL */
2055 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2056 if (!xsetcolorname(j, p)) {
2057 fprintf(stderr, "erresc: invalid color %s\n", p);
2060 * TODO if defaultbg color is changed, borders
2067 fprintf(stderr, "erresc: unknown str ");
2072 case 'k': /* old title set compatibility */
2073 xsettitle(strescseq.args[0]);
2075 case 'P': /* DSC -- Device Control String */
2076 case '_': /* APC -- Application Program Command */
2077 case '^': /* PM -- Privacy Message */
2079 fprintf(stderr, "erresc: unknown str ");
2088 char *p = strescseq.buf;
2091 strescseq.buf[strescseq.len] = '\0';
2092 while(p && strescseq.narg < STR_ARG_SIZ)
2093 strescseq.args[strescseq.narg++] = strsep(&p, ";");
2101 printf("ESC%c", strescseq.type);
2102 for(i = 0; i < strescseq.len; i++) {
2103 c = strescseq.buf[i] & 0xff;
2106 } else if(isprint(c)) {
2108 } else if(c == '\n') {
2110 } else if(c == '\r') {
2112 } else if(c == 0x1b) {
2115 printf("(%02x)", c);
2123 memset(&strescseq, 0, sizeof(strescseq));
2127 tputtab(bool forward) {
2133 for(++x; x < term.col && !term.tabs[x]; ++x)
2138 for(--x; x > 0 && !term.tabs[x]; --x)
2141 tmoveto(x, term.c.y);
2145 techo(char *buf, int len) {
2146 for(; len > 0; buf++, len--) {
2149 if(c == '\033') { /* escape */
2152 } else if(c < '\x20') { /* control code */
2153 if(c != '\n' && c != '\r' && c != '\t') {
2167 tputc(char *c, int len) {
2169 bool control = ascii < '\x20' || ascii == 0177;
2172 if(xwrite(iofd, c, len) < 0) {
2173 fprintf(stderr, "Error writing in %s:%s\n",
2174 opt_io, strerror(errno));
2181 * STR sequences must be checked before anything else
2182 * because it can use some control codes as part of the sequence.
2184 if(term.esc & ESC_STR) {
2187 term.esc = ESC_START | ESC_STR_END;
2189 case '\a': /* backwards compatibility to xterm */
2194 if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2195 memmove(&strescseq.buf[strescseq.len], c, len);
2196 strescseq.len += len;
2199 * Here is a bug in terminals. If the user never sends
2200 * some code to stop the str or esc command, then st
2201 * will stop responding. But this is better than
2202 * silently failing with unknown characters. At least
2203 * then users will report back.
2205 * In the case users ever get fixed, here is the code:
2217 * Actions of control codes must be performed as soon they arrive
2218 * because they can be embedded inside a control sequence, and
2219 * they must not cause conflicts with sequences.
2227 tmoveto(term.c.x-1, term.c.y);
2230 tmoveto(0, term.c.y);
2235 /* go to first col if the mode is set */
2236 tnewline(IS_SET(MODE_CRLF));
2238 case '\a': /* BEL */
2239 if(!(xw.state & WIN_FOCUSED))
2242 case '\033': /* ESC */
2244 term.esc = ESC_START;
2246 case '\016': /* SO */
2247 case '\017': /* SI */
2249 * Different charsets are hard to handle. Applications
2250 * should use the right alt charset escapes for the
2251 * only reason they still exist: line drawing. The
2252 * rest is incompatible history st should not support.
2255 case '\032': /* SUB */
2256 case '\030': /* CAN */
2259 case '\005': /* ENQ (IGNORED) */
2260 case '\000': /* NUL (IGNORED) */
2261 case '\021': /* XON (IGNORED) */
2262 case '\023': /* XOFF (IGNORED) */
2263 case 0177: /* DEL (IGNORED) */
2266 } else if(term.esc & ESC_START) {
2267 if(term.esc & ESC_CSI) {
2268 csiescseq.buf[csiescseq.len++] = ascii;
2269 if(BETWEEN(ascii, 0x40, 0x7E)
2270 || csiescseq.len >= \
2271 sizeof(csiescseq.buf)-1) {
2276 } else if(term.esc & ESC_STR_END) {
2280 } else if(term.esc & ESC_ALTCHARSET) {
2282 case '0': /* Line drawing set */
2283 term.c.attr.mode |= ATTR_GFX;
2285 case 'B': /* USASCII */
2286 term.c.attr.mode &= ~ATTR_GFX;
2288 case 'A': /* UK (IGNORED) */
2289 case '<': /* multinational charset (IGNORED) */
2290 case '5': /* Finnish (IGNORED) */
2291 case 'C': /* Finnish (IGNORED) */
2292 case 'K': /* German (IGNORED) */
2295 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2298 } else if(term.esc & ESC_TEST) {
2299 if(ascii == '8') { /* DEC screen alignment test. */
2300 char E[UTF_SIZ] = "E";
2303 for(x = 0; x < term.col; ++x) {
2304 for(y = 0; y < term.row; ++y)
2305 tsetchar(E, &term.c.attr, x, y);
2312 term.esc |= ESC_CSI;
2315 term.esc |= ESC_TEST;
2317 case 'P': /* DCS -- Device Control String */
2318 case '_': /* APC -- Application Program Command */
2319 case '^': /* PM -- Privacy Message */
2320 case ']': /* OSC -- Operating System Command */
2321 case 'k': /* old title set compatibility */
2323 strescseq.type = ascii;
2324 term.esc |= ESC_STR;
2326 case '(': /* set primary charset G0 */
2327 term.esc |= ESC_ALTCHARSET;
2329 case ')': /* set secondary charset G1 (IGNORED) */
2330 case '*': /* set tertiary charset G2 (IGNORED) */
2331 case '+': /* set quaternary charset G3 (IGNORED) */
2334 case 'D': /* IND -- Linefeed */
2335 if(term.c.y == term.bot) {
2336 tscrollup(term.top, 1);
2338 tmoveto(term.c.x, term.c.y+1);
2342 case 'E': /* NEL -- Next line */
2343 tnewline(1); /* always go to first col */
2346 case 'H': /* HTS -- Horizontal tab stop */
2347 term.tabs[term.c.x] = 1;
2350 case 'M': /* RI -- Reverse index */
2351 if(term.c.y == term.top) {
2352 tscrolldown(term.top, 1);
2354 tmoveto(term.c.x, term.c.y-1);
2358 case 'Z': /* DECID -- Identify Terminal */
2359 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2362 case 'c': /* RIS -- Reset to inital state */
2367 case '=': /* DECPAM -- Application keypad */
2368 term.mode |= MODE_APPKEYPAD;
2371 case '>': /* DECPNM -- Normal keypad */
2372 term.mode &= ~MODE_APPKEYPAD;
2375 case '7': /* DECSC -- Save Cursor */
2376 tcursor(CURSOR_SAVE);
2379 case '8': /* DECRC -- Restore Cursor */
2380 tcursor(CURSOR_LOAD);
2383 case '\\': /* ST -- Stop */
2387 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2388 (uchar) ascii, isprint(ascii)? ascii:'.');
2393 * All characters which form part of a sequence are not
2399 * Display control codes only if we are in graphic mode
2401 if(control && !(term.c.attr.mode & ATTR_GFX))
2403 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2405 if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2406 term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
2410 if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2411 memmove(&term.line[term.c.y][term.c.x+1],
2412 &term.line[term.c.y][term.c.x],
2413 (term.col - term.c.x - 1) * sizeof(Glyph));
2416 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2417 if(term.c.x+1 < term.col) {
2418 tmoveto(term.c.x+1, term.c.y);
2420 term.c.state |= CURSOR_WRAPNEXT;
2425 tresize(int col, int row) {
2427 int minrow = MIN(row, term.row);
2428 int mincol = MIN(col, term.col);
2429 int slide = term.c.y - row + 1;
2433 if(col < 1 || row < 1)
2436 /* free unneeded rows */
2440 * slide screen to keep cursor where we expect it -
2441 * tscrollup would work here, but we can optimize to
2442 * memmove because we're freeing the earlier lines
2444 for(/* i = 0 */; i < slide; i++) {
2448 memmove(term.line, term.line + slide, row * sizeof(Line));
2449 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2451 for(i += row; i < term.row; i++) {
2456 /* resize to new height */
2457 term.line = xrealloc(term.line, row * sizeof(Line));
2458 term.alt = xrealloc(term.alt, row * sizeof(Line));
2459 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2460 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2462 /* resize each row to new width, zero-pad if needed */
2463 for(i = 0; i < minrow; i++) {
2465 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2466 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2469 /* allocate any new rows */
2470 for(/* i == minrow */; i < row; i++) {
2472 term.line[i] = xcalloc(col, sizeof(Glyph));
2473 term.alt [i] = xcalloc(col, sizeof(Glyph));
2475 if(col > term.col) {
2476 bp = term.tabs + term.col;
2478 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2479 while(--bp > term.tabs && !*bp)
2481 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2484 /* update terminal size */
2487 /* reset scrolling region */
2488 tsetscroll(0, row-1);
2489 /* make use of the LIMIT in tmoveto */
2490 tmoveto(term.c.x, term.c.y);
2491 /* Clearing both screens */
2494 if(mincol < col && 0 < minrow) {
2495 tclearregion(mincol, 0, col - 1, minrow - 1);
2497 if(0 < col && minrow < row) {
2498 tclearregion(0, minrow, col - 1, row - 1);
2501 } while(orig != term.line);
2507 xresize(int col, int row) {
2508 xw.tw = MAX(1, col * xw.cw);
2509 xw.th = MAX(1, row * xw.ch);
2511 XFreePixmap(xw.dpy, xw.buf);
2512 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2513 DefaultDepth(xw.dpy, xw.scr));
2514 XftDrawChange(xw.draw, xw.buf);
2515 xclear(0, 0, xw.w, xw.h);
2518 static inline ushort
2519 sixd_to_16bit(int x) {
2520 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2526 XRenderColor color = { .alpha = 0xffff };
2528 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2529 for(i = 0; i < LEN(colorname); i++) {
2532 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2533 die("Could not allocate color '%s'\n", colorname[i]);
2537 /* load colors [16-255] ; same colors as xterm */
2538 for(i = 16, r = 0; r < 6; r++) {
2539 for(g = 0; g < 6; g++) {
2540 for(b = 0; b < 6; b++) {
2541 color.red = sixd_to_16bit(r);
2542 color.green = sixd_to_16bit(g);
2543 color.blue = sixd_to_16bit(b);
2544 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2545 die("Could not allocate color %d\n", i);
2552 for(r = 0; r < 24; r++, i++) {
2553 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2554 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2556 die("Could not allocate color %d\n", i);
2562 xsetcolorname(int x, const char *name) {
2563 XRenderColor color = { .alpha = 0xffff };
2565 if (x < 0 || x > LEN(colorname))
2568 if(16 <= x && x < 16 + 216) {
2569 int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2570 color.red = sixd_to_16bit(r);
2571 color.green = sixd_to_16bit(g);
2572 color.blue = sixd_to_16bit(b);
2573 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2574 return 0; /* something went wrong */
2577 } else if (16 + 216 <= x && x < 256) {
2578 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2579 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2580 return 0; /* something went wrong */
2584 name = colorname[x];
2587 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2594 xtermclear(int col1, int row1, int col2, int row2) {
2595 XftDrawRect(xw.draw,
2596 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2597 borderpx + col1 * xw.cw,
2598 borderpx + row1 * xw.ch,
2599 (col2-col1+1) * xw.cw,
2600 (row2-row1+1) * xw.ch);
2604 * Absolute coordinates.
2607 xclear(int x1, int y1, int x2, int y2) {
2608 XftDrawRect(xw.draw,
2609 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2610 x1, y1, x2-x1, y2-y1);
2615 XClassHint class = {opt_class ? opt_class : termname, termname};
2616 XWMHints wm = {.flags = InputHint, .input = 1};
2617 XSizeHints *sizeh = NULL;
2619 sizeh = XAllocSizeHints();
2620 if(xw.isfixed == False) {
2621 sizeh->flags = PSize | PResizeInc | PBaseSize;
2622 sizeh->height = xw.h;
2623 sizeh->width = xw.w;
2624 sizeh->height_inc = xw.ch;
2625 sizeh->width_inc = xw.cw;
2626 sizeh->base_height = 2 * borderpx;
2627 sizeh->base_width = 2 * borderpx;
2629 sizeh->flags = PMaxSize | PMinSize;
2630 sizeh->min_width = sizeh->max_width = xw.fw;
2631 sizeh->min_height = sizeh->max_height = xw.fh;
2634 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2639 xloadfont(Font *f, FcPattern *pattern) {
2643 match = FcFontMatch(NULL, pattern, &result);
2647 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2648 FcPatternDestroy(match);
2653 f->pattern = FcPatternDuplicate(pattern);
2655 f->ascent = f->match->ascent;
2656 f->descent = f->match->descent;
2658 f->rbearing = f->match->max_advance_width;
2660 f->height = f->ascent + f->descent;
2661 f->width = f->lbearing + f->rbearing;
2667 xloadfonts(char *fontstr, int fontsize) {
2672 if(fontstr[0] == '-') {
2673 pattern = XftXlfdParse(fontstr, False, False);
2675 pattern = FcNameParse((FcChar8 *)fontstr);
2679 die("st: can't open font %s\n", fontstr);
2682 FcPatternDel(pattern, FC_PIXEL_SIZE);
2683 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2684 usedfontsize = fontsize;
2686 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2687 if(result == FcResultMatch) {
2688 usedfontsize = (int)fontval;
2691 * Default font size is 12, if none given. This is to
2692 * have a known usedfontsize value.
2694 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2699 FcConfigSubstitute(0, pattern, FcMatchPattern);
2700 FcDefaultSubstitute(pattern);
2702 if(xloadfont(&dc.font, pattern))
2703 die("st: can't open font %s\n", fontstr);
2705 /* Setting character width and height. */
2706 xw.cw = dc.font.width;
2707 xw.ch = dc.font.height;
2709 FcPatternDel(pattern, FC_SLANT);
2710 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2711 if(xloadfont(&dc.ifont, pattern))
2712 die("st: can't open font %s\n", fontstr);
2714 FcPatternDel(pattern, FC_WEIGHT);
2715 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2716 if(xloadfont(&dc.ibfont, pattern))
2717 die("st: can't open font %s\n", fontstr);
2719 FcPatternDel(pattern, FC_SLANT);
2720 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2721 if(xloadfont(&dc.bfont, pattern))
2722 die("st: can't open font %s\n", fontstr);
2724 FcPatternDestroy(pattern);
2728 xloadfontset(Font *f) {
2731 if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
2737 xunloadfonts(void) {
2741 * Free the loaded fonts in the font cache. This is done backwards
2744 for(i = 0, ip = frccur; i < frclen; i++, ip--) {
2747 XftFontClose(xw.dpy, frc[ip].font);
2752 XftFontClose(xw.dpy, dc.font.match);
2753 FcPatternDestroy(dc.font.pattern);
2754 FcFontSetDestroy(dc.font.set);
2755 XftFontClose(xw.dpy, dc.bfont.match);
2756 FcPatternDestroy(dc.bfont.pattern);
2757 FcFontSetDestroy(dc.bfont.set);
2758 XftFontClose(xw.dpy, dc.ifont.match);
2759 FcPatternDestroy(dc.ifont.pattern);
2760 FcFontSetDestroy(dc.ifont.set);
2761 XftFontClose(xw.dpy, dc.ibfont.match);
2762 FcPatternDestroy(dc.ibfont.pattern);
2763 FcFontSetDestroy(dc.ibfont.set);
2767 xzoom(const Arg *arg) {
2769 xloadfonts(usedfont, usedfontsize + arg->i);
2776 XSetWindowAttributes attrs;
2782 if(!(xw.dpy = XOpenDisplay(NULL)))
2783 die("Can't open display\n");
2784 xw.scr = XDefaultScreen(xw.dpy);
2785 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2789 die("Could not init fontconfig.\n");
2791 usedfont = (opt_font == NULL)? font : opt_font;
2792 xloadfonts(usedfont, 0);
2795 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2798 /* adjust fixed window geometry */
2800 sw = DisplayWidth(xw.dpy, xw.scr);
2801 sh = DisplayHeight(xw.dpy, xw.scr);
2803 xw.fx = sw + xw.fx - xw.fw - 1;
2805 xw.fy = sh + xw.fy - xw.fh - 1;
2810 /* window - default size */
2811 xw.h = 2 * borderpx + term.row * xw.ch;
2812 xw.w = 2 * borderpx + term.col * xw.cw;
2818 attrs.background_pixel = dc.col[defaultbg].pixel;
2819 attrs.border_pixel = dc.col[defaultbg].pixel;
2820 attrs.bit_gravity = NorthWestGravity;
2821 attrs.event_mask = FocusChangeMask | KeyPressMask
2822 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2823 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2824 attrs.colormap = xw.cmap;
2826 parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2827 XRootWindow(xw.dpy, xw.scr);
2828 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2829 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2831 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2835 memset(&gcvalues, 0, sizeof(gcvalues));
2836 gcvalues.graphics_exposures = False;
2837 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2839 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2840 DefaultDepth(xw.dpy, xw.scr));
2841 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
2842 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2844 /* Xft rendering context */
2845 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2848 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2849 XSetLocaleModifiers("@im=local");
2850 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2851 XSetLocaleModifiers("@im=");
2852 if((xw.xim = XOpenIM(xw.dpy,
2853 NULL, NULL, NULL)) == NULL) {
2854 die("XOpenIM failed. Could not open input"
2859 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2860 | XIMStatusNothing, XNClientWindow, xw.win,
2861 XNFocusWindow, xw.win, NULL);
2863 die("XCreateIC failed. Could not obtain input method.\n");
2865 /* white cursor, black outline */
2866 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2867 XDefineCursor(xw.dpy, xw.win, cursor);
2868 XRecolorCursor(xw.dpy, cursor,
2869 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2870 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2872 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2873 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2874 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2877 XMapWindow(xw.dpy, xw.win);
2883 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2884 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2885 width = charlen * xw.cw, xp, i;
2887 int u8fl, u8fblen, u8cblen, doesexist;
2890 Font *font = &dc.font;
2892 FcPattern *fcpattern, *fontpattern;
2893 FcFontSet *fcsets[] = { NULL };
2894 FcCharSet *fccharset;
2895 Colour *fg, *bg, *temp, revfg, revbg;
2896 XRenderColor colfg, colbg;
2899 frcflags = FRC_NORMAL;
2901 if(base.mode & ATTR_ITALIC) {
2902 if(base.fg == defaultfg)
2903 base.fg = defaultitalic;
2905 frcflags = FRC_ITALIC;
2906 } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
2907 if(base.fg == defaultfg)
2908 base.fg = defaultitalic;
2910 frcflags = FRC_ITALICBOLD;
2911 } else if(base.mode & ATTR_UNDERLINE) {
2912 if(base.fg == defaultfg)
2913 base.fg = defaultunderline;
2915 fg = &dc.col[base.fg];
2916 bg = &dc.col[base.bg];
2918 if(base.mode & ATTR_BOLD) {
2919 if(BETWEEN(base.fg, 0, 7)) {
2920 /* basic system colors */
2921 fg = &dc.col[base.fg + 8];
2922 } else if(BETWEEN(base.fg, 16, 195)) {
2924 fg = &dc.col[base.fg + 36];
2925 } else if(BETWEEN(base.fg, 232, 251)) {
2927 fg = &dc.col[base.fg + 4];
2930 * Those ranges will not be brightened:
2931 * 8 - 15 – bright system colors
2932 * 196 - 231 – highest 256 color cube
2933 * 252 - 255 – brightest colors in greyscale
2936 frcflags = FRC_BOLD;
2939 if(IS_SET(MODE_REVERSE)) {
2940 if(fg == &dc.col[defaultfg]) {
2941 fg = &dc.col[defaultbg];
2943 colfg.red = ~fg->color.red;
2944 colfg.green = ~fg->color.green;
2945 colfg.blue = ~fg->color.blue;
2946 colfg.alpha = fg->color.alpha;
2947 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2951 if(bg == &dc.col[defaultbg]) {
2952 bg = &dc.col[defaultfg];
2954 colbg.red = ~bg->color.red;
2955 colbg.green = ~bg->color.green;
2956 colbg.blue = ~bg->color.blue;
2957 colbg.alpha = bg->color.alpha;
2958 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2963 if(base.mode & ATTR_REVERSE) {
2969 if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
2972 /* Intelligent cleaning up of the borders. */
2974 xclear(0, (y == 0)? 0 : winy, borderpx,
2975 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
2977 if(x + charlen >= term.col) {
2978 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2979 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
2982 xclear(winx, 0, winx + width, borderpx);
2984 xclear(winx, winy + xw.ch, winx + width, xw.h);
2986 /* Clean up the region we want to draw to. */
2987 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
2989 /* Set the clip region because Xft is sometimes dirty. */
2994 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
2996 for(xp = winx; bytelen > 0;) {
2998 * Search for the range in the to be printed string of glyphs
2999 * that are in the main font. Then print that range. If
3000 * some glyph is found that is not in the font, do the
3008 u8cblen = utf8decode(s, &u8char);
3012 doesexist = XftCharIndex(xw.dpy, font->match, u8char);
3013 if(!doesexist || bytelen <= 0) {
3022 XftDrawStringUtf8(xw.draw, fg,
3024 winy + font->ascent,
3027 xp += font->width * u8fl;
3040 /* Search the font cache. */
3041 for(i = 0; i < frclen; i++, frp--) {
3045 if(frc[frp].c == u8char
3046 && frc[frp].flags == frcflags) {
3051 /* Nothing was found. */
3055 fcsets[0] = font->set;
3058 * Nothing was found in the cache. Now use
3059 * some dozen of Fontconfig calls to get the
3060 * font for one single character.
3062 fcpattern = FcPatternDuplicate(font->pattern);
3063 fccharset = FcCharSetCreate();
3065 FcCharSetAddChar(fccharset, u8char);
3066 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3068 FcPatternAddBool(fcpattern, FC_SCALABLE,
3071 FcConfigSubstitute(0, fcpattern,
3073 FcDefaultSubstitute(fcpattern);
3075 fontpattern = FcFontSetMatch(0, fcsets,
3076 FcTrue, fcpattern, &fcres);
3079 * Overwrite or create the new cache entry.
3083 if(frccur >= LEN(frc))
3085 if(frclen > LEN(frc)) {
3087 XftFontClose(xw.dpy, frc[frccur].font);
3090 frc[frccur].font = XftFontOpenPattern(xw.dpy,
3092 frc[frccur].c = u8char;
3093 frc[frccur].flags = frcflags;
3095 FcPatternDestroy(fcpattern);
3096 FcCharSetDestroy(fccharset);
3101 XftDrawStringUtf8(xw.draw, fg, frc[frp].font,
3102 xp, winy + frc[frp].font->ascent,
3103 (FcChar8 *)u8c, u8cblen);
3109 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
3110 winy + font->ascent, (FcChar8 *)s, bytelen);
3113 if(base.mode & ATTR_UNDERLINE) {
3114 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
3118 /* Reset clip to none. */
3119 XftDrawSetClip(xw.draw, 0);
3124 static int oldx = 0, oldy = 0;
3126 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
3128 LIMIT(oldx, 0, term.col-1);
3129 LIMIT(oldy, 0, term.row-1);
3131 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
3133 /* remove the old cursor */
3134 sl = utf8size(term.line[oldy][oldx].c);
3135 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
3138 /* draw the new one */
3139 if(!(IS_SET(MODE_HIDE))) {
3140 if(xw.state & WIN_FOCUSED) {
3141 if(IS_SET(MODE_REVERSE)) {
3142 g.mode |= ATTR_REVERSE;
3148 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
3150 XftDrawRect(xw.draw, &dc.col[defaultcs],
3151 borderpx + term.c.x * xw.cw,
3152 borderpx + term.c.y * xw.ch,
3154 XftDrawRect(xw.draw, &dc.col[defaultcs],
3155 borderpx + term.c.x * xw.cw,
3156 borderpx + term.c.y * xw.ch,
3158 XftDrawRect(xw.draw, &dc.col[defaultcs],
3159 borderpx + (term.c.x + 1) * xw.cw - 1,
3160 borderpx + term.c.y * xw.ch,
3162 XftDrawRect(xw.draw, &dc.col[defaultcs],
3163 borderpx + term.c.x * xw.cw,
3164 borderpx + (term.c.y + 1) * xw.ch - 1,
3167 oldx = term.c.x, oldy = term.c.y;
3173 xsettitle(char *p) {
3176 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3178 XSetWMName(xw.dpy, xw.win, &prop);
3183 xsettitle(opt_title ? opt_title : "st");
3187 redraw(int timeout) {
3188 struct timespec tv = {0, timeout * 1000};
3194 nanosleep(&tv, NULL);
3195 XSync(xw.dpy, False); /* necessary for a good tput flash */
3201 drawregion(0, 0, term.col, term.row);
3202 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3204 XSetForeground(xw.dpy, dc.gc,
3205 dc.col[IS_SET(MODE_REVERSE)?
3206 defaultfg : defaultbg].pixel);
3210 drawregion(int x1, int y1, int x2, int y2) {
3211 int ic, ib, x, y, ox, sl;
3213 char buf[DRAW_BUF_SIZ];
3214 bool ena_sel = sel.bx != -1;
3216 if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3219 if(!(xw.state & WIN_VISIBLE))
3222 for(y = y1; y < y2; y++) {
3226 xtermclear(0, y, term.col, y);
3228 base = term.line[y][0];
3230 for(x = x1; x < x2; x++) {
3231 new = term.line[y][x];
3232 if(ena_sel && selected(x, y))
3233 new.mode ^= ATTR_REVERSE;
3234 if(ib > 0 && (ATTRCMP(base, new)
3235 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3236 xdraws(buf, base, ox, y, ic, ib);
3244 sl = utf8size(new.c);
3245 memcpy(buf+ib, new.c, sl);
3250 xdraws(buf, base, ox, y, ic, ib);
3256 expose(XEvent *ev) {
3257 XExposeEvent *e = &ev->xexpose;
3259 if(xw.state & WIN_REDRAW) {
3261 xw.state &= ~WIN_REDRAW;
3267 visibility(XEvent *ev) {
3268 XVisibilityEvent *e = &ev->xvisibility;
3270 if(e->state == VisibilityFullyObscured) {
3271 xw.state &= ~WIN_VISIBLE;
3272 } else if(!(xw.state & WIN_VISIBLE)) {
3273 /* need a full redraw for next Expose, not just a buf copy */
3274 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3280 xw.state &= ~WIN_VISIBLE;
3284 xseturgency(int add) {
3285 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3287 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3288 XSetWMHints(xw.dpy, xw.win, h);
3294 XFocusChangeEvent *e = &ev->xfocus;
3296 if(e->mode == NotifyGrab)
3299 if(ev->type == FocusIn) {
3300 XSetICFocus(xw.xic);
3301 xw.state |= WIN_FOCUSED;
3304 XUnsetICFocus(xw.xic);
3305 xw.state &= ~WIN_FOCUSED;
3310 match(uint mask, uint state) {
3311 state &= ~(ignoremod);
3313 if(mask == XK_NO_MOD && state)
3315 if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
3317 if((state & mask) != state)
3323 numlock(const Arg *dummy) {
3328 kmap(KeySym k, uint state) {
3333 /* Check for mapped keys out of X11 function keys. */
3334 for(i = 0; i < LEN(mappedkeys); i++) {
3335 if(mappedkeys[i] == k)
3338 if(i == LEN(mappedkeys)) {
3339 if((k & 0xFFFF) < 0xFD00)
3343 for(kp = key; kp < key + LEN(key); kp++) {
3349 if(!match(mask, state))
3352 if(kp->appkey > 0) {
3353 if(!IS_SET(MODE_APPKEYPAD))
3355 if(term.numlock && kp->appkey == 2)
3357 } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
3361 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
3363 && !IS_SET(MODE_APPCURSOR))) {
3367 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
3368 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
3379 kpress(XEvent *ev) {
3380 XKeyEvent *e = &ev->xkey;
3382 char xstr[31], buf[32], *customkey, *cp = buf;
3388 if(IS_SET(MODE_KBDLOCK))
3391 len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
3392 e->state &= ~Mod2Mask;
3394 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3395 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3396 bp->func(&(bp->arg));
3401 /* 2. custom keys from config.h */
3402 if((customkey = kmap(ksym, e->state))) {
3403 len = strlen(customkey);
3404 memcpy(buf, customkey, len);
3405 /* 3. hardcoded (overrides X lookup) */
3410 if(len == 1 && e->state & Mod1Mask) {
3411 if(IS_SET(MODE_8BIT)) {
3414 ret = utf8encode(&c, cp);
3423 memcpy(cp, xstr, len);
3424 len = cp - buf + len;
3428 if(IS_SET(MODE_ECHO))
3434 cmessage(XEvent *e) {
3437 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3439 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3440 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3441 xw.state |= WIN_FOCUSED;
3443 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3444 xw.state &= ~WIN_FOCUSED;
3446 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3447 /* Send SIGHUP to shell */
3454 cresize(int width, int height) {
3462 col = (xw.w - 2 * borderpx) / xw.cw;
3463 row = (xw.h - 2 * borderpx) / xw.ch;
3472 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3475 cresize(e->xconfigure.width, e->xconfigure.height);
3482 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3483 struct timeval drawtimeout, *tv = NULL, now, last, lastblink;
3485 gettimeofday(&lastblink, NULL);
3486 gettimeofday(&last, NULL);
3488 for(xev = actionfps;;) {
3490 FD_SET(cmdfd, &rfd);
3493 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3496 die("select failed: %s\n", SERRNO);
3498 if(FD_ISSET(cmdfd, &rfd)) {
3501 blinkset = tattrset(ATTR_BLINK);
3502 if(!blinkset && term.mode & ATTR_BLINK)
3503 term.mode &= ~(MODE_BLINK);
3507 if(FD_ISSET(xfd, &rfd))
3510 gettimeofday(&now, NULL);
3511 drawtimeout.tv_sec = 0;
3512 drawtimeout.tv_usec = (1000/xfps) * 1000;
3516 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3517 tsetdirtattr(ATTR_BLINK);
3518 term.mode ^= MODE_BLINK;
3519 gettimeofday(&lastblink, NULL);
3522 if(TIMEDIFF(now, last) \
3523 > (xev? (1000/xfps) : (1000/actionfps))) {
3529 while(XPending(xw.dpy)) {
3530 XNextEvent(xw.dpy, &ev);
3531 if(XFilterEvent(&ev, None))
3533 if(handler[ev.type])
3534 (handler[ev.type])(&ev);
3540 if(xev && !FD_ISSET(xfd, &rfd))
3542 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3544 if(TIMEDIFF(now, lastblink) \
3546 drawtimeout.tv_usec = 1;
3548 drawtimeout.tv_usec = (1000 * \
3563 die("%s " VERSION " (c) 2010-2013 st engineers\n" \
3564 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
3565 " [-t title] [-w windowid] [-e command ...]\n", argv0);
3569 main(int argc, char *argv[]) {
3573 xw.fw = xw.fh = xw.fx = xw.fy = 0;
3578 allowaltscreen = false;
3581 opt_class = EARGF(usage());
3584 /* eat all remaining arguments */
3589 opt_font = EARGF(usage());
3592 bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
3597 if(bitm & WidthValue)
3599 if(bitm & HeightValue)
3601 if(bitm & XNegative && xw.fx == 0)
3603 if(bitm & XNegative && xw.fy == 0)
3606 if(xw.fh != 0 && xw.fw != 0)
3610 opt_io = EARGF(usage());
3613 opt_title = EARGF(usage());
3616 opt_embed = EARGF(usage());
3624 setlocale(LC_CTYPE, "");
3625 XSetLocaleModifiers("");
3631 cresize(xw.h, xw.w);