history.c 17.2 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
/**************************************************************************
 *   history.c  --  This file is part of GNU nano.                        *
 *                                                                        *
 *   Copyright (C) 2003-2011, 2013-2017 Free Software Foundation, Inc.    *
 *   Copyright (C) 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 <errno.h>
#include <string.h>

#ifndef DISABLE_HISTORIES
static bool history_changed = FALSE;
	/* Have any of the history lists changed? */

/* Initialize the search and replace history lists. */
void history_init(void)
{
    search_history = make_new_node(NULL);
    search_history->data = mallocstrcpy(NULL, "");
    searchtop = search_history;
    searchbot = search_history;

    replace_history = make_new_node(NULL);
    replace_history->data = mallocstrcpy(NULL, "");
    replacetop = replace_history;
    replacebot = replace_history;

    execute_history = make_new_node(NULL);
    execute_history->data = mallocstrcpy(NULL, "");
    executetop = execute_history;
    executebot = execute_history;
}

/* Set the current position in the history list h to the bottom. */
void history_reset(const filestruct *h)
{
    if (h == search_history)
	search_history = searchbot;
    else if (h == replace_history)
	replace_history = replacebot;
    else if (h == execute_history)
	execute_history = executebot;
}

/* Return the first node containing the first len characters of the
 * string s in the history list, starting at h_start and ending at
 * h_end, or NULL if there isn't one. */
filestruct *find_history(const filestruct *h_start, const filestruct
	*h_end, const char *s, size_t len)
{
    const filestruct *p;

    for (p = h_start; p != h_end->prev && p != NULL; p = p->prev) {
	if (strncmp(s, p->data, len) == 0)
	    return (filestruct *)p;
    }

    return NULL;
}

/* Update a history list (the one in which h is the current position)
 * with a fresh string s.  That is: add s, or move it to the end. */
void update_history(filestruct **h, const char *s)
{
    filestruct **htop = NULL, **hbot = NULL, *thesame;

    if (*h == search_history) {
	htop = &searchtop;
	hbot = &searchbot;
    } else if (*h == replace_history) {
	htop = &replacetop;
	hbot = &replacebot;
    } else if (*h == execute_history) {
	htop = &executetop;
	hbot = &executebot;
    }

    /* See if the string is already in the history. */
    thesame = find_history(*hbot, *htop, s, HIGHEST_POSITIVE);

    /* If an identical string was found, delete that item. */
    if (thesame != NULL) {
	filestruct *after = thesame->next;

	/* If the string is at the head of the list, move the head. */
	if (thesame == *htop)
	    *htop = after;

	unlink_node(thesame);
	renumber(after);
    }

    /* If the history is full, delete the oldest item (the one at the
     * head of the list), to make room for a new item at the end. */
    if ((*hbot)->lineno == MAX_SEARCH_HISTORY + 1) {
	filestruct *oldest = *htop;

	*htop = (*htop)->next;
	unlink_node(oldest);
	renumber(*htop);
    }

    /* Store the fresh string in the last item, then create a new item. */
    (*hbot)->data = mallocstrcpy((*hbot)->data, s);
    splice_node(*hbot, make_new_node(*hbot));
    *hbot = (*hbot)->next;
    (*hbot)->data = mallocstrcpy(NULL, "");

    /* Indicate that the history needs to be saved on exit. */
    history_changed = TRUE;

    /* Set the current position in the list to the bottom. */
    *h = *hbot;
}

/* Move h to the string in the history list just before it, and return
 * that string.  If there isn't one, don't move h and return NULL. */
char *get_history_older(filestruct **h)
{
    if ((*h)->prev == NULL)
	return NULL;

    *h = (*h)->prev;

    return (*h)->data;
}

/* Move h to the string in the history list just after it, and return
 * that string.  If there isn't one, don't move h and return NULL. */
char *get_history_newer(filestruct **h)
{
    if ((*h)->next == NULL)
	return NULL;

    *h = (*h)->next;

    return (*h)->data;
}

/* More placeholders. */
void get_history_newer_void(void)
{
    ;
}
void get_history_older_void(void)
{
    ;
}

#ifdef ENABLE_TABCOMP
/* Move h to the next string that's a tab completion of the string s,
 * looking at only the first len characters of s, and return that
 * string.  If there isn't one, or if len is 0, don't move h and return
 * s. */
char *get_history_completion(filestruct **h, char *s, size_t len)
{
    if (len > 0) {
	filestruct *htop = NULL, *hbot = NULL, *p;

	if (*h == search_history) {
	    htop = searchtop;
	    hbot = searchbot;
	} else if (*h == replace_history) {
	    htop = replacetop;
	    hbot = replacebot;
	} else if (*h == execute_history) {
	    htop = executetop;
	    hbot = executebot;
	}

	/* Search the history list from the current position to the top
	 * for a match of len characters.  Skip over an exact match. */
	p = find_history((*h)->prev, htop, s, len);

	while (p != NULL && strcmp(p->data, s) == 0)
	    p = find_history(p->prev, htop, s, len);

	if (p != NULL) {
	    *h = p;
	    return mallocstrcpy(s, (*h)->data);
	}

	/* Search the history list from the bottom to the current position
	 * for a match of len characters.  Skip over an exact match. */
	p = find_history(hbot, *h, s, len);

	while (p != NULL && strcmp(p->data, s) == 0)
	    p = find_history(p->prev, *h, s, len);

	if (p != NULL) {
	    *h = p;
	    return mallocstrcpy(s, (*h)->data);
	}
    }

    /* If we're here, we didn't find a match, we didn't find an inexact
     * match, or len is 0.  Return s. */
    return (char *)s;
}
#endif /* ENSABLE_TABCOMP */

/* Return the constructed dirfile path, or NULL if we can't find the home
 * directory.  The string is dynamically allocated, and should be freed. */
char *construct_filename(const char *str)
{
    char *newstr = NULL;

    if (homedir != NULL) {
	size_t homelen = strlen(homedir);

	newstr = charalloc(homelen + strlen(str) + 1);
	strcpy(newstr, homedir);
	strcpy(newstr + homelen, str);
    }

    return newstr;
}

char *histfilename(void)
{
    return construct_filename("/.nano/search_history");
}

/* Construct the legacy history filename. */
/* (To be removed in 2018.) */
char *legacyhistfilename(void)
{
    return construct_filename("/.nano_history");
}

char *poshistfilename(void)
{
    return construct_filename("/.nano/filepos_history");
}

void history_error(const char *msg, ...)
{
    va_list ap;

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

    fprintf(stderr, _("\nPress Enter to continue\n"));
    while (getchar() != '\n')
	;
}

/* Now that we have more than one history file, let's just rely on a
 * .nano dir for this stuff.  Return 1 if the dir exists or was
 * successfully created, and return 0 otherwise. */
int check_dotnano(void)
{
    int ret = 1;
    struct stat dirstat;
    char *nanodir = construct_filename("/.nano");

    if (stat(nanodir, &dirstat) == -1) {
	if (mkdir(nanodir, S_IRWXU | S_IRWXG | S_IRWXO) == -1) {
	    history_error(N_("Unable to create directory %s: %s\n"
				"It is required for saving/loading "
				"search history or cursor positions.\n"),
				nanodir, strerror(errno));
	    ret = 0;
	}
    } else if (!S_ISDIR(dirstat.st_mode)) {
	history_error(N_("Path %s is not a directory and needs to be.\n"
				"Nano will be unable to load or save "
				"search history or cursor positions.\n"),
				nanodir);
	ret = 0;
    }

    free(nanodir);
    return ret;
}

/* Load the search and replace histories from ~/.nano/search_history. */
void load_history(void)
{
    char *searchhist = histfilename();
    char *legacyhist = legacyhistfilename();
    struct stat hstat;
    FILE *hist;

    /* If no home directory was found, we can't do anything. */
    if (searchhist == NULL || legacyhist == NULL)
	return;

    /* If there is an old history file, migrate it. */
    /* (To be removed in 2018.) */
    if (stat(legacyhist, &hstat) != -1 && stat(searchhist, &hstat) == -1) {
	if (rename(legacyhist, searchhist) == -1)
	    history_error(N_("Detected a legacy nano history file (%s) which I tried to move\n"
			     "to the preferred location (%s) but encountered an error: %s"),
				legacyhist, searchhist, strerror(errno));
	else
	    history_error(N_("Detected a legacy nano history file (%s) which I moved\n"
			     "to the preferred location (%s)\n(see the nano FAQ about this change)"),
				legacyhist, searchhist);
    }

    hist = fopen(searchhist, "rb");

    if (hist == NULL) {
	if (errno != ENOENT) {
	    /* When reading failed, don't save history when we quit. */
	    UNSET(HISTORYLOG);
	    history_error(N_("Error reading %s: %s"), searchhist,
			strerror(errno));
	}
    } else {
	/* Load the two history lists -- first the search history, then
	 * the replace history -- from the oldest entry to the newest.
	 * The two lists are separated by an empty line. */
	filestruct **history = &search_history;
	char *line = NULL;
	size_t buf_len = 0;
	ssize_t read;

	while ((read = getline(&line, &buf_len, hist)) > 0) {
	    line[--read] = '\0';
	    if (read > 0) {
		/* Encode any embedded NUL as 0x0A. */
		unsunder(line, read);
		update_history(history, line);
	    } else if (history == &search_history)
		history = &replace_history;
	   else
		history = &execute_history;

	}

	fclose(hist);
	free(line);
    }

    /* After reading them in, set the status of the lists to "unchanged". */
    history_changed = FALSE;

    free(searchhist);
    free(legacyhist);
}

/* Write the lines of a history list, starting at head, from oldest to newest,
 * to the given file.  Return TRUE if writing succeeded, and FALSE otherwise. */
bool write_list(const filestruct *head, FILE *histfile)
{
    const filestruct *item;

    for (item = head; item != NULL; item = item->next) {
	size_t length = strlen(item->data);

	/* Decode 0x0A bytes as embedded NULs. */
	sunder(item->data);

	if (fwrite(item->data, sizeof(char), length, histfile) < length)
	    return FALSE;
	if (putc('\n', histfile) == EOF)
	    return FALSE;
    }

    return TRUE;
}

/* Save the search and replace histories to ~/.nano/search_history. */
void save_history(void)
{
    char *searchhist;
    FILE *hist;

    /* If the histories are unchanged, don't bother saving them. */
    if (!history_changed)
	return;

    searchhist = histfilename();

    if (searchhist == NULL)
	return;

    hist = fopen(searchhist, "wb");

    if (hist == NULL)
	fprintf(stderr, _("Error writing %s: %s\n"), searchhist,
			strerror(errno));
    else {
	/* Don't allow others to read or write the history file. */
	chmod(searchhist, S_IRUSR | S_IWUSR);

	if (!write_list(searchtop, hist) || !write_list(replacetop, hist) ||
				!write_list(executetop, hist))
	    fprintf(stderr, _("Error writing %s: %s\n"), searchhist,
			strerror(errno));

	fclose(hist);
    }

    free(searchhist);
}

/* Load the recorded file positions from ~/.nano/filepos_history. */
void load_poshistory(void)
{
    char *poshist = poshistfilename();
    FILE *hist;

    /* If the home directory is missing, do_rcfile() will have reported it. */
    if (poshist == NULL)
	return;

    hist = fopen(poshist, "rb");

    if (hist == NULL) {
	if (errno != ENOENT) {
	    /* When reading failed, don't save history when we quit. */
	    UNSET(POS_HISTORY);
	    history_error(N_("Error reading %s: %s"), poshist, strerror(errno));
	}
    } else {
	char *line = NULL, *lineptr, *xptr;
	size_t buf_len = 0;
	ssize_t read, count = 0;
	poshiststruct *record_ptr = NULL, *newrecord;

	/* Read and parse each line, and store the extracted data. */
	while ((read = getline(&line, &buf_len, hist)) > 5) {
	    /* Decode nulls as embedded newlines. */
	    unsunder(line, read);

	    /* Find where the x index and line number are in the line. */
	    xptr = revstrstr(line, " ", line + read - 3);
	    if (xptr == NULL)
		continue;
	    lineptr = revstrstr(line, " ", xptr - 2);
	    if (lineptr == NULL)
		continue;

	    /* Now separate the three elements of the line. */
	    *(xptr++) = '\0';
	    *(lineptr++) = '\0';

	    /* Create a new position record. */
	    newrecord = (poshiststruct *)nmalloc(sizeof(poshiststruct));
	    newrecord->filename = mallocstrcpy(NULL, line);
	    newrecord->lineno = atoi(lineptr);
	    newrecord->xno = atoi(xptr);
	    newrecord->next = NULL;

	    /* Add the record to the list. */
	    if (position_history == NULL)
		position_history = newrecord;
	    else
		record_ptr->next = newrecord;

	    record_ptr = newrecord;

	    /* Impose a limit, so the file will not grow indefinitely. */
	    if (++count > 200) {
		poshiststruct *drop_record = position_history;

		position_history = position_history->next;

		free(drop_record->filename);
		free(drop_record);
	    }
	}
	fclose(hist);
	free(line);
    }
    free(poshist);
}

/* Save the recorded last file positions to ~/.nano/filepos_history. */
void save_poshistory(void)
{
    char *poshist = poshistfilename();
    poshiststruct *posptr;
    FILE *hist;

    if (poshist == NULL)
	return;

    hist = fopen(poshist, "wb");

    if (hist == NULL)
	fprintf(stderr, _("Error writing %s: %s\n"), poshist, strerror(errno));
    else {
	/* Don't allow others to read or write the history file. */
	chmod(poshist, S_IRUSR | S_IWUSR);

	for (posptr = position_history; posptr != NULL; posptr = posptr->next) {
	    char *path_and_place;
	    size_t length;

	    /* Assume 20 decimal positions each for line and column number,
	     * plus two spaces, plus the line feed, plus the null byte. */
	    path_and_place = charalloc(strlen(posptr->filename) + 44);
	    sprintf(path_and_place, "%s %ld %ld\n", posptr->filename,
			(long)posptr->lineno, (long)posptr->xno);
	    length = strlen(path_and_place);

	    /* Encode newlines in filenames as nulls. */
	    sunder(path_and_place);
	    /* Restore the terminating newline. */
	    path_and_place[length - 1] = '\n';

	    if (fwrite(path_and_place, sizeof(char), length, hist) < length)
		fprintf(stderr, _("Error writing %s: %s\n"),
					poshist, strerror(errno));
	    free(path_and_place);
	}
	fclose(hist);
    }
    free(poshist);
}

/* Update the recorded last file positions, given a filename, a line
 * and a column.  If no entry is found, add a new one at the end. */
void update_poshistory(char *filename, ssize_t lineno, ssize_t xpos)
{
    poshiststruct *posptr, *theone, *posprev = NULL;
    char *fullpath = get_full_path(filename);

    if (fullpath == NULL || fullpath[strlen(fullpath) - 1] == '/' || inhelp) {
	free(fullpath);
	return;
    }

    /* Look for a matching filename in the list. */
    for (posptr = position_history; posptr != NULL; posptr = posptr->next) {
	if (!strcmp(posptr->filename, fullpath))
	    break;
	posprev = posptr;
    }

    /* Don't record files that have the default cursor position. */
    if (lineno == 1 && xpos == 1) {
	if (posptr != NULL) {
	    if (posprev == NULL)
		position_history = posptr->next;
	    else
		posprev->next = posptr->next;
	    free(posptr->filename);
	    free(posptr);
	}
	free(fullpath);
	return;
    }

    theone = posptr;

    /* If we didn't find it, make a new node; otherwise, if we're
     * not at the end, move the matching one to the end. */
    if (theone == NULL) {
	theone = (poshiststruct *)nmalloc(sizeof(poshiststruct));
	theone->filename = mallocstrcpy(NULL, fullpath);
	if (position_history == NULL)
	    position_history = theone;
	else
	    posprev->next = theone;
    } else if (posptr->next != NULL) {
	if (posprev == NULL)
	    position_history = posptr->next;
	else
	    posprev->next = posptr->next;
	while (posptr->next != NULL)
	    posptr = posptr->next;
	posptr->next = theone;
    }

    /* Store the last cursor position. */
    theone->lineno = lineno;
    theone->xno = xpos;
    theone->next = NULL;

    free(fullpath);
}

/* Check whether the given file matches an existing entry in the recorded
 * last file positions.  If not, return FALSE.  If yes, return TRUE and
 * set line and column to the retrieved values. */
bool has_old_position(const char *file, ssize_t *line, ssize_t *column)
{
    poshiststruct *posptr = position_history;
    char *fullpath = get_full_path(file);

    if (fullpath == NULL)
	return FALSE;

    while (posptr != NULL && strcmp(posptr->filename, fullpath) != 0)
	posptr = posptr->next;

    free(fullpath);

    if (posptr == NULL)
	return FALSE;

    *line = posptr->lineno;
    *column = posptr->xno;
    return TRUE;
}
#endif /* !DISABLE_HISTORIES */