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