troff: use $$ for inline eqn
[ctxt.git] / txt.c
blob12e2ffb2ef11b59bb839fcb4baff0276541d1a04
1 #include <stdlib.h>
2 #include <string.h>
3 #include <unistd.h>
4 #include "ctxt.h"
5 #include "util.h"
7 static char *file_read(int fd)
9 int size = 1024;
10 char *buf = xmalloc(size);
11 int n = 0;
12 int c = 0;
13 while ((c = read(fd, buf + n, size - n)) > 0) {
14 n += c;
15 if (n == size) {
16 char *newbuf = xmalloc(size * 2);
17 memcpy(newbuf, buf, n);
18 free(buf);
19 buf = newbuf;
20 size *= 2;
23 return buf;
26 static int newlines(char *s)
28 int i;
29 for (i = 0; (s = strchr(s, '\n')); i++, s++);
30 return i;
33 static void initlines(struct txt *txt)
35 int i;
36 txt->lines[0] = txt->txt;
37 for (i = 1; i <= txt->n; i++) {
38 char *s = strchr(txt->lines[i - 1], '\n');
39 if (s)
40 *s = '\0';
41 if (i < txt->n)
42 txt->lines[i] = s + 1;
46 struct txt *txt_alloc(int fd)
48 struct txt *txt = xmalloc(sizeof(struct txt));
49 txt->txt = file_read(fd);
50 txt->n = newlines(txt->txt);
51 txt->lines = xmalloc(sizeof(*txt->lines) * txt->n);
52 initlines(txt);
53 return txt;
56 char *txt_line(struct txt *txt, int line)
58 if (line < txt->n)
59 return txt->lines[line];
60 return NULL;
63 void txt_free(struct txt *txt)
65 free(txt->lines);
66 free(txt->txt);