xref: /plan9/sys/src/cmd/acme/text.c (revision e0d6d19cdffb15d5c5f1e7337cee05064ead1fd0)
1 #include <u.h>
2 #include <libc.h>
3 #include <draw.h>
4 #include <thread.h>
5 #include <cursor.h>
6 #include <mouse.h>
7 #include <keyboard.h>
8 #include <frame.h>
9 #include <fcall.h>
10 #include <plumb.h>
11 #include <complete.h>
12 #include "dat.h"
13 #include "fns.h"
14 
15 Image	*tagcols[NCOL];
16 Image	*textcols[NCOL];
17 
18 enum{
19 	TABDIR = 3	/* width of tabs in directory windows */
20 };
21 
22 void
23 textinit(Text *t, File *f, Rectangle r, Reffont *rf, Image *cols[NCOL])
24 {
25 	t->file = f;
26 	t->all = r;
27 	t->scrollr = r;
28 	t->scrollr.max.x = r.min.x+Scrollwid;
29 	t->lastsr = nullrect;
30 	r.min.x += Scrollwid+Scrollgap;
31 	t->eq0 = ~0;
32 	t->ncache = 0;
33 	t->reffont = rf;
34 	t->tabstop = maxtab;
35 	memmove(t->Frame.cols, cols, sizeof t->Frame.cols);
36 	textredraw(t, r, rf->f, screen, -1);
37 }
38 
39 void
40 textredraw(Text *t, Rectangle r, Font *f, Image *b, int odx)
41 {
42 	int maxt;
43 	Rectangle rr;
44 
45 	frinit(t, r, f, b, t->Frame.cols);
46 	rr = t->r;
47 	rr.min.x -= Scrollwid;	/* back fill to scroll bar */
48 	draw(t->b, rr, t->cols[BACK], nil, ZP);
49 	/* use no wider than 3-space tabs in a directory */
50 	maxt = maxtab;
51 	if(t->what == Body){
52 		if(t->w->isdir)
53 			maxt = min(TABDIR, maxtab);
54 		else
55 			maxt = t->tabstop;
56 	}
57 	t->maxtab = maxt*stringwidth(f, "0");
58 	if(t->what==Body && t->w->isdir && odx!=Dx(t->all)){
59 		if(t->maxlines > 0){
60 			textreset(t);
61 			textcolumnate(t, t->w->dlp,  t->w->ndl);
62 			textshow(t, 0, 0, 1);
63 		}
64 	}else{
65 		textfill(t);
66 		textsetselect(t, t->q0, t->q1);
67 	}
68 }
69 
70 int
71 textresize(Text *t, Rectangle r)
72 {
73 	int odx;
74 
75 	if(Dy(r) > 0)
76 		r.max.y -= Dy(r)%t->font->height;
77 	else
78 		r.max.y = r.min.y;
79 	odx = Dx(t->all);
80 	t->all = r;
81 	t->scrollr = r;
82 	t->scrollr.max.x = r.min.x+Scrollwid;
83 	t->lastsr = nullrect;
84 	r.min.x += Scrollwid+Scrollgap;
85 	frclear(t, 0);
86 	textredraw(t, r, t->font, t->b, odx);
87 	return r.max.y;
88 }
89 
90 void
91 textclose(Text *t)
92 {
93 	free(t->cache);
94 	frclear(t, 1);
95 	filedeltext(t->file, t);
96 	t->file = nil;
97 	rfclose(t->reffont);
98 	if(argtext == t)
99 		argtext = nil;
100 	if(typetext == t)
101 		typetext = nil;
102 	if(seltext == t)
103 		seltext = nil;
104 	if(mousetext == t)
105 		mousetext = nil;
106 	if(barttext == t)
107 		barttext = nil;
108 }
109 
110 int
111 dircmp(void *a, void *b)
112 {
113 	Dirlist *da, *db;
114 	int i, n;
115 
116 	da = *(Dirlist**)a;
117 	db = *(Dirlist**)b;
118 	n = min(da->nr, db->nr);
119 	i = memcmp(da->r, db->r, n*sizeof(Rune));
120 	if(i)
121 		return i;
122 	return da->nr - db->nr;
123 }
124 
125 void
126 textcolumnate(Text *t, Dirlist **dlp, int ndl)
127 {
128 	int i, j, w, colw, mint, maxt, ncol, nrow;
129 	Dirlist *dl;
130 	uint q1;
131 
132 	if(t->file->ntext > 1)
133 		return;
134 	mint = stringwidth(t->font, "0");
135 	/* go for narrower tabs if set more than 3 wide */
136 	t->maxtab = min(maxtab, TABDIR)*mint;
137 	maxt = t->maxtab;
138 	colw = 0;
139 	for(i=0; i<ndl; i++){
140 		dl = dlp[i];
141 		w = dl->wid;
142 		if(maxt-w%maxt < mint || w%maxt==0)
143 			w += mint;
144 		if(w % maxt)
145 			w += maxt-(w%maxt);
146 		if(w > colw)
147 			colw = w;
148 	}
149 	if(colw == 0)
150 		ncol = 1;
151 	else
152 		ncol = max(1, Dx(t->r)/colw);
153 	nrow = (ndl+ncol-1)/ncol;
154 
155 	q1 = 0;
156 	for(i=0; i<nrow; i++){
157 		for(j=i; j<ndl; j+=nrow){
158 			dl = dlp[j];
159 			fileinsert(t->file, q1, dl->r, dl->nr);
160 			q1 += dl->nr;
161 			if(j+nrow >= ndl)
162 				break;
163 			w = dl->wid;
164 			if(maxt-w%maxt < mint){
165 				fileinsert(t->file, q1, L"\t", 1);
166 				q1++;
167 				w += mint;
168 			}
169 			do{
170 				fileinsert(t->file, q1, L"\t", 1);
171 				q1++;
172 				w += maxt-(w%maxt);
173 			}while(w < colw);
174 		}
175 		fileinsert(t->file, q1, L"\n", 1);
176 		q1++;
177 	}
178 }
179 
180 uint
181 textload(Text *t, uint q0, char *file, int setqid)
182 {
183 	Rune *rp;
184 	Dirlist *dl, **dlp;
185 	int fd, i, j, n, ndl, nulls;
186 	uint q, q1;
187 	Dir *d, *dbuf;
188 	char *tmp;
189 	Text *u;
190 
191 	if(t->ncache!=0 || t->file->nc || t->w==nil || t!=&t->w->body)
192 		error("text.load");
193 	if(t->w->isdir && t->file->nname==0){
194 		warning(nil, "empty directory name\n");
195 		return 0;
196 	}
197 	fd = open(file, OREAD);
198 	if(fd < 0){
199 		warning(nil, "can't open %s: %r\n", file);
200 		return 0;
201 	}
202 	d = dirfstat(fd);
203 	if(d == nil){
204 		warning(nil, "can't fstat %s: %r\n", file);
205 		goto Rescue;
206 	}
207 	nulls = FALSE;
208 	if(d->qid.type & QTDIR){
209 		/* this is checked in get() but it's possible the file changed underfoot */
210 		if(t->file->ntext > 1){
211 			warning(nil, "%s is a directory; can't read with multiple windows on it\n", file);
212 			goto Rescue;
213 		}
214 		t->w->isdir = TRUE;
215 		t->w->filemenu = FALSE;
216 		if(t->file->name[t->file->nname-1] != '/'){
217 			rp = runemalloc(t->file->nname+1);
218 			runemove(rp, t->file->name, t->file->nname);
219 			rp[t->file->nname] = '/';
220 			winsetname(t->w, rp, t->file->nname+1);
221 			free(rp);
222 		}
223 		dlp = nil;
224 		ndl = 0;
225 		dbuf = nil;
226 		while((n=dirread(fd, &dbuf)) > 0){
227 			for(i=0; i<n; i++){
228 				dl = emalloc(sizeof(Dirlist));
229 				j = strlen(dbuf[i].name);
230 				tmp = emalloc(j+1+1);
231 				memmove(tmp, dbuf[i].name, j);
232 				if(dbuf[i].qid.type & QTDIR)
233 					tmp[j++] = '/';
234 				tmp[j] = '\0';
235 				dl->r = bytetorune(tmp, &dl->nr);
236 				dl->wid = stringwidth(t->font, tmp);
237 				free(tmp);
238 				ndl++;
239 				dlp = realloc(dlp, ndl*sizeof(Dirlist*));
240 				dlp[ndl-1] = dl;
241 			}
242 			free(dbuf);
243 		}
244 		qsort(dlp, ndl, sizeof(Dirlist*), dircmp);
245 		t->w->dlp = dlp;
246 		t->w->ndl = ndl;
247 		textcolumnate(t, dlp, ndl);
248 		q1 = t->file->nc;
249 	}else{
250 		t->w->isdir = FALSE;
251 		t->w->filemenu = TRUE;
252 		q1 = q0 + fileload(t->file, q0, fd, &nulls);
253 	}
254 	if(setqid){
255 		t->file->dev = d->dev;
256 		t->file->mtime = d->mtime;
257 		t->file->qidpath = d->qid.path;
258 	}
259 	close(fd);
260 	rp = fbufalloc();
261 	for(q=q0; q<q1; q+=n){
262 		n = q1-q;
263 		if(n > RBUFSIZE)
264 			n = RBUFSIZE;
265 		bufread(t->file, q, rp, n);
266 		if(q < t->org)
267 			t->org += n;
268 		else if(q <= t->org+t->nchars)
269 			frinsert(t, rp, rp+n, q-t->org);
270 		if(t->lastlinefull)
271 			break;
272 	}
273 	fbuffree(rp);
274 	for(i=0; i<t->file->ntext; i++){
275 		u = t->file->text[i];
276 		if(u != t){
277 			if(u->org > u->file->nc)	/* will be 0 because of reset(), but safety first */
278 				u->org = 0;
279 			textresize(u, u->all);
280 			textbacknl(u, u->org, 0);	/* go to beginning of line */
281 		}
282 		textsetselect(u, q0, q0);
283 	}
284 	if(nulls)
285 		warning(nil, "%s: NUL bytes elided\n", file);
286 	free(d);
287 	return q1-q0;
288 
289     Rescue:
290 	close(fd);
291 	return 0;
292 }
293 
294 uint
295 textbsinsert(Text *t, uint q0, Rune *r, uint n, int tofile, int *nrp)
296 {
297 	Rune *bp, *tp, *up;
298 	int i, initial;
299 
300 	if(t->what == Tag){	/* can't happen but safety first: mustn't backspace over file name */
301     Err:
302 		textinsert(t, q0, r, n, tofile);
303 		*nrp = n;
304 		return q0;
305 	}
306 	bp = r;
307 	for(i=0; i<n; i++)
308 		if(*bp++ == '\b'){
309 			--bp;
310 			initial = 0;
311 			tp = runemalloc(n);
312 			runemove(tp, r, i);
313 			up = tp+i;
314 			for(; i<n; i++){
315 				*up = *bp++;
316 				if(*up == '\b')
317 					if(up == tp)
318 						initial++;
319 					else
320 						--up;
321 				else
322 					up++;
323 			}
324 			if(initial){
325 				if(initial > q0)
326 					initial = q0;
327 				q0 -= initial;
328 				textdelete(t, q0, q0+initial, tofile);
329 			}
330 			n = up-tp;
331 			textinsert(t, q0, tp, n, tofile);
332 			free(tp);
333 			*nrp = n;
334 			return q0;
335 		}
336 	goto Err;
337 }
338 
339 void
340 textinsert(Text *t, uint q0, Rune *r, uint n, int tofile)
341 {
342 	int c, i;
343 	Text *u;
344 
345 	if(tofile && t->ncache != 0)
346 		error("text.insert");
347 	if(n == 0)
348 		return;
349 	if(tofile){
350 		fileinsert(t->file, q0, r, n);
351 		if(t->what == Body){
352 			t->w->dirty = TRUE;
353 			t->w->utflastqid = -1;
354 		}
355 		if(t->file->ntext > 1)
356 			for(i=0; i<t->file->ntext; i++){
357 				u = t->file->text[i];
358 				if(u != t){
359 					u->w->dirty = TRUE;	/* always a body */
360 					textinsert(u, q0, r, n, FALSE);
361 					textsetselect(u, u->q0, u->q1);
362 					textscrdraw(u);
363 				}
364 			}
365 
366 	}
367 	if(q0 < t->q1)
368 		t->q1 += n;
369 	if(q0 < t->q0)
370 		t->q0 += n;
371 	if(q0 < t->org)
372 		t->org += n;
373 	else if(q0 <= t->org+t->nchars)
374 		frinsert(t, r, r+n, q0-t->org);
375 	if(t->w){
376 		c = 'i';
377 		if(t->what == Body)
378 			c = 'I';
379 		if(n <= EVENTSIZE)
380 			winevent(t->w, "%c%d %d 0 %d %.*S\n", c, q0, q0+n, n, n, r);
381 		else
382 			winevent(t->w, "%c%d %d 0 0 \n", c, q0, q0+n, n);
383 	}
384 }
385 
386 
387 void
388 textfill(Text *t)
389 {
390 	Rune *rp;
391 	int i, n, m, nl;
392 
393 	if(t->lastlinefull || t->nofill)
394 		return;
395 	if(t->ncache > 0){
396 		if(t->w != nil)
397 			wincommit(t->w, t);
398 		else
399 			textcommit(t, TRUE);
400 	}
401 	rp = fbufalloc();
402 	do{
403 		n = t->file->nc-(t->org+t->nchars);
404 		if(n == 0)
405 			break;
406 		if(n > 2000)	/* educated guess at reasonable amount */
407 			n = 2000;
408 		bufread(t->file, t->org+t->nchars, rp, n);
409 		/*
410 		 * it's expensive to frinsert more than we need, so
411 		 * count newlines.
412 		 */
413 		nl = t->maxlines-t->nlines;
414 		m = 0;
415 		for(i=0; i<n; ){
416 			if(rp[i++] == '\n'){
417 				m++;
418 				if(m >= nl)
419 					break;
420 			}
421 		}
422 		frinsert(t, rp, rp+i, t->nchars);
423 	}while(t->lastlinefull == FALSE);
424 	fbuffree(rp);
425 }
426 
427 void
428 textdelete(Text *t, uint q0, uint q1, int tofile)
429 {
430 	uint n, p0, p1;
431 	int i, c;
432 	Text *u;
433 
434 	if(tofile && t->ncache != 0)
435 		error("text.delete");
436 	n = q1-q0;
437 	if(n == 0)
438 		return;
439 	if(tofile){
440 		filedelete(t->file, q0, q1);
441 		if(t->what == Body){
442 			t->w->dirty = TRUE;
443 			t->w->utflastqid = -1;
444 		}
445 		if(t->file->ntext > 1)
446 			for(i=0; i<t->file->ntext; i++){
447 				u = t->file->text[i];
448 				if(u != t){
449 					u->w->dirty = TRUE;	/* always a body */
450 					textdelete(u, q0, q1, FALSE);
451 					textsetselect(u, u->q0, u->q1);
452 					textscrdraw(u);
453 				}
454 			}
455 	}
456 	if(q0 < t->q0)
457 		t->q0 -= min(n, t->q0-q0);
458 	if(q0 < t->q1)
459 		t->q1 -= min(n, t->q1-q0);
460 	if(q1 <= t->org)
461 		t->org -= n;
462 	else if(q0 < t->org+t->nchars){
463 		p1 = q1 - t->org;
464 		if(p1 > t->nchars)
465 			p1 = t->nchars;
466 		if(q0 < t->org){
467 			t->org = q0;
468 			p0 = 0;
469 		}else
470 			p0 = q0 - t->org;
471 		frdelete(t, p0, p1);
472 		textfill(t);
473 	}
474 	if(t->w){
475 		c = 'd';
476 		if(t->what == Body)
477 			c = 'D';
478 		winevent(t->w, "%c%d %d 0 0 \n", c, q0, q1);
479 	}
480 }
481 
482 void
483 textconstrain(Text *t, uint q0, uint q1, uint *p0, uint *p1)
484 {
485 	*p0 = min(q0, t->file->nc);
486 	*p1 = min(q1, t->file->nc);
487 }
488 
489 Rune
490 textreadc(Text *t, uint q)
491 {
492 	Rune r;
493 
494 	if(t->cq0<=q && q<t->cq0+t->ncache)
495 		r = t->cache[q-t->cq0];
496 	else
497 		bufread(t->file, q, &r, 1);
498 	return r;
499 }
500 
501 int
502 textbswidth(Text *t, Rune c)
503 {
504 	uint q, eq;
505 	Rune r;
506 	int skipping;
507 
508 	/* there is known to be at least one character to erase */
509 	if(c == 0x08)	/* ^H: erase character */
510 		return 1;
511 	q = t->q0;
512 	skipping = TRUE;
513 	while(q > 0){
514 		r = textreadc(t, q-1);
515 		if(r == '\n'){		/* eat at most one more character */
516 			if(q == t->q0)	/* eat the newline */
517 				--q;
518 			break;
519 		}
520 		if(c == 0x17){
521 			eq = isalnum(r);
522 			if(eq && skipping)	/* found one; stop skipping */
523 				skipping = FALSE;
524 			else if(!eq && !skipping)
525 				break;
526 		}
527 		--q;
528 	}
529 	return t->q0-q;
530 }
531 
532 int
533 textfilewidth(Text *t, uint q0, int oneelement)
534 {
535 	uint q;
536 	Rune r;
537 
538 	q = q0;
539 	while(q > 0){
540 		r = textreadc(t, q-1);
541 		if(r <= ' ')
542 			break;
543 		if(oneelement && r=='/')
544 			break;
545 		--q;
546 	}
547 	return q0-q;
548 }
549 
550 Rune*
551 textcomplete(Text *t)
552 {
553 	int i, nstr, npath;
554 	uint q;
555 	Rune tmp[200];
556 	Rune *str, *path;
557 	Rune *rp;
558 	Completion *c;
559 	char *s, *dirs;
560 	Runestr dir;
561 
562 	/* control-f: filename completion; works back to white space or / */
563 	if(t->q0<t->file->nc && textreadc(t, t->q0)>' ')	/* must be at end of word */
564 		return nil;
565 	nstr = textfilewidth(t, t->q0, TRUE);
566 	str = runemalloc(nstr);
567 	npath = textfilewidth(t, t->q0-nstr, FALSE);
568 	path = runemalloc(npath);
569 
570 	c = nil;
571 	rp = nil;
572 	dirs = nil;
573 
574 	q = t->q0-nstr;
575 	for(i=0; i<nstr; i++)
576 		str[i] = textreadc(t, q++);
577 	q = t->q0-nstr-npath;
578 	for(i=0; i<npath; i++)
579 		path[i] = textreadc(t, q++);
580 	/* is path rooted? if not, we need to make it relative to window path */
581 	if(npath>0 && path[0]=='/')
582 		dir = (Runestr){path, npath};
583 	else{
584 		dir = dirname(t, nil, 0);
585 		if(dir.nr + 1 + npath > nelem(tmp)){
586 			free(dir.r);
587 			goto Return;
588 		}
589 		if(dir.nr == 0){
590 			dir.nr = 1;
591 			dir.r = runestrdup(L".");
592 		}
593 		runemove(tmp, dir.r, dir.nr);
594 		tmp[dir.nr] = '/';
595 		runemove(tmp+dir.nr+1, path, npath);
596 		free(dir.r);
597 		dir.r = tmp;
598 		dir.nr += 1+npath;
599 		dir = cleanrname(dir);
600 	}
601 
602 	s = smprint("%.*S", nstr, str);
603 	dirs = smprint("%.*S", dir.nr, dir.r);
604 	c = complete(dirs, s);
605 	free(s);
606 	if(c == nil){
607 		warning(nil, "error attempting completion: %r\n");
608 		goto Return;
609 	}
610 
611 	if(!c->advance){
612 		warning(nil, "%.*S%s%.*S*%s\n",
613 			dir.nr, dir.r,
614 			dir.nr>0 && dir.r[dir.nr-1]!='/' ? "/" : "",
615 			nstr, str,
616 			c->nmatch? "" : ": no matches in:");
617 		for(i=0; i<c->nfile; i++)
618 			warning(nil, " %s\n", c->filename[i]);
619 	}
620 
621 	if(c->advance)
622 		rp = runesmprint("%s", c->string);
623 	else
624 		rp = nil;
625   Return:
626 	freecompletion(c);
627 	free(dirs);
628 	free(str);
629 	free(path);
630 	return rp;
631 }
632 
633 void
634 texttype(Text *t, Rune r)
635 {
636 	uint q0, q1;
637 	int nnb, nb, n, i;
638 	int nr;
639 	Rune *rp;
640 	Text *u;
641 
642 	if(t->what!=Body && r=='\n')
643 		return;
644 	nr = 1;
645 	rp = &r;
646 	switch(r){
647 	case Kleft:
648 		if(t->q0 > 0){
649 			textcommit(t, TRUE);
650 			textshow(t, t->q0-1, t->q0-1, TRUE);
651 		}
652 		return;
653 	case Kright:
654 		if(t->q1 < t->file->nc){
655 			textcommit(t, TRUE);
656 			textshow(t, t->q1+1, t->q1+1, TRUE);
657 		}
658 		return;
659 	case Kdown:
660 		n = t->maxlines/3;
661 		goto case_Down;
662 	case Kpgdown:
663 		n = 2*t->maxlines/3;
664 	case_Down:
665 		q0 = t->org+frcharofpt(t, Pt(t->r.min.x, t->r.min.y+n*t->font->height));
666 		textsetorigin(t, q0, FALSE);
667 		return;
668 	case Kup:
669 		n = t->maxlines/3;
670 		goto case_Up;
671 	case Kpgup:
672 		n = 2*t->maxlines/3;
673 	case_Up:
674 		q0 = textbacknl(t, t->org, n);
675 		textsetorigin(t, q0, FALSE);
676 		return;
677 	case Khome:
678 		textshow(t, 0, 0, FALSE);
679 		return;
680 	case Kend:
681 		if(t->w)
682 			wincommit(t->w, t);
683 		else
684 			textcommit(t, TRUE);
685 		textshow(t, t->file->nc, t->file->nc, FALSE);
686 		return;
687 	}
688 	if(t->what == Body){
689 		seq++;
690 		filemark(t->file);
691 	}
692 	if(t->q1 > t->q0){
693 		if(t->ncache != 0)
694 			error("text.type");
695 		cut(t, t, nil, TRUE, TRUE, nil, 0);
696 		t->eq0 = ~0;
697 	}
698 	textshow(t, t->q0, t->q0, 1);
699 	switch(r){
700 	case 0x06:
701 	case Kins:
702 		rp = textcomplete(t);
703 		if(rp == nil)
704 			return;
705 		nr = runestrlen(rp);
706 		break;	/* fall through to normal insertion case */
707 	case 0x1B:
708 		if(t->eq0 != ~0)
709 			textsetselect(t, t->eq0, t->q0);
710 		if(t->ncache > 0){
711 			if(t->w != nil)
712 				wincommit(t->w, t);
713 			else
714 				textcommit(t, TRUE);
715 		}
716 		return;
717 	case 0x08:	/* ^H: erase character */
718 	case 0x15:	/* ^U: erase line */
719 	case 0x17:	/* ^W: erase word */
720 		if(t->q0 == 0)	/* nothing to erase */
721 			return;
722 		nnb = textbswidth(t, r);
723 		q1 = t->q0;
724 		q0 = q1-nnb;
725 		/* if selection is at beginning of window, avoid deleting invisible text */
726 		if(q0 < t->org){
727 			q0 = t->org;
728 			nnb = q1-q0;
729 		}
730 		if(nnb <= 0)
731 			return;
732 		for(i=0; i<t->file->ntext; i++){
733 			u = t->file->text[i];
734 			u->nofill = TRUE;
735 			nb = nnb;
736 			n = u->ncache;
737 			if(n > 0){
738 				if(q1 != u->cq0+n)
739 					error("text.type backspace");
740 				if(n > nb)
741 					n = nb;
742 				u->ncache -= n;
743 				textdelete(u, q1-n, q1, FALSE);
744 				nb -= n;
745 			}
746 			if(u->eq0==q1 || u->eq0==~0)
747 				u->eq0 = q0;
748 			if(nb && u==t)
749 				textdelete(u, q0, q0+nb, TRUE);
750 			if(u != t)
751 				textsetselect(u, u->q0, u->q1);
752 			else
753 				textsetselect(t, q0, q0);
754 			u->nofill = FALSE;
755 		}
756 		for(i=0; i<t->file->ntext; i++)
757 			textfill(t->file->text[i]);
758 		return;
759 	case '\n':
760 		if(t->w->autoindent){
761 			/* find beginning of previous line using backspace code */
762 			nnb = textbswidth(t, 0x15); /* ^U case */
763 			rp = runemalloc(nnb + 1);
764 			nr = 0;
765 			rp[nr++] = r;
766 			for(i=0; i<nnb; i++){
767 				r = textreadc(t, t->q0-nnb+i);
768 				if(r != ' ' && r != '\t')
769 					break;
770 				rp[nr++] = r;
771 			}
772 		}
773 		break; /* fall through to normal code */
774 	}
775 	/* otherwise ordinary character; just insert, typically in caches of all texts */
776 	for(i=0; i<t->file->ntext; i++){
777 		u = t->file->text[i];
778 		if(u->eq0 == ~0)
779 			u->eq0 = t->q0;
780 		if(u->ncache == 0)
781 			u->cq0 = t->q0;
782 		else if(t->q0 != u->cq0+u->ncache)
783 			error("text.type cq1");
784 		textinsert(u, t->q0, rp, nr, FALSE);
785 		if(u != t)
786 			textsetselect(u, u->q0, u->q1);
787 		if(u->ncache+nr > u->ncachealloc){
788 			u->ncachealloc += 10 + nr;
789 			u->cache = runerealloc(u->cache, u->ncachealloc);
790 		}
791 		runemove(u->cache+u->ncache, rp, nr);
792 		u->ncache += nr;
793 	}
794 	if(rp != &r)
795 		free(rp);
796 	textsetselect(t, t->q0+nr, t->q0+nr);
797 	if(r=='\n' && t->w!=nil)
798 		wincommit(t->w, t);
799 }
800 
801 void
802 textcommit(Text *t, int tofile)
803 {
804 	if(t->ncache == 0)
805 		return;
806 	if(tofile)
807 		fileinsert(t->file, t->cq0, t->cache, t->ncache);
808 	if(t->what == Body){
809 		t->w->dirty = TRUE;
810 		t->w->utflastqid = -1;
811 	}
812 	t->ncache = 0;
813 }
814 
815 static	Text	*clicktext;
816 static	uint	clickmsec;
817 static	Text	*selecttext;
818 static	uint	selectq;
819 
820 /*
821  * called from frame library
822  */
823 void
824 framescroll(Frame *f, int dl)
825 {
826 	if(f != &selecttext->Frame)
827 		error("frameselect not right frame");
828 	textframescroll(selecttext, dl);
829 }
830 
831 void
832 textframescroll(Text *t, int dl)
833 {
834 	uint q0;
835 
836 	if(dl == 0){
837 		scrsleep(100);
838 		return;
839 	}
840 	if(dl < 0){
841 		q0 = textbacknl(t, t->org, -dl);
842 		if(selectq > t->org+t->p0)
843 			textsetselect(t, t->org+t->p0, selectq);
844 		else
845 			textsetselect(t, selectq, t->org+t->p0);
846 	}else{
847 		if(t->org+t->nchars == t->file->nc)
848 			return;
849 		q0 = t->org+frcharofpt(t, Pt(t->r.min.x, t->r.min.y+dl*t->font->height));
850 		if(selectq > t->org+t->p1)
851 			textsetselect(t, t->org+t->p1, selectq);
852 		else
853 			textsetselect(t, selectq, t->org+t->p1);
854 	}
855 	textsetorigin(t, q0, TRUE);
856 }
857 
858 
859 void
860 textselect(Text *t)
861 {
862 	uint q0, q1;
863 	int b, x, y;
864 	int state, op;
865 
866 	selecttext = t;
867 	/*
868 	 * To have double-clicking and chording, we double-click
869 	 * immediately if it might make sense.
870 	 */
871 	b = mouse->buttons;
872 	q0 = t->q0;
873 	q1 = t->q1;
874 	selectq = t->org+frcharofpt(t, mouse->xy);
875 	if(clicktext==t && mouse->msec-clickmsec<500)
876 	if(q0==q1 && selectq==q0){
877 		textdoubleclick(t, &q0, &q1);
878 		textsetselect(t, q0, q1);
879 		flushimage(display, 1);
880 		x = mouse->xy.x;
881 		y = mouse->xy.y;
882 		/* stay here until something interesting happens */
883 		do
884 			readmouse(mousectl);
885 		while(mouse->buttons==b && abs(mouse->xy.x-x)<3 && abs(mouse->xy.y-y)<3);
886 		mouse->xy.x = x;	/* in case we're calling frselect */
887 		mouse->xy.y = y;
888 		q0 = t->q0;	/* may have changed */
889 		q1 = t->q1;
890 		selectq = q0;
891 	}
892 	if(mouse->buttons == b){
893 		t->Frame.scroll = framescroll;
894 		frselect(t, mousectl);
895 		/* horrible botch: while asleep, may have lost selection altogether */
896 		if(selectq > t->file->nc)
897 			selectq = t->org + t->p0;
898 		t->Frame.scroll = nil;
899 		if(selectq < t->org)
900 			q0 = selectq;
901 		else
902 			q0 = t->org + t->p0;
903 		if(selectq > t->org+t->nchars)
904 			q1 = selectq;
905 		else
906 			q1 = t->org+t->p1;
907 	}
908 	if(q0 == q1){
909 		if(q0==t->q0 && clicktext==t && mouse->msec-clickmsec<500){
910 			textdoubleclick(t, &q0, &q1);
911 			clicktext = nil;
912 		}else{
913 			clicktext = t;
914 			clickmsec = mouse->msec;
915 		}
916 	}else
917 		clicktext = nil;
918 	textsetselect(t, q0, q1);
919 	flushimage(display, 1);
920 	state = op = 0;	/* undo when possible; +1 for cut, -1 for paste */
921 	while(mouse->buttons){
922 		mouse->msec = 0;
923 		b = mouse->buttons;
924 		if(b & 6){
925 			if(state==0 && op==0 && t->what==Body){
926 				seq++;
927 				filemark(t->w->body.file);
928 			}
929 			if(b & 2){
930 				if(state==-1 && t->what==Body){
931 					winundo(t->w, TRUE);
932 					textsetselect(t, q0, t->q0);
933 					state = 0;
934 				}else if(state != 1 && op != -1){
935 					cut(t, t, nil, TRUE, TRUE, nil, 0);
936 					op = state = 1;
937 				}
938 			}else{
939 				if(state==1 && t->what==Body){
940 					winundo(t->w, TRUE);
941 					textsetselect(t, q0, t->q1);
942 					state = 0;
943 				}else if(state != -1 && op != 1){
944 					paste(t, t, nil, TRUE, FALSE, nil, 0);
945 					op = state = -1;
946 				}
947 			}
948 			textscrdraw(t);
949 			clearmouse();
950 		}
951 		flushimage(display, 1);
952 		while(mouse->buttons == b)
953 			readmouse(mousectl);
954 		clicktext = nil;
955 	}
956 }
957 
958 void
959 textshow(Text *t, uint q0, uint q1, int doselect)
960 {
961 	int qe;
962 	int nl;
963 	uint q;
964 
965 	if(t->what != Body)
966 		return;
967 	if(t->w!=nil && t->maxlines==0)
968 		colgrow(t->col, t->w, 1);
969 	if(doselect)
970 		textsetselect(t, q0, q1);
971 	qe = t->org+t->nchars;
972 	if(t->org<=q0 && (q0<qe || (q0==qe && qe==t->file->nc+t->ncache)))
973 		textscrdraw(t);
974 	else{
975 		if(t->w->nopen[QWevent] > 0)
976 			nl = 3*t->maxlines/4;
977 		else
978 			nl = t->maxlines/4;
979 		q = textbacknl(t, q0, nl);
980 		/* avoid going backwards if trying to go forwards - long lines! */
981 		if(!(q0>t->org && q<t->org))
982 			textsetorigin(t, q, TRUE);
983 		while(q0 > t->org+t->nchars)
984 			textsetorigin(t, t->org+1, FALSE);
985 	}
986 }
987 
988 static
989 int
990 region(int a, int b)
991 {
992 	if(a < b)
993 		return -1;
994 	if(a == b)
995 		return 0;
996 	return 1;
997 }
998 
999 void
1000 selrestore(Frame *f, Point pt0, uint p0, uint p1)
1001 {
1002 	if(p1<=f->p0 || p0>=f->p1){
1003 		/* no overlap */
1004 		frdrawsel0(f, pt0, p0, p1, f->cols[BACK], f->cols[TEXT]);
1005 		return;
1006 	}
1007 	if(p0>=f->p0 && p1<=f->p1){
1008 		/* entirely inside */
1009 		frdrawsel0(f, pt0, p0, p1, f->cols[HIGH], f->cols[HTEXT]);
1010 		return;
1011 	}
1012 
1013 	/* they now are known to overlap */
1014 
1015 	/* before selection */
1016 	if(p0 < f->p0){
1017 		frdrawsel0(f, pt0, p0, f->p0, f->cols[BACK], f->cols[TEXT]);
1018 		p0 = f->p0;
1019 		pt0 = frptofchar(f, p0);
1020 	}
1021 	/* after selection */
1022 	if(p1 > f->p1){
1023 		frdrawsel0(f, frptofchar(f, f->p1), f->p1, p1, f->cols[BACK], f->cols[TEXT]);
1024 		p1 = f->p1;
1025 	}
1026 	/* inside selection */
1027 	frdrawsel0(f, pt0, p0, p1, f->cols[HIGH], f->cols[HTEXT]);
1028 }
1029 
1030 void
1031 textsetselect(Text *t, uint q0, uint q1)
1032 {
1033 	int p0, p1;
1034 
1035 	/* t->p0 and t->p1 are always right; t->q0 and t->q1 may be off */
1036 	t->q0 = q0;
1037 	t->q1 = q1;
1038 	/* compute desired p0,p1 from q0,q1 */
1039 	p0 = q0-t->org;
1040 	p1 = q1-t->org;
1041 	if(p0 < 0)
1042 		p0 = 0;
1043 	if(p1 < 0)
1044 		p1 = 0;
1045 	if(p0 > t->nchars)
1046 		p0 = t->nchars;
1047 	if(p1 > t->nchars)
1048 		p1 = t->nchars;
1049 	if(p0==t->p0 && p1==t->p1)
1050 		return;
1051 	/* screen disagrees with desired selection */
1052 	if(t->p1<=p0 || p1<=t->p0 || p0==p1 || t->p1==t->p0){
1053 		/* no overlap or too easy to bother trying */
1054 		frdrawsel(t, frptofchar(t, t->p0), t->p0, t->p1, 0);
1055 		frdrawsel(t, frptofchar(t, p0), p0, p1, 1);
1056 		goto Return;
1057 	}
1058 	/* overlap; avoid unnecessary painting */
1059 	if(p0 < t->p0){
1060 		/* extend selection backwards */
1061 		frdrawsel(t, frptofchar(t, p0), p0, t->p0, 1);
1062 	}else if(p0 > t->p0){
1063 		/* trim first part of selection */
1064 		frdrawsel(t, frptofchar(t, t->p0), t->p0, p0, 0);
1065 	}
1066 	if(p1 > t->p1){
1067 		/* extend selection forwards */
1068 		frdrawsel(t, frptofchar(t, t->p1), t->p1, p1, 1);
1069 	}else if(p1 < t->p1){
1070 		/* trim last part of selection */
1071 		frdrawsel(t, frptofchar(t, p1), p1, t->p1, 0);
1072 	}
1073 
1074     Return:
1075 	t->p0 = p0;
1076 	t->p1 = p1;
1077 }
1078 
1079 /*
1080  * Release the button in less than DELAY ms and it's considered a null selection
1081  * if the mouse hardly moved, regardless of whether it crossed a char boundary.
1082  */
1083 enum {
1084 	DELAY = 2,
1085 	MINMOVE = 4,
1086 };
1087 
1088 uint
1089 xselect(Frame *f, Mousectl *mc, Image *col, uint *p1p)	/* when called, button is down */
1090 {
1091 	uint p0, p1, q, tmp;
1092 	ulong msec;
1093 	Point mp, pt0, pt1, qt;
1094 	int reg, b;
1095 
1096 	mp = mc->xy;
1097 	b = mc->buttons;
1098 	msec = mc->msec;
1099 
1100 	/* remove tick */
1101 	if(f->p0 == f->p1)
1102 		frtick(f, frptofchar(f, f->p0), 0);
1103 	p0 = p1 = frcharofpt(f, mp);
1104 	pt0 = frptofchar(f, p0);
1105 	pt1 = frptofchar(f, p1);
1106 	reg = 0;
1107 	frtick(f, pt0, 1);
1108 	do{
1109 		q = frcharofpt(f, mc->xy);
1110 		if(p1 != q){
1111 			if(p0 == p1)
1112 				frtick(f, pt0, 0);
1113 			if(reg != region(q, p0)){	/* crossed starting point; reset */
1114 				if(reg > 0)
1115 					selrestore(f, pt0, p0, p1);
1116 				else if(reg < 0)
1117 					selrestore(f, pt1, p1, p0);
1118 				p1 = p0;
1119 				pt1 = pt0;
1120 				reg = region(q, p0);
1121 				if(reg == 0)
1122 					frdrawsel0(f, pt0, p0, p1, col, display->white);
1123 			}
1124 			qt = frptofchar(f, q);
1125 			if(reg > 0){
1126 				if(q > p1)
1127 					frdrawsel0(f, pt1, p1, q, col, display->white);
1128 
1129 				else if(q < p1)
1130 					selrestore(f, qt, q, p1);
1131 			}else if(reg < 0){
1132 				if(q > p1)
1133 					selrestore(f, pt1, p1, q);
1134 				else
1135 					frdrawsel0(f, qt, q, p1, col, display->white);
1136 			}
1137 			p1 = q;
1138 			pt1 = qt;
1139 		}
1140 		if(p0 == p1)
1141 			frtick(f, pt0, 1);
1142 		flushimage(f->display, 1);
1143 		readmouse(mc);
1144 	}while(mc->buttons == b);
1145 	if(mc->msec-msec < DELAY && p0!=p1
1146 	&& abs(mp.x-mc->xy.x)<MINMOVE
1147 	&& abs(mp.y-mc->xy.y)<MINMOVE) {
1148 		if(reg > 0)
1149 			selrestore(f, pt0, p0, p1);
1150 		else if(reg < 0)
1151 			selrestore(f, pt1, p1, p0);
1152 		p1 = p0;
1153 	}
1154 	if(p1 < p0){
1155 		tmp = p0;
1156 		p0 = p1;
1157 		p1 = tmp;
1158 	}
1159 	pt0 = frptofchar(f, p0);
1160 	if(p0 == p1)
1161 		frtick(f, pt0, 0);
1162 	selrestore(f, pt0, p0, p1);
1163 	/* restore tick */
1164 	if(f->p0 == f->p1)
1165 		frtick(f, frptofchar(f, f->p0), 1);
1166 	flushimage(f->display, 1);
1167 	*p1p = p1;
1168 	return p0;
1169 }
1170 
1171 int
1172 textselect23(Text *t, uint *q0, uint *q1, Image *high, int mask)
1173 {
1174 	uint p0, p1;
1175 	int buts;
1176 
1177 	p0 = xselect(t, mousectl, high, &p1);
1178 	buts = mousectl->buttons;
1179 	if((buts & mask) == 0){
1180 		*q0 = p0+t->org;
1181 		*q1 = p1+t->org;
1182 	}
1183 
1184 	while(mousectl->buttons)
1185 		readmouse(mousectl);
1186 	return buts;
1187 }
1188 
1189 int
1190 textselect2(Text *t, uint *q0, uint *q1, Text **tp)
1191 {
1192 	int buts;
1193 
1194 	*tp = nil;
1195 	buts = textselect23(t, q0, q1, but2col, 4);
1196 	if(buts & 4)
1197 		return 0;
1198 	if(buts & 1){	/* pick up argument */
1199 		*tp = argtext;
1200 		return 1;
1201 	}
1202 	return 1;
1203 }
1204 
1205 int
1206 textselect3(Text *t, uint *q0, uint *q1)
1207 {
1208 	int h;
1209 
1210 	h = (textselect23(t, q0, q1, but3col, 1|2) == 0);
1211 	return h;
1212 }
1213 
1214 static Rune left1[] =  { L'{', L'[', L'(', L'<', L'«', 0 };
1215 static Rune right1[] = { L'}', L']', L')', L'>', L'»', 0 };
1216 static Rune left2[] =  { L'\n', 0 };
1217 static Rune left3[] =  { L'\'', L'"', L'`', 0 };
1218 
1219 static
1220 Rune *left[] = {
1221 	left1,
1222 	left2,
1223 	left3,
1224 	nil
1225 };
1226 static
1227 Rune *right[] = {
1228 	right1,
1229 	left2,
1230 	left3,
1231 	nil
1232 };
1233 
1234 void
1235 textdoubleclick(Text *t, uint *q0, uint *q1)
1236 {
1237 	int c, i;
1238 	Rune *r, *l, *p;
1239 	uint q;
1240 
1241 	for(i=0; left[i]!=nil; i++){
1242 		q = *q0;
1243 		l = left[i];
1244 		r = right[i];
1245 		/* try matching character to left, looking right */
1246 		if(q == 0)
1247 			c = '\n';
1248 		else
1249 			c = textreadc(t, q-1);
1250 		p = runestrchr(l, c);
1251 		if(p != nil){
1252 			if(textclickmatch(t, c, r[p-l], 1, &q))
1253 				*q1 = q-(c!='\n');
1254 			return;
1255 		}
1256 		/* try matching character to right, looking left */
1257 		if(q == t->file->nc)
1258 			c = '\n';
1259 		else
1260 			c = textreadc(t, q);
1261 		p = runestrchr(r, c);
1262 		if(p != nil){
1263 			if(textclickmatch(t, c, l[p-r], -1, &q)){
1264 				*q1 = *q0+(*q0<t->file->nc && c=='\n');
1265 				*q0 = q;
1266 				if(c!='\n' || q!=0 || textreadc(t, 0)=='\n')
1267 					(*q0)++;
1268 			}
1269 			return;
1270 		}
1271 	}
1272 	/* try filling out word to right */
1273 	while(*q1<t->file->nc && isalnum(textreadc(t, *q1)))
1274 		(*q1)++;
1275 	/* try filling out word to left */
1276 	while(*q0>0 && isalnum(textreadc(t, *q0-1)))
1277 		(*q0)--;
1278 }
1279 
1280 int
1281 textclickmatch(Text *t, int cl, int cr, int dir, uint *q)
1282 {
1283 	Rune c;
1284 	int nest;
1285 
1286 	nest = 1;
1287 	for(;;){
1288 		if(dir > 0){
1289 			if(*q == t->file->nc)
1290 				break;
1291 			c = textreadc(t, *q);
1292 			(*q)++;
1293 		}else{
1294 			if(*q == 0)
1295 				break;
1296 			(*q)--;
1297 			c = textreadc(t, *q);
1298 		}
1299 		if(c == cr){
1300 			if(--nest==0)
1301 				return 1;
1302 		}else if(c == cl)
1303 			nest++;
1304 	}
1305 	return cl=='\n' && nest==1;
1306 }
1307 
1308 uint
1309 textbacknl(Text *t, uint p, uint n)
1310 {
1311 	int i, j;
1312 
1313 	/* look for start of this line if n==0 */
1314 	if(n==0 && p>0 && textreadc(t, p-1)!='\n')
1315 		n = 1;
1316 	i = n;
1317 	while(i-->0 && p>0){
1318 		--p;	/* it's at a newline now; back over it */
1319 		if(p == 0)
1320 			break;
1321 		/* at 128 chars, call it a line anyway */
1322 		for(j=128; --j>0 && p>0; p--)
1323 			if(textreadc(t, p-1)=='\n')
1324 				break;
1325 	}
1326 	return p;
1327 }
1328 
1329 void
1330 textsetorigin(Text *t, uint org, int exact)
1331 {
1332 	int i, a, fixup;
1333 	Rune *r;
1334 	uint n;
1335 
1336 	if(org>0 && !exact){
1337 		/* org is an estimate of the char posn; find a newline */
1338 		/* don't try harder than 256 chars */
1339 		for(i=0; i<256 && org<t->file->nc; i++){
1340 			if(textreadc(t, org) == '\n'){
1341 				org++;
1342 				break;
1343 			}
1344 			org++;
1345 		}
1346 	}
1347 	a = org-t->org;
1348 	fixup = 0;
1349 	if(a>=0 && a<t->nchars){
1350 		frdelete(t, 0, a);
1351 		fixup = 1;	/* frdelete can leave end of last line in wrong selection mode; it doesn't know what follows */
1352 	}
1353 	else if(a<0 && -a<t->nchars){
1354 		n = t->org - org;
1355 		r = runemalloc(n);
1356 		bufread(t->file, org, r, n);
1357 		frinsert(t, r, r+n, 0);
1358 		free(r);
1359 	}else
1360 		frdelete(t, 0, t->nchars);
1361 	t->org = org;
1362 	textfill(t);
1363 	textscrdraw(t);
1364 	textsetselect(t, t->q0, t->q1);
1365 	if(fixup && t->p1 > t->p0)
1366 		frdrawsel(t, frptofchar(t, t->p1-1), t->p1-1, t->p1, 1);
1367 }
1368 
1369 void
1370 textreset(Text *t)
1371 {
1372 	t->file->seq = 0;
1373 	t->eq0 = ~0;
1374 	/* do t->delete(0, t->nc, TRUE) without building backup stuff */
1375 	textsetselect(t, t->org, t->org);
1376 	frdelete(t, 0, t->nchars);
1377 	t->org = 0;
1378 	t->q0 = 0;
1379 	t->q1 = 0;
1380 	filereset(t->file);
1381 	bufreset(t->file);
1382 }
1383