]> git.sur5r.net Git - i3/i3/blob - src/cfgparse.y
f1843312dbe6e2f3ed0fec3ce8eb3c51331eb323
[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 (strstr(value, " ") == NULL && strstr(value, "\t") == NULL) {
362                 ELOG("Malformed variable assignment, need a value\n");
363                 continue;
364             }
365
366             if (!(v_value = strstr(value, " ")))
367                 v_value = strstr(value, "\t");
368
369             *(v_value++) = '\0';
370
371             struct Variable *new = scalloc(sizeof(struct Variable));
372             new->key = sstrdup(v_key);
373             new->value = sstrdup(v_value);
374             SLIST_INSERT_HEAD(&variables, new, variables);
375             DLOG("Got new variable %s = %s\n", v_key, v_value);
376             continue;
377         }
378     }
379     fclose(fstr);
380
381     /* For every custom variable, see how often it occurs in the file and
382      * how much extra bytes it requires when replaced. */
383     struct Variable *current, *nearest;
384     int extra_bytes = 0;
385     /* We need to copy the buffer because we need to invalidate the
386      * variables (otherwise we will count them twice, which is bad when
387      * 'extra' is negative) */
388     char *bufcopy = sstrdup(buf);
389     SLIST_FOREACH(current, &variables, variables) {
390         int extra = (strlen(current->value) - strlen(current->key));
391         char *next;
392         for (next = bufcopy;
393              (bufcopy + (next - bufcopy)) < (buf + stbuf.st_size) &&
394              (next = strcasestr(bufcopy + (next - bufcopy), current->key)) != NULL;
395              next += strlen(current->key)) {
396             *next = '_';
397             extra_bytes += extra;
398         }
399     }
400     FREE(bufcopy);
401
402     /* Then, allocate a new buffer and copy the file over to the new one,
403      * but replace occurences of our variables */
404     char *walk = buf, *destwalk;
405     char *new = smalloc((stbuf.st_size + extra_bytes + 1) * sizeof(char));
406     destwalk = new;
407     while (walk < (buf + stbuf.st_size)) {
408         /* Find the next variable */
409         SLIST_FOREACH(current, &variables, variables)
410             current->next_match = strcasestr(walk, current->key);
411         nearest = NULL;
412         int distance = stbuf.st_size;
413         SLIST_FOREACH(current, &variables, variables) {
414             if (current->next_match == NULL)
415                 continue;
416             if ((current->next_match - walk) < distance) {
417                 distance = (current->next_match - walk);
418                 nearest = current;
419             }
420         }
421         if (nearest == NULL) {
422             /* If there are no more variables, we just copy the rest */
423             strncpy(destwalk, walk, (buf + stbuf.st_size) - walk);
424             destwalk += (buf + stbuf.st_size) - walk;
425             *destwalk = '\0';
426             break;
427         } else {
428             /* Copy until the next variable, then copy its value */
429             strncpy(destwalk, walk, distance);
430             strncpy(destwalk + distance, nearest->value, strlen(nearest->value));
431             walk += distance + strlen(nearest->key);
432             destwalk += distance + strlen(nearest->value);
433         }
434     }
435
436     /* analyze the string to find out whether this is an old config file (3.x)
437      * or a new config file (4.x). If it’s old, we run the converter script. */
438     int version = detect_version(buf);
439     if (version == 3) {
440         /* We need to convert this v3 configuration */
441         char *converted = migrate_config(new, stbuf.st_size);
442         if (converted != NULL) {
443             printf("\n");
444             printf("****************************************************************\n");
445             printf("NOTE: Automatically converted configuration file from v3 to v4.\n");
446             printf("\n");
447             printf("Please convert your config file to v4. You can use this command:\n");
448             printf("    mv %s %s.O\n", f, f);
449             printf("    i3-migrate-config-to-v4 %s.O > %s\n", f, f);
450             printf("****************************************************************\n");
451             printf("\n");
452             free(new);
453             new = converted;
454         } else {
455             printf("\n");
456             printf("**********************************************************************\n");
457             printf("ERROR: Could not convert config file. Maybe i3-migrate-config-to-v4\n");
458             printf("was not correctly installed on your system?\n");
459             printf("**********************************************************************\n");
460             printf("\n");
461         }
462     }
463
464     /* now lex/parse it */
465     yy_scan_string(new);
466
467     context = scalloc(sizeof(struct context));
468     context->filename = f;
469
470     if (yyparse() != 0) {
471         fprintf(stderr, "Could not parse configfile\n");
472         exit(1);
473     }
474
475     if (context->has_errors) {
476         start_configerror_nagbar(f);
477     }
478
479     yylex_destroy();
480     FREE(context->line_copy);
481     free(context);
482     free(new);
483     free(buf);
484
485     while (!SLIST_EMPTY(&variables)) {
486         current = SLIST_FIRST(&variables);
487         FREE(current->key);
488         FREE(current->value);
489         SLIST_REMOVE_HEAD(&variables, variables);
490         FREE(current);
491     }
492 }
493
494 %}
495
496 %error-verbose
497 %lex-param { struct context *context }
498
499 %union {
500     int number;
501     char *string;
502     uint32_t *single_color;
503     struct Colortriple *color;
504     Match *match;
505     struct Binding *binding;
506 }
507
508 %token  <number>        NUMBER                      "<number>"
509 %token  <string>        WORD                        "<word>"
510 %token  <string>        STR                         "<string>"
511 %token  <string>        STR_NG                      "<string (non-greedy)>"
512 %token  <string>        HEX                         "<hex>"
513 %token  <string>        OUTPUT                      "<RandR output>"
514 %token                  TOKBINDCODE
515 %token                  TOKTERMINAL
516 %token                  TOKCOMMENT                  "<comment>"
517 %token                  TOKFONT                     "font"
518 %token                  TOKBINDSYM                  "bindsym"
519 %token  <number>        MODIFIER                    "<modifier>"
520 %token                  TOKCONTROL                  "control"
521 %token                  TOKSHIFT                    "shift"
522 %token                  TOKFLOATING_MODIFIER        "floating_modifier"
523 %token  <string>        QUOTEDSTRING                "<quoted string>"
524 %token                  TOKWORKSPACE                "workspace"
525 %token                  TOKOUTPUT                   "output"
526 %token                  TOKASSIGN                   "assign"
527 %token                  TOKSET
528 %token                  TOKIPCSOCKET                "ipc_socket"
529 %token                  TOKRESTARTSTATE             "restart_state"
530 %token                  TOKEXEC                     "exec"
531 %token                  TOKEXEC_ALWAYS              "exec_always"
532 %token  <single_color>  TOKSINGLECOLOR
533 %token  <color>         TOKCOLOR
534 %token                  TOKARROW                    "→"
535 %token                  TOKMODE                     "mode"
536 %token                  TOK_ORIENTATION             "default_orientation"
537 %token                  TOK_HORIZ                   "horizontal"
538 %token                  TOK_VERT                    "vertical"
539 %token                  TOK_AUTO                    "auto"
540 %token                  TOK_WORKSPACE_LAYOUT        "workspace_layout"
541 %token                  TOKNEWWINDOW                "new_window"
542 %token                  TOK_NORMAL                  "normal"
543 %token                  TOK_NONE                    "none"
544 %token                  TOK_1PIXEL                  "1pixel"
545 %token                  TOKFOCUSFOLLOWSMOUSE        "focus_follows_mouse"
546 %token                  TOK_FORCE_FOCUS_WRAPPING    "force_focus_wrapping"
547 %token                  TOKWORKSPACEBAR             "workspace_bar"
548 %token                  TOK_DEFAULT                 "default"
549 %token                  TOK_STACKING                "stacking"
550 %token                  TOK_TABBED                  "tabbed"
551 %token  <number>        TOKSTACKLIMIT               "stack-limit"
552 %token                  TOK_POPUP_DURING_FULLSCREEN "popup_during_fullscreen"
553 %token                  TOK_IGNORE                  "ignore"
554 %token                  TOK_LEAVE_FULLSCREEN        "leave_fullscreen"
555 %token                  TOK_FOR_WINDOW              "for_window"
556
557 %token              TOK_MARK            "mark"
558 %token              TOK_CLASS           "class"
559 %token              TOK_INSTANCE        "instance"
560 %token              TOK_ID              "id"
561 %token              TOK_CON_ID          "con_id"
562 %token              TOK_TITLE           "title"
563
564 %type   <binding>       binding
565 %type   <binding>       bindcode
566 %type   <binding>       bindsym
567 %type   <number>        binding_modifiers
568 %type   <number>        binding_modifier
569 %type   <number>        direction
570 %type   <number>        layout_mode
571 %type   <number>        border_style
572 %type   <number>        new_window
573 %type   <number>        colorpixel
574 %type   <number>        bool
575 %type   <number>        popup_setting
576 %type   <string>        command
577 %type   <string>        word_or_number
578 %type   <string>        optional_workspace_name
579 %type   <string>        workspace_name
580 %type   <string>        window_class
581
582 %%
583
584 lines: /* empty */
585     | lines error
586     | lines line
587     ;
588
589 line:
590     bindline
591     | for_window
592     | mode
593     | floating_modifier
594     | orientation
595     | workspace_layout
596     | new_window
597     | focus_follows_mouse
598     | force_focus_wrapping
599     | workspace_bar
600     | workspace
601     | assign
602     | ipcsocket
603     | restart_state
604     | exec
605     | exec_always
606     | single_color
607     | color
608     | terminal
609     | font
610     | comment
611     | popup_during_fullscreen
612     ;
613
614 comment:
615     TOKCOMMENT
616     ;
617
618 command:
619     STR
620     ;
621
622 bindline:
623     binding
624     {
625         TAILQ_INSERT_TAIL(bindings, $1, bindings);
626     }
627     ;
628
629 binding:
630     TOKBINDCODE bindcode         { $$ = $2; }
631     | TOKBINDSYM bindsym         { $$ = $2; }
632     ;
633
634 bindcode:
635     binding_modifiers NUMBER command
636     {
637         printf("\tFound keycode binding mod%d with key %d and command %s\n", $1, $2, $3);
638         Binding *new = scalloc(sizeof(Binding));
639
640         new->keycode = $2;
641         new->mods = $1;
642         new->command = $3;
643
644         $$ = new;
645     }
646     ;
647
648 bindsym:
649     binding_modifiers word_or_number command
650     {
651         printf("\tFound keysym binding mod%d with key %s and command %s\n", $1, $2, $3);
652         Binding *new = scalloc(sizeof(Binding));
653
654         new->symbol = $2;
655         new->mods = $1;
656         new->command = $3;
657
658         $$ = new;
659     }
660     ;
661
662 for_window:
663     TOK_FOR_WINDOW match command
664     {
665         if (match_is_empty(&current_match)) {
666             ELOG("Match is empty, ignoring this for_window statement\n");
667             break;
668         }
669         printf("\t should execute command %s for the criteria mentioned above\n", $3);
670         Assignment *assignment = scalloc(sizeof(Assignment));
671         assignment->type = A_COMMAND;
672         assignment->match = current_match;
673         assignment->dest.command = $3;
674         TAILQ_INSERT_TAIL(&assignments, assignment, assignments);
675     }
676     ;
677
678 match:
679     | matchstart criteria matchend
680     {
681         printf("match parsed\n");
682     }
683     ;
684
685 matchstart:
686     '['
687     {
688         printf("start\n");
689         match_init(&current_match);
690     }
691     ;
692
693 matchend:
694     ']'
695     {
696         printf("match specification finished\n");
697     }
698     ;
699
700 criteria:
701     criteria criterion
702     | criterion
703     ;
704
705 criterion:
706     TOK_CLASS '=' STR
707     {
708         printf("criteria: class = %s\n", $3);
709         current_match.class = $3;
710     }
711     | TOK_INSTANCE '=' STR
712     {
713         printf("criteria: instance = %s\n", $3);
714         current_match.instance = $3;
715     }
716     | TOK_CON_ID '=' STR
717     {
718         printf("criteria: id = %s\n", $3);
719         char *end;
720         long parsed = strtol($3, &end, 10);
721         if (parsed == LONG_MIN ||
722             parsed == LONG_MAX ||
723             parsed < 0 ||
724             (end && *end != '\0')) {
725             ELOG("Could not parse con id \"%s\"\n", $3);
726         } else {
727             current_match.con_id = (Con*)parsed;
728             printf("id as int = %p\n", current_match.con_id);
729         }
730     }
731     | TOK_ID '=' STR
732     {
733         printf("criteria: window id = %s\n", $3);
734         char *end;
735         long parsed = strtol($3, &end, 10);
736         if (parsed == LONG_MIN ||
737             parsed == LONG_MAX ||
738             parsed < 0 ||
739             (end && *end != '\0')) {
740             ELOG("Could not parse window id \"%s\"\n", $3);
741         } else {
742             current_match.id = parsed;
743             printf("window id as int = %d\n", current_match.id);
744         }
745     }
746     | TOK_MARK '=' STR
747     {
748         printf("criteria: mark = %s\n", $3);
749         current_match.mark = $3;
750     }
751     | TOK_TITLE '=' STR
752     {
753         printf("criteria: title = %s\n", $3);
754         current_match.title = $3;
755     }
756     ;
757
758
759
760 word_or_number:
761     WORD
762     | NUMBER
763     {
764         asprintf(&$$, "%d", $1);
765     }
766     ;
767
768 mode:
769     TOKMODE QUOTEDSTRING '{' modelines '}'
770     {
771         if (strcasecmp($2, "default") == 0) {
772             printf("You cannot use the name \"default\" for your mode\n");
773             exit(1);
774         }
775         printf("\t now in mode %s\n", $2);
776         printf("\t current bindings = %p\n", current_bindings);
777         Binding *binding;
778         TAILQ_FOREACH(binding, current_bindings, bindings) {
779             printf("got binding on mods %d, keycode %d, symbol %s, command %s\n",
780                             binding->mods, binding->keycode, binding->symbol, binding->command);
781         }
782
783         struct Mode *mode = scalloc(sizeof(struct Mode));
784         mode->name = $2;
785         mode->bindings = current_bindings;
786         current_bindings = NULL;
787         SLIST_INSERT_HEAD(&modes, mode, modes);
788     }
789     ;
790
791
792 modelines:
793     /* empty */
794     | modelines modeline
795     ;
796
797 modeline:
798     comment
799     | binding
800     {
801         if (current_bindings == NULL) {
802             current_bindings = scalloc(sizeof(struct bindings_head));
803             TAILQ_INIT(current_bindings);
804         }
805
806         TAILQ_INSERT_TAIL(current_bindings, $1, bindings);
807     }
808     ;
809
810 floating_modifier:
811     TOKFLOATING_MODIFIER binding_modifiers
812     {
813         DLOG("floating modifier = %d\n", $2);
814         config.floating_modifier = $2;
815     }
816     ;
817
818 orientation:
819     TOK_ORIENTATION direction
820     {
821         DLOG("New containers should start with split direction %d\n", $2);
822         config.default_orientation = $2;
823     }
824     ;
825
826 direction:
827     TOK_HORIZ       { $$ = HORIZ; }
828     | TOK_VERT      { $$ = VERT; }
829     | TOK_AUTO      { $$ = NO_ORIENTATION; }
830     ;
831
832 workspace_layout:
833     TOK_WORKSPACE_LAYOUT layout_mode
834     {
835         DLOG("new containers will be in mode %d\n", $2);
836         config.default_layout = $2;
837
838 #if 0
839         /* We also need to change the layout of the already existing
840          * workspaces here. Workspaces may exist at this point because
841          * of the other directives which are modifying workspaces
842          * (setting the preferred screen or name). While the workspace
843          * objects are already created, they have never been used.
844          * Thus, the user very likely awaits the default container mode
845          * to trigger in this case, regardless of where it is inside
846          * his configuration file. */
847         Workspace *ws;
848         TAILQ_FOREACH(ws, workspaces, workspaces) {
849                 if (ws->table == NULL)
850                         continue;
851                 switch_layout_mode(global_conn,
852                                    ws->table[0][0],
853                                    config.container_mode);
854         }
855 #endif
856     }
857     | TOK_WORKSPACE_LAYOUT TOKSTACKLIMIT TOKSTACKLIMIT NUMBER
858     {
859         DLOG("stack-limit %d with val %d\n", $3, $4);
860         config.container_stack_limit = $3;
861         config.container_stack_limit_value = $4;
862
863 #if 0
864         /* See the comment above */
865         Workspace *ws;
866         TAILQ_FOREACH(ws, workspaces, workspaces) {
867                 if (ws->table == NULL)
868                         continue;
869                 Container *con = ws->table[0][0];
870                 con->stack_limit = config.container_stack_limit;
871                 con->stack_limit_value = config.container_stack_limit_value;
872         }
873 #endif
874     }
875     ;
876
877 layout_mode:
878     TOK_DEFAULT       { $$ = L_DEFAULT; }
879     | TOK_STACKING    { $$ = L_STACKED; }
880     | TOK_TABBED      { $$ = L_TABBED; }
881     ;
882
883 new_window:
884     TOKNEWWINDOW border_style
885     {
886         DLOG("new windows should start with border style %d\n", $2);
887         config.default_border = $2;
888     }
889     ;
890
891 border_style:
892     TOK_NORMAL      { $$ = BS_NORMAL; }
893     | TOK_NONE      { $$ = BS_NONE; }
894     | TOK_1PIXEL    { $$ = BS_1PIXEL; }
895     ;
896
897 bool:
898     NUMBER
899     {
900         $$ = ($1 == 1);
901     }
902     | WORD
903     {
904         DLOG("checking word \"%s\"\n", $1);
905         $$ = (strcasecmp($1, "yes") == 0 ||
906               strcasecmp($1, "true") == 0 ||
907               strcasecmp($1, "on") == 0 ||
908               strcasecmp($1, "enable") == 0 ||
909               strcasecmp($1, "active") == 0);
910     }
911     ;
912
913 focus_follows_mouse:
914     TOKFOCUSFOLLOWSMOUSE bool
915     {
916         DLOG("focus follows mouse = %d\n", $2);
917         config.disable_focus_follows_mouse = !($2);
918     }
919     ;
920
921 force_focus_wrapping:
922     TOK_FORCE_FOCUS_WRAPPING bool
923     {
924         DLOG("force focus wrapping = %d\n", $2);
925         config.force_focus_wrapping = $2;
926     }
927     ;
928
929 workspace_bar:
930     TOKWORKSPACEBAR bool
931     {
932         DLOG("workspace bar = %d\n", $2);
933         config.disable_workspace_bar = !($2);
934     }
935     ;
936
937 workspace:
938     TOKWORKSPACE NUMBER TOKOUTPUT OUTPUT optional_workspace_name
939     {
940         int ws_num = $2;
941         if (ws_num < 1) {
942             DLOG("Invalid workspace assignment, workspace number %d out of range\n", ws_num);
943         } else {
944             char *ws_name = NULL;
945             if ($5 == NULL) {
946                 asprintf(&ws_name, "%d", ws_num);
947             } else {
948                 ws_name = $5;
949             }
950
951             DLOG("Should assign workspace %s to output %s\n", ws_name, $4);
952             /* Check for earlier assignments of the same workspace so that we
953              * don’t have assignments of a single workspace to different
954              * outputs */
955             struct Workspace_Assignment *assignment;
956             bool duplicate = false;
957             TAILQ_FOREACH(assignment, &ws_assignments, ws_assignments) {
958                 if (strcasecmp(assignment->name, ws_name) == 0) {
959                     ELOG("You have a duplicate workspace assignment for workspace \"%s\"\n",
960                          ws_name);
961                     assignment->output = $4;
962                     duplicate = true;
963                 }
964             }
965             if (!duplicate) {
966                 assignment = scalloc(sizeof(struct Workspace_Assignment));
967                 assignment->name = ws_name;
968                 assignment->output = $4;
969                 TAILQ_INSERT_TAIL(&ws_assignments, assignment, ws_assignments);
970             }
971         }
972     }
973     | TOKWORKSPACE NUMBER workspace_name
974     {
975         int ws_num = $2;
976         if (ws_num < 1) {
977             DLOG("Invalid workspace assignment, workspace number %d out of range\n", ws_num);
978         } else {
979             DLOG("workspace name to: %s\n", $3);
980 #if 0
981             if ($<string>3 != NULL) {
982                     workspace_set_name(workspace_get(ws_num - 1), $<string>3);
983                     free($<string>3);
984             }
985 #endif
986         }
987     }
988     ;
989
990 optional_workspace_name:
991     /* empty */          { $$ = NULL; }
992     | workspace_name     { $$ = $1; }
993     ;
994
995 workspace_name:
996     QUOTEDSTRING         { $$ = $1; }
997     | STR                { $$ = $1; }
998     | WORD               { $$ = $1; }
999     ;
1000
1001 assign:
1002     TOKASSIGN window_class STR
1003     {
1004         printf("assignment of %s to *%s*\n", $2, $3);
1005         char *workspace = $3;
1006         char *criteria = $2;
1007
1008         Assignment *assignment = scalloc(sizeof(Assignment));
1009         Match *match = &(assignment->match);
1010         match_init(match);
1011
1012         char *separator = NULL;
1013         if ((separator = strchr(criteria, '/')) != NULL) {
1014             *(separator++) = '\0';
1015             match->title = sstrdup(separator);
1016         }
1017         if (*criteria != '\0')
1018             match->class = sstrdup(criteria);
1019         free(criteria);
1020
1021         printf("  class = %s\n", match->class);
1022         printf("  title = %s\n", match->title);
1023
1024         /* Compatibility with older versions: If the assignment target starts
1025          * with ~, we create the equivalent of:
1026          *
1027          * for_window [class="foo"] floating enable
1028          */
1029         if (*workspace == '~') {
1030             workspace++;
1031             if (*workspace == '\0') {
1032                 /* This assignment was *only* for floating */
1033                 assignment->type = A_COMMAND;
1034                 assignment->dest.command = sstrdup("floating enable");
1035                 TAILQ_INSERT_TAIL(&assignments, assignment, assignments);
1036                 break;
1037             } else {
1038                 /* Create a new assignment and continue afterwards */
1039                 Assignment *floating = scalloc(sizeof(Assignment));
1040                 match_copy(&(floating->match), match);
1041                 floating->type = A_COMMAND;
1042                 floating->dest.command = sstrdup("floating enable");
1043                 TAILQ_INSERT_TAIL(&assignments, floating, assignments);
1044             }
1045         }
1046
1047         assignment->type = A_TO_WORKSPACE;
1048         assignment->dest.workspace = workspace;
1049         TAILQ_INSERT_TAIL(&assignments, assignment, assignments);
1050     }
1051     ;
1052
1053 window_class:
1054     QUOTEDSTRING
1055     | STR_NG
1056     ;
1057
1058 ipcsocket:
1059     TOKIPCSOCKET STR
1060     {
1061         config.ipc_socket_path = $2;
1062     }
1063     ;
1064
1065 restart_state:
1066     TOKRESTARTSTATE STR
1067     {
1068         config.restart_state_path = $2;
1069     }
1070     ;
1071
1072 exec:
1073     TOKEXEC STR
1074     {
1075         struct Autostart *new = smalloc(sizeof(struct Autostart));
1076         new->command = $2;
1077         TAILQ_INSERT_TAIL(&autostarts, new, autostarts);
1078     }
1079     ;
1080
1081 exec_always:
1082     TOKEXEC_ALWAYS STR
1083     {
1084         struct Autostart *new = smalloc(sizeof(struct Autostart));
1085         new->command = $2;
1086         TAILQ_INSERT_TAIL(&autostarts_always, new, autostarts_always);
1087     }
1088     ;
1089
1090 terminal:
1091     TOKTERMINAL STR
1092     {
1093         ELOG("The terminal option is DEPRECATED and has no effect. "
1094             "Please remove it from your configuration file.\n");
1095     }
1096     ;
1097
1098 font:
1099     TOKFONT STR
1100     {
1101         config.font = load_font($2, true);
1102         printf("font %s\n", $2);
1103         free($2);
1104     }
1105     ;
1106
1107 single_color:
1108     TOKSINGLECOLOR colorpixel
1109     {
1110         uint32_t *dest = $1;
1111         *dest = $2;
1112     }
1113     ;
1114
1115 color:
1116     TOKCOLOR colorpixel colorpixel colorpixel
1117     {
1118         struct Colortriple *dest = $1;
1119
1120         dest->border = $2;
1121         dest->background = $3;
1122         dest->text = $4;
1123     }
1124     ;
1125
1126 colorpixel:
1127     '#' HEX
1128     {
1129         char *hex;
1130         if (asprintf(&hex, "#%s", $2) == -1)
1131             die("asprintf()");
1132         free($2);
1133         $$ = get_colorpixel(hex);
1134         free(hex);
1135     }
1136     ;
1137
1138
1139 binding_modifiers:
1140     /* NULL */                               { $$ = 0; }
1141     | binding_modifier
1142     | binding_modifiers '+' binding_modifier { $$ = $1 | $3; }
1143     | binding_modifiers '+'                  { $$ = $1; }
1144     ;
1145
1146 binding_modifier:
1147     MODIFIER        { $$ = $1; }
1148     | TOKCONTROL    { $$ = BIND_CONTROL; }
1149     | TOKSHIFT      { $$ = BIND_SHIFT; }
1150     ;
1151
1152 popup_during_fullscreen:
1153     TOK_POPUP_DURING_FULLSCREEN popup_setting
1154     {
1155         DLOG("popup_during_fullscreen setting: %d\n", $2);
1156         config.popup_during_fullscreen = $2;
1157     }
1158     ;
1159
1160 popup_setting:
1161     TOK_IGNORE              { $$ = PDF_IGNORE; }
1162     | TOK_LEAVE_FULLSCREEN  { $$ = PDF_LEAVE_FULLSCREEN; }
1163     ;