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