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