1 /* See LICENSE for licence details. */
2 #define _XOPEN_SOURCE 600
15 #include <sys/ioctl.h>
16 #include <sys/select.h>
19 #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/extensions/Xdbe.h>
29 #include <X11/Xft/Xft.h>
30 #include <fontconfig/fontconfig.h>
34 #define Draw XftDraw *
35 #define Colour XftColor
36 #define Colourmap Colormap
40 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
42 #elif defined(__FreeBSD__) || defined(__DragonFly__)
47 "st " VERSION " (c) 2010-2013 st engineers\n" \
48 "usage: st [-v] [-c class] [-f font] [-g geometry] [-o file]" \
49 " [-t title] [-w windowid] [-e command ...]\n"
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
65 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
68 #define SERRNO strerror(errno)
69 #define MIN(a, b) ((a) < (b) ? (a) : (b))
70 #define MAX(a, b) ((a) < (b) ? (b) : (a))
71 #define LEN(a) (sizeof(a) / sizeof(a[0]))
72 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
73 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
74 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
75 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
76 #define IS_SET(flag) ((term.mode & (flag)) != 0)
77 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
79 #define VT102ID "\033[?6c"
81 enum glyph_attribute {
91 enum cursor_movement {
114 MODE_MOUSEMOTION = 64,
120 MODE_APPCURSOR = 2048,
121 MODE_MOUSESGR = 4096,
127 ESC_STR = 4, /* DSC, OSC, PM, APC */
129 ESC_STR_END = 16, /* a final string was encountered */
130 ESC_TEST = 32, /* Enter in test mode */
141 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
143 typedef unsigned char uchar;
144 typedef unsigned int uint;
145 typedef unsigned long ulong;
146 typedef unsigned short ushort;
149 char c[UTF_SIZ]; /* character code */
150 uchar mode; /* attribute flags */
151 ushort fg; /* foreground */
152 ushort bg; /* background */
153 uchar state; /* state flags */
159 Glyph attr; /* current char attributes */
165 /* CSI Escape sequence structs */
166 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
168 char buf[ESC_BUF_SIZ]; /* raw string */
169 int len; /* raw string length */
171 int arg[ESC_ARG_SIZ];
172 int narg; /* nb of args */
176 /* STR Escape sequence structs */
177 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
179 char type; /* ESC type ... */
180 char buf[STR_BUF_SIZ]; /* raw string */
181 int len; /* raw string length */
182 char *args[STR_ARG_SIZ];
183 int narg; /* nb of args */
186 /* Internal representation of the screen */
188 int row; /* nb row */
189 int col; /* nb col */
190 Line *line; /* screen */
191 Line *alt; /* alternate screen */
192 bool *dirty; /* dirtyness of lines */
193 TCursor c; /* cursor */
194 int top; /* top scroll limit */
195 int bot; /* bottom scroll limit */
196 int mode; /* terminal mode flags */
197 int esc; /* escape state flags */
198 bool numlock; /* lock numbers in keyboard */
202 /* Purely graphic info */
208 Atom xembed, wmdeletewin;
214 bool isfixed; /* is fixed geometry? */
215 int fx, fy, fw, fh; /* fixed geometry */
216 int tw, th; /* tty width and height */
217 int w, h; /* window width and height */
218 int ch; /* char height */
219 int cw; /* char width */
220 char state; /* focus, redraw, visible */
227 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
228 signed char appkey; /* application keypad */
229 signed char appcursor; /* application cursor */
230 signed char crlf; /* crlf mode */
233 /* TODO: use better name for vars... */
244 struct timeval tclick1;
245 struct timeval tclick2;
258 void (*func)(const Arg *);
262 /* function definitions used in config.h */
263 static void xzoom(const Arg *);
264 static void selpaste(const Arg *);
265 static void numlock(const Arg *);
267 /* Config.h for applying patches and the configuration. */
283 /* Drawing Context */
285 Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
286 Font font, bfont, ifont, ibfont;
290 static void die(const char *, ...);
291 static void draw(void);
292 static void redraw(int);
293 static void drawregion(int, int, int, int);
294 static void execsh(void);
295 static void sigchld(int);
296 static void run(void);
298 static void csidump(void);
299 static void csihandle(void);
300 static void csiparse(void);
301 static void csireset(void);
302 static void strdump(void);
303 static void strhandle(void);
304 static void strparse(void);
305 static void strreset(void);
307 static void tclearregion(int, int, int, int, int);
308 static void tcursor(int);
309 static void tdeletechar(int);
310 static void tdeleteline(int);
311 static void tinsertblank(int);
312 static void tinsertblankline(int);
313 static void tmoveto(int, int);
314 static void tmoveato(int x, int y);
315 static void tnew(int, int);
316 static void tnewline(int);
317 static void tputtab(bool);
318 static void tputc(char *, int);
319 static void treset(void);
320 static int tresize(int, int);
321 static void tscrollup(int, int);
322 static void tscrolldown(int, int);
323 static void tsetattr(int*, int);
324 static void tsetchar(char *, Glyph *, int, int);
325 static void tsetscroll(int, int);
326 static void tswapscreen(void);
327 static void tsetdirt(int, int);
328 static void tsetmode(bool, bool, int *, int);
329 static void tfulldirt(void);
330 static void techo(char *, int);
332 static inline bool match(uint, uint);
333 static void ttynew(void);
334 static void ttyread(void);
335 static void ttyresize(void);
336 static void ttywrite(const char *, size_t);
338 static void xdraws(char *, Glyph, int, int, int, int);
339 static void xhints(void);
340 static void xclear(int, int, int, int);
341 static void xdrawcursor(void);
342 static void xinit(void);
343 static void xloadcols(void);
344 static int xloadfont(Font *, FcPattern *);
345 static void xloadfonts(char *, int);
346 static void xresettitle(void);
347 static void xseturgency(int);
348 static void xsetsel(char*);
349 static void xtermclear(int, int, int, int);
350 static void xunloadfonts(void);
351 static void xresize(int, int);
353 static void expose(XEvent *);
354 static void visibility(XEvent *);
355 static void unmap(XEvent *);
356 static char *kmap(KeySym, uint);
357 static void kpress(XEvent *);
358 static void cmessage(XEvent *);
359 static void cresize(int, int);
360 static void resize(XEvent *);
361 static void focus(XEvent *);
362 static void brelease(XEvent *);
363 static void bpress(XEvent *);
364 static void bmotion(XEvent *);
365 static void selnotify(XEvent *);
366 static void selclear(XEvent *);
367 static void selrequest(XEvent *);
369 static void selinit(void);
370 static inline bool selected(int, int);
371 static void selcopy(void);
372 static void selscroll(int, int);
374 static int utf8decode(char *, long *);
375 static int utf8encode(long *, char *);
376 static int utf8size(char *);
377 static int isfullutf8(char *, int);
379 static ssize_t xwrite(int, char *, size_t);
380 static void *xmalloc(size_t);
381 static void *xrealloc(void *, size_t);
382 static void *xcalloc(size_t, size_t);
384 static void (*handler[LASTEvent])(XEvent *) = {
386 [ClientMessage] = cmessage,
387 [ConfigureNotify] = resize,
388 [VisibilityNotify] = visibility,
389 [UnmapNotify] = unmap,
393 [MotionNotify] = bmotion,
394 [ButtonPress] = bpress,
395 [ButtonRelease] = brelease,
396 [SelectionClear] = selclear,
397 [SelectionNotify] = selnotify,
398 [SelectionRequest] = selrequest,
405 static CSIEscape csiescseq;
406 static STREscape strescseq;
409 static Selection sel;
410 static int iofd = -1;
411 static char **opt_cmd = NULL;
412 static char *opt_io = NULL;
413 static char *opt_title = NULL;
414 static char *opt_embed = NULL;
415 static char *opt_class = NULL;
416 static char *opt_font = NULL;
420 static char *usedfont = NULL;
421 static int usedfontsize = 0;
423 /* Font Ring Cache */
438 * Fontcache is a ring buffer, with frccur as current position and frclen as
439 * the current length of used elements.
442 static Fontcache frc[1024];
443 static int frccur = -1, frclen = 0;
446 xwrite(int fd, char *s, size_t len) {
450 ssize_t r = write(fd, s, len);
460 xmalloc(size_t len) {
461 void *p = malloc(len);
464 die("Out of memory\n");
470 xrealloc(void *p, size_t len) {
471 if((p = realloc(p, len)) == NULL)
472 die("Out of memory\n");
478 xcalloc(size_t nmemb, size_t size) {
479 void *p = calloc(nmemb, size);
482 die("Out of memory\n");
488 utf8decode(char *s, long *u) {
494 if(~c & B7) { /* 0xxxxxxx */
497 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
498 *u = c&(B4|B3|B2|B1|B0);
500 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
501 *u = c&(B3|B2|B1|B0);
503 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
510 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
512 if((c & (B7|B6)) != B7) /* 10xxxxxx */
515 *u |= c & (B5|B4|B3|B2|B1|B0);
518 if((n == 1 && *u < 0x80) ||
519 (n == 2 && *u < 0x800) ||
520 (n == 3 && *u < 0x10000) ||
521 (*u >= 0xD800 && *u <= 0xDFFF)) {
533 utf8encode(long *u, char *s) {
541 *sp = uc; /* 0xxxxxxx */
543 } else if(*u < 0x800) {
544 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
546 } else if(uc < 0x10000) {
547 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
549 } else if(uc <= 0x10FFFF) {
550 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
556 for(i=n,++sp; i>0; --i,++sp)
557 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
569 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
570 UTF-8 otherwise return 0 */
572 isfullutf8(char *s, int b) {
580 } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
582 } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
584 ((b == 2) && (*c2&(B7|B6)) == B7))) {
586 } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
588 ((b == 2) && (*c2&(B7|B6)) == B7) ||
589 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
602 } else if((c&(B7|B6|B5)) == (B7|B6)) {
604 } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
613 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
614 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
618 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
619 if(sel.xtarget == None)
620 sel.xtarget = XA_STRING;
628 return LIMIT(x, 0, term.col-1);
636 return LIMIT(y, 0, term.row-1);
640 selected(int x, int y) {
643 if(sel.ey == y && sel.by == y) {
644 bx = MIN(sel.bx, sel.ex);
645 ex = MAX(sel.bx, sel.ex);
646 return BETWEEN(x, bx, ex);
649 return ((sel.b.y < y && y < sel.e.y)
650 || (y == sel.e.y && x <= sel.e.x))
651 || (y == sel.b.y && x >= sel.b.x
652 && (x <= sel.e.x || sel.b.y != sel.e.y));
656 getbuttoninfo(XEvent *e) {
657 sel.alt = IS_SET(MODE_ALTSCREEN);
659 sel.ex = x2col(e->xbutton.x);
660 sel.ey = y2row(e->xbutton.y);
662 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
663 sel.b.y = MIN(sel.by, sel.ey);
664 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
665 sel.e.y = MAX(sel.by, sel.ey);
669 mousereport(XEvent *e) {
670 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
671 button = e->xbutton.button, state = e->xbutton.state,
674 static int ob, ox, oy;
677 if(e->xbutton.type == MotionNotify) {
678 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
682 } else if(!IS_SET(MODE_MOUSESGR)
683 && (e->xbutton.type == ButtonRelease
684 || button == AnyButton)) {
690 if(e->xbutton.type == ButtonPress) {
696 button += (state & ShiftMask ? 4 : 0)
697 + (state & Mod4Mask ? 8 : 0)
698 + (state & ControlMask ? 16 : 0);
701 if(IS_SET(MODE_MOUSESGR)) {
702 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
704 e->xbutton.type == ButtonRelease ? 'm' : 'M');
705 } else if(x < 223 && y < 223) {
706 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
707 32+button, 32+x+1, 32+y+1);
717 if(IS_SET(MODE_MOUSE)) {
719 } else if(e->xbutton.button == Button1) {
722 tsetdirt(sel.b.y, sel.e.y);
726 sel.ex = sel.bx = x2col(e->xbutton.x);
727 sel.ey = sel.by = y2row(e->xbutton.y);
728 } else if(e->xbutton.button == Button4) {
730 } else if(e->xbutton.button == Button5) {
738 int x, y, bufsize, is_selected = 0, size;
744 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
745 ptr = str = xmalloc(bufsize);
747 /* append every set & selected glyph to the selection */
748 for(y = 0; y < term.row; y++) {
749 gp = &term.line[y][0];
750 last = gp + term.col;
752 while(--last >= gp && !(last->state & GLYPH_SET))
755 for(x = 0; gp <= last; x++, ++gp) {
756 if(!(is_selected = selected(x, y)))
759 p = (gp->state & GLYPH_SET) ? gp->c : " ";
761 memcpy(ptr, p, size);
764 /* \n at the end of every selected line except for the last one */
765 if(is_selected && y < sel.e.y)
774 selnotify(XEvent *e) {
775 ulong nitems, ofs, rem;
782 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
783 False, AnyPropertyType, &type, &format,
784 &nitems, &rem, &data)) {
785 fprintf(stderr, "Clipboard allocation failed\n");
788 ttywrite((const char *) data, nitems * format / 8);
790 /* number of 32-bit chunks returned */
791 ofs += nitems * format / 32;
796 selpaste(const Arg *dummy) {
797 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
798 xw.win, CurrentTime);
801 void selclear(XEvent *e) {
805 tsetdirt(sel.b.y, sel.e.y);
809 selrequest(XEvent *e) {
810 XSelectionRequestEvent *xsre;
812 Atom xa_targets, string;
814 xsre = (XSelectionRequestEvent *) e;
815 xev.type = SelectionNotify;
816 xev.requestor = xsre->requestor;
817 xev.selection = xsre->selection;
818 xev.target = xsre->target;
819 xev.time = xsre->time;
823 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
824 if(xsre->target == xa_targets) {
825 /* respond with the supported type */
826 string = sel.xtarget;
827 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
828 XA_ATOM, 32, PropModeReplace,
829 (uchar *) &string, 1);
830 xev.property = xsre->property;
831 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
832 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
833 xsre->target, 8, PropModeReplace,
834 (uchar *) sel.clip, strlen(sel.clip));
835 xev.property = xsre->property;
838 /* all done, send a notification to the listener */
839 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
840 fprintf(stderr, "Error sending SelectionNotify event\n");
845 /* register the selection for both the clipboard and the primary */
851 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
853 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
854 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
858 brelease(XEvent *e) {
861 if(IS_SET(MODE_MOUSE)) {
866 if(e->xbutton.button == Button2) {
868 } else if(e->xbutton.button == Button1) {
871 term.dirty[sel.ey] = 1;
872 if(sel.bx == sel.ex && sel.by == sel.ey) {
874 gettimeofday(&now, NULL);
876 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
877 /* triple click on the line */
878 sel.b.x = sel.bx = 0;
879 sel.e.x = sel.ex = term.col;
880 sel.b.y = sel.e.y = sel.ey;
882 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
883 /* double click to select word */
885 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
886 term.line[sel.ey][sel.bx-1].c[0] != ' ') {
890 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
891 term.line[sel.ey][sel.ex+1].c[0] != ' ') {
895 sel.b.y = sel.e.y = sel.ey;
903 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
904 gettimeofday(&sel.tclick1, NULL);
909 int starty, endy, oldey, oldex;
911 if(IS_SET(MODE_MOUSE)) {
923 if(oldey != sel.ey || oldex != sel.ex) {
924 starty = MIN(oldey, sel.ey);
925 endy = MAX(oldey, sel.ey);
926 tsetdirt(starty, endy);
931 die(const char *errstr, ...) {
934 va_start(ap, errstr);
935 vfprintf(stderr, errstr, ap);
943 char *envshell = getenv("SHELL");
944 const struct passwd *pass = getpwuid(getuid());
945 char buf[sizeof(long) * 8 + 1];
952 setenv("LOGNAME", pass->pw_name, 1);
953 setenv("USER", pass->pw_name, 1);
954 setenv("SHELL", pass->pw_shell, 0);
955 setenv("HOME", pass->pw_dir, 0);
958 snprintf(buf, sizeof(buf), "%lu", xw.win);
959 setenv("WINDOWID", buf, 1);
961 signal(SIGCHLD, SIG_DFL);
962 signal(SIGHUP, SIG_DFL);
963 signal(SIGINT, SIG_DFL);
964 signal(SIGQUIT, SIG_DFL);
965 signal(SIGTERM, SIG_DFL);
966 signal(SIGALRM, SIG_DFL);
968 DEFAULT(envshell, shell);
969 setenv("TERM", termname, 1);
970 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
971 execvp(args[0], args);
979 if(waitpid(pid, &stat, 0) < 0)
980 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
982 if(WIFEXITED(stat)) {
983 exit(WEXITSTATUS(stat));
992 struct winsize w = {term.row, term.col, 0, 0};
994 /* seems to work fine on linux, openbsd and freebsd */
995 if(openpty(&m, &s, NULL, NULL, &w) < 0)
996 die("openpty failed: %s\n", SERRNO);
998 switch(pid = fork()) {
1000 die("fork failed\n");
1003 setsid(); /* create a new process group */
1004 dup2(s, STDIN_FILENO);
1005 dup2(s, STDOUT_FILENO);
1006 dup2(s, STDERR_FILENO);
1007 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1008 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
1016 signal(SIGCHLD, sigchld);
1018 iofd = (!strcmp(opt_io, "-")) ?
1020 open(opt_io, O_WRONLY | O_CREAT, 0666);
1022 fprintf(stderr, "Error opening %s:%s\n",
1023 opt_io, strerror(errno));
1033 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1035 fprintf(stderr, "\n");
1040 static char buf[BUFSIZ];
1041 static int buflen = 0;
1044 int charsize; /* size of utf8 char in bytes */
1048 /* append read bytes to unprocessed bytes */
1049 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1050 die("Couldn't read from shell: %s\n", SERRNO);
1052 /* process every complete utf8 char */
1055 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1056 charsize = utf8decode(ptr, &utf8c);
1057 utf8encode(&utf8c, s);
1063 /* keep any uncomplete utf8 char for the next call */
1064 memmove(buf, ptr, buflen);
1068 ttywrite(const char *s, size_t n) {
1069 if(write(cmdfd, s, n) == -1)
1070 die("write error on tty: %s\n", SERRNO);
1077 w.ws_row = term.row;
1078 w.ws_col = term.col;
1079 w.ws_xpixel = xw.tw;
1080 w.ws_ypixel = xw.th;
1081 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1082 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1086 tsetdirt(int top, int bot) {
1089 LIMIT(top, 0, term.row-1);
1090 LIMIT(bot, 0, term.row-1);
1092 for(i = top; i <= bot; i++)
1098 tsetdirt(0, term.row-1);
1105 if(mode == CURSOR_SAVE) {
1107 } else if(mode == CURSOR_LOAD) {
1117 term.c = (TCursor){{
1121 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1123 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1124 for(i = tabspaces; i < term.col; i += tabspaces)
1127 term.bot = term.row - 1;
1128 term.mode = MODE_WRAP;
1130 tclearregion(0, 0, term.col-1, term.row-1, 0);
1132 tcursor(CURSOR_SAVE);
1136 tnew(int col, int row) {
1137 /* set screen size */
1140 term.line = xmalloc(term.row * sizeof(Line));
1141 term.alt = xmalloc(term.row * sizeof(Line));
1142 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1143 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1145 for(row = 0; row < term.row; row++) {
1146 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1147 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1148 term.dirty[row] = 0;
1152 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1159 Line *tmp = term.line;
1161 term.line = term.alt;
1163 term.mode ^= MODE_ALTSCREEN;
1168 tscrolldown(int orig, int n) {
1172 LIMIT(n, 0, term.bot-orig+1);
1174 tclearregion(0, term.bot-n+1, term.col-1, term.bot, 0);
1176 for(i = term.bot; i >= orig+n; i--) {
1177 temp = term.line[i];
1178 term.line[i] = term.line[i-n];
1179 term.line[i-n] = temp;
1182 term.dirty[i-n] = 1;
1189 tscrollup(int orig, int n) {
1192 LIMIT(n, 0, term.bot-orig+1);
1194 tclearregion(0, orig, term.col-1, orig+n-1, 0);
1196 for(i = orig; i <= term.bot-n; i++) {
1197 temp = term.line[i];
1198 term.line[i] = term.line[i+n];
1199 term.line[i+n] = temp;
1202 term.dirty[i+n] = 1;
1205 selscroll(orig, -n);
1209 selscroll(int orig, int n) {
1213 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1214 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1218 if(sel.by < term.top) {
1222 if(sel.ey > term.bot) {
1226 sel.b.y = sel.by, sel.b.x = sel.bx;
1227 sel.e.y = sel.ey, sel.e.x = sel.ex;
1232 tnewline(int first_col) {
1236 tscrollup(term.top, 1);
1240 tmoveto(first_col ? 0 : term.c.x, y);
1245 /* int noarg = 1; */
1246 char *p = csiescseq.buf;
1250 csiescseq.priv = 1, p++;
1252 while(p < csiescseq.buf+csiescseq.len) {
1253 while(isdigit(*p)) {
1254 csiescseq.arg[csiescseq.narg] *= 10;
1255 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1257 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1258 csiescseq.narg++, p++;
1260 csiescseq.mode = *p;
1268 /* for absolute user moves, when decom is set */
1270 tmoveato(int x, int y) {
1271 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1275 tmoveto(int x, int y) {
1278 if(term.c.state & CURSOR_ORIGIN) {
1283 maxy = term.row - 1;
1285 LIMIT(x, 0, term.col-1);
1286 LIMIT(y, miny, maxy);
1287 term.c.state &= ~CURSOR_WRAPNEXT;
1293 tsetchar(char *c, Glyph *attr, int x, int y) {
1294 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1295 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1296 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1297 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1298 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1299 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1300 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1301 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1302 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1306 * The table is proudly stolen from rxvt.
1308 if(attr->mode & ATTR_GFX) {
1309 if(c[0] >= 0x41 && c[0] <= 0x7e
1310 && vt100_0[c[0] - 0x41]) {
1311 c = vt100_0[c[0] - 0x41];
1316 term.line[y][x] = *attr;
1317 memcpy(term.line[y][x].c, c, UTF_SIZ);
1318 term.line[y][x].state |= GLYPH_SET;
1322 tclearregion(int x1, int y1, int x2, int y2, int bce) {
1326 temp = x1, x1 = x2, x2 = temp;
1328 temp = y1, y1 = y2, y2 = temp;
1330 LIMIT(x1, 0, term.col-1);
1331 LIMIT(x2, 0, term.col-1);
1332 LIMIT(y1, 0, term.row-1);
1333 LIMIT(y2, 0, term.row-1);
1335 for(y = y1; y <= y2; y++) {
1337 for(x = x1; x <= x2; x++) {
1339 term.line[y][x] = term.c.attr;
1340 memcpy(term.line[y][x].c, " ", 2);
1341 term.line[y][x].state |= GLYPH_SET;
1343 term.line[y][x].state = 0;
1350 tdeletechar(int n) {
1351 int src = term.c.x + n;
1353 int size = term.col - src;
1355 term.dirty[term.c.y] = 1;
1357 if(src >= term.col) {
1358 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 0);
1362 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1363 size * sizeof(Glyph));
1364 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y, 0);
1368 tinsertblank(int n) {
1371 int size = term.col - dst;
1373 term.dirty[term.c.y] = 1;
1375 if(dst >= term.col) {
1376 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 0);
1380 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1381 size * sizeof(Glyph));
1382 tclearregion(src, term.c.y, dst - 1, term.c.y, 0);
1386 tinsertblankline(int n) {
1387 if(term.c.y < term.top || term.c.y > term.bot)
1390 tscrolldown(term.c.y, n);
1394 tdeleteline(int n) {
1395 if(term.c.y < term.top || term.c.y > term.bot)
1398 tscrollup(term.c.y, n);
1402 tsetattr(int *attr, int l) {
1405 for(i = 0; i < l; i++) {
1408 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1409 | ATTR_ITALIC | ATTR_BLINK);
1410 term.c.attr.fg = defaultfg;
1411 term.c.attr.bg = defaultbg;
1414 term.c.attr.mode |= ATTR_BOLD;
1417 term.c.attr.mode |= ATTR_ITALIC;
1420 term.c.attr.mode |= ATTR_UNDERLINE;
1422 case 5: /* slow blink */
1423 case 6: /* rapid blink */
1424 term.c.attr.mode |= ATTR_BLINK;
1427 term.c.attr.mode |= ATTR_REVERSE;
1431 term.c.attr.mode &= ~ATTR_BOLD;
1434 term.c.attr.mode &= ~ATTR_ITALIC;
1437 term.c.attr.mode &= ~ATTR_UNDERLINE;
1441 term.c.attr.mode &= ~ATTR_BLINK;
1444 term.c.attr.mode &= ~ATTR_REVERSE;
1447 if(i + 2 < l && attr[i + 1] == 5) {
1449 if(BETWEEN(attr[i], 0, 255)) {
1450 term.c.attr.fg = attr[i];
1453 "erresc: bad fgcolor %d\n",
1458 "erresc(38): gfx attr %d unknown\n",
1463 term.c.attr.fg = defaultfg;
1466 if(i + 2 < l && attr[i + 1] == 5) {
1468 if(BETWEEN(attr[i], 0, 255)) {
1469 term.c.attr.bg = attr[i];
1472 "erresc: bad bgcolor %d\n",
1477 "erresc(48): gfx attr %d unknown\n",
1482 term.c.attr.bg = defaultbg;
1485 if(BETWEEN(attr[i], 30, 37)) {
1486 term.c.attr.fg = attr[i] - 30;
1487 } else if(BETWEEN(attr[i], 40, 47)) {
1488 term.c.attr.bg = attr[i] - 40;
1489 } else if(BETWEEN(attr[i], 90, 97)) {
1490 term.c.attr.fg = attr[i] - 90 + 8;
1491 } else if(BETWEEN(attr[i], 100, 107)) {
1492 term.c.attr.bg = attr[i] - 100 + 8;
1495 "erresc(default): gfx attr %d unknown\n",
1496 attr[i]), csidump();
1504 tsetscroll(int t, int b) {
1507 LIMIT(t, 0, term.row-1);
1508 LIMIT(b, 0, term.row-1);
1518 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1521 tsetmode(bool priv, bool set, int *args, int narg) {
1525 for(lim = args + narg; args < lim; ++args) {
1529 case 1: /* DECCKM -- Cursor key */
1530 MODBIT(term.mode, set, MODE_APPCURSOR);
1532 case 5: /* DECSCNM -- Reverse video */
1534 MODBIT(term.mode, set, MODE_REVERSE);
1535 if(mode != term.mode)
1536 redraw(REDRAW_TIMEOUT);
1538 case 6: /* DECOM -- Origin */
1539 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1542 case 7: /* DECAWM -- Auto wrap */
1543 MODBIT(term.mode, set, MODE_WRAP);
1545 case 0: /* Error (IGNORED) */
1546 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1547 case 3: /* DECCOLM -- Column (IGNORED) */
1548 case 4: /* DECSCLM -- Scroll (IGNORED) */
1549 case 8: /* DECARM -- Auto repeat (IGNORED) */
1550 case 18: /* DECPFF -- Printer feed (IGNORED) */
1551 case 19: /* DECPEX -- Printer extent (IGNORED) */
1552 case 42: /* DECNRCM -- National characters (IGNORED) */
1553 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1555 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1556 MODBIT(term.mode, !set, MODE_HIDE);
1558 case 1000: /* 1000,1002: enable xterm mouse report */
1559 MODBIT(term.mode, set, MODE_MOUSEBTN);
1560 MODBIT(term.mode, 0, MODE_MOUSEMOTION);
1563 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1564 MODBIT(term.mode, 0, MODE_MOUSEBTN);
1567 MODBIT(term.mode, set, MODE_MOUSESGR);
1569 case 1049: /* = 1047 and 1048 */
1572 alt = IS_SET(MODE_ALTSCREEN);
1574 tclearregion(0, 0, term.col-1,
1577 if(set ^ alt) /* set is always 1 or 0 */
1584 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1588 "erresc: unknown private set/reset mode %d\n",
1594 case 0: /* Error (IGNORED) */
1596 case 2: /* KAM -- keyboard action */
1597 MODBIT(term.mode, set, MODE_KBDLOCK);
1599 case 4: /* IRM -- Insertion-replacement */
1600 MODBIT(term.mode, set, MODE_INSERT);
1602 case 12: /* SRM -- Send/Receive */
1603 MODBIT(term.mode, !set, MODE_ECHO);
1605 case 20: /* LNM -- Linefeed/new line */
1606 MODBIT(term.mode, set, MODE_CRLF);
1610 "erresc: unknown set/reset mode %d\n",
1622 switch(csiescseq.mode) {
1625 fprintf(stderr, "erresc: unknown csi ");
1629 case '@': /* ICH -- Insert <n> blank char */
1630 DEFAULT(csiescseq.arg[0], 1);
1631 tinsertblank(csiescseq.arg[0]);
1633 case 'A': /* CUU -- Cursor <n> Up */
1634 DEFAULT(csiescseq.arg[0], 1);
1635 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1637 case 'B': /* CUD -- Cursor <n> Down */
1638 case 'e': /* VPR --Cursor <n> Down */
1639 DEFAULT(csiescseq.arg[0], 1);
1640 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1642 case 'c': /* DA -- Device Attributes */
1643 if(csiescseq.arg[0] == 0)
1644 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1646 case 'C': /* CUF -- Cursor <n> Forward */
1647 case 'a': /* HPR -- Cursor <n> Forward */
1648 DEFAULT(csiescseq.arg[0], 1);
1649 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1651 case 'D': /* CUB -- Cursor <n> Backward */
1652 DEFAULT(csiescseq.arg[0], 1);
1653 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1655 case 'E': /* CNL -- Cursor <n> Down and first col */
1656 DEFAULT(csiescseq.arg[0], 1);
1657 tmoveto(0, term.c.y+csiescseq.arg[0]);
1659 case 'F': /* CPL -- Cursor <n> Up and first col */
1660 DEFAULT(csiescseq.arg[0], 1);
1661 tmoveto(0, term.c.y-csiescseq.arg[0]);
1663 case 'g': /* TBC -- Tabulation clear */
1664 switch (csiescseq.arg[0]) {
1665 case 0: /* clear current tab stop */
1666 term.tabs[term.c.x] = 0;
1668 case 3: /* clear all the tabs */
1669 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1675 case 'G': /* CHA -- Move to <col> */
1677 DEFAULT(csiescseq.arg[0], 1);
1678 tmoveto(csiescseq.arg[0]-1, term.c.y);
1680 case 'H': /* CUP -- Move to <row> <col> */
1682 DEFAULT(csiescseq.arg[0], 1);
1683 DEFAULT(csiescseq.arg[1], 1);
1684 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1686 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1687 DEFAULT(csiescseq.arg[0], 1);
1688 while(csiescseq.arg[0]--)
1691 case 'J': /* ED -- Clear screen */
1693 switch(csiescseq.arg[0]) {
1695 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 1);
1696 if(term.c.y < term.row-1) {
1697 tclearregion(0, term.c.y+1, term.col-1,
1703 tclearregion(0, 0, term.col-1, term.c.y-1, 1);
1704 tclearregion(0, term.c.y, term.c.x, term.c.y, 1);
1707 tclearregion(0, 0, term.col-1, term.row-1, 1);
1713 case 'K': /* EL -- Clear line */
1714 switch(csiescseq.arg[0]) {
1716 tclearregion(term.c.x, term.c.y, term.col-1,
1720 tclearregion(0, term.c.y, term.c.x, term.c.y, 1);
1723 tclearregion(0, term.c.y, term.col-1, term.c.y, 1);
1727 case 'S': /* SU -- Scroll <n> line up */
1728 DEFAULT(csiescseq.arg[0], 1);
1729 tscrollup(term.top, csiescseq.arg[0]);
1731 case 'T': /* SD -- Scroll <n> line down */
1732 DEFAULT(csiescseq.arg[0], 1);
1733 tscrolldown(term.top, csiescseq.arg[0]);
1735 case 'L': /* IL -- Insert <n> blank lines */
1736 DEFAULT(csiescseq.arg[0], 1);
1737 tinsertblankline(csiescseq.arg[0]);
1739 case 'l': /* RM -- Reset Mode */
1740 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1742 case 'M': /* DL -- Delete <n> lines */
1743 DEFAULT(csiescseq.arg[0], 1);
1744 tdeleteline(csiescseq.arg[0]);
1746 case 'X': /* ECH -- Erase <n> char */
1747 DEFAULT(csiescseq.arg[0], 1);
1748 tclearregion(term.c.x, term.c.y,
1749 term.c.x + csiescseq.arg[0] - 1, term.c.y, 1);
1751 case 'P': /* DCH -- Delete <n> char */
1752 DEFAULT(csiescseq.arg[0], 1);
1753 tdeletechar(csiescseq.arg[0]);
1755 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1756 DEFAULT(csiescseq.arg[0], 1);
1757 while(csiescseq.arg[0]--)
1760 case 'd': /* VPA -- Move to <row> */
1761 DEFAULT(csiescseq.arg[0], 1);
1762 tmoveato(term.c.x, csiescseq.arg[0]-1);
1764 case 'h': /* SM -- Set terminal mode */
1765 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1767 case 'm': /* SGR -- Terminal attribute (color) */
1768 tsetattr(csiescseq.arg, csiescseq.narg);
1770 case 'r': /* DECSTBM -- Set Scrolling Region */
1771 if(csiescseq.priv) {
1774 DEFAULT(csiescseq.arg[0], 1);
1775 DEFAULT(csiescseq.arg[1], term.row);
1776 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1780 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1781 tcursor(CURSOR_SAVE);
1783 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1784 tcursor(CURSOR_LOAD);
1795 for(i = 0; i < csiescseq.len; i++) {
1796 c = csiescseq.buf[i] & 0xff;
1799 } else if(c == '\n') {
1801 } else if(c == '\r') {
1803 } else if(c == 0x1b) {
1806 printf("(%02x)", c);
1814 memset(&csiescseq, 0, sizeof(csiescseq));
1822 * TODO: make this being useful in case of color palette change.
1828 switch(strescseq.type) {
1829 case ']': /* OSC -- Operating System Command */
1835 * TODO: Handle special chars in string, like umlauts.
1838 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1842 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1844 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1847 fprintf(stderr, "erresc: unknown str ");
1852 case 'k': /* old title set compatibility */
1853 XStoreName(xw.dpy, xw.win, strescseq.buf);
1855 case 'P': /* DSC -- Device Control String */
1856 case '_': /* APC -- Application Program Command */
1857 case '^': /* PM -- Privacy Message */
1859 fprintf(stderr, "erresc: unknown str ");
1869 * TODO: Implement parsing like for CSI when required.
1870 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1880 printf("ESC%c", strescseq.type);
1881 for(i = 0; i < strescseq.len; i++) {
1882 c = strescseq.buf[i] & 0xff;
1885 } else if(c == '\n') {
1887 } else if(c == '\r') {
1889 } else if(c == 0x1b) {
1892 printf("(%02x)", c);
1900 memset(&strescseq, 0, sizeof(strescseq));
1904 tputtab(bool forward) {
1910 for(++x; x < term.col && !term.tabs[x]; ++x)
1915 for(--x; x > 0 && !term.tabs[x]; --x)
1918 tmoveto(x, term.c.y);
1922 techo(char *buf, int len) {
1923 for(; len > 0; buf++, len--) {
1926 if(c == '\033') { /* escape */
1929 } else if (c < '\x20') { /* control code */
1930 if(c != '\n' && c != '\r' && c != '\t') {
1944 tputc(char *c, int len) {
1946 bool control = ascii < '\x20' || ascii == 0177;
1949 if (xwrite(iofd, c, len) < 0) {
1950 fprintf(stderr, "Error writing in %s:%s\n",
1951 opt_io, strerror(errno));
1958 * STR sequences must be checked before anything else
1959 * because it can use some control codes as part of the sequence.
1961 if(term.esc & ESC_STR) {
1964 term.esc = ESC_START | ESC_STR_END;
1966 case '\a': /* backwards compatibility to xterm */
1971 if(strescseq.len + len < sizeof(strescseq.buf)) {
1972 memmove(&strescseq.buf[strescseq.len], c, len);
1973 strescseq.len += len;
1976 * Here is a bug in terminals. If the user never sends
1977 * some code to stop the str or esc command, then st
1978 * will stop responding. But this is better than
1979 * silently failing with unknown characters. At least
1980 * then users will report back.
1982 * In the case users ever get fixed, here is the code:
1994 * Actions of control codes must be performed as soon they arrive
1995 * because they can be embedded inside a control sequence, and
1996 * they must not cause conflicts with sequences.
2004 tmoveto(term.c.x-1, term.c.y);
2007 tmoveto(0, term.c.y);
2012 /* go to first col if the mode is set */
2013 tnewline(IS_SET(MODE_CRLF));
2015 case '\a': /* BEL */
2016 if(!(xw.state & WIN_FOCUSED))
2019 case '\033': /* ESC */
2021 term.esc = ESC_START;
2023 case '\016': /* SO */
2024 case '\017': /* SI */
2026 * Different charsets are hard to handle. Applications
2027 * should use the right alt charset escapes for the
2028 * only reason they still exist: line drawing. The
2029 * rest is incompatible history st should not support.
2032 case '\032': /* SUB */
2033 case '\030': /* CAN */
2036 case '\005': /* ENQ (IGNORED) */
2037 case '\000': /* NUL (IGNORED) */
2038 case '\021': /* XON (IGNORED) */
2039 case '\023': /* XOFF (IGNORED) */
2040 case 0177: /* DEL (IGNORED) */
2043 } else if(term.esc & ESC_START) {
2044 if(term.esc & ESC_CSI) {
2045 csiescseq.buf[csiescseq.len++] = ascii;
2046 if(BETWEEN(ascii, 0x40, 0x7E)
2047 || csiescseq.len >= ESC_BUF_SIZ) {
2049 csiparse(), csihandle();
2051 } else if(term.esc & ESC_STR_END) {
2055 } else if(term.esc & ESC_ALTCHARSET) {
2057 case '0': /* Line drawing set */
2058 term.c.attr.mode |= ATTR_GFX;
2060 case 'B': /* USASCII */
2061 term.c.attr.mode &= ~ATTR_GFX;
2063 case 'A': /* UK (IGNORED) */
2064 case '<': /* multinational charset (IGNORED) */
2065 case '5': /* Finnish (IGNORED) */
2066 case 'C': /* Finnish (IGNORED) */
2067 case 'K': /* German (IGNORED) */
2070 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2073 } else if(term.esc & ESC_TEST) {
2074 if(ascii == '8') { /* DEC screen alignment test. */
2075 char E[UTF_SIZ] = "E";
2078 for(x = 0; x < term.col; ++x) {
2079 for(y = 0; y < term.row; ++y)
2080 tsetchar(E, &term.c.attr, x, y);
2087 term.esc |= ESC_CSI;
2090 term.esc |= ESC_TEST;
2092 case 'P': /* DCS -- Device Control String */
2093 case '_': /* APC -- Application Program Command */
2094 case '^': /* PM -- Privacy Message */
2095 case ']': /* OSC -- Operating System Command */
2096 case 'k': /* old title set compatibility */
2098 strescseq.type = ascii;
2099 term.esc |= ESC_STR;
2101 case '(': /* set primary charset G0 */
2102 term.esc |= ESC_ALTCHARSET;
2104 case ')': /* set secondary charset G1 (IGNORED) */
2105 case '*': /* set tertiary charset G2 (IGNORED) */
2106 case '+': /* set quaternary charset G3 (IGNORED) */
2109 case 'D': /* IND -- Linefeed */
2110 if(term.c.y == term.bot) {
2111 tscrollup(term.top, 1);
2113 tmoveto(term.c.x, term.c.y+1);
2117 case 'E': /* NEL -- Next line */
2118 tnewline(1); /* always go to first col */
2121 case 'H': /* HTS -- Horizontal tab stop */
2122 term.tabs[term.c.x] = 1;
2125 case 'M': /* RI -- Reverse index */
2126 if(term.c.y == term.top) {
2127 tscrolldown(term.top, 1);
2129 tmoveto(term.c.x, term.c.y-1);
2133 case 'Z': /* DECID -- Identify Terminal */
2134 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2137 case 'c': /* RIS -- Reset to inital state */
2142 case '=': /* DECPAM -- Application keypad */
2143 term.mode |= MODE_APPKEYPAD;
2146 case '>': /* DECPNM -- Normal keypad */
2147 term.mode &= ~MODE_APPKEYPAD;
2150 case '7': /* DECSC -- Save Cursor */
2151 tcursor(CURSOR_SAVE);
2154 case '8': /* DECRC -- Restore Cursor */
2155 tcursor(CURSOR_LOAD);
2158 case '\\': /* ST -- Stop */
2162 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2163 (uchar) ascii, isprint(ascii)? ascii:'.');
2168 * All characters which form part of a sequence are not
2174 * Display control codes only if we are in graphic mode
2176 if(control && !(term.c.attr.mode & ATTR_GFX))
2178 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2180 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
2181 tnewline(1); /* always go to first col */
2183 if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2184 memmove(&term.line[term.c.y][term.c.x+1],
2185 &term.line[term.c.y][term.c.x],
2186 (term.col - term.c.x - 1) * sizeof(Glyph));
2189 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2190 if(term.c.x+1 < term.col) {
2191 tmoveto(term.c.x+1, term.c.y);
2193 term.c.state |= CURSOR_WRAPNEXT;
2198 tresize(int col, int row) {
2200 int minrow = MIN(row, term.row);
2201 int mincol = MIN(col, term.col);
2202 int slide = term.c.y - row + 1;
2205 if(col < 1 || row < 1)
2208 /* free unneeded rows */
2212 * slide screen to keep cursor where we expect it -
2213 * tscrollup would work here, but we can optimize to
2214 * memmove because we're freeing the earlier lines
2216 for(/* i = 0 */; i < slide; i++) {
2220 memmove(term.line, term.line + slide, row * sizeof(Line));
2221 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2223 for(i += row; i < term.row; i++) {
2228 /* resize to new height */
2229 term.line = xrealloc(term.line, row * sizeof(Line));
2230 term.alt = xrealloc(term.alt, row * sizeof(Line));
2231 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2232 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2234 /* resize each row to new width, zero-pad if needed */
2235 for(i = 0; i < minrow; i++) {
2237 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2238 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2239 for(x = mincol; x < col; x++) {
2240 term.line[i][x].state = 0;
2241 term.alt[i][x].state = 0;
2245 /* allocate any new rows */
2246 for(/* i == minrow */; i < row; i++) {
2248 term.line[i] = xcalloc(col, sizeof(Glyph));
2249 term.alt [i] = xcalloc(col, sizeof(Glyph));
2251 if(col > term.col) {
2252 bp = term.tabs + term.col;
2254 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2255 while(--bp > term.tabs && !*bp)
2257 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2260 /* update terminal size */
2263 /* reset scrolling region */
2264 tsetscroll(0, row-1);
2265 /* make use of the LIMIT in tmoveto */
2266 tmoveto(term.c.x, term.c.y);
2272 xresize(int col, int row) {
2273 xw.tw = MAX(1, col * xw.cw);
2274 xw.th = MAX(1, row * xw.ch);
2277 XFreePixmap(xw.dpy, xw.buf);
2278 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2279 DefaultDepth(xw.dpy, xw.scr));
2280 XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg].pixel);
2281 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2284 XftDrawChange(xw.draw, xw.buf);
2290 XRenderColor color = { .alpha = 0 };
2292 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2293 for(i = 0; i < LEN(colorname); i++) {
2296 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2297 die("Could not allocate color '%s'\n", colorname[i]);
2301 /* load colors [16-255] ; same colors as xterm */
2302 for(i = 16, r = 0; r < 6; r++) {
2303 for(g = 0; g < 6; g++) {
2304 for(b = 0; b < 6; b++) {
2305 color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
2306 color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
2307 color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
2308 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2309 die("Could not allocate color %d\n", i);
2316 for(r = 0; r < 24; r++, i++) {
2317 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2318 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2320 die("Could not allocate color %d\n", i);
2326 xtermclear(int col1, int row1, int col2, int row2) {
2327 XftDrawRect(xw.draw,
2328 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2329 borderpx + col1 * xw.cw,
2330 borderpx + row1 * xw.ch,
2331 (col2-col1+1) * xw.cw,
2332 (row2-row1+1) * xw.ch);
2336 * Absolute coordinates.
2339 xclear(int x1, int y1, int x2, int y2) {
2340 XftDrawRect(xw.draw,
2341 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2342 x1, y1, x2-x1, y2-y1);
2347 XClassHint class = {opt_class ? opt_class : termname, termname};
2348 XWMHints wm = {.flags = InputHint, .input = 1};
2349 XSizeHints *sizeh = NULL;
2351 sizeh = XAllocSizeHints();
2352 if(xw.isfixed == False) {
2353 sizeh->flags = PSize | PResizeInc | PBaseSize;
2354 sizeh->height = xw.h;
2355 sizeh->width = xw.w;
2356 sizeh->height_inc = xw.ch;
2357 sizeh->width_inc = xw.cw;
2358 sizeh->base_height = 2 * borderpx;
2359 sizeh->base_width = 2 * borderpx;
2361 sizeh->flags = PMaxSize | PMinSize;
2362 sizeh->min_width = sizeh->max_width = xw.fw;
2363 sizeh->min_height = sizeh->max_height = xw.fh;
2366 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2371 xloadfont(Font *f, FcPattern *pattern) {
2375 match = FcFontMatch(NULL, pattern, &result);
2379 if(!(f->set = FcFontSort(0, match, FcTrue, 0, &result))) {
2380 FcPatternDestroy(match);
2384 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2385 FcPatternDestroy(match);
2389 f->pattern = FcPatternDuplicate(pattern);
2391 f->ascent = f->match->ascent;
2392 f->descent = f->match->descent;
2394 f->rbearing = f->match->max_advance_width;
2396 f->height = f->match->height;
2397 f->width = f->lbearing + f->rbearing;
2403 xloadfonts(char *fontstr, int fontsize) {
2408 if(fontstr[0] == '-') {
2409 pattern = XftXlfdParse(fontstr, False, False);
2411 pattern = FcNameParse((FcChar8 *)fontstr);
2415 die("st: can't open font %s\n", fontstr);
2418 FcPatternDel(pattern, FC_PIXEL_SIZE);
2419 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2420 usedfontsize = fontsize;
2422 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2423 if(result == FcResultMatch) {
2424 usedfontsize = (int)fontval;
2427 * Default font size is 12, if none given. This is to
2428 * have a known usedfontsize value.
2430 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2435 FcConfigSubstitute(0, pattern, FcMatchPattern);
2436 FcDefaultSubstitute(pattern);
2438 if(xloadfont(&dc.font, pattern))
2439 die("st: can't open font %s\n", fontstr);
2441 /* Setting character width and height. */
2442 xw.cw = dc.font.width;
2443 xw.ch = dc.font.height;
2445 FcPatternDel(pattern, FC_SLANT);
2446 FcPatternDel(pattern, FC_WEIGHT);
2447 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2448 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2449 if(xloadfont(&dc.bfont, pattern))
2450 die("st: can't open font %s\n", fontstr);
2452 FcPatternDel(pattern, FC_SLANT);
2453 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2454 if(xloadfont(&dc.ibfont, pattern))
2455 die("st: can't open font %s\n", fontstr);
2457 FcPatternDel(pattern, FC_WEIGHT);
2458 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_MEDIUM);
2459 if(xloadfont(&dc.ifont, pattern))
2460 die("st: can't open font %s\n", fontstr);
2462 FcPatternDestroy(pattern);
2466 xunloadfonts(void) {
2470 * Free the loaded fonts in the font cache. This is done backwards
2473 for (i = 0, ip = frccur; i < frclen; i++, ip--) {
2476 XftFontClose(xw.dpy, frc[ip].font);
2481 XftFontClose(xw.dpy, dc.font.match);
2482 FcPatternDestroy(dc.font.pattern);
2483 FcFontSetDestroy(dc.font.set);
2484 XftFontClose(xw.dpy, dc.bfont.match);
2485 FcPatternDestroy(dc.bfont.pattern);
2486 FcFontSetDestroy(dc.bfont.set);
2487 XftFontClose(xw.dpy, dc.ifont.match);
2488 FcPatternDestroy(dc.ifont.pattern);
2489 FcFontSetDestroy(dc.ifont.set);
2490 XftFontClose(xw.dpy, dc.ibfont.match);
2491 FcPatternDestroy(dc.ibfont.pattern);
2492 FcFontSetDestroy(dc.ibfont.set);
2496 xzoom(const Arg *arg) {
2498 xloadfonts(usedfont, usedfontsize + arg->i);
2505 XSetWindowAttributes attrs;
2509 int sw, sh, major, minor;
2511 if(!(xw.dpy = XOpenDisplay(NULL)))
2512 die("Can't open display\n");
2513 xw.scr = XDefaultScreen(xw.dpy);
2514 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2518 die("Could not init fontconfig.\n");
2520 usedfont = (opt_font == NULL)? font : opt_font;
2521 xloadfonts(usedfont, 0);
2524 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2527 /* adjust fixed window geometry */
2529 sw = DisplayWidth(xw.dpy, xw.scr);
2530 sh = DisplayHeight(xw.dpy, xw.scr);
2532 xw.fx = sw + xw.fx - xw.fw - 1;
2534 xw.fy = sh + xw.fy - xw.fh - 1;
2539 /* window - default size */
2540 xw.h = 2 * borderpx + term.row * xw.ch;
2541 xw.w = 2 * borderpx + term.col * xw.cw;
2547 attrs.background_pixel = dc.col[defaultbg].pixel;
2548 attrs.border_pixel = dc.col[defaultbg].pixel;
2549 attrs.bit_gravity = NorthWestGravity;
2550 attrs.event_mask = FocusChangeMask | KeyPressMask
2551 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2552 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2553 attrs.colormap = xw.cmap;
2555 parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2556 XRootWindow(xw.dpy, xw.scr);
2557 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2558 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2560 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2564 /* double buffering */
2566 if(XdbeQueryExtension(xw.dpy, &major, &minor)) {
2567 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win,
2572 memset(&gcvalues, 0, sizeof(gcvalues));
2573 gcvalues.graphics_exposures = False;
2574 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2576 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2577 DefaultDepth(xw.dpy, xw.scr));
2578 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
2579 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2585 /* Xft rendering context */
2586 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2589 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2590 XSetLocaleModifiers("@im=local");
2591 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2592 XSetLocaleModifiers("@im=");
2593 if((xw.xim = XOpenIM(xw.dpy,
2594 NULL, NULL, NULL)) == NULL) {
2595 die("XOpenIM failed. Could not open input"
2600 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2601 | XIMStatusNothing, XNClientWindow, xw.win,
2602 XNFocusWindow, xw.win, NULL);
2604 die("XCreateIC failed. Could not obtain input method.\n");
2606 /* white cursor, black outline */
2607 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2608 XDefineCursor(xw.dpy, xw.win, cursor);
2609 XRecolorCursor(xw.dpy, cursor,
2610 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2611 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2613 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2614 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2615 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2618 XMapWindow(xw.dpy, xw.win);
2624 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2625 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2626 width = charlen * xw.cw, xp, i;
2628 int u8fl, u8fblen, u8cblen, doesexist;
2631 Font *font = &dc.font;
2633 FcPattern *fcpattern, *fontpattern;
2634 FcFontSet *fcsets[] = { NULL };
2635 FcCharSet *fccharset;
2636 Colour *fg = &dc.col[base.fg], *bg = &dc.col[base.bg],
2637 *temp, revfg, revbg;
2638 XRenderColor colfg, colbg;
2640 frcflags = FRC_NORMAL;
2642 if(base.mode & ATTR_BOLD) {
2643 if(BETWEEN(base.fg, 0, 7)) {
2644 /* basic system colors */
2645 fg = &dc.col[base.fg + 8];
2646 } else if(BETWEEN(base.fg, 16, 195)) {
2648 fg = &dc.col[base.fg + 36];
2649 } else if(BETWEEN(base.fg, 232, 251)) {
2651 fg = &dc.col[base.fg + 4];
2654 * Those ranges will not be brightened:
2655 * 8 - 15 – bright system colors
2656 * 196 - 231 – highest 256 color cube
2657 * 252 - 255 – brightest colors in greyscale
2660 frcflags = FRC_BOLD;
2663 if(base.mode & ATTR_ITALIC) {
2665 frcflags = FRC_ITALIC;
2667 if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
2669 frcflags = FRC_ITALICBOLD;
2672 if(IS_SET(MODE_REVERSE)) {
2673 if(fg == &dc.col[defaultfg]) {
2674 fg = &dc.col[defaultbg];
2676 colfg.red = ~fg->color.red;
2677 colfg.green = ~fg->color.green;
2678 colfg.blue = ~fg->color.blue;
2679 colfg.alpha = fg->color.alpha;
2680 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2684 if(bg == &dc.col[defaultbg]) {
2685 bg = &dc.col[defaultfg];
2687 colbg.red = ~bg->color.red;
2688 colbg.green = ~bg->color.green;
2689 colbg.blue = ~bg->color.blue;
2690 colbg.alpha = bg->color.alpha;
2691 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2696 if(base.mode & ATTR_REVERSE) {
2702 /* Intelligent cleaning up of the borders. */
2704 xclear(0, (y == 0)? 0 : winy, borderpx,
2705 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
2707 if(x + charlen >= term.col) {
2708 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2709 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
2712 xclear(winx, 0, winx + width, borderpx);
2714 xclear(winx, winy + xw.ch, winx + width, xw.h);
2716 /* Clean up the region we want to draw to. */
2717 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
2719 fcsets[0] = font->set;
2720 for (xp = winx; bytelen > 0;) {
2722 * Search for the range in the to be printed string of glyphs
2723 * that are in the main font. Then print that range. If
2724 * some glyph is found that is not in the font, do the
2732 u8cblen = utf8decode(s, &u8char);
2736 doesexist = XftCharIndex(xw.dpy, font->match, u8char);
2737 if (!doesexist || bytelen <= 0) {
2746 XftDrawStringUtf8(xw.draw, fg,
2748 winy + font->ascent,
2751 xp += font->width * u8fl;
2763 /* Search the font cache. */
2764 for (i = 0; i < frclen; i++, frp--) {
2768 if (frc[frp].c == u8char
2769 && frc[frp].flags == frcflags) {
2774 /* Nothing was found. */
2777 * Nothing was found in the cache. Now use
2778 * some dozen of Fontconfig calls to get the
2779 * font for one single character.
2781 fcpattern = FcPatternDuplicate(font->pattern);
2782 fccharset = FcCharSetCreate();
2784 FcCharSetAddChar(fccharset, u8char);
2785 FcPatternAddCharSet(fcpattern, FC_CHARSET,
2787 FcPatternAddBool(fcpattern, FC_SCALABLE,
2790 FcConfigSubstitute(0, fcpattern,
2792 FcDefaultSubstitute(fcpattern);
2794 fontpattern = FcFontSetMatch(0, fcsets,
2795 FcTrue, fcpattern, &fcres);
2798 * Overwrite or create the new cache entry
2803 if (frccur >= LEN(frc))
2805 if (frclen > LEN(frc)) {
2807 XftFontClose(xw.dpy, frc[frccur].font);
2810 frc[frccur].font = XftFontOpenPattern(xw.dpy,
2812 frc[frccur].c = u8char;
2813 frc[frccur].flags = frcflags;
2815 FcPatternDestroy(fcpattern);
2816 FcCharSetDestroy(fccharset);
2821 XftDrawStringUtf8(xw.draw, fg, frc[frp].font,
2822 xp, winy + frc[frp].font->ascent,
2823 (FcChar8 *)u8c, u8cblen);
2829 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
2830 winy + font->ascent, (FcChar8 *)s, bytelen);
2833 if(base.mode & ATTR_UNDERLINE) {
2834 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
2841 static int oldx = 0, oldy = 0;
2843 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs, 0};
2845 LIMIT(oldx, 0, term.col-1);
2846 LIMIT(oldy, 0, term.row-1);
2848 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2849 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2851 /* remove the old cursor */
2852 if(term.line[oldy][oldx].state & GLYPH_SET) {
2853 sl = utf8size(term.line[oldy][oldx].c);
2854 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2857 xtermclear(oldx, oldy, oldx, oldy);
2860 /* draw the new one */
2861 if(!(IS_SET(MODE_HIDE))) {
2862 if(!(xw.state & WIN_FOCUSED))
2865 if(IS_SET(MODE_REVERSE))
2866 g.mode |= ATTR_REVERSE, g.fg = defaultcs, g.bg = defaultfg;
2869 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2870 oldx = term.c.x, oldy = term.c.y;
2876 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2880 redraw(int timeout) {
2881 struct timespec tv = {0, timeout * 1000};
2887 nanosleep(&tv, NULL);
2888 XSync(xw.dpy, False); /* necessary for a good tput flash */
2894 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2896 drawregion(0, 0, term.col, term.row);
2898 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2900 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
2902 XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg].pixel);
2907 drawregion(int x1, int y1, int x2, int y2) {
2908 int ic, ib, x, y, ox, sl;
2910 char buf[DRAW_BUF_SIZ];
2911 bool ena_sel = sel.bx != -1;
2913 if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
2916 if(!(xw.state & WIN_VISIBLE))
2919 for(y = y1; y < y2; y++) {
2923 xtermclear(0, y, term.col, y);
2925 base = term.line[y][0];
2927 for(x = x1; x < x2; x++) {
2928 new = term.line[y][x];
2929 if(ena_sel && *(new.c) && selected(x, y))
2930 new.mode ^= ATTR_REVERSE;
2931 if(ib > 0 && (!(new.state & GLYPH_SET)
2932 || ATTRCMP(base, new)
2933 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2934 xdraws(buf, base, ox, y, ic, ib);
2937 if(new.state & GLYPH_SET) {
2943 sl = utf8size(new.c);
2944 memcpy(buf+ib, new.c, sl);
2950 xdraws(buf, base, ox, y, ic, ib);
2956 expose(XEvent *ev) {
2957 XExposeEvent *e = &ev->xexpose;
2959 if(xw.state & WIN_REDRAW) {
2961 xw.state &= ~WIN_REDRAW;
2967 visibility(XEvent *ev) {
2968 XVisibilityEvent *e = &ev->xvisibility;
2970 if(e->state == VisibilityFullyObscured) {
2971 xw.state &= ~WIN_VISIBLE;
2972 } else if(!(xw.state & WIN_VISIBLE)) {
2973 /* need a full redraw for next Expose, not just a buf copy */
2974 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2980 xw.state &= ~WIN_VISIBLE;
2984 xseturgency(int add) {
2985 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2987 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2988 XSetWMHints(xw.dpy, xw.win, h);
2994 XFocusChangeEvent *e = &ev->xfocus;
2996 if(e->mode == NotifyGrab)
2999 if(ev->type == FocusIn) {
3000 XSetICFocus(xw.xic);
3001 xw.state |= WIN_FOCUSED;
3004 XUnsetICFocus(xw.xic);
3005 xw.state &= ~WIN_FOCUSED;
3010 match(uint mask, uint state) {
3011 if(mask == XK_NO_MOD && state)
3013 if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
3015 if((state & mask) != state)
3021 numlock(const Arg *dummy) {
3026 kmap(KeySym k, uint state) {
3031 /* Check for mapped keys out of X11 function keys. */
3032 for(i = 0; i < LEN(mappedkeys); i++) {
3033 if(mappedkeys[i] == k)
3036 if(i == LEN(mappedkeys)) {
3037 if((k & 0xFFFF) < 0xFD00)
3041 for(kp = key; kp < key + LEN(key); kp++) {
3047 if(!match(mask, state))
3050 if(kp->appkey > 0) {
3051 if(!IS_SET(MODE_APPKEYPAD))
3053 if(term.numlock && kp->appkey == 2)
3055 } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
3059 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
3061 && !IS_SET(MODE_APPCURSOR))) {
3065 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
3066 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
3077 kpress(XEvent *ev) {
3078 XKeyEvent *e = &ev->xkey;
3080 char xstr[31], buf[32], *customkey, *cp = buf;
3085 if (IS_SET(MODE_KBDLOCK))
3088 len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
3089 e->state &= ~Mod2Mask;
3091 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3092 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3093 bp->func(&(bp->arg));
3098 /* 2. custom keys from config.h */
3099 if((customkey = kmap(ksym, e->state))) {
3100 len = strlen(customkey);
3101 memcpy(buf, customkey, len);
3102 /* 2. hardcoded (overrides X lookup) */
3107 if (len == 1 && e->state & Mod1Mask)
3110 memcpy(cp, xstr, len);
3111 len = cp - buf + len;
3115 if(IS_SET(MODE_ECHO))
3121 cmessage(XEvent *e) {
3124 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3126 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3127 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3128 xw.state |= WIN_FOCUSED;
3130 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3131 xw.state &= ~WIN_FOCUSED;
3133 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3134 /* Send SIGHUP to shell */
3141 cresize(int width, int height) {
3149 col = (xw.w - 2 * borderpx) / xw.cw;
3150 row = (xw.h - 2 * borderpx) / xw.ch;
3159 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3162 cresize(e->xconfigure.width, e->xconfigure.height);
3169 int xfd = XConnectionNumber(xw.dpy), xev;
3170 struct timeval drawtimeout, *tv = NULL, now, last;
3172 gettimeofday(&last, NULL);
3174 for(xev = actionfps;;) {
3176 FD_SET(cmdfd, &rfd);
3178 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3181 die("select failed: %s\n", SERRNO);
3184 gettimeofday(&now, NULL);
3185 drawtimeout.tv_sec = 0;
3186 drawtimeout.tv_usec = (1000/xfps) * 1000;
3189 if(FD_ISSET(cmdfd, &rfd))
3192 if(FD_ISSET(xfd, &rfd))
3195 if(TIMEDIFF(now, last) > \
3196 (xev ? (1000/xfps) : (1000/actionfps))) {
3197 while(XPending(xw.dpy)) {
3198 XNextEvent(xw.dpy, &ev);
3199 if(XFilterEvent(&ev, None))
3201 if(handler[ev.type])
3202 (handler[ev.type])(&ev);
3209 if(xev && !FD_ISSET(xfd, &rfd))
3211 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd))
3218 main(int argc, char *argv[]) {
3219 int i, bitm, xr, yr;
3222 xw.fw = xw.fh = xw.fx = xw.fy = 0;
3225 for(i = 1; i < argc; i++) {
3226 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
3229 opt_class = argv[i];
3232 /* eat all remaining arguments */
3244 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
3249 if(bitm & WidthValue)
3251 if(bitm & HeightValue)
3253 if(bitm & XNegative && xw.fx == 0)
3255 if(bitm & XNegative && xw.fy == 0)
3258 if(xw.fh != 0 && xw.fw != 0)
3267 opt_title = argv[i];
3274 opt_embed = argv[i];
3280 setlocale(LC_CTYPE, "");
3281 XSetLocaleModifiers("");