4 * Copyright (C) 2014-2016, Lazaros Koromilas <lostd@2f30.org>
5 * Copyright (C) 2014-2016, Dimitris Papastamos <sin@2f30.org>
6 * Copyright (C) 2016-2023, Arun Prakash Jana <engineerarun@gmail.com>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
12 * * Redistributions of source code must retain the above copyright notice, this
13 * list of conditions and the following disclaimer.
15 * * Redistributions in binary form must reproduce the above copyright notice,
16 * this list of conditions and the following disclaimer in the documentation
17 * and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #define _FILE_OFFSET_BITS 64 /* Support large files on 32-bit glibc */
33 #if defined(__linux__) || defined(MINGW) || defined(__MINGW32__) \
34 || defined(__MINGW64__) || defined(__CYGWIN__)
38 #if defined(__linux__)
39 #include <sys/inotify.h>
42 #if !defined(__GLIBC__)
43 #include <sys/types.h>
46 #include <sys/resource.h>
48 #include <sys/statvfs.h>
49 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
50 #include <sys/types.h>
51 #include <sys/event.h>
54 #elif defined(__HAIKU__)
55 #include "../misc/haiku/haiku_interop.h"
58 #include <sys/sysmacros.h>
62 #ifdef __linux__ /* Fix failure due to mvaddnwstr() */
63 #ifndef NCURSES_WIDECHAR
64 #define NCURSES_WIDECHAR 1
66 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
67 || defined(__APPLE__) || defined(__sun)
68 #ifndef _XOPEN_SOURCE_EXTENDED
69 #define _XOPEN_SOURCE_EXTENDED
72 #ifndef __USE_XOPEN /* Fix wcswidth() failure, ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
87 #include <readline/history.h>
88 #include <readline/readline.h>
103 #include <stdalign.h>
104 #ifndef __USE_XOPEN_EXTENDED
105 #define __USE_XOPEN_EXTENDED 1
111 #ifdef MACOS_BELOW_1012
112 #include "../misc/macos-legacy/mach_gettime.h"
115 #if !defined(alloca) && defined(__GNUC__)
117 * GCC doesn't expand alloca() to __builtin_alloca() in standards mode
118 * (-std=...) and not all standard libraries do or supply it, e.g.
119 * NetBSD/arm64 so explicitly use the builtin.
121 #define alloca(size) __builtin_alloca(size)
127 #if defined(ICONS_IN_TERM) || defined(NERD) || defined(EMOJI)
128 #define ICONS_ENABLED
129 #include ICONS_INCLUDE
130 #include "icons-hash.c"
138 /* Macro definitions */
139 #define VERSION "4.8"
140 #define GENERAL_INFO "BSD 2-Clause\nhttps://github.com/jarun/nnn"
143 #define SESSIONS_VERSION 1
147 #define S_BLKSIZE 512 /* S_BLKSIZE is missing on Android NDK (Termux) */
151 * NAME_MAX and PATH_MAX may not exist, e.g. with dirent.c_name being a
152 * flexible array on Illumos. Use somewhat accommodating fallback values.
159 #define PATH_MAX 4096
162 #define _ABSSUB(N, M) (((N) <= (M)) ? ((M) - (N)) : ((N) - (M)))
163 #define ELEMENTS(x) (sizeof(x) / sizeof(*(x)))
165 #define MIN(x, y) ((x) < (y) ? (x) : (y))
167 #define MAX(x, y) ((x) > (y) ? (x) : (y))
168 #define ISODD(x) ((x) & 1)
169 #define ISBLANK(x) ((x) == ' ' || (x) == '\t')
170 #define TOUPPER(ch) (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
171 #define TOLOWER(ch) (((ch) >= 'A' && (ch) <= 'Z') ? ((ch) - 'A' + 'a') : (ch))
172 #define ISUPPER_(ch) ((ch) >= 'A' && (ch) <= 'Z')
173 #define ISLOWER_(ch) ((ch) >= 'a' && (ch) <= 'z')
174 #define CMD_LEN_MAX (PATH_MAX + ((NAME_MAX + 1) << 1))
175 #define ALIGN_UP(x, A) ((((x) + (A) - 1) / (A)) * (A))
176 #define READLINE_MAX 256
182 #define PROMPT ">>> "
184 #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
185 #define NAMEBUF_INCR 0x800 /* 64 dir entries at once, avg. 32 chars per file name = 64*32B = 2KB */
186 #define DESCRIPTOR_LEN 32
187 #define _ALIGNMENT 0x10 /* 16-byte alignment */
188 #define _ALIGNMENT_MASK 0xF
189 #define TMP_LEN_MAX 64
190 #define DOT_FILTER_LEN 7
191 #define ASCII_MAX 128
192 #define EXEC_ARGS_MAX 10
193 #define LIST_FILES_MAX (1 << 14) /* Support listing 16K files */
194 #define LIST_INPUT_MAX ((size_t)LIST_FILES_MAX * PATH_MAX)
196 #define COLOR_256 256
197 #define CREATE_NEW_KEY (-1)
200 #define DBLCLK_INTERVAL_NS (400000000)
201 #define XDELAY_INTERVAL_MS (350000) /* 350 ms delay */
210 /* BSDs or Solaris or SunOS */
211 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) || defined(sun) || defined(__sun)
218 /* Large selection threshold */
220 #define LARGESEL 1000
223 #define MIN_DISPLAY_COL (CTX_MAX * 2)
224 #define ARCHIVE_CMD_LEN 16
225 #define BLK_SHIFT_512 9
227 /* Detect hardlinks in du */
228 #define HASH_BITS (0xFFFFFF)
229 #define HASH_OCTETS (HASH_BITS >> 6) /* 2^6 = 64 */
232 #define DIR_OR_DIRLNK 0x01
233 #define HARD_LINK 0x02
234 #define SYM_ORPHAN 0x04
235 #define FILE_MISSING 0x08
236 #define FILE_SELECTED 0x10
237 #define FILE_SCANNED 0x20
238 #define FILE_YOUNG 0x40
240 /* Macros to define process spawn behaviour as flags */
241 #define F_NONE 0x00 /* no flag set */
242 #define F_MULTI 0x01 /* first arg can be combination of args; to be used with F_NORMAL */
243 #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
244 #define F_NOTRACE 0x04 /* suppress stdout and stderr (no traces) */
245 #define F_NORMAL 0x08 /* spawn child process in non-curses regular CLI mode */
246 #define F_CONFIRM 0x10 /* run command - show results before exit (must have F_NORMAL) */
247 #define F_CHKRTN 0x20 /* wait for user prompt if cmd returns failure status */
248 #define F_NOSTDIN 0x40 /* suppress stdin */
249 #define F_PAGE 0x80 /* page output in run-cmd-as-plugin mode */
250 #define F_TTY 0x100 /* Force stdout to go to tty if redirected to a non-tty */
251 #define F_CLI (F_NORMAL | F_MULTI)
252 #define F_SILENT (F_CLI | F_NOTRACE)
254 /* Version compare macros */
256 * states: S_N: normal, S_I: comparing integral part, S_F: comparing
257 * fractional parts, S_Z: idem but with leading Zeroes only
264 /* result_type: VCMP: return diff; VLEN: compare using len_diff/diff */
273 /* TYPE DEFINITIONS */
274 typedef unsigned int uint_t;
275 typedef unsigned char uchar_t;
276 typedef unsigned short ushort_t;
277 typedef unsigned long long ullong_t;
281 /* Directory entry */
282 typedef struct entry {
283 char *name; /* 8 bytes */
284 time_t sec; /* 8 bytes */
285 uint_t nsec; /* 4 bytes (enough to store nanosec) */
286 mode_t mode; /* 4 bytes */
287 off_t size; /* 8 bytes */
289 ullong_t blocks : 40; /* 5 bytes (enough for 512 TiB in 512B blocks allocated) */
290 ullong_t nlen : 16; /* 2 bytes (length of file name) */
291 ullong_t flags : 8; /* 1 byte (flags specific to the file) */
294 uid_t uid; /* 4 bytes */
295 gid_t gid; /* 4 bytes */
299 /* Selection marker */
305 /* Key-value pairs from env */
315 const regex_t *regex;
324 uint_t filtermode : 1; /* Set to enter filter mode */
325 uint_t timeorder : 1; /* Set to sort by time */
326 uint_t sizeorder : 1; /* Set to sort by file size */
327 uint_t apparentsz : 1; /* Set to sort by apparent size (disk usage) */
328 uint_t blkorder : 1; /* Set to sort by blocks used (disk usage) */
329 uint_t extnorder : 1; /* Order by extension */
330 uint_t showhidden : 1; /* Set to show hidden files */
331 uint_t reserved0 : 1;
332 uint_t showdetail : 1; /* Clear to show lesser file info */
333 uint_t ctxactive : 1; /* Context active or not */
334 uint_t reverse : 1; /* Reverse sort */
335 uint_t version : 1; /* Version sort */
336 uint_t reserved1 : 1;
337 /* The following settings are global */
338 uint_t curctx : 3; /* Current context number */
339 uint_t prefersel : 1; /* Prefer selection over current, if exists */
340 uint_t fileinfo : 1; /* Show file information on hover */
341 uint_t nonavopen : 1; /* Open file on right arrow or `l` */
342 uint_t autoenter : 1; /* auto-enter dir in type-to-nav mode */
343 uint_t reserved2 : 1;
344 uint_t useeditor : 1; /* Use VISUAL to open text files */
345 uint_t reserved3 : 3;
346 uint_t regex : 1; /* Use regex filters */
347 uint_t x11 : 1; /* Copy to system clipboard, show notis, xterm title */
348 uint_t timetype : 2; /* Time sort type (0: access, 1: change, 2: modification) */
349 uint_t cliopener : 1; /* All-CLI app opener */
350 uint_t waitedit : 1; /* For ops that can't be detached, used EDITOR */
351 uint_t rollover : 1; /* Roll over at edges */
354 /* Non-persistent program-internal states (alphabeical order) */
356 uint_t autofifo : 1; /* Auto-create NNN_FIFO */
357 uint_t autonext : 1; /* Auto-advance on file open */
358 uint_t dircolor : 1; /* Current status of dir color */
359 uint_t dirctx : 1; /* Show dirs in context color */
360 uint_t duinit : 1; /* Initialize disk usage */
361 uint_t fifomode : 1; /* FIFO notify mode: 0: preview, 1: explorer */
362 uint_t forcequit : 1; /* Do not prompt on quit */
363 uint_t initfile : 1; /* Positional arg is a file */
364 uint_t interrupt : 1; /* Program received an interrupt */
365 uint_t move : 1; /* Move operation */
366 uint_t oldcolor : 1; /* Use older colorscheme */
367 uint_t picked : 1; /* Plugin has picked files */
368 uint_t picker : 1; /* Write selection to user-specified file */
369 uint_t pluginit : 1; /* Plugin framework initialized */
370 uint_t prstssn : 1; /* Persistent session */
371 uint_t rangesel : 1; /* Range selection on */
372 uint_t runctx : 3; /* The context in which plugin is to be run */
373 uint_t runplugin : 1; /* Choose plugin mode */
374 uint_t selbm : 1; /* Select a bookmark from bookmarks directory */
375 uint_t selmode : 1; /* Set when selecting files */
376 uint_t stayonsel : 1; /* Disable auto-advance on selection */
377 uint_t trash : 2; /* Trash method 0: rm -rf, 1: trash-cli, 2: gio trash */
378 uint_t uidgid : 1; /* Show owner and group info */
379 uint_t usebsdtar : 1; /* Use bsdtar as default archive utility */
380 uint_t reserved : 5; /* Adjust when adding/removing a field */
383 /* Contexts or workspaces */
385 char c_path[PATH_MAX]; /* Current dir */
386 char c_last[PATH_MAX]; /* Last visited dir */
387 char c_name[NAME_MAX + 1]; /* Current file name */
388 char c_fltr[REGEX_MAX]; /* Current filter */
389 settings c_cfg; /* Current configuration */
390 uint_t color; /* Color code for directories */
396 size_t pathln[CTX_MAX];
397 size_t lastln[CTX_MAX];
398 size_t nameln[CTX_MAX];
399 size_t fltrln[CTX_MAX];
405 /* Configuration, contexts */
406 static settings cfg = {
409 .timetype = 2, /* T_MOD */
413 alignas(max_align_t) static context g_ctx[CTX_MAX];
415 static int ndents, cur, last, curscroll, last_curscroll, total_dents = ENTRY_INCR, scroll_lines = 1;
416 static int nselected;
418 static int fifofd = -1;
420 static time_t gtimesecs;
421 static uint_t idletimeout, selbufpos, selbuflen;
422 static ushort_t xlines, xcols;
423 static ushort_t idle;
424 static uchar_t maxbm, maxplug, maxorder;
425 static uchar_t cfgsort[CTX_MAX + 1];
427 static char *pluginstr;
428 static char *orderstr;
431 static char *enveditor;
435 static char *initpath;
436 static char *cfgpath;
437 static char *selpath;
438 static char *listpath;
439 static char *listroot;
440 static char *plgpath;
441 static char *pnamebuf, *pselbuf, *findselpos;
444 static char hostname[_POSIX_HOST_NAME_MAX + 1];
447 static char *fifopath;
449 static char *lastcmd;
450 static ullong_t *ihashbmp;
451 static struct entry *pdents;
452 static blkcnt_t dir_blocks;
456 static uchar_t tmpfplen, homelen;
457 static uchar_t blk_shift = BLK_SHIFT_512;
459 static int middle_click_key;
462 static pcre *archive_pcre;
464 static regex_t archive_re;
467 /* pthread related */
468 #define NUM_DU_THREADS (4) /* Can use sysconf(_SC_NPROCESSORS_ONLN) */
469 #define DU_TEST (((node->fts_info & FTS_F) && \
470 (sb->st_nlink <= 1 || test_set_bit((uint_t)sb->st_ino))) || node->fts_info & FTS_DP)
472 static int threadbmp = -1; /* Has 1 in the bit position for idle threads */
473 static volatile int active_threads;
474 static pthread_mutex_t running_mutex = PTHREAD_MUTEX_INITIALIZER;
475 static pthread_mutex_t hardlink_mutex = PTHREAD_MUTEX_INITIALIZER;
476 static ullong_t *core_files;
477 static blkcnt_t *core_blocks;
478 static ullong_t num_files;
487 static thread_data *core_data;
489 /* Retain old signal handlers */
490 static struct sigaction oldsighup;
491 static struct sigaction oldsigtstp;
492 static struct sigaction oldsigwinch;
494 /* For use in functions which are isolated and don't return the buffer */
495 alignas(max_align_t) static char g_buf[CMD_LEN_MAX];
497 /* For use as a scratch buffer in selection manipulation */
498 alignas(max_align_t) static char g_sel[PATH_MAX];
500 /* Buffer to store tmp file path to show selection, file stats and help */
501 alignas(max_align_t) static char g_tmpfpath[TMP_LEN_MAX];
503 /* Buffer to store plugins control pipe location */
504 alignas(max_align_t) static char g_pipepath[TMP_LEN_MAX];
506 /* Non-persistent runtime states */
507 static runstate g_state;
509 /* Options to identify file MIME */
510 #if defined(__APPLE__)
511 #define FILE_MIME_OPTS "-bIL"
512 #elif !defined(__sun) /* no MIME option for 'file' */
513 #define FILE_MIME_OPTS "-biL"
516 /* Macros for utilities */
517 #define UTIL_OPENER 0
519 #define UTIL_BSDTAR 2
522 #define UTIL_LOCKER 5
523 #define UTIL_LAUNCH 6
524 #define UTIL_SH_EXEC 7
527 #define UTIL_RCLONE 10
535 #define UTIL_TRASH_CLI 18
536 #define UTIL_GIO_TRASH 19
537 #define UTIL_RM_RF 20
538 #define UTIL_ARCHMNT 21
540 /* Utilities to open files, run actions */
541 static char * const utils[] = {
544 #elif defined __CYGWIN__
546 #elif defined __HAIKU__
557 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
559 #elif defined __HAIKU__
583 #define MSG_ZERO 0 /* Unused */
584 #define MSG_0_ENTRIES 1
585 #define STR_TMPFILE 2
586 #define MSG_0_SELECTED 3
589 #define MSG_SSN_NAME 6
590 #define MSG_CP_MV_AS 7
591 #define MSG_CUR_SEL_OPTS 8
592 #define MSG_FORCE_RM 9
593 #define MSG_SIZE_LIMIT 10
594 #define MSG_NEW_OPTS 11
595 #define MSG_CLI_MODE 12
596 #define MSG_OVERWRITE 13
597 #define MSG_SSN_OPTS 14
598 #define MSG_QUIT_ALL 15
599 #define MSG_HOSTNAME 16
600 #define MSG_ARCHIVE_NAME 17
601 #define MSG_OPEN_WITH 18
602 #define MSG_NEW_PATH 19
603 #define MSG_LINK_PREFIX 20
604 #define MSG_COPY_NAME 21
606 #define MSG_SEL_MISSING 23
607 #define MSG_ACCESS 24
608 #define MSG_EMPTY_FILE 25
609 #define MSG_UNSUPPORTED 26
610 #define MSG_NOT_SET 27
611 #define MSG_EXISTS 28
612 #define MSG_FEW_COLUMNS 29
613 #define MSG_REMOTE_OPTS 30
614 #define MSG_RCLONE_DELAY 31
615 #define MSG_APP_NAME 32
616 #define MSG_ARCHIVE_OPTS 33
618 #define MSG_INVALID_REG 35
622 #define MSG_RM_TMP 39
623 #define MSG_INVALID_KEY 40
624 #define MSG_NOCHANGE 41
625 #define MSG_DIR_CHANGED 42
626 #define MSG_BM_NAME 43
627 #define MSG_FILE_LIMIT 44
629 static const char * const messages[] = {
639 "%s %s? [Esc cancels]",
640 "size limit exceeded",
641 "['f'ile]/'d'ir/'s'ym/'h'ard?",
644 "'s'ave/'l'oad/'r'estore?",
645 "Quit all contexts?",
646 "remote name (- for hovered): ",
647 "archive [path/]name: ",
650 "link prefix [@ for none]: ",
651 "copy [path/]name: ",
652 "\n'Enter' to continue",
655 "empty! edit/open with",
663 "['l's]/'o'pen/e'x'tract/'m'nt?",
666 "'a'u/'d'u/'e'xt/'r'ev/'s'z/'t'm/'v'er/'c'lr/'^T'?",
667 "unmount failed! try lazy?",
668 "first file (\')/char?",
672 "dir changed, range sel off",
674 "file limit exceeded",
677 /* Supported configuration environment variables */
683 #define NNN_FCOLORS 5
688 #define NNN_ARCHIVE 10
690 #define NNN_HELP 12 /* strings end here */
691 #define NNN_TRASH 13 /* flags begin here */
693 static const char * const env_cfg[] = {
710 /* Required environment variables */
717 static const char * const envs[] = {
730 #define PROGRESS_CP "cpg -giRp"
731 #define PROGRESS_MV "mvg -gi"
732 static char cp[sizeof PROGRESS_CP] = "cp -iRp";
733 static char mv[sizeof PROGRESS_MV] = "mv -i";
735 /* Archive commands */
736 static char * const archive_cmd[] = {"atool -a", "bsdtar -acvf", "zip -r", "tar -acvf"};
738 /* Tokens used for path creation */
744 static const char * const toks[] = {
748 "plugins", /* must be the last entry */
756 #define P_ARCHIVE_CMD 4
758 static const char * const patterns[] = {
759 SED" -i 's|^\\(\\(.*/\\)\\(.*\\)$\\)|#\\1\\n\\3|' %s",
760 SED" 's|^\\([^#/][^/]\\?.*\\)$|%s/\\1|;s|^#\\(/.*\\)$|\\1|' "
761 "%s | tr '\\n' '\\0' | xargs -0 -n2 sh -c '%s \"$0\" \"$@\" < /dev/tty'",
762 "\\.(bz|bz2|gz|tar|taz|tbz|tbz2|tgz|z|zip)$", /* Basic formats that don't need external tools */
763 SED" -i 's|^%s\\(.*\\)$|%s\\1|' %s",
764 "xargs -0 %s %s < '%s'",
768 #define C_BLK (CTX_MAX + 1) /* Block device: DarkSeaGreen1 */
769 #define C_CHR (C_BLK + 1) /* Character device: Yellow1 */
770 #define C_DIR (C_CHR + 1) /* Directory: DeepSkyBlue1 */
771 #define C_EXE (C_DIR + 1) /* Executable file: Green1 */
772 #define C_FIL (C_EXE + 1) /* Regular file: Normal */
773 #define C_HRD (C_FIL + 1) /* Hard link: Plum4 */
774 #define C_LNK (C_HRD + 1) /* Symbolic link: Cyan1 */
775 #define C_MIS (C_LNK + 1) /* Missing file OR file details: Grey62 */
776 #define C_ORP (C_MIS + 1) /* Orphaned symlink: DeepPink1 */
777 #define C_PIP (C_ORP + 1) /* Named pipe (FIFO): Orange1 */
778 #define C_SOC (C_PIP + 1) /* Socket: MediumOrchid1 */
779 #define C_UND (C_SOC + 1) /* Unknown OR 0B regular/exe file: Red1 */
781 static char gcolors[] = "c1e2272e006033f7c6d6abc4";
782 static uint_t fcolors[C_UND + 1] = {0};
786 #define NUM_EVENT_SLOTS 32 /* Make room for 32 events */
787 #define EVENT_SIZE (sizeof(struct inotify_event))
788 #define EVENT_BUF_LEN (EVENT_SIZE * NUM_EVENT_SLOTS)
789 static int inotify_fd, inotify_wd = -1;
790 static uint_t INOTIFY_MASK = /* IN_ATTRIB | */ IN_CREATE | IN_DELETE | IN_DELETE_SELF
791 | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
792 #elif defined(BSD_KQUEUE)
793 #define NUM_EVENT_SLOTS 1
794 #define NUM_EVENT_FDS 1
795 static int kq, event_fd = -1;
796 static struct kevent events_to_monitor[NUM_EVENT_FDS];
797 static uint_t KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK
798 | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
799 static struct timespec gtimeout;
800 #elif defined(HAIKU_NM)
801 static bool haiku_nm_active = FALSE;
802 static haiku_nm_h haiku_hnd;
805 /* Function macros */
806 #define tolastln() move(xlines - 1, 0)
807 #define tocursor() move(cur + 2 - curscroll, 0)
808 #define exitcurses() endwin()
809 #define printwarn(presel) printwait(strerror(errno), presel)
810 #define istopdir(path) ((path)[1] == '\0' && (path)[0] == '/')
811 #define copycurname() xstrsncpy(lastname, ndents ? pdents[cur].name : "\0", NAME_MAX + 1)
812 #define settimeout() timeout(1000)
813 #define cleartimeout() timeout(-1)
814 #define errexit() printerr(__LINE__)
815 #define setdirwatch() (cfg.filtermode ? (presel = FILTER) : (watch = TRUE))
816 #define filterset() (g_ctx[cfg.curctx].c_fltr[1])
817 /* We don't care about the return value from strcmp() */
818 #define xstrcmp(a, b) (*(a) != *(b) ? -1 : strcmp((a), (b)))
819 /* A faster version of xisdigit */
820 #define xisdigit(c) ((unsigned int) (c) - '0' <= 9)
821 #define xerror() perror(xitoa(__LINE__))
824 #define ENTLESS(i, j) (entrycmpfn(pdents + (i), pdents + (j)) < 0)
825 #define ENTSWAP(i, j) (swap_ent((i), (j)))
826 #define ENTSORT(pdents, ndents, entrycmpfn) QSORT((ndents), ENTLESS, ENTSWAP)
828 #define ENTSORT(pdents, ndents, entrycmpfn) qsort((pdents), (ndents), sizeof(*(pdents)), (entrycmpfn))
831 /* Forward declarations */
832 static void redraw(char *path);
833 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag);
834 static void move_cursor(int target, int ignore_scrolloff);
835 static char *load_input(int fd, const char *path);
836 static int set_sort_flags(int r);
837 static void statusbar(char *path);
838 static bool get_output(char *file, char *arg1, char *arg2, int fdout, bool page);
840 static void notify_fifo(bool force);
845 static void sigint_handler(int sig)
848 g_state.interrupt = 1;
851 static void clean_exit_sighandler(int sig)
855 /* This triggers cleanup() thanks to atexit() */
859 static char *xitoa(uint_t val)
861 static char dst[32] = {'\0'};
862 static const char digits[201] =
863 "0001020304050607080910111213141516171819"
864 "2021222324252627282930313233343536373839"
865 "4041424344454647484950515253545556575859"
866 "6061626364656667686970717273747576777879"
867 "8081828384858687888990919293949596979899";
868 uint_t next = 30, quo, i;
872 i = (val - (quo * 100)) * 2;
874 dst[next] = digits[i + 1];
875 dst[--next] = digits[i];
879 /* Handle last 1-2 digits */
881 dst[next] = '0' + val;
884 dst[next] = digits[i + 1];
885 dst[--next] = digits[i];
891 /* Return the integer value of a char representing HEX */
892 static uchar_t xchartohex(uchar_t c)
897 if (c >= 'a' && c <= 'f')
900 if (c >= 'A' && c <= 'F')
907 * Source: https://elixir.bootlin.com/linux/latest/source/arch/alpha/include/asm/bitops.h
909 static bool test_set_bit(uint_t nr)
913 pthread_mutex_lock(&hardlink_mutex);
914 ullong_t *m = ((ullong_t *)ihashbmp) + (nr >> 6);
916 if (*m & (1 << (nr & 63))) {
917 pthread_mutex_unlock(&hardlink_mutex);
921 *m |= 1 << (nr & 63);
922 pthread_mutex_unlock(&hardlink_mutex);
928 /* Increase the limit on open file descriptors, if possible */
929 static void max_openfds(void)
933 if (!getrlimit(RLIMIT_NOFILE, &rl))
934 if (rl.rlim_cur < rl.rlim_max) {
935 rl.rlim_cur = rl.rlim_max;
936 setrlimit(RLIMIT_NOFILE, &rl);
942 * Wrapper to realloc()
943 * Frees current memory if realloc() fails and returns NULL.
945 * The *alloc() family returns aligned address: https://man7.org/linux/man-pages/man3/malloc.3.html
947 static void *xrealloc(void *pcur, size_t len)
949 void *pmem = realloc(pcur, len);
958 * Just a safe strncpy(3)
959 * Always null ('\0') terminates if both src and dest are valid pointers.
960 * Returns the number of bytes copied including terminating null byte.
962 static size_t xstrsncpy(char *restrict dst, const char *restrict src, size_t n)
964 char *end = memccpy(dst, src, '\0', n);
967 dst[n - 1] = '\0'; // NOLINT
968 end = dst + n; /* If we return n here, binary size increases due to auto-inlining */
974 static inline size_t xstrlen(const char *restrict s)
976 #if !defined(__GLIBC__)
977 return strlen(s); // NOLINT
979 return (char *)rawmemchr(s, '\0') - s; // NOLINT
983 static char *xstrdup(const char *restrict s)
985 size_t len = xstrlen(s) + 1;
986 char *ptr = malloc(len);
987 return ptr ? memcpy(ptr, s, len) : NULL;
990 static bool is_suffix(const char *restrict str, const char *restrict suffix)
995 size_t lenstr = xstrlen(str);
996 size_t lensuffix = xstrlen(suffix);
998 if (lensuffix > lenstr)
1001 return (xstrcmp(str + (lenstr - lensuffix), suffix) == 0);
1004 static inline bool is_prefix(const char *restrict str, const char *restrict prefix, size_t len)
1006 return !strncmp(str, prefix, len);
1009 static inline bool is_bad_len_or_dir(const char *restrict path)
1011 size_t len = xstrlen(path);
1013 return ((len >= PATH_MAX) || (path[len - 1] == '/'));
1016 static char *get_cwd_entry(const char *restrict cwdpath, char *entrypath, size_t *tokenlen)
1018 size_t len = xstrlen(cwdpath);
1021 if (!is_prefix(entrypath, cwdpath, len))
1024 entrypath += len + 1; /* Add 1 for trailing / */
1025 end = strchr(entrypath, '/');
1027 *tokenlen = end - entrypath;
1029 *tokenlen = xstrlen(entrypath);
1030 DPRINTF_U(*tokenlen);
1036 * The poor man's implementation of memrchr(3).
1037 * We are only looking for '/' and '.' in this program.
1038 * And we are NOT expecting a '/' at the end.
1039 * Ideally 0 < n <= xstrlen(s).
1041 static void *xmemrchr(uchar_t *restrict s, uchar_t ch, size_t n)
1043 #if defined(__GLIBC__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
1044 return memrchr(s, ch, n);
1050 uchar_t *ptr = s + n;
1061 /* A very simplified implementation, changes path */
1062 static char *xdirname(char *path)
1064 char *base = xmemrchr((uchar_t *)path, '/', xstrlen(path));
1074 static char *xbasename(char *path)
1076 char *base = xmemrchr((uchar_t *)path, '/', xstrlen(path)); // NOLINT
1078 return base ? base + 1 : path;
1081 static inline char *xextension(const char *fname, size_t len)
1083 return xmemrchr((uchar_t *)fname, '.', len);
1088 * One-shot cache for getpwuid/getgrgid. Returns the cached name if the
1089 * provided uid is the same as the previous uid. Returns xitoa(guid) if
1090 * the guid is not found in the password database.
1092 static char *getpwname(uid_t uid)
1094 static uint_t uidcache = UINT_MAX;
1095 static char *namecache;
1097 if (uidcache != uid) {
1098 struct passwd *pw = getpwuid(uid);
1101 namecache = pw ? pw->pw_name : NULL;
1104 return namecache ? namecache : xitoa(uid);
1107 static char *getgrname(gid_t gid)
1109 static uint_t gidcache = UINT_MAX;
1110 static char *grpcache;
1112 if (gidcache != gid) {
1113 struct group *gr = getgrgid(gid);
1116 grpcache = gr ? gr->gr_name : NULL;
1119 return grpcache ? grpcache : xitoa(gid);
1123 static inline bool getutil(char *util)
1125 return spawn("which", util, NULL, NULL, F_NORMAL | F_NOTRACE) == 0;
1128 static inline bool tilde_is_home(const char *s)
1130 return s[0] == '~' && (s[1] == '\0' || s[1] == '/');
1133 static inline bool tilde_is_home_strict(const char *s)
1135 return s[0] == '~' && s[1] == '/';
1139 * Updates out with "dir/name or "/name"
1140 * Returns the number of bytes copied including the terminating NULL byte
1142 * Note: dir and out must be PATH_MAX in length to avoid macOS fault
1144 static size_t mkpath(const char *dir, const char *name, char *out)
1148 /* same rational for being strict as abspath() */
1149 if (tilde_is_home_strict(name)) { //NOLINT
1150 len = xstrsncpy(out, home, PATH_MAX);
1153 } else if (name[0] != '/') { // NOLINT
1154 /* Handle root case */
1155 len = istopdir(dir) ? 1 : xstrsncpy(out, dir, PATH_MAX);
1156 out[len - 1] = '/'; // NOLINT
1158 return (xstrsncpy(out + len, name, PATH_MAX - len) + len);
1161 /* Assumes both the paths passed are directories */
1162 static char *common_prefix(const char *path, char *prefix)
1164 const char *x = path, *y = prefix;
1167 if (!path || !*path || !prefix)
1171 xstrsncpy(prefix, path, PATH_MAX);
1175 while (*x && *y && (*x == *y))
1178 /* Strings are same */
1182 /* Path is shorter */
1183 if (!*x && *y == '/') {
1184 xstrsncpy(prefix, path, y - path);
1188 /* Prefix is shorter */
1189 if (!*y && *x == '/')
1192 /* Shorten prefix */
1193 prefix[y - prefix] = '\0';
1195 sep = xmemrchr((uchar_t *)prefix, '/', y - prefix);
1205 * The library function realpath() resolves symlinks.
1206 * If there's a symlink in file list we want to show the symlink not what it's points to.
1207 * Resolves ./../~ in filepath
1209 static char *abspath(const char *filepath, char *cwd, char *buf)
1211 const char *path = filepath;
1212 bool allocated = FALSE;
1217 /* when dealing with tilde, we need to be strict.
1218 * otherwise a file named "~" can end up expanding to
1219 * $HOME and causing disaster */
1220 if (tilde_is_home_strict(path)) {
1222 path += 2; /* advance 2 bytes past the "~/" */
1223 } else if ((path[0] != '/') && !cwd) {
1224 cwd = getcwd(NULL, 0);
1230 size_t dst_size = 0, src_size = xstrlen(path), cwd_size = cwd ? xstrlen(cwd) : 0;
1231 size_t len = src_size;
1235 * We need to add 2 chars at the end as relative paths may start with:
1237 * no separator (fd .): this needs an additional char for '/'
1239 char *resolved_path = buf ? buf : malloc(src_size + cwd_size + 2);
1241 if (!resolved_path) {
1247 /* Turn relative paths into absolute */
1248 if (path[0] != '/') {
1251 free(resolved_path);
1254 dst_size = xstrsncpy(resolved_path, cwd, cwd_size + 1) - 1;
1258 resolved_path[0] = '\0';
1261 dst = resolved_path + dst_size;
1262 for (const char *next = NULL; next != path + src_size;) {
1263 next = memchr(src, '/', len);
1265 next = path + src_size;
1267 if (next - src == 2 && src[0] == '.' && src[1] == '.') {
1268 if (dst - resolved_path) {
1269 dst = xmemrchr((uchar_t *)resolved_path, '/', dst - resolved_path);
1272 } else if (next - src == 1 && src[0] == '.') {
1274 } else if (next - src) {
1276 xstrsncpy(dst, src, next - src + 1);
1281 len = src_size - (src - path);
1284 if (*resolved_path == '\0') {
1285 resolved_path[0] = '/';
1286 resolved_path[1] = '\0';
1289 if (xstrlen(resolved_path) >= PATH_MAX) {
1291 free(resolved_path);
1297 return resolved_path;
1300 /* wraps the argument in single quotes so it can be safely fed to shell */
1301 static bool shell_escape(char *output, size_t outlen, const char *s)
1303 size_t n = xstrlen(s), w = 0;
1306 DPRINTF_S("s == output");
1310 output[w++] = '\''; /* begin single quote */
1311 for (size_t r = 0; r < n; ++r) {
1312 /* potentially too big: 4 for the single quote case, 2 from
1313 * outside the loop */
1314 if (w + 6 >= outlen)
1318 /* the only thing that has special meaning inside single
1319 * quotes are single quotes themselves. */
1321 output[w++] = '\''; /* end single quote */
1322 output[w++] = '\\'; /* put \' so it's treated as literal single quote */
1324 output[w++] = '\''; /* start single quoting again */
1331 output[w++] = '\''; /* end single quote */
1332 output[w++] = '\0'; /* nul terminator */
1336 static bool set_tilde_in_path(char *path)
1338 if (is_prefix(path, home, homelen)) {
1339 home[homelen] = path[homelen - 1];
1340 path[homelen - 1] = '~';
1347 static void reset_tilde_in_path(char *path)
1349 path[homelen - 1] = home[homelen];
1350 home[homelen] = '\0';
1354 static void xterm_cfg(char *path)
1356 if (cfg.x11 && !g_state.picker) {
1357 /* Signal CWD change to terminal */
1358 printf("\033]7;file://%s%s\033\\", hostname, path);
1360 /* Set terminal window title */
1361 bool r = set_tilde_in_path(path);
1363 printf("\033]2;%s\007", r ? &path[homelen - 1] : path);
1367 reset_tilde_in_path(path);
1372 static bool convert_tilde(const char *path, char *buf)
1374 if (tilde_is_home(path)) {
1375 ssize_t len = xstrlen(home);
1376 ssize_t loclen = xstrlen(path);
1378 xstrsncpy(buf, home, len + 1);
1379 xstrsncpy(buf + len, path + 1, loclen);
1385 static int create_tmp_file(void)
1387 xstrsncpy(g_tmpfpath + tmpfplen - 1, messages[STR_TMPFILE], TMP_LEN_MAX - tmpfplen);
1389 int fd = mkstemp(g_tmpfpath);
1392 DPRINTF_S(strerror(errno));
1398 static void msg(const char *message)
1400 dprintf(STDERR_FILENO, "%s\n", message);
1404 static void handle_key_resize(void)
1410 /* Clear the old prompt */
1411 static void clearoldprompt(void)
1414 move(xlines - 2, 0);
1419 handle_key_resize();
1423 /* Messages show up at the bottom */
1424 static inline void printmsg_nc(const char *msg)
1431 static void printmsg(const char *msg)
1433 attron(COLOR_PAIR(cfg.curctx + 1));
1435 attroff(COLOR_PAIR(cfg.curctx + 1));
1438 static void printwait(const char *msg, int *presel)
1444 xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
1448 /* Kill curses and display error before exiting */
1449 static void printerr(int linenum)
1452 perror(xitoa(linenum));
1453 if (!g_state.picker && selpath)
1459 static inline bool xconfirm(int c)
1461 return (c == 'y' || c == 'Y');
1464 static int get_input(const char *prompt)
1475 while (*ch == KEY_RESIZE) {
1489 static bool isselfileempty(void)
1493 return (stat(selpath, &sb) == -1) || (!sb.st_size);
1496 static int get_cur_or_sel(void)
1498 bool sel = (selbufpos || !isselfileempty());
1500 /* Check both local buffer and selection file for external selection */
1501 if (sel && ndents) {
1502 /* If selection is preferred and we have a local selection, return selection.
1503 * Always show the prompt in case of an external selection.
1505 if (cfg.prefersel && selbufpos)
1508 int choice = get_input(messages[MSG_CUR_SEL_OPTS]);
1510 return ((choice == 'c' || choice == 's') ? choice : 0);
1522 static void xdelay(useconds_t delay)
1528 static char confirm_force(bool selection)
1532 snprintf(str, 64, messages[MSG_FORCE_RM],
1533 g_state.trash ? utils[UTIL_GIO_TRASH] + 4 : utils[UTIL_RM_RF],
1534 (selection ? "selected" : "hovered"));
1536 int r = get_input(str);
1539 return '\0'; /* cancel */
1540 if (r == 'y' || r == 'Y')
1541 return 'f'; /* forceful for rm */
1542 return (g_state.trash ? '\0' : 'i'); /* interactive for rm */
1545 /* Writes buflen char(s) from buf to a file */
1546 static void writesel(const char *buf, const size_t buflen)
1551 int fd = open(selpath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
1554 if (write(fd, buf, buflen) != (ssize_t)buflen)
1561 static void appendfpath(const char *path, const size_t len)
1563 if ((selbufpos >= selbuflen) || ((len + 3) > (selbuflen - selbufpos))) {
1564 selbuflen += PATH_MAX;
1565 pselbuf = xrealloc(pselbuf, selbuflen);
1570 selbufpos += xstrsncpy(pselbuf + selbufpos, path, len);
1573 static void selbufrealloc(const size_t alloclen)
1575 if ((selbufpos + alloclen) > selbuflen) {
1576 selbuflen = ALIGN_UP(selbufpos + alloclen, PATH_MAX);
1577 pselbuf = xrealloc(pselbuf, selbuflen);
1583 /* Write selected file paths to fd, linefeed separated */
1584 static size_t seltofile(int fd, uint_t *pcount)
1586 uint_t lastpos, count = 0;
1587 char *pbuf = pselbuf;
1589 ssize_t len, prefixlen = 0, initlen = 0;
1597 lastpos = selbufpos - 1;
1600 prefixlen = (ssize_t)xstrlen(listroot);
1601 initlen = (ssize_t)xstrlen(listpath);
1604 while (pos <= lastpos) {
1606 len = (ssize_t)xstrlen(pbuf);
1608 if (!listpath || !is_prefix(pbuf, listpath, initlen)) {
1609 if (write(fd, pbuf, len) != len)
1612 if (write(fd, listroot, prefixlen) != prefixlen)
1614 if (write(fd, pbuf + initlen, len - initlen) != (len - initlen))
1619 if (pos <= lastpos) {
1620 if (write(fd, "\n", 1) != 1)
1634 /* List selection from selection file (another instance) */
1635 static bool listselfile(void)
1637 if (isselfileempty())
1640 snprintf(g_buf, CMD_LEN_MAX, "tr \'\\0\' \'\\n\' < %s", selpath);
1641 spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CONFIRM);
1646 /* Reset selection indicators */
1647 static void resetselind(void)
1649 for (int r = 0; r < ndents; ++r)
1650 if (pdents[r].flags & FILE_SELECTED)
1651 pdents[r].flags &= ~FILE_SELECTED;
1654 static void startselection(void)
1656 if (!g_state.selmode) {
1657 g_state.selmode = 1;
1668 static void clearselection(void)
1672 g_state.selmode = 0;
1676 static char *findinsel(char *startpos, int len)
1684 char *found = startpos;
1685 size_t buflen = selbufpos - (startpos - pselbuf);
1688 /* memmem(3): not specified in POSIX.1, but present on a number of other systems. */
1689 found = memmem(found, buflen - (found - startpos), g_sel, len);
1692 if (found == startpos || *(found - 1) == '\0')
1694 found += len; /* We found g_sel as a substring of a path, move forward */
1695 if (found >= startpos + buflen)
1700 static int markcmp(const void *va, const void *vb)
1702 const selmark *ma = (selmark*)va;
1703 const selmark *mb = (selmark*)vb;
1705 return ma->startpos - mb->startpos;
1708 /* scanselforpath() must be called before calling this */
1709 static inline void findmarkentry(size_t len, struct entry *dentp)
1711 if (!(dentp->flags & FILE_SCANNED)) {
1712 if (findinsel(findselpos, len + xstrsncpy(g_sel + len, dentp->name, dentp->nlen)))
1713 dentp->flags |= FILE_SELECTED;
1714 dentp->flags |= FILE_SCANNED;
1719 * scanselforpath() must be called before calling this
1720 * pathlen = length of path + 1 (+1 for trailing slash)
1722 static void invertselbuf(const int pathlen)
1724 size_t len, endpos, shrinklen = 0, alloclen = 0;
1725 char * const pbuf = g_sel + pathlen;
1727 int i, nmarked = 0, prev = 0;
1728 struct entry *dentp;
1730 selmark *marked = malloc(nselected * sizeof(selmark));
1737 /* First pass: inversion */
1738 for (i = 0; i < ndents; ++i) {
1741 if (dentp->flags & FILE_SCANNED) {
1742 if (dentp->flags & FILE_SELECTED) {
1743 dentp->flags ^= FILE_SELECTED; /* Clear selection status */
1746 dentp->flags |= FILE_SELECTED;
1747 alloclen += pathlen + dentp->nlen;
1750 dentp->flags |= FILE_SCANNED;
1755 len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1756 found = findinsel(findselpos, len);
1758 if (findselpos == found)
1761 if (nmarked && (found
1762 == (marked[nmarked - 1].startpos + marked[nmarked - 1].len)))
1763 marked[nmarked - 1].len += len;
1765 marked[nmarked].startpos = found;
1766 marked[nmarked].len = len;
1771 shrinklen += len; /* buffer size adjustment */
1773 dentp->flags |= FILE_SELECTED;
1774 alloclen += pathlen + dentp->nlen;
1781 * Files marked for deselection could be found in arbitrary order.
1782 * Sort by appearance in selection buffer.
1783 * With entries sorted we can merge adjacent ones allowing us to
1784 * move them in a single go.
1786 qsort(marked, nmarked, sizeof(selmark), &markcmp);
1788 /* Some files might be adjacent. Merge them into a single entry */
1789 for (i = 1; i < nmarked; ++i) {
1790 if (marked[i].startpos == marked[prev].startpos + marked[prev].len)
1791 marked[prev].len += marked[i].len;
1794 marked[prev].startpos = marked[i].startpos;
1795 marked[prev].len = marked[i].len;
1800 * Number of entries is increased by encountering a non-adjacent entry
1801 * After we finish the loop we should increment it once more.
1804 if (nmarked) /* Make sure there is something to deselect */
1807 /* Using merged entries remove unselected chunks from selection buffer */
1808 for (i = 0; i < nmarked; ++i) {
1810 * found: points to where the current block starts
1811 * variable is recycled from previous for readability
1812 * endpos: points to where the the next block starts
1813 * area between the end of current block (found + len)
1814 * and endpos is selected entries. This is what we are
1817 found = marked[i].startpos;
1818 endpos = (i + 1 == nmarked ? selbufpos : marked[i + 1].startpos - pselbuf);
1819 len = marked[i].len;
1821 /* Move back only selected entries. No selected memory is moved twice */
1822 memmove(found, found + len, endpos - (found + len - pselbuf));
1827 /* Buffer size adjustment */
1828 selbufpos -= shrinklen;
1830 selbufrealloc(alloclen);
1832 /* Second pass: append newly selected to buffer */
1833 for (i = 0; i < ndents; ++i) {
1834 if (pdents[i].flags & FILE_SELECTED) {
1835 len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1836 appendfpath(g_sel, len);
1841 nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1845 * scanselforpath() must be called before calling this
1846 * pathlen = length of path + 1 (+1 for trailing slash)
1848 static void addtoselbuf(const int pathlen, int startid, int endid)
1851 size_t len, alloclen = 0;
1852 struct entry *dentp;
1854 char * const pbuf = g_sel + pathlen;
1856 /* Remember current selection buffer position */
1857 for (i = startid; i <= endid; ++i) {
1861 len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1862 found = findinsel(findselpos, len);
1864 dentp->flags |= (FILE_SCANNED | FILE_SELECTED);
1865 if (found == findselpos) {
1867 if (findselpos == (pselbuf + selbufpos))
1871 alloclen += pathlen + dentp->nlen;
1873 alloclen += pathlen + dentp->nlen;
1876 selbufrealloc(alloclen);
1878 for (i = startid; i <= endid; ++i) {
1879 if (!(pdents[i].flags & FILE_SELECTED)) {
1880 len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1881 appendfpath(g_sel, len);
1883 pdents[i].flags |= (FILE_SCANNED | FILE_SELECTED);
1887 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
1890 /* Removes g_sel from selbuf */
1891 static void rmfromselbuf(size_t len)
1893 char *found = findinsel(findselpos, len);
1897 memmove(found, found + len, selbufpos - (found + len - pselbuf));
1900 nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1903 static int scanselforpath(const char *path, bool getsize)
1905 if (!path[1]) { /* path should always be at least two bytes (including NULL) */
1907 findselpos = pselbuf;
1908 return 1; /* Length of '/' is 1 */
1911 size_t off = xstrsncpy(g_sel, path, PATH_MAX);
1913 g_sel[off - 1] = '/';
1915 * We set findselpos only here. Directories can be listed in arbitrary order.
1916 * This is the best best we can do for remembering position.
1918 findselpos = findinsel(NULL, off);
1922 return (findselpos ? off : 0);
1925 /* Finish selection procedure before an operation */
1926 static void endselection(bool endselmode)
1930 char buf[sizeof(patterns[P_REPLACE]) + PATH_MAX + (TMP_LEN_MAX << 1)];
1932 if (endselmode && g_state.selmode)
1933 g_state.selmode = 0;
1935 /* The code below is only for listing mode */
1936 if (!listpath || !selbufpos)
1939 fd = create_tmp_file();
1941 DPRINTF_S("couldn't create tmp file");
1945 seltofile(fd, NULL);
1947 DPRINTF_S(strerror(errno));
1952 snprintf(buf, sizeof(buf), patterns[P_REPLACE], listpath, listroot, g_tmpfpath);
1953 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
1955 fd = open(g_tmpfpath, O_RDONLY);
1957 DPRINTF_S(strerror(errno));
1959 if (unlink(g_tmpfpath)) {
1960 DPRINTF_S(strerror(errno));
1966 count = read(fd, pselbuf, selbuflen);
1968 DPRINTF_S(strerror(errno));
1970 if (close(fd) || unlink(g_tmpfpath)) {
1971 DPRINTF_S(strerror(errno));
1976 if (close(fd) || unlink(g_tmpfpath)) {
1977 DPRINTF_S(strerror(errno));
1983 pselbuf[--count] = '\0';
1984 for (--count; count > 0; --count)
1985 if (pselbuf[count] == '\n' && pselbuf[count+1] == '/')
1986 pselbuf[count] = '\0';
1988 writesel(pselbuf, selbufpos - 1);
1991 /* Returns: 1 - success, 0 - none selected, -1 - other failure */
1992 static int editselection(void)
2000 if (!selbufpos) /* External selection is only editable at source */
2001 return listselfile();
2003 fd = create_tmp_file();
2005 DPRINTF_S("couldn't create tmp file");
2009 seltofile(fd, NULL);
2011 DPRINTF_S(strerror(errno));
2015 /* Save the last modification time */
2016 if (stat(g_tmpfpath, &sb)) {
2017 DPRINTF_S(strerror(errno));
2021 mtime = sb.st_mtime;
2023 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2025 fd = open(g_tmpfpath, O_RDONLY);
2027 DPRINTF_S(strerror(errno));
2034 if (mtime == sb.st_mtime) {
2035 DPRINTF_S("selection is not modified");
2040 if (sb.st_size > selbufpos) {
2041 DPRINTF_S("edited buffer larger than previous");
2046 count = read(fd, pselbuf, selbuflen);
2048 DPRINTF_S(strerror(errno));
2050 if (close(fd) || unlink(g_tmpfpath)) {
2051 DPRINTF_S(strerror(errno));
2057 if (close(fd) || unlink(g_tmpfpath)) {
2058 DPRINTF_S(strerror(errno));
2070 /* The last character should be '\n' */
2071 pselbuf[--count] = '\0';
2072 for (--count; count > 0; --count) {
2073 /* Replace every '\n' that separates two paths */
2074 if (pselbuf[count] == '\n' && pselbuf[count + 1] == '/') {
2076 pselbuf[count] = '\0';
2080 /* Add a line for the last file */
2083 if (lines > nselected) {
2084 DPRINTF_S("files added to selection");
2089 writesel(pselbuf, selbufpos - 1);
2099 static bool selsafe(void)
2101 /* Fail if selection file path not generated */
2103 printmsg(messages[MSG_SEL_MISSING]);
2107 /* Fail if selection file path isn't accessible */
2108 if (access(selpath, R_OK | W_OK) == -1) {
2109 errno == ENOENT ? printmsg(messages[MSG_0_SELECTED]) : printwarn(NULL);
2116 static void export_file_list(void)
2121 struct entry *pdent = pdents;
2122 int fd = create_tmp_file();
2125 DPRINTF_S(strerror(errno));
2129 for (int r = 0; r < ndents; ++pdent, ++r) {
2130 if (write(fd, pdent->name, pdent->nlen - 1) != (pdent->nlen - 1))
2133 if ((r != ndents - 1) && (write(fd, "\n", 1) != 1))
2138 DPRINTF_S(strerror(errno));
2141 spawn(editor, g_tmpfpath, NULL, NULL, F_CLI);
2143 if (xconfirm(get_input(messages[MSG_RM_TMP])))
2147 static bool init_fcolors(void)
2149 char *f_colors = getenv(env_cfg[NNN_FCOLORS]);
2151 if (!f_colors || !*f_colors)
2154 for (uchar_t id = C_BLK; *f_colors && id <= C_UND; ++id) {
2155 fcolors[id] = xchartohex(*f_colors) << 4;
2157 fcolors[id] += xchartohex(*f_colors);
2159 init_pair(id, fcolors[id], -1);
2168 /* Initialize curses mode */
2169 static bool initcurses(void *oldmask)
2175 if (g_state.picker) {
2176 if (!newterm(NULL, stderr, stdin)) {
2180 } else if (!initscr()) {
2182 DPRINTF_S(getenv("TERM"));
2189 //intrflush(stdscr, FALSE);
2190 keypad(stdscr, TRUE);
2192 #if NCURSES_MOUSE_VERSION <= 1
2193 mousemask(BUTTON1_PRESSED | BUTTON1_DOUBLE_CLICKED | BUTTON2_PRESSED | BUTTON3_PRESSED,
2194 (mmask_t *)oldmask);
2196 mousemask(BUTTON1_PRESSED | BUTTON2_PRESSED | BUTTON3_PRESSED | BUTTON4_PRESSED
2197 | BUTTON5_PRESSED, (mmask_t *)oldmask);
2201 curs_set(FALSE); /* Hide cursor */
2203 char *colors = getenv(env_cfg[NNN_COLORS]);
2205 if (colors || !getenv("NO_COLOR")) {
2210 use_default_colors();
2212 /* Initialize file colors */
2213 if (COLORS >= COLOR_256) {
2214 if (!(g_state.oldcolor || init_fcolors())) {
2216 msg(env_cfg[NNN_FCOLORS]);
2220 g_state.oldcolor = 1;
2223 DPRINTF_D(COLOR_PAIRS);
2225 if (colors && *colors == '#') {
2226 char *sep = strchr(colors, ';');
2228 if (!g_state.oldcolor && COLORS >= COLOR_256) {
2233 * If fallback colors are specified, set the separator
2234 * to NULL so we don't interpret separator and fallback
2235 * if fewer than CTX_MAX xterm 256 colors are specified.
2240 colors = sep; /* Detect if 8 colors fallback is appended */
2246 /* Get and set the context colors */
2247 for (uchar_t i = 0; i < CTX_MAX; ++i) {
2248 pcode = &g_ctx[i].color;
2250 if (colors && *colors) {
2252 *pcode = xchartohex(*colors) << 4;
2254 fcolors[i + 1] = *pcode += xchartohex(*colors);
2255 else { /* Each color code must be 2 hex symbols */
2257 msg(env_cfg[NNN_COLORS]);
2261 *pcode = (*colors < '0' || *colors > '7') ? 4 : *colors - '0';
2266 init_pair(i + 1, *pcode, -1);
2269 #ifdef ICONS_ENABLED
2270 if (!g_state.oldcolor) {
2271 for (uint_t i = 0; i < ELEMENTS(init_colors); ++i)
2272 init_pair(C_UND + 1 + init_colors[i], init_colors[i], -1);
2276 settimeout(); /* One second */
2281 /* No NULL check here as spawn() guards against it */
2282 static char *parseargs(char *cmd, char **argv, int *pindex)
2285 size_t len = xstrlen(cmd) + 1;
2286 char *line = (char *)malloc(len);
2289 DPRINTF_S("malloc()!");
2293 xstrsncpy(line, cmd, len);
2294 argv[count++] = line;
2297 while (*line) { // NOLINT
2298 if (ISBLANK(*line)) {
2301 if (!*line) // NOLINT
2304 argv[count++] = line;
2305 if (count == EXEC_ARGS_MAX) {
2314 if (count == -1 || count > (EXEC_ARGS_MAX - 4)) { /* 3 args and last NULL */
2317 DPRINTF_S("NULL or too many args");
2324 static void enable_signals(void)
2326 struct sigaction dfl_act = {.sa_handler = SIG_DFL};
2328 sigaction(SIGHUP, &dfl_act, NULL);
2329 sigaction(SIGINT, &dfl_act, NULL);
2330 sigaction(SIGQUIT, &dfl_act, NULL);
2331 sigaction(SIGTSTP, &dfl_act, NULL);
2332 sigaction(SIGWINCH, &dfl_act, NULL);
2335 static pid_t xfork(uchar_t flag)
2340 /* the parent ignores the interrupt, quit and hangup signals */
2341 sigaction(SIGHUP, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsighup);
2342 sigaction(SIGTSTP, &(struct sigaction){.sa_handler = SIG_DFL}, &oldsigtstp);
2343 sigaction(SIGWINCH, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsigwinch);
2344 } else if (p == 0) {
2345 /* We create a grandchild to detach */
2346 if (flag & F_NOWAIT) {
2350 _exit(EXIT_SUCCESS);
2358 _exit(EXIT_FAILURE);
2361 /* So they can be used to stop the child */
2365 /* This is the parent waiting for the child to create grandchild */
2366 if (flag & F_NOWAIT)
2367 waitpid(p, NULL, 0);
2374 static int join(pid_t p, uchar_t flag)
2376 int status = 0xFFFF;
2378 if (!(flag & F_NOWAIT)) {
2379 /* wait for the child to exit */
2381 } while (waitpid(p, &status, 0) == -1);
2383 if (WIFEXITED(status)) {
2384 status = WEXITSTATUS(status);
2389 /* restore parent's signal handling */
2390 sigaction(SIGHUP, &oldsighup, NULL);
2391 sigaction(SIGTSTP, &oldsigtstp, NULL);
2392 sigaction(SIGWINCH, &oldsigwinch, NULL);
2398 * Spawns a child process. Behaviour can be controlled using flag.
2399 * Limited to 3 arguments to a program, flag works on bit set.
2401 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag)
2404 int status = 0, retstatus = 0xFFFF;
2405 char *argv[EXEC_ARGS_MAX] = {0};
2408 if (!file || !*file)
2411 /* Swap args if the first arg is NULL and the other 2 aren't */
2412 if (!arg1 && arg2) {
2421 if (flag & F_MULTI) {
2422 cmd = parseargs(file, argv, &status);
2426 argv[status++] = file;
2428 argv[status] = arg1;
2429 argv[++status] = arg2;
2430 argv[++status] = arg3;
2432 if (flag & F_NORMAL)
2437 /* Suppress stdout and stderr */
2438 if (flag & F_NOTRACE) {
2439 int fd = open("/dev/null", O_WRONLY, 0200);
2441 if (flag & F_NOSTDIN)
2442 dup2(fd, STDIN_FILENO);
2443 dup2(fd, STDOUT_FILENO);
2444 dup2(fd, STDERR_FILENO);
2446 } else if (flag & F_TTY) {
2447 /* If stdout has been redirected to a non-tty, force output to tty */
2448 if (!isatty(STDOUT_FILENO)) {
2449 int fd = open(ctermid(NULL), O_WRONLY, 0200);
2450 dup2(fd, STDOUT_FILENO);
2455 execvp(*argv, argv);
2456 _exit(EXIT_SUCCESS);
2458 retstatus = join(pid, flag);
2461 if ((flag & F_CONFIRM) || ((flag & F_CHKRTN) && retstatus)) {
2462 status = write(STDOUT_FILENO, messages[MSG_ENTER], xstrlen(messages[MSG_ENTER]));
2464 while ((read(STDIN_FILENO, &status, 1) > 0) && (status != '\n'));
2467 if (flag & F_NORMAL)
2476 /* Get program name from env var, else return fallback program */
2477 static char *xgetenv(const char * const name, char *fallback)
2479 char *value = getenv(name);
2481 return value && value[0] ? value : fallback;
2484 /* Checks if an env variable is set to 1 */
2485 static inline uint_t xgetenv_val(const char *name)
2487 char *str = getenv(name);
2495 /* Check if a dir exists, IS a dir, and is readable */
2496 static bool xdiraccess(const char *path)
2498 DIR *dirp = opendir(path);
2509 static bool plugscript(const char *plugin, uchar_t flags)
2511 mkpath(plgpath, plugin, g_buf);
2512 if (!access(g_buf, X_OK)) {
2513 spawn(g_buf, NULL, NULL, NULL, flags);
2520 static void opstr(char *buf, char *op)
2522 snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c '%s \"$0\" \"$@\" . < /dev/tty' < %s", op, selpath);
2525 static bool rmmulstr(char *buf)
2527 char r = confirm_force(TRUE);
2532 snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c 'rm -%cr \"$0\" \"$@\" < /dev/tty' < %s",
2535 snprintf(buf, CMD_LEN_MAX, "xargs -0 %s < %s",
2536 utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH], selpath);
2541 /* Returns TRUE if file is removed, else FALSE */
2542 static bool xrm(char * const fpath)
2544 char r = confirm_force(FALSE);
2548 if (!g_state.trash) {
2549 char rm_opts[] = "-ir";
2552 spawn("rm", rm_opts, fpath, NULL, F_NORMAL | F_CHKRTN);
2554 spawn(utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH],
2555 fpath, NULL, NULL, F_NORMAL | F_MULTI);
2557 return (access(fpath, F_OK) == -1); /* File is removed */
2560 static void xrmfromsel(char *path, char *fpath)
2563 bool selected = TRUE;
2566 if ((pdents[cur].flags & DIR_OR_DIRLNK) && scanselforpath(fpath, FALSE))
2568 else if (pdents[cur].flags & FILE_SELECTED) {
2570 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
2576 if (selected && cfg.x11)
2577 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
2581 static uint_t lines_in_file(int fd, char *buf, size_t buflen)
2586 while ((len = read(fd, buf, buflen)) > 0)
2588 count += (buf[--len] == '\n');
2590 /* For all use cases 0 linecount is considered as error */
2591 return ((len < 0) ? 0 : count);
2594 static bool cpmv_rename(int choice, const char *path)
2597 uint_t count = 0, lines = 0;
2599 char *cmd = (choice == 'c' ? cp : mv);
2600 char buf[sizeof(patterns[P_CPMVRNM]) + (MAX(sizeof(cp), sizeof(mv))) + (PATH_MAX << 1)];
2602 fd = create_tmp_file();
2606 /* selsafe() returned TRUE for this to be called */
2608 snprintf(buf, sizeof(buf), "tr '\\0' '\\n' < %s > %s", selpath, g_tmpfpath);
2609 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2611 count = lines_in_file(fd, buf, sizeof(buf));
2615 seltofile(fd, &count);
2619 snprintf(buf, sizeof(buf), patterns[P_CPMVFMT], g_tmpfpath);
2620 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2622 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2624 fd = open(g_tmpfpath, O_RDONLY);
2628 lines = lines_in_file(fd, buf, sizeof(buf));
2631 if (!lines || (2 * count != lines)) {
2632 DPRINTF_S("num mismatch");
2636 snprintf(buf, sizeof(buf), patterns[P_CPMVRNM], path, g_tmpfpath, cmd);
2637 if (!spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CHKRTN))
2646 static bool cpmvrm_selection(enum action sel, char *path)
2650 if (isselfileempty()) {
2653 printmsg(messages[MSG_0_SELECTED]);
2668 r = get_input(messages[MSG_CP_MV_AS]);
2669 if (r != 'c' && r != 'm') {
2670 printmsg(messages[MSG_INVALID_KEY]);
2674 if (!cpmv_rename(r, path)) {
2675 printmsg(messages[MSG_FAILED]);
2679 default: /* SEL_RM */
2680 if (!rmmulstr(g_buf)) {
2681 printmsg(messages[MSG_CANCEL]);
2686 if (sel != SEL_CPMVAS && spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CHKRTN)) {
2687 printmsg(messages[MSG_FAILED]);
2691 /* Clear selection */
2698 static bool batch_rename(void)
2701 uint_t count = 0, lines = 0;
2702 bool dir = FALSE, ret = FALSE;
2703 char foriginal[TMP_LEN_MAX] = {0};
2704 static const char batchrenamecmd[] = "paste -d'\n' %s %s | "SED" 'N; /^\\(.*\\)\\n\\1$/!p;d' | "
2705 "tr '\n' '\\0' | xargs -0 -n2 sh -c 'mv -i \"$0\" \"$@\" <"
2707 char buf[sizeof(batchrenamecmd) + (PATH_MAX << 1)];
2708 int i = get_cur_or_sel();
2713 if (i == 'c') { /* Rename entries in current dir */
2718 fd1 = create_tmp_file();
2722 xstrsncpy(foriginal, g_tmpfpath, xstrlen(g_tmpfpath) + 1);
2724 fd2 = create_tmp_file();
2732 for (i = 0; i < ndents; ++i)
2733 appendfpath(pdents[i].name, NAME_MAX);
2735 seltofile(fd1, &count);
2736 seltofile(fd2, NULL);
2739 if (dir) /* Don't retain dir entries in selection */
2742 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2744 /* Reopen file descriptor to get updated contents */
2745 fd2 = open(g_tmpfpath, O_RDONLY);
2749 lines = lines_in_file(fd2, buf, sizeof(buf));
2752 if (!lines || (count != lines)) {
2753 DPRINTF_S("cannot delete files");
2757 snprintf(buf, sizeof(buf), batchrenamecmd, foriginal, g_tmpfpath);
2758 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2774 static char *get_archive_cmd(const char *archive)
2778 if (!g_state.usebsdtar && getutil(utils[UTIL_ATOOL]))
2780 else if (getutil(utils[UTIL_BSDTAR]))
2782 else if (is_suffix(archive, ".zip"))
2786 return archive_cmd[i];
2789 static void archive_selection(const char *cmd, const char *archive)
2791 char *buf = malloc((xstrlen(patterns[P_ARCHIVE_CMD]) + xstrlen(cmd) + xstrlen(archive)
2792 + xstrlen(selpath)) * sizeof(char));
2794 DPRINTF_S(strerror(errno));
2799 snprintf(buf, CMD_LEN_MAX, patterns[P_ARCHIVE_CMD], cmd, archive, selpath);
2800 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CONFIRM);
2804 static void write_lastdir(const char *curpath, const char *outfile)
2808 xstrsncpy(cfgpath + xstrlen(cfgpath), "/.lastd", 8);
2810 tilde = convert_tilde(outfile, g_buf);
2812 int fd = open(outfile
2813 ? (tilde ? g_buf : outfile)
2814 : cfgpath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
2816 if (fd != -1 && shell_escape(g_buf, sizeof(g_buf), curpath)) {
2817 dprintf(fd, "cd %s", g_buf);
2823 * We assume none of the strings are NULL.
2825 * Let's have the logic to sort numeric names in numeric order.
2826 * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
2828 * If the absolute numeric values are same, we fallback to alphasort.
2830 static int xstricmp(const char * const s1, const char * const s2)
2834 long long v1 = strtoll(s1, &p1, 10);
2835 long long v2 = strtoll(s2, &p2, 10);
2837 /* Check if at least 1 string is numeric */
2838 if (s1 != p1 || s2 != p2) {
2839 /* Handle both pure numeric */
2840 if (s1 != p1 && s2 != p2) {
2848 /* Only first string non-numeric */
2852 /* Only second string non-numeric */
2857 /* Handle 1. all non-numeric and 2. both same numeric value cases */
2859 return strcoll(s1, s2);
2861 return strcasecmp(s1, s2);
2866 * Version comparison
2868 * The code for version compare is a modified version of the GLIBC
2869 * and uClibc implementation of strverscmp(). The source is here:
2870 * https://elixir.bootlin.com/uclibc-ng/latest/source/libc/string/strverscmp.c
2874 * Compare S1 and S2 as strings holding indices/version numbers,
2875 * returning less than, equal to or greater than zero if S1 is less than,
2876 * equal to or greater than S2 (for more info, see the texinfo doc).
2880 static int xstrverscasecmp(const char * const s1, const char * const s2)
2882 const uchar_t *p1 = (const uchar_t *)s1;
2883 const uchar_t *p2 = (const uchar_t *)s2;
2888 * Symbol(s) 0 [1-9] others
2889 * Transition (10) 0 (01) d (00) x
2891 static const uint8_t next_state[] = {
2893 /* S_N */ S_N, S_I, S_Z,
2894 /* S_I */ S_N, S_I, S_I,
2895 /* S_F */ S_N, S_F, S_F,
2896 /* S_Z */ S_N, S_F, S_Z
2899 alignas(max_align_t) static const int8_t result_type[] = {
2900 /* state x/x x/d x/0 d/x d/d d/0 0/x 0/d 0/0 */
2902 /* S_N */ VCMP, VCMP, VCMP, VCMP, VLEN, VCMP, VCMP, VCMP, VCMP,
2903 /* S_I */ VCMP, -1, -1, 1, VLEN, VLEN, 1, VLEN, VLEN,
2904 /* S_F */ VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP,
2905 /* S_Z */ VCMP, 1, 1, -1, VCMP, VCMP, -1, VCMP, VCMP
2916 /* Hint: '0' is a digit too. */
2917 state = S_N + ((c1 == '0') + (xisdigit(c1) != 0));
2919 while ((diff = c1 - c2) == 0) {
2923 state = next_state[state];
2928 state += (c1 == '0') + (xisdigit(c1) != 0);
2931 state = result_type[state * 3 + (((c2 == '0') + (xisdigit(c2) != 0)))]; // NOLINT
2937 while (xisdigit(*p1++))
2938 if (!xisdigit(*p2++))
2940 return xisdigit(*p2) ? -1 : diff;
2946 static int (*namecmpfn)(const char * const s1, const char * const s2) = &xstricmp;
2948 static char * (*fnstrstr)(const char *haystack, const char *needle) = &strcasestr;
2950 static const unsigned char *tables;
2951 static int pcreflags = PCRE_NO_AUTO_CAPTURE | PCRE_EXTENDED | PCRE_CASELESS | PCRE_UTF8;
2953 static int regflags = REG_NOSUB | REG_EXTENDED | REG_ICASE;
2957 static int setfilter(pcre **pcrex, const char *filter)
2959 const char *errstr = NULL;
2962 *pcrex = pcre_compile(filter, pcreflags, &errstr, &erroffset, tables);
2964 return errstr ? -1 : 0;
2967 static int setfilter(regex_t *regex, const char *filter)
2969 return regcomp(regex, filter, regflags);
2973 static int visible_re(const fltrexp_t *fltrexp, const char *fname)
2976 return pcre_exec(fltrexp->pcrex, NULL, fname, xstrlen(fname), 0, 0, NULL, 0) == 0;
2978 return regexec(fltrexp->regex, fname, 0, NULL, 0) == 0;
2982 static int visible_str(const fltrexp_t *fltrexp, const char *fname)
2984 return fnstrstr(fname, fltrexp->str) != NULL;
2987 static int (*filterfn)(const fltrexp_t *fltr, const char *fname) = &visible_str;
2989 static void clearfilter(void)
2991 char * const fltr = g_ctx[cfg.curctx].c_fltr;
2994 fltr[REGEX_MAX - 1] = fltr[1];
2999 static int entrycmp(const void *va, const void *vb)
3001 const struct entry *pa = (pEntry)va;
3002 const struct entry *pb = (pEntry)vb;
3004 if ((pb->flags & DIR_OR_DIRLNK) != (pa->flags & DIR_OR_DIRLNK)) {
3005 if (pb->flags & DIR_OR_DIRLNK)
3010 /* Sort based on specified order */
3011 if (cfg.timeorder) {
3012 if (pb->sec > pa->sec)
3014 if (pb->sec < pa->sec)
3016 /* If sec matches, comare nsec */
3017 if (pb->nsec > pa->nsec)
3019 if (pb->nsec < pa->nsec)
3021 } else if (cfg.sizeorder) {
3022 if (pb->size > pa->size)
3024 if (pb->size < pa->size)
3026 } else if (cfg.blkorder) {
3027 if (pb->blocks > pa->blocks)
3029 if (pb->blocks < pa->blocks)
3031 } else if (cfg.extnorder && !(pb->flags & DIR_OR_DIRLNK)) {
3032 char *extna = xextension(pa->name, pa->nlen - 1);
3033 char *extnb = xextension(pb->name, pb->nlen - 1);
3035 if (extna || extnb) {
3042 int ret = strcasecmp(extna, extnb);
3049 return namecmpfn(pa->name, pb->name);
3052 static int reventrycmp(const void *va, const void *vb)
3054 if ((((pEntry)vb)->flags & DIR_OR_DIRLNK)
3055 != (((pEntry)va)->flags & DIR_OR_DIRLNK)) {
3056 if (((pEntry)vb)->flags & DIR_OR_DIRLNK)
3061 return -entrycmp(va, vb);
3064 static int (*entrycmpfn)(const void *va, const void *vb) = &entrycmp;
3066 /* In case of an error, resets *wch to Esc */
3067 static int handle_alt_key(wint_t *wch)
3071 int r = get_wch(wch);
3080 static inline int handle_event(void)
3082 if (nselected && isselfileempty())
3084 return CONTROL('L');
3088 * Returns SEL_* if key is bound and 0 otherwise.
3089 * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
3090 * The next keyboard input can be simulated by presel.
3092 static int nextsel(int presel)
3099 bool escaped = FALSE;
3101 if (c == 0 || c == MSGWAIT) {
3105 //DPRINTF_S(keyname(c));
3108 if (c == KEY_RESIZE)
3109 handle_key_resize();
3112 /* Handle Alt+key */
3124 } else if (escaped) {
3129 if (!g_state.fifomode)
3130 notify_fifo(TRUE); /* Send hovered path to NNN_FIFO */
3138 if (i == ERR && presel == MSGWAIT)
3139 c = (cfg.filtermode || filterset()) ? FILTER : CONTROL('L');
3140 else if (c == FILTER || c == CONTROL('L'))
3141 /* Clear previous filter when manually starting */
3149 * Do not check for directory changes in du mode.
3150 * A redraw forces du calculation.
3151 * Check for changes every odd second.
3153 #ifdef LINUX_INOTIFY
3154 if (!cfg.blkorder && inotify_wd >= 0 && (idle & 1)) {
3155 struct inotify_event *event;
3156 char inotify_buf[EVENT_BUF_LEN] = {0};
3158 i = read(inotify_fd, inotify_buf, EVENT_BUF_LEN);
3160 for (char *ptr = inotify_buf;
3161 ptr + ((struct inotify_event *)ptr)->len < inotify_buf + i;
3162 ptr += sizeof(struct inotify_event) + event->len) {
3163 event = (struct inotify_event *)ptr;
3164 DPRINTF_D(event->wd);
3165 DPRINTF_D(event->mask);
3169 if (event->mask & INOTIFY_MASK) {
3174 DPRINTF_S("inotify read done");
3177 #elif defined(BSD_KQUEUE)
3178 if (!cfg.blkorder && event_fd >= 0 && (idle & 1)) {
3179 struct kevent event_data[NUM_EVENT_SLOTS] = {0};
3181 if (kevent(kq, events_to_monitor, NUM_EVENT_SLOTS,
3182 event_data, NUM_EVENT_FDS, >imeout) > 0)
3185 #elif defined(HAIKU_NM)
3186 if (!cfg.blkorder && haiku_nm_active && (idle & 1) && haiku_is_update_needed(haiku_hnd))
3192 for (i = 0; i < (int)ELEMENTS(bindings); ++i)
3193 if (c == bindings[i].sym)
3194 return bindings[i].act;
3199 static int getorderstr(char *sort)
3207 sort[i++] = (cfg.timetype == T_MOD) ? 'M' : ((cfg.timetype == T_ACCESS) ? 'A' : 'C');
3208 else if (cfg.sizeorder)
3210 else if (cfg.extnorder)
3213 if (entrycmpfn == &reventrycmp)
3216 if (namecmpfn == &xstrverscasecmp)
3225 static void showfilterinfo(void)
3228 char info[REGEX_MAX] = "\0\0\0\0\0";
3230 i = getorderstr(info);
3232 if (cfg.fileinfo && ndents && get_output("file", "-b", pdents[cur].name, -1, FALSE))
3233 mvaddstr(xlines - 2, 2, g_buf);
3235 snprintf(info + i, REGEX_MAX - i - 1, " %s [/], %4s [:]",
3236 (cfg.regex ? "reg" : "str"),
3237 ((fnstrstr == &strcasestr) ? "ic" : "noic"));
3240 mvaddstr(xlines - 2, xcols - xstrlen(info), info);
3243 static void showfilter(char *str)
3245 attron(COLOR_PAIR(cfg.curctx + 1));
3248 // printmsg calls attroff()
3251 static inline void swap_ent(int id1, int id2)
3253 struct entry _dent, *pdent1 = &pdents[id1], *pdent2 = &pdents[id2];
3255 *(&_dent) = *pdent1;
3257 *pdent2 = *(&_dent);
3261 static int fill(const char *fltr, pcre *pcrex)
3263 static int fill(const char *fltr, regex_t *re)
3267 fltrexp_t fltrexp = { .pcrex = pcrex, .str = fltr };
3269 fltrexp_t fltrexp = { .regex = re, .str = fltr };
3272 for (int count = 0; count < ndents; ++count) {
3273 if (filterfn(&fltrexp, pdents[count].name) == 0) {
3274 if (count != --ndents) {
3275 swap_ent(count, ndents);
3286 static int matches(const char *fltr)
3292 if (cfg.regex && setfilter(&pcrex, fltr))
3295 ndents = fill(fltr, pcrex);
3303 if (cfg.regex && setfilter(&re, fltr))
3306 ndents = fill(fltr, &re);
3312 ENTSORT(pdents, ndents, entrycmpfn);
3318 * Return the position of the matching entry or 0 otherwise
3319 * Note there's no NULL check for fname
3321 static int dentfind(const char *fname, int n)
3323 for (int i = 0; i < n; ++i)
3324 if (xstrcmp(fname, pdents[i].name) == 0)
3330 static int filterentries(char *path, char *lastname)
3332 alignas(max_align_t) wchar_t wln[REGEX_MAX];
3333 char *ln = g_ctx[cfg.curctx].c_fltr;
3335 int r, total = ndents, len;
3336 char *pln = g_ctx[cfg.curctx].c_fltr + 1;
3338 DPRINTF_S(__func__);
3340 if (ndents && (ln[0] == FILTER || ln[0] == RFILTER) && *pln) {
3341 if (matches(pln) != -1) {
3342 move_cursor(dentfind(lastname, ndents), 0);
3346 if (!cfg.filtermode) {
3351 len = mbstowcs(wln, ln, REGEX_MAX);
3353 ln[0] = wln[0] = cfg.regex ? RFILTER : FILTER;
3354 ln[1] = wln[1] = '\0';
3362 while ((r = get_wch(ch)) != ERR) {
3364 //DPRINTF_S(keyname(*ch));
3368 case 0: // fallthrough
3375 case KEY_DC: // fallthrough
3376 case KEY_BACKSPACE: // fallthrough
3377 case '\b': // fallthrough
3378 case DEL: /* handle DEL */
3381 wcstombs(ln, wln, REGEX_MAX);
3389 if (*ch == CONTROL('L')) {
3391 ln[REGEX_MAX - 1] = ln[1];
3392 ln[1] = wln[1] = '\0';
3395 } else if (ln[REGEX_MAX - 1]) { /* Show the previous filter */
3396 ln[1] = ln[REGEX_MAX - 1];
3397 ln[REGEX_MAX - 1] = '\0';
3398 len = mbstowcs(wln, ln, REGEX_MAX);
3403 /* Go to the top, we don't know if the hovered file will match the filter */
3406 if (matches(pln) != -1)
3416 if (handle_alt_key(ch) != ERR) {
3417 if (*ch == ESC) /* Handle Alt+Esc */
3418 *ch = 'q'; /* Quit context */
3421 *ch = ';'; /* Run plugin */
3427 if (r != OK) /* Handle Fn keys in main loop */
3430 /* Handle all control chars in main loop */
3431 if (*ch < ASCII_MAX && keyname(*ch)[0] == '^' && *ch != '^')
3435 if (*ch == '?') /* Help and config key, '?' is an invalid regex */
3438 if (cfg.filtermode) {
3440 case '\'': // fallthrough /* Go to first non-dir file */
3441 case '+': // fallthrough /* Toggle file selection */
3442 case ',': // fallthrough /* Mark CWD */
3443 case '-': // fallthrough /* Visit last visited dir */
3444 case '.': // fallthrough /* Show hidden files */
3445 case ';': // fallthrough /* Run plugin key */
3446 case '=': // fallthrough /* Launch app */
3447 case '>': // fallthrough /* Export file list */
3448 case '@': // fallthrough /* Visit start dir */
3449 case ']': // fallthorugh /* Prompt key */
3450 case '`': // fallthrough /* Visit / */
3451 case '~': /* Go HOME */
3456 /* Toggle case-sensitivity */
3458 fnstrstr = (fnstrstr == &strcasestr) ? &strstr : &strcasestr;
3460 pcreflags ^= PCRE_CASELESS;
3462 regflags ^= REG_ICASE;
3468 /* Toggle string or regex filter */
3469 if (*ch == FILTER) {
3470 ln[0] = (ln[0] == FILTER) ? RFILTER : FILTER;
3471 wln[0] = (uchar_t)ln[0];
3473 filterfn = cfg.regex ? &visible_re : &visible_str;
3478 /* Reset cur in case it's a repeat search */
3480 } else if (len == REGEX_MAX - 1)
3483 wln[len] = (wchar_t)*ch;
3485 wcstombs(ln, wln, REGEX_MAX);
3487 /* Forward-filtering optimization:
3488 * - new matches can only be a subset of current matches.
3490 /* ndents = total; */
3494 !r ? unget_wch(KEY_BACKSPACE) : showfilter(ln);
3496 if (matches(pln) == -1) {
3502 /* If the only match is a dir, auto-enter and cd into it */
3503 if ((ndents == 1) && cfg.autoenter && (pdents[0].flags & DIR_OR_DIRLNK)) {
3510 * redraw() should be above the auto-enter optimization, for
3511 * the case where there's an issue with dir auto-enter, say,
3512 * due to a permission problem. The transition is _jumpy_ in
3513 * case of such an error. However, we optimize for successful
3514 * cases where the dir has permissions. This skips a redraw().
3521 /* Save last working filter in-filter */
3523 ln[REGEX_MAX - 1] = ln[1];
3531 /* Return keys for navigation etc. */
3535 /* Show a prompt with input string and return the changes */
3536 static char *xreadline(const char *prefill, const char *prompt)
3540 const int WCHAR_T_WIDTH = sizeof(wchar_t);
3542 wchar_t * const buf = malloc(sizeof(wchar_t) * READLINE_MAX);
3552 len = pos = mbstowcs(buf, prefill, READLINE_MAX);
3556 if (len == (size_t)-1) {
3561 x = getcurx(stdscr);
3566 attron(COLOR_PAIR(cfg.curctx + 1));
3567 if (pos > (size_t)(xcols - x)) {
3568 mvaddnwstr(xlines - 1, x, buf + (pos - (xcols - x) + 1), xcols - x);
3569 move(xlines - 1, xcols - 1);
3571 mvaddnwstr(xlines - 1, x, buf, len + 1);
3572 move(xlines - 1, x + wcswidth(buf, pos));
3574 attroff(COLOR_PAIR(cfg.curctx + 1));
3582 case KEY_ENTER: // fallthrough
3583 case '\n': // fallthrough
3589 else if (!(pos || len)) { /* Exit on ^D at empty prompt */
3595 case DEL: // fallthrough
3596 case '\b': /* rhel25 sends '\b' for backspace */
3598 memmove(buf + pos - 1, buf + pos,
3599 (len - pos) * WCHAR_T_WIDTH);
3604 if (!(len || pos) && ndents)
3605 len = pos = mbstowcs(buf, pdents[cur].name, READLINE_MAX);
3620 memmove(buf + pos - 1, buf + pos,
3621 (len - pos) * WCHAR_T_WIDTH);
3623 } while (buf[pos - 1] != ' ' && buf[pos - 1] != '/'); // NOLINT
3641 memmove(buf, buf + pos, (len - pos) * WCHAR_T_WIDTH);
3645 case ESC: /* Exit prompt on Esc, but just filter out Alt+key */
3646 if (handle_alt_key(ch) != ERR)
3653 /* Filter out all other control chars */
3654 if (*ch < ASCII_MAX && keyname(*ch)[0] == '^')
3657 if (pos < READLINE_MAX - 1) {
3658 memmove(buf + pos + 1, buf + pos,
3659 (len - pos) * WCHAR_T_WIDTH);
3683 memmove(buf + pos - 1, buf + pos,
3684 (len - pos) * WCHAR_T_WIDTH);
3690 memmove(buf + pos, buf + pos + 1,
3691 (len - pos - 1) * WCHAR_T_WIDTH);
3701 case KEY_UP: // fallthrough
3703 if (prompt && lastcmd && (xstrcmp(prompt, PROMPT) == 0)) {
3705 len = pos = mbstowcs(buf, lastcmd, READLINE_MAX); // fallthrough
3720 pos = wcstombs(g_buf, buf, READLINE_MAX - 1);
3721 if (pos >= READLINE_MAX - 1)
3722 g_buf[READLINE_MAX - 1] = '\0';
3730 * Caller should check the value of presel to confirm if it needs to wait to show warning
3732 static char *getreadline(const char *prompt)
3736 char *input = readline(prompt);
3740 if (input && input[0]) {
3742 xstrsncpy(g_buf, input, CMD_LEN_MAX);
3753 * Create symbolic/hard link(s) to file(s) in selection list
3754 * Returns the number of links created, -1 on error
3756 static int xlink(char *prefix, char *path, char *curfname, char *buf, int type)
3758 int count = 0, choice;
3759 char *psel = pselbuf, *fname;
3760 size_t pos = 0, len, r;
3761 int (*link_fn)(const char *, const char *) = NULL;
3762 char lnpath[PATH_MAX];
3764 choice = get_cur_or_sel();
3768 if (type == 's') /* symbolic link */
3770 else /* hard link */
3773 if (choice == 'c' || (nselected == 1)) {
3774 prefix = abspath(prefix, path, lnpath); /* Generate link path */
3779 mkpath(path, curfname, buf); /* Generate target file path */
3781 if (!link_fn((choice == 'c') ? buf : pselbuf, lnpath)) {
3784 return 1; /* One link created */
3789 r = xstrsncpy(buf, prefix, NAME_MAX + 1); /* Copy prefix */
3791 while (pos < selbufpos) {
3792 len = xstrlen(psel);
3793 fname = xbasename(psel);
3795 xstrsncpy(buf + r - 1, fname, NAME_MAX - r); /* Suffix target file name */
3796 mkpath(path, buf, lnpath); /* Generate link path */
3798 if (!link_fn(psel, lnpath))
3805 if (count == nselected) /* Clear selection if all links are generated */
3810 static bool parsekvpair(kv **arr, char **envcpy, const uchar_t id, uchar_t *items)
3813 const uchar_t INCR = 8;
3816 char *ptr = getenv(env_cfg[id]);
3821 *envcpy = xstrdup(ptr);
3829 while (*ptr && i < 100) {
3831 if (!(i & (INCR - 1))) {
3832 kvarr = xrealloc(kvarr, sizeof(kv) * (i + INCR));
3838 memset(kvarr + i, 0, sizeof(kv) * INCR);
3840 kvarr[i].key = (uchar_t)*ptr;
3841 if (*++ptr != ':' || *++ptr == '\0' || *ptr == ';')
3843 kvarr[i].off = ptr - *envcpy;
3862 * Get the value corresponding to a key
3864 * NULL is returned in case of no match, path resolution failure etc.
3865 * buf would be modified, so check return value before access
3867 static char *get_kv_val(kv *kvarr, char *buf, int key, uchar_t max, uchar_t id)
3874 for (int r = 0; r < max && kvarr[r].key; ++r) {
3875 if (kvarr[r].key == key) {
3876 /* Do not allocate new memory for plugin */
3878 return pluginstr + kvarr[r].off;
3880 val = bmstr + kvarr[r].off;
3881 bool tilde = convert_tilde(val, g_buf);
3882 return abspath((tilde ? g_buf : val), NULL, buf);
3886 DPRINTF_S("Invalid key");
3890 static int get_kv_key(kv *kvarr, char *val, uchar_t max, uchar_t id)
3895 if (id != NNN_ORDER) /* For now this function supports only order string */
3898 for (int r = 0; r < max && kvarr[r].key; ++r) {
3899 if (xstrcmp((orderstr + kvarr[r].off), val) == 0)
3900 return kvarr[r].key;
3906 static void resetdircolor(int flags)
3908 /* Directories are always shown on top, clear the color when moving to first file */
3909 if (g_state.dircolor && !(flags & DIR_OR_DIRLNK)) {
3910 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
3911 g_state.dircolor = 0;
3916 * Replace escape characters in a string with '?'
3917 * Adjust string length to maxcols if > 0;
3918 * Max supported str length: NAME_MAX;
3921 static char *unescape(const char *str, uint_t maxcols)
3923 char * const wbuf = g_buf;
3926 xstrsncpy(wbuf, str, maxcols);
3928 static wchar_t *unescape(const char *str, uint_t maxcols)
3930 wchar_t * const wbuf = (wchar_t *)g_buf;
3931 wchar_t *buf = wbuf;
3932 size_t len = mbstowcs(wbuf, str, maxcols); /* Convert multi-byte to wide char */
3934 len = wcswidth(wbuf, len);
3936 if (len >= maxcols) {
3937 size_t lencount = maxcols;
3939 while (len > maxcols) /* Reduce wide chars one by one till it fits */
3940 len = wcswidth(wbuf, --lencount);
3942 wbuf[lencount] = L'\0';
3947 if (*buf <= '\x1f' || *buf == '\x7f')
3956 static off_t get_size(off_t size, off_t *pval, int comp)
3959 off_t quo = rem / 10;
3961 if ((rem - (quo * 10)) >= 5) {
3974 static char *coolsize(off_t size)
3976 const char * const U = "BKMGTPEZY";
3977 static char size_buf[12]; /* Buffer to hold human readable size */
3982 while (size >= 1024) {
3983 rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
3989 rem = (rem * 1000) >> 10;
3991 size = get_size(size, &rem, 10);
3992 } else if (i == 2) {
3993 rem = (rem * 1000) >> 10;
3994 size = get_size(size, &rem, 100);
3996 rem = (rem * 10000) >> 10;
3997 size = get_size(size, &rem, 1000);
4000 if (i > 0 && i < 6 && rem) {
4001 ret = xstrsncpy(size_buf, xitoa(size), 12);
4002 size_buf[ret - 1] = '.';
4004 char *frac = xitoa(rem);
4005 size_t toprint = i > 3 ? 3 : i;
4006 size_t len = xstrlen(frac);
4008 if (len < toprint) {
4009 size_buf[ret] = size_buf[ret + 1] = size_buf[ret + 2] = '0';
4010 xstrsncpy(size_buf + ret + (toprint - len), frac, len + 1);
4012 xstrsncpy(size_buf + ret, frac, toprint + 1);
4016 ret = xstrsncpy(size_buf, size ? xitoa(size) : "0", 12);
4020 size_buf[ret] = U[i];
4021 size_buf[ret + 1] = '\0';
4026 /* Convert a mode field into "ls -l" type perms field. */
4027 static char *get_lsperms(mode_t mode)
4029 static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
4030 static char bits[11] = {'\0'};
4032 switch (mode & S_IFMT) {
4059 xstrsncpy(&bits[1], rwx[(mode >> 6) & 7], 4);
4060 xstrsncpy(&bits[4], rwx[(mode >> 3) & 7], 4);
4061 xstrsncpy(&bits[7], rwx[(mode & 7)], 4);
4064 bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
4066 bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
4068 bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
4073 #ifdef ICONS_ENABLED
4074 static struct icon get_icon(const struct entry *ent)
4076 for (size_t i = 0; i < ELEMENTS(icons_name); ++i)
4077 if (strcasecmp(ent->name, icons_name[i].match) == 0)
4078 return (struct icon){ icons_name[i].icon, icons_name[i].color };
4080 if (ent->flags & DIR_OR_DIRLNK)
4083 char *tmp = xextension(ent->name, ent->nlen);
4086 uint16_t z, k, h = icon_ext_hash(++tmp); /* ++tmp to skip '.' */
4087 for (k = 0; k < ICONS_PROBE_MAX; ++k) {
4088 z = (h + k) % ELEMENTS(icons_ext);
4089 if (strcasecmp(tmp, icons_ext[z].match) == 0)
4090 return (struct icon){ icons_ext_uniq[icons_ext[z].idx], icons_ext[z].color };
4094 /* If there's no match and the file is executable, icon that */
4095 if (ent->mode & 0100)
4100 static void print_icon(const struct entry *ent, const int attrs)
4102 const struct icon icon = get_icon(ent);
4103 addstr(ICON_PADDING_LEFT);
4105 attron(COLOR_PAIR(C_UND + 1 + icon.color));
4110 attroff(COLOR_PAIR(C_UND + 1 + icon.color));
4113 addstr(ICON_PADDING_RIGHT);
4117 static void print_time(const time_t *timep, const uchar_t flags)
4121 /* Highlight timestamp for entries 5 minutes young */
4122 if (flags & FILE_YOUNG)
4125 localtime_r(timep, &t);
4126 printw("%s-%02d-%02d %02d:%02d",
4127 xitoa(t.tm_year + 1900), t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min);
4129 if (flags & FILE_YOUNG)
4133 static char get_detail_ind(const mode_t mode)
4135 switch (mode & S_IFMT) {
4136 case S_IFDIR: // fallthrough
4137 case S_IFREG: return ' ';
4138 case S_IFLNK: return '@';
4139 case S_IFSOCK: return '=';
4140 case S_IFIFO: return '|';
4141 case S_IFBLK: return 'b';
4142 case S_IFCHR: return 'c';
4147 /* Note: attribute and indicator values must be initialized to 0 */
4148 static uchar_t get_color_pair_name_ind(const struct entry *ent, char *pind, int *pattr)
4150 switch (ent->mode & S_IFMT) {
4153 if (ent->mode & 0100)
4157 if (ent->flags & HARD_LINK) {
4158 if (ent->mode & 0100)
4162 if (ent->mode & 0100) {
4169 if (g_state.oldcolor)
4172 return g_state.dirctx ? cfg.curctx + 1 : C_DIR;
4174 if (ent->flags & DIR_OR_DIRLNK) {
4176 *pattr |= g_state.oldcolor ? A_DIM : A_BOLD;
4179 if (g_state.oldcolor)
4182 if (!g_state.oldcolor || cfg.showdetail)
4183 return (ent->flags & SYM_ORPHAN) ? C_ORP : C_LNK;
4201 static void printent(const struct entry *ent, uint_t namecols, bool sel)
4206 if (cfg.showdetail) {
4207 int type = ent->mode & S_IFMT;
4208 char perms[6] = {' ', ' ', (char)('0' + ((ent->mode >> 6) & 7)),
4209 (char)('0' + ((ent->mode >> 3) & 7)),
4210 (char)('0' + (ent->mode & 7)), '\0'};
4213 attrs = g_state.oldcolor ? (resetdircolor(ent->flags), A_DIM)
4214 : (fcolors[C_MIS] ? COLOR_PAIR(C_MIS) : 0);
4219 print_time(&ent->sec, ent->flags);
4221 printw("%s%9s ", perms, (type == S_IFREG || type == S_IFDIR)
4222 ? coolsize(cfg.blkorder ? (blkcnt_t)ent->blocks << blk_shift : ent->size)
4223 : (type = (uchar_t)get_detail_ind(ent->mode), (char *)&type));
4231 uchar_t color_pair = get_color_pair_name_ind(ent, &ind, &attrs);
4233 addch((ent->flags & FILE_SELECTED) ? '+' | A_REVERSE | A_BOLD : ' ');
4235 if (g_state.oldcolor)
4236 resetdircolor(ent->flags);
4238 if (ent->flags & FILE_MISSING)
4240 if (color_pair && fcolors[color_pair])
4241 attrs |= COLOR_PAIR(color_pair);
4242 #ifdef ICONS_ENABLED
4243 print_icon(ent, attrs);
4255 addwstr(unescape(ent->name, namecols));
4257 addstr(unescape(ent->name, MIN(namecols, ent->nlen) + 1));
4266 static void savecurctx(char *path, char *curname, int nextctx)
4268 settings tmpcfg = cfg;
4269 context *ctxr = &g_ctx[nextctx];
4271 /* Save current context */
4273 xstrsncpy(g_ctx[tmpcfg.curctx].c_name, curname, NAME_MAX + 1);
4275 g_ctx[tmpcfg.curctx].c_name[0] = '\0';
4277 g_ctx[tmpcfg.curctx].c_cfg = tmpcfg;
4279 if (ctxr->c_cfg.ctxactive) { /* Switch to saved context */
4280 tmpcfg = ctxr->c_cfg;
4281 /* Skip ordering an open context */
4283 cfgsort[CTX_MAX] = cfgsort[nextctx];
4284 cfgsort[nextctx] = '0';
4286 } else { /* Set up a new context from current context */
4287 ctxr->c_cfg.ctxactive = 1;
4288 xstrsncpy(ctxr->c_path, path, PATH_MAX);
4289 ctxr->c_last[0] = ctxr->c_name[0] = ctxr->c_fltr[0] = ctxr->c_fltr[1] = '\0';
4290 ctxr->c_cfg = tmpcfg;
4291 /* If already in an ordered dir, clear ordering for the new context and let it order */
4292 if (cfgsort[cfg.curctx] == 'z')
4293 cfgsort[nextctx] = 'z';
4296 tmpcfg.curctx = nextctx;
4301 static void save_session(const char *sname, int *presel)
4304 session_header_t header = {0};
4305 bool status = FALSE;
4306 char ssnpath[PATH_MAX];
4307 char spath[PATH_MAX];
4309 header.ver = SESSIONS_VERSION;
4311 for (i = 0; i < CTX_MAX; ++i) {
4312 if (g_ctx[i].c_cfg.ctxactive) {
4313 if (cfg.curctx == i && ndents)
4314 /* Update current file name, arrows don't update it */
4315 xstrsncpy(g_ctx[i].c_name, pdents[cur].name, NAME_MAX + 1);
4316 header.pathln[i] = MIN(xstrlen(g_ctx[i].c_path), PATH_MAX) + 1;
4317 header.lastln[i] = MIN(xstrlen(g_ctx[i].c_last), PATH_MAX) + 1;
4318 header.nameln[i] = MIN(xstrlen(g_ctx[i].c_name), NAME_MAX) + 1;
4319 header.fltrln[i] = REGEX_MAX;
4323 mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4324 mkpath(ssnpath, sname, spath);
4326 fd = open(spath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
4328 printwait(messages[MSG_SEL_MISSING], presel);
4332 if ((write(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4333 || (write(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4336 for (i = 0; i < CTX_MAX; ++i)
4337 if ((write(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4338 || (write(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4339 || (header.nameln[i] > 0
4340 && write(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4341 || (header.lastln[i] > 0
4342 && write(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4343 || (header.fltrln[i] > 0
4344 && write(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4345 || (header.pathln[i] > 0
4346 && write(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4355 printwait(messages[MSG_FAILED], presel);
4358 static bool load_session(const char *sname, char **path, char **lastdir, char **lastname, bool restore)
4361 session_header_t header;
4362 bool has_loaded_dynamically = !(sname || restore);
4363 bool status = (sname && g_state.picker); /* Picker mode with session program option */
4364 char ssnpath[PATH_MAX];
4365 char spath[PATH_MAX];
4367 mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4370 sname = sname ? sname : xreadline(NULL, messages[MSG_SSN_NAME]);
4374 mkpath(ssnpath, sname, spath);
4376 /* If user is explicitly loading the "last session", skip auto-save */
4377 if ((sname[0] == '@') && !sname[1])
4378 has_loaded_dynamically = FALSE;
4380 mkpath(ssnpath, "@", spath);
4382 if (has_loaded_dynamically)
4383 save_session("@", NULL);
4385 fd = open(spath, O_RDONLY, S_IWUSR | S_IRUSR);
4388 printmsg(messages[MSG_SEL_MISSING]);
4389 xdelay(XDELAY_INTERVAL_MS);
4396 if ((read(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4397 || (header.ver != SESSIONS_VERSION)
4398 || (read(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4401 g_ctx[cfg.curctx].c_name[0] = g_ctx[cfg.curctx].c_last[0]
4402 = g_ctx[cfg.curctx].c_fltr[0] = g_ctx[cfg.curctx].c_fltr[1] = '\0';
4404 for (; i < CTX_MAX; ++i)
4405 if ((read(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4406 || (read(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4407 || (header.nameln[i] > 0
4408 && read(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4409 || (header.lastln[i] > 0
4410 && read(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4411 || (header.fltrln[i] > 0
4412 && read(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4413 || (header.pathln[i] > 0
4414 && read(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4417 *path = g_ctx[cfg.curctx].c_path;
4418 *lastdir = g_ctx[cfg.curctx].c_last;
4419 *lastname = g_ctx[cfg.curctx].c_name;
4420 set_sort_flags('\0'); /* Set correct sort options */
4427 printmsg(messages[MSG_FAILED]);
4428 xdelay(XDELAY_INTERVAL_MS);
4436 static uchar_t get_free_ctx(void)
4438 uchar_t r = cfg.curctx;
4441 r = (r + 1) & ~CTX_MAX;
4442 while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
4447 /* ctx is absolute: 1 to 4, + for smart context */
4448 static void set_smart_ctx(int ctx, char *nextpath, char **path, char *file, char **lastname, char **lastdir)
4450 if (ctx == '+') /* Get smart context */
4451 ctx = (int)(get_free_ctx() + 1);
4453 if (ctx == 0 || ctx == cfg.curctx + 1) { /* Same context */
4455 xstrsncpy(*lastdir, *path, PATH_MAX);
4456 xstrsncpy(*path, nextpath, PATH_MAX);
4457 } else { /* New context */
4459 /* Deactivate the new context and build from scratch */
4460 g_ctx[ctx].c_cfg.ctxactive = 0;
4461 DPRINTF_S(nextpath);
4462 savecurctx(nextpath, file, ctx);
4463 *path = g_ctx[ctx].c_path;
4464 *lastdir = g_ctx[ctx].c_last;
4465 *lastname = g_ctx[ctx].c_name;
4470 * This function does one of the following depending on the values of `fdout` and `page`:
4471 * 1) fdout == -1 && !page: Write up to CMD_LEN_MAX bytes of command output into g_buf
4472 * 2) fdout == -1 && page: Create a temp file, write full command output into it and show in pager.
4473 * 3) fdout != -1 && !page: Write full command output into the provided file.
4474 * 4) fdout != -1 && page: Don't use! Returns FALSE.
4476 * g_buf is modified only in case 1.
4477 * g_tmpfpath is modified only in case 2.
4479 static bool get_output(char *file, char *arg1, char *arg2, int fdout, bool page)
4483 int index = 0, flags;
4485 bool have_file = fdout != -1;
4487 int cmd_out_fd = -1;
4491 * In this case the logic of the function dictates that we should write the output of the command
4492 * to `fd` and show it in the pager. But since we didn't open the file descriptor we have no right
4493 * to close it, the caller must do it. We don't even know the path to pass to the pager and
4494 * it's a real hassle to get it. In general this just invites problems so we are blocking it.
4496 if (have_file && page) {
4497 DPRINTF_S("invalid get_ouptput() call");
4501 /* Setup file descriptors for child command */
4502 if (!have_file && page) {
4504 fdout = create_tmp_file();
4508 cmd_in_fd = STDIN_FILENO;
4510 } else if (have_file) {
4512 cmd_in_fd = STDIN_FILENO;
4516 if (pipe(pipefd) == -1)
4519 for (index = 0; index < 2; ++index) {
4520 /* Get previous flags */
4521 flags = fcntl(pipefd[index], F_GETFL, 0);
4523 /* Set bit for non-blocking flag */
4524 flags |= O_NONBLOCK;
4526 /* Change flags on fd */
4527 fcntl(pipefd[index], F_SETFL, flags);
4530 cmd_in_fd = pipefd[0];
4531 cmd_out_fd = pipefd[1];
4538 dup2(cmd_out_fd, STDOUT_FILENO);
4539 dup2(cmd_out_fd, STDERR_FILENO);
4542 spawn(file, arg1, arg2, NULL, F_MULTI);
4543 _exit(EXIT_SUCCESS);
4547 waitpid(pid, NULL, 0);
4549 /* Do what each case should do */
4550 if (!have_file && page) {
4554 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4565 len = read(pipefd[0], g_buf, CMD_LEN_MAX - 1);
4575 * Follows the stat(1) output closely
4577 static bool show_stats(char *fpath)
4579 static char * const cmds[] = {
4580 #ifdef FILE_MIME_OPTS
4581 ("file " FILE_MIME_OPTS),
4584 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
4591 size_t r = ELEMENTS(cmds);
4592 int fd = create_tmp_file();
4597 get_output(cmds[--r], fpath, NULL, fd, FALSE);
4601 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4606 static bool xchmod(const char *fpath, mode_t *mode)
4608 /* (Un)set (S_IXUSR | S_IXGRP | S_IXOTH) */
4609 (0100 & *mode) ? (*mode &= ~0111) : (*mode |= 0111);
4611 return (chmod(fpath, *mode) == 0);
4614 static size_t get_fs_info(const char *path, uchar_t type)
4618 if (statvfs(path, &svb) == -1)
4621 if (type == VFS_AVAIL)
4622 return (size_t)svb.f_bavail << ffs((int)(svb.f_frsize >> 1));
4624 if (type == VFS_USED)
4625 return ((size_t)svb.f_blocks - (size_t)svb.f_bfree) << ffs((int)(svb.f_frsize >> 1));
4627 return (size_t)svb.f_blocks << ffs((int)(svb.f_frsize >> 1)); /* VFS_SIZE */
4630 /* Create non-existent parents and a file or dir */
4631 static bool xmktree(char *path, bool dir)
4639 /* Skip the first '/' */
4642 while (*p != '\0') {
4651 /* Create folder from path to '\0' inserted at p */
4652 if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4654 // XDG_CONFIG_HOME contains a directory
4655 // that is read-only, but the full path
4657 // Try to continue and see what happens.
4658 // TODO: Find a more robust solution.
4659 if (errno == B_READ_ONLY_DEVICE)
4662 DPRINTF_S("mkdir1!");
4663 DPRINTF_S(strerror(errno));
4677 if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4678 DPRINTF_S("mkdir2!");
4679 DPRINTF_S(strerror(errno));
4683 int fd = open(path, O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR); /* Forced create mode for files */
4685 if (fd == -1 && errno != EEXIST) {
4687 DPRINTF_S(strerror(errno));
4697 /* List or extract archive */
4698 static bool handle_archive(char *fpath /* in-out param */, char op)
4700 char arg[] = "-tvf"; /* options for tar/bsdtar to list files */
4701 char *util, *outdir = NULL;
4703 bool is_atool = (!g_state.usebsdtar && getutil(utils[UTIL_ATOOL]));
4706 outdir = xreadline(is_atool ? "." : xbasename(fpath), messages[MSG_NEW_PATH]);
4707 if (!outdir || !*outdir) { /* Cancelled */
4708 printwait(messages[MSG_CANCEL], NULL);
4711 /* Do not create smart context for current dir */
4712 if (!(*outdir == '.' && outdir[1] == '\0')) {
4713 if (!xmktree(outdir, TRUE) || (chdir(outdir) == -1)) {
4717 /* Copy the new dir path to open it in smart context */
4718 outdir = getcwd(NULL, 0);
4724 util = utils[UTIL_ATOOL];
4727 } else if (getutil(utils[UTIL_BSDTAR])) {
4728 util = utils[UTIL_BSDTAR];
4731 } else if (is_suffix(fpath, ".zip")) {
4732 util = utils[UTIL_UNZIP];
4733 arg[1] = (op == 'l') ? 'v' /* verbose listing */ : '\0';
4736 util = utils[UTIL_TAR];
4741 if (op == 'x') /* extract */
4742 spawn(util, arg, fpath, NULL, F_NORMAL | F_MULTI);
4744 get_output(util, arg, fpath, -1, TRUE);
4747 if (chdir(xdirname(fpath)) == -1) {
4752 xstrsncpy(fpath, outdir, PATH_MAX);
4754 } else if (op == 'x')
4760 static char *visit_parent(char *path, char *newpath, int *presel)
4764 /* There is no going back */
4765 if (istopdir(path)) {
4766 /* Continue in type-to-nav mode, if enabled */
4767 if (cfg.filtermode && presel)
4772 /* Use a copy as xdirname() may change the string passed */
4774 xstrsncpy(newpath, path, PATH_MAX);
4778 dir = xdirname(newpath);
4779 if (chdir(dir) == -1) {
4787 static void valid_parent(char *path, char *lastname)
4790 xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
4792 while (!istopdir(path))
4793 if (visit_parent(path, NULL, NULL))
4797 xdelay(XDELAY_INTERVAL_MS);
4800 static bool archive_mount(char *newpath)
4802 char *dir, *cmd = xgetenv("NNN_ARCHMNT", utils[UTIL_ARCHMNT]);
4803 char *name = pdents[cur].name;
4804 size_t len = pdents[cur].nlen;
4805 char mntpath[PATH_MAX];
4807 if (!getutil(cmd)) {
4808 printmsg("install utility");
4812 dir = xstrdup(name);
4814 printmsg(messages[MSG_FAILED]);
4819 if (dir[--len] == '.') {
4826 /* Create the mount point */
4827 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4828 mkpath(mntpath, dir, newpath);
4831 if (!xmktree(newpath, TRUE)) {
4839 if (spawn(cmd, name, newpath, NULL, F_NORMAL)) {
4840 printmsg(messages[MSG_FAILED]);
4847 static bool remote_mount(char *newpath)
4849 uchar_t flag = F_CLI;
4852 bool r = getutil(utils[UTIL_RCLONE]), s = getutil(utils[UTIL_SSHFS]);
4853 char mntpath[PATH_MAX];
4856 printmsg("install sshfs/rclone");
4861 opt = get_input(messages[MSG_REMOTE_OPTS]);
4863 opt = (!s) ? 'r' : 's';
4866 env = xgetenv("NNN_SSHFS", utils[UTIL_SSHFS]);
4867 else if (opt == 'r') {
4868 flag |= F_NOWAIT | F_NOTRACE;
4869 env = xgetenv("NNN_RCLONE", "rclone mount");
4871 printmsg(messages[MSG_INVALID_KEY]);
4875 tmp = xreadline(NULL, "host[:dir] > ");
4877 printmsg(messages[MSG_CANCEL]);
4881 char *div = strchr(tmp, ':');
4886 /* Create the mount point */
4887 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4888 mkpath(mntpath, tmp, newpath);
4889 if (!xmktree(newpath, TRUE)) {
4894 if (!div) { /* Convert "host" to "host:" */
4895 size_t len = xstrlen(tmp);
4898 tmp[len + 1] = '\0';
4902 /* Connect to remote */
4904 if (spawn(env, tmp, newpath, NULL, flag)) {
4905 printmsg(messages[MSG_FAILED]);
4909 spawn(env, tmp, newpath, NULL, flag);
4910 printmsg(messages[MSG_RCLONE_DELAY]);
4911 xdelay(XDELAY_INTERVAL_MS << 2); /* Set 4 times the usual delay */
4918 * Unmounts if the directory represented by name is a mount point.
4919 * Otherwise, asks for hostname
4920 * Returns TRUE if directory needs to be refreshed *.
4922 static bool unmount(char *name, char *newpath, int *presel, char *currentpath)
4924 #if defined(__APPLE__) || defined(__FreeBSD__)
4925 static char cmd[] = "umount";
4927 static char cmd[] = "fusermount3"; /* Arch Linux utility */
4928 static bool found = FALSE;
4931 struct stat sb, psb;
4933 bool parent = FALSE;
4934 bool hovered = FALSE;
4935 char mntpath[PATH_MAX];
4937 #if !defined(__APPLE__) && !defined(__FreeBSD__)
4938 /* On Ubuntu it's fusermount */
4939 if (!found && !getutil(cmd)) {
4945 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4947 if (tmp && strcmp(mntpath, currentpath) == 0) {
4948 mkpath(mntpath, tmp, newpath);
4949 child = lstat(newpath, &sb) != -1;
4950 parent = lstat(xdirname(newpath), &psb) != -1;
4951 if (!child && !parent) {
4957 if (!tmp || !child || !S_ISDIR(sb.st_mode) || (child && parent && sb.st_dev == psb.st_dev)) {
4958 tmp = xreadline(NULL, messages[MSG_HOSTNAME]);
4961 if (name && (tmp[0] == '-') && (tmp[1] == '\0')) {
4962 mkpath(currentpath, name, newpath);
4968 mkpath(mntpath, tmp, newpath);
4970 if (!xdiraccess(newpath)) {
4975 #if defined(__APPLE__) || defined(__FreeBSD__)
4976 if (spawn(cmd, newpath, NULL, NULL, F_NORMAL)) {
4978 if (spawn(cmd, "-qu", newpath, NULL, F_NORMAL)) {
4980 if (!xconfirm(get_input(messages[MSG_LAZY])))
4984 if (spawn(cmd, "-l", newpath, NULL, F_NORMAL)) {
4985 #elif defined(__FreeBSD__)
4986 if (spawn(cmd, "-f", newpath, NULL, F_NORMAL)) {
4988 if (spawn(cmd, "-quz", newpath, NULL, F_NORMAL)) {
4990 printwait(messages[MSG_FAILED], presel);
4995 if (rmdir(newpath) == -1) {
5003 static void lock_terminal(void)
5005 spawn(xgetenv("NNN_LOCKER", utils[UTIL_LOCKER]), NULL, NULL, NULL, F_CLI);
5008 static void printkv(kv *kvarr, int fd, uchar_t max, uchar_t id)
5010 char *val = (id == NNN_BMS) ? bmstr : pluginstr;
5012 for (uchar_t i = 0; i < max && kvarr[i].key; ++i)
5013 dprintf(fd, " %c: %s\n", (char)kvarr[i].key, val + kvarr[i].off);
5016 static void printkeys(kv *kvarr, char *buf, uchar_t max)
5020 for (; i < max && kvarr[i].key; ++i) {
5022 buf[(i << 1) + 1] = kvarr[i].key;
5028 static size_t handle_bookmark(const char *bmark, char *newpath)
5033 if (maxbm || bmark) {
5034 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
5036 if (bmark) { /* There is a marked directory */
5042 printkeys(bookmark, g_buf + r - 1, maxbm);
5044 fd = get_input(NULL);
5048 if (fd == ',') /* Visit marked directory */
5049 bmark ? xstrsncpy(newpath, bmark, PATH_MAX) : (r = MSG_NOT_SET);
5050 else if (fd == '\r') { /* Visit bookmarks directory */
5051 mkpath(cfgpath, toks[TOK_BM], newpath);
5053 } else if (!get_kv_val(bookmark, newpath, fd, maxbm, NNN_BMS))
5054 r = MSG_INVALID_KEY;
5056 if (!r && chdir(newpath) == -1) {
5065 static void add_bookmark(char *path, char *newpath, int *presel)
5067 char *dir = xbasename(path);
5069 dir = xreadline(dir[0] ? dir : NULL, messages[MSG_BM_NAME]);
5071 size_t r = mkpath(cfgpath, toks[TOK_BM], newpath);
5073 newpath[r - 1] = '/';
5074 xstrsncpy(newpath + r, dir, PATH_MAX - r);
5075 printwait((symlink(path, newpath) == -1) ? strerror(errno) : newpath, presel);
5077 printwait(messages[MSG_CANCEL], presel);
5081 * The help string tokens (each line) start with a HEX value which indicates
5082 * the number of spaces to print before the particular token. In the middle,
5083 * %NN can be used to insert a run of spaces, e.g %10 will print 10 spaces.
5084 * %NN MUST be 2 characters long, e.g %05 for 5 spaces.
5086 * This method was chosen instead of a flat string because the number of bytes
5087 * in help was increasing the binary size by around a hundred bytes. This would
5088 * only have increased as we keep adding new options.
5090 static void show_help(const char *path)
5092 static const char helpstr[] = {
5100 "9Up k Up%16PgUp ^U Page up\n"
5101 "9Dn j Down%14PgDn ^D Page down\n"
5102 "9Lt h Parent%12~ ` @ - ~, /, start, prev\n"
5103 "5Ret Rt l Open%20' First file/match\n"
5104 "9g ^A Top%21J Jump to entry/offset\n"
5105 "9G ^E End%20^J Toggle auto-advance on open\n"
5106 "8B (,) Book(mark)%11b ^/ Select bookmark\n"
5107 "a1-4 Context%11(Sh)Tab Cycle/new context\n"
5108 "62Esc ^Q Quit%19^y Next young\n"
5109 "b^G QuitCD%18Q Pick/err, quit\n"
5112 "1FILTER & PROMPT\n"
5113 "c/ Filter%17^N Toggle type-to-nav\n"
5114 "aEsc Exit prompt%12^L Toggle last filter\n"
5115 "c. Toggle hidden%05Alt+Esc Unfilter, quit context\n"
5118 "9o ^O Open with%15n Create new/link\n"
5119 "9f ^F File stats%14d Detail mode toggle\n"
5120 "b^R Rename/dup%14r Batch rename\n"
5121 "cz Archive%17e Edit file\n"
5122 "c* Toggle exe%14> Export list\n"
5123 "6Space + (Un)select%12m-m Select range/clear\n"
5124 "ca Select all%14A Invert sel\n"
5125 "9p ^P Copy here%12w ^W Cp/mv sel as\n"
5126 "9v ^V Move here%15E Edit sel list\n"
5127 "9x ^X Delete%18S Listed sel size\n"
5128 "aEsc Send to FIFO\n"
5131 "8Alt ; Select plugin%11= Launch app\n"
5132 "9! ^] Shell%19] Cmd prompt\n"
5133 "cc Connect remote%10u Unmount remote/archive\n"
5134 "9t ^T Sort toggles%12s Manage session\n"
5135 "cT Set time type%110 Lock\n"
5136 "b^L Redraw%18? Help, conf\n"
5139 int fd = create_tmp_file();
5143 char *prog = xgetenv(env_cfg[NNN_HELP], NULL);
5145 get_output(prog, NULL, NULL, fd, FALSE);
5149 const char *end = helpstr + (sizeof helpstr - 1);
5150 for (const char *s = helpstr; s < end; ++s) {
5152 for (int k = 0, n = xchartohex(*s); k < n; ++k) *w++ = ' ';
5153 } else if (*s == '%') {
5154 int n = ((s[1] - '0') * 10) + (s[2] - '0');
5155 for (int k = 0; k < n; ++k) *w++ = ' ';
5162 if (write(fd, g_buf, w - g_buf)) {} // silence warning
5164 dprintf(fd, "\nLOCATIONS\n");
5165 for (uchar_t i = 0; i < CTX_MAX; ++i)
5166 if (g_ctx[i].c_cfg.ctxactive)
5167 dprintf(fd, " %u: %s\n", i + 1, g_ctx[i].c_path);
5169 dprintf(fd, "\nVOLUME: avail:%s ", coolsize(get_fs_info(path, VFS_AVAIL)));
5170 dprintf(fd, "used:%s ", coolsize(get_fs_info(path, VFS_USED)));
5171 dprintf(fd, "size:%s\n\n", coolsize(get_fs_info(path, VFS_SIZE)));
5174 dprintf(fd, "BOOKMARKS\n");
5175 printkv(bookmark, fd, maxbm, NNN_BMS);
5180 dprintf(fd, "PLUGIN KEYS\n");
5181 printkv(plug, fd, maxplug, NNN_PLUG);
5185 for (uchar_t i = NNN_OPENER; i <= NNN_TRASH; ++i) {
5186 char *s = getenv(env_cfg[i]);
5188 dprintf(fd, "%s: %s\n", env_cfg[i], s);
5192 dprintf(fd, "SELECTION FILE: %s\n", selpath);
5194 dprintf(fd, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
5197 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
5201 static void setexports(void)
5207 setenv(envs[ENV_NCUR], pdents[cur].name, 1);
5208 xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
5209 } else if (g_ctx[cfg.curctx].c_name[0])
5210 g_ctx[cfg.curctx].c_name[0] = '\0';
5212 for (uchar_t i = 0; i < CTX_MAX; ++i) {
5213 if (g_ctx[i].c_cfg.ctxactive) {
5214 dvar[1] = fvar[1] = '1' + i;
5215 setenv(dvar, g_ctx[i].c_path, 1);
5217 if (g_ctx[i].c_name[0]) {
5218 mkpath(g_ctx[i].c_path, g_ctx[i].c_name, g_buf);
5219 setenv(fvar, g_buf, 1);
5223 setenv("NNN_INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
5224 setenv("NNN_PREFER_SELECTION", xitoa(cfg.prefersel), 1);
5227 static void run_cmd_as_plugin(const char *file, uchar_t flags)
5231 xstrsncpy(g_buf, file, PATH_MAX);
5233 len = xstrlen(g_buf);
5234 if (len > 1 && g_buf[len - 1] == '*') {
5235 flags &= ~F_CONFIRM; /* Skip user confirmation */
5236 g_buf[len - 1] = '\0'; /* Get rid of trailing no confirmation symbol */
5241 get_output(utils[UTIL_SH_EXEC], g_buf, NULL, -1, TRUE);
5243 spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, flags);
5246 static bool plctrl_init(void)
5250 /* g_tmpfpath is used to generate tmp file names */
5251 g_tmpfpath[tmpfplen - 1] = '\0';
5252 len = xstrsncpy(g_pipepath, g_tmpfpath, TMP_LEN_MAX);
5253 g_pipepath[len - 1] = '/';
5254 len = xstrsncpy(g_pipepath + len, "nnn-pipe.", TMP_LEN_MAX - len) + len;
5255 xstrsncpy(g_pipepath + len - 1, xitoa(getpid()), TMP_LEN_MAX - len);
5256 setenv(env_cfg[NNN_PIPE], g_pipepath, TRUE);
5258 return EXIT_SUCCESS;
5261 static void rmlistpath(void)
5264 DPRINTF_S(__func__);
5265 DPRINTF_S(listpath);
5266 spawn(utils[UTIL_RM_RF], listpath, NULL, NULL, F_NOTRACE | F_MULTI);
5267 /* Do not free if program was started in list mode */
5268 if (listpath != initpath)
5274 static ssize_t read_nointr(int fd, void *buf, size_t count)
5279 len = read(fd, buf, count);
5280 while (len == -1 && errno == EINTR);
5285 static char *readpipe(int fd, char *ctxnum, char **path)
5287 char ctx, *nextpath = NULL;
5289 if (read_nointr(fd, g_buf, 1) != 1)
5292 if (g_buf[0] == '-') { /* Clear selection on '-' */
5294 if (read_nointr(fd, g_buf, 1) != 1)
5298 if (g_buf[0] == '+')
5299 ctx = (char)(get_free_ctx() + 1);
5300 else if (g_buf[0] < '0')
5303 ctx = g_buf[0] - '0';
5308 if (read_nointr(fd, g_buf, 1) != 1)
5314 ssize_t len = read_nointr(fd, g_buf, PATH_MAX);
5319 g_buf[len] = '\0'; /* Terminate the path read */
5320 if (g_buf[0] == '/') {
5322 len = xstrlen(g_buf);
5323 while (--len && (g_buf[len] == '/')) /* Trim all trailing '/' */
5326 } else if (op == 'l') {
5327 rmlistpath(); /* Remove last list mode path, if any */
5328 nextpath = load_input(fd, *path);
5329 } else if (op == 'p') {
5342 static bool run_plugin(char **path, const char *file, char *runfile, char **lastname, char **lastdir)
5347 bool cmd_as_plugin = FALSE;
5350 if (!g_state.pluginit) {
5352 g_state.pluginit = 1;
5357 /* Check for run-cmd-as-plugin mode */
5359 flags = F_MULTI | F_CONFIRM;
5362 if (*file == '|') { /* Check if output should be paged */
5365 } else if (*file == '&') { /* Check if GUI flags are to be used */
5366 flags = F_MULTI | F_NOTRACE | F_NOWAIT;
5373 if ((flags & F_NOTRACE) || (flags & F_PAGE)) {
5374 run_cmd_as_plugin(file, flags);
5378 cmd_as_plugin = TRUE;
5381 if (mkfifo(g_pipepath, 0600) != 0)
5388 if (!p) { // In child
5389 int wfd = open(g_pipepath, O_WRONLY | O_CLOEXEC);
5392 _exit(EXIT_FAILURE);
5394 if (!cmd_as_plugin) {
5398 /* Generate absolute path to plugin */
5399 mkpath(plgpath, file, g_buf);
5402 sel = selpath ? selpath : std;
5404 if (runfile && runfile[0]) {
5405 xstrsncpy(*lastname, runfile, NAME_MAX);
5406 spawn(g_buf, *lastname, *path, sel, 0);
5408 spawn(g_buf, NULL, *path, sel, 0);
5410 run_cmd_as_plugin(file, flags);
5413 _exit(EXIT_SUCCESS);
5419 rfd = open(g_pipepath, O_RDONLY);
5420 while (rfd == -1 && errno == EINTR);
5422 nextpath = readpipe(rfd, &ctx, path);
5424 set_smart_ctx(ctx, nextpath, path, runfile, lastname, lastdir);
5428 /* wait for the child to finish. no zombies allowed */
5429 waitpid(p, NULL, 0);
5438 static bool launch_app(char *newpath)
5441 char *tmp = newpath;
5443 mkpath(plgpath, utils[UTIL_LAUNCH], newpath);
5445 if (!getutil(utils[UTIL_FZF]) || access(newpath, X_OK) < 0) {
5446 tmp = xreadline(NULL, messages[MSG_APP_NAME]);
5447 r = F_NOWAIT | F_NOTRACE | F_MULTI;
5450 if (tmp && *tmp) // NOLINT
5451 spawn(tmp, (r == F_NORMAL) ? "0" : NULL, NULL, NULL, r);
5456 /* Returns TRUE if at least one command was run */
5457 static bool prompt_run(void)
5460 char *cmdline, *next;
5461 int cnt_j, cnt_J, cmd_ret;
5464 const char *xargs_j = "xargs -0 -I{} %s < %s";
5465 const char *xargs_J = "xargs -0 %s < %s";
5466 char cmd[CMD_LEN_MAX + 32]; // 32 for xargs format strings
5470 if (g_state.picker) {
5472 cmdline = xreadline(NULL, PROMPT);
5475 cmdline = getreadline("\n"PROMPT);
5477 // Check for an empty command
5478 if (!cmdline || !cmdline[0])
5482 lastcmd = xstrdup(cmdline);
5485 len = xstrlen(cmdline);
5489 while ((next = strstr(next, "%j"))) {
5492 // replace %j with {} for xargs later
5501 while ((next = strstr(next, "%J"))) {
5504 // %J should be the last thing in the command
5505 if (next == cmdline + len - 2) {
5506 cmdline[len - 2] = '\0';
5512 // We can't handle both %j and %J in a single command
5517 snprintf(cmd, CMD_LEN_MAX + 32, xargs_j, cmdline, selpath);
5519 snprintf(cmd, CMD_LEN_MAX + 32, xargs_J, cmdline, selpath);
5521 cmd_ret = spawn(shell, "-c", (cnt_j || cnt_J) ? cmd : cmdline, NULL, F_CLI | F_CONFIRM);
5522 if ((cnt_j || cnt_J) && cmd_ret == 0)
5529 static bool handle_cmd(enum action sel, char *newpath)
5531 endselection(FALSE);
5533 if (sel == SEL_LAUNCH)
5534 return launch_app(newpath);
5538 if (sel == SEL_PROMPT)
5539 return prompt_run();
5541 /* Set nnn nesting level */
5542 char *tmp = getenv(env_cfg[NNNLVL]);
5543 int r = tmp ? atoi(tmp) : 0;
5545 setenv(env_cfg[NNNLVL], xitoa(r + 1), 1);
5546 spawn(shell, NULL, NULL, NULL, F_CLI);
5547 setenv(env_cfg[NNNLVL], xitoa(r), 1);
5551 static void dentfree(void)
5557 /* Thread data cleanup */
5563 static void *du_thread(void *p_data)
5565 thread_data *pdata = (thread_data *)p_data;
5566 char *path[2] = {pdata->path, NULL};
5567 ullong_t tfiles = 0;
5568 blkcnt_t tblocks = 0;
5570 FTS *tree = fts_open(path, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR, 0);
5573 while ((node = fts_read(tree))) {
5574 if (node->fts_info & FTS_D) {
5575 if (g_state.interrupt)
5580 sb = node->fts_statp;
5582 if (cfg.apparentsz) {
5583 if (sb->st_size && DU_TEST)
5584 tblocks += sb->st_size;
5585 } else if (sb->st_blocks && DU_TEST)
5586 tblocks += sb->st_blocks;
5593 if (pdata->entnum >= 0)
5594 pdents[pdata->entnum].blocks = tblocks;
5596 if (!pdata->mntpoint) {
5597 core_blocks[pdata->core] += tblocks;
5598 core_files[pdata->core] += tfiles;
5600 core_files[pdata->core] += 1;
5602 pthread_mutex_lock(&running_mutex);
5603 threadbmp |= (1 << pdata->core);
5605 pthread_mutex_unlock(&running_mutex);
5610 static void dirwalk(char *path, int entnum, bool mountpoint)
5612 /* Loop till any core is free */
5613 while (active_threads == NUM_DU_THREADS);
5615 if (g_state.interrupt)
5618 pthread_mutex_lock(&running_mutex);
5619 int core = ffs(threadbmp) - 1;
5621 threadbmp &= ~(1 << core);
5623 pthread_mutex_unlock(&running_mutex);
5625 xstrsncpy(core_data[core].path, path, PATH_MAX);
5626 core_data[core].entnum = entnum;
5627 core_data[core].core = (ushort_t)core;
5628 core_data[core].mntpoint = mountpoint;
5632 pthread_create(&tid, NULL, du_thread, (void *)&(core_data[core]));
5635 addstr(xbasename(path));
5636 addstr(" [^C aborts]\n");
5640 static bool prep_threads(void)
5642 if (!g_state.duinit) {
5644 threadbmp >>= (32 - NUM_DU_THREADS);
5647 core_blocks = calloc(NUM_DU_THREADS, sizeof(blkcnt_t));
5649 core_data = calloc(NUM_DU_THREADS, sizeof(thread_data));
5651 core_files = calloc(NUM_DU_THREADS, sizeof(ullong_t));
5653 if (!core_blocks || !core_data || !core_files) {
5658 /* Increase current open file descriptor limit */
5661 g_state.duinit = TRUE;
5663 memset(core_blocks, 0, NUM_DU_THREADS * sizeof(blkcnt_t));
5664 memset(core_data, 0, NUM_DU_THREADS * sizeof(thread_data));
5665 memset(core_files, 0, NUM_DU_THREADS * sizeof(ullong_t));
5670 /* Skip self and parent */
5671 static inline bool selforparent(const char *path)
5673 return path[0] == '.' && (path[1] == '\0' || (path[1] == '.' && path[2] == '\0'));
5676 static int dentfill(char *path, struct entry **ppdents)
5678 uchar_t entflags = 0;
5681 char *namep, *pnb, *buf;
5682 struct entry *dentp;
5683 size_t off = 0, namebuflen = NAMEBUF_INCR;
5684 struct stat sb_path, sb;
5685 DIR *dirp = opendir(path);
5688 gtimesecs = time(NULL);
5690 DPRINTF_S(__func__);
5695 int fd = dirfd(dirp);
5702 if (fstatat(fd, path, &sb_path, 0) == -1)
5706 ihashbmp = calloc(1, HASH_OCTETS << 3);
5710 memset(ihashbmp, 0, HASH_OCTETS << 3);
5712 if (!prep_threads())
5715 attron(COLOR_PAIR(cfg.curctx + 1));
5718 #if _POSIX_C_SOURCE >= 200112L
5719 posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
5726 #if defined(__sun) || defined(__HAIKU__)
5727 flags = AT_SYMLINK_NOFOLLOW; /* no d_type */
5729 if (cfg.blkorder || dp->d_type == DT_UNKNOWN) {
5731 * Optimization added for filesystems which support dirent.d_type
5734 * - the symlink size is set to 0
5735 * - the modification time of the symlink is set to that of the target file
5737 flags = AT_SYMLINK_NOFOLLOW;
5744 if (selforparent(namep))
5747 if (!cfg.showhidden && namep[0] == '.') {
5751 if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
5754 if (S_ISDIR(sb.st_mode)) {
5755 if (sb_path.st_dev == sb.st_dev) { // NOLINT
5756 mkpath(path, namep, buf); // NOLINT
5757 dirwalk(buf, -1, FALSE);
5759 if (g_state.interrupt)
5763 /* Do not recount hard links */
5764 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5765 dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5772 if (fstatat(fd, namep, &sb, flags) == -1) {
5773 if (flags || (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)) {
5778 DPRINTF_S(strerror(errno));
5781 entflags = FILE_MISSING;
5782 memset(&sb, 0, sizeof(struct stat));
5783 } else /* Orphaned symlink */
5784 entflags = SYM_ORPHAN;
5787 if (ndents == total_dents) {
5789 while (active_threads);
5791 total_dents += ENTRY_INCR;
5792 *ppdents = xrealloc(*ppdents, total_dents * sizeof(**ppdents));
5798 DPRINTF_P(*ppdents);
5801 /* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
5802 if (namebuflen - off < NAME_MAX + 1) {
5803 namebuflen += NAMEBUF_INCR;
5806 pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
5812 DPRINTF_P(pnamebuf);
5814 /* realloc() may result in memory move, we must re-adjust if that happens */
5815 if (pnb != pnamebuf) {
5817 dentp->name = pnamebuf;
5819 for (int count = 1; count < ndents; ++dentp, ++count)
5820 /* Current file name starts at last file name start + length */
5821 (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
5825 dentp = *ppdents + ndents;
5827 /* Selection file name */
5828 dentp->name = (char *)((size_t)pnamebuf + off);
5829 dentp->nlen = xstrsncpy(dentp->name, namep, NAME_MAX + 1);
5832 /* Copy other fields */
5833 if (cfg.timetype == T_MOD) {
5834 dentp->sec = sb.st_mtime;
5836 dentp->nsec = (uint_t)sb.st_mtimespec.tv_nsec;
5838 dentp->nsec = (uint_t)sb.st_mtim.tv_nsec;
5840 } else if (cfg.timetype == T_ACCESS) {
5841 dentp->sec = sb.st_atime;
5843 dentp->nsec = (uint_t)sb.st_atimespec.tv_nsec;
5845 dentp->nsec = (uint_t)sb.st_atim.tv_nsec;
5848 dentp->sec = sb.st_ctime;
5850 dentp->nsec = (uint_t)sb.st_ctimespec.tv_nsec;
5852 dentp->nsec = (uint_t)sb.st_ctim.tv_nsec;
5856 if ((gtimesecs - sb.st_mtime <= 300) || (gtimesecs - sb.st_ctime <= 300))
5857 entflags |= FILE_YOUNG;
5859 #if !(defined(__sun) || defined(__HAIKU__))
5860 if (!flags && dp->d_type == DT_LNK) {
5861 /* Do not add sizes for links */
5862 dentp->mode = (sb.st_mode & ~S_IFMT) | S_IFLNK;
5863 dentp->size = listpath ? sb.st_size : 0;
5865 dentp->mode = sb.st_mode;
5866 dentp->size = sb.st_size;
5869 dentp->mode = sb.st_mode;
5870 dentp->size = sb.st_size;
5874 dentp->uid = sb.st_uid;
5875 dentp->gid = sb.st_gid;
5878 dentp->flags = S_ISDIR(sb.st_mode) ? 0 : ((sb.st_nlink > 1) ? HARD_LINK : 0);
5880 dentp->flags |= entflags;
5885 if (S_ISDIR(sb.st_mode)) {
5886 mkpath(path, namep, buf); // NOLINT
5888 /* Need to show the disk usage of this dir */
5889 dirwalk(buf, ndents, (sb_path.st_dev != sb.st_dev)); // NOLINT
5891 if (g_state.interrupt)
5894 dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5895 /* Do not recount hard links */
5896 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5897 dir_blocks += dentp->blocks;
5903 /* Flag if this is a dir or symlink to a dir */
5904 if (S_ISLNK(sb.st_mode)) {
5906 fstatat(fd, namep, &sb, 0);
5909 if (S_ISDIR(sb.st_mode))
5910 dentp->flags |= DIR_OR_DIRLNK;
5911 #if !(defined(__sun) || defined(__HAIKU__)) /* no d_type */
5912 } else if (dp->d_type == DT_DIR || ((dp->d_type == DT_LNK
5913 || dp->d_type == DT_UNKNOWN) && S_ISDIR(sb.st_mode))) {
5914 dentp->flags |= DIR_OR_DIRLNK;
5919 } while ((dp = readdir(dirp)));
5922 if (g_state.duinit && cfg.blkorder) {
5923 while (active_threads);
5925 attroff(COLOR_PAIR(cfg.curctx + 1));
5926 for (int i = 0; i < NUM_DU_THREADS; ++i) {
5927 num_files += core_files[i];
5928 dir_blocks += core_blocks[i];
5932 /* Should never be null */
5933 if (closedir(dirp) == -1)
5939 static void populate(char *path, char *lastname)
5942 struct timespec ts1, ts2;
5944 clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
5947 ndents = dentfill(path, &pdents);
5952 ENTSORT(pdents, ndents, entrycmpfn);
5956 clock_gettime(CLOCK_REALTIME, &ts2);
5957 DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
5960 /* Find cur from history */
5961 /* No NULL check for lastname, always points to an array */
5962 move_cursor(*lastname ? dentfind(lastname, ndents) : 0, 0);
5964 // Force full redraw
5965 last_curscroll = -1;
5969 static void notify_fifo(bool force)
5975 fifofd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC);
5978 /* Unexpected error, the FIFO file might have been removed */
5979 /* We give up FIFO notification */
5985 static struct entry lastentry;
5987 if (!force && !memcmp(&lastentry, &pdents[cur], sizeof(struct entry))) // NOLINT
5990 lastentry = pdents[cur];
5992 char path[PATH_MAX];
5993 size_t len = mkpath(g_ctx[cfg.curctx].c_path, ndents ? pdents[cur].name : "", path);
5995 path[len - 1] = '\n';
5997 ssize_t ret = write(fifofd, path, len);
5999 if (ret != (ssize_t)len && !(ret == -1 && (errno == EAGAIN || errno == EPIPE))) {
6000 DPRINTF_S(strerror(errno));
6004 static void send_to_explorer(int *presel)
6007 int fd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0600);
6008 if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
6017 notify_fifo(TRUE); /* Send opened path to NNN_FIFO */
6021 static void move_cursor(int target, int ignore_scrolloff)
6023 int onscreen = xlines - 4; /* Leave top 2 and bottom 2 lines */
6025 target = MAX(0, MIN(ndents - 1, target));
6026 last_curscroll = curscroll;
6030 if (!ignore_scrolloff) {
6031 int delta = target - last;
6032 int scrolloff = MIN(SCROLLOFF, onscreen >> 1);
6035 * When ignore_scrolloff is 1, the cursor can jump into the scrolloff
6036 * margin area, but when ignore_scrolloff is 0, act like a boa
6037 * constrictor and squeeze the cursor towards the middle region of the
6038 * screen by allowing it to move inward and disallowing it to move
6039 * outward (deeper into the scrolloff margin area).
6041 if (((cur < (curscroll + scrolloff)) && delta < 0)
6042 || ((cur > (curscroll + onscreen - scrolloff - 1)) && delta > 0))
6045 curscroll = MIN(curscroll, MIN(cur, ndents - onscreen));
6046 curscroll = MAX(curscroll, MAX(cur - (onscreen - 1), 0));
6049 if (!g_state.fifomode)
6050 notify_fifo(FALSE); /* Send hovered path to NNN_FIFO */
6054 static void handle_screen_move(enum action sel)
6060 if (cfg.rollover || (cur != ndents - 1))
6061 move_cursor((cur + 1) % ndents, 0);
6064 if (cfg.rollover || cur)
6065 move_cursor((cur + ndents - 1) % ndents, 0);
6068 onscreen = xlines - 4;
6069 move_cursor(curscroll + (onscreen - 1), 1);
6070 curscroll += onscreen - 1;
6073 onscreen = xlines - 4;
6074 move_cursor(curscroll + (onscreen - 1), 1);
6075 curscroll += onscreen >> 1;
6078 onscreen = xlines - 4;
6079 move_cursor(curscroll, 1);
6080 curscroll -= onscreen - 1;
6083 onscreen = xlines - 4;
6084 move_cursor(curscroll, 1);
6085 curscroll -= onscreen >> 1;
6089 char *input = xreadline(NULL, "jump (+n/-n/n): ");
6091 if (!input || !*input)
6093 if (input[0] == '-') {
6094 cur -= atoi(input + 1);
6097 } else if (input[0] == '+') {
6098 cur += atoi(input + 1);
6102 int index = atoi(input);
6104 if ((index < 1) || (index > ndents))
6108 onscreen = xlines - 4;
6109 move_cursor(cur, 1);
6110 curscroll -= onscreen >> 1;
6117 move_cursor(ndents - 1, 1);
6121 for (int r = cur;;) {
6126 if (pdents[r].flags & FILE_YOUNG) {
6133 default: /* case SEL_FIRST */
6135 int c = get_input(messages[MSG_FIRST]);
6142 int r = (c == TOUPPER(*pdents[cur].name)) ? (cur + 1) : 0;
6144 for (; r < ndents; ++r) {
6145 if (((c == '\'') && !(pdents[r].flags & DIR_OR_DIRLNK))
6146 || (c == TOUPPER(*pdents[r].name))) {
6147 move_cursor((r) % ndents, 0);
6156 static void handle_openwith(const char *path, const char *name, char *newpath, char *tmp)
6158 /* Confirm if app is CLI or GUI */
6159 int r = get_input(messages[MSG_CLI_MODE]);
6161 r = (r == 'c' ? F_CLI :
6162 ((r == 'g' || r == '\r') ? (F_NOWAIT | F_NOTRACE | F_MULTI) : 0));
6164 mkpath(path, name, newpath);
6165 spawn(tmp, newpath, NULL, NULL, r);
6169 static void copynextname(char *lastname)
6172 cur += (cur != (ndents - 1)) ? 1 : -1;
6178 static int handle_context_switch(enum action sel)
6183 case SEL_CYCLE: // fallthrough
6185 /* visit next and previous contexts */
6187 if (sel == SEL_CYCLE)
6189 r = (r + 1) & ~CTX_MAX;
6190 while (!g_ctx[r].c_cfg.ctxactive);
6192 do /* Attempt to create a new context */
6193 r = (r + 1) & ~CTX_MAX;
6194 while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
6196 if (r == cfg.curctx) /* If all contexts are active, reverse cycle */
6198 r = (r + (CTX_MAX - 1)) & (CTX_MAX - 1);
6199 while (!g_ctx[r].c_cfg.ctxactive);
6201 default: /* SEL_CTXN */
6202 if (sel >= SEL_CTX1) /* CYCLE keys are lesser in value */
6203 r = sel - SEL_CTX1; /* Save the next context id */
6205 if (cfg.curctx == r) {
6206 if (sel == SEL_CYCLE)
6207 (r == CTX_MAX - 1) ? (r = 0) : ++r;
6208 else if (sel == SEL_CYCLER)
6209 (r == 0) ? (r = CTX_MAX - 1) : --r;
6218 static int set_sort_flags(int r)
6220 bool session = (r == '\0');
6221 bool reverse = FALSE;
6223 if (ISUPPER_(r) && (r != 'R') && (r != 'C')) {
6228 /* Set the correct input in case of a session load */
6230 if (cfg.apparentsz) {
6233 } else if (cfg.blkorder) {
6239 namecmpfn = &xstrverscasecmp;
6242 entrycmpfn = &reventrycmp;
6243 } else if (r == CONTROL('T')) {
6244 /* Cycling order: clear -> size -> time -> clear */
6247 else if (cfg.sizeorder)
6254 case 'a': /* Apparent du */
6255 cfg.apparentsz ^= 1;
6256 if (cfg.apparentsz) {
6262 case 'd': /* Disk usage */
6264 if (!cfg.apparentsz)
6267 blk_shift = ffs(S_BLKSIZE) - 1;
6277 entrycmpfn = &entrycmp;
6279 endselection(TRUE); /* We are going to reload dir */
6289 entrycmpfn = &entrycmp;
6290 namecmpfn = &xstricmp;
6292 case 'e': /* File extension */
6299 entrycmpfn = &entrycmp;
6301 case 'r': /* Reverse sort */
6303 entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
6305 case 's': /* File size */
6312 entrycmpfn = &entrycmp;
6314 case 't': /* Time */
6321 entrycmpfn = &entrycmp;
6323 case 'v': /* Version */
6325 namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
6338 entrycmpfn = &reventrycmp;
6341 cfgsort[cfg.curctx] = (uchar_t)r;
6346 static bool set_time_type(int *presel)
6349 char buf[] = "'a'ccess / 'c'hange / 'm'od [ ]";
6351 buf[sizeof(buf) - 3] = cfg.timetype == T_MOD ? 'm' : (cfg.timetype == T_ACCESS ? 'a' : 'c');
6353 int r = get_input(buf);
6355 if (r == 'a' || r == 'c' || r == 'm') {
6356 r = (r == 'm') ? T_MOD : ((r == 'a') ? T_ACCESS : T_CHANGE);
6357 if (cfg.timetype != r) {
6360 if (cfg.filtermode || g_ctx[cfg.curctx].c_fltr[1])
6367 r = MSG_INVALID_KEY;
6370 printwait(messages[r], presel);
6375 static void statusbar(char *path)
6379 pEntry pent = &pdents[cur];
6386 /* Get the file extension for regular files */
6387 if (S_ISREG(pent->mode)) {
6388 i = (int)(pent->nlen - 1);
6389 ptr = xextension(pent->name, i);
6391 len = i - (ptr - pent->name);
6392 if (!ptr || len > 5 || len < 2)
6397 attron(COLOR_PAIR(cfg.curctx + 1));
6399 if (cfg.fileinfo && get_output("file", "-b", pdents[cur].name, -1, FALSE))
6400 mvaddstr(xlines - 2, 2, g_buf);
6404 printw("%d/%s ", cur + 1, xitoa(ndents));
6406 if (g_state.selmode || nselected) {
6409 if (g_state.rangesel)
6411 else if (g_state.selmode)
6414 addstr(xitoa(nselected));
6420 if (cfg.blkorder) { /* du mode */
6423 xstrsncpy(buf, coolsize(dir_blocks << blk_shift), 12);
6425 printw("%cu:%s avail:%s files:%llu %lluB %s\n",
6426 (cfg.apparentsz ? 'a' : 'd'), buf, coolsize(get_fs_info(path, VFS_AVAIL)),
6427 num_files, (ullong_t)pent->blocks << blk_shift, ptr);
6428 } else { /* light or detail mode */
6429 char sort[] = "\0\0\0\0\0";
6431 if (getorderstr(sort))
6435 print_time(&pent->sec, pent->flags);
6438 addstr(get_lsperms(pent->mode));
6441 if (g_state.uidgid) {
6442 addstr(getpwname(pent->uid));
6444 addstr(getgrname(pent->gid));
6448 if (S_ISLNK(pent->mode)) {
6449 if (!cfg.fileinfo) {
6450 i = readlink(pent->name, g_buf, PATH_MAX);
6451 addstr(coolsize(i >= 0 ? i : pent->size)); /* Show symlink size */
6452 if (i > 1) { /* Show symlink target */
6456 getyx(stdscr, len, y);
6457 i = MIN(i, xcols - y);
6463 addstr(coolsize(pent->size));
6466 if (pent->flags & HARD_LINK) {
6469 if (stat(pent->name, &sb) != -1) {
6471 addstr(xitoa((int)sb.st_nlink)); /* Show number of links */
6473 addstr(xitoa((int)sb.st_ino)); /* Show inode number */
6480 attroff(COLOR_PAIR(cfg.curctx + 1));
6481 /* Place HW cursor on current for Braille systems */
6485 static inline void markhovered(void)
6487 if (cfg.showdetail && ndents) { /* Bold forward arrowhead */
6489 addch('>' | A_BOLD);
6493 static int adjust_cols(int n)
6495 /* Calculate the number of cols available to print entry name */
6496 #ifdef ICONS_ENABLED
6497 n -= (g_state.oldcolor ? 0 : ICON_SIZE + ICON_PADDING_LEFT_LEN + ICON_PADDING_RIGHT_LEN);
6499 if (cfg.showdetail) {
6500 /* Fallback to light mode if less than 35 columns */
6502 cfg.showdetail ^= 1;
6503 else /* 2 more accounted for below */
6507 /* 2 columns for preceding space and indicator */
6511 static void draw_line(int ncols)
6515 ncols = adjust_cols(ncols);
6517 if (g_state.oldcolor && (pdents[last].flags & DIR_OR_DIRLNK)) {
6518 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6522 move(2 + last - curscroll, 0);
6523 printent(&pdents[last], ncols, FALSE);
6525 if (g_state.oldcolor && (pdents[cur].flags & DIR_OR_DIRLNK)) {
6526 if (!dir) {/* First file is not a directory */
6527 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6530 } else if (dir) { /* Second file is not a directory */
6531 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6535 move(2 + cur - curscroll, 0);
6536 printent(&pdents[cur], ncols, TRUE);
6538 /* Must reset e.g. no files in dir */
6540 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6545 static void redraw(char *path)
6547 getmaxyx(stdscr, xlines, xcols);
6549 int ncols = (xcols <= PATH_MAX) ? xcols : PATH_MAX;
6550 int onscreen = xlines - 4;
6557 if (ndents && (last_curscroll == curscroll))
6558 return draw_line(ncols);
6561 DPRINTF_S(__func__);
6566 /* Enforce scroll/cursor invariants */
6567 move_cursor(cur, 1);
6569 /* Fail redraw if < than 10 columns, context info prints 10 chars */
6570 if (ncols <= MIN_DISPLAY_COL) {
6571 printmsg(messages[MSG_FEW_COLUMNS]);
6578 for (i = 0; i < CTX_MAX; ++i) { /* 8 chars printed for contexts - "1 2 3 4 " */
6579 if (!g_ctx[i].c_cfg.ctxactive)
6582 addch((i + '1') | (COLOR_PAIR(i + 1) | A_BOLD
6583 /* active: underline, current: reverse */
6584 | ((cfg.curctx != i) ? A_UNDERLINE : A_REVERSE)));
6589 attron(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6592 bool in_home = set_tilde_in_path(path);
6593 char *ptr = in_home ? &path[homelen - 1] : path;
6595 i = (int)xstrlen(ptr);
6596 if ((i + MIN_DISPLAY_COL) <= ncols)
6597 addnstr(ptr, ncols - MIN_DISPLAY_COL);
6599 char *base = xmemrchr((uchar_t *)ptr, '/', i);
6608 if (ptr && (base != ptr)) {
6609 while (ptr < base) {
6611 i += 2; /* 2 characters added */
6612 if (ncols < i + MIN_DISPLAY_COL) {
6613 base = NULL; /* Can't print more characters */
6625 addnstr(base, ncols - (MIN_DISPLAY_COL + i));
6629 reset_tilde_in_path(path);
6631 attroff(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6633 /* Go to first entry */
6634 if (curscroll > 0) {
6636 #ifdef ICONS_ENABLED
6637 addstr(ICON_ARROW_UP);
6643 if (g_state.oldcolor) {
6644 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6645 g_state.dircolor = 1;
6648 onscreen = MIN(onscreen + curscroll, ndents);
6650 ncols = adjust_cols(ncols);
6652 int len = scanselforpath(path, FALSE);
6655 for (i = curscroll; i < onscreen; ++i) {
6659 findmarkentry(len, &pdents[i]);
6661 printent(&pdents[i], ncols, i == cur);
6664 /* Must reset e.g. no files in dir */
6665 if (g_state.dircolor) {
6666 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6667 g_state.dircolor = 0;
6670 /* Go to last entry */
6671 if (onscreen < ndents) {
6672 move(xlines - 2, 0);
6673 #ifdef ICONS_ENABLED
6674 addstr(ICON_ARROW_DOWN);
6683 static bool cdprep(char *lastdir, char *lastname, char *path, char *newpath)
6688 /* Save last working directory */
6689 xstrsncpy(lastdir, path, PATH_MAX);
6691 /* Save the newly opted dir in path */
6692 xstrsncpy(path, newpath, PATH_MAX);
6696 return cfg.filtermode;
6699 static void showselsize(const char *path)
6702 int len = scanselforpath(path, FALSE);
6704 for (int r = 0, selcount = nselected; (r < ndents) && selcount; ++r)
6705 if (findinsel(findselpos, len + xstrsncpy(g_sel + len, pdents[r].name, pdents[r].nlen))) {
6706 sz += cfg.blkorder ? pdents[r].blocks : pdents[r].size;
6710 printmsg(coolsize(cfg.blkorder ? sz << blk_shift : sz));
6713 static bool browse(char *ipath, const char *session, int pkey)
6715 alignas(max_align_t) char newpath[PATH_MAX];
6716 alignas(max_align_t) char runfile[NAME_MAX + 1];
6717 char *path, *lastdir, *lastname, *dir, *tmp;
6721 int r = -1, presel, selstartid = 0, selendid = 0;
6722 const uchar_t opener_flags = (cfg.cliopener ? F_CLI : (F_NOTRACE | F_NOSTDIN | F_NOWAIT));
6723 bool watch = FALSE, cd = TRUE;
6728 struct timespec mousetimings[2] = {{.tv_sec = 0, .tv_nsec = 0}, {.tv_sec = 0, .tv_nsec = 0}};
6729 int mousedent[2] = {-1, -1};
6730 bool currentmouse = 1, rightclicksel = 0;
6735 getmaxyx(stdscr, xlines, xcols);
6738 /* set-up first context */
6739 if (!session || !load_session(session, &path, &lastdir, &lastname, FALSE)) {
6743 g_ctx[0].c_last[0] = '\0';
6744 lastdir = g_ctx[0].c_last; /* last visited directory */
6746 if (g_state.initfile) {
6747 xstrsncpy(g_ctx[0].c_name, xbasename(ipath), sizeof(g_ctx[0].c_name));
6750 g_ctx[0].c_name[0] = '\0';
6752 lastname = g_ctx[0].c_name; /* last visited file name */
6754 xstrsncpy(g_ctx[0].c_path, ipath, PATH_MAX);
6755 /* If the initial path is a file, retain a way to return to start dir */
6756 if (g_state.initfile) {
6758 initpath = ipath = getcwd(NULL, 0);
6760 path = g_ctx[0].c_path; /* current directory */
6762 g_ctx[0].c_fltr[0] = g_ctx[0].c_fltr[1] = '\0';
6763 g_ctx[0].c_cfg = cfg; /* current configuration */
6768 newpath[0] = runfile[0] = '\0';
6770 presel = pkey ? ((pkey == CREATE_NEW_KEY) ? 'n' : ';') : ((cfg.filtermode
6771 || (session && (g_ctx[cfg.curctx].c_fltr[0] == FILTER
6772 || g_ctx[cfg.curctx].c_fltr[0] == RFILTER)
6773 && g_ctx[cfg.curctx].c_fltr[1])) ? FILTER : 0);
6775 pdents = xrealloc(pdents, total_dents * sizeof(struct entry));
6779 /* Allocate buffer to hold names */
6780 pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
6784 /* The following call is added to handle a broken window at start */
6785 if (presel == FILTER)
6786 handle_key_resize();
6790 * Can fail when permissions change while browsing.
6791 * It's assumed that path IS a directory when we are here.
6793 if (chdir(path) == -1) {
6794 DPRINTF_S("directory inaccessible");
6795 valid_parent(path, lastname);
6803 #ifdef LINUX_INOTIFY
6804 if ((presel == FILTER || watch) && inotify_wd >= 0) {
6805 inotify_rm_watch(inotify_fd, inotify_wd);
6809 #elif defined(BSD_KQUEUE)
6810 if ((presel == FILTER || watch) && event_fd >= 0) {
6815 #elif defined(HAIKU_NM)
6816 if ((presel == FILTER || watch) && haiku_hnd != NULL) {
6817 haiku_stop_watch(haiku_hnd);
6818 haiku_nm_active = FALSE;
6824 if (cfgsort[cfg.curctx] != '0') {
6825 if (cfgsort[cfg.curctx] == 'z')
6826 set_sort_flags('c');
6827 if ((!cfgsort[cfg.curctx] || (cfgsort[cfg.curctx] == 'c'))
6828 && ((r = get_kv_key(order, path, maxorder, NNN_ORDER)) > 0)) { // NOLINT
6830 cfgsort[cfg.curctx] = 'z';
6833 cfgsort[cfg.curctx] = cfgsort[CTX_MAX];
6837 populate(path, lastname);
6838 if (g_state.interrupt) {
6839 g_state.interrupt = cfg.apparentsz = cfg.blkorder = 0;
6840 blk_shift = BLK_SHIFT_512;
6841 presel = CONTROL('L');
6844 #ifdef LINUX_INOTIFY
6845 if (presel != FILTER && inotify_wd == -1)
6846 inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
6847 #elif defined(BSD_KQUEUE)
6848 if (presel != FILTER && event_fd == -1) {
6849 #if defined(O_EVTONLY)
6850 event_fd = open(path, O_EVTONLY);
6852 event_fd = open(path, O_RDONLY);
6855 EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
6856 EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
6858 #elif defined(HAIKU_NM)
6859 haiku_nm_active = haiku_watch_dir(haiku_hnd, path) == EXIT_SUCCESS;
6863 /* Do not do a double redraw in filterentries */
6864 if ((presel != FILTER) || !filterset()) {
6870 /* Exit if parent has exited */
6872 _exit(EXIT_FAILURE);
6874 /* If CWD is deleted or moved or perms changed, find an accessible parent */
6875 if (chdir(path) == -1)
6878 /* If STDIN is no longer a tty (closed) we should exit */
6879 if (!isatty(STDIN_FILENO) && !g_state.picker)
6880 return EXIT_FAILURE;
6882 sel = nextsel(presel);
6889 if (getmouse(&event) != OK)
6892 /* Handle clicking on a context at the top */
6893 if (event.bstate == BUTTON1_PRESSED && event.y == 0) {
6894 /* Get context from: "[1 2 3 4]..." */
6897 /* If clicked after contexts, go to parent */
6900 else if (r >= 0 && r != cfg.curctx) {
6901 savecurctx(path, ndents ? pdents[cur].name : NULL, r);
6903 /* Reset the pointers */
6904 path = g_ctx[r].c_path;
6905 lastdir = g_ctx[r].c_last;
6906 lastname = g_ctx[r].c_name;
6916 if (sel == SEL_BACK) {
6918 dir = visit_parent(path, newpath, &presel);
6923 xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
6925 cdprep(lastdir, NULL, path, dir) ? (presel = FILTER) : (watch = TRUE);
6932 /* Middle click action */
6933 if (event.bstate == BUTTON2_PRESSED) {
6934 presel = middle_click_key;
6937 #if NCURSES_MOUSE_VERSION > 1
6939 if (event.bstate == BUTTON4_PRESSED && ndents && (cfg.rollover || cur)) {
6940 move_cursor((!cfg.rollover && cur < scroll_lines
6941 ? 0 : (cur + ndents - scroll_lines) % ndents), 0);
6946 if (event.bstate == BUTTON5_PRESSED && ndents
6947 && (cfg.rollover || (cur != ndents - 1))) {
6948 move_cursor((!cfg.rollover && cur >= ndents - scroll_lines)
6949 ? (ndents - 1) : ((cur + scroll_lines) % ndents), 0);
6954 /* Toggle filter mode on left click on last 2 lines */
6955 if (event.y >= xlines - 2 && event.bstate == BUTTON1_PRESSED) {
6957 cfg.filtermode ^= 1;
6958 if (cfg.filtermode) {
6963 /* Start watching the directory */
6970 /* Handle clicking on a file */
6971 if (event.y >= 2 && event.y <= ndents + 1 &&
6972 (event.bstate == BUTTON1_PRESSED ||
6973 event.bstate == BUTTON3_PRESSED)) {
6974 r = curscroll + (event.y - 2);
6978 else if ((event.bstate == BUTTON1_PRESSED) && !g_state.fifomode)
6979 notify_fifo(TRUE); /* Send clicked path to NNN_FIFO */
6981 /* Handle right click selection */
6982 if (event.bstate == BUTTON3_PRESSED) {
6990 #if defined(CLOCK_MONOTONIC_RAW)
6991 CLOCK_MONOTONIC_RAW,
6992 #elif defined(CLOCK_MONOTONIC)
6997 &mousetimings[currentmouse]);
6998 mousedent[currentmouse] = cur;
7000 /* Single click just selects, double click falls through to SEL_OPEN */
7001 if ((mousedent[0] != mousedent[1]) ||
7002 (((_ABSSUB(mousetimings[0].tv_sec, mousetimings[1].tv_sec) << 30)
7003 + (_ABSSUB(mousetimings[0].tv_nsec, mousetimings[1].tv_nsec)))
7004 > DBLCLK_INTERVAL_NS))
7007 mousetimings[currentmouse].tv_sec = 0;
7008 mousedent[currentmouse] = -1;
7011 if (cfg.filtermode || filterset())
7018 case SEL_NAV_IN: // fallthrough
7020 /* Cannot descend in empty directories */
7023 g_state.selbm = g_state.runplugin = 0;
7027 pent = &pdents[cur];
7028 if (!g_state.selbm || !(S_ISLNK(pent->mode) &&
7029 realpath(pent->name, newpath) &&
7030 xstrsncpy(path, lastdir, PATH_MAX)))
7031 mkpath(path, pent->name, newpath);
7035 /* Visit directory */
7036 if (pent->flags & DIR_OR_DIRLNK) {
7037 if (chdir(newpath) == -1) {
7042 cdprep(lastdir, lastname, path, newpath) ? (presel = FILTER) : (watch = TRUE);
7046 /* Cannot use stale data in entry, file may be missing by now */
7047 if (stat(newpath, &sb) == -1) {
7051 DPRINTF_U(sb.st_mode);
7053 /* Do not open non-regular files */
7054 if (!S_ISREG(sb.st_mode)) {
7055 printwait(messages[MSG_UNSUPPORTED], &presel);
7059 /* Handle plugin selection mode */
7060 if (g_state.runplugin) {
7061 g_state.runplugin = 0;
7062 /* Must be in plugin dir and same context to select plugin */
7063 if ((g_state.runctx == cfg.curctx) && !strcmp(path, plgpath)) {
7064 endselection(FALSE);
7065 /* Copy path so we can return back to earlier dir */
7066 xstrsncpy(path, lastdir, PATH_MAX);
7069 if (chdir(path) == -1
7070 || !run_plugin(&path, pent->name, runfile, &lastname, &lastdir)) {
7071 DPRINTF_S("plugin failed!");
7075 return EXIT_SUCCESS;
7078 xstrsncpy(lastname, runfile, NAME_MAX + 1);
7087 if (g_state.fifomode && (sel == SEL_OPEN)) {
7088 send_to_explorer(&presel); /* Write selection to explorer fifo */
7092 /* If opened as vim plugin and Enter/^M pressed, pick */
7093 if (g_state.picker && (sel == SEL_OPEN)) {
7094 if (nselected == 0) /* Pick if none selected */
7095 appendfpath(newpath, mkpath(path, pent->name, newpath));
7096 return EXIT_SUCCESS;
7099 if (sel == SEL_NAV_IN) {
7100 /* If in listing dir, go to target on `l` or Right on symlink */
7101 if (listpath && S_ISLNK(pent->mode)
7102 && is_prefix(path, listpath, xstrlen(listpath))) {
7103 if (!realpath(pent->name, newpath)) {
7110 if (chdir(newpath) == -1) {
7115 cdprep(lastdir, NULL, path, newpath)
7116 ? (presel = FILTER) : (watch = TRUE);
7117 xstrsncpy(lastname, pent->name, NAME_MAX + 1);
7121 /* Open file disabled on right arrow or `l` */
7127 printwait(messages[MSG_EMPTY_FILE], &presel);
7132 #ifdef FILE_MIME_OPTS
7133 && get_output("file", FILE_MIME_OPTS, newpath, -1, FALSE)
7134 && is_prefix(g_buf, "text/", 5)
7136 /* no MIME option; guess from description instead */
7137 && get_output("file", "-bL", newpath, -1, FALSE)
7138 && strstr(g_buf, "text")
7141 spawn(editor, newpath, NULL, NULL, F_CLI);
7142 if (cfg.filtermode) {
7149 /* Get the extension for regex match */
7150 tmp = xextension(pent->name, pent->nlen - 1);
7152 if (tmp && !pcre_exec(archive_pcre, NULL, tmp,
7153 pent->nlen - (tmp - pent->name) - 1, 0, 0, NULL, 0)) {
7155 if (tmp && !regexec(&archive_re, tmp, 0, NULL, 0)) {
7157 r = get_input(messages[MSG_ARCHIVE_OPTS]);
7160 if (r == 'l' || r == 'x') {
7161 mkpath(path, pent->name, newpath);
7162 if (!handle_archive(newpath, r)) {
7172 if ((r == 'm') && !archive_mount(newpath)) {
7177 if (r == 'x' || r == 'm') {
7179 set_smart_ctx('+', newpath, &path,
7180 ndents ? pdents[cur].name : NULL,
7181 &lastname, &lastdir);
7189 printwait(messages[MSG_INVALID_KEY], &presel);
7194 /* Invoke desktop opener as last resort */
7195 spawn(opener, newpath, NULL, NULL, opener_flags);
7197 /* Move cursor to the next entry if not the last entry */
7198 if (g_state.autonext && cur != ndents - 1)
7199 move_cursor((cur + 1) % ndents, 0);
7200 if (cfg.filtermode) {
7205 case SEL_NEXT: // fallthrough
7206 case SEL_PREV: // fallthrough
7207 case SEL_PGDN: // fallthrough
7208 case SEL_CTRL_D: // fallthrough
7209 case SEL_PGUP: // fallthrough
7210 case SEL_CTRL_U: // fallthrough
7211 case SEL_HOME: // fallthrough
7212 case SEL_END: // fallthrough
7213 case SEL_FIRST: // fallthrough
7214 case SEL_JUMP: // fallthrough
7218 handle_screen_move(sel);
7221 case SEL_CDHOME: // fallthrough
7222 case SEL_CDBEGIN: // fallthrough
7223 case SEL_CDLAST: // fallthrough
7225 dir = (sel == SEL_CDHOME) ? home
7226 : ((sel == SEL_CDBEGIN) ? ipath
7227 : ((sel == SEL_CDLAST) ? lastdir
7228 : "/" /* SEL_CDROOT */));
7230 if (!dir || !*dir) {
7231 printwait(messages[MSG_NOT_SET], &presel);
7236 if (strcmp(path, dir) == 0) {
7242 dir = lastdir; /* Go to last dir on home/root key repeat */
7245 if (chdir(dir) == -1) {
7250 /* SEL_CDLAST: dir pointing to lastdir */
7251 xstrsncpy(newpath, dir, PATH_MAX); // fallthrough
7253 if (sel == SEL_BMOPEN) {
7254 r = (int)handle_bookmark(mark, newpath);
7256 printwait(messages[r], &presel);
7260 if (g_state.selbm == 1) /* Allow filtering in bookmarks directory */
7262 if (strcmp(path, newpath) == 0)
7266 /* In list mode, retain the last file name to highlight it, if possible */
7267 cdprep(lastdir, listpath && sel == SEL_CDLAST ? NULL : lastname, path, newpath)
7268 ? (presel = FILTER) : (watch = TRUE);
7271 if ((sel == SEL_REMOTE) && !remote_mount(newpath)) {
7276 set_smart_ctx('+', newpath, &path,
7277 ndents ? pdents[cur].name : NULL, &lastname, &lastdir);
7280 case SEL_CYCLE: // fallthrough
7281 case SEL_CYCLER: // fallthrough
7282 case SEL_CTX1: // fallthrough
7283 case SEL_CTX2: // fallthrough
7284 case SEL_CTX3: // fallthrough
7292 r = handle_context_switch(sel);
7295 savecurctx(path, ndents ? pdents[cur].name : NULL, r);
7297 /* Reset the pointers */
7298 path = g_ctx[r].c_path;
7299 lastdir = g_ctx[r].c_last;
7300 lastname = g_ctx[r].c_name;
7301 tmp = g_ctx[r].c_fltr;
7303 if (cfg.filtermode || ((tmp[0] == FILTER || tmp[0] == RFILTER) && tmp[1]))
7311 mark = xstrdup(path);
7312 printwait(mark, &presel);
7315 add_bookmark(path, newpath, &presel);
7318 /* Unwatch dir if we are still in a filtered view */
7319 #ifdef LINUX_INOTIFY
7320 if (inotify_wd >= 0) {
7321 inotify_rm_watch(inotify_fd, inotify_wd);
7324 #elif defined(BSD_KQUEUE)
7325 if (event_fd >= 0) {
7329 #elif defined(HAIKU_NM)
7330 if (haiku_nm_active) {
7331 haiku_stop_watch(haiku_hnd);
7332 haiku_nm_active = FALSE;
7335 presel = filterentries(path, lastname);
7336 if (presel == ESC) {
7340 if (presel == FILTER) { /* Refresh dir and filter again */
7345 case SEL_MFLTR: // fallthrough
7346 case SEL_HIDDEN: // fallthrough
7347 case SEL_DETAIL: // fallthrough
7351 cfg.filtermode ^= 1;
7352 if (cfg.filtermode) {
7358 watch = TRUE; // fallthrough
7360 if (sel == SEL_HIDDEN) {
7361 cfg.showhidden ^= 1;
7370 cfg.showdetail ^= 1;
7373 default: /* SEL_SORT */
7374 r = set_sort_flags(get_input(messages[MSG_ORDER]));
7376 printwait(messages[MSG_INVALID_KEY], &presel);
7381 if (cfg.filtermode || filterset())
7387 if (r == 'd' || r == 'a') {
7392 ENTSORT(pdents, ndents, entrycmpfn);
7393 move_cursor(ndents ? dentfind(lastname, ndents) : 0, 0);
7396 case SEL_STATS: // fallthrough
7399 tmp = (listpath && xstrcmp(path, listpath) == 0) ? listroot : path;
7400 mkpath(tmp, pdents[cur].name, newpath);
7402 if ((sel == SEL_STATS && !show_stats(newpath))
7403 || (lstat(newpath, &sb) == -1)
7404 || (sel == SEL_CHMODX && !xchmod(newpath, &sb.st_mode))) {
7409 if (sel == SEL_CHMODX)
7410 pdents[cur].mode = sb.st_mode;
7413 case SEL_REDRAW: // fallthrough
7414 case SEL_RENAMEMUL: // fallthrough
7415 case SEL_HELP: // fallthrough
7416 case SEL_AUTONEXT: // fallthrough
7417 case SEL_EDIT: // fallthrough
7420 bool refresh = FALSE;
7423 mkpath(path, pdents[cur].name, newpath);
7424 else if (sel == SEL_EDIT) /* Avoid trying to edit a non-existing file */
7433 setenv("NNN_INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
7434 setenv("NNN_PREFER_SELECTION", xitoa(cfg.prefersel), 1);
7435 setenv("NNN_LIST", listpath ? listroot : "", 1);
7437 if (!(getutil(utils[UTIL_BASH])
7438 && plugscript(utils[UTIL_NMV], F_CLI))
7443 printwait(messages[MSG_FAILED], &presel);
7450 show_help(path); // fallthrough
7452 if (sel == SEL_AUTONEXT)
7453 g_state.autonext ^= 1;
7459 if (!(g_state.picker || g_state.fifomode))
7460 spawn(editor, newpath, NULL, NULL, F_CLI);
7462 default: /* SEL_LOCK */
7467 /* In case of successful operation, reload contents */
7469 /* Continue in type-to-nav mode, if enabled */
7470 if ((cfg.filtermode || filterset()) && !refresh) {
7477 /* Repopulate as directory content may have changed */
7486 if (g_state.rangesel)
7487 g_state.rangesel = 0;
7489 /* Toggle selection status */
7490 pdents[cur].flags ^= FILE_SELECTED;
7492 if (pdents[cur].flags & FILE_SELECTED) {
7494 appendfpath(newpath, mkpath(path, pdents[cur].name, newpath));
7495 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
7498 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
7503 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7510 /* move cursor to the next entry if this is not the last entry */
7511 if (!g_state.stayonsel && (cur != ndents - 1))
7512 move_cursor((cur + 1) % ndents, 0);
7519 g_state.rangesel ^= 1;
7521 if (stat(path, &sb) == -1) {
7526 if (g_state.rangesel) { /* Range selection started */
7532 if (inode != sb.st_ino) {
7533 printwait(messages[MSG_DIR_CHANGED], &presel);
7537 if (cur < selstartid) {
7538 selendid = selstartid;
7543 /* Clear selection on repeat on same file */
7544 if (selstartid == selendid) {
7549 case SEL_SELALL: // fallthrough
7551 if (sel == SEL_SELALL || sel == SEL_SELINV) {
7556 if (g_state.rangesel)
7557 g_state.rangesel = 0;
7560 selendid = ndents - 1;
7563 if ((nselected > LARGESEL) || (nselected && (ndents > LARGESEL))) {
7564 printmsg("processing...");
7568 r = scanselforpath(path, TRUE); /* Get path length suffixed by '/' */
7569 ((sel == SEL_SELINV) && findselpos)
7570 ? invertselbuf(r) : addtoselbuf(r, selstartid, selendid);
7574 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7578 r = editselection();
7580 r = !r ? MSG_0_SELECTED : MSG_FAILED;
7581 printwait(messages[r], &presel);
7585 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7587 cfg.filtermode ? presel = FILTER : statusbar(path);
7590 case SEL_CP: // fallthrough
7591 case SEL_MV: // fallthrough
7592 case SEL_CPMVAS: // fallthrough
7595 if (sel == SEL_RM) {
7596 r = get_cur_or_sel();
7603 tmp = (listpath && xstrcmp(path, listpath) == 0)
7605 mkpath(tmp, pdents[cur].name, newpath);
7609 xrmfromsel(tmp, newpath);
7611 copynextname(lastname);
7613 if (cfg.filtermode || filterset())
7620 (nselected == 1 && (sel == SEL_CP || sel == SEL_MV))
7621 ? mkpath(path, xbasename(pselbuf), newpath)
7622 : (newpath[0] = '\0');
7626 if (!cpmvrm_selection(sel, path)) {
7636 /* Show notification on operation complete */
7638 plugscript(utils[UTIL_NTFY], F_NOWAIT | F_NOTRACE);
7641 if (newpath[0] && !access(newpath, F_OK))
7642 xstrsncpy(lastname, xbasename(newpath), NAME_MAX+1);
7648 case SEL_ARCHIVE: // fallthrough
7649 case SEL_OPENWITH: // fallthrough
7650 case SEL_NEW: // fallthrough
7656 if (!ndents && (sel == SEL_OPENWITH || sel == SEL_RENAME))
7659 if (sel != SEL_OPENWITH)
7664 r = get_cur_or_sel();
7678 tmp = pdents[cur].name;
7680 tmp = xreadline(tmp, messages[MSG_ARCHIVE_NAME]);
7684 if (g_state.picker) {
7686 tmp = xreadline(NULL, messages[MSG_OPEN_WITH]);
7689 tmp = getreadline(messages[MSG_OPEN_WITH]);
7694 r = get_input(messages[MSG_NEW_OPTS]);
7700 tmp = g_ctx[0].c_name;
7704 if (r == 'f' || r == 'd')
7705 tmp = xreadline(tmp, messages[MSG_NEW_PATH]);
7706 else if (r == 's' || r == 'h')
7707 tmp = xreadline(NULL,
7708 messages[nselected <= 1 ? MSG_NEW_PATH : MSG_LINK_PREFIX]);
7712 default: /* SEL_RENAME */
7713 tmp = xreadline(pdents[cur].name, "");
7717 if (!tmp || !*tmp || is_bad_len_or_dir(tmp))
7722 if (r == 'c' && strcmp(tmp, pdents[cur].name) == 0)
7723 continue; /* Cannot overwrite the hovered file */
7725 tmp = abspath(tmp, NULL, newpath);
7728 if (access(tmp, F_OK) == 0) {
7729 if (!xconfirm(get_input(messages[MSG_OVERWRITE]))) {
7735 (r == 's') ? archive_selection(get_archive_cmd(tmp), tmp)
7736 : spawn(get_archive_cmd(tmp), tmp, pdents[cur].name,
7737 NULL, F_CLI | F_CONFIRM);
7739 if (tmp && (access(tmp, F_OK) == 0)) { /* File created */
7741 clearselection(); /* Archive operation complete */
7743 /* Check if any entry is created in the current directory */
7744 tmp = get_cwd_entry(path, tmp, &len);
7746 xstrsncpy(lastname, tmp, len + 1);
7747 clearfilter(); /* Archive name may not match */
7748 } if (cfg.filtermode)
7755 handle_openwith(path, pdents[cur].name, newpath, tmp);
7757 cfg.filtermode ? presel = FILTER : statusbar(path);
7762 /* Skip renaming to same name */
7763 if (strcmp(tmp, pdents[cur].name) == 0) {
7764 tmp = xreadline(pdents[cur].name, messages[MSG_COPY_NAME]);
7765 if (!tmp || !tmp[0] || is_bad_len_or_dir(tmp)
7766 || !strcmp(tmp, pdents[cur].name)) {
7767 cfg.filtermode ? presel = FILTER : statusbar(path);
7774 default: /* SEL_NEW */
7778 if (!(r == 's' || r == 'h')) {
7779 tmp = abspath(tmp, NULL, newpath);
7786 /* Check if another file with same name exists */
7787 if (lstat(tmp, &sb) == 0) {
7788 if ((sel == SEL_RENAME) || ((r == 'f') && (S_ISREG(sb.st_mode)))) {
7789 /* Overwrite file with same name? */
7790 if (!xconfirm(get_input(messages[MSG_OVERWRITE])))
7793 /* Do nothing for SEL_NEW if a non-regular entry exists */
7794 printwait(messages[MSG_EXISTS], &presel);
7799 if (sel == SEL_RENAME) {
7800 /* Rename the file */
7802 spawn("cp -rp", pdents[cur].name, tmp, NULL, F_SILENT);
7803 else if (rename(pdents[cur].name, tmp) != 0) {
7808 /* Check if any entry is created in the current directory */
7809 tmp = get_cwd_entry(path, tmp, &len);
7811 xstrsncpy(lastname, tmp, len + 1);
7812 /* Directory must be reloeaded for rename case */
7813 } else { /* SEL_NEW */
7816 /* Check if it's a dir or file */
7817 if (r == 'f' || r == 'd') {
7818 ret = xmktree(tmp, r == 'f' ? FALSE : TRUE);
7819 } else if (r == 's' || r == 'h') {
7820 if (nselected > 1 && tmp[0] == '@' && tmp[1] == '\0')
7822 ret = xlink(tmp, path, (ndents ? pdents[cur].name : NULL), newpath, r);
7831 if (r == 'f' || r == 'd') {
7832 tmp = get_cwd_entry(path, tmp, &len);
7834 xstrsncpy(lastname, tmp, len + 1);
7836 continue; /* No change in directory */
7837 } else if (ndents) {
7849 /* Check if directory is accessible */
7850 if (!xdiraccess(plgpath)) {
7856 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
7857 printkeys(plug, g_buf + r - 1, maxplug);
7859 r = get_input(NULL);
7866 endselection(FALSE);
7867 tmp = get_kv_val(plug, NULL, r, maxplug, NNN_PLUG);
7869 printwait(messages[MSG_INVALID_KEY], &presel);
7873 if (tmp[0] == '-' && tmp[1]) {
7875 r = FALSE; /* Do not refresh dir after completion */
7879 if (!run_plugin(&path, tmp, (ndents ? pdents[cur].name : NULL),
7880 &lastname, &lastdir)) {
7881 printwait(messages[MSG_FAILED], &presel);
7886 return EXIT_SUCCESS;
7891 cfg.filtermode ? presel = FILTER : statusbar(path);
7894 } else { /* 'Return/Enter' enters the plugin directory */
7895 g_state.runplugin ^= 1;
7896 if (!g_state.runplugin) {
7898 * If toggled, and still in the plugin dir,
7899 * switch to original directory
7901 if (strcmp(path, plgpath) == 0) {
7902 xstrsncpy(path, lastdir, PATH_MAX);
7903 xstrsncpy(lastname, runfile, NAME_MAX + 1);
7909 /* Otherwise, initiate choosing plugin again */
7910 g_state.runplugin = 1;
7913 xstrsncpy(lastdir, path, PATH_MAX);
7914 xstrsncpy(path, plgpath, PATH_MAX);
7916 xstrsncpy(runfile, pdents[cur].name, NAME_MAX);
7917 g_state.runctx = cfg.curctx;
7922 if (g_state.runplugin == 1) /* Allow filtering in plugins directory */
7928 case SEL_SHELL: // fallthrough
7929 case SEL_LAUNCH: // fallthrough
7931 r = handle_cmd(sel, newpath);
7933 /* Continue in type-to-nav mode, if enabled */
7943 /* Repopulate as directory content may have changed */
7948 if (!unmount((ndents ? pdents[cur].name : NULL), newpath, &presel, path)) {
7949 if (presel == MSG_ZERO)
7954 /* Dir removed, go to next entry */
7955 copynextname(lastname);
7960 r = get_input(messages[MSG_SSN_OPTS]);
7963 tmp = xreadline(NULL, messages[MSG_SSN_NAME]);
7965 save_session(tmp, &presel);
7966 } else if (r == 'l' || r == 'r') {
7967 if (load_session(NULL, &path, &lastdir, &lastname, r == 'r')) {
7978 cfg.filtermode ? presel = FILTER : statusbar(path);
7981 if (!set_time_type(&presel))
7985 case SEL_QUITCTX: // fallthrough
7986 case SEL_QUITCD: // fallthrough
7989 if (sel == SEL_QUITCTX) {
7990 int ctx = cfg.curctx;
7992 for (r = (ctx - 1) & (CTX_MAX - 1);
7993 (r != ctx) && !g_ctx[r].c_cfg.ctxactive;
7994 r = ((r - 1) & (CTX_MAX - 1))) {
7998 g_ctx[ctx].c_cfg.ctxactive = 0;
8000 /* Switch to next active context */
8001 path = g_ctx[r].c_path;
8002 lastdir = g_ctx[r].c_last;
8003 lastname = g_ctx[r].c_name;
8005 cfg = g_ctx[r].c_cfg;
8011 } else if (!g_state.forcequit) {
8012 for (r = 0; r < CTX_MAX; ++r)
8013 if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
8014 r = get_input(messages[MSG_QUIT_ALL]);
8018 if (!(r == CTX_MAX || xconfirm(r)))
8019 break; // fallthrough
8023 tmp = getenv("NNN_TMPFILE");
8024 if ((sel == SEL_QUITCD) || tmp) {
8025 write_lastdir(path, tmp);
8026 /* ^G is a way to quit picker mode without picking anything */
8027 if ((sel == SEL_QUITCD) && g_state.picker)
8031 if (sel != SEL_QUITERR)
8032 return EXIT_SUCCESS;
8034 if (selbufpos && !g_state.picker) {
8035 /* Pick files to stdout and exit */
8039 return EXIT_SUCCESS;
8042 return EXIT_FAILURE;
8044 if (xlines != LINES || xcols != COLS)
8047 if (idletimeout && idle == idletimeout) {
8048 lock_terminal(); /* Locker */
8054 } /* switch (sel) */
8058 static char *make_tmp_tree(char **paths, ssize_t entries, const char *prefix)
8060 /* tmpdir holds the full path */
8061 /* tmp holds the path without the tmp dir prefix */
8065 ssize_t len = xstrlen(prefix);
8066 char *tmpdir = malloc(PATH_MAX);
8069 DPRINTF_S(strerror(errno));
8073 tmp = tmpdir + tmpfplen - 1;
8074 xstrsncpy(tmpdir, g_tmpfpath, tmpfplen);
8075 xstrsncpy(tmp, "/nnnXXXXXX", 11);
8077 /* Points right after the base tmp dir */
8080 /* handle the case where files are directly under / */
8081 if (!prefix[1] && (prefix[0] == '/'))
8084 if (!mkdtemp(tmpdir)) {
8087 DPRINTF_S(strerror(errno));
8093 for (ssize_t i = 0; i < entries; ++i) {
8097 err = stat(paths[i], &sb);
8098 if (err && errno == ENOENT)
8101 /* Don't copy the common prefix */
8102 xstrsncpy(tmp, paths[i] + len, xstrlen(paths[i]) - len + 1);
8104 /* Get the dir containing the path */
8105 slash = xmemrchr((uchar_t *)tmp, '/', xstrlen(paths[i]) - len);
8109 if (access(tmpdir, F_OK)) /* Create directory if it doesn't exist */
8110 xmktree(tmpdir, TRUE);
8115 if (symlink(paths[i], tmpdir)) {
8116 DPRINTF_S(paths[i]);
8117 DPRINTF_S(strerror(errno));
8121 /* Get the dir in which to start */
8126 static char *load_input(int fd, const char *path)
8128 size_t i, chunk_count = 1, chunk = 512UL * 1024 /* 512 KiB chunk size */, entries = 0;
8129 char *input = malloc(sizeof(char) * chunk), *tmpdir = NULL;
8130 char cwd[PATH_MAX], *next;
8131 size_t offsets[LIST_FILES_MAX];
8132 char **paths = NULL;
8133 ssize_t input_read, total_read = 0, off = 0;
8137 DPRINTF_S(strerror(errno));
8142 if (!getcwd(cwd, PATH_MAX)) {
8147 xstrsncpy(cwd, path, PATH_MAX);
8149 while (chunk_count < LIST_INPUT_MAX / chunk && !msgnum) {
8150 input_read = read(fd, input + total_read, chunk);
8151 if (input_read < 0) {
8155 DPRINTF_S(strerror(errno));
8159 if (input_read == 0)
8162 total_read += input_read;
8164 while (off < total_read) {
8165 next = memchr(input + off, '\0', total_read - off);
8170 if (next - input == off + 1) {
8175 if (entries == LIST_FILES_MAX) {
8176 msgnum = MSG_FILE_LIMIT;
8180 offsets[entries++] = off;
8184 /* We don't need to allocate another chunk */
8185 if (chunk_count > (total_read + chunk - 1) / chunk)
8188 /* We can never need more than one additional chunk */
8190 if (chunk_count > LIST_INPUT_MAX / chunk) {
8191 msgnum = MSG_SIZE_LIMIT;
8195 input = xrealloc(input, chunk_count * chunk);
8200 /* We close fd outside this function. Any extra data is left to the kernel to handle */
8202 if (off != total_read) {
8203 if (entries == LIST_FILES_MAX)
8204 msgnum = MSG_FILE_LIMIT;
8206 offsets[entries++] = off;
8210 DPRINTF_D(total_read);
8211 DPRINTF_D(chunk_count);
8214 msgnum = MSG_0_ENTRIES;
8218 input[total_read] = '\0';
8220 paths = malloc(entries * sizeof(char *));
8224 for (i = 0; i < entries; ++i)
8225 paths[i] = input + offsets[i];
8227 listroot = malloc(sizeof(char) * PATH_MAX);
8232 DPRINTF_S(paths[0]);
8234 for (i = 0; i < entries; ++i) {
8235 if (paths[i][0] == '\n' || selforparent(paths[i])) {
8240 paths[i] = abspath(paths[i], cwd, NULL);
8242 entries = i; // free from the previous entry
8246 DPRINTF_S(paths[i]);
8248 xstrsncpy(g_buf, paths[i], PATH_MAX);
8249 if (!common_prefix(xdirname(g_buf), listroot)) {
8250 entries = i + 1; // free from the current entry
8254 DPRINTF_S(listroot);
8257 DPRINTF_S(listroot);
8260 tmpdir = make_tmp_tree(paths, entries, listroot);
8263 for (i = 0; i < entries; ++i)
8266 if (msgnum) { /* Check if we are past init stage and show msg */
8268 printmsg(messages[msgnum]);
8269 xdelay(XDELAY_INTERVAL_MS << 2);
8271 msg(messages[msgnum]);
8272 usleep(XDELAY_INTERVAL_MS << 2);
8281 static void check_key_collision(void)
8284 bool bitmap[KEY_MAX] = {FALSE};
8286 for (ullong_t i = 0; i < ELEMENTS(bindings); ++i) {
8287 key = bindings[i].sym;
8290 dprintf(STDERR_FILENO, "key collision! [%s]\n", keyname(key));
8296 static void usage(void)
8298 dprintf(STDOUT_FILENO,
8299 "%s: nnn [OPTIONS] [PATH]\n\n"
8300 "The unorthodox terminal file manager.\n\n"
8301 "positional args:\n"
8302 " PATH start dir/file [default: .]\n\n"
8305 " -a auto NNN_FIFO\n"
8307 " -A no dir auto-enter during filter\n"
8308 " -b key open bookmark key (trumps -s/S)\n"
8309 " -B use bsdtar for archives\n"
8310 " -c cli-only NNN_OPENER (trumps -e)\n"
8311 " -C 8-color scheme\n"
8313 " -D dirs in context color\n"
8314 " -e text in $VISUAL/$EDITOR/vi\n"
8315 " -E internal edits in EDITOR\n"
8317 " -f use readline history file\n"
8320 " -F val fifo mode [0:preview 1:explore]\n"
8322 " -g regex filters\n"
8323 " -H show hidden files\n"
8324 " -i show current file info\n"
8325 " -J no auto-advance on selection\n"
8326 " -K detect key collision and exit\n"
8327 " -l val set scroll lines\n"
8328 " -n type-to-nav mode\n"
8329 " -o open files only on Enter\n"
8330 " -p file selection file [-:stdout]\n"
8331 " -P key run plugin key\n"
8332 " -Q no quit confirmation\n"
8333 " -r use advcpmv patched cp, mv\n"
8334 " -R no rollover at edges\n"
8336 " -s name load session by name\n"
8337 " -S persistent session\n"
8339 " -t secs timeout to lock\n"
8340 " -T key sort order [a/d/e/r/s/t/v]\n"
8341 " -u use selection (no prompt)\n"
8343 " -U show user and group\n"
8345 " -V show version\n"
8347 " -x notis, selection sync, xterm title\n"
8350 "v%s\n%s\n", __func__, VERSION, GENERAL_INFO);
8353 static bool setup_config(void)
8356 char *xdgcfg = getenv("XDG_CONFIG_HOME");
8359 /* Set up configuration file paths */
8360 if (xdgcfg && xdgcfg[0]) {
8362 if (tilde_is_home(xdgcfg)) {
8363 r = xstrsncpy(g_buf, home, PATH_MAX);
8364 xstrsncpy(g_buf + r - 1, xdgcfg + 1, PATH_MAX);
8369 if (!xdiraccess(xdgcfg)) {
8374 len = xstrlen(xdgcfg) + xstrlen("/nnn/bookmarks") + 1;
8379 len = xstrlen(home) + xstrlen("/.config/nnn/bookmarks") + 1;
8381 cfgpath = (char *)malloc(len);
8382 plgpath = (char *)malloc(len);
8383 if (!cfgpath || !plgpath) {
8389 xstrsncpy(cfgpath, xdgcfg, len);
8390 r = len - xstrlen("/nnn/bookmarks");
8392 r = xstrsncpy(cfgpath, home, len);
8394 /* Create ~/.config */
8395 xstrsncpy(cfgpath + r - 1, "/.config", len - r);
8397 r += 8; /* length of "/.config" */
8400 /* Create ~/.config/nnn */
8401 xstrsncpy(cfgpath + r - 1, "/nnn", len - r);
8404 /* Create bookmarks, sessions, mounts and plugins directories */
8405 for (r = 0; r < ELEMENTS(toks); ++r) {
8406 mkpath(cfgpath, toks[r], plgpath);
8407 /* The dirs are created on first run, check if they already exist */
8408 if (access(plgpath, F_OK) && !xmktree(plgpath, TRUE)) {
8415 /* Set selection file path */
8416 if (!g_state.picker) {
8417 char *env_sel = xgetenv(env_cfg[NNN_SEL], NULL);
8419 selpath = env_sel ? xstrdup(env_sel)
8420 : (char *)malloc(len + 3); /* Length of "/.config/nnn/.selection" */
8428 r = xstrsncpy(selpath, cfgpath, len + 3);
8429 xstrsncpy(selpath + r - 1, "/.selection", 12);
8437 static bool set_tmp_path(void)
8440 char *path = xdiraccess(tmp) ? tmp : getenv("TMPDIR");
8447 tmpfplen = (uchar_t)xstrsncpy(g_tmpfpath, path, TMP_LEN_MAX);
8448 DPRINTF_S(g_tmpfpath);
8449 DPRINTF_U(tmpfplen);
8454 static void cleanup(void)
8457 if (cfg.x11 && !g_state.picker) {
8458 printf("\033[23;0t"); /* reset terminal window title */
8474 if (g_state.autofifo)
8477 if (g_state.pluginit)
8484 int main(int argc, char *argv[])
8487 char *session = NULL;
8488 int fd, opt, sort = 0, pkey = '\0'; /* Plugin key */
8491 char *middle_click_env = xgetenv(env_cfg[NNN_MCLICK], "\0");
8493 middle_click_key = (middle_click_env[0] == '^' && middle_click_env[1])
8494 ? CONTROL(middle_click_env[1])
8495 : (uchar_t)middle_click_env[0];
8498 const char * const env_opts = xgetenv(env_cfg[NNN_OPTS], NULL);
8499 int env_opts_id = env_opts ? (int)xstrlen(env_opts) : -1;
8501 bool rlhist = FALSE;
8504 while ((opt = (env_opts_id > 0
8505 ? env_opts[--env_opts_id]
8506 : getopt(argc, argv, "aAb:BcCdDeEfF:gHiJKl:nop:P:QrRs:St:T:uUVxh"))) != -1) {
8510 g_state.autofifo = 1;
8517 if (env_opts_id < 0)
8521 g_state.usebsdtar = 1;
8527 g_state.oldcolor = 1;
8548 if (env_opts_id < 0) {
8550 if ((fd < 0) || (fd > 1))
8551 return EXIT_FAILURE;
8552 g_state.fifomode = fd;
8558 filterfn = &visible_re;
8567 g_state.stayonsel = 1;
8570 check_key_collision();
8571 return EXIT_SUCCESS;
8573 if (env_opts_id < 0)
8574 scroll_lines = atoi(optarg);
8583 if (env_opts_id >= 0)
8587 if (!(optarg[0] == '-' && optarg[1] == '\0')) {
8588 fd = open(optarg, O_WRONLY | O_CREAT, 0600);
8591 return EXIT_FAILURE;
8595 selpath = abspath(optarg, NULL, NULL);
8600 if (env_opts_id < 0 && !optarg[1])
8601 pkey = (uchar_t)optarg[0];
8604 g_state.forcequit = 1;
8608 memcpy(cp, PROGRESS_CP, sizeof PROGRESS_CP);
8609 memcpy(mv, PROGRESS_MV, sizeof PROGRESS_MV);
8617 if (env_opts_id < 0)
8621 g_state.prstssn = 1;
8622 if (!session) /* Support named persistent sessions */
8627 if (env_opts_id < 0)
8628 idletimeout = atoi(optarg);
8631 if (env_opts_id < 0)
8632 sort = (uchar_t)optarg[0];
8641 dprintf(STDOUT_FILENO, "%s\n", VERSION);
8642 return EXIT_SUCCESS;
8648 return EXIT_SUCCESS;
8651 return EXIT_FAILURE;
8653 if (env_opts_id == 0)
8662 /* Prefix for temporary files */
8663 if (!set_tmp_path())
8664 return EXIT_FAILURE;
8668 /* Check if we are in path list mode */
8669 if (!isatty(STDIN_FILENO)) {
8670 /* This is the same as listpath */
8671 initpath = load_input(STDIN_FILENO, NULL);
8673 return EXIT_FAILURE;
8675 /* We return to tty */
8676 if (!isatty(STDOUT_FILENO)) {
8677 fd = open(ctermid(NULL), O_RDONLY, 0400);
8678 dup2(fd, STDIN_FILENO);
8681 dup2(STDOUT_FILENO, STDIN_FILENO);
8687 home = getenv("HOME");
8690 return EXIT_FAILURE;
8693 homelen = (uchar_t)xstrlen(home);
8695 if (!setup_config())
8696 return EXIT_FAILURE;
8698 /* Get custom opener, if set */
8699 opener = xgetenv(env_cfg[NNN_OPENER], utils[UTIL_OPENER]);
8702 /* Parse bookmarks string */
8703 if (!parsekvpair(&bookmark, &bmstr, NNN_BMS, &maxbm)) {
8704 msg(env_cfg[NNN_BMS]);
8705 return EXIT_FAILURE;
8708 /* Parse plugins string */
8709 if (!parsekvpair(&plug, &pluginstr, NNN_PLUG, &maxplug)) {
8710 msg(env_cfg[NNN_PLUG]);
8711 return EXIT_FAILURE;
8714 /* Parse order string */
8715 if (!parsekvpair(&order, &orderstr, NNN_ORDER, &maxorder)) {
8716 msg(env_cfg[NNN_ORDER]);
8717 return EXIT_FAILURE;
8721 if (arg) { /* Open a bookmark directly */
8722 if (!arg[1]) /* Bookmarks keys are single char */
8723 initpath = get_kv_val(bookmark, NULL, *arg, maxbm, NNN_BMS);
8726 msg(messages[MSG_INVALID_KEY]);
8727 return EXIT_FAILURE;
8732 } else if (argc == optind) {
8733 /* Start in the current directory */
8734 char *startpath = getenv("PWD");
8736 initpath = (startpath && *startpath) ? xstrdup(startpath) : getcwd(NULL, 0);
8739 } else { /* Open a file */
8742 size_t len = xstrlen(arg);
8744 if (len > 7 && is_prefix(arg, "file://", 7)) {
8748 initpath = abspath(arg, NULL, NULL);
8749 DPRINTF_S(initpath);
8752 return EXIT_FAILURE;
8755 /* If the file is hidden, enable hidden option */
8756 if (*xbasename(initpath) == '.')
8760 * If nnn is set as the file manager, applications may try to open
8761 * files by invoking nnn. In that case pass the file path to the
8762 * desktop opener and exit.
8766 if (stat(initpath, &sb) == -1) {
8767 bool dir = (arg[len - 1] == '/');
8770 arg = xbasename(initpath);
8771 initpath = xdirname(initpath);
8773 pkey = CREATE_NEW_KEY; /* Override plugin key */
8774 g_state.initfile = 1;
8776 if (dir || (arg != initpath)) { /* We have a directory */
8777 if (!xdiraccess(initpath) && !xmktree(initpath, TRUE)) {
8778 xerror(); /* Fail if directory cannot be created */
8779 return EXIT_FAILURE;
8781 if (!dir) /* Restore the complete path */
8784 } else if (!S_ISDIR(sb.st_mode))
8785 g_state.initfile = 1;
8792 /* Set archive handling (enveditor used as tmp var) */
8793 enveditor = getenv(env_cfg[NNN_ARCHIVE]);
8795 if (setfilter(&archive_pcre, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8797 if (setfilter(&archive_re, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8799 msg(messages[MSG_INVALID_REG]);
8800 return EXIT_FAILURE;
8803 /* An all-CLI opener overrides option -e) */
8807 /* Get VISUAL/EDITOR */
8808 enveditor = xgetenv(envs[ENV_EDITOR], utils[UTIL_VI]);
8809 editor = xgetenv(envs[ENV_VISUAL], enveditor);
8810 DPRINTF_S(getenv(envs[ENV_VISUAL]));
8811 DPRINTF_S(getenv(envs[ENV_EDITOR]));
8815 pager = xgetenv(envs[ENV_PAGER], utils[UTIL_LESS]);
8819 shell = xgetenv(envs[ENV_SHELL], utils[UTIL_SH]);
8822 DPRINTF_S(getenv("PWD"));
8826 if (g_state.autofifo) {
8827 g_tmpfpath[tmpfplen - 1] = '\0';
8829 size_t r = mkpath(g_tmpfpath, "nnn-fifo.", g_buf);
8831 xstrsncpy(g_buf + r - 1, xitoa(getpid()), PATH_MAX - r);
8832 setenv("NNN_FIFO", g_buf, TRUE);
8835 fifopath = xgetenv("NNN_FIFO", NULL);
8837 if (mkfifo(fifopath, 0600) != 0 && !(errno == EEXIST && access(fifopath, W_OK) == 0)) {
8839 return EXIT_FAILURE;
8842 sigaction(SIGPIPE, &(struct sigaction){.sa_handler = SIG_IGN}, NULL);
8846 #ifdef LINUX_INOTIFY
8847 /* Initialize inotify */
8848 inotify_fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
8849 if (inotify_fd < 0) {
8851 return EXIT_FAILURE;
8853 #elif defined(BSD_KQUEUE)
8857 return EXIT_FAILURE;
8859 #elif defined(HAIKU_NM)
8860 haiku_hnd = haiku_init_nm();
8863 return EXIT_FAILURE;
8867 /* Configure trash preference */
8868 opt = xgetenv_val(env_cfg[NNN_TRASH]);
8869 if (opt && opt <= 2)
8870 g_state.trash = opt;
8872 /* Ignore/handle certain signals */
8873 struct sigaction act = {.sa_handler = sigint_handler};
8875 if (sigaction(SIGINT, &act, NULL) < 0) {
8877 return EXIT_FAILURE;
8880 act.sa_handler = clean_exit_sighandler;
8882 if (sigaction(SIGTERM, &act, NULL) < 0 || sigaction(SIGHUP, &act, NULL) < 0) {
8884 return EXIT_FAILURE;
8887 act.sa_handler = SIG_IGN;
8889 if (sigaction(SIGQUIT, &act, NULL) < 0) {
8891 return EXIT_FAILURE;
8896 setlocale(LC_ALL, "");
8898 tables = pcre_maketables();
8903 #if RL_READLINE_VERSION >= 0x0603
8904 /* readline would overwrite the WINCH signal hook */
8905 rl_change_environment = 0;
8907 /* Bind TAB to cycling */
8908 rl_variable_bind("completion-ignore-case", "on");
8910 rl_bind_key('\t', rl_menu_complete);
8912 rl_bind_key('\t', rl_complete);
8915 mkpath(cfgpath, ".history", g_buf);
8916 read_history(g_buf);
8921 if (cfg.x11 && !g_state.picker) {
8922 /* Save terminal window title */
8923 printf("\033[22;0t");
8925 gethostname(hostname, sizeof(hostname));
8926 hostname[sizeof(hostname) - 1] = '\0';
8931 if (!initcurses(&mask))
8933 if (!initcurses(NULL))
8935 return EXIT_FAILURE;
8938 set_sort_flags(sort);
8940 opt = browse(initpath, session, pkey);
8943 if (session && g_state.prstssn)
8944 save_session(session, NULL);
8948 mousemask(mask, NULL);
8955 mkpath(cfgpath, ".history", g_buf);
8956 write_history(g_buf);
8960 if (g_state.picker) {
8962 fd = selpath ? open(selpath, O_WRONLY | O_CREAT | O_TRUNC, 0600) : STDOUT_FILENO;
8963 if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
8972 /* Remove tmp dir in list mode */
8975 /* Free the regex */
8977 pcre_free(archive_pcre);
8979 regfree(&archive_re);
8982 /* Free the selection buffer */
8985 #ifdef LINUX_INOTIFY
8986 /* Shutdown inotify */
8987 if (inotify_wd >= 0)
8988 inotify_rm_watch(inotify_fd, inotify_wd);
8990 #elif defined(BSD_KQUEUE)
8994 #elif defined(HAIKU_NM)
8995 haiku_close_nm(haiku_hnd);
8999 if (!g_state.fifomode)