]> Sergey Matveev's repositories - nnn.git/blob - src/nnn.c
b3c188da677696afcfe51631e1b0ce5cdb735986
[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 static void savecurctx(char *path, char *curname, int nextctx)
4280 {
4281         settings tmpcfg = cfg;
4282         context *ctxr = &g_ctx[nextctx];
4283
4284         /* Save current context */
4285         if (curname)
4286                 xstrsncpy(g_ctx[tmpcfg.curctx].c_name, curname, NAME_MAX + 1);
4287         else
4288                 g_ctx[tmpcfg.curctx].c_name[0] = '\0';
4289
4290         g_ctx[tmpcfg.curctx].c_cfg = tmpcfg;
4291
4292         if (ctxr->c_cfg.ctxactive) { /* Switch to saved context */
4293                 tmpcfg = ctxr->c_cfg;
4294                 /* Skip ordering an open context */
4295                 if (order) {
4296                         cfgsort[CTX_MAX] = cfgsort[nextctx];
4297                         cfgsort[nextctx] = '0';
4298                 }
4299         } else { /* Set up a new context from current context */
4300                 ctxr->c_cfg.ctxactive = 1;
4301                 xstrsncpy(ctxr->c_path, path, PATH_MAX);
4302                 ctxr->c_last[0] = ctxr->c_name[0] = ctxr->c_fltr[0] = ctxr->c_fltr[1] = '\0';
4303                 ctxr->c_cfg = tmpcfg;
4304                 /* If already in an ordered dir, clear ordering for the new context and let it order */
4305                 if (cfgsort[cfg.curctx] == 'z')
4306                         cfgsort[nextctx] = 'z';
4307         }
4308
4309         tmpcfg.curctx = nextctx;
4310         cfg = tmpcfg;
4311         /* Restore the global function pointers alongside the cfg. */
4312         entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
4313         namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
4314 }
4315
4316 #ifndef NOSSN
4317 static void save_session(const char *sname, int *presel)
4318 {
4319         int fd, i;
4320         session_header_t header = {0};
4321         bool status = FALSE;
4322         char ssnpath[PATH_MAX];
4323         char spath[PATH_MAX];
4324
4325         header.ver = SESSIONS_VERSION;
4326
4327         for (i = 0; i < CTX_MAX; ++i) {
4328                 if (g_ctx[i].c_cfg.ctxactive) {
4329                         if (cfg.curctx == i && ndents)
4330                                 /* Update current file name, arrows don't update it */
4331                                 xstrsncpy(g_ctx[i].c_name, pdents[cur].name, NAME_MAX + 1);
4332                         header.pathln[i] = MIN(xstrlen(g_ctx[i].c_path), PATH_MAX) + 1;
4333                         header.lastln[i] = MIN(xstrlen(g_ctx[i].c_last), PATH_MAX) + 1;
4334                         header.nameln[i] = MIN(xstrlen(g_ctx[i].c_name), NAME_MAX) + 1;
4335                         header.fltrln[i] = REGEX_MAX;
4336                 }
4337         }
4338
4339         mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4340         mkpath(ssnpath, sname, spath);
4341
4342         fd = open(spath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
4343         if (fd == -1) {
4344                 printwait(messages[MSG_SEL_MISSING], presel);
4345                 return;
4346         }
4347
4348         if ((write(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4349                 || (write(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4350                 goto END;
4351
4352         for (i = 0; i < CTX_MAX; ++i)
4353                 if ((write(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4354                         || (write(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4355                         || (header.nameln[i] > 0
4356                             && write(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4357                         || (header.lastln[i] > 0
4358                             && write(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4359                         || (header.fltrln[i] > 0
4360                             && write(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4361                         || (header.pathln[i] > 0
4362                             && write(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4363                         goto END;
4364
4365         status = TRUE;
4366
4367 END:
4368         close(fd);
4369
4370         if (!status)
4371                 printwait(messages[MSG_FAILED], presel);
4372 }
4373
4374 static bool load_session(const char *sname, char **path, char **lastdir, char **lastname, bool restore)
4375 {
4376         int fd, i = 0;
4377         session_header_t header;
4378         bool has_loaded_dynamically = !(sname || restore);
4379         bool status = (sname && g_state.picker); /* Picker mode with session program option */
4380         char ssnpath[PATH_MAX];
4381         char spath[PATH_MAX];
4382
4383         mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4384
4385         if (!restore) {
4386                 sname = sname ? sname : xreadline(NULL, messages[MSG_SSN_NAME]);
4387                 if (!sname[0])
4388                         return FALSE;
4389
4390                 mkpath(ssnpath, sname, spath);
4391
4392                 /* If user is explicitly loading the "last session", skip auto-save */
4393                 if ((sname[0] == '@') && !sname[1])
4394                         has_loaded_dynamically = FALSE;
4395         } else
4396                 mkpath(ssnpath, "@", spath);
4397
4398         if (has_loaded_dynamically)
4399                 save_session("@", NULL);
4400
4401         fd = open(spath, O_RDONLY, S_IWUSR | S_IRUSR);
4402         if (fd == -1) {
4403                 if (!status) {
4404                         printmsg(messages[MSG_SEL_MISSING]);
4405                         xdelay(XDELAY_INTERVAL_MS);
4406                 }
4407                 return FALSE;
4408         }
4409
4410         status = FALSE;
4411
4412         if ((read(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4413                 || (header.ver != SESSIONS_VERSION)
4414                 || (read(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4415                 goto END;
4416
4417         g_ctx[cfg.curctx].c_name[0] = g_ctx[cfg.curctx].c_last[0]
4418                 = g_ctx[cfg.curctx].c_fltr[0] = g_ctx[cfg.curctx].c_fltr[1] = '\0';
4419
4420         for (; i < CTX_MAX; ++i)
4421                 if ((read(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4422                         || (read(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4423                         || (header.nameln[i] > 0
4424                             && read(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4425                         || (header.lastln[i] > 0
4426                             && read(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4427                         || (header.fltrln[i] > 0
4428                             && read(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4429                         || (header.pathln[i] > 0
4430                             && read(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4431                         goto END;
4432
4433         *path = g_ctx[cfg.curctx].c_path;
4434         *lastdir = g_ctx[cfg.curctx].c_last;
4435         *lastname = g_ctx[cfg.curctx].c_name;
4436         set_sort_flags('\0'); /* Set correct sort options */
4437         status = TRUE;
4438
4439 END:
4440         close(fd);
4441
4442         if (!status) {
4443                 printmsg(messages[MSG_FAILED]);
4444                 xdelay(XDELAY_INTERVAL_MS);
4445         } else if (restore)
4446                 unlink(spath);
4447
4448         return status;
4449 }
4450 #endif
4451
4452 static uchar_t get_free_ctx(void)
4453 {
4454         uchar_t r = cfg.curctx;
4455
4456         do
4457                 r = (r + 1) & ~CTX_MAX;
4458         while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
4459
4460         return r;
4461 }
4462
4463 /* ctx is absolute: 1 to 4, + for smart context */
4464 static void set_smart_ctx(int ctx, char *nextpath, char **path, char *file, char **lastname, char **lastdir)
4465 {
4466         if (ctx == '+') /* Get smart context */
4467                 ctx = (int)(get_free_ctx() + 1);
4468
4469         if (ctx == 0 || ctx == cfg.curctx + 1) { /* Same context */
4470                 clearfilter();
4471                 xstrsncpy(*lastdir, *path, PATH_MAX);
4472                 xstrsncpy(*path, nextpath, PATH_MAX);
4473         } else { /* New context */
4474                 --ctx;
4475                 /* Deactivate the new context and build from scratch */
4476                 g_ctx[ctx].c_cfg.ctxactive = 0;
4477                 DPRINTF_S(nextpath);
4478                 savecurctx(nextpath, file, ctx);
4479                 *path = g_ctx[ctx].c_path;
4480                 *lastdir = g_ctx[ctx].c_last;
4481                 *lastname = g_ctx[ctx].c_name;
4482         }
4483 }
4484
4485 /*
4486  * This function does one of the following depending on the values of `fdout` and `page`:
4487  *  1) fdout == -1 && !page: Write up to CMD_LEN_MAX bytes of command output into g_buf
4488  *  2) fdout == -1 && page: Create a temp file, write full command output into it and show in pager.
4489  *  3) fdout != -1 && !page: Write full command output into the provided file.
4490  *  4) fdout != -1 && page: Don't use! Returns FALSE.
4491  *
4492  * g_buf is modified only in case 1.
4493  * g_tmpfpath is modified only in case 2.
4494  */
4495 static bool get_output(char *file, char *arg1, char *arg2, int fdout, bool page)
4496 {
4497         pid_t pid;
4498         int pipefd[2];
4499         int index = 0, flags;
4500         bool ret = FALSE;
4501         bool have_file = fdout != -1;
4502         int cmd_in_fd = -1;
4503         int cmd_out_fd = -1;
4504         ssize_t len;
4505
4506         /*
4507          * In this case the logic of the function dictates that we should write the output of the command
4508          * to `fd` and show it in the pager. But since we didn't open the file descriptor we have no right
4509          * to close it, the caller must do it. We don't even know the path to pass to the pager and
4510          * it's a real hassle to get it. In general this just invites problems so we are blocking it.
4511          */
4512         if (have_file && page) {
4513                 DPRINTF_S("invalid get_ouptput() call");
4514                 return FALSE;
4515         }
4516
4517         /* Setup file descriptors for child command */
4518         if (!have_file && page) {
4519                 // Case 2
4520                 fdout = create_tmp_file();
4521                 if (fdout == -1)
4522                         return FALSE;
4523
4524                 cmd_in_fd = STDIN_FILENO;
4525                 cmd_out_fd = fdout;
4526         } else if (have_file) {
4527                 // Case 3
4528                 cmd_in_fd = STDIN_FILENO;
4529                 cmd_out_fd = fdout;
4530         } else {
4531                 // Case 1
4532                 if (pipe(pipefd) == -1)
4533                         errexit();
4534
4535                 for (index = 0; index < 2; ++index) {
4536                         /* Get previous flags */
4537                         flags = fcntl(pipefd[index], F_GETFL, 0);
4538
4539                         /* Set bit for non-blocking flag */
4540                         flags |= O_NONBLOCK;
4541
4542                         /* Change flags on fd */
4543                         fcntl(pipefd[index], F_SETFL, flags);
4544                 }
4545
4546                 cmd_in_fd = pipefd[0];
4547                 cmd_out_fd = pipefd[1];
4548         }
4549
4550         pid = fork();
4551         if (pid == 0) {
4552                 /* In child */
4553                 close(cmd_in_fd);
4554                 dup2(cmd_out_fd, STDOUT_FILENO);
4555                 dup2(cmd_out_fd, STDERR_FILENO);
4556                 close(cmd_out_fd);
4557
4558                 spawn(file, arg1, arg2, NULL, F_MULTI);
4559                 _exit(EXIT_SUCCESS);
4560         }
4561
4562         /* In parent */
4563         waitpid(pid, NULL, 0);
4564
4565         /* Do what each case should do */
4566         if (!have_file && page) {
4567                 // Case 2
4568                 close(fdout);
4569
4570                 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4571
4572                 unlink(g_tmpfpath);
4573                 return TRUE;
4574         }
4575
4576         if (have_file)
4577                 // Case 3
4578                 return TRUE;
4579
4580         // Case 1
4581         len = read(pipefd[0], g_buf, CMD_LEN_MAX - 1);
4582         if (len > 0)
4583                 ret = TRUE;
4584
4585         close(pipefd[0]);
4586         close(pipefd[1]);
4587         return ret;
4588 }
4589
4590 /*
4591  * Follows the stat(1) output closely
4592  */
4593 static bool show_stats(char *fpath)
4594 {
4595         static char * const cmds[] = {
4596 #ifdef FILE_MIME_OPTS
4597                 ("file " FILE_MIME_OPTS),
4598 #endif
4599                 "file -b",
4600 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
4601                 "stat -x",
4602 #else
4603                 "stat",
4604 #endif
4605         };
4606
4607         size_t r = ELEMENTS(cmds);
4608         int fd = create_tmp_file();
4609         if (fd == -1)
4610                 return FALSE;
4611
4612         while (r)
4613                 get_output(cmds[--r], fpath, NULL, fd, FALSE);
4614
4615         close(fd);
4616
4617         spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4618         unlink(g_tmpfpath);
4619         return TRUE;
4620 }
4621
4622 static bool xchmod(const char *fpath, mode_t *mode)
4623 {
4624         /* (Un)set (S_IXUSR | S_IXGRP | S_IXOTH) */
4625         (0100 & *mode) ? (*mode &= ~0111) : (*mode |= 0111);
4626
4627         return (chmod(fpath, *mode) == 0);
4628 }
4629
4630 static size_t get_fs_info(const char *path, uchar_t type)
4631 {
4632         struct statvfs svb;
4633
4634         if (statvfs(path, &svb) == -1)
4635                 return 0;
4636
4637         if (type == VFS_AVAIL)
4638                 return (size_t)svb.f_bavail << ffs((int)(svb.f_frsize >> 1));
4639
4640         if (type == VFS_USED)
4641                 return ((size_t)svb.f_blocks - (size_t)svb.f_bfree) << ffs((int)(svb.f_frsize >> 1));
4642
4643         return (size_t)svb.f_blocks << ffs((int)(svb.f_frsize >> 1)); /* VFS_SIZE */
4644 }
4645
4646 /* Create non-existent parents and a file or dir */
4647 static bool xmktree(char *path, bool dir)
4648 {
4649         char *p = path;
4650         char *slash = path;
4651
4652         if (!p || !*p)
4653                 return FALSE;
4654
4655         /* Skip the first '/' */
4656         ++p;
4657
4658         while (*p != '\0') {
4659                 if (*p == '/') {
4660                         slash = p;
4661                         *p = '\0';
4662                 } else {
4663                         ++p;
4664                         continue;
4665                 }
4666
4667                 /* Create folder from path to '\0' inserted at p */
4668                 if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4669 #ifdef __HAIKU__
4670                         // XDG_CONFIG_HOME contains a directory
4671                         // that is read-only, but the full path
4672                         // is writeable.
4673                         // Try to continue and see what happens.
4674                         // TODO: Find a more robust solution.
4675                         if (errno == B_READ_ONLY_DEVICE)
4676                                 goto next;
4677 #endif
4678                         DPRINTF_S("mkdir1!");
4679                         DPRINTF_S(strerror(errno));
4680                         *slash = '/';
4681                         return FALSE;
4682                 }
4683
4684 #ifdef __HAIKU__
4685 next:
4686 #endif
4687                 /* Restore path */
4688                 *slash = '/';
4689                 ++p;
4690         }
4691
4692         if (dir) {
4693                 if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4694                         DPRINTF_S("mkdir2!");
4695                         DPRINTF_S(strerror(errno));
4696                         return FALSE;
4697                 }
4698         } else {
4699                 int fd = open(path, O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR); /* Forced create mode for files */
4700
4701                 if (fd == -1 && errno != EEXIST) {
4702                         DPRINTF_S("open!");
4703                         DPRINTF_S(strerror(errno));
4704                         return FALSE;
4705                 }
4706
4707                 close(fd);
4708         }
4709
4710         return TRUE;
4711 }
4712
4713 /* List or extract archive */
4714 static bool handle_archive(char *fpath /* in-out param */, char op)
4715 {
4716         char arg[] = "-tvf"; /* options for tar/bsdtar to list files */
4717         char *util, *outdir = NULL;
4718         bool x_to = FALSE;
4719         bool is_atool = (!g_state.usebsdtar && getutil(utils[UTIL_ATOOL]));
4720
4721         if (op == 'x') {
4722                 outdir = xreadline(is_atool ? "." : xbasename(fpath), messages[MSG_NEW_PATH]);
4723                 if (!outdir || !*outdir) { /* Cancelled */
4724                         printwait(messages[MSG_CANCEL], NULL);
4725                         return FALSE;
4726                 }
4727                 /* Do not create smart context for current dir */
4728                 if (!(*outdir == '.' && outdir[1] == '\0')) {
4729                         if (!xmktree(outdir, TRUE) || (chdir(outdir) == -1)) {
4730                                 printwarn(NULL);
4731                                 return FALSE;
4732                         }
4733                         /* Copy the new dir path to open it in smart context */
4734                         outdir = getcwd(NULL, 0);
4735                         x_to = TRUE;
4736                 }
4737         }
4738
4739         if (is_atool) {
4740                 util = utils[UTIL_ATOOL];
4741                 arg[1] = op;
4742                 arg[2] = '\0';
4743         } else if (getutil(utils[UTIL_BSDTAR])) {
4744                 util = utils[UTIL_BSDTAR];
4745                 if (op == 'x')
4746                         arg[1] = op;
4747         } else if (is_suffix(fpath, ".zip")) {
4748                 util = utils[UTIL_UNZIP];
4749                 arg[1] = (op == 'l') ? 'v' /* verbose listing */ : '\0';
4750                 arg[2] = '\0';
4751         } else {
4752                 util = utils[UTIL_TAR];
4753                 if (op == 'x')
4754                         arg[1] = op;
4755         }
4756
4757         if (op == 'x') /* extract */
4758                 spawn(util, arg, fpath, NULL, F_NORMAL | F_MULTI);
4759         else /* list */
4760                 get_output(util, arg, fpath, -1, TRUE);
4761
4762         if (x_to) {
4763                 if (chdir(xdirname(fpath)) == -1) {
4764                         printwarn(NULL);
4765                         free(outdir);
4766                         return FALSE;
4767                 }
4768                 xstrsncpy(fpath, outdir, PATH_MAX);
4769                 free(outdir);
4770         } else if (op == 'x')
4771                 fpath[0] = '\0';
4772
4773         return TRUE;
4774 }
4775
4776 static char *visit_parent(char *path, char *newpath, int *presel)
4777 {
4778         char *dir;
4779
4780         /* There is no going back */
4781         if (istopdir(path)) {
4782                 /* Continue in type-to-nav mode, if enabled */
4783                 if (cfg.filtermode && presel)
4784                         *presel = FILTER;
4785                 return NULL;
4786         }
4787
4788         /* Use a copy as xdirname() may change the string passed */
4789         if (newpath)
4790                 xstrsncpy(newpath, path, PATH_MAX);
4791         else
4792                 newpath = path;
4793
4794         dir = xdirname(newpath);
4795         if (chdir(dir) == -1) {
4796                 printwarn(presel);
4797                 return NULL;
4798         }
4799
4800         return dir;
4801 }
4802
4803 static void valid_parent(char *path, char *lastname)
4804 {
4805         /* Save history */
4806         xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
4807
4808         while (!istopdir(path))
4809                 if (visit_parent(path, NULL, NULL))
4810                         break;
4811
4812         printwarn(NULL);
4813         xdelay(XDELAY_INTERVAL_MS);
4814 }
4815
4816 static bool archive_mount(char *newpath)
4817 {
4818         char *dir, *cmd = xgetenv("NNN_ARCHMNT", utils[UTIL_ARCHMNT]);
4819         char *name = pdents[cur].name;
4820         size_t len = pdents[cur].nlen;
4821         char mntpath[PATH_MAX];
4822
4823         if (!getutil(cmd)) {
4824                 printmsg("install utility");
4825                 return FALSE;
4826         }
4827
4828         dir = xstrdup(name);
4829         if (!dir) {
4830                 printmsg(messages[MSG_FAILED]);
4831                 return FALSE;
4832         }
4833
4834         while (len > 1)
4835                 if (dir[--len] == '.') {
4836                         dir[len] = '\0';
4837                         break;
4838                 }
4839
4840         DPRINTF_S(dir);
4841
4842         /* Create the mount point */
4843         mkpath(cfgpath, toks[TOK_MNT], mntpath);
4844         mkpath(mntpath, dir, newpath);
4845         free(dir);
4846
4847         if (!xmktree(newpath, TRUE)) {
4848                 printwarn(NULL);
4849                 return FALSE;
4850         }
4851
4852         /* Mount archive */
4853         DPRINTF_S(name);
4854         DPRINTF_S(newpath);
4855         if (spawn(cmd, name, newpath, NULL, F_NORMAL)) {
4856                 printmsg(messages[MSG_FAILED]);
4857                 return FALSE;
4858         }
4859
4860         return TRUE;
4861 }
4862
4863 static bool remote_mount(char *newpath)
4864 {
4865         uchar_t flag = F_CLI;
4866         int opt;
4867         char *tmp, *env;
4868         bool r = getutil(utils[UTIL_RCLONE]), s = getutil(utils[UTIL_SSHFS]);
4869         char mntpath[PATH_MAX];
4870
4871         if (!(r || s)) {
4872                 printmsg("install sshfs/rclone");
4873                 return FALSE;
4874         }
4875
4876         if (r && s)
4877                 opt = get_input(messages[MSG_REMOTE_OPTS]);
4878         else
4879                 opt = (!s) ? 'r' : 's';
4880
4881         if (opt == 's')
4882                 env = xgetenv("NNN_SSHFS", utils[UTIL_SSHFS]);
4883         else if (opt == 'r') {
4884                 flag |= F_NOWAIT | F_NOTRACE;
4885                 env = xgetenv("NNN_RCLONE", "rclone mount");
4886         } else {
4887                 printmsg(messages[MSG_INVALID_KEY]);
4888                 return FALSE;
4889         }
4890
4891         tmp = xreadline(NULL, "host[:dir] > ");
4892         if (!tmp[0]) {
4893                 printmsg(messages[MSG_CANCEL]);
4894                 return FALSE;
4895         }
4896
4897         char *div = strchr(tmp, ':');
4898
4899         if (div)
4900                 *div = '\0';
4901
4902         /* Create the mount point */
4903         mkpath(cfgpath, toks[TOK_MNT], mntpath);
4904         mkpath(mntpath, tmp, newpath);
4905         if (!xmktree(newpath, TRUE)) {
4906                 printwarn(NULL);
4907                 return FALSE;
4908         }
4909
4910         if (!div) { /* Convert "host" to "host:" */
4911                 size_t len = xstrlen(tmp);
4912
4913                 tmp[len] = ':';
4914                 tmp[len + 1] = '\0';
4915         } else
4916                 *div = ':';
4917
4918         /* Connect to remote */
4919         if (opt == 's') {
4920                 if (spawn(env, tmp, newpath, NULL, flag)) {
4921                         printmsg(messages[MSG_FAILED]);
4922                         return FALSE;
4923                 }
4924         } else {
4925                 spawn(env, tmp, newpath, NULL, flag);
4926                 printmsg(messages[MSG_RCLONE_DELAY]);
4927                 xdelay(XDELAY_INTERVAL_MS << 2); /* Set 4 times the usual delay */
4928         }
4929
4930         return TRUE;
4931 }
4932
4933 /*
4934  * Unmounts if the directory represented by name is a mount point.
4935  * Otherwise, asks for hostname
4936  * Returns TRUE if directory needs to be refreshed *.
4937  */
4938 static bool unmount(char *name, char *newpath, int *presel, char *currentpath)
4939 {
4940 #if defined(__APPLE__) || defined(__FreeBSD__)
4941         static char cmd[] = "umount";
4942 #else
4943         static char cmd[] = "fusermount3"; /* Arch Linux utility */
4944         static bool found = FALSE;
4945 #endif
4946         char *tmp = name;
4947         struct stat sb, psb;
4948         bool child = FALSE;
4949         bool parent = FALSE;
4950         bool hovered = FALSE;
4951         char mntpath[PATH_MAX];
4952
4953 #if !defined(__APPLE__) && !defined(__FreeBSD__)
4954         /* On Ubuntu it's fusermount */
4955         if (!found && !getutil(cmd)) {
4956                 cmd[10] = '\0';
4957                 found = TRUE;
4958         }
4959 #endif
4960
4961         mkpath(cfgpath, toks[TOK_MNT], mntpath);
4962
4963         if (tmp && strcmp(mntpath, currentpath) == 0) {
4964                 mkpath(mntpath, tmp, newpath);
4965                 child = lstat(newpath, &sb) != -1;
4966                 parent = lstat(xdirname(newpath), &psb) != -1;
4967                 if (!child && !parent) {
4968                         *presel = MSGWAIT;
4969                         return FALSE;
4970                 }
4971         }
4972
4973         if (!tmp || !child || !S_ISDIR(sb.st_mode) || (child && parent && sb.st_dev == psb.st_dev)) {
4974                 tmp = xreadline(NULL, messages[MSG_HOSTNAME]);
4975                 if (!tmp[0])
4976                         return FALSE;
4977                 if (name && (tmp[0] == '-') && (tmp[1] == '\0')) {
4978                         mkpath(currentpath, name, newpath);
4979                         hovered = TRUE;
4980                 }
4981         }
4982
4983         if (!hovered)
4984                 mkpath(mntpath, tmp, newpath);
4985
4986         if (!xdiraccess(newpath)) {
4987                 *presel = MSGWAIT;
4988                 return FALSE;
4989         }
4990
4991 #if defined(__APPLE__) || defined(__FreeBSD__)
4992         if (spawn(cmd, newpath, NULL, NULL, F_NORMAL)) {
4993 #else
4994         if (spawn(cmd, "-qu", newpath, NULL, F_NORMAL)) {
4995 #endif
4996                 if (!xconfirm(get_input(messages[MSG_LAZY])))
4997                         return FALSE;
4998
4999 #ifdef __APPLE__
5000                 if (spawn(cmd, "-l", newpath, NULL, F_NORMAL)) {
5001 #elif defined(__FreeBSD__)
5002                 if (spawn(cmd, "-f", newpath, NULL, F_NORMAL)) {
5003 #else
5004                 if (spawn(cmd, "-quz", newpath, NULL, F_NORMAL)) {
5005 #endif
5006                         printwait(messages[MSG_FAILED], presel);
5007                         return FALSE;
5008                 }
5009         }
5010
5011         if (rmdir(newpath) == -1) {
5012                 printwarn(presel);
5013                 return FALSE;
5014         }
5015
5016         return TRUE;
5017 }
5018
5019 static void lock_terminal(void)
5020 {
5021         spawn(xgetenv("NNN_LOCKER", utils[UTIL_LOCKER]), NULL, NULL, NULL, F_CLI);
5022 }
5023
5024 static void printkv(kv *kvarr, int fd, uchar_t max, uchar_t id)
5025 {
5026         char *val = (id == NNN_BMS) ? bmstr : pluginstr;
5027
5028         for (uchar_t i = 0; i < max && kvarr[i].key; ++i)
5029                 dprintf(fd, " %c: %s\n", (char)kvarr[i].key, val + kvarr[i].off);
5030 }
5031
5032 static void printkeys(kv *kvarr, char *buf, uchar_t max)
5033 {
5034         uchar_t i = 0;
5035
5036         for (; i < max && kvarr[i].key; ++i) {
5037                 buf[i << 1] = ' ';
5038                 buf[(i << 1) + 1] = kvarr[i].key;
5039         }
5040
5041         buf[i << 1] = '\0';
5042 }
5043
5044 static size_t handle_bookmark(const char *bmark, char *newpath)
5045 {
5046         int fd = '\r';
5047         size_t r;
5048
5049         if (maxbm || bmark) {
5050                 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
5051
5052                 if (bmark) { /* There is a marked directory */
5053                         g_buf[--r] = ' ';
5054                         g_buf[++r] = ',';
5055                         g_buf[++r] = '\0';
5056                         ++r;
5057                 }
5058                 printkeys(bookmark, g_buf + r - 1, maxbm);
5059                 printmsg(g_buf);
5060                 fd = get_input(NULL);
5061         }
5062
5063         r = FALSE;
5064         if (fd == ',') /* Visit marked directory */
5065                 bmark ? xstrsncpy(newpath, bmark, PATH_MAX) : (r = MSG_NOT_SET);
5066         else if (fd == '\r') { /* Visit bookmarks directory */
5067                 mkpath(cfgpath, toks[TOK_BM], newpath);
5068                 g_state.selbm = 1;
5069         } else if (!get_kv_val(bookmark, newpath, fd, maxbm, NNN_BMS))
5070                 r = MSG_INVALID_KEY;
5071
5072         if (!r && chdir(newpath) == -1) {
5073                 r = MSG_ACCESS;
5074                 if (g_state.selbm)
5075                         g_state.selbm = 0;
5076         }
5077
5078         return r;
5079 }
5080
5081 static void add_bookmark(char *path, char *newpath, int *presel)
5082 {
5083         char *dir = xbasename(path);
5084
5085         dir = xreadline(dir[0] ? dir : NULL, messages[MSG_BM_NAME]);
5086         if (dir && *dir) {
5087                 size_t r = mkpath(cfgpath, toks[TOK_BM], newpath);
5088
5089                 newpath[r - 1] = '/';
5090                 xstrsncpy(newpath + r, dir, PATH_MAX - r);
5091                 printwait((symlink(path, newpath) == -1) ? strerror(errno) : newpath, presel);
5092         } else
5093                 printwait(messages[MSG_CANCEL], presel);
5094 }
5095
5096 /*
5097  * The help string tokens (each line) start with a HEX value which indicates
5098  * the number of spaces to print before the particular token. In the middle,
5099  * %NN can be used to insert a run of spaces, e.g %10 will print 10 spaces.
5100  * %NN MUST be 2 characters long, e.g %05 for 5 spaces.
5101  *
5102  * This method was chosen instead of a flat string because the number of bytes
5103  * in help was increasing the binary size by around a hundred bytes. This would
5104  * only have increased as we keep adding new options.
5105  */
5106 static void show_help(const char *path)
5107 {
5108         static const char helpstr[] = {
5109         "2|V\\_\n"
5110         "2/. \\\\\n"
5111         "1(;^; ||\n"
5112         "3/___3\n"
5113         "2(___n))\n"
5114         "0\n"
5115         "1NAVIGATION\n"
5116                "9Up k  Up%16PgUp ^U  Page up\n"
5117                "9Dn j  Down%14PgDn ^D  Page down\n"
5118                "9Lt h  Parent%12~ ` @ -  ~, /, start, prev\n"
5119            "5Ret Rt l  Open%20'  First file/match\n"
5120                "9g ^A  Top%21J  Jump to entry/offset\n"
5121                "9G ^E  End%20^J  Toggle auto-advance on open\n"
5122               "8B (,)  Book(mark)%11b ^/  Select bookmark\n"
5123                 "a1-4  Context%11(Sh)Tab  Cycle/new context\n"
5124             "62Esc ^Q  Quit%19^y  Next young\n"
5125                  "b^G  QuitCD%18Q  Pick/err, quit\n"
5126                   "cq  Quit context\n"
5127         "0\n"
5128         "1FILTER & PROMPT\n"
5129                   "c/  Filter%17^N  Toggle type-to-nav\n"
5130                 "aEsc  Exit prompt%12^L  Toggle last filter\n"
5131                   "c.  Toggle hidden%05Alt+Esc  Unfilter, quit context\n"
5132         "0\n"
5133         "1FILES\n"
5134                "9o ^O  Open with%15n  Create new/link\n"
5135                "9f ^F  File stats%14d  Detail mode toggle\n"
5136                  "b^R  Rename/dup%14r  Batch rename\n"
5137                   "cz  Archive%17e  Edit file\n"
5138                   "c*  Toggle exe%14>  Export list\n"
5139             "6Space +  (Un)select%12m-m  Select range/clear\n"
5140                   "ca  Select all%14A  Invert sel\n"
5141                "9p ^P  Copy here%12w ^W  Cp/mv sel as\n"
5142                "9v ^V  Move here%15E  Edit sel list\n"
5143                "9x ^X  Delete%18S  Listed sel size\n"
5144                 "aEsc  Send to FIFO\n"
5145         "0\n"
5146         "1MISC\n"
5147               "8Alt ;  Select plugin%11=  Launch app\n"
5148                "9! ^]  Shell%19]  Cmd prompt\n"
5149                   "cc  Connect remote%10u  Unmount remote/archive\n"
5150                "9t ^T  Sort toggles%12s  Manage session\n"
5151                   "cT  Set time type%110  Lock\n"
5152                  "b^L  Redraw%18?  Help, conf\n"
5153         };
5154
5155         int fd = create_tmp_file();
5156         if (fd == -1)
5157                 return;
5158
5159         char *prog = xgetenv(env_cfg[NNN_HELP], NULL);
5160         if (prog)
5161                 get_output(prog, NULL, NULL, fd, FALSE);
5162
5163         bool hex = true;
5164         char *w = g_buf;
5165         const char *end = helpstr + (sizeof helpstr - 1);
5166         for (const char *s = helpstr; s < end; ++s) {
5167                 if (hex) {
5168                         for (int k = 0, n = xchartohex(*s); k < n; ++k) *w++ = ' ';
5169                 } else if (*s == '%') {
5170                         int n = ((s[1] - '0') * 10) + (s[2] - '0');
5171                         for (int k = 0; k < n; ++k) *w++ = ' ';
5172                         s += 2;
5173                 } else {
5174                         *w++ = *s;
5175                 }
5176                 hex = *s == '\n';
5177         }
5178         if (write(fd, g_buf, w - g_buf)) {} // silence warning
5179
5180         dprintf(fd, "\nLOCATIONS\n");
5181         for (uchar_t i = 0; i < CTX_MAX; ++i)
5182                 if (g_ctx[i].c_cfg.ctxactive)
5183                         dprintf(fd, " %u: %s\n", i + 1, g_ctx[i].c_path);
5184
5185         dprintf(fd, "\nVOLUME: avail:%s ", coolsize(get_fs_info(path, VFS_AVAIL)));
5186         dprintf(fd, "used:%s ", coolsize(get_fs_info(path, VFS_USED)));
5187         dprintf(fd, "size:%s\n\n", coolsize(get_fs_info(path, VFS_SIZE)));
5188
5189         if (bookmark) {
5190                 dprintf(fd, "BOOKMARKS\n");
5191                 printkv(bookmark, fd, maxbm, NNN_BMS);
5192                 dprintf(fd, "\n");
5193         }
5194
5195         if (plug) {
5196                 dprintf(fd, "PLUGIN KEYS\n");
5197                 printkv(plug, fd, maxplug, NNN_PLUG);
5198                 dprintf(fd, "\n");
5199         }
5200
5201         for (uchar_t i = NNN_OPENER; i <= NNN_TRASH; ++i) {
5202                 char *s = getenv(env_cfg[i]);
5203                 if (s)
5204                         dprintf(fd, "%s: %s\n", env_cfg[i], s);
5205         }
5206
5207         if (selpath)
5208                 dprintf(fd, "SELECTION FILE: %s\n", selpath);
5209
5210         dprintf(fd, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
5211         close(fd);
5212
5213         spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
5214         unlink(g_tmpfpath);
5215 }
5216
5217 static void setexports(void)
5218 {
5219         char dvar[] = "d0";
5220         char fvar[] = "f0";
5221
5222         if (ndents) {
5223                 setenv(envs[ENV_NCUR], pdents[cur].name, 1);
5224                 xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
5225         } else if (g_ctx[cfg.curctx].c_name[0])
5226                 g_ctx[cfg.curctx].c_name[0] = '\0';
5227
5228         for (uchar_t i = 0; i < CTX_MAX; ++i) {
5229                 if (g_ctx[i].c_cfg.ctxactive) {
5230                         dvar[1] = fvar[1] = '1' + i;
5231                         setenv(dvar, g_ctx[i].c_path, 1);
5232
5233                         if (g_ctx[i].c_name[0]) {
5234                                 mkpath(g_ctx[i].c_path, g_ctx[i].c_name, g_buf);
5235                                 setenv(fvar, g_buf, 1);
5236                         }
5237                 }
5238         }
5239         setenv("NNN_INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
5240         setenv("NNN_PREFER_SELECTION", xitoa(cfg.prefersel), 1);
5241 }
5242
5243 static void run_cmd_as_plugin(const char *file, uchar_t flags)
5244 {
5245         size_t len;
5246
5247         xstrsncpy(g_buf, file, PATH_MAX);
5248
5249         len = xstrlen(g_buf);
5250         if (len > 1 && g_buf[len - 1] == '*') {
5251                 flags &= ~F_CONFIRM; /* Skip user confirmation */
5252                 g_buf[len - 1] = '\0'; /* Get rid of trailing no confirmation symbol */
5253                 --len;
5254         }
5255
5256         if (flags & F_PAGE)
5257                 get_output(utils[UTIL_SH_EXEC], g_buf, NULL, -1, TRUE);
5258         else
5259                 spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, flags);
5260 }
5261
5262 static bool plctrl_init(void)
5263 {
5264         size_t len;
5265
5266         /* g_tmpfpath is used to generate tmp file names */
5267         g_tmpfpath[tmpfplen - 1] = '\0';
5268         len = xstrsncpy(g_pipepath, g_tmpfpath, TMP_LEN_MAX);
5269         g_pipepath[len - 1] = '/';
5270         len = xstrsncpy(g_pipepath + len, "nnn-pipe.", TMP_LEN_MAX - len) + len;
5271         xstrsncpy(g_pipepath + len - 1, xitoa(getpid()), TMP_LEN_MAX - len);
5272         setenv(env_cfg[NNN_PIPE], g_pipepath, TRUE);
5273
5274         return EXIT_SUCCESS;
5275 }
5276
5277 static void rmlistpath(void)
5278 {
5279         if (listpath) {
5280                 DPRINTF_S(__func__);
5281                 DPRINTF_S(listpath);
5282                 spawn(utils[UTIL_RM_RF], listpath, NULL, NULL, F_NOTRACE | F_MULTI);
5283                 /* Do not free if program was started in list mode */
5284                 if (listpath != initpath)
5285                         free(listpath);
5286                 listpath = NULL;
5287         }
5288 }
5289
5290 static ssize_t read_nointr(int fd, void *buf, size_t count)
5291 {
5292         ssize_t len;
5293
5294         do
5295                 len = read(fd, buf, count);
5296         while (len == -1 && errno == EINTR);
5297
5298         return len;
5299 }
5300
5301 static char *readpipe(int fd, char *ctxnum, char **path)
5302 {
5303         char ctx, *nextpath = NULL;
5304
5305         if (read_nointr(fd, g_buf, 1) != 1)
5306                 return NULL;
5307
5308         if (g_buf[0] == '-') { /* Clear selection on '-' */
5309                 clearselection();
5310                 if (read_nointr(fd, g_buf, 1) != 1)
5311                         return NULL;
5312         }
5313
5314         if (g_buf[0] == '+')
5315                 ctx = (char)(get_free_ctx() + 1);
5316         else if (g_buf[0] < '0')
5317                 return NULL;
5318         else {
5319                 ctx = g_buf[0] - '0';
5320                 if (ctx > CTX_MAX)
5321                         return NULL;
5322         }
5323
5324         if (read_nointr(fd, g_buf, 1) != 1)
5325                 return NULL;
5326
5327         char op = g_buf[0];
5328
5329         if (op == 'c') {
5330                 ssize_t len = read_nointr(fd, g_buf, PATH_MAX);
5331
5332                 if (len <= 0)
5333                         return NULL;
5334
5335                 g_buf[len] = '\0'; /* Terminate the path read */
5336                 if (g_buf[0] == '/') {
5337                         nextpath = g_buf;
5338                         len = xstrlen(g_buf);
5339                         while (--len && (g_buf[len] == '/')) /* Trim all trailing '/' */
5340                                 g_buf[len] = '\0';
5341                 }
5342         } else if (op == 'l') {
5343                 rmlistpath(); /* Remove last list mode path, if any */
5344                 nextpath = load_input(fd, *path);
5345         } else if (op == 'p') {
5346                 free(selpath);
5347                 selpath = NULL;
5348                 clearselection();
5349                 g_state.picker = 0;
5350                 g_state.picked = 1;
5351         }
5352
5353         *ctxnum = ctx;
5354
5355         return nextpath;
5356 }
5357
5358 static bool run_plugin(char **path, const char *file, char *runfile, char **lastname, char **lastdir)
5359 {
5360         pid_t p;
5361         char ctx = 0;
5362         uchar_t flags = 0;
5363         bool cmd_as_plugin = FALSE;
5364         char *nextpath;
5365
5366         if (!g_state.pluginit) {
5367                 plctrl_init();
5368                 g_state.pluginit = 1;
5369         }
5370
5371         setexports();
5372
5373         /* Check for run-cmd-as-plugin mode */
5374         if (*file == '!') {
5375                 flags = F_MULTI | F_CONFIRM;
5376                 ++file;
5377
5378                 if (*file == '|') { /* Check if output should be paged */
5379                         flags |= F_PAGE;
5380                         ++file;
5381                 } else if (*file == '&') { /* Check if GUI flags are to be used */
5382                         flags = F_MULTI | F_NOTRACE | F_NOWAIT;
5383                         ++file;
5384                 }
5385
5386                 if (!*file)
5387                         return FALSE;
5388
5389                 if ((flags & F_NOTRACE) || (flags & F_PAGE)) {
5390                         run_cmd_as_plugin(file, flags);
5391                         return TRUE;
5392                 }
5393
5394                 cmd_as_plugin = TRUE;
5395         }
5396
5397         if (mkfifo(g_pipepath, 0600) != 0)
5398                 return FALSE;
5399
5400         exitcurses();
5401
5402         p = fork();
5403
5404         if (!p) { // In child
5405                 int wfd = open(g_pipepath, O_WRONLY | O_CLOEXEC);
5406
5407                 if (wfd == -1)
5408                         _exit(EXIT_FAILURE);
5409
5410                 if (!cmd_as_plugin) {
5411                         char *sel = NULL;
5412                         char std[2] = "-";
5413
5414                         /* Generate absolute path to plugin */
5415                         mkpath(plgpath, file, g_buf);
5416
5417                         if (g_state.picker)
5418                                 sel = selpath ? selpath : std;
5419
5420                         if (runfile && runfile[0]) {
5421                                 xstrsncpy(*lastname, runfile, NAME_MAX);
5422                                 spawn(g_buf, *lastname, *path, sel, 0);
5423                         } else
5424                                 spawn(g_buf, NULL, *path, sel, 0);
5425                 } else
5426                         run_cmd_as_plugin(file, flags);
5427
5428                 close(wfd);
5429                 _exit(EXIT_SUCCESS);
5430         }
5431
5432         int rfd;
5433
5434         do
5435                 rfd = open(g_pipepath, O_RDONLY);
5436         while (rfd == -1 && errno == EINTR);
5437
5438         nextpath = readpipe(rfd, &ctx, path);
5439         if (nextpath)
5440                 set_smart_ctx(ctx, nextpath, path, runfile, lastname, lastdir);
5441
5442         close(rfd);
5443
5444         /* wait for the child to finish. no zombies allowed */
5445         waitpid(p, NULL, 0);
5446
5447         refresh();
5448
5449         unlink(g_pipepath);
5450
5451         return TRUE;
5452 }
5453
5454 static bool launch_app(char *newpath)
5455 {
5456         int r = F_NORMAL;
5457         char *tmp = newpath;
5458
5459         mkpath(plgpath, utils[UTIL_LAUNCH], newpath);
5460
5461         if (!getutil(utils[UTIL_FZF]) || access(newpath, X_OK) < 0) {
5462                 tmp = xreadline(NULL, messages[MSG_APP_NAME]);
5463                 r = F_NOWAIT | F_NOTRACE | F_MULTI;
5464         }
5465
5466         if (tmp && *tmp) // NOLINT
5467                 spawn(tmp, (r == F_NORMAL) ? "0" : NULL, NULL, NULL, r);
5468
5469         return FALSE;
5470 }
5471
5472 /* Returns TRUE if at least one command was run */
5473 static bool prompt_run(void)
5474 {
5475         bool ret = FALSE;
5476         char *cmdline, *next;
5477         int cnt_j, cnt_J, cmd_ret;
5478         size_t len;
5479
5480         const char *xargs_j = "xargs -0 -I{} %s < %s";
5481         const char *xargs_J = "xargs -0 %s < %s";
5482         char cmd[CMD_LEN_MAX + 32]; // 32 for xargs format strings
5483
5484         while (1) {
5485 #ifndef NORL
5486                 if (g_state.picker || g_state.xprompt) {
5487 #endif
5488                         cmdline = xreadline(NULL, PROMPT);
5489 #ifndef NORL
5490                 } else
5491                         cmdline = getreadline("\n"PROMPT);
5492 #endif
5493                 // Check for an empty command
5494                 if (!cmdline || !cmdline[0])
5495                         break;
5496
5497                 free(lastcmd);
5498                 lastcmd = xstrdup(cmdline);
5499                 ret = TRUE;
5500
5501                 len = xstrlen(cmdline);
5502
5503                 cnt_j = 0;
5504                 next = cmdline;
5505                 while ((next = strstr(next, "%j"))) {
5506                         ++cnt_j;
5507
5508                         // replace %j with {} for xargs later
5509                         next[0] = '{';
5510                         next[1] = '}';
5511
5512                         ++next;
5513                 }
5514
5515                 cnt_J = 0;
5516                 next = cmdline;
5517                 while ((next = strstr(next, "%J"))) {
5518                         ++cnt_J;
5519
5520                         // %J should be the last thing in the command
5521                         if (next == cmdline + len - 2) {
5522                                 cmdline[len - 2] = '\0';
5523                         }
5524
5525                         ++next;
5526                 }
5527
5528                 // We can't handle both %j and %J in a single command
5529                 if (cnt_j && cnt_J)
5530                         break;
5531
5532                 if (cnt_j)
5533                         snprintf(cmd, CMD_LEN_MAX + 32, xargs_j, cmdline, selpath);
5534                 else if (cnt_J)
5535                         snprintf(cmd, CMD_LEN_MAX + 32, xargs_J, cmdline, selpath);
5536
5537                 cmd_ret = spawn(shell, "-c", (cnt_j || cnt_J) ? cmd : cmdline, NULL, F_CLI | F_CONFIRM);
5538                 if ((cnt_j || cnt_J) && cmd_ret == 0)
5539                         clearselection();
5540         }
5541
5542         return ret;
5543 }
5544
5545 static bool handle_cmd(enum action sel, char *newpath)
5546 {
5547         endselection(FALSE);
5548
5549         if (sel == SEL_LAUNCH)
5550                 return launch_app(newpath);
5551
5552         setexports();
5553
5554         if (sel == SEL_PROMPT)
5555                 return prompt_run();
5556
5557         /* Set nnn nesting level */
5558         char *tmp = getenv(env_cfg[NNNLVL]);
5559         int r = tmp ? atoi(tmp) : 0;
5560
5561         setenv(env_cfg[NNNLVL], xitoa(r + 1), 1);
5562         spawn(shell, NULL, NULL, NULL, F_CLI);
5563         setenv(env_cfg[NNNLVL], xitoa(r), 1);
5564         return TRUE;
5565 }
5566
5567 static void dentfree(void)
5568 {
5569         free(pnamebuf);
5570         free(pdents);
5571         free(mark);
5572
5573         /* Thread data cleanup */
5574         free(core_blocks);
5575         free(core_data);
5576         free(core_files);
5577 }
5578
5579 static void *du_thread(void *p_data)
5580 {
5581         thread_data *pdata = (thread_data *)p_data;
5582         char *path[2] = {pdata->path, NULL};
5583         ullong_t tfiles = 0;
5584         blkcnt_t tblocks = 0;
5585         struct stat *sb;
5586         FTS *tree = fts_open(path, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR, 0);
5587         FTSENT *node;
5588
5589         while ((node = fts_read(tree))) {
5590                 if (node->fts_info & FTS_D) {
5591                         if (g_state.interrupt)
5592                                 break;
5593                         continue;
5594                 }
5595
5596                 sb = node->fts_statp;
5597
5598                 if (cfg.apparentsz) {
5599                         if (sb->st_size && DU_TEST)
5600                                 tblocks += sb->st_size;
5601                 } else if (sb->st_blocks && DU_TEST)
5602                         tblocks += sb->st_blocks;
5603
5604                 ++tfiles;
5605         }
5606
5607         fts_close(tree);
5608
5609         if (pdata->entnum >= 0)
5610                 pdents[pdata->entnum].blocks = tblocks;
5611
5612         if (!pdata->mntpoint) {
5613                 core_blocks[pdata->core] += tblocks;
5614                 core_files[pdata->core] += tfiles;
5615         } else
5616                 core_files[pdata->core] += 1;
5617
5618         pthread_mutex_lock(&running_mutex);
5619         threadbmp |= (1 << pdata->core);
5620         --active_threads;
5621         pthread_mutex_unlock(&running_mutex);
5622
5623         return NULL;
5624 }
5625
5626 static void dirwalk(char *path, int entnum, bool mountpoint)
5627 {
5628         /* Loop till any core is free */
5629         while (active_threads == NUM_DU_THREADS);
5630
5631         if (g_state.interrupt)
5632                 return;
5633
5634         pthread_mutex_lock(&running_mutex);
5635         int core = ffs(threadbmp) - 1;
5636
5637         threadbmp &= ~(1 << core);
5638         ++active_threads;
5639         pthread_mutex_unlock(&running_mutex);
5640
5641         xstrsncpy(core_data[core].path, path, PATH_MAX);
5642         core_data[core].entnum = entnum;
5643         core_data[core].core = (ushort_t)core;
5644         core_data[core].mntpoint = mountpoint;
5645
5646         pthread_t tid = 0;
5647
5648         pthread_create(&tid, NULL, du_thread, (void *)&(core_data[core]));
5649
5650         tolastln();
5651         addstr(xbasename(path));
5652         addstr(" [^C aborts]\n");
5653         refresh();
5654 }
5655
5656 static bool prep_threads(void)
5657 {
5658         if (!g_state.duinit) {
5659                 /* drop MSB 1s */
5660                 threadbmp >>= (32 - NUM_DU_THREADS);
5661
5662                 if (!core_blocks)
5663                         core_blocks = calloc(NUM_DU_THREADS, sizeof(blkcnt_t));
5664                 if (!core_data)
5665                         core_data = calloc(NUM_DU_THREADS, sizeof(thread_data));
5666                 if (!core_files)
5667                         core_files = calloc(NUM_DU_THREADS, sizeof(ullong_t));
5668
5669                 if (!core_blocks || !core_data || !core_files) {
5670                         printwarn(NULL);
5671                         return FALSE;
5672                 }
5673 #ifndef __APPLE__
5674                 /* Increase current open file descriptor limit */
5675                 max_openfds();
5676 #endif
5677                 g_state.duinit = TRUE;
5678         } else {
5679                 memset(core_blocks, 0, NUM_DU_THREADS * sizeof(blkcnt_t));
5680                 memset(core_data, 0, NUM_DU_THREADS * sizeof(thread_data));
5681                 memset(core_files, 0, NUM_DU_THREADS * sizeof(ullong_t));
5682         }
5683         return TRUE;
5684 }
5685
5686 /* Skip self and parent */
5687 static inline bool selforparent(const char *path)
5688 {
5689         return path[0] == '.' && (path[1] == '\0' || (path[1] == '.' && path[2] == '\0'));
5690 }
5691
5692 static int dentfill(char *path, struct entry **ppdents)
5693 {
5694         uchar_t entflags = 0;
5695         int flags = 0;
5696         struct dirent *dp;
5697         char *namep, *pnb, *buf;
5698         struct entry *dentp;
5699         size_t off = 0, namebuflen = NAMEBUF_INCR;
5700         struct stat sb_path, sb;
5701         DIR *dirp = opendir(path);
5702
5703         ndents = 0;
5704         gtimesecs = time(NULL);
5705
5706         DPRINTF_S(__func__);
5707
5708         if (!dirp)
5709                 return 0;
5710
5711         int fd = dirfd(dirp);
5712
5713         if (cfg.blkorder) {
5714                 num_files = 0;
5715                 dir_blocks = 0;
5716                 buf = g_buf;
5717
5718                 if (fstatat(fd, path, &sb_path, 0) == -1)
5719                         goto exit;
5720
5721                 if (!ihashbmp) {
5722                         ihashbmp = calloc(1, HASH_OCTETS << 3);
5723                         if (!ihashbmp)
5724                                 goto exit;
5725                 } else
5726                         memset(ihashbmp, 0, HASH_OCTETS << 3);
5727
5728                 if (!prep_threads())
5729                         goto exit;
5730
5731                 attron(COLOR_PAIR(cfg.curctx + 1));
5732         }
5733
5734 #if _POSIX_C_SOURCE >= 200112L
5735         posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
5736 #endif
5737
5738         dp = readdir(dirp);
5739         if (!dp)
5740                 goto exit;
5741
5742 #if defined(__sun) || defined(__HAIKU__)
5743         flags = AT_SYMLINK_NOFOLLOW; /* no d_type */
5744 #else
5745         if (cfg.blkorder || dp->d_type == DT_UNKNOWN) {
5746                 /*
5747                  * Optimization added for filesystems which support dirent.d_type
5748                  * see readdir(3)
5749                  * Known drawbacks:
5750                  * - the symlink size is set to 0
5751                  * - the modification time of the symlink is set to that of the target file
5752                  */
5753                 flags = AT_SYMLINK_NOFOLLOW;
5754         }
5755 #endif
5756
5757         do {
5758                 namep = dp->d_name;
5759
5760                 if (selforparent(namep))
5761                         continue;
5762
5763                 if (!cfg.showhidden && namep[0] == '.') {
5764                         if (!cfg.blkorder)
5765                                 continue;
5766
5767                         if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
5768                                 continue;
5769
5770                         if (S_ISDIR(sb.st_mode)) {
5771                                 if (sb_path.st_dev == sb.st_dev) { // NOLINT
5772                                         mkpath(path, namep, buf); // NOLINT
5773                                         dirwalk(buf, -1, FALSE);
5774
5775                                         if (g_state.interrupt)
5776                                                 goto exit;
5777                                 }
5778                         } else {
5779                                 /* Do not recount hard links */
5780                                 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5781                                         dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5782                                 ++num_files;
5783                         }
5784
5785                         continue;
5786                 }
5787
5788                 if (fstatat(fd, namep, &sb, flags) == -1) {
5789                         if (flags || (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)) {
5790                                 /* Missing file */
5791                                 DPRINTF_U(flags);
5792                                 if (!flags) {
5793                                         DPRINTF_S(namep);
5794                                         DPRINTF_S(strerror(errno));
5795                                 }
5796
5797                                 entflags = FILE_MISSING;
5798                                 memset(&sb, 0, sizeof(struct stat));
5799                         } else /* Orphaned symlink */
5800                                 entflags = SYM_ORPHAN;
5801                 }
5802
5803                 if (ndents == total_dents) {
5804                         if (cfg.blkorder)
5805                                 while (active_threads);
5806
5807                         total_dents += ENTRY_INCR;
5808                         *ppdents = xrealloc(*ppdents, total_dents * sizeof(**ppdents));
5809                         if (!*ppdents) {
5810                                 free(pnamebuf);
5811                                 closedir(dirp);
5812                                 errexit();
5813                         }
5814                         DPRINTF_P(*ppdents);
5815                 }
5816
5817                 /* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
5818                 if (namebuflen - off < NAME_MAX + 1) {
5819                         namebuflen += NAMEBUF_INCR;
5820
5821                         pnb = pnamebuf;
5822                         pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
5823                         if (!pnamebuf) {
5824                                 free(*ppdents);
5825                                 closedir(dirp);
5826                                 errexit();
5827                         }
5828                         DPRINTF_P(pnamebuf);
5829
5830                         /* realloc() may result in memory move, we must re-adjust if that happens */
5831                         if (pnb != pnamebuf) {
5832                                 dentp = *ppdents;
5833                                 dentp->name = pnamebuf;
5834
5835                                 for (int count = 1; count < ndents; ++dentp, ++count)
5836                                         /* Current file name starts at last file name start + length */
5837                                         (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
5838                         }
5839                 }
5840
5841                 dentp = *ppdents + ndents;
5842
5843                 /* Selection file name */
5844                 dentp->name = (char *)((size_t)pnamebuf + off);
5845                 dentp->nlen = xstrsncpy(dentp->name, namep, NAME_MAX + 1);
5846                 off += dentp->nlen;
5847
5848                 /* Copy other fields */
5849                 if (cfg.timetype == T_MOD) {
5850                         dentp->sec = sb.st_mtime;
5851 #ifdef __APPLE__
5852                         dentp->nsec = (uint_t)sb.st_mtimespec.tv_nsec;
5853 #else
5854                         dentp->nsec = (uint_t)sb.st_mtim.tv_nsec;
5855 #endif
5856                 } else if (cfg.timetype == T_ACCESS) {
5857                         dentp->sec = sb.st_atime;
5858 #ifdef __APPLE__
5859                         dentp->nsec = (uint_t)sb.st_atimespec.tv_nsec;
5860 #else
5861                         dentp->nsec = (uint_t)sb.st_atim.tv_nsec;
5862 #endif
5863                 } else {
5864                         dentp->sec = sb.st_ctime;
5865 #ifdef __APPLE__
5866                         dentp->nsec = (uint_t)sb.st_ctimespec.tv_nsec;
5867 #else
5868                         dentp->nsec = (uint_t)sb.st_ctim.tv_nsec;
5869 #endif
5870                 }
5871
5872                 if ((gtimesecs - sb.st_mtime <= 300) || (gtimesecs - sb.st_ctime <= 300))
5873                         entflags |= FILE_YOUNG;
5874
5875 #if !(defined(__sun) || defined(__HAIKU__))
5876                 if (!flags && dp->d_type == DT_LNK) {
5877                          /* Do not add sizes for links */
5878                         dentp->mode = (sb.st_mode & ~S_IFMT) | S_IFLNK;
5879                         dentp->size = listpath ? sb.st_size : 0;
5880                 } else {
5881                         dentp->mode = sb.st_mode;
5882                         dentp->size = sb.st_size;
5883                 }
5884 #else
5885                 dentp->mode = sb.st_mode;
5886                 dentp->size = sb.st_size;
5887 #endif
5888
5889 #ifndef NOUG
5890                 dentp->uid = sb.st_uid;
5891                 dentp->gid = sb.st_gid;
5892 #endif
5893
5894                 dentp->flags = S_ISDIR(sb.st_mode) ? 0 : ((sb.st_nlink > 1) ? HARD_LINK : 0);
5895                 if (entflags) {
5896                         dentp->flags |= entflags;
5897                         entflags = 0;
5898                 }
5899
5900                 if (cfg.blkorder) {
5901                         if (S_ISDIR(sb.st_mode)) {
5902                                 mkpath(path, namep, buf); // NOLINT
5903
5904                                 /* Need to show the disk usage of this dir */
5905                                 dirwalk(buf, ndents, (sb_path.st_dev != sb.st_dev)); // NOLINT
5906
5907                                 if (g_state.interrupt)
5908                                         goto exit;
5909                         } else {
5910                                 dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5911                                 /* Do not recount hard links */
5912                                 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5913                                         dir_blocks += dentp->blocks;
5914                                 ++num_files;
5915                         }
5916                 }
5917
5918                 if (flags) {
5919                         /* Flag if this is a dir or symlink to a dir */
5920                         if (S_ISLNK(sb.st_mode)) {
5921                                 sb.st_mode = 0;
5922                                 fstatat(fd, namep, &sb, 0);
5923                         }
5924
5925                         if (S_ISDIR(sb.st_mode))
5926                                 dentp->flags |= DIR_OR_DIRLNK;
5927 #if !(defined(__sun) || defined(__HAIKU__)) /* no d_type */
5928                 } else if (dp->d_type == DT_DIR || ((dp->d_type == DT_LNK
5929                            || dp->d_type == DT_UNKNOWN) && S_ISDIR(sb.st_mode))) {
5930                         dentp->flags |= DIR_OR_DIRLNK;
5931 #endif
5932                 }
5933
5934                 ++ndents;
5935         } while ((dp = readdir(dirp)));
5936
5937 exit:
5938         if (g_state.duinit && cfg.blkorder) {
5939                 while (active_threads);
5940
5941                 attroff(COLOR_PAIR(cfg.curctx + 1));
5942                 for (int i = 0; i < NUM_DU_THREADS; ++i) {
5943                         num_files += core_files[i];
5944                         dir_blocks += core_blocks[i];
5945                 }
5946         }
5947
5948         /* Should never be null */
5949         if (closedir(dirp) == -1)
5950                 errexit();
5951
5952         return ndents;
5953 }
5954
5955 static void populate(char *path, char *lastname)
5956 {
5957 #ifdef DEBUG
5958         struct timespec ts1, ts2;
5959
5960         clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
5961 #endif
5962
5963         ndents = dentfill(path, &pdents);
5964         if (!ndents)
5965                 return;
5966
5967 #ifndef NOSORT
5968         ENTSORT(pdents, ndents, entrycmpfn);
5969 #endif
5970
5971 #ifdef DEBUG
5972         clock_gettime(CLOCK_REALTIME, &ts2);
5973         DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
5974 #endif
5975
5976         /* Find cur from history */
5977         /* No NULL check for lastname, always points to an array */
5978         move_cursor(*lastname ? dentfind(lastname, ndents) : 0, 0);
5979
5980         // Force full redraw
5981         last_curscroll = -1;
5982 }
5983
5984 #ifndef NOFIFO
5985 static void notify_fifo(bool force)
5986 {
5987         if (!fifopath)
5988                 return;
5989
5990         if (fifofd == -1) {
5991                 fifofd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC);
5992                 if (fifofd == -1) {
5993                         if (errno != ENXIO)
5994                                 /* Unexpected error, the FIFO file might have been removed */
5995                                 /* We give up FIFO notification */
5996                                 fifopath = NULL;
5997                         return;
5998                 }
5999         }
6000
6001         static struct entry lastentry;
6002
6003         if (!force && !memcmp(&lastentry, &pdents[cur], sizeof(struct entry))) // NOLINT
6004                 return;
6005
6006         lastentry = pdents[cur];
6007
6008         char path[PATH_MAX];
6009         size_t len = mkpath(g_ctx[cfg.curctx].c_path, ndents ? pdents[cur].name : "", path);
6010
6011         path[len - 1] = '\n';
6012
6013         ssize_t ret = write(fifofd, path, len);
6014
6015         if (ret != (ssize_t)len && !(ret == -1 && (errno == EAGAIN || errno == EPIPE))) {
6016                 DPRINTF_S(strerror(errno));
6017         }
6018 }
6019
6020 static void send_to_explorer(int *presel)
6021 {
6022         if (nselected) {
6023                 int fd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0600);
6024                 if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
6025                         printwarn(presel);
6026                 else {
6027                         resetselind();
6028                         clearselection();
6029                 }
6030                 if (fd > 1)
6031                         close(fd);
6032         } else
6033                 notify_fifo(TRUE); /* Send opened path to NNN_FIFO */
6034 }
6035 #endif
6036
6037 static void move_cursor(int target, int ignore_scrolloff)
6038 {
6039         int onscreen = xlines - 4; /* Leave top 2 and bottom 2 lines */
6040
6041         target = MAX(0, MIN(ndents - 1, target));
6042         last_curscroll = curscroll;
6043         last = cur;
6044         cur = target;
6045
6046         if (!ignore_scrolloff) {
6047                 int delta = target - last;
6048                 int scrolloff = MIN(SCROLLOFF, onscreen >> 1);
6049
6050                 /*
6051                  * When ignore_scrolloff is 1, the cursor can jump into the scrolloff
6052                  * margin area, but when ignore_scrolloff is 0, act like a boa
6053                  * constrictor and squeeze the cursor towards the middle region of the
6054                  * screen by allowing it to move inward and disallowing it to move
6055                  * outward (deeper into the scrolloff margin area).
6056                  */
6057                 if (((cur < (curscroll + scrolloff)) && delta < 0)
6058                     || ((cur > (curscroll + onscreen - scrolloff - 1)) && delta > 0))
6059                         curscroll += delta;
6060         }
6061         curscroll = MIN(curscroll, MIN(cur, ndents - onscreen));
6062         curscroll = MAX(curscroll, MAX(cur - (onscreen - 1), 0));
6063
6064 #ifndef NOFIFO
6065         if (!g_state.fifomode)
6066                 notify_fifo(FALSE); /* Send hovered path to NNN_FIFO */
6067 #endif
6068 }
6069
6070 static void handle_screen_move(enum action sel)
6071 {
6072         int onscreen;
6073
6074         switch (sel) {
6075         case SEL_NEXT:
6076                 if (cfg.rollover || (cur != ndents - 1))
6077                         move_cursor((cur + 1) % ndents, 0);
6078                 break;
6079         case SEL_PREV:
6080                 if (cfg.rollover || cur)
6081                         move_cursor((cur + ndents - 1) % ndents, 0);
6082                 break;
6083         case SEL_PGDN:
6084                 onscreen = xlines - 4;
6085                 move_cursor(curscroll + (onscreen - 1), 1);
6086                 curscroll += onscreen - 1;
6087                 break;
6088         case SEL_CTRL_D:
6089                 onscreen = xlines - 4;
6090                 move_cursor(curscroll + (onscreen - 1), 1);
6091                 curscroll += onscreen >> 1;
6092                 break;
6093         case SEL_PGUP:
6094                 onscreen = xlines - 4;
6095                 move_cursor(curscroll, 1);
6096                 curscroll -= onscreen - 1;
6097                 break;
6098         case SEL_CTRL_U:
6099                 onscreen = xlines - 4;
6100                 move_cursor(curscroll, 1);
6101                 curscroll -= onscreen >> 1;
6102                 break;
6103         case SEL_JUMP:
6104         {
6105                 char *input = xreadline(NULL, "jump (+n/-n/n): ");
6106
6107                 if (!input || !*input)
6108                         break;
6109                 if (input[0] == '-') {
6110                         cur -= atoi(input + 1);
6111                         if (cur < 0)
6112                                 cur = 0;
6113                 } else if (input[0] == '+') {
6114                         cur += atoi(input + 1);
6115                         if (cur >= ndents)
6116                                 cur = ndents - 1;
6117                 } else {
6118                         int index = atoi(input);
6119
6120                         if ((index < 1) || (index > ndents))
6121                                 break;
6122                         cur = index - 1;
6123                 }
6124                 onscreen = xlines - 4;
6125                 move_cursor(cur, 1);
6126                 curscroll -= onscreen >> 1;
6127                 break;
6128         }
6129         case SEL_HOME:
6130                 move_cursor(0, 1);
6131                 break;
6132         case SEL_END:
6133                 move_cursor(ndents - 1, 1);
6134                 break;
6135         case SEL_YOUNG:
6136         {
6137                 for (int r = cur;;) {
6138                         if (++r >= ndents)
6139                                 r = 0;
6140                         if (r == cur)
6141                                 break;
6142                         if (pdents[r].flags & FILE_YOUNG) {
6143                                 move_cursor(r, 0);
6144                                 break;
6145                         }
6146                 }
6147                 break;
6148         }
6149         default: /* case SEL_FIRST */
6150         {
6151                 int c = get_input(messages[MSG_FIRST]);
6152
6153                 if (!c)
6154                         break;
6155
6156                 c = TOUPPER(c);
6157
6158                 int r = (c == TOUPPER(*pdents[cur].name)) ? (cur + 1) : 0;
6159
6160                 for (; r < ndents; ++r) {
6161                         if (((c == '\'') && !(pdents[r].flags & DIR_OR_DIRLNK))
6162                             || (c == TOUPPER(*pdents[r].name))) {
6163                                 move_cursor((r) % ndents, 0);
6164                                 break;
6165                         }
6166                 }
6167                 break;
6168         }
6169         }
6170 }
6171
6172 static void handle_openwith(const char *path, const char *name, char *newpath, char *tmp)
6173 {
6174         /* Confirm if app is CLI or GUI */
6175         int r = get_input(messages[MSG_CLI_MODE]);
6176
6177         r = (r == 'c' ? F_CLI :
6178              ((r == 'g' || r == '\r') ? (F_NOWAIT | F_NOTRACE | F_MULTI) : 0));
6179         if (r) {
6180                 mkpath(path, name, newpath);
6181                 spawn(tmp, newpath, NULL, NULL, r);
6182         }
6183 }
6184
6185 static void copynextname(char *lastname)
6186 {
6187         if (cur) {
6188                 cur += (cur != (ndents - 1)) ? 1 : -1;
6189                 copycurname();
6190         } else
6191                 lastname[0] = '\0';
6192 }
6193
6194 static int handle_context_switch(enum action sel)
6195 {
6196         int r = -1;
6197
6198         switch (sel) {
6199         case SEL_CYCLE: // fallthrough
6200         case SEL_CYCLER:
6201                 /* visit next and previous contexts */
6202                 r = cfg.curctx;
6203                 if (sel == SEL_CYCLE)
6204                         do
6205                                 r = (r + 1) & ~CTX_MAX;
6206                         while (!g_ctx[r].c_cfg.ctxactive);
6207                 else {
6208                         do /* Attempt to create a new context */
6209                                 r = (r + 1) & ~CTX_MAX;
6210                         while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
6211
6212                         if (r == cfg.curctx) /* If all contexts are active, reverse cycle */
6213                                 do
6214                                         r = (r + (CTX_MAX - 1)) & (CTX_MAX - 1);
6215                                 while (!g_ctx[r].c_cfg.ctxactive);
6216                 } // fallthrough
6217         default: /* SEL_CTXN */
6218                 if (sel >= SEL_CTX1) /* CYCLE keys are lesser in value */
6219                         r = sel - SEL_CTX1; /* Save the next context id */
6220
6221                 if (cfg.curctx == r) {
6222                         if (sel == SEL_CYCLE)
6223                                 (r == CTX_MAX - 1) ? (r = 0) : ++r;
6224                         else if (sel == SEL_CYCLER)
6225                                 (r == 0) ? (r = CTX_MAX - 1) : --r;
6226                         else
6227                                 return -1;
6228                 }
6229         }
6230
6231         return r;
6232 }
6233
6234 static int set_sort_flags(int r)
6235 {
6236         bool session = (r == '\0');
6237         bool reverse = FALSE;
6238
6239         if (ISUPPER_(r) && (r != 'R') && (r != 'C')) {
6240                 reverse = TRUE;
6241                 r = TOLOWER(r);
6242         }
6243
6244         /* Set the correct input in case of a session load */
6245         if (session) {
6246                 if (cfg.apparentsz) {
6247                         cfg.apparentsz = 0;
6248                         r = 'a';
6249                 } else if (cfg.blkorder) {
6250                         cfg.blkorder = 0;
6251                         r = 'd';
6252                 }
6253
6254                 entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
6255                 namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
6256         } else if (r == CONTROL('T')) {
6257                 /* Cycling order: clear -> size -> time -> clear */
6258                 if (cfg.timeorder)
6259                         r = 's';
6260                 else if (cfg.sizeorder)
6261                         r = 'c';
6262                 else
6263                         r = 't';
6264         }
6265
6266         switch (r) {
6267         case 'a': /* Apparent du */
6268                 cfg.apparentsz ^= 1;
6269                 if (cfg.apparentsz) {
6270                         cfg.blkorder = 1;
6271                         blk_shift = 0;
6272                 } else
6273                         cfg.blkorder = 0;
6274                 // fallthrough
6275         case 'd': /* Disk usage */
6276                 if (r == 'd') {
6277                         if (!cfg.apparentsz)
6278                                 cfg.blkorder ^= 1;
6279                         cfg.apparentsz = 0;
6280                         blk_shift = ffs(S_BLKSIZE) - 1;
6281                 }
6282
6283                 if (cfg.blkorder)
6284                         cfg.showdetail = 1;
6285                 cfg.timeorder = 0;
6286                 cfg.sizeorder = 0;
6287                 cfg.extnorder = 0;
6288                 if (!session) {
6289                         cfg.reverse = 0;
6290                         entrycmpfn = &entrycmp;
6291                 }
6292                 endselection(TRUE); /* We are going to reload dir */
6293                 break;
6294         case 'c':
6295                 cfg.timeorder = 0;
6296                 cfg.sizeorder = 0;
6297                 cfg.apparentsz = 0;
6298                 cfg.blkorder = 0;
6299                 cfg.extnorder = 0;
6300                 cfg.reverse = 0;
6301                 cfg.version = 0;
6302                 entrycmpfn = &entrycmp;
6303                 namecmpfn = &xstricmp;
6304                 break;
6305         case 'e': /* File extension */
6306                 cfg.extnorder ^= 1;
6307                 cfg.sizeorder = 0;
6308                 cfg.timeorder = 0;
6309                 cfg.apparentsz = 0;
6310                 cfg.blkorder = 0;
6311                 cfg.reverse = 0;
6312                 entrycmpfn = &entrycmp;
6313                 break;
6314         case 'r': /* Reverse sort */
6315                 cfg.reverse ^= 1;
6316                 entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
6317                 break;
6318         case 's': /* File size */
6319                 cfg.sizeorder ^= 1;
6320                 cfg.timeorder = 0;
6321                 cfg.apparentsz = 0;
6322                 cfg.blkorder = 0;
6323                 cfg.extnorder = 0;
6324                 cfg.reverse = 0;
6325                 entrycmpfn = &entrycmp;
6326                 break;
6327         case 't': /* Time */
6328                 cfg.timeorder ^= 1;
6329                 cfg.sizeorder = 0;
6330                 cfg.apparentsz = 0;
6331                 cfg.blkorder = 0;
6332                 cfg.extnorder = 0;
6333                 cfg.reverse = 0;
6334                 entrycmpfn = &entrycmp;
6335                 break;
6336         case 'v': /* Version */
6337                 cfg.version ^= 1;
6338                 namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
6339                 cfg.timeorder = 0;
6340                 cfg.sizeorder = 0;
6341                 cfg.apparentsz = 0;
6342                 cfg.blkorder = 0;
6343                 cfg.extnorder = 0;
6344                 break;
6345         default:
6346                 return 0;
6347         }
6348
6349         if (reverse) {
6350                 cfg.reverse = 1;
6351                 entrycmpfn = &reventrycmp;
6352         }
6353
6354         cfgsort[cfg.curctx] = (uchar_t)r;
6355
6356         return r;
6357 }
6358
6359 static bool set_time_type(int *presel)
6360 {
6361         bool ret = FALSE;
6362         char buf[] = "'a'ccess / 'c'hange / 'm'od [ ]";
6363
6364         buf[sizeof(buf) - 3] = cfg.timetype == T_MOD ? 'm' : (cfg.timetype == T_ACCESS ? 'a' : 'c');
6365
6366         int r = get_input(buf);
6367
6368         if (r == 'a' || r == 'c' || r == 'm') {
6369                 r = (r == 'm') ? T_MOD : ((r == 'a') ? T_ACCESS : T_CHANGE);
6370                 if (cfg.timetype != r) {
6371                         cfg.timetype = r;
6372
6373                         if (cfg.filtermode || g_ctx[cfg.curctx].c_fltr[1])
6374                                 *presel = FILTER;
6375
6376                         ret = TRUE;
6377                 } else
6378                         r = MSG_NOCHANGE;
6379         } else
6380                 r = MSG_INVALID_KEY;
6381
6382         if (!ret)
6383                 printwait(messages[r], presel);
6384
6385         return ret;
6386 }
6387
6388 static void statusbar(char *path)
6389 {
6390         int i = 0, len = 0;
6391         char *ptr;
6392         pEntry pent = &pdents[cur];
6393
6394         if (!ndents) {
6395                 printmsg("0/0");
6396                 return;
6397         }
6398
6399         /* Get the file extension for regular files */
6400         if (S_ISREG(pent->mode)) {
6401                 i = (int)(pent->nlen - 1);
6402                 ptr = xextension(pent->name, i);
6403                 if (ptr)
6404                         len = i - (ptr - pent->name);
6405                 if (!ptr || len > 5 || len < 2)
6406                         ptr = "\b";
6407         } else
6408                 ptr = "\b";
6409
6410         attron(COLOR_PAIR(cfg.curctx + 1));
6411
6412         if (cfg.fileinfo && get_output("file", "-b", pdents[cur].name, -1, FALSE))
6413                 mvaddstr(xlines - 2, 2, g_buf);
6414
6415         tolastln();
6416
6417         printw("%d/%s ", cur + 1, xitoa(ndents));
6418
6419         if (g_state.selmode || nselected) {
6420                 attron(A_REVERSE);
6421                 addch(' ');
6422                 if (g_state.rangesel)
6423                         addch('*');
6424                 else if (g_state.selmode)
6425                         addch('+');
6426                 if (nselected)
6427                         addstr(xitoa(nselected));
6428                 addch(' ');
6429                 attroff(A_REVERSE);
6430                 addch(' ');
6431         }
6432
6433         if (cfg.blkorder) { /* du mode */
6434                 char buf[24];
6435
6436                 xstrsncpy(buf, coolsize(dir_blocks << blk_shift), 12);
6437
6438                 printw("%cu:%s avail:%s files:%llu %lluB %s\n",
6439                        (cfg.apparentsz ? 'a' : 'd'), buf, coolsize(get_fs_info(path, VFS_AVAIL)),
6440                        num_files, (ullong_t)pent->blocks << blk_shift, ptr);
6441         } else { /* light or detail mode */
6442                 char sort[] = "\0\0\0\0\0";
6443
6444                 if (getorderstr(sort))
6445                         addstr(sort);
6446
6447                 /* Timestamp */
6448                 print_time(&pent->sec, pent->flags);
6449
6450                 addch(' ');
6451                 addstr(get_lsperms(pent->mode));
6452                 addch(' ');
6453 #ifndef NOUG
6454                 if (g_state.uidgid) {
6455                         addstr(getpwname(pent->uid));
6456                         addch(':');
6457                         addstr(getgrname(pent->gid));
6458                         addch(' ');
6459                 }
6460 #endif
6461                 if (S_ISLNK(pent->mode)) {
6462                         if (!cfg.fileinfo) {
6463                                 i = readlink(pent->name, g_buf, PATH_MAX);
6464                                 addstr(coolsize(i >= 0 ? i : pent->size)); /* Show symlink size */
6465                                 if (i > 1) { /* Show symlink target */
6466                                         int y;
6467
6468                                         addstr(" ->");
6469                                         getyx(stdscr, len, y);
6470                                         i = MIN(i, xcols - y);
6471                                         g_buf[i] = '\0';
6472                                         addstr(g_buf);
6473                                 }
6474                         }
6475                 } else {
6476                         addstr(coolsize(pent->size));
6477                         addch(' ');
6478                         addstr(ptr);
6479                         if (pent->flags & HARD_LINK) {
6480                                 struct stat sb;
6481
6482                                 if (stat(pent->name, &sb) != -1) {
6483                                         addch(' ');
6484                                         addstr(xitoa((int)sb.st_nlink)); /* Show number of links */
6485                                         addch('-');
6486                                         addstr(xitoa((int)sb.st_ino)); /* Show inode number */
6487                                 }
6488                         }
6489                 }
6490                 clrtoeol();
6491         }
6492
6493         attroff(COLOR_PAIR(cfg.curctx + 1));
6494         /* Place HW cursor on current for Braille systems */
6495         tocursor();
6496 }
6497
6498 static inline void markhovered(void)
6499 {
6500         if (cfg.showdetail && ndents) { /* Bold forward arrowhead */
6501                 tocursor();
6502                 addch('>' | A_BOLD);
6503         }
6504 }
6505
6506 static int adjust_cols(int n)
6507 {
6508         /* Calculate the number of cols available to print entry name */
6509 #ifdef ICONS_ENABLED
6510         n -= (g_state.oldcolor ? 0 : ICON_SIZE + ICON_PADDING_LEFT_LEN + ICON_PADDING_RIGHT_LEN);
6511 #endif
6512         if (cfg.showdetail) {
6513                 /* Fallback to light mode if less than 35 columns */
6514                 if (n < 36)
6515                         cfg.showdetail ^= 1;
6516                 else /* 2 more accounted for below */
6517                         n -= 32;
6518         }
6519
6520         /* 2 columns for preceding space and indicator */
6521         return (n - 2);
6522 }
6523
6524 static void draw_line(int ncols)
6525 {
6526         bool dir = FALSE;
6527
6528         ncols = adjust_cols(ncols);
6529
6530         if (g_state.oldcolor && (pdents[last].flags & DIR_OR_DIRLNK)) {
6531                 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6532                 dir = TRUE;
6533         }
6534
6535         move(2 + last - curscroll, 0);
6536         macos_icons_hack();
6537         printent(&pdents[last], ncols, FALSE);
6538
6539         if (g_state.oldcolor && (pdents[cur].flags & DIR_OR_DIRLNK)) {
6540                 if (!dir)  {/* First file is not a directory */
6541                         attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6542                         dir = TRUE;
6543                 }
6544         } else if (dir) { /* Second file is not a directory */
6545                 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6546                 dir = FALSE;
6547         }
6548
6549         move(2 + cur - curscroll, 0);
6550         macos_icons_hack();
6551         printent(&pdents[cur], ncols, TRUE);
6552
6553         /* Must reset e.g. no files in dir */
6554         if (dir)
6555                 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6556
6557         markhovered();
6558 }
6559
6560 static void redraw(char *path)
6561 {
6562         getmaxyx(stdscr, xlines, xcols);
6563
6564         int ncols = (xcols <= PATH_MAX) ? xcols : PATH_MAX;
6565         int onscreen = xlines - 4;
6566         int i, j = 1;
6567
6568         // Fast redraw
6569         if (g_state.move) {
6570                 g_state.move = 0;
6571
6572                 if (ndents && (last_curscroll == curscroll))
6573                         return draw_line(ncols);
6574         }
6575
6576         DPRINTF_S(__func__);
6577
6578         /* Clear screen */
6579         erase();
6580
6581         /* Enforce scroll/cursor invariants */
6582         move_cursor(cur, 1);
6583
6584         /* Fail redraw if < than 10 columns, context info prints 10 chars */
6585         if (ncols <= MIN_DISPLAY_COL) {
6586                 printmsg(messages[MSG_FEW_COLUMNS]);
6587                 return;
6588         }
6589
6590         //DPRINTF_D(cur);
6591         DPRINTF_S(path);
6592
6593         for (i = 0; i < CTX_MAX; ++i) { /* 8 chars printed for contexts - "1 2 3 4 " */
6594                 if (!g_ctx[i].c_cfg.ctxactive)
6595                         addch(i + '1');
6596                 else
6597                         addch((i + '1') | (COLOR_PAIR(i + 1) | A_BOLD
6598                                 /* active: underline, current: reverse */
6599                                 | ((cfg.curctx != i) ? A_UNDERLINE : A_REVERSE)));
6600
6601                 addch(' ');
6602         }
6603
6604         attron(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6605
6606         /* Print path */
6607         bool in_home = set_tilde_in_path(path);
6608         char *ptr = in_home ? &path[homelen - 1] : path;
6609
6610         i = (int)xstrlen(ptr);
6611         if ((i + MIN_DISPLAY_COL) <= ncols)
6612                 addnstr(ptr, ncols - MIN_DISPLAY_COL);
6613         else {
6614                 char *base = xmemrchr((uchar_t *)ptr, '/', i);
6615
6616                 if (in_home) {
6617                         addch(*ptr);
6618                         ++ptr;
6619                         i = 1;
6620                 } else
6621                         i = 0;
6622
6623                 if (ptr && (base != ptr)) {
6624                         while (ptr < base) {
6625                                 if (*ptr == '/') {
6626                                         i += 2; /* 2 characters added */
6627                                         if (ncols < i + MIN_DISPLAY_COL) {
6628                                                 base = NULL; /* Can't print more characters */
6629                                                 break;
6630                                         }
6631
6632                                         addch(*ptr);
6633                                         addch(*(++ptr));
6634                                 }
6635                                 ++ptr;
6636                         }
6637                 }
6638
6639                 if (base)
6640                         addnstr(base, ncols - (MIN_DISPLAY_COL + i));
6641         }
6642
6643         if (in_home)
6644                 reset_tilde_in_path(path);
6645
6646         attroff(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6647
6648         /* Go to first entry */
6649         if (curscroll > 0) {
6650                 move(1, 0);
6651 #ifdef ICONS_ENABLED
6652                 addstr(ICON_ARROW_UP);
6653 #else
6654                 addch('^');
6655 #endif
6656         }
6657
6658         if (g_state.oldcolor) {
6659                 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6660                 g_state.dircolor = 1;
6661         }
6662
6663         onscreen = MIN(onscreen + curscroll, ndents);
6664
6665         ncols = adjust_cols(ncols);
6666
6667         int len = scanselforpath(path, FALSE);
6668
6669         /* Print listing */
6670         for (i = curscroll; i < onscreen; ++i) {
6671                 move(++j, 0);
6672
6673                 if (len)
6674                         findmarkentry(len, &pdents[i]);
6675
6676                 printent(&pdents[i], ncols, i == cur);
6677         }
6678
6679         /* Must reset e.g. no files in dir */
6680         if (g_state.dircolor) {
6681                 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6682                 g_state.dircolor = 0;
6683         }
6684
6685         /* Go to last entry */
6686         if (onscreen < ndents) {
6687                 move(xlines - 2, 0);
6688 #ifdef ICONS_ENABLED
6689                 addstr(ICON_ARROW_DOWN);
6690 #else
6691                 addch('v');
6692 #endif
6693         }
6694
6695         markhovered();
6696 }
6697
6698 static bool cdprep(char *lastdir, char *lastname, char *path, char *newpath)
6699 {
6700         if (lastname)
6701                 lastname[0] =  '\0';
6702
6703         /* Save last working directory */
6704         xstrsncpy(lastdir, path, PATH_MAX);
6705
6706         /* Save the newly opted dir in path */
6707         xstrsncpy(path, newpath, PATH_MAX);
6708         DPRINTF_S(path);
6709
6710         clearfilter();
6711         return cfg.filtermode;
6712 }
6713
6714 static void showselsize(const char *path)
6715 {
6716         off_t sz = 0;
6717         int len = scanselforpath(path, FALSE);
6718
6719         for (int r = 0, selcount = nselected; (r < ndents) && selcount; ++r)
6720                 if (findinsel(findselpos, len + xstrsncpy(g_sel + len, pdents[r].name, pdents[r].nlen))) {
6721                         sz += cfg.blkorder ? pdents[r].blocks : pdents[r].size;
6722                         --selcount;
6723                 }
6724
6725         printmsg(coolsize(cfg.blkorder ? sz << blk_shift : sz));
6726 }
6727
6728 static bool browse(char *ipath, const char *session, int pkey)
6729 {
6730         alignas(max_align_t) char newpath[PATH_MAX];
6731         alignas(max_align_t) char runfile[NAME_MAX + 1];
6732         char *path, *lastdir, *lastname, *dir, *tmp;
6733         pEntry pent;
6734         enum action sel;
6735         struct stat sb;
6736         int r = -1, presel, selstartid = 0, selendid = 0;
6737         const uchar_t opener_flags = (cfg.cliopener ? F_CLI : (F_NOTRACE | F_NOSTDIN | F_NOWAIT));
6738         bool watch = FALSE, cd = TRUE;
6739         ino_t inode = 0;
6740
6741 #ifndef NOMOUSE
6742         MEVENT event = {0};
6743         struct timespec mousetimings[2] = {{.tv_sec = 0, .tv_nsec = 0}, {.tv_sec = 0, .tv_nsec = 0}};
6744         int mousedent[2] = {-1, -1};
6745         bool currentmouse = 1, rightclicksel = 0;
6746 #endif
6747
6748         atexit(dentfree);
6749
6750         getmaxyx(stdscr, xlines, xcols);
6751
6752 #ifndef NOSSN
6753         /* set-up first context */
6754         if (!session || !load_session(session, &path, &lastdir, &lastname, FALSE)) {
6755 #else
6756                 (void)session;
6757 #endif
6758                 g_ctx[0].c_last[0] = '\0';
6759                 lastdir = g_ctx[0].c_last; /* last visited directory */
6760
6761                 if (g_state.initfile) {
6762                         xstrsncpy(g_ctx[0].c_name, xbasename(ipath), sizeof(g_ctx[0].c_name));
6763                         xdirname(ipath);
6764                 } else
6765                         g_ctx[0].c_name[0] = '\0';
6766
6767                 lastname = g_ctx[0].c_name; /* last visited file name */
6768
6769                 xstrsncpy(g_ctx[0].c_path, ipath, PATH_MAX);
6770                 /* If the initial path is a file, retain a way to return to start dir */
6771                 if (g_state.initfile) {
6772                         free(initpath);
6773                         initpath = ipath = getcwd(NULL, 0);
6774                 }
6775                 path = g_ctx[0].c_path; /* current directory */
6776
6777                 g_ctx[0].c_fltr[0] = g_ctx[0].c_fltr[1] = '\0';
6778                 g_ctx[0].c_cfg = cfg; /* current configuration */
6779 #ifndef NOSSN
6780         }
6781 #endif
6782
6783         newpath[0] = runfile[0] = '\0';
6784
6785         presel = pkey ? ((pkey == CREATE_NEW_KEY) ? 'n' : ';') : ((cfg.filtermode
6786                         || (session && (g_ctx[cfg.curctx].c_fltr[0] == FILTER
6787                                 || g_ctx[cfg.curctx].c_fltr[0] == RFILTER)
6788                                 && g_ctx[cfg.curctx].c_fltr[1])) ? FILTER : 0);
6789
6790         pdents = xrealloc(pdents, total_dents * sizeof(struct entry));
6791         if (!pdents)
6792                 errexit();
6793
6794         /* Allocate buffer to hold names */
6795         pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
6796         if (!pnamebuf)
6797                 errexit();
6798
6799         /* The following call is added to handle a broken window at start */
6800         if (presel == FILTER)
6801                 handle_key_resize();
6802
6803 begin:
6804         /*
6805          * Can fail when permissions change while browsing.
6806          * It's assumed that path IS a directory when we are here.
6807          */
6808         if (chdir(path) == -1) {
6809                 DPRINTF_S("directory inaccessible");
6810                 valid_parent(path, lastname);
6811                 setdirwatch();
6812         }
6813
6814 #ifndef NOX11
6815         xterm_cfg(path);
6816 #endif
6817
6818 #ifdef LINUX_INOTIFY
6819         if ((presel == FILTER || watch) && inotify_wd >= 0) {
6820                 inotify_rm_watch(inotify_fd, inotify_wd);
6821                 inotify_wd = -1;
6822                 watch = FALSE;
6823         }
6824 #elif defined(BSD_KQUEUE)
6825         if ((presel == FILTER || watch) && event_fd >= 0) {
6826                 close(event_fd);
6827                 event_fd = -1;
6828                 watch = FALSE;
6829         }
6830 #elif defined(HAIKU_NM)
6831         if ((presel == FILTER || watch) && haiku_hnd != NULL) {
6832                 haiku_stop_watch(haiku_hnd);
6833                 haiku_nm_active = FALSE;
6834                 watch = FALSE;
6835         }
6836 #endif
6837
6838         if (order && cd) {
6839                 if (cfgsort[cfg.curctx] != '0') {
6840                         if (cfgsort[cfg.curctx] == 'z')
6841                                 set_sort_flags('c');
6842                         if ((!cfgsort[cfg.curctx] || (cfgsort[cfg.curctx] == 'c'))
6843                             && ((r = get_kv_key(order, path, maxorder, NNN_ORDER)) > 0)) { // NOLINT
6844                                 set_sort_flags(r);
6845                                 cfgsort[cfg.curctx] = 'z';
6846                         }
6847                 } else
6848                         cfgsort[cfg.curctx] = cfgsort[CTX_MAX];
6849         }
6850         cd = TRUE;
6851
6852         populate(path, lastname);
6853         if (g_state.interrupt) {
6854                 g_state.interrupt = cfg.apparentsz = cfg.blkorder = 0;
6855                 blk_shift = BLK_SHIFT_512;
6856                 presel = CONTROL('L');
6857         }
6858
6859 #ifdef LINUX_INOTIFY
6860         if (presel != FILTER && inotify_wd == -1)
6861                 inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
6862 #elif defined(BSD_KQUEUE)
6863         if (presel != FILTER && event_fd == -1) {
6864 #if defined(O_EVTONLY)
6865                 event_fd = open(path, O_EVTONLY);
6866 #else
6867                 event_fd = open(path, O_RDONLY);
6868 #endif
6869                 if (event_fd >= 0)
6870                         EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
6871                                EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
6872         }
6873 #elif defined(HAIKU_NM)
6874         haiku_nm_active = haiku_watch_dir(haiku_hnd, path) == EXIT_SUCCESS;
6875 #endif
6876
6877         while (1) {
6878                 /* Do not do a double redraw in filterentries */
6879                 if ((presel != FILTER) || !filterset()) {
6880                         redraw(path);
6881                         statusbar(path);
6882                 }
6883
6884 nochange:
6885                 /* Exit if parent has exited */
6886                 if (getppid() == 1)
6887                         _exit(EXIT_FAILURE);
6888
6889                 /* If CWD is deleted or moved or perms changed, find an accessible parent */
6890                 if (chdir(path) == -1)
6891                         goto begin;
6892
6893                 /* If STDIN is no longer a tty (closed) we should exit */
6894                 if (!isatty(STDIN_FILENO) && !g_state.picker)
6895                         return EXIT_FAILURE;
6896
6897                 sel = nextsel(presel);
6898                 if (presel)
6899                         presel = 0;
6900
6901                 switch (sel) {
6902 #ifndef NOMOUSE
6903                 case SEL_CLICK:
6904                         if (getmouse(&event) != OK)
6905                                 goto nochange;
6906
6907                         /* Handle clicking on a context at the top */
6908                         if (event.bstate == BUTTON1_PRESSED && event.y == 0) {
6909                                 /* Get context from: "[1 2 3 4]..." */
6910                                 r = event.x >> 1;
6911
6912                                 /* If clicked after contexts, go to parent */
6913                                 if (r >= CTX_MAX)
6914                                         sel = SEL_BACK;
6915                                 else if (r >= 0 && r != cfg.curctx) {
6916                                         savecurctx(path, ndents ? pdents[cur].name : NULL, r);
6917
6918                                         /* Reset the pointers */
6919                                         path = g_ctx[r].c_path;
6920                                         lastdir = g_ctx[r].c_last;
6921                                         lastname = g_ctx[r].c_name;
6922
6923                                         setdirwatch();
6924                                         goto begin;
6925                                 }
6926                         }
6927 #endif
6928                         // fallthrough
6929                 case SEL_BACK:
6930 #ifndef NOMOUSE
6931                         if (sel == SEL_BACK) {
6932 #endif
6933                                 dir = visit_parent(path, newpath, &presel);
6934                                 if (!dir)
6935                                         goto nochange;
6936
6937                                 /* Save history */
6938                                 xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
6939
6940                                 cdprep(lastdir, NULL, path, dir) ? (presel = FILTER) : (watch = TRUE);
6941                                 goto begin;
6942 #ifndef NOMOUSE
6943                         }
6944 #endif
6945
6946 #ifndef NOMOUSE
6947                         /* Middle click action */
6948                         if (event.bstate == BUTTON2_PRESSED) {
6949                                 presel = middle_click_key;
6950                                 goto nochange;
6951                         }
6952 #if NCURSES_MOUSE_VERSION > 1
6953                         /* Scroll up */
6954                         if (event.bstate == BUTTON4_PRESSED && ndents && (cfg.rollover || cur)) {
6955                                 move_cursor((!cfg.rollover && cur < scroll_lines
6956                                                 ? 0 : (cur + ndents - scroll_lines) % ndents), 0);
6957                                 break;
6958                         }
6959
6960                         /* Scroll down */
6961                         if (event.bstate == BUTTON5_PRESSED && ndents
6962                             && (cfg.rollover || (cur != ndents - 1))) {
6963                                 move_cursor((!cfg.rollover && cur >= ndents - scroll_lines)
6964                                                 ? (ndents - 1) : ((cur + scroll_lines) % ndents), 0);
6965                                 break;
6966                         }
6967 #endif
6968
6969                         /* Toggle filter mode on left click on last 2 lines */
6970                         if (event.y >= xlines - 2 && event.bstate == BUTTON1_PRESSED) {
6971                                 clearfilter();
6972                                 cfg.filtermode ^= 1;
6973                                 if (cfg.filtermode) {
6974                                         presel = FILTER;
6975                                         goto nochange;
6976                                 }
6977
6978                                 /* Start watching the directory */
6979                                 watch = TRUE;
6980                                 copycurname();
6981                                 cd = FALSE;
6982                                 goto begin;
6983                         }
6984
6985                         /* Handle clicking on a file */
6986                         if (event.y >= 2 && event.y <= ndents + 1 &&
6987                                         (event.bstate == BUTTON1_PRESSED ||
6988                                          event.bstate == BUTTON3_PRESSED)) {
6989                                 r = curscroll + (event.y - 2);
6990                                 if (r != cur)
6991                                         move_cursor(r, 1);
6992 #ifndef NOFIFO
6993                                 else if ((event.bstate == BUTTON1_PRESSED) && !g_state.fifomode)
6994                                         notify_fifo(TRUE); /* Send clicked path to NNN_FIFO */
6995 #endif
6996                                 /* Handle right click selection */
6997                                 if (event.bstate == BUTTON3_PRESSED) {
6998                                         rightclicksel = 1;
6999                                         presel = SELECT;
7000                                         goto nochange;
7001                                 }
7002
7003                                 currentmouse ^= 1;
7004                                 clock_gettime(
7005 #if defined(CLOCK_MONOTONIC_RAW)
7006                                     CLOCK_MONOTONIC_RAW,
7007 #elif defined(CLOCK_MONOTONIC)
7008                                     CLOCK_MONOTONIC,
7009 #else
7010                                     CLOCK_REALTIME,
7011 #endif
7012                                     &mousetimings[currentmouse]);
7013                                 mousedent[currentmouse] = cur;
7014
7015                                 /* Single click just selects, double click falls through to SEL_OPEN */
7016                                 if ((mousedent[0] != mousedent[1]) ||
7017                                   (((_ABSSUB(mousetimings[0].tv_sec, mousetimings[1].tv_sec) << 30)
7018                                   + (_ABSSUB(mousetimings[0].tv_nsec, mousetimings[1].tv_nsec)))
7019                                         > DBLCLK_INTERVAL_NS))
7020                                         break;
7021                                 /* Double click */
7022                                 mousetimings[currentmouse].tv_sec = 0;
7023                                 mousedent[currentmouse] = -1;
7024                                 sel = SEL_OPEN;
7025                         } else {
7026                                 if (cfg.filtermode || filterset())
7027                                         presel = FILTER;
7028                                 copycurname();
7029                                 goto nochange;
7030                         }
7031 #endif
7032                         // fallthrough
7033                 case SEL_NAV_IN: // fallthrough
7034                 case SEL_OPEN:
7035                         /* Cannot descend in empty directories */
7036                         if (!ndents) {
7037                                 cd = FALSE;
7038                                 g_state.selbm = g_state.runplugin = 0;
7039                                 goto begin;
7040                         }
7041
7042                         pent = &pdents[cur];
7043                         if (!g_state.selbm || !(S_ISLNK(pent->mode) &&
7044                                                 realpath(pent->name, newpath) &&
7045                                                 xstrsncpy(path, lastdir, PATH_MAX)))
7046                                 mkpath(path, pent->name, newpath);
7047                         g_state.selbm = 0;
7048                         DPRINTF_S(newpath);
7049
7050                         /* Visit directory */
7051                         if (pent->flags & DIR_OR_DIRLNK) {
7052                                 if (chdir(newpath) == -1) {
7053                                         printwarn(&presel);
7054                                         goto nochange;
7055                                 }
7056
7057                                 cdprep(lastdir, lastname, path, newpath) ? (presel = FILTER) : (watch = TRUE);
7058                                 goto begin;
7059                         }
7060
7061                         /* Cannot use stale data in entry, file may be missing by now */
7062                         if (stat(newpath, &sb) == -1) {
7063                                 printwarn(&presel);
7064                                 goto nochange;
7065                         }
7066                         DPRINTF_U(sb.st_mode);
7067
7068                         /* Do not open non-regular files */
7069                         if (!S_ISREG(sb.st_mode)) {
7070                                 printwait(messages[MSG_UNSUPPORTED], &presel);
7071                                 goto nochange;
7072                         }
7073
7074                         /* Handle plugin selection mode */
7075                         if (g_state.runplugin) {
7076                                 g_state.runplugin = 0;
7077                                 /* Must be in plugin dir and same context to select plugin */
7078                                 if ((g_state.runctx == cfg.curctx) && !strcmp(path, plgpath)) {
7079                                         endselection(FALSE);
7080                                         /* Copy path so we can return back to earlier dir */
7081                                         xstrsncpy(path, lastdir, PATH_MAX);
7082                                         clearfilter();
7083
7084                                         if (chdir(path) == -1
7085                                             || !run_plugin(&path, pent->name, runfile, &lastname, &lastdir)) {
7086                                                 DPRINTF_S("plugin failed!");
7087                                         }
7088
7089                                         if (g_state.picked)
7090                                                 return EXIT_SUCCESS;
7091
7092                                         if (runfile[0]) {
7093                                                 xstrsncpy(lastname, runfile, NAME_MAX + 1);
7094                                                 runfile[0] = '\0';
7095                                         }
7096                                         setdirwatch();
7097                                         goto begin;
7098                                 }
7099                         }
7100
7101 #ifndef NOFIFO
7102                         if (g_state.fifomode && (sel == SEL_OPEN)) {
7103                                 send_to_explorer(&presel); /* Write selection to explorer fifo */
7104                                 break;
7105                         }
7106 #endif
7107                         /* If opened as vim plugin and Enter/^M pressed, pick */
7108                         if (g_state.picker && (sel == SEL_OPEN)) {
7109                                 if (nselected == 0) /* Pick if none selected */
7110                                         appendfpath(newpath, mkpath(path, pent->name, newpath));
7111                                 return EXIT_SUCCESS;
7112                         }
7113
7114                         if (sel == SEL_NAV_IN) {
7115                                 /* If in listing dir, go to target on `l` or Right on symlink */
7116                                 if (listpath && S_ISLNK(pent->mode)
7117                                     && is_prefix(path, listpath, xstrlen(listpath))) {
7118                                         if (!realpath(pent->name, newpath)) {
7119                                                 printwarn(&presel);
7120                                                 goto nochange;
7121                                         }
7122
7123                                         xdirname(newpath);
7124
7125                                         if (chdir(newpath) == -1) {
7126                                                 printwarn(&presel);
7127                                                 goto nochange;
7128                                         }
7129
7130                                         cdprep(lastdir, NULL, path, newpath)
7131                                                ? (presel = FILTER) : (watch = TRUE);
7132                                         xstrsncpy(lastname, pent->name, NAME_MAX + 1);
7133                                         goto begin;
7134                                 }
7135
7136                                 /* Open file disabled on right arrow or `l` */
7137                                 if (cfg.nonavopen)
7138                                         goto nochange;
7139                         }
7140
7141                         if (!sb.st_size) {
7142                                 printwait(messages[MSG_EMPTY_FILE], &presel);
7143                                 goto nochange;
7144                         }
7145
7146                         if (cfg.useeditor
7147 #ifdef FILE_MIME_OPTS
7148                             && get_output("file", FILE_MIME_OPTS, newpath, -1, FALSE)
7149                             && is_prefix(g_buf, "text/", 5)
7150 #else
7151                             /* no MIME option; guess from description instead */
7152                             && get_output("file", "-bL", newpath, -1, FALSE)
7153                             && strstr(g_buf, "text")
7154 #endif
7155                         ) {
7156                                 spawn(editor, newpath, NULL, NULL, F_CLI);
7157                                 if (cfg.filtermode) {
7158                                         presel = FILTER;
7159                                         clearfilter();
7160                                 }
7161                                 continue;
7162                         }
7163
7164                         /* Get the extension for regex match */
7165                         tmp = xextension(pent->name, pent->nlen - 1);
7166 #ifdef PCRE
7167                         if (tmp && !pcre_exec(archive_pcre, NULL, tmp,
7168                                               pent->nlen - (tmp - pent->name) - 1, 0, 0, NULL, 0)) {
7169 #else
7170                         if (tmp && !regexec(&archive_re, tmp, 0, NULL, 0)) {
7171 #endif
7172                                 r = get_input(messages[MSG_ARCHIVE_OPTS]);
7173                                 if (r == '\r')
7174                                         r = 'l';
7175                                 if (r == 'l' || r == 'x') {
7176                                         mkpath(path, pent->name, newpath);
7177                                         if (!handle_archive(newpath, r)) {
7178                                                 presel = MSGWAIT;
7179                                                 goto nochange;
7180                                         }
7181                                         if (r == 'l') {
7182                                                 statusbar(path);
7183                                                 goto nochange;
7184                                         }
7185                                 }
7186
7187                                 if ((r == 'm') && !archive_mount(newpath)) {
7188                                         presel = MSGWAIT;
7189                                         goto nochange;
7190                                 }
7191
7192                                 if (r == 'x' || r == 'm') {
7193                                         if (newpath[0])
7194                                                 set_smart_ctx('+', newpath, &path,
7195                                                               ndents ? pdents[cur].name : NULL,
7196                                                               &lastname, &lastdir);
7197                                         else
7198                                                 copycurname();
7199                                         clearfilter();
7200                                         goto begin;
7201                                 }
7202
7203                                 if (r != 'o') {
7204                                         printwait(messages[MSG_INVALID_KEY], &presel);
7205                                         goto nochange;
7206                                 }
7207                         }
7208
7209                         /* Invoke desktop opener as last resort */
7210                         spawn(opener, newpath, NULL, NULL, opener_flags);
7211
7212                         /* Move cursor to the next entry if not the last entry */
7213                         if (g_state.autonext && cur != ndents - 1)
7214                                 move_cursor((cur + 1) % ndents, 0);
7215                         if (cfg.filtermode) {
7216                                 presel = FILTER;
7217                                 clearfilter();
7218                         }
7219                         continue;
7220                 case SEL_NEXT: // fallthrough
7221                 case SEL_PREV: // fallthrough
7222                 case SEL_PGDN: // fallthrough
7223                 case SEL_CTRL_D: // fallthrough
7224                 case SEL_PGUP: // fallthrough
7225                 case SEL_CTRL_U: // fallthrough
7226                 case SEL_HOME: // fallthrough
7227                 case SEL_END: // fallthrough
7228                 case SEL_FIRST: // fallthrough
7229                 case SEL_JUMP: // fallthrough
7230                 case SEL_YOUNG:
7231                         if (ndents) {
7232                                 g_state.move = 1;
7233                                 handle_screen_move(sel);
7234                         }
7235                         break;
7236                 case SEL_CDHOME: // fallthrough
7237                 case SEL_CDBEGIN: // fallthrough
7238                 case SEL_CDLAST: // fallthrough
7239                 case SEL_CDROOT:
7240                         dir = (sel == SEL_CDHOME) ? home
7241                                 : ((sel == SEL_CDBEGIN) ? ipath
7242                                 : ((sel == SEL_CDLAST) ? lastdir
7243                                 : "/" /* SEL_CDROOT */));
7244
7245                         if (!dir || !*dir) {
7246                                 printwait(messages[MSG_NOT_SET], &presel);
7247                                 goto nochange;
7248                         }
7249
7250                         g_state.selbm = 0;
7251                         if (strcmp(path, dir) == 0) {
7252                                 if (dir == ipath) {
7253                                         if (cfg.filtermode)
7254                                                 presel = FILTER;
7255                                         goto nochange;
7256                                 }
7257                                 dir = lastdir; /* Go to last dir on home/root key repeat */
7258                         }
7259
7260                         if (chdir(dir) == -1) {
7261                                 presel = MSGWAIT;
7262                                 goto nochange;
7263                         }
7264
7265                         /* SEL_CDLAST: dir pointing to lastdir */
7266                         xstrsncpy(newpath, dir, PATH_MAX); // fallthrough
7267                 case SEL_BMOPEN:
7268                         if (sel == SEL_BMOPEN) {
7269                                 r = (int)handle_bookmark(mark, newpath);
7270                                 if (r) {
7271                                         printwait(messages[r], &presel);
7272                                         goto nochange;
7273                                 }
7274
7275                                 if (g_state.selbm == 1) /* Allow filtering in bookmarks directory */
7276                                         presel = FILTER;
7277                                 if (strcmp(path, newpath) == 0)
7278                                         break;
7279                         }
7280
7281                         /* In list mode, retain the last file name to highlight it, if possible */
7282                         cdprep(lastdir, listpath && sel == SEL_CDLAST ? NULL : lastname, path, newpath)
7283                                ? (presel = FILTER) : (watch = TRUE);
7284                         goto begin;
7285                 case SEL_REMOTE:
7286                         if ((sel == SEL_REMOTE) && !remote_mount(newpath)) {
7287                                 presel = MSGWAIT;
7288                                 goto nochange;
7289                         }
7290
7291                         set_smart_ctx('+', newpath, &path,
7292                                       ndents ? pdents[cur].name : NULL, &lastname, &lastdir);
7293                         clearfilter();
7294                         goto begin;
7295                 case SEL_CYCLE: // fallthrough
7296                 case SEL_CYCLER: // fallthrough
7297                 case SEL_CTX1: // fallthrough
7298                 case SEL_CTX2: // fallthrough
7299                 case SEL_CTX3: // fallthrough
7300                 case SEL_CTX4:
7301 #ifdef CTX8
7302                 case SEL_CTX5:
7303                 case SEL_CTX6:
7304                 case SEL_CTX7:
7305                 case SEL_CTX8:
7306 #endif
7307                         r = handle_context_switch(sel);
7308                         if (r < 0)
7309                                 continue;
7310                         savecurctx(path, ndents ? pdents[cur].name : NULL, r);
7311
7312                         /* Reset the pointers */
7313                         path = g_ctx[r].c_path;
7314                         lastdir = g_ctx[r].c_last;
7315                         lastname = g_ctx[r].c_name;
7316                         tmp = g_ctx[r].c_fltr;
7317
7318                         if (cfg.filtermode || ((tmp[0] == FILTER || tmp[0] == RFILTER) && tmp[1]))
7319                                 presel = FILTER;
7320                         else
7321                                 watch = TRUE;
7322
7323                         goto begin;
7324                 case SEL_MARK:
7325                         free(mark);
7326                         mark = xstrdup(path);
7327                         printwait(mark, &presel);
7328                         goto nochange;
7329                 case SEL_BMARK:
7330                         add_bookmark(path, newpath, &presel);
7331                         goto nochange;
7332                 case SEL_FLTR:
7333                         /* Unwatch dir if we are still in a filtered view */
7334 #ifdef LINUX_INOTIFY
7335                         if (inotify_wd >= 0) {
7336                                 inotify_rm_watch(inotify_fd, inotify_wd);
7337                                 inotify_wd = -1;
7338                         }
7339 #elif defined(BSD_KQUEUE)
7340                         if (event_fd >= 0) {
7341                                 close(event_fd);
7342                                 event_fd = -1;
7343                         }
7344 #elif defined(HAIKU_NM)
7345                         if (haiku_nm_active) {
7346                                 haiku_stop_watch(haiku_hnd);
7347                                 haiku_nm_active = FALSE;
7348                         }
7349 #endif
7350                         presel = filterentries(path, lastname);
7351                         if (presel == ESC) {
7352                                 presel = 0;
7353                                 break;
7354                         }
7355                         if (presel == FILTER) { /* Refresh dir and filter again */
7356                                 cd = FALSE;
7357                                 goto begin;
7358                         }
7359                         goto nochange;
7360                 case SEL_MFLTR: // fallthrough
7361                 case SEL_HIDDEN: // fallthrough
7362                 case SEL_DETAIL: // fallthrough
7363                 case SEL_SORT:
7364                         switch (sel) {
7365                         case SEL_MFLTR:
7366                                 cfg.filtermode ^= 1;
7367                                 if (cfg.filtermode) {
7368                                         presel = FILTER;
7369                                         clearfilter();
7370                                         goto nochange;
7371                                 }
7372
7373                                 watch = TRUE; // fallthrough
7374                         case SEL_HIDDEN:
7375                                 if (sel == SEL_HIDDEN) {
7376                                         cfg.showhidden ^= 1;
7377                                         if (cfg.filtermode)
7378                                                 presel = FILTER;
7379                                         clearfilter();
7380                                 }
7381                                 copycurname();
7382                                 cd = FALSE;
7383                                 goto begin;
7384                         case SEL_DETAIL:
7385                                 cfg.showdetail ^= 1;
7386                                 cfg.blkorder = 0;
7387                                 continue;
7388                         default: /* SEL_SORT */
7389                                 r = set_sort_flags(get_input(messages[MSG_ORDER]));
7390                                 if (!r) {
7391                                         printwait(messages[MSG_INVALID_KEY], &presel);
7392                                         goto nochange;
7393                                 }
7394                         }
7395
7396                         if (cfg.filtermode || filterset())
7397                                 presel = FILTER;
7398
7399                         if (ndents) {
7400                                 copycurname();
7401
7402                                 if (r == 'd' || r == 'a') {
7403                                         presel = 0;
7404                                         goto begin;
7405                                 }
7406
7407                                 ENTSORT(pdents, ndents, entrycmpfn);
7408                                 move_cursor(ndents ? dentfind(lastname, ndents) : 0, 0);
7409                         }
7410                         continue;
7411                 case SEL_STATS: // fallthrough
7412                 case SEL_CHMODX:
7413                         if (ndents) {
7414                                 tmp = (listpath && xstrcmp(path, listpath) == 0) ? listroot : path;
7415                                 mkpath(tmp, pdents[cur].name, newpath);
7416
7417                                 if ((sel == SEL_STATS && !show_stats(newpath))
7418                                     || (lstat(newpath, &sb) == -1)
7419                                     || (sel == SEL_CHMODX && !xchmod(newpath, &sb.st_mode))) {
7420                                         printwarn(&presel);
7421                                         goto nochange;
7422                                 }
7423
7424                                 if (sel == SEL_CHMODX)
7425                                         pdents[cur].mode = sb.st_mode;
7426                         }
7427                         break;
7428                 case SEL_REDRAW: // fallthrough
7429                 case SEL_RENAMEMUL: // fallthrough
7430                 case SEL_HELP: // fallthrough
7431                 case SEL_AUTONEXT: // fallthrough
7432                 case SEL_EDIT: // fallthrough
7433                 case SEL_LOCK:
7434                 {
7435                         bool refresh = FALSE;
7436
7437                         if (ndents)
7438                                 mkpath(path, pdents[cur].name, newpath);
7439                         else if (sel == SEL_EDIT) /* Avoid trying to edit a non-existing file */
7440                                 goto nochange;
7441
7442                         switch (sel) {
7443                         case SEL_REDRAW:
7444                                 refresh = TRUE;
7445                                 break;
7446                         case SEL_RENAMEMUL:
7447                                 endselection(TRUE);
7448                                 setenv("NNN_INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
7449                                 setenv("NNN_PREFER_SELECTION", xitoa(cfg.prefersel), 1);
7450                                 setenv("NNN_LIST", listpath ? listroot : "", 1);
7451
7452                                 if (!(getutil(utils[UTIL_BASH])
7453                                       && plugscript(utils[UTIL_NMV], F_CLI))
7454 #ifndef NOBATCH
7455                                     && !batch_rename()
7456 #endif
7457                                 ) {
7458                                         printwait(messages[MSG_FAILED], &presel);
7459                                         goto nochange;
7460                                 }
7461                                 clearselection();
7462                                 refresh = TRUE;
7463                                 break;
7464                         case SEL_HELP:
7465                                 show_help(path); // fallthrough
7466                         case SEL_AUTONEXT:
7467                                 if (sel == SEL_AUTONEXT)
7468                                         g_state.autonext ^= 1;
7469                                 if (cfg.filtermode)
7470                                         presel = FILTER;
7471                                 copycurname();
7472                                 goto nochange;
7473                         case SEL_EDIT:
7474                                 if (!(g_state.picker || g_state.fifomode))
7475                                         spawn(editor, newpath, NULL, NULL, F_CLI);
7476                                 continue;
7477                         default: /* SEL_LOCK */
7478                                 lock_terminal();
7479                                 break;
7480                         }
7481
7482                         /* In case of successful operation, reload contents */
7483
7484                         /* Continue in type-to-nav mode, if enabled */
7485                         if ((cfg.filtermode || filterset()) && !refresh) {
7486                                 presel = FILTER;
7487                                 goto nochange;
7488                         }
7489
7490                         /* Save current */
7491                         copycurname();
7492                         /* Repopulate as directory content may have changed */
7493                         cd = FALSE;
7494                         goto begin;
7495                 }
7496                 case SEL_SEL:
7497                         if (!ndents)
7498                                 goto nochange;
7499
7500                         startselection();
7501                         if (g_state.rangesel)
7502                                 g_state.rangesel = 0;
7503
7504                         /* Toggle selection status */
7505                         pdents[cur].flags ^= FILE_SELECTED;
7506
7507                         if (pdents[cur].flags & FILE_SELECTED) {
7508                                 ++nselected;
7509                                 appendfpath(newpath, mkpath(path, pdents[cur].name, newpath));
7510                                 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
7511                         } else {
7512                                 --nselected;
7513                                 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
7514                         }
7515
7516 #ifndef NOX11
7517                         if (cfg.x11)
7518                                 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7519 #endif
7520 #ifndef NOMOUSE
7521                         if (rightclicksel)
7522                                 rightclicksel = 0;
7523                         else
7524 #endif
7525                                 /* move cursor to the next entry if this is not the last entry */
7526                                 if (!g_state.stayonsel && (cur != ndents - 1))
7527                                         move_cursor((cur + 1) % ndents, 0);
7528                         break;
7529                 case SEL_SELMUL:
7530                         if (!ndents)
7531                                 goto nochange;
7532
7533                         startselection();
7534                         g_state.rangesel ^= 1;
7535
7536                         if (stat(path, &sb) == -1) {
7537                                 printwarn(&presel);
7538                                 goto nochange;
7539                         }
7540
7541                         if (g_state.rangesel) { /* Range selection started */
7542                                 inode = sb.st_ino;
7543                                 selstartid = cur;
7544                                 continue;
7545                         }
7546
7547                         if (inode != sb.st_ino) {
7548                                 printwait(messages[MSG_DIR_CHANGED], &presel);
7549                                 goto nochange;
7550                         }
7551
7552                         if (cur < selstartid) {
7553                                 selendid = selstartid;
7554                                 selstartid = cur;
7555                         } else
7556                                 selendid = cur;
7557
7558                         /* Clear selection on repeat on same file */
7559                         if (selstartid == selendid) {
7560                                 resetselind();
7561                                 clearselection();
7562                                 break;
7563                         } // fallthrough
7564                 case SEL_SELALL: // fallthrough
7565                 case SEL_SELINV:
7566                         if (sel == SEL_SELALL || sel == SEL_SELINV) {
7567                                 if (!ndents)
7568                                         goto nochange;
7569
7570                                 startselection();
7571                                 if (g_state.rangesel)
7572                                         g_state.rangesel = 0;
7573
7574                                 selstartid = 0;
7575                                 selendid = ndents - 1;
7576                         }
7577
7578                         if ((nselected > LARGESEL) || (nselected && (ndents > LARGESEL))) {
7579                                 printmsg("processing...");
7580                                 refresh();
7581                         }
7582
7583                         r = scanselforpath(path, TRUE); /* Get path length suffixed by '/' */
7584                         ((sel == SEL_SELINV) && findselpos)
7585                                 ? invertselbuf(r) : addtoselbuf(r, selstartid, selendid);
7586
7587 #ifndef NOX11
7588                         if (cfg.x11)
7589                                 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7590 #endif
7591                         continue;
7592                 case SEL_SELEDIT:
7593                         r = editselection();
7594                         if (r <= 0) {
7595                                 r = !r ? MSG_0_SELECTED : MSG_FAILED;
7596                                 printwait(messages[r], &presel);
7597                         } else {
7598 #ifndef NOX11
7599                                 if (cfg.x11)
7600                                         plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7601 #endif
7602                                 cfg.filtermode ?  presel = FILTER : statusbar(path);
7603                         }
7604                         goto nochange;
7605                 case SEL_CP: // fallthrough
7606                 case SEL_MV: // fallthrough
7607                 case SEL_CPMVAS: // fallthrough
7608                 case SEL_RM:
7609                 {
7610                         if (sel == SEL_RM) {
7611                                 r = get_cur_or_sel();
7612                                 if (!r) {
7613                                         statusbar(path);
7614                                         goto nochange;
7615                                 }
7616
7617                                 if (r == 'c') {
7618                                         tmp = (listpath && xstrcmp(path, listpath) == 0)
7619                                               ? listroot : path;
7620                                         mkpath(tmp, pdents[cur].name, newpath);
7621                                         if (!xrm(newpath))
7622                                                 continue;
7623
7624                                         xrmfromsel(tmp, newpath);
7625
7626                                         copynextname(lastname);
7627
7628                                         if (cfg.filtermode || filterset())
7629                                                 presel = FILTER;
7630                                         cd = FALSE;
7631                                         goto begin;
7632                                 }
7633                         }
7634
7635                         (nselected == 1 && (sel == SEL_CP || sel == SEL_MV))
7636                                 ? mkpath(path, xbasename(pselbuf), newpath)
7637                                 : (newpath[0] = '\0');
7638
7639                         endselection(TRUE);
7640
7641                         if (!cpmvrm_selection(sel, path)) {
7642                                 presel = MSGWAIT;
7643                                 goto nochange;
7644                         }
7645
7646                         if (cfg.filtermode)
7647                                 presel = FILTER;
7648                         clearfilter();
7649
7650 #ifndef NOX11
7651                         /* Show notification on operation complete */
7652                         if (cfg.x11)
7653                                 plugscript(utils[UTIL_NTFY], F_NOWAIT | F_NOTRACE);
7654 #endif
7655
7656                         if (newpath[0] && !access(newpath, F_OK))
7657                                 xstrsncpy(lastname, xbasename(newpath), NAME_MAX+1);
7658                         else
7659                                 copycurname();
7660                         cd = FALSE;
7661                         goto begin;
7662                 }
7663                 case SEL_ARCHIVE: // fallthrough
7664                 case SEL_OPENWITH: // fallthrough
7665                 case SEL_NEW: // fallthrough
7666                 case SEL_RENAME:
7667                 {
7668                         int ret = 'n';
7669                         size_t len;
7670
7671                         if (!ndents && (sel == SEL_OPENWITH || sel == SEL_RENAME))
7672                                 break;
7673
7674                         if (sel != SEL_OPENWITH)
7675                                 endselection(TRUE);
7676
7677                         switch (sel) {
7678                         case SEL_ARCHIVE:
7679                                 r = get_cur_or_sel();
7680                                 if (!r) {
7681                                         statusbar(path);
7682                                         goto nochange;
7683                                 }
7684
7685                                 if (r == 's') {
7686                                         if (!selsafe()) {
7687                                                 presel = MSGWAIT;
7688                                                 goto nochange;
7689                                         }
7690
7691                                         tmp = NULL;
7692                                 } else
7693                                         tmp = pdents[cur].name;
7694
7695                                 tmp = xreadline(tmp, messages[MSG_ARCHIVE_NAME]);
7696                                 break;
7697                         case SEL_OPENWITH:
7698 #ifndef NORL
7699                                 if (g_state.picker || g_state.xprompt) {
7700 #endif
7701                                         tmp = xreadline(NULL, messages[MSG_OPEN_WITH]);
7702 #ifndef NORL
7703                                 } else
7704                                         tmp = getreadline(messages[MSG_OPEN_WITH]);
7705 #endif
7706                                 break;
7707                         case SEL_NEW:
7708                                 if (!pkey) {
7709                                         r = get_input(messages[MSG_NEW_OPTS]);
7710                                         if (r == '\r')
7711                                                 r = 'f';
7712                                         tmp = NULL;
7713                                 } else {
7714                                         r = 'f';
7715                                         tmp = g_ctx[0].c_name;
7716                                         pkey = '\0';
7717                                 }
7718
7719                                 if (r == 'f' || r == 'd')
7720                                         tmp = xreadline(tmp, messages[MSG_NEW_PATH]);
7721                                 else if (r == 's' || r == 'h')
7722                                         tmp = xreadline((nselected == 1 && cfg.prefersel) ? xbasename(pselbuf) : NULL,
7723                                                 messages[nselected <= 1 ? MSG_NEW_PATH : MSG_LINK_PREFIX]);
7724                                 else
7725                                         tmp = NULL;
7726                                 break;
7727                         default: /* SEL_RENAME */
7728                                 tmp = xreadline(pdents[cur].name, "");
7729                                 break;
7730                         }
7731
7732                         if (!tmp || !*tmp || is_bad_len_or_dir(tmp))
7733                                 break;
7734
7735                         switch (sel) {
7736                         case SEL_ARCHIVE:
7737                                 if (r == 'c' && strcmp(tmp, pdents[cur].name) == 0)
7738                                         continue; /* Cannot overwrite the hovered file */
7739
7740                                 tmp = abspath(tmp, NULL, newpath);
7741                                 if (!tmp)
7742                                         continue;
7743                                 if (access(tmp, F_OK) == 0) {
7744                                         if (!xconfirm(get_input(messages[MSG_OVERWRITE]))) {
7745                                                 statusbar(path);
7746                                                 goto nochange;
7747                                         }
7748                                 }
7749
7750                                 (r == 's') ? archive_selection(get_archive_cmd(tmp), tmp)
7751                                            : spawn(get_archive_cmd(tmp), tmp, pdents[cur].name,
7752                                                    NULL, F_CLI | F_CONFIRM);
7753
7754                                 if (tmp && (access(tmp, F_OK) == 0)) { /* File created */
7755                                         if (r == 's')
7756                                                 clearselection(); /* Archive operation complete */
7757
7758                                         /* Check if any entry is created in the current directory */
7759                                         tmp = get_cwd_entry(path, tmp, &len);
7760                                         if (tmp) {
7761                                                 xstrsncpy(lastname, tmp, len + 1);
7762                                                 clearfilter(); /* Archive name may not match */
7763                                         } if (cfg.filtermode)
7764                                                 presel = FILTER;
7765                                         cd = FALSE;
7766                                         goto begin;
7767                                 }
7768                                 continue;
7769                         case SEL_OPENWITH:
7770                                 handle_openwith(path, pdents[cur].name, newpath, tmp);
7771
7772                                 cfg.filtermode ?  presel = FILTER : statusbar(path);
7773                                 copycurname();
7774                                 goto nochange;
7775                         case SEL_RENAME:
7776                                 r = 0;
7777                                 /* Skip renaming to same name */
7778                                 if (strcmp(tmp, pdents[cur].name) == 0) {
7779                                         tmp = xreadline(pdents[cur].name, messages[MSG_COPY_NAME]);
7780                                         if (!tmp || !tmp[0] || is_bad_len_or_dir(tmp)
7781                                             || !strcmp(tmp, pdents[cur].name)) {
7782                                                 cfg.filtermode ?  presel = FILTER : statusbar(path);
7783                                                 copycurname();
7784                                                 goto nochange;
7785                                         }
7786                                         ret = 'd';
7787                                 }
7788                                 break;
7789                         default: /* SEL_NEW */
7790                                 break;
7791                         }
7792
7793                         if (!(r == 's' || r == 'h')) {
7794                                 tmp = abspath(tmp, NULL, newpath);
7795                                 if (!tmp) {
7796                                         printwarn(&presel);
7797                                         goto nochange;
7798                                 }
7799                         }
7800
7801                         /* Check if another file with same name exists */
7802                         if (lstat(tmp, &sb) == 0) {
7803                                 if ((sel == SEL_RENAME) || ((r == 'f') && (S_ISREG(sb.st_mode)))) {
7804                                         /* Overwrite file with same name? */
7805                                         if (!xconfirm(get_input(messages[MSG_OVERWRITE])))
7806                                                 break;
7807                                 } else {
7808                                         /* Do nothing for SEL_NEW if a non-regular entry exists */
7809                                         printwait(messages[MSG_EXISTS], &presel);
7810                                         goto nochange;
7811                                 }
7812                         }
7813
7814                         if (sel == SEL_RENAME) {
7815                                 /* Rename the file */
7816                                 if (ret == 'd')
7817                                         spawn("cp -rp", pdents[cur].name, tmp, NULL, F_SILENT);
7818                                 else if (rename(pdents[cur].name, tmp) != 0) {
7819                                         printwarn(&presel);
7820                                         goto nochange;
7821                                 }
7822
7823                                 /* Check if any entry is created in the current directory */
7824                                 tmp = get_cwd_entry(path, tmp, &len);
7825                                 if (tmp)
7826                                         xstrsncpy(lastname, tmp, len + 1);
7827                                 /* Directory must be reloeaded for rename case */
7828                         } else { /* SEL_NEW */
7829                                 presel = 0;
7830
7831                                 /* Check if it's a dir or file */
7832                                 if (r == 'f' || r == 'd') {
7833                                         ret = xmktree(tmp, r == 'f' ? FALSE : TRUE);
7834                                 } else if (r == 's' || r == 'h') {
7835                                         if (nselected > 1 && tmp[0] == '@' && tmp[1] == '\0')
7836                                                 tmp[0] = '\0';
7837                                         ret = xlink(tmp, path, (ndents ? pdents[cur].name : NULL), newpath, r);
7838                                 }
7839
7840                                 if (!ret)
7841                                         printwarn(&presel);
7842
7843                                 if (ret <= 0)
7844                                         goto nochange;
7845
7846                                 if (r == 'f' || r == 'd') {
7847                                         tmp = get_cwd_entry(path, tmp, &len);
7848                                         if (tmp)
7849                                                 xstrsncpy(lastname, tmp, len + 1);
7850                                         else
7851                                                 continue; /* No change in directory */
7852                                 } else if (ndents) {
7853                                         if (cfg.filtermode)
7854                                                 presel = FILTER;
7855                                         copycurname();
7856                                 }
7857                         }
7858                         clearfilter();
7859
7860                         cd = FALSE;
7861                         goto begin;
7862                 }
7863                 case SEL_PLUGIN:
7864                         /* Check if directory is accessible */
7865                         if (!xdiraccess(plgpath)) {
7866                                 printwarn(&presel);
7867                                 goto nochange;
7868                         }
7869
7870                         if (!pkey) {
7871                                 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
7872                                 printkeys(plug, g_buf + r - 1, maxplug);
7873                                 printmsg(g_buf);
7874                                 r = get_input(NULL);
7875                         } else {
7876                                 r = pkey;
7877                                 pkey = '\0';
7878                         }
7879
7880                         if (r != '\r') {
7881                                 endselection(FALSE);
7882                                 tmp = get_kv_val(plug, NULL, r, maxplug, NNN_PLUG);
7883                                 if (!tmp) {
7884                                         printwait(messages[MSG_INVALID_KEY], &presel);
7885                                         goto nochange;
7886                                 }
7887
7888                                 if (tmp[0] == '-' && tmp[1]) {
7889                                         ++tmp;
7890                                         r = FALSE; /* Do not refresh dir after completion */
7891                                 } else
7892                                         r = TRUE;
7893
7894                                 if (!run_plugin(&path, tmp, (ndents ? pdents[cur].name : NULL),
7895                                                          &lastname, &lastdir)) {
7896                                         printwait(messages[MSG_FAILED], &presel);
7897                                         goto nochange;
7898                                 }
7899
7900                                 if (g_state.picked)
7901                                         return EXIT_SUCCESS;
7902
7903                                 copycurname();
7904
7905                                 if (!r) {
7906                                         cfg.filtermode ? presel = FILTER : statusbar(path);
7907                                         goto nochange;
7908                                 }
7909                         } else { /* 'Return/Enter' enters the plugin directory */
7910                                 g_state.runplugin ^= 1;
7911                                 if (!g_state.runplugin) {
7912                                         /*
7913                                          * If toggled, and still in the plugin dir,
7914                                          * switch to original directory
7915                                          */
7916                                         if (strcmp(path, plgpath) == 0) {
7917                                                 xstrsncpy(path, lastdir, PATH_MAX);
7918                                                 xstrsncpy(lastname, runfile, NAME_MAX + 1);
7919                                                 runfile[0] = '\0';
7920                                                 setdirwatch();
7921                                                 goto begin;
7922                                         }
7923
7924                                         /* Otherwise, initiate choosing plugin again */
7925                                         g_state.runplugin = 1;
7926                                 }
7927
7928                                 xstrsncpy(lastdir, path, PATH_MAX);
7929                                 xstrsncpy(path, plgpath, PATH_MAX);
7930                                 if (ndents)
7931                                         xstrsncpy(runfile, pdents[cur].name, NAME_MAX);
7932                                 g_state.runctx = cfg.curctx;
7933                                 lastname[0] = '\0';
7934                                 clearfilter();
7935                         }
7936                         setdirwatch();
7937                         if (g_state.runplugin == 1) /* Allow filtering in plugins directory */
7938                                 presel = FILTER;
7939                         goto begin;
7940                 case SEL_SELSIZE:
7941                         showselsize(path);
7942                         goto nochange;
7943                 case SEL_SHELL: // fallthrough
7944                 case SEL_LAUNCH: // fallthrough
7945                 case SEL_PROMPT:
7946                         r = handle_cmd(sel, newpath);
7947
7948                         /* Continue in type-to-nav mode, if enabled */
7949                         if (cfg.filtermode)
7950                                 presel = FILTER;
7951
7952                         /* Save current */
7953                         copycurname();
7954
7955                         if (!r)
7956                                 goto nochange;
7957
7958                         /* Repopulate as directory content may have changed */
7959                         cd = FALSE;
7960                         goto begin;
7961                 case SEL_UMOUNT:
7962                         presel = MSG_ZERO;
7963                         if (!unmount((ndents ? pdents[cur].name : NULL), newpath, &presel, path)) {
7964                                 if (presel == MSG_ZERO)
7965                                         statusbar(path);
7966                                 goto nochange;
7967                         }
7968
7969                         /* Dir removed, go to next entry */
7970                         copynextname(lastname);
7971                         cd = FALSE;
7972                         goto begin;
7973 #ifndef NOSSN
7974                 case SEL_SESSIONS:
7975                         r = get_input(messages[MSG_SSN_OPTS]);
7976
7977                         if (r == 's') {
7978                                 tmp = xreadline(NULL, messages[MSG_SSN_NAME]);
7979                                 if (tmp && *tmp)
7980                                         save_session(tmp, &presel);
7981                         } else if (r == 'l' || r == 'r') {
7982                                 if (load_session(NULL, &path, &lastdir, &lastname, r == 'r')) {
7983                                         setdirwatch();
7984                                         goto begin;
7985                                 }
7986                         }
7987
7988                         statusbar(path);
7989                         goto nochange;
7990 #endif
7991                 case SEL_EXPORT:
7992                         export_file_list();
7993                         cfg.filtermode ?  presel = FILTER : statusbar(path);
7994                         goto nochange;
7995                 case SEL_TIMETYPE:
7996                         if (!set_time_type(&presel))
7997                                 goto nochange;
7998                         cd = FALSE;
7999                         goto begin;
8000                 case SEL_QUITCTX: // fallthrough
8001                 case SEL_QUITCD: // fallthrough
8002                 case SEL_QUIT:
8003                 case SEL_QUITERR:
8004                         if (sel == SEL_QUITCTX) {
8005                                 int ctx = cfg.curctx;
8006
8007                                 for (r = (ctx - 1) & (CTX_MAX - 1);
8008                                      (r != ctx) && !g_ctx[r].c_cfg.ctxactive;
8009                                      r = ((r - 1) & (CTX_MAX - 1))) {
8010                                 };
8011
8012                                 if (r != ctx) {
8013                                         g_ctx[ctx].c_cfg.ctxactive = 0;
8014
8015                                         /* Switch to next active context */
8016                                         path = g_ctx[r].c_path;
8017                                         lastdir = g_ctx[r].c_last;
8018                                         lastname = g_ctx[r].c_name;
8019
8020                                         cfg = g_ctx[r].c_cfg;
8021                                         /* Restore the global function pointers alongside the cfg. */
8022                                         entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
8023                                         namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
8024
8025                                         cfg.curctx = r;
8026                                         setdirwatch();
8027                                         goto begin;
8028                                 }
8029                         } else if (!g_state.forcequit) {
8030                                 for (r = 0; r < CTX_MAX; ++r)
8031                                         if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
8032                                                 r = get_input(messages[MSG_QUIT_ALL]);
8033                                                 break;
8034                                         }
8035
8036                                 if (!(r == CTX_MAX || xconfirm(r)))
8037                                         break; // fallthrough
8038                         }
8039
8040                         /* CD on Quit */
8041                         tmp = getenv("NNN_TMPFILE");
8042                         if ((sel == SEL_QUITCD) || tmp) {
8043                                 write_lastdir(path, tmp);
8044                                 /* ^G is a way to quit picker mode without picking anything */
8045                                 if ((sel == SEL_QUITCD) && g_state.picker)
8046                                         selbufpos = 0;
8047                         }
8048
8049                         if (sel != SEL_QUITERR)
8050                                 return EXIT_SUCCESS;
8051
8052                         if (selbufpos && !g_state.picker) {
8053                                 /* Pick files to stdout and exit */
8054                                 g_state.picker = 1;
8055                                 free(selpath);
8056                                 selpath = NULL;
8057                                 return EXIT_SUCCESS;
8058                         }
8059
8060                         return EXIT_FAILURE;
8061                 default:
8062                         if (xlines != LINES || xcols != COLS)
8063                                 continue;
8064
8065                         if (idletimeout && idle == idletimeout) {
8066                                 lock_terminal(); /* Locker */
8067                                 idle = 0;
8068                         }
8069
8070                         copycurname();
8071                         goto nochange;
8072                 } /* switch (sel) */
8073         }
8074 }
8075
8076 static char *make_tmp_tree(char **paths, ssize_t entries, const char *prefix)
8077 {
8078         /* tmpdir holds the full path */
8079         /* tmp holds the path without the tmp dir prefix */
8080         int err;
8081         struct stat sb;
8082         char *slash, *tmp;
8083         ssize_t len = xstrlen(prefix);
8084         char *tmpdir = malloc(PATH_MAX);
8085
8086         if (!tmpdir) {
8087                 DPRINTF_S(strerror(errno));
8088                 return NULL;
8089         }
8090
8091         tmp = tmpdir + tmpfplen - 1;
8092         xstrsncpy(tmpdir, g_tmpfpath, tmpfplen);
8093         xstrsncpy(tmp, "/nnnXXXXXX", 11);
8094
8095         /* Points right after the base tmp dir */
8096         tmp += 10;
8097
8098         /* handle the case where files are directly under / */
8099         if (!prefix[1] && (prefix[0] == '/'))
8100                 len = 0;
8101
8102         if (!mkdtemp(tmpdir)) {
8103                 free(tmpdir);
8104
8105                 DPRINTF_S(strerror(errno));
8106                 return NULL;
8107         }
8108
8109         listpath = tmpdir;
8110
8111         for (ssize_t i = 0; i < entries; ++i) {
8112                 if (!paths[i])
8113                         continue;
8114
8115                 err = stat(paths[i], &sb);
8116                 if (err && errno == ENOENT)
8117                         continue;
8118
8119                 /* Don't copy the common prefix */
8120                 xstrsncpy(tmp, paths[i] + len, xstrlen(paths[i]) - len + 1);
8121
8122                 /* Get the dir containing the path */
8123                 slash = xmemrchr((uchar_t *)tmp, '/', xstrlen(paths[i]) - len);
8124                 if (slash)
8125                         *slash = '\0';
8126
8127                 if (access(tmpdir, F_OK)) /* Create directory if it doesn't exist */
8128                         xmktree(tmpdir, TRUE);
8129
8130                 if (slash)
8131                         *slash = '/';
8132
8133                 if (symlink(paths[i], tmpdir)) {
8134                         DPRINTF_S(paths[i]);
8135                         DPRINTF_S(strerror(errno));
8136                 }
8137         }
8138
8139         /* Get the dir in which to start */
8140         *tmp = '\0';
8141         return tmpdir;
8142 }
8143
8144 static char *load_input(int fd, const char *path)
8145 {
8146         size_t i, chunk_count = 1, chunk = 512UL * 1024 /* 512 KiB chunk size */, entries = 0;
8147         char *input = malloc(sizeof(char) * chunk), *tmpdir = NULL;
8148         char cwd[PATH_MAX], *next;
8149         size_t offsets[LIST_FILES_MAX];
8150         char **paths = NULL;
8151         ssize_t input_read, total_read = 0, off = 0;
8152         int msgnum = 0;
8153
8154         if (!input) {
8155                 DPRINTF_S(strerror(errno));
8156                 return NULL;
8157         }
8158
8159         if (!path) {
8160                 if (!getcwd(cwd, PATH_MAX)) {
8161                         free(input);
8162                         return NULL;
8163                 }
8164         } else
8165                 xstrsncpy(cwd, path, PATH_MAX);
8166
8167         while (chunk_count < LIST_INPUT_MAX / chunk && !msgnum) {
8168                 input_read = read(fd, input + total_read, chunk);
8169                 if (input_read < 0) {
8170                         if (errno == EINTR)
8171                                 continue;
8172
8173                         DPRINTF_S(strerror(errno));
8174                         goto malloc_1;
8175                 }
8176
8177                 if (input_read == 0)
8178                         break;
8179
8180                 total_read += input_read;
8181
8182                 while (off < total_read) {
8183                         next = memchr(input + off, '\0', total_read - off);
8184                         if (!next)
8185                                 break;
8186                         ++next;
8187
8188                         if (next - input == off + 1) {
8189                                 off = next - input;
8190                                 continue;
8191                         }
8192
8193                         if (entries == LIST_FILES_MAX) {
8194                                 msgnum = MSG_FILE_LIMIT;
8195                                 break;
8196                         }
8197
8198                         offsets[entries++] = off;
8199                         off = next - input;
8200                 }
8201
8202                 /* We don't need to allocate another chunk */
8203                 if (chunk_count > (total_read + chunk - 1) / chunk)
8204                         continue;
8205
8206                 /* We can never need more than one additional chunk */
8207                 ++chunk_count;
8208                 if (chunk_count > LIST_INPUT_MAX / chunk) {
8209                         msgnum = MSG_SIZE_LIMIT;
8210                         break;
8211                 }
8212
8213                 input = xrealloc(input, chunk_count * chunk);
8214                 if (!input)
8215                         goto malloc_1;
8216         }
8217
8218         /* We close fd outside this function. Any extra data is left to the kernel to handle */
8219
8220         if (off != total_read) {
8221                 if (entries == LIST_FILES_MAX)
8222                         msgnum = MSG_FILE_LIMIT;
8223                 else
8224                         offsets[entries++] = off;
8225         }
8226
8227         DPRINTF_D(entries);
8228         DPRINTF_D(total_read);
8229         DPRINTF_D(chunk_count);
8230
8231         if (!entries) {
8232                 msgnum = MSG_0_ENTRIES;
8233                 goto malloc_1;
8234         }
8235
8236         input[total_read] = '\0';
8237
8238         paths = malloc(entries * sizeof(char *));
8239         if (!paths)
8240                 goto malloc_1;
8241
8242         for (i = 0; i < entries; ++i)
8243                 paths[i] = input + offsets[i];
8244
8245         listroot = malloc(sizeof(char) * PATH_MAX);
8246         if (!listroot)
8247                 goto malloc_1;
8248         listroot[0] = '\0';
8249
8250         DPRINTF_S(paths[0]);
8251
8252         for (i = 0; i < entries; ++i) {
8253                 if (paths[i][0] == '\n' || selforparent(paths[i])) {
8254                         paths[i] = NULL;
8255                         continue;
8256                 }
8257
8258                 paths[i] = abspath(paths[i], cwd, NULL);
8259                 if (!paths[i]) {
8260                         entries = i; // free from the previous entry
8261                         goto malloc_2;
8262                 }
8263
8264                 DPRINTF_S(paths[i]);
8265
8266                 xstrsncpy(g_buf, paths[i], PATH_MAX);
8267                 if (!common_prefix(xdirname(g_buf), listroot)) {
8268                         entries = i + 1; // free from the current entry
8269                         goto malloc_2;
8270                 }
8271
8272                 DPRINTF_S(listroot);
8273         }
8274
8275         DPRINTF_S(listroot);
8276
8277         if (listroot[0])
8278                 tmpdir = make_tmp_tree(paths, entries, listroot);
8279
8280 malloc_2:
8281         for (i = 0; i < entries; ++i)
8282                 free(paths[i]);
8283 malloc_1:
8284         if (msgnum) { /* Check if we are past init stage and show msg */
8285                 if (home) {
8286                         printmsg(messages[msgnum]);
8287                         xdelay(XDELAY_INTERVAL_MS << 2);
8288                 } else {
8289                         msg(messages[msgnum]);
8290                         usleep(XDELAY_INTERVAL_MS << 2);
8291                 }
8292         }
8293
8294         free(input);
8295         free(paths);
8296         return tmpdir;
8297 }
8298
8299 static void check_key_collision(void)
8300 {
8301         wint_t key;
8302         bool bitmap[KEY_MAX] = {FALSE};
8303
8304         for (ullong_t i = 0; i < ELEMENTS(bindings); ++i) {
8305                 key = bindings[i].sym;
8306
8307                 if (bitmap[key])
8308                         dprintf(STDERR_FILENO, "key collision! [%s]\n", keyname(key));
8309                 else
8310                         bitmap[key] = TRUE;
8311         }
8312 }
8313
8314 static void usage(void)
8315 {
8316         dprintf(STDOUT_FILENO,
8317                 "%s: nnn [OPTIONS] [PATH]\n\n"
8318                 "The unorthodox terminal file manager.\n\n"
8319                 "positional args:\n"
8320                 "  PATH   start dir/file [default: .]\n\n"
8321                 "optional args:\n"
8322 #ifndef NOFIFO
8323                 " -a      auto NNN_FIFO\n"
8324 #endif
8325                 " -A      no dir auto-enter during filter\n"
8326                 " -b key  open bookmark key (trumps -s/S)\n"
8327                 " -B      use bsdtar for archives\n"
8328                 " -c      cli-only NNN_OPENER (trumps -e)\n"
8329                 " -C      8-color scheme\n"
8330                 " -d      detail mode\n"
8331                 " -D      dirs in context color\n"
8332                 " -e      text in $VISUAL/$EDITOR/vi\n"
8333                 " -E      internal edits in EDITOR\n"
8334 #ifndef NORL
8335                 " -f      use readline history file\n"
8336 #endif
8337 #ifndef NOFIFO
8338                 " -F val  fifo mode [0:preview 1:explore]\n"
8339 #endif
8340                 " -g      regex filters\n"
8341                 " -H      show hidden files\n"
8342                 " -i      show current file info\n"
8343                 " -J      no auto-advance on selection\n"
8344                 " -K      detect key collision and exit\n"
8345                 " -l val  set scroll lines\n"
8346                 " -n      type-to-nav mode\n"
8347 #ifndef NORL
8348                 " -N      use native prompt\n"
8349 #endif
8350                 " -o      open files only on Enter\n"
8351                 " -p file selection file [-:stdout]\n"
8352                 " -P key  run plugin key\n"
8353                 " -Q      no quit confirmation\n"
8354                 " -r      use advcpmv patched cp, mv\n"
8355                 " -R      no rollover at edges\n"
8356 #ifndef NOSSN
8357                 " -s name load session by name\n"
8358                 " -S      persistent session\n"
8359 #endif
8360                 " -t secs timeout to lock\n"
8361                 " -T key  sort order [a/d/e/r/s/t/v]\n"
8362                 " -u      use selection (no prompt)\n"
8363 #ifndef NOUG
8364                 " -U      show user and group\n"
8365 #endif
8366                 " -V      show version\n"
8367 #ifndef NOX11
8368                 " -x      notis, selection sync, xterm title\n"
8369 #endif
8370                 " -h      show help\n\n"
8371                 "v%s\n%s\n", __func__, VERSION, GENERAL_INFO);
8372 }
8373
8374 static bool setup_config(void)
8375 {
8376         size_t r, len;
8377         char *xdgcfg = getenv("XDG_CONFIG_HOME");
8378         bool xdg = FALSE;
8379
8380         /* Set up configuration file paths */
8381         if (xdgcfg && xdgcfg[0]) {
8382                 DPRINTF_S(xdgcfg);
8383                 if (tilde_is_home(xdgcfg)) {
8384                         r = xstrsncpy(g_buf, home, PATH_MAX);
8385                         xstrsncpy(g_buf + r - 1, xdgcfg + 1, PATH_MAX);
8386                         xdgcfg = g_buf;
8387                         DPRINTF_S(xdgcfg);
8388                 }
8389
8390                 if (!xdiraccess(xdgcfg)) {
8391                         xerror();
8392                         return FALSE;
8393                 }
8394
8395                 len = xstrlen(xdgcfg) + xstrlen("/nnn/bookmarks") + 1;
8396                 xdg = TRUE;
8397         }
8398
8399         if (!xdg)
8400                 len = xstrlen(home) + xstrlen("/.config/nnn/bookmarks") + 1;
8401
8402         cfgpath = (char *)malloc(len);
8403         plgpath = (char *)malloc(len);
8404         if (!cfgpath || !plgpath) {
8405                 xerror();
8406                 return FALSE;
8407         }
8408
8409         if (xdg) {
8410                 xstrsncpy(cfgpath, xdgcfg, len);
8411                 r = len - xstrlen("/nnn/bookmarks");
8412         } else {
8413                 r = xstrsncpy(cfgpath, home, len);
8414
8415                 /* Create ~/.config */
8416                 xstrsncpy(cfgpath + r - 1, "/.config", len - r);
8417                 DPRINTF_S(cfgpath);
8418                 r += 8; /* length of "/.config" */
8419         }
8420
8421         /* Create ~/.config/nnn */
8422         xstrsncpy(cfgpath + r - 1, "/nnn", len - r);
8423         DPRINTF_S(cfgpath);
8424
8425         /* Create bookmarks, sessions, mounts and plugins directories */
8426         for (r = 0; r < ELEMENTS(toks); ++r) {
8427                 mkpath(cfgpath, toks[r], plgpath);
8428                 /* The dirs are created on first run, check if they already exist */
8429                 if (access(plgpath, F_OK) && !xmktree(plgpath, TRUE)) {
8430                         DPRINTF_S(toks[r]);
8431                         xerror();
8432                         return FALSE;
8433                 }
8434         }
8435
8436         /* Set selection file path */
8437         if (!g_state.picker) {
8438                 char *env_sel = xgetenv(env_cfg[NNN_SEL], NULL);
8439
8440                 selpath = env_sel ? xstrdup(env_sel)
8441                                   : (char *)malloc(len + 3); /* Length of "/.config/nnn/.selection" */
8442
8443                 if (!selpath) {
8444                         xerror();
8445                         return FALSE;
8446                 }
8447
8448                 if (!env_sel) {
8449                         r = xstrsncpy(selpath, cfgpath, len + 3);
8450                         xstrsncpy(selpath + r - 1, "/.selection", 12);
8451                         DPRINTF_S(selpath);
8452                 }
8453         }
8454
8455         return TRUE;
8456 }
8457
8458 static bool set_tmp_path(void)
8459 {
8460         char *tmp = "/tmp";
8461         char *path = xdiraccess(tmp) ? tmp : getenv("TMPDIR");
8462
8463         if (!path) {
8464                 msg("set TMPDIR");
8465                 return FALSE;
8466         }
8467
8468         tmpfplen = (uchar_t)xstrsncpy(g_tmpfpath, path, TMP_LEN_MAX);
8469         DPRINTF_S(g_tmpfpath);
8470         DPRINTF_U(tmpfplen);
8471
8472         return TRUE;
8473 }
8474
8475 static void cleanup(void)
8476 {
8477 #ifndef NOX11
8478         if (cfg.x11 && !g_state.picker) {
8479                 printf("\033[23;0t"); /* reset terminal window title */
8480                 fflush(stdout);
8481         }
8482 #endif
8483         free(selpath);
8484         free(plgpath);
8485         free(cfgpath);
8486         free(initpath);
8487         free(bmstr);
8488         free(pluginstr);
8489         free(listroot);
8490         free(ihashbmp);
8491         free(bookmark);
8492         free(plug);
8493         free(lastcmd);
8494 #ifndef NOFIFO
8495         if (g_state.autofifo)
8496                 unlink(fifopath);
8497 #endif
8498         if (g_state.pluginit)
8499                 unlink(g_pipepath);
8500 #ifdef DEBUG
8501         disabledbg();
8502 #endif
8503 }
8504
8505 int main(int argc, char *argv[])
8506 {
8507         char *arg = NULL;
8508         char *session = NULL;
8509         int fd, opt, sort = 0, pkey = '\0'; /* Plugin key */
8510 #ifndef NOMOUSE
8511         mmask_t mask;
8512         char *middle_click_env = xgetenv(env_cfg[NNN_MCLICK], "\0");
8513
8514         middle_click_key = (middle_click_env[0] == '^' && middle_click_env[1])
8515                             ? CONTROL(middle_click_env[1])
8516                             : (uchar_t)middle_click_env[0];
8517 #endif
8518
8519         const char * const env_opts = xgetenv(env_cfg[NNN_OPTS], NULL);
8520         int env_opts_id = env_opts ? (int)xstrlen(env_opts) : -1;
8521 #ifndef NORL
8522         bool rlhist = FALSE;
8523 #endif
8524
8525         while ((opt = (env_opts_id > 0
8526                        ? env_opts[--env_opts_id]
8527                        : getopt(argc, argv, "aAb:BcCdDeEfF:gHiJKl:nNop:P:QrRs:St:T:uUVxh"))) != -1) {
8528                 switch (opt) {
8529 #ifndef NOFIFO
8530                 case 'a':
8531                         g_state.autofifo = 1;
8532                         break;
8533 #endif
8534                 case 'A':
8535                         cfg.autoenter = 0;
8536                         break;
8537                 case 'b':
8538                         if (env_opts_id < 0)
8539                                 arg = optarg;
8540                         break;
8541                 case 'B':
8542                         g_state.usebsdtar = 1;
8543                         break;
8544                 case 'c':
8545                         cfg.cliopener = 1;
8546                         break;
8547                 case 'C':
8548                         g_state.oldcolor = 1;
8549                         break;
8550                 case 'd':
8551                         cfg.showdetail = 1;
8552                         break;
8553                 case 'D':
8554                         g_state.dirctx = 1;
8555                         break;
8556                 case 'e':
8557                         cfg.useeditor = 1;
8558                         break;
8559                 case 'E':
8560                         cfg.waitedit = 1;
8561                         break;
8562                 case 'f':
8563 #ifndef NORL
8564                         rlhist = TRUE;
8565 #endif
8566                         break;
8567 #ifndef NOFIFO
8568                 case 'F':
8569                         if (env_opts_id < 0) {
8570                                 fd = atoi(optarg);
8571                                 if ((fd < 0) || (fd > 1))
8572                                         return EXIT_FAILURE;
8573                                 g_state.fifomode = fd;
8574                         }
8575                         break;
8576 #endif
8577                 case 'g':
8578                         cfg.regex = 1;
8579                         filterfn = &visible_re;
8580                         break;
8581                 case 'H':
8582                         cfg.showhidden = 1;
8583                         break;
8584                 case 'i':
8585                         cfg.fileinfo = 1;
8586                         break;
8587                 case 'J':
8588                         g_state.stayonsel = 1;
8589                         break;
8590                 case 'K':
8591                         check_key_collision();
8592                         return EXIT_SUCCESS;
8593                 case 'l':
8594                         if (env_opts_id < 0)
8595                                 scroll_lines = atoi(optarg);
8596                         break;
8597                 case 'n':
8598                         cfg.filtermode = 1;
8599                         break;
8600 #ifndef NORL
8601                 case 'N':
8602                         g_state.xprompt = 1;
8603                         break;
8604 #endif
8605                 case 'o':
8606                         cfg.nonavopen = 1;
8607                         break;
8608                 case 'p':
8609                         if (env_opts_id >= 0)
8610                                 break;
8611
8612                         g_state.picker = 1;
8613                         if (!(optarg[0] == '-' && optarg[1] == '\0')) {
8614                                 fd = open(optarg, O_WRONLY | O_CREAT, 0600);
8615                                 if (fd == -1) {
8616                                         xerror();
8617                                         return EXIT_FAILURE;
8618                                 }
8619
8620                                 close(fd);
8621                                 selpath = abspath(optarg, NULL, NULL);
8622                                 unlink(selpath);
8623                         }
8624                         break;
8625                 case 'P':
8626                         if (env_opts_id < 0 && !optarg[1])
8627                                 pkey = (uchar_t)optarg[0];
8628                         break;
8629                 case 'Q':
8630                         g_state.forcequit = 1;
8631                         break;
8632                 case 'r':
8633 #ifdef __linux__
8634                         memcpy(cp, PROGRESS_CP, sizeof PROGRESS_CP);
8635                         memcpy(mv, PROGRESS_MV, sizeof PROGRESS_MV);
8636 #endif
8637                         break;
8638                 case 'R':
8639                         cfg.rollover = 0;
8640                         break;
8641 #ifndef NOSSN
8642                 case 's':
8643                         if (env_opts_id < 0)
8644                                 session = optarg;
8645                         break;
8646                 case 'S':
8647                         g_state.prstssn = 1;
8648                         if (!session) /* Support named persistent sessions */
8649                                 session = "@";
8650                         break;
8651 #endif
8652                 case 't':
8653                         if (env_opts_id < 0)
8654                                 idletimeout = atoi(optarg);
8655                         break;
8656                 case 'T':
8657                         if (env_opts_id < 0)
8658                                 sort = (uchar_t)optarg[0];
8659                         break;
8660                 case 'u':
8661                         cfg.prefersel = 1;
8662                         break;
8663                 case 'U':
8664                         g_state.uidgid = 1;
8665                         break;
8666                 case 'V':
8667                         dprintf(STDOUT_FILENO, "%s\n", VERSION);
8668                         return EXIT_SUCCESS;
8669                 case 'x':
8670                         cfg.x11 = 1;
8671                         break;
8672                 case 'h':
8673                         usage();
8674                         return EXIT_SUCCESS;
8675                 default:
8676                         usage();
8677                         return EXIT_FAILURE;
8678                 }
8679                 if (env_opts_id == 0)
8680                         env_opts_id = -1;
8681         }
8682
8683 #ifdef DEBUG
8684         enabledbg();
8685         DPRINTF_S(VERSION);
8686 #endif
8687
8688         /* Prefix for temporary files */
8689         if (!set_tmp_path())
8690                 return EXIT_FAILURE;
8691
8692         atexit(cleanup);
8693
8694         /* Check if we are in path list mode */
8695         if (!isatty(STDIN_FILENO)) {
8696                 /* This is the same as listpath */
8697                 initpath = load_input(STDIN_FILENO, NULL);
8698                 if (!initpath)
8699                         return EXIT_FAILURE;
8700
8701                 /* We return to tty */
8702                 if (!isatty(STDOUT_FILENO)) {
8703                         fd = open(ctermid(NULL), O_RDONLY, 0400);
8704                         dup2(fd, STDIN_FILENO);
8705                         close(fd);
8706                 } else
8707                         dup2(STDOUT_FILENO, STDIN_FILENO);
8708
8709                 if (session)
8710                         session = NULL;
8711         }
8712
8713         home = getenv("HOME");
8714         if (!home) {
8715                 msg("set HOME");
8716                 return EXIT_FAILURE;
8717         }
8718         DPRINTF_S(home);
8719         homelen = (uchar_t)xstrlen(home);
8720
8721         if (!setup_config())
8722                 return EXIT_FAILURE;
8723
8724         /* Get custom opener, if set */
8725         opener = xgetenv(env_cfg[NNN_OPENER], utils[UTIL_OPENER]);
8726         DPRINTF_S(opener);
8727
8728         /* Parse bookmarks string */
8729         if (!parsekvpair(&bookmark, &bmstr, NNN_BMS, &maxbm)) {
8730                 msg(env_cfg[NNN_BMS]);
8731                 return EXIT_FAILURE;
8732         }
8733
8734         /* Parse plugins string */
8735         if (!parsekvpair(&plug, &pluginstr, NNN_PLUG, &maxplug)) {
8736                 msg(env_cfg[NNN_PLUG]);
8737                 return EXIT_FAILURE;
8738         }
8739
8740         /* Parse order string */
8741         if (!parsekvpair(&order, &orderstr, NNN_ORDER, &maxorder)) {
8742                 msg(env_cfg[NNN_ORDER]);
8743                 return EXIT_FAILURE;
8744         }
8745
8746         if (!initpath) {
8747                 if (arg) { /* Open a bookmark directly */
8748                         if (!arg[1]) /* Bookmarks keys are single char */
8749                                 initpath = get_kv_val(bookmark, NULL, *arg, maxbm, NNN_BMS);
8750
8751                         if (!initpath) {
8752                                 msg(messages[MSG_INVALID_KEY]);
8753                                 return EXIT_FAILURE;
8754                         }
8755
8756                         if (session)
8757                                 session = NULL;
8758                 } else if (argc == optind) {
8759                         /* Start in the current directory */
8760                         char *startpath = getenv("PWD");
8761
8762                         initpath = (startpath && *startpath) ? xstrdup(startpath) : getcwd(NULL, 0);
8763                         if (!initpath)
8764                                 initpath = "/";
8765                 } else { /* Open a file */
8766                         arg = argv[optind];
8767                         DPRINTF_S(arg);
8768                         size_t len = xstrlen(arg);
8769
8770                         if (len > 7 && is_prefix(arg, "file://", 7)) {
8771                                 arg = arg + 7;
8772                                 len -= 7;
8773                         }
8774                         initpath = abspath(arg, NULL, NULL);
8775                         DPRINTF_S(initpath);
8776                         if (!initpath) {
8777                                 xerror();
8778                                 return EXIT_FAILURE;
8779                         }
8780
8781                         /* If the file is hidden, enable hidden option */
8782                         if (*xbasename(initpath) == '.')
8783                                 cfg.showhidden = 1;
8784
8785                         /*
8786                          * If nnn is set as the file manager, applications may try to open
8787                          * files by invoking nnn. In that case pass the file path to the
8788                          * desktop opener and exit.
8789                          */
8790                         struct stat sb;
8791
8792                         if (stat(initpath, &sb) == -1) {
8793                                 bool dir = (arg[len - 1] == '/');
8794
8795                                 if (!dir) {
8796                                         arg = xbasename(initpath);
8797                                         initpath = xdirname(initpath);
8798
8799                                         pkey = CREATE_NEW_KEY; /* Override plugin key */
8800                                         g_state.initfile = 1;
8801                                 }
8802                                 if (dir || (arg != initpath)) { /* We have a directory */
8803                                         if (!xdiraccess(initpath) && !xmktree(initpath, TRUE)) {
8804                                                 xerror(); /* Fail if directory cannot be created */
8805                                                 return EXIT_FAILURE;
8806                                         }
8807                                         if (!dir) /* Restore the complete path */
8808                                                 *--arg = '/';
8809                                 }
8810                         } else if (!S_ISDIR(sb.st_mode))
8811                                 g_state.initfile = 1;
8812
8813                         if (session)
8814                                 session = NULL;
8815                 }
8816         }
8817
8818         /* Set archive handling (enveditor used as tmp var) */
8819         enveditor = getenv(env_cfg[NNN_ARCHIVE]);
8820 #ifdef PCRE
8821         if (setfilter(&archive_pcre, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8822 #else
8823         if (setfilter(&archive_re, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8824 #endif
8825                 msg(messages[MSG_INVALID_REG]);
8826                 return EXIT_FAILURE;
8827         }
8828
8829         /* An all-CLI opener overrides option -e) */
8830         if (cfg.cliopener)
8831                 cfg.useeditor = 0;
8832
8833         /* Get VISUAL/EDITOR */
8834         enveditor = xgetenv(envs[ENV_EDITOR], utils[UTIL_VI]);
8835         editor = xgetenv(envs[ENV_VISUAL], enveditor);
8836         DPRINTF_S(getenv(envs[ENV_VISUAL]));
8837         DPRINTF_S(getenv(envs[ENV_EDITOR]));
8838         DPRINTF_S(editor);
8839
8840         /* Get PAGER */
8841         pager = xgetenv(envs[ENV_PAGER], utils[UTIL_LESS]);
8842         DPRINTF_S(pager);
8843
8844         /* Get SHELL */
8845         shell = xgetenv(envs[ENV_SHELL], utils[UTIL_SH]);
8846         DPRINTF_S(shell);
8847
8848         DPRINTF_S(getenv("PWD"));
8849
8850 #ifndef NOFIFO
8851         /* Create fifo */
8852         if (g_state.autofifo) {
8853                 g_tmpfpath[tmpfplen - 1] = '\0';
8854
8855                 size_t r = mkpath(g_tmpfpath, "nnn-fifo.", g_buf);
8856
8857                 xstrsncpy(g_buf + r - 1, xitoa(getpid()), PATH_MAX - r);
8858                 setenv("NNN_FIFO", g_buf, TRUE);
8859         }
8860
8861         fifopath = xgetenv("NNN_FIFO", NULL);
8862         if (fifopath) {
8863                 if (mkfifo(fifopath, 0600) != 0 && !(errno == EEXIST && access(fifopath, W_OK) == 0)) {
8864                         xerror();
8865                         return EXIT_FAILURE;
8866                 }
8867
8868                 sigaction(SIGPIPE, &(struct sigaction){.sa_handler = SIG_IGN}, NULL);
8869         }
8870 #endif
8871
8872 #ifdef LINUX_INOTIFY
8873         /* Initialize inotify */
8874         inotify_fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
8875         if (inotify_fd < 0) {
8876                 xerror();
8877                 return EXIT_FAILURE;
8878         }
8879 #elif defined(BSD_KQUEUE)
8880         kq = kqueue();
8881         if (kq < 0) {
8882                 xerror();
8883                 return EXIT_FAILURE;
8884         }
8885 #elif defined(HAIKU_NM)
8886         haiku_hnd = haiku_init_nm();
8887         if (!haiku_hnd) {
8888                 xerror();
8889                 return EXIT_FAILURE;
8890         }
8891 #endif
8892
8893         /* Configure trash preference */
8894         opt = xgetenv_val(env_cfg[NNN_TRASH]);
8895         if (opt && opt <= 2)
8896                 g_state.trash = opt;
8897
8898         /* Ignore/handle certain signals */
8899         struct sigaction act = {.sa_handler = sigint_handler};
8900
8901         if (sigaction(SIGINT, &act, NULL) < 0) {
8902                 xerror();
8903                 return EXIT_FAILURE;
8904         }
8905
8906         act.sa_handler = clean_exit_sighandler;
8907
8908         if (sigaction(SIGTERM, &act, NULL) < 0 || sigaction(SIGHUP, &act, NULL) < 0) {
8909                 xerror();
8910                 return EXIT_FAILURE;
8911         }
8912
8913         act.sa_handler = SIG_IGN;
8914
8915         if (sigaction(SIGQUIT, &act, NULL) < 0) {
8916                 xerror();
8917                 return EXIT_FAILURE;
8918         }
8919
8920 #ifndef NOLC
8921         /* Set locale */
8922         setlocale(LC_ALL, "");
8923 #ifdef PCRE
8924         tables = pcre_maketables();
8925 #endif
8926 #endif
8927
8928 #ifndef NORL
8929 #if RL_READLINE_VERSION >= 0x0603
8930         /* readline would overwrite the WINCH signal hook */
8931         rl_change_environment = 0;
8932 #endif
8933         /* Bind TAB to cycling */
8934         rl_variable_bind("completion-ignore-case", "on");
8935 #ifdef __linux__
8936         rl_bind_key('\t', rl_menu_complete);
8937 #else
8938         rl_bind_key('\t', rl_complete);
8939 #endif
8940         if (rlhist) {
8941                 mkpath(cfgpath, ".history", g_buf);
8942                 read_history(g_buf);
8943         }
8944 #endif
8945
8946 #ifndef NOX11
8947         if (cfg.x11 && !g_state.picker) {
8948                 /* Save terminal window title */
8949                 printf("\033[22;0t");
8950                 fflush(stdout);
8951                 gethostname(hostname, sizeof(hostname));
8952                 hostname[sizeof(hostname) - 1] = '\0';
8953         }
8954 #endif
8955
8956 #ifndef NOMOUSE
8957         if (!initcurses(&mask))
8958 #else
8959         if (!initcurses(NULL))
8960 #endif
8961                 return EXIT_FAILURE;
8962
8963         if (sort)
8964                 set_sort_flags(sort);
8965
8966         opt = browse(initpath, session, pkey);
8967
8968 #ifndef NOSSN
8969         if (session && g_state.prstssn)
8970                 save_session(session, NULL);
8971 #endif
8972
8973 #ifndef NOMOUSE
8974         mousemask(mask, NULL);
8975 #endif
8976
8977         exitcurses();
8978
8979 #ifndef NORL
8980         if (rlhist && !g_state.xprompt) {
8981                 mkpath(cfgpath, ".history", g_buf);
8982                 write_history(g_buf);
8983         }
8984 #endif
8985
8986         if (g_state.picker) {
8987                 if (selbufpos) {
8988                         fd = selpath ? open(selpath, O_WRONLY | O_CREAT | O_TRUNC, 0600) : STDOUT_FILENO;
8989                         if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
8990                                 xerror();
8991
8992                         if (fd > 1)
8993                                 close(fd);
8994                 }
8995         } else if (selpath)
8996                 unlink(selpath);
8997
8998         /* Remove tmp dir in list mode */
8999         rmlistpath();
9000
9001         /* Free the regex */
9002 #ifdef PCRE
9003         pcre_free(archive_pcre);
9004 #else
9005         regfree(&archive_re);
9006 #endif
9007
9008         /* Free the selection buffer */
9009         free(pselbuf);
9010
9011 #ifdef LINUX_INOTIFY
9012         /* Shutdown inotify */
9013         if (inotify_wd >= 0)
9014                 inotify_rm_watch(inotify_fd, inotify_wd);
9015         close(inotify_fd);
9016 #elif defined(BSD_KQUEUE)
9017         if (event_fd >= 0)
9018                 close(event_fd);
9019         close(kq);
9020 #elif defined(HAIKU_NM)
9021         haiku_close_nm(haiku_hnd);
9022 #endif
9023
9024 #ifndef NOFIFO
9025         if (!g_state.fifomode)
9026                 notify_fifo(FALSE);
9027         if (fifofd != -1)
9028                 close(fifofd);
9029 #endif
9030
9031         return opt;
9032 }