sites

public wiki contents of suckless.org
git clone git://git.suckless.org/sites
Log | Files | Refs

st-vim-0.8.4.patch (38917B)


      1 diff --git a/Makefile b/Makefile
      2 index 470ac86..6688a58 100644
      3 --- a/Makefile
      4 +++ b/Makefile
      5 @@ -21,7 +21,7 @@ config.h:
      6  .c.o:
      7  	$(CC) $(STCFLAGS) -c $<
      8  
      9 -st.o: config.h st.h win.h
     10 +st.o: config.h st.h win.h normalMode.h normalMode.c utils.h
     11  x.o: arg.h config.h st.h win.h
     12  
     13  $(OBJ): config.h config.mk
     14 diff --git a/config.def.h b/config.def.h
     15 index 6f05dce..16cb5e1 100644
     16 --- a/config.def.h
     17 +++ b/config.def.h
     18 @@ -131,6 +131,21 @@ unsigned int defaultfg = 7;
     19  unsigned int defaultbg = 0;
     20  static unsigned int defaultcs = 256;
     21  static unsigned int defaultrcs = 257;
     22 +unsigned int const currentBg = 6, buffSize = 2048;
     23 +/// Enable double / triple click yanking / selection of word / line.
     24 +int const mouseYank = 1, mouseSelect = 0;
     25 +/// [Vim Browse] Colors for search results currently on screen.
     26 +unsigned int const highlightBg = 160, highlightFg = 15;
     27 +char const wDelS[] = "!\"#$%&'()*+,-./:;<=>?@[\\]^`{|}~", wDelL[] = " \t";
     28 +char *nmKeys [] = {              ///< Shortcusts executed in normal mode
     29 +  "R/Building\nN", "r/Building\n", "X/juli@machine\nN", "x/juli@machine\n",
     30 +  "Q?[Leaving vim, starting execution]\n","F/: error:\nN", "f/: error:\n", "DQf"
     31 +};
     32 +unsigned int const amountNmKeys = sizeof(nmKeys) / sizeof(*nmKeys);
     33 +/// Style of the {command, search} string shown in the right corner (y,v,V,/)
     34 +Glyph styleSearch = {' ', ATTR_ITALIC | ATTR_BOLD_FAINT, 7, 16};
     35 +Glyph style[] = {{' ',ATTR_ITALIC|ATTR_FAINT,15,16}, {' ',ATTR_ITALIC,232,11},
     36 +                 {' ', ATTR_ITALIC, 232, 4}, {' ', ATTR_ITALIC, 232, 12}};
     37  
     38  /*
     39   * Default shape of cursor
     40 @@ -199,6 +214,7 @@ static Shortcut shortcuts[] = {
     41  	{ TERMMOD,              XK_Y,           selpaste,       {.i =  0} },
     42  	{ ShiftMask,            XK_Insert,      selpaste,       {.i =  0} },
     43  	{ TERMMOD,              XK_Num_Lock,    numlock,        {.i =  0} },
     44 +	{ MODKEY,               XK_c,           normalMode,     {.i =  0} },
     45  };
     46  
     47  /*
     48 diff --git a/normalMode.c b/normalMode.c
     49 new file mode 100644
     50 index 0000000..f0c7e30
     51 --- /dev/null
     52 +++ b/normalMode.c
     53 @@ -0,0 +1,284 @@
     54 +#include <X11/keysym.h>
     55 +#include <X11/XKBlib.h>
     56 +
     57 +#include "normalMode.h"
     58 +#include "utils.h"
     59 +
     60 +extern Glyph const styleSearch, style[];
     61 +extern char const wDelS[], wDelL[], *nmKeys[];
     62 +extern unsigned int bg[], fg, currentBg, highlightBg, highlightFg, amountNmKeys;
     63 +
     64 +typedef struct { int p[3]; } Pos;
     65 +
     66 +typedef enum {visual='v', visualLine='V', yank = 'y'} Op;
     67 +typedef enum {infix_none=0, infix_i='i', infix_a='a'} Infix;
     68 +typedef enum {fw='/', bw='?'} Search;
     69 +struct NormalModeState {
     70 +	struct OperationState { Op op; Infix infix; } cmd;
     71 +	struct MotionState { uint32_t c; int active; Pos searchPos; Search search; } m;
     72 +} defaultNormalMode, state;
     73 +
     74 +DynamicArray searchStr=UTF8_ARRAY, cCmd=UTF8_ARRAY, lCmd=UTF8_ARRAY;
     75 +Glyph styleCmd;
     76 +char posBuffer[10], braces[6][3] = { {"()"}, {"<>"}, {"{}"}, {"[]"}, {"\"\""}, {"''"}};
     77 +int exited=1, overlay=1;
     78 +static inline Rune cChar() { return term.line[term.c.y][term.c.x].u; }
     79 +static inline int pos(int p, int h) {return IS_SET(MODE_ALTSCREEN)?p:rangeY(p+h*histOff-insertOff);}
     80 +static inline int contains(Rune l, char const * values, size_t const memSize) {
     81 +	for (uint32_t i = 0; i < memSize; ++i) if (l == values[i]) return 1;
     82 +	return 0;
     83 +}
     84 +static inline void decodeTo(char const *cs, size_t len, DynamicArray *arr) {
     85 +	char *var = expand(arr);
     86 +	if (!var) empty(arr); else utf8decode(cs, (Rune*)(var), len);
     87 +}
     88 +static inline void applyPos(Pos p) {
     89 +	term.c.x = p.p[0], term.c.y = p.p[1];
     90 +	if (!IS_SET(MODE_ALTSCREEN) && histOp) term.line = &buf[histOff = p.p[2]];
     91 +}
     92 +/// Find string in history buffer, and provide string-match-lookup for highlighting matches
     93 +static int highlighted(int x, int y) {
     94 +	int const s=term.row*term.col, i=y*term.col+x, sz=size(&searchStr);
     95 +	return sz && i<s && mark[i]!=sz && i+mark[i]<s && !mark[i+mark[i]];
     96 +}
     97 +static void markSearchMatches(int all) {
     98 +	int sz = size(&searchStr), ox = 0, oy = 0, oi=0;
     99 +	for (int y=0; sz && all && y<term.row; ++y)
    100 +		for (int x=0; x<term.col; ++x) term.dirty[y] |= highlighted(x, y);
    101 +	for (int y = 0, wi=0, owi=0, i=0; sz && y < term.row; ++y)
    102 +		for (int x=0; x<term.col; ++x, wi%=sz, ++i, owi=wi)
    103 +			if (all || term.dirty[y]) {
    104 +				mark[i]=sz-(wi=(getU32(&searchStr,wi,1)==term.line[y][x].u?wi+1:0));
    105 +				if (wi==1) ox=x, oy=y, oi=i; else if (!wi && owi) x=ox, y=oy, i=oi;
    106 +			}
    107 +	for (int y=0; sz &&all &&y<term.row; ++y)
    108 +		for (int x=0; x<term.col; ++x) term.dirty[y] |= highlighted(x, y);
    109 +}
    110 +static int findString(int s, int all) {
    111 +	Pos p = (Pos) {.p={term.c.x, term.c.y, IS_SET(MODE_ALTSCREEN) ? 0 : histOff}};
    112 +	historyMove(s, 0, 0);
    113 +	uint32_t strSz=size(&searchStr), maxIter=rows()*term.col+strSz, wIdx=0;
    114 +	for (uint32_t i=0, wi = 0; wIdx<strSz && ++i<=maxIter; historyMove(s, 0, 0), wi=wIdx) {
    115 +		wIdx = (getU32(&searchStr, wIdx, s>0)==cChar())?wIdx+1:0;
    116 +		if (wi && !wIdx) historyMove(-(int)(s*wi), 0, 0);
    117 +	}
    118 +	if (wIdx == strSz && wIdx) historyMove(-(int)(s*strSz), 0, 0);
    119 +	else applyPos(p);
    120 +	markSearchMatches(all);
    121 +	return wIdx == strSz;
    122 +}
    123 +/// Execute series of normal-mode commands from char array / decoded from dynamic array
    124 +ExitState pressKeys(char const* s, size_t e) {
    125 +	ExitState x=success;
    126 +	for (size_t i=0; i<e && (x=(!s[i] ? x : kPressHist(&s[i], 1, 0, NULL))); ++i);
    127 +	return x;
    128 +}
    129 +static ExitState executeCommand(uint32_t *cs, size_t z) {
    130 +	ExitState x=success;
    131 +	char dc [32];
    132 +	for (size_t i=0; i<z && (x=kPressHist(dc, utf8encode(cs[i],dc),0,NULL));++i);
    133 +	return x;
    134 +}
    135 +/// Get character for overlay, if the overlay (st) has something to show, else normal char.
    136 +static void getChar(DynamicArray *st, Glyph *glyphChange, int y, int xEnd, int width, int x) {
    137 +	if (x < xEnd - min(min(width,xEnd), size(st))) *glyphChange = term.line[y][x];
    138 +	else if (x<xEnd) glyphChange->u = *((Rune*)(st->content + (size(st)+x-xEnd)*st->elSize));
    139 +}
    140 +/// Expand "infix" expression: for instance (w =>)       l     b     |   | v     e    |   | y
    141 +static ExitState expandExpression(char l) { //    ({ =>)       l  ?  {  \n | l | v  /  } \n | h | y
    142 +	int a=state.cmd.infix==infix_a, yank=state.cmd.op=='y', lc=tolower(l), found=1;
    143 +	state.cmd.infix = infix_none;
    144 +	if(!yank && state.cmd.op!=visual && state.cmd.op!=visualLine) return failed;
    145 +	char mot[11] = {'l', 0, 'b', 0, 0, 'v', 0, 'e', 0, 0, (char)(yank ? 'y' : 0)};
    146 +	if (lc == 'w') mot[2] = (char) ('b' - lc + l), mot[7] = (char) ((a ? 'w' : 'e') - lc + l), mot[9]=(char)(a?'h':0);
    147 +	else {
    148 +		mot[1]='?', mot[3]=mot[8]='\n', mot[6]='/', mot[4]=(char)(a?0:'l'), mot[9]=(char)(a?0:'h');
    149 +		for (int i=found=0; !found && i < 6; ++i)
    150 +			if ((found=contains(l,braces[i],2))) mot[2]=braces[i][0], mot[7]=braces[i][1];
    151 +	}
    152 +	if (!found) return failed;
    153 +	assign(&lCmd, &cCmd);
    154 +	empty(&cCmd);
    155 +	state.cmd = defaultNormalMode.cmd;
    156 +	return pressKeys(mot, 11);
    157 +}
    158 +
    159 +ExitState executeMotion(char const cs, KeySym const *const ks) {
    160 +	state.m.c = state.m.c < 1u ? 1u : state.m.c;
    161 +	if      (ks && *ks == XK_d) historyMove(0, 0, term.row / 2);
    162 +	else if (ks && *ks == XK_u) historyMove(0, 0, -term.row / 2);
    163 +	else if (ks && *ks == XK_f) historyMove(0, 0, term.row-1+(term.c.y=0));
    164 +	else if (ks && *ks == XK_b) historyMove(0, 0, -(term.c.y=term.row-1));
    165 +	else if (ks && *ks == XK_h) overlay = !overlay;
    166 +	else if (cs == 'K') historyMove(0, 0, -(int)state.m.c);
    167 +	else if (cs == 'J') historyMove(0, 0,  (int)state.m.c);
    168 +	else if (cs == 'k') historyMove(0, -(int)state.m.c, 0);
    169 +	else if (cs == 'j') historyMove(0,  (int)state.m.c, 0);
    170 +	else if (cs == 'h') historyMove(-(int)state.m.c, 0, 0);
    171 +	else if (cs == 'l') historyMove( (int)state.m.c, 0, 0);
    172 +	else if (cs == 'H') term.c.y = 0;
    173 +	else if (cs == 'M') term.c.y = term.bot / 2;
    174 +	else if (cs == 'L') term.c.y = term.bot;
    175 +	else if (cs == 's' || cs == 'S') altToggle = cs == 's' ? !altToggle : 1;
    176 +	else if (cs == 'G' || cs == 'g') {
    177 +		if (cs == 'G') term.c = c[0] = c[IS_SET(MODE_ALTSCREEN)+1];
    178 +		if (!IS_SET(MODE_ALTSCREEN)) term.line = &buf[histOff=insertOff];
    179 +	} else if (cs == '0') term.c.x = 0;
    180 +	else if (cs == '$') term.c.x = term.col-1;
    181 +	else if (cs == 't') sel.type = sel.type==SEL_REGULAR ? SEL_RECTANGULAR : SEL_REGULAR;
    182 +	else if (cs == 'n' || cs == 'N') {
    183 +		int const d = ((cs=='N')!=(state.m.search==bw))?-1:1;
    184 +		for (uint32_t i = state.m.c; i && findString(d, 0); --i);
    185 +	} else if (contains(cs, "wWeEbB", 6)) {
    186 +		int const low=cs<=90, off=tolower(cs)!='w', sgn=(tolower(cs)=='b')?-1:1;
    187 +		size_t const l=strlen(wDelL), s=strlen(wDelS), maxIt=rows()*term.col;
    188 +		for (int it=0, on=0; state.m.c > 0 && it < maxIt; ++it) {
    189 +		    // If an offset is to be performed in beginning or not in beginning, move in history.
    190 +			if ((off || it) && historyMove(sgn, 0, 0)) break;
    191 +			// Determine if the category of the current letter changed since last iteration.
    192 +			int n = 1<<(contains(cChar(),wDelS,s) ?(2-low) :!contains(cChar(),wDelL,l)),
    193 +			    found = (on|=n)^n && ((off ?on^n :n)!=1);
    194 +			// If a reverse offset is to be performed and this is the last letter:
    195 +			if (found && off) historyMove(-sgn, 0, 0);
    196 +			// Terminate iteration: reset #it and old n value #on and decrease operation count:
    197 +			if (found) it=-1, on=0, --state.m.c;
    198 +		}
    199 +	} else return failed;
    200 +	state.m.c = 0;
    201 +	return state.cmd.op == yank ? exitMotion : success;
    202 +}
    203 +
    204 +ExitState kPressHist(char const *cs, size_t len, int ctrl, KeySym const *kSym) {
    205 +	historyOpToggle(1, 1);
    206 +	int const prevYOff=IS_SET(MODE_ALTSCREEN)?0:histOff, search=state.m.search&&state.m.active,
    207 +	          prevAltToggle=altToggle, prevOverlay=overlay;
    208 +	int const noOp=!state.cmd.op&&!state.cmd.infix, num=len==1&&BETWEEN(cs[0],48,57),
    209 +	          esc=kSym&&*kSym==XK_Escape, ret=(kSym&&*kSym==XK_Return)||(len==1&&cs[0]=='\n'),
    210 +	          quantifier=num&&(cs[0]!='0'||state.m.c), ins=!search &&noOp &&len &&cs[0]=='i';
    211 +	exited = 0;
    212 +	ExitState result = success;
    213 +	if (esc || ret || ins) { result = exitMotion, len = 0;
    214 +	} else if (kSym && *kSym == XK_BackSpace) {
    215 +		if ((search || state.m.c) && size(&cCmd)) pop(&cCmd);
    216 +		if (search) {
    217 +			if (size(&searchStr)) pop(&searchStr);
    218 +			else result = exitMotion;
    219 +			if (!size(&searchStr)) tfulldirt();
    220 +			applyPos(state.m.searchPos);
    221 +			findString(state.m.search==fw ? 1 : -1, 1);
    222 +		} else if (state.m.c) state.m.c /= 10;
    223 +		len = 0;
    224 +	} else if (search) {
    225 +		if (len >= 1) decodeTo(cs, len, &searchStr);
    226 +		applyPos(state.m.searchPos);
    227 +		findString(state.m.search==fw ? 1 : -1, 1);
    228 +	} else if (len == 0) { result = failed;
    229 +	} else if (quantifier) { state.m.c = min(SHRT_MAX, (int)state.m.c*10+cs[0]-48);
    230 +	} else if (state.cmd.infix && state.cmd.op && (result = expandExpression(cs[0]), len=0)) {
    231 +    } else if (cs[0] == 'd') { state = defaultNormalMode; result = exitMotion; state.m.active = 1;
    232 +	} else if (cs[0] == '.') {
    233 +		if (size(&cCmd)) assign(&lCmd, &cCmd);
    234 +		empty(&cCmd);
    235 +		executeCommand((uint32_t*) lCmd.content, size(&lCmd));
    236 +		empty(&cCmd);
    237 +		len = 0;
    238 +	} else if (cs[0] == 'r') { tfulldirt();
    239 +	} else if (cs[0] == 'c') {
    240 +		empty(&lCmd);
    241 +		empty(&cCmd);
    242 +		empty(&searchStr);
    243 +		tfulldirt();
    244 +		len = 0;
    245 +	} else if (cs[0] == fw || cs[0] == bw) {
    246 +		empty(&searchStr);
    247 +		state.m.search = (Search) cs[0];
    248 +		state.m.searchPos = (Pos){.p={term.c.x, term.c.y, prevYOff}};
    249 +		state.m.active = 1;
    250 +	} else if (cs[0]==infix_i || cs[0]==infix_a) { state.cmd.infix=(Infix) cs[0];
    251 +	} else if (cs[0] == 'y') {
    252 +		if (state.cmd.op) {
    253 +			result = (state.cmd.op == yank || state.cmd.op == visualLine) ? exitOp : exitMotion;
    254 +			if (state.cmd.op == yank) selstart(0, term.c.y, 0);
    255 +		} else selstart(term.c.x, term.c.y, 0);
    256 +		state.cmd.op = yank;
    257 +	} else if (cs[0] == visual || cs[0] == visualLine) {
    258 +		if (state.cmd.op != (Op) cs[0]) {
    259 +			state.cmd = defaultNormalMode.cmd;
    260 +			state.cmd.op = (Op) cs[0];
    261 +			selstart(cs[0] == visualLine ?0 :term.c.x, term.c.y, 0);
    262 +		} else result = exitOp;
    263 +	} else if (!(result =executeMotion((char) (len?cs[0]:0), ctrl?kSym:NULL))) {
    264 +		result=failed;
    265 +		for (size_t i = 0; !ctrl && i < amountNmKeys; ++i)
    266 +			if (cs[0]==nmKeys[i][0] &&
    267 +			   failed!=(result=pressKeys(&nmKeys[i][1], strlen(nmKeys[i])-1))) goto end;
    268 +	} // Operation/Motion finished if valid: update cmd string, extend selection, update search
    269 +	if (result != failed) {
    270 +		if (len == 1 && !ctrl) decodeTo(cs, len, &cCmd);
    271 +		if ((state.cmd.op == visualLine) || ((state.cmd.op == yank) && (result == exitOp))) {
    272 +			int const off = term.c.y + (IS_SET(MODE_ALTSCREEN) ? 0 : histOff) < sel.ob.y; //< Selection start below end.
    273 +			sel.ob.x = off ? term.col - 1 : 0;
    274 +			selextend(off ? 0 : term.col-1, term.c.y, sel.type, 0);
    275 +		} else if (sel.oe.x != -1) {
    276 +			selextend(term.c.x, term.c.y, sel.type, 0);
    277 +		}
    278 +	} // Set repaint for motion or status bar
    279 +	if (!IS_SET(MODE_ALTSCREEN) && prevYOff != histOff) tfulldirt();
    280 +	// Terminate Motion / operation if thus indicated
    281 +	if (result == exitMotion) {
    282 +		if (!state.m.active) result = (exited=noOp) ? finish : exitOp;
    283 +		 state.m.active = (int) (state.m.c = 0u);
    284 +	}
    285 +	if (result == exitOp || result == finish) {
    286 +		if (state.cmd.op == yank) {
    287 +			xsetsel(getsel());
    288 +			xclipcopy();
    289 +		}
    290 +		state = defaultNormalMode;
    291 +		selclear();
    292 +		if (!esc) assign(&lCmd, &cCmd);
    293 +		empty(&cCmd);
    294 +	} // Update the content displayed in the history overlay
    295 +	styleCmd = style[state.cmd.op==yank ? 1 : (state.cmd.op==visual ? 2 :
    296 +	                (state.cmd.op==visualLine ? 3 :0))];
    297 +	int const posLin = !IS_SET(MODE_ALTSCREEN) ? rangeY(insertOff-histOff):0, h=rows()-term.row;
    298 +	if (!posLin || posLin==h || !h) strcpy(posBuffer, posLin ? " [BOT] " : " [TOP] ");
    299 +	else sprintf(posBuffer, " % 3d%c  ", min(100, max(0, (int)(.5 + posLin * 100. / h))),'%');
    300 +	if ((overlay || overlay!=prevOverlay) && term.col>9 && term.row>4) {
    301 +		if (!term.dirty[term.row-1]) xdrawline(term.line[term.row-1], term.col*2/3, term.row-1, term.col-1);
    302 +		if (!term.dirty[term.row-2]) xdrawline(term.line[term.row-2], term.col*2/3, term.row-2, term.col-1);
    303 +	}
    304 +	if (result==finish) altToggle = 0;
    305 +	if (altToggle != prevAltToggle) tswapscreen();
    306 +end:
    307 +	historyOpToggle(-1, 1);
    308 +	return result;
    309 +}
    310 +
    311 +void historyOverlay(int x, int y, Glyph* g) {
    312 +	if (!histMode) return;
    313 +	TCursor const *cHist = histOp ? &term.c : &c[0];
    314 +	if(overlay && term.col > 9 && term.row > 4 && (x > (2*term.col/3)) && (y >= (term.row-2))) {
    315 +		*g = (y == term.row - 2) ? styleSearch : styleCmd;
    316 +		if (y == term.row-2) getChar(&searchStr, g, term.row-2, term.col-2, term.col/3, x);
    317 +		else if (x > term.col - 7) g->u = (Rune)(posBuffer[x - term.col + 7]);
    318 +		else getChar(size(&cCmd) ?&cCmd :&lCmd, g, term.row-1, term.col-7, term.col/3-6, x);
    319 +	} else if (highlighted(x, y)) g->bg = highlightBg, g->fg = highlightFg;
    320 +	else if ((x==cHist->x) ^ (y==cHist->y)) g->bg = currentBg;
    321 +	else if (x==cHist->x) g->mode^=ATTR_REVERSE;
    322 +}
    323 +void historyPreDraw() {
    324 +	static Pos op = {.p={0, 0, 0}};
    325 +	historyOpToggle(1, 0);
    326 +	// Draw the cursor cross if changed
    327 +	if (term.c.y >= term.row || op.p[1] >= term.row) tfulldirt();
    328 +	else if (exited || (op.p[1] != term.c.y)) term.dirty[term.c.y] = term.dirty[op.p[1]] = 1;
    329 +	for (int i=0; (exited || term.c.x != op.p[0]) && i<term.row; ++i) if (!term.dirty[i]) {
    330 +		xdrawline(term.line[i], term.c.x, i, term.c.x + 1);
    331 +		xdrawline(term.line[i], op.p[0], i, op.p[0] + 1);
    332 +	}
    333 +	// Update search results either only for lines with new content or all results if exiting
    334 +	markSearchMatches(exited);
    335 +	op = (Pos){.p = {term.c.x, term.c.y, 0}};
    336 +	historyOpToggle(-1, 0);
    337 +}
    338 diff --git a/normalMode.h b/normalMode.h
    339 new file mode 100644
    340 index 0000000..eb77484
    341 --- /dev/null
    342 +++ b/normalMode.h
    343 @@ -0,0 +1,8 @@
    344 +void normalMode();
    345 +void historyPreDraw();
    346 +void historyOverlay(int x, int y, Glyph* g);
    347 +void historyModeToggle(int start);
    348 +void historyOpToggle(int, int);
    349 +typedef enum {failed=0, success=1, exitMotion=2, exitOp=3, finish=4} ExitState;
    350 +ExitState kPressHist(char const *txt, size_t len, int ctrl, KeySym const *kSym);
    351 +ExitState pressKeys(char const* s, size_t e);
    352 diff --git a/st.c b/st.c
    353 index 76b7e0d..363f09c 100644
    354 --- a/st.c
    355 +++ b/st.c
    356 @@ -1,4 +1,5 @@
    357  /* See LICENSE for license details. */
    358 +#include <assert.h>
    359  #include <ctype.h>
    360  #include <errno.h>
    361  #include <fcntl.h>
    362 @@ -42,6 +43,8 @@
    363  #define ISCONTROLC1(c)		(BETWEEN(c, 0x80, 0x9f))
    364  #define ISCONTROL(c)		(ISCONTROLC0(c) || ISCONTROLC1(c))
    365  #define ISDELIM(u)		(u && wcschr(worddelimiters, u))
    366 +static inline int max(int a, int b) { return a > b ? a : b; }
    367 +static inline int min(int a, int b) { return a < b ? a : b; }
    368  
    369  enum term_mode {
    370  	MODE_WRAP        = 1 << 0,
    371 @@ -95,6 +98,7 @@ typedef struct {
    372  	int mode;
    373  	int type;
    374  	int snap;
    375 +	int swap;
    376  	/*
    377  	 * Selection variables:
    378  	 * nb – normalized coordinates of the beginning of the selection
    379 @@ -178,7 +182,6 @@ static void tdeleteline(int);
    380  static void tinsertblank(int);
    381  static void tinsertblankline(int);
    382  static int tlinelen(int);
    383 -static void tmoveto(int, int);
    384  static void tmoveato(int, int);
    385  static void tnewline(int);
    386  static void tputtab(int);
    387 @@ -205,7 +208,6 @@ static void drawregion(int, int, int, int);
    388  
    389  static void selnormalize(void);
    390  static void selscroll(int, int);
    391 -static void selsnap(int *, int *, int);
    392  
    393  static size_t utf8decode(const char *, Rune *, size_t);
    394  static Rune utf8decodebyte(char, size_t *);
    395 @@ -231,6 +233,14 @@ static uchar utfmask[UTF_SIZ + 1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
    396  static Rune utfmin[UTF_SIZ + 1] = {       0,    0,  0x80,  0x800,  0x10000};
    397  static Rune utfmax[UTF_SIZ + 1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
    398  
    399 +int buffCols;
    400 +extern int const buffSize;
    401 +int histOp, histMode, histOff, insertOff, altToggle, *mark;
    402 +Line *buf = NULL;
    403 +static TCursor c[3];
    404 +static inline int rows() { return IS_SET(MODE_ALTSCREEN) ? term.row : buffSize;}
    405 +static inline int rangeY(int i) { while (i < 0) i += rows(); return i % rows();}
    406 +
    407  ssize_t
    408  xwrite(int fd, const char *s, size_t len)
    409  {
    410 @@ -423,6 +433,118 @@ tlinelen(int y)
    411  	return i;
    412  }
    413  
    414 +void historyOpToggle(int start, int paint) {
    415 +	if ((!histOp == !(histOp + start)) && ((histOp += start) || 1)) return;
    416 +	if (histMode && paint && (!IS_SET(MODE_ALTSCREEN) || altToggle)) draw();
    417 +	tcursor(CURSOR_SAVE);
    418 +	histOp += start;
    419 +	if (histMode && altToggle) {
    420 +		tswapscreen();
    421 +		memset(term.dirty,0,sizeof(*term.dirty)*term.row);
    422 +	}
    423 +	tcursor(CURSOR_LOAD);
    424 +	*(!IS_SET(MODE_ALTSCREEN)?&term.line:&term.alt)=&buf[histOp?histOff:insertOff];
    425 +}
    426 +
    427 +void historyModeToggle(int start) {
    428 +	if (!(histMode = (histOp = !!start))) {
    429 +		selnormalize();
    430 +		tfulldirt();
    431 +	} else {
    432 +		tcursor(CURSOR_SAVE);
    433 +		histOp = 0;
    434 +		histOff = insertOff;
    435 +	}
    436 +}
    437 +
    438 +int historyBufferScroll(int n) {
    439 +	if (IS_SET(MODE_ALTSCREEN) || !n) return histOp;
    440 +	int p=abs(n=(n<0) ? max(n,-term.row) : min(n,term.row)), r=term.row-p,
    441 +	          s=sizeof(*term.dirty), *ptr=histOp?&histOff:&insertOff;
    442 +	if (!histMode || histOp) tfulldirt(); else {
    443 +		memmove(&term.dirty[-min(n,0)], &term.dirty[max(n,0)], s*r);
    444 +		memset(&term.dirty[n>0 ? r : 0], 0, s * p);
    445 +	}
    446 +	term.line = &buf[*ptr = (buffSize+*ptr+n) % buffSize];
    447 +	// Cut part of selection removed from buffer, and update sel.ne/b.
    448 +	int const prevOffBuf = sel.alt ? 0 : insertOff + term.row;
    449 +	if (sel.ob.x != -1 && !histOp && n) {
    450 +		int const offBuf = sel.alt ? 0 : insertOff + term.row,
    451 +		          pb = rangeY(sel.ob.y - prevOffBuf),
    452 +		          pe = rangeY(sel.oe.y - prevOffBuf);
    453 +		int const b = rangeY(sel.ob.y - offBuf), nln = n < 0,
    454 +		          e = rangeY(sel.oe.y - offBuf), last = offBuf - nln;
    455 +		if (pb != b && ((pb < b) != nln)) sel.ob.y = last;
    456 +		if (pe != e && ((pe < e) != nln)) sel.oe.y = last;
    457 +		if (sel.oe.y == last && sel.ob.y == last) selclear();
    458 +	}
    459 +	selnormalize();
    460 +  // Clear the new region exposed by the shift.
    461 +	if (!histOp) tclearregion(0, n>0?r+1:0, buffCols-1, n>0?term.row:p-1);
    462 +	return 1;
    463 +}
    464 +
    465 +int historyMove(int x, int y, int ly) {
    466 +	historyOpToggle(1, 1);
    467 +	y += ((term.c.x += x) < 0 ?term.c.x-term.col :term.c.x) / term.col;//< x
    468 +	if ((term.c.x %= term.col) < 0) term.c.x += term.col;
    469 +	if ((term.c.y += y) >= term.row) ly += term.c.y - term.row + 1;    //< y
    470 +	else if (term.c.y < 0) ly += term.c.y;
    471 +	term.c.y = MIN(MAX(term.c.y, 0), term.row - 1);
    472 +	// Check if scroll is necessary / arrived at top / bottom of terminal history
    473 +	int t = 0, b = 0, finTop = ly < 0, finBot = ly > 0;
    474 +	if (!IS_SET(MODE_ALTSCREEN)) {
    475 +		b=rangeY(insertOff-histOff), t=-rangeY(-term.row-(insertOff-histOff));
    476 +		finBot = ly > b, finTop=histMode&&((-ly>-t));
    477 +	}
    478 +	if ((finTop || finBot) && (x||y)) term.c.x = finBot ? term.col-1 : 0;
    479 +	historyBufferScroll(finBot ? b : (finTop ? t : ly));
    480 +	historyOpToggle(-1, 1);
    481 +	return finTop || finBot;
    482 +}
    483 +
    484 +#include "normalMode.c"
    485 +
    486 +void selnormalize(void) {
    487 +	historyOpToggle(1, 1);
    488 +
    489 +	int const oldb = sel.nb.y, olde = sel.ne.y;
    490 +	if (sel.ob.x == -1) {
    491 +		sel.ne.y = sel.nb.y = -1;
    492 +	} else {
    493 +		int const offsetBuffer = sel.alt ? 0 : insertOff + term.row;
    494 +		int const off = sel.alt ? 0 : (histMode ? histOff : insertOff);
    495 +		int const nby = rangeY(sel.ob.y - off),
    496 +		          ney = rangeY(sel.oe.y - off);
    497 +		sel.swap = rangeY(sel.ob.y - offsetBuffer)
    498 +		         > rangeY(sel.oe.y - offsetBuffer);
    499 +		sel.nb.y = sel.swap ? ney : nby;
    500 +		sel.ne.y = !sel.swap ? ney : nby;
    501 +		int const cnb = sel.nb.y < term.row, cne = sel.ne.y < term.row;
    502 +		if (sel.type == SEL_REGULAR && sel.ob.y != sel.oe.y) {
    503 +			if (cnb) sel.nb.x = (!sel.swap) ? sel.ob.x : sel.oe.x;
    504 +			if (cne) sel.ne.x = (!sel.swap) ? sel.oe.x : sel.ob.x;
    505 +		} else {
    506 +			if (cnb) sel.nb.x = MIN(sel.ob.x, sel.oe.x);
    507 +			if (cne) sel.ne.x = MAX(sel.ob.x, sel.oe.x);
    508 +		}
    509 +	}
    510 +	int const nBet=sel.nb.y<=sel.ne.y, oBet=oldb<=olde;
    511 +	for (int i = 0; i < term.row; ++i) {
    512 +		int const n = nBet ? BETWEEN(i, sel.nb.y, sel.ne.y)
    513 +		                   : OUT(i, sel.nb.y, sel.ne.y);
    514 +		term.dirty[i] |= (sel.type == SEL_RECTANGULAR && n) ||
    515 +		        (n != (oBet ? BETWEEN(i,oldb,olde) : OUT(i,oldb,olde)));
    516 +
    517 +	}
    518 +	if (BETWEEN(oldb, 0, term.row - 1)) term.dirty[oldb] = 1;
    519 +	if (BETWEEN(olde, 0, term.row - 1)) term.dirty[olde] = 1;
    520 +	if (BETWEEN(sel.nb.y, 0, term.row - 1)) term.dirty[sel.nb.y] = 1;
    521 +	if (BETWEEN(sel.ne.y, 0, term.row - 1)) term.dirty[sel.ne.y] = 1;
    522 +
    523 +	historyOpToggle(-1, 1);
    524 +}
    525 +
    526  void
    527  selstart(int col, int row, int snap)
    528  {
    529 @@ -432,19 +554,14 @@ selstart(int col, int row, int snap)
    530  	sel.alt = IS_SET(MODE_ALTSCREEN);
    531  	sel.snap = snap;
    532  	sel.oe.x = sel.ob.x = col;
    533 -	sel.oe.y = sel.ob.y = row;
    534 +	sel.oe.y = sel.ob.y = row + !sel.alt * (histMode ? histOff : insertOff);
    535 +	if (sel.snap != 0) sel.mode = SEL_READY;
    536  	selnormalize();
    537 -
    538 -	if (sel.snap != 0)
    539 -		sel.mode = SEL_READY;
    540 -	tsetdirt(sel.nb.y, sel.ne.y);
    541  }
    542  
    543  void
    544  selextend(int col, int row, int type, int done)
    545  {
    546 -	int oldey, oldex, oldsby, oldsey, oldtype;
    547 -
    548  	if (sel.mode == SEL_IDLE)
    549  		return;
    550  	if (done && sel.mode == SEL_EMPTY) {
    551 @@ -452,51 +569,13 @@ selextend(int col, int row, int type, int done)
    552  		return;
    553  	}
    554  
    555 -	oldey = sel.oe.y;
    556 -	oldex = sel.oe.x;
    557 -	oldsby = sel.nb.y;
    558 -	oldsey = sel.ne.y;
    559 -	oldtype = sel.type;
    560 -
    561  	sel.oe.x = col;
    562 -	sel.oe.y = row;
    563 +	sel.oe.y = row + (sel.alt ? 0 : (histMode ? histOff : insertOff));
    564  	selnormalize();
    565  	sel.type = type;
    566 -
    567 -	if (oldey != sel.oe.y || oldex != sel.oe.x || oldtype != sel.type || sel.mode == SEL_EMPTY)
    568 -		tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
    569 -
    570  	sel.mode = done ? SEL_IDLE : SEL_READY;
    571  }
    572  
    573 -void
    574 -selnormalize(void)
    575 -{
    576 -	int i;
    577 -
    578 -	if (sel.type == SEL_REGULAR && sel.ob.y != sel.oe.y) {
    579 -		sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
    580 -		sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
    581 -	} else {
    582 -		sel.nb.x = MIN(sel.ob.x, sel.oe.x);
    583 -		sel.ne.x = MAX(sel.ob.x, sel.oe.x);
    584 -	}
    585 -	sel.nb.y = MIN(sel.ob.y, sel.oe.y);
    586 -	sel.ne.y = MAX(sel.ob.y, sel.oe.y);
    587 -
    588 -	selsnap(&sel.nb.x, &sel.nb.y, -1);
    589 -	selsnap(&sel.ne.x, &sel.ne.y, +1);
    590 -
    591 -	/* expand selection over line breaks */
    592 -	if (sel.type == SEL_RECTANGULAR)
    593 -		return;
    594 -	i = tlinelen(sel.nb.y);
    595 -	if (i < sel.nb.x)
    596 -		sel.nb.x = i;
    597 -	if (tlinelen(sel.ne.y) <= sel.ne.x)
    598 -		sel.ne.x = term.col - 1;
    599 -}
    600 -
    601  int
    602  selected(int x, int y)
    603  {
    604 @@ -508,119 +587,47 @@ selected(int x, int y)
    605  		return BETWEEN(y, sel.nb.y, sel.ne.y)
    606  		    && BETWEEN(x, sel.nb.x, sel.ne.x);
    607  
    608 -	return BETWEEN(y, sel.nb.y, sel.ne.y)
    609 -	    && (y != sel.nb.y || x >= sel.nb.x)
    610 -	    && (y != sel.ne.y || x <= sel.ne.x);
    611 -}
    612 -
    613 -void
    614 -selsnap(int *x, int *y, int direction)
    615 -{
    616 -	int newx, newy, xt, yt;
    617 -	int delim, prevdelim;
    618 -	Glyph *gp, *prevgp;
    619 -
    620 -	switch (sel.snap) {
    621 -	case SNAP_WORD:
    622 -		/*
    623 -		 * Snap around if the word wraps around at the end or
    624 -		 * beginning of a line.
    625 -		 */
    626 -		prevgp = &term.line[*y][*x];
    627 -		prevdelim = ISDELIM(prevgp->u);
    628 -		for (;;) {
    629 -			newx = *x + direction;
    630 -			newy = *y;
    631 -			if (!BETWEEN(newx, 0, term.col - 1)) {
    632 -				newy += direction;
    633 -				newx = (newx + term.col) % term.col;
    634 -				if (!BETWEEN(newy, 0, term.row - 1))
    635 -					break;
    636 -
    637 -				if (direction > 0)
    638 -					yt = *y, xt = *x;
    639 -				else
    640 -					yt = newy, xt = newx;
    641 -				if (!(term.line[yt][xt].mode & ATTR_WRAP))
    642 -					break;
    643 -			}
    644 -
    645 -			if (newx >= tlinelen(newy))
    646 -				break;
    647 -
    648 -			gp = &term.line[newy][newx];
    649 -			delim = ISDELIM(gp->u);
    650 -			if (!(gp->mode & ATTR_WDUMMY) && (delim != prevdelim
    651 -					|| (delim && gp->u != prevgp->u)))
    652 -				break;
    653 -
    654 -			*x = newx;
    655 -			*y = newy;
    656 -			prevgp = gp;
    657 -			prevdelim = delim;
    658 -		}
    659 -		break;
    660 -	case SNAP_LINE:
    661 -		/*
    662 -		 * Snap around if the the previous line or the current one
    663 -		 * has set ATTR_WRAP at its end. Then the whole next or
    664 -		 * previous line will be selected.
    665 -		 */
    666 -		*x = (direction < 0) ? 0 : term.col - 1;
    667 -		if (direction < 0) {
    668 -			for (; *y > 0; *y += direction) {
    669 -				if (!(term.line[*y-1][term.col-1].mode
    670 -						& ATTR_WRAP)) {
    671 -					break;
    672 -				}
    673 -			}
    674 -		} else if (direction > 0) {
    675 -			for (; *y < term.row-1; *y += direction) {
    676 -				if (!(term.line[*y][term.col-1].mode
    677 -						& ATTR_WRAP)) {
    678 -					break;
    679 -				}
    680 -			}
    681 -		}
    682 -		break;
    683 -	}
    684 +	return ((sel.nb.y > sel.ne.y) ? OUT(y, sel.nb.y, sel.ne.y)
    685 +	                              : BETWEEN(y, sel.nb.y, sel.ne.y)) &&
    686 +	       (y != sel.nb.y || x >= sel.nb.x) &&
    687 +	       (y != sel.ne.y || x <= sel.ne.x);
    688  }
    689  
    690  char *
    691  getsel(void)
    692  {
    693  	char *str, *ptr;
    694 -	int y, bufsize, lastx, linelen;
    695 +	int y, yy, bufsize, lastx;
    696  	Glyph *gp, *last;
    697  
    698  	if (sel.ob.x == -1)
    699  		return NULL;
    700  
    701 -	bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
    702 +	int const start = sel.swap ? sel.oe.y : sel.ob.y, h = rows();
    703 +	int endy = (sel.swap ? sel.ob.y : sel.oe.y);
    704 +	for (; endy < start; endy += h);
    705 +	Line * const cbuf = IS_SET(MODE_ALTSCREEN) ? term.line : buf;
    706 +	bufsize = (term.col+1) * (endy-start+1 ) * UTF_SIZ;
    707 +	assert(bufsize > 0);
    708  	ptr = str = xmalloc(bufsize);
    709  
    710  	/* append every set & selected glyph to the selection */
    711 -	for (y = sel.nb.y; y <= sel.ne.y; y++) {
    712 -		if ((linelen = tlinelen(y)) == 0) {
    713 -			*ptr++ = '\n';
    714 -			continue;
    715 -		}
    716 +	for (y = start; y <= endy; y++) {
    717 +		yy = y % h;
    718  
    719  		if (sel.type == SEL_RECTANGULAR) {
    720 -			gp = &term.line[y][sel.nb.x];
    721 +			gp = &cbuf[yy][sel.nb.x];
    722  			lastx = sel.ne.x;
    723  		} else {
    724 -			gp = &term.line[y][sel.nb.y == y ? sel.nb.x : 0];
    725 -			lastx = (sel.ne.y == y) ? sel.ne.x : term.col-1;
    726 +			gp = &cbuf[yy][start == y ? sel.nb.x : 0];
    727 +			lastx = (endy == y) ? sel.ne.x : term.col-1;
    728  		}
    729 -		last = &term.line[y][MIN(lastx, linelen-1)];
    730 -		while (last >= gp && last->u == ' ')
    731 -			--last;
    732 +		last = &cbuf[yy][lastx];
    733 +		if (!(cbuf[yy][term.col - 1].mode & ATTR_WRAP))
    734 +			while (last > gp && last->u == ' ') --last;
    735  
    736  		for ( ; gp <= last; ++gp) {
    737 -			if (gp->mode & ATTR_WDUMMY)
    738 -				continue;
    739 -
    740 +			if (gp->mode & ATTR_WDUMMY) continue;
    741  			ptr += utf8encode(gp->u, ptr);
    742  		}
    743  
    744 @@ -633,7 +640,7 @@ getsel(void)
    745  		 * st.
    746  		 * FIXME: Fix the computer world.
    747  		 */
    748 -		if ((y < sel.ne.y || lastx >= linelen) &&
    749 +		if ((y < endy || lastx == term.col - 1) &&
    750  		    (!(last->mode & ATTR_WRAP) || sel.type == SEL_RECTANGULAR))
    751  			*ptr++ = '\n';
    752  	}
    753 @@ -648,7 +655,7 @@ selclear(void)
    754  		return;
    755  	sel.mode = SEL_IDLE;
    756  	sel.ob.x = -1;
    757 -	tsetdirt(sel.nb.y, sel.ne.y);
    758 +	selnormalize();
    759  }
    760  
    761  void
    762 @@ -1000,8 +1007,7 @@ tfulldirt(void)
    763  void
    764  tcursor(int mode)
    765  {
    766 -	static TCursor c[2];
    767 -	int alt = IS_SET(MODE_ALTSCREEN);
    768 +	int alt = (histOp) ? 0 : (IS_SET(MODE_ALTSCREEN) + 1);
    769  
    770  	if (mode == CURSOR_SAVE) {
    771  		c[alt] = term.c;
    772 @@ -1061,6 +1067,7 @@ tswapscreen(void)
    773  void
    774  tscrolldown(int orig, int n)
    775  {
    776 +	if (!orig && historyBufferScroll(-n)) return;
    777  	int i;
    778  	Line temp;
    779  
    780 @@ -1081,6 +1088,7 @@ tscrolldown(int orig, int n)
    781  void
    782  tscrollup(int orig, int n)
    783  {
    784 +	if (!orig && historyBufferScroll(n)) return;
    785  	int i;
    786  	Line temp;
    787  
    788 @@ -1232,8 +1240,8 @@ tclearregion(int x1, int y1, int x2, int y2)
    789  	if (y1 > y2)
    790  		temp = y1, y1 = y2, y2 = temp;
    791  
    792 -	LIMIT(x1, 0, term.col-1);
    793 -	LIMIT(x2, 0, term.col-1);
    794 +	LIMIT(x1, 0, buffCols-1);
    795 +	LIMIT(x2, 0, buffCols-1);
    796  	LIMIT(y1, 0, term.row-1);
    797  	LIMIT(y2, 0, term.row-1);
    798  
    799 @@ -2394,8 +2402,6 @@ check_control_code:
    800  		 */
    801  		return;
    802  	}
    803 -	if (selected(term.c.x, term.c.y))
    804 -		selclear();
    805  
    806  	gp = &term.line[term.c.y][term.c.x];
    807  	if (IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
    808 @@ -2465,8 +2471,10 @@ void
    809  tresize(int col, int row)
    810  {
    811  	int i;
    812 -	int minrow = MIN(row, term.row);
    813 -	int mincol = MIN(col, term.col);
    814 +	int const colSet = col, alt = IS_SET(MODE_ALTSCREEN), ini = buf == NULL;
    815 +	col = MAX(col, buffCols);
    816 +	row = MIN(row, buffSize);
    817 +	int const minrow = MIN(row, term.row), mincol = MIN(col, buffCols);
    818  	int *bp;
    819  	TCursor c;
    820  
    821 @@ -2475,6 +2483,7 @@ tresize(int col, int row)
    822  		        "tresize: error resizing to %dx%d\n", col, row);
    823  		return;
    824  	}
    825 +	if (alt) tswapscreen();
    826  
    827  	/*
    828  	 * slide screen to keep cursor where we expect it -
    829 @@ -2482,48 +2491,54 @@ tresize(int col, int row)
    830  	 * memmove because we're freeing the earlier lines
    831  	 */
    832  	for (i = 0; i <= term.c.y - row; i++) {
    833 -		free(term.line[i]);
    834  		free(term.alt[i]);
    835  	}
    836  	/* ensure that both src and dst are not NULL */
    837  	if (i > 0) {
    838 -		memmove(term.line, term.line + i, row * sizeof(Line));
    839  		memmove(term.alt, term.alt + i, row * sizeof(Line));
    840  	}
    841  	for (i += row; i < term.row; i++) {
    842 -		free(term.line[i]);
    843  		free(term.alt[i]);
    844  	}
    845  
    846  	/* resize to new height */
    847 -	term.line = xrealloc(term.line, row * sizeof(Line));
    848 +	buf = xrealloc(buf, (buffSize + row) * sizeof(Line));
    849  	term.alt  = xrealloc(term.alt,  row * sizeof(Line));
    850  	term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
    851 +	mark = xrealloc(mark, col * row * sizeof(*mark));
    852  	term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
    853  
    854  	/* resize each row to new width, zero-pad if needed */
    855  	for (i = 0; i < minrow; i++) {
    856 -		term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
    857  		term.alt[i]  = xrealloc(term.alt[i],  col * sizeof(Glyph));
    858  	}
    859  
    860  	/* allocate any new rows */
    861  	for (/* i = minrow */; i < row; i++) {
    862 -		term.line[i] = xmalloc(col * sizeof(Glyph));
    863  		term.alt[i] = xmalloc(col * sizeof(Glyph));
    864  	}
    865 -	if (col > term.col) {
    866 -		bp = term.tabs + term.col;
    867 +	if (col > buffCols) {
    868 +		bp = term.tabs + buffCols;
    869  
    870 -		memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
    871 +		memset(bp, 0, sizeof(*term.tabs) * (col - buffCols));
    872  		while (--bp > term.tabs && !*bp)
    873  			/* nothing */ ;
    874  		for (bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
    875  			*bp = 1;
    876  	}
    877 +	Glyph g=(Glyph){.bg=term.c.attr.bg, .fg=term.c.attr.fg, .u=' ', .mode=0};
    878 +	for (i = 0; i < buffSize; ++i) {
    879 +		buf[i] = xrealloc(ini ? NULL : buf[i], col*sizeof(Glyph));
    880 +		for (int j = ini ? 0 : buffCols; j < col; ++j) buf[i][j] = g;
    881 +	}
    882 +	for (i = 0; i < row; ++i) buf[buffSize + i] = buf[i];
    883 +	term.line = &buf[*(histOp?&histOff:&insertOff) +=MAX(term.c.y-row+1,0)];
    884 +	memset(mark, 0, col * row * sizeof(*mark));
    885  	/* update terminal size */
    886 -	term.col = col;
    887 +	term.col = colSet;
    888 +	buffCols = col;
    889  	term.row = row;
    890 +	if (alt) tswapscreen();
    891  	/* reset scrolling region */
    892  	tsetscroll(0, row-1);
    893  	/* make use of the LIMIT in tmoveto */
    894 @@ -2552,15 +2567,17 @@ resettitle(void)
    895  void
    896  drawregion(int x1, int y1, int x2, int y2)
    897  {
    898 +	if (altToggle && histMode && !histOp)
    899 +		memset(term.dirty, 0, sizeof(*term.dirty) * term.row);
    900 +	int const o = !IS_SET(MODE_ALTSCREEN) && histMode && !histOp, h =rows();
    901  	int y;
    902  
    903  	for (y = y1; y < y2; y++) {
    904 -		if (!term.dirty[y])
    905 -			continue;
    906 -
    907 -		term.dirty[y] = 0;
    908 -		xdrawline(term.line[y], x1, y, x2);
    909 +		int const oy = o ? (y + insertOff - histOff + h) % h : y;
    910 +		if (!BETWEEN(oy, 0, term.row-1) || !term.dirty[y]) continue;
    911 +		xdrawline(term.line[y], x1, oy, x2);
    912  	}
    913 +	memset(&term.dirty[y1], 0, sizeof(*term.dirty) * (y2 - y1));
    914  }
    915  
    916  void
    917 @@ -2579,7 +2596,9 @@ draw(void)
    918  	if (term.line[term.c.y][cx].mode & ATTR_WDUMMY)
    919  		cx--;
    920  
    921 +	if (histMode) historyPreDraw();
    922  	drawregion(0, 0, term.col, term.row);
    923 +	if (!histMode)
    924  	xdrawcursor(cx, term.c.y, term.line[term.c.y][cx],
    925  			term.ocx, term.ocy, term.line[term.ocy][term.ocx]);
    926  	term.ocx = cx;
    927 diff --git a/st.h b/st.h
    928 index 3d351b6..ad2915f 100644
    929 --- a/st.h
    930 +++ b/st.h
    931 @@ -8,6 +8,7 @@
    932  #define MAX(a, b)		((a) < (b) ? (b) : (a))
    933  #define LEN(a)			(sizeof(a) / sizeof(a)[0])
    934  #define BETWEEN(x, a, b)	((a) <= (x) && (x) <= (b))
    935 +#define OUT(x, a, b)		((a) <= (x) || (x) <= (b))
    936  #define DIVCEIL(n, d)		(((n) + ((d) - 1)) / (d))
    937  #define DEFAULT(a, b)		(a) = (a) ? (a) : (b)
    938  #define LIMIT(x, a, b)		(x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
    939 @@ -89,6 +90,7 @@ void toggleprinter(const Arg *);
    940  int tattrset(int);
    941  void tnew(int, int);
    942  void tresize(int, int);
    943 +void tmoveto(int x, int y);
    944  void tsetdirtattr(int);
    945  void ttyhangup(void);
    946  int ttynew(char *, char *, char *, char **);
    947 diff --git a/utils.h b/utils.h
    948 new file mode 100644
    949 index 0000000..ca435e6
    950 --- /dev/null
    951 +++ b/utils.h
    952 @@ -0,0 +1,23 @@
    953 +/// Dynamic memory-chunk, with (1) datatype size, (2/3) initialized / allocated chunk, (4) content
    954 +typedef struct { uint8_t const elSize; uint32_t init, alloc; char* content; } DynamicArray;
    955 +#define UTF8_ARRAY {4, 0, 0, NULL}
    956 +
    957 +static inline int p_alloc(DynamicArray *s, uint32_t amount) {
    958 +	uint32_t const diff=s->init+s->elSize*amount-s->alloc, nas=s->alloc+max(diff,15)*s->elSize;
    959 +	if (s->alloc < s->init + s->elSize * amount) {
    960 +		char* tmp = realloc(s->content, nas);
    961 +		if (!tmp) return 0;
    962 +		s->alloc = nas, s->content = tmp;
    963 +	}
    964 +	return 1;
    965 +}
    966 +static inline char *view(DynamicArray * s, uint32_t i) { return s->content + i*s->elSize; }
    967 +static inline char *end(DynamicArray *s, uint32_t i) { return s->content +s->init-(i+1)*s->elSize; }
    968 +static inline uint32_t getU32(DynamicArray* s, uint32_t i, int b) { return *((uint32_t*) (b ?view(s,i) :end(s,i))); }
    969 +static char *expand(DynamicArray *s) { if (!p_alloc(s, 1)) return NULL; s->init += s->elSize; return end(s, 0); }
    970 +static inline void pop(DynamicArray* s) { s->init -= s->elSize; }
    971 +static inline void empty(DynamicArray* s) { s->init = 0; }
    972 +static inline int size(DynamicArray const * s) { return s->init / s->elSize; }
    973 +static inline void assign(DynamicArray* s, DynamicArray const *o) { 
    974 +	if (p_alloc(s, size(o))) memcpy(s->content, o->content, (s->init=o->init));
    975 +}
    976 diff --git a/win.h b/win.h
    977 index a6ef1b9..cea19f3 100644
    978 --- a/win.h
    979 +++ b/win.h
    980 @@ -19,6 +19,7 @@ enum win_mode {
    981  	MODE_MOUSEMANY   = 1 << 15,
    982  	MODE_BRCKTPASTE  = 1 << 16,
    983  	MODE_NUMLOCK     = 1 << 17,
    984 +	MODE_NORMAL      = 1 << 18,
    985  	MODE_MOUSE       = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
    986  	                  |MODE_MOUSEMANY,
    987  };
    988 diff --git a/x.c b/x.c
    989 index 210f184..643e870 100644
    990 --- a/x.c
    991 +++ b/x.c
    992 @@ -19,6 +19,7 @@ char *argv0;
    993  #include "arg.h"
    994  #include "st.h"
    995  #include "win.h"
    996 +#include "normalMode.h"
    997  
    998  /* types used in config.h */
    999  typedef struct {
   1000 @@ -261,6 +262,7 @@ clipcopy(const Arg *dummy)
   1001  
   1002  	free(xsel.clipboard);
   1003  	xsel.clipboard = NULL;
   1004 +	xsetsel(getsel());
   1005  
   1006  	if (xsel.primary != NULL) {
   1007  		xsel.clipboard = xstrdup(xsel.primary);
   1008 @@ -460,7 +462,6 @@ void
   1009  bpress(XEvent *e)
   1010  {
   1011  	struct timespec now;
   1012 -	int snap;
   1013  
   1014  	if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
   1015  		mousereport(e);
   1016 @@ -476,17 +477,34 @@ bpress(XEvent *e)
   1017  		 * snapping behaviour is exposed.
   1018  		 */
   1019  		clock_gettime(CLOCK_MONOTONIC, &now);
   1020 -		if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) {
   1021 -			snap = SNAP_LINE;
   1022 -		} else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) {
   1023 -			snap = SNAP_WORD;
   1024 +		int const tripleClick = TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout,
   1025 +		doubleClick = TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout;
   1026 +		if ((mouseYank || mouseSelect) && (tripleClick || doubleClick)) {
   1027 +			if (!IS_SET(MODE_NORMAL)) normalMode();
   1028 +			historyOpToggle(1, 1);
   1029 +			tmoveto(evcol(e), evrow(e));
   1030 +			if (tripleClick) {
   1031 +				if (mouseYank) pressKeys("dVy", 3);
   1032 +				if (mouseSelect) pressKeys("dV", 2);
   1033 +			} else if (doubleClick) {
   1034 +				if (mouseYank) pressKeys("dyiW", 4);
   1035 +				if (mouseSelect) {
   1036 +					tmoveto(evcol(e), evrow(e));
   1037 +					pressKeys("viW", 3);
   1038 +				}
   1039 +			}
   1040 +			historyOpToggle(-1, 1);
   1041  		} else {
   1042 -			snap = 0;
   1043 +			if (!IS_SET(MODE_NORMAL)) selstart(evcol(e), evrow(e), 0);
   1044 +			else {
   1045 +				historyOpToggle(1, 1);
   1046 +				tmoveto(evcol(e), evrow(e));
   1047 +				pressKeys("v", 1);
   1048 +				historyOpToggle(-1, 1);
   1049 +			}
   1050  		}
   1051  		xsel.tclick2 = xsel.tclick1;
   1052  		xsel.tclick1 = now;
   1053 -
   1054 -		selstart(evcol(e), evrow(e), snap);
   1055  	}
   1056  }
   1057  
   1058 @@ -691,8 +709,7 @@ brelease(XEvent *e)
   1059  
   1060  	if (mouseaction(e, 1))
   1061  		return;
   1062 -	if (e->xbutton.button == Button1)
   1063 -		mousesel(e, 1);
   1064 +	if (e->xbutton.button == Button1 && !IS_SET(MODE_NORMAL)) mousesel(e, 1);
   1065  }
   1066  
   1067  void
   1068 @@ -772,6 +789,8 @@ xloadcolor(int i, const char *name, Color *ncolor)
   1069  	return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
   1070  }
   1071  
   1072 +void normalMode() { historyModeToggle((win.mode ^=MODE_NORMAL) & MODE_NORMAL); }
   1073 +
   1074  void
   1075  xloadcols(void)
   1076  {
   1077 @@ -1225,8 +1244,10 @@ xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x
   1078  
   1079  	for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
   1080  		/* Fetch rune and mode for current glyph. */
   1081 -		rune = glyphs[i].u;
   1082 -		mode = glyphs[i].mode;
   1083 +		Glyph g = glyphs[i];
   1084 +		historyOverlay(x+i, y, &g);
   1085 +		rune = g.u;
   1086 +		mode = g.mode;
   1087  
   1088  		/* Skip dummy wide-character spacing. */
   1089  		if (mode == ATTR_WDUMMY)
   1090 @@ -1609,6 +1630,7 @@ xdrawline(Line line, int x1, int y1, int x2)
   1091  	i = ox = 0;
   1092  	for (x = x1; x < x2 && i < numspecs; x++) {
   1093  		new = line[x];
   1094 +		historyOverlay(x, y1, &new);
   1095  		if (new.mode == ATTR_WDUMMY)
   1096  			continue;
   1097  		if (selected(x, y1))
   1098 @@ -1800,6 +1822,11 @@ kpress(XEvent *ev)
   1099  		len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
   1100  	else
   1101  		len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
   1102 +	if (IS_SET(MODE_NORMAL)) {
   1103 +		if (kPressHist(buf, len, match(ControlMask, e->state), &ksym)
   1104 +		                                      == finish) normalMode();
   1105 +		return;
   1106 +	}
   1107  	/* 1. shortcuts */
   1108  	for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
   1109  		if (ksym == bp->keysym && match(bp->mod, e->state)) {