1 /*
2  * BSD 2-Clause License
3  *
4  * Copyright (C) 2014-2016, Lazaros Koromilas <lostd@2f30.org>
5  * Copyright (C) 2014-2016, Dimitris Papastamos <sin@2f30.org>
6  * Copyright (C) 2016-2021, Arun Prakash Jana <engineerarun@gmail.com>
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions are met:
11  *
12  * * Redistributions of source code must retain the above copyright notice, this
13  *   list of conditions and the following disclaimer.
14  *
15  * * Redistributions in binary form must reproduce the above copyright notice,
16  *   this list of conditions and the following disclaimer in the documentation
17  *   and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 #if defined(__linux__) || defined(MINGW) || defined(__MINGW32__) \
32 	|| defined(__MINGW64__) || defined(__CYGWIN__)
33 #ifndef _GNU_SOURCE
34 #define _GNU_SOURCE
35 #endif
36 #if defined(__arm__) || defined(__i386__)
37 #define _FILE_OFFSET_BITS 64 /* Support large files on 32-bit */
38 #endif
39 #if defined(__linux__)
40 #include <sys/inotify.h>
41 #define LINUX_INOTIFY
42 #endif
43 #if !defined(__GLIBC__)
44 #include <sys/types.h>
45 #endif
46 #endif
47 #include <sys/resource.h>
48 #include <sys/stat.h>
49 #include <sys/statvfs.h>
50 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) || defined(__DragonFly__)
51 #include <sys/types.h>
52 #include <sys/event.h>
53 #include <sys/time.h>
54 #define BSD_KQUEUE
55 #elif defined(__HAIKU__)
56 #include "../misc/haiku/haiku_interop.h"
57 #define HAIKU_NM
58 #else
59 #include <sys/sysmacros.h>
60 #endif
61 #include <sys/wait.h>
62 
63 #ifdef __linux__ /* Fix failure due to mvaddnwstr() */
64 #ifndef NCURSES_WIDECHAR
65 #define NCURSES_WIDECHAR 1
66 #endif
67 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) \
68 	|| defined(__APPLE__) || defined(__sun)
69 #ifndef _XOPEN_SOURCE_EXTENDED
70 #define _XOPEN_SOURCE_EXTENDED
71 #endif
72 #endif
73 #ifndef __USE_XOPEN /* Fix wcswidth() failure, ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
74 #define __USE_XOPEN
75 #endif
76 #include <dirent.h>
77 #include <errno.h>
78 #include <fcntl.h>
79 #include <fts.h>
80 #include <libgen.h>
81 #include <limits.h>
82 #ifndef NOLC
83 #include <locale.h>
84 #endif
85 #include <pthread.h>
86 #include <stdio.h>
87 #ifndef NORL
88 #include <readline/history.h>
89 #include <readline/readline.h>
90 #endif
91 #ifdef PCRE
92 #include <pcre.h>
93 #else
94 #include <regex.h>
95 #endif
96 #include <signal.h>
97 #include <stdarg.h>
98 #include <stdlib.h>
99 #include <string.h>
100 #include <strings.h>
101 #include <time.h>
102 #include <unistd.h>
103 #ifndef __USE_XOPEN_EXTENDED
104 #define __USE_XOPEN_EXTENDED 1
105 #endif
106 #include <ftw.h>
107 #include <wchar.h>
108 #include <pwd.h>
109 #include <grp.h>
110 
111 #ifdef MACOS_BELOW_1012
112 #include "../misc/macos-legacy/mach_gettime.h"
113 #endif
114 
115 #if !defined(alloca) && defined(__GNUC__)
116 /*
117  * GCC doesn't expand alloca() to __builtin_alloca() in standards mode
118  * (-std=...) and not all standard libraries do or supply it, e.g.
119  * NetBSD/arm64 so explicitly use the builtin.
120  */
121 #define alloca(size) __builtin_alloca(size)
122 #endif
123 
124 #include "nnn.h"
125 #include "dbg.h"
126 
127 #if defined(ICONS) || defined(NERD)
128 #include "icons.h"
129 #define ICONS_ENABLED
130 #endif
131 
132 #ifdef TOURBIN_QSORT
133 #include "qsort.h"
134 #endif
135 
136 /* Macro definitions */
137 #define VERSION      "4.3"
138 #define GENERAL_INFO "BSD 2-Clause\nhttps://github.com/jarun/nnn"
139 
140 #ifndef NOSSN
141 #define SESSIONS_VERSION 1
142 #endif
143 
144 #ifndef S_BLKSIZE
145 #define S_BLKSIZE 512 /* S_BLKSIZE is missing on Android NDK (Termux) */
146 #endif
147 
148 /*
149  * NAME_MAX and PATH_MAX may not exist, e.g. with dirent.c_name being a
150  * flexible array on Illumos. Use somewhat accommodating fallback values.
151  */
152 #ifndef NAME_MAX
153 #define NAME_MAX 255
154 #endif
155 
156 #ifndef PATH_MAX
157 #define PATH_MAX 4096
158 #endif
159 
160 #define _ABSSUB(N, M)   (((N) <= (M)) ? ((M) - (N)) : ((N) - (M)))
161 #define ELEMENTS(x)     (sizeof(x) / sizeof(*(x)))
162 #undef MIN
163 #define MIN(x, y)       ((x) < (y) ? (x) : (y))
164 #undef MAX
165 #define MAX(x, y)       ((x) > (y) ? (x) : (y))
166 #define ISODD(x)        ((x) & 1)
167 #define ISBLANK(x)      ((x) == ' ' || (x) == '\t')
168 #define TOUPPER(ch)     (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
169 #define TOLOWER(ch)     (((ch) >= 'A' && (ch) <= 'Z') ? ((ch) - 'A' + 'a') : (ch))
170 #define ISUPPER_(ch)     ((ch) >= 'A' && (ch) <= 'Z')
171 #define ISLOWER_(ch)     ((ch) >= 'a' && (ch) <= 'z')
172 #define CMD_LEN_MAX     (PATH_MAX + ((NAME_MAX + 1) << 1))
173 #define ALIGN_UP(x, A)  ((((x) + (A) - 1) / (A)) * (A))
174 #define READLINE_MAX    256
175 #define FILTER          '/'
176 #define RFILTER         '\\'
177 #define CASE            ':'
178 #define MSGWAIT         '$'
179 #define SELECT          ' '
180 #define PROMPT          ">>> "
181 #define REGEX_MAX       48
182 #define ENTRY_INCR      64 /* Number of dir 'entry' structures to allocate per shot */
183 #define NAMEBUF_INCR    0x800 /* 64 dir entries at once, avg. 32 chars per file name = 64*32B = 2KB */
184 #define DESCRIPTOR_LEN  32
185 #define _ALIGNMENT      0x10 /* 16-byte alignment */
186 #define _ALIGNMENT_MASK 0xF
187 #define TMP_LEN_MAX     64
188 #define DOT_FILTER_LEN  7
189 #define ASCII_MAX       128
190 #define EXEC_ARGS_MAX   10
191 #define LIST_FILES_MAX  (1 << 16)
192 #define SCROLLOFF       3
193 #define COLOR_256       256
194 
195 /* Time intervals */
196 #define DBLCLK_INTERVAL_NS (400000000)
197 #define XDELAY_INTERVAL_MS (350000) /* 350 ms delay */
198 
199 #ifndef CTX8
200 #define CTX_MAX 4
201 #else
202 #define CTX_MAX 8
203 #endif
204 
205 #ifdef __APPLE__
206 #define SED "gsed"
207 #else
208 #define SED "sed"
209 #endif
210 
211 /* Large selection threshold */
212 #ifndef LARGESEL
213 #define LARGESEL 1000
214 #endif
215 
216 #define MIN_DISPLAY_COL (CTX_MAX * 2)
217 #define ARCHIVE_CMD_LEN 16
218 #define BLK_SHIFT_512   9
219 
220 /* Detect hardlinks in du */
221 #define HASH_BITS   (0xFFFFFF)
222 #define HASH_OCTETS (HASH_BITS >> 6) /* 2^6 = 64 */
223 
224 /* Entry flags */
225 #define DIR_OR_DIRLNK 0x01
226 #define HARD_LINK     0x02
227 #define SYM_ORPHAN    0x04
228 #define FILE_MISSING  0x08
229 #define FILE_SELECTED 0x10
230 #define FILE_SCANNED  0x20
231 
232 /* Macros to define process spawn behaviour as flags */
233 #define F_NONE    0x00  /* no flag set */
234 #define F_MULTI   0x01  /* first arg can be combination of args; to be used with F_NORMAL */
235 #define F_NOWAIT  0x02  /* don't wait for child process (e.g. file manager) */
236 #define F_NOTRACE 0x04  /* suppress stdout and stderr (no traces) */
237 #define F_NORMAL  0x08  /* spawn child process in non-curses regular CLI mode */
238 #define F_CONFIRM 0x10  /* run command - show results before exit (must have F_NORMAL) */
239 #define F_CHKRTN  0x20  /* wait for user prompt if cmd returns failure status */
240 #define F_NOSTDIN 0x40  /* suppress stdin */
241 #define F_PAGE    0x80  /* page output in run-cmd-as-plugin mode */
242 #define F_TTY     0x100 /* Force stdout to go to tty if redirected to a non-tty */
243 #define F_CLI     (F_NORMAL | F_MULTI)
244 #define F_SILENT  (F_CLI | F_NOTRACE)
245 
246 /* Version compare macros */
247 /*
248  * states: S_N: normal, S_I: comparing integral part, S_F: comparing
249  *         fractional parts, S_Z: idem but with leading Zeroes only
250  */
251 #define S_N 0x0
252 #define S_I 0x3
253 #define S_F 0x6
254 #define S_Z 0x9
255 
256 /* result_type: VCMP: return diff; VLEN: compare using len_diff/diff */
257 #define VCMP 2
258 #define VLEN 3
259 
260 /* Volume info */
261 #define FREE     0
262 #define CAPACITY 1
263 
264 /* TYPE DEFINITIONS */
265 typedef unsigned int uint_t;
266 typedef unsigned char uchar_t;
267 typedef unsigned short ushort_t;
268 typedef unsigned long long ullong_t;
269 
270 /* STRUCTURES */
271 
272 /* Directory entry */
273 typedef struct entry {
274 	char *name;  /* 8 bytes */
275 	time_t sec;  /* 8 bytes */
276 	uint_t nsec; /* 4 bytes (enough to store nanosec) */
277 	mode_t mode; /* 4 bytes */
278 	off_t size;  /* 8 bytes */
279 	struct {
280 		ullong_t blocks : 40; /* 5 bytes (enough for 512 TiB in 512B blocks allocated) */
281 		ullong_t nlen   : 16; /* 2 bytes (length of file name) */
282 		ullong_t flags  : 8;  /* 1 byte (flags specific to the file) */
283 	};
284 #ifndef NOUG
285 	uid_t uid; /* 4 bytes */
286 	gid_t gid; /* 4 bytes */
287 #endif
288 } *pEntry;
289 
290 /* Selection marker */
291 typedef struct {
292 	char *startpos;
293 	size_t len;
294 } selmark;
295 
296 /* Key-value pairs from env */
297 typedef struct {
298 	int key;
299 	int off;
300 } kv;
301 
302 typedef struct {
303 #ifdef PCRE
304 	const pcre *pcrex;
305 #else
306 	const regex_t *regex;
307 #endif
308 	const char *str;
309 } fltrexp_t;
310 
311 /*
312  * Settings
313  * NOTE: update default values if changing order
314  */
315 typedef struct {
316 	uint_t filtermode : 1;  /* Set to enter filter mode */
317 	uint_t timeorder  : 1;  /* Set to sort by time */
318 	uint_t sizeorder  : 1;  /* Set to sort by file size */
319 	uint_t apparentsz : 1;  /* Set to sort by apparent size (disk usage) */
320 	uint_t blkorder   : 1;  /* Set to sort by blocks used (disk usage) */
321 	uint_t extnorder  : 1;  /* Order by extension */
322 	uint_t showhidden : 1;  /* Set to show hidden files */
323 	uint_t reserved0  : 1;
324 	uint_t showdetail : 1;  /* Clear to show lesser file info */
325 	uint_t ctxactive  : 1;  /* Context active or not */
326 	uint_t reverse    : 1;  /* Reverse sort */
327 	uint_t version    : 1;  /* Version sort */
328 	uint_t reserved1  : 1;
329 	/* The following settings are global */
330 	uint_t curctx     : 3;  /* Current context number */
331 	uint_t prefersel  : 1;  /* Prefer selection over current, if exists */
332 	uint_t reserved2  : 1;
333 	uint_t nonavopen  : 1;  /* Open file on right arrow or `l` */
334 	uint_t autoselect : 1;  /* Auto-select dir in type-to-nav mode */
335 	uint_t cursormode : 1;  /* Move hardware cursor with selection */
336 	uint_t useeditor  : 1;  /* Use VISUAL to open text files */
337 	uint_t reserved3  : 3;
338 	uint_t regex      : 1;  /* Use regex filters */
339 	uint_t x11        : 1;  /* Copy to system clipboard, show notis, xterm title */
340 	uint_t timetype   : 2;  /* Time sort type (0: access, 1: change, 2: modification) */
341 	uint_t cliopener  : 1;  /* All-CLI app opener */
342 	uint_t waitedit   : 1;  /* For ops that can't be detached, used EDITOR */
343 	uint_t rollover   : 1;  /* Roll over at edges */
344 } settings;
345 
346 /* Non-persistent program-internal states (alphabeical order) */
347 typedef struct {
348 	uint_t autofifo   : 1;  /* Auto-create NNN_FIFO */
349 	uint_t autonext   : 1;  /* Auto-proceed on open */
350 	uint_t dircolor   : 1;  /* Current status of dir color */
351 	uint_t dirctx     : 1;  /* Show dirs in context color */
352 	uint_t duinit     : 1;  /* Initialize disk usage */
353 	uint_t fifomode   : 1;  /* FIFO notify mode: 0: preview, 1: explore */
354 	uint_t forcequit  : 1;  /* Do not prompt on quit */
355 	uint_t initfile   : 1;  /* Positional arg is a file */
356 	uint_t interrupt  : 1;  /* Program received an interrupt */
357 	uint_t move       : 1;  /* Move operation */
358 	uint_t oldcolor   : 1;  /* Use older colorscheme */
359 	uint_t picked     : 1;  /* Plugin has picked files */
360 	uint_t picker     : 1;  /* Write selection to user-specified file */
361 	uint_t pluginit   : 1;  /* Plugin framework initialized */
362 	uint_t prstssn    : 1;  /* Persistent session */
363 	uint_t rangesel   : 1;  /* Range selection on */
364 	uint_t runctx     : 3;  /* The context in which plugin is to be run */
365 	uint_t runplugin  : 1;  /* Choose plugin mode */
366 	uint_t selmode    : 1;  /* Set when selecting files */
367 	uint_t stayonsel  : 1;  /* Disable auto-proceed on select */
368 	uint_t trash      : 2;  /* Use trash to delete files 1: trash-cli, 2: gio trash */
369 	uint_t uidgid     : 1;  /* Show owner and group info */
370 	uint_t reserved   : 7;  /* Adjust when adding/removing a field */
371 } runstate;
372 
373 /* Contexts or workspaces */
374 typedef struct {
375 	char c_path[PATH_MAX];     /* Current dir */
376 	char c_last[PATH_MAX];     /* Last visited dir */
377 	char c_name[NAME_MAX + 1]; /* Current file name */
378 	char c_fltr[REGEX_MAX];    /* Current filter */
379 	settings c_cfg;            /* Current configuration */
380 	uint_t color;              /* Color code for directories */
381 } context;
382 
383 #ifndef NOSSN
384 typedef struct {
385 	size_t ver;
386 	size_t pathln[CTX_MAX];
387 	size_t lastln[CTX_MAX];
388 	size_t nameln[CTX_MAX];
389 	size_t fltrln[CTX_MAX];
390 } session_header_t;
391 #endif
392 
393 /* GLOBALS */
394 
395 /* Configuration, contexts */
396 static settings cfg = {
397 	0, /* filtermode */
398 	0, /* timeorder */
399 	0, /* sizeorder */
400 	0, /* apparentsz */
401 	0, /* blkorder */
402 	0, /* extnorder */
403 	0, /* showhidden */
404 	0, /* reserved0 */
405 	0, /* showdetail */
406 	1, /* ctxactive */
407 	0, /* reverse */
408 	0, /* version */
409 	0, /* reserved1 */
410 	0, /* curctx */
411 	0, /* prefersel */
412 	0, /* reserved2 */
413 	0, /* nonavopen */
414 	1, /* autoselect */
415 	0, /* cursormode */
416 	0, /* useeditor */
417 	0, /* reserved3 */
418 	0, /* regex */
419 	0, /* x11 */
420 	2, /* timetype (T_MOD) */
421 	0, /* cliopener */
422 	0, /* waitedit */
423 	1, /* rollover */
424 };
425 
426 static context g_ctx[CTX_MAX] __attribute__ ((aligned));
427 
428 static int ndents, cur, last, curscroll, last_curscroll, total_dents = ENTRY_INCR, scroll_lines = 1;
429 static int nselected;
430 #ifndef NOFIFO
431 static int fifofd = -1;
432 #endif
433 static uint_t idletimeout, selbufpos, selbuflen;
434 static ushort_t xlines, xcols;
435 static ushort_t idle;
436 static uchar_t maxbm, maxplug, maxorder;
437 static uchar_t cfgsort[CTX_MAX + 1];
438 static char *bmstr;
439 static char *pluginstr;
440 static char *orderstr;
441 static char *opener;
442 static char *editor;
443 static char *enveditor;
444 static char *pager;
445 static char *shell;
446 static char *home;
447 static char *initpath;
448 static char *cfgpath;
449 static char *selpath;
450 static char *listpath;
451 static char *listroot;
452 static char *plgpath;
453 static char *pnamebuf, *pselbuf, *findselpos;
454 static char *mark;
455 #ifndef NOX11
456 static char *hostname;
457 #endif
458 #ifndef NOFIFO
459 static char *fifopath;
460 #endif
461 static char *lastcmd;
462 static ullong_t *ihashbmp;
463 static struct entry *pdents;
464 static blkcnt_t dir_blocks;
465 static kv *bookmark;
466 static kv *plug;
467 static kv *order;
468 static uchar_t tmpfplen, homelen;
469 static uchar_t blk_shift = BLK_SHIFT_512;
470 #ifndef NOMOUSE
471 static int middle_click_key;
472 #endif
473 #ifdef PCRE
474 static pcre *archive_pcre;
475 #else
476 static regex_t archive_re;
477 #endif
478 
479 /* pthread related */
480 #define NUM_DU_THREADS (4) /* Can use sysconf(_SC_NPROCESSORS_ONLN) */
481 #define DU_TEST (((node->fts_info & FTS_F) && \
482 		(sb->st_nlink <= 1 || test_set_bit((uint_t)sb->st_ino))) || node->fts_info & FTS_DP)
483 
484 static int threadbmp = -1; /* Has 1 in the bit position for idle threads */
485 static volatile int active_threads;
486 static pthread_mutex_t running_mutex = PTHREAD_MUTEX_INITIALIZER;
487 static pthread_mutex_t hardlink_mutex = PTHREAD_MUTEX_INITIALIZER;
488 static ullong_t *core_files;
489 static blkcnt_t *core_blocks;
490 static ullong_t num_files;
491 
492 typedef struct {
493 	char path[PATH_MAX];
494 	int entnum;
495 	ushort_t core;
496 	bool mntpoint;
497 } thread_data;
498 
499 static thread_data *core_data;
500 
501 /* Retain old signal handlers */
502 static struct sigaction oldsighup;
503 static struct sigaction oldsigtstp;
504 static struct sigaction oldsigwinch;
505 
506 /* For use in functions which are isolated and don't return the buffer */
507 static char g_buf[CMD_LEN_MAX] __attribute__ ((aligned));
508 
509 /* For use as a scratch buffer in selection manipulation */
510 static char g_sel[PATH_MAX] __attribute__ ((aligned));
511 
512 /* Buffer to store tmp file path to show selection, file stats and help */
513 static char g_tmpfpath[TMP_LEN_MAX] __attribute__ ((aligned));
514 
515 /* Buffer to store plugins control pipe location */
516 static char g_pipepath[TMP_LEN_MAX] __attribute__ ((aligned));
517 
518 /* Non-persistent runtime states */
519 static runstate g_state;
520 
521 /* Options to identify file MIME */
522 #if defined(__APPLE__)
523 #define FILE_MIME_OPTS "-bIL"
524 #elif !defined(__sun) /* no MIME option for 'file' */
525 #define FILE_MIME_OPTS "-biL"
526 #endif
527 
528 /* Macros for utilities */
529 #define UTIL_OPENER    0
530 #define UTIL_ATOOL     1
531 #define UTIL_BSDTAR    2
532 #define UTIL_UNZIP     3
533 #define UTIL_TAR       4
534 #define UTIL_LOCKER    5
535 #define UTIL_LAUNCH    6
536 #define UTIL_SH_EXEC   7
537 #define UTIL_BASH      8
538 #define UTIL_SSHFS     9
539 #define UTIL_RCLONE    10
540 #define UTIL_VI        11
541 #define UTIL_LESS      12
542 #define UTIL_SH        13
543 #define UTIL_FZF       14
544 #define UTIL_NTFY      15
545 #define UTIL_CBCP      16
546 #define UTIL_NMV       17
547 #define UTIL_TRASH_CLI 18
548 #define UTIL_GIO_TRASH 19
549 #define UTIL_RM_RF     20
550 
551 /* Utilities to open files, run actions */
552 static char * const utils[] = {
553 #ifdef __APPLE__
554 	"/usr/bin/open",
555 #elif defined __CYGWIN__
556 	"cygstart",
557 #elif defined __HAIKU__
558 	"open",
559 #else
560 	"xdg-open",
561 #endif
562 	"atool",
563 	"bsdtar",
564 	"unzip",
565 	"tar",
566 #ifdef __APPLE__
567 	"bashlock",
568 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
569 	"lock",
570 #elif defined __HAIKU__
571 	"peaclock",
572 #else
573 	"vlock",
574 #endif
575 	"launch",
576 	"sh -c",
577 	"bash",
578 	"sshfs",
579 	"rclone",
580 	"vi",
581 	"less",
582 	"sh",
583 	"fzf",
584 	".ntfy",
585 	".cbcp",
586 	".nmv",
587 	"trash-put",
588 	"gio trash",
589 	"rm -rf",
590 };
591 
592 /* Common strings */
593 #define MSG_ZERO         0 /* Unused */
594 #define MSG_0_ENTRIES    1
595 #define STR_TMPFILE      2
596 #define MSG_0_SELECTED   3
597 #define MSG_CANCEL       4
598 #define MSG_FAILED       5
599 #define MSG_SSN_NAME     6
600 #define MSG_CP_MV_AS     7
601 #define MSG_CUR_SEL_OPTS 8
602 #define MSG_FORCE_RM     9
603 #define MSG_LIMIT        10
604 #define MSG_NEW_OPTS     11
605 #define MSG_CLI_MODE     12
606 #define MSG_OVERWRITE    13
607 #define MSG_SSN_OPTS     14
608 #define MSG_QUIT_ALL     15
609 #define MSG_HOSTNAME     16
610 #define MSG_ARCHIVE_NAME 17
611 #define MSG_OPEN_WITH    18
612 #define MSG_NEW_PATH     19
613 #define MSG_LINK_PREFIX  20
614 #define MSG_COPY_NAME    21
615 #define MSG_ENTER        22
616 #define MSG_SEL_MISSING  23
617 #define MSG_ACCESS       24
618 #define MSG_EMPTY_FILE   25
619 #define MSG_UNSUPPORTED  26
620 #define MSG_NOT_SET      27
621 #define MSG_EXISTS       28
622 #define MSG_FEW_COLUMNS  29
623 #define MSG_REMOTE_OPTS  30
624 #define MSG_RCLONE_DELAY 31
625 #define MSG_APP_NAME     32
626 #define MSG_ARCHIVE_OPTS 33
627 #define MSG_KEYS         34
628 #define MSG_INVALID_REG  35
629 #define MSG_ORDER        36
630 #define MSG_LAZY         37
631 #define MSG_FIRST        38
632 #define MSG_RM_TMP       39
633 #define MSG_INVALID_KEY  40
634 #define MSG_NOCHANGE     41
635 #define MSG_DIR_CHANGED  42
636 
637 static const char * const messages[] = {
638 	"",
639 	"0 entries",
640 	"/.nnnXXXXXX",
641 	"0 selected",
642 	"cancelled",
643 	"failed!",
644 	"session name: ",
645 	"'c'p / 'm'v as?",
646 	"'c'urrent / 's'el?",
647 	"%s %s? [Esc cancels]",
648 	"limit exceeded",
649 	"'f'ile / 'd'ir / 's'ym / 'h'ard?",
650 	"'c'li / 'g'ui?",
651 	"overwrite?",
652 	"'s'ave / 'l'oad / 'r'estore?",
653 	"Quit all contexts?",
654 	"remote name (- for hovered): ",
655 	"archive [path/]name: ",
656 	"open with: ",
657 	"[path/]name: ",
658 	"link prefix [@ for none]: ",
659 	"copy [path/]name: ",
660 	"\n'Enter' to continue",
661 	"open failed",
662 	"dir inaccessible",
663 	"empty! edit/open with",
664 	"?",
665 	"not set",
666 	"entry exists",
667 	"too few cols!",
668 	"'s'shfs / 'r'clone?",
669 	"refresh if slow",
670 	"app name: ",
671 	"'o'pen / e'x'tract / 'l's / 'm'nt?",
672 	"keys:",
673 	"invalid regex",
674 	"'a'u / 'd'u / 'e'xt / 'r'ev / 's'z / 't'm / 'v'er / 'c'lr / '^T'?",
675 	"unmount failed! try lazy?",
676 	"first file (\')/char?",
677 	"remove tmp file?",
678 	"invalid key",
679 	"unchanged",
680 	"dir changed, range sel off",
681 };
682 
683 /* Supported configuration environment variables */
684 #define NNN_OPTS    0
685 #define NNN_BMS     1
686 #define NNN_PLUG    2
687 #define NNN_OPENER  3
688 #define NNN_COLORS  4
689 #define NNN_FCOLORS 5
690 #define NNNLVL      6
691 #define NNN_PIPE    7
692 #define NNN_MCLICK  8
693 #define NNN_SEL     9
694 #define NNN_ARCHIVE 10
695 #define NNN_ORDER   11
696 #define NNN_HELP    12 /* strings end here */
697 #define NNN_TRASH   13 /* flags begin here */
698 
699 static const char * const env_cfg[] = {
700 	"NNN_OPTS",
701 	"NNN_BMS",
702 	"NNN_PLUG",
703 	"NNN_OPENER",
704 	"NNN_COLORS",
705 	"NNN_FCOLORS",
706 	"NNNLVL",
707 	"NNN_PIPE",
708 	"NNN_MCLICK",
709 	"NNN_SEL",
710 	"NNN_ARCHIVE",
711 	"NNN_ORDER",
712 	"NNN_HELP",
713 	"NNN_TRASH",
714 };
715 
716 /* Required environment variables */
717 #define ENV_SHELL  0
718 #define ENV_VISUAL 1
719 #define ENV_EDITOR 2
720 #define ENV_PAGER  3
721 #define ENV_NCUR   4
722 
723 static const char * const envs[] = {
724 	"SHELL",
725 	"VISUAL",
726 	"EDITOR",
727 	"PAGER",
728 	"nnn",
729 };
730 
731 /* Time type used */
732 #define T_ACCESS 0
733 #define T_CHANGE 1
734 #define T_MOD    2
735 
736 #ifdef __linux__
737 static char cp[] = "cp   -iRp";
738 static char mv[] = "mv   -i";
739 #else
740 static char cp[] = "cp -iRp";
741 static char mv[] = "mv -i";
742 #endif
743 
744 /* Archive commands */
745 static const char * const archive_cmd[] = {"atool -a", "bsdtar -acvf", "zip -r", "tar -acvf"};
746 
747 /* Tokens used for path creation */
748 #define TOK_BM  0
749 #define TOK_SSN 1
750 #define TOK_MNT 2
751 #define TOK_PLG 3
752 
753 static const char * const toks[] = {
754 	"bookmarks",
755 	"sessions",
756 	"mounts",
757 	"plugins", /* must be the last entry */
758 };
759 
760 /* Patterns */
761 #define P_CPMVFMT 0
762 #define P_CPMVRNM 1
763 #define P_ARCHIVE 2
764 #define P_REPLACE 3
765 
766 static const char * const patterns[] = {
767 	SED" -i 's|^\\(\\(.*/\\)\\(.*\\)$\\)|#\\1\\n\\3|' %s",
768 	SED" 's|^\\([^#/][^/]\\?.*\\)$|%s/\\1|;s|^#\\(/.*\\)$|\\1|' "
769 		"%s | tr '\\n' '\\0' | xargs -0 -n2 sh -c '%s \"$0\" \"$@\" < /dev/tty'",
770 	"\\.(bz|bz2|gz|tar|taz|tbz|tbz2|tgz|z|zip)$",
771 	SED" -i 's|^%s\\(.*\\)$|%s\\1|' %s",
772 };
773 
774 /* Colors */
775 #define C_BLK (CTX_MAX + 1) /* Block device: DarkSeaGreen1 */
776 #define C_CHR (C_BLK + 1)   /* Character device: Yellow1 */
777 #define C_DIR (C_CHR + 1)   /* Directory: DeepSkyBlue1 */
778 #define C_EXE (C_DIR + 1)   /* Executable file: Green1 */
779 #define C_FIL (C_EXE + 1)   /* Regular file: Normal */
780 #define C_HRD (C_FIL + 1)   /* Hard link: Plum4 */
781 #define C_LNK (C_HRD + 1)   /* Symbolic link: Cyan1 */
782 #define C_MIS (C_LNK + 1)   /* Missing file OR file details: Grey62 */
783 #define C_ORP (C_MIS + 1)   /* Orphaned symlink: DeepPink1 */
784 #define C_PIP (C_ORP + 1)   /* Named pipe (FIFO): Orange1 */
785 #define C_SOC (C_PIP + 1)   /* Socket: MediumOrchid1 */
786 #define C_UND (C_SOC + 1)   /* Unknown OR 0B regular/exe file: Red1 */
787 
788 #ifdef ICONS_ENABLED
789 /* 0-9, A-Z, OTHER = 36. */
790 static ushort_t icon_positions[37];
791 #endif
792 
793 static char gcolors[] = "c1e2272e006033f7c6d6abc4";
794 static uint_t fcolors[C_UND + 1] = {0};
795 
796 /* Event handling */
797 #ifdef LINUX_INOTIFY
798 #define NUM_EVENT_SLOTS 32 /* Make room for 32 events */
799 #define EVENT_SIZE (sizeof(struct inotify_event))
800 #define EVENT_BUF_LEN (EVENT_SIZE * NUM_EVENT_SLOTS)
801 static int inotify_fd, inotify_wd = -1;
802 static uint_t INOTIFY_MASK = /* IN_ATTRIB | */ IN_CREATE | IN_DELETE | IN_DELETE_SELF
803 			   | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
804 #elif defined(BSD_KQUEUE)
805 #define NUM_EVENT_SLOTS 1
806 #define NUM_EVENT_FDS 1
807 static int kq, event_fd = -1;
808 static struct kevent events_to_monitor[NUM_EVENT_FDS];
809 static uint_t KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK
810 			    | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
811 static struct timespec gtimeout;
812 #elif defined(HAIKU_NM)
813 static bool haiku_nm_active = FALSE;
814 static haiku_nm_h haiku_hnd;
815 #endif
816 
817 /* Function macros */
818 #define tolastln() move(xlines - 1, 0)
819 #define tocursor() move(cur + 2 - curscroll, 0)
820 #define exitcurses() endwin()
821 #define printwarn(presel) printwait(strerror(errno), presel)
822 #define istopdir(path) ((path)[1] == '\0' && (path)[0] == '/')
823 #define copycurname() xstrsncpy(lastname, ndents ? pdents[cur].name : "\0", NAME_MAX + 1)
824 #define settimeout() timeout(1000)
825 #define cleartimeout() timeout(-1)
826 #define errexit() printerr(__LINE__)
827 #define setdirwatch() (cfg.filtermode ? (presel = FILTER) : (watch = TRUE))
828 #define filterset() (g_ctx[cfg.curctx].c_fltr[1])
829 /* We don't care about the return value from strcmp() */
830 #define xstrcmp(a, b)  (*(a) != *(b) ? -1 : strcmp((a), (b)))
831 /* A faster version of xisdigit */
832 #define xisdigit(c) ((unsigned int) (c) - '0' <= 9)
833 #define xerror() perror(xitoa(__LINE__))
834 
835 #ifdef TOURBIN_QSORT
836 #define ENTLESS(i, j) (entrycmpfn(pdents + (i), pdents + (j)) < 0)
837 #define ENTSWAP(i, j) (swap_ent((i), (j)))
838 #define ENTSORT(pdents, ndents, entrycmpfn) QSORT((ndents), ENTLESS, ENTSWAP)
839 #else
840 #define ENTSORT(pdents, ndents, entrycmpfn) qsort((pdents), (ndents), sizeof(*(pdents)), (entrycmpfn))
841 #endif
842 
843 /* Forward declarations */
844 static void redraw(char *path);
845 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag);
846 static void move_cursor(int target, int ignore_scrolloff);
847 static char *load_input(int fd, const char *path);
848 static int set_sort_flags(int r);
849 static void statusbar(char *path);
850 #ifndef NOFIFO
851 static void notify_fifo(bool force);
852 #endif
853 
854 /* Functions */
855 
sigint_handler(int sig)856 static void sigint_handler(int sig)
857 {
858 	(void) sig;
859 	g_state.interrupt = 1;
860 }
861 
clean_exit_sighandler(int sig)862 static void clean_exit_sighandler(int sig)
863 {
864 	(void) sig;
865 	exitcurses();
866 	/* This triggers cleanup() thanks to atexit() */
867 	exit(EXIT_SUCCESS);
868 }
869 
xitoa(uint_t val)870 static char *xitoa(uint_t val)
871 {
872 	static char dst[32] = {'\0'};
873 	static const char digits[201] =
874 		"0001020304050607080910111213141516171819"
875 		"2021222324252627282930313233343536373839"
876 		"4041424344454647484950515253545556575859"
877 		"6061626364656667686970717273747576777879"
878 		"8081828384858687888990919293949596979899";
879 	uint_t next = 30, quo, i;
880 
881 	while (val >= 100) {
882 		quo = val / 100;
883 		i = (val - (quo * 100)) * 2;
884 		val = quo;
885 		dst[next] = digits[i + 1];
886 		dst[--next] = digits[i];
887 		--next;
888 	}
889 
890 	/* Handle last 1-2 digits */
891 	if (val < 10)
892 		dst[next] = '0' + val;
893 	else {
894 		i = val * 2;
895 		dst[next] = digits[i + 1];
896 		dst[--next] = digits[i];
897 	}
898 
899 	return &dst[next];
900 }
901 
902 /* Return the integer value of a char representing HEX */
xchartohex(uchar_t c)903 static uchar_t xchartohex(uchar_t c)
904 {
905 	if (xisdigit(c))
906 		return c - '0';
907 
908 	if (c >= 'a' && c <= 'f')
909 		return c - 'a' + 10;
910 
911 	if (c >= 'A' && c <= 'F')
912 		return c - 'A' + 10;
913 
914 	return c;
915 }
916 
917 /*
918  * Source: https://elixir.bootlin.com/linux/latest/source/arch/alpha/include/asm/bitops.h
919  */
test_set_bit(uint_t nr)920 static bool test_set_bit(uint_t nr)
921 {
922 	nr &= HASH_BITS;
923 
924 	pthread_mutex_lock(&hardlink_mutex);
925 	ullong_t *m = ((ullong_t *)ihashbmp) + (nr >> 6);
926 
927 	if (*m & (1 << (nr & 63))) {
928 		pthread_mutex_unlock(&hardlink_mutex);
929 		return FALSE;
930 	}
931 
932 	*m |= 1 << (nr & 63);
933 	pthread_mutex_unlock(&hardlink_mutex);
934 
935 	return TRUE;
936 }
937 
938 #ifndef __APPLE__
939 /* Increase the limit on open file descriptors, if possible */
max_openfds(void)940 static void max_openfds(void)
941 {
942 	struct rlimit rl;
943 
944 	if (!getrlimit(RLIMIT_NOFILE, &rl))
945 		if (rl.rlim_cur < rl.rlim_max) {
946 			rl.rlim_cur = rl.rlim_max;
947 			setrlimit(RLIMIT_NOFILE, &rl);
948 		}
949 }
950 #endif
951 
952 /*
953  * Wrapper to realloc()
954  * Frees current memory if realloc() fails and returns NULL.
955  *
956  * The *alloc() family returns aligned address: https://man7.org/linux/man-pages/man3/malloc.3.html
957  */
xrealloc(void * pcur,size_t len)958 static void *xrealloc(void *pcur, size_t len)
959 {
960 	void *pmem = realloc(pcur, len);
961 
962 	if (!pmem)
963 		free(pcur);
964 
965 	return pmem;
966 }
967 
968 /*
969  * Just a safe strncpy(3)
970  * Always null ('\0') terminates if both src and dest are valid pointers.
971  * Returns the number of bytes copied including terminating null byte.
972  */
xstrsncpy(char * restrict dst,const char * restrict src,size_t n)973 static size_t xstrsncpy(char *restrict dst, const char *restrict src, size_t n)
974 {
975 	char *end = memccpy(dst, src, '\0', n);
976 
977 	if (!end) {
978 		dst[n - 1] = '\0'; // NOLINT
979 		end = dst + n; /* If we return n here, binary size increases due to auto-inlining */
980 	}
981 
982 	return end - dst;
983 }
984 
xstrlen(const char * restrict s)985 static inline size_t xstrlen(const char *restrict s)
986 {
987 #if !defined(__GLIBC__)
988 	return strlen(s); // NOLINT
989 #else
990 	return (char *)rawmemchr(s, '\0') - s; // NOLINT
991 #endif
992 }
993 
xstrdup(const char * restrict s)994 static char *xstrdup(const char *restrict s)
995 {
996 	size_t len = xstrlen(s) + 1;
997 	char *ptr = malloc(len);
998 
999 	if (ptr)
1000 		xstrsncpy(ptr, s, len);
1001 	return ptr;
1002 }
1003 
is_suffix(const char * restrict str,const char * restrict suffix)1004 static bool is_suffix(const char *restrict str, const char *restrict suffix)
1005 {
1006 	if (!str || !suffix)
1007 		return FALSE;
1008 
1009 	size_t lenstr = xstrlen(str);
1010 	size_t lensuffix = xstrlen(suffix);
1011 
1012 	if (lensuffix > lenstr)
1013 		return FALSE;
1014 
1015 	return (xstrcmp(str + (lenstr - lensuffix), suffix) == 0);
1016 }
1017 
is_prefix(const char * restrict str,const char * restrict prefix,size_t len)1018 static bool is_prefix(const char *restrict str, const char *restrict prefix, size_t len)
1019 {
1020 	return !strncmp(str, prefix, len);
1021 }
1022 
1023 /*
1024  * The poor man's implementation of memrchr(3).
1025  * We are only looking for '/' in this program.
1026  * And we are NOT expecting a '/' at the end.
1027  * Ideally 0 < n <= xstrlen(s).
1028  */
xmemrchr(uchar_t * restrict s,uchar_t ch,size_t n)1029 static void *xmemrchr(uchar_t *restrict s, uchar_t ch, size_t n)
1030 {
1031 #if defined(__GLIBC__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
1032 	return memrchr(s, ch, n);
1033 #else
1034 
1035 	if (!s || !n)
1036 		return NULL;
1037 
1038 	uchar_t *ptr = s + n;
1039 
1040 	do {
1041 		if (*--ptr == ch)
1042 			return ptr;
1043 	} while (s != ptr);
1044 
1045 	return NULL;
1046 #endif
1047 }
1048 
1049 /* A very simplified implementation, changes path */
xdirname(char * path)1050 static char *xdirname(char *path)
1051 {
1052 	char *base = xmemrchr((uchar_t *)path, '/', xstrlen(path));
1053 
1054 	if (base == path)
1055 		path[1] = '\0';
1056 	else
1057 		*base = '\0';
1058 
1059 	return path;
1060 }
1061 
xbasename(char * path)1062 static char *xbasename(char *path)
1063 {
1064 	char *base = xmemrchr((uchar_t *)path, '/', xstrlen(path)); // NOLINT
1065 
1066 	return base ? base + 1 : path;
1067 }
1068 
xextension(const char * fname,size_t len)1069 static inline char *xextension(const char *fname, size_t len)
1070 {
1071 	return xmemrchr((uchar_t *)fname, '.', len);
1072 }
1073 
1074 #ifndef NOUG
1075 /*
1076  * One-shot cache for getpwuid/getgrgid. Returns the cached name if the
1077  * provided uid is the same as the previous uid. Returns xitoa(guid) if
1078  * the guid is not found in the password database.
1079  */
getpwname(uid_t uid)1080 static char *getpwname(uid_t uid)
1081 {
1082 	static uint_t uidcache = UINT_MAX;
1083 	static char *namecache;
1084 
1085 	if (uidcache != uid) {
1086 		struct passwd *pw = getpwuid(uid);
1087 
1088 		uidcache = uid;
1089 		namecache = pw ? pw->pw_name : NULL;
1090 	}
1091 
1092 	return namecache ? namecache : xitoa(uid);
1093 }
1094 
getgrname(gid_t gid)1095 static char *getgrname(gid_t gid)
1096 {
1097 	static uint_t gidcache = UINT_MAX;
1098 	static char *grpcache;
1099 
1100 	if (gidcache != gid) {
1101 		struct group *gr = getgrgid(gid);
1102 
1103 		gidcache = gid;
1104 		grpcache = gr ? gr->gr_name : NULL;
1105 	}
1106 
1107 	return grpcache ? grpcache : xitoa(gid);
1108 }
1109 #endif
1110 
getutil(char * util)1111 static inline bool getutil(char *util)
1112 {
1113 	return spawn("which", util, NULL, NULL, F_NORMAL | F_NOTRACE) == 0;
1114 }
1115 
1116 /*
1117  * Updates out with "dir/name or "/name"
1118  * Returns the number of bytes copied including the terminating NULL byte
1119  *
1120  * Note: dir and out must be PATH_MAX in length to avoid macOS fault
1121  */
mkpath(const char * dir,const char * name,char * out)1122 static size_t mkpath(const char *dir, const char *name, char *out)
1123 {
1124 	size_t len = 0;
1125 
1126 	if (name[0] != '/') { // NOLINT
1127 		/* Handle root case */
1128 		if (istopdir(dir))
1129 			len = 1;
1130 		else
1131 			len = xstrsncpy(out, dir, PATH_MAX);
1132 
1133 		out[len - 1] = '/'; // NOLINT
1134 	}
1135 	return (xstrsncpy(out + len, name, PATH_MAX - len) + len);
1136 }
1137 
1138 /* Assumes both the paths passed are directories */
common_prefix(const char * path,char * prefix)1139 static char *common_prefix(const char *path, char *prefix)
1140 {
1141 	const char *x = path, *y = prefix;
1142 	char *sep;
1143 
1144 	if (!path || !*path || !prefix)
1145 		return NULL;
1146 
1147 	if (!*prefix) {
1148 		xstrsncpy(prefix, path, PATH_MAX);
1149 		return prefix;
1150 	}
1151 
1152 	while (*x && *y && (*x == *y))
1153 		++x, ++y;
1154 
1155 	/* Strings are same */
1156 	if (!*x && !*y)
1157 		return prefix;
1158 
1159 	/* Path is shorter */
1160 	if (!*x && *y == '/') {
1161 		xstrsncpy(prefix, path, y - path);
1162 		return prefix;
1163 	}
1164 
1165 	/* Prefix is shorter */
1166 	if (!*y && *x == '/')
1167 		return prefix;
1168 
1169 	/* Shorten prefix */
1170 	prefix[y - prefix] = '\0';
1171 
1172 	sep = xmemrchr((uchar_t *)prefix, '/', y - prefix);
1173 	if (sep != prefix)
1174 		*sep = '\0';
1175 	else /* Just '/' */
1176 		prefix[1] = '\0';
1177 
1178 	return prefix;
1179 }
1180 
1181 /*
1182  * The library function realpath() resolves symlinks.
1183  * If there's a symlink in file list we want to show the symlink not what it's points to.
1184  * Resolves ./../~ in path
1185  */
abspath(const char * path,const char * cwd,char * buf)1186 static char *abspath(const char *path, const char *cwd, char *buf)
1187 {
1188 	if (!path)
1189 		return NULL;
1190 
1191 	if (path[0] == '~')
1192 		cwd = home;
1193 	else if ((path[0] != '/') && !cwd)
1194 		cwd = getcwd(NULL, 0);
1195 
1196 	size_t dst_size = 0, src_size = xstrlen(path), cwd_size = cwd ? xstrlen(cwd) : 0;
1197 	size_t len = src_size;
1198 	const char *src;
1199 	char *dst;
1200 	/*
1201 	 * We need to add 2 chars at the end as relative paths may start with:
1202 	 * ./ (find .)
1203 	 * no separator (fd .): this needs an additional char for '/'
1204 	 */
1205 	char *resolved_path = buf ? buf : malloc(src_size + cwd_size + 2);
1206 
1207 	if (!resolved_path)
1208 		return NULL;
1209 
1210 	/* Turn relative paths into absolute */
1211 	if (path[0] != '/') {
1212 		if (!cwd) {
1213 			if (!buf)
1214 				free(resolved_path);
1215 			return NULL;
1216 		}
1217 		dst_size = xstrsncpy(resolved_path, cwd, cwd_size + 1) - 1;
1218 	} else
1219 		resolved_path[0] = '\0';
1220 
1221 	src = path;
1222 	dst = resolved_path + dst_size;
1223 	for (const char *next = NULL; next != path + src_size;) {
1224 		next = memchr(src, '/', len);
1225 		if (!next)
1226 			next = path + src_size;
1227 
1228 		if (next - src == 2 && src[0] == '.' && src[1] == '.') {
1229 			if (dst - resolved_path) {
1230 				dst = xmemrchr((uchar_t *)resolved_path, '/', dst - resolved_path);
1231 				*dst = '\0';
1232 			}
1233 		} else if (next - src == 1 && src[0] == '.') {
1234 			/* NOP */
1235 		} else if (next - src) {
1236 			*(dst++) = '/';
1237 			xstrsncpy(dst, src, next - src + 1);
1238 			dst += next - src;
1239 		}
1240 
1241 		src = next + 1;
1242 		len = src_size - (src - path);
1243 	}
1244 
1245 	if (*resolved_path == '\0') {
1246 		resolved_path[0] = '/';
1247 		resolved_path[1] = '\0';
1248 	}
1249 
1250 	return resolved_path;
1251 }
1252 
set_tilde_in_path(char * path)1253 static bool set_tilde_in_path(char *path)
1254 {
1255 	if (is_prefix(path, home, homelen)) {
1256 		home[homelen] = path[homelen - 1];
1257 		path[homelen - 1] = '~';
1258 		return TRUE;
1259 	}
1260 
1261 	return FALSE;
1262 }
1263 
reset_tilde_in_path(char * path)1264 static void reset_tilde_in_path(char *path)
1265 {
1266 	path[homelen - 1] = home[homelen];
1267 	home[homelen] = '\0';
1268 }
1269 
convert_tilde(const char * path,char * buf)1270 static void convert_tilde(const char *path, char *buf)
1271 {
1272 	if (path[0] == '~') {
1273 		ssize_t len = xstrlen(home);
1274 		ssize_t loclen = xstrlen(path);
1275 
1276 		xstrsncpy(buf, home, len + 1);
1277 		xstrsncpy(buf + len, path + 1, loclen);
1278 	}
1279 }
1280 
create_tmp_file(void)1281 static int create_tmp_file(void)
1282 {
1283 	xstrsncpy(g_tmpfpath + tmpfplen - 1, messages[STR_TMPFILE], TMP_LEN_MAX - tmpfplen);
1284 
1285 	int fd = mkstemp(g_tmpfpath);
1286 
1287 	if (fd == -1) {
1288 		DPRINTF_S(strerror(errno));
1289 	}
1290 
1291 	return fd;
1292 }
1293 
msg(const char * message)1294 static void msg(const char *message)
1295 {
1296 	dprintf(STDERR_FILENO, "%s\n", message);
1297 }
1298 
clearinfoln(void)1299 static void clearinfoln(void)
1300 {
1301 	move(xlines - 2, 0);
1302 	clrtoeol();
1303 }
1304 
1305 #ifdef KEY_RESIZE
handle_key_resize()1306 static void handle_key_resize()
1307 {
1308 	endwin();
1309 	refresh();
1310 }
1311 
1312 /* Clear the old prompt */
clearoldprompt(void)1313 static void clearoldprompt(void)
1314 {
1315 	clearinfoln();
1316 	tolastln();
1317 	clrtoeol();
1318 	handle_key_resize();
1319 }
1320 #endif
1321 
1322 /* Messages show up at the bottom */
printmsg_nc(const char * msg)1323 static inline void printmsg_nc(const char *msg)
1324 {
1325 	tolastln();
1326 	addstr(msg);
1327 	clrtoeol();
1328 }
1329 
printmsg(const char * msg)1330 static void printmsg(const char *msg)
1331 {
1332 	attron(COLOR_PAIR(cfg.curctx + 1));
1333 	printmsg_nc(msg);
1334 	attroff(COLOR_PAIR(cfg.curctx + 1));
1335 }
1336 
printwait(const char * msg,int * presel)1337 static void printwait(const char *msg, int *presel)
1338 {
1339 	printmsg(msg);
1340 	if (presel) {
1341 		*presel = MSGWAIT;
1342 		if (ndents)
1343 			xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
1344 	}
1345 }
1346 
1347 /* Kill curses and display error before exiting */
printerr(int linenum)1348 static void printerr(int linenum)
1349 {
1350 	exitcurses();
1351 	perror(xitoa(linenum));
1352 	if (!g_state.picker && selpath)
1353 		unlink(selpath);
1354 	free(pselbuf);
1355 	exit(1);
1356 }
1357 
xconfirm(int c)1358 static inline bool xconfirm(int c)
1359 {
1360 	return (c == 'y' || c == 'Y');
1361 }
1362 
get_input(const char * prompt)1363 static int get_input(const char *prompt)
1364 {
1365 	if (prompt)
1366 		printmsg(prompt);
1367 	cleartimeout();
1368 
1369 	int r = getch();
1370 
1371 #ifdef KEY_RESIZE
1372 	while (r == KEY_RESIZE) {
1373 		if (prompt) {
1374 			clearoldprompt();
1375 			xlines = LINES;
1376 			printmsg(prompt);
1377 		}
1378 
1379 		r = getch();
1380 	}
1381 #endif
1382 	settimeout();
1383 	return r;
1384 }
1385 
isselfileempty(void)1386 static bool isselfileempty(void)
1387 {
1388 	struct stat sb;
1389 
1390 	return (stat(selpath, &sb) == -1) || (!sb.st_size);
1391 }
1392 
get_cur_or_sel(void)1393 static int get_cur_or_sel(void)
1394 {
1395 	bool sel = (selbufpos || !isselfileempty());
1396 
1397 	/* Check both local buffer and selection file for external selection */
1398 	if (sel && ndents) {
1399 		/* If selection is preferred and we have a local selection, return selection.
1400 		 * Always show the prompt in case of an external selection.
1401 		 */
1402 		if (cfg.prefersel && selbufpos)
1403 			return 's';
1404 
1405 		int choice = get_input(messages[MSG_CUR_SEL_OPTS]);
1406 
1407 		return ((choice == 'c' || choice == 's') ? choice : 0);
1408 	}
1409 
1410 	if (sel)
1411 		return 's';
1412 
1413 	if (ndents)
1414 		return 'c';
1415 
1416 	return 0;
1417 }
1418 
xdelay(useconds_t delay)1419 static void xdelay(useconds_t delay)
1420 {
1421 	refresh();
1422 	usleep(delay);
1423 }
1424 
confirm_force(bool selection)1425 static char confirm_force(bool selection)
1426 {
1427 	char str[64];
1428 
1429 	snprintf(str, 64, messages[MSG_FORCE_RM],
1430 		 g_state.trash ? utils[UTIL_GIO_TRASH] + 4 : utils[UTIL_RM_RF],
1431 		 (selection ? "selection" : "hovered"));
1432 
1433 	int r = get_input(str);
1434 
1435 	if (r == ESC)
1436 		return '\0'; /* cancel */
1437 	if (r == 'y' || r == 'Y')
1438 		return 'f'; /* forceful for rm */
1439 	return (g_state.trash ? '\0' : 'i'); /* interactive for rm */
1440 }
1441 
1442 /* Writes buflen char(s) from buf to a file */
writesel(const char * buf,const size_t buflen)1443 static void writesel(const char *buf, const size_t buflen)
1444 {
1445 	if (!selpath)
1446 		return;
1447 
1448 	int fd = open(selpath, O_CREAT | O_WRONLY | O_TRUNC, 0666);
1449 
1450 	if (fd != -1) {
1451 		if (write(fd, buf, buflen) != (ssize_t)buflen)
1452 			printwarn(NULL);
1453 		close(fd);
1454 	} else
1455 		printwarn(NULL);
1456 }
1457 
appendfpath(const char * path,const size_t len)1458 static void appendfpath(const char *path, const size_t len)
1459 {
1460 	if ((selbufpos >= selbuflen) || ((len + 3) > (selbuflen - selbufpos))) {
1461 		selbuflen += PATH_MAX;
1462 		pselbuf = xrealloc(pselbuf, selbuflen);
1463 		if (!pselbuf)
1464 			errexit();
1465 	}
1466 
1467 	selbufpos += xstrsncpy(pselbuf + selbufpos, path, len);
1468 }
1469 
selbufrealloc(const size_t alloclen)1470 static void selbufrealloc(const size_t alloclen)
1471 {
1472 	if ((selbufpos + alloclen) > selbuflen) {
1473 		selbuflen = ALIGN_UP(selbufpos + alloclen, PATH_MAX);
1474 		pselbuf = xrealloc(pselbuf, selbuflen);
1475 		if (!pselbuf)
1476 			errexit();
1477 	}
1478 }
1479 
1480 /* Write selected file paths to fd, linefeed separated */
seltofile(int fd,uint_t * pcount)1481 static size_t seltofile(int fd, uint_t *pcount)
1482 {
1483 	uint_t lastpos, count = 0;
1484 	char *pbuf = pselbuf;
1485 	size_t pos = 0;
1486 	ssize_t len, prefixlen = 0, initlen = 0;
1487 
1488 	if (pcount)
1489 		*pcount = 0;
1490 
1491 	if (!selbufpos)
1492 		return 0;
1493 
1494 	lastpos = selbufpos - 1;
1495 
1496 	if (listpath) {
1497 		prefixlen = (ssize_t)xstrlen(listroot);
1498 		initlen = (ssize_t)xstrlen(listpath);
1499 	}
1500 
1501 	while (pos <= lastpos) {
1502 		DPRINTF_S(pbuf);
1503 		len = (ssize_t)xstrlen(pbuf);
1504 
1505 		if (!listpath || !is_prefix(pbuf, listpath, initlen)) {
1506 			if (write(fd, pbuf, len) != len)
1507 				return pos;
1508 		} else {
1509 			if (write(fd, listroot, prefixlen) != prefixlen)
1510 				return pos;
1511 			if (write(fd, pbuf + initlen, len - initlen) != (len - initlen))
1512 				return pos;
1513 		}
1514 
1515 		pos += len;
1516 		if (pos <= lastpos) {
1517 			if (write(fd, "\n", 1) != 1)
1518 				return pos;
1519 			pbuf += len + 1;
1520 		}
1521 		++pos;
1522 		++count;
1523 	}
1524 
1525 	if (pcount)
1526 		*pcount = count;
1527 
1528 	return pos;
1529 }
1530 
1531 /* List selection from selection file (another instance) */
listselfile(void)1532 static bool listselfile(void)
1533 {
1534 	if (isselfileempty())
1535 		return FALSE;
1536 
1537 	snprintf(g_buf, CMD_LEN_MAX, "tr \'\\0\' \'\\n\' < %s", selpath);
1538 	spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CONFIRM);
1539 
1540 	return TRUE;
1541 }
1542 
1543 /* Reset selection indicators */
resetselind(void)1544 static void resetselind(void)
1545 {
1546 	for (int r = 0; r < ndents; ++r)
1547 		if (pdents[r].flags & FILE_SELECTED)
1548 			pdents[r].flags &= ~FILE_SELECTED;
1549 }
1550 
startselection(void)1551 static void startselection(void)
1552 {
1553 	if (!g_state.selmode) {
1554 		g_state.selmode = 1;
1555 		nselected = 0;
1556 
1557 		if (selbufpos) {
1558 			resetselind();
1559 			writesel(NULL, 0);
1560 			selbufpos = 0;
1561 		}
1562 	}
1563 }
1564 
clearselection(void)1565 static void clearselection(void)
1566 {
1567 	nselected = 0;
1568 	selbufpos = 0;
1569 	g_state.selmode = 0;
1570 	writesel(NULL, 0);
1571 }
1572 
findinsel(char * startpos,int len)1573 static char *findinsel(char *startpos, int len)
1574 {
1575 	if (!selbufpos)
1576 		return FALSE;
1577 
1578 	if (!startpos)
1579 		startpos = pselbuf;
1580 
1581 	char *found = startpos;
1582 	size_t buflen = selbufpos - (startpos - pselbuf);
1583 
1584 	while (1) {
1585 		/* memmem(3): not specified in POSIX.1, but present on a number of other systems. */
1586 		found = memmem(found, buflen - (found - startpos), g_sel, len);
1587 		if (!found)
1588 			return NULL;
1589 		if (found == startpos || *(found - 1) == '\0')
1590 			return found;
1591 		found += len; /* We found g_sel as a substring of a path, move forward */
1592 		if (found >= startpos + buflen)
1593 			return NULL;
1594 	}
1595 }
1596 
markcmp(const void * va,const void * vb)1597 static int markcmp(const void *va, const void *vb)
1598 {
1599 	const selmark *ma = (selmark*)va;
1600 	const selmark *mb = (selmark*)vb;
1601 
1602 	return ma->startpos - mb->startpos;
1603 }
1604 
1605 /* scanselforpath() must be called before calling this */
findmarkentry(size_t len,struct entry * dentp)1606 static inline void findmarkentry(size_t len, struct entry *dentp)
1607 {
1608 	if (!(dentp->flags & FILE_SCANNED)) {
1609 		if (findinsel(findselpos, len + xstrsncpy(g_sel + len, dentp->name, dentp->nlen)))
1610 			dentp->flags |= FILE_SELECTED;
1611 		dentp->flags |= FILE_SCANNED;
1612 	}
1613 }
1614 
1615 /*
1616  * scanselforpath() must be called before calling this
1617  * pathlen = length of path + 1 (+1 for trailing slash)
1618  */
invertselbuf(const int pathlen)1619 static void invertselbuf(const int pathlen)
1620 {
1621 	size_t len, endpos, shrinklen = 0, alloclen = 0;
1622 	char * const pbuf = g_sel + pathlen;
1623 	char *found;
1624 	int i, nmarked = 0, prev = 0;
1625 	struct entry *dentp;
1626 	selmark *marked = malloc(nselected * sizeof(selmark));
1627 	bool scan = FALSE;
1628 
1629 	/* First pass: inversion */
1630 	for (i = 0; i < ndents; ++i) {
1631 		dentp = &pdents[i];
1632 
1633 		if (dentp->flags & FILE_SCANNED) {
1634 			if (dentp->flags & FILE_SELECTED) {
1635 				dentp->flags ^= FILE_SELECTED; /* Clear selection status */
1636 				scan = TRUE;
1637 			} else {
1638 				dentp->flags |= FILE_SELECTED;
1639 				alloclen += pathlen + dentp->nlen;
1640 			}
1641 		} else {
1642 			dentp->flags |= FILE_SCANNED;
1643 			scan = TRUE;
1644 		}
1645 
1646 		if (scan) {
1647 			len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1648 			found = findinsel(findselpos, len);
1649 			if (found) {
1650 				if (findselpos == found)
1651 					findselpos += len;
1652 
1653 				if (nmarked && (found
1654 				    == (marked[nmarked - 1].startpos + marked[nmarked - 1].len)))
1655 					marked[nmarked - 1].len += len;
1656 				else {
1657 					marked[nmarked].startpos = found;
1658 					marked[nmarked].len = len;
1659 					++nmarked;
1660 				}
1661 
1662 				--nselected;
1663 				shrinklen += len; /* buffer size adjustment */
1664 			} else {
1665 				dentp->flags |= FILE_SELECTED;
1666 				alloclen += pathlen + dentp->nlen;
1667 			}
1668 			scan = FALSE;
1669 		}
1670 	}
1671 
1672 	/*
1673 	 * Files marked for deselection could be found in arbitrary order.
1674 	 * Sort by appearance in selection buffer.
1675 	 * With entries sorted we can merge adjacent ones allowing us to
1676 	 * move them in a single go.
1677 	 */
1678 	qsort(marked, nmarked, sizeof(selmark), &markcmp);
1679 
1680 	/* Some files might be adjacent. Merge them into a single entry */
1681 	for (i = 1; i < nmarked; ++i) {
1682 		if (marked[i].startpos == marked[prev].startpos + marked[prev].len)
1683 			marked[prev].len += marked[i].len;
1684 		else {
1685 			++prev;
1686 			marked[prev].startpos = marked[i].startpos;
1687 			marked[prev].len = marked[i].len;
1688 		}
1689 	}
1690 
1691 	/*
1692 	 * Number of entries is increased by encountering a non-adjacent entry
1693 	 * After we finish the loop we should increment it once more.
1694 	 */
1695 
1696 	if (nmarked) /* Make sure there is something to deselect */
1697 		nmarked = prev + 1;
1698 
1699 	/* Using merged entries remove unselected chunks from selection buffer */
1700 	for (i = 0; i < nmarked; ++i) {
1701 		/*
1702 		 * found: points to where the current block starts
1703 		 *        variable is recycled from previous for readability
1704 		 * endpos: points to where the the next block starts
1705 		 *         area between the end of current block (found + len)
1706 		 *         and endpos is selected entries. This is what we are
1707 		 *         moving back.
1708 		 */
1709 		found = marked[i].startpos;
1710 		endpos = (i + 1 == nmarked ? selbufpos : marked[i + 1].startpos - pselbuf);
1711 		len = marked[i].len;
1712 
1713 		/* Move back only selected entries. No selected memory is moved twice */
1714 		memmove(found, found + len, endpos - (found + len - pselbuf));
1715 	}
1716 
1717 	free(marked);
1718 
1719 	/* Buffer size adjustment */
1720 	selbufpos -= shrinklen;
1721 
1722 	selbufrealloc(alloclen);
1723 
1724 	/* Second pass: append newly selected to buffer */
1725 	for (i = 0; i < ndents; ++i) {
1726 		if (pdents[i].flags & FILE_SELECTED) {
1727 			len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1728 			appendfpath(g_sel, len);
1729 			++nselected;
1730 		}
1731 	}
1732 
1733 	nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1734 }
1735 
1736 /*
1737  * scanselforpath() must be called before calling this
1738  * pathlen = length of path + 1 (+1 for trailing slash)
1739  */
addtoselbuf(const int pathlen,int startid,int endid)1740 static void addtoselbuf(const int pathlen, int startid, int endid)
1741 {
1742 	int i;
1743 	size_t len, alloclen = 0;
1744 	struct entry *dentp;
1745 	char *found;
1746 	char * const pbuf = g_sel + pathlen;
1747 
1748 	/* Remember current selection buffer position */
1749 	for (i = startid; i <= endid; ++i) {
1750 		dentp = &pdents[i];
1751 
1752 		if (findselpos) {
1753 			len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1754 			found = findinsel(findselpos, len);
1755 			if (found) {
1756 				dentp->flags |= (FILE_SCANNED | FILE_SELECTED);
1757 				if (found == findselpos) {
1758 					findselpos += len;
1759 					if (findselpos == (pselbuf + selbufpos))
1760 						findselpos = NULL;
1761 				}
1762 			} else
1763 				alloclen += pathlen + dentp->nlen;
1764 		} else
1765 			alloclen += pathlen + dentp->nlen;
1766 	}
1767 
1768 	selbufrealloc(alloclen);
1769 
1770 	for (i = startid; i <= endid; ++i) {
1771 		if (!(pdents[i].flags & FILE_SELECTED)) {
1772 			len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1773 			appendfpath(g_sel, len);
1774 			++nselected;
1775 			pdents[i].flags |= (FILE_SCANNED | FILE_SELECTED);
1776 		}
1777 	}
1778 
1779 	writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
1780 }
1781 
1782 /* Removes g_sel from selbuf */
rmfromselbuf(size_t len)1783 static void rmfromselbuf(size_t len)
1784 {
1785 	char *found = findinsel(findselpos, len);
1786 	if (!found)
1787 		return;
1788 
1789 	memmove(found, found + len, selbufpos - (found + len - pselbuf));
1790 	selbufpos -= len;
1791 
1792 	nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1793 }
1794 
scanselforpath(const char * path,bool getsize)1795 static int scanselforpath(const char *path, bool getsize)
1796 {
1797 	if (!path[1]) { /* path should always be at least two bytes (including NULL) */
1798 		g_sel[0] = '/';
1799 		findselpos = pselbuf;
1800 		return 1; /* Length of '/' is 1 */
1801 	}
1802 
1803 	size_t off = xstrsncpy(g_sel, path, PATH_MAX);
1804 
1805 	g_sel[off - 1] = '/';
1806 	/*
1807 	 * We set findselpos only here. Directories can be listed in arbitrary order.
1808 	 * This is the best best we can do for remembering position.
1809 	 */
1810 	findselpos = findinsel(NULL, off);
1811 
1812 	if (getsize)
1813 		return off;
1814 	return (findselpos ? off : 0);
1815 }
1816 
1817 /* Finish selection procedure before an operation */
endselection(bool endselmode)1818 static void endselection(bool endselmode)
1819 {
1820 	int fd;
1821 	ssize_t count;
1822 	char buf[sizeof(patterns[P_REPLACE]) + PATH_MAX + (TMP_LEN_MAX << 1)];
1823 
1824 	if (endselmode && g_state.selmode)
1825 		g_state.selmode = 0;
1826 
1827 	/* The code below is only for listing mode */
1828 	if (!listpath || !selbufpos)
1829 		return;
1830 
1831 	fd = create_tmp_file();
1832 	if (fd == -1) {
1833 		DPRINTF_S("couldn't create tmp file");
1834 		return;
1835 	}
1836 
1837 	seltofile(fd, NULL);
1838 	if (close(fd)) {
1839 		DPRINTF_S(strerror(errno));
1840 		printwarn(NULL);
1841 		return;
1842 	}
1843 
1844 	snprintf(buf, sizeof(buf), patterns[P_REPLACE], listpath, listroot, g_tmpfpath);
1845 	spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
1846 
1847 	fd = open(g_tmpfpath, O_RDONLY);
1848 	if (fd == -1) {
1849 		DPRINTF_S(strerror(errno));
1850 		printwarn(NULL);
1851 		if (unlink(g_tmpfpath)) {
1852 			DPRINTF_S(strerror(errno));
1853 			printwarn(NULL);
1854 		}
1855 		return;
1856 	}
1857 
1858 	count = read(fd, pselbuf, selbuflen);
1859 	if (count < 0) {
1860 		DPRINTF_S(strerror(errno));
1861 		printwarn(NULL);
1862 		if (close(fd) || unlink(g_tmpfpath)) {
1863 			DPRINTF_S(strerror(errno));
1864 		}
1865 		return;
1866 	}
1867 
1868 	if (close(fd) || unlink(g_tmpfpath)) {
1869 		DPRINTF_S(strerror(errno));
1870 		printwarn(NULL);
1871 		return;
1872 	}
1873 
1874 	selbufpos = count;
1875 	pselbuf[--count] = '\0';
1876 	for (--count; count > 0; --count)
1877 		if (pselbuf[count] == '\n' && pselbuf[count+1] == '/')
1878 			pselbuf[count] = '\0';
1879 
1880 	writesel(pselbuf, selbufpos - 1);
1881 }
1882 
1883 /* Returns: 1 - success, 0 - none selected, -1 - other failure */
editselection(void)1884 static int editselection(void)
1885 {
1886 	int ret = -1;
1887 	int fd, lines = 0;
1888 	ssize_t count;
1889 	struct stat sb;
1890 	time_t mtime;
1891 
1892 	if (!selbufpos) /* External selection is only editable at source */
1893 		return listselfile();
1894 
1895 	fd = create_tmp_file();
1896 	if (fd == -1) {
1897 		DPRINTF_S("couldn't create tmp file");
1898 		return -1;
1899 	}
1900 
1901 	seltofile(fd, NULL);
1902 	if (close(fd)) {
1903 		DPRINTF_S(strerror(errno));
1904 		return -1;
1905 	}
1906 
1907 	/* Save the last modification time */
1908 	if (stat(g_tmpfpath, &sb)) {
1909 		DPRINTF_S(strerror(errno));
1910 		unlink(g_tmpfpath);
1911 		return -1;
1912 	}
1913 	mtime = sb.st_mtime;
1914 
1915 	spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
1916 
1917 	fd = open(g_tmpfpath, O_RDONLY);
1918 	if (fd == -1) {
1919 		DPRINTF_S(strerror(errno));
1920 		unlink(g_tmpfpath);
1921 		return -1;
1922 	}
1923 
1924 	fstat(fd, &sb);
1925 
1926 	if (mtime == sb.st_mtime) {
1927 		DPRINTF_S("selection is not modified");
1928 		unlink(g_tmpfpath);
1929 		return 1;
1930 	}
1931 
1932 	if (sb.st_size > selbufpos) {
1933 		DPRINTF_S("edited buffer larger than previous");
1934 		unlink(g_tmpfpath);
1935 		goto emptyedit;
1936 	}
1937 
1938 	count = read(fd, pselbuf, selbuflen);
1939 	if (count < 0) {
1940 		DPRINTF_S(strerror(errno));
1941 		printwarn(NULL);
1942 		if (close(fd) || unlink(g_tmpfpath)) {
1943 			DPRINTF_S(strerror(errno));
1944 			printwarn(NULL);
1945 		}
1946 		goto emptyedit;
1947 	}
1948 
1949 	if (close(fd) || unlink(g_tmpfpath)) {
1950 		DPRINTF_S(strerror(errno));
1951 		printwarn(NULL);
1952 		goto emptyedit;
1953 	}
1954 
1955 	if (!count) {
1956 		ret = 1;
1957 		goto emptyedit;
1958 	}
1959 
1960 	resetselind();
1961 	selbufpos = count;
1962 	/* The last character should be '\n' */
1963 	pselbuf[--count] = '\0';
1964 	for (--count; count > 0; --count) {
1965 		/* Replace every '\n' that separates two paths */
1966 		if (pselbuf[count] == '\n' && pselbuf[count + 1] == '/') {
1967 			++lines;
1968 			pselbuf[count] = '\0';
1969 		}
1970 	}
1971 
1972 	/* Add a line for the last file */
1973 	++lines;
1974 
1975 	if (lines > nselected) {
1976 		DPRINTF_S("files added to selection");
1977 		goto emptyedit;
1978 	}
1979 
1980 	nselected = lines;
1981 	writesel(pselbuf, selbufpos - 1);
1982 
1983 	return 1;
1984 
1985 emptyedit:
1986 	resetselind();
1987 	clearselection();
1988 	return ret;
1989 }
1990 
selsafe(void)1991 static bool selsafe(void)
1992 {
1993 	/* Fail if selection file path not generated */
1994 	if (!selpath) {
1995 		printmsg(messages[MSG_SEL_MISSING]);
1996 		return FALSE;
1997 	}
1998 
1999 	/* Fail if selection file path isn't accessible */
2000 	if (access(selpath, R_OK | W_OK) == -1) {
2001 		errno == ENOENT ? printmsg(messages[MSG_0_SELECTED]) : printwarn(NULL);
2002 		return FALSE;
2003 	}
2004 
2005 	return TRUE;
2006 }
2007 
export_file_list(void)2008 static void export_file_list(void)
2009 {
2010 	if (!ndents)
2011 		return;
2012 
2013 	struct entry *pdent = pdents;
2014 	int fd = create_tmp_file();
2015 
2016 	if (fd == -1) {
2017 		DPRINTF_S(strerror(errno));
2018 		return;
2019 	}
2020 
2021 	for (int r = 0; r < ndents; ++pdent, ++r) {
2022 		if (write(fd, pdent->name, pdent->nlen - 1) != (pdent->nlen - 1))
2023 			break;
2024 
2025 		if ((r != ndents - 1) && (write(fd, "\n", 1) != 1))
2026 			break;
2027 	}
2028 
2029 	if (close(fd)) {
2030 		DPRINTF_S(strerror(errno));
2031 	}
2032 
2033 	spawn(editor, g_tmpfpath, NULL, NULL, F_CLI);
2034 
2035 	if (xconfirm(get_input(messages[MSG_RM_TMP])))
2036 		unlink(g_tmpfpath);
2037 }
2038 
init_fcolors(void)2039 static bool init_fcolors(void)
2040 {
2041 	char *f_colors = getenv(env_cfg[NNN_FCOLORS]);
2042 
2043 	if (!f_colors || !*f_colors)
2044 		f_colors = gcolors;
2045 
2046 	for (uchar_t id = C_BLK; *f_colors && id <= C_UND; ++id) {
2047 		fcolors[id] = xchartohex(*f_colors) << 4;
2048 		if (*++f_colors) {
2049 			fcolors[id] += xchartohex(*f_colors);
2050 			if (fcolors[id])
2051 				init_pair(id, fcolors[id], -1);
2052 		} else
2053 			return FALSE;
2054 		++f_colors;
2055 	}
2056 
2057 	return TRUE;
2058 }
2059 
2060 /* Initialize curses mode */
initcurses(void * oldmask)2061 static bool initcurses(void *oldmask)
2062 {
2063 #ifdef NOMOUSE
2064 	(void) oldmask;
2065 #endif
2066 
2067 	if (g_state.picker) {
2068 		if (!newterm(NULL, stderr, stdin)) {
2069 			msg("newterm!");
2070 			return FALSE;
2071 		}
2072 	} else if (!initscr()) {
2073 		msg("initscr!");
2074 		DPRINTF_S(getenv("TERM"));
2075 		return FALSE;
2076 	}
2077 
2078 	cbreak();
2079 	noecho();
2080 	nonl();
2081 	//intrflush(stdscr, FALSE);
2082 	keypad(stdscr, TRUE);
2083 #ifndef NOMOUSE
2084 #if NCURSES_MOUSE_VERSION <= 1
2085 	mousemask(BUTTON1_PRESSED | BUTTON1_DOUBLE_CLICKED | BUTTON2_PRESSED | BUTTON3_PRESSED,
2086 		  (mmask_t *)oldmask);
2087 #else
2088 	mousemask(BUTTON1_PRESSED | BUTTON2_PRESSED | BUTTON3_PRESSED | BUTTON4_PRESSED
2089 		  | BUTTON5_PRESSED, (mmask_t *)oldmask);
2090 #endif
2091 	mouseinterval(0);
2092 #endif
2093 	curs_set(FALSE); /* Hide cursor */
2094 
2095 	char *colors = getenv(env_cfg[NNN_COLORS]);
2096 
2097 	if (colors || !getenv("NO_COLOR")) {
2098 		uint_t *pcode;
2099 		bool ext = FALSE;
2100 
2101 		start_color();
2102 		use_default_colors();
2103 
2104 		/* Initialize file colors */
2105 		if (COLORS >= COLOR_256) {
2106 			if (!(g_state.oldcolor || init_fcolors())) {
2107 				exitcurses();
2108 				msg(env_cfg[NNN_FCOLORS]);
2109 				return FALSE;
2110 			}
2111 		} else
2112 			g_state.oldcolor = 1;
2113 
2114 		DPRINTF_D(COLORS);
2115 		DPRINTF_D(COLOR_PAIRS);
2116 
2117 		if (colors && *colors == '#') {
2118 			char *sep = strchr(colors, ';');
2119 
2120 			if (!g_state.oldcolor && COLORS >= COLOR_256) {
2121 				++colors;
2122 				ext = TRUE;
2123 
2124 				/*
2125 				 * If fallback colors are specified, set the separator
2126 				 * to NULL so we don't interpret separator and fallback
2127 				 * if fewer than CTX_MAX xterm 256 colors are specified.
2128 				 */
2129 				if (sep)
2130 					*sep = '\0';
2131 			} else {
2132 				colors = sep; /* Detect if 8 colors fallback is appended */
2133 				if (colors)
2134 					++colors;
2135 			}
2136 		}
2137 
2138 		/* Get and set the context colors */
2139 		for (uchar_t i = 0; i <  CTX_MAX; ++i) {
2140 			pcode = &g_ctx[i].color;
2141 
2142 			if (colors && *colors) {
2143 				if (ext) {
2144 					*pcode = xchartohex(*colors) << 4;
2145 					if (*++colors)
2146 						fcolors[i + 1] = *pcode += xchartohex(*colors);
2147 					else { /* Each color code must be 2 hex symbols */
2148 						exitcurses();
2149 						msg(env_cfg[NNN_COLORS]);
2150 						return FALSE;
2151 					}
2152 				} else
2153 					*pcode = (*colors < '0' || *colors > '7') ? 4 : *colors - '0';
2154 				++colors;
2155 			} else
2156 				*pcode = 4;
2157 
2158 			init_pair(i + 1, *pcode, -1);
2159 		}
2160 	}
2161 
2162 #ifdef ICONS_ENABLED
2163 	if (!g_state.oldcolor) {
2164 		uchar_t icolors[COLOR_256] = {0};
2165 		char c;
2166 
2167 		memset(icon_positions, 0x7f, sizeof(icon_positions));
2168 
2169 		for (uint_t i = 0; i < sizeof(icons_ext)/sizeof(struct icon_pair); ++i) {
2170 			c = TOUPPER(icons_ext[i].match[0]);
2171 			if (c >= 'A' && c <= 'Z') {
2172 				if (icon_positions[c - 'A' + 10] == 0x7f7f)
2173 					icon_positions[c - 'A' + 10] = i;
2174 			} else if (c >= '0' && c <= '9') {
2175 				if (icon_positions[c - '0'] == 0x7f7f)
2176 					icon_positions[c - '0'] = i;
2177 			} else if (icon_positions[36] == 0x7f7f)
2178 				icon_positions[36] = i;
2179 
2180 			if (icons_ext[i].color && !icolors[icons_ext[i].color]) {
2181 				init_pair(C_UND + 1 + icons_ext[i].color, icons_ext[i].color, -1);
2182 				icolors[icons_ext[i].color] = 1;
2183 			}
2184 		}
2185 	}
2186 #endif
2187 
2188 	settimeout(); /* One second */
2189 	set_escdelay(25);
2190 	return TRUE;
2191 }
2192 
2193 /* No NULL check here as spawn() guards against it */
parseargs(char * cmd,char ** argv,int * pindex)2194 static char *parseargs(char *cmd, char **argv, int *pindex)
2195 {
2196 	int count = 0;
2197 	size_t len = xstrlen(cmd) + 1;
2198 	char *line = (char *)malloc(len);
2199 
2200 	if (!line) {
2201 		DPRINTF_S("malloc()!");
2202 		return NULL;
2203 	}
2204 
2205 	xstrsncpy(line, cmd, len);
2206 	argv[count++] = line;
2207 	cmd = line;
2208 
2209 	while (*line) { // NOLINT
2210 		if (ISBLANK(*line)) {
2211 			*line++ = '\0';
2212 
2213 			if (!*line) // NOLINT
2214 				break;
2215 
2216 			argv[count++] = line;
2217 			if (count == EXEC_ARGS_MAX) {
2218 				count = -1;
2219 				break;
2220 			}
2221 		}
2222 
2223 		++line;
2224 	}
2225 
2226 	if (count == -1 || count > (EXEC_ARGS_MAX - 4)) { /* 3 args and last NULL */
2227 		free(cmd);
2228 		cmd = NULL;
2229 		DPRINTF_S("NULL or too many args");
2230 	}
2231 
2232 	*pindex = count;
2233 	return cmd;
2234 }
2235 
enable_signals(void)2236 static void enable_signals(void)
2237 {
2238 	struct sigaction dfl_act = {.sa_handler = SIG_DFL};
2239 
2240 	sigaction(SIGHUP, &dfl_act, NULL);
2241 	sigaction(SIGINT, &dfl_act, NULL);
2242 	sigaction(SIGQUIT, &dfl_act, NULL);
2243 	sigaction(SIGTSTP, &dfl_act, NULL);
2244 	sigaction(SIGWINCH, &dfl_act, NULL);
2245 }
2246 
xfork(uchar_t flag)2247 static pid_t xfork(uchar_t flag)
2248 {
2249 	pid_t p = fork();
2250 
2251 	if (p > 0) {
2252 		/* the parent ignores the interrupt, quit and hangup signals */
2253 		sigaction(SIGHUP, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsighup);
2254 		sigaction(SIGTSTP, &(struct sigaction){.sa_handler = SIG_DFL}, &oldsigtstp);
2255 		sigaction(SIGWINCH, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsigwinch);
2256 	} else if (p == 0) {
2257 		/* We create a grandchild to detach */
2258 		if (flag & F_NOWAIT) {
2259 			p = fork();
2260 
2261 			if (p > 0)
2262 				_exit(EXIT_SUCCESS);
2263 			else if (p == 0) {
2264 				enable_signals();
2265 				setsid();
2266 				return p;
2267 			}
2268 
2269 			perror("fork");
2270 			_exit(EXIT_FAILURE);
2271 		}
2272 
2273 		/* So they can be used to stop the child */
2274 		enable_signals();
2275 	}
2276 
2277 	/* This is the parent waiting for the child to create grandchild */
2278 	if (flag & F_NOWAIT)
2279 		waitpid(p, NULL, 0);
2280 
2281 	if (p == -1)
2282 		perror("fork");
2283 	return p;
2284 }
2285 
join(pid_t p,uchar_t flag)2286 static int join(pid_t p, uchar_t flag)
2287 {
2288 	int status = 0xFFFF;
2289 
2290 	if (!(flag & F_NOWAIT)) {
2291 		/* wait for the child to exit */
2292 		do {
2293 		} while (waitpid(p, &status, 0) == -1);
2294 
2295 		if (WIFEXITED(status)) {
2296 			status = WEXITSTATUS(status);
2297 			DPRINTF_D(status);
2298 		}
2299 	}
2300 
2301 	/* restore parent's signal handling */
2302 	sigaction(SIGHUP, &oldsighup, NULL);
2303 	sigaction(SIGTSTP, &oldsigtstp, NULL);
2304 	sigaction(SIGWINCH, &oldsigwinch, NULL);
2305 
2306 	return status;
2307 }
2308 
2309 /*
2310  * Spawns a child process. Behaviour can be controlled using flag.
2311  * Limited to 3 arguments to a program, flag works on bit set.
2312  */
spawn(char * file,char * arg1,char * arg2,char * arg3,ushort_t flag)2313 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag)
2314 {
2315 	pid_t pid;
2316 	int status = 0, retstatus = 0xFFFF;
2317 	char *argv[EXEC_ARGS_MAX] = {0};
2318 	char *cmd = NULL;
2319 
2320 	if (!file || !*file)
2321 		return retstatus;
2322 
2323 	/* Swap args if the first arg is NULL and the other 2 aren't */
2324 	if (!arg1 && arg2) {
2325 		arg1 = arg2;
2326 		if (arg3) {
2327 			arg2 = arg3;
2328 			arg3 = NULL;
2329 		} else
2330 			arg2 = NULL;
2331 	}
2332 
2333 	if (flag & F_MULTI) {
2334 		cmd = parseargs(file, argv, &status);
2335 		if (!cmd)
2336 			return -1;
2337 	} else
2338 		argv[status++] = file;
2339 
2340 	argv[status] = arg1;
2341 	argv[++status] = arg2;
2342 	argv[++status] = arg3;
2343 
2344 	if (flag & F_NORMAL)
2345 		exitcurses();
2346 
2347 	pid = xfork(flag);
2348 	if (pid == 0) {
2349 		/* Suppress stdout and stderr */
2350 		if (flag & F_NOTRACE) {
2351 			int fd = open("/dev/null", O_WRONLY, 0200);
2352 
2353 			if (flag & F_NOSTDIN)
2354 				dup2(fd, STDIN_FILENO);
2355 			dup2(fd, STDOUT_FILENO);
2356 			dup2(fd, STDERR_FILENO);
2357 			close(fd);
2358 		} else if (flag & F_TTY) {
2359 			/* If stdout has been redirected to a non-tty, force output to tty */
2360 			if (!isatty(STDOUT_FILENO)) {
2361 				int fd = open(ctermid(NULL), O_WRONLY, 0200);
2362 				dup2(fd, STDOUT_FILENO);
2363 				close(fd);
2364 			}
2365 		}
2366 
2367 		execvp(*argv, argv);
2368 		_exit(EXIT_SUCCESS);
2369 	} else {
2370 		retstatus = join(pid, flag);
2371 		DPRINTF_D(pid);
2372 
2373 		if ((flag & F_CONFIRM) || ((flag & F_CHKRTN) && retstatus)) {
2374 			status = write(STDOUT_FILENO, messages[MSG_ENTER], xstrlen(messages[MSG_ENTER]));
2375 			(void)status;
2376 			while ((read(STDIN_FILENO, &status, 1) > 0) && (status != '\n'));
2377 		}
2378 
2379 		if (flag & F_NORMAL)
2380 			refresh();
2381 
2382 		free(cmd);
2383 	}
2384 
2385 	return retstatus;
2386 }
2387 
2388 /* Get program name from env var, else return fallback program */
xgetenv(const char * const name,char * fallback)2389 static char *xgetenv(const char * const name, char *fallback)
2390 {
2391 	char *value = getenv(name);
2392 
2393 	return value && value[0] ? value : fallback;
2394 }
2395 
2396 /* Checks if an env variable is set to 1 */
xgetenv_val(const char * name)2397 static inline uint_t xgetenv_val(const char *name)
2398 {
2399 	char *str = getenv(name);
2400 
2401 	if (str && str[0])
2402 		return atoi(str);
2403 
2404 	return 0;
2405 }
2406 
2407 /* Check if a dir exists, IS a dir, and is readable */
xdiraccess(const char * path)2408 static bool xdiraccess(const char *path)
2409 {
2410 	DIR *dirp = opendir(path);
2411 
2412 	if (!dirp) {
2413 		printwarn(NULL);
2414 		return FALSE;
2415 	}
2416 
2417 	closedir(dirp);
2418 	return TRUE;
2419 }
2420 
plugscript(const char * plugin,uchar_t flags)2421 static bool plugscript(const char *plugin, uchar_t flags)
2422 {
2423 	mkpath(plgpath, plugin, g_buf);
2424 	if (!access(g_buf, X_OK)) {
2425 		spawn(g_buf, NULL, NULL, NULL, flags);
2426 		return TRUE;
2427 	}
2428 
2429 	return FALSE;
2430 }
2431 
opstr(char * buf,char * op)2432 static void opstr(char *buf, char *op)
2433 {
2434 	snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c '%s \"$0\" \"$@\" . < /dev/tty' < %s",
2435 		 op, selpath);
2436 }
2437 
rmmulstr(char * buf)2438 static bool rmmulstr(char *buf)
2439 {
2440 	char r = confirm_force(TRUE);
2441 	if (!r)
2442 		return FALSE;
2443 
2444 	if (!g_state.trash)
2445 		snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c 'rm -%cr \"$0\" \"$@\" < /dev/tty' < %s",
2446 			 r, selpath);
2447 	else
2448 		snprintf(buf, CMD_LEN_MAX, "xargs -0 %s < %s",
2449 			 utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH], selpath);
2450 
2451 	return TRUE;
2452 }
2453 
2454 /* Returns TRUE if file is removed, else FALSE */
xrm(char * const fpath)2455 static bool xrm(char * const fpath)
2456 {
2457 	char r = confirm_force(FALSE);
2458 	if (!r)
2459 		return FALSE;
2460 
2461 	if (!g_state.trash) {
2462 		char rm_opts[] = "-ir";
2463 
2464 		rm_opts[1] = r;
2465 		spawn("rm", rm_opts, fpath, NULL, F_NORMAL | F_CHKRTN);
2466 	} else
2467 		spawn(utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH],
2468 		      fpath, NULL, NULL, F_NORMAL | F_MULTI);
2469 
2470 	return (access(fpath, F_OK) == -1); /* File is removed */
2471 }
2472 
xrmfromsel(char * path,char * fpath)2473 static void xrmfromsel(char *path, char *fpath)
2474 {
2475 #ifndef NOX11
2476 	bool selected = TRUE;
2477 #endif
2478 
2479 	if ((pdents[cur].flags & DIR_OR_DIRLNK) && scanselforpath(fpath, FALSE))
2480 		clearselection();
2481 	else if (pdents[cur].flags & FILE_SELECTED) {
2482 		--nselected;
2483 		rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
2484 	}
2485 #ifndef NOX11
2486 	else
2487 		selected = FALSE;
2488 
2489 	if (selected && cfg.x11)
2490 		plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
2491 #endif
2492 }
2493 
lines_in_file(int fd,char * buf,size_t buflen)2494 static uint_t lines_in_file(int fd, char *buf, size_t buflen)
2495 {
2496 	ssize_t len;
2497 	uint_t count = 0;
2498 
2499 	while ((len = read(fd, buf, buflen)) > 0)
2500 		while (len)
2501 			count += (buf[--len] == '\n');
2502 
2503 	/* For all use cases 0 linecount is considered as error */
2504 	return ((len < 0) ? 0 : count);
2505 }
2506 
cpmv_rename(int choice,const char * path)2507 static bool cpmv_rename(int choice, const char *path)
2508 {
2509 	int fd;
2510 	uint_t count = 0, lines = 0;
2511 	bool ret = FALSE;
2512 	char *cmd = (choice == 'c' ? cp : mv);
2513 	char buf[sizeof(patterns[P_CPMVRNM]) + sizeof(cmd) + (PATH_MAX << 1)];
2514 
2515 	fd = create_tmp_file();
2516 	if (fd == -1)
2517 		return ret;
2518 
2519 	/* selsafe() returned TRUE for this to be called */
2520 	if (!selbufpos) {
2521 		snprintf(buf, sizeof(buf), "tr '\\0' '\\n' < %s > %s", selpath, g_tmpfpath);
2522 		spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2523 
2524 		count = lines_in_file(fd, buf, sizeof(buf));
2525 		if (!count)
2526 			goto finish;
2527 	} else
2528 		seltofile(fd, &count);
2529 
2530 	close(fd);
2531 
2532 	snprintf(buf, sizeof(buf), patterns[P_CPMVFMT], g_tmpfpath);
2533 	spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2534 
2535 	spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2536 
2537 	fd = open(g_tmpfpath, O_RDONLY);
2538 	if (fd == -1)
2539 		goto finish;
2540 
2541 	lines = lines_in_file(fd, buf, sizeof(buf));
2542 	DPRINTF_U(count);
2543 	DPRINTF_U(lines);
2544 	if (!lines || (2 * count != lines)) {
2545 		DPRINTF_S("num mismatch");
2546 		goto finish;
2547 	}
2548 
2549 	snprintf(buf, sizeof(buf), patterns[P_CPMVRNM], path, g_tmpfpath, cmd);
2550 	if (!spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CHKRTN))
2551 		ret = TRUE;
2552 finish:
2553 	if (fd >= 0)
2554 		close(fd);
2555 
2556 	return ret;
2557 }
2558 
cpmvrm_selection(enum action sel,char * path)2559 static bool cpmvrm_selection(enum action sel, char *path)
2560 {
2561 	int r;
2562 
2563 	if (isselfileempty()) {
2564 		if (nselected)
2565 			clearselection();
2566 		printmsg(messages[MSG_0_SELECTED]);
2567 		return FALSE;
2568 	}
2569 
2570 	if (!selsafe())
2571 		return FALSE;
2572 
2573 	switch (sel) {
2574 	case SEL_CP:
2575 		opstr(g_buf, cp);
2576 		break;
2577 	case SEL_MV:
2578 		opstr(g_buf, mv);
2579 		break;
2580 	case SEL_CPMVAS:
2581 		r = get_input(messages[MSG_CP_MV_AS]);
2582 		if (r != 'c' && r != 'm') {
2583 			printmsg(messages[MSG_INVALID_KEY]);
2584 			return FALSE;
2585 		}
2586 
2587 		if (!cpmv_rename(r, path)) {
2588 			printmsg(messages[MSG_FAILED]);
2589 			return FALSE;
2590 		}
2591 		break;
2592 	default: /* SEL_RM */
2593 		if (!rmmulstr(g_buf)) {
2594 			printmsg(messages[MSG_CANCEL]);
2595 			return FALSE;
2596 		}
2597 	}
2598 
2599 	if (sel != SEL_CPMVAS && spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CHKRTN)) {
2600 		printmsg(messages[MSG_FAILED]);
2601 		return FALSE;
2602 	}
2603 
2604 	/* Clear selection */
2605 	clearselection();
2606 
2607 	return TRUE;
2608 }
2609 
2610 #ifndef NOBATCH
batch_rename(void)2611 static bool batch_rename(void)
2612 {
2613 	int fd1, fd2;
2614 	uint_t count = 0, lines = 0;
2615 	bool dir = FALSE, ret = FALSE;
2616 	char foriginal[TMP_LEN_MAX] = {0};
2617 	static const char batchrenamecmd[] = "paste -d'\n' %s %s | "SED" 'N; /^\\(.*\\)\\n\\1$/!p;d' | "
2618 					     "tr '\n' '\\0' | xargs -0 -n2 sh -c 'mv -i \"$0\" \"$@\" <"
2619 					     " /dev/tty'";
2620 	char buf[sizeof(batchrenamecmd) + (PATH_MAX << 1)];
2621 	int i = get_cur_or_sel();
2622 
2623 	if (!i)
2624 		return ret;
2625 
2626 	if (i == 'c') { /* Rename entries in current dir */
2627 		selbufpos = 0;
2628 		dir = TRUE;
2629 	}
2630 
2631 	fd1 = create_tmp_file();
2632 	if (fd1 == -1)
2633 		return ret;
2634 
2635 	xstrsncpy(foriginal, g_tmpfpath, xstrlen(g_tmpfpath) + 1);
2636 
2637 	fd2 = create_tmp_file();
2638 	if (fd2 == -1) {
2639 		unlink(foriginal);
2640 		close(fd1);
2641 		return ret;
2642 	}
2643 
2644 	if (dir)
2645 		for (i = 0; i < ndents; ++i)
2646 			appendfpath(pdents[i].name, NAME_MAX);
2647 
2648 	seltofile(fd1, &count);
2649 	seltofile(fd2, NULL);
2650 	close(fd2);
2651 
2652 	if (dir) /* Don't retain dir entries in selection */
2653 		selbufpos = 0;
2654 
2655 	spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2656 
2657 	/* Reopen file descriptor to get updated contents */
2658 	fd2 = open(g_tmpfpath, O_RDONLY);
2659 	if (fd2 == -1)
2660 		goto finish;
2661 
2662 	lines = lines_in_file(fd2, buf, sizeof(buf));
2663 	DPRINTF_U(count);
2664 	DPRINTF_U(lines);
2665 	if (!lines || (count != lines)) {
2666 		DPRINTF_S("cannot delete files");
2667 		goto finish;
2668 	}
2669 
2670 	snprintf(buf, sizeof(buf), batchrenamecmd, foriginal, g_tmpfpath);
2671 	spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2672 	ret = TRUE;
2673 
2674 finish:
2675 	if (fd1 >= 0)
2676 		close(fd1);
2677 	unlink(foriginal);
2678 
2679 	if (fd2 >= 0)
2680 		close(fd2);
2681 	unlink(g_tmpfpath);
2682 
2683 	return ret;
2684 }
2685 #endif
2686 
get_archive_cmd(char * cmd,const char * archive)2687 static void get_archive_cmd(char *cmd, const char *archive)
2688 {
2689 	uchar_t i = 3;
2690 
2691 	if (getutil(utils[UTIL_ATOOL]))
2692 		i = 0;
2693 	else if (getutil(utils[UTIL_BSDTAR]))
2694 		i = 1;
2695 	else if (is_suffix(archive, ".zip"))
2696 		i = 2;
2697 	// else tar
2698 
2699 	xstrsncpy(cmd, archive_cmd[i], ARCHIVE_CMD_LEN);
2700 }
2701 
archive_selection(const char * cmd,const char * archive,const char * curpath)2702 static void archive_selection(const char *cmd, const char *archive, const char *curpath)
2703 {
2704 	/* The 70 comes from the string below */
2705 	char *buf = (char *)malloc((70 + xstrlen(cmd) + xstrlen(archive)
2706 				       + xstrlen(curpath) + xstrlen(selpath)) * sizeof(char));
2707 	if (!buf) {
2708 		DPRINTF_S(strerror(errno));
2709 		printwarn(NULL);
2710 		return;
2711 	}
2712 
2713 	snprintf(buf, CMD_LEN_MAX,
2714 #ifdef __linux__
2715 		SED" -ze 's|^%s/||' '%s' | xargs -0 %s %s", curpath, selpath, cmd, archive
2716 #else
2717 		"tr '\\0' '\n' < '%s' | "SED" -e 's|^%s/||' | tr '\n' '\\0' | xargs -0 %s %s",
2718 		selpath, curpath, cmd, archive
2719 #endif
2720 		);
2721 	spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CONFIRM);
2722 	free(buf);
2723 }
2724 
write_lastdir(const char * curpath,const char * outfile)2725 static void write_lastdir(const char *curpath, const char *outfile)
2726 {
2727 	if (!outfile)
2728 		xstrsncpy(cfgpath + xstrlen(cfgpath), "/.lastd", 8);
2729 	else
2730 		convert_tilde(outfile, g_buf);
2731 
2732 	int fd = open(outfile
2733 			? (outfile[0] == '~' ? g_buf : outfile)
2734 			: cfgpath, O_CREAT | O_WRONLY | O_TRUNC, 0666);
2735 
2736 	if (fd != -1) {
2737 		dprintf(fd, "cd \"%s\"", curpath);
2738 		close(fd);
2739 	}
2740 }
2741 
2742 /*
2743  * We assume none of the strings are NULL.
2744  *
2745  * Let's have the logic to sort numeric names in numeric order.
2746  * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
2747  *
2748  * If the absolute numeric values are same, we fallback to alphasort.
2749  */
xstricmp(const char * const s1,const char * const s2)2750 static int xstricmp(const char * const s1, const char * const s2)
2751 {
2752 	char *p1, *p2;
2753 
2754 	long long v1 = strtoll(s1, &p1, 10);
2755 	long long v2 = strtoll(s2, &p2, 10);
2756 
2757 	/* Check if at least 1 string is numeric */
2758 	if (s1 != p1 || s2 != p2) {
2759 		/* Handle both pure numeric */
2760 		if (s1 != p1 && s2 != p2) {
2761 			if (v2 > v1)
2762 				return -1;
2763 
2764 			if (v1 > v2)
2765 				return 1;
2766 		}
2767 
2768 		/* Only first string non-numeric */
2769 		if (s1 == p1)
2770 			return 1;
2771 
2772 		/* Only second string non-numeric */
2773 		if (s2 == p2)
2774 			return -1;
2775 	}
2776 
2777 	/* Handle 1. all non-numeric and 2. both same numeric value cases */
2778 #ifndef NOLC
2779 	return strcoll(s1, s2);
2780 #else
2781 	return strcasecmp(s1, s2);
2782 #endif
2783 }
2784 
2785 /*
2786  * Version comparison
2787  *
2788  * The code for version compare is a modified version of the GLIBC
2789  * and uClibc implementation of strverscmp(). The source is here:
2790  * https://elixir.bootlin.com/uclibc-ng/latest/source/libc/string/strverscmp.c
2791  */
2792 
2793 /*
2794  * Compare S1 and S2 as strings holding indices/version numbers,
2795  * returning less than, equal to or greater than zero if S1 is less than,
2796  * equal to or greater than S2 (for more info, see the texinfo doc).
2797  *
2798  * Ignores case.
2799  */
xstrverscasecmp(const char * const s1,const char * const s2)2800 static int xstrverscasecmp(const char * const s1, const char * const s2)
2801 {
2802 	const uchar_t *p1 = (const uchar_t *)s1;
2803 	const uchar_t *p2 = (const uchar_t *)s2;
2804 	int state, diff;
2805 	uchar_t c1, c2;
2806 
2807 	/*
2808 	 * Symbol(s)    0       [1-9]   others
2809 	 * Transition   (10) 0  (01) d  (00) x
2810 	 */
2811 	static const uint8_t next_state[] = {
2812 		/* state    x    d    0  */
2813 		/* S_N */  S_N, S_I, S_Z,
2814 		/* S_I */  S_N, S_I, S_I,
2815 		/* S_F */  S_N, S_F, S_F,
2816 		/* S_Z */  S_N, S_F, S_Z
2817 	};
2818 
2819 	static const int8_t result_type[] __attribute__ ((aligned)) = {
2820 		/* state   x/x  x/d  x/0  d/x  d/d  d/0  0/x  0/d  0/0  */
2821 
2822 		/* S_N */  VCMP, VCMP, VCMP, VCMP, VLEN, VCMP, VCMP, VCMP, VCMP,
2823 		/* S_I */  VCMP,   -1,   -1,    1, VLEN, VLEN,    1, VLEN, VLEN,
2824 		/* S_F */  VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP,
2825 		/* S_Z */  VCMP,    1,    1,   -1, VCMP, VCMP,   -1, VCMP, VCMP
2826 	};
2827 
2828 	if (p1 == p2)
2829 		return 0;
2830 
2831 	c1 = TOUPPER(*p1);
2832 	++p1;
2833 	c2 = TOUPPER(*p2);
2834 	++p2;
2835 
2836 	/* Hint: '0' is a digit too.  */
2837 	state = S_N + ((c1 == '0') + (xisdigit(c1) != 0));
2838 
2839 	while ((diff = c1 - c2) == 0) {
2840 		if (c1 == '\0')
2841 			return diff;
2842 
2843 		state = next_state[state];
2844 		c1 = TOUPPER(*p1);
2845 		++p1;
2846 		c2 = TOUPPER(*p2);
2847 		++p2;
2848 		state += (c1 == '0') + (xisdigit(c1) != 0);
2849 	}
2850 
2851 	state = result_type[state * 3 + (((c2 == '0') + (xisdigit(c2) != 0)))]; // NOLINT
2852 
2853 	switch (state) {
2854 	case VCMP:
2855 		return diff;
2856 	case VLEN:
2857 		while (xisdigit(*p1++))
2858 			if (!xisdigit(*p2++))
2859 				return 1;
2860 		return xisdigit(*p2) ? -1 : diff;
2861 	default:
2862 		return state;
2863 	}
2864 }
2865 
2866 static int (*namecmpfn)(const char * const s1, const char * const s2) = &xstricmp;
2867 
2868 static char * (*fnstrstr)(const char *haystack, const char *needle) = &strcasestr;
2869 #ifdef PCRE
2870 static const unsigned char *tables;
2871 static int pcreflags = PCRE_NO_AUTO_CAPTURE | PCRE_EXTENDED | PCRE_CASELESS | PCRE_UTF8;
2872 #else
2873 static int regflags = REG_NOSUB | REG_EXTENDED | REG_ICASE;
2874 #endif
2875 
2876 #ifdef PCRE
setfilter(pcre ** pcrex,const char * filter)2877 static int setfilter(pcre **pcrex, const char *filter)
2878 {
2879 	const char *errstr = NULL;
2880 	int erroffset = 0;
2881 
2882 	*pcrex = pcre_compile(filter, pcreflags, &errstr, &erroffset, tables);
2883 
2884 	return errstr ? -1 : 0;
2885 }
2886 #else
setfilter(regex_t * regex,const char * filter)2887 static int setfilter(regex_t *regex, const char *filter)
2888 {
2889 	return regcomp(regex, filter, regflags);
2890 }
2891 #endif
2892 
visible_re(const fltrexp_t * fltrexp,const char * fname)2893 static int visible_re(const fltrexp_t *fltrexp, const char *fname)
2894 {
2895 #ifdef PCRE
2896 	return pcre_exec(fltrexp->pcrex, NULL, fname, xstrlen(fname), 0, 0, NULL, 0) == 0;
2897 #else
2898 	return regexec(fltrexp->regex, fname, 0, NULL, 0) == 0;
2899 #endif
2900 }
2901 
visible_str(const fltrexp_t * fltrexp,const char * fname)2902 static int visible_str(const fltrexp_t *fltrexp, const char *fname)
2903 {
2904 	return fnstrstr(fname, fltrexp->str) != NULL;
2905 }
2906 
2907 static int (*filterfn)(const fltrexp_t *fltr, const char *fname) = &visible_str;
2908 
clearfilter(void)2909 static void clearfilter(void)
2910 {
2911 	char *fltr = g_ctx[cfg.curctx].c_fltr;
2912 
2913 	if (fltr[1]) {
2914 		fltr[REGEX_MAX - 1] = fltr[1];
2915 		fltr[1] = '\0';
2916 	}
2917 }
2918 
entrycmp(const void * va,const void * vb)2919 static int entrycmp(const void *va, const void *vb)
2920 {
2921 	const struct entry *pa = (pEntry)va;
2922 	const struct entry *pb = (pEntry)vb;
2923 
2924 	if ((pb->flags & DIR_OR_DIRLNK) != (pa->flags & DIR_OR_DIRLNK)) {
2925 		if (pb->flags & DIR_OR_DIRLNK)
2926 			return 1;
2927 		return -1;
2928 	}
2929 
2930 	/* Sort based on specified order */
2931 	if (cfg.timeorder) {
2932 		if (pb->sec > pa->sec)
2933 			return 1;
2934 		if (pb->sec < pa->sec)
2935 			return -1;
2936 		/* If sec matches, comare nsec */
2937 		if (pb->nsec > pa->nsec)
2938 			return 1;
2939 		if (pb->nsec < pa->nsec)
2940 			return -1;
2941 	} else if (cfg.sizeorder) {
2942 		if (pb->size > pa->size)
2943 			return 1;
2944 		if (pb->size < pa->size)
2945 			return -1;
2946 	} else if (cfg.blkorder) {
2947 		if (pb->blocks > pa->blocks)
2948 			return 1;
2949 		if (pb->blocks < pa->blocks)
2950 			return -1;
2951 	} else if (cfg.extnorder && !(pb->flags & DIR_OR_DIRLNK)) {
2952 		char *extna = xextension(pa->name, pa->nlen - 1);
2953 		char *extnb = xextension(pb->name, pb->nlen - 1);
2954 
2955 		if (extna || extnb) {
2956 			if (!extna)
2957 				return -1;
2958 
2959 			if (!extnb)
2960 				return 1;
2961 
2962 			int ret = strcasecmp(extna, extnb);
2963 
2964 			if (ret)
2965 				return ret;
2966 		}
2967 	}
2968 
2969 	return namecmpfn(pa->name, pb->name);
2970 }
2971 
reventrycmp(const void * va,const void * vb)2972 static int reventrycmp(const void *va, const void *vb)
2973 {
2974 	if ((((pEntry)vb)->flags & DIR_OR_DIRLNK)
2975 	    != (((pEntry)va)->flags & DIR_OR_DIRLNK)) {
2976 		if (((pEntry)vb)->flags & DIR_OR_DIRLNK)
2977 			return 1;
2978 		return -1;
2979 	}
2980 
2981 	return -entrycmp(va, vb);
2982 }
2983 
2984 static int (*entrycmpfn)(const void *va, const void *vb) = &entrycmp;
2985 
2986 /* In case of an error, resets *wch to Esc */
handle_alt_key(wint_t * wch)2987 static int handle_alt_key(wint_t *wch)
2988 {
2989 	timeout(0);
2990 
2991 	int r = get_wch(wch);
2992 
2993 	if (r == ERR)
2994 		*wch = ESC;
2995 	cleartimeout();
2996 
2997 	return r;
2998 }
2999 
handle_event(void)3000 static inline int handle_event(void)
3001 {
3002 	if (nselected && isselfileempty())
3003 		clearselection();
3004 	return CONTROL('L');
3005 }
3006 
3007 /*
3008  * Returns SEL_* if key is bound and 0 otherwise.
3009  * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
3010  * The next keyboard input can be simulated by presel.
3011  */
nextsel(int presel)3012 static int nextsel(int presel)
3013 {
3014 #ifdef BENCH
3015 	return SEL_QUIT;
3016 #endif
3017 	int c = presel;
3018 	uint_t i;
3019 	bool escaped = FALSE;
3020 
3021 	if (c == 0 || c == MSGWAIT) {
3022 try_quit:
3023 		c = getch();
3024 		//DPRINTF_D(c);
3025 		//DPRINTF_S(keyname(c));
3026 
3027 #ifdef KEY_RESIZE
3028 		if (c == KEY_RESIZE)
3029 			handle_key_resize();
3030 #endif
3031 
3032 		/* Handle Alt+key */
3033 		if (c == ESC) {
3034 			timeout(0);
3035 			c = getch();
3036 			if (c != ERR) {
3037 				if (c == ESC)
3038 					c = CONTROL('L');
3039 				else {
3040 					ungetch(c);
3041 					c = ';';
3042 				}
3043 				settimeout();
3044 			} else if (escaped) {
3045 				settimeout();
3046 				c = CONTROL('Q');
3047 			} else {
3048 #ifndef NOFIFO
3049 				if (!g_state.fifomode)
3050 					notify_fifo(TRUE); /* Send hovered path to NNN_FIFO */
3051 #endif
3052 				escaped = TRUE;
3053 				settimeout();
3054 				goto try_quit;
3055 			}
3056 		}
3057 
3058 		if (c == ERR && presel == MSGWAIT)
3059 			c = (cfg.filtermode || filterset()) ? FILTER : CONTROL('L');
3060 		else if (c == FILTER || c == CONTROL('L'))
3061 			/* Clear previous filter when manually starting */
3062 			clearfilter();
3063 	}
3064 
3065 	if (c == -1) {
3066 		++idle;
3067 
3068 		/*
3069 		 * Do not check for directory changes in du mode.
3070 		 * A redraw forces du calculation.
3071 		 * Check for changes every odd second.
3072 		 */
3073 #ifdef LINUX_INOTIFY
3074 		if (!cfg.blkorder && inotify_wd >= 0 && (idle & 1)) {
3075 			struct inotify_event *event;
3076 			char inotify_buf[EVENT_BUF_LEN];
3077 
3078 			memset((void *)inotify_buf, 0x0, EVENT_BUF_LEN);
3079 			i = read(inotify_fd, inotify_buf, EVENT_BUF_LEN);
3080 			if (i > 0) {
3081 				for (char *ptr = inotify_buf;
3082 				     ptr + ((struct inotify_event *)ptr)->len < inotify_buf + i;
3083 				     ptr += sizeof(struct inotify_event) + event->len) {
3084 					event = (struct inotify_event *)ptr;
3085 					DPRINTF_D(event->wd);
3086 					DPRINTF_D(event->mask);
3087 					if (!event->wd)
3088 						break;
3089 
3090 					if (event->mask & INOTIFY_MASK) {
3091 						c = handle_event();
3092 						break;
3093 					}
3094 				}
3095 				DPRINTF_S("inotify read done");
3096 			}
3097 		}
3098 #elif defined(BSD_KQUEUE)
3099 		if (!cfg.blkorder && event_fd >= 0 && (idle & 1)) {
3100 			struct kevent event_data[NUM_EVENT_SLOTS];
3101 
3102 			memset((void *)event_data, 0x0, sizeof(struct kevent) * NUM_EVENT_SLOTS);
3103 			if (kevent(kq, events_to_monitor, NUM_EVENT_SLOTS,
3104 				   event_data, NUM_EVENT_FDS, &gtimeout) > 0)
3105 				c = handle_event();
3106 		}
3107 #elif defined(HAIKU_NM)
3108 		if (!cfg.blkorder && haiku_nm_active && (idle & 1) && haiku_is_update_needed(haiku_hnd))
3109 			c = handle_event();
3110 #endif
3111 	} else
3112 		idle = 0;
3113 
3114 	for (i = 0; i < (int)ELEMENTS(bindings); ++i)
3115 		if (c == bindings[i].sym)
3116 			return bindings[i].act;
3117 
3118 	return 0;
3119 }
3120 
getorderstr(char * sort)3121 static int getorderstr(char *sort)
3122 {
3123 	int i = 0;
3124 
3125 	if (cfg.showhidden)
3126 		sort[i++] = 'H';
3127 
3128 	if (cfg.timeorder)
3129 		sort[i++] = (cfg.timetype == T_MOD) ? 'M' : ((cfg.timetype == T_ACCESS) ? 'A' : 'C');
3130 	else if (cfg.sizeorder)
3131 		sort[i++] = 'S';
3132 	else if (cfg.extnorder)
3133 		sort[i++] = 'E';
3134 
3135 	if (entrycmpfn == &reventrycmp)
3136 		sort[i++] = 'R';
3137 
3138 	if (namecmpfn == &xstrverscasecmp)
3139 		sort[i++] = 'V';
3140 
3141 	if (i)
3142 		sort[i] = ' ';
3143 
3144 	return i;
3145 }
3146 
showfilterinfo(void)3147 static void showfilterinfo(void)
3148 {
3149 	int i = 0;
3150 	char info[REGEX_MAX] = "\0\0\0\0\0";
3151 
3152 	i = getorderstr(info);
3153 
3154 	snprintf(info + i, REGEX_MAX - i - 1, "  %s [/], %s [:]",
3155 		 (cfg.regex ? "reg" : "str"),
3156 		 ((fnstrstr == &strcasestr) ? "ic" : "noic"));
3157 
3158 	clearinfoln();
3159 	mvaddstr(xlines - 2, xcols - xstrlen(info), info);
3160 }
3161 
showfilter(char * str)3162 static void showfilter(char *str)
3163 {
3164 	attron(COLOR_PAIR(cfg.curctx + 1));
3165 	showfilterinfo();
3166 	printmsg(str);
3167 	// printmsg calls attroff()
3168 }
3169 
swap_ent(int id1,int id2)3170 static inline void swap_ent(int id1, int id2)
3171 {
3172 	struct entry _dent, *pdent1 = &pdents[id1], *pdent2 =  &pdents[id2];
3173 
3174 	*(&_dent) = *pdent1;
3175 	*pdent1 = *pdent2;
3176 	*pdent2 = *(&_dent);
3177 }
3178 
3179 #ifdef PCRE
fill(const char * fltr,pcre * pcrex)3180 static int fill(const char *fltr, pcre *pcrex)
3181 #else
3182 static int fill(const char *fltr, regex_t *re)
3183 #endif
3184 {
3185 #ifdef PCRE
3186 	fltrexp_t fltrexp = { .pcrex = pcrex, .str = fltr };
3187 #else
3188 	fltrexp_t fltrexp = { .regex = re, .str = fltr };
3189 #endif
3190 
3191 	for (int count = 0; count < ndents; ++count) {
3192 		if (filterfn(&fltrexp, pdents[count].name) == 0) {
3193 			if (count != --ndents) {
3194 				swap_ent(count, ndents);
3195 				--count;
3196 			}
3197 
3198 			continue;
3199 		}
3200 	}
3201 
3202 	return ndents;
3203 }
3204 
matches(const char * fltr)3205 static int matches(const char *fltr)
3206 {
3207 #ifdef PCRE
3208 	pcre *pcrex = NULL;
3209 
3210 	/* Search filter */
3211 	if (cfg.regex && setfilter(&pcrex, fltr))
3212 		return -1;
3213 
3214 	ndents = fill(fltr, pcrex);
3215 
3216 	if (cfg.regex)
3217 		pcre_free(pcrex);
3218 #else
3219 	regex_t re;
3220 
3221 	/* Search filter */
3222 	if (cfg.regex && setfilter(&re, fltr))
3223 		return -1;
3224 
3225 	ndents = fill(fltr, &re);
3226 
3227 	if (cfg.regex)
3228 		regfree(&re);
3229 #endif
3230 
3231 	ENTSORT(pdents, ndents, entrycmpfn);
3232 
3233 	return ndents;
3234 }
3235 
3236 /*
3237  * Return the position of the matching entry or 0 otherwise
3238  * Note there's no NULL check for fname
3239  */
dentfind(const char * fname,int n)3240 static int dentfind(const char *fname, int n)
3241 {
3242 	for (int i = 0; i < n; ++i)
3243 		if (xstrcmp(fname, pdents[i].name) == 0)
3244 			return i;
3245 
3246 	return 0;
3247 }
3248 
filterentries(char * path,char * lastname)3249 static int filterentries(char *path, char *lastname)
3250 {
3251 	wchar_t *wln = (wchar_t *)alloca(sizeof(wchar_t) * REGEX_MAX);
3252 	char *ln = g_ctx[cfg.curctx].c_fltr;
3253 	wint_t ch[2] = {0};
3254 	int r, total = ndents, len;
3255 	char *pln = g_ctx[cfg.curctx].c_fltr + 1;
3256 
3257 	DPRINTF_S(__func__);
3258 
3259 	if (ndents && (ln[0] == FILTER || ln[0] == RFILTER) && *pln) {
3260 		if (matches(pln) != -1) {
3261 			move_cursor(dentfind(lastname, ndents), 0);
3262 			redraw(path);
3263 		}
3264 
3265 		if (!cfg.filtermode) {
3266 			statusbar(path);
3267 			return 0;
3268 		}
3269 
3270 		len = mbstowcs(wln, ln, REGEX_MAX);
3271 	} else {
3272 		ln[0] = wln[0] = cfg.regex ? RFILTER : FILTER;
3273 		ln[1] = wln[1] = '\0';
3274 		len = 1;
3275 	}
3276 
3277 	cleartimeout();
3278 	curs_set(TRUE);
3279 	showfilter(ln);
3280 
3281 	while ((r = get_wch(ch)) != ERR) {
3282 		//DPRINTF_D(*ch);
3283 		//DPRINTF_S(keyname(*ch));
3284 
3285 		switch (*ch) {
3286 #ifdef KEY_RESIZE
3287 		case 0: // fallthrough
3288 		case KEY_RESIZE:
3289 			clearoldprompt();
3290 			redraw(path);
3291 			showfilter(ln);
3292 			continue;
3293 #endif
3294 		case KEY_DC: // fallthrough
3295 		case KEY_BACKSPACE: // fallthrough
3296 		case '\b': // fallthrough
3297 		case DEL: /* handle DEL */
3298 			if (len != 1) {
3299 				wln[--len] = '\0';
3300 				wcstombs(ln, wln, REGEX_MAX);
3301 				ndents = total;
3302 			} else {
3303 				*ch = FILTER;
3304 				goto end;
3305 			}
3306 			// fallthrough
3307 		case CONTROL('L'):
3308 			if (*ch == CONTROL('L')) {
3309 				if (wln[1]) {
3310 					ln[REGEX_MAX - 1] = ln[1];
3311 					ln[1] = wln[1] = '\0';
3312 					len = 1;
3313 					ndents = total;
3314 				} else if (ln[REGEX_MAX - 1]) { /* Show the previous filter */
3315 					ln[1] = ln[REGEX_MAX - 1];
3316 					ln[REGEX_MAX - 1] = '\0';
3317 					len = mbstowcs(wln, ln, REGEX_MAX);
3318 				} else
3319 					goto end;
3320 			}
3321 
3322 			/* Go to the top, we don't know if the hovered file will match the filter */
3323 			cur = 0;
3324 
3325 			if (matches(pln) != -1)
3326 				redraw(path);
3327 
3328 			showfilter(ln);
3329 			continue;
3330 #ifndef NOMOUSE
3331 		case KEY_MOUSE:
3332 			goto end;
3333 #endif
3334 		case ESC:
3335 			if (handle_alt_key(ch) != ERR) {
3336 				if (*ch == ESC) /* Handle Alt+Esc */
3337 					*ch = 'q'; /* Quit context */
3338 				else {
3339 					unget_wch(*ch);
3340 					*ch = ';'; /* Run plugin */
3341 				}
3342 			}
3343 			goto end;
3344 		}
3345 
3346 		if (r != OK) /* Handle Fn keys in main loop */
3347 			break;
3348 
3349 		/* Handle all control chars in main loop */
3350 		if (*ch < ASCII_MAX && keyname(*ch)[0] == '^' && *ch != '^')
3351 			goto end;
3352 
3353 		if (len == 1) {
3354 			if (*ch == '?') /* Help and config key, '?' is an invalid regex */
3355 				goto end;
3356 
3357 			if (cfg.filtermode) {
3358 				switch (*ch) {
3359 				case '\'': // fallthrough /* Go to first non-dir file */
3360 				case '+': // fallthrough /* Toggle auto-advance */
3361 				case ',': // fallthrough /* Mark CWD */
3362 				case '-': // fallthrough /* Visit last visited dir */
3363 				case '.': // fallthrough /* Show hidden files */
3364 				case ';': // fallthrough /* Run plugin key */
3365 				case '=': // fallthrough /* Launch app */
3366 				case '>': // fallthrough /* Export file list */
3367 				case '@': // fallthrough /* Visit start dir */
3368 				case ']': // fallthorugh /* Prompt key */
3369 				case '`': // fallthrough /* Visit / */
3370 				case '~': /* Go HOME */
3371 					goto end;
3372 				}
3373 			}
3374 
3375 			/* Toggle case-sensitivity */
3376 			if (*ch == CASE) {
3377 				fnstrstr = (fnstrstr == &strcasestr) ? &strstr : &strcasestr;
3378 #ifdef PCRE
3379 				pcreflags ^= PCRE_CASELESS;
3380 #else
3381 				regflags ^= REG_ICASE;
3382 #endif
3383 				showfilter(ln);
3384 				continue;
3385 			}
3386 
3387 			/* Toggle string or regex filter */
3388 			if (*ch == FILTER) {
3389 				ln[0] = (ln[0] == FILTER) ? RFILTER : FILTER;
3390 				wln[0] = (uchar_t)ln[0];
3391 				cfg.regex ^= 1;
3392 				filterfn = cfg.regex ? &visible_re : &visible_str;
3393 				showfilter(ln);
3394 				continue;
3395 			}
3396 
3397 			/* Reset cur in case it's a repeat search */
3398 			cur = 0;
3399 		} else if (len == REGEX_MAX - 1)
3400 			continue;
3401 
3402 		wln[len] = (wchar_t)*ch;
3403 		wln[++len] = '\0';
3404 		wcstombs(ln, wln, REGEX_MAX);
3405 
3406 		/* Forward-filtering optimization:
3407 		 * - new matches can only be a subset of current matches.
3408 		 */
3409 		/* ndents = total; */
3410 #ifdef MATCHFLTR
3411 		r = matches(pln);
3412 		if (r <= 0) {
3413 			!r ? unget_wch(KEY_BACKSPACE) : showfilter(ln);
3414 #else
3415 		if (matches(pln) == -1) {
3416 			showfilter(ln);
3417 #endif
3418 			continue;
3419 		}
3420 
3421 		/* If the only match is a dir, auto-select and cd into it */
3422 		if (ndents == 1 && cfg.filtermode
3423 		    && cfg.autoselect && (pdents[0].flags & DIR_OR_DIRLNK)) {
3424 			*ch = KEY_ENTER;
3425 			cur = 0;
3426 			goto end;
3427 		}
3428 
3429 		/*
3430 		 * redraw() should be above the auto-select optimization, for
3431 		 * the case where there's an issue with dir auto-select, say,
3432 		 * due to a permission problem. The transition is _jumpy_ in
3433 		 * case of such an error. However, we optimize for successful
3434 		 * cases where the dir has permissions. This skips a redraw().
3435 		 */
3436 		redraw(path);
3437 		showfilter(ln);
3438 	}
3439 end:
3440 	clearinfoln();
3441 
3442 	/* Save last working filter in-filter */
3443 	if (ln[1])
3444 		ln[REGEX_MAX - 1] = ln[1];
3445 
3446 	/* Save current */
3447 	copycurname();
3448 
3449 	curs_set(FALSE);
3450 	settimeout();
3451 
3452 	/* Return keys for navigation etc. */
3453 	return *ch;
3454 }
3455 
3456 /* Show a prompt with input string and return the changes */
3457 static char *xreadline(const char *prefill, const char *prompt)
3458 {
3459 	size_t len, pos;
3460 	int x, r;
3461 	const int WCHAR_T_WIDTH = sizeof(wchar_t);
3462 	wint_t ch[2] = {0};
3463 	wchar_t * const buf = malloc(sizeof(wchar_t) * READLINE_MAX);
3464 
3465 	if (!buf)
3466 		errexit();
3467 
3468 	cleartimeout();
3469 	printmsg(prompt);
3470 
3471 	if (prefill) {
3472 		DPRINTF_S(prefill);
3473 		len = pos = mbstowcs(buf, prefill, READLINE_MAX);
3474 	} else
3475 		len = (size_t)-1;
3476 
3477 	if (len == (size_t)-1) {
3478 		buf[0] = '\0';
3479 		len = pos = 0;
3480 	}
3481 
3482 	x = getcurx(stdscr);
3483 	curs_set(TRUE);
3484 
3485 	while (1) {
3486 		buf[len] = ' ';
3487 		attron(COLOR_PAIR(cfg.curctx + 1));
3488 		mvaddnwstr(xlines - 1, x, buf, len + 1);
3489 		move(xlines - 1, x + wcswidth(buf, pos));
3490 		attroff(COLOR_PAIR(cfg.curctx + 1));
3491 
3492 		r = get_wch(ch);
3493 		if (r == ERR)
3494 			continue;
3495 
3496 		if (r == OK) {
3497 			switch (*ch) {
3498 			case KEY_ENTER: // fallthrough
3499 			case '\n': // fallthrough
3500 			case '\r':
3501 				goto END;
3502 			case CONTROL('D'):
3503 				if (pos < len)
3504 					++pos;
3505 				else if (!(pos || len)) { /* Exit on ^D at empty prompt */
3506 					len = 0;
3507 					goto END;
3508 				} else
3509 					continue;
3510 				// fallthrough
3511 			case DEL: // fallthrough
3512 			case '\b': /* rhel25 sends '\b' for backspace */
3513 				if (pos > 0) {
3514 					memmove(buf + pos - 1, buf + pos,
3515 						(len - pos) * WCHAR_T_WIDTH);
3516 					--len, --pos;
3517 				}
3518 				continue;
3519 			case '\t':
3520 				if (!(len || pos) && ndents)
3521 					len = pos = mbstowcs(buf, pdents[cur].name, READLINE_MAX);
3522 				continue;
3523 			case CONTROL('F'):
3524 				if (pos < len)
3525 					++pos;
3526 				continue;
3527 			case CONTROL('B'):
3528 				if (pos > 0)
3529 					--pos;
3530 				continue;
3531 			case CONTROL('W'):
3532 				printmsg(prompt);
3533 				do {
3534 					if (pos == 0)
3535 						break;
3536 					memmove(buf + pos - 1, buf + pos,
3537 						(len - pos) * WCHAR_T_WIDTH);
3538 					--pos, --len;
3539 				} while (buf[pos - 1] != ' ' && buf[pos - 1] != '/'); // NOLINT
3540 				continue;
3541 			case CONTROL('K'):
3542 				printmsg(prompt);
3543 				len = pos;
3544 				continue;
3545 			case CONTROL('L'):
3546 				printmsg(prompt);
3547 				len = pos = 0;
3548 				continue;
3549 			case CONTROL('A'):
3550 				pos = 0;
3551 				continue;
3552 			case CONTROL('E'):
3553 				pos = len;
3554 				continue;
3555 			case CONTROL('U'):
3556 				printmsg(prompt);
3557 				memmove(buf, buf + pos, (len - pos) * WCHAR_T_WIDTH);
3558 				len -= pos;
3559 				pos = 0;
3560 				continue;
3561 			case ESC: /* Exit prompt on Esc, but just filter out Alt+key */
3562 				if (handle_alt_key(ch) != ERR)
3563 					continue;
3564 
3565 				len = 0;
3566 				goto END;
3567 			}
3568 
3569 			/* Filter out all other control chars */
3570 			if (*ch < ASCII_MAX && keyname(*ch)[0] == '^')
3571 				continue;
3572 
3573 			if (pos < READLINE_MAX - 1) {
3574 				memmove(buf + pos + 1, buf + pos,
3575 					(len - pos) * WCHAR_T_WIDTH);
3576 				buf[pos] = *ch;
3577 				++len, ++pos;
3578 				continue;
3579 			}
3580 		} else {
3581 			switch (*ch) {
3582 #ifdef KEY_RESIZE
3583 			case KEY_RESIZE:
3584 				clearoldprompt();
3585 				xlines = LINES;
3586 				printmsg(prompt);
3587 				break;
3588 #endif
3589 			case KEY_LEFT:
3590 				if (pos > 0)
3591 					--pos;
3592 				break;
3593 			case KEY_RIGHT:
3594 				if (pos < len)
3595 					++pos;
3596 				break;
3597 			case KEY_BACKSPACE:
3598 				if (pos > 0) {
3599 					memmove(buf + pos - 1, buf + pos,
3600 						(len - pos) * WCHAR_T_WIDTH);
3601 					--len, --pos;
3602 				}
3603 				break;
3604 			case KEY_DC:
3605 				if (pos < len) {
3606 					memmove(buf + pos, buf + pos + 1,
3607 						(len - pos - 1) * WCHAR_T_WIDTH);
3608 					--len;
3609 				}
3610 				break;
3611 			case KEY_END:
3612 				pos = len;
3613 				break;
3614 			case KEY_HOME:
3615 				pos = 0;
3616 				break;
3617 			case KEY_UP: // fallthrough
3618 			case KEY_DOWN:
3619 				if (prompt && lastcmd && (xstrcmp(prompt, PROMPT) == 0)) {
3620 					printmsg(prompt);
3621 					len = pos = mbstowcs(buf, lastcmd, READLINE_MAX); // fallthrough
3622 				}
3623 			default:
3624 				break;
3625 			}
3626 		}
3627 	}
3628 
3629 END:
3630 	curs_set(FALSE);
3631 	settimeout();
3632 	printmsg("");
3633 
3634 	buf[len] = '\0';
3635 
3636 	pos = wcstombs(g_buf, buf, READLINE_MAX - 1);
3637 	if (pos >= READLINE_MAX - 1)
3638 		g_buf[READLINE_MAX - 1] = '\0';
3639 
3640 	free(buf);
3641 	return g_buf;
3642 }
3643 
3644 #ifndef NORL
3645 /*
3646  * Caller should check the value of presel to confirm if it needs to wait to show warning
3647  */
3648 static char *getreadline(const char *prompt)
3649 {
3650 	exitcurses();
3651 
3652 	char *input = readline(prompt);
3653 
3654 	refresh();
3655 
3656 	if (input && input[0]) {
3657 		add_history(input);
3658 		xstrsncpy(g_buf, input, CMD_LEN_MAX);
3659 		free(input);
3660 		return g_buf;
3661 	}
3662 
3663 	free(input);
3664 	return NULL;
3665 }
3666 #endif
3667 
3668 /*
3669  * Create symbolic/hard link(s) to file(s) in selection list
3670  * Returns the number of links created, -1 on error
3671  */
3672 static int xlink(char *prefix, char *path, char *curfname, char *buf, int *presel, int type)
3673 {
3674 	int count = 0, choice;
3675 	char *psel = pselbuf, *fname;
3676 	size_t pos = 0, len, r;
3677 	int (*link_fn)(const char *, const char *) = NULL;
3678 	char lnpath[PATH_MAX];
3679 
3680 	choice = get_cur_or_sel();
3681 	if (!choice)
3682 		return -1;
3683 
3684 	if (type == 's') /* symbolic link */
3685 		link_fn = &symlink;
3686 	else /* hard link */
3687 		link_fn = &link;
3688 
3689 	if (choice == 'c') {
3690 		r = xstrsncpy(buf, prefix, NAME_MAX + 1); /* Copy prefix */
3691 		xstrsncpy(buf + r - 1, curfname, NAME_MAX - r); /* Suffix target file name */
3692 		mkpath(path, buf, lnpath); /* Generate link path */
3693 		mkpath(path, curfname, buf); /* Generate target file path */
3694 
3695 		if (!link_fn(buf, lnpath))
3696 			return 1; /* One link created */
3697 
3698 		printwarn(presel);
3699 		return -1;
3700 	}
3701 
3702 	while (pos < selbufpos) {
3703 		len = xstrlen(psel);
3704 		fname = xbasename(psel);
3705 
3706 		r = xstrsncpy(buf, prefix, NAME_MAX + 1); /* Copy prefix */
3707 		xstrsncpy(buf + r - 1, fname, NAME_MAX - r); /* Suffix target file name */
3708 		mkpath(path, buf, lnpath); /* Generate link path */
3709 
3710 		if (!link_fn(psel, lnpath))
3711 			++count;
3712 
3713 		pos += len + 1;
3714 		psel += len + 1;
3715 	}
3716 
3717 	clearselection();
3718 	return count;
3719 }
3720 
3721 static bool parsekvpair(kv **arr, char **envcpy, const uchar_t id, uchar_t *items)
3722 {
3723 	bool new = TRUE;
3724 	const uchar_t INCR = 8;
3725 	uint_t i = 0;
3726 	kv *kvarr = NULL;
3727 	char *ptr = getenv(env_cfg[id]);
3728 
3729 	if (!ptr || !*ptr)
3730 		return TRUE;
3731 
3732 	*envcpy = xstrdup(ptr);
3733 	if (!*envcpy) {
3734 		xerror();
3735 		return FALSE;
3736 	}
3737 
3738 	ptr = *envcpy;
3739 
3740 	while (*ptr && i < 100) {
3741 		if (new) {
3742 			if (!(i & (INCR - 1))) {
3743 				kvarr = xrealloc(kvarr, sizeof(kv) * (i + INCR));
3744 				*arr = kvarr;
3745 				if (!kvarr) {
3746 					xerror();
3747 					return FALSE;
3748 				}
3749 				memset(kvarr + i, 0, sizeof(kv) * INCR);
3750 			}
3751 			kvarr[i].key = (uchar_t)*ptr;
3752 			if (*++ptr != ':' || *++ptr == '\0' || *ptr == ';')
3753 				return FALSE;
3754 			kvarr[i].off = ptr - *envcpy;
3755 			++i;
3756 
3757 			new = FALSE;
3758 		}
3759 
3760 		if (*ptr == ';') {
3761 			*ptr = '\0';
3762 			new = TRUE;
3763 		}
3764 
3765 		++ptr;
3766 	}
3767 
3768 	*items = i;
3769 	return (i != 0);
3770 }
3771 
3772 /*
3773  * Get the value corresponding to a key
3774  *
3775  * NULL is returned in case of no match, path resolution failure etc.
3776  * buf would be modified, so check return value before access
3777  */
3778 static char *get_kv_val(kv *kvarr, char *buf, int key, uchar_t max, uchar_t id)
3779 {
3780 	char *val;
3781 
3782 	if (!kvarr)
3783 		return NULL;
3784 
3785 	for (int r = 0; kvarr[r].key && r < max; ++r) {
3786 		if (kvarr[r].key == key) {
3787 			/* Do not allocate new memory for plugin */
3788 			if (id == NNN_PLUG)
3789 				return pluginstr + kvarr[r].off;
3790 
3791 			val = bmstr + kvarr[r].off;
3792 			convert_tilde(val, g_buf);
3793 			return abspath(((val[0] == '~') ? g_buf : val), NULL, buf);
3794 		}
3795 	}
3796 
3797 	DPRINTF_S("Invalid key");
3798 	return NULL;
3799 }
3800 
3801 static int get_kv_key(kv *kvarr, char *val, uchar_t max, uchar_t id)
3802 {
3803 	if (!kvarr)
3804 		return -1;
3805 
3806 	if (id != NNN_ORDER) /* For now this function supports only order string */
3807 		return -1;
3808 
3809 	for (int r = 0; kvarr[r].key && r < max; ++r) {
3810 		if (xstrcmp((orderstr + kvarr[r].off), val) == 0)
3811 			return kvarr[r].key;
3812 	}
3813 
3814 	return -1;
3815 }
3816 
3817 static void resetdircolor(int flags)
3818 {
3819 	/* Directories are always shown on top, clear the color when moving to first file */
3820 	if (g_state.dircolor && !(flags & DIR_OR_DIRLNK)) {
3821 		attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
3822 		g_state.dircolor = 0;
3823 	}
3824 }
3825 
3826 /*
3827  * Replace escape characters in a string with '?'
3828  * Adjust string length to maxcols if > 0;
3829  * Max supported str length: NAME_MAX;
3830  */
3831 #ifdef NOLC
3832 static char *unescape(const char *str, uint_t maxcols)
3833 {
3834 	char * const wbuf = g_buf;
3835 	char *buf = wbuf;
3836 
3837 	xstrsncpy(wbuf, str, maxcols);
3838 #else
3839 static wchar_t *unescape(const char *str, uint_t maxcols)
3840 {
3841 	wchar_t * const wbuf = (wchar_t *)g_buf;
3842 	wchar_t *buf = wbuf;
3843 	size_t len = mbstowcs(wbuf, str, maxcols); /* Convert multi-byte to wide char */
3844 
3845 	len = wcswidth(wbuf, len);
3846 
3847 	if (len >= maxcols) {
3848 		size_t lencount = maxcols;
3849 
3850 		while (len > maxcols) /* Reduce wide chars one by one till it fits */
3851 			len = wcswidth(wbuf, --lencount);
3852 
3853 		wbuf[lencount] = L'\0';
3854 	}
3855 #endif
3856 
3857 	while (*buf) {
3858 		if (*buf <= '\x1f' || *buf == '\x7f')
3859 			*buf = '\?';
3860 
3861 		++buf;
3862 	}
3863 
3864 	return wbuf;
3865 }
3866 
3867 static off_t get_size(off_t size, off_t *pval, int comp)
3868 {
3869 	off_t rem = *pval;
3870 	off_t quo = rem / 10;
3871 
3872 	if ((rem - (quo * 10)) >= 5) {
3873 		rem = quo + 1;
3874 		if (rem == comp) {
3875 			++size;
3876 			rem = 0;
3877 		}
3878 	} else
3879 		rem = quo;
3880 
3881 	*pval = rem;
3882 	return size;
3883 }
3884 
3885 static char *coolsize(off_t size)
3886 {
3887 	const char * const U = "BKMGTPEZY";
3888 	static char size_buf[12]; /* Buffer to hold human readable size */
3889 	off_t rem = 0;
3890 	size_t ret;
3891 	int i = 0;
3892 
3893 	while (size >= 1024) {
3894 		rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
3895 		size >>= 10;
3896 		++i;
3897 	}
3898 
3899 	if (i == 1) {
3900 		rem = (rem * 1000) >> 10;
3901 		rem /= 10;
3902 		size = get_size(size, &rem, 10);
3903 	} else if (i == 2) {
3904 		rem = (rem * 1000) >> 10;
3905 		size = get_size(size, &rem, 100);
3906 	} else if (i > 2) {
3907 		rem = (rem * 10000) >> 10;
3908 		size = get_size(size, &rem, 1000);
3909 	}
3910 
3911 	if (i > 0 && i < 6 && rem) {
3912 		ret = xstrsncpy(size_buf, xitoa(size), 12);
3913 		size_buf[ret - 1] = '.';
3914 
3915 		char *frac = xitoa(rem);
3916 		size_t toprint = i > 3 ? 3 : i;
3917 		size_t len = xstrlen(frac);
3918 
3919 		if (len < toprint) {
3920 			size_buf[ret] = size_buf[ret + 1] = size_buf[ret + 2] = '0';
3921 			xstrsncpy(size_buf + ret + (toprint - len), frac, len + 1);
3922 		} else
3923 			xstrsncpy(size_buf + ret, frac, toprint + 1);
3924 
3925 		ret += toprint;
3926 	} else {
3927 		ret = xstrsncpy(size_buf, size ? xitoa(size) : "0", 12);
3928 		--ret;
3929 	}
3930 
3931 	size_buf[ret] = U[i];
3932 	size_buf[ret + 1] = '\0';
3933 
3934 	return size_buf;
3935 }
3936 
3937 /* Convert a mode field into "ls -l" type perms field. */
3938 static char *get_lsperms(mode_t mode)
3939 {
3940 	static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
3941 	static char bits[11] = {'\0'};
3942 
3943 	switch (mode & S_IFMT) {
3944 	case S_IFREG:
3945 		bits[0] = '-';
3946 		break;
3947 	case S_IFDIR:
3948 		bits[0] = 'd';
3949 		break;
3950 	case S_IFLNK:
3951 		bits[0] = 'l';
3952 		break;
3953 	case S_IFSOCK:
3954 		bits[0] = 's';
3955 		break;
3956 	case S_IFIFO:
3957 		bits[0] = 'p';
3958 		break;
3959 	case S_IFBLK:
3960 		bits[0] = 'b';
3961 		break;
3962 	case S_IFCHR:
3963 		bits[0] = 'c';
3964 		break;
3965 	default:
3966 		bits[0] = '?';
3967 		break;
3968 	}
3969 
3970 	xstrsncpy(&bits[1], rwx[(mode >> 6) & 7], 4);
3971 	xstrsncpy(&bits[4], rwx[(mode >> 3) & 7], 4);
3972 	xstrsncpy(&bits[7], rwx[(mode & 7)], 4);
3973 
3974 	if (mode & S_ISUID)
3975 		bits[3] = (mode & 0100) ? 's' : 'S';  /* user executable */
3976 	if (mode & S_ISGID)
3977 		bits[6] = (mode & 0010) ? 's' : 'l';  /* group executable */
3978 	if (mode & S_ISVTX)
3979 		bits[9] = (mode & 0001) ? 't' : 'T';  /* others executable */
3980 
3981 	return bits;
3982 }
3983 
3984 #ifdef ICONS_ENABLED
3985 static const struct icon_pair *get_icon(const struct entry *ent)
3986 {
3987 	ushort_t i = 0;
3988 
3989 	for (; i < sizeof(icons_name)/sizeof(struct icon_pair); ++i)
3990 		if (strcasecmp(ent->name, icons_name[i].match) == 0)
3991 			return &icons_name[i];
3992 
3993 	if (ent->flags & DIR_OR_DIRLNK)
3994 		return &dir_icon;
3995 
3996 	char *tmp = xextension(ent->name, ent->nlen);
3997 
3998 	if (!tmp) {
3999 		if (ent->mode & 0100)
4000 			return &exec_icon;
4001 
4002 		return &file_icon;
4003 	}
4004 
4005 	/* Skip the . */
4006 	++tmp;
4007 
4008 	if (*tmp >= '0' && *tmp <= '9')
4009 		i = *tmp - '0'; /* NUMBER 0-9 */
4010 	else if (TOUPPER(*tmp) >= 'A' && TOUPPER(*tmp) <= 'Z')
4011 		i = TOUPPER(*tmp) - 'A' + 10; /* LETTER A-Z */
4012 	else
4013 		i = 36; /* OTHER */
4014 
4015 	for (ushort_t j = icon_positions[i]; j < sizeof(icons_ext)/sizeof(struct icon_pair) &&
4016 			icons_ext[j].match[0] == icons_ext[icon_positions[i]].match[0]; ++j)
4017 		if (strcasecmp(tmp, icons_ext[j].match) == 0)
4018 			return &icons_ext[j];
4019 
4020 	/* If there's no match and the file is executable, icon that */
4021 	if (ent->mode & 0100)
4022 		return &exec_icon;
4023 
4024 	return &file_icon;
4025 }
4026 
4027 static void print_icon(const struct entry *ent, const int attrs)
4028 {
4029 	const struct icon_pair *picon = get_icon(ent);
4030 
4031 	addstr(ICON_PADDING_LEFT);
4032 	if (picon->color)
4033 		attron(COLOR_PAIR(C_UND + 1 + picon->color));
4034 	else if (attrs)
4035 		attron(attrs);
4036 	addstr(picon->icon);
4037 	if (picon->color)
4038 		attroff(COLOR_PAIR(C_UND + 1 + picon->color));
4039 	else if (attrs)
4040 		attroff(attrs);
4041 	addstr(ICON_PADDING_RIGHT);
4042 }
4043 #endif
4044 
4045 static void print_time(const time_t *timep)
4046 {
4047 	struct tm t;
4048 
4049 	localtime_r(timep, &t);
4050 	printw("%s-%02d-%02d %02d:%02d",
4051 		xitoa(t.tm_year + 1900), t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min);
4052 }
4053 
4054 static char get_detail_ind(const mode_t mode)
4055 {
4056 	switch (mode & S_IFMT) {
4057 	case S_IFDIR:  // fallthrough
4058 	case S_IFREG:  return ' ';
4059 	case S_IFLNK:  return '@';
4060 	case S_IFSOCK: return '=';
4061 	case S_IFIFO:  return '|';
4062 	case S_IFBLK:  return 'b';
4063 	case S_IFCHR:  return 'c';
4064 	}
4065 	return '?';
4066 }
4067 
4068 /* Note: attribute and indicator values must be initialized to 0 */
4069 static uchar_t get_color_pair_name_ind(const struct entry *ent, char *pind, int *pattr)
4070 {
4071 	switch (ent->mode & S_IFMT) {
4072 	case S_IFREG:
4073 		if (!ent->size) {
4074 			if (ent->mode & 0100)
4075 				*pind = '*';
4076 			return C_UND;
4077 		}
4078 		if (ent->flags & HARD_LINK) {
4079 			if (ent->mode & 0100)
4080 				*pind = '*';
4081 			return C_HRD;
4082 		}
4083 		if (ent->mode & 0100) {
4084 			*pind = '*';
4085 			return C_EXE;
4086 		}
4087 		return C_FIL;
4088 	case S_IFDIR:
4089 		*pind = '/';
4090 		if (g_state.oldcolor)
4091 			return C_DIR;
4092 		*pattr |= A_BOLD;
4093 		return g_state.dirctx ? cfg.curctx + 1 : C_DIR;
4094 	case S_IFLNK:
4095 		if (ent->flags & DIR_OR_DIRLNK) {
4096 			*pind = '/';
4097 			*pattr |= g_state.oldcolor ? A_DIM : A_BOLD;
4098 		} else {
4099 			*pind = '@';
4100 			if (g_state.oldcolor)
4101 				*pattr |= A_DIM;
4102 		}
4103 		if (!g_state.oldcolor || cfg.showdetail)
4104 			return (ent->flags & SYM_ORPHAN) ? C_ORP : C_LNK;
4105 		return 0;
4106 	case S_IFSOCK:
4107 		*pind = '=';
4108 		return C_SOC;
4109 	case S_IFIFO:
4110 		*pind = '|';
4111 		return C_PIP;
4112 	case S_IFBLK:
4113 		return C_BLK;
4114 	case S_IFCHR:
4115 		return C_CHR;
4116 	}
4117 
4118 	*pind = '?';
4119 	return C_UND;
4120 }
4121 
4122 static void printent(const struct entry *ent, uint_t namecols, bool sel)
4123 {
4124 	char ind = '\0';
4125 	int attrs;
4126 
4127 	if (cfg.showdetail) {
4128 		int type = ent->mode & S_IFMT;
4129 		char perms[6] = {' ', ' ', (char)('0' + ((ent->mode >> 6) & 7)),
4130 				(char)('0' + ((ent->mode >> 3) & 7)),
4131 				(char)('0' + (ent->mode & 7)), '\0'};
4132 
4133 		addch(' ');
4134 		attrs = g_state.oldcolor ? (resetdircolor(ent->flags), A_DIM)
4135 					 : (fcolors[C_MIS] ? COLOR_PAIR(C_MIS) : 0);
4136 		if (attrs)
4137 			attron(attrs);
4138 
4139 		/* Print details */
4140 		print_time(&ent->sec);
4141 
4142 		printw("%s%9s ", perms, (type == S_IFREG || type == S_IFDIR)
4143 			? coolsize(cfg.blkorder ? (blkcnt_t)ent->blocks << blk_shift : ent->size)
4144 			: (type = (uchar_t)get_detail_ind(ent->mode), (char *)&type));
4145 
4146 		if (attrs)
4147 			attroff(attrs);
4148 	}
4149 
4150 	attrs = 0;
4151 
4152 	uchar_t color_pair = get_color_pair_name_ind(ent, &ind, &attrs);
4153 
4154 	addch((ent->flags & FILE_SELECTED) ? '+' | A_REVERSE | A_BOLD : ' ');
4155 
4156 	if (g_state.oldcolor)
4157 		resetdircolor(ent->flags);
4158 	else {
4159 		if (ent->flags & FILE_MISSING)
4160 			color_pair = C_MIS;
4161 		if (color_pair && fcolors[color_pair])
4162 			attrs |= COLOR_PAIR(color_pair);
4163 #ifdef ICONS_ENABLED
4164 		print_icon(ent, attrs);
4165 #endif
4166 	}
4167 
4168 	if (sel)
4169 		attrs |= A_REVERSE;
4170 	if (attrs)
4171 		attron(attrs);
4172 	if (!ind)
4173 		++namecols;
4174 
4175 #ifndef NOLC
4176 	addwstr(unescape(ent->name, namecols));
4177 #else
4178 	addstr(unescape(ent->name, MIN(namecols, ent->nlen) + 1));
4179 #endif
4180 
4181 	if (attrs)
4182 		attroff(attrs);
4183 	if (ind)
4184 		addch(ind);
4185 }
4186 
4187 static void savecurctx(char *path, char *curname, int nextctx)
4188 {
4189 	settings tmpcfg = cfg;
4190 	context *ctxr = &g_ctx[nextctx];
4191 
4192 	/* Save current context */
4193 	if (curname)
4194 		xstrsncpy(g_ctx[tmpcfg.curctx].c_name, curname, NAME_MAX + 1);
4195 	else
4196 		g_ctx[tmpcfg.curctx].c_name[0] = '\0';
4197 
4198 	g_ctx[tmpcfg.curctx].c_cfg = tmpcfg;
4199 
4200 	if (ctxr->c_cfg.ctxactive) { /* Switch to saved context */
4201 		tmpcfg = ctxr->c_cfg;
4202 		/* Skip ordering an open context */
4203 		if (order) {
4204 			cfgsort[CTX_MAX] = cfgsort[nextctx];
4205 			cfgsort[nextctx] = '0';
4206 		}
4207 	} else { /* Set up a new context from current context */
4208 		ctxr->c_cfg.ctxactive = 1;
4209 		xstrsncpy(ctxr->c_path, path, PATH_MAX);
4210 		ctxr->c_last[0] = ctxr->c_name[0] = ctxr->c_fltr[0] = ctxr->c_fltr[1] = '\0';
4211 		ctxr->c_cfg = tmpcfg;
4212 		/* If already in an ordered dir, clear ordering for the new context and let it order */
4213 		if (cfgsort[cfg.curctx] == 'z')
4214 			cfgsort[nextctx] = 'z';
4215 	}
4216 
4217 	tmpcfg.curctx = nextctx;
4218 	cfg = tmpcfg;
4219 }
4220 
4221 #ifndef NOSSN
4222 static void save_session(const char *sname, int *presel)
4223 {
4224 	int fd, i;
4225 	session_header_t header;
4226 	bool status = FALSE;
4227 	char ssnpath[PATH_MAX];
4228 	char spath[PATH_MAX];
4229 
4230 	memset(&header, 0, sizeof(session_header_t));
4231 
4232 	header.ver = SESSIONS_VERSION;
4233 
4234 	for (i = 0; i < CTX_MAX; ++i) {
4235 		if (g_ctx[i].c_cfg.ctxactive) {
4236 			if (cfg.curctx == i && ndents)
4237 				/* Update current file name, arrows don't update it */
4238 				xstrsncpy(g_ctx[i].c_name, pdents[cur].name, NAME_MAX + 1);
4239 			header.pathln[i] = strnlen(g_ctx[i].c_path, PATH_MAX) + 1;
4240 			header.lastln[i] = strnlen(g_ctx[i].c_last, PATH_MAX) + 1;
4241 			header.nameln[i] = strnlen(g_ctx[i].c_name, NAME_MAX) + 1;
4242 			header.fltrln[i] = REGEX_MAX;
4243 		}
4244 	}
4245 
4246 	mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4247 	mkpath(ssnpath, sname, spath);
4248 
4249 	fd = open(spath, O_CREAT | O_WRONLY | O_TRUNC, 0666);
4250 	if (fd == -1) {
4251 		printwait(messages[MSG_SEL_MISSING], presel);
4252 		return;
4253 	}
4254 
4255 	if ((write(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4256 		|| (write(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4257 		goto END;
4258 
4259 	for (i = 0; i < CTX_MAX; ++i)
4260 		if ((write(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4261 			|| (write(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4262 			|| (header.nameln[i] > 0
4263 			    && write(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4264 			|| (header.lastln[i] > 0
4265 			    && write(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4266 			|| (header.fltrln[i] > 0
4267 			    && write(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4268 			|| (header.pathln[i] > 0
4269 			    && write(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4270 			goto END;
4271 
4272 	status = TRUE;
4273 
4274 END:
4275 	close(fd);
4276 
4277 	if (!status)
4278 		printwait(messages[MSG_FAILED], presel);
4279 }
4280 
4281 static bool load_session(const char *sname, char **path, char **lastdir, char **lastname, bool restore)
4282 {
4283 	int fd, i = 0;
4284 	session_header_t header;
4285 	bool has_loaded_dynamically = !(sname || restore);
4286 	bool status = (sname && g_state.picker); /* Picker mode with session program option */
4287 	char ssnpath[PATH_MAX];
4288 	char spath[PATH_MAX];
4289 
4290 	mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4291 
4292 	if (!restore) {
4293 		sname = sname ? sname : xreadline(NULL, messages[MSG_SSN_NAME]);
4294 		if (!sname[0])
4295 			return FALSE;
4296 
4297 		mkpath(ssnpath, sname, spath);
4298 
4299 		/* If user is explicitly loading the "last session", skip auto-save */
4300 		if ((sname[0] == '@') && !sname[1])
4301 			has_loaded_dynamically = FALSE;
4302 	} else
4303 		mkpath(ssnpath, "@", spath);
4304 
4305 	if (has_loaded_dynamically)
4306 		save_session("@", NULL);
4307 
4308 	fd = open(spath, O_RDONLY, 0666);
4309 	if (fd == -1) {
4310 		if (!status) {
4311 			printmsg(messages[MSG_SEL_MISSING]);
4312 			xdelay(XDELAY_INTERVAL_MS);
4313 		}
4314 		return FALSE;
4315 	}
4316 
4317 	status = FALSE;
4318 
4319 	if ((read(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4320 		|| (header.ver != SESSIONS_VERSION)
4321 		|| (read(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4322 		goto END;
4323 
4324 	g_ctx[cfg.curctx].c_name[0] = g_ctx[cfg.curctx].c_last[0]
4325 		= g_ctx[cfg.curctx].c_fltr[0] = g_ctx[cfg.curctx].c_fltr[1] = '\0';
4326 
4327 	for (; i < CTX_MAX; ++i)
4328 		if ((read(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4329 			|| (read(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4330 			|| (header.nameln[i] > 0
4331 			    && read(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4332 			|| (header.lastln[i] > 0
4333 			    && read(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4334 			|| (header.fltrln[i] > 0
4335 			    && read(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4336 			|| (header.pathln[i] > 0
4337 			    && read(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4338 			goto END;
4339 
4340 	*path = g_ctx[cfg.curctx].c_path;
4341 	*lastdir = g_ctx[cfg.curctx].c_last;
4342 	*lastname = g_ctx[cfg.curctx].c_name;
4343 	set_sort_flags('\0'); /* Set correct sort options */
4344 	status = TRUE;
4345 
4346 END:
4347 	close(fd);
4348 
4349 	if (!status) {
4350 		printmsg(messages[MSG_FAILED]);
4351 		xdelay(XDELAY_INTERVAL_MS);
4352 	} else if (restore)
4353 		unlink(spath);
4354 
4355 	return status;
4356 }
4357 #endif
4358 
4359 static uchar_t get_free_ctx(void)
4360 {
4361 	uchar_t r = cfg.curctx;
4362 
4363 	do
4364 		r = (r + 1) & ~CTX_MAX;
4365 	while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
4366 
4367 	return r;
4368 }
4369 
4370 /* ctx is absolute: 1 to 4, + for smart context */
4371 static void set_smart_ctx(int ctx, char *nextpath, char **path, char *file, char **lastname, char **lastdir)
4372 {
4373 	if (ctx == '+') /* Get smart context */
4374 		ctx = (int)(get_free_ctx() + 1);
4375 
4376 	if (ctx == 0 || ctx == cfg.curctx + 1) { /* Same context */
4377 		xstrsncpy(*lastdir, *path, PATH_MAX);
4378 		xstrsncpy(*path, nextpath, PATH_MAX);
4379 	} else { /* New context */
4380 		--ctx;
4381 		/* Deactivate the new context and build from scratch */
4382 		g_ctx[ctx].c_cfg.ctxactive = 0;
4383 		DPRINTF_S(nextpath);
4384 		savecurctx(nextpath, file, ctx);
4385 		*path = g_ctx[ctx].c_path;
4386 		*lastdir = g_ctx[ctx].c_last;
4387 		*lastname = g_ctx[ctx].c_name;
4388 	}
4389 }
4390 
4391 /*
4392  * Gets only a single line (that's what we need for now) or shows full command output in pager.
4393  * Uses g_buf internally.
4394  */
4395 static bool get_output(char *file, char *arg1, char *arg2, int fdout, bool multi, bool page)
4396 {
4397 	pid_t pid;
4398 	int pipefd[2];
4399 	int index = 0, flags;
4400 	bool ret = FALSE;
4401 	bool tmpfile = ((fdout == -1) && page);
4402 	char *argv[EXEC_ARGS_MAX] = {0};
4403 	char *cmd = NULL;
4404 	int fd = -1;
4405 	ssize_t len;
4406 
4407 	if (tmpfile) {
4408 		fdout = create_tmp_file();
4409 		if (fdout == -1)
4410 			return FALSE;
4411 	}
4412 
4413 	if (multi) {
4414 		cmd = parseargs(file, argv, &index);
4415 		if (!cmd)
4416 			return FALSE;
4417 	} else
4418 		argv[index++] = file;
4419 
4420 	argv[index] = arg1;
4421 	argv[++index] = arg2;
4422 
4423 	if (pipe(pipefd) == -1) {
4424 		free(cmd);
4425 		errexit();
4426 	}
4427 
4428 	for (index = 0; index < 2; ++index) {
4429 		/* Get previous flags */
4430 		flags = fcntl(pipefd[index], F_GETFL, 0);
4431 
4432 		/* Set bit for non-blocking flag */
4433 		flags |= O_NONBLOCK;
4434 
4435 		/* Change flags on fd */
4436 		fcntl(pipefd[index], F_SETFL, flags);
4437 	}
4438 
4439 	pid = fork();
4440 	if (pid == 0) {
4441 		/* In child */
4442 		close(pipefd[0]);
4443 		dup2(pipefd[1], STDOUT_FILENO);
4444 		dup2(pipefd[1], STDERR_FILENO);
4445 		close(pipefd[1]);
4446 		execvp(*argv, argv);
4447 		_exit(EXIT_SUCCESS);
4448 	}
4449 
4450 	/* In parent */
4451 	waitpid(pid, NULL, 0);
4452 	close(pipefd[1]);
4453 	free(cmd);
4454 
4455 	while ((len = read(pipefd[0], g_buf, CMD_LEN_MAX - 1)) > 0) {
4456 		ret = TRUE;
4457 		if (fdout == -1) /* Read only the first line of output to buffer */
4458 			break;
4459 		if (write(fdout, g_buf, len) != len)
4460 			break;
4461 	}
4462 
4463 	close(pipefd[0]);
4464 	if (!page)
4465 		return ret;
4466 
4467 	if (tmpfile) {
4468 		close(fdout);
4469 		close(fd);
4470 	}
4471 
4472 	spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4473 
4474 	if (tmpfile)
4475 		unlink(g_tmpfpath);
4476 
4477 	return TRUE;
4478 }
4479 
4480 /*
4481  * Follows the stat(1) output closely
4482  */
4483 static bool show_stats(char *fpath)
4484 {
4485 	static char * const cmds[] = {
4486 #ifdef FILE_MIME_OPTS
4487 		("file " FILE_MIME_OPTS),
4488 #endif
4489 		"file -b",
4490 		"stat",
4491 	};
4492 
4493 	size_t r = ELEMENTS(cmds);
4494 	int fd = create_tmp_file();
4495 	if (fd == -1)
4496 		return FALSE;
4497 
4498 	while (r)
4499 		get_output(cmds[--r], fpath, NULL, fd, TRUE, FALSE);
4500 
4501 	close(fd);
4502 
4503 	spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4504 	unlink(g_tmpfpath);
4505 	return TRUE;
4506 }
4507 
4508 static bool xchmod(const char *fpath, mode_t mode)
4509 {
4510 	/* (Un)set (S_IXUSR | S_IXGRP | S_IXOTH) */
4511 	(0100 & mode) ? (mode &= ~0111) : (mode |= 0111);
4512 
4513 	return (chmod(fpath, mode) == 0);
4514 }
4515 
4516 static size_t get_fs_info(const char *path, bool type)
4517 {
4518 	struct statvfs svb;
4519 
4520 	if (statvfs(path, &svb) == -1)
4521 		return 0;
4522 
4523 	if (type == CAPACITY)
4524 		return (size_t)svb.f_blocks << ffs((int)(svb.f_frsize >> 1));
4525 
4526 	return (size_t)svb.f_bavail << ffs((int)(svb.f_frsize >> 1));
4527 }
4528 
4529 /* Create non-existent parents and a file or dir */
4530 static bool xmktree(char *path, bool dir)
4531 {
4532 	char *p = path;
4533 	char *slash = path;
4534 
4535 	if (!p || !*p)
4536 		return FALSE;
4537 
4538 	/* Skip the first '/' */
4539 	++p;
4540 
4541 	while (*p != '\0') {
4542 		if (*p == '/') {
4543 			slash = p;
4544 			*p = '\0';
4545 		} else {
4546 			++p;
4547 			continue;
4548 		}
4549 
4550 		/* Create folder from path to '\0' inserted at p */
4551 		if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4552 #ifdef __HAIKU__
4553 			// XDG_CONFIG_HOME contains a directory
4554 			// that is read-only, but the full path
4555 			// is writeable.
4556 			// Try to continue and see what happens.
4557 			// TODO: Find a more robust solution.
4558 			if (errno == B_READ_ONLY_DEVICE)
4559 				goto next;
4560 #endif
4561 			DPRINTF_S("mkdir1!");
4562 			DPRINTF_S(strerror(errno));
4563 			*slash = '/';
4564 			return FALSE;
4565 		}
4566 
4567 #ifdef __HAIKU__
4568 next:
4569 #endif
4570 		/* Restore path */
4571 		*slash = '/';
4572 		++p;
4573 	}
4574 
4575 	if (dir) {
4576 		if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4577 			DPRINTF_S("mkdir2!");
4578 			DPRINTF_S(strerror(errno));
4579 			return FALSE;
4580 		}
4581 	} else {
4582 		int fd = open(path, O_CREAT, 0666);
4583 
4584 		if (fd == -1 && errno != EEXIST) {
4585 			DPRINTF_S("open!");
4586 			DPRINTF_S(strerror(errno));
4587 			return FALSE;
4588 		}
4589 
4590 		close(fd);
4591 	}
4592 
4593 	return TRUE;
4594 }
4595 
4596 /* List or extract archive */
4597 static bool handle_archive(char *fpath /* in-out param */, char op)
4598 {
4599 	char arg[] = "-tvf"; /* options for tar/bsdtar to list files */
4600 	char *util, *outdir = NULL;
4601 	bool x_to = FALSE;
4602 	bool is_atool = getutil(utils[UTIL_ATOOL]);
4603 
4604 	if (op == 'x') {
4605 		outdir = xreadline(is_atool ? "." : xbasename(fpath), messages[MSG_NEW_PATH]);
4606 		if (!outdir || !*outdir) { /* Cancelled */
4607 			printwait(messages[MSG_CANCEL], NULL);
4608 			return FALSE;
4609 		}
4610 		/* Do not create smart context for current dir */
4611 		if (!(*outdir == '.' && outdir[1] == '\0')) {
4612 			if (!xmktree(outdir, TRUE) || (chdir(outdir) == -1)) {
4613 				printwarn(NULL);
4614 				return FALSE;
4615 			}
4616 			/* Copy the new dir path to open it in smart context */
4617 			outdir = getcwd(NULL, 0);
4618 			x_to = TRUE;
4619 		}
4620 	}
4621 
4622 	if (is_atool) {
4623 		util = utils[UTIL_ATOOL];
4624 		arg[1] = op;
4625 		arg[2] = '\0';
4626 	} else if (getutil(utils[UTIL_BSDTAR])) {
4627 		util = utils[UTIL_BSDTAR];
4628 		if (op == 'x')
4629 			arg[1] = op;
4630 	} else if (is_suffix(fpath, ".zip")) {
4631 		util = utils[UTIL_UNZIP];
4632 		arg[1] = (op == 'l') ? 'v' /* verbose listing */ : '\0';
4633 		arg[2] = '\0';
4634 	} else {
4635 		util = utils[UTIL_TAR];
4636 		if (op == 'x')
4637 			arg[1] = op;
4638 	}
4639 
4640 	if (op == 'x') /* extract */
4641 		spawn(util, arg, fpath, NULL, F_NORMAL | F_MULTI);
4642 	else /* list */
4643 		get_output(util, arg, fpath, -1, TRUE, TRUE);
4644 
4645 	if (x_to) {
4646 		if (chdir(xdirname(fpath)) == -1) {
4647 			printwarn(NULL);
4648 			free(outdir);
4649 			return FALSE;
4650 		}
4651 		xstrsncpy(fpath, outdir, PATH_MAX);
4652 		free(outdir);
4653 	} else if (op == 'x')
4654 		fpath[0] = '\0';
4655 
4656 	return TRUE;
4657 }
4658 
4659 static char *visit_parent(char *path, char *newpath, int *presel)
4660 {
4661 	char *dir;
4662 
4663 	/* There is no going back */
4664 	if (istopdir(path)) {
4665 		/* Continue in type-to-nav mode, if enabled */
4666 		if (cfg.filtermode && presel)
4667 			*presel = FILTER;
4668 		return NULL;
4669 	}
4670 
4671 	/* Use a copy as xdirname() may change the string passed */
4672 	if (newpath)
4673 		xstrsncpy(newpath, path, PATH_MAX);
4674 	else
4675 		newpath = path;
4676 
4677 	dir = xdirname(newpath);
4678 	if (chdir(dir) == -1) {
4679 		printwarn(presel);
4680 		return NULL;
4681 	}
4682 
4683 	return dir;
4684 }
4685 
4686 static void valid_parent(char *path, char *lastname)
4687 {
4688 	/* Save history */
4689 	xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
4690 
4691 	while (!istopdir(path))
4692 		if (visit_parent(path, NULL, NULL))
4693 			break;
4694 
4695 	printwarn(NULL);
4696 	xdelay(XDELAY_INTERVAL_MS);
4697 }
4698 
4699 static bool archive_mount(char *newpath)
4700 {
4701 	char *str = "install archivemount";
4702 	char *dir, *cmd = str + 8; /* Start of "archivemount" */
4703 	char *name = pdents[cur].name;
4704 	size_t len = pdents[cur].nlen;
4705 	char mntpath[PATH_MAX];
4706 
4707 	if (!getutil(cmd)) {
4708 		printmsg(str);
4709 		return FALSE;
4710 	}
4711 
4712 	dir = xstrdup(name);
4713 	if (!dir) {
4714 		printmsg(messages[MSG_FAILED]);
4715 		return FALSE;
4716 	}
4717 
4718 	while (len > 1)
4719 		if (dir[--len] == '.') {
4720 			dir[len] = '\0';
4721 			break;
4722 		}
4723 
4724 	DPRINTF_S(dir);
4725 
4726 	/* Create the mount point */
4727 	mkpath(cfgpath, toks[TOK_MNT], mntpath);
4728 	mkpath(mntpath, dir, newpath);
4729 	free(dir);
4730 
4731 	if (!xmktree(newpath, TRUE)) {
4732 		printwarn(NULL);
4733 		return FALSE;
4734 	}
4735 
4736 	/* Mount archive */
4737 	DPRINTF_S(name);
4738 	DPRINTF_S(newpath);
4739 	if (spawn(cmd, name, newpath, NULL, F_NORMAL)) {
4740 		printmsg(messages[MSG_FAILED]);
4741 		return FALSE;
4742 	}
4743 
4744 	return TRUE;
4745 }
4746 
4747 static bool remote_mount(char *newpath)
4748 {
4749 	uchar_t flag = F_CLI;
4750 	int opt;
4751 	char *tmp, *env;
4752 	bool r = getutil(utils[UTIL_RCLONE]), s = getutil(utils[UTIL_SSHFS]);
4753 	char mntpath[PATH_MAX];
4754 
4755 	if (!(r || s)) {
4756 		printmsg("install sshfs/rclone");
4757 		return FALSE;
4758 	}
4759 
4760 	if (r && s)
4761 		opt = get_input(messages[MSG_REMOTE_OPTS]);
4762 	else
4763 		opt = (!s) ? 'r' : 's';
4764 
4765 	if (opt == 's')
4766 		env = xgetenv("NNN_SSHFS", utils[UTIL_SSHFS]);
4767 	else if (opt == 'r') {
4768 		flag |= F_NOWAIT | F_NOTRACE;
4769 		env = xgetenv("NNN_RCLONE", "rclone mount");
4770 	} else {
4771 		printmsg(messages[MSG_INVALID_KEY]);
4772 		return FALSE;
4773 	}
4774 
4775 	tmp = xreadline(NULL, "host[:dir] > ");
4776 	if (!tmp[0]) {
4777 		printmsg(messages[MSG_CANCEL]);
4778 		return FALSE;
4779 	}
4780 
4781 	char *div = strchr(tmp, ':');
4782 
4783 	if (div)
4784 		*div = '\0';
4785 
4786 	/* Create the mount point */
4787 	mkpath(cfgpath, toks[TOK_MNT], mntpath);
4788 	mkpath(mntpath, tmp, newpath);
4789 	if (!xmktree(newpath, TRUE)) {
4790 		printwarn(NULL);
4791 		return FALSE;
4792 	}
4793 
4794 	if (!div) { /* Convert "host" to "host:" */
4795 		size_t len = xstrlen(tmp);
4796 
4797 		tmp[len] = ':';
4798 		tmp[len + 1] = '\0';
4799 	} else
4800 		*div = ':';
4801 
4802 	/* Connect to remote */
4803 	if (opt == 's') {
4804 		if (spawn(env, tmp, newpath, NULL, flag)) {
4805 			printmsg(messages[MSG_FAILED]);
4806 			return FALSE;
4807 		}
4808 	} else {
4809 		spawn(env, tmp, newpath, NULL, flag);
4810 		printmsg(messages[MSG_RCLONE_DELAY]);
4811 		xdelay(XDELAY_INTERVAL_MS << 2); /* Set 4 times the usual delay */
4812 	}
4813 
4814 	return TRUE;
4815 }
4816 
4817 /*
4818  * Unmounts if the directory represented by name is a mount point.
4819  * Otherwise, asks for hostname
4820  * Returns TRUE if directory needs to be refreshed *.
4821  */
4822 static bool unmount(char *name, char *newpath, int *presel, char *currentpath)
4823 {
4824 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__DragonFly__)
4825 	static char cmd[] = "umount";
4826 #else
4827 	static char cmd[] = "fusermount3"; /* Arch Linux utility */
4828 	static bool found = FALSE;
4829 #endif
4830 	char *tmp = name;
4831 	struct stat sb, psb;
4832 	bool child = FALSE;
4833 	bool parent = FALSE;
4834 	bool hovered = FALSE;
4835 	char mntpath[PATH_MAX];
4836 
4837 #if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__DragonFly__)
4838 	/* On Ubuntu it's fusermount */
4839 	if (!found && !getutil(cmd)) {
4840 		cmd[10] = '\0';
4841 		found = TRUE;
4842 	}
4843 #endif
4844 
4845 	mkpath(cfgpath, toks[TOK_MNT], mntpath);
4846 
4847 	if (tmp && strcmp(mntpath, currentpath) == 0) {
4848 		mkpath(mntpath, tmp, newpath);
4849 		child = lstat(newpath, &sb) != -1;
4850 		parent = lstat(xdirname(newpath), &psb) != -1;
4851 		if (!child && !parent) {
4852 			*presel = MSGWAIT;
4853 			return FALSE;
4854 		}
4855 	}
4856 
4857 	if (!tmp || !child || !S_ISDIR(sb.st_mode) || (child && parent && sb.st_dev == psb.st_dev)) {
4858 		tmp = xreadline(NULL, messages[MSG_HOSTNAME]);
4859 		if (!tmp[0])
4860 			return FALSE;
4861 		if (name && (tmp[0] == '-') && (tmp[1] == '\0')) {
4862 			mkpath(currentpath, name, newpath);
4863 			hovered = TRUE;
4864 		}
4865 	}
4866 
4867 	if (!hovered)
4868 		mkpath(mntpath, tmp, newpath);
4869 
4870 	if (!xdiraccess(newpath)) {
4871 		*presel = MSGWAIT;
4872 		return FALSE;
4873 	}
4874 
4875 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__DragonFly__)
4876 	if (spawn(cmd, newpath, NULL, NULL, F_NORMAL)) {
4877 #else
4878 	if (spawn(cmd, "-qu", newpath, NULL, F_NORMAL)) {
4879 #endif
4880 		if (!xconfirm(get_input(messages[MSG_LAZY])))
4881 			return FALSE;
4882 
4883 #ifdef __APPLE__
4884 		if (spawn(cmd, "-l", newpath, NULL, F_NORMAL)) {
4885 #elif defined(__FreeBSD__) || defined(__DragonFly__)
4886 		if (spawn(cmd, "-f", newpath, NULL, F_NORMAL)) {
4887 #else
4888 		if (spawn(cmd, "-quz", newpath, NULL, F_NORMAL)) {
4889 #endif
4890 			printwait(messages[MSG_FAILED], presel);
4891 			return FALSE;
4892 		}
4893 	}
4894 
4895 	if (rmdir(newpath) == -1) {
4896 		printwarn(presel);
4897 		return FALSE;
4898 	}
4899 
4900 	return TRUE;
4901 }
4902 
4903 static void lock_terminal(void)
4904 {
4905 	spawn(xgetenv("NNN_LOCKER", utils[UTIL_LOCKER]), NULL, NULL, NULL, F_CLI);
4906 }
4907 
4908 static void printkv(kv *kvarr, int fd, uchar_t max, uchar_t id)
4909 {
4910 	char *val = (id == NNN_BMS) ? bmstr : pluginstr;
4911 
4912 	for (uchar_t i = 0; i < max && kvarr[i].key; ++i)
4913 		dprintf(fd, " %c: %s\n", (char)kvarr[i].key, val + kvarr[i].off);
4914 }
4915 
4916 static void printkeys(kv *kvarr, char *buf, uchar_t max)
4917 {
4918 	uchar_t i = 0;
4919 
4920 	for (; i < max && kvarr[i].key; ++i) {
4921 		buf[i << 1] = ' ';
4922 		buf[(i << 1) + 1] = kvarr[i].key;
4923 	}
4924 
4925 	buf[i << 1] = '\0';
4926 }
4927 
4928 static size_t handle_bookmark(const char *bmark, char *newpath)
4929 {
4930 	int fd = '\r';
4931 	size_t r;
4932 
4933 	if (maxbm || bmark) {
4934 		r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
4935 
4936 		if (bmark) { /* There is a marked directory */
4937 			g_buf[--r] = ' ';
4938 			g_buf[++r] = ',';
4939 			g_buf[++r] = '\0';
4940 			++r;
4941 		}
4942 		printkeys(bookmark, g_buf + r - 1, maxbm);
4943 		printmsg(g_buf);
4944 		fd = get_input(NULL);
4945 	}
4946 
4947 	r = FALSE;
4948 	if (fd == ',') /* Visit marked directory */
4949 		bmark ? xstrsncpy(newpath, bmark, PATH_MAX) : (r = MSG_NOT_SET);
4950 	else if (fd == '\r') /* Visit bookmarks directory */
4951 		mkpath(cfgpath, toks[TOK_BM], newpath);
4952 	else if (!get_kv_val(bookmark, newpath, fd, maxbm, NNN_BMS))
4953 		r = MSG_INVALID_KEY;
4954 
4955 	if (!r && chdir(newpath) == -1)
4956 		r = MSG_ACCESS;
4957 
4958 	return r;
4959 }
4960 
4961 static void add_bookmark(char *path, char *newpath, int *presel)
4962 {
4963 	char *dir = xbasename(path);
4964 
4965 	dir = xreadline(dir[0] ? dir : NULL, "name: ");
4966 	if (dir && *dir) {
4967 		size_t r = mkpath(cfgpath, toks[TOK_BM], newpath);
4968 
4969 		newpath[r - 1] = '/';
4970 		xstrsncpy(newpath + r, dir, PATH_MAX - r);
4971 		printwait((symlink(path, newpath) == -1) ? strerror(errno) : newpath, presel);
4972 	} else
4973 		printwait(messages[MSG_CANCEL], presel);
4974 }
4975 
4976 /*
4977  * The help string tokens (each line) start with a HEX value
4978  * which indicates the number of spaces to print before the
4979  * particular token. This method was chosen instead of a flat
4980  * string because the number of bytes in help was increasing
4981  * the binary size by around a hundred bytes. This would only
4982  * have increased as we keep adding new options.
4983  */
4984 static void show_help(const char *path)
4985 {
4986 	const char *start, *end;
4987 	const char helpstr[] = {
4988 	"0\n"
4989 	"1NAVIGATION\n"
4990 	       "9Up k  Up%-16cPgUp ^U  Page up\n"
4991 	       "9Dn j  Down%-14cPgDn ^D  Page down\n"
4992 	       "9Lt h  Parent%-12c~ ` @ -  ~, /, start, prev\n"
4993 	   "5Ret Rt l  Open%-20c'  First file/match\n"
4994 	       "9g ^A  Top%-21c.  Toggle hidden\n"
4995 	       "9G ^E  End%-21c+  Toggle auto-advance\n"
4996 	      "8B (,)  Book(mark)%-11cb ^/  Select bookmark\n"
4997 		"a1-4  Context%-11c(Sh)Tab  Cycle/new context\n"
4998 	    "62Esc ^Q  Quit%-20cq  Quit context\n"
4999 		 "b^G  QuitCD%-18cQ  Pick/err, quit\n"
5000 	"0\n"
5001 	"1FILTER & PROMPT\n"
5002 		  "c/  Filter%-17c^N  Toggle type-to-nav\n"
5003 		"aEsc  Exit prompt%-12c^L  Toggle last filter\n"
5004 			"d%-20cAlt+Esc  Unfilter, quit context\n"
5005 	"0\n"
5006 	"1FILES\n"
5007 	       "9o ^O  Open with%-15cn  Create new/link\n"
5008 	       "9f ^F  File stats%-14cd  Detail mode toggle\n"
5009 		 "b^R  Rename/dup%-14cr  Batch rename\n"
5010 		  "cz  Archive%-17ce  Edit file\n"
5011 		  "c*  Toggle exe%-14c>  Export list\n"
5012 	   "5Space ^J  (Un)select%-12cm-m  Select range/clear\n"
5013 	          "ca  Select all%-14cA  Invert sel\n"
5014 	       "9p ^P  Copy here%-12cw ^W  Cp/mv sel as\n"
5015 	       "9v ^V  Move here%-15cE  Edit sel list\n"
5016 	       "9x ^X  Delete%-16cEsc  Send to FIFO\n"
5017 	"0\n"
5018 	"1MISC\n"
5019 	      "8Alt ;  Select plugin%-11c=  Launch app\n"
5020 	       "9! ^]  Shell%-19c]  Cmd prompt\n"
5021 		  "cc  Connect remote%-10cu  Unmount remote/archive\n"
5022 	       "9t ^T  Sort toggles%-12cs  Manage session\n"
5023 		  "cT  Set time type%-11c0  Lock\n"
5024 		 "b^L  Redraw%-18c?  Help, conf\n"
5025 	};
5026 
5027 	int fd = create_tmp_file();
5028 	if (fd == -1)
5029 		return;
5030 
5031 	dprintf(fd, "  |V\\_\n"
5032 		    "  /. \\\\\n"
5033 		    " (;^; ||\n"
5034 		    "   /___3\n"
5035 		    "  (___n))\n");
5036 
5037 	char *prog = xgetenv(env_cfg[NNN_HELP], NULL);
5038 	if (prog)
5039 		get_output(prog, NULL, NULL, fd, TRUE, FALSE);
5040 
5041 	start = end = helpstr;
5042 	while (*end) {
5043 		if (*end == '\n') {
5044 			snprintf(g_buf, CMD_LEN_MAX, "%*c%.*s",
5045 				 xchartohex(*start), ' ', (int)(end - start), start + 1);
5046 			dprintf(fd, g_buf, ' ');
5047 			start = end + 1;
5048 		}
5049 
5050 		++end;
5051 	}
5052 
5053 	dprintf(fd, "\nLOCATIONS:\n");
5054 	for (uchar_t i = 0; i < CTX_MAX; ++i)
5055 		if (g_ctx[i].c_cfg.ctxactive)
5056 			dprintf(fd, " %u: %s\n", i + 1, g_ctx[i].c_path);
5057 
5058 	dprintf(fd, "\nVOLUME: %s of ", coolsize(get_fs_info(path, FREE)));
5059 	dprintf(fd, "%s free\n\n", coolsize(get_fs_info(path, CAPACITY)));
5060 
5061 	if (bookmark) {
5062 		dprintf(fd, "BOOKMARKS\n");
5063 		printkv(bookmark, fd, maxbm, NNN_BMS);
5064 		dprintf(fd, "\n");
5065 	}
5066 
5067 	if (plug) {
5068 		dprintf(fd, "PLUGIN KEYS\n");
5069 		printkv(plug, fd, maxplug, NNN_PLUG);
5070 		dprintf(fd, "\n");
5071 	}
5072 
5073 	for (uchar_t i = NNN_OPENER; i <= NNN_TRASH; ++i) {
5074 		start = getenv(env_cfg[i]);
5075 		if (start)
5076 			dprintf(fd, "%s: %s\n", env_cfg[i], start);
5077 	}
5078 
5079 	if (selpath)
5080 		dprintf(fd, "SELECTION FILE: %s\n", selpath);
5081 
5082 	dprintf(fd, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
5083 	close(fd);
5084 
5085 	spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
5086 	unlink(g_tmpfpath);
5087 }
5088 
5089 static void setexports(void)
5090 {
5091 	char dvar[] = "d0";
5092 	char fvar[] = "f0";
5093 
5094 	if (ndents) {
5095 		setenv(envs[ENV_NCUR], pdents[cur].name, 1);
5096 		xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
5097 	} else if (g_ctx[cfg.curctx].c_name[0])
5098 		g_ctx[cfg.curctx].c_name[0] = '\0';
5099 
5100 	for (uchar_t i = 0; i < CTX_MAX; ++i) {
5101 		if (g_ctx[i].c_cfg.ctxactive) {
5102 			dvar[1] = fvar[1] = '1' + i;
5103 			setenv(dvar, g_ctx[i].c_path, 1);
5104 
5105 			if (g_ctx[i].c_name[0]) {
5106 				mkpath(g_ctx[i].c_path, g_ctx[i].c_name, g_buf);
5107 				setenv(fvar, g_buf, 1);
5108 			}
5109 		}
5110 	}
5111 }
5112 
5113 static bool run_cmd_as_plugin(const char *file, char *runfile, uchar_t flags)
5114 {
5115 	size_t len;
5116 
5117 	xstrsncpy(g_buf, file, PATH_MAX);
5118 
5119 	len = xstrlen(g_buf);
5120 	if (len > 1 && g_buf[len - 1] == '*') {
5121 		flags &= ~F_CONFIRM; /* Skip user confirmation */
5122 		g_buf[len - 1] = '\0'; /* Get rid of trailing no confirmation symbol */
5123 		--len;
5124 	}
5125 
5126 	if (flags & F_PAGE)
5127 		get_output(g_buf, NULL, NULL, -1, TRUE, TRUE);
5128 	else if (flags & F_NOTRACE) {
5129 		if (is_suffix(g_buf, " $nnn"))
5130 			g_buf[len - 5] = '\0';
5131 		else
5132 			runfile = NULL;
5133 		spawn(g_buf, runfile, NULL, NULL, flags);
5134 	} else
5135 		spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, flags);
5136 
5137 	return TRUE;
5138 }
5139 
5140 static bool plctrl_init(void)
5141 {
5142 	size_t len;
5143 
5144 	/* g_tmpfpath is used to generate tmp file names */
5145 	g_tmpfpath[tmpfplen - 1] = '\0';
5146 	len = xstrsncpy(g_pipepath, g_tmpfpath, TMP_LEN_MAX);
5147 	g_pipepath[len - 1] = '/';
5148 	len = xstrsncpy(g_pipepath + len, "nnn-pipe.", TMP_LEN_MAX - len) + len;
5149 	xstrsncpy(g_pipepath + len - 1, xitoa(getpid()), TMP_LEN_MAX - len);
5150 	setenv(env_cfg[NNN_PIPE], g_pipepath, TRUE);
5151 
5152 	return EXIT_SUCCESS;
5153 }
5154 
5155 static void rmlistpath(void)
5156 {
5157 	if (listpath) {
5158 		DPRINTF_S(__func__);
5159 		DPRINTF_S(listpath);
5160 		spawn(utils[UTIL_RM_RF], listpath, NULL, NULL, F_NOTRACE | F_MULTI);
5161 		/* Do not free if program was started in list mode */
5162 		if (listpath != initpath)
5163 			free(listpath);
5164 		listpath = NULL;
5165 	}
5166 }
5167 
5168 static ssize_t read_nointr(int fd, void *buf, size_t count)
5169 {
5170 	ssize_t len;
5171 
5172 	do
5173 		len = read(fd, buf, count);
5174 	while (len == -1 && errno == EINTR);
5175 
5176 	return len;
5177 }
5178 
5179 static char *readpipe(int fd, char *ctxnum, char **path)
5180 {
5181 	char ctx, *nextpath = NULL;
5182 
5183 	if (read_nointr(fd, g_buf, 1) != 1)
5184 		return NULL;
5185 
5186 	if (g_buf[0] == '-') { /* Clear selection on '-' */
5187 		clearselection();
5188 		if (read_nointr(fd, g_buf, 1) != 1)
5189 			return NULL;
5190 	}
5191 
5192 	if (g_buf[0] == '+')
5193 		ctx = (char)(get_free_ctx() + 1);
5194 	else if (g_buf[0] < '0')
5195 		return NULL;
5196 	else {
5197 		ctx = g_buf[0] - '0';
5198 		if (ctx > CTX_MAX)
5199 			return NULL;
5200 	}
5201 
5202 	if (read_nointr(fd, g_buf, 1) != 1)
5203 		return NULL;
5204 
5205 	char op = g_buf[0];
5206 
5207 	if (op == 'c') {
5208 		ssize_t len = read_nointr(fd, g_buf, PATH_MAX);
5209 
5210 		if (len <= 0)
5211 			return NULL;
5212 
5213 		g_buf[len] = '\0'; /* Terminate the path read */
5214 		if (g_buf[0] == '/') {
5215 			nextpath = g_buf;
5216 			len = xstrlen(g_buf);
5217 			while (--len && (g_buf[len] == '/')) /* Trim all trailing '/' */
5218 				g_buf[len] = '\0';
5219 		}
5220 	} else if (op == 'l') {
5221 		rmlistpath(); /* Remove last list mode path, if any */
5222 		nextpath = load_input(fd, *path);
5223 	} else if (op == 'p') {
5224 		free(selpath);
5225 		selpath = NULL;
5226 		clearselection();
5227 		g_state.picker = 0;
5228 		g_state.picked = 1;
5229 	}
5230 
5231 	*ctxnum = ctx;
5232 
5233 	return nextpath;
5234 }
5235 
5236 static bool run_plugin(char **path, const char *file, char *runfile, char **lastname, char **lastdir)
5237 {
5238 	pid_t p;
5239 	char ctx = 0;
5240 	uchar_t flags = 0;
5241 	bool cmd_as_plugin = FALSE;
5242 	char *nextpath;
5243 
5244 	if (!g_state.pluginit) {
5245 		plctrl_init();
5246 		g_state.pluginit = 1;
5247 	}
5248 
5249 	setexports();
5250 
5251 	/* Check for run-cmd-as-plugin mode */
5252 	if (*file == '!') {
5253 		flags = F_MULTI | F_CONFIRM;
5254 		++file;
5255 
5256 		if (*file == '|') { /* Check if output should be paged */
5257 			flags |= F_PAGE;
5258 			++file;
5259 		} else if (*file == '&') { /* Check if GUI flags are to be used */
5260 			flags = F_NOTRACE | F_NOWAIT;
5261 			++file;
5262 		}
5263 
5264 		if (!*file)
5265 			return FALSE;
5266 
5267 		if ((flags & F_NOTRACE) || (flags & F_PAGE))
5268 			return run_cmd_as_plugin(file, runfile, flags);
5269 
5270 		cmd_as_plugin = TRUE;
5271 	}
5272 
5273 	if (mkfifo(g_pipepath, 0600) != 0)
5274 		return FALSE;
5275 
5276 	exitcurses();
5277 
5278 	p = fork();
5279 
5280 	if (!p) { // In child
5281 		int wfd = open(g_pipepath, O_WRONLY | O_CLOEXEC);
5282 
5283 		if (wfd == -1)
5284 			_exit(EXIT_FAILURE);
5285 
5286 		if (!cmd_as_plugin) {
5287 			char *sel = NULL;
5288 			char std[2] = "-";
5289 
5290 			/* Generate absolute path to plugin */
5291 			mkpath(plgpath, file, g_buf);
5292 
5293 			if (g_state.picker)
5294 				sel = selpath ? selpath : std;
5295 
5296 			if (runfile && runfile[0]) {
5297 				xstrsncpy(*lastname, runfile, NAME_MAX);
5298 				spawn(g_buf, *lastname, *path, sel, 0);
5299 			} else
5300 				spawn(g_buf, NULL, *path, sel, 0);
5301 		} else
5302 			run_cmd_as_plugin(file, NULL, flags);
5303 
5304 		close(wfd);
5305 		_exit(EXIT_SUCCESS);
5306 	}
5307 
5308 	int rfd;
5309 
5310 	do
5311 		rfd = open(g_pipepath, O_RDONLY);
5312 	while (rfd == -1 && errno == EINTR);
5313 
5314 	nextpath = readpipe(rfd, &ctx, path);
5315 	if (nextpath)
5316 		set_smart_ctx(ctx, nextpath, path, runfile, lastname, lastdir);
5317 
5318 	close(rfd);
5319 
5320 	/* wait for the child to finish. no zombies allowed */
5321 	waitpid(p, NULL, 0);
5322 
5323 	refresh();
5324 
5325 	unlink(g_pipepath);
5326 
5327 	return TRUE;
5328 }
5329 
5330 static bool launch_app(char *newpath)
5331 {
5332 	int r = F_NORMAL;
5333 	char *tmp = newpath;
5334 
5335 	mkpath(plgpath, utils[UTIL_LAUNCH], newpath);
5336 
5337 	if (!getutil(utils[UTIL_FZF]) || access(newpath, X_OK) < 0) {
5338 		tmp = xreadline(NULL, messages[MSG_APP_NAME]);
5339 		r = F_NOWAIT | F_NOTRACE | F_MULTI;
5340 	}
5341 
5342 	if (tmp && *tmp) // NOLINT
5343 		spawn(tmp, (r == F_NORMAL) ? "0" : NULL, NULL, NULL, r);
5344 
5345 	return FALSE;
5346 }
5347 
5348 /* Returns TRUE if at least one command was run */
5349 static bool prompt_run(void)
5350 {
5351 	bool ret = FALSE;
5352 	char *tmp;
5353 
5354 	while (1) {
5355 #ifndef NORL
5356 		if (g_state.picker) {
5357 #endif
5358 			tmp = xreadline(NULL, PROMPT);
5359 #ifndef NORL
5360 		} else
5361 			tmp = getreadline("\n"PROMPT);
5362 #endif
5363 		if (tmp && *tmp) { // NOLINT
5364 			free(lastcmd);
5365 			lastcmd = xstrdup(tmp);
5366 			ret = TRUE;
5367 			spawn(shell, "-c", tmp, NULL, F_CLI | F_CONFIRM);
5368 		} else
5369 			break;
5370 	}
5371 
5372 	return ret;
5373 }
5374 
5375 static bool handle_cmd(enum action sel, char *newpath)
5376 {
5377 	endselection(FALSE);
5378 
5379 	if (sel == SEL_LAUNCH)
5380 		return launch_app(newpath);
5381 
5382 	setexports();
5383 
5384 	if (sel == SEL_PROMPT)
5385 		return prompt_run();
5386 
5387 	/* Set nnn nesting level */
5388 	char *tmp = getenv(env_cfg[NNNLVL]);
5389 	int r = tmp ? atoi(tmp) : 0;
5390 
5391 	setenv(env_cfg[NNNLVL], xitoa(r + 1), 1);
5392 	spawn(shell, NULL, NULL, NULL, F_CLI);
5393 	setenv(env_cfg[NNNLVL], xitoa(r), 1);
5394 	return TRUE;
5395 }
5396 
5397 static void dentfree(void)
5398 {
5399 	free(pnamebuf);
5400 	free(pdents);
5401 	free(mark);
5402 
5403 	/* Thread data cleanup */
5404 	free(core_blocks);
5405 	free(core_data);
5406 	free(core_files);
5407 }
5408 
5409 static void *du_thread(void *p_data)
5410 {
5411 	thread_data *pdata = (thread_data *)p_data;
5412 	char *path[2] = {pdata->path, NULL};
5413 	ullong_t tfiles = 0;
5414 	blkcnt_t tblocks = 0;
5415 	struct stat *sb;
5416 	FTS *tree = fts_open(path, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR, 0);
5417 	FTSENT *node;
5418 
5419 	while ((node = fts_read(tree))) {
5420 		if (node->fts_info & FTS_D)
5421 			continue;
5422 
5423 		sb = node->fts_statp;
5424 
5425 		if (cfg.apparentsz) {
5426 			if (sb->st_size && DU_TEST)
5427 				tblocks += sb->st_size;
5428 		} else if (sb->st_blocks && DU_TEST)
5429 			tblocks += sb->st_blocks;
5430 
5431 		++tfiles;
5432 	}
5433 
5434 	fts_close(tree);
5435 
5436 	if (pdata->entnum >= 0)
5437 		pdents[pdata->entnum].blocks = tblocks;
5438 
5439 	if (!pdata->mntpoint) {
5440 		core_blocks[pdata->core] += tblocks;
5441 		core_files[pdata->core] += tfiles;
5442 	} else
5443 		core_files[pdata->core] += 1;
5444 
5445 	pthread_mutex_lock(&running_mutex);
5446 	threadbmp |= (1 << pdata->core);
5447 	--active_threads;
5448 	pthread_mutex_unlock(&running_mutex);
5449 
5450 	return NULL;
5451 }
5452 
5453 static void dirwalk(char *path, int entnum, bool mountpoint)
5454 {
5455 	/* Loop till any core is free */
5456 	while (active_threads == NUM_DU_THREADS);
5457 
5458 	if (g_state.interrupt)
5459 		return;
5460 
5461 	pthread_mutex_lock(&running_mutex);
5462 	int core = ffs(threadbmp) - 1;
5463 
5464 	threadbmp &= ~(1 << core);
5465 	++active_threads;
5466 	pthread_mutex_unlock(&running_mutex);
5467 
5468 	xstrsncpy(core_data[core].path, path, PATH_MAX);
5469 	core_data[core].entnum = entnum;
5470 	core_data[core].core = (ushort_t)core;
5471 	core_data[core].mntpoint = mountpoint;
5472 
5473 	pthread_t tid = 0;
5474 
5475 	pthread_create(&tid, NULL, du_thread, (void *)&(core_data[core]));
5476 
5477 	tolastln();
5478 	addstr(xbasename(path));
5479 	addstr(" [^C aborts]\n");
5480 	refresh();
5481 }
5482 
5483 static void prep_threads(void)
5484 {
5485 	if (!g_state.duinit) {
5486 		/* drop MSB 1s */
5487 		threadbmp >>= (32 - NUM_DU_THREADS);
5488 
5489 		core_blocks = calloc(NUM_DU_THREADS, sizeof(blkcnt_t));
5490 		core_data = calloc(NUM_DU_THREADS, sizeof(thread_data));
5491 		core_files = calloc(NUM_DU_THREADS, sizeof(ullong_t));
5492 
5493 #ifndef __APPLE__
5494 		/* Increase current open file descriptor limit */
5495 		max_openfds();
5496 #endif
5497 		g_state.duinit = TRUE;
5498 	} else {
5499 		memset(core_blocks, 0, NUM_DU_THREADS * sizeof(blkcnt_t));
5500 		memset(core_data, 0, NUM_DU_THREADS * sizeof(thread_data));
5501 		memset(core_files, 0, NUM_DU_THREADS * sizeof(ullong_t));
5502 	}
5503 }
5504 
5505 /* Skip self and parent */
5506 static bool selforparent(const char *path)
5507 {
5508 	return path[0] == '.' && (path[1] == '\0' || (path[1] == '.' && path[2] == '\0'));
5509 }
5510 
5511 static int dentfill(char *path, struct entry **ppdents)
5512 {
5513 	uchar_t entflags = 0;
5514 	int flags = 0;
5515 	struct dirent *dp;
5516 	char *namep, *pnb, *buf;
5517 	struct entry *dentp;
5518 	size_t off = 0, namebuflen = NAMEBUF_INCR;
5519 	struct stat sb_path, sb;
5520 	DIR *dirp = opendir(path);
5521 
5522 	ndents = 0;
5523 
5524 	DPRINTF_S(__func__);
5525 
5526 	if (!dirp)
5527 		return 0;
5528 
5529 	int fd = dirfd(dirp);
5530 
5531 	if (cfg.blkorder) {
5532 		num_files = 0;
5533 		dir_blocks = 0;
5534 		buf = g_buf;
5535 
5536 		if (fstatat(fd, path, &sb_path, 0) == -1)
5537 			goto exit;
5538 
5539 		if (!ihashbmp) {
5540 			ihashbmp = calloc(1, HASH_OCTETS << 3);
5541 			if (!ihashbmp)
5542 				goto exit;
5543 		} else
5544 			memset(ihashbmp, 0, HASH_OCTETS << 3);
5545 
5546 		prep_threads();
5547 
5548 		attron(COLOR_PAIR(cfg.curctx + 1));
5549 	}
5550 
5551 #if _POSIX_C_SOURCE >= 200112L
5552 	posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
5553 #endif
5554 
5555 	dp = readdir(dirp);
5556 	if (!dp)
5557 		goto exit;
5558 
5559 #if defined(__sun) || defined(__HAIKU__)
5560 	flags = AT_SYMLINK_NOFOLLOW; /* no d_type */
5561 #else
5562 	if (cfg.blkorder || dp->d_type == DT_UNKNOWN) {
5563 		/*
5564 		 * Optimization added for filesystems which support dirent.d_type
5565 		 * see readdir(3)
5566 		 * Known drawbacks:
5567 		 * - the symlink size is set to 0
5568 		 * - the modification time of the symlink is set to that of the target file
5569 		 */
5570 		flags = AT_SYMLINK_NOFOLLOW;
5571 	}
5572 #endif
5573 
5574 	do {
5575 		namep = dp->d_name;
5576 
5577 		if (selforparent(namep))
5578 			continue;
5579 
5580 		if (!cfg.showhidden && namep[0] == '.') {
5581 			if (!cfg.blkorder)
5582 				continue;
5583 
5584 			if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
5585 				continue;
5586 
5587 			if (S_ISDIR(sb.st_mode)) {
5588 				if (sb_path.st_dev == sb.st_dev) { // NOLINT
5589 					mkpath(path, namep, buf); // NOLINT
5590 					dirwalk(buf, -1, FALSE);
5591 
5592 					if (g_state.interrupt)
5593 						goto exit;
5594 
5595 				}
5596 			} else {
5597 				/* Do not recount hard links */
5598 				if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5599 					dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5600 				++num_files;
5601 			}
5602 
5603 			continue;
5604 		}
5605 
5606 		if (fstatat(fd, namep, &sb, flags) == -1) {
5607 			if (flags || (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)) {
5608 				/* Missing file */
5609 				DPRINTF_U(flags);
5610 				if (!flags) {
5611 					DPRINTF_S(namep);
5612 					DPRINTF_S(strerror(errno));
5613 				}
5614 
5615 				entflags = FILE_MISSING;
5616 				memset(&sb, 0, sizeof(struct stat));
5617 			} else /* Orphaned symlink */
5618 				entflags = SYM_ORPHAN;
5619 		}
5620 
5621 		if (ndents == total_dents) {
5622 			if (cfg.blkorder)
5623 				while (active_threads);
5624 
5625 			total_dents += ENTRY_INCR;
5626 			*ppdents = xrealloc(*ppdents, total_dents * sizeof(**ppdents));
5627 			if (!*ppdents) {
5628 				free(pnamebuf);
5629 				closedir(dirp);
5630 				errexit();
5631 			}
5632 			DPRINTF_P(*ppdents);
5633 		}
5634 
5635 		/* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
5636 		if (namebuflen - off < NAME_MAX + 1) {
5637 			namebuflen += NAMEBUF_INCR;
5638 
5639 			pnb = pnamebuf;
5640 			pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
5641 			if (!pnamebuf) {
5642 				free(*ppdents);
5643 				closedir(dirp);
5644 				errexit();
5645 			}
5646 			DPRINTF_P(pnamebuf);
5647 
5648 			/* realloc() may result in memory move, we must re-adjust if that happens */
5649 			if (pnb != pnamebuf) {
5650 				dentp = *ppdents;
5651 				dentp->name = pnamebuf;
5652 
5653 				for (int count = 1; count < ndents; ++dentp, ++count)
5654 					/* Current file name starts at last file name start + length */
5655 					(dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
5656 			}
5657 		}
5658 
5659 		dentp = *ppdents + ndents;
5660 
5661 		/* Selection file name */
5662 		dentp->name = (char *)((size_t)pnamebuf + off);
5663 		dentp->nlen = xstrsncpy(dentp->name, namep, NAME_MAX + 1);
5664 		off += dentp->nlen;
5665 
5666 		/* Copy other fields */
5667 		if (cfg.timetype == T_MOD) {
5668 			dentp->sec = sb.st_mtime;
5669 #ifdef __APPLE__
5670 			dentp->nsec = (uint_t)sb.st_mtimespec.tv_nsec;
5671 #else
5672 			dentp->nsec = (uint_t)sb.st_mtim.tv_nsec;
5673 #endif
5674 		} else if (cfg.timetype == T_ACCESS) {
5675 			dentp->sec = sb.st_atime;
5676 #ifdef __APPLE__
5677 			dentp->nsec = (uint_t)sb.st_atimespec.tv_nsec;
5678 #else
5679 			dentp->nsec = (uint_t)sb.st_atim.tv_nsec;
5680 #endif
5681 		} else {
5682 			dentp->sec = sb.st_ctime;
5683 #ifdef __APPLE__
5684 			dentp->nsec = (uint_t)sb.st_ctimespec.tv_nsec;
5685 #else
5686 			dentp->nsec = (uint_t)sb.st_ctim.tv_nsec;
5687 #endif
5688 		}
5689 
5690 #if !(defined(__sun) || defined(__HAIKU__))
5691 		if (!flags && dp->d_type == DT_LNK) {
5692 			 /* Do not add sizes for links */
5693 			dentp->mode = (sb.st_mode & ~S_IFMT) | S_IFLNK;
5694 			dentp->size = listpath ? sb.st_size : 0;
5695 		} else {
5696 			dentp->mode = sb.st_mode;
5697 			dentp->size = sb.st_size;
5698 		}
5699 #else
5700 		dentp->mode = sb.st_mode;
5701 		dentp->size = sb.st_size;
5702 #endif
5703 
5704 #ifndef NOUG
5705 		dentp->uid = sb.st_uid;
5706 		dentp->gid = sb.st_gid;
5707 #endif
5708 
5709 		dentp->flags = S_ISDIR(sb.st_mode) ? 0 : ((sb.st_nlink > 1) ? HARD_LINK : 0);
5710 		if (entflags) {
5711 			dentp->flags |= entflags;
5712 			entflags = 0;
5713 		}
5714 
5715 		if (cfg.blkorder) {
5716 			if (S_ISDIR(sb.st_mode)) {
5717 				mkpath(path, namep, buf); // NOLINT
5718 
5719 				/* Need to show the disk usage of this dir */
5720 				dirwalk(buf, ndents, (sb_path.st_dev != sb.st_dev)); // NOLINT
5721 
5722 				if (g_state.interrupt)
5723 					goto exit;
5724 			} else {
5725 				dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5726 				/* Do not recount hard links */
5727 				if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5728 					dir_blocks += dentp->blocks;
5729 				++num_files;
5730 			}
5731 		}
5732 
5733 		if (flags) {
5734 			/* Flag if this is a dir or symlink to a dir */
5735 			if (S_ISLNK(sb.st_mode)) {
5736 				sb.st_mode = 0;
5737 				fstatat(fd, namep, &sb, 0);
5738 			}
5739 
5740 			if (S_ISDIR(sb.st_mode))
5741 				dentp->flags |= DIR_OR_DIRLNK;
5742 #if !(defined(__sun) || defined(__HAIKU__)) /* no d_type */
5743 		} else if (dp->d_type == DT_DIR || ((dp->d_type == DT_LNK
5744 			   || dp->d_type == DT_UNKNOWN) && S_ISDIR(sb.st_mode))) {
5745 			dentp->flags |= DIR_OR_DIRLNK;
5746 #endif
5747 		}
5748 
5749 		++ndents;
5750 	} while ((dp = readdir(dirp)));
5751 
5752 exit:
5753 	if (cfg.blkorder) {
5754 		while (active_threads);
5755 
5756 		attroff(COLOR_PAIR(cfg.curctx + 1));
5757 		for (int i = 0; i < NUM_DU_THREADS; ++i) {
5758 			num_files += core_files[i];
5759 			dir_blocks += core_blocks[i];
5760 		}
5761 	}
5762 
5763 	/* Should never be null */
5764 	if (closedir(dirp) == -1)
5765 		errexit();
5766 
5767 	return ndents;
5768 }
5769 
5770 static void populate(char *path, char *lastname)
5771 {
5772 #ifdef DEBUG
5773 	struct timespec ts1, ts2;
5774 
5775 	clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
5776 #endif
5777 
5778 	ndents = dentfill(path, &pdents);
5779 	if (!ndents)
5780 		return;
5781 
5782 	ENTSORT(pdents, ndents, entrycmpfn);
5783 
5784 #ifdef DEBUG
5785 	clock_gettime(CLOCK_REALTIME, &ts2);
5786 	DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
5787 #endif
5788 
5789 	/* Find cur from history */
5790 	/* No NULL check for lastname, always points to an array */
5791 	move_cursor(*lastname ? dentfind(lastname, ndents) : 0, 0);
5792 
5793 	// Force full redraw
5794 	last_curscroll = -1;
5795 }
5796 
5797 #ifndef NOFIFO
5798 static void notify_fifo(bool force)
5799 {
5800 	if (!fifopath)
5801 		return;
5802 
5803 	if (fifofd == -1) {
5804 		fifofd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC);
5805 		if (fifofd == -1) {
5806 			if (errno != ENXIO)
5807 				/* Unexpected error, the FIFO file might have been removed */
5808 				/* We give up FIFO notification */
5809 				fifopath = NULL;
5810 			return;
5811 		}
5812 	}
5813 
5814 	static struct entry lastentry;
5815 
5816 	if (!force && !memcmp(&lastentry, &pdents[cur], sizeof(struct entry)))
5817 		return;
5818 
5819 	lastentry = pdents[cur];
5820 
5821 	char path[PATH_MAX];
5822 	size_t len = mkpath(g_ctx[cfg.curctx].c_path, ndents ? pdents[cur].name : "", path);
5823 
5824 	path[len - 1] = '\n';
5825 
5826 	ssize_t ret = write(fifofd, path, len);
5827 
5828 	if (ret != (ssize_t)len && !(ret == -1 && (errno == EAGAIN || errno == EPIPE))) {
5829 		DPRINTF_S(strerror(errno));
5830 	}
5831 }
5832 #endif
5833 
5834 static void move_cursor(int target, int ignore_scrolloff)
5835 {
5836 	int onscreen = xlines - 4; /* Leave top 2 and bottom 2 lines */
5837 
5838 	target = MAX(0, MIN(ndents - 1, target));
5839 	last_curscroll = curscroll;
5840 	last = cur;
5841 	cur = target;
5842 
5843 	if (!ignore_scrolloff) {
5844 		int delta = target - last;
5845 		int scrolloff = MIN(SCROLLOFF, onscreen >> 1);
5846 
5847 		/*
5848 		 * When ignore_scrolloff is 1, the cursor can jump into the scrolloff
5849 		 * margin area, but when ignore_scrolloff is 0, act like a boa
5850 		 * constrictor and squeeze the cursor towards the middle region of the
5851 		 * screen by allowing it to move inward and disallowing it to move
5852 		 * outward (deeper into the scrolloff margin area).
5853 		 */
5854 		if (((cur < (curscroll + scrolloff)) && delta < 0)
5855 		    || ((cur > (curscroll + onscreen - scrolloff - 1)) && delta > 0))
5856 			curscroll += delta;
5857 	}
5858 	curscroll = MIN(curscroll, MIN(cur, ndents - onscreen));
5859 	curscroll = MAX(curscroll, MAX(cur - (onscreen - 1), 0));
5860 
5861 #ifndef NOFIFO
5862 	if (!g_state.fifomode)
5863 		notify_fifo(FALSE); /* Send hovered path to NNN_FIFO */
5864 #endif
5865 }
5866 
5867 static void handle_screen_move(enum action sel)
5868 {
5869 	int onscreen;
5870 
5871 	switch (sel) {
5872 	case SEL_NEXT:
5873 		if (ndents && (cfg.rollover || (cur != ndents - 1)))
5874 			move_cursor((cur + 1) % ndents, 0);
5875 		break;
5876 	case SEL_PREV:
5877 		if (ndents && (cfg.rollover || cur))
5878 			move_cursor((cur + ndents - 1) % ndents, 0);
5879 		break;
5880 	case SEL_PGDN:
5881 		onscreen = xlines - 4;
5882 		move_cursor(curscroll + (onscreen - 1), 1);
5883 		curscroll += onscreen - 1;
5884 		break;
5885 	case SEL_CTRL_D:
5886 		onscreen = xlines - 4;
5887 		move_cursor(curscroll + (onscreen - 1), 1);
5888 		curscroll += onscreen >> 1;
5889 		break;
5890 	case SEL_PGUP: // fallthrough
5891 		onscreen = xlines - 4;
5892 		move_cursor(curscroll, 1);
5893 		curscroll -= onscreen - 1;
5894 		break;
5895 	case SEL_CTRL_U:
5896 		onscreen = xlines - 4;
5897 		move_cursor(curscroll, 1);
5898 		curscroll -= onscreen >> 1;
5899 		break;
5900 	case SEL_HOME:
5901 		move_cursor(0, 1);
5902 		break;
5903 	case SEL_END:
5904 		move_cursor(ndents - 1, 1);
5905 		break;
5906 	default: /* case SEL_FIRST */
5907 	{
5908 		int c = get_input(messages[MSG_FIRST]);
5909 
5910 		if (!c)
5911 			break;
5912 
5913 		c = TOUPPER(c);
5914 
5915 		int r = (c == TOUPPER(*pdents[cur].name)) ? (cur + 1) : 0;
5916 
5917 		for (; r < ndents; ++r) {
5918 			if (((c == '\'') && !(pdents[r].flags & DIR_OR_DIRLNK))
5919 			    || (c == TOUPPER(*pdents[r].name))) {
5920 				move_cursor((r) % ndents, 0);
5921 				break;
5922 			}
5923 		}
5924 		break;
5925 	}
5926 	}
5927 }
5928 
5929 static void handle_openwith(const char *path, const char *name, char *newpath, char *tmp)
5930 {
5931 	/* Confirm if app is CLI or GUI */
5932 	int r = get_input(messages[MSG_CLI_MODE]);
5933 
5934 	r = (r == 'c' ? F_CLI :
5935 	     (r == 'g' ? F_NOWAIT | F_NOTRACE | F_MULTI : 0));
5936 	if (r) {
5937 		mkpath(path, name, newpath);
5938 		spawn(tmp, newpath, NULL, NULL, r);
5939 	}
5940 }
5941 
5942 static void copynextname(char *lastname)
5943 {
5944 	if (cur) {
5945 		cur += (cur != (ndents - 1)) ? 1 : -1;
5946 		copycurname();
5947 	} else
5948 		lastname[0] = '\0';
5949 }
5950 
5951 static int handle_context_switch(enum action sel)
5952 {
5953 	int r = -1;
5954 
5955 	switch (sel) {
5956 	case SEL_CYCLE: // fallthrough
5957 	case SEL_CYCLER:
5958 		/* visit next and previous contexts */
5959 		r = cfg.curctx;
5960 		if (sel == SEL_CYCLE)
5961 			do
5962 				r = (r + 1) & ~CTX_MAX;
5963 			while (!g_ctx[r].c_cfg.ctxactive);
5964 		else {
5965 			do /* Attempt to create a new context */
5966 				r = (r + 1) & ~CTX_MAX;
5967 			while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
5968 
5969 			if (r == cfg.curctx) /* If all contexts are active, reverse cycle */
5970 				do
5971 					r = (r + (CTX_MAX - 1)) & (CTX_MAX - 1);
5972 				while (!g_ctx[r].c_cfg.ctxactive);
5973 		} // fallthrough
5974 	default: /* SEL_CTXN */
5975 		if (sel >= SEL_CTX1) /* CYCLE keys are lesser in value */
5976 			r = sel - SEL_CTX1; /* Save the next context id */
5977 
5978 		if (cfg.curctx == r) {
5979 			if (sel == SEL_CYCLE)
5980 				(r == CTX_MAX - 1) ? (r = 0) : ++r;
5981 			else if (sel == SEL_CYCLER)
5982 				(r == 0) ? (r = CTX_MAX - 1) : --r;
5983 			else
5984 				return -1;
5985 		}
5986 	}
5987 
5988 	return r;
5989 }
5990 
5991 static int set_sort_flags(int r)
5992 {
5993 	bool session = (r == '\0');
5994 	bool reverse = FALSE;
5995 
5996 	if (ISUPPER_(r) && (r != 'R') && (r != 'C')) {
5997 		reverse = TRUE;
5998 		r = TOLOWER(r);
5999 	}
6000 
6001 	/* Set the correct input in case of a session load */
6002 	if (session) {
6003 		if (cfg.apparentsz) {
6004 			cfg.apparentsz = 0;
6005 			r = 'a';
6006 		} else if (cfg.blkorder) {
6007 			cfg.blkorder = 0;
6008 			r = 'd';
6009 		}
6010 
6011 		if (cfg.version)
6012 			namecmpfn = &xstrverscasecmp;
6013 
6014 		if (cfg.reverse)
6015 			entrycmpfn = &reventrycmp;
6016 	} else if (r == CONTROL('T')) {
6017 		/* Cycling order: clear -> size -> time -> clear */
6018 		if (cfg.timeorder)
6019 			r = 's';
6020 		else if (cfg.sizeorder)
6021 			r = 'c';
6022 		else
6023 			r = 't';
6024 	}
6025 
6026 	switch (r) {
6027 	case 'a': /* Apparent du */
6028 		cfg.apparentsz ^= 1;
6029 		if (cfg.apparentsz) {
6030 			cfg.blkorder = 1;
6031 			blk_shift = 0;
6032 		} else
6033 			cfg.blkorder = 0;
6034 		// fallthrough
6035 	case 'd': /* Disk usage */
6036 		if (r == 'd') {
6037 			if (!cfg.apparentsz)
6038 				cfg.blkorder ^= 1;
6039 			cfg.apparentsz = 0;
6040 			blk_shift = ffs(S_BLKSIZE) - 1;
6041 		}
6042 
6043 		if (cfg.blkorder)
6044 			cfg.showdetail = 1;
6045 		cfg.timeorder = 0;
6046 		cfg.sizeorder = 0;
6047 		cfg.extnorder = 0;
6048 		if (!session) {
6049 			cfg.reverse = 0;
6050 			entrycmpfn = &entrycmp;
6051 		}
6052 		endselection(TRUE); /* We are going to reload dir */
6053 		break;
6054 	case 'c':
6055 		cfg.timeorder = 0;
6056 		cfg.sizeorder = 0;
6057 		cfg.apparentsz = 0;
6058 		cfg.blkorder = 0;
6059 		cfg.extnorder = 0;
6060 		cfg.reverse = 0;
6061 		cfg.version = 0;
6062 		entrycmpfn = &entrycmp;
6063 		namecmpfn = &xstricmp;
6064 		break;
6065 	case 'e': /* File extension */
6066 		cfg.extnorder ^= 1;
6067 		cfg.sizeorder = 0;
6068 		cfg.timeorder = 0;
6069 		cfg.apparentsz = 0;
6070 		cfg.blkorder = 0;
6071 		cfg.reverse = 0;
6072 		entrycmpfn = &entrycmp;
6073 		break;
6074 	case 'r': /* Reverse sort */
6075 		cfg.reverse ^= 1;
6076 		entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
6077 		break;
6078 	case 's': /* File size */
6079 		cfg.sizeorder ^= 1;
6080 		cfg.timeorder = 0;
6081 		cfg.apparentsz = 0;
6082 		cfg.blkorder = 0;
6083 		cfg.extnorder = 0;
6084 		cfg.reverse = 0;
6085 		entrycmpfn = &entrycmp;
6086 		break;
6087 	case 't': /* Time */
6088 		cfg.timeorder ^= 1;
6089 		cfg.sizeorder = 0;
6090 		cfg.apparentsz = 0;
6091 		cfg.blkorder = 0;
6092 		cfg.extnorder = 0;
6093 		cfg.reverse = 0;
6094 		entrycmpfn = &entrycmp;
6095 		break;
6096 	case 'v': /* Version */
6097 		cfg.version ^= 1;
6098 		namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
6099 		cfg.timeorder = 0;
6100 		cfg.sizeorder = 0;
6101 		cfg.apparentsz = 0;
6102 		cfg.blkorder = 0;
6103 		cfg.extnorder = 0;
6104 		break;
6105 	default:
6106 		return 0;
6107 	}
6108 
6109 	if (reverse) {
6110 		cfg.reverse = 1;
6111 		entrycmpfn = &reventrycmp;
6112 	}
6113 
6114 	cfgsort[cfg.curctx] = (uchar_t)r;
6115 
6116 	return r;
6117 }
6118 
6119 static bool set_time_type(int *presel)
6120 {
6121 	bool ret = FALSE;
6122 	char buf[] = "'a'ccess / 'c'hange / 'm'od [ ]";
6123 
6124 	buf[sizeof(buf) - 3] = cfg.timetype == T_MOD ? 'm' : (cfg.timetype == T_ACCESS ? 'a' : 'c');
6125 
6126 	int r = get_input(buf);
6127 
6128 	if (r == 'a' || r == 'c' || r == 'm') {
6129 		r = (r == 'm') ? T_MOD : ((r == 'a') ? T_ACCESS : T_CHANGE);
6130 		if (cfg.timetype != r) {
6131 			cfg.timetype = r;
6132 
6133 			if (cfg.filtermode || g_ctx[cfg.curctx].c_fltr[1])
6134 				*presel = FILTER;
6135 
6136 			ret = TRUE;
6137 		} else
6138 			r = MSG_NOCHANGE;
6139 	} else
6140 		r = MSG_INVALID_KEY;
6141 
6142 	if (!ret)
6143 		printwait(messages[r], presel);
6144 
6145 	return ret;
6146 }
6147 
6148 static void statusbar(char *path)
6149 {
6150 	int i = 0, len = 0;
6151 	char *ptr;
6152 	pEntry pent = &pdents[cur];
6153 
6154 	if (!ndents) {
6155 		printmsg("0/0");
6156 		return;
6157 	}
6158 
6159 	/* Get the file extension for regular files */
6160 	if (S_ISREG(pent->mode)) {
6161 		i = (int)(pent->nlen - 1);
6162 		ptr = xextension(pent->name, i);
6163 		if (ptr)
6164 			len = i - (ptr - pent->name);
6165 		if (!ptr || len > 5 || len < 2)
6166 			ptr = "\b";
6167 	} else
6168 		ptr = "\b";
6169 
6170 	tolastln();
6171 	attron(COLOR_PAIR(cfg.curctx + 1));
6172 
6173 	printw("%d/%s ", cur + 1, xitoa(ndents));
6174 
6175 	if (g_state.selmode || nselected) {
6176 		attron(A_REVERSE);
6177 		addch(' ');
6178 		if (g_state.rangesel)
6179 			addch('*');
6180 		else if (g_state.selmode)
6181 			addch('+');
6182 		if (nselected)
6183 			addstr(xitoa(nselected));
6184 		addch(' ');
6185 		attroff(A_REVERSE);
6186 		addch(' ');
6187 	}
6188 
6189 	if (cfg.blkorder) { /* du mode */
6190 		char buf[24];
6191 
6192 		xstrsncpy(buf, coolsize(dir_blocks << blk_shift), 12);
6193 
6194 		printw("%cu:%s free:%s files:%llu %lluB %s\n",
6195 		       (cfg.apparentsz ? 'a' : 'd'), buf, coolsize(get_fs_info(path, FREE)),
6196 		       num_files, (ullong_t)pent->blocks << blk_shift, ptr);
6197 	} else { /* light or detail mode */
6198 		char sort[] = "\0\0\0\0\0";
6199 
6200 		if (getorderstr(sort))
6201 			addstr(sort);
6202 
6203 		/* Timestamp */
6204 		print_time(&pent->sec);
6205 
6206 		addch(' ');
6207 		addstr(get_lsperms(pent->mode));
6208 		addch(' ');
6209 #ifndef NOUG
6210 		if (g_state.uidgid) {
6211 			addstr(getpwname(pent->uid));
6212 			addch(':');
6213 			addstr(getgrname(pent->gid));
6214 			addch(' ');
6215 		}
6216 #endif
6217 		if (S_ISLNK(pent->mode)) {
6218 			i = readlink(pent->name, g_buf, PATH_MAX);
6219 			addstr(coolsize(i >= 0 ? i : pent->size)); /* Show symlink size */
6220 			if (i > 1) { /* Show symlink target */
6221 				int y;
6222 
6223 				addstr(" ->");
6224 				getyx(stdscr, len, y);
6225 				i = MIN(i, xcols - y);
6226 				g_buf[i] = '\0';
6227 				addstr(g_buf);
6228 			}
6229 		} else {
6230 			addstr(coolsize(pent->size));
6231 			addch(' ');
6232 			addstr(ptr);
6233 			if (pent->flags & HARD_LINK) {
6234 				struct stat sb;
6235 
6236 				if (stat(pent->name, &sb) != -1) {
6237 					addch(' ');
6238 					addstr(xitoa((int)sb.st_nlink)); /* Show number of links */
6239 					addch('-');
6240 					addstr(xitoa((int)sb.st_ino)); /* Show inode number */
6241 				}
6242 			}
6243 		}
6244 		clrtoeol();
6245 	}
6246 
6247 	attroff(COLOR_PAIR(cfg.curctx + 1));
6248 
6249 	if (cfg.cursormode)
6250 		tocursor();
6251 }
6252 
6253 static inline void markhovered(void)
6254 {
6255 	if (cfg.showdetail && ndents) { /* Reversed block for hovered entry */
6256 		tocursor();
6257 #ifdef ICONS_ENABLED
6258 		addstr(MD_ARROW_FORWARD);
6259 #else
6260 		addch(' ' | A_REVERSE);
6261 #endif
6262 	}
6263 }
6264 
6265 static int adjust_cols(int n)
6266 {
6267 	/* Calculate the number of cols available to print entry name */
6268 #ifdef ICONS_ENABLED
6269 	n -= (g_state.oldcolor ? 0 : 1 + xstrlen(ICON_PADDING_LEFT) + xstrlen(ICON_PADDING_RIGHT));
6270 #endif
6271 	if (cfg.showdetail) {
6272 		/* Fallback to light mode if less than 35 columns */
6273 		if (n < 36)
6274 			cfg.showdetail ^= 1;
6275 		else /* 2 more accounted for below */
6276 			n -= 32;
6277 	}
6278 
6279 	/* 2 columns for preceding space and indicator */
6280 	return (n - 2);
6281 }
6282 
6283 static void draw_line(int ncols)
6284 {
6285 	bool dir = FALSE;
6286 
6287 	ncols = adjust_cols(ncols);
6288 
6289 	if (g_state.oldcolor && (pdents[last].flags & DIR_OR_DIRLNK)) {
6290 		attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6291 		dir = TRUE;
6292 	}
6293 
6294 	move(2 + last - curscroll, 0);
6295 	printent(&pdents[last], ncols, FALSE);
6296 
6297 	if (g_state.oldcolor && (pdents[cur].flags & DIR_OR_DIRLNK)) {
6298 		if (!dir)  {/* First file is not a directory */
6299 			attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6300 			dir = TRUE;
6301 		}
6302 	} else if (dir) { /* Second file is not a directory */
6303 		attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6304 		dir = FALSE;
6305 	}
6306 
6307 	move(2 + cur - curscroll, 0);
6308 	printent(&pdents[cur], ncols, TRUE);
6309 
6310 	/* Must reset e.g. no files in dir */
6311 	if (dir)
6312 		attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6313 
6314 	markhovered();
6315 }
6316 
6317 static void redraw(char *path)
6318 {
6319 	getmaxyx(stdscr, xlines, xcols);
6320 
6321 	int ncols = (xcols <= PATH_MAX) ? xcols : PATH_MAX;
6322 	int onscreen = xlines - 4;
6323 	int i, j = 1;
6324 
6325 	// Fast redraw
6326 	if (g_state.move) {
6327 		g_state.move = 0;
6328 
6329 		if (ndents && (last_curscroll == curscroll))
6330 			return draw_line(ncols);
6331 	}
6332 
6333 	DPRINTF_S(__func__);
6334 
6335 	/* Clear screen */
6336 	erase();
6337 
6338 	/* Enforce scroll/cursor invariants */
6339 	move_cursor(cur, 1);
6340 
6341 	/* Fail redraw if < than 10 columns, context info prints 10 chars */
6342 	if (ncols <= MIN_DISPLAY_COL) {
6343 		printmsg(messages[MSG_FEW_COLUMNS]);
6344 		return;
6345 	}
6346 
6347 	//DPRINTF_D(cur);
6348 	DPRINTF_S(path);
6349 
6350 	for (i = 0; i < CTX_MAX; ++i) { /* 8 chars printed for contexts - "1 2 3 4 " */
6351 		if (!g_ctx[i].c_cfg.ctxactive)
6352 			addch(i + '1');
6353 		else
6354 			addch((i + '1') | (COLOR_PAIR(i + 1) | A_BOLD
6355 				/* active: underline, current: reverse */
6356 				| ((cfg.curctx != i) ? A_UNDERLINE : A_REVERSE)));
6357 
6358 		addch(' ');
6359 	}
6360 
6361 	attron(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6362 
6363 	/* Print path */
6364 	bool in_home = set_tilde_in_path(path);
6365 	char *ptr = in_home ? &path[homelen - 1] : path;
6366 
6367 	i = (int)xstrlen(ptr);
6368 	if ((i + MIN_DISPLAY_COL) <= ncols)
6369 		addnstr(ptr, ncols - MIN_DISPLAY_COL);
6370 	else {
6371 		char *base = xmemrchr((uchar_t *)ptr, '/', i);
6372 
6373 		if (in_home) {
6374 			addch(*ptr);
6375 			++ptr;
6376 			i = 1;
6377 		} else
6378 			i = 0;
6379 
6380 		if (ptr && (base != ptr)) {
6381 			while (ptr < base) {
6382 				if (*ptr == '/') {
6383 					i += 2; /* 2 characters added */
6384 					if (ncols < i + MIN_DISPLAY_COL) {
6385 						base = NULL; /* Can't print more characters */
6386 						break;
6387 					}
6388 
6389 					addch(*ptr);
6390 					addch(*(++ptr));
6391 				}
6392 				++ptr;
6393 			}
6394 		}
6395 
6396 		if (base)
6397 			addnstr(base, ncols - (MIN_DISPLAY_COL + i));
6398 	}
6399 
6400 	if (in_home)
6401 		reset_tilde_in_path(path);
6402 
6403 	attroff(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6404 
6405 	/* Go to first entry */
6406 	if (curscroll > 0) {
6407 		move(1, 0);
6408 #ifdef ICONS_ENABLED
6409 		addstr(MD_ARROW_UPWARD);
6410 #else
6411 		addch('^');
6412 #endif
6413 	}
6414 
6415 	if (g_state.oldcolor) {
6416 		attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6417 		g_state.dircolor = 1;
6418 	}
6419 
6420 	onscreen = MIN(onscreen + curscroll, ndents);
6421 
6422 	ncols = adjust_cols(ncols);
6423 
6424 	int len = scanselforpath(path, FALSE);
6425 
6426 	/* Print listing */
6427 	for (i = curscroll; i < onscreen; ++i) {
6428 		move(++j, 0);
6429 
6430 		if (len)
6431 			findmarkentry(len, &pdents[i]);
6432 
6433 		printent(&pdents[i], ncols, i == cur);
6434 	}
6435 
6436 	/* Must reset e.g. no files in dir */
6437 	if (g_state.dircolor) {
6438 		attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6439 		g_state.dircolor = 0;
6440 	}
6441 
6442 	/* Go to last entry */
6443 	if (onscreen < ndents) {
6444 		move(xlines - 2, 0);
6445 #ifdef ICONS_ENABLED
6446 		addstr(MD_ARROW_DOWNWARD);
6447 #else
6448 		addch('v');
6449 #endif
6450 	}
6451 
6452 	markhovered();
6453 }
6454 
6455 static bool cdprep(char *lastdir, char *lastname, char *path, char *newpath)
6456 {
6457 	if (lastname)
6458 		lastname[0] =  '\0';
6459 
6460 	/* Save last working directory */
6461 	xstrsncpy(lastdir, path, PATH_MAX);
6462 
6463 	/* Save the newly opted dir in path */
6464 	xstrsncpy(path, newpath, PATH_MAX);
6465 	DPRINTF_S(path);
6466 
6467 	clearfilter();
6468 	return cfg.filtermode;
6469 }
6470 
6471 static bool browse(char *ipath, const char *session, int pkey)
6472 {
6473 	char newpath[PATH_MAX] __attribute__ ((aligned)),
6474 	     rundir[PATH_MAX] __attribute__ ((aligned)),
6475 	     runfile[NAME_MAX + 1] __attribute__ ((aligned));
6476 	char *path, *lastdir, *lastname, *dir, *tmp;
6477 	pEntry pent;
6478 	enum action sel;
6479 	struct stat sb;
6480 	int r = -1, presel, selstartid = 0, selendid = 0;
6481 	const uchar_t opener_flags = (cfg.cliopener ? F_CLI : (F_NOTRACE | F_NOSTDIN | F_NOWAIT));
6482 	bool watch = FALSE;
6483 	ino_t inode = 0;
6484 
6485 #ifndef NOMOUSE
6486 	MEVENT event = {0};
6487 	struct timespec mousetimings[2] = {{.tv_sec = 0, .tv_nsec = 0}, {.tv_sec = 0, .tv_nsec = 0} };
6488 	int mousedent[2] = {-1, -1};
6489 	bool currentmouse = 1, rightclicksel = 0;
6490 #endif
6491 
6492 	atexit(dentfree);
6493 
6494 	getmaxyx(stdscr, xlines, xcols);
6495 
6496 #ifndef NOSSN
6497 	/* set-up first context */
6498 	if (!session || !load_session(session, &path, &lastdir, &lastname, FALSE)) {
6499 #else
6500 		(void)session;
6501 #endif
6502 		g_ctx[0].c_last[0] = '\0';
6503 		lastdir = g_ctx[0].c_last; /* last visited directory */
6504 
6505 		if (g_state.initfile) {
6506 			xstrsncpy(g_ctx[0].c_name, xbasename(ipath), sizeof(g_ctx[0].c_name));
6507 			xdirname(ipath);
6508 		} else
6509 			g_ctx[0].c_name[0] = '\0';
6510 
6511 		lastname = g_ctx[0].c_name; /* last visited file name */
6512 
6513 		xstrsncpy(g_ctx[0].c_path, ipath, PATH_MAX);
6514 		/* If the initial path is a file, retain a way to return to start dir */
6515 		if (g_state.initfile) {
6516 			free(initpath);
6517 			initpath = ipath = getcwd(NULL, 0);
6518 		}
6519 		path = g_ctx[0].c_path; /* current directory */
6520 
6521 		g_ctx[0].c_fltr[0] = g_ctx[0].c_fltr[1] = '\0';
6522 		g_ctx[0].c_cfg = cfg; /* current configuration */
6523 #ifndef NOSSN
6524 	}
6525 #endif
6526 
6527 	newpath[0] = rundir[0] = runfile[0] = '\0';
6528 
6529 	presel = pkey ? ';' : ((cfg.filtermode
6530 			|| (session && (g_ctx[cfg.curctx].c_fltr[0] == FILTER
6531 				|| g_ctx[cfg.curctx].c_fltr[0] == RFILTER)
6532 				&& g_ctx[cfg.curctx].c_fltr[1])) ? FILTER : 0);
6533 
6534 	pdents = xrealloc(pdents, total_dents * sizeof(struct entry));
6535 	if (!pdents)
6536 		errexit();
6537 
6538 	/* Allocate buffer to hold names */
6539 	pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
6540 	if (!pnamebuf)
6541 		errexit();
6542 
6543 begin:
6544 	/*
6545 	 * Can fail when permissions change while browsing.
6546 	 * It's assumed that path IS a directory when we are here.
6547 	 */
6548 	if (chdir(path) == -1) {
6549 		DPRINTF_S("directory inaccessible");
6550 		valid_parent(path, lastname);
6551 		setdirwatch();
6552 	}
6553 
6554 #ifndef NOX11
6555 	if (cfg.x11 && !g_state.picker) {
6556 		/* Signal CWD change to terminal */
6557 		printf("\033]7;file://%s%s\033\\", hostname, path);
6558 
6559 		/* Set terminal window title */
6560 		r = set_tilde_in_path(path);
6561 
6562 		printf("\033]2;%s\007", r ? &path[homelen - 1] : path);
6563 		fflush(stdout);
6564 
6565 		if (r)
6566 			reset_tilde_in_path(path);
6567 	}
6568 #endif
6569 
6570 #ifdef LINUX_INOTIFY
6571 	if ((presel == FILTER || watch) && inotify_wd >= 0) {
6572 		inotify_rm_watch(inotify_fd, inotify_wd);
6573 		inotify_wd = -1;
6574 		watch = FALSE;
6575 	}
6576 #elif defined(BSD_KQUEUE)
6577 	if ((presel == FILTER || watch) && event_fd >= 0) {
6578 		close(event_fd);
6579 		event_fd = -1;
6580 		watch = FALSE;
6581 	}
6582 #elif defined(HAIKU_NM)
6583 	if ((presel == FILTER || watch) && haiku_hnd != NULL) {
6584 		haiku_stop_watch(haiku_hnd);
6585 		haiku_nm_active = FALSE;
6586 		watch = FALSE;
6587 	}
6588 #endif
6589 
6590 	if (order) {
6591 		if (cfgsort[cfg.curctx] != '0') {
6592 			if (cfgsort[cfg.curctx] == 'z')
6593 				set_sort_flags('c');
6594 			if ((!cfgsort[cfg.curctx] || (cfgsort[cfg.curctx] == 'c'))
6595 			    && ((r = get_kv_key(order, path, maxorder, NNN_ORDER)) > 0)) {
6596 				set_sort_flags(r);
6597 				cfgsort[cfg.curctx] = 'z';
6598 			}
6599 		} else
6600 			cfgsort[cfg.curctx] = cfgsort[CTX_MAX];
6601 	}
6602 
6603 	populate(path, lastname);
6604 	if (g_state.interrupt) {
6605 		g_state.interrupt = cfg.apparentsz = cfg.blkorder = 0;
6606 		blk_shift = BLK_SHIFT_512;
6607 		presel = CONTROL('L');
6608 	}
6609 
6610 #ifdef LINUX_INOTIFY
6611 	if (presel != FILTER && inotify_wd == -1)
6612 		inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
6613 #elif defined(BSD_KQUEUE)
6614 	if (presel != FILTER && event_fd == -1) {
6615 #if defined(O_EVTONLY)
6616 		event_fd = open(path, O_EVTONLY);
6617 #else
6618 		event_fd = open(path, O_RDONLY);
6619 #endif
6620 		if (event_fd >= 0)
6621 			EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
6622 			       EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
6623 	}
6624 #elif defined(HAIKU_NM)
6625 	haiku_nm_active = haiku_watch_dir(haiku_hnd, path) == EXIT_SUCCESS;
6626 #endif
6627 
6628 	while (1) {
6629 		/* Do not do a double redraw in filterentries */
6630 		if ((presel != FILTER) || !filterset()) {
6631 			redraw(path);
6632 			statusbar(path);
6633 		}
6634 
6635 nochange:
6636 		/* Exit if parent has exited */
6637 		if (getppid() == 1)
6638 			_exit(EXIT_FAILURE);
6639 
6640 		/* If CWD is deleted or moved or perms changed, find an accessible parent */
6641 		if (chdir(path) == -1)
6642 			goto begin;
6643 
6644 		/* If STDIN is no longer a tty (closed) we should exit */
6645 		if (!isatty(STDIN_FILENO) && !g_state.picker)
6646 			return EXIT_FAILURE;
6647 
6648 		sel = nextsel(presel);
6649 		if (presel)
6650 			presel = 0;
6651 
6652 		switch (sel) {
6653 #ifndef NOMOUSE
6654 		case SEL_CLICK:
6655 			if (getmouse(&event) != OK)
6656 				goto nochange;
6657 
6658 			/* Handle clicking on a context at the top */
6659 			if (event.bstate == BUTTON1_PRESSED && event.y == 0) {
6660 				/* Get context from: "[1 2 3 4]..." */
6661 				r = event.x >> 1;
6662 
6663 				/* If clicked after contexts, go to parent */
6664 				if (r >= CTX_MAX)
6665 					sel = SEL_BACK;
6666 				else if (r >= 0 && r != cfg.curctx) {
6667 					savecurctx(path, ndents ? pdents[cur].name : NULL, r);
6668 
6669 					/* Reset the pointers */
6670 					path = g_ctx[r].c_path;
6671 					lastdir = g_ctx[r].c_last;
6672 					lastname = g_ctx[r].c_name;
6673 
6674 					setdirwatch();
6675 					goto begin;
6676 				}
6677 			}
6678 #endif
6679 			// fallthrough
6680 		case SEL_BACK:
6681 #ifndef NOMOUSE
6682 			if (sel == SEL_BACK) {
6683 #endif
6684 				dir = visit_parent(path, newpath, &presel);
6685 				if (!dir)
6686 					goto nochange;
6687 
6688 				/* Save history */
6689 				xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
6690 
6691 				cdprep(lastdir, NULL, path, dir) ? (presel = FILTER) : (watch = TRUE);
6692 				goto begin;
6693 #ifndef NOMOUSE
6694 			}
6695 #endif
6696 
6697 #ifndef NOMOUSE
6698 			/* Middle click action */
6699 			if (event.bstate == BUTTON2_PRESSED) {
6700 				presel = middle_click_key;
6701 				goto nochange;
6702 			}
6703 #if NCURSES_MOUSE_VERSION > 1
6704 			/* Scroll up */
6705 			if (event.bstate == BUTTON4_PRESSED && ndents && (cfg.rollover || cur)) {
6706 				move_cursor((!cfg.rollover && cur < scroll_lines
6707 						? 0 : (cur + ndents - scroll_lines) % ndents), 0);
6708 				break;
6709 			}
6710 
6711 			/* Scroll down */
6712 			if (event.bstate == BUTTON5_PRESSED && ndents
6713 			    && (cfg.rollover || (cur != ndents - 1))) {
6714 				if (!cfg.rollover && cur >= ndents - scroll_lines)
6715 					move_cursor(ndents-1, 0);
6716 				else
6717 					move_cursor((cur + scroll_lines) % ndents, 0);
6718 				break;
6719 			}
6720 #endif
6721 
6722 			/* Toggle filter mode on left click on last 2 lines */
6723 			if (event.y >= xlines - 2 && event.bstate == BUTTON1_PRESSED) {
6724 				clearfilter();
6725 				cfg.filtermode ^= 1;
6726 				if (cfg.filtermode) {
6727 					presel = FILTER;
6728 					goto nochange;
6729 				}
6730 
6731 				/* Start watching the directory */
6732 				watch = TRUE;
6733 				copycurname();
6734 				goto begin;
6735 			}
6736 
6737 			/* Handle clicking on a file */
6738 			if (event.y >= 2 && event.y <= ndents + 1 &&
6739 					(event.bstate == BUTTON1_PRESSED ||
6740 					 event.bstate == BUTTON3_PRESSED)) {
6741 				r = curscroll + (event.y - 2);
6742 				if (r != cur)
6743 					move_cursor(r, 1);
6744 #ifndef NOFIFO
6745 				else if ((event.bstate == BUTTON1_PRESSED) && !g_state.fifomode)
6746 					notify_fifo(TRUE); /* Send clicked path to NNN_FIFO */
6747 #endif
6748 				/* Handle right click selection */
6749 				if (event.bstate == BUTTON3_PRESSED) {
6750 					rightclicksel = 1;
6751 					presel = SELECT;
6752 					goto nochange;
6753 				}
6754 
6755 				currentmouse ^= 1;
6756 				clock_gettime(
6757 #if defined(CLOCK_MONOTONIC_RAW)
6758 				    CLOCK_MONOTONIC_RAW,
6759 #elif defined(CLOCK_MONOTONIC)
6760 				    CLOCK_MONOTONIC,
6761 #else
6762 				    CLOCK_REALTIME,
6763 #endif
6764 				    &mousetimings[currentmouse]);
6765 				mousedent[currentmouse] = cur;
6766 
6767 				/* Single click just selects, double click falls through to SEL_OPEN */
6768 				if ((mousedent[0] != mousedent[1]) ||
6769 				  (((_ABSSUB(mousetimings[0].tv_sec, mousetimings[1].tv_sec) << 30)
6770 				  + (_ABSSUB(mousetimings[0].tv_nsec, mousetimings[1].tv_nsec)))
6771 					> DBLCLK_INTERVAL_NS))
6772 					break;
6773 				mousetimings[currentmouse].tv_sec = 0;
6774 				mousedent[currentmouse] = -1;
6775 			} else {
6776 				if (cfg.filtermode || filterset())
6777 					presel = FILTER;
6778 				copycurname();
6779 				goto nochange;
6780 			}
6781 #endif
6782 			// fallthrough
6783 		case SEL_NAV_IN: // fallthrough
6784 		case SEL_OPEN:
6785 			/* Cannot descend in empty directories */
6786 			if (!ndents)
6787 				goto begin;
6788 
6789 			pent = &pdents[cur];
6790 			mkpath(path, pent->name, newpath);
6791 			DPRINTF_S(newpath);
6792 
6793 			/* Visit directory */
6794 			if (pent->flags & DIR_OR_DIRLNK) {
6795 				if (chdir(newpath) == -1) {
6796 					printwarn(&presel);
6797 					goto nochange;
6798 				}
6799 
6800 				cdprep(lastdir, lastname, path, newpath)
6801 					? (presel = FILTER) : (watch = TRUE);
6802 				goto begin;
6803 			}
6804 
6805 			/* Cannot use stale data in entry, file may be missing by now */
6806 			if (stat(newpath, &sb) == -1) {
6807 				printwarn(&presel);
6808 				goto nochange;
6809 			}
6810 			DPRINTF_U(sb.st_mode);
6811 
6812 			/* Do not open non-regular files */
6813 			if (!S_ISREG(sb.st_mode)) {
6814 				printwait(messages[MSG_UNSUPPORTED], &presel);
6815 				goto nochange;
6816                         }
6817 #ifndef NOFIFO
6818 			if (g_state.fifomode && (sel == SEL_OPEN)) {
6819 				notify_fifo(TRUE); /* Send opened path to NNN_FIFO */
6820 				goto nochange;
6821 			}
6822 #endif
6823 			/* If opened as vim plugin and Enter/^M pressed, pick */
6824 			if (g_state.picker && (sel == SEL_OPEN)) {
6825 				if (!(pdents[cur].flags & FILE_SELECTED))
6826 					appendfpath(newpath, mkpath(path, pent->name, newpath));
6827 				return EXIT_SUCCESS;
6828 			}
6829 
6830 			if (sel == SEL_NAV_IN) {
6831 				/* If in listing dir, go to target on `l` or Right on symlink */
6832 				if (listpath && S_ISLNK(pent->mode)
6833 				    && is_prefix(path, listpath, xstrlen(listpath))) {
6834 					if (!realpath(pent->name, newpath)) {
6835 						printwarn(&presel);
6836 						goto nochange;
6837 					}
6838 
6839 					xdirname(newpath);
6840 
6841 					if (chdir(newpath) == -1) {
6842 						printwarn(&presel);
6843 						goto nochange;
6844 					}
6845 
6846 					cdprep(lastdir, NULL, path, newpath)
6847 					       ? (presel = FILTER) : (watch = TRUE);
6848 					xstrsncpy(lastname, pent->name, NAME_MAX + 1);
6849 					goto begin;
6850 				}
6851 
6852 				/* Open file disabled on right arrow or `l` */
6853 				if (cfg.nonavopen)
6854 					goto nochange;
6855 			}
6856 
6857 			/* Handle plugin selection mode */
6858 			if (g_state.runplugin) {
6859 				g_state.runplugin = 0;
6860 				/* Must be in plugin dir and same context to select plugin */
6861 				if ((g_state.runctx == cfg.curctx) && !strcmp(path, plgpath)) {
6862 					endselection(FALSE);
6863 					/* Copy path so we can return back to earlier dir */
6864 					xstrsncpy(path, rundir, PATH_MAX);
6865 					rundir[0] = '\0';
6866 					clearfilter();
6867 
6868 					if (chdir(path) == -1
6869 					    || !run_plugin(&path, pent->name,
6870 								    runfile, &lastname, &lastdir)) {
6871 						DPRINTF_S("plugin failed!");
6872 					}
6873 
6874 					if (g_state.picked)
6875 						return EXIT_SUCCESS;
6876 
6877 					if (runfile[0]) {
6878 						xstrsncpy(lastname, runfile, NAME_MAX + 1);
6879 						runfile[0] = '\0';
6880 					}
6881 					setdirwatch();
6882 					goto begin;
6883 				}
6884 			}
6885 
6886 			if (!sb.st_size) {
6887 				printwait(messages[MSG_EMPTY_FILE], &presel);
6888 				goto nochange;
6889 			}
6890 
6891 			if (cfg.useeditor
6892 #ifdef FILE_MIME_OPTS
6893 			    && get_output("file", FILE_MIME_OPTS, newpath, -1, FALSE, FALSE)
6894 			    && is_prefix(g_buf, "text/", 5)
6895 #else
6896 			    /* no MIME option; guess from description instead */
6897 			    && get_output("file", "-bL", newpath, -1, FALSE, FALSE)
6898 			    && strstr(g_buf, "text")
6899 #endif
6900 			) {
6901 				spawn(editor, newpath, NULL, NULL, F_CLI);
6902 				if (cfg.filtermode) {
6903 					presel = FILTER;
6904 					clearfilter();
6905 				}
6906 				continue;
6907 			}
6908 
6909 			/* Get the extension for regex match */
6910 			tmp = xextension(pent->name, pent->nlen - 1);
6911 #ifdef PCRE
6912 			if (tmp && !pcre_exec(archive_pcre, NULL, tmp,
6913 					      pent->nlen - (tmp - pent->name) - 1, 0, 0, NULL, 0)) {
6914 #else
6915 			if (tmp && !regexec(&archive_re, tmp, 0, NULL, 0)) {
6916 #endif
6917 				r = get_input(messages[MSG_ARCHIVE_OPTS]);
6918 				if (r == 'l' || r == 'x') {
6919 					mkpath(path, pent->name, newpath);
6920 					if (!handle_archive(newpath, r)) {
6921 						presel = MSGWAIT;
6922 						goto nochange;
6923 					}
6924 					if (r == 'l') {
6925 						statusbar(path);
6926 						goto nochange;
6927 					}
6928 				}
6929 
6930 				if ((r == 'm') && !archive_mount(newpath)) {
6931 					presel = MSGWAIT;
6932 					goto nochange;
6933 				}
6934 
6935 				if (r == 'x' || r == 'm') {
6936 					if (newpath[0])
6937 						set_smart_ctx('+', newpath, &path,
6938 							      ndents ? pdents[cur].name : NULL,
6939 							      &lastname, &lastdir);
6940 					else
6941 						copycurname();
6942 					clearfilter();
6943 					goto begin;
6944 				}
6945 
6946 				if (r != 'o') {
6947 					printwait(messages[MSG_INVALID_KEY], &presel);
6948 					goto nochange;
6949 				}
6950 			}
6951 
6952 			/* Invoke desktop opener as last resort */
6953 			spawn(opener, newpath, NULL, NULL, opener_flags);
6954 
6955 			/* Move cursor to the next entry if not the last entry */
6956 			if (g_state.autonext && cur != ndents - 1)
6957 				move_cursor((cur + 1) % ndents, 0);
6958 			if (cfg.filtermode) {
6959 				presel = FILTER;
6960 				clearfilter();
6961 			}
6962 			continue;
6963 		case SEL_NEXT: // fallthrough
6964 		case SEL_PREV: // fallthrough
6965 		case SEL_PGDN: // fallthrough
6966 		case SEL_CTRL_D: // fallthrough
6967 		case SEL_PGUP: // fallthrough
6968 		case SEL_CTRL_U: // fallthrough
6969 		case SEL_HOME: // fallthrough
6970 		case SEL_END: // fallthrough
6971 		case SEL_FIRST:
6972 			if (ndents) {
6973 				g_state.move = 1;
6974 				handle_screen_move(sel);
6975 			}
6976 			break;
6977 		case SEL_CDHOME: // fallthrough
6978 		case SEL_CDBEGIN: // fallthrough
6979 		case SEL_CDLAST: // fallthrough
6980 		case SEL_CDROOT:
6981 			dir = (sel == SEL_CDHOME) ? home
6982 				: ((sel == SEL_CDBEGIN) ? ipath
6983 				: ((sel == SEL_CDLAST) ? lastdir
6984 				: "/" /* SEL_CDROOT */));
6985 
6986 			if (!dir || !*dir) {
6987 				printwait(messages[MSG_NOT_SET], &presel);
6988 				goto nochange;
6989 			}
6990 
6991 			if (strcmp(path, dir) == 0) {
6992 				if (dir == ipath) {
6993 					if (cfg.filtermode)
6994 						presel = FILTER;
6995 					goto nochange;
6996 				}
6997 				dir = lastdir; /* Go to last dir on home/root key repeat */
6998 			}
6999 
7000 			if (chdir(dir) == -1) {
7001 				presel = MSGWAIT;
7002 				goto nochange;
7003 			}
7004 
7005 			/* SEL_CDLAST: dir pointing to lastdir */
7006 			xstrsncpy(newpath, dir, PATH_MAX); // fallthrough
7007 		case SEL_BMOPEN:
7008 			if (sel == SEL_BMOPEN) {
7009 				r = (int)handle_bookmark(mark, newpath);
7010 				if (r) {
7011 					printwait(messages[r], &presel);
7012 					goto nochange;
7013 				}
7014 
7015 				if (strcmp(path, newpath) == 0)
7016 					break;
7017 			}
7018 
7019 			/* In list mode, retain the last file name to highlight it, if possible */
7020 			cdprep(lastdir, listpath && sel == SEL_CDLAST ? NULL : lastname, path, newpath)
7021 			       ? (presel = FILTER) : (watch = TRUE);
7022 			goto begin;
7023 		case SEL_REMOTE:
7024 			if ((sel == SEL_REMOTE) && !remote_mount(newpath)) {
7025 				presel = MSGWAIT;
7026 				goto nochange;
7027 			}
7028 
7029 			set_smart_ctx('+', newpath, &path,
7030 				      ndents ? pdents[cur].name : NULL, &lastname, &lastdir);
7031 			clearfilter();
7032 			goto begin;
7033 		case SEL_CYCLE: // fallthrough
7034 		case SEL_CYCLER: // fallthrough
7035 		case SEL_CTX1: // fallthrough
7036 		case SEL_CTX2: // fallthrough
7037 		case SEL_CTX3: // fallthrough
7038 		case SEL_CTX4:
7039 #ifdef CTX8
7040 		case SEL_CTX5:
7041 		case SEL_CTX6:
7042 		case SEL_CTX7:
7043 		case SEL_CTX8:
7044 #endif
7045 			r = handle_context_switch(sel);
7046 			if (r < 0)
7047 				continue;
7048 			savecurctx(path, ndents ? pdents[cur].name : NULL, r);
7049 
7050 			/* Reset the pointers */
7051 			path = g_ctx[r].c_path;
7052 			lastdir = g_ctx[r].c_last;
7053 			lastname = g_ctx[r].c_name;
7054 			tmp = g_ctx[r].c_fltr;
7055 
7056 			if (cfg.filtermode || ((tmp[0] == FILTER || tmp[0] == RFILTER) && tmp[1]))
7057 				presel = FILTER;
7058 			else
7059 				watch = TRUE;
7060 
7061 			goto begin;
7062 		case SEL_MARK:
7063 			free(mark);
7064 			mark = xstrdup(path);
7065 			printwait(mark, &presel);
7066 			goto nochange;
7067 		case SEL_BMARK:
7068 			add_bookmark(path, newpath, &presel);
7069 			goto nochange;
7070 		case SEL_FLTR:
7071 			if (!ndents)
7072 				goto nochange;
7073 			/* Unwatch dir if we are still in a filtered view */
7074 #ifdef LINUX_INOTIFY
7075 			if (inotify_wd >= 0) {
7076 				inotify_rm_watch(inotify_fd, inotify_wd);
7077 				inotify_wd = -1;
7078 			}
7079 #elif defined(BSD_KQUEUE)
7080 			if (event_fd >= 0) {
7081 				close(event_fd);
7082 				event_fd = -1;
7083 			}
7084 #elif defined(HAIKU_NM)
7085 			if (haiku_nm_active) {
7086 				haiku_stop_watch(haiku_hnd);
7087 				haiku_nm_active = FALSE;
7088 			}
7089 #endif
7090 			presel = filterentries(path, lastname);
7091 			if (presel == ESC) {
7092 				presel = 0;
7093 				break;
7094 			}
7095 			if (presel == FILTER) /* Refresh dir and filter again */
7096 				goto begin;
7097 			goto nochange;
7098 		case SEL_MFLTR: // fallthrough
7099 		case SEL_HIDDEN: // fallthrough
7100 		case SEL_DETAIL: // fallthrough
7101 		case SEL_SORT:
7102 			switch (sel) {
7103 			case SEL_MFLTR:
7104 				cfg.filtermode ^= 1;
7105 				if (cfg.filtermode) {
7106 					presel = FILTER;
7107 					clearfilter();
7108 					goto nochange;
7109 				}
7110 
7111 				watch = TRUE; // fallthrough
7112 			case SEL_HIDDEN:
7113 				if (sel == SEL_HIDDEN) {
7114 					cfg.showhidden ^= 1;
7115 					if (cfg.filtermode)
7116 						presel = FILTER;
7117 					clearfilter();
7118 				}
7119 				copycurname();
7120 				goto begin;
7121 			case SEL_DETAIL:
7122 				cfg.showdetail ^= 1;
7123 				cfg.blkorder = 0;
7124 				continue;
7125 			default: /* SEL_SORT */
7126 				r = set_sort_flags(get_input(messages[MSG_ORDER]));
7127 				if (!r) {
7128 					printwait(messages[MSG_INVALID_KEY], &presel);
7129 					goto nochange;
7130 				}
7131 			}
7132 
7133 			if (cfg.filtermode || filterset())
7134 				presel = FILTER;
7135 
7136 			if (ndents) {
7137 				copycurname();
7138 
7139 				if (r == 'd' || r == 'a') {
7140 					presel = 0;
7141 					goto begin;
7142 				}
7143 
7144 				ENTSORT(pdents, ndents, entrycmpfn);
7145 				move_cursor(ndents ? dentfind(lastname, ndents) : 0, 0);
7146 			}
7147 			continue;
7148 		case SEL_STATS: // fallthrough
7149 		case SEL_CHMODX:
7150 			if (ndents) {
7151 				tmp = (listpath && xstrcmp(path, listpath) == 0) ? listroot : path;
7152 				mkpath(tmp, pdents[cur].name, newpath);
7153 
7154 				if ((sel == SEL_STATS && !show_stats(newpath))
7155 				    || (lstat(newpath, &sb) == -1)
7156 				    || (sel == SEL_CHMODX && !xchmod(newpath, sb.st_mode))) {
7157 					printwarn(&presel);
7158 					goto nochange;
7159 				}
7160 
7161 				if (sel == SEL_CHMODX)
7162 					pdents[cur].mode ^= 0111;
7163 			}
7164 			break;
7165 		case SEL_REDRAW: // fallthrough
7166 		case SEL_RENAMEMUL: // fallthrough
7167 		case SEL_HELP: // fallthrough
7168 		case SEL_AUTONEXT: // fallthrough
7169 		case SEL_EDIT: // fallthrough
7170 		case SEL_LOCK:
7171 		{
7172 			bool refresh = FALSE;
7173 
7174 			if (ndents)
7175 				mkpath(path, pdents[cur].name, newpath);
7176 			else if (sel == SEL_EDIT) /* Avoid trying to edit a non-existing file */
7177 				goto nochange;
7178 
7179 			switch (sel) {
7180 			case SEL_REDRAW:
7181 				refresh = TRUE;
7182 				break;
7183 			case SEL_RENAMEMUL:
7184 				endselection(TRUE);
7185 				setenv("INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
7186 
7187 				if (!(getutil(utils[UTIL_BASH])
7188 				      && plugscript(utils[UTIL_NMV], F_CLI))
7189 #ifndef NOBATCH
7190 				    && !batch_rename()
7191 #endif
7192 				) {
7193 					printwait(messages[MSG_FAILED], &presel);
7194 					goto nochange;
7195 				}
7196 				clearselection();
7197 				refresh = TRUE;
7198 				break;
7199 			case SEL_HELP:
7200 				show_help(path); // fallthrough
7201 			case SEL_AUTONEXT:
7202 				if (sel == SEL_AUTONEXT)
7203 					g_state.autonext ^= 1;
7204 				if (cfg.filtermode)
7205 					presel = FILTER;
7206 				copycurname();
7207 				goto nochange;
7208 			case SEL_EDIT:
7209 				spawn(editor, newpath, NULL, NULL, F_CLI);
7210 				continue;
7211 			default: /* SEL_LOCK */
7212 				lock_terminal();
7213 				break;
7214 			}
7215 
7216 			/* In case of successful operation, reload contents */
7217 
7218 			/* Continue in type-to-nav mode, if enabled */
7219 			if ((cfg.filtermode || filterset()) && !refresh) {
7220 				presel = FILTER;
7221 				goto nochange;
7222 			}
7223 
7224 			/* Save current */
7225 			copycurname();
7226 			/* Repopulate as directory content may have changed */
7227 			goto begin;
7228 		}
7229 		case SEL_SEL:
7230 			if (!ndents)
7231 				goto nochange;
7232 
7233 			startselection();
7234 			if (g_state.rangesel)
7235 				g_state.rangesel = 0;
7236 
7237 			/* Toggle selection status */
7238 			pdents[cur].flags ^= FILE_SELECTED;
7239 
7240 			if (pdents[cur].flags & FILE_SELECTED) {
7241 				++nselected;
7242 				appendfpath(newpath, mkpath(path, pdents[cur].name, newpath));
7243 				writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
7244 			} else {
7245 				--nselected;
7246 				rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
7247 			}
7248 
7249 #ifndef NOX11
7250 			if (cfg.x11)
7251 				plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7252 #endif
7253 #ifndef NOMOUSE
7254 			if (rightclicksel)
7255 				rightclicksel = 0;
7256 			else
7257 #endif
7258 				/* move cursor to the next entry if this is not the last entry */
7259 				if (!g_state.stayonsel && !g_state.picker && cur != ndents - 1)
7260 					move_cursor((cur + 1) % ndents, 0);
7261 			break;
7262 		case SEL_SELMUL:
7263 			if (!ndents)
7264 				goto nochange;
7265 
7266 			startselection();
7267 			g_state.rangesel ^= 1;
7268 
7269 			if (stat(path, &sb) == -1) {
7270 				printwarn(&presel);
7271 				goto nochange;
7272 			}
7273 
7274 			if (g_state.rangesel) { /* Range selection started */
7275 				inode = sb.st_ino;
7276 				selstartid = cur;
7277 				continue;
7278 			}
7279 
7280 			if (inode != sb.st_ino) {
7281 				printwait(messages[MSG_DIR_CHANGED], &presel);
7282 				goto nochange;
7283 			}
7284 
7285 			if (cur < selstartid) {
7286 				selendid = selstartid;
7287 				selstartid = cur;
7288 			} else
7289 				selendid = cur;
7290 
7291 			/* Clear selection on repeat on same file */
7292 			if (selstartid == selendid) {
7293 				resetselind();
7294 				clearselection();
7295 				break;
7296 			} // fallthrough
7297 		case SEL_SELALL: // fallthrough
7298 		case SEL_SELINV:
7299 			if (sel == SEL_SELALL || sel == SEL_SELINV) {
7300 				if (!ndents)
7301 					goto nochange;
7302 
7303 				startselection();
7304 				if (g_state.rangesel)
7305 					g_state.rangesel = 0;
7306 
7307 				selstartid = 0;
7308 				selendid = ndents - 1;
7309 			}
7310 
7311 			if ((nselected > LARGESEL) || (nselected && (ndents > LARGESEL))) {
7312 				printmsg("processing...");
7313 				refresh();
7314 			}
7315 
7316 			r = scanselforpath(path, TRUE); /* Get path length suffixed by '/' */
7317 			((sel == SEL_SELINV) && findselpos)
7318 				? invertselbuf(r) : addtoselbuf(r, selstartid, selendid);
7319 
7320 #ifndef NOX11
7321 			if (cfg.x11)
7322 				plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7323 #endif
7324 			continue;
7325 		case SEL_SELEDIT:
7326 			r = editselection();
7327 			if (r <= 0) {
7328 				r = !r ? MSG_0_SELECTED : MSG_FAILED;
7329 				printwait(messages[r], &presel);
7330 			} else {
7331 #ifndef NOX11
7332 				if (cfg.x11)
7333 					plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7334 #endif
7335 				cfg.filtermode ?  presel = FILTER : statusbar(path);
7336 			}
7337 			goto nochange;
7338 		case SEL_CP: // fallthrough
7339 		case SEL_MV: // fallthrough
7340 		case SEL_CPMVAS: // fallthrough
7341 		case SEL_RM:
7342 		{
7343 			if (sel == SEL_RM) {
7344 				r = get_cur_or_sel();
7345 				if (!r) {
7346 					statusbar(path);
7347 					goto nochange;
7348 				}
7349 
7350 				if (r == 'c') {
7351 					tmp = (listpath && xstrcmp(path, listpath) == 0)
7352 					      ? listroot : path;
7353 					mkpath(tmp, pdents[cur].name, newpath);
7354 					if (!xrm(newpath))
7355 						continue;
7356 
7357 					xrmfromsel(tmp, newpath);
7358 
7359 					copynextname(lastname);
7360 
7361 					if (cfg.filtermode || filterset())
7362 						presel = FILTER;
7363 					goto begin;
7364 				}
7365 			}
7366 
7367 			(nselected == 1 && (sel == SEL_CP || sel == SEL_MV))
7368 				? mkpath(path, xbasename(pselbuf), newpath)
7369 				: (newpath[0] = '\0');
7370 
7371 			endselection(TRUE);
7372 
7373 			if (!cpmvrm_selection(sel, path)) {
7374 				presel = MSGWAIT;
7375 				goto nochange;
7376 			}
7377 
7378 			if (cfg.filtermode)
7379 				presel = FILTER;
7380 			clearfilter();
7381 
7382 #ifndef NOX11
7383 			/* Show notification on operation complete */
7384 			if (cfg.x11)
7385 				plugscript(utils[UTIL_NTFY], F_NOWAIT | F_NOTRACE);
7386 #endif
7387 
7388 			if (newpath[0] && !access(newpath, F_OK))
7389 				xstrsncpy(lastname, xbasename(newpath), NAME_MAX+1);
7390 			else
7391 				copycurname();
7392 			goto begin;
7393 		}
7394 		case SEL_ARCHIVE: // fallthrough
7395 		case SEL_OPENWITH: // fallthrough
7396 		case SEL_NEW: // fallthrough
7397 		case SEL_RENAME:
7398 		{
7399 			int fd, ret = 'n';
7400 
7401 			if (!ndents && (sel == SEL_OPENWITH || sel == SEL_RENAME))
7402 				break;
7403 
7404 			if (sel != SEL_OPENWITH)
7405 				endselection(TRUE);
7406 
7407 			switch (sel) {
7408 			case SEL_ARCHIVE:
7409 				r = get_cur_or_sel();
7410 				if (!r) {
7411 					statusbar(path);
7412 					goto nochange;
7413 				}
7414 
7415 				if (r == 's') {
7416 					if (!selsafe()) {
7417 						presel = MSGWAIT;
7418 						goto nochange;
7419 					}
7420 
7421 					tmp = NULL;
7422 				} else
7423 					tmp = pdents[cur].name;
7424 
7425 				tmp = xreadline(tmp, messages[MSG_ARCHIVE_NAME]);
7426 				break;
7427 			case SEL_OPENWITH:
7428 #ifdef NORL
7429 				tmp = xreadline(NULL, messages[MSG_OPEN_WITH]);
7430 #else
7431 				tmp = getreadline(messages[MSG_OPEN_WITH]);
7432 #endif
7433 				break;
7434 			case SEL_NEW:
7435 				r = get_input(messages[MSG_NEW_OPTS]);
7436 				if (r == 'f' || r == 'd')
7437 					tmp = xreadline(NULL, messages[MSG_NEW_PATH]);
7438 				else if (r == 's' || r == 'h')
7439 					tmp = xreadline(NULL, messages[MSG_LINK_PREFIX]);
7440 				else
7441 					tmp = NULL;
7442 				break;
7443 			default: /* SEL_RENAME */
7444 				tmp = xreadline(pdents[cur].name, "");
7445 				break;
7446 			}
7447 
7448 			if (!tmp || !*tmp)
7449 				break;
7450 
7451 			switch (sel) {
7452 			case SEL_ARCHIVE:
7453 				if (r == 'c' && strcmp(tmp, pdents[cur].name) == 0)
7454 					goto nochange;
7455 
7456 				mkpath(path, tmp, newpath);
7457 				if (access(newpath, F_OK) == 0) {
7458 					if (!xconfirm(get_input(messages[MSG_OVERWRITE]))) {
7459 						statusbar(path);
7460 						goto nochange;
7461 					}
7462 				}
7463 				get_archive_cmd(newpath, tmp);
7464 				(r == 's') ? archive_selection(newpath, tmp, path)
7465 					   : spawn(newpath, tmp, pdents[cur].name,
7466 						   NULL, F_CLI | F_CONFIRM);
7467 
7468 				mkpath(path, tmp, newpath);
7469 				if (access(newpath, F_OK) == 0) { /* File created */
7470 					xstrsncpy(lastname, tmp, NAME_MAX + 1);
7471 					clearfilter(); /* Archive name may not match */
7472 					clearselection(); /* Archive operation complete */
7473 					goto begin;
7474 				}
7475 				continue;
7476 			case SEL_OPENWITH:
7477 				handle_openwith(path, pdents[cur].name, newpath, tmp);
7478 
7479 				cfg.filtermode ?  presel = FILTER : statusbar(path);
7480 				copycurname();
7481 				goto nochange;
7482 			case SEL_RENAME:
7483 				/* Skip renaming to same name */
7484 				if (strcmp(tmp, pdents[cur].name) == 0) {
7485 					tmp = xreadline(pdents[cur].name, messages[MSG_COPY_NAME]);
7486 					if (!tmp || !tmp[0] || !strcmp(tmp, pdents[cur].name)) {
7487 						cfg.filtermode ?  presel = FILTER : statusbar(path);
7488 						copycurname();
7489 						goto nochange;
7490 					}
7491 					ret = 'd';
7492 				}
7493 				break;
7494 			default: /* SEL_NEW */
7495 				break;
7496 			}
7497 
7498 			/* Open the descriptor to currently open directory */
7499 #ifdef O_DIRECTORY
7500 			fd = open(path, O_RDONLY | O_DIRECTORY);
7501 #else
7502 			fd = open(path, O_RDONLY);
7503 #endif
7504 			if (fd == -1) {
7505 				printwarn(&presel);
7506 				goto nochange;
7507 			}
7508 
7509 			/* Check if another file with same name exists */
7510 			if (fstatat(fd, tmp, &sb, AT_SYMLINK_NOFOLLOW) == 0) {
7511 				if (sel == SEL_RENAME) {
7512 					/* Overwrite file with same name? */
7513 					if (!xconfirm(get_input(messages[MSG_OVERWRITE]))) {
7514 						close(fd);
7515 						break;
7516 					}
7517 				} else {
7518 					/* Do nothing in case of NEW */
7519 					close(fd);
7520 					printwait(messages[MSG_EXISTS], &presel);
7521 					goto nochange;
7522 				}
7523 			}
7524 
7525 			if (sel == SEL_RENAME) {
7526 				/* Rename the file */
7527 				if (ret == 'd')
7528 					spawn("cp -rp", pdents[cur].name, tmp, NULL, F_SILENT);
7529 				else if (renameat(fd, pdents[cur].name, fd, tmp) != 0) {
7530 					close(fd);
7531 					printwarn(&presel);
7532 					goto nochange;
7533 				}
7534 				close(fd);
7535 				xstrsncpy(lastname, tmp, NAME_MAX + 1);
7536 			} else { /* SEL_NEW */
7537 				close(fd);
7538 				presel = 0;
7539 
7540 				/* Check if it's a dir or file */
7541 				if (r == 'f' || r == 'd') {
7542 					mkpath(path, tmp, newpath);
7543 					ret = xmktree(newpath, r == 'f' ? FALSE : TRUE);
7544 				} else if (r == 's' || r == 'h') {
7545 					if (tmp[0] == '@' && tmp[1] == '\0')
7546 						tmp[0] = '\0';
7547 					ret = xlink(tmp, path, (ndents ? pdents[cur].name : NULL),
7548 						  newpath, &presel, r);
7549 				}
7550 
7551 				if (!ret)
7552 					printwait(messages[MSG_FAILED], &presel);
7553 
7554 				if (ret <= 0)
7555 					goto nochange;
7556 
7557 				if (r == 'f' || r == 'd')
7558 					xstrsncpy(lastname, tmp, NAME_MAX + 1);
7559 				else if (ndents) {
7560 					if (cfg.filtermode)
7561 						presel = FILTER;
7562 					copycurname();
7563 				}
7564 				clearfilter();
7565 			}
7566 
7567 			goto begin;
7568 		}
7569 		case SEL_PLUGIN:
7570 			/* Check if directory is accessible */
7571 			if (!xdiraccess(plgpath)) {
7572 				printwarn(&presel);
7573 				goto nochange;
7574 			}
7575 
7576 			if (!pkey) {
7577 				r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
7578 				printkeys(plug, g_buf + r - 1, maxplug);
7579 				printmsg(g_buf);
7580 				r = get_input(NULL);
7581 			} else {
7582 				r = pkey;
7583 				pkey = '\0';
7584 			}
7585 
7586 			if (r != '\r') {
7587 				endselection(FALSE);
7588 				tmp = get_kv_val(plug, NULL, r, maxplug, NNN_PLUG);
7589 				if (!tmp) {
7590 					printwait(messages[MSG_INVALID_KEY], &presel);
7591 					goto nochange;
7592 				}
7593 
7594 				if (tmp[0] == '-' && tmp[1]) {
7595 					++tmp;
7596 					r = FALSE; /* Do not refresh dir after completion */
7597 				} else
7598 					r = TRUE;
7599 
7600 				if (!run_plugin(&path, tmp, (ndents ? pdents[cur].name : NULL),
7601 							 &lastname, &lastdir)) {
7602 					printwait(messages[MSG_FAILED], &presel);
7603 					goto nochange;
7604 				}
7605 
7606 				if (g_state.picked)
7607 					return EXIT_SUCCESS;
7608 
7609 				copycurname();
7610 
7611 				if (!r) {
7612 					cfg.filtermode ? presel = FILTER : statusbar(path);
7613 					goto nochange;
7614 				}
7615 			} else { /* 'Return/Enter' enters the plugin directory */
7616 				g_state.runplugin ^= 1;
7617 				if (!g_state.runplugin && rundir[0]) {
7618 					/*
7619 					 * If toggled, and still in the plugin dir,
7620 					 * switch to original directory
7621 					 */
7622 					if (strcmp(path, plgpath) == 0) {
7623 						xstrsncpy(path, rundir, PATH_MAX);
7624 						xstrsncpy(lastname, runfile, NAME_MAX + 1);
7625 						rundir[0] = runfile[0] = '\0';
7626 						setdirwatch();
7627 						goto begin;
7628 					}
7629 
7630 					/* Otherwise, initiate choosing plugin again */
7631 					g_state.runplugin = 1;
7632 				}
7633 
7634 				xstrsncpy(lastdir, path, PATH_MAX);
7635 				xstrsncpy(rundir, path, PATH_MAX);
7636 				xstrsncpy(path, plgpath, PATH_MAX);
7637 				if (ndents)
7638 					xstrsncpy(runfile, pdents[cur].name, NAME_MAX);
7639 				g_state.runctx = cfg.curctx;
7640 				lastname[0] = '\0';
7641 			}
7642 			setdirwatch();
7643 			clearfilter();
7644 			goto begin;
7645 		case SEL_SHELL: // fallthrough
7646 		case SEL_LAUNCH: // fallthrough
7647 		case SEL_PROMPT:
7648 			r = handle_cmd(sel, newpath);
7649 
7650 			/* Continue in type-to-nav mode, if enabled */
7651 			if (cfg.filtermode)
7652 				presel = FILTER;
7653 
7654 			/* Save current */
7655 			copycurname();
7656 
7657 			if (!r)
7658 				goto nochange;
7659 
7660 			/* Repopulate as directory content may have changed */
7661 			goto begin;
7662 		case SEL_UMOUNT:
7663 			presel = MSG_ZERO;
7664 			if (!unmount((ndents ? pdents[cur].name : NULL), newpath, &presel, path)) {
7665 				if (presel == MSG_ZERO)
7666 					statusbar(path);
7667 				goto nochange;
7668 			}
7669 
7670 			/* Dir removed, go to next entry */
7671 			copynextname(lastname);
7672 			goto begin;
7673 #ifndef NOSSN
7674 		case SEL_SESSIONS:
7675 			r = get_input(messages[MSG_SSN_OPTS]);
7676 
7677 			if (r == 's') {
7678 				tmp = xreadline(NULL, messages[MSG_SSN_NAME]);
7679 				if (tmp && *tmp)
7680 					save_session(tmp, &presel);
7681 			} else if (r == 'l' || r == 'r') {
7682 				if (load_session(NULL, &path, &lastdir, &lastname, r == 'r')) {
7683 					setdirwatch();
7684 					goto begin;
7685 				}
7686 			}
7687 
7688 			statusbar(path);
7689 			goto nochange;
7690 #endif
7691 		case SEL_EXPORT:
7692 			export_file_list();
7693 			cfg.filtermode ?  presel = FILTER : statusbar(path);
7694 			goto nochange;
7695 		case SEL_TIMETYPE:
7696 			if (!set_time_type(&presel))
7697 				goto nochange;
7698 			goto begin;
7699 		case SEL_QUITCTX: // fallthrough
7700 		case SEL_QUITCD: // fallthrough
7701 		case SEL_QUIT:
7702 		case SEL_QUITERR:
7703 			if (sel == SEL_QUITCTX) {
7704 				int ctx = cfg.curctx;
7705 
7706 				for (r = (ctx + 1) & ~CTX_MAX;
7707 				     (r != ctx) && !g_ctx[r].c_cfg.ctxactive;
7708 				     r = ((r + 1) & ~CTX_MAX)) {
7709 				};
7710 
7711 				if (r != ctx) {
7712 					g_ctx[ctx].c_cfg.ctxactive = 0;
7713 
7714 					/* Switch to next active context */
7715 					path = g_ctx[r].c_path;
7716 					lastdir = g_ctx[r].c_last;
7717 					lastname = g_ctx[r].c_name;
7718 
7719 					cfg = g_ctx[r].c_cfg;
7720 
7721 					cfg.curctx = r;
7722 					setdirwatch();
7723 					goto begin;
7724 				}
7725 			} else if (!g_state.forcequit) {
7726 				for (r = 0; r < CTX_MAX; ++r)
7727 					if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
7728 						r = get_input(messages[MSG_QUIT_ALL]);
7729 						break;
7730 					}
7731 
7732 				if (!(r == CTX_MAX || xconfirm(r)))
7733 					break; // fallthrough
7734 			}
7735 
7736 #ifndef NOSSN
7737 			if (session && g_state.prstssn)
7738 				save_session(session, NULL);
7739 #endif
7740 
7741 			/* CD on Quit */
7742 			tmp = getenv("NNN_TMPFILE");
7743 			if ((sel == SEL_QUITCD) || tmp) {
7744 				write_lastdir(path, tmp);
7745 				/* ^G is a way to quit picker mode without picking anything */
7746 				if ((sel == SEL_QUITCD) && g_state.picker)
7747 					selbufpos = 0;
7748 			}
7749 
7750 			if (sel != SEL_QUITERR)
7751 				return EXIT_SUCCESS;
7752 
7753 			if (selbufpos && !g_state.picker) {
7754 				/* Pick files to stdout and exit */
7755 				g_state.picker = 1;
7756 				free(selpath);
7757 				selpath = NULL;
7758 				return EXIT_SUCCESS;
7759 			}
7760 
7761 			return EXIT_FAILURE;
7762 		default:
7763 			if (xlines != LINES || xcols != COLS)
7764 				continue;
7765 
7766 			if (idletimeout && idle == idletimeout) {
7767 				lock_terminal(); /* Locker */
7768 				idle = 0;
7769 			}
7770 
7771 			copycurname();
7772 			goto nochange;
7773 		} /* switch (sel) */
7774 	}
7775 }
7776 
7777 static char *make_tmp_tree(char **paths, ssize_t entries, const char *prefix)
7778 {
7779 	/* tmpdir holds the full path */
7780 	/* tmp holds the path without the tmp dir prefix */
7781 	int err;
7782 	struct stat sb;
7783 	char *slash, *tmp;
7784 	ssize_t len = xstrlen(prefix);
7785 	char *tmpdir = malloc(PATH_MAX);
7786 
7787 	if (!tmpdir) {
7788 		DPRINTF_S(strerror(errno));
7789 		return NULL;
7790 	}
7791 
7792 	tmp = tmpdir + tmpfplen - 1;
7793 	xstrsncpy(tmpdir, g_tmpfpath, tmpfplen);
7794 	xstrsncpy(tmp, "/nnnXXXXXX", 11);
7795 
7796 	/* Points right after the base tmp dir */
7797 	tmp += 10;
7798 
7799 	/* handle the case where files are directly under / */
7800 	if (!prefix[1] && (prefix[0] == '/'))
7801 		len = 0;
7802 
7803 	if (!mkdtemp(tmpdir)) {
7804 		free(tmpdir);
7805 
7806 		DPRINTF_S(strerror(errno));
7807 		return NULL;
7808 	}
7809 
7810 	listpath = tmpdir;
7811 
7812 	for (ssize_t i = 0; i < entries; ++i) {
7813 		if (!paths[i])
7814 			continue;
7815 
7816 		err = stat(paths[i], &sb);
7817 		if (err && errno == ENOENT)
7818 			continue;
7819 
7820 		/* Don't copy the common prefix */
7821 		xstrsncpy(tmp, paths[i] + len, xstrlen(paths[i]) - len + 1);
7822 
7823 		/* Get the dir containing the path */
7824 		slash = xmemrchr((uchar_t *)tmp, '/', xstrlen(paths[i]) - len);
7825 		if (slash)
7826 			*slash = '\0';
7827 
7828 		xmktree(tmpdir, TRUE);
7829 
7830 		if (slash)
7831 			*slash = '/';
7832 
7833 		if (symlink(paths[i], tmpdir)) {
7834 			DPRINTF_S(paths[i]);
7835 			DPRINTF_S(strerror(errno));
7836 		}
7837 	}
7838 
7839 	/* Get the dir in which to start */
7840 	*tmp = '\0';
7841 	return tmpdir;
7842 }
7843 
7844 static char *load_input(int fd, const char *path)
7845 {
7846 	ssize_t i, chunk_count = 1, chunk = 512 * 1024 /* 512 KiB chunk size */, entries = 0;
7847 	char *input = malloc(sizeof(char) * chunk), *tmpdir = NULL;
7848 	char cwd[PATH_MAX], *next;
7849 	size_t offsets[LIST_FILES_MAX];
7850 	char **paths = NULL;
7851 	ssize_t input_read, total_read = 0, off = 0;
7852 	int msgnum = 0;
7853 
7854 	if (!input) {
7855 		DPRINTF_S(strerror(errno));
7856 		return NULL;
7857 	}
7858 
7859 	if (!path) {
7860 		if (!getcwd(cwd, PATH_MAX)) {
7861 			free(input);
7862 			return NULL;
7863 		}
7864 	} else
7865 		xstrsncpy(cwd, path, PATH_MAX);
7866 
7867 	while (chunk_count < 512) {
7868 		input_read = read(fd, input + total_read, chunk);
7869 		if (input_read < 0) {
7870 			DPRINTF_S(strerror(errno));
7871 			goto malloc_1;
7872 		}
7873 
7874 		if (input_read == 0)
7875 			break;
7876 
7877 		total_read += input_read;
7878 		++chunk_count;
7879 
7880 		while (off < total_read) {
7881 			next = memchr(input + off, '\0', total_read - off) + 1;
7882 			if (next == (void *)1)
7883 				break;
7884 
7885 			if (next - input == off + 1) {
7886 				off = next - input;
7887 				continue;
7888 			}
7889 
7890 			if (entries == LIST_FILES_MAX) {
7891 				msgnum = MSG_LIMIT;
7892 				goto malloc_1;
7893 			}
7894 
7895 			offsets[entries++] = off;
7896 			off = next - input;
7897 		}
7898 
7899 		if (chunk_count == 512) {
7900 			msgnum = MSG_LIMIT;
7901 			goto malloc_1;
7902 		}
7903 
7904 		/* We don't need to allocate another chunk */
7905 		if (chunk_count == (total_read - input_read) / chunk)
7906 			continue;
7907 
7908 		chunk_count = total_read / chunk;
7909 		if (total_read % chunk)
7910 			++chunk_count;
7911 
7912 		input = xrealloc(input, (chunk_count + 1) * chunk);
7913 		if (!input)
7914 			return NULL;
7915 	}
7916 
7917 	if (off != total_read) {
7918 		if (entries == LIST_FILES_MAX) {
7919 			msgnum = MSG_LIMIT;
7920 			goto malloc_1;
7921 		}
7922 
7923 		offsets[entries++] = off;
7924 	}
7925 
7926 	DPRINTF_D(entries);
7927 	DPRINTF_D(total_read);
7928 	DPRINTF_D(chunk_count);
7929 
7930 	if (!entries) {
7931 		msgnum = MSG_0_ENTRIES;
7932 		goto malloc_1;
7933 	}
7934 
7935 	input[total_read] = '\0';
7936 
7937 	paths = malloc(entries * sizeof(char *));
7938 	if (!paths)
7939 		goto malloc_1;
7940 
7941 	for (i = 0; i < entries; ++i)
7942 		paths[i] = input + offsets[i];
7943 
7944 	listroot = malloc(sizeof(char) * PATH_MAX);
7945 	if (!listroot)
7946 		goto malloc_1;
7947 	listroot[0] = '\0';
7948 
7949 	DPRINTF_S(paths[0]);
7950 
7951 	for (i = 0; i < entries; ++i) {
7952 		if (paths[i][0] == '\n' || selforparent(paths[i])) {
7953 			paths[i] = NULL;
7954 			continue;
7955 		}
7956 
7957 		paths[i] = abspath(paths[i], cwd, NULL);
7958 		if (!paths[i]) {
7959 			entries = i; // free from the previous entry
7960 			goto malloc_2;
7961 
7962 		}
7963 
7964 		DPRINTF_S(paths[i]);
7965 
7966 		xstrsncpy(g_buf, paths[i], PATH_MAX);
7967 		if (!common_prefix(xdirname(g_buf), listroot)) {
7968 			entries = i + 1; // free from the current entry
7969 			goto malloc_2;
7970 		}
7971 
7972 		DPRINTF_S(listroot);
7973 	}
7974 
7975 	DPRINTF_S(listroot);
7976 
7977 	if (listroot[0])
7978 		tmpdir = make_tmp_tree(paths, entries, listroot);
7979 
7980 malloc_2:
7981 	for (i = entries - 1; i >= 0; --i)
7982 		free(paths[i]);
7983 malloc_1:
7984 	if (msgnum) {
7985 		if (home) { /* We are past init stage */
7986 			printmsg(messages[msgnum]);
7987 			xdelay(XDELAY_INTERVAL_MS);
7988 		} else
7989 			msg(messages[msgnum]);
7990 	}
7991 	free(input);
7992 	free(paths);
7993 	return tmpdir;
7994 }
7995 
7996 static void check_key_collision(void)
7997 {
7998 	int key;
7999 	bool bitmap[KEY_MAX] = {FALSE};
8000 
8001 	for (ullong_t i = 0; i < sizeof(bindings) / sizeof(struct key); ++i) {
8002 		key = bindings[i].sym;
8003 
8004 		if (bitmap[key])
8005 			dprintf(STDERR_FILENO, "key collision! [%s]\n", keyname(key));
8006 		else
8007 			bitmap[key] = TRUE;
8008 	}
8009 }
8010 
8011 static void usage(void)
8012 {
8013 	dprintf(STDERR_FILENO,
8014 		"%s: nnn [OPTIONS] [PATH]\n\n"
8015 		"The unorthodox terminal file manager.\n\n"
8016 		"positional args:\n"
8017 		"  PATH   start dir/file [default: .]\n\n"
8018 		"optional args:\n"
8019 #ifndef NOFIFO
8020 		" -a      auto NNN_FIFO\n"
8021 #endif
8022 		" -A      no dir auto-select\n"
8023 		" -b key  open bookmark key (trumps -s/S)\n"
8024 		" -c      cli-only NNN_OPENER (trumps -e)\n"
8025 		" -C      8-color scheme\n"
8026 		" -d      detail mode\n"
8027 		" -D      dirs in context color\n"
8028 		" -e      text in $VISUAL/$EDITOR/vi\n"
8029 		" -E      internal edits in EDITOR\n"
8030 #ifndef NORL
8031 		" -f      use readline history file\n"
8032 #endif
8033 #ifndef NOFIFO
8034 		" -F val  fifo mode [0:preview 1:explore]\n"
8035 #endif
8036 		" -g      regex filters\n"
8037 		" -H      show hidden files\n"
8038 		" -J      no auto-proceed on select\n"
8039 		" -K      detect key collision\n"
8040 		" -l val  set scroll lines\n"
8041 		" -n      type-to-nav mode\n"
8042 		" -o      open files only on Enter\n"
8043 		" -p file selection file [-:stdout]\n"
8044 		" -P key  run plugin key\n"
8045 		" -Q      no quit confirmation\n"
8046 		" -r      use advcpmv patched cp, mv\n"
8047 		" -R      no rollover at edges\n"
8048 #ifndef NOSSN
8049 		" -s name load session by name\n"
8050 		" -S      persistent session\n"
8051 #endif
8052 		" -t secs timeout to lock\n"
8053 		" -T key  sort order [a/d/e/r/s/t/v]\n"
8054 		" -u      use selection (no prompt)\n"
8055 #ifndef NOUG
8056 		" -U      show user and group\n"
8057 #endif
8058 		" -V      show version\n"
8059 		" -w      place HW cursor on hovered\n"
8060 #ifndef NOX11
8061 		" -x      notis, selection sync, xterm title\n"
8062 #endif
8063 		" -h      show help\n\n"
8064 		"v%s\n%s\n", __func__, VERSION, GENERAL_INFO);
8065 }
8066 
8067 static bool setup_config(void)
8068 {
8069 	size_t r, len;
8070 	char *xdgcfg = getenv("XDG_CONFIG_HOME");
8071 	bool xdg = FALSE;
8072 
8073 	/* Set up configuration file paths */
8074 	if (xdgcfg && xdgcfg[0]) {
8075 		DPRINTF_S(xdgcfg);
8076 		if (xdgcfg[0] == '~') {
8077 			r = xstrsncpy(g_buf, home, PATH_MAX);
8078 			xstrsncpy(g_buf + r - 1, xdgcfg + 1, PATH_MAX);
8079 			xdgcfg = g_buf;
8080 			DPRINTF_S(xdgcfg);
8081 		}
8082 
8083 		if (!xdiraccess(xdgcfg)) {
8084 			xerror();
8085 			return FALSE;
8086 		}
8087 
8088 		len = xstrlen(xdgcfg) + xstrlen("/nnn/bookmarks") + 1;
8089 		xdg = TRUE;
8090 	}
8091 
8092 	if (!xdg)
8093 		len = xstrlen(home) + xstrlen("/.config/nnn/bookmarks") + 1;
8094 
8095 	cfgpath = (char *)malloc(len);
8096 	plgpath = (char *)malloc(len);
8097 	if (!cfgpath || !plgpath) {
8098 		xerror();
8099 		return FALSE;
8100 	}
8101 
8102 	if (xdg) {
8103 		xstrsncpy(cfgpath, xdgcfg, len);
8104 		r = len - xstrlen("/nnn/bookmarks");
8105 	} else {
8106 		r = xstrsncpy(cfgpath, home, len);
8107 
8108 		/* Create ~/.config */
8109 		xstrsncpy(cfgpath + r - 1, "/.config", len - r);
8110 		DPRINTF_S(cfgpath);
8111 		r += 8; /* length of "/.config" */
8112 	}
8113 
8114 	/* Create ~/.config/nnn */
8115 	xstrsncpy(cfgpath + r - 1, "/nnn", len - r);
8116 	DPRINTF_S(cfgpath);
8117 
8118 	/* Create bookmarks, sessions, mounts and plugins directories */
8119 	for (r = 0; r < ELEMENTS(toks); ++r) {
8120 		mkpath(cfgpath, toks[r], plgpath);
8121 		if (!xmktree(plgpath, TRUE)) {
8122 			DPRINTF_S(toks[r]);
8123 			xerror();
8124 			return FALSE;
8125 		}
8126 	}
8127 
8128 	/* Set selection file path */
8129 	if (!g_state.picker) {
8130 		char *env_sel = xgetenv(env_cfg[NNN_SEL], NULL);
8131 
8132 		selpath = env_sel ? xstrdup(env_sel)
8133 				  : (char *)malloc(len + 3); /* Length of "/.config/nnn/.selection" */
8134 
8135 		if (!selpath) {
8136 			xerror();
8137 			return FALSE;
8138 		}
8139 
8140 		if (!env_sel) {
8141 			r = xstrsncpy(selpath, cfgpath, len + 3);
8142 			xstrsncpy(selpath + r - 1, "/.selection", 12);
8143 			DPRINTF_S(selpath);
8144 		}
8145 	}
8146 
8147 	return TRUE;
8148 }
8149 
8150 static bool set_tmp_path(void)
8151 {
8152 	char *tmp = "/tmp";
8153 	char *path = xdiraccess(tmp) ? tmp : getenv("TMPDIR");
8154 
8155 	if (!path) {
8156 		msg("set TMPDIR");
8157 		return FALSE;
8158 	}
8159 
8160 	tmpfplen = (uchar_t)xstrsncpy(g_tmpfpath, path, TMP_LEN_MAX);
8161 	DPRINTF_S(g_tmpfpath);
8162 	DPRINTF_U(tmpfplen);
8163 
8164 	return TRUE;
8165 }
8166 
8167 static void cleanup(void)
8168 {
8169 #ifndef NOX11
8170 	if (cfg.x11 && !g_state.picker) {
8171 		printf("\033[23;0t"); /* reset terminal window title */
8172 		fflush(stdout);
8173 
8174 		free(hostname);
8175 	}
8176 #endif
8177 	free(selpath);
8178 	free(plgpath);
8179 	free(cfgpath);
8180 	free(initpath);
8181 	free(bmstr);
8182 	free(pluginstr);
8183 	free(listroot);
8184 	free(ihashbmp);
8185 	free(bookmark);
8186 	free(plug);
8187 	free(lastcmd);
8188 #ifndef NOFIFO
8189 	if (g_state.autofifo)
8190 		unlink(fifopath);
8191 #endif
8192 	if (g_state.pluginit)
8193 		unlink(g_pipepath);
8194 #ifdef DEBUG
8195 	disabledbg();
8196 #endif
8197 }
8198 
8199 int main(int argc, char *argv[])
8200 {
8201 	char *arg = NULL;
8202 	char *session = NULL;
8203 	int fd, opt, sort = 0, pkey = '\0'; /* Plugin key */
8204 #ifndef NOMOUSE
8205 	mmask_t mask;
8206 	char *middle_click_env = xgetenv(env_cfg[NNN_MCLICK], "\0");
8207 
8208 	middle_click_key = (middle_click_env[0] == '^' && middle_click_env[1])
8209 			    ? CONTROL(middle_click_env[1])
8210 			    : (uchar_t)middle_click_env[0];
8211 #endif
8212 
8213 	const char * const env_opts = xgetenv(env_cfg[NNN_OPTS], NULL);
8214 	int env_opts_id = env_opts ? (int)xstrlen(env_opts) : -1;
8215 #ifndef NORL
8216 	bool rlhist = FALSE;
8217 #endif
8218 
8219 	while ((opt = (env_opts_id > 0
8220 		       ? env_opts[--env_opts_id]
8221 		       : getopt(argc, argv, "aAb:cCdDeEfF:gHJKl:nop:P:QrRs:St:T:uUVwxh"))) != -1) {
8222 		switch (opt) {
8223 #ifndef NOFIFO
8224 		case 'a':
8225 			g_state.autofifo = 1;
8226 			break;
8227 #endif
8228 		case 'A':
8229 			cfg.autoselect = 0;
8230 			break;
8231 		case 'b':
8232 			if (env_opts_id < 0)
8233 				arg = optarg;
8234 			break;
8235 		case 'c':
8236 			cfg.cliopener = 1;
8237 			break;
8238 		case 'C':
8239 			g_state.oldcolor = 1;
8240 			break;
8241 		case 'd':
8242 			cfg.showdetail = 1;
8243 			break;
8244 		case 'D':
8245 			g_state.dirctx = 1;
8246 			break;
8247 		case 'e':
8248 			cfg.useeditor = 1;
8249 			break;
8250 		case 'E':
8251 			cfg.waitedit = 1;
8252 			break;
8253 		case 'f':
8254 #ifndef NORL
8255 			rlhist = TRUE;
8256 #endif
8257 			break;
8258 #ifndef NOFIFO
8259 		case 'F':
8260 			if (env_opts_id < 0) {
8261 				fd = atoi(optarg);
8262 				if ((fd < 0) || (fd > 1))
8263 					return EXIT_FAILURE;
8264 				g_state.fifomode = fd;
8265 			}
8266 			break;
8267 #endif
8268 		case 'g':
8269 			cfg.regex = 1;
8270 			filterfn = &visible_re;
8271 			break;
8272 		case 'H':
8273 			cfg.showhidden = 1;
8274 			break;
8275 		case 'J':
8276 			g_state.stayonsel = 1;
8277 			break;
8278 		case 'K':
8279 			check_key_collision();
8280 			return EXIT_SUCCESS;
8281 		case 'l':
8282 			if (env_opts_id < 0)
8283 				scroll_lines = atoi(optarg);
8284 			break;
8285 		case 'n':
8286 			cfg.filtermode = 1;
8287 			break;
8288 		case 'o':
8289 			cfg.nonavopen = 1;
8290 			break;
8291 		case 'p':
8292 			if (env_opts_id >= 0)
8293 				break;
8294 
8295 			g_state.picker = 1;
8296 			if (!(optarg[0] == '-' && optarg[1] == '\0')) {
8297 				fd = open(optarg, O_WRONLY | O_CREAT, 0600);
8298 				if (fd == -1) {
8299 					xerror();
8300 					return EXIT_FAILURE;
8301 				}
8302 
8303 				close(fd);
8304 				selpath = abspath(optarg, NULL, NULL);
8305 				unlink(selpath);
8306 			}
8307 			break;
8308 		case 'P':
8309 			if (env_opts_id < 0 && !optarg[1])
8310 				pkey = (uchar_t)optarg[0];
8311 			break;
8312 		case 'Q':
8313 			g_state.forcequit = 1;
8314 			break;
8315 		case 'r':
8316 #ifdef __linux__
8317 			cp[2] = cp[5] = mv[2] = mv[5] = 'g'; /* cp -iRp -> cpg -giRp */
8318 			cp[4] = mv[4] = '-';
8319 #endif
8320 			break;
8321 		case 'R':
8322 			cfg.rollover = 0;
8323 			break;
8324 #ifndef NOSSN
8325 		case 's':
8326 			if (env_opts_id < 0)
8327 				session = optarg;
8328 			break;
8329 		case 'S':
8330 			g_state.prstssn = 1;
8331 			if (!session) /* Support named persistent sessions */
8332 				session = "@";
8333 			break;
8334 #endif
8335 		case 't':
8336 			if (env_opts_id < 0)
8337 				idletimeout = atoi(optarg);
8338 			break;
8339 		case 'T':
8340 			if (env_opts_id < 0)
8341 				sort = (uchar_t)optarg[0];
8342 			break;
8343 		case 'u':
8344 			cfg.prefersel = 1;
8345 			break;
8346 		case 'U':
8347 			g_state.uidgid = 1;
8348 			break;
8349 		case 'V':
8350 			dprintf(STDOUT_FILENO, "%s\n", VERSION);
8351 			return EXIT_SUCCESS;
8352 		case 'w':
8353 			cfg.cursormode = 1;
8354 			break;
8355 		case 'x':
8356 			cfg.x11 = 1;
8357 			break;
8358 		case 'h':
8359 			usage();
8360 			return EXIT_SUCCESS;
8361 		default:
8362 			usage();
8363 			return EXIT_FAILURE;
8364 		}
8365 		if (env_opts_id == 0)
8366 			env_opts_id = -1;
8367 	}
8368 
8369 #ifdef DEBUG
8370 	enabledbg();
8371 	DPRINTF_S(VERSION);
8372 #endif
8373 
8374 	/* Prefix for temporary files */
8375 	if (!set_tmp_path())
8376 		return EXIT_FAILURE;
8377 
8378 	atexit(cleanup);
8379 
8380 	/* Check if we are in path list mode */
8381 	if (!isatty(STDIN_FILENO)) {
8382 		/* This is the same as listpath */
8383 		initpath = load_input(STDIN_FILENO, NULL);
8384 		if (!initpath)
8385 			return EXIT_FAILURE;
8386 
8387 		/* We return to tty */
8388 		if (!isatty(STDOUT_FILENO)) {
8389 			fd = open(ctermid(NULL), O_RDONLY, 0400);
8390 			dup2(fd, STDIN_FILENO);
8391 			close(fd);
8392 		} else
8393 			dup2(STDOUT_FILENO, STDIN_FILENO);
8394 
8395 		if (session)
8396 			session = NULL;
8397 	}
8398 
8399 	home = getenv("HOME");
8400 	if (!home) {
8401 		msg("set HOME");
8402 		return EXIT_FAILURE;
8403 	}
8404 	DPRINTF_S(home);
8405 	homelen = (uchar_t)xstrlen(home);
8406 
8407 	if (!setup_config())
8408 		return EXIT_FAILURE;
8409 
8410 	/* Get custom opener, if set */
8411 	opener = xgetenv(env_cfg[NNN_OPENER], utils[UTIL_OPENER]);
8412 	DPRINTF_S(opener);
8413 
8414 	/* Parse bookmarks string */
8415 	if (!parsekvpair(&bookmark, &bmstr, NNN_BMS, &maxbm)) {
8416 		msg(env_cfg[NNN_BMS]);
8417 		return EXIT_FAILURE;
8418 	}
8419 
8420 	/* Parse plugins string */
8421 	if (!parsekvpair(&plug, &pluginstr, NNN_PLUG, &maxplug)) {
8422 		msg(env_cfg[NNN_PLUG]);
8423 		return EXIT_FAILURE;
8424 	}
8425 
8426 	/* Parse order string */
8427 	if (!parsekvpair(&order, &orderstr, NNN_ORDER, &maxorder)) {
8428 		msg(env_cfg[NNN_ORDER]);
8429 		return EXIT_FAILURE;
8430 	}
8431 
8432 	if (!initpath) {
8433 		if (arg) { /* Open a bookmark directly */
8434 			if (!arg[1]) /* Bookmarks keys are single char */
8435 				initpath = get_kv_val(bookmark, NULL, *arg, maxbm, NNN_BMS);
8436 
8437 			if (!initpath) {
8438 				msg(messages[MSG_INVALID_KEY]);
8439 				return EXIT_FAILURE;
8440 			}
8441 
8442 			if (session)
8443 				session = NULL;
8444 		} else if (argc == optind) {
8445 			/* Start in the current directory */
8446 			char *startpath = getenv("PWD");
8447 
8448 			initpath = startpath ? xstrdup(startpath) : getcwd(NULL, 0);
8449 			if (!initpath)
8450 				initpath = "/";
8451 		} else {
8452 			arg = argv[optind];
8453 			DPRINTF_S(arg);
8454 			if (xstrlen(arg) > 7 && is_prefix(arg, "file://", 7))
8455 				arg = arg + 7;
8456 			initpath = abspath(arg, NULL, NULL);
8457 			DPRINTF_S(initpath);
8458 			if (!initpath) {
8459 				xerror();
8460 				return EXIT_FAILURE;
8461 			}
8462 
8463 			/*
8464 			 * If nnn is set as the file manager, applications may try to open
8465 			 * files by invoking nnn. In that case pass the file path to the
8466 			 * desktop opener and exit.
8467 			 */
8468 			struct stat sb;
8469 
8470 			if (stat(initpath, &sb) == -1) {
8471 				xerror();
8472 				return EXIT_FAILURE;
8473 			}
8474 
8475 			if (!S_ISDIR(sb.st_mode))
8476 				g_state.initfile = 1;
8477 
8478 			if (session)
8479 				session = NULL;
8480 		}
8481 	}
8482 
8483 	/* Set archive handling (enveditor used as tmp var) */
8484 	enveditor = getenv(env_cfg[NNN_ARCHIVE]);
8485 #ifdef PCRE
8486 	if (setfilter(&archive_pcre, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8487 #else
8488 	if (setfilter(&archive_re, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8489 #endif
8490 		msg(messages[MSG_INVALID_REG]);
8491 		return EXIT_FAILURE;
8492 	}
8493 
8494 	/* An all-CLI opener overrides option -e) */
8495 	if (cfg.cliopener)
8496 		cfg.useeditor = 0;
8497 
8498 	/* Get VISUAL/EDITOR */
8499 	enveditor = xgetenv(envs[ENV_EDITOR], utils[UTIL_VI]);
8500 	editor = xgetenv(envs[ENV_VISUAL], enveditor);
8501 	DPRINTF_S(getenv(envs[ENV_VISUAL]));
8502 	DPRINTF_S(getenv(envs[ENV_EDITOR]));
8503 	DPRINTF_S(editor);
8504 
8505 	/* Get PAGER */
8506 	pager = xgetenv(envs[ENV_PAGER], utils[UTIL_LESS]);
8507 	DPRINTF_S(pager);
8508 
8509 	/* Get SHELL */
8510 	shell = xgetenv(envs[ENV_SHELL], utils[UTIL_SH]);
8511 	DPRINTF_S(shell);
8512 
8513 	DPRINTF_S(getenv("PWD"));
8514 
8515 #ifndef NOFIFO
8516 	/* Create fifo */
8517 	if (g_state.autofifo) {
8518 		g_tmpfpath[tmpfplen - 1] = '\0';
8519 
8520 		size_t r = mkpath(g_tmpfpath, "nnn-fifo.", g_buf);
8521 
8522 		xstrsncpy(g_buf + r - 1, xitoa(getpid()), PATH_MAX - r);
8523 		setenv("NNN_FIFO", g_buf, TRUE);
8524 	}
8525 
8526 	fifopath = xgetenv("NNN_FIFO", NULL);
8527 	if (fifopath) {
8528 		if (mkfifo(fifopath, 0600) != 0 && !(errno == EEXIST && access(fifopath, W_OK) == 0)) {
8529 			xerror();
8530 			return EXIT_FAILURE;
8531 		}
8532 
8533 		sigaction(SIGPIPE, &(struct sigaction){.sa_handler = SIG_IGN}, NULL);
8534 	}
8535 #endif
8536 
8537 #ifdef LINUX_INOTIFY
8538 	/* Initialize inotify */
8539 	inotify_fd = inotify_init1(IN_NONBLOCK);
8540 	if (inotify_fd < 0) {
8541 		xerror();
8542 		return EXIT_FAILURE;
8543 	}
8544 #elif defined(BSD_KQUEUE)
8545 	kq = kqueue();
8546 	if (kq < 0) {
8547 		xerror();
8548 		return EXIT_FAILURE;
8549 	}
8550 #elif defined(HAIKU_NM)
8551 	haiku_hnd = haiku_init_nm();
8552 	if (!haiku_hnd) {
8553 		xerror();
8554 		return EXIT_FAILURE;
8555 	}
8556 #endif
8557 
8558 	/* Configure trash preference */
8559 	opt = xgetenv_val(env_cfg[NNN_TRASH]);
8560 	if (opt && opt <= 2)
8561 		g_state.trash = opt;
8562 
8563 	/* Ignore/handle certain signals */
8564 	struct sigaction act = {.sa_handler = sigint_handler};
8565 
8566 	if (sigaction(SIGINT, &act, NULL) < 0) {
8567 		xerror();
8568 		return EXIT_FAILURE;
8569 	}
8570 
8571 	act.sa_handler = clean_exit_sighandler;
8572 
8573 	if (sigaction(SIGTERM, &act, NULL) < 0 || sigaction(SIGHUP, &act, NULL) < 0) {
8574 		xerror();
8575 		return EXIT_FAILURE;
8576 	}
8577 
8578 	act.sa_handler = SIG_IGN;
8579 
8580 	if (sigaction(SIGQUIT, &act, NULL) < 0) {
8581 		xerror();
8582 		return EXIT_FAILURE;
8583 	}
8584 
8585 #ifndef NOLC
8586 	/* Set locale */
8587 	setlocale(LC_ALL, "");
8588 #ifdef PCRE
8589 	tables = pcre_maketables();
8590 #endif
8591 #endif
8592 
8593 #ifndef NORL
8594 #if RL_READLINE_VERSION >= 0x0603
8595 	/* readline would overwrite the WINCH signal hook */
8596 	rl_change_environment = 0;
8597 #endif
8598 	/* Bind TAB to cycling */
8599 	rl_variable_bind("completion-ignore-case", "on");
8600 #ifdef __linux__
8601 	rl_bind_key('\t', rl_menu_complete);
8602 #else
8603 	rl_bind_key('\t', rl_complete);
8604 #endif
8605 	if (rlhist) {
8606 		mkpath(cfgpath, ".history", g_buf);
8607 		read_history(g_buf);
8608 	}
8609 #endif
8610 
8611 #ifndef NOX11
8612 	if (cfg.x11 && !g_state.picker) {
8613 		/* Save terminal window title */
8614 		printf("\033[22;0t");
8615 		fflush(stdout);
8616 
8617 		hostname = malloc(_POSIX_HOST_NAME_MAX + 1);
8618 		if (!hostname) {
8619 			xerror();
8620 			return EXIT_FAILURE;
8621 		}
8622 		gethostname(hostname, _POSIX_HOST_NAME_MAX);
8623 		hostname[_POSIX_HOST_NAME_MAX] = '\0';
8624 	}
8625 #endif
8626 
8627 #ifndef NOMOUSE
8628 	if (!initcurses(&mask))
8629 #else
8630 	if (!initcurses(NULL))
8631 #endif
8632 		return EXIT_FAILURE;
8633 
8634 	if (sort)
8635 		set_sort_flags(sort);
8636 
8637 	opt = browse(initpath, session, pkey);
8638 
8639 #ifndef NOMOUSE
8640 	mousemask(mask, NULL);
8641 #endif
8642 
8643 	exitcurses();
8644 
8645 #ifndef NORL
8646 	if (rlhist) {
8647 		mkpath(cfgpath, ".history", g_buf);
8648 		write_history(g_buf);
8649 	}
8650 #endif
8651 
8652 	if (g_state.picker) {
8653 		if (selbufpos) {
8654 			fd = selpath ? open(selpath, O_WRONLY | O_CREAT | O_TRUNC, 0600) : STDOUT_FILENO;
8655 			if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
8656 				xerror();
8657 
8658 			if (fd > 1)
8659 				close(fd);
8660 		}
8661 	} else if (selpath)
8662 		unlink(selpath);
8663 
8664 	/* Remove tmp dir in list mode */
8665 	rmlistpath();
8666 
8667 	/* Free the regex */
8668 #ifdef PCRE
8669 	pcre_free(archive_pcre);
8670 #else
8671 	regfree(&archive_re);
8672 #endif
8673 
8674 	/* Free the selection buffer */
8675 	free(pselbuf);
8676 
8677 #ifdef LINUX_INOTIFY
8678 	/* Shutdown inotify */
8679 	if (inotify_wd >= 0)
8680 		inotify_rm_watch(inotify_fd, inotify_wd);
8681 	close(inotify_fd);
8682 #elif defined(BSD_KQUEUE)
8683 	if (event_fd >= 0)
8684 		close(event_fd);
8685 	close(kq);
8686 #elif defined(HAIKU_NM)
8687 	haiku_close_nm(haiku_hnd);
8688 #endif
8689 
8690 #ifndef NOFIFO
8691 	if (!g_state.fifomode)
8692 		notify_fifo(FALSE);
8693 	if (fifofd != -1)
8694 		close(fifofd);
8695 #endif
8696 
8697 	return opt;
8698 }
8699