search.c 37.8 KB
Newer Older
Chris Allegretta's avatar
Chris Allegretta committed
1
2
3
/**************************************************************************
 *   search.c                                                             *
 *                                                                        *
4
 *   Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,  *
5
 *   2008, 2009, 2010, 2011, 2013, 2014 Free Software Foundation, Inc.    *
6
7
 *   Copyright (C) 2015, 2016 Benno Schulenberg                           *
 *                                                                        *
Chris Allegretta's avatar
Chris Allegretta committed
8
9
 *   This program is free software; you can redistribute it and/or modify *
 *   it under the terms of the GNU General Public License as published by *
10
 *   the Free Software Foundation; either version 3, or (at your option)  *
Chris Allegretta's avatar
Chris Allegretta committed
11
12
 *   any later version.                                                   *
 *                                                                        *
13
14
15
16
 *   This program 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.                             *
Chris Allegretta's avatar
Chris Allegretta committed
17
18
19
 *                                                                        *
 *   You should have received a copy of the GNU General Public License    *
 *   along with this program; if not, write to the Free Software          *
20
21
 *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA            *
 *   02110-1301, USA.                                                     *
Chris Allegretta's avatar
Chris Allegretta committed
22
23
24
 *                                                                        *
 **************************************************************************/

25
#include "proto.h"
26

Chris Allegretta's avatar
Chris Allegretta committed
27
28
#include <string.h>
#include <stdio.h>
29
#include <unistd.h>
Chris Allegretta's avatar
Chris Allegretta committed
30
#include <ctype.h>
31
#include <errno.h>
32
#include <time.h>
Chris Allegretta's avatar
Chris Allegretta committed
33

34
35
static bool came_full_circle = FALSE;
	/* Have we reached the starting line again while searching? */
36
#ifndef DISABLE_HISTORIES
37
38
39
static bool history_changed = FALSE;
	/* Have any of the history lists changed? */
#endif
40
#ifdef HAVE_REGEX_H
41
42
static bool regexp_compiled = FALSE;
	/* Have we compiled any regular expressions? */
43

44
45
/* Compile the regular expression regexp to see if it's valid.  Return
 * TRUE if it is, or FALSE otherwise. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
46
bool regexp_init(const char *regexp)
47
{
48
49
50
51
    int rc;

    assert(!regexp_compiled);

52
    rc = regcomp(&search_regexp, fixbounds(regexp), NANO_REG_EXTENDED
53
#ifndef NANO_TINY
54
55
56
	| (ISSET(CASE_SENSITIVE) ? 0 : REG_ICASE)
#endif
	);
57
58
59
60
61
62

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

	regerror(rc, &search_regexp, str, len);
63
	statusline(ALERT, _("Bad regex \"%s\": %s"), regexp, str);
64
	free(str);
65
66

	return FALSE;
67
    }
68

69
    regexp_compiled = TRUE;
70
71

    return TRUE;
72
73
}

74
75
/* Decompile the compiled regular expression we used in the last
 * search, if any. */
76
void regexp_cleanup(void)
77
{
78
79
    if (regexp_compiled) {
	regexp_compiled = FALSE;
80
81
	regfree(&search_regexp);
    }
82
}
83
#endif
84

85
86
/* Indicate on the statusbar that the string at str was not found by the
 * last search. */
87
88
void not_found_msg(const char *str)
{
89
90
    char *disp;
    int numchars;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
91

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
92
    assert(str != NULL);
93

94
    disp = display_string(str, 0, (COLS / 2) + 1, FALSE);
95
    numchars = actual_x(disp, mbstrnlen(disp, COLS / 2));
96

97
    statusline(HUSH, _("\"%.*s%s\" not found"), numchars, disp,
98
		(disp[numchars] == '\0') ? "" : "...");
99
100

    free(disp);
101
102
}

103
104
105
106
107
/* Abort the current search or replace.  Clean up by displaying the main
 * shortcut list, updating the screen if the mark was on before, and
 * decompiling the compiled regular expression we used in the last
 * search, if any. */
void search_replace_abort(void)
108
{
109
#ifndef NANO_TINY
110
    if (openfile->mark_set)
111
112
	edit_refresh();
#endif
113
#ifdef HAVE_REGEX_H
114
    regexp_cleanup();
115
116
117
#endif
}

118
/* Set up the system variables for a search or replace.  If use_answer
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
119
120
121
122
123
 * is TRUE, only set backupstring to answer.  Return -2 to run the
 * opposite program (search -> replace, replace -> search), return -1 if
 * the search should be canceled (due to Cancel, a blank search string,
 * Go to Line, or a failed regcomp()), return 0 on success, and return 1
 * on rerun calling program.
Chris Allegretta's avatar
Chris Allegretta committed
124
 *
125
126
127
 * replacing is TRUE if we call from do_replace(), and FALSE if called
 * from do_search(). */
int search_init(bool replacing, bool use_answer)
Chris Allegretta's avatar
Chris Allegretta committed
128
{
129
    int i = 0;
130
    char *buf;
131
    static char *backupstring = NULL;
132
	/* The search string we'll be using. */
133
    functionptrtype func;
134
135
136
137
138
139

    /* If use_answer is TRUE, set backupstring to answer and get out. */
    if (use_answer) {
	backupstring = mallocstrcpy(backupstring, answer);
	return 0;
    }
140
141
142
143

    /* We display the search prompt below.  If the user types a partial
     * search string and then Replace or a toggle, we will return to
     * do_search() or do_replace() and be called again.  In that case,
144
     * we should put the same search string back up. */
145

146
    if (*last_search != '\0') {
147
	char *disp = display_string(last_search, 0, COLS / 3, FALSE);
148

149
	buf = charalloc(strlen(disp) + 7);
150
	/* We use (COLS / 3) here because we need to see more on the line. */
151
	sprintf(buf, " [%s%s]", disp,
152
		(strlenpt(last_search) > COLS / 3) ? "..." : "");
153
	free(disp);
154
155
    } else
	buf = mallocstrcpy(NULL, "");
Chris Allegretta's avatar
Chris Allegretta committed
156

157
    /* This is now one simple call.  It just does a lot. */
158
159
    i = do_prompt(FALSE,
#ifndef DISABLE_TABCOMP
160
		TRUE,
161
#endif
162
		replacing ? MREPLACE : MWHEREIS, backupstring,
163
#ifndef DISABLE_HISTORIES
164
		&search_history,
165
#endif
166
167
		/* TRANSLATORS: This is the main search prompt. */
		edit_refresh, "%s%s%s%s%s%s", _("Search"),
168
#ifndef NANO_TINY
169
170
		/* TRANSLATORS: The next three modify the search prompt. */
		ISSET(CASE_SENSITIVE) ? _(" [Case Sensitive]") :
171
#endif
172
		"",
173
#ifdef HAVE_REGEX_H
174
		ISSET(USE_REGEXP) ? _(" [Regexp]") :
175
#endif
176
		"",
177
#ifndef NANO_TINY
178
		ISSET(BACKWARDS_SEARCH) ? _(" [Backwards]") :
179
#endif
180
		"", replacing ?
181
#ifndef NANO_TINY
182
183
		/* TRANSLATORS: The next two modify the search prompt. */
		openfile->mark_set ? _(" (to replace) in selection") :
184
#endif
185
		_(" (to replace)") : "", buf);
Chris Allegretta's avatar
Chris Allegretta committed
186

187
    /* Release buf now that we don't need it anymore. */
Chris Allegretta's avatar
Chris Allegretta committed
188
189
    free(buf);

190
191
192
    free(backupstring);
    backupstring = NULL;

193
194
195
    /* If the search was cancelled, or we have a blank answer and
     * nothing was searched for yet during this session, get out. */
    if (i == -1 || (i == -2 && *last_search == '\0')) {
196
	statusbar(_("Cancelled"));
Chris Allegretta's avatar
Chris Allegretta committed
197
	return -1;
198
    }
199

200
201
202
203
204
    /* If Enter was pressed, see what we got. */
    if (i == 0 || i == -2) {
	/* If an answer was given, remember it. */
	if (*answer != '\0') {
	    last_search = mallocstrcpy(last_search, answer);
205
#ifndef DISABLE_HISTORIES
206
	    update_history(&search_history, answer);
207
#endif
208
209
210
211
212
	}
#ifdef HAVE_REGEX_H
	if (ISSET(USE_REGEXP) && !regexp_init(last_search))
	    return -1;
	else
213
#endif
214
215
216
217
218
	    return 0;	/* We have a valid string or regex. */
    }

    func = func_from_key(&i);

219
#ifndef NANO_TINY
220
221
222
223
224
225
226
227
    if (func == case_sens_void) {
	TOGGLE(CASE_SENSITIVE);
	backupstring = mallocstrcpy(backupstring, answer);
	return 1;
    } else if (func == backwards_void) {
	TOGGLE(BACKWARDS_SEARCH);
	backupstring = mallocstrcpy(backupstring, answer);
	return 1;
228
    } else
229
#endif
230
#ifdef HAVE_REGEX_H
231
    if (func == regexp_void) {
232
233
234
	TOGGLE(USE_REGEXP);
	backupstring = mallocstrcpy(backupstring, answer);
	return 1;
235
    } else
236
#endif
237
    if (func == do_replace || func == flip_replace_void) {
238
239
240
241
	backupstring = mallocstrcpy(backupstring, answer);
	return -2;	/* Call the opposite search function. */
    } else if (func == do_gotolinecolumn_void) {
	do_gotolinecolumn(openfile->current->lineno,
242
			openfile->placewewant + 1, TRUE, TRUE);
243
	return 3;
Chris Allegretta's avatar
Chris Allegretta committed
244
    }
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
245

246
    return -1;
Chris Allegretta's avatar
Chris Allegretta committed
247
248
}

249
/* Look for needle, starting at (current, current_x).  begin is the line
250
251
252
253
 * where we first started searching, at column begin_x.  Return 1 when we
 * found something, 0 when nothing, and -2 on cancel.  When match_len is
 * not NULL, set it to the length of the found string, if any. */
int findnextstr(
254
#ifndef DISABLE_SPELLER
255
	bool whole_word_only,
256
#endif
257
	const filestruct *begin, size_t begin_x,
258
	const char *needle, size_t *match_len)
Chris Allegretta's avatar
Chris Allegretta committed
259
{
260
    size_t found_len;
261
	/* The length of the match we find. */
262
263
    int feedback = 0;
	/* When bigger than zero, show and wipe the "Searching..." message. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
264
265
    filestruct *fileptr = openfile->current;
    const char *rev_start = fileptr->data, *found = NULL;
266
267
    size_t found_x;
	/* The x coordinate of a found occurrence. */
268
    time_t lastkbcheck = time(NULL);
269
270
271
272
273
274

    /* rev_start might end up 1 character before the start or after the
     * end of the line.  This won't be a problem because strstrwrapper()
     * will return immediately and say that no match was found, and
     * rev_start will be properly set when the search continues on the
     * previous or next line. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
275
    rev_start +=
276
#ifndef NANO_TINY
277
	ISSET(BACKWARDS_SEARCH) ?
278
	((openfile->current_x == 0) ? -1 : move_mbleft(fileptr->data, openfile->current_x)) :
279
#endif
280
	move_mbright(fileptr->data, openfile->current_x);
Chris Allegretta's avatar
Chris Allegretta committed
281

282
    enable_nodelay();
283

284
285
286
    if (begin == NULL)
	came_full_circle = FALSE;

287
    /* Start searching through the lines, looking for the needle. */
288
    while (TRUE) {
289
290
	/* Glance at the keyboard once every second. */
	if (time(NULL) - lastkbcheck > 0) {
291
292
	    int input = parse_kbinput(edit);

293
	    lastkbcheck = time(NULL);
294

295
296
297
298
299
300
301
302
	    /* Consume all waiting keystrokes until a Cancel. */
	    while (input) {
		if (func_from_key(&input) == do_cancel) {
		    statusbar(_("Cancelled"));
		    disable_nodelay();
		    return -2;
		}
		input = parse_kbinput(NULL);
303
	    }
304
305

	    if (++feedback > 0)
306
307
		/* TRANSLATORS: This is shown when searching takes
		 * more than half a second. */
308
		statusbar(_("Searching..."));
309
310
	}

311
	/* Search for the needle in the current line. */
312
	found = strstrwrapper(fileptr->data, needle, rev_start);
Chris Allegretta's avatar
Chris Allegretta committed
313

314
	if (found != NULL) {
315
	    /* Remember the length of the potential match. */
316
	    found_len =
317
#ifdef HAVE_REGEX_H
318
319
		ISSET(USE_REGEXP) ?
		regmatches[0].rm_eo - regmatches[0].rm_so :
320
#endif
321
		strlen(needle);
322

323
#ifndef DISABLE_SPELLER
324
325
	    /* When we're spell checking, a match is only a true match when
	     * it is a separate word. */
326
	    if (whole_word_only) {
327
328
329
		if (is_separate_word(found - fileptr->data, found_len,
					fileptr->data))
		    break;
330
331
332
333
334
		else {
		    /* Maybe there is a whole word in the rest of the line. */
		    rev_start = found + 1;
		    continue;
		}
335
	    } else
336
#endif
337
		break;
Chris Allegretta's avatar
Chris Allegretta committed
338
	}
339

340
	/* If we're back at the beginning, then there is no needle. */
341
	if (came_full_circle) {
342
	    not_found_msg(needle);
343
	    disable_nodelay();
344
	    return 0;
345
	}
346

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
347
	/* Move to the previous or next line in the file. */
348
#ifndef NANO_TINY
349
	if (ISSET(BACKWARDS_SEARCH))
350
	    fileptr = fileptr->prev;
351
	else
352
353
#endif
	    fileptr = fileptr->next;
354

355
	/* If we've reached the start or end of the buffer, wrap around. */
356
	if (fileptr == NULL) {
357
358
359
360
361
362
363
#ifndef DISABLE_SPELLER
	    /* When we're spell-checking, end-of-buffer means we're done. */
	    if (whole_word_only) {
		disable_nodelay();
		return 0;
	    }
#endif
364
#ifndef NANO_TINY
365
	    if (ISSET(BACKWARDS_SEARCH))
366
		fileptr = openfile->filebot;
367
	    else
368
#endif
369
		fileptr = openfile->fileage;
370

371
	    statusbar(_("Search Wrapped"));
372
373
	    /* Delay the "Searching..." message for at least two seconds. */
	    feedback = -2;
374
	}
Chris Allegretta's avatar
Chris Allegretta committed
375

376
	/* If we've reached the original starting line, take note. */
377
	if (fileptr == begin)
378
	    came_full_circle = TRUE;
379

380
	/* Set the starting x to the start or end of the line. */
381
	rev_start = fileptr->data;
382
#ifndef NANO_TINY
383
	if (ISSET(BACKWARDS_SEARCH))
384
385
386
	    rev_start += strlen(fileptr->data);
#endif
    }
387

388
389
390
    found_x = found - fileptr->data;

    /* Ensure that the found occurrence is not beyond the starting x. */
391
    if (came_full_circle &&
392
393
394
395
396
397
398
399
400
401
402
403
#ifndef NANO_TINY
		((!ISSET(BACKWARDS_SEARCH) && found_x > begin_x) ||
		(ISSET(BACKWARDS_SEARCH) && found_x < begin_x))
#else
		found_x > begin_x
#endif
		) {
	not_found_msg(needle);
	disable_nodelay();
	return 0;
    }

404
    disable_nodelay();
405

406
    /* Set the current position to point at what we found. */
407
    openfile->current = fileptr;
408
    openfile->current_x = found_x;
409
    openfile->current_y = fileptr->lineno - openfile->edittop->lineno;
410

411
412
413
    /* When requested, pass back the length of the match. */
    if (match_len != NULL)
	*match_len = found_len;
414

415
416
417
    if (feedback > 0)
	blank_statusbar();

418
    return 1;
Chris Allegretta's avatar
Chris Allegretta committed
419
420
}

421
/* Ask what to search for and then go looking for it. */
422
void do_search(void)
Chris Allegretta's avatar
Chris Allegretta committed
423
{
424
    int i = search_init(FALSE, FALSE);
425

426
    if (i == -1)	/* Cancelled, or some other exit reason. */
427
	search_replace_abort();
428
    else if (i == -2)	/* Do a replace instead. */
Chris Allegretta's avatar
Chris Allegretta committed
429
	do_replace();
430
#if !defined(NANO_TINY) || defined(HAVE_REGEX_H)
431
    else if (i == 1)	/* Toggled something. */
Chris Allegretta's avatar
Chris Allegretta committed
432
	do_search();
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
433
#endif
434

435
436
    if (i == 0)
	go_looking();
Chris Allegretta's avatar
Chris Allegretta committed
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
#ifndef NANO_TINY
/* Search in the backward direction for the next occurrence. */
void do_findprevious(void)
{
    if ISSET(BACKWARDS_SEARCH)
	do_research();
    else {
	SET(BACKWARDS_SEARCH);
	do_research();
	UNSET(BACKWARDS_SEARCH);
    }
}

/* Search in the forward direction for the next occurrence. */
void do_findnext(void)
{
    if ISSET(BACKWARDS_SEARCH) {
	UNSET(BACKWARDS_SEARCH);
	do_research();
	SET(BACKWARDS_SEARCH);
    } else
	do_research();
}
462
#endif /* !NANO_TINY */
463

464
#if !defined(NANO_TINY) || !defined(DISABLE_BROWSER)
465
/* Search for the last string without prompting. */
466
void do_research(void)
467
{
468
469
470
#ifndef DISABLE_HISTORIES
    /* If nothing was searched for yet during this run of nano, but
     * there is a search history, take the most recent item. */
471
    if (*last_search == '\0' && searchbot->prev != NULL)
472
473
474
	last_search = mallocstrcpy(last_search, searchbot->prev->data);
#endif

475
    if (*last_search == '\0') {
476
	statusbar(_("No current search pattern"));
477
478
479
	return;
    }

480
#ifdef HAVE_REGEX_H
481
482
    if (ISSET(USE_REGEXP) && !regexp_init(last_search))
	return;
483
484
#endif

485
486
    /* Use the search-menu key bindings, to allow cancelling. */
    currmenu = MWHEREIS;
487

488
489
490
491
492
493
494
495
496
497
    go_looking();
}
#endif /* !NANO_TINY */

/* Search for the global string 'last_search'.  Inform the user when
 * the string occurs only once. */
void go_looking(void)
{
    filestruct *was_current = openfile->current;
    size_t was_current_x = openfile->current_x;
498
    int didfind;
499
500
501
#ifdef DEBUG
    clock_t start = clock();
#endif
502

503
    came_full_circle = FALSE;
504

505
    didfind = findnextstr(
506
507
508
#ifndef DISABLE_SPELLER
		FALSE,
#endif
509
		openfile->current, openfile->current_x, last_search, NULL);
510

511
512
    /* If we found something, and we're back at the exact same spot
     * where we started searching, then this is the only occurrence. */
513
    if (didfind == 1 && openfile->current == was_current &&
514
		openfile->current_x == was_current_x)
515
	statusbar(_("This is the only occurrence"));
516

517
518
519
520
#ifdef DEBUG
    statusline(HUSH, "Took: %.2f", (double)(clock() - start) / CLOCKS_PER_SEC);
#endif

521
    edit_redraw(was_current);
522
    search_replace_abort();
523
524
}

525
#ifdef HAVE_REGEX_H
526
/* Calculate the size of the replacement text, taking possible
527
528
 * subexpressions \1 to \9 into account.  Return the replacement
 * text in the passed string only when create is TRUE. */
529
int replace_regexp(char *string, bool create)
530
{
531
    const char *c = answer;
532
    size_t replacement_size = 0;
533

Chris Allegretta's avatar
Chris Allegretta committed
534
535
    /* Iterate through the replacement text to handle subexpression
     * replacement using \1, \2, \3, etc. */
536
    while (*c != '\0') {
537
	int num = (*(c + 1) - '0');
538

539
	if (*c != '\\' || num < 1 || num > 9 || num > search_regexp.re_nsub) {
540
	    if (create)
541
542
		*string++ = *c;
	    c++;
543
	    replacement_size++;
544
	} else {
545
	    size_t i = regmatches[num].rm_eo - regmatches[num].rm_so;
546

547
548
	    /* Skip over the replacement expression. */
	    c += 2;
549

550
	    /* But add the length of the subexpression to new_size. */
551
	    replacement_size += i;
552

553
	    /* And if create is TRUE, append the result of the
554
	     * subexpression match to the new line. */
555
	    if (create) {
556
557
		strncpy(string, openfile->current->data +
			openfile->current_x + regmatches[num].rm_so, i);
558
		string += i;
559
560
	    }
	}
561
562
    }

563
    if (create)
Chris Allegretta's avatar
Chris Allegretta committed
564
	*string = '\0';
565

566
    return replacement_size;
567
}
568
#endif /* HAVE_REGEX_H */
569

570
/* Return a copy of the current line with one needle replaced. */
571
char *replace_line(const char *needle)
572
{
573
    char *copy;
574
575
    size_t match_len;
    size_t new_line_size = strlen(openfile->current->data) + 1;
576

577
    /* First adjust the size of the new line for the change. */
578
#ifdef HAVE_REGEX_H
579
    if (ISSET(USE_REGEXP)) {
580
581
	match_len = regmatches[0].rm_eo - regmatches[0].rm_so;
	new_line_size += replace_regexp(NULL, FALSE) - match_len;
582
    } else {
583
#endif
584
585
	match_len = strlen(needle);
	new_line_size += strlen(answer) - match_len;
586
#ifdef HAVE_REGEX_H
587
    }
588
#endif
589

590
    /* Create the buffer. */
591
    copy = charalloc(new_line_size);
592

593
    /* Copy the head of the original line. */
594
    strncpy(copy, openfile->current->data, openfile->current_x);
595

596
    /* Add the replacement text. */
597
#ifdef HAVE_REGEX_H
598
    if (ISSET(USE_REGEXP))
599
	replace_regexp(copy + openfile->current_x, TRUE);
600
    else
601
#endif
602
	strcpy(copy + openfile->current_x, answer);
603

604
    assert(openfile->current_x + match_len <= strlen(openfile->current->data));
605

606
    /* Copy the tail of the original line. */
607
    strcat(copy, openfile->current->data + openfile->current_x + match_len);
608
609

    return copy;
Chris Allegretta's avatar
Chris Allegretta committed
610
611
}

612
613
614
/* Step through each occurrence of the search string and prompt the user
 * before replacing it.  We seek for needle, and replace it with answer.
 * The parameters real_current and real_current_x are needed in order to
615
 * allow the cursor position to be updated when a word before the cursor
616
617
 * is replaced by a shorter word.  Return -1 if needle isn't found, -2 if
 * the seeking is aborted, else the number of replacements performed. */
618
619
ssize_t do_replace_loop(
#ifndef DISABLE_SPELLER
620
	bool whole_word_only,
621
#endif
622
623
	const filestruct *real_current, size_t *real_current_x,
	const char *needle)
Chris Allegretta's avatar
Chris Allegretta committed
624
{
625
626
    ssize_t numreplaced = -1;
    size_t match_len;
627
    bool replaceall = FALSE;
628
#ifndef NANO_TINY
629
    bool old_mark_set = openfile->mark_set;
630
    filestruct *top, *bot;
631
632
    size_t top_x, bot_x;
    bool right_side_up = FALSE;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
633
	/* TRUE if (mark_begin, mark_begin_x) is the top of the mark,
634
	 * FALSE if (current, current_x) is. */
Chris Allegretta's avatar
Chris Allegretta committed
635

636
    /* If the mark is on, frame the region, and turn the mark off. */
637
    if (old_mark_set) {
638
	mark_order((const filestruct **)&top, &top_x,
639
			(const filestruct **)&bot, &bot_x, &right_side_up);
640
	openfile->mark_set = FALSE;
641
642
643
644
645
646
647
648
649

	/* Start either at the top or the bottom of the marked region. */
	if (!ISSET(BACKWARDS_SEARCH)) {
	    openfile->current = top;
	    openfile->current_x = (top_x == 0 ? 0 : top_x - 1);
	} else {
	    openfile->current = bot;
	    openfile->current_x = bot_x;
	}
650
    }
651
#endif /* !NANO_TINY */
652

653
    came_full_circle = FALSE;
654

655
656
657
    while (TRUE) {
	int i = 0;
	int result = findnextstr(
658
#ifndef DISABLE_SPELLER
659
			whole_word_only,
660
#endif
661
662
663
664
665
666
667
668
			real_current, *real_current_x, needle, &match_len);

	/* If nothing more was found, or the user aborted, stop looping. */
	if (result < 1) {
	    if (result < 0)
		numreplaced = -2;  /* It's a Cancel instead of Not found. */
	    break;
	}
669

670
671
672
673
674
#ifndef NANO_TINY
	if (old_mark_set) {
	    /* When we've found an occurrence outside of the marked region,
	     * stop the fanfare. */
	    if (openfile->current->lineno > bot->lineno ||
675
676
677
			openfile->current->lineno < top->lineno ||
			(openfile->current == bot && openfile->current_x > bot_x) ||
			(openfile->current == top && openfile->current_x < top_x))
678
679
680
681
		break;
	}
#endif

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
682
	/* Indicate that we found the search string. */
683
684
	if (numreplaced == -1)
	    numreplaced = 0;
685

686
	if (!replaceall) {
687
	    size_t xpt = xplustabs();
688
	    char *exp_word = display_string(openfile->current->data,
689
690
			xpt, strnlenpt(openfile->current->data,
			openfile->current_x + match_len) - xpt, FALSE);
691

692
	    /* Refresh the edit window, scrolling it if necessary. */
693
694
	    edit_refresh();

695
	    /* Don't show cursor, to not distract from highlighted match. */
696
	    curs_set(0);
697

698
	    spotlight(TRUE, exp_word);
699

700
	    /* TRANSLATORS: This is a prompt. */
701
	    i = do_yesno_prompt(TRUE, _("Replace this instance?"));
Chris Allegretta's avatar
Chris Allegretta committed
702

703
	    spotlight(FALSE, exp_word);
704

705
	    free(exp_word);
706

707
	    if (i == -1)  /* The replacing was cancelled. */
708
		break;
709
710
	}

711
	if (i > 0 || replaceall) {	/* Yes, replace it!!!! */
712
	    char *copy;
713
	    size_t length_change;
714

715
#ifndef NANO_TINY
716
	    add_undo(REPLACE);
717
#endif
718
	    if (i == 2)
719
		replaceall = TRUE;
Chris Allegretta's avatar
Chris Allegretta committed
720

721
	    copy = replace_line(needle);
Chris Allegretta's avatar
Chris Allegretta committed
722

723
	    length_change = strlen(copy) - strlen(openfile->current->data);
Chris Allegretta's avatar
Chris Allegretta committed
724

725
#ifndef NANO_TINY
726
727
728
	    /* If the mark was on and it was located after the cursor,
	     * then adjust its x position for any text length changes. */
	    if (old_mark_set && !right_side_up) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
729
730
		if (openfile->current == openfile->mark_begin &&
			openfile->mark_begin_x > openfile->current_x) {
731
		    if (openfile->mark_begin_x < openfile->current_x + match_len)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
732
			openfile->mark_begin_x = openfile->current_x;
733
		    else
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
734
			openfile->mark_begin_x += length_change;
735
		    bot_x = openfile->mark_begin_x;
736
		}
737
	    }
Chris Allegretta's avatar
Chris Allegretta committed
738

739
740
	    /* If the mark was not on or it was before the cursor, then
	     * adjust the cursor's x position for any text length changes. */
741
	    if (!old_mark_set || right_side_up) {
742
#endif
743
744
		if (openfile->current == real_current &&
			openfile->current_x <= *real_current_x) {
745
746
		    if (*real_current_x < openfile->current_x + match_len)
			*real_current_x = openfile->current_x + match_len;
747
		    *real_current_x += length_change;
748
#ifndef NANO_TINY
749
		    bot_x = *real_current_x;
750
		}
751
#endif
752
	    }
753

754
#ifdef HAVE_REGEX_H
755
756
	    /* Don't find the same zero-length or BOL match again. */
	    if (match_len == 0 || (*needle == '^' && ISSET(USE_REGEXP)))
757
758
		match_len++;
#endif
759
	    /* Set the cursor at the last character of the replacement
760
761
	     * text, so that searching will continue /after/ it.  Note
	     * that current_x might be set to (size_t)-1 here. */
762
#ifndef NANO_TINY
763
	    if (!ISSET(BACKWARDS_SEARCH))
764
#endif
765
		openfile->current_x += match_len + length_change - 1;
766

767
768
	    /* Update the file size, and put the changed line into place. */
	    openfile->totsize += mbstrlen(copy) - mbstrlen(openfile->current->data);
769
770
	    free(openfile->current->data);
	    openfile->current->data = copy;
771

772
#ifndef DISABLE_COLOR
773
774
775
776
	    /* Reset the precalculated multiline-regex hints only when
	     * the first replacement has been made. */
	    if (numreplaced == 0)
		reset_multis(openfile->current, TRUE);
777
#endif
778

779
	    if (!replaceall) {
780
#ifndef DISABLE_COLOR
781
782
		/* If color syntaxes are available and turned on, we
		 * need to call edit_refresh(). */
783
		if (openfile->colorstrings != NULL && !ISSET(NO_COLOR_SYNTAX))
784
785
786
		    edit_refresh();
		else
#endif
787
		    update_line(openfile->current, openfile->current_x);
788
789
	    }

Chris Allegretta's avatar
Chris Allegretta committed
790
791
	    set_modified();
	    numreplaced++;
792
	}
Chris Allegretta's avatar
Chris Allegretta committed
793
794
    }

795
796
797
    if (numreplaced == -1)
	not_found_msg(needle);

798
#ifndef NANO_TINY
799
    if (old_mark_set)
800
	openfile->mark_set = TRUE;
801
802
#endif

803
804
805
    /* If the NO_NEWLINES flag isn't set, and text has been added to the
     * magicline, make a new magicline. */
    if (!ISSET(NO_NEWLINES) && openfile->filebot->data[0] != '\0')
806
807
	new_magicline();

Chris Allegretta's avatar
Chris Allegretta committed
808
809
810
    return numreplaced;
}

Chris Allegretta's avatar
Chris Allegretta committed
811
/* Replace a string. */
812
void do_replace(void)
Chris Allegretta's avatar
Chris Allegretta committed
813
{
814
    filestruct *edittop_save, *begin;
815
    size_t begin_x;
816
    ssize_t numreplaced;
817
    int i;
Chris Allegretta's avatar
Chris Allegretta committed
818

Chris Allegretta's avatar
Chris Allegretta committed
819
820
    if (ISSET(VIEW_MODE)) {
	print_view_warning();
821
	search_replace_abort();
822
	return;
Chris Allegretta's avatar
Chris Allegretta committed
823
824
    }

825
    i = search_init(TRUE, FALSE);
826
827

    if (i == -1)	/* Cancelled, or some other exit reason. */
828
	search_replace_abort();
829
    else if (i == -2)	/* Do a search instead. */
Chris Allegretta's avatar
Chris Allegretta committed
830
	do_search();
831
    else if (i == 1)	/* Toggled something. */
832
833
834
	do_replace();

    if (i != 0)
835
	return;
Chris Allegretta's avatar
Chris Allegretta committed
836

837
838
    i = do_prompt(FALSE,
#ifndef DISABLE_TABCOMP
839
		TRUE,
840
#endif
841
		MREPLACEWITH, NULL,
842
#ifndef DISABLE_HISTORIES
843
		&replace_history,
844
#endif
845
846
		/* TRANSLATORS: This is a prompt. */
		edit_refresh, _("Replace with"));
847

848
#ifndef DISABLE_HISTORIES
849
    /* If the replace string is not "", add it to the replace history list. */
850
    if (i == 0)
851
	update_history(&replace_history, answer);
852
853
#endif

854
855
856
    /* When cancelled, or when a function was run, get out. */
    if (i == -1 || i > 0) {
	if (i == -1)
857
	    statusbar(_("Cancelled"));
858
	search_replace_abort();
859
	return;
860
861
862
    }

    /* Save where we are. */
863
864
    edittop_save = openfile->edittop;
    begin = openfile->current;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
865
    begin_x = openfile->current_x;
Chris Allegretta's avatar
Chris Allegretta committed
866

867
868
    numreplaced = do_replace_loop(
#ifndef DISABLE_SPELLER
869
		FALSE,
870
#endif
871
		begin, &begin_x, last_search);
Chris Allegretta's avatar
Chris Allegretta committed
872

873
    /* Restore where we were. */
874
875
    openfile->edittop = edittop_save;
    openfile->current = begin;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
876
    openfile->current_x = begin_x;
877

878
    edit_refresh();
Chris Allegretta's avatar
Chris Allegretta committed
879
880

    if (numreplaced >= 0)
881
	statusline(HUSH, P_("Replaced %lu occurrence",
882
883
		"Replaced %lu occurrences", (unsigned long)numreplaced),
		(unsigned long)numreplaced);
Chris Allegretta's avatar
Chris Allegretta committed
884

885
    search_replace_abort();
Chris Allegretta's avatar
Chris Allegretta committed
886
887
}

888
889
890
/* Go to the specified line and x position. */
void goto_line_posx(ssize_t line, size_t pos_x)
{
891
892
    for (openfile->current = openfile->fileage; line > 1 &&
		openfile->current != openfile->filebot; line--)
893
894
895
896
897
	openfile->current = openfile->current->next;

    openfile->current_x = pos_x;
    openfile->placewewant = xplustabs();

898
    refresh_needed = TRUE;
899
900
}

901
/* Go to the specified line and column, or ask for them if interactive
902
 * is TRUE.  In the latter case also update the screen afterwards.
903
 * Note that both the line and column number should be one-based. */
904
void do_gotolinecolumn(ssize_t line, ssize_t column, bool use_answer,
905
	bool interactive)
Chris Allegretta's avatar
Chris Allegretta committed
906
{
907
    if (interactive) {
908
	functionptrtype func;
909

910
	/* Ask for the line and column. */
911
912
913
914
	int i = do_prompt(FALSE,
#ifndef DISABLE_TABCOMP
		TRUE,
#endif
915
		MGOTOLINE, use_answer ? answer : NULL,
916
#ifndef DISABLE_HISTORIES
917
		NULL,
Chris Allegretta's avatar
Chris Allegretta committed
918
#endif
919
		/* TRANSLATORS: This is a prompt. */
920
		edit_refresh, _("Enter line number, column number"));
921

922
	/* If the user cancelled or gave a blank answer, get out. */
923
	if (i < 0) {
924
	    statusbar(_("Cancelled"));
925
926
927
	    return;
	}

928
	func = func_from_key(&i);
929

930
	if (func == gototext_void) {
931
	    /* Retain what the user typed so far and switch to searching. */
932
	    search_init(TRUE, TRUE);
933
	    do_search();
Chris Allegretta's avatar
Chris Allegretta committed
934
	}
935

936
937
938
939
	/* If a function was executed, we're done here. */
	if (i > 0)
	    return;

940
941
	/* Try to extract one or two numbers from the user's response. */
	if (!parse_line_column(answer, &line, &column)) {
942
	    statusbar(_("Invalid line or column number"));
943
	    return;
Chris Allegretta's avatar
Chris Allegretta committed
944
	}
945
946
    } else {
	if (line < 1)
947
	    line = openfile->current->lineno;
948

949
	if (column < 1)
950
	    column = openfile->placewewant + 1;
Chris Allegretta's avatar
Chris Allegretta committed
951
952
    }

953
954
955
956
957
958
959
    /* Take a negative line number to mean: from the end of the file. */
    if (line < 0)
	line = openfile->filebot->lineno + line + 1;
    if (line < 1)
	line = 1;

    /* Iterate to the requested line. */
960
961
    for (openfile->current = openfile->fileage; line > 1 &&
		openfile->current != openfile->filebot; line--)
962
	openfile->current = openfile->current->next;
Chris Allegretta's avatar
Chris Allegretta committed
963

964
965
966
967
968
969
970
    /* Take a negative column number to mean: from the end of the line. */
    if (column < 0)
	column = strlenpt(openfile->current->data) + column + 2;
    if (column < 1)
	column = 1;

    /* Set the x position that corresponds to the requested column. */
971
972
    openfile->current_x = actual_x(openfile->current->data, column - 1);
    openfile->placewewant = column - 1;
973

974
    /* When the position was manually given, center the target line. */
975
    if (interactive) {
976
	edit_update(CENTERING);
977
	edit_refresh();
978
979
980
981
982
983
984
985
986
987
988
    } else {
	/* If the target line is close to the tail of the file, put the last
	 * line of the file on the bottom line of the screen; otherwise, just
	 * center the target line. */
	if (openfile->filebot->lineno - openfile->current->lineno <
							editwinrows / 2) {
	    openfile->current_y = editwinrows - openfile->filebot->lineno +
					openfile->current->lineno - 1;
	    edit_update(STATIONARY);
	} else
	    edit_update(CENTERING);
989
    }
Chris Allegretta's avatar
Chris Allegretta committed
990
991
}

992
/* Go to the specified line and column, asking for them beforehand. */
993
void do_gotolinecolumn_void(void)
Chris Allegretta's avatar
Chris Allegretta committed
994
{
995
    do_gotolinecolumn(openfile->current->lineno,
996
	openfile->placewewant + 1, FALSE, TRUE);
Chris Allegretta's avatar
Chris Allegretta committed
997
}
998

999
#ifndef NANO_TINY
1000
/* Search for a match to one of the two characters in bracket_set.  If
1001
1002
1003
 * reverse is TRUE, search backwards for the leftmost bracket.
 * Otherwise, search forwards for the rightmost bracket.  Return TRUE if
 * we found a match, and FALSE otherwise. */
1004
1005
1006
1007
1008
bool find_bracket_match(bool reverse, const char *bracket_set)
{
    filestruct *fileptr = openfile->current;
    const char *rev_start = NULL, *found = NULL;

1009
    assert(mbstrlen(bracket_set) == 2);
1010
1011
1012
1013
1014

    /* rev_start might end up 1 character before the start or after the
     * end of the line.  This won't be a problem because we'll skip over
     * it below in that case, and rev_start will be properly set when
     * the search continues on the previous or next line. */
1015
1016
1017
1018
    if (reverse)
	rev_start = fileptr->data + (openfile->current_x - 1);
    else
	rev_start = fileptr->data + (openfile->current_x + 1);
1019
1020
1021
1022
1023

    /* Look for either of the two characters in bracket_set.  rev_start
     * can be 1 character before the start or after the end of the line.
     * In either case, just act as though no match is found. */
    while (TRUE) {
1024
1025
1026
1027
1028
1029
1030
	if ((rev_start > fileptr->data && *(rev_start - 1) == '\0') ||
			rev_start < fileptr->data)
	    found = NULL;
	else if (reverse)
	    found = mbrevstrpbrk(fileptr->data, bracket_set, rev_start);
	else
	    found = mbstrpbrk(rev_start, bracket_set);
1031

1032
	if (found)
1033
1034
	    break;

1035
	if (reverse)
1036
	    fileptr = fileptr->prev;
1037
	else
1038
1039
	    fileptr = fileptr->next;

1040
	/* If we've reached the start or end of the buffer, get out. */
1041
1042
1043
1044
1045
1046
1047
1048
	if (fileptr == NULL)
	    return FALSE;

	rev_start = fileptr->data;
	if (reverse)
	    rev_start += strlen(fileptr->data);
    }

1049
    /* Set the current position to the found matching bracket. */
1050
    openfile->current = fileptr;
1051
    openfile->current_x = found - fileptr->data;
1052
    openfile->current_y = fileptr->lineno - openfile->edittop->lineno;
1053
1054
1055
1056
1057
1058

    return TRUE;
}

/* Search for a match to the bracket at the current cursor position, if
 * there is one. */
1059
void do_find_bracket(void)
1060
{
1061
    filestruct *current_save;
1062
    size_t current_x_save;
1063
    const char *ch;
1064
	/* The location in matchbrackets of the bracket at the current
1065
	 * cursor position. */
1066
1067
1068
    int ch_len;
	/* The length of ch in bytes. */
    const char *wanted_ch;
1069
1070
	/* The location in matchbrackets of the bracket complementing
	 * the bracket at the current cursor position. */
1071
1072
1073
    int wanted_ch_len;
	/* The length of wanted_ch in bytes. */
    char *bracket_set;
1074
	/* The pair of characters in ch and wanted_ch. */
1075
1076
    size_t i;
	/* Generic loop variable. */
1077
    size_t matchhalf;
1078
1079
1080
1081
1082
	/* The number of single-byte characters in one half of
	 * matchbrackets. */
    size_t mbmatchhalf;
	/* The number of multibyte characters in one half of
	 * matchbrackets. */
1083
1084
1085
1086
    size_t count = 1;
	/* The initial bracket count. */
    bool reverse;
	/* The direction we search. */
1087
1088
    char *found_ch;
	/* The character we find. */
1089

1090
    assert(mbstrlen(matchbrackets) % 2 == 0);
1091

1092
    ch = openfile->current->data + openfile->current_x;
1093

1094
    if ((ch = mbstrchr(matchbrackets, ch)) == NULL) {
1095
	statusbar(_("Not a bracket"));
1096
	return;
1097
1098
    }

1099
    /* Save where we are. */
1100
1101
    current_save = openfile->current;
    current_x_save = openfile->current_x;
1102

1103
    /* If we're on an opening bracket, which must be in the first half
1104
     * of matchbrackets, we want to search forwards for a closing
1105
     * bracket.  If we're on a closing bracket, which must be in the
1106
     * second half of matchbrackets, we want to search backwards for an
1107
     * opening bracket. */
1108
1109
1110
1111
    matchhalf = 0;
    mbmatchhalf = mbstrlen(matchbrackets) / 2;

    for (i = 0; i < mbmatchhalf; i++)
1112
	matchhalf += parse_mbchar(matchbrackets + matchhalf, NULL, NULL);
1113

1114
    reverse = ((ch - matchbrackets) >= matchhalf);
1115
1116

    /* If we're on an opening bracket, set wanted_ch to the character
1117
1118
1119
     * that's matchhalf characters after ch.  If we're on a closing
     * bracket, set wanted_ch to the character that's matchhalf
     * characters before ch. */
1120
1121
    wanted_ch = ch;

1122
    while (mbmatchhalf > 0) {
1123
	if (reverse)
1124
	    wanted_ch = matchbrackets + move_mbleft(matchbrackets,
1125
				wanted_ch - matchbrackets);
1126
1127
1128
	else
	    wanted_ch += move_mbright(wanted_ch, 0);

1129
	mbmatchhalf--;
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
    }

    ch_len = parse_mbchar(ch, NULL, NULL);
    wanted_ch_len = parse_mbchar(wanted_ch, NULL, NULL);

    /* Fill bracket_set in with the values of ch and wanted_ch. */
    bracket_set = charalloc((mb_cur_max() * 2) + 1);
    strncpy(bracket_set, ch, ch_len);
    strncpy(bracket_set + ch_len, wanted_ch, wanted_ch_len);
    null_at(&bracket_set, ch_len + wanted_ch_len);

    found_ch = charalloc(mb_cur_max() + 1);
1142

1143
    while (TRUE) {
1144
	if (find_bracket_match(reverse, bracket_set)) {
1145
1146
	    /* If we found an identical bracket, increment count.  If we
	     * found a complementary bracket, decrement it. */
1147
	    parse_mbchar(openfile->current->data + openfile->current_x,
1148
			found_ch, NULL);
1149
	    count += (strncmp(found_ch, ch, ch_len) == 0) ? 1 : -1;
1150
1151
1152
1153

	    /* If count is zero, we've found a matching bracket.  Update
	     * the screen and get out. */
	    if (count == 0) {
1154
		focusing = FALSE;
1155
		edit_redraw(current_save);
1156
		break;
1157
	    }
Chris Allegretta's avatar
Chris Allegretta committed
1158
	} else {
1159
1160
	    /* We didn't find either an opening or closing bracket.
	     * Indicate this, restore where we were, and get out. */
1161
	    statusbar(_("No matching bracket"));
1162
1163
	    openfile->current = current_save;
	    openfile->current_x = current_x_save;
1164
1165
1166
	    break;
	}
    }
1167
1168
1169
1170

    /* Clean up. */
    free(bracket_set);
    free(found_ch);
1171
}
1172
#endif /* !NANO_TINY */
1173

1174
#ifndef DISABLE_HISTORIES
1175
1176
1177
1178
1179
/* Indicate whether any of the history lists have changed. */
bool history_has_changed(void)
{
    return history_changed;
}
1180

1181
/* Initialize the search and replace history lists. */
1182
1183
void history_init(void)
{
1184
1185
1186
1187
1188
1189
1190
1191
1192
    search_history = make_new_node(NULL);
    search_history->data = mallocstrcpy(NULL, "");
    searchage = search_history;
    searchbot = search_history;

    replace_history = make_new_node(NULL);
    replace_history->data = mallocstrcpy(NULL, "");
    replaceage = replace_history;
    replacebot = replace_history;
1193
1194
}

1195
1196
1197
1198
1199
1200
1201
1202
1203
/* 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;
}

1204
1205
1206
/* 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. */
1207
1208
filestruct *find_history(const filestruct *h_start, const filestruct
	*h_end, const char *s, size_t len)
1209
{
1210
    const filestruct *p;
1211

1212
    for (p = h_start; p != h_end->prev && p != NULL; p = p->prev) {
1213
	if (strncmp(s, p->data, len) == 0)
1214
	    return (filestruct *)p;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1215
    }
1216

1217
1218
1219
    return NULL;
}

1220
1221
/* 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. */
1222
void update_history(filestruct **h, const char *s)
1223
{
1224
    filestruct **hage = NULL, **hbot = NULL, *thesame;
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234

    assert(h != NULL && s != NULL);

    if (*h == search_history) {
	hage = &searchage;
	hbot = &searchbot;
    } else if (*h == replace_history) {
	hage = &replaceage;
	hbot = &replacebot;
    }
1235

1236
    assert(hage != NULL && hbot != NULL);
1237

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

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

1245
1246
1247
	/* If the string is at the head of the list, move the head. */
	if (thesame == *hage)
	    *hage = after;
1248

1249
1250
	unlink_node(thesame);
	renumber(after);
1251
1252
    }

1253
1254
    /* 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. */
1255
1256
1257
1258
1259
1260
    if ((*hbot)->lineno == MAX_SEARCH_HISTORY + 1) {
	filestruct *foo = *hage;

	*hage = (*hage)->next;
	unlink_node(foo);
	renumber(*hage);
1261
    }
1262

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

1269
    /* Indicate that the history needs to be saved on exit. */
1270
1271
1272
1273
    history_changed = TRUE;

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

1276
1277
/* 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. */
1278
char *get_history_older(filestruct **h)
1279
{
1280
    assert(h != NULL);
1281

1282
    if ((*h)->prev == NULL)
1283
	return NULL;
1284
1285
1286
1287

    *h = (*h)->prev;

    return (*h)->data;
1288
1289
}

1290
1291
/* 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. */
1292
char *get_history_newer(filestruct **h)
1293
{
1294
    assert(h != NULL);
1295

1296
    if ((*h)->next == NULL)
1297
	return NULL;
1298

1299
1300
1301
1302
    *h = (*h)->next;

    return (*h)->data;
}
1303

1304
/* More placeholders. */
1305
1306
1307
1308
1309
1310
1311
1312
1313
void get_history_newer_void(void)
{
    ;
}
void get_history_older_void(void)
{
    ;
}

1314
1315
1316
#ifndef DISABLE_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
1317
1318
 * string.  If there isn't one, or if len is 0, don't move h and return
 * s. */
1319
char *get_history_completion(filestruct **h, char *s, size_t len)
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
{
    assert(s != NULL);

    if (len > 0) {
	filestruct *hage = NULL, *hbot = NULL, *p;

	assert(h != NULL);

	if (*h == search_history) {
	    hage = searchage;
	    hbot = searchbot;
	} else if (*h == replace_history) {
	    hage = replaceage;
	    hbot = replacebot;
	}

	assert(hage != NULL && hbot != NULL);

1338
1339
1340
	/* 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, hage, s, len);
1341

1342
	while (p != NULL && strcmp(p->data, s) == 0)
1343
	    p = find_history(p->prev, hage, s, len);
1344

1345
1346
	if (p != NULL) {
	    *h = p;
1347
	    return mallocstrcpy(s, (*h)->data);
1348
1349
	}

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

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

1357
1358
	if (p != NULL) {
	    *h = p;
1359
	    return mallocstrcpy(s, (*h)->data);
1360
1361
1362
	}
    }

1363
1364
    /* If we're here, we didn't find a match, we didn't find an inexact
     * match, or len is 0.  Return s. */
1365
    return (char *)s;
1366
}
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1367
#endif /* !DISABLE_TABCOMP */
1368
#endif /* !DISABLE_HISTORIES */