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