xref: /plan9/sys/src/cmd/acme/text.c (revision 282e677fa45fb578cdb8bc2c412ac084c367776e)
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 		if(doselect)
967 			textsetselect(t, q0, q1);
968 		return;
969 	}
970 	if(t->w!=nil && t->maxlines==0)
971 		colgrow(t->col, t->w, 1);
972 	if(doselect)
973 		textsetselect(t, q0, q1);
974 	qe = t->org+t->nchars;
975 	if(t->org<=q0 && (q0<qe || (q0==qe && qe==t->file->nc+t->ncache)))
976 		textscrdraw(t);
977 	else{
978 		if(t->w->nopen[QWevent] > 0)
979 			nl = 3*t->maxlines/4;
980 		else
981 			nl = t->maxlines/4;
982 		q = textbacknl(t, q0, nl);
983 		/* avoid going backwards if trying to go forwards - long lines! */
984 		if(!(q0>t->org && q<t->org))
985 			textsetorigin(t, q, TRUE);
986 		while(q0 > t->org+t->nchars)
987 			textsetorigin(t, t->org+1, FALSE);
988 	}
989 }
990 
991 static
992 int
993 region(int a, int b)
994 {
995 	if(a < b)
996 		return -1;
997 	if(a == b)
998 		return 0;
999 	return 1;
1000 }
1001 
1002 void
1003 selrestore(Frame *f, Point pt0, uint p0, uint p1)
1004 {
1005 	if(p1<=f->p0 || p0>=f->p1){
1006 		/* no overlap */
1007 		frdrawsel0(f, pt0, p0, p1, f->cols[BACK], f->cols[TEXT]);
1008 		return;
1009 	}
1010 	if(p0>=f->p0 && p1<=f->p1){
1011 		/* entirely inside */
1012 		frdrawsel0(f, pt0, p0, p1, f->cols[HIGH], f->cols[HTEXT]);
1013 		return;
1014 	}
1015 
1016 	/* they now are known to overlap */
1017 
1018 	/* before selection */
1019 	if(p0 < f->p0){
1020 		frdrawsel0(f, pt0, p0, f->p0, f->cols[BACK], f->cols[TEXT]);
1021 		p0 = f->p0;
1022 		pt0 = frptofchar(f, p0);
1023 	}
1024 	/* after selection */
1025 	if(p1 > f->p1){
1026 		frdrawsel0(f, frptofchar(f, f->p1), f->p1, p1, f->cols[BACK], f->cols[TEXT]);
1027 		p1 = f->p1;
1028 	}
1029 	/* inside selection */
1030 	frdrawsel0(f, pt0, p0, p1, f->cols[HIGH], f->cols[HTEXT]);
1031 }
1032 
1033 void
1034 textsetselect(Text *t, uint q0, uint q1)
1035 {
1036 	int p0, p1;
1037 
1038 	/* t->p0 and t->p1 are always right; t->q0 and t->q1 may be off */
1039 	t->q0 = q0;
1040 	t->q1 = q1;
1041 	/* compute desired p0,p1 from q0,q1 */
1042 	p0 = q0-t->org;
1043 	p1 = q1-t->org;
1044 	if(p0 < 0)
1045 		p0 = 0;
1046 	if(p1 < 0)
1047 		p1 = 0;
1048 	if(p0 > t->nchars)
1049 		p0 = t->nchars;
1050 	if(p1 > t->nchars)
1051 		p1 = t->nchars;
1052 	if(p0==t->p0 && p1==t->p1)
1053 		return;
1054 	/* screen disagrees with desired selection */
1055 	if(t->p1<=p0 || p1<=t->p0 || p0==p1 || t->p1==t->p0){
1056 		/* no overlap or too easy to bother trying */
1057 		frdrawsel(t, frptofchar(t, t->p0), t->p0, t->p1, 0);
1058 		frdrawsel(t, frptofchar(t, p0), p0, p1, 1);
1059 		goto Return;
1060 	}
1061 	/* overlap; avoid unnecessary painting */
1062 	if(p0 < t->p0){
1063 		/* extend selection backwards */
1064 		frdrawsel(t, frptofchar(t, p0), p0, t->p0, 1);
1065 	}else if(p0 > t->p0){
1066 		/* trim first part of selection */
1067 		frdrawsel(t, frptofchar(t, t->p0), t->p0, p0, 0);
1068 	}
1069 	if(p1 > t->p1){
1070 		/* extend selection forwards */
1071 		frdrawsel(t, frptofchar(t, t->p1), t->p1, p1, 1);
1072 	}else if(p1 < t->p1){
1073 		/* trim last part of selection */
1074 		frdrawsel(t, frptofchar(t, p1), p1, t->p1, 0);
1075 	}
1076 
1077     Return:
1078 	t->p0 = p0;
1079 	t->p1 = p1;
1080 }
1081 
1082 /*
1083  * Release the button in less than DELAY ms and it's considered a null selection
1084  * if the mouse hardly moved, regardless of whether it crossed a char boundary.
1085  */
1086 enum {
1087 	DELAY = 2,
1088 	MINMOVE = 4,
1089 };
1090 
1091 uint
1092 xselect(Frame *f, Mousectl *mc, Image *col, uint *p1p)	/* when called, button is down */
1093 {
1094 	uint p0, p1, q, tmp;
1095 	ulong msec;
1096 	Point mp, pt0, pt1, qt;
1097 	int reg, b;
1098 
1099 	mp = mc->xy;
1100 	b = mc->buttons;
1101 	msec = mc->msec;
1102 
1103 	/* remove tick */
1104 	if(f->p0 == f->p1)
1105 		frtick(f, frptofchar(f, f->p0), 0);
1106 	p0 = p1 = frcharofpt(f, mp);
1107 	pt0 = frptofchar(f, p0);
1108 	pt1 = frptofchar(f, p1);
1109 	reg = 0;
1110 	frtick(f, pt0, 1);
1111 	do{
1112 		q = frcharofpt(f, mc->xy);
1113 		if(p1 != q){
1114 			if(p0 == p1)
1115 				frtick(f, pt0, 0);
1116 			if(reg != region(q, p0)){	/* crossed starting point; reset */
1117 				if(reg > 0)
1118 					selrestore(f, pt0, p0, p1);
1119 				else if(reg < 0)
1120 					selrestore(f, pt1, p1, p0);
1121 				p1 = p0;
1122 				pt1 = pt0;
1123 				reg = region(q, p0);
1124 				if(reg == 0)
1125 					frdrawsel0(f, pt0, p0, p1, col, display->white);
1126 			}
1127 			qt = frptofchar(f, q);
1128 			if(reg > 0){
1129 				if(q > p1)
1130 					frdrawsel0(f, pt1, p1, q, col, display->white);
1131 
1132 				else if(q < p1)
1133 					selrestore(f, qt, q, p1);
1134 			}else if(reg < 0){
1135 				if(q > p1)
1136 					selrestore(f, pt1, p1, q);
1137 				else
1138 					frdrawsel0(f, qt, q, p1, col, display->white);
1139 			}
1140 			p1 = q;
1141 			pt1 = qt;
1142 		}
1143 		if(p0 == p1)
1144 			frtick(f, pt0, 1);
1145 		flushimage(f->display, 1);
1146 		readmouse(mc);
1147 	}while(mc->buttons == b);
1148 	if(mc->msec-msec < DELAY && p0!=p1
1149 	&& abs(mp.x-mc->xy.x)<MINMOVE
1150 	&& abs(mp.y-mc->xy.y)<MINMOVE) {
1151 		if(reg > 0)
1152 			selrestore(f, pt0, p0, p1);
1153 		else if(reg < 0)
1154 			selrestore(f, pt1, p1, p0);
1155 		p1 = p0;
1156 	}
1157 	if(p1 < p0){
1158 		tmp = p0;
1159 		p0 = p1;
1160 		p1 = tmp;
1161 	}
1162 	pt0 = frptofchar(f, p0);
1163 	if(p0 == p1)
1164 		frtick(f, pt0, 0);
1165 	selrestore(f, pt0, p0, p1);
1166 	/* restore tick */
1167 	if(f->p0 == f->p1)
1168 		frtick(f, frptofchar(f, f->p0), 1);
1169 	flushimage(f->display, 1);
1170 	*p1p = p1;
1171 	return p0;
1172 }
1173 
1174 int
1175 textselect23(Text *t, uint *q0, uint *q1, Image *high, int mask)
1176 {
1177 	uint p0, p1;
1178 	int buts;
1179 
1180 	p0 = xselect(t, mousectl, high, &p1);
1181 	buts = mousectl->buttons;
1182 	if((buts & mask) == 0){
1183 		*q0 = p0+t->org;
1184 		*q1 = p1+t->org;
1185 	}
1186 
1187 	while(mousectl->buttons)
1188 		readmouse(mousectl);
1189 	return buts;
1190 }
1191 
1192 int
1193 textselect2(Text *t, uint *q0, uint *q1, Text **tp)
1194 {
1195 	int buts;
1196 
1197 	*tp = nil;
1198 	buts = textselect23(t, q0, q1, but2col, 4);
1199 	if(buts & 4)
1200 		return 0;
1201 	if(buts & 1){	/* pick up argument */
1202 		*tp = argtext;
1203 		return 1;
1204 	}
1205 	return 1;
1206 }
1207 
1208 int
1209 textselect3(Text *t, uint *q0, uint *q1)
1210 {
1211 	int h;
1212 
1213 	h = (textselect23(t, q0, q1, but3col, 1|2) == 0);
1214 	return h;
1215 }
1216 
1217 static Rune left1[] =  { L'{', L'[', L'(', L'<', L'«', 0 };
1218 static Rune right1[] = { L'}', L']', L')', L'>', L'»', 0 };
1219 static Rune left2[] =  { L'\n', 0 };
1220 static Rune left3[] =  { L'\'', L'"', L'`', 0 };
1221 
1222 static
1223 Rune *left[] = {
1224 	left1,
1225 	left2,
1226 	left3,
1227 	nil
1228 };
1229 static
1230 Rune *right[] = {
1231 	right1,
1232 	left2,
1233 	left3,
1234 	nil
1235 };
1236 
1237 void
1238 textdoubleclick(Text *t, uint *q0, uint *q1)
1239 {
1240 	int c, i;
1241 	Rune *r, *l, *p;
1242 	uint q;
1243 
1244 	for(i=0; left[i]!=nil; i++){
1245 		q = *q0;
1246 		l = left[i];
1247 		r = right[i];
1248 		/* try matching character to left, looking right */
1249 		if(q == 0)
1250 			c = '\n';
1251 		else
1252 			c = textreadc(t, q-1);
1253 		p = runestrchr(l, c);
1254 		if(p != nil){
1255 			if(textclickmatch(t, c, r[p-l], 1, &q))
1256 				*q1 = q-(c!='\n');
1257 			return;
1258 		}
1259 		/* try matching character to right, looking left */
1260 		if(q == t->file->nc)
1261 			c = '\n';
1262 		else
1263 			c = textreadc(t, q);
1264 		p = runestrchr(r, c);
1265 		if(p != nil){
1266 			if(textclickmatch(t, c, l[p-r], -1, &q)){
1267 				*q1 = *q0+(*q0<t->file->nc && c=='\n');
1268 				*q0 = q;
1269 				if(c!='\n' || q!=0 || textreadc(t, 0)=='\n')
1270 					(*q0)++;
1271 			}
1272 			return;
1273 		}
1274 	}
1275 	/* try filling out word to right */
1276 	while(*q1<t->file->nc && isalnum(textreadc(t, *q1)))
1277 		(*q1)++;
1278 	/* try filling out word to left */
1279 	while(*q0>0 && isalnum(textreadc(t, *q0-1)))
1280 		(*q0)--;
1281 }
1282 
1283 int
1284 textclickmatch(Text *t, int cl, int cr, int dir, uint *q)
1285 {
1286 	Rune c;
1287 	int nest;
1288 
1289 	nest = 1;
1290 	for(;;){
1291 		if(dir > 0){
1292 			if(*q == t->file->nc)
1293 				break;
1294 			c = textreadc(t, *q);
1295 			(*q)++;
1296 		}else{
1297 			if(*q == 0)
1298 				break;
1299 			(*q)--;
1300 			c = textreadc(t, *q);
1301 		}
1302 		if(c == cr){
1303 			if(--nest==0)
1304 				return 1;
1305 		}else if(c == cl)
1306 			nest++;
1307 	}
1308 	return cl=='\n' && nest==1;
1309 }
1310 
1311 uint
1312 textbacknl(Text *t, uint p, uint n)
1313 {
1314 	int i, j;
1315 
1316 	/* look for start of this line if n==0 */
1317 	if(n==0 && p>0 && textreadc(t, p-1)!='\n')
1318 		n = 1;
1319 	i = n;
1320 	while(i-->0 && p>0){
1321 		--p;	/* it's at a newline now; back over it */
1322 		if(p == 0)
1323 			break;
1324 		/* at 128 chars, call it a line anyway */
1325 		for(j=128; --j>0 && p>0; p--)
1326 			if(textreadc(t, p-1)=='\n')
1327 				break;
1328 	}
1329 	return p;
1330 }
1331 
1332 void
1333 textsetorigin(Text *t, uint org, int exact)
1334 {
1335 	int i, a, fixup;
1336 	Rune *r;
1337 	uint n;
1338 
1339 	if(org>0 && !exact){
1340 		/* org is an estimate of the char posn; find a newline */
1341 		/* don't try harder than 256 chars */
1342 		for(i=0; i<256 && org<t->file->nc; i++){
1343 			if(textreadc(t, org) == '\n'){
1344 				org++;
1345 				break;
1346 			}
1347 			org++;
1348 		}
1349 	}
1350 	a = org-t->org;
1351 	fixup = 0;
1352 	if(a>=0 && a<t->nchars){
1353 		frdelete(t, 0, a);
1354 		fixup = 1;	/* frdelete can leave end of last line in wrong selection mode; it doesn't know what follows */
1355 	}
1356 	else if(a<0 && -a<t->nchars){
1357 		n = t->org - org;
1358 		r = runemalloc(n);
1359 		bufread(t->file, org, r, n);
1360 		frinsert(t, r, r+n, 0);
1361 		free(r);
1362 	}else
1363 		frdelete(t, 0, t->nchars);
1364 	t->org = org;
1365 	textfill(t);
1366 	textscrdraw(t);
1367 	textsetselect(t, t->q0, t->q1);
1368 	if(fixup && t->p1 > t->p0)
1369 		frdrawsel(t, frptofchar(t, t->p1-1), t->p1-1, t->p1, 1);
1370 }
1371 
1372 void
1373 textreset(Text *t)
1374 {
1375 	t->file->seq = 0;
1376 	t->eq0 = ~0;
1377 	/* do t->delete(0, t->nc, TRUE) without building backup stuff */
1378 	textsetselect(t, t->org, t->org);
1379 	frdelete(t, 0, t->nchars);
1380 	t->org = 0;
1381 	t->q0 = 0;
1382 	t->q1 = 0;
1383 	filereset(t->file);
1384 	bufreset(t->file);
1385 }
1386