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>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
12 * * Redistributions of source code must retain the above copyright notice, this
13 * list of conditions and the following disclaimer.
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.
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.
31 #if defined(__linux__) || defined(MINGW) || defined(__MINGW32__) \
32 || defined(__MINGW64__) || defined(__CYGWIN__)
36 #if defined(__arm__) || defined(__i386__)
37 #define _FILE_OFFSET_BITS 64 /* Support large files on 32-bit */
39 #if defined(__linux__)
40 #include <sys/inotify.h>
43 #if !defined(__GLIBC__)
44 #include <sys/types.h>
47 #include <sys/resource.h>
49 #include <sys/statvfs.h>
50 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
51 #include <sys/types.h>
52 #include <sys/event.h>
55 #elif defined(__HAIKU__)
56 #include "../misc/haiku/haiku_interop.h"
59 #include <sys/sysmacros.h>
63 #ifdef __linux__ /* Fix failure due to mvaddnwstr() */
64 #ifndef NCURSES_WIDECHAR
65 #define NCURSES_WIDECHAR 1
67 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
68 || defined(__APPLE__) || defined(__sun)
69 #ifndef _XOPEN_SOURCE_EXTENDED
70 #define _XOPEN_SOURCE_EXTENDED
73 #ifndef __USE_XOPEN /* Fix wcswidth() failure, ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
88 #include <readline/history.h>
89 #include <readline/readline.h>
103 #ifndef __USE_XOPEN_EXTENDED
104 #define __USE_XOPEN_EXTENDED 1
111 #if !defined(alloca) && defined(__GNUC__)
113 * GCC doesn't expand alloca() to __builtin_alloca() in standards mode
114 * (-std=...) and not all standard libraries do or supply it, e.g.
115 * NetBSD/arm64 so explicitly use the builtin.
117 #define alloca(size) __builtin_alloca(size)
123 #if defined(ICONS) || defined(NERD)
125 #define ICONS_ENABLED
132 /* Macro definitions */
133 #define VERSION "4.2"
134 #define GENERAL_INFO "BSD 2-Clause\nhttps://github.com/jarun/nnn"
137 #define SESSIONS_VERSION 1
141 #define S_BLKSIZE 512 /* S_BLKSIZE is missing on Android NDK (Termux) */
145 * NAME_MAX and PATH_MAX may not exist, e.g. with dirent.c_name being a
146 * flexible array on Illumos. Use somewhat accommodating fallback values.
153 #define PATH_MAX 4096
156 #define _ABSSUB(N, M) (((N) <= (M)) ? ((M) - (N)) : ((N) - (M)))
157 #define ELEMENTS(x) (sizeof(x) / sizeof(*(x)))
159 #define MIN(x, y) ((x) < (y) ? (x) : (y))
161 #define MAX(x, y) ((x) > (y) ? (x) : (y))
162 #define ISODD(x) ((x) & 1)
163 #define ISBLANK(x) ((x) == ' ' || (x) == '\t')
164 #define TOUPPER(ch) (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
165 #define CMD_LEN_MAX (PATH_MAX + ((NAME_MAX + 1) << 1))
166 #define ALIGN_UP(x, A) ((((x) + (A) - 1) / (A)) * (A))
167 #define READLINE_MAX 256
173 #define PROMPT ">>> "
175 #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
176 #define NAMEBUF_INCR 0x800 /* 64 dir entries at once, avg. 32 chars per file name = 64*32B = 2KB */
177 #define DESCRIPTOR_LEN 32
178 #define _ALIGNMENT 0x10 /* 16-byte alignment */
179 #define _ALIGNMENT_MASK 0xF
180 #define TMP_LEN_MAX 64
181 #define DOT_FILTER_LEN 7
182 #define ASCII_MAX 128
183 #define EXEC_ARGS_MAX 10
184 #define LIST_FILES_MAX (1 << 16)
188 #define DBLCLK_INTERVAL_NS (400000000)
189 #define XDELAY_INTERVAL_MS (350000) /* 350 ms delay */
203 /* Large selection threshold */
205 #define LARGESEL 1000
208 #define MIN_DISPLAY_COL (CTX_MAX * 2)
209 #define ARCHIVE_CMD_LEN 16
210 #define BLK_SHIFT_512 9
212 /* Detect hardlinks in du */
213 #define HASH_BITS (0xFFFFFF)
214 #define HASH_OCTETS (HASH_BITS >> 6) /* 2^6 = 64 */
217 #define DIR_OR_DIRLNK 0x01
218 #define HARD_LINK 0x02
219 #define SYM_ORPHAN 0x04
220 #define FILE_MISSING 0x08
221 #define FILE_SELECTED 0x10
222 #define FILE_SCANNED 0x20
224 /* Macros to define process spawn behaviour as flags */
225 #define F_NONE 0x00 /* no flag set */
226 #define F_MULTI 0x01 /* first arg can be combination of args; to be used with F_NORMAL */
227 #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
228 #define F_NOTRACE 0x04 /* suppress stdout and stderr (no traces) */
229 #define F_NORMAL 0x08 /* spawn child process in non-curses regular CLI mode */
230 #define F_CONFIRM 0x10 /* run command - show results before exit (must have F_NORMAL) */
231 #define F_CHKRTN 0x20 /* wait for user prompt if cmd returns failure status */
232 #define F_NOSTDIN 0x40 /* suppress stdin */
233 #define F_PAGE 0x80 /* page output in run-cmd-as-plugin mode */
234 #define F_TTY 0x100 /* Force stdout to go to tty if redirected to a non-tty */
235 #define F_CLI (F_NORMAL | F_MULTI)
236 #define F_SILENT (F_CLI | F_NOTRACE)
238 /* Version compare macros */
240 * states: S_N: normal, S_I: comparing integral part, S_F: comparing
241 * fractional parts, S_Z: idem but with leading Zeroes only
248 /* result_type: VCMP: return diff; VLEN: compare using len_diff/diff */
256 /* TYPE DEFINITIONS */
257 typedef unsigned int uint_t;
258 typedef unsigned char uchar_t;
259 typedef unsigned short ushort_t;
260 typedef unsigned long long ullong_t;
264 /* Directory entry */
265 typedef struct entry {
266 char *name; /* 8 bytes */
267 time_t sec; /* 8 bytes */
268 uint_t nsec; /* 4 bytes (enough to store nanosec) */
269 mode_t mode; /* 4 bytes */
270 off_t size; /* 8 bytes */
272 ullong_t blocks : 40; /* 5 bytes (enough for 512 TiB in 512B blocks allocated) */
273 ullong_t nlen : 16; /* 2 bytes (length of file name) */
274 ullong_t flags : 8; /* 1 byte (flags specific to the file) */
277 uid_t uid; /* 4 bytes */
278 gid_t gid; /* 4 bytes */
282 /* Selection marker */
288 /* Key-value pairs from env */
298 const regex_t *regex;
305 * NOTE: update default values if changing order
308 uint_t filtermode : 1; /* Set to enter filter mode */
309 uint_t timeorder : 1; /* Set to sort by time */
310 uint_t sizeorder : 1; /* Set to sort by file size */
311 uint_t apparentsz : 1; /* Set to sort by apparent size (disk usage) */
312 uint_t blkorder : 1; /* Set to sort by blocks used (disk usage) */
313 uint_t extnorder : 1; /* Order by extension */
314 uint_t showhidden : 1; /* Set to show hidden files */
315 uint_t reserved0 : 1;
316 uint_t showdetail : 1; /* Clear to show lesser file info */
317 uint_t ctxactive : 1; /* Context active or not */
318 uint_t reverse : 1; /* Reverse sort */
319 uint_t version : 1; /* Version sort */
320 uint_t reserved1 : 1;
321 /* The following settings are global */
322 uint_t curctx : 3; /* Current context number */
323 uint_t prefersel : 1; /* Prefer selection over current, if exists */
324 uint_t reserved2 : 1;
325 uint_t nonavopen : 1; /* Open file on right arrow or `l` */
326 uint_t autoselect : 1; /* Auto-select dir in type-to-nav mode */
327 uint_t cursormode : 1; /* Move hardware cursor with selection */
328 uint_t useeditor : 1; /* Use VISUAL to open text files */
329 uint_t reserved3 : 3;
330 uint_t regex : 1; /* Use regex filters */
331 uint_t x11 : 1; /* Copy to system clipboard, show notis, xterm title */
332 uint_t timetype : 2; /* Time sort type (0: access, 1: change, 2: modification) */
333 uint_t cliopener : 1; /* All-CLI app opener */
334 uint_t waitedit : 1; /* For ops that can't be detached, used EDITOR */
335 uint_t rollover : 1; /* Roll over at edges */
338 /* Non-persistent program-internal states (alphabeical order) */
340 uint_t autofifo : 1; /* Auto-create NNN_FIFO */
341 uint_t autonext : 1; /* Auto-proceed on open */
342 uint_t dircolor : 1; /* Current status of dir color */
343 uint_t dirctx : 1; /* Show dirs in context color */
344 uint_t duinit : 1; /* Initialize disk usage */
345 uint_t fifomode : 1; /* FIFO notify mode: 0: preview, 1: explore */
346 uint_t forcequit : 1; /* Do not prompt on quit */
347 uint_t initfile : 1; /* Positional arg is a file */
348 uint_t interrupt : 1; /* Program received an interrupt */
349 uint_t move : 1; /* Move operation */
350 uint_t oldcolor : 1; /* Use older colorscheme */
351 uint_t picked : 1; /* Plugin has picked files */
352 uint_t picker : 1; /* Write selection to user-specified file */
353 uint_t pluginit : 1; /* Plugin framework initialized */
354 uint_t prstssn : 1; /* Persistent session */
355 uint_t rangesel : 1; /* Range selection on */
356 uint_t runctx : 3; /* The context in which plugin is to be run */
357 uint_t runplugin : 1; /* Choose plugin mode */
358 uint_t selmode : 1; /* Set when selecting files */
359 uint_t stayonsel : 1; /* Disable auto-proceed on select */
360 uint_t trash : 2; /* Use trash to delete files 1: trash-cli, 2: gio trash */
361 uint_t uidgid : 1; /* Show owner and group info */
362 uint_t reserved : 7; /* Adjust when adding/removing a field */
365 /* Contexts or workspaces */
367 char c_path[PATH_MAX]; /* Current dir */
368 char c_last[PATH_MAX]; /* Last visited dir */
369 char c_name[NAME_MAX + 1]; /* Current file name */
370 char c_fltr[REGEX_MAX]; /* Current filter */
371 settings c_cfg; /* Current configuration */
372 uint_t color; /* Color code for directories */
378 size_t pathln[CTX_MAX];
379 size_t lastln[CTX_MAX];
380 size_t nameln[CTX_MAX];
381 size_t fltrln[CTX_MAX];
387 /* Configuration, contexts */
388 static settings cfg = {
412 2, /* timetype (T_MOD) */
418 static context g_ctx[CTX_MAX] __attribute__ ((aligned));
420 static int ndents, cur, last, curscroll, last_curscroll, total_dents = ENTRY_INCR, scroll_lines = 1;
421 static int nselected;
423 static int fifofd = -1;
425 static uint_t idletimeout, selbufpos, selbuflen;
426 static ushort_t xlines, xcols;
427 static ushort_t idle;
428 static uchar_t maxbm, maxplug;
430 static char *pluginstr;
433 static char *enveditor;
437 static char *initpath;
438 static char *cfgpath;
439 static char *selpath;
440 static char *listpath;
441 static char *listroot;
442 static char *plgpath;
443 static char *pnamebuf, *pselbuf, *findselpos;
446 static char *fifopath;
448 static char *lastcmd;
449 static ullong_t *ihashbmp;
450 static struct entry *pdents;
451 static blkcnt_t dir_blocks;
454 static uchar_t tmpfplen, homelen;
455 static uchar_t blk_shift = BLK_SHIFT_512;
457 static int middle_click_key;
460 static pcre *archive_pcre;
462 static regex_t archive_re;
465 /* pthread related */
466 #define NUM_DU_THREADS (4) /* Can use sysconf(_SC_NPROCESSORS_ONLN) */
467 #define DU_TEST (((node->fts_info & FTS_F) && \
468 (sb->st_nlink <= 1 || test_set_bit((uint_t)sb->st_ino))) || node->fts_info & FTS_DP)
470 static int threadbmp = -1; /* Has 1 in the bit position for idle threads */
471 static volatile int active_threads;
472 static pthread_mutex_t running_mutex = PTHREAD_MUTEX_INITIALIZER;
473 static pthread_mutex_t hardlink_mutex = PTHREAD_MUTEX_INITIALIZER;
474 static ullong_t *core_files;
475 static blkcnt_t *core_blocks;
476 static ullong_t num_files;
485 static thread_data *core_data;
487 /* Retain old signal handlers */
488 static struct sigaction oldsighup;
489 static struct sigaction oldsigtstp;
490 static struct sigaction oldsigwinch;
492 /* For use in functions which are isolated and don't return the buffer */
493 static char g_buf[CMD_LEN_MAX] __attribute__ ((aligned));
495 /* For use as a scratch buffer in selection manipulation */
496 static char g_sel[PATH_MAX] __attribute__ ((aligned));
498 /* Buffer to store tmp file path to show selection, file stats and help */
499 static char g_tmpfpath[TMP_LEN_MAX] __attribute__ ((aligned));
501 /* Buffer to store plugins control pipe location */
502 static char g_pipepath[TMP_LEN_MAX] __attribute__ ((aligned));
504 /* Non-persistent runtime states */
505 static runstate g_state;
507 /* Options to identify file MIME */
508 #if defined(__APPLE__)
509 #define FILE_MIME_OPTS "-bIL"
510 #elif !defined(__sun) /* no MIME option for 'file' */
511 #define FILE_MIME_OPTS "-biL"
514 /* Macros for utilities */
515 #define UTIL_OPENER 0
517 #define UTIL_BSDTAR 2
520 #define UTIL_LOCKER 5
521 #define UTIL_LAUNCH 6
522 #define UTIL_SH_EXEC 7
525 #define UTIL_RCLONE 10
533 #define UTIL_TRASH_CLI 18
534 #define UTIL_GIO_TRASH 19
535 #define UTIL_RM_RF 20
537 /* Utilities to open files, run actions */
538 static char * const utils[] = {
541 #elif defined __CYGWIN__
543 #elif defined __HAIKU__
554 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
556 #elif defined __HAIKU__
579 #define MSG_ZERO 0 /* Unused */
580 #define MSG_0_ENTRIES 1
581 #define STR_TMPFILE 2
582 #define MSG_0_SELECTED 3
585 #define MSG_SSN_NAME 6
586 #define MSG_CP_MV_AS 7
587 #define MSG_CUR_SEL_OPTS 8
588 #define MSG_FORCE_RM 9
590 #define MSG_NEW_OPTS 11
591 #define MSG_CLI_MODE 12
592 #define MSG_OVERWRITE 13
593 #define MSG_SSN_OPTS 14
594 #define MSG_QUIT_ALL 15
595 #define MSG_HOSTNAME 16
596 #define MSG_ARCHIVE_NAME 17
597 #define MSG_OPEN_WITH 18
598 #define MSG_NEW_PATH 19
599 #define MSG_LINK_PREFIX 20
600 #define MSG_COPY_NAME 21
602 #define MSG_SEL_MISSING 23
603 #define MSG_ACCESS 24
604 #define MSG_EMPTY_FILE 25
605 #define MSG_UNSUPPORTED 26
606 #define MSG_NOT_SET 27
607 #define MSG_EXISTS 28
608 #define MSG_FEW_COLUMNS 29
609 #define MSG_REMOTE_OPTS 30
610 #define MSG_RCLONE_DELAY 31
611 #define MSG_APP_NAME 32
612 #define MSG_ARCHIVE_OPTS 33
614 #define MSG_INVALID_REG 35
618 #define MSG_RM_TMP 39
619 #define MSG_INVALID_KEY 40
620 #define MSG_NOCHANGE 41
621 #define MSG_DIR_CHANGED 42
623 static const char * const messages[] = {
632 "'c'urrent / 's'el?",
633 "%s %s file%s? [Esc cancels]",
635 "'f'ile / 'd'ir / 's'ym / 'h'ard?",
638 "'s'ave / 'l'oad / 'r'estore?",
639 "Quit all contexts?",
640 "remote name (- for hovered): ",
641 "archive [path/]name: ",
644 "link prefix [@ for none]: ",
645 "copy [path/]name: ",
646 "\n'Enter' to continue",
649 "empty! edit/open with",
654 "'s'shfs / 'r'clone?",
657 "'o'pen / e'x'tract / 'l's / 'm'nt?",
660 "'a'u / 'd'u / 'e'xt / 'r'ev / 's'z / 't'm / 'v'er / 'c'lr / '^T'?",
661 "unmount failed! try lazy?",
662 "first file (\')/char?",
666 "dir changed, range sel off",
669 /* Supported configuration environment variables */
675 #define NNN_FCOLORS 5
680 #define NNN_ARCHIVE 10
681 #define NNN_HELP 11 /* strings end here */
682 #define NNN_TRASH 12 /* flags begin here */
684 static const char * const env_cfg[] = {
700 /* Required environment variables */
707 static const char * const envs[] = {
721 static char cp[] = "cp -iRp";
722 static char mv[] = "mv -i";
724 static char cp[] = "cp -iRp";
725 static char mv[] = "mv -i";
728 /* Archive commands */
729 static const char * const archive_cmd[] = {"atool -a", "bsdtar -acvf", "zip -r", "tar -acvf"};
731 /* Tokens used for path creation */
736 static const char * const toks[] = {
739 "plugins", /* must be the last entry */
748 static const char * const patterns[] = {
749 SED" -i 's|^\\(\\(.*/\\)\\(.*\\)$\\)|#\\1\\n\\3|' %s",
750 SED" 's|^\\([^#/][^/]\\?.*\\)$|%s/\\1|;s|^#\\(/.*\\)$|\\1|' "
751 "%s | tr '\\n' '\\0' | xargs -0 -n2 sh -c '%s \"$0\" \"$@\" < /dev/tty'",
752 "\\.(bz|bz2|gz|tar|taz|tbz|tbz2|tgz|z|zip)$",
753 SED" -i 's|^%s\\(.*\\)$|%s\\1|' %s",
757 #define C_BLK (CTX_MAX + 1) /* Block device: DarkSeaGreen1 */
758 #define C_CHR (C_BLK + 1) /* Character device: Yellow1 */
759 #define C_DIR (C_CHR + 1) /* Directory: DeepSkyBlue1 */
760 #define C_EXE (C_DIR + 1) /* Executable file: Green1 */
761 #define C_FIL (C_EXE + 1) /* Regular file: Normal */
762 #define C_HRD (C_FIL + 1) /* Hard link: Plum4 */
763 #define C_LNK (C_HRD + 1) /* Symbolic link: Cyan1 */
764 #define C_MIS (C_LNK + 1) /* Missing file OR file details: Grey62 */
765 #define C_ORP (C_MIS + 1) /* Orphaned symlink: DeepPink1 */
766 #define C_PIP (C_ORP + 1) /* Named pipe (FIFO): Orange1 */
767 #define C_SOC (C_PIP + 1) /* Socket: MediumOrchid1 */
768 #define C_UND (C_SOC + 1) /* Unknown OR 0B regular/exe file: Red1 */
771 /* 0-9, A-Z, OTHER = 36. */
772 static ushort_t icon_positions[37];
775 static char gcolors[] = "c1e2272e006033f7c6d6abc4";
776 static uint_t fcolors[C_UND + 1] = {0};
780 #define NUM_EVENT_SLOTS 32 /* Make room for 32 events */
781 #define EVENT_SIZE (sizeof(struct inotify_event))
782 #define EVENT_BUF_LEN (EVENT_SIZE * NUM_EVENT_SLOTS)
783 static int inotify_fd, inotify_wd = -1;
784 static uint_t INOTIFY_MASK = /* IN_ATTRIB | */ IN_CREATE | IN_DELETE | IN_DELETE_SELF
785 | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
786 #elif defined(BSD_KQUEUE)
787 #define NUM_EVENT_SLOTS 1
788 #define NUM_EVENT_FDS 1
789 static int kq, event_fd = -1;
790 static struct kevent events_to_monitor[NUM_EVENT_FDS];
791 static uint_t KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK
792 | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
793 static struct timespec gtimeout;
794 #elif defined(HAIKU_NM)
795 static bool haiku_nm_active = FALSE;
796 static haiku_nm_h haiku_hnd;
799 /* Function macros */
800 #define tolastln() move(xlines - 1, 0)
801 #define tocursor() move(cur + 2 - curscroll, 0)
802 #define exitcurses() endwin()
803 #define printwarn(presel) printwait(strerror(errno), presel)
804 #define istopdir(path) ((path)[1] == '\0' && (path)[0] == '/')
805 #define copycurname() xstrsncpy(lastname, pdents[cur].name, NAME_MAX + 1)
806 #define settimeout() timeout(1000)
807 #define cleartimeout() timeout(-1)
808 #define errexit() printerr(__LINE__)
809 #define setdirwatch() (cfg.filtermode ? (presel = FILTER) : (watch = TRUE))
810 #define filterset() (g_ctx[cfg.curctx].c_fltr[1])
811 /* We don't care about the return value from strcmp() */
812 #define xstrcmp(a, b) (*(a) != *(b) ? -1 : strcmp((a), (b)))
813 /* A faster version of xisdigit */
814 #define xisdigit(c) ((unsigned int) (c) - '0' <= 9)
815 #define xerror() perror(xitoa(__LINE__))
818 #define ENTLESS(i, j) (entrycmpfn(pdents + (i), pdents + (j)) < 0)
819 #define ENTSWAP(i, j) (swap_ent((i), (j)))
820 #define ENTSORT(pdents, ndents, entrycmpfn) QSORT((ndents), ENTLESS, ENTSWAP)
822 #define ENTSORT(pdents, ndents, entrycmpfn) qsort((pdents), (ndents), sizeof(*(pdents)), (entrycmpfn))
825 /* Forward declarations */
826 static void redraw(char *path);
827 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag);
828 static void move_cursor(int target, int ignore_scrolloff);
829 static char *load_input(int fd, const char *path);
830 static int set_sort_flags(int r);
832 static void notify_fifo(bool force);
837 static void sigint_handler(int sig)
840 g_state.interrupt = 1;
843 static void clean_exit_sighandler(int sig)
847 /* This triggers cleanup() thanks to atexit() */
851 static char *xitoa(uint_t val)
853 static char dst[32] = {'\0'};
854 static const char digits[201] =
855 "0001020304050607080910111213141516171819"
856 "2021222324252627282930313233343536373839"
857 "4041424344454647484950515253545556575859"
858 "6061626364656667686970717273747576777879"
859 "8081828384858687888990919293949596979899";
860 uint_t next = 30, quo, i;
864 i = (val - (quo * 100)) * 2;
866 dst[next] = digits[i + 1];
867 dst[--next] = digits[i];
871 /* Handle last 1-2 digits */
873 dst[next] = '0' + val;
876 dst[next] = digits[i + 1];
877 dst[--next] = digits[i];
883 /* Return the integer value of a char representing HEX */
884 static uchar_t xchartohex(uchar_t c)
889 if (c >= 'a' && c <= 'f')
892 if (c >= 'A' && c <= 'F')
899 * Source: https://elixir.bootlin.com/linux/latest/source/arch/alpha/include/asm/bitops.h
901 static bool test_set_bit(uint_t nr)
905 pthread_mutex_lock(&hardlink_mutex);
906 ullong_t *m = ((ullong_t *)ihashbmp) + (nr >> 6);
908 if (*m & (1 << (nr & 63))) {
909 pthread_mutex_unlock(&hardlink_mutex);
913 *m |= 1 << (nr & 63);
914 pthread_mutex_unlock(&hardlink_mutex);
920 /* Increase the limit on open file descriptors, if possible */
921 static void max_openfds(void)
925 if (!getrlimit(RLIMIT_NOFILE, &rl))
926 if (rl.rlim_cur < rl.rlim_max) {
927 rl.rlim_cur = rl.rlim_max;
928 setrlimit(RLIMIT_NOFILE, &rl);
934 * Wrapper to realloc()
935 * Frees current memory if realloc() fails and returns NULL.
937 * The *alloc() family returns aligned address: https://man7.org/linux/man-pages/man3/malloc.3.html
939 static void *xrealloc(void *pcur, size_t len)
941 void *pmem = realloc(pcur, len);
950 * Just a safe strncpy(3)
951 * Always null ('\0') terminates if both src and dest are valid pointers.
952 * Returns the number of bytes copied including terminating null byte.
954 static size_t xstrsncpy(char *restrict dst, const char *restrict src, size_t n)
956 char *end = memccpy(dst, src, '\0', n);
959 dst[n - 1] = '\0'; // NOLINT
960 end = dst + n; /* If we return n here, binary size increases due to auto-inlining */
966 static inline size_t xstrlen(const char *restrict s)
968 #if !defined(__GLIBC__)
969 return strlen(s); // NOLINT
971 return (char *)rawmemchr(s, '\0') - s; // NOLINT
975 static char *xstrdup(const char *restrict s)
977 size_t len = xstrlen(s) + 1;
978 char *ptr = malloc(len);
981 xstrsncpy(ptr, s, len);
985 static bool is_suffix(const char *restrict str, const char *restrict suffix)
990 size_t lenstr = xstrlen(str);
991 size_t lensuffix = xstrlen(suffix);
993 if (lensuffix > lenstr)
996 return (xstrcmp(str + (lenstr - lensuffix), suffix) == 0);
999 static bool is_prefix(const char *restrict str, const char *restrict prefix, size_t len)
1001 return !strncmp(str, prefix, len);
1005 * The poor man's implementation of memrchr(3).
1006 * We are only looking for '/' in this program.
1007 * And we are NOT expecting a '/' at the end.
1008 * Ideally 0 < n <= xstrlen(s).
1010 static void *xmemrchr(uchar_t *restrict s, uchar_t ch, size_t n)
1012 #if defined(__GLIBC__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
1013 return memrchr(s, ch, n);
1019 uchar_t *ptr = s + n;
1030 /* A very simplified implementation, changes path */
1031 static char *xdirname(char *path)
1033 char *base = xmemrchr((uchar_t *)path, '/', xstrlen(path));
1043 static char *xbasename(char *path)
1045 char *base = xmemrchr((uchar_t *)path, '/', xstrlen(path)); // NOLINT
1047 return base ? base + 1 : path;
1050 static inline char *xextension(const char *fname, size_t len)
1052 return xmemrchr((uchar_t *)fname, '.', len);
1057 * One-shot cache for getpwuid/getgrgid. Returns the cached name if the
1058 * provided uid is the same as the previous uid. Returns xitoa(guid) if
1059 * the guid is not found in the password database.
1061 static char *getpwname(uid_t uid)
1063 static uint_t uidcache = UINT_MAX;
1064 static char *namecache;
1066 if (uidcache != uid) {
1067 struct passwd *pw = getpwuid(uid);
1070 namecache = pw ? pw->pw_name : NULL;
1073 return namecache ? namecache : xitoa(uid);
1076 static char *getgrname(gid_t gid)
1078 static uint_t gidcache = UINT_MAX;
1079 static char *grpcache;
1081 if (gidcache != gid) {
1082 struct group *gr = getgrgid(gid);
1085 grpcache = gr ? gr->gr_name : NULL;
1088 return grpcache ? grpcache : xitoa(gid);
1092 static inline bool getutil(char *util)
1094 return spawn("which", util, NULL, NULL, F_NORMAL | F_NOTRACE) == 0;
1098 * Updates out with "dir/name or "/name"
1099 * Returns the number of bytes copied including the terminating NULL byte
1101 * Note: dir and out must be PATH_MAX in length to avoid macOS fault
1103 static size_t mkpath(const char *dir, const char *name, char *out)
1107 if (name[0] != '/') { // NOLINT
1108 /* Handle root case */
1112 len = xstrsncpy(out, dir, PATH_MAX);
1114 out[len - 1] = '/'; // NOLINT
1116 return (xstrsncpy(out + len, name, PATH_MAX - len) + len);
1119 /* Assumes both the paths passed are directories */
1120 static char *common_prefix(const char *path, char *prefix)
1122 const char *x = path, *y = prefix;
1125 if (!path || !*path || !prefix)
1129 xstrsncpy(prefix, path, PATH_MAX);
1133 while (*x && *y && (*x == *y))
1136 /* Strings are same */
1140 /* Path is shorter */
1141 if (!*x && *y == '/') {
1142 xstrsncpy(prefix, path, y - path);
1146 /* Prefix is shorter */
1147 if (!*y && *x == '/')
1150 /* Shorten prefix */
1151 prefix[y - prefix] = '\0';
1153 sep = xmemrchr((uchar_t *)prefix, '/', y - prefix);
1163 * The library function realpath() resolves symlinks.
1164 * If there's a symlink in file list we want to show the symlink not what it's points to.
1166 static char *abspath(const char *path, const char *cwd)
1171 size_t dst_size = 0, src_size = xstrlen(path), cwd_size = xstrlen(cwd);
1172 size_t len = src_size;
1176 * We need to add 2 chars at the end as relative paths may start with:
1178 * no separator (fd .): this needs an additional char for '/'
1180 char *resolved_path = malloc(src_size + (*path == '/' ? 0 : cwd_size) + 2);
1185 /* Turn relative paths into absolute */
1187 dst_size = xstrsncpy(resolved_path, cwd, cwd_size + 1) - 1;
1189 resolved_path[0] = '\0';
1192 dst = resolved_path + dst_size;
1193 for (const char *next = NULL; next != path + src_size;) {
1194 next = memchr(src, '/', len);
1196 next = path + src_size;
1198 if (next - src == 2 && src[0] == '.' && src[1] == '.') {
1199 if (dst - resolved_path) {
1200 dst = xmemrchr((uchar_t *)resolved_path, '/', dst - resolved_path);
1203 } else if (next - src == 1 && src[0] == '.') {
1205 } else if (next - src) {
1207 xstrsncpy(dst, src, next - src + 1);
1212 len = src_size - (src - path);
1215 if (*resolved_path == '\0') {
1216 resolved_path[0] = '/';
1217 resolved_path[1] = '\0';
1220 return resolved_path;
1223 static bool set_tilde_in_path(char *path)
1225 if (is_prefix(path, home, homelen)) {
1226 home[homelen] = path[homelen - 1];
1227 path[homelen - 1] = '~';
1234 static void reset_tilde_in_path(char *path)
1236 path[homelen - 1] = home[homelen];
1237 home[homelen] = '\0';
1240 static int create_tmp_file(void)
1242 xstrsncpy(g_tmpfpath + tmpfplen - 1, messages[STR_TMPFILE], TMP_LEN_MAX - tmpfplen);
1244 int fd = mkstemp(g_tmpfpath);
1247 DPRINTF_S(strerror(errno));
1253 static void msg(const char *message)
1255 dprintf(STDERR_FILENO, "%s\n", message);
1258 static void clearinfoln(void)
1260 move(xlines - 2, 0);
1265 static void handle_key_resize()
1271 /* Clear the old prompt */
1272 static void clearoldprompt(void)
1277 handle_key_resize();
1281 /* Messages show up at the bottom */
1282 static inline void printmsg_nc(const char *msg)
1289 static void printmsg(const char *msg)
1291 attron(COLOR_PAIR(cfg.curctx + 1));
1293 attroff(COLOR_PAIR(cfg.curctx + 1));
1296 static void printwait(const char *msg, int *presel)
1302 xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
1306 /* Kill curses and display error before exiting */
1307 static void printerr(int linenum)
1310 perror(xitoa(linenum));
1311 if (!g_state.picker && selpath)
1317 static inline bool xconfirm(int c)
1319 return (c == 'y' || c == 'Y');
1322 static int get_input(const char *prompt)
1331 while (r == KEY_RESIZE) {
1345 static bool isselfileempty(void)
1349 return (stat(selpath, &sb) == -1) || (!sb.st_size);
1352 static int get_cur_or_sel(void)
1354 /* Check both local buffer and selection file for external selection */
1355 if ((selbufpos || !isselfileempty()) && ndents) {
1356 /* If selection is preferred and we have a local selection, return selection.
1357 * Always show the prompt in case of an external selection.
1359 if (cfg.prefersel && selbufpos)
1362 int choice = get_input(messages[MSG_CUR_SEL_OPTS]);
1364 return ((choice == 'c' || choice == 's') ? choice : 0);
1367 if (selbufpos || !isselfileempty())
1376 static void xdelay(useconds_t delay)
1382 static char confirm_force(bool selection)
1386 snprintf(str, 64, messages[MSG_FORCE_RM],
1387 g_state.trash ? utils[UTIL_GIO_TRASH] + 4 : utils[UTIL_RM_RF],
1388 (selection ? xitoa(nselected) : "current"), (selection ? "(s)" : ""));
1390 int r = get_input(str);
1393 return '\0'; /* cancel */
1394 if (r == 'y' || r == 'Y')
1395 return 'f'; /* forceful for rm */
1396 return (g_state.trash ? '\0' : 'i'); /* interactive for rm */
1399 /* Writes buflen char(s) from buf to a file */
1400 static void writesel(const char *buf, const size_t buflen)
1405 int fd = open(selpath, O_CREAT | O_WRONLY | O_TRUNC, 0666);
1408 if (write(fd, buf, buflen) != (ssize_t)buflen)
1415 static void appendfpath(const char *path, const size_t len)
1417 if ((selbufpos >= selbuflen) || ((len + 3) > (selbuflen - selbufpos))) {
1418 selbuflen += PATH_MAX;
1419 pselbuf = xrealloc(pselbuf, selbuflen);
1424 selbufpos += xstrsncpy(pselbuf + selbufpos, path, len);
1427 static void selbufrealloc(const size_t alloclen)
1429 if ((selbufpos + alloclen) > selbuflen) {
1430 selbuflen = ALIGN_UP(selbufpos + alloclen, PATH_MAX);
1431 pselbuf = xrealloc(pselbuf, selbuflen);
1437 /* Write selected file paths to fd, linefeed separated */
1438 static size_t seltofile(int fd, uint_t *pcount)
1440 uint_t lastpos, count = 0;
1441 char *pbuf = pselbuf;
1443 ssize_t len, prefixlen = 0, initlen = 0;
1451 lastpos = selbufpos - 1;
1454 prefixlen = (ssize_t)xstrlen(listroot);
1455 initlen = (ssize_t)xstrlen(listpath);
1458 while (pos <= lastpos) {
1460 len = (ssize_t)xstrlen(pbuf);
1462 if (!listpath || !is_prefix(pbuf, listpath, initlen)) {
1463 if (write(fd, pbuf, len) != len)
1466 if (write(fd, listroot, prefixlen) != prefixlen)
1468 if (write(fd, pbuf + initlen, len - initlen) != (len - initlen))
1473 if (pos <= lastpos) {
1474 if (write(fd, "\n", 1) != 1)
1488 /* List selection from selection file (another instance) */
1489 static bool listselfile(void)
1491 if (isselfileempty())
1494 snprintf(g_buf, CMD_LEN_MAX, "tr \'\\0\' \'\\n\' < %s", selpath);
1495 spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CONFIRM);
1500 /* Reset selection indicators */
1501 static void resetselind(void)
1503 for (int r = 0; r < ndents; ++r)
1504 if (pdents[r].flags & FILE_SELECTED)
1505 pdents[r].flags &= ~FILE_SELECTED;
1508 static void startselection(void)
1510 if (!g_state.selmode) {
1511 g_state.selmode = 1;
1522 static void clearselection(void)
1526 g_state.selmode = 0;
1530 static char *findinsel(char *startpos, int len)
1538 char *found = startpos;
1539 size_t buflen = selbufpos - (startpos - pselbuf);
1542 /* memmem(3): not specified in POSIX.1, but present on a number of other systems. */
1543 found = memmem(found, buflen - (found - startpos), g_sel, len);
1546 if (found == startpos || *(found - 1) == '\0')
1548 found += len; /* We found g_sel as a substring of a path, move forward */
1549 if (found >= startpos + buflen)
1554 static int markcmp(const void *va, const void *vb)
1556 const selmark *ma = (selmark*)va;
1557 const selmark *mb = (selmark*)vb;
1559 return ma->startpos - mb->startpos;
1562 /* scanselforpath() must be called before calling this */
1563 static inline void findmarkentry(size_t len, struct entry *dentp)
1565 if (!(dentp->flags & FILE_SCANNED)) {
1566 if (findinsel(findselpos, len + xstrsncpy(g_sel + len, dentp->name, dentp->nlen)))
1567 dentp->flags |= FILE_SELECTED;
1568 dentp->flags |= FILE_SCANNED;
1573 * scanselforpath() must be called before calling this
1574 * pathlen = length of path + 1 (+1 for trailing slash)
1576 static void invertselbuf(const int pathlen)
1578 size_t len, endpos, shrinklen = 0, alloclen = 0;
1579 char * const pbuf = g_sel + pathlen;
1581 int i, nmarked = 0, prev = 0;
1582 struct entry *dentp;
1583 selmark *marked = malloc(nselected * sizeof(selmark));
1586 /* First pass: inversion */
1587 for (i = 0; i < ndents; ++i) {
1590 if (dentp->flags & FILE_SCANNED) {
1591 if (dentp->flags & FILE_SELECTED) {
1592 dentp->flags ^= FILE_SELECTED; /* Clear selection status */
1595 dentp->flags |= FILE_SELECTED;
1596 alloclen += pathlen + dentp->nlen;
1599 dentp->flags |= FILE_SCANNED;
1604 len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1605 found = findinsel(findselpos, len);
1607 if (findselpos == found)
1610 if (nmarked && (found
1611 == (marked[nmarked - 1].startpos + marked[nmarked - 1].len)))
1612 marked[nmarked - 1].len += len;
1614 marked[nmarked].startpos = found;
1615 marked[nmarked].len = len;
1620 shrinklen += len; /* buffer size adjustment */
1622 dentp->flags |= FILE_SELECTED;
1623 alloclen += pathlen + dentp->nlen;
1630 * Files marked for deselection could be found in arbitrary order.
1631 * Sort by appearance in selection buffer.
1632 * With entries sorted we can merge adjacent ones allowing us to
1633 * move them in a single go.
1635 qsort(marked, nmarked, sizeof(selmark), &markcmp);
1637 /* Some files might be adjacent. Merge them into a single entry */
1638 for (i = 1; i < nmarked; ++i) {
1639 if (marked[i].startpos == marked[prev].startpos + marked[prev].len)
1640 marked[prev].len += marked[i].len;
1643 marked[prev].startpos = marked[i].startpos;
1644 marked[prev].len = marked[i].len;
1649 * Number of entries is increased by encountering a non-adjacent entry
1650 * After we finish the loop we should increment it once more.
1653 if (nmarked) /* Make sure there is something to deselect */
1656 /* Using merged entries remove unselected chunks from selection buffer */
1657 for (i = 0; i < nmarked; ++i) {
1659 * found: points to where the current block starts
1660 * variable is recycled from previous for readability
1661 * endpos: points to where the the next block starts
1662 * area between the end of current block (found + len)
1663 * and endpos is selected entries. This is what we are
1666 found = marked[i].startpos;
1667 endpos = (i + 1 == nmarked ? selbufpos : marked[i + 1].startpos - pselbuf);
1668 len = marked[i].len;
1670 /* Move back only selected entries. No selected memory is moved twice */
1671 memmove(found, found + len, endpos - (found + len - pselbuf));
1676 /* Buffer size adjustment */
1677 selbufpos -= shrinklen;
1679 selbufrealloc(alloclen);
1681 /* Second pass: append newly selected to buffer */
1682 for (i = 0; i < ndents; ++i) {
1683 if (pdents[i].flags & FILE_SELECTED) {
1684 len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1685 appendfpath(g_sel, len);
1690 nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1694 * scanselforpath() must be called before calling this
1695 * pathlen = length of path + 1 (+1 for trailing slash)
1697 static void addtoselbuf(const int pathlen, int startid, int endid)
1700 size_t len, alloclen = 0;
1701 struct entry *dentp;
1703 char * const pbuf = g_sel + pathlen;
1705 /* Remember current selection buffer position */
1706 for (i = startid; i <= endid; ++i) {
1710 len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1711 found = findinsel(findselpos, len);
1713 dentp->flags |= (FILE_SCANNED | FILE_SELECTED);
1714 if (found == findselpos) {
1716 if (findselpos == (pselbuf + selbufpos))
1720 alloclen += pathlen + dentp->nlen;
1722 alloclen += pathlen + dentp->nlen;
1725 selbufrealloc(alloclen);
1727 for (i = startid; i <= endid; ++i) {
1728 if (!(pdents[i].flags & FILE_SELECTED)) {
1729 len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1730 appendfpath(g_sel, len);
1732 pdents[i].flags |= (FILE_SCANNED | FILE_SELECTED);
1736 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
1739 /* Removes g_sel from selbuf */
1740 static void rmfromselbuf(size_t len)
1742 char *found = findinsel(findselpos, len);
1746 memmove(found, found + len, selbufpos - (found + len - pselbuf));
1749 nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1752 static int scanselforpath(const char *path, bool getsize)
1754 if (!path[1]) { /* path should always be at least two bytes (including NULL) */
1756 findselpos = pselbuf;
1757 return 1; /* Length of '/' is 1 */
1760 size_t off = xstrsncpy(g_sel, path, PATH_MAX);
1762 g_sel[off - 1] = '/';
1764 * We set findselpos only here. Directories can be listed in arbitrary order.
1765 * This is the best best we can do for remembering position.
1767 findselpos = findinsel(NULL, off);
1771 return (findselpos ? off : 0);
1774 /* Finish selection procedure before an operation */
1775 static void endselection(void)
1779 char buf[sizeof(patterns[P_REPLACE]) + PATH_MAX + (TMP_LEN_MAX << 1)];
1781 if (g_state.selmode)
1782 g_state.selmode = 0;
1784 if (!listpath || !selbufpos)
1787 fd = create_tmp_file();
1789 DPRINTF_S("couldn't create tmp file");
1793 seltofile(fd, NULL);
1795 DPRINTF_S(strerror(errno));
1800 snprintf(buf, sizeof(buf), patterns[P_REPLACE], listpath, listroot, g_tmpfpath);
1801 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
1803 fd = open(g_tmpfpath, O_RDONLY);
1805 DPRINTF_S(strerror(errno));
1807 if (unlink(g_tmpfpath)) {
1808 DPRINTF_S(strerror(errno));
1814 count = read(fd, pselbuf, selbuflen);
1816 DPRINTF_S(strerror(errno));
1818 if (close(fd) || unlink(g_tmpfpath)) {
1819 DPRINTF_S(strerror(errno));
1824 if (close(fd) || unlink(g_tmpfpath)) {
1825 DPRINTF_S(strerror(errno));
1831 pselbuf[--count] = '\0';
1832 for (--count; count > 0; --count)
1833 if (pselbuf[count] == '\n' && pselbuf[count+1] == '/')
1834 pselbuf[count] = '\0';
1836 writesel(pselbuf, selbufpos - 1);
1839 /* Returns: 1 - success, 0 - none selected, -1 - other failure */
1840 static int editselection(void)
1848 if (!selbufpos) /* External selection is only editable at source */
1849 return listselfile();
1851 fd = create_tmp_file();
1853 DPRINTF_S("couldn't create tmp file");
1857 seltofile(fd, NULL);
1859 DPRINTF_S(strerror(errno));
1863 /* Save the last modification time */
1864 if (stat(g_tmpfpath, &sb)) {
1865 DPRINTF_S(strerror(errno));
1869 mtime = sb.st_mtime;
1871 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
1873 fd = open(g_tmpfpath, O_RDONLY);
1875 DPRINTF_S(strerror(errno));
1882 if (mtime == sb.st_mtime) {
1883 DPRINTF_S("selection is not modified");
1888 if (sb.st_size > selbufpos) {
1889 DPRINTF_S("edited buffer larger than previous");
1894 count = read(fd, pselbuf, selbuflen);
1896 DPRINTF_S(strerror(errno));
1898 if (close(fd) || unlink(g_tmpfpath)) {
1899 DPRINTF_S(strerror(errno));
1905 if (close(fd) || unlink(g_tmpfpath)) {
1906 DPRINTF_S(strerror(errno));
1918 /* The last character should be '\n' */
1919 pselbuf[--count] = '\0';
1920 for (--count; count > 0; --count) {
1921 /* Replace every '\n' that separates two paths */
1922 if (pselbuf[count] == '\n' && pselbuf[count + 1] == '/') {
1924 pselbuf[count] = '\0';
1928 /* Add a line for the last file */
1931 if (lines > nselected) {
1932 DPRINTF_S("files added to selection");
1937 writesel(pselbuf, selbufpos - 1);
1947 static bool selsafe(void)
1949 /* Fail if selection file path not generated */
1951 printmsg(messages[MSG_SEL_MISSING]);
1955 /* Fail if selection file path isn't accessible */
1956 if (access(selpath, R_OK | W_OK) == -1) {
1957 errno == ENOENT ? printmsg(messages[MSG_0_SELECTED]) : printwarn(NULL);
1964 static void export_file_list(void)
1969 struct entry *pdent = pdents;
1970 int fd = create_tmp_file();
1973 DPRINTF_S(strerror(errno));
1977 for (int r = 0; r < ndents; ++pdent, ++r) {
1978 if (write(fd, pdent->name, pdent->nlen - 1) != (pdent->nlen - 1))
1981 if ((r != ndents - 1) && (write(fd, "\n", 1) != 1))
1986 DPRINTF_S(strerror(errno));
1989 spawn(editor, g_tmpfpath, NULL, NULL, F_CLI);
1991 if (xconfirm(get_input(messages[MSG_RM_TMP])))
1995 static bool init_fcolors(void)
1997 char *f_colors = getenv(env_cfg[NNN_FCOLORS]);
1999 if (!f_colors || !*f_colors)
2002 for (uchar_t id = C_BLK; *f_colors && id <= C_UND; ++id) {
2003 fcolors[id] = xchartohex(*f_colors) << 4;
2005 fcolors[id] += xchartohex(*f_colors);
2007 init_pair(id, fcolors[id], -1);
2016 /* Initialize curses mode */
2017 static bool initcurses(void *oldmask)
2023 if (g_state.picker) {
2024 if (!newterm(NULL, stderr, stdin)) {
2028 } else if (!initscr()) {
2030 DPRINTF_S(getenv("TERM"));
2037 //intrflush(stdscr, FALSE);
2038 keypad(stdscr, TRUE);
2040 #if NCURSES_MOUSE_VERSION <= 1
2041 mousemask(BUTTON1_PRESSED | BUTTON1_DOUBLE_CLICKED | BUTTON2_PRESSED | BUTTON3_PRESSED,
2042 (mmask_t *)oldmask);
2044 mousemask(BUTTON1_PRESSED | BUTTON2_PRESSED | BUTTON3_PRESSED | BUTTON4_PRESSED
2045 | BUTTON5_PRESSED, (mmask_t *)oldmask);
2049 curs_set(FALSE); /* Hide cursor */
2051 char *colors = getenv(env_cfg[NNN_COLORS]);
2053 if (colors || !getenv("NO_COLOR")) {
2058 use_default_colors();
2060 /* Initialize file colors */
2061 if (COLORS >= 256) {
2062 if (!(g_state.oldcolor || init_fcolors())) {
2064 msg(env_cfg[NNN_FCOLORS]);
2068 g_state.oldcolor = 1;
2071 DPRINTF_D(COLOR_PAIRS);
2073 if (colors && *colors == '#') {
2074 char *sep = strchr(colors, ';');
2076 if (!g_state.oldcolor && COLORS >= 256) {
2081 * If fallback colors are specified, set the separator
2082 * to NULL so we don't interpret separator and fallback
2083 * if fewer than CTX_MAX xterm 256 colors are specified.
2088 colors = sep; /* Detect if 8 colors fallback is appended */
2094 /* Get and set the context colors */
2095 for (uchar_t i = 0; i < CTX_MAX; ++i) {
2096 pcode = &g_ctx[i].color;
2098 if (colors && *colors) {
2100 *pcode = xchartohex(*colors) << 4;
2102 fcolors[i + 1] = *pcode += xchartohex(*colors);
2103 else { /* Each color code must be 2 hex symbols */
2105 msg(env_cfg[NNN_COLORS]);
2109 *pcode = (*colors < '0' || *colors > '7') ? 4 : *colors - '0';
2114 init_pair(i + 1, *pcode, -1);
2118 #ifdef ICONS_ENABLED
2119 if (!g_state.oldcolor) {
2120 uchar_t icolors[256] = {0};
2123 memset(icon_positions, 0x7f, sizeof(icon_positions));
2125 for (uint_t i = 0; i < sizeof(icons_ext)/sizeof(struct icon_pair); ++i) {
2126 c = TOUPPER(icons_ext[i].match[0]);
2127 if (c >= 'A' && c <= 'Z') {
2128 if (icon_positions[c - 'A' + 10] == 0x7f7f)
2129 icon_positions[c - 'A' + 10] = i;
2130 } else if (c >= '0' && c <= '9') {
2131 if (icon_positions[c - '0'] == 0x7f7f)
2132 icon_positions[c - '0'] = i;
2133 } else if (icon_positions[36] == 0x7f7f)
2134 icon_positions[36] = i;
2136 if (icons_ext[i].color && !icolors[icons_ext[i].color]) {
2137 init_pair(C_UND + 1 + icons_ext[i].color, icons_ext[i].color, -1);
2138 icolors[icons_ext[i].color] = 1;
2144 settimeout(); /* One second */
2149 /* No NULL check here as spawn() guards against it */
2150 static char *parseargs(char *cmd, char **argv, int *pindex)
2153 size_t len = xstrlen(cmd) + 1;
2154 char *line = (char *)malloc(len);
2157 DPRINTF_S("malloc()!");
2161 xstrsncpy(line, cmd, len);
2162 argv[count++] = line;
2165 while (*line) { // NOLINT
2166 if (ISBLANK(*line)) {
2169 if (!*line) // NOLINT
2172 argv[count++] = line;
2173 if (count == EXEC_ARGS_MAX) {
2182 if (count == -1 || count > (EXEC_ARGS_MAX - 4)) { /* 3 args and last NULL */
2185 DPRINTF_S("NULL or too many args");
2192 static void enable_signals(void)
2194 struct sigaction dfl_act = {.sa_handler = SIG_DFL};
2196 sigaction(SIGHUP, &dfl_act, NULL);
2197 sigaction(SIGINT, &dfl_act, NULL);
2198 sigaction(SIGQUIT, &dfl_act, NULL);
2199 sigaction(SIGTSTP, &dfl_act, NULL);
2200 sigaction(SIGWINCH, &dfl_act, NULL);
2203 static pid_t xfork(uchar_t flag)
2208 /* the parent ignores the interrupt, quit and hangup signals */
2209 sigaction(SIGHUP, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsighup);
2210 sigaction(SIGTSTP, &(struct sigaction){.sa_handler = SIG_DFL}, &oldsigtstp);
2211 sigaction(SIGWINCH, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsigwinch);
2212 } else if (p == 0) {
2213 /* We create a grandchild to detach */
2214 if (flag & F_NOWAIT) {
2218 _exit(EXIT_SUCCESS);
2226 _exit(EXIT_FAILURE);
2229 /* So they can be used to stop the child */
2233 /* This is the parent waiting for the child to create grandchild */
2234 if (flag & F_NOWAIT)
2235 waitpid(p, NULL, 0);
2242 static int join(pid_t p, uchar_t flag)
2244 int status = 0xFFFF;
2246 if (!(flag & F_NOWAIT)) {
2247 /* wait for the child to exit */
2249 } while (waitpid(p, &status, 0) == -1);
2251 if (WIFEXITED(status)) {
2252 status = WEXITSTATUS(status);
2257 /* restore parent's signal handling */
2258 sigaction(SIGHUP, &oldsighup, NULL);
2259 sigaction(SIGTSTP, &oldsigtstp, NULL);
2260 sigaction(SIGWINCH, &oldsigwinch, NULL);
2266 * Spawns a child process. Behaviour can be controlled using flag.
2267 * Limited to 3 arguments to a program, flag works on bit set.
2269 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag)
2272 int status = 0, retstatus = 0xFFFF;
2273 char *argv[EXEC_ARGS_MAX] = {0};
2276 if (!file || !*file)
2279 /* Swap args if the first arg is NULL and the other 2 aren't */
2280 if (!arg1 && arg2) {
2289 if (flag & F_MULTI) {
2290 cmd = parseargs(file, argv, &status);
2294 argv[status++] = file;
2296 argv[status] = arg1;
2297 argv[++status] = arg2;
2298 argv[++status] = arg3;
2300 if (flag & F_NORMAL)
2305 /* Suppress stdout and stderr */
2306 if (flag & F_NOTRACE) {
2307 int fd = open("/dev/null", O_WRONLY, 0200);
2309 if (flag & F_NOSTDIN)
2310 dup2(fd, STDIN_FILENO);
2311 dup2(fd, STDOUT_FILENO);
2312 dup2(fd, STDERR_FILENO);
2314 } else if (flag & F_TTY) {
2315 /* If stdout has been redirected to a non-tty, force output to tty */
2316 if (!isatty(STDOUT_FILENO)) {
2317 int fd = open(ctermid(NULL), O_WRONLY, 0200);
2318 dup2(fd, STDOUT_FILENO);
2323 execvp(*argv, argv);
2324 _exit(EXIT_SUCCESS);
2326 retstatus = join(pid, flag);
2329 if ((flag & F_CONFIRM) || ((flag & F_CHKRTN) && retstatus)) {
2330 status = write(STDOUT_FILENO, messages[MSG_ENTER], xstrlen(messages[MSG_ENTER]));
2332 while ((read(STDIN_FILENO, &status, 1) > 0) && (status != '\n'));
2335 if (flag & F_NORMAL)
2344 /* Get program name from env var, else return fallback program */
2345 static char *xgetenv(const char * const name, char *fallback)
2347 char *value = getenv(name);
2349 return value && value[0] ? value : fallback;
2352 /* Checks if an env variable is set to 1 */
2353 static inline uint_t xgetenv_val(const char *name)
2355 char *str = getenv(name);
2363 /* Check if a dir exists, IS a dir, and is readable */
2364 static bool xdiraccess(const char *path)
2366 DIR *dirp = opendir(path);
2377 static bool plugscript(const char *plugin, uchar_t flags)
2379 mkpath(plgpath, plugin, g_buf);
2380 if (!access(g_buf, X_OK)) {
2381 spawn(g_buf, NULL, NULL, NULL, flags);
2388 static void opstr(char *buf, char *op)
2390 snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c '%s \"$0\" \"$@\" . < /dev/tty' < %s",
2394 static bool rmmulstr(char *buf)
2396 char r = confirm_force(TRUE);
2401 snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c 'rm -%cr \"$0\" \"$@\" < /dev/tty' < %s",
2404 snprintf(buf, CMD_LEN_MAX, "xargs -0 %s < %s",
2405 utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH], selpath);
2410 /* Returns TRUE if file is removed, else FALSE */
2411 static bool xrm(char * const fpath)
2413 char r = confirm_force(FALSE);
2417 if (!g_state.trash) {
2418 char rm_opts[] = "-ir";
2421 spawn("rm", rm_opts, fpath, NULL, F_NORMAL | F_CHKRTN);
2423 spawn(utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH],
2424 fpath, NULL, NULL, F_NORMAL | F_MULTI);
2426 return (access(fpath, F_OK) == -1); /* File is removed */
2429 static void xrmfromsel(char *path, char *fpath)
2432 bool selected = TRUE;
2435 if ((pdents[cur].flags & DIR_OR_DIRLNK) && scanselforpath(fpath, FALSE))
2437 else if (pdents[cur].flags & FILE_SELECTED) {
2439 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
2445 if (selected && cfg.x11)
2446 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
2450 static uint_t lines_in_file(int fd, char *buf, size_t buflen)
2455 while ((len = read(fd, buf, buflen)) > 0)
2457 count += (buf[--len] == '\n');
2459 /* For all use cases 0 linecount is considered as error */
2460 return ((len < 0) ? 0 : count);
2463 static bool cpmv_rename(int choice, const char *path)
2466 uint_t count = 0, lines = 0;
2468 char *cmd = (choice == 'c' ? cp : mv);
2469 char buf[sizeof(patterns[P_CPMVRNM]) + sizeof(cmd) + (PATH_MAX << 1)];
2471 fd = create_tmp_file();
2475 /* selsafe() returned TRUE for this to be called */
2477 snprintf(buf, sizeof(buf), "tr '\\0' '\\n' < %s > %s", selpath, g_tmpfpath);
2478 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2480 count = lines_in_file(fd, buf, sizeof(buf));
2484 seltofile(fd, &count);
2488 snprintf(buf, sizeof(buf), patterns[P_CPMVFMT], g_tmpfpath);
2489 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2491 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2493 fd = open(g_tmpfpath, O_RDONLY);
2497 lines = lines_in_file(fd, buf, sizeof(buf));
2500 if (!lines || (2 * count != lines)) {
2501 DPRINTF_S("num mismatch");
2505 snprintf(buf, sizeof(buf), patterns[P_CPMVRNM], path, g_tmpfpath, cmd);
2506 if (!spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CHKRTN))
2515 static bool cpmvrm_selection(enum action sel, char *path)
2519 if (!selbufpos && isselfileempty()) {
2520 printmsg(messages[MSG_0_SELECTED]);
2535 r = get_input(messages[MSG_CP_MV_AS]);
2536 if (r != 'c' && r != 'm') {
2537 printmsg(messages[MSG_INVALID_KEY]);
2541 if (!cpmv_rename(r, path)) {
2542 printmsg(messages[MSG_FAILED]);
2546 default: /* SEL_RM */
2547 if (!rmmulstr(g_buf)) {
2548 printmsg(messages[MSG_CANCEL]);
2553 if (sel != SEL_CPMVAS && spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CHKRTN)) {
2554 printmsg(messages[MSG_FAILED]);
2558 /* Clear selection */
2565 static bool batch_rename(void)
2568 uint_t count = 0, lines = 0;
2569 bool dir = FALSE, ret = FALSE;
2570 char foriginal[TMP_LEN_MAX] = {0};
2571 static const char batchrenamecmd[] = "paste -d'\n' %s %s | "SED" 'N; /^\\(.*\\)\\n\\1$/!p;d' | "
2572 "tr '\n' '\\0' | xargs -0 -n2 sh -c 'mv -i \"$0\" \"$@\" <"
2574 char buf[sizeof(batchrenamecmd) + (PATH_MAX << 1)];
2575 int i = get_cur_or_sel();
2580 if (i == 'c') { /* Rename entries in current dir */
2585 fd1 = create_tmp_file();
2589 xstrsncpy(foriginal, g_tmpfpath, xstrlen(g_tmpfpath) + 1);
2591 fd2 = create_tmp_file();
2599 for (i = 0; i < ndents; ++i)
2600 appendfpath(pdents[i].name, NAME_MAX);
2602 seltofile(fd1, &count);
2603 seltofile(fd2, NULL);
2606 if (dir) /* Don't retain dir entries in selection */
2609 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2611 /* Reopen file descriptor to get updated contents */
2612 fd2 = open(g_tmpfpath, O_RDONLY);
2616 lines = lines_in_file(fd2, buf, sizeof(buf));
2619 if (!lines || (count != lines)) {
2620 DPRINTF_S("cannot delete files");
2624 snprintf(buf, sizeof(buf), batchrenamecmd, foriginal, g_tmpfpath);
2625 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2641 static void get_archive_cmd(char *cmd, const char *archive)
2645 if (getutil(utils[UTIL_ATOOL]))
2647 else if (getutil(utils[UTIL_BSDTAR]))
2649 else if (is_suffix(archive, ".zip"))
2653 xstrsncpy(cmd, archive_cmd[i], ARCHIVE_CMD_LEN);
2656 static void archive_selection(const char *cmd, const char *archive, const char *curpath)
2658 /* The 70 comes from the string below */
2659 char *buf = (char *)malloc((70 + xstrlen(cmd) + xstrlen(archive)
2660 + xstrlen(curpath) + xstrlen(selpath)) * sizeof(char));
2662 DPRINTF_S(strerror(errno));
2667 snprintf(buf, CMD_LEN_MAX,
2669 SED" -ze 's|^%s/||' '%s' | xargs -0 %s %s", curpath, selpath, cmd, archive
2671 "tr '\\0' '\n' < '%s' | "SED" -e 's|^%s/||' | tr '\n' '\\0' | xargs -0 %s %s",
2672 selpath, curpath, cmd, archive
2675 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CONFIRM);
2679 static bool write_lastdir(const char *curpath)
2682 size_t len = xstrlen(cfgpath);
2684 xstrsncpy(cfgpath + len, "/.lastd", 8);
2686 int fd = open(cfgpath, O_CREAT | O_WRONLY | O_TRUNC, 0666);
2689 dprintf(fd, "cd \"%s\"", curpath);
2697 * We assume none of the strings are NULL.
2699 * Let's have the logic to sort numeric names in numeric order.
2700 * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
2702 * If the absolute numeric values are same, we fallback to alphasort.
2704 static int xstricmp(const char * const s1, const char * const s2)
2708 long long v1 = strtoll(s1, &p1, 10);
2709 long long v2 = strtoll(s2, &p2, 10);
2711 /* Check if at least 1 string is numeric */
2712 if (s1 != p1 || s2 != p2) {
2713 /* Handle both pure numeric */
2714 if (s1 != p1 && s2 != p2) {
2722 /* Only first string non-numeric */
2726 /* Only second string non-numeric */
2731 /* Handle 1. all non-numeric and 2. both same numeric value cases */
2733 return strcoll(s1, s2);
2735 return strcasecmp(s1, s2);
2740 * Version comparison
2742 * The code for version compare is a modified version of the GLIBC
2743 * and uClibc implementation of strverscmp(). The source is here:
2744 * https://elixir.bootlin.com/uclibc-ng/latest/source/libc/string/strverscmp.c
2748 * Compare S1 and S2 as strings holding indices/version numbers,
2749 * returning less than, equal to or greater than zero if S1 is less than,
2750 * equal to or greater than S2 (for more info, see the texinfo doc).
2754 static int xstrverscasecmp(const char * const s1, const char * const s2)
2756 const uchar_t *p1 = (const uchar_t *)s1;
2757 const uchar_t *p2 = (const uchar_t *)s2;
2762 * Symbol(s) 0 [1-9] others
2763 * Transition (10) 0 (01) d (00) x
2765 static const uint8_t next_state[] = {
2767 /* S_N */ S_N, S_I, S_Z,
2768 /* S_I */ S_N, S_I, S_I,
2769 /* S_F */ S_N, S_F, S_F,
2770 /* S_Z */ S_N, S_F, S_Z
2773 static const int8_t result_type[] __attribute__ ((aligned)) = {
2774 /* state x/x x/d x/0 d/x d/d d/0 0/x 0/d 0/0 */
2776 /* S_N */ VCMP, VCMP, VCMP, VCMP, VLEN, VCMP, VCMP, VCMP, VCMP,
2777 /* S_I */ VCMP, -1, -1, 1, VLEN, VLEN, 1, VLEN, VLEN,
2778 /* S_F */ VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP,
2779 /* S_Z */ VCMP, 1, 1, -1, VCMP, VCMP, -1, VCMP, VCMP
2790 /* Hint: '0' is a digit too. */
2791 state = S_N + ((c1 == '0') + (xisdigit(c1) != 0));
2793 while ((diff = c1 - c2) == 0) {
2797 state = next_state[state];
2802 state += (c1 == '0') + (xisdigit(c1) != 0);
2805 state = result_type[state * 3 + (((c2 == '0') + (xisdigit(c2) != 0)))]; // NOLINT
2811 while (xisdigit(*p1++))
2812 if (!xisdigit(*p2++))
2814 return xisdigit(*p2) ? -1 : diff;
2820 static int (*namecmpfn)(const char * const s1, const char * const s2) = &xstricmp;
2822 static char * (*fnstrstr)(const char *haystack, const char *needle) = &strcasestr;
2824 static const unsigned char *tables;
2825 static int pcreflags = PCRE_NO_AUTO_CAPTURE | PCRE_EXTENDED | PCRE_CASELESS | PCRE_UTF8;
2827 static int regflags = REG_NOSUB | REG_EXTENDED | REG_ICASE;
2831 static int setfilter(pcre **pcrex, const char *filter)
2833 const char *errstr = NULL;
2836 *pcrex = pcre_compile(filter, pcreflags, &errstr, &erroffset, tables);
2838 return errstr ? -1 : 0;
2841 static int setfilter(regex_t *regex, const char *filter)
2843 return regcomp(regex, filter, regflags);
2847 static int visible_re(const fltrexp_t *fltrexp, const char *fname)
2850 return pcre_exec(fltrexp->pcrex, NULL, fname, xstrlen(fname), 0, 0, NULL, 0) == 0;
2852 return regexec(fltrexp->regex, fname, 0, NULL, 0) == 0;
2856 static int visible_str(const fltrexp_t *fltrexp, const char *fname)
2858 return fnstrstr(fname, fltrexp->str) != NULL;
2861 static int (*filterfn)(const fltrexp_t *fltr, const char *fname) = &visible_str;
2863 static void clearfilter(void)
2865 char *fltr = g_ctx[cfg.curctx].c_fltr;
2868 fltr[REGEX_MAX - 1] = fltr[1];
2873 static int entrycmp(const void *va, const void *vb)
2875 const struct entry *pa = (pEntry)va;
2876 const struct entry *pb = (pEntry)vb;
2878 if ((pb->flags & DIR_OR_DIRLNK) != (pa->flags & DIR_OR_DIRLNK)) {
2879 if (pb->flags & DIR_OR_DIRLNK)
2884 /* Sort based on specified order */
2885 if (cfg.timeorder) {
2886 if (pb->sec > pa->sec)
2888 if (pb->sec < pa->sec)
2890 /* If sec matches, comare nsec */
2891 if (pb->nsec > pa->nsec)
2893 if (pb->nsec < pa->nsec)
2895 } else if (cfg.sizeorder) {
2896 if (pb->size > pa->size)
2898 if (pb->size < pa->size)
2900 } else if (cfg.blkorder) {
2901 if (pb->blocks > pa->blocks)
2903 if (pb->blocks < pa->blocks)
2905 } else if (cfg.extnorder && !(pb->flags & DIR_OR_DIRLNK)) {
2906 char *extna = xextension(pa->name, pa->nlen - 1);
2907 char *extnb = xextension(pb->name, pb->nlen - 1);
2909 if (extna || extnb) {
2916 int ret = strcasecmp(extna, extnb);
2923 return namecmpfn(pa->name, pb->name);
2926 static int reventrycmp(const void *va, const void *vb)
2928 if ((((pEntry)vb)->flags & DIR_OR_DIRLNK)
2929 != (((pEntry)va)->flags & DIR_OR_DIRLNK)) {
2930 if (((pEntry)vb)->flags & DIR_OR_DIRLNK)
2935 return -entrycmp(va, vb);
2938 static int (*entrycmpfn)(const void *va, const void *vb) = &entrycmp;
2940 /* In case of an error, resets *wch to Esc */
2941 static int handle_alt_key(wint_t *wch)
2945 int r = get_wch(wch);
2955 * Returns SEL_* if key is bound and 0 otherwise.
2956 * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
2957 * The next keyboard input can be simulated by presel.
2959 static int nextsel(int presel)
2966 bool escaped = FALSE;
2968 if (c == 0 || c == MSGWAIT) {
2972 //DPRINTF_S(keyname(c));
2975 if (c == KEY_RESIZE)
2976 handle_key_resize();
2979 /* Handle Alt+key */
2991 } else if (escaped) {
2996 if (!g_state.fifomode)
2997 notify_fifo(TRUE); /* Send hovered path to NNN_FIFO */
3005 if (c == ERR && presel == MSGWAIT)
3006 c = (cfg.filtermode || filterset()) ? FILTER : CONTROL('L');
3007 else if (c == FILTER || c == CONTROL('L'))
3008 /* Clear previous filter when manually starting */
3016 * Do not check for directory changes in du mode.
3017 * A redraw forces du calculation.
3018 * Check for changes every odd second.
3020 #ifdef LINUX_INOTIFY
3021 if (!g_state.selmode && !cfg.blkorder && inotify_wd >= 0 && (idle & 1)) {
3022 struct inotify_event *event;
3023 char inotify_buf[EVENT_BUF_LEN];
3025 memset((void *)inotify_buf, 0x0, EVENT_BUF_LEN);
3026 i = read(inotify_fd, inotify_buf, EVENT_BUF_LEN);
3028 for (char *ptr = inotify_buf;
3029 ptr + ((struct inotify_event *)ptr)->len < inotify_buf + i;
3030 ptr += sizeof(struct inotify_event) + event->len) {
3031 event = (struct inotify_event *)ptr;
3032 DPRINTF_D(event->wd);
3033 DPRINTF_D(event->mask);
3037 if (event->mask & INOTIFY_MASK) {
3039 DPRINTF_S("issue refresh");
3043 DPRINTF_S("inotify read done");
3046 #elif defined(BSD_KQUEUE)
3047 if (!g_state.selmode && !cfg.blkorder && event_fd >= 0 && idle & 1) {
3048 struct kevent event_data[NUM_EVENT_SLOTS];
3050 memset((void *)event_data, 0x0, sizeof(struct kevent) * NUM_EVENT_SLOTS);
3051 if (kevent(kq, events_to_monitor, NUM_EVENT_SLOTS,
3052 event_data, NUM_EVENT_FDS, >imeout) > 0)
3055 #elif defined(HAIKU_NM)
3056 if (!g_state.selmode && !cfg.blkorder && haiku_nm_active
3057 && (idle & 1) && haiku_is_update_needed(haiku_hnd))
3063 for (i = 0; i < (int)ELEMENTS(bindings); ++i)
3064 if (c == bindings[i].sym)
3065 return bindings[i].act;
3070 static int getorderstr(char *sort)
3078 sort[i++] = (cfg.timetype == T_MOD) ? 'M' : ((cfg.timetype == T_ACCESS) ? 'A' : 'C');
3079 else if (cfg.sizeorder)
3081 else if (cfg.extnorder)
3084 if (entrycmpfn == &reventrycmp)
3087 if (namecmpfn == &xstrverscasecmp)
3096 static void showfilterinfo(void)
3099 char info[REGEX_MAX] = "\0\0\0\0\0";
3101 i = getorderstr(info);
3103 snprintf(info + i, REGEX_MAX - i - 1, " %s [/], %s [:]",
3104 (cfg.regex ? "reg" : "str"),
3105 ((fnstrstr == &strcasestr) ? "ic" : "noic"));
3108 mvaddstr(xlines - 2, xcols - xstrlen(info), info);
3111 static void showfilter(char *str)
3113 attron(COLOR_PAIR(cfg.curctx + 1));
3116 // printmsg calls attroff()
3119 static inline void swap_ent(int id1, int id2)
3121 struct entry _dent, *pdent1 = &pdents[id1], *pdent2 = &pdents[id2];
3123 *(&_dent) = *pdent1;
3125 *pdent2 = *(&_dent);
3129 static int fill(const char *fltr, pcre *pcrex)
3131 static int fill(const char *fltr, regex_t *re)
3135 fltrexp_t fltrexp = { .pcrex = pcrex, .str = fltr };
3137 fltrexp_t fltrexp = { .regex = re, .str = fltr };
3140 for (int count = 0; count < ndents; ++count) {
3141 if (filterfn(&fltrexp, pdents[count].name) == 0) {
3142 if (count != --ndents) {
3143 swap_ent(count, ndents);
3154 static int matches(const char *fltr)
3160 if (cfg.regex && setfilter(&pcrex, fltr))
3163 ndents = fill(fltr, pcrex);
3171 if (cfg.regex && setfilter(&re, fltr))
3174 ndents = fill(fltr, &re);
3180 ENTSORT(pdents, ndents, entrycmpfn);
3186 * Return the position of the matching entry or 0 otherwise
3187 * Note there's no NULL check for fname
3189 static int dentfind(const char *fname, int n)
3191 for (int i = 0; i < n; ++i)
3192 if (xstrcmp(fname, pdents[i].name) == 0)
3198 static int filterentries(char *path, char *lastname)
3200 wchar_t *wln = (wchar_t *)alloca(sizeof(wchar_t) * REGEX_MAX);
3201 char *ln = g_ctx[cfg.curctx].c_fltr;
3203 int r, total = ndents, len;
3204 char *pln = g_ctx[cfg.curctx].c_fltr + 1;
3206 DPRINTF_S(__func__);
3208 if (ndents && (ln[0] == FILTER || ln[0] == RFILTER) && *pln) {
3209 if (matches(pln) != -1) {
3210 move_cursor(dentfind(lastname, ndents), 0);
3214 if (!cfg.filtermode)
3217 len = mbstowcs(wln, ln, REGEX_MAX);
3219 ln[0] = wln[0] = cfg.regex ? RFILTER : FILTER;
3220 ln[1] = wln[1] = '\0';
3228 while ((r = get_wch(ch)) != ERR) {
3230 //DPRINTF_S(keyname(*ch));
3234 case 0: // fallthrough
3241 case KEY_DC: // fallthrough
3242 case KEY_BACKSPACE: // fallthrough
3243 case '\b': // fallthrough
3244 case DEL: /* handle DEL */
3247 wcstombs(ln, wln, REGEX_MAX);
3255 if (*ch == CONTROL('L')) {
3257 ln[REGEX_MAX - 1] = ln[1];
3258 ln[1] = wln[1] = '\0';
3261 } else if (ln[REGEX_MAX - 1]) { /* Show the previous filter */
3262 ln[1] = ln[REGEX_MAX - 1];
3263 ln[REGEX_MAX - 1] = '\0';
3264 len = mbstowcs(wln, ln, REGEX_MAX);
3269 /* Go to the top, we don't know if the hovered file will match the filter */
3272 if (matches(pln) != -1)
3282 if (handle_alt_key(ch) != ERR) {
3283 if (*ch == ESC) /* Handle Alt+Esc */
3284 *ch = 'q'; /* Quit context */
3287 *ch = ';'; /* Run plugin */
3293 if (r != OK) /* Handle Fn keys in main loop */
3296 /* Handle all control chars in main loop */
3297 if (*ch < ASCII_MAX && keyname(*ch)[0] == '^' && *ch != '^')
3301 if (*ch == '?') /* Help and config key, '?' is an invalid regex */
3304 if (cfg.filtermode) {
3306 case '\'': // fallthrough /* Go to first non-dir file */
3307 case '+': // fallthrough /* Toggle auto-advance */
3308 case ',': // fallthrough /* Mark CWD */
3309 case '-': // fallthrough /* Visit last visited dir */
3310 case '.': // fallthrough /* Show hidden files */
3311 case ';': // fallthrough /* Run plugin key */
3312 case '=': // fallthrough /* Launch app */
3313 case '>': // fallthrough /* Export file list */
3314 case '@': // fallthrough /* Visit start dir */
3315 case ']': // fallthorugh /* Prompt key */
3316 case '`': // fallthrough /* Visit / */
3317 case '~': /* Go HOME */
3322 /* Toggle case-sensitivity */
3324 fnstrstr = (fnstrstr == &strcasestr) ? &strstr : &strcasestr;
3326 pcreflags ^= PCRE_CASELESS;
3328 regflags ^= REG_ICASE;
3334 /* Toggle string or regex filter */
3335 if (*ch == FILTER) {
3336 ln[0] = (ln[0] == FILTER) ? RFILTER : FILTER;
3337 wln[0] = (uchar_t)ln[0];
3339 filterfn = cfg.regex ? &visible_re : &visible_str;
3344 /* Reset cur in case it's a repeat search */
3346 } else if (len == REGEX_MAX - 1)
3349 wln[len] = (wchar_t)*ch;
3351 wcstombs(ln, wln, REGEX_MAX);
3353 /* Forward-filtering optimization:
3354 * - new matches can only be a subset of current matches.
3356 /* ndents = total; */
3359 !r ? unget_wch(KEY_BACKSPACE) : showfilter(ln);
3363 /* If the only match is a dir, auto-select and cd into it */
3364 if (ndents == 1 && cfg.filtermode
3365 && cfg.autoselect && (pdents[0].flags & DIR_OR_DIRLNK)) {
3372 * redraw() should be above the auto-select optimization, for
3373 * the case where there's an issue with dir auto-select, say,
3374 * due to a permission problem. The transition is _jumpy_ in
3375 * case of such an error. However, we optimize for successful
3376 * cases where the dir has permissions. This skips a redraw().
3384 /* Save last working filter in-filter */
3386 ln[REGEX_MAX - 1] = ln[1];
3395 /* Return keys for navigation etc. */
3399 /* Show a prompt with input string and return the changes */
3400 static char *xreadline(const char *prefill, const char *prompt)
3404 const int WCHAR_T_WIDTH = sizeof(wchar_t);
3406 wchar_t * const buf = malloc(sizeof(wchar_t) * READLINE_MAX);
3416 len = pos = mbstowcs(buf, prefill, READLINE_MAX);
3420 if (len == (size_t)-1) {
3425 x = getcurx(stdscr);
3430 attron(COLOR_PAIR(cfg.curctx + 1));
3431 mvaddnwstr(xlines - 1, x, buf, len + 1);
3432 move(xlines - 1, x + wcswidth(buf, pos));
3433 attroff(COLOR_PAIR(cfg.curctx + 1));
3441 case KEY_ENTER: // fallthrough
3442 case '\n': // fallthrough
3448 else if (!(pos || len)) { /* Exit on ^D at empty prompt */
3454 case DEL: // fallthrough
3455 case '\b': /* rhel25 sends '\b' for backspace */
3457 memmove(buf + pos - 1, buf + pos,
3458 (len - pos) * WCHAR_T_WIDTH);
3463 if (!(len || pos) && ndents)
3464 len = pos = mbstowcs(buf, pdents[cur].name, READLINE_MAX);
3479 memmove(buf + pos - 1, buf + pos,
3480 (len - pos) * WCHAR_T_WIDTH);
3482 } while (buf[pos - 1] != ' ' && buf[pos - 1] != '/'); // NOLINT
3500 memmove(buf, buf + pos, (len - pos) * WCHAR_T_WIDTH);
3504 case ESC: /* Exit prompt on Esc, but just filter out Alt+key */
3505 if (handle_alt_key(ch) != ERR)
3512 /* Filter out all other control chars */
3513 if (*ch < ASCII_MAX && keyname(*ch)[0] == '^')
3516 if (pos < READLINE_MAX - 1) {
3517 memmove(buf + pos + 1, buf + pos,
3518 (len - pos) * WCHAR_T_WIDTH);
3542 memmove(buf + pos - 1, buf + pos,
3543 (len - pos) * WCHAR_T_WIDTH);
3549 memmove(buf + pos, buf + pos + 1,
3550 (len - pos - 1) * WCHAR_T_WIDTH);
3560 case KEY_UP: // fallthrough
3562 if (prompt && lastcmd && (xstrcmp(prompt, PROMPT) == 0)) {
3564 len = pos = mbstowcs(buf, lastcmd, READLINE_MAX); // fallthrough
3579 pos = wcstombs(g_buf, buf, READLINE_MAX - 1);
3580 if (pos >= READLINE_MAX - 1)
3581 g_buf[READLINE_MAX - 1] = '\0';
3589 * Caller should check the value of presel to confirm if it needs to wait to show warning
3591 static char *getreadline(const char *prompt)
3595 char *input = readline(prompt);
3599 if (input && input[0]) {
3601 xstrsncpy(g_buf, input, CMD_LEN_MAX);
3612 * Create symbolic/hard link(s) to file(s) in selection list
3613 * Returns the number of links created, -1 on error
3615 static int xlink(char *prefix, char *path, char *curfname, char *buf, int *presel, int type)
3617 int count = 0, choice;
3618 char *psel = pselbuf, *fname;
3619 size_t pos = 0, len, r;
3620 int (*link_fn)(const char *, const char *) = NULL;
3621 char lnpath[PATH_MAX];
3623 choice = get_cur_or_sel();
3627 if (type == 's') /* symbolic link */
3629 else /* hard link */
3632 if (choice == 'c') {
3633 r = xstrsncpy(buf, prefix, NAME_MAX + 1); /* Copy prefix */
3634 xstrsncpy(buf + r - 1, curfname, NAME_MAX - r); /* Suffix target file name */
3635 mkpath(path, buf, lnpath); /* Generate link path */
3636 mkpath(path, curfname, buf); /* Generate target file path */
3638 if (!link_fn(buf, lnpath))
3639 return 1; /* One link created */
3645 while (pos < selbufpos) {
3646 len = xstrlen(psel);
3647 fname = xbasename(psel);
3649 r = xstrsncpy(buf, prefix, NAME_MAX + 1); /* Copy prefix */
3650 xstrsncpy(buf + r - 1, fname, NAME_MAX - r); /* Suffix target file name */
3651 mkpath(path, buf, lnpath); /* Generate link path */
3653 if (!link_fn(psel, lnpath))
3664 static bool parsekvpair(kv **arr, char **envcpy, const uchar_t id, uchar_t *items)
3667 const uchar_t INCR = 8;
3670 char *ptr = getenv(env_cfg[id]);
3675 *envcpy = xstrdup(ptr);
3683 while (*ptr && i < 100) {
3685 if (!(i & (INCR - 1))) {
3686 kvarr = xrealloc(kvarr, sizeof(kv) * (i + INCR));
3692 memset(kvarr + i, 0, sizeof(kv) * INCR);
3694 kvarr[i].key = (uchar_t)*ptr;
3695 if (*++ptr != ':' || *++ptr == '\0' || *ptr == ';')
3697 kvarr[i].off = ptr - *envcpy;
3716 * Get the value corresponding to a key
3718 * NULL is returned in case of no match, path resolution failure etc.
3719 * buf would be modified, so check return value before access
3721 static char *get_kv_val(kv *kvarr, char *buf, int key, uchar_t max, uchar_t id)
3728 for (int r = 0; kvarr[r].key && r < max; ++r) {
3729 if (kvarr[r].key == key) {
3730 /* Do not allocate new memory for plugin */
3732 return pluginstr + kvarr[r].off;
3734 val = bmstr + kvarr[r].off;
3736 if (val[0] == '~') {
3737 ssize_t len = xstrlen(home);
3738 ssize_t loclen = xstrlen(val);
3740 xstrsncpy(g_buf, home, len + 1);
3741 xstrsncpy(g_buf + len, val + 1, loclen);
3744 return realpath(((val[0] == '~') ? g_buf : val), buf);
3748 DPRINTF_S("Invalid key");
3752 static void resetdircolor(int flags)
3754 /* Directories are always shown on top, clear the color when moving to first file */
3755 if (g_state.dircolor && !(flags & DIR_OR_DIRLNK)) {
3756 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
3757 g_state.dircolor = 0;
3762 * Replace escape characters in a string with '?'
3763 * Adjust string length to maxcols if > 0;
3764 * Max supported str length: NAME_MAX;
3767 static char *unescape(const char *str, uint_t maxcols)
3769 char * const wbuf = g_buf;
3772 xstrsncpy(wbuf, str, maxcols);
3774 static wchar_t *unescape(const char *str, uint_t maxcols)
3776 wchar_t * const wbuf = (wchar_t *)g_buf;
3777 wchar_t *buf = wbuf;
3778 size_t len = mbstowcs(wbuf, str, maxcols); /* Convert multi-byte to wide char */
3780 len = wcswidth(wbuf, len);
3782 if (len >= maxcols) {
3783 size_t lencount = maxcols;
3785 while (len > maxcols) /* Reduce wide chars one by one till it fits */
3786 len = wcswidth(wbuf, --lencount);
3788 wbuf[lencount] = L'\0';
3793 if (*buf <= '\x1f' || *buf == '\x7f')
3802 static off_t get_size(off_t size, off_t *pval, int comp)
3805 off_t quo = rem / 10;
3807 if ((rem - (quo * 10)) >= 5) {
3820 static char *coolsize(off_t size)
3822 const char * const U = "BKMGTPEZY";
3823 static char size_buf[12]; /* Buffer to hold human readable size */
3828 while (size >= 1024) {
3829 rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
3835 rem = (rem * 1000) >> 10;
3837 size = get_size(size, &rem, 10);
3838 } else if (i == 2) {
3839 rem = (rem * 1000) >> 10;
3840 size = get_size(size, &rem, 100);
3842 rem = (rem * 10000) >> 10;
3843 size = get_size(size, &rem, 1000);
3846 if (i > 0 && i < 6 && rem) {
3847 ret = xstrsncpy(size_buf, xitoa(size), 12);
3848 size_buf[ret - 1] = '.';
3850 char *frac = xitoa(rem);
3851 size_t toprint = i > 3 ? 3 : i;
3852 size_t len = xstrlen(frac);
3854 if (len < toprint) {
3855 size_buf[ret] = size_buf[ret + 1] = size_buf[ret + 2] = '0';
3856 xstrsncpy(size_buf + ret + (toprint - len), frac, len + 1);
3858 xstrsncpy(size_buf + ret, frac, toprint + 1);
3862 ret = xstrsncpy(size_buf, size ? xitoa(size) : "0", 12);
3866 size_buf[ret] = U[i];
3867 size_buf[ret + 1] = '\0';
3872 /* Convert a mode field into "ls -l" type perms field. */
3873 static char *get_lsperms(mode_t mode)
3875 static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
3876 static char bits[11] = {'\0'};
3878 switch (mode & S_IFMT) {
3905 xstrsncpy(&bits[1], rwx[(mode >> 6) & 7], 4);
3906 xstrsncpy(&bits[4], rwx[(mode >> 3) & 7], 4);
3907 xstrsncpy(&bits[7], rwx[(mode & 7)], 4);
3910 bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
3912 bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
3914 bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
3919 #ifdef ICONS_ENABLED
3920 static const struct icon_pair *get_icon(const struct entry *ent)
3924 for (; i < sizeof(icons_name)/sizeof(struct icon_pair); ++i)
3925 if (strcasecmp(ent->name, icons_name[i].match) == 0)
3926 return &icons_name[i];
3928 if (ent->flags & DIR_OR_DIRLNK)
3931 char *tmp = xextension(ent->name, ent->nlen);
3934 if (ent->mode & 0100)
3943 if (*tmp >= '0' && *tmp <= '9')
3944 i = *tmp - '0'; /* NUMBER 0-9 */
3945 else if (TOUPPER(*tmp) >= 'A' && TOUPPER(*tmp) <= 'Z')
3946 i = TOUPPER(*tmp) - 'A' + 10; /* LETTER A-Z */
3950 for (ushort_t j = icon_positions[i]; j < sizeof(icons_ext)/sizeof(struct icon_pair) &&
3951 icons_ext[j].match[0] == icons_ext[icon_positions[i]].match[0]; ++j)
3952 if (strcasecmp(tmp, icons_ext[j].match) == 0)
3953 return &icons_ext[j];
3955 /* If there's no match and the file is executable, icon that */
3956 if (ent->mode & 0100)
3962 static void print_icon(const struct entry *ent, const int attrs)
3964 const struct icon_pair *picon = get_icon(ent);
3966 addstr(ICON_PADDING_LEFT);
3968 attron(COLOR_PAIR(C_UND + 1 + picon->color));
3971 addstr(picon->icon);
3973 attroff(COLOR_PAIR(C_UND + 1 + picon->color));
3976 addstr(ICON_PADDING_RIGHT);
3980 static void print_time(const time_t *timep)
3984 localtime_r(timep, &t);
3985 printw("%s-%02d-%02d %02d:%02d",
3986 xitoa(t.tm_year + 1900), t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min);
3989 static char get_detail_ind(const mode_t mode)
3991 switch (mode & S_IFMT) {
3992 case S_IFDIR: // fallthrough
3993 case S_IFREG: return ' ';
3994 case S_IFLNK: return '@';
3995 case S_IFSOCK: return '=';
3996 case S_IFIFO: return '|';
3997 case S_IFBLK: return 'b';
3998 case S_IFCHR: return 'c';
4003 /* Note: attribute and indicator values must be initialized to 0 */
4004 static uchar_t get_color_pair_name_ind(const struct entry *ent, char *pind, int *pattr)
4006 switch (ent->mode & S_IFMT) {
4009 if (ent->mode & 0100)
4013 if (ent->flags & HARD_LINK) {
4014 if (ent->mode & 0100)
4018 if (ent->mode & 0100) {
4025 if (g_state.oldcolor)
4028 return g_state.dirctx ? cfg.curctx + 1 : C_DIR;
4030 if (ent->flags & DIR_OR_DIRLNK) {
4032 *pattr |= g_state.oldcolor ? A_DIM : A_BOLD;
4035 if (g_state.oldcolor)
4038 if (!g_state.oldcolor || cfg.showdetail)
4039 return (ent->flags & SYM_ORPHAN) ? C_ORP : C_LNK;
4057 static void printent(const struct entry *ent, uint_t namecols, bool sel)
4062 if (cfg.showdetail) {
4063 int type = ent->mode & S_IFMT;
4064 char perms[6] = {' ', ' ', (char)('0' + ((ent->mode >> 6) & 7)),
4065 (char)('0' + ((ent->mode >> 3) & 7)),
4066 (char)('0' + (ent->mode & 7)), '\0'};
4069 attrs = g_state.oldcolor ? (resetdircolor(ent->flags), A_DIM)
4070 : (fcolors[C_MIS] ? COLOR_PAIR(C_MIS) : 0);
4075 print_time(&ent->sec);
4077 printw("%s%9s ", perms, (type == S_IFREG || type == S_IFDIR)
4078 ? coolsize(cfg.blkorder ? (blkcnt_t)ent->blocks << blk_shift : ent->size)
4079 : (type = (uchar_t)get_detail_ind(ent->mode), (char *)&type));
4087 uchar_t color_pair = get_color_pair_name_ind(ent, &ind, &attrs);
4089 addch((ent->flags & FILE_SELECTED) ? '+' | A_REVERSE | A_BOLD : ' ');
4091 if (g_state.oldcolor)
4092 resetdircolor(ent->flags);
4094 if (ent->flags & FILE_MISSING)
4096 if (color_pair && fcolors[color_pair])
4097 attrs |= COLOR_PAIR(color_pair);
4098 #ifdef ICONS_ENABLED
4099 print_icon(ent, attrs);
4111 addwstr(unescape(ent->name, namecols));
4113 addstr(unescape(ent->name, MIN(namecols, ent->nlen) + 1));
4122 static void savecurctx(char *path, char *curname, int nextctx)
4124 settings tmpcfg = cfg;
4125 context *ctxr = &g_ctx[nextctx];
4127 /* Save current context */
4129 xstrsncpy(g_ctx[tmpcfg.curctx].c_name, curname, NAME_MAX + 1);
4131 g_ctx[tmpcfg.curctx].c_name[0] = '\0';
4133 g_ctx[tmpcfg.curctx].c_cfg = tmpcfg;
4135 if (ctxr->c_cfg.ctxactive) /* Switch to saved context */
4136 tmpcfg = ctxr->c_cfg;
4137 else { /* Set up a new context from current context */
4138 ctxr->c_cfg.ctxactive = 1;
4139 xstrsncpy(ctxr->c_path, path, PATH_MAX);
4140 ctxr->c_last[0] = ctxr->c_name[0] = ctxr->c_fltr[0] = ctxr->c_fltr[1] = '\0';
4141 ctxr->c_cfg = tmpcfg;
4144 tmpcfg.curctx = nextctx;
4149 static void save_session(const char *sname, int *presel)
4152 session_header_t header;
4153 bool status = FALSE;
4154 char ssnpath[PATH_MAX];
4155 char spath[PATH_MAX];
4157 memset(&header, 0, sizeof(session_header_t));
4159 header.ver = SESSIONS_VERSION;
4161 for (i = 0; i < CTX_MAX; ++i) {
4162 if (g_ctx[i].c_cfg.ctxactive) {
4163 if (cfg.curctx == i && ndents)
4164 /* Update current file name, arrows don't update it */
4165 xstrsncpy(g_ctx[i].c_name, pdents[cur].name, NAME_MAX + 1);
4166 header.pathln[i] = strnlen(g_ctx[i].c_path, PATH_MAX) + 1;
4167 header.lastln[i] = strnlen(g_ctx[i].c_last, PATH_MAX) + 1;
4168 header.nameln[i] = strnlen(g_ctx[i].c_name, NAME_MAX) + 1;
4169 header.fltrln[i] = strnlen(g_ctx[i].c_fltr, REGEX_MAX) + 1;
4173 mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4174 mkpath(ssnpath, sname, spath);
4176 fd = open(spath, O_CREAT | O_WRONLY | O_TRUNC, 0666);
4178 printwait(messages[MSG_SEL_MISSING], presel);
4182 if ((write(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4183 || (write(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4186 for (i = 0; i < CTX_MAX; ++i)
4187 if ((write(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4188 || (write(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4189 || (header.nameln[i] > 0
4190 && write(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4191 || (header.lastln[i] > 0
4192 && write(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4193 || (header.fltrln[i] > 0
4194 && write(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4195 || (header.pathln[i] > 0
4196 && write(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4205 printwait(messages[MSG_FAILED], presel);
4208 static bool load_session(const char *sname, char **path, char **lastdir, char **lastname, bool restore)
4211 session_header_t header;
4212 bool has_loaded_dynamically = !(sname || restore);
4213 bool status = (sname && g_state.picker); /* Picker mode with session program option */
4214 char ssnpath[PATH_MAX];
4215 char spath[PATH_MAX];
4217 mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4220 sname = sname ? sname : xreadline(NULL, messages[MSG_SSN_NAME]);
4224 mkpath(ssnpath, sname, spath);
4226 /* If user is explicitly loading the "last session", skip auto-save */
4227 if ((sname[0] == '@') && !sname[1])
4228 has_loaded_dynamically = FALSE;
4230 mkpath(ssnpath, "@", spath);
4232 if (has_loaded_dynamically)
4233 save_session("@", NULL);
4235 fd = open(spath, O_RDONLY, 0666);
4238 printmsg(messages[MSG_SEL_MISSING]);
4239 xdelay(XDELAY_INTERVAL_MS);
4246 if ((read(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4247 || (header.ver != SESSIONS_VERSION)
4248 || (read(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4251 g_ctx[cfg.curctx].c_name[0] = g_ctx[cfg.curctx].c_last[0]
4252 = g_ctx[cfg.curctx].c_fltr[0] = g_ctx[cfg.curctx].c_fltr[1] = '\0';
4254 for (; i < CTX_MAX; ++i)
4255 if ((read(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4256 || (read(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4257 || (header.nameln[i] > 0
4258 && read(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4259 || (header.lastln[i] > 0
4260 && read(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4261 || (header.fltrln[i] > 0
4262 && read(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4263 || (header.pathln[i] > 0
4264 && read(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4267 *path = g_ctx[cfg.curctx].c_path;
4268 *lastdir = g_ctx[cfg.curctx].c_last;
4269 *lastname = g_ctx[cfg.curctx].c_name;
4270 set_sort_flags('\0'); /* Set correct sort options */
4277 printmsg(messages[MSG_FAILED]);
4278 xdelay(XDELAY_INTERVAL_MS);
4286 static uchar_t get_free_ctx(void)
4288 uchar_t r = cfg.curctx;
4291 r = (r + 1) & ~CTX_MAX;
4292 while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
4297 /* ctx is absolute: 1 to 4, + for smart context */
4298 static void set_smart_ctx(int ctx, char *nextpath, char **path, char **lastname, char **lastdir)
4300 if (ctx == '+') /* Get smart context */
4301 ctx = (int)(get_free_ctx() + 1);
4303 if (ctx == 0 || ctx == cfg.curctx + 1) { /* Same context */
4304 /* Mark current directory */
4306 mark = xstrdup(*path);
4308 xstrsncpy(*lastdir, *path, PATH_MAX);
4309 xstrsncpy(*path, nextpath, PATH_MAX);
4310 } else { /* New context */
4312 /* Deactivate the new context and build from scratch */
4313 g_ctx[ctx].c_cfg.ctxactive = 0;
4314 savecurctx(nextpath, pdents[cur].name, ctx);
4315 *path = g_ctx[ctx].c_path;
4316 *lastdir = g_ctx[ctx].c_last;
4317 *lastname = g_ctx[ctx].c_name;
4322 * Gets only a single line (that's what we need for now) or shows full command output in pager.
4323 * Uses g_buf internally.
4325 static bool get_output(char *file, char *arg1, char *arg2, int fdout, bool multi, bool page)
4329 int index = 0, flags;
4331 bool tmpfile = ((fdout == -1) && page);
4332 char *argv[EXEC_ARGS_MAX] = {0};
4338 fdout = create_tmp_file();
4344 cmd = parseargs(file, argv, &index);
4348 argv[index++] = file;
4351 argv[++index] = arg2;
4353 if (pipe(pipefd) == -1) {
4358 for (index = 0; index < 2; ++index) {
4359 /* Get previous flags */
4360 flags = fcntl(pipefd[index], F_GETFL, 0);
4362 /* Set bit for non-blocking flag */
4363 flags |= O_NONBLOCK;
4365 /* Change flags on fd */
4366 fcntl(pipefd[index], F_SETFL, flags);
4373 dup2(pipefd[1], STDOUT_FILENO);
4374 dup2(pipefd[1], STDERR_FILENO);
4376 execvp(*argv, argv);
4377 _exit(EXIT_SUCCESS);
4381 waitpid(pid, NULL, 0);
4385 while ((len = read(pipefd[0], g_buf, CMD_LEN_MAX - 1)) > 0) {
4387 if (fdout == -1) /* Read only the first line of output to buffer */
4389 if (write(fdout, g_buf, len) != len)
4402 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4411 * Follows the stat(1) output closely
4413 static bool show_stats(char *fpath)
4415 static char * const cmds[] = {
4416 #ifdef FILE_MIME_OPTS
4417 ("file " FILE_MIME_OPTS),
4423 size_t r = ELEMENTS(cmds);
4424 int fd = create_tmp_file();
4429 get_output(cmds[--r], fpath, NULL, fd, TRUE, FALSE);
4433 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4438 static bool xchmod(const char *fpath, mode_t mode)
4440 /* (Un)set (S_IXUSR | S_IXGRP | S_IXOTH) */
4441 (0100 & mode) ? (mode &= ~0111) : (mode |= 0111);
4443 return (chmod(fpath, mode) == 0);
4446 static size_t get_fs_info(const char *path, bool type)
4450 if (statvfs(path, &svb) == -1)
4453 if (type == CAPACITY)
4454 return (size_t)svb.f_blocks << ffs((int)(svb.f_frsize >> 1));
4456 return (size_t)svb.f_bavail << ffs((int)(svb.f_frsize >> 1));
4459 /* Create non-existent parents and a file or dir */
4460 static bool xmktree(char *path, bool dir)
4468 /* Skip the first '/' */
4471 while (*p != '\0') {
4480 /* Create folder from path to '\0' inserted at p */
4481 if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4483 // XDG_CONFIG_HOME contains a directory
4484 // that is read-only, but the full path
4486 // Try to continue and see what happens.
4487 // TODO: Find a more robust solution.
4488 if (errno == B_READ_ONLY_DEVICE)
4491 DPRINTF_S("mkdir1!");
4492 DPRINTF_S(strerror(errno));
4506 if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4507 DPRINTF_S("mkdir2!");
4508 DPRINTF_S(strerror(errno));
4512 int fd = open(path, O_CREAT, 0666);
4514 if (fd == -1 && errno != EEXIST) {
4516 DPRINTF_S(strerror(errno));
4526 /* List or extract archive */
4527 static bool handle_archive(char *fpath /* in-out param */, char op)
4529 char arg[] = "-tvf"; /* options for tar/bsdtar to list files */
4530 char *util, *outdir = NULL;
4532 bool is_atool = getutil(utils[UTIL_ATOOL]);
4535 outdir = xreadline(is_atool ? "." : xbasename(fpath), messages[MSG_NEW_PATH]);
4536 if (!outdir || !*outdir) { /* Cancelled */
4537 printwait(messages[MSG_CANCEL], NULL);
4540 /* Do not create smart context for current dir */
4541 if (!(*outdir == '.' && outdir[1] == '\0')) {
4542 if (!xmktree(outdir, TRUE) || (chdir(outdir) == -1)) {
4546 /* Copy the new dir path to open it in smart context */
4547 outdir = realpath(".", NULL);
4553 util = utils[UTIL_ATOOL];
4556 } else if (getutil(utils[UTIL_BSDTAR])) {
4557 util = utils[UTIL_BSDTAR];
4560 } else if (is_suffix(fpath, ".zip")) {
4561 util = utils[UTIL_UNZIP];
4562 arg[1] = (op == 'l') ? 'v' /* verbose listing */ : '\0';
4565 util = utils[UTIL_TAR];
4570 if (op == 'x') /* extract */
4571 spawn(util, arg, fpath, NULL, F_NORMAL | F_MULTI);
4573 get_output(util, arg, fpath, -1, TRUE, TRUE);
4576 if (chdir(xdirname(fpath)) == -1) {
4581 xstrsncpy(fpath, outdir, PATH_MAX);
4583 } else if (op == 'x')
4589 static char *visit_parent(char *path, char *newpath, int *presel)
4593 /* There is no going back */
4594 if (istopdir(path)) {
4595 /* Continue in type-to-nav mode, if enabled */
4596 if (cfg.filtermode && presel)
4601 /* Use a copy as xdirname() may change the string passed */
4603 xstrsncpy(newpath, path, PATH_MAX);
4607 dir = xdirname(newpath);
4608 if (chdir(dir) == -1) {
4616 static void valid_parent(char *path, char *lastname)
4619 xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
4621 while (!istopdir(path))
4622 if (visit_parent(path, NULL, NULL))
4626 xdelay(XDELAY_INTERVAL_MS);
4629 static bool archive_mount(char *newpath)
4631 char *str = "install archivemount";
4632 char *dir, *cmd = str + 8; /* Start of "archivemount" */
4633 char *name = pdents[cur].name;
4634 size_t len = pdents[cur].nlen;
4635 char mntpath[PATH_MAX];
4637 if (!getutil(cmd)) {
4642 dir = xstrdup(name);
4644 printmsg(messages[MSG_FAILED]);
4649 if (dir[--len] == '.') {
4656 /* Create the mount point */
4657 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4658 mkpath(mntpath, dir, newpath);
4661 if (!xmktree(newpath, TRUE)) {
4669 if (spawn(cmd, name, newpath, NULL, F_NORMAL)) {
4670 printmsg(messages[MSG_FAILED]);
4677 static bool remote_mount(char *newpath)
4679 uchar_t flag = F_CLI;
4682 bool r = getutil(utils[UTIL_RCLONE]), s = getutil(utils[UTIL_SSHFS]);
4683 char mntpath[PATH_MAX];
4686 printmsg("install sshfs/rclone");
4691 opt = get_input(messages[MSG_REMOTE_OPTS]);
4693 opt = (!s) ? 'r' : 's';
4696 env = xgetenv("NNN_SSHFS", utils[UTIL_SSHFS]);
4697 else if (opt == 'r') {
4698 flag |= F_NOWAIT | F_NOTRACE;
4699 env = xgetenv("NNN_RCLONE", "rclone mount");
4701 printmsg(messages[MSG_INVALID_KEY]);
4705 tmp = xreadline(NULL, "host[:dir] > ");
4707 printmsg(messages[MSG_CANCEL]);
4711 char *div = strchr(tmp, ':');
4716 /* Create the mount point */
4717 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4718 mkpath(mntpath, tmp, newpath);
4719 if (!xmktree(newpath, TRUE)) {
4724 if (!div) { /* Convert "host" to "host:" */
4725 size_t len = xstrlen(tmp);
4728 tmp[len + 1] = '\0';
4732 /* Connect to remote */
4734 if (spawn(env, tmp, newpath, NULL, flag)) {
4735 printmsg(messages[MSG_FAILED]);
4739 spawn(env, tmp, newpath, NULL, flag);
4740 printmsg(messages[MSG_RCLONE_DELAY]);
4741 xdelay(XDELAY_INTERVAL_MS << 2); /* Set 4 times the usual delay */
4748 * Unmounts if the directory represented by name is a mount point.
4749 * Otherwise, asks for hostname
4750 * Returns TRUE if directory needs to be refreshed *.
4752 static bool unmount(char *name, char *newpath, int *presel, char *currentpath)
4754 #if defined(__APPLE__) || defined(__FreeBSD__)
4755 static char cmd[] = "umount";
4757 static char cmd[] = "fusermount3"; /* Arch Linux utility */
4758 static bool found = FALSE;
4761 struct stat sb, psb;
4763 bool parent = FALSE;
4764 bool hovered = FALSE;
4765 char mntpath[PATH_MAX];
4767 #if !defined(__APPLE__) && !defined(__FreeBSD__)
4768 /* On Ubuntu it's fusermount */
4769 if (!found && !getutil(cmd)) {
4775 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4777 if (tmp && strcmp(mntpath, currentpath) == 0) {
4778 mkpath(mntpath, tmp, newpath);
4779 child = lstat(newpath, &sb) != -1;
4780 parent = lstat(xdirname(newpath), &psb) != -1;
4781 if (!child && !parent) {
4787 if (!tmp || !child || !S_ISDIR(sb.st_mode) || (child && parent && sb.st_dev == psb.st_dev)) {
4788 tmp = xreadline(NULL, messages[MSG_HOSTNAME]);
4791 if (name && (tmp[0] == '-') && (tmp[1] == '\0')) {
4792 mkpath(currentpath, name, newpath);
4798 mkpath(mntpath, tmp, newpath);
4800 if (!xdiraccess(newpath)) {
4805 #if defined(__APPLE__) || defined(__FreeBSD__)
4806 if (spawn(cmd, newpath, NULL, NULL, F_NORMAL)) {
4808 if (spawn(cmd, "-qu", newpath, NULL, F_NORMAL)) {
4810 if (!xconfirm(get_input(messages[MSG_LAZY])))
4814 if (spawn(cmd, "-l", newpath, NULL, F_NORMAL)) {
4815 #elif defined(__FreeBSD__)
4816 if (spawn(cmd, "-f", newpath, NULL, F_NORMAL)) {
4818 if (spawn(cmd, "-quz", newpath, NULL, F_NORMAL)) {
4820 printwait(messages[MSG_FAILED], presel);
4825 if (rmdir(newpath) == -1) {
4833 static void lock_terminal(void)
4835 spawn(xgetenv("NNN_LOCKER", utils[UTIL_LOCKER]), NULL, NULL, NULL, F_CLI);
4838 static void printkv(kv *kvarr, int fd, uchar_t max, uchar_t id)
4840 char *val = (id == NNN_BMS) ? bmstr : pluginstr;
4842 for (uchar_t i = 0; i < max && kvarr[i].key; ++i)
4843 dprintf(fd, " %c: %s\n", (char)kvarr[i].key, val + kvarr[i].off);
4846 static void printkeys(kv *kvarr, char *buf, uchar_t max)
4850 for (; i < max && kvarr[i].key; ++i) {
4852 buf[(i << 1) + 1] = kvarr[i].key;
4858 static size_t handle_bookmark(const char *bmark, char *newpath)
4861 size_t r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
4863 if (bmark) { /* There is a marked directory */
4869 printkeys(bookmark, g_buf + r - 1, maxbm);
4873 fd = get_input(NULL);
4874 if (fd == ',') /* Visit marked directory */
4875 bmark ? xstrsncpy(newpath, bmark, PATH_MAX) : (r = MSG_NOT_SET);
4876 else if (!get_kv_val(bookmark, newpath, fd, maxbm, NNN_BMS))
4877 r = MSG_INVALID_KEY;
4879 if (!r && chdir(newpath) == -1)
4886 * The help string tokens (each line) start with a HEX value
4887 * which indicates the number of spaces to print before the
4888 * particular token. This method was chosen instead of a flat
4889 * string because the number of bytes in help was increasing
4890 * the binary size by around a hundred bytes. This would only
4891 * have increased as we keep adding new options.
4893 static void show_help(const char *path)
4895 const char *start, *end;
4896 const char helpstr[] = {
4899 "9Up k Up%-16cPgUp ^U Page up\n"
4900 "9Dn j Down%-14cPgDn ^D Page down\n"
4901 "9Lt h Parent%-12c~ ` @ - ~, /, start, prev\n"
4902 "5Ret Rt l Open%-20c' First file/match\n"
4903 "9g ^A Top%-21c. Toggle hidden\n"
4904 "9G ^E End%-21c+ Toggle auto-advance\n"
4905 "c, Mark CWD%-13cb ^/ Select bookmark\n"
4906 "a1-4 Context%-11c(Sh)Tab Cycle/new context\n"
4907 "62Esc ^Q Quit%-20cq Quit context\n"
4908 "b^G QuitCD%-18cQ Pick/err, quit\n"
4910 "1FILTER & PROMPT\n"
4911 "c/ Filter%-17c^N Toggle type-to-nav\n"
4912 "aEsc Exit prompt%-12c^L Toggle last filter\n"
4913 "d%-20cAlt+Esc Unfilter, quit context\n"
4916 "9o ^O Open with%-15cn Create new/link\n"
4917 "9f ^F File stats%-14cd Detail mode toggle\n"
4918 "b^R Rename/dup%-14cr Batch rename\n"
4919 "cz Archive%-17ce Edit file\n"
4920 "c* Toggle exe%-14c> Export list\n"
4921 "5Space ^J (Un)select%-12cm-m Select range/clear\n"
4922 "ca Select all%-14cA Invert sel\n"
4923 "9p ^P Copy here%-12cw ^W Cp/mv sel as\n"
4924 "9v ^V Move here%-15cE Edit sel list\n"
4925 "9x ^X Delete%-16cEsc Send to FIFO\n"
4928 "8Alt ; Select plugin%-11c= Launch app\n"
4929 "9! ^] Shell%-19c] Cmd prompt\n"
4930 "cc Connect remote%-10cu Unmount remote/archive\n"
4931 "9t ^T Sort toggles%-12cs Manage session\n"
4932 "cT Set time type%-11c0 Lock\n"
4933 "b^L Redraw%-18c? Help, conf\n"
4936 int fd = create_tmp_file();
4940 char *prog = xgetenv(env_cfg[NNN_HELP], NULL);
4942 get_output(prog, NULL, NULL, fd, TRUE, FALSE);
4944 start = end = helpstr;
4947 snprintf(g_buf, CMD_LEN_MAX, "%*c%.*s",
4948 xchartohex(*start), ' ', (int)(end - start), start + 1);
4949 dprintf(fd, g_buf, ' ');
4956 dprintf(fd, "\nVOLUME: %s of ", coolsize(get_fs_info(path, FREE)));
4957 dprintf(fd, "%s free\n\n", coolsize(get_fs_info(path, CAPACITY)));
4960 dprintf(fd, "BOOKMARKS\n");
4961 printkv(bookmark, fd, maxbm, NNN_BMS);
4966 dprintf(fd, "PLUGIN KEYS\n");
4967 printkv(plug, fd, maxplug, NNN_PLUG);
4971 for (uchar_t i = NNN_OPENER; i <= NNN_TRASH; ++i) {
4972 start = getenv(env_cfg[i]);
4974 dprintf(fd, "%s: %s\n", env_cfg[i], start);
4978 dprintf(fd, "SELECTION FILE: %s\n", selpath);
4980 dprintf(fd, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
4983 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4987 static bool run_cmd_as_plugin(const char *file, char *runfile, uchar_t flags)
4991 xstrsncpy(g_buf, file, PATH_MAX);
4993 len = xstrlen(g_buf);
4994 if (len > 1 && g_buf[len - 1] == '*') {
4995 flags &= ~F_CONFIRM; /* Skip user confirmation */
4996 g_buf[len - 1] = '\0'; /* Get rid of trailing no confirmation symbol */
5000 if (is_suffix(g_buf, " $nnn"))
5001 g_buf[len - 5] = '\0'; /* Set `\0` to clear ' $nnn' suffix */
5006 get_output(g_buf, runfile, NULL, -1, TRUE, TRUE);
5008 spawn(g_buf, runfile, NULL, NULL, flags);
5013 static bool plctrl_init(void)
5017 /* g_tmpfpath is used to generate tmp file names */
5018 g_tmpfpath[tmpfplen - 1] = '\0';
5019 len = xstrsncpy(g_pipepath, g_tmpfpath, TMP_LEN_MAX);
5020 g_pipepath[len - 1] = '/';
5021 len = xstrsncpy(g_pipepath + len, "nnn-pipe.", TMP_LEN_MAX - len) + len;
5022 xstrsncpy(g_pipepath + len - 1, xitoa(getpid()), TMP_LEN_MAX - len);
5023 setenv(env_cfg[NNN_PIPE], g_pipepath, TRUE);
5025 return EXIT_SUCCESS;
5028 static void rmlistpath(void)
5031 DPRINTF_S(__func__);
5032 DPRINTF_S(listpath);
5033 spawn(utils[UTIL_RM_RF], listpath, NULL, NULL, F_NOTRACE | F_MULTI);
5034 /* Do not free if program was started in list mode */
5035 if (listpath != initpath)
5041 static ssize_t read_nointr(int fd, void *buf, size_t count)
5046 len = read(fd, buf, count);
5047 while (len == -1 && errno == EINTR);
5052 static void readpipe(int fd, char **path, char **lastname, char **lastdir)
5054 char ctx, *nextpath = NULL;
5056 if (read_nointr(fd, g_buf, 1) != 1)
5059 if (g_buf[0] == '-') { /* Clear selection on '-' */
5061 if (read_nointr(fd, g_buf, 1) != 1)
5065 if (g_buf[0] == '+')
5066 ctx = (char)(get_free_ctx() + 1);
5067 else if (g_buf[0] < '0')
5070 ctx = g_buf[0] - '0';
5075 if (read_nointr(fd, g_buf, 1) != 1)
5081 ssize_t len = read_nointr(fd, g_buf, PATH_MAX);
5086 g_buf[len] = '\0'; /* Terminate the path read */
5087 if (g_buf[0] == '/') {
5089 len = xstrlen(g_buf);
5090 while (--len && (g_buf[len] == '/')) /* Trim all trailing '/' */
5093 } else if (op == 'l') {
5094 rmlistpath(); /* Remove last list mode path, if any */
5095 nextpath = load_input(fd, *path);
5096 } else if (op == 'p') {
5105 set_smart_ctx(ctx, nextpath, path, lastname, lastdir);
5108 static bool run_plugin(char **path, const char *file, char *runfile, char **lastname, char **lastdir)
5111 bool cmd_as_plugin = FALSE;
5114 if (!g_state.pluginit) {
5116 g_state.pluginit = 1;
5119 /* Check for run-cmd-as-plugin mode */
5121 flags = F_MULTI | F_CONFIRM;
5124 if (*file == '|') { /* Check if output should be paged */
5127 } else if (*file == '&') { /* Check if GUI flags are to be used */
5128 flags = F_NOTRACE | F_NOWAIT;
5135 if ((flags & F_NOTRACE) || (flags & F_PAGE))
5136 return run_cmd_as_plugin(file, runfile, flags);
5138 cmd_as_plugin = TRUE;
5141 if (mkfifo(g_pipepath, 0600) != 0)
5148 if (!p) { // In child
5149 int wfd = open(g_pipepath, O_WRONLY | O_CLOEXEC);
5152 _exit(EXIT_FAILURE);
5154 if (!cmd_as_plugin) {
5158 /* Generate absolute path to plugin */
5159 mkpath(plgpath, file, g_buf);
5162 sel = selpath ? selpath : std;
5164 if (runfile && runfile[0]) {
5165 xstrsncpy(*lastname, runfile, NAME_MAX);
5166 spawn(g_buf, *lastname, *path, sel, 0);
5168 spawn(g_buf, NULL, *path, sel, 0);
5170 run_cmd_as_plugin(file, runfile, flags);
5173 _exit(EXIT_SUCCESS);
5179 rfd = open(g_pipepath, O_RDONLY);
5180 while (rfd == -1 && errno == EINTR);
5182 readpipe(rfd, path, lastname, lastdir);
5185 /* wait for the child to finish. no zombies allowed */
5186 waitpid(p, NULL, 0);
5195 static bool launch_app(char *newpath)
5198 char *tmp = newpath;
5200 mkpath(plgpath, utils[UTIL_LAUNCH], newpath);
5202 if (!getutil(utils[UTIL_FZF]) || access(newpath, X_OK) < 0) {
5203 tmp = xreadline(NULL, messages[MSG_APP_NAME]);
5204 r = F_NOWAIT | F_NOTRACE | F_MULTI;
5207 if (tmp && *tmp) // NOLINT
5208 spawn(tmp, (r == F_NORMAL) ? "0" : NULL, NULL, NULL, r);
5213 /* Returns TRUE if at least command was run */
5214 static bool prompt_run(const char *current)
5219 setenv(envs[ENV_NCUR], current, 1);
5223 if (g_state.picker) {
5225 tmp = xreadline(NULL, PROMPT);
5228 tmp = getreadline("\n"PROMPT);
5230 if (tmp && *tmp) { // NOLINT
5232 lastcmd = xstrdup(tmp);
5234 spawn(shell, "-c", tmp, NULL, F_CLI | F_CONFIRM);
5242 static bool handle_cmd(enum action sel, const char *current, char *newpath)
5246 if (sel == SEL_PROMPT)
5247 return prompt_run(current);
5249 if (sel == SEL_LAUNCH)
5250 return launch_app(newpath);
5252 /* Set nnn nesting level */
5253 char *tmp = getenv(env_cfg[NNNLVL]);
5254 int r = tmp ? atoi(tmp) : 0;
5256 setenv(env_cfg[NNNLVL], xitoa(r + 1), 1);
5257 setenv(envs[ENV_NCUR], current, 1);
5258 spawn(shell, NULL, NULL, NULL, F_CLI);
5259 setenv(env_cfg[NNNLVL], xitoa(r), 1);
5263 static void dentfree(void)
5269 /* Thread data cleanup */
5275 static void *du_thread(void *p_data)
5277 thread_data *pdata = (thread_data *)p_data;
5278 char *path[2] = {pdata->path, NULL};
5279 ullong_t tfiles = 0;
5280 blkcnt_t tblocks = 0;
5282 FTS *tree = fts_open(path, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR, 0);
5285 while ((node = fts_read(tree))) {
5286 if (node->fts_info & FTS_D)
5289 sb = node->fts_statp;
5291 if (cfg.apparentsz) {
5292 if (sb->st_size && DU_TEST)
5293 tblocks += sb->st_size;
5294 } else if (sb->st_blocks && DU_TEST)
5295 tblocks += sb->st_blocks;
5302 if (pdata->entnum >= 0)
5303 pdents[pdata->entnum].blocks = tblocks;
5305 if (!pdata->mntpoint) {
5306 core_blocks[pdata->core] += tblocks;
5307 core_files[pdata->core] += tfiles;
5309 core_files[pdata->core] += 1;
5311 pthread_mutex_lock(&running_mutex);
5312 threadbmp |= (1 << pdata->core);
5314 pthread_mutex_unlock(&running_mutex);
5319 static void dirwalk(char *dir, char *path, int entnum, bool mountpoint)
5321 /* Loop till any core is free */
5322 while (active_threads == NUM_DU_THREADS);
5324 if (g_state.interrupt)
5327 pthread_mutex_lock(&running_mutex);
5328 int core = ffs(threadbmp) - 1;
5330 threadbmp &= ~(1 << core);
5332 pthread_mutex_unlock(&running_mutex);
5334 xstrsncpy(core_data[core].path, path, PATH_MAX);
5335 core_data[core].entnum = entnum;
5336 core_data[core].core = (ushort_t)core;
5337 core_data[core].mntpoint = mountpoint;
5341 pthread_create(&tid, NULL, du_thread, (void *)&(core_data[core]));
5344 printmsg("^C aborts");
5348 static void prep_threads(void)
5350 if (!g_state.duinit) {
5352 threadbmp >>= (32 - NUM_DU_THREADS);
5354 core_blocks = calloc(NUM_DU_THREADS, sizeof(blkcnt_t));
5355 core_data = calloc(NUM_DU_THREADS, sizeof(thread_data));
5356 core_files = calloc(NUM_DU_THREADS, sizeof(ullong_t));
5359 /* Increase current open file descriptor limit */
5362 g_state.duinit = TRUE;
5364 memset(core_blocks, 0, NUM_DU_THREADS * sizeof(blkcnt_t));
5365 memset(core_data, 0, NUM_DU_THREADS * sizeof(thread_data));
5366 memset(core_files, 0, NUM_DU_THREADS * sizeof(ullong_t));
5370 /* Skip self and parent */
5371 static bool selforparent(const char *path)
5373 return path[0] == '.' && (path[1] == '\0' || (path[1] == '.' && path[2] == '\0'));
5376 static int dentfill(char *path, struct entry **ppdents)
5378 uchar_t entflags = 0;
5381 char *namep, *pnb, *buf;
5382 struct entry *dentp;
5383 size_t off = 0, namebuflen = NAMEBUF_INCR;
5384 struct stat sb_path, sb;
5385 DIR *dirp = opendir(path);
5389 DPRINTF_S(__func__);
5394 int fd = dirfd(dirp);
5401 if (fstatat(fd, path, &sb_path, 0) == -1)
5405 ihashbmp = calloc(1, HASH_OCTETS << 3);
5409 memset(ihashbmp, 0, HASH_OCTETS << 3);
5413 attron(COLOR_PAIR(cfg.curctx + 1));
5416 #if _POSIX_C_SOURCE >= 200112L
5417 posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
5424 #if defined(__sun) || defined(__HAIKU__)
5425 flags = AT_SYMLINK_NOFOLLOW; /* no d_type */
5427 if (cfg.blkorder || dp->d_type == DT_UNKNOWN) {
5429 * Optimization added for filesystems which support dirent.d_type
5432 * - the symlink size is set to 0
5433 * - the modification time of the symlink is set to that of the target file
5435 flags = AT_SYMLINK_NOFOLLOW;
5442 if (selforparent(namep))
5445 if (!cfg.showhidden && namep[0] == '.') {
5449 if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
5452 if (S_ISDIR(sb.st_mode)) {
5453 if (sb_path.st_dev == sb.st_dev) { // NOLINT
5454 mkpath(path, namep, buf); // NOLINT
5455 dirwalk(path, buf, -1, FALSE);
5457 if (g_state.interrupt)
5462 /* Do not recount hard links */
5463 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5464 dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5471 if (fstatat(fd, namep, &sb, flags) == -1) {
5472 if (flags || (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)) {
5477 DPRINTF_S(strerror(errno));
5480 entflags = FILE_MISSING;
5481 memset(&sb, 0, sizeof(struct stat));
5482 } else /* Orphaned symlink */
5483 entflags = SYM_ORPHAN;
5486 if (ndents == total_dents) {
5488 while (active_threads);
5490 total_dents += ENTRY_INCR;
5491 *ppdents = xrealloc(*ppdents, total_dents * sizeof(**ppdents));
5497 DPRINTF_P(*ppdents);
5500 /* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
5501 if (namebuflen - off < NAME_MAX + 1) {
5502 namebuflen += NAMEBUF_INCR;
5505 pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
5511 DPRINTF_P(pnamebuf);
5513 /* realloc() may result in memory move, we must re-adjust if that happens */
5514 if (pnb != pnamebuf) {
5516 dentp->name = pnamebuf;
5518 for (int count = 1; count < ndents; ++dentp, ++count)
5519 /* Current file name starts at last file name start + length */
5520 (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
5524 dentp = *ppdents + ndents;
5526 /* Selection file name */
5527 dentp->name = (char *)((size_t)pnamebuf + off);
5528 dentp->nlen = xstrsncpy(dentp->name, namep, NAME_MAX + 1);
5531 /* Copy other fields */
5532 if (cfg.timetype == T_MOD) {
5533 dentp->sec = sb.st_mtime;
5535 dentp->nsec = (uint_t)sb.st_mtimespec.tv_nsec;
5537 dentp->nsec = (uint_t)sb.st_mtim.tv_nsec;
5539 } else if (cfg.timetype == T_ACCESS) {
5540 dentp->sec = sb.st_atime;
5542 dentp->nsec = (uint_t)sb.st_atimespec.tv_nsec;
5544 dentp->nsec = (uint_t)sb.st_atim.tv_nsec;
5547 dentp->sec = sb.st_ctime;
5549 dentp->nsec = (uint_t)sb.st_ctimespec.tv_nsec;
5551 dentp->nsec = (uint_t)sb.st_ctim.tv_nsec;
5555 #if !(defined(__sun) || defined(__HAIKU__))
5556 if (!flags && dp->d_type == DT_LNK) {
5557 /* Do not add sizes for links */
5558 dentp->mode = (sb.st_mode & ~S_IFMT) | S_IFLNK;
5559 dentp->size = listpath ? sb.st_size : 0;
5561 dentp->mode = sb.st_mode;
5562 dentp->size = sb.st_size;
5565 dentp->mode = sb.st_mode;
5566 dentp->size = sb.st_size;
5570 dentp->uid = sb.st_uid;
5571 dentp->gid = sb.st_gid;
5574 dentp->flags = S_ISDIR(sb.st_mode) ? 0 : ((sb.st_nlink > 1) ? HARD_LINK : 0);
5576 dentp->flags |= entflags;
5581 if (S_ISDIR(sb.st_mode)) {
5582 mkpath(path, namep, buf); // NOLINT
5584 /* Need to show the disk usage of this dir */
5585 dirwalk(path, buf, ndents, (sb_path.st_dev != sb.st_dev)); // NOLINT
5587 if (g_state.interrupt)
5590 dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5591 /* Do not recount hard links */
5592 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5593 dir_blocks += dentp->blocks;
5599 /* Flag if this is a dir or symlink to a dir */
5600 if (S_ISLNK(sb.st_mode)) {
5602 fstatat(fd, namep, &sb, 0);
5605 if (S_ISDIR(sb.st_mode))
5606 dentp->flags |= DIR_OR_DIRLNK;
5607 #if !(defined(__sun) || defined(__HAIKU__)) /* no d_type */
5608 } else if (dp->d_type == DT_DIR || ((dp->d_type == DT_LNK
5609 || dp->d_type == DT_UNKNOWN) && S_ISDIR(sb.st_mode))) {
5610 dentp->flags |= DIR_OR_DIRLNK;
5615 } while ((dp = readdir(dirp)));
5619 while (active_threads);
5621 attroff(COLOR_PAIR(cfg.curctx + 1));
5622 for (int i = 0; i < NUM_DU_THREADS; ++i) {
5623 num_files += core_files[i];
5624 dir_blocks += core_blocks[i];
5628 /* Should never be null */
5629 if (closedir(dirp) == -1)
5635 static void populate(char *path, char *lastname)
5638 struct timespec ts1, ts2;
5640 clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
5643 ndents = dentfill(path, &pdents);
5647 ENTSORT(pdents, ndents, entrycmpfn);
5650 clock_gettime(CLOCK_REALTIME, &ts2);
5651 DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
5654 /* Find cur from history */
5655 /* No NULL check for lastname, always points to an array */
5656 move_cursor(*lastname ? dentfind(lastname, ndents) : 0, 0);
5658 // Force full redraw
5659 last_curscroll = -1;
5663 static void notify_fifo(bool force)
5669 fifofd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC);
5672 /* Unexpected error, the FIFO file might have been removed */
5673 /* We give up FIFO notification */
5679 static struct entry lastentry;
5681 if (!force && !memcmp(&lastentry, &pdents[cur], sizeof(struct entry)))
5684 lastentry = pdents[cur];
5686 char path[PATH_MAX];
5687 size_t len = mkpath(g_ctx[cfg.curctx].c_path, ndents ? pdents[cur].name : "", path);
5689 path[len - 1] = '\n';
5691 ssize_t ret = write(fifofd, path, len);
5693 if (ret != (ssize_t)len && !(ret == -1 && (errno == EAGAIN || errno == EPIPE))) {
5694 DPRINTF_S(strerror(errno));
5699 static void move_cursor(int target, int ignore_scrolloff)
5701 int onscreen = xlines - 4; /* Leave top 2 and bottom 2 lines */
5703 target = MAX(0, MIN(ndents - 1, target));
5704 last_curscroll = curscroll;
5708 if (!ignore_scrolloff) {
5709 int delta = target - last;
5710 int scrolloff = MIN(SCROLLOFF, onscreen >> 1);
5713 * When ignore_scrolloff is 1, the cursor can jump into the scrolloff
5714 * margin area, but when ignore_scrolloff is 0, act like a boa
5715 * constrictor and squeeze the cursor towards the middle region of the
5716 * screen by allowing it to move inward and disallowing it to move
5717 * outward (deeper into the scrolloff margin area).
5719 if (((cur < (curscroll + scrolloff)) && delta < 0)
5720 || ((cur > (curscroll + onscreen - scrolloff - 1)) && delta > 0))
5723 curscroll = MIN(curscroll, MIN(cur, ndents - onscreen));
5724 curscroll = MAX(curscroll, MAX(cur - (onscreen - 1), 0));
5727 if (!g_state.fifomode)
5728 notify_fifo(FALSE); /* Send hovered path to NNN_FIFO */
5732 static void handle_screen_move(enum action sel)
5738 if (ndents && (cfg.rollover || (cur != ndents - 1)))
5739 move_cursor((cur + 1) % ndents, 0);
5742 if (ndents && (cfg.rollover || cur))
5743 move_cursor((cur + ndents - 1) % ndents, 0);
5746 onscreen = xlines - 4;
5747 move_cursor(curscroll + (onscreen - 1), 1);
5748 curscroll += onscreen - 1;
5751 onscreen = xlines - 4;
5752 move_cursor(curscroll + (onscreen - 1), 1);
5753 curscroll += onscreen >> 1;
5755 case SEL_PGUP: // fallthrough
5756 onscreen = xlines - 4;
5757 move_cursor(curscroll, 1);
5758 curscroll -= onscreen - 1;
5761 onscreen = xlines - 4;
5762 move_cursor(curscroll, 1);
5763 curscroll -= onscreen >> 1;
5769 move_cursor(ndents - 1, 1);
5771 default: /* case SEL_FIRST */
5773 int c = get_input(messages[MSG_FIRST]);
5780 int r = (c == TOUPPER(*pdents[cur].name)) ? (cur + 1) : 0;
5782 for (; r < ndents; ++r) {
5783 if (((c == '\'') && !(pdents[r].flags & DIR_OR_DIRLNK))
5784 || (c == TOUPPER(*pdents[r].name))) {
5785 move_cursor((r) % ndents, 0);
5794 static void handle_openwith(const char *path, const char *name, char *newpath, char *tmp)
5796 /* Confirm if app is CLI or GUI */
5797 int r = get_input(messages[MSG_CLI_MODE]);
5799 r = (r == 'c' ? F_CLI :
5800 (r == 'g' ? F_NOWAIT | F_NOTRACE | F_MULTI : 0));
5802 mkpath(path, name, newpath);
5803 spawn(tmp, newpath, NULL, NULL, r);
5807 static void copynextname(char *lastname)
5810 cur += (cur != (ndents - 1)) ? 1 : -1;
5816 static int handle_context_switch(enum action sel)
5821 case SEL_CYCLE: // fallthrough
5823 /* visit next and previous contexts */
5825 if (sel == SEL_CYCLE)
5827 r = (r + 1) & ~CTX_MAX;
5828 while (!g_ctx[r].c_cfg.ctxactive);
5830 do /* Attempt to create a new context */
5831 r = (r + 1) & ~CTX_MAX;
5832 while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
5834 if (r == cfg.curctx) /* If all contexts are active, reverse cycle */
5836 r = (r + (CTX_MAX - 1)) & (CTX_MAX - 1);
5837 while (!g_ctx[r].c_cfg.ctxactive);
5839 default: /* SEL_CTXN */
5840 if (sel >= SEL_CTX1) /* CYCLE keys are lesser in value */
5841 r = sel - SEL_CTX1; /* Save the next context id */
5843 if (cfg.curctx == r) {
5844 if (sel == SEL_CYCLE)
5845 (r == CTX_MAX - 1) ? (r = 0) : ++r;
5846 else if (sel == SEL_CYCLER)
5847 (r == 0) ? (r = CTX_MAX - 1) : --r;
5856 static int set_sort_flags(int r)
5860 /* Set the correct input in case of a session load */
5862 if (cfg.apparentsz) {
5865 } else if (cfg.blkorder) {
5871 namecmpfn = &xstrverscasecmp;
5874 entrycmpfn = &reventrycmp;
5875 } else if (r == CONTROL('T')) {
5876 /* Cycling order: clear -> size -> time -> clear */
5879 else if (cfg.sizeorder)
5886 case 'a': /* Apparent du */
5887 cfg.apparentsz ^= 1;
5888 if (cfg.apparentsz) {
5894 case 'd': /* Disk usage */
5896 if (!cfg.apparentsz)
5899 blk_shift = ffs(S_BLKSIZE) - 1;
5909 entrycmpfn = &entrycmp;
5911 endselection(); /* We are going to reload dir */
5921 entrycmpfn = &entrycmp;
5922 namecmpfn = &xstricmp;
5924 case 'e': /* File extension */
5931 entrycmpfn = &entrycmp;
5933 case 'r': /* Reverse sort */
5935 entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
5937 case 's': /* File size */
5944 entrycmpfn = &entrycmp;
5946 case 't': /* Time */
5953 entrycmpfn = &entrycmp;
5955 case 'v': /* Version */
5957 namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
5971 static bool set_time_type(int *presel)
5974 char buf[] = "'a'ccess / 'c'hange / 'm'od [ ]";
5976 buf[sizeof(buf) - 3] = cfg.timetype == T_MOD ? 'm' : (cfg.timetype == T_ACCESS ? 'a' : 'c');
5978 int r = get_input(buf);
5980 if (r == 'a' || r == 'c' || r == 'm') {
5981 r = (r == 'm') ? T_MOD : ((r == 'a') ? T_ACCESS : T_CHANGE);
5982 if (cfg.timetype != r) {
5985 if (cfg.filtermode || g_ctx[cfg.curctx].c_fltr[1])
5992 r = MSG_INVALID_KEY;
5995 printwait(messages[r], presel);
6000 static void statusbar(char *path)
6002 int i = 0, extnlen = 0;
6004 pEntry pent = &pdents[cur];
6011 /* Get the file extension for regular files */
6012 if (S_ISREG(pent->mode)) {
6013 i = (int)(pent->nlen - 1);
6014 ptr = xextension(pent->name, i);
6016 extnlen = i - (ptr - pent->name);
6017 if (!ptr || extnlen > 5 || extnlen < 2)
6023 attron(COLOR_PAIR(cfg.curctx + 1));
6025 printw("%d/%s ", cur + 1, xitoa(ndents));
6027 if (g_state.selmode || nselected) {
6030 if (g_state.rangesel)
6032 else if (g_state.selmode)
6035 addstr(xitoa(nselected));
6041 if (cfg.blkorder) { /* du mode */
6044 xstrsncpy(buf, coolsize(dir_blocks << blk_shift), 12);
6046 printw("%cu:%s free:%s files:%llu %lluB %s\n",
6047 (cfg.apparentsz ? 'a' : 'd'), buf, coolsize(get_fs_info(path, FREE)),
6048 num_files, (ullong_t)pent->blocks << blk_shift, ptr);
6049 } else { /* light or detail mode */
6050 char sort[] = "\0\0\0\0\0";
6052 if (getorderstr(sort))
6056 print_time(&pent->sec);
6059 addstr(get_lsperms(pent->mode));
6062 if (g_state.uidgid) {
6063 addstr(getpwname(pent->uid));
6065 addstr(getgrname(pent->gid));
6069 if (S_ISLNK(pent->mode)) {
6070 i = readlink(pent->name, g_buf, PATH_MAX);
6072 addstr(coolsize(i >= 0 ? i : pent->size)); /* Show symlink size */
6074 if (i > 1) { /* Show symlink target */
6076 #ifdef ICONS_ENABLED
6077 addstr(" "MD_ARROW_FORWARD);
6084 addstr(coolsize(pent->size));
6087 if (pent->flags & HARD_LINK) {
6090 if (stat(pent->name, &sb) != -1) {
6092 addstr(xitoa((int)sb.st_nlink)); /* Show number of links */
6094 addstr(xitoa((int)sb.st_ino)); /* Show inode number */
6101 attroff(COLOR_PAIR(cfg.curctx + 1));
6107 static inline void markhovered(void)
6109 if (cfg.showdetail && ndents) { /* Reversed block for hovered entry */
6111 #ifdef ICONS_ENABLED
6112 addstr(MD_ARROW_FORWARD);
6114 addch(' ' | A_REVERSE);
6119 static int adjust_cols(int n)
6121 /* Calculate the number of cols available to print entry name */
6122 #ifdef ICONS_ENABLED
6123 n -= (g_state.oldcolor ? 0 : 1 + xstrlen(ICON_PADDING_LEFT) + xstrlen(ICON_PADDING_RIGHT));
6125 if (cfg.showdetail) {
6126 /* Fallback to light mode if less than 35 columns */
6128 cfg.showdetail ^= 1;
6129 else /* 2 more accounted for below */
6133 /* 2 columns for preceding space and indicator */
6137 static void draw_line(char *path, int ncols)
6141 ncols = adjust_cols(ncols);
6143 if (g_state.oldcolor && (pdents[last].flags & DIR_OR_DIRLNK)) {
6144 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6148 move(2 + last - curscroll, 0);
6149 printent(&pdents[last], ncols, FALSE);
6151 if (g_state.oldcolor && (pdents[cur].flags & DIR_OR_DIRLNK)) {
6152 if (!dir) {/* First file is not a directory */
6153 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6156 } else if (dir) { /* Second file is not a directory */
6157 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6161 move(2 + cur - curscroll, 0);
6162 printent(&pdents[cur], ncols, TRUE);
6164 /* Must reset e.g. no files in dir */
6166 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6173 static void redraw(char *path)
6175 getmaxyx(stdscr, xlines, xcols);
6177 int ncols = (xcols <= PATH_MAX) ? xcols : PATH_MAX;
6178 int onscreen = xlines - 4;
6185 if (ndents && (last_curscroll == curscroll))
6186 return draw_line(path, ncols);
6189 DPRINTF_S(__func__);
6194 /* Enforce scroll/cursor invariants */
6195 move_cursor(cur, 1);
6197 /* Fail redraw if < than 10 columns, context info prints 10 chars */
6198 if (ncols <= MIN_DISPLAY_COL) {
6199 printmsg(messages[MSG_FEW_COLUMNS]);
6206 for (i = 0; i < CTX_MAX; ++i) { /* 8 chars printed for contexts - "1 2 3 4 " */
6207 if (!g_ctx[i].c_cfg.ctxactive)
6210 addch((i + '1') | (COLOR_PAIR(i + 1) | A_BOLD
6211 /* active: underline, current: reverse */
6212 | ((cfg.curctx != i) ? A_UNDERLINE : A_REVERSE)));
6217 attron(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6220 bool in_home = set_tilde_in_path(path);
6221 char *ptr = in_home ? &path[homelen - 1] : path;
6223 i = (int)xstrlen(ptr);
6224 if ((i + MIN_DISPLAY_COL) <= ncols)
6225 addnstr(ptr, ncols - MIN_DISPLAY_COL);
6227 char *base = xmemrchr((uchar_t *)ptr, '/', i);
6236 if (ptr && (base != ptr)) {
6237 while (ptr < base) {
6239 i += 2; /* 2 characters added */
6240 if (ncols < i + MIN_DISPLAY_COL) {
6241 base = NULL; /* Can't print more characters */
6253 addnstr(base, ncols - (MIN_DISPLAY_COL + i));
6257 reset_tilde_in_path(path);
6259 attroff(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6261 /* Go to first entry */
6262 if (curscroll > 0) {
6264 #ifdef ICONS_ENABLED
6265 addstr(MD_ARROW_UPWARD);
6271 if (g_state.oldcolor) {
6272 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6273 g_state.dircolor = 1;
6276 onscreen = MIN(onscreen + curscroll, ndents);
6278 ncols = adjust_cols(ncols);
6280 int len = scanselforpath(path, FALSE);
6283 for (i = curscroll; i < onscreen; ++i) {
6287 findmarkentry(len, &pdents[i]);
6289 printent(&pdents[i], ncols, i == cur);
6292 /* Must reset e.g. no files in dir */
6293 if (g_state.dircolor) {
6294 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6295 g_state.dircolor = 0;
6298 /* Go to last entry */
6299 if (onscreen < ndents) {
6300 move(xlines - 2, 0);
6301 #ifdef ICONS_ENABLED
6302 addstr(MD_ARROW_DOWNWARD);
6313 static bool cdprep(char *lastdir, char *lastname, char *path, char *newpath)
6318 /* Save last working directory */
6319 xstrsncpy(lastdir, path, PATH_MAX);
6321 /* Save the newly opted dir in path */
6322 xstrsncpy(path, newpath, PATH_MAX);
6326 return cfg.filtermode;
6329 static bool browse(char *ipath, const char *session, int pkey)
6331 char newpath[PATH_MAX] __attribute__ ((aligned)),
6332 rundir[PATH_MAX] __attribute__ ((aligned)),
6333 runfile[NAME_MAX + 1] __attribute__ ((aligned));
6334 char *path, *lastdir, *lastname, *dir, *tmp;
6338 int r = -1, presel, selstartid = 0, selendid = 0;
6339 const uchar_t opener_flags = (cfg.cliopener ? F_CLI : (F_NOTRACE | F_NOSTDIN | F_NOWAIT));
6345 struct timespec mousetimings[2] = {{.tv_sec = 0, .tv_nsec = 0}, {.tv_sec = 0, .tv_nsec = 0} };
6346 int mousedent[2] = {-1, -1};
6347 bool currentmouse = 1, rightclicksel = 0;
6356 /* set-up first context */
6357 if (!session || !load_session(session, &path, &lastdir, &lastname, FALSE)) {
6361 g_ctx[0].c_last[0] = '\0';
6362 lastdir = g_ctx[0].c_last; /* last visited directory */
6364 if (g_state.initfile) {
6365 xstrsncpy(g_ctx[0].c_name, xbasename(ipath), sizeof(g_ctx[0].c_name));
6368 g_ctx[0].c_name[0] = '\0';
6370 lastname = g_ctx[0].c_name; /* last visited file name */
6372 xstrsncpy(g_ctx[0].c_path, ipath, PATH_MAX);
6373 /* If the initial path is a file, retain a way to return to start dir */
6374 if (g_state.initfile) {
6376 initpath = ipath = getcwd(NULL, 0);
6378 path = g_ctx[0].c_path; /* current directory */
6380 g_ctx[0].c_fltr[0] = g_ctx[0].c_fltr[1] = '\0';
6381 g_ctx[0].c_cfg = cfg; /* current configuration */
6386 newpath[0] = rundir[0] = runfile[0] = '\0';
6388 presel = pkey ? ';' : (cfg.filtermode ? FILTER : 0);
6390 pdents = xrealloc(pdents, total_dents * sizeof(struct entry));
6394 /* Allocate buffer to hold names */
6395 pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
6400 /* Can fail when permissions change while browsing.
6401 * It's assumed that path IS a directory when we are here.
6403 if (chdir(path) == -1) {
6404 DPRINTF_S("directory inaccessible");
6405 valid_parent(path, lastname);
6410 if (cfg.x11 && !g_state.picker) {
6411 /* Set terminal window title */
6412 r = set_tilde_in_path(path);
6414 printf("\033]2;%s\007", r ? &path[homelen - 1] : path);
6418 reset_tilde_in_path(path);
6422 #ifdef LINUX_INOTIFY
6423 if ((presel == FILTER || watch) && inotify_wd >= 0) {
6424 inotify_rm_watch(inotify_fd, inotify_wd);
6428 #elif defined(BSD_KQUEUE)
6429 if ((presel == FILTER || watch) && event_fd >= 0) {
6434 #elif defined(HAIKU_NM)
6435 if ((presel == FILTER || watch) && haiku_hnd != NULL) {
6436 haiku_stop_watch(haiku_hnd);
6437 haiku_nm_active = FALSE;
6442 populate(path, lastname);
6443 if (g_state.interrupt) {
6444 g_state.interrupt = cfg.apparentsz = cfg.blkorder = 0;
6445 blk_shift = BLK_SHIFT_512;
6446 presel = CONTROL('L');
6449 #ifdef LINUX_INOTIFY
6450 if (presel != FILTER && inotify_wd == -1)
6451 inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
6452 #elif defined(BSD_KQUEUE)
6453 if (presel != FILTER && event_fd == -1) {
6454 #if defined(O_EVTONLY)
6455 event_fd = open(path, O_EVTONLY);
6457 event_fd = open(path, O_RDONLY);
6460 EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
6461 EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
6463 #elif defined(HAIKU_NM)
6464 haiku_nm_active = haiku_watch_dir(haiku_hnd, path) == EXIT_SUCCESS;
6468 /* Do not do a double redraw in filterentries */
6469 if ((presel != FILTER) || !filterset())
6473 /* Exit if parent has exited */
6475 _exit(EXIT_FAILURE);
6477 /* If CWD is deleted or moved or perms changed, find an accessible parent */
6478 if (chdir(path) == -1)
6481 /* If STDIN is no longer a tty (closed) we should exit */
6482 if (!isatty(STDIN_FILENO) && !g_state.picker)
6483 return EXIT_FAILURE;
6485 sel = nextsel(presel);
6492 if (getmouse(&event) != OK)
6495 /* Handle clicking on a context at the top */
6496 if (event.bstate == BUTTON1_PRESSED && event.y == 0) {
6497 /* Get context from: "[1 2 3 4]..." */
6500 /* If clicked after contexts, go to parent */
6503 else if (r >= 0 && r != cfg.curctx) {
6504 savecurctx(path, pdents[cur].name, r);
6506 /* Reset the pointers */
6507 path = g_ctx[r].c_path;
6508 lastdir = g_ctx[r].c_last;
6509 lastname = g_ctx[r].c_name;
6519 if (sel == SEL_BACK) {
6521 dir = visit_parent(path, newpath, &presel);
6526 xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
6528 cdprep(lastdir, NULL, path, dir) ? (presel = FILTER) : (watch = TRUE);
6535 /* Middle click action */
6536 if (event.bstate == BUTTON2_PRESSED) {
6537 presel = middle_click_key;
6540 #if NCURSES_MOUSE_VERSION > 1
6542 if (event.bstate == BUTTON4_PRESSED && ndents && (cfg.rollover || cur)) {
6543 move_cursor((!cfg.rollover && cur < scroll_lines
6544 ? 0 : (cur + ndents - scroll_lines) % ndents), 0);
6549 if (event.bstate == BUTTON5_PRESSED && ndents
6550 && (cfg.rollover || (cur != ndents - 1))) {
6551 if (!cfg.rollover && cur >= ndents - scroll_lines)
6552 move_cursor(ndents-1, 0);
6554 move_cursor((cur + scroll_lines) % ndents, 0);
6559 /* Toggle filter mode on left click on last 2 lines */
6560 if (event.y >= xlines - 2 && event.bstate == BUTTON1_PRESSED) {
6562 cfg.filtermode ^= 1;
6563 if (cfg.filtermode) {
6568 /* Start watching the directory */
6576 /* Handle clicking on a file */
6577 if (event.y >= 2 && event.y <= ndents + 1 &&
6578 (event.bstate == BUTTON1_PRESSED ||
6579 event.bstate == BUTTON3_PRESSED)) {
6580 r = curscroll + (event.y - 2);
6584 else if ((event.bstate == BUTTON1_PRESSED) && !g_state.fifomode)
6585 notify_fifo(TRUE); /* Send clicked path to NNN_FIFO */
6587 /* Handle right click selection */
6588 if (event.bstate == BUTTON3_PRESSED) {
6596 #if defined(CLOCK_MONOTONIC_RAW)
6597 CLOCK_MONOTONIC_RAW,
6598 #elif defined(CLOCK_MONOTONIC)
6603 &mousetimings[currentmouse]);
6604 mousedent[currentmouse] = cur;
6606 /* Single click just selects, double click falls through to SEL_OPEN */
6607 if ((mousedent[0] != mousedent[1]) ||
6608 (((_ABSSUB(mousetimings[0].tv_sec, mousetimings[1].tv_sec) << 30)
6609 + (_ABSSUB(mousetimings[0].tv_nsec, mousetimings[1].tv_nsec)))
6610 > DBLCLK_INTERVAL_NS))
6612 mousetimings[currentmouse].tv_sec = 0;
6613 mousedent[currentmouse] = -1;
6615 if (cfg.filtermode || filterset())
6623 case SEL_NAV_IN: // fallthrough
6625 /* Cannot descend in empty directories */
6629 pent = &pdents[cur];
6630 mkpath(path, pent->name, newpath);
6633 /* Visit directory */
6634 if (pent->flags & DIR_OR_DIRLNK) {
6635 if (chdir(newpath) == -1) {
6640 cdprep(lastdir, lastname, path, newpath)
6641 ? (presel = FILTER) : (watch = TRUE);
6645 /* Cannot use stale data in entry, file may be missing by now */
6646 if (stat(newpath, &sb) == -1) {
6650 DPRINTF_U(sb.st_mode);
6652 /* Do not open non-regular files */
6653 if (!S_ISREG(sb.st_mode)) {
6654 printwait(messages[MSG_UNSUPPORTED], &presel);
6658 if (g_state.fifomode && (sel == SEL_OPEN)) {
6659 notify_fifo(TRUE); /* Send opened path to NNN_FIFO */
6663 /* If opened as vim plugin and Enter/^M pressed, pick */
6664 if (g_state.picker && (sel == SEL_OPEN)) {
6665 appendfpath(newpath, mkpath(path, pent->name, newpath));
6666 writesel(pselbuf, selbufpos - 1);
6667 return EXIT_SUCCESS;
6670 if (sel == SEL_NAV_IN) {
6671 /* If in listing dir, go to target on `l` or Right on symlink */
6672 if (listpath && S_ISLNK(pent->mode)
6673 && is_prefix(path, listpath, xstrlen(listpath))) {
6674 if (!realpath(pent->name, newpath)) {
6681 if (chdir(newpath) == -1) {
6686 /* Mark current directory */
6688 mark = xstrdup(path);
6690 cdprep(lastdir, NULL, path, newpath)
6691 ? (presel = FILTER) : (watch = TRUE);
6692 xstrsncpy(lastname, pent->name, NAME_MAX + 1);
6696 /* Open file disabled on right arrow or `l` */
6701 /* Handle plugin selection mode */
6702 if (g_state.runplugin) {
6703 g_state.runplugin = 0;
6704 /* Must be in plugin dir and same context to select plugin */
6705 if ((g_state.runctx == cfg.curctx) && !strcmp(path, plgpath)) {
6707 /* Copy path so we can return back to earlier dir */
6708 xstrsncpy(path, rundir, PATH_MAX);
6712 if (chdir(path) == -1
6713 || !run_plugin(&path, pent->name,
6714 runfile, &lastname, &lastdir)) {
6715 DPRINTF_S("plugin failed!");
6719 return EXIT_SUCCESS;
6722 xstrsncpy(lastname, runfile, NAME_MAX + 1);
6731 printwait(messages[MSG_EMPTY_FILE], &presel);
6736 #ifdef FILE_MIME_OPTS
6737 && get_output("file", FILE_MIME_OPTS, newpath, -1, FALSE, FALSE)
6738 && is_prefix(g_buf, "text/", 5)
6740 /* no MIME option; guess from description instead */
6741 && get_output("file", "-bL", newpath, -1, FALSE, FALSE)
6742 && strstr(g_buf, "text")
6745 spawn(editor, newpath, NULL, NULL, F_CLI);
6746 if (cfg.filtermode) {
6753 /* Get the extension for regex match */
6754 tmp = xextension(pent->name, pent->nlen - 1);
6756 if (tmp && !pcre_exec(archive_pcre, NULL, tmp,
6757 pent->nlen - (tmp - pent->name) - 1, 0, 0, NULL, 0)) {
6759 if (tmp && !regexec(&archive_re, tmp, 0, NULL, 0)) {
6761 r = get_input(messages[MSG_ARCHIVE_OPTS]);
6762 if (r == 'l' || r == 'x') {
6763 mkpath(path, pent->name, newpath);
6764 if (!handle_archive(newpath, r)) {
6774 if ((r == 'm') && !archive_mount(newpath)) {
6779 if (r == 'x' || r == 'm') {
6781 set_smart_ctx('+', newpath, &path, &lastname, &lastdir);
6789 printwait(messages[MSG_INVALID_KEY], &presel);
6794 /* Invoke desktop opener as last resort */
6795 spawn(opener, newpath, NULL, NULL, opener_flags);
6797 /* Move cursor to the next entry if not the last entry */
6798 if (g_state.autonext && cur != ndents - 1)
6799 move_cursor((cur + 1) % ndents, 0);
6800 if (cfg.filtermode) {
6805 case SEL_NEXT: // fallthrough
6806 case SEL_PREV: // fallthrough
6807 case SEL_PGDN: // fallthrough
6808 case SEL_CTRL_D: // fallthrough
6809 case SEL_PGUP: // fallthrough
6810 case SEL_CTRL_U: // fallthrough
6811 case SEL_HOME: // fallthrough
6812 case SEL_END: // fallthrough
6816 handle_screen_move(sel);
6819 case SEL_CDHOME: // fallthrough
6820 case SEL_CDBEGIN: // fallthrough
6821 case SEL_CDLAST: // fallthrough
6823 dir = (sel == SEL_CDHOME) ? home
6824 : ((sel == SEL_CDBEGIN) ? ipath
6825 : ((sel == SEL_CDLAST) ? lastdir
6826 : "/" /* SEL_CDROOT */));
6828 if (!dir || !*dir) {
6829 printwait(messages[MSG_NOT_SET], &presel);
6833 if (strcmp(path, dir) == 0) {
6839 dir = lastdir; /* Go to last dir on home/root key repeat */
6842 if (chdir(dir) == -1) {
6847 /* SEL_CDLAST: dir pointing to lastdir */
6848 xstrsncpy(newpath, dir, PATH_MAX); // fallthrough
6850 if (sel == SEL_BOOKMARK) {
6851 r = (int)handle_bookmark(mark, newpath);
6853 printwait(messages[r], &presel);
6857 if (strcmp(path, newpath) == 0)
6861 /* In list mode, retain the last file name to highlight it, if possible */
6862 cdprep(lastdir, listpath && sel == SEL_CDLAST ? NULL : lastname, path, newpath)
6863 ? (presel = FILTER) : (watch = TRUE);
6866 if ((sel == SEL_REMOTE) && !remote_mount(newpath)) {
6871 set_smart_ctx('+', newpath, &path, &lastname, &lastdir);
6874 case SEL_CYCLE: // fallthrough
6875 case SEL_CYCLER: // fallthrough
6876 case SEL_CTX1: // fallthrough
6877 case SEL_CTX2: // fallthrough
6878 case SEL_CTX3: // fallthrough
6886 r = handle_context_switch(sel);
6889 savecurctx(path, pdents[cur].name, r);
6891 /* Reset the pointers */
6892 path = g_ctx[r].c_path;
6893 lastdir = g_ctx[r].c_last;
6894 lastname = g_ctx[r].c_name;
6895 tmp = g_ctx[r].c_fltr;
6897 if (cfg.filtermode || ((tmp[0] == FILTER || tmp[0] == RFILTER) && tmp[1]))
6905 mark = xstrdup(path);
6906 printwait(mark, &presel);
6911 /* Unwatch dir if we are still in a filtered view */
6912 #ifdef LINUX_INOTIFY
6913 if (inotify_wd >= 0) {
6914 inotify_rm_watch(inotify_fd, inotify_wd);
6917 #elif defined(BSD_KQUEUE)
6918 if (event_fd >= 0) {
6922 #elif defined(HAIKU_NM)
6923 if (haiku_nm_active) {
6924 haiku_stop_watch(haiku_hnd);
6925 haiku_nm_active = FALSE;
6928 presel = filterentries(path, lastname);
6929 if (presel == ESC) {
6933 if (presel == FILTER) /* Refresh dir and filter again */
6936 case SEL_MFLTR: // fallthrough
6937 case SEL_HIDDEN: // fallthrough
6938 case SEL_DETAIL: // fallthrough
6942 cfg.filtermode ^= 1;
6943 if (cfg.filtermode) {
6949 watch = TRUE; // fallthrough
6951 if (sel == SEL_HIDDEN) {
6952 cfg.showhidden ^= 1;
6961 cfg.showdetail ^= 1;
6964 default: /* SEL_SORT */
6965 r = set_sort_flags(get_input(messages[MSG_ORDER]));
6967 printwait(messages[MSG_INVALID_KEY], &presel);
6972 if (cfg.filtermode || filterset())
6978 if (r == 'd' || r == 'a') {
6983 ENTSORT(pdents, ndents, entrycmpfn);
6984 move_cursor(ndents ? dentfind(lastname, ndents) : 0, 0);
6987 case SEL_STATS: // fallthrough
6990 tmp = (listpath && xstrcmp(path, listpath) == 0) ? listroot : path;
6991 mkpath(tmp, pdents[cur].name, newpath);
6993 if ((sel == SEL_STATS && !show_stats(newpath))
6994 || (lstat(newpath, &sb) == -1)
6995 || (sel == SEL_CHMODX && !xchmod(newpath, sb.st_mode))) {
7000 if (sel == SEL_CHMODX)
7001 pdents[cur].mode ^= 0111;
7004 case SEL_REDRAW: // fallthrough
7005 case SEL_RENAMEMUL: // fallthrough
7006 case SEL_HELP: // fallthrough
7007 case SEL_AUTONEXT: // fallthrough
7008 case SEL_EDIT: // fallthrough
7011 bool refresh = FALSE;
7014 mkpath(path, pdents[cur].name, newpath);
7015 else if (sel == SEL_EDIT) /* Avoid trying to edit a non-existing file */
7025 if (!(getutil(utils[UTIL_BASH])
7026 && plugscript(utils[UTIL_NMV], F_CLI))
7031 printwait(messages[MSG_FAILED], &presel);
7038 show_help(path); // fallthrough
7040 if (sel == SEL_AUTONEXT)
7041 g_state.autonext ^= 1;
7048 spawn(editor, newpath, NULL, NULL, F_CLI);
7050 default: /* SEL_LOCK */
7055 /* In case of successful operation, reload contents */
7057 /* Continue in type-to-nav mode, if enabled */
7058 if ((cfg.filtermode || filterset()) && !refresh) {
7066 /* Repopulate as directory content may have changed */
7074 if (g_state.rangesel)
7075 g_state.rangesel = 0;
7077 /* Toggle selection status */
7078 pdents[cur].flags ^= FILE_SELECTED;
7080 if (pdents[cur].flags & FILE_SELECTED) {
7082 appendfpath(newpath, mkpath(path, pdents[cur].name, newpath));
7083 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
7086 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
7091 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7098 /* move cursor to the next entry if this is not the last entry */
7099 if (!g_state.stayonsel && !g_state.picker && cur != ndents - 1)
7100 move_cursor((cur + 1) % ndents, 0);
7107 g_state.rangesel ^= 1;
7109 if (stat(path, &sb) == -1) {
7114 if (g_state.rangesel) { /* Range selection started */
7120 if (inode != sb.st_ino) {
7121 printwait(messages[MSG_DIR_CHANGED], &presel);
7125 if (cur < selstartid) {
7126 selendid = selstartid;
7131 /* Clear selection on repeat on same file */
7132 if (selstartid == selendid) {
7137 case SEL_SELALL: // fallthrough
7139 if (sel == SEL_SELALL || sel == SEL_SELINV) {
7144 if (g_state.rangesel)
7145 g_state.rangesel = 0;
7148 selendid = ndents - 1;
7151 if ((nselected > LARGESEL) || (nselected && (ndents > LARGESEL))) {
7152 printmsg("processing...");
7156 r = scanselforpath(path, TRUE); /* Get path length suffixed by '/' */
7157 ((sel == SEL_SELINV) && findselpos)
7158 ? invertselbuf(r) : addtoselbuf(r, selstartid, selendid);
7162 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7166 r = editselection();
7168 r = !r ? MSG_0_SELECTED : MSG_FAILED;
7169 printwait(messages[r], &presel);
7173 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7175 cfg.filtermode ? presel = FILTER : statusbar(path);
7178 case SEL_CP: // fallthrough
7179 case SEL_MV: // fallthrough
7180 case SEL_CPMVAS: // fallthrough
7183 if (sel == SEL_RM) {
7184 r = get_cur_or_sel();
7191 tmp = (listpath && xstrcmp(path, listpath) == 0)
7193 mkpath(tmp, pdents[cur].name, newpath);
7197 xrmfromsel(tmp, newpath);
7199 copynextname(lastname);
7201 if (cfg.filtermode || filterset())
7207 if (nselected == 1 && (sel == SEL_CP || sel == SEL_MV))
7208 mkpath(path, xbasename(pselbuf), newpath);
7214 if (!cpmvrm_selection(sel, path)) {
7224 /* Show notification on operation complete */
7226 plugscript(utils[UTIL_NTFY], F_NOWAIT | F_NOTRACE);
7229 if (newpath[0] && !access(newpath, F_OK))
7230 xstrsncpy(lastname, xbasename(newpath), NAME_MAX+1);
7235 case SEL_ARCHIVE: // fallthrough
7236 case SEL_OPENWITH: // fallthrough
7237 case SEL_NEW: // fallthrough
7242 if (!ndents && (sel == SEL_OPENWITH || sel == SEL_RENAME))
7245 if (sel != SEL_OPENWITH)
7250 r = get_cur_or_sel();
7264 tmp = pdents[cur].name;
7266 tmp = xreadline(tmp, messages[MSG_ARCHIVE_NAME]);
7270 tmp = xreadline(NULL, messages[MSG_OPEN_WITH]);
7272 tmp = getreadline(messages[MSG_OPEN_WITH]);
7276 r = get_input(messages[MSG_NEW_OPTS]);
7277 if (r == 'f' || r == 'd')
7278 tmp = xreadline(NULL, messages[MSG_NEW_PATH]);
7279 else if (r == 's' || r == 'h')
7280 tmp = xreadline(NULL, messages[MSG_LINK_PREFIX]);
7284 default: /* SEL_RENAME */
7285 tmp = xreadline(pdents[cur].name, "");
7294 if (r == 'c' && strcmp(tmp, pdents[cur].name) == 0)
7297 mkpath(path, tmp, newpath);
7298 if (access(newpath, F_OK) == 0) {
7299 if (!xconfirm(get_input(messages[MSG_OVERWRITE]))) {
7304 get_archive_cmd(newpath, tmp);
7305 (r == 's') ? archive_selection(newpath, tmp, path)
7306 : spawn(newpath, tmp, pdents[cur].name,
7307 NULL, F_CLI | F_CONFIRM);
7309 mkpath(path, tmp, newpath);
7310 if (access(newpath, F_OK) == 0) { /* File created */
7311 xstrsncpy(lastname, tmp, NAME_MAX + 1);
7312 clearfilter(); /* Archive name may not match */
7313 clearselection(); /* Archive operation complete */
7318 handle_openwith(path, pdents[cur].name, newpath, tmp);
7320 cfg.filtermode ? presel = FILTER : statusbar(path);
7324 /* Skip renaming to same name */
7325 if (strcmp(tmp, pdents[cur].name) == 0) {
7326 tmp = xreadline(pdents[cur].name, messages[MSG_COPY_NAME]);
7327 if (!tmp || !tmp[0] || !strcmp(tmp, pdents[cur].name)) {
7328 cfg.filtermode ? presel = FILTER : statusbar(path);
7335 default: /* SEL_NEW */
7339 /* Open the descriptor to currently open directory */
7341 fd = open(path, O_RDONLY | O_DIRECTORY);
7343 fd = open(path, O_RDONLY);
7350 /* Check if another file with same name exists */
7351 if (fstatat(fd, tmp, &sb, AT_SYMLINK_NOFOLLOW) == 0) {
7352 if (sel == SEL_RENAME) {
7353 /* Overwrite file with same name? */
7354 if (!xconfirm(get_input(messages[MSG_OVERWRITE]))) {
7359 /* Do nothing in case of NEW */
7361 printwait(messages[MSG_EXISTS], &presel);
7366 if (sel == SEL_RENAME) {
7367 /* Rename the file */
7369 spawn("cp -rp", pdents[cur].name, tmp, NULL, F_SILENT);
7370 else if (renameat(fd, pdents[cur].name, fd, tmp) != 0) {
7376 xstrsncpy(lastname, tmp, NAME_MAX + 1);
7377 } else { /* SEL_NEW */
7381 /* Check if it's a dir or file */
7382 if (r == 'f' || r == 'd') {
7383 mkpath(path, tmp, newpath);
7384 ret = xmktree(newpath, r == 'f' ? FALSE : TRUE);
7385 } else if (r == 's' || r == 'h') {
7386 if (tmp[0] == '@' && tmp[1] == '\0')
7388 ret = xlink(tmp, path, (ndents ? pdents[cur].name : NULL),
7389 newpath, &presel, r);
7393 printwait(messages[MSG_FAILED], &presel);
7398 if (r == 'f' || r == 'd')
7399 xstrsncpy(lastname, tmp, NAME_MAX + 1);
7411 /* Check if directory is accessible */
7412 if (!xdiraccess(plgpath)) {
7418 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
7419 printkeys(plug, g_buf + r - 1, maxplug);
7421 r = get_input(NULL);
7429 tmp = get_kv_val(plug, NULL, r, maxplug, NNN_PLUG);
7431 printwait(messages[MSG_INVALID_KEY], &presel);
7435 if (tmp[0] == '-' && tmp[1]) {
7437 r = FALSE; /* Do not refresh dir after completion */
7441 if (!run_plugin(&path, tmp, (ndents ? pdents[cur].name : NULL),
7442 &lastname, &lastdir)) {
7443 printwait(messages[MSG_FAILED], &presel);
7448 return EXIT_SUCCESS;
7454 cfg.filtermode ? presel = FILTER : statusbar(path);
7457 } else { /* 'Return/Enter' enters the plugin directory */
7458 g_state.runplugin ^= 1;
7459 if (!g_state.runplugin && rundir[0]) {
7461 * If toggled, and still in the plugin dir,
7462 * switch to original directory
7464 if (strcmp(path, plgpath) == 0) {
7465 xstrsncpy(path, rundir, PATH_MAX);
7466 xstrsncpy(lastname, runfile, NAME_MAX + 1);
7467 rundir[0] = runfile[0] = '\0';
7472 /* Otherwise, initiate choosing plugin again */
7473 g_state.runplugin = 1;
7476 xstrsncpy(rundir, path, PATH_MAX);
7477 xstrsncpy(path, plgpath, PATH_MAX);
7479 xstrsncpy(runfile, pdents[cur].name, NAME_MAX);
7480 g_state.runctx = cfg.curctx;
7486 case SEL_SHELL: // fallthrough
7487 case SEL_LAUNCH: // fallthrough
7489 r = handle_cmd(sel, (ndents ? pdents[cur].name : ""), newpath);
7491 /* Continue in type-to-nav mode, if enabled */
7502 /* Repopulate as directory content may have changed */
7506 if (!unmount((ndents ? pdents[cur].name : NULL), newpath, &presel, path)) {
7507 if (presel == MSG_ZERO)
7512 /* Dir removed, go to next entry */
7513 copynextname(lastname);
7517 r = get_input(messages[MSG_SSN_OPTS]);
7520 tmp = xreadline(NULL, messages[MSG_SSN_NAME]);
7522 save_session(tmp, &presel);
7523 } else if (r == 'l' || r == 'r') {
7524 if (load_session(NULL, &path, &lastdir, &lastname, r == 'r')) {
7535 cfg.filtermode ? presel = FILTER : statusbar(path);
7538 if (!set_time_type(&presel))
7541 case SEL_QUITCTX: // fallthrough
7542 case SEL_QUITCD: // fallthrough
7545 if (sel == SEL_QUITCTX) {
7546 int ctx = cfg.curctx;
7548 for (r = (ctx + 1) & ~CTX_MAX;
7549 (r != ctx) && !g_ctx[r].c_cfg.ctxactive;
7550 r = ((r + 1) & ~CTX_MAX)) {
7554 g_ctx[ctx].c_cfg.ctxactive = 0;
7556 /* Switch to next active context */
7557 path = g_ctx[r].c_path;
7558 lastdir = g_ctx[r].c_last;
7559 lastname = g_ctx[r].c_name;
7561 cfg = g_ctx[r].c_cfg;
7567 } else if (!g_state.forcequit) {
7568 for (r = 0; r < CTX_MAX; ++r)
7569 if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
7570 r = get_input(messages[MSG_QUIT_ALL]);
7574 if (!(r == CTX_MAX || xconfirm(r)))
7575 break; // fallthrough
7579 if (session && g_state.prstssn)
7580 save_session(session, NULL);
7584 if ((sel == SEL_QUITCD) || getenv("NNN_TMPFILE")) {
7585 write_lastdir(path);
7586 if ((sel == SEL_QUITCD) && g_state.picker)
7590 if (sel != SEL_QUITERR)
7591 return EXIT_SUCCESS;
7593 if (selbufpos && !g_state.picker) {
7594 /* Pick files to stdout and exit */
7598 return EXIT_SUCCESS;
7601 return EXIT_FAILURE;
7603 if (xlines != LINES || xcols != COLS)
7606 if (idletimeout && idle == idletimeout) {
7607 lock_terminal(); /* Locker */
7615 } /* switch (sel) */
7619 static char *make_tmp_tree(char **paths, ssize_t entries, const char *prefix)
7621 /* tmpdir holds the full path */
7622 /* tmp holds the path without the tmp dir prefix */
7626 ssize_t len = xstrlen(prefix);
7627 char *tmpdir = malloc(PATH_MAX);
7630 DPRINTF_S(strerror(errno));
7634 tmp = tmpdir + tmpfplen - 1;
7635 xstrsncpy(tmpdir, g_tmpfpath, tmpfplen);
7636 xstrsncpy(tmp, "/nnnXXXXXX", 11);
7638 /* Points right after the base tmp dir */
7641 /* handle the case where files are directly under / */
7642 if (!prefix[1] && (prefix[0] == '/'))
7645 if (!mkdtemp(tmpdir)) {
7648 DPRINTF_S(strerror(errno));
7654 for (ssize_t i = 0; i < entries; ++i) {
7658 err = stat(paths[i], &sb);
7659 if (err && errno == ENOENT)
7662 /* Don't copy the common prefix */
7663 xstrsncpy(tmp, paths[i] + len, xstrlen(paths[i]) - len + 1);
7665 /* Get the dir containing the path */
7666 slash = xmemrchr((uchar_t *)tmp, '/', xstrlen(paths[i]) - len);
7670 xmktree(tmpdir, TRUE);
7675 if (symlink(paths[i], tmpdir)) {
7676 DPRINTF_S(paths[i]);
7677 DPRINTF_S(strerror(errno));
7681 /* Get the dir in which to start */
7686 static char *load_input(int fd, const char *path)
7688 ssize_t i, chunk_count = 1, chunk = 512 * 1024 /* 512 KiB chunk size */, entries = 0;
7689 char *input = malloc(sizeof(char) * chunk), *tmpdir = NULL;
7690 char cwd[PATH_MAX], *next;
7691 size_t offsets[LIST_FILES_MAX];
7692 char **paths = NULL;
7693 ssize_t input_read, total_read = 0, off = 0;
7697 DPRINTF_S(strerror(errno));
7702 if (!getcwd(cwd, PATH_MAX)) {
7707 xstrsncpy(cwd, path, PATH_MAX);
7709 while (chunk_count < 512) {
7710 input_read = read(fd, input + total_read, chunk);
7711 if (input_read < 0) {
7712 DPRINTF_S(strerror(errno));
7716 if (input_read == 0)
7719 total_read += input_read;
7722 while (off < total_read) {
7723 next = memchr(input + off, '\0', total_read - off) + 1;
7724 if (next == (void *)1)
7727 if (next - input == off + 1) {
7732 if (entries == LIST_FILES_MAX) {
7737 offsets[entries++] = off;
7741 if (chunk_count == 512) {
7746 /* We don't need to allocate another chunk */
7747 if (chunk_count == (total_read - input_read) / chunk)
7750 chunk_count = total_read / chunk;
7751 if (total_read % chunk)
7754 input = xrealloc(input, (chunk_count + 1) * chunk);
7759 if (off != total_read) {
7760 if (entries == LIST_FILES_MAX) {
7765 offsets[entries++] = off;
7769 DPRINTF_D(total_read);
7770 DPRINTF_D(chunk_count);
7773 msgnum = MSG_0_ENTRIES;
7777 input[total_read] = '\0';
7779 paths = malloc(entries * sizeof(char *));
7783 for (i = 0; i < entries; ++i)
7784 paths[i] = input + offsets[i];
7786 listroot = malloc(sizeof(char) * PATH_MAX);
7791 DPRINTF_S(paths[0]);
7793 for (i = 0; i < entries; ++i) {
7794 if (paths[i][0] == '\n' || selforparent(paths[i])) {
7799 paths[i] = abspath(paths[i], cwd);
7801 entries = i; // free from the previous entry
7806 DPRINTF_S(paths[i]);
7808 xstrsncpy(g_buf, paths[i], PATH_MAX);
7809 if (!common_prefix(xdirname(g_buf), listroot)) {
7810 entries = i + 1; // free from the current entry
7814 DPRINTF_S(listroot);
7817 DPRINTF_S(listroot);
7820 tmpdir = make_tmp_tree(paths, entries, listroot);
7823 for (i = entries - 1; i >= 0; --i)
7827 if (home) { /* We are past init stage */
7828 printmsg(messages[msgnum]);
7829 xdelay(XDELAY_INTERVAL_MS);
7831 msg(messages[msgnum]);
7838 static void check_key_collision(void)
7841 bool bitmap[KEY_MAX] = {FALSE};
7843 for (ullong_t i = 0; i < sizeof(bindings) / sizeof(struct key); ++i) {
7844 key = bindings[i].sym;
7847 dprintf(STDERR_FILENO, "key collision! [%s]\n", keyname(key));
7853 static void usage(void)
7855 dprintf(STDERR_FILENO,
7856 "%s: nnn [OPTIONS] [PATH]\n\n"
7857 "The unorthodox terminal file manager.\n\n"
7858 "positional args:\n"
7859 " PATH start dir/file [default: .]\n\n"
7862 " -a auto NNN_FIFO\n"
7864 " -A no dir auto-select\n"
7865 " -b key open bookmark key (trumps -s/S)\n"
7866 " -c cli-only NNN_OPENER (trumps -e)\n"
7867 " -C 8-color scheme\n"
7869 " -D dirs in context color\n"
7870 " -e text in $VISUAL/$EDITOR/vi\n"
7871 " -E internal edits in EDITOR\n"
7873 " -f use readline history file\n"
7876 " -F val fifo mode [0:preview 1:explore]\n"
7878 " -g regex filters\n"
7879 " -H show hidden files\n"
7880 " -J no auto-proceed on select\n"
7881 " -K detect key collision\n"
7882 " -l val set scroll lines\n"
7883 " -n type-to-nav mode\n"
7884 " -o open files only on Enter\n"
7885 " -p file selection file [-:stdout]\n"
7886 " -P key run plugin key\n"
7887 " -Q no quit confirmation\n"
7888 " -r use advcpmv patched cp, mv\n"
7889 " -R no rollover at edges\n"
7891 " -s name load session by name\n"
7892 " -S persistent session\n"
7894 " -t secs timeout to lock\n"
7895 " -T key sort order [a/d/e/r/s/t/v]\n"
7896 " -u use selection (no prompt)\n"
7898 " -U show user and group\n"
7900 " -V show version\n"
7901 " -w place HW cursor on hovered\n"
7903 " -x notis, selection sync, xterm title\n"
7906 "v%s\n%s\n", __func__, VERSION, GENERAL_INFO);
7909 static bool setup_config(void)
7912 char *xdgcfg = getenv("XDG_CONFIG_HOME");
7915 /* Set up configuration file paths */
7916 if (xdgcfg && xdgcfg[0]) {
7918 if (xdgcfg[0] == '~') {
7919 r = xstrsncpy(g_buf, home, PATH_MAX);
7920 xstrsncpy(g_buf + r - 1, xdgcfg + 1, PATH_MAX);
7925 if (!xdiraccess(xdgcfg)) {
7930 len = xstrlen(xdgcfg) + 1 + 13; /* add length of "/nnn/sessions" */
7935 len = xstrlen(home) + 1 + 21; /* add length of "/.config/nnn/sessions" */
7937 cfgpath = (char *)malloc(len);
7938 plgpath = (char *)malloc(len);
7939 if (!cfgpath || !plgpath) {
7945 xstrsncpy(cfgpath, xdgcfg, len);
7946 r = len - 13; /* subtract length of "/nnn/sessions" */
7948 r = xstrsncpy(cfgpath, home, len);
7950 /* Create ~/.config */
7951 xstrsncpy(cfgpath + r - 1, "/.config", len - r);
7953 r += 8; /* length of "/.config" */
7956 /* Create ~/.config/nnn */
7957 xstrsncpy(cfgpath + r - 1, "/nnn", len - r);
7960 /* Create sessions, mounts and plugins directories */
7961 for (r = 0; r < ELEMENTS(toks); ++r) {
7962 mkpath(cfgpath, toks[r], plgpath);
7963 if (!xmktree(plgpath, TRUE)) {
7970 /* Set selection file path */
7971 if (!g_state.picker) {
7972 char *env_sel = xgetenv(env_cfg[NNN_SEL], NULL);
7974 selpath = env_sel ? xstrdup(env_sel)
7975 : (char *)malloc(len + 3); /* Length of "/.config/nnn/.selection" */
7983 r = xstrsncpy(selpath, cfgpath, len + 3);
7984 xstrsncpy(selpath + r - 1, "/.selection", 12);
7992 static bool set_tmp_path(void)
7995 char *path = xdiraccess(tmp) ? tmp : getenv("TMPDIR");
8002 tmpfplen = (uchar_t)xstrsncpy(g_tmpfpath, path, TMP_LEN_MAX);
8003 DPRINTF_S(g_tmpfpath);
8004 DPRINTF_U(tmpfplen);
8009 static void cleanup(void)
8012 if (cfg.x11 && !g_state.picker) {
8013 printf("\033[23;0t"); /* reset terminal window title */
8029 if (g_state.autofifo)
8032 if (g_state.pluginit)
8039 int main(int argc, char *argv[])
8042 char *session = NULL;
8043 int fd, opt, sort = 0, pkey = '\0'; /* Plugin key */
8046 char *middle_click_env = xgetenv(env_cfg[NNN_MCLICK], "\0");
8048 middle_click_key = (middle_click_env[0] == '^' && middle_click_env[1])
8049 ? CONTROL(middle_click_env[1])
8050 : (uchar_t)middle_click_env[0];
8053 const char * const env_opts = xgetenv(env_cfg[NNN_OPTS], NULL);
8054 int env_opts_id = env_opts ? (int)xstrlen(env_opts) : -1;
8056 bool rlhist = FALSE;
8059 while ((opt = (env_opts_id > 0
8060 ? env_opts[--env_opts_id]
8061 : getopt(argc, argv, "aAb:cCdDeEfF:gHJKl:nop:P:QrRs:St:T:uUVwxh"))) != -1) {
8065 g_state.autofifo = 1;
8072 if (env_opts_id < 0)
8079 g_state.oldcolor = 1;
8100 if (env_opts_id < 0) {
8102 if ((fd < 0) || (fd > 1))
8103 return EXIT_FAILURE;
8104 g_state.fifomode = fd;
8110 filterfn = &visible_re;
8116 g_state.stayonsel = 1;
8119 check_key_collision();
8120 return EXIT_SUCCESS;
8122 if (env_opts_id < 0)
8123 scroll_lines = atoi(optarg);
8132 if (env_opts_id >= 0)
8136 if (!(optarg[0] == '-' && optarg[1] == '\0')) {
8137 fd = open(optarg, O_WRONLY | O_CREAT, 0600);
8140 return EXIT_FAILURE;
8144 selpath = realpath(optarg, NULL);
8149 if (env_opts_id < 0 && !optarg[1])
8150 pkey = (uchar_t)optarg[0];
8153 g_state.forcequit = 1;
8157 cp[2] = cp[5] = mv[2] = mv[5] = 'g'; /* cp -iRp -> cpg -giRp */
8158 cp[4] = mv[4] = '-';
8166 if (env_opts_id < 0)
8170 g_state.prstssn = 1;
8171 if (!session) /* Support named persistent sessions */
8176 if (env_opts_id < 0)
8177 idletimeout = atoi(optarg);
8180 if (env_opts_id < 0)
8181 sort = (uchar_t)optarg[0];
8190 dprintf(STDOUT_FILENO, "%s\n", VERSION);
8191 return EXIT_SUCCESS;
8200 return EXIT_SUCCESS;
8203 return EXIT_FAILURE;
8205 if (env_opts_id == 0)
8214 /* Prefix for temporary files */
8215 if (!set_tmp_path())
8216 return EXIT_FAILURE;
8220 /* Check if we are in path list mode */
8221 if (!isatty(STDIN_FILENO)) {
8222 /* This is the same as listpath */
8223 initpath = load_input(STDIN_FILENO, NULL);
8225 return EXIT_FAILURE;
8227 /* We return to tty */
8228 dup2(STDOUT_FILENO, STDIN_FILENO);
8234 home = getenv("HOME");
8237 return EXIT_FAILURE;
8240 homelen = (uchar_t)xstrlen(home);
8242 if (!setup_config())
8243 return EXIT_FAILURE;
8245 /* Get custom opener, if set */
8246 opener = xgetenv(env_cfg[NNN_OPENER], utils[UTIL_OPENER]);
8249 /* Parse bookmarks string */
8250 if (!parsekvpair(&bookmark, &bmstr, NNN_BMS, &maxbm)) {
8251 msg(env_cfg[NNN_BMS]);
8252 return EXIT_FAILURE;
8255 /* Parse plugins string */
8256 if (!parsekvpair(&plug, &pluginstr, NNN_PLUG, &maxplug)) {
8257 msg(env_cfg[NNN_PLUG]);
8258 return EXIT_FAILURE;
8262 if (arg) { /* Open a bookmark directly */
8263 if (!arg[1]) /* Bookmarks keys are single char */
8264 initpath = get_kv_val(bookmark, NULL, *arg, maxbm, NNN_BMS);
8267 msg(messages[MSG_INVALID_KEY]);
8268 return EXIT_FAILURE;
8273 } else if (argc == optind) {
8274 /* Start in the current directory */
8275 initpath = getcwd(NULL, 0);
8281 if (xstrlen(arg) > 7 && is_prefix(arg, "file://", 7))
8283 initpath = realpath(arg, NULL);
8284 DPRINTF_S(initpath);
8287 return EXIT_FAILURE;
8291 * If nnn is set as the file manager, applications may try to open
8292 * files by invoking nnn. In that case pass the file path to the
8293 * desktop opener and exit.
8297 if (stat(initpath, &sb) == -1) {
8299 return EXIT_FAILURE;
8302 if (!S_ISDIR(sb.st_mode))
8303 g_state.initfile = 1;
8310 /* Set archive handling (enveditor used as tmp var) */
8311 enveditor = getenv(env_cfg[NNN_ARCHIVE]);
8313 if (setfilter(&archive_pcre, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8315 if (setfilter(&archive_re, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8317 msg(messages[MSG_INVALID_REG]);
8318 return EXIT_FAILURE;
8321 /* An all-CLI opener overrides option -e) */
8325 /* Get VISUAL/EDITOR */
8326 enveditor = xgetenv(envs[ENV_EDITOR], utils[UTIL_VI]);
8327 editor = xgetenv(envs[ENV_VISUAL], enveditor);
8328 DPRINTF_S(getenv(envs[ENV_VISUAL]));
8329 DPRINTF_S(getenv(envs[ENV_EDITOR]));
8333 pager = xgetenv(envs[ENV_PAGER], utils[UTIL_LESS]);
8337 shell = xgetenv(envs[ENV_SHELL], utils[UTIL_SH]);
8340 DPRINTF_S(getenv("PWD"));
8344 if (g_state.autofifo) {
8345 g_tmpfpath[tmpfplen - 1] = '\0';
8347 size_t r = mkpath(g_tmpfpath, "nnn-fifo.", g_buf);
8349 xstrsncpy(g_buf + r - 1, xitoa(getpid()), PATH_MAX - r);
8350 setenv("NNN_FIFO", g_buf, TRUE);
8353 fifopath = xgetenv("NNN_FIFO", NULL);
8355 if (mkfifo(fifopath, 0600) != 0 && !(errno == EEXIST && access(fifopath, W_OK) == 0)) {
8357 return EXIT_FAILURE;
8360 sigaction(SIGPIPE, &(struct sigaction){.sa_handler = SIG_IGN}, NULL);
8364 #ifdef LINUX_INOTIFY
8365 /* Initialize inotify */
8366 inotify_fd = inotify_init1(IN_NONBLOCK);
8367 if (inotify_fd < 0) {
8369 return EXIT_FAILURE;
8371 #elif defined(BSD_KQUEUE)
8375 return EXIT_FAILURE;
8377 #elif defined(HAIKU_NM)
8378 haiku_hnd = haiku_init_nm();
8381 return EXIT_FAILURE;
8385 /* Configure trash preference */
8386 opt = xgetenv_val(env_cfg[NNN_TRASH]);
8387 if (opt && opt <= 2)
8388 g_state.trash = opt;
8390 /* Ignore/handle certain signals */
8391 struct sigaction act = {.sa_handler = sigint_handler};
8393 if (sigaction(SIGINT, &act, NULL) < 0) {
8395 return EXIT_FAILURE;
8398 act.sa_handler = clean_exit_sighandler;
8400 if (sigaction(SIGTERM, &act, NULL) < 0 || sigaction(SIGHUP, &act, NULL) < 0) {
8402 return EXIT_FAILURE;
8405 act.sa_handler = SIG_IGN;
8407 if (sigaction(SIGQUIT, &act, NULL) < 0) {
8409 return EXIT_FAILURE;
8414 setlocale(LC_ALL, "");
8416 tables = pcre_maketables();
8421 #if RL_READLINE_VERSION >= 0x0603
8422 /* readline would overwrite the WINCH signal hook */
8423 rl_change_environment = 0;
8425 /* Bind TAB to cycling */
8426 rl_variable_bind("completion-ignore-case", "on");
8428 rl_bind_key('\t', rl_menu_complete);
8430 rl_bind_key('\t', rl_complete);
8433 mkpath(cfgpath, ".history", g_buf);
8434 read_history(g_buf);
8439 if (cfg.x11 && !g_state.picker) {
8440 /* Save terminal window title */
8441 printf("\033[22;0t");
8447 if (!initcurses(&mask))
8449 if (!initcurses(NULL))
8451 return EXIT_FAILURE;
8454 set_sort_flags(sort);
8456 opt = browse(initpath, session, pkey);
8459 mousemask(mask, NULL);
8466 mkpath(cfgpath, ".history", g_buf);
8467 write_history(g_buf);
8471 if (g_state.picker) {
8473 fd = selpath ? open(selpath, O_WRONLY | O_CREAT, 0600) : STDOUT_FILENO;
8474 if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
8483 /* Remove tmp dir in list mode */
8486 /* Free the regex */
8488 pcre_free(archive_pcre);
8490 regfree(&archive_re);
8493 /* Free the selection buffer */
8496 #ifdef LINUX_INOTIFY
8497 /* Shutdown inotify */
8498 if (inotify_wd >= 0)
8499 inotify_rm_watch(inotify_fd, inotify_wd);
8501 #elif defined(BSD_KQUEUE)
8505 #elif defined(HAIKU_NM)
8506 haiku_close_nm(haiku_hnd);
8510 if (!g_state.fifomode)