1 /* See LICENSE for licence details. */
2 #define _XOPEN_SOURCE 600
15 #include <sys/ioctl.h>
16 #include <sys/select.h>
19 #include <sys/types.h>
23 #include <X11/Xatom.h>
25 #include <X11/Xutil.h>
26 #include <X11/cursorfont.h>
27 #include <X11/keysym.h>
28 #include <X11/extensions/Xdbe.h>
29 #include <X11/Xft/Xft.h>
30 #include <fontconfig/fontconfig.h>
36 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
38 #elif defined(__FreeBSD__) || defined(__DragonFly__)
43 "st " VERSION " (c) 2010-2012 st engineers\n" \
44 "usage: st [-v] [-c class] [-f font] [-g geometry] [-o file]" \
45 " [-t title] [-w windowid] [-e command ...]\n"
48 #define XEMBED_FOCUS_IN 4
49 #define XEMBED_FOCUS_OUT 5
52 #define ESC_BUF_SIZ 256
53 #define ESC_ARG_SIZ 16
54 #define STR_BUF_SIZ 256
55 #define STR_ARG_SIZ 16
56 #define DRAW_BUF_SIZ 20*1024
58 #define XK_NO_MOD UINT_MAX
61 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
64 #define CLEANMASK(mask) (mask & (ShiftMask|ControlMask|Mod1Mask|Mod2Mask|Mod3Mask|Mod4Mask|Mod5Mask))
65 #define SERRNO strerror(errno)
66 #define MIN(a, b) ((a) < (b) ? (a) : (b))
67 #define MAX(a, b) ((a) < (b) ? (b) : (a))
68 #define LEN(a) (sizeof(a) / sizeof(a[0]))
69 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
70 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
71 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
72 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
73 #define IS_SET(flag) (term.mode & (flag))
74 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
75 #define X2COL(x) (((x) - BORDER)/xw.cw)
76 #define Y2ROW(y) (((y) - BORDER)/xw.ch)
78 #define VT102ID "\033[?6c"
80 enum glyph_attribute {
90 enum cursor_movement {
117 MODE_MOUSEMOTION = 64,
126 ESC_STR = 4, /* DSC, OSC, PM, APC */
128 ESC_STR_END = 16, /* a final string was encountered */
129 ESC_TEST = 32, /* Enter in test mode */
140 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
142 typedef unsigned char uchar;
143 typedef unsigned int uint;
144 typedef unsigned long ulong;
145 typedef unsigned short ushort;
148 char c[UTF_SIZ]; /* character code */
149 uchar mode; /* attribute flags */
150 ushort fg; /* foreground */
151 ushort bg; /* background */
152 uchar state; /* state flags */
158 Glyph attr; /* current char attributes */
164 /* CSI Escape sequence structs */
165 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
167 char buf[ESC_BUF_SIZ]; /* raw string */
168 int len; /* raw string length */
170 int arg[ESC_ARG_SIZ];
171 int narg; /* nb of args */
175 /* STR Escape sequence structs */
176 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
178 char type; /* ESC type ... */
179 char buf[STR_BUF_SIZ]; /* raw string */
180 int len; /* raw string length */
181 char *args[STR_ARG_SIZ];
182 int narg; /* nb of args */
185 /* Internal representation of the screen */
187 int row; /* nb row */
188 int col; /* nb col */
189 Line *line; /* screen */
190 Line *alt; /* alternate screen */
191 bool *dirty; /* dirtyness of lines */
192 TCursor c; /* cursor */
193 int top; /* top scroll limit */
194 int bot; /* bottom scroll limit */
195 int mode; /* terminal mode flags */
196 int esc; /* escape state flags */
200 /* Purely graphic info */
206 Atom xembed, wmdeletewin;
212 bool isfixed; /* is fixed geometry? */
213 int fx, fy, fw, fh; /* fixed geometry */
214 int tw, th; /* tty width and height */
215 int w; /* window width */
216 int h; /* window height */
217 int ch; /* char height */
218 int cw; /* char width */
219 char state; /* focus, redraw, visible */
228 /* TODO: use better name for vars... */
239 struct timeval tclick1;
240 struct timeval tclick2;
253 void (*func)(const Arg *);
257 /* function definitions used in config.h */
258 static void xzoom(const Arg *);
260 /* Config.h for applying patches and the configuration. */
274 /* Drawing Context */
276 XftColor xft_col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
278 Font font, bfont, ifont, ibfont;
281 static void die(const char *, ...);
282 static void draw(void);
283 static void redraw(void);
284 static void drawregion(int, int, int, int);
285 static void execsh(void);
286 static void sigchld(int);
287 static void run(void);
289 static void csidump(void);
290 static void csihandle(void);
291 static void csiparse(void);
292 static void csireset(void);
293 static void strdump(void);
294 static void strhandle(void);
295 static void strparse(void);
296 static void strreset(void);
298 static void tclearregion(int, int, int, int);
299 static void tcursor(int);
300 static void tdeletechar(int);
301 static void tdeleteline(int);
302 static void tinsertblank(int);
303 static void tinsertblankline(int);
304 static void tmoveto(int, int);
305 static void tnew(int, int);
306 static void tnewline(int);
307 static void tputtab(bool);
308 static void tputc(char *, int);
309 static void treset(void);
310 static int tresize(int, int);
311 static void tscrollup(int, int);
312 static void tscrolldown(int, int);
313 static void tsetattr(int*, int);
314 static void tsetchar(char *, Glyph *, int, int);
315 static void tsetscroll(int, int);
316 static void tswapscreen(void);
317 static void tsetdirt(int, int);
318 static void tsetmode(bool, bool, int *, int);
319 static void tfulldirt(void);
321 static void ttynew(void);
322 static void ttyread(void);
323 static void ttyresize(void);
324 static void ttywrite(const char *, size_t);
326 static void xdraws(char *, Glyph, int, int, int, int);
327 static void xhints(void);
328 static void xclear(int, int, int, int);
329 static void xdrawcursor(void);
330 static void xinit(void);
331 static void xloadcols(void);
332 static void xresettitle(void);
333 static void xseturgency(int);
334 static void xsetsel(char*);
335 static void xtermclear(int, int, int, int);
336 static void xresize(int, int);
338 static void expose(XEvent *);
339 static void visibility(XEvent *);
340 static void unmap(XEvent *);
341 static char *kmap(KeySym, uint);
342 static void kpress(XEvent *);
343 static void cmessage(XEvent *);
344 static void cresize(int width, int height);
345 static void resize(XEvent *);
346 static void focus(XEvent *);
347 static void brelease(XEvent *);
348 static void bpress(XEvent *);
349 static void bmotion(XEvent *);
350 static void selnotify(XEvent *);
351 static void selclear(XEvent *);
352 static void selrequest(XEvent *);
354 static void selinit(void);
355 static inline bool selected(int, int);
356 static void selcopy(void);
357 static void selpaste(void);
358 static void selscroll(int, int);
360 static int utf8decode(char *, long *);
361 static int utf8encode(long *, char *);
362 static int utf8size(char *);
363 static int isfullutf8(char *, int);
365 static ssize_t xwrite(int, char *, size_t);
366 static void *xmalloc(size_t);
367 static void *xrealloc(void *, size_t);
368 static void *xcalloc(size_t nmemb, size_t size);
370 static void (*handler[LASTEvent])(XEvent *) = {
372 [ClientMessage] = cmessage,
373 [ConfigureNotify] = resize,
374 [VisibilityNotify] = visibility,
375 [UnmapNotify] = unmap,
379 [MotionNotify] = bmotion,
380 [ButtonPress] = bpress,
381 [ButtonRelease] = brelease,
382 [SelectionClear] = selclear,
383 [SelectionNotify] = selnotify,
384 [SelectionRequest] = selrequest,
391 static CSIEscape csiescseq;
392 static STREscape strescseq;
395 static Selection sel;
396 static int iofd = -1;
397 static char **opt_cmd = NULL;
398 static char *opt_io = NULL;
399 static char *opt_title = NULL;
400 static char *opt_embed = NULL;
401 static char *opt_class = NULL;
402 static char *opt_font = NULL;
404 static char *usedfont = NULL;
405 static int usedfontsize = 0;
408 xwrite(int fd, char *s, size_t len) {
412 ssize_t r = write(fd, s, len);
422 xmalloc(size_t len) {
423 void *p = malloc(len);
426 die("Out of memory\n");
432 xrealloc(void *p, size_t len) {
433 if((p = realloc(p, len)) == NULL)
434 die("Out of memory\n");
440 xcalloc(size_t nmemb, size_t size) {
441 void *p = calloc(nmemb, size);
444 die("Out of memory\n");
450 utf8decode(char *s, long *u) {
456 if(~c & B7) { /* 0xxxxxxx */
459 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
460 *u = c&(B4|B3|B2|B1|B0);
462 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
463 *u = c&(B3|B2|B1|B0);
465 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
472 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
474 if((c & (B7|B6)) != B7) /* 10xxxxxx */
477 *u |= c & (B5|B4|B3|B2|B1|B0);
480 if((n == 1 && *u < 0x80) ||
481 (n == 2 && *u < 0x800) ||
482 (n == 3 && *u < 0x10000) ||
483 (*u >= 0xD800 && *u <= 0xDFFF)) {
495 utf8encode(long *u, char *s) {
503 *sp = uc; /* 0xxxxxxx */
505 } else if(*u < 0x800) {
506 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
508 } else if(uc < 0x10000) {
509 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
511 } else if(uc <= 0x10FFFF) {
512 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
518 for(i=n,++sp; i>0; --i,++sp)
519 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
531 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
532 UTF-8 otherwise return 0 */
534 isfullutf8(char *s, int b) {
542 } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
544 } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
546 ((b == 2) && (*c2&(B7|B6)) == B7))) {
548 } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
550 ((b == 2) && (*c2&(B7|B6)) == B7) ||
551 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
564 } else if((c&(B7|B6|B5)) == (B7|B6)) {
566 } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
575 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
576 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
580 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
581 if(sel.xtarget == None)
582 sel.xtarget = XA_STRING;
586 selected(int x, int y) {
589 if(sel.ey == y && sel.by == y) {
590 bx = MIN(sel.bx, sel.ex);
591 ex = MAX(sel.bx, sel.ex);
592 return BETWEEN(x, bx, ex);
595 return ((sel.b.y < y && y < sel.e.y)
596 || (y == sel.e.y && x <= sel.e.x))
597 || (y == sel.b.y && x >= sel.b.x
598 && (x <= sel.e.x || sel.b.y != sel.e.y));
602 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
604 *b = e->xbutton.button;
606 *x = X2COL(e->xbutton.x);
607 *y = Y2ROW(e->xbutton.y);
608 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
609 sel.b.y = MIN(sel.by, sel.ey);
610 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
611 sel.e.y = MAX(sel.by, sel.ey);
615 mousereport(XEvent *e) {
616 int x = X2COL(e->xbutton.x);
617 int y = Y2ROW(e->xbutton.y);
618 int button = e->xbutton.button;
619 int state = e->xbutton.state;
620 char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
621 static int ob, ox, oy;
624 if(e->xbutton.type == MotionNotify) {
625 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
629 } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
635 if(e->xbutton.type == ButtonPress) {
641 buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
642 + (state & Mod4Mask ? 8 : 0)
643 + (state & ControlMask ? 16 : 0);
645 ttywrite(buf, sizeof(buf));
650 if(IS_SET(MODE_MOUSE)) {
652 } else if(e->xbutton.button == Button1) {
655 tsetdirt(sel.b.y, sel.e.y);
659 sel.ex = sel.bx = X2COL(e->xbutton.x);
660 sel.ey = sel.by = Y2ROW(e->xbutton.y);
667 int x, y, bufsize, is_selected = 0, size;
673 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
674 ptr = str = xmalloc(bufsize);
676 /* append every set & selected glyph to the selection */
677 for(y = 0; y < term.row; y++) {
678 for(x = 0; x < term.col; x++) {
679 gp = &term.line[y][x];
681 if(!(is_selected = selected(x, y))
682 || !(gp->state & GLYPH_SET)) {
685 size = utf8size(gp->c);
686 memcpy(ptr, gp->c, size);
689 /* \n at the end of every selected line except for the last one */
690 if(is_selected && y < sel.e.y)
695 sel.alt = IS_SET(MODE_ALTSCREEN);
700 selnotify(XEvent *e) {
701 ulong nitems, ofs, rem;
708 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
709 False, AnyPropertyType, &type, &format,
710 &nitems, &rem, &data)) {
711 fprintf(stderr, "Clipboard allocation failed\n");
714 ttywrite((const char *) data, nitems * format / 8);
716 /* number of 32-bit chunks returned */
717 ofs += nitems * format / 32;
723 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
724 xw.win, CurrentTime);
727 void selclear(XEvent *e) {
731 tsetdirt(sel.b.y, sel.e.y);
735 selrequest(XEvent *e) {
736 XSelectionRequestEvent *xsre;
738 Atom xa_targets, string;
740 xsre = (XSelectionRequestEvent *) e;
741 xev.type = SelectionNotify;
742 xev.requestor = xsre->requestor;
743 xev.selection = xsre->selection;
744 xev.target = xsre->target;
745 xev.time = xsre->time;
749 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
750 if(xsre->target == xa_targets) {
751 /* respond with the supported type */
752 string = sel.xtarget;
753 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
754 XA_ATOM, 32, PropModeReplace,
755 (uchar *) &string, 1);
756 xev.property = xsre->property;
757 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
758 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
759 xsre->target, 8, PropModeReplace,
760 (uchar *) sel.clip, strlen(sel.clip));
761 xev.property = xsre->property;
764 /* all done, send a notification to the listener */
765 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
766 fprintf(stderr, "Error sending SelectionNotify event\n");
771 /* register the selection for both the clipboard and the primary */
777 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
779 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
780 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
784 brelease(XEvent *e) {
787 if(IS_SET(MODE_MOUSE)) {
792 if(e->xbutton.button == Button2) {
794 } else if(e->xbutton.button == Button1) {
796 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
797 term.dirty[sel.ey] = 1;
798 if(sel.bx == sel.ex && sel.by == sel.ey) {
800 gettimeofday(&now, NULL);
802 if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
803 /* triple click on the line */
804 sel.b.x = sel.bx = 0;
805 sel.e.x = sel.ex = term.col;
806 sel.b.y = sel.e.y = sel.ey;
808 } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
809 /* double click to select word */
811 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
812 term.line[sel.ey][sel.bx-1].c[0] != ' ') {
816 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
817 term.line[sel.ey][sel.ex+1].c[0] != ' ') {
821 sel.b.y = sel.e.y = sel.ey;
829 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
830 gettimeofday(&sel.tclick1, NULL);
835 int starty, endy, oldey, oldex;
837 if(IS_SET(MODE_MOUSE)) {
845 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
847 if(oldey != sel.ey || oldex != sel.ex) {
848 starty = MIN(oldey, sel.ey);
849 endy = MAX(oldey, sel.ey);
850 tsetdirt(starty, endy);
856 die(const char *errstr, ...) {
859 va_start(ap, errstr);
860 vfprintf(stderr, errstr, ap);
868 char *envshell = getenv("SHELL");
869 const struct passwd *pass = getpwuid(getuid());
870 char buf[sizeof(long) * 8 + 1];
877 setenv("LOGNAME", pass->pw_name, 1);
878 setenv("USER", pass->pw_name, 1);
879 setenv("SHELL", pass->pw_shell, 0);
880 setenv("HOME", pass->pw_dir, 0);
883 snprintf(buf, sizeof(buf), "%lu", xw.win);
884 setenv("WINDOWID", buf, 1);
886 signal(SIGCHLD, SIG_DFL);
887 signal(SIGHUP, SIG_DFL);
888 signal(SIGINT, SIG_DFL);
889 signal(SIGQUIT, SIG_DFL);
890 signal(SIGTERM, SIG_DFL);
891 signal(SIGALRM, SIG_DFL);
893 DEFAULT(envshell, SHELL);
894 putenv("TERM="TNAME);
895 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
896 execvp(args[0], args);
904 if(waitpid(pid, &stat, 0) < 0)
905 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
907 if(WIFEXITED(stat)) {
908 exit(WEXITSTATUS(stat));
917 struct winsize w = {term.row, term.col, 0, 0};
919 /* seems to work fine on linux, openbsd and freebsd */
920 if(openpty(&m, &s, NULL, NULL, &w) < 0)
921 die("openpty failed: %s\n", SERRNO);
923 switch(pid = fork()) {
925 die("fork failed\n");
928 setsid(); /* create a new process group */
929 dup2(s, STDIN_FILENO);
930 dup2(s, STDOUT_FILENO);
931 dup2(s, STDERR_FILENO);
932 if(ioctl(s, TIOCSCTTY, NULL) < 0)
933 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
941 signal(SIGCHLD, sigchld);
943 iofd = (!strcmp(opt_io, "-")) ?
945 open(opt_io, O_WRONLY | O_CREAT, 0666);
947 fprintf(stderr, "Error opening %s:%s\n",
948 opt_io, strerror(errno));
958 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
960 fprintf(stderr, "\n");
965 static char buf[BUFSIZ];
966 static int buflen = 0;
969 int charsize; /* size of utf8 char in bytes */
973 /* append read bytes to unprocessed bytes */
974 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
975 die("Couldn't read from shell: %s\n", SERRNO);
977 /* process every complete utf8 char */
980 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
981 charsize = utf8decode(ptr, &utf8c);
982 utf8encode(&utf8c, s);
988 /* keep any uncomplete utf8 char for the next call */
989 memmove(buf, ptr, buflen);
993 ttywrite(const char *s, size_t n) {
994 if(write(cmdfd, s, n) == -1)
995 die("write error on tty: %s\n", SERRNO);
1002 w.ws_row = term.row;
1003 w.ws_col = term.col;
1004 w.ws_xpixel = xw.tw;
1005 w.ws_ypixel = xw.th;
1006 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1007 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1011 tsetdirt(int top, int bot) {
1014 LIMIT(top, 0, term.row-1);
1015 LIMIT(bot, 0, term.row-1);
1017 for(i = top; i <= bot; i++)
1023 tsetdirt(0, term.row-1);
1030 if(mode == CURSOR_SAVE) {
1032 } else if(mode == CURSOR_LOAD) {
1042 term.c = (TCursor){{
1046 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1048 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1049 for(i = TAB; i < term.col; i += TAB)
1052 term.bot = term.row - 1;
1053 term.mode = MODE_WRAP;
1055 tclearregion(0, 0, term.col-1, term.row-1);
1059 tnew(int col, int row) {
1060 /* set screen size */
1063 term.line = xmalloc(term.row * sizeof(Line));
1064 term.alt = xmalloc(term.row * sizeof(Line));
1065 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1066 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1068 for(row = 0; row < term.row; row++) {
1069 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1070 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1071 term.dirty[row] = 0;
1073 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1080 Line *tmp = term.line;
1082 term.line = term.alt;
1084 term.mode ^= MODE_ALTSCREEN;
1089 tscrolldown(int orig, int n) {
1093 LIMIT(n, 0, term.bot-orig+1);
1095 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1097 for(i = term.bot; i >= orig+n; i--) {
1098 temp = term.line[i];
1099 term.line[i] = term.line[i-n];
1100 term.line[i-n] = temp;
1103 term.dirty[i-n] = 1;
1110 tscrollup(int orig, int n) {
1113 LIMIT(n, 0, term.bot-orig+1);
1115 tclearregion(0, orig, term.col-1, orig+n-1);
1117 for(i = orig; i <= term.bot-n; i++) {
1118 temp = term.line[i];
1119 term.line[i] = term.line[i+n];
1120 term.line[i+n] = temp;
1123 term.dirty[i+n] = 1;
1126 selscroll(orig, -n);
1130 selscroll(int orig, int n) {
1134 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1135 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1139 if(sel.by < term.top) {
1143 if(sel.ey > term.bot) {
1147 sel.b.y = sel.by, sel.b.x = sel.bx;
1148 sel.e.y = sel.ey, sel.e.x = sel.ex;
1153 tnewline(int first_col) {
1157 tscrollup(term.top, 1);
1161 tmoveto(first_col ? 0 : term.c.x, y);
1166 /* int noarg = 1; */
1167 char *p = csiescseq.buf;
1171 csiescseq.priv = 1, p++;
1173 while(p < csiescseq.buf+csiescseq.len) {
1174 while(isdigit(*p)) {
1175 csiescseq.arg[csiescseq.narg] *= 10;
1176 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1178 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1179 csiescseq.narg++, p++;
1181 csiescseq.mode = *p;
1190 tmoveto(int x, int y) {
1191 LIMIT(x, 0, term.col-1);
1192 LIMIT(y, 0, term.row-1);
1193 term.c.state &= ~CURSOR_WRAPNEXT;
1199 tsetchar(char *c, Glyph *attr, int x, int y) {
1200 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1201 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1202 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1203 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1204 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1205 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1206 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1207 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1208 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1212 * The table is proudly stolen from rxvt.
1214 if(attr->mode & ATTR_GFX) {
1215 if(c[0] >= 0x41 && c[0] <= 0x7e
1216 && vt100_0[c[0] - 0x41]) {
1217 c = vt100_0[c[0] - 0x41];
1222 term.line[y][x] = *attr;
1223 memcpy(term.line[y][x].c, c, UTF_SIZ);
1224 term.line[y][x].state |= GLYPH_SET;
1228 tclearregion(int x1, int y1, int x2, int y2) {
1232 temp = x1, x1 = x2, x2 = temp;
1234 temp = y1, y1 = y2, y2 = temp;
1236 LIMIT(x1, 0, term.col-1);
1237 LIMIT(x2, 0, term.col-1);
1238 LIMIT(y1, 0, term.row-1);
1239 LIMIT(y2, 0, term.row-1);
1241 for(y = y1; y <= y2; y++) {
1243 for(x = x1; x <= x2; x++)
1244 term.line[y][x].state = 0;
1249 tdeletechar(int n) {
1250 int src = term.c.x + n;
1252 int size = term.col - src;
1254 term.dirty[term.c.y] = 1;
1256 if(src >= term.col) {
1257 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1261 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1262 size * sizeof(Glyph));
1263 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1267 tinsertblank(int n) {
1270 int size = term.col - dst;
1272 term.dirty[term.c.y] = 1;
1274 if(dst >= term.col) {
1275 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1279 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1280 size * sizeof(Glyph));
1281 tclearregion(src, term.c.y, dst - 1, term.c.y);
1285 tinsertblankline(int n) {
1286 if(term.c.y < term.top || term.c.y > term.bot)
1289 tscrolldown(term.c.y, n);
1293 tdeleteline(int n) {
1294 if(term.c.y < term.top || term.c.y > term.bot)
1297 tscrollup(term.c.y, n);
1301 tsetattr(int *attr, int l) {
1304 for(i = 0; i < l; i++) {
1307 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1308 | ATTR_ITALIC | ATTR_BLINK);
1309 term.c.attr.fg = DefaultFG;
1310 term.c.attr.bg = DefaultBG;
1313 term.c.attr.mode |= ATTR_BOLD;
1315 case 3: /* enter standout (highlight) */
1316 term.c.attr.mode |= ATTR_ITALIC;
1319 term.c.attr.mode |= ATTR_UNDERLINE;
1322 term.c.attr.mode |= ATTR_BLINK;
1325 term.c.attr.mode |= ATTR_REVERSE;
1329 term.c.attr.mode &= ~ATTR_BOLD;
1331 case 23: /* leave standout (highlight) mode */
1332 term.c.attr.mode &= ~ATTR_ITALIC;
1335 term.c.attr.mode &= ~ATTR_UNDERLINE;
1338 term.c.attr.mode &= ~ATTR_BLINK;
1341 term.c.attr.mode &= ~ATTR_REVERSE;
1344 if(i + 2 < l && attr[i + 1] == 5) {
1346 if(BETWEEN(attr[i], 0, 255)) {
1347 term.c.attr.fg = attr[i];
1350 "erresc: bad fgcolor %d\n",
1355 "erresc(38): gfx attr %d unknown\n",
1360 term.c.attr.fg = DefaultFG;
1363 if(i + 2 < l && attr[i + 1] == 5) {
1365 if(BETWEEN(attr[i], 0, 255)) {
1366 term.c.attr.bg = attr[i];
1369 "erresc: bad bgcolor %d\n",
1374 "erresc(48): gfx attr %d unknown\n",
1379 term.c.attr.bg = DefaultBG;
1382 if(BETWEEN(attr[i], 30, 37)) {
1383 term.c.attr.fg = attr[i] - 30;
1384 } else if(BETWEEN(attr[i], 40, 47)) {
1385 term.c.attr.bg = attr[i] - 40;
1386 } else if(BETWEEN(attr[i], 90, 97)) {
1387 term.c.attr.fg = attr[i] - 90 + 8;
1388 } else if(BETWEEN(attr[i], 100, 107)) {
1389 term.c.attr.bg = attr[i] - 100 + 8;
1392 "erresc(default): gfx attr %d unknown\n",
1393 attr[i]), csidump();
1401 tsetscroll(int t, int b) {
1404 LIMIT(t, 0, term.row-1);
1405 LIMIT(b, 0, term.row-1);
1415 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1418 tsetmode(bool priv, bool set, int *args, int narg) {
1421 for(lim = args + narg; args < lim; ++args) {
1425 case 1: /* DECCKM -- Cursor key */
1426 MODBIT(term.mode, set, MODE_APPKEYPAD);
1428 case 5: /* DECSCNM -- Reverse video */
1430 MODBIT(term.mode, set, MODE_REVERSE);
1431 if(mode != term.mode)
1434 case 6: /* XXX: DECOM -- Origin */
1436 case 7: /* DECAWM -- Auto wrap */
1437 MODBIT(term.mode, set, MODE_WRAP);
1439 case 8: /* XXX: DECARM -- Auto repeat */
1441 case 0: /* Error (IGNORED) */
1442 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1445 MODBIT(term.c.state, !set, CURSOR_HIDE);
1447 case 1000: /* 1000,1002: enable xterm mouse report */
1448 MODBIT(term.mode, set, MODE_MOUSEBTN);
1451 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1453 case 1049: /* = 1047 and 1048 */
1456 if(IS_SET(MODE_ALTSCREEN))
1457 tclearregion(0, 0, term.col-1, term.row-1);
1458 if((set && !IS_SET(MODE_ALTSCREEN)) ||
1459 (!set && IS_SET(MODE_ALTSCREEN))) {
1466 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1469 /* case 2: DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
1470 /* case 3: DECCOLM -- Column (NOT SUPPORTED) */
1471 /* case 4: DECSCLM -- Scroll (NOT SUPPORTED) */
1472 /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
1473 /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
1474 /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
1476 "erresc: unknown private set/reset mode %d\n",
1482 case 0: /* Error (IGNORED) */
1484 case 2: /* KAM -- keyboard action */
1485 MODBIT(term.mode, set, MODE_KBDLOCK);
1487 case 4: /* IRM -- Insertion-replacement */
1488 MODBIT(term.mode, set, MODE_INSERT);
1490 case 12: /* XXX: SRM -- Send/Receive */
1492 case 20: /* LNM -- Linefeed/new line */
1493 MODBIT(term.mode, set, MODE_CRLF);
1497 "erresc: unknown set/reset mode %d\n",
1509 switch(csiescseq.mode) {
1512 fprintf(stderr, "erresc: unknown csi ");
1516 case '@': /* ICH -- Insert <n> blank char */
1517 DEFAULT(csiescseq.arg[0], 1);
1518 tinsertblank(csiescseq.arg[0]);
1520 case 'A': /* CUU -- Cursor <n> Up */
1522 DEFAULT(csiescseq.arg[0], 1);
1523 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1525 case 'B': /* CUD -- Cursor <n> Down */
1526 DEFAULT(csiescseq.arg[0], 1);
1527 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1529 case 'c': /* DA -- Device Attributes */
1530 if(csiescseq.arg[0] == 0)
1531 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1533 case 'C': /* CUF -- Cursor <n> Forward */
1535 DEFAULT(csiescseq.arg[0], 1);
1536 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1538 case 'D': /* CUB -- Cursor <n> Backward */
1539 DEFAULT(csiescseq.arg[0], 1);
1540 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1542 case 'E': /* CNL -- Cursor <n> Down and first col */
1543 DEFAULT(csiescseq.arg[0], 1);
1544 tmoveto(0, term.c.y+csiescseq.arg[0]);
1546 case 'F': /* CPL -- Cursor <n> Up and first col */
1547 DEFAULT(csiescseq.arg[0], 1);
1548 tmoveto(0, term.c.y-csiescseq.arg[0]);
1550 case 'g': /* TBC -- Tabulation clear */
1551 switch (csiescseq.arg[0]) {
1552 case 0: /* clear current tab stop */
1553 term.tabs[term.c.x] = 0;
1555 case 3: /* clear all the tabs */
1556 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1562 case 'G': /* CHA -- Move to <col> */
1564 DEFAULT(csiescseq.arg[0], 1);
1565 tmoveto(csiescseq.arg[0]-1, term.c.y);
1567 case 'H': /* CUP -- Move to <row> <col> */
1569 DEFAULT(csiescseq.arg[0], 1);
1570 DEFAULT(csiescseq.arg[1], 1);
1571 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1573 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1574 DEFAULT(csiescseq.arg[0], 1);
1575 while(csiescseq.arg[0]--)
1578 case 'J': /* ED -- Clear screen */
1580 switch(csiescseq.arg[0]) {
1582 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1583 if(term.c.y < term.row-1)
1584 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1588 tclearregion(0, 0, term.col-1, term.c.y-1);
1589 tclearregion(0, term.c.y, term.c.x, term.c.y);
1592 tclearregion(0, 0, term.col-1, term.row-1);
1598 case 'K': /* EL -- Clear line */
1599 switch(csiescseq.arg[0]) {
1601 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1604 tclearregion(0, term.c.y, term.c.x, term.c.y);
1607 tclearregion(0, term.c.y, term.col-1, term.c.y);
1611 case 'S': /* SU -- Scroll <n> line up */
1612 DEFAULT(csiescseq.arg[0], 1);
1613 tscrollup(term.top, csiescseq.arg[0]);
1615 case 'T': /* SD -- Scroll <n> line down */
1616 DEFAULT(csiescseq.arg[0], 1);
1617 tscrolldown(term.top, csiescseq.arg[0]);
1619 case 'L': /* IL -- Insert <n> blank lines */
1620 DEFAULT(csiescseq.arg[0], 1);
1621 tinsertblankline(csiescseq.arg[0]);
1623 case 'l': /* RM -- Reset Mode */
1624 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1626 case 'M': /* DL -- Delete <n> lines */
1627 DEFAULT(csiescseq.arg[0], 1);
1628 tdeleteline(csiescseq.arg[0]);
1630 case 'X': /* ECH -- Erase <n> char */
1631 DEFAULT(csiescseq.arg[0], 1);
1632 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1634 case 'P': /* DCH -- Delete <n> char */
1635 DEFAULT(csiescseq.arg[0], 1);
1636 tdeletechar(csiescseq.arg[0]);
1638 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1639 DEFAULT(csiescseq.arg[0], 1);
1640 while(csiescseq.arg[0]--)
1643 case 'd': /* VPA -- Move to <row> */
1644 DEFAULT(csiescseq.arg[0], 1);
1645 tmoveto(term.c.x, csiescseq.arg[0]-1);
1647 case 'h': /* SM -- Set terminal mode */
1648 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1650 case 'm': /* SGR -- Terminal attribute (color) */
1651 tsetattr(csiescseq.arg, csiescseq.narg);
1653 case 'r': /* DECSTBM -- Set Scrolling Region */
1654 if(csiescseq.priv) {
1657 DEFAULT(csiescseq.arg[0], 1);
1658 DEFAULT(csiescseq.arg[1], term.row);
1659 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1663 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1664 tcursor(CURSOR_SAVE);
1666 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1667 tcursor(CURSOR_LOAD);
1678 for(i = 0; i < csiescseq.len; i++) {
1679 c = csiescseq.buf[i] & 0xff;
1682 } else if(c == '\n') {
1684 } else if(c == '\r') {
1686 } else if(c == 0x1b) {
1689 printf("(%02x)", c);
1697 memset(&csiescseq, 0, sizeof(csiescseq));
1705 * TODO: make this being useful in case of color palette change.
1711 switch(strescseq.type) {
1712 case ']': /* OSC -- Operating System Command */
1718 * TODO: Handle special chars in string, like umlauts.
1721 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1725 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1727 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1730 fprintf(stderr, "erresc: unknown str ");
1735 case 'k': /* old title set compatibility */
1736 XStoreName(xw.dpy, xw.win, strescseq.buf);
1738 case 'P': /* DSC -- Device Control String */
1739 case '_': /* APC -- Application Program Command */
1740 case '^': /* PM -- Privacy Message */
1742 fprintf(stderr, "erresc: unknown str ");
1752 * TODO: Implement parsing like for CSI when required.
1753 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1763 printf("ESC%c", strescseq.type);
1764 for(i = 0; i < strescseq.len; i++) {
1765 c = strescseq.buf[i] & 0xff;
1768 } else if(c == '\n') {
1770 } else if(c == '\r') {
1772 } else if(c == 0x1b) {
1775 printf("(%02x)", c);
1783 memset(&strescseq, 0, sizeof(strescseq));
1787 tputtab(bool forward) {
1793 for(++x; x < term.col && !term.tabs[x]; ++x)
1798 for(--x; x > 0 && !term.tabs[x]; --x)
1801 tmoveto(x, term.c.y);
1805 tputc(char *c, int len) {
1807 bool control = ascii < '\x20' || ascii == 0177;
1810 if (xwrite(iofd, c, len) < 0) {
1811 fprintf(stderr, "Error writting in %s:%s\n",
1812 opt_io, strerror(errno));
1818 * STR sequences must be checked before of anything
1819 * because it can use some control codes as part of the sequence
1821 if(term.esc & ESC_STR) {
1824 term.esc = ESC_START | ESC_STR_END;
1826 case '\a': /* backwards compatibility to xterm */
1831 strescseq.buf[strescseq.len++] = ascii;
1832 if(strescseq.len+1 >= STR_BUF_SIZ) {
1840 * Actions of control codes must be performed as soon they arrive
1841 * because they can be embedded inside a control sequence, and
1842 * they must not cause conflicts with sequences.
1850 tmoveto(term.c.x-1, term.c.y);
1853 tmoveto(0, term.c.y);
1858 /* go to first col if the mode is set */
1859 tnewline(IS_SET(MODE_CRLF));
1861 case '\a': /* BEL */
1862 if(!(xw.state & WIN_FOCUSED))
1865 case '\033': /* ESC */
1867 term.esc = ESC_START;
1869 case '\016': /* SO */
1870 term.c.attr.mode |= ATTR_GFX;
1872 case '\017': /* SI */
1873 term.c.attr.mode &= ~ATTR_GFX;
1875 case '\032': /* SUB */
1876 case '\030': /* CAN */
1879 case '\005': /* ENQ (IGNORED) */
1880 case '\000': /* NUL (IGNORED) */
1881 case '\021': /* XON (IGNORED) */
1882 case '\023': /* XOFF (IGNORED) */
1883 case 0177: /* DEL (IGNORED) */
1886 } else if(term.esc & ESC_START) {
1887 if(term.esc & ESC_CSI) {
1888 csiescseq.buf[csiescseq.len++] = ascii;
1889 if(BETWEEN(ascii, 0x40, 0x7E)
1890 || csiescseq.len >= ESC_BUF_SIZ) {
1892 csiparse(), csihandle();
1894 } else if(term.esc & ESC_STR_END) {
1898 } else if(term.esc & ESC_ALTCHARSET) {
1900 case '0': /* Line drawing set */
1901 term.c.attr.mode |= ATTR_GFX;
1903 case 'B': /* USASCII */
1904 term.c.attr.mode &= ~ATTR_GFX;
1906 case 'A': /* UK (IGNORED) */
1907 case '<': /* multinational charset (IGNORED) */
1908 case '5': /* Finnish (IGNORED) */
1909 case 'C': /* Finnish (IGNORED) */
1910 case 'K': /* German (IGNORED) */
1913 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1916 } else if(term.esc & ESC_TEST) {
1917 if(ascii == '8') { /* DEC screen alignment test. */
1918 char E[UTF_SIZ] = "E";
1921 for(x = 0; x < term.col; ++x) {
1922 for(y = 0; y < term.row; ++y)
1923 tsetchar(E, &term.c.attr, x, y);
1930 term.esc |= ESC_CSI;
1933 term.esc |= ESC_TEST;
1935 case 'P': /* DCS -- Device Control String */
1936 case '_': /* APC -- Application Program Command */
1937 case '^': /* PM -- Privacy Message */
1938 case ']': /* OSC -- Operating System Command */
1939 case 'k': /* old title set compatibility */
1941 strescseq.type = ascii;
1942 term.esc |= ESC_STR;
1944 case '(': /* set primary charset G0 */
1945 term.esc |= ESC_ALTCHARSET;
1947 case ')': /* set secondary charset G1 (IGNORED) */
1948 case '*': /* set tertiary charset G2 (IGNORED) */
1949 case '+': /* set quaternary charset G3 (IGNORED) */
1952 case 'D': /* IND -- Linefeed */
1953 if(term.c.y == term.bot) {
1954 tscrollup(term.top, 1);
1956 tmoveto(term.c.x, term.c.y+1);
1960 case 'E': /* NEL -- Next line */
1961 tnewline(1); /* always go to first col */
1964 case 'H': /* HTS -- Horizontal tab stop */
1965 term.tabs[term.c.x] = 1;
1968 case 'M': /* RI -- Reverse index */
1969 if(term.c.y == term.top) {
1970 tscrolldown(term.top, 1);
1972 tmoveto(term.c.x, term.c.y-1);
1976 case 'Z': /* DECID -- Identify Terminal */
1977 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1980 case 'c': /* RIS -- Reset to inital state */
1985 case '=': /* DECPAM -- Application keypad */
1986 term.mode |= MODE_APPKEYPAD;
1989 case '>': /* DECPNM -- Normal keypad */
1990 term.mode &= ~MODE_APPKEYPAD;
1993 case '7': /* DECSC -- Save Cursor */
1994 tcursor(CURSOR_SAVE);
1997 case '8': /* DECRC -- Restore Cursor */
1998 tcursor(CURSOR_LOAD);
2001 case '\\': /* ST -- Stop */
2005 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2006 (uchar) ascii, isprint(ascii)? ascii:'.');
2011 * All characters which forms part of a sequence are not
2017 * Display control codes only if we are in graphic mode
2019 if(control && !(term.c.attr.mode & ATTR_GFX))
2021 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2023 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
2024 tnewline(1); /* always go to first col */
2025 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2026 if(term.c.x+1 < term.col)
2027 tmoveto(term.c.x+1, term.c.y);
2029 term.c.state |= CURSOR_WRAPNEXT;
2033 tresize(int col, int row) {
2035 int minrow = MIN(row, term.row);
2036 int mincol = MIN(col, term.col);
2037 int slide = term.c.y - row + 1;
2040 if(col < 1 || row < 1)
2043 /* free unneeded rows */
2046 /* slide screen to keep cursor where we expect it -
2047 * tscrollup would work here, but we can optimize to
2048 * memmove because we're freeing the earlier lines */
2049 for(/* i = 0 */; i < slide; i++) {
2053 memmove(term.line, term.line + slide, row * sizeof(Line));
2054 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2056 for(i += row; i < term.row; i++) {
2061 /* resize to new height */
2062 term.line = xrealloc(term.line, row * sizeof(Line));
2063 term.alt = xrealloc(term.alt, row * sizeof(Line));
2064 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2065 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2067 /* resize each row to new width, zero-pad if needed */
2068 for(i = 0; i < minrow; i++) {
2070 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2071 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2072 for(x = mincol; x < col; x++) {
2073 term.line[i][x].state = 0;
2074 term.alt[i][x].state = 0;
2078 /* allocate any new rows */
2079 for(/* i == minrow */; i < row; i++) {
2081 term.line[i] = xcalloc(col, sizeof(Glyph));
2082 term.alt [i] = xcalloc(col, sizeof(Glyph));
2084 if(col > term.col) {
2085 bp = term.tabs + term.col;
2087 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2088 while(--bp > term.tabs && !*bp)
2090 for(bp += TAB; bp < term.tabs + col; bp += TAB)
2093 /* update terminal size */
2096 /* make use of the LIMIT in tmoveto */
2097 tmoveto(term.c.x, term.c.y);
2098 /* reset scrolling region */
2099 tsetscroll(0, row-1);
2105 xresize(int col, int row) {
2106 xw.tw = MAX(1, 2*BORDER + col * xw.cw);
2107 xw.th = MAX(1, 2*BORDER + row * xw.ch);
2109 XftDrawChange(xw.xft_draw, xw.buf);
2115 XRenderColor xft_color = { .alpha = 0 };
2117 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2118 for(i = 0; i < LEN(colorname); i++) {
2121 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
2122 die("Could not allocate color '%s'\n", colorname[i]);
2126 /* load colors [16-255] ; same colors as xterm */
2127 for(i = 16, r = 0; r < 6; r++) {
2128 for(g = 0; g < 6; g++) {
2129 for(b = 0; b < 6; b++) {
2130 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
2131 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
2132 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
2133 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
2134 die("Could not allocate color %d\n", i);
2141 for(r = 0; r < 24; r++, i++) {
2142 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
2143 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color,
2145 die("Could not allocate color %d\n", i);
2151 xtermclear(int col1, int row1, int col2, int row2) {
2152 XftDrawRect(xw.xft_draw,
2153 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2154 BORDER + col1 * xw.cw,
2155 BORDER + row1 * xw.ch,
2156 (col2-col1+1) * xw.cw,
2157 (row2-row1+1) * xw.ch);
2161 * Absolute coordinates.
2164 xclear(int x1, int y1, int x2, int y2) {
2165 XftDrawRect(xw.xft_draw,
2166 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2167 x1, y1, x2-x1, y2-y1);
2172 XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
2173 XWMHints wm = {.flags = InputHint, .input = 1};
2174 XSizeHints *sizeh = NULL;
2176 sizeh = XAllocSizeHints();
2177 if(xw.isfixed == False) {
2178 sizeh->flags = PSize | PResizeInc | PBaseSize;
2179 sizeh->height = xw.h;
2180 sizeh->width = xw.w;
2181 sizeh->height_inc = xw.ch;
2182 sizeh->width_inc = xw.cw;
2183 sizeh->base_height = 2*BORDER;
2184 sizeh->base_width = 2*BORDER;
2186 sizeh->flags = PMaxSize | PMinSize;
2187 sizeh->min_width = sizeh->max_width = xw.fw;
2188 sizeh->min_height = sizeh->max_height = xw.fh;
2191 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2196 xloadfont(Font *f, FcPattern *pattern) {
2200 match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
2203 if(!(f->xft_set = XftFontOpenPattern(xw.dpy, match))) {
2204 FcPatternDestroy(match);
2208 f->ascent = f->xft_set->ascent;
2209 f->descent = f->xft_set->descent;
2211 f->rbearing = f->xft_set->max_advance_width;
2213 f->height = f->xft_set->height;
2214 f->width = f->lbearing + f->rbearing;
2220 xloadfonts(char *fontstr, int fontsize) {
2225 pattern = FcNameParse((FcChar8 *)fontstr);
2227 die("st: can't open font %s\n", fontstr);
2230 FcPatternDel(pattern, FC_PIXEL_SIZE);
2231 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2232 usedfontsize = fontsize;
2234 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2235 if(result == FcResultMatch) {
2236 usedfontsize = (int)fontval;
2239 * Default font size is 12, if none given. This is to
2240 * have a known usedfontsize value.
2242 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2247 if(xloadfont(&dc.font, pattern))
2248 die("st: can't open font %s\n", fontstr);
2250 /* Setting character width and height. */
2251 xw.cw = dc.font.width;
2252 xw.ch = dc.font.height;
2254 FcPatternDel(pattern, FC_WEIGHT);
2255 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2256 if(xloadfont(&dc.bfont, pattern))
2257 die("st: can't open font %s\n", fontstr);
2259 FcPatternDel(pattern, FC_SLANT);
2260 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2261 if(xloadfont(&dc.ibfont, pattern))
2262 die("st: can't open font %s\n", fontstr);
2264 FcPatternDel(pattern, FC_WEIGHT);
2265 if(xloadfont(&dc.ifont, pattern))
2266 die("st: can't open font %s\n", fontstr);
2268 FcPatternDestroy(pattern);
2272 xzoom(const Arg *arg)
2274 xloadfonts(usedfont, usedfontsize + arg->i);
2281 XSetWindowAttributes attrs;
2284 int sw, sh, major, minor;
2286 if(!(xw.dpy = XOpenDisplay(NULL)))
2287 die("Can't open display\n");
2288 xw.scr = XDefaultScreen(xw.dpy);
2289 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2292 usedfont = (opt_font == NULL)? FONT : opt_font;
2293 xloadfonts(usedfont, 0);
2296 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2299 /* adjust fixed window geometry */
2301 sw = DisplayWidth(xw.dpy, xw.scr);
2302 sh = DisplayHeight(xw.dpy, xw.scr);
2304 xw.fx = sw + xw.fx - xw.fw - 1;
2306 xw.fy = sh + xw.fy - xw.fh - 1;
2311 /* window - default size */
2312 xw.h = 2*BORDER + term.row * xw.ch;
2313 xw.w = 2*BORDER + term.col * xw.cw;
2318 attrs.background_pixel = dc.xft_col[DefaultBG].pixel;
2319 attrs.border_pixel = dc.xft_col[DefaultBG].pixel;
2320 attrs.bit_gravity = NorthWestGravity;
2321 attrs.event_mask = FocusChangeMask | KeyPressMask
2322 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2323 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2324 attrs.colormap = xw.cmap;
2326 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2327 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2328 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2330 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2334 /* double buffering */
2335 if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2336 die("Xdbe extension is not present\n");
2337 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2339 /* Xft rendering context */
2340 xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2343 xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2344 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2345 | XIMStatusNothing, XNClientWindow, xw.win,
2346 XNFocusWindow, xw.win, NULL);
2348 dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2350 /* white cursor, black outline */
2351 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2352 XDefineCursor(xw.dpy, xw.win, cursor);
2353 XRecolorCursor(xw.dpy, cursor,
2354 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2355 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2357 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2358 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2359 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2362 XMapWindow(xw.dpy, xw.win);
2368 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2369 int winx = BORDER + x * xw.cw, winy = BORDER + y * xw.ch,
2370 width = charlen * xw.cw;
2371 Font *font = &dc.font;
2373 XftColor *fg = &dc.xft_col[base.fg], *bg = &dc.xft_col[base.bg],
2374 *temp, revfg, revbg;
2375 XRenderColor colfg, colbg;
2377 if(base.mode & ATTR_REVERSE)
2378 temp = fg, fg = bg, bg = temp;
2380 if(base.mode & ATTR_BOLD) {
2381 if(BETWEEN(base.fg, 0, 7)) {
2382 /* basic system colors */
2383 fg = &dc.xft_col[base.fg + 8];
2384 } else if(BETWEEN(base.fg, 16, 195)) {
2386 fg = &dc.xft_col[base.fg + 36];
2387 } else if(BETWEEN(base.fg, 232, 251)) {
2389 fg = &dc.xft_col[base.fg + 4];
2392 * Those ranges will not be brightened:
2393 * 8 - 15 – bright system colors
2394 * 196 - 231 – highest 256 color cube
2395 * 252 - 255 – brightest colors in greyscale
2400 if(base.mode & ATTR_ITALIC)
2402 if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
2405 if(IS_SET(MODE_REVERSE)) {
2406 if(fg == &dc.xft_col[DefaultFG]) {
2407 fg = &dc.xft_col[DefaultBG];
2409 colfg.red = ~fg->color.red;
2410 colfg.green = ~fg->color.green;
2411 colfg.blue = ~fg->color.blue;
2412 colfg.alpha = fg->color.alpha;
2413 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2417 if(bg == &dc.xft_col[DefaultBG]) {
2418 bg = &dc.xft_col[DefaultFG];
2420 colbg.red = ~bg->color.red;
2421 colbg.green = ~bg->color.green;
2422 colbg.blue = ~bg->color.blue;
2423 colbg.alpha = bg->color.alpha;
2424 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2429 XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen,
2431 width = extents.xOff;
2433 /* Intelligent cleaning up of the borders. */
2435 xclear(0, (y == 0)? 0 : winy, BORDER,
2436 winy + xw.ch + (y == term.row-1)? xw.h : 0);
2438 if(x + charlen >= term.col-1) {
2439 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2440 (y == term.row-1)? xw.h : (winy + xw.ch));
2443 xclear(winx, 0, winx + width, BORDER);
2445 xclear(winx, winy + xw.ch, winx + width, xw.h);
2447 XftDrawRect(xw.xft_draw, bg, winx, winy, width, xw.ch);
2448 XftDrawStringUtf8(xw.xft_draw, fg, font->xft_set, winx,
2449 winy + font->ascent, (FcChar8 *)s, bytelen);
2451 if(base.mode & ATTR_UNDERLINE) {
2452 XftDrawRect(xw.xft_draw, fg, winx, winy + font->ascent + 1,
2459 static int oldx = 0, oldy = 0;
2461 Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
2463 LIMIT(oldx, 0, term.col-1);
2464 LIMIT(oldy, 0, term.row-1);
2466 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2467 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2469 /* remove the old cursor */
2470 if(term.line[oldy][oldx].state & GLYPH_SET) {
2471 sl = utf8size(term.line[oldy][oldx].c);
2472 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2475 xtermclear(oldx, oldy, oldx, oldy);
2478 /* draw the new one */
2479 if(!(term.c.state & CURSOR_HIDE)) {
2480 if(!(xw.state & WIN_FOCUSED))
2483 if(IS_SET(MODE_REVERSE))
2484 g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
2487 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2488 oldx = term.c.x, oldy = term.c.y;
2494 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2499 struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2503 XSync(xw.dpy, False); /* necessary for a good tput flash */
2504 nanosleep(&tv, NULL);
2509 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2511 drawregion(0, 0, term.col, term.row);
2512 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2516 drawregion(int x1, int y1, int x2, int y2) {
2517 int ic, ib, x, y, ox, sl;
2519 char buf[DRAW_BUF_SIZ];
2520 bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
2522 if((sel.alt && !alt) || (!sel.alt && alt))
2524 if(!(xw.state & WIN_VISIBLE))
2527 for(y = y1; y < y2; y++) {
2531 xtermclear(0, y, term.col, y);
2533 base = term.line[y][0];
2535 for(x = x1; x < x2; x++) {
2536 new = term.line[y][x];
2537 if(ena_sel && *(new.c) && selected(x, y))
2538 new.mode ^= ATTR_REVERSE;
2539 if(ib > 0 && (!(new.state & GLYPH_SET)
2540 || ATTRCMP(base, new)
2541 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2542 xdraws(buf, base, ox, y, ic, ib);
2545 if(new.state & GLYPH_SET) {
2550 sl = utf8size(new.c);
2551 memcpy(buf+ib, new.c, sl);
2557 xdraws(buf, base, ox, y, ic, ib);
2563 expose(XEvent *ev) {
2564 XExposeEvent *e = &ev->xexpose;
2566 if(xw.state & WIN_REDRAW) {
2568 xw.state &= ~WIN_REDRAW;
2573 visibility(XEvent *ev) {
2574 XVisibilityEvent *e = &ev->xvisibility;
2576 if(e->state == VisibilityFullyObscured) {
2577 xw.state &= ~WIN_VISIBLE;
2578 } else if(!(xw.state & WIN_VISIBLE)) {
2579 /* need a full redraw for next Expose, not just a buf copy */
2580 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2586 xw.state &= ~WIN_VISIBLE;
2590 xseturgency(int add) {
2591 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2593 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2594 XSetWMHints(xw.dpy, xw.win, h);
2600 if(ev->type == FocusIn) {
2601 xw.state |= WIN_FOCUSED;
2604 xw.state &= ~WIN_FOCUSED;
2609 kmap(KeySym k, uint state) {
2614 for(i = 0; i < LEN(key); i++) {
2617 if(key[i].k == k && ((state & mask) == mask
2618 || (mask == XK_NO_MOD && !state))) {
2619 return (char*)key[i].s;
2626 kpress(XEvent *ev) {
2627 XKeyEvent *e = &ev->xkey;
2629 char buf[32], *customkey;
2630 int len, meta, shift, i;
2633 if (IS_SET(MODE_KBDLOCK))
2636 meta = e->state & Mod1Mask;
2637 shift = e->state & ShiftMask;
2638 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2641 for(i = 0; i < LEN(shortcuts); i++) {
2642 if((ksym == shortcuts[i].keysym)
2643 && (CLEANMASK(shortcuts[i].mod) == \
2644 CLEANMASK(e->state))
2645 && shortcuts[i].func) {
2646 shortcuts[i].func(&(shortcuts[i].arg));
2650 /* 2. custom keys from config.h */
2651 if((customkey = kmap(ksym, e->state))) {
2652 ttywrite(customkey, strlen(customkey));
2653 /* 2. hardcoded (overrides X lookup) */
2660 /* XXX: shift up/down doesn't work */
2661 sprintf(buf, "\033%c%c",
2662 IS_SET(MODE_APPKEYPAD) ? 'O' : '[',
2663 (shift ? "dacb":"DACB")[ksym - XK_Left]);
2671 if(IS_SET(MODE_CRLF)) {
2672 ttywrite("\r\n", 2);
2680 if(meta && len == 1)
2681 ttywrite("\033", 1);
2690 cmessage(XEvent *e) {
2692 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2693 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2694 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2695 xw.state |= WIN_FOCUSED;
2697 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2698 xw.state &= ~WIN_FOCUSED;
2700 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
2701 /* Send SIGHUP to shell */
2708 cresize(int width, int height)
2717 col = (xw.w - 2*BORDER) / xw.cw;
2718 row = (xw.h - 2*BORDER) / xw.ch;
2719 if(col == term.col && row == term.row)
2729 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2732 cresize(e->xconfigure.width, e->xconfigure.height);
2739 int xfd = XConnectionNumber(xw.dpy), i;
2740 struct timeval drawtimeout, *tv = NULL;
2744 FD_SET(cmdfd, &rfd);
2746 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2749 die("select failed: %s\n", SERRNO);
2753 * Stop after a certain number of reads so the user does not
2754 * feel like the system is stuttering.
2756 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2760 * Just wait a bit so it isn't disturbing the
2761 * user and the system is able to write something.
2763 drawtimeout.tv_sec = 0;
2764 drawtimeout.tv_usec = 5;
2771 while(XPending(xw.dpy)) {
2772 XNextEvent(xw.dpy, &ev);
2773 if(XFilterEvent(&ev, xw.win))
2775 if(handler[ev.type])
2776 (handler[ev.type])(&ev);
2785 main(int argc, char *argv[]) {
2786 int i, bitm, xr, yr;
2789 xw.fw = xw.fh = xw.fx = xw.fy = 0;
2792 for(i = 1; i < argc; i++) {
2793 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2796 opt_class = argv[i];
2799 /* eat every remaining arguments */
2811 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2816 if(bitm & WidthValue)
2818 if(bitm & HeightValue)
2820 if(bitm & XNegative && xw.fx == 0)
2822 if(bitm & XNegative && xw.fy == 0)
2825 if(xw.fh != 0 && xw.fw != 0)
2834 opt_title = argv[i];
2841 opt_embed = argv[i];
2847 setlocale(LC_CTYPE, "");