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_ANY_MOD UINT_MAX
65 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
68 #define SERRNO strerror(errno)
69 #define MIN(a, b) ((a) < (b) ? (a) : (b))
70 #define MAX(a, b) ((a) < (b) ? (b) : (a))
71 #define LEN(a) (sizeof(a) / sizeof(a[0]))
72 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
73 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
74 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
75 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
76 #define IS_SET(flag) ((term.mode & (flag)) != 0)
77 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
79 #define VT102ID "\033[?6c"
81 enum glyph_attribute {
91 enum cursor_movement {
114 MODE_MOUSEMOTION = 64,
120 MODE_APPCURSOR = 2048
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 */
197 bool numlock; /* lock numbers in keyboard */
201 /* Purely graphic info */
207 Atom xembed, wmdeletewin;
213 bool isfixed; /* is fixed geometry? */
214 int fx, fy, fw, fh; /* fixed geometry */
215 int tw, th; /* tty width and height */
216 int w; /* window width */
217 int h; /* window height */
218 int ch; /* char height */
219 int cw; /* char width */
220 char state; /* focus, redraw, visible */
227 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
228 signed char appkey; /* application keypad */
229 signed char appcursor; /* application cursor */
230 signed char crlf; /* crlf mode */
233 /* TODO: use better name for vars... */
244 struct timeval tclick1;
245 struct timeval tclick2;
258 void (*func)(const Arg *);
262 /* function definitions used in config.h */
263 static void xzoom(const Arg *);
264 static void selpaste(const Arg *);
265 static void numlock(const Arg *);
267 /* Config.h for applying patches and the configuration. */
281 /* Drawing Context */
283 Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
284 Font font, bfont, ifont, ibfont;
287 static void die(const char *, ...);
288 static void draw(void);
289 static void redraw(void);
290 static void drawregion(int, int, int, int);
291 static void execsh(void);
292 static void sigchld(int);
293 static void run(void);
295 static void csidump(void);
296 static void csihandle(void);
297 static void csiparse(void);
298 static void csireset(void);
299 static void strdump(void);
300 static void strhandle(void);
301 static void strparse(void);
302 static void strreset(void);
304 static void tclearregion(int, int, int, int);
305 static void tcursor(int);
306 static void tdeletechar(int);
307 static void tdeleteline(int);
308 static void tinsertblank(int);
309 static void tinsertblankline(int);
310 static void tmoveto(int, int);
311 static void tmoveato(int x, int y);
312 static void tnew(int, int);
313 static void tnewline(int);
314 static void tputtab(bool);
315 static void tputc(char *, int);
316 static void treset(void);
317 static int tresize(int, int);
318 static void tscrollup(int, int);
319 static void tscrolldown(int, int);
320 static void tsetattr(int*, int);
321 static void tsetchar(char *, Glyph *, int, int);
322 static void tsetscroll(int, int);
323 static void tswapscreen(void);
324 static void tsetdirt(int, int);
325 static void tsetmode(bool, bool, int *, int);
326 static void tfulldirt(void);
327 static void techo(char *, int);
329 static inline bool match(uint, uint);
330 static void ttynew(void);
331 static void ttyread(void);
332 static void ttyresize(void);
333 static void ttywrite(const char *, size_t);
335 static void xdraws(char *, Glyph, int, int, int, int);
336 static void xhints(void);
337 static void xclear(int, int, int, int);
338 static void xdrawcursor(void);
339 static void xinit(void);
340 static void xloadcols(void);
341 static void xresettitle(void);
342 static void xseturgency(int);
343 static void xsetsel(char*);
344 static void xtermclear(int, int, int, int);
345 static void xresize(int, int);
347 static void expose(XEvent *);
348 static void visibility(XEvent *);
349 static void unmap(XEvent *);
350 static char *kmap(KeySym, uint);
351 static void kpress(XEvent *);
352 static void cmessage(XEvent *);
353 static void cresize(int width, int height);
354 static void resize(XEvent *);
355 static void focus(XEvent *);
356 static void brelease(XEvent *);
357 static void bpress(XEvent *);
358 static void bmotion(XEvent *);
359 static void selnotify(XEvent *);
360 static void selclear(XEvent *);
361 static void selrequest(XEvent *);
363 static void selinit(void);
364 static inline bool selected(int, int);
365 static void selcopy(void);
366 static void selscroll(int, int);
368 static int utf8decode(char *, long *);
369 static int utf8encode(long *, char *);
370 static int utf8size(char *);
371 static int isfullutf8(char *, int);
373 static ssize_t xwrite(int, char *, size_t);
374 static void *xmalloc(size_t);
375 static void *xrealloc(void *, size_t);
376 static void *xcalloc(size_t nmemb, size_t size);
378 static void (*handler[LASTEvent])(XEvent *) = {
380 [ClientMessage] = cmessage,
381 [ConfigureNotify] = resize,
382 [VisibilityNotify] = visibility,
383 [UnmapNotify] = unmap,
387 [MotionNotify] = bmotion,
388 [ButtonPress] = bpress,
389 [ButtonRelease] = brelease,
390 [SelectionClear] = selclear,
391 [SelectionNotify] = selnotify,
392 [SelectionRequest] = selrequest,
399 static CSIEscape csiescseq;
400 static STREscape strescseq;
403 static Selection sel;
404 static int iofd = -1;
405 static char **opt_cmd = NULL;
406 static char *opt_io = NULL;
407 static char *opt_title = NULL;
408 static char *opt_embed = NULL;
409 static char *opt_class = NULL;
410 static char *opt_font = NULL;
412 static char *usedfont = NULL;
413 static int usedfontsize = 0;
416 xwrite(int fd, char *s, size_t len) {
420 ssize_t r = write(fd, s, len);
430 xmalloc(size_t len) {
431 void *p = malloc(len);
434 die("Out of memory\n");
440 xrealloc(void *p, size_t len) {
441 if((p = realloc(p, len)) == NULL)
442 die("Out of memory\n");
448 xcalloc(size_t nmemb, size_t size) {
449 void *p = calloc(nmemb, size);
452 die("Out of memory\n");
458 utf8decode(char *s, long *u) {
464 if(~c & B7) { /* 0xxxxxxx */
467 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
468 *u = c&(B4|B3|B2|B1|B0);
470 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
471 *u = c&(B3|B2|B1|B0);
473 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
480 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
482 if((c & (B7|B6)) != B7) /* 10xxxxxx */
485 *u |= c & (B5|B4|B3|B2|B1|B0);
488 if((n == 1 && *u < 0x80) ||
489 (n == 2 && *u < 0x800) ||
490 (n == 3 && *u < 0x10000) ||
491 (*u >= 0xD800 && *u <= 0xDFFF)) {
503 utf8encode(long *u, char *s) {
511 *sp = uc; /* 0xxxxxxx */
513 } else if(*u < 0x800) {
514 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
516 } else if(uc < 0x10000) {
517 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
519 } else if(uc <= 0x10FFFF) {
520 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
526 for(i=n,++sp; i>0; --i,++sp)
527 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
539 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
540 UTF-8 otherwise return 0 */
542 isfullutf8(char *s, int b) {
550 } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
552 } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
554 ((b == 2) && (*c2&(B7|B6)) == B7))) {
556 } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
558 ((b == 2) && (*c2&(B7|B6)) == B7) ||
559 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
572 } else if((c&(B7|B6|B5)) == (B7|B6)) {
574 } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
583 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
584 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
588 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
589 if(sel.xtarget == None)
590 sel.xtarget = XA_STRING;
598 return LIMIT(x, 0, term.col-1);
606 return LIMIT(y, 0, term.row-1);
610 selected(int x, int y) {
613 if(sel.ey == y && sel.by == y) {
614 bx = MIN(sel.bx, sel.ex);
615 ex = MAX(sel.bx, sel.ex);
616 return BETWEEN(x, bx, ex);
619 return ((sel.b.y < y && y < sel.e.y)
620 || (y == sel.e.y && x <= sel.e.x))
621 || (y == sel.b.y && x >= sel.b.x
622 && (x <= sel.e.x || sel.b.y != sel.e.y));
626 getbuttoninfo(XEvent *e) {
627 sel.alt = IS_SET(MODE_ALTSCREEN);
629 sel.ex = x2col(e->xbutton.x);
630 sel.ey = y2row(e->xbutton.y);
632 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
633 sel.b.y = MIN(sel.by, sel.ey);
634 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
635 sel.e.y = MAX(sel.by, sel.ey);
639 mousereport(XEvent *e) {
640 int x = x2col(e->xbutton.x);
641 int y = y2row(e->xbutton.y);
642 int button = e->xbutton.button;
643 int state = e->xbutton.state;
644 char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
645 static int ob, ox, oy;
648 if(e->xbutton.type == MotionNotify) {
649 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
653 } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
659 if(e->xbutton.type == ButtonPress) {
665 buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
666 + (state & Mod4Mask ? 8 : 0)
667 + (state & ControlMask ? 16 : 0);
669 ttywrite(buf, sizeof(buf));
674 if(IS_SET(MODE_MOUSE)) {
676 } else if(e->xbutton.button == Button1) {
679 tsetdirt(sel.b.y, sel.e.y);
683 sel.ex = sel.bx = x2col(e->xbutton.x);
684 sel.ey = sel.by = y2row(e->xbutton.y);
685 } else if(e->xbutton.button == Button4) {
687 } else if(e->xbutton.button == Button5) {
695 int x, y, bufsize, is_selected = 0, size;
701 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
702 ptr = str = xmalloc(bufsize);
704 /* append every set & selected glyph to the selection */
705 for(y = 0; y < term.row; y++) {
706 gp = &term.line[y][0];
707 last = gp + term.col;
709 while(--last >= gp && !(last->state & GLYPH_SET))
712 for(x = 0; gp <= last; x++, ++gp) {
713 if(!(is_selected = selected(x, y)))
716 p = (gp->state & GLYPH_SET) ? gp->c : " ";
718 memcpy(ptr, p, size);
721 /* \n at the end of every selected line except for the last one */
722 if(is_selected && y < sel.e.y)
731 selnotify(XEvent *e) {
732 ulong nitems, ofs, rem;
739 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
740 False, AnyPropertyType, &type, &format,
741 &nitems, &rem, &data)) {
742 fprintf(stderr, "Clipboard allocation failed\n");
745 ttywrite((const char *) data, nitems * format / 8);
747 /* number of 32-bit chunks returned */
748 ofs += nitems * format / 32;
753 selpaste(const Arg *dummy) {
754 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
755 xw.win, CurrentTime);
758 void selclear(XEvent *e) {
762 tsetdirt(sel.b.y, sel.e.y);
766 selrequest(XEvent *e) {
767 XSelectionRequestEvent *xsre;
769 Atom xa_targets, string;
771 xsre = (XSelectionRequestEvent *) e;
772 xev.type = SelectionNotify;
773 xev.requestor = xsre->requestor;
774 xev.selection = xsre->selection;
775 xev.target = xsre->target;
776 xev.time = xsre->time;
780 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
781 if(xsre->target == xa_targets) {
782 /* respond with the supported type */
783 string = sel.xtarget;
784 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
785 XA_ATOM, 32, PropModeReplace,
786 (uchar *) &string, 1);
787 xev.property = xsre->property;
788 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
789 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
790 xsre->target, 8, PropModeReplace,
791 (uchar *) sel.clip, strlen(sel.clip));
792 xev.property = xsre->property;
795 /* all done, send a notification to the listener */
796 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
797 fprintf(stderr, "Error sending SelectionNotify event\n");
802 /* register the selection for both the clipboard and the primary */
808 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
810 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
811 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
815 brelease(XEvent *e) {
818 if(IS_SET(MODE_MOUSE)) {
823 if(e->xbutton.button == Button2) {
825 } else if(e->xbutton.button == Button1) {
828 term.dirty[sel.ey] = 1;
829 if(sel.bx == sel.ex && sel.by == sel.ey) {
831 gettimeofday(&now, NULL);
833 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
834 /* triple click on the line */
835 sel.b.x = sel.bx = 0;
836 sel.e.x = sel.ex = term.col;
837 sel.b.y = sel.e.y = sel.ey;
839 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
840 /* double click to select word */
842 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
843 term.line[sel.ey][sel.bx-1].c[0] != ' ') {
847 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
848 term.line[sel.ey][sel.ex+1].c[0] != ' ') {
852 sel.b.y = sel.e.y = sel.ey;
860 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
861 gettimeofday(&sel.tclick1, NULL);
866 int starty, endy, oldey, oldex;
868 if(IS_SET(MODE_MOUSE)) {
880 if(oldey != sel.ey || oldex != sel.ex) {
881 starty = MIN(oldey, sel.ey);
882 endy = MAX(oldey, sel.ey);
883 tsetdirt(starty, endy);
888 die(const char *errstr, ...) {
891 va_start(ap, errstr);
892 vfprintf(stderr, errstr, ap);
900 char *envshell = getenv("SHELL");
901 const struct passwd *pass = getpwuid(getuid());
902 char buf[sizeof(long) * 8 + 1];
909 setenv("LOGNAME", pass->pw_name, 1);
910 setenv("USER", pass->pw_name, 1);
911 setenv("SHELL", pass->pw_shell, 0);
912 setenv("HOME", pass->pw_dir, 0);
915 snprintf(buf, sizeof(buf), "%lu", xw.win);
916 setenv("WINDOWID", buf, 1);
918 signal(SIGCHLD, SIG_DFL);
919 signal(SIGHUP, SIG_DFL);
920 signal(SIGINT, SIG_DFL);
921 signal(SIGQUIT, SIG_DFL);
922 signal(SIGTERM, SIG_DFL);
923 signal(SIGALRM, SIG_DFL);
925 DEFAULT(envshell, shell);
926 setenv("TERM", termname, 1);
927 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
928 execvp(args[0], args);
936 if(waitpid(pid, &stat, 0) < 0)
937 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
939 if(WIFEXITED(stat)) {
940 exit(WEXITSTATUS(stat));
949 struct winsize w = {term.row, term.col, 0, 0};
951 /* seems to work fine on linux, openbsd and freebsd */
952 if(openpty(&m, &s, NULL, NULL, &w) < 0)
953 die("openpty failed: %s\n", SERRNO);
955 switch(pid = fork()) {
957 die("fork failed\n");
960 setsid(); /* create a new process group */
961 dup2(s, STDIN_FILENO);
962 dup2(s, STDOUT_FILENO);
963 dup2(s, STDERR_FILENO);
964 if(ioctl(s, TIOCSCTTY, NULL) < 0)
965 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
973 signal(SIGCHLD, sigchld);
975 iofd = (!strcmp(opt_io, "-")) ?
977 open(opt_io, O_WRONLY | O_CREAT, 0666);
979 fprintf(stderr, "Error opening %s:%s\n",
980 opt_io, strerror(errno));
990 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
992 fprintf(stderr, "\n");
997 static char buf[BUFSIZ];
998 static int buflen = 0;
1001 int charsize; /* size of utf8 char in bytes */
1005 /* append read bytes to unprocessed bytes */
1006 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1007 die("Couldn't read from shell: %s\n", SERRNO);
1009 /* process every complete utf8 char */
1012 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1013 charsize = utf8decode(ptr, &utf8c);
1014 utf8encode(&utf8c, s);
1020 /* keep any uncomplete utf8 char for the next call */
1021 memmove(buf, ptr, buflen);
1025 ttywrite(const char *s, size_t n) {
1026 if(write(cmdfd, s, n) == -1)
1027 die("write error on tty: %s\n", SERRNO);
1034 w.ws_row = term.row;
1035 w.ws_col = term.col;
1036 w.ws_xpixel = xw.tw;
1037 w.ws_ypixel = xw.th;
1038 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1039 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1043 tsetdirt(int top, int bot) {
1046 LIMIT(top, 0, term.row-1);
1047 LIMIT(bot, 0, term.row-1);
1049 for(i = top; i <= bot; i++)
1055 tsetdirt(0, term.row-1);
1062 if(mode == CURSOR_SAVE) {
1064 } else if(mode == CURSOR_LOAD) {
1074 term.c = (TCursor){{
1078 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1080 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1081 for(i = tabspaces; i < term.col; i += tabspaces)
1084 term.bot = term.row - 1;
1085 term.mode = MODE_WRAP;
1087 tclearregion(0, 0, term.col-1, term.row-1);
1089 tcursor(CURSOR_SAVE);
1093 tnew(int col, int row) {
1094 /* set screen size */
1097 term.line = xmalloc(term.row * sizeof(Line));
1098 term.alt = xmalloc(term.row * sizeof(Line));
1099 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1100 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1102 for(row = 0; row < term.row; row++) {
1103 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1104 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1105 term.dirty[row] = 0;
1109 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1116 Line *tmp = term.line;
1118 term.line = term.alt;
1120 term.mode ^= MODE_ALTSCREEN;
1125 tscrolldown(int orig, int n) {
1129 LIMIT(n, 0, term.bot-orig+1);
1131 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1133 for(i = term.bot; i >= orig+n; i--) {
1134 temp = term.line[i];
1135 term.line[i] = term.line[i-n];
1136 term.line[i-n] = temp;
1139 term.dirty[i-n] = 1;
1146 tscrollup(int orig, int n) {
1149 LIMIT(n, 0, term.bot-orig+1);
1151 tclearregion(0, orig, term.col-1, orig+n-1);
1153 for(i = orig; i <= term.bot-n; i++) {
1154 temp = term.line[i];
1155 term.line[i] = term.line[i+n];
1156 term.line[i+n] = temp;
1159 term.dirty[i+n] = 1;
1162 selscroll(orig, -n);
1166 selscroll(int orig, int n) {
1170 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1171 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1175 if(sel.by < term.top) {
1179 if(sel.ey > term.bot) {
1183 sel.b.y = sel.by, sel.b.x = sel.bx;
1184 sel.e.y = sel.ey, sel.e.x = sel.ex;
1189 tnewline(int first_col) {
1193 tscrollup(term.top, 1);
1197 tmoveto(first_col ? 0 : term.c.x, y);
1202 /* int noarg = 1; */
1203 char *p = csiescseq.buf;
1207 csiescseq.priv = 1, p++;
1209 while(p < csiescseq.buf+csiescseq.len) {
1210 while(isdigit(*p)) {
1211 csiescseq.arg[csiescseq.narg] *= 10;
1212 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1214 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1215 csiescseq.narg++, p++;
1217 csiescseq.mode = *p;
1225 /* for absolute user moves, when decom is set */
1227 tmoveato(int x, int y) {
1228 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1232 tmoveto(int x, int y) {
1235 if(term.c.state & CURSOR_ORIGIN) {
1240 maxy = term.row - 1;
1242 LIMIT(x, 0, term.col-1);
1243 LIMIT(y, miny, maxy);
1244 term.c.state &= ~CURSOR_WRAPNEXT;
1250 tsetchar(char *c, Glyph *attr, int x, int y) {
1251 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1252 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1253 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1254 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1255 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1256 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1257 "", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1258 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1259 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1263 * The table is proudly stolen from rxvt.
1265 if(attr->mode & ATTR_GFX) {
1266 if(c[0] >= 0x41 && c[0] <= 0x7e
1267 && vt100_0[c[0] - 0x41]) {
1268 c = vt100_0[c[0] - 0x41];
1273 term.line[y][x] = *attr;
1274 memcpy(term.line[y][x].c, c, UTF_SIZ);
1275 term.line[y][x].state |= GLYPH_SET;
1279 tclearregion(int x1, int y1, int x2, int y2) {
1283 temp = x1, x1 = x2, x2 = temp;
1285 temp = y1, y1 = y2, y2 = temp;
1287 LIMIT(x1, 0, term.col-1);
1288 LIMIT(x2, 0, term.col-1);
1289 LIMIT(y1, 0, term.row-1);
1290 LIMIT(y2, 0, term.row-1);
1292 for(y = y1; y <= y2; y++) {
1294 for(x = x1; x <= x2; x++)
1295 term.line[y][x].state = 0;
1300 tdeletechar(int n) {
1301 int src = term.c.x + n;
1303 int size = term.col - src;
1305 term.dirty[term.c.y] = 1;
1307 if(src >= term.col) {
1308 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1312 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1313 size * sizeof(Glyph));
1314 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1318 tinsertblank(int n) {
1321 int size = term.col - dst;
1323 term.dirty[term.c.y] = 1;
1325 if(dst >= term.col) {
1326 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1330 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1331 size * sizeof(Glyph));
1332 tclearregion(src, term.c.y, dst - 1, term.c.y);
1336 tinsertblankline(int n) {
1337 if(term.c.y < term.top || term.c.y > term.bot)
1340 tscrolldown(term.c.y, n);
1344 tdeleteline(int n) {
1345 if(term.c.y < term.top || term.c.y > term.bot)
1348 tscrollup(term.c.y, n);
1352 tsetattr(int *attr, int l) {
1355 for(i = 0; i < l; i++) {
1358 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1359 | ATTR_ITALIC | ATTR_BLINK);
1360 term.c.attr.fg = defaultfg;
1361 term.c.attr.bg = defaultbg;
1364 term.c.attr.mode |= ATTR_BOLD;
1366 case 3: /* enter standout (highlight) */
1367 term.c.attr.mode |= ATTR_ITALIC;
1370 term.c.attr.mode |= ATTR_UNDERLINE;
1373 term.c.attr.mode |= ATTR_BLINK;
1376 term.c.attr.mode |= ATTR_REVERSE;
1380 term.c.attr.mode &= ~ATTR_BOLD;
1382 case 23: /* leave standout (highlight) mode */
1383 term.c.attr.mode &= ~ATTR_ITALIC;
1386 term.c.attr.mode &= ~ATTR_UNDERLINE;
1389 term.c.attr.mode &= ~ATTR_BLINK;
1392 term.c.attr.mode &= ~ATTR_REVERSE;
1395 if(i + 2 < l && attr[i + 1] == 5) {
1397 if(BETWEEN(attr[i], 0, 255)) {
1398 term.c.attr.fg = attr[i];
1401 "erresc: bad fgcolor %d\n",
1406 "erresc(38): gfx attr %d unknown\n",
1411 term.c.attr.fg = defaultfg;
1414 if(i + 2 < l && attr[i + 1] == 5) {
1416 if(BETWEEN(attr[i], 0, 255)) {
1417 term.c.attr.bg = attr[i];
1420 "erresc: bad bgcolor %d\n",
1425 "erresc(48): gfx attr %d unknown\n",
1430 term.c.attr.bg = defaultbg;
1433 if(BETWEEN(attr[i], 30, 37)) {
1434 term.c.attr.fg = attr[i] - 30;
1435 } else if(BETWEEN(attr[i], 40, 47)) {
1436 term.c.attr.bg = attr[i] - 40;
1437 } else if(BETWEEN(attr[i], 90, 97)) {
1438 term.c.attr.fg = attr[i] - 90 + 8;
1439 } else if(BETWEEN(attr[i], 100, 107)) {
1440 term.c.attr.bg = attr[i] - 100 + 8;
1443 "erresc(default): gfx attr %d unknown\n",
1444 attr[i]), csidump();
1452 tsetscroll(int t, int b) {
1455 LIMIT(t, 0, term.row-1);
1456 LIMIT(b, 0, term.row-1);
1466 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1469 tsetmode(bool priv, bool set, int *args, int narg) {
1473 for(lim = args + narg; args < lim; ++args) {
1477 case 1: /* DECCKM -- Cursor key */
1478 MODBIT(term.mode, set, MODE_APPCURSOR);
1480 case 5: /* DECSCNM -- Reverse video */
1482 MODBIT(term.mode, set, MODE_REVERSE);
1483 if(mode != term.mode)
1486 case 6: /* DECOM -- Origin */
1487 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1490 case 7: /* DECAWM -- Auto wrap */
1491 MODBIT(term.mode, set, MODE_WRAP);
1493 case 0: /* Error (IGNORED) */
1494 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1495 case 3: /* DECCOLM -- Column (IGNORED) */
1496 case 4: /* DECSCLM -- Scroll (IGNORED) */
1497 case 8: /* DECARM -- Auto repeat (IGNORED) */
1498 case 18: /* DECPFF -- Printer feed (IGNORED) */
1499 case 19: /* DECPEX -- Printer extent (IGNORED) */
1500 case 42: /* DECNRCM -- National characters (IGNORED) */
1501 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1503 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1504 MODBIT(term.mode, !set, MODE_HIDE);
1506 case 1000: /* 1000,1002: enable xterm mouse report */
1507 MODBIT(term.mode, set, MODE_MOUSEBTN);
1510 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1512 case 1049: /* = 1047 and 1048 */
1515 alt = IS_SET(MODE_ALTSCREEN);
1517 tclearregion(0, 0, term.col-1, term.row-1);
1518 if(set ^ alt) /* set is always 1 or 0 */
1525 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1529 "erresc: unknown private set/reset mode %d\n",
1535 case 0: /* Error (IGNORED) */
1537 case 2: /* KAM -- keyboard action */
1538 MODBIT(term.mode, set, MODE_KBDLOCK);
1540 case 4: /* IRM -- Insertion-replacement */
1541 MODBIT(term.mode, set, MODE_INSERT);
1543 case 12: /* SRM -- Send/Receive */
1544 MODBIT(term.mode, !set, MODE_ECHO);
1546 case 20: /* LNM -- Linefeed/new line */
1547 MODBIT(term.mode, set, MODE_CRLF);
1551 "erresc: unknown set/reset mode %d\n",
1563 switch(csiescseq.mode) {
1566 fprintf(stderr, "erresc: unknown csi ");
1570 case '@': /* ICH -- Insert <n> blank char */
1571 DEFAULT(csiescseq.arg[0], 1);
1572 tinsertblank(csiescseq.arg[0]);
1574 case 'A': /* CUU -- Cursor <n> Up */
1575 DEFAULT(csiescseq.arg[0], 1);
1576 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1578 case 'B': /* CUD -- Cursor <n> Down */
1579 case 'e': /* VPR --Cursor <n> Down */
1580 DEFAULT(csiescseq.arg[0], 1);
1581 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1583 case 'c': /* DA -- Device Attributes */
1584 if(csiescseq.arg[0] == 0)
1585 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1587 case 'C': /* CUF -- Cursor <n> Forward */
1588 case 'a': /* HPR -- Cursor <n> Forward */
1589 DEFAULT(csiescseq.arg[0], 1);
1590 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1592 case 'D': /* CUB -- Cursor <n> Backward */
1593 DEFAULT(csiescseq.arg[0], 1);
1594 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1596 case 'E': /* CNL -- Cursor <n> Down and first col */
1597 DEFAULT(csiescseq.arg[0], 1);
1598 tmoveto(0, term.c.y+csiescseq.arg[0]);
1600 case 'F': /* CPL -- Cursor <n> Up and first col */
1601 DEFAULT(csiescseq.arg[0], 1);
1602 tmoveto(0, term.c.y-csiescseq.arg[0]);
1604 case 'g': /* TBC -- Tabulation clear */
1605 switch (csiescseq.arg[0]) {
1606 case 0: /* clear current tab stop */
1607 term.tabs[term.c.x] = 0;
1609 case 3: /* clear all the tabs */
1610 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1616 case 'G': /* CHA -- Move to <col> */
1618 DEFAULT(csiescseq.arg[0], 1);
1619 tmoveto(csiescseq.arg[0]-1, term.c.y);
1621 case 'H': /* CUP -- Move to <row> <col> */
1623 DEFAULT(csiescseq.arg[0], 1);
1624 DEFAULT(csiescseq.arg[1], 1);
1625 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1627 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1628 DEFAULT(csiescseq.arg[0], 1);
1629 while(csiescseq.arg[0]--)
1632 case 'J': /* ED -- Clear screen */
1634 switch(csiescseq.arg[0]) {
1636 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1637 if(term.c.y < term.row-1)
1638 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1642 tclearregion(0, 0, term.col-1, term.c.y-1);
1643 tclearregion(0, term.c.y, term.c.x, term.c.y);
1646 tclearregion(0, 0, term.col-1, term.row-1);
1652 case 'K': /* EL -- Clear line */
1653 switch(csiescseq.arg[0]) {
1655 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1658 tclearregion(0, term.c.y, term.c.x, term.c.y);
1661 tclearregion(0, term.c.y, term.col-1, term.c.y);
1665 case 'S': /* SU -- Scroll <n> line up */
1666 DEFAULT(csiescseq.arg[0], 1);
1667 tscrollup(term.top, csiescseq.arg[0]);
1669 case 'T': /* SD -- Scroll <n> line down */
1670 DEFAULT(csiescseq.arg[0], 1);
1671 tscrolldown(term.top, csiescseq.arg[0]);
1673 case 'L': /* IL -- Insert <n> blank lines */
1674 DEFAULT(csiescseq.arg[0], 1);
1675 tinsertblankline(csiescseq.arg[0]);
1677 case 'l': /* RM -- Reset Mode */
1678 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1680 case 'M': /* DL -- Delete <n> lines */
1681 DEFAULT(csiescseq.arg[0], 1);
1682 tdeleteline(csiescseq.arg[0]);
1684 case 'X': /* ECH -- Erase <n> char */
1685 DEFAULT(csiescseq.arg[0], 1);
1686 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1688 case 'P': /* DCH -- Delete <n> char */
1689 DEFAULT(csiescseq.arg[0], 1);
1690 tdeletechar(csiescseq.arg[0]);
1692 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1693 DEFAULT(csiescseq.arg[0], 1);
1694 while(csiescseq.arg[0]--)
1697 case 'd': /* VPA -- Move to <row> */
1698 DEFAULT(csiescseq.arg[0], 1);
1699 tmoveato(term.c.x, csiescseq.arg[0]-1);
1701 case 'h': /* SM -- Set terminal mode */
1702 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1704 case 'm': /* SGR -- Terminal attribute (color) */
1705 tsetattr(csiescseq.arg, csiescseq.narg);
1707 case 'r': /* DECSTBM -- Set Scrolling Region */
1708 if(csiescseq.priv) {
1711 DEFAULT(csiescseq.arg[0], 1);
1712 DEFAULT(csiescseq.arg[1], term.row);
1713 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1717 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1718 tcursor(CURSOR_SAVE);
1720 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1721 tcursor(CURSOR_LOAD);
1732 for(i = 0; i < csiescseq.len; i++) {
1733 c = csiescseq.buf[i] & 0xff;
1736 } else if(c == '\n') {
1738 } else if(c == '\r') {
1740 } else if(c == 0x1b) {
1743 printf("(%02x)", c);
1751 memset(&csiescseq, 0, sizeof(csiescseq));
1759 * TODO: make this being useful in case of color palette change.
1765 switch(strescseq.type) {
1766 case ']': /* OSC -- Operating System Command */
1772 * TODO: Handle special chars in string, like umlauts.
1775 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1779 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1781 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1784 fprintf(stderr, "erresc: unknown str ");
1789 case 'k': /* old title set compatibility */
1790 XStoreName(xw.dpy, xw.win, strescseq.buf);
1792 case 'P': /* DSC -- Device Control String */
1793 case '_': /* APC -- Application Program Command */
1794 case '^': /* PM -- Privacy Message */
1796 fprintf(stderr, "erresc: unknown str ");
1806 * TODO: Implement parsing like for CSI when required.
1807 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1817 printf("ESC%c", strescseq.type);
1818 for(i = 0; i < strescseq.len; i++) {
1819 c = strescseq.buf[i] & 0xff;
1822 } else if(c == '\n') {
1824 } else if(c == '\r') {
1826 } else if(c == 0x1b) {
1829 printf("(%02x)", c);
1837 memset(&strescseq, 0, sizeof(strescseq));
1841 tputtab(bool forward) {
1847 for(++x; x < term.col && !term.tabs[x]; ++x)
1852 for(--x; x > 0 && !term.tabs[x]; --x)
1855 tmoveto(x, term.c.y);
1859 techo(char *buf, int len) {
1860 for(; len > 0; buf++, len--) {
1863 if(c == '\033') { /* escape */
1866 } else if (c < '\x20') { /* control code */
1867 if(c != '\n' && c != '\r' && c != '\t') {
1881 tputc(char *c, int len) {
1883 bool control = ascii < '\x20' || ascii == 0177;
1886 if (xwrite(iofd, c, len) < 0) {
1887 fprintf(stderr, "Error writting in %s:%s\n",
1888 opt_io, strerror(errno));
1894 * STR sequences must be checked before anything else
1895 * because it can use some control codes as part of the sequence.
1897 if(term.esc & ESC_STR) {
1900 term.esc = ESC_START | ESC_STR_END;
1902 case '\a': /* backwards compatibility to xterm */
1907 strescseq.buf[strescseq.len++] = ascii;
1908 if(strescseq.len+1 >= STR_BUF_SIZ) {
1917 * Actions of control codes must be performed as soon they arrive
1918 * because they can be embedded inside a control sequence, and
1919 * they must not cause conflicts with sequences.
1927 tmoveto(term.c.x-1, term.c.y);
1930 tmoveto(0, term.c.y);
1935 /* go to first col if the mode is set */
1936 tnewline(IS_SET(MODE_CRLF));
1938 case '\a': /* BEL */
1939 if(!(xw.state & WIN_FOCUSED))
1942 case '\033': /* ESC */
1944 term.esc = ESC_START;
1946 case '\016': /* SO */
1947 term.c.attr.mode |= ATTR_GFX;
1949 case '\017': /* SI */
1950 term.c.attr.mode &= ~ATTR_GFX;
1952 case '\032': /* SUB */
1953 case '\030': /* CAN */
1956 case '\005': /* ENQ (IGNORED) */
1957 case '\000': /* NUL (IGNORED) */
1958 case '\021': /* XON (IGNORED) */
1959 case '\023': /* XOFF (IGNORED) */
1960 case 0177: /* DEL (IGNORED) */
1963 } else if(term.esc & ESC_START) {
1964 if(term.esc & ESC_CSI) {
1965 csiescseq.buf[csiescseq.len++] = ascii;
1966 if(BETWEEN(ascii, 0x40, 0x7E)
1967 || csiescseq.len >= ESC_BUF_SIZ) {
1969 csiparse(), csihandle();
1971 } else if(term.esc & ESC_STR_END) {
1975 } else if(term.esc & ESC_ALTCHARSET) {
1977 case '0': /* Line drawing set */
1978 term.c.attr.mode |= ATTR_GFX;
1980 case 'B': /* USASCII */
1981 term.c.attr.mode &= ~ATTR_GFX;
1983 case 'A': /* UK (IGNORED) */
1984 case '<': /* multinational charset (IGNORED) */
1985 case '5': /* Finnish (IGNORED) */
1986 case 'C': /* Finnish (IGNORED) */
1987 case 'K': /* German (IGNORED) */
1990 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1993 } else if(term.esc & ESC_TEST) {
1994 if(ascii == '8') { /* DEC screen alignment test. */
1995 char E[UTF_SIZ] = "E";
1998 for(x = 0; x < term.col; ++x) {
1999 for(y = 0; y < term.row; ++y)
2000 tsetchar(E, &term.c.attr, x, y);
2007 term.esc |= ESC_CSI;
2010 term.esc |= ESC_TEST;
2012 case 'P': /* DCS -- Device Control String */
2013 case '_': /* APC -- Application Program Command */
2014 case '^': /* PM -- Privacy Message */
2015 case ']': /* OSC -- Operating System Command */
2016 case 'k': /* old title set compatibility */
2018 strescseq.type = ascii;
2019 term.esc |= ESC_STR;
2021 case '(': /* set primary charset G0 */
2022 term.esc |= ESC_ALTCHARSET;
2024 case ')': /* set secondary charset G1 (IGNORED) */
2025 case '*': /* set tertiary charset G2 (IGNORED) */
2026 case '+': /* set quaternary charset G3 (IGNORED) */
2029 case 'D': /* IND -- Linefeed */
2030 if(term.c.y == term.bot) {
2031 tscrollup(term.top, 1);
2033 tmoveto(term.c.x, term.c.y+1);
2037 case 'E': /* NEL -- Next line */
2038 tnewline(1); /* always go to first col */
2041 case 'H': /* HTS -- Horizontal tab stop */
2042 term.tabs[term.c.x] = 1;
2045 case 'M': /* RI -- Reverse index */
2046 if(term.c.y == term.top) {
2047 tscrolldown(term.top, 1);
2049 tmoveto(term.c.x, term.c.y-1);
2053 case 'Z': /* DECID -- Identify Terminal */
2054 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2057 case 'c': /* RIS -- Reset to inital state */
2062 case '=': /* DECPAM -- Application keypad */
2063 term.mode |= MODE_APPKEYPAD;
2066 case '>': /* DECPNM -- Normal keypad */
2067 term.mode &= ~MODE_APPKEYPAD;
2070 case '7': /* DECSC -- Save Cursor */
2071 tcursor(CURSOR_SAVE);
2074 case '8': /* DECRC -- Restore Cursor */
2075 tcursor(CURSOR_LOAD);
2078 case '\\': /* ST -- Stop */
2082 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2083 (uchar) ascii, isprint(ascii)? ascii:'.');
2088 * All characters which form part of a sequence are not
2094 * Display control codes only if we are in graphic mode
2096 if(control && !(term.c.attr.mode & ATTR_GFX))
2098 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2100 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
2101 tnewline(1); /* always go to first col */
2103 if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2104 memmove(&term.line[term.c.y][term.c.x+1],
2105 &term.line[term.c.y][term.c.x],
2106 (term.col - term.c.x - 1) * sizeof(Glyph));
2109 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2110 if(term.c.x+1 < term.col) {
2111 tmoveto(term.c.x+1, term.c.y);
2113 term.c.state |= CURSOR_WRAPNEXT;
2118 tresize(int col, int row) {
2120 int minrow = MIN(row, term.row);
2121 int mincol = MIN(col, term.col);
2122 int slide = term.c.y - row + 1;
2125 if(col < 1 || row < 1)
2128 /* free unneeded rows */
2131 /* slide screen to keep cursor where we expect it -
2132 * tscrollup would work here, but we can optimize to
2133 * memmove because we're freeing the earlier lines */
2134 for(/* i = 0 */; i < slide; i++) {
2138 memmove(term.line, term.line + slide, row * sizeof(Line));
2139 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2141 for(i += row; i < term.row; i++) {
2146 /* resize to new height */
2147 term.line = xrealloc(term.line, row * sizeof(Line));
2148 term.alt = xrealloc(term.alt, row * sizeof(Line));
2149 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2150 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2152 /* resize each row to new width, zero-pad if needed */
2153 for(i = 0; i < minrow; i++) {
2155 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2156 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2157 for(x = mincol; x < col; x++) {
2158 term.line[i][x].state = 0;
2159 term.alt[i][x].state = 0;
2163 /* allocate any new rows */
2164 for(/* i == minrow */; i < row; i++) {
2166 term.line[i] = xcalloc(col, sizeof(Glyph));
2167 term.alt [i] = xcalloc(col, sizeof(Glyph));
2169 if(col > term.col) {
2170 bp = term.tabs + term.col;
2172 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2173 while(--bp > term.tabs && !*bp)
2175 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2178 /* update terminal size */
2181 /* reset scrolling region */
2182 tsetscroll(0, row-1);
2183 /* make use of the LIMIT in tmoveto */
2184 tmoveto(term.c.x, term.c.y);
2190 xresize(int col, int row) {
2191 xw.tw = MAX(1, col * xw.cw);
2192 xw.th = MAX(1, row * xw.ch);
2194 XftDrawChange(xw.draw, xw.buf);
2200 XRenderColor color = { .alpha = 0 };
2202 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2203 for(i = 0; i < LEN(colorname); i++) {
2206 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2207 die("Could not allocate color '%s'\n", colorname[i]);
2211 /* load colors [16-255] ; same colors as xterm */
2212 for(i = 16, r = 0; r < 6; r++) {
2213 for(g = 0; g < 6; g++) {
2214 for(b = 0; b < 6; b++) {
2215 color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
2216 color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
2217 color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
2218 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2219 die("Could not allocate color %d\n", i);
2226 for(r = 0; r < 24; r++, i++) {
2227 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2228 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2230 die("Could not allocate color %d\n", i);
2236 xtermclear(int col1, int row1, int col2, int row2) {
2237 XftDrawRect(xw.draw,
2238 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2239 borderpx + col1 * xw.cw,
2240 borderpx + row1 * xw.ch,
2241 (col2-col1+1) * xw.cw,
2242 (row2-row1+1) * xw.ch);
2246 * Absolute coordinates.
2249 xclear(int x1, int y1, int x2, int y2) {
2250 XftDrawRect(xw.draw,
2251 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2252 x1, y1, x2-x1, y2-y1);
2257 XClassHint class = {opt_class ? opt_class : termname, termname};
2258 XWMHints wm = {.flags = InputHint, .input = 1};
2259 XSizeHints *sizeh = NULL;
2261 sizeh = XAllocSizeHints();
2262 if(xw.isfixed == False) {
2263 sizeh->flags = PSize | PResizeInc | PBaseSize;
2264 sizeh->height = xw.h;
2265 sizeh->width = xw.w;
2266 sizeh->height_inc = xw.ch;
2267 sizeh->width_inc = xw.cw;
2268 sizeh->base_height = 2 * borderpx;
2269 sizeh->base_width = 2 * borderpx;
2271 sizeh->flags = PMaxSize | PMinSize;
2272 sizeh->min_width = sizeh->max_width = xw.fw;
2273 sizeh->min_height = sizeh->max_height = xw.fh;
2276 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2281 xloadfont(Font *f, FcPattern *pattern) {
2285 match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
2288 if(!(f->set = XftFontOpenPattern(xw.dpy, match))) {
2289 FcPatternDestroy(match);
2293 f->ascent = f->set->ascent;
2294 f->descent = f->set->descent;
2296 f->rbearing = f->set->max_advance_width;
2298 f->height = f->set->height;
2299 f->width = f->lbearing + f->rbearing;
2305 xloadfonts(char *fontstr, int fontsize) {
2310 if(fontstr[0] == '-') {
2311 pattern = XftXlfdParse(fontstr, False, False);
2313 pattern = FcNameParse((FcChar8 *)fontstr);
2317 die("st: can't open font %s\n", fontstr);
2320 FcPatternDel(pattern, FC_PIXEL_SIZE);
2321 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2322 usedfontsize = fontsize;
2324 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2325 if(result == FcResultMatch) {
2326 usedfontsize = (int)fontval;
2329 * Default font size is 12, if none given. This is to
2330 * have a known usedfontsize value.
2332 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2337 if(xloadfont(&dc.font, pattern))
2338 die("st: can't open font %s\n", fontstr);
2340 /* Setting character width and height. */
2341 xw.cw = dc.font.width;
2342 xw.ch = dc.font.height;
2344 FcPatternDel(pattern, FC_WEIGHT);
2345 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2346 if(xloadfont(&dc.bfont, pattern))
2347 die("st: can't open font %s\n", fontstr);
2349 FcPatternDel(pattern, FC_SLANT);
2350 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2351 if(xloadfont(&dc.ibfont, pattern))
2352 die("st: can't open font %s\n", fontstr);
2354 FcPatternDel(pattern, FC_WEIGHT);
2355 if(xloadfont(&dc.ifont, pattern))
2356 die("st: can't open font %s\n", fontstr);
2358 FcPatternDestroy(pattern);
2362 xzoom(const Arg *arg)
2364 xloadfonts(usedfont, usedfontsize + arg->i);
2371 XSetWindowAttributes attrs;
2374 int sw, sh, major, minor;
2376 if(!(xw.dpy = XOpenDisplay(NULL)))
2377 die("Can't open display\n");
2378 xw.scr = XDefaultScreen(xw.dpy);
2379 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2382 usedfont = (opt_font == NULL)? font : opt_font;
2383 xloadfonts(usedfont, 0);
2386 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2389 /* adjust fixed window geometry */
2391 sw = DisplayWidth(xw.dpy, xw.scr);
2392 sh = DisplayHeight(xw.dpy, xw.scr);
2394 xw.fx = sw + xw.fx - xw.fw - 1;
2396 xw.fy = sh + xw.fy - xw.fh - 1;
2401 /* window - default size */
2402 xw.h = 2 * borderpx + term.row * xw.ch;
2403 xw.w = 2 * borderpx + term.col * xw.cw;
2408 attrs.background_pixel = dc.col[defaultbg].pixel;
2409 attrs.border_pixel = dc.col[defaultbg].pixel;
2410 attrs.bit_gravity = NorthWestGravity;
2411 attrs.event_mask = FocusChangeMask | KeyPressMask
2412 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2413 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2414 attrs.colormap = xw.cmap;
2416 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2417 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2418 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2420 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2424 /* double buffering */
2425 if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2426 die("Xdbe extension is not present\n");
2427 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2429 /* Xft rendering context */
2430 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2433 xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2435 die("XOpenIM failed. Could not open input device.\n");
2436 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2437 | XIMStatusNothing, XNClientWindow, xw.win,
2438 XNFocusWindow, xw.win, NULL);
2440 die("XCreateIC failed. Could not obtain input method.\n");
2442 /* white cursor, black outline */
2443 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2444 XDefineCursor(xw.dpy, xw.win, cursor);
2445 XRecolorCursor(xw.dpy, cursor,
2446 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2447 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2449 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2450 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2451 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2454 XMapWindow(xw.dpy, xw.win);
2460 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2461 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2462 width = charlen * xw.cw;
2463 Font *font = &dc.font;
2465 Colour *fg = &dc.col[base.fg], *bg = &dc.col[base.bg],
2466 *temp, revfg, revbg;
2467 XRenderColor colfg, colbg;
2469 if(base.mode & ATTR_BOLD) {
2470 if(BETWEEN(base.fg, 0, 7)) {
2471 /* basic system colors */
2472 fg = &dc.col[base.fg + 8];
2473 } else if(BETWEEN(base.fg, 16, 195)) {
2475 fg = &dc.col[base.fg + 36];
2476 } else if(BETWEEN(base.fg, 232, 251)) {
2478 fg = &dc.col[base.fg + 4];
2481 * Those ranges will not be brightened:
2482 * 8 - 15 – bright system colors
2483 * 196 - 231 – highest 256 color cube
2484 * 252 - 255 – brightest colors in greyscale
2489 if(base.mode & ATTR_ITALIC)
2491 if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD))
2494 if(IS_SET(MODE_REVERSE)) {
2495 if(fg == &dc.col[defaultfg]) {
2496 fg = &dc.col[defaultbg];
2498 colfg.red = ~fg->color.red;
2499 colfg.green = ~fg->color.green;
2500 colfg.blue = ~fg->color.blue;
2501 colfg.alpha = fg->color.alpha;
2502 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2506 if(bg == &dc.col[defaultbg]) {
2507 bg = &dc.col[defaultfg];
2509 colbg.red = ~bg->color.red;
2510 colbg.green = ~bg->color.green;
2511 colbg.blue = ~bg->color.blue;
2512 colbg.alpha = bg->color.alpha;
2513 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2518 if(base.mode & ATTR_REVERSE)
2519 temp = fg, fg = bg, bg = temp;
2521 XftTextExtentsUtf8(xw.dpy, font->set, (FcChar8 *)s, bytelen,
2523 width = extents.xOff;
2525 /* Intelligent cleaning up of the borders. */
2527 xclear(0, (y == 0)? 0 : winy, borderpx,
2528 winy + xw.ch + (y == term.row-1)? xw.h : 0);
2530 if(x + charlen >= term.col-1) {
2531 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2532 (y == term.row-1)? xw.h : (winy + xw.ch));
2535 xclear(winx, 0, winx + width, borderpx);
2537 xclear(winx, winy + xw.ch, winx + width, xw.h);
2539 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
2540 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
2541 winy + font->ascent, (FcChar8 *)s, bytelen);
2543 if(base.mode & ATTR_UNDERLINE) {
2544 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
2551 static int oldx = 0, oldy = 0;
2553 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs, 0};
2555 LIMIT(oldx, 0, term.col-1);
2556 LIMIT(oldy, 0, term.row-1);
2558 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2559 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2561 /* remove the old cursor */
2562 if(term.line[oldy][oldx].state & GLYPH_SET) {
2563 sl = utf8size(term.line[oldy][oldx].c);
2564 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2567 xtermclear(oldx, oldy, oldx, oldy);
2570 /* draw the new one */
2571 if(!(IS_SET(MODE_HIDE))) {
2572 if(!(xw.state & WIN_FOCUSED))
2575 if(IS_SET(MODE_REVERSE))
2576 g.mode |= ATTR_REVERSE, g.fg = defaultcs, g.bg = defaultfg;
2579 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2580 oldx = term.c.x, oldy = term.c.y;
2586 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2591 struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2595 XSync(xw.dpy, False); /* necessary for a good tput flash */
2596 nanosleep(&tv, NULL);
2601 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2603 drawregion(0, 0, term.col, term.row);
2604 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2608 drawregion(int x1, int y1, int x2, int y2) {
2609 int ic, ib, x, y, ox, sl;
2611 char buf[DRAW_BUF_SIZ];
2612 bool ena_sel = sel.bx != -1;
2614 if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
2617 if(!(xw.state & WIN_VISIBLE))
2620 for(y = y1; y < y2; y++) {
2624 xtermclear(0, y, term.col, y);
2626 base = term.line[y][0];
2628 for(x = x1; x < x2; x++) {
2629 new = term.line[y][x];
2630 if(ena_sel && *(new.c) && selected(x, y))
2631 new.mode ^= ATTR_REVERSE;
2632 if(ib > 0 && (!(new.state & GLYPH_SET)
2633 || ATTRCMP(base, new)
2634 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2635 xdraws(buf, base, ox, y, ic, ib);
2638 if(new.state & GLYPH_SET) {
2643 sl = utf8size(new.c);
2644 memcpy(buf+ib, new.c, sl);
2650 xdraws(buf, base, ox, y, ic, ib);
2656 expose(XEvent *ev) {
2657 XExposeEvent *e = &ev->xexpose;
2659 if(xw.state & WIN_REDRAW) {
2661 xw.state &= ~WIN_REDRAW;
2666 visibility(XEvent *ev) {
2667 XVisibilityEvent *e = &ev->xvisibility;
2669 if(e->state == VisibilityFullyObscured) {
2670 xw.state &= ~WIN_VISIBLE;
2671 } else if(!(xw.state & WIN_VISIBLE)) {
2672 /* need a full redraw for next Expose, not just a buf copy */
2673 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2679 xw.state &= ~WIN_VISIBLE;
2683 xseturgency(int add) {
2684 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2686 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2687 XSetWMHints(xw.dpy, xw.win, h);
2693 if(ev->type == FocusIn) {
2694 XSetICFocus(xw.xic);
2695 xw.state |= WIN_FOCUSED;
2698 XUnsetICFocus(xw.xic);
2699 xw.state &= ~WIN_FOCUSED;
2704 match(uint mask, uint state) {
2705 if(mask == XK_NO_MOD && state)
2707 if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
2709 if((state & mask) != state)
2715 numlock(const Arg *dummy) {
2720 kmap(KeySym k, uint state) {
2725 /* Check for mapped keys out of X11 function keys. */
2726 for(i = 0; i < LEN(mappedkeys); i++) {
2727 if(mappedkeys[i] == k)
2730 if(i == LEN(mappedkeys)) {
2731 if((k & 0xFFFF) < 0xFF00)
2735 for(kp = key; kp < key + LEN(key); kp++) {
2741 if(!match(mask, state))
2744 if(kp->appkey > 0) {
2745 if(!IS_SET(MODE_APPKEYPAD))
2747 if(term.numlock && kp->appkey == 2)
2749 } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
2753 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
2755 && !IS_SET(MODE_APPCURSOR))) {
2759 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
2760 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
2771 kpress(XEvent *ev) {
2772 XKeyEvent *e = &ev->xkey;
2774 char xstr[31], buf[32], *customkey, *cp = buf;
2779 if (IS_SET(MODE_KBDLOCK))
2782 len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
2783 e->state &= ~Mod2Mask;
2785 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
2786 if(ksym == bp->keysym && match(bp->mod, e->state)) {
2787 bp->func(&(bp->arg));
2792 /* 2. custom keys from config.h */
2793 if((customkey = kmap(ksym, e->state))) {
2794 len = strlen(customkey);
2795 memcpy(buf, customkey, len);
2796 /* 2. hardcoded (overrides X lookup) */
2801 if (len == 1 && e->state & Mod1Mask)
2804 memcpy(cp, xstr, len);
2805 len = cp - buf + len;
2809 if(IS_SET(MODE_ECHO))
2815 cmessage(XEvent *e) {
2817 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2818 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2819 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2820 xw.state |= WIN_FOCUSED;
2822 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2823 xw.state &= ~WIN_FOCUSED;
2825 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
2826 /* Send SIGHUP to shell */
2833 cresize(int width, int height)
2842 col = (xw.w - 2 * borderpx) / xw.cw;
2843 row = (xw.h - 2 * borderpx) / xw.ch;
2852 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2855 cresize(e->xconfigure.width, e->xconfigure.height);
2862 int xfd = XConnectionNumber(xw.dpy), i;
2863 struct timeval drawtimeout, *tv = NULL;
2867 FD_SET(cmdfd, &rfd);
2869 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2872 die("select failed: %s\n", SERRNO);
2876 * Stop after a certain number of reads so the user does not
2877 * feel like the system is stuttering.
2879 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2883 * Just wait a bit so it isn't disturbing the
2884 * user and the system is able to write something.
2886 drawtimeout.tv_sec = 0;
2887 drawtimeout.tv_usec = 5;
2894 while(XPending(xw.dpy)) {
2895 XNextEvent(xw.dpy, &ev);
2896 if(XFilterEvent(&ev, None))
2898 if(handler[ev.type])
2899 (handler[ev.type])(&ev);
2908 main(int argc, char *argv[]) {
2909 int i, bitm, xr, yr;
2912 xw.fw = xw.fh = xw.fx = xw.fy = 0;
2915 for(i = 1; i < argc; i++) {
2916 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2919 opt_class = argv[i];
2922 /* eat all remaining arguments */
2934 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2939 if(bitm & WidthValue)
2941 if(bitm & HeightValue)
2943 if(bitm & XNegative && xw.fx == 0)
2945 if(bitm & XNegative && xw.fy == 0)
2948 if(xw.fh != 0 && xw.fw != 0)
2957 opt_title = argv[i];
2964 opt_embed = argv[i];
2970 setlocale(LC_CTYPE, "");
2971 XSetLocaleModifiers("");