browser.c 29.1 KB
Newer Older
1
2
3
4
/* $Id$ */
/**************************************************************************
 *   browser.c                                                            *
 *                                                                        *
5
6
 *   Copyright (C) 2001, 2002, 2003, 2004 Chris Allegretta                *
 *   Copyright (C) 2005, 2006 David Lawrence Ramsey                       *
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 *   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 *
 *   the Free Software Foundation; either version 2, or (at your option)  *
 *   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
27
28
29
30
31
32

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

#ifndef DISABLE_BROWSER

33
static char **filelist = NULL;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
34
	/* The list of files to display in the file browser. */
35
36
37
static size_t filelist_len = 0;
	/* The number of files in the list. */
static int width = 0;
38
	/* The number of files that we can display per line. */
39
40
static int longest = 0;
	/* The number of columns in the longest filename in the list. */
41
static size_t selected = 0;
42
43
	/* The currently selected filename in the list.  This variable
	 * is zero-based. */
44
45
static bool search_last_file = FALSE;
	/* Have we gone past the last file while searching? */
46

47
48
/* Our main file browser function.  path is the tilde-expanded path to
 * start browsing from. */
49
char *do_browser(char *path, DIR *dir)
50
{
51
    char *retval = NULL;
52
    int kbinput;
53
    bool meta_key, func_key, old_const_update = ISSET(CONST_UPDATE);
54
55
    bool abort = FALSE;
	/* Whether we should abort the file browser. */
56
57
    char *prev_dir = NULL;
	/* The directory we were in, if any, before backing up via
58
	 * browsing to "..". */
59
    char *ans = NULL;
60
	/* The last answer the user typed on the statusbar. */
61
62
    size_t old_selected;
	/* The selected file we had before the current selected file. */
63
64
65
66
67
68

    curs_set(0);
    blank_statusbar();
#if !defined(DISABLE_HELP) || !defined(DISABLE_MOUSE)
    currshortcut = browser_list;
#endif
69
70
    bottombars(browser_list);
    wnoutrefresh(bottomwin);
71
72
73

    UNSET(CONST_UPDATE);

74
75
    ans = mallocstrcpy(NULL, "");

76
  change_browser_directory:
77
	/* We go here after we select a new directory. */
78

79
    /* Start with no key pressed. */
80
81
    kbinput = ERR;

82
83
84
85
    path = mallocstrassn(path, get_full_path(path));

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

86
    /* Get the file list, and set longest and width in the process. */
87
    browser_init(path, dir);
88
89
90

    assert(filelist != NULL);

91
    /* Sort the file list. */
92
    qsort(filelist, filelist_len, sizeof(char *), diralphasort);
93

94
95
96
97
98
99
100
    /* If prev_dir isn't NULL, select the directory saved in it, and
     * then blow it away. */
    if (prev_dir != NULL) {
	browser_select_filename(prev_dir);

	free(prev_dir);
	prev_dir = NULL;
101
102
103
    /* Otherwise, select the first file or directory in the list. */
    } else
	selected = 0;
104

105
106
    old_selected = (size_t)-1;

107
108
    titlebar(path);

109
    while (!abort) {
110
111
112
	struct stat st;
	int i;
	size_t fileline = selected / width;
113
		/* The line number the selected file is on. */
114
	char *new_path;
115
116
		/* The path we switch to at the "Go to Directory"
		 * prompt. */
117

118
119
120
121
	/* Display the file list if we don't have a key, or if the
	 * selected file has changed, and set width in the process. */
	if (kbinput == ERR || old_selected != selected)
	    browser_refresh();
122

123
124
	old_selected = selected;

125
126
127
	kbinput = get_kbinput(edit, &meta_key, &func_key);
	parse_browser_input(&kbinput, &meta_key, &func_key);

128
129
130
	switch (kbinput) {
#ifndef DISABLE_MOUSE
	    case KEY_MOUSE:
131
		{
132
		    int mouse_x, mouse_y;
133

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
134
		    if (!get_mouseinput(&mouse_x, &mouse_y, TRUE)) {
135
			/* We can click in the edit window to select a
136
			 * filename. */
137
138
139
140
141
142
143
144
145
146
147
148
			if (wenclose(edit, mouse_y, mouse_x)) {
			    /* Subtract out the size of topwin. */
			    mouse_y -= 2 - no_more_space();

			    /* longest is the width of each column.
			     * There are two spaces between each
			     * column. */
			    selected = (fileline / editwinrows) *
				(editwinrows * width) + (mouse_y *
				width) + (mouse_x / (longest + 2));

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

			    /* If we're off the screen, select the last
155
			     * filename. */
156
157
			    if (selected > filelist_len - 1)
				selected = filelist_len - 1;
158
159
160
161
162

			    /* If we selected the same filename as last
			     * time, put back the Enter key so that it's
			     * read in. */
			    if (old_selected == selected)
163
164
165
166
				unget_kbinput(NANO_ENTER_KEY, FALSE,
					FALSE);
			}
		    }
167
168
		}
		break;
169
#endif /* !DISABLE_MOUSE */
170
171
172
173
	    /* Redraw the screen. */
	    case NANO_REFRESH_KEY:
		total_redraw();
		break;
174
175
176
177
178
179
180
	    case NANO_HELP_KEY:
#ifndef DISABLE_HELP
		do_browser_help();
		curs_set(0);
#else
		nano_disabled_msg();
#endif
181
		break;
182
183
184
185
186
	    /* Search for a filename. */
	    case NANO_WHEREIS_KEY:
		curs_set(1);
		do_filesearch();
		curs_set(0);
187
		break;
188
189
190
	    /* Search for another filename. */
	    case NANO_WHEREIS_NEXT_KEY:
		do_fileresearch();
191
192
193
194
195
196
197
198
199
200
201
202
		break;
	    case NANO_PREVPAGE_KEY:
		if (selected >= (editwinrows + fileline % editwinrows) *
			width)
		    selected -= (editwinrows + fileline % editwinrows) *
			width;
		else
		    selected = 0;
		break;
	    case NANO_NEXTPAGE_KEY:
		selected += (editwinrows - fileline % editwinrows) *
			width;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
203
		if (selected > filelist_len - 1)
204
		    selected = filelist_len - 1;
205
		break;
206
	    case NANO_FIRSTFILE_METAKEY:
207
208
		if (meta_key)
		    selected = 0;
209
		break;
210
	    case NANO_LASTFILE_METAKEY:
211
212
		if (meta_key)
		    selected = filelist_len - 1;
213
		break;
214
	    /* Go to a specific directory. */
215
	    case NANO_GOTODIR_KEY:
216
217
		curs_set(1);

218
		i = do_prompt(TRUE,
219
220
221
#ifndef DISABLE_TABCOMP
			FALSE,
#endif
222
			gotodir_list, ans,
223
#ifndef NANO_TINY
224
225
			NULL,
#endif
226
			browser_refresh, _("Go To Directory"));
227
228

		curs_set(0);
229
230
231
#if !defined(DISABLE_HELP) || !defined(DISABLE_MOUSE)
		currshortcut = browser_list;
#endif
232
233
		bottombars(browser_list);

234
235
236
		if (i < 0) {
		    /* We canceled.  Indicate that on the statusbar, and
		     * blank out ans, since we're done with it. */
237
		    statusbar(_("Cancelled"));
238
239
240
241
242
243
244
245
246
		    ans = mallocstrcpy(ans, "");
		    break;
		} else if (i != 0) {
		    /* Put back the "Go to Directory" key and save
		     * answer in ans, so that the file list is displayed
		     * again, the prompt is displayed again, and what we
		     * typed before at the prompt is displayed again. */
		    unget_kbinput(NANO_GOTOLINE_KEY, FALSE, FALSE);
		    ans = mallocstrcpy(ans, answer);
247
248
249
		    break;
		}

250
251
252
253
		/* We have a directory.  Blank out ans, since we're done
		 * with it. */
		ans = mallocstrcpy(ans, "");

254
255
256
		new_path = real_dir_from_tilde(answer);

		if (new_path[0] != '/') {
257
		    new_path = charealloc(new_path, strlen(path) +
258
			strlen(answer) + 1);
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
		    sprintf(new_path, "%s%s", path, answer);
		}

#ifndef DISABLE_OPERATINGDIR
		if (check_operating_dir(new_path, FALSE)) {
		    statusbar(
			_("Can't go outside of %s in restricted mode"),
			operating_dir);
		    free(new_path);
		    break;
		}
#endif

		dir = opendir(new_path);
		if (dir == NULL) {
274
		    /* We can't open this directory for some reason.
275
276
277
		     * Complain. */
		    statusbar(_("Error reading %s: %s"), answer,
			strerror(errno));
278
		    beep();
279
280
281
282
283
284
285
286
		    free(new_path);
		    break;
		}

		/* Start over again with the new path value. */
		free(path);
		path = new_path;
		goto change_browser_directory;
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
	    case NANO_PREVLINE_KEY:
		if (selected >= width)
		    selected -= width;
		break;
	    case NANO_BACK_KEY:
		if (selected > 0)
		    selected--;
		break;
	    case NANO_NEXTLINE_KEY:
		if (selected + width <= filelist_len - 1)
		    selected += width;
		break;
	    case NANO_FORWARD_KEY:
		if (selected < filelist_len - 1)
		    selected++;
		break;
	    case NANO_ENTER_KEY:
304
		/* We can't move up from "/". */
305
306
307
308
309
310
311
		if (strcmp(filelist[selected], "/..") == 0) {
		    statusbar(_("Can't move up a directory"));
		    beep();
		    break;
		}

#ifndef DISABLE_OPERATINGDIR
312
		/* Note: The selected file can be outside the operating
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
		 * directory if it's ".." or if it's a symlink to a
		 * directory outside the operating directory. */
		if (check_operating_dir(filelist[selected], FALSE)) {
		    statusbar(
			_("Can't go outside of %s in restricted mode"),
			operating_dir);
		    beep();
		    break;
		}
#endif

		if (stat(filelist[selected], &st) == -1) {
		    /* We can't open this file for some reason.
		     * Complain. */
		    statusbar(_("Error reading %s: %s"),
			filelist[selected], strerror(errno));
		    beep();
		    break;
		}

333
334
		/* If we've successfully opened a file, we're done, so
		 * get out. */
335
		if (!S_ISDIR(st.st_mode)) {
336
		    retval = mallocstrcpy(NULL, filelist[selected]);
337
		    abort = TRUE;
338
		    break;
339
340
341
		/* If we've successfully opened a directory, and it's
		 * "..", save the current directory in prev_dir, so that
		 * we can select it later. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
342
343
344
		} else if (strcmp(tail(filelist[selected]), "..") == 0)
		    prev_dir = mallocstrcpy(NULL,
			striponedir(filelist[selected]));
345
346
347

		dir = opendir(filelist[selected]);
		if (dir == NULL) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
348
		    /* We can't open this directory for some reason.
349
350
351
352
353
354
355
356
357
358
359
		     * Complain. */
		    statusbar(_("Error reading %s: %s"),
			filelist[selected], strerror(errno));
		    beep();
		    break;
		}

		path = mallocstrcpy(path, filelist[selected]);

		/* Start over again with the new path value. */
		goto change_browser_directory;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
360
	    /* Abort the file browser. */
361
362
363
	    case NANO_EXIT_KEY:
		abort = TRUE;
		break;
364
	}
365
    }
366
367
368
369
370
371
372

    titlebar(NULL);
    edit_refresh();
    curs_set(1);
    if (old_const_update)
	SET(CONST_UPDATE);

373
374
375
376
377
378
    free(path);
    free(ans);

    free_chararray(filelist, filelist_len);
    filelist = NULL;
    filelist_len = 0;
379
380
381
382

    return retval;
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
383
384
385
/* 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. */
386
387
388
389
390
char *do_browse_from(const char *inpath)
{
    struct stat st;
    char *path;
	/* This holds the tilde-expanded version of inpath. */
391
    DIR *dir = NULL;
392
393
394
395
396
397
398
399
400
401
402
403

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

406
407
408
409
410
411
412
413
414
415
416
417
418
419
	if (stat(path, &st) == -1 || !S_ISDIR(st.st_mode)) {
	    free(path);

	    path = charalloc(PATH_MAX + 1);
	    path = getcwd(path, PATH_MAX + 1);

	    if (path != NULL)
		align(&path);
	}
    }

#ifndef DISABLE_OPERATINGDIR
    /* If the resulting path isn't in the operating directory, use
     * the operating directory instead. */
420
421
    if (check_operating_dir(path, FALSE))
	path = mallocstrcpy(path, operating_dir);
422
423
#endif

424
425
426
427
428
    if (path != NULL)
	dir = opendir(path);

    /* If we can't open the path, get out. */
    if (dir == NULL) {
429
430
	if (path != NULL)
	    free(path);
431
432
433
434
435
	beep();
	return NULL;
    }

    return do_browser(path, dir);
436
437
}

438
/* Set filelist to the list of files contained in the directory path,
439
 * set filelist_len to the number of files in that list, set longest to
440
 * the width in columns of the longest filename in that list (between 15
441
442
443
444
 * 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. */
445
446
447
void browser_init(const char *path, DIR *dir)
{
    const struct dirent *nextdir;
448
    size_t i = 0, path_len = strlen(path);
449
450
451
452
453
454
455
456
    int col = 0;
	/* The maximum number of columns that the filenames will take
	 * up. */
    int line = 0;
	/* The maximum number of lines that the filenames will take
	 * up. */
    int filesperline = 0;
	/* The number of files that we can display per line. */
457

458
    assert(path != NULL && path[strlen(path) - 1] == '/' && dir != NULL);
459

460
    /* Set longest to zero, just before we initialize it. */
461
462
463
464
465
466
467
468
    longest = 0;

    while ((nextdir = readdir(dir)) != NULL) {
	size_t d_len;

	/* Don't show the "." entry. */
	if (strcmp(nextdir->d_name, ".") == 0)
	   continue;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
469

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
470
	d_len = strlenpt(nextdir->d_name);
471
	if (d_len > longest)
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
472
	    longest = (d_len > COLS) ? COLS : d_len;
473
474

	i++;
475
476
477
    }

    rewinddir(dir);
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
478

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
479
480
    /* Put 10 columns' worth of blank space between columns of filenames
     * in the list whenever possible, as Pico does. */
481
    longest += 10;
482

483
484
485
486
487
    if (filelist != NULL)
	free_chararray(filelist, filelist_len);

    filelist_len = i;

488
489
490
491
492
493
494
495
496
497
498
    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)
	   continue;

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

500
501
502
503
504
505
506
	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;
507

508
509
    closedir(dir);

510
    /* Make sure longest is between 15 and COLS. */
511
512
    if (longest < 15)
	longest = 15;
513
514
    if (longest > COLS)
	longest = COLS;
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544

    /* Set width to zero, just before we initialize it. */
    width = 0;

    for (i = 0; i < filelist_len && line < editwinrows; i++) {
	/* Calculate the number of columns one filename will take up. */
	col += longest;
	filesperline++;

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

	/* If the next entry isn't going to fit on the current line,
	 * move to the next line. */
	if (col > COLS - longest) {
	    line++;
	    col = 0;

	    /* If width isn't initialized yet, and we've taken up more
	     * than one line, it means that width is equal to
	     * filesperline. */
	    if (width == 0)
		width = filesperline;
	}
    }

    /* If width isn't initialized yet, and we've taken up only one line,
     * it means that width is equal to (COLS % longest). */
    if (width == 0)
	width = COLS % longest;
545
546
}

547
548
549
/* Determine the shortcut key corresponding to the values of kbinput
 * (the key itself), meta_key (whether the key is a meta sequence), and
 * func_key (whether the key is a function key), if any.  In the
550
551
 * process, convert certain non-shortcut keys into their corresponding
 * shortcut keys. */
552
553
554
555
556
void parse_browser_input(int *kbinput, bool *meta_key, bool *func_key)
{
    get_shortcut(browser_list, kbinput, meta_key, func_key);

    /* Pico compatibility. */
557
    if (!*meta_key) {
558
559
560
561
562
563
564
565
566
567
	switch (*kbinput) {
	    case ' ':
		*kbinput = NANO_NEXTPAGE_KEY;
		break;
	    case '-':
		*kbinput = NANO_PREVPAGE_KEY;
		break;
	    case '?':
		*kbinput = NANO_HELP_KEY;
		break;
568
569
	    /* Cancel is equivalent to Exit here. */
	    case NANO_CANCEL_KEY:
570
571
572
573
574
575
	    case 'E':
	    case 'e':
		*kbinput = NANO_EXIT_KEY;
		break;
	    case 'G':
	    case 'g':
576
		*kbinput = NANO_GOTODIR_KEY;
577
578
579
580
581
		break;
	    case 'S':
	    case 's':
		*kbinput = NANO_ENTER_KEY;
		break;
582
583
584
585
	    case 'W':
	    case 'w':
		*kbinput = NANO_WHEREIS_KEY;
		break;
586
587
588
589
	}
    }
}

590
591
/* Set width to the number of files that we can display per line, if
 * necessary, and display the list of files. */
592
void browser_refresh(void)
593
{
594
    static int uimax_digits = -1;
595
    size_t i;
596
597
598
599
600
601
    int col = 0;
	/* The maximum number of columns that the filenames will take
	 * up. */
    int line = 0;
	/* The maximum number of lines that the filenames will take
	 * up. */
602
    char *foo;
603
	/* The file information that we'll display. */
604
605
606

    if (uimax_digits == -1)
	uimax_digits = digits(UINT_MAX);
607
608
609
610
611

    blank_edit();

    wmove(edit, 0, 0);

612
    i = width * editwinrows * ((selected / width) / editwinrows);
613

614
    for (; i < filelist_len && line < editwinrows; i++) {
615
	struct stat st;
616
	const char *filetail = tail(filelist[i]);
617
618
619
		/* The filename we display, minus the path. */
	size_t filetaillen = strlenpt(filetail);
		/* The length of the filename in columns. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
620
621
622
623
	size_t foolen;
		/* The length of the file information in columns. */
	int foomaxlen = 7;
		/* The maximum length of the file information in
624
625
		 * columns: seven for "--", "(dir)", or the file size,
		 * and 12 for "(parent dir)". */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
626
	bool dots = (COLS >= 15 && filetaillen >= longest -
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
627
		foomaxlen - 1);
628
		/* Do we put an ellipsis before the filename?  Don't set
629
630
631
		 * this to TRUE if we have fewer than 15 columns (i.e.
		 * one column for padding, plus seven columns for a
		 * filename other than ".."). */
632
	char *disp = display_string(filetail, dots ? filetaillen -
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
633
		longest + foomaxlen + 4 : 0, longest, FALSE);
634
635
636
637
		/* 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. */
638

639
640
	/* Start highlighting the currently selected file or
	 * directory. */
641
	if (i == selected)
642
	    wattron(edit, reverse_attr);
643

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
644
	blank_line(edit, line, col, longest);
645
646
647
648
649
650
651

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

652
653
654
655
	free(disp);

	col += longest;

656
657
	/* Show information about the file.  We don't want to report
	 * file sizes for links, so we use lstat(). */
658
	if (lstat(filelist[i], &st) == -1 || S_ISLNK(st.st_mode)) {
659
	    /* If the file doesn't exist (i.e. it's been deleted while
660
661
662
663
664
665
666
	     * 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))
		foo = mallocstrcpy(NULL, "--");
	    /* If the file is a symlink that points to a directory,
	     * display it as a directory. */
	    else
667
668
		/* TRANSLATORS: Try to keep this at most 7
		 * characters. */
669
		foo = mallocstrcpy(NULL, _("(dir)"));
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
670
	} else if (S_ISDIR(st.st_mode)) {
671
	    /* If the file is a directory, display it as such. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
672
	    if (strcmp(filetail, "..") == 0) {
673
674
		/* TRANSLATORS: Try to keep this at most 12
		 * characters. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
675
676
677
678
679
		foo = mallocstrcpy(NULL, _("(parent dir)"));
		foomaxlen = 12;
	    } else
		foo = mallocstrcpy(NULL, _("(dir)"));
	} else {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
680
681
682
	    unsigned long result = st.st_size;
	    char modifier;

683
684
685
	    foo = charalloc(uimax_digits + 4);

	    /* Bytes. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
686
687
	    if (st.st_size < (1 << 10))
		modifier = ' ';
688
	    /* Kilobytes. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
689
690
691
	    else if (st.st_size < (1 << 20)) {
		result >>= 10;
		modifier = 'K';
692
	    /* Megabytes. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
693
694
695
	    } else if (st.st_size < (1 << 30)) {
		result >>= 20;
		modifier = 'M';
696
	    /* Gigabytes. */
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
697
698
699
700
701
702
	    } else {
		result >>= 30;
		modifier = 'G';
	    }

	    sprintf(foo, "%4lu %cB", result, modifier);
703
704
	}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
705
706
707
	/* Make sure foo takes up no more than foomaxlen columns. */
	foolen = strlenpt(foo);
	if (foolen > foomaxlen) {
708
	    null_at(&foo, actual_x(foo, foomaxlen));
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
709
710
711
712
	    foolen = foomaxlen;
	}

	mvwaddstr(edit, line, col - foolen, foo);
713

714
715
	/* Finish highlighting the currently selected file or
	 * directory. */
716
	if (i == selected)
717
	    wattroff(edit, reverse_attr);
718

719
720
	free(foo);

721
722
723
	/* Add some space between the columns. */
	col += 2;

724
725
	/* If the next entry isn't going to fit on the current line,
	 * move to the next line. */
726
	if (col > COLS - longest) {
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
727
	    line++;
728
729
730
	    col = 0;
	}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
731
	wmove(edit, line, col);
732
733
734
735
736
    }

    wnoutrefresh(edit);
}

737
738
739
/* 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.  The
 * return value specifies whether we found anything. */
740
bool browser_select_filename(const char *needle)
741
742
743
744
745
746
747
748
749
750
751
752
{
    size_t currselected;
    bool found = FALSE;

    for (currselected = 0; currselected < filelist_len;
	currselected++) {
	if (strcmp(filelist[currselected], needle) == 0) {
	    found = TRUE;
	    break;
	}
    }

753
    if (found)
754
	selected = currselected;
755
756

    return found;
757
758
}

759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
/* Set up the system variables for a filename search.  Return -1 if the
 * search should be canceled (due to Cancel, a blank search string, or a
 * failed regcomp()), return 0 on success, and return 1 on rerun calling
 * program. */
int filesearch_init(void)
{
    int i = 0;
    char *buf;
    static char *backupstring = NULL;
	/* The search string we'll be using. */

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

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

    search_init_globals();

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

	buf = charalloc(strlen(disp) + 7);
	/* We use (COLS / 3) here because we need to see more on the
	 * line. */
	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. */
    i = do_prompt(FALSE,
#ifndef DISABLE_TABCOMP
	TRUE,
#endif
	whereis_file_list, backupstring,
#ifndef NANO_TINY
	&search_history,
#endif
	browser_refresh, "%s%s%s%s%s%s", _("Search"),
#ifndef NANO_TINY
	/* This string is just a modifier for the search prompt; no
	 * grammar is implied. */
	ISSET(CASE_SENSITIVE) ? _(" [Case Sensitive]") :
#endif
	"",
#ifdef HAVE_REGEX_H
	/* This string is just a modifier for the search prompt; no
	 * grammar is implied. */
	ISSET(USE_REGEXP) ? _(" [Regexp]") :
#endif
	"",
#ifndef NANO_TINY
	/* This string is just a modifier for the search prompt; no
	 * grammar is implied. */
	ISSET(BACKWARDS_SEARCH) ? _(" [Backwards]") :
#endif
	"", "", buf);

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

    free(backupstring);
    backupstring = NULL;

    /* Cancel any search, or just return with no previous search. */
    if (i == -1 || (i < 0 && last_search[0] == '\0') ||
	    (i == 0 && answer[0] == '\0')) {
	statusbar(_("Cancelled"));
	return -1;
    } else {
	switch (i) {
	    case -2:		/* It's an empty string. */
	    case 0:		/* It's a new string. */
#ifdef HAVE_REGEX_H
		/* Use last_search if answer is an empty string, or
		 * answer if it isn't. */
		if (ISSET(USE_REGEXP) &&
			regexp_init((i == -2) ? last_search :
			answer) == 0)
		    return -1;
#endif
		break;
#ifndef NANO_TINY
	    case TOGGLE_CASE_KEY:
		TOGGLE(CASE_SENSITIVE);
		backupstring = mallocstrcpy(backupstring, answer);
		return 1;
	    case TOGGLE_BACKWARDS_KEY:
		TOGGLE(BACKWARDS_SEARCH);
		backupstring = mallocstrcpy(backupstring, answer);
		return 1;
#endif
#ifdef HAVE_REGEX_H
	    case NANO_REGEXP_KEY:
		TOGGLE(USE_REGEXP);
		backupstring = mallocstrcpy(backupstring, answer);
		return 1;
#endif
	    default:
		return -1;
	}
    }

    return 0;
}

/* Look for needle.  If no_sameline is TRUE, skip over selected when
 * looking for needle.  begin is the location of the filename where we
 * first started searching.  The return value specifies whether we found
 * anything. */
bool findnextfile(bool no_sameline, size_t begin, const char *needle)
{
    size_t currselected = selected;
	/* The location in the current file list of the match we
	 * find. */
879
    const char *filetail = tail(filelist[currselected]);
880
	/* The filename we display, minus the path. */
881
    const char *rev_start = filetail, *found = NULL;
882
883
884

#ifndef NANO_TINY
    if (ISSET(BACKWARDS_SEARCH))
885
	rev_start += strlen(rev_start);
886
887
888
889
#endif

    /* Look for needle in the current filename we're searching. */
    while (TRUE) {
890
	found = strstrwrapper(filetail, needle, rev_start);
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929

	/* We've found a potential match.  If we're not allowed to find
	 * a match on the same filename we started on and this potential
	 * match is on that line, continue searching. */
	if (found != NULL && (!no_sameline || currselected != begin))
	    break;

	/* We've finished processing the filenames, so get out. */
	if (search_last_file) {
	    not_found_msg(needle);
	    return FALSE;
	}

	/* Move to the previous or next filename in the list.  If we've
	 * reached the start or end of the list, wrap around. */
#ifndef NANO_TINY
	if (ISSET(BACKWARDS_SEARCH)) {
	    if (currselected > 0)
		currselected--;
	    else {
		currselected = filelist_len - 1;
		statusbar(_("Search Wrapped"));
	    }
	} else {
#endif
	    if (currselected < filelist_len - 1)
		currselected++;
	    else {
		currselected = 0;
		statusbar(_("Search Wrapped"));
	    }
#ifndef NANO_TINY
	}
#endif

	/* We've reached the original starting file. */
	if (currselected == begin)
	    search_last_file = TRUE;

930
931
932
	filetail = tail(filelist[currselected]);

	rev_start = filetail;
933
934
#ifndef NANO_TINY
	if (ISSET(BACKWARDS_SEARCH))
935
	    rev_start += strlen(rev_start);
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
#endif
    }

    /* We've definitely found something. */
    selected = currselected;

    return TRUE;
}

/* Clear the flag indicating that a search reached the last file in the
 * list.  We need to do this just before a new search. */
void findnextfile_wrap_reset(void)
{
    search_last_file = FALSE;
}

/* Abort the current filename search.  Clean up by setting the current
 * shortcut list to the browser shortcut list, displaying it, and
 * decompiling the compiled regular expression we used in the last
 * search, if any. */
void filesearch_abort(void)
{
    currshortcut = browser_list;
    bottombars(browser_list);
#ifdef HAVE_REGEX_H
    regexp_cleanup();
#endif
}

/* Search for a filename. */
void do_filesearch(void)
{
    size_t begin = selected;
    int i;
    bool didfind;

    i = filesearch_init();
    if (i == -1)	/* Cancel, blank search string, or regcomp()
			 * failed. */
	filesearch_abort();
#if !defined(NANO_TINY) || defined(HAVE_REGEX_H)
    else if (i == 1)	/* Case Sensitive, Backwards, or Regexp search
			 * toggle. */
	do_filesearch();
#endif

    if (i != 0)
	return;

    /* If answer is now "", copy last_search into answer. */
    if (answer[0] == '\0')
	answer = mallocstrcpy(answer, last_search);
    else
	last_search = mallocstrcpy(last_search, answer);

#ifndef NANO_TINY
    /* If answer is not "", add this search string to the search history
     * list. */
    if (answer[0] != '\0')
	update_history(&search_history, answer);
#endif

    findnextfile_wrap_reset();
    didfind = findnextfile(FALSE, begin, answer);

    /* Check to see if there's only one occurrence of the string and
     * we're on it now. */
    if (selected == begin && didfind) {
	/* Do the search again, skipping over the current 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. */
	didfind = findnextfile(TRUE, begin, answer);
	if (selected == begin && !didfind)
	    statusbar(_("This is the only occurrence"));
    }

    filesearch_abort();
}

/* Search for the last filename without prompting. */
void do_fileresearch(void)
{
    size_t begin = selected;
    bool didfind;

    search_init_globals();

    if (last_search[0] != '\0') {
#ifdef HAVE_REGEX_H
	/* Since answer is "", use last_search! */
	if (ISSET(USE_REGEXP) && regexp_init(last_search) == 0)
	    return;
#endif

	findnextfile_wrap_reset();
	didfind = findnextfile(FALSE, begin, answer);

	/* Check to see if there's only one occurrence of the string and
	 * we're on it now. */
	if (selected == begin && didfind) {
	    /* Do the search again, skipping over the current 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. */
	    didfind = findnextfile(TRUE, begin, answer);
	    if (selected == begin && !didfind)
		statusbar(_("This is the only occurrence"));
	}
    } else
        statusbar(_("No current search pattern"));

    filesearch_abort();
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1050
/* Select the first file in the list. */
1051
1052
1053
1054
1055
void do_first_file(void)
{
    selected = 0;
}

David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1056
/* Select the last file in the list. */
1057
1058
1059
1060
1061
void do_last_file(void)
{
    selected = filelist_len - 1;
}

1062
1063
1064
1065
/* 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
1066
{
1067
    char *retval, *tmp;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1068
1069
1070

    assert(path != NULL);

1071
1072
1073
    retval = mallocstrcpy(NULL, path);

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

    if (tmp != NULL)
1076
1077
1078
 	null_at(&retval, tmp - retval);

    return retval;
David Lawrence Ramsey's avatar
David Lawrence Ramsey committed
1079
1080
}

1081
#endif /* !DISABLE_BROWSER */