1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
#include "wily.h"
#include "text.h"
/***********************************************************
Functions to do with finding/counting lines.
Currently Wily doesn't keep track of line boundaries,
and searches for them when it needs to. These functions
are all in the one file in case we ever decide to cache any
of this information.
***********************************************************/
/* Rune position p is at what line number? */
int
text_linenumber(Text *t, ulong p) {
int c;
int newlines=1;
Tbgetcset(t, p);
while ( (c=Tbgetc(t)) != -1)
if( c == NEWLINE)
newlines++;
return newlines;
}
Range
text_lastline(Text *t) {
int c;
Tbgetcset(t, t->length);
while ( (c=Tbgetc(t)) != -1 && c != NEWLINE)
;
return range(t->pos+1, t->length);
}
/*
* If 't' has at least 'n' lines, fills 'r' with the range for line 'n',
* and returns true. Otherwise, fills 'r' with gibberish and returns
* false.
*/
Bool
text_findline(Text *t, Range *r, ulong n) {
Bool foundstart = false;
int c;
if (n==0)
return false;
else if (n==1) {
foundstart = true;
r->p0 = 0;
}
n--;
Tgetcset(t,0);
for( ; (c=Tgetc(t)) != -1; ) {
if( c == NEWLINE ) {
if (foundstart)
break;
else if (!--n) {
r->p0 = t->pos;
foundstart = true;
}
}
}
r->p1 = t->pos;
return foundstart;
}
/*
* Find the offset of the first character of the line 'delta' away from 'pos'.
*'delta' may be positive or negative.
*
* text_nl(t, pos, 0): start of current line
* text_nl(t, pos, -1): start of line above
* text_nl(t, pos, 1): start of line below
*/
ulong
text_nl(Text *t, ulong pos, int delta) {
int c;
ulong retval;
assert(pos <= t->length);
if(delta > 0) {
Tgetcset(t, pos);
while ( (c=Tgetc(t)) != -1 )
if(c==NEWLINE)
if(!--delta)
break;
} else {
Tbgetcset(t,pos);
while ( (c=Tbgetc(t)) != -1 )
if(c==NEWLINE)
if(!delta++)
break;
}
retval = t->pos;
if (!(retval == 0 || retval == t->length))
retval++;
return retval;
}
|