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
539 #define UTIL_ARCHMNT 21
541 /* Utilities to open files, run actions */
542 static char * const utils[] = {
545 #elif defined __CYGWIN__
547 #elif defined __HAIKU__
558 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
560 #elif defined __HAIKU__
584 #define MSG_ZERO 0 /* Unused */
585 #define MSG_0_ENTRIES 1
586 #define STR_TMPFILE 2
587 #define MSG_0_SELECTED 3
590 #define MSG_SSN_NAME 6
591 #define MSG_CP_MV_AS 7
592 #define MSG_CUR_SEL_OPTS 8
593 #define MSG_FORCE_RM 9
594 #define MSG_SIZE_LIMIT 10
595 #define MSG_NEW_OPTS 11
596 #define MSG_CLI_MODE 12
597 #define MSG_OVERWRITE 13
598 #define MSG_SSN_OPTS 14
599 #define MSG_QUIT_ALL 15
600 #define MSG_HOSTNAME 16
601 #define MSG_ARCHIVE_NAME 17
602 #define MSG_OPEN_WITH 18
603 #define MSG_NEW_PATH 19
604 #define MSG_LINK_PREFIX 20
605 #define MSG_COPY_NAME 21
607 #define MSG_SEL_MISSING 23
608 #define MSG_ACCESS 24
609 #define MSG_EMPTY_FILE 25
610 #define MSG_UNSUPPORTED 26
611 #define MSG_NOT_SET 27
612 #define MSG_EXISTS 28
613 #define MSG_FEW_COLUMNS 29
614 #define MSG_REMOTE_OPTS 30
615 #define MSG_RCLONE_DELAY 31
616 #define MSG_APP_NAME 32
617 #define MSG_ARCHIVE_OPTS 33
619 #define MSG_INVALID_REG 35
623 #define MSG_RM_TMP 39
624 #define MSG_INVALID_KEY 40
625 #define MSG_NOCHANGE 41
626 #define MSG_DIR_CHANGED 42
627 #define MSG_BM_NAME 43
628 #define MSG_FILE_LIMIT 44
630 static const char * const messages[] = {
640 "%s %s? [Esc cancels]",
641 "size limit exceeded",
642 "['f'ile]/'d'ir/'s'ym/'h'ard?",
645 "'s'ave/'l'oad/'r'estore?",
646 "Quit all contexts?",
647 "remote name (- for hovered): ",
648 "archive [path/]name: ",
651 "link prefix [@ for none]: ",
652 "copy [path/]name: ",
653 "\n'Enter' to continue",
656 "empty! edit/open with",
664 "['l's]/'o'pen/e'x'tract/'m'nt?",
667 "'a'u/'d'u/'e'xt/'r'ev/'s'z/'t'm/'v'er/'c'lr/'^T'?",
668 "unmount failed! try lazy?",
669 "first file (\')/char?",
673 "dir changed, range sel off",
675 "file limit exceeded",
678 /* Supported configuration environment variables */
684 #define NNN_FCOLORS 5
689 #define NNN_ARCHIVE 10
691 #define NNN_HELP 12 /* strings end here */
692 #define NNN_TRASH 13 /* flags begin here */
694 static const char * const env_cfg[] = {
711 /* Required environment variables */
718 static const char * const envs[] = {
731 #define PROGRESS_CP "cpg -giRp"
732 #define PROGRESS_MV "mvg -gi"
733 static char cp[sizeof PROGRESS_CP] = "cp -iRp";
734 static char mv[sizeof PROGRESS_MV] = "mv -i";
736 /* Archive commands */
737 static char * const archive_cmd[] = {"atool -a", "bsdtar -acvf", "zip -r", "tar -acvf"};
739 /* Tokens used for path creation */
745 static const char * const toks[] = {
749 "plugins", /* must be the last entry */
757 #define P_ARCHIVE_CMD 4
759 static const char * const patterns[] = {
760 SED" -i 's|^\\(\\(.*/\\)\\(.*\\)$\\)|#\\1\\n\\3|' %s",
761 SED" 's|^\\([^#/][^/]\\?.*\\)$|%s/\\1|;s|^#\\(/.*\\)$|\\1|' "
762 "%s | tr '\\n' '\\0' | xargs -0 -n2 sh -c '%s \"$0\" \"$@\" < /dev/tty'",
763 "\\.(bz|bz2|gz|tar|taz|tbz|tbz2|tgz|z|zip)$", /* Basic formats that don't need external tools */
764 SED" -i 's|^%s\\(.*\\)$|%s\\1|' %s",
765 "xargs -0 %s %s < '%s'",
769 #define C_BLK (CTX_MAX + 1) /* Block device: DarkSeaGreen1 */
770 #define C_CHR (C_BLK + 1) /* Character device: Yellow1 */
771 #define C_DIR (C_CHR + 1) /* Directory: DeepSkyBlue1 */
772 #define C_EXE (C_DIR + 1) /* Executable file: Green1 */
773 #define C_FIL (C_EXE + 1) /* Regular file: Normal */
774 #define C_HRD (C_FIL + 1) /* Hard link: Plum4 */
775 #define C_LNK (C_HRD + 1) /* Symbolic link: Cyan1 */
776 #define C_MIS (C_LNK + 1) /* Missing file OR file details: Grey62 */
777 #define C_ORP (C_MIS + 1) /* Orphaned symlink: DeepPink1 */
778 #define C_PIP (C_ORP + 1) /* Named pipe (FIFO): Orange1 */
779 #define C_SOC (C_PIP + 1) /* Socket: MediumOrchid1 */
780 #define C_UND (C_SOC + 1) /* Unknown OR 0B regular/exe file: Red1 */
782 static char gcolors[] = "c1e2272e006033f7c6d6abc4";
783 static uint_t fcolors[C_UND + 1] = {0};
787 #define NUM_EVENT_SLOTS 32 /* Make room for 32 events */
788 #define EVENT_SIZE (sizeof(struct inotify_event))
789 #define EVENT_BUF_LEN (EVENT_SIZE * NUM_EVENT_SLOTS)
790 static int inotify_fd, inotify_wd = -1;
791 static uint_t INOTIFY_MASK = /* IN_ATTRIB | */ IN_CREATE | IN_DELETE | IN_DELETE_SELF
792 | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
793 #elif defined(BSD_KQUEUE)
794 #define NUM_EVENT_SLOTS 1
795 #define NUM_EVENT_FDS 1
796 static int kq, event_fd = -1;
797 static struct kevent events_to_monitor[NUM_EVENT_FDS];
798 static uint_t KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK
799 | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
800 static struct timespec gtimeout;
801 #elif defined(HAIKU_NM)
802 static bool haiku_nm_active = FALSE;
803 static haiku_nm_h haiku_hnd;
806 /* Function macros */
807 #define tolastln() move(xlines - 1, 0)
808 #define tocursor() move(cur + 2 - curscroll, 0)
809 #define exitcurses() endwin()
810 #define printwarn(presel) printwait(strerror(errno), presel)
811 #define istopdir(path) ((path)[1] == '\0' && (path)[0] == '/')
812 #define copycurname() xstrsncpy(lastname, ndents ? pdents[cur].name : "\0", NAME_MAX + 1)
813 #define settimeout() timeout(1000)
814 #define cleartimeout() timeout(-1)
815 #define errexit() printerr(__LINE__)
816 #define setdirwatch() (cfg.filtermode ? (presel = FILTER) : (watch = TRUE))
817 #define filterset() (g_ctx[cfg.curctx].c_fltr[1])
818 /* We don't care about the return value from strcmp() */
819 #define xstrcmp(a, b) (*(a) != *(b) ? -1 : strcmp((a), (b)))
820 /* A faster version of xisdigit */
821 #define xisdigit(c) ((unsigned int) (c) - '0' <= 9)
822 #define xerror() perror(xitoa(__LINE__))
825 #define ENTLESS(i, j) (entrycmpfn(pdents + (i), pdents + (j)) < 0)
826 #define ENTSWAP(i, j) (swap_ent((i), (j)))
827 #define ENTSORT(pdents, ndents, entrycmpfn) QSORT((ndents), ENTLESS, ENTSWAP)
829 #define ENTSORT(pdents, ndents, entrycmpfn) qsort((pdents), (ndents), sizeof(*(pdents)), (entrycmpfn))
832 /* Forward declarations */
833 static void redraw(char *path);
834 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag);
835 static void move_cursor(int target, int ignore_scrolloff);
836 static char *load_input(int fd, const char *path);
837 static int set_sort_flags(int r);
838 static void statusbar(char *path);
839 static bool get_output(char *file, char *arg1, char *arg2, int fdout, bool page);
841 static void notify_fifo(bool force);
846 static void sigint_handler(int sig)
849 g_state.interrupt = 1;
852 static void clean_exit_sighandler(int sig)
856 /* This triggers cleanup() thanks to atexit() */
860 static char *xitoa(uint_t val)
862 static char dst[32] = {'\0'};
863 static const char digits[201] =
864 "0001020304050607080910111213141516171819"
865 "2021222324252627282930313233343536373839"
866 "4041424344454647484950515253545556575859"
867 "6061626364656667686970717273747576777879"
868 "8081828384858687888990919293949596979899";
869 uint_t next = 30, quo, i;
873 i = (val - (quo * 100)) * 2;
875 dst[next] = digits[i + 1];
876 dst[--next] = digits[i];
880 /* Handle last 1-2 digits */
882 dst[next] = '0' + val;
885 dst[next] = digits[i + 1];
886 dst[--next] = digits[i];
892 /* Return the integer value of a char representing HEX */
893 static uchar_t xchartohex(uchar_t c)
898 if (c >= 'a' && c <= 'f')
901 if (c >= 'A' && c <= 'F')
908 * Source: https://elixir.bootlin.com/linux/latest/source/arch/alpha/include/asm/bitops.h
910 static bool test_set_bit(uint_t nr)
914 pthread_mutex_lock(&hardlink_mutex);
915 ullong_t *m = ((ullong_t *)ihashbmp) + (nr >> 6);
917 if (*m & (1 << (nr & 63))) {
918 pthread_mutex_unlock(&hardlink_mutex);
922 *m |= 1 << (nr & 63);
923 pthread_mutex_unlock(&hardlink_mutex);
929 /* Increase the limit on open file descriptors, if possible */
930 static void max_openfds(void)
934 if (!getrlimit(RLIMIT_NOFILE, &rl))
935 if (rl.rlim_cur < rl.rlim_max) {
936 rl.rlim_cur = rl.rlim_max;
937 setrlimit(RLIMIT_NOFILE, &rl);
943 * Wrapper to realloc()
944 * Frees current memory if realloc() fails and returns NULL.
946 * The *alloc() family returns aligned address: https://man7.org/linux/man-pages/man3/malloc.3.html
948 static void *xrealloc(void *pcur, size_t len)
950 void *pmem = realloc(pcur, len);
959 * Just a safe strncpy(3)
960 * Always null ('\0') terminates if both src and dest are valid pointers.
961 * Returns the number of bytes copied including terminating null byte.
963 static size_t xstrsncpy(char *restrict dst, const char *restrict src, size_t n)
965 char *end = memccpy(dst, src, '\0', n);
968 dst[n - 1] = '\0'; // NOLINT
969 end = dst + n; /* If we return n here, binary size increases due to auto-inlining */
975 static inline size_t xstrlen(const char *restrict s)
977 #if !defined(__GLIBC__)
978 return strlen(s); // NOLINT
980 return (char *)rawmemchr(s, '\0') - s; // NOLINT
984 static char *xstrdup(const char *restrict s)
986 size_t len = xstrlen(s) + 1;
987 char *ptr = malloc(len);
988 return ptr ? memcpy(ptr, s, len) : NULL;
991 static bool is_suffix(const char *restrict str, const char *restrict suffix)
996 size_t lenstr = xstrlen(str);
997 size_t lensuffix = xstrlen(suffix);
999 if (lensuffix > lenstr)
1002 return (xstrcmp(str + (lenstr - lensuffix), suffix) == 0);
1005 static inline bool is_prefix(const char *restrict str, const char *restrict prefix, size_t len)
1007 return !strncmp(str, prefix, len);
1010 static inline bool is_bad_len_or_dir(const char *restrict path)
1012 size_t len = xstrlen(path);
1014 return ((len >= PATH_MAX) || (path[len - 1] == '/'));
1017 static char *get_cwd_entry(const char *restrict cwdpath, char *entrypath, size_t *tokenlen)
1019 size_t len = xstrlen(cwdpath);
1022 if (!is_prefix(entrypath, cwdpath, len))
1025 entrypath += len + 1; /* Add 1 for trailing / */
1026 end = strchr(entrypath, '/');
1028 *tokenlen = end - entrypath;
1030 *tokenlen = xstrlen(entrypath);
1031 DPRINTF_U(*tokenlen);
1037 * The poor man's implementation of memrchr(3).
1038 * We are only looking for '/' and '.' in this program.
1039 * And we are NOT expecting a '/' at the end.
1040 * Ideally 0 < n <= xstrlen(s).
1042 static void *xmemrchr(uchar_t *restrict s, uchar_t ch, size_t n)
1044 #if defined(__GLIBC__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
1045 return memrchr(s, ch, n);
1051 uchar_t *ptr = s + n;
1062 /* A very simplified implementation, changes path */
1063 static char *xdirname(char *path)
1065 char *base = xmemrchr((uchar_t *)path, '/', xstrlen(path));
1075 static char *xbasename(char *path)
1077 char *base = xmemrchr((uchar_t *)path, '/', xstrlen(path)); // NOLINT
1079 return base ? base + 1 : path;
1082 static inline char *xextension(const char *fname, size_t len)
1084 return xmemrchr((uchar_t *)fname, '.', len);
1089 * One-shot cache for getpwuid/getgrgid. Returns the cached name if the
1090 * provided uid is the same as the previous uid. Returns xitoa(guid) if
1091 * the guid is not found in the password database.
1093 static char *getpwname(uid_t uid)
1095 static uint_t uidcache = UINT_MAX;
1096 static char *namecache;
1098 if (uidcache != uid) {
1099 struct passwd *pw = getpwuid(uid);
1102 namecache = pw ? pw->pw_name : NULL;
1105 return namecache ? namecache : xitoa(uid);
1108 static char *getgrname(gid_t gid)
1110 static uint_t gidcache = UINT_MAX;
1111 static char *grpcache;
1113 if (gidcache != gid) {
1114 struct group *gr = getgrgid(gid);
1117 grpcache = gr ? gr->gr_name : NULL;
1120 return grpcache ? grpcache : xitoa(gid);
1124 static inline bool getutil(char *util)
1126 return spawn("which", util, NULL, NULL, F_NORMAL | F_NOTRACE) == 0;
1129 static inline bool tilde_is_home(const char *s)
1131 return s[0] == '~' && (s[1] == '\0' || s[1] == '/');
1134 static inline bool tilde_is_home_strict(const char *s)
1136 return s[0] == '~' && s[1] == '/';
1140 * Updates out with "dir/name or "/name"
1141 * Returns the number of bytes copied including the terminating NULL byte
1143 * Note: dir and out must be PATH_MAX in length to avoid macOS fault
1145 static size_t mkpath(const char *dir, const char *name, char *out)
1149 /* same rational for being strict as abspath() */
1150 if (tilde_is_home_strict(name)) { //NOLINT
1151 len = xstrsncpy(out, home, PATH_MAX);
1154 } else if (name[0] != '/') { // NOLINT
1155 /* Handle root case */
1156 len = istopdir(dir) ? 1 : xstrsncpy(out, dir, PATH_MAX);
1157 out[len - 1] = '/'; // NOLINT
1159 return (xstrsncpy(out + len, name, PATH_MAX - len) + len);
1162 /* Assumes both the paths passed are directories */
1163 static char *common_prefix(const char *path, char *prefix)
1165 const char *x = path, *y = prefix;
1168 if (!path || !*path || !prefix)
1172 xstrsncpy(prefix, path, PATH_MAX);
1176 while (*x && *y && (*x == *y))
1179 /* Strings are same */
1183 /* Path is shorter */
1184 if (!*x && *y == '/') {
1185 xstrsncpy(prefix, path, y - path);
1189 /* Prefix is shorter */
1190 if (!*y && *x == '/')
1193 /* Shorten prefix */
1194 prefix[y - prefix] = '\0';
1196 sep = xmemrchr((uchar_t *)prefix, '/', y - prefix);
1206 * The library function realpath() resolves symlinks.
1207 * If there's a symlink in file list we want to show the symlink not what it's points to.
1208 * Resolves ./../~ in filepath
1210 static char *abspath(const char *filepath, char *cwd, char *buf)
1212 const char *path = filepath;
1213 bool allocated = FALSE;
1218 /* when dealing with tilde, we need to be strict.
1219 * otherwise a file named "~" can end up expanding to
1220 * $HOME and causing disaster */
1221 if (tilde_is_home_strict(path)) {
1223 path += 2; /* advance 2 bytes past the "~/" */
1224 } else if ((path[0] != '/') && !cwd) {
1225 cwd = getcwd(NULL, 0);
1231 size_t dst_size = 0, src_size = xstrlen(path), cwd_size = cwd ? xstrlen(cwd) : 0;
1232 size_t len = src_size;
1236 * We need to add 2 chars at the end as relative paths may start with:
1238 * no separator (fd .): this needs an additional char for '/'
1240 char *resolved_path = buf ? buf : malloc(src_size + cwd_size + 2);
1242 if (!resolved_path) {
1248 /* Turn relative paths into absolute */
1249 if (path[0] != '/') {
1252 free(resolved_path);
1255 dst_size = xstrsncpy(resolved_path, cwd, cwd_size + 1) - 1;
1259 resolved_path[0] = '\0';
1262 dst = resolved_path + dst_size;
1263 for (const char *next = NULL; next != path + src_size;) {
1264 next = memchr(src, '/', len);
1266 next = path + src_size;
1268 if (next - src == 2 && src[0] == '.' && src[1] == '.') {
1269 if (dst - resolved_path) {
1270 dst = xmemrchr((uchar_t *)resolved_path, '/', dst - resolved_path);
1273 } else if (next - src == 1 && src[0] == '.') {
1275 } else if (next - src) {
1277 xstrsncpy(dst, src, next - src + 1);
1282 len = src_size - (src - path);
1285 if (*resolved_path == '\0') {
1286 resolved_path[0] = '/';
1287 resolved_path[1] = '\0';
1290 if (xstrlen(resolved_path) >= PATH_MAX) {
1292 free(resolved_path);
1298 return resolved_path;
1301 /* wraps the argument in single quotes so it can be safely fed to shell */
1302 static bool shell_escape(char *output, size_t outlen, const char *s)
1304 size_t n = xstrlen(s), w = 0;
1307 DPRINTF_S("s == output");
1311 output[w++] = '\''; /* begin single quote */
1312 for (size_t r = 0; r < n; ++r) {
1313 /* potentially too big: 4 for the single quote case, 2 from
1314 * outside the loop */
1315 if (w + 6 >= outlen)
1319 /* the only thing that has special meaning inside single
1320 * quotes are single quotes themselves. */
1322 output[w++] = '\''; /* end single quote */
1323 output[w++] = '\\'; /* put \' so it's treated as literal single quote */
1325 output[w++] = '\''; /* start single quoting again */
1332 output[w++] = '\''; /* end single quote */
1333 output[w++] = '\0'; /* nul terminator */
1337 static bool set_tilde_in_path(char *path)
1339 if (is_prefix(path, home, homelen)) {
1340 home[homelen] = path[homelen - 1];
1341 path[homelen - 1] = '~';
1348 static void reset_tilde_in_path(char *path)
1350 path[homelen - 1] = home[homelen];
1351 home[homelen] = '\0';
1355 static void xterm_cfg(char *path)
1357 if (cfg.x11 && !g_state.picker) {
1358 /* Signal CWD change to terminal */
1359 printf("\033]7;file://%s%s\033\\", hostname, path);
1361 /* Set terminal window title */
1362 bool r = set_tilde_in_path(path);
1364 printf("\033]2;%s\007", r ? &path[homelen - 1] : path);
1368 reset_tilde_in_path(path);
1373 static bool convert_tilde(const char *path, char *buf)
1375 if (tilde_is_home(path)) {
1376 ssize_t len = xstrlen(home);
1377 ssize_t loclen = xstrlen(path);
1379 xstrsncpy(buf, home, len + 1);
1380 xstrsncpy(buf + len, path + 1, loclen);
1386 static int create_tmp_file(void)
1388 xstrsncpy(g_tmpfpath + tmpfplen - 1, messages[STR_TMPFILE], TMP_LEN_MAX - tmpfplen);
1390 int fd = mkstemp(g_tmpfpath);
1393 DPRINTF_S(strerror(errno));
1399 static void msg(const char *message)
1401 dprintf(STDERR_FILENO, "%s\n", message);
1405 static void handle_key_resize(void)
1411 /* Clear the old prompt */
1412 static void clearoldprompt(void)
1415 move(xlines - 2, 0);
1420 handle_key_resize();
1424 /* Messages show up at the bottom */
1425 static inline void printmsg_nc(const char *msg)
1432 static void printmsg(const char *msg)
1434 attron(COLOR_PAIR(cfg.curctx + 1));
1436 attroff(COLOR_PAIR(cfg.curctx + 1));
1439 static void printwait(const char *msg, int *presel)
1445 xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
1449 /* Kill curses and display error before exiting */
1450 static void printerr(int linenum)
1453 perror(xitoa(linenum));
1454 if (!g_state.picker && selpath)
1460 static inline bool xconfirm(int c)
1462 return (c == 'y' || c == 'Y');
1465 static int get_input(const char *prompt)
1476 while (*ch == KEY_RESIZE) {
1490 static bool isselfileempty(void)
1494 return (stat(selpath, &sb) == -1) || (!sb.st_size);
1497 static int get_cur_or_sel(void)
1499 bool sel = (selbufpos || !isselfileempty());
1501 /* Check both local buffer and selection file for external selection */
1502 if (sel && ndents) {
1503 /* If selection is preferred and we have a local selection, return selection.
1504 * Always show the prompt in case of an external selection.
1506 if (cfg.prefersel && selbufpos)
1509 int choice = get_input(messages[MSG_CUR_SEL_OPTS]);
1511 return ((choice == 'c' || choice == 's') ? choice : 0);
1523 static void xdelay(useconds_t delay)
1529 static char confirm_force(bool selection)
1533 snprintf(str, 64, messages[MSG_FORCE_RM],
1534 g_state.trash ? utils[UTIL_GIO_TRASH] + 4 : utils[UTIL_RM_RF],
1535 (selection ? "selected" : "hovered"));
1537 int r = get_input(str);
1540 return '\0'; /* cancel */
1541 if (r == 'y' || r == 'Y')
1542 return 'f'; /* forceful for rm */
1543 return (g_state.trash ? '\0' : 'i'); /* interactive for rm */
1546 /* Writes buflen char(s) from buf to a file */
1547 static void writesel(const char *buf, const size_t buflen)
1552 int fd = open(selpath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
1555 if (write(fd, buf, buflen) != (ssize_t)buflen)
1562 static void appendfpath(const char *path, const size_t len)
1564 if ((selbufpos >= selbuflen) || ((len + 3) > (selbuflen - selbufpos))) {
1565 selbuflen += PATH_MAX;
1566 pselbuf = xrealloc(pselbuf, selbuflen);
1571 selbufpos += xstrsncpy(pselbuf + selbufpos, path, len);
1574 static void selbufrealloc(const size_t alloclen)
1576 if ((selbufpos + alloclen) > selbuflen) {
1577 selbuflen = ALIGN_UP(selbufpos + alloclen, PATH_MAX);
1578 pselbuf = xrealloc(pselbuf, selbuflen);
1584 /* Write selected file paths to fd, linefeed separated */
1585 static size_t seltofile(int fd, uint_t *pcount)
1587 uint_t lastpos, count = 0;
1588 char *pbuf = pselbuf;
1590 ssize_t len, prefixlen = 0, initlen = 0;
1598 lastpos = selbufpos - 1;
1601 prefixlen = (ssize_t)xstrlen(listroot);
1602 initlen = (ssize_t)xstrlen(listpath);
1605 while (pos <= lastpos) {
1607 len = (ssize_t)xstrlen(pbuf);
1609 if (!listpath || !is_prefix(pbuf, listpath, initlen)) {
1610 if (write(fd, pbuf, len) != len)
1613 if (write(fd, listroot, prefixlen) != prefixlen)
1615 if (write(fd, pbuf + initlen, len - initlen) != (len - initlen))
1620 if (pos <= lastpos) {
1621 if (write(fd, "\n", 1) != 1)
1635 /* List selection from selection file (another instance) */
1636 static bool listselfile(void)
1638 if (isselfileempty())
1641 snprintf(g_buf, CMD_LEN_MAX, "tr \'\\0\' \'\\n\' < %s", selpath);
1642 spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CONFIRM);
1647 /* Reset selection indicators */
1648 static void resetselind(void)
1650 for (int r = 0; r < ndents; ++r)
1651 if (pdents[r].flags & FILE_SELECTED)
1652 pdents[r].flags &= ~FILE_SELECTED;
1655 static void startselection(void)
1657 if (!g_state.selmode) {
1658 g_state.selmode = 1;
1669 static void clearselection(void)
1673 g_state.selmode = 0;
1677 static char *findinsel(char *startpos, int len)
1685 char *found = startpos;
1686 size_t buflen = selbufpos - (startpos - pselbuf);
1689 /* memmem(3): not specified in POSIX.1, but present on a number of other systems. */
1690 found = memmem(found, buflen - (found - startpos), g_sel, len);
1693 if (found == startpos || *(found - 1) == '\0')
1695 found += len; /* We found g_sel as a substring of a path, move forward */
1696 if (found >= startpos + buflen)
1701 static int markcmp(const void *va, const void *vb)
1703 const selmark *ma = (selmark*)va;
1704 const selmark *mb = (selmark*)vb;
1706 return ma->startpos - mb->startpos;
1709 /* scanselforpath() must be called before calling this */
1710 static inline void findmarkentry(size_t len, struct entry *dentp)
1712 if (!(dentp->flags & FILE_SCANNED)) {
1713 if (findinsel(findselpos, len + xstrsncpy(g_sel + len, dentp->name, dentp->nlen)))
1714 dentp->flags |= FILE_SELECTED;
1715 dentp->flags |= FILE_SCANNED;
1720 * scanselforpath() must be called before calling this
1721 * pathlen = length of path + 1 (+1 for trailing slash)
1723 static void invertselbuf(const int pathlen)
1725 size_t len, endpos, shrinklen = 0, alloclen = 0;
1726 char * const pbuf = g_sel + pathlen;
1728 int i, nmarked = 0, prev = 0;
1729 struct entry *dentp;
1731 selmark *marked = malloc(nselected * sizeof(selmark));
1738 /* First pass: inversion */
1739 for (i = 0; i < ndents; ++i) {
1742 if (dentp->flags & FILE_SCANNED) {
1743 if (dentp->flags & FILE_SELECTED) {
1744 dentp->flags ^= FILE_SELECTED; /* Clear selection status */
1747 dentp->flags |= FILE_SELECTED;
1748 alloclen += pathlen + dentp->nlen;
1751 dentp->flags |= FILE_SCANNED;
1756 len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1757 found = findinsel(findselpos, len);
1759 if (findselpos == found)
1762 if (nmarked && (found
1763 == (marked[nmarked - 1].startpos + marked[nmarked - 1].len)))
1764 marked[nmarked - 1].len += len;
1766 marked[nmarked].startpos = found;
1767 marked[nmarked].len = len;
1772 shrinklen += len; /* buffer size adjustment */
1774 dentp->flags |= FILE_SELECTED;
1775 alloclen += pathlen + dentp->nlen;
1782 * Files marked for deselection could be found in arbitrary order.
1783 * Sort by appearance in selection buffer.
1784 * With entries sorted we can merge adjacent ones allowing us to
1785 * move them in a single go.
1787 qsort(marked, nmarked, sizeof(selmark), &markcmp);
1789 /* Some files might be adjacent. Merge them into a single entry */
1790 for (i = 1; i < nmarked; ++i) {
1791 if (marked[i].startpos == marked[prev].startpos + marked[prev].len)
1792 marked[prev].len += marked[i].len;
1795 marked[prev].startpos = marked[i].startpos;
1796 marked[prev].len = marked[i].len;
1801 * Number of entries is increased by encountering a non-adjacent entry
1802 * After we finish the loop we should increment it once more.
1805 if (nmarked) /* Make sure there is something to deselect */
1808 /* Using merged entries remove unselected chunks from selection buffer */
1809 for (i = 0; i < nmarked; ++i) {
1811 * found: points to where the current block starts
1812 * variable is recycled from previous for readability
1813 * endpos: points to where the the next block starts
1814 * area between the end of current block (found + len)
1815 * and endpos is selected entries. This is what we are
1818 found = marked[i].startpos;
1819 endpos = (i + 1 == nmarked ? selbufpos : marked[i + 1].startpos - pselbuf);
1820 len = marked[i].len;
1822 /* Move back only selected entries. No selected memory is moved twice */
1823 memmove(found, found + len, endpos - (found + len - pselbuf));
1828 /* Buffer size adjustment */
1829 selbufpos -= shrinklen;
1831 selbufrealloc(alloclen);
1833 /* Second pass: append newly selected to buffer */
1834 for (i = 0; i < ndents; ++i) {
1835 if (pdents[i].flags & FILE_SELECTED) {
1836 len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1837 appendfpath(g_sel, len);
1842 nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1846 * scanselforpath() must be called before calling this
1847 * pathlen = length of path + 1 (+1 for trailing slash)
1849 static void addtoselbuf(const int pathlen, int startid, int endid)
1852 size_t len, alloclen = 0;
1853 struct entry *dentp;
1855 char * const pbuf = g_sel + pathlen;
1857 /* Remember current selection buffer position */
1858 for (i = startid; i <= endid; ++i) {
1862 len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1863 found = findinsel(findselpos, len);
1865 dentp->flags |= (FILE_SCANNED | FILE_SELECTED);
1866 if (found == findselpos) {
1868 if (findselpos == (pselbuf + selbufpos))
1872 alloclen += pathlen + dentp->nlen;
1874 alloclen += pathlen + dentp->nlen;
1877 selbufrealloc(alloclen);
1879 for (i = startid; i <= endid; ++i) {
1880 if (!(pdents[i].flags & FILE_SELECTED)) {
1881 len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1882 appendfpath(g_sel, len);
1884 pdents[i].flags |= (FILE_SCANNED | FILE_SELECTED);
1888 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
1891 /* Removes g_sel from selbuf */
1892 static void rmfromselbuf(size_t len)
1894 char *found = findinsel(findselpos, len);
1898 memmove(found, found + len, selbufpos - (found + len - pselbuf));
1901 nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1904 static int scanselforpath(const char *path, bool getsize)
1906 if (!path[1]) { /* path should always be at least two bytes (including NULL) */
1908 findselpos = pselbuf;
1909 return 1; /* Length of '/' is 1 */
1912 size_t off = xstrsncpy(g_sel, path, PATH_MAX);
1914 g_sel[off - 1] = '/';
1916 * We set findselpos only here. Directories can be listed in arbitrary order.
1917 * This is the best best we can do for remembering position.
1919 findselpos = findinsel(NULL, off);
1923 return (findselpos ? off : 0);
1926 /* Finish selection procedure before an operation */
1927 static void endselection(bool endselmode)
1931 char buf[sizeof(patterns[P_REPLACE]) + PATH_MAX + (TMP_LEN_MAX << 1)];
1933 if (endselmode && g_state.selmode)
1934 g_state.selmode = 0;
1936 /* The code below is only for listing mode */
1937 if (!listpath || !selbufpos)
1940 fd = create_tmp_file();
1942 DPRINTF_S("couldn't create tmp file");
1946 seltofile(fd, NULL);
1948 DPRINTF_S(strerror(errno));
1953 snprintf(buf, sizeof(buf), patterns[P_REPLACE], listpath, listroot, g_tmpfpath);
1954 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
1956 fd = open(g_tmpfpath, O_RDONLY);
1958 DPRINTF_S(strerror(errno));
1960 if (unlink(g_tmpfpath)) {
1961 DPRINTF_S(strerror(errno));
1967 count = read(fd, pselbuf, selbuflen);
1969 DPRINTF_S(strerror(errno));
1971 if (close(fd) || unlink(g_tmpfpath)) {
1972 DPRINTF_S(strerror(errno));
1977 if (close(fd) || unlink(g_tmpfpath)) {
1978 DPRINTF_S(strerror(errno));
1984 pselbuf[--count] = '\0';
1985 for (--count; count > 0; --count)
1986 if (pselbuf[count] == '\n' && pselbuf[count+1] == '/')
1987 pselbuf[count] = '\0';
1989 writesel(pselbuf, selbufpos - 1);
1992 /* Returns: 1 - success, 0 - none selected, -1 - other failure */
1993 static int editselection(void)
2001 if (!selbufpos) /* External selection is only editable at source */
2002 return listselfile();
2004 fd = create_tmp_file();
2006 DPRINTF_S("couldn't create tmp file");
2010 seltofile(fd, NULL);
2012 DPRINTF_S(strerror(errno));
2016 /* Save the last modification time */
2017 if (stat(g_tmpfpath, &sb)) {
2018 DPRINTF_S(strerror(errno));
2022 mtime = sb.st_mtime;
2024 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2026 fd = open(g_tmpfpath, O_RDONLY);
2028 DPRINTF_S(strerror(errno));
2035 if (mtime == sb.st_mtime) {
2036 DPRINTF_S("selection is not modified");
2041 if (sb.st_size > selbufpos) {
2042 DPRINTF_S("edited buffer larger than previous");
2047 count = read(fd, pselbuf, selbuflen);
2049 DPRINTF_S(strerror(errno));
2051 if (close(fd) || unlink(g_tmpfpath)) {
2052 DPRINTF_S(strerror(errno));
2058 if (close(fd) || unlink(g_tmpfpath)) {
2059 DPRINTF_S(strerror(errno));
2071 /* The last character should be '\n' */
2072 pselbuf[--count] = '\0';
2073 for (--count; count > 0; --count) {
2074 /* Replace every '\n' that separates two paths */
2075 if (pselbuf[count] == '\n' && pselbuf[count + 1] == '/') {
2077 pselbuf[count] = '\0';
2081 /* Add a line for the last file */
2084 if (lines > nselected) {
2085 DPRINTF_S("files added to selection");
2090 writesel(pselbuf, selbufpos - 1);
2100 static bool selsafe(void)
2102 /* Fail if selection file path not generated */
2104 printmsg(messages[MSG_SEL_MISSING]);
2108 /* Fail if selection file path isn't accessible */
2109 if (access(selpath, R_OK | W_OK) == -1) {
2110 errno == ENOENT ? printmsg(messages[MSG_0_SELECTED]) : printwarn(NULL);
2117 static void export_file_list(void)
2122 struct entry *pdent = pdents;
2123 int fd = create_tmp_file();
2126 DPRINTF_S(strerror(errno));
2130 for (int r = 0; r < ndents; ++pdent, ++r) {
2131 if (write(fd, pdent->name, pdent->nlen - 1) != (pdent->nlen - 1))
2134 if ((r != ndents - 1) && (write(fd, "\n", 1) != 1))
2139 DPRINTF_S(strerror(errno));
2142 spawn(editor, g_tmpfpath, NULL, NULL, F_CLI);
2144 if (xconfirm(get_input(messages[MSG_RM_TMP])))
2148 static bool init_fcolors(void)
2150 char *f_colors = getenv(env_cfg[NNN_FCOLORS]);
2152 if (!f_colors || !*f_colors)
2155 for (uchar_t id = C_BLK; *f_colors && id <= C_UND; ++id) {
2156 fcolors[id] = xchartohex(*f_colors) << 4;
2158 fcolors[id] += xchartohex(*f_colors);
2160 init_pair(id, fcolors[id], -1);
2169 /* Initialize curses mode */
2170 static bool initcurses(void *oldmask)
2176 if (g_state.picker) {
2177 if (!newterm(NULL, stderr, stdin)) {
2181 } else if (!initscr()) {
2183 DPRINTF_S(getenv("TERM"));
2190 //intrflush(stdscr, FALSE);
2191 keypad(stdscr, TRUE);
2193 #if NCURSES_MOUSE_VERSION <= 1
2194 mousemask(BUTTON1_PRESSED | BUTTON1_DOUBLE_CLICKED | BUTTON2_PRESSED | BUTTON3_PRESSED,
2195 (mmask_t *)oldmask);
2197 mousemask(BUTTON1_PRESSED | BUTTON2_PRESSED | BUTTON3_PRESSED | BUTTON4_PRESSED
2198 | BUTTON5_PRESSED, (mmask_t *)oldmask);
2202 curs_set(FALSE); /* Hide cursor */
2204 char *colors = getenv(env_cfg[NNN_COLORS]);
2206 if (colors || !getenv("NO_COLOR")) {
2211 use_default_colors();
2213 /* Initialize file colors */
2214 if (COLORS >= COLOR_256) {
2215 if (!(g_state.oldcolor || init_fcolors())) {
2217 msg(env_cfg[NNN_FCOLORS]);
2221 g_state.oldcolor = 1;
2224 DPRINTF_D(COLOR_PAIRS);
2226 if (colors && *colors == '#') {
2227 char *sep = strchr(colors, ';');
2229 if (!g_state.oldcolor && COLORS >= COLOR_256) {
2234 * If fallback colors are specified, set the separator
2235 * to NULL so we don't interpret separator and fallback
2236 * if fewer than CTX_MAX xterm 256 colors are specified.
2241 colors = sep; /* Detect if 8 colors fallback is appended */
2247 /* Get and set the context colors */
2248 for (uchar_t i = 0; i < CTX_MAX; ++i) {
2249 pcode = &g_ctx[i].color;
2251 if (colors && *colors) {
2253 *pcode = xchartohex(*colors) << 4;
2255 fcolors[i + 1] = *pcode += xchartohex(*colors);
2256 else { /* Each color code must be 2 hex symbols */
2258 msg(env_cfg[NNN_COLORS]);
2262 *pcode = (*colors < '0' || *colors > '7') ? 4 : *colors - '0';
2267 init_pair(i + 1, *pcode, -1);
2270 #ifdef ICONS_ENABLED
2271 if (!g_state.oldcolor) {
2272 for (uint_t i = 0; i < ELEMENTS(init_colors); ++i)
2273 init_pair(C_UND + 1 + init_colors[i], init_colors[i], -1);
2277 settimeout(); /* One second */
2282 /* No NULL check here as spawn() guards against it */
2283 static char *parseargs(char *cmd, char **argv, int *pindex)
2286 size_t len = xstrlen(cmd) + 1;
2287 char *line = (char *)malloc(len);
2290 DPRINTF_S("malloc()!");
2294 xstrsncpy(line, cmd, len);
2295 argv[count++] = line;
2298 while (*line) { // NOLINT
2299 if (ISBLANK(*line)) {
2302 if (!*line) // NOLINT
2305 argv[count++] = line;
2306 if (count == EXEC_ARGS_MAX) {
2315 if (count == -1 || count > (EXEC_ARGS_MAX - 4)) { /* 3 args and last NULL */
2318 DPRINTF_S("NULL or too many args");
2325 static void enable_signals(void)
2327 struct sigaction dfl_act = {.sa_handler = SIG_DFL};
2329 sigaction(SIGHUP, &dfl_act, NULL);
2330 sigaction(SIGINT, &dfl_act, NULL);
2331 sigaction(SIGQUIT, &dfl_act, NULL);
2332 sigaction(SIGTSTP, &dfl_act, NULL);
2333 sigaction(SIGWINCH, &dfl_act, NULL);
2336 static pid_t xfork(uchar_t flag)
2341 /* the parent ignores the interrupt, quit and hangup signals */
2342 sigaction(SIGHUP, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsighup);
2343 sigaction(SIGTSTP, &(struct sigaction){.sa_handler = SIG_DFL}, &oldsigtstp);
2344 sigaction(SIGWINCH, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsigwinch);
2345 } else if (p == 0) {
2346 /* We create a grandchild to detach */
2347 if (flag & F_NOWAIT) {
2351 _exit(EXIT_SUCCESS);
2359 _exit(EXIT_FAILURE);
2362 /* So they can be used to stop the child */
2366 /* This is the parent waiting for the child to create grandchild */
2367 if (flag & F_NOWAIT)
2368 waitpid(p, NULL, 0);
2375 static int join(pid_t p, uchar_t flag)
2377 int status = 0xFFFF;
2379 if (!(flag & F_NOWAIT)) {
2380 /* wait for the child to exit */
2382 } while (waitpid(p, &status, 0) == -1);
2384 if (WIFEXITED(status)) {
2385 status = WEXITSTATUS(status);
2390 /* restore parent's signal handling */
2391 sigaction(SIGHUP, &oldsighup, NULL);
2392 sigaction(SIGTSTP, &oldsigtstp, NULL);
2393 sigaction(SIGWINCH, &oldsigwinch, NULL);
2399 * Spawns a child process. Behaviour can be controlled using flag.
2400 * Limited to 3 arguments to a program, flag works on bit set.
2402 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag)
2405 int status = 0, retstatus = 0xFFFF;
2406 char *argv[EXEC_ARGS_MAX] = {0};
2409 if (!file || !*file)
2412 /* Swap args if the first arg is NULL and the other 2 aren't */
2413 if (!arg1 && arg2) {
2422 if (flag & F_MULTI) {
2423 cmd = parseargs(file, argv, &status);
2427 argv[status++] = file;
2429 argv[status] = arg1;
2430 argv[++status] = arg2;
2431 argv[++status] = arg3;
2433 if (flag & F_NORMAL)
2438 /* Suppress stdout and stderr */
2439 if (flag & F_NOTRACE) {
2440 int fd = open("/dev/null", O_WRONLY, 0200);
2442 if (flag & F_NOSTDIN)
2443 dup2(fd, STDIN_FILENO);
2444 dup2(fd, STDOUT_FILENO);
2445 dup2(fd, STDERR_FILENO);
2447 } else if (flag & F_TTY) {
2448 /* If stdout has been redirected to a non-tty, force output to tty */
2449 if (!isatty(STDOUT_FILENO)) {
2450 int fd = open(ctermid(NULL), O_WRONLY, 0200);
2451 dup2(fd, STDOUT_FILENO);
2456 execvp(*argv, argv);
2457 _exit(EXIT_SUCCESS);
2459 retstatus = join(pid, flag);
2462 if ((flag & F_CONFIRM) || ((flag & F_CHKRTN) && retstatus)) {
2463 status = write(STDOUT_FILENO, messages[MSG_ENTER], xstrlen(messages[MSG_ENTER]));
2465 while ((read(STDIN_FILENO, &status, 1) > 0) && (status != '\n'));
2468 if (flag & F_NORMAL)
2477 /* Get program name from env var, else return fallback program */
2478 static char *xgetenv(const char * const name, char *fallback)
2480 char *value = getenv(name);
2482 return value && value[0] ? value : fallback;
2485 /* Checks if an env variable is set to 1 */
2486 static inline uint_t xgetenv_val(const char *name)
2488 char *str = getenv(name);
2496 /* Check if a dir exists, IS a dir, and is readable */
2497 static bool xdiraccess(const char *path)
2499 DIR *dirp = opendir(path);
2510 static bool plugscript(const char *plugin, uchar_t flags)
2512 mkpath(plgpath, plugin, g_buf);
2513 if (!access(g_buf, X_OK)) {
2514 spawn(g_buf, NULL, NULL, NULL, flags);
2521 static void opstr(char *buf, char *op)
2523 snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c '%s \"$0\" \"$@\" . < /dev/tty' < %s", op, selpath);
2526 static bool rmmulstr(char *buf)
2528 char r = confirm_force(TRUE);
2533 snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c 'rm -%cr \"$0\" \"$@\" < /dev/tty' < %s",
2536 snprintf(buf, CMD_LEN_MAX, "xargs -0 %s < %s",
2537 utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH], selpath);
2542 /* Returns TRUE if file is removed, else FALSE */
2543 static bool xrm(char * const fpath)
2545 char r = confirm_force(FALSE);
2549 if (!g_state.trash) {
2550 char rm_opts[] = "-ir";
2553 spawn("rm", rm_opts, fpath, NULL, F_NORMAL | F_CHKRTN);
2555 spawn(utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH],
2556 fpath, NULL, NULL, F_NORMAL | F_MULTI);
2558 return (access(fpath, F_OK) == -1); /* File is removed */
2561 static void xrmfromsel(char *path, char *fpath)
2564 bool selected = TRUE;
2567 if ((pdents[cur].flags & DIR_OR_DIRLNK) && scanselforpath(fpath, FALSE))
2569 else if (pdents[cur].flags & FILE_SELECTED) {
2571 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
2577 if (selected && cfg.x11)
2578 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
2582 static uint_t lines_in_file(int fd, char *buf, size_t buflen)
2587 while ((len = read(fd, buf, buflen)) > 0)
2589 count += (buf[--len] == '\n');
2591 /* For all use cases 0 linecount is considered as error */
2592 return ((len < 0) ? 0 : count);
2595 static bool cpmv_rename(int choice, const char *path)
2598 uint_t count = 0, lines = 0;
2600 char *cmd = (choice == 'c' ? cp : mv);
2601 char buf[sizeof(patterns[P_CPMVRNM]) + (MAX(sizeof(cp), sizeof(mv))) + (PATH_MAX << 1)];
2603 fd = create_tmp_file();
2607 /* selsafe() returned TRUE for this to be called */
2609 snprintf(buf, sizeof(buf), "tr '\\0' '\\n' < %s > %s", selpath, g_tmpfpath);
2610 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2612 count = lines_in_file(fd, buf, sizeof(buf));
2616 seltofile(fd, &count);
2620 snprintf(buf, sizeof(buf), patterns[P_CPMVFMT], g_tmpfpath);
2621 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2623 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2625 fd = open(g_tmpfpath, O_RDONLY);
2629 lines = lines_in_file(fd, buf, sizeof(buf));
2632 if (!lines || (2 * count != lines)) {
2633 DPRINTF_S("num mismatch");
2637 snprintf(buf, sizeof(buf), patterns[P_CPMVRNM], path, g_tmpfpath, cmd);
2638 if (!spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CHKRTN))
2647 static bool cpmvrm_selection(enum action sel, char *path)
2651 if (isselfileempty()) {
2654 printmsg(messages[MSG_0_SELECTED]);
2669 r = get_input(messages[MSG_CP_MV_AS]);
2670 if (r != 'c' && r != 'm') {
2671 printmsg(messages[MSG_INVALID_KEY]);
2675 if (!cpmv_rename(r, path)) {
2676 printmsg(messages[MSG_FAILED]);
2680 default: /* SEL_RM */
2681 if (!rmmulstr(g_buf)) {
2682 printmsg(messages[MSG_CANCEL]);
2687 if (sel != SEL_CPMVAS && spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CHKRTN)) {
2688 printmsg(messages[MSG_FAILED]);
2692 /* Clear selection */
2699 static bool batch_rename(void)
2702 uint_t count = 0, lines = 0;
2703 bool dir = FALSE, ret = FALSE;
2704 char foriginal[TMP_LEN_MAX] = {0};
2705 static const char batchrenamecmd[] = "paste -d'\n' %s %s | "SED" 'N; /^\\(.*\\)\\n\\1$/!p;d' | "
2706 "tr '\n' '\\0' | xargs -0 -n2 sh -c 'mv -i \"$0\" \"$@\" <"
2708 char buf[sizeof(batchrenamecmd) + (PATH_MAX << 1)];
2709 int i = get_cur_or_sel();
2714 if (i == 'c') { /* Rename entries in current dir */
2719 fd1 = create_tmp_file();
2723 xstrsncpy(foriginal, g_tmpfpath, xstrlen(g_tmpfpath) + 1);
2725 fd2 = create_tmp_file();
2733 for (i = 0; i < ndents; ++i)
2734 appendfpath(pdents[i].name, NAME_MAX);
2736 seltofile(fd1, &count);
2737 seltofile(fd2, NULL);
2740 if (dir) /* Don't retain dir entries in selection */
2743 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2745 /* Reopen file descriptor to get updated contents */
2746 fd2 = open(g_tmpfpath, O_RDONLY);
2750 lines = lines_in_file(fd2, buf, sizeof(buf));
2753 if (!lines || (count != lines)) {
2754 DPRINTF_S("cannot delete files");
2758 snprintf(buf, sizeof(buf), batchrenamecmd, foriginal, g_tmpfpath);
2759 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2775 static char *get_archive_cmd(const char *archive)
2779 if (!g_state.usebsdtar && getutil(utils[UTIL_ATOOL]))
2781 else if (getutil(utils[UTIL_BSDTAR]))
2783 else if (is_suffix(archive, ".zip"))
2787 return archive_cmd[i];
2790 static void archive_selection(const char *cmd, const char *archive)
2792 char *buf = malloc((xstrlen(patterns[P_ARCHIVE_CMD]) + xstrlen(cmd) + xstrlen(archive)
2793 + xstrlen(selpath)) * sizeof(char));
2795 DPRINTF_S(strerror(errno));
2800 snprintf(buf, CMD_LEN_MAX, patterns[P_ARCHIVE_CMD], cmd, archive, selpath);
2801 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CONFIRM);
2805 static void write_lastdir(const char *curpath, const char *outfile)
2809 xstrsncpy(cfgpath + xstrlen(cfgpath), "/.lastd", 8);
2811 tilde = convert_tilde(outfile, g_buf);
2813 int fd = open(outfile
2814 ? (tilde ? g_buf : outfile)
2815 : cfgpath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
2817 if (fd != -1 && shell_escape(g_buf, sizeof(g_buf), curpath)) {
2818 dprintf(fd, "cd %s", g_buf);
2824 * We assume none of the strings are NULL.
2826 * Let's have the logic to sort numeric names in numeric order.
2827 * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
2829 * If the absolute numeric values are same, we fallback to alphasort.
2831 static int xstricmp(const char * const s1, const char * const s2)
2835 long long v1 = strtoll(s1, &p1, 10);
2836 long long v2 = strtoll(s2, &p2, 10);
2838 /* Check if at least 1 string is numeric */
2839 if (s1 != p1 || s2 != p2) {
2840 /* Handle both pure numeric */
2841 if (s1 != p1 && s2 != p2) {
2849 /* Only first string non-numeric */
2853 /* Only second string non-numeric */
2858 /* Handle 1. all non-numeric and 2. both same numeric value cases */
2860 return strcoll(s1, s2);
2862 return strcasecmp(s1, s2);
2867 * Version comparison
2869 * The code for version compare is a modified version of the GLIBC
2870 * and uClibc implementation of strverscmp(). The source is here:
2871 * https://elixir.bootlin.com/uclibc-ng/latest/source/libc/string/strverscmp.c
2875 * Compare S1 and S2 as strings holding indices/version numbers,
2876 * returning less than, equal to or greater than zero if S1 is less than,
2877 * equal to or greater than S2 (for more info, see the texinfo doc).
2881 static int xstrverscasecmp(const char * const s1, const char * const s2)
2883 const uchar_t *p1 = (const uchar_t *)s1;
2884 const uchar_t *p2 = (const uchar_t *)s2;
2889 * Symbol(s) 0 [1-9] others
2890 * Transition (10) 0 (01) d (00) x
2892 static const uint8_t next_state[] = {
2894 /* S_N */ S_N, S_I, S_Z,
2895 /* S_I */ S_N, S_I, S_I,
2896 /* S_F */ S_N, S_F, S_F,
2897 /* S_Z */ S_N, S_F, S_Z
2900 alignas(max_align_t) static const int8_t result_type[] = {
2901 /* state x/x x/d x/0 d/x d/d d/0 0/x 0/d 0/0 */
2903 /* S_N */ VCMP, VCMP, VCMP, VCMP, VLEN, VCMP, VCMP, VCMP, VCMP,
2904 /* S_I */ VCMP, -1, -1, 1, VLEN, VLEN, 1, VLEN, VLEN,
2905 /* S_F */ VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP,
2906 /* S_Z */ VCMP, 1, 1, -1, VCMP, VCMP, -1, VCMP, VCMP
2917 /* Hint: '0' is a digit too. */
2918 state = S_N + ((c1 == '0') + (xisdigit(c1) != 0));
2920 while ((diff = c1 - c2) == 0) {
2924 state = next_state[state];
2929 state += (c1 == '0') + (xisdigit(c1) != 0);
2932 state = result_type[state * 3 + (((c2 == '0') + (xisdigit(c2) != 0)))]; // NOLINT
2938 while (xisdigit(*p1++))
2939 if (!xisdigit(*p2++))
2941 return xisdigit(*p2) ? -1 : diff;
2947 static int (*namecmpfn)(const char * const s1, const char * const s2) = &xstricmp;
2949 static char * (*fnstrstr)(const char *haystack, const char *needle) = &strcasestr;
2951 static const unsigned char *tables;
2952 static int pcreflags = PCRE_NO_AUTO_CAPTURE | PCRE_EXTENDED | PCRE_CASELESS | PCRE_UTF8;
2954 static int regflags = REG_NOSUB | REG_EXTENDED | REG_ICASE;
2958 static int setfilter(pcre **pcrex, const char *filter)
2960 const char *errstr = NULL;
2963 *pcrex = pcre_compile(filter, pcreflags, &errstr, &erroffset, tables);
2965 return errstr ? -1 : 0;
2968 static int setfilter(regex_t *regex, const char *filter)
2970 return regcomp(regex, filter, regflags);
2974 static int visible_re(const fltrexp_t *fltrexp, const char *fname)
2977 return pcre_exec(fltrexp->pcrex, NULL, fname, xstrlen(fname), 0, 0, NULL, 0) == 0;
2979 return regexec(fltrexp->regex, fname, 0, NULL, 0) == 0;
2983 static int visible_str(const fltrexp_t *fltrexp, const char *fname)
2985 return fnstrstr(fname, fltrexp->str) != NULL;
2988 static int (*filterfn)(const fltrexp_t *fltr, const char *fname) = &visible_str;
2990 static void clearfilter(void)
2992 char * const fltr = g_ctx[cfg.curctx].c_fltr;
2995 fltr[REGEX_MAX - 1] = fltr[1];
3000 static int entrycmp(const void *va, const void *vb)
3002 const struct entry *pa = (pEntry)va;
3003 const struct entry *pb = (pEntry)vb;
3005 if ((pb->flags & DIR_OR_DIRLNK) != (pa->flags & DIR_OR_DIRLNK)) {
3006 if (pb->flags & DIR_OR_DIRLNK)
3011 /* Sort based on specified order */
3012 if (cfg.timeorder) {
3013 if (pb->sec > pa->sec)
3015 if (pb->sec < pa->sec)
3017 /* If sec matches, comare nsec */
3018 if (pb->nsec > pa->nsec)
3020 if (pb->nsec < pa->nsec)
3022 } else if (cfg.sizeorder) {
3023 if (pb->size > pa->size)
3025 if (pb->size < pa->size)
3027 } else if (cfg.blkorder) {
3028 if (pb->blocks > pa->blocks)
3030 if (pb->blocks < pa->blocks)
3032 } else if (cfg.extnorder && !(pb->flags & DIR_OR_DIRLNK)) {
3033 char *extna = xextension(pa->name, pa->nlen - 1);
3034 char *extnb = xextension(pb->name, pb->nlen - 1);
3036 if (extna || extnb) {
3043 int ret = strcasecmp(extna, extnb);
3050 return namecmpfn(pa->name, pb->name);
3053 static int reventrycmp(const void *va, const void *vb)
3055 if ((((pEntry)vb)->flags & DIR_OR_DIRLNK)
3056 != (((pEntry)va)->flags & DIR_OR_DIRLNK)) {
3057 if (((pEntry)vb)->flags & DIR_OR_DIRLNK)
3062 return -entrycmp(va, vb);
3065 static int (*entrycmpfn)(const void *va, const void *vb) = &entrycmp;
3067 /* In case of an error, resets *wch to Esc */
3068 static int handle_alt_key(wint_t *wch)
3072 int r = get_wch(wch);
3081 static inline int handle_event(void)
3083 if (nselected && isselfileempty())
3085 return CONTROL('L');
3089 * Returns SEL_* if key is bound and 0 otherwise.
3090 * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
3091 * The next keyboard input can be simulated by presel.
3093 static int nextsel(int presel)
3100 bool escaped = FALSE;
3102 if (c == 0 || c == MSGWAIT) {
3106 //DPRINTF_S(keyname(c));
3109 if (c == KEY_RESIZE)
3110 handle_key_resize();
3113 /* Handle Alt+key */
3125 } else if (escaped) {
3130 if (!g_state.fifomode)
3131 notify_fifo(TRUE); /* Send hovered path to NNN_FIFO */
3139 if (i == ERR && presel == MSGWAIT)
3140 c = (cfg.filtermode || filterset()) ? FILTER : CONTROL('L');
3141 else if (c == FILTER || c == CONTROL('L'))
3142 /* Clear previous filter when manually starting */
3150 * Do not check for directory changes in du mode.
3151 * A redraw forces du calculation.
3152 * Check for changes every odd second.
3154 #ifdef LINUX_INOTIFY
3155 if (!cfg.blkorder && inotify_wd >= 0 && (idle & 1)) {
3156 struct inotify_event *event;
3157 char inotify_buf[EVENT_BUF_LEN] = {0};
3159 i = read(inotify_fd, inotify_buf, EVENT_BUF_LEN);
3161 for (char *ptr = inotify_buf;
3162 ptr + ((struct inotify_event *)ptr)->len < inotify_buf + i;
3163 ptr += sizeof(struct inotify_event) + event->len) {
3164 event = (struct inotify_event *)ptr;
3165 DPRINTF_D(event->wd);
3166 DPRINTF_D(event->mask);
3170 if (event->mask & INOTIFY_MASK) {
3175 DPRINTF_S("inotify read done");
3178 #elif defined(BSD_KQUEUE)
3179 if (!cfg.blkorder && event_fd >= 0 && (idle & 1)) {
3180 struct kevent event_data[NUM_EVENT_SLOTS] = {0};
3182 if (kevent(kq, events_to_monitor, NUM_EVENT_SLOTS,
3183 event_data, NUM_EVENT_FDS, >imeout) > 0)
3186 #elif defined(HAIKU_NM)
3187 if (!cfg.blkorder && haiku_nm_active && (idle & 1) && haiku_is_update_needed(haiku_hnd))
3193 for (i = 0; i < (int)ELEMENTS(bindings); ++i)
3194 if (c == bindings[i].sym)
3195 return bindings[i].act;
3200 static int getorderstr(char *sort)
3208 sort[i++] = (cfg.timetype == T_MOD) ? 'M' : ((cfg.timetype == T_ACCESS) ? 'A' : 'C');
3209 else if (cfg.sizeorder)
3211 else if (cfg.extnorder)
3214 if (entrycmpfn == &reventrycmp)
3217 if (namecmpfn == &xstrverscasecmp)
3226 static void showfilterinfo(void)
3229 char info[REGEX_MAX] = "\0\0\0\0\0";
3231 i = getorderstr(info);
3233 if (cfg.fileinfo && ndents && get_output("file", "-b", pdents[cur].name, -1, FALSE))
3234 mvaddstr(xlines - 2, 2, g_buf);
3236 snprintf(info + i, REGEX_MAX - i - 1, " %s [/], %4s [:]",
3237 (cfg.regex ? "reg" : "str"),
3238 ((fnstrstr == &strcasestr) ? "ic" : "noic"));
3241 mvaddstr(xlines - 2, xcols - xstrlen(info), info);
3244 static void showfilter(char *str)
3246 attron(COLOR_PAIR(cfg.curctx + 1));
3249 // printmsg calls attroff()
3252 static inline void swap_ent(int id1, int id2)
3254 struct entry _dent, *pdent1 = &pdents[id1], *pdent2 = &pdents[id2];
3256 *(&_dent) = *pdent1;
3258 *pdent2 = *(&_dent);
3262 static int fill(const char *fltr, pcre *pcrex)
3264 static int fill(const char *fltr, regex_t *re)
3268 fltrexp_t fltrexp = { .pcrex = pcrex, .str = fltr };
3270 fltrexp_t fltrexp = { .regex = re, .str = fltr };
3273 for (int count = 0; count < ndents; ++count) {
3274 if (filterfn(&fltrexp, pdents[count].name) == 0) {
3275 if (count != --ndents) {
3276 swap_ent(count, ndents);
3287 static int matches(const char *fltr)
3293 if (cfg.regex && setfilter(&pcrex, fltr))
3296 ndents = fill(fltr, pcrex);
3304 if (cfg.regex && setfilter(&re, fltr))
3307 ndents = fill(fltr, &re);
3313 ENTSORT(pdents, ndents, entrycmpfn);
3319 * Return the position of the matching entry or 0 otherwise
3320 * Note there's no NULL check for fname
3322 static int dentfind(const char *fname, int n)
3324 for (int i = 0; i < n; ++i)
3325 if (xstrcmp(fname, pdents[i].name) == 0)
3331 static int filterentries(char *path, char *lastname)
3333 alignas(max_align_t) wchar_t wln[REGEX_MAX];
3334 char *ln = g_ctx[cfg.curctx].c_fltr;
3336 int r, total = ndents, len;
3337 char *pln = g_ctx[cfg.curctx].c_fltr + 1;
3339 DPRINTF_S(__func__);
3341 if (ndents && (ln[0] == FILTER || ln[0] == RFILTER) && *pln) {
3342 if (matches(pln) != -1) {
3343 move_cursor(dentfind(lastname, ndents), 0);
3347 if (!cfg.filtermode) {
3352 len = mbstowcs(wln, ln, REGEX_MAX);
3354 ln[0] = wln[0] = cfg.regex ? RFILTER : FILTER;
3355 ln[1] = wln[1] = '\0';
3363 while ((r = get_wch(ch)) != ERR) {
3365 //DPRINTF_S(keyname(*ch));
3369 case 0: // fallthrough
3376 case KEY_DC: // fallthrough
3377 case KEY_BACKSPACE: // fallthrough
3378 case '\b': // fallthrough
3379 case DEL: /* handle DEL */
3382 wcstombs(ln, wln, REGEX_MAX);
3390 if (*ch == CONTROL('L')) {
3392 ln[REGEX_MAX - 1] = ln[1];
3393 ln[1] = wln[1] = '\0';
3396 } else if (ln[REGEX_MAX - 1]) { /* Show the previous filter */
3397 ln[1] = ln[REGEX_MAX - 1];
3398 ln[REGEX_MAX - 1] = '\0';
3399 len = mbstowcs(wln, ln, REGEX_MAX);
3404 /* Go to the top, we don't know if the hovered file will match the filter */
3407 if (matches(pln) != -1)
3417 if (handle_alt_key(ch) != ERR) {
3418 if (*ch == ESC) /* Handle Alt+Esc */
3419 *ch = 'q'; /* Quit context */
3422 *ch = ';'; /* Run plugin */
3428 if (r != OK) /* Handle Fn keys in main loop */
3431 /* Handle all control chars in main loop */
3432 if (*ch < ASCII_MAX && keyname(*ch)[0] == '^' && *ch != '^')
3436 if (*ch == '?') /* Help and config key, '?' is an invalid regex */
3439 if (cfg.filtermode) {
3441 case '\'': // fallthrough /* Go to first non-dir file */
3442 case '+': // fallthrough /* Toggle file selection */
3443 case ',': // fallthrough /* Mark CWD */
3444 case '-': // fallthrough /* Visit last visited dir */
3445 case '.': // fallthrough /* Show hidden files */
3446 case ';': // fallthrough /* Run plugin key */
3447 case '=': // fallthrough /* Launch app */
3448 case '>': // fallthrough /* Export file list */
3449 case '@': // fallthrough /* Visit start dir */
3450 case ']': // fallthorugh /* Prompt key */
3451 case '`': // fallthrough /* Visit / */
3452 case '~': /* Go HOME */
3457 /* Toggle case-sensitivity */
3459 fnstrstr = (fnstrstr == &strcasestr) ? &strstr : &strcasestr;
3461 pcreflags ^= PCRE_CASELESS;
3463 regflags ^= REG_ICASE;
3469 /* Toggle string or regex filter */
3470 if (*ch == FILTER) {
3471 ln[0] = (ln[0] == FILTER) ? RFILTER : FILTER;
3472 wln[0] = (uchar_t)ln[0];
3474 filterfn = cfg.regex ? &visible_re : &visible_str;
3479 /* Reset cur in case it's a repeat search */
3481 } else if (len == REGEX_MAX - 1)
3484 wln[len] = (wchar_t)*ch;
3486 wcstombs(ln, wln, REGEX_MAX);
3488 /* Forward-filtering optimization:
3489 * - new matches can only be a subset of current matches.
3491 /* ndents = total; */
3495 !r ? unget_wch(KEY_BACKSPACE) : showfilter(ln);
3497 if (matches(pln) == -1) {
3503 /* If the only match is a dir, auto-enter and cd into it */
3504 if ((ndents == 1) && cfg.autoenter && (pdents[0].flags & DIR_OR_DIRLNK)) {
3511 * redraw() should be above the auto-enter optimization, for
3512 * the case where there's an issue with dir auto-enter, say,
3513 * due to a permission problem. The transition is _jumpy_ in
3514 * case of such an error. However, we optimize for successful
3515 * cases where the dir has permissions. This skips a redraw().
3522 /* Save last working filter in-filter */
3524 ln[REGEX_MAX - 1] = ln[1];
3532 /* Return keys for navigation etc. */
3536 /* Show a prompt with input string and return the changes */
3537 static char *xreadline(const char *prefill, const char *prompt)
3541 const int WCHAR_T_WIDTH = sizeof(wchar_t);
3543 wchar_t * const buf = malloc(sizeof(wchar_t) * READLINE_MAX);
3553 len = pos = mbstowcs(buf, prefill, READLINE_MAX);
3557 if (len == (size_t)-1) {
3562 x = getcurx(stdscr);
3567 attron(COLOR_PAIR(cfg.curctx + 1));
3568 if (pos > (size_t)(xcols - x)) {
3569 mvaddnwstr(xlines - 1, x, buf + (pos - (xcols - x) + 1), xcols - x);
3570 move(xlines - 1, xcols - 1);
3572 mvaddnwstr(xlines - 1, x, buf, len + 1);
3573 move(xlines - 1, x + wcswidth(buf, pos));
3575 attroff(COLOR_PAIR(cfg.curctx + 1));
3583 case KEY_ENTER: // fallthrough
3584 case '\n': // fallthrough
3590 else if (!(pos || len)) { /* Exit on ^D at empty prompt */
3596 case DEL: // fallthrough
3597 case '\b': /* rhel25 sends '\b' for backspace */
3599 memmove(buf + pos - 1, buf + pos,
3600 (len - pos) * WCHAR_T_WIDTH);
3605 if (!(len || pos) && ndents)
3606 len = pos = mbstowcs(buf, pdents[cur].name, READLINE_MAX);
3621 memmove(buf + pos - 1, buf + pos,
3622 (len - pos) * WCHAR_T_WIDTH);
3624 } while (buf[pos - 1] != ' ' && buf[pos - 1] != '/'); // NOLINT
3642 memmove(buf, buf + pos, (len - pos) * WCHAR_T_WIDTH);
3646 case ESC: /* Exit prompt on Esc, but just filter out Alt+key */
3647 if (handle_alt_key(ch) != ERR)
3654 /* Filter out all other control chars */
3655 if (*ch < ASCII_MAX && keyname(*ch)[0] == '^')
3658 if (pos < READLINE_MAX - 1) {
3659 memmove(buf + pos + 1, buf + pos,
3660 (len - pos) * WCHAR_T_WIDTH);
3684 memmove(buf + pos - 1, buf + pos,
3685 (len - pos) * WCHAR_T_WIDTH);
3691 memmove(buf + pos, buf + pos + 1,
3692 (len - pos - 1) * WCHAR_T_WIDTH);
3702 case KEY_UP: // fallthrough
3704 if (prompt && lastcmd && (xstrcmp(prompt, PROMPT) == 0)) {
3706 len = pos = mbstowcs(buf, lastcmd, READLINE_MAX); // fallthrough
3721 pos = wcstombs(g_buf, buf, READLINE_MAX - 1);
3722 if (pos >= READLINE_MAX - 1)
3723 g_buf[READLINE_MAX - 1] = '\0';
3731 * Caller should check the value of presel to confirm if it needs to wait to show warning
3733 static char *getreadline(const char *prompt)
3737 char *input = readline(prompt);
3741 if (input && input[0]) {
3743 xstrsncpy(g_buf, input, CMD_LEN_MAX);
3754 * Create symbolic/hard link(s) to file(s) in selection list
3755 * Returns the number of links created, -1 on error
3757 static int xlink(char *prefix, char *path, char *curfname, char *buf, int type)
3759 int count = 0, choice;
3760 char *psel = pselbuf, *fname;
3761 size_t pos = 0, len, r;
3762 int (*link_fn)(const char *, const char *) = NULL;
3763 char lnpath[PATH_MAX];
3765 choice = get_cur_or_sel();
3769 if (type == 's') /* symbolic link */
3771 else /* hard link */
3774 if (choice == 'c' || (nselected == 1)) {
3775 prefix = abspath(prefix, path, lnpath); /* Generate link path */
3780 mkpath(path, curfname, buf); /* Generate target file path */
3782 if (!link_fn((choice == 'c') ? buf : pselbuf, lnpath)) {
3785 return 1; /* One link created */
3790 r = xstrsncpy(buf, prefix, NAME_MAX + 1); /* Copy prefix */
3792 while (pos < selbufpos) {
3793 len = xstrlen(psel);
3794 fname = xbasename(psel);
3796 xstrsncpy(buf + r - 1, fname, NAME_MAX - r); /* Suffix target file name */
3797 mkpath(path, buf, lnpath); /* Generate link path */
3799 if (!link_fn(psel, lnpath))
3806 if (count == nselected) /* Clear selection if all links are generated */
3811 static bool parsekvpair(kv **arr, char **envcpy, const uchar_t id, uchar_t *items)
3814 const uchar_t INCR = 8;
3817 char *ptr = getenv(env_cfg[id]);
3822 *envcpy = xstrdup(ptr);
3830 while (*ptr && i < 100) {
3832 if (!(i & (INCR - 1))) {
3833 kvarr = xrealloc(kvarr, sizeof(kv) * (i + INCR));
3839 memset(kvarr + i, 0, sizeof(kv) * INCR);
3841 kvarr[i].key = (uchar_t)*ptr;
3842 if (*++ptr != ':' || *++ptr == '\0' || *ptr == ';')
3844 kvarr[i].off = ptr - *envcpy;
3863 * Get the value corresponding to a key
3865 * NULL is returned in case of no match, path resolution failure etc.
3866 * buf would be modified, so check return value before access
3868 static char *get_kv_val(kv *kvarr, char *buf, int key, uchar_t max, uchar_t id)
3875 for (int r = 0; r < max && kvarr[r].key; ++r) {
3876 if (kvarr[r].key == key) {
3877 /* Do not allocate new memory for plugin */
3879 return pluginstr + kvarr[r].off;
3881 val = bmstr + kvarr[r].off;
3882 bool tilde = convert_tilde(val, g_buf);
3883 return abspath((tilde ? g_buf : val), NULL, buf);
3887 DPRINTF_S("Invalid key");
3891 static int get_kv_key(kv *kvarr, char *val, uchar_t max, uchar_t id)
3896 if (id != NNN_ORDER) /* For now this function supports only order string */
3899 for (int r = 0; r < max && kvarr[r].key; ++r) {
3900 if (xstrcmp((orderstr + kvarr[r].off), val) == 0)
3901 return kvarr[r].key;
3907 static void resetdircolor(int flags)
3909 /* Directories are always shown on top, clear the color when moving to first file */
3910 if (g_state.dircolor && !(flags & DIR_OR_DIRLNK)) {
3911 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
3912 g_state.dircolor = 0;
3917 * Replace escape characters in a string with '?'
3918 * Adjust string length to maxcols if > 0;
3919 * Max supported str length: NAME_MAX;
3922 static char *unescape(const char *str, uint_t maxcols)
3924 char * const wbuf = g_buf;
3927 xstrsncpy(wbuf, str, maxcols);
3929 static wchar_t *unescape(const char *str, uint_t maxcols)
3931 wchar_t * const wbuf = (wchar_t *)g_buf;
3932 wchar_t *buf = wbuf;
3933 size_t len = mbstowcs(wbuf, str, maxcols); /* Convert multi-byte to wide char */
3935 len = wcswidth(wbuf, len);
3937 if (len >= maxcols) {
3938 size_t lencount = maxcols;
3940 while (len > maxcols) /* Reduce wide chars one by one till it fits */
3941 len = wcswidth(wbuf, --lencount);
3943 wbuf[lencount] = L'\0';
3948 if (*buf <= '\x1f' || *buf == '\x7f')
3957 static off_t get_size(off_t size, off_t *pval, int comp)
3960 off_t quo = rem / 10;
3962 if ((rem - (quo * 10)) >= 5) {
3975 static char *coolsize(off_t size)
3977 const char * const U = "BKMGTPEZY";
3978 static char size_buf[12]; /* Buffer to hold human readable size */
3983 while (size >= 1024) {
3984 rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
3990 rem = (rem * 1000) >> 10;
3992 size = get_size(size, &rem, 10);
3993 } else if (i == 2) {
3994 rem = (rem * 1000) >> 10;
3995 size = get_size(size, &rem, 100);
3997 rem = (rem * 10000) >> 10;
3998 size = get_size(size, &rem, 1000);
4001 if (i > 0 && i < 6 && rem) {
4002 ret = xstrsncpy(size_buf, xitoa(size), 12);
4003 size_buf[ret - 1] = '.';
4005 char *frac = xitoa(rem);
4006 size_t toprint = i > 3 ? 3 : i;
4007 size_t len = xstrlen(frac);
4009 if (len < toprint) {
4010 size_buf[ret] = size_buf[ret + 1] = size_buf[ret + 2] = '0';
4011 xstrsncpy(size_buf + ret + (toprint - len), frac, len + 1);
4013 xstrsncpy(size_buf + ret, frac, toprint + 1);
4017 ret = xstrsncpy(size_buf, size ? xitoa(size) : "0", 12);
4021 size_buf[ret] = U[i];
4022 size_buf[ret + 1] = '\0';
4027 /* Convert a mode field into "ls -l" type perms field. */
4028 static char *get_lsperms(mode_t mode)
4030 static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
4031 static char bits[11] = {'\0'};
4033 switch (mode & S_IFMT) {
4060 xstrsncpy(&bits[1], rwx[(mode >> 6) & 7], 4);
4061 xstrsncpy(&bits[4], rwx[(mode >> 3) & 7], 4);
4062 xstrsncpy(&bits[7], rwx[(mode & 7)], 4);
4065 bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
4067 bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
4069 bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
4074 #ifdef ICONS_ENABLED
4075 static struct icon get_icon(const struct entry *ent)
4077 for (size_t i = 0; i < ELEMENTS(icons_name); ++i)
4078 if (strcasecmp(ent->name, icons_name[i].match) == 0)
4079 return (struct icon){ icons_name[i].icon, icons_name[i].color };
4081 if (ent->flags & DIR_OR_DIRLNK)
4084 char *tmp = xextension(ent->name, ent->nlen);
4087 uint16_t z, k, h = icon_ext_hash(++tmp); /* ++tmp to skip '.' */
4088 for (k = 0; k < ICONS_PROBE_MAX; ++k) {
4089 z = (h + k) % ELEMENTS(icons_ext);
4090 if (strcasecmp(tmp, icons_ext[z].match) == 0)
4091 return (struct icon){ icons_ext_uniq[icons_ext[z].idx], icons_ext[z].color };
4095 /* If there's no match and the file is executable, icon that */
4096 if (ent->mode & 0100)
4101 static void print_icon(const struct entry *ent, const int attrs)
4103 const struct icon icon = get_icon(ent);
4104 addstr(ICON_PADDING_LEFT);
4106 attron(COLOR_PAIR(C_UND + 1 + icon.color));
4111 attroff(COLOR_PAIR(C_UND + 1 + icon.color));
4114 addstr(ICON_PADDING_RIGHT);
4118 static void print_time(const time_t *timep, const uchar_t flags)
4122 /* Highlight timestamp for entries 5 minutes young */
4123 if (flags & FILE_YOUNG)
4126 localtime_r(timep, &t);
4127 printw("%s-%02d-%02d %02d:%02d",
4128 xitoa(t.tm_year + 1900), t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min);
4130 if (flags & FILE_YOUNG)
4134 static char get_detail_ind(const mode_t mode)
4136 switch (mode & S_IFMT) {
4137 case S_IFDIR: // fallthrough
4138 case S_IFREG: return ' ';
4139 case S_IFLNK: return '@';
4140 case S_IFSOCK: return '=';
4141 case S_IFIFO: return '|';
4142 case S_IFBLK: return 'b';
4143 case S_IFCHR: return 'c';
4148 /* Note: attribute and indicator values must be initialized to 0 */
4149 static uchar_t get_color_pair_name_ind(const struct entry *ent, char *pind, int *pattr)
4151 switch (ent->mode & S_IFMT) {
4154 if (ent->mode & 0100)
4158 if (ent->flags & HARD_LINK) {
4159 if (ent->mode & 0100)
4163 if (ent->mode & 0100) {
4170 if (g_state.oldcolor)
4173 return g_state.dirctx ? cfg.curctx + 1 : C_DIR;
4175 if (ent->flags & DIR_OR_DIRLNK) {
4177 *pattr |= g_state.oldcolor ? A_DIM : A_BOLD;
4180 if (g_state.oldcolor)
4183 if (!g_state.oldcolor || cfg.showdetail)
4184 return (ent->flags & SYM_ORPHAN) ? C_ORP : C_LNK;
4202 static void printent(const struct entry *ent, uint_t namecols, bool sel)
4207 if (cfg.showdetail) {
4208 int type = ent->mode & S_IFMT;
4209 char perms[6] = {' ', ' ', (char)('0' + ((ent->mode >> 6) & 7)),
4210 (char)('0' + ((ent->mode >> 3) & 7)),
4211 (char)('0' + (ent->mode & 7)), '\0'};
4214 attrs = g_state.oldcolor ? (resetdircolor(ent->flags), A_DIM)
4215 : (fcolors[C_MIS] ? COLOR_PAIR(C_MIS) : 0);
4220 print_time(&ent->sec, ent->flags);
4222 printw("%s%9s ", perms, (type == S_IFREG || type == S_IFDIR)
4223 ? coolsize(cfg.blkorder ? (blkcnt_t)ent->blocks << blk_shift : ent->size)
4224 : (type = (uchar_t)get_detail_ind(ent->mode), (char *)&type));
4232 uchar_t color_pair = get_color_pair_name_ind(ent, &ind, &attrs);
4234 addch((ent->flags & FILE_SELECTED) ? '+' | A_REVERSE | A_BOLD : ' ');
4236 if (g_state.oldcolor)
4237 resetdircolor(ent->flags);
4239 if (ent->flags & FILE_MISSING)
4241 if (color_pair && fcolors[color_pair])
4242 attrs |= COLOR_PAIR(color_pair);
4243 #ifdef ICONS_ENABLED
4244 print_icon(ent, attrs);
4256 addwstr(unescape(ent->name, namecols));
4258 addstr(unescape(ent->name, MIN(namecols, ent->nlen) + 1));
4267 static void savecurctx(char *path, char *curname, int nextctx)
4269 settings tmpcfg = cfg;
4270 context *ctxr = &g_ctx[nextctx];
4272 /* Save current context */
4274 xstrsncpy(g_ctx[tmpcfg.curctx].c_name, curname, NAME_MAX + 1);
4276 g_ctx[tmpcfg.curctx].c_name[0] = '\0';
4278 g_ctx[tmpcfg.curctx].c_cfg = tmpcfg;
4280 if (ctxr->c_cfg.ctxactive) { /* Switch to saved context */
4281 tmpcfg = ctxr->c_cfg;
4282 /* Skip ordering an open context */
4284 cfgsort[CTX_MAX] = cfgsort[nextctx];
4285 cfgsort[nextctx] = '0';
4287 } else { /* Set up a new context from current context */
4288 ctxr->c_cfg.ctxactive = 1;
4289 xstrsncpy(ctxr->c_path, path, PATH_MAX);
4290 ctxr->c_last[0] = ctxr->c_name[0] = ctxr->c_fltr[0] = ctxr->c_fltr[1] = '\0';
4291 ctxr->c_cfg = tmpcfg;
4292 /* If already in an ordered dir, clear ordering for the new context and let it order */
4293 if (cfgsort[cfg.curctx] == 'z')
4294 cfgsort[nextctx] = 'z';
4297 tmpcfg.curctx = nextctx;
4302 static void save_session(const char *sname, int *presel)
4305 session_header_t header = {0};
4306 bool status = FALSE;
4307 char ssnpath[PATH_MAX];
4308 char spath[PATH_MAX];
4310 header.ver = SESSIONS_VERSION;
4312 for (i = 0; i < CTX_MAX; ++i) {
4313 if (g_ctx[i].c_cfg.ctxactive) {
4314 if (cfg.curctx == i && ndents)
4315 /* Update current file name, arrows don't update it */
4316 xstrsncpy(g_ctx[i].c_name, pdents[cur].name, NAME_MAX + 1);
4317 header.pathln[i] = MIN(xstrlen(g_ctx[i].c_path), PATH_MAX) + 1;
4318 header.lastln[i] = MIN(xstrlen(g_ctx[i].c_last), PATH_MAX) + 1;
4319 header.nameln[i] = MIN(xstrlen(g_ctx[i].c_name), NAME_MAX) + 1;
4320 header.fltrln[i] = REGEX_MAX;
4324 mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4325 mkpath(ssnpath, sname, spath);
4327 fd = open(spath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
4329 printwait(messages[MSG_SEL_MISSING], presel);
4333 if ((write(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4334 || (write(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4337 for (i = 0; i < CTX_MAX; ++i)
4338 if ((write(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4339 || (write(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4340 || (header.nameln[i] > 0
4341 && write(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4342 || (header.lastln[i] > 0
4343 && write(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4344 || (header.fltrln[i] > 0
4345 && write(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4346 || (header.pathln[i] > 0
4347 && write(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4356 printwait(messages[MSG_FAILED], presel);
4359 static bool load_session(const char *sname, char **path, char **lastdir, char **lastname, bool restore)
4362 session_header_t header;
4363 bool has_loaded_dynamically = !(sname || restore);
4364 bool status = (sname && g_state.picker); /* Picker mode with session program option */
4365 char ssnpath[PATH_MAX];
4366 char spath[PATH_MAX];
4368 mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4371 sname = sname ? sname : xreadline(NULL, messages[MSG_SSN_NAME]);
4375 mkpath(ssnpath, sname, spath);
4377 /* If user is explicitly loading the "last session", skip auto-save */
4378 if ((sname[0] == '@') && !sname[1])
4379 has_loaded_dynamically = FALSE;
4381 mkpath(ssnpath, "@", spath);
4383 if (has_loaded_dynamically)
4384 save_session("@", NULL);
4386 fd = open(spath, O_RDONLY, S_IWUSR | S_IRUSR);
4389 printmsg(messages[MSG_SEL_MISSING]);
4390 xdelay(XDELAY_INTERVAL_MS);
4397 if ((read(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4398 || (header.ver != SESSIONS_VERSION)
4399 || (read(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4402 g_ctx[cfg.curctx].c_name[0] = g_ctx[cfg.curctx].c_last[0]
4403 = g_ctx[cfg.curctx].c_fltr[0] = g_ctx[cfg.curctx].c_fltr[1] = '\0';
4405 for (; i < CTX_MAX; ++i)
4406 if ((read(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4407 || (read(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4408 || (header.nameln[i] > 0
4409 && read(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4410 || (header.lastln[i] > 0
4411 && read(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4412 || (header.fltrln[i] > 0
4413 && read(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4414 || (header.pathln[i] > 0
4415 && read(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4418 *path = g_ctx[cfg.curctx].c_path;
4419 *lastdir = g_ctx[cfg.curctx].c_last;
4420 *lastname = g_ctx[cfg.curctx].c_name;
4421 set_sort_flags('\0'); /* Set correct sort options */
4428 printmsg(messages[MSG_FAILED]);
4429 xdelay(XDELAY_INTERVAL_MS);
4437 static uchar_t get_free_ctx(void)
4439 uchar_t r = cfg.curctx;
4442 r = (r + 1) & ~CTX_MAX;
4443 while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
4448 /* ctx is absolute: 1 to 4, + for smart context */
4449 static void set_smart_ctx(int ctx, char *nextpath, char **path, char *file, char **lastname, char **lastdir)
4451 if (ctx == '+') /* Get smart context */
4452 ctx = (int)(get_free_ctx() + 1);
4454 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 *dir, *cmd = xgetenv("NNN_ARCHMNT", utils[UTIL_ARCHMNT]);
4804 char *name = pdents[cur].name;
4805 size_t len = pdents[cur].nlen;
4806 char mntpath[PATH_MAX];
4808 if (!getutil(cmd)) {
4809 printmsg("install utility");
4813 dir = xstrdup(name);
4815 printmsg(messages[MSG_FAILED]);
4820 if (dir[--len] == '.') {
4827 /* Create the mount point */
4828 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4829 mkpath(mntpath, dir, newpath);
4832 if (!xmktree(newpath, TRUE)) {
4840 if (spawn(cmd, name, newpath, NULL, F_NORMAL)) {
4841 printmsg(messages[MSG_FAILED]);
4848 static bool remote_mount(char *newpath)
4850 uchar_t flag = F_CLI;
4853 bool r = getutil(utils[UTIL_RCLONE]), s = getutil(utils[UTIL_SSHFS]);
4854 char mntpath[PATH_MAX];
4857 printmsg("install sshfs/rclone");
4862 opt = get_input(messages[MSG_REMOTE_OPTS]);
4864 opt = (!s) ? 'r' : 's';
4867 env = xgetenv("NNN_SSHFS", utils[UTIL_SSHFS]);
4868 else if (opt == 'r') {
4869 flag |= F_NOWAIT | F_NOTRACE;
4870 env = xgetenv("NNN_RCLONE", "rclone mount");
4872 printmsg(messages[MSG_INVALID_KEY]);
4876 tmp = xreadline(NULL, "host[:dir] > ");
4878 printmsg(messages[MSG_CANCEL]);
4882 char *div = strchr(tmp, ':');
4887 /* Create the mount point */
4888 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4889 mkpath(mntpath, tmp, newpath);
4890 if (!xmktree(newpath, TRUE)) {
4895 if (!div) { /* Convert "host" to "host:" */
4896 size_t len = xstrlen(tmp);
4899 tmp[len + 1] = '\0';
4903 /* Connect to remote */
4905 if (spawn(env, tmp, newpath, NULL, flag)) {
4906 printmsg(messages[MSG_FAILED]);
4910 spawn(env, tmp, newpath, NULL, flag);
4911 printmsg(messages[MSG_RCLONE_DELAY]);
4912 xdelay(XDELAY_INTERVAL_MS << 2); /* Set 4 times the usual delay */
4919 * Unmounts if the directory represented by name is a mount point.
4920 * Otherwise, asks for hostname
4921 * Returns TRUE if directory needs to be refreshed *.
4923 static bool unmount(char *name, char *newpath, int *presel, char *currentpath)
4925 #if defined(__APPLE__) || defined(__FreeBSD__)
4926 static char cmd[] = "umount";
4928 static char cmd[] = "fusermount3"; /* Arch Linux utility */
4929 static bool found = FALSE;
4932 struct stat sb, psb;
4934 bool parent = FALSE;
4935 bool hovered = FALSE;
4936 char mntpath[PATH_MAX];
4938 #if !defined(__APPLE__) && !defined(__FreeBSD__)
4939 /* On Ubuntu it's fusermount */
4940 if (!found && !getutil(cmd)) {
4946 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4948 if (tmp && strcmp(mntpath, currentpath) == 0) {
4949 mkpath(mntpath, tmp, newpath);
4950 child = lstat(newpath, &sb) != -1;
4951 parent = lstat(xdirname(newpath), &psb) != -1;
4952 if (!child && !parent) {
4958 if (!tmp || !child || !S_ISDIR(sb.st_mode) || (child && parent && sb.st_dev == psb.st_dev)) {
4959 tmp = xreadline(NULL, messages[MSG_HOSTNAME]);
4962 if (name && (tmp[0] == '-') && (tmp[1] == '\0')) {
4963 mkpath(currentpath, name, newpath);
4969 mkpath(mntpath, tmp, newpath);
4971 if (!xdiraccess(newpath)) {
4976 #if defined(__APPLE__) || defined(__FreeBSD__)
4977 if (spawn(cmd, newpath, NULL, NULL, F_NORMAL)) {
4979 if (spawn(cmd, "-qu", newpath, NULL, F_NORMAL)) {
4981 if (!xconfirm(get_input(messages[MSG_LAZY])))
4985 if (spawn(cmd, "-l", newpath, NULL, F_NORMAL)) {
4986 #elif defined(__FreeBSD__)
4987 if (spawn(cmd, "-f", newpath, NULL, F_NORMAL)) {
4989 if (spawn(cmd, "-quz", newpath, NULL, F_NORMAL)) {
4991 printwait(messages[MSG_FAILED], presel);
4996 if (rmdir(newpath) == -1) {
5004 static void lock_terminal(void)
5006 spawn(xgetenv("NNN_LOCKER", utils[UTIL_LOCKER]), NULL, NULL, NULL, F_CLI);
5009 static void printkv(kv *kvarr, int fd, uchar_t max, uchar_t id)
5011 char *val = (id == NNN_BMS) ? bmstr : pluginstr;
5013 for (uchar_t i = 0; i < max && kvarr[i].key; ++i)
5014 dprintf(fd, " %c: %s\n", (char)kvarr[i].key, val + kvarr[i].off);
5017 static void printkeys(kv *kvarr, char *buf, uchar_t max)
5021 for (; i < max && kvarr[i].key; ++i) {
5023 buf[(i << 1) + 1] = kvarr[i].key;
5029 static size_t handle_bookmark(const char *bmark, char *newpath)
5034 if (maxbm || bmark) {
5035 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
5037 if (bmark) { /* There is a marked directory */
5043 printkeys(bookmark, g_buf + r - 1, maxbm);
5045 fd = get_input(NULL);
5049 if (fd == ',') /* Visit marked directory */
5050 bmark ? xstrsncpy(newpath, bmark, PATH_MAX) : (r = MSG_NOT_SET);
5051 else if (fd == '\r') { /* Visit bookmarks directory */
5052 mkpath(cfgpath, toks[TOK_BM], newpath);
5054 } else if (!get_kv_val(bookmark, newpath, fd, maxbm, NNN_BMS))
5055 r = MSG_INVALID_KEY;
5057 if (!r && chdir(newpath) == -1) {
5066 static void add_bookmark(char *path, char *newpath, int *presel)
5068 char *dir = xbasename(path);
5070 dir = xreadline(dir[0] ? dir : NULL, messages[MSG_BM_NAME]);
5072 size_t r = mkpath(cfgpath, toks[TOK_BM], newpath);
5074 newpath[r - 1] = '/';
5075 xstrsncpy(newpath + r, dir, PATH_MAX - r);
5076 printwait((symlink(path, newpath) == -1) ? strerror(errno) : newpath, presel);
5078 printwait(messages[MSG_CANCEL], presel);
5082 * The help string tokens (each line) start with a HEX value
5083 * which indicates the number of spaces to print before the
5084 * particular token. This method was chosen instead of a flat
5085 * string because the number of bytes in help was increasing
5086 * the binary size by around a hundred bytes. This would only
5087 * have increased as we keep adding new options.
5089 static void show_help(const char *path)
5091 const char *start, *end;
5092 const char helpstr[] = {
5095 "9Up k Up%-16cPgUp ^U Page up\n"
5096 "9Dn j Down%-14cPgDn ^D Page down\n"
5097 "9Lt h Parent%-12c~ ` @ - ~, /, start, prev\n"
5098 "5Ret Rt l Open%-20c' First file/match\n"
5099 "9g ^A Top%-21cJ Jump to entry/offset\n"
5100 "9G ^E End%-20c^J Toggle auto-advance on open\n"
5101 "8B (,) Book(mark)%-11cb ^/ Select bookmark\n"
5102 "a1-4 Context%-11c(Sh)Tab Cycle/new context\n"
5103 "62Esc ^Q Quit%-20cq Quit context\n"
5104 "b^G QuitCD%-18cQ Pick/err, quit\n"
5106 "1FILTER & PROMPT\n"
5107 "c/ Filter%-17c^N Toggle type-to-nav\n"
5108 "aEsc Exit prompt%-12c^L Toggle last filter\n"
5109 "c. Toggle hidden%-5cAlt+Esc Unfilter, quit context\n"
5112 "9o ^O Open with%-15cn Create new/link\n"
5113 "9f ^F File stats%-14cd Detail mode toggle\n"
5114 "b^R Rename/dup%-14cr Batch rename\n"
5115 "cz Archive%-17ce Edit file\n"
5116 "c* Toggle exe%-14c> Export list\n"
5117 "6Space + (Un)select%-12cm-m Select range/clear\n"
5118 "ca Select all%-14cA Invert sel\n"
5119 "9p ^P Copy here%-12cw ^W Cp/mv sel as\n"
5120 "9v ^V Move here%-15cE Edit sel list\n"
5121 "9x ^X Delete%-18cS Listed sel size\n"
5122 "aEsc Send to FIFO\n"
5125 "8Alt ; Select plugin%-11c= Launch app\n"
5126 "9! ^] Shell%-19c] Cmd prompt\n"
5127 "cc Connect remote%-10cu Unmount remote/archive\n"
5128 "9t ^T Sort toggles%-12cs Manage session\n"
5129 "cT Set time type%-11c0 Lock\n"
5130 "b^L Redraw%-18c? Help, conf\n"
5133 int fd = create_tmp_file();
5137 dprintf(fd, " |V\\_\n"
5143 char *prog = xgetenv(env_cfg[NNN_HELP], NULL);
5145 get_output(prog, NULL, NULL, fd, FALSE);
5147 start = end = helpstr;
5150 snprintf(g_buf, CMD_LEN_MAX, "%*c%.*s",
5151 xchartohex(*start), ' ', (int)(end - start), start + 1);
5152 dprintf(fd, g_buf, ' ');
5159 dprintf(fd, "\nLOCATIONS\n");
5160 for (uchar_t i = 0; i < CTX_MAX; ++i)
5161 if (g_ctx[i].c_cfg.ctxactive)
5162 dprintf(fd, " %u: %s\n", i + 1, g_ctx[i].c_path);
5164 dprintf(fd, "\nVOLUME: avail:%s ", coolsize(get_fs_info(path, VFS_AVAIL)));
5165 dprintf(fd, "used:%s ", coolsize(get_fs_info(path, VFS_USED)));
5166 dprintf(fd, "size:%s\n\n", coolsize(get_fs_info(path, VFS_SIZE)));
5169 dprintf(fd, "BOOKMARKS\n");
5170 printkv(bookmark, fd, maxbm, NNN_BMS);
5175 dprintf(fd, "PLUGIN KEYS\n");
5176 printkv(plug, fd, maxplug, NNN_PLUG);
5180 for (uchar_t i = NNN_OPENER; i <= NNN_TRASH; ++i) {
5181 start = getenv(env_cfg[i]);
5183 dprintf(fd, "%s: %s\n", env_cfg[i], start);
5187 dprintf(fd, "SELECTION FILE: %s\n", selpath);
5189 dprintf(fd, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
5192 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
5196 static void setexports(void)
5202 setenv(envs[ENV_NCUR], pdents[cur].name, 1);
5203 xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
5204 } else if (g_ctx[cfg.curctx].c_name[0])
5205 g_ctx[cfg.curctx].c_name[0] = '\0';
5207 for (uchar_t i = 0; i < CTX_MAX; ++i) {
5208 if (g_ctx[i].c_cfg.ctxactive) {
5209 dvar[1] = fvar[1] = '1' + i;
5210 setenv(dvar, g_ctx[i].c_path, 1);
5212 if (g_ctx[i].c_name[0]) {
5213 mkpath(g_ctx[i].c_path, g_ctx[i].c_name, g_buf);
5214 setenv(fvar, g_buf, 1);
5218 setenv("NNN_INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
5219 setenv("NNN_PREFER_SELECTION", xitoa(cfg.prefersel), 1);
5222 static void run_cmd_as_plugin(const char *file, uchar_t flags)
5226 xstrsncpy(g_buf, file, PATH_MAX);
5228 len = xstrlen(g_buf);
5229 if (len > 1 && g_buf[len - 1] == '*') {
5230 flags &= ~F_CONFIRM; /* Skip user confirmation */
5231 g_buf[len - 1] = '\0'; /* Get rid of trailing no confirmation symbol */
5236 get_output(utils[UTIL_SH_EXEC], g_buf, NULL, -1, TRUE);
5238 spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, flags);
5241 static bool plctrl_init(void)
5245 /* g_tmpfpath is used to generate tmp file names */
5246 g_tmpfpath[tmpfplen - 1] = '\0';
5247 len = xstrsncpy(g_pipepath, g_tmpfpath, TMP_LEN_MAX);
5248 g_pipepath[len - 1] = '/';
5249 len = xstrsncpy(g_pipepath + len, "nnn-pipe.", TMP_LEN_MAX - len) + len;
5250 xstrsncpy(g_pipepath + len - 1, xitoa(getpid()), TMP_LEN_MAX - len);
5251 setenv(env_cfg[NNN_PIPE], g_pipepath, TRUE);
5253 return EXIT_SUCCESS;
5256 static void rmlistpath(void)
5259 DPRINTF_S(__func__);
5260 DPRINTF_S(listpath);
5261 spawn(utils[UTIL_RM_RF], listpath, NULL, NULL, F_NOTRACE | F_MULTI);
5262 /* Do not free if program was started in list mode */
5263 if (listpath != initpath)
5269 static ssize_t read_nointr(int fd, void *buf, size_t count)
5274 len = read(fd, buf, count);
5275 while (len == -1 && errno == EINTR);
5280 static char *readpipe(int fd, char *ctxnum, char **path)
5282 char ctx, *nextpath = NULL;
5284 if (read_nointr(fd, g_buf, 1) != 1)
5287 if (g_buf[0] == '-') { /* Clear selection on '-' */
5289 if (read_nointr(fd, g_buf, 1) != 1)
5293 if (g_buf[0] == '+')
5294 ctx = (char)(get_free_ctx() + 1);
5295 else if (g_buf[0] < '0')
5298 ctx = g_buf[0] - '0';
5303 if (read_nointr(fd, g_buf, 1) != 1)
5309 ssize_t len = read_nointr(fd, g_buf, PATH_MAX);
5314 g_buf[len] = '\0'; /* Terminate the path read */
5315 if (g_buf[0] == '/') {
5317 len = xstrlen(g_buf);
5318 while (--len && (g_buf[len] == '/')) /* Trim all trailing '/' */
5321 } else if (op == 'l') {
5322 rmlistpath(); /* Remove last list mode path, if any */
5323 nextpath = load_input(fd, *path);
5324 } else if (op == 'p') {
5337 static bool run_plugin(char **path, const char *file, char *runfile, char **lastname, char **lastdir)
5342 bool cmd_as_plugin = FALSE;
5345 if (!g_state.pluginit) {
5347 g_state.pluginit = 1;
5352 /* Check for run-cmd-as-plugin mode */
5354 flags = F_MULTI | F_CONFIRM;
5357 if (*file == '|') { /* Check if output should be paged */
5360 } else if (*file == '&') { /* Check if GUI flags are to be used */
5361 flags = F_MULTI | F_NOTRACE | F_NOWAIT;
5368 if ((flags & F_NOTRACE) || (flags & F_PAGE)) {
5369 run_cmd_as_plugin(file, flags);
5373 cmd_as_plugin = TRUE;
5376 if (mkfifo(g_pipepath, 0600) != 0)
5383 if (!p) { // In child
5384 int wfd = open(g_pipepath, O_WRONLY | O_CLOEXEC);
5387 _exit(EXIT_FAILURE);
5389 if (!cmd_as_plugin) {
5393 /* Generate absolute path to plugin */
5394 mkpath(plgpath, file, g_buf);
5397 sel = selpath ? selpath : std;
5399 if (runfile && runfile[0]) {
5400 xstrsncpy(*lastname, runfile, NAME_MAX);
5401 spawn(g_buf, *lastname, *path, sel, 0);
5403 spawn(g_buf, NULL, *path, sel, 0);
5405 run_cmd_as_plugin(file, flags);
5408 _exit(EXIT_SUCCESS);
5414 rfd = open(g_pipepath, O_RDONLY);
5415 while (rfd == -1 && errno == EINTR);
5417 nextpath = readpipe(rfd, &ctx, path);
5419 set_smart_ctx(ctx, nextpath, path, runfile, lastname, lastdir);
5423 /* wait for the child to finish. no zombies allowed */
5424 waitpid(p, NULL, 0);
5433 static bool launch_app(char *newpath)
5436 char *tmp = newpath;
5438 mkpath(plgpath, utils[UTIL_LAUNCH], newpath);
5440 if (!getutil(utils[UTIL_FZF]) || access(newpath, X_OK) < 0) {
5441 tmp = xreadline(NULL, messages[MSG_APP_NAME]);
5442 r = F_NOWAIT | F_NOTRACE | F_MULTI;
5445 if (tmp && *tmp) // NOLINT
5446 spawn(tmp, (r == F_NORMAL) ? "0" : NULL, NULL, NULL, r);
5451 /* Returns TRUE if at least one command was run */
5452 static bool prompt_run(void)
5455 char *cmdline, *next;
5456 int cnt_j, cnt_J, cmd_ret;
5459 const char *xargs_j = "xargs -0 -I{} %s < %s";
5460 const char *xargs_J = "xargs -0 %s < %s";
5461 char cmd[CMD_LEN_MAX + 32]; // 32 for xargs format strings
5465 if (g_state.picker) {
5467 cmdline = xreadline(NULL, PROMPT);
5470 cmdline = getreadline("\n"PROMPT);
5472 // Check for an empty command
5473 if (!cmdline || !cmdline[0])
5477 lastcmd = xstrdup(cmdline);
5480 len = xstrlen(cmdline);
5484 while ((next = strstr(next, "%j"))) {
5487 // replace %j with {} for xargs later
5496 while ((next = strstr(next, "%J"))) {
5499 // %J should be the last thing in the command
5500 if (next == cmdline + len - 2) {
5501 cmdline[len - 2] = '\0';
5507 // We can't handle both %j and %J in a single command
5512 snprintf(cmd, CMD_LEN_MAX + 32, xargs_j, cmdline, selpath);
5514 snprintf(cmd, CMD_LEN_MAX + 32, xargs_J, cmdline, selpath);
5516 cmd_ret = spawn(shell, "-c", (cnt_j || cnt_J) ? cmd : cmdline, NULL, F_CLI | F_CONFIRM);
5517 if ((cnt_j || cnt_J) && cmd_ret == 0)
5524 static bool handle_cmd(enum action sel, char *newpath)
5526 endselection(FALSE);
5528 if (sel == SEL_LAUNCH)
5529 return launch_app(newpath);
5533 if (sel == SEL_PROMPT)
5534 return prompt_run();
5536 /* Set nnn nesting level */
5537 char *tmp = getenv(env_cfg[NNNLVL]);
5538 int r = tmp ? atoi(tmp) : 0;
5540 setenv(env_cfg[NNNLVL], xitoa(r + 1), 1);
5541 spawn(shell, NULL, NULL, NULL, F_CLI);
5542 setenv(env_cfg[NNNLVL], xitoa(r), 1);
5546 static void dentfree(void)
5552 /* Thread data cleanup */
5558 static void *du_thread(void *p_data)
5560 thread_data *pdata = (thread_data *)p_data;
5561 char *path[2] = {pdata->path, NULL};
5562 ullong_t tfiles = 0;
5563 blkcnt_t tblocks = 0;
5565 FTS *tree = fts_open(path, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR, 0);
5568 while ((node = fts_read(tree))) {
5569 if (node->fts_info & FTS_D) {
5570 if (g_state.interrupt)
5575 sb = node->fts_statp;
5577 if (cfg.apparentsz) {
5578 if (sb->st_size && DU_TEST)
5579 tblocks += sb->st_size;
5580 } else if (sb->st_blocks && DU_TEST)
5581 tblocks += sb->st_blocks;
5588 if (pdata->entnum >= 0)
5589 pdents[pdata->entnum].blocks = tblocks;
5591 if (!pdata->mntpoint) {
5592 core_blocks[pdata->core] += tblocks;
5593 core_files[pdata->core] += tfiles;
5595 core_files[pdata->core] += 1;
5597 pthread_mutex_lock(&running_mutex);
5598 threadbmp |= (1 << pdata->core);
5600 pthread_mutex_unlock(&running_mutex);
5605 static void dirwalk(char *path, int entnum, bool mountpoint)
5607 /* Loop till any core is free */
5608 while (active_threads == NUM_DU_THREADS);
5610 if (g_state.interrupt)
5613 pthread_mutex_lock(&running_mutex);
5614 int core = ffs(threadbmp) - 1;
5616 threadbmp &= ~(1 << core);
5618 pthread_mutex_unlock(&running_mutex);
5620 xstrsncpy(core_data[core].path, path, PATH_MAX);
5621 core_data[core].entnum = entnum;
5622 core_data[core].core = (ushort_t)core;
5623 core_data[core].mntpoint = mountpoint;
5627 pthread_create(&tid, NULL, du_thread, (void *)&(core_data[core]));
5630 addstr(xbasename(path));
5631 addstr(" [^C aborts]\n");
5635 static bool prep_threads(void)
5637 if (!g_state.duinit) {
5639 threadbmp >>= (32 - NUM_DU_THREADS);
5642 core_blocks = calloc(NUM_DU_THREADS, sizeof(blkcnt_t));
5644 core_data = calloc(NUM_DU_THREADS, sizeof(thread_data));
5646 core_files = calloc(NUM_DU_THREADS, sizeof(ullong_t));
5648 if (!core_blocks || !core_data || !core_files) {
5653 /* Increase current open file descriptor limit */
5656 g_state.duinit = TRUE;
5658 memset(core_blocks, 0, NUM_DU_THREADS * sizeof(blkcnt_t));
5659 memset(core_data, 0, NUM_DU_THREADS * sizeof(thread_data));
5660 memset(core_files, 0, NUM_DU_THREADS * sizeof(ullong_t));
5665 /* Skip self and parent */
5666 static inline bool selforparent(const char *path)
5668 return path[0] == '.' && (path[1] == '\0' || (path[1] == '.' && path[2] == '\0'));
5671 static int dentfill(char *path, struct entry **ppdents)
5673 uchar_t entflags = 0;
5676 char *namep, *pnb, *buf;
5677 struct entry *dentp;
5678 size_t off = 0, namebuflen = NAMEBUF_INCR;
5679 struct stat sb_path, sb;
5680 DIR *dirp = opendir(path);
5683 gtimesecs = time(NULL);
5685 DPRINTF_S(__func__);
5690 int fd = dirfd(dirp);
5697 if (fstatat(fd, path, &sb_path, 0) == -1)
5701 ihashbmp = calloc(1, HASH_OCTETS << 3);
5705 memset(ihashbmp, 0, HASH_OCTETS << 3);
5707 if (!prep_threads())
5710 attron(COLOR_PAIR(cfg.curctx + 1));
5713 #if _POSIX_C_SOURCE >= 200112L
5714 posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
5721 #if defined(__sun) || defined(__HAIKU__)
5722 flags = AT_SYMLINK_NOFOLLOW; /* no d_type */
5724 if (cfg.blkorder || dp->d_type == DT_UNKNOWN) {
5726 * Optimization added for filesystems which support dirent.d_type
5729 * - the symlink size is set to 0
5730 * - the modification time of the symlink is set to that of the target file
5732 flags = AT_SYMLINK_NOFOLLOW;
5739 if (selforparent(namep))
5742 if (!cfg.showhidden && namep[0] == '.') {
5746 if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
5749 if (S_ISDIR(sb.st_mode)) {
5750 if (sb_path.st_dev == sb.st_dev) { // NOLINT
5751 mkpath(path, namep, buf); // NOLINT
5752 dirwalk(buf, -1, FALSE);
5754 if (g_state.interrupt)
5758 /* Do not recount hard links */
5759 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5760 dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5767 if (fstatat(fd, namep, &sb, flags) == -1) {
5768 if (flags || (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)) {
5773 DPRINTF_S(strerror(errno));
5776 entflags = FILE_MISSING;
5777 memset(&sb, 0, sizeof(struct stat));
5778 } else /* Orphaned symlink */
5779 entflags = SYM_ORPHAN;
5782 if (ndents == total_dents) {
5784 while (active_threads);
5786 total_dents += ENTRY_INCR;
5787 *ppdents = xrealloc(*ppdents, total_dents * sizeof(**ppdents));
5793 DPRINTF_P(*ppdents);
5796 /* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
5797 if (namebuflen - off < NAME_MAX + 1) {
5798 namebuflen += NAMEBUF_INCR;
5801 pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
5807 DPRINTF_P(pnamebuf);
5809 /* realloc() may result in memory move, we must re-adjust if that happens */
5810 if (pnb != pnamebuf) {
5812 dentp->name = pnamebuf;
5814 for (int count = 1; count < ndents; ++dentp, ++count)
5815 /* Current file name starts at last file name start + length */
5816 (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
5820 dentp = *ppdents + ndents;
5822 /* Selection file name */
5823 dentp->name = (char *)((size_t)pnamebuf + off);
5824 dentp->nlen = xstrsncpy(dentp->name, namep, NAME_MAX + 1);
5827 /* Copy other fields */
5828 if (cfg.timetype == T_MOD) {
5829 dentp->sec = sb.st_mtime;
5831 dentp->nsec = (uint_t)sb.st_mtimespec.tv_nsec;
5833 dentp->nsec = (uint_t)sb.st_mtim.tv_nsec;
5835 } else if (cfg.timetype == T_ACCESS) {
5836 dentp->sec = sb.st_atime;
5838 dentp->nsec = (uint_t)sb.st_atimespec.tv_nsec;
5840 dentp->nsec = (uint_t)sb.st_atim.tv_nsec;
5843 dentp->sec = sb.st_ctime;
5845 dentp->nsec = (uint_t)sb.st_ctimespec.tv_nsec;
5847 dentp->nsec = (uint_t)sb.st_ctim.tv_nsec;
5851 if ((gtimesecs - sb.st_mtime <= 300) || (gtimesecs - sb.st_ctime <= 300))
5852 entflags |= FILE_YOUNG;
5854 #if !(defined(__sun) || defined(__HAIKU__))
5855 if (!flags && dp->d_type == DT_LNK) {
5856 /* Do not add sizes for links */
5857 dentp->mode = (sb.st_mode & ~S_IFMT) | S_IFLNK;
5858 dentp->size = listpath ? sb.st_size : 0;
5860 dentp->mode = sb.st_mode;
5861 dentp->size = sb.st_size;
5864 dentp->mode = sb.st_mode;
5865 dentp->size = sb.st_size;
5869 dentp->uid = sb.st_uid;
5870 dentp->gid = sb.st_gid;
5873 dentp->flags = S_ISDIR(sb.st_mode) ? 0 : ((sb.st_nlink > 1) ? HARD_LINK : 0);
5875 dentp->flags |= entflags;
5880 if (S_ISDIR(sb.st_mode)) {
5881 mkpath(path, namep, buf); // NOLINT
5883 /* Need to show the disk usage of this dir */
5884 dirwalk(buf, ndents, (sb_path.st_dev != sb.st_dev)); // NOLINT
5886 if (g_state.interrupt)
5889 dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5890 /* Do not recount hard links */
5891 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5892 dir_blocks += dentp->blocks;
5898 /* Flag if this is a dir or symlink to a dir */
5899 if (S_ISLNK(sb.st_mode)) {
5901 fstatat(fd, namep, &sb, 0);
5904 if (S_ISDIR(sb.st_mode))
5905 dentp->flags |= DIR_OR_DIRLNK;
5906 #if !(defined(__sun) || defined(__HAIKU__)) /* no d_type */
5907 } else if (dp->d_type == DT_DIR || ((dp->d_type == DT_LNK
5908 || dp->d_type == DT_UNKNOWN) && S_ISDIR(sb.st_mode))) {
5909 dentp->flags |= DIR_OR_DIRLNK;
5914 } while ((dp = readdir(dirp)));
5917 if (g_state.duinit && cfg.blkorder) {
5918 while (active_threads);
5920 attroff(COLOR_PAIR(cfg.curctx + 1));
5921 for (int i = 0; i < NUM_DU_THREADS; ++i) {
5922 num_files += core_files[i];
5923 dir_blocks += core_blocks[i];
5927 /* Should never be null */
5928 if (closedir(dirp) == -1)
5934 static void populate(char *path, char *lastname)
5937 struct timespec ts1, ts2;
5939 clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
5942 ndents = dentfill(path, &pdents);
5947 ENTSORT(pdents, ndents, entrycmpfn);
5951 clock_gettime(CLOCK_REALTIME, &ts2);
5952 DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
5955 /* Find cur from history */
5956 /* No NULL check for lastname, always points to an array */
5957 move_cursor(*lastname ? dentfind(lastname, ndents) : 0, 0);
5959 // Force full redraw
5960 last_curscroll = -1;
5964 static void notify_fifo(bool force)
5970 fifofd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC);
5973 /* Unexpected error, the FIFO file might have been removed */
5974 /* We give up FIFO notification */
5980 static struct entry lastentry;
5982 if (!force && !memcmp(&lastentry, &pdents[cur], sizeof(struct entry))) // NOLINT
5985 lastentry = pdents[cur];
5987 char path[PATH_MAX];
5988 size_t len = mkpath(g_ctx[cfg.curctx].c_path, ndents ? pdents[cur].name : "", path);
5990 path[len - 1] = '\n';
5992 ssize_t ret = write(fifofd, path, len);
5994 if (ret != (ssize_t)len && !(ret == -1 && (errno == EAGAIN || errno == EPIPE))) {
5995 DPRINTF_S(strerror(errno));
5999 static void send_to_explorer(int *presel)
6002 int fd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0600);
6003 if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
6012 notify_fifo(TRUE); /* Send opened path to NNN_FIFO */
6016 static void move_cursor(int target, int ignore_scrolloff)
6018 int onscreen = xlines - 4; /* Leave top 2 and bottom 2 lines */
6020 target = MAX(0, MIN(ndents - 1, target));
6021 last_curscroll = curscroll;
6025 if (!ignore_scrolloff) {
6026 int delta = target - last;
6027 int scrolloff = MIN(SCROLLOFF, onscreen >> 1);
6030 * When ignore_scrolloff is 1, the cursor can jump into the scrolloff
6031 * margin area, but when ignore_scrolloff is 0, act like a boa
6032 * constrictor and squeeze the cursor towards the middle region of the
6033 * screen by allowing it to move inward and disallowing it to move
6034 * outward (deeper into the scrolloff margin area).
6036 if (((cur < (curscroll + scrolloff)) && delta < 0)
6037 || ((cur > (curscroll + onscreen - scrolloff - 1)) && delta > 0))
6040 curscroll = MIN(curscroll, MIN(cur, ndents - onscreen));
6041 curscroll = MAX(curscroll, MAX(cur - (onscreen - 1), 0));
6044 if (!g_state.fifomode)
6045 notify_fifo(FALSE); /* Send hovered path to NNN_FIFO */
6049 static void handle_screen_move(enum action sel)
6055 if (cfg.rollover || (cur != ndents - 1))
6056 move_cursor((cur + 1) % ndents, 0);
6059 if (cfg.rollover || cur)
6060 move_cursor((cur + ndents - 1) % ndents, 0);
6063 onscreen = xlines - 4;
6064 move_cursor(curscroll + (onscreen - 1), 1);
6065 curscroll += onscreen - 1;
6068 onscreen = xlines - 4;
6069 move_cursor(curscroll + (onscreen - 1), 1);
6070 curscroll += onscreen >> 1;
6073 onscreen = xlines - 4;
6074 move_cursor(curscroll, 1);
6075 curscroll -= onscreen - 1;
6078 onscreen = xlines - 4;
6079 move_cursor(curscroll, 1);
6080 curscroll -= onscreen >> 1;
6084 char *input = xreadline(NULL, "jump (+n/-n/n): ");
6086 if (!input || !*input)
6088 if (input[0] == '-') {
6089 cur -= atoi(input + 1);
6092 } else if (input[0] == '+') {
6093 cur += atoi(input + 1);
6097 int index = atoi(input);
6099 if ((index < 1) || (index > ndents))
6103 onscreen = xlines - 4;
6104 move_cursor(cur, 1);
6105 curscroll -= onscreen >> 1;
6112 move_cursor(ndents - 1, 1);
6114 default: /* case SEL_FIRST */
6116 int c = get_input(messages[MSG_FIRST]);
6123 int r = (c == TOUPPER(*pdents[cur].name)) ? (cur + 1) : 0;
6125 for (; r < ndents; ++r) {
6126 if (((c == '\'') && !(pdents[r].flags & DIR_OR_DIRLNK))
6127 || (c == TOUPPER(*pdents[r].name))) {
6128 move_cursor((r) % ndents, 0);
6137 static void handle_openwith(const char *path, const char *name, char *newpath, char *tmp)
6139 /* Confirm if app is CLI or GUI */
6140 int r = get_input(messages[MSG_CLI_MODE]);
6142 r = (r == 'c' ? F_CLI :
6143 ((r == 'g' || r == '\r') ? (F_NOWAIT | F_NOTRACE | F_MULTI) : 0));
6145 mkpath(path, name, newpath);
6146 spawn(tmp, newpath, NULL, NULL, r);
6150 static void copynextname(char *lastname)
6153 cur += (cur != (ndents - 1)) ? 1 : -1;
6159 static int handle_context_switch(enum action sel)
6164 case SEL_CYCLE: // fallthrough
6166 /* visit next and previous contexts */
6168 if (sel == SEL_CYCLE)
6170 r = (r + 1) & ~CTX_MAX;
6171 while (!g_ctx[r].c_cfg.ctxactive);
6173 do /* Attempt to create a new context */
6174 r = (r + 1) & ~CTX_MAX;
6175 while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
6177 if (r == cfg.curctx) /* If all contexts are active, reverse cycle */
6179 r = (r + (CTX_MAX - 1)) & (CTX_MAX - 1);
6180 while (!g_ctx[r].c_cfg.ctxactive);
6182 default: /* SEL_CTXN */
6183 if (sel >= SEL_CTX1) /* CYCLE keys are lesser in value */
6184 r = sel - SEL_CTX1; /* Save the next context id */
6186 if (cfg.curctx == r) {
6187 if (sel == SEL_CYCLE)
6188 (r == CTX_MAX - 1) ? (r = 0) : ++r;
6189 else if (sel == SEL_CYCLER)
6190 (r == 0) ? (r = CTX_MAX - 1) : --r;
6199 static int set_sort_flags(int r)
6201 bool session = (r == '\0');
6202 bool reverse = FALSE;
6204 if (ISUPPER_(r) && (r != 'R') && (r != 'C')) {
6209 /* Set the correct input in case of a session load */
6211 if (cfg.apparentsz) {
6214 } else if (cfg.blkorder) {
6220 namecmpfn = &xstrverscasecmp;
6223 entrycmpfn = &reventrycmp;
6224 } else if (r == CONTROL('T')) {
6225 /* Cycling order: clear -> size -> time -> clear */
6228 else if (cfg.sizeorder)
6235 case 'a': /* Apparent du */
6236 cfg.apparentsz ^= 1;
6237 if (cfg.apparentsz) {
6243 case 'd': /* Disk usage */
6245 if (!cfg.apparentsz)
6248 blk_shift = ffs(S_BLKSIZE) - 1;
6258 entrycmpfn = &entrycmp;
6260 endselection(TRUE); /* We are going to reload dir */
6270 entrycmpfn = &entrycmp;
6271 namecmpfn = &xstricmp;
6273 case 'e': /* File extension */
6280 entrycmpfn = &entrycmp;
6282 case 'r': /* Reverse sort */
6284 entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
6286 case 's': /* File size */
6293 entrycmpfn = &entrycmp;
6295 case 't': /* Time */
6302 entrycmpfn = &entrycmp;
6304 case 'v': /* Version */
6306 namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
6319 entrycmpfn = &reventrycmp;
6322 cfgsort[cfg.curctx] = (uchar_t)r;
6327 static bool set_time_type(int *presel)
6330 char buf[] = "'a'ccess / 'c'hange / 'm'od [ ]";
6332 buf[sizeof(buf) - 3] = cfg.timetype == T_MOD ? 'm' : (cfg.timetype == T_ACCESS ? 'a' : 'c');
6334 int r = get_input(buf);
6336 if (r == 'a' || r == 'c' || r == 'm') {
6337 r = (r == 'm') ? T_MOD : ((r == 'a') ? T_ACCESS : T_CHANGE);
6338 if (cfg.timetype != r) {
6341 if (cfg.filtermode || g_ctx[cfg.curctx].c_fltr[1])
6348 r = MSG_INVALID_KEY;
6351 printwait(messages[r], presel);
6356 static void statusbar(char *path)
6360 pEntry pent = &pdents[cur];
6367 /* Get the file extension for regular files */
6368 if (S_ISREG(pent->mode)) {
6369 i = (int)(pent->nlen - 1);
6370 ptr = xextension(pent->name, i);
6372 len = i - (ptr - pent->name);
6373 if (!ptr || len > 5 || len < 2)
6378 attron(COLOR_PAIR(cfg.curctx + 1));
6380 if (cfg.fileinfo && get_output("file", "-b", pdents[cur].name, -1, FALSE))
6381 mvaddstr(xlines - 2, 2, g_buf);
6385 printw("%d/%s ", cur + 1, xitoa(ndents));
6387 if (g_state.selmode || nselected) {
6390 if (g_state.rangesel)
6392 else if (g_state.selmode)
6395 addstr(xitoa(nselected));
6401 if (cfg.blkorder) { /* du mode */
6404 xstrsncpy(buf, coolsize(dir_blocks << blk_shift), 12);
6406 printw("%cu:%s avail:%s files:%llu %lluB %s\n",
6407 (cfg.apparentsz ? 'a' : 'd'), buf, coolsize(get_fs_info(path, VFS_AVAIL)),
6408 num_files, (ullong_t)pent->blocks << blk_shift, ptr);
6409 } else { /* light or detail mode */
6410 char sort[] = "\0\0\0\0\0";
6412 if (getorderstr(sort))
6416 print_time(&pent->sec, pent->flags);
6419 addstr(get_lsperms(pent->mode));
6422 if (g_state.uidgid) {
6423 addstr(getpwname(pent->uid));
6425 addstr(getgrname(pent->gid));
6429 if (S_ISLNK(pent->mode)) {
6430 if (!cfg.fileinfo) {
6431 i = readlink(pent->name, g_buf, PATH_MAX);
6432 addstr(coolsize(i >= 0 ? i : pent->size)); /* Show symlink size */
6433 if (i > 1) { /* Show symlink target */
6437 getyx(stdscr, len, y);
6438 i = MIN(i, xcols - y);
6444 addstr(coolsize(pent->size));
6447 if (pent->flags & HARD_LINK) {
6450 if (stat(pent->name, &sb) != -1) {
6452 addstr(xitoa((int)sb.st_nlink)); /* Show number of links */
6454 addstr(xitoa((int)sb.st_ino)); /* Show inode number */
6461 attroff(COLOR_PAIR(cfg.curctx + 1));
6462 /* Place HW cursor on current for Braille systems */
6466 static inline void markhovered(void)
6468 if (cfg.showdetail && ndents) { /* Bold forward arrowhead */
6470 addch('>' | A_BOLD);
6474 static int adjust_cols(int n)
6476 /* Calculate the number of cols available to print entry name */
6477 #ifdef ICONS_ENABLED
6478 n -= (g_state.oldcolor ? 0 : ICON_SIZE + ICON_PADDING_LEFT_LEN + ICON_PADDING_RIGHT_LEN);
6480 if (cfg.showdetail) {
6481 /* Fallback to light mode if less than 35 columns */
6483 cfg.showdetail ^= 1;
6484 else /* 2 more accounted for below */
6488 /* 2 columns for preceding space and indicator */
6492 static void draw_line(int ncols)
6496 ncols = adjust_cols(ncols);
6498 if (g_state.oldcolor && (pdents[last].flags & DIR_OR_DIRLNK)) {
6499 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6503 move(2 + last - curscroll, 0);
6504 printent(&pdents[last], ncols, FALSE);
6506 if (g_state.oldcolor && (pdents[cur].flags & DIR_OR_DIRLNK)) {
6507 if (!dir) {/* First file is not a directory */
6508 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6511 } else if (dir) { /* Second file is not a directory */
6512 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6516 move(2 + cur - curscroll, 0);
6517 printent(&pdents[cur], ncols, TRUE);
6519 /* Must reset e.g. no files in dir */
6521 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6526 static void redraw(char *path)
6528 getmaxyx(stdscr, xlines, xcols);
6530 int ncols = (xcols <= PATH_MAX) ? xcols : PATH_MAX;
6531 int onscreen = xlines - 4;
6538 if (ndents && (last_curscroll == curscroll))
6539 return draw_line(ncols);
6542 DPRINTF_S(__func__);
6547 /* Enforce scroll/cursor invariants */
6548 move_cursor(cur, 1);
6550 /* Fail redraw if < than 10 columns, context info prints 10 chars */
6551 if (ncols <= MIN_DISPLAY_COL) {
6552 printmsg(messages[MSG_FEW_COLUMNS]);
6559 for (i = 0; i < CTX_MAX; ++i) { /* 8 chars printed for contexts - "1 2 3 4 " */
6560 if (!g_ctx[i].c_cfg.ctxactive)
6563 addch((i + '1') | (COLOR_PAIR(i + 1) | A_BOLD
6564 /* active: underline, current: reverse */
6565 | ((cfg.curctx != i) ? A_UNDERLINE : A_REVERSE)));
6570 attron(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6573 bool in_home = set_tilde_in_path(path);
6574 char *ptr = in_home ? &path[homelen - 1] : path;
6576 i = (int)xstrlen(ptr);
6577 if ((i + MIN_DISPLAY_COL) <= ncols)
6578 addnstr(ptr, ncols - MIN_DISPLAY_COL);
6580 char *base = xmemrchr((uchar_t *)ptr, '/', i);
6589 if (ptr && (base != ptr)) {
6590 while (ptr < base) {
6592 i += 2; /* 2 characters added */
6593 if (ncols < i + MIN_DISPLAY_COL) {
6594 base = NULL; /* Can't print more characters */
6606 addnstr(base, ncols - (MIN_DISPLAY_COL + i));
6610 reset_tilde_in_path(path);
6612 attroff(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6614 /* Go to first entry */
6615 if (curscroll > 0) {
6617 #ifdef ICONS_ENABLED
6618 addstr(ICON_ARROW_UP);
6624 if (g_state.oldcolor) {
6625 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6626 g_state.dircolor = 1;
6629 onscreen = MIN(onscreen + curscroll, ndents);
6631 ncols = adjust_cols(ncols);
6633 int len = scanselforpath(path, FALSE);
6636 for (i = curscroll; i < onscreen; ++i) {
6640 findmarkentry(len, &pdents[i]);
6642 printent(&pdents[i], ncols, i == cur);
6645 /* Must reset e.g. no files in dir */
6646 if (g_state.dircolor) {
6647 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6648 g_state.dircolor = 0;
6651 /* Go to last entry */
6652 if (onscreen < ndents) {
6653 move(xlines - 2, 0);
6654 #ifdef ICONS_ENABLED
6655 addstr(ICON_ARROW_DOWN);
6664 static bool cdprep(char *lastdir, char *lastname, char *path, char *newpath)
6669 /* Save last working directory */
6670 xstrsncpy(lastdir, path, PATH_MAX);
6672 /* Save the newly opted dir in path */
6673 xstrsncpy(path, newpath, PATH_MAX);
6677 return cfg.filtermode;
6680 static void showselsize(const char *path)
6683 int len = scanselforpath(path, FALSE);
6685 for (int r = 0, selcount = nselected; (r < ndents) && selcount; ++r)
6686 if (findinsel(findselpos, len + xstrsncpy(g_sel + len, pdents[r].name, pdents[r].nlen))) {
6687 sz += cfg.blkorder ? pdents[r].blocks : pdents[r].size;
6691 printmsg(coolsize(cfg.blkorder ? sz << blk_shift : sz));
6694 static bool browse(char *ipath, const char *session, int pkey)
6696 alignas(max_align_t) char newpath[PATH_MAX];
6697 alignas(max_align_t) char runfile[NAME_MAX + 1];
6698 char *path, *lastdir, *lastname, *dir, *tmp;
6702 int r = -1, presel, selstartid = 0, selendid = 0;
6703 const uchar_t opener_flags = (cfg.cliopener ? F_CLI : (F_NOTRACE | F_NOSTDIN | F_NOWAIT));
6704 bool watch = FALSE, cd = TRUE;
6709 struct timespec mousetimings[2] = {{.tv_sec = 0, .tv_nsec = 0}, {.tv_sec = 0, .tv_nsec = 0}};
6710 int mousedent[2] = {-1, -1};
6711 bool currentmouse = 1, rightclicksel = 0;
6716 getmaxyx(stdscr, xlines, xcols);
6719 /* set-up first context */
6720 if (!session || !load_session(session, &path, &lastdir, &lastname, FALSE)) {
6724 g_ctx[0].c_last[0] = '\0';
6725 lastdir = g_ctx[0].c_last; /* last visited directory */
6727 if (g_state.initfile) {
6728 xstrsncpy(g_ctx[0].c_name, xbasename(ipath), sizeof(g_ctx[0].c_name));
6731 g_ctx[0].c_name[0] = '\0';
6733 lastname = g_ctx[0].c_name; /* last visited file name */
6735 xstrsncpy(g_ctx[0].c_path, ipath, PATH_MAX);
6736 /* If the initial path is a file, retain a way to return to start dir */
6737 if (g_state.initfile) {
6739 initpath = ipath = getcwd(NULL, 0);
6741 path = g_ctx[0].c_path; /* current directory */
6743 g_ctx[0].c_fltr[0] = g_ctx[0].c_fltr[1] = '\0';
6744 g_ctx[0].c_cfg = cfg; /* current configuration */
6749 newpath[0] = runfile[0] = '\0';
6751 presel = pkey ? ((pkey == CREATE_NEW_KEY) ? 'n' : ';') : ((cfg.filtermode
6752 || (session && (g_ctx[cfg.curctx].c_fltr[0] == FILTER
6753 || g_ctx[cfg.curctx].c_fltr[0] == RFILTER)
6754 && g_ctx[cfg.curctx].c_fltr[1])) ? FILTER : 0);
6756 pdents = xrealloc(pdents, total_dents * sizeof(struct entry));
6760 /* Allocate buffer to hold names */
6761 pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
6765 /* The following call is added to handle a broken window at start */
6766 if (presel == FILTER)
6767 handle_key_resize();
6771 * Can fail when permissions change while browsing.
6772 * It's assumed that path IS a directory when we are here.
6774 if (chdir(path) == -1) {
6775 DPRINTF_S("directory inaccessible");
6776 valid_parent(path, lastname);
6784 #ifdef LINUX_INOTIFY
6785 if ((presel == FILTER || watch) && inotify_wd >= 0) {
6786 inotify_rm_watch(inotify_fd, inotify_wd);
6790 #elif defined(BSD_KQUEUE)
6791 if ((presel == FILTER || watch) && event_fd >= 0) {
6796 #elif defined(HAIKU_NM)
6797 if ((presel == FILTER || watch) && haiku_hnd != NULL) {
6798 haiku_stop_watch(haiku_hnd);
6799 haiku_nm_active = FALSE;
6805 if (cfgsort[cfg.curctx] != '0') {
6806 if (cfgsort[cfg.curctx] == 'z')
6807 set_sort_flags('c');
6808 if ((!cfgsort[cfg.curctx] || (cfgsort[cfg.curctx] == 'c'))
6809 && ((r = get_kv_key(order, path, maxorder, NNN_ORDER)) > 0)) { // NOLINT
6811 cfgsort[cfg.curctx] = 'z';
6814 cfgsort[cfg.curctx] = cfgsort[CTX_MAX];
6818 populate(path, lastname);
6819 if (g_state.interrupt) {
6820 g_state.interrupt = cfg.apparentsz = cfg.blkorder = 0;
6821 blk_shift = BLK_SHIFT_512;
6822 presel = CONTROL('L');
6825 #ifdef LINUX_INOTIFY
6826 if (presel != FILTER && inotify_wd == -1)
6827 inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
6828 #elif defined(BSD_KQUEUE)
6829 if (presel != FILTER && event_fd == -1) {
6830 #if defined(O_EVTONLY)
6831 event_fd = open(path, O_EVTONLY);
6833 event_fd = open(path, O_RDONLY);
6836 EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
6837 EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
6839 #elif defined(HAIKU_NM)
6840 haiku_nm_active = haiku_watch_dir(haiku_hnd, path) == EXIT_SUCCESS;
6844 /* Do not do a double redraw in filterentries */
6845 if ((presel != FILTER) || !filterset()) {
6851 /* Exit if parent has exited */
6853 _exit(EXIT_FAILURE);
6855 /* If CWD is deleted or moved or perms changed, find an accessible parent */
6856 if (chdir(path) == -1)
6859 /* If STDIN is no longer a tty (closed) we should exit */
6860 if (!isatty(STDIN_FILENO) && !g_state.picker)
6861 return EXIT_FAILURE;
6863 sel = nextsel(presel);
6870 if (getmouse(&event) != OK)
6873 /* Handle clicking on a context at the top */
6874 if (event.bstate == BUTTON1_PRESSED && event.y == 0) {
6875 /* Get context from: "[1 2 3 4]..." */
6878 /* If clicked after contexts, go to parent */
6881 else if (r >= 0 && r != cfg.curctx) {
6882 savecurctx(path, ndents ? pdents[cur].name : NULL, r);
6884 /* Reset the pointers */
6885 path = g_ctx[r].c_path;
6886 lastdir = g_ctx[r].c_last;
6887 lastname = g_ctx[r].c_name;
6897 if (sel == SEL_BACK) {
6899 dir = visit_parent(path, newpath, &presel);
6904 xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
6906 cdprep(lastdir, NULL, path, dir) ? (presel = FILTER) : (watch = TRUE);
6913 /* Middle click action */
6914 if (event.bstate == BUTTON2_PRESSED) {
6915 presel = middle_click_key;
6918 #if NCURSES_MOUSE_VERSION > 1
6920 if (event.bstate == BUTTON4_PRESSED && ndents && (cfg.rollover || cur)) {
6921 move_cursor((!cfg.rollover && cur < scroll_lines
6922 ? 0 : (cur + ndents - scroll_lines) % ndents), 0);
6927 if (event.bstate == BUTTON5_PRESSED && ndents
6928 && (cfg.rollover || (cur != ndents - 1))) {
6929 move_cursor((!cfg.rollover && cur >= ndents - scroll_lines)
6930 ? (ndents - 1) : ((cur + scroll_lines) % ndents), 0);
6935 /* Toggle filter mode on left click on last 2 lines */
6936 if (event.y >= xlines - 2 && event.bstate == BUTTON1_PRESSED) {
6938 cfg.filtermode ^= 1;
6939 if (cfg.filtermode) {
6944 /* Start watching the directory */
6951 /* Handle clicking on a file */
6952 if (event.y >= 2 && event.y <= ndents + 1 &&
6953 (event.bstate == BUTTON1_PRESSED ||
6954 event.bstate == BUTTON3_PRESSED)) {
6955 r = curscroll + (event.y - 2);
6959 else if ((event.bstate == BUTTON1_PRESSED) && !g_state.fifomode)
6960 notify_fifo(TRUE); /* Send clicked path to NNN_FIFO */
6962 /* Handle right click selection */
6963 if (event.bstate == BUTTON3_PRESSED) {
6971 #if defined(CLOCK_MONOTONIC_RAW)
6972 CLOCK_MONOTONIC_RAW,
6973 #elif defined(CLOCK_MONOTONIC)
6978 &mousetimings[currentmouse]);
6979 mousedent[currentmouse] = cur;
6981 /* Single click just selects, double click falls through to SEL_OPEN */
6982 if ((mousedent[0] != mousedent[1]) ||
6983 (((_ABSSUB(mousetimings[0].tv_sec, mousetimings[1].tv_sec) << 30)
6984 + (_ABSSUB(mousetimings[0].tv_nsec, mousetimings[1].tv_nsec)))
6985 > DBLCLK_INTERVAL_NS))
6988 mousetimings[currentmouse].tv_sec = 0;
6989 mousedent[currentmouse] = -1;
6992 if (cfg.filtermode || filterset())
6999 case SEL_NAV_IN: // fallthrough
7001 /* Cannot descend in empty directories */
7004 g_state.selbm = g_state.runplugin = 0;
7008 pent = &pdents[cur];
7009 if (!g_state.selbm || !(S_ISLNK(pent->mode) &&
7010 realpath(pent->name, newpath) &&
7011 xstrsncpy(path, lastdir, PATH_MAX)))
7012 mkpath(path, pent->name, newpath);
7016 /* Visit directory */
7017 if (pent->flags & DIR_OR_DIRLNK) {
7018 if (chdir(newpath) == -1) {
7023 cdprep(lastdir, lastname, path, newpath) ? (presel = FILTER) : (watch = TRUE);
7027 /* Cannot use stale data in entry, file may be missing by now */
7028 if (stat(newpath, &sb) == -1) {
7032 DPRINTF_U(sb.st_mode);
7034 /* Do not open non-regular files */
7035 if (!S_ISREG(sb.st_mode)) {
7036 printwait(messages[MSG_UNSUPPORTED], &presel);
7040 /* Handle plugin selection mode */
7041 if (g_state.runplugin) {
7042 g_state.runplugin = 0;
7043 /* Must be in plugin dir and same context to select plugin */
7044 if ((g_state.runctx == cfg.curctx) && !strcmp(path, plgpath)) {
7045 endselection(FALSE);
7046 /* Copy path so we can return back to earlier dir */
7047 xstrsncpy(path, lastdir, PATH_MAX);
7050 if (chdir(path) == -1
7051 || !run_plugin(&path, pent->name, runfile, &lastname, &lastdir)) {
7052 DPRINTF_S("plugin failed!");
7056 return EXIT_SUCCESS;
7059 xstrsncpy(lastname, runfile, NAME_MAX + 1);
7068 if (g_state.fifomode && (sel == SEL_OPEN)) {
7069 send_to_explorer(&presel); /* Write selection to explorer fifo */
7073 /* If opened as vim plugin and Enter/^M pressed, pick */
7074 if (g_state.picker && (sel == SEL_OPEN)) {
7075 if (nselected == 0) /* Pick if none selected */
7076 appendfpath(newpath, mkpath(path, pent->name, newpath));
7077 return EXIT_SUCCESS;
7080 if (sel == SEL_NAV_IN) {
7081 /* If in listing dir, go to target on `l` or Right on symlink */
7082 if (listpath && S_ISLNK(pent->mode)
7083 && is_prefix(path, listpath, xstrlen(listpath))) {
7084 if (!realpath(pent->name, newpath)) {
7091 if (chdir(newpath) == -1) {
7096 cdprep(lastdir, NULL, path, newpath)
7097 ? (presel = FILTER) : (watch = TRUE);
7098 xstrsncpy(lastname, pent->name, NAME_MAX + 1);
7102 /* Open file disabled on right arrow or `l` */
7108 printwait(messages[MSG_EMPTY_FILE], &presel);
7113 #ifdef FILE_MIME_OPTS
7114 && get_output("file", FILE_MIME_OPTS, newpath, -1, FALSE)
7115 && is_prefix(g_buf, "text/", 5)
7117 /* no MIME option; guess from description instead */
7118 && get_output("file", "-bL", newpath, -1, FALSE)
7119 && strstr(g_buf, "text")
7122 spawn(editor, newpath, NULL, NULL, F_CLI);
7123 if (cfg.filtermode) {
7130 /* Get the extension for regex match */
7131 tmp = xextension(pent->name, pent->nlen - 1);
7133 if (tmp && !pcre_exec(archive_pcre, NULL, tmp,
7134 pent->nlen - (tmp - pent->name) - 1, 0, 0, NULL, 0)) {
7136 if (tmp && !regexec(&archive_re, tmp, 0, NULL, 0)) {
7138 r = get_input(messages[MSG_ARCHIVE_OPTS]);
7141 if (r == 'l' || r == 'x') {
7142 mkpath(path, pent->name, newpath);
7143 if (!handle_archive(newpath, r)) {
7153 if ((r == 'm') && !archive_mount(newpath)) {
7158 if (r == 'x' || r == 'm') {
7160 set_smart_ctx('+', newpath, &path,
7161 ndents ? pdents[cur].name : NULL,
7162 &lastname, &lastdir);
7170 printwait(messages[MSG_INVALID_KEY], &presel);
7175 /* Invoke desktop opener as last resort */
7176 spawn(opener, newpath, NULL, NULL, opener_flags);
7178 /* Move cursor to the next entry if not the last entry */
7179 if (g_state.autonext && cur != ndents - 1)
7180 move_cursor((cur + 1) % ndents, 0);
7181 if (cfg.filtermode) {
7186 case SEL_NEXT: // fallthrough
7187 case SEL_PREV: // fallthrough
7188 case SEL_PGDN: // fallthrough
7189 case SEL_CTRL_D: // fallthrough
7190 case SEL_PGUP: // fallthrough
7191 case SEL_CTRL_U: // fallthrough
7192 case SEL_HOME: // fallthrough
7193 case SEL_END: // fallthrough
7194 case SEL_FIRST: // fallthrough
7198 handle_screen_move(sel);
7201 case SEL_CDHOME: // fallthrough
7202 case SEL_CDBEGIN: // fallthrough
7203 case SEL_CDLAST: // fallthrough
7205 dir = (sel == SEL_CDHOME) ? home
7206 : ((sel == SEL_CDBEGIN) ? ipath
7207 : ((sel == SEL_CDLAST) ? lastdir
7208 : "/" /* SEL_CDROOT */));
7210 if (!dir || !*dir) {
7211 printwait(messages[MSG_NOT_SET], &presel);
7216 if (strcmp(path, dir) == 0) {
7222 dir = lastdir; /* Go to last dir on home/root key repeat */
7225 if (chdir(dir) == -1) {
7230 /* SEL_CDLAST: dir pointing to lastdir */
7231 xstrsncpy(newpath, dir, PATH_MAX); // fallthrough
7233 if (sel == SEL_BMOPEN) {
7234 r = (int)handle_bookmark(mark, newpath);
7236 printwait(messages[r], &presel);
7240 if (g_state.selbm == 1) /* Allow filtering in bookmarks directory */
7242 if (strcmp(path, newpath) == 0)
7246 /* In list mode, retain the last file name to highlight it, if possible */
7247 cdprep(lastdir, listpath && sel == SEL_CDLAST ? NULL : lastname, path, newpath)
7248 ? (presel = FILTER) : (watch = TRUE);
7251 if ((sel == SEL_REMOTE) && !remote_mount(newpath)) {
7256 set_smart_ctx('+', newpath, &path,
7257 ndents ? pdents[cur].name : NULL, &lastname, &lastdir);
7260 case SEL_CYCLE: // fallthrough
7261 case SEL_CYCLER: // fallthrough
7262 case SEL_CTX1: // fallthrough
7263 case SEL_CTX2: // fallthrough
7264 case SEL_CTX3: // fallthrough
7272 r = handle_context_switch(sel);
7275 savecurctx(path, ndents ? pdents[cur].name : NULL, r);
7277 /* Reset the pointers */
7278 path = g_ctx[r].c_path;
7279 lastdir = g_ctx[r].c_last;
7280 lastname = g_ctx[r].c_name;
7281 tmp = g_ctx[r].c_fltr;
7283 if (cfg.filtermode || ((tmp[0] == FILTER || tmp[0] == RFILTER) && tmp[1]))
7291 mark = xstrdup(path);
7292 printwait(mark, &presel);
7295 add_bookmark(path, newpath, &presel);
7298 /* Unwatch dir if we are still in a filtered view */
7299 #ifdef LINUX_INOTIFY
7300 if (inotify_wd >= 0) {
7301 inotify_rm_watch(inotify_fd, inotify_wd);
7304 #elif defined(BSD_KQUEUE)
7305 if (event_fd >= 0) {
7309 #elif defined(HAIKU_NM)
7310 if (haiku_nm_active) {
7311 haiku_stop_watch(haiku_hnd);
7312 haiku_nm_active = FALSE;
7315 presel = filterentries(path, lastname);
7316 if (presel == ESC) {
7320 if (presel == FILTER) { /* Refresh dir and filter again */
7325 case SEL_MFLTR: // fallthrough
7326 case SEL_HIDDEN: // fallthrough
7327 case SEL_DETAIL: // fallthrough
7331 cfg.filtermode ^= 1;
7332 if (cfg.filtermode) {
7338 watch = TRUE; // fallthrough
7340 if (sel == SEL_HIDDEN) {
7341 cfg.showhidden ^= 1;
7350 cfg.showdetail ^= 1;
7353 default: /* SEL_SORT */
7354 r = set_sort_flags(get_input(messages[MSG_ORDER]));
7356 printwait(messages[MSG_INVALID_KEY], &presel);
7361 if (cfg.filtermode || filterset())
7367 if (r == 'd' || r == 'a') {
7372 ENTSORT(pdents, ndents, entrycmpfn);
7373 move_cursor(ndents ? dentfind(lastname, ndents) : 0, 0);
7376 case SEL_STATS: // fallthrough
7379 tmp = (listpath && xstrcmp(path, listpath) == 0) ? listroot : path;
7380 mkpath(tmp, pdents[cur].name, newpath);
7382 if ((sel == SEL_STATS && !show_stats(newpath))
7383 || (lstat(newpath, &sb) == -1)
7384 || (sel == SEL_CHMODX && !xchmod(newpath, sb.st_mode))) {
7389 if (sel == SEL_CHMODX)
7390 pdents[cur].mode ^= 0111;
7393 case SEL_REDRAW: // fallthrough
7394 case SEL_RENAMEMUL: // fallthrough
7395 case SEL_HELP: // fallthrough
7396 case SEL_AUTONEXT: // fallthrough
7397 case SEL_EDIT: // fallthrough
7400 bool refresh = FALSE;
7403 mkpath(path, pdents[cur].name, newpath);
7404 else if (sel == SEL_EDIT) /* Avoid trying to edit a non-existing file */
7413 setenv("NNN_INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
7414 setenv("NNN_PREFER_SELECTION", xitoa(cfg.prefersel), 1);
7415 setenv("NNN_LIST", listpath ? listroot : "", 1);
7417 if (!(getutil(utils[UTIL_BASH])
7418 && plugscript(utils[UTIL_NMV], F_CLI))
7423 printwait(messages[MSG_FAILED], &presel);
7430 show_help(path); // fallthrough
7432 if (sel == SEL_AUTONEXT)
7433 g_state.autonext ^= 1;
7439 if (!(g_state.picker || g_state.fifomode))
7440 spawn(editor, newpath, NULL, NULL, F_CLI);
7442 default: /* SEL_LOCK */
7447 /* In case of successful operation, reload contents */
7449 /* Continue in type-to-nav mode, if enabled */
7450 if ((cfg.filtermode || filterset()) && !refresh) {
7457 /* Repopulate as directory content may have changed */
7466 if (g_state.rangesel)
7467 g_state.rangesel = 0;
7469 /* Toggle selection status */
7470 pdents[cur].flags ^= FILE_SELECTED;
7472 if (pdents[cur].flags & FILE_SELECTED) {
7474 appendfpath(newpath, mkpath(path, pdents[cur].name, newpath));
7475 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
7478 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
7483 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7490 /* move cursor to the next entry if this is not the last entry */
7491 if (!g_state.stayonsel && (cur != ndents - 1))
7492 move_cursor((cur + 1) % ndents, 0);
7499 g_state.rangesel ^= 1;
7501 if (stat(path, &sb) == -1) {
7506 if (g_state.rangesel) { /* Range selection started */
7512 if (inode != sb.st_ino) {
7513 printwait(messages[MSG_DIR_CHANGED], &presel);
7517 if (cur < selstartid) {
7518 selendid = selstartid;
7523 /* Clear selection on repeat on same file */
7524 if (selstartid == selendid) {
7529 case SEL_SELALL: // fallthrough
7531 if (sel == SEL_SELALL || sel == SEL_SELINV) {
7536 if (g_state.rangesel)
7537 g_state.rangesel = 0;
7540 selendid = ndents - 1;
7543 if ((nselected > LARGESEL) || (nselected && (ndents > LARGESEL))) {
7544 printmsg("processing...");
7548 r = scanselforpath(path, TRUE); /* Get path length suffixed by '/' */
7549 ((sel == SEL_SELINV) && findselpos)
7550 ? invertselbuf(r) : addtoselbuf(r, selstartid, selendid);
7554 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7558 r = editselection();
7560 r = !r ? MSG_0_SELECTED : MSG_FAILED;
7561 printwait(messages[r], &presel);
7565 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7567 cfg.filtermode ? presel = FILTER : statusbar(path);
7570 case SEL_CP: // fallthrough
7571 case SEL_MV: // fallthrough
7572 case SEL_CPMVAS: // fallthrough
7575 if (sel == SEL_RM) {
7576 r = get_cur_or_sel();
7583 tmp = (listpath && xstrcmp(path, listpath) == 0)
7585 mkpath(tmp, pdents[cur].name, newpath);
7589 xrmfromsel(tmp, newpath);
7591 copynextname(lastname);
7593 if (cfg.filtermode || filterset())
7600 (nselected == 1 && (sel == SEL_CP || sel == SEL_MV))
7601 ? mkpath(path, xbasename(pselbuf), newpath)
7602 : (newpath[0] = '\0');
7606 if (!cpmvrm_selection(sel, path)) {
7616 /* Show notification on operation complete */
7618 plugscript(utils[UTIL_NTFY], F_NOWAIT | F_NOTRACE);
7621 if (newpath[0] && !access(newpath, F_OK))
7622 xstrsncpy(lastname, xbasename(newpath), NAME_MAX+1);
7628 case SEL_ARCHIVE: // fallthrough
7629 case SEL_OPENWITH: // fallthrough
7630 case SEL_NEW: // fallthrough
7636 if (!ndents && (sel == SEL_OPENWITH || sel == SEL_RENAME))
7639 if (sel != SEL_OPENWITH)
7644 r = get_cur_or_sel();
7658 tmp = pdents[cur].name;
7660 tmp = xreadline(tmp, messages[MSG_ARCHIVE_NAME]);
7664 if (g_state.picker) {
7666 tmp = xreadline(NULL, messages[MSG_OPEN_WITH]);
7669 tmp = getreadline(messages[MSG_OPEN_WITH]);
7674 r = get_input(messages[MSG_NEW_OPTS]);
7680 tmp = g_ctx[0].c_name;
7684 if (r == 'f' || r == 'd')
7685 tmp = xreadline(tmp, messages[MSG_NEW_PATH]);
7686 else if (r == 's' || r == 'h')
7687 tmp = xreadline(NULL,
7688 messages[nselected <= 1 ? MSG_NEW_PATH : MSG_LINK_PREFIX]);
7692 default: /* SEL_RENAME */
7693 tmp = xreadline(pdents[cur].name, "");
7697 if (!tmp || !*tmp || is_bad_len_or_dir(tmp))
7702 if (r == 'c' && strcmp(tmp, pdents[cur].name) == 0)
7703 continue; /* Cannot overwrite the hovered file */
7705 tmp = abspath(tmp, NULL, newpath);
7708 if (access(tmp, F_OK) == 0) {
7709 if (!xconfirm(get_input(messages[MSG_OVERWRITE]))) {
7715 (r == 's') ? archive_selection(get_archive_cmd(tmp), tmp)
7716 : spawn(get_archive_cmd(tmp), tmp, pdents[cur].name,
7717 NULL, F_CLI | F_CONFIRM);
7719 if (tmp && (access(tmp, F_OK) == 0)) { /* File created */
7721 clearselection(); /* Archive operation complete */
7723 /* Check if any entry is created in the current directory */
7724 tmp = get_cwd_entry(path, tmp, &len);
7726 xstrsncpy(lastname, tmp, len + 1);
7727 clearfilter(); /* Archive name may not match */
7728 } if (cfg.filtermode)
7735 handle_openwith(path, pdents[cur].name, newpath, tmp);
7737 cfg.filtermode ? presel = FILTER : statusbar(path);
7742 /* Skip renaming to same name */
7743 if (strcmp(tmp, pdents[cur].name) == 0) {
7744 tmp = xreadline(pdents[cur].name, messages[MSG_COPY_NAME]);
7745 if (!tmp || !tmp[0] || is_bad_len_or_dir(tmp)
7746 || !strcmp(tmp, pdents[cur].name)) {
7747 cfg.filtermode ? presel = FILTER : statusbar(path);
7754 default: /* SEL_NEW */
7758 if (!(r == 's' || r == 'h')) {
7759 tmp = abspath(tmp, NULL, newpath);
7766 /* Check if another file with same name exists */
7767 if (lstat(tmp, &sb) == 0) {
7768 if ((sel == SEL_RENAME) || ((r == 'f') && (S_ISREG(sb.st_mode)))) {
7769 /* Overwrite file with same name? */
7770 if (!xconfirm(get_input(messages[MSG_OVERWRITE])))
7773 /* Do nothing for SEL_NEW if a non-regular entry exists */
7774 printwait(messages[MSG_EXISTS], &presel);
7779 if (sel == SEL_RENAME) {
7780 /* Rename the file */
7782 spawn("cp -rp", pdents[cur].name, tmp, NULL, F_SILENT);
7783 else if (rename(pdents[cur].name, tmp) != 0) {
7788 /* Check if any entry is created in the current directory */
7789 tmp = get_cwd_entry(path, tmp, &len);
7791 xstrsncpy(lastname, tmp, len + 1);
7792 /* Directory must be reloeaded for rename case */
7793 } else { /* SEL_NEW */
7796 /* Check if it's a dir or file */
7797 if (r == 'f' || r == 'd') {
7798 ret = xmktree(tmp, r == 'f' ? FALSE : TRUE);
7799 } else if (r == 's' || r == 'h') {
7800 if (nselected > 1 && tmp[0] == '@' && tmp[1] == '\0')
7802 ret = xlink(tmp, path, (ndents ? pdents[cur].name : NULL), newpath, r);
7811 if (r == 'f' || r == 'd') {
7812 tmp = get_cwd_entry(path, tmp, &len);
7814 xstrsncpy(lastname, tmp, len + 1);
7816 continue; /* No change in directory */
7817 } else if (ndents) {
7829 /* Check if directory is accessible */
7830 if (!xdiraccess(plgpath)) {
7836 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
7837 printkeys(plug, g_buf + r - 1, maxplug);
7839 r = get_input(NULL);
7846 endselection(FALSE);
7847 tmp = get_kv_val(plug, NULL, r, maxplug, NNN_PLUG);
7849 printwait(messages[MSG_INVALID_KEY], &presel);
7853 if (tmp[0] == '-' && tmp[1]) {
7855 r = FALSE; /* Do not refresh dir after completion */
7859 if (!run_plugin(&path, tmp, (ndents ? pdents[cur].name : NULL),
7860 &lastname, &lastdir)) {
7861 printwait(messages[MSG_FAILED], &presel);
7866 return EXIT_SUCCESS;
7871 cfg.filtermode ? presel = FILTER : statusbar(path);
7874 } else { /* 'Return/Enter' enters the plugin directory */
7875 g_state.runplugin ^= 1;
7876 if (!g_state.runplugin) {
7878 * If toggled, and still in the plugin dir,
7879 * switch to original directory
7881 if (strcmp(path, plgpath) == 0) {
7882 xstrsncpy(path, lastdir, PATH_MAX);
7883 xstrsncpy(lastname, runfile, NAME_MAX + 1);
7889 /* Otherwise, initiate choosing plugin again */
7890 g_state.runplugin = 1;
7893 xstrsncpy(lastdir, path, PATH_MAX);
7894 xstrsncpy(path, plgpath, PATH_MAX);
7896 xstrsncpy(runfile, pdents[cur].name, NAME_MAX);
7897 g_state.runctx = cfg.curctx;
7902 if (g_state.runplugin == 1) /* Allow filtering in plugins directory */
7908 case SEL_SHELL: // fallthrough
7909 case SEL_LAUNCH: // fallthrough
7911 r = handle_cmd(sel, newpath);
7913 /* Continue in type-to-nav mode, if enabled */
7923 /* Repopulate as directory content may have changed */
7928 if (!unmount((ndents ? pdents[cur].name : NULL), newpath, &presel, path)) {
7929 if (presel == MSG_ZERO)
7934 /* Dir removed, go to next entry */
7935 copynextname(lastname);
7940 r = get_input(messages[MSG_SSN_OPTS]);
7943 tmp = xreadline(NULL, messages[MSG_SSN_NAME]);
7945 save_session(tmp, &presel);
7946 } else if (r == 'l' || r == 'r') {
7947 if (load_session(NULL, &path, &lastdir, &lastname, r == 'r')) {
7958 cfg.filtermode ? presel = FILTER : statusbar(path);
7961 if (!set_time_type(&presel))
7965 case SEL_QUITCTX: // fallthrough
7966 case SEL_QUITCD: // fallthrough
7969 if (sel == SEL_QUITCTX) {
7970 int ctx = cfg.curctx;
7972 for (r = (ctx - 1) & (CTX_MAX - 1);
7973 (r != ctx) && !g_ctx[r].c_cfg.ctxactive;
7974 r = ((r - 1) & (CTX_MAX - 1))) {
7978 g_ctx[ctx].c_cfg.ctxactive = 0;
7980 /* Switch to next active context */
7981 path = g_ctx[r].c_path;
7982 lastdir = g_ctx[r].c_last;
7983 lastname = g_ctx[r].c_name;
7985 cfg = g_ctx[r].c_cfg;
7991 } else if (!g_state.forcequit) {
7992 for (r = 0; r < CTX_MAX; ++r)
7993 if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
7994 r = get_input(messages[MSG_QUIT_ALL]);
7998 if (!(r == CTX_MAX || xconfirm(r)))
7999 break; // fallthrough
8003 tmp = getenv("NNN_TMPFILE");
8004 if ((sel == SEL_QUITCD) || tmp) {
8005 write_lastdir(path, tmp);
8006 /* ^G is a way to quit picker mode without picking anything */
8007 if ((sel == SEL_QUITCD) && g_state.picker)
8011 if (sel != SEL_QUITERR)
8012 return EXIT_SUCCESS;
8014 if (selbufpos && !g_state.picker) {
8015 /* Pick files to stdout and exit */
8019 return EXIT_SUCCESS;
8022 return EXIT_FAILURE;
8024 if (xlines != LINES || xcols != COLS)
8027 if (idletimeout && idle == idletimeout) {
8028 lock_terminal(); /* Locker */
8034 } /* switch (sel) */
8038 static char *make_tmp_tree(char **paths, ssize_t entries, const char *prefix)
8040 /* tmpdir holds the full path */
8041 /* tmp holds the path without the tmp dir prefix */
8045 ssize_t len = xstrlen(prefix);
8046 char *tmpdir = malloc(PATH_MAX);
8049 DPRINTF_S(strerror(errno));
8053 tmp = tmpdir + tmpfplen - 1;
8054 xstrsncpy(tmpdir, g_tmpfpath, tmpfplen);
8055 xstrsncpy(tmp, "/nnnXXXXXX", 11);
8057 /* Points right after the base tmp dir */
8060 /* handle the case where files are directly under / */
8061 if (!prefix[1] && (prefix[0] == '/'))
8064 if (!mkdtemp(tmpdir)) {
8067 DPRINTF_S(strerror(errno));
8073 for (ssize_t i = 0; i < entries; ++i) {
8077 err = stat(paths[i], &sb);
8078 if (err && errno == ENOENT)
8081 /* Don't copy the common prefix */
8082 xstrsncpy(tmp, paths[i] + len, xstrlen(paths[i]) - len + 1);
8084 /* Get the dir containing the path */
8085 slash = xmemrchr((uchar_t *)tmp, '/', xstrlen(paths[i]) - len);
8089 if (access(tmpdir, F_OK)) /* Create directory if it doesn't exist */
8090 xmktree(tmpdir, TRUE);
8095 if (symlink(paths[i], tmpdir)) {
8096 DPRINTF_S(paths[i]);
8097 DPRINTF_S(strerror(errno));
8101 /* Get the dir in which to start */
8106 static char *load_input(int fd, const char *path)
8108 size_t i, chunk_count = 1, chunk = 512UL * 1024 /* 512 KiB chunk size */, entries = 0;
8109 char *input = malloc(sizeof(char) * chunk), *tmpdir = NULL;
8110 char cwd[PATH_MAX], *next;
8111 size_t offsets[LIST_FILES_MAX];
8112 char **paths = NULL;
8113 ssize_t input_read, total_read = 0, off = 0;
8117 DPRINTF_S(strerror(errno));
8122 if (!getcwd(cwd, PATH_MAX)) {
8127 xstrsncpy(cwd, path, PATH_MAX);
8129 while (chunk_count < LIST_INPUT_MAX / chunk && !msgnum) {
8130 input_read = read(fd, input + total_read, chunk);
8131 if (input_read < 0) {
8135 DPRINTF_S(strerror(errno));
8139 if (input_read == 0)
8142 total_read += input_read;
8144 while (off < total_read) {
8145 next = memchr(input + off, '\0', total_read - off);
8150 if (next - input == off + 1) {
8155 if (entries == LIST_FILES_MAX) {
8156 msgnum = MSG_FILE_LIMIT;
8160 offsets[entries++] = off;
8164 /* We don't need to allocate another chunk */
8165 if (chunk_count > (total_read + chunk - 1) / chunk)
8168 /* We can never need more than one additional chunk */
8170 if (chunk_count > LIST_INPUT_MAX / chunk) {
8171 msgnum = MSG_SIZE_LIMIT;
8175 input = xrealloc(input, chunk_count * chunk);
8180 /* We close fd outside this function. Any extra data is left to the kernel to handle */
8182 if (off != total_read) {
8183 if (entries == LIST_FILES_MAX)
8184 msgnum = MSG_FILE_LIMIT;
8186 offsets[entries++] = off;
8190 DPRINTF_D(total_read);
8191 DPRINTF_D(chunk_count);
8194 msgnum = MSG_0_ENTRIES;
8198 input[total_read] = '\0';
8200 paths = malloc(entries * sizeof(char *));
8204 for (i = 0; i < entries; ++i)
8205 paths[i] = input + offsets[i];
8207 listroot = malloc(sizeof(char) * PATH_MAX);
8212 DPRINTF_S(paths[0]);
8214 for (i = 0; i < entries; ++i) {
8215 if (paths[i][0] == '\n' || selforparent(paths[i])) {
8220 paths[i] = abspath(paths[i], cwd, NULL);
8222 entries = i; // free from the previous entry
8226 DPRINTF_S(paths[i]);
8228 xstrsncpy(g_buf, paths[i], PATH_MAX);
8229 if (!common_prefix(xdirname(g_buf), listroot)) {
8230 entries = i + 1; // free from the current entry
8234 DPRINTF_S(listroot);
8237 DPRINTF_S(listroot);
8240 tmpdir = make_tmp_tree(paths, entries, listroot);
8243 for (i = 0; i < entries; ++i)
8246 if (msgnum) { /* Check if we are past init stage and show msg */
8248 printmsg(messages[msgnum]);
8249 xdelay(XDELAY_INTERVAL_MS << 2);
8251 msg(messages[msgnum]);
8252 usleep(XDELAY_INTERVAL_MS << 2);
8261 static void check_key_collision(void)
8264 bool bitmap[KEY_MAX] = {FALSE};
8266 for (ullong_t i = 0; i < ELEMENTS(bindings); ++i) {
8267 key = bindings[i].sym;
8270 dprintf(STDERR_FILENO, "key collision! [%s]\n", keyname(key));
8276 static void usage(void)
8278 dprintf(STDOUT_FILENO,
8279 "%s: nnn [OPTIONS] [PATH]\n\n"
8280 "The unorthodox terminal file manager.\n\n"
8281 "positional args:\n"
8282 " PATH start dir/file [default: .]\n\n"
8285 " -a auto NNN_FIFO\n"
8287 " -A no dir auto-enter during filter\n"
8288 " -b key open bookmark key (trumps -s/S)\n"
8289 " -B use bsdtar for archives\n"
8290 " -c cli-only NNN_OPENER (trumps -e)\n"
8291 " -C 8-color scheme\n"
8293 " -D dirs in context color\n"
8294 " -e text in $VISUAL/$EDITOR/vi\n"
8295 " -E internal edits in EDITOR\n"
8297 " -f use readline history file\n"
8300 " -F val fifo mode [0:preview 1:explore]\n"
8302 " -g regex filters\n"
8303 " -H show hidden files\n"
8304 " -i show current file info\n"
8305 " -J no auto-advance on selection\n"
8306 " -K detect key collision and exit\n"
8307 " -l val set scroll lines\n"
8308 " -n type-to-nav mode\n"
8309 " -o open files only on Enter\n"
8310 " -p file selection file [-:stdout]\n"
8311 " -P key run plugin key\n"
8312 " -Q no quit confirmation\n"
8313 " -r use advcpmv patched cp, mv\n"
8314 " -R no rollover at edges\n"
8316 " -s name load session by name\n"
8317 " -S persistent session\n"
8319 " -t secs timeout to lock\n"
8320 " -T key sort order [a/d/e/r/s/t/v]\n"
8321 " -u use selection (no prompt)\n"
8323 " -U show user and group\n"
8325 " -V show version\n"
8327 " -x notis, selection sync, xterm title\n"
8330 "v%s\n%s\n", __func__, VERSION, GENERAL_INFO);
8333 static bool setup_config(void)
8336 char *xdgcfg = getenv("XDG_CONFIG_HOME");
8339 /* Set up configuration file paths */
8340 if (xdgcfg && xdgcfg[0]) {
8342 if (tilde_is_home(xdgcfg)) {
8343 r = xstrsncpy(g_buf, home, PATH_MAX);
8344 xstrsncpy(g_buf + r - 1, xdgcfg + 1, PATH_MAX);
8349 if (!xdiraccess(xdgcfg)) {
8354 len = xstrlen(xdgcfg) + xstrlen("/nnn/bookmarks") + 1;
8359 len = xstrlen(home) + xstrlen("/.config/nnn/bookmarks") + 1;
8361 cfgpath = (char *)malloc(len);
8362 plgpath = (char *)malloc(len);
8363 if (!cfgpath || !plgpath) {
8369 xstrsncpy(cfgpath, xdgcfg, len);
8370 r = len - xstrlen("/nnn/bookmarks");
8372 r = xstrsncpy(cfgpath, home, len);
8374 /* Create ~/.config */
8375 xstrsncpy(cfgpath + r - 1, "/.config", len - r);
8377 r += 8; /* length of "/.config" */
8380 /* Create ~/.config/nnn */
8381 xstrsncpy(cfgpath + r - 1, "/nnn", len - r);
8384 /* Create bookmarks, sessions, mounts and plugins directories */
8385 for (r = 0; r < ELEMENTS(toks); ++r) {
8386 mkpath(cfgpath, toks[r], plgpath);
8387 /* The dirs are created on first run, check if they already exist */
8388 if (access(plgpath, F_OK) && !xmktree(plgpath, TRUE)) {
8395 /* Set selection file path */
8396 if (!g_state.picker) {
8397 char *env_sel = xgetenv(env_cfg[NNN_SEL], NULL);
8399 selpath = env_sel ? xstrdup(env_sel)
8400 : (char *)malloc(len + 3); /* Length of "/.config/nnn/.selection" */
8408 r = xstrsncpy(selpath, cfgpath, len + 3);
8409 xstrsncpy(selpath + r - 1, "/.selection", 12);
8417 static bool set_tmp_path(void)
8420 char *path = xdiraccess(tmp) ? tmp : getenv("TMPDIR");
8427 tmpfplen = (uchar_t)xstrsncpy(g_tmpfpath, path, TMP_LEN_MAX);
8428 DPRINTF_S(g_tmpfpath);
8429 DPRINTF_U(tmpfplen);
8434 static void cleanup(void)
8437 if (cfg.x11 && !g_state.picker) {
8438 printf("\033[23;0t"); /* reset terminal window title */
8454 if (g_state.autofifo)
8457 if (g_state.pluginit)
8464 int main(int argc, char *argv[])
8467 char *session = NULL;
8468 int fd, opt, sort = 0, pkey = '\0'; /* Plugin key */
8471 char *middle_click_env = xgetenv(env_cfg[NNN_MCLICK], "\0");
8473 middle_click_key = (middle_click_env[0] == '^' && middle_click_env[1])
8474 ? CONTROL(middle_click_env[1])
8475 : (uchar_t)middle_click_env[0];
8478 const char * const env_opts = xgetenv(env_cfg[NNN_OPTS], NULL);
8479 int env_opts_id = env_opts ? (int)xstrlen(env_opts) : -1;
8481 bool rlhist = FALSE;
8484 while ((opt = (env_opts_id > 0
8485 ? env_opts[--env_opts_id]
8486 : getopt(argc, argv, "aAb:BcCdDeEfF:gHiJKl:nop:P:QrRs:St:T:uUVxh"))) != -1) {
8490 g_state.autofifo = 1;
8497 if (env_opts_id < 0)
8501 g_state.usebsdtar = 1;
8507 g_state.oldcolor = 1;
8528 if (env_opts_id < 0) {
8530 if ((fd < 0) || (fd > 1))
8531 return EXIT_FAILURE;
8532 g_state.fifomode = fd;
8538 filterfn = &visible_re;
8547 g_state.stayonsel = 1;
8550 check_key_collision();
8551 return EXIT_SUCCESS;
8553 if (env_opts_id < 0)
8554 scroll_lines = atoi(optarg);
8563 if (env_opts_id >= 0)
8567 if (!(optarg[0] == '-' && optarg[1] == '\0')) {
8568 fd = open(optarg, O_WRONLY | O_CREAT, 0600);
8571 return EXIT_FAILURE;
8575 selpath = abspath(optarg, NULL, NULL);
8580 if (env_opts_id < 0 && !optarg[1])
8581 pkey = (uchar_t)optarg[0];
8584 g_state.forcequit = 1;
8588 memcpy(cp, PROGRESS_CP, sizeof PROGRESS_CP);
8589 memcpy(mv, PROGRESS_MV, sizeof PROGRESS_MV);
8597 if (env_opts_id < 0)
8601 g_state.prstssn = 1;
8602 if (!session) /* Support named persistent sessions */
8607 if (env_opts_id < 0)
8608 idletimeout = atoi(optarg);
8611 if (env_opts_id < 0)
8612 sort = (uchar_t)optarg[0];
8621 dprintf(STDOUT_FILENO, "%s\n", VERSION);
8622 return EXIT_SUCCESS;
8628 return EXIT_SUCCESS;
8631 return EXIT_FAILURE;
8633 if (env_opts_id == 0)
8642 /* Prefix for temporary files */
8643 if (!set_tmp_path())
8644 return EXIT_FAILURE;
8648 /* Check if we are in path list mode */
8649 if (!isatty(STDIN_FILENO)) {
8650 /* This is the same as listpath */
8651 initpath = load_input(STDIN_FILENO, NULL);
8653 return EXIT_FAILURE;
8655 /* We return to tty */
8656 if (!isatty(STDOUT_FILENO)) {
8657 fd = open(ctermid(NULL), O_RDONLY, 0400);
8658 dup2(fd, STDIN_FILENO);
8661 dup2(STDOUT_FILENO, STDIN_FILENO);
8667 home = getenv("HOME");
8670 return EXIT_FAILURE;
8673 homelen = (uchar_t)xstrlen(home);
8675 if (!setup_config())
8676 return EXIT_FAILURE;
8678 /* Get custom opener, if set */
8679 opener = xgetenv(env_cfg[NNN_OPENER], utils[UTIL_OPENER]);
8682 /* Parse bookmarks string */
8683 if (!parsekvpair(&bookmark, &bmstr, NNN_BMS, &maxbm)) {
8684 msg(env_cfg[NNN_BMS]);
8685 return EXIT_FAILURE;
8688 /* Parse plugins string */
8689 if (!parsekvpair(&plug, &pluginstr, NNN_PLUG, &maxplug)) {
8690 msg(env_cfg[NNN_PLUG]);
8691 return EXIT_FAILURE;
8694 /* Parse order string */
8695 if (!parsekvpair(&order, &orderstr, NNN_ORDER, &maxorder)) {
8696 msg(env_cfg[NNN_ORDER]);
8697 return EXIT_FAILURE;
8701 if (arg) { /* Open a bookmark directly */
8702 if (!arg[1]) /* Bookmarks keys are single char */
8703 initpath = get_kv_val(bookmark, NULL, *arg, maxbm, NNN_BMS);
8706 msg(messages[MSG_INVALID_KEY]);
8707 return EXIT_FAILURE;
8712 } else if (argc == optind) {
8713 /* Start in the current directory */
8714 char *startpath = getenv("PWD");
8716 initpath = startpath ? xstrdup(startpath) : getcwd(NULL, 0);
8719 } else { /* Open a file */
8722 size_t len = xstrlen(arg);
8724 if (len > 7 && is_prefix(arg, "file://", 7)) {
8728 initpath = abspath(arg, NULL, NULL);
8729 DPRINTF_S(initpath);
8732 return EXIT_FAILURE;
8735 /* If the file is hidden, enable hidden option */
8736 if (*xbasename(initpath) == '.')
8740 * If nnn is set as the file manager, applications may try to open
8741 * files by invoking nnn. In that case pass the file path to the
8742 * desktop opener and exit.
8746 if (stat(initpath, &sb) == -1) {
8747 bool dir = (arg[len - 1] == '/');
8750 arg = xbasename(initpath);
8751 initpath = xdirname(initpath);
8753 pkey = CREATE_NEW_KEY; /* Override plugin key */
8754 g_state.initfile = 1;
8756 if (dir || (arg != initpath)) { /* We have a directory */
8757 if (!xdiraccess(initpath) && !xmktree(initpath, TRUE)) {
8758 xerror(); /* Fail if directory cannot be created */
8759 return EXIT_FAILURE;
8761 if (!dir) /* Restore the complete path */
8764 } else if (!S_ISDIR(sb.st_mode))
8765 g_state.initfile = 1;
8772 /* Set archive handling (enveditor used as tmp var) */
8773 enveditor = getenv(env_cfg[NNN_ARCHIVE]);
8775 if (setfilter(&archive_pcre, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8777 if (setfilter(&archive_re, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8779 msg(messages[MSG_INVALID_REG]);
8780 return EXIT_FAILURE;
8783 /* An all-CLI opener overrides option -e) */
8787 /* Get VISUAL/EDITOR */
8788 enveditor = xgetenv(envs[ENV_EDITOR], utils[UTIL_VI]);
8789 editor = xgetenv(envs[ENV_VISUAL], enveditor);
8790 DPRINTF_S(getenv(envs[ENV_VISUAL]));
8791 DPRINTF_S(getenv(envs[ENV_EDITOR]));
8795 pager = xgetenv(envs[ENV_PAGER], utils[UTIL_LESS]);
8799 shell = xgetenv(envs[ENV_SHELL], utils[UTIL_SH]);
8802 DPRINTF_S(getenv("PWD"));
8806 if (g_state.autofifo) {
8807 g_tmpfpath[tmpfplen - 1] = '\0';
8809 size_t r = mkpath(g_tmpfpath, "nnn-fifo.", g_buf);
8811 xstrsncpy(g_buf + r - 1, xitoa(getpid()), PATH_MAX - r);
8812 setenv("NNN_FIFO", g_buf, TRUE);
8815 fifopath = xgetenv("NNN_FIFO", NULL);
8817 if (mkfifo(fifopath, 0600) != 0 && !(errno == EEXIST && access(fifopath, W_OK) == 0)) {
8819 return EXIT_FAILURE;
8822 sigaction(SIGPIPE, &(struct sigaction){.sa_handler = SIG_IGN}, NULL);
8826 #ifdef LINUX_INOTIFY
8827 /* Initialize inotify */
8828 inotify_fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
8829 if (inotify_fd < 0) {
8831 return EXIT_FAILURE;
8833 #elif defined(BSD_KQUEUE)
8837 return EXIT_FAILURE;
8839 #elif defined(HAIKU_NM)
8840 haiku_hnd = haiku_init_nm();
8843 return EXIT_FAILURE;
8847 /* Configure trash preference */
8848 opt = xgetenv_val(env_cfg[NNN_TRASH]);
8849 if (opt && opt <= 2)
8850 g_state.trash = opt;
8852 /* Ignore/handle certain signals */
8853 struct sigaction act = {.sa_handler = sigint_handler};
8855 if (sigaction(SIGINT, &act, NULL) < 0) {
8857 return EXIT_FAILURE;
8860 act.sa_handler = clean_exit_sighandler;
8862 if (sigaction(SIGTERM, &act, NULL) < 0 || sigaction(SIGHUP, &act, NULL) < 0) {
8864 return EXIT_FAILURE;
8867 act.sa_handler = SIG_IGN;
8869 if (sigaction(SIGQUIT, &act, NULL) < 0) {
8871 return EXIT_FAILURE;
8876 setlocale(LC_ALL, "");
8878 tables = pcre_maketables();
8883 #if RL_READLINE_VERSION >= 0x0603
8884 /* readline would overwrite the WINCH signal hook */
8885 rl_change_environment = 0;
8887 /* Bind TAB to cycling */
8888 rl_variable_bind("completion-ignore-case", "on");
8890 rl_bind_key('\t', rl_menu_complete);
8892 rl_bind_key('\t', rl_complete);
8895 mkpath(cfgpath, ".history", g_buf);
8896 read_history(g_buf);
8901 if (cfg.x11 && !g_state.picker) {
8902 /* Save terminal window title */
8903 printf("\033[22;0t");
8905 gethostname(hostname, sizeof(hostname));
8906 hostname[sizeof(hostname) - 1] = '\0';
8911 if (!initcurses(&mask))
8913 if (!initcurses(NULL))
8915 return EXIT_FAILURE;
8918 set_sort_flags(sort);
8920 opt = browse(initpath, session, pkey);
8923 if (session && g_state.prstssn)
8924 save_session(session, NULL);
8928 mousemask(mask, NULL);
8935 mkpath(cfgpath, ".history", g_buf);
8936 write_history(g_buf);
8940 if (g_state.picker) {
8942 fd = selpath ? open(selpath, O_WRONLY | O_CREAT | O_TRUNC, 0600) : STDOUT_FILENO;
8943 if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
8952 /* Remove tmp dir in list mode */
8955 /* Free the regex */
8957 pcre_free(archive_pcre);
8959 regfree(&archive_re);
8962 /* Free the selection buffer */
8965 #ifdef LINUX_INOTIFY
8966 /* Shutdown inotify */
8967 if (inotify_wd >= 0)
8968 inotify_rm_watch(inotify_fd, inotify_wd);
8970 #elif defined(BSD_KQUEUE)
8974 #elif defined(HAIKU_NM)
8975 haiku_close_nm(haiku_hnd);
8979 if (!g_state.fifomode)