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 #define _FILE_OFFSET_BITS 64 /* Support large files on 32-bit glibc */
33 #if defined(__linux__) || defined(MINGW) || defined(__MINGW32__) \
34 || defined(__MINGW64__) || defined(__CYGWIN__)
38 #if defined(__linux__)
39 #include <sys/inotify.h>
42 #if !defined(__GLIBC__)
43 #include <sys/types.h>
46 #include <sys/resource.h>
48 #include <sys/statvfs.h>
49 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
50 #include <sys/types.h>
51 #include <sys/event.h>
54 #elif defined(__HAIKU__)
55 #include "../misc/haiku/haiku_interop.h"
58 #include <sys/sysmacros.h>
62 #ifdef __linux__ /* Fix failure due to mvaddnwstr() */
63 #ifndef NCURSES_WIDECHAR
64 #define NCURSES_WIDECHAR 1
66 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
67 || defined(__APPLE__) || defined(__sun)
68 #ifndef _XOPEN_SOURCE_EXTENDED
69 #define _XOPEN_SOURCE_EXTENDED
72 #ifndef __USE_XOPEN /* Fix wcswidth() failure, ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
87 #include <readline/history.h>
88 #include <readline/readline.h>
103 #include <stdalign.h>
104 #ifndef __USE_XOPEN_EXTENDED
105 #define __USE_XOPEN_EXTENDED 1
111 #ifdef MACOS_BELOW_1012
112 #include "../misc/macos-legacy/mach_gettime.h"
115 #if !defined(alloca) && defined(__GNUC__)
117 * GCC doesn't expand alloca() to __builtin_alloca() in standards mode
118 * (-std=...) and not all standard libraries do or supply it, e.g.
119 * NetBSD/arm64 so explicitly use the builtin.
121 #define alloca(size) __builtin_alloca(size)
127 #if defined(ICONS_IN_TERM) || defined(NERD) || defined(EMOJI)
128 #define ICONS_ENABLED
129 #include ICONS_INCLUDE
130 #include "icons-hash.c"
134 #if defined(ICONS_ENABLED) && defined(__APPLE__)
136 * For some reason, wcswidth returns 2 for certain icons on macOS
137 * leading to duplicated first characters in filenames when navigating.
138 * https://github.com/jarun/nnn/issues/1692
139 * There might be a better way to fix it without requiring a refresh.
141 #define macos_icons_hack() do { clrtoeol(); refresh(); } while(0)
143 #define macos_icons_hack()
150 /* Macro definitions */
151 #define VERSION "4.9"
152 #define GENERAL_INFO "BSD 2-Clause\nhttps://github.com/jarun/nnn"
155 #define SESSIONS_VERSION 1
159 #define S_BLKSIZE 512 /* S_BLKSIZE is missing on Android NDK (Termux) */
163 * NAME_MAX and PATH_MAX may not exist, e.g. with dirent.c_name being a
164 * flexible array on Illumos. Use somewhat accommodating fallback values.
171 #define PATH_MAX 4096
174 #define _ABSSUB(N, M) (((N) <= (M)) ? ((M) - (N)) : ((N) - (M)))
175 #define ELEMENTS(x) (sizeof(x) / sizeof(*(x)))
177 #define MIN(x, y) ((x) < (y) ? (x) : (y))
179 #define MAX(x, y) ((x) > (y) ? (x) : (y))
180 #define ISODD(x) ((x) & 1)
181 #define ISBLANK(x) ((x) == ' ' || (x) == '\t')
182 #define TOUPPER(ch) (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
183 #define TOLOWER(ch) (((ch) >= 'A' && (ch) <= 'Z') ? ((ch) - 'A' + 'a') : (ch))
184 #define ISUPPER_(ch) ((ch) >= 'A' && (ch) <= 'Z')
185 #define ISLOWER_(ch) ((ch) >= 'a' && (ch) <= 'z')
186 #define CMD_LEN_MAX (PATH_MAX + ((NAME_MAX + 1) << 1))
187 #define ALIGN_UP(x, A) ((((x) + (A) - 1) / (A)) * (A))
188 #define READLINE_MAX 256
194 #define PROMPT ">>> "
196 #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
197 #define NAMEBUF_INCR 0x800 /* 64 dir entries at once, avg. 32 chars per file name = 64*32B = 2KB */
198 #define DESCRIPTOR_LEN 32
199 #define _ALIGNMENT 0x10 /* 16-byte alignment */
200 #define _ALIGNMENT_MASK 0xF
201 #define TMP_LEN_MAX 64
202 #define DOT_FILTER_LEN 7
203 #define ASCII_MAX 128
204 #define EXEC_ARGS_MAX 10
205 #define LIST_FILES_MAX (1 << 14) /* Support listing 16K files */
206 #define LIST_INPUT_MAX ((size_t)LIST_FILES_MAX * PATH_MAX)
208 #define COLOR_256 256
209 #define CREATE_NEW_KEY (-1)
212 #define DBLCLK_INTERVAL_NS (400000000)
213 #define XDELAY_INTERVAL_MS (350000) /* 350 ms delay */
222 /* BSDs or Solaris or SunOS */
223 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) || defined(sun) || defined(__sun)
230 /* Large selection threshold */
232 #define LARGESEL 1000
235 #define MIN_DISPLAY_COL (CTX_MAX * 2)
236 #define ARCHIVE_CMD_LEN 16
237 #define BLK_SHIFT_512 9
239 /* Detect hardlinks in du */
240 #define HASH_BITS (0xFFFFFF)
241 #define HASH_OCTETS (HASH_BITS >> 6) /* 2^6 = 64 */
244 #define DIR_OR_DIRLNK 0x01
245 #define HARD_LINK 0x02
246 #define SYM_ORPHAN 0x04
247 #define FILE_MISSING 0x08
248 #define FILE_SELECTED 0x10
249 #define FILE_SCANNED 0x20
250 #define FILE_YOUNG 0x40
252 /* Macros to define process spawn behaviour as flags */
253 #define F_NONE 0x00 /* no flag set */
254 #define F_MULTI 0x01 /* first arg can be combination of args; to be used with F_NORMAL */
255 #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
256 #define F_NOTRACE 0x04 /* suppress stdout and stderr (no traces) */
257 #define F_NORMAL 0x08 /* spawn child process in non-curses regular CLI mode */
258 #define F_CONFIRM 0x10 /* run command - show results before exit (must have F_NORMAL) */
259 #define F_CHKRTN 0x20 /* wait for user prompt if cmd returns failure status */
260 #define F_NOSTDIN 0x40 /* suppress stdin */
261 #define F_PAGE 0x80 /* page output in run-cmd-as-plugin mode */
262 #define F_TTY 0x100 /* Force stdout to go to tty if redirected to a non-tty */
263 #define F_CLI (F_NORMAL | F_MULTI)
264 #define F_SILENT (F_CLI | F_NOTRACE)
266 /* Version compare macros */
268 * states: S_N: normal, S_I: comparing integral part, S_F: comparing
269 * fractional parts, S_Z: idem but with leading Zeroes only
276 /* result_type: VCMP: return diff; VLEN: compare using len_diff/diff */
285 /* TYPE DEFINITIONS */
286 typedef unsigned int uint_t;
287 typedef unsigned char uchar_t;
288 typedef unsigned short ushort_t;
289 typedef unsigned long long ullong_t;
293 /* Directory entry */
294 typedef struct entry {
295 char *name; /* 8 bytes */
296 time_t sec; /* 8 bytes */
297 uint_t nsec; /* 4 bytes (enough to store nanosec) */
298 mode_t mode; /* 4 bytes */
299 off_t size; /* 8 bytes */
301 ullong_t blocks : 40; /* 5 bytes (enough for 512 TiB in 512B blocks allocated) */
302 ullong_t nlen : 16; /* 2 bytes (length of file name) */
303 ullong_t flags : 8; /* 1 byte (flags specific to the file) */
306 uid_t uid; /* 4 bytes */
307 gid_t gid; /* 4 bytes */
311 /* Selection marker */
317 /* Key-value pairs from env */
327 const regex_t *regex;
336 uint_t filtermode : 1; /* Set to enter filter mode */
337 uint_t timeorder : 1; /* Set to sort by time */
338 uint_t sizeorder : 1; /* Set to sort by file size */
339 uint_t apparentsz : 1; /* Set to sort by apparent size (disk usage) */
340 uint_t blkorder : 1; /* Set to sort by blocks used (disk usage) */
341 uint_t extnorder : 1; /* Order by extension */
342 uint_t showhidden : 1; /* Set to show hidden files */
343 uint_t reserved0 : 1;
344 uint_t showdetail : 1; /* Clear to show lesser file info */
345 uint_t ctxactive : 1; /* Context active or not */
346 uint_t reverse : 1; /* Reverse sort */
347 uint_t version : 1; /* Version sort */
348 uint_t reserved1 : 1;
349 /* The following settings are global */
350 uint_t curctx : 3; /* Current context number */
351 uint_t prefersel : 1; /* Prefer selection over current, if exists */
352 uint_t fileinfo : 1; /* Show file information on hover */
353 uint_t nonavopen : 1; /* Open file on right arrow or `l` */
354 uint_t autoenter : 1; /* auto-enter dir in type-to-nav mode */
355 uint_t reserved2 : 1;
356 uint_t useeditor : 1; /* Use VISUAL to open text files */
357 uint_t reserved3 : 3;
358 uint_t regex : 1; /* Use regex filters */
359 uint_t x11 : 1; /* Copy to system clipboard, show notis, xterm title */
360 uint_t timetype : 2; /* Time sort type (0: access, 1: change, 2: modification) */
361 uint_t cliopener : 1; /* All-CLI app opener */
362 uint_t waitedit : 1; /* For ops that can't be detached, used EDITOR */
363 uint_t rollover : 1; /* Roll over at edges */
366 /* Non-persistent program-internal states (alphabeical order) */
368 uint_t autofifo : 1; /* Auto-create NNN_FIFO */
369 uint_t autonext : 1; /* Auto-advance on file open */
370 uint_t dircolor : 1; /* Current status of dir color */
371 uint_t dirctx : 1; /* Show dirs in context color */
372 uint_t duinit : 1; /* Initialize disk usage */
373 uint_t fifomode : 1; /* FIFO notify mode: 0: preview, 1: explorer */
374 uint_t forcequit : 1; /* Do not prompt on quit */
375 uint_t initfile : 1; /* Positional arg is a file */
376 uint_t interrupt : 1; /* Program received an interrupt */
377 uint_t move : 1; /* Move operation */
378 uint_t oldcolor : 1; /* Use older colorscheme */
379 uint_t picked : 1; /* Plugin has picked files */
380 uint_t picker : 1; /* Write selection to user-specified file */
381 uint_t pluginit : 1; /* Plugin framework initialized */
382 uint_t prstssn : 1; /* Persistent session */
383 uint_t rangesel : 1; /* Range selection on */
384 uint_t runctx : 3; /* The context in which plugin is to be run */
385 uint_t runplugin : 1; /* Choose plugin mode */
386 uint_t selbm : 1; /* Select a bookmark from bookmarks directory */
387 uint_t selmode : 1; /* Set when selecting files */
388 uint_t stayonsel : 1; /* Disable auto-advance on selection */
389 uint_t trash : 2; /* Trash method 0: rm -rf, 1: trash-cli, 2: gio trash */
390 uint_t uidgid : 1; /* Show owner and group info */
391 uint_t usebsdtar : 1; /* Use bsdtar as default archive utility */
392 uint_t xprompt : 1; /* Use native prompt instead of readline prompt */
393 uint_t reserved : 4; /* Adjust when adding/removing a field */
396 /* Contexts or workspaces */
398 char c_path[PATH_MAX]; /* Current dir */
399 char c_last[PATH_MAX]; /* Last visited dir */
400 char c_name[NAME_MAX + 1]; /* Current file name */
401 char c_fltr[REGEX_MAX]; /* Current filter */
402 settings c_cfg; /* Current configuration */
403 uint_t color; /* Color code for directories */
409 size_t pathln[CTX_MAX];
410 size_t lastln[CTX_MAX];
411 size_t nameln[CTX_MAX];
412 size_t fltrln[CTX_MAX];
418 /* Configuration, contexts */
419 static settings cfg = {
422 .timetype = 2, /* T_MOD */
426 alignas(max_align_t) static context g_ctx[CTX_MAX];
428 static int ndents, cur, last, curscroll, last_curscroll, total_dents = ENTRY_INCR, scroll_lines = 1;
429 static int nselected;
431 static int fifofd = -1;
433 static time_t gtimesecs;
434 static uint_t idletimeout, selbufpos, selbuflen;
435 static ushort_t xlines, xcols;
436 static ushort_t idle;
437 static uchar_t maxbm, maxplug, maxorder;
438 static uchar_t cfgsort[CTX_MAX + 1];
440 static char *pluginstr;
441 static char *orderstr;
444 static char *enveditor;
448 static char *initpath;
449 static char *cfgpath;
450 static char *selpath;
451 static char *listpath;
452 static char *listroot;
453 static char *plgpath;
454 static char *pnamebuf, *pselbuf, *findselpos;
457 static char hostname[_POSIX_HOST_NAME_MAX + 1];
460 static char *fifopath;
462 static char *lastcmd;
463 static ullong_t *ihashbmp;
464 static struct entry *pdents;
465 static blkcnt_t dir_blocks;
469 static uchar_t tmpfplen, homelen;
470 static uchar_t blk_shift = BLK_SHIFT_512;
472 static int middle_click_key;
475 static pcre *archive_pcre;
477 static regex_t archive_re;
480 /* pthread related */
481 #define NUM_DU_THREADS (4) /* Can use sysconf(_SC_NPROCESSORS_ONLN) */
482 #define DU_TEST (((node->fts_info & FTS_F) && \
483 (sb->st_nlink <= 1 || test_set_bit((uint_t)sb->st_ino))) || node->fts_info & FTS_DP)
485 static int threadbmp = -1; /* Has 1 in the bit position for idle threads */
486 static volatile int active_threads;
487 static pthread_mutex_t running_mutex = PTHREAD_MUTEX_INITIALIZER;
488 static pthread_mutex_t hardlink_mutex = PTHREAD_MUTEX_INITIALIZER;
489 static ullong_t *core_files;
490 static blkcnt_t *core_blocks;
491 static ullong_t num_files;
500 static thread_data *core_data;
502 /* Retain old signal handlers */
503 static struct sigaction oldsighup;
504 static struct sigaction oldsigtstp;
505 static struct sigaction oldsigwinch;
507 /* For use in functions which are isolated and don't return the buffer */
508 alignas(max_align_t) static char g_buf[CMD_LEN_MAX];
510 /* For use as a scratch buffer in selection manipulation */
511 alignas(max_align_t) static char g_sel[PATH_MAX];
513 /* Buffer to store tmp file path to show selection, file stats and help */
514 alignas(max_align_t) static char g_tmpfpath[TMP_LEN_MAX];
516 /* Buffer to store plugins control pipe location */
517 alignas(max_align_t) static char g_pipepath[TMP_LEN_MAX];
519 /* Non-persistent runtime states */
520 static runstate g_state;
522 /* Options to identify file MIME */
523 #if defined(__APPLE__)
524 #define FILE_MIME_OPTS "-bIL"
525 #elif !defined(__sun) /* no MIME option for 'file' */
526 #define FILE_MIME_OPTS "-biL"
529 /* Macros for utilities */
530 #define UTIL_OPENER 0
532 #define UTIL_BSDTAR 2
535 #define UTIL_LOCKER 5
536 #define UTIL_LAUNCH 6
537 #define UTIL_SH_EXEC 7
540 #define UTIL_RCLONE 10
548 #define UTIL_TRASH_CLI 18
549 #define UTIL_GIO_TRASH 19
550 #define UTIL_RM_RF 20
551 #define UTIL_ARCHMNT 21
553 /* Utilities to open files, run actions */
554 static char * const utils[] = {
557 #elif defined __CYGWIN__
559 #elif defined __HAIKU__
570 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
572 #elif defined __HAIKU__
596 #define MSG_ZERO 0 /* Unused */
597 #define MSG_0_ENTRIES 1
598 #define STR_TMPFILE 2
599 #define MSG_0_SELECTED 3
602 #define MSG_SSN_NAME 6
603 #define MSG_CP_MV_AS 7
604 #define MSG_CUR_SEL_OPTS 8
605 #define MSG_FORCE_RM 9
606 #define MSG_SIZE_LIMIT 10
607 #define MSG_NEW_OPTS 11
608 #define MSG_CLI_MODE 12
609 #define MSG_OVERWRITE 13
610 #define MSG_SSN_OPTS 14
611 #define MSG_QUIT_ALL 15
612 #define MSG_HOSTNAME 16
613 #define MSG_ARCHIVE_NAME 17
614 #define MSG_OPEN_WITH 18
615 #define MSG_NEW_PATH 19
616 #define MSG_LINK_PREFIX 20
617 #define MSG_COPY_NAME 21
619 #define MSG_SEL_MISSING 23
620 #define MSG_ACCESS 24
621 #define MSG_EMPTY_FILE 25
622 #define MSG_UNSUPPORTED 26
623 #define MSG_NOT_SET 27
624 #define MSG_EXISTS 28
625 #define MSG_FEW_COLUMNS 29
626 #define MSG_REMOTE_OPTS 30
627 #define MSG_RCLONE_DELAY 31
628 #define MSG_APP_NAME 32
629 #define MSG_ARCHIVE_OPTS 33
631 #define MSG_INVALID_REG 35
635 #define MSG_RM_TMP 39
636 #define MSG_INVALID_KEY 40
637 #define MSG_NOCHANGE 41
638 #define MSG_DIR_CHANGED 42
639 #define MSG_BM_NAME 43
640 #define MSG_FILE_LIMIT 44
642 static const char * const messages[] = {
652 "%s %s? [Esc cancels]",
653 "size limit exceeded",
654 "['f'ile]/'d'ir/'s'ym/'h'ard?",
657 "'s'ave/'l'oad/'r'estore?",
658 "Quit all contexts?",
659 "remote name (- for hovered): ",
660 "archive [path/]name: ",
663 "link prefix [@ for none]: ",
664 "copy [path/]name: ",
665 "\n'Enter' to continue",
668 "empty! edit/open with",
676 "['l's]/'o'pen/e'x'tract/'m'nt?",
679 "'a'u/'d'u/'e'xt/'r'ev/'s'z/'t'm/'v'er/'c'lr/'^T'?",
680 "unmount failed! try lazy?",
681 "first file (\')/char?",
685 "dir changed, range sel off",
687 "file limit exceeded",
690 /* Supported configuration environment variables */
696 #define NNN_FCOLORS 5
701 #define NNN_ARCHIVE 10
703 #define NNN_HELP 12 /* strings end here */
704 #define NNN_TRASH 13 /* flags begin here */
706 static const char * const env_cfg[] = {
723 /* Required environment variables */
730 static const char * const envs[] = {
743 #define PROGRESS_CP "cpg -giRp"
744 #define PROGRESS_MV "mvg -gi"
745 static char cp[sizeof PROGRESS_CP] = "cp -iRp";
746 static char mv[sizeof PROGRESS_MV] = "mv -i";
748 /* Archive commands */
749 static char * const archive_cmd[] = {"atool -a", "bsdtar -acvf", "zip -r", "tar -acvf"};
751 /* Tokens used for path creation */
757 static const char * const toks[] = {
761 "plugins", /* must be the last entry */
769 #define P_ARCHIVE_CMD 4
771 static const char * const patterns[] = {
772 SED" -i 's|^\\(\\(.*/\\)\\(.*\\)$\\)|#\\1\\n\\3|' %s",
773 SED" 's|^\\([^#/][^/]\\?.*\\)$|%s/\\1|;s|^#\\(/.*\\)$|\\1|' "
774 "%s | tr '\\n' '\\0' | xargs -0 -n2 sh -c '%s \"$0\" \"$@\" < /dev/tty'",
775 "\\.(bz|bz2|gz|tar|taz|tbz|tbz2|tgz|z|zip)$", /* Basic formats that don't need external tools */
776 SED" -i 's|^%s\\(.*\\)$|%s\\1|' %s",
777 "xargs -0 %s %s < '%s'",
781 #define C_BLK (CTX_MAX + 1) /* Block device: DarkSeaGreen1 */
782 #define C_CHR (C_BLK + 1) /* Character device: Yellow1 */
783 #define C_DIR (C_CHR + 1) /* Directory: DeepSkyBlue1 */
784 #define C_EXE (C_DIR + 1) /* Executable file: Green1 */
785 #define C_FIL (C_EXE + 1) /* Regular file: Normal */
786 #define C_HRD (C_FIL + 1) /* Hard link: Plum4 */
787 #define C_LNK (C_HRD + 1) /* Symbolic link: Cyan1 */
788 #define C_MIS (C_LNK + 1) /* Missing file OR file details: Grey62 */
789 #define C_ORP (C_MIS + 1) /* Orphaned symlink: DeepPink1 */
790 #define C_PIP (C_ORP + 1) /* Named pipe (FIFO): Orange1 */
791 #define C_SOC (C_PIP + 1) /* Socket: MediumOrchid1 */
792 #define C_UND (C_SOC + 1) /* Unknown OR 0B regular/exe file: Red1 */
794 static char gcolors[] = "c1e2272e006033f7c6d6abc4";
795 static uint_t fcolors[C_UND + 1] = {0};
799 #define NUM_EVENT_SLOTS 32 /* Make room for 32 events */
800 #define EVENT_SIZE (sizeof(struct inotify_event))
801 #define EVENT_BUF_LEN (EVENT_SIZE * NUM_EVENT_SLOTS)
802 static int inotify_fd, inotify_wd = -1;
803 static uint_t INOTIFY_MASK = /* IN_ATTRIB | */ IN_CREATE | IN_DELETE | IN_DELETE_SELF
804 | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
805 #elif defined(BSD_KQUEUE)
806 #define NUM_EVENT_SLOTS 1
807 #define NUM_EVENT_FDS 1
808 static int kq, event_fd = -1;
809 static struct kevent events_to_monitor[NUM_EVENT_FDS];
810 static uint_t KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK
811 | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
812 static struct timespec gtimeout;
813 #elif defined(HAIKU_NM)
814 static bool haiku_nm_active = FALSE;
815 static haiku_nm_h haiku_hnd;
818 /* Function macros */
819 #define tolastln() move(xlines - 1, 0)
820 #define tocursor() move(cur + 2 - curscroll, 0)
821 #define exitcurses() endwin()
822 #define printwarn(presel) printwait(strerror(errno), presel)
823 #define istopdir(path) ((path)[1] == '\0' && (path)[0] == '/')
824 #define copycurname() xstrsncpy(lastname, ndents ? pdents[cur].name : "\0", NAME_MAX + 1)
825 #define settimeout() timeout(1000)
826 #define cleartimeout() timeout(-1)
827 #define errexit() printerr(__LINE__)
828 #define setdirwatch() (cfg.filtermode ? (presel = FILTER) : (watch = TRUE))
829 #define filterset() (g_ctx[cfg.curctx].c_fltr[1])
830 /* We don't care about the return value from strcmp() */
831 #define xstrcmp(a, b) (*(a) != *(b) ? -1 : strcmp((a), (b)))
832 /* A faster version of xisdigit */
833 #define xisdigit(c) ((unsigned int) (c) - '0' <= 9)
834 #define xerror() perror(xitoa(__LINE__))
837 #define ENTLESS(i, j) (entrycmpfn(pdents + (i), pdents + (j)) < 0)
838 #define ENTSWAP(i, j) (swap_ent((i), (j)))
839 #define ENTSORT(pdents, ndents, entrycmpfn) QSORT((ndents), ENTLESS, ENTSWAP)
841 #define ENTSORT(pdents, ndents, entrycmpfn) qsort((pdents), (ndents), sizeof(*(pdents)), (entrycmpfn))
844 /* Forward declarations */
845 static void redraw(char *path);
846 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag);
847 static void move_cursor(int target, int ignore_scrolloff);
848 static char *load_input(int fd, const char *path);
849 static int set_sort_flags(int r);
850 static void statusbar(char *path);
851 static bool get_output(char *file, char *arg1, char *arg2, int fdout, bool page);
853 static void notify_fifo(bool force);
858 static void sigint_handler(int sig)
861 g_state.interrupt = 1;
864 static void clean_exit_sighandler(int sig)
868 /* This triggers cleanup() thanks to atexit() */
872 static char *xitoa(uint_t val)
874 static char dst[32] = {'\0'};
875 static const char digits[201] =
876 "0001020304050607080910111213141516171819"
877 "2021222324252627282930313233343536373839"
878 "4041424344454647484950515253545556575859"
879 "6061626364656667686970717273747576777879"
880 "8081828384858687888990919293949596979899";
881 uint_t next = 30, quo, i;
885 i = (val - (quo * 100)) * 2;
887 dst[next] = digits[i + 1];
888 dst[--next] = digits[i];
892 /* Handle last 1-2 digits */
894 dst[next] = '0' + val;
897 dst[next] = digits[i + 1];
898 dst[--next] = digits[i];
904 /* Return the integer value of a char representing HEX */
905 static uchar_t xchartohex(uchar_t c)
910 if (c >= 'a' && c <= 'f')
913 if (c >= 'A' && c <= 'F')
920 * Source: https://elixir.bootlin.com/linux/latest/source/arch/alpha/include/asm/bitops.h
922 static bool test_set_bit(uint_t nr)
926 pthread_mutex_lock(&hardlink_mutex);
927 ullong_t *m = ((ullong_t *)ihashbmp) + (nr >> 6);
929 if (*m & (1 << (nr & 63))) {
930 pthread_mutex_unlock(&hardlink_mutex);
934 *m |= 1 << (nr & 63);
935 pthread_mutex_unlock(&hardlink_mutex);
941 /* Increase the limit on open file descriptors, if possible */
942 static void max_openfds(void)
946 if (!getrlimit(RLIMIT_NOFILE, &rl))
947 if (rl.rlim_cur < rl.rlim_max) {
948 rl.rlim_cur = rl.rlim_max;
949 setrlimit(RLIMIT_NOFILE, &rl);
955 * Wrapper to realloc()
956 * Frees current memory if realloc() fails and returns NULL.
958 * The *alloc() family returns aligned address: https://man7.org/linux/man-pages/man3/malloc.3.html
960 static void *xrealloc(void *pcur, size_t len)
962 void *pmem = realloc(pcur, len);
971 * Just a safe strncpy(3)
972 * Always null ('\0') terminates if both src and dest are valid pointers.
973 * Returns the number of bytes copied including terminating null byte.
975 static size_t xstrsncpy(char *restrict dst, const char *restrict src, size_t n)
977 char *end = memccpy(dst, src, '\0', n);
980 dst[n - 1] = '\0'; // NOLINT
981 end = dst + n; /* If we return n here, binary size increases due to auto-inlining */
987 static inline size_t xstrlen(const char *restrict s)
989 #if !defined(__GLIBC__)
990 return strlen(s); // NOLINT
992 return (char *)rawmemchr(s, '\0') - s; // NOLINT
996 static char *xstrdup(const char *restrict s)
998 size_t len = xstrlen(s) + 1;
999 char *ptr = malloc(len);
1000 return ptr ? memcpy(ptr, s, len) : NULL;
1003 static bool is_suffix(const char *restrict str, const char *restrict suffix)
1005 if (!str || !suffix)
1008 size_t lenstr = xstrlen(str);
1009 size_t lensuffix = xstrlen(suffix);
1011 if (lensuffix > lenstr)
1014 return (xstrcmp(str + (lenstr - lensuffix), suffix) == 0);
1017 static inline bool is_prefix(const char *restrict str, const char *restrict prefix, size_t len)
1019 return !strncmp(str, prefix, len);
1022 static inline bool is_bad_len_or_dir(const char *restrict path)
1024 size_t len = xstrlen(path);
1026 return ((len >= PATH_MAX) || (path[len - 1] == '/'));
1029 static char *get_cwd_entry(const char *restrict cwdpath, char *entrypath, size_t *tokenlen)
1031 size_t len = xstrlen(cwdpath);
1034 if (!is_prefix(entrypath, cwdpath, len))
1037 entrypath += len + 1; /* Add 1 for trailing / */
1038 end = strchr(entrypath, '/');
1040 *tokenlen = end - entrypath;
1042 *tokenlen = xstrlen(entrypath);
1043 DPRINTF_U(*tokenlen);
1049 * The poor man's implementation of memrchr(3).
1050 * We are only looking for '/' and '.' in this program.
1051 * And we are NOT expecting a '/' at the end.
1052 * Ideally 0 < n <= xstrlen(s).
1054 static void *xmemrchr(uchar_t *restrict s, uchar_t ch, size_t n)
1056 #if defined(__GLIBC__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
1057 return memrchr(s, ch, n);
1063 uchar_t *ptr = s + n;
1074 /* A very simplified implementation, changes path */
1075 static char *xdirname(char *path)
1077 char *base = xmemrchr((uchar_t *)path, '/', xstrlen(path));
1087 static char *xbasename(char *path)
1089 char *base = xmemrchr((uchar_t *)path, '/', xstrlen(path)); // NOLINT
1091 return base ? base + 1 : path;
1094 static inline char *xextension(const char *fname, size_t len)
1096 return xmemrchr((uchar_t *)fname, '.', len);
1101 * One-shot cache for getpwuid/getgrgid. Returns the cached name if the
1102 * provided uid is the same as the previous uid. Returns xitoa(guid) if
1103 * the guid is not found in the password database.
1105 static char *getpwname(uid_t uid)
1107 static uint_t uidcache = UINT_MAX;
1108 static char *namecache;
1110 if (uidcache != uid) {
1111 struct passwd *pw = getpwuid(uid);
1114 namecache = pw ? pw->pw_name : NULL;
1117 return namecache ? namecache : xitoa(uid);
1120 static char *getgrname(gid_t gid)
1122 static uint_t gidcache = UINT_MAX;
1123 static char *grpcache;
1125 if (gidcache != gid) {
1126 struct group *gr = getgrgid(gid);
1129 grpcache = gr ? gr->gr_name : NULL;
1132 return grpcache ? grpcache : xitoa(gid);
1136 static inline bool getutil(char *util)
1138 return spawn("which", util, NULL, NULL, F_NORMAL | F_NOTRACE) == 0;
1141 static inline bool tilde_is_home(const char *s)
1143 return s[0] == '~' && (s[1] == '\0' || s[1] == '/');
1146 static inline bool tilde_is_home_strict(const char *s)
1148 return s[0] == '~' && s[1] == '/';
1152 * Updates out with "dir/name or "/name"
1153 * Returns the number of bytes copied including the terminating NULL byte
1155 * Note: dir and out must be PATH_MAX in length to avoid macOS fault
1157 static size_t mkpath(const char *dir, const char *name, char *out)
1161 /* same rational for being strict as abspath() */
1162 if (tilde_is_home_strict(name)) { //NOLINT
1163 len = xstrsncpy(out, home, PATH_MAX);
1166 } else if (name[0] != '/') { // NOLINT
1167 /* Handle root case */
1168 len = istopdir(dir) ? 1 : xstrsncpy(out, dir, PATH_MAX);
1169 out[len - 1] = '/'; // NOLINT
1171 return (xstrsncpy(out + len, name, PATH_MAX - len) + len);
1174 /* Assumes both the paths passed are directories */
1175 static char *common_prefix(const char *path, char *prefix)
1177 const char *x = path, *y = prefix;
1180 if (!path || !*path || !prefix)
1184 xstrsncpy(prefix, path, PATH_MAX);
1188 while (*x && *y && (*x == *y))
1191 /* Strings are same */
1195 /* Path is shorter */
1196 if (!*x && *y == '/') {
1197 xstrsncpy(prefix, path, y - path);
1201 /* Prefix is shorter */
1202 if (!*y && *x == '/')
1205 /* Shorten prefix */
1206 prefix[y - prefix] = '\0';
1208 sep = xmemrchr((uchar_t *)prefix, '/', y - prefix);
1218 * The library function realpath() resolves symlinks.
1219 * If there's a symlink in file list we want to show the symlink not what it's points to.
1220 * Resolves ./../~ in filepath
1222 static char *abspath(const char *filepath, char *cwd, char *buf)
1224 const char *path = filepath;
1225 bool allocated = FALSE;
1230 /* when dealing with tilde, we need to be strict.
1231 * otherwise a file named "~" can end up expanding to
1232 * $HOME and causing disaster */
1233 if (tilde_is_home_strict(path)) {
1235 path += 2; /* advance 2 bytes past the "~/" */
1236 } else if ((path[0] != '/') && !cwd) {
1237 cwd = getcwd(NULL, 0);
1243 size_t dst_size = 0, src_size = xstrlen(path), cwd_size = cwd ? xstrlen(cwd) : 0;
1244 size_t len = src_size;
1248 * We need to add 2 chars at the end as relative paths may start with:
1250 * no separator (fd .): this needs an additional char for '/'
1252 char *resolved_path = buf ? buf : malloc(src_size + cwd_size + 2);
1254 if (!resolved_path) {
1260 /* Turn relative paths into absolute */
1261 if (path[0] != '/') {
1264 free(resolved_path);
1267 dst_size = xstrsncpy(resolved_path, cwd, cwd_size + 1) - 1;
1271 resolved_path[0] = '\0';
1274 dst = resolved_path + dst_size;
1275 for (const char *next = NULL; next != path + src_size;) {
1276 next = memchr(src, '/', len);
1278 next = path + src_size;
1280 if (next - src == 2 && src[0] == '.' && src[1] == '.') {
1281 if (dst - resolved_path) {
1282 dst = xmemrchr((uchar_t *)resolved_path, '/', dst - resolved_path);
1285 } else if (next - src == 1 && src[0] == '.') {
1287 } else if (next - src) {
1289 xstrsncpy(dst, src, next - src + 1);
1294 len = src_size - (src - path);
1297 if (*resolved_path == '\0') {
1298 resolved_path[0] = '/';
1299 resolved_path[1] = '\0';
1302 if (xstrlen(resolved_path) >= PATH_MAX) {
1304 free(resolved_path);
1310 return resolved_path;
1313 /* finds abspath of link pointed by filepath, taking cwd into account */
1314 static char *bmtarget(const char *filepath, char *cwd, char *buf)
1316 char target[PATH_MAX + 1];
1317 ssize_t n = readlink(filepath, target, PATH_MAX);
1320 return abspath(target, cwd, buf);
1325 /* wraps the argument in single quotes so it can be safely fed to shell */
1326 static bool shell_escape(char *output, size_t outlen, const char *s)
1328 size_t n = xstrlen(s), w = 0;
1331 DPRINTF_S("s == output");
1335 output[w++] = '\''; /* begin single quote */
1336 for (size_t r = 0; r < n; ++r) {
1337 /* potentially too big: 4 for the single quote case, 2 from
1338 * outside the loop */
1339 if (w + 6 >= outlen)
1343 /* the only thing that has special meaning inside single
1344 * quotes are single quotes themselves. */
1346 output[w++] = '\''; /* end single quote */
1347 output[w++] = '\\'; /* put \' so it's treated as literal single quote */
1349 output[w++] = '\''; /* start single quoting again */
1356 output[w++] = '\''; /* end single quote */
1357 output[w++] = '\0'; /* nul terminator */
1361 static bool set_tilde_in_path(char *path)
1363 if (is_prefix(path, home, homelen)) {
1364 home[homelen] = path[homelen - 1];
1365 path[homelen - 1] = '~';
1372 static void reset_tilde_in_path(char *path)
1374 path[homelen - 1] = home[homelen];
1375 home[homelen] = '\0';
1379 static void xterm_cfg(char *path)
1381 if (cfg.x11 && !g_state.picker) {
1382 /* Signal CWD change to terminal */
1383 printf("\033]7;file://%s%s\033\\", hostname, path);
1385 /* Set terminal window title */
1386 bool r = set_tilde_in_path(path);
1388 printf("\033]2;%s\007", r ? &path[homelen - 1] : path);
1392 reset_tilde_in_path(path);
1397 static bool convert_tilde(const char *path, char *buf)
1399 if (tilde_is_home(path)) {
1400 ssize_t len = xstrlen(home);
1401 ssize_t loclen = xstrlen(path);
1403 xstrsncpy(buf, home, len + 1);
1404 xstrsncpy(buf + len, path + 1, loclen);
1410 static int create_tmp_file(void)
1412 xstrsncpy(g_tmpfpath + tmpfplen - 1, messages[STR_TMPFILE], TMP_LEN_MAX - tmpfplen);
1414 int fd = mkstemp(g_tmpfpath);
1417 DPRINTF_S(strerror(errno));
1423 static void msg(const char *message)
1425 dprintf(STDERR_FILENO, "%s\n", message);
1429 static void handle_key_resize(void)
1435 /* Clear the old prompt */
1436 static void clearoldprompt(void)
1439 move(xlines - 2, 0);
1444 handle_key_resize();
1448 /* Messages show up at the bottom */
1449 static inline void printmsg_nc(const char *msg)
1456 static void printmsg(const char *msg)
1458 attron(COLOR_PAIR(cfg.curctx + 1));
1460 attroff(COLOR_PAIR(cfg.curctx + 1));
1463 static void printwait(const char *msg, int *presel)
1469 xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
1473 /* Kill curses and display error before exiting */
1474 static void printerr(int linenum)
1477 perror(xitoa(linenum));
1478 if (!g_state.picker && selpath)
1484 static inline bool xconfirm(int c)
1486 return (c == 'y' || c == 'Y');
1489 static int get_input(const char *prompt)
1500 while (*ch == KEY_RESIZE) {
1514 static bool isselfileempty(void)
1518 return (stat(selpath, &sb) == -1) || (!sb.st_size);
1521 static int get_cur_or_sel(void)
1523 bool sel = (selbufpos || !isselfileempty());
1525 /* Check both local buffer and selection file for external selection */
1526 if (sel && ndents) {
1527 /* If selection is preferred and we have a local selection, return selection.
1528 * Always show the prompt in case of an external selection.
1530 if (cfg.prefersel && selbufpos)
1533 int choice = get_input(messages[MSG_CUR_SEL_OPTS]);
1535 return ((choice == 'c' || choice == 's') ? choice : 0);
1547 static void xdelay(useconds_t delay)
1553 static char confirm_force(bool selection)
1557 snprintf(str, 64, messages[MSG_FORCE_RM],
1558 g_state.trash ? utils[UTIL_GIO_TRASH] + 4 : utils[UTIL_RM_RF],
1559 (selection ? "selected" : "hovered"));
1561 int r = get_input(str);
1564 return '\0'; /* cancel */
1565 if (r == 'y' || r == 'Y')
1566 return 'f'; /* forceful for rm */
1567 return (g_state.trash ? '\0' : 'i'); /* interactive for rm */
1570 /* Writes buflen char(s) from buf to a file */
1571 static void writesel(const char *buf, const size_t buflen)
1576 int fd = open(selpath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
1579 if (write(fd, buf, buflen) != (ssize_t)buflen)
1586 static void appendfpath(const char *path, const size_t len)
1588 if ((selbufpos >= selbuflen) || ((len + 3) > (selbuflen - selbufpos))) {
1589 selbuflen += PATH_MAX;
1590 pselbuf = xrealloc(pselbuf, selbuflen);
1595 selbufpos += xstrsncpy(pselbuf + selbufpos, path, len);
1598 static void selbufrealloc(const size_t alloclen)
1600 if ((selbufpos + alloclen) > selbuflen) {
1601 selbuflen = ALIGN_UP(selbufpos + alloclen, PATH_MAX);
1602 pselbuf = xrealloc(pselbuf, selbuflen);
1608 /* Write selected file paths to fd, linefeed separated */
1609 static size_t seltofile(int fd, uint_t *pcount)
1611 uint_t lastpos, count = 0;
1612 char *pbuf = pselbuf;
1614 ssize_t len, prefixlen = 0, initlen = 0;
1622 lastpos = selbufpos - 1;
1625 prefixlen = (ssize_t)xstrlen(listroot);
1626 initlen = (ssize_t)xstrlen(listpath);
1629 while (pos <= lastpos) {
1631 len = (ssize_t)xstrlen(pbuf);
1633 if (!listpath || !is_prefix(pbuf, listpath, initlen)) {
1634 if (write(fd, pbuf, len) != len)
1637 if (write(fd, listroot, prefixlen) != prefixlen)
1639 if (write(fd, pbuf + initlen, len - initlen) != (len - initlen))
1644 if (pos <= lastpos) {
1645 if (write(fd, "\n", 1) != 1)
1659 /* List selection from selection file (another instance) */
1660 static bool listselfile(void)
1662 if (isselfileempty())
1665 snprintf(g_buf, CMD_LEN_MAX, "tr \'\\0\' \'\\n\' < %s", selpath);
1666 spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CONFIRM);
1671 /* Reset selection indicators */
1672 static void resetselind(void)
1674 for (int r = 0; r < ndents; ++r)
1675 if (pdents[r].flags & FILE_SELECTED)
1676 pdents[r].flags &= ~FILE_SELECTED;
1679 static void startselection(void)
1681 if (!g_state.selmode) {
1682 g_state.selmode = 1;
1693 static void clearselection(void)
1697 g_state.selmode = 0;
1701 static char *findinsel(char *startpos, int len)
1709 char *found = startpos;
1710 size_t buflen = selbufpos - (startpos - pselbuf);
1713 /* memmem(3): not specified in POSIX.1, but present on a number of other systems. */
1714 found = memmem(found, buflen - (found - startpos), g_sel, len);
1717 if (found == startpos || *(found - 1) == '\0')
1719 found += len; /* We found g_sel as a substring of a path, move forward */
1720 if (found >= startpos + buflen)
1725 static int markcmp(const void *va, const void *vb)
1727 const selmark *ma = (selmark*)va;
1728 const selmark *mb = (selmark*)vb;
1730 return ma->startpos - mb->startpos;
1733 /* scanselforpath() must be called before calling this */
1734 static inline void findmarkentry(size_t len, struct entry *dentp)
1736 if (!(dentp->flags & FILE_SCANNED)) {
1737 if (findinsel(findselpos, len + xstrsncpy(g_sel + len, dentp->name, dentp->nlen)))
1738 dentp->flags |= FILE_SELECTED;
1739 dentp->flags |= FILE_SCANNED;
1744 * scanselforpath() must be called before calling this
1745 * pathlen = length of path + 1 (+1 for trailing slash)
1747 static void invertselbuf(const int pathlen)
1749 size_t len, endpos, shrinklen = 0, alloclen = 0;
1750 char * const pbuf = g_sel + pathlen;
1752 int i, nmarked = 0, prev = 0;
1753 struct entry *dentp;
1755 selmark *marked = malloc(nselected * sizeof(selmark));
1762 /* First pass: inversion */
1763 for (i = 0; i < ndents; ++i) {
1766 if (dentp->flags & FILE_SCANNED) {
1767 if (dentp->flags & FILE_SELECTED) {
1768 dentp->flags ^= FILE_SELECTED; /* Clear selection status */
1771 dentp->flags |= FILE_SELECTED;
1772 alloclen += pathlen + dentp->nlen;
1775 dentp->flags |= FILE_SCANNED;
1780 len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1781 found = findinsel(findselpos, len);
1783 if (findselpos == found)
1786 if (nmarked && (found
1787 == (marked[nmarked - 1].startpos + marked[nmarked - 1].len)))
1788 marked[nmarked - 1].len += len;
1790 marked[nmarked].startpos = found;
1791 marked[nmarked].len = len;
1796 shrinklen += len; /* buffer size adjustment */
1798 dentp->flags |= FILE_SELECTED;
1799 alloclen += pathlen + dentp->nlen;
1806 * Files marked for deselection could be found in arbitrary order.
1807 * Sort by appearance in selection buffer.
1808 * With entries sorted we can merge adjacent ones allowing us to
1809 * move them in a single go.
1811 qsort(marked, nmarked, sizeof(selmark), &markcmp);
1813 /* Some files might be adjacent. Merge them into a single entry */
1814 for (i = 1; i < nmarked; ++i) {
1815 if (marked[i].startpos == marked[prev].startpos + marked[prev].len)
1816 marked[prev].len += marked[i].len;
1819 marked[prev].startpos = marked[i].startpos;
1820 marked[prev].len = marked[i].len;
1825 * Number of entries is increased by encountering a non-adjacent entry
1826 * After we finish the loop we should increment it once more.
1829 if (nmarked) /* Make sure there is something to deselect */
1832 /* Using merged entries remove unselected chunks from selection buffer */
1833 for (i = 0; i < nmarked; ++i) {
1835 * found: points to where the current block starts
1836 * variable is recycled from previous for readability
1837 * endpos: points to where the the next block starts
1838 * area between the end of current block (found + len)
1839 * and endpos is selected entries. This is what we are
1842 found = marked[i].startpos;
1843 endpos = (i + 1 == nmarked ? selbufpos : marked[i + 1].startpos - pselbuf);
1844 len = marked[i].len;
1846 /* Move back only selected entries. No selected memory is moved twice */
1847 memmove(found, found + len, endpos - (found + len - pselbuf));
1852 /* Buffer size adjustment */
1853 selbufpos -= shrinklen;
1855 selbufrealloc(alloclen);
1857 /* Second pass: append newly selected to buffer */
1858 for (i = 0; i < ndents; ++i) {
1859 if (pdents[i].flags & FILE_SELECTED) {
1860 len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1861 appendfpath(g_sel, len);
1866 nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1870 * scanselforpath() must be called before calling this
1871 * pathlen = length of path + 1 (+1 for trailing slash)
1873 static void addtoselbuf(const int pathlen, int startid, int endid)
1876 size_t len, alloclen = 0;
1877 struct entry *dentp;
1879 char * const pbuf = g_sel + pathlen;
1881 /* Remember current selection buffer position */
1882 for (i = startid; i <= endid; ++i) {
1886 len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1887 found = findinsel(findselpos, len);
1889 dentp->flags |= (FILE_SCANNED | FILE_SELECTED);
1890 if (found == findselpos) {
1892 if (findselpos == (pselbuf + selbufpos))
1896 alloclen += pathlen + dentp->nlen;
1898 alloclen += pathlen + dentp->nlen;
1901 selbufrealloc(alloclen);
1903 for (i = startid; i <= endid; ++i) {
1904 if (!(pdents[i].flags & FILE_SELECTED)) {
1905 len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1906 appendfpath(g_sel, len);
1908 pdents[i].flags |= (FILE_SCANNED | FILE_SELECTED);
1912 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
1915 /* Removes g_sel from selbuf */
1916 static void rmfromselbuf(size_t len)
1918 char *found = findinsel(findselpos, len);
1922 memmove(found, found + len, selbufpos - (found + len - pselbuf));
1925 nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1928 static int scanselforpath(const char *path, bool getsize)
1930 if (!path[1]) { /* path should always be at least two bytes (including NULL) */
1932 findselpos = pselbuf;
1933 return 1; /* Length of '/' is 1 */
1936 size_t off = xstrsncpy(g_sel, path, PATH_MAX);
1938 g_sel[off - 1] = '/';
1940 * We set findselpos only here. Directories can be listed in arbitrary order.
1941 * This is the best best we can do for remembering position.
1943 findselpos = findinsel(NULL, off);
1947 return (findselpos ? off : 0);
1950 /* Finish selection procedure before an operation */
1951 static void endselection(bool endselmode)
1955 char buf[sizeof(patterns[P_REPLACE]) + PATH_MAX + (TMP_LEN_MAX << 1)];
1957 if (endselmode && g_state.selmode)
1958 g_state.selmode = 0;
1960 /* The code below is only for listing mode */
1961 if (!listpath || !selbufpos)
1964 fd = create_tmp_file();
1966 DPRINTF_S("couldn't create tmp file");
1970 seltofile(fd, NULL);
1972 DPRINTF_S(strerror(errno));
1977 snprintf(buf, sizeof(buf), patterns[P_REPLACE], listpath, listroot, g_tmpfpath);
1978 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
1980 fd = open(g_tmpfpath, O_RDONLY);
1982 DPRINTF_S(strerror(errno));
1984 if (unlink(g_tmpfpath)) {
1985 DPRINTF_S(strerror(errno));
1991 count = read(fd, pselbuf, selbuflen);
1993 DPRINTF_S(strerror(errno));
1995 if (close(fd) || unlink(g_tmpfpath)) {
1996 DPRINTF_S(strerror(errno));
2001 if (close(fd) || unlink(g_tmpfpath)) {
2002 DPRINTF_S(strerror(errno));
2008 pselbuf[--count] = '\0';
2009 for (--count; count > 0; --count)
2010 if (pselbuf[count] == '\n' && pselbuf[count+1] == '/')
2011 pselbuf[count] = '\0';
2013 writesel(pselbuf, selbufpos - 1);
2016 /* Returns: 1 - success, 0 - none selected, -1 - other failure */
2017 static int editselection(void)
2025 if (!selbufpos) /* External selection is only editable at source */
2026 return listselfile();
2028 fd = create_tmp_file();
2030 DPRINTF_S("couldn't create tmp file");
2034 seltofile(fd, NULL);
2036 DPRINTF_S(strerror(errno));
2040 /* Save the last modification time */
2041 if (stat(g_tmpfpath, &sb)) {
2042 DPRINTF_S(strerror(errno));
2046 mtime = sb.st_mtime;
2048 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2050 fd = open(g_tmpfpath, O_RDONLY);
2052 DPRINTF_S(strerror(errno));
2059 if (mtime == sb.st_mtime) {
2060 DPRINTF_S("selection is not modified");
2065 if (sb.st_size > selbufpos) {
2066 DPRINTF_S("edited buffer larger than previous");
2071 count = read(fd, pselbuf, selbuflen);
2073 DPRINTF_S(strerror(errno));
2075 if (close(fd) || unlink(g_tmpfpath)) {
2076 DPRINTF_S(strerror(errno));
2082 if (close(fd) || unlink(g_tmpfpath)) {
2083 DPRINTF_S(strerror(errno));
2095 /* The last character should be '\n' */
2096 pselbuf[--count] = '\0';
2097 for (--count; count > 0; --count) {
2098 /* Replace every '\n' that separates two paths */
2099 if (pselbuf[count] == '\n' && pselbuf[count + 1] == '/') {
2101 pselbuf[count] = '\0';
2105 /* Add a line for the last file */
2108 if (lines > nselected) {
2109 DPRINTF_S("files added to selection");
2114 writesel(pselbuf, selbufpos - 1);
2124 static bool selsafe(void)
2126 /* Fail if selection file path not generated */
2128 printmsg(messages[MSG_SEL_MISSING]);
2132 /* Fail if selection file path isn't accessible */
2133 if (access(selpath, R_OK | W_OK) == -1) {
2134 errno == ENOENT ? printmsg(messages[MSG_0_SELECTED]) : printwarn(NULL);
2141 static void export_file_list(void)
2146 struct entry *pdent = pdents;
2147 int fd = create_tmp_file();
2150 DPRINTF_S(strerror(errno));
2154 for (int r = 0; r < ndents; ++pdent, ++r) {
2155 if (write(fd, pdent->name, pdent->nlen - 1) != (pdent->nlen - 1))
2158 if ((r != ndents - 1) && (write(fd, "\n", 1) != 1))
2163 DPRINTF_S(strerror(errno));
2166 spawn(editor, g_tmpfpath, NULL, NULL, F_CLI);
2168 if (xconfirm(get_input(messages[MSG_RM_TMP])))
2172 static bool init_fcolors(void)
2174 char *f_colors = getenv(env_cfg[NNN_FCOLORS]);
2176 if (!f_colors || !*f_colors)
2179 for (uchar_t id = C_BLK; *f_colors && id <= C_UND; ++id) {
2180 fcolors[id] = xchartohex(*f_colors) << 4;
2182 fcolors[id] += xchartohex(*f_colors);
2184 init_pair(id, fcolors[id], -1);
2193 /* Initialize curses mode */
2194 static bool initcurses(void *oldmask)
2200 if (g_state.picker) {
2201 if (!newterm(NULL, stderr, stdin)) {
2205 } else if (!initscr()) {
2207 DPRINTF_S(getenv("TERM"));
2214 //intrflush(stdscr, FALSE);
2215 keypad(stdscr, TRUE);
2217 #if NCURSES_MOUSE_VERSION <= 1
2218 mousemask(BUTTON1_PRESSED | BUTTON1_DOUBLE_CLICKED | BUTTON2_PRESSED | BUTTON3_PRESSED,
2219 (mmask_t *)oldmask);
2221 mousemask(BUTTON1_PRESSED | BUTTON2_PRESSED | BUTTON3_PRESSED | BUTTON4_PRESSED
2222 | BUTTON5_PRESSED, (mmask_t *)oldmask);
2226 curs_set(FALSE); /* Hide cursor */
2228 char *colors = getenv(env_cfg[NNN_COLORS]);
2230 if (colors || !getenv("NO_COLOR")) {
2235 use_default_colors();
2237 /* Initialize file colors */
2238 if (COLORS >= COLOR_256) {
2239 if (!(g_state.oldcolor || init_fcolors())) {
2241 msg(env_cfg[NNN_FCOLORS]);
2245 g_state.oldcolor = 1;
2248 DPRINTF_D(COLOR_PAIRS);
2250 if (colors && *colors == '#') {
2251 char *sep = strchr(colors, ';');
2253 if (!g_state.oldcolor && COLORS >= COLOR_256) {
2258 * If fallback colors are specified, set the separator
2259 * to NULL so we don't interpret separator and fallback
2260 * if fewer than CTX_MAX xterm 256 colors are specified.
2265 colors = sep; /* Detect if 8 colors fallback is appended */
2271 /* Get and set the context colors */
2272 for (uchar_t i = 0; i < CTX_MAX; ++i) {
2273 pcode = &g_ctx[i].color;
2275 if (colors && *colors) {
2277 *pcode = xchartohex(*colors) << 4;
2279 fcolors[i + 1] = *pcode += xchartohex(*colors);
2280 else { /* Each color code must be 2 hex symbols */
2282 msg(env_cfg[NNN_COLORS]);
2286 *pcode = (*colors < '0' || *colors > '7') ? 4 : *colors - '0';
2291 init_pair(i + 1, *pcode, -1);
2294 #ifdef ICONS_ENABLED
2295 if (!g_state.oldcolor) {
2296 for (uint_t i = 0; i < ELEMENTS(init_colors); ++i)
2297 init_pair(C_UND + 1 + init_colors[i], init_colors[i], -1);
2301 settimeout(); /* One second */
2306 /* No NULL check here as spawn() guards against it */
2307 static char *parseargs(char *cmd, char **argv, int *pindex)
2310 size_t len = xstrlen(cmd) + 1;
2311 char *line = (char *)malloc(len);
2314 DPRINTF_S("malloc()!");
2318 xstrsncpy(line, cmd, len);
2319 argv[count++] = line;
2322 while (*line) { // NOLINT
2323 if (ISBLANK(*line)) {
2326 if (!*line) // NOLINT
2329 argv[count++] = line;
2330 if (count == EXEC_ARGS_MAX) {
2339 if (count == -1 || count > (EXEC_ARGS_MAX - 4)) { /* 3 args and last NULL */
2342 DPRINTF_S("NULL or too many args");
2349 static void enable_signals(void)
2351 struct sigaction dfl_act = {.sa_handler = SIG_DFL};
2353 sigaction(SIGHUP, &dfl_act, NULL);
2354 sigaction(SIGINT, &dfl_act, NULL);
2355 sigaction(SIGQUIT, &dfl_act, NULL);
2356 sigaction(SIGTSTP, &dfl_act, NULL);
2357 sigaction(SIGWINCH, &dfl_act, NULL);
2360 static pid_t xfork(uchar_t flag)
2365 /* the parent ignores the interrupt, quit and hangup signals */
2366 sigaction(SIGHUP, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsighup);
2367 sigaction(SIGTSTP, &(struct sigaction){.sa_handler = SIG_DFL}, &oldsigtstp);
2368 sigaction(SIGWINCH, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsigwinch);
2369 } else if (p == 0) {
2370 /* We create a grandchild to detach */
2371 if (flag & F_NOWAIT) {
2375 _exit(EXIT_SUCCESS);
2383 _exit(EXIT_FAILURE);
2386 /* So they can be used to stop the child */
2390 /* This is the parent waiting for the child to create grandchild */
2391 if (flag & F_NOWAIT)
2392 waitpid(p, NULL, 0);
2399 static int join(pid_t p, uchar_t flag)
2401 int status = 0xFFFF;
2403 if (!(flag & F_NOWAIT)) {
2404 /* wait for the child to exit */
2406 } while (waitpid(p, &status, 0) == -1);
2408 if (WIFEXITED(status)) {
2409 status = WEXITSTATUS(status);
2414 /* restore parent's signal handling */
2415 sigaction(SIGHUP, &oldsighup, NULL);
2416 sigaction(SIGTSTP, &oldsigtstp, NULL);
2417 sigaction(SIGWINCH, &oldsigwinch, NULL);
2423 * Spawns a child process. Behaviour can be controlled using flag.
2424 * Limited to 3 arguments to a program, flag works on bit set.
2426 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag)
2429 int status = 0, retstatus = 0xFFFF;
2430 char *argv[EXEC_ARGS_MAX] = {0};
2433 if (!file || !*file)
2436 /* Swap args if the first arg is NULL and the other 2 aren't */
2437 if (!arg1 && arg2) {
2446 if (flag & F_MULTI) {
2447 cmd = parseargs(file, argv, &status);
2451 argv[status++] = file;
2453 argv[status] = arg1;
2454 argv[++status] = arg2;
2455 argv[++status] = arg3;
2457 if (flag & F_NORMAL)
2462 /* Suppress stdout and stderr */
2463 if (flag & F_NOTRACE) {
2464 int fd = open("/dev/null", O_WRONLY, 0200);
2466 if (flag & F_NOSTDIN)
2467 dup2(fd, STDIN_FILENO);
2468 dup2(fd, STDOUT_FILENO);
2469 dup2(fd, STDERR_FILENO);
2471 } else if (flag & F_TTY) {
2472 /* If stdout has been redirected to a non-tty, force output to tty */
2473 if (!isatty(STDOUT_FILENO)) {
2474 int fd = open(ctermid(NULL), O_WRONLY, 0200);
2475 dup2(fd, STDOUT_FILENO);
2480 execvp(*argv, argv);
2481 _exit(EXIT_SUCCESS);
2483 retstatus = join(pid, flag);
2486 if ((flag & F_CONFIRM) || ((flag & F_CHKRTN) && retstatus)) {
2487 status = write(STDOUT_FILENO, messages[MSG_ENTER], xstrlen(messages[MSG_ENTER]));
2489 while ((read(STDIN_FILENO, &status, 1) > 0) && (status != '\n'));
2492 if (flag & F_NORMAL)
2501 /* Get program name from env var, else return fallback program */
2502 static char *xgetenv(const char * const name, char *fallback)
2504 char *value = getenv(name);
2506 return value && value[0] ? value : fallback;
2509 /* Checks if an env variable is set to 1 */
2510 static inline uint_t xgetenv_val(const char *name)
2512 char *str = getenv(name);
2520 /* Check if a dir exists, IS a dir, and is readable */
2521 static bool xdiraccess(const char *path)
2523 DIR *dirp = opendir(path);
2534 static bool plugscript(const char *plugin, uchar_t flags)
2536 mkpath(plgpath, plugin, g_buf);
2537 if (!access(g_buf, X_OK)) {
2538 spawn(g_buf, NULL, NULL, NULL, flags);
2545 static void opstr(char *buf, char *op)
2547 snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c '%s \"$0\" \"$@\" . < /dev/tty' < %s", op, selpath);
2550 static bool rmmulstr(char *buf)
2552 char r = confirm_force(TRUE);
2557 snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c 'rm -%cr \"$0\" \"$@\" < /dev/tty' < %s",
2560 snprintf(buf, CMD_LEN_MAX, "xargs -0 %s < %s",
2561 utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH], selpath);
2566 /* Returns TRUE if file is removed, else FALSE */
2567 static bool xrm(char * const fpath)
2569 char r = confirm_force(FALSE);
2573 if (!g_state.trash) {
2574 char rm_opts[] = "-ir";
2577 spawn("rm", rm_opts, fpath, NULL, F_NORMAL | F_CHKRTN);
2579 spawn(utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH],
2580 fpath, NULL, NULL, F_NORMAL | F_MULTI);
2582 return (access(fpath, F_OK) == -1); /* File is removed */
2585 static void xrmfromsel(char *path, char *fpath)
2588 bool selected = TRUE;
2591 if ((pdents[cur].flags & DIR_OR_DIRLNK) && scanselforpath(fpath, FALSE))
2593 else if (pdents[cur].flags & FILE_SELECTED) {
2595 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
2601 if (selected && cfg.x11)
2602 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
2606 static uint_t lines_in_file(int fd, char *buf, size_t buflen)
2611 while ((len = read(fd, buf, buflen)) > 0)
2613 count += (buf[--len] == '\n');
2615 /* For all use cases 0 linecount is considered as error */
2616 return ((len < 0) ? 0 : count);
2619 static bool cpmv_rename(int choice, const char *path)
2622 uint_t count = 0, lines = 0;
2624 char *cmd = (choice == 'c' ? cp : mv);
2625 char buf[sizeof(patterns[P_CPMVRNM]) + (MAX(sizeof(cp), sizeof(mv))) + (PATH_MAX << 1)];
2627 fd = create_tmp_file();
2631 /* selsafe() returned TRUE for this to be called */
2633 snprintf(buf, sizeof(buf), "tr '\\0' '\\n' < %s > %s", selpath, g_tmpfpath);
2634 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2636 count = lines_in_file(fd, buf, sizeof(buf));
2640 seltofile(fd, &count);
2644 snprintf(buf, sizeof(buf), patterns[P_CPMVFMT], g_tmpfpath);
2645 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2647 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2649 fd = open(g_tmpfpath, O_RDONLY);
2653 lines = lines_in_file(fd, buf, sizeof(buf));
2656 if (!lines || (2 * count != lines)) {
2657 DPRINTF_S("num mismatch");
2661 snprintf(buf, sizeof(buf), patterns[P_CPMVRNM], path, g_tmpfpath, cmd);
2662 if (!spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CHKRTN))
2671 static bool cpmvrm_selection(enum action sel, char *path)
2675 if (isselfileempty()) {
2678 printmsg(messages[MSG_0_SELECTED]);
2693 r = get_input(messages[MSG_CP_MV_AS]);
2694 if (r != 'c' && r != 'm') {
2695 printmsg(messages[MSG_INVALID_KEY]);
2699 if (!cpmv_rename(r, path)) {
2700 printmsg(messages[MSG_FAILED]);
2704 default: /* SEL_RM */
2705 if (!rmmulstr(g_buf)) {
2706 printmsg(messages[MSG_CANCEL]);
2711 if (sel != SEL_CPMVAS && spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CHKRTN)) {
2712 printmsg(messages[MSG_FAILED]);
2716 /* Clear selection */
2723 static bool batch_rename(void)
2726 uint_t count = 0, lines = 0;
2727 bool dir = FALSE, ret = FALSE;
2728 char foriginal[TMP_LEN_MAX] = {0};
2729 static const char batchrenamecmd[] = "paste -d'\n' %s %s | "SED" 'N; /^\\(.*\\)\\n\\1$/!p;d' | "
2730 "tr '\n' '\\0' | xargs -0 -n2 sh -c 'mv -i \"$0\" \"$@\" <"
2732 char buf[sizeof(batchrenamecmd) + (PATH_MAX << 1)];
2733 int i = get_cur_or_sel();
2738 if (i == 'c') { /* Rename entries in current dir */
2743 fd1 = create_tmp_file();
2747 xstrsncpy(foriginal, g_tmpfpath, xstrlen(g_tmpfpath) + 1);
2749 fd2 = create_tmp_file();
2757 for (i = 0; i < ndents; ++i)
2758 appendfpath(pdents[i].name, NAME_MAX);
2760 seltofile(fd1, &count);
2761 seltofile(fd2, NULL);
2764 if (dir) /* Don't retain dir entries in selection */
2767 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2769 /* Reopen file descriptor to get updated contents */
2770 fd2 = open(g_tmpfpath, O_RDONLY);
2774 lines = lines_in_file(fd2, buf, sizeof(buf));
2777 if (!lines || (count != lines)) {
2778 DPRINTF_S("cannot delete files");
2782 snprintf(buf, sizeof(buf), batchrenamecmd, foriginal, g_tmpfpath);
2783 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2799 static char *get_archive_cmd(const char *archive)
2803 if (!g_state.usebsdtar && getutil(utils[UTIL_ATOOL]))
2805 else if (getutil(utils[UTIL_BSDTAR]))
2807 else if (is_suffix(archive, ".zip"))
2811 return archive_cmd[i];
2814 static void archive_selection(const char *cmd, const char *archive)
2816 char *buf = malloc((xstrlen(patterns[P_ARCHIVE_CMD]) + xstrlen(cmd) + xstrlen(archive)
2817 + xstrlen(selpath)) * sizeof(char));
2819 DPRINTF_S(strerror(errno));
2824 snprintf(buf, CMD_LEN_MAX, patterns[P_ARCHIVE_CMD], cmd, archive, selpath);
2825 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CONFIRM);
2829 static void write_lastdir(const char *curpath, const char *outfile)
2833 xstrsncpy(cfgpath + xstrlen(cfgpath), "/.lastd", 8);
2835 tilde = convert_tilde(outfile, g_buf);
2837 int fd = open(outfile
2838 ? (tilde ? g_buf : outfile)
2839 : cfgpath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
2841 if (fd != -1 && shell_escape(g_buf, sizeof(g_buf), curpath)) {
2842 dprintf(fd, "cd %s", g_buf);
2848 * We assume none of the strings are NULL.
2850 * Let's have the logic to sort numeric names in numeric order.
2851 * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
2853 * If the absolute numeric values are same, we fallback to alphasort.
2855 static int xstricmp(const char * const s1, const char * const s2)
2859 long long v1 = strtoll(s1, &p1, 10);
2860 long long v2 = strtoll(s2, &p2, 10);
2862 /* Check if at least 1 string is numeric */
2863 if (s1 != p1 || s2 != p2) {
2864 /* Handle both pure numeric */
2865 if (s1 != p1 && s2 != p2) {
2873 /* Only first string non-numeric */
2877 /* Only second string non-numeric */
2882 /* Handle 1. all non-numeric and 2. both same numeric value cases */
2884 return strcoll(s1, s2);
2886 return strcasecmp(s1, s2);
2891 * Version comparison
2893 * The code for version compare is a modified version of the GLIBC
2894 * and uClibc implementation of strverscmp(). The source is here:
2895 * https://elixir.bootlin.com/uclibc-ng/latest/source/libc/string/strverscmp.c
2899 * Compare S1 and S2 as strings holding indices/version numbers,
2900 * returning less than, equal to or greater than zero if S1 is less than,
2901 * equal to or greater than S2 (for more info, see the texinfo doc).
2905 static int xstrverscasecmp(const char * const s1, const char * const s2)
2907 const uchar_t *p1 = (const uchar_t *)s1;
2908 const uchar_t *p2 = (const uchar_t *)s2;
2913 * Symbol(s) 0 [1-9] others
2914 * Transition (10) 0 (01) d (00) x
2916 static const uint8_t next_state[] = {
2918 /* S_N */ S_N, S_I, S_Z,
2919 /* S_I */ S_N, S_I, S_I,
2920 /* S_F */ S_N, S_F, S_F,
2921 /* S_Z */ S_N, S_F, S_Z
2924 alignas(max_align_t) static const int8_t result_type[] = {
2925 /* state x/x x/d x/0 d/x d/d d/0 0/x 0/d 0/0 */
2927 /* S_N */ VCMP, VCMP, VCMP, VCMP, VLEN, VCMP, VCMP, VCMP, VCMP,
2928 /* S_I */ VCMP, -1, -1, 1, VLEN, VLEN, 1, VLEN, VLEN,
2929 /* S_F */ VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP,
2930 /* S_Z */ VCMP, 1, 1, -1, VCMP, VCMP, -1, VCMP, VCMP
2941 /* Hint: '0' is a digit too. */
2942 state = S_N + ((c1 == '0') + (xisdigit(c1) != 0));
2944 while ((diff = c1 - c2) == 0) {
2948 state = next_state[state];
2953 state += (c1 == '0') + (xisdigit(c1) != 0);
2956 state = result_type[state * 3 + (((c2 == '0') + (xisdigit(c2) != 0)))]; // NOLINT
2962 while (xisdigit(*p1++))
2963 if (!xisdigit(*p2++))
2965 return xisdigit(*p2) ? -1 : diff;
2971 static int (*namecmpfn)(const char * const s1, const char * const s2) = &xstricmp;
2973 static char * (*fnstrstr)(const char *haystack, const char *needle) = &strcasestr;
2975 static const unsigned char *tables;
2976 static int pcreflags = PCRE_NO_AUTO_CAPTURE | PCRE_EXTENDED | PCRE_CASELESS | PCRE_UTF8;
2978 static int regflags = REG_NOSUB | REG_EXTENDED | REG_ICASE;
2982 static int setfilter(pcre **pcrex, const char *filter)
2984 const char *errstr = NULL;
2987 *pcrex = pcre_compile(filter, pcreflags, &errstr, &erroffset, tables);
2989 return errstr ? -1 : 0;
2992 static int setfilter(regex_t *regex, const char *filter)
2994 return regcomp(regex, filter, regflags);
2998 static int visible_re(const fltrexp_t *fltrexp, const char *fname)
3001 return pcre_exec(fltrexp->pcrex, NULL, fname, xstrlen(fname), 0, 0, NULL, 0) == 0;
3003 return regexec(fltrexp->regex, fname, 0, NULL, 0) == 0;
3007 static int visible_str(const fltrexp_t *fltrexp, const char *fname)
3009 return fnstrstr(fname, fltrexp->str) != NULL;
3012 static int (*filterfn)(const fltrexp_t *fltr, const char *fname) = &visible_str;
3014 static void clearfilter(void)
3016 char * const fltr = g_ctx[cfg.curctx].c_fltr;
3019 fltr[REGEX_MAX - 1] = fltr[1];
3024 static int entrycmp(const void *va, const void *vb)
3026 const struct entry *pa = (pEntry)va;
3027 const struct entry *pb = (pEntry)vb;
3029 if ((pb->flags & DIR_OR_DIRLNK) != (pa->flags & DIR_OR_DIRLNK)) {
3030 if (pb->flags & DIR_OR_DIRLNK)
3035 /* Sort based on specified order */
3036 if (cfg.timeorder) {
3037 if (pb->sec > pa->sec)
3039 if (pb->sec < pa->sec)
3041 /* If sec matches, comare nsec */
3042 if (pb->nsec > pa->nsec)
3044 if (pb->nsec < pa->nsec)
3046 } else if (cfg.sizeorder) {
3047 if (pb->size > pa->size)
3049 if (pb->size < pa->size)
3051 } else if (cfg.blkorder) {
3052 if (pb->blocks > pa->blocks)
3054 if (pb->blocks < pa->blocks)
3056 } else if (cfg.extnorder && !(pb->flags & DIR_OR_DIRLNK)) {
3057 char *extna = xextension(pa->name, pa->nlen - 1);
3058 char *extnb = xextension(pb->name, pb->nlen - 1);
3060 if (extna || extnb) {
3067 int ret = strcasecmp(extna, extnb);
3074 return namecmpfn(pa->name, pb->name);
3077 static int reventrycmp(const void *va, const void *vb)
3079 if ((((pEntry)vb)->flags & DIR_OR_DIRLNK)
3080 != (((pEntry)va)->flags & DIR_OR_DIRLNK)) {
3081 if (((pEntry)vb)->flags & DIR_OR_DIRLNK)
3086 return -entrycmp(va, vb);
3089 static int (*entrycmpfn)(const void *va, const void *vb) = &entrycmp;
3091 /* In case of an error, resets *wch to Esc */
3092 static int handle_alt_key(wint_t *wch)
3096 int r = get_wch(wch);
3105 static inline int handle_event(void)
3107 if (nselected && isselfileempty())
3109 return CONTROL('L');
3113 * Returns SEL_* if key is bound and 0 otherwise.
3114 * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
3115 * The next keyboard input can be simulated by presel.
3117 static int nextsel(int presel)
3124 bool escaped = FALSE;
3126 if (c == 0 || c == MSGWAIT) {
3130 //DPRINTF_S(keyname(c));
3133 if (c == KEY_RESIZE)
3134 handle_key_resize();
3137 /* Handle Alt+key */
3149 } else if (escaped) {
3154 if (!g_state.fifomode)
3155 notify_fifo(TRUE); /* Send hovered path to NNN_FIFO */
3163 if (i == ERR && presel == MSGWAIT)
3164 c = (cfg.filtermode || filterset()) ? FILTER : CONTROL('L');
3165 else if (c == FILTER || c == CONTROL('L'))
3166 /* Clear previous filter when manually starting */
3174 * Do not check for directory changes in du mode.
3175 * A redraw forces du calculation.
3176 * Check for changes every odd second.
3178 #ifdef LINUX_INOTIFY
3179 if (!cfg.blkorder && inotify_wd >= 0 && (idle & 1)) {
3180 struct inotify_event *event;
3181 char inotify_buf[EVENT_BUF_LEN] = {0};
3183 i = read(inotify_fd, inotify_buf, EVENT_BUF_LEN);
3185 for (char *ptr = inotify_buf;
3186 ptr + ((struct inotify_event *)ptr)->len < inotify_buf + i;
3187 ptr += sizeof(struct inotify_event) + event->len) {
3188 event = (struct inotify_event *)ptr;
3189 DPRINTF_D(event->wd);
3190 DPRINTF_D(event->mask);
3194 if (event->mask & INOTIFY_MASK) {
3199 DPRINTF_S("inotify read done");
3202 #elif defined(BSD_KQUEUE)
3203 if (!cfg.blkorder && event_fd >= 0 && (idle & 1)) {
3204 struct kevent event_data[NUM_EVENT_SLOTS] = {0};
3206 if (kevent(kq, events_to_monitor, NUM_EVENT_SLOTS,
3207 event_data, NUM_EVENT_FDS, >imeout) > 0)
3210 #elif defined(HAIKU_NM)
3211 if (!cfg.blkorder && haiku_nm_active && (idle & 1) && haiku_is_update_needed(haiku_hnd))
3217 for (i = 0; i < (int)ELEMENTS(bindings); ++i)
3218 if (c == bindings[i].sym)
3219 return bindings[i].act;
3224 static int getorderstr(char *sort)
3232 sort[i++] = (cfg.timetype == T_MOD) ? 'M' : ((cfg.timetype == T_ACCESS) ? 'A' : 'C');
3233 else if (cfg.sizeorder)
3235 else if (cfg.extnorder)
3238 if (entrycmpfn == &reventrycmp)
3241 if (namecmpfn == &xstrverscasecmp)
3250 static void showfilterinfo(void)
3253 char info[REGEX_MAX] = "\0\0\0\0\0";
3255 i = getorderstr(info);
3257 if (cfg.fileinfo && ndents && get_output("file", "-b", pdents[cur].name, -1, FALSE))
3258 mvaddstr(xlines - 2, 2, g_buf);
3260 snprintf(info + i, REGEX_MAX - i - 1, " %s [/], %4s [:]",
3261 (cfg.regex ? "reg" : "str"),
3262 ((fnstrstr == &strcasestr) ? "ic" : "noic"));
3265 mvaddstr(xlines - 2, xcols - xstrlen(info), info);
3268 static void showfilter(char *str)
3270 attron(COLOR_PAIR(cfg.curctx + 1));
3273 // printmsg calls attroff()
3276 static inline void swap_ent(int id1, int id2)
3278 struct entry _dent, *pdent1 = &pdents[id1], *pdent2 = &pdents[id2];
3280 *(&_dent) = *pdent1;
3282 *pdent2 = *(&_dent);
3286 static int fill(const char *fltr, pcre *pcrex)
3288 static int fill(const char *fltr, regex_t *re)
3292 fltrexp_t fltrexp = { .pcrex = pcrex, .str = fltr };
3294 fltrexp_t fltrexp = { .regex = re, .str = fltr };
3297 for (int count = 0; count < ndents; ++count) {
3298 if (filterfn(&fltrexp, pdents[count].name) == 0) {
3299 if (count != --ndents) {
3300 swap_ent(count, ndents);
3311 static int matches(const char *fltr)
3317 if (cfg.regex && setfilter(&pcrex, fltr))
3320 ndents = fill(fltr, pcrex);
3328 if (cfg.regex && setfilter(&re, fltr))
3331 ndents = fill(fltr, &re);
3337 ENTSORT(pdents, ndents, entrycmpfn);
3343 * Return the position of the matching entry or 0 otherwise
3344 * Note there's no NULL check for fname
3346 static int dentfind(const char *fname, int n)
3348 for (int i = 0; i < n; ++i)
3349 if (xstrcmp(fname, pdents[i].name) == 0)
3355 static int filterentries(char *path, char *lastname)
3357 alignas(max_align_t) wchar_t wln[REGEX_MAX];
3358 char *ln = g_ctx[cfg.curctx].c_fltr;
3360 int r, total = ndents, len;
3361 char *pln = g_ctx[cfg.curctx].c_fltr + 1;
3363 DPRINTF_S(__func__);
3365 if (ndents && (ln[0] == FILTER || ln[0] == RFILTER) && *pln) {
3366 if (matches(pln) != -1) {
3367 move_cursor(dentfind(lastname, ndents), 0);
3371 if (!cfg.filtermode) {
3376 len = mbstowcs(wln, ln, REGEX_MAX);
3378 ln[0] = wln[0] = cfg.regex ? RFILTER : FILTER;
3379 ln[1] = wln[1] = '\0';
3387 while ((r = get_wch(ch)) != ERR) {
3389 //DPRINTF_S(keyname(*ch));
3393 case 0: // fallthrough
3400 case KEY_DC: // fallthrough
3401 case KEY_BACKSPACE: // fallthrough
3402 case '\b': // fallthrough
3403 case DEL: /* handle DEL */
3406 wcstombs(ln, wln, REGEX_MAX);
3414 if (*ch == CONTROL('L')) {
3416 ln[REGEX_MAX - 1] = ln[1];
3417 ln[1] = wln[1] = '\0';
3420 } else if (ln[REGEX_MAX - 1]) { /* Show the previous filter */
3421 ln[1] = ln[REGEX_MAX - 1];
3422 ln[REGEX_MAX - 1] = '\0';
3423 len = mbstowcs(wln, ln, REGEX_MAX);
3428 /* Go to the top, we don't know if the hovered file will match the filter */
3431 if (matches(pln) != -1)
3441 if (handle_alt_key(ch) != ERR) {
3442 if (*ch == ESC) /* Handle Alt+Esc */
3443 *ch = 'q'; /* Quit context */
3446 *ch = ';'; /* Run plugin */
3452 if (r != OK) /* Handle Fn keys in main loop */
3455 /* Handle all control chars in main loop */
3456 if (*ch < ASCII_MAX && keyname(*ch)[0] == '^' && *ch != '^')
3460 if (*ch == '?') /* Help and config key, '?' is an invalid regex */
3463 if (cfg.filtermode) {
3465 case '\'': // fallthrough /* Go to first non-dir file */
3466 case '+': // fallthrough /* Toggle file selection */
3467 case ',': // fallthrough /* Mark CWD */
3468 case '-': // fallthrough /* Visit last visited dir */
3469 case '.': // fallthrough /* Show hidden files */
3470 case ';': // fallthrough /* Run plugin key */
3471 case '=': // fallthrough /* Launch app */
3472 case '>': // fallthrough /* Export file list */
3473 case '@': // fallthrough /* Visit start dir */
3474 case ']': // fallthorugh /* Prompt key */
3475 case '`': // fallthrough /* Visit / */
3476 case '~': /* Go HOME */
3481 /* Toggle case-sensitivity */
3483 fnstrstr = (fnstrstr == &strcasestr) ? &strstr : &strcasestr;
3485 pcreflags ^= PCRE_CASELESS;
3487 regflags ^= REG_ICASE;
3493 /* Toggle string or regex filter */
3494 if (*ch == FILTER) {
3495 ln[0] = (ln[0] == FILTER) ? RFILTER : FILTER;
3496 wln[0] = (uchar_t)ln[0];
3498 filterfn = cfg.regex ? &visible_re : &visible_str;
3503 /* Reset cur in case it's a repeat search */
3505 } else if (len == REGEX_MAX - 1)
3508 wln[len] = (wchar_t)*ch;
3510 wcstombs(ln, wln, REGEX_MAX);
3512 /* Forward-filtering optimization:
3513 * - new matches can only be a subset of current matches.
3515 /* ndents = total; */
3519 !r ? unget_wch(KEY_BACKSPACE) : showfilter(ln);
3521 if (matches(pln) == -1) {
3527 /* If the only match is a dir, auto-enter and cd into it */
3528 if ((ndents == 1) && cfg.autoenter && (pdents[0].flags & DIR_OR_DIRLNK)) {
3535 * redraw() should be above the auto-enter optimization, for
3536 * the case where there's an issue with dir auto-enter, say,
3537 * due to a permission problem. The transition is _jumpy_ in
3538 * case of such an error. However, we optimize for successful
3539 * cases where the dir has permissions. This skips a redraw().
3546 /* Save last working filter in-filter */
3548 ln[REGEX_MAX - 1] = ln[1];
3556 /* Return keys for navigation etc. */
3560 /* Show a prompt with input string and return the changes */
3561 static char *xreadline(const char *prefill, const char *prompt)
3565 const int WCHAR_T_WIDTH = sizeof(wchar_t);
3567 wchar_t * const buf = malloc(sizeof(wchar_t) * READLINE_MAX);
3577 len = pos = mbstowcs(buf, prefill, READLINE_MAX);
3581 if (len == (size_t)-1) {
3586 x = getcurx(stdscr);
3591 attron(COLOR_PAIR(cfg.curctx + 1));
3592 if (pos > (size_t)(xcols - x)) {
3593 mvaddnwstr(xlines - 1, x, buf + (pos - (xcols - x) + 1), xcols - x);
3594 move(xlines - 1, xcols - 1);
3596 mvaddnwstr(xlines - 1, x, buf, len + 1);
3597 move(xlines - 1, x + wcswidth(buf, pos));
3599 attroff(COLOR_PAIR(cfg.curctx + 1));
3607 case KEY_ENTER: // fallthrough
3608 case '\n': // fallthrough
3614 else if (!(pos || len)) { /* Exit on ^D at empty prompt */
3620 case DEL: // fallthrough
3621 case '\b': /* rhel25 sends '\b' for backspace */
3623 memmove(buf + pos - 1, buf + pos,
3624 (len - pos) * WCHAR_T_WIDTH);
3629 if (!(len || pos) && ndents)
3630 len = pos = mbstowcs(buf, pdents[cur].name, READLINE_MAX);
3645 memmove(buf + pos - 1, buf + pos,
3646 (len - pos) * WCHAR_T_WIDTH);
3648 } while (buf[pos - 1] != ' ' && buf[pos - 1] != '/'); // NOLINT
3666 memmove(buf, buf + pos, (len - pos) * WCHAR_T_WIDTH);
3670 case ESC: /* Exit prompt on Esc, but just filter out Alt+key */
3671 if (handle_alt_key(ch) != ERR)
3678 /* Filter out all other control chars */
3679 if (*ch < ASCII_MAX && keyname(*ch)[0] == '^')
3682 if (pos < READLINE_MAX - 1) {
3683 memmove(buf + pos + 1, buf + pos,
3684 (len - pos) * WCHAR_T_WIDTH);
3708 memmove(buf + pos - 1, buf + pos,
3709 (len - pos) * WCHAR_T_WIDTH);
3715 memmove(buf + pos, buf + pos + 1,
3716 (len - pos - 1) * WCHAR_T_WIDTH);
3726 case KEY_UP: // fallthrough
3728 if (prompt && lastcmd && (xstrcmp(prompt, PROMPT) == 0)) {
3730 len = pos = mbstowcs(buf, lastcmd, READLINE_MAX); // fallthrough
3745 pos = wcstombs(g_buf, buf, READLINE_MAX - 1);
3746 if (pos >= READLINE_MAX - 1)
3747 g_buf[READLINE_MAX - 1] = '\0';
3755 * Caller should check the value of presel to confirm if it needs to wait to show warning
3757 static char *getreadline(const char *prompt)
3761 char *input = readline(prompt);
3765 if (input && input[0]) {
3767 xstrsncpy(g_buf, input, CMD_LEN_MAX);
3778 * Create symbolic/hard link(s) to file(s) in selection list
3779 * Returns the number of links created, -1 on error
3781 static int xlink(char *prefix, char *path, char *curfname, char *buf, int type)
3783 int count = 0, choice;
3784 char *psel = pselbuf, *fname;
3785 size_t pos = 0, len, r;
3786 int (*link_fn)(const char *, const char *) = NULL;
3787 char lnpath[PATH_MAX];
3789 choice = get_cur_or_sel();
3793 if (type == 's') /* symbolic link */
3795 else /* hard link */
3798 if (choice == 'c' || (nselected == 1)) {
3799 prefix = abspath(prefix, path, lnpath); /* Generate link path */
3804 mkpath(path, curfname, buf); /* Generate target file path */
3806 if (!link_fn((choice == 'c') ? buf : pselbuf, lnpath)) {
3809 return 1; /* One link created */
3814 r = xstrsncpy(buf, prefix, NAME_MAX + 1); /* Copy prefix */
3816 while (pos < selbufpos) {
3817 len = xstrlen(psel);
3818 fname = xbasename(psel);
3820 xstrsncpy(buf + r - 1, fname, NAME_MAX - r); /* Suffix target file name */
3821 mkpath(path, buf, lnpath); /* Generate link path */
3823 if (!link_fn(psel, lnpath))
3830 if (count == nselected) /* Clear selection if all links are generated */
3835 static bool parsekvpair(kv **arr, char **envcpy, const uchar_t id, uchar_t *items)
3838 const uchar_t INCR = 8;
3841 char *ptr = getenv(env_cfg[id]);
3846 *envcpy = xstrdup(ptr);
3854 while (*ptr && i < 100) {
3856 if (!(i & (INCR - 1))) {
3857 kvarr = xrealloc(kvarr, sizeof(kv) * (i + INCR));
3863 memset(kvarr + i, 0, sizeof(kv) * INCR);
3865 kvarr[i].key = (uchar_t)*ptr;
3866 if (*++ptr != ':' || *++ptr == '\0' || *ptr == ';')
3868 kvarr[i].off = ptr - *envcpy;
3887 * Get the value corresponding to a key
3889 * NULL is returned in case of no match, path resolution failure etc.
3890 * buf would be modified, so check return value before access
3892 static char *get_kv_val(kv *kvarr, char *buf, int key, uchar_t max, uchar_t id)
3899 for (int r = 0; r < max && kvarr[r].key; ++r) {
3900 if (kvarr[r].key == key) {
3901 /* Do not allocate new memory for plugin */
3903 return pluginstr + kvarr[r].off;
3905 val = bmstr + kvarr[r].off;
3906 bool tilde = convert_tilde(val, g_buf);
3907 return abspath((tilde ? g_buf : val), NULL, buf);
3911 DPRINTF_S("Invalid key");
3915 static int get_kv_key(kv *kvarr, char *val, uchar_t max, uchar_t id)
3920 if (id != NNN_ORDER) /* For now this function supports only order string */
3923 for (int r = 0; r < max && kvarr[r].key; ++r) {
3924 if (xstrcmp((orderstr + kvarr[r].off), val) == 0)
3925 return kvarr[r].key;
3931 static void resetdircolor(int flags)
3933 /* Directories are always shown on top, clear the color when moving to first file */
3934 if (g_state.dircolor && !(flags & DIR_OR_DIRLNK)) {
3935 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
3936 g_state.dircolor = 0;
3941 * Replace escape characters in a string with '?'
3942 * Adjust string length to maxcols if > 0;
3943 * Max supported str length: NAME_MAX;
3946 static char *unescape(const char *str, uint_t maxcols)
3948 char * const wbuf = g_buf;
3951 xstrsncpy(wbuf, str, maxcols);
3953 static wchar_t *unescape(const char *str, uint_t maxcols)
3955 wchar_t * const wbuf = (wchar_t *)g_buf;
3956 wchar_t *buf = wbuf;
3957 size_t len = mbstowcs(wbuf, str, maxcols); /* Convert multi-byte to wide char */
3959 len = wcswidth(wbuf, len);
3961 if (len >= maxcols) {
3962 size_t lencount = maxcols;
3964 while (len > maxcols) /* Reduce wide chars one by one till it fits */
3965 len = wcswidth(wbuf, --lencount);
3967 wbuf[lencount] = L'\0';
3972 if (*buf <= '\x1f' || *buf == '\x7f')
3981 static off_t get_size(off_t size, off_t *pval, int comp)
3984 off_t quo = rem / 10;
3986 if ((rem - (quo * 10)) >= 5) {
3999 static char *coolsize(off_t size)
4001 const char * const U = "BKMGTPEZY";
4002 static char size_buf[12]; /* Buffer to hold human readable size */
4007 while (size >= 1024) {
4008 rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
4014 rem = (rem * 1000) >> 10;
4016 size = get_size(size, &rem, 10);
4017 } else if (i == 2) {
4018 rem = (rem * 1000) >> 10;
4019 size = get_size(size, &rem, 100);
4021 rem = (rem * 10000) >> 10;
4022 size = get_size(size, &rem, 1000);
4025 if (i > 0 && i < 6 && rem) {
4026 ret = xstrsncpy(size_buf, xitoa(size), 12);
4027 size_buf[ret - 1] = '.';
4029 char *frac = xitoa(rem);
4030 size_t toprint = i > 3 ? 3 : i;
4031 size_t len = xstrlen(frac);
4033 if (len < toprint) {
4034 size_buf[ret] = size_buf[ret + 1] = size_buf[ret + 2] = '0';
4035 xstrsncpy(size_buf + ret + (toprint - len), frac, len + 1);
4037 xstrsncpy(size_buf + ret, frac, toprint + 1);
4041 ret = xstrsncpy(size_buf, size ? xitoa(size) : "0", 12);
4045 size_buf[ret] = U[i];
4046 size_buf[ret + 1] = '\0';
4051 /* Convert a mode field into "ls -l" type perms field. */
4052 static char *get_lsperms(mode_t mode)
4054 static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
4055 static char bits[11] = {'\0'};
4057 switch (mode & S_IFMT) {
4084 xstrsncpy(&bits[1], rwx[(mode >> 6) & 7], 4);
4085 xstrsncpy(&bits[4], rwx[(mode >> 3) & 7], 4);
4086 xstrsncpy(&bits[7], rwx[(mode & 7)], 4);
4089 bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
4091 bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
4093 bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
4098 #ifdef ICONS_ENABLED
4099 static struct icon get_icon(const struct entry *ent)
4101 for (size_t i = 0; i < ELEMENTS(icons_name); ++i)
4102 if (strcasecmp(ent->name, icons_name[i].match) == 0)
4103 return (struct icon){ icons_name[i].icon, icons_name[i].color };
4105 if (ent->flags & DIR_OR_DIRLNK)
4108 char *tmp = xextension(ent->name, ent->nlen);
4111 uint16_t z, k, h = icon_ext_hash(++tmp); /* ++tmp to skip '.' */
4112 for (k = 0; k < ICONS_PROBE_MAX; ++k) {
4113 z = (h + k) % ELEMENTS(icons_ext);
4114 if (strcasecmp(tmp, icons_ext[z].match) == 0)
4115 return (struct icon){ icons_ext_uniq[icons_ext[z].idx], icons_ext[z].color };
4119 /* If there's no match and the file is executable, icon that */
4120 if (ent->mode & 0100)
4125 static void print_icon(const struct entry *ent, const int attrs)
4127 const struct icon icon = get_icon(ent);
4128 addstr(ICON_PADDING_LEFT);
4130 attron(COLOR_PAIR(C_UND + 1 + icon.color));
4135 attroff(COLOR_PAIR(C_UND + 1 + icon.color));
4138 addstr(ICON_PADDING_RIGHT);
4142 static void print_time(const time_t *timep, const uchar_t flags)
4146 /* Highlight timestamp for entries 5 minutes young */
4147 if (flags & FILE_YOUNG)
4150 localtime_r(timep, &t);
4151 printw("%s-%02d-%02d %02d:%02d",
4152 xitoa(t.tm_year + 1900), t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min);
4154 if (flags & FILE_YOUNG)
4158 static char get_detail_ind(const mode_t mode)
4160 switch (mode & S_IFMT) {
4161 case S_IFDIR: // fallthrough
4162 case S_IFREG: return ' ';
4163 case S_IFLNK: return '@';
4164 case S_IFSOCK: return '=';
4165 case S_IFIFO: return '|';
4166 case S_IFBLK: return 'b';
4167 case S_IFCHR: return 'c';
4172 /* Note: attribute and indicator values must be initialized to 0 */
4173 static uchar_t get_color_pair_name_ind(const struct entry *ent, char *pind, int *pattr)
4175 switch (ent->mode & S_IFMT) {
4178 if (ent->mode & 0100)
4182 if (ent->flags & HARD_LINK) {
4183 if (ent->mode & 0100)
4187 if (ent->mode & 0100) {
4194 if (g_state.oldcolor)
4197 return g_state.dirctx ? cfg.curctx + 1 : C_DIR;
4199 if (ent->flags & DIR_OR_DIRLNK) {
4201 *pattr |= g_state.oldcolor ? A_DIM : A_BOLD;
4204 if (g_state.oldcolor)
4207 if (!g_state.oldcolor || cfg.showdetail)
4208 return (ent->flags & SYM_ORPHAN) ? C_ORP : C_LNK;
4226 static void printent(const struct entry *ent, uint_t namecols, bool sel)
4231 if (cfg.showdetail) {
4232 int type = ent->mode & S_IFMT;
4233 char perms[6] = {' ', ' ', (char)('0' + ((ent->mode >> 6) & 7)),
4234 (char)('0' + ((ent->mode >> 3) & 7)),
4235 (char)('0' + (ent->mode & 7)), '\0'};
4238 attrs = g_state.oldcolor ? (resetdircolor(ent->flags), A_DIM)
4239 : (fcolors[C_MIS] ? COLOR_PAIR(C_MIS) : 0);
4244 print_time(&ent->sec, ent->flags);
4246 printw("%s%9s ", perms, (type == S_IFREG || type == S_IFDIR)
4247 ? coolsize(cfg.blkorder ? (blkcnt_t)ent->blocks << blk_shift : ent->size)
4248 : (type = (uchar_t)get_detail_ind(ent->mode), (char *)&type));
4256 uchar_t color_pair = get_color_pair_name_ind(ent, &ind, &attrs);
4258 addch((ent->flags & FILE_SELECTED) ? '+' | A_REVERSE | A_BOLD : ' ');
4260 if (g_state.oldcolor)
4261 resetdircolor(ent->flags);
4263 if (ent->flags & FILE_MISSING)
4265 if (color_pair && fcolors[color_pair])
4266 attrs |= COLOR_PAIR(color_pair);
4267 #ifdef ICONS_ENABLED
4268 print_icon(ent, attrs);
4280 addwstr(unescape(ent->name, namecols));
4282 addstr(unescape(ent->name, MIN(namecols, ent->nlen) + 1));
4292 * Sets the global cfg variable and restores related state to match the new
4295 static void setcfg(settings newcfg)
4298 /* Synchronize the global function pointers to match the new cfg. */
4299 entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
4300 namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
4303 static void savecurctx(char *path, char *curname, int nextctx)
4305 settings tmpcfg = cfg;
4306 context *ctxr = &g_ctx[nextctx];
4308 /* Save current context */
4310 xstrsncpy(g_ctx[tmpcfg.curctx].c_name, curname, NAME_MAX + 1);
4312 g_ctx[tmpcfg.curctx].c_name[0] = '\0';
4314 g_ctx[tmpcfg.curctx].c_cfg = tmpcfg;
4316 if (ctxr->c_cfg.ctxactive) { /* Switch to saved context */
4317 tmpcfg = ctxr->c_cfg;
4318 /* Skip ordering an open context */
4320 cfgsort[CTX_MAX] = cfgsort[nextctx];
4321 cfgsort[nextctx] = '0';
4323 } else { /* Set up a new context from current context */
4324 ctxr->c_cfg.ctxactive = 1;
4325 xstrsncpy(ctxr->c_path, path, PATH_MAX);
4326 ctxr->c_last[0] = ctxr->c_name[0] = ctxr->c_fltr[0] = ctxr->c_fltr[1] = '\0';
4327 ctxr->c_cfg = tmpcfg;
4328 /* If already in an ordered dir, clear ordering for the new context and let it order */
4329 if (cfgsort[cfg.curctx] == 'z')
4330 cfgsort[nextctx] = 'z';
4333 tmpcfg.curctx = nextctx;
4338 static void save_session(const char *sname, int *presel)
4341 session_header_t header = {0};
4342 bool status = FALSE;
4343 char ssnpath[PATH_MAX];
4344 char spath[PATH_MAX];
4346 header.ver = SESSIONS_VERSION;
4348 for (i = 0; i < CTX_MAX; ++i) {
4349 if (g_ctx[i].c_cfg.ctxactive) {
4350 if (cfg.curctx == i && ndents)
4351 /* Update current file name, arrows don't update it */
4352 xstrsncpy(g_ctx[i].c_name, pdents[cur].name, NAME_MAX + 1);
4353 header.pathln[i] = MIN(xstrlen(g_ctx[i].c_path), PATH_MAX) + 1;
4354 header.lastln[i] = MIN(xstrlen(g_ctx[i].c_last), PATH_MAX) + 1;
4355 header.nameln[i] = MIN(xstrlen(g_ctx[i].c_name), NAME_MAX) + 1;
4356 header.fltrln[i] = REGEX_MAX;
4360 mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4361 mkpath(ssnpath, sname, spath);
4363 fd = open(spath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
4365 printwait(messages[MSG_SEL_MISSING], presel);
4369 if ((write(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4370 || (write(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4373 for (i = 0; i < CTX_MAX; ++i)
4374 if ((write(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4375 || (write(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4376 || (header.nameln[i] > 0
4377 && write(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4378 || (header.lastln[i] > 0
4379 && write(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4380 || (header.fltrln[i] > 0
4381 && write(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4382 || (header.pathln[i] > 0
4383 && write(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4392 printwait(messages[MSG_FAILED], presel);
4395 static bool load_session(const char *sname, char **path, char **lastdir, char **lastname, bool restore)
4398 session_header_t header;
4399 bool has_loaded_dynamically = !(sname || restore);
4400 bool status = (sname && g_state.picker); /* Picker mode with session program option */
4401 char ssnpath[PATH_MAX];
4402 char spath[PATH_MAX];
4404 mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4407 sname = sname ? sname : xreadline(NULL, messages[MSG_SSN_NAME]);
4411 mkpath(ssnpath, sname, spath);
4413 /* If user is explicitly loading the "last session", skip auto-save */
4414 if ((sname[0] == '@') && !sname[1])
4415 has_loaded_dynamically = FALSE;
4417 mkpath(ssnpath, "@", spath);
4419 if (has_loaded_dynamically)
4420 save_session("@", NULL);
4422 fd = open(spath, O_RDONLY, S_IWUSR | S_IRUSR);
4425 printmsg(messages[MSG_SEL_MISSING]);
4426 xdelay(XDELAY_INTERVAL_MS);
4433 if ((read(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4434 || (header.ver != SESSIONS_VERSION)
4435 || (read(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4438 g_ctx[cfg.curctx].c_name[0] = g_ctx[cfg.curctx].c_last[0]
4439 = g_ctx[cfg.curctx].c_fltr[0] = g_ctx[cfg.curctx].c_fltr[1] = '\0';
4441 for (; i < CTX_MAX; ++i)
4442 if ((read(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4443 || (read(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4444 || (header.nameln[i] > 0
4445 && read(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4446 || (header.lastln[i] > 0
4447 && read(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4448 || (header.fltrln[i] > 0
4449 && read(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4450 || (header.pathln[i] > 0
4451 && read(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4454 *path = g_ctx[cfg.curctx].c_path;
4455 *lastdir = g_ctx[cfg.curctx].c_last;
4456 *lastname = g_ctx[cfg.curctx].c_name;
4457 set_sort_flags('\0'); /* Set correct sort options */
4464 printmsg(messages[MSG_FAILED]);
4465 xdelay(XDELAY_INTERVAL_MS);
4473 static uchar_t get_free_ctx(void)
4475 uchar_t r = cfg.curctx;
4478 r = (r + 1) & ~CTX_MAX;
4479 while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
4484 /* ctx is absolute: 1 to 4, + for smart context */
4485 static void set_smart_ctx(int ctx, char *nextpath, char **path, char *file, char **lastname, char **lastdir)
4487 if (ctx == '+') /* Get smart context */
4488 ctx = (int)(get_free_ctx() + 1);
4490 if (ctx == 0 || ctx == cfg.curctx + 1) { /* Same context */
4492 xstrsncpy(*lastdir, *path, PATH_MAX);
4493 xstrsncpy(*path, nextpath, PATH_MAX);
4494 } else { /* New context */
4496 /* Deactivate the new context and build from scratch */
4497 g_ctx[ctx].c_cfg.ctxactive = 0;
4498 DPRINTF_S(nextpath);
4499 savecurctx(nextpath, file, ctx);
4500 *path = g_ctx[ctx].c_path;
4501 *lastdir = g_ctx[ctx].c_last;
4502 *lastname = g_ctx[ctx].c_name;
4507 * This function does one of the following depending on the values of `fdout` and `page`:
4508 * 1) fdout == -1 && !page: Write up to CMD_LEN_MAX bytes of command output into g_buf
4509 * 2) fdout == -1 && page: Create a temp file, write full command output into it and show in pager.
4510 * 3) fdout != -1 && !page: Write full command output into the provided file.
4511 * 4) fdout != -1 && page: Don't use! Returns FALSE.
4513 * g_buf is modified only in case 1.
4514 * g_tmpfpath is modified only in case 2.
4516 static bool get_output(char *file, char *arg1, char *arg2, int fdout, bool page)
4520 int index = 0, flags;
4522 bool have_file = fdout != -1;
4524 int cmd_out_fd = -1;
4528 * In this case the logic of the function dictates that we should write the output of the command
4529 * to `fd` and show it in the pager. But since we didn't open the file descriptor we have no right
4530 * to close it, the caller must do it. We don't even know the path to pass to the pager and
4531 * it's a real hassle to get it. In general this just invites problems so we are blocking it.
4533 if (have_file && page) {
4534 DPRINTF_S("invalid get_ouptput() call");
4538 /* Setup file descriptors for child command */
4539 if (!have_file && page) {
4541 fdout = create_tmp_file();
4545 cmd_in_fd = STDIN_FILENO;
4547 } else if (have_file) {
4549 cmd_in_fd = STDIN_FILENO;
4553 if (pipe(pipefd) == -1)
4556 for (index = 0; index < 2; ++index) {
4557 /* Get previous flags */
4558 flags = fcntl(pipefd[index], F_GETFL, 0);
4560 /* Set bit for non-blocking flag */
4561 flags |= O_NONBLOCK;
4563 /* Change flags on fd */
4564 fcntl(pipefd[index], F_SETFL, flags);
4567 cmd_in_fd = pipefd[0];
4568 cmd_out_fd = pipefd[1];
4575 dup2(cmd_out_fd, STDOUT_FILENO);
4576 dup2(cmd_out_fd, STDERR_FILENO);
4579 spawn(file, arg1, arg2, NULL, F_MULTI);
4580 _exit(EXIT_SUCCESS);
4584 waitpid(pid, NULL, 0);
4586 /* Do what each case should do */
4587 if (!have_file && page) {
4591 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4602 len = read(pipefd[0], g_buf, CMD_LEN_MAX - 1);
4612 * Follows the stat(1) output closely
4614 static bool show_stats(char *fpath)
4616 static char * const cmds[] = {
4617 #ifdef FILE_MIME_OPTS
4618 ("file " FILE_MIME_OPTS),
4621 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
4628 size_t r = ELEMENTS(cmds);
4629 int fd = create_tmp_file();
4634 get_output(cmds[--r], fpath, NULL, fd, FALSE);
4638 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4643 static bool xchmod(const char *fpath, mode_t *mode)
4645 /* (Un)set (S_IXUSR | S_IXGRP | S_IXOTH) */
4646 (0100 & *mode) ? (*mode &= ~0111) : (*mode |= 0111);
4648 return (chmod(fpath, *mode) == 0);
4651 static size_t get_fs_info(const char *path, uchar_t type)
4655 if (statvfs(path, &svb) == -1)
4658 if (type == VFS_AVAIL)
4659 return (size_t)svb.f_bavail << ffs((int)(svb.f_frsize >> 1));
4661 if (type == VFS_USED)
4662 return ((size_t)svb.f_blocks - (size_t)svb.f_bfree) << ffs((int)(svb.f_frsize >> 1));
4664 return (size_t)svb.f_blocks << ffs((int)(svb.f_frsize >> 1)); /* VFS_SIZE */
4667 /* Create non-existent parents and a file or dir */
4668 static bool xmktree(char *path, bool dir)
4676 /* Skip the first '/' */
4679 while (*p != '\0') {
4688 /* Create folder from path to '\0' inserted at p */
4689 if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4691 // XDG_CONFIG_HOME contains a directory
4692 // that is read-only, but the full path
4694 // Try to continue and see what happens.
4695 // TODO: Find a more robust solution.
4696 if (errno == B_READ_ONLY_DEVICE)
4699 DPRINTF_S("mkdir1!");
4700 DPRINTF_S(strerror(errno));
4714 if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4715 DPRINTF_S("mkdir2!");
4716 DPRINTF_S(strerror(errno));
4720 int fd = open(path, O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR); /* Forced create mode for files */
4722 if (fd == -1 && errno != EEXIST) {
4724 DPRINTF_S(strerror(errno));
4734 /* List or extract archive */
4735 static bool handle_archive(char *fpath /* in-out param */, char op)
4737 char arg[] = "-tvf"; /* options for tar/bsdtar to list files */
4738 char *util, *outdir = NULL;
4740 bool is_atool = (!g_state.usebsdtar && getutil(utils[UTIL_ATOOL]));
4743 outdir = xreadline(is_atool ? "." : xbasename(fpath), messages[MSG_NEW_PATH]);
4744 if (!outdir || !*outdir) { /* Cancelled */
4745 printwait(messages[MSG_CANCEL], NULL);
4748 /* Do not create smart context for current dir */
4749 if (!(*outdir == '.' && outdir[1] == '\0')) {
4750 if (!xmktree(outdir, TRUE) || (chdir(outdir) == -1)) {
4754 /* Copy the new dir path to open it in smart context */
4755 outdir = getcwd(NULL, 0);
4761 util = utils[UTIL_ATOOL];
4764 } else if (getutil(utils[UTIL_BSDTAR])) {
4765 util = utils[UTIL_BSDTAR];
4768 } else if (is_suffix(fpath, ".zip")) {
4769 util = utils[UTIL_UNZIP];
4770 arg[1] = (op == 'l') ? 'v' /* verbose listing */ : '\0';
4773 util = utils[UTIL_TAR];
4778 if (op == 'x') /* extract */
4779 spawn(util, arg, fpath, NULL, F_NORMAL | F_MULTI);
4781 get_output(util, arg, fpath, -1, TRUE);
4784 if (chdir(xdirname(fpath)) == -1) {
4789 xstrsncpy(fpath, outdir, PATH_MAX);
4791 } else if (op == 'x')
4797 static char *visit_parent(char *path, char *newpath, int *presel)
4801 /* There is no going back */
4802 if (istopdir(path)) {
4803 /* Continue in type-to-nav mode, if enabled */
4804 if (cfg.filtermode && presel)
4809 /* Use a copy as xdirname() may change the string passed */
4811 xstrsncpy(newpath, path, PATH_MAX);
4815 dir = xdirname(newpath);
4816 if (chdir(dir) == -1) {
4824 static void valid_parent(char *path, char *lastname)
4827 xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
4829 while (!istopdir(path))
4830 if (visit_parent(path, NULL, NULL))
4834 xdelay(XDELAY_INTERVAL_MS);
4837 static bool archive_mount(char *newpath)
4839 char *dir, *cmd = xgetenv("NNN_ARCHMNT", utils[UTIL_ARCHMNT]);
4840 char *name = pdents[cur].name;
4841 size_t len = pdents[cur].nlen;
4842 char mntpath[PATH_MAX];
4844 if (!getutil(cmd)) {
4845 printmsg("install utility");
4849 dir = xstrdup(name);
4851 printmsg(messages[MSG_FAILED]);
4856 if (dir[--len] == '.') {
4863 /* Create the mount point */
4864 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4865 mkpath(mntpath, dir, newpath);
4868 if (!xmktree(newpath, TRUE)) {
4876 if (spawn(cmd, name, newpath, NULL, F_NORMAL)) {
4877 printmsg(messages[MSG_FAILED]);
4884 static bool remote_mount(char *newpath)
4886 uchar_t flag = F_CLI;
4889 bool r = getutil(utils[UTIL_RCLONE]), s = getutil(utils[UTIL_SSHFS]);
4890 char mntpath[PATH_MAX];
4893 printmsg("install sshfs/rclone");
4898 opt = get_input(messages[MSG_REMOTE_OPTS]);
4900 opt = (!s) ? 'r' : 's';
4903 env = xgetenv("NNN_SSHFS", utils[UTIL_SSHFS]);
4904 else if (opt == 'r') {
4905 flag |= F_NOWAIT | F_NOTRACE;
4906 env = xgetenv("NNN_RCLONE", "rclone mount");
4908 printmsg(messages[MSG_INVALID_KEY]);
4912 tmp = xreadline(NULL, "host[:dir] > ");
4914 printmsg(messages[MSG_CANCEL]);
4918 char *div = strchr(tmp, ':');
4923 /* Create the mount point */
4924 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4925 mkpath(mntpath, tmp, newpath);
4926 if (!xmktree(newpath, TRUE)) {
4931 if (!div) { /* Convert "host" to "host:" */
4932 size_t len = xstrlen(tmp);
4935 tmp[len + 1] = '\0';
4939 /* Connect to remote */
4941 if (spawn(env, tmp, newpath, NULL, flag)) {
4942 printmsg(messages[MSG_FAILED]);
4946 spawn(env, tmp, newpath, NULL, flag);
4947 printmsg(messages[MSG_RCLONE_DELAY]);
4948 xdelay(XDELAY_INTERVAL_MS << 2); /* Set 4 times the usual delay */
4955 * Unmounts if the directory represented by name is a mount point.
4956 * Otherwise, asks for hostname
4957 * Returns TRUE if directory needs to be refreshed *.
4959 static bool unmount(char *name, char *newpath, int *presel, char *currentpath)
4961 #if defined(__APPLE__) || defined(__FreeBSD__)
4962 static char cmd[] = "umount";
4964 static char cmd[] = "fusermount3"; /* Arch Linux utility */
4965 static bool found = FALSE;
4968 struct stat sb, psb;
4970 bool parent = FALSE;
4971 bool hovered = FALSE;
4972 char mntpath[PATH_MAX];
4974 #if !defined(__APPLE__) && !defined(__FreeBSD__)
4975 /* On Ubuntu it's fusermount */
4976 if (!found && !getutil(cmd)) {
4982 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4984 if (tmp && strcmp(mntpath, currentpath) == 0) {
4985 mkpath(mntpath, tmp, newpath);
4986 child = lstat(newpath, &sb) != -1;
4987 parent = lstat(xdirname(newpath), &psb) != -1;
4988 if (!child && !parent) {
4994 if (!tmp || !child || !S_ISDIR(sb.st_mode) || (child && parent && sb.st_dev == psb.st_dev)) {
4995 tmp = xreadline(NULL, messages[MSG_HOSTNAME]);
4998 if (name && (tmp[0] == '-') && (tmp[1] == '\0')) {
4999 mkpath(currentpath, name, newpath);
5005 mkpath(mntpath, tmp, newpath);
5007 if (!xdiraccess(newpath)) {
5012 #if defined(__APPLE__) || defined(__FreeBSD__)
5013 if (spawn(cmd, newpath, NULL, NULL, F_NORMAL)) {
5015 if (spawn(cmd, "-qu", newpath, NULL, F_NORMAL)) {
5017 if (!xconfirm(get_input(messages[MSG_LAZY])))
5021 if (spawn(cmd, "-l", newpath, NULL, F_NORMAL)) {
5022 #elif defined(__FreeBSD__)
5023 if (spawn(cmd, "-f", newpath, NULL, F_NORMAL)) {
5025 if (spawn(cmd, "-quz", newpath, NULL, F_NORMAL)) {
5027 printwait(messages[MSG_FAILED], presel);
5032 if (rmdir(newpath) == -1) {
5040 static void lock_terminal(void)
5042 spawn(xgetenv("NNN_LOCKER", utils[UTIL_LOCKER]), NULL, NULL, NULL, F_CLI);
5045 static void printkv(kv *kvarr, int fd, uchar_t max, uchar_t id)
5047 char *val = (id == NNN_BMS) ? bmstr : pluginstr;
5049 for (uchar_t i = 0; i < max && kvarr[i].key; ++i)
5050 dprintf(fd, " %c: %s\n", (char)kvarr[i].key, val + kvarr[i].off);
5053 static void printkeys(kv *kvarr, char *buf, uchar_t max)
5057 for (; i < max && kvarr[i].key; ++i) {
5059 buf[(i << 1) + 1] = kvarr[i].key;
5065 static size_t handle_bookmark(const char *bmark, char *newpath)
5070 if (maxbm || bmark) {
5071 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
5073 if (bmark) { /* There is a marked directory */
5079 printkeys(bookmark, g_buf + r - 1, maxbm);
5081 fd = get_input(NULL);
5085 if (fd == ',') /* Visit marked directory */
5086 bmark ? xstrsncpy(newpath, bmark, PATH_MAX) : (r = MSG_NOT_SET);
5087 else if (fd == '\r') { /* Visit bookmarks directory */
5088 mkpath(cfgpath, toks[TOK_BM], newpath);
5090 } else if (!get_kv_val(bookmark, newpath, fd, maxbm, NNN_BMS))
5091 r = MSG_INVALID_KEY;
5093 if (!r && chdir(newpath) == -1) {
5102 static void add_bookmark(char *path, char *newpath, int *presel)
5104 char *dir = xbasename(path);
5106 dir = xreadline(dir[0] ? dir : NULL, messages[MSG_BM_NAME]);
5108 size_t r = mkpath(cfgpath, toks[TOK_BM], newpath);
5110 newpath[r - 1] = '/';
5111 xstrsncpy(newpath + r, dir, PATH_MAX - r);
5112 printwait((symlink(path, newpath) == -1) ? strerror(errno) : newpath, presel);
5114 printwait(messages[MSG_CANCEL], presel);
5118 * The help string tokens (each line) start with a HEX value which indicates
5119 * the number of spaces to print before the particular token. In the middle,
5120 * %NN can be used to insert a run of spaces, e.g %10 will print 10 spaces.
5121 * %NN MUST be 2 characters long, e.g %05 for 5 spaces.
5123 * This method was chosen instead of a flat string because the number of bytes
5124 * in help was increasing the binary size by around a hundred bytes. This would
5125 * only have increased as we keep adding new options.
5127 static void show_help(const char *path)
5129 static const char helpstr[] = {
5137 "9Up k Up%16PgUp ^U Page up\n"
5138 "9Dn j Down%14PgDn ^D Page down\n"
5139 "9Lt h Parent%12~ ` @ - ~, /, start, prev\n"
5140 "5Ret Rt l Open%20' First file/match\n"
5141 "9g ^A Top%21J Jump to entry/offset\n"
5142 "9G ^E End%20^J Toggle auto-advance on open\n"
5143 "8B (,) Book(mark)%11b ^/ Select bookmark\n"
5144 "a1-4 Context%11(Sh)Tab Cycle/new context\n"
5145 "62Esc ^Q Quit%19^y Next young\n"
5146 "b^G QuitCD%18Q Pick/err, quit\n"
5149 "1FILTER & PROMPT\n"
5150 "c/ Filter%17^N Toggle type-to-nav\n"
5151 "aEsc Exit prompt%12^L Toggle last filter\n"
5152 "c. Toggle hidden%05Alt+Esc Unfilter, quit context\n"
5155 "9o ^O Open with%15n Create new/link\n"
5156 "9f ^F File stats%14d Detail mode toggle\n"
5157 "b^R Rename/dup%14r Batch rename\n"
5158 "cz Archive%17e Edit file\n"
5159 "c* Toggle exe%14> Export list\n"
5160 "6Space + (Un)select%12m-m Select range/clear\n"
5161 "ca Select all%14A Invert sel\n"
5162 "9p ^P Copy here%12w ^W Cp/mv sel as\n"
5163 "9v ^V Move here%15E Edit sel list\n"
5164 "9x ^X Delete%18S Listed sel size\n"
5165 "aEsc Send to FIFO\n"
5168 "8Alt ; Select plugin%11= Launch app\n"
5169 "9! ^] Shell%19] Cmd prompt\n"
5170 "cc Connect remote%10u Unmount remote/archive\n"
5171 "9t ^T Sort toggles%12s Manage session\n"
5172 "cT Set time type%110 Lock\n"
5173 "b^L Redraw%18? Help, conf\n"
5175 char help_buf[1<<11]; // if editing helpstr, ensure this has enough space to decode it
5177 int fd = create_tmp_file();
5181 char *prog = xgetenv(env_cfg[NNN_HELP], NULL);
5183 get_output(prog, NULL, NULL, fd, FALSE);
5187 const char *end = helpstr + (sizeof helpstr - 1);
5188 for (const char *s = helpstr; s < end; ++s) {
5190 for (int k = 0, n = xchartohex(*s); k < n; ++k) *w++ = ' ';
5191 } else if (*s == '%') {
5192 int n = ((s[1] - '0') * 10) + (s[2] - '0');
5193 for (int k = 0; k < n; ++k) *w++ = ' ';
5200 ssize_t res = write(fd, help_buf, w - help_buf);
5201 (void)res; // silence warning
5203 dprintf(fd, "\nLOCATIONS\n");
5204 for (uchar_t i = 0; i < CTX_MAX; ++i)
5205 if (g_ctx[i].c_cfg.ctxactive)
5206 dprintf(fd, " %u: %s\n", i + 1, g_ctx[i].c_path);
5208 dprintf(fd, "\nVOLUME: avail:%s ", coolsize(get_fs_info(path, VFS_AVAIL)));
5209 dprintf(fd, "used:%s ", coolsize(get_fs_info(path, VFS_USED)));
5210 dprintf(fd, "size:%s\n\n", coolsize(get_fs_info(path, VFS_SIZE)));
5213 dprintf(fd, "BOOKMARKS\n");
5214 printkv(bookmark, fd, maxbm, NNN_BMS);
5219 dprintf(fd, "PLUGIN KEYS\n");
5220 printkv(plug, fd, maxplug, NNN_PLUG);
5224 for (uchar_t i = NNN_OPENER; i <= NNN_TRASH; ++i) {
5225 char *s = getenv(env_cfg[i]);
5227 dprintf(fd, "%s: %s\n", env_cfg[i], s);
5231 dprintf(fd, "SELECTION FILE: %s\n", selpath);
5233 dprintf(fd, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
5236 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
5240 static void setexports(void)
5246 setenv(envs[ENV_NCUR], pdents[cur].name, 1);
5247 xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
5248 } else if (g_ctx[cfg.curctx].c_name[0])
5249 g_ctx[cfg.curctx].c_name[0] = '\0';
5251 for (uchar_t i = 0; i < CTX_MAX; ++i) {
5252 if (g_ctx[i].c_cfg.ctxactive) {
5253 dvar[1] = fvar[1] = '1' + i;
5254 setenv(dvar, g_ctx[i].c_path, 1);
5256 if (g_ctx[i].c_name[0]) {
5257 mkpath(g_ctx[i].c_path, g_ctx[i].c_name, g_buf);
5258 setenv(fvar, g_buf, 1);
5262 setenv("NNN_INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
5263 setenv("NNN_PREFER_SELECTION", xitoa(cfg.prefersel), 1);
5266 static void run_cmd_as_plugin(const char *file, uchar_t flags)
5270 xstrsncpy(g_buf, file, PATH_MAX);
5272 len = xstrlen(g_buf);
5273 if (len > 1 && g_buf[len - 1] == '*') {
5274 flags &= ~F_CONFIRM; /* Skip user confirmation */
5275 g_buf[len - 1] = '\0'; /* Get rid of trailing no confirmation symbol */
5280 get_output(utils[UTIL_SH_EXEC], g_buf, NULL, -1, TRUE);
5282 spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, flags);
5285 static bool plctrl_init(void)
5289 /* g_tmpfpath is used to generate tmp file names */
5290 g_tmpfpath[tmpfplen - 1] = '\0';
5291 len = xstrsncpy(g_pipepath, g_tmpfpath, TMP_LEN_MAX);
5292 g_pipepath[len - 1] = '/';
5293 len = xstrsncpy(g_pipepath + len, "nnn-pipe.", TMP_LEN_MAX - len) + len;
5294 xstrsncpy(g_pipepath + len - 1, xitoa(getpid()), TMP_LEN_MAX - len);
5295 setenv(env_cfg[NNN_PIPE], g_pipepath, TRUE);
5297 return EXIT_SUCCESS;
5300 static void rmlistpath(void)
5303 DPRINTF_S(__func__);
5304 DPRINTF_S(listpath);
5305 spawn(utils[UTIL_RM_RF], listpath, NULL, NULL, F_NOTRACE | F_MULTI);
5306 /* Do not free if program was started in list mode */
5307 if (listpath != initpath)
5313 static ssize_t read_nointr(int fd, void *buf, size_t count)
5318 len = read(fd, buf, count);
5319 while (len == -1 && errno == EINTR);
5324 static char *readpipe(int fd, char *ctxnum, char **path)
5326 char ctx, *nextpath = NULL;
5328 if (read_nointr(fd, g_buf, 1) != 1)
5331 if (g_buf[0] == '-') { /* Clear selection on '-' */
5333 if (read_nointr(fd, g_buf, 1) != 1)
5337 if (g_buf[0] == '+')
5338 ctx = (char)(get_free_ctx() + 1);
5339 else if (g_buf[0] < '0')
5342 ctx = g_buf[0] - '0';
5347 if (read_nointr(fd, g_buf, 1) != 1)
5353 ssize_t len = read_nointr(fd, g_buf, PATH_MAX);
5358 g_buf[len] = '\0'; /* Terminate the path read */
5359 if (g_buf[0] == '/') {
5361 len = xstrlen(g_buf);
5362 while (--len && (g_buf[len] == '/')) /* Trim all trailing '/' */
5365 } else if (op == 'l') {
5366 rmlistpath(); /* Remove last list mode path, if any */
5367 nextpath = load_input(fd, *path);
5368 } else if (op == 'p') {
5381 static bool run_plugin(char **path, const char *file, char *runfile, char **lastname, char **lastdir)
5386 bool cmd_as_plugin = FALSE;
5389 if (!g_state.pluginit) {
5391 g_state.pluginit = 1;
5396 /* Check for run-cmd-as-plugin mode */
5398 flags = F_MULTI | F_CONFIRM;
5401 if (*file == '|') { /* Check if output should be paged */
5404 } else if (*file == '&') { /* Check if GUI flags are to be used */
5405 flags = F_MULTI | F_NOTRACE | F_NOWAIT;
5412 if ((flags & F_NOTRACE) || (flags & F_PAGE)) {
5413 run_cmd_as_plugin(file, flags);
5417 cmd_as_plugin = TRUE;
5420 if (mkfifo(g_pipepath, 0600) != 0)
5427 if (!p) { // In child
5428 int wfd = open(g_pipepath, O_WRONLY | O_CLOEXEC);
5431 _exit(EXIT_FAILURE);
5433 if (!cmd_as_plugin) {
5437 /* Generate absolute path to plugin */
5438 mkpath(plgpath, file, g_buf);
5441 sel = selpath ? selpath : std;
5443 if (runfile && runfile[0]) {
5444 xstrsncpy(*lastname, runfile, NAME_MAX);
5445 spawn(g_buf, *lastname, *path, sel, 0);
5447 spawn(g_buf, NULL, *path, sel, 0);
5449 run_cmd_as_plugin(file, flags);
5452 _exit(EXIT_SUCCESS);
5458 rfd = open(g_pipepath, O_RDONLY);
5459 while (rfd == -1 && errno == EINTR);
5461 nextpath = readpipe(rfd, &ctx, path);
5463 set_smart_ctx(ctx, nextpath, path, runfile, lastname, lastdir);
5467 /* wait for the child to finish. no zombies allowed */
5468 waitpid(p, NULL, 0);
5477 static bool launch_app(char *newpath)
5480 char *tmp = newpath;
5482 mkpath(plgpath, utils[UTIL_LAUNCH], newpath);
5484 if (!getutil(utils[UTIL_FZF]) || access(newpath, X_OK) < 0) {
5485 tmp = xreadline(NULL, messages[MSG_APP_NAME]);
5486 r = F_NOWAIT | F_NOTRACE | F_MULTI;
5489 if (tmp && *tmp) // NOLINT
5490 spawn(tmp, (r == F_NORMAL) ? "0" : NULL, NULL, NULL, r);
5495 /* Returns TRUE if at least one command was run */
5496 static bool prompt_run(void)
5499 char *cmdline, *next;
5500 int cnt_j, cnt_J, cmd_ret;
5503 const char *xargs_j = "xargs -0 -I{} %s < %s";
5504 const char *xargs_J = "xargs -0 %s < %s";
5505 char cmd[CMD_LEN_MAX + 32]; // 32 for xargs format strings
5509 if (g_state.picker || g_state.xprompt) {
5511 cmdline = xreadline(NULL, PROMPT);
5514 cmdline = getreadline("\n"PROMPT);
5516 // Check for an empty command
5517 if (!cmdline || !cmdline[0])
5521 lastcmd = xstrdup(cmdline);
5524 len = xstrlen(cmdline);
5528 while ((next = strstr(next, "%j"))) {
5531 // replace %j with {} for xargs later
5540 while ((next = strstr(next, "%J"))) {
5543 // %J should be the last thing in the command
5544 if (next == cmdline + len - 2) {
5545 cmdline[len - 2] = '\0';
5551 // We can't handle both %j and %J in a single command
5556 snprintf(cmd, CMD_LEN_MAX + 32, xargs_j, cmdline, selpath);
5558 snprintf(cmd, CMD_LEN_MAX + 32, xargs_J, cmdline, selpath);
5560 cmd_ret = spawn(shell, "-c", (cnt_j || cnt_J) ? cmd : cmdline, NULL, F_CLI | F_CONFIRM);
5561 if ((cnt_j || cnt_J) && cmd_ret == 0)
5568 static bool handle_cmd(enum action sel, char *newpath)
5570 endselection(FALSE);
5572 if (sel == SEL_LAUNCH)
5573 return launch_app(newpath);
5577 if (sel == SEL_PROMPT)
5578 return prompt_run();
5580 /* Set nnn nesting level */
5581 char *tmp = getenv(env_cfg[NNNLVL]);
5582 int r = tmp ? atoi(tmp) : 0;
5584 setenv(env_cfg[NNNLVL], xitoa(r + 1), 1);
5585 spawn(shell, NULL, NULL, NULL, F_CLI);
5586 setenv(env_cfg[NNNLVL], xitoa(r), 1);
5590 static void dentfree(void)
5596 /* Thread data cleanup */
5602 static void *du_thread(void *p_data)
5604 thread_data *pdata = (thread_data *)p_data;
5605 char *path[2] = {pdata->path, NULL};
5606 ullong_t tfiles = 0;
5607 blkcnt_t tblocks = 0;
5609 FTS *tree = fts_open(path, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR, 0);
5612 while ((node = fts_read(tree))) {
5613 if (node->fts_info & FTS_D) {
5614 if (g_state.interrupt)
5619 sb = node->fts_statp;
5621 if (cfg.apparentsz) {
5622 if (sb->st_size && DU_TEST)
5623 tblocks += sb->st_size;
5624 } else if (sb->st_blocks && DU_TEST)
5625 tblocks += sb->st_blocks;
5632 if (pdata->entnum >= 0)
5633 pdents[pdata->entnum].blocks = tblocks;
5635 if (!pdata->mntpoint) {
5636 core_blocks[pdata->core] += tblocks;
5637 core_files[pdata->core] += tfiles;
5639 core_files[pdata->core] += 1;
5641 pthread_mutex_lock(&running_mutex);
5642 threadbmp |= (1 << pdata->core);
5644 pthread_mutex_unlock(&running_mutex);
5649 static void dirwalk(char *path, int entnum, bool mountpoint)
5651 /* Loop till any core is free */
5652 while (active_threads == NUM_DU_THREADS);
5654 if (g_state.interrupt)
5657 pthread_mutex_lock(&running_mutex);
5658 int core = ffs(threadbmp) - 1;
5660 threadbmp &= ~(1 << core);
5662 pthread_mutex_unlock(&running_mutex);
5664 xstrsncpy(core_data[core].path, path, PATH_MAX);
5665 core_data[core].entnum = entnum;
5666 core_data[core].core = (ushort_t)core;
5667 core_data[core].mntpoint = mountpoint;
5671 pthread_create(&tid, NULL, du_thread, (void *)&(core_data[core]));
5674 addstr(xbasename(path));
5675 addstr(" [^C aborts]\n");
5679 static bool prep_threads(void)
5681 if (!g_state.duinit) {
5683 threadbmp >>= (32 - NUM_DU_THREADS);
5686 core_blocks = calloc(NUM_DU_THREADS, sizeof(blkcnt_t));
5688 core_data = calloc(NUM_DU_THREADS, sizeof(thread_data));
5690 core_files = calloc(NUM_DU_THREADS, sizeof(ullong_t));
5692 if (!core_blocks || !core_data || !core_files) {
5697 /* Increase current open file descriptor limit */
5700 g_state.duinit = TRUE;
5702 memset(core_blocks, 0, NUM_DU_THREADS * sizeof(blkcnt_t));
5703 memset(core_data, 0, NUM_DU_THREADS * sizeof(thread_data));
5704 memset(core_files, 0, NUM_DU_THREADS * sizeof(ullong_t));
5709 /* Skip self and parent */
5710 static inline bool selforparent(const char *path)
5712 return path[0] == '.' && (path[1] == '\0' || (path[1] == '.' && path[2] == '\0'));
5715 static int dentfill(char *path, struct entry **ppdents)
5717 uchar_t entflags = 0;
5720 char *namep, *pnb, *buf;
5721 struct entry *dentp;
5722 size_t off = 0, namebuflen = NAMEBUF_INCR;
5723 struct stat sb_path, sb;
5724 DIR *dirp = opendir(path);
5727 gtimesecs = time(NULL);
5729 DPRINTF_S(__func__);
5734 int fd = dirfd(dirp);
5741 if (fstatat(fd, path, &sb_path, 0) == -1)
5745 ihashbmp = calloc(1, HASH_OCTETS << 3);
5749 memset(ihashbmp, 0, HASH_OCTETS << 3);
5751 if (!prep_threads())
5754 attron(COLOR_PAIR(cfg.curctx + 1));
5757 #if _POSIX_C_SOURCE >= 200112L
5758 posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
5765 #if defined(__sun) || defined(__HAIKU__)
5766 flags = AT_SYMLINK_NOFOLLOW; /* no d_type */
5768 if (cfg.blkorder || dp->d_type == DT_UNKNOWN) {
5770 * Optimization added for filesystems which support dirent.d_type
5773 * - the symlink size is set to 0
5774 * - the modification time of the symlink is set to that of the target file
5776 flags = AT_SYMLINK_NOFOLLOW;
5783 if (selforparent(namep))
5786 if (!cfg.showhidden && namep[0] == '.') {
5790 if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
5793 if (S_ISDIR(sb.st_mode)) {
5794 if (sb_path.st_dev == sb.st_dev) { // NOLINT
5795 mkpath(path, namep, buf); // NOLINT
5796 dirwalk(buf, -1, FALSE);
5798 if (g_state.interrupt)
5802 /* Do not recount hard links */
5803 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5804 dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5811 if (fstatat(fd, namep, &sb, flags) == -1) {
5812 if (flags || (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)) {
5817 DPRINTF_S(strerror(errno));
5820 entflags = FILE_MISSING;
5821 memset(&sb, 0, sizeof(struct stat));
5822 } else /* Orphaned symlink */
5823 entflags = SYM_ORPHAN;
5826 if (ndents == total_dents) {
5828 while (active_threads);
5830 total_dents += ENTRY_INCR;
5831 *ppdents = xrealloc(*ppdents, total_dents * sizeof(**ppdents));
5837 DPRINTF_P(*ppdents);
5840 /* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
5841 if (namebuflen - off < NAME_MAX + 1) {
5842 namebuflen += NAMEBUF_INCR;
5845 pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
5851 DPRINTF_P(pnamebuf);
5853 /* realloc() may result in memory move, we must re-adjust if that happens */
5854 if (pnb != pnamebuf) {
5856 dentp->name = pnamebuf;
5858 for (int count = 1; count < ndents; ++dentp, ++count)
5859 /* Current file name starts at last file name start + length */
5860 (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
5864 dentp = *ppdents + ndents;
5866 /* Selection file name */
5867 dentp->name = (char *)((size_t)pnamebuf + off);
5868 dentp->nlen = xstrsncpy(dentp->name, namep, NAME_MAX + 1);
5871 /* Copy other fields */
5872 if (cfg.timetype == T_MOD) {
5873 dentp->sec = sb.st_mtime;
5875 dentp->nsec = (uint_t)sb.st_mtimespec.tv_nsec;
5877 dentp->nsec = (uint_t)sb.st_mtim.tv_nsec;
5879 } else if (cfg.timetype == T_ACCESS) {
5880 dentp->sec = sb.st_atime;
5882 dentp->nsec = (uint_t)sb.st_atimespec.tv_nsec;
5884 dentp->nsec = (uint_t)sb.st_atim.tv_nsec;
5887 dentp->sec = sb.st_ctime;
5889 dentp->nsec = (uint_t)sb.st_ctimespec.tv_nsec;
5891 dentp->nsec = (uint_t)sb.st_ctim.tv_nsec;
5895 if ((gtimesecs - sb.st_mtime <= 300) || (gtimesecs - sb.st_ctime <= 300))
5896 entflags |= FILE_YOUNG;
5898 #if !(defined(__sun) || defined(__HAIKU__))
5899 if (!flags && dp->d_type == DT_LNK) {
5900 /* Do not add sizes for links */
5901 dentp->mode = (sb.st_mode & ~S_IFMT) | S_IFLNK;
5902 dentp->size = listpath ? sb.st_size : 0;
5904 dentp->mode = sb.st_mode;
5905 dentp->size = sb.st_size;
5908 dentp->mode = sb.st_mode;
5909 dentp->size = sb.st_size;
5913 dentp->uid = sb.st_uid;
5914 dentp->gid = sb.st_gid;
5917 dentp->flags = S_ISDIR(sb.st_mode) ? 0 : ((sb.st_nlink > 1) ? HARD_LINK : 0);
5919 dentp->flags |= entflags;
5924 if (S_ISDIR(sb.st_mode)) {
5925 mkpath(path, namep, buf); // NOLINT
5927 /* Need to show the disk usage of this dir */
5928 dirwalk(buf, ndents, (sb_path.st_dev != sb.st_dev)); // NOLINT
5930 if (g_state.interrupt)
5933 dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5934 /* Do not recount hard links */
5935 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5936 dir_blocks += dentp->blocks;
5942 /* Flag if this is a dir or symlink to a dir */
5943 if (S_ISLNK(sb.st_mode)) {
5945 fstatat(fd, namep, &sb, 0);
5948 if (S_ISDIR(sb.st_mode))
5949 dentp->flags |= DIR_OR_DIRLNK;
5950 #if !(defined(__sun) || defined(__HAIKU__)) /* no d_type */
5951 } else if (dp->d_type == DT_DIR || ((dp->d_type == DT_LNK
5952 || dp->d_type == DT_UNKNOWN) && S_ISDIR(sb.st_mode))) {
5953 dentp->flags |= DIR_OR_DIRLNK;
5958 } while ((dp = readdir(dirp)));
5961 if (g_state.duinit && cfg.blkorder) {
5962 while (active_threads);
5964 attroff(COLOR_PAIR(cfg.curctx + 1));
5965 for (int i = 0; i < NUM_DU_THREADS; ++i) {
5966 num_files += core_files[i];
5967 dir_blocks += core_blocks[i];
5971 /* Should never be null */
5972 if (closedir(dirp) == -1)
5978 static void populate(char *path, char *lastname)
5981 struct timespec ts1, ts2;
5983 clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
5986 ndents = dentfill(path, &pdents);
5991 ENTSORT(pdents, ndents, entrycmpfn);
5995 clock_gettime(CLOCK_REALTIME, &ts2);
5996 DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
5999 /* Find cur from history */
6000 /* No NULL check for lastname, always points to an array */
6001 move_cursor(*lastname ? dentfind(lastname, ndents) : 0, 0);
6003 // Force full redraw
6004 last_curscroll = -1;
6008 static void notify_fifo(bool force)
6014 fifofd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC);
6017 /* Unexpected error, the FIFO file might have been removed */
6018 /* We give up FIFO notification */
6024 static struct entry lastentry;
6026 if (!force && !memcmp(&lastentry, &pdents[cur], sizeof(struct entry))) // NOLINT
6029 lastentry = pdents[cur];
6031 char path[PATH_MAX];
6032 size_t len = mkpath(g_ctx[cfg.curctx].c_path, ndents ? pdents[cur].name : "", path);
6034 path[len - 1] = '\n';
6036 ssize_t ret = write(fifofd, path, len);
6038 if (ret != (ssize_t)len && !(ret == -1 && (errno == EAGAIN || errno == EPIPE))) {
6039 DPRINTF_S(strerror(errno));
6043 static void send_to_explorer(int *presel)
6046 int fd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0600);
6047 if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
6056 notify_fifo(TRUE); /* Send opened path to NNN_FIFO */
6060 static void move_cursor(int target, int ignore_scrolloff)
6062 int onscreen = xlines - 4; /* Leave top 2 and bottom 2 lines */
6064 target = MAX(0, MIN(ndents - 1, target));
6065 last_curscroll = curscroll;
6069 if (!ignore_scrolloff) {
6070 int delta = target - last;
6071 int scrolloff = MIN(SCROLLOFF, onscreen >> 1);
6074 * When ignore_scrolloff is 1, the cursor can jump into the scrolloff
6075 * margin area, but when ignore_scrolloff is 0, act like a boa
6076 * constrictor and squeeze the cursor towards the middle region of the
6077 * screen by allowing it to move inward and disallowing it to move
6078 * outward (deeper into the scrolloff margin area).
6080 if (((cur < (curscroll + scrolloff)) && delta < 0)
6081 || ((cur > (curscroll + onscreen - scrolloff - 1)) && delta > 0))
6084 curscroll = MIN(curscroll, MIN(cur, ndents - onscreen));
6085 curscroll = MAX(curscroll, MAX(cur - (onscreen - 1), 0));
6088 if (!g_state.fifomode)
6089 notify_fifo(FALSE); /* Send hovered path to NNN_FIFO */
6093 static void handle_screen_move(enum action sel)
6099 if (cfg.rollover || (cur != ndents - 1))
6100 move_cursor((cur + 1) % ndents, 0);
6103 if (cfg.rollover || cur)
6104 move_cursor((cur + ndents - 1) % ndents, 0);
6107 onscreen = xlines - 4;
6108 move_cursor(curscroll + (onscreen - 1), 1);
6109 curscroll += onscreen - 1;
6112 onscreen = xlines - 4;
6113 move_cursor(curscroll + (onscreen - 1), 1);
6114 curscroll += onscreen >> 1;
6117 onscreen = xlines - 4;
6118 move_cursor(curscroll, 1);
6119 curscroll -= onscreen - 1;
6122 onscreen = xlines - 4;
6123 move_cursor(curscroll, 1);
6124 curscroll -= onscreen >> 1;
6128 char *input = xreadline(NULL, "jump (+n/-n/n): ");
6130 if (!input || !*input)
6132 if (input[0] == '-') {
6133 cur -= atoi(input + 1);
6136 } else if (input[0] == '+') {
6137 cur += atoi(input + 1);
6141 int index = atoi(input);
6143 if ((index < 1) || (index > ndents))
6147 onscreen = xlines - 4;
6148 move_cursor(cur, 1);
6149 curscroll -= onscreen >> 1;
6156 move_cursor(ndents - 1, 1);
6160 for (int r = cur;;) {
6165 if (pdents[r].flags & FILE_YOUNG) {
6172 default: /* case SEL_FIRST */
6174 int c = get_input(messages[MSG_FIRST]);
6181 int r = (c == TOUPPER(*pdents[cur].name)) ? (cur + 1) : 0;
6183 for (; r < ndents; ++r) {
6184 if (((c == '\'') && !(pdents[r].flags & DIR_OR_DIRLNK))
6185 || (c == TOUPPER(*pdents[r].name))) {
6186 move_cursor((r) % ndents, 0);
6195 static void handle_openwith(const char *path, const char *name, char *newpath, char *tmp)
6197 /* Confirm if app is CLI or GUI */
6198 int r = get_input(messages[MSG_CLI_MODE]);
6200 r = (r == 'c' ? F_CLI :
6201 ((r == 'g' || r == '\r') ? (F_NOWAIT | F_NOTRACE | F_MULTI) : 0));
6203 mkpath(path, name, newpath);
6204 spawn(tmp, newpath, NULL, NULL, r);
6208 static void copynextname(char *lastname)
6211 cur += (cur != (ndents - 1)) ? 1 : -1;
6217 static int handle_context_switch(enum action sel)
6222 case SEL_CYCLE: // fallthrough
6224 /* visit next and previous contexts */
6226 if (sel == SEL_CYCLE)
6228 r = (r + 1) & ~CTX_MAX;
6229 while (!g_ctx[r].c_cfg.ctxactive);
6231 do /* Attempt to create a new context */
6232 r = (r + 1) & ~CTX_MAX;
6233 while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
6235 if (r == cfg.curctx) /* If all contexts are active, reverse cycle */
6237 r = (r + (CTX_MAX - 1)) & (CTX_MAX - 1);
6238 while (!g_ctx[r].c_cfg.ctxactive);
6240 default: /* SEL_CTXN */
6241 if (sel >= SEL_CTX1) /* CYCLE keys are lesser in value */
6242 r = sel - SEL_CTX1; /* Save the next context id */
6244 if (cfg.curctx == r) {
6245 if (sel == SEL_CYCLE)
6246 (r == CTX_MAX - 1) ? (r = 0) : ++r;
6247 else if (sel == SEL_CYCLER)
6248 (r == 0) ? (r = CTX_MAX - 1) : --r;
6257 static int set_sort_flags(int r)
6259 bool session = (r == '\0');
6260 bool reverse = FALSE;
6262 if (ISUPPER_(r) && (r != 'R') && (r != 'C')) {
6267 /* Set the correct input in case of a session load */
6269 if (cfg.apparentsz) {
6272 } else if (cfg.blkorder) {
6277 /* Ensure function pointers are in sync with cfg. */
6278 entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
6279 namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
6280 } else if (r == CONTROL('T')) {
6281 /* Cycling order: clear -> size -> time -> clear */
6284 else if (cfg.sizeorder)
6291 case 'a': /* Apparent du */
6292 cfg.apparentsz ^= 1;
6293 if (cfg.apparentsz) {
6299 case 'd': /* Disk usage */
6301 if (!cfg.apparentsz)
6304 blk_shift = ffs(S_BLKSIZE) - 1;
6314 entrycmpfn = &entrycmp;
6316 endselection(TRUE); /* We are going to reload dir */
6326 entrycmpfn = &entrycmp;
6327 namecmpfn = &xstricmp;
6329 case 'e': /* File extension */
6336 entrycmpfn = &entrycmp;
6338 case 'r': /* Reverse sort */
6340 entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
6342 case 's': /* File size */
6349 entrycmpfn = &entrycmp;
6351 case 't': /* Time */
6358 entrycmpfn = &entrycmp;
6360 case 'v': /* Version */
6362 namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
6375 entrycmpfn = &reventrycmp;
6378 cfgsort[cfg.curctx] = (uchar_t)r;
6383 static bool set_time_type(int *presel)
6386 char buf[] = "'a'ccess / 'c'hange / 'm'od [ ]";
6388 buf[sizeof(buf) - 3] = cfg.timetype == T_MOD ? 'm' : (cfg.timetype == T_ACCESS ? 'a' : 'c');
6390 int r = get_input(buf);
6392 if (r == 'a' || r == 'c' || r == 'm') {
6393 r = (r == 'm') ? T_MOD : ((r == 'a') ? T_ACCESS : T_CHANGE);
6394 if (cfg.timetype != r) {
6397 if (cfg.filtermode || g_ctx[cfg.curctx].c_fltr[1])
6404 r = MSG_INVALID_KEY;
6407 printwait(messages[r], presel);
6412 static void statusbar(char *path)
6416 pEntry pent = &pdents[cur];
6423 /* Get the file extension for regular files */
6424 if (S_ISREG(pent->mode)) {
6425 i = (int)(pent->nlen - 1);
6426 ptr = xextension(pent->name, i);
6428 len = i - (ptr - pent->name);
6429 if (!ptr || len > 5 || len < 2)
6434 attron(COLOR_PAIR(cfg.curctx + 1));
6436 if (cfg.fileinfo && get_output("file", "-b", pdents[cur].name, -1, FALSE))
6437 mvaddstr(xlines - 2, 2, g_buf);
6441 printw("%d/%s ", cur + 1, xitoa(ndents));
6443 if (g_state.selmode || nselected) {
6446 if (g_state.rangesel)
6448 else if (g_state.selmode)
6451 addstr(xitoa(nselected));
6457 if (cfg.blkorder) { /* du mode */
6460 xstrsncpy(buf, coolsize(dir_blocks << blk_shift), 12);
6462 printw("%cu:%s avail:%s files:%llu %lluB %s\n",
6463 (cfg.apparentsz ? 'a' : 'd'), buf, coolsize(get_fs_info(path, VFS_AVAIL)),
6464 num_files, (ullong_t)pent->blocks << blk_shift, ptr);
6465 } else { /* light or detail mode */
6466 char sort[] = "\0\0\0\0\0";
6468 if (getorderstr(sort))
6472 print_time(&pent->sec, pent->flags);
6475 addstr(get_lsperms(pent->mode));
6478 if (g_state.uidgid) {
6479 addstr(getpwname(pent->uid));
6481 addstr(getgrname(pent->gid));
6485 if (S_ISLNK(pent->mode)) {
6486 if (!cfg.fileinfo) {
6487 i = readlink(pent->name, g_buf, PATH_MAX);
6488 addstr(coolsize(i >= 0 ? i : pent->size)); /* Show symlink size */
6489 if (i > 1) { /* Show symlink target */
6493 getyx(stdscr, len, y);
6494 i = MIN(i, xcols - y);
6500 addstr(coolsize(pent->size));
6503 if (pent->flags & HARD_LINK) {
6506 if (stat(pent->name, &sb) != -1) {
6508 addstr(xitoa((int)sb.st_nlink)); /* Show number of links */
6510 addstr(xitoa((int)sb.st_ino)); /* Show inode number */
6517 attroff(COLOR_PAIR(cfg.curctx + 1));
6518 /* Place HW cursor on current for Braille systems */
6522 static inline void markhovered(void)
6524 if (cfg.showdetail && ndents) { /* Bold forward arrowhead */
6526 addch('>' | A_BOLD);
6530 static int adjust_cols(int n)
6532 /* Calculate the number of cols available to print entry name */
6533 #ifdef ICONS_ENABLED
6534 n -= (g_state.oldcolor ? 0 : ICON_SIZE + ICON_PADDING_LEFT_LEN + ICON_PADDING_RIGHT_LEN);
6536 if (cfg.showdetail) {
6537 /* Fallback to light mode if less than 35 columns */
6539 cfg.showdetail ^= 1;
6540 else /* 2 more accounted for below */
6544 /* 2 columns for preceding space and indicator */
6548 static void draw_line(int ncols)
6552 ncols = adjust_cols(ncols);
6554 if (g_state.oldcolor && (pdents[last].flags & DIR_OR_DIRLNK)) {
6555 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6559 move(2 + last - curscroll, 0);
6561 printent(&pdents[last], ncols, FALSE);
6563 if (g_state.oldcolor && (pdents[cur].flags & DIR_OR_DIRLNK)) {
6564 if (!dir) {/* First file is not a directory */
6565 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6568 } else if (dir) { /* Second file is not a directory */
6569 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6573 move(2 + cur - curscroll, 0);
6575 printent(&pdents[cur], ncols, TRUE);
6577 /* Must reset e.g. no files in dir */
6579 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6584 static void redraw(char *path)
6586 getmaxyx(stdscr, xlines, xcols);
6588 int ncols = (xcols <= PATH_MAX) ? xcols : PATH_MAX;
6589 int onscreen = xlines - 4;
6596 if (ndents && (last_curscroll == curscroll))
6597 return draw_line(ncols);
6600 DPRINTF_S(__func__);
6605 /* Enforce scroll/cursor invariants */
6606 move_cursor(cur, 1);
6608 /* Fail redraw if < than 10 columns, context info prints 10 chars */
6609 if (ncols <= MIN_DISPLAY_COL) {
6610 printmsg(messages[MSG_FEW_COLUMNS]);
6617 for (i = 0; i < CTX_MAX; ++i) { /* 8 chars printed for contexts - "1 2 3 4 " */
6618 if (!g_ctx[i].c_cfg.ctxactive)
6621 addch((i + '1') | (COLOR_PAIR(i + 1) | A_BOLD
6622 /* active: underline, current: reverse */
6623 | ((cfg.curctx != i) ? A_UNDERLINE : A_REVERSE)));
6628 attron(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6631 bool in_home = set_tilde_in_path(path);
6632 char *ptr = in_home ? &path[homelen - 1] : path;
6634 i = (int)xstrlen(ptr);
6635 if ((i + MIN_DISPLAY_COL) <= ncols)
6636 addnstr(ptr, ncols - MIN_DISPLAY_COL);
6638 char *base = xmemrchr((uchar_t *)ptr, '/', i);
6647 if (ptr && (base != ptr)) {
6648 while (ptr < base) {
6650 i += 2; /* 2 characters added */
6651 if (ncols < i + MIN_DISPLAY_COL) {
6652 base = NULL; /* Can't print more characters */
6664 addnstr(base, ncols - (MIN_DISPLAY_COL + i));
6668 reset_tilde_in_path(path);
6670 attroff(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6672 /* Go to first entry */
6673 if (curscroll > 0) {
6675 #ifdef ICONS_ENABLED
6676 addstr(ICON_ARROW_UP);
6682 if (g_state.oldcolor) {
6683 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6684 g_state.dircolor = 1;
6687 onscreen = MIN(onscreen + curscroll, ndents);
6689 ncols = adjust_cols(ncols);
6691 int len = scanselforpath(path, FALSE);
6694 for (i = curscroll; i < onscreen; ++i) {
6698 findmarkentry(len, &pdents[i]);
6700 printent(&pdents[i], ncols, i == cur);
6703 /* Must reset e.g. no files in dir */
6704 if (g_state.dircolor) {
6705 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6706 g_state.dircolor = 0;
6709 /* Go to last entry */
6710 if (onscreen < ndents) {
6711 move(xlines - 2, 0);
6712 #ifdef ICONS_ENABLED
6713 addstr(ICON_ARROW_DOWN);
6722 static bool cdprep(char *lastdir, char *lastname, char *path, char *newpath)
6727 /* Save last working directory */
6728 xstrsncpy(lastdir, path, PATH_MAX);
6730 /* Save the newly opted dir in path */
6731 xstrsncpy(path, newpath, PATH_MAX);
6735 return cfg.filtermode;
6738 static void showselsize(const char *path)
6741 int len = scanselforpath(path, FALSE);
6743 for (int r = 0, selcount = nselected; (r < ndents) && selcount; ++r)
6744 if (findinsel(findselpos, len + xstrsncpy(g_sel + len, pdents[r].name, pdents[r].nlen))) {
6745 sz += cfg.blkorder ? pdents[r].blocks : pdents[r].size;
6749 printmsg(coolsize(cfg.blkorder ? sz << blk_shift : sz));
6752 static bool browse(char *ipath, const char *session, int pkey)
6754 alignas(max_align_t) char newpath[PATH_MAX];
6755 alignas(max_align_t) char runfile[NAME_MAX + 1];
6756 char *path, *lastdir, *lastname, *dir, *tmp;
6760 int r = -1, presel, selstartid = 0, selendid = 0;
6761 const uchar_t opener_flags = (cfg.cliopener ? F_CLI : (F_NOTRACE | F_NOSTDIN | F_NOWAIT));
6762 bool watch = FALSE, cd = TRUE;
6767 struct timespec mousetimings[2] = {{.tv_sec = 0, .tv_nsec = 0}, {.tv_sec = 0, .tv_nsec = 0}};
6768 int mousedent[2] = {-1, -1};
6769 bool currentmouse = 1, rightclicksel = 0;
6774 getmaxyx(stdscr, xlines, xcols);
6777 /* set-up first context */
6778 if (!session || !load_session(session, &path, &lastdir, &lastname, FALSE)) {
6782 g_ctx[0].c_last[0] = '\0';
6783 lastdir = g_ctx[0].c_last; /* last visited directory */
6785 if (g_state.initfile) {
6786 xstrsncpy(g_ctx[0].c_name, xbasename(ipath), sizeof(g_ctx[0].c_name));
6789 g_ctx[0].c_name[0] = '\0';
6791 lastname = g_ctx[0].c_name; /* last visited file name */
6793 xstrsncpy(g_ctx[0].c_path, ipath, PATH_MAX);
6794 /* If the initial path is a file, retain a way to return to start dir */
6795 if (g_state.initfile) {
6797 initpath = ipath = getcwd(NULL, 0);
6799 path = g_ctx[0].c_path; /* current directory */
6801 g_ctx[0].c_fltr[0] = g_ctx[0].c_fltr[1] = '\0';
6802 g_ctx[0].c_cfg = cfg; /* current configuration */
6807 newpath[0] = runfile[0] = '\0';
6809 presel = pkey ? ((pkey == CREATE_NEW_KEY) ? 'n' : ';') : ((cfg.filtermode
6810 || (session && (g_ctx[cfg.curctx].c_fltr[0] == FILTER
6811 || g_ctx[cfg.curctx].c_fltr[0] == RFILTER)
6812 && g_ctx[cfg.curctx].c_fltr[1])) ? FILTER : 0);
6814 pdents = xrealloc(pdents, total_dents * sizeof(struct entry));
6818 /* Allocate buffer to hold names */
6819 pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
6823 /* The following call is added to handle a broken window at start */
6824 if (presel == FILTER)
6825 handle_key_resize();
6829 * Can fail when permissions change while browsing.
6830 * It's assumed that path IS a directory when we are here.
6832 if (chdir(path) == -1) {
6833 DPRINTF_S("directory inaccessible");
6834 valid_parent(path, lastname);
6842 #ifdef LINUX_INOTIFY
6843 if ((presel == FILTER || watch) && inotify_wd >= 0) {
6844 inotify_rm_watch(inotify_fd, inotify_wd);
6848 #elif defined(BSD_KQUEUE)
6849 if ((presel == FILTER || watch) && event_fd >= 0) {
6854 #elif defined(HAIKU_NM)
6855 if ((presel == FILTER || watch) && haiku_hnd != NULL) {
6856 haiku_stop_watch(haiku_hnd);
6857 haiku_nm_active = FALSE;
6863 if (cfgsort[cfg.curctx] != '0') {
6864 if (cfgsort[cfg.curctx] == 'z')
6865 set_sort_flags('c');
6866 if ((!cfgsort[cfg.curctx] || (cfgsort[cfg.curctx] == 'c'))
6867 && ((r = get_kv_key(order, path, maxorder, NNN_ORDER)) > 0)) { // NOLINT
6869 cfgsort[cfg.curctx] = 'z';
6872 cfgsort[cfg.curctx] = cfgsort[CTX_MAX];
6876 populate(path, lastname);
6877 if (g_state.interrupt) {
6878 g_state.interrupt = cfg.apparentsz = cfg.blkorder = 0;
6879 blk_shift = BLK_SHIFT_512;
6880 presel = CONTROL('L');
6883 #ifdef LINUX_INOTIFY
6884 if (presel != FILTER && inotify_wd == -1)
6885 inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
6886 #elif defined(BSD_KQUEUE)
6887 if (presel != FILTER && event_fd == -1) {
6888 #if defined(O_EVTONLY)
6889 event_fd = open(path, O_EVTONLY);
6891 event_fd = open(path, O_RDONLY);
6894 EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
6895 EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
6897 #elif defined(HAIKU_NM)
6898 haiku_nm_active = haiku_watch_dir(haiku_hnd, path) == EXIT_SUCCESS;
6902 /* Do not do a double redraw in filterentries */
6903 if ((presel != FILTER) || !filterset()) {
6909 /* Exit if parent has exited */
6911 _exit(EXIT_FAILURE);
6913 /* If CWD is deleted or moved or perms changed, find an accessible parent */
6914 if (chdir(path) == -1)
6917 /* If STDIN is no longer a tty (closed) we should exit */
6918 if (!isatty(STDIN_FILENO) && !g_state.picker)
6919 return EXIT_FAILURE;
6921 sel = nextsel(presel);
6928 if (getmouse(&event) != OK)
6931 /* Handle clicking on a context at the top */
6932 if (event.bstate == BUTTON1_PRESSED && event.y == 0) {
6933 /* Get context from: "[1 2 3 4]..." */
6936 /* If clicked after contexts, go to parent */
6939 else if (r >= 0 && r != cfg.curctx) {
6940 savecurctx(path, ndents ? pdents[cur].name : NULL, r);
6942 /* Reset the pointers */
6943 path = g_ctx[r].c_path;
6944 lastdir = g_ctx[r].c_last;
6945 lastname = g_ctx[r].c_name;
6955 if (sel == SEL_BACK) {
6957 dir = visit_parent(path, newpath, &presel);
6962 xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
6964 cdprep(lastdir, NULL, path, dir) ? (presel = FILTER) : (watch = TRUE);
6971 /* Middle click action */
6972 if (event.bstate == BUTTON2_PRESSED) {
6973 presel = middle_click_key;
6976 #if NCURSES_MOUSE_VERSION > 1
6978 if (event.bstate == BUTTON4_PRESSED && ndents && (cfg.rollover || cur)) {
6979 move_cursor((!cfg.rollover && cur < scroll_lines
6980 ? 0 : (cur + ndents - scroll_lines) % ndents), 0);
6985 if (event.bstate == BUTTON5_PRESSED && ndents
6986 && (cfg.rollover || (cur != ndents - 1))) {
6987 move_cursor((!cfg.rollover && cur >= ndents - scroll_lines)
6988 ? (ndents - 1) : ((cur + scroll_lines) % ndents), 0);
6993 /* Toggle filter mode on left click on last 2 lines */
6994 if (event.y >= xlines - 2 && event.bstate == BUTTON1_PRESSED) {
6996 cfg.filtermode ^= 1;
6997 if (cfg.filtermode) {
7002 /* Start watching the directory */
7009 /* Handle clicking on a file */
7010 if (event.y >= 2 && event.y <= ndents + 1 &&
7011 (event.bstate == BUTTON1_PRESSED ||
7012 event.bstate == BUTTON3_PRESSED)) {
7013 r = curscroll + (event.y - 2);
7017 else if ((event.bstate == BUTTON1_PRESSED) && !g_state.fifomode)
7018 notify_fifo(TRUE); /* Send clicked path to NNN_FIFO */
7020 /* Handle right click selection */
7021 if (event.bstate == BUTTON3_PRESSED) {
7029 #if defined(CLOCK_MONOTONIC_RAW)
7030 CLOCK_MONOTONIC_RAW,
7031 #elif defined(CLOCK_MONOTONIC)
7036 &mousetimings[currentmouse]);
7037 mousedent[currentmouse] = cur;
7039 /* Single click just selects, double click falls through to SEL_OPEN */
7040 if ((mousedent[0] != mousedent[1]) ||
7041 (((_ABSSUB(mousetimings[0].tv_sec, mousetimings[1].tv_sec) << 30)
7042 + (_ABSSUB(mousetimings[0].tv_nsec, mousetimings[1].tv_nsec)))
7043 > DBLCLK_INTERVAL_NS))
7046 mousetimings[currentmouse].tv_sec = 0;
7047 mousedent[currentmouse] = -1;
7050 if (cfg.filtermode || filterset())
7057 case SEL_NAV_IN: // fallthrough
7059 /* Cannot descend in empty directories */
7062 g_state.selbm = g_state.runplugin = 0;
7066 pent = &pdents[cur];
7067 if (!g_state.selbm || !(S_ISLNK(pent->mode) &&
7068 bmtarget(pent->name, path, newpath) &&
7069 xstrsncpy(path, lastdir, PATH_MAX)))
7070 mkpath(path, pent->name, newpath);
7074 /* Visit directory */
7075 if (pent->flags & DIR_OR_DIRLNK) {
7076 if (chdir(newpath) == -1) {
7081 cdprep(lastdir, lastname, path, newpath) ? (presel = FILTER) : (watch = TRUE);
7085 /* Cannot use stale data in entry, file may be missing by now */
7086 if (stat(newpath, &sb) == -1) {
7090 DPRINTF_U(sb.st_mode);
7092 /* Do not open non-regular files */
7093 if (!S_ISREG(sb.st_mode)) {
7094 printwait(messages[MSG_UNSUPPORTED], &presel);
7098 /* Handle plugin selection mode */
7099 if (g_state.runplugin) {
7100 g_state.runplugin = 0;
7101 /* Must be in plugin dir and same context to select plugin */
7102 if ((g_state.runctx == cfg.curctx) && !strcmp(path, plgpath)) {
7103 endselection(FALSE);
7104 /* Copy path so we can return back to earlier dir */
7105 xstrsncpy(path, lastdir, PATH_MAX);
7108 if (chdir(path) == -1
7109 || !run_plugin(&path, pent->name, runfile, &lastname, &lastdir)) {
7110 DPRINTF_S("plugin failed!");
7114 return EXIT_SUCCESS;
7117 xstrsncpy(lastname, runfile, NAME_MAX + 1);
7126 if (g_state.fifomode && (sel == SEL_OPEN)) {
7127 send_to_explorer(&presel); /* Write selection to explorer fifo */
7131 /* If opened as vim plugin and Enter/^M pressed, pick */
7132 if (g_state.picker && (sel == SEL_OPEN)) {
7133 if (nselected == 0) /* Pick if none selected */
7134 appendfpath(newpath, mkpath(path, pent->name, newpath));
7135 return EXIT_SUCCESS;
7138 if (sel == SEL_NAV_IN) {
7139 /* If in listing dir, go to target on `l` or Right on symlink */
7140 if (listpath && S_ISLNK(pent->mode)
7141 && is_prefix(path, listpath, xstrlen(listpath))) {
7142 if (!realpath(pent->name, newpath)) {
7149 if (chdir(newpath) == -1) {
7154 cdprep(lastdir, NULL, path, newpath)
7155 ? (presel = FILTER) : (watch = TRUE);
7156 xstrsncpy(lastname, pent->name, NAME_MAX + 1);
7160 /* Open file disabled on right arrow or `l` */
7166 printwait(messages[MSG_EMPTY_FILE], &presel);
7171 #ifdef FILE_MIME_OPTS
7172 && get_output("file", FILE_MIME_OPTS, newpath, -1, FALSE)
7173 && is_prefix(g_buf, "text/", 5)
7175 /* no MIME option; guess from description instead */
7176 && get_output("file", "-bL", newpath, -1, FALSE)
7177 && strstr(g_buf, "text")
7180 spawn(editor, newpath, NULL, NULL, F_CLI);
7181 if (cfg.filtermode) {
7188 /* Get the extension for regex match */
7189 tmp = xextension(pent->name, pent->nlen - 1);
7191 if (tmp && !pcre_exec(archive_pcre, NULL, tmp,
7192 pent->nlen - (tmp - pent->name) - 1, 0, 0, NULL, 0)) {
7194 if (tmp && !regexec(&archive_re, tmp, 0, NULL, 0)) {
7196 r = get_input(messages[MSG_ARCHIVE_OPTS]);
7199 if (r == 'l' || r == 'x') {
7200 mkpath(path, pent->name, newpath);
7201 if (!handle_archive(newpath, r)) {
7211 if ((r == 'm') && !archive_mount(newpath)) {
7216 if (r == 'x' || r == 'm') {
7218 set_smart_ctx('+', newpath, &path,
7219 ndents ? pdents[cur].name : NULL,
7220 &lastname, &lastdir);
7228 printwait(messages[MSG_INVALID_KEY], &presel);
7233 /* Invoke desktop opener as last resort */
7234 spawn(opener, newpath, NULL, NULL, opener_flags);
7236 /* Move cursor to the next entry if not the last entry */
7237 if (g_state.autonext && cur != ndents - 1)
7238 move_cursor((cur + 1) % ndents, 0);
7239 if (cfg.filtermode) {
7244 case SEL_NEXT: // fallthrough
7245 case SEL_PREV: // fallthrough
7246 case SEL_PGDN: // fallthrough
7247 case SEL_CTRL_D: // fallthrough
7248 case SEL_PGUP: // fallthrough
7249 case SEL_CTRL_U: // fallthrough
7250 case SEL_HOME: // fallthrough
7251 case SEL_END: // fallthrough
7252 case SEL_FIRST: // fallthrough
7253 case SEL_JUMP: // fallthrough
7257 handle_screen_move(sel);
7260 case SEL_CDHOME: // fallthrough
7261 case SEL_CDBEGIN: // fallthrough
7262 case SEL_CDLAST: // fallthrough
7264 dir = (sel == SEL_CDHOME) ? home
7265 : ((sel == SEL_CDBEGIN) ? ipath
7266 : ((sel == SEL_CDLAST) ? lastdir
7267 : "/" /* SEL_CDROOT */));
7269 if (!dir || !*dir) {
7270 printwait(messages[MSG_NOT_SET], &presel);
7275 if (strcmp(path, dir) == 0) {
7281 dir = lastdir; /* Go to last dir on home/root key repeat */
7284 if (chdir(dir) == -1) {
7289 /* SEL_CDLAST: dir pointing to lastdir */
7290 xstrsncpy(newpath, dir, PATH_MAX); // fallthrough
7292 if (sel == SEL_BMOPEN) {
7293 r = (int)handle_bookmark(mark, newpath);
7295 printwait(messages[r], &presel);
7299 if (g_state.selbm == 1) /* Allow filtering in bookmarks directory */
7301 if (strcmp(path, newpath) == 0)
7305 /* In list mode, retain the last file name to highlight it, if possible */
7306 cdprep(lastdir, listpath && sel == SEL_CDLAST ? NULL : lastname, path, newpath)
7307 ? (presel = FILTER) : (watch = TRUE);
7310 if ((sel == SEL_REMOTE) && !remote_mount(newpath)) {
7315 set_smart_ctx('+', newpath, &path,
7316 ndents ? pdents[cur].name : NULL, &lastname, &lastdir);
7319 case SEL_CYCLE: // fallthrough
7320 case SEL_CYCLER: // fallthrough
7321 case SEL_CTX1: // fallthrough
7322 case SEL_CTX2: // fallthrough
7323 case SEL_CTX3: // fallthrough
7331 r = handle_context_switch(sel);
7334 savecurctx(path, ndents ? pdents[cur].name : NULL, r);
7336 /* Reset the pointers */
7337 path = g_ctx[r].c_path;
7338 lastdir = g_ctx[r].c_last;
7339 lastname = g_ctx[r].c_name;
7340 tmp = g_ctx[r].c_fltr;
7342 if (cfg.filtermode || ((tmp[0] == FILTER || tmp[0] == RFILTER) && tmp[1]))
7350 mark = xstrdup(path);
7351 printwait(mark, &presel);
7354 add_bookmark(path, newpath, &presel);
7357 /* Unwatch dir if we are still in a filtered view */
7358 #ifdef LINUX_INOTIFY
7359 if (inotify_wd >= 0) {
7360 inotify_rm_watch(inotify_fd, inotify_wd);
7363 #elif defined(BSD_KQUEUE)
7364 if (event_fd >= 0) {
7368 #elif defined(HAIKU_NM)
7369 if (haiku_nm_active) {
7370 haiku_stop_watch(haiku_hnd);
7371 haiku_nm_active = FALSE;
7374 presel = filterentries(path, lastname);
7375 if (presel == ESC) {
7379 if (presel == FILTER) { /* Refresh dir and filter again */
7384 case SEL_MFLTR: // fallthrough
7385 case SEL_HIDDEN: // fallthrough
7386 case SEL_DETAIL: // fallthrough
7390 cfg.filtermode ^= 1;
7391 if (cfg.filtermode) {
7397 watch = TRUE; // fallthrough
7399 if (sel == SEL_HIDDEN) {
7400 cfg.showhidden ^= 1;
7409 cfg.showdetail ^= 1;
7412 default: /* SEL_SORT */
7413 r = set_sort_flags(get_input(messages[MSG_ORDER]));
7415 printwait(messages[MSG_INVALID_KEY], &presel);
7420 if (cfg.filtermode || filterset())
7426 if (r == 'd' || r == 'a') {
7431 ENTSORT(pdents, ndents, entrycmpfn);
7432 move_cursor(ndents ? dentfind(lastname, ndents) : 0, 0);
7435 case SEL_STATS: // fallthrough
7438 tmp = (listpath && xstrcmp(path, listpath) == 0) ? listroot : path;
7439 mkpath(tmp, pdents[cur].name, newpath);
7441 if ((sel == SEL_STATS && !show_stats(newpath))
7442 || (lstat(newpath, &sb) == -1)
7443 || (sel == SEL_CHMODX && !xchmod(newpath, &sb.st_mode))) {
7448 if (sel == SEL_CHMODX)
7449 pdents[cur].mode = sb.st_mode;
7452 case SEL_REDRAW: // fallthrough
7453 case SEL_RENAMEMUL: // fallthrough
7454 case SEL_HELP: // fallthrough
7455 case SEL_AUTONEXT: // fallthrough
7456 case SEL_EDIT: // fallthrough
7457 case SEL_VIEW: // fallthrough
7460 bool refresh = FALSE;
7463 mkpath(path, pdents[cur].name, newpath);
7464 else if ((sel == SEL_EDIT) || (sel == SEL_VIEW)) /* Avoid trying to edit a non-existing file */
7473 setenv("NNN_INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
7474 setenv("NNN_PREFER_SELECTION", xitoa(cfg.prefersel), 1);
7475 setenv("NNN_LIST", listpath ? listroot : "", 1);
7477 if (!(getutil(utils[UTIL_BASH])
7478 && plugscript(utils[UTIL_NMV], F_CLI))
7483 printwait(messages[MSG_FAILED], &presel);
7490 show_help(path); // fallthrough
7492 if (sel == SEL_AUTONEXT)
7493 g_state.autonext ^= 1;
7499 if (!(g_state.picker || g_state.fifomode))
7500 spawn(editor, newpath, NULL, NULL, F_CLI);
7503 if (!(g_state.picker || g_state.fifomode))
7504 spawn("less --clear-screen", newpath, NULL, NULL, F_CLI);
7506 default: /* SEL_LOCK */
7511 /* In case of successful operation, reload contents */
7513 /* Continue in type-to-nav mode, if enabled */
7514 if ((cfg.filtermode || filterset()) && !refresh) {
7521 /* Repopulate as directory content may have changed */
7530 if (g_state.rangesel)
7531 g_state.rangesel = 0;
7533 /* Toggle selection status */
7534 pdents[cur].flags ^= FILE_SELECTED;
7536 if (pdents[cur].flags & FILE_SELECTED) {
7538 appendfpath(newpath, mkpath(path, pdents[cur].name, newpath));
7539 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
7542 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
7547 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7554 /* move cursor to the next entry if this is not the last entry */
7555 if (!g_state.stayonsel && (cur != ndents - 1))
7556 move_cursor((cur + 1) % ndents, 0);
7563 g_state.rangesel ^= 1;
7565 if (stat(path, &sb) == -1) {
7570 if (g_state.rangesel) { /* Range selection started */
7576 if (inode != sb.st_ino) {
7577 printwait(messages[MSG_DIR_CHANGED], &presel);
7581 if (cur < selstartid) {
7582 selendid = selstartid;
7587 /* Clear selection on repeat on same file */
7588 if (selstartid == selendid) {
7593 case SEL_SELALL: // fallthrough
7595 if (sel == SEL_SELALL || sel == SEL_SELINV) {
7600 if (g_state.rangesel)
7601 g_state.rangesel = 0;
7604 selendid = ndents - 1;
7607 if ((nselected > LARGESEL) || (nselected && (ndents > LARGESEL))) {
7608 printmsg("processing...");
7612 r = scanselforpath(path, TRUE); /* Get path length suffixed by '/' */
7613 ((sel == SEL_SELINV) && findselpos)
7614 ? invertselbuf(r) : addtoselbuf(r, selstartid, selendid);
7618 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7622 r = editselection();
7624 r = !r ? MSG_0_SELECTED : MSG_FAILED;
7625 printwait(messages[r], &presel);
7629 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7631 cfg.filtermode ? presel = FILTER : statusbar(path);
7634 case SEL_CP: // fallthrough
7635 case SEL_MV: // fallthrough
7636 case SEL_CPMVAS: // fallthrough
7639 if (sel == SEL_RM) {
7640 r = get_cur_or_sel();
7647 tmp = (listpath && xstrcmp(path, listpath) == 0)
7649 mkpath(tmp, pdents[cur].name, newpath);
7653 xrmfromsel(tmp, newpath);
7655 copynextname(lastname);
7657 if (cfg.filtermode || filterset())
7664 (nselected == 1 && (sel == SEL_CP || sel == SEL_MV))
7665 ? mkpath(path, xbasename(pselbuf), newpath)
7666 : (newpath[0] = '\0');
7670 if (!cpmvrm_selection(sel, path)) {
7680 /* Show notification on operation complete */
7682 plugscript(utils[UTIL_NTFY], F_NOWAIT | F_NOTRACE);
7685 if (newpath[0] && !access(newpath, F_OK))
7686 xstrsncpy(lastname, xbasename(newpath), NAME_MAX+1);
7692 case SEL_ARCHIVE: // fallthrough
7693 case SEL_OPENWITH: // fallthrough
7694 case SEL_NEW: // fallthrough
7700 if (!ndents && (sel == SEL_OPENWITH || sel == SEL_RENAME))
7703 if (sel != SEL_OPENWITH)
7708 r = get_cur_or_sel();
7722 tmp = pdents[cur].name;
7724 tmp = xreadline(tmp, messages[MSG_ARCHIVE_NAME]);
7728 if (g_state.picker || g_state.xprompt) {
7730 tmp = xreadline(NULL, messages[MSG_OPEN_WITH]);
7733 tmp = getreadline(messages[MSG_OPEN_WITH]);
7738 r = get_input(messages[MSG_NEW_OPTS]);
7744 tmp = g_ctx[0].c_name;
7748 if (r == 'f' || r == 'd')
7749 tmp = xreadline(tmp, messages[MSG_NEW_PATH]);
7750 else if (r == 's' || r == 'h')
7751 tmp = xreadline((nselected == 1 && cfg.prefersel) ? xbasename(pselbuf) : NULL,
7752 messages[nselected <= 1 ? MSG_NEW_PATH : MSG_LINK_PREFIX]);
7756 default: /* SEL_RENAME */
7757 tmp = xreadline(pdents[cur].name, "");
7761 if (!tmp || !*tmp || is_bad_len_or_dir(tmp))
7766 if (r == 'c' && strcmp(tmp, pdents[cur].name) == 0)
7767 continue; /* Cannot overwrite the hovered file */
7769 tmp = abspath(tmp, NULL, newpath);
7772 if (access(tmp, F_OK) == 0) {
7773 if (!xconfirm(get_input(messages[MSG_OVERWRITE]))) {
7779 (r == 's') ? archive_selection(get_archive_cmd(tmp), tmp)
7780 : spawn(get_archive_cmd(tmp), tmp, pdents[cur].name,
7781 NULL, F_CLI | F_CONFIRM);
7783 if (tmp && (access(tmp, F_OK) == 0)) { /* File created */
7785 clearselection(); /* Archive operation complete */
7787 /* Check if any entry is created in the current directory */
7788 tmp = get_cwd_entry(path, tmp, &len);
7790 xstrsncpy(lastname, tmp, len + 1);
7791 clearfilter(); /* Archive name may not match */
7792 } if (cfg.filtermode)
7799 handle_openwith(path, pdents[cur].name, newpath, tmp);
7801 cfg.filtermode ? presel = FILTER : statusbar(path);
7806 /* Skip renaming to same name */
7807 if (strcmp(tmp, pdents[cur].name) == 0) {
7808 tmp = xreadline(pdents[cur].name, messages[MSG_COPY_NAME]);
7809 if (!tmp || !tmp[0] || is_bad_len_or_dir(tmp)
7810 || !strcmp(tmp, pdents[cur].name)) {
7811 cfg.filtermode ? presel = FILTER : statusbar(path);
7818 default: /* SEL_NEW */
7822 if (!(r == 's' || r == 'h')) {
7823 tmp = abspath(tmp, path, newpath);
7830 /* Check if another file with same name exists */
7831 if (lstat(tmp, &sb) == 0) {
7832 if ((sel == SEL_RENAME) || ((r == 'f') && (S_ISREG(sb.st_mode)))) {
7833 /* Overwrite file with same name? */
7834 if (!xconfirm(get_input(messages[MSG_OVERWRITE])))
7837 /* Do nothing for SEL_NEW if a non-regular entry exists */
7838 printwait(messages[MSG_EXISTS], &presel);
7843 if (sel == SEL_RENAME) {
7844 /* Rename the file */
7846 spawn("cp -rp", pdents[cur].name, tmp, NULL, F_SILENT);
7847 else if (rename(pdents[cur].name, tmp) != 0) {
7852 /* Check if any entry is created in the current directory */
7853 tmp = get_cwd_entry(path, tmp, &len);
7855 xstrsncpy(lastname, tmp, len + 1);
7856 /* Directory must be reloeaded for rename case */
7857 } else { /* SEL_NEW */
7860 /* Check if it's a dir or file */
7861 if (r == 'f' || r == 'd') {
7862 ret = xmktree(tmp, r == 'f' ? FALSE : TRUE);
7863 } else if (r == 's' || r == 'h') {
7864 if (nselected > 1 && tmp[0] == '@' && tmp[1] == '\0')
7866 ret = xlink(tmp, path, (ndents ? pdents[cur].name : NULL), newpath, r);
7875 if (r == 'f' || r == 'd') {
7876 tmp = get_cwd_entry(path, tmp, &len);
7878 xstrsncpy(lastname, tmp, len + 1);
7880 continue; /* No change in directory */
7881 } else if (ndents) {
7892 case SEL_CD: // fallthrough
7894 if (!xdiraccess(plgpath)) {
7898 endselection(FALSE);
7899 tmp = sel == SEL_CD ? "!_nnn-cd*" : "!_nnn-cp";
7900 if (!run_plugin(&path, tmp, (ndents ? pdents[cur].name : NULL),
7901 &lastname, &lastdir)) {
7902 printwait(messages[MSG_FAILED], &presel);
7909 /* Check if directory is accessible */
7910 if (!xdiraccess(plgpath)) {
7916 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
7917 printkeys(plug, g_buf + r - 1, maxplug);
7919 r = get_input(NULL);
7926 endselection(FALSE);
7927 tmp = get_kv_val(plug, NULL, r, maxplug, NNN_PLUG);
7929 printwait(messages[MSG_INVALID_KEY], &presel);
7933 if (tmp[0] == '-' && tmp[1]) {
7935 r = FALSE; /* Do not refresh dir after completion */
7939 if (!run_plugin(&path, tmp, (ndents ? pdents[cur].name : NULL),
7940 &lastname, &lastdir)) {
7941 printwait(messages[MSG_FAILED], &presel);
7946 return EXIT_SUCCESS;
7951 cfg.filtermode ? presel = FILTER : statusbar(path);
7954 } else { /* 'Return/Enter' enters the plugin directory */
7955 g_state.runplugin ^= 1;
7956 if (!g_state.runplugin) {
7958 * If toggled, and still in the plugin dir,
7959 * switch to original directory
7961 if (strcmp(path, plgpath) == 0) {
7962 xstrsncpy(path, lastdir, PATH_MAX);
7963 xstrsncpy(lastname, runfile, NAME_MAX + 1);
7969 /* Otherwise, initiate choosing plugin again */
7970 g_state.runplugin = 1;
7973 xstrsncpy(lastdir, path, PATH_MAX);
7974 xstrsncpy(path, plgpath, PATH_MAX);
7976 xstrsncpy(runfile, pdents[cur].name, NAME_MAX);
7977 g_state.runctx = cfg.curctx;
7982 if (g_state.runplugin == 1) /* Allow filtering in plugins directory */
7988 case SEL_SHELL: // fallthrough
7989 case SEL_LAUNCH: // fallthrough
7991 r = handle_cmd(sel, newpath);
7993 /* Continue in type-to-nav mode, if enabled */
8003 /* Repopulate as directory content may have changed */
8008 if (!unmount((ndents ? pdents[cur].name : NULL), newpath, &presel, path)) {
8009 if (presel == MSG_ZERO)
8014 /* Dir removed, go to next entry */
8015 copynextname(lastname);
8020 r = get_input(messages[MSG_SSN_OPTS]);
8023 tmp = xreadline(NULL, messages[MSG_SSN_NAME]);
8025 save_session(tmp, &presel);
8026 } else if (r == 'l' || r == 'r') {
8027 if (load_session(NULL, &path, &lastdir, &lastname, r == 'r')) {
8038 cfg.filtermode ? presel = FILTER : statusbar(path);
8041 if (!set_time_type(&presel))
8045 case SEL_QUITCTX: // fallthrough
8046 case SEL_QUITCD: // fallthrough
8049 if (sel == SEL_QUITCTX) {
8050 int ctx = cfg.curctx;
8052 for (r = (ctx - 1) & (CTX_MAX - 1);
8053 (r != ctx) && !g_ctx[r].c_cfg.ctxactive;
8054 r = ((r - 1) & (CTX_MAX - 1))) {
8058 g_ctx[ctx].c_cfg.ctxactive = 0;
8060 /* Switch to next active context */
8061 path = g_ctx[r].c_path;
8062 lastdir = g_ctx[r].c_last;
8063 lastname = g_ctx[r].c_name;
8065 g_ctx[r].c_cfg.curctx = r;
8066 setcfg(g_ctx[r].c_cfg);
8071 } else if (!g_state.forcequit) {
8072 for (r = 0; r < CTX_MAX; ++r)
8073 if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
8074 r = get_input(messages[MSG_QUIT_ALL]);
8078 if (!(r == CTX_MAX || xconfirm(r)))
8079 break; // fallthrough
8083 tmp = getenv("NNN_TMPFILE");
8084 if ((sel == SEL_QUITCD) || tmp) {
8085 write_lastdir(path, tmp);
8086 /* ^G is a way to quit picker mode without picking anything */
8087 if ((sel == SEL_QUITCD) && g_state.picker)
8091 if (sel != SEL_QUITERR)
8092 return EXIT_SUCCESS;
8094 if (selbufpos && !g_state.picker) {
8095 /* Pick files to stdout and exit */
8099 return EXIT_SUCCESS;
8102 return EXIT_FAILURE;
8104 if (xlines != LINES || xcols != COLS)
8107 if (idletimeout && idle == idletimeout) {
8108 lock_terminal(); /* Locker */
8114 } /* switch (sel) */
8118 static char *make_tmp_tree(char **paths, ssize_t entries, const char *prefix)
8120 /* tmpdir holds the full path */
8121 /* tmp holds the path without the tmp dir prefix */
8125 ssize_t len = xstrlen(prefix);
8126 char *tmpdir = malloc(PATH_MAX);
8129 DPRINTF_S(strerror(errno));
8133 tmp = tmpdir + tmpfplen - 1;
8134 xstrsncpy(tmpdir, g_tmpfpath, tmpfplen);
8135 xstrsncpy(tmp, "/nnnXXXXXX", 11);
8137 /* Points right after the base tmp dir */
8140 /* handle the case where files are directly under / */
8141 if (!prefix[1] && (prefix[0] == '/'))
8144 if (!mkdtemp(tmpdir)) {
8147 DPRINTF_S(strerror(errno));
8153 for (ssize_t i = 0; i < entries; ++i) {
8157 err = stat(paths[i], &sb);
8158 if (err && errno == ENOENT)
8161 /* Don't copy the common prefix */
8162 xstrsncpy(tmp, paths[i] + len, xstrlen(paths[i]) - len + 1);
8164 /* Get the dir containing the path */
8165 slash = xmemrchr((uchar_t *)tmp, '/', xstrlen(paths[i]) - len);
8169 if (access(tmpdir, F_OK)) /* Create directory if it doesn't exist */
8170 xmktree(tmpdir, TRUE);
8175 if (symlink(paths[i], tmpdir)) {
8176 DPRINTF_S(paths[i]);
8177 DPRINTF_S(strerror(errno));
8181 /* Get the dir in which to start */
8186 static char *load_input(int fd, const char *path)
8188 size_t i, chunk_count = 1, chunk = 512UL * 1024 /* 512 KiB chunk size */, entries = 0;
8189 char *input = malloc(sizeof(char) * chunk), *tmpdir = NULL;
8190 char cwd[PATH_MAX], *next;
8191 size_t offsets[LIST_FILES_MAX];
8192 char **paths = NULL;
8193 ssize_t input_read, total_read = 0, off = 0;
8197 DPRINTF_S(strerror(errno));
8202 if (!getcwd(cwd, PATH_MAX)) {
8207 xstrsncpy(cwd, path, PATH_MAX);
8209 while (chunk_count < LIST_INPUT_MAX / chunk && !msgnum) {
8210 input_read = read(fd, input + total_read, chunk);
8211 if (input_read < 0) {
8215 DPRINTF_S(strerror(errno));
8219 if (input_read == 0)
8222 total_read += input_read;
8224 while (off < total_read) {
8225 next = memchr(input + off, '\0', total_read - off);
8230 if (next - input == off + 1) {
8235 if (entries == LIST_FILES_MAX) {
8236 msgnum = MSG_FILE_LIMIT;
8240 offsets[entries++] = off;
8244 /* We don't need to allocate another chunk */
8245 if (chunk_count > (total_read + chunk - 1) / chunk)
8248 /* We can never need more than one additional chunk */
8250 if (chunk_count > LIST_INPUT_MAX / chunk) {
8251 msgnum = MSG_SIZE_LIMIT;
8255 input = xrealloc(input, chunk_count * chunk);
8260 /* We close fd outside this function. Any extra data is left to the kernel to handle */
8262 if (off != total_read) {
8263 if (entries == LIST_FILES_MAX)
8264 msgnum = MSG_FILE_LIMIT;
8266 offsets[entries++] = off;
8270 DPRINTF_D(total_read);
8271 DPRINTF_D(chunk_count);
8274 msgnum = MSG_0_ENTRIES;
8278 input[total_read] = '\0';
8280 paths = malloc(entries * sizeof(char *));
8284 for (i = 0; i < entries; ++i)
8285 paths[i] = input + offsets[i];
8287 listroot = malloc(sizeof(char) * PATH_MAX);
8292 DPRINTF_S(paths[0]);
8294 for (i = 0; i < entries; ++i) {
8295 if (paths[i][0] == '\n' || selforparent(paths[i])) {
8300 paths[i] = abspath(paths[i], cwd, NULL);
8302 entries = i; // free from the previous entry
8306 DPRINTF_S(paths[i]);
8308 xstrsncpy(g_buf, paths[i], PATH_MAX);
8309 if (!common_prefix(xdirname(g_buf), listroot)) {
8310 entries = i + 1; // free from the current entry
8314 DPRINTF_S(listroot);
8317 DPRINTF_S(listroot);
8320 tmpdir = make_tmp_tree(paths, entries, listroot);
8323 for (i = 0; i < entries; ++i)
8326 if (msgnum) { /* Check if we are past init stage and show msg */
8328 printmsg(messages[msgnum]);
8329 xdelay(XDELAY_INTERVAL_MS << 2);
8331 msg(messages[msgnum]);
8332 usleep(XDELAY_INTERVAL_MS << 2);
8341 static void check_key_collision(void)
8344 bool bitmap[KEY_MAX] = {FALSE};
8346 for (ullong_t i = 0; i < ELEMENTS(bindings); ++i) {
8347 key = bindings[i].sym;
8350 dprintf(STDERR_FILENO, "key collision! [%s]\n", keyname(key));
8356 static void usage(void)
8358 dprintf(STDOUT_FILENO,
8359 "%s: nnn [OPTIONS] [PATH]\n\n"
8360 "The unorthodox terminal file manager.\n\n"
8361 "positional args:\n"
8362 " PATH start dir/file [default: .]\n\n"
8365 " -a auto NNN_FIFO\n"
8367 " -A no dir auto-enter during filter\n"
8368 " -b key open bookmark key (trumps -s/S)\n"
8369 " -B use bsdtar for archives\n"
8370 " -c cli-only NNN_OPENER (trumps -e)\n"
8371 " -C 8-color scheme\n"
8373 " -D dirs in context color\n"
8374 " -e text in $VISUAL/$EDITOR/vi\n"
8375 " -E internal edits in EDITOR\n"
8377 " -f use readline history file\n"
8380 " -F val fifo mode [0:preview 1:explore]\n"
8382 " -g regex filters\n"
8383 " -H show hidden files\n"
8384 " -i show current file info\n"
8385 " -J no auto-advance on selection\n"
8386 " -K detect key collision and exit\n"
8387 " -l val set scroll lines\n"
8388 " -n type-to-nav mode\n"
8390 " -N use native prompt\n"
8392 " -o open files only on Enter\n"
8393 " -p file selection file [-:stdout]\n"
8394 " -P key run plugin key\n"
8395 " -Q no quit confirmation\n"
8396 " -r use advcpmv patched cp, mv\n"
8397 " -R no rollover at edges\n"
8399 " -s name load session by name\n"
8400 " -S persistent session\n"
8402 " -t secs timeout to lock\n"
8403 " -T key sort order [a/d/e/r/s/t/v]\n"
8404 " -u use selection (no prompt)\n"
8406 " -U show user and group\n"
8408 " -V show version\n"
8410 " -x notis, selection sync, xterm title\n"
8413 "v%s\n%s\n", __func__, VERSION, GENERAL_INFO);
8416 static bool setup_config(void)
8419 char *xdgcfg = getenv("XDG_CONFIG_HOME");
8422 /* Set up configuration file paths */
8423 if (xdgcfg && xdgcfg[0]) {
8425 if (tilde_is_home(xdgcfg)) {
8426 r = xstrsncpy(g_buf, home, PATH_MAX);
8427 xstrsncpy(g_buf + r - 1, xdgcfg + 1, PATH_MAX);
8432 if (!xdiraccess(xdgcfg)) {
8437 len = xstrlen(xdgcfg) + xstrlen("/nnn/bookmarks") + 1;
8442 len = xstrlen(home) + xstrlen("/.config/nnn/bookmarks") + 1;
8444 cfgpath = (char *)malloc(len);
8445 plgpath = (char *)malloc(len);
8446 if (!cfgpath || !plgpath) {
8452 xstrsncpy(cfgpath, xdgcfg, len);
8453 r = len - xstrlen("/nnn/bookmarks");
8455 r = xstrsncpy(cfgpath, home, len);
8457 /* Create ~/.config */
8458 xstrsncpy(cfgpath + r - 1, "/.config", len - r);
8460 r += 8; /* length of "/.config" */
8463 /* Create ~/.config/nnn */
8464 xstrsncpy(cfgpath + r - 1, "/nnn", len - r);
8467 /* Create bookmarks, sessions, mounts and plugins directories */
8468 for (r = 0; r < ELEMENTS(toks); ++r) {
8469 mkpath(cfgpath, toks[r], plgpath);
8470 /* The dirs are created on first run, check if they already exist */
8471 if (access(plgpath, F_OK) && !xmktree(plgpath, TRUE)) {
8478 /* Set selection file path */
8479 if (!g_state.picker) {
8480 char *env_sel = xgetenv(env_cfg[NNN_SEL], NULL);
8482 selpath = env_sel ? xstrdup(env_sel)
8483 : (char *)malloc(len + 3); /* Length of "/.config/nnn/.selection" */
8491 r = xstrsncpy(selpath, cfgpath, len + 3);
8492 xstrsncpy(selpath + r - 1, "/.selection", 12);
8500 static bool set_tmp_path(void)
8503 char *path = xdiraccess(tmp) ? tmp : getenv("TMPDIR");
8510 tmpfplen = (uchar_t)xstrsncpy(g_tmpfpath, path, TMP_LEN_MAX);
8511 DPRINTF_S(g_tmpfpath);
8512 DPRINTF_U(tmpfplen);
8517 static void cleanup(void)
8520 if (cfg.x11 && !g_state.picker) {
8521 printf("\033[23;0t"); /* reset terminal window title */
8537 if (g_state.autofifo)
8540 if (g_state.pluginit)
8547 int main(int argc, char *argv[])
8550 char *session = NULL;
8551 int fd, opt, sort = 0, pkey = '\0'; /* Plugin key */
8554 char *middle_click_env = xgetenv(env_cfg[NNN_MCLICK], "\0");
8556 middle_click_key = (middle_click_env[0] == '^' && middle_click_env[1])
8557 ? CONTROL(middle_click_env[1])
8558 : (uchar_t)middle_click_env[0];
8561 const char * const env_opts = xgetenv(env_cfg[NNN_OPTS], NULL);
8562 int env_opts_id = env_opts ? (int)xstrlen(env_opts) : -1;
8564 bool rlhist = FALSE;
8567 while ((opt = (env_opts_id > 0
8568 ? env_opts[--env_opts_id]
8569 : getopt(argc, argv, "aAb:BcCdDeEfF:gHiJKl:nNop:P:QrRs:St:T:uUVxh"))) != -1) {
8573 g_state.autofifo = 1;
8580 if (env_opts_id < 0)
8584 g_state.usebsdtar = 1;
8590 g_state.oldcolor = 1;
8611 if (env_opts_id < 0) {
8613 if ((fd < 0) || (fd > 1))
8614 return EXIT_FAILURE;
8615 g_state.fifomode = fd;
8621 filterfn = &visible_re;
8630 g_state.stayonsel = 1;
8633 check_key_collision();
8634 return EXIT_SUCCESS;
8636 if (env_opts_id < 0)
8637 scroll_lines = atoi(optarg);
8644 g_state.xprompt = 1;
8651 if (env_opts_id >= 0)
8655 if (!(optarg[0] == '-' && optarg[1] == '\0')) {
8656 fd = open(optarg, O_WRONLY | O_CREAT, 0600);
8659 return EXIT_FAILURE;
8663 selpath = abspath(optarg, NULL, NULL);
8668 if (env_opts_id < 0 && !optarg[1])
8669 pkey = (uchar_t)optarg[0];
8672 g_state.forcequit = 1;
8676 memcpy(cp, PROGRESS_CP, sizeof PROGRESS_CP);
8677 memcpy(mv, PROGRESS_MV, sizeof PROGRESS_MV);
8685 if (env_opts_id < 0)
8689 g_state.prstssn = 1;
8690 if (!session) /* Support named persistent sessions */
8695 if (env_opts_id < 0)
8696 idletimeout = atoi(optarg);
8699 if (env_opts_id < 0)
8700 sort = (uchar_t)optarg[0];
8709 dprintf(STDOUT_FILENO, "%s\n", VERSION);
8710 return EXIT_SUCCESS;
8716 return EXIT_SUCCESS;
8719 return EXIT_FAILURE;
8721 if (env_opts_id == 0)
8730 /* Prefix for temporary files */
8731 if (!set_tmp_path())
8732 return EXIT_FAILURE;
8736 /* Check if we are in path list mode */
8737 if (!isatty(STDIN_FILENO)) {
8738 /* This is the same as listpath */
8739 initpath = load_input(STDIN_FILENO, NULL);
8741 return EXIT_FAILURE;
8743 /* We return to tty */
8744 if (!isatty(STDOUT_FILENO)) {
8745 fd = open(ctermid(NULL), O_RDONLY, 0400);
8746 dup2(fd, STDIN_FILENO);
8749 dup2(STDOUT_FILENO, STDIN_FILENO);
8755 home = getenv("HOME");
8758 return EXIT_FAILURE;
8761 homelen = (uchar_t)xstrlen(home);
8763 if (!setup_config())
8764 return EXIT_FAILURE;
8766 /* Get custom opener, if set */
8767 opener = xgetenv(env_cfg[NNN_OPENER], utils[UTIL_OPENER]);
8770 /* Parse bookmarks string */
8771 if (!parsekvpair(&bookmark, &bmstr, NNN_BMS, &maxbm)) {
8772 msg(env_cfg[NNN_BMS]);
8773 return EXIT_FAILURE;
8776 /* Parse plugins string */
8777 if (!parsekvpair(&plug, &pluginstr, NNN_PLUG, &maxplug)) {
8778 msg(env_cfg[NNN_PLUG]);
8779 return EXIT_FAILURE;
8782 /* Parse order string */
8783 if (!parsekvpair(&order, &orderstr, NNN_ORDER, &maxorder)) {
8784 msg(env_cfg[NNN_ORDER]);
8785 return EXIT_FAILURE;
8789 if (arg) { /* Open a bookmark directly */
8790 if (!arg[1]) /* Bookmarks keys are single char */
8791 initpath = get_kv_val(bookmark, NULL, *arg, maxbm, NNN_BMS);
8794 msg(messages[MSG_INVALID_KEY]);
8795 return EXIT_FAILURE;
8800 } else if (argc == optind) {
8801 /* Start in the current directory */
8802 char *startpath = getenv("PWD");
8804 initpath = (startpath && *startpath) ? xstrdup(startpath) : getcwd(NULL, 0);
8807 } else { /* Open a file */
8810 size_t len = xstrlen(arg);
8812 if (len > 7 && is_prefix(arg, "file://", 7)) {
8816 initpath = abspath(arg, NULL, NULL);
8817 DPRINTF_S(initpath);
8820 return EXIT_FAILURE;
8823 /* If the file is hidden, enable hidden option */
8824 if (*xbasename(initpath) == '.')
8828 * If nnn is set as the file manager, applications may try to open
8829 * files by invoking nnn. In that case pass the file path to the
8830 * desktop opener and exit.
8834 if (stat(initpath, &sb) == -1) {
8835 bool dir = (arg[len - 1] == '/');
8838 arg = xbasename(initpath);
8839 initpath = xdirname(initpath);
8841 pkey = CREATE_NEW_KEY; /* Override plugin key */
8842 g_state.initfile = 1;
8844 if (dir || (arg != initpath)) { /* We have a directory */
8845 if (!xdiraccess(initpath) && !xmktree(initpath, TRUE)) {
8846 xerror(); /* Fail if directory cannot be created */
8847 return EXIT_FAILURE;
8849 if (!dir) /* Restore the complete path */
8852 } else if (!S_ISDIR(sb.st_mode))
8853 g_state.initfile = 1;
8860 /* Set archive handling (enveditor used as tmp var) */
8861 enveditor = getenv(env_cfg[NNN_ARCHIVE]);
8863 if (setfilter(&archive_pcre, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8865 if (setfilter(&archive_re, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8867 msg(messages[MSG_INVALID_REG]);
8868 return EXIT_FAILURE;
8871 /* An all-CLI opener overrides option -e) */
8875 /* Get VISUAL/EDITOR */
8876 enveditor = xgetenv(envs[ENV_EDITOR], utils[UTIL_VI]);
8877 editor = xgetenv(envs[ENV_VISUAL], enveditor);
8878 DPRINTF_S(getenv(envs[ENV_VISUAL]));
8879 DPRINTF_S(getenv(envs[ENV_EDITOR]));
8883 pager = xgetenv(envs[ENV_PAGER], utils[UTIL_LESS]);
8887 shell = xgetenv(envs[ENV_SHELL], utils[UTIL_SH]);
8890 DPRINTF_S(getenv("PWD"));
8894 if (g_state.autofifo) {
8895 g_tmpfpath[tmpfplen - 1] = '\0';
8897 size_t r = mkpath(g_tmpfpath, "nnn-fifo.", g_buf);
8899 xstrsncpy(g_buf + r - 1, xitoa(getpid()), PATH_MAX - r);
8900 setenv("NNN_FIFO", g_buf, TRUE);
8903 fifopath = xgetenv("NNN_FIFO", NULL);
8905 if (mkfifo(fifopath, 0600) != 0 && !(errno == EEXIST && access(fifopath, W_OK) == 0)) {
8907 return EXIT_FAILURE;
8910 sigaction(SIGPIPE, &(struct sigaction){.sa_handler = SIG_IGN}, NULL);
8914 #ifdef LINUX_INOTIFY
8915 /* Initialize inotify */
8916 inotify_fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
8917 if (inotify_fd < 0) {
8919 return EXIT_FAILURE;
8921 #elif defined(BSD_KQUEUE)
8925 return EXIT_FAILURE;
8927 #elif defined(HAIKU_NM)
8928 haiku_hnd = haiku_init_nm();
8931 return EXIT_FAILURE;
8935 /* Configure trash preference */
8936 opt = xgetenv_val(env_cfg[NNN_TRASH]);
8937 if (opt && opt <= 2)
8938 g_state.trash = opt;
8940 /* Ignore/handle certain signals */
8941 struct sigaction act = {.sa_handler = sigint_handler};
8943 if (sigaction(SIGINT, &act, NULL) < 0) {
8945 return EXIT_FAILURE;
8948 act.sa_handler = clean_exit_sighandler;
8950 if (sigaction(SIGTERM, &act, NULL) < 0 || sigaction(SIGHUP, &act, NULL) < 0) {
8952 return EXIT_FAILURE;
8955 act.sa_handler = SIG_IGN;
8957 if (sigaction(SIGQUIT, &act, NULL) < 0) {
8959 return EXIT_FAILURE;
8964 setlocale(LC_ALL, "");
8966 tables = pcre_maketables();
8971 #if RL_READLINE_VERSION >= 0x0603
8972 /* readline would overwrite the WINCH signal hook */
8973 rl_change_environment = 0;
8975 /* Bind TAB to cycling */
8976 rl_variable_bind("completion-ignore-case", "on");
8978 rl_bind_key('\t', rl_menu_complete);
8980 rl_bind_key('\t', rl_complete);
8983 mkpath(cfgpath, ".history", g_buf);
8984 read_history(g_buf);
8989 if (cfg.x11 && !g_state.picker) {
8990 /* Save terminal window title */
8991 printf("\033[22;0t");
8993 gethostname(hostname, sizeof(hostname));
8994 hostname[sizeof(hostname) - 1] = '\0';
8999 if (!initcurses(&mask))
9001 if (!initcurses(NULL))
9003 return EXIT_FAILURE;
9006 set_sort_flags(sort);
9008 opt = browse(initpath, session, pkey);
9011 if (session && g_state.prstssn)
9012 save_session(session, NULL);
9016 mousemask(mask, NULL);
9022 if (rlhist && !g_state.xprompt) {
9023 mkpath(cfgpath, ".history", g_buf);
9024 write_history(g_buf);
9028 if (g_state.picker) {
9030 fd = selpath ? open(selpath, O_WRONLY | O_CREAT | O_TRUNC, 0600) : STDOUT_FILENO;
9031 if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
9040 /* Remove tmp dir in list mode */
9043 /* Free the regex */
9045 pcre_free(archive_pcre);
9047 regfree(&archive_re);
9050 /* Free the selection buffer */
9053 #ifdef LINUX_INOTIFY
9054 /* Shutdown inotify */
9055 if (inotify_wd >= 0)
9056 inotify_rm_watch(inotify_fd, inotify_wd);
9058 #elif defined(BSD_KQUEUE)
9062 #elif defined(HAIKU_NM)
9063 haiku_close_nm(haiku_hnd);
9067 if (!g_state.fifomode)