ctxt: introduce an escape character to prevent unwanted markups
[ctxt.git] / txt.c
blob3fc94deffd7c58021eac0e31273b5a1f9a4bed05
1 #include <stdlib.h>
2 #include <string.h>
3 #include <unistd.h>
4 #include "ctxt.h"
6 static char *file_read(int fd)
8 int size = 1024;
9 char *buf = xmalloc(size);
10 int n = 0;
11 int c = 0;
12 while ((c = read(fd, buf + n, size - n)) > 0) {
13 n += c;
14 if (n == size) {
15 char *newbuf = xmalloc(size * 2);
16 memcpy(newbuf, buf, n);
17 free(buf);
18 buf = newbuf;
19 size *= 2;
22 return buf;
25 static int newlines(char *s)
27 int i;
28 for (i = 0; (s = strchr(s, '\n')); i++, s++);
29 return i;
32 static void initlines(struct txt *txt)
34 int i;
35 txt->lines[0] = txt->txt;
36 for (i = 1; i <= txt->n; i++) {
37 char *s = strchr(txt->lines[i - 1], '\n');
38 if (s)
39 *s = '\0';
40 if (i < txt->n)
41 txt->lines[i] = s + 1;
45 struct txt *txt_alloc(int fd)
47 struct txt *txt = xmalloc(sizeof(struct txt));
48 txt->txt = file_read(fd);
49 txt->n = newlines(txt->txt);
50 txt->lines = xmalloc(sizeof(*txt->lines) * txt->n);
51 initlines(txt);
52 return txt;
55 char *txt_line(struct txt *txt, int line)
57 if (line < txt->n)
58 return txt->lines[line];
59 return NULL;
62 void txt_free(struct txt *txt)
64 free(txt->lines);
65 free(txt->txt);