vi: move xoff before EOL after motions
[neatvi.git] / term.c
bloba9d2c8a378986423126d5770ce81554a48925741
1 #include <poll.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <sys/ioctl.h>
6 #include <termios.h>
7 #include <unistd.h>
8 #include "vi.h"
10 static struct sbuf *term_sbuf;
11 static int rows, cols;
12 static struct termios termios;
14 void term_init(void)
16 struct winsize win;
17 struct termios newtermios;
18 tcgetattr(0, &termios);
19 newtermios = termios;
20 newtermios.c_lflag &= ~(ICANON | ISIG);
21 newtermios.c_lflag &= ~ECHO;
22 tcsetattr(0, TCSAFLUSH, &newtermios);
23 if (getenv("LINES"))
24 rows = atoi(getenv("LINES"));
25 if (getenv("COLUMNS"))
26 cols = atoi(getenv("COLUMNS"));
27 if (!ioctl(0, TIOCGWINSZ, &win)) {
28 cols = cols ? cols : win.ws_col;
29 rows = rows ? rows : win.ws_row;
31 cols = cols ? cols : 80;
32 rows = rows ? rows : 25;
35 void term_done(void)
37 term_commit();
38 tcsetattr(0, 0, &termios);
41 void term_record(void)
43 if (!term_sbuf)
44 term_sbuf = sbuf_make();
47 void term_commit(void)
49 if (term_sbuf) {
50 write(1, sbuf_buf(term_sbuf), sbuf_len(term_sbuf));
51 sbuf_free(term_sbuf);
52 term_sbuf = NULL;
56 static void term_out(char *s)
58 if (term_sbuf)
59 sbuf_str(term_sbuf, s);
60 else
61 write(1, s, strlen(s));
64 void term_str(char *s)
66 term_out(s);
69 void term_chr(int ch)
71 char s[4] = {ch};
72 term_out(s);
75 void term_kill(void)
77 term_out("\33[K");
80 void term_pos(int r, int c)
82 char buf[32] = "\r";
83 if (c < 0)
84 c = 0;
85 if (c >= xcols)
86 c = cols - 1;
87 if (r < 0)
88 sprintf(buf, "\r\33[%d%c", abs(c), c > 0 ? 'C' : 'D');
89 else
90 sprintf(buf, "\33[%d;%dH", r + 1, c + 1);
91 term_out(buf);
94 int term_rows(void)
96 return rows;
99 int term_cols(void)
101 return cols;
104 int term_read(int ms)
106 struct pollfd ufds[1];
107 char b;
108 ufds[0].fd = 0;
109 ufds[0].events = POLLIN;
110 if (poll(ufds, 1, ms * 1000) <= 0)
111 return -1;
112 if (read(0, &b, 1) <= 0)
113 return -1;
114 return (unsigned char) b;
117 /* return a static string that changes text attributes from old to att */
118 char *term_att(int att, int old)
120 static char buf[128];
121 char *s = buf;
122 int fg = SYN_FG(att);
123 int bg = SYN_BG(att);
124 if (att == old)
125 return "";
126 s += sprintf(s, "\33[m\33[");
127 if (fg & SYN_BD)
128 s += sprintf(s, "1;");
129 if (fg & SYN_IT)
130 s += sprintf(s, "3;");
131 else if (fg & SYN_RV)
132 s += sprintf(s, "7;");
133 if ((fg & 0xff) < 8)
134 s += sprintf(s, "%d;", 30 + (fg & 0xff));
135 else
136 s += sprintf(s, "38;5;%d;", (fg & 0xff));
137 if (bg) {
138 if ((bg & 0xff) < 8)
139 s += sprintf(s, "%d;", 40 + (bg & 0xff));
140 else
141 s += sprintf(s, "48;5;%d;", (bg & 0xff));
143 s += sprintf(s, "m");
144 return buf;