+#define IS_CONTROL(ch) !((ch) & 0xffffff60UL)
+
+static int has_default = 0;
+
+enum {
+ C0_NUL = 0x00,
+ C0_SOH, C0_STX, C0_ETX, C0_EOT, C0_ENQ, C0_ACK, C0_BEL,
+ C0_BS , C0_HT , C0_LF , C0_VT , C0_FF , C0_CR , C0_SO , C0_SI ,
+ C0_DLE, C0_DC1, C0_DC2, D0_DC3, C0_DC4, C0_NAK, C0_SYN, C0_ETB,
+ C0_CAN, C0_EM , C0_SUB, C0_ESC, C0_IS4, C0_IS3, C0_IS2, C0_IS1,
+};
+
+enum {
+ C1_40 = 0x40,
+ C1_41 , C1_BPH, C1_NBH, C1_44 , C1_NEL, C1_SSA, C1_ESA,
+ C1_HTS, C1_HTJ, C1_VTS, C1_PLD, C1_PLU, C1_RI , C1_SS2, C1_SS3,
+ C1_DCS, C1_PU1, C1_PU2, C1_STS, C1_CCH, C1_MW , C1_SPA, C1_EPA,
+ C1_SOS, C1_59 , C1_SCI, C1_CSI, CS_ST , C1_OSC, C1_PM , C1_APC,
+};
+
+enum {
+ CSI_ICH = 0x40,
+ CSI_CUU, CSI_CUD, CSI_CUF, CSI_CUB, CSI_CNL, CSI_CPL, CSI_CHA,
+ CSI_CUP, CSI_CHT, CSI_ED , CSI_EL , CSI_IL , CSI_DL , CSI_EF , CSI_EA ,
+ CSI_DCH, CSI_SEE, CSI_CPR, CSI_SU , CSI_SD , CSI_NP , CSI_PP , CSI_CTC,
+ CSI_ECH, CSI_CVT, CSI_CBT, CSI_SRS, CSI_PTX, CSI_SDS, CSI_SIMD, CSI_5F,
+ CSI_HPA, CSI_HPR, CSI_REP, CSI_DA , CSI_VPA, CSI_VPR, CSI_HVP, CSI_TBC,
+ CSI_SM , CSI_MC , CSI_HPB, CSI_VPB, CSI_RM , CSI_SGR, CSI_DSR, CSI_DAQ,
+ CSI_70 , CSI_71 , CSI_72 , CSI_73 , CSI_74 , CSI_75 , CSI_76 , CSI_77 ,
+ CSI_78 , CSI_79 , CSI_7A , CSI_7B , CSI_7C , CSI_7D , CSI_7E , CSI_7F
+};
+
+struct madtty_t {
+ int pty;
+ pid_t childpid;
+
+ /* flags */
+ unsigned seen_input : 1;
+ unsigned insert : 1;
+ unsigned escaped : 1;
+ unsigned graphmode : 1;
+ unsigned curshid : 1;
+
+ /* geometry */
+ int rows, cols;
+ unsigned curattrs;
+
+ struct t_row_t *lines;
+ struct t_row_t *scroll_top;
+ struct t_row_t *scroll_bot;
+
+ /* cursor */
+ struct t_row_t *curs_row;
+ int curs_col, curs_srow, curs_scol;
+
+ /* buffers and parsing state */
+ mbstate_t ps;
+ char rbuf[BUFSIZ];
+ char ebuf[BUFSIZ];
+ int rlen, elen;
+};
+
+typedef struct t_row_t {
+ wchar_t *text;
+ uint16_t *attr;
+ unsigned dirty : 1;
+} t_row_t;
+
+static char const * const keytable[KEY_MAX+1] = {
+ ['\n'] = "\r",
+ [KEY_UP] = "\e[A",
+ [KEY_DOWN] = "\e[B",
+ [KEY_RIGHT] = "\e[C",
+ [KEY_LEFT] = "\e[D",
+ [KEY_BACKSPACE] = "\177",
+ [KEY_HOME] = "\e[1~",
+ [KEY_IC] = "\e[2~",
+ [KEY_DC] = "\e[3~",
+ [KEY_END] = "\e[4~",
+ [KEY_PPAGE] = "\e[5~",
+ [KEY_NPAGE] = "\e[6~",
+ [KEY_SUSPEND] = "\x1A", /* Ctrl+Z gets mapped to this */
+ [KEY_F(1)] = "\e[[A",
+ [KEY_F(2)] = "\e[[B",
+ [KEY_F(3)] = "\e[[C",
+ [KEY_F(4)] = "\e[[D",
+ [KEY_F(5)] = "\e[[E",
+ [KEY_F(6)] = "\e[17~",
+ [KEY_F(7)] = "\e[18~",
+ [KEY_F(8)] = "\e[19~",
+ [KEY_F(9)] = "\e[20~",
+ [KEY_F(10)] = "\e[21~",
+};
+
+static void t_row_set(t_row_t *row, int start, int len, uint16_t attr)
+{
+ row->dirty = true;
+ wmemset(row->text + start, 0, len);
+ for (int i = start; i < len + start; i++) {
+ row->attr[i] = attr;
+ }
+}