search.c 32.1 KB
Newer Older
Chris Allegretta's avatar
Chris Allegretta committed
1
/**************************************************************************
2
 *   search.c  --  This file is part of GNU nano.                         *
Chris Allegretta's avatar
Chris Allegretta committed
3
 *                                                                        *
4
 *   Copyright (C) 1999-2011, 2013-2017 Free Software Foundation, Inc.    *
5
 *   Copyright (C) 2015, 2016, 2017 Benno Schulenberg                     *
6
 *                                                                        *
7
8
9
10
 *   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.                               *
Chris Allegretta's avatar
Chris Allegretta committed
11
 *                                                                        *
12
13
14
15
 *   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.                 *
Chris Allegretta's avatar
Chris Allegretta committed
16
17
 *                                                                        *
 *   You should have received a copy of the GNU General Public License    *
18
 *   along with this program.  If not, see http://www.gnu.org/licenses/.  *
Chris Allegretta's avatar
Chris Allegretta committed
19
20
21
 *                                                                        *
 **************************************************************************/

22
#include "proto.h"
23

Chris Allegretta's avatar
Chris Allegretta committed
24
#include <string.h>
25
#ifdef DEBUG
26
#include <time.h>
27
#endif
Chris Allegretta's avatar
Chris Allegretta committed
28

29
30
static bool came_full_circle = FALSE;
	/* Have we reached the starting line again while searching? */
31
32
static bool regexp_compiled = FALSE;
	/* Have we compiled any regular expressions? */
33

34
35
/* Compile the given regular expression and store it in search_regexp.
 * Return TRUE if the expression is valid, and FALSE otherwise. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
36
bool regexp_init(const char *regexp)
37
{
38
    int value = regcomp(&search_regexp, fixbounds(regexp),
39
		NANO_REG_EXTENDED | (ISSET(CASE_SENSITIVE) ? 0 : REG_ICASE));
40

41
42
43
    /* If regex compilation failed, show the error message. */
    if (value != 0) {
	size_t len = regerror(value, &search_regexp, NULL, 0);
44
45
	char *str = charalloc(len);

46
	regerror(value, &search_regexp, str, len);
47
	statusline(ALERT, _("Bad regex \"%s\": %s"), regexp, str);
48
	free(str);
49
50

	return FALSE;
51
    }
52

53
    regexp_compiled = TRUE;
54
55

    return TRUE;
56
57
}

58
59
/* Decompile the compiled regular expression we used in the last
 * search, if any. */
60
void regexp_cleanup(void)
61
{
62
63
    if (regexp_compiled) {
	regexp_compiled = FALSE;
64
65
	regfree(&search_regexp);
    }
66
67
}

68
/* Report on the status bar that the given string was not found. */
69
70
void not_found_msg(const char *str)
{
71
72
    char *disp = display_string(str, 0, (COLS / 2) + 1, FALSE);
    size_t numchars = actual_x(disp, strnlenpt(disp, COLS / 2));
73

74
    statusline(HUSH, _("\"%.*s%s\" not found"), numchars, disp,
75
		(disp[numchars] == '\0') ? "" : "...");
76
    free(disp);
77
78
}

79
80
81
82
83
/* 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)
84
{
85
#ifndef NANO_TINY
86
    if (openfile->mark_set)
87
	refresh_needed = TRUE;
88
89
#endif
    regexp_cleanup();
90
91
}

92
/* Set up the system variables for a search or replace.  If use_answer
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
93
94
95
96
97
 * 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
98
 *
99
100
101
 * 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
102
{
103
    int i = 0;
104
    char *buf;
105
    static char *backupstring = NULL;
106
	/* The search string we'll be using. */
107
    functionptrtype func;
108
109
110
111
112
113

    /* If use_answer is TRUE, set backupstring to answer and get out. */
    if (use_answer) {
	backupstring = mallocstrcpy(backupstring, answer);
	return 0;
    }
114
115
116
117

    /* 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,
118
     * we should put the same search string back up. */
119

120
    if (*last_search != '\0') {
121
	char *disp = display_string(last_search, 0, COLS / 3, FALSE);
122

123
	buf = charalloc(strlen(disp) + 7);
124
	/* We use (COLS / 3) here because we need to see more on the line. */
125
	sprintf(buf, " [%s%s]", disp,
126
		(strlenpt(last_search) > COLS / 3) ? "..." : "");
127
	free(disp);
128
129
    } else
	buf = mallocstrcpy(NULL, "");
Chris Allegretta's avatar
Chris Allegretta committed
130

131
    /* This is now one simple call.  It just does a lot. */
132
    i = do_prompt(FALSE, FALSE,
133
134
		inhelp ? MFINDINHELP : (replacing ? MREPLACE : MWHEREIS),
		backupstring,
135
#ifndef DISABLE_HISTORIES
136
		&search_history,
137
#endif
138
139
140
		/* TRANSLATORS: This is the main search prompt. */
		edit_refresh, "%s%s%s%s%s%s", _("Search"),
		/* TRANSLATORS: The next three modify the search prompt. */
141
		ISSET(CASE_SENSITIVE) ? _(" [Case Sensitive]") : "",
142
		ISSET(USE_REGEXP) ? _(" [Regexp]") : "",
143
		ISSET(BACKWARDS_SEARCH) ? _(" [Backwards]") : "", replacing ?
144
#ifndef NANO_TINY
145
146
		/* TRANSLATORS: The next two modify the search prompt. */
		openfile->mark_set ? _(" (to replace) in selection") :
147
#endif
148
		_(" (to replace)") : "", buf);
Chris Allegretta's avatar
Chris Allegretta committed
149

150
    /* Release buf now that we don't need it anymore. */
Chris Allegretta's avatar
Chris Allegretta committed
151
152
    free(buf);

153
154
155
    free(backupstring);
    backupstring = NULL;

156
157
158
    /* 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')) {
159
	statusbar(_("Cancelled"));
Chris Allegretta's avatar
Chris Allegretta committed
160
	return -1;
161
    }
162

163
164
165
166
167
    /* 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);
168
#ifndef DISABLE_HISTORIES
169
	    update_history(&search_history, answer);
170
#endif
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
	}
	if (ISSET(USE_REGEXP) && !regexp_init(last_search))
	    return -1;
	else
	    return 0;	/* We have a valid string or regex. */
    }

    func = func_from_key(&i);

    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;
188
    } else if (func == regexp_void) {
189
190
191
	TOGGLE(USE_REGEXP);
	backupstring = mallocstrcpy(backupstring, answer);
	return 1;
192
    } else if (func == flip_replace) {
193
194
195
196
	backupstring = mallocstrcpy(backupstring, answer);
	return -2;	/* Call the opposite search function. */
    } else if (func == do_gotolinecolumn_void) {
	do_gotolinecolumn(openfile->current->lineno,
197
			openfile->placewewant + 1, TRUE, TRUE);
198
	return 3;
Chris Allegretta's avatar
Chris Allegretta committed
199
    }
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
200

201
    return -1;
Chris Allegretta's avatar
Chris Allegretta committed
202
203
}

204
/* Look for needle, starting at (current, current_x).  begin is the line
205
206
207
 * 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. */
208
209
int findnextstr(const char *needle, bool whole_word_only, bool have_region,
	size_t *match_len, bool skipone, const filestruct *begin, size_t begin_x)
Chris Allegretta's avatar
Chris Allegretta committed
210
{
211
212
    size_t found_len = strlen(needle);
	/* The length of a match -- will be recomputed for a regex. */
213
214
    int feedback = 0;
	/* When bigger than zero, show and wipe the "Searching..." message. */
215
    filestruct *line = openfile->current;
216
217
218
219
220
	/* The line that we will search through now. */
    const char *from = line->data + openfile->current_x;
	/* The point in the line from where we start searching. */
    const char *found = NULL;
	/* A pointer to the location of the match, if any. */
221
222
    size_t found_x;
	/* The x coordinate of a found occurrence. */
223
    time_t lastkbcheck = time(NULL);
224
	/* The time we last looked at the keyboard. */
225

226
227
    /* Set non-blocking input so that we can just peek for a Cancel. */
    disable_waiting();
228

229
230
231
    if (begin == NULL)
	came_full_circle = FALSE;

232
    /* Start searching through the lines, looking for the needle. */
233
    while (TRUE) {
234
235
	/* Glance at the keyboard once every second. */
	if (time(NULL) - lastkbcheck > 0) {
236
237
	    int input = parse_kbinput(edit);

238
	    lastkbcheck = time(NULL);
239

240
241
242
243
	    /* Consume all waiting keystrokes until a Cancel. */
	    while (input) {
		if (func_from_key(&input) == do_cancel) {
		    statusbar(_("Cancelled"));
244
		    enable_waiting();
245
246
247
		    return -2;
		}
		input = parse_kbinput(NULL);
248
	    }
249
250

	    if (++feedback > 0)
251
252
		/* TRANSLATORS: This is shown when searching takes
		 * more than half a second. */
253
		statusbar(_("Searching..."));
254
255
	}

256
	/* Search for the needle in the current line. */
257
258
	if (!skipone)
	    found = strstrwrapper(line->data, needle, from);
Chris Allegretta's avatar
Chris Allegretta committed
259

260
261
	/* Ignore the initial match at the starting position: continue
	 * searching from the next character, or invalidate the match. */
262
263
	if (skipone || (!whole_word_only && !came_full_circle &&
				found == begin->data + begin_x)) {
264
	    skipone = FALSE;
265
266
267
268
269
270
271
272
273
274
	    if (ISSET(BACKWARDS_SEARCH) && from != line->data) {
		from = line->data + move_mbleft(line->data, from - line->data);
		continue;
	    } else if (!ISSET(BACKWARDS_SEARCH) && *from != '\0') {
		from += move_mbright(from, 0);
		continue;
	    }
	    found = NULL;
	}

275
	if (found != NULL) {
276
	    /* When doing a regex search, compute the length of the match. */
277
	    if (ISSET(USE_REGEXP))
278
		found_len = regmatches[0].rm_eo - regmatches[0].rm_so;
279
#ifndef DISABLE_SPELLER
280
281
282
283
284
285
286
	    /* When we're spell checking, a match should be a separate word;
	     * if it's not, continue looking in the rest of the line. */
	    if (whole_word_only && !is_separate_word(found - line->data,
						found_len, line->data)) {
		from = found + move_mbright(found, 0);
		continue;
	    }
287
#endif
288
289
	    /* The match is valid. */
	    break;
Chris Allegretta's avatar
Chris Allegretta committed
290
	}
291

292
	/* If we're back at the beginning, then there is no needle. */
293
	if (came_full_circle) {
294
	    not_found_msg(needle);
295
	    enable_waiting();
296
	    return 0;
297
	}
298

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
299
	/* Move to the previous or next line in the file. */
300
	if (ISSET(BACKWARDS_SEARCH))
301
	    line = line->prev;
302
	else
303
	    line = line->next;
304

305
306
	/* If we've reached the start or end of the buffer, wrap around;
	 * but stop when spell-checking or replacing in a region. */
307
	if (line == NULL) {
308
	    if (whole_word_only || have_region) {
309
		enable_waiting();
310
311
		return 0;
	    }
312

313
	    if (ISSET(BACKWARDS_SEARCH))
314
		line = openfile->filebot;
315
	    else
316
		line = openfile->fileage;
317

318
	    statusbar(_("Search Wrapped"));
319
320
	    /* Delay the "Searching..." message for at least two seconds. */
	    feedback = -2;
321
	}
Chris Allegretta's avatar
Chris Allegretta committed
322

323
	/* If we've reached the original starting line, take note. */
324
	if (line == begin)
325
	    came_full_circle = TRUE;
326

327
	/* Set the starting x to the start or end of the line. */
328
	from = line->data;
329
	if (ISSET(BACKWARDS_SEARCH))
330
	    from += strlen(line->data);
331
    }
332

333
    found_x = found - line->data;
334

335
336
    enable_waiting();

337
    /* Ensure that the found occurrence is not beyond the starting x. */
338
339
    if (came_full_circle && ((!ISSET(BACKWARDS_SEARCH) && found_x > begin_x) ||
			(ISSET(BACKWARDS_SEARCH) && found_x < begin_x))) {
340
341
342
343
	not_found_msg(needle);
	return 0;
    }

344
    /* Set the current position to point at what we found. */
345
    openfile->current = line;
346
    openfile->current_x = found_x;
347

348
349
350
    /* When requested, pass back the length of the match. */
    if (match_len != NULL)
	*match_len = found_len;
351

352
353
    /* Wipe the "Searching..." message and unset the suppression flag. */
    if (feedback > 0) {
354
	blank_statusbar();
355
356
	suppress_cursorpos = FALSE;
    }
357

358
    return 1;
Chris Allegretta's avatar
Chris Allegretta committed
359
360
}

361
/* Ask what to search for and then go looking for it. */
362
void do_search(void)
Chris Allegretta's avatar
Chris Allegretta committed
363
{
364
    int i = search_init(FALSE, FALSE);
365

366
    if (i == -1)	/* Cancelled, or some other exit reason. */
367
	search_replace_abort();
368
    else if (i == -2)	/* Do a replace instead. */
Chris Allegretta's avatar
Chris Allegretta committed
369
	do_replace();
370
    else if (i == 1)	/* Toggled something. */
Chris Allegretta's avatar
Chris Allegretta committed
371
	do_search();
372

373
374
    if (i == 0)
	go_looking();
Chris Allegretta's avatar
Chris Allegretta committed
375
376
}

377
378
379
380
381
382
383
384
385
386
387
388
389
390
/* Search forward for a string. */
void do_search_forward(void)
{
    UNSET(BACKWARDS_SEARCH);
    do_search();
}

/* Search backwards for a string. */
void do_search_backward(void)
{
    SET(BACKWARDS_SEARCH);
    do_search();
}

391
392
393
394
#ifndef NANO_TINY
/* Search in the backward direction for the next occurrence. */
void do_findprevious(void)
{
395
396
    SET(BACKWARDS_SEARCH);
    do_research();
397
398
399
400
401
}

/* Search in the forward direction for the next occurrence. */
void do_findnext(void)
{
402
403
    UNSET(BACKWARDS_SEARCH);
    do_research();
404
}
405
#endif /* !NANO_TINY */
406

407
/* Search for the last string without prompting. */
408
void do_research(void)
409
{
410
411
412
#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. */
413
    if (*last_search == '\0' && searchbot->prev != NULL)
414
415
416
	last_search = mallocstrcpy(last_search, searchbot->prev->data);
#endif

417
    if (*last_search == '\0') {
418
	statusbar(_("No current search pattern"));
419
420
421
422
423
	return;
    }

    if (ISSET(USE_REGEXP) && !regexp_init(last_search))
	return;
424

425
426
    /* Use the search-menu key bindings, to allow cancelling. */
    currmenu = MWHEREIS;
427

428
429
430
431
432
433
434
435
436
    go_looking();
}

/* 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;
437
438
439
#ifdef DEBUG
    clock_t start = clock();
#endif
440

441
    came_full_circle = FALSE;
442

443
    didfind = findnextstr(last_search, FALSE, FALSE, NULL, FALSE,
444
				openfile->current, openfile->current_x);
445

446
447
    /* If we found something, and we're back at the exact same spot
     * where we started searching, then this is the only occurrence. */
448
    if (didfind == 1 && openfile->current == was_current &&
449
		openfile->current_x == was_current_x)
450
	statusbar(_("This is the only occurrence"));
451

452
453
454
455
#ifdef DEBUG
    statusline(HUSH, "Took: %.2f", (double)(clock() - start) / CLOCKS_PER_SEC);
#endif

456
    edit_redraw(was_current, CENTERING);
457
    search_replace_abort();
458
459
}

460
/* Calculate the size of the replacement text, taking possible
461
462
 * subexpressions \1 to \9 into account.  Return the replacement
 * text in the passed string only when create is TRUE. */
463
int replace_regexp(char *string, bool create)
464
{
465
    const char *c = answer;
466
    size_t replacement_size = 0;
467

Chris Allegretta's avatar
Chris Allegretta committed
468
469
    /* Iterate through the replacement text to handle subexpression
     * replacement using \1, \2, \3, etc. */
470
    while (*c != '\0') {
471
	int num = (*(c + 1) - '0');
472

473
	if (*c != '\\' || num < 1 || num > 9 || num > search_regexp.re_nsub) {
474
	    if (create)
475
476
		*string++ = *c;
	    c++;
477
	    replacement_size++;
478
	} else {
479
	    size_t i = regmatches[num].rm_eo - regmatches[num].rm_so;
480

481
482
	    /* Skip over the replacement expression. */
	    c += 2;
483

484
	    /* But add the length of the subexpression to new_size. */
485
	    replacement_size += i;
486

487
	    /* And if create is TRUE, append the result of the
488
	     * subexpression match to the new line. */
489
	    if (create) {
490
		strncpy(string, openfile->current->data +
491
					regmatches[num].rm_so, i);
492
		string += i;
493
494
	    }
	}
495
496
    }

497
    if (create)
Chris Allegretta's avatar
Chris Allegretta committed
498
	*string = '\0';
499

500
    return replacement_size;
501
}
502

503
/* Return a copy of the current line with one needle replaced. */
504
char *replace_line(const char *needle)
505
{
506
    char *copy;
507
508
    size_t match_len;
    size_t new_line_size = strlen(openfile->current->data) + 1;
509

510
    /* First adjust the size of the new line for the change. */
511
    if (ISSET(USE_REGEXP)) {
512
513
	match_len = regmatches[0].rm_eo - regmatches[0].rm_so;
	new_line_size += replace_regexp(NULL, FALSE) - match_len;
514
    } else {
515
516
	match_len = strlen(needle);
	new_line_size += strlen(answer) - match_len;
517
    }
518

519
    /* Create the buffer. */
520
    copy = charalloc(new_line_size);
521

522
    /* Copy the head of the original line. */
523
    strncpy(copy, openfile->current->data, openfile->current_x);
524

525
    /* Add the replacement text. */
526
    if (ISSET(USE_REGEXP))
527
	replace_regexp(copy + openfile->current_x, TRUE);
528
    else
529
	strcpy(copy + openfile->current_x, answer);
530

531
    assert(openfile->current_x + match_len <= strlen(openfile->current->data));
532

533
    /* Copy the tail of the original line. */
534
    strcat(copy, openfile->current->data + openfile->current_x + match_len);
535
536

    return copy;
Chris Allegretta's avatar
Chris Allegretta committed
537
538
}

539
540
541
/* 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
542
 * allow the cursor position to be updated when a word before the cursor
543
544
 * 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. */
545
546
ssize_t do_replace_loop(const char *needle, bool whole_word_only,
	const filestruct *real_current, size_t *real_current_x)
Chris Allegretta's avatar
Chris Allegretta committed
547
{
548
549
    ssize_t numreplaced = -1;
    size_t match_len;
550
    bool replaceall = FALSE;
551
    bool skipone = FALSE;
552
    bool mark_was_set = FALSE;
553
#ifndef NANO_TINY
554
    filestruct *top, *bot;
555
556
    size_t top_x, bot_x;
    bool right_side_up = FALSE;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
557
	/* TRUE if (mark_begin, mark_begin_x) is the top of the mark,
558
	 * FALSE if (current, current_x) is. */
Chris Allegretta's avatar
Chris Allegretta committed
559

560
561
    mark_was_set = openfile->mark_set;

562
    /* If the mark is on, frame the region, and turn the mark off. */
563
    if (mark_was_set) {
564
	mark_order((const filestruct **)&top, &top_x,
565
			(const filestruct **)&bot, &bot_x, &right_side_up);
566
	openfile->mark_set = FALSE;
567
568
569
570

	/* Start either at the top or the bottom of the marked region. */
	if (!ISSET(BACKWARDS_SEARCH)) {
	    openfile->current = top;
571
	    openfile->current_x = top_x;
572
573
574
575
	} else {
	    openfile->current = bot;
	    openfile->current_x = bot_x;
	}
576
    }
577
#endif /* !NANO_TINY */
578

579
    came_full_circle = FALSE;
580

581
582
    while (TRUE) {
	int i = 0;
583
	int result = findnextstr(needle, whole_word_only, mark_was_set,
584
			&match_len, skipone, real_current, *real_current_x);
585
586
587
588
589
590
591

	/* 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;
	}
592

593
#ifndef NANO_TINY
594
595
596
597
598
599
600
601
	/* An occurrence outside of the marked region means we're done. */
	if (mark_was_set && (openfile->current->lineno > bot->lineno ||
				openfile->current->lineno < top->lineno ||
				(openfile->current == bot &&
				openfile->current_x + match_len > bot_x) ||
				(openfile->current == top &&
				openfile->current_x < top_x)))
	    break;
602
603
#endif

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
604
	/* Indicate that we found the search string. */
605
606
	if (numreplaced == -1)
	    numreplaced = 0;
607

608
	if (!replaceall) {
609
610
611
	    size_t from_col = xplustabs();
	    size_t to_col = strnlenpt(openfile->current->data,
					openfile->current_x + match_len);
612

613
	    /* Refresh the edit window, scrolling it if necessary. */
614
615
	    edit_refresh();

616
	    spotlight(TRUE, from_col, to_col);
617

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

621
	    spotlight(FALSE, from_col, to_col);
622

623
	    if (i == -1)  /* The replacing was cancelled. */
624
		break;
625
626
	    else if (i == 2)
		replaceall = TRUE;
627
628
629
630

	    /* When "No" or moving backwards, the search routine should
	     * first move one character further before continuing. */
	    skipone = (i == 0 || ISSET(BACKWARDS_SEARCH));
631
632
	}

633
	if (i == 1 || replaceall) {  /* Yes, replace it. */
634
	    char *copy;
635
	    size_t length_change;
636

637
#ifndef NANO_TINY
638
	    add_undo(REPLACE);
639
#endif
640
	    copy = replace_line(needle);
Chris Allegretta's avatar
Chris Allegretta committed
641

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

644
#ifndef NANO_TINY
645
646
	    /* If the mark was on and it was located after the cursor,
	     * then adjust its x position for any text length changes. */
647
	    if (mark_was_set && !right_side_up) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
648
649
		if (openfile->current == openfile->mark_begin &&
			openfile->mark_begin_x > openfile->current_x) {
650
		    if (openfile->mark_begin_x < openfile->current_x + match_len)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
651
			openfile->mark_begin_x = openfile->current_x;
652
		    else
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
653
			openfile->mark_begin_x += length_change;
654
		    bot_x = openfile->mark_begin_x;
655
		}
656
	    }
Chris Allegretta's avatar
Chris Allegretta committed
657

658
659
	    /* If the mark was not on or it was before the cursor, then
	     * adjust the cursor's x position for any text length changes. */
660
	    if (!mark_was_set || right_side_up) {
661
#endif
662
		if (openfile->current == real_current &&
663
			openfile->current_x < *real_current_x) {
664
665
		    if (*real_current_x < openfile->current_x + match_len)
			*real_current_x = openfile->current_x + match_len;
666
		    *real_current_x += length_change;
667
#ifndef NANO_TINY
668
		    bot_x = *real_current_x;
669
		}
670
#endif
671
	    }
672

673
674
	    /* Don't find the same zero-length or BOL match again. */
	    if (match_len == 0 || (*needle == '^' && ISSET(USE_REGEXP)))
675
		skipone = TRUE;
676

677
678
	    /* When moving forward, put the cursor just after the replacement
	     * text, so that searching will continue there. */
679
	    if (!ISSET(BACKWARDS_SEARCH))
680
		openfile->current_x += match_len + length_change;
681

682
683
	    /* Update the file size, and put the changed line into place. */
	    openfile->totsize += mbstrlen(copy) - mbstrlen(openfile->current->data);
684
685
	    free(openfile->current->data);
	    openfile->current->data = copy;
686

687
	    if (!replaceall) {
688
#ifndef DISABLE_COLOR
689
690
		/* When doing syntax coloring, the replacement might require
		 * a change of colors, so refresh the whole edit window. */
691
		if (openfile->colorstrings != NULL && !ISSET(NO_COLOR_SYNTAX))
692
693
694
		    edit_refresh();
		else
#endif
695
		    update_line(openfile->current, openfile->current_x);
696
697
	    }

Chris Allegretta's avatar
Chris Allegretta committed
698
	    set_modified();
699
	    as_an_at = TRUE;
Chris Allegretta's avatar
Chris Allegretta committed
700
	    numreplaced++;
701
	}
Chris Allegretta's avatar
Chris Allegretta committed
702
703
    }

704
705
    if (numreplaced == -1)
	not_found_msg(needle);
706
707
708
709
#ifndef DISABLE_COLOR
    else if (numreplaced > 0)
	refresh_needed = TRUE;
#endif
710

711
#ifndef NANO_TINY
712
    if (mark_was_set)
713
	openfile->mark_set = TRUE;
714
715
#endif

716
717
718
    /* 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')
719
720
	new_magicline();

Chris Allegretta's avatar
Chris Allegretta committed
721
722
723
    return numreplaced;
}

Chris Allegretta's avatar
Chris Allegretta committed
724
/* Replace a string. */
725
void do_replace(void)
Chris Allegretta's avatar
Chris Allegretta committed
726
{
727
    filestruct *edittop_save, *begin;
728
    size_t firstcolumn_save, begin_x;
729
    ssize_t numreplaced;
730
    int i;
Chris Allegretta's avatar
Chris Allegretta committed
731

Chris Allegretta's avatar
Chris Allegretta committed
732
733
    if (ISSET(VIEW_MODE)) {
	print_view_warning();
734
	return;
Chris Allegretta's avatar
Chris Allegretta committed
735
736
    }

737
    i = search_init(TRUE, FALSE);
738
739

    if (i == -1)	/* Cancelled, or some other exit reason. */
740
	search_replace_abort();
741
    else if (i == -2)	/* Do a search instead. */
Chris Allegretta's avatar
Chris Allegretta committed
742
	do_search();
743
    else if (i == 1)	/* Toggled something. */
744
745
746
	do_replace();

    if (i != 0)
747
	return;
Chris Allegretta's avatar
Chris Allegretta committed
748

749
    i = do_prompt(FALSE, FALSE, MREPLACEWITH, NULL,
750
#ifndef DISABLE_HISTORIES
751
		&replace_history,
752
#endif
753
754
		/* TRANSLATORS: This is a prompt. */
		edit_refresh, _("Replace with"));
755

756
#ifndef DISABLE_HISTORIES
757
    /* If the replace string is not "", add it to the replace history list. */
758
    if (i == 0)
759
	update_history(&replace_history, answer);
760
761
#endif

762
763
764
    /* When cancelled, or when a function was run, get out. */
    if (i == -1 || i > 0) {
	if (i == -1)
765
	    statusbar(_("Cancelled"));
766
	search_replace_abort();
767
	return;
768
769
770
    }

    /* Save where we are. */
771
    edittop_save = openfile->edittop;
772
    firstcolumn_save = openfile->firstcolumn;
773
    begin = openfile->current;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
774
    begin_x = openfile->current_x;
Chris Allegretta's avatar
Chris Allegretta committed
775

776
    numreplaced = do_replace_loop(last_search, FALSE, begin, &begin_x);
Chris Allegretta's avatar
Chris Allegretta committed
777

778
    /* Restore where we were. */
779
    openfile->edittop = edittop_save;
780
    openfile->firstcolumn = firstcolumn_save;
781
    openfile->current = begin;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
782
    openfile->current_x = begin_x;
783
    refresh_needed = TRUE;
Chris Allegretta's avatar
Chris Allegretta committed
784
785

    if (numreplaced >= 0)
786
	statusline(HUSH, P_("Replaced %lu occurrence",
787
788
		"Replaced %lu occurrences", (unsigned long)numreplaced),
		(unsigned long)numreplaced);
Chris Allegretta's avatar
Chris Allegretta committed
789

790
    search_replace_abort();
Chris Allegretta's avatar
Chris Allegretta committed
791
792
}

793
794
795
/* Go to the specified line and x position. */
void goto_line_posx(ssize_t line, size_t pos_x)
{
796
797
    for (openfile->current = openfile->fileage; line > 1 &&
		openfile->current != openfile->filebot; line--)
798
799
800
801
802
	openfile->current = openfile->current->next;

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

803
    refresh_needed = TRUE;
804
805
}

806
/* Go to the specified line and column, or ask for them if interactive
807
 * is TRUE.  In the latter case also update the screen afterwards.
808
 * Note that both the line and column number should be one-based. */
809
void do_gotolinecolumn(ssize_t line, ssize_t column, bool use_answer,
810
	bool interactive)
Chris Allegretta's avatar
Chris Allegretta committed
811
{
812
    if (interactive) {
813
	functionptrtype func;
814

815
	/* Ask for the line and column. */
816
817
	int i = do_prompt(FALSE, FALSE, MGOTOLINE,
		use_answer ? answer : NULL,
818
#ifndef DISABLE_HISTORIES
819
		NULL,
Chris Allegretta's avatar
Chris Allegretta committed
820
#endif
821
		/* TRANSLATORS: This is a prompt. */
822
		edit_refresh, _("Enter line number, column number"));
823

824
	/* If the user cancelled or gave a blank answer, get out. */
825
	if (i < 0) {
826
	    statusbar(_("Cancelled"));
827
828
829
	    return;
	}

830
	func = func_from_key(&i);
831

832
	if (func == gototext_void) {
833
	    /* Retain what the user typed so far and switch to searching. */
834
	    search_init(TRUE, TRUE);
835
	    do_search();
Chris Allegretta's avatar
Chris Allegretta committed
836
	}
837

838
839
840
841
	/* If a function was executed, we're done here. */
	if (i > 0)
	    return;

842
843
	/* Try to extract one or two numbers from the user's response. */
	if (!parse_line_column(answer, &line, &column)) {
844
	    statusline(ALERT, _("Invalid line or column number"));
845
	    return;
Chris Allegretta's avatar
Chris Allegretta committed
846
	}
847
    } else {
848
	if (line == 0)
849
	    line = openfile->current->lineno;
850

851
	if (column == 0)
852
	    column = openfile->placewewant + 1;
Chris Allegretta's avatar
Chris Allegretta committed
853
854
    }

855
856
857
858
859
860
861
    /* 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. */
862
863
    for (openfile->current = openfile->fileage; line > 1 &&
		openfile->current != openfile->filebot; line--)
864
	openfile->current = openfile->current->next;
Chris Allegretta's avatar
Chris Allegretta committed
865

866
867
868
869
870
871
872
    /* 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. */
873
874
    openfile->current_x = actual_x(openfile->current->data, column - 1);
    openfile->placewewant = column - 1;
875

876
877
878
879
880
881
#ifndef NANO_TINY
    if (ISSET(SOFTWRAP) && openfile->placewewant / editwincols >
			strlenpt(openfile->current->data) / editwincols)
	openfile->placewewant = strlenpt(openfile->current->data);
#endif

882
    /* When the position was manually given, center the target line. */
883
    if (interactive) {
884
885
	adjust_viewport(CENTERING);
	refresh_needed = TRUE;
886
    } else {
887
888
889
890
891
	int rows_from_tail;

#ifndef NANO_TINY
	if (ISSET(SOFTWRAP)) {
	    filestruct *line = openfile->current;
892
	    size_t leftedge = leftedge_for(xplustabs(), openfile->current);
893
894
895
896
897
898
899
900

	    rows_from_tail = (editwinrows / 2) -
			go_forward_chunks(editwinrows / 2, &line, &leftedge);
	} else
#endif
	    rows_from_tail = openfile->filebot->lineno -
				openfile->current->lineno;

901
	/* If the target line is close to the tail of the file, put the last
902
	 * line or chunk on the bottom line of the screen; otherwise, just
903
	 * center the target line. */
904
	if (rows_from_tail < editwinrows / 2 && ISSET(SMOOTH_SCROLL)) {
905
	    openfile->current_y = editwinrows - 1 - rows_from_tail;
906
	    adjust_viewport(STATIONARY);
907
	} else
908
	    adjust_viewport(CENTERING);
909
    }
Chris Allegretta's avatar
Chris Allegretta committed
910
911
}

912
/* Go to the specified line and column, asking for them beforehand. */
913
void do_gotolinecolumn_void(void)
Chris Allegretta's avatar
Chris Allegretta committed
914
{
915
    do_gotolinecolumn(openfile->current->lineno,
916
	openfile->placewewant + 1, FALSE, TRUE);
Chris Allegretta's avatar
Chris Allegretta committed
917
}
918

919
#ifndef NANO_TINY
920
/* Search for a match to one of the two characters in bracket_set.  If
921
922
923
 * 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. */
924
925
926
927
928
bool find_bracket_match(bool reverse, const char *bracket_set)
{
    filestruct *fileptr = openfile->current;
    const char *rev_start = NULL, *found = NULL;

929
    assert(mbstrlen(bracket_set) == 2);
930
931
932
933
934

    /* 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. */
935
936
937
938
    if (reverse)
	rev_start = fileptr->data + (openfile->current_x - 1);
    else
	rev_start = fileptr->data + (openfile->current_x + 1);
939
940
941
942
943

    /* 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) {
944
945
946
947
948
949
950
	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);
951

952
	if (found)
953
954
	    break;

955
	if (reverse)
956
	    fileptr = fileptr->prev;
957
	else
958
959
	    fileptr = fileptr->next;

960
	/* If we've reached the start or end of the buffer, get out. */
961
962
963
964
965
966
967
968
	if (fileptr == NULL)
	    return FALSE;

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

969
    /* Set the current position to the found matching bracket. */
970
    openfile->current = fileptr;
971
    openfile->current_x = found - fileptr->data;
972
973
974
975
976
977

    return TRUE;
}

/* Search for a match to the bracket at the current cursor position, if
 * there is one. */
978
void do_find_bracket(void)
979
{
980
    filestruct *current_save;
981
    size_t current_x_save;
982
    const char *ch;
983
	/* The location in matchbrackets of the bracket at the current
984
	 * cursor position. */
985
986
987
    int ch_len;
	/* The length of ch in bytes. */
    const char *wanted_ch;
988
989
	/* The location in matchbrackets of the bracket complementing
	 * the bracket at the current cursor position. */
990
991
    int wanted_ch_len;
	/* The length of wanted_ch in bytes. */
992
    char bracket_set[MAXCHARLEN * 2 + 1];
993
	/* The pair of characters in ch and wanted_ch. */
994
995
    size_t i;
	/* Generic loop variable. */
996
    size_t matchhalf;
997
998
999
1000
1001
	/* The number of single-byte characters in one half of
	 * matchbrackets. */
    size_t mbmatchhalf;
	/* The number of multibyte characters in one half of
	 * matchbrackets. */
1002
1003
1004
1005
1006
    size_t count = 1;
	/* The initial bracket count. */
    bool reverse;
	/* The direction we search. */

1007
    assert(mbstrlen(matchbrackets) % 2 == 0);
1008

1009
    ch = openfile->current->data + openfile->current_x;
1010

1011
    if ((ch = mbstrchr(matchbrackets, ch)) == NULL) {
1012
	statusbar(_("Not a bracket"));
1013
	return;
1014
1015
    }

1016
    /* Save where we are. */
1017
1018
    current_save = openfile->current;
    current_x_save = openfile->current_x;
1019

1020
    /* If we're on an opening bracket, which must be in the first half
1021
     * of matchbrackets, we want to search forwards for a closing
1022
     * bracket.  If we're on a closing bracket, which must be in the
1023
     * second half of matchbrackets, we want to search backwards for an
1024
     * opening bracket. */
1025
1026
1027
1028
    matchhalf = 0;
    mbmatchhalf = mbstrlen(matchbrackets) / 2;

    for (i = 0; i < mbmatchhalf; i++)
1029
	matchhalf += parse_mbchar(matchbrackets + matchhalf, NULL, NULL);
1030

1031
    reverse = ((ch - matchbrackets) >= matchhalf);
1032
1033

    /* If we're on an opening bracket, set wanted_ch to the character
1034
1035
1036
     * 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. */
1037
1038
    wanted_ch = ch;

1039
    while (mbmatchhalf > 0) {
1040
	if (reverse)
1041
	    wanted_ch = matchbrackets + move_mbleft(matchbrackets,
1042
				wanted_ch - matchbrackets);
1043
1044
1045
	else
	    wanted_ch += move_mbright(wanted_ch, 0);

1046
	mbmatchhalf--;
1047
1048
1049
1050
1051
1052
1053
1054
    }

    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. */
    strncpy(bracket_set, ch, ch_len);
    strncpy(bracket_set + ch_len, wanted_ch, wanted_ch_len);
1055
    bracket_set[ch_len + wanted_ch_len] = '\0';
1056

1057
    while (TRUE) {
1058
	if (find_bracket_match(reverse, bracket_set)) {
1059
1060
	    /* If we found an identical bracket, increment count.  If we
	     * found a complementary bracket, decrement it. */
1061
1062
	    count += (strncmp(openfile->current->data + openfile->current_x,
				 ch, ch_len) == 0) ? 1 : -1;
1063
1064
1065
1066

	    /* If count is zero, we've found a matching bracket.  Update
	     * the screen and get out. */
	    if (count == 0) {
1067
		edit_redraw(current_save, FLOWING);
1068
		break;
1069
	    }
Chris Allegretta's avatar
Chris Allegretta committed
1070
	} else {
1071
1072
	    /* We didn't find either an opening or closing bracket.
	     * Indicate this, restore where we were, and get out. */
1073
	    statusbar(_("No matching bracket"));
1074
1075
	    openfile->current = current_save;
	    openfile->current_x = current_x_save;
1076
1077
1078
1079
	    break;
	}
    }
}
1080
#endif /* !NANO_TINY */