4 * Copyright (C) 2014-2016, Lazaros Koromilas <lostd@2f30.org>
5 * Copyright (C) 2014-2016, Dimitris Papastamos <sin@2f30.org>
6 * Copyright (C) 2016-2023, Arun Prakash Jana <engineerarun@gmail.com>
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>
104 #include <stdalign.h>
105 #ifndef __USE_XOPEN_EXTENDED
106 #define __USE_XOPEN_EXTENDED 1
112 #ifdef MACOS_BELOW_1012
113 #include "../misc/macos-legacy/mach_gettime.h"
116 #if !defined(alloca) && defined(__GNUC__)
118 * GCC doesn't expand alloca() to __builtin_alloca() in standards mode
119 * (-std=...) and not all standard libraries do or supply it, e.g.
120 * NetBSD/arm64 so explicitly use the builtin.
122 #define alloca(size) __builtin_alloca(size)
128 #if defined(ICONS_IN_TERM) || defined(NERD) || defined(EMOJI)
129 #define ICONS_ENABLED
130 #include ICONS_INCLUDE
131 #include "icons-hash.c"
139 /* Macro definitions */
140 #define VERSION "4.8"
141 #define GENERAL_INFO "BSD 2-Clause\nhttps://github.com/jarun/nnn"
144 #define SESSIONS_VERSION 1
148 #define S_BLKSIZE 512 /* S_BLKSIZE is missing on Android NDK (Termux) */
152 * NAME_MAX and PATH_MAX may not exist, e.g. with dirent.c_name being a
153 * flexible array on Illumos. Use somewhat accommodating fallback values.
160 #define PATH_MAX 4096
163 #define _ABSSUB(N, M) (((N) <= (M)) ? ((M) - (N)) : ((N) - (M)))
164 #define ELEMENTS(x) (sizeof(x) / sizeof(*(x)))
166 #define MIN(x, y) ((x) < (y) ? (x) : (y))
168 #define MAX(x, y) ((x) > (y) ? (x) : (y))
169 #define ISODD(x) ((x) & 1)
170 #define ISBLANK(x) ((x) == ' ' || (x) == '\t')
171 #define TOUPPER(ch) (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
172 #define TOLOWER(ch) (((ch) >= 'A' && (ch) <= 'Z') ? ((ch) - 'A' + 'a') : (ch))
173 #define ISUPPER_(ch) ((ch) >= 'A' && (ch) <= 'Z')
174 #define ISLOWER_(ch) ((ch) >= 'a' && (ch) <= 'z')
175 #define CMD_LEN_MAX (PATH_MAX + ((NAME_MAX + 1) << 1))
176 #define ALIGN_UP(x, A) ((((x) + (A) - 1) / (A)) * (A))
177 #define READLINE_MAX 256
183 #define PROMPT ">>> "
185 #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
186 #define NAMEBUF_INCR 0x800 /* 64 dir entries at once, avg. 32 chars per file name = 64*32B = 2KB */
187 #define DESCRIPTOR_LEN 32
188 #define _ALIGNMENT 0x10 /* 16-byte alignment */
189 #define _ALIGNMENT_MASK 0xF
190 #define TMP_LEN_MAX 64
191 #define DOT_FILTER_LEN 7
192 #define ASCII_MAX 128
193 #define EXEC_ARGS_MAX 10
194 #define LIST_FILES_MAX (1 << 14) /* Support listing 16K files */
195 #define LIST_INPUT_MAX ((size_t)LIST_FILES_MAX * PATH_MAX)
197 #define COLOR_256 256
198 #define CREATE_NEW_KEY (-1)
201 #define DBLCLK_INTERVAL_NS (400000000)
202 #define XDELAY_INTERVAL_MS (350000) /* 350 ms delay */
211 /* BSDs or Solaris or SunOS */
212 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) || defined(sun) || defined(__sun)
219 /* Large selection threshold */
221 #define LARGESEL 1000
224 #define MIN_DISPLAY_COL (CTX_MAX * 2)
225 #define ARCHIVE_CMD_LEN 16
226 #define BLK_SHIFT_512 9
228 /* Detect hardlinks in du */
229 #define HASH_BITS (0xFFFFFF)
230 #define HASH_OCTETS (HASH_BITS >> 6) /* 2^6 = 64 */
233 #define DIR_OR_DIRLNK 0x01
234 #define HARD_LINK 0x02
235 #define SYM_ORPHAN 0x04
236 #define FILE_MISSING 0x08
237 #define FILE_SELECTED 0x10
238 #define FILE_SCANNED 0x20
239 #define FILE_YOUNG 0x40
241 /* Macros to define process spawn behaviour as flags */
242 #define F_NONE 0x00 /* no flag set */
243 #define F_MULTI 0x01 /* first arg can be combination of args; to be used with F_NORMAL */
244 #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
245 #define F_NOTRACE 0x04 /* suppress stdout and stderr (no traces) */
246 #define F_NORMAL 0x08 /* spawn child process in non-curses regular CLI mode */
247 #define F_CONFIRM 0x10 /* run command - show results before exit (must have F_NORMAL) */
248 #define F_CHKRTN 0x20 /* wait for user prompt if cmd returns failure status */
249 #define F_NOSTDIN 0x40 /* suppress stdin */
250 #define F_PAGE 0x80 /* page output in run-cmd-as-plugin mode */
251 #define F_TTY 0x100 /* Force stdout to go to tty if redirected to a non-tty */
252 #define F_CLI (F_NORMAL | F_MULTI)
253 #define F_SILENT (F_CLI | F_NOTRACE)
255 /* Version compare macros */
257 * states: S_N: normal, S_I: comparing integral part, S_F: comparing
258 * fractional parts, S_Z: idem but with leading Zeroes only
265 /* result_type: VCMP: return diff; VLEN: compare using len_diff/diff */
274 /* TYPE DEFINITIONS */
275 typedef unsigned int uint_t;
276 typedef unsigned char uchar_t;
277 typedef unsigned short ushort_t;
278 typedef unsigned long long ullong_t;
282 /* Directory entry */
283 typedef struct entry {
284 char *name; /* 8 bytes */
285 time_t sec; /* 8 bytes */
286 uint_t nsec; /* 4 bytes (enough to store nanosec) */
287 mode_t mode; /* 4 bytes */
288 off_t size; /* 8 bytes */
290 ullong_t blocks : 40; /* 5 bytes (enough for 512 TiB in 512B blocks allocated) */
291 ullong_t nlen : 16; /* 2 bytes (length of file name) */
292 ullong_t flags : 8; /* 1 byte (flags specific to the file) */
295 uid_t uid; /* 4 bytes */
296 gid_t gid; /* 4 bytes */
300 /* Selection marker */
306 /* Key-value pairs from env */
316 const regex_t *regex;
325 uint_t filtermode : 1; /* Set to enter filter mode */
326 uint_t timeorder : 1; /* Set to sort by time */
327 uint_t sizeorder : 1; /* Set to sort by file size */
328 uint_t apparentsz : 1; /* Set to sort by apparent size (disk usage) */
329 uint_t blkorder : 1; /* Set to sort by blocks used (disk usage) */
330 uint_t extnorder : 1; /* Order by extension */
331 uint_t showhidden : 1; /* Set to show hidden files */
332 uint_t reserved0 : 1;
333 uint_t showdetail : 1; /* Clear to show lesser file info */
334 uint_t ctxactive : 1; /* Context active or not */
335 uint_t reverse : 1; /* Reverse sort */
336 uint_t version : 1; /* Version sort */
337 uint_t reserved1 : 1;
338 /* The following settings are global */
339 uint_t curctx : 3; /* Current context number */
340 uint_t prefersel : 1; /* Prefer selection over current, if exists */
341 uint_t fileinfo : 1; /* Show file information on hover */
342 uint_t nonavopen : 1; /* Open file on right arrow or `l` */
343 uint_t autoenter : 1; /* auto-enter dir in type-to-nav mode */
344 uint_t reserved2 : 1;
345 uint_t useeditor : 1; /* Use VISUAL to open text files */
346 uint_t reserved3 : 3;
347 uint_t regex : 1; /* Use regex filters */
348 uint_t x11 : 1; /* Copy to system clipboard, show notis, xterm title */
349 uint_t timetype : 2; /* Time sort type (0: access, 1: change, 2: modification) */
350 uint_t cliopener : 1; /* All-CLI app opener */
351 uint_t waitedit : 1; /* For ops that can't be detached, used EDITOR */
352 uint_t rollover : 1; /* Roll over at edges */
355 /* Non-persistent program-internal states (alphabeical order) */
357 uint_t autofifo : 1; /* Auto-create NNN_FIFO */
358 uint_t autonext : 1; /* Auto-advance on file open */
359 uint_t dircolor : 1; /* Current status of dir color */
360 uint_t dirctx : 1; /* Show dirs in context color */
361 uint_t duinit : 1; /* Initialize disk usage */
362 uint_t fifomode : 1; /* FIFO notify mode: 0: preview, 1: explorer */
363 uint_t forcequit : 1; /* Do not prompt on quit */
364 uint_t initfile : 1; /* Positional arg is a file */
365 uint_t interrupt : 1; /* Program received an interrupt */
366 uint_t move : 1; /* Move operation */
367 uint_t oldcolor : 1; /* Use older colorscheme */
368 uint_t picked : 1; /* Plugin has picked files */
369 uint_t picker : 1; /* Write selection to user-specified file */
370 uint_t pluginit : 1; /* Plugin framework initialized */
371 uint_t prstssn : 1; /* Persistent session */
372 uint_t rangesel : 1; /* Range selection on */
373 uint_t runctx : 3; /* The context in which plugin is to be run */
374 uint_t runplugin : 1; /* Choose plugin mode */
375 uint_t selbm : 1; /* Select a bookmark from bookmarks directory */
376 uint_t selmode : 1; /* Set when selecting files */
377 uint_t stayonsel : 1; /* Disable auto-advance on selection */
378 uint_t trash : 2; /* Trash method 0: rm -rf, 1: trash-cli, 2: gio trash */
379 uint_t uidgid : 1; /* Show owner and group info */
380 uint_t usebsdtar : 1; /* Use bsdtar as default archive utility */
381 uint_t reserved : 5; /* Adjust when adding/removing a field */
384 /* Contexts or workspaces */
386 char c_path[PATH_MAX]; /* Current dir */
387 char c_last[PATH_MAX]; /* Last visited dir */
388 char c_name[NAME_MAX + 1]; /* Current file name */
389 char c_fltr[REGEX_MAX]; /* Current filter */
390 settings c_cfg; /* Current configuration */
391 uint_t color; /* Color code for directories */
397 size_t pathln[CTX_MAX];
398 size_t lastln[CTX_MAX];
399 size_t nameln[CTX_MAX];
400 size_t fltrln[CTX_MAX];
406 /* Configuration, contexts */
407 static settings cfg = {
410 .timetype = 2, /* T_MOD */
414 alignas(max_align_t) static context g_ctx[CTX_MAX];
416 static int ndents, cur, last, curscroll, last_curscroll, total_dents = ENTRY_INCR, scroll_lines = 1;
417 static int nselected;
419 static int fifofd = -1;
421 static time_t gtimesecs;
422 static uint_t idletimeout, selbufpos, selbuflen;
423 static ushort_t xlines, xcols;
424 static ushort_t idle;
425 static uchar_t maxbm, maxplug, maxorder;
426 static uchar_t cfgsort[CTX_MAX + 1];
428 static char *pluginstr;
429 static char *orderstr;
432 static char *enveditor;
436 static char *initpath;
437 static char *cfgpath;
438 static char *selpath;
439 static char *listpath;
440 static char *listroot;
441 static char *plgpath;
442 static char *pnamebuf, *pselbuf, *findselpos;
445 static char hostname[_POSIX_HOST_NAME_MAX + 1];
448 static char *fifopath;
450 static char *lastcmd;
451 static ullong_t *ihashbmp;
452 static struct entry *pdents;
453 static blkcnt_t dir_blocks;
457 static uchar_t tmpfplen, homelen;
458 static uchar_t blk_shift = BLK_SHIFT_512;
460 static int middle_click_key;
463 static pcre *archive_pcre;
465 static regex_t archive_re;
468 /* pthread related */
469 #define NUM_DU_THREADS (4) /* Can use sysconf(_SC_NPROCESSORS_ONLN) */
470 #define DU_TEST (((node->fts_info & FTS_F) && \
471 (sb->st_nlink <= 1 || test_set_bit((uint_t)sb->st_ino))) || node->fts_info & FTS_DP)
473 static int threadbmp = -1; /* Has 1 in the bit position for idle threads */
474 static volatile int active_threads;
475 static pthread_mutex_t running_mutex = PTHREAD_MUTEX_INITIALIZER;
476 static pthread_mutex_t hardlink_mutex = PTHREAD_MUTEX_INITIALIZER;
477 static ullong_t *core_files;
478 static blkcnt_t *core_blocks;
479 static ullong_t num_files;
488 static thread_data *core_data;
490 /* Retain old signal handlers */
491 static struct sigaction oldsighup;
492 static struct sigaction oldsigtstp;
493 static struct sigaction oldsigwinch;
495 /* For use in functions which are isolated and don't return the buffer */
496 alignas(max_align_t) static char g_buf[CMD_LEN_MAX];
498 /* For use as a scratch buffer in selection manipulation */
499 alignas(max_align_t) static char g_sel[PATH_MAX];
501 /* Buffer to store tmp file path to show selection, file stats and help */
502 alignas(max_align_t) static char g_tmpfpath[TMP_LEN_MAX];
504 /* Buffer to store plugins control pipe location */
505 alignas(max_align_t) static char g_pipepath[TMP_LEN_MAX];
507 /* Non-persistent runtime states */
508 static runstate g_state;
510 /* Options to identify file MIME */
511 #if defined(__APPLE__)
512 #define FILE_MIME_OPTS "-bIL"
513 #elif !defined(__sun) /* no MIME option for 'file' */
514 #define FILE_MIME_OPTS "-biL"
517 /* Macros for utilities */
518 #define UTIL_OPENER 0
520 #define UTIL_BSDTAR 2
523 #define UTIL_LOCKER 5
524 #define UTIL_LAUNCH 6
525 #define UTIL_SH_EXEC 7
528 #define UTIL_RCLONE 10
536 #define UTIL_TRASH_CLI 18
537 #define UTIL_GIO_TRASH 19
538 #define UTIL_RM_RF 20
540 /* Utilities to open files, run actions */
541 static char * const utils[] = {
544 #elif defined __CYGWIN__
546 #elif defined __HAIKU__
557 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
559 #elif defined __HAIKU__
582 #define MSG_ZERO 0 /* Unused */
583 #define MSG_0_ENTRIES 1
584 #define STR_TMPFILE 2
585 #define MSG_0_SELECTED 3
588 #define MSG_SSN_NAME 6
589 #define MSG_CP_MV_AS 7
590 #define MSG_CUR_SEL_OPTS 8
591 #define MSG_FORCE_RM 9
592 #define MSG_SIZE_LIMIT 10
593 #define MSG_NEW_OPTS 11
594 #define MSG_CLI_MODE 12
595 #define MSG_OVERWRITE 13
596 #define MSG_SSN_OPTS 14
597 #define MSG_QUIT_ALL 15
598 #define MSG_HOSTNAME 16
599 #define MSG_ARCHIVE_NAME 17
600 #define MSG_OPEN_WITH 18
601 #define MSG_NEW_PATH 19
602 #define MSG_LINK_PREFIX 20
603 #define MSG_COPY_NAME 21
605 #define MSG_SEL_MISSING 23
606 #define MSG_ACCESS 24
607 #define MSG_EMPTY_FILE 25
608 #define MSG_UNSUPPORTED 26
609 #define MSG_NOT_SET 27
610 #define MSG_EXISTS 28
611 #define MSG_FEW_COLUMNS 29
612 #define MSG_REMOTE_OPTS 30
613 #define MSG_RCLONE_DELAY 31
614 #define MSG_APP_NAME 32
615 #define MSG_ARCHIVE_OPTS 33
617 #define MSG_INVALID_REG 35
621 #define MSG_RM_TMP 39
622 #define MSG_INVALID_KEY 40
623 #define MSG_NOCHANGE 41
624 #define MSG_DIR_CHANGED 42
625 #define MSG_BM_NAME 43
626 #define MSG_FILE_LIMIT 44
628 static const char * const messages[] = {
638 "%s %s? [Esc cancels]",
639 "size limit exceeded",
640 "['f'ile]/'d'ir/'s'ym/'h'ard?",
643 "'s'ave/'l'oad/'r'estore?",
644 "Quit all contexts?",
645 "remote name (- for hovered): ",
646 "archive [path/]name: ",
649 "link prefix [@ for none]: ",
650 "copy [path/]name: ",
651 "\n'Enter' to continue",
654 "empty! edit/open with",
662 "['l's]/'o'pen/e'x'tract/'m'nt?",
665 "'a'u/'d'u/'e'xt/'r'ev/'s'z/'t'm/'v'er/'c'lr/'^T'?",
666 "unmount failed! try lazy?",
667 "first file (\')/char?",
671 "dir changed, range sel off",
673 "file limit exceeded",
676 /* Supported configuration environment variables */
682 #define NNN_FCOLORS 5
687 #define NNN_ARCHIVE 10
689 #define NNN_HELP 12 /* strings end here */
690 #define NNN_TRASH 13 /* flags begin here */
692 static const char * const env_cfg[] = {
709 /* Required environment variables */
716 static const char * const envs[] = {
730 static char cp[] = "cp -iRp";
731 static char mv[] = "mv -i";
733 static char cp[] = "cp -iRp";
734 static char mv[] = "mv -i";
737 /* Archive commands */
738 static char * const archive_cmd[] = {"atool -a", "bsdtar -acvf", "zip -r", "tar -acvf"};
740 /* Tokens used for path creation */
746 static const char * const toks[] = {
750 "plugins", /* must be the last entry */
758 #define P_ARCHIVE_CMD 4
760 static const char * const patterns[] = {
761 SED" -i 's|^\\(\\(.*/\\)\\(.*\\)$\\)|#\\1\\n\\3|' %s",
762 SED" 's|^\\([^#/][^/]\\?.*\\)$|%s/\\1|;s|^#\\(/.*\\)$|\\1|' "
763 "%s | tr '\\n' '\\0' | xargs -0 -n2 sh -c '%s \"$0\" \"$@\" < /dev/tty'",
764 "\\.(bz|bz2|gz|tar|taz|tbz|tbz2|tgz|z|zip)$", /* Basic formats that don't need external tools */
765 SED" -i 's|^%s\\(.*\\)$|%s\\1|' %s",
766 "xargs -0 %s %s < '%s'",
770 #define C_BLK (CTX_MAX + 1) /* Block device: DarkSeaGreen1 */
771 #define C_CHR (C_BLK + 1) /* Character device: Yellow1 */
772 #define C_DIR (C_CHR + 1) /* Directory: DeepSkyBlue1 */
773 #define C_EXE (C_DIR + 1) /* Executable file: Green1 */
774 #define C_FIL (C_EXE + 1) /* Regular file: Normal */
775 #define C_HRD (C_FIL + 1) /* Hard link: Plum4 */
776 #define C_LNK (C_HRD + 1) /* Symbolic link: Cyan1 */
777 #define C_MIS (C_LNK + 1) /* Missing file OR file details: Grey62 */
778 #define C_ORP (C_MIS + 1) /* Orphaned symlink: DeepPink1 */
779 #define C_PIP (C_ORP + 1) /* Named pipe (FIFO): Orange1 */
780 #define C_SOC (C_PIP + 1) /* Socket: MediumOrchid1 */
781 #define C_UND (C_SOC + 1) /* Unknown OR 0B regular/exe file: Red1 */
783 static char gcolors[] = "c1e2272e006033f7c6d6abc4";
784 static uint_t fcolors[C_UND + 1] = {0};
788 #define NUM_EVENT_SLOTS 32 /* Make room for 32 events */
789 #define EVENT_SIZE (sizeof(struct inotify_event))
790 #define EVENT_BUF_LEN (EVENT_SIZE * NUM_EVENT_SLOTS)
791 static int inotify_fd, inotify_wd = -1;
792 static uint_t INOTIFY_MASK = /* IN_ATTRIB | */ IN_CREATE | IN_DELETE | IN_DELETE_SELF
793 | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
794 #elif defined(BSD_KQUEUE)
795 #define NUM_EVENT_SLOTS 1
796 #define NUM_EVENT_FDS 1
797 static int kq, event_fd = -1;
798 static struct kevent events_to_monitor[NUM_EVENT_FDS];
799 static uint_t KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK
800 | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
801 static struct timespec gtimeout;
802 #elif defined(HAIKU_NM)
803 static bool haiku_nm_active = FALSE;
804 static haiku_nm_h haiku_hnd;
807 /* Function macros */
808 #define tolastln() move(xlines - 1, 0)
809 #define tocursor() move(cur + 2 - curscroll, 0)
810 #define exitcurses() endwin()
811 #define printwarn(presel) printwait(strerror(errno), presel)
812 #define istopdir(path) ((path)[1] == '\0' && (path)[0] == '/')
813 #define copycurname() xstrsncpy(lastname, ndents ? pdents[cur].name : "\0", NAME_MAX + 1)
814 #define settimeout() timeout(1000)
815 #define cleartimeout() timeout(-1)
816 #define errexit() printerr(__LINE__)
817 #define setdirwatch() (cfg.filtermode ? (presel = FILTER) : (watch = TRUE))
818 #define filterset() (g_ctx[cfg.curctx].c_fltr[1])
819 /* We don't care about the return value from strcmp() */
820 #define xstrcmp(a, b) (*(a) != *(b) ? -1 : strcmp((a), (b)))
821 /* A faster version of xisdigit */
822 #define xisdigit(c) ((unsigned int) (c) - '0' <= 9)
823 #define xerror() perror(xitoa(__LINE__))
826 #define ENTLESS(i, j) (entrycmpfn(pdents + (i), pdents + (j)) < 0)
827 #define ENTSWAP(i, j) (swap_ent((i), (j)))
828 #define ENTSORT(pdents, ndents, entrycmpfn) QSORT((ndents), ENTLESS, ENTSWAP)
830 #define ENTSORT(pdents, ndents, entrycmpfn) qsort((pdents), (ndents), sizeof(*(pdents)), (entrycmpfn))
833 /* Forward declarations */
834 static void redraw(char *path);
835 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag);
836 static void move_cursor(int target, int ignore_scrolloff);
837 static char *load_input(int fd, const char *path);
838 static int set_sort_flags(int r);
839 static void statusbar(char *path);
840 static bool get_output(char *file, char *arg1, char *arg2, int fdout, bool page);
842 static void notify_fifo(bool force);
847 static void sigint_handler(int sig)
850 g_state.interrupt = 1;
853 static void clean_exit_sighandler(int sig)
857 /* This triggers cleanup() thanks to atexit() */
861 static char *xitoa(uint_t val)
863 static char dst[32] = {'\0'};
864 static const char digits[201] =
865 "0001020304050607080910111213141516171819"
866 "2021222324252627282930313233343536373839"
867 "4041424344454647484950515253545556575859"
868 "6061626364656667686970717273747576777879"
869 "8081828384858687888990919293949596979899";
870 uint_t next = 30, quo, i;
874 i = (val - (quo * 100)) * 2;
876 dst[next] = digits[i + 1];
877 dst[--next] = digits[i];
881 /* Handle last 1-2 digits */
883 dst[next] = '0' + val;
886 dst[next] = digits[i + 1];
887 dst[--next] = digits[i];
893 /* Return the integer value of a char representing HEX */
894 static uchar_t xchartohex(uchar_t c)
899 if (c >= 'a' && c <= 'f')
902 if (c >= 'A' && c <= 'F')
909 * Source: https://elixir.bootlin.com/linux/latest/source/arch/alpha/include/asm/bitops.h
911 static bool test_set_bit(uint_t nr)
915 pthread_mutex_lock(&hardlink_mutex);
916 ullong_t *m = ((ullong_t *)ihashbmp) + (nr >> 6);
918 if (*m & (1 << (nr & 63))) {
919 pthread_mutex_unlock(&hardlink_mutex);
923 *m |= 1 << (nr & 63);
924 pthread_mutex_unlock(&hardlink_mutex);
930 /* Increase the limit on open file descriptors, if possible */
931 static void max_openfds(void)
935 if (!getrlimit(RLIMIT_NOFILE, &rl))
936 if (rl.rlim_cur < rl.rlim_max) {
937 rl.rlim_cur = rl.rlim_max;
938 setrlimit(RLIMIT_NOFILE, &rl);
944 * Wrapper to realloc()
945 * Frees current memory if realloc() fails and returns NULL.
947 * The *alloc() family returns aligned address: https://man7.org/linux/man-pages/man3/malloc.3.html
949 static void *xrealloc(void *pcur, size_t len)
951 void *pmem = realloc(pcur, len);
960 * Just a safe strncpy(3)
961 * Always null ('\0') terminates if both src and dest are valid pointers.
962 * Returns the number of bytes copied including terminating null byte.
964 static size_t xstrsncpy(char *restrict dst, const char *restrict src, size_t n)
966 char *end = memccpy(dst, src, '\0', n);
969 dst[n - 1] = '\0'; // NOLINT
970 end = dst + n; /* If we return n here, binary size increases due to auto-inlining */
976 static inline size_t xstrlen(const char *restrict s)
978 #if !defined(__GLIBC__)
979 return strlen(s); // NOLINT
981 return (char *)rawmemchr(s, '\0') - s; // NOLINT
985 static char *xstrdup(const char *restrict s)
987 size_t len = xstrlen(s) + 1;
988 char *ptr = malloc(len);
989 return ptr ? memcpy(ptr, s, len) : NULL;
992 static bool is_suffix(const char *restrict str, const char *restrict suffix)
997 size_t lenstr = xstrlen(str);
998 size_t lensuffix = xstrlen(suffix);
1000 if (lensuffix > lenstr)
1003 return (xstrcmp(str + (lenstr - lensuffix), suffix) == 0);
1006 static inline bool is_prefix(const char *restrict str, const char *restrict prefix, size_t len)
1008 return !strncmp(str, prefix, len);
1011 static inline bool is_bad_len_or_dir(const char *restrict path)
1013 size_t len = xstrlen(path);
1015 return ((len >= PATH_MAX) || (path[len - 1] == '/'));
1018 static char *get_cwd_entry(const char *restrict cwdpath, char *entrypath, size_t *tokenlen)
1020 size_t len = xstrlen(cwdpath);
1023 if (!is_prefix(entrypath, cwdpath, len))
1026 entrypath += len + 1; /* Add 1 for trailing / */
1027 end = strchr(entrypath, '/');
1029 *tokenlen = end - entrypath;
1031 *tokenlen = xstrlen(entrypath);
1032 DPRINTF_U(*tokenlen);
1038 * The poor man's implementation of memrchr(3).
1039 * We are only looking for '/' and '.' in this program.
1040 * And we are NOT expecting a '/' at the end.
1041 * Ideally 0 < n <= xstrlen(s).
1043 static void *xmemrchr(uchar_t *restrict s, uchar_t ch, size_t n)
1045 #if defined(__GLIBC__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
1046 return memrchr(s, ch, n);
1052 uchar_t *ptr = s + n;
1063 /* A very simplified implementation, changes path */
1064 static char *xdirname(char *path)
1066 char *base = xmemrchr((uchar_t *)path, '/', xstrlen(path));
1076 static char *xbasename(char *path)
1078 char *base = xmemrchr((uchar_t *)path, '/', xstrlen(path)); // NOLINT
1080 return base ? base + 1 : path;
1083 static inline char *xextension(const char *fname, size_t len)
1085 return xmemrchr((uchar_t *)fname, '.', len);
1090 * One-shot cache for getpwuid/getgrgid. Returns the cached name if the
1091 * provided uid is the same as the previous uid. Returns xitoa(guid) if
1092 * the guid is not found in the password database.
1094 static char *getpwname(uid_t uid)
1096 static uint_t uidcache = UINT_MAX;
1097 static char *namecache;
1099 if (uidcache != uid) {
1100 struct passwd *pw = getpwuid(uid);
1103 namecache = pw ? pw->pw_name : NULL;
1106 return namecache ? namecache : xitoa(uid);
1109 static char *getgrname(gid_t gid)
1111 static uint_t gidcache = UINT_MAX;
1112 static char *grpcache;
1114 if (gidcache != gid) {
1115 struct group *gr = getgrgid(gid);
1118 grpcache = gr ? gr->gr_name : NULL;
1121 return grpcache ? grpcache : xitoa(gid);
1125 static inline bool getutil(char *util)
1127 return spawn("which", util, NULL, NULL, F_NORMAL | F_NOTRACE) == 0;
1130 static inline bool tilde_is_home(const char *s)
1132 return s[0] == '~' && (s[1] == '\0' || s[1] == '/');
1135 static inline bool tilde_is_home_strict(const char *s)
1137 return s[0] == '~' && s[1] == '/';
1141 * Updates out with "dir/name or "/name"
1142 * Returns the number of bytes copied including the terminating NULL byte
1144 * Note: dir and out must be PATH_MAX in length to avoid macOS fault
1146 static size_t mkpath(const char *dir, const char *name, char *out)
1150 /* same rational for being strict as abspath() */
1151 if (tilde_is_home_strict(name)) { //NOLINT
1152 len = xstrsncpy(out, home, PATH_MAX);
1155 } else if (name[0] != '/') { // NOLINT
1156 /* Handle root case */
1157 len = istopdir(dir) ? 1 : xstrsncpy(out, dir, PATH_MAX);
1158 out[len - 1] = '/'; // NOLINT
1160 return (xstrsncpy(out + len, name, PATH_MAX - len) + len);
1163 /* Assumes both the paths passed are directories */
1164 static char *common_prefix(const char *path, char *prefix)
1166 const char *x = path, *y = prefix;
1169 if (!path || !*path || !prefix)
1173 xstrsncpy(prefix, path, PATH_MAX);
1177 while (*x && *y && (*x == *y))
1180 /* Strings are same */
1184 /* Path is shorter */
1185 if (!*x && *y == '/') {
1186 xstrsncpy(prefix, path, y - path);
1190 /* Prefix is shorter */
1191 if (!*y && *x == '/')
1194 /* Shorten prefix */
1195 prefix[y - prefix] = '\0';
1197 sep = xmemrchr((uchar_t *)prefix, '/', y - prefix);
1207 * The library function realpath() resolves symlinks.
1208 * If there's a symlink in file list we want to show the symlink not what it's points to.
1209 * Resolves ./../~ in filepath
1211 static char *abspath(const char *filepath, char *cwd, char *buf)
1213 const char *path = filepath;
1214 bool allocated = FALSE;
1219 /* when dealing with tilde, we need to be strict.
1220 * otherwise a file named "~" can end up expanding to
1221 * $HOME and causing disaster */
1222 if (tilde_is_home_strict(path)) {
1224 path += 2; /* advance 2 bytes past the "~/" */
1225 } else if ((path[0] != '/') && !cwd) {
1226 cwd = getcwd(NULL, 0);
1232 size_t dst_size = 0, src_size = xstrlen(path), cwd_size = cwd ? xstrlen(cwd) : 0;
1233 size_t len = src_size;
1237 * We need to add 2 chars at the end as relative paths may start with:
1239 * no separator (fd .): this needs an additional char for '/'
1241 char *resolved_path = buf ? buf : malloc(src_size + cwd_size + 2);
1243 if (!resolved_path) {
1249 /* Turn relative paths into absolute */
1250 if (path[0] != '/') {
1253 free(resolved_path);
1256 dst_size = xstrsncpy(resolved_path, cwd, cwd_size + 1) - 1;
1260 resolved_path[0] = '\0';
1263 dst = resolved_path + dst_size;
1264 for (const char *next = NULL; next != path + src_size;) {
1265 next = memchr(src, '/', len);
1267 next = path + src_size;
1269 if (next - src == 2 && src[0] == '.' && src[1] == '.') {
1270 if (dst - resolved_path) {
1271 dst = xmemrchr((uchar_t *)resolved_path, '/', dst - resolved_path);
1274 } else if (next - src == 1 && src[0] == '.') {
1276 } else if (next - src) {
1278 xstrsncpy(dst, src, next - src + 1);
1283 len = src_size - (src - path);
1286 if (*resolved_path == '\0') {
1287 resolved_path[0] = '/';
1288 resolved_path[1] = '\0';
1291 if (xstrlen(resolved_path) >= PATH_MAX) {
1293 free(resolved_path);
1299 return resolved_path;
1302 /* wraps the argument in single quotes so it can be safely fed to shell */
1303 static bool shell_escape(char *output, size_t outlen, const char *s)
1305 size_t n = xstrlen(s), w = 0;
1308 DPRINTF_S("s == output");
1312 output[w++] = '\''; /* begin single quote */
1313 for (size_t r = 0; r < n; ++r) {
1314 /* potentially too big: 4 for the single quote case, 2 from
1315 * outside the loop */
1316 if (w + 6 >= outlen)
1320 /* the only thing that has special meaning inside single
1321 * quotes are single quotes themselves. */
1323 output[w++] = '\''; /* end single quote */
1324 output[w++] = '\\'; /* put \' so it's treated as literal single quote */
1326 output[w++] = '\''; /* start single quoting again */
1333 output[w++] = '\''; /* end single quote */
1334 output[w++] = '\0'; /* nul terminator */
1338 static bool set_tilde_in_path(char *path)
1340 if (is_prefix(path, home, homelen)) {
1341 home[homelen] = path[homelen - 1];
1342 path[homelen - 1] = '~';
1349 static void reset_tilde_in_path(char *path)
1351 path[homelen - 1] = home[homelen];
1352 home[homelen] = '\0';
1356 static void xterm_cfg(char *path)
1358 if (cfg.x11 && !g_state.picker) {
1359 /* Signal CWD change to terminal */
1360 printf("\033]7;file://%s%s\033\\", hostname, path);
1362 /* Set terminal window title */
1363 bool r = set_tilde_in_path(path);
1365 printf("\033]2;%s\007", r ? &path[homelen - 1] : path);
1369 reset_tilde_in_path(path);
1374 static bool convert_tilde(const char *path, char *buf)
1376 if (tilde_is_home(path)) {
1377 ssize_t len = xstrlen(home);
1378 ssize_t loclen = xstrlen(path);
1380 xstrsncpy(buf, home, len + 1);
1381 xstrsncpy(buf + len, path + 1, loclen);
1387 static int create_tmp_file(void)
1389 xstrsncpy(g_tmpfpath + tmpfplen - 1, messages[STR_TMPFILE], TMP_LEN_MAX - tmpfplen);
1391 int fd = mkstemp(g_tmpfpath);
1394 DPRINTF_S(strerror(errno));
1400 static void msg(const char *message)
1402 dprintf(STDERR_FILENO, "%s\n", message);
1406 static void handle_key_resize(void)
1412 /* Clear the old prompt */
1413 static void clearoldprompt(void)
1416 move(xlines - 2, 0);
1421 handle_key_resize();
1425 /* Messages show up at the bottom */
1426 static inline void printmsg_nc(const char *msg)
1433 static void printmsg(const char *msg)
1435 attron(COLOR_PAIR(cfg.curctx + 1));
1437 attroff(COLOR_PAIR(cfg.curctx + 1));
1440 static void printwait(const char *msg, int *presel)
1446 xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
1450 /* Kill curses and display error before exiting */
1451 static void printerr(int linenum)
1454 perror(xitoa(linenum));
1455 if (!g_state.picker && selpath)
1461 static inline bool xconfirm(int c)
1463 return (c == 'y' || c == 'Y');
1466 static int get_input(const char *prompt)
1477 while (*ch == KEY_RESIZE) {
1491 static bool isselfileempty(void)
1495 return (stat(selpath, &sb) == -1) || (!sb.st_size);
1498 static int get_cur_or_sel(void)
1500 bool sel = (selbufpos || !isselfileempty());
1502 /* Check both local buffer and selection file for external selection */
1503 if (sel && ndents) {
1504 /* If selection is preferred and we have a local selection, return selection.
1505 * Always show the prompt in case of an external selection.
1507 if (cfg.prefersel && selbufpos)
1510 int choice = get_input(messages[MSG_CUR_SEL_OPTS]);
1512 return ((choice == 'c' || choice == 's') ? choice : 0);
1524 static void xdelay(useconds_t delay)
1530 static char confirm_force(bool selection)
1534 snprintf(str, 64, messages[MSG_FORCE_RM],
1535 g_state.trash ? utils[UTIL_GIO_TRASH] + 4 : utils[UTIL_RM_RF],
1536 (selection ? "selected" : "hovered"));
1538 int r = get_input(str);
1541 return '\0'; /* cancel */
1542 if (r == 'y' || r == 'Y')
1543 return 'f'; /* forceful for rm */
1544 return (g_state.trash ? '\0' : 'i'); /* interactive for rm */
1547 /* Writes buflen char(s) from buf to a file */
1548 static void writesel(const char *buf, const size_t buflen)
1553 int fd = open(selpath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
1556 if (write(fd, buf, buflen) != (ssize_t)buflen)
1563 static void appendfpath(const char *path, const size_t len)
1565 if ((selbufpos >= selbuflen) || ((len + 3) > (selbuflen - selbufpos))) {
1566 selbuflen += PATH_MAX;
1567 pselbuf = xrealloc(pselbuf, selbuflen);
1572 selbufpos += xstrsncpy(pselbuf + selbufpos, path, len);
1575 static void selbufrealloc(const size_t alloclen)
1577 if ((selbufpos + alloclen) > selbuflen) {
1578 selbuflen = ALIGN_UP(selbufpos + alloclen, PATH_MAX);
1579 pselbuf = xrealloc(pselbuf, selbuflen);
1585 /* Write selected file paths to fd, linefeed separated */
1586 static size_t seltofile(int fd, uint_t *pcount)
1588 uint_t lastpos, count = 0;
1589 char *pbuf = pselbuf;
1591 ssize_t len, prefixlen = 0, initlen = 0;
1599 lastpos = selbufpos - 1;
1602 prefixlen = (ssize_t)xstrlen(listroot);
1603 initlen = (ssize_t)xstrlen(listpath);
1606 while (pos <= lastpos) {
1608 len = (ssize_t)xstrlen(pbuf);
1610 if (!listpath || !is_prefix(pbuf, listpath, initlen)) {
1611 if (write(fd, pbuf, len) != len)
1614 if (write(fd, listroot, prefixlen) != prefixlen)
1616 if (write(fd, pbuf + initlen, len - initlen) != (len - initlen))
1621 if (pos <= lastpos) {
1622 if (write(fd, "\n", 1) != 1)
1636 /* List selection from selection file (another instance) */
1637 static bool listselfile(void)
1639 if (isselfileempty())
1642 snprintf(g_buf, CMD_LEN_MAX, "tr \'\\0\' \'\\n\' < %s", selpath);
1643 spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CONFIRM);
1648 /* Reset selection indicators */
1649 static void resetselind(void)
1651 for (int r = 0; r < ndents; ++r)
1652 if (pdents[r].flags & FILE_SELECTED)
1653 pdents[r].flags &= ~FILE_SELECTED;
1656 static void startselection(void)
1658 if (!g_state.selmode) {
1659 g_state.selmode = 1;
1670 static void clearselection(void)
1674 g_state.selmode = 0;
1678 static char *findinsel(char *startpos, int len)
1686 char *found = startpos;
1687 size_t buflen = selbufpos - (startpos - pselbuf);
1690 /* memmem(3): not specified in POSIX.1, but present on a number of other systems. */
1691 found = memmem(found, buflen - (found - startpos), g_sel, len);
1694 if (found == startpos || *(found - 1) == '\0')
1696 found += len; /* We found g_sel as a substring of a path, move forward */
1697 if (found >= startpos + buflen)
1702 static int markcmp(const void *va, const void *vb)
1704 const selmark *ma = (selmark*)va;
1705 const selmark *mb = (selmark*)vb;
1707 return ma->startpos - mb->startpos;
1710 /* scanselforpath() must be called before calling this */
1711 static inline void findmarkentry(size_t len, struct entry *dentp)
1713 if (!(dentp->flags & FILE_SCANNED)) {
1714 if (findinsel(findselpos, len + xstrsncpy(g_sel + len, dentp->name, dentp->nlen)))
1715 dentp->flags |= FILE_SELECTED;
1716 dentp->flags |= FILE_SCANNED;
1721 * scanselforpath() must be called before calling this
1722 * pathlen = length of path + 1 (+1 for trailing slash)
1724 static void invertselbuf(const int pathlen)
1726 size_t len, endpos, shrinklen = 0, alloclen = 0;
1727 char * const pbuf = g_sel + pathlen;
1729 int i, nmarked = 0, prev = 0;
1730 struct entry *dentp;
1732 selmark *marked = malloc(nselected * sizeof(selmark));
1739 /* First pass: inversion */
1740 for (i = 0; i < ndents; ++i) {
1743 if (dentp->flags & FILE_SCANNED) {
1744 if (dentp->flags & FILE_SELECTED) {
1745 dentp->flags ^= FILE_SELECTED; /* Clear selection status */
1748 dentp->flags |= FILE_SELECTED;
1749 alloclen += pathlen + dentp->nlen;
1752 dentp->flags |= FILE_SCANNED;
1757 len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1758 found = findinsel(findselpos, len);
1760 if (findselpos == found)
1763 if (nmarked && (found
1764 == (marked[nmarked - 1].startpos + marked[nmarked - 1].len)))
1765 marked[nmarked - 1].len += len;
1767 marked[nmarked].startpos = found;
1768 marked[nmarked].len = len;
1773 shrinklen += len; /* buffer size adjustment */
1775 dentp->flags |= FILE_SELECTED;
1776 alloclen += pathlen + dentp->nlen;
1783 * Files marked for deselection could be found in arbitrary order.
1784 * Sort by appearance in selection buffer.
1785 * With entries sorted we can merge adjacent ones allowing us to
1786 * move them in a single go.
1788 qsort(marked, nmarked, sizeof(selmark), &markcmp);
1790 /* Some files might be adjacent. Merge them into a single entry */
1791 for (i = 1; i < nmarked; ++i) {
1792 if (marked[i].startpos == marked[prev].startpos + marked[prev].len)
1793 marked[prev].len += marked[i].len;
1796 marked[prev].startpos = marked[i].startpos;
1797 marked[prev].len = marked[i].len;
1802 * Number of entries is increased by encountering a non-adjacent entry
1803 * After we finish the loop we should increment it once more.
1806 if (nmarked) /* Make sure there is something to deselect */
1809 /* Using merged entries remove unselected chunks from selection buffer */
1810 for (i = 0; i < nmarked; ++i) {
1812 * found: points to where the current block starts
1813 * variable is recycled from previous for readability
1814 * endpos: points to where the the next block starts
1815 * area between the end of current block (found + len)
1816 * and endpos is selected entries. This is what we are
1819 found = marked[i].startpos;
1820 endpos = (i + 1 == nmarked ? selbufpos : marked[i + 1].startpos - pselbuf);
1821 len = marked[i].len;
1823 /* Move back only selected entries. No selected memory is moved twice */
1824 memmove(found, found + len, endpos - (found + len - pselbuf));
1829 /* Buffer size adjustment */
1830 selbufpos -= shrinklen;
1832 selbufrealloc(alloclen);
1834 /* Second pass: append newly selected to buffer */
1835 for (i = 0; i < ndents; ++i) {
1836 if (pdents[i].flags & FILE_SELECTED) {
1837 len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1838 appendfpath(g_sel, len);
1843 nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1847 * scanselforpath() must be called before calling this
1848 * pathlen = length of path + 1 (+1 for trailing slash)
1850 static void addtoselbuf(const int pathlen, int startid, int endid)
1853 size_t len, alloclen = 0;
1854 struct entry *dentp;
1856 char * const pbuf = g_sel + pathlen;
1858 /* Remember current selection buffer position */
1859 for (i = startid; i <= endid; ++i) {
1863 len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1864 found = findinsel(findselpos, len);
1866 dentp->flags |= (FILE_SCANNED | FILE_SELECTED);
1867 if (found == findselpos) {
1869 if (findselpos == (pselbuf + selbufpos))
1873 alloclen += pathlen + dentp->nlen;
1875 alloclen += pathlen + dentp->nlen;
1878 selbufrealloc(alloclen);
1880 for (i = startid; i <= endid; ++i) {
1881 if (!(pdents[i].flags & FILE_SELECTED)) {
1882 len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1883 appendfpath(g_sel, len);
1885 pdents[i].flags |= (FILE_SCANNED | FILE_SELECTED);
1889 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
1892 /* Removes g_sel from selbuf */
1893 static void rmfromselbuf(size_t len)
1895 char *found = findinsel(findselpos, len);
1899 memmove(found, found + len, selbufpos - (found + len - pselbuf));
1902 nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1905 static int scanselforpath(const char *path, bool getsize)
1907 if (!path[1]) { /* path should always be at least two bytes (including NULL) */
1909 findselpos = pselbuf;
1910 return 1; /* Length of '/' is 1 */
1913 size_t off = xstrsncpy(g_sel, path, PATH_MAX);
1915 g_sel[off - 1] = '/';
1917 * We set findselpos only here. Directories can be listed in arbitrary order.
1918 * This is the best best we can do for remembering position.
1920 findselpos = findinsel(NULL, off);
1924 return (findselpos ? off : 0);
1927 /* Finish selection procedure before an operation */
1928 static void endselection(bool endselmode)
1932 char buf[sizeof(patterns[P_REPLACE]) + PATH_MAX + (TMP_LEN_MAX << 1)];
1934 if (endselmode && g_state.selmode)
1935 g_state.selmode = 0;
1937 /* The code below is only for listing mode */
1938 if (!listpath || !selbufpos)
1941 fd = create_tmp_file();
1943 DPRINTF_S("couldn't create tmp file");
1947 seltofile(fd, NULL);
1949 DPRINTF_S(strerror(errno));
1954 snprintf(buf, sizeof(buf), patterns[P_REPLACE], listpath, listroot, g_tmpfpath);
1955 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
1957 fd = open(g_tmpfpath, O_RDONLY);
1959 DPRINTF_S(strerror(errno));
1961 if (unlink(g_tmpfpath)) {
1962 DPRINTF_S(strerror(errno));
1968 count = read(fd, pselbuf, selbuflen);
1970 DPRINTF_S(strerror(errno));
1972 if (close(fd) || unlink(g_tmpfpath)) {
1973 DPRINTF_S(strerror(errno));
1978 if (close(fd) || unlink(g_tmpfpath)) {
1979 DPRINTF_S(strerror(errno));
1985 pselbuf[--count] = '\0';
1986 for (--count; count > 0; --count)
1987 if (pselbuf[count] == '\n' && pselbuf[count+1] == '/')
1988 pselbuf[count] = '\0';
1990 writesel(pselbuf, selbufpos - 1);
1993 /* Returns: 1 - success, 0 - none selected, -1 - other failure */
1994 static int editselection(void)
2002 if (!selbufpos) /* External selection is only editable at source */
2003 return listselfile();
2005 fd = create_tmp_file();
2007 DPRINTF_S("couldn't create tmp file");
2011 seltofile(fd, NULL);
2013 DPRINTF_S(strerror(errno));
2017 /* Save the last modification time */
2018 if (stat(g_tmpfpath, &sb)) {
2019 DPRINTF_S(strerror(errno));
2023 mtime = sb.st_mtime;
2025 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2027 fd = open(g_tmpfpath, O_RDONLY);
2029 DPRINTF_S(strerror(errno));
2036 if (mtime == sb.st_mtime) {
2037 DPRINTF_S("selection is not modified");
2042 if (sb.st_size > selbufpos) {
2043 DPRINTF_S("edited buffer larger than previous");
2048 count = read(fd, pselbuf, selbuflen);
2050 DPRINTF_S(strerror(errno));
2052 if (close(fd) || unlink(g_tmpfpath)) {
2053 DPRINTF_S(strerror(errno));
2059 if (close(fd) || unlink(g_tmpfpath)) {
2060 DPRINTF_S(strerror(errno));
2072 /* The last character should be '\n' */
2073 pselbuf[--count] = '\0';
2074 for (--count; count > 0; --count) {
2075 /* Replace every '\n' that separates two paths */
2076 if (pselbuf[count] == '\n' && pselbuf[count + 1] == '/') {
2078 pselbuf[count] = '\0';
2082 /* Add a line for the last file */
2085 if (lines > nselected) {
2086 DPRINTF_S("files added to selection");
2091 writesel(pselbuf, selbufpos - 1);
2101 static bool selsafe(void)
2103 /* Fail if selection file path not generated */
2105 printmsg(messages[MSG_SEL_MISSING]);
2109 /* Fail if selection file path isn't accessible */
2110 if (access(selpath, R_OK | W_OK) == -1) {
2111 errno == ENOENT ? printmsg(messages[MSG_0_SELECTED]) : printwarn(NULL);
2118 static void export_file_list(void)
2123 struct entry *pdent = pdents;
2124 int fd = create_tmp_file();
2127 DPRINTF_S(strerror(errno));
2131 for (int r = 0; r < ndents; ++pdent, ++r) {
2132 if (write(fd, pdent->name, pdent->nlen - 1) != (pdent->nlen - 1))
2135 if ((r != ndents - 1) && (write(fd, "\n", 1) != 1))
2140 DPRINTF_S(strerror(errno));
2143 spawn(editor, g_tmpfpath, NULL, NULL, F_CLI);
2145 if (xconfirm(get_input(messages[MSG_RM_TMP])))
2149 static bool init_fcolors(void)
2151 char *f_colors = getenv(env_cfg[NNN_FCOLORS]);
2153 if (!f_colors || !*f_colors)
2156 for (uchar_t id = C_BLK; *f_colors && id <= C_UND; ++id) {
2157 fcolors[id] = xchartohex(*f_colors) << 4;
2159 fcolors[id] += xchartohex(*f_colors);
2161 init_pair(id, fcolors[id], -1);
2170 /* Initialize curses mode */
2171 static bool initcurses(void *oldmask)
2177 if (g_state.picker) {
2178 if (!newterm(NULL, stderr, stdin)) {
2182 } else if (!initscr()) {
2184 DPRINTF_S(getenv("TERM"));
2191 //intrflush(stdscr, FALSE);
2192 keypad(stdscr, TRUE);
2194 #if NCURSES_MOUSE_VERSION <= 1
2195 mousemask(BUTTON1_PRESSED | BUTTON1_DOUBLE_CLICKED | BUTTON2_PRESSED | BUTTON3_PRESSED,
2196 (mmask_t *)oldmask);
2198 mousemask(BUTTON1_PRESSED | BUTTON2_PRESSED | BUTTON3_PRESSED | BUTTON4_PRESSED
2199 | BUTTON5_PRESSED, (mmask_t *)oldmask);
2203 curs_set(FALSE); /* Hide cursor */
2205 char *colors = getenv(env_cfg[NNN_COLORS]);
2207 if (colors || !getenv("NO_COLOR")) {
2212 use_default_colors();
2214 /* Initialize file colors */
2215 if (COLORS >= COLOR_256) {
2216 if (!(g_state.oldcolor || init_fcolors())) {
2218 msg(env_cfg[NNN_FCOLORS]);
2222 g_state.oldcolor = 1;
2225 DPRINTF_D(COLOR_PAIRS);
2227 if (colors && *colors == '#') {
2228 char *sep = strchr(colors, ';');
2230 if (!g_state.oldcolor && COLORS >= COLOR_256) {
2235 * If fallback colors are specified, set the separator
2236 * to NULL so we don't interpret separator and fallback
2237 * if fewer than CTX_MAX xterm 256 colors are specified.
2242 colors = sep; /* Detect if 8 colors fallback is appended */
2248 /* Get and set the context colors */
2249 for (uchar_t i = 0; i < CTX_MAX; ++i) {
2250 pcode = &g_ctx[i].color;
2252 if (colors && *colors) {
2254 *pcode = xchartohex(*colors) << 4;
2256 fcolors[i + 1] = *pcode += xchartohex(*colors);
2257 else { /* Each color code must be 2 hex symbols */
2259 msg(env_cfg[NNN_COLORS]);
2263 *pcode = (*colors < '0' || *colors > '7') ? 4 : *colors - '0';
2268 init_pair(i + 1, *pcode, -1);
2271 #ifdef ICONS_ENABLED
2272 if (!g_state.oldcolor) {
2273 for (uint_t i = 0; i < ELEMENTS(init_colors); ++i)
2274 init_pair(C_UND + 1 + init_colors[i], init_colors[i], -1);
2278 settimeout(); /* One second */
2283 /* No NULL check here as spawn() guards against it */
2284 static char *parseargs(char *cmd, char **argv, int *pindex)
2287 size_t len = xstrlen(cmd) + 1;
2288 char *line = (char *)malloc(len);
2291 DPRINTF_S("malloc()!");
2295 xstrsncpy(line, cmd, len);
2296 argv[count++] = line;
2299 while (*line) { // NOLINT
2300 if (ISBLANK(*line)) {
2303 if (!*line) // NOLINT
2306 argv[count++] = line;
2307 if (count == EXEC_ARGS_MAX) {
2316 if (count == -1 || count > (EXEC_ARGS_MAX - 4)) { /* 3 args and last NULL */
2319 DPRINTF_S("NULL or too many args");
2326 static void enable_signals(void)
2328 struct sigaction dfl_act = {.sa_handler = SIG_DFL};
2330 sigaction(SIGHUP, &dfl_act, NULL);
2331 sigaction(SIGINT, &dfl_act, NULL);
2332 sigaction(SIGQUIT, &dfl_act, NULL);
2333 sigaction(SIGTSTP, &dfl_act, NULL);
2334 sigaction(SIGWINCH, &dfl_act, NULL);
2337 static pid_t xfork(uchar_t flag)
2342 /* the parent ignores the interrupt, quit and hangup signals */
2343 sigaction(SIGHUP, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsighup);
2344 sigaction(SIGTSTP, &(struct sigaction){.sa_handler = SIG_DFL}, &oldsigtstp);
2345 sigaction(SIGWINCH, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsigwinch);
2346 } else if (p == 0) {
2347 /* We create a grandchild to detach */
2348 if (flag & F_NOWAIT) {
2352 _exit(EXIT_SUCCESS);
2360 _exit(EXIT_FAILURE);
2363 /* So they can be used to stop the child */
2367 /* This is the parent waiting for the child to create grandchild */
2368 if (flag & F_NOWAIT)
2369 waitpid(p, NULL, 0);
2376 static int join(pid_t p, uchar_t flag)
2378 int status = 0xFFFF;
2380 if (!(flag & F_NOWAIT)) {
2381 /* wait for the child to exit */
2383 } while (waitpid(p, &status, 0) == -1);
2385 if (WIFEXITED(status)) {
2386 status = WEXITSTATUS(status);
2391 /* restore parent's signal handling */
2392 sigaction(SIGHUP, &oldsighup, NULL);
2393 sigaction(SIGTSTP, &oldsigtstp, NULL);
2394 sigaction(SIGWINCH, &oldsigwinch, NULL);
2400 * Spawns a child process. Behaviour can be controlled using flag.
2401 * Limited to 3 arguments to a program, flag works on bit set.
2403 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag)
2406 int status = 0, retstatus = 0xFFFF;
2407 char *argv[EXEC_ARGS_MAX] = {0};
2410 if (!file || !*file)
2413 /* Swap args if the first arg is NULL and the other 2 aren't */
2414 if (!arg1 && arg2) {
2423 if (flag & F_MULTI) {
2424 cmd = parseargs(file, argv, &status);
2428 argv[status++] = file;
2430 argv[status] = arg1;
2431 argv[++status] = arg2;
2432 argv[++status] = arg3;
2434 if (flag & F_NORMAL)
2439 /* Suppress stdout and stderr */
2440 if (flag & F_NOTRACE) {
2441 int fd = open("/dev/null", O_WRONLY, 0200);
2443 if (flag & F_NOSTDIN)
2444 dup2(fd, STDIN_FILENO);
2445 dup2(fd, STDOUT_FILENO);
2446 dup2(fd, STDERR_FILENO);
2448 } else if (flag & F_TTY) {
2449 /* If stdout has been redirected to a non-tty, force output to tty */
2450 if (!isatty(STDOUT_FILENO)) {
2451 int fd = open(ctermid(NULL), O_WRONLY, 0200);
2452 dup2(fd, STDOUT_FILENO);
2457 execvp(*argv, argv);
2458 _exit(EXIT_SUCCESS);
2460 retstatus = join(pid, flag);
2463 if ((flag & F_CONFIRM) || ((flag & F_CHKRTN) && retstatus)) {
2464 status = write(STDOUT_FILENO, messages[MSG_ENTER], xstrlen(messages[MSG_ENTER]));
2466 while ((read(STDIN_FILENO, &status, 1) > 0) && (status != '\n'));
2469 if (flag & F_NORMAL)
2478 /* Get program name from env var, else return fallback program */
2479 static char *xgetenv(const char * const name, char *fallback)
2481 char *value = getenv(name);
2483 return value && value[0] ? value : fallback;
2486 /* Checks if an env variable is set to 1 */
2487 static inline uint_t xgetenv_val(const char *name)
2489 char *str = getenv(name);
2497 /* Check if a dir exists, IS a dir, and is readable */
2498 static bool xdiraccess(const char *path)
2500 DIR *dirp = opendir(path);
2511 static bool plugscript(const char *plugin, uchar_t flags)
2513 mkpath(plgpath, plugin, g_buf);
2514 if (!access(g_buf, X_OK)) {
2515 spawn(g_buf, NULL, NULL, NULL, flags);
2522 static void opstr(char *buf, char *op)
2524 snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c '%s \"$0\" \"$@\" . < /dev/tty' < %s", op, selpath);
2527 static bool rmmulstr(char *buf)
2529 char r = confirm_force(TRUE);
2534 snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c 'rm -%cr \"$0\" \"$@\" < /dev/tty' < %s",
2537 snprintf(buf, CMD_LEN_MAX, "xargs -0 %s < %s",
2538 utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH], selpath);
2543 /* Returns TRUE if file is removed, else FALSE */
2544 static bool xrm(char * const fpath)
2546 char r = confirm_force(FALSE);
2550 if (!g_state.trash) {
2551 char rm_opts[] = "-ir";
2554 spawn("rm", rm_opts, fpath, NULL, F_NORMAL | F_CHKRTN);
2556 spawn(utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH],
2557 fpath, NULL, NULL, F_NORMAL | F_MULTI);
2559 return (access(fpath, F_OK) == -1); /* File is removed */
2562 static void xrmfromsel(char *path, char *fpath)
2565 bool selected = TRUE;
2568 if ((pdents[cur].flags & DIR_OR_DIRLNK) && scanselforpath(fpath, FALSE))
2570 else if (pdents[cur].flags & FILE_SELECTED) {
2572 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
2578 if (selected && cfg.x11)
2579 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
2583 static uint_t lines_in_file(int fd, char *buf, size_t buflen)
2588 while ((len = read(fd, buf, buflen)) > 0)
2590 count += (buf[--len] == '\n');
2592 /* For all use cases 0 linecount is considered as error */
2593 return ((len < 0) ? 0 : count);
2596 static bool cpmv_rename(int choice, const char *path)
2599 uint_t count = 0, lines = 0;
2601 char *cmd = (choice == 'c' ? cp : mv);
2602 char buf[sizeof(patterns[P_CPMVRNM]) + (MAX(sizeof(cp), sizeof(mv))) + (PATH_MAX << 1)];
2604 fd = create_tmp_file();
2608 /* selsafe() returned TRUE for this to be called */
2610 snprintf(buf, sizeof(buf), "tr '\\0' '\\n' < %s > %s", selpath, g_tmpfpath);
2611 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2613 count = lines_in_file(fd, buf, sizeof(buf));
2617 seltofile(fd, &count);
2621 snprintf(buf, sizeof(buf), patterns[P_CPMVFMT], g_tmpfpath);
2622 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2624 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2626 fd = open(g_tmpfpath, O_RDONLY);
2630 lines = lines_in_file(fd, buf, sizeof(buf));
2633 if (!lines || (2 * count != lines)) {
2634 DPRINTF_S("num mismatch");
2638 snprintf(buf, sizeof(buf), patterns[P_CPMVRNM], path, g_tmpfpath, cmd);
2639 if (!spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CHKRTN))
2648 static bool cpmvrm_selection(enum action sel, char *path)
2652 if (isselfileempty()) {
2655 printmsg(messages[MSG_0_SELECTED]);
2670 r = get_input(messages[MSG_CP_MV_AS]);
2671 if (r != 'c' && r != 'm') {
2672 printmsg(messages[MSG_INVALID_KEY]);
2676 if (!cpmv_rename(r, path)) {
2677 printmsg(messages[MSG_FAILED]);
2681 default: /* SEL_RM */
2682 if (!rmmulstr(g_buf)) {
2683 printmsg(messages[MSG_CANCEL]);
2688 if (sel != SEL_CPMVAS && spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CHKRTN)) {
2689 printmsg(messages[MSG_FAILED]);
2693 /* Clear selection */
2700 static bool batch_rename(void)
2703 uint_t count = 0, lines = 0;
2704 bool dir = FALSE, ret = FALSE;
2705 char foriginal[TMP_LEN_MAX] = {0};
2706 static const char batchrenamecmd[] = "paste -d'\n' %s %s | "SED" 'N; /^\\(.*\\)\\n\\1$/!p;d' | "
2707 "tr '\n' '\\0' | xargs -0 -n2 sh -c 'mv -i \"$0\" \"$@\" <"
2709 char buf[sizeof(batchrenamecmd) + (PATH_MAX << 1)];
2710 int i = get_cur_or_sel();
2715 if (i == 'c') { /* Rename entries in current dir */
2720 fd1 = create_tmp_file();
2724 xstrsncpy(foriginal, g_tmpfpath, xstrlen(g_tmpfpath) + 1);
2726 fd2 = create_tmp_file();
2734 for (i = 0; i < ndents; ++i)
2735 appendfpath(pdents[i].name, NAME_MAX);
2737 seltofile(fd1, &count);
2738 seltofile(fd2, NULL);
2741 if (dir) /* Don't retain dir entries in selection */
2744 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2746 /* Reopen file descriptor to get updated contents */
2747 fd2 = open(g_tmpfpath, O_RDONLY);
2751 lines = lines_in_file(fd2, buf, sizeof(buf));
2754 if (!lines || (count != lines)) {
2755 DPRINTF_S("cannot delete files");
2759 snprintf(buf, sizeof(buf), batchrenamecmd, foriginal, g_tmpfpath);
2760 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2776 static char *get_archive_cmd(const char *archive)
2780 if (!g_state.usebsdtar && getutil(utils[UTIL_ATOOL]))
2782 else if (getutil(utils[UTIL_BSDTAR]))
2784 else if (is_suffix(archive, ".zip"))
2788 return archive_cmd[i];
2791 static void archive_selection(const char *cmd, const char *archive)
2793 char *buf = malloc((xstrlen(patterns[P_ARCHIVE_CMD]) + xstrlen(cmd) + xstrlen(archive)
2794 + xstrlen(selpath)) * sizeof(char));
2796 DPRINTF_S(strerror(errno));
2801 snprintf(buf, CMD_LEN_MAX, patterns[P_ARCHIVE_CMD], cmd, archive, selpath);
2802 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CONFIRM);
2806 static void write_lastdir(const char *curpath, const char *outfile)
2810 xstrsncpy(cfgpath + xstrlen(cfgpath), "/.lastd", 8);
2812 tilde = convert_tilde(outfile, g_buf);
2814 int fd = open(outfile
2815 ? (tilde ? g_buf : outfile)
2816 : cfgpath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
2818 if (fd != -1 && shell_escape(g_buf, sizeof(g_buf), curpath)) {
2819 dprintf(fd, "cd %s", g_buf);
2825 * We assume none of the strings are NULL.
2827 * Let's have the logic to sort numeric names in numeric order.
2828 * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
2830 * If the absolute numeric values are same, we fallback to alphasort.
2832 static int xstricmp(const char * const s1, const char * const s2)
2836 long long v1 = strtoll(s1, &p1, 10);
2837 long long v2 = strtoll(s2, &p2, 10);
2839 /* Check if at least 1 string is numeric */
2840 if (s1 != p1 || s2 != p2) {
2841 /* Handle both pure numeric */
2842 if (s1 != p1 && s2 != p2) {
2850 /* Only first string non-numeric */
2854 /* Only second string non-numeric */
2859 /* Handle 1. all non-numeric and 2. both same numeric value cases */
2861 return strcoll(s1, s2);
2863 return strcasecmp(s1, s2);
2868 * Version comparison
2870 * The code for version compare is a modified version of the GLIBC
2871 * and uClibc implementation of strverscmp(). The source is here:
2872 * https://elixir.bootlin.com/uclibc-ng/latest/source/libc/string/strverscmp.c
2876 * Compare S1 and S2 as strings holding indices/version numbers,
2877 * returning less than, equal to or greater than zero if S1 is less than,
2878 * equal to or greater than S2 (for more info, see the texinfo doc).
2882 static int xstrverscasecmp(const char * const s1, const char * const s2)
2884 const uchar_t *p1 = (const uchar_t *)s1;
2885 const uchar_t *p2 = (const uchar_t *)s2;
2890 * Symbol(s) 0 [1-9] others
2891 * Transition (10) 0 (01) d (00) x
2893 static const uint8_t next_state[] = {
2895 /* S_N */ S_N, S_I, S_Z,
2896 /* S_I */ S_N, S_I, S_I,
2897 /* S_F */ S_N, S_F, S_F,
2898 /* S_Z */ S_N, S_F, S_Z
2901 alignas(max_align_t) static const int8_t result_type[] = {
2902 /* state x/x x/d x/0 d/x d/d d/0 0/x 0/d 0/0 */
2904 /* S_N */ VCMP, VCMP, VCMP, VCMP, VLEN, VCMP, VCMP, VCMP, VCMP,
2905 /* S_I */ VCMP, -1, -1, 1, VLEN, VLEN, 1, VLEN, VLEN,
2906 /* S_F */ VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP,
2907 /* S_Z */ VCMP, 1, 1, -1, VCMP, VCMP, -1, VCMP, VCMP
2918 /* Hint: '0' is a digit too. */
2919 state = S_N + ((c1 == '0') + (xisdigit(c1) != 0));
2921 while ((diff = c1 - c2) == 0) {
2925 state = next_state[state];
2930 state += (c1 == '0') + (xisdigit(c1) != 0);
2933 state = result_type[state * 3 + (((c2 == '0') + (xisdigit(c2) != 0)))]; // NOLINT
2939 while (xisdigit(*p1++))
2940 if (!xisdigit(*p2++))
2942 return xisdigit(*p2) ? -1 : diff;
2948 static int (*namecmpfn)(const char * const s1, const char * const s2) = &xstricmp;
2950 static char * (*fnstrstr)(const char *haystack, const char *needle) = &strcasestr;
2952 static const unsigned char *tables;
2953 static int pcreflags = PCRE_NO_AUTO_CAPTURE | PCRE_EXTENDED | PCRE_CASELESS | PCRE_UTF8;
2955 static int regflags = REG_NOSUB | REG_EXTENDED | REG_ICASE;
2959 static int setfilter(pcre **pcrex, const char *filter)
2961 const char *errstr = NULL;
2964 *pcrex = pcre_compile(filter, pcreflags, &errstr, &erroffset, tables);
2966 return errstr ? -1 : 0;
2969 static int setfilter(regex_t *regex, const char *filter)
2971 return regcomp(regex, filter, regflags);
2975 static int visible_re(const fltrexp_t *fltrexp, const char *fname)
2978 return pcre_exec(fltrexp->pcrex, NULL, fname, xstrlen(fname), 0, 0, NULL, 0) == 0;
2980 return regexec(fltrexp->regex, fname, 0, NULL, 0) == 0;
2984 static int visible_str(const fltrexp_t *fltrexp, const char *fname)
2986 return fnstrstr(fname, fltrexp->str) != NULL;
2989 static int (*filterfn)(const fltrexp_t *fltr, const char *fname) = &visible_str;
2991 static void clearfilter(void)
2993 char *fltr = g_ctx[cfg.curctx].c_fltr;
2996 fltr[REGEX_MAX - 1] = fltr[1];
3001 static int entrycmp(const void *va, const void *vb)
3003 const struct entry *pa = (pEntry)va;
3004 const struct entry *pb = (pEntry)vb;
3006 if ((pb->flags & DIR_OR_DIRLNK) != (pa->flags & DIR_OR_DIRLNK)) {
3007 if (pb->flags & DIR_OR_DIRLNK)
3012 /* Sort based on specified order */
3013 if (cfg.timeorder) {
3014 if (pb->sec > pa->sec)
3016 if (pb->sec < pa->sec)
3018 /* If sec matches, comare nsec */
3019 if (pb->nsec > pa->nsec)
3021 if (pb->nsec < pa->nsec)
3023 } else if (cfg.sizeorder) {
3024 if (pb->size > pa->size)
3026 if (pb->size < pa->size)
3028 } else if (cfg.blkorder) {
3029 if (pb->blocks > pa->blocks)
3031 if (pb->blocks < pa->blocks)
3033 } else if (cfg.extnorder && !(pb->flags & DIR_OR_DIRLNK)) {
3034 char *extna = xextension(pa->name, pa->nlen - 1);
3035 char *extnb = xextension(pb->name, pb->nlen - 1);
3037 if (extna || extnb) {
3044 int ret = strcasecmp(extna, extnb);
3051 return namecmpfn(pa->name, pb->name);
3054 static int reventrycmp(const void *va, const void *vb)
3056 if ((((pEntry)vb)->flags & DIR_OR_DIRLNK)
3057 != (((pEntry)va)->flags & DIR_OR_DIRLNK)) {
3058 if (((pEntry)vb)->flags & DIR_OR_DIRLNK)
3063 return -entrycmp(va, vb);
3066 static int (*entrycmpfn)(const void *va, const void *vb) = &entrycmp;
3068 /* In case of an error, resets *wch to Esc */
3069 static int handle_alt_key(wint_t *wch)
3073 int r = get_wch(wch);
3082 static inline int handle_event(void)
3084 if (nselected && isselfileempty())
3086 return CONTROL('L');
3090 * Returns SEL_* if key is bound and 0 otherwise.
3091 * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
3092 * The next keyboard input can be simulated by presel.
3094 static int nextsel(int presel)
3101 bool escaped = FALSE;
3103 if (c == 0 || c == MSGWAIT) {
3107 //DPRINTF_S(keyname(c));
3110 if (c == KEY_RESIZE)
3111 handle_key_resize();
3114 /* Handle Alt+key */
3126 } else if (escaped) {
3131 if (!g_state.fifomode)
3132 notify_fifo(TRUE); /* Send hovered path to NNN_FIFO */
3140 if (i == ERR && presel == MSGWAIT)
3141 c = (cfg.filtermode || filterset()) ? FILTER : CONTROL('L');
3142 else if (c == FILTER || c == CONTROL('L'))
3143 /* Clear previous filter when manually starting */
3151 * Do not check for directory changes in du mode.
3152 * A redraw forces du calculation.
3153 * Check for changes every odd second.
3155 #ifdef LINUX_INOTIFY
3156 if (!cfg.blkorder && inotify_wd >= 0 && (idle & 1)) {
3157 struct inotify_event *event;
3158 char inotify_buf[EVENT_BUF_LEN] = {0};
3160 i = read(inotify_fd, inotify_buf, EVENT_BUF_LEN);
3162 for (char *ptr = inotify_buf;
3163 ptr + ((struct inotify_event *)ptr)->len < inotify_buf + i;
3164 ptr += sizeof(struct inotify_event) + event->len) {
3165 event = (struct inotify_event *)ptr;
3166 DPRINTF_D(event->wd);
3167 DPRINTF_D(event->mask);
3171 if (event->mask & INOTIFY_MASK) {
3176 DPRINTF_S("inotify read done");
3179 #elif defined(BSD_KQUEUE)
3180 if (!cfg.blkorder && event_fd >= 0 && (idle & 1)) {
3181 struct kevent event_data[NUM_EVENT_SLOTS] = {0};
3183 if (kevent(kq, events_to_monitor, NUM_EVENT_SLOTS,
3184 event_data, NUM_EVENT_FDS, >imeout) > 0)
3187 #elif defined(HAIKU_NM)
3188 if (!cfg.blkorder && haiku_nm_active && (idle & 1) && haiku_is_update_needed(haiku_hnd))
3194 for (i = 0; i < (int)ELEMENTS(bindings); ++i)
3195 if (c == bindings[i].sym)
3196 return bindings[i].act;
3201 static int getorderstr(char *sort)
3209 sort[i++] = (cfg.timetype == T_MOD) ? 'M' : ((cfg.timetype == T_ACCESS) ? 'A' : 'C');
3210 else if (cfg.sizeorder)
3212 else if (cfg.extnorder)
3215 if (entrycmpfn == &reventrycmp)
3218 if (namecmpfn == &xstrverscasecmp)
3227 static void showfilterinfo(void)
3230 char info[REGEX_MAX] = "\0\0\0\0\0";
3232 i = getorderstr(info);
3234 if (cfg.fileinfo && ndents && get_output("file", "-b", pdents[cur].name, -1, FALSE))
3235 mvaddstr(xlines - 2, 2, g_buf);
3237 snprintf(info + i, REGEX_MAX - i - 1, " %s [/], %4s [:]",
3238 (cfg.regex ? "reg" : "str"),
3239 ((fnstrstr == &strcasestr) ? "ic" : "noic"));
3242 mvaddstr(xlines - 2, xcols - xstrlen(info), info);
3245 static void showfilter(char *str)
3247 attron(COLOR_PAIR(cfg.curctx + 1));
3250 // printmsg calls attroff()
3253 static inline void swap_ent(int id1, int id2)
3255 struct entry _dent, *pdent1 = &pdents[id1], *pdent2 = &pdents[id2];
3257 *(&_dent) = *pdent1;
3259 *pdent2 = *(&_dent);
3263 static int fill(const char *fltr, pcre *pcrex)
3265 static int fill(const char *fltr, regex_t *re)
3269 fltrexp_t fltrexp = { .pcrex = pcrex, .str = fltr };
3271 fltrexp_t fltrexp = { .regex = re, .str = fltr };
3274 for (int count = 0; count < ndents; ++count) {
3275 if (filterfn(&fltrexp, pdents[count].name) == 0) {
3276 if (count != --ndents) {
3277 swap_ent(count, ndents);
3288 static int matches(const char *fltr)
3294 if (cfg.regex && setfilter(&pcrex, fltr))
3297 ndents = fill(fltr, pcrex);
3305 if (cfg.regex && setfilter(&re, fltr))
3308 ndents = fill(fltr, &re);
3314 ENTSORT(pdents, ndents, entrycmpfn);
3320 * Return the position of the matching entry or 0 otherwise
3321 * Note there's no NULL check for fname
3323 static int dentfind(const char *fname, int n)
3325 for (int i = 0; i < n; ++i)
3326 if (xstrcmp(fname, pdents[i].name) == 0)
3332 static int filterentries(char *path, char *lastname)
3334 alignas(max_align_t) wchar_t wln[REGEX_MAX];
3335 char *ln = g_ctx[cfg.curctx].c_fltr;
3337 int r, total = ndents, len;
3338 char *pln = g_ctx[cfg.curctx].c_fltr + 1;
3340 DPRINTF_S(__func__);
3342 if (ndents && (ln[0] == FILTER || ln[0] == RFILTER) && *pln) {
3343 if (matches(pln) != -1) {
3344 move_cursor(dentfind(lastname, ndents), 0);
3348 if (!cfg.filtermode) {
3353 len = mbstowcs(wln, ln, REGEX_MAX);
3355 ln[0] = wln[0] = cfg.regex ? RFILTER : FILTER;
3356 ln[1] = wln[1] = '\0';
3364 while ((r = get_wch(ch)) != ERR) {
3366 //DPRINTF_S(keyname(*ch));
3370 case 0: // fallthrough
3377 case KEY_DC: // fallthrough
3378 case KEY_BACKSPACE: // fallthrough
3379 case '\b': // fallthrough
3380 case DEL: /* handle DEL */
3383 wcstombs(ln, wln, REGEX_MAX);
3391 if (*ch == CONTROL('L')) {
3393 ln[REGEX_MAX - 1] = ln[1];
3394 ln[1] = wln[1] = '\0';
3397 } else if (ln[REGEX_MAX - 1]) { /* Show the previous filter */
3398 ln[1] = ln[REGEX_MAX - 1];
3399 ln[REGEX_MAX - 1] = '\0';
3400 len = mbstowcs(wln, ln, REGEX_MAX);
3405 /* Go to the top, we don't know if the hovered file will match the filter */
3408 if (matches(pln) != -1)
3418 if (handle_alt_key(ch) != ERR) {
3419 if (*ch == ESC) /* Handle Alt+Esc */
3420 *ch = 'q'; /* Quit context */
3423 *ch = ';'; /* Run plugin */
3429 if (r != OK) /* Handle Fn keys in main loop */
3432 /* Handle all control chars in main loop */
3433 if (*ch < ASCII_MAX && keyname(*ch)[0] == '^' && *ch != '^')
3437 if (*ch == '?') /* Help and config key, '?' is an invalid regex */
3440 if (cfg.filtermode) {
3442 case '\'': // fallthrough /* Go to first non-dir file */
3443 case '+': // fallthrough /* Toggle file selection */
3444 case ',': // fallthrough /* Mark CWD */
3445 case '-': // fallthrough /* Visit last visited dir */
3446 case '.': // fallthrough /* Show hidden files */
3447 case ';': // fallthrough /* Run plugin key */
3448 case '=': // fallthrough /* Launch app */
3449 case '>': // fallthrough /* Export file list */
3450 case '@': // fallthrough /* Visit start dir */
3451 case ']': // fallthorugh /* Prompt key */
3452 case '`': // fallthrough /* Visit / */
3453 case '~': /* Go HOME */
3458 /* Toggle case-sensitivity */
3460 fnstrstr = (fnstrstr == &strcasestr) ? &strstr : &strcasestr;
3462 pcreflags ^= PCRE_CASELESS;
3464 regflags ^= REG_ICASE;
3470 /* Toggle string or regex filter */
3471 if (*ch == FILTER) {
3472 ln[0] = (ln[0] == FILTER) ? RFILTER : FILTER;
3473 wln[0] = (uchar_t)ln[0];
3475 filterfn = cfg.regex ? &visible_re : &visible_str;
3480 /* Reset cur in case it's a repeat search */
3482 } else if (len == REGEX_MAX - 1)
3485 wln[len] = (wchar_t)*ch;
3487 wcstombs(ln, wln, REGEX_MAX);
3489 /* Forward-filtering optimization:
3490 * - new matches can only be a subset of current matches.
3492 /* ndents = total; */
3496 !r ? unget_wch(KEY_BACKSPACE) : showfilter(ln);
3498 if (matches(pln) == -1) {
3504 /* If the only match is a dir, auto-enter and cd into it */
3505 if ((ndents == 1) && cfg.autoenter && (pdents[0].flags & DIR_OR_DIRLNK)) {
3512 * redraw() should be above the auto-enter optimization, for
3513 * the case where there's an issue with dir auto-enter, say,
3514 * due to a permission problem. The transition is _jumpy_ in
3515 * case of such an error. However, we optimize for successful
3516 * cases where the dir has permissions. This skips a redraw().
3523 /* Save last working filter in-filter */
3525 ln[REGEX_MAX - 1] = ln[1];
3533 /* Return keys for navigation etc. */
3537 /* Show a prompt with input string and return the changes */
3538 static char *xreadline(const char *prefill, const char *prompt)
3542 const int WCHAR_T_WIDTH = sizeof(wchar_t);
3544 wchar_t * const buf = malloc(sizeof(wchar_t) * READLINE_MAX);
3554 len = pos = mbstowcs(buf, prefill, READLINE_MAX);
3558 if (len == (size_t)-1) {
3563 x = getcurx(stdscr);
3568 attron(COLOR_PAIR(cfg.curctx + 1));
3569 if (pos > (size_t)(xcols - x)) {
3570 mvaddnwstr(xlines - 1, x, buf + (pos - (xcols - x) + 1), xcols - x);
3571 move(xlines - 1, xcols - 1);
3573 mvaddnwstr(xlines - 1, x, buf, len + 1);
3574 move(xlines - 1, x + wcswidth(buf, pos));
3576 attroff(COLOR_PAIR(cfg.curctx + 1));
3584 case KEY_ENTER: // fallthrough
3585 case '\n': // fallthrough
3591 else if (!(pos || len)) { /* Exit on ^D at empty prompt */
3597 case DEL: // fallthrough
3598 case '\b': /* rhel25 sends '\b' for backspace */
3600 memmove(buf + pos - 1, buf + pos,
3601 (len - pos) * WCHAR_T_WIDTH);
3606 if (!(len || pos) && ndents)
3607 len = pos = mbstowcs(buf, pdents[cur].name, READLINE_MAX);
3622 memmove(buf + pos - 1, buf + pos,
3623 (len - pos) * WCHAR_T_WIDTH);
3625 } while (buf[pos - 1] != ' ' && buf[pos - 1] != '/'); // NOLINT
3643 memmove(buf, buf + pos, (len - pos) * WCHAR_T_WIDTH);
3647 case ESC: /* Exit prompt on Esc, but just filter out Alt+key */
3648 if (handle_alt_key(ch) != ERR)
3655 /* Filter out all other control chars */
3656 if (*ch < ASCII_MAX && keyname(*ch)[0] == '^')
3659 if (pos < READLINE_MAX - 1) {
3660 memmove(buf + pos + 1, buf + pos,
3661 (len - pos) * WCHAR_T_WIDTH);
3685 memmove(buf + pos - 1, buf + pos,
3686 (len - pos) * WCHAR_T_WIDTH);
3692 memmove(buf + pos, buf + pos + 1,
3693 (len - pos - 1) * WCHAR_T_WIDTH);
3703 case KEY_UP: // fallthrough
3705 if (prompt && lastcmd && (xstrcmp(prompt, PROMPT) == 0)) {
3707 len = pos = mbstowcs(buf, lastcmd, READLINE_MAX); // fallthrough
3722 pos = wcstombs(g_buf, buf, READLINE_MAX - 1);
3723 if (pos >= READLINE_MAX - 1)
3724 g_buf[READLINE_MAX - 1] = '\0';
3732 * Caller should check the value of presel to confirm if it needs to wait to show warning
3734 static char *getreadline(const char *prompt)
3738 char *input = readline(prompt);
3742 if (input && input[0]) {
3744 xstrsncpy(g_buf, input, CMD_LEN_MAX);
3755 * Create symbolic/hard link(s) to file(s) in selection list
3756 * Returns the number of links created, -1 on error
3758 static int xlink(char *prefix, char *path, char *curfname, char *buf, int type)
3760 int count = 0, choice;
3761 char *psel = pselbuf, *fname;
3762 size_t pos = 0, len, r;
3763 int (*link_fn)(const char *, const char *) = NULL;
3764 char lnpath[PATH_MAX];
3766 choice = get_cur_or_sel();
3770 if (type == 's') /* symbolic link */
3772 else /* hard link */
3775 if (choice == 'c' || (nselected == 1)) {
3776 prefix = abspath(prefix, path, lnpath); /* Generate link path */
3781 mkpath(path, curfname, buf); /* Generate target file path */
3783 if (!link_fn((choice == 'c') ? buf : pselbuf, lnpath)) {
3786 return 1; /* One link created */
3791 r = xstrsncpy(buf, prefix, NAME_MAX + 1); /* Copy prefix */
3793 while (pos < selbufpos) {
3794 len = xstrlen(psel);
3795 fname = xbasename(psel);
3797 xstrsncpy(buf + r - 1, fname, NAME_MAX - r); /* Suffix target file name */
3798 mkpath(path, buf, lnpath); /* Generate link path */
3800 if (!link_fn(psel, lnpath))
3807 if (count == nselected) /* Clear selection if all links are generated */
3812 static bool parsekvpair(kv **arr, char **envcpy, const uchar_t id, uchar_t *items)
3815 const uchar_t INCR = 8;
3818 char *ptr = getenv(env_cfg[id]);
3823 *envcpy = xstrdup(ptr);
3831 while (*ptr && i < 100) {
3833 if (!(i & (INCR - 1))) {
3834 kvarr = xrealloc(kvarr, sizeof(kv) * (i + INCR));
3840 memset(kvarr + i, 0, sizeof(kv) * INCR);
3842 kvarr[i].key = (uchar_t)*ptr;
3843 if (*++ptr != ':' || *++ptr == '\0' || *ptr == ';')
3845 kvarr[i].off = ptr - *envcpy;
3864 * Get the value corresponding to a key
3866 * NULL is returned in case of no match, path resolution failure etc.
3867 * buf would be modified, so check return value before access
3869 static char *get_kv_val(kv *kvarr, char *buf, int key, uchar_t max, uchar_t id)
3876 for (int r = 0; r < max && kvarr[r].key; ++r) {
3877 if (kvarr[r].key == key) {
3878 /* Do not allocate new memory for plugin */
3880 return pluginstr + kvarr[r].off;
3882 val = bmstr + kvarr[r].off;
3883 bool tilde = convert_tilde(val, g_buf);
3884 return abspath((tilde ? g_buf : val), NULL, buf);
3888 DPRINTF_S("Invalid key");
3892 static int get_kv_key(kv *kvarr, char *val, uchar_t max, uchar_t id)
3897 if (id != NNN_ORDER) /* For now this function supports only order string */
3900 for (int r = 0; r < max && kvarr[r].key; ++r) {
3901 if (xstrcmp((orderstr + kvarr[r].off), val) == 0)
3902 return kvarr[r].key;
3908 static void resetdircolor(int flags)
3910 /* Directories are always shown on top, clear the color when moving to first file */
3911 if (g_state.dircolor && !(flags & DIR_OR_DIRLNK)) {
3912 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
3913 g_state.dircolor = 0;
3918 * Replace escape characters in a string with '?'
3919 * Adjust string length to maxcols if > 0;
3920 * Max supported str length: NAME_MAX;
3923 static char *unescape(const char *str, uint_t maxcols)
3925 char * const wbuf = g_buf;
3928 xstrsncpy(wbuf, str, maxcols);
3930 static wchar_t *unescape(const char *str, uint_t maxcols)
3932 wchar_t * const wbuf = (wchar_t *)g_buf;
3933 wchar_t *buf = wbuf;
3934 size_t len = mbstowcs(wbuf, str, maxcols); /* Convert multi-byte to wide char */
3936 len = wcswidth(wbuf, len);
3938 if (len >= maxcols) {
3939 size_t lencount = maxcols;
3941 while (len > maxcols) /* Reduce wide chars one by one till it fits */
3942 len = wcswidth(wbuf, --lencount);
3944 wbuf[lencount] = L'\0';
3949 if (*buf <= '\x1f' || *buf == '\x7f')
3958 static off_t get_size(off_t size, off_t *pval, int comp)
3961 off_t quo = rem / 10;
3963 if ((rem - (quo * 10)) >= 5) {
3976 static char *coolsize(off_t size)
3978 const char * const U = "BKMGTPEZY";
3979 static char size_buf[12]; /* Buffer to hold human readable size */
3984 while (size >= 1024) {
3985 rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
3991 rem = (rem * 1000) >> 10;
3993 size = get_size(size, &rem, 10);
3994 } else if (i == 2) {
3995 rem = (rem * 1000) >> 10;
3996 size = get_size(size, &rem, 100);
3998 rem = (rem * 10000) >> 10;
3999 size = get_size(size, &rem, 1000);
4002 if (i > 0 && i < 6 && rem) {
4003 ret = xstrsncpy(size_buf, xitoa(size), 12);
4004 size_buf[ret - 1] = '.';
4006 char *frac = xitoa(rem);
4007 size_t toprint = i > 3 ? 3 : i;
4008 size_t len = xstrlen(frac);
4010 if (len < toprint) {
4011 size_buf[ret] = size_buf[ret + 1] = size_buf[ret + 2] = '0';
4012 xstrsncpy(size_buf + ret + (toprint - len), frac, len + 1);
4014 xstrsncpy(size_buf + ret, frac, toprint + 1);
4018 ret = xstrsncpy(size_buf, size ? xitoa(size) : "0", 12);
4022 size_buf[ret] = U[i];
4023 size_buf[ret + 1] = '\0';
4028 /* Convert a mode field into "ls -l" type perms field. */
4029 static char *get_lsperms(mode_t mode)
4031 static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
4032 static char bits[11] = {'\0'};
4034 switch (mode & S_IFMT) {
4061 xstrsncpy(&bits[1], rwx[(mode >> 6) & 7], 4);
4062 xstrsncpy(&bits[4], rwx[(mode >> 3) & 7], 4);
4063 xstrsncpy(&bits[7], rwx[(mode & 7)], 4);
4066 bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
4068 bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
4070 bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
4075 #ifdef ICONS_ENABLED
4076 static struct icon get_icon(const struct entry *ent)
4078 for (size_t i = 0; i < ELEMENTS(icons_name); ++i)
4079 if (strcasecmp(ent->name, icons_name[i].match) == 0)
4080 return (struct icon){ icons_name[i].icon, icons_name[i].color };
4082 if (ent->flags & DIR_OR_DIRLNK)
4085 char *tmp = xextension(ent->name, ent->nlen);
4088 uint16_t z, k, h = icon_ext_hash(++tmp); /* ++tmp to skip '.' */
4089 for (k = 0; k < ICONS_PROBE_MAX; ++k) {
4090 z = (h + k) % ELEMENTS(icons_ext);
4091 if (strcasecmp(tmp, icons_ext[z].match) == 0)
4092 return (struct icon){ icons_ext_uniq[icons_ext[z].idx], icons_ext[z].color };
4096 /* If there's no match and the file is executable, icon that */
4097 if (ent->mode & 0100)
4102 static void print_icon(const struct entry *ent, const int attrs)
4104 const struct icon icon = get_icon(ent);
4105 addstr(ICON_PADDING_LEFT);
4107 attron(COLOR_PAIR(C_UND + 1 + icon.color));
4112 attroff(COLOR_PAIR(C_UND + 1 + icon.color));
4115 addstr(ICON_PADDING_RIGHT);
4119 static void print_time(const time_t *timep, const uchar_t flags)
4123 /* Highlight timestamp for entries 5 minutes young */
4124 if (flags & FILE_YOUNG)
4127 localtime_r(timep, &t);
4128 printw("%s-%02d-%02d %02d:%02d",
4129 xitoa(t.tm_year + 1900), t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min);
4131 if (flags & FILE_YOUNG)
4135 static char get_detail_ind(const mode_t mode)
4137 switch (mode & S_IFMT) {
4138 case S_IFDIR: // fallthrough
4139 case S_IFREG: return ' ';
4140 case S_IFLNK: return '@';
4141 case S_IFSOCK: return '=';
4142 case S_IFIFO: return '|';
4143 case S_IFBLK: return 'b';
4144 case S_IFCHR: return 'c';
4149 /* Note: attribute and indicator values must be initialized to 0 */
4150 static uchar_t get_color_pair_name_ind(const struct entry *ent, char *pind, int *pattr)
4152 switch (ent->mode & S_IFMT) {
4155 if (ent->mode & 0100)
4159 if (ent->flags & HARD_LINK) {
4160 if (ent->mode & 0100)
4164 if (ent->mode & 0100) {
4171 if (g_state.oldcolor)
4174 return g_state.dirctx ? cfg.curctx + 1 : C_DIR;
4176 if (ent->flags & DIR_OR_DIRLNK) {
4178 *pattr |= g_state.oldcolor ? A_DIM : A_BOLD;
4181 if (g_state.oldcolor)
4184 if (!g_state.oldcolor || cfg.showdetail)
4185 return (ent->flags & SYM_ORPHAN) ? C_ORP : C_LNK;
4203 static void printent(const struct entry *ent, uint_t namecols, bool sel)
4208 if (cfg.showdetail) {
4209 int type = ent->mode & S_IFMT;
4210 char perms[6] = {' ', ' ', (char)('0' + ((ent->mode >> 6) & 7)),
4211 (char)('0' + ((ent->mode >> 3) & 7)),
4212 (char)('0' + (ent->mode & 7)), '\0'};
4215 attrs = g_state.oldcolor ? (resetdircolor(ent->flags), A_DIM)
4216 : (fcolors[C_MIS] ? COLOR_PAIR(C_MIS) : 0);
4221 print_time(&ent->sec, ent->flags);
4223 printw("%s%9s ", perms, (type == S_IFREG || type == S_IFDIR)
4224 ? coolsize(cfg.blkorder ? (blkcnt_t)ent->blocks << blk_shift : ent->size)
4225 : (type = (uchar_t)get_detail_ind(ent->mode), (char *)&type));
4233 uchar_t color_pair = get_color_pair_name_ind(ent, &ind, &attrs);
4235 addch((ent->flags & FILE_SELECTED) ? '+' | A_REVERSE | A_BOLD : ' ');
4237 if (g_state.oldcolor)
4238 resetdircolor(ent->flags);
4240 if (ent->flags & FILE_MISSING)
4242 if (color_pair && fcolors[color_pair])
4243 attrs |= COLOR_PAIR(color_pair);
4244 #ifdef ICONS_ENABLED
4245 print_icon(ent, attrs);
4257 addwstr(unescape(ent->name, namecols));
4259 addstr(unescape(ent->name, MIN(namecols, ent->nlen) + 1));
4268 static void savecurctx(char *path, char *curname, int nextctx)
4270 settings tmpcfg = cfg;
4271 context *ctxr = &g_ctx[nextctx];
4273 /* Save current context */
4275 xstrsncpy(g_ctx[tmpcfg.curctx].c_name, curname, NAME_MAX + 1);
4277 g_ctx[tmpcfg.curctx].c_name[0] = '\0';
4279 g_ctx[tmpcfg.curctx].c_cfg = tmpcfg;
4281 if (ctxr->c_cfg.ctxactive) { /* Switch to saved context */
4282 tmpcfg = ctxr->c_cfg;
4283 /* Skip ordering an open context */
4285 cfgsort[CTX_MAX] = cfgsort[nextctx];
4286 cfgsort[nextctx] = '0';
4288 } else { /* Set up a new context from current context */
4289 ctxr->c_cfg.ctxactive = 1;
4290 xstrsncpy(ctxr->c_path, path, PATH_MAX);
4291 ctxr->c_last[0] = ctxr->c_name[0] = ctxr->c_fltr[0] = ctxr->c_fltr[1] = '\0';
4292 ctxr->c_cfg = tmpcfg;
4293 /* If already in an ordered dir, clear ordering for the new context and let it order */
4294 if (cfgsort[cfg.curctx] == 'z')
4295 cfgsort[nextctx] = 'z';
4298 tmpcfg.curctx = nextctx;
4303 static void save_session(const char *sname, int *presel)
4306 session_header_t header = {0};
4307 bool status = FALSE;
4308 char ssnpath[PATH_MAX];
4309 char spath[PATH_MAX];
4311 header.ver = SESSIONS_VERSION;
4313 for (i = 0; i < CTX_MAX; ++i) {
4314 if (g_ctx[i].c_cfg.ctxactive) {
4315 if (cfg.curctx == i && ndents)
4316 /* Update current file name, arrows don't update it */
4317 xstrsncpy(g_ctx[i].c_name, pdents[cur].name, NAME_MAX + 1);
4318 header.pathln[i] = MIN(xstrlen(g_ctx[i].c_path), PATH_MAX) + 1;
4319 header.lastln[i] = MIN(xstrlen(g_ctx[i].c_last), PATH_MAX) + 1;
4320 header.nameln[i] = MIN(xstrlen(g_ctx[i].c_name), NAME_MAX) + 1;
4321 header.fltrln[i] = REGEX_MAX;
4325 mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4326 mkpath(ssnpath, sname, spath);
4328 fd = open(spath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
4330 printwait(messages[MSG_SEL_MISSING], presel);
4334 if ((write(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4335 || (write(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4338 for (i = 0; i < CTX_MAX; ++i)
4339 if ((write(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4340 || (write(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4341 || (header.nameln[i] > 0
4342 && write(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4343 || (header.lastln[i] > 0
4344 && write(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4345 || (header.fltrln[i] > 0
4346 && write(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4347 || (header.pathln[i] > 0
4348 && write(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4357 printwait(messages[MSG_FAILED], presel);
4360 static bool load_session(const char *sname, char **path, char **lastdir, char **lastname, bool restore)
4363 session_header_t header;
4364 bool has_loaded_dynamically = !(sname || restore);
4365 bool status = (sname && g_state.picker); /* Picker mode with session program option */
4366 char ssnpath[PATH_MAX];
4367 char spath[PATH_MAX];
4369 mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4372 sname = sname ? sname : xreadline(NULL, messages[MSG_SSN_NAME]);
4376 mkpath(ssnpath, sname, spath);
4378 /* If user is explicitly loading the "last session", skip auto-save */
4379 if ((sname[0] == '@') && !sname[1])
4380 has_loaded_dynamically = FALSE;
4382 mkpath(ssnpath, "@", spath);
4384 if (has_loaded_dynamically)
4385 save_session("@", NULL);
4387 fd = open(spath, O_RDONLY, S_IWUSR | S_IRUSR);
4390 printmsg(messages[MSG_SEL_MISSING]);
4391 xdelay(XDELAY_INTERVAL_MS);
4398 if ((read(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4399 || (header.ver != SESSIONS_VERSION)
4400 || (read(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4403 g_ctx[cfg.curctx].c_name[0] = g_ctx[cfg.curctx].c_last[0]
4404 = g_ctx[cfg.curctx].c_fltr[0] = g_ctx[cfg.curctx].c_fltr[1] = '\0';
4406 for (; i < CTX_MAX; ++i)
4407 if ((read(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4408 || (read(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4409 || (header.nameln[i] > 0
4410 && read(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4411 || (header.lastln[i] > 0
4412 && read(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4413 || (header.fltrln[i] > 0
4414 && read(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4415 || (header.pathln[i] > 0
4416 && read(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4419 *path = g_ctx[cfg.curctx].c_path;
4420 *lastdir = g_ctx[cfg.curctx].c_last;
4421 *lastname = g_ctx[cfg.curctx].c_name;
4422 set_sort_flags('\0'); /* Set correct sort options */
4429 printmsg(messages[MSG_FAILED]);
4430 xdelay(XDELAY_INTERVAL_MS);
4438 static uchar_t get_free_ctx(void)
4440 uchar_t r = cfg.curctx;
4443 r = (r + 1) & ~CTX_MAX;
4444 while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
4449 /* ctx is absolute: 1 to 4, + for smart context */
4450 static void set_smart_ctx(int ctx, char *nextpath, char **path, char *file, char **lastname, char **lastdir)
4452 if (ctx == '+') /* Get smart context */
4453 ctx = (int)(get_free_ctx() + 1);
4455 if (ctx == 0 || ctx == cfg.curctx + 1) { /* Same context */
4456 xstrsncpy(*lastdir, *path, PATH_MAX);
4457 xstrsncpy(*path, nextpath, PATH_MAX);
4458 } else { /* New context */
4460 /* Deactivate the new context and build from scratch */
4461 g_ctx[ctx].c_cfg.ctxactive = 0;
4462 DPRINTF_S(nextpath);
4463 savecurctx(nextpath, file, ctx);
4464 *path = g_ctx[ctx].c_path;
4465 *lastdir = g_ctx[ctx].c_last;
4466 *lastname = g_ctx[ctx].c_name;
4471 * This function does one of the following depending on the values of `fdout` and `page`:
4472 * 1) fdout == -1 && !page: Write up to CMD_LEN_MAX bytes of command output into g_buf
4473 * 2) fdout == -1 && page: Create a temp file, write full command output into it and show in pager.
4474 * 3) fdout != -1 && !page: Write full command output into the provided file.
4475 * 4) fdout != -1 && page: Don't use! Returns FALSE.
4477 * g_buf is modified only in case 1.
4478 * g_tmpfpath is modified only in case 2.
4480 static bool get_output(char *file, char *arg1, char *arg2, int fdout, bool page)
4484 int index = 0, flags;
4486 bool have_file = fdout != -1;
4488 int cmd_out_fd = -1;
4492 * In this case the logic of the function dictates that we should write the output of the command
4493 * to `fd` and show it in the pager. But since we didn't open the file descriptor we have no right
4494 * to close it, the caller must do it. We don't even know the path to pass to the pager and
4495 * it's a real hassle to get it. In general this just invites problems so we are blocking it.
4497 if (have_file && page) {
4498 DPRINTF_S("invalid get_ouptput() call");
4502 /* Setup file descriptors for child command */
4503 if (!have_file && page) {
4505 fdout = create_tmp_file();
4509 cmd_in_fd = STDIN_FILENO;
4511 } else if (have_file) {
4513 cmd_in_fd = STDIN_FILENO;
4517 if (pipe(pipefd) == -1)
4520 for (index = 0; index < 2; ++index) {
4521 /* Get previous flags */
4522 flags = fcntl(pipefd[index], F_GETFL, 0);
4524 /* Set bit for non-blocking flag */
4525 flags |= O_NONBLOCK;
4527 /* Change flags on fd */
4528 fcntl(pipefd[index], F_SETFL, flags);
4531 cmd_in_fd = pipefd[0];
4532 cmd_out_fd = pipefd[1];
4539 dup2(cmd_out_fd, STDOUT_FILENO);
4540 dup2(cmd_out_fd, STDERR_FILENO);
4543 spawn(file, arg1, arg2, NULL, F_MULTI);
4544 _exit(EXIT_SUCCESS);
4548 waitpid(pid, NULL, 0);
4550 /* Do what each case should do */
4551 if (!have_file && page) {
4555 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4566 len = read(pipefd[0], g_buf, CMD_LEN_MAX - 1);
4576 * Follows the stat(1) output closely
4578 static bool show_stats(char *fpath)
4580 static char * const cmds[] = {
4581 #ifdef FILE_MIME_OPTS
4582 ("file " FILE_MIME_OPTS),
4585 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
4592 size_t r = ELEMENTS(cmds);
4593 int fd = create_tmp_file();
4598 get_output(cmds[--r], fpath, NULL, fd, FALSE);
4602 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4607 static bool xchmod(const char *fpath, mode_t mode)
4609 /* (Un)set (S_IXUSR | S_IXGRP | S_IXOTH) */
4610 (0100 & mode) ? (mode &= ~0111) : (mode |= 0111);
4612 return (chmod(fpath, mode) == 0);
4615 static size_t get_fs_info(const char *path, uchar_t type)
4619 if (statvfs(path, &svb) == -1)
4622 if (type == VFS_AVAIL)
4623 return (size_t)svb.f_bavail << ffs((int)(svb.f_frsize >> 1));
4625 if (type == VFS_USED)
4626 return ((size_t)svb.f_blocks - (size_t)svb.f_bfree) << ffs((int)(svb.f_frsize >> 1));
4628 return (size_t)svb.f_blocks << ffs((int)(svb.f_frsize >> 1)); /* VFS_SIZE */
4631 /* Create non-existent parents and a file or dir */
4632 static bool xmktree(char *path, bool dir)
4640 /* Skip the first '/' */
4643 while (*p != '\0') {
4652 /* Create folder from path to '\0' inserted at p */
4653 if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4655 // XDG_CONFIG_HOME contains a directory
4656 // that is read-only, but the full path
4658 // Try to continue and see what happens.
4659 // TODO: Find a more robust solution.
4660 if (errno == B_READ_ONLY_DEVICE)
4663 DPRINTF_S("mkdir1!");
4664 DPRINTF_S(strerror(errno));
4678 if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4679 DPRINTF_S("mkdir2!");
4680 DPRINTF_S(strerror(errno));
4684 int fd = open(path, O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR); /* Forced create mode for files */
4686 if (fd == -1 && errno != EEXIST) {
4688 DPRINTF_S(strerror(errno));
4698 /* List or extract archive */
4699 static bool handle_archive(char *fpath /* in-out param */, char op)
4701 char arg[] = "-tvf"; /* options for tar/bsdtar to list files */
4702 char *util, *outdir = NULL;
4704 bool is_atool = (!g_state.usebsdtar && getutil(utils[UTIL_ATOOL]));
4707 outdir = xreadline(is_atool ? "." : xbasename(fpath), messages[MSG_NEW_PATH]);
4708 if (!outdir || !*outdir) { /* Cancelled */
4709 printwait(messages[MSG_CANCEL], NULL);
4712 /* Do not create smart context for current dir */
4713 if (!(*outdir == '.' && outdir[1] == '\0')) {
4714 if (!xmktree(outdir, TRUE) || (chdir(outdir) == -1)) {
4718 /* Copy the new dir path to open it in smart context */
4719 outdir = getcwd(NULL, 0);
4725 util = utils[UTIL_ATOOL];
4728 } else if (getutil(utils[UTIL_BSDTAR])) {
4729 util = utils[UTIL_BSDTAR];
4732 } else if (is_suffix(fpath, ".zip")) {
4733 util = utils[UTIL_UNZIP];
4734 arg[1] = (op == 'l') ? 'v' /* verbose listing */ : '\0';
4737 util = utils[UTIL_TAR];
4742 if (op == 'x') /* extract */
4743 spawn(util, arg, fpath, NULL, F_NORMAL | F_MULTI);
4745 get_output(util, arg, fpath, -1, TRUE);
4748 if (chdir(xdirname(fpath)) == -1) {
4753 xstrsncpy(fpath, outdir, PATH_MAX);
4755 } else if (op == 'x')
4761 static char *visit_parent(char *path, char *newpath, int *presel)
4765 /* There is no going back */
4766 if (istopdir(path)) {
4767 /* Continue in type-to-nav mode, if enabled */
4768 if (cfg.filtermode && presel)
4773 /* Use a copy as xdirname() may change the string passed */
4775 xstrsncpy(newpath, path, PATH_MAX);
4779 dir = xdirname(newpath);
4780 if (chdir(dir) == -1) {
4788 static void valid_parent(char *path, char *lastname)
4791 xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
4793 while (!istopdir(path))
4794 if (visit_parent(path, NULL, NULL))
4798 xdelay(XDELAY_INTERVAL_MS);
4801 static bool archive_mount(char *newpath)
4803 char *str = "install archivemount";
4804 char *dir, *cmd = str + 8; /* Start of "archivemount" */
4805 char *name = pdents[cur].name;
4806 size_t len = pdents[cur].nlen;
4807 char mntpath[PATH_MAX];
4809 if (!getutil(cmd)) {
4814 dir = xstrdup(name);
4816 printmsg(messages[MSG_FAILED]);
4821 if (dir[--len] == '.') {
4828 /* Create the mount point */
4829 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4830 mkpath(mntpath, dir, newpath);
4833 if (!xmktree(newpath, TRUE)) {
4841 if (spawn(cmd, name, newpath, NULL, F_NORMAL)) {
4842 printmsg(messages[MSG_FAILED]);
4849 static bool remote_mount(char *newpath)
4851 uchar_t flag = F_CLI;
4854 bool r = getutil(utils[UTIL_RCLONE]), s = getutil(utils[UTIL_SSHFS]);
4855 char mntpath[PATH_MAX];
4858 printmsg("install sshfs/rclone");
4863 opt = get_input(messages[MSG_REMOTE_OPTS]);
4865 opt = (!s) ? 'r' : 's';
4868 env = xgetenv("NNN_SSHFS", utils[UTIL_SSHFS]);
4869 else if (opt == 'r') {
4870 flag |= F_NOWAIT | F_NOTRACE;
4871 env = xgetenv("NNN_RCLONE", "rclone mount");
4873 printmsg(messages[MSG_INVALID_KEY]);
4877 tmp = xreadline(NULL, "host[:dir] > ");
4879 printmsg(messages[MSG_CANCEL]);
4883 char *div = strchr(tmp, ':');
4888 /* Create the mount point */
4889 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4890 mkpath(mntpath, tmp, newpath);
4891 if (!xmktree(newpath, TRUE)) {
4896 if (!div) { /* Convert "host" to "host:" */
4897 size_t len = xstrlen(tmp);
4900 tmp[len + 1] = '\0';
4904 /* Connect to remote */
4906 if (spawn(env, tmp, newpath, NULL, flag)) {
4907 printmsg(messages[MSG_FAILED]);
4911 spawn(env, tmp, newpath, NULL, flag);
4912 printmsg(messages[MSG_RCLONE_DELAY]);
4913 xdelay(XDELAY_INTERVAL_MS << 2); /* Set 4 times the usual delay */
4920 * Unmounts if the directory represented by name is a mount point.
4921 * Otherwise, asks for hostname
4922 * Returns TRUE if directory needs to be refreshed *.
4924 static bool unmount(char *name, char *newpath, int *presel, char *currentpath)
4926 #if defined(__APPLE__) || defined(__FreeBSD__)
4927 static char cmd[] = "umount";
4929 static char cmd[] = "fusermount3"; /* Arch Linux utility */
4930 static bool found = FALSE;
4933 struct stat sb, psb;
4935 bool parent = FALSE;
4936 bool hovered = FALSE;
4937 char mntpath[PATH_MAX];
4939 #if !defined(__APPLE__) && !defined(__FreeBSD__)
4940 /* On Ubuntu it's fusermount */
4941 if (!found && !getutil(cmd)) {
4947 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4949 if (tmp && strcmp(mntpath, currentpath) == 0) {
4950 mkpath(mntpath, tmp, newpath);
4951 child = lstat(newpath, &sb) != -1;
4952 parent = lstat(xdirname(newpath), &psb) != -1;
4953 if (!child && !parent) {
4959 if (!tmp || !child || !S_ISDIR(sb.st_mode) || (child && parent && sb.st_dev == psb.st_dev)) {
4960 tmp = xreadline(NULL, messages[MSG_HOSTNAME]);
4963 if (name && (tmp[0] == '-') && (tmp[1] == '\0')) {
4964 mkpath(currentpath, name, newpath);
4970 mkpath(mntpath, tmp, newpath);
4972 if (!xdiraccess(newpath)) {
4977 #if defined(__APPLE__) || defined(__FreeBSD__)
4978 if (spawn(cmd, newpath, NULL, NULL, F_NORMAL)) {
4980 if (spawn(cmd, "-qu", newpath, NULL, F_NORMAL)) {
4982 if (!xconfirm(get_input(messages[MSG_LAZY])))
4986 if (spawn(cmd, "-l", newpath, NULL, F_NORMAL)) {
4987 #elif defined(__FreeBSD__)
4988 if (spawn(cmd, "-f", newpath, NULL, F_NORMAL)) {
4990 if (spawn(cmd, "-quz", newpath, NULL, F_NORMAL)) {
4992 printwait(messages[MSG_FAILED], presel);
4997 if (rmdir(newpath) == -1) {
5005 static void lock_terminal(void)
5007 spawn(xgetenv("NNN_LOCKER", utils[UTIL_LOCKER]), NULL, NULL, NULL, F_CLI);
5010 static void printkv(kv *kvarr, int fd, uchar_t max, uchar_t id)
5012 char *val = (id == NNN_BMS) ? bmstr : pluginstr;
5014 for (uchar_t i = 0; i < max && kvarr[i].key; ++i)
5015 dprintf(fd, " %c: %s\n", (char)kvarr[i].key, val + kvarr[i].off);
5018 static void printkeys(kv *kvarr, char *buf, uchar_t max)
5022 for (; i < max && kvarr[i].key; ++i) {
5024 buf[(i << 1) + 1] = kvarr[i].key;
5030 static size_t handle_bookmark(const char *bmark, char *newpath)
5035 if (maxbm || bmark) {
5036 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
5038 if (bmark) { /* There is a marked directory */
5044 printkeys(bookmark, g_buf + r - 1, maxbm);
5046 fd = get_input(NULL);
5050 if (fd == ',') /* Visit marked directory */
5051 bmark ? xstrsncpy(newpath, bmark, PATH_MAX) : (r = MSG_NOT_SET);
5052 else if (fd == '\r') { /* Visit bookmarks directory */
5053 mkpath(cfgpath, toks[TOK_BM], newpath);
5055 } else if (!get_kv_val(bookmark, newpath, fd, maxbm, NNN_BMS))
5056 r = MSG_INVALID_KEY;
5058 if (!r && chdir(newpath) == -1) {
5067 static void add_bookmark(char *path, char *newpath, int *presel)
5069 char *dir = xbasename(path);
5071 dir = xreadline(dir[0] ? dir : NULL, messages[MSG_BM_NAME]);
5073 size_t r = mkpath(cfgpath, toks[TOK_BM], newpath);
5075 newpath[r - 1] = '/';
5076 xstrsncpy(newpath + r, dir, PATH_MAX - r);
5077 printwait((symlink(path, newpath) == -1) ? strerror(errno) : newpath, presel);
5079 printwait(messages[MSG_CANCEL], presel);
5083 * The help string tokens (each line) start with a HEX value
5084 * which indicates the number of spaces to print before the
5085 * particular token. This method was chosen instead of a flat
5086 * string because the number of bytes in help was increasing
5087 * the binary size by around a hundred bytes. This would only
5088 * have increased as we keep adding new options.
5090 static void show_help(const char *path)
5092 const char *start, *end;
5093 const char helpstr[] = {
5096 "9Up k Up%-16cPgUp ^U Page up\n"
5097 "9Dn j Down%-14cPgDn ^D Page down\n"
5098 "9Lt h Parent%-12c~ ` @ - ~, /, start, prev\n"
5099 "5Ret Rt l Open%-20c' First file/match\n"
5100 "9g ^A Top%-21cJ Jump to entry/offset\n"
5101 "9G ^E End%-20c^J Toggle auto-advance on open\n"
5102 "8B (,) Book(mark)%-11cb ^/ Select bookmark\n"
5103 "a1-4 Context%-11c(Sh)Tab Cycle/new context\n"
5104 "62Esc ^Q Quit%-20cq Quit context\n"
5105 "b^G QuitCD%-18cQ Pick/err, quit\n"
5107 "1FILTER & PROMPT\n"
5108 "c/ Filter%-17c^N Toggle type-to-nav\n"
5109 "aEsc Exit prompt%-12c^L Toggle last filter\n"
5110 "c. Toggle hidden%-5cAlt+Esc Unfilter, quit context\n"
5113 "9o ^O Open with%-15cn Create new/link\n"
5114 "9f ^F File stats%-14cd Detail mode toggle\n"
5115 "b^R Rename/dup%-14cr Batch rename\n"
5116 "cz Archive%-17ce Edit file\n"
5117 "c* Toggle exe%-14c> Export list\n"
5118 "6Space + (Un)select%-12cm-m Select range/clear\n"
5119 "ca Select all%-14cA Invert sel\n"
5120 "9p ^P Copy here%-12cw ^W Cp/mv sel as\n"
5121 "9v ^V Move here%-15cE Edit sel list\n"
5122 "9x ^X Delete%-18cS Listed sel size\n"
5123 "aEsc Send to FIFO\n"
5126 "8Alt ; Select plugin%-11c= Launch app\n"
5127 "9! ^] Shell%-19c] Cmd prompt\n"
5128 "cc Connect remote%-10cu Unmount remote/archive\n"
5129 "9t ^T Sort toggles%-12cs Manage session\n"
5130 "cT Set time type%-11c0 Lock\n"
5131 "b^L Redraw%-18c? Help, conf\n"
5134 int fd = create_tmp_file();
5138 dprintf(fd, " |V\\_\n"
5144 char *prog = xgetenv(env_cfg[NNN_HELP], NULL);
5146 get_output(prog, NULL, NULL, fd, FALSE);
5148 start = end = helpstr;
5151 snprintf(g_buf, CMD_LEN_MAX, "%*c%.*s",
5152 xchartohex(*start), ' ', (int)(end - start), start + 1);
5153 dprintf(fd, g_buf, ' ');
5160 dprintf(fd, "\nLOCATIONS\n");
5161 for (uchar_t i = 0; i < CTX_MAX; ++i)
5162 if (g_ctx[i].c_cfg.ctxactive)
5163 dprintf(fd, " %u: %s\n", i + 1, g_ctx[i].c_path);
5165 dprintf(fd, "\nVOLUME: avail:%s ", coolsize(get_fs_info(path, VFS_AVAIL)));
5166 dprintf(fd, "used:%s ", coolsize(get_fs_info(path, VFS_USED)));
5167 dprintf(fd, "size:%s\n\n", coolsize(get_fs_info(path, VFS_SIZE)));
5170 dprintf(fd, "BOOKMARKS\n");
5171 printkv(bookmark, fd, maxbm, NNN_BMS);
5176 dprintf(fd, "PLUGIN KEYS\n");
5177 printkv(plug, fd, maxplug, NNN_PLUG);
5181 for (uchar_t i = NNN_OPENER; i <= NNN_TRASH; ++i) {
5182 start = getenv(env_cfg[i]);
5184 dprintf(fd, "%s: %s\n", env_cfg[i], start);
5188 dprintf(fd, "SELECTION FILE: %s\n", selpath);
5190 dprintf(fd, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
5193 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
5197 static void setexports(void)
5203 setenv(envs[ENV_NCUR], pdents[cur].name, 1);
5204 xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
5205 } else if (g_ctx[cfg.curctx].c_name[0])
5206 g_ctx[cfg.curctx].c_name[0] = '\0';
5208 for (uchar_t i = 0; i < CTX_MAX; ++i) {
5209 if (g_ctx[i].c_cfg.ctxactive) {
5210 dvar[1] = fvar[1] = '1' + i;
5211 setenv(dvar, g_ctx[i].c_path, 1);
5213 if (g_ctx[i].c_name[0]) {
5214 mkpath(g_ctx[i].c_path, g_ctx[i].c_name, g_buf);
5215 setenv(fvar, g_buf, 1);
5219 setenv("NNN_INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
5220 setenv("NNN_PREFER_SELECTION", xitoa(cfg.prefersel), 1);
5223 static void run_cmd_as_plugin(const char *file, uchar_t flags)
5227 xstrsncpy(g_buf, file, PATH_MAX);
5229 len = xstrlen(g_buf);
5230 if (len > 1 && g_buf[len - 1] == '*') {
5231 flags &= ~F_CONFIRM; /* Skip user confirmation */
5232 g_buf[len - 1] = '\0'; /* Get rid of trailing no confirmation symbol */
5237 get_output(utils[UTIL_SH_EXEC], g_buf, NULL, -1, TRUE);
5239 spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, flags);
5242 static bool plctrl_init(void)
5246 /* g_tmpfpath is used to generate tmp file names */
5247 g_tmpfpath[tmpfplen - 1] = '\0';
5248 len = xstrsncpy(g_pipepath, g_tmpfpath, TMP_LEN_MAX);
5249 g_pipepath[len - 1] = '/';
5250 len = xstrsncpy(g_pipepath + len, "nnn-pipe.", TMP_LEN_MAX - len) + len;
5251 xstrsncpy(g_pipepath + len - 1, xitoa(getpid()), TMP_LEN_MAX - len);
5252 setenv(env_cfg[NNN_PIPE], g_pipepath, TRUE);
5254 return EXIT_SUCCESS;
5257 static void rmlistpath(void)
5260 DPRINTF_S(__func__);
5261 DPRINTF_S(listpath);
5262 spawn(utils[UTIL_RM_RF], listpath, NULL, NULL, F_NOTRACE | F_MULTI);
5263 /* Do not free if program was started in list mode */
5264 if (listpath != initpath)
5270 static ssize_t read_nointr(int fd, void *buf, size_t count)
5275 len = read(fd, buf, count);
5276 while (len == -1 && errno == EINTR);
5281 static char *readpipe(int fd, char *ctxnum, char **path)
5283 char ctx, *nextpath = NULL;
5285 if (read_nointr(fd, g_buf, 1) != 1)
5288 if (g_buf[0] == '-') { /* Clear selection on '-' */
5290 if (read_nointr(fd, g_buf, 1) != 1)
5294 if (g_buf[0] == '+')
5295 ctx = (char)(get_free_ctx() + 1);
5296 else if (g_buf[0] < '0')
5299 ctx = g_buf[0] - '0';
5304 if (read_nointr(fd, g_buf, 1) != 1)
5310 ssize_t len = read_nointr(fd, g_buf, PATH_MAX);
5315 g_buf[len] = '\0'; /* Terminate the path read */
5316 if (g_buf[0] == '/') {
5318 len = xstrlen(g_buf);
5319 while (--len && (g_buf[len] == '/')) /* Trim all trailing '/' */
5322 } else if (op == 'l') {
5323 rmlistpath(); /* Remove last list mode path, if any */
5324 nextpath = load_input(fd, *path);
5325 } else if (op == 'p') {
5338 static bool run_plugin(char **path, const char *file, char *runfile, char **lastname, char **lastdir)
5343 bool cmd_as_plugin = FALSE;
5346 if (!g_state.pluginit) {
5348 g_state.pluginit = 1;
5353 /* Check for run-cmd-as-plugin mode */
5355 flags = F_MULTI | F_CONFIRM;
5358 if (*file == '|') { /* Check if output should be paged */
5361 } else if (*file == '&') { /* Check if GUI flags are to be used */
5362 flags = F_MULTI | F_NOTRACE | F_NOWAIT;
5369 if ((flags & F_NOTRACE) || (flags & F_PAGE)) {
5370 run_cmd_as_plugin(file, flags);
5374 cmd_as_plugin = TRUE;
5377 if (mkfifo(g_pipepath, 0600) != 0)
5384 if (!p) { // In child
5385 int wfd = open(g_pipepath, O_WRONLY | O_CLOEXEC);
5388 _exit(EXIT_FAILURE);
5390 if (!cmd_as_plugin) {
5394 /* Generate absolute path to plugin */
5395 mkpath(plgpath, file, g_buf);
5398 sel = selpath ? selpath : std;
5400 if (runfile && runfile[0]) {
5401 xstrsncpy(*lastname, runfile, NAME_MAX);
5402 spawn(g_buf, *lastname, *path, sel, 0);
5404 spawn(g_buf, NULL, *path, sel, 0);
5406 run_cmd_as_plugin(file, flags);
5409 _exit(EXIT_SUCCESS);
5415 rfd = open(g_pipepath, O_RDONLY);
5416 while (rfd == -1 && errno == EINTR);
5418 nextpath = readpipe(rfd, &ctx, path);
5420 set_smart_ctx(ctx, nextpath, path, runfile, lastname, lastdir);
5424 /* wait for the child to finish. no zombies allowed */
5425 waitpid(p, NULL, 0);
5434 static bool launch_app(char *newpath)
5437 char *tmp = newpath;
5439 mkpath(plgpath, utils[UTIL_LAUNCH], newpath);
5441 if (!getutil(utils[UTIL_FZF]) || access(newpath, X_OK) < 0) {
5442 tmp = xreadline(NULL, messages[MSG_APP_NAME]);
5443 r = F_NOWAIT | F_NOTRACE | F_MULTI;
5446 if (tmp && *tmp) // NOLINT
5447 spawn(tmp, (r == F_NORMAL) ? "0" : NULL, NULL, NULL, r);
5452 /* Returns TRUE if at least one command was run */
5453 static bool prompt_run(void)
5456 char *cmdline, *next;
5457 int cnt_j, cnt_J, cmd_ret;
5460 const char *xargs_j = "xargs -0 -I{} %s < %s";
5461 const char *xargs_J = "xargs -0 %s < %s";
5462 char cmd[CMD_LEN_MAX + 32]; // 32 for xargs format strings
5466 if (g_state.picker) {
5468 cmdline = xreadline(NULL, PROMPT);
5471 cmdline = getreadline("\n"PROMPT);
5473 // Check for an empty command
5474 if (!cmdline || !cmdline[0])
5478 lastcmd = xstrdup(cmdline);
5481 len = xstrlen(cmdline);
5485 while ((next = strstr(next, "%j"))) {
5488 // replace %j with {} for xargs later
5497 while ((next = strstr(next, "%J"))) {
5500 // %J should be the last thing in the command
5501 if (next == cmdline + len - 2) {
5502 cmdline[len - 2] = '\0';
5508 // We can't handle both %j and %J in a single command
5513 snprintf(cmd, CMD_LEN_MAX + 32, xargs_j, cmdline, selpath);
5515 snprintf(cmd, CMD_LEN_MAX + 32, xargs_J, cmdline, selpath);
5517 cmd_ret = spawn(shell, "-c", (cnt_j || cnt_J) ? cmd : cmdline, NULL, F_CLI | F_CONFIRM);
5518 if ((cnt_j || cnt_J) && cmd_ret == 0)
5525 static bool handle_cmd(enum action sel, char *newpath)
5527 endselection(FALSE);
5529 if (sel == SEL_LAUNCH)
5530 return launch_app(newpath);
5534 if (sel == SEL_PROMPT)
5535 return prompt_run();
5537 /* Set nnn nesting level */
5538 char *tmp = getenv(env_cfg[NNNLVL]);
5539 int r = tmp ? atoi(tmp) : 0;
5541 setenv(env_cfg[NNNLVL], xitoa(r + 1), 1);
5542 spawn(shell, NULL, NULL, NULL, F_CLI);
5543 setenv(env_cfg[NNNLVL], xitoa(r), 1);
5547 static void dentfree(void)
5553 /* Thread data cleanup */
5559 static void *du_thread(void *p_data)
5561 thread_data *pdata = (thread_data *)p_data;
5562 char *path[2] = {pdata->path, NULL};
5563 ullong_t tfiles = 0;
5564 blkcnt_t tblocks = 0;
5566 FTS *tree = fts_open(path, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR, 0);
5569 while ((node = fts_read(tree))) {
5570 if (node->fts_info & FTS_D) {
5571 if (g_state.interrupt)
5576 sb = node->fts_statp;
5578 if (cfg.apparentsz) {
5579 if (sb->st_size && DU_TEST)
5580 tblocks += sb->st_size;
5581 } else if (sb->st_blocks && DU_TEST)
5582 tblocks += sb->st_blocks;
5589 if (pdata->entnum >= 0)
5590 pdents[pdata->entnum].blocks = tblocks;
5592 if (!pdata->mntpoint) {
5593 core_blocks[pdata->core] += tblocks;
5594 core_files[pdata->core] += tfiles;
5596 core_files[pdata->core] += 1;
5598 pthread_mutex_lock(&running_mutex);
5599 threadbmp |= (1 << pdata->core);
5601 pthread_mutex_unlock(&running_mutex);
5606 static void dirwalk(char *path, int entnum, bool mountpoint)
5608 /* Loop till any core is free */
5609 while (active_threads == NUM_DU_THREADS);
5611 if (g_state.interrupt)
5614 pthread_mutex_lock(&running_mutex);
5615 int core = ffs(threadbmp) - 1;
5617 threadbmp &= ~(1 << core);
5619 pthread_mutex_unlock(&running_mutex);
5621 xstrsncpy(core_data[core].path, path, PATH_MAX);
5622 core_data[core].entnum = entnum;
5623 core_data[core].core = (ushort_t)core;
5624 core_data[core].mntpoint = mountpoint;
5628 pthread_create(&tid, NULL, du_thread, (void *)&(core_data[core]));
5631 addstr(xbasename(path));
5632 addstr(" [^C aborts]\n");
5636 static bool prep_threads(void)
5638 if (!g_state.duinit) {
5640 threadbmp >>= (32 - NUM_DU_THREADS);
5643 core_blocks = calloc(NUM_DU_THREADS, sizeof(blkcnt_t));
5645 core_data = calloc(NUM_DU_THREADS, sizeof(thread_data));
5647 core_files = calloc(NUM_DU_THREADS, sizeof(ullong_t));
5649 if (!core_blocks || !core_data || !core_files) {
5654 /* Increase current open file descriptor limit */
5657 g_state.duinit = TRUE;
5659 memset(core_blocks, 0, NUM_DU_THREADS * sizeof(blkcnt_t));
5660 memset(core_data, 0, NUM_DU_THREADS * sizeof(thread_data));
5661 memset(core_files, 0, NUM_DU_THREADS * sizeof(ullong_t));
5666 /* Skip self and parent */
5667 static inline bool selforparent(const char *path)
5669 return path[0] == '.' && (path[1] == '\0' || (path[1] == '.' && path[2] == '\0'));
5672 static int dentfill(char *path, struct entry **ppdents)
5674 uchar_t entflags = 0;
5677 char *namep, *pnb, *buf;
5678 struct entry *dentp;
5679 size_t off = 0, namebuflen = NAMEBUF_INCR;
5680 struct stat sb_path, sb;
5681 DIR *dirp = opendir(path);
5684 gtimesecs = time(NULL);
5686 DPRINTF_S(__func__);
5691 int fd = dirfd(dirp);
5698 if (fstatat(fd, path, &sb_path, 0) == -1)
5702 ihashbmp = calloc(1, HASH_OCTETS << 3);
5706 memset(ihashbmp, 0, HASH_OCTETS << 3);
5708 if (!prep_threads())
5711 attron(COLOR_PAIR(cfg.curctx + 1));
5714 #if _POSIX_C_SOURCE >= 200112L
5715 posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
5722 #if defined(__sun) || defined(__HAIKU__)
5723 flags = AT_SYMLINK_NOFOLLOW; /* no d_type */
5725 if (cfg.blkorder || dp->d_type == DT_UNKNOWN) {
5727 * Optimization added for filesystems which support dirent.d_type
5730 * - the symlink size is set to 0
5731 * - the modification time of the symlink is set to that of the target file
5733 flags = AT_SYMLINK_NOFOLLOW;
5740 if (selforparent(namep))
5743 if (!cfg.showhidden && namep[0] == '.') {
5747 if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
5750 if (S_ISDIR(sb.st_mode)) {
5751 if (sb_path.st_dev == sb.st_dev) { // NOLINT
5752 mkpath(path, namep, buf); // NOLINT
5753 dirwalk(buf, -1, FALSE);
5755 if (g_state.interrupt)
5759 /* Do not recount hard links */
5760 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5761 dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5768 if (fstatat(fd, namep, &sb, flags) == -1) {
5769 if (flags || (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)) {
5774 DPRINTF_S(strerror(errno));
5777 entflags = FILE_MISSING;
5778 memset(&sb, 0, sizeof(struct stat));
5779 } else /* Orphaned symlink */
5780 entflags = SYM_ORPHAN;
5783 if (ndents == total_dents) {
5785 while (active_threads);
5787 total_dents += ENTRY_INCR;
5788 *ppdents = xrealloc(*ppdents, total_dents * sizeof(**ppdents));
5794 DPRINTF_P(*ppdents);
5797 /* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
5798 if (namebuflen - off < NAME_MAX + 1) {
5799 namebuflen += NAMEBUF_INCR;
5802 pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
5808 DPRINTF_P(pnamebuf);
5810 /* realloc() may result in memory move, we must re-adjust if that happens */
5811 if (pnb != pnamebuf) {
5813 dentp->name = pnamebuf;
5815 for (int count = 1; count < ndents; ++dentp, ++count)
5816 /* Current file name starts at last file name start + length */
5817 (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
5821 dentp = *ppdents + ndents;
5823 /* Selection file name */
5824 dentp->name = (char *)((size_t)pnamebuf + off);
5825 dentp->nlen = xstrsncpy(dentp->name, namep, NAME_MAX + 1);
5828 /* Copy other fields */
5829 if (cfg.timetype == T_MOD) {
5830 dentp->sec = sb.st_mtime;
5832 dentp->nsec = (uint_t)sb.st_mtimespec.tv_nsec;
5834 dentp->nsec = (uint_t)sb.st_mtim.tv_nsec;
5836 } else if (cfg.timetype == T_ACCESS) {
5837 dentp->sec = sb.st_atime;
5839 dentp->nsec = (uint_t)sb.st_atimespec.tv_nsec;
5841 dentp->nsec = (uint_t)sb.st_atim.tv_nsec;
5844 dentp->sec = sb.st_ctime;
5846 dentp->nsec = (uint_t)sb.st_ctimespec.tv_nsec;
5848 dentp->nsec = (uint_t)sb.st_ctim.tv_nsec;
5852 if ((gtimesecs - sb.st_mtime <= 300) || (gtimesecs - sb.st_ctime <= 300))
5853 entflags |= FILE_YOUNG;
5855 #if !(defined(__sun) || defined(__HAIKU__))
5856 if (!flags && dp->d_type == DT_LNK) {
5857 /* Do not add sizes for links */
5858 dentp->mode = (sb.st_mode & ~S_IFMT) | S_IFLNK;
5859 dentp->size = listpath ? sb.st_size : 0;
5861 dentp->mode = sb.st_mode;
5862 dentp->size = sb.st_size;
5865 dentp->mode = sb.st_mode;
5866 dentp->size = sb.st_size;
5870 dentp->uid = sb.st_uid;
5871 dentp->gid = sb.st_gid;
5874 dentp->flags = S_ISDIR(sb.st_mode) ? 0 : ((sb.st_nlink > 1) ? HARD_LINK : 0);
5876 dentp->flags |= entflags;
5881 if (S_ISDIR(sb.st_mode)) {
5882 mkpath(path, namep, buf); // NOLINT
5884 /* Need to show the disk usage of this dir */
5885 dirwalk(buf, ndents, (sb_path.st_dev != sb.st_dev)); // NOLINT
5887 if (g_state.interrupt)
5890 dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5891 /* Do not recount hard links */
5892 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5893 dir_blocks += dentp->blocks;
5899 /* Flag if this is a dir or symlink to a dir */
5900 if (S_ISLNK(sb.st_mode)) {
5902 fstatat(fd, namep, &sb, 0);
5905 if (S_ISDIR(sb.st_mode))
5906 dentp->flags |= DIR_OR_DIRLNK;
5907 #if !(defined(__sun) || defined(__HAIKU__)) /* no d_type */
5908 } else if (dp->d_type == DT_DIR || ((dp->d_type == DT_LNK
5909 || dp->d_type == DT_UNKNOWN) && S_ISDIR(sb.st_mode))) {
5910 dentp->flags |= DIR_OR_DIRLNK;
5915 } while ((dp = readdir(dirp)));
5918 if (g_state.duinit && cfg.blkorder) {
5919 while (active_threads);
5921 attroff(COLOR_PAIR(cfg.curctx + 1));
5922 for (int i = 0; i < NUM_DU_THREADS; ++i) {
5923 num_files += core_files[i];
5924 dir_blocks += core_blocks[i];
5928 /* Should never be null */
5929 if (closedir(dirp) == -1)
5935 static void populate(char *path, char *lastname)
5938 struct timespec ts1, ts2;
5940 clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
5943 ndents = dentfill(path, &pdents);
5948 ENTSORT(pdents, ndents, entrycmpfn);
5952 clock_gettime(CLOCK_REALTIME, &ts2);
5953 DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
5956 /* Find cur from history */
5957 /* No NULL check for lastname, always points to an array */
5958 move_cursor(*lastname ? dentfind(lastname, ndents) : 0, 0);
5960 // Force full redraw
5961 last_curscroll = -1;
5965 static void notify_fifo(bool force)
5971 fifofd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC);
5974 /* Unexpected error, the FIFO file might have been removed */
5975 /* We give up FIFO notification */
5981 static struct entry lastentry;
5983 if (!force && !memcmp(&lastentry, &pdents[cur], sizeof(struct entry))) // NOLINT
5986 lastentry = pdents[cur];
5988 char path[PATH_MAX];
5989 size_t len = mkpath(g_ctx[cfg.curctx].c_path, ndents ? pdents[cur].name : "", path);
5991 path[len - 1] = '\n';
5993 ssize_t ret = write(fifofd, path, len);
5995 if (ret != (ssize_t)len && !(ret == -1 && (errno == EAGAIN || errno == EPIPE))) {
5996 DPRINTF_S(strerror(errno));
6000 static void send_to_explorer(int *presel)
6003 int fd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0600);
6004 if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
6013 notify_fifo(TRUE); /* Send opened path to NNN_FIFO */
6017 static void move_cursor(int target, int ignore_scrolloff)
6019 int onscreen = xlines - 4; /* Leave top 2 and bottom 2 lines */
6021 target = MAX(0, MIN(ndents - 1, target));
6022 last_curscroll = curscroll;
6026 if (!ignore_scrolloff) {
6027 int delta = target - last;
6028 int scrolloff = MIN(SCROLLOFF, onscreen >> 1);
6031 * When ignore_scrolloff is 1, the cursor can jump into the scrolloff
6032 * margin area, but when ignore_scrolloff is 0, act like a boa
6033 * constrictor and squeeze the cursor towards the middle region of the
6034 * screen by allowing it to move inward and disallowing it to move
6035 * outward (deeper into the scrolloff margin area).
6037 if (((cur < (curscroll + scrolloff)) && delta < 0)
6038 || ((cur > (curscroll + onscreen - scrolloff - 1)) && delta > 0))
6041 curscroll = MIN(curscroll, MIN(cur, ndents - onscreen));
6042 curscroll = MAX(curscroll, MAX(cur - (onscreen - 1), 0));
6045 if (!g_state.fifomode)
6046 notify_fifo(FALSE); /* Send hovered path to NNN_FIFO */
6050 static void handle_screen_move(enum action sel)
6056 if (cfg.rollover || (cur != ndents - 1))
6057 move_cursor((cur + 1) % ndents, 0);
6060 if (cfg.rollover || cur)
6061 move_cursor((cur + ndents - 1) % ndents, 0);
6064 onscreen = xlines - 4;
6065 move_cursor(curscroll + (onscreen - 1), 1);
6066 curscroll += onscreen - 1;
6069 onscreen = xlines - 4;
6070 move_cursor(curscroll + (onscreen - 1), 1);
6071 curscroll += onscreen >> 1;
6074 onscreen = xlines - 4;
6075 move_cursor(curscroll, 1);
6076 curscroll -= onscreen - 1;
6079 onscreen = xlines - 4;
6080 move_cursor(curscroll, 1);
6081 curscroll -= onscreen >> 1;
6085 char *input = xreadline(NULL, "jump (+n/-n/n): ");
6087 if (!input || !*input)
6089 if (input[0] == '-') {
6090 cur -= atoi(input + 1);
6093 } else if (input[0] == '+') {
6094 cur += atoi(input + 1);
6098 int index = atoi(input);
6100 if ((index < 1) || (index > ndents))
6104 onscreen = xlines - 4;
6105 move_cursor(cur, 1);
6106 curscroll -= onscreen >> 1;
6113 move_cursor(ndents - 1, 1);
6115 default: /* case SEL_FIRST */
6117 int c = get_input(messages[MSG_FIRST]);
6124 int r = (c == TOUPPER(*pdents[cur].name)) ? (cur + 1) : 0;
6126 for (; r < ndents; ++r) {
6127 if (((c == '\'') && !(pdents[r].flags & DIR_OR_DIRLNK))
6128 || (c == TOUPPER(*pdents[r].name))) {
6129 move_cursor((r) % ndents, 0);
6138 static void handle_openwith(const char *path, const char *name, char *newpath, char *tmp)
6140 /* Confirm if app is CLI or GUI */
6141 int r = get_input(messages[MSG_CLI_MODE]);
6143 r = (r == 'c' ? F_CLI :
6144 ((r == 'g' || r == '\r') ? (F_NOWAIT | F_NOTRACE | F_MULTI) : 0));
6146 mkpath(path, name, newpath);
6147 spawn(tmp, newpath, NULL, NULL, r);
6151 static void copynextname(char *lastname)
6154 cur += (cur != (ndents - 1)) ? 1 : -1;
6160 static int handle_context_switch(enum action sel)
6165 case SEL_CYCLE: // fallthrough
6167 /* visit next and previous contexts */
6169 if (sel == SEL_CYCLE)
6171 r = (r + 1) & ~CTX_MAX;
6172 while (!g_ctx[r].c_cfg.ctxactive);
6174 do /* Attempt to create a new context */
6175 r = (r + 1) & ~CTX_MAX;
6176 while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
6178 if (r == cfg.curctx) /* If all contexts are active, reverse cycle */
6180 r = (r + (CTX_MAX - 1)) & (CTX_MAX - 1);
6181 while (!g_ctx[r].c_cfg.ctxactive);
6183 default: /* SEL_CTXN */
6184 if (sel >= SEL_CTX1) /* CYCLE keys are lesser in value */
6185 r = sel - SEL_CTX1; /* Save the next context id */
6187 if (cfg.curctx == r) {
6188 if (sel == SEL_CYCLE)
6189 (r == CTX_MAX - 1) ? (r = 0) : ++r;
6190 else if (sel == SEL_CYCLER)
6191 (r == 0) ? (r = CTX_MAX - 1) : --r;
6200 static int set_sort_flags(int r)
6202 bool session = (r == '\0');
6203 bool reverse = FALSE;
6205 if (ISUPPER_(r) && (r != 'R') && (r != 'C')) {
6210 /* Set the correct input in case of a session load */
6212 if (cfg.apparentsz) {
6215 } else if (cfg.blkorder) {
6221 namecmpfn = &xstrverscasecmp;
6224 entrycmpfn = &reventrycmp;
6225 } else if (r == CONTROL('T')) {
6226 /* Cycling order: clear -> size -> time -> clear */
6229 else if (cfg.sizeorder)
6236 case 'a': /* Apparent du */
6237 cfg.apparentsz ^= 1;
6238 if (cfg.apparentsz) {
6244 case 'd': /* Disk usage */
6246 if (!cfg.apparentsz)
6249 blk_shift = ffs(S_BLKSIZE) - 1;
6259 entrycmpfn = &entrycmp;
6261 endselection(TRUE); /* We are going to reload dir */
6271 entrycmpfn = &entrycmp;
6272 namecmpfn = &xstricmp;
6274 case 'e': /* File extension */
6281 entrycmpfn = &entrycmp;
6283 case 'r': /* Reverse sort */
6285 entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
6287 case 's': /* File size */
6294 entrycmpfn = &entrycmp;
6296 case 't': /* Time */
6303 entrycmpfn = &entrycmp;
6305 case 'v': /* Version */
6307 namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
6320 entrycmpfn = &reventrycmp;
6323 cfgsort[cfg.curctx] = (uchar_t)r;
6328 static bool set_time_type(int *presel)
6331 char buf[] = "'a'ccess / 'c'hange / 'm'od [ ]";
6333 buf[sizeof(buf) - 3] = cfg.timetype == T_MOD ? 'm' : (cfg.timetype == T_ACCESS ? 'a' : 'c');
6335 int r = get_input(buf);
6337 if (r == 'a' || r == 'c' || r == 'm') {
6338 r = (r == 'm') ? T_MOD : ((r == 'a') ? T_ACCESS : T_CHANGE);
6339 if (cfg.timetype != r) {
6342 if (cfg.filtermode || g_ctx[cfg.curctx].c_fltr[1])
6349 r = MSG_INVALID_KEY;
6352 printwait(messages[r], presel);
6357 static void statusbar(char *path)
6361 pEntry pent = &pdents[cur];
6368 /* Get the file extension for regular files */
6369 if (S_ISREG(pent->mode)) {
6370 i = (int)(pent->nlen - 1);
6371 ptr = xextension(pent->name, i);
6373 len = i - (ptr - pent->name);
6374 if (!ptr || len > 5 || len < 2)
6379 attron(COLOR_PAIR(cfg.curctx + 1));
6381 if (cfg.fileinfo && get_output("file", "-b", pdents[cur].name, -1, FALSE))
6382 mvaddstr(xlines - 2, 2, g_buf);
6386 printw("%d/%s ", cur + 1, xitoa(ndents));
6388 if (g_state.selmode || nselected) {
6391 if (g_state.rangesel)
6393 else if (g_state.selmode)
6396 addstr(xitoa(nselected));
6402 if (cfg.blkorder) { /* du mode */
6405 xstrsncpy(buf, coolsize(dir_blocks << blk_shift), 12);
6407 printw("%cu:%s avail:%s files:%llu %lluB %s\n",
6408 (cfg.apparentsz ? 'a' : 'd'), buf, coolsize(get_fs_info(path, VFS_AVAIL)),
6409 num_files, (ullong_t)pent->blocks << blk_shift, ptr);
6410 } else { /* light or detail mode */
6411 char sort[] = "\0\0\0\0\0";
6413 if (getorderstr(sort))
6417 print_time(&pent->sec, pent->flags);
6420 addstr(get_lsperms(pent->mode));
6423 if (g_state.uidgid) {
6424 addstr(getpwname(pent->uid));
6426 addstr(getgrname(pent->gid));
6430 if (S_ISLNK(pent->mode)) {
6431 if (!cfg.fileinfo) {
6432 i = readlink(pent->name, g_buf, PATH_MAX);
6433 addstr(coolsize(i >= 0 ? i : pent->size)); /* Show symlink size */
6434 if (i > 1) { /* Show symlink target */
6438 getyx(stdscr, len, y);
6439 i = MIN(i, xcols - y);
6445 addstr(coolsize(pent->size));
6448 if (pent->flags & HARD_LINK) {
6451 if (stat(pent->name, &sb) != -1) {
6453 addstr(xitoa((int)sb.st_nlink)); /* Show number of links */
6455 addstr(xitoa((int)sb.st_ino)); /* Show inode number */
6462 attroff(COLOR_PAIR(cfg.curctx + 1));
6463 /* Place HW cursor on current for Braille systems */
6467 static inline void markhovered(void)
6469 if (cfg.showdetail && ndents) { /* Bold forward arrowhead */
6471 addch('>' | A_BOLD);
6475 static int adjust_cols(int n)
6477 /* Calculate the number of cols available to print entry name */
6478 #ifdef ICONS_ENABLED
6479 n -= (g_state.oldcolor ? 0 : ICON_SIZE + ICON_PADDING_LEFT_LEN + ICON_PADDING_RIGHT_LEN);
6481 if (cfg.showdetail) {
6482 /* Fallback to light mode if less than 35 columns */
6484 cfg.showdetail ^= 1;
6485 else /* 2 more accounted for below */
6489 /* 2 columns for preceding space and indicator */
6493 static void draw_line(int ncols)
6497 ncols = adjust_cols(ncols);
6499 if (g_state.oldcolor && (pdents[last].flags & DIR_OR_DIRLNK)) {
6500 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6504 move(2 + last - curscroll, 0);
6505 printent(&pdents[last], ncols, FALSE);
6507 if (g_state.oldcolor && (pdents[cur].flags & DIR_OR_DIRLNK)) {
6508 if (!dir) {/* First file is not a directory */
6509 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6512 } else if (dir) { /* Second file is not a directory */
6513 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6517 move(2 + cur - curscroll, 0);
6518 printent(&pdents[cur], ncols, TRUE);
6520 /* Must reset e.g. no files in dir */
6522 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6527 static void redraw(char *path)
6529 getmaxyx(stdscr, xlines, xcols);
6531 int ncols = (xcols <= PATH_MAX) ? xcols : PATH_MAX;
6532 int onscreen = xlines - 4;
6539 if (ndents && (last_curscroll == curscroll))
6540 return draw_line(ncols);
6543 DPRINTF_S(__func__);
6548 /* Enforce scroll/cursor invariants */
6549 move_cursor(cur, 1);
6551 /* Fail redraw if < than 10 columns, context info prints 10 chars */
6552 if (ncols <= MIN_DISPLAY_COL) {
6553 printmsg(messages[MSG_FEW_COLUMNS]);
6560 for (i = 0; i < CTX_MAX; ++i) { /* 8 chars printed for contexts - "1 2 3 4 " */
6561 if (!g_ctx[i].c_cfg.ctxactive)
6564 addch((i + '1') | (COLOR_PAIR(i + 1) | A_BOLD
6565 /* active: underline, current: reverse */
6566 | ((cfg.curctx != i) ? A_UNDERLINE : A_REVERSE)));
6571 attron(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6574 bool in_home = set_tilde_in_path(path);
6575 char *ptr = in_home ? &path[homelen - 1] : path;
6577 i = (int)xstrlen(ptr);
6578 if ((i + MIN_DISPLAY_COL) <= ncols)
6579 addnstr(ptr, ncols - MIN_DISPLAY_COL);
6581 char *base = xmemrchr((uchar_t *)ptr, '/', i);
6590 if (ptr && (base != ptr)) {
6591 while (ptr < base) {
6593 i += 2; /* 2 characters added */
6594 if (ncols < i + MIN_DISPLAY_COL) {
6595 base = NULL; /* Can't print more characters */
6607 addnstr(base, ncols - (MIN_DISPLAY_COL + i));
6611 reset_tilde_in_path(path);
6613 attroff(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6615 /* Go to first entry */
6616 if (curscroll > 0) {
6618 #ifdef ICONS_ENABLED
6619 addstr(ICON_ARROW_UP);
6625 if (g_state.oldcolor) {
6626 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6627 g_state.dircolor = 1;
6630 onscreen = MIN(onscreen + curscroll, ndents);
6632 ncols = adjust_cols(ncols);
6634 int len = scanselforpath(path, FALSE);
6637 for (i = curscroll; i < onscreen; ++i) {
6641 findmarkentry(len, &pdents[i]);
6643 printent(&pdents[i], ncols, i == cur);
6646 /* Must reset e.g. no files in dir */
6647 if (g_state.dircolor) {
6648 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6649 g_state.dircolor = 0;
6652 /* Go to last entry */
6653 if (onscreen < ndents) {
6654 move(xlines - 2, 0);
6655 #ifdef ICONS_ENABLED
6656 addstr(ICON_ARROW_DOWN);
6665 static bool cdprep(char *lastdir, char *lastname, char *path, char *newpath)
6670 /* Save last working directory */
6671 xstrsncpy(lastdir, path, PATH_MAX);
6673 /* Save the newly opted dir in path */
6674 xstrsncpy(path, newpath, PATH_MAX);
6678 return cfg.filtermode;
6681 static void showselsize(const char *path)
6684 int len = scanselforpath(path, FALSE);
6686 for (int r = 0, selcount = nselected; (r < ndents) && selcount; ++r)
6687 if (findinsel(findselpos, len + xstrsncpy(g_sel + len, pdents[r].name, pdents[r].nlen))) {
6688 sz += cfg.blkorder ? pdents[r].blocks : pdents[r].size;
6692 printmsg(coolsize(cfg.blkorder ? sz << blk_shift : sz));
6695 static bool browse(char *ipath, const char *session, int pkey)
6697 alignas(max_align_t) char newpath[PATH_MAX];
6698 alignas(max_align_t) char runfile[NAME_MAX + 1];
6699 char *path, *lastdir, *lastname, *dir, *tmp;
6703 int r = -1, presel, selstartid = 0, selendid = 0;
6704 const uchar_t opener_flags = (cfg.cliopener ? F_CLI : (F_NOTRACE | F_NOSTDIN | F_NOWAIT));
6705 bool watch = FALSE, cd = TRUE;
6710 struct timespec mousetimings[2] = {{.tv_sec = 0, .tv_nsec = 0}, {.tv_sec = 0, .tv_nsec = 0}};
6711 int mousedent[2] = {-1, -1};
6712 bool currentmouse = 1, rightclicksel = 0;
6717 getmaxyx(stdscr, xlines, xcols);
6720 /* set-up first context */
6721 if (!session || !load_session(session, &path, &lastdir, &lastname, FALSE)) {
6725 g_ctx[0].c_last[0] = '\0';
6726 lastdir = g_ctx[0].c_last; /* last visited directory */
6728 if (g_state.initfile) {
6729 xstrsncpy(g_ctx[0].c_name, xbasename(ipath), sizeof(g_ctx[0].c_name));
6732 g_ctx[0].c_name[0] = '\0';
6734 lastname = g_ctx[0].c_name; /* last visited file name */
6736 xstrsncpy(g_ctx[0].c_path, ipath, PATH_MAX);
6737 /* If the initial path is a file, retain a way to return to start dir */
6738 if (g_state.initfile) {
6740 initpath = ipath = getcwd(NULL, 0);
6742 path = g_ctx[0].c_path; /* current directory */
6744 g_ctx[0].c_fltr[0] = g_ctx[0].c_fltr[1] = '\0';
6745 g_ctx[0].c_cfg = cfg; /* current configuration */
6750 newpath[0] = runfile[0] = '\0';
6752 presel = pkey ? ((pkey == CREATE_NEW_KEY) ? 'n' : ';') : ((cfg.filtermode
6753 || (session && (g_ctx[cfg.curctx].c_fltr[0] == FILTER
6754 || g_ctx[cfg.curctx].c_fltr[0] == RFILTER)
6755 && g_ctx[cfg.curctx].c_fltr[1])) ? FILTER : 0);
6757 pdents = xrealloc(pdents, total_dents * sizeof(struct entry));
6761 /* Allocate buffer to hold names */
6762 pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
6766 /* The following call is added to handle a broken window at start */
6767 if (presel == FILTER)
6768 handle_key_resize();
6772 * Can fail when permissions change while browsing.
6773 * It's assumed that path IS a directory when we are here.
6775 if (chdir(path) == -1) {
6776 DPRINTF_S("directory inaccessible");
6777 valid_parent(path, lastname);
6785 #ifdef LINUX_INOTIFY
6786 if ((presel == FILTER || watch) && inotify_wd >= 0) {
6787 inotify_rm_watch(inotify_fd, inotify_wd);
6791 #elif defined(BSD_KQUEUE)
6792 if ((presel == FILTER || watch) && event_fd >= 0) {
6797 #elif defined(HAIKU_NM)
6798 if ((presel == FILTER || watch) && haiku_hnd != NULL) {
6799 haiku_stop_watch(haiku_hnd);
6800 haiku_nm_active = FALSE;
6806 if (cfgsort[cfg.curctx] != '0') {
6807 if (cfgsort[cfg.curctx] == 'z')
6808 set_sort_flags('c');
6809 if ((!cfgsort[cfg.curctx] || (cfgsort[cfg.curctx] == 'c'))
6810 && ((r = get_kv_key(order, path, maxorder, NNN_ORDER)) > 0)) { // NOLINT
6812 cfgsort[cfg.curctx] = 'z';
6815 cfgsort[cfg.curctx] = cfgsort[CTX_MAX];
6819 populate(path, lastname);
6820 if (g_state.interrupt) {
6821 g_state.interrupt = cfg.apparentsz = cfg.blkorder = 0;
6822 blk_shift = BLK_SHIFT_512;
6823 presel = CONTROL('L');
6826 #ifdef LINUX_INOTIFY
6827 if (presel != FILTER && inotify_wd == -1)
6828 inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
6829 #elif defined(BSD_KQUEUE)
6830 if (presel != FILTER && event_fd == -1) {
6831 #if defined(O_EVTONLY)
6832 event_fd = open(path, O_EVTONLY);
6834 event_fd = open(path, O_RDONLY);
6837 EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
6838 EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
6840 #elif defined(HAIKU_NM)
6841 haiku_nm_active = haiku_watch_dir(haiku_hnd, path) == EXIT_SUCCESS;
6845 /* Do not do a double redraw in filterentries */
6846 if ((presel != FILTER) || !filterset()) {
6852 /* Exit if parent has exited */
6854 _exit(EXIT_FAILURE);
6856 /* If CWD is deleted or moved or perms changed, find an accessible parent */
6857 if (chdir(path) == -1)
6860 /* If STDIN is no longer a tty (closed) we should exit */
6861 if (!isatty(STDIN_FILENO) && !g_state.picker)
6862 return EXIT_FAILURE;
6864 sel = nextsel(presel);
6871 if (getmouse(&event) != OK)
6874 /* Handle clicking on a context at the top */
6875 if (event.bstate == BUTTON1_PRESSED && event.y == 0) {
6876 /* Get context from: "[1 2 3 4]..." */
6879 /* If clicked after contexts, go to parent */
6882 else if (r >= 0 && r != cfg.curctx) {
6883 savecurctx(path, ndents ? pdents[cur].name : NULL, r);
6885 /* Reset the pointers */
6886 path = g_ctx[r].c_path;
6887 lastdir = g_ctx[r].c_last;
6888 lastname = g_ctx[r].c_name;
6898 if (sel == SEL_BACK) {
6900 dir = visit_parent(path, newpath, &presel);
6905 xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
6907 cdprep(lastdir, NULL, path, dir) ? (presel = FILTER) : (watch = TRUE);
6914 /* Middle click action */
6915 if (event.bstate == BUTTON2_PRESSED) {
6916 presel = middle_click_key;
6919 #if NCURSES_MOUSE_VERSION > 1
6921 if (event.bstate == BUTTON4_PRESSED && ndents && (cfg.rollover || cur)) {
6922 move_cursor((!cfg.rollover && cur < scroll_lines
6923 ? 0 : (cur + ndents - scroll_lines) % ndents), 0);
6928 if (event.bstate == BUTTON5_PRESSED && ndents
6929 && (cfg.rollover || (cur != ndents - 1))) {
6930 move_cursor((!cfg.rollover && cur >= ndents - scroll_lines)
6931 ? (ndents - 1) : ((cur + scroll_lines) % ndents), 0);
6936 /* Toggle filter mode on left click on last 2 lines */
6937 if (event.y >= xlines - 2 && event.bstate == BUTTON1_PRESSED) {
6939 cfg.filtermode ^= 1;
6940 if (cfg.filtermode) {
6945 /* Start watching the directory */
6952 /* Handle clicking on a file */
6953 if (event.y >= 2 && event.y <= ndents + 1 &&
6954 (event.bstate == BUTTON1_PRESSED ||
6955 event.bstate == BUTTON3_PRESSED)) {
6956 r = curscroll + (event.y - 2);
6960 else if ((event.bstate == BUTTON1_PRESSED) && !g_state.fifomode)
6961 notify_fifo(TRUE); /* Send clicked path to NNN_FIFO */
6963 /* Handle right click selection */
6964 if (event.bstate == BUTTON3_PRESSED) {
6972 #if defined(CLOCK_MONOTONIC_RAW)
6973 CLOCK_MONOTONIC_RAW,
6974 #elif defined(CLOCK_MONOTONIC)
6979 &mousetimings[currentmouse]);
6980 mousedent[currentmouse] = cur;
6982 /* Single click just selects, double click falls through to SEL_OPEN */
6983 if ((mousedent[0] != mousedent[1]) ||
6984 (((_ABSSUB(mousetimings[0].tv_sec, mousetimings[1].tv_sec) << 30)
6985 + (_ABSSUB(mousetimings[0].tv_nsec, mousetimings[1].tv_nsec)))
6986 > DBLCLK_INTERVAL_NS))
6989 mousetimings[currentmouse].tv_sec = 0;
6990 mousedent[currentmouse] = -1;
6993 if (cfg.filtermode || filterset())
7000 case SEL_NAV_IN: // fallthrough
7002 /* Cannot descend in empty directories */
7005 g_state.selbm = g_state.runplugin = 0;
7009 pent = &pdents[cur];
7010 if (!g_state.selbm || !(S_ISLNK(pent->mode) &&
7011 realpath(pent->name, newpath) &&
7012 xstrsncpy(path, lastdir, PATH_MAX)))
7013 mkpath(path, pent->name, newpath);
7017 /* Visit directory */
7018 if (pent->flags & DIR_OR_DIRLNK) {
7019 if (chdir(newpath) == -1) {
7024 cdprep(lastdir, lastname, path, newpath) ? (presel = FILTER) : (watch = TRUE);
7028 /* Cannot use stale data in entry, file may be missing by now */
7029 if (stat(newpath, &sb) == -1) {
7033 DPRINTF_U(sb.st_mode);
7035 /* Do not open non-regular files */
7036 if (!S_ISREG(sb.st_mode)) {
7037 printwait(messages[MSG_UNSUPPORTED], &presel);
7041 /* Handle plugin selection mode */
7042 if (g_state.runplugin) {
7043 g_state.runplugin = 0;
7044 /* Must be in plugin dir and same context to select plugin */
7045 if ((g_state.runctx == cfg.curctx) && !strcmp(path, plgpath)) {
7046 endselection(FALSE);
7047 /* Copy path so we can return back to earlier dir */
7048 xstrsncpy(path, lastdir, PATH_MAX);
7051 if (chdir(path) == -1
7052 || !run_plugin(&path, pent->name, runfile, &lastname, &lastdir)) {
7053 DPRINTF_S("plugin failed!");
7057 return EXIT_SUCCESS;
7060 xstrsncpy(lastname, runfile, NAME_MAX + 1);
7069 if (g_state.fifomode && (sel == SEL_OPEN)) {
7070 send_to_explorer(&presel); /* Write selection to explorer fifo */
7074 /* If opened as vim plugin and Enter/^M pressed, pick */
7075 if (g_state.picker && (sel == SEL_OPEN)) {
7076 if (nselected == 0) /* Pick if none selected */
7077 appendfpath(newpath, mkpath(path, pent->name, newpath));
7078 return EXIT_SUCCESS;
7081 if (sel == SEL_NAV_IN) {
7082 /* If in listing dir, go to target on `l` or Right on symlink */
7083 if (listpath && S_ISLNK(pent->mode)
7084 && is_prefix(path, listpath, xstrlen(listpath))) {
7085 if (!realpath(pent->name, newpath)) {
7092 if (chdir(newpath) == -1) {
7097 cdprep(lastdir, NULL, path, newpath)
7098 ? (presel = FILTER) : (watch = TRUE);
7099 xstrsncpy(lastname, pent->name, NAME_MAX + 1);
7103 /* Open file disabled on right arrow or `l` */
7109 printwait(messages[MSG_EMPTY_FILE], &presel);
7114 #ifdef FILE_MIME_OPTS
7115 && get_output("file", FILE_MIME_OPTS, newpath, -1, FALSE)
7116 && is_prefix(g_buf, "text/", 5)
7118 /* no MIME option; guess from description instead */
7119 && get_output("file", "-bL", newpath, -1, FALSE)
7120 && strstr(g_buf, "text")
7123 spawn(editor, newpath, NULL, NULL, F_CLI);
7124 if (cfg.filtermode) {
7131 /* Get the extension for regex match */
7132 tmp = xextension(pent->name, pent->nlen - 1);
7134 if (tmp && !pcre_exec(archive_pcre, NULL, tmp,
7135 pent->nlen - (tmp - pent->name) - 1, 0, 0, NULL, 0)) {
7137 if (tmp && !regexec(&archive_re, tmp, 0, NULL, 0)) {
7139 r = get_input(messages[MSG_ARCHIVE_OPTS]);
7142 if (r == 'l' || r == 'x') {
7143 mkpath(path, pent->name, newpath);
7144 if (!handle_archive(newpath, r)) {
7154 if ((r == 'm') && !archive_mount(newpath)) {
7159 if (r == 'x' || r == 'm') {
7161 set_smart_ctx('+', newpath, &path,
7162 ndents ? pdents[cur].name : NULL,
7163 &lastname, &lastdir);
7171 printwait(messages[MSG_INVALID_KEY], &presel);
7176 /* Invoke desktop opener as last resort */
7177 spawn(opener, newpath, NULL, NULL, opener_flags);
7179 /* Move cursor to the next entry if not the last entry */
7180 if (g_state.autonext && cur != ndents - 1)
7181 move_cursor((cur + 1) % ndents, 0);
7182 if (cfg.filtermode) {
7187 case SEL_NEXT: // fallthrough
7188 case SEL_PREV: // fallthrough
7189 case SEL_PGDN: // fallthrough
7190 case SEL_CTRL_D: // fallthrough
7191 case SEL_PGUP: // fallthrough
7192 case SEL_CTRL_U: // fallthrough
7193 case SEL_HOME: // fallthrough
7194 case SEL_END: // fallthrough
7195 case SEL_FIRST: // fallthrough
7199 handle_screen_move(sel);
7202 case SEL_CDHOME: // fallthrough
7203 case SEL_CDBEGIN: // fallthrough
7204 case SEL_CDLAST: // fallthrough
7206 dir = (sel == SEL_CDHOME) ? home
7207 : ((sel == SEL_CDBEGIN) ? ipath
7208 : ((sel == SEL_CDLAST) ? lastdir
7209 : "/" /* SEL_CDROOT */));
7211 if (!dir || !*dir) {
7212 printwait(messages[MSG_NOT_SET], &presel);
7217 if (strcmp(path, dir) == 0) {
7223 dir = lastdir; /* Go to last dir on home/root key repeat */
7226 if (chdir(dir) == -1) {
7231 /* SEL_CDLAST: dir pointing to lastdir */
7232 xstrsncpy(newpath, dir, PATH_MAX); // fallthrough
7234 if (sel == SEL_BMOPEN) {
7235 r = (int)handle_bookmark(mark, newpath);
7237 printwait(messages[r], &presel);
7241 if (g_state.selbm == 1) /* Allow filtering in bookmarks directory */
7243 if (strcmp(path, newpath) == 0)
7247 /* In list mode, retain the last file name to highlight it, if possible */
7248 cdprep(lastdir, listpath && sel == SEL_CDLAST ? NULL : lastname, path, newpath)
7249 ? (presel = FILTER) : (watch = TRUE);
7252 if ((sel == SEL_REMOTE) && !remote_mount(newpath)) {
7257 set_smart_ctx('+', newpath, &path,
7258 ndents ? pdents[cur].name : NULL, &lastname, &lastdir);
7261 case SEL_CYCLE: // fallthrough
7262 case SEL_CYCLER: // fallthrough
7263 case SEL_CTX1: // fallthrough
7264 case SEL_CTX2: // fallthrough
7265 case SEL_CTX3: // fallthrough
7273 r = handle_context_switch(sel);
7276 savecurctx(path, ndents ? pdents[cur].name : NULL, r);
7278 /* Reset the pointers */
7279 path = g_ctx[r].c_path;
7280 lastdir = g_ctx[r].c_last;
7281 lastname = g_ctx[r].c_name;
7282 tmp = g_ctx[r].c_fltr;
7284 if (cfg.filtermode || ((tmp[0] == FILTER || tmp[0] == RFILTER) && tmp[1]))
7292 mark = xstrdup(path);
7293 printwait(mark, &presel);
7296 add_bookmark(path, newpath, &presel);
7299 /* Unwatch dir if we are still in a filtered view */
7300 #ifdef LINUX_INOTIFY
7301 if (inotify_wd >= 0) {
7302 inotify_rm_watch(inotify_fd, inotify_wd);
7305 #elif defined(BSD_KQUEUE)
7306 if (event_fd >= 0) {
7310 #elif defined(HAIKU_NM)
7311 if (haiku_nm_active) {
7312 haiku_stop_watch(haiku_hnd);
7313 haiku_nm_active = FALSE;
7316 presel = filterentries(path, lastname);
7317 if (presel == ESC) {
7321 if (presel == FILTER) { /* Refresh dir and filter again */
7326 case SEL_MFLTR: // fallthrough
7327 case SEL_HIDDEN: // fallthrough
7328 case SEL_DETAIL: // fallthrough
7332 cfg.filtermode ^= 1;
7333 if (cfg.filtermode) {
7339 watch = TRUE; // fallthrough
7341 if (sel == SEL_HIDDEN) {
7342 cfg.showhidden ^= 1;
7351 cfg.showdetail ^= 1;
7354 default: /* SEL_SORT */
7355 r = set_sort_flags(get_input(messages[MSG_ORDER]));
7357 printwait(messages[MSG_INVALID_KEY], &presel);
7362 if (cfg.filtermode || filterset())
7368 if (r == 'd' || r == 'a') {
7373 ENTSORT(pdents, ndents, entrycmpfn);
7374 move_cursor(ndents ? dentfind(lastname, ndents) : 0, 0);
7377 case SEL_STATS: // fallthrough
7380 tmp = (listpath && xstrcmp(path, listpath) == 0) ? listroot : path;
7381 mkpath(tmp, pdents[cur].name, newpath);
7383 if ((sel == SEL_STATS && !show_stats(newpath))
7384 || (lstat(newpath, &sb) == -1)
7385 || (sel == SEL_CHMODX && !xchmod(newpath, sb.st_mode))) {
7390 if (sel == SEL_CHMODX)
7391 pdents[cur].mode ^= 0111;
7394 case SEL_REDRAW: // fallthrough
7395 case SEL_RENAMEMUL: // fallthrough
7396 case SEL_HELP: // fallthrough
7397 case SEL_AUTONEXT: // fallthrough
7398 case SEL_EDIT: // fallthrough
7401 bool refresh = FALSE;
7404 mkpath(path, pdents[cur].name, newpath);
7405 else if (sel == SEL_EDIT) /* Avoid trying to edit a non-existing file */
7414 setenv("NNN_INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
7415 setenv("NNN_PREFER_SELECTION", xitoa(cfg.prefersel), 1);
7416 setenv("NNN_LIST", listpath ? listroot : "", 1);
7418 if (!(getutil(utils[UTIL_BASH])
7419 && plugscript(utils[UTIL_NMV], F_CLI))
7424 printwait(messages[MSG_FAILED], &presel);
7431 show_help(path); // fallthrough
7433 if (sel == SEL_AUTONEXT)
7434 g_state.autonext ^= 1;
7440 if (!(g_state.picker || g_state.fifomode))
7441 spawn(editor, newpath, NULL, NULL, F_CLI);
7443 default: /* SEL_LOCK */
7448 /* In case of successful operation, reload contents */
7450 /* Continue in type-to-nav mode, if enabled */
7451 if ((cfg.filtermode || filterset()) && !refresh) {
7458 /* Repopulate as directory content may have changed */
7467 if (g_state.rangesel)
7468 g_state.rangesel = 0;
7470 /* Toggle selection status */
7471 pdents[cur].flags ^= FILE_SELECTED;
7473 if (pdents[cur].flags & FILE_SELECTED) {
7475 appendfpath(newpath, mkpath(path, pdents[cur].name, newpath));
7476 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
7479 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
7484 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7491 /* move cursor to the next entry if this is not the last entry */
7492 if (!g_state.stayonsel && (cur != ndents - 1))
7493 move_cursor((cur + 1) % ndents, 0);
7500 g_state.rangesel ^= 1;
7502 if (stat(path, &sb) == -1) {
7507 if (g_state.rangesel) { /* Range selection started */
7513 if (inode != sb.st_ino) {
7514 printwait(messages[MSG_DIR_CHANGED], &presel);
7518 if (cur < selstartid) {
7519 selendid = selstartid;
7524 /* Clear selection on repeat on same file */
7525 if (selstartid == selendid) {
7530 case SEL_SELALL: // fallthrough
7532 if (sel == SEL_SELALL || sel == SEL_SELINV) {
7537 if (g_state.rangesel)
7538 g_state.rangesel = 0;
7541 selendid = ndents - 1;
7544 if ((nselected > LARGESEL) || (nselected && (ndents > LARGESEL))) {
7545 printmsg("processing...");
7549 r = scanselforpath(path, TRUE); /* Get path length suffixed by '/' */
7550 ((sel == SEL_SELINV) && findselpos)
7551 ? invertselbuf(r) : addtoselbuf(r, selstartid, selendid);
7555 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7559 r = editselection();
7561 r = !r ? MSG_0_SELECTED : MSG_FAILED;
7562 printwait(messages[r], &presel);
7566 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7568 cfg.filtermode ? presel = FILTER : statusbar(path);
7571 case SEL_CP: // fallthrough
7572 case SEL_MV: // fallthrough
7573 case SEL_CPMVAS: // fallthrough
7576 if (sel == SEL_RM) {
7577 r = get_cur_or_sel();
7584 tmp = (listpath && xstrcmp(path, listpath) == 0)
7586 mkpath(tmp, pdents[cur].name, newpath);
7590 xrmfromsel(tmp, newpath);
7592 copynextname(lastname);
7594 if (cfg.filtermode || filterset())
7601 (nselected == 1 && (sel == SEL_CP || sel == SEL_MV))
7602 ? mkpath(path, xbasename(pselbuf), newpath)
7603 : (newpath[0] = '\0');
7607 if (!cpmvrm_selection(sel, path)) {
7617 /* Show notification on operation complete */
7619 plugscript(utils[UTIL_NTFY], F_NOWAIT | F_NOTRACE);
7622 if (newpath[0] && !access(newpath, F_OK))
7623 xstrsncpy(lastname, xbasename(newpath), NAME_MAX+1);
7629 case SEL_ARCHIVE: // fallthrough
7630 case SEL_OPENWITH: // fallthrough
7631 case SEL_NEW: // fallthrough
7637 if (!ndents && (sel == SEL_OPENWITH || sel == SEL_RENAME))
7640 if (sel != SEL_OPENWITH)
7645 r = get_cur_or_sel();
7659 tmp = pdents[cur].name;
7661 tmp = xreadline(tmp, messages[MSG_ARCHIVE_NAME]);
7665 if (g_state.picker) {
7667 tmp = xreadline(NULL, messages[MSG_OPEN_WITH]);
7670 tmp = getreadline(messages[MSG_OPEN_WITH]);
7675 r = get_input(messages[MSG_NEW_OPTS]);
7681 tmp = g_ctx[0].c_name;
7685 if (r == 'f' || r == 'd')
7686 tmp = xreadline(tmp, messages[MSG_NEW_PATH]);
7687 else if (r == 's' || r == 'h')
7688 tmp = xreadline(NULL,
7689 messages[nselected <= 1 ? MSG_NEW_PATH : MSG_LINK_PREFIX]);
7693 default: /* SEL_RENAME */
7694 tmp = xreadline(pdents[cur].name, "");
7698 if (!tmp || !*tmp || is_bad_len_or_dir(tmp))
7703 if (r == 'c' && strcmp(tmp, pdents[cur].name) == 0)
7704 continue; /* Cannot overwrite the hovered file */
7706 tmp = abspath(tmp, NULL, newpath);
7709 if (access(tmp, F_OK) == 0) {
7710 if (!xconfirm(get_input(messages[MSG_OVERWRITE]))) {
7716 (r == 's') ? archive_selection(get_archive_cmd(tmp), tmp)
7717 : spawn(get_archive_cmd(tmp), tmp, pdents[cur].name,
7718 NULL, F_CLI | F_CONFIRM);
7720 if (tmp && (access(tmp, F_OK) == 0)) { /* File created */
7722 clearselection(); /* Archive operation complete */
7724 /* Check if any entry is created in the current directory */
7725 tmp = get_cwd_entry(path, tmp, &len);
7727 xstrsncpy(lastname, tmp, len + 1);
7728 clearfilter(); /* Archive name may not match */
7729 } if (cfg.filtermode)
7736 handle_openwith(path, pdents[cur].name, newpath, tmp);
7738 cfg.filtermode ? presel = FILTER : statusbar(path);
7743 /* Skip renaming to same name */
7744 if (strcmp(tmp, pdents[cur].name) == 0) {
7745 tmp = xreadline(pdents[cur].name, messages[MSG_COPY_NAME]);
7746 if (!tmp || !tmp[0] || is_bad_len_or_dir(tmp)
7747 || !strcmp(tmp, pdents[cur].name)) {
7748 cfg.filtermode ? presel = FILTER : statusbar(path);
7755 default: /* SEL_NEW */
7759 if (!(r == 's' || r == 'h')) {
7760 tmp = abspath(tmp, NULL, newpath);
7767 /* Check if another file with same name exists */
7768 if (lstat(tmp, &sb) == 0) {
7769 if ((sel == SEL_RENAME) || ((r == 'f') && (S_ISREG(sb.st_mode)))) {
7770 /* Overwrite file with same name? */
7771 if (!xconfirm(get_input(messages[MSG_OVERWRITE])))
7774 /* Do nothing for SEL_NEW if a non-regular entry exists */
7775 printwait(messages[MSG_EXISTS], &presel);
7780 if (sel == SEL_RENAME) {
7781 /* Rename the file */
7783 spawn("cp -rp", pdents[cur].name, tmp, NULL, F_SILENT);
7784 else if (rename(pdents[cur].name, tmp) != 0) {
7789 /* Check if any entry is created in the current directory */
7790 tmp = get_cwd_entry(path, tmp, &len);
7792 xstrsncpy(lastname, tmp, len + 1);
7793 /* Directory must be reloeaded for rename case */
7794 } else { /* SEL_NEW */
7797 /* Check if it's a dir or file */
7798 if (r == 'f' || r == 'd') {
7799 ret = xmktree(tmp, r == 'f' ? FALSE : TRUE);
7800 } else if (r == 's' || r == 'h') {
7801 if (nselected > 1 && tmp[0] == '@' && tmp[1] == '\0')
7803 ret = xlink(tmp, path, (ndents ? pdents[cur].name : NULL), newpath, r);
7812 if (r == 'f' || r == 'd') {
7813 tmp = get_cwd_entry(path, tmp, &len);
7815 xstrsncpy(lastname, tmp, len + 1);
7817 continue; /* No change in directory */
7818 } else if (ndents) {
7830 /* Check if directory is accessible */
7831 if (!xdiraccess(plgpath)) {
7837 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
7838 printkeys(plug, g_buf + r - 1, maxplug);
7840 r = get_input(NULL);
7847 endselection(FALSE);
7848 tmp = get_kv_val(plug, NULL, r, maxplug, NNN_PLUG);
7850 printwait(messages[MSG_INVALID_KEY], &presel);
7854 if (tmp[0] == '-' && tmp[1]) {
7856 r = FALSE; /* Do not refresh dir after completion */
7860 if (!run_plugin(&path, tmp, (ndents ? pdents[cur].name : NULL),
7861 &lastname, &lastdir)) {
7862 printwait(messages[MSG_FAILED], &presel);
7867 return EXIT_SUCCESS;
7872 cfg.filtermode ? presel = FILTER : statusbar(path);
7875 } else { /* 'Return/Enter' enters the plugin directory */
7876 g_state.runplugin ^= 1;
7877 if (!g_state.runplugin) {
7879 * If toggled, and still in the plugin dir,
7880 * switch to original directory
7882 if (strcmp(path, plgpath) == 0) {
7883 xstrsncpy(path, lastdir, PATH_MAX);
7884 xstrsncpy(lastname, runfile, NAME_MAX + 1);
7890 /* Otherwise, initiate choosing plugin again */
7891 g_state.runplugin = 1;
7894 xstrsncpy(lastdir, path, PATH_MAX);
7895 xstrsncpy(path, plgpath, PATH_MAX);
7897 xstrsncpy(runfile, pdents[cur].name, NAME_MAX);
7898 g_state.runctx = cfg.curctx;
7903 if (g_state.runplugin == 1) /* Allow filtering in plugins directory */
7909 case SEL_SHELL: // fallthrough
7910 case SEL_LAUNCH: // fallthrough
7912 r = handle_cmd(sel, newpath);
7914 /* Continue in type-to-nav mode, if enabled */
7924 /* Repopulate as directory content may have changed */
7929 if (!unmount((ndents ? pdents[cur].name : NULL), newpath, &presel, path)) {
7930 if (presel == MSG_ZERO)
7935 /* Dir removed, go to next entry */
7936 copynextname(lastname);
7941 r = get_input(messages[MSG_SSN_OPTS]);
7944 tmp = xreadline(NULL, messages[MSG_SSN_NAME]);
7946 save_session(tmp, &presel);
7947 } else if (r == 'l' || r == 'r') {
7948 if (load_session(NULL, &path, &lastdir, &lastname, r == 'r')) {
7959 cfg.filtermode ? presel = FILTER : statusbar(path);
7962 if (!set_time_type(&presel))
7966 case SEL_QUITCTX: // fallthrough
7967 case SEL_QUITCD: // fallthrough
7970 if (sel == SEL_QUITCTX) {
7971 int ctx = cfg.curctx;
7973 for (r = (ctx - 1) & (CTX_MAX - 1);
7974 (r != ctx) && !g_ctx[r].c_cfg.ctxactive;
7975 r = ((r - 1) & (CTX_MAX - 1))) {
7979 g_ctx[ctx].c_cfg.ctxactive = 0;
7981 /* Switch to next active context */
7982 path = g_ctx[r].c_path;
7983 lastdir = g_ctx[r].c_last;
7984 lastname = g_ctx[r].c_name;
7986 cfg = g_ctx[r].c_cfg;
7992 } else if (!g_state.forcequit) {
7993 for (r = 0; r < CTX_MAX; ++r)
7994 if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
7995 r = get_input(messages[MSG_QUIT_ALL]);
7999 if (!(r == CTX_MAX || xconfirm(r)))
8000 break; // fallthrough
8004 tmp = getenv("NNN_TMPFILE");
8005 if ((sel == SEL_QUITCD) || tmp) {
8006 write_lastdir(path, tmp);
8007 /* ^G is a way to quit picker mode without picking anything */
8008 if ((sel == SEL_QUITCD) && g_state.picker)
8012 if (sel != SEL_QUITERR)
8013 return EXIT_SUCCESS;
8015 if (selbufpos && !g_state.picker) {
8016 /* Pick files to stdout and exit */
8020 return EXIT_SUCCESS;
8023 return EXIT_FAILURE;
8025 if (xlines != LINES || xcols != COLS)
8028 if (idletimeout && idle == idletimeout) {
8029 lock_terminal(); /* Locker */
8035 } /* switch (sel) */
8039 static char *make_tmp_tree(char **paths, ssize_t entries, const char *prefix)
8041 /* tmpdir holds the full path */
8042 /* tmp holds the path without the tmp dir prefix */
8046 ssize_t len = xstrlen(prefix);
8047 char *tmpdir = malloc(PATH_MAX);
8050 DPRINTF_S(strerror(errno));
8054 tmp = tmpdir + tmpfplen - 1;
8055 xstrsncpy(tmpdir, g_tmpfpath, tmpfplen);
8056 xstrsncpy(tmp, "/nnnXXXXXX", 11);
8058 /* Points right after the base tmp dir */
8061 /* handle the case where files are directly under / */
8062 if (!prefix[1] && (prefix[0] == '/'))
8065 if (!mkdtemp(tmpdir)) {
8068 DPRINTF_S(strerror(errno));
8074 for (ssize_t i = 0; i < entries; ++i) {
8078 err = stat(paths[i], &sb);
8079 if (err && errno == ENOENT)
8082 /* Don't copy the common prefix */
8083 xstrsncpy(tmp, paths[i] + len, xstrlen(paths[i]) - len + 1);
8085 /* Get the dir containing the path */
8086 slash = xmemrchr((uchar_t *)tmp, '/', xstrlen(paths[i]) - len);
8090 if (access(tmpdir, F_OK)) /* Create directory if it doesn't exist */
8091 xmktree(tmpdir, TRUE);
8096 if (symlink(paths[i], tmpdir)) {
8097 DPRINTF_S(paths[i]);
8098 DPRINTF_S(strerror(errno));
8102 /* Get the dir in which to start */
8107 static char *load_input(int fd, const char *path)
8109 size_t i, chunk_count = 1, chunk = 512UL * 1024 /* 512 KiB chunk size */, entries = 0;
8110 char *input = malloc(sizeof(char) * chunk), *tmpdir = NULL;
8111 char cwd[PATH_MAX], *next;
8112 size_t offsets[LIST_FILES_MAX];
8113 char **paths = NULL;
8114 ssize_t input_read, total_read = 0, off = 0;
8118 DPRINTF_S(strerror(errno));
8123 if (!getcwd(cwd, PATH_MAX)) {
8128 xstrsncpy(cwd, path, PATH_MAX);
8130 while (chunk_count < LIST_INPUT_MAX / chunk && !msgnum) {
8131 input_read = read(fd, input + total_read, chunk);
8132 if (input_read < 0) {
8136 DPRINTF_S(strerror(errno));
8140 if (input_read == 0)
8143 total_read += input_read;
8145 while (off < total_read) {
8146 next = memchr(input + off, '\0', total_read - off);
8151 if (next - input == off + 1) {
8156 if (entries == LIST_FILES_MAX) {
8157 msgnum = MSG_FILE_LIMIT;
8161 offsets[entries++] = off;
8165 /* We don't need to allocate another chunk */
8166 if (chunk_count > (total_read + chunk - 1) / chunk)
8169 /* We can never need more than one additional chunk */
8171 if (chunk_count > LIST_INPUT_MAX / chunk) {
8172 msgnum = MSG_SIZE_LIMIT;
8176 input = xrealloc(input, chunk_count * chunk);
8181 /* We close fd outside this function. Any extra data is left to the kernel to handle */
8183 if (off != total_read) {
8184 if (entries == LIST_FILES_MAX)
8185 msgnum = MSG_FILE_LIMIT;
8187 offsets[entries++] = off;
8191 DPRINTF_D(total_read);
8192 DPRINTF_D(chunk_count);
8195 msgnum = MSG_0_ENTRIES;
8199 input[total_read] = '\0';
8201 paths = malloc(entries * sizeof(char *));
8205 for (i = 0; i < entries; ++i)
8206 paths[i] = input + offsets[i];
8208 listroot = malloc(sizeof(char) * PATH_MAX);
8213 DPRINTF_S(paths[0]);
8215 for (i = 0; i < entries; ++i) {
8216 if (paths[i][0] == '\n' || selforparent(paths[i])) {
8221 paths[i] = abspath(paths[i], cwd, NULL);
8223 entries = i; // free from the previous entry
8227 DPRINTF_S(paths[i]);
8229 xstrsncpy(g_buf, paths[i], PATH_MAX);
8230 if (!common_prefix(xdirname(g_buf), listroot)) {
8231 entries = i + 1; // free from the current entry
8235 DPRINTF_S(listroot);
8238 DPRINTF_S(listroot);
8241 tmpdir = make_tmp_tree(paths, entries, listroot);
8244 for (i = 0; i < entries; ++i)
8247 if (msgnum) { /* Check if we are past init stage and show msg */
8249 printmsg(messages[msgnum]);
8250 xdelay(XDELAY_INTERVAL_MS << 2);
8252 msg(messages[msgnum]);
8253 usleep(XDELAY_INTERVAL_MS << 2);
8262 static void check_key_collision(void)
8265 bool bitmap[KEY_MAX] = {FALSE};
8267 for (ullong_t i = 0; i < ELEMENTS(bindings); ++i) {
8268 key = bindings[i].sym;
8271 dprintf(STDERR_FILENO, "key collision! [%s]\n", keyname(key));
8277 static void usage(void)
8279 dprintf(STDOUT_FILENO,
8280 "%s: nnn [OPTIONS] [PATH]\n\n"
8281 "The unorthodox terminal file manager.\n\n"
8282 "positional args:\n"
8283 " PATH start dir/file [default: .]\n\n"
8286 " -a auto NNN_FIFO\n"
8288 " -A no dir auto-enter during filter\n"
8289 " -b key open bookmark key (trumps -s/S)\n"
8290 " -B use bsdtar for archives\n"
8291 " -c cli-only NNN_OPENER (trumps -e)\n"
8292 " -C 8-color scheme\n"
8294 " -D dirs in context color\n"
8295 " -e text in $VISUAL/$EDITOR/vi\n"
8296 " -E internal edits in EDITOR\n"
8298 " -f use readline history file\n"
8301 " -F val fifo mode [0:preview 1:explore]\n"
8303 " -g regex filters\n"
8304 " -H show hidden files\n"
8305 " -i show current file info\n"
8306 " -J no auto-advance on selection\n"
8307 " -K detect key collision and exit\n"
8308 " -l val set scroll lines\n"
8309 " -n type-to-nav mode\n"
8310 " -o open files only on Enter\n"
8311 " -p file selection file [-:stdout]\n"
8312 " -P key run plugin key\n"
8313 " -Q no quit confirmation\n"
8314 " -r use advcpmv patched cp, mv\n"
8315 " -R no rollover at edges\n"
8317 " -s name load session by name\n"
8318 " -S persistent session\n"
8320 " -t secs timeout to lock\n"
8321 " -T key sort order [a/d/e/r/s/t/v]\n"
8322 " -u use selection (no prompt)\n"
8324 " -U show user and group\n"
8326 " -V show version\n"
8328 " -x notis, selection sync, xterm title\n"
8331 "v%s\n%s\n", __func__, VERSION, GENERAL_INFO);
8334 static bool setup_config(void)
8337 char *xdgcfg = getenv("XDG_CONFIG_HOME");
8340 /* Set up configuration file paths */
8341 if (xdgcfg && xdgcfg[0]) {
8343 if (tilde_is_home(xdgcfg)) {
8344 r = xstrsncpy(g_buf, home, PATH_MAX);
8345 xstrsncpy(g_buf + r - 1, xdgcfg + 1, PATH_MAX);
8350 if (!xdiraccess(xdgcfg)) {
8355 len = xstrlen(xdgcfg) + xstrlen("/nnn/bookmarks") + 1;
8360 len = xstrlen(home) + xstrlen("/.config/nnn/bookmarks") + 1;
8362 cfgpath = (char *)malloc(len);
8363 plgpath = (char *)malloc(len);
8364 if (!cfgpath || !plgpath) {
8370 xstrsncpy(cfgpath, xdgcfg, len);
8371 r = len - xstrlen("/nnn/bookmarks");
8373 r = xstrsncpy(cfgpath, home, len);
8375 /* Create ~/.config */
8376 xstrsncpy(cfgpath + r - 1, "/.config", len - r);
8378 r += 8; /* length of "/.config" */
8381 /* Create ~/.config/nnn */
8382 xstrsncpy(cfgpath + r - 1, "/nnn", len - r);
8385 /* Create bookmarks, sessions, mounts and plugins directories */
8386 for (r = 0; r < ELEMENTS(toks); ++r) {
8387 mkpath(cfgpath, toks[r], plgpath);
8388 /* The dirs are created on first run, check if they already exist */
8389 if (access(plgpath, F_OK) && !xmktree(plgpath, TRUE)) {
8396 /* Set selection file path */
8397 if (!g_state.picker) {
8398 char *env_sel = xgetenv(env_cfg[NNN_SEL], NULL);
8400 selpath = env_sel ? xstrdup(env_sel)
8401 : (char *)malloc(len + 3); /* Length of "/.config/nnn/.selection" */
8409 r = xstrsncpy(selpath, cfgpath, len + 3);
8410 xstrsncpy(selpath + r - 1, "/.selection", 12);
8418 static bool set_tmp_path(void)
8421 char *path = xdiraccess(tmp) ? tmp : getenv("TMPDIR");
8428 tmpfplen = (uchar_t)xstrsncpy(g_tmpfpath, path, TMP_LEN_MAX);
8429 DPRINTF_S(g_tmpfpath);
8430 DPRINTF_U(tmpfplen);
8435 static void cleanup(void)
8438 if (cfg.x11 && !g_state.picker) {
8439 printf("\033[23;0t"); /* reset terminal window title */
8455 if (g_state.autofifo)
8458 if (g_state.pluginit)
8465 int main(int argc, char *argv[])
8468 char *session = NULL;
8469 int fd, opt, sort = 0, pkey = '\0'; /* Plugin key */
8472 char *middle_click_env = xgetenv(env_cfg[NNN_MCLICK], "\0");
8474 middle_click_key = (middle_click_env[0] == '^' && middle_click_env[1])
8475 ? CONTROL(middle_click_env[1])
8476 : (uchar_t)middle_click_env[0];
8479 const char * const env_opts = xgetenv(env_cfg[NNN_OPTS], NULL);
8480 int env_opts_id = env_opts ? (int)xstrlen(env_opts) : -1;
8482 bool rlhist = FALSE;
8485 while ((opt = (env_opts_id > 0
8486 ? env_opts[--env_opts_id]
8487 : getopt(argc, argv, "aAb:BcCdDeEfF:gHiJKl:nop:P:QrRs:St:T:uUVxh"))) != -1) {
8491 g_state.autofifo = 1;
8498 if (env_opts_id < 0)
8502 g_state.usebsdtar = 1;
8508 g_state.oldcolor = 1;
8529 if (env_opts_id < 0) {
8531 if ((fd < 0) || (fd > 1))
8532 return EXIT_FAILURE;
8533 g_state.fifomode = fd;
8539 filterfn = &visible_re;
8548 g_state.stayonsel = 1;
8551 check_key_collision();
8552 return EXIT_SUCCESS;
8554 if (env_opts_id < 0)
8555 scroll_lines = atoi(optarg);
8564 if (env_opts_id >= 0)
8568 if (!(optarg[0] == '-' && optarg[1] == '\0')) {
8569 fd = open(optarg, O_WRONLY | O_CREAT, 0600);
8572 return EXIT_FAILURE;
8576 selpath = abspath(optarg, NULL, NULL);
8581 if (env_opts_id < 0 && !optarg[1])
8582 pkey = (uchar_t)optarg[0];
8585 g_state.forcequit = 1;
8589 cp[2] = cp[5] = mv[2] = mv[5] = 'g'; /* cp -iRp -> cpg -giRp */
8590 cp[4] = mv[4] = '-';
8598 if (env_opts_id < 0)
8602 g_state.prstssn = 1;
8603 if (!session) /* Support named persistent sessions */
8608 if (env_opts_id < 0)
8609 idletimeout = atoi(optarg);
8612 if (env_opts_id < 0)
8613 sort = (uchar_t)optarg[0];
8622 dprintf(STDOUT_FILENO, "%s\n", VERSION);
8623 return EXIT_SUCCESS;
8629 return EXIT_SUCCESS;
8632 return EXIT_FAILURE;
8634 if (env_opts_id == 0)
8643 /* Prefix for temporary files */
8644 if (!set_tmp_path())
8645 return EXIT_FAILURE;
8649 /* Check if we are in path list mode */
8650 if (!isatty(STDIN_FILENO)) {
8651 /* This is the same as listpath */
8652 initpath = load_input(STDIN_FILENO, NULL);
8654 return EXIT_FAILURE;
8656 /* We return to tty */
8657 if (!isatty(STDOUT_FILENO)) {
8658 fd = open(ctermid(NULL), O_RDONLY, 0400);
8659 dup2(fd, STDIN_FILENO);
8662 dup2(STDOUT_FILENO, STDIN_FILENO);
8668 home = getenv("HOME");
8671 return EXIT_FAILURE;
8674 homelen = (uchar_t)xstrlen(home);
8676 if (!setup_config())
8677 return EXIT_FAILURE;
8679 /* Get custom opener, if set */
8680 opener = xgetenv(env_cfg[NNN_OPENER], utils[UTIL_OPENER]);
8683 /* Parse bookmarks string */
8684 if (!parsekvpair(&bookmark, &bmstr, NNN_BMS, &maxbm)) {
8685 msg(env_cfg[NNN_BMS]);
8686 return EXIT_FAILURE;
8689 /* Parse plugins string */
8690 if (!parsekvpair(&plug, &pluginstr, NNN_PLUG, &maxplug)) {
8691 msg(env_cfg[NNN_PLUG]);
8692 return EXIT_FAILURE;
8695 /* Parse order string */
8696 if (!parsekvpair(&order, &orderstr, NNN_ORDER, &maxorder)) {
8697 msg(env_cfg[NNN_ORDER]);
8698 return EXIT_FAILURE;
8702 if (arg) { /* Open a bookmark directly */
8703 if (!arg[1]) /* Bookmarks keys are single char */
8704 initpath = get_kv_val(bookmark, NULL, *arg, maxbm, NNN_BMS);
8707 msg(messages[MSG_INVALID_KEY]);
8708 return EXIT_FAILURE;
8713 } else if (argc == optind) {
8714 /* Start in the current directory */
8715 char *startpath = getenv("PWD");
8717 initpath = startpath ? xstrdup(startpath) : getcwd(NULL, 0);
8720 } else { /* Open a file */
8723 size_t len = xstrlen(arg);
8725 if (len > 7 && is_prefix(arg, "file://", 7)) {
8729 initpath = abspath(arg, NULL, NULL);
8730 DPRINTF_S(initpath);
8733 return EXIT_FAILURE;
8736 /* If the file is hidden, enable hidden option */
8737 if (*xbasename(initpath) == '.')
8741 * If nnn is set as the file manager, applications may try to open
8742 * files by invoking nnn. In that case pass the file path to the
8743 * desktop opener and exit.
8747 if (stat(initpath, &sb) == -1) {
8748 bool dir = (arg[len - 1] == '/');
8751 arg = xbasename(initpath);
8752 initpath = xdirname(initpath);
8754 pkey = CREATE_NEW_KEY; /* Override plugin key */
8755 g_state.initfile = 1;
8757 if (dir || (arg != initpath)) { /* We have a directory */
8758 if (!xdiraccess(initpath) && !xmktree(initpath, TRUE)) {
8759 xerror(); /* Fail if directory cannot be created */
8760 return EXIT_FAILURE;
8762 if (!dir) /* Restore the complete path */
8765 } else if (!S_ISDIR(sb.st_mode))
8766 g_state.initfile = 1;
8773 /* Set archive handling (enveditor used as tmp var) */
8774 enveditor = getenv(env_cfg[NNN_ARCHIVE]);
8776 if (setfilter(&archive_pcre, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8778 if (setfilter(&archive_re, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8780 msg(messages[MSG_INVALID_REG]);
8781 return EXIT_FAILURE;
8784 /* An all-CLI opener overrides option -e) */
8788 /* Get VISUAL/EDITOR */
8789 enveditor = xgetenv(envs[ENV_EDITOR], utils[UTIL_VI]);
8790 editor = xgetenv(envs[ENV_VISUAL], enveditor);
8791 DPRINTF_S(getenv(envs[ENV_VISUAL]));
8792 DPRINTF_S(getenv(envs[ENV_EDITOR]));
8796 pager = xgetenv(envs[ENV_PAGER], utils[UTIL_LESS]);
8800 shell = xgetenv(envs[ENV_SHELL], utils[UTIL_SH]);
8803 DPRINTF_S(getenv("PWD"));
8807 if (g_state.autofifo) {
8808 g_tmpfpath[tmpfplen - 1] = '\0';
8810 size_t r = mkpath(g_tmpfpath, "nnn-fifo.", g_buf);
8812 xstrsncpy(g_buf + r - 1, xitoa(getpid()), PATH_MAX - r);
8813 setenv("NNN_FIFO", g_buf, TRUE);
8816 fifopath = xgetenv("NNN_FIFO", NULL);
8818 if (mkfifo(fifopath, 0600) != 0 && !(errno == EEXIST && access(fifopath, W_OK) == 0)) {
8820 return EXIT_FAILURE;
8823 sigaction(SIGPIPE, &(struct sigaction){.sa_handler = SIG_IGN}, NULL);
8827 #ifdef LINUX_INOTIFY
8828 /* Initialize inotify */
8829 inotify_fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
8830 if (inotify_fd < 0) {
8832 return EXIT_FAILURE;
8834 #elif defined(BSD_KQUEUE)
8838 return EXIT_FAILURE;
8840 #elif defined(HAIKU_NM)
8841 haiku_hnd = haiku_init_nm();
8844 return EXIT_FAILURE;
8848 /* Configure trash preference */
8849 opt = xgetenv_val(env_cfg[NNN_TRASH]);
8850 if (opt && opt <= 2)
8851 g_state.trash = opt;
8853 /* Ignore/handle certain signals */
8854 struct sigaction act = {.sa_handler = sigint_handler};
8856 if (sigaction(SIGINT, &act, NULL) < 0) {
8858 return EXIT_FAILURE;
8861 act.sa_handler = clean_exit_sighandler;
8863 if (sigaction(SIGTERM, &act, NULL) < 0 || sigaction(SIGHUP, &act, NULL) < 0) {
8865 return EXIT_FAILURE;
8868 act.sa_handler = SIG_IGN;
8870 if (sigaction(SIGQUIT, &act, NULL) < 0) {
8872 return EXIT_FAILURE;
8877 setlocale(LC_ALL, "");
8879 tables = pcre_maketables();
8884 #if RL_READLINE_VERSION >= 0x0603
8885 /* readline would overwrite the WINCH signal hook */
8886 rl_change_environment = 0;
8888 /* Bind TAB to cycling */
8889 rl_variable_bind("completion-ignore-case", "on");
8891 rl_bind_key('\t', rl_menu_complete);
8893 rl_bind_key('\t', rl_complete);
8896 mkpath(cfgpath, ".history", g_buf);
8897 read_history(g_buf);
8902 if (cfg.x11 && !g_state.picker) {
8903 /* Save terminal window title */
8904 printf("\033[22;0t");
8906 gethostname(hostname, sizeof(hostname));
8907 hostname[sizeof(hostname) - 1] = '\0';
8912 if (!initcurses(&mask))
8914 if (!initcurses(NULL))
8916 return EXIT_FAILURE;
8919 set_sort_flags(sort);
8921 opt = browse(initpath, session, pkey);
8924 if (session && g_state.prstssn)
8925 save_session(session, NULL);
8929 mousemask(mask, NULL);
8936 mkpath(cfgpath, ".history", g_buf);
8937 write_history(g_buf);
8941 if (g_state.picker) {
8943 fd = selpath ? open(selpath, O_WRONLY | O_CREAT | O_TRUNC, 0600) : STDOUT_FILENO;
8944 if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
8953 /* Remove tmp dir in list mode */
8956 /* Free the regex */
8958 pcre_free(archive_pcre);
8960 regfree(&archive_re);
8963 /* Free the selection buffer */
8966 #ifdef LINUX_INOTIFY
8967 /* Shutdown inotify */
8968 if (inotify_wd >= 0)
8969 inotify_rm_watch(inotify_fd, inotify_wd);
8971 #elif defined(BSD_KQUEUE)
8975 #elif defined(HAIKU_NM)
8976 haiku_close_nm(haiku_hnd);
8980 if (!g_state.fifomode)