rcfile.c 34.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
/**************************************************************************
 *   rcfile.c  --  This file is part of GNU nano.                         *
 *                                                                        *
 *   Copyright (C) 2001-2011, 2013-2017 Free Software Foundation, Inc.    *
 *   Copyright (C) 2014 Mike Frysinger                                    *
 *   Copyright (C) 2014, 2015, 2016 Benno Schulenberg                     *
 *                                                                        *
 *   GNU nano is free software: you can redistribute it and/or modify     *
 *   it under the terms of the GNU General Public License as published    *
 *   by the Free Software Foundation, either version 3 of the License,    *
 *   or (at your option) any later version.                               *
 *                                                                        *
 *   GNU nano is distributed in the hope that it will be useful,          *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty          *
 *   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.              *
 *   See the GNU General Public License for more details.                 *
 *                                                                        *
 *   You should have received a copy of the GNU General Public License    *
 *   along with this program.  If not, see http://www.gnu.org/licenses/.  *
 *                                                                        *
 **************************************************************************/

#include "proto.h"

#include <ctype.h>
#include <errno.h>
#include <glob.h>
#include <string.h>
#include <unistd.h>

#ifdef ENABLE_NANORC

#ifndef RCFILE_NAME
#define RCFILE_NAME ".nanorc"
#endif

static const rcoption rcopts[] = {
    {"boldtext", BOLD_TEXT},
#ifdef ENABLE_LINENUMBERS
    {"linenumbers", LINE_NUMBERS},
#endif
#ifndef DISABLE_JUSTIFY
    {"brackets", 0},
#endif
    {"const", CONSTANT_SHOW},  /* deprecated form, remove in 2018 */
    {"constantshow", CONSTANT_SHOW},
#ifndef DISABLE_WRAPJUSTIFY
    {"fill", 0},
#endif
#ifndef DISABLE_HISTORIES
    {"historylog", HISTORYLOG},
#endif
    {"morespace", MORE_SPACE},
#ifdef ENABLE_MOUSE
    {"mouse", USE_MOUSE},
#endif
#ifdef ENABLE_MULTIBUFFER
    {"multibuffer", MULTIBUFFER},
#endif
    {"nohelp", NO_HELP},
    {"nonewlines", NO_NEWLINES},
    {"nopauses", NO_PAUSES},
#ifndef DISABLE_WRAPPING
    {"nowrap", NO_WRAP},
#endif
#ifndef DISABLE_OPERATINGDIR
    {"operatingdir", 0},
#endif
#ifndef DISABLE_HISTORIES
    {"poslog", POS_HISTORY},  /* deprecated form, remove in 2018 */
    {"positionlog", POS_HISTORY},
#endif
    {"preserve", PRESERVE},
#ifndef DISABLE_JUSTIFY
    {"punct", 0},
    {"quotestr", 0},
#endif
    {"quickblank", QUICK_BLANK},
    {"rebinddelete", REBIND_DELETE},
    {"rebindkeypad", REBIND_KEYPAD},
    {"regexp", USE_REGEXP},
#ifndef DISABLE_SPELLER
    {"speller", 0},
#endif
    {"suspend", SUSPEND},
    {"tabsize", 0},
    {"tempfile", TEMP_FILE},
    {"view", VIEW_MODE},
#ifndef NANO_TINY
    {"allow_insecure_backup", INSECURE_BACKUP},
    {"atblanks", AT_BLANKS},
    {"autoindent", AUTOINDENT},
    {"backup", BACKUP_FILE},
    {"backupdir", 0},
    {"backwards", BACKWARDS_SEARCH},
    {"casesensitive", CASE_SENSITIVE},
    {"cut", CUT_FROM_CURSOR},  /* deprecated form, remove in 2020 */
    {"cutfromcursor", CUT_FROM_CURSOR},
    {"justifytrim", JUSTIFY_TRIM},
    {"locking", LOCKING},
    {"matchbrackets", 0},
    {"noconvert", NO_CONVERT},
    {"quiet", QUIET},
    {"showcursor", SHOW_CURSOR},
    {"smarthome", SMART_HOME},
    {"smooth", SMOOTH_SCROLL},
    {"softwrap", SOFTWRAP},
    {"tabstospaces", TABS_TO_SPACES},
    {"unix", MAKE_IT_UNIX},
    {"whitespace", 0},
    {"wordbounds", WORD_BOUNDS},
    {"wordchars", 0},
#endif
#ifndef DISABLE_COLOR
    {"titlecolor", 0},
    {"numbercolor", 0},
    {"selectedcolor", 0},
    {"statuscolor", 0},
    {"keycolor", 0},
    {"functioncolor", 0},
#endif
    {NULL, 0}
};

static bool errors = FALSE;
	/* Whether we got any errors while parsing an rcfile. */
static size_t lineno = 0;
	/* If we did, the line number where the last error occurred. */
static char *nanorc = NULL;
	/* The path to the rcfile we're parsing. */
#ifndef DISABLE_COLOR
static bool opensyntax = FALSE;
	/* Whether we're allowed to add to the last syntax.  When a file ends,
	 * or when a new syntax command is seen, this bool becomes FALSE. */
static syntaxtype *live_syntax;
	/* The syntax that is currently being parsed. */
static colortype *lastcolor = NULL;
	/* The end of the color list for the current syntax. */
#endif

/* We have an error in some part of the rcfile.  Print the error message
 * on stderr, and then make the user hit Enter to continue starting
 * nano. */
void rcfile_error(const char *msg, ...)
{
    va_list ap;

    if (ISSET(QUIET))
	return;

    fprintf(stderr, "\n");
    if (lineno > 0) {
	errors = TRUE;
	fprintf(stderr, _("Error in %s on line %lu: "), nanorc, (unsigned long)lineno);
    }

    va_start(ap, msg);
    vfprintf(stderr, _(msg), ap);
    va_end(ap);

    fprintf(stderr, "\n");
}
#endif /* ENABLE_NANORC */

#if defined(ENABLE_NANORC) || !defined(DISABLE_HISTORIES)
/* Parse the next word from the string, null-terminate it, and return
 * a pointer to the first character after the null terminator.  The
 * returned pointer will point to '\0' if we hit the end of the line. */
char *parse_next_word(char *ptr)
{
    while (!isblank((unsigned char)*ptr) && *ptr != '\0')
	ptr++;

    if (*ptr == '\0')
	return ptr;

    /* Null-terminate and advance ptr. */
    *ptr++ = '\0';

    while (isblank((unsigned char)*ptr))
	ptr++;

    return ptr;
}
#endif /* ENABLE_NANORC || !DISABLE_HISTORIES */

#ifdef ENABLE_NANORC
/* Parse an argument, with optional quotes, after a keyword that takes
 * one.  If the next word starts with a ", we say that it ends with the
 * last " of the line.  Otherwise, we interpret it as usual, so that the
 * arguments can contain "'s too. */
char *parse_argument(char *ptr)
{
    const char *ptr_save = ptr;
    char *last_quote = NULL;

    assert(ptr != NULL);

    if (*ptr != '"')
	return parse_next_word(ptr);

    do {
	ptr++;
	if (*ptr == '"')
	    last_quote = ptr;
    } while (*ptr != '\0');

    if (last_quote == NULL) {
	if (*ptr == '\0')
	    ptr = NULL;
	else
	    *ptr++ = '\0';
	rcfile_error(N_("Argument '%s' has an unterminated \""), ptr_save);
    } else {
	*last_quote = '\0';
	ptr = last_quote + 1;
    }
    if (ptr != NULL)
	while (isblank((unsigned char)*ptr))
	    ptr++;
    return ptr;
}

#ifndef DISABLE_COLOR
/* Pass over the current regex string in the line starting at ptr,
 * null-terminate it, and return a pointer to the /next/ word. */
char *parse_next_regex(char *ptr)
{
    assert(ptr != NULL);

    /* Continue until the end of line, or until a " followed by a
     * blank character or the end of line. */
    while (*ptr != '\0' && (*ptr != '"' ||
		(*(ptr + 1) != '\0' && !isblank((unsigned char)ptr[1]))))
	ptr++;

    assert(*ptr == '"' || *ptr == '\0');

    if (*ptr == '\0') {
	rcfile_error(
		N_("Regex strings must begin and end with a \" character"));
	return NULL;
    }

    /* Null-terminate and advance ptr. */
    *ptr++ = '\0';

    while (isblank((unsigned char)*ptr))
	ptr++;

    return ptr;
}

/* Compile the regular expression regex to see if it's valid.  Return
 * TRUE if it is, and FALSE otherwise. */
bool nregcomp(const char *regex, int compile_flags)
{
    regex_t preg;
    const char *r = fixbounds(regex);
    int rc = regcomp(&preg, r, compile_flags);

    if (rc != 0) {
	size_t len = regerror(rc, &preg, NULL, 0);
	char *str = charalloc(len);

	regerror(rc, &preg, str, len);
	rcfile_error(N_("Bad regex \"%s\": %s"), r, str);
	free(str);
    }

    regfree(&preg);
    return (rc == 0);
}

/* Parse the next syntax name and its possible extension regexes from the
 * line at ptr, and add it to the global linked list of color syntaxes. */
void parse_syntax(char *ptr)
{
    char *nameptr;
	/* A pointer to what should be the name of the syntax. */

    opensyntax = FALSE;

    assert(ptr != NULL);

    /* Check that the syntax name is not empty. */
    if (*ptr == '\0' || (*ptr == '"' &&
			(*(ptr + 1) == '\0' || *(ptr + 1) == '"'))) {
	rcfile_error(N_("Missing syntax name"));
	return;
    }

    nameptr = ++ptr;
    ptr = parse_next_word(ptr);

    /* Check that the name starts and ends with a double quote. */
    if (*(nameptr - 1) != '\x22' || nameptr[strlen(nameptr) - 1] != '\x22') {
	rcfile_error(N_("A syntax name must be quoted"));
	return;
    }

    /* Strip the end quote. */
    nameptr[strlen(nameptr) - 1] = '\0';

    /* Redefining the "none" syntax is not allowed. */
    if (strcmp(nameptr, "none") == 0) {
	rcfile_error(N_("The \"none\" syntax is reserved"));
	return;
    }

    /* Initialize a new syntax struct. */
    live_syntax = (syntaxtype *)nmalloc(sizeof(syntaxtype));
    live_syntax->name = mallocstrcpy(NULL, nameptr);
    live_syntax->extensions = NULL;
    live_syntax->headers = NULL;
    live_syntax->magics = NULL;
    live_syntax->linter = NULL;
    live_syntax->formatter = NULL;
#ifdef ENABLE_COMMENT
    live_syntax->comment = mallocstrcpy(NULL, GENERAL_COMMENT_CHARACTER);
#endif
    live_syntax->color = NULL;
    lastcolor = NULL;
    live_syntax->nmultis = 0;

    /* Hook the new syntax in at the top of the list. */
    live_syntax->next = syntaxes;
    syntaxes = live_syntax;

    opensyntax = TRUE;

#ifdef DEBUG
    fprintf(stderr, "Starting a new syntax type: \"%s\"\n", nameptr);
#endif

    /* The default syntax should have no associated extensions. */
    if (strcmp(live_syntax->name, "default") == 0 && *ptr != '\0') {
	rcfile_error(
		N_("The \"default\" syntax does not accept extensions"));
	return;
    }

    /* If there seem to be extension regexes, pick them up. */
    if (*ptr != '\0')
	grab_and_store("extension", ptr, &live_syntax->extensions);
}
#endif /* !DISABLE_COLOR */

/* Check whether the given executable function is "universal" (meaning
 * any horizontal movement or deletion) and thus is present in almost
 * all menus. */
bool is_universal(void (*func)(void))
{
    if (func == do_left || func == do_right ||
	func == do_home_void || func == do_end_void ||
#ifndef NANO_TINY
	func == do_prev_word_void || func == do_next_word_void ||
#endif
	func == do_delete || func == do_backspace ||
	func == do_cut_text_void || func == do_uncut_text ||
	func == do_tab || func == do_enter || func == do_verbatim_input)
	return TRUE;
    else
	return FALSE;
}

/* Bind or unbind a key combo, to or from a function. */
void parse_binding(char *ptr, bool dobind)
{
    char *keyptr = NULL, *keycopy = NULL, *funcptr = NULL, *menuptr = NULL;
    sc *s, *newsc = NULL;
    int menu;

    assert(ptr != NULL);

#ifdef DEBUG
    fprintf(stderr, "Starting the rebinding code...\n");
#endif

    if (*ptr == '\0') {
	rcfile_error(N_("Missing key name"));
	return;
    }

    keyptr = ptr;
    ptr = parse_next_word(ptr);
    keycopy = mallocstrcpy(NULL, keyptr);

    if (strlen(keycopy) < 2) {
	rcfile_error(N_("Key name is too short"));
	goto free_copy;
    }

    /* Uppercase only the first two or three characters of the key name. */
    keycopy[0] = toupper((unsigned char)keycopy[0]);
    keycopy[1] = toupper((unsigned char)keycopy[1]);
    if (keycopy[0] == 'M' && keycopy[1] == '-') {
	if (strlen(keycopy) > 2)
	    keycopy[2] = toupper((unsigned char)keycopy[2]);
	else {
	    rcfile_error(N_("Key name is too short"));
	    goto free_copy;
	}
    }

    /* Allow the codes for Insert and Delete to be rebound, but apart
     * from those two only Control, Meta and Function sequences. */
    if (!strcasecmp(keycopy, "Ins") || !strcasecmp(keycopy, "Del"))
	keycopy[1] = tolower((unsigned char)keycopy[1]);
    else if (keycopy[0] != '^' && keycopy[0] != 'M' && keycopy[0] != 'F') {
	rcfile_error(N_("Key name must begin with \"^\", \"M\", or \"F\""));
	goto free_copy;
    } else if ((keycopy[0] == 'M' && keycopy[1] != '-') ||
		(keycopy[0] == '^' && ((keycopy[1] < 'A' || keycopy[1] > 'z') ||
		keycopy[1] == '[' || keycopy[1] == '`' ||
		(strlen(keycopy) > 2 && strcmp(keycopy, "^Space") != 0))) ||
		(strlen(keycopy) > 3 && strcmp(keycopy, "^Space") != 0 &&
		strcmp(keycopy, "M-Space") != 0)) {
	rcfile_error(N_("Key name %s is invalid"), keycopy);
	goto free_copy;
    }

    if (dobind) {
	funcptr = ptr;
	ptr = parse_next_word(ptr);

	if (funcptr[0] == '\0') {
	    rcfile_error(N_("Must specify a function to bind the key to"));
	    goto free_copy;
	}
    }

    menuptr = ptr;
    ptr = parse_next_word(ptr);

    if (menuptr[0] == '\0') {
	/* TRANSLATORS: Do not translate the word "all". */
	rcfile_error(N_("Must specify a menu (or \"all\") in which to bind/unbind the key"));
	goto free_copy;
    }

    if (dobind) {
	newsc = strtosc(funcptr);
	if (newsc == NULL) {
	    rcfile_error(N_("Cannot map name \"%s\" to a function"), funcptr);
	    goto free_copy;
	}
    }

    menu = strtomenu(menuptr);
    if (menu < 1) {
	rcfile_error(N_("Cannot map name \"%s\" to a menu"), menuptr);
	goto free_copy;
    }

#ifdef DEBUG
    if (dobind)
	fprintf(stderr, "newsc address is now %ld, assigned func = %ld, menu = %x\n",
	    (long)&newsc, (long)newsc->scfunc, menu);
    else
	fprintf(stderr, "unbinding \"%s\" from menu %x\n", keycopy, menu);
#endif

    if (dobind) {
	subnfunc *f;
	int mask = 0;

	/* Tally up the menus where the function exists. */
	for (f = allfuncs; f != NULL; f = f->next)
	    if (f->scfunc == newsc->scfunc)
		mask = mask | f->menus;

#ifndef NANO_TINY
	/* Handle the special case of the toggles. */
	if (newsc->scfunc == do_toggle_void)
	    mask = MMAIN;
#endif

	/* Now limit the given menu to those where the function exists. */
	if (is_universal(newsc->scfunc))
	    menu = menu & MMOST;
	else
	    menu = menu & mask;

	if (!menu) {
	    rcfile_error(N_("Function '%s' does not exist in menu '%s'"), funcptr, menuptr);
	    free(newsc);
	    goto free_copy;
	}

	newsc->menus = menu;
	assign_keyinfo(newsc, keycopy, 0);

	/* Do not allow rebinding a frequent escape-sequence starter: Esc [. */
	if (newsc->meta && newsc->keycode == 91) {
	    rcfile_error(N_("Sorry, keystroke \"%s\" may not be rebound"), newsc->keystr);
	    free(newsc);
	    goto free_copy;
	}
#ifdef DEBUG
	fprintf(stderr, "s->keystr = \"%s\"\n", newsc->keystr);
	fprintf(stderr, "s->keycode = \"%d\"\n", newsc->keycode);
#endif
    }

    /* Now find and delete any existing same shortcut in the menu(s). */
    for (s = sclist; s != NULL; s = s->next) {
	if ((s->menus & menu) && !strcmp(s->keystr, keycopy)) {
#ifdef DEBUG
	    fprintf(stderr, "deleting entry from among menus %x\n", s->menus);
#endif
	    s->menus &= ~menu;
	}
    }

    if (dobind) {
#ifndef NANO_TINY
	/* If this is a toggle, copy its sequence number. */
	if (newsc->scfunc == do_toggle_void) {
	    for (s = sclist; s != NULL; s = s->next)
		if (s->scfunc == do_toggle_void && s->toggle == newsc->toggle)
		    newsc->ordinal = s->ordinal;
	} else
	    newsc->ordinal = 0;
#endif
	/* Add the new shortcut at the start of the list. */
	newsc->next = sclist;
	sclist = newsc;
	return;
    }

  free_copy:
    free(keycopy);
}

/* Verify that the given file is not a folder nor a device. */
bool is_good_file(char *file)
{
    struct stat rcinfo;

    /* If the thing exists, it may not be a directory nor a device. */
    if (stat(file, &rcinfo) != -1 && (S_ISDIR(rcinfo.st_mode) ||
		S_ISCHR(rcinfo.st_mode) || S_ISBLK(rcinfo.st_mode))) {
	rcfile_error(S_ISDIR(rcinfo.st_mode) ? _("\"%s\" is a directory") :
					_("\"%s\" is a device file"), file);
	return FALSE;
    } else
	return TRUE;
}

#ifndef DISABLE_COLOR
/* Read and parse one included syntax file. */
static void parse_one_include(char *file)
{
    FILE *rcstream;

    /* Don't open directories, character files, or block files. */
    if (!is_good_file(file))
	return;

    /* Open the included syntax file. */
    rcstream = fopen(file, "rb");

    if (rcstream == NULL) {
	rcfile_error(_("Error reading %s: %s"), file, strerror(errno));
	return;
    }

    /* Use the name and line number position of the included syntax file
     * while parsing it, so we can know where any errors in it are. */
    nanorc = file;
    lineno = 0;

#ifdef DEBUG
    fprintf(stderr, "Parsing file \"%s\"\n", file);
#endif

    parse_rcfile(rcstream, TRUE);
}

/* Expand globs in the passed name, and parse the resultant files. */
void parse_includes(char *ptr)
{
    char *option, *nanorc_save = nanorc, *expanded;
    size_t lineno_save = lineno, i;
    glob_t files;

    option = ptr;
    if (*option == '"')
	option++;
    ptr = parse_argument(ptr);

    /* Expand tildes first, then the globs. */
    expanded = real_dir_from_tilde(option);

    if (glob(expanded, GLOB_ERR|GLOB_NOSORT, NULL, &files) == 0) {
	for (i = 0; i < files.gl_pathc; ++i)
	    parse_one_include(files.gl_pathv[i]);
    } else
	rcfile_error(_("Error expanding %s: %s"), option, strerror(errno));

    globfree(&files);
    free(expanded);

    /* We're done with the included file(s).  Restore the original
     * filename and line number position. */
    nanorc = nanorc_save;
    lineno = lineno_save;
}

/* Return the short value corresponding to the color named in colorname,
 * and set bright to TRUE if that color is bright. */
short color_to_short(const char *colorname, bool *bright)
{
    if (strncasecmp(colorname, "bright", 6) == 0) {
	*bright = TRUE;
	colorname += 6;
    }

    if (strcasecmp(colorname, "green") == 0)
	return COLOR_GREEN;
    else if (strcasecmp(colorname, "red") == 0)
	return COLOR_RED;
    else if (strcasecmp(colorname, "blue") == 0)
	return COLOR_BLUE;
    else if (strcasecmp(colorname, "white") == 0)
	return COLOR_WHITE;
    else if (strcasecmp(colorname, "yellow") == 0)
	return COLOR_YELLOW;
    else if (strcasecmp(colorname, "cyan") == 0)
	return COLOR_CYAN;
    else if (strcasecmp(colorname, "magenta") == 0)
	return COLOR_MAGENTA;
    else if (strcasecmp(colorname, "black") == 0)
	return COLOR_BLACK;

    rcfile_error(N_("Color \"%s\" not understood.\n"
		"Valid colors are \"green\", \"red\", \"blue\",\n"
		"\"white\", \"yellow\", \"cyan\", \"magenta\" and\n"
		"\"black\", with the optional prefix \"bright\"\n"
		"for foreground colors."), colorname);
    return -1;
}

/* Parse the color string in the line at ptr, and add it to the current
 * file's associated colors.  rex_flags are the regex compilation flags
 * to use, excluding or including REG_ICASE for case (in)sensitivity. */
void parse_colors(char *ptr, int rex_flags)
{
    short fg, bg;
    bool bright = FALSE;
    char *item;

    if (!opensyntax) {
	rcfile_error(
		N_("A '%s' command requires a preceding 'syntax' command"),
		"color");
	return;
    }

    if (*ptr == '\0') {
	rcfile_error(N_("Missing color name"));
	return;
    }

    item = ptr;
    ptr = parse_next_word(ptr);
    if (!parse_color_names(item, &fg, &bg, &bright))
	return;

    if (*ptr == '\0') {
	rcfile_error(N_("Missing regex string after '%s' command"), "color");
	return;
    }

    /* Now for the fun part.  Start adding regexes to individual strings
     * in the colorstrings array, woo! */
    while (ptr != NULL && *ptr != '\0') {
	colortype *newcolor = NULL;
	    /* The container for a color plus its regexes. */
	bool goodstart;
	    /* Whether the start expression was valid. */
	bool expectend = FALSE;
	    /* Whether to expect an end= line. */

	if (strncasecmp(ptr, "start=", 6) == 0) {
	    ptr += 6;
	    expectend = TRUE;
	}

	if (*ptr != '"') {
	    rcfile_error(
		N_("Regex strings must begin and end with a \" character"));
	    ptr = parse_next_regex(ptr);
	    continue;
	}

	item = ++ptr;
	ptr = parse_next_regex(ptr);
	if (ptr == NULL)
	    break;

	if (*item == '\0') {
	    rcfile_error(N_("Empty regex string"));
	    goodstart = FALSE;
	} else
	    goodstart = nregcomp(item, rex_flags);

	/* If the starting regex is valid, initialize a new color struct,
	 * and hook it in at the tail of the linked list. */
	if (goodstart) {
	    newcolor = (colortype *)nmalloc(sizeof(colortype));

	    newcolor->fg = fg;
	    newcolor->bg = bg;
	    newcolor->bright = bright;
	    newcolor->rex_flags = rex_flags;

	    newcolor->start_regex = mallocstrcpy(NULL, item);
	    newcolor->start = NULL;

	    newcolor->end_regex = NULL;
	    newcolor->end = NULL;

	    newcolor->next = NULL;

	    if (lastcolor == NULL)
		live_syntax->color = newcolor;
	    else
		lastcolor->next = newcolor;

	    lastcolor = newcolor;
	}

	if (!expectend)
	    continue;

	if (ptr == NULL || strncasecmp(ptr, "end=", 4) != 0) {
	    rcfile_error(N_("\"start=\" requires a corresponding \"end=\""));
	    return;
	}

	ptr += 4;
	if (*ptr != '"') {
	    rcfile_error(N_("Regex strings must begin and end with a \" character"));
	    continue;
	}

	item = ++ptr;
	ptr = parse_next_regex(ptr);
	if (ptr == NULL)
	    break;

	if (*item == '\0') {
	    rcfile_error(N_("Empty regex string"));
	    continue;
	}

	/* If the start regex was invalid, skip past the end regex
	 * to stay in sync. */
	if (!goodstart)
	    continue;

	/* If it's valid, save the ending regex string. */
	if (nregcomp(item, rex_flags))
	    newcolor->end_regex = mallocstrcpy(NULL, item);

	/* Lame way to skip another static counter. */
	newcolor->id = live_syntax->nmultis;
	live_syntax->nmultis++;
    }
}

/* Parse the color name, or pair of color names, in combostr. */
bool parse_color_names(char *combostr, short *fg, short *bg, bool *bright)
{
    char *comma = strchr(combostr, ',');

    if (comma != NULL) {
	*bg = color_to_short(comma + 1, bright);
	if (*bright) {
	    rcfile_error(N_("A background color cannot be bright"));
	    return FALSE;
	}
	*comma = '\0';
    } else
	*bg = -1;

    if (comma != combostr) {
	*fg = color_to_short(combostr, bright);

	/* If the specified foreground color is bad, ignore the regexes. */
	if (*fg == -1)
	    return FALSE;
    } else
	*fg = -1;

    return TRUE;
}

/* Read regex strings enclosed in double quotes from the line pointed at
 * by ptr, and store them quoteless in the passed storage place. */
void grab_and_store(const char *kind, char *ptr, regexlisttype **storage)
{
    regexlisttype *lastthing;

    if (!opensyntax) {
	rcfile_error(
		N_("A '%s' command requires a preceding 'syntax' command"), kind);
	return;
    }

    /* The default syntax doesn't take any file matching stuff. */
    if (strcmp(live_syntax->name, "default") == 0 && *ptr != '\0') {
	rcfile_error(
		N_("The \"default\" syntax does not accept '%s' regexes"), kind);
	return;
    }

    if (*ptr == '\0') {
	rcfile_error(N_("Missing regex string after '%s' command"), kind);
	return;
    }

    lastthing = *storage;

    /* If there was an earlier command, go to the last of those regexes. */
    while (lastthing != NULL && lastthing->next != NULL)
	lastthing = lastthing->next;

    /* Now gather any valid regexes and add them to the linked list. */
    while (*ptr != '\0') {
	const char *regexstring;
	regexlisttype *newthing;

	if (*ptr != '"') {
	    rcfile_error(
		N_("Regex strings must begin and end with a \" character"));
	    return;
	}

	regexstring = ++ptr;
	ptr = parse_next_regex(ptr);
	if (ptr == NULL)
	    return;

	/* If the regex string is malformed, skip it. */
	if (!nregcomp(regexstring, NANO_REG_EXTENDED | REG_NOSUB))
	    continue;

	/* Copy the regex into a struct, and hook this in at the end. */
	newthing = (regexlisttype *)nmalloc(sizeof(regexlisttype));
	newthing->full_regex = mallocstrcpy(NULL, regexstring);
	newthing->next = NULL;

	if (lastthing == NULL)
	    *storage = newthing;
	else
	    lastthing->next = newthing;

	lastthing = newthing;
    }
}

/* Gather and store the string after a comment/linter/formatter command. */
void pick_up_name(const char *kind, char *ptr, char **storage)
{
    assert(ptr != NULL);

    if (!opensyntax) {
	rcfile_error(
		N_("A '%s' command requires a preceding 'syntax' command"), kind);
	return;
    }

    if (*ptr == '\0') {
	rcfile_error(N_("Missing argument after '%s'"), kind);
	return;
    }

    /* If the argument starts with a quote, find the terminating quote. */
    if (*ptr == '"') {
	char *look = ++ptr;

	look += strlen(ptr);

	while (*look != '"') {
	    if (--look < ptr) {
		rcfile_error(N_("Argument of '%s' lacks closing \""), kind);
		return;
	    }
	}
	*look = '\0';
    }

    *storage = mallocstrcpy(*storage, ptr);

}
#endif /* !DISABLE_COLOR */

/* Verify that the user has not unmapped every shortcut for a
 * function that we consider 'vital' (such as "Exit"). */
static void check_vitals_mapped(void)
{
    subnfunc *f;
    int v;
#define VITALS 5
    void (*vitals[VITALS])(void) = { do_exit, do_exit, do_cancel, do_cancel, do_cancel };
    int inmenus[VITALS] = { MMAIN, MHELP, MWHEREIS, MREPLACE, MGOTOLINE };

    for  (v = 0; v < VITALS; v++) {
	for (f = allfuncs; f != NULL; f = f->next) {
	    if (f->scfunc == vitals[v] && f->menus & inmenus[v]) {
		const sc *s = first_sc_for(inmenus[v], f->scfunc);
		if (!s) {
		    fprintf(stderr, _("Fatal error: no keys mapped for function "
					"\"%s\".  Exiting.\n"), f->desc);
		    fprintf(stderr, _("If needed, use nano with the -I option "
					"to adjust your nanorc settings.\n"));
		    exit(1);
		}
		break;
	    }
	}
    }
}

/* Parse the rcfile, once it has been opened successfully at rcstream,
 * and close it afterwards.  If syntax_only is TRUE, allow the file to
 * to contain only color syntax commands. */
void parse_rcfile(FILE *rcstream, bool syntax_only)
{
    char *buf = NULL;
    ssize_t len;
    size_t n = 0;

    while ((len = getline(&buf, &n, rcstream)) > 0) {
	char *ptr, *keyword, *option;
	int set = 0;
	size_t i;

	/* Ignore the newline. */
	if (buf[len - 1] == '\n')
	    buf[len - 1] = '\0';

	lineno++;
	ptr = buf;
	while (isblank((unsigned char)*ptr))
	    ptr++;

	/* If we have a blank line or a comment, skip to the next
	 * line. */
	if (*ptr == '\0' || *ptr == '#')
	    continue;

	/* Otherwise, skip to the next space. */
	keyword = ptr;
	ptr = parse_next_word(ptr);

#ifndef DISABLE_COLOR
	/* Handle extending first... */
	if (strcasecmp(keyword, "extendsyntax") == 0) {
	    syntaxtype *sint;
	    char *syntaxname = ptr;

	    ptr = parse_next_word(ptr);

	    for (sint = syntaxes; sint != NULL; sint = sint->next)
		if (!strcmp(sint->name, syntaxname))
		    break;

	    if (sint == NULL) {
		rcfile_error(N_("Could not find syntax \"%s\" to extend"),
				syntaxname);
		opensyntax = FALSE;
		continue;
	    }

	    live_syntax = sint;
	    opensyntax = TRUE;

	    /* Refind the tail of the color list for this syntax. */
	    lastcolor = sint->color;
	    if (lastcolor != NULL)
		while (lastcolor->next != NULL)
		    lastcolor = lastcolor->next;

	    keyword = ptr;
	    ptr = parse_next_word(ptr);
	}

	/* Try to parse the keyword. */
	if (strcasecmp(keyword, "syntax") == 0) {
	    if (opensyntax && lastcolor == NULL)
		rcfile_error(N_("Syntax \"%s\" has no color commands"),
				live_syntax->name);
	    parse_syntax(ptr);
	}
	else if (strcasecmp(keyword, "header") == 0)
	    grab_and_store("header", ptr, &live_syntax->headers);
	else if (strcasecmp(keyword, "magic") == 0)
#ifdef HAVE_LIBMAGIC
	    grab_and_store("magic", ptr, &live_syntax->magics);
#else
	    ;
#endif
	else if (strcasecmp(keyword, "comment") == 0)
#ifdef ENABLE_COMMENT
	    pick_up_name("comment", ptr, &live_syntax->comment);
#else
	    ;
#endif
	else if (strcasecmp(keyword, "color") == 0)
	    parse_colors(ptr, NANO_REG_EXTENDED);
	else if (strcasecmp(keyword, "icolor") == 0)
	    parse_colors(ptr, NANO_REG_EXTENDED | REG_ICASE);
	else if (strcasecmp(keyword, "linter") == 0)
	    pick_up_name("linter", ptr, &live_syntax->linter);
	else if (strcasecmp(keyword, "formatter") == 0)
#ifndef DISABLE_SPELLER
	    pick_up_name("formatter", ptr, &live_syntax->formatter);
#else
	    ;
#endif
	else if (syntax_only)
	    rcfile_error(N_("Command \"%s\" not allowed in included file"),
					keyword);
	else if (strcasecmp(keyword, "include") == 0)
	    parse_includes(ptr);
	else
#endif /* !DISABLE_COLOR */
	if (strcasecmp(keyword, "set") == 0)
	    set = 1;
	else if (strcasecmp(keyword, "unset") == 0)
	    set = -1;
	else if (strcasecmp(keyword, "bind") == 0)
	    parse_binding(ptr, TRUE);
	else if (strcasecmp(keyword, "unbind") == 0)
	    parse_binding(ptr, FALSE);
	else
	    rcfile_error(N_("Command \"%s\" not understood"), keyword);

#ifndef DISABLE_COLOR
	/* If a syntax was extended, it stops at the end of the command. */
	if (live_syntax != syntaxes)
	    opensyntax = FALSE;
#endif

	if (set == 0)
	    continue;

	if (*ptr == '\0') {
	    rcfile_error(N_("Missing option"));
	    continue;
	}

	option = ptr;
	ptr = parse_next_word(ptr);

	/* Find the just read name among the existing options. */
	for (i = 0; rcopts[i].name != NULL; i++) {
	    if (strcasecmp(option, rcopts[i].name) == 0)
		break;
	}

	if (rcopts[i].name == NULL) {
	    rcfile_error(N_("Unknown option \"%s\""), option);
	    continue;
	}

#ifdef DEBUG
	fprintf(stderr, "    Option name = \"%s\"\n", rcopts[i].name);
	fprintf(stderr, "    Flag = %ld\n", rcopts[i].flag);
#endif
	/* First handle unsetting. */
	if (set == -1) {
	    if (rcopts[i].flag != 0)
		UNSET(rcopts[i].flag);
	    else
		rcfile_error(N_("Cannot unset option \"%s\""), rcopts[i].name);
	    continue;
	}

	/* If the option has a flag, it doesn't take an argument. */
	if (rcopts[i].flag != 0) {
	    SET(rcopts[i].flag);
	    continue;
	}

	/* The option doesn't have a flag, so it takes an argument. */
	if (*ptr == '\0') {
	    rcfile_error(N_("Option \"%s\" requires an argument"),
				rcopts[i].name);
	    continue;
	}

	option = ptr;
	if (*option == '"')
	    option++;
	ptr = parse_argument(ptr);

	option = mallocstrcpy(NULL, option);
#ifdef DEBUG
	fprintf(stderr, "    Option argument = \"%s\"\n", option);
#endif
	/* Make sure the option argument is a valid multibyte string. */
	if (!is_valid_mbstring(option)) {
	    rcfile_error(N_("Argument is not a valid multibyte string"));
	    continue;
	}

#ifndef DISABLE_COLOR
	if (strcasecmp(rcopts[i].name, "titlecolor") == 0)
	    specified_color_combo[TITLE_BAR] = option;
	else if (strcasecmp(rcopts[i].name, "numbercolor") == 0)
	    specified_color_combo[LINE_NUMBER] = option;
	else if (strcasecmp(rcopts[i].name, "selectedcolor") == 0)
	    specified_color_combo[SELECTED_TEXT] = option;
	else if (strcasecmp(rcopts[i].name, "statuscolor") == 0)
	    specified_color_combo[STATUS_BAR] = option;
	else if (strcasecmp(rcopts[i].name, "keycolor") == 0)
	    specified_color_combo[KEY_COMBO] = option;
	else if (strcasecmp(rcopts[i].name, "functioncolor") == 0)
	    specified_color_combo[FUNCTION_TAG] = option;
	else
#endif
#ifndef DISABLE_OPERATINGDIR
	if (strcasecmp(rcopts[i].name, "operatingdir") == 0)
	    operating_dir = option;
	else
#endif
#ifndef DISABLE_WRAPJUSTIFY
	if (strcasecmp(rcopts[i].name, "fill") == 0) {
	    if (!parse_num(option, &wrap_at)) {
		rcfile_error(N_("Requested fill size \"%s\" is invalid"),
				option);
		wrap_at = -CHARS_FROM_EOL;
	    } else
		UNSET(NO_WRAP);
	    free(option);
	} else
#endif
#ifndef NANO_TINY
	if (strcasecmp(rcopts[i].name, "matchbrackets") == 0) {
	    matchbrackets = option;
	    if (has_blank_mbchars(matchbrackets)) {
		rcfile_error(N_("Non-blank characters required"));
		free(matchbrackets);
		matchbrackets = NULL;
	    }
	} else if (strcasecmp(rcopts[i].name, "whitespace") == 0) {
	    whitespace = option;
	    if (mbstrlen(whitespace) != 2 || strlenpt(whitespace) != 2) {
		rcfile_error(N_("Two single-column characters required"));
		free(whitespace);
		whitespace = NULL;
	    } else {
		whitespace_len[0] = parse_mbchar(whitespace, NULL, NULL);
		whitespace_len[1] = parse_mbchar(whitespace +
					whitespace_len[0], NULL, NULL);
	    }
	} else
#endif
#ifndef DISABLE_JUSTIFY
	if (strcasecmp(rcopts[i].name, "punct") == 0) {
	    punct = option;
	    if (has_blank_mbchars(punct)) {
		rcfile_error(N_("Non-blank characters required"));
		free(punct);
		punct = NULL;
	    }
	} else if (strcasecmp(rcopts[i].name, "brackets") == 0) {
	    brackets = option;
	    if (has_blank_mbchars(brackets)) {
		rcfile_error(N_("Non-blank characters required"));
		free(brackets);
		brackets = NULL;
	    }
	} else if (strcasecmp(rcopts[i].name, "quotestr") == 0)
	    quotestr = option;
	else
#endif
#ifndef NANO_TINY
	if (strcasecmp(rcopts[i].name, "backupdir") == 0)
	    backup_dir = option;
	else
	if (strcasecmp(rcopts[i].name, "wordchars") == 0)
	    word_chars = option;
	else
#endif
#ifndef DISABLE_SPELLER
	if (strcasecmp(rcopts[i].name, "speller") == 0)
	    alt_speller = option;
	else
#endif
	if (strcasecmp(rcopts[i].name, "tabsize") == 0) {
	    if (!parse_num(option, &tabsize) || tabsize <= 0) {
		rcfile_error(N_("Requested tab size \"%s\" is invalid"),
				option);
		tabsize = -1;
	    }
	    free(option);
	} else
	    assert(FALSE);
    }

#ifndef DISABLE_COLOR
    if (opensyntax && lastcolor == NULL)
	rcfile_error(N_("Syntax \"%s\" has no color commands"),
			live_syntax->name);

    opensyntax = FALSE;
#endif

    free(buf);
    fclose(rcstream);
    lineno = 0;

    return;
}

/* Read and interpret one of the two nanorc files. */
void parse_one_nanorc(void)
{
    FILE *rcstream;

    /* Don't try to open directories nor devices. */
    if (!is_good_file(nanorc))
	return;

#ifdef DEBUG
    fprintf(stderr, "Going to parse file \"%s\"\n", nanorc);
#endif

    rcstream = fopen(nanorc, "rb");

    /* If opening the file succeeded, parse it.  Otherwise, only
     * complain if the file actually exists. */
    if (rcstream != NULL)
	parse_rcfile(rcstream, FALSE);
    else if (errno != ENOENT)
	rcfile_error(N_("Error reading %s: %s"), nanorc, strerror(errno));
}

/* First read the system-wide rcfile, then the user's rcfile. */
void do_rcfiles(void)
{
    nanorc = mallocstrcpy(nanorc, SYSCONFDIR "/nanorc");

    /* Process the system-wide nanorc. */
    parse_one_nanorc();

    /* When configured with --disable-wrapping-as-root, turn wrapping off
     * for root, so that only root's .nanorc or --fill can turn it on. */
#ifdef DISABLE_ROOTWRAPPING
    if (geteuid() == NANO_ROOT_UID)
	SET(NO_WRAP);
#endif

    get_homedir();

    if (homedir == NULL)
	rcfile_error(N_("I can't find my home directory!  Wah!"));
    else {
	nanorc = charealloc(nanorc, strlen(homedir) + strlen(RCFILE_NAME) + 2);
	sprintf(nanorc, "%s/%s", homedir, RCFILE_NAME);

	/* Process the current user's nanorc. */
	parse_one_nanorc();
    }

    check_vitals_mapped();

    free(nanorc);

    if (errors && !ISSET(QUIET) && !ISSET(NO_PAUSES)) {
	errors = FALSE;
	fprintf(stderr, _("\nPress Enter to continue starting nano.\n"));
	while (getchar() != '\n')
	    ;
    }
}

#endif /* ENABLE_NANORC */