1 /* See LICENSE for licence details. */
14 #include <sys/ioctl.h>
15 #include <sys/select.h>
18 #include <sys/types.h>
23 #include <X11/Xatom.h>
25 #include <X11/Xutil.h>
26 #include <X11/cursorfont.h>
27 #include <X11/keysym.h>
28 #include <X11/Xft/Xft.h>
29 #include <fontconfig/fontconfig.h>
37 #define Draw XftDraw *
38 #define Colour XftColor
39 #define Colourmap Colormap
40 #define Rectangle XRectangle
44 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
46 #elif defined(__FreeBSD__) || defined(__DragonFly__)
52 #define XEMBED_FOCUS_IN 4
53 #define XEMBED_FOCUS_OUT 5
57 #define ESC_BUF_SIZ (128*UTF_SIZ)
58 #define ESC_ARG_SIZ 16
59 #define STR_BUF_SIZ ESC_BUF_SIZ
60 #define STR_ARG_SIZ ESC_ARG_SIZ
61 #define DRAW_BUF_SIZ 20*1024
62 #define XK_ANY_MOD UINT_MAX
64 #define XK_SWITCH_MOD (1<<13)
66 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
69 #define SERRNO strerror(errno)
70 #define MIN(a, b) ((a) < (b) ? (a) : (b))
71 #define MAX(a, b) ((a) < (b) ? (b) : (a))
72 #define LEN(a) (sizeof(a) / sizeof(a[0]))
73 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
74 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
75 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
76 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
77 #define IS_SET(flag) ((term.mode & (flag)) != 0)
78 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
80 #define VT102ID "\033[?6c"
82 enum glyph_attribute {
93 enum cursor_movement {
111 MODE_MOUSEMOTION = 64,
116 MODE_APPCURSOR = 2048,
117 MODE_MOUSESGR = 4096,
122 MODE_MOUSEX10 = 131072,
123 MODE_MOUSEMANY = 262144,
124 MODE_MOUSE = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
131 ESC_STR = 4, /* DSC, OSC, PM, APC */
133 ESC_STR_END = 16, /* a final string was encountered */
134 ESC_TEST = 32, /* Enter in test mode */
143 enum selection_type {
148 enum selection_snap {
153 typedef unsigned char uchar;
154 typedef unsigned int uint;
155 typedef unsigned long ulong;
156 typedef unsigned short ushort;
159 char c[UTF_SIZ]; /* character code */
160 uchar mode; /* attribute flags */
161 ushort fg; /* foreground */
162 ushort bg; /* background */
168 Glyph attr; /* current char attributes */
174 /* CSI Escape sequence structs */
175 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
177 char buf[ESC_BUF_SIZ]; /* raw string */
178 int len; /* raw string length */
180 int arg[ESC_ARG_SIZ];
181 int narg; /* nb of args */
185 /* STR Escape sequence structs */
186 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
188 char type; /* ESC type ... */
189 char buf[STR_BUF_SIZ]; /* raw string */
190 int len; /* raw string length */
191 char *args[STR_ARG_SIZ];
192 int narg; /* nb of args */
195 /* Internal representation of the screen */
197 int row; /* nb row */
198 int col; /* nb col */
199 Line *line; /* screen */
200 Line *alt; /* alternate screen */
201 bool *dirty; /* dirtyness of lines */
202 TCursor c; /* cursor */
203 int top; /* top scroll limit */
204 int bot; /* bottom scroll limit */
205 int mode; /* terminal mode flags */
206 int esc; /* escape state flags */
207 bool numlock; /* lock numbers in keyboard */
211 /* Purely graphic info */
217 Atom xembed, wmdeletewin;
222 XSetWindowAttributes attrs;
224 bool isfixed; /* is fixed geometry? */
225 int fx, fy, fw, fh; /* fixed geometry */
226 int tw, th; /* tty width and height */
227 int w, h; /* window width and height */
228 int ch; /* char height */
229 int cw; /* char width */
230 char state; /* focus, redraw, visible */
243 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
244 signed char appkey; /* application keypad */
245 signed char appcursor; /* application cursor */
246 signed char crlf; /* crlf mode */
254 * Selection variables:
255 * nb – normalized coordinates of the beginning of the selection
256 * ne – normalized coordinates of the end of the selection
257 * ob – original coordinates of the beginning of the selection
258 * oe – original coordinates of the end of the selection
267 struct timeval tclick1;
268 struct timeval tclick2;
281 void (*func)(const Arg *);
285 /* function definitions used in config.h */
286 static void clippaste(const Arg *);
287 static void numlock(const Arg *);
288 static void selpaste(const Arg *);
289 static void xzoom(const Arg *);
291 /* Config.h for applying patches and the configuration. */
307 /* Drawing Context */
309 Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
310 Font font, bfont, ifont, ibfont;
314 static void die(const char *, ...);
315 static void draw(void);
316 static void redraw(int);
317 static void drawregion(int, int, int, int);
318 static void execsh(void);
319 static void sigchld(int);
320 static void run(void);
322 static void csidump(void);
323 static void csihandle(void);
324 static void csiparse(void);
325 static void csireset(void);
326 static void strdump(void);
327 static void strhandle(void);
328 static void strparse(void);
329 static void strreset(void);
331 static int tattrset(int);
332 static void tclearregion(int, int, int, int);
333 static void tcursor(int);
334 static void tdeletechar(int);
335 static void tdeleteline(int);
336 static void tinsertblank(int);
337 static void tinsertblankline(int);
338 static void tmoveto(int, int);
339 static void tmoveato(int x, int y);
340 static void tnew(int, int);
341 static void tnewline(int);
342 static void tputtab(bool);
343 static void tputc(char *, int);
344 static void treset(void);
345 static int tresize(int, int);
346 static void tscrollup(int, int);
347 static void tscrolldown(int, int);
348 static void tsetattr(int*, int);
349 static void tsetchar(char *, Glyph *, int, int);
350 static void tsetscroll(int, int);
351 static void tswapscreen(void);
352 static void tsetdirt(int, int);
353 static void tsetdirtattr(int);
354 static void tsetmode(bool, bool, int *, int);
355 static void tfulldirt(void);
356 static void techo(char *, int);
358 static inline bool match(uint, uint);
359 static void ttynew(void);
360 static void ttyread(void);
361 static void ttyresize(void);
362 static void ttywrite(const char *, size_t);
364 static void xdraws(char *, Glyph, int, int, int, int);
365 static void xhints(void);
366 static void xclear(int, int, int, int);
367 static void xdrawcursor(void);
368 static void xinit(void);
369 static void xloadcols(void);
370 static int xsetcolorname(int, const char *);
371 static int xloadfont(Font *, FcPattern *);
372 static void xloadfonts(char *, int);
373 static int xloadfontset(Font *);
374 static void xsettitle(char *);
375 static void xresettitle(void);
376 static void xsetpointermotion(int);
377 static void xseturgency(int);
378 static void xsetsel(char*);
379 static void xtermclear(int, int, int, int);
380 static void xunloadfont(Font *f);
381 static void xunloadfonts(void);
382 static void xresize(int, int);
384 static void expose(XEvent *);
385 static void visibility(XEvent *);
386 static void unmap(XEvent *);
387 static char *kmap(KeySym, uint);
388 static void kpress(XEvent *);
389 static void cmessage(XEvent *);
390 static void cresize(int, int);
391 static void resize(XEvent *);
392 static void focus(XEvent *);
393 static void brelease(XEvent *);
394 static void bpress(XEvent *);
395 static void bmotion(XEvent *);
396 static void selnotify(XEvent *);
397 static void selclear(XEvent *);
398 static void selrequest(XEvent *);
400 static void selinit(void);
401 static void selsort(void);
402 static inline bool selected(int, int);
403 static void selcopy(void);
404 static void selscroll(int, int);
405 static void selsnap(int, int *, int *, int);
407 static int utf8decode(char *, long *);
408 static int utf8encode(long *, char *);
409 static int utf8size(char *);
410 static int isfullutf8(char *, int);
412 static ssize_t xwrite(int, char *, size_t);
413 static void *xmalloc(size_t);
414 static void *xrealloc(void *, size_t);
415 static void *xcalloc(size_t, size_t);
417 static void (*handler[LASTEvent])(XEvent *) = {
419 [ClientMessage] = cmessage,
420 [ConfigureNotify] = resize,
421 [VisibilityNotify] = visibility,
422 [UnmapNotify] = unmap,
426 [MotionNotify] = bmotion,
427 [ButtonPress] = bpress,
428 [ButtonRelease] = brelease,
429 [SelectionClear] = selclear,
430 [SelectionNotify] = selnotify,
431 [SelectionRequest] = selrequest,
438 static CSIEscape csiescseq;
439 static STREscape strescseq;
442 static Selection sel;
443 static int iofd = -1;
444 static char **opt_cmd = NULL;
445 static char *opt_io = NULL;
446 static char *opt_title = NULL;
447 static char *opt_embed = NULL;
448 static char *opt_class = NULL;
449 static char *opt_font = NULL;
450 static int oldbutton = 3; /* button event on startup: 3 = release */
452 static char *usedfont = NULL;
453 static int usedfontsize = 0;
455 /* Font Ring Cache */
470 * Fontcache is a ring buffer, with frccur as current position and frclen as
471 * the current length of used elements.
474 static Fontcache frc[1024];
475 static int frccur = -1, frclen = 0;
478 xwrite(int fd, char *s, size_t len) {
482 ssize_t r = write(fd, s, len);
492 xmalloc(size_t len) {
493 void *p = malloc(len);
496 die("Out of memory\n");
502 xrealloc(void *p, size_t len) {
503 if((p = realloc(p, len)) == NULL)
504 die("Out of memory\n");
510 xcalloc(size_t nmemb, size_t size) {
511 void *p = calloc(nmemb, size);
514 die("Out of memory\n");
520 utf8decode(char *s, long *u) {
526 if(~c & 0x80) { /* 0xxxxxxx */
529 } else if((c & 0xE0) == 0xC0) { /* 110xxxxx */
532 } else if((c & 0xF0) == 0xE0) { /* 1110xxxx */
535 } else if((c & 0xF8) == 0xF0) { /* 11110xxx */
542 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
544 if((c & 0xC0) != 0x80) /* 10xxxxxx */
550 if((n == 1 && *u < 0x80) ||
551 (n == 2 && *u < 0x800) ||
552 (n == 3 && *u < 0x10000) ||
553 (*u >= 0xD800 && *u <= 0xDFFF)) {
565 utf8encode(long *u, char *s) {
573 *sp = uc; /* 0xxxxxxx */
575 } else if(*u < 0x800) {
576 *sp = (uc >> 6) | 0xC0; /* 110xxxxx */
578 } else if(uc < 0x10000) {
579 *sp = (uc >> 12) | 0xE0; /* 1110xxxx */
581 } else if(uc <= 0x10FFFF) {
582 *sp = (uc >> 18) | 0xF0; /* 11110xxx */
588 for(i=n,++sp; i>0; --i,++sp)
589 *sp = ((uc >> 6*(i-1)) & 0x3F) | 0x80; /* 10xxxxxx */
601 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
602 UTF-8 otherwise return 0 */
604 isfullutf8(char *s, int b) {
612 } else if((*c1 & 0xE0) == 0xC0 && b == 1) {
614 } else if((*c1 & 0xF0) == 0xE0 &&
616 ((b == 2) && (*c2 & 0xC0) == 0x80))) {
618 } else if((*c1 & 0xF8) == 0xF0 &&
620 ((b == 2) && (*c2 & 0xC0) == 0x80) ||
621 ((b == 3) && (*c2 & 0xC0) == 0x80 && (*c3 & 0xC0) == 0x80))) {
634 } else if((c & 0xE0) == 0xC0) {
636 } else if((c & 0xF0) == 0xE0) {
645 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
646 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
650 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
651 if(sel.xtarget == None)
652 sel.xtarget = XA_STRING;
660 return LIMIT(x, 0, term.col-1);
668 return LIMIT(y, 0, term.row-1);
673 if(sel.ob.y == sel.oe.y) {
674 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
675 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
677 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
678 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
680 sel.nb.y = MIN(sel.ob.y, sel.oe.y);
681 sel.ne.y = MAX(sel.ob.y, sel.oe.y);
685 selected(int x, int y) {
686 if(sel.ne.y == y && sel.nb.y == y)
687 return BETWEEN(x, sel.nb.x, sel.ne.x);
689 if(sel.type == SEL_RECTANGULAR) {
690 return ((sel.nb.y <= y && y <= sel.ne.y)
691 && (sel.nb.x <= x && x <= sel.ne.x));
694 return ((sel.nb.y < y && y < sel.ne.y)
695 || (y == sel.ne.y && x <= sel.ne.x))
696 || (y == sel.nb.y && x >= sel.nb.x
697 && (x <= sel.ne.x || sel.nb.y != sel.ne.y));
701 selsnap(int mode, int *x, int *y, int direction) {
707 * Snap around if the word wraps around at the end or
708 * beginning of a line.
711 if(direction < 0 && *x <= 0) {
712 if(*y > 0 && term.line[*y - 1][term.col-1].mode
720 if(direction > 0 && *x >= term.col-1) {
721 if(*y < term.row-1 && term.line[*y][*x].mode
730 if(strchr(worddelimiters,
731 term.line[*y][*x + direction].c[0])) {
740 * Snap around if the the previous line or the current one
741 * has set ATTR_WRAP at its end. Then the whole next or
742 * previous line will be selected.
744 *x = (direction < 0) ? 0 : term.col - 1;
745 if(direction < 0 && *y > 0) {
746 for(; *y > 0; *y += direction) {
747 if(!(term.line[*y-1][term.col-1].mode
752 } else if(direction > 0 && *y < term.row-1) {
753 for(; *y < term.row; *y += direction) {
754 if(!(term.line[*y][term.col-1].mode
763 * Select the whole line when the end of line is reached.
767 while(--i > 0 && term.line[*y][i].c[0] == ' ')
777 getbuttoninfo(XEvent *e) {
779 uint state = e->xbutton.state &~Button1Mask;
781 sel.alt = IS_SET(MODE_ALTSCREEN);
783 sel.oe.x = x2col(e->xbutton.x);
784 sel.oe.y = y2row(e->xbutton.y);
786 if(sel.ob.y < sel.oe.y
787 || (sel.ob.y == sel.oe.y && sel.ob.x < sel.oe.x)) {
788 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
789 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
791 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, -1);
792 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, +1);
796 sel.type = SEL_REGULAR;
797 for(type = 1; type < LEN(selmasks); ++type) {
798 if(match(selmasks[type], state)) {
806 mousereport(XEvent *e) {
807 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
808 button = e->xbutton.button, state = e->xbutton.state,
814 if(e->xbutton.type == MotionNotify) {
815 if(x == ox && y == oy)
817 if(!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
819 /* MOUSE_MOTION: no reporting if no button is pressed */
820 if(IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
823 button = oldbutton + 32;
826 } else if(!IS_SET(MODE_MOUSESGR)
827 && (e->xbutton.type == ButtonRelease
828 || button == AnyButton)) {
834 if(e->xbutton.type == ButtonPress) {
841 if(!IS_SET(MODE_MOUSEX10)) {
842 button += (state & ShiftMask ? 4 : 0)
843 + (state & Mod4Mask ? 8 : 0)
844 + (state & ControlMask ? 16 : 0);
848 if(IS_SET(MODE_MOUSESGR)) {
849 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
851 e->xbutton.type == ButtonRelease ? 'm' : 'M');
852 } else if(x < 223 && y < 223) {
853 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
854 IS_SET(MODE_MOUSEX10)? button-1 : 32+button,
868 if(IS_SET(MODE_MOUSE)) {
873 for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
874 if(e->xbutton.button == mk->b
875 && match(mk->mask, e->xbutton.state)) {
876 ttywrite(mk->s, strlen(mk->s));
877 if(IS_SET(MODE_ECHO))
878 techo(mk->s, strlen(mk->s));
883 if(e->xbutton.button == Button1) {
884 gettimeofday(&now, NULL);
886 /* Clear previous selection, logically and visually. */
889 sel.type = SEL_REGULAR;
890 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
891 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
894 * If the user clicks below predefined timeouts specific
895 * snapping behaviour is exposed.
897 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
898 sel.snap = SNAP_LINE;
899 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
900 sel.snap = SNAP_WORD;
904 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
905 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
909 * Draw selection, unless it's regular and we don't want to
910 * make clicks visible
914 tsetdirt(sel.nb.y, sel.ne.y);
916 sel.tclick2 = sel.tclick1;
924 int x, y, bufsize, size, i, ex;
930 bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
931 ptr = str = xmalloc(bufsize);
933 /* append every set & selected glyph to the selection */
934 for(y = sel.nb.y; y < sel.ne.y + 1; y++) {
935 gp = &term.line[y][0];
936 last = gp + term.col;
938 while(--last >= gp && !(selected(last - gp, y) && \
939 strcmp(last->c, " ") != 0))
942 for(x = 0; gp <= last; x++, ++gp) {
946 size = utf8size(gp->c);
947 memcpy(ptr, gp->c, size);
952 * Copy and pasting of line endings is inconsistent
953 * in the inconsistent terminal and GUI world.
954 * The best solution seems like to produce '\n' when
955 * something is copied from st and convert '\n' to
956 * '\r', when something to be pasted is received by
958 * FIXME: Fix the computer world.
960 if(y < sel.ne.y && !((gp-1)->mode & ATTR_WRAP))
964 * If the last selected line expands in the selection
965 * after the visible text '\n' is appended.
969 while(--i > 0 && term.line[y][i].c[0] == ' ')
972 if(sel.nb.y == sel.ne.y && sel.ne.x < sel.nb.x)
984 selnotify(XEvent *e) {
985 ulong nitems, ofs, rem;
987 uchar *data, *last, *repl;
992 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
993 False, AnyPropertyType, &type, &format,
994 &nitems, &rem, &data)) {
995 fprintf(stderr, "Clipboard allocation failed\n");
1000 * As seen in selcopy:
1001 * Line endings are inconsistent in the terminal and GUI world
1002 * copy and pasting. When receiving some selection data,
1003 * replace all '\n' with '\r'.
1004 * FIXME: Fix the computer world.
1007 last = data + nitems * format / 8;
1008 while((repl = memchr(repl, '\n', last - repl))) {
1012 ttywrite((const char *)data, nitems * format / 8);
1014 /* number of 32-bit chunks returned */
1015 ofs += nitems * format / 32;
1020 selpaste(const Arg *dummy) {
1021 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1022 xw.win, CurrentTime);
1026 clippaste(const Arg *dummy) {
1029 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1030 XConvertSelection(xw.dpy, clipboard, sel.xtarget, XA_PRIMARY,
1031 xw.win, CurrentTime);
1035 selclear(XEvent *e) {
1039 tsetdirt(sel.nb.y, sel.ne.y);
1043 selrequest(XEvent *e) {
1044 XSelectionRequestEvent *xsre;
1045 XSelectionEvent xev;
1046 Atom xa_targets, string;
1048 xsre = (XSelectionRequestEvent *) e;
1049 xev.type = SelectionNotify;
1050 xev.requestor = xsre->requestor;
1051 xev.selection = xsre->selection;
1052 xev.target = xsre->target;
1053 xev.time = xsre->time;
1055 xev.property = None;
1057 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1058 if(xsre->target == xa_targets) {
1059 /* respond with the supported type */
1060 string = sel.xtarget;
1061 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1062 XA_ATOM, 32, PropModeReplace,
1063 (uchar *) &string, 1);
1064 xev.property = xsre->property;
1065 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
1066 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1067 xsre->target, 8, PropModeReplace,
1068 (uchar *) sel.clip, strlen(sel.clip));
1069 xev.property = xsre->property;
1072 /* all done, send a notification to the listener */
1073 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
1074 fprintf(stderr, "Error sending SelectionNotify event\n");
1078 xsetsel(char *str) {
1079 /* register the selection for both the clipboard and the primary */
1085 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
1087 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1088 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1092 brelease(XEvent *e) {
1093 if(IS_SET(MODE_MOUSE)) {
1098 if(e->xbutton.button == Button2) {
1100 } else if(e->xbutton.button == Button1) {
1108 tsetdirt(sel.nb.y, sel.ne.y);
1113 bmotion(XEvent *e) {
1114 int oldey, oldex, oldsby, oldsey;
1116 if(IS_SET(MODE_MOUSE)) {
1131 if(oldey != sel.oe.y || oldex != sel.oe.x)
1132 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1136 die(const char *errstr, ...) {
1139 va_start(ap, errstr);
1140 vfprintf(stderr, errstr, ap);
1148 char *envshell = getenv("SHELL");
1149 const struct passwd *pass = getpwuid(getuid());
1150 char buf[sizeof(long) * 8 + 1];
1152 unsetenv("COLUMNS");
1154 unsetenv("TERMCAP");
1157 setenv("LOGNAME", pass->pw_name, 1);
1158 setenv("USER", pass->pw_name, 1);
1159 setenv("SHELL", pass->pw_shell, 0);
1160 setenv("HOME", pass->pw_dir, 0);
1163 snprintf(buf, sizeof(buf), "%lu", xw.win);
1164 setenv("WINDOWID", buf, 1);
1166 signal(SIGCHLD, SIG_DFL);
1167 signal(SIGHUP, SIG_DFL);
1168 signal(SIGINT, SIG_DFL);
1169 signal(SIGQUIT, SIG_DFL);
1170 signal(SIGTERM, SIG_DFL);
1171 signal(SIGALRM, SIG_DFL);
1173 DEFAULT(envshell, shell);
1174 setenv("TERM", termname, 1);
1175 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
1176 execvp(args[0], args);
1184 if(waitpid(pid, &stat, 0) < 0)
1185 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
1187 if(WIFEXITED(stat)) {
1188 exit(WEXITSTATUS(stat));
1197 struct winsize w = {term.row, term.col, 0, 0};
1199 /* seems to work fine on linux, openbsd and freebsd */
1200 if(openpty(&m, &s, NULL, NULL, &w) < 0)
1201 die("openpty failed: %s\n", SERRNO);
1203 switch(pid = fork()) {
1205 die("fork failed\n");
1208 setsid(); /* create a new process group */
1209 dup2(s, STDIN_FILENO);
1210 dup2(s, STDOUT_FILENO);
1211 dup2(s, STDERR_FILENO);
1212 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1213 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
1221 signal(SIGCHLD, sigchld);
1223 iofd = (!strcmp(opt_io, "-")) ?
1225 open(opt_io, O_WRONLY | O_CREAT, 0666);
1227 fprintf(stderr, "Error opening %s:%s\n",
1228 opt_io, strerror(errno));
1238 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1240 fprintf(stderr, "\n");
1245 static char buf[BUFSIZ];
1246 static int buflen = 0;
1249 int charsize; /* size of utf8 char in bytes */
1253 /* append read bytes to unprocessed bytes */
1254 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1255 die("Couldn't read from shell: %s\n", SERRNO);
1257 /* process every complete utf8 char */
1260 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1261 charsize = utf8decode(ptr, &utf8c);
1262 utf8encode(&utf8c, s);
1268 /* keep any uncomplete utf8 char for the next call */
1269 memmove(buf, ptr, buflen);
1273 ttywrite(const char *s, size_t n) {
1274 if(write(cmdfd, s, n) == -1)
1275 die("write error on tty: %s\n", SERRNO);
1282 w.ws_row = term.row;
1283 w.ws_col = term.col;
1284 w.ws_xpixel = xw.tw;
1285 w.ws_ypixel = xw.th;
1286 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1287 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1291 tattrset(int attr) {
1294 for(i = 0; i < term.row-1; i++) {
1295 for(j = 0; j < term.col-1; j++) {
1296 if(term.line[i][j].mode & attr)
1305 tsetdirt(int top, int bot) {
1308 LIMIT(top, 0, term.row-1);
1309 LIMIT(bot, 0, term.row-1);
1311 for(i = top; i <= bot; i++)
1316 tsetdirtattr(int attr) {
1319 for(i = 0; i < term.row-1; i++) {
1320 for(j = 0; j < term.col-1; j++) {
1321 if(term.line[i][j].mode & attr) {
1331 tsetdirt(0, term.row-1);
1338 if(mode == CURSOR_SAVE) {
1340 } else if(mode == CURSOR_LOAD) {
1350 term.c = (TCursor){{
1354 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1356 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1357 for(i = tabspaces; i < term.col; i += tabspaces)
1360 term.bot = term.row - 1;
1361 term.mode = MODE_WRAP;
1363 tclearregion(0, 0, term.col-1, term.row-1);
1365 tcursor(CURSOR_SAVE);
1369 tnew(int col, int row) {
1370 memset(&term, 0, sizeof(Term));
1379 Line *tmp = term.line;
1381 term.line = term.alt;
1383 term.mode ^= MODE_ALTSCREEN;
1388 tscrolldown(int orig, int n) {
1392 LIMIT(n, 0, term.bot-orig+1);
1394 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1396 for(i = term.bot; i >= orig+n; i--) {
1397 temp = term.line[i];
1398 term.line[i] = term.line[i-n];
1399 term.line[i-n] = temp;
1402 term.dirty[i-n] = 1;
1409 tscrollup(int orig, int n) {
1412 LIMIT(n, 0, term.bot-orig+1);
1414 tclearregion(0, orig, term.col-1, orig+n-1);
1416 for(i = orig; i <= term.bot-n; i++) {
1417 temp = term.line[i];
1418 term.line[i] = term.line[i+n];
1419 term.line[i+n] = temp;
1422 term.dirty[i+n] = 1;
1425 selscroll(orig, -n);
1429 selscroll(int orig, int n) {
1433 if(BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1434 if((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1438 if(sel.type == SEL_RECTANGULAR) {
1439 if(sel.ob.y < term.top)
1440 sel.ob.y = term.top;
1441 if(sel.oe.y > term.bot)
1442 sel.oe.y = term.bot;
1444 if(sel.ob.y < term.top) {
1445 sel.ob.y = term.top;
1448 if(sel.oe.y > term.bot) {
1449 sel.oe.y = term.bot;
1450 sel.oe.x = term.col;
1458 tnewline(int first_col) {
1462 tscrollup(term.top, 1);
1466 tmoveto(first_col ? 0 : term.c.x, y);
1471 char *p = csiescseq.buf, *np;
1480 csiescseq.buf[csiescseq.len] = '\0';
1481 while(p < csiescseq.buf+csiescseq.len) {
1483 v = strtol(p, &np, 10);
1486 if(v == LONG_MAX || v == LONG_MIN)
1488 csiescseq.arg[csiescseq.narg++] = v;
1490 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1494 csiescseq.mode = *p;
1497 /* for absolute user moves, when decom is set */
1499 tmoveato(int x, int y) {
1500 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1504 tmoveto(int x, int y) {
1507 if(term.c.state & CURSOR_ORIGIN) {
1512 maxy = term.row - 1;
1514 LIMIT(x, 0, term.col-1);
1515 LIMIT(y, miny, maxy);
1516 term.c.state &= ~CURSOR_WRAPNEXT;
1522 tsetchar(char *c, Glyph *attr, int x, int y) {
1523 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1524 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1525 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1526 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1527 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1528 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1529 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1530 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1531 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1535 * The table is proudly stolen from rxvt.
1537 if(attr->mode & ATTR_GFX) {
1538 if(c[0] >= 0x41 && c[0] <= 0x7e
1539 && vt100_0[c[0] - 0x41]) {
1540 c = vt100_0[c[0] - 0x41];
1545 term.line[y][x] = *attr;
1546 memcpy(term.line[y][x].c, c, UTF_SIZ);
1550 tclearregion(int x1, int y1, int x2, int y2) {
1554 temp = x1, x1 = x2, x2 = temp;
1556 temp = y1, y1 = y2, y2 = temp;
1558 LIMIT(x1, 0, term.col-1);
1559 LIMIT(x2, 0, term.col-1);
1560 LIMIT(y1, 0, term.row-1);
1561 LIMIT(y2, 0, term.row-1);
1563 for(y = y1; y <= y2; y++) {
1565 for(x = x1; x <= x2; x++) {
1568 term.line[y][x] = term.c.attr;
1569 memcpy(term.line[y][x].c, " ", 2);
1575 tdeletechar(int n) {
1576 int src = term.c.x + n;
1578 int size = term.col - src;
1580 term.dirty[term.c.y] = 1;
1582 if(src >= term.col) {
1583 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1587 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1588 size * sizeof(Glyph));
1589 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1593 tinsertblank(int n) {
1596 int size = term.col - dst;
1598 term.dirty[term.c.y] = 1;
1600 if(dst >= term.col) {
1601 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1605 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1606 size * sizeof(Glyph));
1607 tclearregion(src, term.c.y, dst - 1, term.c.y);
1611 tinsertblankline(int n) {
1612 if(term.c.y < term.top || term.c.y > term.bot)
1615 tscrolldown(term.c.y, n);
1619 tdeleteline(int n) {
1620 if(term.c.y < term.top || term.c.y > term.bot)
1623 tscrollup(term.c.y, n);
1627 tsetattr(int *attr, int l) {
1630 for(i = 0; i < l; i++) {
1633 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE \
1634 | ATTR_BOLD | ATTR_ITALIC \
1636 term.c.attr.fg = defaultfg;
1637 term.c.attr.bg = defaultbg;
1640 term.c.attr.mode |= ATTR_BOLD;
1643 term.c.attr.mode |= ATTR_ITALIC;
1646 term.c.attr.mode |= ATTR_UNDERLINE;
1648 case 5: /* slow blink */
1649 case 6: /* rapid blink */
1650 term.c.attr.mode |= ATTR_BLINK;
1653 term.c.attr.mode |= ATTR_REVERSE;
1657 term.c.attr.mode &= ~ATTR_BOLD;
1660 term.c.attr.mode &= ~ATTR_ITALIC;
1663 term.c.attr.mode &= ~ATTR_UNDERLINE;
1667 term.c.attr.mode &= ~ATTR_BLINK;
1670 term.c.attr.mode &= ~ATTR_REVERSE;
1673 if(i + 2 < l && attr[i + 1] == 5) {
1675 if(BETWEEN(attr[i], 0, 255)) {
1676 term.c.attr.fg = attr[i];
1679 "erresc: bad fgcolor %d\n",
1684 "erresc(38): gfx attr %d unknown\n",
1689 term.c.attr.fg = defaultfg;
1692 if(i + 2 < l && attr[i + 1] == 5) {
1694 if(BETWEEN(attr[i], 0, 255)) {
1695 term.c.attr.bg = attr[i];
1698 "erresc: bad bgcolor %d\n",
1703 "erresc(48): gfx attr %d unknown\n",
1708 term.c.attr.bg = defaultbg;
1711 if(BETWEEN(attr[i], 30, 37)) {
1712 term.c.attr.fg = attr[i] - 30;
1713 } else if(BETWEEN(attr[i], 40, 47)) {
1714 term.c.attr.bg = attr[i] - 40;
1715 } else if(BETWEEN(attr[i], 90, 97)) {
1716 term.c.attr.fg = attr[i] - 90 + 8;
1717 } else if(BETWEEN(attr[i], 100, 107)) {
1718 term.c.attr.bg = attr[i] - 100 + 8;
1721 "erresc(default): gfx attr %d unknown\n",
1722 attr[i]), csidump();
1730 tsetscroll(int t, int b) {
1733 LIMIT(t, 0, term.row-1);
1734 LIMIT(b, 0, term.row-1);
1744 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1747 tsetmode(bool priv, bool set, int *args, int narg) {
1751 for(lim = args + narg; args < lim; ++args) {
1755 case 1: /* DECCKM -- Cursor key */
1756 MODBIT(term.mode, set, MODE_APPCURSOR);
1758 case 5: /* DECSCNM -- Reverse video */
1760 MODBIT(term.mode, set, MODE_REVERSE);
1761 if(mode != term.mode)
1762 redraw(REDRAW_TIMEOUT);
1764 case 6: /* DECOM -- Origin */
1765 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1768 case 7: /* DECAWM -- Auto wrap */
1769 MODBIT(term.mode, set, MODE_WRAP);
1771 case 0: /* Error (IGNORED) */
1772 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1773 case 3: /* DECCOLM -- Column (IGNORED) */
1774 case 4: /* DECSCLM -- Scroll (IGNORED) */
1775 case 8: /* DECARM -- Auto repeat (IGNORED) */
1776 case 18: /* DECPFF -- Printer feed (IGNORED) */
1777 case 19: /* DECPEX -- Printer extent (IGNORED) */
1778 case 42: /* DECNRCM -- National characters (IGNORED) */
1779 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1781 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1782 MODBIT(term.mode, !set, MODE_HIDE);
1784 case 9: /* X10 mouse compatibility mode */
1785 xsetpointermotion(0);
1786 MODBIT(term.mode, 0, MODE_MOUSE);
1787 MODBIT(term.mode, set, MODE_MOUSEX10);
1789 case 1000: /* 1000: report button press */
1790 xsetpointermotion(0);
1791 MODBIT(term.mode, 0, MODE_MOUSE);
1792 MODBIT(term.mode, set, MODE_MOUSEBTN);
1794 case 1002: /* 1002: report motion on button press */
1795 xsetpointermotion(0);
1796 MODBIT(term.mode, 0, MODE_MOUSE);
1797 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1799 case 1003: /* 1003: enable all mouse motions */
1800 xsetpointermotion(set);
1801 MODBIT(term.mode, 0, MODE_MOUSE);
1802 MODBIT(term.mode, set, MODE_MOUSEMANY);
1804 case 1004: /* 1004: send focus events to tty */
1805 MODBIT(term.mode, set, MODE_FOCUS);
1807 case 1006: /* 1006: extended reporting mode */
1808 MODBIT(term.mode, set, MODE_MOUSESGR);
1811 MODBIT(term.mode, set, MODE_8BIT);
1813 case 1049: /* = 1047 and 1048 */
1816 if (!allowaltscreen)
1819 alt = IS_SET(MODE_ALTSCREEN);
1821 tclearregion(0, 0, term.col-1,
1824 if(set ^ alt) /* set is always 1 or 0 */
1830 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1832 /* Not implemented mouse modes. See comments there. */
1833 case 1001: /* mouse highlight mode; can hang the
1834 terminal by design when implemented. */
1835 case 1005: /* UTF-8 mouse mode; will confuse
1836 applications not supporting UTF-8
1838 case 1015: /* urxvt mangled mouse mode; incompatible
1839 and can be mistaken for other control
1843 "erresc: unknown private set/reset mode %d\n",
1849 case 0: /* Error (IGNORED) */
1851 case 2: /* KAM -- keyboard action */
1852 MODBIT(term.mode, set, MODE_KBDLOCK);
1854 case 4: /* IRM -- Insertion-replacement */
1855 MODBIT(term.mode, set, MODE_INSERT);
1857 case 12: /* SRM -- Send/Receive */
1858 MODBIT(term.mode, !set, MODE_ECHO);
1860 case 20: /* LNM -- Linefeed/new line */
1861 MODBIT(term.mode, set, MODE_CRLF);
1865 "erresc: unknown set/reset mode %d\n",
1875 switch(csiescseq.mode) {
1878 fprintf(stderr, "erresc: unknown csi ");
1882 case '@': /* ICH -- Insert <n> blank char */
1883 DEFAULT(csiescseq.arg[0], 1);
1884 tinsertblank(csiescseq.arg[0]);
1886 case 'A': /* CUU -- Cursor <n> Up */
1887 DEFAULT(csiescseq.arg[0], 1);
1888 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1890 case 'B': /* CUD -- Cursor <n> Down */
1891 case 'e': /* VPR --Cursor <n> Down */
1892 DEFAULT(csiescseq.arg[0], 1);
1893 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1895 case 'c': /* DA -- Device Attributes */
1896 if(csiescseq.arg[0] == 0)
1897 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1899 case 'C': /* CUF -- Cursor <n> Forward */
1900 case 'a': /* HPR -- Cursor <n> Forward */
1901 DEFAULT(csiescseq.arg[0], 1);
1902 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1904 case 'D': /* CUB -- Cursor <n> Backward */
1905 DEFAULT(csiescseq.arg[0], 1);
1906 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1908 case 'E': /* CNL -- Cursor <n> Down and first col */
1909 DEFAULT(csiescseq.arg[0], 1);
1910 tmoveto(0, term.c.y+csiescseq.arg[0]);
1912 case 'F': /* CPL -- Cursor <n> Up and first col */
1913 DEFAULT(csiescseq.arg[0], 1);
1914 tmoveto(0, term.c.y-csiescseq.arg[0]);
1916 case 'g': /* TBC -- Tabulation clear */
1917 switch(csiescseq.arg[0]) {
1918 case 0: /* clear current tab stop */
1919 term.tabs[term.c.x] = 0;
1921 case 3: /* clear all the tabs */
1922 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1928 case 'G': /* CHA -- Move to <col> */
1930 DEFAULT(csiescseq.arg[0], 1);
1931 tmoveto(csiescseq.arg[0]-1, term.c.y);
1933 case 'H': /* CUP -- Move to <row> <col> */
1935 DEFAULT(csiescseq.arg[0], 1);
1936 DEFAULT(csiescseq.arg[1], 1);
1937 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1939 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1940 DEFAULT(csiescseq.arg[0], 1);
1941 while(csiescseq.arg[0]--)
1944 case 'J': /* ED -- Clear screen */
1946 switch(csiescseq.arg[0]) {
1948 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1949 if(term.c.y < term.row-1) {
1950 tclearregion(0, term.c.y+1, term.col-1,
1956 tclearregion(0, 0, term.col-1, term.c.y-1);
1957 tclearregion(0, term.c.y, term.c.x, term.c.y);
1960 tclearregion(0, 0, term.col-1, term.row-1);
1966 case 'K': /* EL -- Clear line */
1967 switch(csiescseq.arg[0]) {
1969 tclearregion(term.c.x, term.c.y, term.col-1,
1973 tclearregion(0, term.c.y, term.c.x, term.c.y);
1976 tclearregion(0, term.c.y, term.col-1, term.c.y);
1980 case 'S': /* SU -- Scroll <n> line up */
1981 DEFAULT(csiescseq.arg[0], 1);
1982 tscrollup(term.top, csiescseq.arg[0]);
1984 case 'T': /* SD -- Scroll <n> line down */
1985 DEFAULT(csiescseq.arg[0], 1);
1986 tscrolldown(term.top, csiescseq.arg[0]);
1988 case 'L': /* IL -- Insert <n> blank lines */
1989 DEFAULT(csiescseq.arg[0], 1);
1990 tinsertblankline(csiescseq.arg[0]);
1992 case 'l': /* RM -- Reset Mode */
1993 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1995 case 'M': /* DL -- Delete <n> lines */
1996 DEFAULT(csiescseq.arg[0], 1);
1997 tdeleteline(csiescseq.arg[0]);
1999 case 'X': /* ECH -- Erase <n> char */
2000 DEFAULT(csiescseq.arg[0], 1);
2001 tclearregion(term.c.x, term.c.y,
2002 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2004 case 'P': /* DCH -- Delete <n> char */
2005 DEFAULT(csiescseq.arg[0], 1);
2006 tdeletechar(csiescseq.arg[0]);
2008 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2009 DEFAULT(csiescseq.arg[0], 1);
2010 while(csiescseq.arg[0]--)
2013 case 'd': /* VPA -- Move to <row> */
2014 DEFAULT(csiescseq.arg[0], 1);
2015 tmoveato(term.c.x, csiescseq.arg[0]-1);
2017 case 'h': /* SM -- Set terminal mode */
2018 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2020 case 'm': /* SGR -- Terminal attribute (color) */
2021 tsetattr(csiescseq.arg, csiescseq.narg);
2023 case 'r': /* DECSTBM -- Set Scrolling Region */
2024 if(csiescseq.priv) {
2027 DEFAULT(csiescseq.arg[0], 1);
2028 DEFAULT(csiescseq.arg[1], term.row);
2029 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2033 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2034 tcursor(CURSOR_SAVE);
2036 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2037 tcursor(CURSOR_LOAD);
2048 for(i = 0; i < csiescseq.len; i++) {
2049 c = csiescseq.buf[i] & 0xff;
2052 } else if(c == '\n') {
2054 } else if(c == '\r') {
2056 } else if(c == 0x1b) {
2059 printf("(%02x)", c);
2067 memset(&csiescseq, 0, sizeof(csiescseq));
2076 narg = strescseq.narg;
2078 switch(strescseq.type) {
2079 case ']': /* OSC -- Operating System Command */
2080 switch(i = atoi(strescseq.args[0])) {
2085 xsettitle(strescseq.args[1]);
2087 case 4: /* color set */
2090 p = strescseq.args[2];
2092 case 104: /* color reset, here p = NULL */
2093 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2094 if (!xsetcolorname(j, p)) {
2095 fprintf(stderr, "erresc: invalid color %s\n", p);
2098 * TODO if defaultbg color is changed, borders
2105 fprintf(stderr, "erresc: unknown str ");
2110 case 'k': /* old title set compatibility */
2111 xsettitle(strescseq.args[0]);
2113 case 'P': /* DSC -- Device Control String */
2114 case '_': /* APC -- Application Program Command */
2115 case '^': /* PM -- Privacy Message */
2117 fprintf(stderr, "erresc: unknown str ");
2126 char *p = strescseq.buf;
2129 strescseq.buf[strescseq.len] = '\0';
2130 while(p && strescseq.narg < STR_ARG_SIZ)
2131 strescseq.args[strescseq.narg++] = strsep(&p, ";");
2139 printf("ESC%c", strescseq.type);
2140 for(i = 0; i < strescseq.len; i++) {
2141 c = strescseq.buf[i] & 0xff;
2144 } else if(isprint(c)) {
2146 } else if(c == '\n') {
2148 } else if(c == '\r') {
2150 } else if(c == 0x1b) {
2153 printf("(%02x)", c);
2161 memset(&strescseq, 0, sizeof(strescseq));
2165 tputtab(bool forward) {
2171 for(++x; x < term.col && !term.tabs[x]; ++x)
2176 for(--x; x > 0 && !term.tabs[x]; --x)
2179 tmoveto(x, term.c.y);
2183 techo(char *buf, int len) {
2184 for(; len > 0; buf++, len--) {
2187 if(c == '\033') { /* escape */
2190 } else if(c < '\x20') { /* control code */
2191 if(c != '\n' && c != '\r' && c != '\t') {
2205 tputc(char *c, int len) {
2207 bool control = ascii < '\x20' || ascii == 0177;
2210 if(xwrite(iofd, c, len) < 0) {
2211 fprintf(stderr, "Error writing in %s:%s\n",
2212 opt_io, strerror(errno));
2219 * STR sequences must be checked before anything else
2220 * because it can use some control codes as part of the sequence.
2222 if(term.esc & ESC_STR) {
2225 term.esc = ESC_START | ESC_STR_END;
2227 case '\a': /* backwards compatibility to xterm */
2232 if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2233 memmove(&strescseq.buf[strescseq.len], c, len);
2234 strescseq.len += len;
2237 * Here is a bug in terminals. If the user never sends
2238 * some code to stop the str or esc command, then st
2239 * will stop responding. But this is better than
2240 * silently failing with unknown characters. At least
2241 * then users will report back.
2243 * In the case users ever get fixed, here is the code:
2255 * Actions of control codes must be performed as soon they arrive
2256 * because they can be embedded inside a control sequence, and
2257 * they must not cause conflicts with sequences.
2265 tmoveto(term.c.x-1, term.c.y);
2268 tmoveto(0, term.c.y);
2273 /* go to first col if the mode is set */
2274 tnewline(IS_SET(MODE_CRLF));
2276 case '\a': /* BEL */
2277 if(!(xw.state & WIN_FOCUSED))
2280 case '\033': /* ESC */
2282 term.esc = ESC_START;
2284 case '\016': /* SO */
2285 case '\017': /* SI */
2287 * Different charsets are hard to handle. Applications
2288 * should use the right alt charset escapes for the
2289 * only reason they still exist: line drawing. The
2290 * rest is incompatible history st should not support.
2293 case '\032': /* SUB */
2294 case '\030': /* CAN */
2297 case '\005': /* ENQ (IGNORED) */
2298 case '\000': /* NUL (IGNORED) */
2299 case '\021': /* XON (IGNORED) */
2300 case '\023': /* XOFF (IGNORED) */
2301 case 0177: /* DEL (IGNORED) */
2304 } else if(term.esc & ESC_START) {
2305 if(term.esc & ESC_CSI) {
2306 csiescseq.buf[csiescseq.len++] = ascii;
2307 if(BETWEEN(ascii, 0x40, 0x7E)
2308 || csiescseq.len >= \
2309 sizeof(csiescseq.buf)-1) {
2314 } else if(term.esc & ESC_STR_END) {
2318 } else if(term.esc & ESC_ALTCHARSET) {
2320 case '0': /* Line drawing set */
2321 term.c.attr.mode |= ATTR_GFX;
2323 case 'B': /* USASCII */
2324 term.c.attr.mode &= ~ATTR_GFX;
2326 case 'A': /* UK (IGNORED) */
2327 case '<': /* multinational charset (IGNORED) */
2328 case '5': /* Finnish (IGNORED) */
2329 case 'C': /* Finnish (IGNORED) */
2330 case 'K': /* German (IGNORED) */
2333 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2336 } else if(term.esc & ESC_TEST) {
2337 if(ascii == '8') { /* DEC screen alignment test. */
2338 char E[UTF_SIZ] = "E";
2341 for(x = 0; x < term.col; ++x) {
2342 for(y = 0; y < term.row; ++y)
2343 tsetchar(E, &term.c.attr, x, y);
2350 term.esc |= ESC_CSI;
2353 term.esc |= ESC_TEST;
2355 case 'P': /* DCS -- Device Control String */
2356 case '_': /* APC -- Application Program Command */
2357 case '^': /* PM -- Privacy Message */
2358 case ']': /* OSC -- Operating System Command */
2359 case 'k': /* old title set compatibility */
2361 strescseq.type = ascii;
2362 term.esc |= ESC_STR;
2364 case '(': /* set primary charset G0 */
2365 term.esc |= ESC_ALTCHARSET;
2367 case ')': /* set secondary charset G1 (IGNORED) */
2368 case '*': /* set tertiary charset G2 (IGNORED) */
2369 case '+': /* set quaternary charset G3 (IGNORED) */
2372 case 'D': /* IND -- Linefeed */
2373 if(term.c.y == term.bot) {
2374 tscrollup(term.top, 1);
2376 tmoveto(term.c.x, term.c.y+1);
2380 case 'E': /* NEL -- Next line */
2381 tnewline(1); /* always go to first col */
2384 case 'H': /* HTS -- Horizontal tab stop */
2385 term.tabs[term.c.x] = 1;
2388 case 'M': /* RI -- Reverse index */
2389 if(term.c.y == term.top) {
2390 tscrolldown(term.top, 1);
2392 tmoveto(term.c.x, term.c.y-1);
2396 case 'Z': /* DECID -- Identify Terminal */
2397 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2400 case 'c': /* RIS -- Reset to inital state */
2405 case '=': /* DECPAM -- Application keypad */
2406 term.mode |= MODE_APPKEYPAD;
2409 case '>': /* DECPNM -- Normal keypad */
2410 term.mode &= ~MODE_APPKEYPAD;
2413 case '7': /* DECSC -- Save Cursor */
2414 tcursor(CURSOR_SAVE);
2417 case '8': /* DECRC -- Restore Cursor */
2418 tcursor(CURSOR_LOAD);
2421 case '\\': /* ST -- Stop */
2425 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2426 (uchar) ascii, isprint(ascii)? ascii:'.');
2431 * All characters which form part of a sequence are not
2437 * Display control codes only if we are in graphic mode
2439 if(control && !(term.c.attr.mode & ATTR_GFX))
2441 if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2443 if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2444 term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
2448 if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2449 memmove(&term.line[term.c.y][term.c.x+1],
2450 &term.line[term.c.y][term.c.x],
2451 (term.col - term.c.x - 1) * sizeof(Glyph));
2454 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2455 if(term.c.x+1 < term.col) {
2456 tmoveto(term.c.x+1, term.c.y);
2458 term.c.state |= CURSOR_WRAPNEXT;
2463 tresize(int col, int row) {
2465 int minrow = MIN(row, term.row);
2466 int mincol = MIN(col, term.col);
2467 int slide = term.c.y - row + 1;
2471 if(col < 1 || row < 1)
2474 /* free unneeded rows */
2478 * slide screen to keep cursor where we expect it -
2479 * tscrollup would work here, but we can optimize to
2480 * memmove because we're freeing the earlier lines
2482 for(/* i = 0 */; i < slide; i++) {
2486 memmove(term.line, term.line + slide, row * sizeof(Line));
2487 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2489 for(i += row; i < term.row; i++) {
2494 /* resize to new height */
2495 term.line = xrealloc(term.line, row * sizeof(Line));
2496 term.alt = xrealloc(term.alt, row * sizeof(Line));
2497 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2498 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2500 /* resize each row to new width, zero-pad if needed */
2501 for(i = 0; i < minrow; i++) {
2503 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2504 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2507 /* allocate any new rows */
2508 for(/* i == minrow */; i < row; i++) {
2510 term.line[i] = xcalloc(col, sizeof(Glyph));
2511 term.alt [i] = xcalloc(col, sizeof(Glyph));
2513 if(col > term.col) {
2514 bp = term.tabs + term.col;
2516 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2517 while(--bp > term.tabs && !*bp)
2519 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2522 /* update terminal size */
2525 /* reset scrolling region */
2526 tsetscroll(0, row-1);
2527 /* make use of the LIMIT in tmoveto */
2528 tmoveto(term.c.x, term.c.y);
2529 /* Clearing both screens */
2532 if(mincol < col && 0 < minrow) {
2533 tclearregion(mincol, 0, col - 1, minrow - 1);
2535 if(0 < col && minrow < row) {
2536 tclearregion(0, minrow, col - 1, row - 1);
2539 } while(orig != term.line);
2545 xresize(int col, int row) {
2546 xw.tw = MAX(1, col * xw.cw);
2547 xw.th = MAX(1, row * xw.ch);
2549 XFreePixmap(xw.dpy, xw.buf);
2550 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2551 DefaultDepth(xw.dpy, xw.scr));
2552 XftDrawChange(xw.draw, xw.buf);
2553 xclear(0, 0, xw.w, xw.h);
2556 static inline ushort
2557 sixd_to_16bit(int x) {
2558 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2564 XRenderColor color = { .alpha = 0xffff };
2566 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2567 for(i = 0; i < LEN(colorname); i++) {
2570 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2571 die("Could not allocate color '%s'\n", colorname[i]);
2575 /* load colors [16-255] ; same colors as xterm */
2576 for(i = 16, r = 0; r < 6; r++) {
2577 for(g = 0; g < 6; g++) {
2578 for(b = 0; b < 6; b++) {
2579 color.red = sixd_to_16bit(r);
2580 color.green = sixd_to_16bit(g);
2581 color.blue = sixd_to_16bit(b);
2582 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2583 die("Could not allocate color %d\n", i);
2590 for(r = 0; r < 24; r++, i++) {
2591 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2592 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2594 die("Could not allocate color %d\n", i);
2600 xsetcolorname(int x, const char *name) {
2601 XRenderColor color = { .alpha = 0xffff };
2603 if (x < 0 || x > LEN(colorname))
2606 if(16 <= x && x < 16 + 216) {
2607 int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2608 color.red = sixd_to_16bit(r);
2609 color.green = sixd_to_16bit(g);
2610 color.blue = sixd_to_16bit(b);
2611 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2612 return 0; /* something went wrong */
2615 } else if (16 + 216 <= x && x < 256) {
2616 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2617 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2618 return 0; /* something went wrong */
2622 name = colorname[x];
2625 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2632 xtermclear(int col1, int row1, int col2, int row2) {
2633 XftDrawRect(xw.draw,
2634 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2635 borderpx + col1 * xw.cw,
2636 borderpx + row1 * xw.ch,
2637 (col2-col1+1) * xw.cw,
2638 (row2-row1+1) * xw.ch);
2642 * Absolute coordinates.
2645 xclear(int x1, int y1, int x2, int y2) {
2646 XftDrawRect(xw.draw,
2647 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2648 x1, y1, x2-x1, y2-y1);
2653 XClassHint class = {opt_class ? opt_class : termname, termname};
2654 XWMHints wm = {.flags = InputHint, .input = 1};
2655 XSizeHints *sizeh = NULL;
2657 sizeh = XAllocSizeHints();
2658 if(xw.isfixed == False) {
2659 sizeh->flags = PSize | PResizeInc | PBaseSize;
2660 sizeh->height = xw.h;
2661 sizeh->width = xw.w;
2662 sizeh->height_inc = xw.ch;
2663 sizeh->width_inc = xw.cw;
2664 sizeh->base_height = 2 * borderpx;
2665 sizeh->base_width = 2 * borderpx;
2667 sizeh->flags = PMaxSize | PMinSize;
2668 sizeh->min_width = sizeh->max_width = xw.fw;
2669 sizeh->min_height = sizeh->max_height = xw.fh;
2672 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2677 xloadfont(Font *f, FcPattern *pattern) {
2681 match = FcFontMatch(NULL, pattern, &result);
2685 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2686 FcPatternDestroy(match);
2691 f->pattern = FcPatternDuplicate(pattern);
2693 f->ascent = f->match->ascent;
2694 f->descent = f->match->descent;
2696 f->rbearing = f->match->max_advance_width;
2698 f->height = f->ascent + f->descent;
2699 f->width = f->lbearing + f->rbearing;
2705 xloadfonts(char *fontstr, int fontsize) {
2710 if(fontstr[0] == '-') {
2711 pattern = XftXlfdParse(fontstr, False, False);
2713 pattern = FcNameParse((FcChar8 *)fontstr);
2717 die("st: can't open font %s\n", fontstr);
2720 FcPatternDel(pattern, FC_PIXEL_SIZE);
2721 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2722 usedfontsize = fontsize;
2724 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2725 if(result == FcResultMatch) {
2726 usedfontsize = (int)fontval;
2729 * Default font size is 12, if none given. This is to
2730 * have a known usedfontsize value.
2732 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2737 FcConfigSubstitute(0, pattern, FcMatchPattern);
2738 FcDefaultSubstitute(pattern);
2740 if(xloadfont(&dc.font, pattern))
2741 die("st: can't open font %s\n", fontstr);
2743 /* Setting character width and height. */
2744 xw.cw = dc.font.width;
2745 xw.ch = dc.font.height;
2747 FcPatternDel(pattern, FC_SLANT);
2748 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2749 if(xloadfont(&dc.ifont, pattern))
2750 die("st: can't open font %s\n", fontstr);
2752 FcPatternDel(pattern, FC_WEIGHT);
2753 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2754 if(xloadfont(&dc.ibfont, pattern))
2755 die("st: can't open font %s\n", fontstr);
2757 FcPatternDel(pattern, FC_SLANT);
2758 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2759 if(xloadfont(&dc.bfont, pattern))
2760 die("st: can't open font %s\n", fontstr);
2762 FcPatternDestroy(pattern);
2766 xloadfontset(Font *f) {
2769 if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
2775 xunloadfont(Font *f) {
2776 XftFontClose(xw.dpy, f->match);
2777 FcPatternDestroy(f->pattern);
2779 FcFontSetDestroy(f->set);
2783 xunloadfonts(void) {
2787 * Free the loaded fonts in the font cache. This is done backwards
2790 for(i = 0, ip = frccur; i < frclen; i++, ip--) {
2793 XftFontClose(xw.dpy, frc[ip].font);
2798 xunloadfont(&dc.font);
2799 xunloadfont(&dc.bfont);
2800 xunloadfont(&dc.ifont);
2801 xunloadfont(&dc.ibfont);
2805 xzoom(const Arg *arg) {
2807 xloadfonts(usedfont, usedfontsize + arg->i);
2819 if(!(xw.dpy = XOpenDisplay(NULL)))
2820 die("Can't open display\n");
2821 xw.scr = XDefaultScreen(xw.dpy);
2822 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2826 die("Could not init fontconfig.\n");
2828 usedfont = (opt_font == NULL)? font : opt_font;
2829 xloadfonts(usedfont, 0);
2832 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2835 /* adjust fixed window geometry */
2837 sw = DisplayWidth(xw.dpy, xw.scr);
2838 sh = DisplayHeight(xw.dpy, xw.scr);
2840 xw.fx = sw + xw.fx - xw.fw - 1;
2842 xw.fy = sh + xw.fy - xw.fh - 1;
2847 /* window - default size */
2848 xw.h = 2 * borderpx + term.row * xw.ch;
2849 xw.w = 2 * borderpx + term.col * xw.cw;
2855 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
2856 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
2857 xw.attrs.bit_gravity = NorthWestGravity;
2858 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
2859 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2860 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2861 xw.attrs.colormap = xw.cmap;
2863 parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2864 XRootWindow(xw.dpy, xw.scr);
2865 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2866 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2867 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
2868 | CWEventMask | CWColormap, &xw.attrs);
2870 memset(&gcvalues, 0, sizeof(gcvalues));
2871 gcvalues.graphics_exposures = False;
2872 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2874 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2875 DefaultDepth(xw.dpy, xw.scr));
2876 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
2877 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2879 /* Xft rendering context */
2880 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2883 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2884 XSetLocaleModifiers("@im=local");
2885 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2886 XSetLocaleModifiers("@im=");
2887 if((xw.xim = XOpenIM(xw.dpy,
2888 NULL, NULL, NULL)) == NULL) {
2889 die("XOpenIM failed. Could not open input"
2894 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2895 | XIMStatusNothing, XNClientWindow, xw.win,
2896 XNFocusWindow, xw.win, NULL);
2898 die("XCreateIC failed. Could not obtain input method.\n");
2900 /* white cursor, black outline */
2901 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2902 XDefineCursor(xw.dpy, xw.win, cursor);
2903 XRecolorCursor(xw.dpy, cursor,
2904 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2905 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2907 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2908 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2909 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2912 XMapWindow(xw.dpy, xw.win);
2918 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2919 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2920 width = charlen * xw.cw, xp, i;
2922 int u8fl, u8fblen, u8cblen, doesexist;
2925 Font *font = &dc.font;
2927 FcPattern *fcpattern, *fontpattern;
2928 FcFontSet *fcsets[] = { NULL };
2929 FcCharSet *fccharset;
2930 Colour *fg, *bg, *temp, revfg, revbg;
2931 XRenderColor colfg, colbg;
2934 frcflags = FRC_NORMAL;
2936 if(base.mode & ATTR_ITALIC) {
2937 if(base.fg == defaultfg)
2938 base.fg = defaultitalic;
2940 frcflags = FRC_ITALIC;
2941 } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
2942 if(base.fg == defaultfg)
2943 base.fg = defaultitalic;
2945 frcflags = FRC_ITALICBOLD;
2946 } else if(base.mode & ATTR_UNDERLINE) {
2947 if(base.fg == defaultfg)
2948 base.fg = defaultunderline;
2950 fg = &dc.col[base.fg];
2951 bg = &dc.col[base.bg];
2953 if(base.mode & ATTR_BOLD) {
2954 if(BETWEEN(base.fg, 0, 7)) {
2955 /* basic system colors */
2956 fg = &dc.col[base.fg + 8];
2957 } else if(BETWEEN(base.fg, 16, 195)) {
2959 fg = &dc.col[base.fg + 36];
2960 } else if(BETWEEN(base.fg, 232, 251)) {
2962 fg = &dc.col[base.fg + 4];
2965 * Those ranges will not be brightened:
2966 * 8 - 15 – bright system colors
2967 * 196 - 231 – highest 256 color cube
2968 * 252 - 255 – brightest colors in greyscale
2971 frcflags = FRC_BOLD;
2974 if(IS_SET(MODE_REVERSE)) {
2975 if(fg == &dc.col[defaultfg]) {
2976 fg = &dc.col[defaultbg];
2978 colfg.red = ~fg->color.red;
2979 colfg.green = ~fg->color.green;
2980 colfg.blue = ~fg->color.blue;
2981 colfg.alpha = fg->color.alpha;
2982 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2986 if(bg == &dc.col[defaultbg]) {
2987 bg = &dc.col[defaultfg];
2989 colbg.red = ~bg->color.red;
2990 colbg.green = ~bg->color.green;
2991 colbg.blue = ~bg->color.blue;
2992 colbg.alpha = bg->color.alpha;
2993 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2998 if(base.mode & ATTR_REVERSE) {
3004 if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3007 /* Intelligent cleaning up of the borders. */
3009 xclear(0, (y == 0)? 0 : winy, borderpx,
3010 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3012 if(x + charlen >= term.col) {
3013 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3014 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3017 xclear(winx, 0, winx + width, borderpx);
3019 xclear(winx, winy + xw.ch, winx + width, xw.h);
3021 /* Clean up the region we want to draw to. */
3022 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3024 /* Set the clip region because Xft is sometimes dirty. */
3029 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3031 for(xp = winx; bytelen > 0;) {
3033 * Search for the range in the to be printed string of glyphs
3034 * that are in the main font. Then print that range. If
3035 * some glyph is found that is not in the font, do the
3043 u8cblen = utf8decode(s, &u8char);
3047 doesexist = XftCharIndex(xw.dpy, font->match, u8char);
3048 if(!doesexist || bytelen <= 0) {
3057 XftDrawStringUtf8(xw.draw, fg,
3059 winy + font->ascent,
3062 xp += font->width * u8fl;
3075 /* Search the font cache. */
3076 for(i = 0; i < frclen; i++, frp--) {
3080 if(frc[frp].c == u8char
3081 && frc[frp].flags == frcflags) {
3086 /* Nothing was found. */
3090 fcsets[0] = font->set;
3093 * Nothing was found in the cache. Now use
3094 * some dozen of Fontconfig calls to get the
3095 * font for one single character.
3097 fcpattern = FcPatternDuplicate(font->pattern);
3098 fccharset = FcCharSetCreate();
3100 FcCharSetAddChar(fccharset, u8char);
3101 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3103 FcPatternAddBool(fcpattern, FC_SCALABLE,
3106 FcConfigSubstitute(0, fcpattern,
3108 FcDefaultSubstitute(fcpattern);
3110 fontpattern = FcFontSetMatch(0, fcsets,
3111 FcTrue, fcpattern, &fcres);
3114 * Overwrite or create the new cache entry.
3118 if(frccur >= LEN(frc))
3120 if(frclen > LEN(frc)) {
3122 XftFontClose(xw.dpy, frc[frccur].font);
3125 frc[frccur].font = XftFontOpenPattern(xw.dpy,
3127 frc[frccur].c = u8char;
3128 frc[frccur].flags = frcflags;
3130 FcPatternDestroy(fcpattern);
3131 FcCharSetDestroy(fccharset);
3136 XftDrawStringUtf8(xw.draw, fg, frc[frp].font,
3137 xp, winy + frc[frp].font->ascent,
3138 (FcChar8 *)u8c, u8cblen);
3144 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
3145 winy + font->ascent, (FcChar8 *)s, bytelen);
3148 if(base.mode & ATTR_UNDERLINE) {
3149 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
3153 /* Reset clip to none. */
3154 XftDrawSetClip(xw.draw, 0);
3159 static int oldx = 0, oldy = 0;
3161 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
3163 LIMIT(oldx, 0, term.col-1);
3164 LIMIT(oldy, 0, term.row-1);
3166 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
3168 /* remove the old cursor */
3169 sl = utf8size(term.line[oldy][oldx].c);
3170 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
3173 /* draw the new one */
3174 if(!(IS_SET(MODE_HIDE))) {
3175 if(xw.state & WIN_FOCUSED) {
3176 if(IS_SET(MODE_REVERSE)) {
3177 g.mode |= ATTR_REVERSE;
3183 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
3185 XftDrawRect(xw.draw, &dc.col[defaultcs],
3186 borderpx + term.c.x * xw.cw,
3187 borderpx + term.c.y * xw.ch,
3189 XftDrawRect(xw.draw, &dc.col[defaultcs],
3190 borderpx + term.c.x * xw.cw,
3191 borderpx + term.c.y * xw.ch,
3193 XftDrawRect(xw.draw, &dc.col[defaultcs],
3194 borderpx + (term.c.x + 1) * xw.cw - 1,
3195 borderpx + term.c.y * xw.ch,
3197 XftDrawRect(xw.draw, &dc.col[defaultcs],
3198 borderpx + term.c.x * xw.cw,
3199 borderpx + (term.c.y + 1) * xw.ch - 1,
3202 oldx = term.c.x, oldy = term.c.y;
3208 xsettitle(char *p) {
3211 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3213 XSetWMName(xw.dpy, xw.win, &prop);
3218 xsettitle(opt_title ? opt_title : "st");
3222 redraw(int timeout) {
3223 struct timespec tv = {0, timeout * 1000};
3229 nanosleep(&tv, NULL);
3230 XSync(xw.dpy, False); /* necessary for a good tput flash */
3236 drawregion(0, 0, term.col, term.row);
3237 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3239 XSetForeground(xw.dpy, dc.gc,
3240 dc.col[IS_SET(MODE_REVERSE)?
3241 defaultfg : defaultbg].pixel);
3245 drawregion(int x1, int y1, int x2, int y2) {
3246 int ic, ib, x, y, ox, sl;
3248 char buf[DRAW_BUF_SIZ];
3249 bool ena_sel = sel.ob.x != -1;
3251 if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3254 if(!(xw.state & WIN_VISIBLE))
3257 for(y = y1; y < y2; y++) {
3261 xtermclear(0, y, term.col, y);
3263 base = term.line[y][0];
3265 for(x = x1; x < x2; x++) {
3266 new = term.line[y][x];
3267 if(ena_sel && selected(x, y))
3268 new.mode ^= ATTR_REVERSE;
3269 if(ib > 0 && (ATTRCMP(base, new)
3270 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3271 xdraws(buf, base, ox, y, ic, ib);
3279 sl = utf8size(new.c);
3280 memcpy(buf+ib, new.c, sl);
3285 xdraws(buf, base, ox, y, ic, ib);
3291 expose(XEvent *ev) {
3292 XExposeEvent *e = &ev->xexpose;
3294 if(xw.state & WIN_REDRAW) {
3296 xw.state &= ~WIN_REDRAW;
3302 visibility(XEvent *ev) {
3303 XVisibilityEvent *e = &ev->xvisibility;
3305 if(e->state == VisibilityFullyObscured) {
3306 xw.state &= ~WIN_VISIBLE;
3307 } else if(!(xw.state & WIN_VISIBLE)) {
3308 /* need a full redraw for next Expose, not just a buf copy */
3309 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3315 xw.state &= ~WIN_VISIBLE;
3319 xsetpointermotion(int set) {
3320 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3321 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3325 xseturgency(int add) {
3326 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3328 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3329 XSetWMHints(xw.dpy, xw.win, h);
3335 XFocusChangeEvent *e = &ev->xfocus;
3337 if(e->mode == NotifyGrab)
3340 if(ev->type == FocusIn) {
3341 XSetICFocus(xw.xic);
3342 xw.state |= WIN_FOCUSED;
3344 if(IS_SET(MODE_FOCUS))
3345 ttywrite("\033[I", 3);
3347 XUnsetICFocus(xw.xic);
3348 xw.state &= ~WIN_FOCUSED;
3349 if(IS_SET(MODE_FOCUS))
3350 ttywrite("\033[O", 3);
3355 match(uint mask, uint state) {
3356 state &= ~ignoremod;
3358 if(mask == XK_NO_MOD && state)
3360 if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
3362 if(mask == XK_ANY_MOD)
3364 return state == mask;
3368 numlock(const Arg *dummy) {
3373 kmap(KeySym k, uint state) {
3377 /* Check for mapped keys out of X11 function keys. */
3378 for(i = 0; i < LEN(mappedkeys); i++) {
3379 if(mappedkeys[i] == k)
3382 if(i == LEN(mappedkeys)) {
3383 if((k & 0xFFFF) < 0xFD00)
3387 for(kp = key; kp < key + LEN(key); kp++) {
3391 if(!match(kp->mask, state))
3394 if(kp->appkey > 0) {
3395 if(!IS_SET(MODE_APPKEYPAD))
3397 if(term.numlock && kp->appkey == 2)
3399 } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
3403 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
3405 && !IS_SET(MODE_APPCURSOR))) {
3409 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
3410 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
3421 kpress(XEvent *ev) {
3422 XKeyEvent *e = &ev->xkey;
3424 char xstr[31], buf[32], *customkey, *cp = buf;
3430 if(IS_SET(MODE_KBDLOCK))
3433 len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
3434 e->state &= ~Mod2Mask;
3436 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3437 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3438 bp->func(&(bp->arg));
3443 /* 2. custom keys from config.h */
3444 if((customkey = kmap(ksym, e->state))) {
3445 len = strlen(customkey);
3446 memcpy(buf, customkey, len);
3447 /* 3. hardcoded (overrides X lookup) */
3452 if(len == 1 && e->state & Mod1Mask) {
3453 if(IS_SET(MODE_8BIT)) {
3456 ret = utf8encode(&c, cp);
3465 memcpy(cp, xstr, len);
3466 len = cp - buf + len;
3470 if(IS_SET(MODE_ECHO))
3476 cmessage(XEvent *e) {
3479 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3481 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3482 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3483 xw.state |= WIN_FOCUSED;
3485 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3486 xw.state &= ~WIN_FOCUSED;
3488 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3489 /* Send SIGHUP to shell */
3496 cresize(int width, int height) {
3504 col = (xw.w - 2 * borderpx) / xw.cw;
3505 row = (xw.h - 2 * borderpx) / xw.ch;
3514 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3517 cresize(e->xconfigure.width, e->xconfigure.height);
3523 int w = xw.w, h = xw.h;
3525 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3526 struct timeval drawtimeout, *tv = NULL, now, last, lastblink;
3528 /* Waiting for window mapping */
3530 XNextEvent(xw.dpy, &ev);
3531 if(ev.type == ConfigureNotify) {
3532 w = ev.xconfigure.width;
3533 h = ev.xconfigure.height;
3534 } else if(ev.type == MapNotify) {
3542 cresize(xw.fw, xw.fh);
3545 gettimeofday(&lastblink, NULL);
3546 gettimeofday(&last, NULL);
3548 for(xev = actionfps;;) {
3550 FD_SET(cmdfd, &rfd);
3553 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3556 die("select failed: %s\n", SERRNO);
3558 if(FD_ISSET(cmdfd, &rfd)) {
3561 blinkset = tattrset(ATTR_BLINK);
3562 if(!blinkset && term.mode & ATTR_BLINK)
3563 term.mode &= ~(MODE_BLINK);
3567 if(FD_ISSET(xfd, &rfd))
3570 gettimeofday(&now, NULL);
3571 drawtimeout.tv_sec = 0;
3572 drawtimeout.tv_usec = (1000/xfps) * 1000;
3576 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3577 tsetdirtattr(ATTR_BLINK);
3578 term.mode ^= MODE_BLINK;
3579 gettimeofday(&lastblink, NULL);
3582 if(TIMEDIFF(now, last) \
3583 > (xev? (1000/xfps) : (1000/actionfps))) {
3589 while(XPending(xw.dpy)) {
3590 XNextEvent(xw.dpy, &ev);
3591 if(XFilterEvent(&ev, None))
3593 if(handler[ev.type])
3594 (handler[ev.type])(&ev);
3600 if(xev && !FD_ISSET(xfd, &rfd))
3602 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3604 if(TIMEDIFF(now, lastblink) \
3606 drawtimeout.tv_usec = 1;
3608 drawtimeout.tv_usec = (1000 * \
3623 die("%s " VERSION " (c) 2010-2013 st engineers\n" \
3624 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
3625 " [-t title] [-w windowid] [-e command ...]\n", argv0);
3629 main(int argc, char *argv[]) {
3634 xw.fw = xw.fh = xw.fx = xw.fy = 0;
3639 allowaltscreen = false;
3642 opt_class = EARGF(usage());
3645 /* eat all remaining arguments */
3648 if(argv[1] != NULL && opt_title == NULL) {
3649 titles = strdup(argv[1]);
3650 opt_title = basename(titles);
3655 opt_font = EARGF(usage());
3658 bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
3663 if(bitm & WidthValue)
3665 if(bitm & HeightValue)
3667 if(bitm & XNegative && xw.fx == 0)
3669 if(bitm & XNegative && xw.fy == 0)
3672 if(xw.fh != 0 && xw.fw != 0)
3676 opt_io = EARGF(usage());
3679 opt_title = EARGF(usage());
3682 opt_embed = EARGF(usage());
3690 setlocale(LC_CTYPE, "");
3691 XSetLocaleModifiers("");