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)
76 #define VT102ID "\033[?6c"
78 enum glyph_attribute {
88 enum cursor_movement {
115 MODE_MOUSEMOTION = 64,
125 ESC_STR = 4, /* DSC, OSC, PM, APC */
127 ESC_STR_END = 16, /* a final string was encountered */
128 ESC_TEST = 32, /* Enter in test mode */
139 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
141 typedef unsigned char uchar;
142 typedef unsigned int uint;
143 typedef unsigned long ulong;
144 typedef unsigned short ushort;
147 char c[UTF_SIZ]; /* character code */
148 uchar mode; /* attribute flags */
149 ushort fg; /* foreground */
150 ushort bg; /* background */
151 uchar state; /* state flags */
157 Glyph attr; /* current char attributes */
163 /* CSI Escape sequence structs */
164 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
166 char buf[ESC_BUF_SIZ]; /* raw string */
167 int len; /* raw string length */
169 int arg[ESC_ARG_SIZ];
170 int narg; /* nb of args */
174 /* STR Escape sequence structs */
175 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
177 char type; /* ESC type ... */
178 char buf[STR_BUF_SIZ]; /* raw string */
179 int len; /* raw string length */
180 char *args[STR_ARG_SIZ];
181 int narg; /* nb of args */
184 /* Internal representation of the screen */
186 int row; /* nb row */
187 int col; /* nb col */
188 Line *line; /* screen */
189 Line *alt; /* alternate screen */
190 bool *dirty; /* dirtyness of lines */
191 TCursor c; /* cursor */
192 int top; /* top scroll limit */
193 int bot; /* bottom scroll limit */
194 int mode; /* terminal mode flags */
195 int esc; /* escape state flags */
199 /* Purely graphic info */
205 Atom xembed, wmdeletewin;
211 bool isfixed; /* is fixed geometry? */
212 int fx, fy, fw, fh; /* fixed geometry */
213 int tw, th; /* tty width and height */
214 int w; /* window width */
215 int h; /* window height */
216 int ch; /* char height */
217 int cw; /* char width */
218 char state; /* focus, redraw, visible */
227 /* TODO: use better name for vars... */
238 struct timeval tclick1;
239 struct timeval tclick2;
252 void (*func)(const Arg *);
256 /* function definitions used in config.h */
257 static void xzoom(const Arg *);
259 /* Config.h for applying patches and the configuration. */
273 /* Drawing Context */
275 XftColor xft_col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
277 Font font, bfont, ifont, ibfont;
280 static void die(const char *, ...);
281 static void draw(void);
282 static void redraw(void);
283 static void drawregion(int, int, int, int);
284 static void execsh(void);
285 static void sigchld(int);
286 static void run(void);
288 static void csidump(void);
289 static void csihandle(void);
290 static void csiparse(void);
291 static void csireset(void);
292 static void strdump(void);
293 static void strhandle(void);
294 static void strparse(void);
295 static void strreset(void);
297 static void tclearregion(int, int, int, int);
298 static void tcursor(int);
299 static void tdeletechar(int);
300 static void tdeleteline(int);
301 static void tinsertblank(int);
302 static void tinsertblankline(int);
303 static void tmoveto(int, int);
304 static void tmoveato(int x, int y);
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;
590 return LIMIT(x, 0, term.col-1);
598 return LIMIT(y, 0, term.row-1);
602 selected(int x, int y) {
605 if(sel.ey == y && sel.by == y) {
606 bx = MIN(sel.bx, sel.ex);
607 ex = MAX(sel.bx, sel.ex);
608 return BETWEEN(x, bx, ex);
611 return ((sel.b.y < y && y < sel.e.y)
612 || (y == sel.e.y && x <= sel.e.x))
613 || (y == sel.b.y && x >= sel.b.x
614 && (x <= sel.e.x || sel.b.y != sel.e.y));
618 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
620 *b = e->xbutton.button;
622 *x = x2col(e->xbutton.x);
623 *y = y2row(e->xbutton.y);
625 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
626 sel.b.y = MIN(sel.by, sel.ey);
627 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
628 sel.e.y = MAX(sel.by, sel.ey);
632 mousereport(XEvent *e) {
633 int x = x2col(e->xbutton.x);
634 int y = y2row(e->xbutton.y);
635 int button = e->xbutton.button;
636 int state = e->xbutton.state;
637 char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
638 static int ob, ox, oy;
641 if(e->xbutton.type == MotionNotify) {
642 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
646 } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
652 if(e->xbutton.type == ButtonPress) {
658 buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
659 + (state & Mod4Mask ? 8 : 0)
660 + (state & ControlMask ? 16 : 0);
662 ttywrite(buf, sizeof(buf));
667 if(IS_SET(MODE_MOUSE)) {
669 } else if(e->xbutton.button == Button1) {
672 tsetdirt(sel.b.y, sel.e.y);
676 sel.ex = sel.bx = x2col(e->xbutton.x);
677 sel.ey = sel.by = y2row(e->xbutton.y);
678 } else if(e->xbutton.button == Button4) {
680 } else if(e->xbutton.button == Button5) {
688 int x, y, bufsize, is_selected = 0, size;
694 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
695 ptr = str = xmalloc(bufsize);
697 /* append every set & selected glyph to the selection */
698 for(y = 0; y < term.row; y++) {
699 gp = &term.line[y][0];
700 last = gp + term.col;
702 while(--last >= gp && !(last->state & GLYPH_SET))
705 for(x = 0; gp <= last; x++, ++gp) {
706 if(!(is_selected = selected(x, y)))
709 p = (gp->state & GLYPH_SET) ? gp->c : " ";
711 memcpy(ptr, p, size);
714 /* \n at the end of every selected line except for the last one */
715 if(is_selected && y < sel.e.y)
720 sel.alt = IS_SET(MODE_ALTSCREEN);
725 selnotify(XEvent *e) {
726 ulong nitems, ofs, rem;
733 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
734 False, AnyPropertyType, &type, &format,
735 &nitems, &rem, &data)) {
736 fprintf(stderr, "Clipboard allocation failed\n");
739 ttywrite((const char *) data, nitems * format / 8);
741 /* number of 32-bit chunks returned */
742 ofs += nitems * format / 32;
748 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
749 xw.win, CurrentTime);
752 void selclear(XEvent *e) {
756 tsetdirt(sel.b.y, sel.e.y);
760 selrequest(XEvent *e) {
761 XSelectionRequestEvent *xsre;
763 Atom xa_targets, string;
765 xsre = (XSelectionRequestEvent *) e;
766 xev.type = SelectionNotify;
767 xev.requestor = xsre->requestor;
768 xev.selection = xsre->selection;
769 xev.target = xsre->target;
770 xev.time = xsre->time;
774 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
775 if(xsre->target == xa_targets) {
776 /* respond with the supported type */
777 string = sel.xtarget;
778 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
779 XA_ATOM, 32, PropModeReplace,
780 (uchar *) &string, 1);
781 xev.property = xsre->property;
782 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
783 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
784 xsre->target, 8, PropModeReplace,
785 (uchar *) sel.clip, strlen(sel.clip));
786 xev.property = xsre->property;
789 /* all done, send a notification to the listener */
790 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
791 fprintf(stderr, "Error sending SelectionNotify event\n");
796 /* register the selection for both the clipboard and the primary */
802 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
804 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
805 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
809 brelease(XEvent *e) {
812 if(IS_SET(MODE_MOUSE)) {
817 if(e->xbutton.button == Button2) {
819 } else if(e->xbutton.button == Button1) {
821 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
822 term.dirty[sel.ey] = 1;
823 if(sel.bx == sel.ex && sel.by == sel.ey) {
825 gettimeofday(&now, NULL);
827 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
828 /* triple click on the line */
829 sel.b.x = sel.bx = 0;
830 sel.e.x = sel.ex = term.col;
831 sel.b.y = sel.e.y = sel.ey;
833 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
834 /* double click to select word */
836 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
837 term.line[sel.ey][sel.bx-1].c[0] != ' ') {
841 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
842 term.line[sel.ey][sel.ex+1].c[0] != ' ') {
846 sel.b.y = sel.e.y = sel.ey;
854 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
855 gettimeofday(&sel.tclick1, NULL);
860 int starty, endy, oldey, oldex;
862 if(IS_SET(MODE_MOUSE)) {
870 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
872 if(oldey != sel.ey || oldex != sel.ex) {
873 starty = MIN(oldey, sel.ey);
874 endy = MAX(oldey, sel.ey);
875 tsetdirt(starty, endy);
881 die(const char *errstr, ...) {
884 va_start(ap, errstr);
885 vfprintf(stderr, errstr, ap);
893 char *envshell = getenv("SHELL");
894 const struct passwd *pass = getpwuid(getuid());
895 char buf[sizeof(long) * 8 + 1];
902 setenv("LOGNAME", pass->pw_name, 1);
903 setenv("USER", pass->pw_name, 1);
904 setenv("SHELL", pass->pw_shell, 0);
905 setenv("HOME", pass->pw_dir, 0);
908 snprintf(buf, sizeof(buf), "%lu", xw.win);
909 setenv("WINDOWID", buf, 1);
911 signal(SIGCHLD, SIG_DFL);
912 signal(SIGHUP, SIG_DFL);
913 signal(SIGINT, SIG_DFL);
914 signal(SIGQUIT, SIG_DFL);
915 signal(SIGTERM, SIG_DFL);
916 signal(SIGALRM, SIG_DFL);
918 DEFAULT(envshell, shell);
919 setenv("TERM", termname, 1);
920 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
921 execvp(args[0], args);
929 if(waitpid(pid, &stat, 0) < 0)
930 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
932 if(WIFEXITED(stat)) {
933 exit(WEXITSTATUS(stat));
942 struct winsize w = {term.row, term.col, 0, 0};
944 /* seems to work fine on linux, openbsd and freebsd */
945 if(openpty(&m, &s, NULL, NULL, &w) < 0)
946 die("openpty failed: %s\n", SERRNO);
948 switch(pid = fork()) {
950 die("fork failed\n");
953 setsid(); /* create a new process group */
954 dup2(s, STDIN_FILENO);
955 dup2(s, STDOUT_FILENO);
956 dup2(s, STDERR_FILENO);
957 if(ioctl(s, TIOCSCTTY, NULL) < 0)
958 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
966 signal(SIGCHLD, sigchld);
968 iofd = (!strcmp(opt_io, "-")) ?
970 open(opt_io, O_WRONLY | O_CREAT, 0666);
972 fprintf(stderr, "Error opening %s:%s\n",
973 opt_io, strerror(errno));
983 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
985 fprintf(stderr, "\n");
990 static char buf[BUFSIZ];
991 static int buflen = 0;
994 int charsize; /* size of utf8 char in bytes */
998 /* append read bytes to unprocessed bytes */
999 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1000 die("Couldn't read from shell: %s\n", SERRNO);
1002 /* process every complete utf8 char */
1005 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1006 charsize = utf8decode(ptr, &utf8c);
1007 utf8encode(&utf8c, s);
1013 /* keep any uncomplete utf8 char for the next call */
1014 memmove(buf, ptr, buflen);
1018 ttywrite(const char *s, size_t n) {
1019 if(write(cmdfd, s, n) == -1)
1020 die("write error on tty: %s\n", SERRNO);
1027 w.ws_row = term.row;
1028 w.ws_col = term.col;
1029 w.ws_xpixel = xw.tw;
1030 w.ws_ypixel = xw.th;
1031 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1032 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1036 tsetdirt(int top, int bot) {
1039 LIMIT(top, 0, term.row-1);
1040 LIMIT(bot, 0, term.row-1);
1042 for(i = top; i <= bot; i++)
1048 tsetdirt(0, term.row-1);
1055 if(mode == CURSOR_SAVE) {
1057 } else if(mode == CURSOR_LOAD) {
1067 term.c = (TCursor){{
1071 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1073 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1074 for(i = tabspaces; i < term.col; i += tabspaces)
1077 term.bot = term.row - 1;
1078 term.mode = MODE_WRAP;
1080 tclearregion(0, 0, term.col-1, term.row-1);
1082 tcursor(CURSOR_SAVE);
1086 tnew(int col, int row) {
1087 /* set screen size */
1090 term.line = xmalloc(term.row * sizeof(Line));
1091 term.alt = xmalloc(term.row * sizeof(Line));
1092 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1093 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1095 for(row = 0; row < term.row; row++) {
1096 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1097 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1098 term.dirty[row] = 0;
1100 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1107 Line *tmp = term.line;
1109 term.line = term.alt;
1111 term.mode ^= MODE_ALTSCREEN;
1116 tscrolldown(int orig, int n) {
1120 LIMIT(n, 0, term.bot-orig+1);
1122 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1124 for(i = term.bot; i >= orig+n; i--) {
1125 temp = term.line[i];
1126 term.line[i] = term.line[i-n];
1127 term.line[i-n] = temp;
1130 term.dirty[i-n] = 1;
1137 tscrollup(int orig, int n) {
1140 LIMIT(n, 0, term.bot-orig+1);
1142 tclearregion(0, orig, term.col-1, orig+n-1);
1144 for(i = orig; i <= term.bot-n; i++) {
1145 temp = term.line[i];
1146 term.line[i] = term.line[i+n];
1147 term.line[i+n] = temp;
1150 term.dirty[i+n] = 1;
1153 selscroll(orig, -n);
1157 selscroll(int orig, int n) {
1161 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1162 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1166 if(sel.by < term.top) {
1170 if(sel.ey > term.bot) {
1174 sel.b.y = sel.by, sel.b.x = sel.bx;
1175 sel.e.y = sel.ey, sel.e.x = sel.ex;
1180 tnewline(int first_col) {
1184 tscrollup(term.top, 1);
1188 tmoveto(first_col ? 0 : term.c.x, y);
1193 /* int noarg = 1; */
1194 char *p = csiescseq.buf;
1198 csiescseq.priv = 1, p++;
1200 while(p < csiescseq.buf+csiescseq.len) {
1201 while(isdigit(*p)) {
1202 csiescseq.arg[csiescseq.narg] *= 10;
1203 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1205 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1206 csiescseq.narg++, p++;
1208 csiescseq.mode = *p;
1216 /* for absolute user moves, when decom is set */
1218 tmoveato(int x, int y) {
1219 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1223 tmoveto(int x, int y) {
1226 if(term.c.state & CURSOR_ORIGIN) {
1231 maxy = term.row - 1;
1233 LIMIT(x, 0, term.col-1);
1234 LIMIT(y, miny, maxy);
1235 term.c.state &= ~CURSOR_WRAPNEXT;
1241 tsetchar(char *c, Glyph *attr, int x, int y) {
1242 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1243 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1244 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1245 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1246 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1247 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1248 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1249 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1250 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1254 * The table is proudly stolen from rxvt.
1256 if(attr->mode & ATTR_GFX) {
1257 if(c[0] >= 0x41 && c[0] <= 0x7e
1258 && vt100_0[c[0] - 0x41]) {
1259 c = vt100_0[c[0] - 0x41];
1264 term.line[y][x] = *attr;
1265 memcpy(term.line[y][x].c, c, UTF_SIZ);
1266 term.line[y][x].state |= GLYPH_SET;
1270 tclearregion(int x1, int y1, int x2, int y2) {
1274 temp = x1, x1 = x2, x2 = temp;
1276 temp = y1, y1 = y2, y2 = temp;
1278 LIMIT(x1, 0, term.col-1);
1279 LIMIT(x2, 0, term.col-1);
1280 LIMIT(y1, 0, term.row-1);
1281 LIMIT(y2, 0, term.row-1);
1283 for(y = y1; y <= y2; y++) {
1285 for(x = x1; x <= x2; x++)
1286 term.line[y][x].state = 0;
1291 tdeletechar(int n) {
1292 int src = term.c.x + n;
1294 int size = term.col - src;
1296 term.dirty[term.c.y] = 1;
1298 if(src >= term.col) {
1299 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1303 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1304 size * sizeof(Glyph));
1305 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1309 tinsertblank(int n) {
1312 int size = term.col - dst;
1314 term.dirty[term.c.y] = 1;
1316 if(dst >= term.col) {
1317 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1321 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1322 size * sizeof(Glyph));
1323 tclearregion(src, term.c.y, dst - 1, term.c.y);
1327 tinsertblankline(int n) {
1328 if(term.c.y < term.top || term.c.y > term.bot)
1331 tscrolldown(term.c.y, n);
1335 tdeleteline(int n) {
1336 if(term.c.y < term.top || term.c.y > term.bot)
1339 tscrollup(term.c.y, n);
1343 tsetattr(int *attr, int l) {
1346 for(i = 0; i < l; i++) {
1349 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1350 | ATTR_ITALIC | ATTR_BLINK);
1351 term.c.attr.fg = defaultfg;
1352 term.c.attr.bg = defaultbg;
1355 term.c.attr.mode |= ATTR_BOLD;
1357 case 3: /* enter standout (highlight) */
1358 term.c.attr.mode |= ATTR_ITALIC;
1361 term.c.attr.mode |= ATTR_UNDERLINE;
1364 term.c.attr.mode |= ATTR_BLINK;
1367 term.c.attr.mode |= ATTR_REVERSE;
1371 term.c.attr.mode &= ~ATTR_BOLD;
1373 case 23: /* leave standout (highlight) mode */
1374 term.c.attr.mode &= ~ATTR_ITALIC;
1377 term.c.attr.mode &= ~ATTR_UNDERLINE;
1380 term.c.attr.mode &= ~ATTR_BLINK;
1383 term.c.attr.mode &= ~ATTR_REVERSE;
1386 if(i + 2 < l && attr[i + 1] == 5) {
1388 if(BETWEEN(attr[i], 0, 255)) {
1389 term.c.attr.fg = attr[i];
1392 "erresc: bad fgcolor %d\n",
1397 "erresc(38): gfx attr %d unknown\n",
1402 term.c.attr.fg = defaultfg;
1405 if(i + 2 < l && attr[i + 1] == 5) {
1407 if(BETWEEN(attr[i], 0, 255)) {
1408 term.c.attr.bg = attr[i];
1411 "erresc: bad bgcolor %d\n",
1416 "erresc(48): gfx attr %d unknown\n",
1421 term.c.attr.bg = defaultbg;
1424 if(BETWEEN(attr[i], 30, 37)) {
1425 term.c.attr.fg = attr[i] - 30;
1426 } else if(BETWEEN(attr[i], 40, 47)) {
1427 term.c.attr.bg = attr[i] - 40;
1428 } else if(BETWEEN(attr[i], 90, 97)) {
1429 term.c.attr.fg = attr[i] - 90 + 8;
1430 } else if(BETWEEN(attr[i], 100, 107)) {
1431 term.c.attr.bg = attr[i] - 100 + 8;
1434 "erresc(default): gfx attr %d unknown\n",
1435 attr[i]), csidump();
1443 tsetscroll(int t, int b) {
1446 LIMIT(t, 0, term.row-1);
1447 LIMIT(b, 0, term.row-1);
1457 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1460 tsetmode(bool priv, bool set, int *args, int narg) {
1463 for(lim = args + narg; args < lim; ++args) {
1467 case 1: /* DECCKM -- Cursor key */
1468 MODBIT(term.mode, set, MODE_APPKEYPAD);
1470 case 5: /* DECSCNM -- Reverse video */
1472 MODBIT(term.mode, set, MODE_REVERSE);
1473 if(mode != term.mode)
1476 case 6: /* DECOM -- Origin */
1477 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1480 case 7: /* DECAWM -- Auto wrap */
1481 MODBIT(term.mode, set, MODE_WRAP);
1483 case 8: /* DECARM -- Auto repeat (IGNORED) */
1484 case 0: /* Error (IGNORED) */
1485 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1487 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1488 MODBIT(term.mode, !set, MODE_HIDE);
1490 case 1000: /* 1000,1002: enable xterm mouse report */
1491 MODBIT(term.mode, set, MODE_MOUSEBTN);
1494 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1496 case 1049: /* = 1047 and 1048 */
1499 bool alt = IS_SET(MODE_ALTSCREEN) != 0;
1501 tclearregion(0, 0, term.col-1, term.row-1);
1502 if(set ^ alt) /* set is always 1 or 0 */
1509 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1512 /* case 2: DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
1513 /* case 3: DECCOLM -- Column (NOT SUPPORTED) */
1514 /* case 4: DECSCLM -- Scroll (NOT SUPPORTED) */
1515 /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
1516 /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
1517 /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
1519 "erresc: unknown private set/reset mode %d\n",
1525 case 0: /* Error (IGNORED) */
1527 case 2: /* KAM -- keyboard action */
1528 MODBIT(term.mode, set, MODE_KBDLOCK);
1530 case 4: /* IRM -- Insertion-replacement */
1531 MODBIT(term.mode, set, MODE_INSERT);
1533 case 12: /* XXX: SRM -- Send/Receive */
1535 case 20: /* LNM -- Linefeed/new line */
1536 MODBIT(term.mode, set, MODE_CRLF);
1540 "erresc: unknown set/reset mode %d\n",
1552 switch(csiescseq.mode) {
1555 fprintf(stderr, "erresc: unknown csi ");
1559 case '@': /* ICH -- Insert <n> blank char */
1560 DEFAULT(csiescseq.arg[0], 1);
1561 tinsertblank(csiescseq.arg[0]);
1563 case 'A': /* CUU -- Cursor <n> Up */
1564 DEFAULT(csiescseq.arg[0], 1);
1565 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1567 case 'B': /* CUD -- Cursor <n> Down */
1568 case 'e': /* VPR --Cursor <n> Down */
1569 DEFAULT(csiescseq.arg[0], 1);
1570 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1572 case 'c': /* DA -- Device Attributes */
1573 if(csiescseq.arg[0] == 0)
1574 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1576 case 'C': /* CUF -- Cursor <n> Forward */
1577 case 'a': /* HPR -- Cursor <n> Forward */
1578 DEFAULT(csiescseq.arg[0], 1);
1579 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1581 case 'D': /* CUB -- Cursor <n> Backward */
1582 DEFAULT(csiescseq.arg[0], 1);
1583 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1585 case 'E': /* CNL -- Cursor <n> Down and first col */
1586 DEFAULT(csiescseq.arg[0], 1);
1587 tmoveto(0, term.c.y+csiescseq.arg[0]);
1589 case 'F': /* CPL -- Cursor <n> Up and first col */
1590 DEFAULT(csiescseq.arg[0], 1);
1591 tmoveto(0, term.c.y-csiescseq.arg[0]);
1593 case 'g': /* TBC -- Tabulation clear */
1594 switch (csiescseq.arg[0]) {
1595 case 0: /* clear current tab stop */
1596 term.tabs[term.c.x] = 0;
1598 case 3: /* clear all the tabs */
1599 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1605 case 'G': /* CHA -- Move to <col> */
1607 DEFAULT(csiescseq.arg[0], 1);
1608 tmoveto(csiescseq.arg[0]-1, term.c.y);
1610 case 'H': /* CUP -- Move to <row> <col> */
1612 DEFAULT(csiescseq.arg[0], 1);
1613 DEFAULT(csiescseq.arg[1], 1);
1614 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1616 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1617 DEFAULT(csiescseq.arg[0], 1);
1618 while(csiescseq.arg[0]--)
1621 case 'J': /* ED -- Clear screen */
1623 switch(csiescseq.arg[0]) {
1625 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1626 if(term.c.y < term.row-1)
1627 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1631 tclearregion(0, 0, term.col-1, term.c.y-1);
1632 tclearregion(0, term.c.y, term.c.x, term.c.y);
1635 tclearregion(0, 0, term.col-1, term.row-1);
1641 case 'K': /* EL -- Clear line */
1642 switch(csiescseq.arg[0]) {
1644 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1647 tclearregion(0, term.c.y, term.c.x, term.c.y);
1650 tclearregion(0, term.c.y, term.col-1, term.c.y);
1654 case 'S': /* SU -- Scroll <n> line up */
1655 DEFAULT(csiescseq.arg[0], 1);
1656 tscrollup(term.top, csiescseq.arg[0]);
1658 case 'T': /* SD -- Scroll <n> line down */
1659 DEFAULT(csiescseq.arg[0], 1);
1660 tscrolldown(term.top, csiescseq.arg[0]);
1662 case 'L': /* IL -- Insert <n> blank lines */
1663 DEFAULT(csiescseq.arg[0], 1);
1664 tinsertblankline(csiescseq.arg[0]);
1666 case 'l': /* RM -- Reset Mode */
1667 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1669 case 'M': /* DL -- Delete <n> lines */
1670 DEFAULT(csiescseq.arg[0], 1);
1671 tdeleteline(csiescseq.arg[0]);
1673 case 'X': /* ECH -- Erase <n> char */
1674 DEFAULT(csiescseq.arg[0], 1);
1675 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1677 case 'P': /* DCH -- Delete <n> char */
1678 DEFAULT(csiescseq.arg[0], 1);
1679 tdeletechar(csiescseq.arg[0]);
1681 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1682 DEFAULT(csiescseq.arg[0], 1);
1683 while(csiescseq.arg[0]--)
1686 case 'd': /* VPA -- Move to <row> */
1687 DEFAULT(csiescseq.arg[0], 1);
1688 tmoveato(term.c.x, csiescseq.arg[0]-1);
1690 case 'h': /* SM -- Set terminal mode */
1691 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1693 case 'm': /* SGR -- Terminal attribute (color) */
1694 tsetattr(csiescseq.arg, csiescseq.narg);
1696 case 'r': /* DECSTBM -- Set Scrolling Region */
1697 if(csiescseq.priv) {
1700 DEFAULT(csiescseq.arg[0], 1);
1701 DEFAULT(csiescseq.arg[1], term.row);
1702 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1706 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1707 tcursor(CURSOR_SAVE);
1709 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1710 tcursor(CURSOR_LOAD);
1721 for(i = 0; i < csiescseq.len; i++) {
1722 c = csiescseq.buf[i] & 0xff;
1725 } else if(c == '\n') {
1727 } else if(c == '\r') {
1729 } else if(c == 0x1b) {
1732 printf("(%02x)", c);
1740 memset(&csiescseq, 0, sizeof(csiescseq));
1748 * TODO: make this being useful in case of color palette change.
1754 switch(strescseq.type) {
1755 case ']': /* OSC -- Operating System Command */
1761 * TODO: Handle special chars in string, like umlauts.
1764 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1768 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1770 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1773 fprintf(stderr, "erresc: unknown str ");
1778 case 'k': /* old title set compatibility */
1779 XStoreName(xw.dpy, xw.win, strescseq.buf);
1781 case 'P': /* DSC -- Device Control String */
1782 case '_': /* APC -- Application Program Command */
1783 case '^': /* PM -- Privacy Message */
1785 fprintf(stderr, "erresc: unknown str ");
1795 * TODO: Implement parsing like for CSI when required.
1796 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1806 printf("ESC%c", strescseq.type);
1807 for(i = 0; i < strescseq.len; i++) {
1808 c = strescseq.buf[i] & 0xff;
1811 } else if(c == '\n') {
1813 } else if(c == '\r') {
1815 } else if(c == 0x1b) {
1818 printf("(%02x)", c);
1826 memset(&strescseq, 0, sizeof(strescseq));
1830 tputtab(bool forward) {
1836 for(++x; x < term.col && !term.tabs[x]; ++x)
1841 for(--x; x > 0 && !term.tabs[x]; --x)
1844 tmoveto(x, term.c.y);
1848 tputc(char *c, int len) {
1850 bool control = ascii < '\x20' || ascii == 0177;
1853 if (xwrite(iofd, c, len) < 0) {
1854 fprintf(stderr, "Error writting in %s:%s\n",
1855 opt_io, strerror(errno));
1861 * STR sequences must be checked before anything else
1862 * because it can use some control codes as part of the sequence.
1864 if(term.esc & ESC_STR) {
1867 term.esc = ESC_START | ESC_STR_END;
1869 case '\a': /* backwards compatibility to xterm */
1874 strescseq.buf[strescseq.len++] = ascii;
1875 if(strescseq.len+1 >= STR_BUF_SIZ) {
1884 * Actions of control codes must be performed as soon they arrive
1885 * because they can be embedded inside a control sequence, and
1886 * they must not cause conflicts with sequences.
1894 tmoveto(term.c.x-1, term.c.y);
1897 tmoveto(0, term.c.y);
1902 /* go to first col if the mode is set */
1903 tnewline(IS_SET(MODE_CRLF));
1905 case '\a': /* BEL */
1906 if(!(xw.state & WIN_FOCUSED))
1909 case '\033': /* ESC */
1911 term.esc = ESC_START;
1913 case '\016': /* SO */
1914 term.c.attr.mode |= ATTR_GFX;
1916 case '\017': /* SI */
1917 term.c.attr.mode &= ~ATTR_GFX;
1919 case '\032': /* SUB */
1920 case '\030': /* CAN */
1923 case '\005': /* ENQ (IGNORED) */
1924 case '\000': /* NUL (IGNORED) */
1925 case '\021': /* XON (IGNORED) */
1926 case '\023': /* XOFF (IGNORED) */
1927 case 0177: /* DEL (IGNORED) */
1930 } else if(term.esc & ESC_START) {
1931 if(term.esc & ESC_CSI) {
1932 csiescseq.buf[csiescseq.len++] = ascii;
1933 if(BETWEEN(ascii, 0x40, 0x7E)
1934 || csiescseq.len >= ESC_BUF_SIZ) {
1936 csiparse(), csihandle();
1938 } else if(term.esc & ESC_STR_END) {
1942 } else if(term.esc & ESC_ALTCHARSET) {
1944 case '0': /* Line drawing set */
1945 term.c.attr.mode |= ATTR_GFX;
1947 case 'B': /* USASCII */
1948 term.c.attr.mode &= ~ATTR_GFX;
1950 case 'A': /* UK (IGNORED) */
1951 case '<': /* multinational charset (IGNORED) */
1952 case '5': /* Finnish (IGNORED) */
1953 case 'C': /* Finnish (IGNORED) */
1954 case 'K': /* German (IGNORED) */
1957 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1960 } else if(term.esc & ESC_TEST) {
1961 if(ascii == '8') { /* DEC screen alignment test. */
1962 char E[UTF_SIZ] = "E";
1965 for(x = 0; x < term.col; ++x) {
1966 for(y = 0; y < term.row; ++y)
1967 tsetchar(E, &term.c.attr, x, y);
1974 term.esc |= ESC_CSI;
1977 term.esc |= ESC_TEST;
1979 case 'P': /* DCS -- Device Control String */
1980 case '_': /* APC -- Application Program Command */
1981 case '^': /* PM -- Privacy Message */
1982 case ']': /* OSC -- Operating System Command */
1983 case 'k': /* old title set compatibility */
1985 strescseq.type = ascii;
1986 term.esc |= ESC_STR;
1988 case '(': /* set primary charset G0 */
1989 term.esc |= ESC_ALTCHARSET;
1991 case ')': /* set secondary charset G1 (IGNORED) */
1992 case '*': /* set tertiary charset G2 (IGNORED) */
1993 case '+': /* set quaternary charset G3 (IGNORED) */
1996 case 'D': /* IND -- Linefeed */
1997 if(term.c.y == term.bot) {
1998 tscrollup(term.top, 1);
2000 tmoveto(term.c.x, term.c.y+1);
2004 case 'E': /* NEL -- Next line */
2005 tnewline(1); /* always go to first col */
2008 case 'H': /* HTS -- Horizontal tab stop */
2009 term.tabs[term.c.x] = 1;
2012 case 'M': /* RI -- Reverse index */
2013 if(term.c.y == term.top) {
2014 tscrolldown(term.top, 1);
2016 tmoveto(term.c.x, term.c.y-1);
2020 case 'Z': /* DECID -- Identify Terminal */
2021 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2024 case 'c': /* RIS -- Reset to inital state */
2029 case '=': /* DECPAM -- Application keypad */
2030 term.mode |= MODE_APPKEYPAD;
2033 case '>': /* DECPNM -- Normal keypad */
2034 term.mode &= ~MODE_APPKEYPAD;
2037 case '7': /* DECSC -- Save Cursor */
2038 tcursor(CURSOR_SAVE);
2041 case '8': /* DECRC -- Restore Cursor */
2042 tcursor(CURSOR_LOAD);
2045 case '\\': /* ST -- Stop */
2049 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2050 (uchar) ascii, isprint(ascii)? ascii:'.');
2055 * All characters which forms part of a sequence are not
2061 * Display control codes only if we are in graphic mode
2063 if(control && !(term.c.attr.mode & ATTR_GFX))
2065 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2067 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
2068 tnewline(1); /* always go to first col */
2069 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2070 if(term.c.x+1 < term.col)
2071 tmoveto(term.c.x+1, term.c.y);
2073 term.c.state |= CURSOR_WRAPNEXT;
2077 tresize(int col, int row) {
2079 int minrow = MIN(row, term.row);
2080 int mincol = MIN(col, term.col);
2081 int slide = term.c.y - row + 1;
2084 if(col < 1 || row < 1)
2087 /* free unneeded rows */
2090 /* slide screen to keep cursor where we expect it -
2091 * tscrollup would work here, but we can optimize to
2092 * memmove because we're freeing the earlier lines */
2093 for(/* i = 0 */; i < slide; i++) {
2097 memmove(term.line, term.line + slide, row * sizeof(Line));
2098 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2100 for(i += row; i < term.row; i++) {
2105 /* resize to new height */
2106 term.line = xrealloc(term.line, row * sizeof(Line));
2107 term.alt = xrealloc(term.alt, row * sizeof(Line));
2108 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2109 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2111 /* resize each row to new width, zero-pad if needed */
2112 for(i = 0; i < minrow; i++) {
2114 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2115 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2116 for(x = mincol; x < col; x++) {
2117 term.line[i][x].state = 0;
2118 term.alt[i][x].state = 0;
2122 /* allocate any new rows */
2123 for(/* i == minrow */; i < row; i++) {
2125 term.line[i] = xcalloc(col, sizeof(Glyph));
2126 term.alt [i] = xcalloc(col, sizeof(Glyph));
2128 if(col > term.col) {
2129 bp = term.tabs + term.col;
2131 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2132 while(--bp > term.tabs && !*bp)
2134 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2137 /* update terminal size */
2140 /* reset scrolling region */
2141 tsetscroll(0, row-1);
2142 /* make use of the LIMIT in tmoveto */
2143 tmoveto(term.c.x, term.c.y);
2149 xresize(int col, int row) {
2150 xw.tw = MAX(1, 2*borderpx + col * xw.cw);
2151 xw.th = MAX(1, 2*borderpx + row * xw.ch);
2153 XftDrawChange(xw.xft_draw, xw.buf);
2159 XRenderColor xft_color = { .alpha = 0 };
2161 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2162 for(i = 0; i < LEN(colorname); i++) {
2165 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
2166 die("Could not allocate color '%s'\n", colorname[i]);
2170 /* load colors [16-255] ; same colors as xterm */
2171 for(i = 16, r = 0; r < 6; r++) {
2172 for(g = 0; g < 6; g++) {
2173 for(b = 0; b < 6; b++) {
2174 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
2175 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
2176 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
2177 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
2178 die("Could not allocate color %d\n", i);
2185 for(r = 0; r < 24; r++, i++) {
2186 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
2187 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color,
2189 die("Could not allocate color %d\n", i);
2195 xtermclear(int col1, int row1, int col2, int row2) {
2196 XftDrawRect(xw.xft_draw,
2197 &dc.xft_col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2198 borderpx + col1 * xw.cw,
2199 borderpx + row1 * xw.ch,
2200 (col2-col1+1) * xw.cw,
2201 (row2-row1+1) * xw.ch);
2205 * Absolute coordinates.
2208 xclear(int x1, int y1, int x2, int y2) {
2209 XftDrawRect(xw.xft_draw,
2210 &dc.xft_col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2211 x1, y1, x2-x1, y2-y1);
2216 XClassHint class = {opt_class ? opt_class : termname, termname};
2217 XWMHints wm = {.flags = InputHint, .input = 1};
2218 XSizeHints *sizeh = NULL;
2220 sizeh = XAllocSizeHints();
2221 if(xw.isfixed == False) {
2222 sizeh->flags = PSize | PResizeInc | PBaseSize;
2223 sizeh->height = xw.h;
2224 sizeh->width = xw.w;
2225 sizeh->height_inc = xw.ch;
2226 sizeh->width_inc = xw.cw;
2227 sizeh->base_height = 2*borderpx;
2228 sizeh->base_width = 2*borderpx;
2230 sizeh->flags = PMaxSize | PMinSize;
2231 sizeh->min_width = sizeh->max_width = xw.fw;
2232 sizeh->min_height = sizeh->max_height = xw.fh;
2235 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2240 xloadfont(Font *f, FcPattern *pattern) {
2244 match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
2247 if(!(f->xft_set = XftFontOpenPattern(xw.dpy, match))) {
2248 FcPatternDestroy(match);
2252 f->ascent = f->xft_set->ascent;
2253 f->descent = f->xft_set->descent;
2255 f->rbearing = f->xft_set->max_advance_width;
2257 f->height = f->xft_set->height;
2258 f->width = f->lbearing + f->rbearing;
2264 xloadfonts(char *fontstr, int fontsize) {
2269 if(fontstr[0] == '-') {
2270 pattern = XftXlfdParse(fontstr, False, False);
2272 pattern = FcNameParse((FcChar8 *)fontstr);
2276 die("st: can't open font %s\n", fontstr);
2279 FcPatternDel(pattern, FC_PIXEL_SIZE);
2280 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2281 usedfontsize = fontsize;
2283 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2284 if(result == FcResultMatch) {
2285 usedfontsize = (int)fontval;
2288 * Default font size is 12, if none given. This is to
2289 * have a known usedfontsize value.
2291 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2296 if(xloadfont(&dc.font, pattern))
2297 die("st: can't open font %s\n", fontstr);
2299 /* Setting character width and height. */
2300 xw.cw = dc.font.width;
2301 xw.ch = dc.font.height;
2303 FcPatternDel(pattern, FC_WEIGHT);
2304 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2305 if(xloadfont(&dc.bfont, pattern))
2306 die("st: can't open font %s\n", fontstr);
2308 FcPatternDel(pattern, FC_SLANT);
2309 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2310 if(xloadfont(&dc.ibfont, pattern))
2311 die("st: can't open font %s\n", fontstr);
2313 FcPatternDel(pattern, FC_WEIGHT);
2314 if(xloadfont(&dc.ifont, pattern))
2315 die("st: can't open font %s\n", fontstr);
2317 FcPatternDestroy(pattern);
2321 xzoom(const Arg *arg)
2323 xloadfonts(usedfont, usedfontsize + arg->i);
2330 XSetWindowAttributes attrs;
2333 int sw, sh, major, minor;
2335 if(!(xw.dpy = XOpenDisplay(NULL)))
2336 die("Can't open display\n");
2337 xw.scr = XDefaultScreen(xw.dpy);
2338 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2341 usedfont = (opt_font == NULL)? font : opt_font;
2342 xloadfonts(usedfont, 0);
2345 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2348 /* adjust fixed window geometry */
2350 sw = DisplayWidth(xw.dpy, xw.scr);
2351 sh = DisplayHeight(xw.dpy, xw.scr);
2353 xw.fx = sw + xw.fx - xw.fw - 1;
2355 xw.fy = sh + xw.fy - xw.fh - 1;
2360 /* window - default size */
2361 xw.h = 2*borderpx + term.row * xw.ch;
2362 xw.w = 2*borderpx + term.col * xw.cw;
2367 attrs.background_pixel = dc.xft_col[defaultbg].pixel;
2368 attrs.border_pixel = dc.xft_col[defaultbg].pixel;
2369 attrs.bit_gravity = NorthWestGravity;
2370 attrs.event_mask = FocusChangeMask | KeyPressMask
2371 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2372 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2373 attrs.colormap = xw.cmap;
2375 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2376 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2377 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2379 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2383 /* double buffering */
2384 if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2385 die("Xdbe extension is not present\n");
2386 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2388 /* Xft rendering context */
2389 xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2392 xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2393 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2394 | XIMStatusNothing, XNClientWindow, xw.win,
2395 XNFocusWindow, xw.win, NULL);
2397 dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2399 /* white cursor, black outline */
2400 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2401 XDefineCursor(xw.dpy, xw.win, cursor);
2402 XRecolorCursor(xw.dpy, cursor,
2403 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2404 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2406 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2407 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2408 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2411 XMapWindow(xw.dpy, xw.win);
2417 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2418 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2419 width = charlen * xw.cw;
2420 Font *font = &dc.font;
2422 XftColor *fg = &dc.xft_col[base.fg], *bg = &dc.xft_col[base.bg],
2423 *temp, revfg, revbg;
2424 XRenderColor colfg, colbg;
2426 if(base.mode & ATTR_BOLD) {
2427 if(BETWEEN(base.fg, 0, 7)) {
2428 /* basic system colors */
2429 fg = &dc.xft_col[base.fg + 8];
2430 } else if(BETWEEN(base.fg, 16, 195)) {
2432 fg = &dc.xft_col[base.fg + 36];
2433 } else if(BETWEEN(base.fg, 232, 251)) {
2435 fg = &dc.xft_col[base.fg + 4];
2438 * Those ranges will not be brightened:
2439 * 8 - 15 – bright system colors
2440 * 196 - 231 – highest 256 color cube
2441 * 252 - 255 – brightest colors in greyscale
2446 if(base.mode & ATTR_ITALIC)
2448 if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD))
2451 if(IS_SET(MODE_REVERSE)) {
2452 if(fg == &dc.xft_col[defaultfg]) {
2453 fg = &dc.xft_col[defaultbg];
2455 colfg.red = ~fg->color.red;
2456 colfg.green = ~fg->color.green;
2457 colfg.blue = ~fg->color.blue;
2458 colfg.alpha = fg->color.alpha;
2459 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2463 if(bg == &dc.xft_col[defaultbg]) {
2464 bg = &dc.xft_col[defaultfg];
2466 colbg.red = ~bg->color.red;
2467 colbg.green = ~bg->color.green;
2468 colbg.blue = ~bg->color.blue;
2469 colbg.alpha = bg->color.alpha;
2470 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2475 if(base.mode & ATTR_REVERSE)
2476 temp = fg, fg = bg, bg = temp;
2478 XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen,
2480 width = extents.xOff;
2482 /* Intelligent cleaning up of the borders. */
2484 xclear(0, (y == 0)? 0 : winy, borderpx,
2485 winy + xw.ch + (y == term.row-1)? xw.h : 0);
2487 if(x + charlen >= term.col-1) {
2488 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2489 (y == term.row-1)? xw.h : (winy + xw.ch));
2492 xclear(winx, 0, winx + width, borderpx);
2494 xclear(winx, winy + xw.ch, winx + width, xw.h);
2496 XftDrawRect(xw.xft_draw, bg, winx, winy, width, xw.ch);
2497 XftDrawStringUtf8(xw.xft_draw, fg, font->xft_set, winx,
2498 winy + font->ascent, (FcChar8 *)s, bytelen);
2500 if(base.mode & ATTR_UNDERLINE) {
2501 XftDrawRect(xw.xft_draw, fg, winx, winy + font->ascent + 1,
2508 static int oldx = 0, oldy = 0;
2510 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs, 0};
2512 LIMIT(oldx, 0, term.col-1);
2513 LIMIT(oldy, 0, term.row-1);
2515 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2516 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2518 /* remove the old cursor */
2519 if(term.line[oldy][oldx].state & GLYPH_SET) {
2520 sl = utf8size(term.line[oldy][oldx].c);
2521 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2524 xtermclear(oldx, oldy, oldx, oldy);
2527 /* draw the new one */
2528 if(!(IS_SET(MODE_HIDE))) {
2529 if(!(xw.state & WIN_FOCUSED))
2532 if(IS_SET(MODE_REVERSE))
2533 g.mode |= ATTR_REVERSE, g.fg = defaultcs, g.bg = defaultfg;
2536 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2537 oldx = term.c.x, oldy = term.c.y;
2543 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2548 struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2552 XSync(xw.dpy, False); /* necessary for a good tput flash */
2553 nanosleep(&tv, NULL);
2558 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2560 drawregion(0, 0, term.col, term.row);
2561 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2565 drawregion(int x1, int y1, int x2, int y2) {
2566 int ic, ib, x, y, ox, sl;
2568 char buf[DRAW_BUF_SIZ];
2569 bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN) != 0;
2571 if((sel.alt != 0) ^ alt)
2573 if(!(xw.state & WIN_VISIBLE))
2576 for(y = y1; y < y2; y++) {
2580 xtermclear(0, y, term.col, y);
2582 base = term.line[y][0];
2584 for(x = x1; x < x2; x++) {
2585 new = term.line[y][x];
2586 if(ena_sel && *(new.c) && selected(x, y))
2587 new.mode ^= ATTR_REVERSE;
2588 if(ib > 0 && (!(new.state & GLYPH_SET)
2589 || ATTRCMP(base, new)
2590 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2591 xdraws(buf, base, ox, y, ic, ib);
2594 if(new.state & GLYPH_SET) {
2599 sl = utf8size(new.c);
2600 memcpy(buf+ib, new.c, sl);
2606 xdraws(buf, base, ox, y, ic, ib);
2612 expose(XEvent *ev) {
2613 XExposeEvent *e = &ev->xexpose;
2615 if(xw.state & WIN_REDRAW) {
2617 xw.state &= ~WIN_REDRAW;
2622 visibility(XEvent *ev) {
2623 XVisibilityEvent *e = &ev->xvisibility;
2625 if(e->state == VisibilityFullyObscured) {
2626 xw.state &= ~WIN_VISIBLE;
2627 } else if(!(xw.state & WIN_VISIBLE)) {
2628 /* need a full redraw for next Expose, not just a buf copy */
2629 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2635 xw.state &= ~WIN_VISIBLE;
2639 xseturgency(int add) {
2640 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2642 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2643 XSetWMHints(xw.dpy, xw.win, h);
2649 if(ev->type == FocusIn) {
2650 XSetICFocus(xw.xic);
2651 xw.state |= WIN_FOCUSED;
2654 XUnsetICFocus(xw.xic);
2655 xw.state &= ~WIN_FOCUSED;
2660 kmap(KeySym k, uint state) {
2665 for(i = 0; i < LEN(key); i++) {
2668 if(key[i].k == k && ((state & mask) == mask
2669 || (mask == XK_NO_MOD && !state))) {
2670 return (char*)key[i].s;
2677 kpress(XEvent *ev) {
2678 XKeyEvent *e = &ev->xkey;
2680 char buf[32], *customkey;
2681 int len, meta, shift, i;
2684 if (IS_SET(MODE_KBDLOCK))
2687 meta = e->state & Mod1Mask;
2688 shift = e->state & ShiftMask;
2689 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2692 for(i = 0; i < LEN(shortcuts); i++) {
2693 if((ksym == shortcuts[i].keysym)
2694 && (CLEANMASK(shortcuts[i].mod) == \
2695 CLEANMASK(e->state))
2696 && shortcuts[i].func) {
2697 shortcuts[i].func(&(shortcuts[i].arg));
2701 /* 2. custom keys from config.h */
2702 if((customkey = kmap(ksym, e->state))) {
2703 ttywrite(customkey, strlen(customkey));
2704 /* 2. hardcoded (overrides X lookup) */
2711 /* XXX: shift up/down doesn't work */
2712 sprintf(buf, "\033%c%c",
2713 IS_SET(MODE_APPKEYPAD) ? 'O' : '[',
2714 (shift ? "dacb":"DACB")[ksym - XK_Left]);
2723 ttywrite("\033", 1);
2725 if(IS_SET(MODE_CRLF)) {
2726 ttywrite("\r\n", 2);
2734 if(meta && len == 1)
2735 ttywrite("\033", 1);
2744 cmessage(XEvent *e) {
2746 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2747 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2748 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2749 xw.state |= WIN_FOCUSED;
2751 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2752 xw.state &= ~WIN_FOCUSED;
2754 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
2755 /* Send SIGHUP to shell */
2762 cresize(int width, int height)
2771 col = (xw.w - 2*borderpx) / xw.cw;
2772 row = (xw.h - 2*borderpx) / xw.ch;
2781 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2784 cresize(e->xconfigure.width, e->xconfigure.height);
2791 int xfd = XConnectionNumber(xw.dpy), i;
2792 struct timeval drawtimeout, *tv = NULL;
2796 FD_SET(cmdfd, &rfd);
2798 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2801 die("select failed: %s\n", SERRNO);
2805 * Stop after a certain number of reads so the user does not
2806 * feel like the system is stuttering.
2808 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2812 * Just wait a bit so it isn't disturbing the
2813 * user and the system is able to write something.
2815 drawtimeout.tv_sec = 0;
2816 drawtimeout.tv_usec = 5;
2823 while(XPending(xw.dpy)) {
2824 XNextEvent(xw.dpy, &ev);
2825 if(XFilterEvent(&ev, None))
2827 if(handler[ev.type])
2828 (handler[ev.type])(&ev);
2837 main(int argc, char *argv[]) {
2838 int i, bitm, xr, yr;
2841 xw.fw = xw.fh = xw.fx = xw.fy = 0;
2844 for(i = 1; i < argc; i++) {
2845 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2848 opt_class = argv[i];
2851 /* eat every remaining arguments */
2863 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2868 if(bitm & WidthValue)
2870 if(bitm & HeightValue)
2872 if(bitm & XNegative && xw.fx == 0)
2874 if(bitm & XNegative && xw.fy == 0)
2877 if(xw.fh != 0 && xw.fw != 0)
2886 opt_title = argv[i];
2893 opt_embed = argv[i];
2899 setlocale(LC_CTYPE, "");
2900 XSetLocaleModifiers("");