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: /* XXX: DECARM -- Auto repeat */
1485 case 0: /* Error (IGNORED) */
1486 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1488 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1489 MODBIT(term.mode, !set, MODE_HIDE);
1491 case 1000: /* 1000,1002: enable xterm mouse report */
1492 MODBIT(term.mode, set, MODE_MOUSEBTN);
1495 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1497 case 1049: /* = 1047 and 1048 */
1500 bool alt = IS_SET(MODE_ALTSCREEN) != 0;
1502 tclearregion(0, 0, term.col-1, term.row-1);
1503 if(set ^ alt) /* set is always 1 or 0 */
1510 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1513 /* case 2: DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
1514 /* case 3: DECCOLM -- Column (NOT SUPPORTED) */
1515 /* case 4: DECSCLM -- Scroll (NOT SUPPORTED) */
1516 /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
1517 /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
1518 /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
1520 "erresc: unknown private set/reset mode %d\n",
1526 case 0: /* Error (IGNORED) */
1528 case 2: /* KAM -- keyboard action */
1529 MODBIT(term.mode, set, MODE_KBDLOCK);
1531 case 4: /* IRM -- Insertion-replacement */
1532 MODBIT(term.mode, set, MODE_INSERT);
1534 case 12: /* XXX: SRM -- Send/Receive */
1536 case 20: /* LNM -- Linefeed/new line */
1537 MODBIT(term.mode, set, MODE_CRLF);
1541 "erresc: unknown set/reset mode %d\n",
1553 switch(csiescseq.mode) {
1556 fprintf(stderr, "erresc: unknown csi ");
1560 case '@': /* ICH -- Insert <n> blank char */
1561 DEFAULT(csiescseq.arg[0], 1);
1562 tinsertblank(csiescseq.arg[0]);
1564 case 'A': /* CUU -- Cursor <n> Up */
1565 DEFAULT(csiescseq.arg[0], 1);
1566 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1568 case 'B': /* CUD -- Cursor <n> Down */
1569 case 'e': /* VPR --Cursor <n> Down */
1570 DEFAULT(csiescseq.arg[0], 1);
1571 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1573 case 'c': /* DA -- Device Attributes */
1574 if(csiescseq.arg[0] == 0)
1575 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1577 case 'C': /* CUF -- Cursor <n> Forward */
1578 case 'a': /* HPR -- Cursor <n> Forward */
1579 DEFAULT(csiescseq.arg[0], 1);
1580 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1582 case 'D': /* CUB -- Cursor <n> Backward */
1583 DEFAULT(csiescseq.arg[0], 1);
1584 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1586 case 'E': /* CNL -- Cursor <n> Down and first col */
1587 DEFAULT(csiescseq.arg[0], 1);
1588 tmoveto(0, term.c.y+csiescseq.arg[0]);
1590 case 'F': /* CPL -- Cursor <n> Up and first col */
1591 DEFAULT(csiescseq.arg[0], 1);
1592 tmoveto(0, term.c.y-csiescseq.arg[0]);
1594 case 'g': /* TBC -- Tabulation clear */
1595 switch (csiescseq.arg[0]) {
1596 case 0: /* clear current tab stop */
1597 term.tabs[term.c.x] = 0;
1599 case 3: /* clear all the tabs */
1600 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1606 case 'G': /* CHA -- Move to <col> */
1608 DEFAULT(csiescseq.arg[0], 1);
1609 tmoveto(csiescseq.arg[0]-1, term.c.y);
1611 case 'H': /* CUP -- Move to <row> <col> */
1613 DEFAULT(csiescseq.arg[0], 1);
1614 DEFAULT(csiescseq.arg[1], 1);
1615 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1617 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1618 DEFAULT(csiescseq.arg[0], 1);
1619 while(csiescseq.arg[0]--)
1622 case 'J': /* ED -- Clear screen */
1624 switch(csiescseq.arg[0]) {
1626 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1627 if(term.c.y < term.row-1)
1628 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1632 tclearregion(0, 0, term.col-1, term.c.y-1);
1633 tclearregion(0, term.c.y, term.c.x, term.c.y);
1636 tclearregion(0, 0, term.col-1, term.row-1);
1642 case 'K': /* EL -- Clear line */
1643 switch(csiescseq.arg[0]) {
1645 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1648 tclearregion(0, term.c.y, term.c.x, term.c.y);
1651 tclearregion(0, term.c.y, term.col-1, term.c.y);
1655 case 'S': /* SU -- Scroll <n> line up */
1656 DEFAULT(csiescseq.arg[0], 1);
1657 tscrollup(term.top, csiescseq.arg[0]);
1659 case 'T': /* SD -- Scroll <n> line down */
1660 DEFAULT(csiescseq.arg[0], 1);
1661 tscrolldown(term.top, csiescseq.arg[0]);
1663 case 'L': /* IL -- Insert <n> blank lines */
1664 DEFAULT(csiescseq.arg[0], 1);
1665 tinsertblankline(csiescseq.arg[0]);
1667 case 'l': /* RM -- Reset Mode */
1668 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1670 case 'M': /* DL -- Delete <n> lines */
1671 DEFAULT(csiescseq.arg[0], 1);
1672 tdeleteline(csiescseq.arg[0]);
1674 case 'X': /* ECH -- Erase <n> char */
1675 DEFAULT(csiescseq.arg[0], 1);
1676 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1678 case 'P': /* DCH -- Delete <n> char */
1679 DEFAULT(csiescseq.arg[0], 1);
1680 tdeletechar(csiescseq.arg[0]);
1682 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1683 DEFAULT(csiescseq.arg[0], 1);
1684 while(csiescseq.arg[0]--)
1687 case 'd': /* VPA -- Move to <row> */
1688 DEFAULT(csiescseq.arg[0], 1);
1689 tmoveato(term.c.x, csiescseq.arg[0]-1);
1691 case 'h': /* SM -- Set terminal mode */
1692 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1694 case 'm': /* SGR -- Terminal attribute (color) */
1695 tsetattr(csiescseq.arg, csiescseq.narg);
1697 case 'r': /* DECSTBM -- Set Scrolling Region */
1698 if(csiescseq.priv) {
1701 DEFAULT(csiescseq.arg[0], 1);
1702 DEFAULT(csiescseq.arg[1], term.row);
1703 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1707 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1708 tcursor(CURSOR_SAVE);
1710 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1711 tcursor(CURSOR_LOAD);
1722 for(i = 0; i < csiescseq.len; i++) {
1723 c = csiescseq.buf[i] & 0xff;
1726 } else if(c == '\n') {
1728 } else if(c == '\r') {
1730 } else if(c == 0x1b) {
1733 printf("(%02x)", c);
1741 memset(&csiescseq, 0, sizeof(csiescseq));
1749 * TODO: make this being useful in case of color palette change.
1755 switch(strescseq.type) {
1756 case ']': /* OSC -- Operating System Command */
1762 * TODO: Handle special chars in string, like umlauts.
1765 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1769 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1771 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1774 fprintf(stderr, "erresc: unknown str ");
1779 case 'k': /* old title set compatibility */
1780 XStoreName(xw.dpy, xw.win, strescseq.buf);
1782 case 'P': /* DSC -- Device Control String */
1783 case '_': /* APC -- Application Program Command */
1784 case '^': /* PM -- Privacy Message */
1786 fprintf(stderr, "erresc: unknown str ");
1796 * TODO: Implement parsing like for CSI when required.
1797 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1807 printf("ESC%c", strescseq.type);
1808 for(i = 0; i < strescseq.len; i++) {
1809 c = strescseq.buf[i] & 0xff;
1812 } else if(c == '\n') {
1814 } else if(c == '\r') {
1816 } else if(c == 0x1b) {
1819 printf("(%02x)", c);
1827 memset(&strescseq, 0, sizeof(strescseq));
1831 tputtab(bool forward) {
1837 for(++x; x < term.col && !term.tabs[x]; ++x)
1842 for(--x; x > 0 && !term.tabs[x]; --x)
1845 tmoveto(x, term.c.y);
1849 tputc(char *c, int len) {
1851 bool control = ascii < '\x20' || ascii == 0177;
1854 if (xwrite(iofd, c, len) < 0) {
1855 fprintf(stderr, "Error writting in %s:%s\n",
1856 opt_io, strerror(errno));
1862 * STR sequences must be checked before anything else
1863 * because it can use some control codes as part of the sequence.
1865 if(term.esc & ESC_STR) {
1868 term.esc = ESC_START | ESC_STR_END;
1870 case '\a': /* backwards compatibility to xterm */
1875 strescseq.buf[strescseq.len++] = ascii;
1876 if(strescseq.len+1 >= STR_BUF_SIZ) {
1885 * Actions of control codes must be performed as soon they arrive
1886 * because they can be embedded inside a control sequence, and
1887 * they must not cause conflicts with sequences.
1895 tmoveto(term.c.x-1, term.c.y);
1898 tmoveto(0, term.c.y);
1903 /* go to first col if the mode is set */
1904 tnewline(IS_SET(MODE_CRLF));
1906 case '\a': /* BEL */
1907 if(!(xw.state & WIN_FOCUSED))
1910 case '\033': /* ESC */
1912 term.esc = ESC_START;
1914 case '\016': /* SO */
1915 term.c.attr.mode |= ATTR_GFX;
1917 case '\017': /* SI */
1918 term.c.attr.mode &= ~ATTR_GFX;
1920 case '\032': /* SUB */
1921 case '\030': /* CAN */
1924 case '\005': /* ENQ (IGNORED) */
1925 case '\000': /* NUL (IGNORED) */
1926 case '\021': /* XON (IGNORED) */
1927 case '\023': /* XOFF (IGNORED) */
1928 case 0177: /* DEL (IGNORED) */
1931 } else if(term.esc & ESC_START) {
1932 if(term.esc & ESC_CSI) {
1933 csiescseq.buf[csiescseq.len++] = ascii;
1934 if(BETWEEN(ascii, 0x40, 0x7E)
1935 || csiescseq.len >= ESC_BUF_SIZ) {
1937 csiparse(), csihandle();
1939 } else if(term.esc & ESC_STR_END) {
1943 } else if(term.esc & ESC_ALTCHARSET) {
1945 case '0': /* Line drawing set */
1946 term.c.attr.mode |= ATTR_GFX;
1948 case 'B': /* USASCII */
1949 term.c.attr.mode &= ~ATTR_GFX;
1951 case 'A': /* UK (IGNORED) */
1952 case '<': /* multinational charset (IGNORED) */
1953 case '5': /* Finnish (IGNORED) */
1954 case 'C': /* Finnish (IGNORED) */
1955 case 'K': /* German (IGNORED) */
1958 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1961 } else if(term.esc & ESC_TEST) {
1962 if(ascii == '8') { /* DEC screen alignment test. */
1963 char E[UTF_SIZ] = "E";
1966 for(x = 0; x < term.col; ++x) {
1967 for(y = 0; y < term.row; ++y)
1968 tsetchar(E, &term.c.attr, x, y);
1975 term.esc |= ESC_CSI;
1978 term.esc |= ESC_TEST;
1980 case 'P': /* DCS -- Device Control String */
1981 case '_': /* APC -- Application Program Command */
1982 case '^': /* PM -- Privacy Message */
1983 case ']': /* OSC -- Operating System Command */
1984 case 'k': /* old title set compatibility */
1986 strescseq.type = ascii;
1987 term.esc |= ESC_STR;
1989 case '(': /* set primary charset G0 */
1990 term.esc |= ESC_ALTCHARSET;
1992 case ')': /* set secondary charset G1 (IGNORED) */
1993 case '*': /* set tertiary charset G2 (IGNORED) */
1994 case '+': /* set quaternary charset G3 (IGNORED) */
1997 case 'D': /* IND -- Linefeed */
1998 if(term.c.y == term.bot) {
1999 tscrollup(term.top, 1);
2001 tmoveto(term.c.x, term.c.y+1);
2005 case 'E': /* NEL -- Next line */
2006 tnewline(1); /* always go to first col */
2009 case 'H': /* HTS -- Horizontal tab stop */
2010 term.tabs[term.c.x] = 1;
2013 case 'M': /* RI -- Reverse index */
2014 if(term.c.y == term.top) {
2015 tscrolldown(term.top, 1);
2017 tmoveto(term.c.x, term.c.y-1);
2021 case 'Z': /* DECID -- Identify Terminal */
2022 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2025 case 'c': /* RIS -- Reset to inital state */
2030 case '=': /* DECPAM -- Application keypad */
2031 term.mode |= MODE_APPKEYPAD;
2034 case '>': /* DECPNM -- Normal keypad */
2035 term.mode &= ~MODE_APPKEYPAD;
2038 case '7': /* DECSC -- Save Cursor */
2039 tcursor(CURSOR_SAVE);
2042 case '8': /* DECRC -- Restore Cursor */
2043 tcursor(CURSOR_LOAD);
2046 case '\\': /* ST -- Stop */
2050 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2051 (uchar) ascii, isprint(ascii)? ascii:'.');
2056 * All characters which forms part of a sequence are not
2062 * Display control codes only if we are in graphic mode
2064 if(control && !(term.c.attr.mode & ATTR_GFX))
2066 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2068 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
2069 tnewline(1); /* always go to first col */
2070 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2071 if(term.c.x+1 < term.col)
2072 tmoveto(term.c.x+1, term.c.y);
2074 term.c.state |= CURSOR_WRAPNEXT;
2078 tresize(int col, int row) {
2080 int minrow = MIN(row, term.row);
2081 int mincol = MIN(col, term.col);
2082 int slide = term.c.y - row + 1;
2085 if(col < 1 || row < 1)
2088 /* free unneeded rows */
2091 /* slide screen to keep cursor where we expect it -
2092 * tscrollup would work here, but we can optimize to
2093 * memmove because we're freeing the earlier lines */
2094 for(/* i = 0 */; i < slide; i++) {
2098 memmove(term.line, term.line + slide, row * sizeof(Line));
2099 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2101 for(i += row; i < term.row; i++) {
2106 /* resize to new height */
2107 term.line = xrealloc(term.line, row * sizeof(Line));
2108 term.alt = xrealloc(term.alt, row * sizeof(Line));
2109 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2110 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2112 /* resize each row to new width, zero-pad if needed */
2113 for(i = 0; i < minrow; i++) {
2115 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2116 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2117 for(x = mincol; x < col; x++) {
2118 term.line[i][x].state = 0;
2119 term.alt[i][x].state = 0;
2123 /* allocate any new rows */
2124 for(/* i == minrow */; i < row; i++) {
2126 term.line[i] = xcalloc(col, sizeof(Glyph));
2127 term.alt [i] = xcalloc(col, sizeof(Glyph));
2129 if(col > term.col) {
2130 bp = term.tabs + term.col;
2132 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2133 while(--bp > term.tabs && !*bp)
2135 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2138 /* update terminal size */
2141 /* reset scrolling region */
2142 tsetscroll(0, row-1);
2143 /* make use of the LIMIT in tmoveto */
2144 tmoveto(term.c.x, term.c.y);
2150 xresize(int col, int row) {
2151 xw.tw = MAX(1, 2*borderpx + col * xw.cw);
2152 xw.th = MAX(1, 2*borderpx + row * xw.ch);
2154 XftDrawChange(xw.xft_draw, xw.buf);
2160 XRenderColor xft_color = { .alpha = 0 };
2162 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2163 for(i = 0; i < LEN(colorname); i++) {
2166 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
2167 die("Could not allocate color '%s'\n", colorname[i]);
2171 /* load colors [16-255] ; same colors as xterm */
2172 for(i = 16, r = 0; r < 6; r++) {
2173 for(g = 0; g < 6; g++) {
2174 for(b = 0; b < 6; b++) {
2175 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
2176 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
2177 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
2178 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
2179 die("Could not allocate color %d\n", i);
2186 for(r = 0; r < 24; r++, i++) {
2187 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
2188 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color,
2190 die("Could not allocate color %d\n", i);
2196 xtermclear(int col1, int row1, int col2, int row2) {
2197 XftDrawRect(xw.xft_draw,
2198 &dc.xft_col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2199 borderpx + col1 * xw.cw,
2200 borderpx + row1 * xw.ch,
2201 (col2-col1+1) * xw.cw,
2202 (row2-row1+1) * xw.ch);
2206 * Absolute coordinates.
2209 xclear(int x1, int y1, int x2, int y2) {
2210 XftDrawRect(xw.xft_draw,
2211 &dc.xft_col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2212 x1, y1, x2-x1, y2-y1);
2217 XClassHint class = {opt_class ? opt_class : termname, termname};
2218 XWMHints wm = {.flags = InputHint, .input = 1};
2219 XSizeHints *sizeh = NULL;
2221 sizeh = XAllocSizeHints();
2222 if(xw.isfixed == False) {
2223 sizeh->flags = PSize | PResizeInc | PBaseSize;
2224 sizeh->height = xw.h;
2225 sizeh->width = xw.w;
2226 sizeh->height_inc = xw.ch;
2227 sizeh->width_inc = xw.cw;
2228 sizeh->base_height = 2*borderpx;
2229 sizeh->base_width = 2*borderpx;
2231 sizeh->flags = PMaxSize | PMinSize;
2232 sizeh->min_width = sizeh->max_width = xw.fw;
2233 sizeh->min_height = sizeh->max_height = xw.fh;
2236 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2241 xloadfont(Font *f, FcPattern *pattern) {
2245 match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
2248 if(!(f->xft_set = XftFontOpenPattern(xw.dpy, match))) {
2249 FcPatternDestroy(match);
2253 f->ascent = f->xft_set->ascent;
2254 f->descent = f->xft_set->descent;
2256 f->rbearing = f->xft_set->max_advance_width;
2258 f->height = f->xft_set->height;
2259 f->width = f->lbearing + f->rbearing;
2265 xloadfonts(char *fontstr, int fontsize) {
2270 if(fontstr[0] == '-') {
2271 pattern = XftXlfdParse(fontstr, False, False);
2273 pattern = FcNameParse((FcChar8 *)fontstr);
2277 die("st: can't open font %s\n", fontstr);
2280 FcPatternDel(pattern, FC_PIXEL_SIZE);
2281 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2282 usedfontsize = fontsize;
2284 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2285 if(result == FcResultMatch) {
2286 usedfontsize = (int)fontval;
2289 * Default font size is 12, if none given. This is to
2290 * have a known usedfontsize value.
2292 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2297 if(xloadfont(&dc.font, pattern))
2298 die("st: can't open font %s\n", fontstr);
2300 /* Setting character width and height. */
2301 xw.cw = dc.font.width;
2302 xw.ch = dc.font.height;
2304 FcPatternDel(pattern, FC_WEIGHT);
2305 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2306 if(xloadfont(&dc.bfont, pattern))
2307 die("st: can't open font %s\n", fontstr);
2309 FcPatternDel(pattern, FC_SLANT);
2310 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2311 if(xloadfont(&dc.ibfont, pattern))
2312 die("st: can't open font %s\n", fontstr);
2314 FcPatternDel(pattern, FC_WEIGHT);
2315 if(xloadfont(&dc.ifont, pattern))
2316 die("st: can't open font %s\n", fontstr);
2318 FcPatternDestroy(pattern);
2322 xzoom(const Arg *arg)
2324 xloadfonts(usedfont, usedfontsize + arg->i);
2331 XSetWindowAttributes attrs;
2334 int sw, sh, major, minor;
2336 if(!(xw.dpy = XOpenDisplay(NULL)))
2337 die("Can't open display\n");
2338 xw.scr = XDefaultScreen(xw.dpy);
2339 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2342 usedfont = (opt_font == NULL)? font : opt_font;
2343 xloadfonts(usedfont, 0);
2346 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2349 /* adjust fixed window geometry */
2351 sw = DisplayWidth(xw.dpy, xw.scr);
2352 sh = DisplayHeight(xw.dpy, xw.scr);
2354 xw.fx = sw + xw.fx - xw.fw - 1;
2356 xw.fy = sh + xw.fy - xw.fh - 1;
2361 /* window - default size */
2362 xw.h = 2*borderpx + term.row * xw.ch;
2363 xw.w = 2*borderpx + term.col * xw.cw;
2368 attrs.background_pixel = dc.xft_col[defaultbg].pixel;
2369 attrs.border_pixel = dc.xft_col[defaultbg].pixel;
2370 attrs.bit_gravity = NorthWestGravity;
2371 attrs.event_mask = FocusChangeMask | KeyPressMask
2372 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2373 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2374 attrs.colormap = xw.cmap;
2376 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2377 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2378 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2380 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2384 /* double buffering */
2385 if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2386 die("Xdbe extension is not present\n");
2387 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2389 /* Xft rendering context */
2390 xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2393 xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2394 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2395 | XIMStatusNothing, XNClientWindow, xw.win,
2396 XNFocusWindow, xw.win, NULL);
2398 dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2400 /* white cursor, black outline */
2401 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2402 XDefineCursor(xw.dpy, xw.win, cursor);
2403 XRecolorCursor(xw.dpy, cursor,
2404 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2405 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2407 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2408 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2409 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2412 XMapWindow(xw.dpy, xw.win);
2418 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2419 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2420 width = charlen * xw.cw;
2421 Font *font = &dc.font;
2423 XftColor *fg = &dc.xft_col[base.fg], *bg = &dc.xft_col[base.bg],
2424 *temp, revfg, revbg;
2425 XRenderColor colfg, colbg;
2427 if(base.mode & ATTR_BOLD) {
2428 if(BETWEEN(base.fg, 0, 7)) {
2429 /* basic system colors */
2430 fg = &dc.xft_col[base.fg + 8];
2431 } else if(BETWEEN(base.fg, 16, 195)) {
2433 fg = &dc.xft_col[base.fg + 36];
2434 } else if(BETWEEN(base.fg, 232, 251)) {
2436 fg = &dc.xft_col[base.fg + 4];
2439 * Those ranges will not be brightened:
2440 * 8 - 15 – bright system colors
2441 * 196 - 231 – highest 256 color cube
2442 * 252 - 255 – brightest colors in greyscale
2447 if(base.mode & ATTR_ITALIC)
2449 if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD))
2452 if(IS_SET(MODE_REVERSE)) {
2453 if(fg == &dc.xft_col[defaultfg]) {
2454 fg = &dc.xft_col[defaultbg];
2456 colfg.red = ~fg->color.red;
2457 colfg.green = ~fg->color.green;
2458 colfg.blue = ~fg->color.blue;
2459 colfg.alpha = fg->color.alpha;
2460 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2464 if(bg == &dc.xft_col[defaultbg]) {
2465 bg = &dc.xft_col[defaultfg];
2467 colbg.red = ~bg->color.red;
2468 colbg.green = ~bg->color.green;
2469 colbg.blue = ~bg->color.blue;
2470 colbg.alpha = bg->color.alpha;
2471 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2476 if(base.mode & ATTR_REVERSE)
2477 temp = fg, fg = bg, bg = temp;
2479 XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen,
2481 width = extents.xOff;
2483 /* Intelligent cleaning up of the borders. */
2485 xclear(0, (y == 0)? 0 : winy, borderpx,
2486 winy + xw.ch + (y == term.row-1)? xw.h : 0);
2488 if(x + charlen >= term.col-1) {
2489 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2490 (y == term.row-1)? xw.h : (winy + xw.ch));
2493 xclear(winx, 0, winx + width, borderpx);
2495 xclear(winx, winy + xw.ch, winx + width, xw.h);
2497 XftDrawRect(xw.xft_draw, bg, winx, winy, width, xw.ch);
2498 XftDrawStringUtf8(xw.xft_draw, fg, font->xft_set, winx,
2499 winy + font->ascent, (FcChar8 *)s, bytelen);
2501 if(base.mode & ATTR_UNDERLINE) {
2502 XftDrawRect(xw.xft_draw, fg, winx, winy + font->ascent + 1,
2509 static int oldx = 0, oldy = 0;
2511 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs, 0};
2513 LIMIT(oldx, 0, term.col-1);
2514 LIMIT(oldy, 0, term.row-1);
2516 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2517 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2519 /* remove the old cursor */
2520 if(term.line[oldy][oldx].state & GLYPH_SET) {
2521 sl = utf8size(term.line[oldy][oldx].c);
2522 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2525 xtermclear(oldx, oldy, oldx, oldy);
2528 /* draw the new one */
2529 if(!(IS_SET(MODE_HIDE))) {
2530 if(!(xw.state & WIN_FOCUSED))
2533 if(IS_SET(MODE_REVERSE))
2534 g.mode |= ATTR_REVERSE, g.fg = defaultcs, g.bg = defaultfg;
2537 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2538 oldx = term.c.x, oldy = term.c.y;
2544 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2549 struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2553 XSync(xw.dpy, False); /* necessary for a good tput flash */
2554 nanosleep(&tv, NULL);
2559 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2561 drawregion(0, 0, term.col, term.row);
2562 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2566 drawregion(int x1, int y1, int x2, int y2) {
2567 int ic, ib, x, y, ox, sl;
2569 char buf[DRAW_BUF_SIZ];
2570 bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN) != 0;
2572 if((sel.alt != 0) ^ alt)
2574 if(!(xw.state & WIN_VISIBLE))
2577 for(y = y1; y < y2; y++) {
2581 xtermclear(0, y, term.col, y);
2583 base = term.line[y][0];
2585 for(x = x1; x < x2; x++) {
2586 new = term.line[y][x];
2587 if(ena_sel && *(new.c) && selected(x, y))
2588 new.mode ^= ATTR_REVERSE;
2589 if(ib > 0 && (!(new.state & GLYPH_SET)
2590 || ATTRCMP(base, new)
2591 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2592 xdraws(buf, base, ox, y, ic, ib);
2595 if(new.state & GLYPH_SET) {
2600 sl = utf8size(new.c);
2601 memcpy(buf+ib, new.c, sl);
2607 xdraws(buf, base, ox, y, ic, ib);
2613 expose(XEvent *ev) {
2614 XExposeEvent *e = &ev->xexpose;
2616 if(xw.state & WIN_REDRAW) {
2618 xw.state &= ~WIN_REDRAW;
2623 visibility(XEvent *ev) {
2624 XVisibilityEvent *e = &ev->xvisibility;
2626 if(e->state == VisibilityFullyObscured) {
2627 xw.state &= ~WIN_VISIBLE;
2628 } else if(!(xw.state & WIN_VISIBLE)) {
2629 /* need a full redraw for next Expose, not just a buf copy */
2630 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2636 xw.state &= ~WIN_VISIBLE;
2640 xseturgency(int add) {
2641 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2643 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2644 XSetWMHints(xw.dpy, xw.win, h);
2650 if(ev->type == FocusIn) {
2651 XSetICFocus(xw.xic);
2652 xw.state |= WIN_FOCUSED;
2655 XUnsetICFocus(xw.xic);
2656 xw.state &= ~WIN_FOCUSED;
2661 kmap(KeySym k, uint state) {
2666 for(i = 0; i < LEN(key); i++) {
2669 if(key[i].k == k && ((state & mask) == mask
2670 || (mask == XK_NO_MOD && !state))) {
2671 return (char*)key[i].s;
2678 kpress(XEvent *ev) {
2679 XKeyEvent *e = &ev->xkey;
2681 char buf[32], *customkey;
2682 int len, meta, shift, i;
2685 if (IS_SET(MODE_KBDLOCK))
2688 meta = e->state & Mod1Mask;
2689 shift = e->state & ShiftMask;
2690 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2693 for(i = 0; i < LEN(shortcuts); i++) {
2694 if((ksym == shortcuts[i].keysym)
2695 && (CLEANMASK(shortcuts[i].mod) == \
2696 CLEANMASK(e->state))
2697 && shortcuts[i].func) {
2698 shortcuts[i].func(&(shortcuts[i].arg));
2702 /* 2. custom keys from config.h */
2703 if((customkey = kmap(ksym, e->state))) {
2704 ttywrite(customkey, strlen(customkey));
2705 /* 2. hardcoded (overrides X lookup) */
2712 /* XXX: shift up/down doesn't work */
2713 sprintf(buf, "\033%c%c",
2714 IS_SET(MODE_APPKEYPAD) ? 'O' : '[',
2715 (shift ? "dacb":"DACB")[ksym - XK_Left]);
2724 ttywrite("\033", 1);
2726 if(IS_SET(MODE_CRLF)) {
2727 ttywrite("\r\n", 2);
2735 if(meta && len == 1)
2736 ttywrite("\033", 1);
2745 cmessage(XEvent *e) {
2747 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2748 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2749 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2750 xw.state |= WIN_FOCUSED;
2752 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2753 xw.state &= ~WIN_FOCUSED;
2755 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
2756 /* Send SIGHUP to shell */
2763 cresize(int width, int height)
2772 col = (xw.w - 2*borderpx) / xw.cw;
2773 row = (xw.h - 2*borderpx) / xw.ch;
2782 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2785 cresize(e->xconfigure.width, e->xconfigure.height);
2792 int xfd = XConnectionNumber(xw.dpy), i;
2793 struct timeval drawtimeout, *tv = NULL;
2797 FD_SET(cmdfd, &rfd);
2799 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2802 die("select failed: %s\n", SERRNO);
2806 * Stop after a certain number of reads so the user does not
2807 * feel like the system is stuttering.
2809 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2813 * Just wait a bit so it isn't disturbing the
2814 * user and the system is able to write something.
2816 drawtimeout.tv_sec = 0;
2817 drawtimeout.tv_usec = 5;
2824 while(XPending(xw.dpy)) {
2825 XNextEvent(xw.dpy, &ev);
2826 if(XFilterEvent(&ev, None))
2828 if(handler[ev.type])
2829 (handler[ev.type])(&ev);
2838 main(int argc, char *argv[]) {
2839 int i, bitm, xr, yr;
2842 xw.fw = xw.fh = xw.fx = xw.fy = 0;
2845 for(i = 1; i < argc; i++) {
2846 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2849 opt_class = argv[i];
2852 /* eat every remaining arguments */
2864 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2869 if(bitm & WidthValue)
2871 if(bitm & HeightValue)
2873 if(bitm & XNegative && xw.fx == 0)
2875 if(bitm & XNegative && xw.fy == 0)
2878 if(xw.fh != 0 && xw.fw != 0)
2887 opt_title = argv[i];
2894 opt_embed = argv[i];
2900 setlocale(LC_CTYPE, "");
2901 XSetLocaleModifiers("");