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