4 * Copyright (C) 2014-2016, Lazaros Koromilas <lostd@2f30.org>
5 * Copyright (C) 2014-2016, Dimitris Papastamos <sin@2f30.org>
6 * Copyright (C) 2016-2023, Arun Prakash Jana <engineerarun@gmail.com>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
12 * * Redistributions of source code must retain the above copyright notice, this
13 * list of conditions and the following disclaimer.
15 * * Redistributions in binary form must reproduce the above copyright notice,
16 * this list of conditions and the following disclaimer in the documentation
17 * and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #if defined(__linux__) || defined(MINGW) || defined(__MINGW32__) \
32 || defined(__MINGW64__) || defined(__CYGWIN__)
36 #if defined(__arm__) || defined(__i386__)
37 #define _FILE_OFFSET_BITS 64 /* Support large files on 32-bit */
39 #if defined(__linux__)
40 #include <sys/inotify.h>
43 #if !defined(__GLIBC__)
44 #include <sys/types.h>
47 #include <sys/resource.h>
49 #include <sys/statvfs.h>
50 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
51 #include <sys/types.h>
52 #include <sys/event.h>
55 #elif defined(__HAIKU__)
56 #include "../misc/haiku/haiku_interop.h"
59 #include <sys/sysmacros.h>
63 #ifdef __linux__ /* Fix failure due to mvaddnwstr() */
64 #ifndef NCURSES_WIDECHAR
65 #define NCURSES_WIDECHAR 1
67 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
68 || defined(__APPLE__) || defined(__sun)
69 #ifndef _XOPEN_SOURCE_EXTENDED
70 #define _XOPEN_SOURCE_EXTENDED
73 #ifndef __USE_XOPEN /* Fix wcswidth() failure, ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
88 #include <readline/history.h>
89 #include <readline/readline.h>
104 #include <stdalign.h>
105 #ifndef __USE_XOPEN_EXTENDED
106 #define __USE_XOPEN_EXTENDED 1
112 #ifdef MACOS_BELOW_1012
113 #include "../misc/macos-legacy/mach_gettime.h"
116 #if !defined(alloca) && defined(__GNUC__)
118 * GCC doesn't expand alloca() to __builtin_alloca() in standards mode
119 * (-std=...) and not all standard libraries do or supply it, e.g.
120 * NetBSD/arm64 so explicitly use the builtin.
122 #define alloca(size) __builtin_alloca(size)
128 #if defined(ICONS_IN_TERM) || defined(NERD) || defined(EMOJI)
129 #define ICONS_ENABLED
130 #include ICONS_INCLUDE
131 #include "icons-hash.c"
139 /* Macro definitions */
140 #define VERSION "4.8"
141 #define GENERAL_INFO "BSD 2-Clause\nhttps://github.com/jarun/nnn"
144 #define SESSIONS_VERSION 1
148 #define S_BLKSIZE 512 /* S_BLKSIZE is missing on Android NDK (Termux) */
152 * NAME_MAX and PATH_MAX may not exist, e.g. with dirent.c_name being a
153 * flexible array on Illumos. Use somewhat accommodating fallback values.
160 #define PATH_MAX 4096
163 #define _ABSSUB(N, M) (((N) <= (M)) ? ((M) - (N)) : ((N) - (M)))
164 #define ELEMENTS(x) (sizeof(x) / sizeof(*(x)))
166 #define MIN(x, y) ((x) < (y) ? (x) : (y))
168 #define MAX(x, y) ((x) > (y) ? (x) : (y))
169 #define ISODD(x) ((x) & 1)
170 #define ISBLANK(x) ((x) == ' ' || (x) == '\t')
171 #define TOUPPER(ch) (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
172 #define TOLOWER(ch) (((ch) >= 'A' && (ch) <= 'Z') ? ((ch) - 'A' + 'a') : (ch))
173 #define ISUPPER_(ch) ((ch) >= 'A' && (ch) <= 'Z')
174 #define ISLOWER_(ch) ((ch) >= 'a' && (ch) <= 'z')
175 #define CMD_LEN_MAX (PATH_MAX + ((NAME_MAX + 1) << 1))
176 #define ALIGN_UP(x, A) ((((x) + (A) - 1) / (A)) * (A))
177 #define READLINE_MAX 256
183 #define PROMPT ">>> "
185 #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
186 #define NAMEBUF_INCR 0x800 /* 64 dir entries at once, avg. 32 chars per file name = 64*32B = 2KB */
187 #define DESCRIPTOR_LEN 32
188 #define _ALIGNMENT 0x10 /* 16-byte alignment */
189 #define _ALIGNMENT_MASK 0xF
190 #define TMP_LEN_MAX 64
191 #define DOT_FILTER_LEN 7
192 #define ASCII_MAX 128
193 #define EXEC_ARGS_MAX 10
194 #define LIST_FILES_MAX (1 << 14) /* Support listing 16K files */
195 #define LIST_INPUT_MAX ((size_t)LIST_FILES_MAX * PATH_MAX)
197 #define COLOR_256 256
198 #define CREATE_NEW_KEY (-1)
201 #define DBLCLK_INTERVAL_NS (400000000)
202 #define XDELAY_INTERVAL_MS (350000) /* 350 ms delay */
211 /* BSDs or Solaris or SunOS */
212 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) || defined(sun) || defined(__sun)
219 /* Large selection threshold */
221 #define LARGESEL 1000
224 #define MIN_DISPLAY_COL (CTX_MAX * 2)
225 #define ARCHIVE_CMD_LEN 16
226 #define BLK_SHIFT_512 9
228 /* Detect hardlinks in du */
229 #define HASH_BITS (0xFFFFFF)
230 #define HASH_OCTETS (HASH_BITS >> 6) /* 2^6 = 64 */
233 #define DIR_OR_DIRLNK 0x01
234 #define HARD_LINK 0x02
235 #define SYM_ORPHAN 0x04
236 #define FILE_MISSING 0x08
237 #define FILE_SELECTED 0x10
238 #define FILE_SCANNED 0x20
239 #define FILE_YOUNG 0x40
241 /* Macros to define process spawn behaviour as flags */
242 #define F_NONE 0x00 /* no flag set */
243 #define F_MULTI 0x01 /* first arg can be combination of args; to be used with F_NORMAL */
244 #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
245 #define F_NOTRACE 0x04 /* suppress stdout and stderr (no traces) */
246 #define F_NORMAL 0x08 /* spawn child process in non-curses regular CLI mode */
247 #define F_CONFIRM 0x10 /* run command - show results before exit (must have F_NORMAL) */
248 #define F_CHKRTN 0x20 /* wait for user prompt if cmd returns failure status */
249 #define F_NOSTDIN 0x40 /* suppress stdin */
250 #define F_PAGE 0x80 /* page output in run-cmd-as-plugin mode */
251 #define F_TTY 0x100 /* Force stdout to go to tty if redirected to a non-tty */
252 #define F_CLI (F_NORMAL | F_MULTI)
253 #define F_SILENT (F_CLI | F_NOTRACE)
255 /* Version compare macros */
257 * states: S_N: normal, S_I: comparing integral part, S_F: comparing
258 * fractional parts, S_Z: idem but with leading Zeroes only
265 /* result_type: VCMP: return diff; VLEN: compare using len_diff/diff */
274 /* TYPE DEFINITIONS */
275 typedef unsigned int uint_t;
276 typedef unsigned char uchar_t;
277 typedef unsigned short ushort_t;
278 typedef unsigned long long ullong_t;
282 /* Directory entry */
283 typedef struct entry {
284 char *name; /* 8 bytes */
285 time_t sec; /* 8 bytes */
286 uint_t nsec; /* 4 bytes (enough to store nanosec) */
287 mode_t mode; /* 4 bytes */
288 off_t size; /* 8 bytes */
290 ullong_t blocks : 40; /* 5 bytes (enough for 512 TiB in 512B blocks allocated) */
291 ullong_t nlen : 16; /* 2 bytes (length of file name) */
292 ullong_t flags : 8; /* 1 byte (flags specific to the file) */
295 uid_t uid; /* 4 bytes */
296 gid_t gid; /* 4 bytes */
300 /* Selection marker */
306 /* Key-value pairs from env */
316 const regex_t *regex;
325 uint_t filtermode : 1; /* Set to enter filter mode */
326 uint_t timeorder : 1; /* Set to sort by time */
327 uint_t sizeorder : 1; /* Set to sort by file size */
328 uint_t apparentsz : 1; /* Set to sort by apparent size (disk usage) */
329 uint_t blkorder : 1; /* Set to sort by blocks used (disk usage) */
330 uint_t extnorder : 1; /* Order by extension */
331 uint_t showhidden : 1; /* Set to show hidden files */
332 uint_t reserved0 : 1;
333 uint_t showdetail : 1; /* Clear to show lesser file info */
334 uint_t ctxactive : 1; /* Context active or not */
335 uint_t reverse : 1; /* Reverse sort */
336 uint_t version : 1; /* Version sort */
337 uint_t reserved1 : 1;
338 /* The following settings are global */
339 uint_t curctx : 3; /* Current context number */
340 uint_t prefersel : 1; /* Prefer selection over current, if exists */
341 uint_t fileinfo : 1; /* Show file information on hover */
342 uint_t nonavopen : 1; /* Open file on right arrow or `l` */
343 uint_t autoenter : 1; /* auto-enter dir in type-to-nav mode */
344 uint_t reserved2 : 1;
345 uint_t useeditor : 1; /* Use VISUAL to open text files */
346 uint_t reserved3 : 3;
347 uint_t regex : 1; /* Use regex filters */
348 uint_t x11 : 1; /* Copy to system clipboard, show notis, xterm title */
349 uint_t timetype : 2; /* Time sort type (0: access, 1: change, 2: modification) */
350 uint_t cliopener : 1; /* All-CLI app opener */
351 uint_t waitedit : 1; /* For ops that can't be detached, used EDITOR */
352 uint_t rollover : 1; /* Roll over at edges */
355 /* Non-persistent program-internal states (alphabeical order) */
357 uint_t autofifo : 1; /* Auto-create NNN_FIFO */
358 uint_t autonext : 1; /* Auto-advance on file open */
359 uint_t dircolor : 1; /* Current status of dir color */
360 uint_t dirctx : 1; /* Show dirs in context color */
361 uint_t duinit : 1; /* Initialize disk usage */
362 uint_t fifomode : 1; /* FIFO notify mode: 0: preview, 1: explorer */
363 uint_t forcequit : 1; /* Do not prompt on quit */
364 uint_t initfile : 1; /* Positional arg is a file */
365 uint_t interrupt : 1; /* Program received an interrupt */
366 uint_t move : 1; /* Move operation */
367 uint_t oldcolor : 1; /* Use older colorscheme */
368 uint_t picked : 1; /* Plugin has picked files */
369 uint_t picker : 1; /* Write selection to user-specified file */
370 uint_t pluginit : 1; /* Plugin framework initialized */
371 uint_t prstssn : 1; /* Persistent session */
372 uint_t rangesel : 1; /* Range selection on */
373 uint_t runctx : 3; /* The context in which plugin is to be run */
374 uint_t runplugin : 1; /* Choose plugin mode */
375 uint_t selbm : 1; /* Select a bookmark from bookmarks directory */
376 uint_t selmode : 1; /* Set when selecting files */
377 uint_t stayonsel : 1; /* Disable auto-advance on selection */
378 uint_t trash : 2; /* Trash method 0: rm -rf, 1: trash-cli, 2: gio trash */
379 uint_t uidgid : 1; /* Show owner and group info */
380 uint_t usebsdtar : 1; /* Use bsdtar as default archive utility */
381 uint_t reserved : 5; /* Adjust when adding/removing a field */
384 /* Contexts or workspaces */
386 char c_path[PATH_MAX]; /* Current dir */
387 char c_last[PATH_MAX]; /* Last visited dir */
388 char c_name[NAME_MAX + 1]; /* Current file name */
389 char c_fltr[REGEX_MAX]; /* Current filter */
390 settings c_cfg; /* Current configuration */
391 uint_t color; /* Color code for directories */
397 size_t pathln[CTX_MAX];
398 size_t lastln[CTX_MAX];
399 size_t nameln[CTX_MAX];
400 size_t fltrln[CTX_MAX];
406 /* Configuration, contexts */
407 static settings cfg = {
410 .timetype = 2, /* T_MOD */
414 alignas(max_align_t) static context g_ctx[CTX_MAX];
416 static int ndents, cur, last, curscroll, last_curscroll, total_dents = ENTRY_INCR, scroll_lines = 1;
417 static int nselected;
419 static int fifofd = -1;
421 static time_t gtimesecs;
422 static uint_t idletimeout, selbufpos, selbuflen;
423 static ushort_t xlines, xcols;
424 static ushort_t idle;
425 static uchar_t maxbm, maxplug, maxorder;
426 static uchar_t cfgsort[CTX_MAX + 1];
428 static char *pluginstr;
429 static char *orderstr;
432 static char *enveditor;
436 static char *initpath;
437 static char *cfgpath;
438 static char *selpath;
439 static char *listpath;
440 static char *listroot;
441 static char *plgpath;
442 static char *pnamebuf, *pselbuf, *findselpos;
445 static char hostname[_POSIX_HOST_NAME_MAX + 1];
448 static char *fifopath;
450 static char *lastcmd;
451 static ullong_t *ihashbmp;
452 static struct entry *pdents;
453 static blkcnt_t dir_blocks;
457 static uchar_t tmpfplen, homelen;
458 static uchar_t blk_shift = BLK_SHIFT_512;
460 static int middle_click_key;
463 static pcre *archive_pcre;
465 static regex_t archive_re;
468 /* pthread related */
469 #define NUM_DU_THREADS (4) /* Can use sysconf(_SC_NPROCESSORS_ONLN) */
470 #define DU_TEST (((node->fts_info & FTS_F) && \
471 (sb->st_nlink <= 1 || test_set_bit((uint_t)sb->st_ino))) || node->fts_info & FTS_DP)
473 static int threadbmp = -1; /* Has 1 in the bit position for idle threads */
474 static volatile int active_threads;
475 static pthread_mutex_t running_mutex = PTHREAD_MUTEX_INITIALIZER;
476 static pthread_mutex_t hardlink_mutex = PTHREAD_MUTEX_INITIALIZER;
477 static ullong_t *core_files;
478 static blkcnt_t *core_blocks;
479 static ullong_t num_files;
488 static thread_data *core_data;
490 /* Retain old signal handlers */
491 static struct sigaction oldsighup;
492 static struct sigaction oldsigtstp;
493 static struct sigaction oldsigwinch;
495 /* For use in functions which are isolated and don't return the buffer */
496 alignas(max_align_t) static char g_buf[CMD_LEN_MAX];
498 /* For use as a scratch buffer in selection manipulation */
499 alignas(max_align_t) static char g_sel[PATH_MAX];
501 /* Buffer to store tmp file path to show selection, file stats and help */
502 alignas(max_align_t) static char g_tmpfpath[TMP_LEN_MAX];
504 /* Buffer to store plugins control pipe location */
505 alignas(max_align_t) static char g_pipepath[TMP_LEN_MAX];
507 /* Non-persistent runtime states */
508 static runstate g_state;
510 /* Options to identify file MIME */
511 #if defined(__APPLE__)
512 #define FILE_MIME_OPTS "-bIL"
513 #elif !defined(__sun) /* no MIME option for 'file' */
514 #define FILE_MIME_OPTS "-biL"
517 /* Macros for utilities */
518 #define UTIL_OPENER 0
520 #define UTIL_BSDTAR 2
523 #define UTIL_LOCKER 5
524 #define UTIL_LAUNCH 6
525 #define UTIL_SH_EXEC 7
528 #define UTIL_RCLONE 10
536 #define UTIL_TRASH_CLI 18
537 #define UTIL_GIO_TRASH 19
538 #define UTIL_RM_RF 20
539 #define UTIL_ARCHMNT 21
541 /* Utilities to open files, run actions */
542 static char * const utils[] = {
545 #elif defined __CYGWIN__
547 #elif defined __HAIKU__
558 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
560 #elif defined __HAIKU__
584 #define MSG_ZERO 0 /* Unused */
585 #define MSG_0_ENTRIES 1
586 #define STR_TMPFILE 2
587 #define MSG_0_SELECTED 3
590 #define MSG_SSN_NAME 6
591 #define MSG_CP_MV_AS 7
592 #define MSG_CUR_SEL_OPTS 8
593 #define MSG_FORCE_RM 9
594 #define MSG_SIZE_LIMIT 10
595 #define MSG_NEW_OPTS 11
596 #define MSG_CLI_MODE 12
597 #define MSG_OVERWRITE 13
598 #define MSG_SSN_OPTS 14
599 #define MSG_QUIT_ALL 15
600 #define MSG_HOSTNAME 16
601 #define MSG_ARCHIVE_NAME 17
602 #define MSG_OPEN_WITH 18
603 #define MSG_NEW_PATH 19
604 #define MSG_LINK_PREFIX 20
605 #define MSG_COPY_NAME 21
607 #define MSG_SEL_MISSING 23
608 #define MSG_ACCESS 24
609 #define MSG_EMPTY_FILE 25
610 #define MSG_UNSUPPORTED 26
611 #define MSG_NOT_SET 27
612 #define MSG_EXISTS 28
613 #define MSG_FEW_COLUMNS 29
614 #define MSG_REMOTE_OPTS 30
615 #define MSG_RCLONE_DELAY 31
616 #define MSG_APP_NAME 32
617 #define MSG_ARCHIVE_OPTS 33
619 #define MSG_INVALID_REG 35
623 #define MSG_RM_TMP 39
624 #define MSG_INVALID_KEY 40
625 #define MSG_NOCHANGE 41
626 #define MSG_DIR_CHANGED 42
627 #define MSG_BM_NAME 43
628 #define MSG_FILE_LIMIT 44
630 static const char * const messages[] = {
640 "%s %s? [Esc cancels]",
641 "size limit exceeded",
642 "['f'ile]/'d'ir/'s'ym/'h'ard?",
645 "'s'ave/'l'oad/'r'estore?",
646 "Quit all contexts?",
647 "remote name (- for hovered): ",
648 "archive [path/]name: ",
651 "link prefix [@ for none]: ",
652 "copy [path/]name: ",
653 "\n'Enter' to continue",
656 "empty! edit/open with",
664 "['l's]/'o'pen/e'x'tract/'m'nt?",
667 "'a'u/'d'u/'e'xt/'r'ev/'s'z/'t'm/'v'er/'c'lr/'^T'?",
668 "unmount failed! try lazy?",
669 "first file (\')/char?",
673 "dir changed, range sel off",
675 "file limit exceeded",
678 /* Supported configuration environment variables */
684 #define NNN_FCOLORS 5
689 #define NNN_ARCHIVE 10
691 #define NNN_HELP 12 /* strings end here */
692 #define NNN_TRASH 13 /* flags begin here */
694 static const char * const env_cfg[] = {
711 /* Required environment variables */
718 static const char * const envs[] = {
732 static char cp[] = "cp -iRp";
733 static char mv[] = "mv -i";
735 static char cp[] = "cp -iRp";
736 static char mv[] = "mv -i";
739 /* Archive commands */
740 static char * const archive_cmd[] = {"atool -a", "bsdtar -acvf", "zip -r", "tar -acvf"};
742 /* Tokens used for path creation */
748 static const char * const toks[] = {
752 "plugins", /* must be the last entry */
760 #define P_ARCHIVE_CMD 4
762 static const char * const patterns[] = {
763 SED" -i 's|^\\(\\(.*/\\)\\(.*\\)$\\)|#\\1\\n\\3|' %s",
764 SED" 's|^\\([^#/][^/]\\?.*\\)$|%s/\\1|;s|^#\\(/.*\\)$|\\1|' "
765 "%s | tr '\\n' '\\0' | xargs -0 -n2 sh -c '%s \"$0\" \"$@\" < /dev/tty'",
766 "\\.(bz|bz2|gz|tar|taz|tbz|tbz2|tgz|z|zip)$", /* Basic formats that don't need external tools */
767 SED" -i 's|^%s\\(.*\\)$|%s\\1|' %s",
768 "xargs -0 %s %s < '%s'",
772 #define C_BLK (CTX_MAX + 1) /* Block device: DarkSeaGreen1 */
773 #define C_CHR (C_BLK + 1) /* Character device: Yellow1 */
774 #define C_DIR (C_CHR + 1) /* Directory: DeepSkyBlue1 */
775 #define C_EXE (C_DIR + 1) /* Executable file: Green1 */
776 #define C_FIL (C_EXE + 1) /* Regular file: Normal */
777 #define C_HRD (C_FIL + 1) /* Hard link: Plum4 */
778 #define C_LNK (C_HRD + 1) /* Symbolic link: Cyan1 */
779 #define C_MIS (C_LNK + 1) /* Missing file OR file details: Grey62 */
780 #define C_ORP (C_MIS + 1) /* Orphaned symlink: DeepPink1 */
781 #define C_PIP (C_ORP + 1) /* Named pipe (FIFO): Orange1 */
782 #define C_SOC (C_PIP + 1) /* Socket: MediumOrchid1 */
783 #define C_UND (C_SOC + 1) /* Unknown OR 0B regular/exe file: Red1 */
785 static char gcolors[] = "c1e2272e006033f7c6d6abc4";
786 static uint_t fcolors[C_UND + 1] = {0};
790 #define NUM_EVENT_SLOTS 32 /* Make room for 32 events */
791 #define EVENT_SIZE (sizeof(struct inotify_event))
792 #define EVENT_BUF_LEN (EVENT_SIZE * NUM_EVENT_SLOTS)
793 static int inotify_fd, inotify_wd = -1;
794 static uint_t INOTIFY_MASK = /* IN_ATTRIB | */ IN_CREATE | IN_DELETE | IN_DELETE_SELF
795 | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
796 #elif defined(BSD_KQUEUE)
797 #define NUM_EVENT_SLOTS 1
798 #define NUM_EVENT_FDS 1
799 static int kq, event_fd = -1;
800 static struct kevent events_to_monitor[NUM_EVENT_FDS];
801 static uint_t KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK
802 | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
803 static struct timespec gtimeout;
804 #elif defined(HAIKU_NM)
805 static bool haiku_nm_active = FALSE;
806 static haiku_nm_h haiku_hnd;
809 /* Function macros */
810 #define tolastln() move(xlines - 1, 0)
811 #define tocursor() move(cur + 2 - curscroll, 0)
812 #define exitcurses() endwin()
813 #define printwarn(presel) printwait(strerror(errno), presel)
814 #define istopdir(path) ((path)[1] == '\0' && (path)[0] == '/')
815 #define copycurname() xstrsncpy(lastname, ndents ? pdents[cur].name : "\0", NAME_MAX + 1)
816 #define settimeout() timeout(1000)
817 #define cleartimeout() timeout(-1)
818 #define errexit() printerr(__LINE__)
819 #define setdirwatch() (cfg.filtermode ? (presel = FILTER) : (watch = TRUE))
820 #define filterset() (g_ctx[cfg.curctx].c_fltr[1])
821 /* We don't care about the return value from strcmp() */
822 #define xstrcmp(a, b) (*(a) != *(b) ? -1 : strcmp((a), (b)))
823 /* A faster version of xisdigit */
824 #define xisdigit(c) ((unsigned int) (c) - '0' <= 9)
825 #define xerror() perror(xitoa(__LINE__))
828 #define ENTLESS(i, j) (entrycmpfn(pdents + (i), pdents + (j)) < 0)
829 #define ENTSWAP(i, j) (swap_ent((i), (j)))
830 #define ENTSORT(pdents, ndents, entrycmpfn) QSORT((ndents), ENTLESS, ENTSWAP)
832 #define ENTSORT(pdents, ndents, entrycmpfn) qsort((pdents), (ndents), sizeof(*(pdents)), (entrycmpfn))
835 /* Forward declarations */
836 static void redraw(char *path);
837 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag);
838 static void move_cursor(int target, int ignore_scrolloff);
839 static char *load_input(int fd, const char *path);
840 static int set_sort_flags(int r);
841 static void statusbar(char *path);
842 static bool get_output(char *file, char *arg1, char *arg2, int fdout, bool page);
844 static void notify_fifo(bool force);
849 static void sigint_handler(int sig)
852 g_state.interrupt = 1;
855 static void clean_exit_sighandler(int sig)
859 /* This triggers cleanup() thanks to atexit() */
863 static char *xitoa(uint_t val)
865 static char dst[32] = {'\0'};
866 static const char digits[201] =
867 "0001020304050607080910111213141516171819"
868 "2021222324252627282930313233343536373839"
869 "4041424344454647484950515253545556575859"
870 "6061626364656667686970717273747576777879"
871 "8081828384858687888990919293949596979899";
872 uint_t next = 30, quo, i;
876 i = (val - (quo * 100)) * 2;
878 dst[next] = digits[i + 1];
879 dst[--next] = digits[i];
883 /* Handle last 1-2 digits */
885 dst[next] = '0' + val;
888 dst[next] = digits[i + 1];
889 dst[--next] = digits[i];
895 /* Return the integer value of a char representing HEX */
896 static uchar_t xchartohex(uchar_t c)
901 if (c >= 'a' && c <= 'f')
904 if (c >= 'A' && c <= 'F')
911 * Source: https://elixir.bootlin.com/linux/latest/source/arch/alpha/include/asm/bitops.h
913 static bool test_set_bit(uint_t nr)
917 pthread_mutex_lock(&hardlink_mutex);
918 ullong_t *m = ((ullong_t *)ihashbmp) + (nr >> 6);
920 if (*m & (1 << (nr & 63))) {
921 pthread_mutex_unlock(&hardlink_mutex);
925 *m |= 1 << (nr & 63);
926 pthread_mutex_unlock(&hardlink_mutex);
932 /* Increase the limit on open file descriptors, if possible */
933 static void max_openfds(void)
937 if (!getrlimit(RLIMIT_NOFILE, &rl))
938 if (rl.rlim_cur < rl.rlim_max) {
939 rl.rlim_cur = rl.rlim_max;
940 setrlimit(RLIMIT_NOFILE, &rl);
946 * Wrapper to realloc()
947 * Frees current memory if realloc() fails and returns NULL.
949 * The *alloc() family returns aligned address: https://man7.org/linux/man-pages/man3/malloc.3.html
951 static void *xrealloc(void *pcur, size_t len)
953 void *pmem = realloc(pcur, len);
962 * Just a safe strncpy(3)
963 * Always null ('\0') terminates if both src and dest are valid pointers.
964 * Returns the number of bytes copied including terminating null byte.
966 static size_t xstrsncpy(char *restrict dst, const char *restrict src, size_t n)
968 char *end = memccpy(dst, src, '\0', n);
971 dst[n - 1] = '\0'; // NOLINT
972 end = dst + n; /* If we return n here, binary size increases due to auto-inlining */
978 static inline size_t xstrlen(const char *restrict s)
980 #if !defined(__GLIBC__)
981 return strlen(s); // NOLINT
983 return (char *)rawmemchr(s, '\0') - s; // NOLINT
987 static char *xstrdup(const char *restrict s)
989 size_t len = xstrlen(s) + 1;
990 char *ptr = malloc(len);
991 return ptr ? memcpy(ptr, s, len) : NULL;
994 static bool is_suffix(const char *restrict str, const char *restrict suffix)
999 size_t lenstr = xstrlen(str);
1000 size_t lensuffix = xstrlen(suffix);
1002 if (lensuffix > lenstr)
1005 return (xstrcmp(str + (lenstr - lensuffix), suffix) == 0);
1008 static inline bool is_prefix(const char *restrict str, const char *restrict prefix, size_t len)
1010 return !strncmp(str, prefix, len);
1013 static inline bool is_bad_len_or_dir(const char *restrict path)
1015 size_t len = xstrlen(path);
1017 return ((len >= PATH_MAX) || (path[len - 1] == '/'));
1020 static char *get_cwd_entry(const char *restrict cwdpath, char *entrypath, size_t *tokenlen)
1022 size_t len = xstrlen(cwdpath);
1025 if (!is_prefix(entrypath, cwdpath, len))
1028 entrypath += len + 1; /* Add 1 for trailing / */
1029 end = strchr(entrypath, '/');
1031 *tokenlen = end - entrypath;
1033 *tokenlen = xstrlen(entrypath);
1034 DPRINTF_U(*tokenlen);
1040 * The poor man's implementation of memrchr(3).
1041 * We are only looking for '/' and '.' in this program.
1042 * And we are NOT expecting a '/' at the end.
1043 * Ideally 0 < n <= xstrlen(s).
1045 static void *xmemrchr(uchar_t *restrict s, uchar_t ch, size_t n)
1047 #if defined(__GLIBC__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
1048 return memrchr(s, ch, n);
1054 uchar_t *ptr = s + n;
1065 /* A very simplified implementation, changes path */
1066 static char *xdirname(char *path)
1068 char *base = xmemrchr((uchar_t *)path, '/', xstrlen(path));
1078 static char *xbasename(char *path)
1080 char *base = xmemrchr((uchar_t *)path, '/', xstrlen(path)); // NOLINT
1082 return base ? base + 1 : path;
1085 static inline char *xextension(const char *fname, size_t len)
1087 return xmemrchr((uchar_t *)fname, '.', len);
1092 * One-shot cache for getpwuid/getgrgid. Returns the cached name if the
1093 * provided uid is the same as the previous uid. Returns xitoa(guid) if
1094 * the guid is not found in the password database.
1096 static char *getpwname(uid_t uid)
1098 static uint_t uidcache = UINT_MAX;
1099 static char *namecache;
1101 if (uidcache != uid) {
1102 struct passwd *pw = getpwuid(uid);
1105 namecache = pw ? pw->pw_name : NULL;
1108 return namecache ? namecache : xitoa(uid);
1111 static char *getgrname(gid_t gid)
1113 static uint_t gidcache = UINT_MAX;
1114 static char *grpcache;
1116 if (gidcache != gid) {
1117 struct group *gr = getgrgid(gid);
1120 grpcache = gr ? gr->gr_name : NULL;
1123 return grpcache ? grpcache : xitoa(gid);
1127 static inline bool getutil(char *util)
1129 return spawn("which", util, NULL, NULL, F_NORMAL | F_NOTRACE) == 0;
1132 static inline bool tilde_is_home(const char *s)
1134 return s[0] == '~' && (s[1] == '\0' || s[1] == '/');
1137 static inline bool tilde_is_home_strict(const char *s)
1139 return s[0] == '~' && s[1] == '/';
1143 * Updates out with "dir/name or "/name"
1144 * Returns the number of bytes copied including the terminating NULL byte
1146 * Note: dir and out must be PATH_MAX in length to avoid macOS fault
1148 static size_t mkpath(const char *dir, const char *name, char *out)
1152 /* same rational for being strict as abspath() */
1153 if (tilde_is_home_strict(name)) { //NOLINT
1154 len = xstrsncpy(out, home, PATH_MAX);
1157 } else if (name[0] != '/') { // NOLINT
1158 /* Handle root case */
1159 len = istopdir(dir) ? 1 : xstrsncpy(out, dir, PATH_MAX);
1160 out[len - 1] = '/'; // NOLINT
1162 return (xstrsncpy(out + len, name, PATH_MAX - len) + len);
1165 /* Assumes both the paths passed are directories */
1166 static char *common_prefix(const char *path, char *prefix)
1168 const char *x = path, *y = prefix;
1171 if (!path || !*path || !prefix)
1175 xstrsncpy(prefix, path, PATH_MAX);
1179 while (*x && *y && (*x == *y))
1182 /* Strings are same */
1186 /* Path is shorter */
1187 if (!*x && *y == '/') {
1188 xstrsncpy(prefix, path, y - path);
1192 /* Prefix is shorter */
1193 if (!*y && *x == '/')
1196 /* Shorten prefix */
1197 prefix[y - prefix] = '\0';
1199 sep = xmemrchr((uchar_t *)prefix, '/', y - prefix);
1209 * The library function realpath() resolves symlinks.
1210 * If there's a symlink in file list we want to show the symlink not what it's points to.
1211 * Resolves ./../~ in filepath
1213 static char *abspath(const char *filepath, char *cwd, char *buf)
1215 const char *path = filepath;
1216 bool allocated = FALSE;
1221 /* when dealing with tilde, we need to be strict.
1222 * otherwise a file named "~" can end up expanding to
1223 * $HOME and causing disaster */
1224 if (tilde_is_home_strict(path)) {
1226 path += 2; /* advance 2 bytes past the "~/" */
1227 } else if ((path[0] != '/') && !cwd) {
1228 cwd = getcwd(NULL, 0);
1234 size_t dst_size = 0, src_size = xstrlen(path), cwd_size = cwd ? xstrlen(cwd) : 0;
1235 size_t len = src_size;
1239 * We need to add 2 chars at the end as relative paths may start with:
1241 * no separator (fd .): this needs an additional char for '/'
1243 char *resolved_path = buf ? buf : malloc(src_size + cwd_size + 2);
1245 if (!resolved_path) {
1251 /* Turn relative paths into absolute */
1252 if (path[0] != '/') {
1255 free(resolved_path);
1258 dst_size = xstrsncpy(resolved_path, cwd, cwd_size + 1) - 1;
1262 resolved_path[0] = '\0';
1265 dst = resolved_path + dst_size;
1266 for (const char *next = NULL; next != path + src_size;) {
1267 next = memchr(src, '/', len);
1269 next = path + src_size;
1271 if (next - src == 2 && src[0] == '.' && src[1] == '.') {
1272 if (dst - resolved_path) {
1273 dst = xmemrchr((uchar_t *)resolved_path, '/', dst - resolved_path);
1276 } else if (next - src == 1 && src[0] == '.') {
1278 } else if (next - src) {
1280 xstrsncpy(dst, src, next - src + 1);
1285 len = src_size - (src - path);
1288 if (*resolved_path == '\0') {
1289 resolved_path[0] = '/';
1290 resolved_path[1] = '\0';
1293 if (xstrlen(resolved_path) >= PATH_MAX) {
1295 free(resolved_path);
1301 return resolved_path;
1304 /* wraps the argument in single quotes so it can be safely fed to shell */
1305 static bool shell_escape(char *output, size_t outlen, const char *s)
1307 size_t n = xstrlen(s), w = 0;
1310 DPRINTF_S("s == output");
1314 output[w++] = '\''; /* begin single quote */
1315 for (size_t r = 0; r < n; ++r) {
1316 /* potentially too big: 4 for the single quote case, 2 from
1317 * outside the loop */
1318 if (w + 6 >= outlen)
1322 /* the only thing that has special meaning inside single
1323 * quotes are single quotes themselves. */
1325 output[w++] = '\''; /* end single quote */
1326 output[w++] = '\\'; /* put \' so it's treated as literal single quote */
1328 output[w++] = '\''; /* start single quoting again */
1335 output[w++] = '\''; /* end single quote */
1336 output[w++] = '\0'; /* nul terminator */
1340 static bool set_tilde_in_path(char *path)
1342 if (is_prefix(path, home, homelen)) {
1343 home[homelen] = path[homelen - 1];
1344 path[homelen - 1] = '~';
1351 static void reset_tilde_in_path(char *path)
1353 path[homelen - 1] = home[homelen];
1354 home[homelen] = '\0';
1358 static void xterm_cfg(char *path)
1360 if (cfg.x11 && !g_state.picker) {
1361 /* Signal CWD change to terminal */
1362 printf("\033]7;file://%s%s\033\\", hostname, path);
1364 /* Set terminal window title */
1365 bool r = set_tilde_in_path(path);
1367 printf("\033]2;%s\007", r ? &path[homelen - 1] : path);
1371 reset_tilde_in_path(path);
1376 static bool convert_tilde(const char *path, char *buf)
1378 if (tilde_is_home(path)) {
1379 ssize_t len = xstrlen(home);
1380 ssize_t loclen = xstrlen(path);
1382 xstrsncpy(buf, home, len + 1);
1383 xstrsncpy(buf + len, path + 1, loclen);
1389 static int create_tmp_file(void)
1391 xstrsncpy(g_tmpfpath + tmpfplen - 1, messages[STR_TMPFILE], TMP_LEN_MAX - tmpfplen);
1393 int fd = mkstemp(g_tmpfpath);
1396 DPRINTF_S(strerror(errno));
1402 static void msg(const char *message)
1404 dprintf(STDERR_FILENO, "%s\n", message);
1408 static void handle_key_resize(void)
1414 /* Clear the old prompt */
1415 static void clearoldprompt(void)
1418 move(xlines - 2, 0);
1423 handle_key_resize();
1427 /* Messages show up at the bottom */
1428 static inline void printmsg_nc(const char *msg)
1435 static void printmsg(const char *msg)
1437 attron(COLOR_PAIR(cfg.curctx + 1));
1439 attroff(COLOR_PAIR(cfg.curctx + 1));
1442 static void printwait(const char *msg, int *presel)
1448 xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
1452 /* Kill curses and display error before exiting */
1453 static void printerr(int linenum)
1456 perror(xitoa(linenum));
1457 if (!g_state.picker && selpath)
1463 static inline bool xconfirm(int c)
1465 return (c == 'y' || c == 'Y');
1468 static int get_input(const char *prompt)
1479 while (*ch == KEY_RESIZE) {
1493 static bool isselfileempty(void)
1497 return (stat(selpath, &sb) == -1) || (!sb.st_size);
1500 static int get_cur_or_sel(void)
1502 bool sel = (selbufpos || !isselfileempty());
1504 /* Check both local buffer and selection file for external selection */
1505 if (sel && ndents) {
1506 /* If selection is preferred and we have a local selection, return selection.
1507 * Always show the prompt in case of an external selection.
1509 if (cfg.prefersel && selbufpos)
1512 int choice = get_input(messages[MSG_CUR_SEL_OPTS]);
1514 return ((choice == 'c' || choice == 's') ? choice : 0);
1526 static void xdelay(useconds_t delay)
1532 static char confirm_force(bool selection)
1536 snprintf(str, 64, messages[MSG_FORCE_RM],
1537 g_state.trash ? utils[UTIL_GIO_TRASH] + 4 : utils[UTIL_RM_RF],
1538 (selection ? "selected" : "hovered"));
1540 int r = get_input(str);
1543 return '\0'; /* cancel */
1544 if (r == 'y' || r == 'Y')
1545 return 'f'; /* forceful for rm */
1546 return (g_state.trash ? '\0' : 'i'); /* interactive for rm */
1549 /* Writes buflen char(s) from buf to a file */
1550 static void writesel(const char *buf, const size_t buflen)
1555 int fd = open(selpath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
1558 if (write(fd, buf, buflen) != (ssize_t)buflen)
1565 static void appendfpath(const char *path, const size_t len)
1567 if ((selbufpos >= selbuflen) || ((len + 3) > (selbuflen - selbufpos))) {
1568 selbuflen += PATH_MAX;
1569 pselbuf = xrealloc(pselbuf, selbuflen);
1574 selbufpos += xstrsncpy(pselbuf + selbufpos, path, len);
1577 static void selbufrealloc(const size_t alloclen)
1579 if ((selbufpos + alloclen) > selbuflen) {
1580 selbuflen = ALIGN_UP(selbufpos + alloclen, PATH_MAX);
1581 pselbuf = xrealloc(pselbuf, selbuflen);
1587 /* Write selected file paths to fd, linefeed separated */
1588 static size_t seltofile(int fd, uint_t *pcount)
1590 uint_t lastpos, count = 0;
1591 char *pbuf = pselbuf;
1593 ssize_t len, prefixlen = 0, initlen = 0;
1601 lastpos = selbufpos - 1;
1604 prefixlen = (ssize_t)xstrlen(listroot);
1605 initlen = (ssize_t)xstrlen(listpath);
1608 while (pos <= lastpos) {
1610 len = (ssize_t)xstrlen(pbuf);
1612 if (!listpath || !is_prefix(pbuf, listpath, initlen)) {
1613 if (write(fd, pbuf, len) != len)
1616 if (write(fd, listroot, prefixlen) != prefixlen)
1618 if (write(fd, pbuf + initlen, len - initlen) != (len - initlen))
1623 if (pos <= lastpos) {
1624 if (write(fd, "\n", 1) != 1)
1638 /* List selection from selection file (another instance) */
1639 static bool listselfile(void)
1641 if (isselfileempty())
1644 snprintf(g_buf, CMD_LEN_MAX, "tr \'\\0\' \'\\n\' < %s", selpath);
1645 spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CONFIRM);
1650 /* Reset selection indicators */
1651 static void resetselind(void)
1653 for (int r = 0; r < ndents; ++r)
1654 if (pdents[r].flags & FILE_SELECTED)
1655 pdents[r].flags &= ~FILE_SELECTED;
1658 static void startselection(void)
1660 if (!g_state.selmode) {
1661 g_state.selmode = 1;
1672 static void clearselection(void)
1676 g_state.selmode = 0;
1680 static char *findinsel(char *startpos, int len)
1688 char *found = startpos;
1689 size_t buflen = selbufpos - (startpos - pselbuf);
1692 /* memmem(3): not specified in POSIX.1, but present on a number of other systems. */
1693 found = memmem(found, buflen - (found - startpos), g_sel, len);
1696 if (found == startpos || *(found - 1) == '\0')
1698 found += len; /* We found g_sel as a substring of a path, move forward */
1699 if (found >= startpos + buflen)
1704 static int markcmp(const void *va, const void *vb)
1706 const selmark *ma = (selmark*)va;
1707 const selmark *mb = (selmark*)vb;
1709 return ma->startpos - mb->startpos;
1712 /* scanselforpath() must be called before calling this */
1713 static inline void findmarkentry(size_t len, struct entry *dentp)
1715 if (!(dentp->flags & FILE_SCANNED)) {
1716 if (findinsel(findselpos, len + xstrsncpy(g_sel + len, dentp->name, dentp->nlen)))
1717 dentp->flags |= FILE_SELECTED;
1718 dentp->flags |= FILE_SCANNED;
1723 * scanselforpath() must be called before calling this
1724 * pathlen = length of path + 1 (+1 for trailing slash)
1726 static void invertselbuf(const int pathlen)
1728 size_t len, endpos, shrinklen = 0, alloclen = 0;
1729 char * const pbuf = g_sel + pathlen;
1731 int i, nmarked = 0, prev = 0;
1732 struct entry *dentp;
1734 selmark *marked = malloc(nselected * sizeof(selmark));
1741 /* First pass: inversion */
1742 for (i = 0; i < ndents; ++i) {
1745 if (dentp->flags & FILE_SCANNED) {
1746 if (dentp->flags & FILE_SELECTED) {
1747 dentp->flags ^= FILE_SELECTED; /* Clear selection status */
1750 dentp->flags |= FILE_SELECTED;
1751 alloclen += pathlen + dentp->nlen;
1754 dentp->flags |= FILE_SCANNED;
1759 len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1760 found = findinsel(findselpos, len);
1762 if (findselpos == found)
1765 if (nmarked && (found
1766 == (marked[nmarked - 1].startpos + marked[nmarked - 1].len)))
1767 marked[nmarked - 1].len += len;
1769 marked[nmarked].startpos = found;
1770 marked[nmarked].len = len;
1775 shrinklen += len; /* buffer size adjustment */
1777 dentp->flags |= FILE_SELECTED;
1778 alloclen += pathlen + dentp->nlen;
1785 * Files marked for deselection could be found in arbitrary order.
1786 * Sort by appearance in selection buffer.
1787 * With entries sorted we can merge adjacent ones allowing us to
1788 * move them in a single go.
1790 qsort(marked, nmarked, sizeof(selmark), &markcmp);
1792 /* Some files might be adjacent. Merge them into a single entry */
1793 for (i = 1; i < nmarked; ++i) {
1794 if (marked[i].startpos == marked[prev].startpos + marked[prev].len)
1795 marked[prev].len += marked[i].len;
1798 marked[prev].startpos = marked[i].startpos;
1799 marked[prev].len = marked[i].len;
1804 * Number of entries is increased by encountering a non-adjacent entry
1805 * After we finish the loop we should increment it once more.
1808 if (nmarked) /* Make sure there is something to deselect */
1811 /* Using merged entries remove unselected chunks from selection buffer */
1812 for (i = 0; i < nmarked; ++i) {
1814 * found: points to where the current block starts
1815 * variable is recycled from previous for readability
1816 * endpos: points to where the the next block starts
1817 * area between the end of current block (found + len)
1818 * and endpos is selected entries. This is what we are
1821 found = marked[i].startpos;
1822 endpos = (i + 1 == nmarked ? selbufpos : marked[i + 1].startpos - pselbuf);
1823 len = marked[i].len;
1825 /* Move back only selected entries. No selected memory is moved twice */
1826 memmove(found, found + len, endpos - (found + len - pselbuf));
1831 /* Buffer size adjustment */
1832 selbufpos -= shrinklen;
1834 selbufrealloc(alloclen);
1836 /* Second pass: append newly selected to buffer */
1837 for (i = 0; i < ndents; ++i) {
1838 if (pdents[i].flags & FILE_SELECTED) {
1839 len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1840 appendfpath(g_sel, len);
1845 nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1849 * scanselforpath() must be called before calling this
1850 * pathlen = length of path + 1 (+1 for trailing slash)
1852 static void addtoselbuf(const int pathlen, int startid, int endid)
1855 size_t len, alloclen = 0;
1856 struct entry *dentp;
1858 char * const pbuf = g_sel + pathlen;
1860 /* Remember current selection buffer position */
1861 for (i = startid; i <= endid; ++i) {
1865 len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1866 found = findinsel(findselpos, len);
1868 dentp->flags |= (FILE_SCANNED | FILE_SELECTED);
1869 if (found == findselpos) {
1871 if (findselpos == (pselbuf + selbufpos))
1875 alloclen += pathlen + dentp->nlen;
1877 alloclen += pathlen + dentp->nlen;
1880 selbufrealloc(alloclen);
1882 for (i = startid; i <= endid; ++i) {
1883 if (!(pdents[i].flags & FILE_SELECTED)) {
1884 len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1885 appendfpath(g_sel, len);
1887 pdents[i].flags |= (FILE_SCANNED | FILE_SELECTED);
1891 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
1894 /* Removes g_sel from selbuf */
1895 static void rmfromselbuf(size_t len)
1897 char *found = findinsel(findselpos, len);
1901 memmove(found, found + len, selbufpos - (found + len - pselbuf));
1904 nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1907 static int scanselforpath(const char *path, bool getsize)
1909 if (!path[1]) { /* path should always be at least two bytes (including NULL) */
1911 findselpos = pselbuf;
1912 return 1; /* Length of '/' is 1 */
1915 size_t off = xstrsncpy(g_sel, path, PATH_MAX);
1917 g_sel[off - 1] = '/';
1919 * We set findselpos only here. Directories can be listed in arbitrary order.
1920 * This is the best best we can do for remembering position.
1922 findselpos = findinsel(NULL, off);
1926 return (findselpos ? off : 0);
1929 /* Finish selection procedure before an operation */
1930 static void endselection(bool endselmode)
1934 char buf[sizeof(patterns[P_REPLACE]) + PATH_MAX + (TMP_LEN_MAX << 1)];
1936 if (endselmode && g_state.selmode)
1937 g_state.selmode = 0;
1939 /* The code below is only for listing mode */
1940 if (!listpath || !selbufpos)
1943 fd = create_tmp_file();
1945 DPRINTF_S("couldn't create tmp file");
1949 seltofile(fd, NULL);
1951 DPRINTF_S(strerror(errno));
1956 snprintf(buf, sizeof(buf), patterns[P_REPLACE], listpath, listroot, g_tmpfpath);
1957 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
1959 fd = open(g_tmpfpath, O_RDONLY);
1961 DPRINTF_S(strerror(errno));
1963 if (unlink(g_tmpfpath)) {
1964 DPRINTF_S(strerror(errno));
1970 count = read(fd, pselbuf, selbuflen);
1972 DPRINTF_S(strerror(errno));
1974 if (close(fd) || unlink(g_tmpfpath)) {
1975 DPRINTF_S(strerror(errno));
1980 if (close(fd) || unlink(g_tmpfpath)) {
1981 DPRINTF_S(strerror(errno));
1987 pselbuf[--count] = '\0';
1988 for (--count; count > 0; --count)
1989 if (pselbuf[count] == '\n' && pselbuf[count+1] == '/')
1990 pselbuf[count] = '\0';
1992 writesel(pselbuf, selbufpos - 1);
1995 /* Returns: 1 - success, 0 - none selected, -1 - other failure */
1996 static int editselection(void)
2004 if (!selbufpos) /* External selection is only editable at source */
2005 return listselfile();
2007 fd = create_tmp_file();
2009 DPRINTF_S("couldn't create tmp file");
2013 seltofile(fd, NULL);
2015 DPRINTF_S(strerror(errno));
2019 /* Save the last modification time */
2020 if (stat(g_tmpfpath, &sb)) {
2021 DPRINTF_S(strerror(errno));
2025 mtime = sb.st_mtime;
2027 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2029 fd = open(g_tmpfpath, O_RDONLY);
2031 DPRINTF_S(strerror(errno));
2038 if (mtime == sb.st_mtime) {
2039 DPRINTF_S("selection is not modified");
2044 if (sb.st_size > selbufpos) {
2045 DPRINTF_S("edited buffer larger than previous");
2050 count = read(fd, pselbuf, selbuflen);
2052 DPRINTF_S(strerror(errno));
2054 if (close(fd) || unlink(g_tmpfpath)) {
2055 DPRINTF_S(strerror(errno));
2061 if (close(fd) || unlink(g_tmpfpath)) {
2062 DPRINTF_S(strerror(errno));
2074 /* The last character should be '\n' */
2075 pselbuf[--count] = '\0';
2076 for (--count; count > 0; --count) {
2077 /* Replace every '\n' that separates two paths */
2078 if (pselbuf[count] == '\n' && pselbuf[count + 1] == '/') {
2080 pselbuf[count] = '\0';
2084 /* Add a line for the last file */
2087 if (lines > nselected) {
2088 DPRINTF_S("files added to selection");
2093 writesel(pselbuf, selbufpos - 1);
2103 static bool selsafe(void)
2105 /* Fail if selection file path not generated */
2107 printmsg(messages[MSG_SEL_MISSING]);
2111 /* Fail if selection file path isn't accessible */
2112 if (access(selpath, R_OK | W_OK) == -1) {
2113 errno == ENOENT ? printmsg(messages[MSG_0_SELECTED]) : printwarn(NULL);
2120 static void export_file_list(void)
2125 struct entry *pdent = pdents;
2126 int fd = create_tmp_file();
2129 DPRINTF_S(strerror(errno));
2133 for (int r = 0; r < ndents; ++pdent, ++r) {
2134 if (write(fd, pdent->name, pdent->nlen - 1) != (pdent->nlen - 1))
2137 if ((r != ndents - 1) && (write(fd, "\n", 1) != 1))
2142 DPRINTF_S(strerror(errno));
2145 spawn(editor, g_tmpfpath, NULL, NULL, F_CLI);
2147 if (xconfirm(get_input(messages[MSG_RM_TMP])))
2151 static bool init_fcolors(void)
2153 char *f_colors = getenv(env_cfg[NNN_FCOLORS]);
2155 if (!f_colors || !*f_colors)
2158 for (uchar_t id = C_BLK; *f_colors && id <= C_UND; ++id) {
2159 fcolors[id] = xchartohex(*f_colors) << 4;
2161 fcolors[id] += xchartohex(*f_colors);
2163 init_pair(id, fcolors[id], -1);
2172 /* Initialize curses mode */
2173 static bool initcurses(void *oldmask)
2179 if (g_state.picker) {
2180 if (!newterm(NULL, stderr, stdin)) {
2184 } else if (!initscr()) {
2186 DPRINTF_S(getenv("TERM"));
2193 //intrflush(stdscr, FALSE);
2194 keypad(stdscr, TRUE);
2196 #if NCURSES_MOUSE_VERSION <= 1
2197 mousemask(BUTTON1_PRESSED | BUTTON1_DOUBLE_CLICKED | BUTTON2_PRESSED | BUTTON3_PRESSED,
2198 (mmask_t *)oldmask);
2200 mousemask(BUTTON1_PRESSED | BUTTON2_PRESSED | BUTTON3_PRESSED | BUTTON4_PRESSED
2201 | BUTTON5_PRESSED, (mmask_t *)oldmask);
2205 curs_set(FALSE); /* Hide cursor */
2207 char *colors = getenv(env_cfg[NNN_COLORS]);
2209 if (colors || !getenv("NO_COLOR")) {
2214 use_default_colors();
2216 /* Initialize file colors */
2217 if (COLORS >= COLOR_256) {
2218 if (!(g_state.oldcolor || init_fcolors())) {
2220 msg(env_cfg[NNN_FCOLORS]);
2224 g_state.oldcolor = 1;
2227 DPRINTF_D(COLOR_PAIRS);
2229 if (colors && *colors == '#') {
2230 char *sep = strchr(colors, ';');
2232 if (!g_state.oldcolor && COLORS >= COLOR_256) {
2237 * If fallback colors are specified, set the separator
2238 * to NULL so we don't interpret separator and fallback
2239 * if fewer than CTX_MAX xterm 256 colors are specified.
2244 colors = sep; /* Detect if 8 colors fallback is appended */
2250 /* Get and set the context colors */
2251 for (uchar_t i = 0; i < CTX_MAX; ++i) {
2252 pcode = &g_ctx[i].color;
2254 if (colors && *colors) {
2256 *pcode = xchartohex(*colors) << 4;
2258 fcolors[i + 1] = *pcode += xchartohex(*colors);
2259 else { /* Each color code must be 2 hex symbols */
2261 msg(env_cfg[NNN_COLORS]);
2265 *pcode = (*colors < '0' || *colors > '7') ? 4 : *colors - '0';
2270 init_pair(i + 1, *pcode, -1);
2273 #ifdef ICONS_ENABLED
2274 if (!g_state.oldcolor) {
2275 for (uint_t i = 0; i < ELEMENTS(init_colors); ++i)
2276 init_pair(C_UND + 1 + init_colors[i], init_colors[i], -1);
2280 settimeout(); /* One second */
2285 /* No NULL check here as spawn() guards against it */
2286 static char *parseargs(char *cmd, char **argv, int *pindex)
2289 size_t len = xstrlen(cmd) + 1;
2290 char *line = (char *)malloc(len);
2293 DPRINTF_S("malloc()!");
2297 xstrsncpy(line, cmd, len);
2298 argv[count++] = line;
2301 while (*line) { // NOLINT
2302 if (ISBLANK(*line)) {
2305 if (!*line) // NOLINT
2308 argv[count++] = line;
2309 if (count == EXEC_ARGS_MAX) {
2318 if (count == -1 || count > (EXEC_ARGS_MAX - 4)) { /* 3 args and last NULL */
2321 DPRINTF_S("NULL or too many args");
2328 static void enable_signals(void)
2330 struct sigaction dfl_act = {.sa_handler = SIG_DFL};
2332 sigaction(SIGHUP, &dfl_act, NULL);
2333 sigaction(SIGINT, &dfl_act, NULL);
2334 sigaction(SIGQUIT, &dfl_act, NULL);
2335 sigaction(SIGTSTP, &dfl_act, NULL);
2336 sigaction(SIGWINCH, &dfl_act, NULL);
2339 static pid_t xfork(uchar_t flag)
2344 /* the parent ignores the interrupt, quit and hangup signals */
2345 sigaction(SIGHUP, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsighup);
2346 sigaction(SIGTSTP, &(struct sigaction){.sa_handler = SIG_DFL}, &oldsigtstp);
2347 sigaction(SIGWINCH, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsigwinch);
2348 } else if (p == 0) {
2349 /* We create a grandchild to detach */
2350 if (flag & F_NOWAIT) {
2354 _exit(EXIT_SUCCESS);
2362 _exit(EXIT_FAILURE);
2365 /* So they can be used to stop the child */
2369 /* This is the parent waiting for the child to create grandchild */
2370 if (flag & F_NOWAIT)
2371 waitpid(p, NULL, 0);
2378 static int join(pid_t p, uchar_t flag)
2380 int status = 0xFFFF;
2382 if (!(flag & F_NOWAIT)) {
2383 /* wait for the child to exit */
2385 } while (waitpid(p, &status, 0) == -1);
2387 if (WIFEXITED(status)) {
2388 status = WEXITSTATUS(status);
2393 /* restore parent's signal handling */
2394 sigaction(SIGHUP, &oldsighup, NULL);
2395 sigaction(SIGTSTP, &oldsigtstp, NULL);
2396 sigaction(SIGWINCH, &oldsigwinch, NULL);
2402 * Spawns a child process. Behaviour can be controlled using flag.
2403 * Limited to 3 arguments to a program, flag works on bit set.
2405 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag)
2408 int status = 0, retstatus = 0xFFFF;
2409 char *argv[EXEC_ARGS_MAX] = {0};
2412 if (!file || !*file)
2415 /* Swap args if the first arg is NULL and the other 2 aren't */
2416 if (!arg1 && arg2) {
2425 if (flag & F_MULTI) {
2426 cmd = parseargs(file, argv, &status);
2430 argv[status++] = file;
2432 argv[status] = arg1;
2433 argv[++status] = arg2;
2434 argv[++status] = arg3;
2436 if (flag & F_NORMAL)
2441 /* Suppress stdout and stderr */
2442 if (flag & F_NOTRACE) {
2443 int fd = open("/dev/null", O_WRONLY, 0200);
2445 if (flag & F_NOSTDIN)
2446 dup2(fd, STDIN_FILENO);
2447 dup2(fd, STDOUT_FILENO);
2448 dup2(fd, STDERR_FILENO);
2450 } else if (flag & F_TTY) {
2451 /* If stdout has been redirected to a non-tty, force output to tty */
2452 if (!isatty(STDOUT_FILENO)) {
2453 int fd = open(ctermid(NULL), O_WRONLY, 0200);
2454 dup2(fd, STDOUT_FILENO);
2459 execvp(*argv, argv);
2460 _exit(EXIT_SUCCESS);
2462 retstatus = join(pid, flag);
2465 if ((flag & F_CONFIRM) || ((flag & F_CHKRTN) && retstatus)) {
2466 status = write(STDOUT_FILENO, messages[MSG_ENTER], xstrlen(messages[MSG_ENTER]));
2468 while ((read(STDIN_FILENO, &status, 1) > 0) && (status != '\n'));
2471 if (flag & F_NORMAL)
2480 /* Get program name from env var, else return fallback program */
2481 static char *xgetenv(const char * const name, char *fallback)
2483 char *value = getenv(name);
2485 return value && value[0] ? value : fallback;
2488 /* Checks if an env variable is set to 1 */
2489 static inline uint_t xgetenv_val(const char *name)
2491 char *str = getenv(name);
2499 /* Check if a dir exists, IS a dir, and is readable */
2500 static bool xdiraccess(const char *path)
2502 DIR *dirp = opendir(path);
2513 static bool plugscript(const char *plugin, uchar_t flags)
2515 mkpath(plgpath, plugin, g_buf);
2516 if (!access(g_buf, X_OK)) {
2517 spawn(g_buf, NULL, NULL, NULL, flags);
2524 static void opstr(char *buf, char *op)
2526 snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c '%s \"$0\" \"$@\" . < /dev/tty' < %s", op, selpath);
2529 static bool rmmulstr(char *buf)
2531 char r = confirm_force(TRUE);
2536 snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c 'rm -%cr \"$0\" \"$@\" < /dev/tty' < %s",
2539 snprintf(buf, CMD_LEN_MAX, "xargs -0 %s < %s",
2540 utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH], selpath);
2545 /* Returns TRUE if file is removed, else FALSE */
2546 static bool xrm(char * const fpath)
2548 char r = confirm_force(FALSE);
2552 if (!g_state.trash) {
2553 char rm_opts[] = "-ir";
2556 spawn("rm", rm_opts, fpath, NULL, F_NORMAL | F_CHKRTN);
2558 spawn(utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH],
2559 fpath, NULL, NULL, F_NORMAL | F_MULTI);
2561 return (access(fpath, F_OK) == -1); /* File is removed */
2564 static void xrmfromsel(char *path, char *fpath)
2567 bool selected = TRUE;
2570 if ((pdents[cur].flags & DIR_OR_DIRLNK) && scanselforpath(fpath, FALSE))
2572 else if (pdents[cur].flags & FILE_SELECTED) {
2574 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
2580 if (selected && cfg.x11)
2581 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
2585 static uint_t lines_in_file(int fd, char *buf, size_t buflen)
2590 while ((len = read(fd, buf, buflen)) > 0)
2592 count += (buf[--len] == '\n');
2594 /* For all use cases 0 linecount is considered as error */
2595 return ((len < 0) ? 0 : count);
2598 static bool cpmv_rename(int choice, const char *path)
2601 uint_t count = 0, lines = 0;
2603 char *cmd = (choice == 'c' ? cp : mv);
2604 char buf[sizeof(patterns[P_CPMVRNM]) + (MAX(sizeof(cp), sizeof(mv))) + (PATH_MAX << 1)];
2606 fd = create_tmp_file();
2610 /* selsafe() returned TRUE for this to be called */
2612 snprintf(buf, sizeof(buf), "tr '\\0' '\\n' < %s > %s", selpath, g_tmpfpath);
2613 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2615 count = lines_in_file(fd, buf, sizeof(buf));
2619 seltofile(fd, &count);
2623 snprintf(buf, sizeof(buf), patterns[P_CPMVFMT], g_tmpfpath);
2624 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2626 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2628 fd = open(g_tmpfpath, O_RDONLY);
2632 lines = lines_in_file(fd, buf, sizeof(buf));
2635 if (!lines || (2 * count != lines)) {
2636 DPRINTF_S("num mismatch");
2640 snprintf(buf, sizeof(buf), patterns[P_CPMVRNM], path, g_tmpfpath, cmd);
2641 if (!spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CHKRTN))
2650 static bool cpmvrm_selection(enum action sel, char *path)
2654 if (isselfileempty()) {
2657 printmsg(messages[MSG_0_SELECTED]);
2672 r = get_input(messages[MSG_CP_MV_AS]);
2673 if (r != 'c' && r != 'm') {
2674 printmsg(messages[MSG_INVALID_KEY]);
2678 if (!cpmv_rename(r, path)) {
2679 printmsg(messages[MSG_FAILED]);
2683 default: /* SEL_RM */
2684 if (!rmmulstr(g_buf)) {
2685 printmsg(messages[MSG_CANCEL]);
2690 if (sel != SEL_CPMVAS && spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CHKRTN)) {
2691 printmsg(messages[MSG_FAILED]);
2695 /* Clear selection */
2702 static bool batch_rename(void)
2705 uint_t count = 0, lines = 0;
2706 bool dir = FALSE, ret = FALSE;
2707 char foriginal[TMP_LEN_MAX] = {0};
2708 static const char batchrenamecmd[] = "paste -d'\n' %s %s | "SED" 'N; /^\\(.*\\)\\n\\1$/!p;d' | "
2709 "tr '\n' '\\0' | xargs -0 -n2 sh -c 'mv -i \"$0\" \"$@\" <"
2711 char buf[sizeof(batchrenamecmd) + (PATH_MAX << 1)];
2712 int i = get_cur_or_sel();
2717 if (i == 'c') { /* Rename entries in current dir */
2722 fd1 = create_tmp_file();
2726 xstrsncpy(foriginal, g_tmpfpath, xstrlen(g_tmpfpath) + 1);
2728 fd2 = create_tmp_file();
2736 for (i = 0; i < ndents; ++i)
2737 appendfpath(pdents[i].name, NAME_MAX);
2739 seltofile(fd1, &count);
2740 seltofile(fd2, NULL);
2743 if (dir) /* Don't retain dir entries in selection */
2746 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2748 /* Reopen file descriptor to get updated contents */
2749 fd2 = open(g_tmpfpath, O_RDONLY);
2753 lines = lines_in_file(fd2, buf, sizeof(buf));
2756 if (!lines || (count != lines)) {
2757 DPRINTF_S("cannot delete files");
2761 snprintf(buf, sizeof(buf), batchrenamecmd, foriginal, g_tmpfpath);
2762 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2778 static char *get_archive_cmd(const char *archive)
2782 if (!g_state.usebsdtar && getutil(utils[UTIL_ATOOL]))
2784 else if (getutil(utils[UTIL_BSDTAR]))
2786 else if (is_suffix(archive, ".zip"))
2790 return archive_cmd[i];
2793 static void archive_selection(const char *cmd, const char *archive)
2795 char *buf = malloc((xstrlen(patterns[P_ARCHIVE_CMD]) + xstrlen(cmd) + xstrlen(archive)
2796 + xstrlen(selpath)) * sizeof(char));
2798 DPRINTF_S(strerror(errno));
2803 snprintf(buf, CMD_LEN_MAX, patterns[P_ARCHIVE_CMD], cmd, archive, selpath);
2804 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CONFIRM);
2808 static void write_lastdir(const char *curpath, const char *outfile)
2812 xstrsncpy(cfgpath + xstrlen(cfgpath), "/.lastd", 8);
2814 tilde = convert_tilde(outfile, g_buf);
2816 int fd = open(outfile
2817 ? (tilde ? g_buf : outfile)
2818 : cfgpath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
2820 if (fd != -1 && shell_escape(g_buf, sizeof(g_buf), curpath)) {
2821 dprintf(fd, "cd %s", g_buf);
2827 * We assume none of the strings are NULL.
2829 * Let's have the logic to sort numeric names in numeric order.
2830 * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
2832 * If the absolute numeric values are same, we fallback to alphasort.
2834 static int xstricmp(const char * const s1, const char * const s2)
2838 long long v1 = strtoll(s1, &p1, 10);
2839 long long v2 = strtoll(s2, &p2, 10);
2841 /* Check if at least 1 string is numeric */
2842 if (s1 != p1 || s2 != p2) {
2843 /* Handle both pure numeric */
2844 if (s1 != p1 && s2 != p2) {
2852 /* Only first string non-numeric */
2856 /* Only second string non-numeric */
2861 /* Handle 1. all non-numeric and 2. both same numeric value cases */
2863 return strcoll(s1, s2);
2865 return strcasecmp(s1, s2);
2870 * Version comparison
2872 * The code for version compare is a modified version of the GLIBC
2873 * and uClibc implementation of strverscmp(). The source is here:
2874 * https://elixir.bootlin.com/uclibc-ng/latest/source/libc/string/strverscmp.c
2878 * Compare S1 and S2 as strings holding indices/version numbers,
2879 * returning less than, equal to or greater than zero if S1 is less than,
2880 * equal to or greater than S2 (for more info, see the texinfo doc).
2884 static int xstrverscasecmp(const char * const s1, const char * const s2)
2886 const uchar_t *p1 = (const uchar_t *)s1;
2887 const uchar_t *p2 = (const uchar_t *)s2;
2892 * Symbol(s) 0 [1-9] others
2893 * Transition (10) 0 (01) d (00) x
2895 static const uint8_t next_state[] = {
2897 /* S_N */ S_N, S_I, S_Z,
2898 /* S_I */ S_N, S_I, S_I,
2899 /* S_F */ S_N, S_F, S_F,
2900 /* S_Z */ S_N, S_F, S_Z
2903 alignas(max_align_t) static const int8_t result_type[] = {
2904 /* state x/x x/d x/0 d/x d/d d/0 0/x 0/d 0/0 */
2906 /* S_N */ VCMP, VCMP, VCMP, VCMP, VLEN, VCMP, VCMP, VCMP, VCMP,
2907 /* S_I */ VCMP, -1, -1, 1, VLEN, VLEN, 1, VLEN, VLEN,
2908 /* S_F */ VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP,
2909 /* S_Z */ VCMP, 1, 1, -1, VCMP, VCMP, -1, VCMP, VCMP
2920 /* Hint: '0' is a digit too. */
2921 state = S_N + ((c1 == '0') + (xisdigit(c1) != 0));
2923 while ((diff = c1 - c2) == 0) {
2927 state = next_state[state];
2932 state += (c1 == '0') + (xisdigit(c1) != 0);
2935 state = result_type[state * 3 + (((c2 == '0') + (xisdigit(c2) != 0)))]; // NOLINT
2941 while (xisdigit(*p1++))
2942 if (!xisdigit(*p2++))
2944 return xisdigit(*p2) ? -1 : diff;
2950 static int (*namecmpfn)(const char * const s1, const char * const s2) = &xstricmp;
2952 static char * (*fnstrstr)(const char *haystack, const char *needle) = &strcasestr;
2954 static const unsigned char *tables;
2955 static int pcreflags = PCRE_NO_AUTO_CAPTURE | PCRE_EXTENDED | PCRE_CASELESS | PCRE_UTF8;
2957 static int regflags = REG_NOSUB | REG_EXTENDED | REG_ICASE;
2961 static int setfilter(pcre **pcrex, const char *filter)
2963 const char *errstr = NULL;
2966 *pcrex = pcre_compile(filter, pcreflags, &errstr, &erroffset, tables);
2968 return errstr ? -1 : 0;
2971 static int setfilter(regex_t *regex, const char *filter)
2973 return regcomp(regex, filter, regflags);
2977 static int visible_re(const fltrexp_t *fltrexp, const char *fname)
2980 return pcre_exec(fltrexp->pcrex, NULL, fname, xstrlen(fname), 0, 0, NULL, 0) == 0;
2982 return regexec(fltrexp->regex, fname, 0, NULL, 0) == 0;
2986 static int visible_str(const fltrexp_t *fltrexp, const char *fname)
2988 return fnstrstr(fname, fltrexp->str) != NULL;
2991 static int (*filterfn)(const fltrexp_t *fltr, const char *fname) = &visible_str;
2993 static void clearfilter(void)
2995 char * const fltr = g_ctx[cfg.curctx].c_fltr;
2998 fltr[REGEX_MAX - 1] = fltr[1];
3003 static int entrycmp(const void *va, const void *vb)
3005 const struct entry *pa = (pEntry)va;
3006 const struct entry *pb = (pEntry)vb;
3008 if ((pb->flags & DIR_OR_DIRLNK) != (pa->flags & DIR_OR_DIRLNK)) {
3009 if (pb->flags & DIR_OR_DIRLNK)
3014 /* Sort based on specified order */
3015 if (cfg.timeorder) {
3016 if (pb->sec > pa->sec)
3018 if (pb->sec < pa->sec)
3020 /* If sec matches, comare nsec */
3021 if (pb->nsec > pa->nsec)
3023 if (pb->nsec < pa->nsec)
3025 } else if (cfg.sizeorder) {
3026 if (pb->size > pa->size)
3028 if (pb->size < pa->size)
3030 } else if (cfg.blkorder) {
3031 if (pb->blocks > pa->blocks)
3033 if (pb->blocks < pa->blocks)
3035 } else if (cfg.extnorder && !(pb->flags & DIR_OR_DIRLNK)) {
3036 char *extna = xextension(pa->name, pa->nlen - 1);
3037 char *extnb = xextension(pb->name, pb->nlen - 1);
3039 if (extna || extnb) {
3046 int ret = strcasecmp(extna, extnb);
3053 return namecmpfn(pa->name, pb->name);
3056 static int reventrycmp(const void *va, const void *vb)
3058 if ((((pEntry)vb)->flags & DIR_OR_DIRLNK)
3059 != (((pEntry)va)->flags & DIR_OR_DIRLNK)) {
3060 if (((pEntry)vb)->flags & DIR_OR_DIRLNK)
3065 return -entrycmp(va, vb);
3068 static int (*entrycmpfn)(const void *va, const void *vb) = &entrycmp;
3070 /* In case of an error, resets *wch to Esc */
3071 static int handle_alt_key(wint_t *wch)
3075 int r = get_wch(wch);
3084 static inline int handle_event(void)
3086 if (nselected && isselfileempty())
3088 return CONTROL('L');
3092 * Returns SEL_* if key is bound and 0 otherwise.
3093 * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
3094 * The next keyboard input can be simulated by presel.
3096 static int nextsel(int presel)
3103 bool escaped = FALSE;
3105 if (c == 0 || c == MSGWAIT) {
3109 //DPRINTF_S(keyname(c));
3112 if (c == KEY_RESIZE)
3113 handle_key_resize();
3116 /* Handle Alt+key */
3128 } else if (escaped) {
3133 if (!g_state.fifomode)
3134 notify_fifo(TRUE); /* Send hovered path to NNN_FIFO */
3142 if (i == ERR && presel == MSGWAIT)
3143 c = (cfg.filtermode || filterset()) ? FILTER : CONTROL('L');
3144 else if (c == FILTER || c == CONTROL('L'))
3145 /* Clear previous filter when manually starting */
3153 * Do not check for directory changes in du mode.
3154 * A redraw forces du calculation.
3155 * Check for changes every odd second.
3157 #ifdef LINUX_INOTIFY
3158 if (!cfg.blkorder && inotify_wd >= 0 && (idle & 1)) {
3159 struct inotify_event *event;
3160 char inotify_buf[EVENT_BUF_LEN] = {0};
3162 i = read(inotify_fd, inotify_buf, EVENT_BUF_LEN);
3164 for (char *ptr = inotify_buf;
3165 ptr + ((struct inotify_event *)ptr)->len < inotify_buf + i;
3166 ptr += sizeof(struct inotify_event) + event->len) {
3167 event = (struct inotify_event *)ptr;
3168 DPRINTF_D(event->wd);
3169 DPRINTF_D(event->mask);
3173 if (event->mask & INOTIFY_MASK) {
3178 DPRINTF_S("inotify read done");
3181 #elif defined(BSD_KQUEUE)
3182 if (!cfg.blkorder && event_fd >= 0 && (idle & 1)) {
3183 struct kevent event_data[NUM_EVENT_SLOTS] = {0};
3185 if (kevent(kq, events_to_monitor, NUM_EVENT_SLOTS,
3186 event_data, NUM_EVENT_FDS, >imeout) > 0)
3189 #elif defined(HAIKU_NM)
3190 if (!cfg.blkorder && haiku_nm_active && (idle & 1) && haiku_is_update_needed(haiku_hnd))
3196 for (i = 0; i < (int)ELEMENTS(bindings); ++i)
3197 if (c == bindings[i].sym)
3198 return bindings[i].act;
3203 static int getorderstr(char *sort)
3211 sort[i++] = (cfg.timetype == T_MOD) ? 'M' : ((cfg.timetype == T_ACCESS) ? 'A' : 'C');
3212 else if (cfg.sizeorder)
3214 else if (cfg.extnorder)
3217 if (entrycmpfn == &reventrycmp)
3220 if (namecmpfn == &xstrverscasecmp)
3229 static void showfilterinfo(void)
3232 char info[REGEX_MAX] = "\0\0\0\0\0";
3234 i = getorderstr(info);
3236 if (cfg.fileinfo && ndents && get_output("file", "-b", pdents[cur].name, -1, FALSE))
3237 mvaddstr(xlines - 2, 2, g_buf);
3239 snprintf(info + i, REGEX_MAX - i - 1, " %s [/], %4s [:]",
3240 (cfg.regex ? "reg" : "str"),
3241 ((fnstrstr == &strcasestr) ? "ic" : "noic"));
3244 mvaddstr(xlines - 2, xcols - xstrlen(info), info);
3247 static void showfilter(char *str)
3249 attron(COLOR_PAIR(cfg.curctx + 1));
3252 // printmsg calls attroff()
3255 static inline void swap_ent(int id1, int id2)
3257 struct entry _dent, *pdent1 = &pdents[id1], *pdent2 = &pdents[id2];
3259 *(&_dent) = *pdent1;
3261 *pdent2 = *(&_dent);
3265 static int fill(const char *fltr, pcre *pcrex)
3267 static int fill(const char *fltr, regex_t *re)
3271 fltrexp_t fltrexp = { .pcrex = pcrex, .str = fltr };
3273 fltrexp_t fltrexp = { .regex = re, .str = fltr };
3276 for (int count = 0; count < ndents; ++count) {
3277 if (filterfn(&fltrexp, pdents[count].name) == 0) {
3278 if (count != --ndents) {
3279 swap_ent(count, ndents);
3290 static int matches(const char *fltr)
3296 if (cfg.regex && setfilter(&pcrex, fltr))
3299 ndents = fill(fltr, pcrex);
3307 if (cfg.regex && setfilter(&re, fltr))
3310 ndents = fill(fltr, &re);
3316 ENTSORT(pdents, ndents, entrycmpfn);
3322 * Return the position of the matching entry or 0 otherwise
3323 * Note there's no NULL check for fname
3325 static int dentfind(const char *fname, int n)
3327 for (int i = 0; i < n; ++i)
3328 if (xstrcmp(fname, pdents[i].name) == 0)
3334 static int filterentries(char *path, char *lastname)
3336 alignas(max_align_t) wchar_t wln[REGEX_MAX];
3337 char *ln = g_ctx[cfg.curctx].c_fltr;
3339 int r, total = ndents, len;
3340 char *pln = g_ctx[cfg.curctx].c_fltr + 1;
3342 DPRINTF_S(__func__);
3344 if (ndents && (ln[0] == FILTER || ln[0] == RFILTER) && *pln) {
3345 if (matches(pln) != -1) {
3346 move_cursor(dentfind(lastname, ndents), 0);
3350 if (!cfg.filtermode) {
3355 len = mbstowcs(wln, ln, REGEX_MAX);
3357 ln[0] = wln[0] = cfg.regex ? RFILTER : FILTER;
3358 ln[1] = wln[1] = '\0';
3366 while ((r = get_wch(ch)) != ERR) {
3368 //DPRINTF_S(keyname(*ch));
3372 case 0: // fallthrough
3379 case KEY_DC: // fallthrough
3380 case KEY_BACKSPACE: // fallthrough
3381 case '\b': // fallthrough
3382 case DEL: /* handle DEL */
3385 wcstombs(ln, wln, REGEX_MAX);
3393 if (*ch == CONTROL('L')) {
3395 ln[REGEX_MAX - 1] = ln[1];
3396 ln[1] = wln[1] = '\0';
3399 } else if (ln[REGEX_MAX - 1]) { /* Show the previous filter */
3400 ln[1] = ln[REGEX_MAX - 1];
3401 ln[REGEX_MAX - 1] = '\0';
3402 len = mbstowcs(wln, ln, REGEX_MAX);
3407 /* Go to the top, we don't know if the hovered file will match the filter */
3410 if (matches(pln) != -1)
3420 if (handle_alt_key(ch) != ERR) {
3421 if (*ch == ESC) /* Handle Alt+Esc */
3422 *ch = 'q'; /* Quit context */
3425 *ch = ';'; /* Run plugin */
3431 if (r != OK) /* Handle Fn keys in main loop */
3434 /* Handle all control chars in main loop */
3435 if (*ch < ASCII_MAX && keyname(*ch)[0] == '^' && *ch != '^')
3439 if (*ch == '?') /* Help and config key, '?' is an invalid regex */
3442 if (cfg.filtermode) {
3444 case '\'': // fallthrough /* Go to first non-dir file */
3445 case '+': // fallthrough /* Toggle file selection */
3446 case ',': // fallthrough /* Mark CWD */
3447 case '-': // fallthrough /* Visit last visited dir */
3448 case '.': // fallthrough /* Show hidden files */
3449 case ';': // fallthrough /* Run plugin key */
3450 case '=': // fallthrough /* Launch app */
3451 case '>': // fallthrough /* Export file list */
3452 case '@': // fallthrough /* Visit start dir */
3453 case ']': // fallthorugh /* Prompt key */
3454 case '`': // fallthrough /* Visit / */
3455 case '~': /* Go HOME */
3460 /* Toggle case-sensitivity */
3462 fnstrstr = (fnstrstr == &strcasestr) ? &strstr : &strcasestr;
3464 pcreflags ^= PCRE_CASELESS;
3466 regflags ^= REG_ICASE;
3472 /* Toggle string or regex filter */
3473 if (*ch == FILTER) {
3474 ln[0] = (ln[0] == FILTER) ? RFILTER : FILTER;
3475 wln[0] = (uchar_t)ln[0];
3477 filterfn = cfg.regex ? &visible_re : &visible_str;
3482 /* Reset cur in case it's a repeat search */
3484 } else if (len == REGEX_MAX - 1)
3487 wln[len] = (wchar_t)*ch;
3489 wcstombs(ln, wln, REGEX_MAX);
3491 /* Forward-filtering optimization:
3492 * - new matches can only be a subset of current matches.
3494 /* ndents = total; */
3498 !r ? unget_wch(KEY_BACKSPACE) : showfilter(ln);
3500 if (matches(pln) == -1) {
3506 /* If the only match is a dir, auto-enter and cd into it */
3507 if ((ndents == 1) && cfg.autoenter && (pdents[0].flags & DIR_OR_DIRLNK)) {
3514 * redraw() should be above the auto-enter optimization, for
3515 * the case where there's an issue with dir auto-enter, say,
3516 * due to a permission problem. The transition is _jumpy_ in
3517 * case of such an error. However, we optimize for successful
3518 * cases where the dir has permissions. This skips a redraw().
3525 /* Save last working filter in-filter */
3527 ln[REGEX_MAX - 1] = ln[1];
3535 /* Return keys for navigation etc. */
3539 /* Show a prompt with input string and return the changes */
3540 static char *xreadline(const char *prefill, const char *prompt)
3544 const int WCHAR_T_WIDTH = sizeof(wchar_t);
3546 wchar_t * const buf = malloc(sizeof(wchar_t) * READLINE_MAX);
3556 len = pos = mbstowcs(buf, prefill, READLINE_MAX);
3560 if (len == (size_t)-1) {
3565 x = getcurx(stdscr);
3570 attron(COLOR_PAIR(cfg.curctx + 1));
3571 if (pos > (size_t)(xcols - x)) {
3572 mvaddnwstr(xlines - 1, x, buf + (pos - (xcols - x) + 1), xcols - x);
3573 move(xlines - 1, xcols - 1);
3575 mvaddnwstr(xlines - 1, x, buf, len + 1);
3576 move(xlines - 1, x + wcswidth(buf, pos));
3578 attroff(COLOR_PAIR(cfg.curctx + 1));
3586 case KEY_ENTER: // fallthrough
3587 case '\n': // fallthrough
3593 else if (!(pos || len)) { /* Exit on ^D at empty prompt */
3599 case DEL: // fallthrough
3600 case '\b': /* rhel25 sends '\b' for backspace */
3602 memmove(buf + pos - 1, buf + pos,
3603 (len - pos) * WCHAR_T_WIDTH);
3608 if (!(len || pos) && ndents)
3609 len = pos = mbstowcs(buf, pdents[cur].name, READLINE_MAX);
3624 memmove(buf + pos - 1, buf + pos,
3625 (len - pos) * WCHAR_T_WIDTH);
3627 } while (buf[pos - 1] != ' ' && buf[pos - 1] != '/'); // NOLINT
3645 memmove(buf, buf + pos, (len - pos) * WCHAR_T_WIDTH);
3649 case ESC: /* Exit prompt on Esc, but just filter out Alt+key */
3650 if (handle_alt_key(ch) != ERR)
3657 /* Filter out all other control chars */
3658 if (*ch < ASCII_MAX && keyname(*ch)[0] == '^')
3661 if (pos < READLINE_MAX - 1) {
3662 memmove(buf + pos + 1, buf + pos,
3663 (len - pos) * WCHAR_T_WIDTH);
3687 memmove(buf + pos - 1, buf + pos,
3688 (len - pos) * WCHAR_T_WIDTH);
3694 memmove(buf + pos, buf + pos + 1,
3695 (len - pos - 1) * WCHAR_T_WIDTH);
3705 case KEY_UP: // fallthrough
3707 if (prompt && lastcmd && (xstrcmp(prompt, PROMPT) == 0)) {
3709 len = pos = mbstowcs(buf, lastcmd, READLINE_MAX); // fallthrough
3724 pos = wcstombs(g_buf, buf, READLINE_MAX - 1);
3725 if (pos >= READLINE_MAX - 1)
3726 g_buf[READLINE_MAX - 1] = '\0';
3734 * Caller should check the value of presel to confirm if it needs to wait to show warning
3736 static char *getreadline(const char *prompt)
3740 char *input = readline(prompt);
3744 if (input && input[0]) {
3746 xstrsncpy(g_buf, input, CMD_LEN_MAX);
3757 * Create symbolic/hard link(s) to file(s) in selection list
3758 * Returns the number of links created, -1 on error
3760 static int xlink(char *prefix, char *path, char *curfname, char *buf, int type)
3762 int count = 0, choice;
3763 char *psel = pselbuf, *fname;
3764 size_t pos = 0, len, r;
3765 int (*link_fn)(const char *, const char *) = NULL;
3766 char lnpath[PATH_MAX];
3768 choice = get_cur_or_sel();
3772 if (type == 's') /* symbolic link */
3774 else /* hard link */
3777 if (choice == 'c' || (nselected == 1)) {
3778 prefix = abspath(prefix, path, lnpath); /* Generate link path */
3783 mkpath(path, curfname, buf); /* Generate target file path */
3785 if (!link_fn((choice == 'c') ? buf : pselbuf, lnpath)) {
3788 return 1; /* One link created */
3793 r = xstrsncpy(buf, prefix, NAME_MAX + 1); /* Copy prefix */
3795 while (pos < selbufpos) {
3796 len = xstrlen(psel);
3797 fname = xbasename(psel);
3799 xstrsncpy(buf + r - 1, fname, NAME_MAX - r); /* Suffix target file name */
3800 mkpath(path, buf, lnpath); /* Generate link path */
3802 if (!link_fn(psel, lnpath))
3809 if (count == nselected) /* Clear selection if all links are generated */
3814 static bool parsekvpair(kv **arr, char **envcpy, const uchar_t id, uchar_t *items)
3817 const uchar_t INCR = 8;
3820 char *ptr = getenv(env_cfg[id]);
3825 *envcpy = xstrdup(ptr);
3833 while (*ptr && i < 100) {
3835 if (!(i & (INCR - 1))) {
3836 kvarr = xrealloc(kvarr, sizeof(kv) * (i + INCR));
3842 memset(kvarr + i, 0, sizeof(kv) * INCR);
3844 kvarr[i].key = (uchar_t)*ptr;
3845 if (*++ptr != ':' || *++ptr == '\0' || *ptr == ';')
3847 kvarr[i].off = ptr - *envcpy;
3866 * Get the value corresponding to a key
3868 * NULL is returned in case of no match, path resolution failure etc.
3869 * buf would be modified, so check return value before access
3871 static char *get_kv_val(kv *kvarr, char *buf, int key, uchar_t max, uchar_t id)
3878 for (int r = 0; r < max && kvarr[r].key; ++r) {
3879 if (kvarr[r].key == key) {
3880 /* Do not allocate new memory for plugin */
3882 return pluginstr + kvarr[r].off;
3884 val = bmstr + kvarr[r].off;
3885 bool tilde = convert_tilde(val, g_buf);
3886 return abspath((tilde ? g_buf : val), NULL, buf);
3890 DPRINTF_S("Invalid key");
3894 static int get_kv_key(kv *kvarr, char *val, uchar_t max, uchar_t id)
3899 if (id != NNN_ORDER) /* For now this function supports only order string */
3902 for (int r = 0; r < max && kvarr[r].key; ++r) {
3903 if (xstrcmp((orderstr + kvarr[r].off), val) == 0)
3904 return kvarr[r].key;
3910 static void resetdircolor(int flags)
3912 /* Directories are always shown on top, clear the color when moving to first file */
3913 if (g_state.dircolor && !(flags & DIR_OR_DIRLNK)) {
3914 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
3915 g_state.dircolor = 0;
3920 * Replace escape characters in a string with '?'
3921 * Adjust string length to maxcols if > 0;
3922 * Max supported str length: NAME_MAX;
3925 static char *unescape(const char *str, uint_t maxcols)
3927 char * const wbuf = g_buf;
3930 xstrsncpy(wbuf, str, maxcols);
3932 static wchar_t *unescape(const char *str, uint_t maxcols)
3934 wchar_t * const wbuf = (wchar_t *)g_buf;
3935 wchar_t *buf = wbuf;
3936 size_t len = mbstowcs(wbuf, str, maxcols); /* Convert multi-byte to wide char */
3938 len = wcswidth(wbuf, len);
3940 if (len >= maxcols) {
3941 size_t lencount = maxcols;
3943 while (len > maxcols) /* Reduce wide chars one by one till it fits */
3944 len = wcswidth(wbuf, --lencount);
3946 wbuf[lencount] = L'\0';
3951 if (*buf <= '\x1f' || *buf == '\x7f')
3960 static off_t get_size(off_t size, off_t *pval, int comp)
3963 off_t quo = rem / 10;
3965 if ((rem - (quo * 10)) >= 5) {
3978 static char *coolsize(off_t size)
3980 const char * const U = "BKMGTPEZY";
3981 static char size_buf[12]; /* Buffer to hold human readable size */
3986 while (size >= 1024) {
3987 rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
3993 rem = (rem * 1000) >> 10;
3995 size = get_size(size, &rem, 10);
3996 } else if (i == 2) {
3997 rem = (rem * 1000) >> 10;
3998 size = get_size(size, &rem, 100);
4000 rem = (rem * 10000) >> 10;
4001 size = get_size(size, &rem, 1000);
4004 if (i > 0 && i < 6 && rem) {
4005 ret = xstrsncpy(size_buf, xitoa(size), 12);
4006 size_buf[ret - 1] = '.';
4008 char *frac = xitoa(rem);
4009 size_t toprint = i > 3 ? 3 : i;
4010 size_t len = xstrlen(frac);
4012 if (len < toprint) {
4013 size_buf[ret] = size_buf[ret + 1] = size_buf[ret + 2] = '0';
4014 xstrsncpy(size_buf + ret + (toprint - len), frac, len + 1);
4016 xstrsncpy(size_buf + ret, frac, toprint + 1);
4020 ret = xstrsncpy(size_buf, size ? xitoa(size) : "0", 12);
4024 size_buf[ret] = U[i];
4025 size_buf[ret + 1] = '\0';
4030 /* Convert a mode field into "ls -l" type perms field. */
4031 static char *get_lsperms(mode_t mode)
4033 static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
4034 static char bits[11] = {'\0'};
4036 switch (mode & S_IFMT) {
4063 xstrsncpy(&bits[1], rwx[(mode >> 6) & 7], 4);
4064 xstrsncpy(&bits[4], rwx[(mode >> 3) & 7], 4);
4065 xstrsncpy(&bits[7], rwx[(mode & 7)], 4);
4068 bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
4070 bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
4072 bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
4077 #ifdef ICONS_ENABLED
4078 static struct icon get_icon(const struct entry *ent)
4080 for (size_t i = 0; i < ELEMENTS(icons_name); ++i)
4081 if (strcasecmp(ent->name, icons_name[i].match) == 0)
4082 return (struct icon){ icons_name[i].icon, icons_name[i].color };
4084 if (ent->flags & DIR_OR_DIRLNK)
4087 char *tmp = xextension(ent->name, ent->nlen);
4090 uint16_t z, k, h = icon_ext_hash(++tmp); /* ++tmp to skip '.' */
4091 for (k = 0; k < ICONS_PROBE_MAX; ++k) {
4092 z = (h + k) % ELEMENTS(icons_ext);
4093 if (strcasecmp(tmp, icons_ext[z].match) == 0)
4094 return (struct icon){ icons_ext_uniq[icons_ext[z].idx], icons_ext[z].color };
4098 /* If there's no match and the file is executable, icon that */
4099 if (ent->mode & 0100)
4104 static void print_icon(const struct entry *ent, const int attrs)
4106 const struct icon icon = get_icon(ent);
4107 addstr(ICON_PADDING_LEFT);
4109 attron(COLOR_PAIR(C_UND + 1 + icon.color));
4114 attroff(COLOR_PAIR(C_UND + 1 + icon.color));
4117 addstr(ICON_PADDING_RIGHT);
4121 static void print_time(const time_t *timep, const uchar_t flags)
4125 /* Highlight timestamp for entries 5 minutes young */
4126 if (flags & FILE_YOUNG)
4129 localtime_r(timep, &t);
4130 printw("%s-%02d-%02d %02d:%02d",
4131 xitoa(t.tm_year + 1900), t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min);
4133 if (flags & FILE_YOUNG)
4137 static char get_detail_ind(const mode_t mode)
4139 switch (mode & S_IFMT) {
4140 case S_IFDIR: // fallthrough
4141 case S_IFREG: return ' ';
4142 case S_IFLNK: return '@';
4143 case S_IFSOCK: return '=';
4144 case S_IFIFO: return '|';
4145 case S_IFBLK: return 'b';
4146 case S_IFCHR: return 'c';
4151 /* Note: attribute and indicator values must be initialized to 0 */
4152 static uchar_t get_color_pair_name_ind(const struct entry *ent, char *pind, int *pattr)
4154 switch (ent->mode & S_IFMT) {
4157 if (ent->mode & 0100)
4161 if (ent->flags & HARD_LINK) {
4162 if (ent->mode & 0100)
4166 if (ent->mode & 0100) {
4173 if (g_state.oldcolor)
4176 return g_state.dirctx ? cfg.curctx + 1 : C_DIR;
4178 if (ent->flags & DIR_OR_DIRLNK) {
4180 *pattr |= g_state.oldcolor ? A_DIM : A_BOLD;
4183 if (g_state.oldcolor)
4186 if (!g_state.oldcolor || cfg.showdetail)
4187 return (ent->flags & SYM_ORPHAN) ? C_ORP : C_LNK;
4205 static void printent(const struct entry *ent, uint_t namecols, bool sel)
4210 if (cfg.showdetail) {
4211 int type = ent->mode & S_IFMT;
4212 char perms[6] = {' ', ' ', (char)('0' + ((ent->mode >> 6) & 7)),
4213 (char)('0' + ((ent->mode >> 3) & 7)),
4214 (char)('0' + (ent->mode & 7)), '\0'};
4217 attrs = g_state.oldcolor ? (resetdircolor(ent->flags), A_DIM)
4218 : (fcolors[C_MIS] ? COLOR_PAIR(C_MIS) : 0);
4223 print_time(&ent->sec, ent->flags);
4225 printw("%s%9s ", perms, (type == S_IFREG || type == S_IFDIR)
4226 ? coolsize(cfg.blkorder ? (blkcnt_t)ent->blocks << blk_shift : ent->size)
4227 : (type = (uchar_t)get_detail_ind(ent->mode), (char *)&type));
4235 uchar_t color_pair = get_color_pair_name_ind(ent, &ind, &attrs);
4237 addch((ent->flags & FILE_SELECTED) ? '+' | A_REVERSE | A_BOLD : ' ');
4239 if (g_state.oldcolor)
4240 resetdircolor(ent->flags);
4242 if (ent->flags & FILE_MISSING)
4244 if (color_pair && fcolors[color_pair])
4245 attrs |= COLOR_PAIR(color_pair);
4246 #ifdef ICONS_ENABLED
4247 print_icon(ent, attrs);
4259 addwstr(unescape(ent->name, namecols));
4261 addstr(unescape(ent->name, MIN(namecols, ent->nlen) + 1));
4270 static void savecurctx(char *path, char *curname, int nextctx)
4272 settings tmpcfg = cfg;
4273 context *ctxr = &g_ctx[nextctx];
4275 /* Save current context */
4277 xstrsncpy(g_ctx[tmpcfg.curctx].c_name, curname, NAME_MAX + 1);
4279 g_ctx[tmpcfg.curctx].c_name[0] = '\0';
4281 g_ctx[tmpcfg.curctx].c_cfg = tmpcfg;
4283 if (ctxr->c_cfg.ctxactive) { /* Switch to saved context */
4284 tmpcfg = ctxr->c_cfg;
4285 /* Skip ordering an open context */
4287 cfgsort[CTX_MAX] = cfgsort[nextctx];
4288 cfgsort[nextctx] = '0';
4290 } else { /* Set up a new context from current context */
4291 ctxr->c_cfg.ctxactive = 1;
4292 xstrsncpy(ctxr->c_path, path, PATH_MAX);
4293 ctxr->c_last[0] = ctxr->c_name[0] = ctxr->c_fltr[0] = ctxr->c_fltr[1] = '\0';
4294 ctxr->c_cfg = tmpcfg;
4295 /* If already in an ordered dir, clear ordering for the new context and let it order */
4296 if (cfgsort[cfg.curctx] == 'z')
4297 cfgsort[nextctx] = 'z';
4300 tmpcfg.curctx = nextctx;
4305 static void save_session(const char *sname, int *presel)
4308 session_header_t header = {0};
4309 bool status = FALSE;
4310 char ssnpath[PATH_MAX];
4311 char spath[PATH_MAX];
4313 header.ver = SESSIONS_VERSION;
4315 for (i = 0; i < CTX_MAX; ++i) {
4316 if (g_ctx[i].c_cfg.ctxactive) {
4317 if (cfg.curctx == i && ndents)
4318 /* Update current file name, arrows don't update it */
4319 xstrsncpy(g_ctx[i].c_name, pdents[cur].name, NAME_MAX + 1);
4320 header.pathln[i] = MIN(xstrlen(g_ctx[i].c_path), PATH_MAX) + 1;
4321 header.lastln[i] = MIN(xstrlen(g_ctx[i].c_last), PATH_MAX) + 1;
4322 header.nameln[i] = MIN(xstrlen(g_ctx[i].c_name), NAME_MAX) + 1;
4323 header.fltrln[i] = REGEX_MAX;
4327 mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4328 mkpath(ssnpath, sname, spath);
4330 fd = open(spath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
4332 printwait(messages[MSG_SEL_MISSING], presel);
4336 if ((write(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4337 || (write(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4340 for (i = 0; i < CTX_MAX; ++i)
4341 if ((write(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4342 || (write(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4343 || (header.nameln[i] > 0
4344 && write(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4345 || (header.lastln[i] > 0
4346 && write(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4347 || (header.fltrln[i] > 0
4348 && write(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4349 || (header.pathln[i] > 0
4350 && write(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4359 printwait(messages[MSG_FAILED], presel);
4362 static bool load_session(const char *sname, char **path, char **lastdir, char **lastname, bool restore)
4365 session_header_t header;
4366 bool has_loaded_dynamically = !(sname || restore);
4367 bool status = (sname && g_state.picker); /* Picker mode with session program option */
4368 char ssnpath[PATH_MAX];
4369 char spath[PATH_MAX];
4371 mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4374 sname = sname ? sname : xreadline(NULL, messages[MSG_SSN_NAME]);
4378 mkpath(ssnpath, sname, spath);
4380 /* If user is explicitly loading the "last session", skip auto-save */
4381 if ((sname[0] == '@') && !sname[1])
4382 has_loaded_dynamically = FALSE;
4384 mkpath(ssnpath, "@", spath);
4386 if (has_loaded_dynamically)
4387 save_session("@", NULL);
4389 fd = open(spath, O_RDONLY, S_IWUSR | S_IRUSR);
4392 printmsg(messages[MSG_SEL_MISSING]);
4393 xdelay(XDELAY_INTERVAL_MS);
4400 if ((read(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4401 || (header.ver != SESSIONS_VERSION)
4402 || (read(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4405 g_ctx[cfg.curctx].c_name[0] = g_ctx[cfg.curctx].c_last[0]
4406 = g_ctx[cfg.curctx].c_fltr[0] = g_ctx[cfg.curctx].c_fltr[1] = '\0';
4408 for (; i < CTX_MAX; ++i)
4409 if ((read(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4410 || (read(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4411 || (header.nameln[i] > 0
4412 && read(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4413 || (header.lastln[i] > 0
4414 && read(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4415 || (header.fltrln[i] > 0
4416 && read(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4417 || (header.pathln[i] > 0
4418 && read(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4421 *path = g_ctx[cfg.curctx].c_path;
4422 *lastdir = g_ctx[cfg.curctx].c_last;
4423 *lastname = g_ctx[cfg.curctx].c_name;
4424 set_sort_flags('\0'); /* Set correct sort options */
4431 printmsg(messages[MSG_FAILED]);
4432 xdelay(XDELAY_INTERVAL_MS);
4440 static uchar_t get_free_ctx(void)
4442 uchar_t r = cfg.curctx;
4445 r = (r + 1) & ~CTX_MAX;
4446 while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
4451 /* ctx is absolute: 1 to 4, + for smart context */
4452 static void set_smart_ctx(int ctx, char *nextpath, char **path, char *file, char **lastname, char **lastdir)
4454 if (ctx == '+') /* Get smart context */
4455 ctx = (int)(get_free_ctx() + 1);
4457 if (ctx == 0 || ctx == cfg.curctx + 1) { /* Same context */
4459 xstrsncpy(*lastdir, *path, PATH_MAX);
4460 xstrsncpy(*path, nextpath, PATH_MAX);
4461 } else { /* New context */
4463 /* Deactivate the new context and build from scratch */
4464 g_ctx[ctx].c_cfg.ctxactive = 0;
4465 DPRINTF_S(nextpath);
4466 savecurctx(nextpath, file, ctx);
4467 *path = g_ctx[ctx].c_path;
4468 *lastdir = g_ctx[ctx].c_last;
4469 *lastname = g_ctx[ctx].c_name;
4474 * This function does one of the following depending on the values of `fdout` and `page`:
4475 * 1) fdout == -1 && !page: Write up to CMD_LEN_MAX bytes of command output into g_buf
4476 * 2) fdout == -1 && page: Create a temp file, write full command output into it and show in pager.
4477 * 3) fdout != -1 && !page: Write full command output into the provided file.
4478 * 4) fdout != -1 && page: Don't use! Returns FALSE.
4480 * g_buf is modified only in case 1.
4481 * g_tmpfpath is modified only in case 2.
4483 static bool get_output(char *file, char *arg1, char *arg2, int fdout, bool page)
4487 int index = 0, flags;
4489 bool have_file = fdout != -1;
4491 int cmd_out_fd = -1;
4495 * In this case the logic of the function dictates that we should write the output of the command
4496 * to `fd` and show it in the pager. But since we didn't open the file descriptor we have no right
4497 * to close it, the caller must do it. We don't even know the path to pass to the pager and
4498 * it's a real hassle to get it. In general this just invites problems so we are blocking it.
4500 if (have_file && page) {
4501 DPRINTF_S("invalid get_ouptput() call");
4505 /* Setup file descriptors for child command */
4506 if (!have_file && page) {
4508 fdout = create_tmp_file();
4512 cmd_in_fd = STDIN_FILENO;
4514 } else if (have_file) {
4516 cmd_in_fd = STDIN_FILENO;
4520 if (pipe(pipefd) == -1)
4523 for (index = 0; index < 2; ++index) {
4524 /* Get previous flags */
4525 flags = fcntl(pipefd[index], F_GETFL, 0);
4527 /* Set bit for non-blocking flag */
4528 flags |= O_NONBLOCK;
4530 /* Change flags on fd */
4531 fcntl(pipefd[index], F_SETFL, flags);
4534 cmd_in_fd = pipefd[0];
4535 cmd_out_fd = pipefd[1];
4542 dup2(cmd_out_fd, STDOUT_FILENO);
4543 dup2(cmd_out_fd, STDERR_FILENO);
4546 spawn(file, arg1, arg2, NULL, F_MULTI);
4547 _exit(EXIT_SUCCESS);
4551 waitpid(pid, NULL, 0);
4553 /* Do what each case should do */
4554 if (!have_file && page) {
4558 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4569 len = read(pipefd[0], g_buf, CMD_LEN_MAX - 1);
4579 * Follows the stat(1) output closely
4581 static bool show_stats(char *fpath)
4583 static char * const cmds[] = {
4584 #ifdef FILE_MIME_OPTS
4585 ("file " FILE_MIME_OPTS),
4588 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
4595 size_t r = ELEMENTS(cmds);
4596 int fd = create_tmp_file();
4601 get_output(cmds[--r], fpath, NULL, fd, FALSE);
4605 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4610 static bool xchmod(const char *fpath, mode_t mode)
4612 /* (Un)set (S_IXUSR | S_IXGRP | S_IXOTH) */
4613 (0100 & mode) ? (mode &= ~0111) : (mode |= 0111);
4615 return (chmod(fpath, mode) == 0);
4618 static size_t get_fs_info(const char *path, uchar_t type)
4622 if (statvfs(path, &svb) == -1)
4625 if (type == VFS_AVAIL)
4626 return (size_t)svb.f_bavail << ffs((int)(svb.f_frsize >> 1));
4628 if (type == VFS_USED)
4629 return ((size_t)svb.f_blocks - (size_t)svb.f_bfree) << ffs((int)(svb.f_frsize >> 1));
4631 return (size_t)svb.f_blocks << ffs((int)(svb.f_frsize >> 1)); /* VFS_SIZE */
4634 /* Create non-existent parents and a file or dir */
4635 static bool xmktree(char *path, bool dir)
4643 /* Skip the first '/' */
4646 while (*p != '\0') {
4655 /* Create folder from path to '\0' inserted at p */
4656 if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4658 // XDG_CONFIG_HOME contains a directory
4659 // that is read-only, but the full path
4661 // Try to continue and see what happens.
4662 // TODO: Find a more robust solution.
4663 if (errno == B_READ_ONLY_DEVICE)
4666 DPRINTF_S("mkdir1!");
4667 DPRINTF_S(strerror(errno));
4681 if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4682 DPRINTF_S("mkdir2!");
4683 DPRINTF_S(strerror(errno));
4687 int fd = open(path, O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR); /* Forced create mode for files */
4689 if (fd == -1 && errno != EEXIST) {
4691 DPRINTF_S(strerror(errno));
4701 /* List or extract archive */
4702 static bool handle_archive(char *fpath /* in-out param */, char op)
4704 char arg[] = "-tvf"; /* options for tar/bsdtar to list files */
4705 char *util, *outdir = NULL;
4707 bool is_atool = (!g_state.usebsdtar && getutil(utils[UTIL_ATOOL]));
4710 outdir = xreadline(is_atool ? "." : xbasename(fpath), messages[MSG_NEW_PATH]);
4711 if (!outdir || !*outdir) { /* Cancelled */
4712 printwait(messages[MSG_CANCEL], NULL);
4715 /* Do not create smart context for current dir */
4716 if (!(*outdir == '.' && outdir[1] == '\0')) {
4717 if (!xmktree(outdir, TRUE) || (chdir(outdir) == -1)) {
4721 /* Copy the new dir path to open it in smart context */
4722 outdir = getcwd(NULL, 0);
4728 util = utils[UTIL_ATOOL];
4731 } else if (getutil(utils[UTIL_BSDTAR])) {
4732 util = utils[UTIL_BSDTAR];
4735 } else if (is_suffix(fpath, ".zip")) {
4736 util = utils[UTIL_UNZIP];
4737 arg[1] = (op == 'l') ? 'v' /* verbose listing */ : '\0';
4740 util = utils[UTIL_TAR];
4745 if (op == 'x') /* extract */
4746 spawn(util, arg, fpath, NULL, F_NORMAL | F_MULTI);
4748 get_output(util, arg, fpath, -1, TRUE);
4751 if (chdir(xdirname(fpath)) == -1) {
4756 xstrsncpy(fpath, outdir, PATH_MAX);
4758 } else if (op == 'x')
4764 static char *visit_parent(char *path, char *newpath, int *presel)
4768 /* There is no going back */
4769 if (istopdir(path)) {
4770 /* Continue in type-to-nav mode, if enabled */
4771 if (cfg.filtermode && presel)
4776 /* Use a copy as xdirname() may change the string passed */
4778 xstrsncpy(newpath, path, PATH_MAX);
4782 dir = xdirname(newpath);
4783 if (chdir(dir) == -1) {
4791 static void valid_parent(char *path, char *lastname)
4794 xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
4796 while (!istopdir(path))
4797 if (visit_parent(path, NULL, NULL))
4801 xdelay(XDELAY_INTERVAL_MS);
4804 static bool archive_mount(char *newpath)
4806 char *dir, *cmd = xgetenv("NNN_ARCHMNT", utils[UTIL_ARCHMNT]);
4807 char *name = pdents[cur].name;
4808 size_t len = pdents[cur].nlen;
4809 char mntpath[PATH_MAX];
4811 if (!getutil(cmd)) {
4812 printmsg("install utility");
4816 dir = xstrdup(name);
4818 printmsg(messages[MSG_FAILED]);
4823 if (dir[--len] == '.') {
4830 /* Create the mount point */
4831 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4832 mkpath(mntpath, dir, newpath);
4835 if (!xmktree(newpath, TRUE)) {
4843 if (spawn(cmd, name, newpath, NULL, F_NORMAL)) {
4844 printmsg(messages[MSG_FAILED]);
4851 static bool remote_mount(char *newpath)
4853 uchar_t flag = F_CLI;
4856 bool r = getutil(utils[UTIL_RCLONE]), s = getutil(utils[UTIL_SSHFS]);
4857 char mntpath[PATH_MAX];
4860 printmsg("install sshfs/rclone");
4865 opt = get_input(messages[MSG_REMOTE_OPTS]);
4867 opt = (!s) ? 'r' : 's';
4870 env = xgetenv("NNN_SSHFS", utils[UTIL_SSHFS]);
4871 else if (opt == 'r') {
4872 flag |= F_NOWAIT | F_NOTRACE;
4873 env = xgetenv("NNN_RCLONE", "rclone mount");
4875 printmsg(messages[MSG_INVALID_KEY]);
4879 tmp = xreadline(NULL, "host[:dir] > ");
4881 printmsg(messages[MSG_CANCEL]);
4885 char *div = strchr(tmp, ':');
4890 /* Create the mount point */
4891 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4892 mkpath(mntpath, tmp, newpath);
4893 if (!xmktree(newpath, TRUE)) {
4898 if (!div) { /* Convert "host" to "host:" */
4899 size_t len = xstrlen(tmp);
4902 tmp[len + 1] = '\0';
4906 /* Connect to remote */
4908 if (spawn(env, tmp, newpath, NULL, flag)) {
4909 printmsg(messages[MSG_FAILED]);
4913 spawn(env, tmp, newpath, NULL, flag);
4914 printmsg(messages[MSG_RCLONE_DELAY]);
4915 xdelay(XDELAY_INTERVAL_MS << 2); /* Set 4 times the usual delay */
4922 * Unmounts if the directory represented by name is a mount point.
4923 * Otherwise, asks for hostname
4924 * Returns TRUE if directory needs to be refreshed *.
4926 static bool unmount(char *name, char *newpath, int *presel, char *currentpath)
4928 #if defined(__APPLE__) || defined(__FreeBSD__)
4929 static char cmd[] = "umount";
4931 static char cmd[] = "fusermount3"; /* Arch Linux utility */
4932 static bool found = FALSE;
4935 struct stat sb, psb;
4937 bool parent = FALSE;
4938 bool hovered = FALSE;
4939 char mntpath[PATH_MAX];
4941 #if !defined(__APPLE__) && !defined(__FreeBSD__)
4942 /* On Ubuntu it's fusermount */
4943 if (!found && !getutil(cmd)) {
4949 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4951 if (tmp && strcmp(mntpath, currentpath) == 0) {
4952 mkpath(mntpath, tmp, newpath);
4953 child = lstat(newpath, &sb) != -1;
4954 parent = lstat(xdirname(newpath), &psb) != -1;
4955 if (!child && !parent) {
4961 if (!tmp || !child || !S_ISDIR(sb.st_mode) || (child && parent && sb.st_dev == psb.st_dev)) {
4962 tmp = xreadline(NULL, messages[MSG_HOSTNAME]);
4965 if (name && (tmp[0] == '-') && (tmp[1] == '\0')) {
4966 mkpath(currentpath, name, newpath);
4972 mkpath(mntpath, tmp, newpath);
4974 if (!xdiraccess(newpath)) {
4979 #if defined(__APPLE__) || defined(__FreeBSD__)
4980 if (spawn(cmd, newpath, NULL, NULL, F_NORMAL)) {
4982 if (spawn(cmd, "-qu", newpath, NULL, F_NORMAL)) {
4984 if (!xconfirm(get_input(messages[MSG_LAZY])))
4988 if (spawn(cmd, "-l", newpath, NULL, F_NORMAL)) {
4989 #elif defined(__FreeBSD__)
4990 if (spawn(cmd, "-f", newpath, NULL, F_NORMAL)) {
4992 if (spawn(cmd, "-quz", newpath, NULL, F_NORMAL)) {
4994 printwait(messages[MSG_FAILED], presel);
4999 if (rmdir(newpath) == -1) {
5007 static void lock_terminal(void)
5009 spawn(xgetenv("NNN_LOCKER", utils[UTIL_LOCKER]), NULL, NULL, NULL, F_CLI);
5012 static void printkv(kv *kvarr, int fd, uchar_t max, uchar_t id)
5014 char *val = (id == NNN_BMS) ? bmstr : pluginstr;
5016 for (uchar_t i = 0; i < max && kvarr[i].key; ++i)
5017 dprintf(fd, " %c: %s\n", (char)kvarr[i].key, val + kvarr[i].off);
5020 static void printkeys(kv *kvarr, char *buf, uchar_t max)
5024 for (; i < max && kvarr[i].key; ++i) {
5026 buf[(i << 1) + 1] = kvarr[i].key;
5032 static size_t handle_bookmark(const char *bmark, char *newpath)
5037 if (maxbm || bmark) {
5038 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
5040 if (bmark) { /* There is a marked directory */
5046 printkeys(bookmark, g_buf + r - 1, maxbm);
5048 fd = get_input(NULL);
5052 if (fd == ',') /* Visit marked directory */
5053 bmark ? xstrsncpy(newpath, bmark, PATH_MAX) : (r = MSG_NOT_SET);
5054 else if (fd == '\r') { /* Visit bookmarks directory */
5055 mkpath(cfgpath, toks[TOK_BM], newpath);
5057 } else if (!get_kv_val(bookmark, newpath, fd, maxbm, NNN_BMS))
5058 r = MSG_INVALID_KEY;
5060 if (!r && chdir(newpath) == -1) {
5069 static void add_bookmark(char *path, char *newpath, int *presel)
5071 char *dir = xbasename(path);
5073 dir = xreadline(dir[0] ? dir : NULL, messages[MSG_BM_NAME]);
5075 size_t r = mkpath(cfgpath, toks[TOK_BM], newpath);
5077 newpath[r - 1] = '/';
5078 xstrsncpy(newpath + r, dir, PATH_MAX - r);
5079 printwait((symlink(path, newpath) == -1) ? strerror(errno) : newpath, presel);
5081 printwait(messages[MSG_CANCEL], presel);
5085 * The help string tokens (each line) start with a HEX value
5086 * which indicates the number of spaces to print before the
5087 * particular token. This method was chosen instead of a flat
5088 * string because the number of bytes in help was increasing
5089 * the binary size by around a hundred bytes. This would only
5090 * have increased as we keep adding new options.
5092 static void show_help(const char *path)
5094 const char *start, *end;
5095 const char helpstr[] = {
5098 "9Up k Up%-16cPgUp ^U Page up\n"
5099 "9Dn j Down%-14cPgDn ^D Page down\n"
5100 "9Lt h Parent%-12c~ ` @ - ~, /, start, prev\n"
5101 "5Ret Rt l Open%-20c' First file/match\n"
5102 "9g ^A Top%-21cJ Jump to entry/offset\n"
5103 "9G ^E End%-20c^J Toggle auto-advance on open\n"
5104 "8B (,) Book(mark)%-11cb ^/ Select bookmark\n"
5105 "a1-4 Context%-11c(Sh)Tab Cycle/new context\n"
5106 "62Esc ^Q Quit%-20cq Quit context\n"
5107 "b^G QuitCD%-18cQ Pick/err, quit\n"
5109 "1FILTER & PROMPT\n"
5110 "c/ Filter%-17c^N Toggle type-to-nav\n"
5111 "aEsc Exit prompt%-12c^L Toggle last filter\n"
5112 "c. Toggle hidden%-5cAlt+Esc Unfilter, quit context\n"
5115 "9o ^O Open with%-15cn Create new/link\n"
5116 "9f ^F File stats%-14cd Detail mode toggle\n"
5117 "b^R Rename/dup%-14cr Batch rename\n"
5118 "cz Archive%-17ce Edit file\n"
5119 "c* Toggle exe%-14c> Export list\n"
5120 "6Space + (Un)select%-12cm-m Select range/clear\n"
5121 "ca Select all%-14cA Invert sel\n"
5122 "9p ^P Copy here%-12cw ^W Cp/mv sel as\n"
5123 "9v ^V Move here%-15cE Edit sel list\n"
5124 "9x ^X Delete%-18cS Listed sel size\n"
5125 "aEsc Send to FIFO\n"
5128 "8Alt ; Select plugin%-11c= Launch app\n"
5129 "9! ^] Shell%-19c] Cmd prompt\n"
5130 "cc Connect remote%-10cu Unmount remote/archive\n"
5131 "9t ^T Sort toggles%-12cs Manage session\n"
5132 "cT Set time type%-11c0 Lock\n"
5133 "b^L Redraw%-18c? Help, conf\n"
5136 int fd = create_tmp_file();
5140 dprintf(fd, " |V\\_\n"
5146 char *prog = xgetenv(env_cfg[NNN_HELP], NULL);
5148 get_output(prog, NULL, NULL, fd, FALSE);
5150 start = end = helpstr;
5153 snprintf(g_buf, CMD_LEN_MAX, "%*c%.*s",
5154 xchartohex(*start), ' ', (int)(end - start), start + 1);
5155 dprintf(fd, g_buf, ' ');
5162 dprintf(fd, "\nLOCATIONS\n");
5163 for (uchar_t i = 0; i < CTX_MAX; ++i)
5164 if (g_ctx[i].c_cfg.ctxactive)
5165 dprintf(fd, " %u: %s\n", i + 1, g_ctx[i].c_path);
5167 dprintf(fd, "\nVOLUME: avail:%s ", coolsize(get_fs_info(path, VFS_AVAIL)));
5168 dprintf(fd, "used:%s ", coolsize(get_fs_info(path, VFS_USED)));
5169 dprintf(fd, "size:%s\n\n", coolsize(get_fs_info(path, VFS_SIZE)));
5172 dprintf(fd, "BOOKMARKS\n");
5173 printkv(bookmark, fd, maxbm, NNN_BMS);
5178 dprintf(fd, "PLUGIN KEYS\n");
5179 printkv(plug, fd, maxplug, NNN_PLUG);
5183 for (uchar_t i = NNN_OPENER; i <= NNN_TRASH; ++i) {
5184 start = getenv(env_cfg[i]);
5186 dprintf(fd, "%s: %s\n", env_cfg[i], start);
5190 dprintf(fd, "SELECTION FILE: %s\n", selpath);
5192 dprintf(fd, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
5195 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
5199 static void setexports(void)
5205 setenv(envs[ENV_NCUR], pdents[cur].name, 1);
5206 xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
5207 } else if (g_ctx[cfg.curctx].c_name[0])
5208 g_ctx[cfg.curctx].c_name[0] = '\0';
5210 for (uchar_t i = 0; i < CTX_MAX; ++i) {
5211 if (g_ctx[i].c_cfg.ctxactive) {
5212 dvar[1] = fvar[1] = '1' + i;
5213 setenv(dvar, g_ctx[i].c_path, 1);
5215 if (g_ctx[i].c_name[0]) {
5216 mkpath(g_ctx[i].c_path, g_ctx[i].c_name, g_buf);
5217 setenv(fvar, g_buf, 1);
5221 setenv("NNN_INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
5222 setenv("NNN_PREFER_SELECTION", xitoa(cfg.prefersel), 1);
5225 static void run_cmd_as_plugin(const char *file, uchar_t flags)
5229 xstrsncpy(g_buf, file, PATH_MAX);
5231 len = xstrlen(g_buf);
5232 if (len > 1 && g_buf[len - 1] == '*') {
5233 flags &= ~F_CONFIRM; /* Skip user confirmation */
5234 g_buf[len - 1] = '\0'; /* Get rid of trailing no confirmation symbol */
5239 get_output(utils[UTIL_SH_EXEC], g_buf, NULL, -1, TRUE);
5241 spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, flags);
5244 static bool plctrl_init(void)
5248 /* g_tmpfpath is used to generate tmp file names */
5249 g_tmpfpath[tmpfplen - 1] = '\0';
5250 len = xstrsncpy(g_pipepath, g_tmpfpath, TMP_LEN_MAX);
5251 g_pipepath[len - 1] = '/';
5252 len = xstrsncpy(g_pipepath + len, "nnn-pipe.", TMP_LEN_MAX - len) + len;
5253 xstrsncpy(g_pipepath + len - 1, xitoa(getpid()), TMP_LEN_MAX - len);
5254 setenv(env_cfg[NNN_PIPE], g_pipepath, TRUE);
5256 return EXIT_SUCCESS;
5259 static void rmlistpath(void)
5262 DPRINTF_S(__func__);
5263 DPRINTF_S(listpath);
5264 spawn(utils[UTIL_RM_RF], listpath, NULL, NULL, F_NOTRACE | F_MULTI);
5265 /* Do not free if program was started in list mode */
5266 if (listpath != initpath)
5272 static ssize_t read_nointr(int fd, void *buf, size_t count)
5277 len = read(fd, buf, count);
5278 while (len == -1 && errno == EINTR);
5283 static char *readpipe(int fd, char *ctxnum, char **path)
5285 char ctx, *nextpath = NULL;
5287 if (read_nointr(fd, g_buf, 1) != 1)
5290 if (g_buf[0] == '-') { /* Clear selection on '-' */
5292 if (read_nointr(fd, g_buf, 1) != 1)
5296 if (g_buf[0] == '+')
5297 ctx = (char)(get_free_ctx() + 1);
5298 else if (g_buf[0] < '0')
5301 ctx = g_buf[0] - '0';
5306 if (read_nointr(fd, g_buf, 1) != 1)
5312 ssize_t len = read_nointr(fd, g_buf, PATH_MAX);
5317 g_buf[len] = '\0'; /* Terminate the path read */
5318 if (g_buf[0] == '/') {
5320 len = xstrlen(g_buf);
5321 while (--len && (g_buf[len] == '/')) /* Trim all trailing '/' */
5324 } else if (op == 'l') {
5325 rmlistpath(); /* Remove last list mode path, if any */
5326 nextpath = load_input(fd, *path);
5327 } else if (op == 'p') {
5340 static bool run_plugin(char **path, const char *file, char *runfile, char **lastname, char **lastdir)
5345 bool cmd_as_plugin = FALSE;
5348 if (!g_state.pluginit) {
5350 g_state.pluginit = 1;
5355 /* Check for run-cmd-as-plugin mode */
5357 flags = F_MULTI | F_CONFIRM;
5360 if (*file == '|') { /* Check if output should be paged */
5363 } else if (*file == '&') { /* Check if GUI flags are to be used */
5364 flags = F_MULTI | F_NOTRACE | F_NOWAIT;
5371 if ((flags & F_NOTRACE) || (flags & F_PAGE)) {
5372 run_cmd_as_plugin(file, flags);
5376 cmd_as_plugin = TRUE;
5379 if (mkfifo(g_pipepath, 0600) != 0)
5386 if (!p) { // In child
5387 int wfd = open(g_pipepath, O_WRONLY | O_CLOEXEC);
5390 _exit(EXIT_FAILURE);
5392 if (!cmd_as_plugin) {
5396 /* Generate absolute path to plugin */
5397 mkpath(plgpath, file, g_buf);
5400 sel = selpath ? selpath : std;
5402 if (runfile && runfile[0]) {
5403 xstrsncpy(*lastname, runfile, NAME_MAX);
5404 spawn(g_buf, *lastname, *path, sel, 0);
5406 spawn(g_buf, NULL, *path, sel, 0);
5408 run_cmd_as_plugin(file, flags);
5411 _exit(EXIT_SUCCESS);
5417 rfd = open(g_pipepath, O_RDONLY);
5418 while (rfd == -1 && errno == EINTR);
5420 nextpath = readpipe(rfd, &ctx, path);
5422 set_smart_ctx(ctx, nextpath, path, runfile, lastname, lastdir);
5426 /* wait for the child to finish. no zombies allowed */
5427 waitpid(p, NULL, 0);
5436 static bool launch_app(char *newpath)
5439 char *tmp = newpath;
5441 mkpath(plgpath, utils[UTIL_LAUNCH], newpath);
5443 if (!getutil(utils[UTIL_FZF]) || access(newpath, X_OK) < 0) {
5444 tmp = xreadline(NULL, messages[MSG_APP_NAME]);
5445 r = F_NOWAIT | F_NOTRACE | F_MULTI;
5448 if (tmp && *tmp) // NOLINT
5449 spawn(tmp, (r == F_NORMAL) ? "0" : NULL, NULL, NULL, r);
5454 /* Returns TRUE if at least one command was run */
5455 static bool prompt_run(void)
5458 char *cmdline, *next;
5459 int cnt_j, cnt_J, cmd_ret;
5462 const char *xargs_j = "xargs -0 -I{} %s < %s";
5463 const char *xargs_J = "xargs -0 %s < %s";
5464 char cmd[CMD_LEN_MAX + 32]; // 32 for xargs format strings
5468 if (g_state.picker) {
5470 cmdline = xreadline(NULL, PROMPT);
5473 cmdline = getreadline("\n"PROMPT);
5475 // Check for an empty command
5476 if (!cmdline || !cmdline[0])
5480 lastcmd = xstrdup(cmdline);
5483 len = xstrlen(cmdline);
5487 while ((next = strstr(next, "%j"))) {
5490 // replace %j with {} for xargs later
5499 while ((next = strstr(next, "%J"))) {
5502 // %J should be the last thing in the command
5503 if (next == cmdline + len - 2) {
5504 cmdline[len - 2] = '\0';
5510 // We can't handle both %j and %J in a single command
5515 snprintf(cmd, CMD_LEN_MAX + 32, xargs_j, cmdline, selpath);
5517 snprintf(cmd, CMD_LEN_MAX + 32, xargs_J, cmdline, selpath);
5519 cmd_ret = spawn(shell, "-c", (cnt_j || cnt_J) ? cmd : cmdline, NULL, F_CLI | F_CONFIRM);
5520 if ((cnt_j || cnt_J) && cmd_ret == 0)
5527 static bool handle_cmd(enum action sel, char *newpath)
5529 endselection(FALSE);
5531 if (sel == SEL_LAUNCH)
5532 return launch_app(newpath);
5536 if (sel == SEL_PROMPT)
5537 return prompt_run();
5539 /* Set nnn nesting level */
5540 char *tmp = getenv(env_cfg[NNNLVL]);
5541 int r = tmp ? atoi(tmp) : 0;
5543 setenv(env_cfg[NNNLVL], xitoa(r + 1), 1);
5544 spawn(shell, NULL, NULL, NULL, F_CLI);
5545 setenv(env_cfg[NNNLVL], xitoa(r), 1);
5549 static void dentfree(void)
5555 /* Thread data cleanup */
5561 static void *du_thread(void *p_data)
5563 thread_data *pdata = (thread_data *)p_data;
5564 char *path[2] = {pdata->path, NULL};
5565 ullong_t tfiles = 0;
5566 blkcnt_t tblocks = 0;
5568 FTS *tree = fts_open(path, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR, 0);
5571 while ((node = fts_read(tree))) {
5572 if (node->fts_info & FTS_D) {
5573 if (g_state.interrupt)
5578 sb = node->fts_statp;
5580 if (cfg.apparentsz) {
5581 if (sb->st_size && DU_TEST)
5582 tblocks += sb->st_size;
5583 } else if (sb->st_blocks && DU_TEST)
5584 tblocks += sb->st_blocks;
5591 if (pdata->entnum >= 0)
5592 pdents[pdata->entnum].blocks = tblocks;
5594 if (!pdata->mntpoint) {
5595 core_blocks[pdata->core] += tblocks;
5596 core_files[pdata->core] += tfiles;
5598 core_files[pdata->core] += 1;
5600 pthread_mutex_lock(&running_mutex);
5601 threadbmp |= (1 << pdata->core);
5603 pthread_mutex_unlock(&running_mutex);
5608 static void dirwalk(char *path, int entnum, bool mountpoint)
5610 /* Loop till any core is free */
5611 while (active_threads == NUM_DU_THREADS);
5613 if (g_state.interrupt)
5616 pthread_mutex_lock(&running_mutex);
5617 int core = ffs(threadbmp) - 1;
5619 threadbmp &= ~(1 << core);
5621 pthread_mutex_unlock(&running_mutex);
5623 xstrsncpy(core_data[core].path, path, PATH_MAX);
5624 core_data[core].entnum = entnum;
5625 core_data[core].core = (ushort_t)core;
5626 core_data[core].mntpoint = mountpoint;
5630 pthread_create(&tid, NULL, du_thread, (void *)&(core_data[core]));
5633 addstr(xbasename(path));
5634 addstr(" [^C aborts]\n");
5638 static bool prep_threads(void)
5640 if (!g_state.duinit) {
5642 threadbmp >>= (32 - NUM_DU_THREADS);
5645 core_blocks = calloc(NUM_DU_THREADS, sizeof(blkcnt_t));
5647 core_data = calloc(NUM_DU_THREADS, sizeof(thread_data));
5649 core_files = calloc(NUM_DU_THREADS, sizeof(ullong_t));
5651 if (!core_blocks || !core_data || !core_files) {
5656 /* Increase current open file descriptor limit */
5659 g_state.duinit = TRUE;
5661 memset(core_blocks, 0, NUM_DU_THREADS * sizeof(blkcnt_t));
5662 memset(core_data, 0, NUM_DU_THREADS * sizeof(thread_data));
5663 memset(core_files, 0, NUM_DU_THREADS * sizeof(ullong_t));
5668 /* Skip self and parent */
5669 static inline bool selforparent(const char *path)
5671 return path[0] == '.' && (path[1] == '\0' || (path[1] == '.' && path[2] == '\0'));
5674 static int dentfill(char *path, struct entry **ppdents)
5676 uchar_t entflags = 0;
5679 char *namep, *pnb, *buf;
5680 struct entry *dentp;
5681 size_t off = 0, namebuflen = NAMEBUF_INCR;
5682 struct stat sb_path, sb;
5683 DIR *dirp = opendir(path);
5686 gtimesecs = time(NULL);
5688 DPRINTF_S(__func__);
5693 int fd = dirfd(dirp);
5700 if (fstatat(fd, path, &sb_path, 0) == -1)
5704 ihashbmp = calloc(1, HASH_OCTETS << 3);
5708 memset(ihashbmp, 0, HASH_OCTETS << 3);
5710 if (!prep_threads())
5713 attron(COLOR_PAIR(cfg.curctx + 1));
5716 #if _POSIX_C_SOURCE >= 200112L
5717 posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
5724 #if defined(__sun) || defined(__HAIKU__)
5725 flags = AT_SYMLINK_NOFOLLOW; /* no d_type */
5727 if (cfg.blkorder || dp->d_type == DT_UNKNOWN) {
5729 * Optimization added for filesystems which support dirent.d_type
5732 * - the symlink size is set to 0
5733 * - the modification time of the symlink is set to that of the target file
5735 flags = AT_SYMLINK_NOFOLLOW;
5742 if (selforparent(namep))
5745 if (!cfg.showhidden && namep[0] == '.') {
5749 if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
5752 if (S_ISDIR(sb.st_mode)) {
5753 if (sb_path.st_dev == sb.st_dev) { // NOLINT
5754 mkpath(path, namep, buf); // NOLINT
5755 dirwalk(buf, -1, FALSE);
5757 if (g_state.interrupt)
5761 /* Do not recount hard links */
5762 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5763 dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5770 if (fstatat(fd, namep, &sb, flags) == -1) {
5771 if (flags || (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)) {
5776 DPRINTF_S(strerror(errno));
5779 entflags = FILE_MISSING;
5780 memset(&sb, 0, sizeof(struct stat));
5781 } else /* Orphaned symlink */
5782 entflags = SYM_ORPHAN;
5785 if (ndents == total_dents) {
5787 while (active_threads);
5789 total_dents += ENTRY_INCR;
5790 *ppdents = xrealloc(*ppdents, total_dents * sizeof(**ppdents));
5796 DPRINTF_P(*ppdents);
5799 /* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
5800 if (namebuflen - off < NAME_MAX + 1) {
5801 namebuflen += NAMEBUF_INCR;
5804 pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
5810 DPRINTF_P(pnamebuf);
5812 /* realloc() may result in memory move, we must re-adjust if that happens */
5813 if (pnb != pnamebuf) {
5815 dentp->name = pnamebuf;
5817 for (int count = 1; count < ndents; ++dentp, ++count)
5818 /* Current file name starts at last file name start + length */
5819 (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
5823 dentp = *ppdents + ndents;
5825 /* Selection file name */
5826 dentp->name = (char *)((size_t)pnamebuf + off);
5827 dentp->nlen = xstrsncpy(dentp->name, namep, NAME_MAX + 1);
5830 /* Copy other fields */
5831 if (cfg.timetype == T_MOD) {
5832 dentp->sec = sb.st_mtime;
5834 dentp->nsec = (uint_t)sb.st_mtimespec.tv_nsec;
5836 dentp->nsec = (uint_t)sb.st_mtim.tv_nsec;
5838 } else if (cfg.timetype == T_ACCESS) {
5839 dentp->sec = sb.st_atime;
5841 dentp->nsec = (uint_t)sb.st_atimespec.tv_nsec;
5843 dentp->nsec = (uint_t)sb.st_atim.tv_nsec;
5846 dentp->sec = sb.st_ctime;
5848 dentp->nsec = (uint_t)sb.st_ctimespec.tv_nsec;
5850 dentp->nsec = (uint_t)sb.st_ctim.tv_nsec;
5854 if ((gtimesecs - sb.st_mtime <= 300) || (gtimesecs - sb.st_ctime <= 300))
5855 entflags |= FILE_YOUNG;
5857 #if !(defined(__sun) || defined(__HAIKU__))
5858 if (!flags && dp->d_type == DT_LNK) {
5859 /* Do not add sizes for links */
5860 dentp->mode = (sb.st_mode & ~S_IFMT) | S_IFLNK;
5861 dentp->size = listpath ? sb.st_size : 0;
5863 dentp->mode = sb.st_mode;
5864 dentp->size = sb.st_size;
5867 dentp->mode = sb.st_mode;
5868 dentp->size = sb.st_size;
5872 dentp->uid = sb.st_uid;
5873 dentp->gid = sb.st_gid;
5876 dentp->flags = S_ISDIR(sb.st_mode) ? 0 : ((sb.st_nlink > 1) ? HARD_LINK : 0);
5878 dentp->flags |= entflags;
5883 if (S_ISDIR(sb.st_mode)) {
5884 mkpath(path, namep, buf); // NOLINT
5886 /* Need to show the disk usage of this dir */
5887 dirwalk(buf, ndents, (sb_path.st_dev != sb.st_dev)); // NOLINT
5889 if (g_state.interrupt)
5892 dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5893 /* Do not recount hard links */
5894 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5895 dir_blocks += dentp->blocks;
5901 /* Flag if this is a dir or symlink to a dir */
5902 if (S_ISLNK(sb.st_mode)) {
5904 fstatat(fd, namep, &sb, 0);
5907 if (S_ISDIR(sb.st_mode))
5908 dentp->flags |= DIR_OR_DIRLNK;
5909 #if !(defined(__sun) || defined(__HAIKU__)) /* no d_type */
5910 } else if (dp->d_type == DT_DIR || ((dp->d_type == DT_LNK
5911 || dp->d_type == DT_UNKNOWN) && S_ISDIR(sb.st_mode))) {
5912 dentp->flags |= DIR_OR_DIRLNK;
5917 } while ((dp = readdir(dirp)));
5920 if (g_state.duinit && cfg.blkorder) {
5921 while (active_threads);
5923 attroff(COLOR_PAIR(cfg.curctx + 1));
5924 for (int i = 0; i < NUM_DU_THREADS; ++i) {
5925 num_files += core_files[i];
5926 dir_blocks += core_blocks[i];
5930 /* Should never be null */
5931 if (closedir(dirp) == -1)
5937 static void populate(char *path, char *lastname)
5940 struct timespec ts1, ts2;
5942 clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
5945 ndents = dentfill(path, &pdents);
5950 ENTSORT(pdents, ndents, entrycmpfn);
5954 clock_gettime(CLOCK_REALTIME, &ts2);
5955 DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
5958 /* Find cur from history */
5959 /* No NULL check for lastname, always points to an array */
5960 move_cursor(*lastname ? dentfind(lastname, ndents) : 0, 0);
5962 // Force full redraw
5963 last_curscroll = -1;
5967 static void notify_fifo(bool force)
5973 fifofd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC);
5976 /* Unexpected error, the FIFO file might have been removed */
5977 /* We give up FIFO notification */
5983 static struct entry lastentry;
5985 if (!force && !memcmp(&lastentry, &pdents[cur], sizeof(struct entry))) // NOLINT
5988 lastentry = pdents[cur];
5990 char path[PATH_MAX];
5991 size_t len = mkpath(g_ctx[cfg.curctx].c_path, ndents ? pdents[cur].name : "", path);
5993 path[len - 1] = '\n';
5995 ssize_t ret = write(fifofd, path, len);
5997 if (ret != (ssize_t)len && !(ret == -1 && (errno == EAGAIN || errno == EPIPE))) {
5998 DPRINTF_S(strerror(errno));
6002 static void send_to_explorer(int *presel)
6005 int fd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0600);
6006 if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
6015 notify_fifo(TRUE); /* Send opened path to NNN_FIFO */
6019 static void move_cursor(int target, int ignore_scrolloff)
6021 int onscreen = xlines - 4; /* Leave top 2 and bottom 2 lines */
6023 target = MAX(0, MIN(ndents - 1, target));
6024 last_curscroll = curscroll;
6028 if (!ignore_scrolloff) {
6029 int delta = target - last;
6030 int scrolloff = MIN(SCROLLOFF, onscreen >> 1);
6033 * When ignore_scrolloff is 1, the cursor can jump into the scrolloff
6034 * margin area, but when ignore_scrolloff is 0, act like a boa
6035 * constrictor and squeeze the cursor towards the middle region of the
6036 * screen by allowing it to move inward and disallowing it to move
6037 * outward (deeper into the scrolloff margin area).
6039 if (((cur < (curscroll + scrolloff)) && delta < 0)
6040 || ((cur > (curscroll + onscreen - scrolloff - 1)) && delta > 0))
6043 curscroll = MIN(curscroll, MIN(cur, ndents - onscreen));
6044 curscroll = MAX(curscroll, MAX(cur - (onscreen - 1), 0));
6047 if (!g_state.fifomode)
6048 notify_fifo(FALSE); /* Send hovered path to NNN_FIFO */
6052 static void handle_screen_move(enum action sel)
6058 if (cfg.rollover || (cur != ndents - 1))
6059 move_cursor((cur + 1) % ndents, 0);
6062 if (cfg.rollover || cur)
6063 move_cursor((cur + ndents - 1) % ndents, 0);
6066 onscreen = xlines - 4;
6067 move_cursor(curscroll + (onscreen - 1), 1);
6068 curscroll += onscreen - 1;
6071 onscreen = xlines - 4;
6072 move_cursor(curscroll + (onscreen - 1), 1);
6073 curscroll += onscreen >> 1;
6076 onscreen = xlines - 4;
6077 move_cursor(curscroll, 1);
6078 curscroll -= onscreen - 1;
6081 onscreen = xlines - 4;
6082 move_cursor(curscroll, 1);
6083 curscroll -= onscreen >> 1;
6087 char *input = xreadline(NULL, "jump (+n/-n/n): ");
6089 if (!input || !*input)
6091 if (input[0] == '-') {
6092 cur -= atoi(input + 1);
6095 } else if (input[0] == '+') {
6096 cur += atoi(input + 1);
6100 int index = atoi(input);
6102 if ((index < 1) || (index > ndents))
6106 onscreen = xlines - 4;
6107 move_cursor(cur, 1);
6108 curscroll -= onscreen >> 1;
6115 move_cursor(ndents - 1, 1);
6117 default: /* case SEL_FIRST */
6119 int c = get_input(messages[MSG_FIRST]);
6126 int r = (c == TOUPPER(*pdents[cur].name)) ? (cur + 1) : 0;
6128 for (; r < ndents; ++r) {
6129 if (((c == '\'') && !(pdents[r].flags & DIR_OR_DIRLNK))
6130 || (c == TOUPPER(*pdents[r].name))) {
6131 move_cursor((r) % ndents, 0);
6140 static void handle_openwith(const char *path, const char *name, char *newpath, char *tmp)
6142 /* Confirm if app is CLI or GUI */
6143 int r = get_input(messages[MSG_CLI_MODE]);
6145 r = (r == 'c' ? F_CLI :
6146 ((r == 'g' || r == '\r') ? (F_NOWAIT | F_NOTRACE | F_MULTI) : 0));
6148 mkpath(path, name, newpath);
6149 spawn(tmp, newpath, NULL, NULL, r);
6153 static void copynextname(char *lastname)
6156 cur += (cur != (ndents - 1)) ? 1 : -1;
6162 static int handle_context_switch(enum action sel)
6167 case SEL_CYCLE: // fallthrough
6169 /* visit next and previous contexts */
6171 if (sel == SEL_CYCLE)
6173 r = (r + 1) & ~CTX_MAX;
6174 while (!g_ctx[r].c_cfg.ctxactive);
6176 do /* Attempt to create a new context */
6177 r = (r + 1) & ~CTX_MAX;
6178 while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
6180 if (r == cfg.curctx) /* If all contexts are active, reverse cycle */
6182 r = (r + (CTX_MAX - 1)) & (CTX_MAX - 1);
6183 while (!g_ctx[r].c_cfg.ctxactive);
6185 default: /* SEL_CTXN */
6186 if (sel >= SEL_CTX1) /* CYCLE keys are lesser in value */
6187 r = sel - SEL_CTX1; /* Save the next context id */
6189 if (cfg.curctx == r) {
6190 if (sel == SEL_CYCLE)
6191 (r == CTX_MAX - 1) ? (r = 0) : ++r;
6192 else if (sel == SEL_CYCLER)
6193 (r == 0) ? (r = CTX_MAX - 1) : --r;
6202 static int set_sort_flags(int r)
6204 bool session = (r == '\0');
6205 bool reverse = FALSE;
6207 if (ISUPPER_(r) && (r != 'R') && (r != 'C')) {
6212 /* Set the correct input in case of a session load */
6214 if (cfg.apparentsz) {
6217 } else if (cfg.blkorder) {
6223 namecmpfn = &xstrverscasecmp;
6226 entrycmpfn = &reventrycmp;
6227 } else if (r == CONTROL('T')) {
6228 /* Cycling order: clear -> size -> time -> clear */
6231 else if (cfg.sizeorder)
6238 case 'a': /* Apparent du */
6239 cfg.apparentsz ^= 1;
6240 if (cfg.apparentsz) {
6246 case 'd': /* Disk usage */
6248 if (!cfg.apparentsz)
6251 blk_shift = ffs(S_BLKSIZE) - 1;
6261 entrycmpfn = &entrycmp;
6263 endselection(TRUE); /* We are going to reload dir */
6273 entrycmpfn = &entrycmp;
6274 namecmpfn = &xstricmp;
6276 case 'e': /* File extension */
6283 entrycmpfn = &entrycmp;
6285 case 'r': /* Reverse sort */
6287 entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
6289 case 's': /* File size */
6296 entrycmpfn = &entrycmp;
6298 case 't': /* Time */
6305 entrycmpfn = &entrycmp;
6307 case 'v': /* Version */
6309 namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
6322 entrycmpfn = &reventrycmp;
6325 cfgsort[cfg.curctx] = (uchar_t)r;
6330 static bool set_time_type(int *presel)
6333 char buf[] = "'a'ccess / 'c'hange / 'm'od [ ]";
6335 buf[sizeof(buf) - 3] = cfg.timetype == T_MOD ? 'm' : (cfg.timetype == T_ACCESS ? 'a' : 'c');
6337 int r = get_input(buf);
6339 if (r == 'a' || r == 'c' || r == 'm') {
6340 r = (r == 'm') ? T_MOD : ((r == 'a') ? T_ACCESS : T_CHANGE);
6341 if (cfg.timetype != r) {
6344 if (cfg.filtermode || g_ctx[cfg.curctx].c_fltr[1])
6351 r = MSG_INVALID_KEY;
6354 printwait(messages[r], presel);
6359 static void statusbar(char *path)
6363 pEntry pent = &pdents[cur];
6370 /* Get the file extension for regular files */
6371 if (S_ISREG(pent->mode)) {
6372 i = (int)(pent->nlen - 1);
6373 ptr = xextension(pent->name, i);
6375 len = i - (ptr - pent->name);
6376 if (!ptr || len > 5 || len < 2)
6381 attron(COLOR_PAIR(cfg.curctx + 1));
6383 if (cfg.fileinfo && get_output("file", "-b", pdents[cur].name, -1, FALSE))
6384 mvaddstr(xlines - 2, 2, g_buf);
6388 printw("%d/%s ", cur + 1, xitoa(ndents));
6390 if (g_state.selmode || nselected) {
6393 if (g_state.rangesel)
6395 else if (g_state.selmode)
6398 addstr(xitoa(nselected));
6404 if (cfg.blkorder) { /* du mode */
6407 xstrsncpy(buf, coolsize(dir_blocks << blk_shift), 12);
6409 printw("%cu:%s avail:%s files:%llu %lluB %s\n",
6410 (cfg.apparentsz ? 'a' : 'd'), buf, coolsize(get_fs_info(path, VFS_AVAIL)),
6411 num_files, (ullong_t)pent->blocks << blk_shift, ptr);
6412 } else { /* light or detail mode */
6413 char sort[] = "\0\0\0\0\0";
6415 if (getorderstr(sort))
6419 print_time(&pent->sec, pent->flags);
6422 addstr(get_lsperms(pent->mode));
6425 if (g_state.uidgid) {
6426 addstr(getpwname(pent->uid));
6428 addstr(getgrname(pent->gid));
6432 if (S_ISLNK(pent->mode)) {
6433 if (!cfg.fileinfo) {
6434 i = readlink(pent->name, g_buf, PATH_MAX);
6435 addstr(coolsize(i >= 0 ? i : pent->size)); /* Show symlink size */
6436 if (i > 1) { /* Show symlink target */
6440 getyx(stdscr, len, y);
6441 i = MIN(i, xcols - y);
6447 addstr(coolsize(pent->size));
6450 if (pent->flags & HARD_LINK) {
6453 if (stat(pent->name, &sb) != -1) {
6455 addstr(xitoa((int)sb.st_nlink)); /* Show number of links */
6457 addstr(xitoa((int)sb.st_ino)); /* Show inode number */
6464 attroff(COLOR_PAIR(cfg.curctx + 1));
6465 /* Place HW cursor on current for Braille systems */
6469 static inline void markhovered(void)
6471 if (cfg.showdetail && ndents) { /* Bold forward arrowhead */
6473 addch('>' | A_BOLD);
6477 static int adjust_cols(int n)
6479 /* Calculate the number of cols available to print entry name */
6480 #ifdef ICONS_ENABLED
6481 n -= (g_state.oldcolor ? 0 : ICON_SIZE + ICON_PADDING_LEFT_LEN + ICON_PADDING_RIGHT_LEN);
6483 if (cfg.showdetail) {
6484 /* Fallback to light mode if less than 35 columns */
6486 cfg.showdetail ^= 1;
6487 else /* 2 more accounted for below */
6491 /* 2 columns for preceding space and indicator */
6495 static void draw_line(int ncols)
6499 ncols = adjust_cols(ncols);
6501 if (g_state.oldcolor && (pdents[last].flags & DIR_OR_DIRLNK)) {
6502 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6506 move(2 + last - curscroll, 0);
6507 printent(&pdents[last], ncols, FALSE);
6509 if (g_state.oldcolor && (pdents[cur].flags & DIR_OR_DIRLNK)) {
6510 if (!dir) {/* First file is not a directory */
6511 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6514 } else if (dir) { /* Second file is not a directory */
6515 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6519 move(2 + cur - curscroll, 0);
6520 printent(&pdents[cur], ncols, TRUE);
6522 /* Must reset e.g. no files in dir */
6524 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6529 static void redraw(char *path)
6531 getmaxyx(stdscr, xlines, xcols);
6533 int ncols = (xcols <= PATH_MAX) ? xcols : PATH_MAX;
6534 int onscreen = xlines - 4;
6541 if (ndents && (last_curscroll == curscroll))
6542 return draw_line(ncols);
6545 DPRINTF_S(__func__);
6550 /* Enforce scroll/cursor invariants */
6551 move_cursor(cur, 1);
6553 /* Fail redraw if < than 10 columns, context info prints 10 chars */
6554 if (ncols <= MIN_DISPLAY_COL) {
6555 printmsg(messages[MSG_FEW_COLUMNS]);
6562 for (i = 0; i < CTX_MAX; ++i) { /* 8 chars printed for contexts - "1 2 3 4 " */
6563 if (!g_ctx[i].c_cfg.ctxactive)
6566 addch((i + '1') | (COLOR_PAIR(i + 1) | A_BOLD
6567 /* active: underline, current: reverse */
6568 | ((cfg.curctx != i) ? A_UNDERLINE : A_REVERSE)));
6573 attron(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6576 bool in_home = set_tilde_in_path(path);
6577 char *ptr = in_home ? &path[homelen - 1] : path;
6579 i = (int)xstrlen(ptr);
6580 if ((i + MIN_DISPLAY_COL) <= ncols)
6581 addnstr(ptr, ncols - MIN_DISPLAY_COL);
6583 char *base = xmemrchr((uchar_t *)ptr, '/', i);
6592 if (ptr && (base != ptr)) {
6593 while (ptr < base) {
6595 i += 2; /* 2 characters added */
6596 if (ncols < i + MIN_DISPLAY_COL) {
6597 base = NULL; /* Can't print more characters */
6609 addnstr(base, ncols - (MIN_DISPLAY_COL + i));
6613 reset_tilde_in_path(path);
6615 attroff(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6617 /* Go to first entry */
6618 if (curscroll > 0) {
6620 #ifdef ICONS_ENABLED
6621 addstr(ICON_ARROW_UP);
6627 if (g_state.oldcolor) {
6628 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6629 g_state.dircolor = 1;
6632 onscreen = MIN(onscreen + curscroll, ndents);
6634 ncols = adjust_cols(ncols);
6636 int len = scanselforpath(path, FALSE);
6639 for (i = curscroll; i < onscreen; ++i) {
6643 findmarkentry(len, &pdents[i]);
6645 printent(&pdents[i], ncols, i == cur);
6648 /* Must reset e.g. no files in dir */
6649 if (g_state.dircolor) {
6650 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6651 g_state.dircolor = 0;
6654 /* Go to last entry */
6655 if (onscreen < ndents) {
6656 move(xlines - 2, 0);
6657 #ifdef ICONS_ENABLED
6658 addstr(ICON_ARROW_DOWN);
6667 static bool cdprep(char *lastdir, char *lastname, char *path, char *newpath)
6672 /* Save last working directory */
6673 xstrsncpy(lastdir, path, PATH_MAX);
6675 /* Save the newly opted dir in path */
6676 xstrsncpy(path, newpath, PATH_MAX);
6680 return cfg.filtermode;
6683 static void showselsize(const char *path)
6686 int len = scanselforpath(path, FALSE);
6688 for (int r = 0, selcount = nselected; (r < ndents) && selcount; ++r)
6689 if (findinsel(findselpos, len + xstrsncpy(g_sel + len, pdents[r].name, pdents[r].nlen))) {
6690 sz += cfg.blkorder ? pdents[r].blocks : pdents[r].size;
6694 printmsg(coolsize(cfg.blkorder ? sz << blk_shift : sz));
6697 static bool browse(char *ipath, const char *session, int pkey)
6699 alignas(max_align_t) char newpath[PATH_MAX];
6700 alignas(max_align_t) char runfile[NAME_MAX + 1];
6701 char *path, *lastdir, *lastname, *dir, *tmp;
6705 int r = -1, presel, selstartid = 0, selendid = 0;
6706 const uchar_t opener_flags = (cfg.cliopener ? F_CLI : (F_NOTRACE | F_NOSTDIN | F_NOWAIT));
6707 bool watch = FALSE, cd = TRUE;
6712 struct timespec mousetimings[2] = {{.tv_sec = 0, .tv_nsec = 0}, {.tv_sec = 0, .tv_nsec = 0}};
6713 int mousedent[2] = {-1, -1};
6714 bool currentmouse = 1, rightclicksel = 0;
6719 getmaxyx(stdscr, xlines, xcols);
6722 /* set-up first context */
6723 if (!session || !load_session(session, &path, &lastdir, &lastname, FALSE)) {
6727 g_ctx[0].c_last[0] = '\0';
6728 lastdir = g_ctx[0].c_last; /* last visited directory */
6730 if (g_state.initfile) {
6731 xstrsncpy(g_ctx[0].c_name, xbasename(ipath), sizeof(g_ctx[0].c_name));
6734 g_ctx[0].c_name[0] = '\0';
6736 lastname = g_ctx[0].c_name; /* last visited file name */
6738 xstrsncpy(g_ctx[0].c_path, ipath, PATH_MAX);
6739 /* If the initial path is a file, retain a way to return to start dir */
6740 if (g_state.initfile) {
6742 initpath = ipath = getcwd(NULL, 0);
6744 path = g_ctx[0].c_path; /* current directory */
6746 g_ctx[0].c_fltr[0] = g_ctx[0].c_fltr[1] = '\0';
6747 g_ctx[0].c_cfg = cfg; /* current configuration */
6752 newpath[0] = runfile[0] = '\0';
6754 presel = pkey ? ((pkey == CREATE_NEW_KEY) ? 'n' : ';') : ((cfg.filtermode
6755 || (session && (g_ctx[cfg.curctx].c_fltr[0] == FILTER
6756 || g_ctx[cfg.curctx].c_fltr[0] == RFILTER)
6757 && g_ctx[cfg.curctx].c_fltr[1])) ? FILTER : 0);
6759 pdents = xrealloc(pdents, total_dents * sizeof(struct entry));
6763 /* Allocate buffer to hold names */
6764 pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
6768 /* The following call is added to handle a broken window at start */
6769 if (presel == FILTER)
6770 handle_key_resize();
6774 * Can fail when permissions change while browsing.
6775 * It's assumed that path IS a directory when we are here.
6777 if (chdir(path) == -1) {
6778 DPRINTF_S("directory inaccessible");
6779 valid_parent(path, lastname);
6787 #ifdef LINUX_INOTIFY
6788 if ((presel == FILTER || watch) && inotify_wd >= 0) {
6789 inotify_rm_watch(inotify_fd, inotify_wd);
6793 #elif defined(BSD_KQUEUE)
6794 if ((presel == FILTER || watch) && event_fd >= 0) {
6799 #elif defined(HAIKU_NM)
6800 if ((presel == FILTER || watch) && haiku_hnd != NULL) {
6801 haiku_stop_watch(haiku_hnd);
6802 haiku_nm_active = FALSE;
6808 if (cfgsort[cfg.curctx] != '0') {
6809 if (cfgsort[cfg.curctx] == 'z')
6810 set_sort_flags('c');
6811 if ((!cfgsort[cfg.curctx] || (cfgsort[cfg.curctx] == 'c'))
6812 && ((r = get_kv_key(order, path, maxorder, NNN_ORDER)) > 0)) { // NOLINT
6814 cfgsort[cfg.curctx] = 'z';
6817 cfgsort[cfg.curctx] = cfgsort[CTX_MAX];
6821 populate(path, lastname);
6822 if (g_state.interrupt) {
6823 g_state.interrupt = cfg.apparentsz = cfg.blkorder = 0;
6824 blk_shift = BLK_SHIFT_512;
6825 presel = CONTROL('L');
6828 #ifdef LINUX_INOTIFY
6829 if (presel != FILTER && inotify_wd == -1)
6830 inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
6831 #elif defined(BSD_KQUEUE)
6832 if (presel != FILTER && event_fd == -1) {
6833 #if defined(O_EVTONLY)
6834 event_fd = open(path, O_EVTONLY);
6836 event_fd = open(path, O_RDONLY);
6839 EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
6840 EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
6842 #elif defined(HAIKU_NM)
6843 haiku_nm_active = haiku_watch_dir(haiku_hnd, path) == EXIT_SUCCESS;
6847 /* Do not do a double redraw in filterentries */
6848 if ((presel != FILTER) || !filterset()) {
6854 /* Exit if parent has exited */
6856 _exit(EXIT_FAILURE);
6858 /* If CWD is deleted or moved or perms changed, find an accessible parent */
6859 if (chdir(path) == -1)
6862 /* If STDIN is no longer a tty (closed) we should exit */
6863 if (!isatty(STDIN_FILENO) && !g_state.picker)
6864 return EXIT_FAILURE;
6866 sel = nextsel(presel);
6873 if (getmouse(&event) != OK)
6876 /* Handle clicking on a context at the top */
6877 if (event.bstate == BUTTON1_PRESSED && event.y == 0) {
6878 /* Get context from: "[1 2 3 4]..." */
6881 /* If clicked after contexts, go to parent */
6884 else if (r >= 0 && r != cfg.curctx) {
6885 savecurctx(path, ndents ? pdents[cur].name : NULL, r);
6887 /* Reset the pointers */
6888 path = g_ctx[r].c_path;
6889 lastdir = g_ctx[r].c_last;
6890 lastname = g_ctx[r].c_name;
6900 if (sel == SEL_BACK) {
6902 dir = visit_parent(path, newpath, &presel);
6907 xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
6909 cdprep(lastdir, NULL, path, dir) ? (presel = FILTER) : (watch = TRUE);
6916 /* Middle click action */
6917 if (event.bstate == BUTTON2_PRESSED) {
6918 presel = middle_click_key;
6921 #if NCURSES_MOUSE_VERSION > 1
6923 if (event.bstate == BUTTON4_PRESSED && ndents && (cfg.rollover || cur)) {
6924 move_cursor((!cfg.rollover && cur < scroll_lines
6925 ? 0 : (cur + ndents - scroll_lines) % ndents), 0);
6930 if (event.bstate == BUTTON5_PRESSED && ndents
6931 && (cfg.rollover || (cur != ndents - 1))) {
6932 move_cursor((!cfg.rollover && cur >= ndents - scroll_lines)
6933 ? (ndents - 1) : ((cur + scroll_lines) % ndents), 0);
6938 /* Toggle filter mode on left click on last 2 lines */
6939 if (event.y >= xlines - 2 && event.bstate == BUTTON1_PRESSED) {
6941 cfg.filtermode ^= 1;
6942 if (cfg.filtermode) {
6947 /* Start watching the directory */
6954 /* Handle clicking on a file */
6955 if (event.y >= 2 && event.y <= ndents + 1 &&
6956 (event.bstate == BUTTON1_PRESSED ||
6957 event.bstate == BUTTON3_PRESSED)) {
6958 r = curscroll + (event.y - 2);
6962 else if ((event.bstate == BUTTON1_PRESSED) && !g_state.fifomode)
6963 notify_fifo(TRUE); /* Send clicked path to NNN_FIFO */
6965 /* Handle right click selection */
6966 if (event.bstate == BUTTON3_PRESSED) {
6974 #if defined(CLOCK_MONOTONIC_RAW)
6975 CLOCK_MONOTONIC_RAW,
6976 #elif defined(CLOCK_MONOTONIC)
6981 &mousetimings[currentmouse]);
6982 mousedent[currentmouse] = cur;
6984 /* Single click just selects, double click falls through to SEL_OPEN */
6985 if ((mousedent[0] != mousedent[1]) ||
6986 (((_ABSSUB(mousetimings[0].tv_sec, mousetimings[1].tv_sec) << 30)
6987 + (_ABSSUB(mousetimings[0].tv_nsec, mousetimings[1].tv_nsec)))
6988 > DBLCLK_INTERVAL_NS))
6991 mousetimings[currentmouse].tv_sec = 0;
6992 mousedent[currentmouse] = -1;
6995 if (cfg.filtermode || filterset())
7002 case SEL_NAV_IN: // fallthrough
7004 /* Cannot descend in empty directories */
7007 g_state.selbm = g_state.runplugin = 0;
7011 pent = &pdents[cur];
7012 if (!g_state.selbm || !(S_ISLNK(pent->mode) &&
7013 realpath(pent->name, newpath) &&
7014 xstrsncpy(path, lastdir, PATH_MAX)))
7015 mkpath(path, pent->name, newpath);
7019 /* Visit directory */
7020 if (pent->flags & DIR_OR_DIRLNK) {
7021 if (chdir(newpath) == -1) {
7026 cdprep(lastdir, lastname, path, newpath) ? (presel = FILTER) : (watch = TRUE);
7030 /* Cannot use stale data in entry, file may be missing by now */
7031 if (stat(newpath, &sb) == -1) {
7035 DPRINTF_U(sb.st_mode);
7037 /* Do not open non-regular files */
7038 if (!S_ISREG(sb.st_mode)) {
7039 printwait(messages[MSG_UNSUPPORTED], &presel);
7043 /* Handle plugin selection mode */
7044 if (g_state.runplugin) {
7045 g_state.runplugin = 0;
7046 /* Must be in plugin dir and same context to select plugin */
7047 if ((g_state.runctx == cfg.curctx) && !strcmp(path, plgpath)) {
7048 endselection(FALSE);
7049 /* Copy path so we can return back to earlier dir */
7050 xstrsncpy(path, lastdir, PATH_MAX);
7053 if (chdir(path) == -1
7054 || !run_plugin(&path, pent->name, runfile, &lastname, &lastdir)) {
7055 DPRINTF_S("plugin failed!");
7059 return EXIT_SUCCESS;
7062 xstrsncpy(lastname, runfile, NAME_MAX + 1);
7071 if (g_state.fifomode && (sel == SEL_OPEN)) {
7072 send_to_explorer(&presel); /* Write selection to explorer fifo */
7076 /* If opened as vim plugin and Enter/^M pressed, pick */
7077 if (g_state.picker && (sel == SEL_OPEN)) {
7078 if (nselected == 0) /* Pick if none selected */
7079 appendfpath(newpath, mkpath(path, pent->name, newpath));
7080 return EXIT_SUCCESS;
7083 if (sel == SEL_NAV_IN) {
7084 /* If in listing dir, go to target on `l` or Right on symlink */
7085 if (listpath && S_ISLNK(pent->mode)
7086 && is_prefix(path, listpath, xstrlen(listpath))) {
7087 if (!realpath(pent->name, newpath)) {
7094 if (chdir(newpath) == -1) {
7099 cdprep(lastdir, NULL, path, newpath)
7100 ? (presel = FILTER) : (watch = TRUE);
7101 xstrsncpy(lastname, pent->name, NAME_MAX + 1);
7105 /* Open file disabled on right arrow or `l` */
7111 printwait(messages[MSG_EMPTY_FILE], &presel);
7116 #ifdef FILE_MIME_OPTS
7117 && get_output("file", FILE_MIME_OPTS, newpath, -1, FALSE)
7118 && is_prefix(g_buf, "text/", 5)
7120 /* no MIME option; guess from description instead */
7121 && get_output("file", "-bL", newpath, -1, FALSE)
7122 && strstr(g_buf, "text")
7125 spawn(editor, newpath, NULL, NULL, F_CLI);
7126 if (cfg.filtermode) {
7133 /* Get the extension for regex match */
7134 tmp = xextension(pent->name, pent->nlen - 1);
7136 if (tmp && !pcre_exec(archive_pcre, NULL, tmp,
7137 pent->nlen - (tmp - pent->name) - 1, 0, 0, NULL, 0)) {
7139 if (tmp && !regexec(&archive_re, tmp, 0, NULL, 0)) {
7141 r = get_input(messages[MSG_ARCHIVE_OPTS]);
7144 if (r == 'l' || r == 'x') {
7145 mkpath(path, pent->name, newpath);
7146 if (!handle_archive(newpath, r)) {
7156 if ((r == 'm') && !archive_mount(newpath)) {
7161 if (r == 'x' || r == 'm') {
7163 set_smart_ctx('+', newpath, &path,
7164 ndents ? pdents[cur].name : NULL,
7165 &lastname, &lastdir);
7173 printwait(messages[MSG_INVALID_KEY], &presel);
7178 /* Invoke desktop opener as last resort */
7179 spawn(opener, newpath, NULL, NULL, opener_flags);
7181 /* Move cursor to the next entry if not the last entry */
7182 if (g_state.autonext && cur != ndents - 1)
7183 move_cursor((cur + 1) % ndents, 0);
7184 if (cfg.filtermode) {
7189 case SEL_NEXT: // fallthrough
7190 case SEL_PREV: // fallthrough
7191 case SEL_PGDN: // fallthrough
7192 case SEL_CTRL_D: // fallthrough
7193 case SEL_PGUP: // fallthrough
7194 case SEL_CTRL_U: // fallthrough
7195 case SEL_HOME: // fallthrough
7196 case SEL_END: // fallthrough
7197 case SEL_FIRST: // fallthrough
7201 handle_screen_move(sel);
7204 case SEL_CDHOME: // fallthrough
7205 case SEL_CDBEGIN: // fallthrough
7206 case SEL_CDLAST: // fallthrough
7208 dir = (sel == SEL_CDHOME) ? home
7209 : ((sel == SEL_CDBEGIN) ? ipath
7210 : ((sel == SEL_CDLAST) ? lastdir
7211 : "/" /* SEL_CDROOT */));
7213 if (!dir || !*dir) {
7214 printwait(messages[MSG_NOT_SET], &presel);
7219 if (strcmp(path, dir) == 0) {
7225 dir = lastdir; /* Go to last dir on home/root key repeat */
7228 if (chdir(dir) == -1) {
7233 /* SEL_CDLAST: dir pointing to lastdir */
7234 xstrsncpy(newpath, dir, PATH_MAX); // fallthrough
7236 if (sel == SEL_BMOPEN) {
7237 r = (int)handle_bookmark(mark, newpath);
7239 printwait(messages[r], &presel);
7243 if (g_state.selbm == 1) /* Allow filtering in bookmarks directory */
7245 if (strcmp(path, newpath) == 0)
7249 /* In list mode, retain the last file name to highlight it, if possible */
7250 cdprep(lastdir, listpath && sel == SEL_CDLAST ? NULL : lastname, path, newpath)
7251 ? (presel = FILTER) : (watch = TRUE);
7254 if ((sel == SEL_REMOTE) && !remote_mount(newpath)) {
7259 set_smart_ctx('+', newpath, &path,
7260 ndents ? pdents[cur].name : NULL, &lastname, &lastdir);
7263 case SEL_CYCLE: // fallthrough
7264 case SEL_CYCLER: // fallthrough
7265 case SEL_CTX1: // fallthrough
7266 case SEL_CTX2: // fallthrough
7267 case SEL_CTX3: // fallthrough
7275 r = handle_context_switch(sel);
7278 savecurctx(path, ndents ? pdents[cur].name : NULL, r);
7280 /* Reset the pointers */
7281 path = g_ctx[r].c_path;
7282 lastdir = g_ctx[r].c_last;
7283 lastname = g_ctx[r].c_name;
7284 tmp = g_ctx[r].c_fltr;
7286 if (cfg.filtermode || ((tmp[0] == FILTER || tmp[0] == RFILTER) && tmp[1]))
7294 mark = xstrdup(path);
7295 printwait(mark, &presel);
7298 add_bookmark(path, newpath, &presel);
7301 /* Unwatch dir if we are still in a filtered view */
7302 #ifdef LINUX_INOTIFY
7303 if (inotify_wd >= 0) {
7304 inotify_rm_watch(inotify_fd, inotify_wd);
7307 #elif defined(BSD_KQUEUE)
7308 if (event_fd >= 0) {
7312 #elif defined(HAIKU_NM)
7313 if (haiku_nm_active) {
7314 haiku_stop_watch(haiku_hnd);
7315 haiku_nm_active = FALSE;
7318 presel = filterentries(path, lastname);
7319 if (presel == ESC) {
7323 if (presel == FILTER) { /* Refresh dir and filter again */
7328 case SEL_MFLTR: // fallthrough
7329 case SEL_HIDDEN: // fallthrough
7330 case SEL_DETAIL: // fallthrough
7334 cfg.filtermode ^= 1;
7335 if (cfg.filtermode) {
7341 watch = TRUE; // fallthrough
7343 if (sel == SEL_HIDDEN) {
7344 cfg.showhidden ^= 1;
7353 cfg.showdetail ^= 1;
7356 default: /* SEL_SORT */
7357 r = set_sort_flags(get_input(messages[MSG_ORDER]));
7359 printwait(messages[MSG_INVALID_KEY], &presel);
7364 if (cfg.filtermode || filterset())
7370 if (r == 'd' || r == 'a') {
7375 ENTSORT(pdents, ndents, entrycmpfn);
7376 move_cursor(ndents ? dentfind(lastname, ndents) : 0, 0);
7379 case SEL_STATS: // fallthrough
7382 tmp = (listpath && xstrcmp(path, listpath) == 0) ? listroot : path;
7383 mkpath(tmp, pdents[cur].name, newpath);
7385 if ((sel == SEL_STATS && !show_stats(newpath))
7386 || (lstat(newpath, &sb) == -1)
7387 || (sel == SEL_CHMODX && !xchmod(newpath, sb.st_mode))) {
7392 if (sel == SEL_CHMODX)
7393 pdents[cur].mode ^= 0111;
7396 case SEL_REDRAW: // fallthrough
7397 case SEL_RENAMEMUL: // fallthrough
7398 case SEL_HELP: // fallthrough
7399 case SEL_AUTONEXT: // fallthrough
7400 case SEL_EDIT: // fallthrough
7403 bool refresh = FALSE;
7406 mkpath(path, pdents[cur].name, newpath);
7407 else if (sel == SEL_EDIT) /* Avoid trying to edit a non-existing file */
7416 setenv("NNN_INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
7417 setenv("NNN_PREFER_SELECTION", xitoa(cfg.prefersel), 1);
7418 setenv("NNN_LIST", listpath ? listroot : "", 1);
7420 if (!(getutil(utils[UTIL_BASH])
7421 && plugscript(utils[UTIL_NMV], F_CLI))
7426 printwait(messages[MSG_FAILED], &presel);
7433 show_help(path); // fallthrough
7435 if (sel == SEL_AUTONEXT)
7436 g_state.autonext ^= 1;
7442 if (!(g_state.picker || g_state.fifomode))
7443 spawn(editor, newpath, NULL, NULL, F_CLI);
7445 default: /* SEL_LOCK */
7450 /* In case of successful operation, reload contents */
7452 /* Continue in type-to-nav mode, if enabled */
7453 if ((cfg.filtermode || filterset()) && !refresh) {
7460 /* Repopulate as directory content may have changed */
7469 if (g_state.rangesel)
7470 g_state.rangesel = 0;
7472 /* Toggle selection status */
7473 pdents[cur].flags ^= FILE_SELECTED;
7475 if (pdents[cur].flags & FILE_SELECTED) {
7477 appendfpath(newpath, mkpath(path, pdents[cur].name, newpath));
7478 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
7481 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
7486 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7493 /* move cursor to the next entry if this is not the last entry */
7494 if (!g_state.stayonsel && (cur != ndents - 1))
7495 move_cursor((cur + 1) % ndents, 0);
7502 g_state.rangesel ^= 1;
7504 if (stat(path, &sb) == -1) {
7509 if (g_state.rangesel) { /* Range selection started */
7515 if (inode != sb.st_ino) {
7516 printwait(messages[MSG_DIR_CHANGED], &presel);
7520 if (cur < selstartid) {
7521 selendid = selstartid;
7526 /* Clear selection on repeat on same file */
7527 if (selstartid == selendid) {
7532 case SEL_SELALL: // fallthrough
7534 if (sel == SEL_SELALL || sel == SEL_SELINV) {
7539 if (g_state.rangesel)
7540 g_state.rangesel = 0;
7543 selendid = ndents - 1;
7546 if ((nselected > LARGESEL) || (nselected && (ndents > LARGESEL))) {
7547 printmsg("processing...");
7551 r = scanselforpath(path, TRUE); /* Get path length suffixed by '/' */
7552 ((sel == SEL_SELINV) && findselpos)
7553 ? invertselbuf(r) : addtoselbuf(r, selstartid, selendid);
7557 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7561 r = editselection();
7563 r = !r ? MSG_0_SELECTED : MSG_FAILED;
7564 printwait(messages[r], &presel);
7568 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7570 cfg.filtermode ? presel = FILTER : statusbar(path);
7573 case SEL_CP: // fallthrough
7574 case SEL_MV: // fallthrough
7575 case SEL_CPMVAS: // fallthrough
7578 if (sel == SEL_RM) {
7579 r = get_cur_or_sel();
7586 tmp = (listpath && xstrcmp(path, listpath) == 0)
7588 mkpath(tmp, pdents[cur].name, newpath);
7592 xrmfromsel(tmp, newpath);
7594 copynextname(lastname);
7596 if (cfg.filtermode || filterset())
7603 (nselected == 1 && (sel == SEL_CP || sel == SEL_MV))
7604 ? mkpath(path, xbasename(pselbuf), newpath)
7605 : (newpath[0] = '\0');
7609 if (!cpmvrm_selection(sel, path)) {
7619 /* Show notification on operation complete */
7621 plugscript(utils[UTIL_NTFY], F_NOWAIT | F_NOTRACE);
7624 if (newpath[0] && !access(newpath, F_OK))
7625 xstrsncpy(lastname, xbasename(newpath), NAME_MAX+1);
7631 case SEL_ARCHIVE: // fallthrough
7632 case SEL_OPENWITH: // fallthrough
7633 case SEL_NEW: // fallthrough
7639 if (!ndents && (sel == SEL_OPENWITH || sel == SEL_RENAME))
7642 if (sel != SEL_OPENWITH)
7647 r = get_cur_or_sel();
7661 tmp = pdents[cur].name;
7663 tmp = xreadline(tmp, messages[MSG_ARCHIVE_NAME]);
7667 if (g_state.picker) {
7669 tmp = xreadline(NULL, messages[MSG_OPEN_WITH]);
7672 tmp = getreadline(messages[MSG_OPEN_WITH]);
7677 r = get_input(messages[MSG_NEW_OPTS]);
7683 tmp = g_ctx[0].c_name;
7687 if (r == 'f' || r == 'd')
7688 tmp = xreadline(tmp, messages[MSG_NEW_PATH]);
7689 else if (r == 's' || r == 'h')
7690 tmp = xreadline(NULL,
7691 messages[nselected <= 1 ? MSG_NEW_PATH : MSG_LINK_PREFIX]);
7695 default: /* SEL_RENAME */
7696 tmp = xreadline(pdents[cur].name, "");
7700 if (!tmp || !*tmp || is_bad_len_or_dir(tmp))
7705 if (r == 'c' && strcmp(tmp, pdents[cur].name) == 0)
7706 continue; /* Cannot overwrite the hovered file */
7708 tmp = abspath(tmp, NULL, newpath);
7711 if (access(tmp, F_OK) == 0) {
7712 if (!xconfirm(get_input(messages[MSG_OVERWRITE]))) {
7718 (r == 's') ? archive_selection(get_archive_cmd(tmp), tmp)
7719 : spawn(get_archive_cmd(tmp), tmp, pdents[cur].name,
7720 NULL, F_CLI | F_CONFIRM);
7722 if (tmp && (access(tmp, F_OK) == 0)) { /* File created */
7724 clearselection(); /* Archive operation complete */
7726 /* Check if any entry is created in the current directory */
7727 tmp = get_cwd_entry(path, tmp, &len);
7729 xstrsncpy(lastname, tmp, len + 1);
7730 clearfilter(); /* Archive name may not match */
7731 } if (cfg.filtermode)
7738 handle_openwith(path, pdents[cur].name, newpath, tmp);
7740 cfg.filtermode ? presel = FILTER : statusbar(path);
7745 /* Skip renaming to same name */
7746 if (strcmp(tmp, pdents[cur].name) == 0) {
7747 tmp = xreadline(pdents[cur].name, messages[MSG_COPY_NAME]);
7748 if (!tmp || !tmp[0] || is_bad_len_or_dir(tmp)
7749 || !strcmp(tmp, pdents[cur].name)) {
7750 cfg.filtermode ? presel = FILTER : statusbar(path);
7757 default: /* SEL_NEW */
7761 if (!(r == 's' || r == 'h')) {
7762 tmp = abspath(tmp, NULL, newpath);
7769 /* Check if another file with same name exists */
7770 if (lstat(tmp, &sb) == 0) {
7771 if ((sel == SEL_RENAME) || ((r == 'f') && (S_ISREG(sb.st_mode)))) {
7772 /* Overwrite file with same name? */
7773 if (!xconfirm(get_input(messages[MSG_OVERWRITE])))
7776 /* Do nothing for SEL_NEW if a non-regular entry exists */
7777 printwait(messages[MSG_EXISTS], &presel);
7782 if (sel == SEL_RENAME) {
7783 /* Rename the file */
7785 spawn("cp -rp", pdents[cur].name, tmp, NULL, F_SILENT);
7786 else if (rename(pdents[cur].name, tmp) != 0) {
7791 /* Check if any entry is created in the current directory */
7792 tmp = get_cwd_entry(path, tmp, &len);
7794 xstrsncpy(lastname, tmp, len + 1);
7795 /* Directory must be reloeaded for rename case */
7796 } else { /* SEL_NEW */
7799 /* Check if it's a dir or file */
7800 if (r == 'f' || r == 'd') {
7801 ret = xmktree(tmp, r == 'f' ? FALSE : TRUE);
7802 } else if (r == 's' || r == 'h') {
7803 if (nselected > 1 && tmp[0] == '@' && tmp[1] == '\0')
7805 ret = xlink(tmp, path, (ndents ? pdents[cur].name : NULL), newpath, r);
7814 if (r == 'f' || r == 'd') {
7815 tmp = get_cwd_entry(path, tmp, &len);
7817 xstrsncpy(lastname, tmp, len + 1);
7819 continue; /* No change in directory */
7820 } else if (ndents) {
7832 /* Check if directory is accessible */
7833 if (!xdiraccess(plgpath)) {
7839 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
7840 printkeys(plug, g_buf + r - 1, maxplug);
7842 r = get_input(NULL);
7849 endselection(FALSE);
7850 tmp = get_kv_val(plug, NULL, r, maxplug, NNN_PLUG);
7852 printwait(messages[MSG_INVALID_KEY], &presel);
7856 if (tmp[0] == '-' && tmp[1]) {
7858 r = FALSE; /* Do not refresh dir after completion */
7862 if (!run_plugin(&path, tmp, (ndents ? pdents[cur].name : NULL),
7863 &lastname, &lastdir)) {
7864 printwait(messages[MSG_FAILED], &presel);
7869 return EXIT_SUCCESS;
7874 cfg.filtermode ? presel = FILTER : statusbar(path);
7877 } else { /* 'Return/Enter' enters the plugin directory */
7878 g_state.runplugin ^= 1;
7879 if (!g_state.runplugin) {
7881 * If toggled, and still in the plugin dir,
7882 * switch to original directory
7884 if (strcmp(path, plgpath) == 0) {
7885 xstrsncpy(path, lastdir, PATH_MAX);
7886 xstrsncpy(lastname, runfile, NAME_MAX + 1);
7892 /* Otherwise, initiate choosing plugin again */
7893 g_state.runplugin = 1;
7896 xstrsncpy(lastdir, path, PATH_MAX);
7897 xstrsncpy(path, plgpath, PATH_MAX);
7899 xstrsncpy(runfile, pdents[cur].name, NAME_MAX);
7900 g_state.runctx = cfg.curctx;
7905 if (g_state.runplugin == 1) /* Allow filtering in plugins directory */
7911 case SEL_SHELL: // fallthrough
7912 case SEL_LAUNCH: // fallthrough
7914 r = handle_cmd(sel, newpath);
7916 /* Continue in type-to-nav mode, if enabled */
7926 /* Repopulate as directory content may have changed */
7931 if (!unmount((ndents ? pdents[cur].name : NULL), newpath, &presel, path)) {
7932 if (presel == MSG_ZERO)
7937 /* Dir removed, go to next entry */
7938 copynextname(lastname);
7943 r = get_input(messages[MSG_SSN_OPTS]);
7946 tmp = xreadline(NULL, messages[MSG_SSN_NAME]);
7948 save_session(tmp, &presel);
7949 } else if (r == 'l' || r == 'r') {
7950 if (load_session(NULL, &path, &lastdir, &lastname, r == 'r')) {
7961 cfg.filtermode ? presel = FILTER : statusbar(path);
7964 if (!set_time_type(&presel))
7968 case SEL_QUITCTX: // fallthrough
7969 case SEL_QUITCD: // fallthrough
7972 if (sel == SEL_QUITCTX) {
7973 int ctx = cfg.curctx;
7975 for (r = (ctx - 1) & (CTX_MAX - 1);
7976 (r != ctx) && !g_ctx[r].c_cfg.ctxactive;
7977 r = ((r - 1) & (CTX_MAX - 1))) {
7981 g_ctx[ctx].c_cfg.ctxactive = 0;
7983 /* Switch to next active context */
7984 path = g_ctx[r].c_path;
7985 lastdir = g_ctx[r].c_last;
7986 lastname = g_ctx[r].c_name;
7988 cfg = g_ctx[r].c_cfg;
7994 } else if (!g_state.forcequit) {
7995 for (r = 0; r < CTX_MAX; ++r)
7996 if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
7997 r = get_input(messages[MSG_QUIT_ALL]);
8001 if (!(r == CTX_MAX || xconfirm(r)))
8002 break; // fallthrough
8006 tmp = getenv("NNN_TMPFILE");
8007 if ((sel == SEL_QUITCD) || tmp) {
8008 write_lastdir(path, tmp);
8009 /* ^G is a way to quit picker mode without picking anything */
8010 if ((sel == SEL_QUITCD) && g_state.picker)
8014 if (sel != SEL_QUITERR)
8015 return EXIT_SUCCESS;
8017 if (selbufpos && !g_state.picker) {
8018 /* Pick files to stdout and exit */
8022 return EXIT_SUCCESS;
8025 return EXIT_FAILURE;
8027 if (xlines != LINES || xcols != COLS)
8030 if (idletimeout && idle == idletimeout) {
8031 lock_terminal(); /* Locker */
8037 } /* switch (sel) */
8041 static char *make_tmp_tree(char **paths, ssize_t entries, const char *prefix)
8043 /* tmpdir holds the full path */
8044 /* tmp holds the path without the tmp dir prefix */
8048 ssize_t len = xstrlen(prefix);
8049 char *tmpdir = malloc(PATH_MAX);
8052 DPRINTF_S(strerror(errno));
8056 tmp = tmpdir + tmpfplen - 1;
8057 xstrsncpy(tmpdir, g_tmpfpath, tmpfplen);
8058 xstrsncpy(tmp, "/nnnXXXXXX", 11);
8060 /* Points right after the base tmp dir */
8063 /* handle the case where files are directly under / */
8064 if (!prefix[1] && (prefix[0] == '/'))
8067 if (!mkdtemp(tmpdir)) {
8070 DPRINTF_S(strerror(errno));
8076 for (ssize_t i = 0; i < entries; ++i) {
8080 err = stat(paths[i], &sb);
8081 if (err && errno == ENOENT)
8084 /* Don't copy the common prefix */
8085 xstrsncpy(tmp, paths[i] + len, xstrlen(paths[i]) - len + 1);
8087 /* Get the dir containing the path */
8088 slash = xmemrchr((uchar_t *)tmp, '/', xstrlen(paths[i]) - len);
8092 if (access(tmpdir, F_OK)) /* Create directory if it doesn't exist */
8093 xmktree(tmpdir, TRUE);
8098 if (symlink(paths[i], tmpdir)) {
8099 DPRINTF_S(paths[i]);
8100 DPRINTF_S(strerror(errno));
8104 /* Get the dir in which to start */
8109 static char *load_input(int fd, const char *path)
8111 size_t i, chunk_count = 1, chunk = 512UL * 1024 /* 512 KiB chunk size */, entries = 0;
8112 char *input = malloc(sizeof(char) * chunk), *tmpdir = NULL;
8113 char cwd[PATH_MAX], *next;
8114 size_t offsets[LIST_FILES_MAX];
8115 char **paths = NULL;
8116 ssize_t input_read, total_read = 0, off = 0;
8120 DPRINTF_S(strerror(errno));
8125 if (!getcwd(cwd, PATH_MAX)) {
8130 xstrsncpy(cwd, path, PATH_MAX);
8132 while (chunk_count < LIST_INPUT_MAX / chunk && !msgnum) {
8133 input_read = read(fd, input + total_read, chunk);
8134 if (input_read < 0) {
8138 DPRINTF_S(strerror(errno));
8142 if (input_read == 0)
8145 total_read += input_read;
8147 while (off < total_read) {
8148 next = memchr(input + off, '\0', total_read - off);
8153 if (next - input == off + 1) {
8158 if (entries == LIST_FILES_MAX) {
8159 msgnum = MSG_FILE_LIMIT;
8163 offsets[entries++] = off;
8167 /* We don't need to allocate another chunk */
8168 if (chunk_count > (total_read + chunk - 1) / chunk)
8171 /* We can never need more than one additional chunk */
8173 if (chunk_count > LIST_INPUT_MAX / chunk) {
8174 msgnum = MSG_SIZE_LIMIT;
8178 input = xrealloc(input, chunk_count * chunk);
8183 /* We close fd outside this function. Any extra data is left to the kernel to handle */
8185 if (off != total_read) {
8186 if (entries == LIST_FILES_MAX)
8187 msgnum = MSG_FILE_LIMIT;
8189 offsets[entries++] = off;
8193 DPRINTF_D(total_read);
8194 DPRINTF_D(chunk_count);
8197 msgnum = MSG_0_ENTRIES;
8201 input[total_read] = '\0';
8203 paths = malloc(entries * sizeof(char *));
8207 for (i = 0; i < entries; ++i)
8208 paths[i] = input + offsets[i];
8210 listroot = malloc(sizeof(char) * PATH_MAX);
8215 DPRINTF_S(paths[0]);
8217 for (i = 0; i < entries; ++i) {
8218 if (paths[i][0] == '\n' || selforparent(paths[i])) {
8223 paths[i] = abspath(paths[i], cwd, NULL);
8225 entries = i; // free from the previous entry
8229 DPRINTF_S(paths[i]);
8231 xstrsncpy(g_buf, paths[i], PATH_MAX);
8232 if (!common_prefix(xdirname(g_buf), listroot)) {
8233 entries = i + 1; // free from the current entry
8237 DPRINTF_S(listroot);
8240 DPRINTF_S(listroot);
8243 tmpdir = make_tmp_tree(paths, entries, listroot);
8246 for (i = 0; i < entries; ++i)
8249 if (msgnum) { /* Check if we are past init stage and show msg */
8251 printmsg(messages[msgnum]);
8252 xdelay(XDELAY_INTERVAL_MS << 2);
8254 msg(messages[msgnum]);
8255 usleep(XDELAY_INTERVAL_MS << 2);
8264 static void check_key_collision(void)
8267 bool bitmap[KEY_MAX] = {FALSE};
8269 for (ullong_t i = 0; i < ELEMENTS(bindings); ++i) {
8270 key = bindings[i].sym;
8273 dprintf(STDERR_FILENO, "key collision! [%s]\n", keyname(key));
8279 static void usage(void)
8281 dprintf(STDOUT_FILENO,
8282 "%s: nnn [OPTIONS] [PATH]\n\n"
8283 "The unorthodox terminal file manager.\n\n"
8284 "positional args:\n"
8285 " PATH start dir/file [default: .]\n\n"
8288 " -a auto NNN_FIFO\n"
8290 " -A no dir auto-enter during filter\n"
8291 " -b key open bookmark key (trumps -s/S)\n"
8292 " -B use bsdtar for archives\n"
8293 " -c cli-only NNN_OPENER (trumps -e)\n"
8294 " -C 8-color scheme\n"
8296 " -D dirs in context color\n"
8297 " -e text in $VISUAL/$EDITOR/vi\n"
8298 " -E internal edits in EDITOR\n"
8300 " -f use readline history file\n"
8303 " -F val fifo mode [0:preview 1:explore]\n"
8305 " -g regex filters\n"
8306 " -H show hidden files\n"
8307 " -i show current file info\n"
8308 " -J no auto-advance on selection\n"
8309 " -K detect key collision and exit\n"
8310 " -l val set scroll lines\n"
8311 " -n type-to-nav mode\n"
8312 " -o open files only on Enter\n"
8313 " -p file selection file [-:stdout]\n"
8314 " -P key run plugin key\n"
8315 " -Q no quit confirmation\n"
8316 " -r use advcpmv patched cp, mv\n"
8317 " -R no rollover at edges\n"
8319 " -s name load session by name\n"
8320 " -S persistent session\n"
8322 " -t secs timeout to lock\n"
8323 " -T key sort order [a/d/e/r/s/t/v]\n"
8324 " -u use selection (no prompt)\n"
8326 " -U show user and group\n"
8328 " -V show version\n"
8330 " -x notis, selection sync, xterm title\n"
8333 "v%s\n%s\n", __func__, VERSION, GENERAL_INFO);
8336 static bool setup_config(void)
8339 char *xdgcfg = getenv("XDG_CONFIG_HOME");
8342 /* Set up configuration file paths */
8343 if (xdgcfg && xdgcfg[0]) {
8345 if (tilde_is_home(xdgcfg)) {
8346 r = xstrsncpy(g_buf, home, PATH_MAX);
8347 xstrsncpy(g_buf + r - 1, xdgcfg + 1, PATH_MAX);
8352 if (!xdiraccess(xdgcfg)) {
8357 len = xstrlen(xdgcfg) + xstrlen("/nnn/bookmarks") + 1;
8362 len = xstrlen(home) + xstrlen("/.config/nnn/bookmarks") + 1;
8364 cfgpath = (char *)malloc(len);
8365 plgpath = (char *)malloc(len);
8366 if (!cfgpath || !plgpath) {
8372 xstrsncpy(cfgpath, xdgcfg, len);
8373 r = len - xstrlen("/nnn/bookmarks");
8375 r = xstrsncpy(cfgpath, home, len);
8377 /* Create ~/.config */
8378 xstrsncpy(cfgpath + r - 1, "/.config", len - r);
8380 r += 8; /* length of "/.config" */
8383 /* Create ~/.config/nnn */
8384 xstrsncpy(cfgpath + r - 1, "/nnn", len - r);
8387 /* Create bookmarks, sessions, mounts and plugins directories */
8388 for (r = 0; r < ELEMENTS(toks); ++r) {
8389 mkpath(cfgpath, toks[r], plgpath);
8390 /* The dirs are created on first run, check if they already exist */
8391 if (access(plgpath, F_OK) && !xmktree(plgpath, TRUE)) {
8398 /* Set selection file path */
8399 if (!g_state.picker) {
8400 char *env_sel = xgetenv(env_cfg[NNN_SEL], NULL);
8402 selpath = env_sel ? xstrdup(env_sel)
8403 : (char *)malloc(len + 3); /* Length of "/.config/nnn/.selection" */
8411 r = xstrsncpy(selpath, cfgpath, len + 3);
8412 xstrsncpy(selpath + r - 1, "/.selection", 12);
8420 static bool set_tmp_path(void)
8423 char *path = xdiraccess(tmp) ? tmp : getenv("TMPDIR");
8430 tmpfplen = (uchar_t)xstrsncpy(g_tmpfpath, path, TMP_LEN_MAX);
8431 DPRINTF_S(g_tmpfpath);
8432 DPRINTF_U(tmpfplen);
8437 static void cleanup(void)
8440 if (cfg.x11 && !g_state.picker) {
8441 printf("\033[23;0t"); /* reset terminal window title */
8457 if (g_state.autofifo)
8460 if (g_state.pluginit)
8467 int main(int argc, char *argv[])
8470 char *session = NULL;
8471 int fd, opt, sort = 0, pkey = '\0'; /* Plugin key */
8474 char *middle_click_env = xgetenv(env_cfg[NNN_MCLICK], "\0");
8476 middle_click_key = (middle_click_env[0] == '^' && middle_click_env[1])
8477 ? CONTROL(middle_click_env[1])
8478 : (uchar_t)middle_click_env[0];
8481 const char * const env_opts = xgetenv(env_cfg[NNN_OPTS], NULL);
8482 int env_opts_id = env_opts ? (int)xstrlen(env_opts) : -1;
8484 bool rlhist = FALSE;
8487 while ((opt = (env_opts_id > 0
8488 ? env_opts[--env_opts_id]
8489 : getopt(argc, argv, "aAb:BcCdDeEfF:gHiJKl:nop:P:QrRs:St:T:uUVxh"))) != -1) {
8493 g_state.autofifo = 1;
8500 if (env_opts_id < 0)
8504 g_state.usebsdtar = 1;
8510 g_state.oldcolor = 1;
8531 if (env_opts_id < 0) {
8533 if ((fd < 0) || (fd > 1))
8534 return EXIT_FAILURE;
8535 g_state.fifomode = fd;
8541 filterfn = &visible_re;
8550 g_state.stayonsel = 1;
8553 check_key_collision();
8554 return EXIT_SUCCESS;
8556 if (env_opts_id < 0)
8557 scroll_lines = atoi(optarg);
8566 if (env_opts_id >= 0)
8570 if (!(optarg[0] == '-' && optarg[1] == '\0')) {
8571 fd = open(optarg, O_WRONLY | O_CREAT, 0600);
8574 return EXIT_FAILURE;
8578 selpath = abspath(optarg, NULL, NULL);
8583 if (env_opts_id < 0 && !optarg[1])
8584 pkey = (uchar_t)optarg[0];
8587 g_state.forcequit = 1;
8591 cp[2] = cp[5] = mv[2] = mv[5] = 'g'; /* cp -iRp -> cpg -giRp */
8592 cp[4] = mv[4] = '-';
8600 if (env_opts_id < 0)
8604 g_state.prstssn = 1;
8605 if (!session) /* Support named persistent sessions */
8610 if (env_opts_id < 0)
8611 idletimeout = atoi(optarg);
8614 if (env_opts_id < 0)
8615 sort = (uchar_t)optarg[0];
8624 dprintf(STDOUT_FILENO, "%s\n", VERSION);
8625 return EXIT_SUCCESS;
8631 return EXIT_SUCCESS;
8634 return EXIT_FAILURE;
8636 if (env_opts_id == 0)
8645 /* Prefix for temporary files */
8646 if (!set_tmp_path())
8647 return EXIT_FAILURE;
8651 /* Check if we are in path list mode */
8652 if (!isatty(STDIN_FILENO)) {
8653 /* This is the same as listpath */
8654 initpath = load_input(STDIN_FILENO, NULL);
8656 return EXIT_FAILURE;
8658 /* We return to tty */
8659 if (!isatty(STDOUT_FILENO)) {
8660 fd = open(ctermid(NULL), O_RDONLY, 0400);
8661 dup2(fd, STDIN_FILENO);
8664 dup2(STDOUT_FILENO, STDIN_FILENO);
8670 home = getenv("HOME");
8673 return EXIT_FAILURE;
8676 homelen = (uchar_t)xstrlen(home);
8678 if (!setup_config())
8679 return EXIT_FAILURE;
8681 /* Get custom opener, if set */
8682 opener = xgetenv(env_cfg[NNN_OPENER], utils[UTIL_OPENER]);
8685 /* Parse bookmarks string */
8686 if (!parsekvpair(&bookmark, &bmstr, NNN_BMS, &maxbm)) {
8687 msg(env_cfg[NNN_BMS]);
8688 return EXIT_FAILURE;
8691 /* Parse plugins string */
8692 if (!parsekvpair(&plug, &pluginstr, NNN_PLUG, &maxplug)) {
8693 msg(env_cfg[NNN_PLUG]);
8694 return EXIT_FAILURE;
8697 /* Parse order string */
8698 if (!parsekvpair(&order, &orderstr, NNN_ORDER, &maxorder)) {
8699 msg(env_cfg[NNN_ORDER]);
8700 return EXIT_FAILURE;
8704 if (arg) { /* Open a bookmark directly */
8705 if (!arg[1]) /* Bookmarks keys are single char */
8706 initpath = get_kv_val(bookmark, NULL, *arg, maxbm, NNN_BMS);
8709 msg(messages[MSG_INVALID_KEY]);
8710 return EXIT_FAILURE;
8715 } else if (argc == optind) {
8716 /* Start in the current directory */
8717 char *startpath = getenv("PWD");
8719 initpath = startpath ? xstrdup(startpath) : getcwd(NULL, 0);
8722 } else { /* Open a file */
8725 size_t len = xstrlen(arg);
8727 if (len > 7 && is_prefix(arg, "file://", 7)) {
8731 initpath = abspath(arg, NULL, NULL);
8732 DPRINTF_S(initpath);
8735 return EXIT_FAILURE;
8738 /* If the file is hidden, enable hidden option */
8739 if (*xbasename(initpath) == '.')
8743 * If nnn is set as the file manager, applications may try to open
8744 * files by invoking nnn. In that case pass the file path to the
8745 * desktop opener and exit.
8749 if (stat(initpath, &sb) == -1) {
8750 bool dir = (arg[len - 1] == '/');
8753 arg = xbasename(initpath);
8754 initpath = xdirname(initpath);
8756 pkey = CREATE_NEW_KEY; /* Override plugin key */
8757 g_state.initfile = 1;
8759 if (dir || (arg != initpath)) { /* We have a directory */
8760 if (!xdiraccess(initpath) && !xmktree(initpath, TRUE)) {
8761 xerror(); /* Fail if directory cannot be created */
8762 return EXIT_FAILURE;
8764 if (!dir) /* Restore the complete path */
8767 } else if (!S_ISDIR(sb.st_mode))
8768 g_state.initfile = 1;
8775 /* Set archive handling (enveditor used as tmp var) */
8776 enveditor = getenv(env_cfg[NNN_ARCHIVE]);
8778 if (setfilter(&archive_pcre, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8780 if (setfilter(&archive_re, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8782 msg(messages[MSG_INVALID_REG]);
8783 return EXIT_FAILURE;
8786 /* An all-CLI opener overrides option -e) */
8790 /* Get VISUAL/EDITOR */
8791 enveditor = xgetenv(envs[ENV_EDITOR], utils[UTIL_VI]);
8792 editor = xgetenv(envs[ENV_VISUAL], enveditor);
8793 DPRINTF_S(getenv(envs[ENV_VISUAL]));
8794 DPRINTF_S(getenv(envs[ENV_EDITOR]));
8798 pager = xgetenv(envs[ENV_PAGER], utils[UTIL_LESS]);
8802 shell = xgetenv(envs[ENV_SHELL], utils[UTIL_SH]);
8805 DPRINTF_S(getenv("PWD"));
8809 if (g_state.autofifo) {
8810 g_tmpfpath[tmpfplen - 1] = '\0';
8812 size_t r = mkpath(g_tmpfpath, "nnn-fifo.", g_buf);
8814 xstrsncpy(g_buf + r - 1, xitoa(getpid()), PATH_MAX - r);
8815 setenv("NNN_FIFO", g_buf, TRUE);
8818 fifopath = xgetenv("NNN_FIFO", NULL);
8820 if (mkfifo(fifopath, 0600) != 0 && !(errno == EEXIST && access(fifopath, W_OK) == 0)) {
8822 return EXIT_FAILURE;
8825 sigaction(SIGPIPE, &(struct sigaction){.sa_handler = SIG_IGN}, NULL);
8829 #ifdef LINUX_INOTIFY
8830 /* Initialize inotify */
8831 inotify_fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
8832 if (inotify_fd < 0) {
8834 return EXIT_FAILURE;
8836 #elif defined(BSD_KQUEUE)
8840 return EXIT_FAILURE;
8842 #elif defined(HAIKU_NM)
8843 haiku_hnd = haiku_init_nm();
8846 return EXIT_FAILURE;
8850 /* Configure trash preference */
8851 opt = xgetenv_val(env_cfg[NNN_TRASH]);
8852 if (opt && opt <= 2)
8853 g_state.trash = opt;
8855 /* Ignore/handle certain signals */
8856 struct sigaction act = {.sa_handler = sigint_handler};
8858 if (sigaction(SIGINT, &act, NULL) < 0) {
8860 return EXIT_FAILURE;
8863 act.sa_handler = clean_exit_sighandler;
8865 if (sigaction(SIGTERM, &act, NULL) < 0 || sigaction(SIGHUP, &act, NULL) < 0) {
8867 return EXIT_FAILURE;
8870 act.sa_handler = SIG_IGN;
8872 if (sigaction(SIGQUIT, &act, NULL) < 0) {
8874 return EXIT_FAILURE;
8879 setlocale(LC_ALL, "");
8881 tables = pcre_maketables();
8886 #if RL_READLINE_VERSION >= 0x0603
8887 /* readline would overwrite the WINCH signal hook */
8888 rl_change_environment = 0;
8890 /* Bind TAB to cycling */
8891 rl_variable_bind("completion-ignore-case", "on");
8893 rl_bind_key('\t', rl_menu_complete);
8895 rl_bind_key('\t', rl_complete);
8898 mkpath(cfgpath, ".history", g_buf);
8899 read_history(g_buf);
8904 if (cfg.x11 && !g_state.picker) {
8905 /* Save terminal window title */
8906 printf("\033[22;0t");
8908 gethostname(hostname, sizeof(hostname));
8909 hostname[sizeof(hostname) - 1] = '\0';
8914 if (!initcurses(&mask))
8916 if (!initcurses(NULL))
8918 return EXIT_FAILURE;
8921 set_sort_flags(sort);
8923 opt = browse(initpath, session, pkey);
8926 if (session && g_state.prstssn)
8927 save_session(session, NULL);
8931 mousemask(mask, NULL);
8938 mkpath(cfgpath, ".history", g_buf);
8939 write_history(g_buf);
8943 if (g_state.picker) {
8945 fd = selpath ? open(selpath, O_WRONLY | O_CREAT | O_TRUNC, 0600) : STDOUT_FILENO;
8946 if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
8955 /* Remove tmp dir in list mode */
8958 /* Free the regex */
8960 pcre_free(archive_pcre);
8962 regfree(&archive_re);
8965 /* Free the selection buffer */
8968 #ifdef LINUX_INOTIFY
8969 /* Shutdown inotify */
8970 if (inotify_wd >= 0)
8971 inotify_rm_watch(inotify_fd, inotify_wd);
8973 #elif defined(BSD_KQUEUE)
8977 #elif defined(HAIKU_NM)
8978 haiku_close_nm(haiku_hnd);
8982 if (!g_state.fifomode)