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