Update README to include recent changes to supported registers
[vis.git] / text-regex.c
blobc4134aa24257a496a3f64c504bb1505377a21b26
1 #include <stdlib.h>
2 #include <regex.h>
4 #include "text-regex.h"
6 struct Regex {
7 regex_t regex;
8 };
10 Regex *text_regex_new(void) {
11 Regex *r = calloc(1, sizeof(Regex));
12 if (!r)
13 return NULL;
14 regcomp(&r->regex, "\0\0", 0); /* this should not match anything */
15 return r;
18 int text_regex_compile(Regex *regex, const char *string, int cflags) {
19 int r = regcomp(&regex->regex, string, cflags);
20 if (r)
21 regcomp(&regex->regex, "\0\0", 0);
22 return r;
25 void text_regex_free(Regex *r) {
26 if (!r)
27 return;
28 regfree(&r->regex);
29 free(r);
32 int text_search_range_forward(Text *txt, size_t pos, size_t len, Regex *r, size_t nmatch, RegexMatch pmatch[], int eflags) {
33 char *buf = text_bytes_alloc0(txt, pos, len);
34 if (!buf)
35 return REG_NOMATCH;
36 regmatch_t match[nmatch];
37 int ret = regexec(&r->regex, buf, nmatch, match, eflags);
38 if (!ret) {
39 for (size_t i = 0; i < nmatch; i++) {
40 pmatch[i].start = match[i].rm_so == -1 ? EPOS : pos + match[i].rm_so;
41 pmatch[i].end = match[i].rm_eo == -1 ? EPOS : pos + match[i].rm_eo;
44 free(buf);
45 return ret;
48 int text_search_range_backward(Text *txt, size_t pos, size_t len, Regex *r, size_t nmatch, RegexMatch pmatch[], int eflags) {
49 char *buf = text_bytes_alloc0(txt, pos, len);
50 if (!buf)
51 return REG_NOMATCH;
52 regmatch_t match[nmatch];
53 char *cur = buf;
54 int ret = REG_NOMATCH;
55 while (!regexec(&r->regex, cur, nmatch, match, eflags)) {
56 ret = 0;
57 for (size_t i = 0; i < nmatch; i++) {
58 pmatch[i].start = match[i].rm_so == -1 ? EPOS : pos + (size_t)(cur - buf) + match[i].rm_so;
59 pmatch[i].end = match[i].rm_eo == -1 ? EPOS : pos + (size_t)(cur - buf) + match[i].rm_eo;
61 cur += match[0].rm_eo;
63 free(buf);
64 return ret;