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