1 /**************************************************************************
2  *   browser.c  --  This file is part of GNU nano.                        *
3  *                                                                        *
4  *   Copyright (C) 2001-2011, 2013-2021 Free Software Foundation, Inc.    *
5  *   Copyright (C) 2015-2016, 2020 Benno Schulenberg                      *
6  *                                                                        *
7  *   GNU nano is free software: you can redistribute it and/or modify     *
8  *   it under the terms of the GNU General Public License as published    *
9  *   by the Free Software Foundation, either version 3 of the License,    *
10  *   or (at your option) any later version.                               *
11  *                                                                        *
12  *   GNU nano is distributed in the hope that it will be useful,          *
13  *   but WITHOUT ANY WARRANTY; without even the implied warranty          *
14  *   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.              *
15  *   See the GNU General Public License for more details.                 *
16  *                                                                        *
17  *   You should have received a copy of the GNU General Public License    *
18  *   along with this program.  If not, see http://www.gnu.org/licenses/.  *
19  *                                                                        *
20  **************************************************************************/
21 
22 #include "prototypes.h"
23 
24 #ifdef ENABLE_BROWSER
25 
26 #include <errno.h>
27 #include <stdint.h>
28 #include <string.h>
29 #include <unistd.h>
30 
31 static char **filelist = NULL;
32 		/* The list of files to display in the file browser. */
33 static size_t list_length = 0;
34 		/* The number of files in the list. */
35 static size_t width = 0;
36 		/* The number of files that we can display per screen row. */
37 static size_t longest = 0;
38 		/* The number of columns in the longest filename in the list. */
39 static size_t selected = 0;
40 		/* The currently selected filename in the list; zero-based. */
41 
42 /* Set filelist to the list of files contained in the directory path,
43  * set list_length to the number of files in that list, set longest to
44  * the width in columns of the longest filename in that list (between 15
45  * and COLS), and set width to the number of files that we can display
46  * per screen row.  And sort the list too. */
read_the_list(const char * path,DIR * dir)47 void read_the_list(const char *path, DIR *dir)
48 {
49 	size_t path_len = strlen(path), index = 0;
50 	const struct dirent *nextdir;
51 
52 	longest = 0;
53 
54 	/* Find the length of the longest filename in the current folder. */
55 	while ((nextdir = readdir(dir)) != NULL) {
56 		size_t name_len = breadth(nextdir->d_name);
57 
58 		if (name_len > longest)
59 			longest = name_len;
60 
61 		index++;
62 	}
63 
64 	/* Put 10 characters' worth of blank space between columns of filenames
65 	 * in the list whenever possible, as Pico does. */
66 	longest += 10;
67 
68 	/* If needed, make room for ".. (parent dir)". */
69 	if (longest < 15)
70 		longest = 15;
71 	/* Make sure we're not wider than the window. */
72 	if (longest > COLS)
73 		longest = COLS;
74 
75 	rewinddir(dir);
76 
77 	free_chararray(filelist, list_length);
78 
79 	list_length = index;
80 	index = 0;
81 
82 	filelist = nmalloc(list_length * sizeof(char *));
83 
84 	while ((nextdir = readdir(dir)) != NULL && index < list_length) {
85 		/* Don't show the "." entry. */
86 		if (strcmp(nextdir->d_name, ".") == 0)
87 			continue;
88 
89 		filelist[index] = nmalloc(path_len + strlen(nextdir->d_name) + 1);
90 		sprintf(filelist[index], "%s%s", path, nextdir->d_name);
91 
92 		index++;
93 	}
94 
95 	/* Maybe the number of files in the directory decreased between the
96 	 * first time we scanned and the second time.  index is the actual
97 	 * length of the file list, so record it. */
98 	list_length = index;
99 
100 	/* Sort the list of names. */
101 	qsort(filelist, list_length, sizeof(char *), diralphasort);
102 
103 	/* Calculate how many files fit on a line -- feigning room for two
104 	 * spaces beyond the right edge, and adding two spaces of padding
105 	 * between columns. */
106 	width = (COLS + 2) / (longest + 2);
107 }
108 
109 /* Look for needle.  If we find it, set selected to its location.
110  * Note that needle must be an exact match for a file in the list. */
browser_select_dirname(const char * needle)111 void browser_select_dirname(const char *needle)
112 {
113 	size_t looking_at = 0;
114 
115 	for (; looking_at < list_length; looking_at++) {
116 		if (strcmp(filelist[looking_at], needle) == 0) {
117 			selected = looking_at;
118 			break;
119 		}
120 	}
121 
122 	/* If the sought name isn't found, move the highlight so that the
123 	 * changed selection will be noticed. */
124 	if (looking_at == list_length) {
125 		--selected;
126 
127 		/* Make sure we stay within the available range. */
128 		if (selected >= list_length)
129 			selected = list_length - 1;
130 	}
131 }
132 
133 /* Display at most a screenful of filenames from the gleaned filelist. */
browser_refresh(void)134 void browser_refresh(void)
135 {
136 	int row = 0, col = 0;
137 		/* The current row and column while the list is getting displayed. */
138 	int the_row = 0, the_column = 0;
139 		/* The row and column of the selected item. */
140 	char *info;
141 		/* The additional information that we'll display about a file. */
142 
143 	titlebar(present_path);
144 	blank_edit();
145 
146 	for (size_t index = selected - selected % (editwinrows * width);
147 					index < list_length && row < editwinrows; index++) {
148 		const char *thename = tail(filelist[index]);
149 				/* The filename we display, minus the path. */
150 		size_t namelen = breadth(thename);
151 				/* The length of the filename in columns. */
152 		size_t infolen;
153 				/* The length of the file information in columns. */
154 		size_t infomaxlen = 7;
155 				/* The maximum length of the file information in columns:
156 				 * normally seven, but will be twelve for "(parent dir)". */
157 		bool dots = (COLS >= 15 && namelen >= longest - infomaxlen);
158 				/* Whether to put an ellipsis before the filename?  We don't
159 				 * waste space on dots when there are fewer than 15 columns. */
160 		char *disp = display_string(thename, dots ?
161 				namelen + infomaxlen + 4 - longest : 0, longest, FALSE, FALSE);
162 				/* The filename (or a fragment of it) in displayable format.
163 				 * When a fragment, account for dots plus one space padding. */
164 		struct stat state;
165 
166 		/* If this is the selected item, draw its highlighted bar upfront, and
167 		 * remember its location to be able to place the cursor on it. */
168 		if (index == selected) {
169 			wattron(edit, interface_color_pair[SELECTED_TEXT]);
170 			mvwprintw(edit, row, col, "%*s", longest, " ");
171 			the_row = row;
172 			the_column = col;
173 		}
174 
175 		/* If the name is too long, we display something like "...ename". */
176 		if (dots)
177 			mvwaddstr(edit, row, col, "...");
178 		mvwaddstr(edit, row, dots ? col + 3 : col, disp);
179 
180 		col += longest;
181 
182 		/* Show information about the file: "--" for symlinks (except when
183 		 * they point to a directory) and for files that have disappeared,
184 		 * "(dir)" for directories, and the file size for normal files. */
185 		if (lstat(filelist[index], &state) == -1 || S_ISLNK(state.st_mode)) {
186 			if (stat(filelist[index], &state) == -1 || !S_ISDIR(state.st_mode))
187 				info = copy_of("--");
188 			else
189 				/* TRANSLATORS: Try to keep this at most 7 characters. */
190 				info = copy_of(_("(dir)"));
191 		} else if (S_ISDIR(state.st_mode)) {
192 			if (strcmp(thename, "..") == 0) {
193 				/* TRANSLATORS: Try to keep this at most 12 characters. */
194 				info = copy_of(_("(parent dir)"));
195 				infomaxlen = 12;
196 			} else
197 				info = copy_of(_("(dir)"));
198 		} else {
199 			off_t result = state.st_size;
200 			char modifier;
201 
202 			info = nmalloc(infomaxlen + 1);
203 
204 			/* Massage the file size into a human-readable form. */
205 			if (state.st_size < (1 << 10))
206 				modifier = ' ';  /* bytes */
207 			else if (state.st_size < (1 << 20)) {
208 				result >>= 10;
209 				modifier = 'K';  /* kilobytes */
210 			} else if (state.st_size < (1 << 30)) {
211 				result >>= 20;
212 				modifier = 'M';  /* megabytes */
213 			} else {
214 				result >>= 30;
215 				modifier = 'G';  /* gigabytes */
216 			}
217 
218 			/* Show the size if less than a terabyte, else show "(huge)". */
219 			if (result < (1 << 10))
220 				sprintf(info, "%4ju %cB", (intmax_t)result, modifier);
221 			else
222 				/* TRANSLATORS: Try to keep this at most 7 characters.
223 				 * If necessary, you can leave out the parentheses. */
224 				info = mallocstrcpy(info, _("(huge)"));
225 		}
226 
227 		/* Make sure info takes up no more than infomaxlen columns. */
228 		infolen = breadth(info);
229 		if (infolen > infomaxlen) {
230 			info[actual_x(info, infomaxlen)] = '\0';
231 			infolen = infomaxlen;
232 		}
233 
234 		mvwaddstr(edit, row, col - infolen, info);
235 
236 		/* If this is the selected item, finish its highlighting. */
237 		if (index == selected)
238 			wattroff(edit, interface_color_pair[SELECTED_TEXT]);
239 
240 		free(disp);
241 		free(info);
242 
243 		/* Add some space between the columns. */
244 		col += 2;
245 
246 		/* If the next entry will not fit on this row, move to next row. */
247 		if (col > COLS - longest) {
248 			row++;
249 			col = 0;
250 		}
251 	}
252 
253 	/* If requested, put the cursor on the selected item and switch it on. */
254 	if (ISSET(SHOW_CURSOR)) {
255 		wmove(edit, the_row, the_column);
256 		curs_set(1);
257 	}
258 
259 	wnoutrefresh(edit);
260 }
261 
262 /* Look for the given needle in the list of files.  If forwards is TRUE,
263  * search forward in the list; otherwise, search backward. */
findfile(const char * needle,bool forwards)264 void findfile(const char *needle, bool forwards)
265 {
266 	size_t looking_at = selected;
267 		/* The location in the file list of the filename we're looking at. */
268 	const char *thename;
269 		/* The plain filename, without the path. */
270 	unsigned stash[sizeof(flags) / sizeof(flags[0])];
271 		/* A storage place for the current flag settings. */
272 
273 	/* Save the settings of all flags. */
274 	memcpy(stash, flags, sizeof(flags));
275 
276 	/* Search forward, case insensitive, and without regexes. */
277 	UNSET(BACKWARDS_SEARCH);
278 	UNSET(CASE_SENSITIVE);
279 	UNSET(USE_REGEXP);
280 
281 	/* Step through each filename in the list until a match is found or
282 	 * we've come back to the point where we started. */
283 	while (TRUE) {
284 		if (forwards) {
285 			if (looking_at++ == list_length - 1) {
286 				looking_at = 0;
287 				statusbar(_("Search Wrapped"));
288 			}
289 		} else {
290 			if (looking_at-- == 0) {
291 				looking_at = list_length - 1;
292 				statusbar(_("Search Wrapped"));
293 			}
294 		}
295 
296 		/* Get the bare filename, without the path. */
297 		thename = tail(filelist[looking_at]);
298 
299 		/* If the needle matches, we're done.  And if we're back at the file
300 		 * where we started, it is the only occurrence. */
301 		if (strstrwrapper(thename, needle, thename)) {
302 			if (looking_at == selected)
303 				statusbar(_("This is the only occurrence"));
304 			break;
305 		}
306 
307 		/* If we're back at the beginning and didn't find any match... */
308 		if (looking_at == selected) {
309 			not_found_msg(needle);
310 			break;
311 		}
312 	}
313 
314 	/* Restore the settings of all flags. */
315 	memcpy(flags, stash, sizeof(flags));
316 
317 	/* Select the one we've found. */
318 	selected = looking_at;
319 }
320 
321 /* Prepare the prompt and ask the user what to search for; then search for it.
322  * If forwards is TRUE, search forward in the list; otherwise, search backward. */
search_filename(bool forwards)323 void search_filename(bool forwards)
324 {
325 	char *thedefault;
326 	int response;
327 
328 	/* If something was searched for before, show it between square brackets. */
329 	if (*last_search != '\0') {
330 		char *disp = display_string(last_search, 0, COLS / 3, FALSE, FALSE);
331 
332 		thedefault = nmalloc(strlen(disp) + 7);
333 		/* We use (COLS / 3) here because we need to see more on the line. */
334 		sprintf(thedefault, " [%s%s]", disp,
335 				(breadth(last_search) > COLS / 3) ? "..." : "");
336 		free(disp);
337 	} else
338 		thedefault = copy_of("");
339 
340 	/* Now ask what to search for. */
341 	response = do_prompt(MWHEREISFILE, "", &search_history,
342 						browser_refresh, "%s%s%s", _("Search"),
343 						/* TRANSLATORS: A modifier of the Search prompt. */
344 						!forwards ? _(" [Backwards]") : "", thedefault);
345 	free(thedefault);
346 
347 	/* If the user cancelled, or typed <Enter> on a blank answer and
348 	 * nothing was searched for yet during this session, get out. */
349 	if (response == -1 || (response == -2 && *last_search == '\0')) {
350 		statusbar(_("Cancelled"));
351 		return;
352 	}
353 
354 	/* If the user typed an answer, remember it. */
355 	if (*answer != '\0') {
356 		last_search = mallocstrcpy(last_search, answer);
357 #ifdef ENABLE_HISTORIES
358 		update_history(&search_history, answer);
359 #endif
360 	}
361 
362 	if (response == 0 || response == -2)
363 		findfile(last_search, forwards);
364 }
365 
366 /* Search again without prompting for the last given search string,
367  * either forwards or backwards. */
research_filename(bool forwards)368 void research_filename(bool forwards)
369 {
370 #ifdef ENABLE_HISTORIES
371 	/* If nothing was searched for yet, take the last item from history. */
372 	if (*last_search == '\0' && searchbot->prev != NULL)
373 		last_search = mallocstrcpy(last_search, searchbot->prev->data);
374 #endif
375 
376 	if (*last_search == '\0')
377 		statusbar(_("No current search pattern"));
378 	else {
379 		wipe_statusbar();
380 		findfile(last_search, forwards);
381 	}
382 }
383 
384 /* Select the first file in the list -- called by ^W^Y. */
to_first_file(void)385 void to_first_file(void)
386 {
387 	selected = 0;
388 }
389 
390 /* Select the last file in the list -- called by ^W^V. */
to_last_file(void)391 void to_last_file(void)
392 {
393 	selected = list_length - 1;
394 }
395 
396 /* Strip one element from the end of path, and return the stripped path.
397  * The returned string is dynamically allocated, and should be freed. */
strip_last_component(const char * path)398 char *strip_last_component(const char *path)
399 {
400 	char *copy = copy_of(path);
401 	char *last_slash = strrchr(copy, '/');
402 
403 	if (last_slash != NULL)
404 		*last_slash = '\0';
405 
406 	return copy;
407 }
408 
409 /* Allow the user to browse through the directories in the filesystem,
410  * starting at the given path. */
browse(char * path)411 char *browse(char *path)
412 {
413 	char *present_name = NULL;
414 		/* The name of the currently selected file, or of the directory we
415 		 * were in before backing up to "..". */
416 	size_t old_selected;
417 		/* The number of the selected file before the current selected file. */
418 	DIR *dir;
419 		/* The directory whose contents we are showing. */
420 	char *chosen = NULL;
421 		/* The name of the file that the user picked, or NULL if none. */
422 
423   read_directory_contents:
424 		/* We come here when the user refreshes or selects a new directory. */
425 
426 	path = free_and_assign(path, get_full_path(path));
427 
428 	if (path != NULL)
429 		dir = opendir(path);
430 
431 	if (path == NULL || dir == NULL) {
432 		statusline(ALERT, _("Cannot open directory: %s"), strerror(errno));
433 		/* If we don't have a file list yet, there is nothing to show. */
434 		if (filelist == NULL) {
435 			lastmessage = VACUUM;
436 			free(present_name);
437 			free(path);
438 			napms(1200);
439 			return NULL;
440 		}
441 		path = mallocstrcpy(path, present_path);
442 		present_name = mallocstrcpy(present_name, filelist[selected]);
443 	}
444 
445 	if (dir != NULL) {
446 		/* Get the file list, and set longest and width in the process. */
447 		read_the_list(path, dir);
448 		closedir(dir);
449 		dir = NULL;
450 	}
451 
452 	/* If given, reselect the present_name and then discard it. */
453 	if (present_name != NULL) {
454 		browser_select_dirname(present_name);
455 
456 		free(present_name);
457 		present_name = NULL;
458 	/* Otherwise, select the first file or directory in the list. */
459 	} else
460 		selected = 0;
461 
462 	old_selected = (size_t)-1;
463 
464 	present_path = mallocstrcpy(present_path, path);
465 
466 	titlebar(path);
467 
468 	while (TRUE) {
469 		functionptrtype func;
470 		int kbinput;
471 
472 		lastmessage = VACUUM;
473 
474 		bottombars(MBROWSER);
475 
476 		/* Display (or redisplay) the file list if the list itself or
477 		 * the selected file has changed. */
478 		if (old_selected != selected || ISSET(SHOW_CURSOR))
479 			browser_refresh();
480 
481 		old_selected = selected;
482 
483 		kbinput = get_kbinput(edit, ISSET(SHOW_CURSOR));
484 
485 #ifdef ENABLE_MOUSE
486 		if (kbinput == KEY_MOUSE) {
487 			int mouse_x, mouse_y;
488 
489 			/* We can click on the edit window to select a filename. */
490 			if (get_mouseinput(&mouse_y, &mouse_x, TRUE) == 0 &&
491 						wmouse_trafo(edit, &mouse_y, &mouse_x, FALSE)) {
492 				/* longest is the width of each column.  There
493 				 * are two spaces between each column. */
494 				selected = selected - selected % (editwinrows * width) +
495 								(mouse_y * width) + (mouse_x / (longest + 2));
496 
497 				/* If they clicked beyond the end of a row,
498 				 * select the last filename in that row. */
499 				if (mouse_x > width * (longest + 2))
500 					selected--;
501 
502 				/* If we're beyond the list, select the last filename. */
503 				if (selected > list_length - 1)
504 					selected = list_length - 1;
505 
506 				/* If we selected the same filename as last time, fake a
507 				 * press of the Enter key so that the file is read in. */
508 				if (old_selected == selected)
509 					kbinput = KEY_ENTER;
510 			}
511 
512 			if (kbinput == KEY_MOUSE)
513 				continue;
514 		}
515 #endif /* ENABLE_MOUSE */
516 #ifndef NANO_TINY
517 		if (bracketed_paste || kbinput == BRACKETED_PASTE_MARKER) {
518 			beep();
519 			continue;
520 		}
521 #endif
522 		func = interpret(&kbinput);
523 
524 		if (func == full_refresh) {
525 			full_refresh();
526 #ifndef NANO_TINY
527 			/* Simulate a window resize to force a directory reread. */
528 			kbinput = KEY_WINCH;
529 #endif
530 		} else if (func == do_help) {
531 			do_help();
532 #ifndef NANO_TINY
533 			/* The window dimensions might have changed, so act as if. */
534 			kbinput = KEY_WINCH;
535 #endif
536 #ifndef NANO_TINY
537 		} else if (func == do_toggle_void) {
538 			TOGGLE(NO_HELP);
539 			window_init();
540 			kbinput = KEY_WINCH;
541 #endif
542 		} else if (func == do_search_backward) {
543 			search_filename(BACKWARD);
544 		} else if (func == do_search_forward) {
545 			search_filename(FORWARD);
546 		} else if (func == do_findprevious) {
547 			research_filename(BACKWARD);
548 		} else if (func == do_findnext) {
549 			research_filename(FORWARD);
550 		} else if (func == do_left) {
551 			if (selected > 0)
552 				selected--;
553 		} else if (func == do_right) {
554 			if (selected < list_length - 1)
555 				selected++;
556 		} else if (func == to_prev_word) {
557 			selected -= (selected % width);
558 		} else if (func == to_next_word) {
559 			selected += width - 1 - (selected % width);
560 			if (selected >= list_length)
561 				selected = list_length - 1;
562 		} else if (func == do_up) {
563 			if (selected >= width)
564 				selected -= width;
565 		} else if (func == do_down) {
566 			if (selected + width <= list_length - 1)
567 				selected += width;
568 		} else if (func == to_prev_block) {
569 			selected = ((selected / (editwinrows * width)) *
570 								editwinrows * width) + selected % width;
571 		} else if (func == to_next_block) {
572 			selected = ((selected / (editwinrows * width)) *
573 								editwinrows * width) + selected % width +
574 								editwinrows * width - width;
575 			if (selected >= list_length)
576 				selected = (list_length / width) * width + selected % width;
577 			if (selected >= list_length)
578 				selected -= width;
579 		} else if (func == do_page_up) {
580 			if (selected < width)
581 				selected = 0;
582 			else if (selected < editwinrows * width)
583 				selected = selected % width;
584 			else
585 				selected -= editwinrows * width;
586 		} else if (func == do_page_down) {
587 			if (selected + width >= list_length - 1)
588 				selected = list_length - 1;
589 			else if (selected + editwinrows * width >= list_length)
590 				selected = (selected + editwinrows * width - list_length) %
591 								width + list_length - width;
592 			else
593 				selected += editwinrows * width;
594 		} else if (func == to_first_file) {
595 			selected = 0;
596 		} else if (func == to_last_file) {
597 			selected = list_length - 1;
598 		} else if (func == goto_dir) {
599 			/* Ask for the directory to go to. */
600 			if (do_prompt(MGOTODIR, "", NULL,
601 							/* TRANSLATORS: This is a prompt. */
602 							browser_refresh, _("Go To Directory")) < 0) {
603 				statusbar(_("Cancelled"));
604 				continue;
605 			}
606 
607 			path = free_and_assign(path, real_dir_from_tilde(answer));
608 
609 			/* If the given path is relative, join it with the current path. */
610 			if (*path != '/') {
611 				path = nrealloc(path, strlen(present_path) +
612 												strlen(answer) + 1);
613 				sprintf(path, "%s%s", present_path, answer);
614 			}
615 
616 #ifdef ENABLE_OPERATINGDIR
617 			if (outside_of_confinement(path, FALSE)) {
618 				/* TRANSLATORS: This refers to the confining effect of the
619 				 * option --operatingdir, not of --restricted. */
620 				statusline(ALERT, _("Can't go outside of %s"), operating_dir);
621 				path = mallocstrcpy(path, present_path);
622 				continue;
623 			}
624 #endif
625 			/* Snip any trailing slashes, so the name can be compared. */
626 			while (strlen(path) > 1 && path[strlen(path) - 1] == '/')
627 				path[strlen(path) - 1] = '\0';
628 
629 			/* In case the specified directory cannot be entered, select it
630 			 * (if it is in the current list) so it will be highlighted. */
631 			for (size_t j = 0; j < list_length; j++)
632 				if (strcmp(filelist[j], path) == 0)
633 					selected = j;
634 
635 			/* Try opening and reading the specified directory. */
636 			goto read_directory_contents;
637 		} else if (func == do_enter) {
638 			struct stat st;
639 
640 			/* It isn't possible to move up from the root directory. */
641 			if (strcmp(filelist[selected], "/..") == 0) {
642 				statusline(ALERT, _("Can't move up a directory"));
643 				continue;
644 			}
645 
646 #ifdef ENABLE_OPERATINGDIR
647 			/* Note: The selected file can be outside the operating
648 			 * directory if it's ".." or if it's a symlink to a
649 			 * directory outside the operating directory. */
650 			if (outside_of_confinement(filelist[selected], FALSE)) {
651 				statusline(ALERT, _("Can't go outside of %s"), operating_dir);
652 				continue;
653 			}
654 #endif
655 			/* If for some reason the file is inaccessible, complain. */
656 			if (stat(filelist[selected], &st) == -1) {
657 				statusline(ALERT, _("Error reading %s: %s"),
658 								filelist[selected], strerror(errno));
659 				continue;
660 			}
661 
662 			/* If it isn't a directory, a file was selected -- we're done. */
663 			if (!S_ISDIR(st.st_mode)) {
664 				chosen = copy_of(filelist[selected]);
665 				break;
666 			}
667 
668 			/* If we are moving up one level, remember where we came from, so
669 			 * this directory can be highlighted and easily reentered. */
670 			if (strcmp(tail(filelist[selected]), "..") == 0)
671 				present_name = strip_last_component(filelist[selected]);
672 
673 			/* Try opening and reading the selected directory. */
674 			path = mallocstrcpy(path, filelist[selected]);
675 			goto read_directory_contents;
676 #ifdef ENABLE_NANORC
677 		} else if (func == (functionptrtype)implant) {
678 			implant(first_sc_for(MBROWSER, func)->expansion);
679 #endif
680 #ifndef NANO_TINY
681 		} else if (kbinput == KEY_WINCH) {
682 			;  /* Nothing to do. */
683 #endif
684 		} else if (func == do_exit) {
685 			break;
686 		} else
687 			unbound_key(kbinput);
688 
689 #ifndef NANO_TINY
690 		/* If the window resized, refresh the file list. */
691 		if (kbinput == KEY_WINCH) {
692 			/* Remember the selected file, to be able to reselect it. */
693 			present_name = copy_of(filelist[selected]);
694 			/* Reread the contents of the current directory. */
695 			goto read_directory_contents;
696 		}
697 #endif
698 	}
699 
700 	titlebar(NULL);
701 	edit_refresh();
702 
703 	free(path);
704 
705 	free_chararray(filelist, list_length);
706 	filelist = NULL;
707 	list_length = 0;
708 
709 	return chosen;
710 }
711 
712 /* Prepare to start browsing.  If the given path has a directory part,
713  * start browsing in that directory, otherwise in the current directory. */
browse_in(const char * inpath)714 char *browse_in(const char *inpath)
715 {
716 	char *path = real_dir_from_tilde(inpath);
717 	struct stat fileinfo;
718 
719 	/* If path is not a directory, try to strip a filename from it; if then
720 	 * still not a directory, use the current working directory instead. */
721 	if (stat(path, &fileinfo) == -1 || !S_ISDIR(fileinfo.st_mode)) {
722 		path = free_and_assign(path, strip_last_component(path));
723 
724 		if (stat(path, &fileinfo) == -1 || !S_ISDIR(fileinfo.st_mode)) {
725 			char *currentdir = nmalloc(PATH_MAX + 1);
726 
727 			path = free_and_assign(path, getcwd(currentdir, PATH_MAX + 1));
728 
729 			if (path == NULL) {
730 				statusline(MILD, _("The working directory has disappeared"));
731 				free(currentdir);
732 				beep();
733 				napms(1200);
734 				return NULL;
735 			}
736 		}
737 	}
738 
739 #ifdef ENABLE_OPERATINGDIR
740 	/* If the resulting path isn't in the operating directory, use
741 	 * the operating directory instead. */
742 	if (outside_of_confinement(path, FALSE))
743 		path = mallocstrcpy(path, operating_dir);
744 #endif
745 
746 	return browse(path);
747 }
748 
749 #endif /* ENABLE_BROWSER */
750