]> git.sur5r.net Git - i3/i3/blob - src/regex.c
Implement support for PCRE regular expressions for all criteria (for_window, commands...
[i3/i3] / src / regex.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009-2011 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  *
8  */
9
10 #include "all.h"
11
12 /*
13  * Creates a new 'regex' struct containing the given pattern and a PCRE
14  * compiled regular expression. Also, calls pcre_study because this regex will
15  * most likely be used often (like for every new window and on every relevant
16  * property change of existing windows).
17  *
18  * Returns NULL if the pattern could not be compiled into a regular expression
19  * (and ELOGs an appropriate error message).
20  *
21  */
22 struct regex *regex_new(const char *pattern) {
23     const char *error;
24     int offset;
25
26     struct regex *re = scalloc(sizeof(struct regex));
27     re->pattern = sstrdup(pattern);
28     if (!(re->regex = pcre_compile(pattern, 0, &error, &offset, NULL))) {
29         ELOG("PCRE regular expression compilation failed at %d: %s",
30              offset, error);
31         return NULL;
32     }
33     re->extra = pcre_study(re->regex, 0, &error);
34     return re;
35 }
36
37 /*
38  * Checks if the given regular expression matches the given input and returns
39  * true if it does. In either case, it logs the outcome using LOG(), so it will
40  * be visible without any debug loglevel.
41  *
42  */
43 bool regex_matches(struct regex *regex, const char *input) {
44     int rc;
45
46     /* TODO: is strlen(input) correct for UTF-8 matching? */
47     /* TODO: enable UTF-8 */
48     if ((rc = pcre_exec(regex->regex, regex->extra, input, strlen(input), 0, 0, NULL, 0)) == 0) {
49         LOG("Regular expression \"%s\" matches \"%s\"\n",
50             regex->pattern, input);
51         return true;
52     }
53
54     if (rc == PCRE_ERROR_NOMATCH) {
55         LOG("Regular expression \"%s\" does not match \"%s\"\n",
56             regex->pattern, input);
57         return false;
58     }
59
60     /* TODO: handle the other error codes */
61     LOG("PCRE error\n");
62     return false;
63 }