]> git.sur5r.net Git - i3/i3/blob - src/cfgparse.y
Bugfix: Accept '\t' in the 'set' command, don’t die but ELOG in case of errors (Thank...
[i3/i3] / src / cfgparse.y
1 %{
2 /*
3  * vim:ts=4:sw=4:expandtab
4  *
5  */
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <sys/wait.h>
9 #include <unistd.h>
10 #include <fcntl.h>
11
12 #include "all.h"
13
14 static pid_t configerror_pid = -1;
15
16 static Match current_match;
17
18 typedef struct yy_buffer_state *YY_BUFFER_STATE;
19 extern int yylex(struct context *context);
20 extern int yyparse(void);
21 extern int yylex_destroy(void);
22 extern FILE *yyin;
23 YY_BUFFER_STATE yy_scan_string(const char *);
24
25 static struct bindings_head *current_bindings;
26 static struct context *context;
27
28 /* We don’t need yydebug for now, as we got decent error messages using
29  * yyerror(). Should you ever want to extend the parser, it might be handy
30  * to just comment it in again, so it stays here. */
31 //int yydebug = 1;
32
33 void yyerror(const char *error_message) {
34     context->has_errors = true;
35
36     ELOG("\n");
37     ELOG("CONFIG: %s\n", error_message);
38     ELOG("CONFIG: in file \"%s\", line %d:\n",
39         context->filename, context->line_number);
40     ELOG("CONFIG:   %s\n", context->line_copy);
41     char buffer[context->last_column+1];
42     buffer[context->last_column] = '\0';
43     for (int c = 1; c <= context->last_column; c++)
44         buffer[c-1] = (c >= context->first_column ? '^' : ' ');
45     ELOG("CONFIG:   %s\n", buffer);
46     ELOG("\n");
47 }
48
49 int yywrap() {
50     return 1;
51 }
52
53 /*
54  * Goes through each line of buf (separated by \n) and checks for statements /
55  * commands which only occur in i3 v4 configuration files. If it finds any, it
56  * returns version 4, otherwise it returns version 3.
57  *
58  */
59 static int detect_version(char *buf) {
60     char *walk = buf;
61     char *line = buf;
62     while (*walk != '\0') {
63         if (*walk != '\n') {
64             walk++;
65             continue;
66         }
67
68         /* check for some v4-only statements */
69         if (strncasecmp(line, "bindcode", strlen("bindcode")) == 0 ||
70             strncasecmp(line, "force_focus_wrapping", strlen("force_focus_wrapping")) == 0 ||
71             strncasecmp(line, "# i3 config file (v4)", strlen("# i3 config file (v4)")) == 0 ||
72             strncasecmp(line, "workspace_layout", strlen("workspace_layout")) == 0) {
73             printf("deciding for version 4 due to this line: %.*s\n", (int)(walk-line), line);
74             return 4;
75         }
76
77         /* if this is a bind statement, we can check the command */
78         if (strncasecmp(line, "bind", strlen("bind")) == 0) {
79             char *bind = strchr(line, ' ');
80             if (bind == NULL)
81                 goto next;
82             while ((*bind == ' ' || *bind == '\t') && *bind != '\0')
83                 bind++;
84             if (*bind == '\0')
85                 goto next;
86             if ((bind = strchr(bind, ' ')) == NULL)
87                 goto next;
88             while ((*bind == ' ' || *bind == '\t') && *bind != '\0')
89                 bind++;
90             if (*bind == '\0')
91                 goto next;
92             if (strncasecmp(bind, "layout", strlen("layout")) == 0 ||
93                 strncasecmp(bind, "floating", strlen("floating")) == 0 ||
94                 strncasecmp(bind, "workspace", strlen("workspace")) == 0 ||
95                 strncasecmp(bind, "focus left", strlen("focus left")) == 0 ||
96                 strncasecmp(bind, "focus right", strlen("focus right")) == 0 ||
97                 strncasecmp(bind, "focus up", strlen("focus up")) == 0 ||
98                 strncasecmp(bind, "focus down", strlen("focus down")) == 0 ||
99                 strncasecmp(bind, "border normal", strlen("border normal")) == 0 ||
100                 strncasecmp(bind, "border 1pixel", strlen("border 1pixel")) == 0 ||
101                 strncasecmp(bind, "border borderless", strlen("border borderless")) == 0) {
102                 printf("deciding for version 4 due to this line: %.*s\n", (int)(walk-line), line);
103                 return 4;
104             }
105         }
106
107 next:
108         /* advance to the next line */
109         walk++;
110         line = walk;
111     }
112
113     return 3;
114 }
115
116 /*
117  * Calls i3-migrate-config-to-v4 to migrate a configuration file (input
118  * buffer).
119  *
120  * Returns the converted config file or NULL if there was an error (for
121  * example the script could not be found in $PATH or the i3 executable’s
122  * directory).
123  *
124  */
125 static char *migrate_config(char *input, off_t size) {
126     int writepipe[2];
127     int readpipe[2];
128
129     if (pipe(writepipe) != 0 ||
130         pipe(readpipe) != 0) {
131         warn("migrate_config: Could not create pipes");
132         return NULL;
133     }
134
135     pid_t pid = fork();
136     if (pid == -1) {
137         warn("Could not fork()");
138         return NULL;
139     }
140
141     /* child */
142     if (pid == 0) {
143         /* close writing end of writepipe, connect reading side to stdin */
144         close(writepipe[1]);
145         dup2(writepipe[0], 0);
146
147         /* close reading end of readpipe, connect writing side to stdout */
148         close(readpipe[0]);
149         dup2(readpipe[1], 1);
150
151         static char *argv[] = {
152             NULL, /* will be replaced by the executable path */
153             NULL
154         };
155         exec_i3_utility("i3-migrate-config-to-v4", argv);
156     }
157
158     /* parent */
159
160     /* close reading end of the writepipe (connected to the script’s stdin) */
161     close(writepipe[0]);
162
163     /* write the whole config file to the pipe, the script will read everything
164      * immediately */
165     int written = 0;
166     int ret;
167     while (written < size) {
168         if ((ret = write(writepipe[1], input + written, size - written)) < 0) {
169             warn("Could not write to pipe");
170             return NULL;
171         }
172         written += ret;
173     }
174     close(writepipe[1]);
175
176     /* close writing end of the readpipe (connected to the script’s stdout) */
177     close(readpipe[1]);
178
179     /* read the script’s output */
180     int conv_size = 65535;
181     char *converted = malloc(conv_size);
182     int read_bytes = 0;
183     do {
184         if (read_bytes == conv_size) {
185             conv_size += 65535;
186             converted = realloc(converted, conv_size);
187         }
188         ret = read(readpipe[0], converted + read_bytes, conv_size - read_bytes);
189         if (ret == -1) {
190             warn("Cannot read from pipe");
191             return NULL;
192         }
193         read_bytes += ret;
194     } while (ret > 0);
195
196     /* get the returncode */
197     int status;
198     wait(&status);
199     if (!WIFEXITED(status)) {
200         fprintf(stderr, "Child did not terminate normally, using old config file (will lead to broken behaviour)\n");
201         return NULL;
202     }
203
204     int returncode = WEXITSTATUS(status);
205     if (returncode != 0) {
206         fprintf(stderr, "Migration process exit code was != 0\n");
207         if (returncode == 2) {
208             fprintf(stderr, "could not start the migration script\n");
209             /* TODO: script was not found. tell the user to fix his system or create a v4 config */
210         } else if (returncode == 1) {
211             fprintf(stderr, "This already was a v4 config. Please add the following line to your config file:\n");
212             fprintf(stderr, "# i3 config file (v4)\n");
213             /* TODO: nag the user with a message to include a hint for i3 in his config file */
214         }
215         return NULL;
216     }
217
218     return converted;
219 }
220
221 /*
222  * Handler which will be called when we get a SIGCHLD for the nagbar, meaning
223  * it exited (or could not be started, depending on the exit code).
224  *
225  */
226 static void nagbar_exited(EV_P_ ev_child *watcher, int revents) {
227     ev_child_stop(EV_A_ watcher);
228     if (!WIFEXITED(watcher->rstatus)) {
229         fprintf(stderr, "ERROR: i3-nagbar did not exit normally.\n");
230         return;
231     }
232
233     int exitcode = WEXITSTATUS(watcher->rstatus);
234     printf("i3-nagbar process exited with status %d\n", exitcode);
235     if (exitcode == 2) {
236         fprintf(stderr, "ERROR: i3-nagbar could not be found. Is it correctly installed on your system?\n");
237     }
238
239     configerror_pid = -1;
240 }
241
242 /*
243  * Starts an i3-nagbar process which alerts the user that his configuration
244  * file contains one or more errors. Also offers two buttons: One to launch an
245  * $EDITOR on the config file and another one to launch a $PAGER on the error
246  * logfile.
247  *
248  */
249 static void start_configerror_nagbar(const char *config_path) {
250     fprintf(stderr, "Would start i3-nagscreen now\n");
251     configerror_pid = fork();
252     if (configerror_pid == -1) {
253         warn("Could not fork()");
254         return;
255     }
256
257     /* child */
258     if (configerror_pid == 0) {
259         char *editaction,
260              *pageraction;
261         if (asprintf(&editaction, TERM_EMU " -e sh -c \"${EDITOR:-vi} \"%s\" && i3-msg reload\"", config_path) == -1)
262             exit(1);
263         if (asprintf(&pageraction, TERM_EMU " -e sh -c \"${PAGER:-less} \"%s\"\"", errorfilename) == -1)
264             exit(1);
265         char *argv[] = {
266             NULL, /* will be replaced by the executable path */
267             "-m",
268             "You have an error in your i3 config file!",
269             "-b",
270             "edit config",
271             editaction,
272             (errorfilename ? "-b" : NULL),
273             "show errors",
274             pageraction,
275             NULL
276         };
277         exec_i3_utility("i3-nagbar", argv);
278     }
279
280     /* parent */
281     /* install a child watcher */
282     ev_child *child = smalloc(sizeof(ev_child));
283     ev_child_init(child, &nagbar_exited, configerror_pid, 0);
284     ev_child_start(main_loop, child);
285 }
286
287 /*
288  * Kills the configerror i3-nagbar process, if any.
289  *
290  * Called when reloading/restarting.
291  *
292  * If wait_for_it is set (restarting), this function will waitpid(), otherwise,
293  * ev is assumed to handle it (reloading).
294  *
295  */
296 void kill_configerror_nagbar(bool wait_for_it) {
297     if (configerror_pid == -1)
298         return;
299
300     if (kill(configerror_pid, SIGTERM) == -1)
301         warn("kill(configerror_nagbar) failed");
302
303     if (!wait_for_it)
304         return;
305
306     /* When restarting, we don’t enter the ev main loop anymore and after the
307      * exec(), our old pid is no longer watched. So, ev won’t handle SIGCHLD
308      * for us and we would end up with a <defunct> process. Therefore we
309      * waitpid() here. */
310     waitpid(configerror_pid, NULL, 0);
311 }
312
313 void parse_file(const char *f) {
314     SLIST_HEAD(variables_head, Variable) variables = SLIST_HEAD_INITIALIZER(&variables);
315     int fd, ret, read_bytes = 0;
316     struct stat stbuf;
317     char *buf;
318     FILE *fstr;
319     char buffer[1026], key[512], value[512];
320
321     if ((fd = open(f, O_RDONLY)) == -1)
322         die("Could not open configuration file: %s\n", strerror(errno));
323
324     if (fstat(fd, &stbuf) == -1)
325         die("Could not fstat file: %s\n", strerror(errno));
326
327     buf = scalloc((stbuf.st_size + 1) * sizeof(char));
328     while (read_bytes < stbuf.st_size) {
329         if ((ret = read(fd, buf + read_bytes, (stbuf.st_size - read_bytes))) < 0)
330             die("Could not read(): %s\n", strerror(errno));
331         read_bytes += ret;
332     }
333
334     if (lseek(fd, 0, SEEK_SET) == (off_t)-1)
335         die("Could not lseek: %s\n", strerror(errno));
336
337     if ((fstr = fdopen(fd, "r")) == NULL)
338         die("Could not fdopen: %s\n", strerror(errno));
339
340     while (!feof(fstr)) {
341         if (fgets(buffer, 1024, fstr) == NULL) {
342             if (feof(fstr))
343                 break;
344             die("Could not read configuration file\n");
345         }
346
347         /* sscanf implicitly strips whitespace. Also, we skip comments and empty lines. */
348         if (sscanf(buffer, "%s %[^\n]", key, value) < 1 ||
349             key[0] == '#' || strlen(key) < 3)
350             continue;
351
352         if (strcasecmp(key, "set") == 0) {
353             if (value[0] != '$') {
354                 ELOG("Malformed variable assignment, name has to start with $\n");
355                 continue;
356             }
357
358             /* get key/value for this variable */
359             char *v_key = value, *v_value;
360             if ((v_value = strstr(value, " ")) == NULL &&
361                 (v_value = strstr(value, "\t")) == NULL) {
362                 ELOG("Malformed variable assignment, need a value\n");
363                 continue;
364             }
365
366             *(v_value++) = '\0';
367
368             struct Variable *new = scalloc(sizeof(struct Variable));
369             new->key = sstrdup(v_key);
370             new->value = sstrdup(v_value);
371             SLIST_INSERT_HEAD(&variables, new, variables);
372             DLOG("Got new variable %s = %s\n", v_key, v_value);
373             continue;
374         }
375     }
376     fclose(fstr);
377
378     /* For every custom variable, see how often it occurs in the file and
379      * how much extra bytes it requires when replaced. */
380     struct Variable *current, *nearest;
381     int extra_bytes = 0;
382     /* We need to copy the buffer because we need to invalidate the
383      * variables (otherwise we will count them twice, which is bad when
384      * 'extra' is negative) */
385     char *bufcopy = sstrdup(buf);
386     SLIST_FOREACH(current, &variables, variables) {
387         int extra = (strlen(current->value) - strlen(current->key));
388         char *next;
389         for (next = bufcopy;
390              (next = strcasestr(bufcopy + (next - bufcopy), current->key)) != NULL;
391              next += strlen(current->key)) {
392             *next = '_';
393             extra_bytes += extra;
394         }
395     }
396     FREE(bufcopy);
397
398     /* Then, allocate a new buffer and copy the file over to the new one,
399      * but replace occurences of our variables */
400     char *walk = buf, *destwalk;
401     char *new = smalloc((stbuf.st_size + extra_bytes + 1) * sizeof(char));
402     destwalk = new;
403     while (walk < (buf + stbuf.st_size)) {
404         /* Find the next variable */
405         SLIST_FOREACH(current, &variables, variables)
406             current->next_match = strcasestr(walk, current->key);
407         nearest = NULL;
408         int distance = stbuf.st_size;
409         SLIST_FOREACH(current, &variables, variables) {
410             if (current->next_match == NULL)
411                 continue;
412             if ((current->next_match - walk) < distance) {
413                 distance = (current->next_match - walk);
414                 nearest = current;
415             }
416         }
417         if (nearest == NULL) {
418             /* If there are no more variables, we just copy the rest */
419             strncpy(destwalk, walk, (buf + stbuf.st_size) - walk);
420             destwalk += (buf + stbuf.st_size) - walk;
421             *destwalk = '\0';
422             break;
423         } else {
424             /* Copy until the next variable, then copy its value */
425             strncpy(destwalk, walk, distance);
426             strncpy(destwalk + distance, nearest->value, strlen(nearest->value));
427             walk += distance + strlen(nearest->key);
428             destwalk += distance + strlen(nearest->value);
429         }
430     }
431
432     /* analyze the string to find out whether this is an old config file (3.x)
433      * or a new config file (4.x). If it’s old, we run the converter script. */
434     int version = detect_version(buf);
435     if (version == 3) {
436         /* We need to convert this v3 configuration */
437         char *converted = migrate_config(new, stbuf.st_size);
438         if (converted != NULL) {
439             printf("\n");
440             printf("****************************************************************\n");
441             printf("NOTE: Automatically converted configuration file from v3 to v4.\n");
442             printf("\n");
443             printf("Please convert your config file to v4. You can use this command:\n");
444             printf("    mv %s %s.O\n", f, f);
445             printf("    i3-migrate-config-to-v4 %s.O > %s\n", f, f);
446             printf("****************************************************************\n");
447             printf("\n");
448             free(new);
449             new = converted;
450         } else {
451             printf("\n");
452             printf("**********************************************************************\n");
453             printf("ERROR: Could not convert config file. Maybe i3-migrate-config-to-v4\n");
454             printf("was not correctly installed on your system?\n");
455             printf("**********************************************************************\n");
456             printf("\n");
457         }
458     }
459
460     /* now lex/parse it */
461     yy_scan_string(new);
462
463     context = scalloc(sizeof(struct context));
464     context->filename = f;
465
466     if (yyparse() != 0) {
467         fprintf(stderr, "Could not parse configfile\n");
468         exit(1);
469     }
470
471     if (context->has_errors) {
472         start_configerror_nagbar(f);
473     }
474
475     yylex_destroy();
476     FREE(context->line_copy);
477     free(context);
478     free(new);
479     free(buf);
480
481     while (!SLIST_EMPTY(&variables)) {
482         current = SLIST_FIRST(&variables);
483         FREE(current->key);
484         FREE(current->value);
485         SLIST_REMOVE_HEAD(&variables, variables);
486         FREE(current);
487     }
488 }
489
490 %}
491
492 %error-verbose
493 %lex-param { struct context *context }
494
495 %union {
496     int number;
497     char *string;
498     uint32_t *single_color;
499     struct Colortriple *color;
500     Match *match;
501     struct Binding *binding;
502 }
503
504 %token  <number>        NUMBER                      "<number>"
505 %token  <string>        WORD                        "<word>"
506 %token  <string>        STR                         "<string>"
507 %token  <string>        STR_NG                      "<string (non-greedy)>"
508 %token  <string>        HEX                         "<hex>"
509 %token  <string>        OUTPUT                      "<RandR output>"
510 %token                  TOKBINDCODE
511 %token                  TOKTERMINAL
512 %token                  TOKCOMMENT                  "<comment>"
513 %token                  TOKFONT                     "font"
514 %token                  TOKBINDSYM                  "bindsym"
515 %token  <number>        MODIFIER                    "<modifier>"
516 %token                  TOKCONTROL                  "control"
517 %token                  TOKSHIFT                    "shift"
518 %token                  TOKFLOATING_MODIFIER        "floating_modifier"
519 %token  <string>        QUOTEDSTRING                "<quoted string>"
520 %token                  TOKWORKSPACE                "workspace"
521 %token                  TOKOUTPUT                   "output"
522 %token                  TOKASSIGN                   "assign"
523 %token                  TOKSET
524 %token                  TOKIPCSOCKET                "ipc_socket"
525 %token                  TOKRESTARTSTATE             "restart_state"
526 %token                  TOKEXEC                     "exec"
527 %token                  TOKEXEC_ALWAYS              "exec_always"
528 %token  <single_color>  TOKSINGLECOLOR
529 %token  <color>         TOKCOLOR
530 %token                  TOKARROW                    "→"
531 %token                  TOKMODE                     "mode"
532 %token                  TOK_ORIENTATION             "default_orientation"
533 %token                  TOK_HORIZ                   "horizontal"
534 %token                  TOK_VERT                    "vertical"
535 %token                  TOK_AUTO                    "auto"
536 %token                  TOK_WORKSPACE_LAYOUT        "workspace_layout"
537 %token                  TOKNEWWINDOW                "new_window"
538 %token                  TOK_NORMAL                  "normal"
539 %token                  TOK_NONE                    "none"
540 %token                  TOK_1PIXEL                  "1pixel"
541 %token                  TOKFOCUSFOLLOWSMOUSE        "focus_follows_mouse"
542 %token                  TOK_FORCE_FOCUS_WRAPPING    "force_focus_wrapping"
543 %token                  TOKWORKSPACEBAR             "workspace_bar"
544 %token                  TOK_DEFAULT                 "default"
545 %token                  TOK_STACKING                "stacking"
546 %token                  TOK_TABBED                  "tabbed"
547 %token  <number>        TOKSTACKLIMIT               "stack-limit"
548 %token                  TOK_POPUP_DURING_FULLSCREEN "popup_during_fullscreen"
549 %token                  TOK_IGNORE                  "ignore"
550 %token                  TOK_LEAVE_FULLSCREEN        "leave_fullscreen"
551 %token                  TOK_FOR_WINDOW              "for_window"
552
553 %token              TOK_MARK            "mark"
554 %token              TOK_CLASS           "class"
555 %token              TOK_INSTANCE        "instance"
556 %token              TOK_ID              "id"
557 %token              TOK_CON_ID          "con_id"
558 %token              TOK_TITLE           "title"
559
560 %type   <binding>       binding
561 %type   <binding>       bindcode
562 %type   <binding>       bindsym
563 %type   <number>        binding_modifiers
564 %type   <number>        binding_modifier
565 %type   <number>        direction
566 %type   <number>        layout_mode
567 %type   <number>        border_style
568 %type   <number>        new_window
569 %type   <number>        colorpixel
570 %type   <number>        bool
571 %type   <number>        popup_setting
572 %type   <string>        command
573 %type   <string>        word_or_number
574 %type   <string>        optional_workspace_name
575 %type   <string>        workspace_name
576 %type   <string>        window_class
577
578 %%
579
580 lines: /* empty */
581     | lines error
582     | lines line
583     ;
584
585 line:
586     bindline
587     | for_window
588     | mode
589     | floating_modifier
590     | orientation
591     | workspace_layout
592     | new_window
593     | focus_follows_mouse
594     | force_focus_wrapping
595     | workspace_bar
596     | workspace
597     | assign
598     | ipcsocket
599     | restart_state
600     | exec
601     | exec_always
602     | single_color
603     | color
604     | terminal
605     | font
606     | comment
607     | popup_during_fullscreen
608     ;
609
610 comment:
611     TOKCOMMENT
612     ;
613
614 command:
615     STR
616     ;
617
618 bindline:
619     binding
620     {
621         TAILQ_INSERT_TAIL(bindings, $1, bindings);
622     }
623     ;
624
625 binding:
626     TOKBINDCODE bindcode         { $$ = $2; }
627     | TOKBINDSYM bindsym         { $$ = $2; }
628     ;
629
630 bindcode:
631     binding_modifiers NUMBER command
632     {
633         printf("\tFound keycode binding mod%d with key %d and command %s\n", $1, $2, $3);
634         Binding *new = scalloc(sizeof(Binding));
635
636         new->keycode = $2;
637         new->mods = $1;
638         new->command = $3;
639
640         $$ = new;
641     }
642     ;
643
644 bindsym:
645     binding_modifiers word_or_number command
646     {
647         printf("\tFound keysym binding mod%d with key %s and command %s\n", $1, $2, $3);
648         Binding *new = scalloc(sizeof(Binding));
649
650         new->symbol = $2;
651         new->mods = $1;
652         new->command = $3;
653
654         $$ = new;
655     }
656     ;
657
658 for_window:
659     TOK_FOR_WINDOW match command
660     {
661         printf("\t should execute command %s for the criteria mentioned above\n", $3);
662         Assignment *assignment = scalloc(sizeof(Assignment));
663         assignment->type = A_COMMAND;
664         assignment->match = current_match;
665         assignment->dest.command = $3;
666         TAILQ_INSERT_TAIL(&assignments, assignment, assignments);
667     }
668     ;
669
670 match:
671     | matchstart criteria matchend
672     {
673         printf("match parsed\n");
674     }
675     ;
676
677 matchstart:
678     '['
679     {
680         printf("start\n");
681         match_init(&current_match);
682     }
683     ;
684
685 matchend:
686     ']'
687     {
688         printf("match specification finished\n");
689     }
690     ;
691
692 criteria:
693     criteria criterion
694     | criterion
695     ;
696
697 criterion:
698     TOK_CLASS '=' STR
699     {
700         printf("criteria: class = %s\n", $3);
701         current_match.class = $3;
702     }
703     | TOK_INSTANCE '=' STR
704     {
705         printf("criteria: instance = %s\n", $3);
706         current_match.instance = $3;
707     }
708     | TOK_CON_ID '=' STR
709     {
710         printf("criteria: id = %s\n", $3);
711         char *end;
712         long parsed = strtol($3, &end, 10);
713         if (parsed == LONG_MIN ||
714             parsed == LONG_MAX ||
715             parsed < 0 ||
716             (end && *end != '\0')) {
717             ELOG("Could not parse con id \"%s\"\n", $3);
718         } else {
719             current_match.con_id = (Con*)parsed;
720             printf("id as int = %p\n", current_match.con_id);
721         }
722     }
723     | TOK_ID '=' STR
724     {
725         printf("criteria: window id = %s\n", $3);
726         char *end;
727         long parsed = strtol($3, &end, 10);
728         if (parsed == LONG_MIN ||
729             parsed == LONG_MAX ||
730             parsed < 0 ||
731             (end && *end != '\0')) {
732             ELOG("Could not parse window id \"%s\"\n", $3);
733         } else {
734             current_match.id = parsed;
735             printf("window id as int = %d\n", current_match.id);
736         }
737     }
738     | TOK_MARK '=' STR
739     {
740         printf("criteria: mark = %s\n", $3);
741         current_match.mark = $3;
742     }
743     | TOK_TITLE '=' STR
744     {
745         printf("criteria: title = %s\n", $3);
746         current_match.title = $3;
747     }
748     ;
749
750
751
752 word_or_number:
753     WORD
754     | NUMBER
755     {
756         asprintf(&$$, "%d", $1);
757     }
758     ;
759
760 mode:
761     TOKMODE QUOTEDSTRING '{' modelines '}'
762     {
763         if (strcasecmp($2, "default") == 0) {
764             printf("You cannot use the name \"default\" for your mode\n");
765             exit(1);
766         }
767         printf("\t now in mode %s\n", $2);
768         printf("\t current bindings = %p\n", current_bindings);
769         Binding *binding;
770         TAILQ_FOREACH(binding, current_bindings, bindings) {
771             printf("got binding on mods %d, keycode %d, symbol %s, command %s\n",
772                             binding->mods, binding->keycode, binding->symbol, binding->command);
773         }
774
775         struct Mode *mode = scalloc(sizeof(struct Mode));
776         mode->name = $2;
777         mode->bindings = current_bindings;
778         current_bindings = NULL;
779         SLIST_INSERT_HEAD(&modes, mode, modes);
780     }
781     ;
782
783
784 modelines:
785     /* empty */
786     | modelines modeline
787     ;
788
789 modeline:
790     comment
791     | binding
792     {
793         if (current_bindings == NULL) {
794             current_bindings = scalloc(sizeof(struct bindings_head));
795             TAILQ_INIT(current_bindings);
796         }
797
798         TAILQ_INSERT_TAIL(current_bindings, $1, bindings);
799     }
800     ;
801
802 floating_modifier:
803     TOKFLOATING_MODIFIER binding_modifiers
804     {
805         DLOG("floating modifier = %d\n", $2);
806         config.floating_modifier = $2;
807     }
808     ;
809
810 orientation:
811     TOK_ORIENTATION direction
812     {
813         DLOG("New containers should start with split direction %d\n", $2);
814         config.default_orientation = $2;
815     }
816     ;
817
818 direction:
819     TOK_HORIZ       { $$ = HORIZ; }
820     | TOK_VERT      { $$ = VERT; }
821     | TOK_AUTO      { $$ = NO_ORIENTATION; }
822     ;
823
824 workspace_layout:
825     TOK_WORKSPACE_LAYOUT layout_mode
826     {
827         DLOG("new containers will be in mode %d\n", $2);
828         config.default_layout = $2;
829
830 #if 0
831         /* We also need to change the layout of the already existing
832          * workspaces here. Workspaces may exist at this point because
833          * of the other directives which are modifying workspaces
834          * (setting the preferred screen or name). While the workspace
835          * objects are already created, they have never been used.
836          * Thus, the user very likely awaits the default container mode
837          * to trigger in this case, regardless of where it is inside
838          * his configuration file. */
839         Workspace *ws;
840         TAILQ_FOREACH(ws, workspaces, workspaces) {
841                 if (ws->table == NULL)
842                         continue;
843                 switch_layout_mode(global_conn,
844                                    ws->table[0][0],
845                                    config.container_mode);
846         }
847 #endif
848     }
849     | TOK_WORKSPACE_LAYOUT TOKSTACKLIMIT TOKSTACKLIMIT NUMBER
850     {
851         DLOG("stack-limit %d with val %d\n", $3, $4);
852         config.container_stack_limit = $3;
853         config.container_stack_limit_value = $4;
854
855 #if 0
856         /* See the comment above */
857         Workspace *ws;
858         TAILQ_FOREACH(ws, workspaces, workspaces) {
859                 if (ws->table == NULL)
860                         continue;
861                 Container *con = ws->table[0][0];
862                 con->stack_limit = config.container_stack_limit;
863                 con->stack_limit_value = config.container_stack_limit_value;
864         }
865 #endif
866     }
867     ;
868
869 layout_mode:
870     TOK_DEFAULT       { $$ = L_DEFAULT; }
871     | TOK_STACKING    { $$ = L_STACKED; }
872     | TOK_TABBED      { $$ = L_TABBED; }
873     ;
874
875 new_window:
876     TOKNEWWINDOW border_style
877     {
878         DLOG("new windows should start with border style %d\n", $2);
879         config.default_border = $2;
880     }
881     ;
882
883 border_style:
884     TOK_NORMAL      { $$ = BS_NORMAL; }
885     | TOK_NONE      { $$ = BS_NONE; }
886     | TOK_1PIXEL    { $$ = BS_1PIXEL; }
887     ;
888
889 bool:
890     NUMBER
891     {
892         $$ = ($1 == 1);
893     }
894     | WORD
895     {
896         DLOG("checking word \"%s\"\n", $1);
897         $$ = (strcasecmp($1, "yes") == 0 ||
898               strcasecmp($1, "true") == 0 ||
899               strcasecmp($1, "on") == 0 ||
900               strcasecmp($1, "enable") == 0 ||
901               strcasecmp($1, "active") == 0);
902     }
903     ;
904
905 focus_follows_mouse:
906     TOKFOCUSFOLLOWSMOUSE bool
907     {
908         DLOG("focus follows mouse = %d\n", $2);
909         config.disable_focus_follows_mouse = !($2);
910     }
911     ;
912
913 force_focus_wrapping:
914     TOK_FORCE_FOCUS_WRAPPING bool
915     {
916         DLOG("force focus wrapping = %d\n", $2);
917         config.force_focus_wrapping = $2;
918     }
919     ;
920
921 workspace_bar:
922     TOKWORKSPACEBAR bool
923     {
924         DLOG("workspace bar = %d\n", $2);
925         config.disable_workspace_bar = !($2);
926     }
927     ;
928
929 workspace:
930     TOKWORKSPACE NUMBER TOKOUTPUT OUTPUT optional_workspace_name
931     {
932         int ws_num = $2;
933         if (ws_num < 1) {
934             DLOG("Invalid workspace assignment, workspace number %d out of range\n", ws_num);
935         } else {
936             char *ws_name = NULL;
937             if ($5 == NULL) {
938                 asprintf(&ws_name, "%d", ws_num);
939             } else {
940                 ws_name = $5;
941             }
942
943             DLOG("Should assign workspace %s to output %s\n", ws_name, $4);
944             struct Workspace_Assignment *assignment = scalloc(sizeof(struct Workspace_Assignment));
945             assignment->name = ws_name;
946             assignment->output = $4;
947             TAILQ_INSERT_TAIL(&ws_assignments, assignment, ws_assignments);
948         }
949     }
950     | TOKWORKSPACE NUMBER workspace_name
951     {
952         int ws_num = $2;
953         if (ws_num < 1) {
954             DLOG("Invalid workspace assignment, workspace number %d out of range\n", ws_num);
955         } else {
956             DLOG("workspace name to: %s\n", $3);
957 #if 0
958             if ($<string>3 != NULL) {
959                     workspace_set_name(workspace_get(ws_num - 1), $<string>3);
960                     free($<string>3);
961             }
962 #endif
963         }
964     }
965     ;
966
967 optional_workspace_name:
968     /* empty */          { $$ = NULL; }
969     | workspace_name     { $$ = $1; }
970     ;
971
972 workspace_name:
973     QUOTEDSTRING         { $$ = $1; }
974     | STR                { $$ = $1; }
975     | WORD               { $$ = $1; }
976     ;
977
978 assign:
979     TOKASSIGN window_class STR
980     {
981         printf("assignment of %s to *%s*\n", $2, $3);
982         char *workspace = $3;
983         char *criteria = $2;
984
985         Assignment *assignment = scalloc(sizeof(Assignment));
986         Match *match = &(assignment->match);
987         match_init(match);
988
989         char *separator = NULL;
990         if ((separator = strchr(criteria, '/')) != NULL) {
991             *(separator++) = '\0';
992             match->title = sstrdup(separator);
993         }
994         if (*criteria != '\0')
995             match->class = sstrdup(criteria);
996         free(criteria);
997
998         printf("  class = %s\n", match->class);
999         printf("  title = %s\n", match->title);
1000
1001         /* Compatibility with older versions: If the assignment target starts
1002          * with ~, we create the equivalent of:
1003          *
1004          * for_window [class="foo"] floating enable
1005          */
1006         if (*workspace == '~') {
1007             workspace++;
1008             if (*workspace == '\0') {
1009                 /* This assignment was *only* for floating */
1010                 assignment->type = A_COMMAND;
1011                 assignment->dest.command = sstrdup("floating enable");
1012                 TAILQ_INSERT_TAIL(&assignments, assignment, assignments);
1013                 break;
1014             } else {
1015                 /* Create a new assignment and continue afterwards */
1016                 Assignment *floating = scalloc(sizeof(Assignment));
1017                 match_copy(&(floating->match), match);
1018                 floating->type = A_COMMAND;
1019                 floating->dest.command = sstrdup("floating enable");
1020                 TAILQ_INSERT_TAIL(&assignments, floating, assignments);
1021             }
1022         }
1023
1024         assignment->type = A_TO_WORKSPACE;
1025         assignment->dest.workspace = workspace;
1026         TAILQ_INSERT_TAIL(&assignments, assignment, assignments);
1027     }
1028     ;
1029
1030 window_class:
1031     QUOTEDSTRING
1032     | STR_NG
1033     ;
1034
1035 ipcsocket:
1036     TOKIPCSOCKET STR
1037     {
1038         config.ipc_socket_path = $2;
1039     }
1040     ;
1041
1042 restart_state:
1043     TOKRESTARTSTATE STR
1044     {
1045         config.restart_state_path = $2;
1046     }
1047     ;
1048
1049 exec:
1050     TOKEXEC STR
1051     {
1052         struct Autostart *new = smalloc(sizeof(struct Autostart));
1053         new->command = $2;
1054         TAILQ_INSERT_TAIL(&autostarts, new, autostarts);
1055     }
1056     ;
1057
1058 exec_always:
1059     TOKEXEC_ALWAYS STR
1060     {
1061         struct Autostart *new = smalloc(sizeof(struct Autostart));
1062         new->command = $2;
1063         TAILQ_INSERT_TAIL(&autostarts_always, new, autostarts_always);
1064     }
1065     ;
1066
1067 terminal:
1068     TOKTERMINAL STR
1069     {
1070         ELOG("The terminal option is DEPRECATED and has no effect. "
1071             "Please remove it from your configuration file.\n");
1072     }
1073     ;
1074
1075 font:
1076     TOKFONT STR
1077     {
1078         config.font = load_font($2, true);
1079         printf("font %s\n", $2);
1080         free($2);
1081     }
1082     ;
1083
1084 single_color:
1085     TOKSINGLECOLOR colorpixel
1086     {
1087         uint32_t *dest = $1;
1088         *dest = $2;
1089     }
1090     ;
1091
1092 color:
1093     TOKCOLOR colorpixel colorpixel colorpixel
1094     {
1095         struct Colortriple *dest = $1;
1096
1097         dest->border = $2;
1098         dest->background = $3;
1099         dest->text = $4;
1100     }
1101     ;
1102
1103 colorpixel:
1104     '#' HEX
1105     {
1106         char *hex;
1107         if (asprintf(&hex, "#%s", $2) == -1)
1108             die("asprintf()");
1109         free($2);
1110         $$ = get_colorpixel(hex);
1111         free(hex);
1112     }
1113     ;
1114
1115
1116 binding_modifiers:
1117     /* NULL */                               { $$ = 0; }
1118     | binding_modifier
1119     | binding_modifiers '+' binding_modifier { $$ = $1 | $3; }
1120     | binding_modifiers '+'                  { $$ = $1; }
1121     ;
1122
1123 binding_modifier:
1124     MODIFIER        { $$ = $1; }
1125     | TOKCONTROL    { $$ = BIND_CONTROL; }
1126     | TOKSHIFT      { $$ = BIND_SHIFT; }
1127     ;
1128
1129 popup_during_fullscreen:
1130     TOK_POPUP_DURING_FULLSCREEN popup_setting
1131     {
1132         DLOG("popup_during_fullscreen setting: %d\n", $2);
1133         config.popup_during_fullscreen = $2;
1134     }
1135     ;
1136
1137 popup_setting:
1138     TOK_IGNORE              { $$ = PDF_IGNORE; }
1139     | TOK_LEAVE_FULLSCREEN  { $$ = PDF_LEAVE_FULLSCREEN; }
1140     ;