1 /* See LICENSE for licence details. */
2 #define _XOPEN_SOURCE 600
15 #include <sys/ioctl.h>
16 #include <sys/select.h>
19 #include <sys/types.h>
23 #include <X11/Xatom.h>
25 #include <X11/Xutil.h>
26 #include <X11/cursorfont.h>
27 #include <X11/keysym.h>
28 #include <X11/extensions/Xdbe.h>
29 #include <X11/Xft/Xft.h>
30 #include <fontconfig/fontconfig.h>
34 #define Draw XftDraw *
35 #define Colour XftColor
36 #define Colourmap Colormap
40 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
42 #elif defined(__FreeBSD__) || defined(__DragonFly__)
47 "st " VERSION " (c) 2010-2012 st engineers\n" \
48 "usage: st [-v] [-c class] [-f font] [-g geometry] [-o file]" \
49 " [-t title] [-w windowid] [-e command ...]\n"
52 #define XEMBED_FOCUS_IN 4
53 #define XEMBED_FOCUS_OUT 5
56 #define ESC_BUF_SIZ 256
57 #define ESC_ARG_SIZ 16
58 #define STR_BUF_SIZ 256
59 #define STR_ARG_SIZ 16
60 #define DRAW_BUF_SIZ 20*1024
62 #define XK_NO_MOD UINT_MAX
65 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
68 #define CLEANMASK(mask) (mask & (ShiftMask|ControlMask|Mod1Mask|Mod2Mask|Mod3Mask|Mod4Mask|Mod5Mask))
69 #define SERRNO strerror(errno)
70 #define MIN(a, b) ((a) < (b) ? (a) : (b))
71 #define MAX(a, b) ((a) < (b) ? (b) : (a))
72 #define LEN(a) (sizeof(a) / sizeof(a[0]))
73 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
74 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
75 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
76 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
77 #define IS_SET(flag) (term.mode & (flag))
78 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
80 #define VT102ID "\033[?6c"
82 enum glyph_attribute {
92 enum cursor_movement {
119 MODE_MOUSEMOTION = 64,
125 MODE_APPCURSOR = 2048
131 ESC_STR = 4, /* DSC, OSC, PM, APC */
133 ESC_STR_END = 16, /* a final string was encountered */
134 ESC_TEST = 32, /* Enter in test mode */
145 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
147 typedef unsigned char uchar;
148 typedef unsigned int uint;
149 typedef unsigned long ulong;
150 typedef unsigned short ushort;
153 char c[UTF_SIZ]; /* character code */
154 uchar mode; /* attribute flags */
155 ushort fg; /* foreground */
156 ushort bg; /* background */
157 uchar state; /* state flags */
163 Glyph attr; /* current char attributes */
169 /* CSI Escape sequence structs */
170 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
172 char buf[ESC_BUF_SIZ]; /* raw string */
173 int len; /* raw string length */
175 int arg[ESC_ARG_SIZ];
176 int narg; /* nb of args */
180 /* STR Escape sequence structs */
181 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
183 char type; /* ESC type ... */
184 char buf[STR_BUF_SIZ]; /* raw string */
185 int len; /* raw string length */
186 char *args[STR_ARG_SIZ];
187 int narg; /* nb of args */
190 /* Internal representation of the screen */
192 int row; /* nb row */
193 int col; /* nb col */
194 Line *line; /* screen */
195 Line *alt; /* alternate screen */
196 bool *dirty; /* dirtyness of lines */
197 TCursor c; /* cursor */
198 int top; /* top scroll limit */
199 int bot; /* bottom scroll limit */
200 int mode; /* terminal mode flags */
201 int esc; /* escape state flags */
205 /* Purely graphic info */
211 Atom xembed, wmdeletewin;
217 bool isfixed; /* is fixed geometry? */
218 int fx, fy, fw, fh; /* fixed geometry */
219 int tw, th; /* tty width and height */
220 int w; /* window width */
221 int h; /* window height */
222 int ch; /* char height */
223 int cw; /* char width */
224 char state; /* focus, redraw, visible */
233 /* TODO: use better name for vars... */
244 struct timeval tclick1;
245 struct timeval tclick2;
258 void (*func)(const Arg *);
262 /* function definitions used in config.h */
263 static void xzoom(const Arg *);
265 /* Config.h for applying patches and the configuration. */
279 /* Drawing Context */
281 Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
282 Font font, bfont, ifont, ibfont;
285 static void die(const char *, ...);
286 static void draw(void);
287 static void redraw(void);
288 static void drawregion(int, int, int, int);
289 static void execsh(void);
290 static void sigchld(int);
291 static void run(void);
293 static void csidump(void);
294 static void csihandle(void);
295 static void csiparse(void);
296 static void csireset(void);
297 static void strdump(void);
298 static void strhandle(void);
299 static void strparse(void);
300 static void strreset(void);
302 static void tclearregion(int, int, int, int);
303 static void tcursor(int);
304 static void tdeletechar(int);
305 static void tdeleteline(int);
306 static void tinsertblank(int);
307 static void tinsertblankline(int);
308 static void tmoveto(int, int);
309 static void tmoveato(int x, int y);
310 static void tnew(int, int);
311 static void tnewline(int);
312 static void tputtab(bool);
313 static void tputc(char *, int);
314 static void treset(void);
315 static int tresize(int, int);
316 static void tscrollup(int, int);
317 static void tscrolldown(int, int);
318 static void tsetattr(int*, int);
319 static void tsetchar(char *, Glyph *, int, int);
320 static void tsetscroll(int, int);
321 static void tswapscreen(void);
322 static void tsetdirt(int, int);
323 static void tsetmode(bool, bool, int *, int);
324 static void tfulldirt(void);
325 static void techo(char *, int);
327 static void ttynew(void);
328 static void ttyread(void);
329 static void ttyresize(void);
330 static void ttywrite(const char *, size_t);
332 static void xdraws(char *, Glyph, int, int, int, int);
333 static void xhints(void);
334 static void xclear(int, int, int, int);
335 static void xdrawcursor(void);
336 static void xinit(void);
337 static void xloadcols(void);
338 static void xresettitle(void);
339 static void xseturgency(int);
340 static void xsetsel(char*);
341 static void xtermclear(int, int, int, int);
342 static void xresize(int, int);
344 static void expose(XEvent *);
345 static void visibility(XEvent *);
346 static void unmap(XEvent *);
347 static char *kmap(KeySym, uint);
348 static void kpress(XEvent *);
349 static void cmessage(XEvent *);
350 static void cresize(int width, int height);
351 static void resize(XEvent *);
352 static void focus(XEvent *);
353 static void brelease(XEvent *);
354 static void bpress(XEvent *);
355 static void bmotion(XEvent *);
356 static void selnotify(XEvent *);
357 static void selclear(XEvent *);
358 static void selrequest(XEvent *);
360 static void selinit(void);
361 static inline bool selected(int, int);
362 static void selcopy(void);
363 static void selpaste(void);
364 static void selscroll(int, int);
366 static int utf8decode(char *, long *);
367 static int utf8encode(long *, char *);
368 static int utf8size(char *);
369 static int isfullutf8(char *, int);
371 static ssize_t xwrite(int, char *, size_t);
372 static void *xmalloc(size_t);
373 static void *xrealloc(void *, size_t);
374 static void *xcalloc(size_t nmemb, size_t size);
376 static void (*handler[LASTEvent])(XEvent *) = {
378 [ClientMessage] = cmessage,
379 [ConfigureNotify] = resize,
380 [VisibilityNotify] = visibility,
381 [UnmapNotify] = unmap,
385 [MotionNotify] = bmotion,
386 [ButtonPress] = bpress,
387 [ButtonRelease] = brelease,
388 [SelectionClear] = selclear,
389 [SelectionNotify] = selnotify,
390 [SelectionRequest] = selrequest,
397 static CSIEscape csiescseq;
398 static STREscape strescseq;
401 static Selection sel;
402 static int iofd = -1;
403 static char **opt_cmd = NULL;
404 static char *opt_io = NULL;
405 static char *opt_title = NULL;
406 static char *opt_embed = NULL;
407 static char *opt_class = NULL;
408 static char *opt_font = NULL;
410 static char *usedfont = NULL;
411 static int usedfontsize = 0;
414 xwrite(int fd, char *s, size_t len) {
418 ssize_t r = write(fd, s, len);
428 xmalloc(size_t len) {
429 void *p = malloc(len);
432 die("Out of memory\n");
438 xrealloc(void *p, size_t len) {
439 if((p = realloc(p, len)) == NULL)
440 die("Out of memory\n");
446 xcalloc(size_t nmemb, size_t size) {
447 void *p = calloc(nmemb, size);
450 die("Out of memory\n");
456 utf8decode(char *s, long *u) {
462 if(~c & B7) { /* 0xxxxxxx */
465 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
466 *u = c&(B4|B3|B2|B1|B0);
468 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
469 *u = c&(B3|B2|B1|B0);
471 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
478 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
480 if((c & (B7|B6)) != B7) /* 10xxxxxx */
483 *u |= c & (B5|B4|B3|B2|B1|B0);
486 if((n == 1 && *u < 0x80) ||
487 (n == 2 && *u < 0x800) ||
488 (n == 3 && *u < 0x10000) ||
489 (*u >= 0xD800 && *u <= 0xDFFF)) {
501 utf8encode(long *u, char *s) {
509 *sp = uc; /* 0xxxxxxx */
511 } else if(*u < 0x800) {
512 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
514 } else if(uc < 0x10000) {
515 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
517 } else if(uc <= 0x10FFFF) {
518 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
524 for(i=n,++sp; i>0; --i,++sp)
525 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
537 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
538 UTF-8 otherwise return 0 */
540 isfullutf8(char *s, int b) {
548 } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
550 } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
552 ((b == 2) && (*c2&(B7|B6)) == B7))) {
554 } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
556 ((b == 2) && (*c2&(B7|B6)) == B7) ||
557 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
570 } else if((c&(B7|B6|B5)) == (B7|B6)) {
572 } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
581 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
582 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
586 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
587 if(sel.xtarget == None)
588 sel.xtarget = XA_STRING;
596 return LIMIT(x, 0, term.col-1);
604 return LIMIT(y, 0, term.row-1);
608 selected(int x, int y) {
611 if(sel.ey == y && sel.by == y) {
612 bx = MIN(sel.bx, sel.ex);
613 ex = MAX(sel.bx, sel.ex);
614 return BETWEEN(x, bx, ex);
617 return ((sel.b.y < y && y < sel.e.y)
618 || (y == sel.e.y && x <= sel.e.x))
619 || (y == sel.b.y && x >= sel.b.x
620 && (x <= sel.e.x || sel.b.y != sel.e.y));
624 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
626 *b = e->xbutton.button;
628 *x = x2col(e->xbutton.x);
629 *y = y2row(e->xbutton.y);
631 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
632 sel.b.y = MIN(sel.by, sel.ey);
633 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
634 sel.e.y = MAX(sel.by, sel.ey);
638 mousereport(XEvent *e) {
639 int x = x2col(e->xbutton.x);
640 int y = y2row(e->xbutton.y);
641 int button = e->xbutton.button;
642 int state = e->xbutton.state;
643 char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
644 static int ob, ox, oy;
647 if(e->xbutton.type == MotionNotify) {
648 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
652 } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
658 if(e->xbutton.type == ButtonPress) {
664 buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
665 + (state & Mod4Mask ? 8 : 0)
666 + (state & ControlMask ? 16 : 0);
668 ttywrite(buf, sizeof(buf));
673 if(IS_SET(MODE_MOUSE)) {
675 } else if(e->xbutton.button == Button1) {
678 tsetdirt(sel.b.y, sel.e.y);
682 sel.ex = sel.bx = x2col(e->xbutton.x);
683 sel.ey = sel.by = y2row(e->xbutton.y);
684 } else if(e->xbutton.button == Button4) {
686 } else if(e->xbutton.button == Button5) {
694 int x, y, bufsize, is_selected = 0, size;
700 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
701 ptr = str = xmalloc(bufsize);
703 /* append every set & selected glyph to the selection */
704 for(y = 0; y < term.row; y++) {
705 gp = &term.line[y][0];
706 last = gp + term.col;
708 while(--last >= gp && !(last->state & GLYPH_SET))
711 for(x = 0; gp <= last; x++, ++gp) {
712 if(!(is_selected = selected(x, y)))
715 p = (gp->state & GLYPH_SET) ? gp->c : " ";
717 memcpy(ptr, p, size);
720 /* \n at the end of every selected line except for the last one */
721 if(is_selected && y < sel.e.y)
726 sel.alt = IS_SET(MODE_ALTSCREEN);
731 selnotify(XEvent *e) {
732 ulong nitems, ofs, rem;
739 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
740 False, AnyPropertyType, &type, &format,
741 &nitems, &rem, &data)) {
742 fprintf(stderr, "Clipboard allocation failed\n");
745 ttywrite((const char *) data, nitems * format / 8);
747 /* number of 32-bit chunks returned */
748 ofs += nitems * format / 32;
754 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
755 xw.win, CurrentTime);
758 void selclear(XEvent *e) {
762 tsetdirt(sel.b.y, sel.e.y);
766 selrequest(XEvent *e) {
767 XSelectionRequestEvent *xsre;
769 Atom xa_targets, string;
771 xsre = (XSelectionRequestEvent *) e;
772 xev.type = SelectionNotify;
773 xev.requestor = xsre->requestor;
774 xev.selection = xsre->selection;
775 xev.target = xsre->target;
776 xev.time = xsre->time;
780 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
781 if(xsre->target == xa_targets) {
782 /* respond with the supported type */
783 string = sel.xtarget;
784 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
785 XA_ATOM, 32, PropModeReplace,
786 (uchar *) &string, 1);
787 xev.property = xsre->property;
788 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
789 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
790 xsre->target, 8, PropModeReplace,
791 (uchar *) sel.clip, strlen(sel.clip));
792 xev.property = xsre->property;
795 /* all done, send a notification to the listener */
796 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
797 fprintf(stderr, "Error sending SelectionNotify event\n");
802 /* register the selection for both the clipboard and the primary */
808 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
810 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
811 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
815 brelease(XEvent *e) {
818 if(IS_SET(MODE_MOUSE)) {
823 if(e->xbutton.button == Button2) {
825 } else if(e->xbutton.button == Button1) {
827 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
828 term.dirty[sel.ey] = 1;
829 if(sel.bx == sel.ex && sel.by == sel.ey) {
831 gettimeofday(&now, NULL);
833 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
834 /* triple click on the line */
835 sel.b.x = sel.bx = 0;
836 sel.e.x = sel.ex = term.col;
837 sel.b.y = sel.e.y = sel.ey;
839 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
840 /* double click to select word */
842 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
843 term.line[sel.ey][sel.bx-1].c[0] != ' ') {
847 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
848 term.line[sel.ey][sel.ex+1].c[0] != ' ') {
852 sel.b.y = sel.e.y = sel.ey;
860 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
861 gettimeofday(&sel.tclick1, NULL);
866 int starty, endy, oldey, oldex;
868 if(IS_SET(MODE_MOUSE)) {
876 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
878 if(oldey != sel.ey || oldex != sel.ex) {
879 starty = MIN(oldey, sel.ey);
880 endy = MAX(oldey, sel.ey);
881 tsetdirt(starty, endy);
887 die(const char *errstr, ...) {
890 va_start(ap, errstr);
891 vfprintf(stderr, errstr, ap);
899 char *envshell = getenv("SHELL");
900 const struct passwd *pass = getpwuid(getuid());
901 char buf[sizeof(long) * 8 + 1];
908 setenv("LOGNAME", pass->pw_name, 1);
909 setenv("USER", pass->pw_name, 1);
910 setenv("SHELL", pass->pw_shell, 0);
911 setenv("HOME", pass->pw_dir, 0);
914 snprintf(buf, sizeof(buf), "%lu", xw.win);
915 setenv("WINDOWID", buf, 1);
917 signal(SIGCHLD, SIG_DFL);
918 signal(SIGHUP, SIG_DFL);
919 signal(SIGINT, SIG_DFL);
920 signal(SIGQUIT, SIG_DFL);
921 signal(SIGTERM, SIG_DFL);
922 signal(SIGALRM, SIG_DFL);
924 DEFAULT(envshell, shell);
925 setenv("TERM", termname, 1);
926 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
927 execvp(args[0], args);
935 if(waitpid(pid, &stat, 0) < 0)
936 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
938 if(WIFEXITED(stat)) {
939 exit(WEXITSTATUS(stat));
948 struct winsize w = {term.row, term.col, 0, 0};
950 /* seems to work fine on linux, openbsd and freebsd */
951 if(openpty(&m, &s, NULL, NULL, &w) < 0)
952 die("openpty failed: %s\n", SERRNO);
954 switch(pid = fork()) {
956 die("fork failed\n");
959 setsid(); /* create a new process group */
960 dup2(s, STDIN_FILENO);
961 dup2(s, STDOUT_FILENO);
962 dup2(s, STDERR_FILENO);
963 if(ioctl(s, TIOCSCTTY, NULL) < 0)
964 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
972 signal(SIGCHLD, sigchld);
974 iofd = (!strcmp(opt_io, "-")) ?
976 open(opt_io, O_WRONLY | O_CREAT, 0666);
978 fprintf(stderr, "Error opening %s:%s\n",
979 opt_io, strerror(errno));
989 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
991 fprintf(stderr, "\n");
996 static char buf[BUFSIZ];
997 static int buflen = 0;
1000 int charsize; /* size of utf8 char in bytes */
1004 /* append read bytes to unprocessed bytes */
1005 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1006 die("Couldn't read from shell: %s\n", SERRNO);
1008 /* process every complete utf8 char */
1011 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1012 charsize = utf8decode(ptr, &utf8c);
1013 utf8encode(&utf8c, s);
1019 /* keep any uncomplete utf8 char for the next call */
1020 memmove(buf, ptr, buflen);
1024 ttywrite(const char *s, size_t n) {
1025 if(write(cmdfd, s, n) == -1)
1026 die("write error on tty: %s\n", SERRNO);
1033 w.ws_row = term.row;
1034 w.ws_col = term.col;
1035 w.ws_xpixel = xw.tw;
1036 w.ws_ypixel = xw.th;
1037 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1038 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1042 tsetdirt(int top, int bot) {
1045 LIMIT(top, 0, term.row-1);
1046 LIMIT(bot, 0, term.row-1);
1048 for(i = top; i <= bot; i++)
1054 tsetdirt(0, term.row-1);
1061 if(mode == CURSOR_SAVE) {
1063 } else if(mode == CURSOR_LOAD) {
1073 term.c = (TCursor){{
1077 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1079 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1080 for(i = tabspaces; i < term.col; i += tabspaces)
1083 term.bot = term.row - 1;
1084 term.mode = MODE_WRAP;
1086 tclearregion(0, 0, term.col-1, term.row-1);
1088 tcursor(CURSOR_SAVE);
1092 tnew(int col, int row) {
1093 /* set screen size */
1096 term.line = xmalloc(term.row * sizeof(Line));
1097 term.alt = xmalloc(term.row * sizeof(Line));
1098 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1099 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1101 for(row = 0; row < term.row; row++) {
1102 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1103 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1104 term.dirty[row] = 0;
1106 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1113 Line *tmp = term.line;
1115 term.line = term.alt;
1117 term.mode ^= MODE_ALTSCREEN;
1122 tscrolldown(int orig, int n) {
1126 LIMIT(n, 0, term.bot-orig+1);
1128 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1130 for(i = term.bot; i >= orig+n; i--) {
1131 temp = term.line[i];
1132 term.line[i] = term.line[i-n];
1133 term.line[i-n] = temp;
1136 term.dirty[i-n] = 1;
1143 tscrollup(int orig, int n) {
1146 LIMIT(n, 0, term.bot-orig+1);
1148 tclearregion(0, orig, term.col-1, orig+n-1);
1150 for(i = orig; i <= term.bot-n; i++) {
1151 temp = term.line[i];
1152 term.line[i] = term.line[i+n];
1153 term.line[i+n] = temp;
1156 term.dirty[i+n] = 1;
1159 selscroll(orig, -n);
1163 selscroll(int orig, int n) {
1167 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1168 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1172 if(sel.by < term.top) {
1176 if(sel.ey > term.bot) {
1180 sel.b.y = sel.by, sel.b.x = sel.bx;
1181 sel.e.y = sel.ey, sel.e.x = sel.ex;
1186 tnewline(int first_col) {
1190 tscrollup(term.top, 1);
1194 tmoveto(first_col ? 0 : term.c.x, y);
1199 /* int noarg = 1; */
1200 char *p = csiescseq.buf;
1204 csiescseq.priv = 1, p++;
1206 while(p < csiescseq.buf+csiescseq.len) {
1207 while(isdigit(*p)) {
1208 csiescseq.arg[csiescseq.narg] *= 10;
1209 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1211 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1212 csiescseq.narg++, p++;
1214 csiescseq.mode = *p;
1222 /* for absolute user moves, when decom is set */
1224 tmoveato(int x, int y) {
1225 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1229 tmoveto(int x, int y) {
1232 if(term.c.state & CURSOR_ORIGIN) {
1237 maxy = term.row - 1;
1239 LIMIT(x, 0, term.col-1);
1240 LIMIT(y, miny, maxy);
1241 term.c.state &= ~CURSOR_WRAPNEXT;
1247 tsetchar(char *c, Glyph *attr, int x, int y) {
1248 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1249 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1250 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1251 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1252 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1253 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1254 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1255 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1256 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1260 * The table is proudly stolen from rxvt.
1262 if(attr->mode & ATTR_GFX) {
1263 if(c[0] >= 0x41 && c[0] <= 0x7e
1264 && vt100_0[c[0] - 0x41]) {
1265 c = vt100_0[c[0] - 0x41];
1270 term.line[y][x] = *attr;
1271 memcpy(term.line[y][x].c, c, UTF_SIZ);
1272 term.line[y][x].state |= GLYPH_SET;
1276 tclearregion(int x1, int y1, int x2, int y2) {
1280 temp = x1, x1 = x2, x2 = temp;
1282 temp = y1, y1 = y2, y2 = temp;
1284 LIMIT(x1, 0, term.col-1);
1285 LIMIT(x2, 0, term.col-1);
1286 LIMIT(y1, 0, term.row-1);
1287 LIMIT(y2, 0, term.row-1);
1289 for(y = y1; y <= y2; y++) {
1291 for(x = x1; x <= x2; x++)
1292 term.line[y][x].state = 0;
1297 tdeletechar(int n) {
1298 int src = term.c.x + n;
1300 int size = term.col - src;
1302 term.dirty[term.c.y] = 1;
1304 if(src >= term.col) {
1305 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1309 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1310 size * sizeof(Glyph));
1311 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1315 tinsertblank(int n) {
1318 int size = term.col - dst;
1320 term.dirty[term.c.y] = 1;
1322 if(dst >= term.col) {
1323 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1327 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1328 size * sizeof(Glyph));
1329 tclearregion(src, term.c.y, dst - 1, term.c.y);
1333 tinsertblankline(int n) {
1334 if(term.c.y < term.top || term.c.y > term.bot)
1337 tscrolldown(term.c.y, n);
1341 tdeleteline(int n) {
1342 if(term.c.y < term.top || term.c.y > term.bot)
1345 tscrollup(term.c.y, n);
1349 tsetattr(int *attr, int l) {
1352 for(i = 0; i < l; i++) {
1355 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1356 | ATTR_ITALIC | ATTR_BLINK);
1357 term.c.attr.fg = defaultfg;
1358 term.c.attr.bg = defaultbg;
1361 term.c.attr.mode |= ATTR_BOLD;
1363 case 3: /* enter standout (highlight) */
1364 term.c.attr.mode |= ATTR_ITALIC;
1367 term.c.attr.mode |= ATTR_UNDERLINE;
1370 term.c.attr.mode |= ATTR_BLINK;
1373 term.c.attr.mode |= ATTR_REVERSE;
1377 term.c.attr.mode &= ~ATTR_BOLD;
1379 case 23: /* leave standout (highlight) mode */
1380 term.c.attr.mode &= ~ATTR_ITALIC;
1383 term.c.attr.mode &= ~ATTR_UNDERLINE;
1386 term.c.attr.mode &= ~ATTR_BLINK;
1389 term.c.attr.mode &= ~ATTR_REVERSE;
1392 if(i + 2 < l && attr[i + 1] == 5) {
1394 if(BETWEEN(attr[i], 0, 255)) {
1395 term.c.attr.fg = attr[i];
1398 "erresc: bad fgcolor %d\n",
1403 "erresc(38): gfx attr %d unknown\n",
1408 term.c.attr.fg = defaultfg;
1411 if(i + 2 < l && attr[i + 1] == 5) {
1413 if(BETWEEN(attr[i], 0, 255)) {
1414 term.c.attr.bg = attr[i];
1417 "erresc: bad bgcolor %d\n",
1422 "erresc(48): gfx attr %d unknown\n",
1427 term.c.attr.bg = defaultbg;
1430 if(BETWEEN(attr[i], 30, 37)) {
1431 term.c.attr.fg = attr[i] - 30;
1432 } else if(BETWEEN(attr[i], 40, 47)) {
1433 term.c.attr.bg = attr[i] - 40;
1434 } else if(BETWEEN(attr[i], 90, 97)) {
1435 term.c.attr.fg = attr[i] - 90 + 8;
1436 } else if(BETWEEN(attr[i], 100, 107)) {
1437 term.c.attr.bg = attr[i] - 100 + 8;
1440 "erresc(default): gfx attr %d unknown\n",
1441 attr[i]), csidump();
1449 tsetscroll(int t, int b) {
1452 LIMIT(t, 0, term.row-1);
1453 LIMIT(b, 0, term.row-1);
1463 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1466 tsetmode(bool priv, bool set, int *args, int narg) {
1470 for(lim = args + narg; args < lim; ++args) {
1474 case 1: /* DECCKM -- Cursor key */
1475 MODBIT(term.mode, set, MODE_APPCURSOR);
1477 case 5: /* DECSCNM -- Reverse video */
1479 MODBIT(term.mode, set, MODE_REVERSE);
1480 if(mode != term.mode)
1483 case 6: /* DECOM -- Origin */
1484 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1487 case 7: /* DECAWM -- Auto wrap */
1488 MODBIT(term.mode, set, MODE_WRAP);
1490 case 0: /* Error (IGNORED) */
1491 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1492 case 3: /* DECCOLM -- Column (IGNORED) */
1493 case 4: /* DECSCLM -- Scroll (IGNORED) */
1494 case 8: /* DECARM -- Auto repeat (IGNORED) */
1495 case 18: /* DECPFF -- Printer feed (IGNORED) */
1496 case 19: /* DECPEX -- Printer extent (IGNORED) */
1497 case 42: /* DECNRCM -- National characters (IGNORED) */
1498 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1500 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1501 MODBIT(term.mode, !set, MODE_HIDE);
1503 case 1000: /* 1000,1002: enable xterm mouse report */
1504 MODBIT(term.mode, set, MODE_MOUSEBTN);
1507 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1509 case 1049: /* = 1047 and 1048 */
1512 alt = IS_SET(MODE_ALTSCREEN) != 0;
1514 tclearregion(0, 0, term.col-1, term.row-1);
1515 if(set ^ alt) /* set is always 1 or 0 */
1522 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1526 "erresc: unknown private set/reset mode %d\n",
1532 case 0: /* Error (IGNORED) */
1534 case 2: /* KAM -- keyboard action */
1535 MODBIT(term.mode, set, MODE_KBDLOCK);
1537 case 4: /* IRM -- Insertion-replacement */
1538 MODBIT(term.mode, set, MODE_INSERT);
1540 case 12: /* SRM -- Send/Receive */
1541 MODBIT(term.mode, !set, MODE_ECHO);
1543 case 20: /* LNM -- Linefeed/new line */
1544 MODBIT(term.mode, set, MODE_CRLF);
1548 "erresc: unknown set/reset mode %d\n",
1560 switch(csiescseq.mode) {
1563 fprintf(stderr, "erresc: unknown csi ");
1567 case '@': /* ICH -- Insert <n> blank char */
1568 DEFAULT(csiescseq.arg[0], 1);
1569 tinsertblank(csiescseq.arg[0]);
1571 case 'A': /* CUU -- Cursor <n> Up */
1572 DEFAULT(csiescseq.arg[0], 1);
1573 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1575 case 'B': /* CUD -- Cursor <n> Down */
1576 case 'e': /* VPR --Cursor <n> Down */
1577 DEFAULT(csiescseq.arg[0], 1);
1578 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1580 case 'c': /* DA -- Device Attributes */
1581 if(csiescseq.arg[0] == 0)
1582 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1584 case 'C': /* CUF -- Cursor <n> Forward */
1585 case 'a': /* HPR -- Cursor <n> Forward */
1586 DEFAULT(csiescseq.arg[0], 1);
1587 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1589 case 'D': /* CUB -- Cursor <n> Backward */
1590 DEFAULT(csiescseq.arg[0], 1);
1591 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1593 case 'E': /* CNL -- Cursor <n> Down and first col */
1594 DEFAULT(csiescseq.arg[0], 1);
1595 tmoveto(0, term.c.y+csiescseq.arg[0]);
1597 case 'F': /* CPL -- Cursor <n> Up and first col */
1598 DEFAULT(csiescseq.arg[0], 1);
1599 tmoveto(0, term.c.y-csiescseq.arg[0]);
1601 case 'g': /* TBC -- Tabulation clear */
1602 switch (csiescseq.arg[0]) {
1603 case 0: /* clear current tab stop */
1604 term.tabs[term.c.x] = 0;
1606 case 3: /* clear all the tabs */
1607 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1613 case 'G': /* CHA -- Move to <col> */
1615 DEFAULT(csiescseq.arg[0], 1);
1616 tmoveto(csiescseq.arg[0]-1, term.c.y);
1618 case 'H': /* CUP -- Move to <row> <col> */
1620 DEFAULT(csiescseq.arg[0], 1);
1621 DEFAULT(csiescseq.arg[1], 1);
1622 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1624 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1625 DEFAULT(csiescseq.arg[0], 1);
1626 while(csiescseq.arg[0]--)
1629 case 'J': /* ED -- Clear screen */
1631 switch(csiescseq.arg[0]) {
1633 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1634 if(term.c.y < term.row-1)
1635 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1639 tclearregion(0, 0, term.col-1, term.c.y-1);
1640 tclearregion(0, term.c.y, term.c.x, term.c.y);
1643 tclearregion(0, 0, term.col-1, term.row-1);
1649 case 'K': /* EL -- Clear line */
1650 switch(csiescseq.arg[0]) {
1652 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1655 tclearregion(0, term.c.y, term.c.x, term.c.y);
1658 tclearregion(0, term.c.y, term.col-1, term.c.y);
1662 case 'S': /* SU -- Scroll <n> line up */
1663 DEFAULT(csiescseq.arg[0], 1);
1664 tscrollup(term.top, csiescseq.arg[0]);
1666 case 'T': /* SD -- Scroll <n> line down */
1667 DEFAULT(csiescseq.arg[0], 1);
1668 tscrolldown(term.top, csiescseq.arg[0]);
1670 case 'L': /* IL -- Insert <n> blank lines */
1671 DEFAULT(csiescseq.arg[0], 1);
1672 tinsertblankline(csiescseq.arg[0]);
1674 case 'l': /* RM -- Reset Mode */
1675 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1677 case 'M': /* DL -- Delete <n> lines */
1678 DEFAULT(csiescseq.arg[0], 1);
1679 tdeleteline(csiescseq.arg[0]);
1681 case 'X': /* ECH -- Erase <n> char */
1682 DEFAULT(csiescseq.arg[0], 1);
1683 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1685 case 'P': /* DCH -- Delete <n> char */
1686 DEFAULT(csiescseq.arg[0], 1);
1687 tdeletechar(csiescseq.arg[0]);
1689 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1690 DEFAULT(csiescseq.arg[0], 1);
1691 while(csiescseq.arg[0]--)
1694 case 'd': /* VPA -- Move to <row> */
1695 DEFAULT(csiescseq.arg[0], 1);
1696 tmoveato(term.c.x, csiescseq.arg[0]-1);
1698 case 'h': /* SM -- Set terminal mode */
1699 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1701 case 'm': /* SGR -- Terminal attribute (color) */
1702 tsetattr(csiescseq.arg, csiescseq.narg);
1704 case 'r': /* DECSTBM -- Set Scrolling Region */
1705 if(csiescseq.priv) {
1708 DEFAULT(csiescseq.arg[0], 1);
1709 DEFAULT(csiescseq.arg[1], term.row);
1710 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1714 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1715 tcursor(CURSOR_SAVE);
1717 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1718 tcursor(CURSOR_LOAD);
1729 for(i = 0; i < csiescseq.len; i++) {
1730 c = csiescseq.buf[i] & 0xff;
1733 } else if(c == '\n') {
1735 } else if(c == '\r') {
1737 } else if(c == 0x1b) {
1740 printf("(%02x)", c);
1748 memset(&csiescseq, 0, sizeof(csiescseq));
1756 * TODO: make this being useful in case of color palette change.
1762 switch(strescseq.type) {
1763 case ']': /* OSC -- Operating System Command */
1769 * TODO: Handle special chars in string, like umlauts.
1772 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1776 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1778 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1781 fprintf(stderr, "erresc: unknown str ");
1786 case 'k': /* old title set compatibility */
1787 XStoreName(xw.dpy, xw.win, strescseq.buf);
1789 case 'P': /* DSC -- Device Control String */
1790 case '_': /* APC -- Application Program Command */
1791 case '^': /* PM -- Privacy Message */
1793 fprintf(stderr, "erresc: unknown str ");
1803 * TODO: Implement parsing like for CSI when required.
1804 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1814 printf("ESC%c", strescseq.type);
1815 for(i = 0; i < strescseq.len; i++) {
1816 c = strescseq.buf[i] & 0xff;
1819 } else if(c == '\n') {
1821 } else if(c == '\r') {
1823 } else if(c == 0x1b) {
1826 printf("(%02x)", c);
1834 memset(&strescseq, 0, sizeof(strescseq));
1838 tputtab(bool forward) {
1844 for(++x; x < term.col && !term.tabs[x]; ++x)
1849 for(--x; x > 0 && !term.tabs[x]; --x)
1852 tmoveto(x, term.c.y);
1856 techo(char *buf, int len) {
1857 for(; len > 0; buf++, len--) {
1860 if(c == '\033') { /* escape */
1863 } else if (c < '\x20') { /* control code */
1864 if(c != '\n' && c != '\r' && c != '\t') {
1878 tputc(char *c, int len) {
1880 bool control = ascii < '\x20' || ascii == 0177;
1883 if (xwrite(iofd, c, len) < 0) {
1884 fprintf(stderr, "Error writting in %s:%s\n",
1885 opt_io, strerror(errno));
1891 * STR sequences must be checked before anything else
1892 * because it can use some control codes as part of the sequence.
1894 if(term.esc & ESC_STR) {
1897 term.esc = ESC_START | ESC_STR_END;
1899 case '\a': /* backwards compatibility to xterm */
1904 strescseq.buf[strescseq.len++] = ascii;
1905 if(strescseq.len+1 >= STR_BUF_SIZ) {
1914 * Actions of control codes must be performed as soon they arrive
1915 * because they can be embedded inside a control sequence, and
1916 * they must not cause conflicts with sequences.
1924 tmoveto(term.c.x-1, term.c.y);
1927 tmoveto(0, term.c.y);
1932 /* go to first col if the mode is set */
1933 tnewline(IS_SET(MODE_CRLF));
1935 case '\a': /* BEL */
1936 if(!(xw.state & WIN_FOCUSED))
1939 case '\033': /* ESC */
1941 term.esc = ESC_START;
1943 case '\016': /* SO */
1944 term.c.attr.mode |= ATTR_GFX;
1946 case '\017': /* SI */
1947 term.c.attr.mode &= ~ATTR_GFX;
1949 case '\032': /* SUB */
1950 case '\030': /* CAN */
1953 case '\005': /* ENQ (IGNORED) */
1954 case '\000': /* NUL (IGNORED) */
1955 case '\021': /* XON (IGNORED) */
1956 case '\023': /* XOFF (IGNORED) */
1957 case 0177: /* DEL (IGNORED) */
1960 } else if(term.esc & ESC_START) {
1961 if(term.esc & ESC_CSI) {
1962 csiescseq.buf[csiescseq.len++] = ascii;
1963 if(BETWEEN(ascii, 0x40, 0x7E)
1964 || csiescseq.len >= ESC_BUF_SIZ) {
1966 csiparse(), csihandle();
1968 } else if(term.esc & ESC_STR_END) {
1972 } else if(term.esc & ESC_ALTCHARSET) {
1974 case '0': /* Line drawing set */
1975 term.c.attr.mode |= ATTR_GFX;
1977 case 'B': /* USASCII */
1978 term.c.attr.mode &= ~ATTR_GFX;
1980 case 'A': /* UK (IGNORED) */
1981 case '<': /* multinational charset (IGNORED) */
1982 case '5': /* Finnish (IGNORED) */
1983 case 'C': /* Finnish (IGNORED) */
1984 case 'K': /* German (IGNORED) */
1987 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1990 } else if(term.esc & ESC_TEST) {
1991 if(ascii == '8') { /* DEC screen alignment test. */
1992 char E[UTF_SIZ] = "E";
1995 for(x = 0; x < term.col; ++x) {
1996 for(y = 0; y < term.row; ++y)
1997 tsetchar(E, &term.c.attr, x, y);
2004 term.esc |= ESC_CSI;
2007 term.esc |= ESC_TEST;
2009 case 'P': /* DCS -- Device Control String */
2010 case '_': /* APC -- Application Program Command */
2011 case '^': /* PM -- Privacy Message */
2012 case ']': /* OSC -- Operating System Command */
2013 case 'k': /* old title set compatibility */
2015 strescseq.type = ascii;
2016 term.esc |= ESC_STR;
2018 case '(': /* set primary charset G0 */
2019 term.esc |= ESC_ALTCHARSET;
2021 case ')': /* set secondary charset G1 (IGNORED) */
2022 case '*': /* set tertiary charset G2 (IGNORED) */
2023 case '+': /* set quaternary charset G3 (IGNORED) */
2026 case 'D': /* IND -- Linefeed */
2027 if(term.c.y == term.bot) {
2028 tscrollup(term.top, 1);
2030 tmoveto(term.c.x, term.c.y+1);
2034 case 'E': /* NEL -- Next line */
2035 tnewline(1); /* always go to first col */
2038 case 'H': /* HTS -- Horizontal tab stop */
2039 term.tabs[term.c.x] = 1;
2042 case 'M': /* RI -- Reverse index */
2043 if(term.c.y == term.top) {
2044 tscrolldown(term.top, 1);
2046 tmoveto(term.c.x, term.c.y-1);
2050 case 'Z': /* DECID -- Identify Terminal */
2051 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2054 case 'c': /* RIS -- Reset to inital state */
2059 case '=': /* DECPAM -- Application keypad */
2060 term.mode |= MODE_APPKEYPAD;
2063 case '>': /* DECPNM -- Normal keypad */
2064 term.mode &= ~MODE_APPKEYPAD;
2067 case '7': /* DECSC -- Save Cursor */
2068 tcursor(CURSOR_SAVE);
2071 case '8': /* DECRC -- Restore Cursor */
2072 tcursor(CURSOR_LOAD);
2075 case '\\': /* ST -- Stop */
2079 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2080 (uchar) ascii, isprint(ascii)? ascii:'.');
2085 * All characters which forms part of a sequence are not
2091 * Display control codes only if we are in graphic mode
2093 if(control && !(term.c.attr.mode & ATTR_GFX))
2095 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2097 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
2098 tnewline(1); /* always go to first col */
2099 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2100 if(term.c.x+1 < term.col)
2101 tmoveto(term.c.x+1, term.c.y);
2103 term.c.state |= CURSOR_WRAPNEXT;
2107 tresize(int col, int row) {
2109 int minrow = MIN(row, term.row);
2110 int mincol = MIN(col, term.col);
2111 int slide = term.c.y - row + 1;
2114 if(col < 1 || row < 1)
2117 /* free unneeded rows */
2120 /* slide screen to keep cursor where we expect it -
2121 * tscrollup would work here, but we can optimize to
2122 * memmove because we're freeing the earlier lines */
2123 for(/* i = 0 */; i < slide; i++) {
2127 memmove(term.line, term.line + slide, row * sizeof(Line));
2128 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2130 for(i += row; i < term.row; i++) {
2135 /* resize to new height */
2136 term.line = xrealloc(term.line, row * sizeof(Line));
2137 term.alt = xrealloc(term.alt, row * sizeof(Line));
2138 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2139 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2141 /* resize each row to new width, zero-pad if needed */
2142 for(i = 0; i < minrow; i++) {
2144 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2145 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2146 for(x = mincol; x < col; x++) {
2147 term.line[i][x].state = 0;
2148 term.alt[i][x].state = 0;
2152 /* allocate any new rows */
2153 for(/* i == minrow */; i < row; i++) {
2155 term.line[i] = xcalloc(col, sizeof(Glyph));
2156 term.alt [i] = xcalloc(col, sizeof(Glyph));
2158 if(col > term.col) {
2159 bp = term.tabs + term.col;
2161 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2162 while(--bp > term.tabs && !*bp)
2164 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2167 /* update terminal size */
2170 /* reset scrolling region */
2171 tsetscroll(0, row-1);
2172 /* make use of the LIMIT in tmoveto */
2173 tmoveto(term.c.x, term.c.y);
2179 xresize(int col, int row) {
2180 xw.tw = MAX(1, 2*borderpx + col * xw.cw);
2181 xw.th = MAX(1, 2*borderpx + row * xw.ch);
2183 XftDrawChange(xw.draw, xw.buf);
2189 XRenderColor color = { .alpha = 0 };
2191 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2192 for(i = 0; i < LEN(colorname); i++) {
2195 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2196 die("Could not allocate color '%s'\n", colorname[i]);
2200 /* load colors [16-255] ; same colors as xterm */
2201 for(i = 16, r = 0; r < 6; r++) {
2202 for(g = 0; g < 6; g++) {
2203 for(b = 0; b < 6; b++) {
2204 color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
2205 color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
2206 color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
2207 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2208 die("Could not allocate color %d\n", i);
2215 for(r = 0; r < 24; r++, i++) {
2216 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2217 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2219 die("Could not allocate color %d\n", i);
2225 xtermclear(int col1, int row1, int col2, int row2) {
2226 XftDrawRect(xw.draw,
2227 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2228 borderpx + col1 * xw.cw,
2229 borderpx + row1 * xw.ch,
2230 (col2-col1+1) * xw.cw,
2231 (row2-row1+1) * xw.ch);
2235 * Absolute coordinates.
2238 xclear(int x1, int y1, int x2, int y2) {
2239 XftDrawRect(xw.draw,
2240 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2241 x1, y1, x2-x1, y2-y1);
2246 XClassHint class = {opt_class ? opt_class : termname, termname};
2247 XWMHints wm = {.flags = InputHint, .input = 1};
2248 XSizeHints *sizeh = NULL;
2250 sizeh = XAllocSizeHints();
2251 if(xw.isfixed == False) {
2252 sizeh->flags = PSize | PResizeInc | PBaseSize;
2253 sizeh->height = xw.h;
2254 sizeh->width = xw.w;
2255 sizeh->height_inc = xw.ch;
2256 sizeh->width_inc = xw.cw;
2257 sizeh->base_height = 2*borderpx;
2258 sizeh->base_width = 2*borderpx;
2260 sizeh->flags = PMaxSize | PMinSize;
2261 sizeh->min_width = sizeh->max_width = xw.fw;
2262 sizeh->min_height = sizeh->max_height = xw.fh;
2265 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2270 xloadfont(Font *f, FcPattern *pattern) {
2274 match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
2277 if(!(f->set = XftFontOpenPattern(xw.dpy, match))) {
2278 FcPatternDestroy(match);
2282 f->ascent = f->set->ascent;
2283 f->descent = f->set->descent;
2285 f->rbearing = f->set->max_advance_width;
2287 f->height = f->set->height;
2288 f->width = f->lbearing + f->rbearing;
2294 xloadfonts(char *fontstr, int fontsize) {
2299 if(fontstr[0] == '-') {
2300 pattern = XftXlfdParse(fontstr, False, False);
2302 pattern = FcNameParse((FcChar8 *)fontstr);
2306 die("st: can't open font %s\n", fontstr);
2309 FcPatternDel(pattern, FC_PIXEL_SIZE);
2310 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2311 usedfontsize = fontsize;
2313 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2314 if(result == FcResultMatch) {
2315 usedfontsize = (int)fontval;
2318 * Default font size is 12, if none given. This is to
2319 * have a known usedfontsize value.
2321 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2326 if(xloadfont(&dc.font, pattern))
2327 die("st: can't open font %s\n", fontstr);
2329 /* Setting character width and height. */
2330 xw.cw = dc.font.width;
2331 xw.ch = dc.font.height;
2333 FcPatternDel(pattern, FC_WEIGHT);
2334 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2335 if(xloadfont(&dc.bfont, pattern))
2336 die("st: can't open font %s\n", fontstr);
2338 FcPatternDel(pattern, FC_SLANT);
2339 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2340 if(xloadfont(&dc.ibfont, pattern))
2341 die("st: can't open font %s\n", fontstr);
2343 FcPatternDel(pattern, FC_WEIGHT);
2344 if(xloadfont(&dc.ifont, pattern))
2345 die("st: can't open font %s\n", fontstr);
2347 FcPatternDestroy(pattern);
2351 xzoom(const Arg *arg)
2353 xloadfonts(usedfont, usedfontsize + arg->i);
2360 XSetWindowAttributes attrs;
2363 int sw, sh, major, minor;
2365 if(!(xw.dpy = XOpenDisplay(NULL)))
2366 die("Can't open display\n");
2367 xw.scr = XDefaultScreen(xw.dpy);
2368 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2371 usedfont = (opt_font == NULL)? font : opt_font;
2372 xloadfonts(usedfont, 0);
2375 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2378 /* adjust fixed window geometry */
2380 sw = DisplayWidth(xw.dpy, xw.scr);
2381 sh = DisplayHeight(xw.dpy, xw.scr);
2383 xw.fx = sw + xw.fx - xw.fw - 1;
2385 xw.fy = sh + xw.fy - xw.fh - 1;
2390 /* window - default size */
2391 xw.h = 2*borderpx + term.row * xw.ch;
2392 xw.w = 2*borderpx + term.col * xw.cw;
2397 attrs.background_pixel = dc.col[defaultbg].pixel;
2398 attrs.border_pixel = dc.col[defaultbg].pixel;
2399 attrs.bit_gravity = NorthWestGravity;
2400 attrs.event_mask = FocusChangeMask | KeyPressMask
2401 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2402 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2403 attrs.colormap = xw.cmap;
2405 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2406 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2407 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2409 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2413 /* double buffering */
2414 if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2415 die("Xdbe extension is not present\n");
2416 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2418 /* Xft rendering context */
2419 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2422 xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2423 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2424 | XIMStatusNothing, XNClientWindow, xw.win,
2425 XNFocusWindow, xw.win, NULL);
2427 /* white cursor, black outline */
2428 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2429 XDefineCursor(xw.dpy, xw.win, cursor);
2430 XRecolorCursor(xw.dpy, cursor,
2431 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2432 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2434 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2435 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2436 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2439 XMapWindow(xw.dpy, xw.win);
2445 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2446 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2447 width = charlen * xw.cw;
2448 Font *font = &dc.font;
2450 Colour *fg = &dc.col[base.fg], *bg = &dc.col[base.bg],
2451 *temp, revfg, revbg;
2452 XRenderColor colfg, colbg;
2454 if(base.mode & ATTR_BOLD) {
2455 if(BETWEEN(base.fg, 0, 7)) {
2456 /* basic system colors */
2457 fg = &dc.col[base.fg + 8];
2458 } else if(BETWEEN(base.fg, 16, 195)) {
2460 fg = &dc.col[base.fg + 36];
2461 } else if(BETWEEN(base.fg, 232, 251)) {
2463 fg = &dc.col[base.fg + 4];
2466 * Those ranges will not be brightened:
2467 * 8 - 15 – bright system colors
2468 * 196 - 231 – highest 256 color cube
2469 * 252 - 255 – brightest colors in greyscale
2474 if(base.mode & ATTR_ITALIC)
2476 if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD))
2479 if(IS_SET(MODE_REVERSE)) {
2480 if(fg == &dc.col[defaultfg]) {
2481 fg = &dc.col[defaultbg];
2483 colfg.red = ~fg->color.red;
2484 colfg.green = ~fg->color.green;
2485 colfg.blue = ~fg->color.blue;
2486 colfg.alpha = fg->color.alpha;
2487 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2491 if(bg == &dc.col[defaultbg]) {
2492 bg = &dc.col[defaultfg];
2494 colbg.red = ~bg->color.red;
2495 colbg.green = ~bg->color.green;
2496 colbg.blue = ~bg->color.blue;
2497 colbg.alpha = bg->color.alpha;
2498 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2503 if(base.mode & ATTR_REVERSE)
2504 temp = fg, fg = bg, bg = temp;
2506 XftTextExtentsUtf8(xw.dpy, font->set, (FcChar8 *)s, bytelen,
2508 width = extents.xOff;
2510 /* Intelligent cleaning up of the borders. */
2512 xclear(0, (y == 0)? 0 : winy, borderpx,
2513 winy + xw.ch + (y == term.row-1)? xw.h : 0);
2515 if(x + charlen >= term.col-1) {
2516 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2517 (y == term.row-1)? xw.h : (winy + xw.ch));
2520 xclear(winx, 0, winx + width, borderpx);
2522 xclear(winx, winy + xw.ch, winx + width, xw.h);
2524 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
2525 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
2526 winy + font->ascent, (FcChar8 *)s, bytelen);
2528 if(base.mode & ATTR_UNDERLINE) {
2529 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
2536 static int oldx = 0, oldy = 0;
2538 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs, 0};
2540 LIMIT(oldx, 0, term.col-1);
2541 LIMIT(oldy, 0, term.row-1);
2543 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2544 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2546 /* remove the old cursor */
2547 if(term.line[oldy][oldx].state & GLYPH_SET) {
2548 sl = utf8size(term.line[oldy][oldx].c);
2549 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2552 xtermclear(oldx, oldy, oldx, oldy);
2555 /* draw the new one */
2556 if(!(IS_SET(MODE_HIDE))) {
2557 if(!(xw.state & WIN_FOCUSED))
2560 if(IS_SET(MODE_REVERSE))
2561 g.mode |= ATTR_REVERSE, g.fg = defaultcs, g.bg = defaultfg;
2564 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2565 oldx = term.c.x, oldy = term.c.y;
2571 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2576 struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2580 XSync(xw.dpy, False); /* necessary for a good tput flash */
2581 nanosleep(&tv, NULL);
2586 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2588 drawregion(0, 0, term.col, term.row);
2589 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2593 drawregion(int x1, int y1, int x2, int y2) {
2594 int ic, ib, x, y, ox, sl;
2596 char buf[DRAW_BUF_SIZ];
2597 bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN) != 0;
2599 if((sel.alt != 0) ^ alt)
2601 if(!(xw.state & WIN_VISIBLE))
2604 for(y = y1; y < y2; y++) {
2608 xtermclear(0, y, term.col, y);
2610 base = term.line[y][0];
2612 for(x = x1; x < x2; x++) {
2613 new = term.line[y][x];
2614 if(ena_sel && *(new.c) && selected(x, y))
2615 new.mode ^= ATTR_REVERSE;
2616 if(ib > 0 && (!(new.state & GLYPH_SET)
2617 || ATTRCMP(base, new)
2618 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2619 xdraws(buf, base, ox, y, ic, ib);
2622 if(new.state & GLYPH_SET) {
2627 sl = utf8size(new.c);
2628 memcpy(buf+ib, new.c, sl);
2634 xdraws(buf, base, ox, y, ic, ib);
2640 expose(XEvent *ev) {
2641 XExposeEvent *e = &ev->xexpose;
2643 if(xw.state & WIN_REDRAW) {
2645 xw.state &= ~WIN_REDRAW;
2650 visibility(XEvent *ev) {
2651 XVisibilityEvent *e = &ev->xvisibility;
2653 if(e->state == VisibilityFullyObscured) {
2654 xw.state &= ~WIN_VISIBLE;
2655 } else if(!(xw.state & WIN_VISIBLE)) {
2656 /* need a full redraw for next Expose, not just a buf copy */
2657 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2663 xw.state &= ~WIN_VISIBLE;
2667 xseturgency(int add) {
2668 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2670 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2671 XSetWMHints(xw.dpy, xw.win, h);
2677 if(ev->type == FocusIn) {
2678 XSetICFocus(xw.xic);
2679 xw.state |= WIN_FOCUSED;
2682 XUnsetICFocus(xw.xic);
2683 xw.state &= ~WIN_FOCUSED;
2688 kmap(KeySym k, uint state) {
2693 for(i = 0; i < LEN(key); i++) {
2696 if(key[i].k == k && ((state & mask) == mask
2697 || (mask == XK_NO_MOD && !state))) {
2698 return (char*)key[i].s;
2705 kpress(XEvent *ev) {
2706 XKeyEvent *e = &ev->xkey;
2708 char xstr[31], buf[32], *customkey, *cp = buf;
2709 int len, meta, shift, i;
2712 if (IS_SET(MODE_KBDLOCK))
2715 meta = e->state & Mod1Mask;
2716 shift = e->state & ShiftMask;
2717 len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
2720 for(i = 0; i < LEN(shortcuts); i++) {
2721 if((ksym == shortcuts[i].keysym)
2722 && (CLEANMASK(shortcuts[i].mod) == \
2723 CLEANMASK(e->state))
2724 && shortcuts[i].func) {
2725 shortcuts[i].func(&(shortcuts[i].arg));
2729 /* 2. custom keys from config.h */
2730 if((customkey = kmap(ksym, e->state))) {
2731 len = strlen(customkey);
2732 memcpy(buf, customkey, len);
2733 /* 2. hardcoded (overrides X lookup) */
2740 /* XXX: shift up/down doesn't work */
2741 sprintf(buf, "\033%c%c",
2742 IS_SET(MODE_APPKEYPAD) ? 'O' : '[',
2743 (shift ? "dacb":"DACB")[ksym - XK_Left]);
2751 memcpy(buf, xstr, len);
2756 *cp++ = '\033', len++;
2758 *cp++ = '\r', len++;
2760 if(IS_SET(MODE_CRLF))
2768 if (len == 1 && meta)
2771 memcpy(cp, xstr, len);
2772 len = cp - buf + len;
2777 if(IS_SET(MODE_ECHO))
2783 cmessage(XEvent *e) {
2785 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2786 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2787 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2788 xw.state |= WIN_FOCUSED;
2790 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2791 xw.state &= ~WIN_FOCUSED;
2793 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
2794 /* Send SIGHUP to shell */
2801 cresize(int width, int height)
2810 col = (xw.w - 2*borderpx) / xw.cw;
2811 row = (xw.h - 2*borderpx) / xw.ch;
2820 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2823 cresize(e->xconfigure.width, e->xconfigure.height);
2830 int xfd = XConnectionNumber(xw.dpy), i;
2831 struct timeval drawtimeout, *tv = NULL;
2835 FD_SET(cmdfd, &rfd);
2837 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2840 die("select failed: %s\n", SERRNO);
2844 * Stop after a certain number of reads so the user does not
2845 * feel like the system is stuttering.
2847 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2851 * Just wait a bit so it isn't disturbing the
2852 * user and the system is able to write something.
2854 drawtimeout.tv_sec = 0;
2855 drawtimeout.tv_usec = 5;
2862 while(XPending(xw.dpy)) {
2863 XNextEvent(xw.dpy, &ev);
2864 if(XFilterEvent(&ev, None))
2866 if(handler[ev.type])
2867 (handler[ev.type])(&ev);
2876 main(int argc, char *argv[]) {
2877 int i, bitm, xr, yr;
2880 xw.fw = xw.fh = xw.fx = xw.fy = 0;
2883 for(i = 1; i < argc; i++) {
2884 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2887 opt_class = argv[i];
2890 /* eat every remaining arguments */
2902 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2907 if(bitm & WidthValue)
2909 if(bitm & HeightValue)
2911 if(bitm & XNegative && xw.fx == 0)
2913 if(bitm & XNegative && xw.fy == 0)
2916 if(xw.fh != 0 && xw.fw != 0)
2925 opt_title = argv[i];
2932 opt_embed = argv[i];
2938 setlocale(LC_CTYPE, "");
2939 XSetLocaleModifiers("");