vi: show the cursor even after failed motions
[neatvi.git] / term.c
blob4322e5fa6673eb52bd77085b753e9643d318025f
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;