4 #include "text-regex.h"
10 Regex
*text_regex_new(void) {
11 Regex
*r
= calloc(1, sizeof(Regex
));
14 regcomp(&r
->regex
, "\0\0", 0); /* this should not match anything */
18 int text_regex_compile(Regex
*regex
, const char *string
, int cflags
) {
19 int r
= regcomp(®ex
->regex
, string
, cflags
);
21 regcomp(®ex
->regex
, "\0\0", 0);
25 size_t text_regex_nsub(Regex
*r
) {
28 return r
->regex
.re_nsub
;
31 void text_regex_free(Regex
*r
) {
38 int text_regex_match(Regex
*r
, const char *data
, int eflags
) {
39 return regexec(&r
->regex
, data
, 0, NULL
, eflags
);
42 int text_search_range_forward(Text
*txt
, size_t pos
, size_t len
, Regex
*r
, size_t nmatch
, RegexMatch pmatch
[], int eflags
) {
43 char *buf
= text_bytes_alloc0(txt
, pos
, len
);
46 char *cur
= buf
, *end
= buf
+ len
;
47 int ret
= REG_NOMATCH
;
48 regmatch_t match
[nmatch
];
49 for (size_t junk
= len
; len
> 0; len
-= junk
, pos
+= junk
) {
50 ret
= regexec(&r
->regex
, cur
, nmatch
, match
, eflags
);
52 for (size_t i
= 0; i
< nmatch
; i
++) {
53 pmatch
[i
].start
= match
[i
].rm_so
== -1 ? EPOS
: pos
+ match
[i
].rm_so
;
54 pmatch
[i
].end
= match
[i
].rm_eo
== -1 ? EPOS
: pos
+ match
[i
].rm_eo
;
58 char *next
= memchr(cur
, 0, len
);
61 while (!*next
&& next
!= end
)
70 int text_search_range_backward(Text
*txt
, size_t pos
, size_t len
, Regex
*r
, size_t nmatch
, RegexMatch pmatch
[], int eflags
) {
71 char *buf
= text_bytes_alloc0(txt
, pos
, len
);
74 char *cur
= buf
, *end
= buf
+ len
;
75 int ret
= REG_NOMATCH
;
76 regmatch_t match
[nmatch
];
77 for (size_t junk
= len
; len
> 0; len
-= junk
, pos
+= junk
) {
79 if (!regexec(&r
->regex
, cur
, nmatch
, match
, eflags
)) {
81 for (size_t i
= 0; i
< nmatch
; i
++) {
82 pmatch
[i
].start
= match
[i
].rm_so
== -1 ? EPOS
: pos
+ match
[i
].rm_so
;
83 pmatch
[i
].end
= match
[i
].rm_eo
== -1 ? EPOS
: pos
+ match
[i
].rm_eo
;
86 if (match
[0].rm_so
== 0 && match
[0].rm_eo
== 0) {
87 /* empty match at the beginning of cur, advance to next line */
88 next
= strchr(cur
, '\n');
93 next
= cur
+ match
[0].rm_eo
;
96 next
= memchr(cur
, 0, len
);
99 while (!*next
&& next
!= end
)