1 /* See LICENSE for licence details. */
2 #define _XOPEN_SOURCE 600
15 #include <sys/ioctl.h>
16 #include <sys/select.h>
19 #include <sys/types.h>
23 #include <X11/Xatom.h>
25 #include <X11/Xutil.h>
26 #include <X11/cursorfont.h>
27 #include <X11/keysym.h>
28 #include <X11/extensions/Xdbe.h>
29 #include <X11/Xft/Xft.h>
30 #include <fontconfig/fontconfig.h>
34 #define Draw XftDraw *
35 #define Colour XftColor
36 #define Colourmap Colormap
40 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
42 #elif defined(__FreeBSD__) || defined(__DragonFly__)
47 "st " VERSION " (c) 2010-2012 st engineers\n" \
48 "usage: st [-v] [-c class] [-f font] [-g geometry] [-o file]" \
49 " [-t title] [-w windowid] [-e command ...]\n"
52 #define XEMBED_FOCUS_IN 4
53 #define XEMBED_FOCUS_OUT 5
56 #define ESC_BUF_SIZ 256
57 #define ESC_ARG_SIZ 16
58 #define STR_BUF_SIZ 256
59 #define STR_ARG_SIZ 16
60 #define DRAW_BUF_SIZ 20*1024
62 #define XK_NO_MOD UINT_MAX
65 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
68 #define CLEANMASK(mask) (mask & (ShiftMask|ControlMask|Mod1Mask|Mod2Mask|Mod3Mask|Mod4Mask|Mod5Mask))
69 #define SERRNO strerror(errno)
70 #define MIN(a, b) ((a) < (b) ? (a) : (b))
71 #define MAX(a, b) ((a) < (b) ? (b) : (a))
72 #define LEN(a) (sizeof(a) / sizeof(a[0]))
73 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
74 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
75 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
76 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
77 #define IS_SET(flag) (term.mode & (flag))
78 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
80 #define VT102ID "\033[?6c"
82 enum glyph_attribute {
92 enum cursor_movement {
119 MODE_MOUSEMOTION = 64,
125 MODE_APPCURSOR = 2048
131 ESC_STR = 4, /* DSC, OSC, PM, APC */
133 ESC_STR_END = 16, /* a final string was encountered */
134 ESC_TEST = 32, /* Enter in test mode */
145 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
147 typedef unsigned char uchar;
148 typedef unsigned int uint;
149 typedef unsigned long ulong;
150 typedef unsigned short ushort;
153 char c[UTF_SIZ]; /* character code */
154 uchar mode; /* attribute flags */
155 ushort fg; /* foreground */
156 ushort bg; /* background */
157 uchar state; /* state flags */
163 Glyph attr; /* current char attributes */
169 /* CSI Escape sequence structs */
170 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
172 char buf[ESC_BUF_SIZ]; /* raw string */
173 int len; /* raw string length */
175 int arg[ESC_ARG_SIZ];
176 int narg; /* nb of args */
180 /* STR Escape sequence structs */
181 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
183 char type; /* ESC type ... */
184 char buf[STR_BUF_SIZ]; /* raw string */
185 int len; /* raw string length */
186 char *args[STR_ARG_SIZ];
187 int narg; /* nb of args */
190 /* Internal representation of the screen */
192 int row; /* nb row */
193 int col; /* nb col */
194 Line *line; /* screen */
195 Line *alt; /* alternate screen */
196 bool *dirty; /* dirtyness of lines */
197 TCursor c; /* cursor */
198 int top; /* top scroll limit */
199 int bot; /* bottom scroll limit */
200 int mode; /* terminal mode flags */
201 int esc; /* escape state flags */
205 /* Purely graphic info */
211 Atom xembed, wmdeletewin;
217 bool isfixed; /* is fixed geometry? */
218 int fx, fy, fw, fh; /* fixed geometry */
219 int tw, th; /* tty width and height */
220 int w; /* window width */
221 int h; /* window height */
222 int ch; /* char height */
223 int cw; /* char width */
224 char state; /* focus, redraw, visible */
231 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
232 signed char appkey; /* application keypad */
233 signed char appcursor; /* application cursor */
234 signed char crlf; /* crlf mode */
237 /* TODO: use better name for vars... */
248 struct timeval tclick1;
249 struct timeval tclick2;
262 void (*func)(const Arg *);
266 /* function definitions used in config.h */
267 static void xzoom(const Arg *);
268 static void selpaste(const Arg *);
270 /* Config.h for applying patches and the configuration. */
284 /* Drawing Context */
286 Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
287 Font font, bfont, ifont, ibfont;
290 static void die(const char *, ...);
291 static void draw(void);
292 static void redraw(void);
293 static void drawregion(int, int, int, int);
294 static void execsh(void);
295 static void sigchld(int);
296 static void run(void);
298 static void csidump(void);
299 static void csihandle(void);
300 static void csiparse(void);
301 static void csireset(void);
302 static void strdump(void);
303 static void strhandle(void);
304 static void strparse(void);
305 static void strreset(void);
307 static void tclearregion(int, int, int, int);
308 static void tcursor(int);
309 static void tdeletechar(int);
310 static void tdeleteline(int);
311 static void tinsertblank(int);
312 static void tinsertblankline(int);
313 static void tmoveto(int, int);
314 static void tmoveato(int x, int y);
315 static void tnew(int, int);
316 static void tnewline(int);
317 static void tputtab(bool);
318 static void tputc(char *, int);
319 static void treset(void);
320 static int tresize(int, int);
321 static void tscrollup(int, int);
322 static void tscrolldown(int, int);
323 static void tsetattr(int*, int);
324 static void tsetchar(char *, Glyph *, int, int);
325 static void tsetscroll(int, int);
326 static void tswapscreen(void);
327 static void tsetdirt(int, int);
328 static void tsetmode(bool, bool, int *, int);
329 static void tfulldirt(void);
330 static void techo(char *, int);
332 static void ttynew(void);
333 static void ttyread(void);
334 static void ttyresize(void);
335 static void ttywrite(const char *, size_t);
337 static void xdraws(char *, Glyph, int, int, int, int);
338 static void xhints(void);
339 static void xclear(int, int, int, int);
340 static void xdrawcursor(void);
341 static void xinit(void);
342 static void xloadcols(void);
343 static void xresettitle(void);
344 static void xseturgency(int);
345 static void xsetsel(char*);
346 static void xtermclear(int, int, int, int);
347 static void xresize(int, int);
349 static void expose(XEvent *);
350 static void visibility(XEvent *);
351 static void unmap(XEvent *);
352 static char *kmap(KeySym, uint);
353 static void kpress(XEvent *);
354 static void cmessage(XEvent *);
355 static void cresize(int width, int height);
356 static void resize(XEvent *);
357 static void focus(XEvent *);
358 static void brelease(XEvent *);
359 static void bpress(XEvent *);
360 static void bmotion(XEvent *);
361 static void selnotify(XEvent *);
362 static void selclear(XEvent *);
363 static void selrequest(XEvent *);
365 static void selinit(void);
366 static inline bool selected(int, int);
367 static void selcopy(void);
368 static void selscroll(int, int);
370 static int utf8decode(char *, long *);
371 static int utf8encode(long *, char *);
372 static int utf8size(char *);
373 static int isfullutf8(char *, int);
375 static ssize_t xwrite(int, char *, size_t);
376 static void *xmalloc(size_t);
377 static void *xrealloc(void *, size_t);
378 static void *xcalloc(size_t nmemb, size_t size);
380 static void (*handler[LASTEvent])(XEvent *) = {
382 [ClientMessage] = cmessage,
383 [ConfigureNotify] = resize,
384 [VisibilityNotify] = visibility,
385 [UnmapNotify] = unmap,
389 [MotionNotify] = bmotion,
390 [ButtonPress] = bpress,
391 [ButtonRelease] = brelease,
392 [SelectionClear] = selclear,
393 [SelectionNotify] = selnotify,
394 [SelectionRequest] = selrequest,
401 static CSIEscape csiescseq;
402 static STREscape strescseq;
405 static Selection sel;
406 static int iofd = -1;
407 static char **opt_cmd = NULL;
408 static char *opt_io = NULL;
409 static char *opt_title = NULL;
410 static char *opt_embed = NULL;
411 static char *opt_class = NULL;
412 static char *opt_font = NULL;
414 static char *usedfont = NULL;
415 static int usedfontsize = 0;
418 xwrite(int fd, char *s, size_t len) {
422 ssize_t r = write(fd, s, len);
432 xmalloc(size_t len) {
433 void *p = malloc(len);
436 die("Out of memory\n");
442 xrealloc(void *p, size_t len) {
443 if((p = realloc(p, len)) == NULL)
444 die("Out of memory\n");
450 xcalloc(size_t nmemb, size_t size) {
451 void *p = calloc(nmemb, size);
454 die("Out of memory\n");
460 utf8decode(char *s, long *u) {
466 if(~c & B7) { /* 0xxxxxxx */
469 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
470 *u = c&(B4|B3|B2|B1|B0);
472 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
473 *u = c&(B3|B2|B1|B0);
475 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
482 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
484 if((c & (B7|B6)) != B7) /* 10xxxxxx */
487 *u |= c & (B5|B4|B3|B2|B1|B0);
490 if((n == 1 && *u < 0x80) ||
491 (n == 2 && *u < 0x800) ||
492 (n == 3 && *u < 0x10000) ||
493 (*u >= 0xD800 && *u <= 0xDFFF)) {
505 utf8encode(long *u, char *s) {
513 *sp = uc; /* 0xxxxxxx */
515 } else if(*u < 0x800) {
516 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
518 } else if(uc < 0x10000) {
519 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
521 } else if(uc <= 0x10FFFF) {
522 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
528 for(i=n,++sp; i>0; --i,++sp)
529 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
541 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
542 UTF-8 otherwise return 0 */
544 isfullutf8(char *s, int b) {
552 } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
554 } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
556 ((b == 2) && (*c2&(B7|B6)) == B7))) {
558 } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
560 ((b == 2) && (*c2&(B7|B6)) == B7) ||
561 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
574 } else if((c&(B7|B6|B5)) == (B7|B6)) {
576 } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
585 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
586 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
590 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
591 if(sel.xtarget == None)
592 sel.xtarget = XA_STRING;
600 return LIMIT(x, 0, term.col-1);
608 return LIMIT(y, 0, term.row-1);
612 selected(int x, int y) {
615 if(sel.ey == y && sel.by == y) {
616 bx = MIN(sel.bx, sel.ex);
617 ex = MAX(sel.bx, sel.ex);
618 return BETWEEN(x, bx, ex);
621 return ((sel.b.y < y && y < sel.e.y)
622 || (y == sel.e.y && x <= sel.e.x))
623 || (y == sel.b.y && x >= sel.b.x
624 && (x <= sel.e.x || sel.b.y != sel.e.y));
628 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
630 *b = e->xbutton.button;
632 *x = x2col(e->xbutton.x);
633 *y = y2row(e->xbutton.y);
635 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
636 sel.b.y = MIN(sel.by, sel.ey);
637 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
638 sel.e.y = MAX(sel.by, sel.ey);
642 mousereport(XEvent *e) {
643 int x = x2col(e->xbutton.x);
644 int y = y2row(e->xbutton.y);
645 int button = e->xbutton.button;
646 int state = e->xbutton.state;
647 char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
648 static int ob, ox, oy;
651 if(e->xbutton.type == MotionNotify) {
652 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
656 } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
662 if(e->xbutton.type == ButtonPress) {
668 buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
669 + (state & Mod4Mask ? 8 : 0)
670 + (state & ControlMask ? 16 : 0);
672 ttywrite(buf, sizeof(buf));
677 if(IS_SET(MODE_MOUSE)) {
679 } else if(e->xbutton.button == Button1) {
682 tsetdirt(sel.b.y, sel.e.y);
686 sel.ex = sel.bx = x2col(e->xbutton.x);
687 sel.ey = sel.by = y2row(e->xbutton.y);
688 } else if(e->xbutton.button == Button4) {
690 } else if(e->xbutton.button == Button5) {
698 int x, y, bufsize, is_selected = 0, size;
704 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
705 ptr = str = xmalloc(bufsize);
707 /* append every set & selected glyph to the selection */
708 for(y = 0; y < term.row; y++) {
709 gp = &term.line[y][0];
710 last = gp + term.col;
712 while(--last >= gp && !(last->state & GLYPH_SET))
715 for(x = 0; gp <= last; x++, ++gp) {
716 if(!(is_selected = selected(x, y)))
719 p = (gp->state & GLYPH_SET) ? gp->c : " ";
721 memcpy(ptr, p, size);
724 /* \n at the end of every selected line except for the last one */
725 if(is_selected && y < sel.e.y)
730 sel.alt = IS_SET(MODE_ALTSCREEN);
735 selnotify(XEvent *e) {
736 ulong nitems, ofs, rem;
743 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
744 False, AnyPropertyType, &type, &format,
745 &nitems, &rem, &data)) {
746 fprintf(stderr, "Clipboard allocation failed\n");
749 ttywrite((const char *) data, nitems * format / 8);
751 /* number of 32-bit chunks returned */
752 ofs += nitems * format / 32;
757 selpaste(const Arg *dummy) {
758 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
759 xw.win, CurrentTime);
762 void selclear(XEvent *e) {
766 tsetdirt(sel.b.y, sel.e.y);
770 selrequest(XEvent *e) {
771 XSelectionRequestEvent *xsre;
773 Atom xa_targets, string;
775 xsre = (XSelectionRequestEvent *) e;
776 xev.type = SelectionNotify;
777 xev.requestor = xsre->requestor;
778 xev.selection = xsre->selection;
779 xev.target = xsre->target;
780 xev.time = xsre->time;
784 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
785 if(xsre->target == xa_targets) {
786 /* respond with the supported type */
787 string = sel.xtarget;
788 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
789 XA_ATOM, 32, PropModeReplace,
790 (uchar *) &string, 1);
791 xev.property = xsre->property;
792 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
793 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
794 xsre->target, 8, PropModeReplace,
795 (uchar *) sel.clip, strlen(sel.clip));
796 xev.property = xsre->property;
799 /* all done, send a notification to the listener */
800 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
801 fprintf(stderr, "Error sending SelectionNotify event\n");
806 /* register the selection for both the clipboard and the primary */
812 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
814 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
815 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
819 brelease(XEvent *e) {
822 if(IS_SET(MODE_MOUSE)) {
827 if(e->xbutton.button == Button2) {
829 } else if(e->xbutton.button == Button1) {
831 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
832 term.dirty[sel.ey] = 1;
833 if(sel.bx == sel.ex && sel.by == sel.ey) {
835 gettimeofday(&now, NULL);
837 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
838 /* triple click on the line */
839 sel.b.x = sel.bx = 0;
840 sel.e.x = sel.ex = term.col;
841 sel.b.y = sel.e.y = sel.ey;
843 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
844 /* double click to select word */
846 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
847 term.line[sel.ey][sel.bx-1].c[0] != ' ') {
851 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
852 term.line[sel.ey][sel.ex+1].c[0] != ' ') {
856 sel.b.y = sel.e.y = sel.ey;
864 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
865 gettimeofday(&sel.tclick1, NULL);
870 int starty, endy, oldey, oldex;
872 if(IS_SET(MODE_MOUSE)) {
880 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
882 if(oldey != sel.ey || oldex != sel.ex) {
883 starty = MIN(oldey, sel.ey);
884 endy = MAX(oldey, sel.ey);
885 tsetdirt(starty, endy);
891 die(const char *errstr, ...) {
894 va_start(ap, errstr);
895 vfprintf(stderr, errstr, ap);
903 char *envshell = getenv("SHELL");
904 const struct passwd *pass = getpwuid(getuid());
905 char buf[sizeof(long) * 8 + 1];
912 setenv("LOGNAME", pass->pw_name, 1);
913 setenv("USER", pass->pw_name, 1);
914 setenv("SHELL", pass->pw_shell, 0);
915 setenv("HOME", pass->pw_dir, 0);
918 snprintf(buf, sizeof(buf), "%lu", xw.win);
919 setenv("WINDOWID", buf, 1);
921 signal(SIGCHLD, SIG_DFL);
922 signal(SIGHUP, SIG_DFL);
923 signal(SIGINT, SIG_DFL);
924 signal(SIGQUIT, SIG_DFL);
925 signal(SIGTERM, SIG_DFL);
926 signal(SIGALRM, SIG_DFL);
928 DEFAULT(envshell, shell);
929 setenv("TERM", termname, 1);
930 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
931 execvp(args[0], args);
939 if(waitpid(pid, &stat, 0) < 0)
940 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
942 if(WIFEXITED(stat)) {
943 exit(WEXITSTATUS(stat));
952 struct winsize w = {term.row, term.col, 0, 0};
954 /* seems to work fine on linux, openbsd and freebsd */
955 if(openpty(&m, &s, NULL, NULL, &w) < 0)
956 die("openpty failed: %s\n", SERRNO);
958 switch(pid = fork()) {
960 die("fork failed\n");
963 setsid(); /* create a new process group */
964 dup2(s, STDIN_FILENO);
965 dup2(s, STDOUT_FILENO);
966 dup2(s, STDERR_FILENO);
967 if(ioctl(s, TIOCSCTTY, NULL) < 0)
968 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
976 signal(SIGCHLD, sigchld);
978 iofd = (!strcmp(opt_io, "-")) ?
980 open(opt_io, O_WRONLY | O_CREAT, 0666);
982 fprintf(stderr, "Error opening %s:%s\n",
983 opt_io, strerror(errno));
993 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
995 fprintf(stderr, "\n");
1000 static char buf[BUFSIZ];
1001 static int buflen = 0;
1004 int charsize; /* size of utf8 char in bytes */
1008 /* append read bytes to unprocessed bytes */
1009 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1010 die("Couldn't read from shell: %s\n", SERRNO);
1012 /* process every complete utf8 char */
1015 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1016 charsize = utf8decode(ptr, &utf8c);
1017 utf8encode(&utf8c, s);
1023 /* keep any uncomplete utf8 char for the next call */
1024 memmove(buf, ptr, buflen);
1028 ttywrite(const char *s, size_t n) {
1029 if(write(cmdfd, s, n) == -1)
1030 die("write error on tty: %s\n", SERRNO);
1037 w.ws_row = term.row;
1038 w.ws_col = term.col;
1039 w.ws_xpixel = xw.tw;
1040 w.ws_ypixel = xw.th;
1041 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1042 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1046 tsetdirt(int top, int bot) {
1049 LIMIT(top, 0, term.row-1);
1050 LIMIT(bot, 0, term.row-1);
1052 for(i = top; i <= bot; i++)
1058 tsetdirt(0, term.row-1);
1065 if(mode == CURSOR_SAVE) {
1067 } else if(mode == CURSOR_LOAD) {
1077 term.c = (TCursor){{
1081 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1083 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1084 for(i = tabspaces; i < term.col; i += tabspaces)
1087 term.bot = term.row - 1;
1088 term.mode = MODE_WRAP;
1090 tclearregion(0, 0, term.col-1, term.row-1);
1092 tcursor(CURSOR_SAVE);
1096 tnew(int col, int row) {
1097 /* set screen size */
1100 term.line = xmalloc(term.row * sizeof(Line));
1101 term.alt = xmalloc(term.row * sizeof(Line));
1102 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1103 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1105 for(row = 0; row < term.row; row++) {
1106 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1107 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1108 term.dirty[row] = 0;
1110 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1117 Line *tmp = term.line;
1119 term.line = term.alt;
1121 term.mode ^= MODE_ALTSCREEN;
1126 tscrolldown(int orig, int n) {
1130 LIMIT(n, 0, term.bot-orig+1);
1132 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1134 for(i = term.bot; i >= orig+n; i--) {
1135 temp = term.line[i];
1136 term.line[i] = term.line[i-n];
1137 term.line[i-n] = temp;
1140 term.dirty[i-n] = 1;
1147 tscrollup(int orig, int n) {
1150 LIMIT(n, 0, term.bot-orig+1);
1152 tclearregion(0, orig, term.col-1, orig+n-1);
1154 for(i = orig; i <= term.bot-n; i++) {
1155 temp = term.line[i];
1156 term.line[i] = term.line[i+n];
1157 term.line[i+n] = temp;
1160 term.dirty[i+n] = 1;
1163 selscroll(orig, -n);
1167 selscroll(int orig, int n) {
1171 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1172 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1176 if(sel.by < term.top) {
1180 if(sel.ey > term.bot) {
1184 sel.b.y = sel.by, sel.b.x = sel.bx;
1185 sel.e.y = sel.ey, sel.e.x = sel.ex;
1190 tnewline(int first_col) {
1194 tscrollup(term.top, 1);
1198 tmoveto(first_col ? 0 : term.c.x, y);
1203 /* int noarg = 1; */
1204 char *p = csiescseq.buf;
1208 csiescseq.priv = 1, p++;
1210 while(p < csiescseq.buf+csiescseq.len) {
1211 while(isdigit(*p)) {
1212 csiescseq.arg[csiescseq.narg] *= 10;
1213 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1215 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1216 csiescseq.narg++, p++;
1218 csiescseq.mode = *p;
1226 /* for absolute user moves, when decom is set */
1228 tmoveato(int x, int y) {
1229 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1233 tmoveto(int x, int y) {
1236 if(term.c.state & CURSOR_ORIGIN) {
1241 maxy = term.row - 1;
1243 LIMIT(x, 0, term.col-1);
1244 LIMIT(y, miny, maxy);
1245 term.c.state &= ~CURSOR_WRAPNEXT;
1251 tsetchar(char *c, Glyph *attr, int x, int y) {
1252 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1253 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1254 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1255 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1256 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1257 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1258 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1259 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1260 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1264 * The table is proudly stolen from rxvt.
1266 if(attr->mode & ATTR_GFX) {
1267 if(c[0] >= 0x41 && c[0] <= 0x7e
1268 && vt100_0[c[0] - 0x41]) {
1269 c = vt100_0[c[0] - 0x41];
1274 term.line[y][x] = *attr;
1275 memcpy(term.line[y][x].c, c, UTF_SIZ);
1276 term.line[y][x].state |= GLYPH_SET;
1280 tclearregion(int x1, int y1, int x2, int y2) {
1284 temp = x1, x1 = x2, x2 = temp;
1286 temp = y1, y1 = y2, y2 = temp;
1288 LIMIT(x1, 0, term.col-1);
1289 LIMIT(x2, 0, term.col-1);
1290 LIMIT(y1, 0, term.row-1);
1291 LIMIT(y2, 0, term.row-1);
1293 for(y = y1; y <= y2; y++) {
1295 for(x = x1; x <= x2; x++)
1296 term.line[y][x].state = 0;
1301 tdeletechar(int n) {
1302 int src = term.c.x + n;
1304 int size = term.col - src;
1306 term.dirty[term.c.y] = 1;
1308 if(src >= term.col) {
1309 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1313 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1314 size * sizeof(Glyph));
1315 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1319 tinsertblank(int n) {
1322 int size = term.col - dst;
1324 term.dirty[term.c.y] = 1;
1326 if(dst >= term.col) {
1327 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1331 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1332 size * sizeof(Glyph));
1333 tclearregion(src, term.c.y, dst - 1, term.c.y);
1337 tinsertblankline(int n) {
1338 if(term.c.y < term.top || term.c.y > term.bot)
1341 tscrolldown(term.c.y, n);
1345 tdeleteline(int n) {
1346 if(term.c.y < term.top || term.c.y > term.bot)
1349 tscrollup(term.c.y, n);
1353 tsetattr(int *attr, int l) {
1356 for(i = 0; i < l; i++) {
1359 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1360 | ATTR_ITALIC | ATTR_BLINK);
1361 term.c.attr.fg = defaultfg;
1362 term.c.attr.bg = defaultbg;
1365 term.c.attr.mode |= ATTR_BOLD;
1367 case 3: /* enter standout (highlight) */
1368 term.c.attr.mode |= ATTR_ITALIC;
1371 term.c.attr.mode |= ATTR_UNDERLINE;
1374 term.c.attr.mode |= ATTR_BLINK;
1377 term.c.attr.mode |= ATTR_REVERSE;
1381 term.c.attr.mode &= ~ATTR_BOLD;
1383 case 23: /* leave standout (highlight) mode */
1384 term.c.attr.mode &= ~ATTR_ITALIC;
1387 term.c.attr.mode &= ~ATTR_UNDERLINE;
1390 term.c.attr.mode &= ~ATTR_BLINK;
1393 term.c.attr.mode &= ~ATTR_REVERSE;
1396 if(i + 2 < l && attr[i + 1] == 5) {
1398 if(BETWEEN(attr[i], 0, 255)) {
1399 term.c.attr.fg = attr[i];
1402 "erresc: bad fgcolor %d\n",
1407 "erresc(38): gfx attr %d unknown\n",
1412 term.c.attr.fg = defaultfg;
1415 if(i + 2 < l && attr[i + 1] == 5) {
1417 if(BETWEEN(attr[i], 0, 255)) {
1418 term.c.attr.bg = attr[i];
1421 "erresc: bad bgcolor %d\n",
1426 "erresc(48): gfx attr %d unknown\n",
1431 term.c.attr.bg = defaultbg;
1434 if(BETWEEN(attr[i], 30, 37)) {
1435 term.c.attr.fg = attr[i] - 30;
1436 } else if(BETWEEN(attr[i], 40, 47)) {
1437 term.c.attr.bg = attr[i] - 40;
1438 } else if(BETWEEN(attr[i], 90, 97)) {
1439 term.c.attr.fg = attr[i] - 90 + 8;
1440 } else if(BETWEEN(attr[i], 100, 107)) {
1441 term.c.attr.bg = attr[i] - 100 + 8;
1444 "erresc(default): gfx attr %d unknown\n",
1445 attr[i]), csidump();
1453 tsetscroll(int t, int b) {
1456 LIMIT(t, 0, term.row-1);
1457 LIMIT(b, 0, term.row-1);
1467 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1470 tsetmode(bool priv, bool set, int *args, int narg) {
1474 for(lim = args + narg; args < lim; ++args) {
1478 case 1: /* DECCKM -- Cursor key */
1479 MODBIT(term.mode, set, MODE_APPCURSOR);
1481 case 5: /* DECSCNM -- Reverse video */
1483 MODBIT(term.mode, set, MODE_REVERSE);
1484 if(mode != term.mode)
1487 case 6: /* DECOM -- Origin */
1488 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1491 case 7: /* DECAWM -- Auto wrap */
1492 MODBIT(term.mode, set, MODE_WRAP);
1494 case 0: /* Error (IGNORED) */
1495 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1496 case 3: /* DECCOLM -- Column (IGNORED) */
1497 case 4: /* DECSCLM -- Scroll (IGNORED) */
1498 case 8: /* DECARM -- Auto repeat (IGNORED) */
1499 case 18: /* DECPFF -- Printer feed (IGNORED) */
1500 case 19: /* DECPEX -- Printer extent (IGNORED) */
1501 case 42: /* DECNRCM -- National characters (IGNORED) */
1502 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1504 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1505 MODBIT(term.mode, !set, MODE_HIDE);
1507 case 1000: /* 1000,1002: enable xterm mouse report */
1508 MODBIT(term.mode, set, MODE_MOUSEBTN);
1511 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1513 case 1049: /* = 1047 and 1048 */
1516 alt = IS_SET(MODE_ALTSCREEN) != 0;
1518 tclearregion(0, 0, term.col-1, term.row-1);
1519 if(set ^ alt) /* set is always 1 or 0 */
1526 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1530 "erresc: unknown private set/reset mode %d\n",
1536 case 0: /* Error (IGNORED) */
1538 case 2: /* KAM -- keyboard action */
1539 MODBIT(term.mode, set, MODE_KBDLOCK);
1541 case 4: /* IRM -- Insertion-replacement */
1542 MODBIT(term.mode, set, MODE_INSERT);
1544 case 12: /* SRM -- Send/Receive */
1545 MODBIT(term.mode, !set, MODE_ECHO);
1547 case 20: /* LNM -- Linefeed/new line */
1548 MODBIT(term.mode, set, MODE_CRLF);
1552 "erresc: unknown set/reset mode %d\n",
1564 switch(csiescseq.mode) {
1567 fprintf(stderr, "erresc: unknown csi ");
1571 case '@': /* ICH -- Insert <n> blank char */
1572 DEFAULT(csiescseq.arg[0], 1);
1573 tinsertblank(csiescseq.arg[0]);
1575 case 'A': /* CUU -- Cursor <n> Up */
1576 DEFAULT(csiescseq.arg[0], 1);
1577 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1579 case 'B': /* CUD -- Cursor <n> Down */
1580 case 'e': /* VPR --Cursor <n> Down */
1581 DEFAULT(csiescseq.arg[0], 1);
1582 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1584 case 'c': /* DA -- Device Attributes */
1585 if(csiescseq.arg[0] == 0)
1586 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1588 case 'C': /* CUF -- Cursor <n> Forward */
1589 case 'a': /* HPR -- Cursor <n> Forward */
1590 DEFAULT(csiescseq.arg[0], 1);
1591 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1593 case 'D': /* CUB -- Cursor <n> Backward */
1594 DEFAULT(csiescseq.arg[0], 1);
1595 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1597 case 'E': /* CNL -- Cursor <n> Down and first col */
1598 DEFAULT(csiescseq.arg[0], 1);
1599 tmoveto(0, term.c.y+csiescseq.arg[0]);
1601 case 'F': /* CPL -- Cursor <n> Up and first col */
1602 DEFAULT(csiescseq.arg[0], 1);
1603 tmoveto(0, term.c.y-csiescseq.arg[0]);
1605 case 'g': /* TBC -- Tabulation clear */
1606 switch (csiescseq.arg[0]) {
1607 case 0: /* clear current tab stop */
1608 term.tabs[term.c.x] = 0;
1610 case 3: /* clear all the tabs */
1611 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1617 case 'G': /* CHA -- Move to <col> */
1619 DEFAULT(csiescseq.arg[0], 1);
1620 tmoveto(csiescseq.arg[0]-1, term.c.y);
1622 case 'H': /* CUP -- Move to <row> <col> */
1624 DEFAULT(csiescseq.arg[0], 1);
1625 DEFAULT(csiescseq.arg[1], 1);
1626 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1628 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1629 DEFAULT(csiescseq.arg[0], 1);
1630 while(csiescseq.arg[0]--)
1633 case 'J': /* ED -- Clear screen */
1635 switch(csiescseq.arg[0]) {
1637 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1638 if(term.c.y < term.row-1)
1639 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1643 tclearregion(0, 0, term.col-1, term.c.y-1);
1644 tclearregion(0, term.c.y, term.c.x, term.c.y);
1647 tclearregion(0, 0, term.col-1, term.row-1);
1653 case 'K': /* EL -- Clear line */
1654 switch(csiescseq.arg[0]) {
1656 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1659 tclearregion(0, term.c.y, term.c.x, term.c.y);
1662 tclearregion(0, term.c.y, term.col-1, term.c.y);
1666 case 'S': /* SU -- Scroll <n> line up */
1667 DEFAULT(csiescseq.arg[0], 1);
1668 tscrollup(term.top, csiescseq.arg[0]);
1670 case 'T': /* SD -- Scroll <n> line down */
1671 DEFAULT(csiescseq.arg[0], 1);
1672 tscrolldown(term.top, csiescseq.arg[0]);
1674 case 'L': /* IL -- Insert <n> blank lines */
1675 DEFAULT(csiescseq.arg[0], 1);
1676 tinsertblankline(csiescseq.arg[0]);
1678 case 'l': /* RM -- Reset Mode */
1679 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1681 case 'M': /* DL -- Delete <n> lines */
1682 DEFAULT(csiescseq.arg[0], 1);
1683 tdeleteline(csiescseq.arg[0]);
1685 case 'X': /* ECH -- Erase <n> char */
1686 DEFAULT(csiescseq.arg[0], 1);
1687 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1689 case 'P': /* DCH -- Delete <n> char */
1690 DEFAULT(csiescseq.arg[0], 1);
1691 tdeletechar(csiescseq.arg[0]);
1693 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1694 DEFAULT(csiescseq.arg[0], 1);
1695 while(csiescseq.arg[0]--)
1698 case 'd': /* VPA -- Move to <row> */
1699 DEFAULT(csiescseq.arg[0], 1);
1700 tmoveato(term.c.x, csiescseq.arg[0]-1);
1702 case 'h': /* SM -- Set terminal mode */
1703 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1705 case 'm': /* SGR -- Terminal attribute (color) */
1706 tsetattr(csiescseq.arg, csiescseq.narg);
1708 case 'r': /* DECSTBM -- Set Scrolling Region */
1709 if(csiescseq.priv) {
1712 DEFAULT(csiescseq.arg[0], 1);
1713 DEFAULT(csiescseq.arg[1], term.row);
1714 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1718 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1719 tcursor(CURSOR_SAVE);
1721 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1722 tcursor(CURSOR_LOAD);
1733 for(i = 0; i < csiescseq.len; i++) {
1734 c = csiescseq.buf[i] & 0xff;
1737 } else if(c == '\n') {
1739 } else if(c == '\r') {
1741 } else if(c == 0x1b) {
1744 printf("(%02x)", c);
1752 memset(&csiescseq, 0, sizeof(csiescseq));
1760 * TODO: make this being useful in case of color palette change.
1766 switch(strescseq.type) {
1767 case ']': /* OSC -- Operating System Command */
1773 * TODO: Handle special chars in string, like umlauts.
1776 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1780 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1782 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1785 fprintf(stderr, "erresc: unknown str ");
1790 case 'k': /* old title set compatibility */
1791 XStoreName(xw.dpy, xw.win, strescseq.buf);
1793 case 'P': /* DSC -- Device Control String */
1794 case '_': /* APC -- Application Program Command */
1795 case '^': /* PM -- Privacy Message */
1797 fprintf(stderr, "erresc: unknown str ");
1807 * TODO: Implement parsing like for CSI when required.
1808 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1818 printf("ESC%c", strescseq.type);
1819 for(i = 0; i < strescseq.len; i++) {
1820 c = strescseq.buf[i] & 0xff;
1823 } else if(c == '\n') {
1825 } else if(c == '\r') {
1827 } else if(c == 0x1b) {
1830 printf("(%02x)", c);
1838 memset(&strescseq, 0, sizeof(strescseq));
1842 tputtab(bool forward) {
1848 for(++x; x < term.col && !term.tabs[x]; ++x)
1853 for(--x; x > 0 && !term.tabs[x]; --x)
1856 tmoveto(x, term.c.y);
1860 techo(char *buf, int len) {
1861 for(; len > 0; buf++, len--) {
1864 if(c == '\033') { /* escape */
1867 } else if (c < '\x20') { /* control code */
1868 if(c != '\n' && c != '\r' && c != '\t') {
1882 tputc(char *c, int len) {
1884 bool control = ascii < '\x20' || ascii == 0177;
1887 if (xwrite(iofd, c, len) < 0) {
1888 fprintf(stderr, "Error writting in %s:%s\n",
1889 opt_io, strerror(errno));
1895 * STR sequences must be checked before anything else
1896 * because it can use some control codes as part of the sequence.
1898 if(term.esc & ESC_STR) {
1901 term.esc = ESC_START | ESC_STR_END;
1903 case '\a': /* backwards compatibility to xterm */
1908 strescseq.buf[strescseq.len++] = ascii;
1909 if(strescseq.len+1 >= STR_BUF_SIZ) {
1918 * Actions of control codes must be performed as soon they arrive
1919 * because they can be embedded inside a control sequence, and
1920 * they must not cause conflicts with sequences.
1928 tmoveto(term.c.x-1, term.c.y);
1931 tmoveto(0, term.c.y);
1936 /* go to first col if the mode is set */
1937 tnewline(IS_SET(MODE_CRLF));
1939 case '\a': /* BEL */
1940 if(!(xw.state & WIN_FOCUSED))
1943 case '\033': /* ESC */
1945 term.esc = ESC_START;
1947 case '\016': /* SO */
1948 term.c.attr.mode |= ATTR_GFX;
1950 case '\017': /* SI */
1951 term.c.attr.mode &= ~ATTR_GFX;
1953 case '\032': /* SUB */
1954 case '\030': /* CAN */
1957 case '\005': /* ENQ (IGNORED) */
1958 case '\000': /* NUL (IGNORED) */
1959 case '\021': /* XON (IGNORED) */
1960 case '\023': /* XOFF (IGNORED) */
1961 case 0177: /* DEL (IGNORED) */
1964 } else if(term.esc & ESC_START) {
1965 if(term.esc & ESC_CSI) {
1966 csiescseq.buf[csiescseq.len++] = ascii;
1967 if(BETWEEN(ascii, 0x40, 0x7E)
1968 || csiescseq.len >= ESC_BUF_SIZ) {
1970 csiparse(), csihandle();
1972 } else if(term.esc & ESC_STR_END) {
1976 } else if(term.esc & ESC_ALTCHARSET) {
1978 case '0': /* Line drawing set */
1979 term.c.attr.mode |= ATTR_GFX;
1981 case 'B': /* USASCII */
1982 term.c.attr.mode &= ~ATTR_GFX;
1984 case 'A': /* UK (IGNORED) */
1985 case '<': /* multinational charset (IGNORED) */
1986 case '5': /* Finnish (IGNORED) */
1987 case 'C': /* Finnish (IGNORED) */
1988 case 'K': /* German (IGNORED) */
1991 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1994 } else if(term.esc & ESC_TEST) {
1995 if(ascii == '8') { /* DEC screen alignment test. */
1996 char E[UTF_SIZ] = "E";
1999 for(x = 0; x < term.col; ++x) {
2000 for(y = 0; y < term.row; ++y)
2001 tsetchar(E, &term.c.attr, x, y);
2008 term.esc |= ESC_CSI;
2011 term.esc |= ESC_TEST;
2013 case 'P': /* DCS -- Device Control String */
2014 case '_': /* APC -- Application Program Command */
2015 case '^': /* PM -- Privacy Message */
2016 case ']': /* OSC -- Operating System Command */
2017 case 'k': /* old title set compatibility */
2019 strescseq.type = ascii;
2020 term.esc |= ESC_STR;
2022 case '(': /* set primary charset G0 */
2023 term.esc |= ESC_ALTCHARSET;
2025 case ')': /* set secondary charset G1 (IGNORED) */
2026 case '*': /* set tertiary charset G2 (IGNORED) */
2027 case '+': /* set quaternary charset G3 (IGNORED) */
2030 case 'D': /* IND -- Linefeed */
2031 if(term.c.y == term.bot) {
2032 tscrollup(term.top, 1);
2034 tmoveto(term.c.x, term.c.y+1);
2038 case 'E': /* NEL -- Next line */
2039 tnewline(1); /* always go to first col */
2042 case 'H': /* HTS -- Horizontal tab stop */
2043 term.tabs[term.c.x] = 1;
2046 case 'M': /* RI -- Reverse index */
2047 if(term.c.y == term.top) {
2048 tscrolldown(term.top, 1);
2050 tmoveto(term.c.x, term.c.y-1);
2054 case 'Z': /* DECID -- Identify Terminal */
2055 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2058 case 'c': /* RIS -- Reset to inital state */
2063 case '=': /* DECPAM -- Application keypad */
2064 term.mode |= MODE_APPKEYPAD;
2067 case '>': /* DECPNM -- Normal keypad */
2068 term.mode &= ~MODE_APPKEYPAD;
2071 case '7': /* DECSC -- Save Cursor */
2072 tcursor(CURSOR_SAVE);
2075 case '8': /* DECRC -- Restore Cursor */
2076 tcursor(CURSOR_LOAD);
2079 case '\\': /* ST -- Stop */
2083 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2084 (uchar) ascii, isprint(ascii)? ascii:'.');
2089 * All characters which forms part of a sequence are not
2095 * Display control codes only if we are in graphic mode
2097 if(control && !(term.c.attr.mode & ATTR_GFX))
2099 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2101 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
2102 tnewline(1); /* always go to first col */
2103 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2104 if(term.c.x+1 < term.col)
2105 tmoveto(term.c.x+1, term.c.y);
2107 term.c.state |= CURSOR_WRAPNEXT;
2111 tresize(int col, int row) {
2113 int minrow = MIN(row, term.row);
2114 int mincol = MIN(col, term.col);
2115 int slide = term.c.y - row + 1;
2118 if(col < 1 || row < 1)
2121 /* free unneeded rows */
2124 /* slide screen to keep cursor where we expect it -
2125 * tscrollup would work here, but we can optimize to
2126 * memmove because we're freeing the earlier lines */
2127 for(/* i = 0 */; i < slide; i++) {
2131 memmove(term.line, term.line + slide, row * sizeof(Line));
2132 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2134 for(i += row; i < term.row; i++) {
2139 /* resize to new height */
2140 term.line = xrealloc(term.line, row * sizeof(Line));
2141 term.alt = xrealloc(term.alt, row * sizeof(Line));
2142 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2143 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2145 /* resize each row to new width, zero-pad if needed */
2146 for(i = 0; i < minrow; i++) {
2148 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2149 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2150 for(x = mincol; x < col; x++) {
2151 term.line[i][x].state = 0;
2152 term.alt[i][x].state = 0;
2156 /* allocate any new rows */
2157 for(/* i == minrow */; i < row; i++) {
2159 term.line[i] = xcalloc(col, sizeof(Glyph));
2160 term.alt [i] = xcalloc(col, sizeof(Glyph));
2162 if(col > term.col) {
2163 bp = term.tabs + term.col;
2165 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2166 while(--bp > term.tabs && !*bp)
2168 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2171 /* update terminal size */
2174 /* reset scrolling region */
2175 tsetscroll(0, row-1);
2176 /* make use of the LIMIT in tmoveto */
2177 tmoveto(term.c.x, term.c.y);
2183 xresize(int col, int row) {
2184 xw.tw = MAX(1, 2*borderpx + col * xw.cw);
2185 xw.th = MAX(1, 2*borderpx + row * xw.ch);
2187 XftDrawChange(xw.draw, xw.buf);
2193 XRenderColor color = { .alpha = 0 };
2195 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2196 for(i = 0; i < LEN(colorname); i++) {
2199 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2200 die("Could not allocate color '%s'\n", colorname[i]);
2204 /* load colors [16-255] ; same colors as xterm */
2205 for(i = 16, r = 0; r < 6; r++) {
2206 for(g = 0; g < 6; g++) {
2207 for(b = 0; b < 6; b++) {
2208 color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
2209 color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
2210 color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
2211 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2212 die("Could not allocate color %d\n", i);
2219 for(r = 0; r < 24; r++, i++) {
2220 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2221 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2223 die("Could not allocate color %d\n", i);
2229 xtermclear(int col1, int row1, int col2, int row2) {
2230 XftDrawRect(xw.draw,
2231 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2232 borderpx + col1 * xw.cw,
2233 borderpx + row1 * xw.ch,
2234 (col2-col1+1) * xw.cw,
2235 (row2-row1+1) * xw.ch);
2239 * Absolute coordinates.
2242 xclear(int x1, int y1, int x2, int y2) {
2243 XftDrawRect(xw.draw,
2244 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2245 x1, y1, x2-x1, y2-y1);
2250 XClassHint class = {opt_class ? opt_class : termname, termname};
2251 XWMHints wm = {.flags = InputHint, .input = 1};
2252 XSizeHints *sizeh = NULL;
2254 sizeh = XAllocSizeHints();
2255 if(xw.isfixed == False) {
2256 sizeh->flags = PSize | PResizeInc | PBaseSize;
2257 sizeh->height = xw.h;
2258 sizeh->width = xw.w;
2259 sizeh->height_inc = xw.ch;
2260 sizeh->width_inc = xw.cw;
2261 sizeh->base_height = 2*borderpx;
2262 sizeh->base_width = 2*borderpx;
2264 sizeh->flags = PMaxSize | PMinSize;
2265 sizeh->min_width = sizeh->max_width = xw.fw;
2266 sizeh->min_height = sizeh->max_height = xw.fh;
2269 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2274 xloadfont(Font *f, FcPattern *pattern) {
2278 match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
2281 if(!(f->set = XftFontOpenPattern(xw.dpy, match))) {
2282 FcPatternDestroy(match);
2286 f->ascent = f->set->ascent;
2287 f->descent = f->set->descent;
2289 f->rbearing = f->set->max_advance_width;
2291 f->height = f->set->height;
2292 f->width = f->lbearing + f->rbearing;
2298 xloadfonts(char *fontstr, int fontsize) {
2303 if(fontstr[0] == '-') {
2304 pattern = XftXlfdParse(fontstr, False, False);
2306 pattern = FcNameParse((FcChar8 *)fontstr);
2310 die("st: can't open font %s\n", fontstr);
2313 FcPatternDel(pattern, FC_PIXEL_SIZE);
2314 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2315 usedfontsize = fontsize;
2317 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2318 if(result == FcResultMatch) {
2319 usedfontsize = (int)fontval;
2322 * Default font size is 12, if none given. This is to
2323 * have a known usedfontsize value.
2325 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2330 if(xloadfont(&dc.font, pattern))
2331 die("st: can't open font %s\n", fontstr);
2333 /* Setting character width and height. */
2334 xw.cw = dc.font.width;
2335 xw.ch = dc.font.height;
2337 FcPatternDel(pattern, FC_WEIGHT);
2338 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2339 if(xloadfont(&dc.bfont, pattern))
2340 die("st: can't open font %s\n", fontstr);
2342 FcPatternDel(pattern, FC_SLANT);
2343 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2344 if(xloadfont(&dc.ibfont, pattern))
2345 die("st: can't open font %s\n", fontstr);
2347 FcPatternDel(pattern, FC_WEIGHT);
2348 if(xloadfont(&dc.ifont, pattern))
2349 die("st: can't open font %s\n", fontstr);
2351 FcPatternDestroy(pattern);
2355 xzoom(const Arg *arg)
2357 xloadfonts(usedfont, usedfontsize + arg->i);
2364 XSetWindowAttributes attrs;
2367 int sw, sh, major, minor;
2369 if(!(xw.dpy = XOpenDisplay(NULL)))
2370 die("Can't open display\n");
2371 xw.scr = XDefaultScreen(xw.dpy);
2372 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2375 usedfont = (opt_font == NULL)? font : opt_font;
2376 xloadfonts(usedfont, 0);
2379 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2382 /* adjust fixed window geometry */
2384 sw = DisplayWidth(xw.dpy, xw.scr);
2385 sh = DisplayHeight(xw.dpy, xw.scr);
2387 xw.fx = sw + xw.fx - xw.fw - 1;
2389 xw.fy = sh + xw.fy - xw.fh - 1;
2394 /* window - default size */
2395 xw.h = 2*borderpx + term.row * xw.ch;
2396 xw.w = 2*borderpx + term.col * xw.cw;
2401 attrs.background_pixel = dc.col[defaultbg].pixel;
2402 attrs.border_pixel = dc.col[defaultbg].pixel;
2403 attrs.bit_gravity = NorthWestGravity;
2404 attrs.event_mask = FocusChangeMask | KeyPressMask
2405 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2406 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2407 attrs.colormap = xw.cmap;
2409 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2410 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2411 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2413 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2417 /* double buffering */
2418 if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2419 die("Xdbe extension is not present\n");
2420 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2422 /* Xft rendering context */
2423 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2426 xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2427 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2428 | XIMStatusNothing, XNClientWindow, xw.win,
2429 XNFocusWindow, xw.win, NULL);
2431 /* white cursor, black outline */
2432 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2433 XDefineCursor(xw.dpy, xw.win, cursor);
2434 XRecolorCursor(xw.dpy, cursor,
2435 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2436 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2438 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2439 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2440 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2443 XMapWindow(xw.dpy, xw.win);
2449 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2450 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2451 width = charlen * xw.cw;
2452 Font *font = &dc.font;
2454 Colour *fg = &dc.col[base.fg], *bg = &dc.col[base.bg],
2455 *temp, revfg, revbg;
2456 XRenderColor colfg, colbg;
2458 if(base.mode & ATTR_BOLD) {
2459 if(BETWEEN(base.fg, 0, 7)) {
2460 /* basic system colors */
2461 fg = &dc.col[base.fg + 8];
2462 } else if(BETWEEN(base.fg, 16, 195)) {
2464 fg = &dc.col[base.fg + 36];
2465 } else if(BETWEEN(base.fg, 232, 251)) {
2467 fg = &dc.col[base.fg + 4];
2470 * Those ranges will not be brightened:
2471 * 8 - 15 – bright system colors
2472 * 196 - 231 – highest 256 color cube
2473 * 252 - 255 – brightest colors in greyscale
2478 if(base.mode & ATTR_ITALIC)
2480 if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD))
2483 if(IS_SET(MODE_REVERSE)) {
2484 if(fg == &dc.col[defaultfg]) {
2485 fg = &dc.col[defaultbg];
2487 colfg.red = ~fg->color.red;
2488 colfg.green = ~fg->color.green;
2489 colfg.blue = ~fg->color.blue;
2490 colfg.alpha = fg->color.alpha;
2491 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2495 if(bg == &dc.col[defaultbg]) {
2496 bg = &dc.col[defaultfg];
2498 colbg.red = ~bg->color.red;
2499 colbg.green = ~bg->color.green;
2500 colbg.blue = ~bg->color.blue;
2501 colbg.alpha = bg->color.alpha;
2502 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2507 if(base.mode & ATTR_REVERSE)
2508 temp = fg, fg = bg, bg = temp;
2510 XftTextExtentsUtf8(xw.dpy, font->set, (FcChar8 *)s, bytelen,
2512 width = extents.xOff;
2514 /* Intelligent cleaning up of the borders. */
2516 xclear(0, (y == 0)? 0 : winy, borderpx,
2517 winy + xw.ch + (y == term.row-1)? xw.h : 0);
2519 if(x + charlen >= term.col-1) {
2520 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2521 (y == term.row-1)? xw.h : (winy + xw.ch));
2524 xclear(winx, 0, winx + width, borderpx);
2526 xclear(winx, winy + xw.ch, winx + width, xw.h);
2528 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
2529 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
2530 winy + font->ascent, (FcChar8 *)s, bytelen);
2532 if(base.mode & ATTR_UNDERLINE) {
2533 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
2540 static int oldx = 0, oldy = 0;
2542 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs, 0};
2544 LIMIT(oldx, 0, term.col-1);
2545 LIMIT(oldy, 0, term.row-1);
2547 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2548 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2550 /* remove the old cursor */
2551 if(term.line[oldy][oldx].state & GLYPH_SET) {
2552 sl = utf8size(term.line[oldy][oldx].c);
2553 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2556 xtermclear(oldx, oldy, oldx, oldy);
2559 /* draw the new one */
2560 if(!(IS_SET(MODE_HIDE))) {
2561 if(!(xw.state & WIN_FOCUSED))
2564 if(IS_SET(MODE_REVERSE))
2565 g.mode |= ATTR_REVERSE, g.fg = defaultcs, g.bg = defaultfg;
2568 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2569 oldx = term.c.x, oldy = term.c.y;
2575 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2580 struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2584 XSync(xw.dpy, False); /* necessary for a good tput flash */
2585 nanosleep(&tv, NULL);
2590 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2592 drawregion(0, 0, term.col, term.row);
2593 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2597 drawregion(int x1, int y1, int x2, int y2) {
2598 int ic, ib, x, y, ox, sl;
2600 char buf[DRAW_BUF_SIZ];
2601 bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN) != 0;
2603 if((sel.alt != 0) ^ alt)
2605 if(!(xw.state & WIN_VISIBLE))
2608 for(y = y1; y < y2; y++) {
2612 xtermclear(0, y, term.col, y);
2614 base = term.line[y][0];
2616 for(x = x1; x < x2; x++) {
2617 new = term.line[y][x];
2618 if(ena_sel && *(new.c) && selected(x, y))
2619 new.mode ^= ATTR_REVERSE;
2620 if(ib > 0 && (!(new.state & GLYPH_SET)
2621 || ATTRCMP(base, new)
2622 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2623 xdraws(buf, base, ox, y, ic, ib);
2626 if(new.state & GLYPH_SET) {
2631 sl = utf8size(new.c);
2632 memcpy(buf+ib, new.c, sl);
2638 xdraws(buf, base, ox, y, ic, ib);
2644 expose(XEvent *ev) {
2645 XExposeEvent *e = &ev->xexpose;
2647 if(xw.state & WIN_REDRAW) {
2649 xw.state &= ~WIN_REDRAW;
2654 visibility(XEvent *ev) {
2655 XVisibilityEvent *e = &ev->xvisibility;
2657 if(e->state == VisibilityFullyObscured) {
2658 xw.state &= ~WIN_VISIBLE;
2659 } else if(!(xw.state & WIN_VISIBLE)) {
2660 /* need a full redraw for next Expose, not just a buf copy */
2661 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2667 xw.state &= ~WIN_VISIBLE;
2671 xseturgency(int add) {
2672 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2674 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2675 XSetWMHints(xw.dpy, xw.win, h);
2681 if(ev->type == FocusIn) {
2682 XSetICFocus(xw.xic);
2683 xw.state |= WIN_FOCUSED;
2686 XUnsetICFocus(xw.xic);
2687 xw.state &= ~WIN_FOCUSED;
2692 kmap(KeySym k, uint state) {
2697 for(kp = key; kp < key + LEN(key); kp++) {
2703 if((state & mask) != mask ||
2704 (mask == XK_NO_MOD && state)) {
2708 if((kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) ||
2709 (kp->appkey > 0 && !IS_SET(MODE_APPKEYPAD))) {
2713 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
2714 (kp->appcursor > 0 && !IS_SET(MODE_APPCURSOR))) {
2718 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
2719 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
2730 kpress(XEvent *ev) {
2731 XKeyEvent *e = &ev->xkey;
2733 char xstr[31], buf[32], *customkey, *cp = buf;
2737 if (IS_SET(MODE_KBDLOCK))
2740 len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
2743 for(i = 0; i < LEN(shortcuts); i++) {
2744 if((ksym == shortcuts[i].keysym)
2745 && (CLEANMASK(shortcuts[i].mod) == \
2746 CLEANMASK(e->state))
2747 && shortcuts[i].func) {
2748 shortcuts[i].func(&(shortcuts[i].arg));
2752 /* 2. custom keys from config.h */
2753 if((customkey = kmap(ksym, e->state))) {
2754 len = strlen(customkey);
2755 memcpy(buf, customkey, len);
2756 /* 2. hardcoded (overrides X lookup) */
2761 if (len == 1 && e->state & Mod1Mask)
2764 memcpy(cp, xstr, len);
2765 len = cp - buf + len;
2769 if(IS_SET(MODE_ECHO))
2775 cmessage(XEvent *e) {
2777 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2778 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2779 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2780 xw.state |= WIN_FOCUSED;
2782 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2783 xw.state &= ~WIN_FOCUSED;
2785 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
2786 /* Send SIGHUP to shell */
2793 cresize(int width, int height)
2802 col = (xw.w - 2*borderpx) / xw.cw;
2803 row = (xw.h - 2*borderpx) / xw.ch;
2812 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2815 cresize(e->xconfigure.width, e->xconfigure.height);
2822 int xfd = XConnectionNumber(xw.dpy), i;
2823 struct timeval drawtimeout, *tv = NULL;
2827 FD_SET(cmdfd, &rfd);
2829 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2832 die("select failed: %s\n", SERRNO);
2836 * Stop after a certain number of reads so the user does not
2837 * feel like the system is stuttering.
2839 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2843 * Just wait a bit so it isn't disturbing the
2844 * user and the system is able to write something.
2846 drawtimeout.tv_sec = 0;
2847 drawtimeout.tv_usec = 5;
2854 while(XPending(xw.dpy)) {
2855 XNextEvent(xw.dpy, &ev);
2856 if(XFilterEvent(&ev, None))
2858 if(handler[ev.type])
2859 (handler[ev.type])(&ev);
2868 main(int argc, char *argv[]) {
2869 int i, bitm, xr, yr;
2872 xw.fw = xw.fh = xw.fx = xw.fy = 0;
2875 for(i = 1; i < argc; i++) {
2876 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2879 opt_class = argv[i];
2882 /* eat all remaining arguments */
2894 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2899 if(bitm & WidthValue)
2901 if(bitm & HeightValue)
2903 if(bitm & XNegative && xw.fx == 0)
2905 if(bitm & XNegative && xw.fy == 0)
2908 if(xw.fh != 0 && xw.fw != 0)
2917 opt_title = argv[i];
2924 opt_embed = argv[i];
2930 setlocale(LC_CTYPE, "");
2931 XSetLocaleModifiers("");