"src/search.c" did not exist on "7a50009b1f3e337dff510f903d593590785646fa"
search.c 30.4 KB
Newer Older
Chris Allegretta's avatar
Chris Allegretta committed
1
/* $Id$ */
Chris Allegretta's avatar
Chris Allegretta committed
2
3
4
/**************************************************************************
 *   search.c                                                             *
 *                                                                        *
5
 *   Copyright (C) 2000-2004 Chris Allegretta                             *
Chris Allegretta's avatar
Chris Allegretta committed
6
7
 *   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 *
8
 *   the Free Software Foundation; either version 2, or (at your option)  *
Chris Allegretta's avatar
Chris Allegretta committed
9
10
11
12
13
14
15
16
17
18
19
20
21
 *   any later version.                                                   *
 *                                                                        *
 *   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.                         *
 *                                                                        *
 *   You should have received a copy of the GNU General Public License    *
 *   along with this program; if not, write to the Free Software          *
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.            *
 *                                                                        *
 **************************************************************************/

22
23
#include "config.h"

Chris Allegretta's avatar
Chris Allegretta committed
24
25
26
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
27
#include <unistd.h>
Chris Allegretta's avatar
Chris Allegretta committed
28
#include <ctype.h>
29
#include <errno.h>
Chris Allegretta's avatar
Chris Allegretta committed
30
#include <assert.h>
Chris Allegretta's avatar
Chris Allegretta committed
31
32
#include "proto.h"
#include "nano.h"
Chris Allegretta's avatar
Chris Allegretta committed
33

34
#ifdef HAVE_REGEX_H
35
36
37
38
39
40
41
static int regexp_compiled = FALSE;

/* Regular expression helper functions. */

/* Compile the given regular expression.  Return value 0 means the
 * expression was invalid, and we wrote an error message on the status
 * bar.  Return value 1 means success. */
42
int regexp_init(const char *regexp)
43
{
44
45
46
47
48
    int rc = regcomp(&search_regexp, regexp, REG_EXTENDED
#ifndef NANO_SMALL
	| (ISSET(CASE_SENSITIVE) ? 0 : REG_ICASE)
#endif
	);
49
50
51
52
53
54
55
56
57

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

	regerror(rc, &search_regexp, str, len);
	statusbar(_("Bad regex \"%s\": %s"), regexp, str);
	free(str);
58
	return 0;
59
    }
60

61
    regexp_compiled = TRUE;
62
    return 1;
63
64
}

65
void regexp_cleanup(void)
66
{
67
68
    if (regexp_compiled) {
	regexp_compiled = FALSE;
69
70
	regfree(&search_regexp);
    }
71
}
72
#endif
73

74
75
void not_found_msg(const char *str)
{
76
77
78
    char *disp;
    int numchars;
 
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
79
    assert(str != NULL);
80
81
82
83
84
85
86
87

    disp = display_string(str, 0, (COLS / 2) + 1);
    numchars = strnlen(disp, COLS / 2);

    statusbar(_("\"%.*s%s\" not found"), numchars, disp,
	disp[numchars] == '\0' ? "" : "...");

    free(disp);
88
89
90
91
92
}

void search_abort(void)
{
    display_main_list();
93
#ifndef NANO_SMALL
94
    if (ISSET(MARK_ISSET))
95
96
	edit_refresh();
#endif
97
#ifdef HAVE_REGEX_H
98
    regexp_cleanup();
99
100
101
#endif
}

Chris Allegretta's avatar
Chris Allegretta committed
102
103
void search_init_globals(void)
{
104
105
106
107
    if (last_search == NULL)
	last_search = mallocstrcpy(NULL, "");
    if (last_replace == NULL)
	last_replace = mallocstrcpy(NULL, "");
Chris Allegretta's avatar
Chris Allegretta committed
108
109
}

110
111
112
113
114
115
/* Set up the system variables for a search or replace.  If use_answer
 * is TRUE, only set backupstring to answer.  Return -2 to run opposite
 * program (search -> replace, replace -> search), return -1 if the
 * search should be canceled (due to Cancel, 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
116
 *
117
118
119
 * 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
120
{
121
    int i = 0;
122
    char *buf;
123
    static char *backupstring = NULL;
124
125
126
127
128
129
130
131
132
133
134
	/* The search string we'll be using. */

    /* If backupstring doesn't exist, initialize it to "". */
    if (backupstring == NULL)
	backupstring = mallocstrcpy(NULL, "");

    /* If use_answer is TRUE, set backupstring to answer and get out. */
    if (use_answer) {
	backupstring = mallocstrcpy(backupstring, answer);
	return 0;
    }
135
136
137
138

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

Chris Allegretta's avatar
Chris Allegretta committed
141
    search_init_globals();
142

143
#ifndef NANO_SMALL
144
    search_history.current = (historytype *)&search_history.next;
145
#endif
146
147

    if (last_search[0] != '\0') {
148
149
	char *disp = display_string(last_search, 0, COLS / 3);

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

159
    /* This is now one simple call.  It just does a lot. */
160
161
    i = statusq(FALSE, replacing ? replace_list : whereis_list,
	backupstring,
162
163
164
#ifndef NANO_SMALL
	&search_history,
#endif
165
	"%s%s%s%s%s%s", _("Search"),
166

167
#ifndef NANO_SMALL
168
169
	/* This string is just a modifier for the search prompt; no
	 * grammar is implied. */
170
171
172
	ISSET(CASE_SENSITIVE) ? _(" [Case Sensitive]") :
#endif
		"",
173

174
#ifdef HAVE_REGEX_H
175
176
	/* This string is just a modifier for the search prompt; no
	 * grammar is implied. */
177
178
179
	ISSET(USE_REGEXP) ? _(" [Regexp]") :
#endif
		"",
180

181
#ifndef NANO_SMALL
182
183
	/* This string is just a modifier for the search prompt; no
	 * grammar is implied. */
184
185
186
	ISSET(REVERSE_SEARCH) ? _(" [Backwards]") :
#endif
		"",
187

Chris Allegretta's avatar
Chris Allegretta committed
188
189
	replacing ? _(" (to replace)") : "",
	buf);
Chris Allegretta's avatar
Chris Allegretta committed
190

191
    /* Release buf now that we don't need it anymore. */
Chris Allegretta's avatar
Chris Allegretta committed
192
193
    free(buf);

194
195
196
    free(backupstring);
    backupstring = NULL;

197
198
199
    /* Cancel any search, or just return with no previous search. */
    if (i == -1 || (i < 0 && last_search[0] == '\0') ||
	    (!replacing && i == 0 && answer[0] == '\0')) {
200
	statusbar(_("Cancelled"));
201
202
203
#ifndef NANO_SMALL
	search_history.current = search_history.next;
#endif
Chris Allegretta's avatar
Chris Allegretta committed
204
	return -1;
Chris Allegretta's avatar
Chris Allegretta committed
205
206
    } else {
	switch (i) {
207
	    case -2:		/* It's the same string. */
208
#ifdef HAVE_REGEX_H
209
210
211
		/* Since answer is "", use last_search! */
		if (ISSET(USE_REGEXP) && regexp_init(last_search) == 0)
		    return -1;
212
#endif
213
214
215
		break;
	    case 0:		/* They entered something new. */
		last_replace[0] = '\0';
216
#ifdef HAVE_REGEX_H
217
218
		if (ISSET(USE_REGEXP) && regexp_init(answer) == 0)
		    return -1;
219
#endif
220
		break;
Chris Allegretta's avatar
Chris Allegretta committed
221
#ifndef NANO_SMALL
222
223
224
225
226
227
228
229
	    case TOGGLE_CASE_KEY:
		TOGGLE(CASE_SENSITIVE);
		backupstring = mallocstrcpy(backupstring, answer);
		return 1;
	    case TOGGLE_BACKWARDS_KEY:
		TOGGLE(REVERSE_SEARCH);
		backupstring = mallocstrcpy(backupstring, answer);
		return 1;
230
#ifdef HAVE_REGEX_H
231
232
233
234
	    case TOGGLE_REGEXP_KEY:
		TOGGLE(USE_REGEXP);
		backupstring = mallocstrcpy(backupstring, answer);
		return 1;
235
#endif
Chris Allegretta's avatar
Chris Allegretta committed
236
#endif /* !NANO_SMALL */
237
238
239
240
	    case NANO_TOOTHERSEARCH_KEY:
		backupstring = mallocstrcpy(backupstring, answer);
		return -2;	/* Call the opposite search function. */
	    case NANO_TOGOTOLINE_KEY:
241
#ifndef NANO_SMALL
242
		search_history.current = search_history.next;
243
#endif
244
245
246
247
248
		/* Put answer up on the statusbar. */
		do_gotoline(-1, FALSE);
		/* Fall through. */
	    default:
		return -1;
Chris Allegretta's avatar
Chris Allegretta committed
249
	}
Chris Allegretta's avatar
Chris Allegretta committed
250
251
252
253
    }
    return 0;
}

254
bool is_whole_word(int curr_pos, const char *datastr, const char
255
	*searchword)
256
{
Chris Allegretta's avatar
Chris Allegretta committed
257
    size_t sln = curr_pos + strlen(searchword);
258

259
260
    /* Start of line or previous character is not a letter and end of
     * line or next character is not a letter. */
Chris Allegretta's avatar
Chris Allegretta committed
261
262
    return (curr_pos < 1 || !isalpha((int)datastr[curr_pos - 1])) &&
	(sln == strlen(datastr) || !isalpha((int)datastr[sln]));
263
264
}

265
/* Look for needle, starting at current, column current_x.  If
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
266
267
268
269
270
 * no_sameline is TRUE, skip over begin when looking for needle.  begin
 * is the line where we first started searching, at column beginx.  If
 * can_display_wrap is TRUE, we put messages on the statusbar, and wrap
 * around the file boundaries.  The return value specifies whether we
 * found anything. */
271
272
273
bool findnextstr(bool can_display_wrap, bool wholeword, bool
	no_sameline, const filestruct *begin, size_t beginx, const char
	*needle)
Chris Allegretta's avatar
Chris Allegretta committed
274
{
Chris Allegretta's avatar
Chris Allegretta committed
275
    filestruct *fileptr = current;
276
277
278
    const char *rev_start = NULL, *found = NULL;
    size_t current_x_find = 0;
	/* Where needle was found. */
279
    int current_y_find = current_y;
280
281
282
283
284
285

    /* 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
286
    rev_start =
287
#ifndef NANO_SMALL
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
288
	ISSET(REVERSE_SEARCH) ? fileptr->data + (current_x - 1) :
289
#endif
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
290
	fileptr->data + (current_x + 1);
Chris Allegretta's avatar
Chris Allegretta committed
291

292
    /* Look for needle in searchstr. */
293
    while (TRUE) {
294
	found = strstrwrapper(fileptr->data, needle, rev_start);
Chris Allegretta's avatar
Chris Allegretta committed
295

296
297
298
299
	if (found != NULL && (!wholeword || is_whole_word(found -
		fileptr->data, fileptr->data, needle))) {
	    if (!no_sameline || fileptr != current)
		break;
Chris Allegretta's avatar
Chris Allegretta committed
300
	}
301

302
	/* We've finished processing the file, so get out. */
303
304
	if (search_last_line) {
	    if (can_display_wrap)
Chris Allegretta's avatar
Chris Allegretta committed
305
		not_found_msg(needle);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
306
	    return FALSE;
307
	}
308
309
310
311
312
313
314
315
316

#ifndef NANO_SMALL
	if (ISSET(REVERSE_SEARCH)) {
	    fileptr = fileptr->prev;
	    current_y_find--;
	} else {
#endif
	    fileptr = fileptr->next;
	    current_y_find++;
317
#ifndef NANO_SMALL
318
	}
319
#endif
320

321
	/* Start or end of buffer reached, so wrap around. */
322
323
	if (fileptr == NULL) {
	    if (!can_display_wrap)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
324
		return FALSE;
325

326
#ifndef NANO_SMALL
327
328
329
330
	    if (ISSET(REVERSE_SEARCH)) {
		fileptr = filebot;
		current_y_find = editwinrows - 1;
	    } else {
331
#endif
332
333
334
335
336
337
		fileptr = fileage;
		current_y_find = 0;
#ifndef NANO_SMALL
	    }
#endif

338
339
340
	    if (can_display_wrap)
		statusbar(_("Search Wrapped"));
	}
Chris Allegretta's avatar
Chris Allegretta committed
341

342
343
	/* Original start line reached. */
	if (fileptr == begin)
344
	    search_last_line = TRUE;
345
346
347
348
349
350
	rev_start = fileptr->data;
#ifndef NANO_SMALL
	if (ISSET(REVERSE_SEARCH))
	    rev_start += strlen(fileptr->data);
#endif
    }
351

352
353
    /* We found an instance. */
    current_x_find = found - fileptr->data;
Chris Allegretta's avatar
Chris Allegretta committed
354

355
356
357
358
359
360
361
362
363
    /* Ensure we haven't wrapped around again! */
    if (search_last_line &&
#ifndef NANO_SMALL
	((!ISSET(REVERSE_SEARCH) && current_x_find > beginx) ||
	(ISSET(REVERSE_SEARCH) && current_x_find < beginx))
#else
	current_x_find > beginx
#endif
	) {
Chris Allegretta's avatar
Chris Allegretta committed
364

365
366
	if (can_display_wrap)
	    not_found_msg(needle);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
367
	return FALSE;
Chris Allegretta's avatar
Chris Allegretta committed
368
369
    }

370
    /* Set globals now that we are sure we found something. */
371
372
    current = fileptr;
    current_x = current_x_find;
373
    current_y = current_y_find;
374

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
375
    return TRUE;
Chris Allegretta's avatar
Chris Allegretta committed
376
377
}

Chris Allegretta's avatar
Chris Allegretta committed
378
/* Search for a string. */
379
void do_search(void)
Chris Allegretta's avatar
Chris Allegretta committed
380
{
381
    size_t old_pww = placewewant, fileptr_x = current_x;
382
383
    int i;
    bool didfind;
384
    filestruct *fileptr = current;
Chris Allegretta's avatar
Chris Allegretta committed
385

386
#ifndef DISABLE_WRAPPING
Chris Allegretta's avatar
Chris Allegretta committed
387
    wrap_reset();
388
#endif
389

390
    i = search_init(FALSE, FALSE);
391
392
    if (i == -1)	/* Cancel, Go to Line, blank search string, or
			 * regcomp() failed. */
Chris Allegretta's avatar
Chris Allegretta committed
393
	search_abort();
394
    else if (i == -2)	/* Replace. */
Chris Allegretta's avatar
Chris Allegretta committed
395
	do_replace();
396
397
398
#ifndef NANO_SMALL
    else if (i == 1)	/* Case Sensitive, Backwards, or Regexp search
			 * toggle. */
Chris Allegretta's avatar
Chris Allegretta committed
399
	do_search();
400
#endif
401

402
    if (i != 0)
403
	return;
404
405

    /* If answer is now "", copy last_search into answer. */
Chris Allegretta's avatar
Chris Allegretta committed
406
    if (answer[0] == '\0')
407
408
409
410
	answer = mallocstrcpy(answer, last_search);
    else
	last_search = mallocstrcpy(last_search, answer);

411
#ifndef NANO_SMALL
412
413
    /* If answer is not "", add this search string to the search history
     * list. */
Chris Allegretta's avatar
Chris Allegretta committed
414
    if (answer[0] != '\0')
415
	update_history(&search_history, answer);
416
#endif
417

418
    search_last_line = FALSE;
419
    didfind = findnextstr(TRUE, FALSE, FALSE, current, current_x, answer);
420

421
422
423
424
425
426
427
428
429
    /* Check to see if there's only one occurrence of the string and
     * we're on it now. */
    if (fileptr == current && fileptr_x == current_x && didfind) {
#ifdef HAVE_REGEX_H
	/* Do the search again, skipping over the current line, if we're
	 * doing a bol and/or eol regex search ("^", "$", or "^$"), so
	 * that we find one only once per line.  We should only end up
	 * back at the same position if the string isn't found again, in
	 * which case it's the only occurrence. */
430
431
	if (ISSET(USE_REGEXP) && regexp_bol_or_eol(&search_regexp,
		last_search)) {
432
433
	    didfind = findnextstr(TRUE, FALSE, TRUE, current, current_x,
		answer);
434
435
436
437
438
439
440
441
442
	    if (fileptr == current && fileptr_x == current_x && !didfind)
		statusbar(_("This is the only occurrence"));
	} else {
#endif
	    statusbar(_("This is the only occurrence"));
#ifdef HAVE_REGEX_H
	}
#endif
    }
443

444
    placewewant = xplustabs();
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
445
    edit_redraw(fileptr, old_pww);
Chris Allegretta's avatar
Chris Allegretta committed
446
447
448
    search_abort();
}

449
#ifndef NANO_SMALL
450
/* Search for the next string without prompting. */
451
void do_research(void)
452
{
453
    size_t old_pww = placewewant, fileptr_x = current_x;
454
    bool didfind;
455
    filestruct *fileptr = current;
456

457
#ifndef DISABLE_WRAPPING
458
    wrap_reset();
459
#endif
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
460

461
462
463
464
465
    search_init_globals();

    if (last_search[0] != '\0') {

#ifdef HAVE_REGEX_H
466
	/* Since answer is "", use last_search! */
467
	if (ISSET(USE_REGEXP) && regexp_init(last_search) == 0)
468
	    return;
469
470
#endif

471
	search_last_line = FALSE;
472
473
	didfind = findnextstr(TRUE, FALSE, FALSE, current, current_x,
		last_search);
474

475
476
477
478
479
480
481
482
483
	/* Check to see if there's only one occurrence of the string and
	 * we're on it now. */
	if (fileptr == current && fileptr_x == current_x && didfind) {
#ifdef HAVE_REGEX_H
	    /* Do the search again, skipping over the current line, if
	     * we're doing a bol and/or eol regex search ("^", "$", or
	     * "^$"), so that we find one only once per line.  We should
	     * only end up back at the same position if the string isn't
	     * found again, in which case it's the only occurrence. */
484
485
	    if (ISSET(USE_REGEXP) && regexp_bol_or_eol(&search_regexp,
		last_search)) {
486
487
		didfind = findnextstr(TRUE, FALSE, TRUE, current,
			current_x, answer);
488
489
490
491
492
493
494
495
496
		if (fileptr == current && fileptr_x == current_x && !didfind)
		    statusbar(_("This is the only occurrence"));
	    } else {
#endif
		statusbar(_("This is the only occurrence"));
#ifdef HAVE_REGEX_H
	    }
#endif
	}
497
498
499
    } else
        statusbar(_("No current search pattern"));

500
    placewewant = xplustabs();
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
501
    edit_redraw(fileptr, old_pww);
502
503
    search_abort();
}
504
#endif
505

Chris Allegretta's avatar
Chris Allegretta committed
506
507
void replace_abort(void)
{
508
509
510
    /* Identical to search_abort(), so we'll call it here.  If it does
     * something different later, we can change it back.  For now, it's
     * just a waste to duplicate code. */
511
    search_abort();
512
    placewewant = xplustabs();
513
514
}

515
#ifdef HAVE_REGEX_H
516
int replace_regexp(char *string, bool create_flag)
517
{
518
    /* Split personality here - if create_flag is FALSE, just calculate
519
     * the size of the replacement line (necessary because of
520
     * subexpressions \1 to \9 in the replaced text). */
521

522
    const char *c = last_replace;
523
    int search_match_count = regmatches[0].rm_eo - regmatches[0].rm_so;
524
    int new_size = strlen(current->data) + 1 - search_match_count;
525

Chris Allegretta's avatar
Chris Allegretta committed
526
527
    /* Iterate through the replacement text to handle subexpression
     * replacement using \1, \2, \3, etc. */
528
    while (*c != '\0') {
529
530
	int num = (int)(*(c + 1) - '0');

531
532
	if (*c != '\\' || num < 1 || num > 9 || num >
		search_regexp.re_nsub) {
533
534
535
536
537
	    if (create_flag)
		*string++ = *c;
	    c++;
	    new_size++;
	} else {
538
	    int i = regmatches[num].rm_eo - regmatches[num].rm_so;
539

540
541
	    /* Skip over the replacement expression. */
	    c += 2;
542

543
544
	    /* But add the length of the subexpression to new_size. */
	    new_size += i;
545

546
	    /* And if create_flag is TRUE, append the result of the
547
548
549
550
551
	     * subexpression match to the new line. */
	    if (create_flag) {
		strncpy(string, current->data + current_x +
			regmatches[num].rm_so, i);
		string += i;
552
553
	    }
	}
554
555
556
    }

    if (create_flag)
Chris Allegretta's avatar
Chris Allegretta committed
557
	*string = '\0';
558
559
560

    return new_size;
}
561
#endif
562

563
char *replace_line(const char *needle)
564
{
565
    char *copy;
566
567
568
    int new_line_size;
    int search_match_count;

569
    /* Calculate the size of the new line. */
570
#ifdef HAVE_REGEX_H
571
    if (ISSET(USE_REGEXP)) {
572
	search_match_count = regmatches[0].rm_eo - regmatches[0].rm_so;
573
	new_line_size = replace_regexp(NULL, 0);
574
    } else {
575
#endif
576
577
578
579
	search_match_count = strlen(needle);
	new_line_size = strlen(current->data) - search_match_count +
	    strlen(answer) + 1;
#ifdef HAVE_REGEX_H
580
    }
581
#endif
582

583
    /* Create the buffer. */
584
    copy = charalloc(new_line_size);
585

586
    /* The head of the original line. */
587
588
    strncpy(copy, current->data, current_x);

589
    /* The replacement text. */
590
#ifdef HAVE_REGEX_H
591
592
    if (ISSET(USE_REGEXP))
	replace_regexp(copy + current_x, TRUE);
593
    else
594
#endif
595
	strcpy(copy + current_x, answer);
596

597
598
599
    /* The tail of the original line. */
    assert(current_x + search_match_count <= strlen(current->data));
    strcat(copy, current->data + current_x + search_match_count);
600
601

    return copy;
Chris Allegretta's avatar
Chris Allegretta committed
602
603
}

604
/* Step through each replace word and prompt user before replacing.
605
606
607
 * Parameters real_current and real_current_x are needed in order to
 * allow the cursor position to be updated when a word before the cursor
 * is replaced by a shorter word.
608
609
610
 *
 * needle is the string to seek.  We replace it with answer.  Return -1
 * if needle isn't found, else the number of replacements performed. */
611
612
int do_replace_loop(const char *needle, filestruct *real_current, size_t
	*real_current_x, bool wholewords)
Chris Allegretta's avatar
Chris Allegretta committed
613
{
614
    int numreplaced = -1;
615
616
    size_t old_pww = placewewant, current_x_save = *real_current_x;
    const filestruct *current_save = real_current;
617
    bool replaceall = FALSE;
618
#ifdef HAVE_REGEX_H
619
    /* The starting-line match and bol/eol regex flags. */
620
    bool begin_line = FALSE, bol_or_eol = FALSE;
621
#endif
622
#ifndef NANO_SMALL
623
    bool old_mark_set = ISSET(MARK_ISSET);
624
625
    const filestruct *top, *bot;
    size_t top_x, bot_x;
Chris Allegretta's avatar
Chris Allegretta committed
626

627
    if (old_mark_set) {
628
	/* Save the locations where the mark begins and ends. */
629
630
631
632
633
	filestruct *old_current = current;
	size_t old_current_x = current_x;

	current = real_current;
	current_x = *real_current_x;
634
	mark_order(&top, &top_x, &bot, &bot_x);
635
636
	current = old_current;
	current_x = old_current_x;
637

638
639
640
	UNSET(MARK_ISSET);
	edit_refresh();
    }
641
#endif
642

643
    while (findnextstr(TRUE, wholewords,
644
#ifdef HAVE_REGEX_H
645
646
647
648
649
	/* We should find a bol and/or eol regex only once per line.  If
	 * the bol_or_eol flag is set, it means that the last search
	 * found one on the beginning line, so we should skip over the
	 * beginning line when doing this search. */
	bol_or_eol
650
#else
651
	FALSE
652
#endif
653
	, current_save, current_x_save, needle)) {
654
655

	int i = 0;
656
657
658
659
660
661
662
663
664
665
666
	size_t match_len =
#ifdef HAVE_REGEX_H
		ISSET(USE_REGEXP) ?
		regmatches[0].rm_eo - regmatches[0].rm_so :
#endif
		strlen(needle);

#ifndef NANO_SMALL
	/* If we've found a match outside the marked text, skip over it
	 * and search for another one. */
	if (old_mark_set) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
667
668
669
670
	    if (current->lineno < top->lineno || current->lineno >
		bot->lineno || (current == top && current_x < top_x) ||
		(current == bot && (current_x > bot_x || current_x +
		match_len > bot_x)))
671
672
673
		continue;
	}
#endif
674
675

#ifdef HAVE_REGEX_H
676
	/* If the bol_or_eol flag is set, we've found a match on the
677
678
	 * beginning line already, and we're still on the beginning line
	 * after the search, it means that we've wrapped around, so
679
	 * we're done. */
680
681
682
683
684
	if (bol_or_eol && begin_line && current == real_current)
	    break;
	/* Otherwise, set the begin_line flag if we've found a match on
	 * the beginning line, reset the bol_or_eol flag, and
	 * continue. */
685
	else {
686
	    if (current == real_current)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
687
688
		begin_line = TRUE;
	    bol_or_eol = FALSE;
689
690
	}
#endif
Chris Allegretta's avatar
Chris Allegretta committed
691

692
693
	if (!replaceall) {
	    placewewant = xplustabs();
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
694
	    edit_redraw(current_save, old_pww);
695
696
	    old_pww = placewewant;
	}
Chris Allegretta's avatar
Chris Allegretta committed
697

698
699
700
	/* Record for the return value that we found the search string. */
	if (numreplaced == -1)
	    numreplaced = 0;
701

702
	if (!replaceall) {
703
704
705
706
707
708
	    char *exp_word;
	    size_t xpt = xplustabs();

	    exp_word = display_string(current->data, xpt,
		strnlenpt(current->data, match_len + current_x) - xpt);

709
	    curs_set(0);
710
	    do_replace_highlight(TRUE, exp_word);
711

712
	    i = do_yesno(TRUE, _("Replace this instance?"));
Chris Allegretta's avatar
Chris Allegretta committed
713

714
715
	    do_replace_highlight(FALSE, exp_word);
	    free(exp_word);
716
	    curs_set(1);
717

718
	    if (i == -1)	/* We canceled the replace. */
719
		break;
720
721
	}

722
#ifdef HAVE_REGEX_H
723
	/* Set the bol_or_eol flag if we're doing a bol and/or eol regex
724
	 * replace ("^", "$", or "^$"). */
725
726
	if (ISSET(USE_REGEXP) && regexp_bol_or_eol(&search_regexp,
		needle))
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
727
	    bol_or_eol = TRUE;
728
729
#endif

730
	if (i > 0 || replaceall) {	/* Yes, replace it!!!! */
731
	    char *copy;
732
	    ssize_t length_change;
733

734
	    if (i == 2)
735
		replaceall = TRUE;
Chris Allegretta's avatar
Chris Allegretta committed
736

737
	    copy = replace_line(needle);
Chris Allegretta's avatar
Chris Allegretta committed
738

739
	    length_change = strlen(copy) - strlen(current->data);
Chris Allegretta's avatar
Chris Allegretta committed
740

741
742
743
744
745
746
747
748
#ifndef NANO_SMALL
	    if (current == mark_beginbuf && mark_beginx > current_x) {
		if (mark_beginx < current_x + match_len)
		    mark_beginx = current_x;
		else
		    mark_beginx += length_change;
	    }
#endif
Chris Allegretta's avatar
Chris Allegretta committed
749

750
	    assert(0 <= match_len + length_change);
751
752
753
754
	    if (current == real_current && current_x <= *real_current_x) {
		if (*real_current_x < current_x + match_len)
		    *real_current_x = current_x + match_len;
		*real_current_x += length_change;
755
	    }
756

757
	    /* Set the cursor at the last character of the replacement
758
759
	     * text, so searching will resume after the replacement
	     * text.  Note that current_x might be set to -1 here. */
760
#ifndef NANO_SMALL
761
	    if (!ISSET(REVERSE_SEARCH))
762
763
#endif
		current_x += match_len + length_change - 1;
764

765
	    /* Cleanup. */
766
767
768
	    totsize += length_change;
	    free(current->data);
	    current->data = copy;
769

770
771
772
773
774
775
776
777
778
	    if (!replaceall) {
#ifdef ENABLE_COLOR
		if (ISSET(COLOR_SYNTAX))
		    edit_refresh();
		else
#endif
		    update_line(current, current_x);
	    }

Chris Allegretta's avatar
Chris Allegretta committed
779
780
	    set_modified();
	    numreplaced++;
781
	}
782
783
784
785
786
787
788
789
790
791
792
793
794

	/* Save the locations where the mark begins and ends again,
	 * since they may have changed. */
	if (old_mark_set) {
	    filestruct *old_current = current;
	    size_t old_current_x = current_x;

	    current = real_current;
	    current_x = *real_current_x;
	    mark_order(&top, &top_x, &bot, &bot_x);
	    current = old_current;
	    current_x = old_current_x;
	}
Chris Allegretta's avatar
Chris Allegretta committed
795
796
    }

Chris Allegretta's avatar
Chris Allegretta committed
797
798
799
800
    /* If text has been added to the magicline, make a new magicline. */
    if (filebot->data[0] != '\0')
	new_magicline();

801
#ifndef NANO_SMALL
802
    if (old_mark_set)
803
804
805
	SET(MARK_ISSET);
#endif

Chris Allegretta's avatar
Chris Allegretta committed
806
807
808
    return numreplaced;
}

Chris Allegretta's avatar
Chris Allegretta committed
809
/* Replace a string. */
810
void do_replace(void)
Chris Allegretta's avatar
Chris Allegretta committed
811
{
812
813
814
    int i, numreplaced;
    filestruct *edittop_save, *begin;
    size_t beginx;
Chris Allegretta's avatar
Chris Allegretta committed
815

Chris Allegretta's avatar
Chris Allegretta committed
816
817
818
    if (ISSET(VIEW_MODE)) {
	print_view_warning();
	replace_abort();
819
	return;
Chris Allegretta's avatar
Chris Allegretta committed
820
821
    }

822
    i = search_init(TRUE, FALSE);
823
824
    if (i == -1) {		/* Cancel, Go to Line, blank search
				 * string, or regcomp() failed. */
Chris Allegretta's avatar
Chris Allegretta committed
825
	replace_abort();
826
	return;
827
    } else if (i == -2) {	/* No Replace. */
Chris Allegretta's avatar
Chris Allegretta committed
828
	do_search();
829
	return;
830
831
832
833
834
    } else if (i == 1)		/* Case Sensitive, Backwards, or Regexp
				 * search toggle. */
	do_replace();

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

837
838
839
    /* If answer is not "", add answer to the search history list and
     * copy answer into last_search. */
    if (answer[0] != '\0') {
840
#ifndef NANO_SMALL
841
	update_history(&search_history, answer);
842
#endif
Chris Allegretta's avatar
Chris Allegretta committed
843
	last_search = mallocstrcpy(last_search, answer);
844
    }
Chris Allegretta's avatar
Chris Allegretta committed
845

846
#ifndef NANO_SMALL
847
848
    replace_history.current = (historytype *)&replace_history.next;
    last_replace = mallocstrcpy(last_replace, "");
849
#endif
850

851
    i = statusq(FALSE, replace_list_2, last_replace,
852
#ifndef NANO_SMALL
853
	&replace_history,
854
#endif
855
	_("Replace with"));
856

857
#ifndef NANO_SMALL
858
859
860
    /* Add this replace string to the replace history list.  i == 0
     * means that the string is not "". */
    if (i == 0)
861
	update_history(&replace_history, answer);
862
863
864
865
866
867
#endif

    if (i != 0 && i != -2) {
	if (i == -1) {		/* Cancel. */
	    if (last_replace[0] != '\0')
		answer = mallocstrcpy(answer, last_replace);
868
	    statusbar(_("Cancelled"));
869
870
	}
	replace_abort();
871
	return;
872
873
874
    }

    last_replace = mallocstrcpy(last_replace, answer);
Chris Allegretta's avatar
Chris Allegretta committed
875

876
    /* Save where we are. */
Chris Allegretta's avatar
Chris Allegretta committed
877
    begin = current;
878
    beginx = current_x;
879
880
    edittop_save = edittop;
    search_last_line = FALSE;
Chris Allegretta's avatar
Chris Allegretta committed
881

882
    numreplaced = do_replace_loop(last_search, begin, &beginx, FALSE);
Chris Allegretta's avatar
Chris Allegretta committed
883

884
    /* Restore where we were. */
885
    edittop = edittop_save;
Chris Allegretta's avatar
Chris Allegretta committed
886
    current = begin;
887
    current_x = beginx;
Chris Allegretta's avatar
Chris Allegretta committed
888
    renumber_all();
889
    edit_refresh();
Chris Allegretta's avatar
Chris Allegretta committed
890
891

    if (numreplaced >= 0)
892
	statusbar(P_("Replaced %d occurrence", "Replaced %d occurrences",
Chris Allegretta's avatar
Chris Allegretta committed
893
894
		numreplaced), numreplaced);

Chris Allegretta's avatar
Chris Allegretta committed
895
896
897
    replace_abort();
}

898
void do_gotoline(int line, bool save_pos)
Chris Allegretta's avatar
Chris Allegretta committed
899
{
900
    if (line <= 0) {		/* Ask for it. */
901
	char *ans = mallocstrcpy(NULL, answer);
902
	int i = statusq(FALSE, gotoline_list, line < 0 ? ans : "",
Chris Allegretta's avatar
Chris Allegretta committed
903
#ifndef NANO_SMALL
904
		NULL,
Chris Allegretta's avatar
Chris Allegretta committed
905
#endif
906
907
908
		_("Enter line number"));

	free(ans);
Chris Allegretta's avatar
Chris Allegretta committed
909
910

	/* Cancel, or Enter with blank string. */
911
	if (i < 0) {
912
	    statusbar(_("Cancelled"));
913
	    display_main_list();
914
915
916
	    return;
	}

917
	if (i == NANO_TOOTHERWHEREIS_KEY) {
918
919
920
	    /* Keep answer up on the statusbar. */
	    search_init(TRUE, TRUE);

921
	    do_search();
922
	    return;
Chris Allegretta's avatar
Chris Allegretta committed
923
	}
924

925
926
	/* Do a bounds check.  Display a warning on an out-of-bounds
	 * line number only if we hit Enter at the statusbar prompt. */
927
	if (!parse_num(answer, &line) || line < 0) {
928
929
	    if (i == 0)
		statusbar(_("Come on, be reasonable"));
Chris Allegretta's avatar
Chris Allegretta committed
930
	    display_main_list();
931
	    return;
Chris Allegretta's avatar
Chris Allegretta committed
932
933
934
	}
    }

935
936
937
938
939
940
941
942
943
    if (current->lineno > line) {
	for (; current->prev != NULL && current->lineno > line;
		current = current->prev)
	    ;
    } else {
	for (; current->next != NULL && current->lineno < line;
		current = current->next)
	    ;
    }
Chris Allegretta's avatar
Chris Allegretta committed
944

945
    current_x = 0;
946

947
    /* If save_pos is TRUE, don't change the cursor position when
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
948
     * updating the edit window. */
949
    edit_update(save_pos ? NONE : CENTER);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
950

951
    placewewant = 0;
Chris Allegretta's avatar
Chris Allegretta committed
952
    display_main_list();
Chris Allegretta's avatar
Chris Allegretta committed
953
954
}

955
void do_gotoline_void(void)
Chris Allegretta's avatar
Chris Allegretta committed
956
{
957
    do_gotoline(0, FALSE);
Chris Allegretta's avatar
Chris Allegretta committed
958
}
959

960
#if defined(ENABLE_MULTIBUFFER) || !defined(DISABLE_SPELLER)
961
void do_gotopos(int line, int pos_x, int pos_y, size_t pos_pww)
962
{
963
964
    /* Since do_gotoline() resets the x-coordinate but not the
     * y-coordinate, set the coordinates up this way. */
965
    current_y = pos_y;
966
    do_gotoline(line, TRUE);
967

968
969
970
971
    /* Make sure that the x-coordinate is sane here. */
    current_x = strlen(current->data);
    if (pos_x < current_x)
	current_x = pos_x;
972

973
    /* Set the rest of the coordinates up. */
974
    placewewant = pos_pww;
975
976
977
    update_line(current, pos_x);
}
#endif
978
979

#if !defined(NANO_SMALL) && defined(HAVE_REGEX_H)
980
void do_find_bracket(void)
981
982
{
    char ch_under_cursor, wanted_ch;
983
    const char *pos, *brackets = "([{<>}])";
984
    char regexp_pat[] = "[  ]";
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
985
    size_t current_x_save, old_pww;
986
    int count = 1;
987
    long flags_save;
988
989
990
    filestruct *current_save;

    ch_under_cursor = current->data[current_x];
991

992
993
    pos = strchr(brackets, ch_under_cursor);
    if (ch_under_cursor == '\0' || pos == NULL) {
994
	statusbar(_("Not a bracket"));
995
	return;
996
997
    }

998
999
    assert(strlen(brackets) % 2 == 0);
    wanted_ch = brackets[(strlen(brackets) - 1) - (pos - brackets)];
1000
1001

    current_save = current;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1002
1003
    current_x_save = current_x;
    old_pww = placewewant;
1004
    flags_save = flags;
1005
1006
    SET(USE_REGEXP);

1007
1008
    /* Apparent near redundancy with regexp_pat[] here is needed.
     * "[][]" works, "[[]]" doesn't. */
1009

1010
1011
    if (pos < brackets + (strlen(brackets) / 2)) {
	/* On a left bracket. */
1012
1013
1014
	regexp_pat[1] = wanted_ch;
	regexp_pat[2] = ch_under_cursor;
	UNSET(REVERSE_SEARCH);
1015
1016
    } else {
	/* On a right bracket. */
1017
1018
1019
1020
1021
1022
	regexp_pat[1] = ch_under_cursor;
	regexp_pat[2] = wanted_ch;
	SET(REVERSE_SEARCH);
    }

    regexp_init(regexp_pat);
1023
    /* We constructed regexp_pat to be a valid expression. */
1024
    assert(regexp_compiled);
1025

1026
    search_last_line = FALSE;
1027
    while (TRUE) {
1028
1029
	if (findnextstr(FALSE, FALSE, FALSE, current, current_x,
		regexp_pat)) {
1030
	    /* Found identical bracket. */
Chris Allegretta's avatar
Chris Allegretta committed
1031
	    if (current->data[current_x] == ch_under_cursor)
1032
		count++;
1033
1034
1035
	    /* Found complementary bracket. */
	    else if (--count == 0) {
		placewewant = xplustabs();
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1036
		edit_redraw(current_save, old_pww);
1037
		break;
1038
	    }
Chris Allegretta's avatar
Chris Allegretta committed
1039
	} else {
1040
	    /* Didn't find either a left or right bracket. */
1041
1042
	    statusbar(_("No matching bracket"));
	    current = current_save;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1043
	    current_x = current_x_save;
Chris Allegretta's avatar
Chris Allegretta committed
1044
	    update_line(current, current_x);
1045
1046
1047
1048
	    break;
	}
    }

1049
    regexp_cleanup();
1050
    flags = flags_save;
1051
1052
}
#endif
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077

#ifndef NANO_SMALL
/*
 * search and replace history list support functions
 */

/* initialize search and replace history lists */
void history_init(void)
{
    search_history.next = (historytype *)&search_history.prev;
    search_history.prev = NULL;
    search_history.tail = (historytype *)&search_history.next;
    search_history.current = search_history.next;
    search_history.count = 0;
    search_history.len = 0;

    replace_history.next = (historytype *)&replace_history.prev;
    replace_history.prev = NULL;
    replace_history.tail = (historytype *)&replace_history.next;
    replace_history.current = replace_history.next;
    replace_history.count = 0;
    replace_history.len = 0;
}

/* find first node containing string *s in history list *h */
1078
historytype *find_node(historytype *h, const char *s)
1079
{
Chris Allegretta's avatar
Chris Allegretta committed
1080
    for (; h->next != NULL; h = h->next)
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
	if (strcmp(s, h->data) == 0)
	    return h;
    return NULL;
}

/* remove node *r */
void remove_node(historytype *r)
{
    r->prev->next = r->next;
    r->next->prev = r->prev;
    free(r->data);
    free(r);
}

/* add a node after node *h */
void insert_node(historytype *h, const char *s)
{
    historytype *a;

David Lawrence Ramsey's avatar
   
David Lawrence Ramsey committed
1100
    a = (historytype *)nmalloc(sizeof(historytype));
1101
    a->next = h->next;
1102
    a->prev = h;
1103
1104
1105
1106
1107
1108
    h->next->prev = a;
    h->next = a;
    a->data = mallocstrcpy(NULL, s);
}

/* update history list */
1109
void update_history(historyheadtype *h, const char *s)
1110
1111
1112
{
    historytype *p;

Chris Allegretta's avatar
Chris Allegretta committed
1113
1114
1115
    if ((p = find_node(h->next, s)) != NULL) {
	if (p == h->next)		/* catch delete and re-insert of
					   same string in 1st node */
1116
	    goto up_hs;
Chris Allegretta's avatar
Chris Allegretta committed
1117
	remove_node(p);			/* delete identical older string */
1118
1119
1120
1121
1122
1123
1124
1125
	h->count--;
    }
    if (h->count == MAX_SEARCH_HISTORY) {	/* list 'full', delete oldest */
	remove_node(h->tail);
	h->count--;
    }
    insert_node((historytype *)h, s);
    h->count++;
1126
    SET(HISTORY_CHANGED);
Chris Allegretta's avatar
Chris Allegretta committed
1127
  up_hs:
1128
1129
1130
1131
1132
1133
    h->current = h->next;
}

/* return a pointer to either the next older history or NULL if no more */
char *get_history_older(historyheadtype *h)
{
Chris Allegretta's avatar
Chris Allegretta committed
1134
    if (h->current->next != NULL) {	/* any older entries? */
1135
1136
1137
1138
1139
1140
1141
1142
	h->current = h->current->next;	/* yes */
	return h->current->data;	/* return it */
    }
    return NULL;			/* end of list */
}

char *get_history_newer(historyheadtype *h)
{
Chris Allegretta's avatar
Chris Allegretta committed
1143
    if (h->current->prev != NULL) {
1144
	h->current = h->current->prev;
Chris Allegretta's avatar
Chris Allegretta committed
1145
	if (h->current->prev != NULL)
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
	    return h->current->data;
    }
    return NULL;
}

/* get a completion */
char *get_history_completion(historyheadtype *h, char *s)
{
    historytype *p;

Chris Allegretta's avatar
Chris Allegretta committed
1156
1157
    for (p = h->current->next; p->next != NULL; p = p->next) {
	if (strncmp(s, p->data, h->len) == 0 && strlen(p->data) != h->len) {
1158
1159
1160
1161
1162
1163
1164
1165
1166
	    h->current = p;
	    return p->data;
	}
    }
    h->current = (historytype*)h;
    null_at(&s, h->len);
    return s;
}

1167
#ifdef DEBUG
1168
1169
1170
/* free a history list */
void free_history(historyheadtype *h)
{
1171
    historytype *p;
1172

1173
    for (p = h->next; p->next != NULL; p = p->next)
1174
1175
	remove_node(p);
}
1176
#endif
1177
1178
1179

/* end of history support functions */
#endif /* !NANO_SMALL */