2 * vim:ts=4:sw=4:expandtab
4 * i3 - an improved dynamic tiling window manager
5 * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
7 * config_parser.c: hand-written parser to parse configuration directives.
9 * See also src/commands_parser.c for rationale on why we use a custom parser.
11 * This parser works VERY MUCH like src/commands_parser.c, so read that first.
12 * The differences are:
14 * 1. config_parser supports the 'number' token type (in addition to 'word' and
15 * 'string'). Numbers are referred to using &num (like $str).
17 * 2. Criteria are not executed immediately, they are just stored.
19 * 3. config_parser recognizes \n and \r as 'end' token, while commands_parser
22 * 4. config_parser skips the current line on invalid inputs and follows the
23 * nearest <error> token.
34 #include <sys/types.h>
38 #include <xcb/xcb_xrm.h>
40 // Macros to make the YAJL API a bit easier to use.
41 #define y(x, ...) yajl_gen_##x(command_output.json_gen, ##__VA_ARGS__)
42 #define ystr(str) yajl_gen_string(command_output.json_gen, (unsigned char *)str, strlen(str))
44 xcb_xrm_database_t *database = NULL;
47 pid_t config_error_nagbar_pid = -1;
48 static struct context *context;
51 /*******************************************************************************
52 * The data structures used for parsing. Essentially the current state and a
53 * list of tokens for that state.
55 * The GENERATED_* files are generated by generate-commands-parser.pl with the
56 * input parser-specs/configs.spec.
57 ******************************************************************************/
59 #include "GENERATED_config_enums.h"
61 typedef struct token {
64 /* This might be __CALL */
65 cmdp_state next_state;
67 uint16_t call_identifier;
71 typedef struct tokenptr {
76 #include "GENERATED_config_tokens.h"
78 /*******************************************************************************
79 * The (small) stack where identified literals are stored during the parsing
80 * of a single command (like $workspace).
81 ******************************************************************************/
84 /* Just a pointer, not dynamically allocated. */
85 const char *identifier;
96 /* 10 entries should be enough for everybody. */
97 static struct stack_entry stack[10];
100 * Pushes a string (identified by 'identifier') on the stack. We simply use a
101 * single array, since the number of entries we have to store is very small.
104 static void push_string(const char *identifier, const char *str) {
105 for (int c = 0; c < 10; c++) {
106 if (stack[c].identifier != NULL &&
107 strcmp(stack[c].identifier, identifier) != 0)
109 if (stack[c].identifier == NULL) {
110 /* Found a free slot, let’s store it here. */
111 stack[c].identifier = identifier;
112 stack[c].val.str = sstrdup(str);
113 stack[c].type = STACK_STR;
115 /* Append the value. */
116 char *prev = stack[c].val.str;
117 sasprintf(&(stack[c].val.str), "%s,%s", prev, str);
123 /* When we arrive here, the stack is full. This should not happen and
124 * means there’s either a bug in this parser or the specification
125 * contains a command with more than 10 identified tokens. */
126 fprintf(stderr, "BUG: config_parser stack full. This means either a bug "
127 "in the code, or a new command which contains more than "
128 "10 identified tokens.\n");
132 static void push_long(const char *identifier, long num) {
133 for (int c = 0; c < 10; c++) {
134 if (stack[c].identifier != NULL)
136 /* Found a free slot, let’s store it here. */
137 stack[c].identifier = identifier;
138 stack[c].val.num = num;
139 stack[c].type = STACK_LONG;
143 /* When we arrive here, the stack is full. This should not happen and
144 * means there’s either a bug in this parser or the specification
145 * contains a command with more than 10 identified tokens. */
146 fprintf(stderr, "BUG: config_parser stack full. This means either a bug "
147 "in the code, or a new command which contains more than "
148 "10 identified tokens.\n");
152 static const char *get_string(const char *identifier) {
153 for (int c = 0; c < 10; c++) {
154 if (stack[c].identifier == NULL)
156 if (strcmp(identifier, stack[c].identifier) == 0)
157 return stack[c].val.str;
162 static long get_long(const char *identifier) {
163 for (int c = 0; c < 10; c++) {
164 if (stack[c].identifier == NULL)
166 if (strcmp(identifier, stack[c].identifier) == 0)
167 return stack[c].val.num;
172 static void clear_stack(void) {
173 for (int c = 0; c < 10; c++) {
174 if (stack[c].type == STACK_STR && stack[c].val.str != NULL)
175 free(stack[c].val.str);
176 stack[c].identifier = NULL;
177 stack[c].val.str = NULL;
178 stack[c].val.num = 0;
182 /*******************************************************************************
184 ******************************************************************************/
186 static cmdp_state state;
187 static Match current_match;
188 static struct ConfigResultIR subcommand_output;
189 static struct ConfigResultIR command_output;
191 /* A list which contains the states that lead to the current state, e.g.
192 * INITIAL, WORKSPACE_LAYOUT.
193 * When jumping back to INITIAL, statelist_idx will simply be set to 1
194 * (likewise for other states, e.g. MODE or BAR).
195 * This list is used to process the nearest error token. */
196 static cmdp_state statelist[10] = {INITIAL};
197 /* NB: statelist_idx points to where the next entry will be inserted */
198 static int statelist_idx = 1;
200 #include "GENERATED_config_call.h"
202 static void next_state(const cmdp_token *token) {
203 cmdp_state _next_state = token->next_state;
205 //printf("token = name %s identifier %s\n", token->name, token->identifier);
206 //printf("next_state = %d\n", token->next_state);
207 if (token->next_state == __CALL) {
208 subcommand_output.json_gen = command_output.json_gen;
209 GENERATED_call(token->extra.call_identifier, &subcommand_output);
210 _next_state = subcommand_output.next_state;
215 if (state == INITIAL) {
219 /* See if we are jumping back to a state in which we were in previously
220 * (statelist contains INITIAL) and just move statelist_idx accordingly. */
221 for (int i = 0; i < statelist_idx; i++) {
222 if (statelist[i] != _next_state)
224 statelist_idx = i + 1;
228 /* Otherwise, the state is new and we add it to the list */
229 statelist[statelist_idx++] = _next_state;
233 * Returns a pointer to the start of the line (one byte after the previous \r,
234 * \n) or the start of the input, if this is the first line.
237 static const char *start_of_line(const char *walk, const char *beginning) {
238 while (walk >= beginning && *walk != '\n' && *walk != '\r') {
246 * Copies the line and terminates it at the next \n, if any.
248 * The caller has to free() the result.
251 static char *single_line(const char *start) {
252 char *result = sstrdup(start);
253 char *end = strchr(result, '\n');
259 struct ConfigResultIR *parse_config(const char *input, struct context *context) {
260 /* Dump the entire config file into the debug log. We cannot just use
261 * DLOG("%s", input); because one log message must not exceed 4 KiB. */
262 const char *dumpwalk = input;
264 while (*dumpwalk != '\0') {
265 char *next_nl = strchr(dumpwalk, '\n');
266 if (next_nl != NULL) {
267 DLOG("CONFIG(line %3d): %.*s\n", linecnt, (int)(next_nl - dumpwalk), dumpwalk);
268 dumpwalk = next_nl + 1;
270 DLOG("CONFIG(line %3d): %s\n", linecnt, dumpwalk);
278 /* A YAJL JSON generator used for formatting replies. */
279 command_output.json_gen = yajl_gen_alloc(NULL);
283 const char *walk = input;
284 const size_t len = strlen(input);
286 const cmdp_token *token;
290 // TODO: make this testable
292 cfg_criteria_init(¤t_match, &subcommand_output, INITIAL);
295 /* The "<=" operator is intentional: We also handle the terminating 0-byte
296 * explicitly by looking for an 'end' token. */
297 while ((size_t)(walk - input) <= len) {
298 /* Skip whitespace before every token, newlines are relevant since they
299 * separate configuration directives. */
300 while ((*walk == ' ' || *walk == '\t') && *walk != '\0')
303 //printf("remaining input: %s\n", walk);
305 cmdp_token_ptr *ptr = &(tokens[state]);
306 token_handled = false;
307 for (c = 0; c < ptr->n; c++) {
308 token = &(ptr->array[c]);
311 if (token->name[0] == '\'') {
312 if (strncasecmp(walk, token->name + 1, strlen(token->name) - 1) == 0) {
313 if (token->identifier != NULL)
314 push_string(token->identifier, token->name + 1);
315 walk += strlen(token->name) - 1;
317 token_handled = true;
323 if (strcmp(token->name, "number") == 0) {
324 /* Handle numbers. We only accept decimal numbers for now. */
327 long int num = strtol(walk, &end, 10);
328 if ((errno == ERANGE && (num == LONG_MIN || num == LONG_MAX)) ||
329 (errno != 0 && num == 0))
332 /* No valid numbers found */
336 if (token->identifier != NULL)
337 push_long(token->identifier, num);
339 /* Set walk to the first non-number character */
342 token_handled = true;
346 if (strcmp(token->name, "string") == 0 ||
347 strcmp(token->name, "word") == 0) {
348 const char *beginning = walk;
349 /* Handle quoted strings (or words). */
353 while (*walk != '\0' && (*walk != '"' || *(walk - 1) == '\\'))
356 if (token->name[0] == 's') {
357 while (*walk != '\0' && *walk != '\r' && *walk != '\n')
360 /* For a word, the delimiters are white space (' ' or
361 * '\t'), closing square bracket (]), comma (,) and
363 while (*walk != ' ' && *walk != '\t' &&
364 *walk != ']' && *walk != ',' &&
365 *walk != ';' && *walk != '\r' &&
366 *walk != '\n' && *walk != '\0')
370 if (walk != beginning) {
371 char *str = scalloc(walk - beginning + 1, 1);
372 /* We copy manually to handle escaping of characters. */
374 for (inpos = 0, outpos = 0;
375 inpos < (walk - beginning);
377 /* We only handle escaped double quotes to not break
378 * backwards compatibility with people using \w in
379 * regular expressions etc. */
380 if (beginning[inpos] == '\\' && beginning[inpos + 1] == '"')
382 str[outpos] = beginning[inpos];
384 if (token->identifier)
385 push_string(token->identifier, str);
387 /* If we are at the end of a quoted string, skip the ending
392 token_handled = true;
397 if (strcmp(token->name, "line") == 0) {
398 while (*walk != '\0' && *walk != '\n' && *walk != '\r')
401 token_handled = true;
407 if (strcmp(token->name, "end") == 0) {
408 //printf("checking for end: *%s*\n", walk);
409 if (*walk == '\0' || *walk == '\n' || *walk == '\r') {
411 token_handled = true;
412 /* To make sure we start with an appropriate matching
413 * datastructure for commands which do *not* specify any
414 * criteria, we re-initialize the criteria system after
416 // TODO: make this testable
418 cfg_criteria_init(¤t_match, &subcommand_output, INITIAL);
427 if (!token_handled) {
428 /* Figure out how much memory we will need to fill in the names of
429 * all tokens afterwards. */
431 for (c = 0; c < ptr->n; c++)
432 tokenlen += strlen(ptr->array[c].name) + strlen("'', ");
434 /* Build up a decent error message. We include the problem, the
435 * full input, and underline the position where the parser
438 char *possible_tokens = smalloc(tokenlen + 1);
439 char *tokenwalk = possible_tokens;
440 for (c = 0; c < ptr->n; c++) {
441 token = &(ptr->array[c]);
442 if (token->name[0] == '\'') {
443 /* A literal is copied to the error message enclosed with
446 strcpy(tokenwalk, token->name + 1);
447 tokenwalk += strlen(token->name + 1);
450 /* Skip error tokens in error messages, they are used
451 * internally only and might confuse users. */
452 if (strcmp(token->name, "error") == 0)
454 /* Any other token is copied to the error message enclosed
455 * with angle brackets. */
457 strcpy(tokenwalk, token->name);
458 tokenwalk += strlen(token->name);
461 if (c < (ptr->n - 1)) {
467 sasprintf(&errormessage, "Expected one of these tokens: %s",
469 free(possible_tokens);
471 /* Go back to the beginning of the line */
472 const char *error_line = start_of_line(walk, input);
474 /* Contains the same amount of characters as 'input' has, but with
475 * the unparseable part highlighted using ^ characters. */
476 char *position = scalloc(strlen(error_line) + 1, 1);
477 const char *copywalk;
478 for (copywalk = error_line;
479 *copywalk != '\n' && *copywalk != '\r' && *copywalk != '\0';
481 position[(copywalk - error_line)] = (copywalk >= walk ? '^' : (*copywalk == '\t' ? '\t' : ' '));
482 position[(copywalk - error_line)] = '\0';
484 ELOG("CONFIG: %s\n", errormessage);
485 ELOG("CONFIG: (in file %s)\n", context->filename);
486 char *error_copy = single_line(error_line);
488 /* Print context lines *before* the error, if any. */
490 const char *context_p1_start = start_of_line(error_line - 2, input);
491 char *context_p1_line = single_line(context_p1_start);
493 const char *context_p2_start = start_of_line(context_p1_start - 2, input);
494 char *context_p2_line = single_line(context_p2_start);
495 ELOG("CONFIG: Line %3d: %s\n", linecnt - 2, context_p2_line);
496 free(context_p2_line);
498 ELOG("CONFIG: Line %3d: %s\n", linecnt - 1, context_p1_line);
499 free(context_p1_line);
501 ELOG("CONFIG: Line %3d: %s\n", linecnt, error_copy);
502 ELOG("CONFIG: %s\n", position);
504 /* Print context lines *after* the error, if any. */
505 for (int i = 0; i < 2; i++) {
506 char *error_line_end = strchr(error_line, '\n');
507 if (error_line_end != NULL && *(error_line_end + 1) != '\0') {
508 error_line = error_line_end + 1;
509 error_copy = single_line(error_line);
510 ELOG("CONFIG: Line %3d: %s\n", linecnt + i + 1, error_copy);
515 context->has_errors = true;
517 /* Format this error message as a JSON reply. */
521 /* We set parse_error to true to distinguish this from other
522 * errors. i3-nagbar is spawned upon keypresses only for parser
530 ystr("errorposition");
534 /* Skip the rest of this line, but continue parsing. */
535 while ((size_t)(walk - input) <= len && *walk != '\n')
542 /* To figure out in which state to go (e.g. MODE or INITIAL),
543 * we find the nearest state which contains an <error> token
544 * and follow that one. */
545 bool error_token_found = false;
546 for (int i = statelist_idx - 1; (i >= 0) && !error_token_found; i--) {
547 cmdp_token_ptr *errptr = &(tokens[statelist[i]]);
548 for (int j = 0; j < errptr->n; j++) {
549 if (strcmp(errptr->array[j].name, "error") != 0)
551 next_state(&(errptr->array[j]));
552 error_token_found = true;
557 assert(error_token_found);
563 return &command_output;
566 /*******************************************************************************
567 * Code for building the stand-alone binary test.commands_parser which is used
568 * by t/187-commands-parser.t.
569 ******************************************************************************/
574 * Logs the given message to stdout while prefixing the current time to it,
575 * but only if debug logging was activated.
576 * This is to be called by DLOG() which includes filename/linenumber
579 void debuglog(char *fmt, ...) {
583 fprintf(stdout, "# ");
584 vfprintf(stdout, fmt, args);
588 void errorlog(char *fmt, ...) {
592 vfprintf(stderr, fmt, args);
596 static int criteria_next_state;
598 void cfg_criteria_init(I3_CFG, int _state) {
599 criteria_next_state = _state;
602 void cfg_criteria_add(I3_CFG, const char *ctype, const char *cvalue) {
605 void cfg_criteria_pop_state(I3_CFG) {
606 result->next_state = criteria_next_state;
609 int main(int argc, char *argv[]) {
611 fprintf(stderr, "Syntax: %s <command>\n", argv[0]);
614 struct context context;
615 context.filename = "<stdin>";
616 parse_config(argv[1], &context);
622 * Goes through each line of buf (separated by \n) and checks for statements /
623 * commands which only occur in i3 v4 configuration files. If it finds any, it
624 * returns version 4, otherwise it returns version 3.
627 static int detect_version(char *buf) {
630 while (*walk != '\0') {
636 /* check for some v4-only statements */
637 if (strncasecmp(line, "bindcode", strlen("bindcode")) == 0 ||
638 strncasecmp(line, "force_focus_wrapping", strlen("force_focus_wrapping")) == 0 ||
639 strncasecmp(line, "# i3 config file (v4)", strlen("# i3 config file (v4)")) == 0 ||
640 strncasecmp(line, "workspace_layout", strlen("workspace_layout")) == 0) {
641 LOG("deciding for version 4 due to this line: %.*s\n", (int)(walk - line), line);
645 /* if this is a bind statement, we can check the command */
646 if (strncasecmp(line, "bind", strlen("bind")) == 0) {
647 char *bind = strchr(line, ' ');
650 while ((*bind == ' ' || *bind == '\t') && *bind != '\0')
654 if ((bind = strchr(bind, ' ')) == NULL)
656 while ((*bind == ' ' || *bind == '\t') && *bind != '\0')
660 if (strncasecmp(bind, "layout", strlen("layout")) == 0 ||
661 strncasecmp(bind, "floating", strlen("floating")) == 0 ||
662 strncasecmp(bind, "workspace", strlen("workspace")) == 0 ||
663 strncasecmp(bind, "focus left", strlen("focus left")) == 0 ||
664 strncasecmp(bind, "focus right", strlen("focus right")) == 0 ||
665 strncasecmp(bind, "focus up", strlen("focus up")) == 0 ||
666 strncasecmp(bind, "focus down", strlen("focus down")) == 0 ||
667 strncasecmp(bind, "border normal", strlen("border normal")) == 0 ||
668 strncasecmp(bind, "border 1pixel", strlen("border 1pixel")) == 0 ||
669 strncasecmp(bind, "border pixel", strlen("border pixel")) == 0 ||
670 strncasecmp(bind, "border borderless", strlen("border borderless")) == 0 ||
671 strncasecmp(bind, "--no-startup-id", strlen("--no-startup-id")) == 0 ||
672 strncasecmp(bind, "bar", strlen("bar")) == 0) {
673 LOG("deciding for version 4 due to this line: %.*s\n", (int)(walk - line), line);
679 /* advance to the next line */
688 * Calls i3-migrate-config-to-v4 to migrate a configuration file (input
691 * Returns the converted config file or NULL if there was an error (for
692 * example the script could not be found in $PATH or the i3 executable’s
696 static char *migrate_config(char *input, off_t size) {
700 if (pipe(writepipe) != 0 ||
701 pipe(readpipe) != 0) {
702 warn("migrate_config: Could not create pipes");
708 warn("Could not fork()");
714 /* close writing end of writepipe, connect reading side to stdin */
716 dup2(writepipe[0], 0);
718 /* close reading end of readpipe, connect writing side to stdout */
720 dup2(readpipe[1], 1);
722 static char *argv[] = {
723 NULL, /* will be replaced by the executable path */
725 exec_i3_utility("i3-migrate-config-to-v4", argv);
730 /* close reading end of the writepipe (connected to the script’s stdin) */
733 /* write the whole config file to the pipe, the script will read everything
735 if (writeall(writepipe[1], input, size) == -1) {
736 warn("Could not write to pipe");
741 /* close writing end of the readpipe (connected to the script’s stdout) */
744 /* read the script’s output */
745 int conv_size = 65535;
746 char *converted = scalloc(conv_size, 1);
747 int read_bytes = 0, ret;
749 if (read_bytes == conv_size) {
751 converted = srealloc(converted, conv_size);
753 ret = read(readpipe[0], converted + read_bytes, conv_size - read_bytes);
755 warn("Cannot read from pipe");
762 /* get the returncode */
765 if (!WIFEXITED(status)) {
766 fprintf(stderr, "Child did not terminate normally, using old config file (will lead to broken behaviour)\n");
771 int returncode = WEXITSTATUS(status);
772 if (returncode != 0) {
773 fprintf(stderr, "Migration process exit code was != 0\n");
774 if (returncode == 2) {
775 fprintf(stderr, "could not start the migration script\n");
776 /* TODO: script was not found. tell the user to fix their system or create a v4 config */
777 } else if (returncode == 1) {
778 fprintf(stderr, "This already was a v4 config. Please add the following line to your config file:\n");
779 fprintf(stderr, "# i3 config file (v4)\n");
780 /* 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 FREE(current_config);
904 current_config = scalloc(stbuf.st_size + 1, 1);
905 if ((ssize_t)fread(current_config, 1, stbuf.st_size, fstr) != stbuf.st_size) {
906 die("Could not fread: %s\n", strerror(errno));
910 bool invalid_sets = false;
912 while (!feof(fstr)) {
914 continuation = buffer;
915 if (fgets(continuation, sizeof(buffer) - (continuation - buffer), fstr) == NULL) {
918 die("Could not read configuration file\n");
920 if (buffer[strlen(buffer) - 1] != '\n' && !feof(fstr)) {
921 ELOG("Your line continuation is too long, it exceeds %zd bytes\n", sizeof(buffer));
924 /* sscanf implicitly strips whitespace. */
926 const bool skip_line = (sscanf(buffer, "%511s %4095[^\n]", key, value) < 1 || strlen(key) < 3);
927 const bool comment = (key[0] == '#');
930 continuation = strstr(buffer, "\\\n");
935 DLOG("line continuation in comment is ignored: \"%.*s\"\n", (int)strlen(buffer) - 1, buffer);
939 strncpy(buf + strlen(buf), buffer, strlen(buffer) + 1);
941 /* Skip comments and empty lines. */
942 if (skip_line || comment) {
946 if (strcasecmp(key, "set") == 0 && *value != '\0') {
948 char v_value[4096] = {'\0'};
950 if (sscanf(value, "%511s %4095[^\n]", v_key, v_value) < 1) {
951 ELOG("Failed to parse variable specification '%s', skipping it.\n", value);
956 if (v_key[0] != '$') {
957 ELOG("Malformed variable assignment, name has to start with $\n");
962 upsert_variable(&variables, v_key, v_value);
964 } else if (strcasecmp(key, "set_from_resource") == 0) {
965 char res_name[512] = {'\0'};
967 char fallback[4096] = {'\0'};
969 /* Ensure that this string is terminated. For example, a user might
970 * want a variable to be empty if the resource can't be found and
972 * set_from_resource $foo i3wm.foo
973 * Without explicitly terminating the string first, sscanf() will
974 * leave it uninitialized, causing garbage in the config.*/
977 if (sscanf(value, "%511s %511s %4095[^\n]", v_key, res_name, fallback) < 1) {
978 ELOG("Failed to parse resource specification '%s', skipping it.\n", value);
983 if (v_key[0] != '$') {
984 ELOG("Malformed variable assignment, name has to start with $\n");
989 char *res_value = get_resource(res_name);
990 if (res_value == NULL) {
991 DLOG("Could not get resource '%s', using fallback '%s'.\n", res_name, fallback);
992 res_value = sstrdup(fallback);
995 upsert_variable(&variables, v_key, res_value);
1002 if (database != NULL) {
1003 xcb_xrm_database_free(database);
1004 /* Explicitly set the database to NULL again in case the config gets reloaded. */
1008 /* For every custom variable, see how often it occurs in the file and
1009 * how much extra bytes it requires when replaced. */
1010 struct Variable *current, *nearest;
1011 int extra_bytes = 0;
1012 /* We need to copy the buffer because we need to invalidate the
1013 * variables (otherwise we will count them twice, which is bad when
1014 * 'extra' is negative) */
1015 char *bufcopy = sstrdup(buf);
1016 SLIST_FOREACH(current, &variables, variables) {
1017 int extra = (strlen(current->value) - strlen(current->key));
1019 for (next = bufcopy;
1020 next < (bufcopy + stbuf.st_size) &&
1021 (next = strcasestr(next, current->key)) != NULL;
1022 next += strlen(current->key)) {
1024 extra_bytes += extra;
1029 /* Then, allocate a new buffer and copy the file over to the new one,
1030 * but replace occurrences of our variables */
1031 char *walk = buf, *destwalk;
1032 char *new = scalloc(stbuf.st_size + extra_bytes + 1, 1);
1034 while (walk < (buf + stbuf.st_size)) {
1035 /* Find the next variable */
1036 SLIST_FOREACH(current, &variables, variables)
1037 current->next_match = strcasestr(walk, current->key);
1039 int distance = stbuf.st_size;
1040 SLIST_FOREACH(current, &variables, variables) {
1041 if (current->next_match == NULL)
1043 if ((current->next_match - walk) < distance) {
1044 distance = (current->next_match - walk);
1048 if (nearest == NULL) {
1049 /* If there are no more variables, we just copy the rest */
1050 strncpy(destwalk, walk, (buf + stbuf.st_size) - walk);
1051 destwalk += (buf + stbuf.st_size) - walk;
1055 /* Copy until the next variable, then copy its value */
1056 strncpy(destwalk, walk, distance);
1057 strncpy(destwalk + distance, nearest->value, strlen(nearest->value));
1058 walk += distance + strlen(nearest->key);
1059 destwalk += distance + strlen(nearest->value);
1063 /* analyze the string to find out whether this is an old config file (3.x)
1064 * or a new config file (4.x). If it’s old, we run the converter script. */
1065 int version = detect_version(buf);
1067 /* We need to convert this v3 configuration */
1068 char *converted = migrate_config(new, strlen(new));
1069 if (converted != NULL) {
1071 ELOG("****************************************************************\n");
1072 ELOG("NOTE: Automatically converted configuration file from v3 to v4.\n");
1074 ELOG("Please convert your config file to v4. You can use this command:\n");
1075 ELOG(" mv %s %s.O\n", f, f);
1076 ELOG(" i3-migrate-config-to-v4 %s.O > %s\n", f, f);
1077 ELOG("****************************************************************\n");
1083 LOG("**********************************************************************\n");
1084 LOG("ERROR: Could not convert config file. Maybe i3-migrate-config-to-v4\n");
1085 LOG("was not correctly installed on your system?\n");
1086 LOG("**********************************************************************\n");
1091 context = scalloc(1, sizeof(struct context));
1092 context->filename = f;
1094 struct ConfigResultIR *config_output = parse_config(new, context);
1095 yajl_gen_free(config_output->json_gen);
1097 extract_workspace_names_from_bindings();
1098 check_for_duplicate_bindings(context);
1101 if (use_nagbar && (context->has_errors || context->has_warnings || invalid_sets)) {
1102 ELOG("FYI: You are using i3 version %s\n", i3_version);
1104 ELOG("Please convert your configfile first, then fix any remaining errors (see above).\n");
1106 start_config_error_nagbar(f, context->has_errors || invalid_sets);
1109 bool has_errors = context->has_errors;
1111 FREE(context->line_copy);
1116 while (!SLIST_EMPTY(&variables)) {
1117 current = SLIST_FIRST(&variables);
1119 FREE(current->value);
1120 SLIST_REMOVE_HEAD(&variables, variables);