browser.c 23.8 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)
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
60
61
62
63
64
65
    DIR *dir = opendir(path);

    /* If we can't open the given directory, forget it. */
    if (dir == NULL) {
	beep();
	free(path);
	return NULL;
    }
66

67
    /* Don't show a cursor in the file list. */
68
69
    curs_set(0);
    blank_statusbar();
70
    bottombars(MBROWSER);
71

72
  read_directory_contents:
73
	/* We come here when we refresh or select a new directory. */
74

75
    /* Start with no key pressed. */
76
77
    kbinput = ERR;

78
79
    path = mallocstrassn(path, get_full_path(path));

80
    /* Save the current path in order to be used later. */
81
    present_path = mallocstrcpy(present_path, path);
82

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

85
    /* Get the file list, and set longest and width in the process. */
86
    read_the_list(path, dir);
87

88
89
    closedir(dir);

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

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

100
101
    old_selected = (size_t)-1;

102
103
    titlebar(path);

104
    while (TRUE) {
105
106
	struct stat st;
	int i;
107
	char *new_path;
108
109
		/* The path we switch to at the "Go to Directory"
		 * prompt. */
110

111
112
	/* Make sure that the cursor is off. */
	curs_set(0);
113
	lastmessage = HUSH;
114

115
116
#ifndef NANO_TINY
	if (kbinput == KEY_WINCH) {
117
118
	    /* Remember the selected file, to be able to reselect it. */
	    present_name = strdup(filelist[selected]);
119

120
121
122
123
	    /* Reopen the current directory. */
	    dir = opendir(path);
	    if (dir != NULL)
		goto read_directory_contents;
124

125
	    statusline(ALERT, _("Error reading %s: %s"), path, strerror(errno));
126
	    kbinput = ERR;
127
128
129
130
	}
#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. */
131
	if (kbinput == ERR || old_selected != selected)
132
	    browser_refresh();
133

134
135
	old_selected = selected;

136
	kbinput = get_kbinput(edit);
137

138
#ifndef NANO_TINY
139
	if (kbinput == KEY_WINCH)
140
141
142
	    continue;
#endif

143
#ifndef DISABLE_MOUSE
144
	if (kbinput == KEY_MOUSE) {
145
146
	    int mouse_x, mouse_y;

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

155
		/* If they clicked beyond the end of a row,
156
		 * select the last filename in that row. */
157
158
159
		if (mouse_x > width * (longest + 2))
		    selected--;

160
		/* If we're beyond the list, select the last filename. */
161
162
163
		if (selected > filelist_len - 1)
		    selected = filelist_len - 1;

164
165
		/* If we selected the same filename as last time, fake a
		 * press of the Enter key so that the file is read in. */
166
		if (old_selected == selected)
167
		    unget_kbinput(sc_seq_or(do_enter, 0), FALSE, FALSE);
168
	    }
169
170

	    continue;
171
	}
172
#endif /* !DISABLE_MOUSE */
173

174
	func = parse_browser_input(&kbinput);
175

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

230
231
232
233
234
235
236
237
238
	    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;
	    }

239
	    /* Convert newlines to nulls in the directory name. */
240
241
242
243
244
245
246
247
248
249
	    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);
	    }
250
251

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

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

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

#ifndef DISABLE_OPERATINGDIR
303
304
305
306
	    /* 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)) {
307
		statusline(ALERT, _("Can't go outside of %s "
308
				"in confined mode"), full_operating_dir);
309
310
		continue;
	    }
311
312
#endif

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

	    if (!S_ISDIR(st.st_mode)) {
322
323
		/* We've successfully opened a file, we're done, so
		 * get out. */
324
		retval = mallocstrcpy(NULL, filelist[selected]);
325
		break;
326
	    }
327
328

	    dir = opendir(filelist[selected]);
329

330
	    if (dir == NULL) {
331
		statusline(ALERT, _("Error reading %s: %s"),
332
333
334
335
				filelist[selected], strerror(errno));
		continue;
	    }

336
337
338
	    /* 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)
339
		present_name = striponedir(filelist[selected]);
340

341
342
343
	    path = mallocstrcpy(path, filelist[selected]);

	    /* Start over again with the new path value. */
344
	    goto read_directory_contents;
345
	} else if (func == do_exit) {
346
347
	    /* Exit from the file browser. */
	    break;
348
349
	} else
	    unbound_key(kbinput);
350
    }
351

352
353
354
    titlebar(NULL);
    edit_refresh();

355
356
357
358
359
    free(path);

    free_chararray(filelist, filelist_len);
    filelist = NULL;
    filelist_len = 0;
360
361
362
363

    return retval;
}

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

    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
384
385
	path = mallocstrassn(path, striponedir(path));

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

389
390
	    free(path);
	    path = getcwd(currentdir, PATH_MAX + 1);
391

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

#ifndef DISABLE_OPERATINGDIR
    /* If the resulting path isn't in the operating directory, use
     * the operating directory instead. */
406
407
    if (check_operating_dir(path, FALSE))
	path = mallocstrcpy(path, operating_dir);
408
409
#endif

410
    return do_browser(path);
411
412
}

413
/* Set filelist to the list of files contained in the directory path,
414
 * set filelist_len to the number of files in that list, set longest to
415
 * the width in columns of the longest filename in that list (between 15
416
 * and COLS), and set width to the number of files that we can display
417
418
 * per line.  And sort the list too. */
void read_the_list(const char *path, DIR *dir)
419
420
{
    const struct dirent *nextdir;
421
    size_t i = 0, path_len = strlen(path);
422

423
    assert(path != NULL && path[strlen(path) - 1] == '/' && dir != NULL);
424
425
426

    longest = 0;

427
    /* Find the length of the longest filename in the current folder. */
428
    while ((nextdir = readdir(dir)) != NULL) {
429
	size_t name_len = strlenpt(nextdir->d_name);
430

431
432
	if (name_len > longest)
	    longest = name_len;
433
434

	i++;
435
436
    }

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

441
    /* If needed, make room for ".. (parent dir)". */
442
443
    if (longest < 15)
	longest = 15;
444
    /* Make sure we're not wider than the window. */
445
446
447
448
449
    if (longest > COLS)
	longest = COLS;

    rewinddir(dir);

450
    free_chararray(filelist, filelist_len);
451
452
453

    filelist_len = i;

454
455
456
457
458
459
460
    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)
461
	    continue;
462
463
464

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

466
467
468
469
470
471
472
	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;
473

474
475
476
477
478
    assert(filelist != NULL);

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

479
480
481
482
    /* 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);
483
484
}

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

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

524
    titlebar(present_path);
525
526
527
528
    blank_edit();

    wmove(edit, 0, 0);

529
    i = selected - selected % (editwinrows * width);
530

531
    for (; i < filelist_len && line < editwinrows; i++) {
532
	struct stat st;
Benno Schulenberg's avatar
Benno Schulenberg committed
533
	const char *thename = tail(filelist[i]);
534
		/* The filename we display, minus the path. */
Benno Schulenberg's avatar
Benno Schulenberg committed
535
	size_t namelen = strlenpt(thename);
536
		/* The length of the filename in columns. */
Benno Schulenberg's avatar
Benno Schulenberg committed
537
	size_t infolen;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
538
		/* The length of the file information in columns. */
Benno Schulenberg's avatar
Benno Schulenberg committed
539
	int infomaxlen = 7;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
540
		/* The maximum length of the file information in
541
542
		 * columns: seven for "--", "(dir)", or the file size,
		 * and 12 for "(parent dir)". */
Benno Schulenberg's avatar
Benno Schulenberg committed
543
	bool dots = (COLS >= 15 && namelen >= longest - infomaxlen);
544
		/* Do we put an ellipsis before the filename?  Don't set
545
546
547
		 * 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
548
549
	char *disp = display_string(thename, dots ? namelen -
		longest + infomaxlen + 4 : 0, longest, FALSE);
550
551
552
553
		/* 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. */
554

555
	/* Start highlighting the currently selected file or directory. */
556
	if (i == selected)
557
	    wattron(edit, hilite_attribute);
558

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

561
	/* If dots is TRUE, we will display something like "...ename". */
562
563
564
565
	if (dots)
	    mvwaddstr(edit, line, col, "...");
	mvwaddstr(edit, line, dots ? col + 3 : col, disp);

566
567
568
569
	free(disp);

	col += longest;

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

Benno Schulenberg's avatar
Benno Schulenberg committed
595
	    info = charalloc(infomaxlen + 1);
596

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

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

Benno Schulenberg's avatar
Benno Schulenberg committed
620
621
622
623
624
	/* 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
625
626
	}

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

629
	/* Finish highlighting the currently selected file or directory. */
630
	if (i == selected)
631
	    wattroff(edit, hilite_attribute);
632

Benno Schulenberg's avatar
Benno Schulenberg committed
633
	free(info);
634

635
636
637
	/* Add some space between the columns. */
	col += 2;

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

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
645
	wmove(edit, line, col);
646
647
648
649
650
    }

    wnoutrefresh(edit);
}

651
652
653
/* 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)
654
{
655
    size_t looking_at = 0;
656

657
658
659
    for (; looking_at < filelist_len; looking_at++) {
	if (strcmp(filelist[looking_at], needle) == 0) {
	    selected = looking_at;
660
661
662
	    break;
	}
    }
663
664
665

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

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

675
676
677
678
/* 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. */
679
680
int filesearch_init(void)
{
681
    int input;
682
683
684
685
686
687
    char *buf;

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

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

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

709
710
711
712
713
714
    /* 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)
715
716
	statusbar(_("Cancelled"));

717
    return input;
718
719
}

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

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

749
	/* Get the bare filename, without the path. */
Benno Schulenberg's avatar
Benno Schulenberg committed
750
	thename = tail(filelist[looking_at]);
751
752
753
754

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

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

767
768
769
    /* Restore the settings of all flags. */
    memcpy(flags, stash, sizeof(flags));

770
    /* Select the one we've found. */
771
    selected = looking_at;
772
773
774
775
776
}

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

    /* If answer is now "", copy last_search into answer. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
784
    if (*answer == '\0')
785
786
787
788
	answer = mallocstrcpy(answer, last_search);
    else
	last_search = mallocstrcpy(last_search, answer);

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

796
    findnextfile(answer);
797

798
    bottombars(MBROWSER);
799
800
}

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

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
810
/* Select the first file in the list. */
811
812
813
814
815
void do_first_file(void)
{
    selected = 0;
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
816
/* Select the last file in the list. */
817
818
819
820
821
void do_last_file(void)
{
    selected = filelist_len - 1;
}

822
823
824
825
/* 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
826
{
827
    char *retval, *tmp;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
828
829
830

    assert(path != NULL);

831
832
833
    retval = mallocstrcpy(NULL, path);

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

    if (tmp != NULL)
836
	null_at(&retval, tmp - retval);
837
838

    return retval;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
839
840
}

841
#endif /* !DISABLE_BROWSER */