browser.c 23.9 KB
Newer Older
1
2
3
/**************************************************************************
 *   browser.c                                                            *
 *                                                                        *
4
 *   Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,  *
5
6
 *   2010, 2011, 2013, 2014, 2015 Free Software Foundation, Inc.          *
 *                                                                        *
7
8
 *   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 *
9
 *   the Free Software Foundation; either version 3, or (at your option)  *
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 *   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., 51 Franklin St, Fifth Floor, Boston, MA            *
 *   02110-1301, USA.                                                     *
 *                                                                        *
 **************************************************************************/

24
#include "proto.h"
25

26
#include <stdint.h>
27
28
29
30
31
32
33
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

#ifndef DISABLE_BROWSER

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

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

59
    /* Don't show a cursor in the file list. */
60
61
    curs_set(0);
    blank_statusbar();
62
    bottombars(MBROWSER);
63

64
  read_directory_contents:
65
	/* We come here when we refresh or select a new directory. */
66

67
    /* Start with no key pressed. */
68
69
    kbinput = ERR;

70
71
    path = mallocstrassn(path, get_full_path(path));

72
    /* Save the current path in order to be used later. */
73
    present_path = mallocstrcpy(present_path, path);
74

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

77
    /* Get the file list, and set longest and width in the process. */
78
    browser_init(path, dir);
79
80
81

    assert(filelist != NULL);

82
    /* Sort the file list. */
83
    qsort(filelist, filelist_len, sizeof(char *), diralphasort);
84

85
86
87
    /* If given, reselect the present_name and then discard it. */
    if (present_name != NULL) {
	browser_select_dirname(present_name);
88

89
90
	free(present_name);
	present_name = NULL;
91
92
93
    /* Otherwise, select the first file or directory in the list. */
    } else
	selected = 0;
94

95
96
    old_selected = (size_t)-1;

97
98
    titlebar(path);

99
    while (TRUE) {
100
101
	struct stat st;
	int i;
102
	char *new_path;
103
104
		/* The path we switch to at the "Go to Directory"
		 * prompt. */
105

106
107
	/* Make sure that the cursor is off. */
	curs_set(0);
108
	lastmessage = HUSH;
109

110
111
#ifndef NANO_TINY
	if (kbinput == KEY_WINCH) {
112
113
	    /* Remember the selected file, to be able to reselect it. */
	    present_name = strdup(filelist[selected]);
114

115
116
117
118
	    /* Reopen the current directory. */
	    dir = opendir(path);
	    if (dir != NULL)
		goto read_directory_contents;
119

120
	    statusline(ALERT, _("Error reading %s: %s"), path, strerror(errno));
121
	    kbinput = ERR;
122
123
124
125
	}
#endif
	/* Display (or redisplay) the file list if we don't have a key yet,
	 * or the list has changed, or the selected file has changed. */
126
	if (kbinput == ERR || old_selected != selected)
127
	    browser_refresh();
128

129
130
	old_selected = selected;

131
	kbinput = get_kbinput(edit);
132

133
#ifndef NANO_TINY
134
	if (kbinput == KEY_WINCH)
135
136
137
	    continue;
#endif

138
#ifndef DISABLE_MOUSE
139
	if (kbinput == KEY_MOUSE) {
140
141
	    int mouse_x, mouse_y;

142
	    /* We can click on the edit window to select a filename. */
143
	    if (get_mouseinput(&mouse_x, &mouse_y, TRUE) == 0 &&
144
			wmouse_trafo(edit, &mouse_y, &mouse_x, FALSE)) {
145
146
		/* longest is the width of each column.  There
		 * are two spaces between each column. */
147
		selected = selected - selected % (editwinrows * width) +
148
				(mouse_y * width) + (mouse_x / (longest + 2));
149

150
		/* If they clicked beyond the end of a row,
151
		 * select the last filename in that row. */
152
153
154
		if (mouse_x > width * (longest + 2))
		    selected--;

155
		/* If we're beyond the list, select the last filename. */
156
157
158
		if (selected > filelist_len - 1)
		    selected = filelist_len - 1;

159
160
		/* If we selected the same filename as last time, fake a
		 * press of the Enter key so that the file is read in. */
161
		if (old_selected == selected)
162
		    unget_kbinput(sc_seq_or(do_enter, 0), FALSE, FALSE);
163
	    }
164
165

	    continue;
166
	}
167
#endif /* !DISABLE_MOUSE */
168

169
	func = parse_browser_input(&kbinput);
170

171
	if (func == total_refresh) {
172
	    total_redraw();
173
	    /* Simulate a window resize to force a directory reread. */
174
#ifndef NANO_TINY
175
	    kbinput = KEY_WINCH;
176
#endif
177
	} else if (func == do_help_void) {
178
#ifndef DISABLE_HELP
179
	    do_help_void();
180
	    /* The window dimensions might have changed, so act as if. */
181
#ifndef NANO_TINY
182
	    kbinput = KEY_WINCH;
183
#endif
184
#else
185
	    say_there_is_no_help();
186
#endif
187
	} else if (func == do_search) {
188
189
	    /* Search for a filename. */
	    do_filesearch();
190
	} else if (func == do_research) {
191
192
	    /* Search for another filename. */
	    do_fileresearch();
193
	} else if (func == do_page_up) {
194
	    if (selected < width)
195
		selected = 0;
196
197
198
199
	    else if (selected < editwinrows * width)
		selected = selected % width;
	    else
		selected -= editwinrows * width;
200
	} else if (func == do_page_down) {
201
	    if (selected + width >= filelist_len - 1)
202
		selected = filelist_len - 1;
203
204
205
206
207
	    else if (selected + editwinrows * width >= filelist_len)
		selected = (selected + editwinrows * width - filelist_len) %
				width +	filelist_len - width;
	    else
		selected += editwinrows * width;
208
	} else if (func == do_first_file) {
209
	    selected = 0;
210
	} else if (func == do_last_file) {
211
	    selected = filelist_len - 1;
212
	} else if (func == goto_dir_void) {
213
	    /* Ask for the directory to go to. */
214
	    i = do_prompt(TRUE,
215
216
217
#ifndef DISABLE_TABCOMP
			FALSE,
#endif
218
			MGOTODIR, NULL,
219
#ifndef DISABLE_HISTORIES
220
221
			NULL,
#endif
222
			/* TRANSLATORS: This is a prompt. */
223
			browser_refresh, _("Go To Directory"));
224

225
226
227
228
229
230
231
232
233
	    bottombars(MBROWSER);

	    /* If the directory begins with a newline (i.e. an
	     * encoded null), treat it as though it's blank. */
	    if (i < 0 || *answer == '\n') {
		statusbar(_("Cancelled"));
		continue;
	    }

234
	    /* Convert newlines to nulls in the directory name. */
235
236
237
238
239
240
241
242
243
244
	    sunder(answer);
	    align(&answer);

	    new_path = real_dir_from_tilde(answer);

	    if (new_path[0] != '/') {
		new_path = charealloc(new_path, strlen(path) +
				strlen(answer) + 1);
		sprintf(new_path, "%s%s", path, answer);
	    }
245
246

#ifndef DISABLE_OPERATINGDIR
247
	    if (check_operating_dir(new_path, FALSE)) {
248
249
		/* TRANSLATORS: This refers to the option --operatingdir,
		 * not to --restricted. */
250
		statusline(ALERT, _("Can't go outside of %s "
251
				"in confined mode"), full_operating_dir);
252
253
254
		free(new_path);
		continue;
	    }
255
256
#endif

257
258
	    dir = opendir(new_path);
	    if (dir == NULL) {
259
		/* We can't open this directory for some reason. */
260
		statusline(ALERT, _("Error reading %s: %s"), answer,
261
262
263
264
265
266
267
268
				strerror(errno));
		free(new_path);
		continue;
	    }

	    /* Start over again with the new path value. */
	    free(path);
	    path = new_path;
269
	    goto read_directory_contents;
270
	} else if (func == do_up_void) {
271
272
	    if (selected >= width)
		selected -= width;
273
	} else if (func == do_down_void) {
274
275
	    if (selected + width <= filelist_len - 1)
		selected += width;
276
#ifndef NANO_TINY
277
278
279
280
281
282
	} 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;
283
#endif
284
285
286
	} else if (func == do_left) {
	    if (selected > 0)
		selected--;
287
	} else if (func == do_right) {
288
289
	    if (selected < filelist_len - 1)
		selected++;
290
	} else if (func == do_enter) {
291
292
	    /* We can't move up from "/". */
	    if (strcmp(filelist[selected], "/..") == 0) {
293
		statusline(ALERT, _("Can't move up a directory"));
294
295
		continue;
	    }
296
297

#ifndef DISABLE_OPERATINGDIR
298
299
300
301
	    /* 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. */
	    if (check_operating_dir(filelist[selected], FALSE)) {
302
		statusline(ALERT, _("Can't go outside of %s "
303
				"in confined mode"), full_operating_dir);
304
305
		continue;
	    }
306
307
#endif

308
309
310
	    if (stat(filelist[selected], &st) == -1) {
		/* We can't open this file for some reason.
		 * Complain. */
311
		 statusline(ALERT, _("Error reading %s: %s"),
312
313
314
315
316
				filelist[selected], strerror(errno));
		 continue;
	    }

	    if (!S_ISDIR(st.st_mode)) {
317
318
		/* We've successfully opened a file, we're done, so
		 * get out. */
319
		retval = mallocstrcpy(NULL, filelist[selected]);
320
		break;
321
	    }
322
323

	    dir = opendir(filelist[selected]);
324

325
	    if (dir == NULL) {
326
		statusline(ALERT, _("Error reading %s: %s"),
327
328
329
330
				filelist[selected], strerror(errno));
		continue;
	    }

331
332
333
	    /* If we moved up one level, remember where we came from, so
	     * this directory can be highlighted and easily reentered. */
	    if (strcmp(tail(filelist[selected]), "..") == 0)
334
		present_name = striponedir(filelist[selected]);
335

336
337
338
	    path = mallocstrcpy(path, filelist[selected]);

	    /* Start over again with the new path value. */
339
	    goto read_directory_contents;
340
	} else if (func == do_exit) {
341
342
	    /* Exit from the file browser. */
	    break;
343
344
	} else
	    unbound_key(kbinput);
345
    }
346

347
348
349
    titlebar(NULL);
    edit_refresh();

350
351
352
353
354
    free(path);

    free_chararray(filelist, filelist_len);
    filelist = NULL;
    filelist_len = 0;
355
356
357
358

    return retval;
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
359
360
361
/* 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. */
362
363
364
365
366
char *do_browse_from(const char *inpath)
{
    struct stat st;
    char *path;
	/* This holds the tilde-expanded version of inpath. */
367
    DIR *dir = NULL;
368
369
370
371
372
373
374
375
376
377
378
379

    assert(inpath != NULL);

    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)) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
380
381
	path = mallocstrassn(path, striponedir(path));

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

385
386
	    free(path);
	    path = getcwd(currentdir, PATH_MAX + 1);
387

388
	    if (path == NULL) {
389
		free(currentdir);
390
391
392
393
394
		statusline(MILD, "The working directory has disappeared");
		beep();
		napms(1200);
		return NULL;
	   } else
395
396
397
398
399
400
401
		align(&path);
	}
    }

#ifndef DISABLE_OPERATINGDIR
    /* If the resulting path isn't in the operating directory, use
     * the operating directory instead. */
402
403
    if (check_operating_dir(path, FALSE))
	path = mallocstrcpy(path, operating_dir);
404
405
#endif

406
407
408
409
410
    if (path != NULL)
	dir = opendir(path);

    /* If we can't open the path, get out. */
    if (dir == NULL) {
411
	free(path);
412
413
414
415
416
	beep();
	return NULL;
    }

    return do_browser(path, dir);
417
418
}

419
/* Set filelist to the list of files contained in the directory path,
420
 * set filelist_len to the number of files in that list, set longest to
421
 * the width in columns of the longest filename in that list (between 15
422
423
424
425
 * and COLS), and set width to the number of files that we can display
 * per line.  longest needs to be at least 15 columns in order to
 * display ".. (parent dir)", as Pico does.  Assume path exists and is a
 * directory. */
426
427
428
void browser_init(const char *path, DIR *dir)
{
    const struct dirent *nextdir;
429
    size_t i = 0, path_len = strlen(path);
430

431
    assert(path != NULL && path[strlen(path) - 1] == '/' && dir != NULL);
432
433
434

    longest = 0;

435
    /* Find the length of the longest filename in the current folder. */
436
    while ((nextdir = readdir(dir)) != NULL) {
437
	size_t name_len = strlenpt(nextdir->d_name);
438

439
440
	if (name_len > longest)
	    longest = name_len;
441
442

	i++;
443
444
    }

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

449
450
451
452
453
454
455
456
    /* Make sure longest is between 15 and COLS. */
    if (longest < 15)
	longest = 15;
    if (longest > COLS)
	longest = COLS;

    rewinddir(dir);

457
    free_chararray(filelist, filelist_len);
458
459
460

    filelist_len = i;

461
462
463
464
465
466
467
    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)
468
	    continue;
469
470
471

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

473
474
475
476
477
478
479
	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;
480

481
482
    closedir(dir);

483
484
485
486
    /* 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);
487
488
}

489
490
491
/* 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)
492
{
493
    if (!meta_key) {
494
495
	switch (*kbinput) {
	    case ' ':
496
		return do_page_down;
497
	    case '-':
498
		return do_page_up;
499
	    case '?':
500
		return do_help_void;
501
502
	    case 'E':
	    case 'e':
503
		return do_exit;
504
505
	    case 'G':
	    case 'g':
506
		return goto_dir_void;
507
508
	    case 'S':
	    case 's':
509
		return do_enter;
510
511
	    case 'W':
	    case 'w':
512
		return do_search;
513
514
	}
    }
515
    return func_from_key(kbinput);
516
517
}

518
519
/* Set width to the number of files that we can display per line, if
 * necessary, and display the list of files. */
520
void browser_refresh(void)
521
{
522
    size_t i;
523
524
    int line = 0, col = 0;
	/* The current line and column while the list is getting displayed. */
Benno Schulenberg's avatar
Benno Schulenberg committed
525
    char *info;
526
	/* The additional information that we'll display about a file. */
527

528
    titlebar(present_path);
529
530
531
532
    blank_edit();

    wmove(edit, 0, 0);

533
    i = selected - selected % (editwinrows * width);
534

535
    for (; i < filelist_len && line < editwinrows; i++) {
536
	struct stat st;
Benno Schulenberg's avatar
Benno Schulenberg committed
537
	const char *thename = tail(filelist[i]);
538
		/* The filename we display, minus the path. */
Benno Schulenberg's avatar
Benno Schulenberg committed
539
	size_t namelen = strlenpt(thename);
540
		/* The length of the filename in columns. */
Benno Schulenberg's avatar
Benno Schulenberg committed
541
	size_t infolen;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
542
		/* The length of the file information in columns. */
Benno Schulenberg's avatar
Benno Schulenberg committed
543
	int infomaxlen = 7;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
544
		/* The maximum length of the file information in
545
546
		 * columns: seven for "--", "(dir)", or the file size,
		 * and 12 for "(parent dir)". */
Benno Schulenberg's avatar
Benno Schulenberg committed
547
	bool dots = (COLS >= 15 && namelen >= longest - infomaxlen);
548
		/* Do we put an ellipsis before the filename?  Don't set
549
550
551
		 * this to TRUE if we have fewer than 15 columns (i.e.
		 * one column for padding, plus seven columns for a
		 * filename other than ".."). */
Benno Schulenberg's avatar
Benno Schulenberg committed
552
553
	char *disp = display_string(thename, dots ? namelen -
		longest + infomaxlen + 4 : 0, longest, FALSE);
554
555
556
557
		/* If we put an ellipsis before the filename, reserve
		 * one column for padding, plus seven columns for "--",
		 * "(dir)", or the file size, plus three columns for the
		 * ellipsis. */
558

559
	/* Start highlighting the currently selected file or directory. */
560
	if (i == selected)
561
	    wattron(edit, hilite_attribute);
562

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
563
	blank_line(edit, line, col, longest);
564

565
	/* If dots is TRUE, we will display something like "...ename". */
566
567
568
569
	if (dots)
	    mvwaddstr(edit, line, col, "...");
	mvwaddstr(edit, line, dots ? col + 3 : col, disp);

570
571
572
573
	free(disp);

	col += longest;

574
575
	/* Show information about the file.  We don't want to report
	 * file sizes for links, so we use lstat(). */
576
	if (lstat(filelist[i], &st) == -1 || S_ISLNK(st.st_mode)) {
577
	    /* If the file doesn't exist (i.e. it's been deleted while
578
579
580
	     * the file browser is open), or it's a symlink that doesn't
	     * point to a directory, display "--". */
	    if (stat(filelist[i], &st) == -1 || !S_ISDIR(st.st_mode))
Benno Schulenberg's avatar
Benno Schulenberg committed
581
		info = mallocstrcpy(NULL, "--");
582
583
584
	    /* If the file is a symlink that points to a directory,
	     * display it as a directory. */
	    else
585
		/* TRANSLATORS: Try to keep this at most 7 characters. */
Benno Schulenberg's avatar
Benno Schulenberg committed
586
		info = mallocstrcpy(NULL, _("(dir)"));
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
587
	} else if (S_ISDIR(st.st_mode)) {
588
	    /* If the file is a directory, display it as such. */
Benno Schulenberg's avatar
Benno Schulenberg committed
589
	    if (strcmp(thename, "..") == 0) {
590
		/* TRANSLATORS: Try to keep this at most 12 characters. */
Benno Schulenberg's avatar
Benno Schulenberg committed
591
592
		info = mallocstrcpy(NULL, _("(parent dir)"));
		infomaxlen = 12;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
593
	    } else
Benno Schulenberg's avatar
Benno Schulenberg committed
594
		info = mallocstrcpy(NULL, _("(dir)"));
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
595
	} else {
596
	    off_t result = st.st_size;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
597
598
	    char modifier;

Benno Schulenberg's avatar
Benno Schulenberg committed
599
	    info = charalloc(infomaxlen + 1);
600

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
601
	    if (st.st_size < (1 << 10))
602
		modifier = ' ';  /* bytes */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
603
604
	    else if (st.st_size < (1 << 20)) {
		result >>= 10;
605
		modifier = 'K';  /* kilobytes */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
606
607
	    } else if (st.st_size < (1 << 30)) {
		result >>= 20;
608
		modifier = 'M';  /* megabytes */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
609
610
	    } else {
		result >>= 30;
611
		modifier = 'G';  /* gigabytes */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
612
613
	    }

614
615
616
	    /* Show the size if less than a terabyte,
	     * otherwise show "(huge)". */
	    if (result < (1 << 10))
Benno Schulenberg's avatar
Benno Schulenberg committed
617
		sprintf(info, "%4ju %cB", (intmax_t)result, modifier);
618
619
620
	    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
621
		info = mallocstrcpy(info, _("(huge)"));
622
623
	}

Benno Schulenberg's avatar
Benno Schulenberg committed
624
625
626
627
628
	/* Make sure info takes up no more than infomaxlen columns. */
	infolen = strlenpt(info);
	if (infolen > infomaxlen) {
	    null_at(&info, actual_x(info, infomaxlen));
	    infolen = infomaxlen;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
629
630
	}

Benno Schulenberg's avatar
Benno Schulenberg committed
631
	mvwaddstr(edit, line, col - infolen, info);
632

633
	/* Finish highlighting the currently selected file or directory. */
634
	if (i == selected)
635
	    wattroff(edit, hilite_attribute);
636

Benno Schulenberg's avatar
Benno Schulenberg committed
637
	free(info);
638

639
640
641
	/* Add some space between the columns. */
	col += 2;

642
643
	/* If the next entry isn't going to fit on the current line,
	 * move to the next line. */
644
	if (col > COLS - longest) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
645
	    line++;
646
647
648
	    col = 0;
	}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
649
	wmove(edit, line, col);
650
651
652
653
654
    }

    wnoutrefresh(edit);
}

655
656
657
/* 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)
658
{
659
    size_t looking_at = 0;
660

661
662
663
    for (; looking_at < filelist_len; looking_at++) {
	if (strcmp(filelist[looking_at], needle) == 0) {
	    selected = looking_at;
664
665
666
	    break;
	}
    }
667
668
669

    /* If the sought name isn't found, move the highlight so that the
     * changed selection will be noticed. */
670
    if (looking_at == filelist_len) {
671
	--selected;
672
673
674
675
676

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

679
680
681
682
/* 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. */
683
684
int filesearch_init(void)
{
685
    int input;
686
687
688
689
690
691
    char *buf;

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

	buf = charalloc(strlen(disp) + 7);
692
	/* We use (COLS / 3) here because we need to see more on the line. */
693
694
695
696
697
698
699
	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. */
700
    input = do_prompt(FALSE,
701
702
703
#ifndef DISABLE_TABCOMP
	TRUE,
#endif
704
	MWHEREISFILE, NULL,
705
#ifndef DISABLE_HISTORIES
706
707
	&search_history,
#endif
708
	browser_refresh, "%s%s", _("Search"), buf);
709
710
711
712

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

713
714
715
716
717
718
    /* 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)
719
720
	statusbar(_("Cancelled"));

721
    return input;
722
723
}

724
725
/* Look for the given needle in the list of files. */
void findnextfile(const char *needle)
726
{
727
    size_t looking_at = selected;
728
	/* The location in the file list of the filename we're looking at. */
729
730
    const char *thename;
	/* The plain filename, without the path. */
731
732
733
734
735
736
737
738
739
740
    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));

    /* Search forward, case insensitive and without regexes. */
    UNSET(BACKWARDS_SEARCH);
    UNSET(CASE_SENSITIVE);
    UNSET(USE_REGEXP);
741

742
743
    /* Step through each filename in the list until a match is found or
     * we've come back to the point where we started. */
744
    while (TRUE) {
745
	/* Move to the next filename in the list, or back to the first. */
746
747
	if (looking_at < filelist_len - 1)
	    looking_at++;
748
	else {
749
	    looking_at = 0;
750
	    statusbar(_("Search Wrapped"));
751
752
	}

753
	/* Get the bare filename, without the path. */
Benno Schulenberg's avatar
Benno Schulenberg committed
754
	thename = tail(filelist[looking_at]);
755
756
757
758

	/* 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)) {
759
	    if (looking_at == selected)
760
		statusbar(_("This is the only occurrence"));
761
	    break;
762
763
764
765
766
767
768
	}

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

771
772
773
    /* Restore the settings of all flags. */
    memcpy(flags, stash, sizeof(flags));

774
    /* Select the one we've found. */
775
    selected = looking_at;
776
777
778
779
780
}

/* Search for a filename. */
void do_filesearch(void)
{
781
    if (filesearch_init() != 0) {
782
	/* Cancelled, or a blank search string, or done something. */
783
	bottombars(MBROWSER);
784
	return;
785
    }
786
787

    /* If answer is now "", copy last_search into answer. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
788
    if (*answer == '\0')
789
790
791
792
	answer = mallocstrcpy(answer, last_search);
    else
	last_search = mallocstrcpy(last_search, answer);

793
#ifndef DISABLE_HISTORIES
794
795
796
797
798
799
    /* If answer is not "", add this search string to the search history
     * list. */
    if (answer[0] != '\0')
	update_history(&search_history, answer);
#endif

800
    findnextfile(answer);
801

802
    bottombars(MBROWSER);
803
804
}

805
/* Search for the last given filename again without prompting. */
806
807
void do_fileresearch(void)
{
808
809
810
811
    if (last_search[0] == '\0')
	statusbar(_("No current search pattern"));
    else
	findnextfile(last_search);
812
813
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
814
/* Select the first file in the list. */
815
816
817
818
819
void do_first_file(void)
{
    selected = 0;
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
820
/* Select the last file in the list. */
821
822
823
824
825
void do_last_file(void)
{
    selected = filelist_len - 1;
}

826
827
828
829
/* Strip one directory from the end of path, and return the stripped
 * path.  The returned string is dynamically allocated, and should be
 * freed. */
char *striponedir(const char *path)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
830
{
831
    char *retval, *tmp;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
832
833
834

    assert(path != NULL);

835
836
837
    retval = mallocstrcpy(NULL, path);

    tmp = strrchr(retval, '/');
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
838
839

    if (tmp != NULL)
840
	null_at(&retval, tmp - retval);
841
842

    return retval;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
843
844
}

845
#endif /* !DISABLE_BROWSER */