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
64 #define XK_SWITCH_MOD (1<<13)
66 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
69 #define SERRNO strerror(errno)
70 #define MIN(a, b) ((a) < (b) ? (a) : (b))
71 #define MAX(a, b) ((a) < (b) ? (b) : (a))
72 #define LEN(a) (sizeof(a) / sizeof(a[0]))
73 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
74 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
75 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
76 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
77 #define IS_SET(flag) ((term.mode & (flag)) != 0)
78 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
80 #define VT102ID "\033[?6c"
82 enum glyph_attribute {
92 enum cursor_movement {
115 MODE_MOUSEMOTION = 64,
121 MODE_APPCURSOR = 2048,
122 MODE_MOUSESGR = 4096,
128 ESC_STR = 4, /* DSC, OSC, PM, APC */
130 ESC_STR_END = 16, /* a final string was encountered */
131 ESC_TEST = 32, /* Enter in test mode */
140 enum selection_type {
147 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
149 typedef unsigned char uchar;
150 typedef unsigned int uint;
151 typedef unsigned long ulong;
152 typedef unsigned short ushort;
155 char c[UTF_SIZ]; /* character code */
156 uchar mode; /* attribute flags */
157 ushort fg; /* foreground */
158 ushort bg; /* background */
159 uchar state; /* state flags */
165 Glyph attr; /* current char attributes */
171 /* CSI Escape sequence structs */
172 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
174 char buf[ESC_BUF_SIZ]; /* raw string */
175 int len; /* raw string length */
177 int arg[ESC_ARG_SIZ];
178 int narg; /* nb of args */
182 /* STR Escape sequence structs */
183 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
185 char type; /* ESC type ... */
186 char buf[STR_BUF_SIZ]; /* raw string */
187 int len; /* raw string length */
188 char *args[STR_ARG_SIZ];
189 int narg; /* nb of args */
192 /* Internal representation of the screen */
194 int row; /* nb row */
195 int col; /* nb col */
196 Line *line; /* screen */
197 Line *alt; /* alternate screen */
198 bool *dirty; /* dirtyness of lines */
199 TCursor c; /* cursor */
200 int top; /* top scroll limit */
201 int bot; /* bottom scroll limit */
202 int mode; /* terminal mode flags */
203 int esc; /* escape state flags */
204 bool numlock; /* lock numbers in keyboard */
208 /* Purely graphic info */
214 Atom xembed, wmdeletewin;
220 bool isfixed; /* is fixed geometry? */
221 int fx, fy, fw, fh; /* fixed geometry */
222 int tw, th; /* tty width and height */
223 int w, h; /* window width and height */
224 int ch; /* char height */
225 int cw; /* char width */
226 char state; /* focus, redraw, visible */
233 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
234 signed char appkey; /* application keypad */
235 signed char appcursor; /* application cursor */
236 signed char crlf; /* crlf mode */
239 /* TODO: use better name for vars... */
251 struct timeval tclick1;
252 struct timeval tclick2;
265 void (*func)(const Arg *);
269 /* function definitions used in config.h */
270 static void xzoom(const Arg *);
271 static void selpaste(const Arg *);
272 static void numlock(const Arg *);
274 /* Config.h for applying patches and the configuration. */
290 /* Drawing Context */
292 Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
293 Font font, bfont, ifont, ibfont;
297 static void die(const char *, ...);
298 static void draw(void);
299 static void redraw(int);
300 static void drawregion(int, int, int, int);
301 static void execsh(void);
302 static void sigchld(int);
303 static void run(void);
305 static inline int parse_int(char *);
306 static void csidump(void);
307 static void csihandle(void);
308 static void csiparse(void);
309 static void csireset(void);
310 static void strdump(void);
311 static void strhandle(void);
312 static void strparse(void);
313 static void strreset(void);
315 static void tclearregion(int, int, int, int, int);
316 static void tcursor(int);
317 static void tdeletechar(int);
318 static void tdeleteline(int);
319 static void tinsertblank(int);
320 static void tinsertblankline(int);
321 static void tmoveto(int, int);
322 static void tmoveato(int x, int y);
323 static void tnew(int, int);
324 static void tnewline(int);
325 static void tputtab(bool);
326 static void tputc(char *, int);
327 static void treset(void);
328 static int tresize(int, int);
329 static void tscrollup(int, int);
330 static void tscrolldown(int, int);
331 static void tsetattr(int*, int);
332 static void tsetchar(char *, Glyph *, int, int);
333 static void tsetscroll(int, int);
334 static void tswapscreen(void);
335 static void tsetdirt(int, int);
336 static void tsetmode(bool, bool, int *, int);
337 static void tfulldirt(void);
338 static void techo(char *, int);
340 static inline bool match(uint, uint);
341 static void ttynew(void);
342 static void ttyread(void);
343 static void ttyresize(void);
344 static void ttywrite(const char *, size_t);
346 static void xdraws(char *, Glyph, int, int, int, int);
347 static void xhints(void);
348 static void xclear(int, int, int, int);
349 static void xdrawcursor(void);
350 static void xinit(void);
351 static void xloadcols(void);
352 static int xsetcolorname(int, const char *);
353 static int xloadfont(Font *, FcPattern *);
354 static void xloadfonts(char *, int);
355 static void xresettitle(void);
356 static void xseturgency(int);
357 static void xsetsel(char*);
358 static void xtermclear(int, int, int, int);
359 static void xunloadfonts(void);
360 static void xresize(int, int);
362 static void expose(XEvent *);
363 static void visibility(XEvent *);
364 static void unmap(XEvent *);
365 static char *kmap(KeySym, uint);
366 static void kpress(XEvent *);
367 static void cmessage(XEvent *);
368 static void cresize(int, int);
369 static void resize(XEvent *);
370 static void focus(XEvent *);
371 static void brelease(XEvent *);
372 static void bpress(XEvent *);
373 static void bmotion(XEvent *);
374 static void selnotify(XEvent *);
375 static void selclear(XEvent *);
376 static void selrequest(XEvent *);
378 static void selinit(void);
379 static inline bool selected(int, int);
380 static void selcopy(void);
381 static void selscroll(int, int);
383 static int utf8decode(char *, long *);
384 static int utf8encode(long *, char *);
385 static int utf8size(char *);
386 static int isfullutf8(char *, int);
388 static ssize_t xwrite(int, char *, size_t);
389 static void *xmalloc(size_t);
390 static void *xrealloc(void *, size_t);
391 static void *xcalloc(size_t, size_t);
393 static void (*handler[LASTEvent])(XEvent *) = {
395 [ClientMessage] = cmessage,
396 [ConfigureNotify] = resize,
397 [VisibilityNotify] = visibility,
398 [UnmapNotify] = unmap,
402 [MotionNotify] = bmotion,
403 [ButtonPress] = bpress,
404 [ButtonRelease] = brelease,
405 [SelectionClear] = selclear,
406 [SelectionNotify] = selnotify,
407 [SelectionRequest] = selrequest,
414 static CSIEscape csiescseq;
415 static STREscape strescseq;
418 static Selection sel;
419 static int iofd = -1;
420 static char **opt_cmd = NULL;
421 static char *opt_io = NULL;
422 static char *opt_title = NULL;
423 static char *opt_embed = NULL;
424 static char *opt_class = NULL;
425 static char *opt_font = NULL;
429 static char *usedfont = NULL;
430 static int usedfontsize = 0;
432 /* Font Ring Cache */
447 * Fontcache is a ring buffer, with frccur as current position and frclen as
448 * the current length of used elements.
451 static Fontcache frc[1024];
452 static int frccur = -1, frclen = 0;
455 xwrite(int fd, char *s, size_t len) {
459 ssize_t r = write(fd, s, len);
469 xmalloc(size_t len) {
470 void *p = malloc(len);
473 die("Out of memory\n");
479 xrealloc(void *p, size_t len) {
480 if((p = realloc(p, len)) == NULL)
481 die("Out of memory\n");
487 xcalloc(size_t nmemb, size_t size) {
488 void *p = calloc(nmemb, size);
491 die("Out of memory\n");
497 utf8decode(char *s, long *u) {
503 if(~c & B7) { /* 0xxxxxxx */
506 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
507 *u = c&(B4|B3|B2|B1|B0);
509 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
510 *u = c&(B3|B2|B1|B0);
512 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
519 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
521 if((c & (B7|B6)) != B7) /* 10xxxxxx */
524 *u |= c & (B5|B4|B3|B2|B1|B0);
527 if((n == 1 && *u < 0x80) ||
528 (n == 2 && *u < 0x800) ||
529 (n == 3 && *u < 0x10000) ||
530 (*u >= 0xD800 && *u <= 0xDFFF)) {
542 utf8encode(long *u, char *s) {
550 *sp = uc; /* 0xxxxxxx */
552 } else if(*u < 0x800) {
553 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
555 } else if(uc < 0x10000) {
556 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
558 } else if(uc <= 0x10FFFF) {
559 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
565 for(i=n,++sp; i>0; --i,++sp)
566 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
578 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
579 UTF-8 otherwise return 0 */
581 isfullutf8(char *s, int b) {
589 } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
591 } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
593 ((b == 2) && (*c2&(B7|B6)) == B7))) {
595 } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
597 ((b == 2) && (*c2&(B7|B6)) == B7) ||
598 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
611 } else if((c&(B7|B6|B5)) == (B7|B6)) {
613 } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
622 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
623 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
627 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
628 if(sel.xtarget == None)
629 sel.xtarget = XA_STRING;
637 return LIMIT(x, 0, term.col-1);
645 return LIMIT(y, 0, term.row-1);
649 selected(int x, int y) {
652 if(sel.ey == y && sel.by == y) {
653 bx = MIN(sel.bx, sel.ex);
654 ex = MAX(sel.bx, sel.ex);
655 return BETWEEN(x, bx, ex);
658 return ((sel.b.y < y && y < sel.e.y)
659 || (y == sel.e.y && x <= sel.e.x))
660 || (y == sel.b.y && x >= sel.b.x
661 && (x <= sel.e.x || sel.b.y != sel.e.y));
664 return ((sel.b.y < y && y < sel.e.y)
665 || (y == sel.e.y && x <= sel.e.x))
666 || (y == sel.b.y && x >= sel.b.x
667 && (x <= sel.e.x || sel.b.y != sel.e.y));
668 case SEL_RECTANGULAR:
669 return ((sel.b.y <= y && y <= sel.e.y)
670 && (sel.b.x <= x && x <= sel.e.x));
675 getbuttoninfo(XEvent *e) {
677 uint state = e->xbutton.state &~Button1Mask;
679 sel.alt = IS_SET(MODE_ALTSCREEN);
681 sel.ex = x2col(e->xbutton.x);
682 sel.ey = y2row(e->xbutton.y);
684 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
685 sel.b.y = MIN(sel.by, sel.ey);
686 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
687 sel.e.y = MAX(sel.by, sel.ey);
689 sel.type = SEL_REGULAR;
690 for(type = 1; type < LEN(selmasks); ++type) {
691 if(match(selmasks[type], state)) {
699 mousereport(XEvent *e) {
700 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
701 button = e->xbutton.button, state = e->xbutton.state,
704 static int ob, ox, oy;
707 if(e->xbutton.type == MotionNotify) {
708 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
712 } else if(!IS_SET(MODE_MOUSESGR)
713 && (e->xbutton.type == ButtonRelease
714 || button == AnyButton)) {
720 if(e->xbutton.type == ButtonPress) {
726 button += (state & ShiftMask ? 4 : 0)
727 + (state & Mod4Mask ? 8 : 0)
728 + (state & ControlMask ? 16 : 0);
731 if(IS_SET(MODE_MOUSESGR)) {
732 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
734 e->xbutton.type == ButtonRelease ? 'm' : 'M');
735 } else if(x < 223 && y < 223) {
736 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
737 32+button, 32+x+1, 32+y+1);
747 if(IS_SET(MODE_MOUSE)) {
749 } else if(e->xbutton.button == Button1) {
752 tsetdirt(sel.b.y, sel.e.y);
756 sel.type = SEL_REGULAR;
757 sel.ex = sel.bx = x2col(e->xbutton.x);
758 sel.ey = sel.by = y2row(e->xbutton.y);
759 } else if(e->xbutton.button == Button4) {
761 } else if(e->xbutton.button == Button5) {
769 int x, y, bufsize, is_selected = 0, size;
775 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
776 ptr = str = xmalloc(bufsize);
778 /* append every set & selected glyph to the selection */
779 for(y = sel.b.y; y < sel.e.y + 1; y++) {
781 gp = &term.line[y][0];
782 last = gp + term.col;
784 while(--last >= gp && !(last->state & GLYPH_SET))
787 for(x = 0; gp <= last; x++, ++gp) {
788 if(!selected(x, y)) {
794 p = (gp->state & GLYPH_SET) ? gp->c : " ";
796 memcpy(ptr, p, size);
799 /* \n at the end of every selected line except for the last one */
800 if(is_selected && y < sel.e.y)
809 selnotify(XEvent *e) {
810 ulong nitems, ofs, rem;
817 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
818 False, AnyPropertyType, &type, &format,
819 &nitems, &rem, &data)) {
820 fprintf(stderr, "Clipboard allocation failed\n");
823 ttywrite((const char *) data, nitems * format / 8);
825 /* number of 32-bit chunks returned */
826 ofs += nitems * format / 32;
831 selpaste(const Arg *dummy) {
832 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
833 xw.win, CurrentTime);
836 void selclear(XEvent *e) {
840 tsetdirt(sel.b.y, sel.e.y);
844 selrequest(XEvent *e) {
845 XSelectionRequestEvent *xsre;
847 Atom xa_targets, string;
849 xsre = (XSelectionRequestEvent *) e;
850 xev.type = SelectionNotify;
851 xev.requestor = xsre->requestor;
852 xev.selection = xsre->selection;
853 xev.target = xsre->target;
854 xev.time = xsre->time;
858 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
859 if(xsre->target == xa_targets) {
860 /* respond with the supported type */
861 string = sel.xtarget;
862 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
863 XA_ATOM, 32, PropModeReplace,
864 (uchar *) &string, 1);
865 xev.property = xsre->property;
866 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
867 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
868 xsre->target, 8, PropModeReplace,
869 (uchar *) sel.clip, strlen(sel.clip));
870 xev.property = xsre->property;
873 /* all done, send a notification to the listener */
874 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
875 fprintf(stderr, "Error sending SelectionNotify event\n");
880 /* register the selection for both the clipboard and the primary */
886 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
888 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
889 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
893 brelease(XEvent *e) {
896 if(IS_SET(MODE_MOUSE)) {
901 if(e->xbutton.button == Button2) {
903 } else if(e->xbutton.button == Button1) {
906 term.dirty[sel.ey] = 1;
907 if(sel.bx == sel.ex && sel.by == sel.ey) {
909 gettimeofday(&now, NULL);
911 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
912 /* triple click on the line */
913 sel.b.x = sel.bx = 0;
914 sel.e.x = sel.ex = term.col;
915 sel.b.y = sel.e.y = sel.ey;
917 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
918 /* double click to select word */
920 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
921 term.line[sel.ey][sel.bx-1].c[0] != ' ') {
925 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
926 term.line[sel.ey][sel.ex+1].c[0] != ' ') {
930 sel.b.y = sel.e.y = sel.ey;
938 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
939 gettimeofday(&sel.tclick1, NULL);
946 if(IS_SET(MODE_MOUSE)) {
958 if(oldey != sel.ey || oldex != sel.ex) {
959 tsetdirt(sel.b.y, sel.e.y);
964 die(const char *errstr, ...) {
967 va_start(ap, errstr);
968 vfprintf(stderr, errstr, ap);
976 char *envshell = getenv("SHELL");
977 const struct passwd *pass = getpwuid(getuid());
978 char buf[sizeof(long) * 8 + 1];
985 setenv("LOGNAME", pass->pw_name, 1);
986 setenv("USER", pass->pw_name, 1);
987 setenv("SHELL", pass->pw_shell, 0);
988 setenv("HOME", pass->pw_dir, 0);
991 snprintf(buf, sizeof(buf), "%lu", xw.win);
992 setenv("WINDOWID", buf, 1);
994 signal(SIGCHLD, SIG_DFL);
995 signal(SIGHUP, SIG_DFL);
996 signal(SIGINT, SIG_DFL);
997 signal(SIGQUIT, SIG_DFL);
998 signal(SIGTERM, SIG_DFL);
999 signal(SIGALRM, SIG_DFL);
1001 DEFAULT(envshell, shell);
1002 setenv("TERM", termname, 1);
1003 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
1004 execvp(args[0], args);
1012 if(waitpid(pid, &stat, 0) < 0)
1013 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
1015 if(WIFEXITED(stat)) {
1016 exit(WEXITSTATUS(stat));
1025 struct winsize w = {term.row, term.col, 0, 0};
1027 /* seems to work fine on linux, openbsd and freebsd */
1028 if(openpty(&m, &s, NULL, NULL, &w) < 0)
1029 die("openpty failed: %s\n", SERRNO);
1031 switch(pid = fork()) {
1033 die("fork failed\n");
1036 setsid(); /* create a new process group */
1037 dup2(s, STDIN_FILENO);
1038 dup2(s, STDOUT_FILENO);
1039 dup2(s, STDERR_FILENO);
1040 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1041 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
1049 signal(SIGCHLD, sigchld);
1051 iofd = (!strcmp(opt_io, "-")) ?
1053 open(opt_io, O_WRONLY | O_CREAT, 0666);
1055 fprintf(stderr, "Error opening %s:%s\n",
1056 opt_io, strerror(errno));
1066 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1068 fprintf(stderr, "\n");
1073 static char buf[BUFSIZ];
1074 static int buflen = 0;
1077 int charsize; /* size of utf8 char in bytes */
1081 /* append read bytes to unprocessed bytes */
1082 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1083 die("Couldn't read from shell: %s\n", SERRNO);
1085 /* process every complete utf8 char */
1088 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1089 charsize = utf8decode(ptr, &utf8c);
1090 utf8encode(&utf8c, s);
1096 /* keep any uncomplete utf8 char for the next call */
1097 memmove(buf, ptr, buflen);
1101 ttywrite(const char *s, size_t n) {
1102 if(write(cmdfd, s, n) == -1)
1103 die("write error on tty: %s\n", SERRNO);
1110 w.ws_row = term.row;
1111 w.ws_col = term.col;
1112 w.ws_xpixel = xw.tw;
1113 w.ws_ypixel = xw.th;
1114 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1115 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1119 tsetdirt(int top, int bot) {
1122 LIMIT(top, 0, term.row-1);
1123 LIMIT(bot, 0, term.row-1);
1125 for(i = top; i <= bot; i++)
1131 tsetdirt(0, term.row-1);
1138 if(mode == CURSOR_SAVE) {
1140 } else if(mode == CURSOR_LOAD) {
1150 term.c = (TCursor){{
1154 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1156 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1157 for(i = tabspaces; i < term.col; i += tabspaces)
1160 term.bot = term.row - 1;
1161 term.mode = MODE_WRAP;
1163 tclearregion(0, 0, term.col-1, term.row-1, 0);
1165 tcursor(CURSOR_SAVE);
1169 tnew(int col, int row) {
1170 /* set screen size */
1173 term.line = xmalloc(term.row * sizeof(Line));
1174 term.alt = xmalloc(term.row * sizeof(Line));
1175 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1176 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1178 for(row = 0; row < term.row; row++) {
1179 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1180 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1181 term.dirty[row] = 0;
1185 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1192 Line *tmp = term.line;
1194 term.line = term.alt;
1196 term.mode ^= MODE_ALTSCREEN;
1201 tscrolldown(int orig, int n) {
1205 LIMIT(n, 0, term.bot-orig+1);
1207 tclearregion(0, term.bot-n+1, term.col-1, term.bot, 0);
1209 for(i = term.bot; i >= orig+n; i--) {
1210 temp = term.line[i];
1211 term.line[i] = term.line[i-n];
1212 term.line[i-n] = temp;
1215 term.dirty[i-n] = 1;
1222 tscrollup(int orig, int n) {
1225 LIMIT(n, 0, term.bot-orig+1);
1227 tclearregion(0, orig, term.col-1, orig+n-1, 0);
1229 for(i = orig; i <= term.bot-n; i++) {
1230 temp = term.line[i];
1231 term.line[i] = term.line[i+n];
1232 term.line[i+n] = temp;
1235 term.dirty[i+n] = 1;
1238 selscroll(orig, -n);
1242 selscroll(int orig, int n) {
1246 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1247 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1253 if(sel.by < term.top) {
1257 if(sel.ey > term.bot) {
1262 case SEL_RECTANGULAR:
1263 if(sel.by < term.top)
1265 if(sel.ey > term.bot)
1269 sel.b.y = sel.by, sel.b.x = sel.bx;
1270 sel.e.y = sel.ey, sel.e.x = sel.ex;
1275 tnewline(int first_col) {
1279 tscrollup(term.top, 1);
1283 tmoveto(first_col ? 0 : term.c.x, y);
1288 /* int noarg = 1; */
1289 char *p = csiescseq.buf;
1293 csiescseq.priv = 1, p++;
1295 while(p < csiescseq.buf+csiescseq.len) {
1296 while(isdigit(*p)) {
1297 csiescseq.arg[csiescseq.narg] *= 10;
1298 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1300 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1301 csiescseq.narg++, p++;
1303 csiescseq.mode = *p;
1311 /* for absolute user moves, when decom is set */
1313 tmoveato(int x, int y) {
1314 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1318 tmoveto(int x, int y) {
1321 if(term.c.state & CURSOR_ORIGIN) {
1326 maxy = term.row - 1;
1328 LIMIT(x, 0, term.col-1);
1329 LIMIT(y, miny, maxy);
1330 term.c.state &= ~CURSOR_WRAPNEXT;
1336 tsetchar(char *c, Glyph *attr, int x, int y) {
1337 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1338 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1339 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1340 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1341 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1342 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1343 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1344 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1345 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1349 * The table is proudly stolen from rxvt.
1351 if(attr->mode & ATTR_GFX) {
1352 if(c[0] >= 0x41 && c[0] <= 0x7e
1353 && vt100_0[c[0] - 0x41]) {
1354 c = vt100_0[c[0] - 0x41];
1359 term.line[y][x] = *attr;
1360 memcpy(term.line[y][x].c, c, UTF_SIZ);
1361 term.line[y][x].state |= GLYPH_SET;
1365 tclearregion(int x1, int y1, int x2, int y2, int bce) {
1369 temp = x1, x1 = x2, x2 = temp;
1371 temp = y1, y1 = y2, y2 = temp;
1373 LIMIT(x1, 0, term.col-1);
1374 LIMIT(x2, 0, term.col-1);
1375 LIMIT(y1, 0, term.row-1);
1376 LIMIT(y2, 0, term.row-1);
1378 for(y = y1; y <= y2; y++) {
1380 for(x = x1; x <= x2; x++) {
1382 term.line[y][x] = term.c.attr;
1383 memcpy(term.line[y][x].c, " ", 2);
1384 term.line[y][x].state |= GLYPH_SET;
1386 term.line[y][x].state = 0;
1393 tdeletechar(int n) {
1394 int src = term.c.x + n;
1396 int size = term.col - src;
1398 term.dirty[term.c.y] = 1;
1400 if(src >= term.col) {
1401 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 0);
1405 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1406 size * sizeof(Glyph));
1407 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y, 0);
1411 tinsertblank(int n) {
1414 int size = term.col - dst;
1416 term.dirty[term.c.y] = 1;
1418 if(dst >= term.col) {
1419 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 0);
1423 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1424 size * sizeof(Glyph));
1425 tclearregion(src, term.c.y, dst - 1, term.c.y, 0);
1429 tinsertblankline(int n) {
1430 if(term.c.y < term.top || term.c.y > term.bot)
1433 tscrolldown(term.c.y, n);
1437 tdeleteline(int n) {
1438 if(term.c.y < term.top || term.c.y > term.bot)
1441 tscrollup(term.c.y, n);
1445 tsetattr(int *attr, int l) {
1448 for(i = 0; i < l; i++) {
1451 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1452 | ATTR_ITALIC | ATTR_BLINK);
1453 term.c.attr.fg = defaultfg;
1454 term.c.attr.bg = defaultbg;
1457 term.c.attr.mode |= ATTR_BOLD;
1460 term.c.attr.mode |= ATTR_ITALIC;
1463 term.c.attr.mode |= ATTR_UNDERLINE;
1465 case 5: /* slow blink */
1466 case 6: /* rapid blink */
1467 term.c.attr.mode |= ATTR_BLINK;
1470 term.c.attr.mode |= ATTR_REVERSE;
1474 term.c.attr.mode &= ~ATTR_BOLD;
1477 term.c.attr.mode &= ~ATTR_ITALIC;
1480 term.c.attr.mode &= ~ATTR_UNDERLINE;
1484 term.c.attr.mode &= ~ATTR_BLINK;
1487 term.c.attr.mode &= ~ATTR_REVERSE;
1490 if(i + 2 < l && attr[i + 1] == 5) {
1492 if(BETWEEN(attr[i], 0, 255)) {
1493 term.c.attr.fg = attr[i];
1496 "erresc: bad fgcolor %d\n",
1501 "erresc(38): gfx attr %d unknown\n",
1506 term.c.attr.fg = defaultfg;
1509 if(i + 2 < l && attr[i + 1] == 5) {
1511 if(BETWEEN(attr[i], 0, 255)) {
1512 term.c.attr.bg = attr[i];
1515 "erresc: bad bgcolor %d\n",
1520 "erresc(48): gfx attr %d unknown\n",
1525 term.c.attr.bg = defaultbg;
1528 if(BETWEEN(attr[i], 30, 37)) {
1529 term.c.attr.fg = attr[i] - 30;
1530 } else if(BETWEEN(attr[i], 40, 47)) {
1531 term.c.attr.bg = attr[i] - 40;
1532 } else if(BETWEEN(attr[i], 90, 97)) {
1533 term.c.attr.fg = attr[i] - 90 + 8;
1534 } else if(BETWEEN(attr[i], 100, 107)) {
1535 term.c.attr.bg = attr[i] - 100 + 8;
1538 "erresc(default): gfx attr %d unknown\n",
1539 attr[i]), csidump();
1547 tsetscroll(int t, int b) {
1550 LIMIT(t, 0, term.row-1);
1551 LIMIT(b, 0, term.row-1);
1561 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1564 tsetmode(bool priv, bool set, int *args, int narg) {
1568 for(lim = args + narg; args < lim; ++args) {
1572 case 1: /* DECCKM -- Cursor key */
1573 MODBIT(term.mode, set, MODE_APPCURSOR);
1575 case 5: /* DECSCNM -- Reverse video */
1577 MODBIT(term.mode, set, MODE_REVERSE);
1578 if(mode != term.mode)
1579 redraw(REDRAW_TIMEOUT);
1581 case 6: /* DECOM -- Origin */
1582 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1585 case 7: /* DECAWM -- Auto wrap */
1586 MODBIT(term.mode, set, MODE_WRAP);
1588 case 0: /* Error (IGNORED) */
1589 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1590 case 3: /* DECCOLM -- Column (IGNORED) */
1591 case 4: /* DECSCLM -- Scroll (IGNORED) */
1592 case 8: /* DECARM -- Auto repeat (IGNORED) */
1593 case 18: /* DECPFF -- Printer feed (IGNORED) */
1594 case 19: /* DECPEX -- Printer extent (IGNORED) */
1595 case 42: /* DECNRCM -- National characters (IGNORED) */
1596 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1598 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1599 MODBIT(term.mode, !set, MODE_HIDE);
1601 case 1000: /* 1000,1002: enable xterm mouse report */
1602 MODBIT(term.mode, set, MODE_MOUSEBTN);
1603 MODBIT(term.mode, 0, MODE_MOUSEMOTION);
1606 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1607 MODBIT(term.mode, 0, MODE_MOUSEBTN);
1610 MODBIT(term.mode, set, MODE_MOUSESGR);
1612 case 1049: /* = 1047 and 1048 */
1615 alt = IS_SET(MODE_ALTSCREEN);
1617 tclearregion(0, 0, term.col-1,
1620 if(set ^ alt) /* set is always 1 or 0 */
1627 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1631 "erresc: unknown private set/reset mode %d\n",
1637 case 0: /* Error (IGNORED) */
1639 case 2: /* KAM -- keyboard action */
1640 MODBIT(term.mode, set, MODE_KBDLOCK);
1642 case 4: /* IRM -- Insertion-replacement */
1643 MODBIT(term.mode, set, MODE_INSERT);
1645 case 12: /* SRM -- Send/Receive */
1646 MODBIT(term.mode, !set, MODE_ECHO);
1648 case 20: /* LNM -- Linefeed/new line */
1649 MODBIT(term.mode, set, MODE_CRLF);
1653 "erresc: unknown set/reset mode %d\n",
1665 switch(csiescseq.mode) {
1668 fprintf(stderr, "erresc: unknown csi ");
1672 case '@': /* ICH -- Insert <n> blank char */
1673 DEFAULT(csiescseq.arg[0], 1);
1674 tinsertblank(csiescseq.arg[0]);
1676 case 'A': /* CUU -- Cursor <n> Up */
1677 DEFAULT(csiescseq.arg[0], 1);
1678 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1680 case 'B': /* CUD -- Cursor <n> Down */
1681 case 'e': /* VPR --Cursor <n> Down */
1682 DEFAULT(csiescseq.arg[0], 1);
1683 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1685 case 'c': /* DA -- Device Attributes */
1686 if(csiescseq.arg[0] == 0)
1687 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1689 case 'C': /* CUF -- Cursor <n> Forward */
1690 case 'a': /* HPR -- Cursor <n> Forward */
1691 DEFAULT(csiescseq.arg[0], 1);
1692 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1694 case 'D': /* CUB -- Cursor <n> Backward */
1695 DEFAULT(csiescseq.arg[0], 1);
1696 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1698 case 'E': /* CNL -- Cursor <n> Down and first col */
1699 DEFAULT(csiescseq.arg[0], 1);
1700 tmoveto(0, term.c.y+csiescseq.arg[0]);
1702 case 'F': /* CPL -- Cursor <n> Up and first col */
1703 DEFAULT(csiescseq.arg[0], 1);
1704 tmoveto(0, term.c.y-csiescseq.arg[0]);
1706 case 'g': /* TBC -- Tabulation clear */
1707 switch(csiescseq.arg[0]) {
1708 case 0: /* clear current tab stop */
1709 term.tabs[term.c.x] = 0;
1711 case 3: /* clear all the tabs */
1712 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1718 case 'G': /* CHA -- Move to <col> */
1720 DEFAULT(csiescseq.arg[0], 1);
1721 tmoveto(csiescseq.arg[0]-1, term.c.y);
1723 case 'H': /* CUP -- Move to <row> <col> */
1725 DEFAULT(csiescseq.arg[0], 1);
1726 DEFAULT(csiescseq.arg[1], 1);
1727 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1729 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1730 DEFAULT(csiescseq.arg[0], 1);
1731 while(csiescseq.arg[0]--)
1734 case 'J': /* ED -- Clear screen */
1736 switch(csiescseq.arg[0]) {
1738 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 1);
1739 if(term.c.y < term.row-1) {
1740 tclearregion(0, term.c.y+1, term.col-1,
1746 tclearregion(0, 0, term.col-1, term.c.y-1, 1);
1747 tclearregion(0, term.c.y, term.c.x, term.c.y, 1);
1750 tclearregion(0, 0, term.col-1, term.row-1, 1);
1756 case 'K': /* EL -- Clear line */
1757 switch(csiescseq.arg[0]) {
1759 tclearregion(term.c.x, term.c.y, term.col-1,
1763 tclearregion(0, term.c.y, term.c.x, term.c.y, 1);
1766 tclearregion(0, term.c.y, term.col-1, term.c.y, 1);
1770 case 'S': /* SU -- Scroll <n> line up */
1771 DEFAULT(csiescseq.arg[0], 1);
1772 tscrollup(term.top, csiescseq.arg[0]);
1774 case 'T': /* SD -- Scroll <n> line down */
1775 DEFAULT(csiescseq.arg[0], 1);
1776 tscrolldown(term.top, csiescseq.arg[0]);
1778 case 'L': /* IL -- Insert <n> blank lines */
1779 DEFAULT(csiescseq.arg[0], 1);
1780 tinsertblankline(csiescseq.arg[0]);
1782 case 'l': /* RM -- Reset Mode */
1783 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1785 case 'M': /* DL -- Delete <n> lines */
1786 DEFAULT(csiescseq.arg[0], 1);
1787 tdeleteline(csiescseq.arg[0]);
1789 case 'X': /* ECH -- Erase <n> char */
1790 DEFAULT(csiescseq.arg[0], 1);
1791 tclearregion(term.c.x, term.c.y,
1792 term.c.x + csiescseq.arg[0] - 1, term.c.y, 1);
1794 case 'P': /* DCH -- Delete <n> char */
1795 DEFAULT(csiescseq.arg[0], 1);
1796 tdeletechar(csiescseq.arg[0]);
1798 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1799 DEFAULT(csiescseq.arg[0], 1);
1800 while(csiescseq.arg[0]--)
1803 case 'd': /* VPA -- Move to <row> */
1804 DEFAULT(csiescseq.arg[0], 1);
1805 tmoveato(term.c.x, csiescseq.arg[0]-1);
1807 case 'h': /* SM -- Set terminal mode */
1808 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1810 case 'm': /* SGR -- Terminal attribute (color) */
1811 tsetattr(csiescseq.arg, csiescseq.narg);
1813 case 'r': /* DECSTBM -- Set Scrolling Region */
1814 if(csiescseq.priv) {
1817 DEFAULT(csiescseq.arg[0], 1);
1818 DEFAULT(csiescseq.arg[1], term.row);
1819 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1823 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1824 tcursor(CURSOR_SAVE);
1826 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1827 tcursor(CURSOR_LOAD);
1838 for(i = 0; i < csiescseq.len; i++) {
1839 c = csiescseq.buf[i] & 0xff;
1842 } else if(c == '\n') {
1844 } else if(c == '\r') {
1846 } else if(c == 0x1b) {
1849 printf("(%02x)", c);
1857 memset(&csiescseq, 0, sizeof(csiescseq));
1861 parse_int(char *s) {
1864 while(isdigit(c = *s)) {
1865 if((INT_MAX - c + '0') / 10 >= x) {
1866 x = x * 10 + c - '0';
1883 * TODO: make this being useful in case of color palette change.
1886 narg = strescseq.narg;
1888 switch(strescseq.type) {
1889 case ']': /* OSC -- Operating System Command */
1890 switch(i = parse_int(strescseq.args[0])) {
1895 * TODO: Handle special chars in string, like umlauts.
1898 XStoreName(xw.dpy, xw.win, strescseq.args[2]);
1900 case 4: /* color set */
1903 p = strescseq.args[2];
1905 case 104: /* color reset, here p = NULL */
1906 j = (narg > 1) ? parse_int(strescseq.args[1]) : -1;
1907 if (!xsetcolorname(j, p))
1908 fprintf(stderr, "erresc: invalid color %s\n", p);
1910 redraw(0); /* TODO if defaultbg color is changed, borders are dirty */
1914 fprintf(stderr, "erresc: unknown str ");
1919 case 'k': /* old title set compatibility */
1920 XStoreName(xw.dpy, xw.win, strescseq.buf);
1922 case 'P': /* DSC -- Device Control String */
1923 case '_': /* APC -- Application Program Command */
1924 case '^': /* PM -- Privacy Message */
1926 fprintf(stderr, "erresc: unknown str ");
1936 * TODO: Implement parsing like for CSI when required.
1937 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1940 char *start = strescseq.buf, *end = start + strescseq.len;
1941 strescseq.args[0] = start;
1942 while(start < end && narg < LEN(strescseq.args)) {
1943 start = memchr(start, ';', end - start);
1948 strescseq.args[++narg] = start;
1951 strescseq.narg = narg + 1;
1959 printf("ESC%c", strescseq.type);
1960 for(i = 0; i < strescseq.len; i++) {
1961 c = strescseq.buf[i] & 0xff;
1964 } else if(c == '\n') {
1966 } else if(c == '\r') {
1968 } else if(c == 0x1b) {
1971 printf("(%02x)", c);
1979 memset(&strescseq, 0, sizeof(strescseq));
1983 tputtab(bool forward) {
1989 for(++x; x < term.col && !term.tabs[x]; ++x)
1994 for(--x; x > 0 && !term.tabs[x]; --x)
1997 tmoveto(x, term.c.y);
2001 techo(char *buf, int len) {
2002 for(; len > 0; buf++, len--) {
2005 if(c == '\033') { /* escape */
2008 } else if(c < '\x20') { /* control code */
2009 if(c != '\n' && c != '\r' && c != '\t') {
2023 tputc(char *c, int len) {
2025 bool control = ascii < '\x20' || ascii == 0177;
2028 if(xwrite(iofd, c, len) < 0) {
2029 fprintf(stderr, "Error writing in %s:%s\n",
2030 opt_io, strerror(errno));
2037 * STR sequences must be checked before anything else
2038 * because it can use some control codes as part of the sequence.
2040 if(term.esc & ESC_STR) {
2043 term.esc = ESC_START | ESC_STR_END;
2045 case '\a': /* backwards compatibility to xterm */
2050 if(strescseq.len + len < sizeof(strescseq.buf)) {
2051 memmove(&strescseq.buf[strescseq.len], c, len);
2052 strescseq.len += len;
2055 * Here is a bug in terminals. If the user never sends
2056 * some code to stop the str or esc command, then st
2057 * will stop responding. But this is better than
2058 * silently failing with unknown characters. At least
2059 * then users will report back.
2061 * In the case users ever get fixed, here is the code:
2073 * Actions of control codes must be performed as soon they arrive
2074 * because they can be embedded inside a control sequence, and
2075 * they must not cause conflicts with sequences.
2083 tmoveto(term.c.x-1, term.c.y);
2086 tmoveto(0, term.c.y);
2091 /* go to first col if the mode is set */
2092 tnewline(IS_SET(MODE_CRLF));
2094 case '\a': /* BEL */
2095 if(!(xw.state & WIN_FOCUSED))
2098 case '\033': /* ESC */
2100 term.esc = ESC_START;
2102 case '\016': /* SO */
2103 case '\017': /* SI */
2105 * Different charsets are hard to handle. Applications
2106 * should use the right alt charset escapes for the
2107 * only reason they still exist: line drawing. The
2108 * rest is incompatible history st should not support.
2111 case '\032': /* SUB */
2112 case '\030': /* CAN */
2115 case '\005': /* ENQ (IGNORED) */
2116 case '\000': /* NUL (IGNORED) */
2117 case '\021': /* XON (IGNORED) */
2118 case '\023': /* XOFF (IGNORED) */
2119 case 0177: /* DEL (IGNORED) */
2122 } else if(term.esc & ESC_START) {
2123 if(term.esc & ESC_CSI) {
2124 csiescseq.buf[csiescseq.len++] = ascii;
2125 if(BETWEEN(ascii, 0x40, 0x7E)
2126 || csiescseq.len >= ESC_BUF_SIZ) {
2128 csiparse(), csihandle();
2130 } else if(term.esc & ESC_STR_END) {
2134 } else if(term.esc & ESC_ALTCHARSET) {
2136 case '0': /* Line drawing set */
2137 term.c.attr.mode |= ATTR_GFX;
2139 case 'B': /* USASCII */
2140 term.c.attr.mode &= ~ATTR_GFX;
2142 case 'A': /* UK (IGNORED) */
2143 case '<': /* multinational charset (IGNORED) */
2144 case '5': /* Finnish (IGNORED) */
2145 case 'C': /* Finnish (IGNORED) */
2146 case 'K': /* German (IGNORED) */
2149 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2152 } else if(term.esc & ESC_TEST) {
2153 if(ascii == '8') { /* DEC screen alignment test. */
2154 char E[UTF_SIZ] = "E";
2157 for(x = 0; x < term.col; ++x) {
2158 for(y = 0; y < term.row; ++y)
2159 tsetchar(E, &term.c.attr, x, y);
2166 term.esc |= ESC_CSI;
2169 term.esc |= ESC_TEST;
2171 case 'P': /* DCS -- Device Control String */
2172 case '_': /* APC -- Application Program Command */
2173 case '^': /* PM -- Privacy Message */
2174 case ']': /* OSC -- Operating System Command */
2175 case 'k': /* old title set compatibility */
2177 strescseq.type = ascii;
2178 term.esc |= ESC_STR;
2180 case '(': /* set primary charset G0 */
2181 term.esc |= ESC_ALTCHARSET;
2183 case ')': /* set secondary charset G1 (IGNORED) */
2184 case '*': /* set tertiary charset G2 (IGNORED) */
2185 case '+': /* set quaternary charset G3 (IGNORED) */
2188 case 'D': /* IND -- Linefeed */
2189 if(term.c.y == term.bot) {
2190 tscrollup(term.top, 1);
2192 tmoveto(term.c.x, term.c.y+1);
2196 case 'E': /* NEL -- Next line */
2197 tnewline(1); /* always go to first col */
2200 case 'H': /* HTS -- Horizontal tab stop */
2201 term.tabs[term.c.x] = 1;
2204 case 'M': /* RI -- Reverse index */
2205 if(term.c.y == term.top) {
2206 tscrolldown(term.top, 1);
2208 tmoveto(term.c.x, term.c.y-1);
2212 case 'Z': /* DECID -- Identify Terminal */
2213 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2216 case 'c': /* RIS -- Reset to inital state */
2221 case '=': /* DECPAM -- Application keypad */
2222 term.mode |= MODE_APPKEYPAD;
2225 case '>': /* DECPNM -- Normal keypad */
2226 term.mode &= ~MODE_APPKEYPAD;
2229 case '7': /* DECSC -- Save Cursor */
2230 tcursor(CURSOR_SAVE);
2233 case '8': /* DECRC -- Restore Cursor */
2234 tcursor(CURSOR_LOAD);
2237 case '\\': /* ST -- Stop */
2241 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2242 (uchar) ascii, isprint(ascii)? ascii:'.');
2247 * All characters which form part of a sequence are not
2253 * Display control codes only if we are in graphic mode
2255 if(control && !(term.c.attr.mode & ATTR_GFX))
2257 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2259 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
2260 tnewline(1); /* always go to first col */
2262 if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2263 memmove(&term.line[term.c.y][term.c.x+1],
2264 &term.line[term.c.y][term.c.x],
2265 (term.col - term.c.x - 1) * sizeof(Glyph));
2268 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2269 if(term.c.x+1 < term.col) {
2270 tmoveto(term.c.x+1, term.c.y);
2272 term.c.state |= CURSOR_WRAPNEXT;
2277 tresize(int col, int row) {
2279 int minrow = MIN(row, term.row);
2280 int mincol = MIN(col, term.col);
2281 int slide = term.c.y - row + 1;
2284 if(col < 1 || row < 1)
2287 /* free unneeded rows */
2291 * slide screen to keep cursor where we expect it -
2292 * tscrollup would work here, but we can optimize to
2293 * memmove because we're freeing the earlier lines
2295 for(/* i = 0 */; i < slide; i++) {
2299 memmove(term.line, term.line + slide, row * sizeof(Line));
2300 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2302 for(i += row; i < term.row; i++) {
2307 /* resize to new height */
2308 term.line = xrealloc(term.line, row * sizeof(Line));
2309 term.alt = xrealloc(term.alt, row * sizeof(Line));
2310 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2311 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2313 /* resize each row to new width, zero-pad if needed */
2314 for(i = 0; i < minrow; i++) {
2316 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2317 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2318 for(x = mincol; x < col; x++) {
2319 term.line[i][x].state = 0;
2320 term.alt[i][x].state = 0;
2324 /* allocate any new rows */
2325 for(/* i == minrow */; i < row; i++) {
2327 term.line[i] = xcalloc(col, sizeof(Glyph));
2328 term.alt [i] = xcalloc(col, sizeof(Glyph));
2330 if(col > term.col) {
2331 bp = term.tabs + term.col;
2333 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2334 while(--bp > term.tabs && !*bp)
2336 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2339 /* update terminal size */
2342 /* reset scrolling region */
2343 tsetscroll(0, row-1);
2344 /* make use of the LIMIT in tmoveto */
2345 tmoveto(term.c.x, term.c.y);
2351 xresize(int col, int row) {
2352 xw.tw = MAX(1, col * xw.cw);
2353 xw.th = MAX(1, row * xw.ch);
2356 XFreePixmap(xw.dpy, xw.buf);
2357 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2358 DefaultDepth(xw.dpy, xw.scr));
2359 XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg].pixel);
2360 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2363 XftDrawChange(xw.draw, xw.buf);
2366 static inline ushort
2367 sixd_to_16bit(int x) {
2368 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2374 XRenderColor color = { .alpha = 0xffff };
2376 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2377 for(i = 0; i < LEN(colorname); i++) {
2380 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2381 die("Could not allocate color '%s'\n", colorname[i]);
2385 /* load colors [16-255] ; same colors as xterm */
2386 for(i = 16, r = 0; r < 6; r++) {
2387 for(g = 0; g < 6; g++) {
2388 for(b = 0; b < 6; b++) {
2389 color.red = sixd_to_16bit(r);
2390 color.green = sixd_to_16bit(g);
2391 color.blue = sixd_to_16bit(b);
2392 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2393 die("Could not allocate color %d\n", i);
2400 for(r = 0; r < 24; r++, i++) {
2401 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2402 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2404 die("Could not allocate color %d\n", i);
2410 xsetcolorname(int x, const char *name) {
2411 XRenderColor color = { .alpha = 0xffff };
2413 if (x < 0 || x > LEN(colorname))
2416 if(16 <= x && x < 16 + 216) {
2417 int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2418 color.red = sixd_to_16bit(r);
2419 color.green = sixd_to_16bit(g);
2420 color.blue = sixd_to_16bit(b);
2421 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2422 return 0; /* something went wrong */
2425 } else if (16 + 216 <= x && x < 256) {
2426 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2427 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2428 return 0; /* something went wrong */
2432 name = colorname[x];
2435 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2442 xtermclear(int col1, int row1, int col2, int row2) {
2443 XftDrawRect(xw.draw,
2444 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2445 borderpx + col1 * xw.cw,
2446 borderpx + row1 * xw.ch,
2447 (col2-col1+1) * xw.cw,
2448 (row2-row1+1) * xw.ch);
2452 * Absolute coordinates.
2455 xclear(int x1, int y1, int x2, int y2) {
2456 XftDrawRect(xw.draw,
2457 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2458 x1, y1, x2-x1, y2-y1);
2463 XClassHint class = {opt_class ? opt_class : termname, termname};
2464 XWMHints wm = {.flags = InputHint, .input = 1};
2465 XSizeHints *sizeh = NULL;
2467 sizeh = XAllocSizeHints();
2468 if(xw.isfixed == False) {
2469 sizeh->flags = PSize | PResizeInc | PBaseSize;
2470 sizeh->height = xw.h;
2471 sizeh->width = xw.w;
2472 sizeh->height_inc = xw.ch;
2473 sizeh->width_inc = xw.cw;
2474 sizeh->base_height = 2 * borderpx;
2475 sizeh->base_width = 2 * borderpx;
2477 sizeh->flags = PMaxSize | PMinSize;
2478 sizeh->min_width = sizeh->max_width = xw.fw;
2479 sizeh->min_height = sizeh->max_height = xw.fh;
2482 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2487 xloadfont(Font *f, FcPattern *pattern) {
2491 match = FcFontMatch(NULL, pattern, &result);
2495 if(!(f->set = FcFontSort(0, match, FcTrue, 0, &result))) {
2496 FcPatternDestroy(match);
2500 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2501 FcPatternDestroy(match);
2505 f->pattern = FcPatternDuplicate(pattern);
2507 f->ascent = f->match->ascent;
2508 f->descent = f->match->descent;
2510 f->rbearing = f->match->max_advance_width;
2512 f->height = f->match->height;
2513 f->width = f->lbearing + f->rbearing;
2519 xloadfonts(char *fontstr, int fontsize) {
2524 if(fontstr[0] == '-') {
2525 pattern = XftXlfdParse(fontstr, False, False);
2527 pattern = FcNameParse((FcChar8 *)fontstr);
2531 die("st: can't open font %s\n", fontstr);
2534 FcPatternDel(pattern, FC_PIXEL_SIZE);
2535 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2536 usedfontsize = fontsize;
2538 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2539 if(result == FcResultMatch) {
2540 usedfontsize = (int)fontval;
2543 * Default font size is 12, if none given. This is to
2544 * have a known usedfontsize value.
2546 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2551 FcConfigSubstitute(0, pattern, FcMatchPattern);
2552 FcDefaultSubstitute(pattern);
2554 if(xloadfont(&dc.font, pattern))
2555 die("st: can't open font %s\n", fontstr);
2557 /* Setting character width and height. */
2558 xw.cw = dc.font.width;
2559 xw.ch = dc.font.height;
2561 FcPatternDel(pattern, FC_SLANT);
2562 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2563 if(xloadfont(&dc.ifont, pattern))
2564 die("st: can't open font %s\n", fontstr);
2566 FcPatternDel(pattern, FC_WEIGHT);
2567 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2568 if(xloadfont(&dc.ibfont, pattern))
2569 die("st: can't open font %s\n", fontstr);
2571 FcPatternDel(pattern, FC_SLANT);
2572 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2573 if(xloadfont(&dc.bfont, pattern))
2574 die("st: can't open font %s\n", fontstr);
2576 FcPatternDestroy(pattern);
2580 xunloadfonts(void) {
2584 * Free the loaded fonts in the font cache. This is done backwards
2587 for(i = 0, ip = frccur; i < frclen; i++, ip--) {
2590 XftFontClose(xw.dpy, frc[ip].font);
2595 XftFontClose(xw.dpy, dc.font.match);
2596 FcPatternDestroy(dc.font.pattern);
2597 FcFontSetDestroy(dc.font.set);
2598 XftFontClose(xw.dpy, dc.bfont.match);
2599 FcPatternDestroy(dc.bfont.pattern);
2600 FcFontSetDestroy(dc.bfont.set);
2601 XftFontClose(xw.dpy, dc.ifont.match);
2602 FcPatternDestroy(dc.ifont.pattern);
2603 FcFontSetDestroy(dc.ifont.set);
2604 XftFontClose(xw.dpy, dc.ibfont.match);
2605 FcPatternDestroy(dc.ibfont.pattern);
2606 FcFontSetDestroy(dc.ibfont.set);
2610 xzoom(const Arg *arg) {
2612 xloadfonts(usedfont, usedfontsize + arg->i);
2619 XSetWindowAttributes attrs;
2623 int sw, sh, major, minor;
2625 if(!(xw.dpy = XOpenDisplay(NULL)))
2626 die("Can't open display\n");
2627 xw.scr = XDefaultScreen(xw.dpy);
2628 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2632 die("Could not init fontconfig.\n");
2634 usedfont = (opt_font == NULL)? font : opt_font;
2635 xloadfonts(usedfont, 0);
2638 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2641 /* adjust fixed window geometry */
2643 sw = DisplayWidth(xw.dpy, xw.scr);
2644 sh = DisplayHeight(xw.dpy, xw.scr);
2646 xw.fx = sw + xw.fx - xw.fw - 1;
2648 xw.fy = sh + xw.fy - xw.fh - 1;
2653 /* window - default size */
2654 xw.h = 2 * borderpx + term.row * xw.ch;
2655 xw.w = 2 * borderpx + term.col * xw.cw;
2661 attrs.background_pixel = dc.col[defaultbg].pixel;
2662 attrs.border_pixel = dc.col[defaultbg].pixel;
2663 attrs.bit_gravity = NorthWestGravity;
2664 attrs.event_mask = FocusChangeMask | KeyPressMask
2665 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2666 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2667 attrs.colormap = xw.cmap;
2669 parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2670 XRootWindow(xw.dpy, xw.scr);
2671 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2672 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2674 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2678 /* double buffering */
2680 if(XdbeQueryExtension(xw.dpy, &major, &minor)) {
2681 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win,
2686 memset(&gcvalues, 0, sizeof(gcvalues));
2687 gcvalues.graphics_exposures = False;
2688 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2690 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2691 DefaultDepth(xw.dpy, xw.scr));
2692 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
2693 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2699 /* Xft rendering context */
2700 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2703 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2704 XSetLocaleModifiers("@im=local");
2705 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2706 XSetLocaleModifiers("@im=");
2707 if((xw.xim = XOpenIM(xw.dpy,
2708 NULL, NULL, NULL)) == NULL) {
2709 die("XOpenIM failed. Could not open input"
2714 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2715 | XIMStatusNothing, XNClientWindow, xw.win,
2716 XNFocusWindow, xw.win, NULL);
2718 die("XCreateIC failed. Could not obtain input method.\n");
2720 /* white cursor, black outline */
2721 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2722 XDefineCursor(xw.dpy, xw.win, cursor);
2723 XRecolorCursor(xw.dpy, cursor,
2724 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2725 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2727 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2728 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2729 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2732 XMapWindow(xw.dpy, xw.win);
2738 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2739 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2740 width = charlen * xw.cw, xp, i;
2742 int u8fl, u8fblen, u8cblen, doesexist;
2745 Font *font = &dc.font;
2747 FcPattern *fcpattern, *fontpattern;
2748 FcFontSet *fcsets[] = { NULL };
2749 FcCharSet *fccharset;
2750 Colour *fg = &dc.col[base.fg], *bg = &dc.col[base.bg],
2751 *temp, revfg, revbg;
2752 XRenderColor colfg, colbg;
2754 frcflags = FRC_NORMAL;
2756 if(base.mode & ATTR_BOLD) {
2757 if(BETWEEN(base.fg, 0, 7)) {
2758 /* basic system colors */
2759 fg = &dc.col[base.fg + 8];
2760 } else if(BETWEEN(base.fg, 16, 195)) {
2762 fg = &dc.col[base.fg + 36];
2763 } else if(BETWEEN(base.fg, 232, 251)) {
2765 fg = &dc.col[base.fg + 4];
2768 * Those ranges will not be brightened:
2769 * 8 - 15 – bright system colors
2770 * 196 - 231 – highest 256 color cube
2771 * 252 - 255 – brightest colors in greyscale
2774 frcflags = FRC_BOLD;
2777 if(base.mode & ATTR_ITALIC) {
2779 frcflags = FRC_ITALIC;
2781 if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
2783 frcflags = FRC_ITALICBOLD;
2786 if(IS_SET(MODE_REVERSE)) {
2787 if(fg == &dc.col[defaultfg]) {
2788 fg = &dc.col[defaultbg];
2790 colfg.red = ~fg->color.red;
2791 colfg.green = ~fg->color.green;
2792 colfg.blue = ~fg->color.blue;
2793 colfg.alpha = fg->color.alpha;
2794 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2798 if(bg == &dc.col[defaultbg]) {
2799 bg = &dc.col[defaultfg];
2801 colbg.red = ~bg->color.red;
2802 colbg.green = ~bg->color.green;
2803 colbg.blue = ~bg->color.blue;
2804 colbg.alpha = bg->color.alpha;
2805 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2810 if(base.mode & ATTR_REVERSE) {
2816 /* Intelligent cleaning up of the borders. */
2818 xclear(0, (y == 0)? 0 : winy, borderpx,
2819 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
2821 if(x + charlen >= term.col) {
2822 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2823 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
2826 xclear(winx, 0, winx + width, borderpx);
2828 xclear(winx, winy + xw.ch, winx + width, xw.h);
2830 /* Clean up the region we want to draw to. */
2831 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
2833 fcsets[0] = font->set;
2834 for(xp = winx; bytelen > 0;) {
2836 * Search for the range in the to be printed string of glyphs
2837 * that are in the main font. Then print that range. If
2838 * some glyph is found that is not in the font, do the
2846 u8cblen = utf8decode(s, &u8char);
2850 doesexist = XftCharIndex(xw.dpy, font->match, u8char);
2851 if(!doesexist || bytelen <= 0) {
2860 XftDrawStringUtf8(xw.draw, fg,
2862 winy + font->ascent,
2865 xp += font->width * u8fl;
2877 /* Search the font cache. */
2878 for(i = 0; i < frclen; i++, frp--) {
2882 if(frc[frp].c == u8char
2883 && frc[frp].flags == frcflags) {
2888 /* Nothing was found. */
2891 * Nothing was found in the cache. Now use
2892 * some dozen of Fontconfig calls to get the
2893 * font for one single character.
2895 fcpattern = FcPatternDuplicate(font->pattern);
2896 fccharset = FcCharSetCreate();
2898 FcCharSetAddChar(fccharset, u8char);
2899 FcPatternAddCharSet(fcpattern, FC_CHARSET,
2901 FcPatternAddBool(fcpattern, FC_SCALABLE,
2904 FcConfigSubstitute(0, fcpattern,
2906 FcDefaultSubstitute(fcpattern);
2908 fontpattern = FcFontSetMatch(0, fcsets,
2909 FcTrue, fcpattern, &fcres);
2912 * Overwrite or create the new cache entry
2917 if(frccur >= LEN(frc))
2919 if(frclen > LEN(frc)) {
2921 XftFontClose(xw.dpy, frc[frccur].font);
2924 frc[frccur].font = XftFontOpenPattern(xw.dpy,
2926 frc[frccur].c = u8char;
2927 frc[frccur].flags = frcflags;
2929 FcPatternDestroy(fcpattern);
2930 FcCharSetDestroy(fccharset);
2935 XftDrawStringUtf8(xw.draw, fg, frc[frp].font,
2936 xp, winy + frc[frp].font->ascent,
2937 (FcChar8 *)u8c, u8cblen);
2943 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
2944 winy + font->ascent, (FcChar8 *)s, bytelen);
2947 if(base.mode & ATTR_UNDERLINE) {
2948 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
2955 static int oldx = 0, oldy = 0;
2957 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs, 0};
2959 LIMIT(oldx, 0, term.col-1);
2960 LIMIT(oldy, 0, term.row-1);
2962 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2963 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2965 /* remove the old cursor */
2966 if(term.line[oldy][oldx].state & GLYPH_SET) {
2967 sl = utf8size(term.line[oldy][oldx].c);
2968 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2971 xtermclear(oldx, oldy, oldx, oldy);
2974 /* draw the new one */
2975 if(!(IS_SET(MODE_HIDE))) {
2976 if(!(xw.state & WIN_FOCUSED))
2979 if(IS_SET(MODE_REVERSE))
2980 g.mode |= ATTR_REVERSE, g.fg = defaultcs, g.bg = defaultfg;
2983 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2984 oldx = term.c.x, oldy = term.c.y;
2990 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2994 redraw(int timeout) {
2995 struct timespec tv = {0, timeout * 1000};
3001 nanosleep(&tv, NULL);
3002 XSync(xw.dpy, False); /* necessary for a good tput flash */
3008 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
3010 drawregion(0, 0, term.col, term.row);
3012 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
3014 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3016 XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg].pixel);
3021 drawregion(int x1, int y1, int x2, int y2) {
3022 int ic, ib, x, y, ox, sl;
3024 char buf[DRAW_BUF_SIZ];
3025 bool ena_sel = sel.bx != -1;
3027 if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3030 if(!(xw.state & WIN_VISIBLE))
3033 for(y = y1; y < y2; y++) {
3037 xtermclear(0, y, term.col, y);
3039 base = term.line[y][0];
3041 for(x = x1; x < x2; x++) {
3042 new = term.line[y][x];
3043 if(ena_sel && *(new.c) && selected(x, y))
3044 new.mode ^= ATTR_REVERSE;
3045 if(ib > 0 && (!(new.state & GLYPH_SET)
3046 || ATTRCMP(base, new)
3047 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3048 xdraws(buf, base, ox, y, ic, ib);
3051 if(new.state & GLYPH_SET) {
3057 sl = utf8size(new.c);
3058 memcpy(buf+ib, new.c, sl);
3064 xdraws(buf, base, ox, y, ic, ib);
3070 expose(XEvent *ev) {
3071 XExposeEvent *e = &ev->xexpose;
3073 if(xw.state & WIN_REDRAW) {
3075 xw.state &= ~WIN_REDRAW;
3081 visibility(XEvent *ev) {
3082 XVisibilityEvent *e = &ev->xvisibility;
3084 if(e->state == VisibilityFullyObscured) {
3085 xw.state &= ~WIN_VISIBLE;
3086 } else if(!(xw.state & WIN_VISIBLE)) {
3087 /* need a full redraw for next Expose, not just a buf copy */
3088 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3094 xw.state &= ~WIN_VISIBLE;
3098 xseturgency(int add) {
3099 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3101 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3102 XSetWMHints(xw.dpy, xw.win, h);
3108 XFocusChangeEvent *e = &ev->xfocus;
3110 if(e->mode == NotifyGrab)
3113 if(ev->type == FocusIn) {
3114 XSetICFocus(xw.xic);
3115 xw.state |= WIN_FOCUSED;
3118 XUnsetICFocus(xw.xic);
3119 xw.state &= ~WIN_FOCUSED;
3124 match(uint mask, uint state) {
3125 state &= ~(ignoremod);
3127 if(mask == XK_NO_MOD && state)
3129 if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
3131 if((state & mask) != state)
3137 numlock(const Arg *dummy) {
3142 kmap(KeySym k, uint state) {
3147 /* Check for mapped keys out of X11 function keys. */
3148 for(i = 0; i < LEN(mappedkeys); i++) {
3149 if(mappedkeys[i] == k)
3152 if(i == LEN(mappedkeys)) {
3153 if((k & 0xFFFF) < 0xFD00)
3157 for(kp = key; kp < key + LEN(key); kp++) {
3163 if(!match(mask, state))
3166 if(kp->appkey > 0) {
3167 if(!IS_SET(MODE_APPKEYPAD))
3169 if(term.numlock && kp->appkey == 2)
3171 } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
3175 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
3177 && !IS_SET(MODE_APPCURSOR))) {
3181 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
3182 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
3193 kpress(XEvent *ev) {
3194 XKeyEvent *e = &ev->xkey;
3196 char xstr[31], buf[32], *customkey, *cp = buf;
3201 if(IS_SET(MODE_KBDLOCK))
3204 len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
3205 e->state &= ~Mod2Mask;
3207 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3208 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3209 bp->func(&(bp->arg));
3214 /* 2. custom keys from config.h */
3215 if((customkey = kmap(ksym, e->state))) {
3216 len = strlen(customkey);
3217 memcpy(buf, customkey, len);
3218 /* 2. hardcoded (overrides X lookup) */
3223 if(len == 1 && e->state & Mod1Mask)
3226 memcpy(cp, xstr, len);
3227 len = cp - buf + len;
3231 if(IS_SET(MODE_ECHO))
3237 cmessage(XEvent *e) {
3240 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3242 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3243 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3244 xw.state |= WIN_FOCUSED;
3246 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3247 xw.state &= ~WIN_FOCUSED;
3249 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3250 /* Send SIGHUP to shell */
3257 cresize(int width, int height) {
3265 col = (xw.w - 2 * borderpx) / xw.cw;
3266 row = (xw.h - 2 * borderpx) / xw.ch;
3275 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3278 cresize(e->xconfigure.width, e->xconfigure.height);
3285 int xfd = XConnectionNumber(xw.dpy), xev;
3286 struct timeval drawtimeout, *tv = NULL, now, last;
3288 gettimeofday(&last, NULL);
3290 for(xev = actionfps;;) {
3292 FD_SET(cmdfd, &rfd);
3294 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3297 die("select failed: %s\n", SERRNO);
3300 gettimeofday(&now, NULL);
3301 drawtimeout.tv_sec = 0;
3302 drawtimeout.tv_usec = (1000/xfps) * 1000;
3305 if(FD_ISSET(cmdfd, &rfd))
3308 if(FD_ISSET(xfd, &rfd))
3311 if(TIMEDIFF(now, last) > \
3312 (xev ? (1000/xfps) : (1000/actionfps))) {
3313 while(XPending(xw.dpy)) {
3314 XNextEvent(xw.dpy, &ev);
3315 if(XFilterEvent(&ev, None))
3317 if(handler[ev.type])
3318 (handler[ev.type])(&ev);
3325 if(xev && !FD_ISSET(xfd, &rfd))
3327 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd))
3334 main(int argc, char *argv[]) {
3335 int i, bitm, xr, yr;
3338 xw.fw = xw.fh = xw.fx = xw.fy = 0;
3341 for(i = 1; i < argc; i++) {
3342 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
3345 opt_class = argv[i];
3348 /* eat all remaining arguments */
3360 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
3365 if(bitm & WidthValue)
3367 if(bitm & HeightValue)
3369 if(bitm & XNegative && xw.fx == 0)
3371 if(bitm & XNegative && xw.fy == 0)
3374 if(xw.fh != 0 && xw.fw != 0)
3383 opt_title = argv[i];
3390 opt_embed = argv[i];
3396 setlocale(LC_CTYPE, "");
3397 XSetLocaleModifiers("");