1 /* See LICENSE for licence details. */
2 #define _XOPEN_SOURCE 600
15 #include <sys/ioctl.h>
16 #include <sys/select.h>
19 #include <sys/types.h>
23 #include <X11/Xatom.h>
25 #include <X11/Xutil.h>
26 #include <X11/cursorfont.h>
27 #include <X11/keysym.h>
28 #include <X11/extensions/Xdbe.h>
29 #include <X11/Xft/Xft.h>
30 #include <fontconfig/fontconfig.h>
36 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
38 #elif defined(__FreeBSD__) || defined(__DragonFly__)
43 "st " VERSION " (c) 2010-2012 st engineers\n" \
44 "usage: st [-v] [-c class] [-f font] [-g geometry] [-o file]" \
45 " [-t title] [-w windowid] [-e command ...]\n"
48 #define XEMBED_FOCUS_IN 4
49 #define XEMBED_FOCUS_OUT 5
52 #define ESC_BUF_SIZ 256
53 #define ESC_ARG_SIZ 16
54 #define STR_BUF_SIZ 256
55 #define STR_ARG_SIZ 16
56 #define DRAW_BUF_SIZ 20*1024
58 #define XK_NO_MOD UINT_MAX
61 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
64 #define CLEANMASK(mask) (mask & (ShiftMask|ControlMask|Mod1Mask|Mod2Mask|Mod3Mask|Mod4Mask|Mod5Mask))
65 #define SERRNO strerror(errno)
66 #define MIN(a, b) ((a) < (b) ? (a) : (b))
67 #define MAX(a, b) ((a) < (b) ? (b) : (a))
68 #define LEN(a) (sizeof(a) / sizeof(a[0]))
69 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
70 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
71 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
72 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
73 #define IS_SET(flag) (term.mode & (flag))
74 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
75 #define X2COL(x) (((x) - borderpx)/xw.cw)
76 #define Y2ROW(y) (((y) - borderpx)/xw.ch)
78 #define VT102ID "\033[?6c"
80 enum glyph_attribute {
90 enum cursor_movement {
117 MODE_MOUSEMOTION = 64,
126 ESC_STR = 4, /* DSC, OSC, PM, APC */
128 ESC_STR_END = 16, /* a final string was encountered */
129 ESC_TEST = 32, /* Enter in test mode */
140 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
142 typedef unsigned char uchar;
143 typedef unsigned int uint;
144 typedef unsigned long ulong;
145 typedef unsigned short ushort;
148 char c[UTF_SIZ]; /* character code */
149 uchar mode; /* attribute flags */
150 ushort fg; /* foreground */
151 ushort bg; /* background */
152 uchar state; /* state flags */
158 Glyph attr; /* current char attributes */
164 /* CSI Escape sequence structs */
165 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
167 char buf[ESC_BUF_SIZ]; /* raw string */
168 int len; /* raw string length */
170 int arg[ESC_ARG_SIZ];
171 int narg; /* nb of args */
175 /* STR Escape sequence structs */
176 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
178 char type; /* ESC type ... */
179 char buf[STR_BUF_SIZ]; /* raw string */
180 int len; /* raw string length */
181 char *args[STR_ARG_SIZ];
182 int narg; /* nb of args */
185 /* Internal representation of the screen */
187 int row; /* nb row */
188 int col; /* nb col */
189 Line *line; /* screen */
190 Line *alt; /* alternate screen */
191 bool *dirty; /* dirtyness of lines */
192 TCursor c; /* cursor */
193 int top; /* top scroll limit */
194 int bot; /* bottom scroll limit */
195 int mode; /* terminal mode flags */
196 int esc; /* escape state flags */
200 /* Purely graphic info */
206 Atom xembed, wmdeletewin;
212 bool isfixed; /* is fixed geometry? */
213 int fx, fy, fw, fh; /* fixed geometry */
214 int tw, th; /* tty width and height */
215 int w; /* window width */
216 int h; /* window height */
217 int ch; /* char height */
218 int cw; /* char width */
219 char state; /* focus, redraw, visible */
228 /* TODO: use better name for vars... */
239 struct timeval tclick1;
240 struct timeval tclick2;
253 void (*func)(const Arg *);
257 /* function definitions used in config.h */
258 static void xzoom(const Arg *);
260 /* Config.h for applying patches and the configuration. */
274 /* Drawing Context */
276 XftColor xft_col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
278 Font font, bfont, ifont, ibfont;
281 static void die(const char *, ...);
282 static void draw(void);
283 static void redraw(void);
284 static void drawregion(int, int, int, int);
285 static void execsh(void);
286 static void sigchld(int);
287 static void run(void);
289 static void csidump(void);
290 static void csihandle(void);
291 static void csiparse(void);
292 static void csireset(void);
293 static void strdump(void);
294 static void strhandle(void);
295 static void strparse(void);
296 static void strreset(void);
298 static void tclearregion(int, int, int, int);
299 static void tcursor(int);
300 static void tdeletechar(int);
301 static void tdeleteline(int);
302 static void tinsertblank(int);
303 static void tinsertblankline(int);
304 static void tmoveto(int, int);
305 static void tnew(int, int);
306 static void tnewline(int);
307 static void tputtab(bool);
308 static void tputc(char *, int);
309 static void treset(void);
310 static int tresize(int, int);
311 static void tscrollup(int, int);
312 static void tscrolldown(int, int);
313 static void tsetattr(int*, int);
314 static void tsetchar(char *, Glyph *, int, int);
315 static void tsetscroll(int, int);
316 static void tswapscreen(void);
317 static void tsetdirt(int, int);
318 static void tsetmode(bool, bool, int *, int);
319 static void tfulldirt(void);
321 static void ttynew(void);
322 static void ttyread(void);
323 static void ttyresize(void);
324 static void ttywrite(const char *, size_t);
326 static void xdraws(char *, Glyph, int, int, int, int);
327 static void xhints(void);
328 static void xclear(int, int, int, int);
329 static void xdrawcursor(void);
330 static void xinit(void);
331 static void xloadcols(void);
332 static void xresettitle(void);
333 static void xseturgency(int);
334 static void xsetsel(char*);
335 static void xtermclear(int, int, int, int);
336 static void xresize(int, int);
338 static void expose(XEvent *);
339 static void visibility(XEvent *);
340 static void unmap(XEvent *);
341 static char *kmap(KeySym, uint);
342 static void kpress(XEvent *);
343 static void cmessage(XEvent *);
344 static void cresize(int width, int height);
345 static void resize(XEvent *);
346 static void focus(XEvent *);
347 static void brelease(XEvent *);
348 static void bpress(XEvent *);
349 static void bmotion(XEvent *);
350 static void selnotify(XEvent *);
351 static void selclear(XEvent *);
352 static void selrequest(XEvent *);
354 static void selinit(void);
355 static inline bool selected(int, int);
356 static void selcopy(void);
357 static void selpaste(void);
358 static void selscroll(int, int);
360 static int utf8decode(char *, long *);
361 static int utf8encode(long *, char *);
362 static int utf8size(char *);
363 static int isfullutf8(char *, int);
365 static ssize_t xwrite(int, char *, size_t);
366 static void *xmalloc(size_t);
367 static void *xrealloc(void *, size_t);
368 static void *xcalloc(size_t nmemb, size_t size);
370 static void (*handler[LASTEvent])(XEvent *) = {
372 [ClientMessage] = cmessage,
373 [ConfigureNotify] = resize,
374 [VisibilityNotify] = visibility,
375 [UnmapNotify] = unmap,
379 [MotionNotify] = bmotion,
380 [ButtonPress] = bpress,
381 [ButtonRelease] = brelease,
382 [SelectionClear] = selclear,
383 [SelectionNotify] = selnotify,
384 [SelectionRequest] = selrequest,
391 static CSIEscape csiescseq;
392 static STREscape strescseq;
395 static Selection sel;
396 static int iofd = -1;
397 static char **opt_cmd = NULL;
398 static char *opt_io = NULL;
399 static char *opt_title = NULL;
400 static char *opt_embed = NULL;
401 static char *opt_class = NULL;
402 static char *opt_font = NULL;
404 static char *usedfont = NULL;
405 static int usedfontsize = 0;
408 xwrite(int fd, char *s, size_t len) {
412 ssize_t r = write(fd, s, len);
422 xmalloc(size_t len) {
423 void *p = malloc(len);
426 die("Out of memory\n");
432 xrealloc(void *p, size_t len) {
433 if((p = realloc(p, len)) == NULL)
434 die("Out of memory\n");
440 xcalloc(size_t nmemb, size_t size) {
441 void *p = calloc(nmemb, size);
444 die("Out of memory\n");
450 utf8decode(char *s, long *u) {
456 if(~c & B7) { /* 0xxxxxxx */
459 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
460 *u = c&(B4|B3|B2|B1|B0);
462 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
463 *u = c&(B3|B2|B1|B0);
465 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
472 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
474 if((c & (B7|B6)) != B7) /* 10xxxxxx */
477 *u |= c & (B5|B4|B3|B2|B1|B0);
480 if((n == 1 && *u < 0x80) ||
481 (n == 2 && *u < 0x800) ||
482 (n == 3 && *u < 0x10000) ||
483 (*u >= 0xD800 && *u <= 0xDFFF)) {
495 utf8encode(long *u, char *s) {
503 *sp = uc; /* 0xxxxxxx */
505 } else if(*u < 0x800) {
506 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
508 } else if(uc < 0x10000) {
509 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
511 } else if(uc <= 0x10FFFF) {
512 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
518 for(i=n,++sp; i>0; --i,++sp)
519 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
531 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
532 UTF-8 otherwise return 0 */
534 isfullutf8(char *s, int b) {
542 } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
544 } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
546 ((b == 2) && (*c2&(B7|B6)) == B7))) {
548 } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
550 ((b == 2) && (*c2&(B7|B6)) == B7) ||
551 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
564 } else if((c&(B7|B6|B5)) == (B7|B6)) {
566 } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
575 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
576 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
580 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
581 if(sel.xtarget == None)
582 sel.xtarget = XA_STRING;
586 selected(int x, int y) {
589 if(sel.ey == y && sel.by == y) {
590 bx = MIN(sel.bx, sel.ex);
591 ex = MAX(sel.bx, sel.ex);
592 return BETWEEN(x, bx, ex);
595 return ((sel.b.y < y && y < sel.e.y)
596 || (y == sel.e.y && x <= sel.e.x))
597 || (y == sel.b.y && x >= sel.b.x
598 && (x <= sel.e.x || sel.b.y != sel.e.y));
602 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
604 *b = e->xbutton.button;
606 *x = X2COL(e->xbutton.x);
607 *y = Y2ROW(e->xbutton.y);
608 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
609 sel.b.y = MIN(sel.by, sel.ey);
610 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
611 sel.e.y = MAX(sel.by, sel.ey);
615 mousereport(XEvent *e) {
616 int x = X2COL(e->xbutton.x);
617 int y = Y2ROW(e->xbutton.y);
618 int button = e->xbutton.button;
619 int state = e->xbutton.state;
620 char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
621 static int ob, ox, oy;
624 if(e->xbutton.type == MotionNotify) {
625 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
629 } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
635 if(e->xbutton.type == ButtonPress) {
641 buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
642 + (state & Mod4Mask ? 8 : 0)
643 + (state & ControlMask ? 16 : 0);
645 ttywrite(buf, sizeof(buf));
650 if(IS_SET(MODE_MOUSE)) {
652 } else if(e->xbutton.button == Button1) {
655 tsetdirt(sel.b.y, sel.e.y);
659 sel.ex = sel.bx = X2COL(e->xbutton.x);
660 sel.ey = sel.by = Y2ROW(e->xbutton.y);
667 int x, y, bufsize, is_selected = 0, size;
673 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
674 ptr = str = xmalloc(bufsize);
676 /* append every set & selected glyph to the selection */
677 for(y = 0; y < term.row; y++) {
678 gp = &term.line[y][0];
679 last = gp + term.col;
681 while(--last >= gp && !(last->state & GLYPH_SET))
684 for(x = 0; gp <= last; x++, ++gp) {
685 if(!(is_selected = selected(x, y)))
688 p = (gp->state & GLYPH_SET) ? gp->c : " ";
690 memcpy(ptr, p, size);
693 /* \n at the end of every selected line except for the last one */
694 if(is_selected && y < sel.e.y)
699 sel.alt = IS_SET(MODE_ALTSCREEN);
704 selnotify(XEvent *e) {
705 ulong nitems, ofs, rem;
712 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
713 False, AnyPropertyType, &type, &format,
714 &nitems, &rem, &data)) {
715 fprintf(stderr, "Clipboard allocation failed\n");
718 ttywrite((const char *) data, nitems * format / 8);
720 /* number of 32-bit chunks returned */
721 ofs += nitems * format / 32;
727 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
728 xw.win, CurrentTime);
731 void selclear(XEvent *e) {
735 tsetdirt(sel.b.y, sel.e.y);
739 selrequest(XEvent *e) {
740 XSelectionRequestEvent *xsre;
742 Atom xa_targets, string;
744 xsre = (XSelectionRequestEvent *) e;
745 xev.type = SelectionNotify;
746 xev.requestor = xsre->requestor;
747 xev.selection = xsre->selection;
748 xev.target = xsre->target;
749 xev.time = xsre->time;
753 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
754 if(xsre->target == xa_targets) {
755 /* respond with the supported type */
756 string = sel.xtarget;
757 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
758 XA_ATOM, 32, PropModeReplace,
759 (uchar *) &string, 1);
760 xev.property = xsre->property;
761 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
762 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
763 xsre->target, 8, PropModeReplace,
764 (uchar *) sel.clip, strlen(sel.clip));
765 xev.property = xsre->property;
768 /* all done, send a notification to the listener */
769 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
770 fprintf(stderr, "Error sending SelectionNotify event\n");
775 /* register the selection for both the clipboard and the primary */
781 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
783 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
784 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
788 brelease(XEvent *e) {
791 if(IS_SET(MODE_MOUSE)) {
796 if(e->xbutton.button == Button2) {
798 } else if(e->xbutton.button == Button1) {
800 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
801 term.dirty[sel.ey] = 1;
802 if(sel.bx == sel.ex && sel.by == sel.ey) {
804 gettimeofday(&now, NULL);
806 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
807 /* triple click on the line */
808 sel.b.x = sel.bx = 0;
809 sel.e.x = sel.ex = term.col;
810 sel.b.y = sel.e.y = sel.ey;
812 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
813 /* double click to select word */
815 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
816 term.line[sel.ey][sel.bx-1].c[0] != ' ') {
820 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
821 term.line[sel.ey][sel.ex+1].c[0] != ' ') {
825 sel.b.y = sel.e.y = sel.ey;
833 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
834 gettimeofday(&sel.tclick1, NULL);
839 int starty, endy, oldey, oldex;
841 if(IS_SET(MODE_MOUSE)) {
849 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
851 if(oldey != sel.ey || oldex != sel.ex) {
852 starty = MIN(oldey, sel.ey);
853 endy = MAX(oldey, sel.ey);
854 tsetdirt(starty, endy);
860 die(const char *errstr, ...) {
863 va_start(ap, errstr);
864 vfprintf(stderr, errstr, ap);
872 char *envshell = getenv("SHELL");
873 const struct passwd *pass = getpwuid(getuid());
874 char buf[sizeof(long) * 8 + 1];
881 setenv("LOGNAME", pass->pw_name, 1);
882 setenv("USER", pass->pw_name, 1);
883 setenv("SHELL", pass->pw_shell, 0);
884 setenv("HOME", pass->pw_dir, 0);
887 snprintf(buf, sizeof(buf), "%lu", xw.win);
888 setenv("WINDOWID", buf, 1);
890 signal(SIGCHLD, SIG_DFL);
891 signal(SIGHUP, SIG_DFL);
892 signal(SIGINT, SIG_DFL);
893 signal(SIGQUIT, SIG_DFL);
894 signal(SIGTERM, SIG_DFL);
895 signal(SIGALRM, SIG_DFL);
897 DEFAULT(envshell, shell);
898 setenv("TERM", termname, 1);
899 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
900 execvp(args[0], args);
908 if(waitpid(pid, &stat, 0) < 0)
909 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
911 if(WIFEXITED(stat)) {
912 exit(WEXITSTATUS(stat));
921 struct winsize w = {term.row, term.col, 0, 0};
923 /* seems to work fine on linux, openbsd and freebsd */
924 if(openpty(&m, &s, NULL, NULL, &w) < 0)
925 die("openpty failed: %s\n", SERRNO);
927 switch(pid = fork()) {
929 die("fork failed\n");
932 setsid(); /* create a new process group */
933 dup2(s, STDIN_FILENO);
934 dup2(s, STDOUT_FILENO);
935 dup2(s, STDERR_FILENO);
936 if(ioctl(s, TIOCSCTTY, NULL) < 0)
937 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
945 signal(SIGCHLD, sigchld);
947 iofd = (!strcmp(opt_io, "-")) ?
949 open(opt_io, O_WRONLY | O_CREAT, 0666);
951 fprintf(stderr, "Error opening %s:%s\n",
952 opt_io, strerror(errno));
962 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
964 fprintf(stderr, "\n");
969 static char buf[BUFSIZ];
970 static int buflen = 0;
973 int charsize; /* size of utf8 char in bytes */
977 /* append read bytes to unprocessed bytes */
978 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
979 die("Couldn't read from shell: %s\n", SERRNO);
981 /* process every complete utf8 char */
984 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
985 charsize = utf8decode(ptr, &utf8c);
986 utf8encode(&utf8c, s);
992 /* keep any uncomplete utf8 char for the next call */
993 memmove(buf, ptr, buflen);
997 ttywrite(const char *s, size_t n) {
998 if(write(cmdfd, s, n) == -1)
999 die("write error on tty: %s\n", SERRNO);
1006 w.ws_row = term.row;
1007 w.ws_col = term.col;
1008 w.ws_xpixel = xw.tw;
1009 w.ws_ypixel = xw.th;
1010 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1011 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1015 tsetdirt(int top, int bot) {
1018 LIMIT(top, 0, term.row-1);
1019 LIMIT(bot, 0, term.row-1);
1021 for(i = top; i <= bot; i++)
1027 tsetdirt(0, term.row-1);
1034 if(mode == CURSOR_SAVE) {
1036 } else if(mode == CURSOR_LOAD) {
1046 term.c = (TCursor){{
1050 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1052 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1053 for(i = tabspaces; i < term.col; i += tabspaces)
1056 term.bot = term.row - 1;
1057 term.mode = MODE_WRAP;
1059 tclearregion(0, 0, term.col-1, term.row-1);
1063 tnew(int col, int row) {
1064 /* set screen size */
1067 term.line = xmalloc(term.row * sizeof(Line));
1068 term.alt = xmalloc(term.row * sizeof(Line));
1069 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1070 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1072 for(row = 0; row < term.row; row++) {
1073 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1074 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1075 term.dirty[row] = 0;
1077 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1084 Line *tmp = term.line;
1086 term.line = term.alt;
1088 term.mode ^= MODE_ALTSCREEN;
1093 tscrolldown(int orig, int n) {
1097 LIMIT(n, 0, term.bot-orig+1);
1099 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1101 for(i = term.bot; i >= orig+n; i--) {
1102 temp = term.line[i];
1103 term.line[i] = term.line[i-n];
1104 term.line[i-n] = temp;
1107 term.dirty[i-n] = 1;
1114 tscrollup(int orig, int n) {
1117 LIMIT(n, 0, term.bot-orig+1);
1119 tclearregion(0, orig, term.col-1, orig+n-1);
1121 for(i = orig; i <= term.bot-n; i++) {
1122 temp = term.line[i];
1123 term.line[i] = term.line[i+n];
1124 term.line[i+n] = temp;
1127 term.dirty[i+n] = 1;
1130 selscroll(orig, -n);
1134 selscroll(int orig, int n) {
1138 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1139 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1143 if(sel.by < term.top) {
1147 if(sel.ey > term.bot) {
1151 sel.b.y = sel.by, sel.b.x = sel.bx;
1152 sel.e.y = sel.ey, sel.e.x = sel.ex;
1157 tnewline(int first_col) {
1161 tscrollup(term.top, 1);
1165 tmoveto(first_col ? 0 : term.c.x, y);
1170 /* int noarg = 1; */
1171 char *p = csiescseq.buf;
1175 csiescseq.priv = 1, p++;
1177 while(p < csiescseq.buf+csiescseq.len) {
1178 while(isdigit(*p)) {
1179 csiescseq.arg[csiescseq.narg] *= 10;
1180 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1182 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1183 csiescseq.narg++, p++;
1185 csiescseq.mode = *p;
1194 tmoveto(int x, int y) {
1195 LIMIT(x, 0, term.col-1);
1196 LIMIT(y, 0, term.row-1);
1197 term.c.state &= ~CURSOR_WRAPNEXT;
1203 tsetchar(char *c, Glyph *attr, int x, int y) {
1204 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1205 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1206 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1207 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1208 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1209 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1210 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1211 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1212 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1216 * The table is proudly stolen from rxvt.
1218 if(attr->mode & ATTR_GFX) {
1219 if(c[0] >= 0x41 && c[0] <= 0x7e
1220 && vt100_0[c[0] - 0x41]) {
1221 c = vt100_0[c[0] - 0x41];
1226 term.line[y][x] = *attr;
1227 memcpy(term.line[y][x].c, c, UTF_SIZ);
1228 term.line[y][x].state |= GLYPH_SET;
1232 tclearregion(int x1, int y1, int x2, int y2) {
1236 temp = x1, x1 = x2, x2 = temp;
1238 temp = y1, y1 = y2, y2 = temp;
1240 LIMIT(x1, 0, term.col-1);
1241 LIMIT(x2, 0, term.col-1);
1242 LIMIT(y1, 0, term.row-1);
1243 LIMIT(y2, 0, term.row-1);
1245 for(y = y1; y <= y2; y++) {
1247 for(x = x1; x <= x2; x++)
1248 term.line[y][x].state = 0;
1253 tdeletechar(int n) {
1254 int src = term.c.x + n;
1256 int size = term.col - src;
1258 term.dirty[term.c.y] = 1;
1260 if(src >= 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(term.col-n, term.c.y, term.col-1, term.c.y);
1271 tinsertblank(int n) {
1274 int size = term.col - dst;
1276 term.dirty[term.c.y] = 1;
1278 if(dst >= term.col) {
1279 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1283 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1284 size * sizeof(Glyph));
1285 tclearregion(src, term.c.y, dst - 1, term.c.y);
1289 tinsertblankline(int n) {
1290 if(term.c.y < term.top || term.c.y > term.bot)
1293 tscrolldown(term.c.y, n);
1297 tdeleteline(int n) {
1298 if(term.c.y < term.top || term.c.y > term.bot)
1301 tscrollup(term.c.y, n);
1305 tsetattr(int *attr, int l) {
1308 for(i = 0; i < l; i++) {
1311 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1312 | ATTR_ITALIC | ATTR_BLINK);
1313 term.c.attr.fg = defaultfg;
1314 term.c.attr.bg = defaultbg;
1317 term.c.attr.mode |= ATTR_BOLD;
1319 case 3: /* enter standout (highlight) */
1320 term.c.attr.mode |= ATTR_ITALIC;
1323 term.c.attr.mode |= ATTR_UNDERLINE;
1326 term.c.attr.mode |= ATTR_BLINK;
1329 term.c.attr.mode |= ATTR_REVERSE;
1333 term.c.attr.mode &= ~ATTR_BOLD;
1335 case 23: /* leave standout (highlight) mode */
1336 term.c.attr.mode &= ~ATTR_ITALIC;
1339 term.c.attr.mode &= ~ATTR_UNDERLINE;
1342 term.c.attr.mode &= ~ATTR_BLINK;
1345 term.c.attr.mode &= ~ATTR_REVERSE;
1348 if(i + 2 < l && attr[i + 1] == 5) {
1350 if(BETWEEN(attr[i], 0, 255)) {
1351 term.c.attr.fg = attr[i];
1354 "erresc: bad fgcolor %d\n",
1359 "erresc(38): gfx attr %d unknown\n",
1364 term.c.attr.fg = defaultfg;
1367 if(i + 2 < l && attr[i + 1] == 5) {
1369 if(BETWEEN(attr[i], 0, 255)) {
1370 term.c.attr.bg = attr[i];
1373 "erresc: bad bgcolor %d\n",
1378 "erresc(48): gfx attr %d unknown\n",
1383 term.c.attr.bg = defaultbg;
1386 if(BETWEEN(attr[i], 30, 37)) {
1387 term.c.attr.fg = attr[i] - 30;
1388 } else if(BETWEEN(attr[i], 40, 47)) {
1389 term.c.attr.bg = attr[i] - 40;
1390 } else if(BETWEEN(attr[i], 90, 97)) {
1391 term.c.attr.fg = attr[i] - 90 + 8;
1392 } else if(BETWEEN(attr[i], 100, 107)) {
1393 term.c.attr.bg = attr[i] - 100 + 8;
1396 "erresc(default): gfx attr %d unknown\n",
1397 attr[i]), csidump();
1405 tsetscroll(int t, int b) {
1408 LIMIT(t, 0, term.row-1);
1409 LIMIT(b, 0, term.row-1);
1419 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1422 tsetmode(bool priv, bool set, int *args, int narg) {
1425 for(lim = args + narg; args < lim; ++args) {
1429 case 1: /* DECCKM -- Cursor key */
1430 MODBIT(term.mode, set, MODE_APPKEYPAD);
1432 case 5: /* DECSCNM -- Reverse video */
1434 MODBIT(term.mode, set, MODE_REVERSE);
1435 if(mode != term.mode)
1438 case 6: /* XXX: DECOM -- Origin */
1440 case 7: /* DECAWM -- Auto wrap */
1441 MODBIT(term.mode, set, MODE_WRAP);
1443 case 8: /* XXX: DECARM -- Auto repeat */
1445 case 0: /* Error (IGNORED) */
1446 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1449 MODBIT(term.c.state, !set, CURSOR_HIDE);
1451 case 1000: /* 1000,1002: enable xterm mouse report */
1452 MODBIT(term.mode, set, MODE_MOUSEBTN);
1455 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1457 case 1049: /* = 1047 and 1048 */
1460 if(IS_SET(MODE_ALTSCREEN))
1461 tclearregion(0, 0, term.col-1, term.row-1);
1462 if((set && !IS_SET(MODE_ALTSCREEN)) ||
1463 (!set && IS_SET(MODE_ALTSCREEN))) {
1470 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1473 /* case 2: DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
1474 /* case 3: DECCOLM -- Column (NOT SUPPORTED) */
1475 /* case 4: DECSCLM -- Scroll (NOT SUPPORTED) */
1476 /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
1477 /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
1478 /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
1480 "erresc: unknown private set/reset mode %d\n",
1486 case 0: /* Error (IGNORED) */
1488 case 2: /* KAM -- keyboard action */
1489 MODBIT(term.mode, set, MODE_KBDLOCK);
1491 case 4: /* IRM -- Insertion-replacement */
1492 MODBIT(term.mode, set, MODE_INSERT);
1494 case 12: /* XXX: SRM -- Send/Receive */
1496 case 20: /* LNM -- Linefeed/new line */
1497 MODBIT(term.mode, set, MODE_CRLF);
1501 "erresc: unknown set/reset mode %d\n",
1513 switch(csiescseq.mode) {
1516 fprintf(stderr, "erresc: unknown csi ");
1520 case '@': /* ICH -- Insert <n> blank char */
1521 DEFAULT(csiescseq.arg[0], 1);
1522 tinsertblank(csiescseq.arg[0]);
1524 case 'A': /* CUU -- Cursor <n> Up */
1526 DEFAULT(csiescseq.arg[0], 1);
1527 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1529 case 'B': /* CUD -- Cursor <n> Down */
1530 DEFAULT(csiescseq.arg[0], 1);
1531 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1533 case 'c': /* DA -- Device Attributes */
1534 if(csiescseq.arg[0] == 0)
1535 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1537 case 'C': /* CUF -- Cursor <n> Forward */
1539 DEFAULT(csiescseq.arg[0], 1);
1540 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1542 case 'D': /* CUB -- Cursor <n> Backward */
1543 DEFAULT(csiescseq.arg[0], 1);
1544 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1546 case 'E': /* CNL -- Cursor <n> Down and first col */
1547 DEFAULT(csiescseq.arg[0], 1);
1548 tmoveto(0, term.c.y+csiescseq.arg[0]);
1550 case 'F': /* CPL -- Cursor <n> Up and first col */
1551 DEFAULT(csiescseq.arg[0], 1);
1552 tmoveto(0, term.c.y-csiescseq.arg[0]);
1554 case 'g': /* TBC -- Tabulation clear */
1555 switch (csiescseq.arg[0]) {
1556 case 0: /* clear current tab stop */
1557 term.tabs[term.c.x] = 0;
1559 case 3: /* clear all the tabs */
1560 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1566 case 'G': /* CHA -- Move to <col> */
1568 DEFAULT(csiescseq.arg[0], 1);
1569 tmoveto(csiescseq.arg[0]-1, term.c.y);
1571 case 'H': /* CUP -- Move to <row> <col> */
1573 DEFAULT(csiescseq.arg[0], 1);
1574 DEFAULT(csiescseq.arg[1], 1);
1575 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1577 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1578 DEFAULT(csiescseq.arg[0], 1);
1579 while(csiescseq.arg[0]--)
1582 case 'J': /* ED -- Clear screen */
1584 switch(csiescseq.arg[0]) {
1586 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1587 if(term.c.y < term.row-1)
1588 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1592 tclearregion(0, 0, term.col-1, term.c.y-1);
1593 tclearregion(0, term.c.y, term.c.x, term.c.y);
1596 tclearregion(0, 0, term.col-1, term.row-1);
1602 case 'K': /* EL -- Clear line */
1603 switch(csiescseq.arg[0]) {
1605 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1608 tclearregion(0, term.c.y, term.c.x, term.c.y);
1611 tclearregion(0, term.c.y, term.col-1, term.c.y);
1615 case 'S': /* SU -- Scroll <n> line up */
1616 DEFAULT(csiescseq.arg[0], 1);
1617 tscrollup(term.top, csiescseq.arg[0]);
1619 case 'T': /* SD -- Scroll <n> line down */
1620 DEFAULT(csiescseq.arg[0], 1);
1621 tscrolldown(term.top, csiescseq.arg[0]);
1623 case 'L': /* IL -- Insert <n> blank lines */
1624 DEFAULT(csiescseq.arg[0], 1);
1625 tinsertblankline(csiescseq.arg[0]);
1627 case 'l': /* RM -- Reset Mode */
1628 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1630 case 'M': /* DL -- Delete <n> lines */
1631 DEFAULT(csiescseq.arg[0], 1);
1632 tdeleteline(csiescseq.arg[0]);
1634 case 'X': /* ECH -- Erase <n> char */
1635 DEFAULT(csiescseq.arg[0], 1);
1636 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1638 case 'P': /* DCH -- Delete <n> char */
1639 DEFAULT(csiescseq.arg[0], 1);
1640 tdeletechar(csiescseq.arg[0]);
1642 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1643 DEFAULT(csiescseq.arg[0], 1);
1644 while(csiescseq.arg[0]--)
1647 case 'd': /* VPA -- Move to <row> */
1648 DEFAULT(csiescseq.arg[0], 1);
1649 tmoveto(term.c.x, csiescseq.arg[0]-1);
1651 case 'h': /* SM -- Set terminal mode */
1652 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1654 case 'm': /* SGR -- Terminal attribute (color) */
1655 tsetattr(csiescseq.arg, csiescseq.narg);
1657 case 'r': /* DECSTBM -- Set Scrolling Region */
1658 if(csiescseq.priv) {
1661 DEFAULT(csiescseq.arg[0], 1);
1662 DEFAULT(csiescseq.arg[1], term.row);
1663 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1667 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1668 tcursor(CURSOR_SAVE);
1670 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1671 tcursor(CURSOR_LOAD);
1682 for(i = 0; i < csiescseq.len; i++) {
1683 c = csiescseq.buf[i] & 0xff;
1686 } else if(c == '\n') {
1688 } else if(c == '\r') {
1690 } else if(c == 0x1b) {
1693 printf("(%02x)", c);
1701 memset(&csiescseq, 0, sizeof(csiescseq));
1709 * TODO: make this being useful in case of color palette change.
1715 switch(strescseq.type) {
1716 case ']': /* OSC -- Operating System Command */
1722 * TODO: Handle special chars in string, like umlauts.
1725 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1729 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1731 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1734 fprintf(stderr, "erresc: unknown str ");
1739 case 'k': /* old title set compatibility */
1740 XStoreName(xw.dpy, xw.win, strescseq.buf);
1742 case 'P': /* DSC -- Device Control String */
1743 case '_': /* APC -- Application Program Command */
1744 case '^': /* PM -- Privacy Message */
1746 fprintf(stderr, "erresc: unknown str ");
1756 * TODO: Implement parsing like for CSI when required.
1757 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1767 printf("ESC%c", strescseq.type);
1768 for(i = 0; i < strescseq.len; i++) {
1769 c = strescseq.buf[i] & 0xff;
1772 } else if(c == '\n') {
1774 } else if(c == '\r') {
1776 } else if(c == 0x1b) {
1779 printf("(%02x)", c);
1787 memset(&strescseq, 0, sizeof(strescseq));
1791 tputtab(bool forward) {
1797 for(++x; x < term.col && !term.tabs[x]; ++x)
1802 for(--x; x > 0 && !term.tabs[x]; --x)
1805 tmoveto(x, term.c.y);
1809 tputc(char *c, int len) {
1811 bool control = ascii < '\x20' || ascii == 0177;
1814 if (xwrite(iofd, c, len) < 0) {
1815 fprintf(stderr, "Error writting in %s:%s\n",
1816 opt_io, strerror(errno));
1822 * STR sequences must be checked before of anything
1823 * because it can use some control codes as part of the sequence
1825 if(term.esc & ESC_STR) {
1828 term.esc = ESC_START | ESC_STR_END;
1830 case '\a': /* backwards compatibility to xterm */
1835 strescseq.buf[strescseq.len++] = ascii;
1836 if(strescseq.len+1 >= STR_BUF_SIZ) {
1844 * Actions of control codes must be performed as soon they arrive
1845 * because they can be embedded inside a control sequence, and
1846 * they must not cause conflicts with sequences.
1854 tmoveto(term.c.x-1, term.c.y);
1857 tmoveto(0, term.c.y);
1862 /* go to first col if the mode is set */
1863 tnewline(IS_SET(MODE_CRLF));
1865 case '\a': /* BEL */
1866 if(!(xw.state & WIN_FOCUSED))
1869 case '\033': /* ESC */
1871 term.esc = ESC_START;
1873 case '\016': /* SO */
1874 term.c.attr.mode |= ATTR_GFX;
1876 case '\017': /* SI */
1877 term.c.attr.mode &= ~ATTR_GFX;
1879 case '\032': /* SUB */
1880 case '\030': /* CAN */
1883 case '\005': /* ENQ (IGNORED) */
1884 case '\000': /* NUL (IGNORED) */
1885 case '\021': /* XON (IGNORED) */
1886 case '\023': /* XOFF (IGNORED) */
1887 case 0177: /* DEL (IGNORED) */
1890 } else if(term.esc & ESC_START) {
1891 if(term.esc & ESC_CSI) {
1892 csiescseq.buf[csiescseq.len++] = ascii;
1893 if(BETWEEN(ascii, 0x40, 0x7E)
1894 || csiescseq.len >= ESC_BUF_SIZ) {
1896 csiparse(), csihandle();
1898 } else if(term.esc & ESC_STR_END) {
1902 } else if(term.esc & ESC_ALTCHARSET) {
1904 case '0': /* Line drawing set */
1905 term.c.attr.mode |= ATTR_GFX;
1907 case 'B': /* USASCII */
1908 term.c.attr.mode &= ~ATTR_GFX;
1910 case 'A': /* UK (IGNORED) */
1911 case '<': /* multinational charset (IGNORED) */
1912 case '5': /* Finnish (IGNORED) */
1913 case 'C': /* Finnish (IGNORED) */
1914 case 'K': /* German (IGNORED) */
1917 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1920 } else if(term.esc & ESC_TEST) {
1921 if(ascii == '8') { /* DEC screen alignment test. */
1922 char E[UTF_SIZ] = "E";
1925 for(x = 0; x < term.col; ++x) {
1926 for(y = 0; y < term.row; ++y)
1927 tsetchar(E, &term.c.attr, x, y);
1934 term.esc |= ESC_CSI;
1937 term.esc |= ESC_TEST;
1939 case 'P': /* DCS -- Device Control String */
1940 case '_': /* APC -- Application Program Command */
1941 case '^': /* PM -- Privacy Message */
1942 case ']': /* OSC -- Operating System Command */
1943 case 'k': /* old title set compatibility */
1945 strescseq.type = ascii;
1946 term.esc |= ESC_STR;
1948 case '(': /* set primary charset G0 */
1949 term.esc |= ESC_ALTCHARSET;
1951 case ')': /* set secondary charset G1 (IGNORED) */
1952 case '*': /* set tertiary charset G2 (IGNORED) */
1953 case '+': /* set quaternary charset G3 (IGNORED) */
1956 case 'D': /* IND -- Linefeed */
1957 if(term.c.y == term.bot) {
1958 tscrollup(term.top, 1);
1960 tmoveto(term.c.x, term.c.y+1);
1964 case 'E': /* NEL -- Next line */
1965 tnewline(1); /* always go to first col */
1968 case 'H': /* HTS -- Horizontal tab stop */
1969 term.tabs[term.c.x] = 1;
1972 case 'M': /* RI -- Reverse index */
1973 if(term.c.y == term.top) {
1974 tscrolldown(term.top, 1);
1976 tmoveto(term.c.x, term.c.y-1);
1980 case 'Z': /* DECID -- Identify Terminal */
1981 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1984 case 'c': /* RIS -- Reset to inital state */
1989 case '=': /* DECPAM -- Application keypad */
1990 term.mode |= MODE_APPKEYPAD;
1993 case '>': /* DECPNM -- Normal keypad */
1994 term.mode &= ~MODE_APPKEYPAD;
1997 case '7': /* DECSC -- Save Cursor */
1998 tcursor(CURSOR_SAVE);
2001 case '8': /* DECRC -- Restore Cursor */
2002 tcursor(CURSOR_LOAD);
2005 case '\\': /* ST -- Stop */
2009 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2010 (uchar) ascii, isprint(ascii)? ascii:'.');
2015 * All characters which forms part of a sequence are not
2021 * Display control codes only if we are in graphic mode
2023 if(control && !(term.c.attr.mode & ATTR_GFX))
2025 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2027 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
2028 tnewline(1); /* always go to first col */
2029 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2030 if(term.c.x+1 < term.col)
2031 tmoveto(term.c.x+1, term.c.y);
2033 term.c.state |= CURSOR_WRAPNEXT;
2037 tresize(int col, int row) {
2039 int minrow = MIN(row, term.row);
2040 int mincol = MIN(col, term.col);
2041 int slide = term.c.y - row + 1;
2044 if(col < 1 || row < 1)
2047 /* free unneeded rows */
2050 /* slide screen to keep cursor where we expect it -
2051 * tscrollup would work here, but we can optimize to
2052 * memmove because we're freeing the earlier lines */
2053 for(/* i = 0 */; i < slide; i++) {
2057 memmove(term.line, term.line + slide, row * sizeof(Line));
2058 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2060 for(i += row; i < term.row; i++) {
2065 /* resize to new height */
2066 term.line = xrealloc(term.line, row * sizeof(Line));
2067 term.alt = xrealloc(term.alt, row * sizeof(Line));
2068 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2069 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2071 /* resize each row to new width, zero-pad if needed */
2072 for(i = 0; i < minrow; i++) {
2074 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2075 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2076 for(x = mincol; x < col; x++) {
2077 term.line[i][x].state = 0;
2078 term.alt[i][x].state = 0;
2082 /* allocate any new rows */
2083 for(/* i == minrow */; i < row; i++) {
2085 term.line[i] = xcalloc(col, sizeof(Glyph));
2086 term.alt [i] = xcalloc(col, sizeof(Glyph));
2088 if(col > term.col) {
2089 bp = term.tabs + term.col;
2091 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2092 while(--bp > term.tabs && !*bp)
2094 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2097 /* update terminal size */
2100 /* make use of the LIMIT in tmoveto */
2101 tmoveto(term.c.x, term.c.y);
2102 /* reset scrolling region */
2103 tsetscroll(0, row-1);
2109 xresize(int col, int row) {
2110 xw.tw = MAX(1, 2*borderpx + col * xw.cw);
2111 xw.th = MAX(1, 2*borderpx + row * xw.ch);
2113 XftDrawChange(xw.xft_draw, xw.buf);
2119 XRenderColor xft_color = { .alpha = 0 };
2121 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2122 for(i = 0; i < LEN(colorname); i++) {
2125 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
2126 die("Could not allocate color '%s'\n", colorname[i]);
2130 /* load colors [16-255] ; same colors as xterm */
2131 for(i = 16, r = 0; r < 6; r++) {
2132 for(g = 0; g < 6; g++) {
2133 for(b = 0; b < 6; b++) {
2134 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
2135 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
2136 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
2137 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
2138 die("Could not allocate color %d\n", i);
2145 for(r = 0; r < 24; r++, i++) {
2146 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
2147 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color,
2149 die("Could not allocate color %d\n", i);
2155 xtermclear(int col1, int row1, int col2, int row2) {
2156 XftDrawRect(xw.xft_draw,
2157 &dc.xft_col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2158 borderpx + col1 * xw.cw,
2159 borderpx + row1 * xw.ch,
2160 (col2-col1+1) * xw.cw,
2161 (row2-row1+1) * xw.ch);
2165 * Absolute coordinates.
2168 xclear(int x1, int y1, int x2, int y2) {
2169 XftDrawRect(xw.xft_draw,
2170 &dc.xft_col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2171 x1, y1, x2-x1, y2-y1);
2176 XClassHint class = {opt_class ? opt_class : termname, termname};
2177 XWMHints wm = {.flags = InputHint, .input = 1};
2178 XSizeHints *sizeh = NULL;
2180 sizeh = XAllocSizeHints();
2181 if(xw.isfixed == False) {
2182 sizeh->flags = PSize | PResizeInc | PBaseSize;
2183 sizeh->height = xw.h;
2184 sizeh->width = xw.w;
2185 sizeh->height_inc = xw.ch;
2186 sizeh->width_inc = xw.cw;
2187 sizeh->base_height = 2*borderpx;
2188 sizeh->base_width = 2*borderpx;
2190 sizeh->flags = PMaxSize | PMinSize;
2191 sizeh->min_width = sizeh->max_width = xw.fw;
2192 sizeh->min_height = sizeh->max_height = xw.fh;
2195 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2200 xloadfont(Font *f, FcPattern *pattern) {
2204 match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
2207 if(!(f->xft_set = XftFontOpenPattern(xw.dpy, match))) {
2208 FcPatternDestroy(match);
2212 f->ascent = f->xft_set->ascent;
2213 f->descent = f->xft_set->descent;
2215 f->rbearing = f->xft_set->max_advance_width;
2217 f->height = f->xft_set->height;
2218 f->width = f->lbearing + f->rbearing;
2224 xloadfonts(char *fontstr, int fontsize) {
2229 if(fontstr[0] == '-') {
2230 pattern = XftXlfdParse(fontstr, False, False);
2232 pattern = FcNameParse((FcChar8 *)fontstr);
2236 die("st: can't open font %s\n", fontstr);
2239 FcPatternDel(pattern, FC_PIXEL_SIZE);
2240 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2241 usedfontsize = fontsize;
2243 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2244 if(result == FcResultMatch) {
2245 usedfontsize = (int)fontval;
2248 * Default font size is 12, if none given. This is to
2249 * have a known usedfontsize value.
2251 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2256 if(xloadfont(&dc.font, pattern))
2257 die("st: can't open font %s\n", fontstr);
2259 /* Setting character width and height. */
2260 xw.cw = dc.font.width;
2261 xw.ch = dc.font.height;
2263 FcPatternDel(pattern, FC_WEIGHT);
2264 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2265 if(xloadfont(&dc.bfont, pattern))
2266 die("st: can't open font %s\n", fontstr);
2268 FcPatternDel(pattern, FC_SLANT);
2269 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2270 if(xloadfont(&dc.ibfont, pattern))
2271 die("st: can't open font %s\n", fontstr);
2273 FcPatternDel(pattern, FC_WEIGHT);
2274 if(xloadfont(&dc.ifont, pattern))
2275 die("st: can't open font %s\n", fontstr);
2277 FcPatternDestroy(pattern);
2281 xzoom(const Arg *arg)
2283 xloadfonts(usedfont, usedfontsize + arg->i);
2290 XSetWindowAttributes attrs;
2293 int sw, sh, major, minor;
2295 if(!(xw.dpy = XOpenDisplay(NULL)))
2296 die("Can't open display\n");
2297 xw.scr = XDefaultScreen(xw.dpy);
2298 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2301 usedfont = (opt_font == NULL)? font : opt_font;
2302 xloadfonts(usedfont, 0);
2305 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2308 /* adjust fixed window geometry */
2310 sw = DisplayWidth(xw.dpy, xw.scr);
2311 sh = DisplayHeight(xw.dpy, xw.scr);
2313 xw.fx = sw + xw.fx - xw.fw - 1;
2315 xw.fy = sh + xw.fy - xw.fh - 1;
2320 /* window - default size */
2321 xw.h = 2*borderpx + term.row * xw.ch;
2322 xw.w = 2*borderpx + term.col * xw.cw;
2327 attrs.background_pixel = dc.xft_col[defaultbg].pixel;
2328 attrs.border_pixel = dc.xft_col[defaultbg].pixel;
2329 attrs.bit_gravity = NorthWestGravity;
2330 attrs.event_mask = FocusChangeMask | KeyPressMask
2331 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2332 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2333 attrs.colormap = xw.cmap;
2335 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2336 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2337 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2339 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2343 /* double buffering */
2344 if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2345 die("Xdbe extension is not present\n");
2346 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2348 /* Xft rendering context */
2349 xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2352 xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2353 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2354 | XIMStatusNothing, XNClientWindow, xw.win,
2355 XNFocusWindow, xw.win, NULL);
2357 dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2359 /* white cursor, black outline */
2360 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2361 XDefineCursor(xw.dpy, xw.win, cursor);
2362 XRecolorCursor(xw.dpy, cursor,
2363 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2364 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2366 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2367 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2368 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2371 XMapWindow(xw.dpy, xw.win);
2377 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2378 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2379 width = charlen * xw.cw;
2380 Font *font = &dc.font;
2382 XftColor *fg = &dc.xft_col[base.fg], *bg = &dc.xft_col[base.bg],
2383 *temp, revfg, revbg;
2384 XRenderColor colfg, colbg;
2386 if(base.mode & ATTR_REVERSE)
2387 temp = fg, fg = bg, bg = temp;
2389 if(base.mode & ATTR_BOLD) {
2390 if(BETWEEN(base.fg, 0, 7)) {
2391 /* basic system colors */
2392 fg = &dc.xft_col[base.fg + 8];
2393 } else if(BETWEEN(base.fg, 16, 195)) {
2395 fg = &dc.xft_col[base.fg + 36];
2396 } else if(BETWEEN(base.fg, 232, 251)) {
2398 fg = &dc.xft_col[base.fg + 4];
2401 * Those ranges will not be brightened:
2402 * 8 - 15 – bright system colors
2403 * 196 - 231 – highest 256 color cube
2404 * 252 - 255 – brightest colors in greyscale
2409 if(base.mode & ATTR_ITALIC)
2411 if(base.mode & (ATTR_ITALIC|ATTR_BOLD))
2414 if(IS_SET(MODE_REVERSE)) {
2415 if(fg == &dc.xft_col[defaultfg]) {
2416 fg = &dc.xft_col[defaultbg];
2418 colfg.red = ~fg->color.red;
2419 colfg.green = ~fg->color.green;
2420 colfg.blue = ~fg->color.blue;
2421 colfg.alpha = fg->color.alpha;
2422 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2426 if(bg == &dc.xft_col[defaultbg]) {
2427 bg = &dc.xft_col[defaultfg];
2429 colbg.red = ~bg->color.red;
2430 colbg.green = ~bg->color.green;
2431 colbg.blue = ~bg->color.blue;
2432 colbg.alpha = bg->color.alpha;
2433 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2438 XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen,
2440 width = extents.xOff;
2442 /* Intelligent cleaning up of the borders. */
2444 xclear(0, (y == 0)? 0 : winy, borderpx,
2445 winy + xw.ch + (y == term.row-1)? xw.h : 0);
2447 if(x + charlen >= term.col-1) {
2448 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2449 (y == term.row-1)? xw.h : (winy + xw.ch));
2452 xclear(winx, 0, winx + width, borderpx);
2454 xclear(winx, winy + xw.ch, winx + width, xw.h);
2456 XftDrawRect(xw.xft_draw, bg, winx, winy, width, xw.ch);
2457 XftDrawStringUtf8(xw.xft_draw, fg, font->xft_set, winx,
2458 winy + font->ascent, (FcChar8 *)s, bytelen);
2460 if(base.mode & ATTR_UNDERLINE) {
2461 XftDrawRect(xw.xft_draw, fg, winx, winy + font->ascent + 1,
2468 static int oldx = 0, oldy = 0;
2470 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs, 0};
2472 LIMIT(oldx, 0, term.col-1);
2473 LIMIT(oldy, 0, term.row-1);
2475 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2476 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2478 /* remove the old cursor */
2479 if(term.line[oldy][oldx].state & GLYPH_SET) {
2480 sl = utf8size(term.line[oldy][oldx].c);
2481 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2484 xtermclear(oldx, oldy, oldx, oldy);
2487 /* draw the new one */
2488 if(!(term.c.state & CURSOR_HIDE)) {
2489 if(!(xw.state & WIN_FOCUSED))
2492 if(IS_SET(MODE_REVERSE))
2493 g.mode |= ATTR_REVERSE, g.fg = defaultcs, g.bg = defaultfg;
2496 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2497 oldx = term.c.x, oldy = term.c.y;
2503 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2508 struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2512 XSync(xw.dpy, False); /* necessary for a good tput flash */
2513 nanosleep(&tv, NULL);
2518 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2520 drawregion(0, 0, term.col, term.row);
2521 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2525 drawregion(int x1, int y1, int x2, int y2) {
2526 int ic, ib, x, y, ox, sl;
2528 char buf[DRAW_BUF_SIZ];
2529 bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
2531 if((sel.alt && !alt) || (!sel.alt && alt))
2533 if(!(xw.state & WIN_VISIBLE))
2536 for(y = y1; y < y2; y++) {
2540 xtermclear(0, y, term.col, y);
2542 base = term.line[y][0];
2544 for(x = x1; x < x2; x++) {
2545 new = term.line[y][x];
2546 if(ena_sel && *(new.c) && selected(x, y))
2547 new.mode ^= ATTR_REVERSE;
2548 if(ib > 0 && (!(new.state & GLYPH_SET)
2549 || ATTRCMP(base, new)
2550 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2551 xdraws(buf, base, ox, y, ic, ib);
2554 if(new.state & GLYPH_SET) {
2559 sl = utf8size(new.c);
2560 memcpy(buf+ib, new.c, sl);
2566 xdraws(buf, base, ox, y, ic, ib);
2572 expose(XEvent *ev) {
2573 XExposeEvent *e = &ev->xexpose;
2575 if(xw.state & WIN_REDRAW) {
2577 xw.state &= ~WIN_REDRAW;
2582 visibility(XEvent *ev) {
2583 XVisibilityEvent *e = &ev->xvisibility;
2585 if(e->state == VisibilityFullyObscured) {
2586 xw.state &= ~WIN_VISIBLE;
2587 } else if(!(xw.state & WIN_VISIBLE)) {
2588 /* need a full redraw for next Expose, not just a buf copy */
2589 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2595 xw.state &= ~WIN_VISIBLE;
2599 xseturgency(int add) {
2600 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2602 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2603 XSetWMHints(xw.dpy, xw.win, h);
2609 if(ev->type == FocusIn) {
2610 XSetICFocus(xw.xic);
2611 xw.state |= WIN_FOCUSED;
2614 XUnsetICFocus(xw.xic);
2615 xw.state &= ~WIN_FOCUSED;
2620 kmap(KeySym k, uint state) {
2625 for(i = 0; i < LEN(key); i++) {
2628 if(key[i].k == k && ((state & mask) == mask
2629 || (mask == XK_NO_MOD && !state))) {
2630 return (char*)key[i].s;
2637 kpress(XEvent *ev) {
2638 XKeyEvent *e = &ev->xkey;
2640 char buf[32], *customkey;
2641 int len, meta, shift, i;
2644 if (IS_SET(MODE_KBDLOCK))
2647 meta = e->state & Mod1Mask;
2648 shift = e->state & ShiftMask;
2649 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2652 for(i = 0; i < LEN(shortcuts); i++) {
2653 if((ksym == shortcuts[i].keysym)
2654 && (CLEANMASK(shortcuts[i].mod) == \
2655 CLEANMASK(e->state))
2656 && shortcuts[i].func) {
2657 shortcuts[i].func(&(shortcuts[i].arg));
2661 /* 2. custom keys from config.h */
2662 if((customkey = kmap(ksym, e->state))) {
2663 ttywrite(customkey, strlen(customkey));
2664 /* 2. hardcoded (overrides X lookup) */
2671 /* XXX: shift up/down doesn't work */
2672 sprintf(buf, "\033%c%c",
2673 IS_SET(MODE_APPKEYPAD) ? 'O' : '[',
2674 (shift ? "dacb":"DACB")[ksym - XK_Left]);
2682 if(IS_SET(MODE_CRLF)) {
2683 ttywrite("\r\n", 2);
2691 if(meta && len == 1)
2692 ttywrite("\033", 1);
2701 cmessage(XEvent *e) {
2703 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2704 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2705 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2706 xw.state |= WIN_FOCUSED;
2708 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2709 xw.state &= ~WIN_FOCUSED;
2711 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
2712 /* Send SIGHUP to shell */
2719 cresize(int width, int height)
2728 col = (xw.w - 2*borderpx) / xw.cw;
2729 row = (xw.h - 2*borderpx) / xw.ch;
2730 if(col == term.col && row == term.row)
2740 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2743 cresize(e->xconfigure.width, e->xconfigure.height);
2750 int xfd = XConnectionNumber(xw.dpy), i;
2751 struct timeval drawtimeout, *tv = NULL;
2755 FD_SET(cmdfd, &rfd);
2757 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2760 die("select failed: %s\n", SERRNO);
2764 * Stop after a certain number of reads so the user does not
2765 * feel like the system is stuttering.
2767 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2771 * Just wait a bit so it isn't disturbing the
2772 * user and the system is able to write something.
2774 drawtimeout.tv_sec = 0;
2775 drawtimeout.tv_usec = 5;
2782 while(XPending(xw.dpy)) {
2783 XNextEvent(xw.dpy, &ev);
2784 if(XFilterEvent(&ev, None))
2786 if(handler[ev.type])
2787 (handler[ev.type])(&ev);
2796 main(int argc, char *argv[]) {
2797 int i, bitm, xr, yr;
2800 xw.fw = xw.fh = xw.fx = xw.fy = 0;
2803 for(i = 1; i < argc; i++) {
2804 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2807 opt_class = argv[i];
2810 /* eat every remaining arguments */
2822 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2827 if(bitm & WidthValue)
2829 if(bitm & HeightValue)
2831 if(bitm & XNegative && xw.fx == 0)
2833 if(bitm & XNegative && xw.fy == 0)
2836 if(xw.fh != 0 && xw.fw != 0)
2845 opt_title = argv[i];
2852 opt_embed = argv[i];
2858 setlocale(LC_CTYPE, "");
2859 XSetLocaleModifiers("");