2 #define I3__FILE__ "config_parser.c"
4 * vim:ts=4:sw=4:expandtab
6 * i3 - an improved dynamic tiling window manager
7 * © 2009 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>
38 #include <xcb/xcb_xrm.h>
42 // Macros to make the YAJL API a bit easier to use.
43 #define y(x, ...) yajl_gen_##x(command_output.json_gen, ##__VA_ARGS__)
44 #define ystr(str) yajl_gen_string(command_output.json_gen, (unsigned char *)str, strlen(str))
46 xcb_xrm_database_t *database = NULL;
49 pid_t config_error_nagbar_pid = -1;
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: config_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: config_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");
154 static const char *get_string(const char *identifier) {
155 for (int c = 0; c < 10; c++) {
156 if (stack[c].identifier == NULL)
158 if (strcmp(identifier, stack[c].identifier) == 0)
159 return stack[c].val.str;
164 static long get_long(const char *identifier) {
165 for (int c = 0; c < 10; c++) {
166 if (stack[c].identifier == NULL)
168 if (strcmp(identifier, stack[c].identifier) == 0)
169 return stack[c].val.num;
174 static void clear_stack(void) {
175 for (int c = 0; c < 10; c++) {
176 if (stack[c].type == STACK_STR && stack[c].val.str != NULL)
177 free(stack[c].val.str);
178 stack[c].identifier = NULL;
179 stack[c].val.str = NULL;
180 stack[c].val.num = 0;
184 /*******************************************************************************
186 ******************************************************************************/
188 static cmdp_state state;
189 static Match current_match;
190 static struct ConfigResultIR subcommand_output;
191 static struct ConfigResultIR command_output;
193 /* A list which contains the states that lead to the current state, e.g.
194 * INITIAL, WORKSPACE_LAYOUT.
195 * When jumping back to INITIAL, statelist_idx will simply be set to 1
196 * (likewise for other states, e.g. MODE or BAR).
197 * This list is used to process the nearest error token. */
198 static cmdp_state statelist[10] = {INITIAL};
199 /* NB: statelist_idx points to where the next entry will be inserted */
200 static int statelist_idx = 1;
202 #include "GENERATED_config_call.h"
204 static void next_state(const cmdp_token *token) {
205 cmdp_state _next_state = token->next_state;
207 //printf("token = name %s identifier %s\n", token->name, token->identifier);
208 //printf("next_state = %d\n", token->next_state);
209 if (token->next_state == __CALL) {
210 subcommand_output.json_gen = command_output.json_gen;
211 GENERATED_call(token->extra.call_identifier, &subcommand_output);
212 _next_state = subcommand_output.next_state;
217 if (state == INITIAL) {
221 /* See if we are jumping back to a state in which we were in previously
222 * (statelist contains INITIAL) and just move statelist_idx accordingly. */
223 for (int i = 0; i < statelist_idx; i++) {
224 if (statelist[i] != _next_state)
226 statelist_idx = i + 1;
230 /* Otherwise, the state is new and we add it to the list */
231 statelist[statelist_idx++] = _next_state;
235 * Returns a pointer to the start of the line (one byte after the previous \r,
236 * \n) or the start of the input, if this is the first line.
239 static const char *start_of_line(const char *walk, const char *beginning) {
240 while (*walk != '\n' && *walk != '\r' && walk >= beginning) {
248 * Copies the line and terminates it at the next \n, if any.
250 * The caller has to free() the result.
253 static char *single_line(const char *start) {
254 char *result = sstrdup(start);
255 char *end = strchr(result, '\n');
261 struct ConfigResultIR *parse_config(const char *input, struct context *context) {
262 /* Dump the entire config file into the debug log. We cannot just use
263 * DLOG("%s", input); because one log message must not exceed 4 KiB. */
264 const char *dumpwalk = input;
266 while (*dumpwalk != '\0') {
267 char *next_nl = strchr(dumpwalk, '\n');
268 if (next_nl != NULL) {
269 DLOG("CONFIG(line %3d): %.*s\n", linecnt, (int)(next_nl - dumpwalk), dumpwalk);
270 dumpwalk = next_nl + 1;
272 DLOG("CONFIG(line %3d): %s\n", linecnt, dumpwalk);
280 /* A YAJL JSON generator used for formatting replies. */
281 command_output.json_gen = yajl_gen_alloc(NULL);
285 const char *walk = input;
286 const size_t len = strlen(input);
288 const cmdp_token *token;
292 // TODO: make this testable
294 cfg_criteria_init(¤t_match, &subcommand_output, INITIAL);
297 /* The "<=" operator is intentional: We also handle the terminating 0-byte
298 * explicitly by looking for an 'end' token. */
299 while ((size_t)(walk - input) <= len) {
300 /* Skip whitespace before every token, newlines are relevant since they
301 * separate configuration directives. */
302 while ((*walk == ' ' || *walk == '\t') && *walk != '\0')
305 //printf("remaining input: %s\n", walk);
307 cmdp_token_ptr *ptr = &(tokens[state]);
308 token_handled = false;
309 for (c = 0; c < ptr->n; c++) {
310 token = &(ptr->array[c]);
313 if (token->name[0] == '\'') {
314 if (strncasecmp(walk, token->name + 1, strlen(token->name) - 1) == 0) {
315 if (token->identifier != NULL)
316 push_string(token->identifier, token->name + 1);
317 walk += strlen(token->name) - 1;
319 token_handled = true;
325 if (strcmp(token->name, "number") == 0) {
326 /* Handle numbers. We only accept decimal numbers for now. */
329 long int num = strtol(walk, &end, 10);
330 if ((errno == ERANGE && (num == LONG_MIN || num == LONG_MAX)) ||
331 (errno != 0 && num == 0))
334 /* No valid numbers found */
338 if (token->identifier != NULL)
339 push_long(token->identifier, num);
341 /* Set walk to the first non-number character */
344 token_handled = true;
348 if (strcmp(token->name, "string") == 0 ||
349 strcmp(token->name, "word") == 0) {
350 const char *beginning = walk;
351 /* Handle quoted strings (or words). */
355 while (*walk != '\0' && (*walk != '"' || *(walk - 1) == '\\'))
358 if (token->name[0] == 's') {
359 while (*walk != '\0' && *walk != '\r' && *walk != '\n')
362 /* For a word, the delimiters are white space (' ' or
363 * '\t'), closing square bracket (]), comma (,) and
365 while (*walk != ' ' && *walk != '\t' &&
366 *walk != ']' && *walk != ',' &&
367 *walk != ';' && *walk != '\r' &&
368 *walk != '\n' && *walk != '\0')
372 if (walk != beginning) {
373 char *str = scalloc(walk - beginning + 1, 1);
374 /* We copy manually to handle escaping of characters. */
376 for (inpos = 0, outpos = 0;
377 inpos < (walk - beginning);
379 /* We only handle escaped double quotes to not break
380 * backwards compatibility with people using \w in
381 * regular expressions etc. */
382 if (beginning[inpos] == '\\' && beginning[inpos + 1] == '"')
384 str[outpos] = beginning[inpos];
386 if (token->identifier)
387 push_string(token->identifier, str);
389 /* If we are at the end of a quoted string, skip the ending
394 token_handled = true;
399 if (strcmp(token->name, "line") == 0) {
400 while (*walk != '\0' && *walk != '\n' && *walk != '\r')
403 token_handled = true;
409 if (strcmp(token->name, "end") == 0) {
410 //printf("checking for end: *%s*\n", walk);
411 if (*walk == '\0' || *walk == '\n' || *walk == '\r') {
413 token_handled = true;
414 /* To make sure we start with an appropriate matching
415 * datastructure for commands which do *not* specify any
416 * criteria, we re-initialize the criteria system after
418 // TODO: make this testable
420 cfg_criteria_init(¤t_match, &subcommand_output, INITIAL);
429 if (!token_handled) {
430 /* Figure out how much memory we will need to fill in the names of
431 * all tokens afterwards. */
433 for (c = 0; c < ptr->n; c++)
434 tokenlen += strlen(ptr->array[c].name) + strlen("'', ");
436 /* Build up a decent error message. We include the problem, the
437 * full input, and underline the position where the parser
440 char *possible_tokens = smalloc(tokenlen + 1);
441 char *tokenwalk = possible_tokens;
442 for (c = 0; c < ptr->n; c++) {
443 token = &(ptr->array[c]);
444 if (token->name[0] == '\'') {
445 /* A literal is copied to the error message enclosed with
448 strcpy(tokenwalk, token->name + 1);
449 tokenwalk += strlen(token->name + 1);
452 /* Skip error tokens in error messages, they are used
453 * internally only and might confuse users. */
454 if (strcmp(token->name, "error") == 0)
456 /* Any other token is copied to the error message enclosed
457 * with angle brackets. */
459 strcpy(tokenwalk, token->name);
460 tokenwalk += strlen(token->name);
463 if (c < (ptr->n - 1)) {
469 sasprintf(&errormessage, "Expected one of these tokens: %s",
471 free(possible_tokens);
473 /* Go back to the beginning of the line */
474 const char *error_line = start_of_line(walk, input);
476 /* Contains the same amount of characters as 'input' has, but with
477 * the unparseable part highlighted using ^ characters. */
478 char *position = scalloc(strlen(error_line) + 1, 1);
479 const char *copywalk;
480 for (copywalk = error_line;
481 *copywalk != '\n' && *copywalk != '\r' && *copywalk != '\0';
483 position[(copywalk - error_line)] = (copywalk >= walk ? '^' : (*copywalk == '\t' ? '\t' : ' '));
484 position[(copywalk - error_line)] = '\0';
486 ELOG("CONFIG: %s\n", errormessage);
487 ELOG("CONFIG: (in file %s)\n", context->filename);
488 char *error_copy = single_line(error_line);
490 /* Print context lines *before* the error, if any. */
492 const char *context_p1_start = start_of_line(error_line - 2, input);
493 char *context_p1_line = single_line(context_p1_start);
495 const char *context_p2_start = start_of_line(context_p1_start - 2, input);
496 char *context_p2_line = single_line(context_p2_start);
497 ELOG("CONFIG: Line %3d: %s\n", linecnt - 2, context_p2_line);
498 free(context_p2_line);
500 ELOG("CONFIG: Line %3d: %s\n", linecnt - 1, context_p1_line);
501 free(context_p1_line);
503 ELOG("CONFIG: Line %3d: %s\n", linecnt, error_copy);
504 ELOG("CONFIG: %s\n", position);
506 /* Print context lines *after* the error, if any. */
507 for (int i = 0; i < 2; i++) {
508 char *error_line_end = strchr(error_line, '\n');
509 if (error_line_end != NULL && *(error_line_end + 1) != '\0') {
510 error_line = error_line_end + 1;
511 error_copy = single_line(error_line);
512 ELOG("CONFIG: Line %3d: %s\n", linecnt + i + 1, error_copy);
517 context->has_errors = true;
519 /* Format this error message as a JSON reply. */
523 /* We set parse_error to true to distinguish this from other
524 * errors. i3-nagbar is spawned upon keypresses only for parser
532 ystr("errorposition");
536 /* Skip the rest of this line, but continue parsing. */
537 while ((size_t)(walk - input) <= len && *walk != '\n')
544 /* To figure out in which state to go (e.g. MODE or INITIAL),
545 * we find the nearest state which contains an <error> token
546 * and follow that one. */
547 bool error_token_found = false;
548 for (int i = statelist_idx - 1; (i >= 0) && !error_token_found; i--) {
549 cmdp_token_ptr *errptr = &(tokens[statelist[i]]);
550 for (int j = 0; j < errptr->n; j++) {
551 if (strcmp(errptr->array[j].name, "error") != 0)
553 next_state(&(errptr->array[j]));
554 error_token_found = true;
559 assert(error_token_found);
565 return &command_output;
568 /*******************************************************************************
569 * Code for building the stand-alone binary test.commands_parser which is used
570 * by t/187-commands-parser.t.
571 ******************************************************************************/
576 * Logs the given message to stdout while prefixing the current time to it,
577 * but only if debug logging was activated.
578 * This is to be called by DLOG() which includes filename/linenumber
581 void debuglog(char *fmt, ...) {
585 fprintf(stdout, "# ");
586 vfprintf(stdout, fmt, args);
590 void errorlog(char *fmt, ...) {
594 vfprintf(stderr, fmt, args);
598 static int criteria_next_state;
600 void cfg_criteria_init(I3_CFG, int _state) {
601 criteria_next_state = _state;
604 void cfg_criteria_add(I3_CFG, const char *ctype, const char *cvalue) {
607 void cfg_criteria_pop_state(I3_CFG) {
608 result->next_state = criteria_next_state;
611 int main(int argc, char *argv[]) {
613 fprintf(stderr, "Syntax: %s <command>\n", argv[0]);
616 struct context context;
617 context.filename = "<stdin>";
618 parse_config(argv[1], &context);
624 * Goes through each line of buf (separated by \n) and checks for statements /
625 * commands which only occur in i3 v4 configuration files. If it finds any, it
626 * returns version 4, otherwise it returns version 3.
629 static int detect_version(char *buf) {
632 while (*walk != '\0') {
638 /* check for some v4-only statements */
639 if (strncasecmp(line, "bindcode", strlen("bindcode")) == 0 ||
640 strncasecmp(line, "force_focus_wrapping", strlen("force_focus_wrapping")) == 0 ||
641 strncasecmp(line, "# i3 config file (v4)", strlen("# i3 config file (v4)")) == 0 ||
642 strncasecmp(line, "workspace_layout", strlen("workspace_layout")) == 0) {
643 LOG("deciding for version 4 due to this line: %.*s\n", (int)(walk - line), line);
647 /* if this is a bind statement, we can check the command */
648 if (strncasecmp(line, "bind", strlen("bind")) == 0) {
649 char *bind = strchr(line, ' ');
652 while ((*bind == ' ' || *bind == '\t') && *bind != '\0')
656 if ((bind = strchr(bind, ' ')) == NULL)
658 while ((*bind == ' ' || *bind == '\t') && *bind != '\0')
662 if (strncasecmp(bind, "layout", strlen("layout")) == 0 ||
663 strncasecmp(bind, "floating", strlen("floating")) == 0 ||
664 strncasecmp(bind, "workspace", strlen("workspace")) == 0 ||
665 strncasecmp(bind, "focus left", strlen("focus left")) == 0 ||
666 strncasecmp(bind, "focus right", strlen("focus right")) == 0 ||
667 strncasecmp(bind, "focus up", strlen("focus up")) == 0 ||
668 strncasecmp(bind, "focus down", strlen("focus down")) == 0 ||
669 strncasecmp(bind, "border normal", strlen("border normal")) == 0 ||
670 strncasecmp(bind, "border 1pixel", strlen("border 1pixel")) == 0 ||
671 strncasecmp(bind, "border pixel", strlen("border pixel")) == 0 ||
672 strncasecmp(bind, "border borderless", strlen("border borderless")) == 0 ||
673 strncasecmp(bind, "--no-startup-id", strlen("--no-startup-id")) == 0 ||
674 strncasecmp(bind, "bar", strlen("bar")) == 0) {
675 LOG("deciding for version 4 due to this line: %.*s\n", (int)(walk - line), line);
681 /* advance to the next line */
690 * Calls i3-migrate-config-to-v4 to migrate a configuration file (input
693 * Returns the converted config file or NULL if there was an error (for
694 * example the script could not be found in $PATH or the i3 executable’s
698 static char *migrate_config(char *input, off_t size) {
702 if (pipe(writepipe) != 0 ||
703 pipe(readpipe) != 0) {
704 warn("migrate_config: Could not create pipes");
710 warn("Could not fork()");
716 /* close writing end of writepipe, connect reading side to stdin */
718 dup2(writepipe[0], 0);
720 /* close reading end of readpipe, connect writing side to stdout */
722 dup2(readpipe[1], 1);
724 static char *argv[] = {
725 NULL, /* will be replaced by the executable path */
727 exec_i3_utility("i3-migrate-config-to-v4", argv);
732 /* close reading end of the writepipe (connected to the script’s stdin) */
735 /* write the whole config file to the pipe, the script will read everything
737 if (writeall(writepipe[1], input, size) == -1) {
738 warn("Could not write to pipe");
743 /* close writing end of the readpipe (connected to the script’s stdout) */
746 /* read the script’s output */
747 int conv_size = 65535;
748 char *converted = smalloc(conv_size);
749 int read_bytes = 0, ret;
751 if (read_bytes == conv_size) {
753 converted = srealloc(converted, conv_size);
755 ret = read(readpipe[0], converted + read_bytes, conv_size - read_bytes);
757 warn("Cannot read from pipe");
764 /* get the returncode */
767 if (!WIFEXITED(status)) {
768 fprintf(stderr, "Child did not terminate normally, using old config file (will lead to broken behaviour)\n");
772 int returncode = WEXITSTATUS(status);
773 if (returncode != 0) {
774 fprintf(stderr, "Migration process exit code was != 0\n");
775 if (returncode == 2) {
776 fprintf(stderr, "could not start the migration script\n");
777 /* TODO: script was not found. tell the user to fix their system or create a v4 config */
778 } else if (returncode == 1) {
779 fprintf(stderr, "This already was a v4 config. Please add the following line to your config file:\n");
780 fprintf(stderr, "# i3 config file (v4)\n");
781 /* TODO: nag the user with a message to include a hint for i3 in their config file */
790 * Launch nagbar to indicate errors in the configuration file.
792 void start_config_error_nagbar(const char *configpath, bool has_errors) {
793 char *editaction, *pageraction;
794 sasprintf(&editaction, "i3-sensible-editor \"%s\" && i3-msg reload\n", configpath);
795 sasprintf(&pageraction, "i3-sensible-pager \"%s\"\n", errorfilename);
797 NULL, /* will be replaced by the executable path */
799 (config.font.pattern ? config.font.pattern : "fixed"),
801 (has_errors ? "error" : "warning"),
803 (has_errors ? "You have an error in your i3 config file!" : "Your config is outdated. Please fix the warnings to make sure everything works."),
807 (errorfilename ? "-b" : NULL),
808 (has_errors ? "show errors" : "show warnings"),
812 start_nagbar(&config_error_nagbar_pid, argv);
818 * Inserts or updates a variable assignment depending on whether it already exists.
821 static void upsert_variable(struct variables_head *variables, char *key, char *value) {
822 struct Variable *current;
823 SLIST_FOREACH(current, variables, variables) {
824 if (strcmp(current->key, key) != 0) {
828 DLOG("Updated variable: %s = %s -> %s\n", key, current->value, value);
829 FREE(current->value);
830 current->value = sstrdup(value);
834 DLOG("Defined new variable: %s = %s\n", key, value);
835 struct Variable *new = scalloc(1, sizeof(struct Variable));
836 struct Variable *test = NULL, *loc = NULL;
837 new->key = sstrdup(key);
838 new->value = sstrdup(value);
839 /* ensure that the correct variable is matched in case of one being
840 * the prefix of another */
841 SLIST_FOREACH(test, variables, variables) {
842 if (strlen(new->key) >= strlen(test->key))
848 SLIST_INSERT_HEAD(variables, new, variables);
850 SLIST_INSERT_AFTER(loc, new, variables);
854 static char *get_resource(char *name) {
859 /* Load the resource database lazily. */
860 if (database == NULL) {
861 database = xcb_xrm_database_from_default(conn);
863 if (database == NULL) {
864 ELOG("Failed to open the resource database.\n");
866 /* Load an empty database so we don't keep trying to load the
867 * default database over and over again. */
868 database = xcb_xrm_database_from_string("");
875 xcb_xrm_resource_get_string(database, name, NULL, &resource);
880 * Parses the given file by first replacing the variables, then calling
881 * parse_config and possibly launching i3-nagbar.
884 bool parse_file(const char *f, bool use_nagbar) {
885 struct variables_head variables = SLIST_HEAD_INITIALIZER(&variables);
890 char buffer[4096], key[512], value[4096], *continuation = NULL;
892 if ((fd = open(f, O_RDONLY)) == -1)
893 die("Could not open configuration file: %s\n", strerror(errno));
895 if (fstat(fd, &stbuf) == -1)
896 die("Could not fstat file: %s\n", strerror(errno));
898 buf = scalloc(stbuf.st_size + 1, 1);
900 if ((fstr = fdopen(fd, "r")) == NULL)
901 die("Could not fdopen: %s\n", strerror(errno));
903 while (!feof(fstr)) {
905 continuation = buffer;
906 if (fgets(continuation, sizeof(buffer) - (continuation - buffer), fstr) == NULL) {
909 die("Could not read configuration file\n");
911 if (buffer[strlen(buffer) - 1] != '\n' && !feof(fstr)) {
912 ELOG("Your line continuation is too long, it exceeds %zd bytes\n", sizeof(buffer));
915 /* sscanf implicitly strips whitespace. */
916 const bool skip_line = (sscanf(buffer, "%511s %4095[^\n]", key, value) < 1 || strlen(key) < 3);
917 const bool comment = (key[0] == '#');
920 continuation = strstr(buffer, "\\\n");
925 DLOG("line continuation in comment is ignored: \"%.*s\"\n", (int)strlen(buffer) - 1, buffer);
929 strncpy(buf + strlen(buf), buffer, strlen(buffer) + 1);
931 /* Skip comments and empty lines. */
932 if (skip_line || comment) {
936 if (strcasecmp(key, "set") == 0) {
940 if (sscanf(value, "%511s %4095[^\n]", v_key, v_value) < 1) {
941 ELOG("Failed to parse variable specification '%s', skipping it.\n", value);
945 if (v_key[0] != '$') {
946 ELOG("Malformed variable assignment, name has to start with $\n");
950 upsert_variable(&variables, v_key, v_value);
952 } else if (strcasecmp(key, "set_from_resource") == 0) {
957 if (sscanf(value, "%511s %511s %4095[^\n]", v_key, res_name, fallback) < 1) {
958 ELOG("Failed to parse resource specification '%s', skipping it.\n", value);
962 if (v_key[0] != '$') {
963 ELOG("Malformed variable assignment, name has to start with $\n");
967 char *res_value = get_resource(res_name);
968 if (res_value == NULL) {
969 DLOG("Could not get resource '%s', using fallback '%s'.\n", res_name, fallback);
970 res_value = sstrdup(fallback);
973 upsert_variable(&variables, v_key, res_value);
980 if (database != NULL) {
981 xcb_xrm_database_free(database);
982 /* Explicitly set the database to NULL again in case the config gets reloaded. */
986 /* For every custom variable, see how often it occurs in the file and
987 * how much extra bytes it requires when replaced. */
988 struct Variable *current, *nearest;
990 /* We need to copy the buffer because we need to invalidate the
991 * variables (otherwise we will count them twice, which is bad when
992 * 'extra' is negative) */
993 char *bufcopy = sstrdup(buf);
994 SLIST_FOREACH(current, &variables, variables) {
995 int extra = (strlen(current->value) - strlen(current->key));
998 next < (bufcopy + stbuf.st_size) &&
999 (next = strcasestr(next, current->key)) != NULL;
1000 next += strlen(current->key)) {
1002 extra_bytes += extra;
1007 /* Then, allocate a new buffer and copy the file over to the new one,
1008 * but replace occurrences of our variables */
1009 char *walk = buf, *destwalk;
1010 char *new = smalloc(stbuf.st_size + extra_bytes + 1);
1012 while (walk < (buf + stbuf.st_size)) {
1013 /* Find the next variable */
1014 SLIST_FOREACH(current, &variables, variables)
1015 current->next_match = strcasestr(walk, current->key);
1017 int distance = stbuf.st_size;
1018 SLIST_FOREACH(current, &variables, variables) {
1019 if (current->next_match == NULL)
1021 if ((current->next_match - walk) < distance) {
1022 distance = (current->next_match - walk);
1026 if (nearest == NULL) {
1027 /* If there are no more variables, we just copy the rest */
1028 strncpy(destwalk, walk, (buf + stbuf.st_size) - walk);
1029 destwalk += (buf + stbuf.st_size) - walk;
1033 /* Copy until the next variable, then copy its value */
1034 strncpy(destwalk, walk, distance);
1035 strncpy(destwalk + distance, nearest->value, strlen(nearest->value));
1036 walk += distance + strlen(nearest->key);
1037 destwalk += distance + strlen(nearest->value);
1041 /* analyze the string to find out whether this is an old config file (3.x)
1042 * or a new config file (4.x). If it’s old, we run the converter script. */
1043 int version = detect_version(buf);
1045 /* We need to convert this v3 configuration */
1046 char *converted = migrate_config(new, stbuf.st_size);
1047 if (converted != NULL) {
1049 ELOG("****************************************************************\n");
1050 ELOG("NOTE: Automatically converted configuration file from v3 to v4.\n");
1052 ELOG("Please convert your config file to v4. You can use this command:\n");
1053 ELOG(" mv %s %s.O\n", f, f);
1054 ELOG(" i3-migrate-config-to-v4 %s.O > %s\n", f, f);
1055 ELOG("****************************************************************\n");
1061 LOG("**********************************************************************\n");
1062 LOG("ERROR: Could not convert config file. Maybe i3-migrate-config-to-v4\n");
1063 LOG("was not correctly installed on your system?\n");
1064 LOG("**********************************************************************\n");
1069 context = scalloc(1, sizeof(struct context));
1070 context->filename = f;
1072 struct ConfigResultIR *config_output = parse_config(new, context);
1073 yajl_gen_free(config_output->json_gen);
1075 extract_workspace_names_from_bindings();
1076 check_for_duplicate_bindings(context);
1079 if (use_nagbar && (context->has_errors || context->has_warnings)) {
1080 ELOG("FYI: You are using i3 version %s\n", i3_version);
1082 ELOG("Please convert your configfile first, then fix any remaining errors (see above).\n");
1084 start_config_error_nagbar(f, context->has_errors);
1087 bool has_errors = context->has_errors;
1089 FREE(context->line_copy);
1094 while (!SLIST_EMPTY(&variables)) {
1095 current = SLIST_FIRST(&variables);
1097 FREE(current->value);
1098 SLIST_REMOVE_HEAD(&variables, variables);