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>
38 #define Draw XftDraw *
39 #define Colour XftColor
40 #define Colourmap Colormap
41 #define Rectangle XRectangle
45 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
47 #elif defined(__FreeBSD__) || defined(__DragonFly__)
53 #define XEMBED_FOCUS_IN 4
54 #define XEMBED_FOCUS_OUT 5
58 #define ESC_BUF_SIZ (128*UTF_SIZ)
59 #define ESC_ARG_SIZ 16
60 #define STR_BUF_SIZ ESC_BUF_SIZ
61 #define STR_ARG_SIZ ESC_ARG_SIZ
62 #define DRAW_BUF_SIZ 20*1024
63 #define XK_ANY_MOD UINT_MAX
65 #define XK_SWITCH_MOD (1<<13)
67 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
70 #define SERRNO strerror(errno)
71 #define MIN(a, b) ((a) < (b) ? (a) : (b))
72 #define MAX(a, b) ((a) < (b) ? (b) : (a))
73 #define LEN(a) (sizeof(a) / sizeof(a[0]))
74 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
75 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
76 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
77 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
78 #define IS_SET(flag) ((term.mode & (flag)) != 0)
79 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
80 #define CEIL(x) (((x) != (int) (x)) ? (x) + 1 : (x))
82 #define TRUECOLOR(r,g,b) (1 << 24 | (r) << 16 | (g) << 8 | (b))
83 #define IS_TRUECOL(x) (1 << 24 & (x))
84 #define TRUERED(x) (((x) & 0xff0000) >> 8)
85 #define TRUEGREEN(x) (((x) & 0xff00))
86 #define TRUEBLUE(x) (((x) & 0xff) << 8)
89 #define VT102ID "\033[?6c"
91 enum glyph_attribute {
104 enum cursor_movement {
122 MODE_MOUSEMOTION = 64,
127 MODE_APPCURSOR = 2048,
128 MODE_MOUSESGR = 4096,
133 MODE_MOUSEX10 = 131072,
134 MODE_MOUSEMANY = 262144,
135 MODE_MOUSE = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
142 ESC_STR = 4, /* DSC, OSC, PM, APC */
144 ESC_STR_END = 16, /* a final string was encountered */
145 ESC_TEST = 32, /* Enter in test mode */
154 enum selection_type {
159 enum selection_snap {
164 typedef unsigned char uchar;
165 typedef unsigned int uint;
166 typedef unsigned long ulong;
167 typedef unsigned short ushort;
170 char c[UTF_SIZ]; /* character code */
171 ushort mode; /* attribute flags */
172 ulong fg; /* foreground */
173 ulong bg; /* background */
179 Glyph attr; /* current char attributes */
185 /* CSI Escape sequence structs */
186 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
188 char buf[ESC_BUF_SIZ]; /* raw string */
189 int len; /* raw string length */
191 int arg[ESC_ARG_SIZ];
192 int narg; /* nb of args */
196 /* STR Escape sequence structs */
197 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
199 char type; /* ESC type ... */
200 char buf[STR_BUF_SIZ]; /* raw string */
201 int len; /* raw string length */
202 char *args[STR_ARG_SIZ];
203 int narg; /* nb of args */
206 /* Internal representation of the screen */
208 int row; /* nb row */
209 int col; /* nb col */
210 Line *line; /* screen */
211 Line *alt; /* alternate screen */
212 bool *dirty; /* dirtyness of lines */
213 TCursor c; /* cursor */
214 int top; /* top scroll limit */
215 int bot; /* bottom scroll limit */
216 int mode; /* terminal mode flags */
217 int esc; /* escape state flags */
218 bool numlock; /* lock numbers in keyboard */
222 /* Purely graphic info */
228 Atom xembed, wmdeletewin;
233 XSetWindowAttributes attrs;
235 bool isfixed; /* is fixed geometry? */
236 int fx, fy, fw, fh; /* fixed geometry */
237 int tw, th; /* tty width and height */
238 int w, h; /* window width and height */
239 int ch; /* char height */
240 int cw; /* char width */
241 char state; /* focus, redraw, visible */
254 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
255 signed char appkey; /* application keypad */
256 signed char appcursor; /* application cursor */
257 signed char crlf; /* crlf mode */
265 * Selection variables:
266 * nb – normalized coordinates of the beginning of the selection
267 * ne – normalized coordinates of the end of the selection
268 * ob – original coordinates of the beginning of the selection
269 * oe – original coordinates of the end of the selection
278 struct timeval tclick1;
279 struct timeval tclick2;
292 void (*func)(const Arg *);
296 /* function definitions used in config.h */
297 static void clippaste(const Arg *);
298 static void numlock(const Arg *);
299 static void selpaste(const Arg *);
300 static void xzoom(const Arg *);
302 /* Config.h for applying patches and the configuration. */
318 /* Drawing Context */
320 Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
321 Font font, bfont, ifont, ibfont;
325 static void die(const char *, ...);
326 static void draw(void);
327 static void redraw(int);
328 static void drawregion(int, int, int, int);
329 static void execsh(void);
330 static void sigchld(int);
331 static void run(void);
333 static void csidump(void);
334 static void csihandle(void);
335 static void csiparse(void);
336 static void csireset(void);
337 static void strdump(void);
338 static void strhandle(void);
339 static void strparse(void);
340 static void strreset(void);
342 static int tattrset(int);
343 static void tclearregion(int, int, int, int);
344 static void tcursor(int);
345 static void tdeletechar(int);
346 static void tdeleteline(int);
347 static void tinsertblank(int);
348 static void tinsertblankline(int);
349 static void tmoveto(int, int);
350 static void tmoveato(int x, int y);
351 static void tnew(int, int);
352 static void tnewline(int);
353 static void tputtab(bool);
354 static void tputc(char *, int);
355 static void treset(void);
356 static int tresize(int, int);
357 static void tscrollup(int, int);
358 static void tscrolldown(int, int);
359 static void tsetattr(int*, int);
360 static void tsetchar(char *, Glyph *, int, int);
361 static void tsetscroll(int, int);
362 static void tswapscreen(void);
363 static void tsetdirt(int, int);
364 static void tsetdirtattr(int);
365 static void tsetmode(bool, bool, int *, int);
366 static void tfulldirt(void);
367 static void techo(char *, int);
368 static long tdefcolor(int *, int *, int);
369 static inline bool match(uint, uint);
370 static void ttynew(void);
371 static void ttyread(void);
372 static void ttyresize(void);
373 static void ttywrite(const char *, size_t);
375 static void xdraws(char *, Glyph, int, int, int, int);
376 static void xhints(void);
377 static void xclear(int, int, int, int);
378 static void xdrawcursor(void);
379 static void xinit(void);
380 static void xloadcols(void);
381 static int xsetcolorname(int, const char *);
382 static int xloadfont(Font *, FcPattern *);
383 static void xloadfonts(char *, int);
384 static int xloadfontset(Font *);
385 static void xsettitle(char *);
386 static void xresettitle(void);
387 static void xsetpointermotion(int);
388 static void xseturgency(int);
389 static void xsetsel(char*);
390 static void xtermclear(int, int, int, int);
391 static void xunloadfont(Font *f);
392 static void xunloadfonts(void);
393 static void xresize(int, int);
395 static void expose(XEvent *);
396 static void visibility(XEvent *);
397 static void unmap(XEvent *);
398 static char *kmap(KeySym, uint);
399 static void kpress(XEvent *);
400 static void cmessage(XEvent *);
401 static void cresize(int, int);
402 static void resize(XEvent *);
403 static void focus(XEvent *);
404 static void brelease(XEvent *);
405 static void bpress(XEvent *);
406 static void bmotion(XEvent *);
407 static void selnotify(XEvent *);
408 static void selclear(XEvent *);
409 static void selrequest(XEvent *);
411 static void selinit(void);
412 static void selsort(void);
413 static inline bool selected(int, int);
414 static void selcopy(void);
415 static void selscroll(int, int);
416 static void selsnap(int, int *, int *, int);
418 static int utf8decode(char *, long *);
419 static int utf8encode(long *, char *);
420 static int utf8size(char *);
421 static int isfullutf8(char *, int);
423 static ssize_t xwrite(int, char *, size_t);
424 static void *xmalloc(size_t);
425 static void *xrealloc(void *, size_t);
427 static void (*handler[LASTEvent])(XEvent *) = {
429 [ClientMessage] = cmessage,
430 [ConfigureNotify] = resize,
431 [VisibilityNotify] = visibility,
432 [UnmapNotify] = unmap,
436 [MotionNotify] = bmotion,
437 [ButtonPress] = bpress,
438 [ButtonRelease] = brelease,
439 [SelectionClear] = selclear,
440 [SelectionNotify] = selnotify,
441 [SelectionRequest] = selrequest,
448 static CSIEscape csiescseq;
449 static STREscape strescseq;
452 static Selection sel;
453 static int iofd = -1;
454 static char **opt_cmd = NULL;
455 static char *opt_io = NULL;
456 static char *opt_title = NULL;
457 static char *opt_embed = NULL;
458 static char *opt_class = NULL;
459 static char *opt_font = NULL;
460 static int oldbutton = 3; /* button event on startup: 3 = release */
462 static char *usedfont = NULL;
463 static int usedfontsize = 0;
465 /* Font Ring Cache */
478 /* Fontcache is an array now. A new font will be appended to the array. */
479 static Fontcache frc[16];
480 static int frclen = 0;
483 xwrite(int fd, char *s, size_t len) {
487 ssize_t r = write(fd, s, len);
497 xmalloc(size_t len) {
498 void *p = malloc(len);
501 die("Out of memory\n");
507 xrealloc(void *p, size_t len) {
508 if((p = realloc(p, len)) == NULL)
509 die("Out of memory\n");
515 utf8decode(char *s, long *u) {
521 if(~c & 0x80) { /* 0xxxxxxx */
524 } else if((c & 0xE0) == 0xC0) { /* 110xxxxx */
527 } else if((c & 0xF0) == 0xE0) { /* 1110xxxx */
530 } else if((c & 0xF8) == 0xF0) { /* 11110xxx */
537 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
539 if((c & 0xC0) != 0x80) /* 10xxxxxx */
545 if((n == 1 && *u < 0x80) ||
546 (n == 2 && *u < 0x800) ||
547 (n == 3 && *u < 0x10000) ||
548 (*u >= 0xD800 && *u <= 0xDFFF)) {
560 utf8encode(long *u, char *s) {
568 *sp = uc; /* 0xxxxxxx */
570 } else if(*u < 0x800) {
571 *sp = (uc >> 6) | 0xC0; /* 110xxxxx */
573 } else if(uc < 0x10000) {
574 *sp = (uc >> 12) | 0xE0; /* 1110xxxx */
576 } else if(uc <= 0x10FFFF) {
577 *sp = (uc >> 18) | 0xF0; /* 11110xxx */
583 for(i=n,++sp; i>0; --i,++sp)
584 *sp = ((uc >> 6*(i-1)) & 0x3F) | 0x80; /* 10xxxxxx */
596 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
597 UTF-8 otherwise return 0 */
599 isfullutf8(char *s, int b) {
607 } else if((*c1 & 0xE0) == 0xC0 && b == 1) {
609 } else if((*c1 & 0xF0) == 0xE0 &&
611 ((b == 2) && (*c2 & 0xC0) == 0x80))) {
613 } else if((*c1 & 0xF8) == 0xF0 &&
615 ((b == 2) && (*c2 & 0xC0) == 0x80) ||
616 ((b == 3) && (*c2 & 0xC0) == 0x80 && (*c3 & 0xC0) == 0x80))) {
629 } else if((c & 0xE0) == 0xC0) {
631 } else if((c & 0xF0) == 0xE0) {
640 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
641 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
645 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
646 if(sel.xtarget == None)
647 sel.xtarget = XA_STRING;
655 return LIMIT(x, 0, term.col-1);
663 return LIMIT(y, 0, term.row-1);
668 if(sel.ob.y == sel.oe.y) {
669 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
670 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
672 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
673 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
675 sel.nb.y = MIN(sel.ob.y, sel.oe.y);
676 sel.ne.y = MAX(sel.ob.y, sel.oe.y);
680 selected(int x, int y) {
681 if(sel.ne.y == y && sel.nb.y == y)
682 return BETWEEN(x, sel.nb.x, sel.ne.x);
684 if(sel.type == SEL_RECTANGULAR) {
685 return ((sel.nb.y <= y && y <= sel.ne.y)
686 && (sel.nb.x <= x && x <= sel.ne.x));
689 return ((sel.nb.y < y && y < sel.ne.y)
690 || (y == sel.ne.y && x <= sel.ne.x))
691 || (y == sel.nb.y && x >= sel.nb.x
692 && (x <= sel.ne.x || sel.nb.y != sel.ne.y));
696 selsnap(int mode, int *x, int *y, int direction) {
702 * Snap around if the word wraps around at the end or
703 * beginning of a line.
706 if(direction < 0 && *x <= 0) {
707 if(*y > 0 && term.line[*y - 1][term.col-1].mode
715 if(direction > 0 && *x >= term.col-1) {
716 if(*y < term.row-1 && term.line[*y][*x].mode
725 if(term.line[*y][*x+direction].mode & ATTR_WDUMMY) {
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) {
943 if(!selected(x, y) || (gp->mode & ATTR_WDUMMY))
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 term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
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];
1544 if(term.line[y][x].mode & ATTR_WIDE) {
1545 if(x+1 < term.col) {
1546 term.line[y][x+1].c[0] = ' ';
1547 term.line[y][x+1].mode &= ~ATTR_WDUMMY;
1549 } else if(term.line[y][x].mode & ATTR_WDUMMY) {
1550 term.line[y][x-1].c[0] = ' ';
1551 term.line[y][x-1].mode &= ~ATTR_WIDE;
1555 term.line[y][x] = *attr;
1556 memcpy(term.line[y][x].c, c, UTF_SIZ);
1560 tclearregion(int x1, int y1, int x2, int y2) {
1564 temp = x1, x1 = x2, x2 = temp;
1566 temp = y1, y1 = y2, y2 = temp;
1568 LIMIT(x1, 0, term.col-1);
1569 LIMIT(x2, 0, term.col-1);
1570 LIMIT(y1, 0, term.row-1);
1571 LIMIT(y2, 0, term.row-1);
1573 for(y = y1; y <= y2; y++) {
1575 for(x = x1; x <= x2; x++) {
1578 term.line[y][x] = term.c.attr;
1579 memcpy(term.line[y][x].c, " ", 2);
1585 tdeletechar(int n) {
1586 int src = term.c.x + n;
1588 int size = term.col - src;
1590 term.dirty[term.c.y] = 1;
1592 if(src >= term.col) {
1593 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1597 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1598 size * sizeof(Glyph));
1599 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1603 tinsertblank(int n) {
1606 int size = term.col - dst;
1608 term.dirty[term.c.y] = 1;
1610 if(dst >= term.col) {
1611 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1615 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1616 size * sizeof(Glyph));
1617 tclearregion(src, term.c.y, dst - 1, term.c.y);
1621 tinsertblankline(int n) {
1622 if(term.c.y < term.top || term.c.y > term.bot)
1625 tscrolldown(term.c.y, n);
1629 tdeleteline(int n) {
1630 if(term.c.y < term.top || term.c.y > term.bot)
1633 tscrollup(term.c.y, n);
1637 tdefcolor(int *attr, int *npar, int l) {
1641 switch (attr[*npar + 1]) {
1642 case 2: /* direct colour in RGB space */
1643 if (*npar + 4 >= l) {
1645 "erresc(38): Incorrect number of parameters (%d)\n",
1649 r = attr[*npar + 2];
1650 g = attr[*npar + 3];
1651 b = attr[*npar + 4];
1653 if(!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1654 fprintf(stderr, "erresc: bad rgb color (%d,%d,%d)\n",
1657 idx = TRUECOLOR(r, g, b);
1659 case 5: /* indexed colour */
1660 if (*npar + 2 >= l) {
1662 "erresc(38): Incorrect number of parameters (%d)\n",
1667 if(!BETWEEN(attr[*npar], 0, 255))
1668 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
1672 case 0: /* implemented defined (only foreground) */
1673 case 1: /* transparent */
1674 case 3: /* direct colour in CMY space */
1675 case 4: /* direct colour in CMYK space */
1678 "erresc(38): gfx attr %d unknown\n", attr[*npar]);
1685 tsetattr(int *attr, int l) {
1689 for(i = 0; i < l; i++) {
1692 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE \
1693 | ATTR_BOLD | ATTR_ITALIC \
1695 term.c.attr.fg = defaultfg;
1696 term.c.attr.bg = defaultbg;
1699 term.c.attr.mode |= ATTR_BOLD;
1702 term.c.attr.mode |= ATTR_ITALIC;
1705 term.c.attr.mode |= ATTR_UNDERLINE;
1707 case 5: /* slow blink */
1708 case 6: /* rapid blink */
1709 term.c.attr.mode |= ATTR_BLINK;
1712 term.c.attr.mode |= ATTR_REVERSE;
1716 term.c.attr.mode &= ~ATTR_BOLD;
1719 term.c.attr.mode &= ~ATTR_ITALIC;
1722 term.c.attr.mode &= ~ATTR_UNDERLINE;
1726 term.c.attr.mode &= ~ATTR_BLINK;
1729 term.c.attr.mode &= ~ATTR_REVERSE;
1732 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1733 term.c.attr.fg = idx;
1736 term.c.attr.fg = defaultfg;
1739 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1740 term.c.attr.bg = idx;
1743 term.c.attr.bg = defaultbg;
1746 if(BETWEEN(attr[i], 30, 37)) {
1747 term.c.attr.fg = attr[i] - 30;
1748 } else if(BETWEEN(attr[i], 40, 47)) {
1749 term.c.attr.bg = attr[i] - 40;
1750 } else if(BETWEEN(attr[i], 90, 97)) {
1751 term.c.attr.fg = attr[i] - 90 + 8;
1752 } else if(BETWEEN(attr[i], 100, 107)) {
1753 term.c.attr.bg = attr[i] - 100 + 8;
1756 "erresc(default): gfx attr %d unknown\n",
1757 attr[i]), csidump();
1765 tsetscroll(int t, int b) {
1768 LIMIT(t, 0, term.row-1);
1769 LIMIT(b, 0, term.row-1);
1779 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1782 tsetmode(bool priv, bool set, int *args, int narg) {
1786 for(lim = args + narg; args < lim; ++args) {
1790 case 1: /* DECCKM -- Cursor key */
1791 MODBIT(term.mode, set, MODE_APPCURSOR);
1793 case 5: /* DECSCNM -- Reverse video */
1795 MODBIT(term.mode, set, MODE_REVERSE);
1796 if(mode != term.mode)
1797 redraw(REDRAW_TIMEOUT);
1799 case 6: /* DECOM -- Origin */
1800 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1803 case 7: /* DECAWM -- Auto wrap */
1804 MODBIT(term.mode, set, MODE_WRAP);
1806 case 0: /* Error (IGNORED) */
1807 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1808 case 3: /* DECCOLM -- Column (IGNORED) */
1809 case 4: /* DECSCLM -- Scroll (IGNORED) */
1810 case 8: /* DECARM -- Auto repeat (IGNORED) */
1811 case 18: /* DECPFF -- Printer feed (IGNORED) */
1812 case 19: /* DECPEX -- Printer extent (IGNORED) */
1813 case 42: /* DECNRCM -- National characters (IGNORED) */
1814 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1816 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1817 MODBIT(term.mode, !set, MODE_HIDE);
1819 case 9: /* X10 mouse compatibility mode */
1820 xsetpointermotion(0);
1821 MODBIT(term.mode, 0, MODE_MOUSE);
1822 MODBIT(term.mode, set, MODE_MOUSEX10);
1824 case 1000: /* 1000: report button press */
1825 xsetpointermotion(0);
1826 MODBIT(term.mode, 0, MODE_MOUSE);
1827 MODBIT(term.mode, set, MODE_MOUSEBTN);
1829 case 1002: /* 1002: report motion on button press */
1830 xsetpointermotion(0);
1831 MODBIT(term.mode, 0, MODE_MOUSE);
1832 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1834 case 1003: /* 1003: enable all mouse motions */
1835 xsetpointermotion(set);
1836 MODBIT(term.mode, 0, MODE_MOUSE);
1837 MODBIT(term.mode, set, MODE_MOUSEMANY);
1839 case 1004: /* 1004: send focus events to tty */
1840 MODBIT(term.mode, set, MODE_FOCUS);
1842 case 1006: /* 1006: extended reporting mode */
1843 MODBIT(term.mode, set, MODE_MOUSESGR);
1846 MODBIT(term.mode, set, MODE_8BIT);
1848 case 1049: /* = 1047 and 1048 */
1851 if (!allowaltscreen)
1854 alt = IS_SET(MODE_ALTSCREEN);
1856 tclearregion(0, 0, term.col-1,
1859 if(set ^ alt) /* set is always 1 or 0 */
1865 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1867 /* Not implemented mouse modes. See comments there. */
1868 case 1001: /* mouse highlight mode; can hang the
1869 terminal by design when implemented. */
1870 case 1005: /* UTF-8 mouse mode; will confuse
1871 applications not supporting UTF-8
1873 case 1015: /* urxvt mangled mouse mode; incompatible
1874 and can be mistaken for other control
1878 "erresc: unknown private set/reset mode %d\n",
1884 case 0: /* Error (IGNORED) */
1886 case 2: /* KAM -- keyboard action */
1887 MODBIT(term.mode, set, MODE_KBDLOCK);
1889 case 4: /* IRM -- Insertion-replacement */
1890 MODBIT(term.mode, set, MODE_INSERT);
1892 case 12: /* SRM -- Send/Receive */
1893 MODBIT(term.mode, !set, MODE_ECHO);
1895 case 20: /* LNM -- Linefeed/new line */
1896 MODBIT(term.mode, set, MODE_CRLF);
1900 "erresc: unknown set/reset mode %d\n",
1910 switch(csiescseq.mode) {
1913 fprintf(stderr, "erresc: unknown csi ");
1917 case '@': /* ICH -- Insert <n> blank char */
1918 DEFAULT(csiescseq.arg[0], 1);
1919 tinsertblank(csiescseq.arg[0]);
1921 case 'A': /* CUU -- Cursor <n> Up */
1922 DEFAULT(csiescseq.arg[0], 1);
1923 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1925 case 'B': /* CUD -- Cursor <n> Down */
1926 case 'e': /* VPR --Cursor <n> Down */
1927 DEFAULT(csiescseq.arg[0], 1);
1928 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1930 case 'c': /* DA -- Device Attributes */
1931 if(csiescseq.arg[0] == 0)
1932 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1934 case 'C': /* CUF -- Cursor <n> Forward */
1935 case 'a': /* HPR -- Cursor <n> Forward */
1936 DEFAULT(csiescseq.arg[0], 1);
1937 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1939 case 'D': /* CUB -- Cursor <n> Backward */
1940 DEFAULT(csiescseq.arg[0], 1);
1941 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1943 case 'E': /* CNL -- Cursor <n> Down and first col */
1944 DEFAULT(csiescseq.arg[0], 1);
1945 tmoveto(0, term.c.y+csiescseq.arg[0]);
1947 case 'F': /* CPL -- Cursor <n> Up and first col */
1948 DEFAULT(csiescseq.arg[0], 1);
1949 tmoveto(0, term.c.y-csiescseq.arg[0]);
1951 case 'g': /* TBC -- Tabulation clear */
1952 switch(csiescseq.arg[0]) {
1953 case 0: /* clear current tab stop */
1954 term.tabs[term.c.x] = 0;
1956 case 3: /* clear all the tabs */
1957 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1963 case 'G': /* CHA -- Move to <col> */
1965 DEFAULT(csiescseq.arg[0], 1);
1966 tmoveto(csiescseq.arg[0]-1, term.c.y);
1968 case 'H': /* CUP -- Move to <row> <col> */
1970 DEFAULT(csiescseq.arg[0], 1);
1971 DEFAULT(csiescseq.arg[1], 1);
1972 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1974 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1975 DEFAULT(csiescseq.arg[0], 1);
1976 while(csiescseq.arg[0]--)
1979 case 'J': /* ED -- Clear screen */
1981 switch(csiescseq.arg[0]) {
1983 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1984 if(term.c.y < term.row-1) {
1985 tclearregion(0, term.c.y+1, term.col-1,
1991 tclearregion(0, 0, term.col-1, term.c.y-1);
1992 tclearregion(0, term.c.y, term.c.x, term.c.y);
1995 tclearregion(0, 0, term.col-1, term.row-1);
2001 case 'K': /* EL -- Clear line */
2002 switch(csiescseq.arg[0]) {
2004 tclearregion(term.c.x, term.c.y, term.col-1,
2008 tclearregion(0, term.c.y, term.c.x, term.c.y);
2011 tclearregion(0, term.c.y, term.col-1, term.c.y);
2015 case 'S': /* SU -- Scroll <n> line up */
2016 DEFAULT(csiescseq.arg[0], 1);
2017 tscrollup(term.top, csiescseq.arg[0]);
2019 case 'T': /* SD -- Scroll <n> line down */
2020 DEFAULT(csiescseq.arg[0], 1);
2021 tscrolldown(term.top, csiescseq.arg[0]);
2023 case 'L': /* IL -- Insert <n> blank lines */
2024 DEFAULT(csiescseq.arg[0], 1);
2025 tinsertblankline(csiescseq.arg[0]);
2027 case 'l': /* RM -- Reset Mode */
2028 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2030 case 'M': /* DL -- Delete <n> lines */
2031 DEFAULT(csiescseq.arg[0], 1);
2032 tdeleteline(csiescseq.arg[0]);
2034 case 'X': /* ECH -- Erase <n> char */
2035 DEFAULT(csiescseq.arg[0], 1);
2036 tclearregion(term.c.x, term.c.y,
2037 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2039 case 'P': /* DCH -- Delete <n> char */
2040 DEFAULT(csiescseq.arg[0], 1);
2041 tdeletechar(csiescseq.arg[0]);
2043 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2044 DEFAULT(csiescseq.arg[0], 1);
2045 while(csiescseq.arg[0]--)
2048 case 'd': /* VPA -- Move to <row> */
2049 DEFAULT(csiescseq.arg[0], 1);
2050 tmoveato(term.c.x, csiescseq.arg[0]-1);
2052 case 'h': /* SM -- Set terminal mode */
2053 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2055 case 'm': /* SGR -- Terminal attribute (color) */
2056 tsetattr(csiescseq.arg, csiescseq.narg);
2058 case 'r': /* DECSTBM -- Set Scrolling Region */
2059 if(csiescseq.priv) {
2062 DEFAULT(csiescseq.arg[0], 1);
2063 DEFAULT(csiescseq.arg[1], term.row);
2064 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2068 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2069 tcursor(CURSOR_SAVE);
2071 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2072 tcursor(CURSOR_LOAD);
2083 for(i = 0; i < csiescseq.len; i++) {
2084 c = csiescseq.buf[i] & 0xff;
2087 } else if(c == '\n') {
2089 } else if(c == '\r') {
2091 } else if(c == 0x1b) {
2094 printf("(%02x)", c);
2102 memset(&csiescseq, 0, sizeof(csiescseq));
2111 narg = strescseq.narg;
2113 switch(strescseq.type) {
2114 case ']': /* OSC -- Operating System Command */
2115 switch(i = atoi(strescseq.args[0])) {
2120 xsettitle(strescseq.args[1]);
2122 case 4: /* color set */
2125 p = strescseq.args[2];
2127 case 104: /* color reset, here p = NULL */
2128 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2129 if (!xsetcolorname(j, p)) {
2130 fprintf(stderr, "erresc: invalid color %s\n", p);
2133 * TODO if defaultbg color is changed, borders
2140 fprintf(stderr, "erresc: unknown str ");
2145 case 'k': /* old title set compatibility */
2146 xsettitle(strescseq.args[0]);
2148 case 'P': /* DSC -- Device Control String */
2149 case '_': /* APC -- Application Program Command */
2150 case '^': /* PM -- Privacy Message */
2152 fprintf(stderr, "erresc: unknown str ");
2161 char *p = strescseq.buf;
2164 strescseq.buf[strescseq.len] = '\0';
2165 while(p && strescseq.narg < STR_ARG_SIZ)
2166 strescseq.args[strescseq.narg++] = strsep(&p, ";");
2174 printf("ESC%c", strescseq.type);
2175 for(i = 0; i < strescseq.len; i++) {
2176 c = strescseq.buf[i] & 0xff;
2179 } else if(isprint(c)) {
2181 } else if(c == '\n') {
2183 } else if(c == '\r') {
2185 } else if(c == 0x1b) {
2188 printf("(%02x)", c);
2196 memset(&strescseq, 0, sizeof(strescseq));
2200 tputtab(bool forward) {
2206 for(++x; x < term.col && !term.tabs[x]; ++x)
2211 for(--x; x > 0 && !term.tabs[x]; --x)
2214 tmoveto(x, term.c.y);
2218 techo(char *buf, int len) {
2219 for(; len > 0; buf++, len--) {
2222 if(c == '\033') { /* escape */
2225 } else if(c < '\x20') { /* control code */
2226 if(c != '\n' && c != '\r' && c != '\t') {
2240 tputc(char *c, int len) {
2242 bool control = ascii < '\x20' || ascii == 0177;
2249 utf8decode(c, &u8char);
2250 width = wcwidth(u8char);
2254 if(xwrite(iofd, c, len) < 0) {
2255 fprintf(stderr, "Error writing in %s:%s\n",
2256 opt_io, strerror(errno));
2263 * STR sequences must be checked before anything else
2264 * because it can use some control codes as part of the sequence.
2266 if(term.esc & ESC_STR) {
2269 term.esc = ESC_START | ESC_STR_END;
2271 case '\a': /* backwards compatibility to xterm */
2276 if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2277 memmove(&strescseq.buf[strescseq.len], c, len);
2278 strescseq.len += len;
2281 * Here is a bug in terminals. If the user never sends
2282 * some code to stop the str or esc command, then st
2283 * will stop responding. But this is better than
2284 * silently failing with unknown characters. At least
2285 * then users will report back.
2287 * In the case users ever get fixed, here is the code:
2299 * Actions of control codes must be performed as soon they arrive
2300 * because they can be embedded inside a control sequence, and
2301 * they must not cause conflicts with sequences.
2309 tmoveto(term.c.x-1, term.c.y);
2312 tmoveto(0, term.c.y);
2317 /* go to first col if the mode is set */
2318 tnewline(IS_SET(MODE_CRLF));
2320 case '\a': /* BEL */
2321 if(!(xw.state & WIN_FOCUSED))
2324 case '\033': /* ESC */
2326 term.esc = ESC_START;
2328 case '\016': /* SO */
2329 case '\017': /* SI */
2331 * Different charsets are hard to handle. Applications
2332 * should use the right alt charset escapes for the
2333 * only reason they still exist: line drawing. The
2334 * rest is incompatible history st should not support.
2337 case '\032': /* SUB */
2338 case '\030': /* CAN */
2341 case '\005': /* ENQ (IGNORED) */
2342 case '\000': /* NUL (IGNORED) */
2343 case '\021': /* XON (IGNORED) */
2344 case '\023': /* XOFF (IGNORED) */
2345 case 0177: /* DEL (IGNORED) */
2348 } else if(term.esc & ESC_START) {
2349 if(term.esc & ESC_CSI) {
2350 csiescseq.buf[csiescseq.len++] = ascii;
2351 if(BETWEEN(ascii, 0x40, 0x7E)
2352 || csiescseq.len >= \
2353 sizeof(csiescseq.buf)-1) {
2358 } else if(term.esc & ESC_STR_END) {
2362 } else if(term.esc & ESC_ALTCHARSET) {
2364 case '0': /* Line drawing set */
2365 term.c.attr.mode |= ATTR_GFX;
2367 case 'B': /* USASCII */
2368 term.c.attr.mode &= ~ATTR_GFX;
2370 case 'A': /* UK (IGNORED) */
2371 case '<': /* multinational charset (IGNORED) */
2372 case '5': /* Finnish (IGNORED) */
2373 case 'C': /* Finnish (IGNORED) */
2374 case 'K': /* German (IGNORED) */
2377 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2380 } else if(term.esc & ESC_TEST) {
2381 if(ascii == '8') { /* DEC screen alignment test. */
2382 char E[UTF_SIZ] = "E";
2385 for(x = 0; x < term.col; ++x) {
2386 for(y = 0; y < term.row; ++y)
2387 tsetchar(E, &term.c.attr, x, y);
2394 term.esc |= ESC_CSI;
2397 term.esc |= ESC_TEST;
2399 case 'P': /* DCS -- Device Control String */
2400 case '_': /* APC -- Application Program Command */
2401 case '^': /* PM -- Privacy Message */
2402 case ']': /* OSC -- Operating System Command */
2403 case 'k': /* old title set compatibility */
2405 strescseq.type = ascii;
2406 term.esc |= ESC_STR;
2408 case '(': /* set primary charset G0 */
2409 term.esc |= ESC_ALTCHARSET;
2411 case ')': /* set secondary charset G1 (IGNORED) */
2412 case '*': /* set tertiary charset G2 (IGNORED) */
2413 case '+': /* set quaternary charset G3 (IGNORED) */
2416 case 'D': /* IND -- Linefeed */
2417 if(term.c.y == term.bot) {
2418 tscrollup(term.top, 1);
2420 tmoveto(term.c.x, term.c.y+1);
2424 case 'E': /* NEL -- Next line */
2425 tnewline(1); /* always go to first col */
2428 case 'H': /* HTS -- Horizontal tab stop */
2429 term.tabs[term.c.x] = 1;
2432 case 'M': /* RI -- Reverse index */
2433 if(term.c.y == term.top) {
2434 tscrolldown(term.top, 1);
2436 tmoveto(term.c.x, term.c.y-1);
2440 case 'Z': /* DECID -- Identify Terminal */
2441 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2444 case 'c': /* RIS -- Reset to inital state */
2450 case '=': /* DECPAM -- Application keypad */
2451 term.mode |= MODE_APPKEYPAD;
2454 case '>': /* DECPNM -- Normal keypad */
2455 term.mode &= ~MODE_APPKEYPAD;
2458 case '7': /* DECSC -- Save Cursor */
2459 tcursor(CURSOR_SAVE);
2462 case '8': /* DECRC -- Restore Cursor */
2463 tcursor(CURSOR_LOAD);
2466 case '\\': /* ST -- Stop */
2470 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2471 (uchar) ascii, isprint(ascii)? ascii:'.');
2476 * All characters which form part of a sequence are not
2482 * Display control codes only if we are in graphic mode
2484 if(control && !(term.c.attr.mode & ATTR_GFX))
2486 if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2488 if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2489 term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
2493 if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2494 memmove(&term.line[term.c.y][term.c.x+1],
2495 &term.line[term.c.y][term.c.x],
2496 (term.col - term.c.x - 1) * sizeof(Glyph));
2499 if(term.c.x+width > term.col)
2502 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2505 term.line[term.c.y][term.c.x].mode |= ATTR_WIDE;
2506 if(term.c.x+1 < term.col) {
2507 term.line[term.c.y][term.c.x+1].c[0] = '\0';
2508 term.line[term.c.y][term.c.x+1].mode = ATTR_WDUMMY;
2511 if(term.c.x+width < term.col) {
2512 tmoveto(term.c.x+width, term.c.y);
2514 term.c.state |= CURSOR_WRAPNEXT;
2519 tresize(int col, int row) {
2521 int minrow = MIN(row, term.row);
2522 int mincol = MIN(col, term.col);
2523 int slide = term.c.y - row + 1;
2527 if(col < 1 || row < 1)
2530 /* free unneeded rows */
2534 * slide screen to keep cursor where we expect it -
2535 * tscrollup would work here, but we can optimize to
2536 * memmove because we're freeing the earlier lines
2538 for(/* i = 0 */; i < slide; i++) {
2542 memmove(term.line, term.line + slide, row * sizeof(Line));
2543 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2545 for(i += row; i < term.row; i++) {
2550 /* resize to new height */
2551 term.line = xrealloc(term.line, row * sizeof(Line));
2552 term.alt = xrealloc(term.alt, row * sizeof(Line));
2553 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2554 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2556 /* resize each row to new width, zero-pad if needed */
2557 for(i = 0; i < minrow; i++) {
2559 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2560 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2563 /* allocate any new rows */
2564 for(/* i == minrow */; i < row; i++) {
2566 term.line[i] = xmalloc(col * sizeof(Glyph));
2567 term.alt[i] = xmalloc(col * sizeof(Glyph));
2569 if(col > term.col) {
2570 bp = term.tabs + term.col;
2572 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2573 while(--bp > term.tabs && !*bp)
2575 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2578 /* update terminal size */
2581 /* reset scrolling region */
2582 tsetscroll(0, row-1);
2583 /* make use of the LIMIT in tmoveto */
2584 tmoveto(term.c.x, term.c.y);
2585 /* Clearing both screens */
2588 if(mincol < col && 0 < minrow) {
2589 tclearregion(mincol, 0, col - 1, minrow - 1);
2591 if(0 < col && minrow < row) {
2592 tclearregion(0, minrow, col - 1, row - 1);
2595 } while(orig != term.line);
2601 xresize(int col, int row) {
2602 xw.tw = MAX(1, col * xw.cw);
2603 xw.th = MAX(1, row * xw.ch);
2605 XFreePixmap(xw.dpy, xw.buf);
2606 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2607 DefaultDepth(xw.dpy, xw.scr));
2608 XftDrawChange(xw.draw, xw.buf);
2609 xclear(0, 0, xw.w, xw.h);
2612 static inline ushort
2613 sixd_to_16bit(int x) {
2614 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2620 XRenderColor color = { .alpha = 0xffff };
2625 for (cp = dc.col; cp < dc.col + LEN(dc.col); ++cp)
2626 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
2629 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2630 for(i = 0; i < LEN(colorname); i++) {
2633 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2634 die("Could not allocate color '%s'\n", colorname[i]);
2638 /* load colors [16-255] ; same colors as xterm */
2639 for(i = 16, r = 0; r < 6; r++) {
2640 for(g = 0; g < 6; g++) {
2641 for(b = 0; b < 6; b++) {
2642 color.red = sixd_to_16bit(r);
2643 color.green = sixd_to_16bit(g);
2644 color.blue = sixd_to_16bit(b);
2645 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2646 die("Could not allocate color %d\n", i);
2653 for(r = 0; r < 24; r++, i++) {
2654 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2655 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2657 die("Could not allocate color %d\n", i);
2664 xsetcolorname(int x, const char *name) {
2665 XRenderColor color = { .alpha = 0xffff };
2667 if (x < 0 || x > LEN(colorname))
2670 if(16 <= x && x < 16 + 216) {
2671 int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2672 color.red = sixd_to_16bit(r);
2673 color.green = sixd_to_16bit(g);
2674 color.blue = sixd_to_16bit(b);
2675 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2676 return 0; /* something went wrong */
2679 } else if (16 + 216 <= x && x < 256) {
2680 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2681 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2682 return 0; /* something went wrong */
2686 name = colorname[x];
2689 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2696 xtermclear(int col1, int row1, int col2, int row2) {
2697 XftDrawRect(xw.draw,
2698 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2699 borderpx + col1 * xw.cw,
2700 borderpx + row1 * xw.ch,
2701 (col2-col1+1) * xw.cw,
2702 (row2-row1+1) * xw.ch);
2706 * Absolute coordinates.
2709 xclear(int x1, int y1, int x2, int y2) {
2710 XftDrawRect(xw.draw,
2711 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2712 x1, y1, x2-x1, y2-y1);
2717 XClassHint class = {opt_class ? opt_class : termname, termname};
2718 XWMHints wm = {.flags = InputHint, .input = 1};
2719 XSizeHints *sizeh = NULL;
2721 sizeh = XAllocSizeHints();
2722 if(xw.isfixed == False) {
2723 sizeh->flags = PSize | PResizeInc | PBaseSize;
2724 sizeh->height = xw.h;
2725 sizeh->width = xw.w;
2726 sizeh->height_inc = xw.ch;
2727 sizeh->width_inc = xw.cw;
2728 sizeh->base_height = 2 * borderpx;
2729 sizeh->base_width = 2 * borderpx;
2731 sizeh->flags = PMaxSize | PMinSize;
2732 sizeh->min_width = sizeh->max_width = xw.fw;
2733 sizeh->min_height = sizeh->max_height = xw.fh;
2736 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2741 xloadfont(Font *f, FcPattern *pattern) {
2745 match = FcFontMatch(NULL, pattern, &result);
2749 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2750 FcPatternDestroy(match);
2755 f->pattern = FcPatternDuplicate(pattern);
2757 f->ascent = f->match->ascent;
2758 f->descent = f->match->descent;
2760 f->rbearing = f->match->max_advance_width;
2762 f->height = f->ascent + f->descent;
2763 f->width = f->lbearing + f->rbearing;
2769 xloadfonts(char *fontstr, int fontsize) {
2774 if(fontstr[0] == '-') {
2775 pattern = XftXlfdParse(fontstr, False, False);
2777 pattern = FcNameParse((FcChar8 *)fontstr);
2781 die("st: can't open font %s\n", fontstr);
2784 FcPatternDel(pattern, FC_PIXEL_SIZE);
2785 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2786 usedfontsize = fontsize;
2788 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2789 if(result == FcResultMatch) {
2790 usedfontsize = (int)fontval;
2793 * Default font size is 12, if none given. This is to
2794 * have a known usedfontsize value.
2796 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2801 FcConfigSubstitute(0, pattern, FcMatchPattern);
2802 FcDefaultSubstitute(pattern);
2804 if(xloadfont(&dc.font, pattern))
2805 die("st: can't open font %s\n", fontstr);
2807 /* Setting character width and height. */
2808 xw.cw = CEIL(dc.font.width * cwscale);
2809 xw.ch = CEIL(dc.font.height * chscale);
2811 FcPatternDel(pattern, FC_SLANT);
2812 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2813 if(xloadfont(&dc.ifont, pattern))
2814 die("st: can't open font %s\n", fontstr);
2816 FcPatternDel(pattern, FC_WEIGHT);
2817 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2818 if(xloadfont(&dc.ibfont, pattern))
2819 die("st: can't open font %s\n", fontstr);
2821 FcPatternDel(pattern, FC_SLANT);
2822 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2823 if(xloadfont(&dc.bfont, pattern))
2824 die("st: can't open font %s\n", fontstr);
2826 FcPatternDestroy(pattern);
2830 xloadfontset(Font *f) {
2833 if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
2839 xunloadfont(Font *f) {
2840 XftFontClose(xw.dpy, f->match);
2841 FcPatternDestroy(f->pattern);
2843 FcFontSetDestroy(f->set);
2847 xunloadfonts(void) {
2850 /* Free the loaded fonts in the font cache. */
2851 for(i = 0; i < frclen; i++) {
2852 XftFontClose(xw.dpy, frc[i].font);
2856 xunloadfont(&dc.font);
2857 xunloadfont(&dc.bfont);
2858 xunloadfont(&dc.ifont);
2859 xunloadfont(&dc.ibfont);
2863 xzoom(const Arg *arg) {
2865 xloadfonts(usedfont, usedfontsize + arg->i);
2877 if(!(xw.dpy = XOpenDisplay(NULL)))
2878 die("Can't open display\n");
2879 xw.scr = XDefaultScreen(xw.dpy);
2880 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2884 die("Could not init fontconfig.\n");
2886 usedfont = (opt_font == NULL)? font : opt_font;
2887 xloadfonts(usedfont, 0);
2890 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2893 /* adjust fixed window geometry */
2895 sw = DisplayWidth(xw.dpy, xw.scr);
2896 sh = DisplayHeight(xw.dpy, xw.scr);
2898 xw.fx = sw + xw.fx - xw.fw - 1;
2900 xw.fy = sh + xw.fy - xw.fh - 1;
2905 /* window - default size */
2906 xw.h = 2 * borderpx + term.row * xw.ch;
2907 xw.w = 2 * borderpx + term.col * xw.cw;
2913 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
2914 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
2915 xw.attrs.bit_gravity = NorthWestGravity;
2916 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
2917 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2918 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2919 xw.attrs.colormap = xw.cmap;
2921 parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2922 XRootWindow(xw.dpy, xw.scr);
2923 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2924 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2925 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
2926 | CWEventMask | CWColormap, &xw.attrs);
2928 memset(&gcvalues, 0, sizeof(gcvalues));
2929 gcvalues.graphics_exposures = False;
2930 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2932 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2933 DefaultDepth(xw.dpy, xw.scr));
2934 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
2935 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2937 /* Xft rendering context */
2938 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2941 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2942 XSetLocaleModifiers("@im=local");
2943 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2944 XSetLocaleModifiers("@im=");
2945 if((xw.xim = XOpenIM(xw.dpy,
2946 NULL, NULL, NULL)) == NULL) {
2947 die("XOpenIM failed. Could not open input"
2952 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2953 | XIMStatusNothing, XNClientWindow, xw.win,
2954 XNFocusWindow, xw.win, NULL);
2956 die("XCreateIC failed. Could not obtain input method.\n");
2958 /* white cursor, black outline */
2959 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2960 XDefineCursor(xw.dpy, xw.win, cursor);
2961 XRecolorCursor(xw.dpy, cursor,
2962 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2963 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2965 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2966 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2967 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2970 XMapWindow(xw.dpy, xw.win);
2976 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2977 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2978 width = charlen * xw.cw, xp, i;
2980 int u8fl, u8fblen, u8cblen, doesexist;
2983 Font *font = &dc.font;
2985 FcPattern *fcpattern, *fontpattern;
2986 FcFontSet *fcsets[] = { NULL };
2987 FcCharSet *fccharset;
2988 Colour *fg, *bg, *temp, revfg, revbg, truefg, truebg;
2989 XRenderColor colfg, colbg;
2993 frcflags = FRC_NORMAL;
2995 if(base.mode & ATTR_ITALIC) {
2996 if(base.fg == defaultfg)
2997 base.fg = defaultitalic;
2999 frcflags = FRC_ITALIC;
3000 } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
3001 if(base.fg == defaultfg)
3002 base.fg = defaultitalic;
3004 frcflags = FRC_ITALICBOLD;
3005 } else if(base.mode & ATTR_UNDERLINE) {
3006 if(base.fg == defaultfg)
3007 base.fg = defaultunderline;
3009 if(IS_TRUECOL(base.fg)) {
3010 colfg.red = TRUERED(base.fg);
3011 colfg.green = TRUEGREEN(base.fg);
3012 colfg.blue = TRUEBLUE(base.fg);
3013 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
3016 fg = &dc.col[base.fg];
3019 if(IS_TRUECOL(base.bg)) {
3020 colbg.green = TRUEGREEN(base.bg);
3021 colbg.red = TRUERED(base.bg);
3022 colbg.blue = TRUEBLUE(base.bg);
3023 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
3026 bg = &dc.col[base.bg];
3031 if(base.mode & ATTR_BOLD) {
3032 if(BETWEEN(base.fg, 0, 7)) {
3033 /* basic system colors */
3034 fg = &dc.col[base.fg + 8];
3035 } else if(BETWEEN(base.fg, 16, 195)) {
3037 fg = &dc.col[base.fg + 36];
3038 } else if(BETWEEN(base.fg, 232, 251)) {
3040 fg = &dc.col[base.fg + 4];
3043 * Those ranges will not be brightened:
3044 * 8 - 15 – bright system colors
3045 * 196 - 231 – highest 256 color cube
3046 * 252 - 255 – brightest colors in greyscale
3049 frcflags = FRC_BOLD;
3052 if(IS_SET(MODE_REVERSE)) {
3053 if(fg == &dc.col[defaultfg]) {
3054 fg = &dc.col[defaultbg];
3056 colfg.red = ~fg->color.red;
3057 colfg.green = ~fg->color.green;
3058 colfg.blue = ~fg->color.blue;
3059 colfg.alpha = fg->color.alpha;
3060 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
3064 if(bg == &dc.col[defaultbg]) {
3065 bg = &dc.col[defaultfg];
3067 colbg.red = ~bg->color.red;
3068 colbg.green = ~bg->color.green;
3069 colbg.blue = ~bg->color.blue;
3070 colbg.alpha = bg->color.alpha;
3071 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
3076 if(base.mode & ATTR_REVERSE) {
3082 if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3085 /* Intelligent cleaning up of the borders. */
3087 xclear(0, (y == 0)? 0 : winy, borderpx,
3088 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3090 if(x + charlen >= term.col) {
3091 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3092 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3095 xclear(winx, 0, winx + width, borderpx);
3097 xclear(winx, winy + xw.ch, winx + width, xw.h);
3099 /* Clean up the region we want to draw to. */
3100 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3102 /* Set the clip region because Xft is sometimes dirty. */
3107 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3109 for(xp = winx; bytelen > 0;) {
3111 * Search for the range in the to be printed string of glyphs
3112 * that are in the main font. Then print that range. If
3113 * some glyph is found that is not in the font, do the
3119 oneatatime = font->width != xw.cw;
3122 u8cblen = utf8decode(s, &u8char);
3126 doesexist = XftCharExists(xw.dpy, font->match, u8char);
3127 if(oneatatime || !doesexist || bytelen <= 0) {
3128 if(oneatatime || bytelen <= 0) {
3136 XftDrawStringUtf8(xw.draw, fg,
3138 winy + font->ascent,
3156 /* Search the font cache. */
3157 for(i = 0; i < frclen; i++) {
3158 if(XftCharExists(xw.dpy, frc[i].font, u8char)
3159 && frc[i].flags == frcflags) {
3164 /* Nothing was found. */
3168 fcsets[0] = font->set;
3171 * Nothing was found in the cache. Now use
3172 * some dozen of Fontconfig calls to get the
3173 * font for one single character.
3175 fcpattern = FcPatternDuplicate(font->pattern);
3176 fccharset = FcCharSetCreate();
3178 FcCharSetAddChar(fccharset, u8char);
3179 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3181 FcPatternAddBool(fcpattern, FC_SCALABLE,
3184 FcConfigSubstitute(0, fcpattern,
3186 FcDefaultSubstitute(fcpattern);
3188 fontpattern = FcFontSetMatch(0, fcsets,
3189 FcTrue, fcpattern, &fcres);
3192 * Overwrite or create the new cache entry.
3194 if(frclen >= LEN(frc)) {
3195 frclen = LEN(frc) - 1;
3196 XftFontClose(xw.dpy, frc[frclen].font);
3199 frc[frclen].font = XftFontOpenPattern(xw.dpy,
3201 frc[frclen].flags = frcflags;
3206 FcPatternDestroy(fcpattern);
3207 FcCharSetDestroy(fccharset);
3210 XftDrawStringUtf8(xw.draw, fg, frc[i].font,
3211 xp, winy + frc[i].font->ascent,
3212 (FcChar8 *)u8c, u8cblen);
3214 xp += xw.cw * wcwidth(u8char);
3218 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
3219 winy + font->ascent, (FcChar8 *)s, bytelen);
3222 if(base.mode & ATTR_UNDERLINE) {
3223 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
3227 /* Reset clip to none. */
3228 XftDrawSetClip(xw.draw, 0);
3233 static int oldx = 0, oldy = 0;
3234 int sl, width, curx;
3235 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
3237 LIMIT(oldx, 0, term.col-1);
3238 LIMIT(oldy, 0, term.row-1);
3242 /* adjust position if in dummy */
3243 if(term.line[oldy][oldx].mode & ATTR_WDUMMY)
3245 if(term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3248 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
3250 /* remove the old cursor */
3251 sl = utf8size(term.line[oldy][oldx].c);
3252 width = (term.line[oldy][oldx].mode & ATTR_WIDE)? 2 : 1;
3253 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
3256 /* draw the new one */
3257 if(!(IS_SET(MODE_HIDE))) {
3258 if(xw.state & WIN_FOCUSED) {
3259 if(IS_SET(MODE_REVERSE)) {
3260 g.mode |= ATTR_REVERSE;
3266 width = (term.line[term.c.y][curx].mode & ATTR_WIDE)\
3268 xdraws(g.c, g, term.c.x, term.c.y, width, sl);
3270 XftDrawRect(xw.draw, &dc.col[defaultcs],
3271 borderpx + curx * xw.cw,
3272 borderpx + term.c.y * xw.ch,
3274 XftDrawRect(xw.draw, &dc.col[defaultcs],
3275 borderpx + curx * xw.cw,
3276 borderpx + term.c.y * xw.ch,
3278 XftDrawRect(xw.draw, &dc.col[defaultcs],
3279 borderpx + (curx + 1) * xw.cw - 1,
3280 borderpx + term.c.y * xw.ch,
3282 XftDrawRect(xw.draw, &dc.col[defaultcs],
3283 borderpx + curx * xw.cw,
3284 borderpx + (term.c.y + 1) * xw.ch - 1,
3287 oldx = curx, oldy = term.c.y;
3293 xsettitle(char *p) {
3296 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3298 XSetWMName(xw.dpy, xw.win, &prop);
3304 xsettitle(opt_title ? opt_title : "st");
3308 redraw(int timeout) {
3309 struct timespec tv = {0, timeout * 1000};
3315 nanosleep(&tv, NULL);
3316 XSync(xw.dpy, False); /* necessary for a good tput flash */
3322 drawregion(0, 0, term.col, term.row);
3323 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3325 XSetForeground(xw.dpy, dc.gc,
3326 dc.col[IS_SET(MODE_REVERSE)?
3327 defaultfg : defaultbg].pixel);
3331 drawregion(int x1, int y1, int x2, int y2) {
3332 int ic, ib, x, y, ox, sl;
3334 char buf[DRAW_BUF_SIZ];
3335 bool ena_sel = sel.ob.x != -1;
3338 if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3341 if(!(xw.state & WIN_VISIBLE))
3344 for(y = y1; y < y2; y++) {
3348 xtermclear(0, y, term.col, y);
3350 base = term.line[y][0];
3352 for(x = x1; x < x2; x++) {
3353 new = term.line[y][x];
3354 if(new.mode == ATTR_WDUMMY)
3356 if(ena_sel && selected(x, y))
3357 new.mode ^= ATTR_REVERSE;
3358 if(ib > 0 && (ATTRCMP(base, new)
3359 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3360 xdraws(buf, base, ox, y, ic, ib);
3368 sl = utf8decode(new.c, &u8char);
3369 memcpy(buf+ib, new.c, sl);
3371 ic += (new.mode & ATTR_WIDE)? 2 : 1;
3374 xdraws(buf, base, ox, y, ic, ib);
3380 expose(XEvent *ev) {
3381 XExposeEvent *e = &ev->xexpose;
3383 if(xw.state & WIN_REDRAW) {
3385 xw.state &= ~WIN_REDRAW;
3391 visibility(XEvent *ev) {
3392 XVisibilityEvent *e = &ev->xvisibility;
3394 if(e->state == VisibilityFullyObscured) {
3395 xw.state &= ~WIN_VISIBLE;
3396 } else if(!(xw.state & WIN_VISIBLE)) {
3397 /* need a full redraw for next Expose, not just a buf copy */
3398 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3404 xw.state &= ~WIN_VISIBLE;
3408 xsetpointermotion(int set) {
3409 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3410 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3414 xseturgency(int add) {
3415 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3417 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3418 XSetWMHints(xw.dpy, xw.win, h);
3424 XFocusChangeEvent *e = &ev->xfocus;
3426 if(e->mode == NotifyGrab)
3429 if(ev->type == FocusIn) {
3430 XSetICFocus(xw.xic);
3431 xw.state |= WIN_FOCUSED;
3433 if(IS_SET(MODE_FOCUS))
3434 ttywrite("\033[I", 3);
3436 XUnsetICFocus(xw.xic);
3437 xw.state &= ~WIN_FOCUSED;
3438 if(IS_SET(MODE_FOCUS))
3439 ttywrite("\033[O", 3);
3444 match(uint mask, uint state) {
3445 state &= ~ignoremod;
3447 if(mask == XK_NO_MOD && state)
3449 if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
3451 if(mask == XK_ANY_MOD)
3453 return state == mask;
3457 numlock(const Arg *dummy) {
3462 kmap(KeySym k, uint state) {
3466 /* Check for mapped keys out of X11 function keys. */
3467 for(i = 0; i < LEN(mappedkeys); i++) {
3468 if(mappedkeys[i] == k)
3471 if(i == LEN(mappedkeys)) {
3472 if((k & 0xFFFF) < 0xFD00)
3476 for(kp = key; kp < key + LEN(key); kp++) {
3480 if(!match(kp->mask, state))
3483 if(kp->appkey > 0) {
3484 if(!IS_SET(MODE_APPKEYPAD))
3486 if(term.numlock && kp->appkey == 2)
3488 } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
3492 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
3494 && !IS_SET(MODE_APPCURSOR))) {
3498 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
3499 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
3510 kpress(XEvent *ev) {
3511 XKeyEvent *e = &ev->xkey;
3513 char xstr[31], buf[32], *customkey, *cp = buf;
3519 if(IS_SET(MODE_KBDLOCK))
3522 len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
3523 e->state &= ~Mod2Mask;
3525 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3526 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3527 bp->func(&(bp->arg));
3532 /* 2. custom keys from config.h */
3533 if((customkey = kmap(ksym, e->state))) {
3534 len = strlen(customkey);
3535 memcpy(buf, customkey, len);
3536 /* 3. hardcoded (overrides X lookup) */
3541 if(len == 1 && e->state & Mod1Mask) {
3542 if(IS_SET(MODE_8BIT)) {
3545 ret = utf8encode(&c, cp);
3554 memcpy(cp, xstr, len);
3555 len = cp - buf + len;
3559 if(IS_SET(MODE_ECHO))
3565 cmessage(XEvent *e) {
3568 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3570 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3571 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3572 xw.state |= WIN_FOCUSED;
3574 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3575 xw.state &= ~WIN_FOCUSED;
3577 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3578 /* Send SIGHUP to shell */
3585 cresize(int width, int height) {
3593 col = (xw.w - 2 * borderpx) / xw.cw;
3594 row = (xw.h - 2 * borderpx) / xw.ch;
3603 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3606 cresize(e->xconfigure.width, e->xconfigure.height);
3612 int w = xw.w, h = xw.h;
3614 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3615 struct timeval drawtimeout, *tv = NULL, now, last, lastblink;
3617 /* Waiting for window mapping */
3619 XNextEvent(xw.dpy, &ev);
3620 if(ev.type == ConfigureNotify) {
3621 w = ev.xconfigure.width;
3622 h = ev.xconfigure.height;
3623 } else if(ev.type == MapNotify) {
3631 cresize(xw.fw, xw.fh);
3634 gettimeofday(&lastblink, NULL);
3635 gettimeofday(&last, NULL);
3637 for(xev = actionfps;;) {
3639 FD_SET(cmdfd, &rfd);
3642 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3645 die("select failed: %s\n", SERRNO);
3647 if(FD_ISSET(cmdfd, &rfd)) {
3650 blinkset = tattrset(ATTR_BLINK);
3652 MODBIT(term.mode, 0, MODE_BLINK);
3656 if(FD_ISSET(xfd, &rfd))
3659 gettimeofday(&now, NULL);
3660 drawtimeout.tv_sec = 0;
3661 drawtimeout.tv_usec = (1000/xfps) * 1000;
3665 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3666 tsetdirtattr(ATTR_BLINK);
3667 term.mode ^= MODE_BLINK;
3668 gettimeofday(&lastblink, NULL);
3671 if(TIMEDIFF(now, last) \
3672 > (xev? (1000/xfps) : (1000/actionfps))) {
3678 while(XPending(xw.dpy)) {
3679 XNextEvent(xw.dpy, &ev);
3680 if(XFilterEvent(&ev, None))
3682 if(handler[ev.type])
3683 (handler[ev.type])(&ev);
3689 if(xev && !FD_ISSET(xfd, &rfd))
3691 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3693 if(TIMEDIFF(now, lastblink) \
3695 drawtimeout.tv_usec = 1;
3697 drawtimeout.tv_usec = (1000 * \
3712 die("%s " VERSION " (c) 2010-2013 st engineers\n" \
3713 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
3714 " [-t title] [-w windowid] [-e command ...]\n", argv0);
3718 main(int argc, char *argv[]) {
3723 xw.fw = xw.fh = xw.fx = xw.fy = 0;
3728 allowaltscreen = false;
3731 opt_class = EARGF(usage());
3734 /* eat all remaining arguments */
3737 if(argv[1] != NULL && opt_title == NULL) {
3738 titles = strdup(argv[1]);
3739 opt_title = basename(titles);
3744 opt_font = EARGF(usage());
3747 bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
3752 if(bitm & WidthValue)
3754 if(bitm & HeightValue)
3756 if(bitm & XNegative && xw.fx == 0)
3758 if(bitm & YNegative && xw.fy == 0)
3761 if(xw.fh != 0 && xw.fw != 0)
3765 opt_io = EARGF(usage());
3768 opt_title = EARGF(usage());
3771 opt_embed = EARGF(usage());
3779 setlocale(LC_CTYPE, "");
3780 XSetLocaleModifiers("");