browser.c 24.2 KB
Newer Older
1
/**************************************************************************
2
 *   browser.c  --  This file is part of GNU nano.                        *
3
 *                                                                        *
4
 *   Copyright (C) 2001-2011, 2013-2017 Free Software Foundation, Inc.    *
5
 *   Copyright (C) 2015, 2016 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.                               *
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.                 *
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/.  *
19
20
21
 *                                                                        *
 **************************************************************************/

22
#include "proto.h"
23

24
#include <errno.h>
25
#include <stdint.h>
26
27
28
#include <string.h>
#include <unistd.h>

29
#ifdef ENABLE_BROWSER
30

31
static char **filelist = NULL;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
32
	/* The list of files to display in the file browser. */
33
34
35
static size_t filelist_len = 0;
	/* The number of files in the list. */
static int width = 0;
36
	/* The number of files that we can display per screen row. */
37
38
static int longest = 0;
	/* The number of columns in the longest filename in the list. */
39
static size_t selected = 0;
40
	/* The currently selected filename in the list; zero-based. */
41

42
/* Our main file browser function.  path is the tilde-expanded path we
43
 * start browsing from. */
44
char *do_browser(char *path)
45
{
46
    char *retval = NULL;
47
    int kbinput;
48
49
50
    char *present_name = NULL;
	/* The name of the currently selected file, or of the directory we
	 * were in before backing up to "..". */
51
    size_t old_selected;
52
	/* The number of the selected file before the current selected file. */
53
54
    functionptrtype func;
	/* The function of the key the user typed in. */
55
56
    DIR *dir;
	/* The directory whose contents we are showing. */
57

58
    /* Don't show a cursor in the file list. */
59
60
    curs_set(0);

61
  read_directory_contents:
62
	/* We come here when we refresh or select a new directory. */
63

64
    path = free_and_assign(path, get_full_path(path));
65

66
    if (path != NULL)
67
	dir = opendir(path);
68

69
    if (path == NULL || dir == NULL) {
70
	statusline(ALERT, _("Cannot open directory: %s"), strerror(errno));
71
72
73
74
75
76
77
78
79
80
81
	/* If we don't have a file list yet, there is nothing to show. */
	if (filelist == NULL) {
	    napms(1200);
	    lastmessage = HUSH;
	    free(path);
	    free(present_name);
	    return NULL;
	}
	path = mallocstrcpy(path, present_path);
	present_name = mallocstrcpy(present_name, filelist[selected]);
    }
82

83
    assert(path != NULL && path[strlen(path) - 1] == '/');
84

85
86
87
88
89
90
    if (dir != NULL) {
	/* Get the file list, and set longest and width in the process. */
	read_the_list(path, dir);
	closedir(dir);
	dir = NULL;
    }
91

92
93
94
    /* If given, reselect the present_name and then discard it. */
    if (present_name != NULL) {
	browser_select_dirname(present_name);
95

96
97
	free(present_name);
	present_name = NULL;
98
99
100
    /* Otherwise, select the first file or directory in the list. */
    } else
	selected = 0;
101

102
103
    old_selected = (size_t)-1;

104
105
    present_path = mallocstrcpy(present_path, path);

106
107
    titlebar(path);

108
    while (TRUE) {
109
110
	/* Make sure that the cursor is off. */
	curs_set(0);
111
	lastmessage = HUSH;
112

113
114
	bottombars(MBROWSER);

115
116
117
	/* Display (or redisplay) the file list if the list itself or
	 * the selected file has changed. */
	if (old_selected != selected)
118
	    browser_refresh();
119

120
121
	old_selected = selected;

122
	kbinput = get_kbinput(edit);
123

124
#ifdef ENABLE_MOUSE
125
	if (kbinput == KEY_MOUSE) {
126
127
	    int mouse_x, mouse_y;

128
	    /* We can click on the edit window to select a filename. */
129
	    if (get_mouseinput(&mouse_x, &mouse_y, TRUE) == 0 &&
130
			wmouse_trafo(edit, &mouse_y, &mouse_x, FALSE)) {
131
132
		/* longest is the width of each column.  There
		 * are two spaces between each column. */
133
		selected = selected - selected % (editwinrows * width) +
134
				(mouse_y * width) + (mouse_x / (longest + 2));
135

136
		/* If they clicked beyond the end of a row,
137
		 * select the last filename in that row. */
138
139
140
		if (mouse_x > width * (longest + 2))
		    selected--;

141
		/* If we're beyond the list, select the last filename. */
142
143
144
		if (selected > filelist_len - 1)
		    selected = filelist_len - 1;

145
146
		/* If we selected the same filename as last time, fake a
		 * press of the Enter key so that the file is read in. */
147
		if (old_selected == selected)
148
		    unget_kbinput(KEY_ENTER, FALSE);
149
	    }
150
151

	    continue;
152
	}
153
#endif /* ENABLE_MOUSE */
154

155
	func = parse_browser_input(&kbinput);
156

157
	if (func == total_refresh) {
158
	    total_redraw();
159
#ifndef NANO_TINY
160
	    /* Simulate a window resize to force a directory reread. */
161
	    kbinput = KEY_WINCH;
162
#endif
163
	} else if (func == do_help_void) {
164
#ifdef ENABLE_HELP
165
	    do_help_void();
166
#ifndef NANO_TINY
167
	    /* The window dimensions might have changed, so act as if. */
168
	    kbinput = KEY_WINCH;
169
#endif
170
#else
171
	    say_there_is_no_help();
172
#endif
173
	} else if (func == do_search) {
174
	    do_filesearch();
175
	} else if (func == do_research) {
176
	    do_fileresearch(TRUE);
177
178
179
#ifndef NANO_TINY
	} else if (func == do_findprevious) {
	    do_fileresearch(FALSE);
180
181
	} else if (func == do_findnext) {
	    do_fileresearch(TRUE);
182
#endif
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
	} else if (func == do_left) {
	    if (selected > 0)
		selected--;
	} else if (func == do_right) {
	    if (selected < filelist_len - 1)
		selected++;
	} else if (func == do_prev_word_void) {
	    selected -= (selected % width);
	} else if (func == do_next_word_void) {
	    selected += width - 1 - (selected % width);
	    if (selected >= filelist_len)
		selected = filelist_len - 1;
	} else if (func == do_up_void) {
	    if (selected >= width)
		selected -= width;
	} else if (func == do_down_void) {
	    if (selected + width <= filelist_len - 1)
		selected += width;
201
202
203
204
205
206
207
208
209
210
211
	} else if (func == do_prev_block) {
	    selected = ((selected / (editwinrows * width)) *
				editwinrows * width) + selected % width;
	} else if (func == do_next_block) {
	    selected = ((selected / (editwinrows * width)) *
				editwinrows * width) + selected % width +
				editwinrows * width - width;
	    if (selected >= filelist_len)
		selected = (filelist_len / width) * width + selected % width;
	    if (selected >= filelist_len)
		selected -= width;
212
	} else if (func == do_page_up) {
213
	    if (selected < width)
214
		selected = 0;
215
216
217
218
	    else if (selected < editwinrows * width)
		selected = selected % width;
	    else
		selected -= editwinrows * width;
219
	} else if (func == do_page_down) {
220
	    if (selected + width >= filelist_len - 1)
221
		selected = filelist_len - 1;
222
223
224
225
226
	    else if (selected + editwinrows * width >= filelist_len)
		selected = (selected + editwinrows * width - filelist_len) %
				width +	filelist_len - width;
	    else
		selected += editwinrows * width;
227
	} else if (func == do_first_file) {
228
	    selected = 0;
229
	} else if (func == do_last_file) {
230
	    selected = filelist_len - 1;
231
	} else if (func == goto_dir_void) {
232
	    /* Ask for the directory to go to. */
233
	    int i = do_prompt(TRUE, FALSE, MGOTODIR, NULL,
234
#ifndef DISABLE_HISTORIES
235
236
			NULL,
#endif
237
			/* TRANSLATORS: This is a prompt. */
238
			browser_refresh, _("Go To Directory"));
239

240
	    if (i < 0) {
241
242
243
244
		statusbar(_("Cancelled"));
		continue;
	    }

245
	    path = free_and_assign(path, real_dir_from_tilde(answer));
246

247
248
249
250
251
	    /* If the given path is relative, join it with the current path. */
	    if (*path != '/') {
		path = charealloc(path, strlen(present_path) +
						strlen(answer) + 1);
		sprintf(path, "%s%s", present_path, answer);
252
	    }
253
254

#ifndef DISABLE_OPERATINGDIR
255
	    if (outside_of_confinement(path, FALSE)) {
256
257
		/* TRANSLATORS: This refers to the confining effect of the
		 * option --operatingdir, not of --restricted. */
258
		statusline(ALERT, _("Can't go outside of %s"), operating_dir);
259
		path = mallocstrcpy(path, present_path);
260
261
		continue;
	    }
262
#endif
263
	    /* Snip any trailing slashes, so the name can be compared. */
264
265
	    while (strlen(path) > 1 && path[strlen(path) - 1] == '/')
		path[strlen(path) - 1] = '\0';
266

267
268
269
	    /* In case the specified directory cannot be entered, select it
	     * (if it is in the current list) so it will be highlighted. */
	    for (i = 0; i < filelist_len; i++)
270
		if (strcmp(filelist[i], path) == 0)
271
		    selected = i;
272

273
	    /* Try opening and reading the specified directory. */
274
	    goto read_directory_contents;
275
	} else if (func == do_enter) {
276
277
	    struct stat st;

278
	    /* It isn't possible to move up from the root directory. */
279
	    if (strcmp(filelist[selected], "/..") == 0) {
280
		statusline(ALERT, _("Can't move up a directory"));
281
282
		continue;
	    }
283
284

#ifndef DISABLE_OPERATINGDIR
285
286
287
	    /* Note: The selected file can be outside the operating
	     * directory if it's ".." or if it's a symlink to a
	     * directory outside the operating directory. */
288
	    if (outside_of_confinement(filelist[selected], FALSE)) {
289
		statusline(ALERT, _("Can't go outside of %s"), operating_dir);
290
291
		continue;
	    }
292
#endif
293
	    /* If for some reason the file is inaccessible, complain. */
294
	    if (stat(filelist[selected], &st) == -1) {
295
		statusline(ALERT, _("Error reading %s: %s"),
296
				filelist[selected], strerror(errno));
297
		continue;
298
299
	    }

300
	    /* If it isn't a directory, a file was selected -- we're done. */
301
302
	    if (!S_ISDIR(st.st_mode)) {
		retval = mallocstrcpy(NULL, filelist[selected]);
303
		break;
304
	    }
305

306
	    /* If we are moving up one level, remember where we came from, so
307
308
	     * this directory can be highlighted and easily reentered. */
	    if (strcmp(tail(filelist[selected]), "..") == 0)
309
		present_name = strip_last_component(filelist[selected]);
310

311
	    /* Try opening and reading the selected directory. */
312
	    path = mallocstrcpy(path, filelist[selected]);
313
	    goto read_directory_contents;
314
	} else if (func == do_exit) {
315
316
	    /* Exit from the file browser. */
	    break;
317
318
319
320
#ifndef NANO_TINY
	} else if (kbinput == KEY_WINCH) {
	    ;
#endif
321
322
	} else
	    unbound_key(kbinput);
323
324
325
326
327

#ifndef NANO_TINY
	/* If the window resized, refresh the file list. */
	if (kbinput == KEY_WINCH) {
	    /* Remember the selected file, to be able to reselect it. */
328
	    present_name = mallocstrcpy(NULL, filelist[selected]);
329
330
331
332
	    /* Reread the contents of the current directory. */
	    goto read_directory_contents;
	}
#endif
333
    }
334

335
336
337
    titlebar(NULL);
    edit_refresh();

338
339
340
341
342
    free(path);

    free_chararray(filelist, filelist_len);
    filelist = NULL;
    filelist_len = 0;
343
344
345
346

    return retval;
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
347
348
349
/* The file browser front end.  We check to see if inpath has a
 * directory in it.  If it does, we start do_browser() from there.
 * Otherwise, we start do_browser() from the current directory. */
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
char *do_browse_from(const char *inpath)
{
    struct stat st;
    char *path;
	/* This holds the tilde-expanded version of inpath. */

    path = real_dir_from_tilde(inpath);

    /* Perhaps path is a directory.  If so, we'll pass it to
     * do_browser().  Or perhaps path is a directory / a file.  If so,
     * we'll try stripping off the last path element and passing it to
     * do_browser().  Or perhaps path doesn't have a directory portion
     * at all.  If so, we'll just pass the current directory to
     * do_browser(). */
    if (stat(path, &st) == -1 || !S_ISDIR(st.st_mode)) {
365
	path = free_and_assign(path, strip_last_component(path));
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
366

367
	if (stat(path, &st) == -1 || !S_ISDIR(st.st_mode)) {
368
	    char * currentdir = charalloc(PATH_MAX + 1);
369

370
371
	    free(path);
	    path = getcwd(currentdir, PATH_MAX + 1);
372

373
	    if (path == NULL) {
374
		free(currentdir);
375
		statusline(MILD, _("The working directory has disappeared"));
376
377
378
		beep();
		napms(1200);
		return NULL;
379
	    }
380
381
382
383
384
385
	}
    }

#ifndef DISABLE_OPERATINGDIR
    /* If the resulting path isn't in the operating directory, use
     * the operating directory instead. */
386
    if (outside_of_confinement(path, FALSE))
387
	path = mallocstrcpy(path, operating_dir);
388
389
#endif

390
    return do_browser(path);
391
392
}

393
/* Set filelist to the list of files contained in the directory path,
394
 * set filelist_len to the number of files in that list, set longest to
395
 * the width in columns of the longest filename in that list (between 15
396
 * and COLS), and set width to the number of files that we can display
397
 * per screen row.  And sort the list too. */
398
void read_the_list(const char *path, DIR *dir)
399
400
{
    const struct dirent *nextdir;
401
    size_t i = 0, path_len = strlen(path);
402

403
    assert(path != NULL && path[strlen(path) - 1] == '/' && dir != NULL);
404
405
406

    longest = 0;

407
    /* Find the length of the longest filename in the current folder. */
408
    while ((nextdir = readdir(dir)) != NULL) {
409
	size_t name_len = strlenpt(nextdir->d_name);
410

411
412
	if (name_len > longest)
	    longest = name_len;
413
414

	i++;
415
416
    }

417
    /* Put 10 characters' worth of blank space between columns of filenames
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
418
     * in the list whenever possible, as Pico does. */
419
    longest += 10;
420

421
    /* If needed, make room for ".. (parent dir)". */
422
423
    if (longest < 15)
	longest = 15;
424
    /* Make sure we're not wider than the window. */
425
426
427
428
429
    if (longest > COLS)
	longest = COLS;

    rewinddir(dir);

430
    free_chararray(filelist, filelist_len);
431
432
433

    filelist_len = i;

434
435
436
437
438
439
440
    filelist = (char **)nmalloc(filelist_len * sizeof(char *));

    i = 0;

    while ((nextdir = readdir(dir)) != NULL && i < filelist_len) {
	/* Don't show the "." entry. */
	if (strcmp(nextdir->d_name, ".") == 0)
441
	    continue;
442
443
444

	filelist[i] = charalloc(path_len + strlen(nextdir->d_name) + 1);
	sprintf(filelist[i], "%s%s", path, nextdir->d_name);
445

446
447
448
449
450
451
452
	i++;
    }

    /* Maybe the number of files in the directory changed between the
     * first time we scanned and the second.  i is the actual length of
     * filelist, so record it. */
    filelist_len = i;
453

454
455
456
457
458
    assert(filelist != NULL);

    /* Sort the list of names. */
    qsort(filelist, filelist_len, sizeof(char *), diralphasort);

459
460
461
462
    /* Calculate how many files fit on a line -- feigning room for two
     * spaces beyond the right edge, and adding two spaces of padding
     * between columns. */
    width = (COLS + 2) / (longest + 2);
463
464
}

465
466
467
/* Return the function that is bound to the given key, accepting certain
 * plain characters too, for compatibility with Pico. */
functionptrtype parse_browser_input(int *kbinput)
468
{
469
    if (!meta_key) {
470
471
	switch (*kbinput) {
	    case ' ':
472
		return do_page_down;
473
	    case '-':
474
		return do_page_up;
475
	    case '?':
476
		return do_help_void;
477
478
	    case 'E':
	    case 'e':
479
480
481
482
	    case 'Q':
	    case 'q':
	    case 'X':
	    case 'x':
483
		return do_exit;
484
485
	    case 'G':
	    case 'g':
486
		return goto_dir_void;
487
488
	    case 'S':
	    case 's':
489
		return do_enter;
490
491
	    case 'W':
	    case 'w':
492
	    case '/':
493
		return do_search;
494
	    case 'N':
495
496
497
#ifndef NANO_TINY
		return do_findprevious;
#endif
498
499
	    case 'n':
		return do_research;
500
501
	}
    }
502
    return func_from_key(kbinput);
503
504
}

505
506
/* Set width to the number of files that we can display per screen row,
 * if necessary, and display the list of files. */
507
void browser_refresh(void)
508
{
509
    size_t i;
510
511
512
513
    int row = 0, col = 0;
	/* The current row and column while the list is getting displayed. */
    int the_row = 0, the_column = 0;
	/* The row and column of the selected item. */
Benno Schulenberg's avatar
Benno Schulenberg committed
514
    char *info;
515
	/* The additional information that we'll display about a file. */
516

517
    titlebar(present_path);
518
519
520
521
    blank_edit();

    wmove(edit, 0, 0);

522
    i = selected - selected % (editwinrows * width);
523

524
    for (; i < filelist_len && row < editwinrows; i++) {
525
	struct stat st;
Benno Schulenberg's avatar
Benno Schulenberg committed
526
	const char *thename = tail(filelist[i]);
527
		/* The filename we display, minus the path. */
Benno Schulenberg's avatar
Benno Schulenberg committed
528
	size_t namelen = strlenpt(thename);
529
		/* The length of the filename in columns. */
Benno Schulenberg's avatar
Benno Schulenberg committed
530
	size_t infolen;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
531
		/* The length of the file information in columns. */
Benno Schulenberg's avatar
Benno Schulenberg committed
532
	int infomaxlen = 7;
533
534
		/* The maximum length of the file information in columns:
		 * normally seven, but will be twelve for "(parent dir)". */
Benno Schulenberg's avatar
Benno Schulenberg committed
535
	bool dots = (COLS >= 15 && namelen >= longest - infomaxlen);
536
537
538
539
540
541
		/* Whether to put an ellipsis before the filename?  We don't
		 * waste space on dots when there are fewer than 15 columns. */
	char *disp = display_string(thename, dots ?
		namelen + infomaxlen + 4 - longest : 0, longest, FALSE);
		/* The filename (or a fragment of it) in displayable format.
		 * When a fragment, account for dots plus one space padding. */
542

543
544
545
	/* If this is the selected item, start its highlighting, and
	 * remember its location to be able to place the cursor on it. */
	if (i == selected) {
546
	    wattron(edit, interface_color_pair[SELECTED_TEXT]);
547
	    the_row = row;
548
549
	    the_column = col;
	}
550

551
	blank_row(edit, row, col, longest);
552

553
	/* If the name is too long, we display something like "...ename". */
554
	if (dots)
555
556
	    mvwaddstr(edit, row, col, "...");
	mvwaddstr(edit, row, dots ? col + 3 : col, disp);
557

558
559
560
561
	free(disp);

	col += longest;

562
563
564
	/* Show information about the file: "--" for symlinks (except when
	 * they point to a directory) and for files that have disappeared,
	 * "(dir)" for directories, and the file size for normal files. */
565
	if (lstat(filelist[i], &st) == -1 || S_ISLNK(st.st_mode)) {
566
	    if (stat(filelist[i], &st) == -1 || !S_ISDIR(st.st_mode))
Benno Schulenberg's avatar
Benno Schulenberg committed
567
		info = mallocstrcpy(NULL, "--");
568
	    else
569
		/* TRANSLATORS: Try to keep this at most 7 characters. */
Benno Schulenberg's avatar
Benno Schulenberg committed
570
		info = mallocstrcpy(NULL, _("(dir)"));
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
571
	} else if (S_ISDIR(st.st_mode)) {
Benno Schulenberg's avatar
Benno Schulenberg committed
572
	    if (strcmp(thename, "..") == 0) {
573
		/* TRANSLATORS: Try to keep this at most 12 characters. */
Benno Schulenberg's avatar
Benno Schulenberg committed
574
575
		info = mallocstrcpy(NULL, _("(parent dir)"));
		infomaxlen = 12;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
576
	    } else
Benno Schulenberg's avatar
Benno Schulenberg committed
577
		info = mallocstrcpy(NULL, _("(dir)"));
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
578
	} else {
579
	    off_t result = st.st_size;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
580
581
	    char modifier;

Benno Schulenberg's avatar
Benno Schulenberg committed
582
	    info = charalloc(infomaxlen + 1);
583

584
	    /* Massage the file size into a human-readable form. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
585
	    if (st.st_size < (1 << 10))
586
		modifier = ' ';  /* bytes */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
587
588
	    else if (st.st_size < (1 << 20)) {
		result >>= 10;
589
		modifier = 'K';  /* kilobytes */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
590
591
	    } else if (st.st_size < (1 << 30)) {
		result >>= 20;
592
		modifier = 'M';  /* megabytes */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
593
594
	    } else {
		result >>= 30;
595
		modifier = 'G';  /* gigabytes */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
596
597
	    }

598
	    /* Show the size if less than a terabyte, else show "(huge)". */
599
	    if (result < (1 << 10))
Benno Schulenberg's avatar
Benno Schulenberg committed
600
		sprintf(info, "%4ju %cB", (intmax_t)result, modifier);
601
602
603
	    else
		/* TRANSLATORS: Try to keep this at most 7 characters.
		 * If necessary, you can leave out the parentheses. */
Benno Schulenberg's avatar
Benno Schulenberg committed
604
		info = mallocstrcpy(info, _("(huge)"));
605
606
	}

Benno Schulenberg's avatar
Benno Schulenberg committed
607
608
609
	/* Make sure info takes up no more than infomaxlen columns. */
	infolen = strlenpt(info);
	if (infolen > infomaxlen) {
610
	    info[actual_x(info, infomaxlen)] = '\0';
Benno Schulenberg's avatar
Benno Schulenberg committed
611
	    infolen = infomaxlen;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
612
613
	}

614
	mvwaddstr(edit, row, col - infolen, info);
615

616
	/* If this is the selected item, finish its highlighting. */
617
	if (i == selected)
618
	    wattroff(edit, interface_color_pair[SELECTED_TEXT]);
619

Benno Schulenberg's avatar
Benno Schulenberg committed
620
	free(info);
621

622
623
624
	/* Add some space between the columns. */
	col += 2;

625
626
	/* If the next entry isn't going to fit on the current row,
	 * move to the next row. */
627
	if (col > COLS - longest) {
628
	    row++;
629
630
631
632
	    col = 0;
	}
    }

633
634
    /* If requested, put the cursor on the selected item and switch it on. */
    if (ISSET(SHOW_CURSOR)) {
635
	wmove(edit, the_row, the_column);
636
637
638
	curs_set(1);
    }

639
640
641
    wnoutrefresh(edit);
}

642
643
644
/* Look for needle.  If we find it, set selected to its location.
 * Note that needle must be an exact match for a file in the list. */
void browser_select_dirname(const char *needle)
645
{
646
    size_t looking_at = 0;
647

648
649
650
    for (; looking_at < filelist_len; looking_at++) {
	if (strcmp(filelist[looking_at], needle) == 0) {
	    selected = looking_at;
651
652
653
	    break;
	}
    }
654
655
656

    /* If the sought name isn't found, move the highlight so that the
     * changed selection will be noticed. */
657
    if (looking_at == filelist_len) {
658
	--selected;
659
660
661
662
663

	/* Make sure we stay within the available range. */
	if (selected >= filelist_len)
	    selected = filelist_len - 1;
    }
664
665
}

666
667
668
669
/* Set up the system variables for a filename search.  Return -1 or -2 if
 * the search should be canceled (due to Cancel or a blank search string),
 * return 0 when we have a string, and return a positive value when some
 * function was run. */
670
671
int filesearch_init(void)
{
672
    int input;
673
674
    char *buf;

675
    if (*last_search != '\0') {
676
677
678
	char *disp = display_string(last_search, 0, COLS / 3, FALSE);

	buf = charalloc(strlen(disp) + 7);
679
	/* We use (COLS / 3) here because we need to see more on the line. */
680
681
682
683
684
685
686
	sprintf(buf, " [%s%s]", disp,
		(strlenpt(last_search) > COLS / 3) ? "..." : "");
	free(disp);
    } else
	buf = mallocstrcpy(NULL, "");

    /* This is now one simple call.  It just does a lot. */
687
    input = do_prompt(FALSE, FALSE, MWHEREISFILE, NULL,
688
#ifndef DISABLE_HISTORIES
689
		&search_history,
690
#endif
691
		browser_refresh, "%s%s", _("Search"), buf);
692
693
694
695

    /* Release buf now that we don't need it anymore. */
    free(buf);

696
697
698
699
700
701
    /* If only Enter was pressed but we have a previous string, it's okay. */
    if (input == -2 && *last_search != '\0')
	return 0;

    /* Otherwise negative inputs are a bailout. */
    if (input < 0)
702
703
	statusbar(_("Cancelled"));

704
    return input;
705
706
}

707
708
709
/* Look for the given needle in the list of files.  If forwards is TRUE,
 * search forward in the list; otherwise, search backward. */
void findfile(const char *needle, bool forwards)
710
{
711
    size_t looking_at = selected;
712
	/* The location in the file list of the filename we're looking at. */
713
714
    const char *thename;
	/* The plain filename, without the path. */
715
716
717
718
719
720
    unsigned stash[sizeof(flags) / sizeof(flags[0])];
	/* A storage place for the current flag settings. */

    /* Save the settings of all flags. */
    memcpy(stash, flags, sizeof(flags));

721
    /* Search forward, case insensitive, and without regexes. */
722
723
724
    UNSET(BACKWARDS_SEARCH);
    UNSET(CASE_SENSITIVE);
    UNSET(USE_REGEXP);
725

726
727
    /* Step through each filename in the list until a match is found or
     * we've come back to the point where we started. */
728
    while (TRUE) {
729
730
731
732
733
734
735
736
737
738
	if (forwards) {
	    if (looking_at++ == filelist_len - 1) {
		looking_at = 0;
		statusbar(_("Search Wrapped"));
	    }
	} else {
	    if (looking_at-- == 0) {
		looking_at = filelist_len - 1;
		statusbar(_("Search Wrapped"));
	    }
739
740
	}

741
	/* Get the bare filename, without the path. */
Benno Schulenberg's avatar
Benno Schulenberg committed
742
	thename = tail(filelist[looking_at]);
743
744
745
746

	/* If the needle matches, we're done.  And if we're back at the file
	 * where we started, it is the only occurrence. */
	if (strstrwrapper(thename, needle, thename)) {
747
	    if (looking_at == selected)
748
		statusbar(_("This is the only occurrence"));
749
	    break;
750
751
752
753
754
755
756
	}

	/* If we're back at the beginning and didn't find any match... */
	if (looking_at == selected) {
	    not_found_msg(needle);
	    break;
	}
757
758
    }

759
760
761
    /* Restore the settings of all flags. */
    memcpy(flags, stash, sizeof(flags));

762
    /* Select the one we've found. */
763
    selected = looking_at;
764
765
766
767
768
}

/* Search for a filename. */
void do_filesearch(void)
{
769
770
    /* If the user cancelled or jumped to first or last file, don't search. */
    if (filesearch_init() != 0)
771
772
773
	return;

    /* If answer is now "", copy last_search into answer. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
774
    if (*answer == '\0')
775
776
777
778
	answer = mallocstrcpy(answer, last_search);
    else
	last_search = mallocstrcpy(last_search, answer);

779
#ifndef DISABLE_HISTORIES
780
781
    /* If answer is not empty, add the string to the search history list. */
    if (*answer != '\0')
782
783
784
	update_history(&search_history, answer);
#endif

785
    findfile(answer, TRUE);
786
787
}

788
789
790
/* Search again without prompting for the last given search string,
 * either forwards or backwards. */
void do_fileresearch(bool forwards)
791
{
792
    if (*last_search == '\0')
793
794
	statusbar(_("No current search pattern"));
    else
795
	findfile(last_search, forwards);
796
797
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
798
/* Select the first file in the list. */
799
800
801
802
803
void do_first_file(void)
{
    selected = 0;
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
804
/* Select the last file in the list. */
805
806
807
808
809
void do_last_file(void)
{
    selected = filelist_len - 1;
}

810
811
812
/* Strip one element from the end of path, and return the stripped path.
 * The returned string is dynamically allocated, and should be freed. */
char *strip_last_component(const char *path)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
813
{
814
815
    char *copy = mallocstrcpy(NULL, path);
    char *last_slash = strrchr(copy, '/');
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
816

817
818
    if (last_slash != NULL)
	*last_slash = '\0';
819

820
    return copy;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
821
822
}

823
#endif /* ENABLE_BROWSER */