4 * Copyright (C) 2014-2016, Lazaros Koromilas <lostd@2f30.org>
5 * Copyright (C) 2014-2016, Dimitris Papastamos <sin@2f30.org>
6 * Copyright (C) 2016-2022, Arun Prakash Jana <engineerarun@gmail.com>
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 #ifdef MACOS_BELOW_1012
112 #include "../misc/macos-legacy/mach_gettime.h"
115 #if !defined(alloca) && defined(__GNUC__)
117 * GCC doesn't expand alloca() to __builtin_alloca() in standards mode
118 * (-std=...) and not all standard libraries do or supply it, e.g.
119 * NetBSD/arm64 so explicitly use the builtin.
121 #define alloca(size) __builtin_alloca(size)
127 #if defined(ICONS) || defined(NERD)
129 #define ICONS_ENABLED
136 /* Macro definitions */
137 #define VERSION "4.5"
138 #define GENERAL_INFO "BSD 2-Clause\nhttps://github.com/jarun/nnn"
141 #define SESSIONS_VERSION 1
145 #define S_BLKSIZE 512 /* S_BLKSIZE is missing on Android NDK (Termux) */
149 * NAME_MAX and PATH_MAX may not exist, e.g. with dirent.c_name being a
150 * flexible array on Illumos. Use somewhat accommodating fallback values.
157 #define PATH_MAX 4096
160 #define _ABSSUB(N, M) (((N) <= (M)) ? ((M) - (N)) : ((N) - (M)))
161 #define ELEMENTS(x) (sizeof(x) / sizeof(*(x)))
163 #define MIN(x, y) ((x) < (y) ? (x) : (y))
165 #define MAX(x, y) ((x) > (y) ? (x) : (y))
166 #define ISODD(x) ((x) & 1)
167 #define ISBLANK(x) ((x) == ' ' || (x) == '\t')
168 #define TOUPPER(ch) (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
169 #define TOLOWER(ch) (((ch) >= 'A' && (ch) <= 'Z') ? ((ch) - 'A' + 'a') : (ch))
170 #define ISUPPER_(ch) ((ch) >= 'A' && (ch) <= 'Z')
171 #define ISLOWER_(ch) ((ch) >= 'a' && (ch) <= 'z')
172 #define CMD_LEN_MAX (PATH_MAX + ((NAME_MAX + 1) << 1))
173 #define ALIGN_UP(x, A) ((((x) + (A) - 1) / (A)) * (A))
174 #define READLINE_MAX 256
180 #define PROMPT ">>> "
182 #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
183 #define NAMEBUF_INCR 0x800 /* 64 dir entries at once, avg. 32 chars per file name = 64*32B = 2KB */
184 #define DESCRIPTOR_LEN 32
185 #define _ALIGNMENT 0x10 /* 16-byte alignment */
186 #define _ALIGNMENT_MASK 0xF
187 #define TMP_LEN_MAX 64
188 #define DOT_FILTER_LEN 7
189 #define ASCII_MAX 128
190 #define EXEC_ARGS_MAX 10
191 #define LIST_FILES_MAX (1 << 16)
193 #define COLOR_256 256
196 #define DBLCLK_INTERVAL_NS (400000000)
197 #define XDELAY_INTERVAL_MS (350000) /* 350 ms delay */
206 /* BSDs or Solaris or SunOS */
207 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) || defined(sun) || defined(__sun)
214 /* Large selection threshold */
216 #define LARGESEL 1000
219 #define MIN_DISPLAY_COL (CTX_MAX * 2)
220 #define ARCHIVE_CMD_LEN 16
221 #define BLK_SHIFT_512 9
223 /* Detect hardlinks in du */
224 #define HASH_BITS (0xFFFFFF)
225 #define HASH_OCTETS (HASH_BITS >> 6) /* 2^6 = 64 */
228 #define DIR_OR_DIRLNK 0x01
229 #define HARD_LINK 0x02
230 #define SYM_ORPHAN 0x04
231 #define FILE_MISSING 0x08
232 #define FILE_SELECTED 0x10
233 #define FILE_SCANNED 0x20
234 #define FILE_YOUNG 0x40
236 /* Macros to define process spawn behaviour as flags */
237 #define F_NONE 0x00 /* no flag set */
238 #define F_MULTI 0x01 /* first arg can be combination of args; to be used with F_NORMAL */
239 #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
240 #define F_NOTRACE 0x04 /* suppress stdout and stderr (no traces) */
241 #define F_NORMAL 0x08 /* spawn child process in non-curses regular CLI mode */
242 #define F_CONFIRM 0x10 /* run command - show results before exit (must have F_NORMAL) */
243 #define F_CHKRTN 0x20 /* wait for user prompt if cmd returns failure status */
244 #define F_NOSTDIN 0x40 /* suppress stdin */
245 #define F_PAGE 0x80 /* page output in run-cmd-as-plugin mode */
246 #define F_TTY 0x100 /* Force stdout to go to tty if redirected to a non-tty */
247 #define F_CLI (F_NORMAL | F_MULTI)
248 #define F_SILENT (F_CLI | F_NOTRACE)
250 /* Version compare macros */
252 * states: S_N: normal, S_I: comparing integral part, S_F: comparing
253 * fractional parts, S_Z: idem but with leading Zeroes only
260 /* result_type: VCMP: return diff; VLEN: compare using len_diff/diff */
268 /* TYPE DEFINITIONS */
269 typedef unsigned int uint_t;
270 typedef unsigned char uchar_t;
271 typedef unsigned short ushort_t;
272 typedef unsigned long long ullong_t;
276 /* Directory entry */
277 typedef struct entry {
278 char *name; /* 8 bytes */
279 time_t sec; /* 8 bytes */
280 uint_t nsec; /* 4 bytes (enough to store nanosec) */
281 mode_t mode; /* 4 bytes */
282 off_t size; /* 8 bytes */
284 ullong_t blocks : 40; /* 5 bytes (enough for 512 TiB in 512B blocks allocated) */
285 ullong_t nlen : 16; /* 2 bytes (length of file name) */
286 ullong_t flags : 8; /* 1 byte (flags specific to the file) */
289 uid_t uid; /* 4 bytes */
290 gid_t gid; /* 4 bytes */
294 /* Selection marker */
300 /* Key-value pairs from env */
310 const regex_t *regex;
317 * NOTE: update default values if changing order
320 uint_t filtermode : 1; /* Set to enter filter mode */
321 uint_t timeorder : 1; /* Set to sort by time */
322 uint_t sizeorder : 1; /* Set to sort by file size */
323 uint_t apparentsz : 1; /* Set to sort by apparent size (disk usage) */
324 uint_t blkorder : 1; /* Set to sort by blocks used (disk usage) */
325 uint_t extnorder : 1; /* Order by extension */
326 uint_t showhidden : 1; /* Set to show hidden files */
327 uint_t reserved0 : 1;
328 uint_t showdetail : 1; /* Clear to show lesser file info */
329 uint_t ctxactive : 1; /* Context active or not */
330 uint_t reverse : 1; /* Reverse sort */
331 uint_t version : 1; /* Version sort */
332 uint_t reserved1 : 1;
333 /* The following settings are global */
334 uint_t curctx : 3; /* Current context number */
335 uint_t prefersel : 1; /* Prefer selection over current, if exists */
336 uint_t fileinfo : 1; /* Show file information on hover */
337 uint_t nonavopen : 1; /* Open file on right arrow or `l` */
338 uint_t autoenter : 1; /* auto-enter dir in type-to-nav mode */
339 uint_t reserved2 : 1;
340 uint_t useeditor : 1; /* Use VISUAL to open text files */
341 uint_t reserved3 : 3;
342 uint_t regex : 1; /* Use regex filters */
343 uint_t x11 : 1; /* Copy to system clipboard, show notis, xterm title */
344 uint_t timetype : 2; /* Time sort type (0: access, 1: change, 2: modification) */
345 uint_t cliopener : 1; /* All-CLI app opener */
346 uint_t waitedit : 1; /* For ops that can't be detached, used EDITOR */
347 uint_t rollover : 1; /* Roll over at edges */
350 /* Non-persistent program-internal states (alphabeical order) */
352 uint_t autofifo : 1; /* Auto-create NNN_FIFO */
353 uint_t autonext : 1; /* Auto-jump on open */
354 uint_t dircolor : 1; /* Current status of dir color */
355 uint_t dirctx : 1; /* Show dirs in context color */
356 uint_t duinit : 1; /* Initialize disk usage */
357 uint_t fifomode : 1; /* FIFO notify mode: 0: preview, 1: explore */
358 uint_t forcequit : 1; /* Do not prompt on quit */
359 uint_t initfile : 1; /* Positional arg is a file */
360 uint_t interrupt : 1; /* Program received an interrupt */
361 uint_t move : 1; /* Move operation */
362 uint_t oldcolor : 1; /* Use older colorscheme */
363 uint_t picked : 1; /* Plugin has picked files */
364 uint_t picker : 1; /* Write selection to user-specified file */
365 uint_t pluginit : 1; /* Plugin framework initialized */
366 uint_t prstssn : 1; /* Persistent session */
367 uint_t rangesel : 1; /* Range selection on */
368 uint_t runctx : 3; /* The context in which plugin is to be run */
369 uint_t runplugin : 1; /* Choose plugin mode */
370 uint_t selmode : 1; /* Set when selecting files */
371 uint_t stayonsel : 1; /* Disable auto-jump on select */
372 uint_t trash : 2; /* Trash method 0: rm -rf, 1: trash-cli, 2: gio trash */
373 uint_t uidgid : 1; /* Show owner and group info */
374 uint_t reserved : 7; /* Adjust when adding/removing a field */
377 /* Contexts or workspaces */
379 char c_path[PATH_MAX]; /* Current dir */
380 char c_last[PATH_MAX]; /* Last visited dir */
381 char c_name[NAME_MAX + 1]; /* Current file name */
382 char c_fltr[REGEX_MAX]; /* Current filter */
383 settings c_cfg; /* Current configuration */
384 uint_t color; /* Color code for directories */
390 size_t pathln[CTX_MAX];
391 size_t lastln[CTX_MAX];
392 size_t nameln[CTX_MAX];
393 size_t fltrln[CTX_MAX];
399 /* Configuration, contexts */
400 static settings cfg = {
424 2, /* timetype (T_MOD) */
430 static context g_ctx[CTX_MAX] __attribute__ ((aligned));
432 static int ndents, cur, last, curscroll, last_curscroll, total_dents = ENTRY_INCR, scroll_lines = 1;
433 static int nselected;
435 static int fifofd = -1;
437 static time_t gtimesecs;
438 static uint_t idletimeout, selbufpos, selbuflen;
439 static ushort_t xlines, xcols;
440 static ushort_t idle;
441 static uchar_t maxbm, maxplug, maxorder;
442 static uchar_t cfgsort[CTX_MAX + 1];
444 static char *pluginstr;
445 static char *orderstr;
448 static char *enveditor;
452 static char *initpath;
453 static char *cfgpath;
454 static char *selpath;
455 static char *listpath;
456 static char *listroot;
457 static char *plgpath;
458 static char *pnamebuf, *pselbuf, *findselpos;
461 static char hostname[_POSIX_HOST_NAME_MAX + 1];
464 static char *fifopath;
466 static char *lastcmd;
467 static ullong_t *ihashbmp;
468 static struct entry *pdents;
469 static blkcnt_t dir_blocks;
473 static uchar_t tmpfplen, homelen;
474 static uchar_t blk_shift = BLK_SHIFT_512;
476 static int middle_click_key;
479 static pcre *archive_pcre;
481 static regex_t archive_re;
484 /* pthread related */
485 #define NUM_DU_THREADS (4) /* Can use sysconf(_SC_NPROCESSORS_ONLN) */
486 #define DU_TEST (((node->fts_info & FTS_F) && \
487 (sb->st_nlink <= 1 || test_set_bit((uint_t)sb->st_ino))) || node->fts_info & FTS_DP)
489 static int threadbmp = -1; /* Has 1 in the bit position for idle threads */
490 static volatile int active_threads;
491 static pthread_mutex_t running_mutex = PTHREAD_MUTEX_INITIALIZER;
492 static pthread_mutex_t hardlink_mutex = PTHREAD_MUTEX_INITIALIZER;
493 static ullong_t *core_files;
494 static blkcnt_t *core_blocks;
495 static ullong_t num_files;
504 static thread_data *core_data;
506 /* Retain old signal handlers */
507 static struct sigaction oldsighup;
508 static struct sigaction oldsigtstp;
509 static struct sigaction oldsigwinch;
511 /* For use in functions which are isolated and don't return the buffer */
512 static char g_buf[CMD_LEN_MAX] __attribute__ ((aligned));
514 /* For use as a scratch buffer in selection manipulation */
515 static char g_sel[PATH_MAX] __attribute__ ((aligned));
517 /* Buffer to store tmp file path to show selection, file stats and help */
518 static char g_tmpfpath[TMP_LEN_MAX] __attribute__ ((aligned));
520 /* Buffer to store plugins control pipe location */
521 static char g_pipepath[TMP_LEN_MAX] __attribute__ ((aligned));
523 /* Non-persistent runtime states */
524 static runstate g_state;
526 /* Options to identify file MIME */
527 #if defined(__APPLE__)
528 #define FILE_MIME_OPTS "-bIL"
529 #elif !defined(__sun) /* no MIME option for 'file' */
530 #define FILE_MIME_OPTS "-biL"
533 /* Macros for utilities */
534 #define UTIL_OPENER 0
536 #define UTIL_BSDTAR 2
539 #define UTIL_LOCKER 5
540 #define UTIL_LAUNCH 6
541 #define UTIL_SH_EXEC 7
544 #define UTIL_RCLONE 10
552 #define UTIL_TRASH_CLI 18
553 #define UTIL_GIO_TRASH 19
554 #define UTIL_RM_RF 20
556 /* Utilities to open files, run actions */
557 static char * const utils[] = {
560 #elif defined __CYGWIN__
562 #elif defined __HAIKU__
573 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
575 #elif defined __HAIKU__
598 #define MSG_ZERO 0 /* Unused */
599 #define MSG_0_ENTRIES 1
600 #define STR_TMPFILE 2
601 #define MSG_0_SELECTED 3
604 #define MSG_SSN_NAME 6
605 #define MSG_CP_MV_AS 7
606 #define MSG_CUR_SEL_OPTS 8
607 #define MSG_FORCE_RM 9
609 #define MSG_NEW_OPTS 11
610 #define MSG_CLI_MODE 12
611 #define MSG_OVERWRITE 13
612 #define MSG_SSN_OPTS 14
613 #define MSG_QUIT_ALL 15
614 #define MSG_HOSTNAME 16
615 #define MSG_ARCHIVE_NAME 17
616 #define MSG_OPEN_WITH 18
617 #define MSG_NEW_PATH 19
618 #define MSG_LINK_PREFIX 20
619 #define MSG_COPY_NAME 21
621 #define MSG_SEL_MISSING 23
622 #define MSG_ACCESS 24
623 #define MSG_EMPTY_FILE 25
624 #define MSG_UNSUPPORTED 26
625 #define MSG_NOT_SET 27
626 #define MSG_EXISTS 28
627 #define MSG_FEW_COLUMNS 29
628 #define MSG_REMOTE_OPTS 30
629 #define MSG_RCLONE_DELAY 31
630 #define MSG_APP_NAME 32
631 #define MSG_ARCHIVE_OPTS 33
633 #define MSG_INVALID_REG 35
637 #define MSG_RM_TMP 39
638 #define MSG_INVALID_KEY 40
639 #define MSG_NOCHANGE 41
640 #define MSG_DIR_CHANGED 42
642 static const char * const messages[] = {
651 "'c'urrent / 's'el?",
652 "%s %s? [Esc/n/N cancels]",
654 "'f'ile / 'd'ir / 's'ym / 'h'ard?",
657 "'s'ave / 'l'oad / 'r'estore?",
658 "Quit all contexts?",
659 "remote name (- for hovered): ",
660 "archive [path/]name: ",
663 "link prefix [@ for none]: ",
664 "copy [path/]name: ",
665 "\n'Enter' to continue",
668 "empty! edit/open with",
673 "'s'shfs / 'r'clone?",
676 "'o'pen / e'x'tract / 'l's / 'm'nt?",
679 "'a'u / 'd'u / 'e'xt / 'r'ev / 's'z / 't'm / 'v'er / 'c'lr / '^T'?",
680 "unmount failed! try lazy?",
681 "first file (\')/char?",
685 "dir changed, range sel off",
688 /* Supported configuration environment variables */
694 #define NNN_FCOLORS 5
699 #define NNN_ARCHIVE 10
701 #define NNN_HELP 12 /* strings end here */
702 #define NNN_TRASH 13 /* flags begin here */
704 static const char * const env_cfg[] = {
721 /* Required environment variables */
728 static const char * const envs[] = {
742 static char cp[] = "cp -iRp";
743 static char mv[] = "mv -i";
745 static char cp[] = "cp -iRp";
746 static char mv[] = "mv -i";
749 /* Archive commands */
750 static const char * const archive_cmd[] = {"atool -a", "bsdtar -acvf", "zip -r", "tar -acvf"};
752 /* Tokens used for path creation */
758 static const char * const toks[] = {
762 "plugins", /* must be the last entry */
770 #define P_ARCHIVE_CMD 4
772 static const char * const patterns[] = {
773 SED" -i 's|^\\(\\(.*/\\)\\(.*\\)$\\)|#\\1\\n\\3|' %s",
774 SED" 's|^\\([^#/][^/]\\?.*\\)$|%s/\\1|;s|^#\\(/.*\\)$|\\1|' "
775 "%s | tr '\\n' '\\0' | xargs -0 -n2 sh -c '%s \"$0\" \"$@\" < /dev/tty'",
776 "\\.(bz|bz2|gz|tar|taz|tbz|tbz2|tgz|z|zip)$",
777 SED" -i 's|^%s\\(.*\\)$|%s\\1|' %s",
778 SED" -ze 's|^%s/||' '%s' | xargs -0 %s %s",
782 #define C_BLK (CTX_MAX + 1) /* Block device: DarkSeaGreen1 */
783 #define C_CHR (C_BLK + 1) /* Character device: Yellow1 */
784 #define C_DIR (C_CHR + 1) /* Directory: DeepSkyBlue1 */
785 #define C_EXE (C_DIR + 1) /* Executable file: Green1 */
786 #define C_FIL (C_EXE + 1) /* Regular file: Normal */
787 #define C_HRD (C_FIL + 1) /* Hard link: Plum4 */
788 #define C_LNK (C_HRD + 1) /* Symbolic link: Cyan1 */
789 #define C_MIS (C_LNK + 1) /* Missing file OR file details: Grey62 */
790 #define C_ORP (C_MIS + 1) /* Orphaned symlink: DeepPink1 */
791 #define C_PIP (C_ORP + 1) /* Named pipe (FIFO): Orange1 */
792 #define C_SOC (C_PIP + 1) /* Socket: MediumOrchid1 */
793 #define C_UND (C_SOC + 1) /* Unknown OR 0B regular/exe file: Red1 */
796 /* 0-9, A-Z, OTHER = 36. */
797 static ushort_t icon_positions[37];
800 static char gcolors[] = "c1e2272e006033f7c6d6abc4";
801 static uint_t fcolors[C_UND + 1] = {0};
805 #define NUM_EVENT_SLOTS 32 /* Make room for 32 events */
806 #define EVENT_SIZE (sizeof(struct inotify_event))
807 #define EVENT_BUF_LEN (EVENT_SIZE * NUM_EVENT_SLOTS)
808 static int inotify_fd, inotify_wd = -1;
809 static uint_t INOTIFY_MASK = /* IN_ATTRIB | */ IN_CREATE | IN_DELETE | IN_DELETE_SELF
810 | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
811 #elif defined(BSD_KQUEUE)
812 #define NUM_EVENT_SLOTS 1
813 #define NUM_EVENT_FDS 1
814 static int kq, event_fd = -1;
815 static struct kevent events_to_monitor[NUM_EVENT_FDS];
816 static uint_t KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK
817 | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
818 static struct timespec gtimeout;
819 #elif defined(HAIKU_NM)
820 static bool haiku_nm_active = FALSE;
821 static haiku_nm_h haiku_hnd;
824 /* Function macros */
825 #define tolastln() move(xlines - 1, 0)
826 #define tocursor() move(cur + 2 - curscroll, 0)
827 #define exitcurses() endwin()
828 #define printwarn(presel) printwait(strerror(errno), presel)
829 #define istopdir(path) ((path)[1] == '\0' && (path)[0] == '/')
830 #define copycurname() xstrsncpy(lastname, ndents ? pdents[cur].name : "\0", NAME_MAX + 1)
831 #define settimeout() timeout(1000)
832 #define cleartimeout() timeout(-1)
833 #define errexit() printerr(__LINE__)
834 #define setdirwatch() (cfg.filtermode ? (presel = FILTER) : (watch = TRUE))
835 #define filterset() (g_ctx[cfg.curctx].c_fltr[1])
836 /* We don't care about the return value from strcmp() */
837 #define xstrcmp(a, b) (*(a) != *(b) ? -1 : strcmp((a), (b)))
838 /* A faster version of xisdigit */
839 #define xisdigit(c) ((unsigned int) (c) - '0' <= 9)
840 #define xerror() perror(xitoa(__LINE__))
843 #define ENTLESS(i, j) (entrycmpfn(pdents + (i), pdents + (j)) < 0)
844 #define ENTSWAP(i, j) (swap_ent((i), (j)))
845 #define ENTSORT(pdents, ndents, entrycmpfn) QSORT((ndents), ENTLESS, ENTSWAP)
847 #define ENTSORT(pdents, ndents, entrycmpfn) qsort((pdents), (ndents), sizeof(*(pdents)), (entrycmpfn))
850 /* Forward declarations */
851 static void redraw(char *path);
852 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag);
853 static void move_cursor(int target, int ignore_scrolloff);
854 static char *load_input(int fd, const char *path);
855 static int set_sort_flags(int r);
856 static void statusbar(char *path);
857 static bool get_output(char *file, char *arg1, char *arg2, int fdout, bool multi, bool page);
859 static void notify_fifo(bool force);
864 static void sigint_handler(int sig)
867 g_state.interrupt = 1;
870 static void clean_exit_sighandler(int sig)
874 /* This triggers cleanup() thanks to atexit() */
878 static char *xitoa(uint_t val)
880 static char dst[32] = {'\0'};
881 static const char digits[201] =
882 "0001020304050607080910111213141516171819"
883 "2021222324252627282930313233343536373839"
884 "4041424344454647484950515253545556575859"
885 "6061626364656667686970717273747576777879"
886 "8081828384858687888990919293949596979899";
887 uint_t next = 30, quo, i;
891 i = (val - (quo * 100)) * 2;
893 dst[next] = digits[i + 1];
894 dst[--next] = digits[i];
898 /* Handle last 1-2 digits */
900 dst[next] = '0' + val;
903 dst[next] = digits[i + 1];
904 dst[--next] = digits[i];
910 /* Return the integer value of a char representing HEX */
911 static uchar_t xchartohex(uchar_t c)
916 if (c >= 'a' && c <= 'f')
919 if (c >= 'A' && c <= 'F')
926 * Source: https://elixir.bootlin.com/linux/latest/source/arch/alpha/include/asm/bitops.h
928 static bool test_set_bit(uint_t nr)
932 pthread_mutex_lock(&hardlink_mutex);
933 ullong_t *m = ((ullong_t *)ihashbmp) + (nr >> 6);
935 if (*m & (1 << (nr & 63))) {
936 pthread_mutex_unlock(&hardlink_mutex);
940 *m |= 1 << (nr & 63);
941 pthread_mutex_unlock(&hardlink_mutex);
947 /* Increase the limit on open file descriptors, if possible */
948 static void max_openfds(void)
952 if (!getrlimit(RLIMIT_NOFILE, &rl))
953 if (rl.rlim_cur < rl.rlim_max) {
954 rl.rlim_cur = rl.rlim_max;
955 setrlimit(RLIMIT_NOFILE, &rl);
961 * Wrapper to realloc()
962 * Frees current memory if realloc() fails and returns NULL.
964 * The *alloc() family returns aligned address: https://man7.org/linux/man-pages/man3/malloc.3.html
966 static void *xrealloc(void *pcur, size_t len)
968 void *pmem = realloc(pcur, len);
977 * Just a safe strncpy(3)
978 * Always null ('\0') terminates if both src and dest are valid pointers.
979 * Returns the number of bytes copied including terminating null byte.
981 static size_t xstrsncpy(char *restrict dst, const char *restrict src, size_t n)
983 char *end = memccpy(dst, src, '\0', n);
986 dst[n - 1] = '\0'; // NOLINT
987 end = dst + n; /* If we return n here, binary size increases due to auto-inlining */
993 static inline size_t xstrlen(const char *restrict s)
995 #if !defined(__GLIBC__)
996 return strlen(s); // NOLINT
998 return (char *)rawmemchr(s, '\0') - s; // NOLINT
1002 static char *xstrdup(const char *restrict s)
1004 size_t len = xstrlen(s) + 1;
1005 char *ptr = malloc(len);
1008 xstrsncpy(ptr, s, len);
1012 static bool is_suffix(const char *restrict str, const char *restrict suffix)
1014 if (!str || !suffix)
1017 size_t lenstr = xstrlen(str);
1018 size_t lensuffix = xstrlen(suffix);
1020 if (lensuffix > lenstr)
1023 return (xstrcmp(str + (lenstr - lensuffix), suffix) == 0);
1026 static inline bool is_prefix(const char *restrict str, const char *restrict prefix, size_t len)
1028 return !strncmp(str, prefix, len);
1032 * The poor man's implementation of memrchr(3).
1033 * We are only looking for '/' in this program.
1034 * And we are NOT expecting a '/' at the end.
1035 * Ideally 0 < n <= xstrlen(s).
1037 static void *xmemrchr(uchar_t *restrict s, uchar_t ch, size_t n)
1039 #if defined(__GLIBC__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
1040 return memrchr(s, ch, n);
1046 uchar_t *ptr = s + n;
1057 /* A very simplified implementation, changes path */
1058 static char *xdirname(char *path)
1060 char *base = xmemrchr((uchar_t *)path, '/', xstrlen(path));
1070 static char *xbasename(char *path)
1072 char *base = xmemrchr((uchar_t *)path, '/', xstrlen(path)); // NOLINT
1074 return base ? base + 1 : path;
1077 static inline char *xextension(const char *fname, size_t len)
1079 return xmemrchr((uchar_t *)fname, '.', len);
1084 * One-shot cache for getpwuid/getgrgid. Returns the cached name if the
1085 * provided uid is the same as the previous uid. Returns xitoa(guid) if
1086 * the guid is not found in the password database.
1088 static char *getpwname(uid_t uid)
1090 static uint_t uidcache = UINT_MAX;
1091 static char *namecache;
1093 if (uidcache != uid) {
1094 struct passwd *pw = getpwuid(uid);
1097 namecache = pw ? pw->pw_name : NULL;
1100 return namecache ? namecache : xitoa(uid);
1103 static char *getgrname(gid_t gid)
1105 static uint_t gidcache = UINT_MAX;
1106 static char *grpcache;
1108 if (gidcache != gid) {
1109 struct group *gr = getgrgid(gid);
1112 grpcache = gr ? gr->gr_name : NULL;
1115 return grpcache ? grpcache : xitoa(gid);
1119 static inline bool getutil(char *util)
1121 return spawn("which", util, NULL, NULL, F_NORMAL | F_NOTRACE) == 0;
1125 * Updates out with "dir/name or "/name"
1126 * Returns the number of bytes copied including the terminating NULL byte
1128 * Note: dir and out must be PATH_MAX in length to avoid macOS fault
1130 static size_t mkpath(const char *dir, const char *name, char *out)
1134 if (name[0] != '/') { // NOLINT
1135 /* Handle root case */
1139 len = xstrsncpy(out, dir, PATH_MAX);
1141 out[len - 1] = '/'; // NOLINT
1143 return (xstrsncpy(out + len, name, PATH_MAX - len) + len);
1146 /* Assumes both the paths passed are directories */
1147 static char *common_prefix(const char *path, char *prefix)
1149 const char *x = path, *y = prefix;
1152 if (!path || !*path || !prefix)
1156 xstrsncpy(prefix, path, PATH_MAX);
1160 while (*x && *y && (*x == *y))
1163 /* Strings are same */
1167 /* Path is shorter */
1168 if (!*x && *y == '/') {
1169 xstrsncpy(prefix, path, y - path);
1173 /* Prefix is shorter */
1174 if (!*y && *x == '/')
1177 /* Shorten prefix */
1178 prefix[y - prefix] = '\0';
1180 sep = xmemrchr((uchar_t *)prefix, '/', y - prefix);
1190 * The library function realpath() resolves symlinks.
1191 * If there's a symlink in file list we want to show the symlink not what it's points to.
1192 * Resolves ./../~ in path
1194 static char *abspath(const char *path, const char *cwd, char *buf)
1201 else if ((path[0] != '/') && !cwd)
1202 cwd = getcwd(NULL, 0);
1204 size_t dst_size = 0, src_size = xstrlen(path), cwd_size = cwd ? xstrlen(cwd) : 0;
1205 size_t len = src_size;
1209 * We need to add 2 chars at the end as relative paths may start with:
1211 * no separator (fd .): this needs an additional char for '/'
1213 char *resolved_path = buf ? buf : malloc(src_size + cwd_size + 2);
1218 /* Turn relative paths into absolute */
1219 if (path[0] != '/') {
1222 free(resolved_path);
1225 dst_size = xstrsncpy(resolved_path, cwd, cwd_size + 1) - 1;
1227 resolved_path[0] = '\0';
1230 dst = resolved_path + dst_size;
1231 for (const char *next = NULL; next != path + src_size;) {
1232 next = memchr(src, '/', len);
1234 next = path + src_size;
1236 if (next - src == 2 && src[0] == '.' && src[1] == '.') {
1237 if (dst - resolved_path) {
1238 dst = xmemrchr((uchar_t *)resolved_path, '/', dst - resolved_path);
1241 } else if (next - src == 1 && src[0] == '.') {
1243 } else if (next - src) {
1245 xstrsncpy(dst, src, next - src + 1);
1250 len = src_size - (src - path);
1253 if (*resolved_path == '\0') {
1254 resolved_path[0] = '/';
1255 resolved_path[1] = '\0';
1258 return resolved_path;
1261 static bool set_tilde_in_path(char *path)
1263 if (is_prefix(path, home, homelen)) {
1264 home[homelen] = path[homelen - 1];
1265 path[homelen - 1] = '~';
1272 static void reset_tilde_in_path(char *path)
1274 path[homelen - 1] = home[homelen];
1275 home[homelen] = '\0';
1279 static void xterm_cfg(char *path)
1281 if (cfg.x11 && !g_state.picker) {
1282 /* Signal CWD change to terminal */
1283 printf("\033]7;file://%s%s\033\\", hostname, path);
1285 /* Set terminal window title */
1286 bool r = set_tilde_in_path(path);
1288 printf("\033]2;%s\007", r ? &path[homelen - 1] : path);
1292 reset_tilde_in_path(path);
1297 static void convert_tilde(const char *path, char *buf)
1299 if (path[0] == '~') {
1300 ssize_t len = xstrlen(home);
1301 ssize_t loclen = xstrlen(path);
1303 xstrsncpy(buf, home, len + 1);
1304 xstrsncpy(buf + len, path + 1, loclen);
1308 static int create_tmp_file(void)
1310 xstrsncpy(g_tmpfpath + tmpfplen - 1, messages[STR_TMPFILE], TMP_LEN_MAX - tmpfplen);
1312 int fd = mkstemp(g_tmpfpath);
1315 DPRINTF_S(strerror(errno));
1321 static void msg(const char *message)
1323 dprintf(STDERR_FILENO, "%s\n", message);
1327 static void handle_key_resize(void)
1333 /* Clear the old prompt */
1334 static void clearoldprompt(void)
1337 move(xlines - 2, 0);
1342 handle_key_resize();
1346 /* Messages show up at the bottom */
1347 static inline void printmsg_nc(const char *msg)
1354 static void printmsg(const char *msg)
1356 attron(COLOR_PAIR(cfg.curctx + 1));
1358 attroff(COLOR_PAIR(cfg.curctx + 1));
1361 static void printwait(const char *msg, int *presel)
1367 xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
1371 /* Kill curses and display error before exiting */
1372 static void printerr(int linenum)
1375 perror(xitoa(linenum));
1376 if (!g_state.picker && selpath)
1382 static inline bool xconfirm(int c)
1384 return (c == 'y' || c == 'Y');
1387 static int get_input(const char *prompt)
1396 while (r == KEY_RESIZE) {
1410 static bool isselfileempty(void)
1414 return (stat(selpath, &sb) == -1) || (!sb.st_size);
1417 static int get_cur_or_sel(void)
1419 bool sel = (selbufpos || !isselfileempty());
1421 /* Check both local buffer and selection file for external selection */
1422 if (sel && ndents) {
1423 /* If selection is preferred and we have a local selection, return selection.
1424 * Always show the prompt in case of an external selection.
1426 if (cfg.prefersel && selbufpos)
1429 int choice = get_input(messages[MSG_CUR_SEL_OPTS]);
1431 return ((choice == 'c' || choice == 's') ? choice : 0);
1443 static void xdelay(useconds_t delay)
1449 static char confirm_force(bool selection)
1453 snprintf(str, 64, messages[MSG_FORCE_RM],
1454 g_state.trash ? utils[UTIL_GIO_TRASH] + 4 : utils[UTIL_RM_RF],
1455 (selection ? "selection" : "hovered"));
1457 int r = get_input(str);
1459 if (r == ESC || r == 'n' || r == 'N')
1460 return '\0'; /* cancel */
1461 if (r == 'y' || r == 'Y')
1462 return 'f'; /* forceful for rm */
1463 return (g_state.trash ? '\0' : 'i'); /* interactive for rm */
1466 /* Writes buflen char(s) from buf to a file */
1467 static void writesel(const char *buf, const size_t buflen)
1472 int fd = open(selpath, O_CREAT | O_WRONLY | O_TRUNC, 0666);
1475 if (write(fd, buf, buflen) != (ssize_t)buflen)
1482 static void appendfpath(const char *path, const size_t len)
1484 if ((selbufpos >= selbuflen) || ((len + 3) > (selbuflen - selbufpos))) {
1485 selbuflen += PATH_MAX;
1486 pselbuf = xrealloc(pselbuf, selbuflen);
1491 selbufpos += xstrsncpy(pselbuf + selbufpos, path, len);
1494 static void selbufrealloc(const size_t alloclen)
1496 if ((selbufpos + alloclen) > selbuflen) {
1497 selbuflen = ALIGN_UP(selbufpos + alloclen, PATH_MAX);
1498 pselbuf = xrealloc(pselbuf, selbuflen);
1504 /* Write selected file paths to fd, linefeed separated */
1505 static size_t seltofile(int fd, uint_t *pcount)
1507 uint_t lastpos, count = 0;
1508 char *pbuf = pselbuf;
1510 ssize_t len, prefixlen = 0, initlen = 0;
1518 lastpos = selbufpos - 1;
1521 prefixlen = (ssize_t)xstrlen(listroot);
1522 initlen = (ssize_t)xstrlen(listpath);
1525 while (pos <= lastpos) {
1527 len = (ssize_t)xstrlen(pbuf);
1529 if (!listpath || !is_prefix(pbuf, listpath, initlen)) {
1530 if (write(fd, pbuf, len) != len)
1533 if (write(fd, listroot, prefixlen) != prefixlen)
1535 if (write(fd, pbuf + initlen, len - initlen) != (len - initlen))
1540 if (pos <= lastpos) {
1541 if (write(fd, "\n", 1) != 1)
1555 /* List selection from selection file (another instance) */
1556 static bool listselfile(void)
1558 if (isselfileempty())
1561 snprintf(g_buf, CMD_LEN_MAX, "tr \'\\0\' \'\\n\' < %s", selpath);
1562 spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CONFIRM);
1567 /* Reset selection indicators */
1568 static void resetselind(void)
1570 for (int r = 0; r < ndents; ++r)
1571 if (pdents[r].flags & FILE_SELECTED)
1572 pdents[r].flags &= ~FILE_SELECTED;
1575 static void startselection(void)
1577 if (!g_state.selmode) {
1578 g_state.selmode = 1;
1589 static void clearselection(void)
1593 g_state.selmode = 0;
1597 static char *findinsel(char *startpos, int len)
1605 char *found = startpos;
1606 size_t buflen = selbufpos - (startpos - pselbuf);
1609 /* memmem(3): not specified in POSIX.1, but present on a number of other systems. */
1610 found = memmem(found, buflen - (found - startpos), g_sel, len);
1613 if (found == startpos || *(found - 1) == '\0')
1615 found += len; /* We found g_sel as a substring of a path, move forward */
1616 if (found >= startpos + buflen)
1621 static int markcmp(const void *va, const void *vb)
1623 const selmark *ma = (selmark*)va;
1624 const selmark *mb = (selmark*)vb;
1626 return ma->startpos - mb->startpos;
1629 /* scanselforpath() must be called before calling this */
1630 static inline void findmarkentry(size_t len, struct entry *dentp)
1632 if (!(dentp->flags & FILE_SCANNED)) {
1633 if (findinsel(findselpos, len + xstrsncpy(g_sel + len, dentp->name, dentp->nlen)))
1634 dentp->flags |= FILE_SELECTED;
1635 dentp->flags |= FILE_SCANNED;
1640 * scanselforpath() must be called before calling this
1641 * pathlen = length of path + 1 (+1 for trailing slash)
1643 static void invertselbuf(const int pathlen)
1645 size_t len, endpos, shrinklen = 0, alloclen = 0;
1646 char * const pbuf = g_sel + pathlen;
1648 int i, nmarked = 0, prev = 0;
1649 struct entry *dentp;
1650 selmark *marked = malloc(nselected * sizeof(selmark));
1653 /* First pass: inversion */
1654 for (i = 0; i < ndents; ++i) {
1657 if (dentp->flags & FILE_SCANNED) {
1658 if (dentp->flags & FILE_SELECTED) {
1659 dentp->flags ^= FILE_SELECTED; /* Clear selection status */
1662 dentp->flags |= FILE_SELECTED;
1663 alloclen += pathlen + dentp->nlen;
1666 dentp->flags |= FILE_SCANNED;
1671 len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1672 found = findinsel(findselpos, len);
1674 if (findselpos == found)
1677 if (nmarked && (found
1678 == (marked[nmarked - 1].startpos + marked[nmarked - 1].len)))
1679 marked[nmarked - 1].len += len;
1681 marked[nmarked].startpos = found;
1682 marked[nmarked].len = len;
1687 shrinklen += len; /* buffer size adjustment */
1689 dentp->flags |= FILE_SELECTED;
1690 alloclen += pathlen + dentp->nlen;
1697 * Files marked for deselection could be found in arbitrary order.
1698 * Sort by appearance in selection buffer.
1699 * With entries sorted we can merge adjacent ones allowing us to
1700 * move them in a single go.
1702 qsort(marked, nmarked, sizeof(selmark), &markcmp);
1704 /* Some files might be adjacent. Merge them into a single entry */
1705 for (i = 1; i < nmarked; ++i) {
1706 if (marked[i].startpos == marked[prev].startpos + marked[prev].len)
1707 marked[prev].len += marked[i].len;
1710 marked[prev].startpos = marked[i].startpos;
1711 marked[prev].len = marked[i].len;
1716 * Number of entries is increased by encountering a non-adjacent entry
1717 * After we finish the loop we should increment it once more.
1720 if (nmarked) /* Make sure there is something to deselect */
1723 /* Using merged entries remove unselected chunks from selection buffer */
1724 for (i = 0; i < nmarked; ++i) {
1726 * found: points to where the current block starts
1727 * variable is recycled from previous for readability
1728 * endpos: points to where the the next block starts
1729 * area between the end of current block (found + len)
1730 * and endpos is selected entries. This is what we are
1733 found = marked[i].startpos;
1734 endpos = (i + 1 == nmarked ? selbufpos : marked[i + 1].startpos - pselbuf);
1735 len = marked[i].len;
1737 /* Move back only selected entries. No selected memory is moved twice */
1738 memmove(found, found + len, endpos - (found + len - pselbuf));
1743 /* Buffer size adjustment */
1744 selbufpos -= shrinklen;
1746 selbufrealloc(alloclen);
1748 /* Second pass: append newly selected to buffer */
1749 for (i = 0; i < ndents; ++i) {
1750 if (pdents[i].flags & FILE_SELECTED) {
1751 len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1752 appendfpath(g_sel, len);
1757 nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1761 * scanselforpath() must be called before calling this
1762 * pathlen = length of path + 1 (+1 for trailing slash)
1764 static void addtoselbuf(const int pathlen, int startid, int endid)
1767 size_t len, alloclen = 0;
1768 struct entry *dentp;
1770 char * const pbuf = g_sel + pathlen;
1772 /* Remember current selection buffer position */
1773 for (i = startid; i <= endid; ++i) {
1777 len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1778 found = findinsel(findselpos, len);
1780 dentp->flags |= (FILE_SCANNED | FILE_SELECTED);
1781 if (found == findselpos) {
1783 if (findselpos == (pselbuf + selbufpos))
1787 alloclen += pathlen + dentp->nlen;
1789 alloclen += pathlen + dentp->nlen;
1792 selbufrealloc(alloclen);
1794 for (i = startid; i <= endid; ++i) {
1795 if (!(pdents[i].flags & FILE_SELECTED)) {
1796 len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1797 appendfpath(g_sel, len);
1799 pdents[i].flags |= (FILE_SCANNED | FILE_SELECTED);
1803 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
1806 /* Removes g_sel from selbuf */
1807 static void rmfromselbuf(size_t len)
1809 char *found = findinsel(findselpos, len);
1813 memmove(found, found + len, selbufpos - (found + len - pselbuf));
1816 nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1819 static int scanselforpath(const char *path, bool getsize)
1821 if (!path[1]) { /* path should always be at least two bytes (including NULL) */
1823 findselpos = pselbuf;
1824 return 1; /* Length of '/' is 1 */
1827 size_t off = xstrsncpy(g_sel, path, PATH_MAX);
1829 g_sel[off - 1] = '/';
1831 * We set findselpos only here. Directories can be listed in arbitrary order.
1832 * This is the best best we can do for remembering position.
1834 findselpos = findinsel(NULL, off);
1838 return (findselpos ? off : 0);
1841 /* Finish selection procedure before an operation */
1842 static void endselection(bool endselmode)
1846 char buf[sizeof(patterns[P_REPLACE]) + PATH_MAX + (TMP_LEN_MAX << 1)];
1848 if (endselmode && g_state.selmode)
1849 g_state.selmode = 0;
1851 /* The code below is only for listing mode */
1852 if (!listpath || !selbufpos)
1855 fd = create_tmp_file();
1857 DPRINTF_S("couldn't create tmp file");
1861 seltofile(fd, NULL);
1863 DPRINTF_S(strerror(errno));
1868 snprintf(buf, sizeof(buf), patterns[P_REPLACE], listpath, listroot, g_tmpfpath);
1869 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
1871 fd = open(g_tmpfpath, O_RDONLY);
1873 DPRINTF_S(strerror(errno));
1875 if (unlink(g_tmpfpath)) {
1876 DPRINTF_S(strerror(errno));
1882 count = read(fd, pselbuf, selbuflen);
1884 DPRINTF_S(strerror(errno));
1886 if (close(fd) || unlink(g_tmpfpath)) {
1887 DPRINTF_S(strerror(errno));
1892 if (close(fd) || unlink(g_tmpfpath)) {
1893 DPRINTF_S(strerror(errno));
1899 pselbuf[--count] = '\0';
1900 for (--count; count > 0; --count)
1901 if (pselbuf[count] == '\n' && pselbuf[count+1] == '/')
1902 pselbuf[count] = '\0';
1904 writesel(pselbuf, selbufpos - 1);
1907 /* Returns: 1 - success, 0 - none selected, -1 - other failure */
1908 static int editselection(void)
1916 if (!selbufpos) /* External selection is only editable at source */
1917 return listselfile();
1919 fd = create_tmp_file();
1921 DPRINTF_S("couldn't create tmp file");
1925 seltofile(fd, NULL);
1927 DPRINTF_S(strerror(errno));
1931 /* Save the last modification time */
1932 if (stat(g_tmpfpath, &sb)) {
1933 DPRINTF_S(strerror(errno));
1937 mtime = sb.st_mtime;
1939 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
1941 fd = open(g_tmpfpath, O_RDONLY);
1943 DPRINTF_S(strerror(errno));
1950 if (mtime == sb.st_mtime) {
1951 DPRINTF_S("selection is not modified");
1956 if (sb.st_size > selbufpos) {
1957 DPRINTF_S("edited buffer larger than previous");
1962 count = read(fd, pselbuf, selbuflen);
1964 DPRINTF_S(strerror(errno));
1966 if (close(fd) || unlink(g_tmpfpath)) {
1967 DPRINTF_S(strerror(errno));
1973 if (close(fd) || unlink(g_tmpfpath)) {
1974 DPRINTF_S(strerror(errno));
1986 /* The last character should be '\n' */
1987 pselbuf[--count] = '\0';
1988 for (--count; count > 0; --count) {
1989 /* Replace every '\n' that separates two paths */
1990 if (pselbuf[count] == '\n' && pselbuf[count + 1] == '/') {
1992 pselbuf[count] = '\0';
1996 /* Add a line for the last file */
1999 if (lines > nselected) {
2000 DPRINTF_S("files added to selection");
2005 writesel(pselbuf, selbufpos - 1);
2015 static bool selsafe(void)
2017 /* Fail if selection file path not generated */
2019 printmsg(messages[MSG_SEL_MISSING]);
2023 /* Fail if selection file path isn't accessible */
2024 if (access(selpath, R_OK | W_OK) == -1) {
2025 errno == ENOENT ? printmsg(messages[MSG_0_SELECTED]) : printwarn(NULL);
2032 static void export_file_list(void)
2037 struct entry *pdent = pdents;
2038 int fd = create_tmp_file();
2041 DPRINTF_S(strerror(errno));
2045 for (int r = 0; r < ndents; ++pdent, ++r) {
2046 if (write(fd, pdent->name, pdent->nlen - 1) != (pdent->nlen - 1))
2049 if ((r != ndents - 1) && (write(fd, "\n", 1) != 1))
2054 DPRINTF_S(strerror(errno));
2057 spawn(editor, g_tmpfpath, NULL, NULL, F_CLI);
2059 if (xconfirm(get_input(messages[MSG_RM_TMP])))
2063 static bool init_fcolors(void)
2065 char *f_colors = getenv(env_cfg[NNN_FCOLORS]);
2067 if (!f_colors || !*f_colors)
2070 for (uchar_t id = C_BLK; *f_colors && id <= C_UND; ++id) {
2071 fcolors[id] = xchartohex(*f_colors) << 4;
2073 fcolors[id] += xchartohex(*f_colors);
2075 init_pair(id, fcolors[id], -1);
2084 /* Initialize curses mode */
2085 static bool initcurses(void *oldmask)
2091 if (g_state.picker) {
2092 if (!newterm(NULL, stderr, stdin)) {
2096 } else if (!initscr()) {
2098 DPRINTF_S(getenv("TERM"));
2105 //intrflush(stdscr, FALSE);
2106 keypad(stdscr, TRUE);
2108 #if NCURSES_MOUSE_VERSION <= 1
2109 mousemask(BUTTON1_PRESSED | BUTTON1_DOUBLE_CLICKED | BUTTON2_PRESSED | BUTTON3_PRESSED,
2110 (mmask_t *)oldmask);
2112 mousemask(BUTTON1_PRESSED | BUTTON2_PRESSED | BUTTON3_PRESSED | BUTTON4_PRESSED
2113 | BUTTON5_PRESSED, (mmask_t *)oldmask);
2117 curs_set(FALSE); /* Hide cursor */
2119 char *colors = getenv(env_cfg[NNN_COLORS]);
2121 if (colors || !getenv("NO_COLOR")) {
2126 use_default_colors();
2128 /* Initialize file colors */
2129 if (COLORS >= COLOR_256) {
2130 if (!(g_state.oldcolor || init_fcolors())) {
2132 msg(env_cfg[NNN_FCOLORS]);
2136 g_state.oldcolor = 1;
2139 DPRINTF_D(COLOR_PAIRS);
2141 if (colors && *colors == '#') {
2142 char *sep = strchr(colors, ';');
2144 if (!g_state.oldcolor && COLORS >= COLOR_256) {
2149 * If fallback colors are specified, set the separator
2150 * to NULL so we don't interpret separator and fallback
2151 * if fewer than CTX_MAX xterm 256 colors are specified.
2156 colors = sep; /* Detect if 8 colors fallback is appended */
2162 /* Get and set the context colors */
2163 for (uchar_t i = 0; i < CTX_MAX; ++i) {
2164 pcode = &g_ctx[i].color;
2166 if (colors && *colors) {
2168 *pcode = xchartohex(*colors) << 4;
2170 fcolors[i + 1] = *pcode += xchartohex(*colors);
2171 else { /* Each color code must be 2 hex symbols */
2173 msg(env_cfg[NNN_COLORS]);
2177 *pcode = (*colors < '0' || *colors > '7') ? 4 : *colors - '0';
2182 init_pair(i + 1, *pcode, -1);
2186 #ifdef ICONS_ENABLED
2187 if (!g_state.oldcolor) {
2188 uchar_t icolors[COLOR_256] = {0};
2191 memset(icon_positions, 0x7f, sizeof(icon_positions));
2193 for (uint_t i = 0; i < ELEMENTS(icons_ext); ++i) {
2194 c = TOUPPER(icons_ext[i].match[0]);
2195 if (c >= 'A' && c <= 'Z') {
2196 if (icon_positions[c - 'A' + 10] == 0x7f7f)
2197 icon_positions[c - 'A' + 10] = i;
2198 } else if (c >= '0' && c <= '9') {
2199 if (icon_positions[c - '0'] == 0x7f7f)
2200 icon_positions[c - '0'] = i;
2201 } else if (icon_positions[36] == 0x7f7f)
2202 icon_positions[36] = i;
2204 if (icons_ext[i].color && !icolors[icons_ext[i].color]) {
2205 init_pair(C_UND + 1 + icons_ext[i].color, icons_ext[i].color, -1);
2206 icolors[icons_ext[i].color] = 1;
2212 settimeout(); /* One second */
2217 /* No NULL check here as spawn() guards against it */
2218 static char *parseargs(char *cmd, char **argv, int *pindex)
2221 size_t len = xstrlen(cmd) + 1;
2222 char *line = (char *)malloc(len);
2225 DPRINTF_S("malloc()!");
2229 xstrsncpy(line, cmd, len);
2230 argv[count++] = line;
2233 while (*line) { // NOLINT
2234 if (ISBLANK(*line)) {
2237 if (!*line) // NOLINT
2240 argv[count++] = line;
2241 if (count == EXEC_ARGS_MAX) {
2250 if (count == -1 || count > (EXEC_ARGS_MAX - 4)) { /* 3 args and last NULL */
2253 DPRINTF_S("NULL or too many args");
2260 static void enable_signals(void)
2262 struct sigaction dfl_act = {.sa_handler = SIG_DFL};
2264 sigaction(SIGHUP, &dfl_act, NULL);
2265 sigaction(SIGINT, &dfl_act, NULL);
2266 sigaction(SIGQUIT, &dfl_act, NULL);
2267 sigaction(SIGTSTP, &dfl_act, NULL);
2268 sigaction(SIGWINCH, &dfl_act, NULL);
2271 static pid_t xfork(uchar_t flag)
2276 /* the parent ignores the interrupt, quit and hangup signals */
2277 sigaction(SIGHUP, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsighup);
2278 sigaction(SIGTSTP, &(struct sigaction){.sa_handler = SIG_DFL}, &oldsigtstp);
2279 sigaction(SIGWINCH, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsigwinch);
2280 } else if (p == 0) {
2281 /* We create a grandchild to detach */
2282 if (flag & F_NOWAIT) {
2286 _exit(EXIT_SUCCESS);
2294 _exit(EXIT_FAILURE);
2297 /* So they can be used to stop the child */
2301 /* This is the parent waiting for the child to create grandchild */
2302 if (flag & F_NOWAIT)
2303 waitpid(p, NULL, 0);
2310 static int join(pid_t p, uchar_t flag)
2312 int status = 0xFFFF;
2314 if (!(flag & F_NOWAIT)) {
2315 /* wait for the child to exit */
2317 } while (waitpid(p, &status, 0) == -1);
2319 if (WIFEXITED(status)) {
2320 status = WEXITSTATUS(status);
2325 /* restore parent's signal handling */
2326 sigaction(SIGHUP, &oldsighup, NULL);
2327 sigaction(SIGTSTP, &oldsigtstp, NULL);
2328 sigaction(SIGWINCH, &oldsigwinch, NULL);
2334 * Spawns a child process. Behaviour can be controlled using flag.
2335 * Limited to 3 arguments to a program, flag works on bit set.
2337 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag)
2340 int status = 0, retstatus = 0xFFFF;
2341 char *argv[EXEC_ARGS_MAX] = {0};
2344 if (!file || !*file)
2347 /* Swap args if the first arg is NULL and the other 2 aren't */
2348 if (!arg1 && arg2) {
2357 if (flag & F_MULTI) {
2358 cmd = parseargs(file, argv, &status);
2362 argv[status++] = file;
2364 argv[status] = arg1;
2365 argv[++status] = arg2;
2366 argv[++status] = arg3;
2368 if (flag & F_NORMAL)
2373 /* Suppress stdout and stderr */
2374 if (flag & F_NOTRACE) {
2375 int fd = open("/dev/null", O_WRONLY, 0200);
2377 if (flag & F_NOSTDIN)
2378 dup2(fd, STDIN_FILENO);
2379 dup2(fd, STDOUT_FILENO);
2380 dup2(fd, STDERR_FILENO);
2382 } else if (flag & F_TTY) {
2383 /* If stdout has been redirected to a non-tty, force output to tty */
2384 if (!isatty(STDOUT_FILENO)) {
2385 int fd = open(ctermid(NULL), O_WRONLY, 0200);
2386 dup2(fd, STDOUT_FILENO);
2391 execvp(*argv, argv);
2392 _exit(EXIT_SUCCESS);
2394 retstatus = join(pid, flag);
2397 if ((flag & F_CONFIRM) || ((flag & F_CHKRTN) && retstatus)) {
2398 status = write(STDOUT_FILENO, messages[MSG_ENTER], xstrlen(messages[MSG_ENTER]));
2400 while ((read(STDIN_FILENO, &status, 1) > 0) && (status != '\n'));
2403 if (flag & F_NORMAL)
2412 /* Get program name from env var, else return fallback program */
2413 static char *xgetenv(const char * const name, char *fallback)
2415 char *value = getenv(name);
2417 return value && value[0] ? value : fallback;
2420 /* Checks if an env variable is set to 1 */
2421 static inline uint_t xgetenv_val(const char *name)
2423 char *str = getenv(name);
2431 /* Check if a dir exists, IS a dir, and is readable */
2432 static bool xdiraccess(const char *path)
2434 DIR *dirp = opendir(path);
2445 static bool plugscript(const char *plugin, uchar_t flags)
2447 mkpath(plgpath, plugin, g_buf);
2448 if (!access(g_buf, X_OK)) {
2449 spawn(g_buf, NULL, NULL, NULL, flags);
2456 static void opstr(char *buf, char *op)
2458 snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c '%s \"$0\" \"$@\" . < /dev/tty' < %s",
2462 static bool rmmulstr(char *buf)
2464 char r = confirm_force(TRUE);
2469 snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c 'rm -%cr \"$0\" \"$@\" < /dev/tty' < %s",
2472 snprintf(buf, CMD_LEN_MAX, "xargs -0 %s < %s",
2473 utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH], selpath);
2478 /* Returns TRUE if file is removed, else FALSE */
2479 static bool xrm(char * const fpath)
2481 char r = confirm_force(FALSE);
2485 if (!g_state.trash) {
2486 char rm_opts[] = "-ir";
2489 spawn("rm", rm_opts, fpath, NULL, F_NORMAL | F_CHKRTN);
2491 spawn(utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH],
2492 fpath, NULL, NULL, F_NORMAL | F_MULTI);
2494 return (access(fpath, F_OK) == -1); /* File is removed */
2497 static void xrmfromsel(char *path, char *fpath)
2500 bool selected = TRUE;
2503 if ((pdents[cur].flags & DIR_OR_DIRLNK) && scanselforpath(fpath, FALSE))
2505 else if (pdents[cur].flags & FILE_SELECTED) {
2507 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
2513 if (selected && cfg.x11)
2514 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
2518 static uint_t lines_in_file(int fd, char *buf, size_t buflen)
2523 while ((len = read(fd, buf, buflen)) > 0)
2525 count += (buf[--len] == '\n');
2527 /* For all use cases 0 linecount is considered as error */
2528 return ((len < 0) ? 0 : count);
2531 static bool cpmv_rename(int choice, const char *path)
2534 uint_t count = 0, lines = 0;
2536 char *cmd = (choice == 'c' ? cp : mv);
2537 char buf[sizeof(patterns[P_CPMVRNM]) + sizeof(cmd) + (PATH_MAX << 1)];
2539 fd = create_tmp_file();
2543 /* selsafe() returned TRUE for this to be called */
2545 snprintf(buf, sizeof(buf), "tr '\\0' '\\n' < %s > %s", selpath, g_tmpfpath);
2546 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2548 count = lines_in_file(fd, buf, sizeof(buf));
2552 seltofile(fd, &count);
2556 snprintf(buf, sizeof(buf), patterns[P_CPMVFMT], g_tmpfpath);
2557 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2559 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2561 fd = open(g_tmpfpath, O_RDONLY);
2565 lines = lines_in_file(fd, buf, sizeof(buf));
2568 if (!lines || (2 * count != lines)) {
2569 DPRINTF_S("num mismatch");
2573 snprintf(buf, sizeof(buf), patterns[P_CPMVRNM], path, g_tmpfpath, cmd);
2574 if (!spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CHKRTN))
2583 static bool cpmvrm_selection(enum action sel, char *path)
2587 if (isselfileempty()) {
2590 printmsg(messages[MSG_0_SELECTED]);
2605 r = get_input(messages[MSG_CP_MV_AS]);
2606 if (r != 'c' && r != 'm') {
2607 printmsg(messages[MSG_INVALID_KEY]);
2611 if (!cpmv_rename(r, path)) {
2612 printmsg(messages[MSG_FAILED]);
2616 default: /* SEL_RM */
2617 if (!rmmulstr(g_buf)) {
2618 printmsg(messages[MSG_CANCEL]);
2623 if (sel != SEL_CPMVAS && spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CHKRTN)) {
2624 printmsg(messages[MSG_FAILED]);
2628 /* Clear selection */
2635 static bool batch_rename(void)
2638 uint_t count = 0, lines = 0;
2639 bool dir = FALSE, ret = FALSE;
2640 char foriginal[TMP_LEN_MAX] = {0};
2641 static const char batchrenamecmd[] = "paste -d'\n' %s %s | "SED" 'N; /^\\(.*\\)\\n\\1$/!p;d' | "
2642 "tr '\n' '\\0' | xargs -0 -n2 sh -c 'mv -i \"$0\" \"$@\" <"
2644 char buf[sizeof(batchrenamecmd) + (PATH_MAX << 1)];
2645 int i = get_cur_or_sel();
2650 if (i == 'c') { /* Rename entries in current dir */
2655 fd1 = create_tmp_file();
2659 xstrsncpy(foriginal, g_tmpfpath, xstrlen(g_tmpfpath) + 1);
2661 fd2 = create_tmp_file();
2669 for (i = 0; i < ndents; ++i)
2670 appendfpath(pdents[i].name, NAME_MAX);
2672 seltofile(fd1, &count);
2673 seltofile(fd2, NULL);
2676 if (dir) /* Don't retain dir entries in selection */
2679 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2681 /* Reopen file descriptor to get updated contents */
2682 fd2 = open(g_tmpfpath, O_RDONLY);
2686 lines = lines_in_file(fd2, buf, sizeof(buf));
2689 if (!lines || (count != lines)) {
2690 DPRINTF_S("cannot delete files");
2694 snprintf(buf, sizeof(buf), batchrenamecmd, foriginal, g_tmpfpath);
2695 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2711 static void get_archive_cmd(char *cmd, const char *archive)
2715 if (getutil(utils[UTIL_ATOOL]))
2717 else if (getutil(utils[UTIL_BSDTAR]))
2719 else if (is_suffix(archive, ".zip"))
2723 xstrsncpy(cmd, archive_cmd[i], ARCHIVE_CMD_LEN);
2726 static void archive_selection(const char *cmd, const char *archive, const char *curpath)
2728 char *buf = malloc((xstrlen(patterns[P_ARCHIVE_CMD]) + xstrlen(cmd) + xstrlen(archive)
2729 + xstrlen(curpath) + xstrlen(selpath)) * sizeof(char));
2731 DPRINTF_S(strerror(errno));
2736 snprintf(buf, CMD_LEN_MAX, patterns[P_ARCHIVE_CMD], curpath, selpath, cmd, archive);
2737 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CONFIRM);
2741 static void write_lastdir(const char *curpath, const char *outfile)
2744 xstrsncpy(cfgpath + xstrlen(cfgpath), "/.lastd", 8);
2746 convert_tilde(outfile, g_buf);
2748 int fd = open(outfile
2749 ? (outfile[0] == '~' ? g_buf : outfile)
2750 : cfgpath, O_CREAT | O_WRONLY | O_TRUNC, 0666);
2753 dprintf(fd, "cd \"%s\"", curpath);
2759 * We assume none of the strings are NULL.
2761 * Let's have the logic to sort numeric names in numeric order.
2762 * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
2764 * If the absolute numeric values are same, we fallback to alphasort.
2766 static int xstricmp(const char * const s1, const char * const s2)
2770 long long v1 = strtoll(s1, &p1, 10);
2771 long long v2 = strtoll(s2, &p2, 10);
2773 /* Check if at least 1 string is numeric */
2774 if (s1 != p1 || s2 != p2) {
2775 /* Handle both pure numeric */
2776 if (s1 != p1 && s2 != p2) {
2784 /* Only first string non-numeric */
2788 /* Only second string non-numeric */
2793 /* Handle 1. all non-numeric and 2. both same numeric value cases */
2795 return strcoll(s1, s2);
2797 return strcasecmp(s1, s2);
2802 * Version comparison
2804 * The code for version compare is a modified version of the GLIBC
2805 * and uClibc implementation of strverscmp(). The source is here:
2806 * https://elixir.bootlin.com/uclibc-ng/latest/source/libc/string/strverscmp.c
2810 * Compare S1 and S2 as strings holding indices/version numbers,
2811 * returning less than, equal to or greater than zero if S1 is less than,
2812 * equal to or greater than S2 (for more info, see the texinfo doc).
2816 static int xstrverscasecmp(const char * const s1, const char * const s2)
2818 const uchar_t *p1 = (const uchar_t *)s1;
2819 const uchar_t *p2 = (const uchar_t *)s2;
2824 * Symbol(s) 0 [1-9] others
2825 * Transition (10) 0 (01) d (00) x
2827 static const uint8_t next_state[] = {
2829 /* S_N */ S_N, S_I, S_Z,
2830 /* S_I */ S_N, S_I, S_I,
2831 /* S_F */ S_N, S_F, S_F,
2832 /* S_Z */ S_N, S_F, S_Z
2835 static const int8_t result_type[] __attribute__ ((aligned)) = {
2836 /* state x/x x/d x/0 d/x d/d d/0 0/x 0/d 0/0 */
2838 /* S_N */ VCMP, VCMP, VCMP, VCMP, VLEN, VCMP, VCMP, VCMP, VCMP,
2839 /* S_I */ VCMP, -1, -1, 1, VLEN, VLEN, 1, VLEN, VLEN,
2840 /* S_F */ VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP,
2841 /* S_Z */ VCMP, 1, 1, -1, VCMP, VCMP, -1, VCMP, VCMP
2852 /* Hint: '0' is a digit too. */
2853 state = S_N + ((c1 == '0') + (xisdigit(c1) != 0));
2855 while ((diff = c1 - c2) == 0) {
2859 state = next_state[state];
2864 state += (c1 == '0') + (xisdigit(c1) != 0);
2867 state = result_type[state * 3 + (((c2 == '0') + (xisdigit(c2) != 0)))]; // NOLINT
2873 while (xisdigit(*p1++))
2874 if (!xisdigit(*p2++))
2876 return xisdigit(*p2) ? -1 : diff;
2882 static int (*namecmpfn)(const char * const s1, const char * const s2) = &xstricmp;
2884 static char * (*fnstrstr)(const char *haystack, const char *needle) = &strcasestr;
2886 static const unsigned char *tables;
2887 static int pcreflags = PCRE_NO_AUTO_CAPTURE | PCRE_EXTENDED | PCRE_CASELESS | PCRE_UTF8;
2889 static int regflags = REG_NOSUB | REG_EXTENDED | REG_ICASE;
2893 static int setfilter(pcre **pcrex, const char *filter)
2895 const char *errstr = NULL;
2898 *pcrex = pcre_compile(filter, pcreflags, &errstr, &erroffset, tables);
2900 return errstr ? -1 : 0;
2903 static int setfilter(regex_t *regex, const char *filter)
2905 return regcomp(regex, filter, regflags);
2909 static int visible_re(const fltrexp_t *fltrexp, const char *fname)
2912 return pcre_exec(fltrexp->pcrex, NULL, fname, xstrlen(fname), 0, 0, NULL, 0) == 0;
2914 return regexec(fltrexp->regex, fname, 0, NULL, 0) == 0;
2918 static int visible_str(const fltrexp_t *fltrexp, const char *fname)
2920 return fnstrstr(fname, fltrexp->str) != NULL;
2923 static int (*filterfn)(const fltrexp_t *fltr, const char *fname) = &visible_str;
2925 static void clearfilter(void)
2927 char *fltr = g_ctx[cfg.curctx].c_fltr;
2930 fltr[REGEX_MAX - 1] = fltr[1];
2935 static int entrycmp(const void *va, const void *vb)
2937 const struct entry *pa = (pEntry)va;
2938 const struct entry *pb = (pEntry)vb;
2940 if ((pb->flags & DIR_OR_DIRLNK) != (pa->flags & DIR_OR_DIRLNK)) {
2941 if (pb->flags & DIR_OR_DIRLNK)
2946 /* Sort based on specified order */
2947 if (cfg.timeorder) {
2948 if (pb->sec > pa->sec)
2950 if (pb->sec < pa->sec)
2952 /* If sec matches, comare nsec */
2953 if (pb->nsec > pa->nsec)
2955 if (pb->nsec < pa->nsec)
2957 } else if (cfg.sizeorder) {
2958 if (pb->size > pa->size)
2960 if (pb->size < pa->size)
2962 } else if (cfg.blkorder) {
2963 if (pb->blocks > pa->blocks)
2965 if (pb->blocks < pa->blocks)
2967 } else if (cfg.extnorder && !(pb->flags & DIR_OR_DIRLNK)) {
2968 char *extna = xextension(pa->name, pa->nlen - 1);
2969 char *extnb = xextension(pb->name, pb->nlen - 1);
2971 if (extna || extnb) {
2978 int ret = strcasecmp(extna, extnb);
2985 return namecmpfn(pa->name, pb->name);
2988 static int reventrycmp(const void *va, const void *vb)
2990 if ((((pEntry)vb)->flags & DIR_OR_DIRLNK)
2991 != (((pEntry)va)->flags & DIR_OR_DIRLNK)) {
2992 if (((pEntry)vb)->flags & DIR_OR_DIRLNK)
2997 return -entrycmp(va, vb);
3000 static int (*entrycmpfn)(const void *va, const void *vb) = &entrycmp;
3002 /* In case of an error, resets *wch to Esc */
3003 static int handle_alt_key(wint_t *wch)
3007 int r = get_wch(wch);
3016 static inline int handle_event(void)
3018 if (nselected && isselfileempty())
3020 return CONTROL('L');
3024 * Returns SEL_* if key is bound and 0 otherwise.
3025 * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
3026 * The next keyboard input can be simulated by presel.
3028 static int nextsel(int presel)
3035 bool escaped = FALSE;
3037 if (c == 0 || c == MSGWAIT) {
3041 //DPRINTF_S(keyname(c));
3044 if (c == KEY_RESIZE)
3045 handle_key_resize();
3048 /* Handle Alt+key */
3060 } else if (escaped) {
3065 if (!g_state.fifomode)
3066 notify_fifo(TRUE); /* Send hovered path to NNN_FIFO */
3074 if (c == ERR && presel == MSGWAIT)
3075 c = (cfg.filtermode || filterset()) ? FILTER : CONTROL('L');
3076 else if (c == FILTER || c == CONTROL('L'))
3077 /* Clear previous filter when manually starting */
3085 * Do not check for directory changes in du mode.
3086 * A redraw forces du calculation.
3087 * Check for changes every odd second.
3089 #ifdef LINUX_INOTIFY
3090 if (!cfg.blkorder && inotify_wd >= 0 && (idle & 1)) {
3091 struct inotify_event *event;
3092 char inotify_buf[EVENT_BUF_LEN];
3094 memset((void *)inotify_buf, 0x0, EVENT_BUF_LEN);
3095 i = read(inotify_fd, inotify_buf, EVENT_BUF_LEN);
3097 for (char *ptr = inotify_buf;
3098 ptr + ((struct inotify_event *)ptr)->len < inotify_buf + i;
3099 ptr += sizeof(struct inotify_event) + event->len) {
3100 event = (struct inotify_event *)ptr;
3101 DPRINTF_D(event->wd);
3102 DPRINTF_D(event->mask);
3106 if (event->mask & INOTIFY_MASK) {
3111 DPRINTF_S("inotify read done");
3114 #elif defined(BSD_KQUEUE)
3115 if (!cfg.blkorder && event_fd >= 0 && (idle & 1)) {
3116 struct kevent event_data[NUM_EVENT_SLOTS];
3118 memset((void *)event_data, 0x0, sizeof(struct kevent) * NUM_EVENT_SLOTS);
3119 if (kevent(kq, events_to_monitor, NUM_EVENT_SLOTS,
3120 event_data, NUM_EVENT_FDS, >imeout) > 0)
3123 #elif defined(HAIKU_NM)
3124 if (!cfg.blkorder && haiku_nm_active && (idle & 1) && haiku_is_update_needed(haiku_hnd))
3130 for (i = 0; i < (int)ELEMENTS(bindings); ++i)
3131 if (c == bindings[i].sym)
3132 return bindings[i].act;
3137 static int getorderstr(char *sort)
3145 sort[i++] = (cfg.timetype == T_MOD) ? 'M' : ((cfg.timetype == T_ACCESS) ? 'A' : 'C');
3146 else if (cfg.sizeorder)
3148 else if (cfg.extnorder)
3151 if (entrycmpfn == &reventrycmp)
3154 if (namecmpfn == &xstrverscasecmp)
3163 static void showfilterinfo(void)
3166 char info[REGEX_MAX] = "\0\0\0\0\0";
3168 i = getorderstr(info);
3170 if (cfg.fileinfo && ndents && get_output("file", "-b", pdents[cur].name, -1, FALSE, FALSE))
3171 mvaddstr(xlines - 2, 2, g_buf);
3173 snprintf(info + i, REGEX_MAX - i - 1, " %s [/], %s [:]",
3174 (cfg.regex ? "reg" : "str"),
3175 ((fnstrstr == &strcasestr) ? "ic" : "noic"));
3178 mvaddstr(xlines - 2, xcols - xstrlen(info), info);
3181 static void showfilter(char *str)
3183 attron(COLOR_PAIR(cfg.curctx + 1));
3186 // printmsg calls attroff()
3189 static inline void swap_ent(int id1, int id2)
3191 struct entry _dent, *pdent1 = &pdents[id1], *pdent2 = &pdents[id2];
3193 *(&_dent) = *pdent1;
3195 *pdent2 = *(&_dent);
3199 static int fill(const char *fltr, pcre *pcrex)
3201 static int fill(const char *fltr, regex_t *re)
3205 fltrexp_t fltrexp = { .pcrex = pcrex, .str = fltr };
3207 fltrexp_t fltrexp = { .regex = re, .str = fltr };
3210 for (int count = 0; count < ndents; ++count) {
3211 if (filterfn(&fltrexp, pdents[count].name) == 0) {
3212 if (count != --ndents) {
3213 swap_ent(count, ndents);
3224 static int matches(const char *fltr)
3230 if (cfg.regex && setfilter(&pcrex, fltr))
3233 ndents = fill(fltr, pcrex);
3241 if (cfg.regex && setfilter(&re, fltr))
3244 ndents = fill(fltr, &re);
3250 ENTSORT(pdents, ndents, entrycmpfn);
3256 * Return the position of the matching entry or 0 otherwise
3257 * Note there's no NULL check for fname
3259 static int dentfind(const char *fname, int n)
3261 for (int i = 0; i < n; ++i)
3262 if (xstrcmp(fname, pdents[i].name) == 0)
3268 static int filterentries(char *path, char *lastname)
3270 wchar_t *wln = (wchar_t *)alloca(sizeof(wchar_t) * REGEX_MAX);
3271 char *ln = g_ctx[cfg.curctx].c_fltr;
3273 int r, total = ndents, len;
3274 char *pln = g_ctx[cfg.curctx].c_fltr + 1;
3276 DPRINTF_S(__func__);
3278 if (ndents && (ln[0] == FILTER || ln[0] == RFILTER) && *pln) {
3279 if (matches(pln) != -1) {
3280 move_cursor(dentfind(lastname, ndents), 0);
3284 if (!cfg.filtermode) {
3289 len = mbstowcs(wln, ln, REGEX_MAX);
3291 ln[0] = wln[0] = cfg.regex ? RFILTER : FILTER;
3292 ln[1] = wln[1] = '\0';
3300 while ((r = get_wch(ch)) != ERR) {
3302 //DPRINTF_S(keyname(*ch));
3306 case 0: // fallthrough
3313 case KEY_DC: // fallthrough
3314 case KEY_BACKSPACE: // fallthrough
3315 case '\b': // fallthrough
3316 case DEL: /* handle DEL */
3319 wcstombs(ln, wln, REGEX_MAX);
3327 if (*ch == CONTROL('L')) {
3329 ln[REGEX_MAX - 1] = ln[1];
3330 ln[1] = wln[1] = '\0';
3333 } else if (ln[REGEX_MAX - 1]) { /* Show the previous filter */
3334 ln[1] = ln[REGEX_MAX - 1];
3335 ln[REGEX_MAX - 1] = '\0';
3336 len = mbstowcs(wln, ln, REGEX_MAX);
3341 /* Go to the top, we don't know if the hovered file will match the filter */
3344 if (matches(pln) != -1)
3354 if (handle_alt_key(ch) != ERR) {
3355 if (*ch == ESC) /* Handle Alt+Esc */
3356 *ch = 'q'; /* Quit context */
3359 *ch = ';'; /* Run plugin */
3365 if (r != OK) /* Handle Fn keys in main loop */
3368 /* Handle all control chars in main loop */
3369 if (*ch < ASCII_MAX && keyname(*ch)[0] == '^' && *ch != '^')
3373 if (*ch == '?') /* Help and config key, '?' is an invalid regex */
3376 if (cfg.filtermode) {
3378 case '\'': // fallthrough /* Go to first non-dir file */
3379 case '+': // fallthrough /* Toggle file selection */
3380 case ',': // fallthrough /* Mark CWD */
3381 case '-': // fallthrough /* Visit last visited dir */
3382 case '.': // fallthrough /* Show hidden files */
3383 case ';': // fallthrough /* Run plugin key */
3384 case '=': // fallthrough /* Launch app */
3385 case '>': // fallthrough /* Export file list */
3386 case '@': // fallthrough /* Visit start dir */
3387 case ']': // fallthorugh /* Prompt key */
3388 case '`': // fallthrough /* Visit / */
3389 case '~': /* Go HOME */
3394 /* Toggle case-sensitivity */
3396 fnstrstr = (fnstrstr == &strcasestr) ? &strstr : &strcasestr;
3398 pcreflags ^= PCRE_CASELESS;
3400 regflags ^= REG_ICASE;
3406 /* Toggle string or regex filter */
3407 if (*ch == FILTER) {
3408 ln[0] = (ln[0] == FILTER) ? RFILTER : FILTER;
3409 wln[0] = (uchar_t)ln[0];
3411 filterfn = cfg.regex ? &visible_re : &visible_str;
3416 /* Reset cur in case it's a repeat search */
3418 } else if (len == REGEX_MAX - 1)
3421 wln[len] = (wchar_t)*ch;
3423 wcstombs(ln, wln, REGEX_MAX);
3425 /* Forward-filtering optimization:
3426 * - new matches can only be a subset of current matches.
3428 /* ndents = total; */
3432 !r ? unget_wch(KEY_BACKSPACE) : showfilter(ln);
3434 if (matches(pln) == -1) {
3440 /* If the only match is a dir, auto-enter and cd into it */
3441 if (ndents == 1 && cfg.filtermode
3442 && cfg.autoenter && (pdents[0].flags & DIR_OR_DIRLNK)) {
3449 * redraw() should be above the auto-enter optimization, for
3450 * the case where there's an issue with dir auto-enter, say,
3451 * due to a permission problem. The transition is _jumpy_ in
3452 * case of such an error. However, we optimize for successful
3453 * cases where the dir has permissions. This skips a redraw().
3460 /* Save last working filter in-filter */
3462 ln[REGEX_MAX - 1] = ln[1];
3470 /* Return keys for navigation etc. */
3474 /* Show a prompt with input string and return the changes */
3475 static char *xreadline(const char *prefill, const char *prompt)
3479 const int WCHAR_T_WIDTH = sizeof(wchar_t);
3481 wchar_t * const buf = malloc(sizeof(wchar_t) * READLINE_MAX);
3491 len = pos = mbstowcs(buf, prefill, READLINE_MAX);
3495 if (len == (size_t)-1) {
3500 x = getcurx(stdscr);
3505 attron(COLOR_PAIR(cfg.curctx + 1));
3506 if (pos > (size_t)(xcols - x)) {
3507 mvaddnwstr(xlines - 1, x, buf + (pos - (xcols - x) + 1), xcols - x);
3508 move(xlines - 1, xcols - 1);
3510 mvaddnwstr(xlines - 1, x, buf, len + 1);
3511 move(xlines - 1, x + wcswidth(buf, pos));
3513 attroff(COLOR_PAIR(cfg.curctx + 1));
3521 case KEY_ENTER: // fallthrough
3522 case '\n': // fallthrough
3528 else if (!(pos || len)) { /* Exit on ^D at empty prompt */
3534 case DEL: // fallthrough
3535 case '\b': /* rhel25 sends '\b' for backspace */
3537 memmove(buf + pos - 1, buf + pos,
3538 (len - pos) * WCHAR_T_WIDTH);
3543 if (!(len || pos) && ndents)
3544 len = pos = mbstowcs(buf, pdents[cur].name, READLINE_MAX);
3559 memmove(buf + pos - 1, buf + pos,
3560 (len - pos) * WCHAR_T_WIDTH);
3562 } while (buf[pos - 1] != ' ' && buf[pos - 1] != '/'); // NOLINT
3580 memmove(buf, buf + pos, (len - pos) * WCHAR_T_WIDTH);
3584 case ESC: /* Exit prompt on Esc, but just filter out Alt+key */
3585 if (handle_alt_key(ch) != ERR)
3592 /* Filter out all other control chars */
3593 if (*ch < ASCII_MAX && keyname(*ch)[0] == '^')
3596 if (pos < READLINE_MAX - 1) {
3597 memmove(buf + pos + 1, buf + pos,
3598 (len - pos) * WCHAR_T_WIDTH);
3622 memmove(buf + pos - 1, buf + pos,
3623 (len - pos) * WCHAR_T_WIDTH);
3629 memmove(buf + pos, buf + pos + 1,
3630 (len - pos - 1) * WCHAR_T_WIDTH);
3640 case KEY_UP: // fallthrough
3642 if (prompt && lastcmd && (xstrcmp(prompt, PROMPT) == 0)) {
3644 len = pos = mbstowcs(buf, lastcmd, READLINE_MAX); // fallthrough
3659 pos = wcstombs(g_buf, buf, READLINE_MAX - 1);
3660 if (pos >= READLINE_MAX - 1)
3661 g_buf[READLINE_MAX - 1] = '\0';
3669 * Caller should check the value of presel to confirm if it needs to wait to show warning
3671 static char *getreadline(const char *prompt)
3675 char *input = readline(prompt);
3679 if (input && input[0]) {
3681 xstrsncpy(g_buf, input, CMD_LEN_MAX);
3692 * Create symbolic/hard link(s) to file(s) in selection list
3693 * Returns the number of links created, -1 on error
3695 static int xlink(char *prefix, char *path, char *curfname, char *buf, int *presel, int type)
3697 int count = 0, choice;
3698 char *psel = pselbuf, *fname;
3699 size_t pos = 0, len, r;
3700 int (*link_fn)(const char *, const char *) = NULL;
3701 char lnpath[PATH_MAX];
3703 choice = get_cur_or_sel();
3707 if (type == 's') /* symbolic link */
3709 else /* hard link */
3712 if (choice == 'c' || (nselected == 1)) {
3713 mkpath(path, prefix, lnpath); /* Generate link path */
3714 mkpath(path, (choice == 'c') ? curfname : pselbuf, buf); /* Generate target file path */
3716 if (!link_fn(buf, lnpath)) {
3719 return 1; /* One link created */
3726 while (pos < selbufpos) {
3727 len = xstrlen(psel);
3728 fname = xbasename(psel);
3730 r = xstrsncpy(buf, prefix, NAME_MAX + 1); /* Copy prefix */
3731 xstrsncpy(buf + r - 1, fname, NAME_MAX - r); /* Suffix target file name */
3732 mkpath(path, buf, lnpath); /* Generate link path */
3734 if (!link_fn(psel, lnpath))
3745 static bool parsekvpair(kv **arr, char **envcpy, const uchar_t id, uchar_t *items)
3748 const uchar_t INCR = 8;
3751 char *ptr = getenv(env_cfg[id]);
3756 *envcpy = xstrdup(ptr);
3764 while (*ptr && i < 100) {
3766 if (!(i & (INCR - 1))) {
3767 kvarr = xrealloc(kvarr, sizeof(kv) * (i + INCR));
3773 memset(kvarr + i, 0, sizeof(kv) * INCR);
3775 kvarr[i].key = (uchar_t)*ptr;
3776 if (*++ptr != ':' || *++ptr == '\0' || *ptr == ';')
3778 kvarr[i].off = ptr - *envcpy;
3797 * Get the value corresponding to a key
3799 * NULL is returned in case of no match, path resolution failure etc.
3800 * buf would be modified, so check return value before access
3802 static char *get_kv_val(kv *kvarr, char *buf, int key, uchar_t max, uchar_t id)
3809 for (int r = 0; r < max && kvarr[r].key; ++r) {
3810 if (kvarr[r].key == key) {
3811 /* Do not allocate new memory for plugin */
3813 return pluginstr + kvarr[r].off;
3815 val = bmstr + kvarr[r].off;
3816 convert_tilde(val, g_buf);
3817 return abspath(((val[0] == '~') ? g_buf : val), NULL, buf);
3821 DPRINTF_S("Invalid key");
3825 static int get_kv_key(kv *kvarr, char *val, uchar_t max, uchar_t id)
3830 if (id != NNN_ORDER) /* For now this function supports only order string */
3833 for (int r = 0; r < max && kvarr[r].key; ++r) {
3834 if (xstrcmp((orderstr + kvarr[r].off), val) == 0)
3835 return kvarr[r].key;
3841 static void resetdircolor(int flags)
3843 /* Directories are always shown on top, clear the color when moving to first file */
3844 if (g_state.dircolor && !(flags & DIR_OR_DIRLNK)) {
3845 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
3846 g_state.dircolor = 0;
3851 * Replace escape characters in a string with '?'
3852 * Adjust string length to maxcols if > 0;
3853 * Max supported str length: NAME_MAX;
3856 static char *unescape(const char *str, uint_t maxcols)
3858 char * const wbuf = g_buf;
3861 xstrsncpy(wbuf, str, maxcols);
3863 static wchar_t *unescape(const char *str, uint_t maxcols)
3865 wchar_t * const wbuf = (wchar_t *)g_buf;
3866 wchar_t *buf = wbuf;
3867 size_t len = mbstowcs(wbuf, str, maxcols); /* Convert multi-byte to wide char */
3869 len = wcswidth(wbuf, len);
3871 if (len >= maxcols) {
3872 size_t lencount = maxcols;
3874 while (len > maxcols) /* Reduce wide chars one by one till it fits */
3875 len = wcswidth(wbuf, --lencount);
3877 wbuf[lencount] = L'\0';
3882 if (*buf <= '\x1f' || *buf == '\x7f')
3891 static off_t get_size(off_t size, off_t *pval, int comp)
3894 off_t quo = rem / 10;
3896 if ((rem - (quo * 10)) >= 5) {
3909 static char *coolsize(off_t size)
3911 const char * const U = "BKMGTPEZY";
3912 static char size_buf[12]; /* Buffer to hold human readable size */
3917 while (size >= 1024) {
3918 rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
3924 rem = (rem * 1000) >> 10;
3926 size = get_size(size, &rem, 10);
3927 } else if (i == 2) {
3928 rem = (rem * 1000) >> 10;
3929 size = get_size(size, &rem, 100);
3931 rem = (rem * 10000) >> 10;
3932 size = get_size(size, &rem, 1000);
3935 if (i > 0 && i < 6 && rem) {
3936 ret = xstrsncpy(size_buf, xitoa(size), 12);
3937 size_buf[ret - 1] = '.';
3939 char *frac = xitoa(rem);
3940 size_t toprint = i > 3 ? 3 : i;
3941 size_t len = xstrlen(frac);
3943 if (len < toprint) {
3944 size_buf[ret] = size_buf[ret + 1] = size_buf[ret + 2] = '0';
3945 xstrsncpy(size_buf + ret + (toprint - len), frac, len + 1);
3947 xstrsncpy(size_buf + ret, frac, toprint + 1);
3951 ret = xstrsncpy(size_buf, size ? xitoa(size) : "0", 12);
3955 size_buf[ret] = U[i];
3956 size_buf[ret + 1] = '\0';
3961 /* Convert a mode field into "ls -l" type perms field. */
3962 static char *get_lsperms(mode_t mode)
3964 static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
3965 static char bits[11] = {'\0'};
3967 switch (mode & S_IFMT) {
3994 xstrsncpy(&bits[1], rwx[(mode >> 6) & 7], 4);
3995 xstrsncpy(&bits[4], rwx[(mode >> 3) & 7], 4);
3996 xstrsncpy(&bits[7], rwx[(mode & 7)], 4);
3999 bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
4001 bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
4003 bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
4008 #ifdef ICONS_ENABLED
4009 static const struct icon_pair *get_icon(const struct entry *ent)
4013 for (; i < ELEMENTS(icons_name); ++i)
4014 if (strcasecmp(ent->name, icons_name[i].match) == 0)
4015 return &icons_name[i];
4017 if (ent->flags & DIR_OR_DIRLNK)
4020 char *tmp = xextension(ent->name, ent->nlen);
4023 if (ent->mode & 0100)
4032 if (*tmp >= '0' && *tmp <= '9')
4033 i = *tmp - '0'; /* NUMBER 0-9 */
4034 else if (TOUPPER(*tmp) >= 'A' && TOUPPER(*tmp) <= 'Z')
4035 i = TOUPPER(*tmp) - 'A' + 10; /* LETTER A-Z */
4039 for (ushort_t j = icon_positions[i]; j < ELEMENTS(icons_ext) &&
4040 icons_ext[j].match[0] == icons_ext[icon_positions[i]].match[0]; ++j)
4041 if (strcasecmp(tmp, icons_ext[j].match) == 0)
4042 return &icons_ext[j];
4044 /* If there's no match and the file is executable, icon that */
4045 if (ent->mode & 0100)
4051 static void print_icon(const struct entry *ent, const int attrs)
4053 const struct icon_pair *picon = get_icon(ent);
4055 addstr(ICON_PADDING_LEFT);
4057 attron(COLOR_PAIR(C_UND + 1 + picon->color));
4060 addstr(picon->icon);
4062 attroff(COLOR_PAIR(C_UND + 1 + picon->color));
4065 addstr(ICON_PADDING_RIGHT);
4069 static void print_time(const time_t *timep, const uchar_t flags)
4073 /* Highlight timestamp for entries 5 minutes young */
4074 if (flags & FILE_YOUNG)
4077 localtime_r(timep, &t);
4078 printw("%s-%02d-%02d %02d:%02d",
4079 xitoa(t.tm_year + 1900), t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min);
4081 if (flags & FILE_YOUNG)
4085 static char get_detail_ind(const mode_t mode)
4087 switch (mode & S_IFMT) {
4088 case S_IFDIR: // fallthrough
4089 case S_IFREG: return ' ';
4090 case S_IFLNK: return '@';
4091 case S_IFSOCK: return '=';
4092 case S_IFIFO: return '|';
4093 case S_IFBLK: return 'b';
4094 case S_IFCHR: return 'c';
4099 /* Note: attribute and indicator values must be initialized to 0 */
4100 static uchar_t get_color_pair_name_ind(const struct entry *ent, char *pind, int *pattr)
4102 switch (ent->mode & S_IFMT) {
4105 if (ent->mode & 0100)
4109 if (ent->flags & HARD_LINK) {
4110 if (ent->mode & 0100)
4114 if (ent->mode & 0100) {
4121 if (g_state.oldcolor)
4124 return g_state.dirctx ? cfg.curctx + 1 : C_DIR;
4126 if (ent->flags & DIR_OR_DIRLNK) {
4128 *pattr |= g_state.oldcolor ? A_DIM : A_BOLD;
4131 if (g_state.oldcolor)
4134 if (!g_state.oldcolor || cfg.showdetail)
4135 return (ent->flags & SYM_ORPHAN) ? C_ORP : C_LNK;
4153 static void printent(const struct entry *ent, uint_t namecols, bool sel)
4158 if (cfg.showdetail) {
4159 int type = ent->mode & S_IFMT;
4160 char perms[6] = {' ', ' ', (char)('0' + ((ent->mode >> 6) & 7)),
4161 (char)('0' + ((ent->mode >> 3) & 7)),
4162 (char)('0' + (ent->mode & 7)), '\0'};
4165 attrs = g_state.oldcolor ? (resetdircolor(ent->flags), A_DIM)
4166 : (fcolors[C_MIS] ? COLOR_PAIR(C_MIS) : 0);
4171 print_time(&ent->sec, ent->flags);
4173 printw("%s%9s ", perms, (type == S_IFREG || type == S_IFDIR)
4174 ? coolsize(cfg.blkorder ? (blkcnt_t)ent->blocks << blk_shift : ent->size)
4175 : (type = (uchar_t)get_detail_ind(ent->mode), (char *)&type));
4183 uchar_t color_pair = get_color_pair_name_ind(ent, &ind, &attrs);
4185 addch((ent->flags & FILE_SELECTED) ? '+' | A_REVERSE | A_BOLD : ' ');
4187 if (g_state.oldcolor)
4188 resetdircolor(ent->flags);
4190 if (ent->flags & FILE_MISSING)
4192 if (color_pair && fcolors[color_pair])
4193 attrs |= COLOR_PAIR(color_pair);
4194 #ifdef ICONS_ENABLED
4195 print_icon(ent, attrs);
4207 addwstr(unescape(ent->name, namecols));
4209 addstr(unescape(ent->name, MIN(namecols, ent->nlen) + 1));
4218 static void savecurctx(char *path, char *curname, int nextctx)
4220 settings tmpcfg = cfg;
4221 context *ctxr = &g_ctx[nextctx];
4223 /* Save current context */
4225 xstrsncpy(g_ctx[tmpcfg.curctx].c_name, curname, NAME_MAX + 1);
4227 g_ctx[tmpcfg.curctx].c_name[0] = '\0';
4229 g_ctx[tmpcfg.curctx].c_cfg = tmpcfg;
4231 if (ctxr->c_cfg.ctxactive) { /* Switch to saved context */
4232 tmpcfg = ctxr->c_cfg;
4233 /* Skip ordering an open context */
4235 cfgsort[CTX_MAX] = cfgsort[nextctx];
4236 cfgsort[nextctx] = '0';
4238 } else { /* Set up a new context from current context */
4239 ctxr->c_cfg.ctxactive = 1;
4240 xstrsncpy(ctxr->c_path, path, PATH_MAX);
4241 ctxr->c_last[0] = ctxr->c_name[0] = ctxr->c_fltr[0] = ctxr->c_fltr[1] = '\0';
4242 ctxr->c_cfg = tmpcfg;
4243 /* If already in an ordered dir, clear ordering for the new context and let it order */
4244 if (cfgsort[cfg.curctx] == 'z')
4245 cfgsort[nextctx] = 'z';
4248 tmpcfg.curctx = nextctx;
4253 static void save_session(const char *sname, int *presel)
4256 session_header_t header;
4257 bool status = FALSE;
4258 char ssnpath[PATH_MAX];
4259 char spath[PATH_MAX];
4261 memset(&header, 0, sizeof(session_header_t));
4263 header.ver = SESSIONS_VERSION;
4265 for (i = 0; i < CTX_MAX; ++i) {
4266 if (g_ctx[i].c_cfg.ctxactive) {
4267 if (cfg.curctx == i && ndents)
4268 /* Update current file name, arrows don't update it */
4269 xstrsncpy(g_ctx[i].c_name, pdents[cur].name, NAME_MAX + 1);
4270 header.pathln[i] = strnlen(g_ctx[i].c_path, PATH_MAX) + 1;
4271 header.lastln[i] = strnlen(g_ctx[i].c_last, PATH_MAX) + 1;
4272 header.nameln[i] = strnlen(g_ctx[i].c_name, NAME_MAX) + 1;
4273 header.fltrln[i] = REGEX_MAX;
4277 mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4278 mkpath(ssnpath, sname, spath);
4280 fd = open(spath, O_CREAT | O_WRONLY | O_TRUNC, 0666);
4282 printwait(messages[MSG_SEL_MISSING], presel);
4286 if ((write(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4287 || (write(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4290 for (i = 0; i < CTX_MAX; ++i)
4291 if ((write(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4292 || (write(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4293 || (header.nameln[i] > 0
4294 && write(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4295 || (header.lastln[i] > 0
4296 && write(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4297 || (header.fltrln[i] > 0
4298 && write(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4299 || (header.pathln[i] > 0
4300 && write(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4309 printwait(messages[MSG_FAILED], presel);
4312 static bool load_session(const char *sname, char **path, char **lastdir, char **lastname, bool restore)
4315 session_header_t header;
4316 bool has_loaded_dynamically = !(sname || restore);
4317 bool status = (sname && g_state.picker); /* Picker mode with session program option */
4318 char ssnpath[PATH_MAX];
4319 char spath[PATH_MAX];
4321 mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4324 sname = sname ? sname : xreadline(NULL, messages[MSG_SSN_NAME]);
4328 mkpath(ssnpath, sname, spath);
4330 /* If user is explicitly loading the "last session", skip auto-save */
4331 if ((sname[0] == '@') && !sname[1])
4332 has_loaded_dynamically = FALSE;
4334 mkpath(ssnpath, "@", spath);
4336 if (has_loaded_dynamically)
4337 save_session("@", NULL);
4339 fd = open(spath, O_RDONLY, 0666);
4342 printmsg(messages[MSG_SEL_MISSING]);
4343 xdelay(XDELAY_INTERVAL_MS);
4350 if ((read(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4351 || (header.ver != SESSIONS_VERSION)
4352 || (read(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4355 g_ctx[cfg.curctx].c_name[0] = g_ctx[cfg.curctx].c_last[0]
4356 = g_ctx[cfg.curctx].c_fltr[0] = g_ctx[cfg.curctx].c_fltr[1] = '\0';
4358 for (; i < CTX_MAX; ++i)
4359 if ((read(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4360 || (read(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4361 || (header.nameln[i] > 0
4362 && read(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4363 || (header.lastln[i] > 0
4364 && read(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4365 || (header.fltrln[i] > 0
4366 && read(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4367 || (header.pathln[i] > 0
4368 && read(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4371 *path = g_ctx[cfg.curctx].c_path;
4372 *lastdir = g_ctx[cfg.curctx].c_last;
4373 *lastname = g_ctx[cfg.curctx].c_name;
4374 set_sort_flags('\0'); /* Set correct sort options */
4381 printmsg(messages[MSG_FAILED]);
4382 xdelay(XDELAY_INTERVAL_MS);
4390 static uchar_t get_free_ctx(void)
4392 uchar_t r = cfg.curctx;
4395 r = (r + 1) & ~CTX_MAX;
4396 while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
4401 /* ctx is absolute: 1 to 4, + for smart context */
4402 static void set_smart_ctx(int ctx, char *nextpath, char **path, char *file, char **lastname, char **lastdir)
4404 if (ctx == '+') /* Get smart context */
4405 ctx = (int)(get_free_ctx() + 1);
4407 if (ctx == 0 || ctx == cfg.curctx + 1) { /* Same context */
4408 xstrsncpy(*lastdir, *path, PATH_MAX);
4409 xstrsncpy(*path, nextpath, PATH_MAX);
4410 } else { /* New context */
4412 /* Deactivate the new context and build from scratch */
4413 g_ctx[ctx].c_cfg.ctxactive = 0;
4414 DPRINTF_S(nextpath);
4415 savecurctx(nextpath, file, ctx);
4416 *path = g_ctx[ctx].c_path;
4417 *lastdir = g_ctx[ctx].c_last;
4418 *lastname = g_ctx[ctx].c_name;
4423 * Gets only a single line (that's what we need for now) or shows full command output in pager.
4424 * Uses g_buf internally.
4426 static bool get_output(char *file, char *arg1, char *arg2, int fdout, bool multi, bool page)
4430 int index = 0, flags;
4432 bool tmpfile = ((fdout == -1) && page);
4433 char *argv[EXEC_ARGS_MAX] = {0};
4439 fdout = create_tmp_file();
4445 cmd = parseargs(file, argv, &index);
4449 argv[index++] = file;
4452 argv[++index] = arg2;
4454 if (pipe(pipefd) == -1) {
4459 for (index = 0; index < 2; ++index) {
4460 /* Get previous flags */
4461 flags = fcntl(pipefd[index], F_GETFL, 0);
4463 /* Set bit for non-blocking flag */
4464 flags |= O_NONBLOCK;
4466 /* Change flags on fd */
4467 fcntl(pipefd[index], F_SETFL, flags);
4474 dup2(pipefd[1], STDOUT_FILENO);
4475 dup2(pipefd[1], STDERR_FILENO);
4477 execvp(*argv, argv);
4478 _exit(EXIT_SUCCESS);
4482 waitpid(pid, NULL, 0);
4486 while ((len = read(pipefd[0], g_buf, CMD_LEN_MAX - 1)) > 0) {
4488 if (fdout == -1) /* Read only the first line of output to buffer */
4490 if (write(fdout, g_buf, len) != len)
4503 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4512 * Follows the stat(1) output closely
4514 static bool show_stats(char *fpath)
4516 static char * const cmds[] = {
4517 #ifdef FILE_MIME_OPTS
4518 ("file " FILE_MIME_OPTS),
4524 size_t r = ELEMENTS(cmds);
4525 int fd = create_tmp_file();
4530 get_output(cmds[--r], fpath, NULL, fd, TRUE, FALSE);
4534 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4539 static bool xchmod(const char *fpath, mode_t mode)
4541 /* (Un)set (S_IXUSR | S_IXGRP | S_IXOTH) */
4542 (0100 & mode) ? (mode &= ~0111) : (mode |= 0111);
4544 return (chmod(fpath, mode) == 0);
4547 static size_t get_fs_info(const char *path, bool type)
4551 if (statvfs(path, &svb) == -1)
4554 if (type == CAPACITY)
4555 return (size_t)svb.f_blocks << ffs((int)(svb.f_frsize >> 1));
4557 return (size_t)svb.f_bavail << ffs((int)(svb.f_frsize >> 1));
4560 /* Create non-existent parents and a file or dir */
4561 static bool xmktree(char *path, bool dir)
4569 /* Skip the first '/' */
4572 while (*p != '\0') {
4581 /* Create folder from path to '\0' inserted at p */
4582 if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4584 // XDG_CONFIG_HOME contains a directory
4585 // that is read-only, but the full path
4587 // Try to continue and see what happens.
4588 // TODO: Find a more robust solution.
4589 if (errno == B_READ_ONLY_DEVICE)
4592 DPRINTF_S("mkdir1!");
4593 DPRINTF_S(strerror(errno));
4607 if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4608 DPRINTF_S("mkdir2!");
4609 DPRINTF_S(strerror(errno));
4613 int fd = open(path, O_CREAT, 0666);
4615 if (fd == -1 && errno != EEXIST) {
4617 DPRINTF_S(strerror(errno));
4627 /* List or extract archive */
4628 static bool handle_archive(char *fpath /* in-out param */, char op)
4630 char arg[] = "-tvf"; /* options for tar/bsdtar to list files */
4631 char *util, *outdir = NULL;
4633 bool is_atool = getutil(utils[UTIL_ATOOL]);
4636 outdir = xreadline(is_atool ? "." : xbasename(fpath), messages[MSG_NEW_PATH]);
4637 if (!outdir || !*outdir) { /* Cancelled */
4638 printwait(messages[MSG_CANCEL], NULL);
4641 /* Do not create smart context for current dir */
4642 if (!(*outdir == '.' && outdir[1] == '\0')) {
4643 if (!xmktree(outdir, TRUE) || (chdir(outdir) == -1)) {
4647 /* Copy the new dir path to open it in smart context */
4648 outdir = getcwd(NULL, 0);
4654 util = utils[UTIL_ATOOL];
4657 } else if (getutil(utils[UTIL_BSDTAR])) {
4658 util = utils[UTIL_BSDTAR];
4661 } else if (is_suffix(fpath, ".zip")) {
4662 util = utils[UTIL_UNZIP];
4663 arg[1] = (op == 'l') ? 'v' /* verbose listing */ : '\0';
4666 util = utils[UTIL_TAR];
4671 if (op == 'x') /* extract */
4672 spawn(util, arg, fpath, NULL, F_NORMAL | F_MULTI);
4674 get_output(util, arg, fpath, -1, TRUE, TRUE);
4677 if (chdir(xdirname(fpath)) == -1) {
4682 xstrsncpy(fpath, outdir, PATH_MAX);
4684 } else if (op == 'x')
4690 static char *visit_parent(char *path, char *newpath, int *presel)
4694 /* There is no going back */
4695 if (istopdir(path)) {
4696 /* Continue in type-to-nav mode, if enabled */
4697 if (cfg.filtermode && presel)
4702 /* Use a copy as xdirname() may change the string passed */
4704 xstrsncpy(newpath, path, PATH_MAX);
4708 dir = xdirname(newpath);
4709 if (chdir(dir) == -1) {
4717 static void valid_parent(char *path, char *lastname)
4720 xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
4722 while (!istopdir(path))
4723 if (visit_parent(path, NULL, NULL))
4727 xdelay(XDELAY_INTERVAL_MS);
4730 static bool archive_mount(char *newpath)
4732 char *str = "install archivemount";
4733 char *dir, *cmd = str + 8; /* Start of "archivemount" */
4734 char *name = pdents[cur].name;
4735 size_t len = pdents[cur].nlen;
4736 char mntpath[PATH_MAX];
4738 if (!getutil(cmd)) {
4743 dir = xstrdup(name);
4745 printmsg(messages[MSG_FAILED]);
4750 if (dir[--len] == '.') {
4757 /* Create the mount point */
4758 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4759 mkpath(mntpath, dir, newpath);
4762 if (!xmktree(newpath, TRUE)) {
4770 if (spawn(cmd, name, newpath, NULL, F_NORMAL)) {
4771 printmsg(messages[MSG_FAILED]);
4778 static bool remote_mount(char *newpath)
4780 uchar_t flag = F_CLI;
4783 bool r = getutil(utils[UTIL_RCLONE]), s = getutil(utils[UTIL_SSHFS]);
4784 char mntpath[PATH_MAX];
4787 printmsg("install sshfs/rclone");
4792 opt = get_input(messages[MSG_REMOTE_OPTS]);
4794 opt = (!s) ? 'r' : 's';
4797 env = xgetenv("NNN_SSHFS", utils[UTIL_SSHFS]);
4798 else if (opt == 'r') {
4799 flag |= F_NOWAIT | F_NOTRACE;
4800 env = xgetenv("NNN_RCLONE", "rclone mount");
4802 printmsg(messages[MSG_INVALID_KEY]);
4806 tmp = xreadline(NULL, "host[:dir] > ");
4808 printmsg(messages[MSG_CANCEL]);
4812 char *div = strchr(tmp, ':');
4817 /* Create the mount point */
4818 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4819 mkpath(mntpath, tmp, newpath);
4820 if (!xmktree(newpath, TRUE)) {
4825 if (!div) { /* Convert "host" to "host:" */
4826 size_t len = xstrlen(tmp);
4829 tmp[len + 1] = '\0';
4833 /* Connect to remote */
4835 if (spawn(env, tmp, newpath, NULL, flag)) {
4836 printmsg(messages[MSG_FAILED]);
4840 spawn(env, tmp, newpath, NULL, flag);
4841 printmsg(messages[MSG_RCLONE_DELAY]);
4842 xdelay(XDELAY_INTERVAL_MS << 2); /* Set 4 times the usual delay */
4849 * Unmounts if the directory represented by name is a mount point.
4850 * Otherwise, asks for hostname
4851 * Returns TRUE if directory needs to be refreshed *.
4853 static bool unmount(char *name, char *newpath, int *presel, char *currentpath)
4855 #if defined(__APPLE__) || defined(__FreeBSD__)
4856 static char cmd[] = "umount";
4858 static char cmd[] = "fusermount3"; /* Arch Linux utility */
4859 static bool found = FALSE;
4862 struct stat sb, psb;
4864 bool parent = FALSE;
4865 bool hovered = FALSE;
4866 char mntpath[PATH_MAX];
4868 #if !defined(__APPLE__) && !defined(__FreeBSD__)
4869 /* On Ubuntu it's fusermount */
4870 if (!found && !getutil(cmd)) {
4876 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4878 if (tmp && strcmp(mntpath, currentpath) == 0) {
4879 mkpath(mntpath, tmp, newpath);
4880 child = lstat(newpath, &sb) != -1;
4881 parent = lstat(xdirname(newpath), &psb) != -1;
4882 if (!child && !parent) {
4888 if (!tmp || !child || !S_ISDIR(sb.st_mode) || (child && parent && sb.st_dev == psb.st_dev)) {
4889 tmp = xreadline(NULL, messages[MSG_HOSTNAME]);
4892 if (name && (tmp[0] == '-') && (tmp[1] == '\0')) {
4893 mkpath(currentpath, name, newpath);
4899 mkpath(mntpath, tmp, newpath);
4901 if (!xdiraccess(newpath)) {
4906 #if defined(__APPLE__) || defined(__FreeBSD__)
4907 if (spawn(cmd, newpath, NULL, NULL, F_NORMAL)) {
4909 if (spawn(cmd, "-qu", newpath, NULL, F_NORMAL)) {
4911 if (!xconfirm(get_input(messages[MSG_LAZY])))
4915 if (spawn(cmd, "-l", newpath, NULL, F_NORMAL)) {
4916 #elif defined(__FreeBSD__)
4917 if (spawn(cmd, "-f", newpath, NULL, F_NORMAL)) {
4919 if (spawn(cmd, "-quz", newpath, NULL, F_NORMAL)) {
4921 printwait(messages[MSG_FAILED], presel);
4926 if (rmdir(newpath) == -1) {
4934 static void lock_terminal(void)
4936 spawn(xgetenv("NNN_LOCKER", utils[UTIL_LOCKER]), NULL, NULL, NULL, F_CLI);
4939 static void printkv(kv *kvarr, int fd, uchar_t max, uchar_t id)
4941 char *val = (id == NNN_BMS) ? bmstr : pluginstr;
4943 for (uchar_t i = 0; i < max && kvarr[i].key; ++i)
4944 dprintf(fd, " %c: %s\n", (char)kvarr[i].key, val + kvarr[i].off);
4947 static void printkeys(kv *kvarr, char *buf, uchar_t max)
4951 for (; i < max && kvarr[i].key; ++i) {
4953 buf[(i << 1) + 1] = kvarr[i].key;
4959 static size_t handle_bookmark(const char *bmark, char *newpath)
4964 if (maxbm || bmark) {
4965 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
4967 if (bmark) { /* There is a marked directory */
4973 printkeys(bookmark, g_buf + r - 1, maxbm);
4975 fd = get_input(NULL);
4979 if (fd == ',') /* Visit marked directory */
4980 bmark ? xstrsncpy(newpath, bmark, PATH_MAX) : (r = MSG_NOT_SET);
4981 else if (fd == '\r') /* Visit bookmarks directory */
4982 mkpath(cfgpath, toks[TOK_BM], newpath);
4983 else if (!get_kv_val(bookmark, newpath, fd, maxbm, NNN_BMS))
4984 r = MSG_INVALID_KEY;
4986 if (!r && chdir(newpath) == -1)
4992 static void add_bookmark(char *path, char *newpath, int *presel)
4994 char *dir = xbasename(path);
4996 dir = xreadline(dir[0] ? dir : NULL, "name: ");
4998 size_t r = mkpath(cfgpath, toks[TOK_BM], newpath);
5000 newpath[r - 1] = '/';
5001 xstrsncpy(newpath + r, dir, PATH_MAX - r);
5002 printwait((symlink(path, newpath) == -1) ? strerror(errno) : newpath, presel);
5004 printwait(messages[MSG_CANCEL], presel);
5008 * The help string tokens (each line) start with a HEX value
5009 * which indicates the number of spaces to print before the
5010 * particular token. This method was chosen instead of a flat
5011 * string because the number of bytes in help was increasing
5012 * the binary size by around a hundred bytes. This would only
5013 * have increased as we keep adding new options.
5015 static void show_help(const char *path)
5017 const char *start, *end;
5018 const char helpstr[] = {
5021 "9Up k Up%-16cPgUp ^U Page up\n"
5022 "9Dn j Down%-14cPgDn ^D Page down\n"
5023 "9Lt h Parent%-12c~ ` @ - ~, /, start, prev\n"
5024 "5Ret Rt l Open%-20c' First file/match\n"
5025 "9g ^A Top%-21c. Toggle hidden\n"
5026 "9G ^E End%-20c^J Toggle auto-jump on open\n"
5027 "8B (,) Book(mark)%-11cb ^/ Select bookmark\n"
5028 "a1-4 Context%-11c(Sh)Tab Cycle/new context\n"
5029 "62Esc ^Q Quit%-20cq Quit context\n"
5030 "b^G QuitCD%-18cQ Pick/err, quit\n"
5032 "1FILTER & PROMPT\n"
5033 "c/ Filter%-17c^N Toggle type-to-nav\n"
5034 "aEsc Exit prompt%-12c^L Toggle last filter\n"
5035 "d%-20cAlt+Esc Unfilter, quit context\n"
5038 "9o ^O Open with%-15cn Create new/link\n"
5039 "9f ^F File stats%-14cd Detail mode toggle\n"
5040 "b^R Rename/dup%-14cr Batch rename\n"
5041 "cz Archive%-17ce Edit file\n"
5042 "c* Toggle exe%-14c> Export list\n"
5043 "6Space + (Un)select%-12cm-m Select range/clear\n"
5044 "ca Select all%-14cA Invert sel\n"
5045 "9p ^P Copy here%-12cw ^W Cp/mv sel as\n"
5046 "9v ^V Move here%-15cE Edit sel list\n"
5047 "9x ^X Delete%-16cEsc Send to FIFO\n"
5050 "8Alt ; Select plugin%-11c= Launch app\n"
5051 "9! ^] Shell%-19c] Cmd prompt\n"
5052 "cc Connect remote%-10cu Unmount remote/archive\n"
5053 "9t ^T Sort toggles%-12cs Manage session\n"
5054 "cT Set time type%-11c0 Lock\n"
5055 "b^L Redraw%-18c? Help, conf\n"
5058 int fd = create_tmp_file();
5062 dprintf(fd, " |V\\_\n"
5068 char *prog = xgetenv(env_cfg[NNN_HELP], NULL);
5070 get_output(prog, NULL, NULL, fd, TRUE, FALSE);
5072 start = end = helpstr;
5075 snprintf(g_buf, CMD_LEN_MAX, "%*c%.*s",
5076 xchartohex(*start), ' ', (int)(end - start), start + 1);
5077 dprintf(fd, g_buf, ' ');
5084 dprintf(fd, "\nLOCATIONS:\n");
5085 for (uchar_t i = 0; i < CTX_MAX; ++i)
5086 if (g_ctx[i].c_cfg.ctxactive)
5087 dprintf(fd, " %u: %s\n", i + 1, g_ctx[i].c_path);
5089 dprintf(fd, "\nVOLUME: %s of ", coolsize(get_fs_info(path, FREE)));
5090 dprintf(fd, "%s free\n\n", coolsize(get_fs_info(path, CAPACITY)));
5093 dprintf(fd, "BOOKMARKS\n");
5094 printkv(bookmark, fd, maxbm, NNN_BMS);
5099 dprintf(fd, "PLUGIN KEYS\n");
5100 printkv(plug, fd, maxplug, NNN_PLUG);
5104 for (uchar_t i = NNN_OPENER; i <= NNN_TRASH; ++i) {
5105 start = getenv(env_cfg[i]);
5107 dprintf(fd, "%s: %s\n", env_cfg[i], start);
5111 dprintf(fd, "SELECTION FILE: %s\n", selpath);
5113 dprintf(fd, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
5116 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
5120 static void setexports(void)
5126 setenv(envs[ENV_NCUR], pdents[cur].name, 1);
5127 xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
5128 } else if (g_ctx[cfg.curctx].c_name[0])
5129 g_ctx[cfg.curctx].c_name[0] = '\0';
5131 for (uchar_t i = 0; i < CTX_MAX; ++i) {
5132 if (g_ctx[i].c_cfg.ctxactive) {
5133 dvar[1] = fvar[1] = '1' + i;
5134 setenv(dvar, g_ctx[i].c_path, 1);
5136 if (g_ctx[i].c_name[0]) {
5137 mkpath(g_ctx[i].c_path, g_ctx[i].c_name, g_buf);
5138 setenv(fvar, g_buf, 1);
5142 setenv("NNN_INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
5145 static bool run_cmd_as_plugin(const char *file, char *runfile, uchar_t flags)
5149 xstrsncpy(g_buf, file, PATH_MAX);
5151 len = xstrlen(g_buf);
5152 if (len > 1 && g_buf[len - 1] == '*') {
5153 flags &= ~F_CONFIRM; /* Skip user confirmation */
5154 g_buf[len - 1] = '\0'; /* Get rid of trailing no confirmation symbol */
5159 get_output(g_buf, NULL, NULL, -1, TRUE, TRUE);
5160 else if (flags & F_NOTRACE) {
5161 if (is_suffix(g_buf, " $nnn"))
5162 g_buf[len - 5] = '\0';
5165 spawn(g_buf, runfile, NULL, NULL, flags);
5167 spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, flags);
5172 static bool plctrl_init(void)
5176 /* g_tmpfpath is used to generate tmp file names */
5177 g_tmpfpath[tmpfplen - 1] = '\0';
5178 len = xstrsncpy(g_pipepath, g_tmpfpath, TMP_LEN_MAX);
5179 g_pipepath[len - 1] = '/';
5180 len = xstrsncpy(g_pipepath + len, "nnn-pipe.", TMP_LEN_MAX - len) + len;
5181 xstrsncpy(g_pipepath + len - 1, xitoa(getpid()), TMP_LEN_MAX - len);
5182 setenv(env_cfg[NNN_PIPE], g_pipepath, TRUE);
5184 return EXIT_SUCCESS;
5187 static void rmlistpath(void)
5190 DPRINTF_S(__func__);
5191 DPRINTF_S(listpath);
5192 spawn(utils[UTIL_RM_RF], listpath, NULL, NULL, F_NOTRACE | F_MULTI);
5193 /* Do not free if program was started in list mode */
5194 if (listpath != initpath)
5200 static ssize_t read_nointr(int fd, void *buf, size_t count)
5205 len = read(fd, buf, count);
5206 while (len == -1 && errno == EINTR);
5211 static char *readpipe(int fd, char *ctxnum, char **path)
5213 char ctx, *nextpath = NULL;
5215 if (read_nointr(fd, g_buf, 1) != 1)
5218 if (g_buf[0] == '-') { /* Clear selection on '-' */
5220 if (read_nointr(fd, g_buf, 1) != 1)
5224 if (g_buf[0] == '+')
5225 ctx = (char)(get_free_ctx() + 1);
5226 else if (g_buf[0] < '0')
5229 ctx = g_buf[0] - '0';
5234 if (read_nointr(fd, g_buf, 1) != 1)
5240 ssize_t len = read_nointr(fd, g_buf, PATH_MAX);
5245 g_buf[len] = '\0'; /* Terminate the path read */
5246 if (g_buf[0] == '/') {
5248 len = xstrlen(g_buf);
5249 while (--len && (g_buf[len] == '/')) /* Trim all trailing '/' */
5252 } else if (op == 'l') {
5253 rmlistpath(); /* Remove last list mode path, if any */
5254 nextpath = load_input(fd, *path);
5255 } else if (op == 'p') {
5268 static bool run_plugin(char **path, const char *file, char *runfile, char **lastname, char **lastdir)
5273 bool cmd_as_plugin = FALSE;
5276 if (!g_state.pluginit) {
5278 g_state.pluginit = 1;
5283 /* Check for run-cmd-as-plugin mode */
5285 flags = F_MULTI | F_CONFIRM;
5288 if (*file == '|') { /* Check if output should be paged */
5291 } else if (*file == '&') { /* Check if GUI flags are to be used */
5292 flags = F_NOTRACE | F_NOWAIT;
5299 if ((flags & F_NOTRACE) || (flags & F_PAGE))
5300 return run_cmd_as_plugin(file, runfile, flags);
5302 cmd_as_plugin = TRUE;
5305 if (mkfifo(g_pipepath, 0600) != 0)
5312 if (!p) { // In child
5313 int wfd = open(g_pipepath, O_WRONLY | O_CLOEXEC);
5316 _exit(EXIT_FAILURE);
5318 if (!cmd_as_plugin) {
5322 /* Generate absolute path to plugin */
5323 mkpath(plgpath, file, g_buf);
5326 sel = selpath ? selpath : std;
5328 if (runfile && runfile[0]) {
5329 xstrsncpy(*lastname, runfile, NAME_MAX);
5330 spawn(g_buf, *lastname, *path, sel, 0);
5332 spawn(g_buf, NULL, *path, sel, 0);
5334 run_cmd_as_plugin(file, NULL, flags);
5337 _exit(EXIT_SUCCESS);
5343 rfd = open(g_pipepath, O_RDONLY);
5344 while (rfd == -1 && errno == EINTR);
5346 nextpath = readpipe(rfd, &ctx, path);
5348 set_smart_ctx(ctx, nextpath, path, runfile, lastname, lastdir);
5352 /* wait for the child to finish. no zombies allowed */
5353 waitpid(p, NULL, 0);
5362 static bool launch_app(char *newpath)
5365 char *tmp = newpath;
5367 mkpath(plgpath, utils[UTIL_LAUNCH], newpath);
5369 if (!getutil(utils[UTIL_FZF]) || access(newpath, X_OK) < 0) {
5370 tmp = xreadline(NULL, messages[MSG_APP_NAME]);
5371 r = F_NOWAIT | F_NOTRACE | F_MULTI;
5374 if (tmp && *tmp) // NOLINT
5375 spawn(tmp, (r == F_NORMAL) ? "0" : NULL, NULL, NULL, r);
5380 /* Returns TRUE if at least one command was run */
5381 static bool prompt_run(void)
5384 char *cmdline, *next;
5385 int cnt_j, cnt_J, cmd_ret;
5388 const char *xargs_j = "xargs -0 -I{} %s < %s";
5389 const char *xargs_J = "xargs -0 %s < %s";
5390 char cmd[CMD_LEN_MAX + 32]; // 32 for xargs format strings
5394 if (g_state.picker) {
5396 cmdline = xreadline(NULL, PROMPT);
5399 cmdline = getreadline("\n"PROMPT);
5401 // Check for an empty command
5402 if (!cmdline || !cmdline[0])
5406 lastcmd = xstrdup(cmdline);
5409 len = xstrlen(cmdline);
5413 while ((next = strstr(next, "%j"))) {
5416 // replace %j with {} for xargs later
5425 while ((next = strstr(next, "%J"))) {
5428 // %J should be the last thing in the command
5429 if (next == cmdline + len - 2) {
5430 cmdline[len - 2] = '\0';
5436 // We can't handle both %j and %J in a single command
5441 snprintf(cmd, CMD_LEN_MAX + 32, xargs_j, cmdline, selpath);
5443 snprintf(cmd, CMD_LEN_MAX + 32, xargs_J, cmdline, selpath);
5445 cmd_ret = spawn(shell, "-c", (cnt_j || cnt_J) ? cmd : cmdline, NULL, F_CLI | F_CONFIRM);
5446 if ((cnt_j || cnt_J) && cmd_ret == 0)
5453 static bool handle_cmd(enum action sel, char *newpath)
5455 endselection(FALSE);
5457 if (sel == SEL_LAUNCH)
5458 return launch_app(newpath);
5462 if (sel == SEL_PROMPT)
5463 return prompt_run();
5465 /* Set nnn nesting level */
5466 char *tmp = getenv(env_cfg[NNNLVL]);
5467 int r = tmp ? atoi(tmp) : 0;
5469 setenv(env_cfg[NNNLVL], xitoa(r + 1), 1);
5470 spawn(shell, NULL, NULL, NULL, F_CLI);
5471 setenv(env_cfg[NNNLVL], xitoa(r), 1);
5475 static void dentfree(void)
5481 /* Thread data cleanup */
5487 static void *du_thread(void *p_data)
5489 thread_data *pdata = (thread_data *)p_data;
5490 char *path[2] = {pdata->path, NULL};
5491 ullong_t tfiles = 0;
5492 blkcnt_t tblocks = 0;
5494 FTS *tree = fts_open(path, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR, 0);
5497 while ((node = fts_read(tree))) {
5498 if (node->fts_info & FTS_D) {
5499 if (g_state.interrupt)
5504 sb = node->fts_statp;
5506 if (cfg.apparentsz) {
5507 if (sb->st_size && DU_TEST)
5508 tblocks += sb->st_size;
5509 } else if (sb->st_blocks && DU_TEST)
5510 tblocks += sb->st_blocks;
5517 if (pdata->entnum >= 0)
5518 pdents[pdata->entnum].blocks = tblocks;
5520 if (!pdata->mntpoint) {
5521 core_blocks[pdata->core] += tblocks;
5522 core_files[pdata->core] += tfiles;
5524 core_files[pdata->core] += 1;
5526 pthread_mutex_lock(&running_mutex);
5527 threadbmp |= (1 << pdata->core);
5529 pthread_mutex_unlock(&running_mutex);
5534 static void dirwalk(char *path, int entnum, bool mountpoint)
5536 /* Loop till any core is free */
5537 while (active_threads == NUM_DU_THREADS);
5539 if (g_state.interrupt)
5542 pthread_mutex_lock(&running_mutex);
5543 int core = ffs(threadbmp) - 1;
5545 threadbmp &= ~(1 << core);
5547 pthread_mutex_unlock(&running_mutex);
5549 xstrsncpy(core_data[core].path, path, PATH_MAX);
5550 core_data[core].entnum = entnum;
5551 core_data[core].core = (ushort_t)core;
5552 core_data[core].mntpoint = mountpoint;
5556 pthread_create(&tid, NULL, du_thread, (void *)&(core_data[core]));
5559 addstr(xbasename(path));
5560 addstr(" [^C aborts]\n");
5564 static void prep_threads(void)
5566 if (!g_state.duinit) {
5568 threadbmp >>= (32 - NUM_DU_THREADS);
5570 core_blocks = calloc(NUM_DU_THREADS, sizeof(blkcnt_t));
5571 core_data = calloc(NUM_DU_THREADS, sizeof(thread_data));
5572 core_files = calloc(NUM_DU_THREADS, sizeof(ullong_t));
5575 /* Increase current open file descriptor limit */
5578 g_state.duinit = TRUE;
5580 memset(core_blocks, 0, NUM_DU_THREADS * sizeof(blkcnt_t));
5581 memset(core_data, 0, NUM_DU_THREADS * sizeof(thread_data));
5582 memset(core_files, 0, NUM_DU_THREADS * sizeof(ullong_t));
5586 /* Skip self and parent */
5587 static bool selforparent(const char *path)
5589 return path[0] == '.' && (path[1] == '\0' || (path[1] == '.' && path[2] == '\0'));
5592 static int dentfill(char *path, struct entry **ppdents)
5594 uchar_t entflags = 0;
5597 char *namep, *pnb, *buf;
5598 struct entry *dentp;
5599 size_t off = 0, namebuflen = NAMEBUF_INCR;
5600 struct stat sb_path, sb;
5601 DIR *dirp = opendir(path);
5604 gtimesecs = time(NULL);
5606 DPRINTF_S(__func__);
5611 int fd = dirfd(dirp);
5618 if (fstatat(fd, path, &sb_path, 0) == -1)
5622 ihashbmp = calloc(1, HASH_OCTETS << 3);
5626 memset(ihashbmp, 0, HASH_OCTETS << 3);
5630 attron(COLOR_PAIR(cfg.curctx + 1));
5633 #if _POSIX_C_SOURCE >= 200112L
5634 posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
5641 #if defined(__sun) || defined(__HAIKU__)
5642 flags = AT_SYMLINK_NOFOLLOW; /* no d_type */
5644 if (cfg.blkorder || dp->d_type == DT_UNKNOWN) {
5646 * Optimization added for filesystems which support dirent.d_type
5649 * - the symlink size is set to 0
5650 * - the modification time of the symlink is set to that of the target file
5652 flags = AT_SYMLINK_NOFOLLOW;
5659 if (selforparent(namep))
5662 if (!cfg.showhidden && namep[0] == '.') {
5666 if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
5669 if (S_ISDIR(sb.st_mode)) {
5670 if (sb_path.st_dev == sb.st_dev) { // NOLINT
5671 mkpath(path, namep, buf); // NOLINT
5672 dirwalk(buf, -1, FALSE);
5674 if (g_state.interrupt)
5678 /* Do not recount hard links */
5679 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5680 dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5687 if (fstatat(fd, namep, &sb, flags) == -1) {
5688 if (flags || (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)) {
5693 DPRINTF_S(strerror(errno));
5696 entflags = FILE_MISSING;
5697 memset(&sb, 0, sizeof(struct stat));
5698 } else /* Orphaned symlink */
5699 entflags = SYM_ORPHAN;
5702 if (ndents == total_dents) {
5704 while (active_threads);
5706 total_dents += ENTRY_INCR;
5707 *ppdents = xrealloc(*ppdents, total_dents * sizeof(**ppdents));
5713 DPRINTF_P(*ppdents);
5716 /* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
5717 if (namebuflen - off < NAME_MAX + 1) {
5718 namebuflen += NAMEBUF_INCR;
5721 pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
5727 DPRINTF_P(pnamebuf);
5729 /* realloc() may result in memory move, we must re-adjust if that happens */
5730 if (pnb != pnamebuf) {
5732 dentp->name = pnamebuf;
5734 for (int count = 1; count < ndents; ++dentp, ++count)
5735 /* Current file name starts at last file name start + length */
5736 (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
5740 dentp = *ppdents + ndents;
5742 /* Selection file name */
5743 dentp->name = (char *)((size_t)pnamebuf + off);
5744 dentp->nlen = xstrsncpy(dentp->name, namep, NAME_MAX + 1);
5747 /* Copy other fields */
5748 if (cfg.timetype == T_MOD) {
5749 dentp->sec = sb.st_mtime;
5751 dentp->nsec = (uint_t)sb.st_mtimespec.tv_nsec;
5753 dentp->nsec = (uint_t)sb.st_mtim.tv_nsec;
5755 } else if (cfg.timetype == T_ACCESS) {
5756 dentp->sec = sb.st_atime;
5758 dentp->nsec = (uint_t)sb.st_atimespec.tv_nsec;
5760 dentp->nsec = (uint_t)sb.st_atim.tv_nsec;
5763 dentp->sec = sb.st_ctime;
5765 dentp->nsec = (uint_t)sb.st_ctimespec.tv_nsec;
5767 dentp->nsec = (uint_t)sb.st_ctim.tv_nsec;
5771 if ((gtimesecs - sb.st_mtime <= 300) || (gtimesecs - sb.st_ctime <= 300))
5772 entflags |= FILE_YOUNG;
5774 #if !(defined(__sun) || defined(__HAIKU__))
5775 if (!flags && dp->d_type == DT_LNK) {
5776 /* Do not add sizes for links */
5777 dentp->mode = (sb.st_mode & ~S_IFMT) | S_IFLNK;
5778 dentp->size = listpath ? sb.st_size : 0;
5780 dentp->mode = sb.st_mode;
5781 dentp->size = sb.st_size;
5784 dentp->mode = sb.st_mode;
5785 dentp->size = sb.st_size;
5789 dentp->uid = sb.st_uid;
5790 dentp->gid = sb.st_gid;
5793 dentp->flags = S_ISDIR(sb.st_mode) ? 0 : ((sb.st_nlink > 1) ? HARD_LINK : 0);
5795 dentp->flags |= entflags;
5800 if (S_ISDIR(sb.st_mode)) {
5801 mkpath(path, namep, buf); // NOLINT
5803 /* Need to show the disk usage of this dir */
5804 dirwalk(buf, ndents, (sb_path.st_dev != sb.st_dev)); // NOLINT
5806 if (g_state.interrupt)
5809 dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5810 /* Do not recount hard links */
5811 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5812 dir_blocks += dentp->blocks;
5818 /* Flag if this is a dir or symlink to a dir */
5819 if (S_ISLNK(sb.st_mode)) {
5821 fstatat(fd, namep, &sb, 0);
5824 if (S_ISDIR(sb.st_mode))
5825 dentp->flags |= DIR_OR_DIRLNK;
5826 #if !(defined(__sun) || defined(__HAIKU__)) /* no d_type */
5827 } else if (dp->d_type == DT_DIR || ((dp->d_type == DT_LNK
5828 || dp->d_type == DT_UNKNOWN) && S_ISDIR(sb.st_mode))) {
5829 dentp->flags |= DIR_OR_DIRLNK;
5834 } while ((dp = readdir(dirp)));
5838 while (active_threads);
5840 attroff(COLOR_PAIR(cfg.curctx + 1));
5841 for (int i = 0; i < NUM_DU_THREADS; ++i) {
5842 num_files += core_files[i];
5843 dir_blocks += core_blocks[i];
5847 /* Should never be null */
5848 if (closedir(dirp) == -1)
5854 static void populate(char *path, char *lastname)
5857 struct timespec ts1, ts2;
5859 clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
5862 ndents = dentfill(path, &pdents);
5867 ENTSORT(pdents, ndents, entrycmpfn);
5871 clock_gettime(CLOCK_REALTIME, &ts2);
5872 DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
5875 /* Find cur from history */
5876 /* No NULL check for lastname, always points to an array */
5877 move_cursor(*lastname ? dentfind(lastname, ndents) : 0, 0);
5879 // Force full redraw
5880 last_curscroll = -1;
5884 static void notify_fifo(bool force)
5890 fifofd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC);
5893 /* Unexpected error, the FIFO file might have been removed */
5894 /* We give up FIFO notification */
5900 static struct entry lastentry;
5902 if (!force && !memcmp(&lastentry, &pdents[cur], sizeof(struct entry)))
5905 lastentry = pdents[cur];
5907 char path[PATH_MAX];
5908 size_t len = mkpath(g_ctx[cfg.curctx].c_path, ndents ? pdents[cur].name : "", path);
5910 path[len - 1] = '\n';
5912 ssize_t ret = write(fifofd, path, len);
5914 if (ret != (ssize_t)len && !(ret == -1 && (errno == EAGAIN || errno == EPIPE))) {
5915 DPRINTF_S(strerror(errno));
5919 static void send_to_explorer(int *presel)
5922 int fd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0600);
5923 if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
5932 notify_fifo(TRUE); /* Send opened path to NNN_FIFO */
5936 static void move_cursor(int target, int ignore_scrolloff)
5938 int onscreen = xlines - 4; /* Leave top 2 and bottom 2 lines */
5940 target = MAX(0, MIN(ndents - 1, target));
5941 last_curscroll = curscroll;
5945 if (!ignore_scrolloff) {
5946 int delta = target - last;
5947 int scrolloff = MIN(SCROLLOFF, onscreen >> 1);
5950 * When ignore_scrolloff is 1, the cursor can jump into the scrolloff
5951 * margin area, but when ignore_scrolloff is 0, act like a boa
5952 * constrictor and squeeze the cursor towards the middle region of the
5953 * screen by allowing it to move inward and disallowing it to move
5954 * outward (deeper into the scrolloff margin area).
5956 if (((cur < (curscroll + scrolloff)) && delta < 0)
5957 || ((cur > (curscroll + onscreen - scrolloff - 1)) && delta > 0))
5960 curscroll = MIN(curscroll, MIN(cur, ndents - onscreen));
5961 curscroll = MAX(curscroll, MAX(cur - (onscreen - 1), 0));
5964 if (!g_state.fifomode)
5965 notify_fifo(FALSE); /* Send hovered path to NNN_FIFO */
5969 static void handle_screen_move(enum action sel)
5975 if (ndents && (cfg.rollover || (cur != ndents - 1)))
5976 move_cursor((cur + 1) % ndents, 0);
5979 if (ndents && (cfg.rollover || cur))
5980 move_cursor((cur + ndents - 1) % ndents, 0);
5983 onscreen = xlines - 4;
5984 move_cursor(curscroll + (onscreen - 1), 1);
5985 curscroll += onscreen - 1;
5988 onscreen = xlines - 4;
5989 move_cursor(curscroll + (onscreen - 1), 1);
5990 curscroll += onscreen >> 1;
5992 case SEL_PGUP: // fallthrough
5993 onscreen = xlines - 4;
5994 move_cursor(curscroll, 1);
5995 curscroll -= onscreen - 1;
5998 onscreen = xlines - 4;
5999 move_cursor(curscroll, 1);
6000 curscroll -= onscreen >> 1;
6006 move_cursor(ndents - 1, 1);
6008 default: /* case SEL_FIRST */
6010 int c = get_input(messages[MSG_FIRST]);
6017 int r = (c == TOUPPER(*pdents[cur].name)) ? (cur + 1) : 0;
6019 for (; r < ndents; ++r) {
6020 if (((c == '\'') && !(pdents[r].flags & DIR_OR_DIRLNK))
6021 || (c == TOUPPER(*pdents[r].name))) {
6022 move_cursor((r) % ndents, 0);
6031 static void handle_openwith(const char *path, const char *name, char *newpath, char *tmp)
6033 /* Confirm if app is CLI or GUI */
6034 int r = get_input(messages[MSG_CLI_MODE]);
6036 r = (r == 'c' ? F_CLI :
6037 (r == 'g' ? F_NOWAIT | F_NOTRACE | F_MULTI : 0));
6039 mkpath(path, name, newpath);
6040 spawn(tmp, newpath, NULL, NULL, r);
6044 static void copynextname(char *lastname)
6047 cur += (cur != (ndents - 1)) ? 1 : -1;
6053 static int handle_context_switch(enum action sel)
6058 case SEL_CYCLE: // fallthrough
6060 /* visit next and previous contexts */
6062 if (sel == SEL_CYCLE)
6064 r = (r + 1) & ~CTX_MAX;
6065 while (!g_ctx[r].c_cfg.ctxactive);
6067 do /* Attempt to create a new context */
6068 r = (r + 1) & ~CTX_MAX;
6069 while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
6071 if (r == cfg.curctx) /* If all contexts are active, reverse cycle */
6073 r = (r + (CTX_MAX - 1)) & (CTX_MAX - 1);
6074 while (!g_ctx[r].c_cfg.ctxactive);
6076 default: /* SEL_CTXN */
6077 if (sel >= SEL_CTX1) /* CYCLE keys are lesser in value */
6078 r = sel - SEL_CTX1; /* Save the next context id */
6080 if (cfg.curctx == r) {
6081 if (sel == SEL_CYCLE)
6082 (r == CTX_MAX - 1) ? (r = 0) : ++r;
6083 else if (sel == SEL_CYCLER)
6084 (r == 0) ? (r = CTX_MAX - 1) : --r;
6093 static int set_sort_flags(int r)
6095 bool session = (r == '\0');
6096 bool reverse = FALSE;
6098 if (ISUPPER_(r) && (r != 'R') && (r != 'C')) {
6103 /* Set the correct input in case of a session load */
6105 if (cfg.apparentsz) {
6108 } else if (cfg.blkorder) {
6114 namecmpfn = &xstrverscasecmp;
6117 entrycmpfn = &reventrycmp;
6118 } else if (r == CONTROL('T')) {
6119 /* Cycling order: clear -> size -> time -> clear */
6122 else if (cfg.sizeorder)
6129 case 'a': /* Apparent du */
6130 cfg.apparentsz ^= 1;
6131 if (cfg.apparentsz) {
6137 case 'd': /* Disk usage */
6139 if (!cfg.apparentsz)
6142 blk_shift = ffs(S_BLKSIZE) - 1;
6152 entrycmpfn = &entrycmp;
6154 endselection(TRUE); /* We are going to reload dir */
6164 entrycmpfn = &entrycmp;
6165 namecmpfn = &xstricmp;
6167 case 'e': /* File extension */
6174 entrycmpfn = &entrycmp;
6176 case 'r': /* Reverse sort */
6178 entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
6180 case 's': /* File size */
6187 entrycmpfn = &entrycmp;
6189 case 't': /* Time */
6196 entrycmpfn = &entrycmp;
6198 case 'v': /* Version */
6200 namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
6213 entrycmpfn = &reventrycmp;
6216 cfgsort[cfg.curctx] = (uchar_t)r;
6221 static bool set_time_type(int *presel)
6224 char buf[] = "'a'ccess / 'c'hange / 'm'od [ ]";
6226 buf[sizeof(buf) - 3] = cfg.timetype == T_MOD ? 'm' : (cfg.timetype == T_ACCESS ? 'a' : 'c');
6228 int r = get_input(buf);
6230 if (r == 'a' || r == 'c' || r == 'm') {
6231 r = (r == 'm') ? T_MOD : ((r == 'a') ? T_ACCESS : T_CHANGE);
6232 if (cfg.timetype != r) {
6235 if (cfg.filtermode || g_ctx[cfg.curctx].c_fltr[1])
6242 r = MSG_INVALID_KEY;
6245 printwait(messages[r], presel);
6250 static void statusbar(char *path)
6254 pEntry pent = &pdents[cur];
6261 /* Get the file extension for regular files */
6262 if (S_ISREG(pent->mode)) {
6263 i = (int)(pent->nlen - 1);
6264 ptr = xextension(pent->name, i);
6266 len = i - (ptr - pent->name);
6267 if (!ptr || len > 5 || len < 2)
6272 attron(COLOR_PAIR(cfg.curctx + 1));
6274 if (cfg.fileinfo && get_output("file", "-b", pdents[cur].name, -1, FALSE, FALSE))
6275 mvaddstr(xlines - 2, 2, g_buf);
6279 printw("%d/%s ", cur + 1, xitoa(ndents));
6281 if (g_state.selmode || nselected) {
6284 if (g_state.rangesel)
6286 else if (g_state.selmode)
6289 addstr(xitoa(nselected));
6295 if (cfg.blkorder) { /* du mode */
6298 xstrsncpy(buf, coolsize(dir_blocks << blk_shift), 12);
6300 printw("%cu:%s free:%s files:%llu %lluB %s\n",
6301 (cfg.apparentsz ? 'a' : 'd'), buf, coolsize(get_fs_info(path, FREE)),
6302 num_files, (ullong_t)pent->blocks << blk_shift, ptr);
6303 } else { /* light or detail mode */
6304 char sort[] = "\0\0\0\0\0";
6306 if (getorderstr(sort))
6310 print_time(&pent->sec, pent->flags);
6313 addstr(get_lsperms(pent->mode));
6316 if (g_state.uidgid) {
6317 addstr(getpwname(pent->uid));
6319 addstr(getgrname(pent->gid));
6323 if (S_ISLNK(pent->mode)) {
6324 if (!cfg.fileinfo) {
6325 i = readlink(pent->name, g_buf, PATH_MAX);
6326 addstr(coolsize(i >= 0 ? i : pent->size)); /* Show symlink size */
6327 if (i > 1) { /* Show symlink target */
6331 getyx(stdscr, len, y);
6332 i = MIN(i, xcols - y);
6338 addstr(coolsize(pent->size));
6341 if (pent->flags & HARD_LINK) {
6344 if (stat(pent->name, &sb) != -1) {
6346 addstr(xitoa((int)sb.st_nlink)); /* Show number of links */
6348 addstr(xitoa((int)sb.st_ino)); /* Show inode number */
6355 attroff(COLOR_PAIR(cfg.curctx + 1));
6356 /* Plase HW cursor on current for Braille systems */
6360 static inline void markhovered(void)
6362 if (cfg.showdetail && ndents) { /* Bold forward arrowhead */
6364 addch('>' | A_BOLD);
6368 static int adjust_cols(int n)
6370 /* Calculate the number of cols available to print entry name */
6371 #ifdef ICONS_ENABLED
6372 n -= (g_state.oldcolor ? 0 : 1 + ICON_PADDING_LEFT_LEN + ICON_PADDING_RIGHT_LEN);
6374 if (cfg.showdetail) {
6375 /* Fallback to light mode if less than 35 columns */
6377 cfg.showdetail ^= 1;
6378 else /* 2 more accounted for below */
6382 /* 2 columns for preceding space and indicator */
6386 static void draw_line(int ncols)
6390 ncols = adjust_cols(ncols);
6392 if (g_state.oldcolor && (pdents[last].flags & DIR_OR_DIRLNK)) {
6393 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6397 move(2 + last - curscroll, 0);
6398 printent(&pdents[last], ncols, FALSE);
6400 if (g_state.oldcolor && (pdents[cur].flags & DIR_OR_DIRLNK)) {
6401 if (!dir) {/* First file is not a directory */
6402 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6405 } else if (dir) { /* Second file is not a directory */
6406 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6410 move(2 + cur - curscroll, 0);
6411 printent(&pdents[cur], ncols, TRUE);
6413 /* Must reset e.g. no files in dir */
6415 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6420 static void redraw(char *path)
6422 getmaxyx(stdscr, xlines, xcols);
6424 int ncols = (xcols <= PATH_MAX) ? xcols : PATH_MAX;
6425 int onscreen = xlines - 4;
6432 if (ndents && (last_curscroll == curscroll))
6433 return draw_line(ncols);
6436 DPRINTF_S(__func__);
6441 /* Enforce scroll/cursor invariants */
6442 move_cursor(cur, 1);
6444 /* Fail redraw if < than 10 columns, context info prints 10 chars */
6445 if (ncols <= MIN_DISPLAY_COL) {
6446 printmsg(messages[MSG_FEW_COLUMNS]);
6453 for (i = 0; i < CTX_MAX; ++i) { /* 8 chars printed for contexts - "1 2 3 4 " */
6454 if (!g_ctx[i].c_cfg.ctxactive)
6457 addch((i + '1') | (COLOR_PAIR(i + 1) | A_BOLD
6458 /* active: underline, current: reverse */
6459 | ((cfg.curctx != i) ? A_UNDERLINE : A_REVERSE)));
6464 attron(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6467 bool in_home = set_tilde_in_path(path);
6468 char *ptr = in_home ? &path[homelen - 1] : path;
6470 i = (int)xstrlen(ptr);
6471 if ((i + MIN_DISPLAY_COL) <= ncols)
6472 addnstr(ptr, ncols - MIN_DISPLAY_COL);
6474 char *base = xmemrchr((uchar_t *)ptr, '/', i);
6483 if (ptr && (base != ptr)) {
6484 while (ptr < base) {
6486 i += 2; /* 2 characters added */
6487 if (ncols < i + MIN_DISPLAY_COL) {
6488 base = NULL; /* Can't print more characters */
6500 addnstr(base, ncols - (MIN_DISPLAY_COL + i));
6504 reset_tilde_in_path(path);
6506 attroff(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6508 /* Go to first entry */
6509 if (curscroll > 0) {
6511 #ifdef ICONS_ENABLED
6512 addstr(MD_ARROW_UPWARD);
6518 if (g_state.oldcolor) {
6519 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6520 g_state.dircolor = 1;
6523 onscreen = MIN(onscreen + curscroll, ndents);
6525 ncols = adjust_cols(ncols);
6527 int len = scanselforpath(path, FALSE);
6530 for (i = curscroll; i < onscreen; ++i) {
6534 findmarkentry(len, &pdents[i]);
6536 printent(&pdents[i], ncols, i == cur);
6539 /* Must reset e.g. no files in dir */
6540 if (g_state.dircolor) {
6541 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6542 g_state.dircolor = 0;
6545 /* Go to last entry */
6546 if (onscreen < ndents) {
6547 move(xlines - 2, 0);
6548 #ifdef ICONS_ENABLED
6549 addstr(MD_ARROW_DOWNWARD);
6558 static bool cdprep(char *lastdir, char *lastname, char *path, char *newpath)
6563 /* Save last working directory */
6564 xstrsncpy(lastdir, path, PATH_MAX);
6566 /* Save the newly opted dir in path */
6567 xstrsncpy(path, newpath, PATH_MAX);
6571 return cfg.filtermode;
6574 static bool browse(char *ipath, const char *session, int pkey)
6576 char newpath[PATH_MAX] __attribute__ ((aligned)),
6577 rundir[PATH_MAX] __attribute__ ((aligned)),
6578 runfile[NAME_MAX + 1] __attribute__ ((aligned));
6579 char *path, *lastdir, *lastname, *dir, *tmp;
6583 int r = -1, presel, selstartid = 0, selendid = 0;
6584 const uchar_t opener_flags = (cfg.cliopener ? F_CLI : (F_NOTRACE | F_NOSTDIN | F_NOWAIT));
6585 bool watch = FALSE, cd = TRUE;
6590 struct timespec mousetimings[2] = {{.tv_sec = 0, .tv_nsec = 0}, {.tv_sec = 0, .tv_nsec = 0} };
6591 int mousedent[2] = {-1, -1};
6592 bool currentmouse = 1, rightclicksel = 0;
6597 getmaxyx(stdscr, xlines, xcols);
6600 /* set-up first context */
6601 if (!session || !load_session(session, &path, &lastdir, &lastname, FALSE)) {
6605 g_ctx[0].c_last[0] = '\0';
6606 lastdir = g_ctx[0].c_last; /* last visited directory */
6608 if (g_state.initfile) {
6609 xstrsncpy(g_ctx[0].c_name, xbasename(ipath), sizeof(g_ctx[0].c_name));
6612 g_ctx[0].c_name[0] = '\0';
6614 lastname = g_ctx[0].c_name; /* last visited file name */
6616 xstrsncpy(g_ctx[0].c_path, ipath, PATH_MAX);
6617 /* If the initial path is a file, retain a way to return to start dir */
6618 if (g_state.initfile) {
6620 initpath = ipath = getcwd(NULL, 0);
6622 path = g_ctx[0].c_path; /* current directory */
6624 g_ctx[0].c_fltr[0] = g_ctx[0].c_fltr[1] = '\0';
6625 g_ctx[0].c_cfg = cfg; /* current configuration */
6630 newpath[0] = rundir[0] = runfile[0] = '\0';
6632 presel = pkey ? ';' : ((cfg.filtermode
6633 || (session && (g_ctx[cfg.curctx].c_fltr[0] == FILTER
6634 || g_ctx[cfg.curctx].c_fltr[0] == RFILTER)
6635 && g_ctx[cfg.curctx].c_fltr[1])) ? FILTER : 0);
6637 pdents = xrealloc(pdents, total_dents * sizeof(struct entry));
6641 /* Allocate buffer to hold names */
6642 pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
6646 /* The following call is added to handle a broken window at start */
6647 if (presel == FILTER)
6648 handle_key_resize();
6652 * Can fail when permissions change while browsing.
6653 * It's assumed that path IS a directory when we are here.
6655 if (chdir(path) == -1) {
6656 DPRINTF_S("directory inaccessible");
6657 valid_parent(path, lastname);
6665 #ifdef LINUX_INOTIFY
6666 if ((presel == FILTER || watch) && inotify_wd >= 0) {
6667 inotify_rm_watch(inotify_fd, inotify_wd);
6671 #elif defined(BSD_KQUEUE)
6672 if ((presel == FILTER || watch) && event_fd >= 0) {
6677 #elif defined(HAIKU_NM)
6678 if ((presel == FILTER || watch) && haiku_hnd != NULL) {
6679 haiku_stop_watch(haiku_hnd);
6680 haiku_nm_active = FALSE;
6686 if (cfgsort[cfg.curctx] != '0') {
6687 if (cfgsort[cfg.curctx] == 'z')
6688 set_sort_flags('c');
6689 if ((!cfgsort[cfg.curctx] || (cfgsort[cfg.curctx] == 'c'))
6690 && ((r = get_kv_key(order, path, maxorder, NNN_ORDER)) > 0)) {
6692 cfgsort[cfg.curctx] = 'z';
6695 cfgsort[cfg.curctx] = cfgsort[CTX_MAX];
6699 populate(path, lastname);
6700 if (g_state.interrupt) {
6701 g_state.interrupt = cfg.apparentsz = cfg.blkorder = 0;
6702 blk_shift = BLK_SHIFT_512;
6703 presel = CONTROL('L');
6706 #ifdef LINUX_INOTIFY
6707 if (presel != FILTER && inotify_wd == -1)
6708 inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
6709 #elif defined(BSD_KQUEUE)
6710 if (presel != FILTER && event_fd == -1) {
6711 #if defined(O_EVTONLY)
6712 event_fd = open(path, O_EVTONLY);
6714 event_fd = open(path, O_RDONLY);
6717 EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
6718 EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
6720 #elif defined(HAIKU_NM)
6721 haiku_nm_active = haiku_watch_dir(haiku_hnd, path) == EXIT_SUCCESS;
6725 /* Do not do a double redraw in filterentries */
6726 if ((presel != FILTER) || !filterset()) {
6732 /* Exit if parent has exited */
6734 _exit(EXIT_FAILURE);
6736 /* If CWD is deleted or moved or perms changed, find an accessible parent */
6737 if (chdir(path) == -1)
6740 /* If STDIN is no longer a tty (closed) we should exit */
6741 if (!isatty(STDIN_FILENO) && !g_state.picker)
6742 return EXIT_FAILURE;
6744 sel = nextsel(presel);
6751 if (getmouse(&event) != OK)
6754 /* Handle clicking on a context at the top */
6755 if (event.bstate == BUTTON1_PRESSED && event.y == 0) {
6756 /* Get context from: "[1 2 3 4]..." */
6759 /* If clicked after contexts, go to parent */
6762 else if (r >= 0 && r != cfg.curctx) {
6763 savecurctx(path, ndents ? pdents[cur].name : NULL, r);
6765 /* Reset the pointers */
6766 path = g_ctx[r].c_path;
6767 lastdir = g_ctx[r].c_last;
6768 lastname = g_ctx[r].c_name;
6778 if (sel == SEL_BACK) {
6780 dir = visit_parent(path, newpath, &presel);
6785 xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
6787 cdprep(lastdir, NULL, path, dir) ? (presel = FILTER) : (watch = TRUE);
6794 /* Middle click action */
6795 if (event.bstate == BUTTON2_PRESSED) {
6796 presel = middle_click_key;
6799 #if NCURSES_MOUSE_VERSION > 1
6801 if (event.bstate == BUTTON4_PRESSED && ndents && (cfg.rollover || cur)) {
6802 move_cursor((!cfg.rollover && cur < scroll_lines
6803 ? 0 : (cur + ndents - scroll_lines) % ndents), 0);
6808 if (event.bstate == BUTTON5_PRESSED && ndents
6809 && (cfg.rollover || (cur != ndents - 1))) {
6810 move_cursor((!cfg.rollover && cur >= ndents - scroll_lines)
6811 ? (ndents - 1) : ((cur + scroll_lines) % ndents), 0);
6816 /* Toggle filter mode on left click on last 2 lines */
6817 if (event.y >= xlines - 2 && event.bstate == BUTTON1_PRESSED) {
6819 cfg.filtermode ^= 1;
6820 if (cfg.filtermode) {
6825 /* Start watching the directory */
6832 /* Handle clicking on a file */
6833 if (event.y >= 2 && event.y <= ndents + 1 &&
6834 (event.bstate == BUTTON1_PRESSED ||
6835 event.bstate == BUTTON3_PRESSED)) {
6836 r = curscroll + (event.y - 2);
6840 else if ((event.bstate == BUTTON1_PRESSED) && !g_state.fifomode)
6841 notify_fifo(TRUE); /* Send clicked path to NNN_FIFO */
6843 /* Handle right click selection */
6844 if (event.bstate == BUTTON3_PRESSED) {
6852 #if defined(CLOCK_MONOTONIC_RAW)
6853 CLOCK_MONOTONIC_RAW,
6854 #elif defined(CLOCK_MONOTONIC)
6859 &mousetimings[currentmouse]);
6860 mousedent[currentmouse] = cur;
6862 /* Single click just selects, double click falls through to SEL_OPEN */
6863 if ((mousedent[0] != mousedent[1]) ||
6864 (((_ABSSUB(mousetimings[0].tv_sec, mousetimings[1].tv_sec) << 30)
6865 + (_ABSSUB(mousetimings[0].tv_nsec, mousetimings[1].tv_nsec)))
6866 > DBLCLK_INTERVAL_NS))
6869 mousetimings[currentmouse].tv_sec = 0;
6870 mousedent[currentmouse] = -1;
6873 if (cfg.filtermode || filterset())
6880 case SEL_NAV_IN: // fallthrough
6882 /* Cannot descend in empty directories */
6888 pent = &pdents[cur];
6889 mkpath(path, pent->name, newpath);
6892 /* Visit directory */
6893 if (pent->flags & DIR_OR_DIRLNK) {
6894 if (chdir(newpath) == -1) {
6899 cdprep(lastdir, lastname, path, newpath)
6900 ? (presel = FILTER) : (watch = TRUE);
6904 /* Cannot use stale data in entry, file may be missing by now */
6905 if (stat(newpath, &sb) == -1) {
6909 DPRINTF_U(sb.st_mode);
6911 /* Do not open non-regular files */
6912 if (!S_ISREG(sb.st_mode)) {
6913 printwait(messages[MSG_UNSUPPORTED], &presel);
6917 /* Handle plugin selection mode */
6918 if (g_state.runplugin) {
6919 g_state.runplugin = 0;
6920 /* Must be in plugin dir and same context to select plugin */
6921 if ((g_state.runctx == cfg.curctx) && !strcmp(path, plgpath)) {
6922 endselection(FALSE);
6923 /* Copy path so we can return back to earlier dir */
6924 xstrsncpy(path, rundir, PATH_MAX);
6928 if (chdir(path) == -1
6929 || !run_plugin(&path, pent->name,
6930 runfile, &lastname, &lastdir)) {
6931 DPRINTF_S("plugin failed!");
6935 return EXIT_SUCCESS;
6938 xstrsncpy(lastname, runfile, NAME_MAX + 1);
6947 if (g_state.fifomode && (sel == SEL_OPEN)) {
6948 send_to_explorer(&presel); /* Write selection to explorer fifo */
6952 /* If opened as vim plugin and Enter/^M pressed, pick */
6953 if (g_state.picker && (sel == SEL_OPEN)) {
6954 if (nselected == 0) /* Pick if none selected */
6955 appendfpath(newpath, mkpath(path, pent->name, newpath));
6956 return EXIT_SUCCESS;
6959 if (sel == SEL_NAV_IN) {
6960 /* If in listing dir, go to target on `l` or Right on symlink */
6961 if (listpath && S_ISLNK(pent->mode)
6962 && is_prefix(path, listpath, xstrlen(listpath))) {
6963 if (!realpath(pent->name, newpath)) {
6970 if (chdir(newpath) == -1) {
6975 cdprep(lastdir, NULL, path, newpath)
6976 ? (presel = FILTER) : (watch = TRUE);
6977 xstrsncpy(lastname, pent->name, NAME_MAX + 1);
6981 /* Open file disabled on right arrow or `l` */
6987 printwait(messages[MSG_EMPTY_FILE], &presel);
6992 #ifdef FILE_MIME_OPTS
6993 && get_output("file", FILE_MIME_OPTS, newpath, -1, FALSE, FALSE)
6994 && is_prefix(g_buf, "text/", 5)
6996 /* no MIME option; guess from description instead */
6997 && get_output("file", "-bL", newpath, -1, FALSE, FALSE)
6998 && strstr(g_buf, "text")
7001 spawn(editor, newpath, NULL, NULL, F_CLI);
7002 if (cfg.filtermode) {
7009 /* Get the extension for regex match */
7010 tmp = xextension(pent->name, pent->nlen - 1);
7012 if (tmp && !pcre_exec(archive_pcre, NULL, tmp,
7013 pent->nlen - (tmp - pent->name) - 1, 0, 0, NULL, 0)) {
7015 if (tmp && !regexec(&archive_re, tmp, 0, NULL, 0)) {
7017 r = get_input(messages[MSG_ARCHIVE_OPTS]);
7018 if (r == 'l' || r == 'x') {
7019 mkpath(path, pent->name, newpath);
7020 if (!handle_archive(newpath, r)) {
7030 if ((r == 'm') && !archive_mount(newpath)) {
7035 if (r == 'x' || r == 'm') {
7037 set_smart_ctx('+', newpath, &path,
7038 ndents ? pdents[cur].name : NULL,
7039 &lastname, &lastdir);
7047 printwait(messages[MSG_INVALID_KEY], &presel);
7052 /* Invoke desktop opener as last resort */
7053 spawn(opener, newpath, NULL, NULL, opener_flags);
7055 /* Move cursor to the next entry if not the last entry */
7056 if (g_state.autonext && cur != ndents - 1)
7057 move_cursor((cur + 1) % ndents, 0);
7058 if (cfg.filtermode) {
7063 case SEL_NEXT: // fallthrough
7064 case SEL_PREV: // fallthrough
7065 case SEL_PGDN: // fallthrough
7066 case SEL_CTRL_D: // fallthrough
7067 case SEL_PGUP: // fallthrough
7068 case SEL_CTRL_U: // fallthrough
7069 case SEL_HOME: // fallthrough
7070 case SEL_END: // fallthrough
7074 handle_screen_move(sel);
7077 case SEL_CDHOME: // fallthrough
7078 case SEL_CDBEGIN: // fallthrough
7079 case SEL_CDLAST: // fallthrough
7081 dir = (sel == SEL_CDHOME) ? home
7082 : ((sel == SEL_CDBEGIN) ? ipath
7083 : ((sel == SEL_CDLAST) ? lastdir
7084 : "/" /* SEL_CDROOT */));
7086 if (!dir || !*dir) {
7087 printwait(messages[MSG_NOT_SET], &presel);
7091 if (strcmp(path, dir) == 0) {
7097 dir = lastdir; /* Go to last dir on home/root key repeat */
7100 if (chdir(dir) == -1) {
7105 /* SEL_CDLAST: dir pointing to lastdir */
7106 xstrsncpy(newpath, dir, PATH_MAX); // fallthrough
7108 if (sel == SEL_BMOPEN) {
7109 r = (int)handle_bookmark(mark, newpath);
7111 printwait(messages[r], &presel);
7115 if (strcmp(path, newpath) == 0)
7119 /* In list mode, retain the last file name to highlight it, if possible */
7120 cdprep(lastdir, listpath && sel == SEL_CDLAST ? NULL : lastname, path, newpath)
7121 ? (presel = FILTER) : (watch = TRUE);
7124 if ((sel == SEL_REMOTE) && !remote_mount(newpath)) {
7129 set_smart_ctx('+', newpath, &path,
7130 ndents ? pdents[cur].name : NULL, &lastname, &lastdir);
7133 case SEL_CYCLE: // fallthrough
7134 case SEL_CYCLER: // fallthrough
7135 case SEL_CTX1: // fallthrough
7136 case SEL_CTX2: // fallthrough
7137 case SEL_CTX3: // fallthrough
7145 r = handle_context_switch(sel);
7148 savecurctx(path, ndents ? pdents[cur].name : NULL, r);
7150 /* Reset the pointers */
7151 path = g_ctx[r].c_path;
7152 lastdir = g_ctx[r].c_last;
7153 lastname = g_ctx[r].c_name;
7154 tmp = g_ctx[r].c_fltr;
7156 if (cfg.filtermode || ((tmp[0] == FILTER || tmp[0] == RFILTER) && tmp[1]))
7164 mark = xstrdup(path);
7165 printwait(mark, &presel);
7168 add_bookmark(path, newpath, &presel);
7171 /* Unwatch dir if we are still in a filtered view */
7172 #ifdef LINUX_INOTIFY
7173 if (inotify_wd >= 0) {
7174 inotify_rm_watch(inotify_fd, inotify_wd);
7177 #elif defined(BSD_KQUEUE)
7178 if (event_fd >= 0) {
7182 #elif defined(HAIKU_NM)
7183 if (haiku_nm_active) {
7184 haiku_stop_watch(haiku_hnd);
7185 haiku_nm_active = FALSE;
7188 presel = filterentries(path, lastname);
7189 if (presel == ESC) {
7193 if (presel == FILTER) { /* Refresh dir and filter again */
7198 case SEL_MFLTR: // fallthrough
7199 case SEL_HIDDEN: // fallthrough
7200 case SEL_DETAIL: // fallthrough
7204 cfg.filtermode ^= 1;
7205 if (cfg.filtermode) {
7211 watch = TRUE; // fallthrough
7213 if (sel == SEL_HIDDEN) {
7214 cfg.showhidden ^= 1;
7223 cfg.showdetail ^= 1;
7226 default: /* SEL_SORT */
7227 r = set_sort_flags(get_input(messages[MSG_ORDER]));
7229 printwait(messages[MSG_INVALID_KEY], &presel);
7234 if (cfg.filtermode || filterset())
7240 if (r == 'd' || r == 'a') {
7245 ENTSORT(pdents, ndents, entrycmpfn);
7246 move_cursor(ndents ? dentfind(lastname, ndents) : 0, 0);
7249 case SEL_STATS: // fallthrough
7252 tmp = (listpath && xstrcmp(path, listpath) == 0) ? listroot : path;
7253 mkpath(tmp, pdents[cur].name, newpath);
7255 if ((sel == SEL_STATS && !show_stats(newpath))
7256 || (lstat(newpath, &sb) == -1)
7257 || (sel == SEL_CHMODX && !xchmod(newpath, sb.st_mode))) {
7262 if (sel == SEL_CHMODX)
7263 pdents[cur].mode ^= 0111;
7266 case SEL_REDRAW: // fallthrough
7267 case SEL_RENAMEMUL: // fallthrough
7268 case SEL_HELP: // fallthrough
7269 case SEL_AUTONEXT: // fallthrough
7270 case SEL_EDIT: // fallthrough
7273 bool refresh = FALSE;
7276 mkpath(path, pdents[cur].name, newpath);
7277 else if (sel == SEL_EDIT) /* Avoid trying to edit a non-existing file */
7286 setenv("NNN_INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
7287 setenv("NNN_LIST", listpath ? listroot : "", 1);
7289 if (!(getutil(utils[UTIL_BASH])
7290 && plugscript(utils[UTIL_NMV], F_CLI))
7295 printwait(messages[MSG_FAILED], &presel);
7302 show_help(path); // fallthrough
7304 if (sel == SEL_AUTONEXT)
7305 g_state.autonext ^= 1;
7311 if (!g_state.picker)
7312 spawn(editor, newpath, NULL, NULL, F_CLI);
7314 default: /* SEL_LOCK */
7319 /* In case of successful operation, reload contents */
7321 /* Continue in type-to-nav mode, if enabled */
7322 if ((cfg.filtermode || filterset()) && !refresh) {
7329 /* Repopulate as directory content may have changed */
7338 if (g_state.rangesel)
7339 g_state.rangesel = 0;
7341 /* Toggle selection status */
7342 pdents[cur].flags ^= FILE_SELECTED;
7344 if (pdents[cur].flags & FILE_SELECTED) {
7346 appendfpath(newpath, mkpath(path, pdents[cur].name, newpath));
7347 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
7350 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
7355 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7362 /* move cursor to the next entry if this is not the last entry */
7363 if (!g_state.stayonsel && (cur != ndents - 1))
7364 move_cursor((cur + 1) % ndents, 0);
7371 g_state.rangesel ^= 1;
7373 if (stat(path, &sb) == -1) {
7378 if (g_state.rangesel) { /* Range selection started */
7384 if (inode != sb.st_ino) {
7385 printwait(messages[MSG_DIR_CHANGED], &presel);
7389 if (cur < selstartid) {
7390 selendid = selstartid;
7395 /* Clear selection on repeat on same file */
7396 if (selstartid == selendid) {
7401 case SEL_SELALL: // fallthrough
7403 if (sel == SEL_SELALL || sel == SEL_SELINV) {
7408 if (g_state.rangesel)
7409 g_state.rangesel = 0;
7412 selendid = ndents - 1;
7415 if ((nselected > LARGESEL) || (nselected && (ndents > LARGESEL))) {
7416 printmsg("processing...");
7420 r = scanselforpath(path, TRUE); /* Get path length suffixed by '/' */
7421 ((sel == SEL_SELINV) && findselpos)
7422 ? invertselbuf(r) : addtoselbuf(r, selstartid, selendid);
7426 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7430 r = editselection();
7432 r = !r ? MSG_0_SELECTED : MSG_FAILED;
7433 printwait(messages[r], &presel);
7437 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7439 cfg.filtermode ? presel = FILTER : statusbar(path);
7442 case SEL_CP: // fallthrough
7443 case SEL_MV: // fallthrough
7444 case SEL_CPMVAS: // fallthrough
7447 if (sel == SEL_RM) {
7448 r = get_cur_or_sel();
7455 tmp = (listpath && xstrcmp(path, listpath) == 0)
7457 mkpath(tmp, pdents[cur].name, newpath);
7461 xrmfromsel(tmp, newpath);
7463 copynextname(lastname);
7465 if (cfg.filtermode || filterset())
7472 (nselected == 1 && (sel == SEL_CP || sel == SEL_MV))
7473 ? mkpath(path, xbasename(pselbuf), newpath)
7474 : (newpath[0] = '\0');
7478 if (!cpmvrm_selection(sel, path)) {
7488 /* Show notification on operation complete */
7490 plugscript(utils[UTIL_NTFY], F_NOWAIT | F_NOTRACE);
7493 if (newpath[0] && !access(newpath, F_OK))
7494 xstrsncpy(lastname, xbasename(newpath), NAME_MAX+1);
7500 case SEL_ARCHIVE: // fallthrough
7501 case SEL_OPENWITH: // fallthrough
7502 case SEL_NEW: // fallthrough
7507 if (!ndents && (sel == SEL_OPENWITH || sel == SEL_RENAME))
7510 if (sel != SEL_OPENWITH)
7515 r = get_cur_or_sel();
7529 tmp = pdents[cur].name;
7531 tmp = xreadline(tmp, messages[MSG_ARCHIVE_NAME]);
7535 if (g_state.picker) {
7537 tmp = xreadline(NULL, messages[MSG_OPEN_WITH]);
7540 tmp = getreadline(messages[MSG_OPEN_WITH]);
7544 r = get_input(messages[MSG_NEW_OPTS]);
7545 if (r == 'f' || r == 'd')
7546 tmp = xreadline(NULL, messages[MSG_NEW_PATH]);
7547 else if (r == 's' || r == 'h')
7548 tmp = xreadline(NULL,
7549 messages[nselected <= 1?MSG_NEW_PATH:MSG_LINK_PREFIX]);
7553 default: /* SEL_RENAME */
7554 tmp = xreadline(pdents[cur].name, "");
7563 if (r == 'c' && strcmp(tmp, pdents[cur].name) == 0)
7566 mkpath(path, tmp, newpath);
7567 if (access(newpath, F_OK) == 0) {
7568 if (!xconfirm(get_input(messages[MSG_OVERWRITE]))) {
7573 get_archive_cmd(newpath, tmp);
7574 (r == 's') ? archive_selection(newpath, tmp, path)
7575 : spawn(newpath, tmp, pdents[cur].name,
7576 NULL, F_CLI | F_CONFIRM);
7578 mkpath(path, tmp, newpath);
7579 if (access(newpath, F_OK) == 0) { /* File created */
7580 xstrsncpy(lastname, tmp, NAME_MAX + 1);
7581 clearfilter(); /* Archive name may not match */
7582 clearselection(); /* Archive operation complete */
7588 handle_openwith(path, pdents[cur].name, newpath, tmp);
7590 cfg.filtermode ? presel = FILTER : statusbar(path);
7594 /* Skip renaming to same name */
7595 if (strcmp(tmp, pdents[cur].name) == 0) {
7596 tmp = xreadline(pdents[cur].name, messages[MSG_COPY_NAME]);
7597 if (!tmp || !tmp[0] || !strcmp(tmp, pdents[cur].name)) {
7598 cfg.filtermode ? presel = FILTER : statusbar(path);
7605 default: /* SEL_NEW */
7609 /* Open the descriptor to currently open directory */
7611 fd = open(path, O_RDONLY | O_DIRECTORY);
7613 fd = open(path, O_RDONLY);
7620 /* Check if another file with same name exists */
7621 if (fstatat(fd, tmp, &sb, AT_SYMLINK_NOFOLLOW) == 0) {
7622 if (sel == SEL_RENAME) {
7623 /* Overwrite file with same name? */
7624 if (!xconfirm(get_input(messages[MSG_OVERWRITE]))) {
7629 /* Do nothing in case of NEW */
7631 printwait(messages[MSG_EXISTS], &presel);
7636 if (sel == SEL_RENAME) {
7637 /* Rename the file */
7639 spawn("cp -rp", pdents[cur].name, tmp, NULL, F_SILENT);
7640 else if (renameat(fd, pdents[cur].name, fd, tmp) != 0) {
7646 xstrsncpy(lastname, tmp, NAME_MAX + 1);
7647 } else { /* SEL_NEW */
7651 /* Check if it's a dir or file */
7652 if (r == 'f' || r == 'd') {
7653 mkpath(path, tmp, newpath);
7654 ret = xmktree(newpath, r == 'f' ? FALSE : TRUE);
7655 } else if (r == 's' || r == 'h') {
7656 if (nselected > 1 && tmp[0] == '@' && tmp[1] == '\0')
7658 ret = xlink(tmp, path, (ndents ? pdents[cur].name : NULL),
7659 newpath, &presel, r);
7663 printwait(messages[MSG_FAILED], &presel);
7668 if (r == 'f' || r == 'd')
7669 xstrsncpy(lastname, tmp, NAME_MAX + 1);
7682 /* Check if directory is accessible */
7683 if (!xdiraccess(plgpath)) {
7689 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
7690 printkeys(plug, g_buf + r - 1, maxplug);
7692 r = get_input(NULL);
7699 endselection(FALSE);
7700 tmp = get_kv_val(plug, NULL, r, maxplug, NNN_PLUG);
7702 printwait(messages[MSG_INVALID_KEY], &presel);
7706 if (tmp[0] == '-' && tmp[1]) {
7708 r = FALSE; /* Do not refresh dir after completion */
7712 if (!run_plugin(&path, tmp, (ndents ? pdents[cur].name : NULL),
7713 &lastname, &lastdir)) {
7714 printwait(messages[MSG_FAILED], &presel);
7719 return EXIT_SUCCESS;
7724 cfg.filtermode ? presel = FILTER : statusbar(path);
7727 } else { /* 'Return/Enter' enters the plugin directory */
7728 g_state.runplugin ^= 1;
7729 if (!g_state.runplugin && rundir[0]) {
7731 * If toggled, and still in the plugin dir,
7732 * switch to original directory
7734 if (strcmp(path, plgpath) == 0) {
7735 xstrsncpy(path, rundir, PATH_MAX);
7736 xstrsncpy(lastname, runfile, NAME_MAX + 1);
7737 rundir[0] = runfile[0] = '\0';
7742 /* Otherwise, initiate choosing plugin again */
7743 g_state.runplugin = 1;
7746 xstrsncpy(lastdir, path, PATH_MAX);
7747 xstrsncpy(rundir, path, PATH_MAX);
7748 xstrsncpy(path, plgpath, PATH_MAX);
7750 xstrsncpy(runfile, pdents[cur].name, NAME_MAX);
7751 g_state.runctx = cfg.curctx;
7757 case SEL_SHELL: // fallthrough
7758 case SEL_LAUNCH: // fallthrough
7760 r = handle_cmd(sel, newpath);
7762 /* Continue in type-to-nav mode, if enabled */
7772 /* Repopulate as directory content may have changed */
7777 if (!unmount((ndents ? pdents[cur].name : NULL), newpath, &presel, path)) {
7778 if (presel == MSG_ZERO)
7783 /* Dir removed, go to next entry */
7784 copynextname(lastname);
7789 r = get_input(messages[MSG_SSN_OPTS]);
7792 tmp = xreadline(NULL, messages[MSG_SSN_NAME]);
7794 save_session(tmp, &presel);
7795 } else if (r == 'l' || r == 'r') {
7796 if (load_session(NULL, &path, &lastdir, &lastname, r == 'r')) {
7807 cfg.filtermode ? presel = FILTER : statusbar(path);
7810 if (!set_time_type(&presel))
7814 case SEL_QUITCTX: // fallthrough
7815 case SEL_QUITCD: // fallthrough
7818 if (sel == SEL_QUITCTX) {
7819 int ctx = cfg.curctx;
7821 for (r = (ctx - 1) & (CTX_MAX - 1);
7822 (r != ctx) && !g_ctx[r].c_cfg.ctxactive;
7823 r = ((r - 1) & (CTX_MAX - 1))) {
7827 g_ctx[ctx].c_cfg.ctxactive = 0;
7829 /* Switch to next active context */
7830 path = g_ctx[r].c_path;
7831 lastdir = g_ctx[r].c_last;
7832 lastname = g_ctx[r].c_name;
7834 cfg = g_ctx[r].c_cfg;
7840 } else if (!g_state.forcequit) {
7841 for (r = 0; r < CTX_MAX; ++r)
7842 if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
7843 r = get_input(messages[MSG_QUIT_ALL]);
7847 if (!(r == CTX_MAX || xconfirm(r)))
7848 break; // fallthrough
7852 tmp = getenv("NNN_TMPFILE");
7853 if ((sel == SEL_QUITCD) || tmp) {
7854 write_lastdir(path, tmp);
7855 /* ^G is a way to quit picker mode without picking anything */
7856 if ((sel == SEL_QUITCD) && g_state.picker)
7860 if (sel != SEL_QUITERR)
7861 return EXIT_SUCCESS;
7863 if (selbufpos && !g_state.picker) {
7864 /* Pick files to stdout and exit */
7868 return EXIT_SUCCESS;
7871 return EXIT_FAILURE;
7873 if (xlines != LINES || xcols != COLS)
7876 if (idletimeout && idle == idletimeout) {
7877 lock_terminal(); /* Locker */
7883 } /* switch (sel) */
7887 static char *make_tmp_tree(char **paths, ssize_t entries, const char *prefix)
7889 /* tmpdir holds the full path */
7890 /* tmp holds the path without the tmp dir prefix */
7894 ssize_t len = xstrlen(prefix);
7895 char *tmpdir = malloc(PATH_MAX);
7898 DPRINTF_S(strerror(errno));
7902 tmp = tmpdir + tmpfplen - 1;
7903 xstrsncpy(tmpdir, g_tmpfpath, tmpfplen);
7904 xstrsncpy(tmp, "/nnnXXXXXX", 11);
7906 /* Points right after the base tmp dir */
7909 /* handle the case where files are directly under / */
7910 if (!prefix[1] && (prefix[0] == '/'))
7913 if (!mkdtemp(tmpdir)) {
7916 DPRINTF_S(strerror(errno));
7922 for (ssize_t i = 0; i < entries; ++i) {
7926 err = stat(paths[i], &sb);
7927 if (err && errno == ENOENT)
7930 /* Don't copy the common prefix */
7931 xstrsncpy(tmp, paths[i] + len, xstrlen(paths[i]) - len + 1);
7933 /* Get the dir containing the path */
7934 slash = xmemrchr((uchar_t *)tmp, '/', xstrlen(paths[i]) - len);
7938 xmktree(tmpdir, TRUE);
7943 if (symlink(paths[i], tmpdir)) {
7944 DPRINTF_S(paths[i]);
7945 DPRINTF_S(strerror(errno));
7949 /* Get the dir in which to start */
7954 static char *load_input(int fd, const char *path)
7956 ssize_t i, chunk_count = 1, chunk = (ssize_t)(512 * 1024) /* 512 KiB chunk size */, entries = 0;
7957 char *input = malloc(sizeof(char) * chunk), *tmpdir = NULL;
7958 char cwd[PATH_MAX], *next;
7959 size_t offsets[LIST_FILES_MAX];
7960 char **paths = NULL;
7961 ssize_t input_read, total_read = 0, off = 0;
7965 DPRINTF_S(strerror(errno));
7970 if (!getcwd(cwd, PATH_MAX)) {
7975 xstrsncpy(cwd, path, PATH_MAX);
7977 while (chunk_count < 512) {
7978 input_read = read(fd, input + total_read, chunk);
7979 if (input_read < 0) {
7980 DPRINTF_S(strerror(errno));
7984 if (input_read == 0)
7987 total_read += input_read;
7990 while (off < total_read) {
7991 if ((next = memchr(input + off, '\0', total_read - off)) == NULL)
7995 if (next - input == off + 1) {
8000 if (entries == LIST_FILES_MAX) {
8005 offsets[entries++] = off;
8009 if (chunk_count == 512) {
8014 /* We don't need to allocate another chunk */
8015 if (chunk_count == (total_read - input_read) / chunk)
8018 chunk_count = total_read / chunk;
8019 if (total_read % chunk)
8022 input = xrealloc(input, (chunk_count + 1) * chunk);
8027 if (off != total_read) {
8028 if (entries == LIST_FILES_MAX) {
8033 offsets[entries++] = off;
8037 DPRINTF_D(total_read);
8038 DPRINTF_D(chunk_count);
8041 msgnum = MSG_0_ENTRIES;
8045 input[total_read] = '\0';
8047 paths = malloc(entries * sizeof(char *));
8051 for (i = 0; i < entries; ++i)
8052 paths[i] = input + offsets[i];
8054 listroot = malloc(sizeof(char) * PATH_MAX);
8059 DPRINTF_S(paths[0]);
8061 for (i = 0; i < entries; ++i) {
8062 if (paths[i][0] == '\n' || selforparent(paths[i])) {
8067 paths[i] = abspath(paths[i], cwd, NULL);
8069 entries = i; // free from the previous entry
8074 DPRINTF_S(paths[i]);
8076 xstrsncpy(g_buf, paths[i], PATH_MAX);
8077 if (!common_prefix(xdirname(g_buf), listroot)) {
8078 entries = i + 1; // free from the current entry
8082 DPRINTF_S(listroot);
8085 DPRINTF_S(listroot);
8088 tmpdir = make_tmp_tree(paths, entries, listroot);
8091 for (i = entries - 1; i >= 0; --i)
8095 if (home) { /* We are past init stage */
8096 printmsg(messages[msgnum]);
8097 xdelay(XDELAY_INTERVAL_MS);
8099 msg(messages[msgnum]);
8106 static void check_key_collision(void)
8109 bool bitmap[KEY_MAX] = {FALSE};
8111 for (ullong_t i = 0; i < ELEMENTS(bindings); ++i) {
8112 key = bindings[i].sym;
8115 dprintf(STDERR_FILENO, "key collision! [%s]\n", keyname(key));
8121 static void usage(void)
8123 dprintf(STDERR_FILENO,
8124 "%s: nnn [OPTIONS] [PATH]\n\n"
8125 "The unorthodox terminal file manager.\n\n"
8126 "positional args:\n"
8127 " PATH start dir/file [default: .]\n\n"
8130 " -a auto NNN_FIFO\n"
8132 " -A no dir auto-enter in type-to-nav\n"
8133 " -b key open bookmark key (trumps -s/S)\n"
8134 " -c cli-only NNN_OPENER (trumps -e)\n"
8135 " -C 8-color scheme\n"
8137 " -D dirs in context color\n"
8138 " -e text in $VISUAL/$EDITOR/vi\n"
8139 " -E internal edits in EDITOR\n"
8141 " -f use readline history file\n"
8144 " -F val fifo mode [0:preview 1:explore]\n"
8146 " -g regex filters\n"
8147 " -H show hidden files\n"
8148 " -i show current file info\n"
8149 " -J no auto-jump on selection\n"
8150 " -K detect key collision\n"
8151 " -l val set scroll lines\n"
8152 " -n type-to-nav mode\n"
8153 " -o open files only on Enter\n"
8154 " -p file selection file [-:stdout]\n"
8155 " -P key run plugin key\n"
8156 " -Q no quit confirmation\n"
8157 " -r use advcpmv patched cp, mv\n"
8158 " -R no rollover at edges\n"
8160 " -s name load session by name\n"
8161 " -S persistent session\n"
8163 " -t secs timeout to lock\n"
8164 " -T key sort order [a/d/e/r/s/t/v]\n"
8165 " -u use selection (no prompt)\n"
8167 " -U show user and group\n"
8169 " -V show version\n"
8171 " -x notis, selection sync, xterm title\n"
8174 "v%s\n%s\n", __func__, VERSION, GENERAL_INFO);
8177 static bool setup_config(void)
8180 char *xdgcfg = getenv("XDG_CONFIG_HOME");
8183 /* Set up configuration file paths */
8184 if (xdgcfg && xdgcfg[0]) {
8186 if (xdgcfg[0] == '~') {
8187 r = xstrsncpy(g_buf, home, PATH_MAX);
8188 xstrsncpy(g_buf + r - 1, xdgcfg + 1, PATH_MAX);
8193 if (!xdiraccess(xdgcfg)) {
8198 len = xstrlen(xdgcfg) + xstrlen("/nnn/bookmarks") + 1;
8203 len = xstrlen(home) + xstrlen("/.config/nnn/bookmarks") + 1;
8205 cfgpath = (char *)malloc(len);
8206 plgpath = (char *)malloc(len);
8207 if (!cfgpath || !plgpath) {
8213 xstrsncpy(cfgpath, xdgcfg, len);
8214 r = len - xstrlen("/nnn/bookmarks");
8216 r = xstrsncpy(cfgpath, home, len);
8218 /* Create ~/.config */
8219 xstrsncpy(cfgpath + r - 1, "/.config", len - r);
8221 r += 8; /* length of "/.config" */
8224 /* Create ~/.config/nnn */
8225 xstrsncpy(cfgpath + r - 1, "/nnn", len - r);
8228 /* Create bookmarks, sessions, mounts and plugins directories */
8229 for (r = 0; r < ELEMENTS(toks); ++r) {
8230 mkpath(cfgpath, toks[r], plgpath);
8231 if (!xmktree(plgpath, TRUE)) {
8238 /* Set selection file path */
8239 if (!g_state.picker) {
8240 char *env_sel = xgetenv(env_cfg[NNN_SEL], NULL);
8242 selpath = env_sel ? xstrdup(env_sel)
8243 : (char *)malloc(len + 3); /* Length of "/.config/nnn/.selection" */
8251 r = xstrsncpy(selpath, cfgpath, len + 3);
8252 xstrsncpy(selpath + r - 1, "/.selection", 12);
8260 static bool set_tmp_path(void)
8263 char *path = xdiraccess(tmp) ? tmp : getenv("TMPDIR");
8270 tmpfplen = (uchar_t)xstrsncpy(g_tmpfpath, path, TMP_LEN_MAX);
8271 DPRINTF_S(g_tmpfpath);
8272 DPRINTF_U(tmpfplen);
8277 static void cleanup(void)
8280 if (cfg.x11 && !g_state.picker) {
8281 printf("\033[23;0t"); /* reset terminal window title */
8297 if (g_state.autofifo)
8300 if (g_state.pluginit)
8307 int main(int argc, char *argv[])
8310 char *session = NULL;
8311 int fd, opt, sort = 0, pkey = '\0'; /* Plugin key */
8314 char *middle_click_env = xgetenv(env_cfg[NNN_MCLICK], "\0");
8316 middle_click_key = (middle_click_env[0] == '^' && middle_click_env[1])
8317 ? CONTROL(middle_click_env[1])
8318 : (uchar_t)middle_click_env[0];
8321 const char * const env_opts = xgetenv(env_cfg[NNN_OPTS], NULL);
8322 int env_opts_id = env_opts ? (int)xstrlen(env_opts) : -1;
8324 bool rlhist = FALSE;
8327 while ((opt = (env_opts_id > 0
8328 ? env_opts[--env_opts_id]
8329 : getopt(argc, argv, "aAb:cCdDeEfF:gHiJKl:nop:P:QrRs:St:T:uUVxh"))) != -1) {
8333 g_state.autofifo = 1;
8340 if (env_opts_id < 0)
8347 g_state.oldcolor = 1;
8368 if (env_opts_id < 0) {
8370 if ((fd < 0) || (fd > 1))
8371 return EXIT_FAILURE;
8372 g_state.fifomode = fd;
8378 filterfn = &visible_re;
8387 g_state.stayonsel = 1;
8390 check_key_collision();
8391 return EXIT_SUCCESS;
8393 if (env_opts_id < 0)
8394 scroll_lines = atoi(optarg);
8403 if (env_opts_id >= 0)
8407 if (!(optarg[0] == '-' && optarg[1] == '\0')) {
8408 fd = open(optarg, O_WRONLY | O_CREAT, 0600);
8411 return EXIT_FAILURE;
8415 selpath = abspath(optarg, NULL, NULL);
8420 if (env_opts_id < 0 && !optarg[1])
8421 pkey = (uchar_t)optarg[0];
8424 g_state.forcequit = 1;
8428 cp[2] = cp[5] = mv[2] = mv[5] = 'g'; /* cp -iRp -> cpg -giRp */
8429 cp[4] = mv[4] = '-';
8437 if (env_opts_id < 0)
8441 g_state.prstssn = 1;
8442 if (!session) /* Support named persistent sessions */
8447 if (env_opts_id < 0)
8448 idletimeout = atoi(optarg);
8451 if (env_opts_id < 0)
8452 sort = (uchar_t)optarg[0];
8461 dprintf(STDOUT_FILENO, "%s\n", VERSION);
8462 return EXIT_SUCCESS;
8468 return EXIT_SUCCESS;
8471 return EXIT_FAILURE;
8473 if (env_opts_id == 0)
8482 /* Prefix for temporary files */
8483 if (!set_tmp_path())
8484 return EXIT_FAILURE;
8488 /* Check if we are in path list mode */
8489 if (!isatty(STDIN_FILENO)) {
8490 /* This is the same as listpath */
8491 initpath = load_input(STDIN_FILENO, NULL);
8493 return EXIT_FAILURE;
8495 /* We return to tty */
8496 if (!isatty(STDOUT_FILENO)) {
8497 fd = open(ctermid(NULL), O_RDONLY, 0400);
8498 dup2(fd, STDIN_FILENO);
8501 dup2(STDOUT_FILENO, STDIN_FILENO);
8507 home = getenv("HOME");
8510 return EXIT_FAILURE;
8513 homelen = (uchar_t)xstrlen(home);
8515 if (!setup_config())
8516 return EXIT_FAILURE;
8518 /* Get custom opener, if set */
8519 opener = xgetenv(env_cfg[NNN_OPENER], utils[UTIL_OPENER]);
8522 /* Parse bookmarks string */
8523 if (!parsekvpair(&bookmark, &bmstr, NNN_BMS, &maxbm)) {
8524 msg(env_cfg[NNN_BMS]);
8525 return EXIT_FAILURE;
8528 /* Parse plugins string */
8529 if (!parsekvpair(&plug, &pluginstr, NNN_PLUG, &maxplug)) {
8530 msg(env_cfg[NNN_PLUG]);
8531 return EXIT_FAILURE;
8534 /* Parse order string */
8535 if (!parsekvpair(&order, &orderstr, NNN_ORDER, &maxorder)) {
8536 msg(env_cfg[NNN_ORDER]);
8537 return EXIT_FAILURE;
8541 if (arg) { /* Open a bookmark directly */
8542 if (!arg[1]) /* Bookmarks keys are single char */
8543 initpath = get_kv_val(bookmark, NULL, *arg, maxbm, NNN_BMS);
8546 msg(messages[MSG_INVALID_KEY]);
8547 return EXIT_FAILURE;
8552 } else if (argc == optind) {
8553 /* Start in the current directory */
8554 char *startpath = getenv("PWD");
8556 initpath = startpath ? xstrdup(startpath) : getcwd(NULL, 0);
8562 if (xstrlen(arg) > 7 && is_prefix(arg, "file://", 7))
8564 initpath = abspath(arg, NULL, NULL);
8565 DPRINTF_S(initpath);
8568 return EXIT_FAILURE;
8572 * If nnn is set as the file manager, applications may try to open
8573 * files by invoking nnn. In that case pass the file path to the
8574 * desktop opener and exit.
8578 if (stat(initpath, &sb) == -1) {
8580 return EXIT_FAILURE;
8583 if (!S_ISDIR(sb.st_mode))
8584 g_state.initfile = 1;
8591 /* Set archive handling (enveditor used as tmp var) */
8592 enveditor = getenv(env_cfg[NNN_ARCHIVE]);
8594 if (setfilter(&archive_pcre, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8596 if (setfilter(&archive_re, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8598 msg(messages[MSG_INVALID_REG]);
8599 return EXIT_FAILURE;
8602 /* An all-CLI opener overrides option -e) */
8606 /* Get VISUAL/EDITOR */
8607 enveditor = xgetenv(envs[ENV_EDITOR], utils[UTIL_VI]);
8608 editor = xgetenv(envs[ENV_VISUAL], enveditor);
8609 DPRINTF_S(getenv(envs[ENV_VISUAL]));
8610 DPRINTF_S(getenv(envs[ENV_EDITOR]));
8614 pager = xgetenv(envs[ENV_PAGER], utils[UTIL_LESS]);
8618 shell = xgetenv(envs[ENV_SHELL], utils[UTIL_SH]);
8621 DPRINTF_S(getenv("PWD"));
8625 if (g_state.autofifo) {
8626 g_tmpfpath[tmpfplen - 1] = '\0';
8628 size_t r = mkpath(g_tmpfpath, "nnn-fifo.", g_buf);
8630 xstrsncpy(g_buf + r - 1, xitoa(getpid()), PATH_MAX - r);
8631 setenv("NNN_FIFO", g_buf, TRUE);
8634 fifopath = xgetenv("NNN_FIFO", NULL);
8636 if (mkfifo(fifopath, 0600) != 0 && !(errno == EEXIST && access(fifopath, W_OK) == 0)) {
8638 return EXIT_FAILURE;
8641 sigaction(SIGPIPE, &(struct sigaction){.sa_handler = SIG_IGN}, NULL);
8645 #ifdef LINUX_INOTIFY
8646 /* Initialize inotify */
8647 inotify_fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
8648 if (inotify_fd < 0) {
8650 return EXIT_FAILURE;
8652 #elif defined(BSD_KQUEUE)
8656 return EXIT_FAILURE;
8658 #elif defined(HAIKU_NM)
8659 haiku_hnd = haiku_init_nm();
8662 return EXIT_FAILURE;
8666 /* Configure trash preference */
8667 opt = xgetenv_val(env_cfg[NNN_TRASH]);
8668 if (opt && opt <= 2)
8669 g_state.trash = opt;
8671 /* Ignore/handle certain signals */
8672 struct sigaction act = {.sa_handler = sigint_handler};
8674 if (sigaction(SIGINT, &act, NULL) < 0) {
8676 return EXIT_FAILURE;
8679 act.sa_handler = clean_exit_sighandler;
8681 if (sigaction(SIGTERM, &act, NULL) < 0 || sigaction(SIGHUP, &act, NULL) < 0) {
8683 return EXIT_FAILURE;
8686 act.sa_handler = SIG_IGN;
8688 if (sigaction(SIGQUIT, &act, NULL) < 0) {
8690 return EXIT_FAILURE;
8695 setlocale(LC_ALL, "");
8697 tables = pcre_maketables();
8702 #if RL_READLINE_VERSION >= 0x0603
8703 /* readline would overwrite the WINCH signal hook */
8704 rl_change_environment = 0;
8706 /* Bind TAB to cycling */
8707 rl_variable_bind("completion-ignore-case", "on");
8709 rl_bind_key('\t', rl_menu_complete);
8711 rl_bind_key('\t', rl_complete);
8714 mkpath(cfgpath, ".history", g_buf);
8715 read_history(g_buf);
8720 if (cfg.x11 && !g_state.picker) {
8721 /* Save terminal window title */
8722 printf("\033[22;0t");
8724 gethostname(hostname, sizeof(hostname));
8725 hostname[sizeof(hostname) - 1] = '\0';
8730 if (!initcurses(&mask))
8732 if (!initcurses(NULL))
8734 return EXIT_FAILURE;
8737 set_sort_flags(sort);
8739 opt = browse(initpath, session, pkey);
8742 if (session && g_state.prstssn)
8743 save_session(session, NULL);
8747 mousemask(mask, NULL);
8754 mkpath(cfgpath, ".history", g_buf);
8755 write_history(g_buf);
8759 if (g_state.picker) {
8761 fd = selpath ? open(selpath, O_WRONLY | O_CREAT | O_TRUNC, 0600) : STDOUT_FILENO;
8762 if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
8771 /* Remove tmp dir in list mode */
8774 /* Free the regex */
8776 pcre_free(archive_pcre);
8778 regfree(&archive_re);
8781 /* Free the selection buffer */
8784 #ifdef LINUX_INOTIFY
8785 /* Shutdown inotify */
8786 if (inotify_wd >= 0)
8787 inotify_rm_watch(inotify_fd, inotify_wd);
8789 #elif defined(BSD_KQUEUE)
8793 #elif defined(HAIKU_NM)
8794 haiku_close_nm(haiku_hnd);
8798 if (!g_state.fifomode)