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 */
126 ESC_TEST = 32, /* Enter in test mode */
137 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
139 typedef unsigned char uchar;
140 typedef unsigned int uint;
141 typedef unsigned long ulong;
142 typedef unsigned short ushort;
145 char c[UTF_SIZ]; /* character code */
146 uchar mode; /* attribute flags */
147 ushort fg; /* foreground */
148 ushort bg; /* background */
149 uchar state; /* state flags */
155 Glyph attr; /* current char attributes */
161 /* CSI Escape sequence structs */
162 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
164 char buf[ESC_BUF_SIZ]; /* raw string */
165 int len; /* raw string length */
167 int arg[ESC_ARG_SIZ];
168 int narg; /* nb of args */
172 /* STR Escape sequence structs */
173 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
175 char type; /* ESC type ... */
176 char buf[STR_BUF_SIZ]; /* raw string */
177 int len; /* raw string length */
178 char *args[STR_ARG_SIZ];
179 int narg; /* nb of args */
182 /* Internal representation of the screen */
184 int row; /* nb row */
185 int col; /* nb col */
186 Line *line; /* screen */
187 Line *alt; /* alternate screen */
188 bool *dirty; /* dirtyness of lines */
189 TCursor c; /* cursor */
190 int top; /* top scroll limit */
191 int bot; /* bottom scroll limit */
192 int mode; /* terminal mode flags */
193 int esc; /* escape state flags */
197 /* Purely graphic info */
203 Atom xembed, wmdeletewin;
209 bool isfixed; /* is fixed geometry? */
210 int fx, fy, fw, fh; /* fixed geometry */
211 int tw, th; /* tty width and height */
212 int w; /* window width */
213 int h; /* window height */
214 int ch; /* char height */
215 int cw; /* char width */
216 char state; /* focus, redraw, visible */
225 /* TODO: use better name for vars... */
236 struct timeval tclick1;
237 struct timeval tclick2;
253 /* Drawing Context */
255 XftColor xft_col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
257 Font font, bfont, ifont, ibfont;
260 static void die(const char *, ...);
261 static void draw(void);
262 static void redraw(void);
263 static void drawregion(int, int, int, int);
264 static void execsh(void);
265 static void sigchld(int);
266 static void run(void);
268 static void csidump(void);
269 static void csihandle(void);
270 static void csiparse(void);
271 static void csireset(void);
272 static void strdump(void);
273 static void strhandle(void);
274 static void strparse(void);
275 static void strreset(void);
277 static void tclearregion(int, int, int, int);
278 static void tcursor(int);
279 static void tdeletechar(int);
280 static void tdeleteline(int);
281 static void tinsertblank(int);
282 static void tinsertblankline(int);
283 static void tmoveto(int, int);
284 static void tnew(int, int);
285 static void tnewline(int);
286 static void tputtab(bool);
287 static void tputc(char *, int);
288 static void treset(void);
289 static int tresize(int, int);
290 static void tscrollup(int, int);
291 static void tscrolldown(int, int);
292 static void tsetattr(int*, int);
293 static void tsetchar(char *, Glyph *, int, int);
294 static void tsetscroll(int, int);
295 static void tswapscreen(void);
296 static void tsetdirt(int, int);
297 static void tsetmode(bool, bool, int *, int);
298 static void tfulldirt(void);
300 static void ttynew(void);
301 static void ttyread(void);
302 static void ttyresize(void);
303 static void ttywrite(const char *, size_t);
305 static void xdraws(char *, Glyph, int, int, int, int);
306 static void xhints(void);
307 static void xclear(int, int, int, int);
308 static void xdrawcursor(void);
309 static void xinit(void);
310 static void xloadcols(void);
311 static void xresettitle(void);
312 static void xseturgency(int);
313 static void xsetsel(char*);
314 static void xtermclear(int, int, int, int);
315 static void xresize(int, int);
317 static void expose(XEvent *);
318 static void visibility(XEvent *);
319 static void unmap(XEvent *);
320 static char *kmap(KeySym, uint);
321 static void kpress(XEvent *);
322 static void cmessage(XEvent *);
323 static void resize(XEvent *);
324 static void focus(XEvent *);
325 static void brelease(XEvent *);
326 static void bpress(XEvent *);
327 static void bmotion(XEvent *);
328 static void selnotify(XEvent *);
329 static void selclear(XEvent *);
330 static void selrequest(XEvent *);
332 static void selinit(void);
333 static inline bool selected(int, int);
334 static void selcopy(void);
335 static void selpaste(void);
336 static void selscroll(int, int);
338 static int utf8decode(char *, long *);
339 static int utf8encode(long *, char *);
340 static int utf8size(char *);
341 static int isfullutf8(char *, int);
343 static ssize_t xwrite(int, char *, size_t);
344 static void *xmalloc(size_t);
345 static void *xrealloc(void *, size_t);
346 static void *xcalloc(size_t nmemb, size_t size);
347 static char *smstrcat(char *, ...);
349 static void (*handler[LASTEvent])(XEvent *) = {
351 [ClientMessage] = cmessage,
352 [ConfigureNotify] = resize,
353 [VisibilityNotify] = visibility,
354 [UnmapNotify] = unmap,
358 [MotionNotify] = bmotion,
359 [ButtonPress] = bpress,
360 [ButtonRelease] = brelease,
361 [SelectionClear] = selclear,
362 [SelectionNotify] = selnotify,
363 [SelectionRequest] = selrequest,
370 static CSIEscape csiescseq;
371 static STREscape strescseq;
374 static Selection sel;
375 static int iofd = -1;
376 static char **opt_cmd = NULL;
377 static char *opt_io = NULL;
378 static char *opt_title = NULL;
379 static char *opt_embed = NULL;
380 static char *opt_class = NULL;
381 static char *opt_font = NULL;
385 xwrite(int fd, char *s, size_t len) {
389 ssize_t r = write(fd, s, len);
399 xmalloc(size_t len) {
400 void *p = malloc(len);
403 die("Out of memory\n");
409 xrealloc(void *p, size_t len) {
410 if((p = realloc(p, len)) == NULL)
411 die("Out of memory\n");
417 xcalloc(size_t nmemb, size_t size) {
418 void *p = calloc(nmemb, size);
421 die("Out of memory\n");
427 smstrcat(char *src, ...)
433 len = slen = strlen(src);
435 va_start(fmtargs, src);
437 v = va_arg(fmtargs, char *);
444 p = ret = xmalloc(len+1);
445 memmove(p, src, slen);
448 va_start(fmtargs, src);
450 v = va_arg(fmtargs, char *);
465 utf8decode(char *s, long *u) {
471 if(~c & B7) { /* 0xxxxxxx */
474 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
475 *u = c&(B4|B3|B2|B1|B0);
477 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
478 *u = c&(B3|B2|B1|B0);
480 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
487 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
489 if((c & (B7|B6)) != B7) /* 10xxxxxx */
492 *u |= c & (B5|B4|B3|B2|B1|B0);
495 if((n == 1 && *u < 0x80) ||
496 (n == 2 && *u < 0x800) ||
497 (n == 3 && *u < 0x10000) ||
498 (*u >= 0xD800 && *u <= 0xDFFF)) {
510 utf8encode(long *u, char *s) {
518 *sp = uc; /* 0xxxxxxx */
520 } else if(*u < 0x800) {
521 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
523 } else if(uc < 0x10000) {
524 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
526 } else if(uc <= 0x10FFFF) {
527 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
533 for(i=n,++sp; i>0; --i,++sp)
534 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
546 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
547 UTF-8 otherwise return 0 */
549 isfullutf8(char *s, int b) {
557 } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
559 } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
561 ((b == 2) && (*c2&(B7|B6)) == B7))) {
563 } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
565 ((b == 2) && (*c2&(B7|B6)) == B7) ||
566 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
579 } else if((c&(B7|B6|B5)) == (B7|B6)) {
581 } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
590 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
591 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
595 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
596 if(sel.xtarget == None)
597 sel.xtarget = XA_STRING;
601 selected(int x, int y) {
604 if(sel.ey == y && sel.by == y) {
605 bx = MIN(sel.bx, sel.ex);
606 ex = MAX(sel.bx, sel.ex);
607 return BETWEEN(x, bx, ex);
610 return ((sel.b.y < y && y < sel.e.y)
611 || (y == sel.e.y && x <= sel.e.x))
612 || (y == sel.b.y && x >= sel.b.x
613 && (x <= sel.e.x || sel.b.y != sel.e.y));
617 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
619 *b = e->xbutton.button;
621 *x = X2COL(e->xbutton.x);
622 *y = Y2ROW(e->xbutton.y);
623 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
624 sel.b.y = MIN(sel.by, sel.ey);
625 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
626 sel.e.y = MAX(sel.by, sel.ey);
630 mousereport(XEvent *e) {
631 int x = X2COL(e->xbutton.x);
632 int y = Y2ROW(e->xbutton.y);
633 int button = e->xbutton.button;
634 int state = e->xbutton.state;
635 char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
636 static int ob, ox, oy;
639 if(e->xbutton.type == MotionNotify) {
640 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
644 } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
650 if(e->xbutton.type == ButtonPress) {
656 buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
657 + (state & Mod4Mask ? 8 : 0)
658 + (state & ControlMask ? 16 : 0);
660 ttywrite(buf, sizeof(buf));
665 if(IS_SET(MODE_MOUSE)) {
667 } else if(e->xbutton.button == Button1) {
670 tsetdirt(sel.b.y, sel.e.y);
674 sel.ex = sel.bx = X2COL(e->xbutton.x);
675 sel.ey = sel.by = Y2ROW(e->xbutton.y);
682 int x, y, bufsize, is_selected = 0, size;
688 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
689 ptr = str = xmalloc(bufsize);
691 /* append every set & selected glyph to the selection */
692 for(y = 0; y < term.row; y++) {
693 for(x = 0; x < term.col; x++) {
694 gp = &term.line[y][x];
696 if(!(is_selected = selected(x, y))
697 || !(gp->state & GLYPH_SET)) {
700 size = utf8size(gp->c);
701 memcpy(ptr, gp->c, size);
704 /* \n at the end of every selected line except for the last one */
705 if(is_selected && y < sel.e.y)
710 sel.alt = IS_SET(MODE_ALTSCREEN);
715 selnotify(XEvent *e) {
716 ulong nitems, ofs, rem;
723 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
724 False, AnyPropertyType, &type, &format,
725 &nitems, &rem, &data)) {
726 fprintf(stderr, "Clipboard allocation failed\n");
729 ttywrite((const char *) data, nitems * format / 8);
731 /* number of 32-bit chunks returned */
732 ofs += nitems * format / 32;
738 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
739 xw.win, CurrentTime);
742 void selclear(XEvent *e) {
746 tsetdirt(sel.b.y, sel.e.y);
750 selrequest(XEvent *e) {
751 XSelectionRequestEvent *xsre;
753 Atom xa_targets, string;
755 xsre = (XSelectionRequestEvent *) e;
756 xev.type = SelectionNotify;
757 xev.requestor = xsre->requestor;
758 xev.selection = xsre->selection;
759 xev.target = xsre->target;
760 xev.time = xsre->time;
764 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
765 if(xsre->target == xa_targets) {
766 /* respond with the supported type */
767 string = sel.xtarget;
768 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
769 XA_ATOM, 32, PropModeReplace,
770 (uchar *) &string, 1);
771 xev.property = xsre->property;
772 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
773 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
774 xsre->target, 8, PropModeReplace,
775 (uchar *) sel.clip, strlen(sel.clip));
776 xev.property = xsre->property;
779 /* all done, send a notification to the listener */
780 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
781 fprintf(stderr, "Error sending SelectionNotify event\n");
786 /* register the selection for both the clipboard and the primary */
792 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
794 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
795 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
799 brelease(XEvent *e) {
802 if(IS_SET(MODE_MOUSE)) {
807 if(e->xbutton.button == Button2) {
809 } else if(e->xbutton.button == Button1) {
811 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
812 term.dirty[sel.ey] = 1;
813 if(sel.bx == sel.ex && sel.by == sel.ey) {
815 gettimeofday(&now, NULL);
817 if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
818 /* triple click on the line */
819 sel.b.x = sel.bx = 0;
820 sel.e.x = sel.ex = term.col;
821 sel.b.y = sel.e.y = sel.ey;
823 } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
824 /* double click to select word */
826 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
827 term.line[sel.ey][sel.bx-1].c[0] != ' ') {
831 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
832 term.line[sel.ey][sel.ex+1].c[0] != ' ') {
836 sel.b.y = sel.e.y = sel.ey;
844 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
845 gettimeofday(&sel.tclick1, NULL);
850 int starty, endy, oldey, oldex;
852 if(IS_SET(MODE_MOUSE)) {
860 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
862 if(oldey != sel.ey || oldex != sel.ex) {
863 starty = MIN(oldey, sel.ey);
864 endy = MAX(oldey, sel.ey);
865 tsetdirt(starty, endy);
871 die(const char *errstr, ...) {
874 va_start(ap, errstr);
875 vfprintf(stderr, errstr, ap);
883 char *envshell = getenv("SHELL");
889 signal(SIGCHLD, SIG_DFL);
890 signal(SIGHUP, SIG_DFL);
891 signal(SIGINT, SIG_DFL);
892 signal(SIGQUIT, SIG_DFL);
893 signal(SIGTERM, SIG_DFL);
894 signal(SIGALRM, SIG_DFL);
896 DEFAULT(envshell, SHELL);
897 putenv("TERM="TNAME);
898 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
899 execvp(args[0], args);
907 if(waitpid(pid, &stat, 0) < 0)
908 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
910 if(WIFEXITED(stat)) {
911 exit(WEXITSTATUS(stat));
920 struct winsize w = {term.row, term.col, 0, 0};
922 /* seems to work fine on linux, openbsd and freebsd */
923 if(openpty(&m, &s, NULL, NULL, &w) < 0)
924 die("openpty failed: %s\n", SERRNO);
926 switch(pid = fork()) {
928 die("fork failed\n");
931 setsid(); /* create a new process group */
932 dup2(s, STDIN_FILENO);
933 dup2(s, STDOUT_FILENO);
934 dup2(s, STDERR_FILENO);
935 if(ioctl(s, TIOCSCTTY, NULL) < 0)
936 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
944 signal(SIGCHLD, sigchld);
946 iofd = (!strcmp(opt_io, "-")) ?
948 open(opt_io, O_WRONLY | O_CREAT, 0666);
950 fprintf(stderr, "Error opening %s:%s\n",
951 opt_io, strerror(errno));
961 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
963 fprintf(stderr, "\n");
968 static char buf[BUFSIZ];
969 static int buflen = 0;
972 int charsize; /* size of utf8 char in bytes */
976 /* append read bytes to unprocessed bytes */
977 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
978 die("Couldn't read from shell: %s\n", SERRNO);
980 /* process every complete utf8 char */
983 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
984 charsize = utf8decode(ptr, &utf8c);
985 utf8encode(&utf8c, s);
991 /* keep any uncomplete utf8 char for the next call */
992 memmove(buf, ptr, buflen);
996 ttywrite(const char *s, size_t n) {
997 if(write(cmdfd, s, n) == -1)
998 die("write error on tty: %s\n", SERRNO);
1005 w.ws_row = term.row;
1006 w.ws_col = term.col;
1007 w.ws_xpixel = xw.tw;
1008 w.ws_ypixel = xw.th;
1009 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1010 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1014 tsetdirt(int top, int bot) {
1017 LIMIT(top, 0, term.row-1);
1018 LIMIT(bot, 0, term.row-1);
1020 for(i = top; i <= bot; i++)
1026 tsetdirt(0, term.row-1);
1033 if(mode == CURSOR_SAVE) {
1035 } else if(mode == CURSOR_LOAD) {
1045 term.c = (TCursor){{
1049 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1051 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1052 for(i = TAB; i < term.col; i += TAB)
1055 term.bot = term.row - 1;
1056 term.mode = MODE_WRAP;
1058 tclearregion(0, 0, term.col-1, term.row-1);
1062 tnew(int col, int row) {
1063 /* set screen size */
1066 term.line = xmalloc(term.row * sizeof(Line));
1067 term.alt = xmalloc(term.row * sizeof(Line));
1068 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1069 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1071 for(row = 0; row < term.row; row++) {
1072 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1073 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1074 term.dirty[row] = 0;
1076 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1083 Line *tmp = term.line;
1085 term.line = term.alt;
1087 term.mode ^= MODE_ALTSCREEN;
1092 tscrolldown(int orig, int n) {
1096 LIMIT(n, 0, term.bot-orig+1);
1098 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1100 for(i = term.bot; i >= orig+n; i--) {
1101 temp = term.line[i];
1102 term.line[i] = term.line[i-n];
1103 term.line[i-n] = temp;
1106 term.dirty[i-n] = 1;
1113 tscrollup(int orig, int n) {
1116 LIMIT(n, 0, term.bot-orig+1);
1118 tclearregion(0, orig, term.col-1, orig+n-1);
1120 for(i = orig; i <= term.bot-n; i++) {
1121 temp = term.line[i];
1122 term.line[i] = term.line[i+n];
1123 term.line[i+n] = temp;
1126 term.dirty[i+n] = 1;
1129 selscroll(orig, -n);
1133 selscroll(int orig, int n) {
1137 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1138 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1142 if(sel.by < term.top) {
1146 if(sel.ey > term.bot) {
1150 sel.b.y = sel.by, sel.b.x = sel.bx;
1151 sel.e.y = sel.ey, sel.e.x = sel.ex;
1156 tnewline(int first_col) {
1160 tscrollup(term.top, 1);
1164 tmoveto(first_col ? 0 : term.c.x, y);
1169 /* int noarg = 1; */
1170 char *p = csiescseq.buf;
1174 csiescseq.priv = 1, p++;
1176 while(p < csiescseq.buf+csiescseq.len) {
1177 while(isdigit(*p)) {
1178 csiescseq.arg[csiescseq.narg] *= 10;
1179 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1181 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1182 csiescseq.narg++, p++;
1184 csiescseq.mode = *p;
1193 tmoveto(int x, int y) {
1194 LIMIT(x, 0, term.col-1);
1195 LIMIT(y, 0, term.row-1);
1196 term.c.state &= ~CURSOR_WRAPNEXT;
1202 tsetchar(char *c, Glyph *attr, int x, int y) {
1203 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1204 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1205 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1206 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1207 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1208 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1209 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1210 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1211 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1215 * The table is proudly stolen from rxvt.
1217 if(attr->mode & ATTR_GFX) {
1218 if(c[0] >= 0x41 && c[0] <= 0x7e
1219 && vt100_0[c[0] - 0x41]) {
1220 c = vt100_0[c[0] - 0x41];
1225 term.line[y][x] = *attr;
1226 memcpy(term.line[y][x].c, c, UTF_SIZ);
1227 term.line[y][x].state |= GLYPH_SET;
1231 tclearregion(int x1, int y1, int x2, int y2) {
1235 temp = x1, x1 = x2, x2 = temp;
1237 temp = y1, y1 = y2, y2 = temp;
1239 LIMIT(x1, 0, term.col-1);
1240 LIMIT(x2, 0, term.col-1);
1241 LIMIT(y1, 0, term.row-1);
1242 LIMIT(y2, 0, term.row-1);
1244 for(y = y1; y <= y2; y++) {
1246 for(x = x1; x <= x2; x++)
1247 term.line[y][x].state = 0;
1252 tdeletechar(int n) {
1253 int src = term.c.x + n;
1255 int size = term.col - src;
1257 term.dirty[term.c.y] = 1;
1259 if(src >= term.col) {
1260 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1264 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1265 size * sizeof(Glyph));
1266 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1270 tinsertblank(int n) {
1273 int size = term.col - dst;
1275 term.dirty[term.c.y] = 1;
1277 if(dst >= term.col) {
1278 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1282 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1283 size * sizeof(Glyph));
1284 tclearregion(src, term.c.y, dst - 1, term.c.y);
1288 tinsertblankline(int n) {
1289 if(term.c.y < term.top || term.c.y > term.bot)
1292 tscrolldown(term.c.y, n);
1296 tdeleteline(int n) {
1297 if(term.c.y < term.top || term.c.y > term.bot)
1300 tscrollup(term.c.y, n);
1304 tsetattr(int *attr, int l) {
1307 for(i = 0; i < l; i++) {
1310 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1311 | ATTR_ITALIC | ATTR_BLINK);
1312 term.c.attr.fg = DefaultFG;
1313 term.c.attr.bg = DefaultBG;
1316 term.c.attr.mode |= ATTR_BOLD;
1318 case 3: /* enter standout (highlight) */
1319 term.c.attr.mode |= ATTR_ITALIC;
1322 term.c.attr.mode |= ATTR_UNDERLINE;
1325 term.c.attr.mode |= ATTR_BLINK;
1328 term.c.attr.mode |= ATTR_REVERSE;
1332 term.c.attr.mode &= ~ATTR_BOLD;
1334 case 23: /* leave standout (highlight) mode */
1335 term.c.attr.mode &= ~ATTR_ITALIC;
1338 term.c.attr.mode &= ~ATTR_UNDERLINE;
1341 term.c.attr.mode &= ~ATTR_BLINK;
1344 term.c.attr.mode &= ~ATTR_REVERSE;
1347 if(i + 2 < l && attr[i + 1] == 5) {
1349 if(BETWEEN(attr[i], 0, 255)) {
1350 term.c.attr.fg = attr[i];
1353 "erresc: bad fgcolor %d\n",
1358 "erresc(38): gfx attr %d unknown\n",
1363 term.c.attr.fg = DefaultFG;
1366 if(i + 2 < l && attr[i + 1] == 5) {
1368 if(BETWEEN(attr[i], 0, 255)) {
1369 term.c.attr.bg = attr[i];
1372 "erresc: bad bgcolor %d\n",
1377 "erresc(48): gfx attr %d unknown\n",
1382 term.c.attr.bg = DefaultBG;
1385 if(BETWEEN(attr[i], 30, 37)) {
1386 term.c.attr.fg = attr[i] - 30;
1387 } else if(BETWEEN(attr[i], 40, 47)) {
1388 term.c.attr.bg = attr[i] - 40;
1389 } else if(BETWEEN(attr[i], 90, 97)) {
1390 term.c.attr.fg = attr[i] - 90 + 8;
1391 } else if(BETWEEN(attr[i], 100, 107)) {
1392 term.c.attr.bg = attr[i] - 100 + 8;
1395 "erresc(default): gfx attr %d unknown\n",
1396 attr[i]), csidump();
1404 tsetscroll(int t, int b) {
1407 LIMIT(t, 0, term.row-1);
1408 LIMIT(b, 0, term.row-1);
1418 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1421 tsetmode(bool priv, bool set, int *args, int narg) {
1424 for(lim = args + narg; args < lim; ++args) {
1428 case 1: /* DECCKM -- Cursor key */
1429 MODBIT(term.mode, set, MODE_APPKEYPAD);
1431 case 5: /* DECSCNM -- Reverse video */
1433 MODBIT(term.mode, set, MODE_REVERSE);
1434 if(mode != term.mode)
1437 case 6: /* XXX: DECOM -- Origin */
1439 case 7: /* DECAWM -- Auto wrap */
1440 MODBIT(term.mode, set, MODE_WRAP);
1442 case 8: /* XXX: DECARM -- Auto repeat */
1444 case 0: /* Error (IGNORED) */
1445 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1448 MODBIT(term.c.state, !set, CURSOR_HIDE);
1450 case 1000: /* 1000,1002: enable xterm mouse report */
1451 MODBIT(term.mode, set, MODE_MOUSEBTN);
1454 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1456 case 1049: /* = 1047 and 1048 */
1459 if(IS_SET(MODE_ALTSCREEN))
1460 tclearregion(0, 0, term.col-1, term.row-1);
1461 if((set && !IS_SET(MODE_ALTSCREEN)) ||
1462 (!set && IS_SET(MODE_ALTSCREEN))) {
1469 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1472 /* case 2: DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
1473 /* case 3: DECCOLM -- Column (NOT SUPPORTED) */
1474 /* case 4: DECSCLM -- Scroll (NOT SUPPORTED) */
1475 /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
1476 /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
1477 /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
1479 "erresc: unknown private set/reset mode %d\n",
1485 case 0: /* Error (IGNORED) */
1487 case 2: /* KAM -- keyboard action */
1488 MODBIT(term.mode, set, MODE_KBDLOCK);
1490 case 4: /* IRM -- Insertion-replacement */
1491 MODBIT(term.mode, set, MODE_INSERT);
1493 case 12: /* XXX: SRM -- Send/Receive */
1495 case 20: /* LNM -- Linefeed/new line */
1496 MODBIT(term.mode, set, MODE_CRLF);
1500 "erresc: unknown set/reset mode %d\n",
1512 switch(csiescseq.mode) {
1515 fprintf(stderr, "erresc: unknown csi ");
1519 case '@': /* ICH -- Insert <n> blank char */
1520 DEFAULT(csiescseq.arg[0], 1);
1521 tinsertblank(csiescseq.arg[0]);
1523 case 'A': /* CUU -- Cursor <n> Up */
1525 DEFAULT(csiescseq.arg[0], 1);
1526 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1528 case 'B': /* CUD -- Cursor <n> Down */
1529 DEFAULT(csiescseq.arg[0], 1);
1530 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1532 case 'c': /* DA -- Device Attributes */
1533 if(csiescseq.arg[0] == 0)
1534 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1536 case 'C': /* CUF -- Cursor <n> Forward */
1538 DEFAULT(csiescseq.arg[0], 1);
1539 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1541 case 'D': /* CUB -- Cursor <n> Backward */
1542 DEFAULT(csiescseq.arg[0], 1);
1543 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1545 case 'E': /* CNL -- Cursor <n> Down and first col */
1546 DEFAULT(csiescseq.arg[0], 1);
1547 tmoveto(0, term.c.y+csiescseq.arg[0]);
1549 case 'F': /* CPL -- Cursor <n> Up and first col */
1550 DEFAULT(csiescseq.arg[0], 1);
1551 tmoveto(0, term.c.y-csiescseq.arg[0]);
1553 case 'g': /* TBC -- Tabulation clear */
1554 switch (csiescseq.arg[0]) {
1555 case 0: /* clear current tab stop */
1556 term.tabs[term.c.x] = 0;
1558 case 3: /* clear all the tabs */
1559 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1565 case 'G': /* CHA -- Move to <col> */
1567 DEFAULT(csiescseq.arg[0], 1);
1568 tmoveto(csiescseq.arg[0]-1, term.c.y);
1570 case 'H': /* CUP -- Move to <row> <col> */
1572 DEFAULT(csiescseq.arg[0], 1);
1573 DEFAULT(csiescseq.arg[1], 1);
1574 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1576 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1577 DEFAULT(csiescseq.arg[0], 1);
1578 while(csiescseq.arg[0]--)
1581 case 'J': /* ED -- Clear screen */
1583 switch(csiescseq.arg[0]) {
1585 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1586 if(term.c.y < term.row-1)
1587 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1591 tclearregion(0, 0, term.col-1, term.c.y-1);
1592 tclearregion(0, term.c.y, term.c.x, term.c.y);
1595 tclearregion(0, 0, term.col-1, term.row-1);
1601 case 'K': /* EL -- Clear line */
1602 switch(csiescseq.arg[0]) {
1604 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1607 tclearregion(0, term.c.y, term.c.x, term.c.y);
1610 tclearregion(0, term.c.y, term.col-1, term.c.y);
1614 case 'S': /* SU -- Scroll <n> line up */
1615 DEFAULT(csiescseq.arg[0], 1);
1616 tscrollup(term.top, csiescseq.arg[0]);
1618 case 'T': /* SD -- Scroll <n> line down */
1619 DEFAULT(csiescseq.arg[0], 1);
1620 tscrolldown(term.top, csiescseq.arg[0]);
1622 case 'L': /* IL -- Insert <n> blank lines */
1623 DEFAULT(csiescseq.arg[0], 1);
1624 tinsertblankline(csiescseq.arg[0]);
1626 case 'l': /* RM -- Reset Mode */
1627 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1629 case 'M': /* DL -- Delete <n> lines */
1630 DEFAULT(csiescseq.arg[0], 1);
1631 tdeleteline(csiescseq.arg[0]);
1633 case 'X': /* ECH -- Erase <n> char */
1634 DEFAULT(csiescseq.arg[0], 1);
1635 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1637 case 'P': /* DCH -- Delete <n> char */
1638 DEFAULT(csiescseq.arg[0], 1);
1639 tdeletechar(csiescseq.arg[0]);
1641 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1642 DEFAULT(csiescseq.arg[0], 1);
1643 while(csiescseq.arg[0]--)
1646 case 'd': /* VPA -- Move to <row> */
1647 DEFAULT(csiescseq.arg[0], 1);
1648 tmoveto(term.c.x, csiescseq.arg[0]-1);
1650 case 'h': /* SM -- Set terminal mode */
1651 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1653 case 'm': /* SGR -- Terminal attribute (color) */
1654 tsetattr(csiescseq.arg, csiescseq.narg);
1656 case 'r': /* DECSTBM -- Set Scrolling Region */
1657 if(csiescseq.priv) {
1660 DEFAULT(csiescseq.arg[0], 1);
1661 DEFAULT(csiescseq.arg[1], term.row);
1662 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1666 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1667 tcursor(CURSOR_SAVE);
1669 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1670 tcursor(CURSOR_LOAD);
1681 for(i = 0; i < csiescseq.len; i++) {
1682 c = csiescseq.buf[i] & 0xff;
1685 } else if(c == '\n') {
1687 } else if(c == '\r') {
1689 } else if(c == 0x1b) {
1692 printf("(%02x)", c);
1700 memset(&csiescseq, 0, sizeof(csiescseq));
1708 * TODO: make this being useful in case of color palette change.
1714 switch(strescseq.type) {
1715 case ']': /* OSC -- Operating System Command */
1721 * TODO: Handle special chars in string, like umlauts.
1724 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1728 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1730 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1733 fprintf(stderr, "erresc: unknown str ");
1738 case 'k': /* old title set compatibility */
1739 XStoreName(xw.dpy, xw.win, strescseq.buf);
1741 case 'P': /* DSC -- Device Control String */
1742 case '_': /* APC -- Application Program Command */
1743 case '^': /* PM -- Privacy Message */
1745 fprintf(stderr, "erresc: unknown str ");
1755 * TODO: Implement parsing like for CSI when required.
1756 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1766 printf("ESC%c", strescseq.type);
1767 for(i = 0; i < strescseq.len; i++) {
1768 c = strescseq.buf[i] & 0xff;
1771 } else if(c == '\n') {
1773 } else if(c == '\r') {
1775 } else if(c == 0x1b) {
1778 printf("(%02x)", c);
1786 memset(&strescseq, 0, sizeof(strescseq));
1790 tputtab(bool forward) {
1796 for(++x; x < term.col && !term.tabs[x]; ++x)
1801 for(--x; x > 0 && !term.tabs[x]; --x)
1804 tmoveto(x, term.c.y);
1808 tputc(char *c, int len) {
1810 bool control = ascii < '\x20' || ascii == 0177;
1813 if (xwrite(iofd, c, len) < 0) {
1814 fprintf(stderr, "Error writting in %s:%s\n",
1815 opt_io, strerror(errno));
1821 * STR sequences must be checked before of anything
1822 * because it can use some control codes as part of the sequence
1824 if(term.esc & ESC_STR) {
1827 term.esc = ESC_START | ESC_STR_END;
1829 case '\a': /* backwards compatibility to xterm */
1834 strescseq.buf[strescseq.len++] = ascii;
1835 if(strescseq.len+1 >= STR_BUF_SIZ) {
1843 * Actions of control codes must be performed as soon they arrive
1844 * because they can be embedded inside a control sequence, and
1845 * they must not cause conflicts with sequences.
1853 tmoveto(term.c.x-1, term.c.y);
1856 tmoveto(0, term.c.y);
1861 /* go to first col if the mode is set */
1862 tnewline(IS_SET(MODE_CRLF));
1864 case '\a': /* BEL */
1865 if(!(xw.state & WIN_FOCUSED))
1868 case '\033': /* ESC */
1870 term.esc = ESC_START;
1872 case '\016': /* SO */
1873 term.c.attr.mode |= ATTR_GFX;
1875 case '\017': /* SI */
1876 term.c.attr.mode &= ~ATTR_GFX;
1878 case '\032': /* SUB */
1879 case '\030': /* CAN */
1882 case '\005': /* ENQ (IGNORED) */
1883 case '\000': /* NUL (IGNORED) */
1884 case '\021': /* XON (IGNORED) */
1885 case '\023': /* XOFF (IGNORED) */
1886 case 0177: /* DEL (IGNORED) */
1889 } else if(term.esc & ESC_START) {
1890 if(term.esc & ESC_CSI) {
1891 csiescseq.buf[csiescseq.len++] = ascii;
1892 if(BETWEEN(ascii, 0x40, 0x7E)
1893 || csiescseq.len >= ESC_BUF_SIZ) {
1895 csiparse(), csihandle();
1897 } else if(term.esc & ESC_STR_END) {
1901 } else if(term.esc & ESC_ALTCHARSET) {
1903 case '0': /* Line drawing set */
1904 term.c.attr.mode |= ATTR_GFX;
1906 case 'B': /* USASCII */
1907 term.c.attr.mode &= ~ATTR_GFX;
1909 case 'A': /* UK (IGNORED) */
1910 case '<': /* multinational charset (IGNORED) */
1911 case '5': /* Finnish (IGNORED) */
1912 case 'C': /* Finnish (IGNORED) */
1913 case 'K': /* German (IGNORED) */
1916 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1919 } else if(term.esc & ESC_TEST) {
1920 if(ascii == '8') { /* DEC screen alignment test. */
1921 char E[UTF_SIZ] = "E";
1924 for(x = 0; x < term.col; ++x) {
1925 for(y = 0; y < term.row; ++y)
1926 tsetchar(E, &term.c.attr, x, y);
1933 term.esc |= ESC_CSI;
1936 term.esc |= ESC_TEST;
1938 case 'P': /* DCS -- Device Control String */
1939 case '_': /* APC -- Application Program Command */
1940 case '^': /* PM -- Privacy Message */
1941 case ']': /* OSC -- Operating System Command */
1942 case 'k': /* old title set compatibility */
1944 strescseq.type = ascii;
1945 term.esc |= ESC_STR;
1947 case '(': /* set primary charset G0 */
1948 term.esc |= ESC_ALTCHARSET;
1950 case ')': /* set secondary charset G1 (IGNORED) */
1951 case '*': /* set tertiary charset G2 (IGNORED) */
1952 case '+': /* set quaternary charset G3 (IGNORED) */
1955 case 'D': /* IND -- Linefeed */
1956 if(term.c.y == term.bot) {
1957 tscrollup(term.top, 1);
1959 tmoveto(term.c.x, term.c.y+1);
1963 case 'E': /* NEL -- Next line */
1964 tnewline(1); /* always go to first col */
1967 case 'H': /* HTS -- Horizontal tab stop */
1968 term.tabs[term.c.x] = 1;
1971 case 'M': /* RI -- Reverse index */
1972 if(term.c.y == term.top) {
1973 tscrolldown(term.top, 1);
1975 tmoveto(term.c.x, term.c.y-1);
1979 case 'Z': /* DECID -- Identify Terminal */
1980 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1983 case 'c': /* RIS -- Reset to inital state */
1988 case '=': /* DECPAM -- Application keypad */
1989 term.mode |= MODE_APPKEYPAD;
1992 case '>': /* DECPNM -- Normal keypad */
1993 term.mode &= ~MODE_APPKEYPAD;
1996 case '7': /* DECSC -- Save Cursor */
1997 tcursor(CURSOR_SAVE);
2000 case '8': /* DECRC -- Restore Cursor */
2001 tcursor(CURSOR_LOAD);
2004 case '\\': /* ST -- Stop */
2008 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2009 (uchar) ascii, isprint(ascii)? ascii:'.');
2014 * All characters which forms part of a sequence are not
2020 * Display control codes only if we are in graphic mode
2022 if(control && !(term.c.attr.mode & ATTR_GFX))
2024 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2026 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
2027 tnewline(1); /* always go to first col */
2028 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2029 if(term.c.x+1 < term.col)
2030 tmoveto(term.c.x+1, term.c.y);
2032 term.c.state |= CURSOR_WRAPNEXT;
2036 tresize(int col, int row) {
2038 int minrow = MIN(row, term.row);
2039 int mincol = MIN(col, term.col);
2040 int slide = term.c.y - row + 1;
2043 if(col < 1 || row < 1)
2046 /* free unneeded rows */
2049 /* slide screen to keep cursor where we expect it -
2050 * tscrollup would work here, but we can optimize to
2051 * memmove because we're freeing the earlier lines */
2052 for(/* i = 0 */; i < slide; i++) {
2056 memmove(term.line, term.line + slide, row * sizeof(Line));
2057 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2059 for(i += row; i < term.row; i++) {
2064 /* resize to new height */
2065 term.line = xrealloc(term.line, row * sizeof(Line));
2066 term.alt = xrealloc(term.alt, row * sizeof(Line));
2067 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2068 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2070 /* resize each row to new width, zero-pad if needed */
2071 for(i = 0; i < minrow; i++) {
2073 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2074 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2075 for(x = mincol; x < col; x++) {
2076 term.line[i][x].state = 0;
2077 term.alt[i][x].state = 0;
2081 /* allocate any new rows */
2082 for(/* i == minrow */; i < row; i++) {
2084 term.line[i] = xcalloc(col, sizeof(Glyph));
2085 term.alt [i] = xcalloc(col, sizeof(Glyph));
2087 if(col > term.col) {
2088 bp = term.tabs + term.col;
2090 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2091 while(--bp > term.tabs && !*bp)
2093 for(bp += TAB; bp < term.tabs + col; bp += TAB)
2096 /* update terminal size */
2097 term.col = col, term.row = row;
2098 /* make use of the LIMIT in tmoveto */
2099 tmoveto(term.c.x, term.c.y);
2100 /* reset scrolling region */
2101 tsetscroll(0, row-1);
2107 xresize(int col, int row) {
2108 xw.tw = MAX(1, 2*BORDER + col * xw.cw);
2109 xw.th = MAX(1, 2*BORDER + row * xw.ch);
2111 XftDrawChange(xw.xft_draw, xw.buf);
2117 XRenderColor xft_color = { .alpha = 0 };
2119 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2120 for(i = 0; i < LEN(colorname); i++) {
2123 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
2124 die("Could not allocate color '%s'\n", colorname[i]);
2128 /* load colors [16-255] ; same colors as xterm */
2129 for(i = 16, r = 0; r < 6; r++) {
2130 for(g = 0; g < 6; g++) {
2131 for(b = 0; b < 6; b++) {
2132 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
2133 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
2134 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
2135 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
2136 die("Could not allocate color %d\n", i);
2143 for(r = 0; r < 24; r++, i++) {
2144 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
2145 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color,
2147 die("Could not allocate color %d\n", i);
2153 xtermclear(int col1, int row1, int col2, int row2) {
2154 XftDrawRect(xw.xft_draw,
2155 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2156 BORDER + col1 * xw.cw,
2157 BORDER + row1 * xw.ch,
2158 (col2-col1+1) * xw.cw,
2159 (row2-row1+1) * xw.ch);
2163 * Absolute coordinates.
2166 xclear(int x1, int y1, int x2, int y2) {
2167 XftDrawRect(xw.xft_draw,
2168 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2169 x1, y1, x2-x1, y2-y1);
2174 XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
2175 XWMHints wm = {.flags = InputHint, .input = 1};
2176 XSizeHints *sizeh = NULL;
2178 sizeh = XAllocSizeHints();
2179 if(xw.isfixed == False) {
2180 sizeh->flags = PSize | PResizeInc | PBaseSize;
2181 sizeh->height = xw.h;
2182 sizeh->width = xw.w;
2183 sizeh->height_inc = xw.ch;
2184 sizeh->width_inc = xw.cw;
2185 sizeh->base_height = 2*BORDER;
2186 sizeh->base_width = 2*BORDER;
2188 sizeh->flags = PMaxSize | PMinSize;
2189 sizeh->min_width = sizeh->max_width = xw.fw;
2190 sizeh->min_height = sizeh->max_height = xw.fh;
2193 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2198 xinitfont(Font *f, char *fontstr) {
2199 FcPattern *pattern, *match;
2202 pattern = FcNameParse((FcChar8 *)fontstr);
2204 die("st: can't open font %s\n", fontstr);
2206 match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
2207 FcPatternDestroy(pattern);
2209 die("st: can't open font %s\n", fontstr);
2210 if(!(f->xft_set = XftFontOpenPattern(xw.dpy, match))) {
2211 FcPatternDestroy(match);
2212 die("st: can't open font %s.\n", fontstr);
2215 f->ascent = f->xft_set->ascent;
2216 f->descent = f->xft_set->descent;
2218 f->rbearing = f->xft_set->max_advance_width;
2220 f->height = f->xft_set->height;
2221 f->width = f->lbearing + f->rbearing;
2225 initfonts(char *fontstr) {
2228 xinitfont(&dc.font, fontstr);
2229 xw.cw = dc.font.width;
2230 xw.ch = dc.font.height;
2232 fstr = smstrcat(fontstr, ":weight=bold", NULL);
2233 xinitfont(&dc.bfont, fstr);
2236 fstr = smstrcat(fontstr, ":slant=italic,oblique", NULL);
2237 xinitfont(&dc.ifont, fstr);
2240 fstr = smstrcat(fontstr, ":weight=bold:slant=italic,oblique", NULL);
2241 xinitfont(&dc.ibfont, fstr);
2247 XSetWindowAttributes attrs;
2250 int sw, sh, major, minor;
2252 if(!(xw.dpy = XOpenDisplay(NULL)))
2253 die("Can't open display\n");
2254 xw.scr = XDefaultScreen(xw.dpy);
2255 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2258 initfonts((opt_font != NULL)? opt_font : FONT);
2261 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2264 /* adjust fixed window geometry */
2266 sw = DisplayWidth(xw.dpy, xw.scr);
2267 sh = DisplayHeight(xw.dpy, xw.scr);
2269 xw.fx = sw + xw.fx - xw.fw - 1;
2271 xw.fy = sh + xw.fy - xw.fh - 1;
2276 /* window - default size */
2277 xw.h = 2*BORDER + term.row * xw.ch;
2278 xw.w = 2*BORDER + term.col * xw.cw;
2283 attrs.background_pixel = dc.xft_col[DefaultBG].pixel;
2284 attrs.border_pixel = dc.xft_col[DefaultBG].pixel;
2285 attrs.bit_gravity = NorthWestGravity;
2286 attrs.event_mask = FocusChangeMask | KeyPressMask
2287 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2288 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2289 attrs.colormap = xw.cmap;
2291 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2292 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2293 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2295 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2299 /* double buffering */
2300 if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2301 die("Xdbe extension is not present\n");
2302 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2304 /* Xft rendering context */
2305 xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2308 xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2309 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2310 | XIMStatusNothing, XNClientWindow, xw.win,
2311 XNFocusWindow, xw.win, NULL);
2313 dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2315 /* white cursor, black outline */
2316 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2317 XDefineCursor(xw.dpy, xw.win, cursor);
2318 XRecolorCursor(xw.dpy, cursor,
2319 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2320 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2322 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2323 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2324 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2327 XMapWindow(xw.dpy, xw.win);
2333 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2334 int winx = BORDER + x * xw.cw, winy = BORDER + y * xw.ch,
2335 width = charlen * xw.cw;
2336 Font *font = &dc.font;
2338 XftColor *fg = &dc.xft_col[base.fg], *bg = &dc.xft_col[base.bg],
2339 *temp, revfg, revbg;
2340 XRenderColor colfg, colbg;
2342 if(base.mode & ATTR_REVERSE)
2343 temp = fg, fg = bg, bg = temp;
2345 if(base.mode & ATTR_BOLD) {
2346 if(BETWEEN(base.fg, 0, 7)) {
2347 /* basic system colors */
2348 fg = &dc.xft_col[base.fg + 8];
2349 } else if(BETWEEN(base.fg, 16, 195)) {
2351 fg = &dc.xft_col[base.fg + 36];
2352 } else if(BETWEEN(base.fg, 232, 251)) {
2354 fg = &dc.xft_col[base.fg + 4];
2357 * Those ranges will not be brightened:
2358 * 8 - 15 – bright system colors
2359 * 196 - 231 – highest 256 color cube
2360 * 252 - 255 – brightest colors in greyscale
2365 if(base.mode & ATTR_ITALIC)
2367 if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
2370 if(IS_SET(MODE_REVERSE)) {
2371 if(fg == &dc.xft_col[DefaultFG]) {
2372 fg = &dc.xft_col[DefaultBG];
2374 colfg.red = ~fg->color.red;
2375 colfg.green = ~fg->color.green;
2376 colfg.blue = ~fg->color.blue;
2377 colfg.alpha = fg->color.alpha;
2378 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2382 if(bg == &dc.xft_col[DefaultBG]) {
2383 bg = &dc.xft_col[DefaultFG];
2385 colbg.red = ~bg->color.red;
2386 colbg.green = ~bg->color.green;
2387 colbg.blue = ~bg->color.blue;
2388 colbg.alpha = bg->color.alpha;
2389 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2394 XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen,
2396 width = extents.xOff;
2398 /* Intelligent cleaning up of the borders. */
2400 xclear(0, (y == 0)? 0 : winy, BORDER,
2401 winy + xw.ch + (y == term.row-1)? xw.h : 0);
2403 if(x + charlen >= term.col-1) {
2404 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2405 (y == term.row-1)? xw.h : (winy + xw.ch));
2408 xclear(winx, 0, winx + width, BORDER);
2410 xclear(winx, winy + xw.ch, winx + width, xw.h);
2412 XftDrawRect(xw.xft_draw, bg, winx, winy, width, xw.ch);
2413 XftDrawStringUtf8(xw.xft_draw, fg, font->xft_set, winx,
2414 winy + font->ascent, (FcChar8 *)s, bytelen);
2416 if(base.mode & ATTR_UNDERLINE) {
2417 XftDrawRect(xw.xft_draw, fg, winx, winy + font->ascent + 1,
2424 static int oldx = 0, oldy = 0;
2426 Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
2428 LIMIT(oldx, 0, term.col-1);
2429 LIMIT(oldy, 0, term.row-1);
2431 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2432 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2434 /* remove the old cursor */
2435 if(term.line[oldy][oldx].state & GLYPH_SET) {
2436 sl = utf8size(term.line[oldy][oldx].c);
2437 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2440 xtermclear(oldx, oldy, oldx, oldy);
2443 /* draw the new one */
2444 if(!(term.c.state & CURSOR_HIDE)) {
2445 if(!(xw.state & WIN_FOCUSED))
2448 if(IS_SET(MODE_REVERSE))
2449 g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
2452 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2453 oldx = term.c.x, oldy = term.c.y;
2459 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2464 struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2468 XSync(xw.dpy, False); /* necessary for a good tput flash */
2469 nanosleep(&tv, NULL);
2474 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2476 drawregion(0, 0, term.col, term.row);
2477 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2481 drawregion(int x1, int y1, int x2, int y2) {
2482 int ic, ib, x, y, ox, sl;
2484 char buf[DRAW_BUF_SIZ];
2485 bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
2487 if((sel.alt && !alt) || (!sel.alt && alt))
2489 if(!(xw.state & WIN_VISIBLE))
2492 for(y = y1; y < y2; y++) {
2496 xtermclear(0, y, term.col, y);
2498 base = term.line[y][0];
2500 for(x = x1; x < x2; x++) {
2501 new = term.line[y][x];
2502 if(ena_sel && *(new.c) && selected(x, y))
2503 new.mode ^= ATTR_REVERSE;
2504 if(ib > 0 && (!(new.state & GLYPH_SET)
2505 || ATTRCMP(base, new)
2506 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2507 xdraws(buf, base, ox, y, ic, ib);
2510 if(new.state & GLYPH_SET) {
2515 sl = utf8size(new.c);
2516 memcpy(buf+ib, new.c, sl);
2522 xdraws(buf, base, ox, y, ic, ib);
2528 expose(XEvent *ev) {
2529 XExposeEvent *e = &ev->xexpose;
2531 if(xw.state & WIN_REDRAW) {
2533 xw.state &= ~WIN_REDRAW;
2538 visibility(XEvent *ev) {
2539 XVisibilityEvent *e = &ev->xvisibility;
2541 if(e->state == VisibilityFullyObscured) {
2542 xw.state &= ~WIN_VISIBLE;
2543 } else if(!(xw.state & WIN_VISIBLE)) {
2544 /* need a full redraw for next Expose, not just a buf copy */
2545 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2551 xw.state &= ~WIN_VISIBLE;
2555 xseturgency(int add) {
2556 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2558 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2559 XSetWMHints(xw.dpy, xw.win, h);
2565 if(ev->type == FocusIn) {
2566 xw.state |= WIN_FOCUSED;
2569 xw.state &= ~WIN_FOCUSED;
2574 kmap(KeySym k, uint state) {
2579 for(i = 0; i < LEN(key); i++) {
2582 if(key[i].k == k && ((state & mask) == mask
2583 || (mask == XK_NO_MOD && !state))) {
2584 return (char*)key[i].s;
2591 kpress(XEvent *ev) {
2592 XKeyEvent *e = &ev->xkey;
2601 if (IS_SET(MODE_KBDLOCK))
2604 meta = e->state & Mod1Mask;
2605 shift = e->state & ShiftMask;
2606 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2608 /* 1. custom keys from config.h */
2609 if((customkey = kmap(ksym, e->state))) {
2610 ttywrite(customkey, strlen(customkey));
2611 /* 2. hardcoded (overrides X lookup) */
2618 /* XXX: shift up/down doesn't work */
2619 sprintf(buf, "\033%c%c",
2620 IS_SET(MODE_APPKEYPAD) ? 'O' : '[',
2621 (shift ? "dacb":"DACB")[ksym - XK_Left]);
2629 if(IS_SET(MODE_CRLF)) {
2630 ttywrite("\r\n", 2);
2638 if(meta && len == 1)
2639 ttywrite("\033", 1);
2648 cmessage(XEvent *e) {
2650 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2651 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2652 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2653 xw.state |= WIN_FOCUSED;
2655 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2656 xw.state &= ~WIN_FOCUSED;
2658 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
2659 /* Send SIGHUP to shell */
2669 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2672 xw.w = e->xconfigure.width;
2673 xw.h = e->xconfigure.height;
2674 col = (xw.w - 2*BORDER) / xw.cw;
2675 row = (xw.h - 2*BORDER) / xw.ch;
2676 if(col == term.col && row == term.row)
2688 int xfd = XConnectionNumber(xw.dpy), i;
2689 struct timeval drawtimeout, *tv = NULL;
2693 FD_SET(cmdfd, &rfd);
2695 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2698 die("select failed: %s\n", SERRNO);
2702 * Stop after a certain number of reads so the user does not
2703 * feel like the system is stuttering.
2705 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2709 * Just wait a bit so it isn't disturbing the
2710 * user and the system is able to write something.
2712 drawtimeout.tv_sec = 0;
2713 drawtimeout.tv_usec = 5;
2720 while(XPending(xw.dpy)) {
2721 XNextEvent(xw.dpy, &ev);
2722 if(XFilterEvent(&ev, xw.win))
2724 if(handler[ev.type])
2725 (handler[ev.type])(&ev);
2734 main(int argc, char *argv[]) {
2735 int i, bitm, xr, yr;
2738 xw.fw = xw.fh = xw.fx = xw.fy = 0;
2741 for(i = 1; i < argc; i++) {
2742 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2745 opt_class = argv[i];
2748 /* eat every remaining arguments */
2760 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2765 if(bitm & WidthValue)
2767 if(bitm & HeightValue)
2769 if(bitm & XNegative && xw.fx == 0)
2771 if(bitm & XNegative && xw.fy == 0)
2774 if(xw.fh != 0 && xw.fw != 0)
2783 opt_title = argv[i];
2790 opt_embed = argv[i];
2796 setlocale(LC_CTYPE, "");