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