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 /* wraps the argument in single quotes so it can be safely fed to shell */
1314 static bool shell_escape(char *output, size_t outlen, const char *s)
1316 size_t n = xstrlen(s), w = 0;
1319 DPRINTF_S("s == output");
1323 output[w++] = '\''; /* begin single quote */
1324 for (size_t r = 0; r < n; ++r) {
1325 /* potentially too big: 4 for the single quote case, 2 from
1326 * outside the loop */
1327 if (w + 6 >= outlen)
1331 /* the only thing that has special meaning inside single
1332 * quotes are single quotes themselves. */
1334 output[w++] = '\''; /* end single quote */
1335 output[w++] = '\\'; /* put \' so it's treated as literal single quote */
1337 output[w++] = '\''; /* start single quoting again */
1344 output[w++] = '\''; /* end single quote */
1345 output[w++] = '\0'; /* nul terminator */
1349 static bool set_tilde_in_path(char *path)
1351 if (is_prefix(path, home, homelen)) {
1352 home[homelen] = path[homelen - 1];
1353 path[homelen - 1] = '~';
1360 static void reset_tilde_in_path(char *path)
1362 path[homelen - 1] = home[homelen];
1363 home[homelen] = '\0';
1367 static void xterm_cfg(char *path)
1369 if (cfg.x11 && !g_state.picker) {
1370 /* Signal CWD change to terminal */
1371 printf("\033]7;file://%s%s\033\\", hostname, path);
1373 /* Set terminal window title */
1374 bool r = set_tilde_in_path(path);
1376 printf("\033]2;%s\007", r ? &path[homelen - 1] : path);
1380 reset_tilde_in_path(path);
1385 static bool convert_tilde(const char *path, char *buf)
1387 if (tilde_is_home(path)) {
1388 ssize_t len = xstrlen(home);
1389 ssize_t loclen = xstrlen(path);
1391 xstrsncpy(buf, home, len + 1);
1392 xstrsncpy(buf + len, path + 1, loclen);
1398 static int create_tmp_file(void)
1400 xstrsncpy(g_tmpfpath + tmpfplen - 1, messages[STR_TMPFILE], TMP_LEN_MAX - tmpfplen);
1402 int fd = mkstemp(g_tmpfpath);
1405 DPRINTF_S(strerror(errno));
1411 static void msg(const char *message)
1413 dprintf(STDERR_FILENO, "%s\n", message);
1417 static void handle_key_resize(void)
1423 /* Clear the old prompt */
1424 static void clearoldprompt(void)
1427 move(xlines - 2, 0);
1432 handle_key_resize();
1436 /* Messages show up at the bottom */
1437 static inline void printmsg_nc(const char *msg)
1444 static void printmsg(const char *msg)
1446 attron(COLOR_PAIR(cfg.curctx + 1));
1448 attroff(COLOR_PAIR(cfg.curctx + 1));
1451 static void printwait(const char *msg, int *presel)
1457 xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
1461 /* Kill curses and display error before exiting */
1462 static void printerr(int linenum)
1465 perror(xitoa(linenum));
1466 if (!g_state.picker && selpath)
1472 static inline bool xconfirm(int c)
1474 return (c == 'y' || c == 'Y');
1477 static int get_input(const char *prompt)
1488 while (*ch == KEY_RESIZE) {
1502 static bool isselfileempty(void)
1506 return (stat(selpath, &sb) == -1) || (!sb.st_size);
1509 static int get_cur_or_sel(void)
1511 bool sel = (selbufpos || !isselfileempty());
1513 /* Check both local buffer and selection file for external selection */
1514 if (sel && ndents) {
1515 /* If selection is preferred and we have a local selection, return selection.
1516 * Always show the prompt in case of an external selection.
1518 if (cfg.prefersel && selbufpos)
1521 int choice = get_input(messages[MSG_CUR_SEL_OPTS]);
1523 return ((choice == 'c' || choice == 's') ? choice : 0);
1535 static void xdelay(useconds_t delay)
1541 static char confirm_force(bool selection)
1545 snprintf(str, 64, messages[MSG_FORCE_RM],
1546 g_state.trash ? utils[UTIL_GIO_TRASH] + 4 : utils[UTIL_RM_RF],
1547 (selection ? "selected" : "hovered"));
1549 int r = get_input(str);
1552 return '\0'; /* cancel */
1553 if (r == 'y' || r == 'Y')
1554 return 'f'; /* forceful for rm */
1555 return (g_state.trash ? '\0' : 'i'); /* interactive for rm */
1558 /* Writes buflen char(s) from buf to a file */
1559 static void writesel(const char *buf, const size_t buflen)
1564 int fd = open(selpath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
1567 if (write(fd, buf, buflen) != (ssize_t)buflen)
1574 static void appendfpath(const char *path, const size_t len)
1576 if ((selbufpos >= selbuflen) || ((len + 3) > (selbuflen - selbufpos))) {
1577 selbuflen += PATH_MAX;
1578 pselbuf = xrealloc(pselbuf, selbuflen);
1583 selbufpos += xstrsncpy(pselbuf + selbufpos, path, len);
1586 static void selbufrealloc(const size_t alloclen)
1588 if ((selbufpos + alloclen) > selbuflen) {
1589 selbuflen = ALIGN_UP(selbufpos + alloclen, PATH_MAX);
1590 pselbuf = xrealloc(pselbuf, selbuflen);
1596 /* Write selected file paths to fd, linefeed separated */
1597 static size_t seltofile(int fd, uint_t *pcount)
1599 uint_t lastpos, count = 0;
1600 char *pbuf = pselbuf;
1602 ssize_t len, prefixlen = 0, initlen = 0;
1610 lastpos = selbufpos - 1;
1613 prefixlen = (ssize_t)xstrlen(listroot);
1614 initlen = (ssize_t)xstrlen(listpath);
1617 while (pos <= lastpos) {
1619 len = (ssize_t)xstrlen(pbuf);
1621 if (!listpath || !is_prefix(pbuf, listpath, initlen)) {
1622 if (write(fd, pbuf, len) != len)
1625 if (write(fd, listroot, prefixlen) != prefixlen)
1627 if (write(fd, pbuf + initlen, len - initlen) != (len - initlen))
1632 if (pos <= lastpos) {
1633 if (write(fd, "\n", 1) != 1)
1647 /* List selection from selection file (another instance) */
1648 static bool listselfile(void)
1650 if (isselfileempty())
1653 snprintf(g_buf, CMD_LEN_MAX, "tr \'\\0\' \'\\n\' < %s", selpath);
1654 spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CONFIRM);
1659 /* Reset selection indicators */
1660 static void resetselind(void)
1662 for (int r = 0; r < ndents; ++r)
1663 if (pdents[r].flags & FILE_SELECTED)
1664 pdents[r].flags &= ~FILE_SELECTED;
1667 static void startselection(void)
1669 if (!g_state.selmode) {
1670 g_state.selmode = 1;
1681 static void clearselection(void)
1685 g_state.selmode = 0;
1689 static char *findinsel(char *startpos, int len)
1697 char *found = startpos;
1698 size_t buflen = selbufpos - (startpos - pselbuf);
1701 /* memmem(3): not specified in POSIX.1, but present on a number of other systems. */
1702 found = memmem(found, buflen - (found - startpos), g_sel, len);
1705 if (found == startpos || *(found - 1) == '\0')
1707 found += len; /* We found g_sel as a substring of a path, move forward */
1708 if (found >= startpos + buflen)
1713 static int markcmp(const void *va, const void *vb)
1715 const selmark *ma = (selmark*)va;
1716 const selmark *mb = (selmark*)vb;
1718 return ma->startpos - mb->startpos;
1721 /* scanselforpath() must be called before calling this */
1722 static inline void findmarkentry(size_t len, struct entry *dentp)
1724 if (!(dentp->flags & FILE_SCANNED)) {
1725 if (findinsel(findselpos, len + xstrsncpy(g_sel + len, dentp->name, dentp->nlen)))
1726 dentp->flags |= FILE_SELECTED;
1727 dentp->flags |= FILE_SCANNED;
1732 * scanselforpath() must be called before calling this
1733 * pathlen = length of path + 1 (+1 for trailing slash)
1735 static void invertselbuf(const int pathlen)
1737 size_t len, endpos, shrinklen = 0, alloclen = 0;
1738 char * const pbuf = g_sel + pathlen;
1740 int i, nmarked = 0, prev = 0;
1741 struct entry *dentp;
1743 selmark *marked = malloc(nselected * sizeof(selmark));
1750 /* First pass: inversion */
1751 for (i = 0; i < ndents; ++i) {
1754 if (dentp->flags & FILE_SCANNED) {
1755 if (dentp->flags & FILE_SELECTED) {
1756 dentp->flags ^= FILE_SELECTED; /* Clear selection status */
1759 dentp->flags |= FILE_SELECTED;
1760 alloclen += pathlen + dentp->nlen;
1763 dentp->flags |= FILE_SCANNED;
1768 len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1769 found = findinsel(findselpos, len);
1771 if (findselpos == found)
1774 if (nmarked && (found
1775 == (marked[nmarked - 1].startpos + marked[nmarked - 1].len)))
1776 marked[nmarked - 1].len += len;
1778 marked[nmarked].startpos = found;
1779 marked[nmarked].len = len;
1784 shrinklen += len; /* buffer size adjustment */
1786 dentp->flags |= FILE_SELECTED;
1787 alloclen += pathlen + dentp->nlen;
1794 * Files marked for deselection could be found in arbitrary order.
1795 * Sort by appearance in selection buffer.
1796 * With entries sorted we can merge adjacent ones allowing us to
1797 * move them in a single go.
1799 qsort(marked, nmarked, sizeof(selmark), &markcmp);
1801 /* Some files might be adjacent. Merge them into a single entry */
1802 for (i = 1; i < nmarked; ++i) {
1803 if (marked[i].startpos == marked[prev].startpos + marked[prev].len)
1804 marked[prev].len += marked[i].len;
1807 marked[prev].startpos = marked[i].startpos;
1808 marked[prev].len = marked[i].len;
1813 * Number of entries is increased by encountering a non-adjacent entry
1814 * After we finish the loop we should increment it once more.
1817 if (nmarked) /* Make sure there is something to deselect */
1820 /* Using merged entries remove unselected chunks from selection buffer */
1821 for (i = 0; i < nmarked; ++i) {
1823 * found: points to where the current block starts
1824 * variable is recycled from previous for readability
1825 * endpos: points to where the the next block starts
1826 * area between the end of current block (found + len)
1827 * and endpos is selected entries. This is what we are
1830 found = marked[i].startpos;
1831 endpos = (i + 1 == nmarked ? selbufpos : marked[i + 1].startpos - pselbuf);
1832 len = marked[i].len;
1834 /* Move back only selected entries. No selected memory is moved twice */
1835 memmove(found, found + len, endpos - (found + len - pselbuf));
1840 /* Buffer size adjustment */
1841 selbufpos -= shrinklen;
1843 selbufrealloc(alloclen);
1845 /* Second pass: append newly selected to buffer */
1846 for (i = 0; i < ndents; ++i) {
1847 if (pdents[i].flags & FILE_SELECTED) {
1848 len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1849 appendfpath(g_sel, len);
1854 nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1858 * scanselforpath() must be called before calling this
1859 * pathlen = length of path + 1 (+1 for trailing slash)
1861 static void addtoselbuf(const int pathlen, int startid, int endid)
1864 size_t len, alloclen = 0;
1865 struct entry *dentp;
1867 char * const pbuf = g_sel + pathlen;
1869 /* Remember current selection buffer position */
1870 for (i = startid; i <= endid; ++i) {
1874 len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1875 found = findinsel(findselpos, len);
1877 dentp->flags |= (FILE_SCANNED | FILE_SELECTED);
1878 if (found == findselpos) {
1880 if (findselpos == (pselbuf + selbufpos))
1884 alloclen += pathlen + dentp->nlen;
1886 alloclen += pathlen + dentp->nlen;
1889 selbufrealloc(alloclen);
1891 for (i = startid; i <= endid; ++i) {
1892 if (!(pdents[i].flags & FILE_SELECTED)) {
1893 len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1894 appendfpath(g_sel, len);
1896 pdents[i].flags |= (FILE_SCANNED | FILE_SELECTED);
1900 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
1903 /* Removes g_sel from selbuf */
1904 static void rmfromselbuf(size_t len)
1906 char *found = findinsel(findselpos, len);
1910 memmove(found, found + len, selbufpos - (found + len - pselbuf));
1913 nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1916 static int scanselforpath(const char *path, bool getsize)
1918 if (!path[1]) { /* path should always be at least two bytes (including NULL) */
1920 findselpos = pselbuf;
1921 return 1; /* Length of '/' is 1 */
1924 size_t off = xstrsncpy(g_sel, path, PATH_MAX);
1926 g_sel[off - 1] = '/';
1928 * We set findselpos only here. Directories can be listed in arbitrary order.
1929 * This is the best best we can do for remembering position.
1931 findselpos = findinsel(NULL, off);
1935 return (findselpos ? off : 0);
1938 /* Finish selection procedure before an operation */
1939 static void endselection(bool endselmode)
1943 char buf[sizeof(patterns[P_REPLACE]) + PATH_MAX + (TMP_LEN_MAX << 1)];
1945 if (endselmode && g_state.selmode)
1946 g_state.selmode = 0;
1948 /* The code below is only for listing mode */
1949 if (!listpath || !selbufpos)
1952 fd = create_tmp_file();
1954 DPRINTF_S("couldn't create tmp file");
1958 seltofile(fd, NULL);
1960 DPRINTF_S(strerror(errno));
1965 snprintf(buf, sizeof(buf), patterns[P_REPLACE], listpath, listroot, g_tmpfpath);
1966 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
1968 fd = open(g_tmpfpath, O_RDONLY);
1970 DPRINTF_S(strerror(errno));
1972 if (unlink(g_tmpfpath)) {
1973 DPRINTF_S(strerror(errno));
1979 count = read(fd, pselbuf, selbuflen);
1981 DPRINTF_S(strerror(errno));
1983 if (close(fd) || unlink(g_tmpfpath)) {
1984 DPRINTF_S(strerror(errno));
1989 if (close(fd) || unlink(g_tmpfpath)) {
1990 DPRINTF_S(strerror(errno));
1996 pselbuf[--count] = '\0';
1997 for (--count; count > 0; --count)
1998 if (pselbuf[count] == '\n' && pselbuf[count+1] == '/')
1999 pselbuf[count] = '\0';
2001 writesel(pselbuf, selbufpos - 1);
2004 /* Returns: 1 - success, 0 - none selected, -1 - other failure */
2005 static int editselection(void)
2013 if (!selbufpos) /* External selection is only editable at source */
2014 return listselfile();
2016 fd = create_tmp_file();
2018 DPRINTF_S("couldn't create tmp file");
2022 seltofile(fd, NULL);
2024 DPRINTF_S(strerror(errno));
2028 /* Save the last modification time */
2029 if (stat(g_tmpfpath, &sb)) {
2030 DPRINTF_S(strerror(errno));
2034 mtime = sb.st_mtime;
2036 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2038 fd = open(g_tmpfpath, O_RDONLY);
2040 DPRINTF_S(strerror(errno));
2047 if (mtime == sb.st_mtime) {
2048 DPRINTF_S("selection is not modified");
2053 if (sb.st_size > selbufpos) {
2054 DPRINTF_S("edited buffer larger than previous");
2059 count = read(fd, pselbuf, selbuflen);
2061 DPRINTF_S(strerror(errno));
2063 if (close(fd) || unlink(g_tmpfpath)) {
2064 DPRINTF_S(strerror(errno));
2070 if (close(fd) || unlink(g_tmpfpath)) {
2071 DPRINTF_S(strerror(errno));
2083 /* The last character should be '\n' */
2084 pselbuf[--count] = '\0';
2085 for (--count; count > 0; --count) {
2086 /* Replace every '\n' that separates two paths */
2087 if (pselbuf[count] == '\n' && pselbuf[count + 1] == '/') {
2089 pselbuf[count] = '\0';
2093 /* Add a line for the last file */
2096 if (lines > nselected) {
2097 DPRINTF_S("files added to selection");
2102 writesel(pselbuf, selbufpos - 1);
2112 static bool selsafe(void)
2114 /* Fail if selection file path not generated */
2116 printmsg(messages[MSG_SEL_MISSING]);
2120 /* Fail if selection file path isn't accessible */
2121 if (access(selpath, R_OK | W_OK) == -1) {
2122 errno == ENOENT ? printmsg(messages[MSG_0_SELECTED]) : printwarn(NULL);
2129 static void export_file_list(void)
2134 struct entry *pdent = pdents;
2135 int fd = create_tmp_file();
2138 DPRINTF_S(strerror(errno));
2142 for (int r = 0; r < ndents; ++pdent, ++r) {
2143 if (write(fd, pdent->name, pdent->nlen - 1) != (pdent->nlen - 1))
2146 if ((r != ndents - 1) && (write(fd, "\n", 1) != 1))
2151 DPRINTF_S(strerror(errno));
2154 spawn(editor, g_tmpfpath, NULL, NULL, F_CLI);
2156 if (xconfirm(get_input(messages[MSG_RM_TMP])))
2160 static bool init_fcolors(void)
2162 char *f_colors = getenv(env_cfg[NNN_FCOLORS]);
2164 if (!f_colors || !*f_colors)
2167 for (uchar_t id = C_BLK; *f_colors && id <= C_UND; ++id) {
2168 fcolors[id] = xchartohex(*f_colors) << 4;
2170 fcolors[id] += xchartohex(*f_colors);
2172 init_pair(id, fcolors[id], -1);
2181 /* Initialize curses mode */
2182 static bool initcurses(void *oldmask)
2188 if (g_state.picker) {
2189 if (!newterm(NULL, stderr, stdin)) {
2193 } else if (!initscr()) {
2195 DPRINTF_S(getenv("TERM"));
2202 //intrflush(stdscr, FALSE);
2203 keypad(stdscr, TRUE);
2205 #if NCURSES_MOUSE_VERSION <= 1
2206 mousemask(BUTTON1_PRESSED | BUTTON1_DOUBLE_CLICKED | BUTTON2_PRESSED | BUTTON3_PRESSED,
2207 (mmask_t *)oldmask);
2209 mousemask(BUTTON1_PRESSED | BUTTON2_PRESSED | BUTTON3_PRESSED | BUTTON4_PRESSED
2210 | BUTTON5_PRESSED, (mmask_t *)oldmask);
2214 curs_set(FALSE); /* Hide cursor */
2216 char *colors = getenv(env_cfg[NNN_COLORS]);
2218 if (colors || !getenv("NO_COLOR")) {
2223 use_default_colors();
2225 /* Initialize file colors */
2226 if (COLORS >= COLOR_256) {
2227 if (!(g_state.oldcolor || init_fcolors())) {
2229 msg(env_cfg[NNN_FCOLORS]);
2233 g_state.oldcolor = 1;
2236 DPRINTF_D(COLOR_PAIRS);
2238 if (colors && *colors == '#') {
2239 char *sep = strchr(colors, ';');
2241 if (!g_state.oldcolor && COLORS >= COLOR_256) {
2246 * If fallback colors are specified, set the separator
2247 * to NULL so we don't interpret separator and fallback
2248 * if fewer than CTX_MAX xterm 256 colors are specified.
2253 colors = sep; /* Detect if 8 colors fallback is appended */
2259 /* Get and set the context colors */
2260 for (uchar_t i = 0; i < CTX_MAX; ++i) {
2261 pcode = &g_ctx[i].color;
2263 if (colors && *colors) {
2265 *pcode = xchartohex(*colors) << 4;
2267 fcolors[i + 1] = *pcode += xchartohex(*colors);
2268 else { /* Each color code must be 2 hex symbols */
2270 msg(env_cfg[NNN_COLORS]);
2274 *pcode = (*colors < '0' || *colors > '7') ? 4 : *colors - '0';
2279 init_pair(i + 1, *pcode, -1);
2282 #ifdef ICONS_ENABLED
2283 if (!g_state.oldcolor) {
2284 for (uint_t i = 0; i < ELEMENTS(init_colors); ++i)
2285 init_pair(C_UND + 1 + init_colors[i], init_colors[i], -1);
2289 settimeout(); /* One second */
2294 /* No NULL check here as spawn() guards against it */
2295 static char *parseargs(char *cmd, char **argv, int *pindex)
2298 size_t len = xstrlen(cmd) + 1;
2299 char *line = (char *)malloc(len);
2302 DPRINTF_S("malloc()!");
2306 xstrsncpy(line, cmd, len);
2307 argv[count++] = line;
2310 while (*line) { // NOLINT
2311 if (ISBLANK(*line)) {
2314 if (!*line) // NOLINT
2317 argv[count++] = line;
2318 if (count == EXEC_ARGS_MAX) {
2327 if (count == -1 || count > (EXEC_ARGS_MAX - 4)) { /* 3 args and last NULL */
2330 DPRINTF_S("NULL or too many args");
2337 static void enable_signals(void)
2339 struct sigaction dfl_act = {.sa_handler = SIG_DFL};
2341 sigaction(SIGHUP, &dfl_act, NULL);
2342 sigaction(SIGINT, &dfl_act, NULL);
2343 sigaction(SIGQUIT, &dfl_act, NULL);
2344 sigaction(SIGTSTP, &dfl_act, NULL);
2345 sigaction(SIGWINCH, &dfl_act, NULL);
2348 static pid_t xfork(uchar_t flag)
2353 /* the parent ignores the interrupt, quit and hangup signals */
2354 sigaction(SIGHUP, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsighup);
2355 sigaction(SIGTSTP, &(struct sigaction){.sa_handler = SIG_DFL}, &oldsigtstp);
2356 sigaction(SIGWINCH, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsigwinch);
2357 } else if (p == 0) {
2358 /* We create a grandchild to detach */
2359 if (flag & F_NOWAIT) {
2363 _exit(EXIT_SUCCESS);
2371 _exit(EXIT_FAILURE);
2374 /* So they can be used to stop the child */
2378 /* This is the parent waiting for the child to create grandchild */
2379 if (flag & F_NOWAIT)
2380 waitpid(p, NULL, 0);
2387 static int join(pid_t p, uchar_t flag)
2389 int status = 0xFFFF;
2391 if (!(flag & F_NOWAIT)) {
2392 /* wait for the child to exit */
2394 } while (waitpid(p, &status, 0) == -1);
2396 if (WIFEXITED(status)) {
2397 status = WEXITSTATUS(status);
2402 /* restore parent's signal handling */
2403 sigaction(SIGHUP, &oldsighup, NULL);
2404 sigaction(SIGTSTP, &oldsigtstp, NULL);
2405 sigaction(SIGWINCH, &oldsigwinch, NULL);
2411 * Spawns a child process. Behaviour can be controlled using flag.
2412 * Limited to 3 arguments to a program, flag works on bit set.
2414 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag)
2417 int status = 0, retstatus = 0xFFFF;
2418 char *argv[EXEC_ARGS_MAX] = {0};
2421 if (!file || !*file)
2424 /* Swap args if the first arg is NULL and the other 2 aren't */
2425 if (!arg1 && arg2) {
2434 if (flag & F_MULTI) {
2435 cmd = parseargs(file, argv, &status);
2439 argv[status++] = file;
2441 argv[status] = arg1;
2442 argv[++status] = arg2;
2443 argv[++status] = arg3;
2445 if (flag & F_NORMAL)
2450 /* Suppress stdout and stderr */
2451 if (flag & F_NOTRACE) {
2452 int fd = open("/dev/null", O_WRONLY, 0200);
2454 if (flag & F_NOSTDIN)
2455 dup2(fd, STDIN_FILENO);
2456 dup2(fd, STDOUT_FILENO);
2457 dup2(fd, STDERR_FILENO);
2459 } else if (flag & F_TTY) {
2460 /* If stdout has been redirected to a non-tty, force output to tty */
2461 if (!isatty(STDOUT_FILENO)) {
2462 int fd = open(ctermid(NULL), O_WRONLY, 0200);
2463 dup2(fd, STDOUT_FILENO);
2468 execvp(*argv, argv);
2469 _exit(EXIT_SUCCESS);
2471 retstatus = join(pid, flag);
2474 if ((flag & F_CONFIRM) || ((flag & F_CHKRTN) && retstatus)) {
2475 status = write(STDOUT_FILENO, messages[MSG_ENTER], xstrlen(messages[MSG_ENTER]));
2477 while ((read(STDIN_FILENO, &status, 1) > 0) && (status != '\n'));
2480 if (flag & F_NORMAL)
2489 /* Get program name from env var, else return fallback program */
2490 static char *xgetenv(const char * const name, char *fallback)
2492 char *value = getenv(name);
2494 return value && value[0] ? value : fallback;
2497 /* Checks if an env variable is set to 1 */
2498 static inline uint_t xgetenv_val(const char *name)
2500 char *str = getenv(name);
2508 /* Check if a dir exists, IS a dir, and is readable */
2509 static bool xdiraccess(const char *path)
2511 DIR *dirp = opendir(path);
2522 static bool plugscript(const char *plugin, uchar_t flags)
2524 mkpath(plgpath, plugin, g_buf);
2525 if (!access(g_buf, X_OK)) {
2526 spawn(g_buf, NULL, NULL, NULL, flags);
2533 static void opstr(char *buf, char *op)
2535 snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c '%s \"$0\" \"$@\" . < /dev/tty' < %s", op, selpath);
2538 static bool rmmulstr(char *buf)
2540 char r = confirm_force(TRUE);
2545 snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c 'rm -%cr \"$0\" \"$@\" < /dev/tty' < %s",
2548 snprintf(buf, CMD_LEN_MAX, "xargs -0 %s < %s",
2549 utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH], selpath);
2554 /* Returns TRUE if file is removed, else FALSE */
2555 static bool xrm(char * const fpath)
2557 char r = confirm_force(FALSE);
2561 if (!g_state.trash) {
2562 char rm_opts[] = "-ir";
2565 spawn("rm", rm_opts, fpath, NULL, F_NORMAL | F_CHKRTN);
2567 spawn(utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH],
2568 fpath, NULL, NULL, F_NORMAL | F_MULTI);
2570 return (access(fpath, F_OK) == -1); /* File is removed */
2573 static void xrmfromsel(char *path, char *fpath)
2576 bool selected = TRUE;
2579 if ((pdents[cur].flags & DIR_OR_DIRLNK) && scanselforpath(fpath, FALSE))
2581 else if (pdents[cur].flags & FILE_SELECTED) {
2583 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
2589 if (selected && cfg.x11)
2590 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
2594 static uint_t lines_in_file(int fd, char *buf, size_t buflen)
2599 while ((len = read(fd, buf, buflen)) > 0)
2601 count += (buf[--len] == '\n');
2603 /* For all use cases 0 linecount is considered as error */
2604 return ((len < 0) ? 0 : count);
2607 static bool cpmv_rename(int choice, const char *path)
2610 uint_t count = 0, lines = 0;
2612 char *cmd = (choice == 'c' ? cp : mv);
2613 char buf[sizeof(patterns[P_CPMVRNM]) + (MAX(sizeof(cp), sizeof(mv))) + (PATH_MAX << 1)];
2615 fd = create_tmp_file();
2619 /* selsafe() returned TRUE for this to be called */
2621 snprintf(buf, sizeof(buf), "tr '\\0' '\\n' < %s > %s", selpath, g_tmpfpath);
2622 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2624 count = lines_in_file(fd, buf, sizeof(buf));
2628 seltofile(fd, &count);
2632 snprintf(buf, sizeof(buf), patterns[P_CPMVFMT], g_tmpfpath);
2633 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2635 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2637 fd = open(g_tmpfpath, O_RDONLY);
2641 lines = lines_in_file(fd, buf, sizeof(buf));
2644 if (!lines || (2 * count != lines)) {
2645 DPRINTF_S("num mismatch");
2649 snprintf(buf, sizeof(buf), patterns[P_CPMVRNM], path, g_tmpfpath, cmd);
2650 if (!spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CHKRTN))
2659 static bool cpmvrm_selection(enum action sel, char *path)
2663 if (isselfileempty()) {
2666 printmsg(messages[MSG_0_SELECTED]);
2681 r = get_input(messages[MSG_CP_MV_AS]);
2682 if (r != 'c' && r != 'm') {
2683 printmsg(messages[MSG_INVALID_KEY]);
2687 if (!cpmv_rename(r, path)) {
2688 printmsg(messages[MSG_FAILED]);
2692 default: /* SEL_RM */
2693 if (!rmmulstr(g_buf)) {
2694 printmsg(messages[MSG_CANCEL]);
2699 if (sel != SEL_CPMVAS && spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CHKRTN)) {
2700 printmsg(messages[MSG_FAILED]);
2704 /* Clear selection */
2711 static bool batch_rename(void)
2714 uint_t count = 0, lines = 0;
2715 bool dir = FALSE, ret = FALSE;
2716 char foriginal[TMP_LEN_MAX] = {0};
2717 static const char batchrenamecmd[] = "paste -d'\n' %s %s | "SED" 'N; /^\\(.*\\)\\n\\1$/!p;d' | "
2718 "tr '\n' '\\0' | xargs -0 -n2 sh -c 'mv -i \"$0\" \"$@\" <"
2720 char buf[sizeof(batchrenamecmd) + (PATH_MAX << 1)];
2721 int i = get_cur_or_sel();
2726 if (i == 'c') { /* Rename entries in current dir */
2731 fd1 = create_tmp_file();
2735 xstrsncpy(foriginal, g_tmpfpath, xstrlen(g_tmpfpath) + 1);
2737 fd2 = create_tmp_file();
2745 for (i = 0; i < ndents; ++i)
2746 appendfpath(pdents[i].name, NAME_MAX);
2748 seltofile(fd1, &count);
2749 seltofile(fd2, NULL);
2752 if (dir) /* Don't retain dir entries in selection */
2755 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2757 /* Reopen file descriptor to get updated contents */
2758 fd2 = open(g_tmpfpath, O_RDONLY);
2762 lines = lines_in_file(fd2, buf, sizeof(buf));
2765 if (!lines || (count != lines)) {
2766 DPRINTF_S("cannot delete files");
2770 snprintf(buf, sizeof(buf), batchrenamecmd, foriginal, g_tmpfpath);
2771 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2787 static char *get_archive_cmd(const char *archive)
2791 if (!g_state.usebsdtar && getutil(utils[UTIL_ATOOL]))
2793 else if (getutil(utils[UTIL_BSDTAR]))
2795 else if (is_suffix(archive, ".zip"))
2799 return archive_cmd[i];
2802 static void archive_selection(const char *cmd, const char *archive)
2804 char *buf = malloc((xstrlen(patterns[P_ARCHIVE_CMD]) + xstrlen(cmd) + xstrlen(archive)
2805 + xstrlen(selpath)) * sizeof(char));
2807 DPRINTF_S(strerror(errno));
2812 snprintf(buf, CMD_LEN_MAX, patterns[P_ARCHIVE_CMD], cmd, archive, selpath);
2813 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CONFIRM);
2817 static void write_lastdir(const char *curpath, const char *outfile)
2821 xstrsncpy(cfgpath + xstrlen(cfgpath), "/.lastd", 8);
2823 tilde = convert_tilde(outfile, g_buf);
2825 int fd = open(outfile
2826 ? (tilde ? g_buf : outfile)
2827 : cfgpath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
2829 if (fd != -1 && shell_escape(g_buf, sizeof(g_buf), curpath)) {
2830 dprintf(fd, "cd %s", g_buf);
2836 * We assume none of the strings are NULL.
2838 * Let's have the logic to sort numeric names in numeric order.
2839 * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
2841 * If the absolute numeric values are same, we fallback to alphasort.
2843 static int xstricmp(const char * const s1, const char * const s2)
2847 long long v1 = strtoll(s1, &p1, 10);
2848 long long v2 = strtoll(s2, &p2, 10);
2850 /* Check if at least 1 string is numeric */
2851 if (s1 != p1 || s2 != p2) {
2852 /* Handle both pure numeric */
2853 if (s1 != p1 && s2 != p2) {
2861 /* Only first string non-numeric */
2865 /* Only second string non-numeric */
2870 /* Handle 1. all non-numeric and 2. both same numeric value cases */
2872 return strcoll(s1, s2);
2874 return strcasecmp(s1, s2);
2879 * Version comparison
2881 * The code for version compare is a modified version of the GLIBC
2882 * and uClibc implementation of strverscmp(). The source is here:
2883 * https://elixir.bootlin.com/uclibc-ng/latest/source/libc/string/strverscmp.c
2887 * Compare S1 and S2 as strings holding indices/version numbers,
2888 * returning less than, equal to or greater than zero if S1 is less than,
2889 * equal to or greater than S2 (for more info, see the texinfo doc).
2893 static int xstrverscasecmp(const char * const s1, const char * const s2)
2895 const uchar_t *p1 = (const uchar_t *)s1;
2896 const uchar_t *p2 = (const uchar_t *)s2;
2901 * Symbol(s) 0 [1-9] others
2902 * Transition (10) 0 (01) d (00) x
2904 static const uint8_t next_state[] = {
2906 /* S_N */ S_N, S_I, S_Z,
2907 /* S_I */ S_N, S_I, S_I,
2908 /* S_F */ S_N, S_F, S_F,
2909 /* S_Z */ S_N, S_F, S_Z
2912 alignas(max_align_t) static const int8_t result_type[] = {
2913 /* state x/x x/d x/0 d/x d/d d/0 0/x 0/d 0/0 */
2915 /* S_N */ VCMP, VCMP, VCMP, VCMP, VLEN, VCMP, VCMP, VCMP, VCMP,
2916 /* S_I */ VCMP, -1, -1, 1, VLEN, VLEN, 1, VLEN, VLEN,
2917 /* S_F */ VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP,
2918 /* S_Z */ VCMP, 1, 1, -1, VCMP, VCMP, -1, VCMP, VCMP
2929 /* Hint: '0' is a digit too. */
2930 state = S_N + ((c1 == '0') + (xisdigit(c1) != 0));
2932 while ((diff = c1 - c2) == 0) {
2936 state = next_state[state];
2941 state += (c1 == '0') + (xisdigit(c1) != 0);
2944 state = result_type[state * 3 + (((c2 == '0') + (xisdigit(c2) != 0)))]; // NOLINT
2950 while (xisdigit(*p1++))
2951 if (!xisdigit(*p2++))
2953 return xisdigit(*p2) ? -1 : diff;
2959 static int (*namecmpfn)(const char * const s1, const char * const s2) = &xstricmp;
2961 static char * (*fnstrstr)(const char *haystack, const char *needle) = &strcasestr;
2963 static const unsigned char *tables;
2964 static int pcreflags = PCRE_NO_AUTO_CAPTURE | PCRE_EXTENDED | PCRE_CASELESS | PCRE_UTF8;
2966 static int regflags = REG_NOSUB | REG_EXTENDED | REG_ICASE;
2970 static int setfilter(pcre **pcrex, const char *filter)
2972 const char *errstr = NULL;
2975 *pcrex = pcre_compile(filter, pcreflags, &errstr, &erroffset, tables);
2977 return errstr ? -1 : 0;
2980 static int setfilter(regex_t *regex, const char *filter)
2982 return regcomp(regex, filter, regflags);
2986 static int visible_re(const fltrexp_t *fltrexp, const char *fname)
2989 return pcre_exec(fltrexp->pcrex, NULL, fname, xstrlen(fname), 0, 0, NULL, 0) == 0;
2991 return regexec(fltrexp->regex, fname, 0, NULL, 0) == 0;
2995 static int visible_str(const fltrexp_t *fltrexp, const char *fname)
2997 return fnstrstr(fname, fltrexp->str) != NULL;
3000 static int (*filterfn)(const fltrexp_t *fltr, const char *fname) = &visible_str;
3002 static void clearfilter(void)
3004 char * const fltr = g_ctx[cfg.curctx].c_fltr;
3007 fltr[REGEX_MAX - 1] = fltr[1];
3012 static int entrycmp(const void *va, const void *vb)
3014 const struct entry *pa = (pEntry)va;
3015 const struct entry *pb = (pEntry)vb;
3017 if ((pb->flags & DIR_OR_DIRLNK) != (pa->flags & DIR_OR_DIRLNK)) {
3018 if (pb->flags & DIR_OR_DIRLNK)
3023 /* Sort based on specified order */
3024 if (cfg.timeorder) {
3025 if (pb->sec > pa->sec)
3027 if (pb->sec < pa->sec)
3029 /* If sec matches, comare nsec */
3030 if (pb->nsec > pa->nsec)
3032 if (pb->nsec < pa->nsec)
3034 } else if (cfg.sizeorder) {
3035 if (pb->size > pa->size)
3037 if (pb->size < pa->size)
3039 } else if (cfg.blkorder) {
3040 if (pb->blocks > pa->blocks)
3042 if (pb->blocks < pa->blocks)
3044 } else if (cfg.extnorder && !(pb->flags & DIR_OR_DIRLNK)) {
3045 char *extna = xextension(pa->name, pa->nlen - 1);
3046 char *extnb = xextension(pb->name, pb->nlen - 1);
3048 if (extna || extnb) {
3055 int ret = strcasecmp(extna, extnb);
3062 return namecmpfn(pa->name, pb->name);
3065 static int reventrycmp(const void *va, const void *vb)
3067 if ((((pEntry)vb)->flags & DIR_OR_DIRLNK)
3068 != (((pEntry)va)->flags & DIR_OR_DIRLNK)) {
3069 if (((pEntry)vb)->flags & DIR_OR_DIRLNK)
3074 return -entrycmp(va, vb);
3077 static int (*entrycmpfn)(const void *va, const void *vb) = &entrycmp;
3079 /* In case of an error, resets *wch to Esc */
3080 static int handle_alt_key(wint_t *wch)
3084 int r = get_wch(wch);
3093 static inline int handle_event(void)
3095 if (nselected && isselfileempty())
3097 return CONTROL('L');
3101 * Returns SEL_* if key is bound and 0 otherwise.
3102 * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
3103 * The next keyboard input can be simulated by presel.
3105 static int nextsel(int presel)
3112 bool escaped = FALSE;
3114 if (c == 0 || c == MSGWAIT) {
3118 //DPRINTF_S(keyname(c));
3121 if (c == KEY_RESIZE)
3122 handle_key_resize();
3125 /* Handle Alt+key */
3137 } else if (escaped) {
3142 if (!g_state.fifomode)
3143 notify_fifo(TRUE); /* Send hovered path to NNN_FIFO */
3151 if (i == ERR && presel == MSGWAIT)
3152 c = (cfg.filtermode || filterset()) ? FILTER : CONTROL('L');
3153 else if (c == FILTER || c == CONTROL('L'))
3154 /* Clear previous filter when manually starting */
3162 * Do not check for directory changes in du mode.
3163 * A redraw forces du calculation.
3164 * Check for changes every odd second.
3166 #ifdef LINUX_INOTIFY
3167 if (!cfg.blkorder && inotify_wd >= 0 && (idle & 1)) {
3168 struct inotify_event *event;
3169 char inotify_buf[EVENT_BUF_LEN] = {0};
3171 i = read(inotify_fd, inotify_buf, EVENT_BUF_LEN);
3173 for (char *ptr = inotify_buf;
3174 ptr + ((struct inotify_event *)ptr)->len < inotify_buf + i;
3175 ptr += sizeof(struct inotify_event) + event->len) {
3176 event = (struct inotify_event *)ptr;
3177 DPRINTF_D(event->wd);
3178 DPRINTF_D(event->mask);
3182 if (event->mask & INOTIFY_MASK) {
3187 DPRINTF_S("inotify read done");
3190 #elif defined(BSD_KQUEUE)
3191 if (!cfg.blkorder && event_fd >= 0 && (idle & 1)) {
3192 struct kevent event_data[NUM_EVENT_SLOTS] = {0};
3194 if (kevent(kq, events_to_monitor, NUM_EVENT_SLOTS,
3195 event_data, NUM_EVENT_FDS, >imeout) > 0)
3198 #elif defined(HAIKU_NM)
3199 if (!cfg.blkorder && haiku_nm_active && (idle & 1) && haiku_is_update_needed(haiku_hnd))
3205 for (i = 0; i < (int)ELEMENTS(bindings); ++i)
3206 if (c == bindings[i].sym)
3207 return bindings[i].act;
3212 static int getorderstr(char *sort)
3220 sort[i++] = (cfg.timetype == T_MOD) ? 'M' : ((cfg.timetype == T_ACCESS) ? 'A' : 'C');
3221 else if (cfg.sizeorder)
3223 else if (cfg.extnorder)
3226 if (entrycmpfn == &reventrycmp)
3229 if (namecmpfn == &xstrverscasecmp)
3238 static void showfilterinfo(void)
3241 char info[REGEX_MAX] = "\0\0\0\0\0";
3243 i = getorderstr(info);
3245 if (cfg.fileinfo && ndents && get_output("file", "-b", pdents[cur].name, -1, FALSE))
3246 mvaddstr(xlines - 2, 2, g_buf);
3248 snprintf(info + i, REGEX_MAX - i - 1, " %s [/], %4s [:]",
3249 (cfg.regex ? "reg" : "str"),
3250 ((fnstrstr == &strcasestr) ? "ic" : "noic"));
3253 mvaddstr(xlines - 2, xcols - xstrlen(info), info);
3256 static void showfilter(char *str)
3258 attron(COLOR_PAIR(cfg.curctx + 1));
3261 // printmsg calls attroff()
3264 static inline void swap_ent(int id1, int id2)
3266 struct entry _dent, *pdent1 = &pdents[id1], *pdent2 = &pdents[id2];
3268 *(&_dent) = *pdent1;
3270 *pdent2 = *(&_dent);
3274 static int fill(const char *fltr, pcre *pcrex)
3276 static int fill(const char *fltr, regex_t *re)
3280 fltrexp_t fltrexp = { .pcrex = pcrex, .str = fltr };
3282 fltrexp_t fltrexp = { .regex = re, .str = fltr };
3285 for (int count = 0; count < ndents; ++count) {
3286 if (filterfn(&fltrexp, pdents[count].name) == 0) {
3287 if (count != --ndents) {
3288 swap_ent(count, ndents);
3299 static int matches(const char *fltr)
3305 if (cfg.regex && setfilter(&pcrex, fltr))
3308 ndents = fill(fltr, pcrex);
3316 if (cfg.regex && setfilter(&re, fltr))
3319 ndents = fill(fltr, &re);
3325 ENTSORT(pdents, ndents, entrycmpfn);
3331 * Return the position of the matching entry or 0 otherwise
3332 * Note there's no NULL check for fname
3334 static int dentfind(const char *fname, int n)
3336 for (int i = 0; i < n; ++i)
3337 if (xstrcmp(fname, pdents[i].name) == 0)
3343 static int filterentries(char *path, char *lastname)
3345 alignas(max_align_t) wchar_t wln[REGEX_MAX];
3346 char *ln = g_ctx[cfg.curctx].c_fltr;
3348 int r, total = ndents, len;
3349 char *pln = g_ctx[cfg.curctx].c_fltr + 1;
3351 DPRINTF_S(__func__);
3353 if (ndents && (ln[0] == FILTER || ln[0] == RFILTER) && *pln) {
3354 if (matches(pln) != -1) {
3355 move_cursor(dentfind(lastname, ndents), 0);
3359 if (!cfg.filtermode) {
3364 len = mbstowcs(wln, ln, REGEX_MAX);
3366 ln[0] = wln[0] = cfg.regex ? RFILTER : FILTER;
3367 ln[1] = wln[1] = '\0';
3375 while ((r = get_wch(ch)) != ERR) {
3377 //DPRINTF_S(keyname(*ch));
3381 case 0: // fallthrough
3388 case KEY_DC: // fallthrough
3389 case KEY_BACKSPACE: // fallthrough
3390 case '\b': // fallthrough
3391 case DEL: /* handle DEL */
3394 wcstombs(ln, wln, REGEX_MAX);
3402 if (*ch == CONTROL('L')) {
3404 ln[REGEX_MAX - 1] = ln[1];
3405 ln[1] = wln[1] = '\0';
3408 } else if (ln[REGEX_MAX - 1]) { /* Show the previous filter */
3409 ln[1] = ln[REGEX_MAX - 1];
3410 ln[REGEX_MAX - 1] = '\0';
3411 len = mbstowcs(wln, ln, REGEX_MAX);
3416 /* Go to the top, we don't know if the hovered file will match the filter */
3419 if (matches(pln) != -1)
3429 if (handle_alt_key(ch) != ERR) {
3430 if (*ch == ESC) /* Handle Alt+Esc */
3431 *ch = 'q'; /* Quit context */
3434 *ch = ';'; /* Run plugin */
3440 if (r != OK) /* Handle Fn keys in main loop */
3443 /* Handle all control chars in main loop */
3444 if (*ch < ASCII_MAX && keyname(*ch)[0] == '^' && *ch != '^')
3448 if (*ch == '?') /* Help and config key, '?' is an invalid regex */
3451 if (cfg.filtermode) {
3453 case '\'': // fallthrough /* Go to first non-dir file */
3454 case '+': // fallthrough /* Toggle file selection */
3455 case ',': // fallthrough /* Mark CWD */
3456 case '-': // fallthrough /* Visit last visited dir */
3457 case '.': // fallthrough /* Show hidden files */
3458 case ';': // fallthrough /* Run plugin key */
3459 case '=': // fallthrough /* Launch app */
3460 case '>': // fallthrough /* Export file list */
3461 case '@': // fallthrough /* Visit start dir */
3462 case ']': // fallthorugh /* Prompt key */
3463 case '`': // fallthrough /* Visit / */
3464 case '~': /* Go HOME */
3469 /* Toggle case-sensitivity */
3471 fnstrstr = (fnstrstr == &strcasestr) ? &strstr : &strcasestr;
3473 pcreflags ^= PCRE_CASELESS;
3475 regflags ^= REG_ICASE;
3481 /* Toggle string or regex filter */
3482 if (*ch == FILTER) {
3483 ln[0] = (ln[0] == FILTER) ? RFILTER : FILTER;
3484 wln[0] = (uchar_t)ln[0];
3486 filterfn = cfg.regex ? &visible_re : &visible_str;
3491 /* Reset cur in case it's a repeat search */
3493 } else if (len == REGEX_MAX - 1)
3496 wln[len] = (wchar_t)*ch;
3498 wcstombs(ln, wln, REGEX_MAX);
3500 /* Forward-filtering optimization:
3501 * - new matches can only be a subset of current matches.
3503 /* ndents = total; */
3507 !r ? unget_wch(KEY_BACKSPACE) : showfilter(ln);
3509 if (matches(pln) == -1) {
3515 /* If the only match is a dir, auto-enter and cd into it */
3516 if ((ndents == 1) && cfg.autoenter && (pdents[0].flags & DIR_OR_DIRLNK)) {
3523 * redraw() should be above the auto-enter optimization, for
3524 * the case where there's an issue with dir auto-enter, say,
3525 * due to a permission problem. The transition is _jumpy_ in
3526 * case of such an error. However, we optimize for successful
3527 * cases where the dir has permissions. This skips a redraw().
3534 /* Save last working filter in-filter */
3536 ln[REGEX_MAX - 1] = ln[1];
3544 /* Return keys for navigation etc. */
3548 /* Show a prompt with input string and return the changes */
3549 static char *xreadline(const char *prefill, const char *prompt)
3553 const int WCHAR_T_WIDTH = sizeof(wchar_t);
3555 wchar_t * const buf = malloc(sizeof(wchar_t) * READLINE_MAX);
3565 len = pos = mbstowcs(buf, prefill, READLINE_MAX);
3569 if (len == (size_t)-1) {
3574 x = getcurx(stdscr);
3579 attron(COLOR_PAIR(cfg.curctx + 1));
3580 if (pos > (size_t)(xcols - x)) {
3581 mvaddnwstr(xlines - 1, x, buf + (pos - (xcols - x) + 1), xcols - x);
3582 move(xlines - 1, xcols - 1);
3584 mvaddnwstr(xlines - 1, x, buf, len + 1);
3585 move(xlines - 1, x + wcswidth(buf, pos));
3587 attroff(COLOR_PAIR(cfg.curctx + 1));
3595 case KEY_ENTER: // fallthrough
3596 case '\n': // fallthrough
3602 else if (!(pos || len)) { /* Exit on ^D at empty prompt */
3608 case DEL: // fallthrough
3609 case '\b': /* rhel25 sends '\b' for backspace */
3611 memmove(buf + pos - 1, buf + pos,
3612 (len - pos) * WCHAR_T_WIDTH);
3617 if (!(len || pos) && ndents)
3618 len = pos = mbstowcs(buf, pdents[cur].name, READLINE_MAX);
3633 memmove(buf + pos - 1, buf + pos,
3634 (len - pos) * WCHAR_T_WIDTH);
3636 } while (buf[pos - 1] != ' ' && buf[pos - 1] != '/'); // NOLINT
3654 memmove(buf, buf + pos, (len - pos) * WCHAR_T_WIDTH);
3658 case ESC: /* Exit prompt on Esc, but just filter out Alt+key */
3659 if (handle_alt_key(ch) != ERR)
3666 /* Filter out all other control chars */
3667 if (*ch < ASCII_MAX && keyname(*ch)[0] == '^')
3670 if (pos < READLINE_MAX - 1) {
3671 memmove(buf + pos + 1, buf + pos,
3672 (len - pos) * WCHAR_T_WIDTH);
3696 memmove(buf + pos - 1, buf + pos,
3697 (len - pos) * WCHAR_T_WIDTH);
3703 memmove(buf + pos, buf + pos + 1,
3704 (len - pos - 1) * WCHAR_T_WIDTH);
3714 case KEY_UP: // fallthrough
3716 if (prompt && lastcmd && (xstrcmp(prompt, PROMPT) == 0)) {
3718 len = pos = mbstowcs(buf, lastcmd, READLINE_MAX); // fallthrough
3733 pos = wcstombs(g_buf, buf, READLINE_MAX - 1);
3734 if (pos >= READLINE_MAX - 1)
3735 g_buf[READLINE_MAX - 1] = '\0';
3743 * Caller should check the value of presel to confirm if it needs to wait to show warning
3745 static char *getreadline(const char *prompt)
3749 char *input = readline(prompt);
3753 if (input && input[0]) {
3755 xstrsncpy(g_buf, input, CMD_LEN_MAX);
3766 * Create symbolic/hard link(s) to file(s) in selection list
3767 * Returns the number of links created, -1 on error
3769 static int xlink(char *prefix, char *path, char *curfname, char *buf, int type)
3771 int count = 0, choice;
3772 char *psel = pselbuf, *fname;
3773 size_t pos = 0, len, r;
3774 int (*link_fn)(const char *, const char *) = NULL;
3775 char lnpath[PATH_MAX];
3777 choice = get_cur_or_sel();
3781 if (type == 's') /* symbolic link */
3783 else /* hard link */
3786 if (choice == 'c' || (nselected == 1)) {
3787 prefix = abspath(prefix, path, lnpath); /* Generate link path */
3792 mkpath(path, curfname, buf); /* Generate target file path */
3794 if (!link_fn((choice == 'c') ? buf : pselbuf, lnpath)) {
3797 return 1; /* One link created */
3802 r = xstrsncpy(buf, prefix, NAME_MAX + 1); /* Copy prefix */
3804 while (pos < selbufpos) {
3805 len = xstrlen(psel);
3806 fname = xbasename(psel);
3808 xstrsncpy(buf + r - 1, fname, NAME_MAX - r); /* Suffix target file name */
3809 mkpath(path, buf, lnpath); /* Generate link path */
3811 if (!link_fn(psel, lnpath))
3818 if (count == nselected) /* Clear selection if all links are generated */
3823 static bool parsekvpair(kv **arr, char **envcpy, const uchar_t id, uchar_t *items)
3826 const uchar_t INCR = 8;
3829 char *ptr = getenv(env_cfg[id]);
3834 *envcpy = xstrdup(ptr);
3842 while (*ptr && i < 100) {
3844 if (!(i & (INCR - 1))) {
3845 kvarr = xrealloc(kvarr, sizeof(kv) * (i + INCR));
3851 memset(kvarr + i, 0, sizeof(kv) * INCR);
3853 kvarr[i].key = (uchar_t)*ptr;
3854 if (*++ptr != ':' || *++ptr == '\0' || *ptr == ';')
3856 kvarr[i].off = ptr - *envcpy;
3875 * Get the value corresponding to a key
3877 * NULL is returned in case of no match, path resolution failure etc.
3878 * buf would be modified, so check return value before access
3880 static char *get_kv_val(kv *kvarr, char *buf, int key, uchar_t max, uchar_t id)
3887 for (int r = 0; r < max && kvarr[r].key; ++r) {
3888 if (kvarr[r].key == key) {
3889 /* Do not allocate new memory for plugin */
3891 return pluginstr + kvarr[r].off;
3893 val = bmstr + kvarr[r].off;
3894 bool tilde = convert_tilde(val, g_buf);
3895 return abspath((tilde ? g_buf : val), NULL, buf);
3899 DPRINTF_S("Invalid key");
3903 static int get_kv_key(kv *kvarr, char *val, uchar_t max, uchar_t id)
3908 if (id != NNN_ORDER) /* For now this function supports only order string */
3911 for (int r = 0; r < max && kvarr[r].key; ++r) {
3912 if (xstrcmp((orderstr + kvarr[r].off), val) == 0)
3913 return kvarr[r].key;
3919 static void resetdircolor(int flags)
3921 /* Directories are always shown on top, clear the color when moving to first file */
3922 if (g_state.dircolor && !(flags & DIR_OR_DIRLNK)) {
3923 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
3924 g_state.dircolor = 0;
3929 * Replace escape characters in a string with '?'
3930 * Adjust string length to maxcols if > 0;
3931 * Max supported str length: NAME_MAX;
3934 static char *unescape(const char *str, uint_t maxcols)
3936 char * const wbuf = g_buf;
3939 xstrsncpy(wbuf, str, maxcols);
3941 static wchar_t *unescape(const char *str, uint_t maxcols)
3943 wchar_t * const wbuf = (wchar_t *)g_buf;
3944 wchar_t *buf = wbuf;
3945 size_t len = mbstowcs(wbuf, str, maxcols); /* Convert multi-byte to wide char */
3947 len = wcswidth(wbuf, len);
3949 if (len >= maxcols) {
3950 size_t lencount = maxcols;
3952 while (len > maxcols) /* Reduce wide chars one by one till it fits */
3953 len = wcswidth(wbuf, --lencount);
3955 wbuf[lencount] = L'\0';
3960 if (*buf <= '\x1f' || *buf == '\x7f')
3969 static off_t get_size(off_t size, off_t *pval, int comp)
3972 off_t quo = rem / 10;
3974 if ((rem - (quo * 10)) >= 5) {
3987 static char *coolsize(off_t size)
3989 const char * const U = "BKMGTPEZY";
3990 static char size_buf[12]; /* Buffer to hold human readable size */
3995 while (size >= 1024) {
3996 rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
4002 rem = (rem * 1000) >> 10;
4004 size = get_size(size, &rem, 10);
4005 } else if (i == 2) {
4006 rem = (rem * 1000) >> 10;
4007 size = get_size(size, &rem, 100);
4009 rem = (rem * 10000) >> 10;
4010 size = get_size(size, &rem, 1000);
4013 if (i > 0 && i < 6 && rem) {
4014 ret = xstrsncpy(size_buf, xitoa(size), 12);
4015 size_buf[ret - 1] = '.';
4017 char *frac = xitoa(rem);
4018 size_t toprint = i > 3 ? 3 : i;
4019 size_t len = xstrlen(frac);
4021 if (len < toprint) {
4022 size_buf[ret] = size_buf[ret + 1] = size_buf[ret + 2] = '0';
4023 xstrsncpy(size_buf + ret + (toprint - len), frac, len + 1);
4025 xstrsncpy(size_buf + ret, frac, toprint + 1);
4029 ret = xstrsncpy(size_buf, size ? xitoa(size) : "0", 12);
4033 size_buf[ret] = U[i];
4034 size_buf[ret + 1] = '\0';
4039 /* Convert a mode field into "ls -l" type perms field. */
4040 static char *get_lsperms(mode_t mode)
4042 static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
4043 static char bits[11] = {'\0'};
4045 switch (mode & S_IFMT) {
4072 xstrsncpy(&bits[1], rwx[(mode >> 6) & 7], 4);
4073 xstrsncpy(&bits[4], rwx[(mode >> 3) & 7], 4);
4074 xstrsncpy(&bits[7], rwx[(mode & 7)], 4);
4077 bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
4079 bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
4081 bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
4086 #ifdef ICONS_ENABLED
4087 static struct icon get_icon(const struct entry *ent)
4089 for (size_t i = 0; i < ELEMENTS(icons_name); ++i)
4090 if (strcasecmp(ent->name, icons_name[i].match) == 0)
4091 return (struct icon){ icons_name[i].icon, icons_name[i].color };
4093 if (ent->flags & DIR_OR_DIRLNK)
4096 char *tmp = xextension(ent->name, ent->nlen);
4099 uint16_t z, k, h = icon_ext_hash(++tmp); /* ++tmp to skip '.' */
4100 for (k = 0; k < ICONS_PROBE_MAX; ++k) {
4101 z = (h + k) % ELEMENTS(icons_ext);
4102 if (strcasecmp(tmp, icons_ext[z].match) == 0)
4103 return (struct icon){ icons_ext_uniq[icons_ext[z].idx], icons_ext[z].color };
4107 /* If there's no match and the file is executable, icon that */
4108 if (ent->mode & 0100)
4113 static void print_icon(const struct entry *ent, const int attrs)
4115 const struct icon icon = get_icon(ent);
4116 addstr(ICON_PADDING_LEFT);
4118 attron(COLOR_PAIR(C_UND + 1 + icon.color));
4123 attroff(COLOR_PAIR(C_UND + 1 + icon.color));
4126 addstr(ICON_PADDING_RIGHT);
4130 static void print_time(const time_t *timep, const uchar_t flags)
4134 /* Highlight timestamp for entries 5 minutes young */
4135 if (flags & FILE_YOUNG)
4138 localtime_r(timep, &t);
4139 printw("%s-%02d-%02d %02d:%02d",
4140 xitoa(t.tm_year + 1900), t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min);
4142 if (flags & FILE_YOUNG)
4146 static char get_detail_ind(const mode_t mode)
4148 switch (mode & S_IFMT) {
4149 case S_IFDIR: // fallthrough
4150 case S_IFREG: return ' ';
4151 case S_IFLNK: return '@';
4152 case S_IFSOCK: return '=';
4153 case S_IFIFO: return '|';
4154 case S_IFBLK: return 'b';
4155 case S_IFCHR: return 'c';
4160 /* Note: attribute and indicator values must be initialized to 0 */
4161 static uchar_t get_color_pair_name_ind(const struct entry *ent, char *pind, int *pattr)
4163 switch (ent->mode & S_IFMT) {
4166 if (ent->mode & 0100)
4170 if (ent->flags & HARD_LINK) {
4171 if (ent->mode & 0100)
4175 if (ent->mode & 0100) {
4182 if (g_state.oldcolor)
4185 return g_state.dirctx ? cfg.curctx + 1 : C_DIR;
4187 if (ent->flags & DIR_OR_DIRLNK) {
4189 *pattr |= g_state.oldcolor ? A_DIM : A_BOLD;
4192 if (g_state.oldcolor)
4195 if (!g_state.oldcolor || cfg.showdetail)
4196 return (ent->flags & SYM_ORPHAN) ? C_ORP : C_LNK;
4214 static void printent(const struct entry *ent, uint_t namecols, bool sel)
4219 if (cfg.showdetail) {
4220 int type = ent->mode & S_IFMT;
4221 char perms[6] = {' ', ' ', (char)('0' + ((ent->mode >> 6) & 7)),
4222 (char)('0' + ((ent->mode >> 3) & 7)),
4223 (char)('0' + (ent->mode & 7)), '\0'};
4226 attrs = g_state.oldcolor ? (resetdircolor(ent->flags), A_DIM)
4227 : (fcolors[C_MIS] ? COLOR_PAIR(C_MIS) : 0);
4232 print_time(&ent->sec, ent->flags);
4234 printw("%s%9s ", perms, (type == S_IFREG || type == S_IFDIR)
4235 ? coolsize(cfg.blkorder ? (blkcnt_t)ent->blocks << blk_shift : ent->size)
4236 : (type = (uchar_t)get_detail_ind(ent->mode), (char *)&type));
4244 uchar_t color_pair = get_color_pair_name_ind(ent, &ind, &attrs);
4246 addch((ent->flags & FILE_SELECTED) ? '+' | A_REVERSE | A_BOLD : ' ');
4248 if (g_state.oldcolor)
4249 resetdircolor(ent->flags);
4251 if (ent->flags & FILE_MISSING)
4253 if (color_pair && fcolors[color_pair])
4254 attrs |= COLOR_PAIR(color_pair);
4255 #ifdef ICONS_ENABLED
4256 print_icon(ent, attrs);
4268 addwstr(unescape(ent->name, namecols));
4270 addstr(unescape(ent->name, MIN(namecols, ent->nlen) + 1));
4279 static void savecurctx(char *path, char *curname, int nextctx)
4281 settings tmpcfg = cfg;
4282 context *ctxr = &g_ctx[nextctx];
4284 /* Save current context */
4286 xstrsncpy(g_ctx[tmpcfg.curctx].c_name, curname, NAME_MAX + 1);
4288 g_ctx[tmpcfg.curctx].c_name[0] = '\0';
4290 g_ctx[tmpcfg.curctx].c_cfg = tmpcfg;
4292 if (ctxr->c_cfg.ctxactive) { /* Switch to saved context */
4293 tmpcfg = ctxr->c_cfg;
4294 /* Skip ordering an open context */
4296 cfgsort[CTX_MAX] = cfgsort[nextctx];
4297 cfgsort[nextctx] = '0';
4299 } else { /* Set up a new context from current context */
4300 ctxr->c_cfg.ctxactive = 1;
4301 xstrsncpy(ctxr->c_path, path, PATH_MAX);
4302 ctxr->c_last[0] = ctxr->c_name[0] = ctxr->c_fltr[0] = ctxr->c_fltr[1] = '\0';
4303 ctxr->c_cfg = tmpcfg;
4304 /* If already in an ordered dir, clear ordering for the new context and let it order */
4305 if (cfgsort[cfg.curctx] == 'z')
4306 cfgsort[nextctx] = 'z';
4309 tmpcfg.curctx = nextctx;
4311 /* Restore the global function pointers alongside the cfg. */
4312 entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
4313 namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
4317 static void save_session(const char *sname, int *presel)
4320 session_header_t header = {0};
4321 bool status = FALSE;
4322 char ssnpath[PATH_MAX];
4323 char spath[PATH_MAX];
4325 header.ver = SESSIONS_VERSION;
4327 for (i = 0; i < CTX_MAX; ++i) {
4328 if (g_ctx[i].c_cfg.ctxactive) {
4329 if (cfg.curctx == i && ndents)
4330 /* Update current file name, arrows don't update it */
4331 xstrsncpy(g_ctx[i].c_name, pdents[cur].name, NAME_MAX + 1);
4332 header.pathln[i] = MIN(xstrlen(g_ctx[i].c_path), PATH_MAX) + 1;
4333 header.lastln[i] = MIN(xstrlen(g_ctx[i].c_last), PATH_MAX) + 1;
4334 header.nameln[i] = MIN(xstrlen(g_ctx[i].c_name), NAME_MAX) + 1;
4335 header.fltrln[i] = REGEX_MAX;
4339 mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4340 mkpath(ssnpath, sname, spath);
4342 fd = open(spath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
4344 printwait(messages[MSG_SEL_MISSING], presel);
4348 if ((write(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4349 || (write(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4352 for (i = 0; i < CTX_MAX; ++i)
4353 if ((write(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4354 || (write(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4355 || (header.nameln[i] > 0
4356 && write(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4357 || (header.lastln[i] > 0
4358 && write(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4359 || (header.fltrln[i] > 0
4360 && write(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4361 || (header.pathln[i] > 0
4362 && write(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4371 printwait(messages[MSG_FAILED], presel);
4374 static bool load_session(const char *sname, char **path, char **lastdir, char **lastname, bool restore)
4377 session_header_t header;
4378 bool has_loaded_dynamically = !(sname || restore);
4379 bool status = (sname && g_state.picker); /* Picker mode with session program option */
4380 char ssnpath[PATH_MAX];
4381 char spath[PATH_MAX];
4383 mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4386 sname = sname ? sname : xreadline(NULL, messages[MSG_SSN_NAME]);
4390 mkpath(ssnpath, sname, spath);
4392 /* If user is explicitly loading the "last session", skip auto-save */
4393 if ((sname[0] == '@') && !sname[1])
4394 has_loaded_dynamically = FALSE;
4396 mkpath(ssnpath, "@", spath);
4398 if (has_loaded_dynamically)
4399 save_session("@", NULL);
4401 fd = open(spath, O_RDONLY, S_IWUSR | S_IRUSR);
4404 printmsg(messages[MSG_SEL_MISSING]);
4405 xdelay(XDELAY_INTERVAL_MS);
4412 if ((read(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4413 || (header.ver != SESSIONS_VERSION)
4414 || (read(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4417 g_ctx[cfg.curctx].c_name[0] = g_ctx[cfg.curctx].c_last[0]
4418 = g_ctx[cfg.curctx].c_fltr[0] = g_ctx[cfg.curctx].c_fltr[1] = '\0';
4420 for (; i < CTX_MAX; ++i)
4421 if ((read(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4422 || (read(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4423 || (header.nameln[i] > 0
4424 && read(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4425 || (header.lastln[i] > 0
4426 && read(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4427 || (header.fltrln[i] > 0
4428 && read(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4429 || (header.pathln[i] > 0
4430 && read(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4433 *path = g_ctx[cfg.curctx].c_path;
4434 *lastdir = g_ctx[cfg.curctx].c_last;
4435 *lastname = g_ctx[cfg.curctx].c_name;
4436 set_sort_flags('\0'); /* Set correct sort options */
4443 printmsg(messages[MSG_FAILED]);
4444 xdelay(XDELAY_INTERVAL_MS);
4452 static uchar_t get_free_ctx(void)
4454 uchar_t r = cfg.curctx;
4457 r = (r + 1) & ~CTX_MAX;
4458 while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
4463 /* ctx is absolute: 1 to 4, + for smart context */
4464 static void set_smart_ctx(int ctx, char *nextpath, char **path, char *file, char **lastname, char **lastdir)
4466 if (ctx == '+') /* Get smart context */
4467 ctx = (int)(get_free_ctx() + 1);
4469 if (ctx == 0 || ctx == cfg.curctx + 1) { /* Same context */
4471 xstrsncpy(*lastdir, *path, PATH_MAX);
4472 xstrsncpy(*path, nextpath, PATH_MAX);
4473 } else { /* New context */
4475 /* Deactivate the new context and build from scratch */
4476 g_ctx[ctx].c_cfg.ctxactive = 0;
4477 DPRINTF_S(nextpath);
4478 savecurctx(nextpath, file, ctx);
4479 *path = g_ctx[ctx].c_path;
4480 *lastdir = g_ctx[ctx].c_last;
4481 *lastname = g_ctx[ctx].c_name;
4486 * This function does one of the following depending on the values of `fdout` and `page`:
4487 * 1) fdout == -1 && !page: Write up to CMD_LEN_MAX bytes of command output into g_buf
4488 * 2) fdout == -1 && page: Create a temp file, write full command output into it and show in pager.
4489 * 3) fdout != -1 && !page: Write full command output into the provided file.
4490 * 4) fdout != -1 && page: Don't use! Returns FALSE.
4492 * g_buf is modified only in case 1.
4493 * g_tmpfpath is modified only in case 2.
4495 static bool get_output(char *file, char *arg1, char *arg2, int fdout, bool page)
4499 int index = 0, flags;
4501 bool have_file = fdout != -1;
4503 int cmd_out_fd = -1;
4507 * In this case the logic of the function dictates that we should write the output of the command
4508 * to `fd` and show it in the pager. But since we didn't open the file descriptor we have no right
4509 * to close it, the caller must do it. We don't even know the path to pass to the pager and
4510 * it's a real hassle to get it. In general this just invites problems so we are blocking it.
4512 if (have_file && page) {
4513 DPRINTF_S("invalid get_ouptput() call");
4517 /* Setup file descriptors for child command */
4518 if (!have_file && page) {
4520 fdout = create_tmp_file();
4524 cmd_in_fd = STDIN_FILENO;
4526 } else if (have_file) {
4528 cmd_in_fd = STDIN_FILENO;
4532 if (pipe(pipefd) == -1)
4535 for (index = 0; index < 2; ++index) {
4536 /* Get previous flags */
4537 flags = fcntl(pipefd[index], F_GETFL, 0);
4539 /* Set bit for non-blocking flag */
4540 flags |= O_NONBLOCK;
4542 /* Change flags on fd */
4543 fcntl(pipefd[index], F_SETFL, flags);
4546 cmd_in_fd = pipefd[0];
4547 cmd_out_fd = pipefd[1];
4554 dup2(cmd_out_fd, STDOUT_FILENO);
4555 dup2(cmd_out_fd, STDERR_FILENO);
4558 spawn(file, arg1, arg2, NULL, F_MULTI);
4559 _exit(EXIT_SUCCESS);
4563 waitpid(pid, NULL, 0);
4565 /* Do what each case should do */
4566 if (!have_file && page) {
4570 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4581 len = read(pipefd[0], g_buf, CMD_LEN_MAX - 1);
4591 * Follows the stat(1) output closely
4593 static bool show_stats(char *fpath)
4595 static char * const cmds[] = {
4596 #ifdef FILE_MIME_OPTS
4597 ("file " FILE_MIME_OPTS),
4600 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
4607 size_t r = ELEMENTS(cmds);
4608 int fd = create_tmp_file();
4613 get_output(cmds[--r], fpath, NULL, fd, FALSE);
4617 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4622 static bool xchmod(const char *fpath, mode_t *mode)
4624 /* (Un)set (S_IXUSR | S_IXGRP | S_IXOTH) */
4625 (0100 & *mode) ? (*mode &= ~0111) : (*mode |= 0111);
4627 return (chmod(fpath, *mode) == 0);
4630 static size_t get_fs_info(const char *path, uchar_t type)
4634 if (statvfs(path, &svb) == -1)
4637 if (type == VFS_AVAIL)
4638 return (size_t)svb.f_bavail << ffs((int)(svb.f_frsize >> 1));
4640 if (type == VFS_USED)
4641 return ((size_t)svb.f_blocks - (size_t)svb.f_bfree) << ffs((int)(svb.f_frsize >> 1));
4643 return (size_t)svb.f_blocks << ffs((int)(svb.f_frsize >> 1)); /* VFS_SIZE */
4646 /* Create non-existent parents and a file or dir */
4647 static bool xmktree(char *path, bool dir)
4655 /* Skip the first '/' */
4658 while (*p != '\0') {
4667 /* Create folder from path to '\0' inserted at p */
4668 if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4670 // XDG_CONFIG_HOME contains a directory
4671 // that is read-only, but the full path
4673 // Try to continue and see what happens.
4674 // TODO: Find a more robust solution.
4675 if (errno == B_READ_ONLY_DEVICE)
4678 DPRINTF_S("mkdir1!");
4679 DPRINTF_S(strerror(errno));
4693 if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4694 DPRINTF_S("mkdir2!");
4695 DPRINTF_S(strerror(errno));
4699 int fd = open(path, O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR); /* Forced create mode for files */
4701 if (fd == -1 && errno != EEXIST) {
4703 DPRINTF_S(strerror(errno));
4713 /* List or extract archive */
4714 static bool handle_archive(char *fpath /* in-out param */, char op)
4716 char arg[] = "-tvf"; /* options for tar/bsdtar to list files */
4717 char *util, *outdir = NULL;
4719 bool is_atool = (!g_state.usebsdtar && getutil(utils[UTIL_ATOOL]));
4722 outdir = xreadline(is_atool ? "." : xbasename(fpath), messages[MSG_NEW_PATH]);
4723 if (!outdir || !*outdir) { /* Cancelled */
4724 printwait(messages[MSG_CANCEL], NULL);
4727 /* Do not create smart context for current dir */
4728 if (!(*outdir == '.' && outdir[1] == '\0')) {
4729 if (!xmktree(outdir, TRUE) || (chdir(outdir) == -1)) {
4733 /* Copy the new dir path to open it in smart context */
4734 outdir = getcwd(NULL, 0);
4740 util = utils[UTIL_ATOOL];
4743 } else if (getutil(utils[UTIL_BSDTAR])) {
4744 util = utils[UTIL_BSDTAR];
4747 } else if (is_suffix(fpath, ".zip")) {
4748 util = utils[UTIL_UNZIP];
4749 arg[1] = (op == 'l') ? 'v' /* verbose listing */ : '\0';
4752 util = utils[UTIL_TAR];
4757 if (op == 'x') /* extract */
4758 spawn(util, arg, fpath, NULL, F_NORMAL | F_MULTI);
4760 get_output(util, arg, fpath, -1, TRUE);
4763 if (chdir(xdirname(fpath)) == -1) {
4768 xstrsncpy(fpath, outdir, PATH_MAX);
4770 } else if (op == 'x')
4776 static char *visit_parent(char *path, char *newpath, int *presel)
4780 /* There is no going back */
4781 if (istopdir(path)) {
4782 /* Continue in type-to-nav mode, if enabled */
4783 if (cfg.filtermode && presel)
4788 /* Use a copy as xdirname() may change the string passed */
4790 xstrsncpy(newpath, path, PATH_MAX);
4794 dir = xdirname(newpath);
4795 if (chdir(dir) == -1) {
4803 static void valid_parent(char *path, char *lastname)
4806 xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
4808 while (!istopdir(path))
4809 if (visit_parent(path, NULL, NULL))
4813 xdelay(XDELAY_INTERVAL_MS);
4816 static bool archive_mount(char *newpath)
4818 char *dir, *cmd = xgetenv("NNN_ARCHMNT", utils[UTIL_ARCHMNT]);
4819 char *name = pdents[cur].name;
4820 size_t len = pdents[cur].nlen;
4821 char mntpath[PATH_MAX];
4823 if (!getutil(cmd)) {
4824 printmsg("install utility");
4828 dir = xstrdup(name);
4830 printmsg(messages[MSG_FAILED]);
4835 if (dir[--len] == '.') {
4842 /* Create the mount point */
4843 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4844 mkpath(mntpath, dir, newpath);
4847 if (!xmktree(newpath, TRUE)) {
4855 if (spawn(cmd, name, newpath, NULL, F_NORMAL)) {
4856 printmsg(messages[MSG_FAILED]);
4863 static bool remote_mount(char *newpath)
4865 uchar_t flag = F_CLI;
4868 bool r = getutil(utils[UTIL_RCLONE]), s = getutil(utils[UTIL_SSHFS]);
4869 char mntpath[PATH_MAX];
4872 printmsg("install sshfs/rclone");
4877 opt = get_input(messages[MSG_REMOTE_OPTS]);
4879 opt = (!s) ? 'r' : 's';
4882 env = xgetenv("NNN_SSHFS", utils[UTIL_SSHFS]);
4883 else if (opt == 'r') {
4884 flag |= F_NOWAIT | F_NOTRACE;
4885 env = xgetenv("NNN_RCLONE", "rclone mount");
4887 printmsg(messages[MSG_INVALID_KEY]);
4891 tmp = xreadline(NULL, "host[:dir] > ");
4893 printmsg(messages[MSG_CANCEL]);
4897 char *div = strchr(tmp, ':');
4902 /* Create the mount point */
4903 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4904 mkpath(mntpath, tmp, newpath);
4905 if (!xmktree(newpath, TRUE)) {
4910 if (!div) { /* Convert "host" to "host:" */
4911 size_t len = xstrlen(tmp);
4914 tmp[len + 1] = '\0';
4918 /* Connect to remote */
4920 if (spawn(env, tmp, newpath, NULL, flag)) {
4921 printmsg(messages[MSG_FAILED]);
4925 spawn(env, tmp, newpath, NULL, flag);
4926 printmsg(messages[MSG_RCLONE_DELAY]);
4927 xdelay(XDELAY_INTERVAL_MS << 2); /* Set 4 times the usual delay */
4934 * Unmounts if the directory represented by name is a mount point.
4935 * Otherwise, asks for hostname
4936 * Returns TRUE if directory needs to be refreshed *.
4938 static bool unmount(char *name, char *newpath, int *presel, char *currentpath)
4940 #if defined(__APPLE__) || defined(__FreeBSD__)
4941 static char cmd[] = "umount";
4943 static char cmd[] = "fusermount3"; /* Arch Linux utility */
4944 static bool found = FALSE;
4947 struct stat sb, psb;
4949 bool parent = FALSE;
4950 bool hovered = FALSE;
4951 char mntpath[PATH_MAX];
4953 #if !defined(__APPLE__) && !defined(__FreeBSD__)
4954 /* On Ubuntu it's fusermount */
4955 if (!found && !getutil(cmd)) {
4961 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4963 if (tmp && strcmp(mntpath, currentpath) == 0) {
4964 mkpath(mntpath, tmp, newpath);
4965 child = lstat(newpath, &sb) != -1;
4966 parent = lstat(xdirname(newpath), &psb) != -1;
4967 if (!child && !parent) {
4973 if (!tmp || !child || !S_ISDIR(sb.st_mode) || (child && parent && sb.st_dev == psb.st_dev)) {
4974 tmp = xreadline(NULL, messages[MSG_HOSTNAME]);
4977 if (name && (tmp[0] == '-') && (tmp[1] == '\0')) {
4978 mkpath(currentpath, name, newpath);
4984 mkpath(mntpath, tmp, newpath);
4986 if (!xdiraccess(newpath)) {
4991 #if defined(__APPLE__) || defined(__FreeBSD__)
4992 if (spawn(cmd, newpath, NULL, NULL, F_NORMAL)) {
4994 if (spawn(cmd, "-qu", newpath, NULL, F_NORMAL)) {
4996 if (!xconfirm(get_input(messages[MSG_LAZY])))
5000 if (spawn(cmd, "-l", newpath, NULL, F_NORMAL)) {
5001 #elif defined(__FreeBSD__)
5002 if (spawn(cmd, "-f", newpath, NULL, F_NORMAL)) {
5004 if (spawn(cmd, "-quz", newpath, NULL, F_NORMAL)) {
5006 printwait(messages[MSG_FAILED], presel);
5011 if (rmdir(newpath) == -1) {
5019 static void lock_terminal(void)
5021 spawn(xgetenv("NNN_LOCKER", utils[UTIL_LOCKER]), NULL, NULL, NULL, F_CLI);
5024 static void printkv(kv *kvarr, int fd, uchar_t max, uchar_t id)
5026 char *val = (id == NNN_BMS) ? bmstr : pluginstr;
5028 for (uchar_t i = 0; i < max && kvarr[i].key; ++i)
5029 dprintf(fd, " %c: %s\n", (char)kvarr[i].key, val + kvarr[i].off);
5032 static void printkeys(kv *kvarr, char *buf, uchar_t max)
5036 for (; i < max && kvarr[i].key; ++i) {
5038 buf[(i << 1) + 1] = kvarr[i].key;
5044 static size_t handle_bookmark(const char *bmark, char *newpath)
5049 if (maxbm || bmark) {
5050 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
5052 if (bmark) { /* There is a marked directory */
5058 printkeys(bookmark, g_buf + r - 1, maxbm);
5060 fd = get_input(NULL);
5064 if (fd == ',') /* Visit marked directory */
5065 bmark ? xstrsncpy(newpath, bmark, PATH_MAX) : (r = MSG_NOT_SET);
5066 else if (fd == '\r') { /* Visit bookmarks directory */
5067 mkpath(cfgpath, toks[TOK_BM], newpath);
5069 } else if (!get_kv_val(bookmark, newpath, fd, maxbm, NNN_BMS))
5070 r = MSG_INVALID_KEY;
5072 if (!r && chdir(newpath) == -1) {
5081 static void add_bookmark(char *path, char *newpath, int *presel)
5083 char *dir = xbasename(path);
5085 dir = xreadline(dir[0] ? dir : NULL, messages[MSG_BM_NAME]);
5087 size_t r = mkpath(cfgpath, toks[TOK_BM], newpath);
5089 newpath[r - 1] = '/';
5090 xstrsncpy(newpath + r, dir, PATH_MAX - r);
5091 printwait((symlink(path, newpath) == -1) ? strerror(errno) : newpath, presel);
5093 printwait(messages[MSG_CANCEL], presel);
5097 * The help string tokens (each line) start with a HEX value which indicates
5098 * the number of spaces to print before the particular token. In the middle,
5099 * %NN can be used to insert a run of spaces, e.g %10 will print 10 spaces.
5100 * %NN MUST be 2 characters long, e.g %05 for 5 spaces.
5102 * This method was chosen instead of a flat string because the number of bytes
5103 * in help was increasing the binary size by around a hundred bytes. This would
5104 * only have increased as we keep adding new options.
5106 static void show_help(const char *path)
5108 static const char helpstr[] = {
5116 "9Up k Up%16PgUp ^U Page up\n"
5117 "9Dn j Down%14PgDn ^D Page down\n"
5118 "9Lt h Parent%12~ ` @ - ~, /, start, prev\n"
5119 "5Ret Rt l Open%20' First file/match\n"
5120 "9g ^A Top%21J Jump to entry/offset\n"
5121 "9G ^E End%20^J Toggle auto-advance on open\n"
5122 "8B (,) Book(mark)%11b ^/ Select bookmark\n"
5123 "a1-4 Context%11(Sh)Tab Cycle/new context\n"
5124 "62Esc ^Q Quit%19^y Next young\n"
5125 "b^G QuitCD%18Q Pick/err, quit\n"
5128 "1FILTER & PROMPT\n"
5129 "c/ Filter%17^N Toggle type-to-nav\n"
5130 "aEsc Exit prompt%12^L Toggle last filter\n"
5131 "c. Toggle hidden%05Alt+Esc Unfilter, quit context\n"
5134 "9o ^O Open with%15n Create new/link\n"
5135 "9f ^F File stats%14d Detail mode toggle\n"
5136 "b^R Rename/dup%14r Batch rename\n"
5137 "cz Archive%17e Edit file\n"
5138 "c* Toggle exe%14> Export list\n"
5139 "6Space + (Un)select%12m-m Select range/clear\n"
5140 "ca Select all%14A Invert sel\n"
5141 "9p ^P Copy here%12w ^W Cp/mv sel as\n"
5142 "9v ^V Move here%15E Edit sel list\n"
5143 "9x ^X Delete%18S Listed sel size\n"
5144 "aEsc Send to FIFO\n"
5147 "8Alt ; Select plugin%11= Launch app\n"
5148 "9! ^] Shell%19] Cmd prompt\n"
5149 "cc Connect remote%10u Unmount remote/archive\n"
5150 "9t ^T Sort toggles%12s Manage session\n"
5151 "cT Set time type%110 Lock\n"
5152 "b^L Redraw%18? Help, conf\n"
5155 int fd = create_tmp_file();
5159 char *prog = xgetenv(env_cfg[NNN_HELP], NULL);
5161 get_output(prog, NULL, NULL, fd, FALSE);
5165 const char *end = helpstr + (sizeof helpstr - 1);
5166 for (const char *s = helpstr; s < end; ++s) {
5168 for (int k = 0, n = xchartohex(*s); k < n; ++k) *w++ = ' ';
5169 } else if (*s == '%') {
5170 int n = ((s[1] - '0') * 10) + (s[2] - '0');
5171 for (int k = 0; k < n; ++k) *w++ = ' ';
5178 if (write(fd, g_buf, w - g_buf)) {} // silence warning
5180 dprintf(fd, "\nLOCATIONS\n");
5181 for (uchar_t i = 0; i < CTX_MAX; ++i)
5182 if (g_ctx[i].c_cfg.ctxactive)
5183 dprintf(fd, " %u: %s\n", i + 1, g_ctx[i].c_path);
5185 dprintf(fd, "\nVOLUME: avail:%s ", coolsize(get_fs_info(path, VFS_AVAIL)));
5186 dprintf(fd, "used:%s ", coolsize(get_fs_info(path, VFS_USED)));
5187 dprintf(fd, "size:%s\n\n", coolsize(get_fs_info(path, VFS_SIZE)));
5190 dprintf(fd, "BOOKMARKS\n");
5191 printkv(bookmark, fd, maxbm, NNN_BMS);
5196 dprintf(fd, "PLUGIN KEYS\n");
5197 printkv(plug, fd, maxplug, NNN_PLUG);
5201 for (uchar_t i = NNN_OPENER; i <= NNN_TRASH; ++i) {
5202 char *s = getenv(env_cfg[i]);
5204 dprintf(fd, "%s: %s\n", env_cfg[i], s);
5208 dprintf(fd, "SELECTION FILE: %s\n", selpath);
5210 dprintf(fd, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
5213 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
5217 static void setexports(void)
5223 setenv(envs[ENV_NCUR], pdents[cur].name, 1);
5224 xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
5225 } else if (g_ctx[cfg.curctx].c_name[0])
5226 g_ctx[cfg.curctx].c_name[0] = '\0';
5228 for (uchar_t i = 0; i < CTX_MAX; ++i) {
5229 if (g_ctx[i].c_cfg.ctxactive) {
5230 dvar[1] = fvar[1] = '1' + i;
5231 setenv(dvar, g_ctx[i].c_path, 1);
5233 if (g_ctx[i].c_name[0]) {
5234 mkpath(g_ctx[i].c_path, g_ctx[i].c_name, g_buf);
5235 setenv(fvar, g_buf, 1);
5239 setenv("NNN_INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
5240 setenv("NNN_PREFER_SELECTION", xitoa(cfg.prefersel), 1);
5243 static void run_cmd_as_plugin(const char *file, uchar_t flags)
5247 xstrsncpy(g_buf, file, PATH_MAX);
5249 len = xstrlen(g_buf);
5250 if (len > 1 && g_buf[len - 1] == '*') {
5251 flags &= ~F_CONFIRM; /* Skip user confirmation */
5252 g_buf[len - 1] = '\0'; /* Get rid of trailing no confirmation symbol */
5257 get_output(utils[UTIL_SH_EXEC], g_buf, NULL, -1, TRUE);
5259 spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, flags);
5262 static bool plctrl_init(void)
5266 /* g_tmpfpath is used to generate tmp file names */
5267 g_tmpfpath[tmpfplen - 1] = '\0';
5268 len = xstrsncpy(g_pipepath, g_tmpfpath, TMP_LEN_MAX);
5269 g_pipepath[len - 1] = '/';
5270 len = xstrsncpy(g_pipepath + len, "nnn-pipe.", TMP_LEN_MAX - len) + len;
5271 xstrsncpy(g_pipepath + len - 1, xitoa(getpid()), TMP_LEN_MAX - len);
5272 setenv(env_cfg[NNN_PIPE], g_pipepath, TRUE);
5274 return EXIT_SUCCESS;
5277 static void rmlistpath(void)
5280 DPRINTF_S(__func__);
5281 DPRINTF_S(listpath);
5282 spawn(utils[UTIL_RM_RF], listpath, NULL, NULL, F_NOTRACE | F_MULTI);
5283 /* Do not free if program was started in list mode */
5284 if (listpath != initpath)
5290 static ssize_t read_nointr(int fd, void *buf, size_t count)
5295 len = read(fd, buf, count);
5296 while (len == -1 && errno == EINTR);
5301 static char *readpipe(int fd, char *ctxnum, char **path)
5303 char ctx, *nextpath = NULL;
5305 if (read_nointr(fd, g_buf, 1) != 1)
5308 if (g_buf[0] == '-') { /* Clear selection on '-' */
5310 if (read_nointr(fd, g_buf, 1) != 1)
5314 if (g_buf[0] == '+')
5315 ctx = (char)(get_free_ctx() + 1);
5316 else if (g_buf[0] < '0')
5319 ctx = g_buf[0] - '0';
5324 if (read_nointr(fd, g_buf, 1) != 1)
5330 ssize_t len = read_nointr(fd, g_buf, PATH_MAX);
5335 g_buf[len] = '\0'; /* Terminate the path read */
5336 if (g_buf[0] == '/') {
5338 len = xstrlen(g_buf);
5339 while (--len && (g_buf[len] == '/')) /* Trim all trailing '/' */
5342 } else if (op == 'l') {
5343 rmlistpath(); /* Remove last list mode path, if any */
5344 nextpath = load_input(fd, *path);
5345 } else if (op == 'p') {
5358 static bool run_plugin(char **path, const char *file, char *runfile, char **lastname, char **lastdir)
5363 bool cmd_as_plugin = FALSE;
5366 if (!g_state.pluginit) {
5368 g_state.pluginit = 1;
5373 /* Check for run-cmd-as-plugin mode */
5375 flags = F_MULTI | F_CONFIRM;
5378 if (*file == '|') { /* Check if output should be paged */
5381 } else if (*file == '&') { /* Check if GUI flags are to be used */
5382 flags = F_MULTI | F_NOTRACE | F_NOWAIT;
5389 if ((flags & F_NOTRACE) || (flags & F_PAGE)) {
5390 run_cmd_as_plugin(file, flags);
5394 cmd_as_plugin = TRUE;
5397 if (mkfifo(g_pipepath, 0600) != 0)
5404 if (!p) { // In child
5405 int wfd = open(g_pipepath, O_WRONLY | O_CLOEXEC);
5408 _exit(EXIT_FAILURE);
5410 if (!cmd_as_plugin) {
5414 /* Generate absolute path to plugin */
5415 mkpath(plgpath, file, g_buf);
5418 sel = selpath ? selpath : std;
5420 if (runfile && runfile[0]) {
5421 xstrsncpy(*lastname, runfile, NAME_MAX);
5422 spawn(g_buf, *lastname, *path, sel, 0);
5424 spawn(g_buf, NULL, *path, sel, 0);
5426 run_cmd_as_plugin(file, flags);
5429 _exit(EXIT_SUCCESS);
5435 rfd = open(g_pipepath, O_RDONLY);
5436 while (rfd == -1 && errno == EINTR);
5438 nextpath = readpipe(rfd, &ctx, path);
5440 set_smart_ctx(ctx, nextpath, path, runfile, lastname, lastdir);
5444 /* wait for the child to finish. no zombies allowed */
5445 waitpid(p, NULL, 0);
5454 static bool launch_app(char *newpath)
5457 char *tmp = newpath;
5459 mkpath(plgpath, utils[UTIL_LAUNCH], newpath);
5461 if (!getutil(utils[UTIL_FZF]) || access(newpath, X_OK) < 0) {
5462 tmp = xreadline(NULL, messages[MSG_APP_NAME]);
5463 r = F_NOWAIT | F_NOTRACE | F_MULTI;
5466 if (tmp && *tmp) // NOLINT
5467 spawn(tmp, (r == F_NORMAL) ? "0" : NULL, NULL, NULL, r);
5472 /* Returns TRUE if at least one command was run */
5473 static bool prompt_run(void)
5476 char *cmdline, *next;
5477 int cnt_j, cnt_J, cmd_ret;
5480 const char *xargs_j = "xargs -0 -I{} %s < %s";
5481 const char *xargs_J = "xargs -0 %s < %s";
5482 char cmd[CMD_LEN_MAX + 32]; // 32 for xargs format strings
5486 if (g_state.picker || g_state.xprompt) {
5488 cmdline = xreadline(NULL, PROMPT);
5491 cmdline = getreadline("\n"PROMPT);
5493 // Check for an empty command
5494 if (!cmdline || !cmdline[0])
5498 lastcmd = xstrdup(cmdline);
5501 len = xstrlen(cmdline);
5505 while ((next = strstr(next, "%j"))) {
5508 // replace %j with {} for xargs later
5517 while ((next = strstr(next, "%J"))) {
5520 // %J should be the last thing in the command
5521 if (next == cmdline + len - 2) {
5522 cmdline[len - 2] = '\0';
5528 // We can't handle both %j and %J in a single command
5533 snprintf(cmd, CMD_LEN_MAX + 32, xargs_j, cmdline, selpath);
5535 snprintf(cmd, CMD_LEN_MAX + 32, xargs_J, cmdline, selpath);
5537 cmd_ret = spawn(shell, "-c", (cnt_j || cnt_J) ? cmd : cmdline, NULL, F_CLI | F_CONFIRM);
5538 if ((cnt_j || cnt_J) && cmd_ret == 0)
5545 static bool handle_cmd(enum action sel, char *newpath)
5547 endselection(FALSE);
5549 if (sel == SEL_LAUNCH)
5550 return launch_app(newpath);
5554 if (sel == SEL_PROMPT)
5555 return prompt_run();
5557 /* Set nnn nesting level */
5558 char *tmp = getenv(env_cfg[NNNLVL]);
5559 int r = tmp ? atoi(tmp) : 0;
5561 setenv(env_cfg[NNNLVL], xitoa(r + 1), 1);
5562 spawn(shell, NULL, NULL, NULL, F_CLI);
5563 setenv(env_cfg[NNNLVL], xitoa(r), 1);
5567 static void dentfree(void)
5573 /* Thread data cleanup */
5579 static void *du_thread(void *p_data)
5581 thread_data *pdata = (thread_data *)p_data;
5582 char *path[2] = {pdata->path, NULL};
5583 ullong_t tfiles = 0;
5584 blkcnt_t tblocks = 0;
5586 FTS *tree = fts_open(path, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR, 0);
5589 while ((node = fts_read(tree))) {
5590 if (node->fts_info & FTS_D) {
5591 if (g_state.interrupt)
5596 sb = node->fts_statp;
5598 if (cfg.apparentsz) {
5599 if (sb->st_size && DU_TEST)
5600 tblocks += sb->st_size;
5601 } else if (sb->st_blocks && DU_TEST)
5602 tblocks += sb->st_blocks;
5609 if (pdata->entnum >= 0)
5610 pdents[pdata->entnum].blocks = tblocks;
5612 if (!pdata->mntpoint) {
5613 core_blocks[pdata->core] += tblocks;
5614 core_files[pdata->core] += tfiles;
5616 core_files[pdata->core] += 1;
5618 pthread_mutex_lock(&running_mutex);
5619 threadbmp |= (1 << pdata->core);
5621 pthread_mutex_unlock(&running_mutex);
5626 static void dirwalk(char *path, int entnum, bool mountpoint)
5628 /* Loop till any core is free */
5629 while (active_threads == NUM_DU_THREADS);
5631 if (g_state.interrupt)
5634 pthread_mutex_lock(&running_mutex);
5635 int core = ffs(threadbmp) - 1;
5637 threadbmp &= ~(1 << core);
5639 pthread_mutex_unlock(&running_mutex);
5641 xstrsncpy(core_data[core].path, path, PATH_MAX);
5642 core_data[core].entnum = entnum;
5643 core_data[core].core = (ushort_t)core;
5644 core_data[core].mntpoint = mountpoint;
5648 pthread_create(&tid, NULL, du_thread, (void *)&(core_data[core]));
5651 addstr(xbasename(path));
5652 addstr(" [^C aborts]\n");
5656 static bool prep_threads(void)
5658 if (!g_state.duinit) {
5660 threadbmp >>= (32 - NUM_DU_THREADS);
5663 core_blocks = calloc(NUM_DU_THREADS, sizeof(blkcnt_t));
5665 core_data = calloc(NUM_DU_THREADS, sizeof(thread_data));
5667 core_files = calloc(NUM_DU_THREADS, sizeof(ullong_t));
5669 if (!core_blocks || !core_data || !core_files) {
5674 /* Increase current open file descriptor limit */
5677 g_state.duinit = TRUE;
5679 memset(core_blocks, 0, NUM_DU_THREADS * sizeof(blkcnt_t));
5680 memset(core_data, 0, NUM_DU_THREADS * sizeof(thread_data));
5681 memset(core_files, 0, NUM_DU_THREADS * sizeof(ullong_t));
5686 /* Skip self and parent */
5687 static inline bool selforparent(const char *path)
5689 return path[0] == '.' && (path[1] == '\0' || (path[1] == '.' && path[2] == '\0'));
5692 static int dentfill(char *path, struct entry **ppdents)
5694 uchar_t entflags = 0;
5697 char *namep, *pnb, *buf;
5698 struct entry *dentp;
5699 size_t off = 0, namebuflen = NAMEBUF_INCR;
5700 struct stat sb_path, sb;
5701 DIR *dirp = opendir(path);
5704 gtimesecs = time(NULL);
5706 DPRINTF_S(__func__);
5711 int fd = dirfd(dirp);
5718 if (fstatat(fd, path, &sb_path, 0) == -1)
5722 ihashbmp = calloc(1, HASH_OCTETS << 3);
5726 memset(ihashbmp, 0, HASH_OCTETS << 3);
5728 if (!prep_threads())
5731 attron(COLOR_PAIR(cfg.curctx + 1));
5734 #if _POSIX_C_SOURCE >= 200112L
5735 posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
5742 #if defined(__sun) || defined(__HAIKU__)
5743 flags = AT_SYMLINK_NOFOLLOW; /* no d_type */
5745 if (cfg.blkorder || dp->d_type == DT_UNKNOWN) {
5747 * Optimization added for filesystems which support dirent.d_type
5750 * - the symlink size is set to 0
5751 * - the modification time of the symlink is set to that of the target file
5753 flags = AT_SYMLINK_NOFOLLOW;
5760 if (selforparent(namep))
5763 if (!cfg.showhidden && namep[0] == '.') {
5767 if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
5770 if (S_ISDIR(sb.st_mode)) {
5771 if (sb_path.st_dev == sb.st_dev) { // NOLINT
5772 mkpath(path, namep, buf); // NOLINT
5773 dirwalk(buf, -1, FALSE);
5775 if (g_state.interrupt)
5779 /* Do not recount hard links */
5780 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5781 dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5788 if (fstatat(fd, namep, &sb, flags) == -1) {
5789 if (flags || (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)) {
5794 DPRINTF_S(strerror(errno));
5797 entflags = FILE_MISSING;
5798 memset(&sb, 0, sizeof(struct stat));
5799 } else /* Orphaned symlink */
5800 entflags = SYM_ORPHAN;
5803 if (ndents == total_dents) {
5805 while (active_threads);
5807 total_dents += ENTRY_INCR;
5808 *ppdents = xrealloc(*ppdents, total_dents * sizeof(**ppdents));
5814 DPRINTF_P(*ppdents);
5817 /* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
5818 if (namebuflen - off < NAME_MAX + 1) {
5819 namebuflen += NAMEBUF_INCR;
5822 pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
5828 DPRINTF_P(pnamebuf);
5830 /* realloc() may result in memory move, we must re-adjust if that happens */
5831 if (pnb != pnamebuf) {
5833 dentp->name = pnamebuf;
5835 for (int count = 1; count < ndents; ++dentp, ++count)
5836 /* Current file name starts at last file name start + length */
5837 (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
5841 dentp = *ppdents + ndents;
5843 /* Selection file name */
5844 dentp->name = (char *)((size_t)pnamebuf + off);
5845 dentp->nlen = xstrsncpy(dentp->name, namep, NAME_MAX + 1);
5848 /* Copy other fields */
5849 if (cfg.timetype == T_MOD) {
5850 dentp->sec = sb.st_mtime;
5852 dentp->nsec = (uint_t)sb.st_mtimespec.tv_nsec;
5854 dentp->nsec = (uint_t)sb.st_mtim.tv_nsec;
5856 } else if (cfg.timetype == T_ACCESS) {
5857 dentp->sec = sb.st_atime;
5859 dentp->nsec = (uint_t)sb.st_atimespec.tv_nsec;
5861 dentp->nsec = (uint_t)sb.st_atim.tv_nsec;
5864 dentp->sec = sb.st_ctime;
5866 dentp->nsec = (uint_t)sb.st_ctimespec.tv_nsec;
5868 dentp->nsec = (uint_t)sb.st_ctim.tv_nsec;
5872 if ((gtimesecs - sb.st_mtime <= 300) || (gtimesecs - sb.st_ctime <= 300))
5873 entflags |= FILE_YOUNG;
5875 #if !(defined(__sun) || defined(__HAIKU__))
5876 if (!flags && dp->d_type == DT_LNK) {
5877 /* Do not add sizes for links */
5878 dentp->mode = (sb.st_mode & ~S_IFMT) | S_IFLNK;
5879 dentp->size = listpath ? sb.st_size : 0;
5881 dentp->mode = sb.st_mode;
5882 dentp->size = sb.st_size;
5885 dentp->mode = sb.st_mode;
5886 dentp->size = sb.st_size;
5890 dentp->uid = sb.st_uid;
5891 dentp->gid = sb.st_gid;
5894 dentp->flags = S_ISDIR(sb.st_mode) ? 0 : ((sb.st_nlink > 1) ? HARD_LINK : 0);
5896 dentp->flags |= entflags;
5901 if (S_ISDIR(sb.st_mode)) {
5902 mkpath(path, namep, buf); // NOLINT
5904 /* Need to show the disk usage of this dir */
5905 dirwalk(buf, ndents, (sb_path.st_dev != sb.st_dev)); // NOLINT
5907 if (g_state.interrupt)
5910 dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5911 /* Do not recount hard links */
5912 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5913 dir_blocks += dentp->blocks;
5919 /* Flag if this is a dir or symlink to a dir */
5920 if (S_ISLNK(sb.st_mode)) {
5922 fstatat(fd, namep, &sb, 0);
5925 if (S_ISDIR(sb.st_mode))
5926 dentp->flags |= DIR_OR_DIRLNK;
5927 #if !(defined(__sun) || defined(__HAIKU__)) /* no d_type */
5928 } else if (dp->d_type == DT_DIR || ((dp->d_type == DT_LNK
5929 || dp->d_type == DT_UNKNOWN) && S_ISDIR(sb.st_mode))) {
5930 dentp->flags |= DIR_OR_DIRLNK;
5935 } while ((dp = readdir(dirp)));
5938 if (g_state.duinit && cfg.blkorder) {
5939 while (active_threads);
5941 attroff(COLOR_PAIR(cfg.curctx + 1));
5942 for (int i = 0; i < NUM_DU_THREADS; ++i) {
5943 num_files += core_files[i];
5944 dir_blocks += core_blocks[i];
5948 /* Should never be null */
5949 if (closedir(dirp) == -1)
5955 static void populate(char *path, char *lastname)
5958 struct timespec ts1, ts2;
5960 clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
5963 ndents = dentfill(path, &pdents);
5968 ENTSORT(pdents, ndents, entrycmpfn);
5972 clock_gettime(CLOCK_REALTIME, &ts2);
5973 DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
5976 /* Find cur from history */
5977 /* No NULL check for lastname, always points to an array */
5978 move_cursor(*lastname ? dentfind(lastname, ndents) : 0, 0);
5980 // Force full redraw
5981 last_curscroll = -1;
5985 static void notify_fifo(bool force)
5991 fifofd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC);
5994 /* Unexpected error, the FIFO file might have been removed */
5995 /* We give up FIFO notification */
6001 static struct entry lastentry;
6003 if (!force && !memcmp(&lastentry, &pdents[cur], sizeof(struct entry))) // NOLINT
6006 lastentry = pdents[cur];
6008 char path[PATH_MAX];
6009 size_t len = mkpath(g_ctx[cfg.curctx].c_path, ndents ? pdents[cur].name : "", path);
6011 path[len - 1] = '\n';
6013 ssize_t ret = write(fifofd, path, len);
6015 if (ret != (ssize_t)len && !(ret == -1 && (errno == EAGAIN || errno == EPIPE))) {
6016 DPRINTF_S(strerror(errno));
6020 static void send_to_explorer(int *presel)
6023 int fd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0600);
6024 if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
6033 notify_fifo(TRUE); /* Send opened path to NNN_FIFO */
6037 static void move_cursor(int target, int ignore_scrolloff)
6039 int onscreen = xlines - 4; /* Leave top 2 and bottom 2 lines */
6041 target = MAX(0, MIN(ndents - 1, target));
6042 last_curscroll = curscroll;
6046 if (!ignore_scrolloff) {
6047 int delta = target - last;
6048 int scrolloff = MIN(SCROLLOFF, onscreen >> 1);
6051 * When ignore_scrolloff is 1, the cursor can jump into the scrolloff
6052 * margin area, but when ignore_scrolloff is 0, act like a boa
6053 * constrictor and squeeze the cursor towards the middle region of the
6054 * screen by allowing it to move inward and disallowing it to move
6055 * outward (deeper into the scrolloff margin area).
6057 if (((cur < (curscroll + scrolloff)) && delta < 0)
6058 || ((cur > (curscroll + onscreen - scrolloff - 1)) && delta > 0))
6061 curscroll = MIN(curscroll, MIN(cur, ndents - onscreen));
6062 curscroll = MAX(curscroll, MAX(cur - (onscreen - 1), 0));
6065 if (!g_state.fifomode)
6066 notify_fifo(FALSE); /* Send hovered path to NNN_FIFO */
6070 static void handle_screen_move(enum action sel)
6076 if (cfg.rollover || (cur != ndents - 1))
6077 move_cursor((cur + 1) % ndents, 0);
6080 if (cfg.rollover || cur)
6081 move_cursor((cur + ndents - 1) % ndents, 0);
6084 onscreen = xlines - 4;
6085 move_cursor(curscroll + (onscreen - 1), 1);
6086 curscroll += onscreen - 1;
6089 onscreen = xlines - 4;
6090 move_cursor(curscroll + (onscreen - 1), 1);
6091 curscroll += onscreen >> 1;
6094 onscreen = xlines - 4;
6095 move_cursor(curscroll, 1);
6096 curscroll -= onscreen - 1;
6099 onscreen = xlines - 4;
6100 move_cursor(curscroll, 1);
6101 curscroll -= onscreen >> 1;
6105 char *input = xreadline(NULL, "jump (+n/-n/n): ");
6107 if (!input || !*input)
6109 if (input[0] == '-') {
6110 cur -= atoi(input + 1);
6113 } else if (input[0] == '+') {
6114 cur += atoi(input + 1);
6118 int index = atoi(input);
6120 if ((index < 1) || (index > ndents))
6124 onscreen = xlines - 4;
6125 move_cursor(cur, 1);
6126 curscroll -= onscreen >> 1;
6133 move_cursor(ndents - 1, 1);
6137 for (int r = cur;;) {
6142 if (pdents[r].flags & FILE_YOUNG) {
6149 default: /* case SEL_FIRST */
6151 int c = get_input(messages[MSG_FIRST]);
6158 int r = (c == TOUPPER(*pdents[cur].name)) ? (cur + 1) : 0;
6160 for (; r < ndents; ++r) {
6161 if (((c == '\'') && !(pdents[r].flags & DIR_OR_DIRLNK))
6162 || (c == TOUPPER(*pdents[r].name))) {
6163 move_cursor((r) % ndents, 0);
6172 static void handle_openwith(const char *path, const char *name, char *newpath, char *tmp)
6174 /* Confirm if app is CLI or GUI */
6175 int r = get_input(messages[MSG_CLI_MODE]);
6177 r = (r == 'c' ? F_CLI :
6178 ((r == 'g' || r == '\r') ? (F_NOWAIT | F_NOTRACE | F_MULTI) : 0));
6180 mkpath(path, name, newpath);
6181 spawn(tmp, newpath, NULL, NULL, r);
6185 static void copynextname(char *lastname)
6188 cur += (cur != (ndents - 1)) ? 1 : -1;
6194 static int handle_context_switch(enum action sel)
6199 case SEL_CYCLE: // fallthrough
6201 /* visit next and previous contexts */
6203 if (sel == SEL_CYCLE)
6205 r = (r + 1) & ~CTX_MAX;
6206 while (!g_ctx[r].c_cfg.ctxactive);
6208 do /* Attempt to create a new context */
6209 r = (r + 1) & ~CTX_MAX;
6210 while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
6212 if (r == cfg.curctx) /* If all contexts are active, reverse cycle */
6214 r = (r + (CTX_MAX - 1)) & (CTX_MAX - 1);
6215 while (!g_ctx[r].c_cfg.ctxactive);
6217 default: /* SEL_CTXN */
6218 if (sel >= SEL_CTX1) /* CYCLE keys are lesser in value */
6219 r = sel - SEL_CTX1; /* Save the next context id */
6221 if (cfg.curctx == r) {
6222 if (sel == SEL_CYCLE)
6223 (r == CTX_MAX - 1) ? (r = 0) : ++r;
6224 else if (sel == SEL_CYCLER)
6225 (r == 0) ? (r = CTX_MAX - 1) : --r;
6234 static int set_sort_flags(int r)
6236 bool session = (r == '\0');
6237 bool reverse = FALSE;
6239 if (ISUPPER_(r) && (r != 'R') && (r != 'C')) {
6244 /* Set the correct input in case of a session load */
6246 if (cfg.apparentsz) {
6249 } else if (cfg.blkorder) {
6254 entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
6255 namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
6256 } else if (r == CONTROL('T')) {
6257 /* Cycling order: clear -> size -> time -> clear */
6260 else if (cfg.sizeorder)
6267 case 'a': /* Apparent du */
6268 cfg.apparentsz ^= 1;
6269 if (cfg.apparentsz) {
6275 case 'd': /* Disk usage */
6277 if (!cfg.apparentsz)
6280 blk_shift = ffs(S_BLKSIZE) - 1;
6290 entrycmpfn = &entrycmp;
6292 endselection(TRUE); /* We are going to reload dir */
6302 entrycmpfn = &entrycmp;
6303 namecmpfn = &xstricmp;
6305 case 'e': /* File extension */
6312 entrycmpfn = &entrycmp;
6314 case 'r': /* Reverse sort */
6316 entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
6318 case 's': /* File size */
6325 entrycmpfn = &entrycmp;
6327 case 't': /* Time */
6334 entrycmpfn = &entrycmp;
6336 case 'v': /* Version */
6338 namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
6351 entrycmpfn = &reventrycmp;
6354 cfgsort[cfg.curctx] = (uchar_t)r;
6359 static bool set_time_type(int *presel)
6362 char buf[] = "'a'ccess / 'c'hange / 'm'od [ ]";
6364 buf[sizeof(buf) - 3] = cfg.timetype == T_MOD ? 'm' : (cfg.timetype == T_ACCESS ? 'a' : 'c');
6366 int r = get_input(buf);
6368 if (r == 'a' || r == 'c' || r == 'm') {
6369 r = (r == 'm') ? T_MOD : ((r == 'a') ? T_ACCESS : T_CHANGE);
6370 if (cfg.timetype != r) {
6373 if (cfg.filtermode || g_ctx[cfg.curctx].c_fltr[1])
6380 r = MSG_INVALID_KEY;
6383 printwait(messages[r], presel);
6388 static void statusbar(char *path)
6392 pEntry pent = &pdents[cur];
6399 /* Get the file extension for regular files */
6400 if (S_ISREG(pent->mode)) {
6401 i = (int)(pent->nlen - 1);
6402 ptr = xextension(pent->name, i);
6404 len = i - (ptr - pent->name);
6405 if (!ptr || len > 5 || len < 2)
6410 attron(COLOR_PAIR(cfg.curctx + 1));
6412 if (cfg.fileinfo && get_output("file", "-b", pdents[cur].name, -1, FALSE))
6413 mvaddstr(xlines - 2, 2, g_buf);
6417 printw("%d/%s ", cur + 1, xitoa(ndents));
6419 if (g_state.selmode || nselected) {
6422 if (g_state.rangesel)
6424 else if (g_state.selmode)
6427 addstr(xitoa(nselected));
6433 if (cfg.blkorder) { /* du mode */
6436 xstrsncpy(buf, coolsize(dir_blocks << blk_shift), 12);
6438 printw("%cu:%s avail:%s files:%llu %lluB %s\n",
6439 (cfg.apparentsz ? 'a' : 'd'), buf, coolsize(get_fs_info(path, VFS_AVAIL)),
6440 num_files, (ullong_t)pent->blocks << blk_shift, ptr);
6441 } else { /* light or detail mode */
6442 char sort[] = "\0\0\0\0\0";
6444 if (getorderstr(sort))
6448 print_time(&pent->sec, pent->flags);
6451 addstr(get_lsperms(pent->mode));
6454 if (g_state.uidgid) {
6455 addstr(getpwname(pent->uid));
6457 addstr(getgrname(pent->gid));
6461 if (S_ISLNK(pent->mode)) {
6462 if (!cfg.fileinfo) {
6463 i = readlink(pent->name, g_buf, PATH_MAX);
6464 addstr(coolsize(i >= 0 ? i : pent->size)); /* Show symlink size */
6465 if (i > 1) { /* Show symlink target */
6469 getyx(stdscr, len, y);
6470 i = MIN(i, xcols - y);
6476 addstr(coolsize(pent->size));
6479 if (pent->flags & HARD_LINK) {
6482 if (stat(pent->name, &sb) != -1) {
6484 addstr(xitoa((int)sb.st_nlink)); /* Show number of links */
6486 addstr(xitoa((int)sb.st_ino)); /* Show inode number */
6493 attroff(COLOR_PAIR(cfg.curctx + 1));
6494 /* Place HW cursor on current for Braille systems */
6498 static inline void markhovered(void)
6500 if (cfg.showdetail && ndents) { /* Bold forward arrowhead */
6502 addch('>' | A_BOLD);
6506 static int adjust_cols(int n)
6508 /* Calculate the number of cols available to print entry name */
6509 #ifdef ICONS_ENABLED
6510 n -= (g_state.oldcolor ? 0 : ICON_SIZE + ICON_PADDING_LEFT_LEN + ICON_PADDING_RIGHT_LEN);
6512 if (cfg.showdetail) {
6513 /* Fallback to light mode if less than 35 columns */
6515 cfg.showdetail ^= 1;
6516 else /* 2 more accounted for below */
6520 /* 2 columns for preceding space and indicator */
6524 static void draw_line(int ncols)
6528 ncols = adjust_cols(ncols);
6530 if (g_state.oldcolor && (pdents[last].flags & DIR_OR_DIRLNK)) {
6531 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6535 move(2 + last - curscroll, 0);
6537 printent(&pdents[last], ncols, FALSE);
6539 if (g_state.oldcolor && (pdents[cur].flags & DIR_OR_DIRLNK)) {
6540 if (!dir) {/* First file is not a directory */
6541 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6544 } else if (dir) { /* Second file is not a directory */
6545 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6549 move(2 + cur - curscroll, 0);
6551 printent(&pdents[cur], ncols, TRUE);
6553 /* Must reset e.g. no files in dir */
6555 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6560 static void redraw(char *path)
6562 getmaxyx(stdscr, xlines, xcols);
6564 int ncols = (xcols <= PATH_MAX) ? xcols : PATH_MAX;
6565 int onscreen = xlines - 4;
6572 if (ndents && (last_curscroll == curscroll))
6573 return draw_line(ncols);
6576 DPRINTF_S(__func__);
6581 /* Enforce scroll/cursor invariants */
6582 move_cursor(cur, 1);
6584 /* Fail redraw if < than 10 columns, context info prints 10 chars */
6585 if (ncols <= MIN_DISPLAY_COL) {
6586 printmsg(messages[MSG_FEW_COLUMNS]);
6593 for (i = 0; i < CTX_MAX; ++i) { /* 8 chars printed for contexts - "1 2 3 4 " */
6594 if (!g_ctx[i].c_cfg.ctxactive)
6597 addch((i + '1') | (COLOR_PAIR(i + 1) | A_BOLD
6598 /* active: underline, current: reverse */
6599 | ((cfg.curctx != i) ? A_UNDERLINE : A_REVERSE)));
6604 attron(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6607 bool in_home = set_tilde_in_path(path);
6608 char *ptr = in_home ? &path[homelen - 1] : path;
6610 i = (int)xstrlen(ptr);
6611 if ((i + MIN_DISPLAY_COL) <= ncols)
6612 addnstr(ptr, ncols - MIN_DISPLAY_COL);
6614 char *base = xmemrchr((uchar_t *)ptr, '/', i);
6623 if (ptr && (base != ptr)) {
6624 while (ptr < base) {
6626 i += 2; /* 2 characters added */
6627 if (ncols < i + MIN_DISPLAY_COL) {
6628 base = NULL; /* Can't print more characters */
6640 addnstr(base, ncols - (MIN_DISPLAY_COL + i));
6644 reset_tilde_in_path(path);
6646 attroff(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6648 /* Go to first entry */
6649 if (curscroll > 0) {
6651 #ifdef ICONS_ENABLED
6652 addstr(ICON_ARROW_UP);
6658 if (g_state.oldcolor) {
6659 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6660 g_state.dircolor = 1;
6663 onscreen = MIN(onscreen + curscroll, ndents);
6665 ncols = adjust_cols(ncols);
6667 int len = scanselforpath(path, FALSE);
6670 for (i = curscroll; i < onscreen; ++i) {
6674 findmarkentry(len, &pdents[i]);
6676 printent(&pdents[i], ncols, i == cur);
6679 /* Must reset e.g. no files in dir */
6680 if (g_state.dircolor) {
6681 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6682 g_state.dircolor = 0;
6685 /* Go to last entry */
6686 if (onscreen < ndents) {
6687 move(xlines - 2, 0);
6688 #ifdef ICONS_ENABLED
6689 addstr(ICON_ARROW_DOWN);
6698 static bool cdprep(char *lastdir, char *lastname, char *path, char *newpath)
6703 /* Save last working directory */
6704 xstrsncpy(lastdir, path, PATH_MAX);
6706 /* Save the newly opted dir in path */
6707 xstrsncpy(path, newpath, PATH_MAX);
6711 return cfg.filtermode;
6714 static void showselsize(const char *path)
6717 int len = scanselforpath(path, FALSE);
6719 for (int r = 0, selcount = nselected; (r < ndents) && selcount; ++r)
6720 if (findinsel(findselpos, len + xstrsncpy(g_sel + len, pdents[r].name, pdents[r].nlen))) {
6721 sz += cfg.blkorder ? pdents[r].blocks : pdents[r].size;
6725 printmsg(coolsize(cfg.blkorder ? sz << blk_shift : sz));
6728 static bool browse(char *ipath, const char *session, int pkey)
6730 alignas(max_align_t) char newpath[PATH_MAX];
6731 alignas(max_align_t) char runfile[NAME_MAX + 1];
6732 char *path, *lastdir, *lastname, *dir, *tmp;
6736 int r = -1, presel, selstartid = 0, selendid = 0;
6737 const uchar_t opener_flags = (cfg.cliopener ? F_CLI : (F_NOTRACE | F_NOSTDIN | F_NOWAIT));
6738 bool watch = FALSE, cd = TRUE;
6743 struct timespec mousetimings[2] = {{.tv_sec = 0, .tv_nsec = 0}, {.tv_sec = 0, .tv_nsec = 0}};
6744 int mousedent[2] = {-1, -1};
6745 bool currentmouse = 1, rightclicksel = 0;
6750 getmaxyx(stdscr, xlines, xcols);
6753 /* set-up first context */
6754 if (!session || !load_session(session, &path, &lastdir, &lastname, FALSE)) {
6758 g_ctx[0].c_last[0] = '\0';
6759 lastdir = g_ctx[0].c_last; /* last visited directory */
6761 if (g_state.initfile) {
6762 xstrsncpy(g_ctx[0].c_name, xbasename(ipath), sizeof(g_ctx[0].c_name));
6765 g_ctx[0].c_name[0] = '\0';
6767 lastname = g_ctx[0].c_name; /* last visited file name */
6769 xstrsncpy(g_ctx[0].c_path, ipath, PATH_MAX);
6770 /* If the initial path is a file, retain a way to return to start dir */
6771 if (g_state.initfile) {
6773 initpath = ipath = getcwd(NULL, 0);
6775 path = g_ctx[0].c_path; /* current directory */
6777 g_ctx[0].c_fltr[0] = g_ctx[0].c_fltr[1] = '\0';
6778 g_ctx[0].c_cfg = cfg; /* current configuration */
6783 newpath[0] = runfile[0] = '\0';
6785 presel = pkey ? ((pkey == CREATE_NEW_KEY) ? 'n' : ';') : ((cfg.filtermode
6786 || (session && (g_ctx[cfg.curctx].c_fltr[0] == FILTER
6787 || g_ctx[cfg.curctx].c_fltr[0] == RFILTER)
6788 && g_ctx[cfg.curctx].c_fltr[1])) ? FILTER : 0);
6790 pdents = xrealloc(pdents, total_dents * sizeof(struct entry));
6794 /* Allocate buffer to hold names */
6795 pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
6799 /* The following call is added to handle a broken window at start */
6800 if (presel == FILTER)
6801 handle_key_resize();
6805 * Can fail when permissions change while browsing.
6806 * It's assumed that path IS a directory when we are here.
6808 if (chdir(path) == -1) {
6809 DPRINTF_S("directory inaccessible");
6810 valid_parent(path, lastname);
6818 #ifdef LINUX_INOTIFY
6819 if ((presel == FILTER || watch) && inotify_wd >= 0) {
6820 inotify_rm_watch(inotify_fd, inotify_wd);
6824 #elif defined(BSD_KQUEUE)
6825 if ((presel == FILTER || watch) && event_fd >= 0) {
6830 #elif defined(HAIKU_NM)
6831 if ((presel == FILTER || watch) && haiku_hnd != NULL) {
6832 haiku_stop_watch(haiku_hnd);
6833 haiku_nm_active = FALSE;
6839 if (cfgsort[cfg.curctx] != '0') {
6840 if (cfgsort[cfg.curctx] == 'z')
6841 set_sort_flags('c');
6842 if ((!cfgsort[cfg.curctx] || (cfgsort[cfg.curctx] == 'c'))
6843 && ((r = get_kv_key(order, path, maxorder, NNN_ORDER)) > 0)) { // NOLINT
6845 cfgsort[cfg.curctx] = 'z';
6848 cfgsort[cfg.curctx] = cfgsort[CTX_MAX];
6852 populate(path, lastname);
6853 if (g_state.interrupt) {
6854 g_state.interrupt = cfg.apparentsz = cfg.blkorder = 0;
6855 blk_shift = BLK_SHIFT_512;
6856 presel = CONTROL('L');
6859 #ifdef LINUX_INOTIFY
6860 if (presel != FILTER && inotify_wd == -1)
6861 inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
6862 #elif defined(BSD_KQUEUE)
6863 if (presel != FILTER && event_fd == -1) {
6864 #if defined(O_EVTONLY)
6865 event_fd = open(path, O_EVTONLY);
6867 event_fd = open(path, O_RDONLY);
6870 EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
6871 EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
6873 #elif defined(HAIKU_NM)
6874 haiku_nm_active = haiku_watch_dir(haiku_hnd, path) == EXIT_SUCCESS;
6878 /* Do not do a double redraw in filterentries */
6879 if ((presel != FILTER) || !filterset()) {
6885 /* Exit if parent has exited */
6887 _exit(EXIT_FAILURE);
6889 /* If CWD is deleted or moved or perms changed, find an accessible parent */
6890 if (chdir(path) == -1)
6893 /* If STDIN is no longer a tty (closed) we should exit */
6894 if (!isatty(STDIN_FILENO) && !g_state.picker)
6895 return EXIT_FAILURE;
6897 sel = nextsel(presel);
6904 if (getmouse(&event) != OK)
6907 /* Handle clicking on a context at the top */
6908 if (event.bstate == BUTTON1_PRESSED && event.y == 0) {
6909 /* Get context from: "[1 2 3 4]..." */
6912 /* If clicked after contexts, go to parent */
6915 else if (r >= 0 && r != cfg.curctx) {
6916 savecurctx(path, ndents ? pdents[cur].name : NULL, r);
6918 /* Reset the pointers */
6919 path = g_ctx[r].c_path;
6920 lastdir = g_ctx[r].c_last;
6921 lastname = g_ctx[r].c_name;
6931 if (sel == SEL_BACK) {
6933 dir = visit_parent(path, newpath, &presel);
6938 xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
6940 cdprep(lastdir, NULL, path, dir) ? (presel = FILTER) : (watch = TRUE);
6947 /* Middle click action */
6948 if (event.bstate == BUTTON2_PRESSED) {
6949 presel = middle_click_key;
6952 #if NCURSES_MOUSE_VERSION > 1
6954 if (event.bstate == BUTTON4_PRESSED && ndents && (cfg.rollover || cur)) {
6955 move_cursor((!cfg.rollover && cur < scroll_lines
6956 ? 0 : (cur + ndents - scroll_lines) % ndents), 0);
6961 if (event.bstate == BUTTON5_PRESSED && ndents
6962 && (cfg.rollover || (cur != ndents - 1))) {
6963 move_cursor((!cfg.rollover && cur >= ndents - scroll_lines)
6964 ? (ndents - 1) : ((cur + scroll_lines) % ndents), 0);
6969 /* Toggle filter mode on left click on last 2 lines */
6970 if (event.y >= xlines - 2 && event.bstate == BUTTON1_PRESSED) {
6972 cfg.filtermode ^= 1;
6973 if (cfg.filtermode) {
6978 /* Start watching the directory */
6985 /* Handle clicking on a file */
6986 if (event.y >= 2 && event.y <= ndents + 1 &&
6987 (event.bstate == BUTTON1_PRESSED ||
6988 event.bstate == BUTTON3_PRESSED)) {
6989 r = curscroll + (event.y - 2);
6993 else if ((event.bstate == BUTTON1_PRESSED) && !g_state.fifomode)
6994 notify_fifo(TRUE); /* Send clicked path to NNN_FIFO */
6996 /* Handle right click selection */
6997 if (event.bstate == BUTTON3_PRESSED) {
7005 #if defined(CLOCK_MONOTONIC_RAW)
7006 CLOCK_MONOTONIC_RAW,
7007 #elif defined(CLOCK_MONOTONIC)
7012 &mousetimings[currentmouse]);
7013 mousedent[currentmouse] = cur;
7015 /* Single click just selects, double click falls through to SEL_OPEN */
7016 if ((mousedent[0] != mousedent[1]) ||
7017 (((_ABSSUB(mousetimings[0].tv_sec, mousetimings[1].tv_sec) << 30)
7018 + (_ABSSUB(mousetimings[0].tv_nsec, mousetimings[1].tv_nsec)))
7019 > DBLCLK_INTERVAL_NS))
7022 mousetimings[currentmouse].tv_sec = 0;
7023 mousedent[currentmouse] = -1;
7026 if (cfg.filtermode || filterset())
7033 case SEL_NAV_IN: // fallthrough
7035 /* Cannot descend in empty directories */
7038 g_state.selbm = g_state.runplugin = 0;
7042 pent = &pdents[cur];
7043 if (!g_state.selbm || !(S_ISLNK(pent->mode) &&
7044 realpath(pent->name, newpath) &&
7045 xstrsncpy(path, lastdir, PATH_MAX)))
7046 mkpath(path, pent->name, newpath);
7050 /* Visit directory */
7051 if (pent->flags & DIR_OR_DIRLNK) {
7052 if (chdir(newpath) == -1) {
7057 cdprep(lastdir, lastname, path, newpath) ? (presel = FILTER) : (watch = TRUE);
7061 /* Cannot use stale data in entry, file may be missing by now */
7062 if (stat(newpath, &sb) == -1) {
7066 DPRINTF_U(sb.st_mode);
7068 /* Do not open non-regular files */
7069 if (!S_ISREG(sb.st_mode)) {
7070 printwait(messages[MSG_UNSUPPORTED], &presel);
7074 /* Handle plugin selection mode */
7075 if (g_state.runplugin) {
7076 g_state.runplugin = 0;
7077 /* Must be in plugin dir and same context to select plugin */
7078 if ((g_state.runctx == cfg.curctx) && !strcmp(path, plgpath)) {
7079 endselection(FALSE);
7080 /* Copy path so we can return back to earlier dir */
7081 xstrsncpy(path, lastdir, PATH_MAX);
7084 if (chdir(path) == -1
7085 || !run_plugin(&path, pent->name, runfile, &lastname, &lastdir)) {
7086 DPRINTF_S("plugin failed!");
7090 return EXIT_SUCCESS;
7093 xstrsncpy(lastname, runfile, NAME_MAX + 1);
7102 if (g_state.fifomode && (sel == SEL_OPEN)) {
7103 send_to_explorer(&presel); /* Write selection to explorer fifo */
7107 /* If opened as vim plugin and Enter/^M pressed, pick */
7108 if (g_state.picker && (sel == SEL_OPEN)) {
7109 if (nselected == 0) /* Pick if none selected */
7110 appendfpath(newpath, mkpath(path, pent->name, newpath));
7111 return EXIT_SUCCESS;
7114 if (sel == SEL_NAV_IN) {
7115 /* If in listing dir, go to target on `l` or Right on symlink */
7116 if (listpath && S_ISLNK(pent->mode)
7117 && is_prefix(path, listpath, xstrlen(listpath))) {
7118 if (!realpath(pent->name, newpath)) {
7125 if (chdir(newpath) == -1) {
7130 cdprep(lastdir, NULL, path, newpath)
7131 ? (presel = FILTER) : (watch = TRUE);
7132 xstrsncpy(lastname, pent->name, NAME_MAX + 1);
7136 /* Open file disabled on right arrow or `l` */
7142 printwait(messages[MSG_EMPTY_FILE], &presel);
7147 #ifdef FILE_MIME_OPTS
7148 && get_output("file", FILE_MIME_OPTS, newpath, -1, FALSE)
7149 && is_prefix(g_buf, "text/", 5)
7151 /* no MIME option; guess from description instead */
7152 && get_output("file", "-bL", newpath, -1, FALSE)
7153 && strstr(g_buf, "text")
7156 spawn(editor, newpath, NULL, NULL, F_CLI);
7157 if (cfg.filtermode) {
7164 /* Get the extension for regex match */
7165 tmp = xextension(pent->name, pent->nlen - 1);
7167 if (tmp && !pcre_exec(archive_pcre, NULL, tmp,
7168 pent->nlen - (tmp - pent->name) - 1, 0, 0, NULL, 0)) {
7170 if (tmp && !regexec(&archive_re, tmp, 0, NULL, 0)) {
7172 r = get_input(messages[MSG_ARCHIVE_OPTS]);
7175 if (r == 'l' || r == 'x') {
7176 mkpath(path, pent->name, newpath);
7177 if (!handle_archive(newpath, r)) {
7187 if ((r == 'm') && !archive_mount(newpath)) {
7192 if (r == 'x' || r == 'm') {
7194 set_smart_ctx('+', newpath, &path,
7195 ndents ? pdents[cur].name : NULL,
7196 &lastname, &lastdir);
7204 printwait(messages[MSG_INVALID_KEY], &presel);
7209 /* Invoke desktop opener as last resort */
7210 spawn(opener, newpath, NULL, NULL, opener_flags);
7212 /* Move cursor to the next entry if not the last entry */
7213 if (g_state.autonext && cur != ndents - 1)
7214 move_cursor((cur + 1) % ndents, 0);
7215 if (cfg.filtermode) {
7220 case SEL_NEXT: // fallthrough
7221 case SEL_PREV: // fallthrough
7222 case SEL_PGDN: // fallthrough
7223 case SEL_CTRL_D: // fallthrough
7224 case SEL_PGUP: // fallthrough
7225 case SEL_CTRL_U: // fallthrough
7226 case SEL_HOME: // fallthrough
7227 case SEL_END: // fallthrough
7228 case SEL_FIRST: // fallthrough
7229 case SEL_JUMP: // fallthrough
7233 handle_screen_move(sel);
7236 case SEL_CDHOME: // fallthrough
7237 case SEL_CDBEGIN: // fallthrough
7238 case SEL_CDLAST: // fallthrough
7240 dir = (sel == SEL_CDHOME) ? home
7241 : ((sel == SEL_CDBEGIN) ? ipath
7242 : ((sel == SEL_CDLAST) ? lastdir
7243 : "/" /* SEL_CDROOT */));
7245 if (!dir || !*dir) {
7246 printwait(messages[MSG_NOT_SET], &presel);
7251 if (strcmp(path, dir) == 0) {
7257 dir = lastdir; /* Go to last dir on home/root key repeat */
7260 if (chdir(dir) == -1) {
7265 /* SEL_CDLAST: dir pointing to lastdir */
7266 xstrsncpy(newpath, dir, PATH_MAX); // fallthrough
7268 if (sel == SEL_BMOPEN) {
7269 r = (int)handle_bookmark(mark, newpath);
7271 printwait(messages[r], &presel);
7275 if (g_state.selbm == 1) /* Allow filtering in bookmarks directory */
7277 if (strcmp(path, newpath) == 0)
7281 /* In list mode, retain the last file name to highlight it, if possible */
7282 cdprep(lastdir, listpath && sel == SEL_CDLAST ? NULL : lastname, path, newpath)
7283 ? (presel = FILTER) : (watch = TRUE);
7286 if ((sel == SEL_REMOTE) && !remote_mount(newpath)) {
7291 set_smart_ctx('+', newpath, &path,
7292 ndents ? pdents[cur].name : NULL, &lastname, &lastdir);
7295 case SEL_CYCLE: // fallthrough
7296 case SEL_CYCLER: // fallthrough
7297 case SEL_CTX1: // fallthrough
7298 case SEL_CTX2: // fallthrough
7299 case SEL_CTX3: // fallthrough
7307 r = handle_context_switch(sel);
7310 savecurctx(path, ndents ? pdents[cur].name : NULL, r);
7312 /* Reset the pointers */
7313 path = g_ctx[r].c_path;
7314 lastdir = g_ctx[r].c_last;
7315 lastname = g_ctx[r].c_name;
7316 tmp = g_ctx[r].c_fltr;
7318 if (cfg.filtermode || ((tmp[0] == FILTER || tmp[0] == RFILTER) && tmp[1]))
7326 mark = xstrdup(path);
7327 printwait(mark, &presel);
7330 add_bookmark(path, newpath, &presel);
7333 /* Unwatch dir if we are still in a filtered view */
7334 #ifdef LINUX_INOTIFY
7335 if (inotify_wd >= 0) {
7336 inotify_rm_watch(inotify_fd, inotify_wd);
7339 #elif defined(BSD_KQUEUE)
7340 if (event_fd >= 0) {
7344 #elif defined(HAIKU_NM)
7345 if (haiku_nm_active) {
7346 haiku_stop_watch(haiku_hnd);
7347 haiku_nm_active = FALSE;
7350 presel = filterentries(path, lastname);
7351 if (presel == ESC) {
7355 if (presel == FILTER) { /* Refresh dir and filter again */
7360 case SEL_MFLTR: // fallthrough
7361 case SEL_HIDDEN: // fallthrough
7362 case SEL_DETAIL: // fallthrough
7366 cfg.filtermode ^= 1;
7367 if (cfg.filtermode) {
7373 watch = TRUE; // fallthrough
7375 if (sel == SEL_HIDDEN) {
7376 cfg.showhidden ^= 1;
7385 cfg.showdetail ^= 1;
7388 default: /* SEL_SORT */
7389 r = set_sort_flags(get_input(messages[MSG_ORDER]));
7391 printwait(messages[MSG_INVALID_KEY], &presel);
7396 if (cfg.filtermode || filterset())
7402 if (r == 'd' || r == 'a') {
7407 ENTSORT(pdents, ndents, entrycmpfn);
7408 move_cursor(ndents ? dentfind(lastname, ndents) : 0, 0);
7411 case SEL_STATS: // fallthrough
7414 tmp = (listpath && xstrcmp(path, listpath) == 0) ? listroot : path;
7415 mkpath(tmp, pdents[cur].name, newpath);
7417 if ((sel == SEL_STATS && !show_stats(newpath))
7418 || (lstat(newpath, &sb) == -1)
7419 || (sel == SEL_CHMODX && !xchmod(newpath, &sb.st_mode))) {
7424 if (sel == SEL_CHMODX)
7425 pdents[cur].mode = sb.st_mode;
7428 case SEL_REDRAW: // fallthrough
7429 case SEL_RENAMEMUL: // fallthrough
7430 case SEL_HELP: // fallthrough
7431 case SEL_AUTONEXT: // fallthrough
7432 case SEL_EDIT: // fallthrough
7435 bool refresh = FALSE;
7438 mkpath(path, pdents[cur].name, newpath);
7439 else if (sel == SEL_EDIT) /* Avoid trying to edit a non-existing file */
7448 setenv("NNN_INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
7449 setenv("NNN_PREFER_SELECTION", xitoa(cfg.prefersel), 1);
7450 setenv("NNN_LIST", listpath ? listroot : "", 1);
7452 if (!(getutil(utils[UTIL_BASH])
7453 && plugscript(utils[UTIL_NMV], F_CLI))
7458 printwait(messages[MSG_FAILED], &presel);
7465 show_help(path); // fallthrough
7467 if (sel == SEL_AUTONEXT)
7468 g_state.autonext ^= 1;
7474 if (!(g_state.picker || g_state.fifomode))
7475 spawn(editor, newpath, NULL, NULL, F_CLI);
7477 default: /* SEL_LOCK */
7482 /* In case of successful operation, reload contents */
7484 /* Continue in type-to-nav mode, if enabled */
7485 if ((cfg.filtermode || filterset()) && !refresh) {
7492 /* Repopulate as directory content may have changed */
7501 if (g_state.rangesel)
7502 g_state.rangesel = 0;
7504 /* Toggle selection status */
7505 pdents[cur].flags ^= FILE_SELECTED;
7507 if (pdents[cur].flags & FILE_SELECTED) {
7509 appendfpath(newpath, mkpath(path, pdents[cur].name, newpath));
7510 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
7513 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
7518 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7525 /* move cursor to the next entry if this is not the last entry */
7526 if (!g_state.stayonsel && (cur != ndents - 1))
7527 move_cursor((cur + 1) % ndents, 0);
7534 g_state.rangesel ^= 1;
7536 if (stat(path, &sb) == -1) {
7541 if (g_state.rangesel) { /* Range selection started */
7547 if (inode != sb.st_ino) {
7548 printwait(messages[MSG_DIR_CHANGED], &presel);
7552 if (cur < selstartid) {
7553 selendid = selstartid;
7558 /* Clear selection on repeat on same file */
7559 if (selstartid == selendid) {
7564 case SEL_SELALL: // fallthrough
7566 if (sel == SEL_SELALL || sel == SEL_SELINV) {
7571 if (g_state.rangesel)
7572 g_state.rangesel = 0;
7575 selendid = ndents - 1;
7578 if ((nselected > LARGESEL) || (nselected && (ndents > LARGESEL))) {
7579 printmsg("processing...");
7583 r = scanselforpath(path, TRUE); /* Get path length suffixed by '/' */
7584 ((sel == SEL_SELINV) && findselpos)
7585 ? invertselbuf(r) : addtoselbuf(r, selstartid, selendid);
7589 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7593 r = editselection();
7595 r = !r ? MSG_0_SELECTED : MSG_FAILED;
7596 printwait(messages[r], &presel);
7600 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7602 cfg.filtermode ? presel = FILTER : statusbar(path);
7605 case SEL_CP: // fallthrough
7606 case SEL_MV: // fallthrough
7607 case SEL_CPMVAS: // fallthrough
7610 if (sel == SEL_RM) {
7611 r = get_cur_or_sel();
7618 tmp = (listpath && xstrcmp(path, listpath) == 0)
7620 mkpath(tmp, pdents[cur].name, newpath);
7624 xrmfromsel(tmp, newpath);
7626 copynextname(lastname);
7628 if (cfg.filtermode || filterset())
7635 (nselected == 1 && (sel == SEL_CP || sel == SEL_MV))
7636 ? mkpath(path, xbasename(pselbuf), newpath)
7637 : (newpath[0] = '\0');
7641 if (!cpmvrm_selection(sel, path)) {
7651 /* Show notification on operation complete */
7653 plugscript(utils[UTIL_NTFY], F_NOWAIT | F_NOTRACE);
7656 if (newpath[0] && !access(newpath, F_OK))
7657 xstrsncpy(lastname, xbasename(newpath), NAME_MAX+1);
7663 case SEL_ARCHIVE: // fallthrough
7664 case SEL_OPENWITH: // fallthrough
7665 case SEL_NEW: // fallthrough
7671 if (!ndents && (sel == SEL_OPENWITH || sel == SEL_RENAME))
7674 if (sel != SEL_OPENWITH)
7679 r = get_cur_or_sel();
7693 tmp = pdents[cur].name;
7695 tmp = xreadline(tmp, messages[MSG_ARCHIVE_NAME]);
7699 if (g_state.picker || g_state.xprompt) {
7701 tmp = xreadline(NULL, messages[MSG_OPEN_WITH]);
7704 tmp = getreadline(messages[MSG_OPEN_WITH]);
7709 r = get_input(messages[MSG_NEW_OPTS]);
7715 tmp = g_ctx[0].c_name;
7719 if (r == 'f' || r == 'd')
7720 tmp = xreadline(tmp, messages[MSG_NEW_PATH]);
7721 else if (r == 's' || r == 'h')
7722 tmp = xreadline((nselected == 1 && cfg.prefersel) ? xbasename(pselbuf) : NULL,
7723 messages[nselected <= 1 ? MSG_NEW_PATH : MSG_LINK_PREFIX]);
7727 default: /* SEL_RENAME */
7728 tmp = xreadline(pdents[cur].name, "");
7732 if (!tmp || !*tmp || is_bad_len_or_dir(tmp))
7737 if (r == 'c' && strcmp(tmp, pdents[cur].name) == 0)
7738 continue; /* Cannot overwrite the hovered file */
7740 tmp = abspath(tmp, NULL, newpath);
7743 if (access(tmp, F_OK) == 0) {
7744 if (!xconfirm(get_input(messages[MSG_OVERWRITE]))) {
7750 (r == 's') ? archive_selection(get_archive_cmd(tmp), tmp)
7751 : spawn(get_archive_cmd(tmp), tmp, pdents[cur].name,
7752 NULL, F_CLI | F_CONFIRM);
7754 if (tmp && (access(tmp, F_OK) == 0)) { /* File created */
7756 clearselection(); /* Archive operation complete */
7758 /* Check if any entry is created in the current directory */
7759 tmp = get_cwd_entry(path, tmp, &len);
7761 xstrsncpy(lastname, tmp, len + 1);
7762 clearfilter(); /* Archive name may not match */
7763 } if (cfg.filtermode)
7770 handle_openwith(path, pdents[cur].name, newpath, tmp);
7772 cfg.filtermode ? presel = FILTER : statusbar(path);
7777 /* Skip renaming to same name */
7778 if (strcmp(tmp, pdents[cur].name) == 0) {
7779 tmp = xreadline(pdents[cur].name, messages[MSG_COPY_NAME]);
7780 if (!tmp || !tmp[0] || is_bad_len_or_dir(tmp)
7781 || !strcmp(tmp, pdents[cur].name)) {
7782 cfg.filtermode ? presel = FILTER : statusbar(path);
7789 default: /* SEL_NEW */
7793 if (!(r == 's' || r == 'h')) {
7794 tmp = abspath(tmp, NULL, newpath);
7801 /* Check if another file with same name exists */
7802 if (lstat(tmp, &sb) == 0) {
7803 if ((sel == SEL_RENAME) || ((r == 'f') && (S_ISREG(sb.st_mode)))) {
7804 /* Overwrite file with same name? */
7805 if (!xconfirm(get_input(messages[MSG_OVERWRITE])))
7808 /* Do nothing for SEL_NEW if a non-regular entry exists */
7809 printwait(messages[MSG_EXISTS], &presel);
7814 if (sel == SEL_RENAME) {
7815 /* Rename the file */
7817 spawn("cp -rp", pdents[cur].name, tmp, NULL, F_SILENT);
7818 else if (rename(pdents[cur].name, tmp) != 0) {
7823 /* Check if any entry is created in the current directory */
7824 tmp = get_cwd_entry(path, tmp, &len);
7826 xstrsncpy(lastname, tmp, len + 1);
7827 /* Directory must be reloeaded for rename case */
7828 } else { /* SEL_NEW */
7831 /* Check if it's a dir or file */
7832 if (r == 'f' || r == 'd') {
7833 ret = xmktree(tmp, r == 'f' ? FALSE : TRUE);
7834 } else if (r == 's' || r == 'h') {
7835 if (nselected > 1 && tmp[0] == '@' && tmp[1] == '\0')
7837 ret = xlink(tmp, path, (ndents ? pdents[cur].name : NULL), newpath, r);
7846 if (r == 'f' || r == 'd') {
7847 tmp = get_cwd_entry(path, tmp, &len);
7849 xstrsncpy(lastname, tmp, len + 1);
7851 continue; /* No change in directory */
7852 } else if (ndents) {
7864 /* Check if directory is accessible */
7865 if (!xdiraccess(plgpath)) {
7871 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
7872 printkeys(plug, g_buf + r - 1, maxplug);
7874 r = get_input(NULL);
7881 endselection(FALSE);
7882 tmp = get_kv_val(plug, NULL, r, maxplug, NNN_PLUG);
7884 printwait(messages[MSG_INVALID_KEY], &presel);
7888 if (tmp[0] == '-' && tmp[1]) {
7890 r = FALSE; /* Do not refresh dir after completion */
7894 if (!run_plugin(&path, tmp, (ndents ? pdents[cur].name : NULL),
7895 &lastname, &lastdir)) {
7896 printwait(messages[MSG_FAILED], &presel);
7901 return EXIT_SUCCESS;
7906 cfg.filtermode ? presel = FILTER : statusbar(path);
7909 } else { /* 'Return/Enter' enters the plugin directory */
7910 g_state.runplugin ^= 1;
7911 if (!g_state.runplugin) {
7913 * If toggled, and still in the plugin dir,
7914 * switch to original directory
7916 if (strcmp(path, plgpath) == 0) {
7917 xstrsncpy(path, lastdir, PATH_MAX);
7918 xstrsncpy(lastname, runfile, NAME_MAX + 1);
7924 /* Otherwise, initiate choosing plugin again */
7925 g_state.runplugin = 1;
7928 xstrsncpy(lastdir, path, PATH_MAX);
7929 xstrsncpy(path, plgpath, PATH_MAX);
7931 xstrsncpy(runfile, pdents[cur].name, NAME_MAX);
7932 g_state.runctx = cfg.curctx;
7937 if (g_state.runplugin == 1) /* Allow filtering in plugins directory */
7943 case SEL_SHELL: // fallthrough
7944 case SEL_LAUNCH: // fallthrough
7946 r = handle_cmd(sel, newpath);
7948 /* Continue in type-to-nav mode, if enabled */
7958 /* Repopulate as directory content may have changed */
7963 if (!unmount((ndents ? pdents[cur].name : NULL), newpath, &presel, path)) {
7964 if (presel == MSG_ZERO)
7969 /* Dir removed, go to next entry */
7970 copynextname(lastname);
7975 r = get_input(messages[MSG_SSN_OPTS]);
7978 tmp = xreadline(NULL, messages[MSG_SSN_NAME]);
7980 save_session(tmp, &presel);
7981 } else if (r == 'l' || r == 'r') {
7982 if (load_session(NULL, &path, &lastdir, &lastname, r == 'r')) {
7993 cfg.filtermode ? presel = FILTER : statusbar(path);
7996 if (!set_time_type(&presel))
8000 case SEL_QUITCTX: // fallthrough
8001 case SEL_QUITCD: // fallthrough
8004 if (sel == SEL_QUITCTX) {
8005 int ctx = cfg.curctx;
8007 for (r = (ctx - 1) & (CTX_MAX - 1);
8008 (r != ctx) && !g_ctx[r].c_cfg.ctxactive;
8009 r = ((r - 1) & (CTX_MAX - 1))) {
8013 g_ctx[ctx].c_cfg.ctxactive = 0;
8015 /* Switch to next active context */
8016 path = g_ctx[r].c_path;
8017 lastdir = g_ctx[r].c_last;
8018 lastname = g_ctx[r].c_name;
8020 cfg = g_ctx[r].c_cfg;
8021 /* Restore the global function pointers alongside the cfg. */
8022 entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
8023 namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
8029 } else if (!g_state.forcequit) {
8030 for (r = 0; r < CTX_MAX; ++r)
8031 if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
8032 r = get_input(messages[MSG_QUIT_ALL]);
8036 if (!(r == CTX_MAX || xconfirm(r)))
8037 break; // fallthrough
8041 tmp = getenv("NNN_TMPFILE");
8042 if ((sel == SEL_QUITCD) || tmp) {
8043 write_lastdir(path, tmp);
8044 /* ^G is a way to quit picker mode without picking anything */
8045 if ((sel == SEL_QUITCD) && g_state.picker)
8049 if (sel != SEL_QUITERR)
8050 return EXIT_SUCCESS;
8052 if (selbufpos && !g_state.picker) {
8053 /* Pick files to stdout and exit */
8057 return EXIT_SUCCESS;
8060 return EXIT_FAILURE;
8062 if (xlines != LINES || xcols != COLS)
8065 if (idletimeout && idle == idletimeout) {
8066 lock_terminal(); /* Locker */
8072 } /* switch (sel) */
8076 static char *make_tmp_tree(char **paths, ssize_t entries, const char *prefix)
8078 /* tmpdir holds the full path */
8079 /* tmp holds the path without the tmp dir prefix */
8083 ssize_t len = xstrlen(prefix);
8084 char *tmpdir = malloc(PATH_MAX);
8087 DPRINTF_S(strerror(errno));
8091 tmp = tmpdir + tmpfplen - 1;
8092 xstrsncpy(tmpdir, g_tmpfpath, tmpfplen);
8093 xstrsncpy(tmp, "/nnnXXXXXX", 11);
8095 /* Points right after the base tmp dir */
8098 /* handle the case where files are directly under / */
8099 if (!prefix[1] && (prefix[0] == '/'))
8102 if (!mkdtemp(tmpdir)) {
8105 DPRINTF_S(strerror(errno));
8111 for (ssize_t i = 0; i < entries; ++i) {
8115 err = stat(paths[i], &sb);
8116 if (err && errno == ENOENT)
8119 /* Don't copy the common prefix */
8120 xstrsncpy(tmp, paths[i] + len, xstrlen(paths[i]) - len + 1);
8122 /* Get the dir containing the path */
8123 slash = xmemrchr((uchar_t *)tmp, '/', xstrlen(paths[i]) - len);
8127 if (access(tmpdir, F_OK)) /* Create directory if it doesn't exist */
8128 xmktree(tmpdir, TRUE);
8133 if (symlink(paths[i], tmpdir)) {
8134 DPRINTF_S(paths[i]);
8135 DPRINTF_S(strerror(errno));
8139 /* Get the dir in which to start */
8144 static char *load_input(int fd, const char *path)
8146 size_t i, chunk_count = 1, chunk = 512UL * 1024 /* 512 KiB chunk size */, entries = 0;
8147 char *input = malloc(sizeof(char) * chunk), *tmpdir = NULL;
8148 char cwd[PATH_MAX], *next;
8149 size_t offsets[LIST_FILES_MAX];
8150 char **paths = NULL;
8151 ssize_t input_read, total_read = 0, off = 0;
8155 DPRINTF_S(strerror(errno));
8160 if (!getcwd(cwd, PATH_MAX)) {
8165 xstrsncpy(cwd, path, PATH_MAX);
8167 while (chunk_count < LIST_INPUT_MAX / chunk && !msgnum) {
8168 input_read = read(fd, input + total_read, chunk);
8169 if (input_read < 0) {
8173 DPRINTF_S(strerror(errno));
8177 if (input_read == 0)
8180 total_read += input_read;
8182 while (off < total_read) {
8183 next = memchr(input + off, '\0', total_read - off);
8188 if (next - input == off + 1) {
8193 if (entries == LIST_FILES_MAX) {
8194 msgnum = MSG_FILE_LIMIT;
8198 offsets[entries++] = off;
8202 /* We don't need to allocate another chunk */
8203 if (chunk_count > (total_read + chunk - 1) / chunk)
8206 /* We can never need more than one additional chunk */
8208 if (chunk_count > LIST_INPUT_MAX / chunk) {
8209 msgnum = MSG_SIZE_LIMIT;
8213 input = xrealloc(input, chunk_count * chunk);
8218 /* We close fd outside this function. Any extra data is left to the kernel to handle */
8220 if (off != total_read) {
8221 if (entries == LIST_FILES_MAX)
8222 msgnum = MSG_FILE_LIMIT;
8224 offsets[entries++] = off;
8228 DPRINTF_D(total_read);
8229 DPRINTF_D(chunk_count);
8232 msgnum = MSG_0_ENTRIES;
8236 input[total_read] = '\0';
8238 paths = malloc(entries * sizeof(char *));
8242 for (i = 0; i < entries; ++i)
8243 paths[i] = input + offsets[i];
8245 listroot = malloc(sizeof(char) * PATH_MAX);
8250 DPRINTF_S(paths[0]);
8252 for (i = 0; i < entries; ++i) {
8253 if (paths[i][0] == '\n' || selforparent(paths[i])) {
8258 paths[i] = abspath(paths[i], cwd, NULL);
8260 entries = i; // free from the previous entry
8264 DPRINTF_S(paths[i]);
8266 xstrsncpy(g_buf, paths[i], PATH_MAX);
8267 if (!common_prefix(xdirname(g_buf), listroot)) {
8268 entries = i + 1; // free from the current entry
8272 DPRINTF_S(listroot);
8275 DPRINTF_S(listroot);
8278 tmpdir = make_tmp_tree(paths, entries, listroot);
8281 for (i = 0; i < entries; ++i)
8284 if (msgnum) { /* Check if we are past init stage and show msg */
8286 printmsg(messages[msgnum]);
8287 xdelay(XDELAY_INTERVAL_MS << 2);
8289 msg(messages[msgnum]);
8290 usleep(XDELAY_INTERVAL_MS << 2);
8299 static void check_key_collision(void)
8302 bool bitmap[KEY_MAX] = {FALSE};
8304 for (ullong_t i = 0; i < ELEMENTS(bindings); ++i) {
8305 key = bindings[i].sym;
8308 dprintf(STDERR_FILENO, "key collision! [%s]\n", keyname(key));
8314 static void usage(void)
8316 dprintf(STDOUT_FILENO,
8317 "%s: nnn [OPTIONS] [PATH]\n\n"
8318 "The unorthodox terminal file manager.\n\n"
8319 "positional args:\n"
8320 " PATH start dir/file [default: .]\n\n"
8323 " -a auto NNN_FIFO\n"
8325 " -A no dir auto-enter during filter\n"
8326 " -b key open bookmark key (trumps -s/S)\n"
8327 " -B use bsdtar for archives\n"
8328 " -c cli-only NNN_OPENER (trumps -e)\n"
8329 " -C 8-color scheme\n"
8331 " -D dirs in context color\n"
8332 " -e text in $VISUAL/$EDITOR/vi\n"
8333 " -E internal edits in EDITOR\n"
8335 " -f use readline history file\n"
8338 " -F val fifo mode [0:preview 1:explore]\n"
8340 " -g regex filters\n"
8341 " -H show hidden files\n"
8342 " -i show current file info\n"
8343 " -J no auto-advance on selection\n"
8344 " -K detect key collision and exit\n"
8345 " -l val set scroll lines\n"
8346 " -n type-to-nav mode\n"
8348 " -N use native prompt\n"
8350 " -o open files only on Enter\n"
8351 " -p file selection file [-:stdout]\n"
8352 " -P key run plugin key\n"
8353 " -Q no quit confirmation\n"
8354 " -r use advcpmv patched cp, mv\n"
8355 " -R no rollover at edges\n"
8357 " -s name load session by name\n"
8358 " -S persistent session\n"
8360 " -t secs timeout to lock\n"
8361 " -T key sort order [a/d/e/r/s/t/v]\n"
8362 " -u use selection (no prompt)\n"
8364 " -U show user and group\n"
8366 " -V show version\n"
8368 " -x notis, selection sync, xterm title\n"
8371 "v%s\n%s\n", __func__, VERSION, GENERAL_INFO);
8374 static bool setup_config(void)
8377 char *xdgcfg = getenv("XDG_CONFIG_HOME");
8380 /* Set up configuration file paths */
8381 if (xdgcfg && xdgcfg[0]) {
8383 if (tilde_is_home(xdgcfg)) {
8384 r = xstrsncpy(g_buf, home, PATH_MAX);
8385 xstrsncpy(g_buf + r - 1, xdgcfg + 1, PATH_MAX);
8390 if (!xdiraccess(xdgcfg)) {
8395 len = xstrlen(xdgcfg) + xstrlen("/nnn/bookmarks") + 1;
8400 len = xstrlen(home) + xstrlen("/.config/nnn/bookmarks") + 1;
8402 cfgpath = (char *)malloc(len);
8403 plgpath = (char *)malloc(len);
8404 if (!cfgpath || !plgpath) {
8410 xstrsncpy(cfgpath, xdgcfg, len);
8411 r = len - xstrlen("/nnn/bookmarks");
8413 r = xstrsncpy(cfgpath, home, len);
8415 /* Create ~/.config */
8416 xstrsncpy(cfgpath + r - 1, "/.config", len - r);
8418 r += 8; /* length of "/.config" */
8421 /* Create ~/.config/nnn */
8422 xstrsncpy(cfgpath + r - 1, "/nnn", len - r);
8425 /* Create bookmarks, sessions, mounts and plugins directories */
8426 for (r = 0; r < ELEMENTS(toks); ++r) {
8427 mkpath(cfgpath, toks[r], plgpath);
8428 /* The dirs are created on first run, check if they already exist */
8429 if (access(plgpath, F_OK) && !xmktree(plgpath, TRUE)) {
8436 /* Set selection file path */
8437 if (!g_state.picker) {
8438 char *env_sel = xgetenv(env_cfg[NNN_SEL], NULL);
8440 selpath = env_sel ? xstrdup(env_sel)
8441 : (char *)malloc(len + 3); /* Length of "/.config/nnn/.selection" */
8449 r = xstrsncpy(selpath, cfgpath, len + 3);
8450 xstrsncpy(selpath + r - 1, "/.selection", 12);
8458 static bool set_tmp_path(void)
8461 char *path = xdiraccess(tmp) ? tmp : getenv("TMPDIR");
8468 tmpfplen = (uchar_t)xstrsncpy(g_tmpfpath, path, TMP_LEN_MAX);
8469 DPRINTF_S(g_tmpfpath);
8470 DPRINTF_U(tmpfplen);
8475 static void cleanup(void)
8478 if (cfg.x11 && !g_state.picker) {
8479 printf("\033[23;0t"); /* reset terminal window title */
8495 if (g_state.autofifo)
8498 if (g_state.pluginit)
8505 int main(int argc, char *argv[])
8508 char *session = NULL;
8509 int fd, opt, sort = 0, pkey = '\0'; /* Plugin key */
8512 char *middle_click_env = xgetenv(env_cfg[NNN_MCLICK], "\0");
8514 middle_click_key = (middle_click_env[0] == '^' && middle_click_env[1])
8515 ? CONTROL(middle_click_env[1])
8516 : (uchar_t)middle_click_env[0];
8519 const char * const env_opts = xgetenv(env_cfg[NNN_OPTS], NULL);
8520 int env_opts_id = env_opts ? (int)xstrlen(env_opts) : -1;
8522 bool rlhist = FALSE;
8525 while ((opt = (env_opts_id > 0
8526 ? env_opts[--env_opts_id]
8527 : getopt(argc, argv, "aAb:BcCdDeEfF:gHiJKl:nNop:P:QrRs:St:T:uUVxh"))) != -1) {
8531 g_state.autofifo = 1;
8538 if (env_opts_id < 0)
8542 g_state.usebsdtar = 1;
8548 g_state.oldcolor = 1;
8569 if (env_opts_id < 0) {
8571 if ((fd < 0) || (fd > 1))
8572 return EXIT_FAILURE;
8573 g_state.fifomode = fd;
8579 filterfn = &visible_re;
8588 g_state.stayonsel = 1;
8591 check_key_collision();
8592 return EXIT_SUCCESS;
8594 if (env_opts_id < 0)
8595 scroll_lines = atoi(optarg);
8602 g_state.xprompt = 1;
8609 if (env_opts_id >= 0)
8613 if (!(optarg[0] == '-' && optarg[1] == '\0')) {
8614 fd = open(optarg, O_WRONLY | O_CREAT, 0600);
8617 return EXIT_FAILURE;
8621 selpath = abspath(optarg, NULL, NULL);
8626 if (env_opts_id < 0 && !optarg[1])
8627 pkey = (uchar_t)optarg[0];
8630 g_state.forcequit = 1;
8634 memcpy(cp, PROGRESS_CP, sizeof PROGRESS_CP);
8635 memcpy(mv, PROGRESS_MV, sizeof PROGRESS_MV);
8643 if (env_opts_id < 0)
8647 g_state.prstssn = 1;
8648 if (!session) /* Support named persistent sessions */
8653 if (env_opts_id < 0)
8654 idletimeout = atoi(optarg);
8657 if (env_opts_id < 0)
8658 sort = (uchar_t)optarg[0];
8667 dprintf(STDOUT_FILENO, "%s\n", VERSION);
8668 return EXIT_SUCCESS;
8674 return EXIT_SUCCESS;
8677 return EXIT_FAILURE;
8679 if (env_opts_id == 0)
8688 /* Prefix for temporary files */
8689 if (!set_tmp_path())
8690 return EXIT_FAILURE;
8694 /* Check if we are in path list mode */
8695 if (!isatty(STDIN_FILENO)) {
8696 /* This is the same as listpath */
8697 initpath = load_input(STDIN_FILENO, NULL);
8699 return EXIT_FAILURE;
8701 /* We return to tty */
8702 if (!isatty(STDOUT_FILENO)) {
8703 fd = open(ctermid(NULL), O_RDONLY, 0400);
8704 dup2(fd, STDIN_FILENO);
8707 dup2(STDOUT_FILENO, STDIN_FILENO);
8713 home = getenv("HOME");
8716 return EXIT_FAILURE;
8719 homelen = (uchar_t)xstrlen(home);
8721 if (!setup_config())
8722 return EXIT_FAILURE;
8724 /* Get custom opener, if set */
8725 opener = xgetenv(env_cfg[NNN_OPENER], utils[UTIL_OPENER]);
8728 /* Parse bookmarks string */
8729 if (!parsekvpair(&bookmark, &bmstr, NNN_BMS, &maxbm)) {
8730 msg(env_cfg[NNN_BMS]);
8731 return EXIT_FAILURE;
8734 /* Parse plugins string */
8735 if (!parsekvpair(&plug, &pluginstr, NNN_PLUG, &maxplug)) {
8736 msg(env_cfg[NNN_PLUG]);
8737 return EXIT_FAILURE;
8740 /* Parse order string */
8741 if (!parsekvpair(&order, &orderstr, NNN_ORDER, &maxorder)) {
8742 msg(env_cfg[NNN_ORDER]);
8743 return EXIT_FAILURE;
8747 if (arg) { /* Open a bookmark directly */
8748 if (!arg[1]) /* Bookmarks keys are single char */
8749 initpath = get_kv_val(bookmark, NULL, *arg, maxbm, NNN_BMS);
8752 msg(messages[MSG_INVALID_KEY]);
8753 return EXIT_FAILURE;
8758 } else if (argc == optind) {
8759 /* Start in the current directory */
8760 char *startpath = getenv("PWD");
8762 initpath = (startpath && *startpath) ? xstrdup(startpath) : getcwd(NULL, 0);
8765 } else { /* Open a file */
8768 size_t len = xstrlen(arg);
8770 if (len > 7 && is_prefix(arg, "file://", 7)) {
8774 initpath = abspath(arg, NULL, NULL);
8775 DPRINTF_S(initpath);
8778 return EXIT_FAILURE;
8781 /* If the file is hidden, enable hidden option */
8782 if (*xbasename(initpath) == '.')
8786 * If nnn is set as the file manager, applications may try to open
8787 * files by invoking nnn. In that case pass the file path to the
8788 * desktop opener and exit.
8792 if (stat(initpath, &sb) == -1) {
8793 bool dir = (arg[len - 1] == '/');
8796 arg = xbasename(initpath);
8797 initpath = xdirname(initpath);
8799 pkey = CREATE_NEW_KEY; /* Override plugin key */
8800 g_state.initfile = 1;
8802 if (dir || (arg != initpath)) { /* We have a directory */
8803 if (!xdiraccess(initpath) && !xmktree(initpath, TRUE)) {
8804 xerror(); /* Fail if directory cannot be created */
8805 return EXIT_FAILURE;
8807 if (!dir) /* Restore the complete path */
8810 } else if (!S_ISDIR(sb.st_mode))
8811 g_state.initfile = 1;
8818 /* Set archive handling (enveditor used as tmp var) */
8819 enveditor = getenv(env_cfg[NNN_ARCHIVE]);
8821 if (setfilter(&archive_pcre, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8823 if (setfilter(&archive_re, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8825 msg(messages[MSG_INVALID_REG]);
8826 return EXIT_FAILURE;
8829 /* An all-CLI opener overrides option -e) */
8833 /* Get VISUAL/EDITOR */
8834 enveditor = xgetenv(envs[ENV_EDITOR], utils[UTIL_VI]);
8835 editor = xgetenv(envs[ENV_VISUAL], enveditor);
8836 DPRINTF_S(getenv(envs[ENV_VISUAL]));
8837 DPRINTF_S(getenv(envs[ENV_EDITOR]));
8841 pager = xgetenv(envs[ENV_PAGER], utils[UTIL_LESS]);
8845 shell = xgetenv(envs[ENV_SHELL], utils[UTIL_SH]);
8848 DPRINTF_S(getenv("PWD"));
8852 if (g_state.autofifo) {
8853 g_tmpfpath[tmpfplen - 1] = '\0';
8855 size_t r = mkpath(g_tmpfpath, "nnn-fifo.", g_buf);
8857 xstrsncpy(g_buf + r - 1, xitoa(getpid()), PATH_MAX - r);
8858 setenv("NNN_FIFO", g_buf, TRUE);
8861 fifopath = xgetenv("NNN_FIFO", NULL);
8863 if (mkfifo(fifopath, 0600) != 0 && !(errno == EEXIST && access(fifopath, W_OK) == 0)) {
8865 return EXIT_FAILURE;
8868 sigaction(SIGPIPE, &(struct sigaction){.sa_handler = SIG_IGN}, NULL);
8872 #ifdef LINUX_INOTIFY
8873 /* Initialize inotify */
8874 inotify_fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
8875 if (inotify_fd < 0) {
8877 return EXIT_FAILURE;
8879 #elif defined(BSD_KQUEUE)
8883 return EXIT_FAILURE;
8885 #elif defined(HAIKU_NM)
8886 haiku_hnd = haiku_init_nm();
8889 return EXIT_FAILURE;
8893 /* Configure trash preference */
8894 opt = xgetenv_val(env_cfg[NNN_TRASH]);
8895 if (opt && opt <= 2)
8896 g_state.trash = opt;
8898 /* Ignore/handle certain signals */
8899 struct sigaction act = {.sa_handler = sigint_handler};
8901 if (sigaction(SIGINT, &act, NULL) < 0) {
8903 return EXIT_FAILURE;
8906 act.sa_handler = clean_exit_sighandler;
8908 if (sigaction(SIGTERM, &act, NULL) < 0 || sigaction(SIGHUP, &act, NULL) < 0) {
8910 return EXIT_FAILURE;
8913 act.sa_handler = SIG_IGN;
8915 if (sigaction(SIGQUIT, &act, NULL) < 0) {
8917 return EXIT_FAILURE;
8922 setlocale(LC_ALL, "");
8924 tables = pcre_maketables();
8929 #if RL_READLINE_VERSION >= 0x0603
8930 /* readline would overwrite the WINCH signal hook */
8931 rl_change_environment = 0;
8933 /* Bind TAB to cycling */
8934 rl_variable_bind("completion-ignore-case", "on");
8936 rl_bind_key('\t', rl_menu_complete);
8938 rl_bind_key('\t', rl_complete);
8941 mkpath(cfgpath, ".history", g_buf);
8942 read_history(g_buf);
8947 if (cfg.x11 && !g_state.picker) {
8948 /* Save terminal window title */
8949 printf("\033[22;0t");
8951 gethostname(hostname, sizeof(hostname));
8952 hostname[sizeof(hostname) - 1] = '\0';
8957 if (!initcurses(&mask))
8959 if (!initcurses(NULL))
8961 return EXIT_FAILURE;
8964 set_sort_flags(sort);
8966 opt = browse(initpath, session, pkey);
8969 if (session && g_state.prstssn)
8970 save_session(session, NULL);
8974 mousemask(mask, NULL);
8980 if (rlhist && !g_state.xprompt) {
8981 mkpath(cfgpath, ".history", g_buf);
8982 write_history(g_buf);
8986 if (g_state.picker) {
8988 fd = selpath ? open(selpath, O_WRONLY | O_CREAT | O_TRUNC, 0600) : STDOUT_FILENO;
8989 if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
8998 /* Remove tmp dir in list mode */
9001 /* Free the regex */
9003 pcre_free(archive_pcre);
9005 regfree(&archive_re);
9008 /* Free the selection buffer */
9011 #ifdef LINUX_INOTIFY
9012 /* Shutdown inotify */
9013 if (inotify_wd >= 0)
9014 inotify_rm_watch(inotify_fd, inotify_wd);
9016 #elif defined(BSD_KQUEUE)
9020 #elif defined(HAIKU_NM)
9021 haiku_close_nm(haiku_hnd);
9025 if (!g_state.fifomode)