2 #define I3__FILE__ "config_parser.c"
4 * vim:ts=4:sw=4:expandtab
6 * i3 - an improved dynamic tiling window manager
7 * © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
9 * config_parser.c: hand-written parser to parse configuration directives.
11 * See also src/commands_parser.c for rationale on why we use a custom parser.
13 * This parser works VERY MUCH like src/commands_parser.c, so read that first.
14 * The differences are:
16 * 1. config_parser supports the 'number' token type (in addition to 'word' and
17 * 'string'). Numbers are referred to using &num (like $str).
19 * 2. Criteria are not executed immediately, they are just stored.
21 * 3. config_parser recognizes \n and \r as 'end' token, while commands_parser
24 * 4. config_parser skips the current line on invalid inputs and follows the
25 * nearest <error> token.
34 #include <sys/types.h>
41 // Macros to make the YAJL API a bit easier to use.
42 #define y(x, ...) yajl_gen_ ## x (command_output.json_gen, ##__VA_ARGS__)
43 #define ystr(str) yajl_gen_string(command_output.json_gen, (unsigned char*)str, strlen(str))
46 static pid_t configerror_pid = -1;
47 /* The path to the temporary script files used by i3-nagbar. We need to keep
48 * them around to delete the files in the i3-nagbar SIGCHLD handler. */
49 static char *edit_script_path, *pager_script_path;
50 static struct context *context;
53 /*******************************************************************************
54 * The data structures used for parsing. Essentially the current state and a
55 * list of tokens for that state.
57 * The GENERATED_* files are generated by generate-commands-parser.pl with the
58 * input parser-specs/configs.spec.
59 ******************************************************************************/
61 #include "GENERATED_config_enums.h"
63 typedef struct token {
66 /* This might be __CALL */
67 cmdp_state next_state;
69 uint16_t call_identifier;
73 typedef struct tokenptr {
78 #include "GENERATED_config_tokens.h"
80 /*******************************************************************************
81 * The (small) stack where identified literals are stored during the parsing
82 * of a single command (like $workspace).
83 ******************************************************************************/
86 /* Just a pointer, not dynamically allocated. */
87 const char *identifier;
98 /* 10 entries should be enough for everybody. */
99 static struct stack_entry stack[10];
102 * Pushes a string (identified by 'identifier') on the stack. We simply use a
103 * single array, since the number of entries we have to store is very small.
106 static void push_string(const char *identifier, const char *str) {
107 for (int c = 0; c < 10; c++) {
108 if (stack[c].identifier != NULL &&
109 strcmp(stack[c].identifier, identifier) != 0)
111 if (stack[c].identifier == NULL) {
112 /* Found a free slot, let’s store it here. */
113 stack[c].identifier = identifier;
114 stack[c].val.str = sstrdup(str);
115 stack[c].type = STACK_STR;
117 /* Append the value. */
118 char *prev = stack[c].val.str;
119 sasprintf(&(stack[c].val.str), "%s,%s", prev, str);
125 /* When we arrive here, the stack is full. This should not happen and
126 * means there’s either a bug in this parser or the specification
127 * contains a command with more than 10 identified tokens. */
128 fprintf(stderr, "BUG: commands_parser stack full. This means either a bug "
129 "in the code, or a new command which contains more than "
130 "10 identified tokens.\n");
134 static void push_long(const char *identifier, long num) {
135 for (int c = 0; c < 10; c++) {
136 if (stack[c].identifier != NULL)
138 /* Found a free slot, let’s store it here. */
139 stack[c].identifier = identifier;
140 stack[c].val.num = num;
141 stack[c].type = STACK_LONG;
145 /* When we arrive here, the stack is full. This should not happen and
146 * means there’s either a bug in this parser or the specification
147 * contains a command with more than 10 identified tokens. */
148 fprintf(stderr, "BUG: commands_parser stack full. This means either a bug "
149 "in the code, or a new command which contains more than "
150 "10 identified tokens.\n");
155 static const char *get_string(const char *identifier) {
156 for (int c = 0; c < 10; c++) {
157 if (stack[c].identifier == NULL)
159 if (strcmp(identifier, stack[c].identifier) == 0)
160 return stack[c].val.str;
165 static const long get_long(const char *identifier) {
166 for (int c = 0; c < 10; c++) {
167 if (stack[c].identifier == NULL)
169 if (strcmp(identifier, stack[c].identifier) == 0)
170 return stack[c].val.num;
175 static void clear_stack(void) {
176 for (int c = 0; c < 10; c++) {
177 if (stack[c].type == STACK_STR && stack[c].val.str != NULL)
178 free(stack[c].val.str);
179 stack[c].identifier = NULL;
180 stack[c].val.str = NULL;
181 stack[c].val.num = 0;
185 // TODO: remove this if it turns out we don’t need it for testing.
187 /*******************************************************************************
188 * A dynamically growing linked list which holds the criteria for the current
190 ******************************************************************************/
192 typedef struct criterion {
196 TAILQ_ENTRY(criterion) criteria;
199 static TAILQ_HEAD(criteria_head, criterion) criteria =
200 TAILQ_HEAD_INITIALIZER(criteria);
203 * Stores the given type/value in the list of criteria.
204 * Accepts a pointer as first argument, since it is 'call'ed by the parser.
207 static void push_criterion(void *unused_criteria, const char *type,
209 struct criterion *criterion = malloc(sizeof(struct criterion));
210 criterion->type = strdup(type);
211 criterion->value = strdup(value);
212 TAILQ_INSERT_TAIL(&criteria, criterion, criteria);
216 * Clears the criteria linked list.
217 * Accepts a pointer as first argument, since it is 'call'ed by the parser.
220 static void clear_criteria(void *unused_criteria) {
221 struct criterion *criterion;
222 while (!TAILQ_EMPTY(&criteria)) {
223 criterion = TAILQ_FIRST(&criteria);
224 free(criterion->type);
225 free(criterion->value);
226 TAILQ_REMOVE(&criteria, criterion, criteria);
232 /*******************************************************************************
234 ******************************************************************************/
236 static cmdp_state state;
237 static Match current_match;
238 static struct ConfigResult subcommand_output;
239 static struct ConfigResult command_output;
241 /* A list which contains the states that lead to the current state, e.g.
242 * INITIAL, WORKSPACE_LAYOUT.
243 * When jumping back to INITIAL, statelist_idx will simply be set to 1
244 * (likewise for other states, e.g. MODE or BAR).
245 * This list is used to process the nearest error token. */
246 static cmdp_state statelist[10] = { INITIAL };
247 /* NB: statelist_idx points to where the next entry will be inserted */
248 static int statelist_idx = 1;
250 #include "GENERATED_config_call.h"
253 static void next_state(const cmdp_token *token) {
254 cmdp_state _next_state = token->next_state;
256 //printf("token = name %s identifier %s\n", token->name, token->identifier);
257 //printf("next_state = %d\n", token->next_state);
258 if (token->next_state == __CALL) {
259 subcommand_output.json_gen = command_output.json_gen;
260 GENERATED_call(token->extra.call_identifier, &subcommand_output);
261 _next_state = subcommand_output.next_state;
266 if (state == INITIAL) {
270 /* See if we are jumping back to a state in which we were in previously
271 * (statelist contains INITIAL) and just move statelist_idx accordingly. */
272 for (int i = 0; i < statelist_idx; i++) {
273 if (statelist[i] != _next_state)
279 /* Otherwise, the state is new and we add it to the list */
280 statelist[statelist_idx++] = _next_state;
284 * Returns a pointer to the start of the line (one byte after the previous \r,
285 * \n) or the start of the input, if this is the first line.
288 static const char *start_of_line(const char *walk, const char *beginning) {
289 while (*walk != '\n' && *walk != '\r' && walk >= beginning) {
297 * Copies the line and terminates it at the next \n, if any.
299 * The caller has to free() the result.
302 static char *single_line(const char *start) {
303 char *result = sstrdup(start);
304 char *end = strchr(result, '\n');
310 struct ConfigResult *parse_config(const char *input, struct context *context) {
311 /* Dump the entire config file into the debug log. We cannot just use
312 * DLOG("%s", input); because one log message must not exceed 4 KiB. */
313 const char *dumpwalk = input;
315 while (*dumpwalk != '\0') {
316 char *next_nl = strchr(dumpwalk, '\n');
317 if (next_nl != NULL) {
318 DLOG("CONFIG(line %3d): %.*s\n", linecnt, (int)(next_nl - dumpwalk), dumpwalk);
319 dumpwalk = next_nl + 1;
321 DLOG("CONFIG(line %3d): %s\n", linecnt, dumpwalk);
329 /* A YAJL JSON generator used for formatting replies. */
331 command_output.json_gen = yajl_gen_alloc(NULL);
333 command_output.json_gen = yajl_gen_alloc(NULL, NULL);
338 const char *walk = input;
339 const size_t len = strlen(input);
341 const cmdp_token *token;
345 // TODO: make this testable
347 cfg_criteria_init(¤t_match, &subcommand_output, INITIAL);
350 /* The "<=" operator is intentional: We also handle the terminating 0-byte
351 * explicitly by looking for an 'end' token. */
352 while ((walk - input) <= len) {
353 /* Skip whitespace before every token, newlines are relevant since they
354 * separate configuration directives. */
355 while ((*walk == ' ' || *walk == '\t') && *walk != '\0')
358 //printf("remaining input: %s\n", walk);
360 cmdp_token_ptr *ptr = &(tokens[state]);
361 token_handled = false;
362 for (c = 0; c < ptr->n; c++) {
363 token = &(ptr->array[c]);
366 if (token->name[0] == '\'') {
367 if (strncasecmp(walk, token->name + 1, strlen(token->name) - 1) == 0) {
368 if (token->identifier != NULL)
369 push_string(token->identifier, token->name + 1);
370 walk += strlen(token->name) - 1;
372 token_handled = true;
378 if (strcmp(token->name, "number") == 0) {
379 /* Handle numbers. We only accept decimal numbers for now. */
382 long int num = strtol(walk, &end, 10);
383 if ((errno == ERANGE && (num == LONG_MIN || num == LONG_MAX)) ||
384 (errno != 0 && num == 0))
387 /* No valid numbers found */
391 if (token->identifier != NULL)
392 push_long(token->identifier, num);
394 /* Set walk to the first non-number character */
397 token_handled = true;
401 if (strcmp(token->name, "string") == 0 ||
402 strcmp(token->name, "word") == 0) {
403 const char *beginning = walk;
404 /* Handle quoted strings (or words). */
408 while (*walk != '\0' && (*walk != '"' || *(walk-1) == '\\'))
411 if (token->name[0] == 's') {
412 while (*walk != '\0' && *walk != '\r' && *walk != '\n')
415 /* For a word, the delimiters are white space (' ' or
416 * '\t'), closing square bracket (]), comma (,) and
418 while (*walk != ' ' && *walk != '\t' &&
419 *walk != ']' && *walk != ',' &&
420 *walk != ';' && *walk != '\r' &&
421 *walk != '\n' && *walk != '\0')
425 if (walk != beginning) {
426 char *str = scalloc(walk-beginning + 1);
427 /* We copy manually to handle escaping of characters. */
429 for (inpos = 0, outpos = 0;
430 inpos < (walk-beginning);
432 /* We only handle escaped double quotes to not break
433 * backwards compatibility with people using \w in
434 * regular expressions etc. */
435 if (beginning[inpos] == '\\' && beginning[inpos+1] == '"')
437 str[outpos] = beginning[inpos];
439 if (token->identifier)
440 push_string(token->identifier, str);
442 /* If we are at the end of a quoted string, skip the ending
447 token_handled = true;
452 if (strcmp(token->name, "end") == 0) {
453 //printf("checking for end: *%s*\n", walk);
454 if (*walk == '\0' || *walk == '\n' || *walk == '\r') {
456 token_handled = true;
457 /* To make sure we start with an appropriate matching
458 * datastructure for commands which do *not* specify any
459 * criteria, we re-initialize the criteria system after
461 // TODO: make this testable
463 cfg_criteria_init(¤t_match, &subcommand_output, INITIAL);
472 if (!token_handled) {
473 /* Figure out how much memory we will need to fill in the names of
474 * all tokens afterwards. */
476 for (c = 0; c < ptr->n; c++)
477 tokenlen += strlen(ptr->array[c].name) + strlen("'', ");
479 /* Build up a decent error message. We include the problem, the
480 * full input, and underline the position where the parser
483 char *possible_tokens = smalloc(tokenlen + 1);
484 char *tokenwalk = possible_tokens;
485 for (c = 0; c < ptr->n; c++) {
486 token = &(ptr->array[c]);
487 if (token->name[0] == '\'') {
488 /* A literal is copied to the error message enclosed with
491 strcpy(tokenwalk, token->name + 1);
492 tokenwalk += strlen(token->name + 1);
495 /* Skip error tokens in error messages, they are used
496 * internally only and might confuse users. */
497 if (strcmp(token->name, "error") == 0)
499 /* Any other token is copied to the error message enclosed
500 * with angle brackets. */
502 strcpy(tokenwalk, token->name);
503 tokenwalk += strlen(token->name);
506 if (c < (ptr->n - 1)) {
512 sasprintf(&errormessage, "Expected one of these tokens: %s",
514 free(possible_tokens);
517 /* Go back to the beginning of the line */
518 const char *error_line = start_of_line(walk, input);
520 /* Contains the same amount of characters as 'input' has, but with
521 * the unparseable part highlighted using ^ characters. */
522 char *position = scalloc(strlen(error_line) + 1);
523 const char *copywalk;
524 for (copywalk = error_line;
525 *copywalk != '\n' && *copywalk != '\r' && *copywalk != '\0';
527 position[(copywalk - error_line)] = (copywalk >= walk ? '^' : (*copywalk == '\t' ? '\t' : ' '));
528 position[(copywalk - error_line)] = '\0';
530 ELOG("CONFIG: %s\n", errormessage);
531 ELOG("CONFIG: (in file %s)\n", context->filename);
532 char *error_copy = single_line(error_line);
534 /* Print context lines *before* the error, if any. */
536 const char *context_p1_start = start_of_line(error_line-2, input);
537 char *context_p1_line = single_line(context_p1_start);
539 const char *context_p2_start = start_of_line(context_p1_start-2, input);
540 char *context_p2_line = single_line(context_p2_start);
541 ELOG("CONFIG: Line %3d: %s\n", linecnt - 2, context_p2_line);
542 free(context_p2_line);
544 ELOG("CONFIG: Line %3d: %s\n", linecnt - 1, context_p1_line);
545 free(context_p1_line);
547 ELOG("CONFIG: Line %3d: %s\n", linecnt, error_copy);
548 ELOG("CONFIG: %s\n", position);
550 /* Print context lines *after* the error, if any. */
551 for (int i = 0; i < 2; i++) {
552 char *error_line_end = strchr(error_line, '\n');
553 if (error_line_end != NULL && *(error_line_end + 1) != '\0') {
554 error_line = error_line_end + 1;
555 error_copy = single_line(error_line);
556 ELOG("CONFIG: Line %3d: %s\n", linecnt + i + 1, error_copy);
561 context->has_errors = true;
563 /* Format this error message as a JSON reply. */
567 /* We set parse_error to true to distinguish this from other
568 * errors. i3-nagbar is spawned upon keypresses only for parser
576 ystr("errorposition");
580 /* Skip the rest of this line, but continue parsing. */
581 while ((walk - input) <= len && *walk != '\n')
588 /* To figure out in which state to go (e.g. MODE or INITIAL),
589 * we find the nearest state which contains an <error> token
590 * and follow that one. */
591 bool error_token_found = false;
592 for (int i = statelist_idx-1; (i >= 0) && !error_token_found; i--) {
593 cmdp_token_ptr *errptr = &(tokens[statelist[i]]);
594 for (int j = 0; j < errptr->n; j++) {
595 if (strcmp(errptr->array[j].name, "error") != 0)
597 next_state(&(errptr->array[j]));
598 error_token_found = true;
603 assert(error_token_found);
609 return &command_output;
612 /*******************************************************************************
613 * Code for building the stand-alone binary test.commands_parser which is used
614 * by t/187-commands-parser.t.
615 ******************************************************************************/
620 * Logs the given message to stdout while prefixing the current time to it,
621 * but only if debug logging was activated.
622 * This is to be called by DLOG() which includes filename/linenumber
625 void debuglog(char *fmt, ...) {
629 fprintf(stdout, "# ");
630 vfprintf(stdout, fmt, args);
634 void errorlog(char *fmt, ...) {
638 vfprintf(stderr, fmt, args);
642 static int criteria_next_state;
644 void cfg_criteria_init(I3_CFG, int _state) {
645 criteria_next_state = _state;
648 void cfg_criteria_add(I3_CFG, const char *ctype, const char *cvalue) {
651 void cfg_criteria_pop_state(I3_CFG) {
652 result->next_state = criteria_next_state;
655 int main(int argc, char *argv[]) {
657 fprintf(stderr, "Syntax: %s <command>\n", argv[0]);
660 struct context context;
661 context.filename = "<stdin>";
662 parse_config(argv[1], &context);
668 * Writes the given command as a shell script to path.
669 * Returns true unless something went wrong.
672 static bool write_nagbar_script(const char *path, const char *command) {
673 int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IXUSR);
675 warn("Could not create temporary script to store the nagbar command");
678 write(fd, "#!/bin/sh\n", strlen("#!/bin/sh\n"));
679 write(fd, command, strlen(command));
685 * Handler which will be called when we get a SIGCHLD for the nagbar, meaning
686 * it exited (or could not be started, depending on the exit code).
689 static void nagbar_exited(EV_P_ ev_child *watcher, int revents) {
690 ev_child_stop(EV_A_ watcher);
692 if (unlink(edit_script_path) != 0)
693 warn("Could not delete temporary i3-nagbar script %s", edit_script_path);
694 if (unlink(pager_script_path) != 0)
695 warn("Could not delete temporary i3-nagbar script %s", pager_script_path);
697 if (!WIFEXITED(watcher->rstatus)) {
698 fprintf(stderr, "ERROR: i3-nagbar did not exit normally.\n");
702 int exitcode = WEXITSTATUS(watcher->rstatus);
703 printf("i3-nagbar process exited with status %d\n", exitcode);
705 fprintf(stderr, "ERROR: i3-nagbar could not be found. Is it correctly installed on your system?\n");
708 configerror_pid = -1;
711 /* We need ev >= 4 for the following code. Since it is not *that* important (it
712 * only makes sure that there are no i3-nagbar instances left behind) we still
713 * support old systems with libev 3. */
714 #if EV_VERSION_MAJOR >= 4
716 * Cleanup handler. Will be called when i3 exits. Kills i3-nagbar with signal
717 * SIGKILL (9) to make sure there are no left-over i3-nagbar processes.
720 static void nagbar_cleanup(EV_P_ ev_cleanup *watcher, int revent) {
721 if (configerror_pid != -1) {
722 LOG("Sending SIGKILL (9) to i3-nagbar with PID %d\n", configerror_pid);
723 kill(configerror_pid, SIGKILL);
729 * Kills the configerror i3-nagbar process, if any.
731 * Called when reloading/restarting.
733 * If wait_for_it is set (restarting), this function will waitpid(), otherwise,
734 * ev is assumed to handle it (reloading).
737 void kill_configerror_nagbar(bool wait_for_it) {
738 if (configerror_pid == -1)
741 if (kill(configerror_pid, SIGTERM) == -1)
742 warn("kill(configerror_nagbar) failed");
747 /* When restarting, we don’t enter the ev main loop anymore and after the
748 * exec(), our old pid is no longer watched. So, ev won’t handle SIGCHLD
749 * for us and we would end up with a <defunct> process. Therefore we
751 waitpid(configerror_pid, NULL, 0);
755 * Goes through each line of buf (separated by \n) and checks for statements /
756 * commands which only occur in i3 v4 configuration files. If it finds any, it
757 * returns version 4, otherwise it returns version 3.
760 static int detect_version(char *buf) {
763 while (*walk != '\0') {
769 /* check for some v4-only statements */
770 if (strncasecmp(line, "bindcode", strlen("bindcode")) == 0 ||
771 strncasecmp(line, "force_focus_wrapping", strlen("force_focus_wrapping")) == 0 ||
772 strncasecmp(line, "# i3 config file (v4)", strlen("# i3 config file (v4)")) == 0 ||
773 strncasecmp(line, "workspace_layout", strlen("workspace_layout")) == 0) {
774 printf("deciding for version 4 due to this line: %.*s\n", (int)(walk-line), line);
778 /* if this is a bind statement, we can check the command */
779 if (strncasecmp(line, "bind", strlen("bind")) == 0) {
780 char *bind = strchr(line, ' ');
783 while ((*bind == ' ' || *bind == '\t') && *bind != '\0')
787 if ((bind = strchr(bind, ' ')) == NULL)
789 while ((*bind == ' ' || *bind == '\t') && *bind != '\0')
793 if (strncasecmp(bind, "layout", strlen("layout")) == 0 ||
794 strncasecmp(bind, "floating", strlen("floating")) == 0 ||
795 strncasecmp(bind, "workspace", strlen("workspace")) == 0 ||
796 strncasecmp(bind, "focus left", strlen("focus left")) == 0 ||
797 strncasecmp(bind, "focus right", strlen("focus right")) == 0 ||
798 strncasecmp(bind, "focus up", strlen("focus up")) == 0 ||
799 strncasecmp(bind, "focus down", strlen("focus down")) == 0 ||
800 strncasecmp(bind, "border normal", strlen("border normal")) == 0 ||
801 strncasecmp(bind, "border 1pixel", strlen("border 1pixel")) == 0 ||
802 strncasecmp(bind, "border pixel", strlen("border pixel")) == 0 ||
803 strncasecmp(bind, "border borderless", strlen("border borderless")) == 0 ||
804 strncasecmp(bind, "--no-startup-id", strlen("--no-startup-id")) == 0 ||
805 strncasecmp(bind, "bar", strlen("bar")) == 0) {
806 printf("deciding for version 4 due to this line: %.*s\n", (int)(walk-line), line);
812 /* advance to the next line */
821 * Calls i3-migrate-config-to-v4 to migrate a configuration file (input
824 * Returns the converted config file or NULL if there was an error (for
825 * example the script could not be found in $PATH or the i3 executable’s
829 static char *migrate_config(char *input, off_t size) {
833 if (pipe(writepipe) != 0 ||
834 pipe(readpipe) != 0) {
835 warn("migrate_config: Could not create pipes");
841 warn("Could not fork()");
847 /* close writing end of writepipe, connect reading side to stdin */
849 dup2(writepipe[0], 0);
851 /* close reading end of readpipe, connect writing side to stdout */
853 dup2(readpipe[1], 1);
855 static char *argv[] = {
856 NULL, /* will be replaced by the executable path */
859 exec_i3_utility("i3-migrate-config-to-v4", argv);
864 /* close reading end of the writepipe (connected to the script’s stdin) */
867 /* write the whole config file to the pipe, the script will read everything
871 while (written < size) {
872 if ((ret = write(writepipe[1], input + written, size - written)) < 0) {
873 warn("Could not write to pipe");
880 /* close writing end of the readpipe (connected to the script’s stdout) */
883 /* read the script’s output */
884 int conv_size = 65535;
885 char *converted = malloc(conv_size);
888 if (read_bytes == conv_size) {
890 converted = realloc(converted, conv_size);
892 ret = read(readpipe[0], converted + read_bytes, conv_size - read_bytes);
894 warn("Cannot read from pipe");
901 /* get the returncode */
904 if (!WIFEXITED(status)) {
905 fprintf(stderr, "Child did not terminate normally, using old config file (will lead to broken behaviour)\n");
909 int returncode = WEXITSTATUS(status);
910 if (returncode != 0) {
911 fprintf(stderr, "Migration process exit code was != 0\n");
912 if (returncode == 2) {
913 fprintf(stderr, "could not start the migration script\n");
914 /* TODO: script was not found. tell the user to fix his system or create a v4 config */
915 } else if (returncode == 1) {
916 fprintf(stderr, "This already was a v4 config. Please add the following line to your config file:\n");
917 fprintf(stderr, "# i3 config file (v4)\n");
918 /* TODO: nag the user with a message to include a hint for i3 in his config file */
927 * Checks for duplicate key bindings (the same keycode or keysym is configured
928 * more than once). If a duplicate binding is found, a message is printed to
929 * stderr and the has_errors variable is set to true, which will start
933 static void check_for_duplicate_bindings(struct context *context) {
934 Binding *bind, *current;
935 TAILQ_FOREACH(current, bindings, bindings) {
936 TAILQ_FOREACH(bind, bindings, bindings) {
937 /* Abort when we reach the current keybinding, only check the
942 /* Check if one is using keysym while the other is using bindsym.
944 /* XXX: It should be checked at a later place (when translating the
945 * keysym to keycodes) if there are any duplicates */
946 if ((bind->symbol == NULL && current->symbol != NULL) ||
947 (bind->symbol != NULL && current->symbol == NULL))
950 /* If bind is NULL, current has to be NULL, too (see above).
951 * If the keycodes differ, it can't be a duplicate. */
952 if (bind->symbol != NULL &&
953 strcasecmp(bind->symbol, current->symbol) != 0)
956 /* Check if the keycodes or modifiers are different. If so, they
957 * can't be duplicate */
958 if (bind->keycode != current->keycode ||
959 bind->mods != current->mods ||
960 bind->release != current->release)
963 context->has_errors = true;
964 if (current->keycode != 0) {
965 ELOG("Duplicate keybinding in config file:\n modmask %d with keycode %d, command \"%s\"\n",
966 current->mods, current->keycode, current->command);
968 ELOG("Duplicate keybinding in config file:\n modmask %d with keysym %s, command \"%s\"\n",
969 current->mods, current->symbol, current->command);
976 * Starts an i3-nagbar process which alerts the user that his configuration
977 * file contains one or more errors. Also offers two buttons: One to launch an
978 * $EDITOR on the config file and another one to launch a $PAGER on the error
982 static void start_configerror_nagbar(const char *config_path) {
983 if (only_check_config)
986 fprintf(stderr, "Starting i3-nagbar due to configuration errors\n");
988 /* We need to create a custom script containing our actual command
989 * since not every terminal emulator which is contained in
990 * i3-sensible-terminal supports -e with multiple arguments (and not
991 * all of them support -e with one quoted argument either).
993 * NB: The paths need to be unique, that is, don’t assume users close
994 * their nagbars at any point in time (and they still need to work).
996 edit_script_path = get_process_filename("nagbar-cfgerror-edit");
997 pager_script_path = get_process_filename("nagbar-cfgerror-pager");
999 configerror_pid = fork();
1000 if (configerror_pid == -1) {
1001 warn("Could not fork()");
1006 if (configerror_pid == 0) {
1007 char *edit_command, *pager_command;
1008 sasprintf(&edit_command, "i3-sensible-editor \"%s\" && i3-msg reload\n", config_path);
1009 sasprintf(&pager_command, "i3-sensible-pager \"%s\"\n", errorfilename);
1010 if (!write_nagbar_script(edit_script_path, edit_command) ||
1011 !write_nagbar_script(pager_script_path, pager_command))
1016 sasprintf(&editaction, "i3-sensible-terminal -e \"%s\"", edit_script_path);
1017 sasprintf(&pageraction, "i3-sensible-terminal -e \"%s\"", pager_script_path);
1019 NULL, /* will be replaced by the executable path */
1021 (context->has_errors ? "error" : "warning"),
1023 (context->has_errors ?
1024 "You have an error in your i3 config file!" :
1025 "Your config is outdated. Please fix the warnings to make sure everything works."),
1029 (errorfilename ? "-b" : NULL),
1030 (context->has_errors ? "show errors" : "show warnings"),
1034 exec_i3_utility("i3-nagbar", argv);
1038 /* install a child watcher */
1039 ev_child *child = smalloc(sizeof(ev_child));
1040 ev_child_init(child, &nagbar_exited, configerror_pid, 0);
1041 ev_child_start(main_loop, child);
1043 /* We need ev >= 4 for the following code. Since it is not *that* important (it
1044 * only makes sure that there are no i3-nagbar instances left behind) we still
1045 * support old systems with libev 3. */
1046 #if EV_VERSION_MAJOR >= 4
1047 /* install a cleanup watcher (will be called when i3 exits and i3-nagbar is
1049 ev_cleanup *cleanup = smalloc(sizeof(ev_cleanup));
1050 ev_cleanup_init(cleanup, nagbar_cleanup);
1051 ev_cleanup_start(main_loop, cleanup);
1057 void parse_file(const char *f) {
1058 SLIST_HEAD(variables_head, Variable) variables = SLIST_HEAD_INITIALIZER(&variables);
1059 int fd, ret, read_bytes = 0;
1063 char buffer[1026], key[512], value[512];
1065 if ((fd = open(f, O_RDONLY)) == -1)
1066 die("Could not open configuration file: %s\n", strerror(errno));
1068 if (fstat(fd, &stbuf) == -1)
1069 die("Could not fstat file: %s\n", strerror(errno));
1071 buf = scalloc((stbuf.st_size + 1) * sizeof(char));
1072 while (read_bytes < stbuf.st_size) {
1073 if ((ret = read(fd, buf + read_bytes, (stbuf.st_size - read_bytes))) < 0)
1074 die("Could not read(): %s\n", strerror(errno));
1078 if (lseek(fd, 0, SEEK_SET) == (off_t)-1)
1079 die("Could not lseek: %s\n", strerror(errno));
1081 if ((fstr = fdopen(fd, "r")) == NULL)
1082 die("Could not fdopen: %s\n", strerror(errno));
1084 while (!feof(fstr)) {
1085 if (fgets(buffer, 1024, fstr) == NULL) {
1088 die("Could not read configuration file\n");
1091 /* sscanf implicitly strips whitespace. Also, we skip comments and empty lines. */
1092 if (sscanf(buffer, "%s %[^\n]", key, value) < 1 ||
1093 key[0] == '#' || strlen(key) < 3)
1096 if (strcasecmp(key, "set") == 0) {
1097 if (value[0] != '$') {
1098 ELOG("Malformed variable assignment, name has to start with $\n");
1102 /* get key/value for this variable */
1103 char *v_key = value, *v_value;
1104 if (strstr(value, " ") == NULL && strstr(value, "\t") == NULL) {
1105 ELOG("Malformed variable assignment, need a value\n");
1109 if (!(v_value = strstr(value, " ")))
1110 v_value = strstr(value, "\t");
1112 *(v_value++) = '\0';
1113 while (*v_value == '\t' || *v_value == ' ')
1116 struct Variable *new = scalloc(sizeof(struct Variable));
1117 new->key = sstrdup(v_key);
1118 new->value = sstrdup(v_value);
1119 SLIST_INSERT_HEAD(&variables, new, variables);
1120 DLOG("Got new variable %s = %s\n", v_key, v_value);
1126 /* For every custom variable, see how often it occurs in the file and
1127 * how much extra bytes it requires when replaced. */
1128 struct Variable *current, *nearest;
1129 int extra_bytes = 0;
1130 /* We need to copy the buffer because we need to invalidate the
1131 * variables (otherwise we will count them twice, which is bad when
1132 * 'extra' is negative) */
1133 char *bufcopy = sstrdup(buf);
1134 SLIST_FOREACH(current, &variables, variables) {
1135 int extra = (strlen(current->value) - strlen(current->key));
1137 for (next = bufcopy;
1138 next < (bufcopy + stbuf.st_size) &&
1139 (next = strcasestr(next, current->key)) != NULL;
1140 next += strlen(current->key)) {
1142 extra_bytes += extra;
1147 /* Then, allocate a new buffer and copy the file over to the new one,
1148 * but replace occurences of our variables */
1149 char *walk = buf, *destwalk;
1150 char *new = smalloc((stbuf.st_size + extra_bytes + 1) * sizeof(char));
1152 while (walk < (buf + stbuf.st_size)) {
1153 /* Find the next variable */
1154 SLIST_FOREACH(current, &variables, variables)
1155 current->next_match = strcasestr(walk, current->key);
1157 int distance = stbuf.st_size;
1158 SLIST_FOREACH(current, &variables, variables) {
1159 if (current->next_match == NULL)
1161 if ((current->next_match - walk) < distance) {
1162 distance = (current->next_match - walk);
1166 if (nearest == NULL) {
1167 /* If there are no more variables, we just copy the rest */
1168 strncpy(destwalk, walk, (buf + stbuf.st_size) - walk);
1169 destwalk += (buf + stbuf.st_size) - walk;
1173 /* Copy until the next variable, then copy its value */
1174 strncpy(destwalk, walk, distance);
1175 strncpy(destwalk + distance, nearest->value, strlen(nearest->value));
1176 walk += distance + strlen(nearest->key);
1177 destwalk += distance + strlen(nearest->value);
1181 /* analyze the string to find out whether this is an old config file (3.x)
1182 * or a new config file (4.x). If it’s old, we run the converter script. */
1183 int version = detect_version(buf);
1185 /* We need to convert this v3 configuration */
1186 char *converted = migrate_config(new, stbuf.st_size);
1187 if (converted != NULL) {
1189 ELOG("****************************************************************\n");
1190 ELOG("NOTE: Automatically converted configuration file from v3 to v4.\n");
1192 ELOG("Please convert your config file to v4. You can use this command:\n");
1193 ELOG(" mv %s %s.O\n", f, f);
1194 ELOG(" i3-migrate-config-to-v4 %s.O > %s\n", f, f);
1195 ELOG("****************************************************************\n");
1201 printf("**********************************************************************\n");
1202 printf("ERROR: Could not convert config file. Maybe i3-migrate-config-to-v4\n");
1203 printf("was not correctly installed on your system?\n");
1204 printf("**********************************************************************\n");
1210 context = scalloc(sizeof(struct context));
1211 context->filename = f;
1213 struct ConfigResult *config_output = parse_config(new, context);
1214 yajl_gen_free(config_output->json_gen);
1216 check_for_duplicate_bindings(context);
1218 if (context->has_errors || context->has_warnings) {
1219 ELOG("FYI: You are using i3 version " I3_VERSION "\n");
1221 ELOG("Please convert your configfile first, then fix any remaining errors (see above).\n");
1222 start_configerror_nagbar(f);
1225 FREE(context->line_copy);
1230 while (!SLIST_EMPTY(&variables)) {
1231 current = SLIST_FIRST(&variables);
1233 FREE(current->value);
1234 SLIST_REMOVE_HEAD(&variables, variables);