1 /* See LICENSE for licence details. */
2 #define _XOPEN_SOURCE 600
14 #include <sys/ioctl.h>
15 #include <sys/select.h>
18 #include <sys/types.h>
22 #include <X11/Xatom.h>
24 #include <X11/Xutil.h>
25 #include <X11/cursorfont.h>
26 #include <X11/keysym.h>
27 #include <X11/extensions/Xdbe.h>
28 #include <X11/Xft/Xft.h>
29 #include <fontconfig/fontconfig.h>
35 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
37 #elif defined(__FreeBSD__) || defined(__DragonFly__)
42 "st " VERSION " (c) 2010-2012 st engineers\n" \
43 "usage: st [-v] [-c class] [-f font] [-g geometry] [-o file]" \
44 " [-t title] [-w windowid] [-e command ...]\n"
47 #define XEMBED_FOCUS_IN 4
48 #define XEMBED_FOCUS_OUT 5
51 #define ESC_BUF_SIZ 256
52 #define ESC_ARG_SIZ 16
53 #define STR_BUF_SIZ 256
54 #define STR_ARG_SIZ 16
55 #define DRAW_BUF_SIZ 20*1024
57 #define XK_NO_MOD UINT_MAX
60 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
62 #define SERRNO strerror(errno)
63 #define MIN(a, b) ((a) < (b) ? (a) : (b))
64 #define MAX(a, b) ((a) < (b) ? (b) : (a))
65 #define LEN(a) (sizeof(a) / sizeof(a[0]))
66 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
67 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
68 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
69 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
70 #define IS_SET(flag) (term.mode & (flag))
71 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
72 #define X2COL(x) (((x) - BORDER)/xw.cw)
73 #define Y2ROW(y) (((y) - BORDER)/xw.ch)
75 #define VT102ID "\033[?6c"
77 enum glyph_attribute {
87 enum cursor_movement {
114 MODE_MOUSEMOTION = 64,
123 ESC_STR = 4, /* DSC, OSC, PM, APC */
125 ESC_STR_END = 16, /* a final string was encountered */
136 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
138 typedef unsigned char uchar;
139 typedef unsigned int uint;
140 typedef unsigned long ulong;
141 typedef unsigned short ushort;
144 char c[UTF_SIZ]; /* character code */
145 uchar mode; /* attribute flags */
146 ushort fg; /* foreground */
147 ushort bg; /* background */
148 uchar state; /* state flags */
154 Glyph attr; /* current char attributes */
160 /* CSI Escape sequence structs */
161 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
163 char buf[ESC_BUF_SIZ]; /* raw string */
164 int len; /* raw string length */
166 int arg[ESC_ARG_SIZ];
167 int narg; /* nb of args */
171 /* STR Escape sequence structs */
172 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
174 char type; /* ESC type ... */
175 char buf[STR_BUF_SIZ]; /* raw string */
176 int len; /* raw string length */
177 char *args[STR_ARG_SIZ];
178 int narg; /* nb of args */
181 /* Internal representation of the screen */
183 int row; /* nb row */
184 int col; /* nb col */
185 Line *line; /* screen */
186 Line *alt; /* alternate screen */
187 bool *dirty; /* dirtyness of lines */
188 TCursor c; /* cursor */
189 int top; /* top scroll limit */
190 int bot; /* bottom scroll limit */
191 int mode; /* terminal mode flags */
192 int esc; /* escape state flags */
196 /* Purely graphic info */
202 Atom xembed, wmdeletewin;
208 bool isfixed; /* is fixed geometry? */
209 int fx, fy, fw, fh; /* fixed geometry */
210 int tw, th; /* tty width and height */
211 int w; /* window width */
212 int h; /* window height */
213 int ch; /* char height */
214 int cw; /* char width */
215 char state; /* focus, redraw, visible */
224 /* TODO: use better name for vars... */
235 struct timeval tclick1;
236 struct timeval tclick2;
252 /* Drawing Context */
254 XftColor xft_col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
256 Font font, bfont, ifont, ibfont;
259 static void die(const char *, ...);
260 static void draw(void);
261 static void redraw(void);
262 static void drawregion(int, int, int, int);
263 static void execsh(void);
264 static void sigchld(int);
265 static void run(void);
267 static void csidump(void);
268 static void csihandle(void);
269 static void csiparse(void);
270 static void csireset(void);
271 static void strdump(void);
272 static void strhandle(void);
273 static void strparse(void);
274 static void strreset(void);
276 static void tclearregion(int, int, int, int);
277 static void tcursor(int);
278 static void tdeletechar(int);
279 static void tdeleteline(int);
280 static void tinsertblank(int);
281 static void tinsertblankline(int);
282 static void tmoveto(int, int);
283 static void tnew(int, int);
284 static void tnewline(int);
285 static void tputtab(bool);
286 static void tputc(char *, int);
287 static void treset(void);
288 static int tresize(int, int);
289 static void tscrollup(int, int);
290 static void tscrolldown(int, int);
291 static void tsetattr(int*, int);
292 static void tsetchar(char*);
293 static void tsetscroll(int, int);
294 static void tswapscreen(void);
295 static void tsetdirt(int, int);
296 static void tsetmode(bool, bool, int *, int);
297 static void tfulldirt(void);
299 static void ttynew(void);
300 static void ttyread(void);
301 static void ttyresize(void);
302 static void ttywrite(const char *, size_t);
304 static void xdraws(char *, Glyph, int, int, int, int);
305 static void xhints(void);
306 static void xclear(int, int, int, int);
307 static void xdrawcursor(void);
308 static void xinit(void);
309 static void xloadcols(void);
310 static void xresettitle(void);
311 static void xseturgency(int);
312 static void xsetsel(char*);
313 static void xtermclear(int, int, int, int);
314 static void xresize(int, int);
316 static void expose(XEvent *);
317 static void visibility(XEvent *);
318 static void unmap(XEvent *);
319 static char *kmap(KeySym, uint);
320 static void kpress(XEvent *);
321 static void cmessage(XEvent *);
322 static void resize(XEvent *);
323 static void focus(XEvent *);
324 static void brelease(XEvent *);
325 static void bpress(XEvent *);
326 static void bmotion(XEvent *);
327 static void selnotify(XEvent *);
328 static void selclear(XEvent *);
329 static void selrequest(XEvent *);
331 static void selinit(void);
332 static inline bool selected(int, int);
333 static void selcopy(void);
334 static void selpaste(void);
335 static void selscroll(int, int);
337 static int utf8decode(char *, long *);
338 static int utf8encode(long *, char *);
339 static int utf8size(char *);
340 static int isfullutf8(char *, int);
342 static void *xmalloc(size_t);
343 static void *xrealloc(void *, size_t);
344 static void *xcalloc(size_t nmemb, size_t size);
345 static char *smstrcat(char *, ...);
347 static void (*handler[LASTEvent])(XEvent *) = {
349 [ClientMessage] = cmessage,
350 [ConfigureNotify] = resize,
351 [VisibilityNotify] = visibility,
352 [UnmapNotify] = unmap,
356 [MotionNotify] = bmotion,
357 [ButtonPress] = bpress,
358 [ButtonRelease] = brelease,
359 [SelectionClear] = selclear,
360 [SelectionNotify] = selnotify,
361 [SelectionRequest] = selrequest,
368 static CSIEscape csiescseq;
369 static STREscape strescseq;
372 static Selection sel;
373 static int iofd = -1;
374 static char **opt_cmd = NULL;
375 static char *opt_io = NULL;
376 static char *opt_title = NULL;
377 static char *opt_embed = NULL;
378 static char *opt_class = NULL;
379 static char *opt_font = NULL;
382 xmalloc(size_t len) {
383 void *p = malloc(len);
386 die("Out of memory\n");
392 xrealloc(void *p, size_t len) {
393 if((p = realloc(p, len)) == NULL)
394 die("Out of memory\n");
400 xcalloc(size_t nmemb, size_t size) {
401 void *p = calloc(nmemb, size);
404 die("Out of memory\n");
410 smstrcat(char *src, ...)
416 len = slen = strlen(src);
418 va_start(fmtargs, src);
420 v = va_arg(fmtargs, char *);
427 p = ret = xmalloc(len+1);
428 memmove(p, src, slen);
431 va_start(fmtargs, src);
433 v = va_arg(fmtargs, char *);
448 utf8decode(char *s, long *u) {
454 if(~c & B7) { /* 0xxxxxxx */
457 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
458 *u = c&(B4|B3|B2|B1|B0);
460 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
461 *u = c&(B3|B2|B1|B0);
463 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
470 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
472 if((c & (B7|B6)) != B7) /* 10xxxxxx */
475 *u |= c & (B5|B4|B3|B2|B1|B0);
478 if((n == 1 && *u < 0x80) ||
479 (n == 2 && *u < 0x800) ||
480 (n == 3 && *u < 0x10000) ||
481 (*u >= 0xD800 && *u <= 0xDFFF)) {
493 utf8encode(long *u, char *s) {
501 *sp = uc; /* 0xxxxxxx */
503 } else if(*u < 0x800) {
504 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
506 } else if(uc < 0x10000) {
507 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
509 } else if(uc <= 0x10FFFF) {
510 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
516 for(i=n,++sp; i>0; --i,++sp)
517 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
529 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
530 UTF-8 otherwise return 0 */
532 isfullutf8(char *s, int b) {
540 } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
542 } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
544 ((b == 2) && (*c2&(B7|B6)) == B7))) {
546 } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
548 ((b == 2) && (*c2&(B7|B6)) == B7) ||
549 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
562 } else if((c&(B7|B6|B5)) == (B7|B6)) {
564 } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
573 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
574 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
578 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
579 if(sel.xtarget == None)
580 sel.xtarget = XA_STRING;
584 selected(int x, int y) {
587 if(sel.ey == y && sel.by == y) {
588 bx = MIN(sel.bx, sel.ex);
589 ex = MAX(sel.bx, sel.ex);
590 return BETWEEN(x, bx, ex);
593 return ((sel.b.y < y && y < sel.e.y)
594 || (y == sel.e.y && x <= sel.e.x))
595 || (y == sel.b.y && x >= sel.b.x
596 && (x <= sel.e.x || sel.b.y != sel.e.y));
600 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
602 *b = e->xbutton.button;
604 *x = X2COL(e->xbutton.x);
605 *y = Y2ROW(e->xbutton.y);
606 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
607 sel.b.y = MIN(sel.by, sel.ey);
608 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
609 sel.e.y = MAX(sel.by, sel.ey);
613 mousereport(XEvent *e) {
614 int x = X2COL(e->xbutton.x);
615 int y = Y2ROW(e->xbutton.y);
616 int button = e->xbutton.button;
617 int state = e->xbutton.state;
618 char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
619 static int ob, ox, oy;
622 if(e->xbutton.type == MotionNotify) {
623 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
627 } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
633 if(e->xbutton.type == ButtonPress) {
639 buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
640 + (state & Mod4Mask ? 8 : 0)
641 + (state & ControlMask ? 16 : 0);
643 ttywrite(buf, sizeof(buf));
648 if(IS_SET(MODE_MOUSE)) {
650 } else if(e->xbutton.button == Button1) {
653 tsetdirt(sel.b.y, sel.e.y);
657 sel.ex = sel.bx = X2COL(e->xbutton.x);
658 sel.ey = sel.by = Y2ROW(e->xbutton.y);
665 int x, y, bufsize, is_selected = 0, size;
671 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
672 ptr = str = xmalloc(bufsize);
674 /* append every set & selected glyph to the selection */
675 for(y = 0; y < term.row; y++) {
676 for(x = 0; x < term.col; x++) {
677 gp = &term.line[y][x];
679 if(!(is_selected = selected(x, y)))
681 p = (gp->state & GLYPH_SET) ? gp->c : " ";
683 memcpy(ptr, p, size);
686 /* \n at the end of every selected line except for the last one */
687 if(is_selected && y < sel.e.y)
692 sel.alt = IS_SET(MODE_ALTSCREEN);
697 selnotify(XEvent *e) {
698 ulong nitems, ofs, rem;
705 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
706 False, AnyPropertyType, &type, &format,
707 &nitems, &rem, &data)) {
708 fprintf(stderr, "Clipboard allocation failed\n");
711 ttywrite((const char *) data, nitems * format / 8);
713 /* number of 32-bit chunks returned */
714 ofs += nitems * format / 32;
720 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
721 xw.win, CurrentTime);
724 void selclear(XEvent *e) {
728 tsetdirt(sel.b.y, sel.e.y);
732 selrequest(XEvent *e) {
733 XSelectionRequestEvent *xsre;
735 Atom xa_targets, string;
737 xsre = (XSelectionRequestEvent *) e;
738 xev.type = SelectionNotify;
739 xev.requestor = xsre->requestor;
740 xev.selection = xsre->selection;
741 xev.target = xsre->target;
742 xev.time = xsre->time;
746 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
747 if(xsre->target == xa_targets) {
748 /* respond with the supported type */
749 string = sel.xtarget;
750 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
751 XA_ATOM, 32, PropModeReplace,
752 (uchar *) &string, 1);
753 xev.property = xsre->property;
754 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
755 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
756 xsre->target, 8, PropModeReplace,
757 (uchar *) sel.clip, strlen(sel.clip));
758 xev.property = xsre->property;
761 /* all done, send a notification to the listener */
762 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
763 fprintf(stderr, "Error sending SelectionNotify event\n");
768 /* register the selection for both the clipboard and the primary */
774 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
776 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
777 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
781 brelease(XEvent *e) {
784 if(IS_SET(MODE_MOUSE)) {
789 if(e->xbutton.button == Button2) {
791 } else if(e->xbutton.button == Button1) {
793 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
794 term.dirty[sel.ey] = 1;
795 if(sel.bx == sel.ex && sel.by == sel.ey) {
797 gettimeofday(&now, NULL);
799 if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
800 /* triple click on the line */
801 sel.b.x = sel.bx = 0;
802 sel.e.x = sel.ex = term.col;
803 sel.b.y = sel.e.y = sel.ey;
805 } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
806 /* double click to select word */
808 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
809 term.line[sel.ey][sel.bx-1].c[0] != ' ') {
813 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
814 term.line[sel.ey][sel.ex+1].c[0] != ' ') {
818 sel.b.y = sel.e.y = sel.ey;
826 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
827 gettimeofday(&sel.tclick1, NULL);
832 int starty, endy, oldey, oldex;
834 if(IS_SET(MODE_MOUSE)) {
842 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
844 if(oldey != sel.ey || oldex != sel.ex) {
845 starty = MIN(oldey, sel.ey);
846 endy = MAX(oldey, sel.ey);
847 tsetdirt(starty, endy);
853 die(const char *errstr, ...) {
856 va_start(ap, errstr);
857 vfprintf(stderr, errstr, ap);
865 char *envshell = getenv("SHELL");
871 signal(SIGCHLD, SIG_DFL);
872 signal(SIGHUP, SIG_DFL);
873 signal(SIGINT, SIG_DFL);
874 signal(SIGQUIT, SIG_DFL);
875 signal(SIGTERM, SIG_DFL);
876 signal(SIGALRM, SIG_DFL);
878 DEFAULT(envshell, SHELL);
879 putenv("TERM="TNAME);
880 args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
881 execvp(args[0], args);
889 if(waitpid(pid, &stat, 0) < 0)
890 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
892 if(WIFEXITED(stat)) {
893 exit(WEXITSTATUS(stat));
902 struct winsize w = {term.row, term.col, 0, 0};
904 /* seems to work fine on linux, openbsd and freebsd */
905 if(openpty(&m, &s, NULL, NULL, &w) < 0)
906 die("openpty failed: %s\n", SERRNO);
908 switch(pid = fork()) {
910 die("fork failed\n");
913 setsid(); /* create a new process group */
914 dup2(s, STDIN_FILENO);
915 dup2(s, STDOUT_FILENO);
916 dup2(s, STDERR_FILENO);
917 if(ioctl(s, TIOCSCTTY, NULL) < 0)
918 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
926 signal(SIGCHLD, sigchld);
928 if(!strcmp(opt_io, "-")) {
929 iofd = STDOUT_FILENO;
931 if((iofd = open(opt_io, O_WRONLY | O_CREAT, 0666)) < 0) {
932 fprintf(stderr, "Error opening %s:%s\n",
933 opt_io, strerror(errno));
944 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
946 fprintf(stderr, "\n");
951 static char buf[BUFSIZ];
952 static int buflen = 0;
955 int charsize; /* size of utf8 char in bytes */
959 /* append read bytes to unprocessed bytes */
960 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
961 die("Couldn't read from shell: %s\n", SERRNO);
963 /* process every complete utf8 char */
966 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
967 charsize = utf8decode(ptr, &utf8c);
968 utf8encode(&utf8c, s);
974 /* keep any uncomplete utf8 char for the next call */
975 memmove(buf, ptr, buflen);
979 ttywrite(const char *s, size_t n) {
980 if(write(cmdfd, s, n) == -1)
981 die("write error on tty: %s\n", SERRNO);
992 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
993 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
997 tsetdirt(int top, int bot) {
1000 LIMIT(top, 0, term.row-1);
1001 LIMIT(bot, 0, term.row-1);
1003 for(i = top; i <= bot; i++)
1009 tsetdirt(0, term.row-1);
1016 if(mode == CURSOR_SAVE) {
1018 } else if(mode == CURSOR_LOAD) {
1028 term.c = (TCursor){{
1032 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1034 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1035 for(i = TAB; i < term.col; i += TAB)
1038 term.bot = term.row - 1;
1039 term.mode = MODE_WRAP;
1041 tclearregion(0, 0, term.col-1, term.row-1);
1045 tnew(int col, int row) {
1046 /* set screen size */
1049 term.line = xmalloc(term.row * sizeof(Line));
1050 term.alt = xmalloc(term.row * sizeof(Line));
1051 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1052 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1054 for(row = 0; row < term.row; row++) {
1055 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1056 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1057 term.dirty[row] = 0;
1059 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1066 Line *tmp = term.line;
1068 term.line = term.alt;
1070 term.mode ^= MODE_ALTSCREEN;
1075 tscrolldown(int orig, int n) {
1079 LIMIT(n, 0, term.bot-orig+1);
1081 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1083 for(i = term.bot; i >= orig+n; i--) {
1084 temp = term.line[i];
1085 term.line[i] = term.line[i-n];
1086 term.line[i-n] = temp;
1089 term.dirty[i-n] = 1;
1096 tscrollup(int orig, int n) {
1099 LIMIT(n, 0, term.bot-orig+1);
1101 tclearregion(0, orig, term.col-1, orig+n-1);
1103 for(i = orig; i <= term.bot-n; i++) {
1104 temp = term.line[i];
1105 term.line[i] = term.line[i+n];
1106 term.line[i+n] = temp;
1109 term.dirty[i+n] = 1;
1112 selscroll(orig, -n);
1116 selscroll(int orig, int n) {
1120 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1121 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1125 if(sel.by < term.top) {
1129 if(sel.ey > term.bot) {
1133 sel.b.y = sel.by, sel.b.x = sel.bx;
1134 sel.e.y = sel.ey, sel.e.x = sel.ex;
1139 tnewline(int first_col) {
1143 tscrollup(term.top, 1);
1147 tmoveto(first_col ? 0 : term.c.x, y);
1152 /* int noarg = 1; */
1153 char *p = csiescseq.buf;
1157 csiescseq.priv = 1, p++;
1159 while(p < csiescseq.buf+csiescseq.len) {
1160 while(isdigit(*p)) {
1161 csiescseq.arg[csiescseq.narg] *= 10;
1162 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1164 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1165 csiescseq.narg++, p++;
1167 csiescseq.mode = *p;
1176 tmoveto(int x, int y) {
1177 LIMIT(x, 0, term.col-1);
1178 LIMIT(y, 0, term.row-1);
1179 term.c.state &= ~CURSOR_WRAPNEXT;
1186 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1187 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1188 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1189 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1190 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1191 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1192 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1193 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1194 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1198 * The table is proudly stolen from rxvt.
1200 if(term.c.attr.mode & ATTR_GFX) {
1201 if(c[0] >= 0x41 && c[0] <= 0x7e
1202 && vt100_0[c[0] - 0x41]) {
1203 c = vt100_0[c[0] - 0x41];
1207 term.dirty[term.c.y] = 1;
1208 term.line[term.c.y][term.c.x] = term.c.attr;
1209 memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
1210 term.line[term.c.y][term.c.x].state |= GLYPH_SET;
1214 tclearregion(int x1, int y1, int x2, int y2) {
1218 temp = x1, x1 = x2, x2 = temp;
1220 temp = y1, y1 = y2, y2 = temp;
1222 LIMIT(x1, 0, term.col-1);
1223 LIMIT(x2, 0, term.col-1);
1224 LIMIT(y1, 0, term.row-1);
1225 LIMIT(y2, 0, term.row-1);
1227 for(y = y1; y <= y2; y++) {
1229 for(x = x1; x <= x2; x++)
1230 term.line[y][x].state = 0;
1235 tdeletechar(int n) {
1236 int src = term.c.x + n;
1238 int size = term.col - src;
1240 term.dirty[term.c.y] = 1;
1242 if(src >= term.col) {
1243 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1247 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1248 size * sizeof(Glyph));
1249 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1253 tinsertblank(int n) {
1256 int size = term.col - dst;
1258 term.dirty[term.c.y] = 1;
1260 if(dst >= term.col) {
1261 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1265 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1266 size * sizeof(Glyph));
1267 tclearregion(src, term.c.y, dst - 1, term.c.y);
1271 tinsertblankline(int n) {
1272 if(term.c.y < term.top || term.c.y > term.bot)
1275 tscrolldown(term.c.y, n);
1279 tdeleteline(int n) {
1280 if(term.c.y < term.top || term.c.y > term.bot)
1283 tscrollup(term.c.y, n);
1287 tsetattr(int *attr, int l) {
1290 for(i = 0; i < l; i++) {
1293 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1294 | ATTR_ITALIC | ATTR_BLINK);
1295 term.c.attr.fg = DefaultFG;
1296 term.c.attr.bg = DefaultBG;
1299 term.c.attr.mode |= ATTR_BOLD;
1301 case 3: /* enter standout (highlight) */
1302 term.c.attr.mode |= ATTR_ITALIC;
1305 term.c.attr.mode |= ATTR_UNDERLINE;
1308 term.c.attr.mode |= ATTR_BLINK;
1311 term.c.attr.mode |= ATTR_REVERSE;
1315 term.c.attr.mode &= ~ATTR_BOLD;
1317 case 23: /* leave standout (highlight) mode */
1318 term.c.attr.mode &= ~ATTR_ITALIC;
1321 term.c.attr.mode &= ~ATTR_UNDERLINE;
1324 term.c.attr.mode &= ~ATTR_BLINK;
1327 term.c.attr.mode &= ~ATTR_REVERSE;
1330 if(i + 2 < l && attr[i + 1] == 5) {
1332 if(BETWEEN(attr[i], 0, 255)) {
1333 term.c.attr.fg = attr[i];
1336 "erresc: bad fgcolor %d\n",
1341 "erresc(38): gfx attr %d unknown\n",
1346 term.c.attr.fg = DefaultFG;
1349 if(i + 2 < l && attr[i + 1] == 5) {
1351 if(BETWEEN(attr[i], 0, 255)) {
1352 term.c.attr.bg = attr[i];
1355 "erresc: bad bgcolor %d\n",
1360 "erresc(48): gfx attr %d unknown\n",
1365 term.c.attr.bg = DefaultBG;
1368 if(BETWEEN(attr[i], 30, 37)) {
1369 term.c.attr.fg = attr[i] - 30;
1370 } else if(BETWEEN(attr[i], 40, 47)) {
1371 term.c.attr.bg = attr[i] - 40;
1372 } else if(BETWEEN(attr[i], 90, 97)) {
1373 term.c.attr.fg = attr[i] - 90 + 8;
1374 } else if(BETWEEN(attr[i], 100, 107)) {
1375 term.c.attr.bg = attr[i] - 100 + 8;
1378 "erresc(default): gfx attr %d unknown\n",
1379 attr[i]), csidump();
1387 tsetscroll(int t, int b) {
1390 LIMIT(t, 0, term.row-1);
1391 LIMIT(b, 0, term.row-1);
1401 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1404 tsetmode(bool priv, bool set, int *args, int narg) {
1407 for(lim = args + narg; args < lim; ++args) {
1411 case 1: /* DECCKM -- Cursor key */
1412 MODBIT(term.mode, set, MODE_APPKEYPAD);
1414 case 5: /* DECSCNM -- Reverse video */
1416 MODBIT(term.mode, set, MODE_REVERSE);
1417 if(mode != term.mode)
1420 case 6: /* XXX: DECOM -- Origin */
1422 case 7: /* DECAWM -- Auto wrap */
1423 MODBIT(term.mode, set, MODE_WRAP);
1425 case 8: /* XXX: DECARM -- Auto repeat */
1427 case 0: /* Error (IGNORED) */
1428 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1431 MODBIT(term.c.state, !set, CURSOR_HIDE);
1433 case 1000: /* 1000,1002: enable xterm mouse report */
1434 MODBIT(term.mode, set, MODE_MOUSEBTN);
1437 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1439 case 1049: /* = 1047 and 1048 */
1442 if(IS_SET(MODE_ALTSCREEN))
1443 tclearregion(0, 0, term.col-1, term.row-1);
1444 if((set && !IS_SET(MODE_ALTSCREEN)) ||
1445 (!set && IS_SET(MODE_ALTSCREEN))) {
1452 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1455 /* case 2: DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
1456 /* case 3: DECCOLM -- Column (NOT SUPPORTED) */
1457 /* case 4: DECSCLM -- Scroll (NOT SUPPORTED) */
1458 /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
1459 /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
1460 /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
1462 "erresc: unknown private set/reset mode %d\n",
1468 case 0: /* Error (IGNORED) */
1470 case 2: /* KAM -- keyboard action */
1471 MODBIT(term.mode, set, MODE_KBDLOCK);
1473 case 4: /* IRM -- Insertion-replacement */
1474 MODBIT(term.mode, set, MODE_INSERT);
1476 case 12: /* XXX: SRM -- Send/Receive */
1478 case 20: /* LNM -- Linefeed/new line */
1479 MODBIT(term.mode, set, MODE_CRLF);
1483 "erresc: unknown set/reset mode %d\n",
1495 switch(csiescseq.mode) {
1498 fprintf(stderr, "erresc: unknown csi ");
1502 case '@': /* ICH -- Insert <n> blank char */
1503 DEFAULT(csiescseq.arg[0], 1);
1504 tinsertblank(csiescseq.arg[0]);
1506 case 'A': /* CUU -- Cursor <n> Up */
1508 DEFAULT(csiescseq.arg[0], 1);
1509 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1511 case 'B': /* CUD -- Cursor <n> Down */
1512 DEFAULT(csiescseq.arg[0], 1);
1513 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1515 case 'c': /* DA -- Device Attributes */
1516 if(csiescseq.arg[0] == 0)
1517 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1519 case 'C': /* CUF -- Cursor <n> Forward */
1521 DEFAULT(csiescseq.arg[0], 1);
1522 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1524 case 'D': /* CUB -- Cursor <n> Backward */
1525 DEFAULT(csiescseq.arg[0], 1);
1526 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1528 case 'E': /* CNL -- Cursor <n> Down and first col */
1529 DEFAULT(csiescseq.arg[0], 1);
1530 tmoveto(0, term.c.y+csiescseq.arg[0]);
1532 case 'F': /* CPL -- Cursor <n> Up and first col */
1533 DEFAULT(csiescseq.arg[0], 1);
1534 tmoveto(0, term.c.y-csiescseq.arg[0]);
1536 case 'g': /* TBC -- Tabulation clear */
1537 switch (csiescseq.arg[0]) {
1538 case 0: /* clear current tab stop */
1539 term.tabs[term.c.x] = 0;
1541 case 3: /* clear all the tabs */
1542 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1548 case 'G': /* CHA -- Move to <col> */
1550 DEFAULT(csiescseq.arg[0], 1);
1551 tmoveto(csiescseq.arg[0]-1, term.c.y);
1553 case 'H': /* CUP -- Move to <row> <col> */
1555 DEFAULT(csiescseq.arg[0], 1);
1556 DEFAULT(csiescseq.arg[1], 1);
1557 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1559 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1560 DEFAULT(csiescseq.arg[0], 1);
1561 while(csiescseq.arg[0]--)
1564 case 'J': /* ED -- Clear screen */
1566 switch(csiescseq.arg[0]) {
1568 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1569 if(term.c.y < term.row-1)
1570 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1574 tclearregion(0, 0, term.col-1, term.c.y-1);
1575 tclearregion(0, term.c.y, term.c.x, term.c.y);
1578 tclearregion(0, 0, term.col-1, term.row-1);
1584 case 'K': /* EL -- Clear line */
1585 switch(csiescseq.arg[0]) {
1587 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1590 tclearregion(0, term.c.y, term.c.x, term.c.y);
1593 tclearregion(0, term.c.y, term.col-1, term.c.y);
1597 case 'S': /* SU -- Scroll <n> line up */
1598 DEFAULT(csiescseq.arg[0], 1);
1599 tscrollup(term.top, csiescseq.arg[0]);
1601 case 'T': /* SD -- Scroll <n> line down */
1602 DEFAULT(csiescseq.arg[0], 1);
1603 tscrolldown(term.top, csiescseq.arg[0]);
1605 case 'L': /* IL -- Insert <n> blank lines */
1606 DEFAULT(csiescseq.arg[0], 1);
1607 tinsertblankline(csiescseq.arg[0]);
1609 case 'l': /* RM -- Reset Mode */
1610 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1612 case 'M': /* DL -- Delete <n> lines */
1613 DEFAULT(csiescseq.arg[0], 1);
1614 tdeleteline(csiescseq.arg[0]);
1616 case 'X': /* ECH -- Erase <n> char */
1617 DEFAULT(csiescseq.arg[0], 1);
1618 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1620 case 'P': /* DCH -- Delete <n> char */
1621 DEFAULT(csiescseq.arg[0], 1);
1622 tdeletechar(csiescseq.arg[0]);
1624 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1625 DEFAULT(csiescseq.arg[0], 1);
1626 while(csiescseq.arg[0]--)
1629 case 'd': /* VPA -- Move to <row> */
1630 DEFAULT(csiescseq.arg[0], 1);
1631 tmoveto(term.c.x, csiescseq.arg[0]-1);
1633 case 'h': /* SM -- Set terminal mode */
1634 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1636 case 'm': /* SGR -- Terminal attribute (color) */
1637 tsetattr(csiescseq.arg, csiescseq.narg);
1639 case 'r': /* DECSTBM -- Set Scrolling Region */
1640 if(csiescseq.priv) {
1643 DEFAULT(csiescseq.arg[0], 1);
1644 DEFAULT(csiescseq.arg[1], term.row);
1645 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1649 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1650 tcursor(CURSOR_SAVE);
1652 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1653 tcursor(CURSOR_LOAD);
1664 for(i = 0; i < csiescseq.len; i++) {
1665 c = csiescseq.buf[i] & 0xff;
1668 } else if(c == '\n') {
1670 } else if(c == '\r') {
1672 } else if(c == 0x1b) {
1675 printf("(%02x)", c);
1683 memset(&csiescseq, 0, sizeof(csiescseq));
1691 * TODO: make this being useful in case of color palette change.
1697 switch(strescseq.type) {
1698 case ']': /* OSC -- Operating System Command */
1704 * TODO: Handle special chars in string, like umlauts.
1707 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1711 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1713 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1716 fprintf(stderr, "erresc: unknown str ");
1721 case 'k': /* old title set compatibility */
1722 XStoreName(xw.dpy, xw.win, strescseq.buf);
1724 case 'P': /* DSC -- Device Control String */
1725 case '_': /* APC -- Application Program Command */
1726 case '^': /* PM -- Privacy Message */
1728 fprintf(stderr, "erresc: unknown str ");
1738 * TODO: Implement parsing like for CSI when required.
1739 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1749 printf("ESC%c", strescseq.type);
1750 for(i = 0; i < strescseq.len; i++) {
1751 c = strescseq.buf[i] & 0xff;
1754 } else if(c == '\n') {
1756 } else if(c == '\r') {
1758 } else if(c == 0x1b) {
1761 printf("(%02x)", c);
1769 memset(&strescseq, 0, sizeof(strescseq));
1773 tputtab(bool forward) {
1779 for(++x; x < term.col && !term.tabs[x]; ++x)
1784 for(--x; x > 0 && !term.tabs[x]; --x)
1787 tmoveto(x, term.c.y);
1791 tputc(char *c, int len) {
1793 bool control = ascii < '\x20' || ascii == 0177;
1796 write(iofd, c, len);
1798 * STR sequences must be checked before of anything
1799 * because it can use some control codes as part of the sequence
1801 if(term.esc & ESC_STR) {
1804 term.esc = ESC_START | ESC_STR_END;
1806 case '\a': /* backwards compatibility to xterm */
1811 strescseq.buf[strescseq.len++] = ascii;
1812 if(strescseq.len+1 >= STR_BUF_SIZ) {
1820 * Actions of control codes must be performed as soon they arrive
1821 * because they can be embedded inside a control sequence, and
1822 * they must not cause conflicts with sequences.
1830 tmoveto(term.c.x-1, term.c.y);
1833 tmoveto(0, term.c.y);
1838 /* go to first col if the mode is set */
1839 tnewline(IS_SET(MODE_CRLF));
1841 case '\a': /* BEL */
1842 if(!(xw.state & WIN_FOCUSED))
1845 case '\033': /* ESC */
1847 term.esc = ESC_START;
1849 case '\016': /* SO */
1850 term.c.attr.mode |= ATTR_GFX;
1852 case '\017': /* SI */
1853 term.c.attr.mode &= ~ATTR_GFX;
1855 case '\032': /* SUB */
1856 case '\030': /* CAN */
1859 case '\005': /* ENQ (IGNORED) */
1860 case '\000': /* NUL (IGNORED) */
1861 case '\021': /* XON (IGNORED) */
1862 case '\023': /* XOFF (IGNORED) */
1863 case 0177: /* DEL (IGNORED) */
1866 } else if(term.esc & ESC_START) {
1867 if(term.esc & ESC_CSI) {
1868 csiescseq.buf[csiescseq.len++] = ascii;
1869 if(BETWEEN(ascii, 0x40, 0x7E)
1870 || csiescseq.len >= ESC_BUF_SIZ) {
1872 csiparse(), csihandle();
1874 } else if(term.esc & ESC_STR_END) {
1878 } else if(term.esc & ESC_ALTCHARSET) {
1880 case '0': /* Line drawing set */
1881 term.c.attr.mode |= ATTR_GFX;
1883 case 'B': /* USASCII */
1884 term.c.attr.mode &= ~ATTR_GFX;
1886 case 'A': /* UK (IGNORED) */
1887 case '<': /* multinational charset (IGNORED) */
1888 case '5': /* Finnish (IGNORED) */
1889 case 'C': /* Finnish (IGNORED) */
1890 case 'K': /* German (IGNORED) */
1893 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1899 term.esc |= ESC_CSI;
1901 case 'P': /* DCS -- Device Control String */
1902 case '_': /* APC -- Application Program Command */
1903 case '^': /* PM -- Privacy Message */
1904 case ']': /* OSC -- Operating System Command */
1905 case 'k': /* old title set compatibility */
1907 strescseq.type = ascii;
1908 term.esc |= ESC_STR;
1910 case '(': /* set primary charset G0 */
1911 term.esc |= ESC_ALTCHARSET;
1913 case ')': /* set secondary charset G1 (IGNORED) */
1914 case '*': /* set tertiary charset G2 (IGNORED) */
1915 case '+': /* set quaternary charset G3 (IGNORED) */
1918 case 'D': /* IND -- Linefeed */
1919 if(term.c.y == term.bot) {
1920 tscrollup(term.top, 1);
1922 tmoveto(term.c.x, term.c.y+1);
1926 case 'E': /* NEL -- Next line */
1927 tnewline(1); /* always go to first col */
1930 case 'H': /* HTS -- Horizontal tab stop */
1931 term.tabs[term.c.x] = 1;
1934 case 'M': /* RI -- Reverse index */
1935 if(term.c.y == term.top) {
1936 tscrolldown(term.top, 1);
1938 tmoveto(term.c.x, term.c.y-1);
1942 case 'Z': /* DECID -- Identify Terminal */
1943 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1946 case 'c': /* RIS -- Reset to inital state */
1951 case '=': /* DECPAM -- Application keypad */
1952 term.mode |= MODE_APPKEYPAD;
1955 case '>': /* DECPNM -- Normal keypad */
1956 term.mode &= ~MODE_APPKEYPAD;
1959 case '7': /* DECSC -- Save Cursor */
1960 tcursor(CURSOR_SAVE);
1963 case '8': /* DECRC -- Restore Cursor */
1964 tcursor(CURSOR_LOAD);
1967 case '\\': /* ST -- Stop */
1971 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
1972 (uchar) ascii, isprint(ascii)? ascii:'.');
1977 * All characters which forms part of a sequence are not
1983 * Display control codes only if we are in graphic mode
1985 if(control && !(term.c.attr.mode & ATTR_GFX))
1987 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
1989 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1990 tnewline(1); /* always go to first col */
1992 if(term.c.x+1 < term.col)
1993 tmoveto(term.c.x+1, term.c.y);
1995 term.c.state |= CURSOR_WRAPNEXT;
1999 tresize(int col, int row) {
2001 int minrow = MIN(row, term.row);
2002 int mincol = MIN(col, term.col);
2003 int slide = term.c.y - row + 1;
2006 if(col < 1 || row < 1)
2009 /* free unneeded rows */
2012 /* slide screen to keep cursor where we expect it -
2013 * tscrollup would work here, but we can optimize to
2014 * memmove because we're freeing the earlier lines */
2015 for(/* i = 0 */; i < slide; i++) {
2019 memmove(term.line, term.line + slide, row * sizeof(Line));
2020 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2022 for(i += row; i < term.row; i++) {
2027 /* resize to new height */
2028 term.line = xrealloc(term.line, row * sizeof(Line));
2029 term.alt = xrealloc(term.alt, row * sizeof(Line));
2030 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2031 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2033 /* resize each row to new width, zero-pad if needed */
2034 for(i = 0; i < minrow; i++) {
2036 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2037 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2038 for(x = mincol; x < col; x++) {
2039 term.line[i][x].state = 0;
2040 term.alt[i][x].state = 0;
2044 /* allocate any new rows */
2045 for(/* i == minrow */; i < row; i++) {
2047 term.line[i] = xcalloc(col, sizeof(Glyph));
2048 term.alt [i] = xcalloc(col, sizeof(Glyph));
2050 if(col > term.col) {
2051 bp = term.tabs + term.col;
2053 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2054 while(--bp > term.tabs && !*bp)
2056 for(bp += TAB; bp < term.tabs + col; bp += TAB)
2059 /* update terminal size */
2060 term.col = col, term.row = row;
2061 /* make use of the LIMIT in tmoveto */
2062 tmoveto(term.c.x, term.c.y);
2063 /* reset scrolling region */
2064 tsetscroll(0, row-1);
2070 xresize(int col, int row) {
2071 xw.tw = MAX(1, 2*BORDER + col * xw.cw);
2072 xw.th = MAX(1, 2*BORDER + row * xw.ch);
2074 XftDrawChange(xw.xft_draw, xw.buf);
2080 XRenderColor xft_color = { .alpha = 0 };
2082 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2083 for(i = 0; i < LEN(colorname); i++) {
2086 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
2087 die("Could not allocate color '%s'\n", colorname[i]);
2091 /* load colors [16-255] ; same colors as xterm */
2092 for(i = 16, r = 0; r < 6; r++) {
2093 for(g = 0; g < 6; g++) {
2094 for(b = 0; b < 6; b++) {
2095 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
2096 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
2097 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
2098 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
2099 die("Could not allocate color %d\n", i);
2106 for(r = 0; r < 24; r++, i++) {
2107 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
2108 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color,
2110 die("Could not allocate color %d\n", i);
2116 xtermclear(int col1, int row1, int col2, int row2) {
2117 XftDrawRect(xw.xft_draw,
2118 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2119 BORDER + col1 * xw.cw,
2120 BORDER + row1 * xw.ch,
2121 (col2-col1+1) * xw.cw,
2122 (row2-row1+1) * xw.ch);
2126 * Absolute coordinates.
2129 xclear(int x1, int y1, int x2, int y2) {
2130 XftDrawRect(xw.xft_draw,
2131 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2132 x1, y1, x2-x1, y2-y1);
2137 XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
2138 XWMHints wm = {.flags = InputHint, .input = 1};
2139 XSizeHints *sizeh = NULL;
2141 sizeh = XAllocSizeHints();
2142 if(xw.isfixed == False) {
2143 sizeh->flags = PSize | PResizeInc | PBaseSize;
2144 sizeh->height = xw.h;
2145 sizeh->width = xw.w;
2146 sizeh->height_inc = xw.ch;
2147 sizeh->width_inc = xw.cw;
2148 sizeh->base_height = 2*BORDER;
2149 sizeh->base_width = 2*BORDER;
2151 sizeh->flags = PMaxSize | PMinSize;
2152 sizeh->min_width = sizeh->max_width = xw.fw;
2153 sizeh->min_height = sizeh->max_height = xw.fh;
2156 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2161 xinitfont(Font *f, char *fontstr) {
2162 FcPattern *pattern, *match;
2165 pattern = FcNameParse((FcChar8 *)fontstr);
2167 die("st: can't open font %s\n", fontstr);
2169 match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
2170 FcPatternDestroy(pattern);
2172 die("st: can't open font %s\n", fontstr);
2173 if(!(f->xft_set = XftFontOpenPattern(xw.dpy, match))) {
2174 FcPatternDestroy(match);
2175 die("st: can't open font %s.\n", fontstr);
2178 f->ascent = f->xft_set->ascent;
2179 f->descent = f->xft_set->descent;
2181 f->rbearing = f->xft_set->max_advance_width;
2183 f->height = f->xft_set->height;
2184 f->width = f->lbearing + f->rbearing;
2188 initfonts(char *fontstr) {
2191 xinitfont(&dc.font, fontstr);
2192 xw.cw = dc.font.width;
2193 xw.ch = dc.font.height;
2195 fstr = smstrcat(fontstr, ":weight=bold", NULL);
2196 xinitfont(&dc.bfont, fstr);
2199 fstr = smstrcat(fontstr, ":slant=italic,oblique", NULL);
2200 xinitfont(&dc.ifont, fstr);
2203 fstr = smstrcat(fontstr, ":weight=bold:slant=italic,oblique", NULL);
2204 xinitfont(&dc.ibfont, fstr);
2210 XSetWindowAttributes attrs;
2213 int sw, sh, major, minor;
2215 if(!(xw.dpy = XOpenDisplay(NULL)))
2216 die("Can't open display\n");
2217 xw.scr = XDefaultScreen(xw.dpy);
2218 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2221 initfonts((opt_font != NULL)? opt_font : FONT);
2224 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2227 /* adjust fixed window geometry */
2229 sw = DisplayWidth(xw.dpy, xw.scr);
2230 sh = DisplayHeight(xw.dpy, xw.scr);
2232 xw.fx = sw + xw.fx - xw.fw - 1;
2234 xw.fy = sh + xw.fy - xw.fh - 1;
2239 /* window - default size */
2240 xw.h = 2*BORDER + term.row * xw.ch;
2241 xw.w = 2*BORDER + term.col * xw.cw;
2246 attrs.background_pixel = dc.xft_col[DefaultBG].pixel;
2247 attrs.border_pixel = dc.xft_col[DefaultBG].pixel;
2248 attrs.bit_gravity = NorthWestGravity;
2249 attrs.event_mask = FocusChangeMask | KeyPressMask
2250 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2251 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2252 attrs.colormap = xw.cmap;
2254 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2255 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2256 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2258 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2262 /* double buffering */
2263 if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2264 die("Xdbe extension is not present\n");
2265 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2267 /* Xft rendering context */
2268 xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2271 xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2272 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2273 | XIMStatusNothing, XNClientWindow, xw.win,
2274 XNFocusWindow, xw.win, NULL);
2276 dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2278 /* white cursor, black outline */
2279 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2280 XDefineCursor(xw.dpy, xw.win, cursor);
2281 XRecolorCursor(xw.dpy, cursor,
2282 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2283 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2285 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2286 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2287 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2290 XMapWindow(xw.dpy, xw.win);
2296 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2297 int winx = BORDER + x * xw.cw, winy = BORDER + y * xw.ch,
2298 width = charlen * xw.cw;
2299 Font *font = &dc.font;
2301 XftColor *fg = &dc.xft_col[base.fg], *bg = &dc.xft_col[base.bg],
2302 *temp, revfg, revbg;
2303 XRenderColor colfg, colbg;
2305 if(base.mode & ATTR_REVERSE)
2306 temp = fg, fg = bg, bg = temp;
2308 if(base.mode & ATTR_BOLD) {
2309 if(BETWEEN(base.fg, 0, 7)) {
2310 /* basic system colors */
2311 fg = &dc.xft_col[base.fg + 8];
2312 } else if(BETWEEN(base.fg, 16, 195)) {
2314 fg = &dc.xft_col[base.fg + 36];
2315 } else if(BETWEEN(base.fg, 232, 251)) {
2317 fg = &dc.xft_col[base.fg + 4];
2320 * Those ranges will not be brightened:
2321 * 8 - 15 – bright system colors
2322 * 196 - 231 – highest 256 color cube
2323 * 252 - 255 – brightest colors in greyscale
2328 if(base.mode & ATTR_ITALIC)
2330 if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
2333 if(IS_SET(MODE_REVERSE)) {
2334 if(fg == &dc.xft_col[DefaultFG]) {
2335 fg = &dc.xft_col[DefaultBG];
2337 colfg.red = ~fg->color.red;
2338 colfg.green = ~fg->color.green;
2339 colfg.blue = ~fg->color.blue;
2340 colfg.alpha = fg->color.alpha;
2341 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2345 if(bg == &dc.xft_col[DefaultBG]) {
2346 bg = &dc.xft_col[DefaultFG];
2348 colbg.red = ~bg->color.red;
2349 colbg.green = ~bg->color.green;
2350 colbg.blue = ~bg->color.blue;
2351 colbg.alpha = bg->color.alpha;
2352 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2357 XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen,
2359 width = extents.xOff;
2361 /* Intelligent cleaning up of the borders. */
2363 xclear(0, (y == 0)? 0 : winy, BORDER,
2364 winy + xw.ch + (y == term.row-1)? xw.h : 0);
2366 if(x + charlen >= term.col-1) {
2367 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2368 (y == term.row-1)? xw.h : (winy + xw.ch));
2371 xclear(winx, 0, winx + width, BORDER);
2373 xclear(winx, winy + xw.ch, winx + width, xw.h);
2375 XftDrawRect(xw.xft_draw, bg, winx, winy, width, xw.ch);
2376 XftDrawStringUtf8(xw.xft_draw, fg, font->xft_set, winx,
2377 winy + font->ascent, (FcChar8 *)s, bytelen);
2379 if(base.mode & ATTR_UNDERLINE) {
2380 XftDrawRect(xw.xft_draw, fg, winx, winy + font->ascent + 1,
2387 static int oldx = 0, oldy = 0;
2389 Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
2391 LIMIT(oldx, 0, term.col-1);
2392 LIMIT(oldy, 0, term.row-1);
2394 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2395 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2397 /* remove the old cursor */
2398 if(term.line[oldy][oldx].state & GLYPH_SET) {
2399 sl = utf8size(term.line[oldy][oldx].c);
2400 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2403 xtermclear(oldx, oldy, oldx, oldy);
2406 /* draw the new one */
2407 if(!(term.c.state & CURSOR_HIDE)) {
2408 if(!(xw.state & WIN_FOCUSED))
2411 if(IS_SET(MODE_REVERSE))
2412 g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
2415 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2416 oldx = term.c.x, oldy = term.c.y;
2422 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2427 struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2431 XSync(xw.dpy, False); /* necessary for a good tput flash */
2432 nanosleep(&tv, NULL);
2437 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2439 drawregion(0, 0, term.col, term.row);
2440 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2444 drawregion(int x1, int y1, int x2, int y2) {
2445 int ic, ib, x, y, ox, sl;
2447 char buf[DRAW_BUF_SIZ];
2448 bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
2450 if((sel.alt && !alt) || (!sel.alt && alt))
2452 if(!(xw.state & WIN_VISIBLE))
2455 for(y = y1; y < y2; y++) {
2459 xtermclear(0, y, term.col, y);
2461 base = term.line[y][0];
2463 for(x = x1; x < x2; x++) {
2464 new = term.line[y][x];
2465 if(ena_sel && *(new.c) && selected(x, y))
2466 new.mode ^= ATTR_REVERSE;
2467 if(ib > 0 && (!(new.state & GLYPH_SET)
2468 || ATTRCMP(base, new)
2469 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2470 xdraws(buf, base, ox, y, ic, ib);
2473 if(new.state & GLYPH_SET) {
2478 sl = utf8size(new.c);
2479 memcpy(buf+ib, new.c, sl);
2485 xdraws(buf, base, ox, y, ic, ib);
2491 expose(XEvent *ev) {
2492 XExposeEvent *e = &ev->xexpose;
2494 if(xw.state & WIN_REDRAW) {
2496 xw.state &= ~WIN_REDRAW;
2501 visibility(XEvent *ev) {
2502 XVisibilityEvent *e = &ev->xvisibility;
2504 if(e->state == VisibilityFullyObscured) {
2505 xw.state &= ~WIN_VISIBLE;
2506 } else if(!(xw.state & WIN_VISIBLE)) {
2507 /* need a full redraw for next Expose, not just a buf copy */
2508 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2514 xw.state &= ~WIN_VISIBLE;
2518 xseturgency(int add) {
2519 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2521 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2522 XSetWMHints(xw.dpy, xw.win, h);
2528 if(ev->type == FocusIn) {
2529 xw.state |= WIN_FOCUSED;
2532 xw.state &= ~WIN_FOCUSED;
2537 kmap(KeySym k, uint state) {
2542 for(i = 0; i < LEN(key); i++) {
2545 if(key[i].k == k && ((state & mask) == mask
2546 || (mask == XK_NO_MOD && !state))) {
2547 return (char*)key[i].s;
2554 kpress(XEvent *ev) {
2555 XKeyEvent *e = &ev->xkey;
2564 if (IS_SET(MODE_KBDLOCK))
2567 meta = e->state & Mod1Mask;
2568 shift = e->state & ShiftMask;
2569 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2571 /* 1. custom keys from config.h */
2572 if((customkey = kmap(ksym, e->state))) {
2573 ttywrite(customkey, strlen(customkey));
2574 /* 2. hardcoded (overrides X lookup) */
2581 /* XXX: shift up/down doesn't work */
2582 sprintf(buf, "\033%c%c",
2583 IS_SET(MODE_APPKEYPAD) ? 'O' : '[',
2584 (shift ? "dacb":"DACB")[ksym - XK_Left]);
2592 if(IS_SET(MODE_CRLF)) {
2593 ttywrite("\r\n", 2);
2601 if(meta && len == 1)
2602 ttywrite("\033", 1);
2611 cmessage(XEvent *e) {
2613 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2614 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2615 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2616 xw.state |= WIN_FOCUSED;
2618 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2619 xw.state &= ~WIN_FOCUSED;
2621 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
2622 /* Send SIGHUP to shell */
2632 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2635 xw.w = e->xconfigure.width;
2636 xw.h = e->xconfigure.height;
2637 col = (xw.w - 2*BORDER) / xw.cw;
2638 row = (xw.h - 2*BORDER) / xw.ch;
2639 if(col == term.col && row == term.row)
2651 int xfd = XConnectionNumber(xw.dpy), i;
2652 struct timeval drawtimeout, *tv = NULL;
2656 FD_SET(cmdfd, &rfd);
2658 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2661 die("select failed: %s\n", SERRNO);
2665 * Stop after a certain number of reads so the user does not
2666 * feel like the system is stuttering.
2668 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2672 * Just wait a bit so it isn't disturbing the
2673 * user and the system is able to write something.
2675 drawtimeout.tv_sec = 0;
2676 drawtimeout.tv_usec = 5;
2683 while(XPending(xw.dpy)) {
2684 XNextEvent(xw.dpy, &ev);
2685 if(XFilterEvent(&ev, xw.win))
2687 if(handler[ev.type])
2688 (handler[ev.type])(&ev);
2697 main(int argc, char *argv[]) {
2698 int i, bitm, xr, yr;
2701 xw.fw = xw.fh = xw.fx = xw.fy = 0;
2704 for(i = 1; i < argc; i++) {
2705 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2708 opt_class = argv[i];
2711 /* eat every remaining arguments */
2723 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2728 if(bitm & WidthValue)
2730 if(bitm & HeightValue)
2732 if(bitm & XNegative && xw.fx == 0)
2734 if(bitm & XNegative && xw.fy == 0)
2737 if(xw.fh != 0 && xw.fw != 0)
2746 opt_title = argv[i];
2753 opt_embed = argv[i];
2759 setlocale(LC_CTYPE, "");