4 * Copyright (C) 2014-2016, Lazaros Koromilas <lostd@2f30.org>
5 * Copyright (C) 2014-2016, Dimitris Papastamos <sin@2f30.org>
6 * Copyright (C) 2016-2023, Arun Prakash Jana <engineerarun@gmail.com>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
12 * * Redistributions of source code must retain the above copyright notice, this
13 * list of conditions and the following disclaimer.
15 * * Redistributions in binary form must reproduce the above copyright notice,
16 * this list of conditions and the following disclaimer in the documentation
17 * and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #define _FILE_OFFSET_BITS 64 /* Support large files on 32-bit glibc */
33 #if defined(__linux__) || defined(MINGW) || defined(__MINGW32__) \
34 || defined(__MINGW64__) || defined(__CYGWIN__)
38 #if defined(__linux__)
39 #include <sys/inotify.h>
42 #if !defined(__GLIBC__)
43 #include <sys/types.h>
46 #include <sys/resource.h>
48 #include <sys/statvfs.h>
49 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
50 #include <sys/types.h>
51 #include <sys/event.h>
54 #elif defined(__HAIKU__)
55 #include "../misc/haiku/haiku_interop.h"
58 #include <sys/sysmacros.h>
62 #ifdef __linux__ /* Fix failure due to mvaddnwstr() */
63 #ifndef NCURSES_WIDECHAR
64 #define NCURSES_WIDECHAR 1
66 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
67 || defined(__APPLE__) || defined(__sun)
68 #ifndef _XOPEN_SOURCE_EXTENDED
69 #define _XOPEN_SOURCE_EXTENDED
72 #ifndef __USE_XOPEN /* Fix wcswidth() failure, ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
87 #include <readline/history.h>
88 #include <readline/readline.h>
103 #include <stdalign.h>
104 #ifndef __USE_XOPEN_EXTENDED
105 #define __USE_XOPEN_EXTENDED 1
111 #ifdef MACOS_BELOW_1012
112 #include "../misc/macos-legacy/mach_gettime.h"
115 #if !defined(alloca) && defined(__GNUC__)
117 * GCC doesn't expand alloca() to __builtin_alloca() in standards mode
118 * (-std=...) and not all standard libraries do or supply it, e.g.
119 * NetBSD/arm64 so explicitly use the builtin.
121 #define alloca(size) __builtin_alloca(size)
127 #if defined(ICONS_IN_TERM) || defined(NERD) || defined(EMOJI)
128 #define ICONS_ENABLED
129 #include ICONS_INCLUDE
130 #include "icons-hash.c"
134 #if defined(ICONS_ENABLED) && defined(__APPLE__)
136 * For some reason, wcswidth returns 2 for certain icons on macOS
137 * leading to duplicated first characters in filenames when navigating.
138 * https://github.com/jarun/nnn/issues/1692
139 * There might be a better way to fix it without requiring a refresh.
141 #define macos_icons_hack() do { clrtoeol(); refresh(); } while(0)
143 #define macos_icons_hack()
150 /* Macro definitions */
151 #define VERSION "4.8"
152 #define GENERAL_INFO "BSD 2-Clause\nhttps://github.com/jarun/nnn"
155 #define SESSIONS_VERSION 1
159 #define S_BLKSIZE 512 /* S_BLKSIZE is missing on Android NDK (Termux) */
163 * NAME_MAX and PATH_MAX may not exist, e.g. with dirent.c_name being a
164 * flexible array on Illumos. Use somewhat accommodating fallback values.
171 #define PATH_MAX 4096
174 #define _ABSSUB(N, M) (((N) <= (M)) ? ((M) - (N)) : ((N) - (M)))
175 #define ELEMENTS(x) (sizeof(x) / sizeof(*(x)))
177 #define MIN(x, y) ((x) < (y) ? (x) : (y))
179 #define MAX(x, y) ((x) > (y) ? (x) : (y))
180 #define ISODD(x) ((x) & 1)
181 #define ISBLANK(x) ((x) == ' ' || (x) == '\t')
182 #define TOUPPER(ch) (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
183 #define TOLOWER(ch) (((ch) >= 'A' && (ch) <= 'Z') ? ((ch) - 'A' + 'a') : (ch))
184 #define ISUPPER_(ch) ((ch) >= 'A' && (ch) <= 'Z')
185 #define ISLOWER_(ch) ((ch) >= 'a' && (ch) <= 'z')
186 #define CMD_LEN_MAX (PATH_MAX + ((NAME_MAX + 1) << 1))
187 #define ALIGN_UP(x, A) ((((x) + (A) - 1) / (A)) * (A))
188 #define READLINE_MAX 256
194 #define PROMPT ">>> "
196 #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
197 #define NAMEBUF_INCR 0x800 /* 64 dir entries at once, avg. 32 chars per file name = 64*32B = 2KB */
198 #define DESCRIPTOR_LEN 32
199 #define _ALIGNMENT 0x10 /* 16-byte alignment */
200 #define _ALIGNMENT_MASK 0xF
201 #define TMP_LEN_MAX 64
202 #define DOT_FILTER_LEN 7
203 #define ASCII_MAX 128
204 #define EXEC_ARGS_MAX 10
205 #define LIST_FILES_MAX (1 << 14) /* Support listing 16K files */
206 #define LIST_INPUT_MAX ((size_t)LIST_FILES_MAX * PATH_MAX)
208 #define COLOR_256 256
209 #define CREATE_NEW_KEY (-1)
212 #define DBLCLK_INTERVAL_NS (400000000)
213 #define XDELAY_INTERVAL_MS (350000) /* 350 ms delay */
222 /* BSDs or Solaris or SunOS */
223 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) || defined(sun) || defined(__sun)
230 /* Large selection threshold */
232 #define LARGESEL 1000
235 #define MIN_DISPLAY_COL (CTX_MAX * 2)
236 #define ARCHIVE_CMD_LEN 16
237 #define BLK_SHIFT_512 9
239 /* Detect hardlinks in du */
240 #define HASH_BITS (0xFFFFFF)
241 #define HASH_OCTETS (HASH_BITS >> 6) /* 2^6 = 64 */
244 #define DIR_OR_DIRLNK 0x01
245 #define HARD_LINK 0x02
246 #define SYM_ORPHAN 0x04
247 #define FILE_MISSING 0x08
248 #define FILE_SELECTED 0x10
249 #define FILE_SCANNED 0x20
250 #define FILE_YOUNG 0x40
252 /* Macros to define process spawn behaviour as flags */
253 #define F_NONE 0x00 /* no flag set */
254 #define F_MULTI 0x01 /* first arg can be combination of args; to be used with F_NORMAL */
255 #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
256 #define F_NOTRACE 0x04 /* suppress stdout and stderr (no traces) */
257 #define F_NORMAL 0x08 /* spawn child process in non-curses regular CLI mode */
258 #define F_CONFIRM 0x10 /* run command - show results before exit (must have F_NORMAL) */
259 #define F_CHKRTN 0x20 /* wait for user prompt if cmd returns failure status */
260 #define F_NOSTDIN 0x40 /* suppress stdin */
261 #define F_PAGE 0x80 /* page output in run-cmd-as-plugin mode */
262 #define F_TTY 0x100 /* Force stdout to go to tty if redirected to a non-tty */
263 #define F_CLI (F_NORMAL | F_MULTI)
264 #define F_SILENT (F_CLI | F_NOTRACE)
266 /* Version compare macros */
268 * states: S_N: normal, S_I: comparing integral part, S_F: comparing
269 * fractional parts, S_Z: idem but with leading Zeroes only
276 /* result_type: VCMP: return diff; VLEN: compare using len_diff/diff */
285 /* TYPE DEFINITIONS */
286 typedef unsigned int uint_t;
287 typedef unsigned char uchar_t;
288 typedef unsigned short ushort_t;
289 typedef unsigned long long ullong_t;
293 /* Directory entry */
294 typedef struct entry {
295 char *name; /* 8 bytes */
296 time_t sec; /* 8 bytes */
297 uint_t nsec; /* 4 bytes (enough to store nanosec) */
298 mode_t mode; /* 4 bytes */
299 off_t size; /* 8 bytes */
301 ullong_t blocks : 40; /* 5 bytes (enough for 512 TiB in 512B blocks allocated) */
302 ullong_t nlen : 16; /* 2 bytes (length of file name) */
303 ullong_t flags : 8; /* 1 byte (flags specific to the file) */
306 uid_t uid; /* 4 bytes */
307 gid_t gid; /* 4 bytes */
311 /* Selection marker */
317 /* Key-value pairs from env */
327 const regex_t *regex;
336 uint_t filtermode : 1; /* Set to enter filter mode */
337 uint_t timeorder : 1; /* Set to sort by time */
338 uint_t sizeorder : 1; /* Set to sort by file size */
339 uint_t apparentsz : 1; /* Set to sort by apparent size (disk usage) */
340 uint_t blkorder : 1; /* Set to sort by blocks used (disk usage) */
341 uint_t extnorder : 1; /* Order by extension */
342 uint_t showhidden : 1; /* Set to show hidden files */
343 uint_t reserved0 : 1;
344 uint_t showdetail : 1; /* Clear to show lesser file info */
345 uint_t ctxactive : 1; /* Context active or not */
346 uint_t reverse : 1; /* Reverse sort */
347 uint_t version : 1; /* Version sort */
348 uint_t reserved1 : 1;
349 /* The following settings are global */
350 uint_t curctx : 3; /* Current context number */
351 uint_t prefersel : 1; /* Prefer selection over current, if exists */
352 uint_t fileinfo : 1; /* Show file information on hover */
353 uint_t nonavopen : 1; /* Open file on right arrow or `l` */
354 uint_t autoenter : 1; /* auto-enter dir in type-to-nav mode */
355 uint_t reserved2 : 1;
356 uint_t useeditor : 1; /* Use VISUAL to open text files */
357 uint_t reserved3 : 3;
358 uint_t regex : 1; /* Use regex filters */
359 uint_t x11 : 1; /* Copy to system clipboard, show notis, xterm title */
360 uint_t timetype : 2; /* Time sort type (0: access, 1: change, 2: modification) */
361 uint_t cliopener : 1; /* All-CLI app opener */
362 uint_t waitedit : 1; /* For ops that can't be detached, used EDITOR */
363 uint_t rollover : 1; /* Roll over at edges */
366 /* Non-persistent program-internal states (alphabeical order) */
368 uint_t autofifo : 1; /* Auto-create NNN_FIFO */
369 uint_t autonext : 1; /* Auto-advance on file open */
370 uint_t dircolor : 1; /* Current status of dir color */
371 uint_t dirctx : 1; /* Show dirs in context color */
372 uint_t duinit : 1; /* Initialize disk usage */
373 uint_t fifomode : 1; /* FIFO notify mode: 0: preview, 1: explorer */
374 uint_t forcequit : 1; /* Do not prompt on quit */
375 uint_t initfile : 1; /* Positional arg is a file */
376 uint_t interrupt : 1; /* Program received an interrupt */
377 uint_t move : 1; /* Move operation */
378 uint_t oldcolor : 1; /* Use older colorscheme */
379 uint_t picked : 1; /* Plugin has picked files */
380 uint_t picker : 1; /* Write selection to user-specified file */
381 uint_t pluginit : 1; /* Plugin framework initialized */
382 uint_t prstssn : 1; /* Persistent session */
383 uint_t rangesel : 1; /* Range selection on */
384 uint_t runctx : 3; /* The context in which plugin is to be run */
385 uint_t runplugin : 1; /* Choose plugin mode */
386 uint_t selbm : 1; /* Select a bookmark from bookmarks directory */
387 uint_t selmode : 1; /* Set when selecting files */
388 uint_t stayonsel : 1; /* Disable auto-advance on selection */
389 uint_t trash : 2; /* Trash method 0: rm -rf, 1: trash-cli, 2: gio trash */
390 uint_t uidgid : 1; /* Show owner and group info */
391 uint_t usebsdtar : 1; /* Use bsdtar as default archive utility */
392 uint_t reserved : 5; /* Adjust when adding/removing a field */
395 /* Contexts or workspaces */
397 char c_path[PATH_MAX]; /* Current dir */
398 char c_last[PATH_MAX]; /* Last visited dir */
399 char c_name[NAME_MAX + 1]; /* Current file name */
400 char c_fltr[REGEX_MAX]; /* Current filter */
401 settings c_cfg; /* Current configuration */
402 uint_t color; /* Color code for directories */
408 size_t pathln[CTX_MAX];
409 size_t lastln[CTX_MAX];
410 size_t nameln[CTX_MAX];
411 size_t fltrln[CTX_MAX];
417 /* Configuration, contexts */
418 static settings cfg = {
421 .timetype = 2, /* T_MOD */
425 alignas(max_align_t) static context g_ctx[CTX_MAX];
427 static int ndents, cur, last, curscroll, last_curscroll, total_dents = ENTRY_INCR, scroll_lines = 1;
428 static int nselected;
430 static int fifofd = -1;
432 static time_t gtimesecs;
433 static uint_t idletimeout, selbufpos, selbuflen;
434 static ushort_t xlines, xcols;
435 static ushort_t idle;
436 static uchar_t maxbm, maxplug, maxorder;
437 static uchar_t cfgsort[CTX_MAX + 1];
439 static char *pluginstr;
440 static char *orderstr;
443 static char *enveditor;
447 static char *initpath;
448 static char *cfgpath;
449 static char *selpath;
450 static char *listpath;
451 static char *listroot;
452 static char *plgpath;
453 static char *pnamebuf, *pselbuf, *findselpos;
456 static char hostname[_POSIX_HOST_NAME_MAX + 1];
459 static char *fifopath;
461 static char *lastcmd;
462 static ullong_t *ihashbmp;
463 static struct entry *pdents;
464 static blkcnt_t dir_blocks;
468 static uchar_t tmpfplen, homelen;
469 static uchar_t blk_shift = BLK_SHIFT_512;
471 static int middle_click_key;
474 static pcre *archive_pcre;
476 static regex_t archive_re;
479 /* pthread related */
480 #define NUM_DU_THREADS (4) /* Can use sysconf(_SC_NPROCESSORS_ONLN) */
481 #define DU_TEST (((node->fts_info & FTS_F) && \
482 (sb->st_nlink <= 1 || test_set_bit((uint_t)sb->st_ino))) || node->fts_info & FTS_DP)
484 static int threadbmp = -1; /* Has 1 in the bit position for idle threads */
485 static volatile int active_threads;
486 static pthread_mutex_t running_mutex = PTHREAD_MUTEX_INITIALIZER;
487 static pthread_mutex_t hardlink_mutex = PTHREAD_MUTEX_INITIALIZER;
488 static ullong_t *core_files;
489 static blkcnt_t *core_blocks;
490 static ullong_t num_files;
499 static thread_data *core_data;
501 /* Retain old signal handlers */
502 static struct sigaction oldsighup;
503 static struct sigaction oldsigtstp;
504 static struct sigaction oldsigwinch;
506 /* For use in functions which are isolated and don't return the buffer */
507 alignas(max_align_t) static char g_buf[CMD_LEN_MAX];
509 /* For use as a scratch buffer in selection manipulation */
510 alignas(max_align_t) static char g_sel[PATH_MAX];
512 /* Buffer to store tmp file path to show selection, file stats and help */
513 alignas(max_align_t) static char g_tmpfpath[TMP_LEN_MAX];
515 /* Buffer to store plugins control pipe location */
516 alignas(max_align_t) static char g_pipepath[TMP_LEN_MAX];
518 /* Non-persistent runtime states */
519 static runstate g_state;
521 /* Options to identify file MIME */
522 #if defined(__APPLE__)
523 #define FILE_MIME_OPTS "-bIL"
524 #elif !defined(__sun) /* no MIME option for 'file' */
525 #define FILE_MIME_OPTS "-biL"
528 /* Macros for utilities */
529 #define UTIL_OPENER 0
531 #define UTIL_BSDTAR 2
534 #define UTIL_LOCKER 5
535 #define UTIL_LAUNCH 6
536 #define UTIL_SH_EXEC 7
539 #define UTIL_RCLONE 10
547 #define UTIL_TRASH_CLI 18
548 #define UTIL_GIO_TRASH 19
549 #define UTIL_RM_RF 20
550 #define UTIL_ARCHMNT 21
552 /* Utilities to open files, run actions */
553 static char * const utils[] = {
556 #elif defined __CYGWIN__
558 #elif defined __HAIKU__
569 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
571 #elif defined __HAIKU__
595 #define MSG_ZERO 0 /* Unused */
596 #define MSG_0_ENTRIES 1
597 #define STR_TMPFILE 2
598 #define MSG_0_SELECTED 3
601 #define MSG_SSN_NAME 6
602 #define MSG_CP_MV_AS 7
603 #define MSG_CUR_SEL_OPTS 8
604 #define MSG_FORCE_RM 9
605 #define MSG_SIZE_LIMIT 10
606 #define MSG_NEW_OPTS 11
607 #define MSG_CLI_MODE 12
608 #define MSG_OVERWRITE 13
609 #define MSG_SSN_OPTS 14
610 #define MSG_QUIT_ALL 15
611 #define MSG_HOSTNAME 16
612 #define MSG_ARCHIVE_NAME 17
613 #define MSG_OPEN_WITH 18
614 #define MSG_NEW_PATH 19
615 #define MSG_LINK_PREFIX 20
616 #define MSG_COPY_NAME 21
618 #define MSG_SEL_MISSING 23
619 #define MSG_ACCESS 24
620 #define MSG_EMPTY_FILE 25
621 #define MSG_UNSUPPORTED 26
622 #define MSG_NOT_SET 27
623 #define MSG_EXISTS 28
624 #define MSG_FEW_COLUMNS 29
625 #define MSG_REMOTE_OPTS 30
626 #define MSG_RCLONE_DELAY 31
627 #define MSG_APP_NAME 32
628 #define MSG_ARCHIVE_OPTS 33
630 #define MSG_INVALID_REG 35
634 #define MSG_RM_TMP 39
635 #define MSG_INVALID_KEY 40
636 #define MSG_NOCHANGE 41
637 #define MSG_DIR_CHANGED 42
638 #define MSG_BM_NAME 43
639 #define MSG_FILE_LIMIT 44
641 static const char * const messages[] = {
651 "%s %s? [Esc cancels]",
652 "size limit exceeded",
653 "['f'ile]/'d'ir/'s'ym/'h'ard?",
656 "'s'ave/'l'oad/'r'estore?",
657 "Quit all contexts?",
658 "remote name (- for hovered): ",
659 "archive [path/]name: ",
662 "link prefix [@ for none]: ",
663 "copy [path/]name: ",
664 "\n'Enter' to continue",
667 "empty! edit/open with",
675 "['l's]/'o'pen/e'x'tract/'m'nt?",
678 "'a'u/'d'u/'e'xt/'r'ev/'s'z/'t'm/'v'er/'c'lr/'^T'?",
679 "unmount failed! try lazy?",
680 "first file (\')/char?",
684 "dir changed, range sel off",
686 "file limit exceeded",
689 /* Supported configuration environment variables */
695 #define NNN_FCOLORS 5
700 #define NNN_ARCHIVE 10
702 #define NNN_HELP 12 /* strings end here */
703 #define NNN_TRASH 13 /* flags begin here */
705 static const char * const env_cfg[] = {
722 /* Required environment variables */
729 static const char * const envs[] = {
742 #define PROGRESS_CP "cpg -giRp"
743 #define PROGRESS_MV "mvg -gi"
744 static char cp[sizeof PROGRESS_CP] = "cp -iRp";
745 static char mv[sizeof PROGRESS_MV] = "mv -i";
747 /* Archive commands */
748 static char * const archive_cmd[] = {"atool -a", "bsdtar -acvf", "zip -r", "tar -acvf"};
750 /* Tokens used for path creation */
756 static const char * const toks[] = {
760 "plugins", /* must be the last entry */
768 #define P_ARCHIVE_CMD 4
770 static const char * const patterns[] = {
771 SED" -i 's|^\\(\\(.*/\\)\\(.*\\)$\\)|#\\1\\n\\3|' %s",
772 SED" 's|^\\([^#/][^/]\\?.*\\)$|%s/\\1|;s|^#\\(/.*\\)$|\\1|' "
773 "%s | tr '\\n' '\\0' | xargs -0 -n2 sh -c '%s \"$0\" \"$@\" < /dev/tty'",
774 "\\.(bz|bz2|gz|tar|taz|tbz|tbz2|tgz|z|zip)$", /* Basic formats that don't need external tools */
775 SED" -i 's|^%s\\(.*\\)$|%s\\1|' %s",
776 "xargs -0 %s %s < '%s'",
780 #define C_BLK (CTX_MAX + 1) /* Block device: DarkSeaGreen1 */
781 #define C_CHR (C_BLK + 1) /* Character device: Yellow1 */
782 #define C_DIR (C_CHR + 1) /* Directory: DeepSkyBlue1 */
783 #define C_EXE (C_DIR + 1) /* Executable file: Green1 */
784 #define C_FIL (C_EXE + 1) /* Regular file: Normal */
785 #define C_HRD (C_FIL + 1) /* Hard link: Plum4 */
786 #define C_LNK (C_HRD + 1) /* Symbolic link: Cyan1 */
787 #define C_MIS (C_LNK + 1) /* Missing file OR file details: Grey62 */
788 #define C_ORP (C_MIS + 1) /* Orphaned symlink: DeepPink1 */
789 #define C_PIP (C_ORP + 1) /* Named pipe (FIFO): Orange1 */
790 #define C_SOC (C_PIP + 1) /* Socket: MediumOrchid1 */
791 #define C_UND (C_SOC + 1) /* Unknown OR 0B regular/exe file: Red1 */
793 static char gcolors[] = "c1e2272e006033f7c6d6abc4";
794 static uint_t fcolors[C_UND + 1] = {0};
798 #define NUM_EVENT_SLOTS 32 /* Make room for 32 events */
799 #define EVENT_SIZE (sizeof(struct inotify_event))
800 #define EVENT_BUF_LEN (EVENT_SIZE * NUM_EVENT_SLOTS)
801 static int inotify_fd, inotify_wd = -1;
802 static uint_t INOTIFY_MASK = /* IN_ATTRIB | */ IN_CREATE | IN_DELETE | IN_DELETE_SELF
803 | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
804 #elif defined(BSD_KQUEUE)
805 #define NUM_EVENT_SLOTS 1
806 #define NUM_EVENT_FDS 1
807 static int kq, event_fd = -1;
808 static struct kevent events_to_monitor[NUM_EVENT_FDS];
809 static uint_t KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK
810 | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
811 static struct timespec gtimeout;
812 #elif defined(HAIKU_NM)
813 static bool haiku_nm_active = FALSE;
814 static haiku_nm_h haiku_hnd;
817 /* Function macros */
818 #define tolastln() move(xlines - 1, 0)
819 #define tocursor() move(cur + 2 - curscroll, 0)
820 #define exitcurses() endwin()
821 #define printwarn(presel) printwait(strerror(errno), presel)
822 #define istopdir(path) ((path)[1] == '\0' && (path)[0] == '/')
823 #define copycurname() xstrsncpy(lastname, ndents ? pdents[cur].name : "\0", NAME_MAX + 1)
824 #define settimeout() timeout(1000)
825 #define cleartimeout() timeout(-1)
826 #define errexit() printerr(__LINE__)
827 #define setdirwatch() (cfg.filtermode ? (presel = FILTER) : (watch = TRUE))
828 #define filterset() (g_ctx[cfg.curctx].c_fltr[1])
829 /* We don't care about the return value from strcmp() */
830 #define xstrcmp(a, b) (*(a) != *(b) ? -1 : strcmp((a), (b)))
831 /* A faster version of xisdigit */
832 #define xisdigit(c) ((unsigned int) (c) - '0' <= 9)
833 #define xerror() perror(xitoa(__LINE__))
836 #define ENTLESS(i, j) (entrycmpfn(pdents + (i), pdents + (j)) < 0)
837 #define ENTSWAP(i, j) (swap_ent((i), (j)))
838 #define ENTSORT(pdents, ndents, entrycmpfn) QSORT((ndents), ENTLESS, ENTSWAP)
840 #define ENTSORT(pdents, ndents, entrycmpfn) qsort((pdents), (ndents), sizeof(*(pdents)), (entrycmpfn))
843 /* Forward declarations */
844 static void redraw(char *path);
845 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag);
846 static void move_cursor(int target, int ignore_scrolloff);
847 static char *load_input(int fd, const char *path);
848 static int set_sort_flags(int r);
849 static void statusbar(char *path);
850 static bool get_output(char *file, char *arg1, char *arg2, int fdout, bool page);
852 static void notify_fifo(bool force);
857 static void sigint_handler(int sig)
860 g_state.interrupt = 1;
863 static void clean_exit_sighandler(int sig)
867 /* This triggers cleanup() thanks to atexit() */
871 static char *xitoa(uint_t val)
873 static char dst[32] = {'\0'};
874 static const char digits[201] =
875 "0001020304050607080910111213141516171819"
876 "2021222324252627282930313233343536373839"
877 "4041424344454647484950515253545556575859"
878 "6061626364656667686970717273747576777879"
879 "8081828384858687888990919293949596979899";
880 uint_t next = 30, quo, i;
884 i = (val - (quo * 100)) * 2;
886 dst[next] = digits[i + 1];
887 dst[--next] = digits[i];
891 /* Handle last 1-2 digits */
893 dst[next] = '0' + val;
896 dst[next] = digits[i + 1];
897 dst[--next] = digits[i];
903 /* Return the integer value of a char representing HEX */
904 static uchar_t xchartohex(uchar_t c)
909 if (c >= 'a' && c <= 'f')
912 if (c >= 'A' && c <= 'F')
919 * Source: https://elixir.bootlin.com/linux/latest/source/arch/alpha/include/asm/bitops.h
921 static bool test_set_bit(uint_t nr)
925 pthread_mutex_lock(&hardlink_mutex);
926 ullong_t *m = ((ullong_t *)ihashbmp) + (nr >> 6);
928 if (*m & (1 << (nr & 63))) {
929 pthread_mutex_unlock(&hardlink_mutex);
933 *m |= 1 << (nr & 63);
934 pthread_mutex_unlock(&hardlink_mutex);
940 /* Increase the limit on open file descriptors, if possible */
941 static void max_openfds(void)
945 if (!getrlimit(RLIMIT_NOFILE, &rl))
946 if (rl.rlim_cur < rl.rlim_max) {
947 rl.rlim_cur = rl.rlim_max;
948 setrlimit(RLIMIT_NOFILE, &rl);
954 * Wrapper to realloc()
955 * Frees current memory if realloc() fails and returns NULL.
957 * The *alloc() family returns aligned address: https://man7.org/linux/man-pages/man3/malloc.3.html
959 static void *xrealloc(void *pcur, size_t len)
961 void *pmem = realloc(pcur, len);
970 * Just a safe strncpy(3)
971 * Always null ('\0') terminates if both src and dest are valid pointers.
972 * Returns the number of bytes copied including terminating null byte.
974 static size_t xstrsncpy(char *restrict dst, const char *restrict src, size_t n)
976 char *end = memccpy(dst, src, '\0', n);
979 dst[n - 1] = '\0'; // NOLINT
980 end = dst + n; /* If we return n here, binary size increases due to auto-inlining */
986 static inline size_t xstrlen(const char *restrict s)
988 #if !defined(__GLIBC__)
989 return strlen(s); // NOLINT
991 return (char *)rawmemchr(s, '\0') - s; // NOLINT
995 static char *xstrdup(const char *restrict s)
997 size_t len = xstrlen(s) + 1;
998 char *ptr = malloc(len);
999 return ptr ? memcpy(ptr, s, len) : NULL;
1002 static bool is_suffix(const char *restrict str, const char *restrict suffix)
1004 if (!str || !suffix)
1007 size_t lenstr = xstrlen(str);
1008 size_t lensuffix = xstrlen(suffix);
1010 if (lensuffix > lenstr)
1013 return (xstrcmp(str + (lenstr - lensuffix), suffix) == 0);
1016 static inline bool is_prefix(const char *restrict str, const char *restrict prefix, size_t len)
1018 return !strncmp(str, prefix, len);
1021 static inline bool is_bad_len_or_dir(const char *restrict path)
1023 size_t len = xstrlen(path);
1025 return ((len >= PATH_MAX) || (path[len - 1] == '/'));
1028 static char *get_cwd_entry(const char *restrict cwdpath, char *entrypath, size_t *tokenlen)
1030 size_t len = xstrlen(cwdpath);
1033 if (!is_prefix(entrypath, cwdpath, len))
1036 entrypath += len + 1; /* Add 1 for trailing / */
1037 end = strchr(entrypath, '/');
1039 *tokenlen = end - entrypath;
1041 *tokenlen = xstrlen(entrypath);
1042 DPRINTF_U(*tokenlen);
1048 * The poor man's implementation of memrchr(3).
1049 * We are only looking for '/' and '.' in this program.
1050 * And we are NOT expecting a '/' at the end.
1051 * Ideally 0 < n <= xstrlen(s).
1053 static void *xmemrchr(uchar_t *restrict s, uchar_t ch, size_t n)
1055 #if defined(__GLIBC__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
1056 return memrchr(s, ch, n);
1062 uchar_t *ptr = s + n;
1073 /* A very simplified implementation, changes path */
1074 static char *xdirname(char *path)
1076 char *base = xmemrchr((uchar_t *)path, '/', xstrlen(path));
1086 static char *xbasename(char *path)
1088 char *base = xmemrchr((uchar_t *)path, '/', xstrlen(path)); // NOLINT
1090 return base ? base + 1 : path;
1093 static inline char *xextension(const char *fname, size_t len)
1095 return xmemrchr((uchar_t *)fname, '.', len);
1100 * One-shot cache for getpwuid/getgrgid. Returns the cached name if the
1101 * provided uid is the same as the previous uid. Returns xitoa(guid) if
1102 * the guid is not found in the password database.
1104 static char *getpwname(uid_t uid)
1106 static uint_t uidcache = UINT_MAX;
1107 static char *namecache;
1109 if (uidcache != uid) {
1110 struct passwd *pw = getpwuid(uid);
1113 namecache = pw ? pw->pw_name : NULL;
1116 return namecache ? namecache : xitoa(uid);
1119 static char *getgrname(gid_t gid)
1121 static uint_t gidcache = UINT_MAX;
1122 static char *grpcache;
1124 if (gidcache != gid) {
1125 struct group *gr = getgrgid(gid);
1128 grpcache = gr ? gr->gr_name : NULL;
1131 return grpcache ? grpcache : xitoa(gid);
1135 static inline bool getutil(char *util)
1137 return spawn("which", util, NULL, NULL, F_NORMAL | F_NOTRACE) == 0;
1140 static inline bool tilde_is_home(const char *s)
1142 return s[0] == '~' && (s[1] == '\0' || s[1] == '/');
1145 static inline bool tilde_is_home_strict(const char *s)
1147 return s[0] == '~' && s[1] == '/';
1151 * Updates out with "dir/name or "/name"
1152 * Returns the number of bytes copied including the terminating NULL byte
1154 * Note: dir and out must be PATH_MAX in length to avoid macOS fault
1156 static size_t mkpath(const char *dir, const char *name, char *out)
1160 /* same rational for being strict as abspath() */
1161 if (tilde_is_home_strict(name)) { //NOLINT
1162 len = xstrsncpy(out, home, PATH_MAX);
1165 } else if (name[0] != '/') { // NOLINT
1166 /* Handle root case */
1167 len = istopdir(dir) ? 1 : xstrsncpy(out, dir, PATH_MAX);
1168 out[len - 1] = '/'; // NOLINT
1170 return (xstrsncpy(out + len, name, PATH_MAX - len) + len);
1173 /* Assumes both the paths passed are directories */
1174 static char *common_prefix(const char *path, char *prefix)
1176 const char *x = path, *y = prefix;
1179 if (!path || !*path || !prefix)
1183 xstrsncpy(prefix, path, PATH_MAX);
1187 while (*x && *y && (*x == *y))
1190 /* Strings are same */
1194 /* Path is shorter */
1195 if (!*x && *y == '/') {
1196 xstrsncpy(prefix, path, y - path);
1200 /* Prefix is shorter */
1201 if (!*y && *x == '/')
1204 /* Shorten prefix */
1205 prefix[y - prefix] = '\0';
1207 sep = xmemrchr((uchar_t *)prefix, '/', y - prefix);
1217 * The library function realpath() resolves symlinks.
1218 * If there's a symlink in file list we want to show the symlink not what it's points to.
1219 * Resolves ./../~ in filepath
1221 static char *abspath(const char *filepath, char *cwd, char *buf)
1223 const char *path = filepath;
1224 bool allocated = FALSE;
1229 /* when dealing with tilde, we need to be strict.
1230 * otherwise a file named "~" can end up expanding to
1231 * $HOME and causing disaster */
1232 if (tilde_is_home_strict(path)) {
1234 path += 2; /* advance 2 bytes past the "~/" */
1235 } else if ((path[0] != '/') && !cwd) {
1236 cwd = getcwd(NULL, 0);
1242 size_t dst_size = 0, src_size = xstrlen(path), cwd_size = cwd ? xstrlen(cwd) : 0;
1243 size_t len = src_size;
1247 * We need to add 2 chars at the end as relative paths may start with:
1249 * no separator (fd .): this needs an additional char for '/'
1251 char *resolved_path = buf ? buf : malloc(src_size + cwd_size + 2);
1253 if (!resolved_path) {
1259 /* Turn relative paths into absolute */
1260 if (path[0] != '/') {
1263 free(resolved_path);
1266 dst_size = xstrsncpy(resolved_path, cwd, cwd_size + 1) - 1;
1270 resolved_path[0] = '\0';
1273 dst = resolved_path + dst_size;
1274 for (const char *next = NULL; next != path + src_size;) {
1275 next = memchr(src, '/', len);
1277 next = path + src_size;
1279 if (next - src == 2 && src[0] == '.' && src[1] == '.') {
1280 if (dst - resolved_path) {
1281 dst = xmemrchr((uchar_t *)resolved_path, '/', dst - resolved_path);
1284 } else if (next - src == 1 && src[0] == '.') {
1286 } else if (next - src) {
1288 xstrsncpy(dst, src, next - src + 1);
1293 len = src_size - (src - path);
1296 if (*resolved_path == '\0') {
1297 resolved_path[0] = '/';
1298 resolved_path[1] = '\0';
1301 if (xstrlen(resolved_path) >= PATH_MAX) {
1303 free(resolved_path);
1309 return resolved_path;
1312 /* wraps the argument in single quotes so it can be safely fed to shell */
1313 static bool shell_escape(char *output, size_t outlen, const char *s)
1315 size_t n = xstrlen(s), w = 0;
1318 DPRINTF_S("s == output");
1322 output[w++] = '\''; /* begin single quote */
1323 for (size_t r = 0; r < n; ++r) {
1324 /* potentially too big: 4 for the single quote case, 2 from
1325 * outside the loop */
1326 if (w + 6 >= outlen)
1330 /* the only thing that has special meaning inside single
1331 * quotes are single quotes themselves. */
1333 output[w++] = '\''; /* end single quote */
1334 output[w++] = '\\'; /* put \' so it's treated as literal single quote */
1336 output[w++] = '\''; /* start single quoting again */
1343 output[w++] = '\''; /* end single quote */
1344 output[w++] = '\0'; /* nul terminator */
1348 static bool set_tilde_in_path(char *path)
1350 if (is_prefix(path, home, homelen)) {
1351 home[homelen] = path[homelen - 1];
1352 path[homelen - 1] = '~';
1359 static void reset_tilde_in_path(char *path)
1361 path[homelen - 1] = home[homelen];
1362 home[homelen] = '\0';
1366 static void xterm_cfg(char *path)
1368 if (cfg.x11 && !g_state.picker) {
1369 /* Signal CWD change to terminal */
1370 printf("\033]7;file://%s%s\033\\", hostname, path);
1372 /* Set terminal window title */
1373 bool r = set_tilde_in_path(path);
1375 printf("\033]2;%s\007", r ? &path[homelen - 1] : path);
1379 reset_tilde_in_path(path);
1384 static bool convert_tilde(const char *path, char *buf)
1386 if (tilde_is_home(path)) {
1387 ssize_t len = xstrlen(home);
1388 ssize_t loclen = xstrlen(path);
1390 xstrsncpy(buf, home, len + 1);
1391 xstrsncpy(buf + len, path + 1, loclen);
1397 static int create_tmp_file(void)
1399 xstrsncpy(g_tmpfpath + tmpfplen - 1, messages[STR_TMPFILE], TMP_LEN_MAX - tmpfplen);
1401 int fd = mkstemp(g_tmpfpath);
1404 DPRINTF_S(strerror(errno));
1410 static void msg(const char *message)
1412 dprintf(STDERR_FILENO, "%s\n", message);
1416 static void handle_key_resize(void)
1422 /* Clear the old prompt */
1423 static void clearoldprompt(void)
1426 move(xlines - 2, 0);
1431 handle_key_resize();
1435 /* Messages show up at the bottom */
1436 static inline void printmsg_nc(const char *msg)
1443 static void printmsg(const char *msg)
1445 attron(COLOR_PAIR(cfg.curctx + 1));
1447 attroff(COLOR_PAIR(cfg.curctx + 1));
1450 static void printwait(const char *msg, int *presel)
1456 xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
1460 /* Kill curses and display error before exiting */
1461 static void printerr(int linenum)
1464 perror(xitoa(linenum));
1465 if (!g_state.picker && selpath)
1471 static inline bool xconfirm(int c)
1473 return (c == 'y' || c == 'Y');
1476 static int get_input(const char *prompt)
1487 while (*ch == KEY_RESIZE) {
1501 static bool isselfileempty(void)
1505 return (stat(selpath, &sb) == -1) || (!sb.st_size);
1508 static int get_cur_or_sel(void)
1510 bool sel = (selbufpos || !isselfileempty());
1512 /* Check both local buffer and selection file for external selection */
1513 if (sel && ndents) {
1514 /* If selection is preferred and we have a local selection, return selection.
1515 * Always show the prompt in case of an external selection.
1517 if (cfg.prefersel && selbufpos)
1520 int choice = get_input(messages[MSG_CUR_SEL_OPTS]);
1522 return ((choice == 'c' || choice == 's') ? choice : 0);
1534 static void xdelay(useconds_t delay)
1540 static char confirm_force(bool selection)
1544 snprintf(str, 64, messages[MSG_FORCE_RM],
1545 g_state.trash ? utils[UTIL_GIO_TRASH] + 4 : utils[UTIL_RM_RF],
1546 (selection ? "selected" : "hovered"));
1548 int r = get_input(str);
1551 return '\0'; /* cancel */
1552 if (r == 'y' || r == 'Y')
1553 return 'f'; /* forceful for rm */
1554 return (g_state.trash ? '\0' : 'i'); /* interactive for rm */
1557 /* Writes buflen char(s) from buf to a file */
1558 static void writesel(const char *buf, const size_t buflen)
1563 int fd = open(selpath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
1566 if (write(fd, buf, buflen) != (ssize_t)buflen)
1573 static void appendfpath(const char *path, const size_t len)
1575 if ((selbufpos >= selbuflen) || ((len + 3) > (selbuflen - selbufpos))) {
1576 selbuflen += PATH_MAX;
1577 pselbuf = xrealloc(pselbuf, selbuflen);
1582 selbufpos += xstrsncpy(pselbuf + selbufpos, path, len);
1585 static void selbufrealloc(const size_t alloclen)
1587 if ((selbufpos + alloclen) > selbuflen) {
1588 selbuflen = ALIGN_UP(selbufpos + alloclen, PATH_MAX);
1589 pselbuf = xrealloc(pselbuf, selbuflen);
1595 /* Write selected file paths to fd, linefeed separated */
1596 static size_t seltofile(int fd, uint_t *pcount)
1598 uint_t lastpos, count = 0;
1599 char *pbuf = pselbuf;
1601 ssize_t len, prefixlen = 0, initlen = 0;
1609 lastpos = selbufpos - 1;
1612 prefixlen = (ssize_t)xstrlen(listroot);
1613 initlen = (ssize_t)xstrlen(listpath);
1616 while (pos <= lastpos) {
1618 len = (ssize_t)xstrlen(pbuf);
1620 if (!listpath || !is_prefix(pbuf, listpath, initlen)) {
1621 if (write(fd, pbuf, len) != len)
1624 if (write(fd, listroot, prefixlen) != prefixlen)
1626 if (write(fd, pbuf + initlen, len - initlen) != (len - initlen))
1631 if (pos <= lastpos) {
1632 if (write(fd, "\n", 1) != 1)
1646 /* List selection from selection file (another instance) */
1647 static bool listselfile(void)
1649 if (isselfileempty())
1652 snprintf(g_buf, CMD_LEN_MAX, "tr \'\\0\' \'\\n\' < %s", selpath);
1653 spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CONFIRM);
1658 /* Reset selection indicators */
1659 static void resetselind(void)
1661 for (int r = 0; r < ndents; ++r)
1662 if (pdents[r].flags & FILE_SELECTED)
1663 pdents[r].flags &= ~FILE_SELECTED;
1666 static void startselection(void)
1668 if (!g_state.selmode) {
1669 g_state.selmode = 1;
1680 static void clearselection(void)
1684 g_state.selmode = 0;
1688 static char *findinsel(char *startpos, int len)
1696 char *found = startpos;
1697 size_t buflen = selbufpos - (startpos - pselbuf);
1700 /* memmem(3): not specified in POSIX.1, but present on a number of other systems. */
1701 found = memmem(found, buflen - (found - startpos), g_sel, len);
1704 if (found == startpos || *(found - 1) == '\0')
1706 found += len; /* We found g_sel as a substring of a path, move forward */
1707 if (found >= startpos + buflen)
1712 static int markcmp(const void *va, const void *vb)
1714 const selmark *ma = (selmark*)va;
1715 const selmark *mb = (selmark*)vb;
1717 return ma->startpos - mb->startpos;
1720 /* scanselforpath() must be called before calling this */
1721 static inline void findmarkentry(size_t len, struct entry *dentp)
1723 if (!(dentp->flags & FILE_SCANNED)) {
1724 if (findinsel(findselpos, len + xstrsncpy(g_sel + len, dentp->name, dentp->nlen)))
1725 dentp->flags |= FILE_SELECTED;
1726 dentp->flags |= FILE_SCANNED;
1731 * scanselforpath() must be called before calling this
1732 * pathlen = length of path + 1 (+1 for trailing slash)
1734 static void invertselbuf(const int pathlen)
1736 size_t len, endpos, shrinklen = 0, alloclen = 0;
1737 char * const pbuf = g_sel + pathlen;
1739 int i, nmarked = 0, prev = 0;
1740 struct entry *dentp;
1742 selmark *marked = malloc(nselected * sizeof(selmark));
1749 /* First pass: inversion */
1750 for (i = 0; i < ndents; ++i) {
1753 if (dentp->flags & FILE_SCANNED) {
1754 if (dentp->flags & FILE_SELECTED) {
1755 dentp->flags ^= FILE_SELECTED; /* Clear selection status */
1758 dentp->flags |= FILE_SELECTED;
1759 alloclen += pathlen + dentp->nlen;
1762 dentp->flags |= FILE_SCANNED;
1767 len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1768 found = findinsel(findselpos, len);
1770 if (findselpos == found)
1773 if (nmarked && (found
1774 == (marked[nmarked - 1].startpos + marked[nmarked - 1].len)))
1775 marked[nmarked - 1].len += len;
1777 marked[nmarked].startpos = found;
1778 marked[nmarked].len = len;
1783 shrinklen += len; /* buffer size adjustment */
1785 dentp->flags |= FILE_SELECTED;
1786 alloclen += pathlen + dentp->nlen;
1793 * Files marked for deselection could be found in arbitrary order.
1794 * Sort by appearance in selection buffer.
1795 * With entries sorted we can merge adjacent ones allowing us to
1796 * move them in a single go.
1798 qsort(marked, nmarked, sizeof(selmark), &markcmp);
1800 /* Some files might be adjacent. Merge them into a single entry */
1801 for (i = 1; i < nmarked; ++i) {
1802 if (marked[i].startpos == marked[prev].startpos + marked[prev].len)
1803 marked[prev].len += marked[i].len;
1806 marked[prev].startpos = marked[i].startpos;
1807 marked[prev].len = marked[i].len;
1812 * Number of entries is increased by encountering a non-adjacent entry
1813 * After we finish the loop we should increment it once more.
1816 if (nmarked) /* Make sure there is something to deselect */
1819 /* Using merged entries remove unselected chunks from selection buffer */
1820 for (i = 0; i < nmarked; ++i) {
1822 * found: points to where the current block starts
1823 * variable is recycled from previous for readability
1824 * endpos: points to where the the next block starts
1825 * area between the end of current block (found + len)
1826 * and endpos is selected entries. This is what we are
1829 found = marked[i].startpos;
1830 endpos = (i + 1 == nmarked ? selbufpos : marked[i + 1].startpos - pselbuf);
1831 len = marked[i].len;
1833 /* Move back only selected entries. No selected memory is moved twice */
1834 memmove(found, found + len, endpos - (found + len - pselbuf));
1839 /* Buffer size adjustment */
1840 selbufpos -= shrinklen;
1842 selbufrealloc(alloclen);
1844 /* Second pass: append newly selected to buffer */
1845 for (i = 0; i < ndents; ++i) {
1846 if (pdents[i].flags & FILE_SELECTED) {
1847 len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1848 appendfpath(g_sel, len);
1853 nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1857 * scanselforpath() must be called before calling this
1858 * pathlen = length of path + 1 (+1 for trailing slash)
1860 static void addtoselbuf(const int pathlen, int startid, int endid)
1863 size_t len, alloclen = 0;
1864 struct entry *dentp;
1866 char * const pbuf = g_sel + pathlen;
1868 /* Remember current selection buffer position */
1869 for (i = startid; i <= endid; ++i) {
1873 len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1874 found = findinsel(findselpos, len);
1876 dentp->flags |= (FILE_SCANNED | FILE_SELECTED);
1877 if (found == findselpos) {
1879 if (findselpos == (pselbuf + selbufpos))
1883 alloclen += pathlen + dentp->nlen;
1885 alloclen += pathlen + dentp->nlen;
1888 selbufrealloc(alloclen);
1890 for (i = startid; i <= endid; ++i) {
1891 if (!(pdents[i].flags & FILE_SELECTED)) {
1892 len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1893 appendfpath(g_sel, len);
1895 pdents[i].flags |= (FILE_SCANNED | FILE_SELECTED);
1899 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
1902 /* Removes g_sel from selbuf */
1903 static void rmfromselbuf(size_t len)
1905 char *found = findinsel(findselpos, len);
1909 memmove(found, found + len, selbufpos - (found + len - pselbuf));
1912 nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1915 static int scanselforpath(const char *path, bool getsize)
1917 if (!path[1]) { /* path should always be at least two bytes (including NULL) */
1919 findselpos = pselbuf;
1920 return 1; /* Length of '/' is 1 */
1923 size_t off = xstrsncpy(g_sel, path, PATH_MAX);
1925 g_sel[off - 1] = '/';
1927 * We set findselpos only here. Directories can be listed in arbitrary order.
1928 * This is the best best we can do for remembering position.
1930 findselpos = findinsel(NULL, off);
1934 return (findselpos ? off : 0);
1937 /* Finish selection procedure before an operation */
1938 static void endselection(bool endselmode)
1942 char buf[sizeof(patterns[P_REPLACE]) + PATH_MAX + (TMP_LEN_MAX << 1)];
1944 if (endselmode && g_state.selmode)
1945 g_state.selmode = 0;
1947 /* The code below is only for listing mode */
1948 if (!listpath || !selbufpos)
1951 fd = create_tmp_file();
1953 DPRINTF_S("couldn't create tmp file");
1957 seltofile(fd, NULL);
1959 DPRINTF_S(strerror(errno));
1964 snprintf(buf, sizeof(buf), patterns[P_REPLACE], listpath, listroot, g_tmpfpath);
1965 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
1967 fd = open(g_tmpfpath, O_RDONLY);
1969 DPRINTF_S(strerror(errno));
1971 if (unlink(g_tmpfpath)) {
1972 DPRINTF_S(strerror(errno));
1978 count = read(fd, pselbuf, selbuflen);
1980 DPRINTF_S(strerror(errno));
1982 if (close(fd) || unlink(g_tmpfpath)) {
1983 DPRINTF_S(strerror(errno));
1988 if (close(fd) || unlink(g_tmpfpath)) {
1989 DPRINTF_S(strerror(errno));
1995 pselbuf[--count] = '\0';
1996 for (--count; count > 0; --count)
1997 if (pselbuf[count] == '\n' && pselbuf[count+1] == '/')
1998 pselbuf[count] = '\0';
2000 writesel(pselbuf, selbufpos - 1);
2003 /* Returns: 1 - success, 0 - none selected, -1 - other failure */
2004 static int editselection(void)
2012 if (!selbufpos) /* External selection is only editable at source */
2013 return listselfile();
2015 fd = create_tmp_file();
2017 DPRINTF_S("couldn't create tmp file");
2021 seltofile(fd, NULL);
2023 DPRINTF_S(strerror(errno));
2027 /* Save the last modification time */
2028 if (stat(g_tmpfpath, &sb)) {
2029 DPRINTF_S(strerror(errno));
2033 mtime = sb.st_mtime;
2035 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2037 fd = open(g_tmpfpath, O_RDONLY);
2039 DPRINTF_S(strerror(errno));
2046 if (mtime == sb.st_mtime) {
2047 DPRINTF_S("selection is not modified");
2052 if (sb.st_size > selbufpos) {
2053 DPRINTF_S("edited buffer larger than previous");
2058 count = read(fd, pselbuf, selbuflen);
2060 DPRINTF_S(strerror(errno));
2062 if (close(fd) || unlink(g_tmpfpath)) {
2063 DPRINTF_S(strerror(errno));
2069 if (close(fd) || unlink(g_tmpfpath)) {
2070 DPRINTF_S(strerror(errno));
2082 /* The last character should be '\n' */
2083 pselbuf[--count] = '\0';
2084 for (--count; count > 0; --count) {
2085 /* Replace every '\n' that separates two paths */
2086 if (pselbuf[count] == '\n' && pselbuf[count + 1] == '/') {
2088 pselbuf[count] = '\0';
2092 /* Add a line for the last file */
2095 if (lines > nselected) {
2096 DPRINTF_S("files added to selection");
2101 writesel(pselbuf, selbufpos - 1);
2111 static bool selsafe(void)
2113 /* Fail if selection file path not generated */
2115 printmsg(messages[MSG_SEL_MISSING]);
2119 /* Fail if selection file path isn't accessible */
2120 if (access(selpath, R_OK | W_OK) == -1) {
2121 errno == ENOENT ? printmsg(messages[MSG_0_SELECTED]) : printwarn(NULL);
2128 static void export_file_list(void)
2133 struct entry *pdent = pdents;
2134 int fd = create_tmp_file();
2137 DPRINTF_S(strerror(errno));
2141 for (int r = 0; r < ndents; ++pdent, ++r) {
2142 if (write(fd, pdent->name, pdent->nlen - 1) != (pdent->nlen - 1))
2145 if ((r != ndents - 1) && (write(fd, "\n", 1) != 1))
2150 DPRINTF_S(strerror(errno));
2153 spawn(editor, g_tmpfpath, NULL, NULL, F_CLI);
2155 if (xconfirm(get_input(messages[MSG_RM_TMP])))
2159 static bool init_fcolors(void)
2161 char *f_colors = getenv(env_cfg[NNN_FCOLORS]);
2163 if (!f_colors || !*f_colors)
2166 for (uchar_t id = C_BLK; *f_colors && id <= C_UND; ++id) {
2167 fcolors[id] = xchartohex(*f_colors) << 4;
2169 fcolors[id] += xchartohex(*f_colors);
2171 init_pair(id, fcolors[id], -1);
2180 /* Initialize curses mode */
2181 static bool initcurses(void *oldmask)
2187 if (g_state.picker) {
2188 if (!newterm(NULL, stderr, stdin)) {
2192 } else if (!initscr()) {
2194 DPRINTF_S(getenv("TERM"));
2201 //intrflush(stdscr, FALSE);
2202 keypad(stdscr, TRUE);
2204 #if NCURSES_MOUSE_VERSION <= 1
2205 mousemask(BUTTON1_PRESSED | BUTTON1_DOUBLE_CLICKED | BUTTON2_PRESSED | BUTTON3_PRESSED,
2206 (mmask_t *)oldmask);
2208 mousemask(BUTTON1_PRESSED | BUTTON2_PRESSED | BUTTON3_PRESSED | BUTTON4_PRESSED
2209 | BUTTON5_PRESSED, (mmask_t *)oldmask);
2213 curs_set(FALSE); /* Hide cursor */
2215 char *colors = getenv(env_cfg[NNN_COLORS]);
2217 if (colors || !getenv("NO_COLOR")) {
2222 use_default_colors();
2224 /* Initialize file colors */
2225 if (COLORS >= COLOR_256) {
2226 if (!(g_state.oldcolor || init_fcolors())) {
2228 msg(env_cfg[NNN_FCOLORS]);
2232 g_state.oldcolor = 1;
2235 DPRINTF_D(COLOR_PAIRS);
2237 if (colors && *colors == '#') {
2238 char *sep = strchr(colors, ';');
2240 if (!g_state.oldcolor && COLORS >= COLOR_256) {
2245 * If fallback colors are specified, set the separator
2246 * to NULL so we don't interpret separator and fallback
2247 * if fewer than CTX_MAX xterm 256 colors are specified.
2252 colors = sep; /* Detect if 8 colors fallback is appended */
2258 /* Get and set the context colors */
2259 for (uchar_t i = 0; i < CTX_MAX; ++i) {
2260 pcode = &g_ctx[i].color;
2262 if (colors && *colors) {
2264 *pcode = xchartohex(*colors) << 4;
2266 fcolors[i + 1] = *pcode += xchartohex(*colors);
2267 else { /* Each color code must be 2 hex symbols */
2269 msg(env_cfg[NNN_COLORS]);
2273 *pcode = (*colors < '0' || *colors > '7') ? 4 : *colors - '0';
2278 init_pair(i + 1, *pcode, -1);
2281 #ifdef ICONS_ENABLED
2282 if (!g_state.oldcolor) {
2283 for (uint_t i = 0; i < ELEMENTS(init_colors); ++i)
2284 init_pair(C_UND + 1 + init_colors[i], init_colors[i], -1);
2288 settimeout(); /* One second */
2293 /* No NULL check here as spawn() guards against it */
2294 static char *parseargs(char *cmd, char **argv, int *pindex)
2297 size_t len = xstrlen(cmd) + 1;
2298 char *line = (char *)malloc(len);
2301 DPRINTF_S("malloc()!");
2305 xstrsncpy(line, cmd, len);
2306 argv[count++] = line;
2309 while (*line) { // NOLINT
2310 if (ISBLANK(*line)) {
2313 if (!*line) // NOLINT
2316 argv[count++] = line;
2317 if (count == EXEC_ARGS_MAX) {
2326 if (count == -1 || count > (EXEC_ARGS_MAX - 4)) { /* 3 args and last NULL */
2329 DPRINTF_S("NULL or too many args");
2336 static void enable_signals(void)
2338 struct sigaction dfl_act = {.sa_handler = SIG_DFL};
2340 sigaction(SIGHUP, &dfl_act, NULL);
2341 sigaction(SIGINT, &dfl_act, NULL);
2342 sigaction(SIGQUIT, &dfl_act, NULL);
2343 sigaction(SIGTSTP, &dfl_act, NULL);
2344 sigaction(SIGWINCH, &dfl_act, NULL);
2347 static pid_t xfork(uchar_t flag)
2352 /* the parent ignores the interrupt, quit and hangup signals */
2353 sigaction(SIGHUP, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsighup);
2354 sigaction(SIGTSTP, &(struct sigaction){.sa_handler = SIG_DFL}, &oldsigtstp);
2355 sigaction(SIGWINCH, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsigwinch);
2356 } else if (p == 0) {
2357 /* We create a grandchild to detach */
2358 if (flag & F_NOWAIT) {
2362 _exit(EXIT_SUCCESS);
2370 _exit(EXIT_FAILURE);
2373 /* So they can be used to stop the child */
2377 /* This is the parent waiting for the child to create grandchild */
2378 if (flag & F_NOWAIT)
2379 waitpid(p, NULL, 0);
2386 static int join(pid_t p, uchar_t flag)
2388 int status = 0xFFFF;
2390 if (!(flag & F_NOWAIT)) {
2391 /* wait for the child to exit */
2393 } while (waitpid(p, &status, 0) == -1);
2395 if (WIFEXITED(status)) {
2396 status = WEXITSTATUS(status);
2401 /* restore parent's signal handling */
2402 sigaction(SIGHUP, &oldsighup, NULL);
2403 sigaction(SIGTSTP, &oldsigtstp, NULL);
2404 sigaction(SIGWINCH, &oldsigwinch, NULL);
2410 * Spawns a child process. Behaviour can be controlled using flag.
2411 * Limited to 3 arguments to a program, flag works on bit set.
2413 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag)
2416 int status = 0, retstatus = 0xFFFF;
2417 char *argv[EXEC_ARGS_MAX] = {0};
2420 if (!file || !*file)
2423 /* Swap args if the first arg is NULL and the other 2 aren't */
2424 if (!arg1 && arg2) {
2433 if (flag & F_MULTI) {
2434 cmd = parseargs(file, argv, &status);
2438 argv[status++] = file;
2440 argv[status] = arg1;
2441 argv[++status] = arg2;
2442 argv[++status] = arg3;
2444 if (flag & F_NORMAL)
2449 /* Suppress stdout and stderr */
2450 if (flag & F_NOTRACE) {
2451 int fd = open("/dev/null", O_WRONLY, 0200);
2453 if (flag & F_NOSTDIN)
2454 dup2(fd, STDIN_FILENO);
2455 dup2(fd, STDOUT_FILENO);
2456 dup2(fd, STDERR_FILENO);
2458 } else if (flag & F_TTY) {
2459 /* If stdout has been redirected to a non-tty, force output to tty */
2460 if (!isatty(STDOUT_FILENO)) {
2461 int fd = open(ctermid(NULL), O_WRONLY, 0200);
2462 dup2(fd, STDOUT_FILENO);
2467 execvp(*argv, argv);
2468 _exit(EXIT_SUCCESS);
2470 retstatus = join(pid, flag);
2473 if ((flag & F_CONFIRM) || ((flag & F_CHKRTN) && retstatus)) {
2474 status = write(STDOUT_FILENO, messages[MSG_ENTER], xstrlen(messages[MSG_ENTER]));
2476 while ((read(STDIN_FILENO, &status, 1) > 0) && (status != '\n'));
2479 if (flag & F_NORMAL)
2488 /* Get program name from env var, else return fallback program */
2489 static char *xgetenv(const char * const name, char *fallback)
2491 char *value = getenv(name);
2493 return value && value[0] ? value : fallback;
2496 /* Checks if an env variable is set to 1 */
2497 static inline uint_t xgetenv_val(const char *name)
2499 char *str = getenv(name);
2507 /* Check if a dir exists, IS a dir, and is readable */
2508 static bool xdiraccess(const char *path)
2510 DIR *dirp = opendir(path);
2521 static bool plugscript(const char *plugin, uchar_t flags)
2523 mkpath(plgpath, plugin, g_buf);
2524 if (!access(g_buf, X_OK)) {
2525 spawn(g_buf, NULL, NULL, NULL, flags);
2532 static void opstr(char *buf, char *op)
2534 snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c '%s \"$0\" \"$@\" . < /dev/tty' < %s", op, selpath);
2537 static bool rmmulstr(char *buf)
2539 char r = confirm_force(TRUE);
2544 snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c 'rm -%cr \"$0\" \"$@\" < /dev/tty' < %s",
2547 snprintf(buf, CMD_LEN_MAX, "xargs -0 %s < %s",
2548 utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH], selpath);
2553 /* Returns TRUE if file is removed, else FALSE */
2554 static bool xrm(char * const fpath)
2556 char r = confirm_force(FALSE);
2560 if (!g_state.trash) {
2561 char rm_opts[] = "-ir";
2564 spawn("rm", rm_opts, fpath, NULL, F_NORMAL | F_CHKRTN);
2566 spawn(utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH],
2567 fpath, NULL, NULL, F_NORMAL | F_MULTI);
2569 return (access(fpath, F_OK) == -1); /* File is removed */
2572 static void xrmfromsel(char *path, char *fpath)
2575 bool selected = TRUE;
2578 if ((pdents[cur].flags & DIR_OR_DIRLNK) && scanselforpath(fpath, FALSE))
2580 else if (pdents[cur].flags & FILE_SELECTED) {
2582 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
2588 if (selected && cfg.x11)
2589 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
2593 static uint_t lines_in_file(int fd, char *buf, size_t buflen)
2598 while ((len = read(fd, buf, buflen)) > 0)
2600 count += (buf[--len] == '\n');
2602 /* For all use cases 0 linecount is considered as error */
2603 return ((len < 0) ? 0 : count);
2606 static bool cpmv_rename(int choice, const char *path)
2609 uint_t count = 0, lines = 0;
2611 char *cmd = (choice == 'c' ? cp : mv);
2612 char buf[sizeof(patterns[P_CPMVRNM]) + (MAX(sizeof(cp), sizeof(mv))) + (PATH_MAX << 1)];
2614 fd = create_tmp_file();
2618 /* selsafe() returned TRUE for this to be called */
2620 snprintf(buf, sizeof(buf), "tr '\\0' '\\n' < %s > %s", selpath, g_tmpfpath);
2621 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2623 count = lines_in_file(fd, buf, sizeof(buf));
2627 seltofile(fd, &count);
2631 snprintf(buf, sizeof(buf), patterns[P_CPMVFMT], g_tmpfpath);
2632 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2634 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2636 fd = open(g_tmpfpath, O_RDONLY);
2640 lines = lines_in_file(fd, buf, sizeof(buf));
2643 if (!lines || (2 * count != lines)) {
2644 DPRINTF_S("num mismatch");
2648 snprintf(buf, sizeof(buf), patterns[P_CPMVRNM], path, g_tmpfpath, cmd);
2649 if (!spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CHKRTN))
2658 static bool cpmvrm_selection(enum action sel, char *path)
2662 if (isselfileempty()) {
2665 printmsg(messages[MSG_0_SELECTED]);
2680 r = get_input(messages[MSG_CP_MV_AS]);
2681 if (r != 'c' && r != 'm') {
2682 printmsg(messages[MSG_INVALID_KEY]);
2686 if (!cpmv_rename(r, path)) {
2687 printmsg(messages[MSG_FAILED]);
2691 default: /* SEL_RM */
2692 if (!rmmulstr(g_buf)) {
2693 printmsg(messages[MSG_CANCEL]);
2698 if (sel != SEL_CPMVAS && spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CHKRTN)) {
2699 printmsg(messages[MSG_FAILED]);
2703 /* Clear selection */
2710 static bool batch_rename(void)
2713 uint_t count = 0, lines = 0;
2714 bool dir = FALSE, ret = FALSE;
2715 char foriginal[TMP_LEN_MAX] = {0};
2716 static const char batchrenamecmd[] = "paste -d'\n' %s %s | "SED" 'N; /^\\(.*\\)\\n\\1$/!p;d' | "
2717 "tr '\n' '\\0' | xargs -0 -n2 sh -c 'mv -i \"$0\" \"$@\" <"
2719 char buf[sizeof(batchrenamecmd) + (PATH_MAX << 1)];
2720 int i = get_cur_or_sel();
2725 if (i == 'c') { /* Rename entries in current dir */
2730 fd1 = create_tmp_file();
2734 xstrsncpy(foriginal, g_tmpfpath, xstrlen(g_tmpfpath) + 1);
2736 fd2 = create_tmp_file();
2744 for (i = 0; i < ndents; ++i)
2745 appendfpath(pdents[i].name, NAME_MAX);
2747 seltofile(fd1, &count);
2748 seltofile(fd2, NULL);
2751 if (dir) /* Don't retain dir entries in selection */
2754 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2756 /* Reopen file descriptor to get updated contents */
2757 fd2 = open(g_tmpfpath, O_RDONLY);
2761 lines = lines_in_file(fd2, buf, sizeof(buf));
2764 if (!lines || (count != lines)) {
2765 DPRINTF_S("cannot delete files");
2769 snprintf(buf, sizeof(buf), batchrenamecmd, foriginal, g_tmpfpath);
2770 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2786 static char *get_archive_cmd(const char *archive)
2790 if (!g_state.usebsdtar && getutil(utils[UTIL_ATOOL]))
2792 else if (getutil(utils[UTIL_BSDTAR]))
2794 else if (is_suffix(archive, ".zip"))
2798 return archive_cmd[i];
2801 static void archive_selection(const char *cmd, const char *archive)
2803 char *buf = malloc((xstrlen(patterns[P_ARCHIVE_CMD]) + xstrlen(cmd) + xstrlen(archive)
2804 + xstrlen(selpath)) * sizeof(char));
2806 DPRINTF_S(strerror(errno));
2811 snprintf(buf, CMD_LEN_MAX, patterns[P_ARCHIVE_CMD], cmd, archive, selpath);
2812 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CONFIRM);
2816 static void write_lastdir(const char *curpath, const char *outfile)
2820 xstrsncpy(cfgpath + xstrlen(cfgpath), "/.lastd", 8);
2822 tilde = convert_tilde(outfile, g_buf);
2824 int fd = open(outfile
2825 ? (tilde ? g_buf : outfile)
2826 : cfgpath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
2828 if (fd != -1 && shell_escape(g_buf, sizeof(g_buf), curpath)) {
2829 dprintf(fd, "cd %s", g_buf);
2835 * We assume none of the strings are NULL.
2837 * Let's have the logic to sort numeric names in numeric order.
2838 * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
2840 * If the absolute numeric values are same, we fallback to alphasort.
2842 static int xstricmp(const char * const s1, const char * const s2)
2846 long long v1 = strtoll(s1, &p1, 10);
2847 long long v2 = strtoll(s2, &p2, 10);
2849 /* Check if at least 1 string is numeric */
2850 if (s1 != p1 || s2 != p2) {
2851 /* Handle both pure numeric */
2852 if (s1 != p1 && s2 != p2) {
2860 /* Only first string non-numeric */
2864 /* Only second string non-numeric */
2869 /* Handle 1. all non-numeric and 2. both same numeric value cases */
2871 return strcoll(s1, s2);
2873 return strcasecmp(s1, s2);
2878 * Version comparison
2880 * The code for version compare is a modified version of the GLIBC
2881 * and uClibc implementation of strverscmp(). The source is here:
2882 * https://elixir.bootlin.com/uclibc-ng/latest/source/libc/string/strverscmp.c
2886 * Compare S1 and S2 as strings holding indices/version numbers,
2887 * returning less than, equal to or greater than zero if S1 is less than,
2888 * equal to or greater than S2 (for more info, see the texinfo doc).
2892 static int xstrverscasecmp(const char * const s1, const char * const s2)
2894 const uchar_t *p1 = (const uchar_t *)s1;
2895 const uchar_t *p2 = (const uchar_t *)s2;
2900 * Symbol(s) 0 [1-9] others
2901 * Transition (10) 0 (01) d (00) x
2903 static const uint8_t next_state[] = {
2905 /* S_N */ S_N, S_I, S_Z,
2906 /* S_I */ S_N, S_I, S_I,
2907 /* S_F */ S_N, S_F, S_F,
2908 /* S_Z */ S_N, S_F, S_Z
2911 alignas(max_align_t) static const int8_t result_type[] = {
2912 /* state x/x x/d x/0 d/x d/d d/0 0/x 0/d 0/0 */
2914 /* S_N */ VCMP, VCMP, VCMP, VCMP, VLEN, VCMP, VCMP, VCMP, VCMP,
2915 /* S_I */ VCMP, -1, -1, 1, VLEN, VLEN, 1, VLEN, VLEN,
2916 /* S_F */ VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP,
2917 /* S_Z */ VCMP, 1, 1, -1, VCMP, VCMP, -1, VCMP, VCMP
2928 /* Hint: '0' is a digit too. */
2929 state = S_N + ((c1 == '0') + (xisdigit(c1) != 0));
2931 while ((diff = c1 - c2) == 0) {
2935 state = next_state[state];
2940 state += (c1 == '0') + (xisdigit(c1) != 0);
2943 state = result_type[state * 3 + (((c2 == '0') + (xisdigit(c2) != 0)))]; // NOLINT
2949 while (xisdigit(*p1++))
2950 if (!xisdigit(*p2++))
2952 return xisdigit(*p2) ? -1 : diff;
2958 static int (*namecmpfn)(const char * const s1, const char * const s2) = &xstricmp;
2960 static char * (*fnstrstr)(const char *haystack, const char *needle) = &strcasestr;
2962 static const unsigned char *tables;
2963 static int pcreflags = PCRE_NO_AUTO_CAPTURE | PCRE_EXTENDED | PCRE_CASELESS | PCRE_UTF8;
2965 static int regflags = REG_NOSUB | REG_EXTENDED | REG_ICASE;
2969 static int setfilter(pcre **pcrex, const char *filter)
2971 const char *errstr = NULL;
2974 *pcrex = pcre_compile(filter, pcreflags, &errstr, &erroffset, tables);
2976 return errstr ? -1 : 0;
2979 static int setfilter(regex_t *regex, const char *filter)
2981 return regcomp(regex, filter, regflags);
2985 static int visible_re(const fltrexp_t *fltrexp, const char *fname)
2988 return pcre_exec(fltrexp->pcrex, NULL, fname, xstrlen(fname), 0, 0, NULL, 0) == 0;
2990 return regexec(fltrexp->regex, fname, 0, NULL, 0) == 0;
2994 static int visible_str(const fltrexp_t *fltrexp, const char *fname)
2996 return fnstrstr(fname, fltrexp->str) != NULL;
2999 static int (*filterfn)(const fltrexp_t *fltr, const char *fname) = &visible_str;
3001 static void clearfilter(void)
3003 char * const fltr = g_ctx[cfg.curctx].c_fltr;
3006 fltr[REGEX_MAX - 1] = fltr[1];
3011 static int entrycmp(const void *va, const void *vb)
3013 const struct entry *pa = (pEntry)va;
3014 const struct entry *pb = (pEntry)vb;
3016 if ((pb->flags & DIR_OR_DIRLNK) != (pa->flags & DIR_OR_DIRLNK)) {
3017 if (pb->flags & DIR_OR_DIRLNK)
3022 /* Sort based on specified order */
3023 if (cfg.timeorder) {
3024 if (pb->sec > pa->sec)
3026 if (pb->sec < pa->sec)
3028 /* If sec matches, comare nsec */
3029 if (pb->nsec > pa->nsec)
3031 if (pb->nsec < pa->nsec)
3033 } else if (cfg.sizeorder) {
3034 if (pb->size > pa->size)
3036 if (pb->size < pa->size)
3038 } else if (cfg.blkorder) {
3039 if (pb->blocks > pa->blocks)
3041 if (pb->blocks < pa->blocks)
3043 } else if (cfg.extnorder && !(pb->flags & DIR_OR_DIRLNK)) {
3044 char *extna = xextension(pa->name, pa->nlen - 1);
3045 char *extnb = xextension(pb->name, pb->nlen - 1);
3047 if (extna || extnb) {
3054 int ret = strcasecmp(extna, extnb);
3061 return namecmpfn(pa->name, pb->name);
3064 static int reventrycmp(const void *va, const void *vb)
3066 if ((((pEntry)vb)->flags & DIR_OR_DIRLNK)
3067 != (((pEntry)va)->flags & DIR_OR_DIRLNK)) {
3068 if (((pEntry)vb)->flags & DIR_OR_DIRLNK)
3073 return -entrycmp(va, vb);
3076 static int (*entrycmpfn)(const void *va, const void *vb) = &entrycmp;
3078 /* In case of an error, resets *wch to Esc */
3079 static int handle_alt_key(wint_t *wch)
3083 int r = get_wch(wch);
3092 static inline int handle_event(void)
3094 if (nselected && isselfileempty())
3096 return CONTROL('L');
3100 * Returns SEL_* if key is bound and 0 otherwise.
3101 * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
3102 * The next keyboard input can be simulated by presel.
3104 static int nextsel(int presel)
3111 bool escaped = FALSE;
3113 if (c == 0 || c == MSGWAIT) {
3117 //DPRINTF_S(keyname(c));
3120 if (c == KEY_RESIZE)
3121 handle_key_resize();
3124 /* Handle Alt+key */
3136 } else if (escaped) {
3141 if (!g_state.fifomode)
3142 notify_fifo(TRUE); /* Send hovered path to NNN_FIFO */
3150 if (i == ERR && presel == MSGWAIT)
3151 c = (cfg.filtermode || filterset()) ? FILTER : CONTROL('L');
3152 else if (c == FILTER || c == CONTROL('L'))
3153 /* Clear previous filter when manually starting */
3161 * Do not check for directory changes in du mode.
3162 * A redraw forces du calculation.
3163 * Check for changes every odd second.
3165 #ifdef LINUX_INOTIFY
3166 if (!cfg.blkorder && inotify_wd >= 0 && (idle & 1)) {
3167 struct inotify_event *event;
3168 char inotify_buf[EVENT_BUF_LEN] = {0};
3170 i = read(inotify_fd, inotify_buf, EVENT_BUF_LEN);
3172 for (char *ptr = inotify_buf;
3173 ptr + ((struct inotify_event *)ptr)->len < inotify_buf + i;
3174 ptr += sizeof(struct inotify_event) + event->len) {
3175 event = (struct inotify_event *)ptr;
3176 DPRINTF_D(event->wd);
3177 DPRINTF_D(event->mask);
3181 if (event->mask & INOTIFY_MASK) {
3186 DPRINTF_S("inotify read done");
3189 #elif defined(BSD_KQUEUE)
3190 if (!cfg.blkorder && event_fd >= 0 && (idle & 1)) {
3191 struct kevent event_data[NUM_EVENT_SLOTS] = {0};
3193 if (kevent(kq, events_to_monitor, NUM_EVENT_SLOTS,
3194 event_data, NUM_EVENT_FDS, >imeout) > 0)
3197 #elif defined(HAIKU_NM)
3198 if (!cfg.blkorder && haiku_nm_active && (idle & 1) && haiku_is_update_needed(haiku_hnd))
3204 for (i = 0; i < (int)ELEMENTS(bindings); ++i)
3205 if (c == bindings[i].sym)
3206 return bindings[i].act;
3211 static int getorderstr(char *sort)
3219 sort[i++] = (cfg.timetype == T_MOD) ? 'M' : ((cfg.timetype == T_ACCESS) ? 'A' : 'C');
3220 else if (cfg.sizeorder)
3222 else if (cfg.extnorder)
3225 if (entrycmpfn == &reventrycmp)
3228 if (namecmpfn == &xstrverscasecmp)
3237 static void showfilterinfo(void)
3240 char info[REGEX_MAX] = "\0\0\0\0\0";
3242 i = getorderstr(info);
3244 if (cfg.fileinfo && ndents && get_output("file", "-b", pdents[cur].name, -1, FALSE))
3245 mvaddstr(xlines - 2, 2, g_buf);
3247 snprintf(info + i, REGEX_MAX - i - 1, " %s [/], %4s [:]",
3248 (cfg.regex ? "reg" : "str"),
3249 ((fnstrstr == &strcasestr) ? "ic" : "noic"));
3252 mvaddstr(xlines - 2, xcols - xstrlen(info), info);
3255 static void showfilter(char *str)
3257 attron(COLOR_PAIR(cfg.curctx + 1));
3260 // printmsg calls attroff()
3263 static inline void swap_ent(int id1, int id2)
3265 struct entry _dent, *pdent1 = &pdents[id1], *pdent2 = &pdents[id2];
3267 *(&_dent) = *pdent1;
3269 *pdent2 = *(&_dent);
3273 static int fill(const char *fltr, pcre *pcrex)
3275 static int fill(const char *fltr, regex_t *re)
3279 fltrexp_t fltrexp = { .pcrex = pcrex, .str = fltr };
3281 fltrexp_t fltrexp = { .regex = re, .str = fltr };
3284 for (int count = 0; count < ndents; ++count) {
3285 if (filterfn(&fltrexp, pdents[count].name) == 0) {
3286 if (count != --ndents) {
3287 swap_ent(count, ndents);
3298 static int matches(const char *fltr)
3304 if (cfg.regex && setfilter(&pcrex, fltr))
3307 ndents = fill(fltr, pcrex);
3315 if (cfg.regex && setfilter(&re, fltr))
3318 ndents = fill(fltr, &re);
3324 ENTSORT(pdents, ndents, entrycmpfn);
3330 * Return the position of the matching entry or 0 otherwise
3331 * Note there's no NULL check for fname
3333 static int dentfind(const char *fname, int n)
3335 for (int i = 0; i < n; ++i)
3336 if (xstrcmp(fname, pdents[i].name) == 0)
3342 static int filterentries(char *path, char *lastname)
3344 alignas(max_align_t) wchar_t wln[REGEX_MAX];
3345 char *ln = g_ctx[cfg.curctx].c_fltr;
3347 int r, total = ndents, len;
3348 char *pln = g_ctx[cfg.curctx].c_fltr + 1;
3350 DPRINTF_S(__func__);
3352 if (ndents && (ln[0] == FILTER || ln[0] == RFILTER) && *pln) {
3353 if (matches(pln) != -1) {
3354 move_cursor(dentfind(lastname, ndents), 0);
3358 if (!cfg.filtermode) {
3363 len = mbstowcs(wln, ln, REGEX_MAX);
3365 ln[0] = wln[0] = cfg.regex ? RFILTER : FILTER;
3366 ln[1] = wln[1] = '\0';
3374 while ((r = get_wch(ch)) != ERR) {
3376 //DPRINTF_S(keyname(*ch));
3380 case 0: // fallthrough
3387 case KEY_DC: // fallthrough
3388 case KEY_BACKSPACE: // fallthrough
3389 case '\b': // fallthrough
3390 case DEL: /* handle DEL */
3393 wcstombs(ln, wln, REGEX_MAX);
3401 if (*ch == CONTROL('L')) {
3403 ln[REGEX_MAX - 1] = ln[1];
3404 ln[1] = wln[1] = '\0';
3407 } else if (ln[REGEX_MAX - 1]) { /* Show the previous filter */
3408 ln[1] = ln[REGEX_MAX - 1];
3409 ln[REGEX_MAX - 1] = '\0';
3410 len = mbstowcs(wln, ln, REGEX_MAX);
3415 /* Go to the top, we don't know if the hovered file will match the filter */
3418 if (matches(pln) != -1)
3428 if (handle_alt_key(ch) != ERR) {
3429 if (*ch == ESC) /* Handle Alt+Esc */
3430 *ch = 'q'; /* Quit context */
3433 *ch = ';'; /* Run plugin */
3439 if (r != OK) /* Handle Fn keys in main loop */
3442 /* Handle all control chars in main loop */
3443 if (*ch < ASCII_MAX && keyname(*ch)[0] == '^' && *ch != '^')
3447 if (*ch == '?') /* Help and config key, '?' is an invalid regex */
3450 if (cfg.filtermode) {
3452 case '\'': // fallthrough /* Go to first non-dir file */
3453 case '+': // fallthrough /* Toggle file selection */
3454 case ',': // fallthrough /* Mark CWD */
3455 case '-': // fallthrough /* Visit last visited dir */
3456 case '.': // fallthrough /* Show hidden files */
3457 case ';': // fallthrough /* Run plugin key */
3458 case '=': // fallthrough /* Launch app */
3459 case '>': // fallthrough /* Export file list */
3460 case '@': // fallthrough /* Visit start dir */
3461 case ']': // fallthorugh /* Prompt key */
3462 case '`': // fallthrough /* Visit / */
3463 case '~': /* Go HOME */
3468 /* Toggle case-sensitivity */
3470 fnstrstr = (fnstrstr == &strcasestr) ? &strstr : &strcasestr;
3472 pcreflags ^= PCRE_CASELESS;
3474 regflags ^= REG_ICASE;
3480 /* Toggle string or regex filter */
3481 if (*ch == FILTER) {
3482 ln[0] = (ln[0] == FILTER) ? RFILTER : FILTER;
3483 wln[0] = (uchar_t)ln[0];
3485 filterfn = cfg.regex ? &visible_re : &visible_str;
3490 /* Reset cur in case it's a repeat search */
3492 } else if (len == REGEX_MAX - 1)
3495 wln[len] = (wchar_t)*ch;
3497 wcstombs(ln, wln, REGEX_MAX);
3499 /* Forward-filtering optimization:
3500 * - new matches can only be a subset of current matches.
3502 /* ndents = total; */
3506 !r ? unget_wch(KEY_BACKSPACE) : showfilter(ln);
3508 if (matches(pln) == -1) {
3514 /* If the only match is a dir, auto-enter and cd into it */
3515 if ((ndents == 1) && cfg.autoenter && (pdents[0].flags & DIR_OR_DIRLNK)) {
3522 * redraw() should be above the auto-enter optimization, for
3523 * the case where there's an issue with dir auto-enter, say,
3524 * due to a permission problem. The transition is _jumpy_ in
3525 * case of such an error. However, we optimize for successful
3526 * cases where the dir has permissions. This skips a redraw().
3533 /* Save last working filter in-filter */
3535 ln[REGEX_MAX - 1] = ln[1];
3543 /* Return keys for navigation etc. */
3547 /* Show a prompt with input string and return the changes */
3548 static char *xreadline(const char *prefill, const char *prompt)
3552 const int WCHAR_T_WIDTH = sizeof(wchar_t);
3554 wchar_t * const buf = malloc(sizeof(wchar_t) * READLINE_MAX);
3564 len = pos = mbstowcs(buf, prefill, READLINE_MAX);
3568 if (len == (size_t)-1) {
3573 x = getcurx(stdscr);
3578 attron(COLOR_PAIR(cfg.curctx + 1));
3579 if (pos > (size_t)(xcols - x)) {
3580 mvaddnwstr(xlines - 1, x, buf + (pos - (xcols - x) + 1), xcols - x);
3581 move(xlines - 1, xcols - 1);
3583 mvaddnwstr(xlines - 1, x, buf, len + 1);
3584 move(xlines - 1, x + wcswidth(buf, pos));
3586 attroff(COLOR_PAIR(cfg.curctx + 1));
3594 case KEY_ENTER: // fallthrough
3595 case '\n': // fallthrough
3601 else if (!(pos || len)) { /* Exit on ^D at empty prompt */
3607 case DEL: // fallthrough
3608 case '\b': /* rhel25 sends '\b' for backspace */
3610 memmove(buf + pos - 1, buf + pos,
3611 (len - pos) * WCHAR_T_WIDTH);
3616 if (!(len || pos) && ndents)
3617 len = pos = mbstowcs(buf, pdents[cur].name, READLINE_MAX);
3632 memmove(buf + pos - 1, buf + pos,
3633 (len - pos) * WCHAR_T_WIDTH);
3635 } while (buf[pos - 1] != ' ' && buf[pos - 1] != '/'); // NOLINT
3653 memmove(buf, buf + pos, (len - pos) * WCHAR_T_WIDTH);
3657 case ESC: /* Exit prompt on Esc, but just filter out Alt+key */
3658 if (handle_alt_key(ch) != ERR)
3665 /* Filter out all other control chars */
3666 if (*ch < ASCII_MAX && keyname(*ch)[0] == '^')
3669 if (pos < READLINE_MAX - 1) {
3670 memmove(buf + pos + 1, buf + pos,
3671 (len - pos) * WCHAR_T_WIDTH);
3695 memmove(buf + pos - 1, buf + pos,
3696 (len - pos) * WCHAR_T_WIDTH);
3702 memmove(buf + pos, buf + pos + 1,
3703 (len - pos - 1) * WCHAR_T_WIDTH);
3713 case KEY_UP: // fallthrough
3715 if (prompt && lastcmd && (xstrcmp(prompt, PROMPT) == 0)) {
3717 len = pos = mbstowcs(buf, lastcmd, READLINE_MAX); // fallthrough
3732 pos = wcstombs(g_buf, buf, READLINE_MAX - 1);
3733 if (pos >= READLINE_MAX - 1)
3734 g_buf[READLINE_MAX - 1] = '\0';
3742 * Caller should check the value of presel to confirm if it needs to wait to show warning
3744 static char *getreadline(const char *prompt)
3748 char *input = readline(prompt);
3752 if (input && input[0]) {
3754 xstrsncpy(g_buf, input, CMD_LEN_MAX);
3765 * Create symbolic/hard link(s) to file(s) in selection list
3766 * Returns the number of links created, -1 on error
3768 static int xlink(char *prefix, char *path, char *curfname, char *buf, int type)
3770 int count = 0, choice;
3771 char *psel = pselbuf, *fname;
3772 size_t pos = 0, len, r;
3773 int (*link_fn)(const char *, const char *) = NULL;
3774 char lnpath[PATH_MAX];
3776 choice = get_cur_or_sel();
3780 if (type == 's') /* symbolic link */
3782 else /* hard link */
3785 if (choice == 'c' || (nselected == 1)) {
3786 prefix = abspath(prefix, path, lnpath); /* Generate link path */
3791 mkpath(path, curfname, buf); /* Generate target file path */
3793 if (!link_fn((choice == 'c') ? buf : pselbuf, lnpath)) {
3796 return 1; /* One link created */
3801 r = xstrsncpy(buf, prefix, NAME_MAX + 1); /* Copy prefix */
3803 while (pos < selbufpos) {
3804 len = xstrlen(psel);
3805 fname = xbasename(psel);
3807 xstrsncpy(buf + r - 1, fname, NAME_MAX - r); /* Suffix target file name */
3808 mkpath(path, buf, lnpath); /* Generate link path */
3810 if (!link_fn(psel, lnpath))
3817 if (count == nselected) /* Clear selection if all links are generated */
3822 static bool parsekvpair(kv **arr, char **envcpy, const uchar_t id, uchar_t *items)
3825 const uchar_t INCR = 8;
3828 char *ptr = getenv(env_cfg[id]);
3833 *envcpy = xstrdup(ptr);
3841 while (*ptr && i < 100) {
3843 if (!(i & (INCR - 1))) {
3844 kvarr = xrealloc(kvarr, sizeof(kv) * (i + INCR));
3850 memset(kvarr + i, 0, sizeof(kv) * INCR);
3852 kvarr[i].key = (uchar_t)*ptr;
3853 if (*++ptr != ':' || *++ptr == '\0' || *ptr == ';')
3855 kvarr[i].off = ptr - *envcpy;
3874 * Get the value corresponding to a key
3876 * NULL is returned in case of no match, path resolution failure etc.
3877 * buf would be modified, so check return value before access
3879 static char *get_kv_val(kv *kvarr, char *buf, int key, uchar_t max, uchar_t id)
3886 for (int r = 0; r < max && kvarr[r].key; ++r) {
3887 if (kvarr[r].key == key) {
3888 /* Do not allocate new memory for plugin */
3890 return pluginstr + kvarr[r].off;
3892 val = bmstr + kvarr[r].off;
3893 bool tilde = convert_tilde(val, g_buf);
3894 return abspath((tilde ? g_buf : val), NULL, buf);
3898 DPRINTF_S("Invalid key");
3902 static int get_kv_key(kv *kvarr, char *val, uchar_t max, uchar_t id)
3907 if (id != NNN_ORDER) /* For now this function supports only order string */
3910 for (int r = 0; r < max && kvarr[r].key; ++r) {
3911 if (xstrcmp((orderstr + kvarr[r].off), val) == 0)
3912 return kvarr[r].key;
3918 static void resetdircolor(int flags)
3920 /* Directories are always shown on top, clear the color when moving to first file */
3921 if (g_state.dircolor && !(flags & DIR_OR_DIRLNK)) {
3922 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
3923 g_state.dircolor = 0;
3928 * Replace escape characters in a string with '?'
3929 * Adjust string length to maxcols if > 0;
3930 * Max supported str length: NAME_MAX;
3933 static char *unescape(const char *str, uint_t maxcols)
3935 char * const wbuf = g_buf;
3938 xstrsncpy(wbuf, str, maxcols);
3940 static wchar_t *unescape(const char *str, uint_t maxcols)
3942 wchar_t * const wbuf = (wchar_t *)g_buf;
3943 wchar_t *buf = wbuf;
3944 size_t len = mbstowcs(wbuf, str, maxcols); /* Convert multi-byte to wide char */
3946 len = wcswidth(wbuf, len);
3948 if (len >= maxcols) {
3949 size_t lencount = maxcols;
3951 while (len > maxcols) /* Reduce wide chars one by one till it fits */
3952 len = wcswidth(wbuf, --lencount);
3954 wbuf[lencount] = L'\0';
3959 if (*buf <= '\x1f' || *buf == '\x7f')
3968 static off_t get_size(off_t size, off_t *pval, int comp)
3971 off_t quo = rem / 10;
3973 if ((rem - (quo * 10)) >= 5) {
3986 static char *coolsize(off_t size)
3988 const char * const U = "BKMGTPEZY";
3989 static char size_buf[12]; /* Buffer to hold human readable size */
3994 while (size >= 1024) {
3995 rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
4001 rem = (rem * 1000) >> 10;
4003 size = get_size(size, &rem, 10);
4004 } else if (i == 2) {
4005 rem = (rem * 1000) >> 10;
4006 size = get_size(size, &rem, 100);
4008 rem = (rem * 10000) >> 10;
4009 size = get_size(size, &rem, 1000);
4012 if (i > 0 && i < 6 && rem) {
4013 ret = xstrsncpy(size_buf, xitoa(size), 12);
4014 size_buf[ret - 1] = '.';
4016 char *frac = xitoa(rem);
4017 size_t toprint = i > 3 ? 3 : i;
4018 size_t len = xstrlen(frac);
4020 if (len < toprint) {
4021 size_buf[ret] = size_buf[ret + 1] = size_buf[ret + 2] = '0';
4022 xstrsncpy(size_buf + ret + (toprint - len), frac, len + 1);
4024 xstrsncpy(size_buf + ret, frac, toprint + 1);
4028 ret = xstrsncpy(size_buf, size ? xitoa(size) : "0", 12);
4032 size_buf[ret] = U[i];
4033 size_buf[ret + 1] = '\0';
4038 /* Convert a mode field into "ls -l" type perms field. */
4039 static char *get_lsperms(mode_t mode)
4041 static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
4042 static char bits[11] = {'\0'};
4044 switch (mode & S_IFMT) {
4071 xstrsncpy(&bits[1], rwx[(mode >> 6) & 7], 4);
4072 xstrsncpy(&bits[4], rwx[(mode >> 3) & 7], 4);
4073 xstrsncpy(&bits[7], rwx[(mode & 7)], 4);
4076 bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
4078 bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
4080 bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
4085 #ifdef ICONS_ENABLED
4086 static struct icon get_icon(const struct entry *ent)
4088 for (size_t i = 0; i < ELEMENTS(icons_name); ++i)
4089 if (strcasecmp(ent->name, icons_name[i].match) == 0)
4090 return (struct icon){ icons_name[i].icon, icons_name[i].color };
4092 if (ent->flags & DIR_OR_DIRLNK)
4095 char *tmp = xextension(ent->name, ent->nlen);
4098 uint16_t z, k, h = icon_ext_hash(++tmp); /* ++tmp to skip '.' */
4099 for (k = 0; k < ICONS_PROBE_MAX; ++k) {
4100 z = (h + k) % ELEMENTS(icons_ext);
4101 if (strcasecmp(tmp, icons_ext[z].match) == 0)
4102 return (struct icon){ icons_ext_uniq[icons_ext[z].idx], icons_ext[z].color };
4106 /* If there's no match and the file is executable, icon that */
4107 if (ent->mode & 0100)
4112 static void print_icon(const struct entry *ent, const int attrs)
4114 const struct icon icon = get_icon(ent);
4115 addstr(ICON_PADDING_LEFT);
4117 attron(COLOR_PAIR(C_UND + 1 + icon.color));
4122 attroff(COLOR_PAIR(C_UND + 1 + icon.color));
4125 addstr(ICON_PADDING_RIGHT);
4129 static void print_time(const time_t *timep, const uchar_t flags)
4133 /* Highlight timestamp for entries 5 minutes young */
4134 if (flags & FILE_YOUNG)
4137 localtime_r(timep, &t);
4138 printw("%s-%02d-%02d %02d:%02d",
4139 xitoa(t.tm_year + 1900), t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min);
4141 if (flags & FILE_YOUNG)
4145 static char get_detail_ind(const mode_t mode)
4147 switch (mode & S_IFMT) {
4148 case S_IFDIR: // fallthrough
4149 case S_IFREG: return ' ';
4150 case S_IFLNK: return '@';
4151 case S_IFSOCK: return '=';
4152 case S_IFIFO: return '|';
4153 case S_IFBLK: return 'b';
4154 case S_IFCHR: return 'c';
4159 /* Note: attribute and indicator values must be initialized to 0 */
4160 static uchar_t get_color_pair_name_ind(const struct entry *ent, char *pind, int *pattr)
4162 switch (ent->mode & S_IFMT) {
4165 if (ent->mode & 0100)
4169 if (ent->flags & HARD_LINK) {
4170 if (ent->mode & 0100)
4174 if (ent->mode & 0100) {
4181 if (g_state.oldcolor)
4184 return g_state.dirctx ? cfg.curctx + 1 : C_DIR;
4186 if (ent->flags & DIR_OR_DIRLNK) {
4188 *pattr |= g_state.oldcolor ? A_DIM : A_BOLD;
4191 if (g_state.oldcolor)
4194 if (!g_state.oldcolor || cfg.showdetail)
4195 return (ent->flags & SYM_ORPHAN) ? C_ORP : C_LNK;
4213 static void printent(const struct entry *ent, uint_t namecols, bool sel)
4218 if (cfg.showdetail) {
4219 int type = ent->mode & S_IFMT;
4220 char perms[6] = {' ', ' ', (char)('0' + ((ent->mode >> 6) & 7)),
4221 (char)('0' + ((ent->mode >> 3) & 7)),
4222 (char)('0' + (ent->mode & 7)), '\0'};
4225 attrs = g_state.oldcolor ? (resetdircolor(ent->flags), A_DIM)
4226 : (fcolors[C_MIS] ? COLOR_PAIR(C_MIS) : 0);
4231 print_time(&ent->sec, ent->flags);
4233 printw("%s%9s ", perms, (type == S_IFREG || type == S_IFDIR)
4234 ? coolsize(cfg.blkorder ? (blkcnt_t)ent->blocks << blk_shift : ent->size)
4235 : (type = (uchar_t)get_detail_ind(ent->mode), (char *)&type));
4243 uchar_t color_pair = get_color_pair_name_ind(ent, &ind, &attrs);
4245 addch((ent->flags & FILE_SELECTED) ? '+' | A_REVERSE | A_BOLD : ' ');
4247 if (g_state.oldcolor)
4248 resetdircolor(ent->flags);
4250 if (ent->flags & FILE_MISSING)
4252 if (color_pair && fcolors[color_pair])
4253 attrs |= COLOR_PAIR(color_pair);
4254 #ifdef ICONS_ENABLED
4255 print_icon(ent, attrs);
4267 addwstr(unescape(ent->name, namecols));
4269 addstr(unescape(ent->name, MIN(namecols, ent->nlen) + 1));
4278 static void savecurctx(char *path, char *curname, int nextctx)
4280 settings tmpcfg = cfg;
4281 context *ctxr = &g_ctx[nextctx];
4283 /* Save current context */
4285 xstrsncpy(g_ctx[tmpcfg.curctx].c_name, curname, NAME_MAX + 1);
4287 g_ctx[tmpcfg.curctx].c_name[0] = '\0';
4289 g_ctx[tmpcfg.curctx].c_cfg = tmpcfg;
4291 if (ctxr->c_cfg.ctxactive) { /* Switch to saved context */
4292 tmpcfg = ctxr->c_cfg;
4293 /* Skip ordering an open context */
4295 cfgsort[CTX_MAX] = cfgsort[nextctx];
4296 cfgsort[nextctx] = '0';
4298 } else { /* Set up a new context from current context */
4299 ctxr->c_cfg.ctxactive = 1;
4300 xstrsncpy(ctxr->c_path, path, PATH_MAX);
4301 ctxr->c_last[0] = ctxr->c_name[0] = ctxr->c_fltr[0] = ctxr->c_fltr[1] = '\0';
4302 ctxr->c_cfg = tmpcfg;
4303 /* If already in an ordered dir, clear ordering for the new context and let it order */
4304 if (cfgsort[cfg.curctx] == 'z')
4305 cfgsort[nextctx] = 'z';
4308 tmpcfg.curctx = nextctx;
4313 static void save_session(const char *sname, int *presel)
4316 session_header_t header = {0};
4317 bool status = FALSE;
4318 char ssnpath[PATH_MAX];
4319 char spath[PATH_MAX];
4321 header.ver = SESSIONS_VERSION;
4323 for (i = 0; i < CTX_MAX; ++i) {
4324 if (g_ctx[i].c_cfg.ctxactive) {
4325 if (cfg.curctx == i && ndents)
4326 /* Update current file name, arrows don't update it */
4327 xstrsncpy(g_ctx[i].c_name, pdents[cur].name, NAME_MAX + 1);
4328 header.pathln[i] = MIN(xstrlen(g_ctx[i].c_path), PATH_MAX) + 1;
4329 header.lastln[i] = MIN(xstrlen(g_ctx[i].c_last), PATH_MAX) + 1;
4330 header.nameln[i] = MIN(xstrlen(g_ctx[i].c_name), NAME_MAX) + 1;
4331 header.fltrln[i] = REGEX_MAX;
4335 mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4336 mkpath(ssnpath, sname, spath);
4338 fd = open(spath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
4340 printwait(messages[MSG_SEL_MISSING], presel);
4344 if ((write(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4345 || (write(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4348 for (i = 0; i < CTX_MAX; ++i)
4349 if ((write(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4350 || (write(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4351 || (header.nameln[i] > 0
4352 && write(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4353 || (header.lastln[i] > 0
4354 && write(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4355 || (header.fltrln[i] > 0
4356 && write(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4357 || (header.pathln[i] > 0
4358 && write(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4367 printwait(messages[MSG_FAILED], presel);
4370 static bool load_session(const char *sname, char **path, char **lastdir, char **lastname, bool restore)
4373 session_header_t header;
4374 bool has_loaded_dynamically = !(sname || restore);
4375 bool status = (sname && g_state.picker); /* Picker mode with session program option */
4376 char ssnpath[PATH_MAX];
4377 char spath[PATH_MAX];
4379 mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4382 sname = sname ? sname : xreadline(NULL, messages[MSG_SSN_NAME]);
4386 mkpath(ssnpath, sname, spath);
4388 /* If user is explicitly loading the "last session", skip auto-save */
4389 if ((sname[0] == '@') && !sname[1])
4390 has_loaded_dynamically = FALSE;
4392 mkpath(ssnpath, "@", spath);
4394 if (has_loaded_dynamically)
4395 save_session("@", NULL);
4397 fd = open(spath, O_RDONLY, S_IWUSR | S_IRUSR);
4400 printmsg(messages[MSG_SEL_MISSING]);
4401 xdelay(XDELAY_INTERVAL_MS);
4408 if ((read(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4409 || (header.ver != SESSIONS_VERSION)
4410 || (read(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4413 g_ctx[cfg.curctx].c_name[0] = g_ctx[cfg.curctx].c_last[0]
4414 = g_ctx[cfg.curctx].c_fltr[0] = g_ctx[cfg.curctx].c_fltr[1] = '\0';
4416 for (; i < CTX_MAX; ++i)
4417 if ((read(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4418 || (read(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4419 || (header.nameln[i] > 0
4420 && read(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4421 || (header.lastln[i] > 0
4422 && read(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4423 || (header.fltrln[i] > 0
4424 && read(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4425 || (header.pathln[i] > 0
4426 && read(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4429 *path = g_ctx[cfg.curctx].c_path;
4430 *lastdir = g_ctx[cfg.curctx].c_last;
4431 *lastname = g_ctx[cfg.curctx].c_name;
4432 set_sort_flags('\0'); /* Set correct sort options */
4439 printmsg(messages[MSG_FAILED]);
4440 xdelay(XDELAY_INTERVAL_MS);
4448 static uchar_t get_free_ctx(void)
4450 uchar_t r = cfg.curctx;
4453 r = (r + 1) & ~CTX_MAX;
4454 while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
4459 /* ctx is absolute: 1 to 4, + for smart context */
4460 static void set_smart_ctx(int ctx, char *nextpath, char **path, char *file, char **lastname, char **lastdir)
4462 if (ctx == '+') /* Get smart context */
4463 ctx = (int)(get_free_ctx() + 1);
4465 if (ctx == 0 || ctx == cfg.curctx + 1) { /* Same context */
4467 xstrsncpy(*lastdir, *path, PATH_MAX);
4468 xstrsncpy(*path, nextpath, PATH_MAX);
4469 } else { /* New context */
4471 /* Deactivate the new context and build from scratch */
4472 g_ctx[ctx].c_cfg.ctxactive = 0;
4473 DPRINTF_S(nextpath);
4474 savecurctx(nextpath, file, ctx);
4475 *path = g_ctx[ctx].c_path;
4476 *lastdir = g_ctx[ctx].c_last;
4477 *lastname = g_ctx[ctx].c_name;
4482 * This function does one of the following depending on the values of `fdout` and `page`:
4483 * 1) fdout == -1 && !page: Write up to CMD_LEN_MAX bytes of command output into g_buf
4484 * 2) fdout == -1 && page: Create a temp file, write full command output into it and show in pager.
4485 * 3) fdout != -1 && !page: Write full command output into the provided file.
4486 * 4) fdout != -1 && page: Don't use! Returns FALSE.
4488 * g_buf is modified only in case 1.
4489 * g_tmpfpath is modified only in case 2.
4491 static bool get_output(char *file, char *arg1, char *arg2, int fdout, bool page)
4495 int index = 0, flags;
4497 bool have_file = fdout != -1;
4499 int cmd_out_fd = -1;
4503 * In this case the logic of the function dictates that we should write the output of the command
4504 * to `fd` and show it in the pager. But since we didn't open the file descriptor we have no right
4505 * to close it, the caller must do it. We don't even know the path to pass to the pager and
4506 * it's a real hassle to get it. In general this just invites problems so we are blocking it.
4508 if (have_file && page) {
4509 DPRINTF_S("invalid get_ouptput() call");
4513 /* Setup file descriptors for child command */
4514 if (!have_file && page) {
4516 fdout = create_tmp_file();
4520 cmd_in_fd = STDIN_FILENO;
4522 } else if (have_file) {
4524 cmd_in_fd = STDIN_FILENO;
4528 if (pipe(pipefd) == -1)
4531 for (index = 0; index < 2; ++index) {
4532 /* Get previous flags */
4533 flags = fcntl(pipefd[index], F_GETFL, 0);
4535 /* Set bit for non-blocking flag */
4536 flags |= O_NONBLOCK;
4538 /* Change flags on fd */
4539 fcntl(pipefd[index], F_SETFL, flags);
4542 cmd_in_fd = pipefd[0];
4543 cmd_out_fd = pipefd[1];
4550 dup2(cmd_out_fd, STDOUT_FILENO);
4551 dup2(cmd_out_fd, STDERR_FILENO);
4554 spawn(file, arg1, arg2, NULL, F_MULTI);
4555 _exit(EXIT_SUCCESS);
4559 waitpid(pid, NULL, 0);
4561 /* Do what each case should do */
4562 if (!have_file && page) {
4566 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4577 len = read(pipefd[0], g_buf, CMD_LEN_MAX - 1);
4587 * Follows the stat(1) output closely
4589 static bool show_stats(char *fpath)
4591 static char * const cmds[] = {
4592 #ifdef FILE_MIME_OPTS
4593 ("file " FILE_MIME_OPTS),
4596 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
4603 size_t r = ELEMENTS(cmds);
4604 int fd = create_tmp_file();
4609 get_output(cmds[--r], fpath, NULL, fd, FALSE);
4613 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4618 static bool xchmod(const char *fpath, mode_t *mode)
4620 /* (Un)set (S_IXUSR | S_IXGRP | S_IXOTH) */
4621 (0100 & *mode) ? (*mode &= ~0111) : (*mode |= 0111);
4623 return (chmod(fpath, *mode) == 0);
4626 static size_t get_fs_info(const char *path, uchar_t type)
4630 if (statvfs(path, &svb) == -1)
4633 if (type == VFS_AVAIL)
4634 return (size_t)svb.f_bavail << ffs((int)(svb.f_frsize >> 1));
4636 if (type == VFS_USED)
4637 return ((size_t)svb.f_blocks - (size_t)svb.f_bfree) << ffs((int)(svb.f_frsize >> 1));
4639 return (size_t)svb.f_blocks << ffs((int)(svb.f_frsize >> 1)); /* VFS_SIZE */
4642 /* Create non-existent parents and a file or dir */
4643 static bool xmktree(char *path, bool dir)
4651 /* Skip the first '/' */
4654 while (*p != '\0') {
4663 /* Create folder from path to '\0' inserted at p */
4664 if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4666 // XDG_CONFIG_HOME contains a directory
4667 // that is read-only, but the full path
4669 // Try to continue and see what happens.
4670 // TODO: Find a more robust solution.
4671 if (errno == B_READ_ONLY_DEVICE)
4674 DPRINTF_S("mkdir1!");
4675 DPRINTF_S(strerror(errno));
4689 if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4690 DPRINTF_S("mkdir2!");
4691 DPRINTF_S(strerror(errno));
4695 int fd = open(path, O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR); /* Forced create mode for files */
4697 if (fd == -1 && errno != EEXIST) {
4699 DPRINTF_S(strerror(errno));
4709 /* List or extract archive */
4710 static bool handle_archive(char *fpath /* in-out param */, char op)
4712 char arg[] = "-tvf"; /* options for tar/bsdtar to list files */
4713 char *util, *outdir = NULL;
4715 bool is_atool = (!g_state.usebsdtar && getutil(utils[UTIL_ATOOL]));
4718 outdir = xreadline(is_atool ? "." : xbasename(fpath), messages[MSG_NEW_PATH]);
4719 if (!outdir || !*outdir) { /* Cancelled */
4720 printwait(messages[MSG_CANCEL], NULL);
4723 /* Do not create smart context for current dir */
4724 if (!(*outdir == '.' && outdir[1] == '\0')) {
4725 if (!xmktree(outdir, TRUE) || (chdir(outdir) == -1)) {
4729 /* Copy the new dir path to open it in smart context */
4730 outdir = getcwd(NULL, 0);
4736 util = utils[UTIL_ATOOL];
4739 } else if (getutil(utils[UTIL_BSDTAR])) {
4740 util = utils[UTIL_BSDTAR];
4743 } else if (is_suffix(fpath, ".zip")) {
4744 util = utils[UTIL_UNZIP];
4745 arg[1] = (op == 'l') ? 'v' /* verbose listing */ : '\0';
4748 util = utils[UTIL_TAR];
4753 if (op == 'x') /* extract */
4754 spawn(util, arg, fpath, NULL, F_NORMAL | F_MULTI);
4756 get_output(util, arg, fpath, -1, TRUE);
4759 if (chdir(xdirname(fpath)) == -1) {
4764 xstrsncpy(fpath, outdir, PATH_MAX);
4766 } else if (op == 'x')
4772 static char *visit_parent(char *path, char *newpath, int *presel)
4776 /* There is no going back */
4777 if (istopdir(path)) {
4778 /* Continue in type-to-nav mode, if enabled */
4779 if (cfg.filtermode && presel)
4784 /* Use a copy as xdirname() may change the string passed */
4786 xstrsncpy(newpath, path, PATH_MAX);
4790 dir = xdirname(newpath);
4791 if (chdir(dir) == -1) {
4799 static void valid_parent(char *path, char *lastname)
4802 xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
4804 while (!istopdir(path))
4805 if (visit_parent(path, NULL, NULL))
4809 xdelay(XDELAY_INTERVAL_MS);
4812 static bool archive_mount(char *newpath)
4814 char *dir, *cmd = xgetenv("NNN_ARCHMNT", utils[UTIL_ARCHMNT]);
4815 char *name = pdents[cur].name;
4816 size_t len = pdents[cur].nlen;
4817 char mntpath[PATH_MAX];
4819 if (!getutil(cmd)) {
4820 printmsg("install utility");
4824 dir = xstrdup(name);
4826 printmsg(messages[MSG_FAILED]);
4831 if (dir[--len] == '.') {
4838 /* Create the mount point */
4839 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4840 mkpath(mntpath, dir, newpath);
4843 if (!xmktree(newpath, TRUE)) {
4851 if (spawn(cmd, name, newpath, NULL, F_NORMAL)) {
4852 printmsg(messages[MSG_FAILED]);
4859 static bool remote_mount(char *newpath)
4861 uchar_t flag = F_CLI;
4864 bool r = getutil(utils[UTIL_RCLONE]), s = getutil(utils[UTIL_SSHFS]);
4865 char mntpath[PATH_MAX];
4868 printmsg("install sshfs/rclone");
4873 opt = get_input(messages[MSG_REMOTE_OPTS]);
4875 opt = (!s) ? 'r' : 's';
4878 env = xgetenv("NNN_SSHFS", utils[UTIL_SSHFS]);
4879 else if (opt == 'r') {
4880 flag |= F_NOWAIT | F_NOTRACE;
4881 env = xgetenv("NNN_RCLONE", "rclone mount");
4883 printmsg(messages[MSG_INVALID_KEY]);
4887 tmp = xreadline(NULL, "host[:dir] > ");
4889 printmsg(messages[MSG_CANCEL]);
4893 char *div = strchr(tmp, ':');
4898 /* Create the mount point */
4899 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4900 mkpath(mntpath, tmp, newpath);
4901 if (!xmktree(newpath, TRUE)) {
4906 if (!div) { /* Convert "host" to "host:" */
4907 size_t len = xstrlen(tmp);
4910 tmp[len + 1] = '\0';
4914 /* Connect to remote */
4916 if (spawn(env, tmp, newpath, NULL, flag)) {
4917 printmsg(messages[MSG_FAILED]);
4921 spawn(env, tmp, newpath, NULL, flag);
4922 printmsg(messages[MSG_RCLONE_DELAY]);
4923 xdelay(XDELAY_INTERVAL_MS << 2); /* Set 4 times the usual delay */
4930 * Unmounts if the directory represented by name is a mount point.
4931 * Otherwise, asks for hostname
4932 * Returns TRUE if directory needs to be refreshed *.
4934 static bool unmount(char *name, char *newpath, int *presel, char *currentpath)
4936 #if defined(__APPLE__) || defined(__FreeBSD__)
4937 static char cmd[] = "umount";
4939 static char cmd[] = "fusermount3"; /* Arch Linux utility */
4940 static bool found = FALSE;
4943 struct stat sb, psb;
4945 bool parent = FALSE;
4946 bool hovered = FALSE;
4947 char mntpath[PATH_MAX];
4949 #if !defined(__APPLE__) && !defined(__FreeBSD__)
4950 /* On Ubuntu it's fusermount */
4951 if (!found && !getutil(cmd)) {
4957 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4959 if (tmp && strcmp(mntpath, currentpath) == 0) {
4960 mkpath(mntpath, tmp, newpath);
4961 child = lstat(newpath, &sb) != -1;
4962 parent = lstat(xdirname(newpath), &psb) != -1;
4963 if (!child && !parent) {
4969 if (!tmp || !child || !S_ISDIR(sb.st_mode) || (child && parent && sb.st_dev == psb.st_dev)) {
4970 tmp = xreadline(NULL, messages[MSG_HOSTNAME]);
4973 if (name && (tmp[0] == '-') && (tmp[1] == '\0')) {
4974 mkpath(currentpath, name, newpath);
4980 mkpath(mntpath, tmp, newpath);
4982 if (!xdiraccess(newpath)) {
4987 #if defined(__APPLE__) || defined(__FreeBSD__)
4988 if (spawn(cmd, newpath, NULL, NULL, F_NORMAL)) {
4990 if (spawn(cmd, "-qu", newpath, NULL, F_NORMAL)) {
4992 if (!xconfirm(get_input(messages[MSG_LAZY])))
4996 if (spawn(cmd, "-l", newpath, NULL, F_NORMAL)) {
4997 #elif defined(__FreeBSD__)
4998 if (spawn(cmd, "-f", newpath, NULL, F_NORMAL)) {
5000 if (spawn(cmd, "-quz", newpath, NULL, F_NORMAL)) {
5002 printwait(messages[MSG_FAILED], presel);
5007 if (rmdir(newpath) == -1) {
5015 static void lock_terminal(void)
5017 spawn(xgetenv("NNN_LOCKER", utils[UTIL_LOCKER]), NULL, NULL, NULL, F_CLI);
5020 static void printkv(kv *kvarr, int fd, uchar_t max, uchar_t id)
5022 char *val = (id == NNN_BMS) ? bmstr : pluginstr;
5024 for (uchar_t i = 0; i < max && kvarr[i].key; ++i)
5025 dprintf(fd, " %c: %s\n", (char)kvarr[i].key, val + kvarr[i].off);
5028 static void printkeys(kv *kvarr, char *buf, uchar_t max)
5032 for (; i < max && kvarr[i].key; ++i) {
5034 buf[(i << 1) + 1] = kvarr[i].key;
5040 static size_t handle_bookmark(const char *bmark, char *newpath)
5045 if (maxbm || bmark) {
5046 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
5048 if (bmark) { /* There is a marked directory */
5054 printkeys(bookmark, g_buf + r - 1, maxbm);
5056 fd = get_input(NULL);
5060 if (fd == ',') /* Visit marked directory */
5061 bmark ? xstrsncpy(newpath, bmark, PATH_MAX) : (r = MSG_NOT_SET);
5062 else if (fd == '\r') { /* Visit bookmarks directory */
5063 mkpath(cfgpath, toks[TOK_BM], newpath);
5065 } else if (!get_kv_val(bookmark, newpath, fd, maxbm, NNN_BMS))
5066 r = MSG_INVALID_KEY;
5068 if (!r && chdir(newpath) == -1) {
5077 static void add_bookmark(char *path, char *newpath, int *presel)
5079 char *dir = xbasename(path);
5081 dir = xreadline(dir[0] ? dir : NULL, messages[MSG_BM_NAME]);
5083 size_t r = mkpath(cfgpath, toks[TOK_BM], newpath);
5085 newpath[r - 1] = '/';
5086 xstrsncpy(newpath + r, dir, PATH_MAX - r);
5087 printwait((symlink(path, newpath) == -1) ? strerror(errno) : newpath, presel);
5089 printwait(messages[MSG_CANCEL], presel);
5093 * The help string tokens (each line) start with a HEX value which indicates
5094 * the number of spaces to print before the particular token. In the middle,
5095 * %NN can be used to insert a run of spaces, e.g %10 will print 10 spaces.
5096 * %NN MUST be 2 characters long, e.g %05 for 5 spaces.
5098 * This method was chosen instead of a flat string because the number of bytes
5099 * in help was increasing the binary size by around a hundred bytes. This would
5100 * only have increased as we keep adding new options.
5102 static void show_help(const char *path)
5104 static const char helpstr[] = {
5112 "9Up k Up%16PgUp ^U Page up\n"
5113 "9Dn j Down%14PgDn ^D Page down\n"
5114 "9Lt h Parent%12~ ` @ - ~, /, start, prev\n"
5115 "5Ret Rt l Open%20' First file/match\n"
5116 "9g ^A Top%21J Jump to entry/offset\n"
5117 "9G ^E End%20^J Toggle auto-advance on open\n"
5118 "8B (,) Book(mark)%11b ^/ Select bookmark\n"
5119 "a1-4 Context%11(Sh)Tab Cycle/new context\n"
5120 "62Esc ^Q Quit%19^y Next young\n"
5121 "b^G QuitCD%18Q Pick/err, quit\n"
5124 "1FILTER & PROMPT\n"
5125 "c/ Filter%17^N Toggle type-to-nav\n"
5126 "aEsc Exit prompt%12^L Toggle last filter\n"
5127 "c. Toggle hidden%05Alt+Esc Unfilter, quit context\n"
5130 "9o ^O Open with%15n Create new/link\n"
5131 "9f ^F File stats%14d Detail mode toggle\n"
5132 "b^R Rename/dup%14r Batch rename\n"
5133 "cz Archive%17e Edit file\n"
5134 "c* Toggle exe%14> Export list\n"
5135 "6Space + (Un)select%12m-m Select range/clear\n"
5136 "ca Select all%14A Invert sel\n"
5137 "9p ^P Copy here%12w ^W Cp/mv sel as\n"
5138 "9v ^V Move here%15E Edit sel list\n"
5139 "9x ^X Delete%18S Listed sel size\n"
5140 "aEsc Send to FIFO\n"
5143 "8Alt ; Select plugin%11= Launch app\n"
5144 "9! ^] Shell%19] Cmd prompt\n"
5145 "cc Connect remote%10u Unmount remote/archive\n"
5146 "9t ^T Sort toggles%12s Manage session\n"
5147 "cT Set time type%110 Lock\n"
5148 "b^L Redraw%18? Help, conf\n"
5151 int fd = create_tmp_file();
5155 char *prog = xgetenv(env_cfg[NNN_HELP], NULL);
5157 get_output(prog, NULL, NULL, fd, FALSE);
5161 const char *end = helpstr + (sizeof helpstr - 1);
5162 for (const char *s = helpstr; s < end; ++s) {
5164 for (int k = 0, n = xchartohex(*s); k < n; ++k) *w++ = ' ';
5165 } else if (*s == '%') {
5166 int n = ((s[1] - '0') * 10) + (s[2] - '0');
5167 for (int k = 0; k < n; ++k) *w++ = ' ';
5174 if (write(fd, g_buf, w - g_buf)) {} // silence warning
5176 dprintf(fd, "\nLOCATIONS\n");
5177 for (uchar_t i = 0; i < CTX_MAX; ++i)
5178 if (g_ctx[i].c_cfg.ctxactive)
5179 dprintf(fd, " %u: %s\n", i + 1, g_ctx[i].c_path);
5181 dprintf(fd, "\nVOLUME: avail:%s ", coolsize(get_fs_info(path, VFS_AVAIL)));
5182 dprintf(fd, "used:%s ", coolsize(get_fs_info(path, VFS_USED)));
5183 dprintf(fd, "size:%s\n\n", coolsize(get_fs_info(path, VFS_SIZE)));
5186 dprintf(fd, "BOOKMARKS\n");
5187 printkv(bookmark, fd, maxbm, NNN_BMS);
5192 dprintf(fd, "PLUGIN KEYS\n");
5193 printkv(plug, fd, maxplug, NNN_PLUG);
5197 for (uchar_t i = NNN_OPENER; i <= NNN_TRASH; ++i) {
5198 char *s = getenv(env_cfg[i]);
5200 dprintf(fd, "%s: %s\n", env_cfg[i], s);
5204 dprintf(fd, "SELECTION FILE: %s\n", selpath);
5206 dprintf(fd, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
5209 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
5213 static void setexports(void)
5219 setenv(envs[ENV_NCUR], pdents[cur].name, 1);
5220 xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
5221 } else if (g_ctx[cfg.curctx].c_name[0])
5222 g_ctx[cfg.curctx].c_name[0] = '\0';
5224 for (uchar_t i = 0; i < CTX_MAX; ++i) {
5225 if (g_ctx[i].c_cfg.ctxactive) {
5226 dvar[1] = fvar[1] = '1' + i;
5227 setenv(dvar, g_ctx[i].c_path, 1);
5229 if (g_ctx[i].c_name[0]) {
5230 mkpath(g_ctx[i].c_path, g_ctx[i].c_name, g_buf);
5231 setenv(fvar, g_buf, 1);
5235 setenv("NNN_INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
5236 setenv("NNN_PREFER_SELECTION", xitoa(cfg.prefersel), 1);
5239 static void run_cmd_as_plugin(const char *file, uchar_t flags)
5243 xstrsncpy(g_buf, file, PATH_MAX);
5245 len = xstrlen(g_buf);
5246 if (len > 1 && g_buf[len - 1] == '*') {
5247 flags &= ~F_CONFIRM; /* Skip user confirmation */
5248 g_buf[len - 1] = '\0'; /* Get rid of trailing no confirmation symbol */
5253 get_output(utils[UTIL_SH_EXEC], g_buf, NULL, -1, TRUE);
5255 spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, flags);
5258 static bool plctrl_init(void)
5262 /* g_tmpfpath is used to generate tmp file names */
5263 g_tmpfpath[tmpfplen - 1] = '\0';
5264 len = xstrsncpy(g_pipepath, g_tmpfpath, TMP_LEN_MAX);
5265 g_pipepath[len - 1] = '/';
5266 len = xstrsncpy(g_pipepath + len, "nnn-pipe.", TMP_LEN_MAX - len) + len;
5267 xstrsncpy(g_pipepath + len - 1, xitoa(getpid()), TMP_LEN_MAX - len);
5268 setenv(env_cfg[NNN_PIPE], g_pipepath, TRUE);
5270 return EXIT_SUCCESS;
5273 static void rmlistpath(void)
5276 DPRINTF_S(__func__);
5277 DPRINTF_S(listpath);
5278 spawn(utils[UTIL_RM_RF], listpath, NULL, NULL, F_NOTRACE | F_MULTI);
5279 /* Do not free if program was started in list mode */
5280 if (listpath != initpath)
5286 static ssize_t read_nointr(int fd, void *buf, size_t count)
5291 len = read(fd, buf, count);
5292 while (len == -1 && errno == EINTR);
5297 static char *readpipe(int fd, char *ctxnum, char **path)
5299 char ctx, *nextpath = NULL;
5301 if (read_nointr(fd, g_buf, 1) != 1)
5304 if (g_buf[0] == '-') { /* Clear selection on '-' */
5306 if (read_nointr(fd, g_buf, 1) != 1)
5310 if (g_buf[0] == '+')
5311 ctx = (char)(get_free_ctx() + 1);
5312 else if (g_buf[0] < '0')
5315 ctx = g_buf[0] - '0';
5320 if (read_nointr(fd, g_buf, 1) != 1)
5326 ssize_t len = read_nointr(fd, g_buf, PATH_MAX);
5331 g_buf[len] = '\0'; /* Terminate the path read */
5332 if (g_buf[0] == '/') {
5334 len = xstrlen(g_buf);
5335 while (--len && (g_buf[len] == '/')) /* Trim all trailing '/' */
5338 } else if (op == 'l') {
5339 rmlistpath(); /* Remove last list mode path, if any */
5340 nextpath = load_input(fd, *path);
5341 } else if (op == 'p') {
5354 static bool run_plugin(char **path, const char *file, char *runfile, char **lastname, char **lastdir)
5359 bool cmd_as_plugin = FALSE;
5362 if (!g_state.pluginit) {
5364 g_state.pluginit = 1;
5369 /* Check for run-cmd-as-plugin mode */
5371 flags = F_MULTI | F_CONFIRM;
5374 if (*file == '|') { /* Check if output should be paged */
5377 } else if (*file == '&') { /* Check if GUI flags are to be used */
5378 flags = F_MULTI | F_NOTRACE | F_NOWAIT;
5385 if ((flags & F_NOTRACE) || (flags & F_PAGE)) {
5386 run_cmd_as_plugin(file, flags);
5390 cmd_as_plugin = TRUE;
5393 if (mkfifo(g_pipepath, 0600) != 0)
5400 if (!p) { // In child
5401 int wfd = open(g_pipepath, O_WRONLY | O_CLOEXEC);
5404 _exit(EXIT_FAILURE);
5406 if (!cmd_as_plugin) {
5410 /* Generate absolute path to plugin */
5411 mkpath(plgpath, file, g_buf);
5414 sel = selpath ? selpath : std;
5416 if (runfile && runfile[0]) {
5417 xstrsncpy(*lastname, runfile, NAME_MAX);
5418 spawn(g_buf, *lastname, *path, sel, 0);
5420 spawn(g_buf, NULL, *path, sel, 0);
5422 run_cmd_as_plugin(file, flags);
5425 _exit(EXIT_SUCCESS);
5431 rfd = open(g_pipepath, O_RDONLY);
5432 while (rfd == -1 && errno == EINTR);
5434 nextpath = readpipe(rfd, &ctx, path);
5436 set_smart_ctx(ctx, nextpath, path, runfile, lastname, lastdir);
5440 /* wait for the child to finish. no zombies allowed */
5441 waitpid(p, NULL, 0);
5450 static bool launch_app(char *newpath)
5453 char *tmp = newpath;
5455 mkpath(plgpath, utils[UTIL_LAUNCH], newpath);
5457 if (!getutil(utils[UTIL_FZF]) || access(newpath, X_OK) < 0) {
5458 tmp = xreadline(NULL, messages[MSG_APP_NAME]);
5459 r = F_NOWAIT | F_NOTRACE | F_MULTI;
5462 if (tmp && *tmp) // NOLINT
5463 spawn(tmp, (r == F_NORMAL) ? "0" : NULL, NULL, NULL, r);
5468 /* Returns TRUE if at least one command was run */
5469 static bool prompt_run(void)
5472 char *cmdline, *next;
5473 int cnt_j, cnt_J, cmd_ret;
5476 const char *xargs_j = "xargs -0 -I{} %s < %s";
5477 const char *xargs_J = "xargs -0 %s < %s";
5478 char cmd[CMD_LEN_MAX + 32]; // 32 for xargs format strings
5482 if (g_state.picker) {
5484 cmdline = xreadline(NULL, PROMPT);
5487 cmdline = getreadline("\n"PROMPT);
5489 // Check for an empty command
5490 if (!cmdline || !cmdline[0])
5494 lastcmd = xstrdup(cmdline);
5497 len = xstrlen(cmdline);
5501 while ((next = strstr(next, "%j"))) {
5504 // replace %j with {} for xargs later
5513 while ((next = strstr(next, "%J"))) {
5516 // %J should be the last thing in the command
5517 if (next == cmdline + len - 2) {
5518 cmdline[len - 2] = '\0';
5524 // We can't handle both %j and %J in a single command
5529 snprintf(cmd, CMD_LEN_MAX + 32, xargs_j, cmdline, selpath);
5531 snprintf(cmd, CMD_LEN_MAX + 32, xargs_J, cmdline, selpath);
5533 cmd_ret = spawn(shell, "-c", (cnt_j || cnt_J) ? cmd : cmdline, NULL, F_CLI | F_CONFIRM);
5534 if ((cnt_j || cnt_J) && cmd_ret == 0)
5541 static bool handle_cmd(enum action sel, char *newpath)
5543 endselection(FALSE);
5545 if (sel == SEL_LAUNCH)
5546 return launch_app(newpath);
5550 if (sel == SEL_PROMPT)
5551 return prompt_run();
5553 /* Set nnn nesting level */
5554 char *tmp = getenv(env_cfg[NNNLVL]);
5555 int r = tmp ? atoi(tmp) : 0;
5557 setenv(env_cfg[NNNLVL], xitoa(r + 1), 1);
5558 spawn(shell, NULL, NULL, NULL, F_CLI);
5559 setenv(env_cfg[NNNLVL], xitoa(r), 1);
5563 static void dentfree(void)
5569 /* Thread data cleanup */
5575 static void *du_thread(void *p_data)
5577 thread_data *pdata = (thread_data *)p_data;
5578 char *path[2] = {pdata->path, NULL};
5579 ullong_t tfiles = 0;
5580 blkcnt_t tblocks = 0;
5582 FTS *tree = fts_open(path, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR, 0);
5585 while ((node = fts_read(tree))) {
5586 if (node->fts_info & FTS_D) {
5587 if (g_state.interrupt)
5592 sb = node->fts_statp;
5594 if (cfg.apparentsz) {
5595 if (sb->st_size && DU_TEST)
5596 tblocks += sb->st_size;
5597 } else if (sb->st_blocks && DU_TEST)
5598 tblocks += sb->st_blocks;
5605 if (pdata->entnum >= 0)
5606 pdents[pdata->entnum].blocks = tblocks;
5608 if (!pdata->mntpoint) {
5609 core_blocks[pdata->core] += tblocks;
5610 core_files[pdata->core] += tfiles;
5612 core_files[pdata->core] += 1;
5614 pthread_mutex_lock(&running_mutex);
5615 threadbmp |= (1 << pdata->core);
5617 pthread_mutex_unlock(&running_mutex);
5622 static void dirwalk(char *path, int entnum, bool mountpoint)
5624 /* Loop till any core is free */
5625 while (active_threads == NUM_DU_THREADS);
5627 if (g_state.interrupt)
5630 pthread_mutex_lock(&running_mutex);
5631 int core = ffs(threadbmp) - 1;
5633 threadbmp &= ~(1 << core);
5635 pthread_mutex_unlock(&running_mutex);
5637 xstrsncpy(core_data[core].path, path, PATH_MAX);
5638 core_data[core].entnum = entnum;
5639 core_data[core].core = (ushort_t)core;
5640 core_data[core].mntpoint = mountpoint;
5644 pthread_create(&tid, NULL, du_thread, (void *)&(core_data[core]));
5647 addstr(xbasename(path));
5648 addstr(" [^C aborts]\n");
5652 static bool prep_threads(void)
5654 if (!g_state.duinit) {
5656 threadbmp >>= (32 - NUM_DU_THREADS);
5659 core_blocks = calloc(NUM_DU_THREADS, sizeof(blkcnt_t));
5661 core_data = calloc(NUM_DU_THREADS, sizeof(thread_data));
5663 core_files = calloc(NUM_DU_THREADS, sizeof(ullong_t));
5665 if (!core_blocks || !core_data || !core_files) {
5670 /* Increase current open file descriptor limit */
5673 g_state.duinit = TRUE;
5675 memset(core_blocks, 0, NUM_DU_THREADS * sizeof(blkcnt_t));
5676 memset(core_data, 0, NUM_DU_THREADS * sizeof(thread_data));
5677 memset(core_files, 0, NUM_DU_THREADS * sizeof(ullong_t));
5682 /* Skip self and parent */
5683 static inline bool selforparent(const char *path)
5685 return path[0] == '.' && (path[1] == '\0' || (path[1] == '.' && path[2] == '\0'));
5688 static int dentfill(char *path, struct entry **ppdents)
5690 uchar_t entflags = 0;
5693 char *namep, *pnb, *buf;
5694 struct entry *dentp;
5695 size_t off = 0, namebuflen = NAMEBUF_INCR;
5696 struct stat sb_path, sb;
5697 DIR *dirp = opendir(path);
5700 gtimesecs = time(NULL);
5702 DPRINTF_S(__func__);
5707 int fd = dirfd(dirp);
5714 if (fstatat(fd, path, &sb_path, 0) == -1)
5718 ihashbmp = calloc(1, HASH_OCTETS << 3);
5722 memset(ihashbmp, 0, HASH_OCTETS << 3);
5724 if (!prep_threads())
5727 attron(COLOR_PAIR(cfg.curctx + 1));
5730 #if _POSIX_C_SOURCE >= 200112L
5731 posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
5738 #if defined(__sun) || defined(__HAIKU__)
5739 flags = AT_SYMLINK_NOFOLLOW; /* no d_type */
5741 if (cfg.blkorder || dp->d_type == DT_UNKNOWN) {
5743 * Optimization added for filesystems which support dirent.d_type
5746 * - the symlink size is set to 0
5747 * - the modification time of the symlink is set to that of the target file
5749 flags = AT_SYMLINK_NOFOLLOW;
5756 if (selforparent(namep))
5759 if (!cfg.showhidden && namep[0] == '.') {
5763 if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
5766 if (S_ISDIR(sb.st_mode)) {
5767 if (sb_path.st_dev == sb.st_dev) { // NOLINT
5768 mkpath(path, namep, buf); // NOLINT
5769 dirwalk(buf, -1, FALSE);
5771 if (g_state.interrupt)
5775 /* Do not recount hard links */
5776 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5777 dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5784 if (fstatat(fd, namep, &sb, flags) == -1) {
5785 if (flags || (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)) {
5790 DPRINTF_S(strerror(errno));
5793 entflags = FILE_MISSING;
5794 memset(&sb, 0, sizeof(struct stat));
5795 } else /* Orphaned symlink */
5796 entflags = SYM_ORPHAN;
5799 if (ndents == total_dents) {
5801 while (active_threads);
5803 total_dents += ENTRY_INCR;
5804 *ppdents = xrealloc(*ppdents, total_dents * sizeof(**ppdents));
5810 DPRINTF_P(*ppdents);
5813 /* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
5814 if (namebuflen - off < NAME_MAX + 1) {
5815 namebuflen += NAMEBUF_INCR;
5818 pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
5824 DPRINTF_P(pnamebuf);
5826 /* realloc() may result in memory move, we must re-adjust if that happens */
5827 if (pnb != pnamebuf) {
5829 dentp->name = pnamebuf;
5831 for (int count = 1; count < ndents; ++dentp, ++count)
5832 /* Current file name starts at last file name start + length */
5833 (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
5837 dentp = *ppdents + ndents;
5839 /* Selection file name */
5840 dentp->name = (char *)((size_t)pnamebuf + off);
5841 dentp->nlen = xstrsncpy(dentp->name, namep, NAME_MAX + 1);
5844 /* Copy other fields */
5845 if (cfg.timetype == T_MOD) {
5846 dentp->sec = sb.st_mtime;
5848 dentp->nsec = (uint_t)sb.st_mtimespec.tv_nsec;
5850 dentp->nsec = (uint_t)sb.st_mtim.tv_nsec;
5852 } else if (cfg.timetype == T_ACCESS) {
5853 dentp->sec = sb.st_atime;
5855 dentp->nsec = (uint_t)sb.st_atimespec.tv_nsec;
5857 dentp->nsec = (uint_t)sb.st_atim.tv_nsec;
5860 dentp->sec = sb.st_ctime;
5862 dentp->nsec = (uint_t)sb.st_ctimespec.tv_nsec;
5864 dentp->nsec = (uint_t)sb.st_ctim.tv_nsec;
5868 if ((gtimesecs - sb.st_mtime <= 300) || (gtimesecs - sb.st_ctime <= 300))
5869 entflags |= FILE_YOUNG;
5871 #if !(defined(__sun) || defined(__HAIKU__))
5872 if (!flags && dp->d_type == DT_LNK) {
5873 /* Do not add sizes for links */
5874 dentp->mode = (sb.st_mode & ~S_IFMT) | S_IFLNK;
5875 dentp->size = listpath ? sb.st_size : 0;
5877 dentp->mode = sb.st_mode;
5878 dentp->size = sb.st_size;
5881 dentp->mode = sb.st_mode;
5882 dentp->size = sb.st_size;
5886 dentp->uid = sb.st_uid;
5887 dentp->gid = sb.st_gid;
5890 dentp->flags = S_ISDIR(sb.st_mode) ? 0 : ((sb.st_nlink > 1) ? HARD_LINK : 0);
5892 dentp->flags |= entflags;
5897 if (S_ISDIR(sb.st_mode)) {
5898 mkpath(path, namep, buf); // NOLINT
5900 /* Need to show the disk usage of this dir */
5901 dirwalk(buf, ndents, (sb_path.st_dev != sb.st_dev)); // NOLINT
5903 if (g_state.interrupt)
5906 dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5907 /* Do not recount hard links */
5908 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5909 dir_blocks += dentp->blocks;
5915 /* Flag if this is a dir or symlink to a dir */
5916 if (S_ISLNK(sb.st_mode)) {
5918 fstatat(fd, namep, &sb, 0);
5921 if (S_ISDIR(sb.st_mode))
5922 dentp->flags |= DIR_OR_DIRLNK;
5923 #if !(defined(__sun) || defined(__HAIKU__)) /* no d_type */
5924 } else if (dp->d_type == DT_DIR || ((dp->d_type == DT_LNK
5925 || dp->d_type == DT_UNKNOWN) && S_ISDIR(sb.st_mode))) {
5926 dentp->flags |= DIR_OR_DIRLNK;
5931 } while ((dp = readdir(dirp)));
5934 if (g_state.duinit && cfg.blkorder) {
5935 while (active_threads);
5937 attroff(COLOR_PAIR(cfg.curctx + 1));
5938 for (int i = 0; i < NUM_DU_THREADS; ++i) {
5939 num_files += core_files[i];
5940 dir_blocks += core_blocks[i];
5944 /* Should never be null */
5945 if (closedir(dirp) == -1)
5951 static void populate(char *path, char *lastname)
5954 struct timespec ts1, ts2;
5956 clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
5959 ndents = dentfill(path, &pdents);
5964 ENTSORT(pdents, ndents, entrycmpfn);
5968 clock_gettime(CLOCK_REALTIME, &ts2);
5969 DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
5972 /* Find cur from history */
5973 /* No NULL check for lastname, always points to an array */
5974 move_cursor(*lastname ? dentfind(lastname, ndents) : 0, 0);
5976 // Force full redraw
5977 last_curscroll = -1;
5981 static void notify_fifo(bool force)
5987 fifofd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC);
5990 /* Unexpected error, the FIFO file might have been removed */
5991 /* We give up FIFO notification */
5997 static struct entry lastentry;
5999 if (!force && !memcmp(&lastentry, &pdents[cur], sizeof(struct entry))) // NOLINT
6002 lastentry = pdents[cur];
6004 char path[PATH_MAX];
6005 size_t len = mkpath(g_ctx[cfg.curctx].c_path, ndents ? pdents[cur].name : "", path);
6007 path[len - 1] = '\n';
6009 ssize_t ret = write(fifofd, path, len);
6011 if (ret != (ssize_t)len && !(ret == -1 && (errno == EAGAIN || errno == EPIPE))) {
6012 DPRINTF_S(strerror(errno));
6016 static void send_to_explorer(int *presel)
6019 int fd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0600);
6020 if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
6029 notify_fifo(TRUE); /* Send opened path to NNN_FIFO */
6033 static void move_cursor(int target, int ignore_scrolloff)
6035 int onscreen = xlines - 4; /* Leave top 2 and bottom 2 lines */
6037 target = MAX(0, MIN(ndents - 1, target));
6038 last_curscroll = curscroll;
6042 if (!ignore_scrolloff) {
6043 int delta = target - last;
6044 int scrolloff = MIN(SCROLLOFF, onscreen >> 1);
6047 * When ignore_scrolloff is 1, the cursor can jump into the scrolloff
6048 * margin area, but when ignore_scrolloff is 0, act like a boa
6049 * constrictor and squeeze the cursor towards the middle region of the
6050 * screen by allowing it to move inward and disallowing it to move
6051 * outward (deeper into the scrolloff margin area).
6053 if (((cur < (curscroll + scrolloff)) && delta < 0)
6054 || ((cur > (curscroll + onscreen - scrolloff - 1)) && delta > 0))
6057 curscroll = MIN(curscroll, MIN(cur, ndents - onscreen));
6058 curscroll = MAX(curscroll, MAX(cur - (onscreen - 1), 0));
6061 if (!g_state.fifomode)
6062 notify_fifo(FALSE); /* Send hovered path to NNN_FIFO */
6066 static void handle_screen_move(enum action sel)
6072 if (cfg.rollover || (cur != ndents - 1))
6073 move_cursor((cur + 1) % ndents, 0);
6076 if (cfg.rollover || cur)
6077 move_cursor((cur + ndents - 1) % ndents, 0);
6080 onscreen = xlines - 4;
6081 move_cursor(curscroll + (onscreen - 1), 1);
6082 curscroll += onscreen - 1;
6085 onscreen = xlines - 4;
6086 move_cursor(curscroll + (onscreen - 1), 1);
6087 curscroll += onscreen >> 1;
6090 onscreen = xlines - 4;
6091 move_cursor(curscroll, 1);
6092 curscroll -= onscreen - 1;
6095 onscreen = xlines - 4;
6096 move_cursor(curscroll, 1);
6097 curscroll -= onscreen >> 1;
6101 char *input = xreadline(NULL, "jump (+n/-n/n): ");
6103 if (!input || !*input)
6105 if (input[0] == '-') {
6106 cur -= atoi(input + 1);
6109 } else if (input[0] == '+') {
6110 cur += atoi(input + 1);
6114 int index = atoi(input);
6116 if ((index < 1) || (index > ndents))
6120 onscreen = xlines - 4;
6121 move_cursor(cur, 1);
6122 curscroll -= onscreen >> 1;
6129 move_cursor(ndents - 1, 1);
6133 for (int r = cur;;) {
6138 if (pdents[r].flags & FILE_YOUNG) {
6145 default: /* case SEL_FIRST */
6147 int c = get_input(messages[MSG_FIRST]);
6154 int r = (c == TOUPPER(*pdents[cur].name)) ? (cur + 1) : 0;
6156 for (; r < ndents; ++r) {
6157 if (((c == '\'') && !(pdents[r].flags & DIR_OR_DIRLNK))
6158 || (c == TOUPPER(*pdents[r].name))) {
6159 move_cursor((r) % ndents, 0);
6168 static void handle_openwith(const char *path, const char *name, char *newpath, char *tmp)
6170 /* Confirm if app is CLI or GUI */
6171 int r = get_input(messages[MSG_CLI_MODE]);
6173 r = (r == 'c' ? F_CLI :
6174 ((r == 'g' || r == '\r') ? (F_NOWAIT | F_NOTRACE | F_MULTI) : 0));
6176 mkpath(path, name, newpath);
6177 spawn(tmp, newpath, NULL, NULL, r);
6181 static void copynextname(char *lastname)
6184 cur += (cur != (ndents - 1)) ? 1 : -1;
6190 static int handle_context_switch(enum action sel)
6195 case SEL_CYCLE: // fallthrough
6197 /* visit next and previous contexts */
6199 if (sel == SEL_CYCLE)
6201 r = (r + 1) & ~CTX_MAX;
6202 while (!g_ctx[r].c_cfg.ctxactive);
6204 do /* Attempt to create a new context */
6205 r = (r + 1) & ~CTX_MAX;
6206 while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
6208 if (r == cfg.curctx) /* If all contexts are active, reverse cycle */
6210 r = (r + (CTX_MAX - 1)) & (CTX_MAX - 1);
6211 while (!g_ctx[r].c_cfg.ctxactive);
6213 default: /* SEL_CTXN */
6214 if (sel >= SEL_CTX1) /* CYCLE keys are lesser in value */
6215 r = sel - SEL_CTX1; /* Save the next context id */
6217 if (cfg.curctx == r) {
6218 if (sel == SEL_CYCLE)
6219 (r == CTX_MAX - 1) ? (r = 0) : ++r;
6220 else if (sel == SEL_CYCLER)
6221 (r == 0) ? (r = CTX_MAX - 1) : --r;
6230 static int set_sort_flags(int r)
6232 bool session = (r == '\0');
6233 bool reverse = FALSE;
6235 if (ISUPPER_(r) && (r != 'R') && (r != 'C')) {
6240 /* Set the correct input in case of a session load */
6242 if (cfg.apparentsz) {
6245 } else if (cfg.blkorder) {
6251 namecmpfn = &xstrverscasecmp;
6254 entrycmpfn = &reventrycmp;
6255 } else if (r == CONTROL('T')) {
6256 /* Cycling order: clear -> size -> time -> clear */
6259 else if (cfg.sizeorder)
6266 case 'a': /* Apparent du */
6267 cfg.apparentsz ^= 1;
6268 if (cfg.apparentsz) {
6274 case 'd': /* Disk usage */
6276 if (!cfg.apparentsz)
6279 blk_shift = ffs(S_BLKSIZE) - 1;
6289 entrycmpfn = &entrycmp;
6291 endselection(TRUE); /* We are going to reload dir */
6301 entrycmpfn = &entrycmp;
6302 namecmpfn = &xstricmp;
6304 case 'e': /* File extension */
6311 entrycmpfn = &entrycmp;
6313 case 'r': /* Reverse sort */
6315 entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
6317 case 's': /* File size */
6324 entrycmpfn = &entrycmp;
6326 case 't': /* Time */
6333 entrycmpfn = &entrycmp;
6335 case 'v': /* Version */
6337 namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
6350 entrycmpfn = &reventrycmp;
6353 cfgsort[cfg.curctx] = (uchar_t)r;
6358 static bool set_time_type(int *presel)
6361 char buf[] = "'a'ccess / 'c'hange / 'm'od [ ]";
6363 buf[sizeof(buf) - 3] = cfg.timetype == T_MOD ? 'm' : (cfg.timetype == T_ACCESS ? 'a' : 'c');
6365 int r = get_input(buf);
6367 if (r == 'a' || r == 'c' || r == 'm') {
6368 r = (r == 'm') ? T_MOD : ((r == 'a') ? T_ACCESS : T_CHANGE);
6369 if (cfg.timetype != r) {
6372 if (cfg.filtermode || g_ctx[cfg.curctx].c_fltr[1])
6379 r = MSG_INVALID_KEY;
6382 printwait(messages[r], presel);
6387 static void statusbar(char *path)
6391 pEntry pent = &pdents[cur];
6398 /* Get the file extension for regular files */
6399 if (S_ISREG(pent->mode)) {
6400 i = (int)(pent->nlen - 1);
6401 ptr = xextension(pent->name, i);
6403 len = i - (ptr - pent->name);
6404 if (!ptr || len > 5 || len < 2)
6409 attron(COLOR_PAIR(cfg.curctx + 1));
6411 if (cfg.fileinfo && get_output("file", "-b", pdents[cur].name, -1, FALSE))
6412 mvaddstr(xlines - 2, 2, g_buf);
6416 printw("%d/%s ", cur + 1, xitoa(ndents));
6418 if (g_state.selmode || nselected) {
6421 if (g_state.rangesel)
6423 else if (g_state.selmode)
6426 addstr(xitoa(nselected));
6432 if (cfg.blkorder) { /* du mode */
6435 xstrsncpy(buf, coolsize(dir_blocks << blk_shift), 12);
6437 printw("%cu:%s avail:%s files:%llu %lluB %s\n",
6438 (cfg.apparentsz ? 'a' : 'd'), buf, coolsize(get_fs_info(path, VFS_AVAIL)),
6439 num_files, (ullong_t)pent->blocks << blk_shift, ptr);
6440 } else { /* light or detail mode */
6441 char sort[] = "\0\0\0\0\0";
6443 if (getorderstr(sort))
6447 print_time(&pent->sec, pent->flags);
6450 addstr(get_lsperms(pent->mode));
6453 if (g_state.uidgid) {
6454 addstr(getpwname(pent->uid));
6456 addstr(getgrname(pent->gid));
6460 if (S_ISLNK(pent->mode)) {
6461 if (!cfg.fileinfo) {
6462 i = readlink(pent->name, g_buf, PATH_MAX);
6463 addstr(coolsize(i >= 0 ? i : pent->size)); /* Show symlink size */
6464 if (i > 1) { /* Show symlink target */
6468 getyx(stdscr, len, y);
6469 i = MIN(i, xcols - y);
6475 addstr(coolsize(pent->size));
6478 if (pent->flags & HARD_LINK) {
6481 if (stat(pent->name, &sb) != -1) {
6483 addstr(xitoa((int)sb.st_nlink)); /* Show number of links */
6485 addstr(xitoa((int)sb.st_ino)); /* Show inode number */
6492 attroff(COLOR_PAIR(cfg.curctx + 1));
6493 /* Place HW cursor on current for Braille systems */
6497 static inline void markhovered(void)
6499 if (cfg.showdetail && ndents) { /* Bold forward arrowhead */
6501 addch('>' | A_BOLD);
6505 static int adjust_cols(int n)
6507 /* Calculate the number of cols available to print entry name */
6508 #ifdef ICONS_ENABLED
6509 n -= (g_state.oldcolor ? 0 : ICON_SIZE + ICON_PADDING_LEFT_LEN + ICON_PADDING_RIGHT_LEN);
6511 if (cfg.showdetail) {
6512 /* Fallback to light mode if less than 35 columns */
6514 cfg.showdetail ^= 1;
6515 else /* 2 more accounted for below */
6519 /* 2 columns for preceding space and indicator */
6523 static void draw_line(int ncols)
6527 ncols = adjust_cols(ncols);
6529 if (g_state.oldcolor && (pdents[last].flags & DIR_OR_DIRLNK)) {
6530 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6534 move(2 + last - curscroll, 0);
6536 printent(&pdents[last], ncols, FALSE);
6538 if (g_state.oldcolor && (pdents[cur].flags & DIR_OR_DIRLNK)) {
6539 if (!dir) {/* First file is not a directory */
6540 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6543 } else if (dir) { /* Second file is not a directory */
6544 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6548 move(2 + cur - curscroll, 0);
6550 printent(&pdents[cur], ncols, TRUE);
6552 /* Must reset e.g. no files in dir */
6554 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6559 static void redraw(char *path)
6561 getmaxyx(stdscr, xlines, xcols);
6563 int ncols = (xcols <= PATH_MAX) ? xcols : PATH_MAX;
6564 int onscreen = xlines - 4;
6571 if (ndents && (last_curscroll == curscroll))
6572 return draw_line(ncols);
6575 DPRINTF_S(__func__);
6580 /* Enforce scroll/cursor invariants */
6581 move_cursor(cur, 1);
6583 /* Fail redraw if < than 10 columns, context info prints 10 chars */
6584 if (ncols <= MIN_DISPLAY_COL) {
6585 printmsg(messages[MSG_FEW_COLUMNS]);
6592 for (i = 0; i < CTX_MAX; ++i) { /* 8 chars printed for contexts - "1 2 3 4 " */
6593 if (!g_ctx[i].c_cfg.ctxactive)
6596 addch((i + '1') | (COLOR_PAIR(i + 1) | A_BOLD
6597 /* active: underline, current: reverse */
6598 | ((cfg.curctx != i) ? A_UNDERLINE : A_REVERSE)));
6603 attron(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6606 bool in_home = set_tilde_in_path(path);
6607 char *ptr = in_home ? &path[homelen - 1] : path;
6609 i = (int)xstrlen(ptr);
6610 if ((i + MIN_DISPLAY_COL) <= ncols)
6611 addnstr(ptr, ncols - MIN_DISPLAY_COL);
6613 char *base = xmemrchr((uchar_t *)ptr, '/', i);
6622 if (ptr && (base != ptr)) {
6623 while (ptr < base) {
6625 i += 2; /* 2 characters added */
6626 if (ncols < i + MIN_DISPLAY_COL) {
6627 base = NULL; /* Can't print more characters */
6639 addnstr(base, ncols - (MIN_DISPLAY_COL + i));
6643 reset_tilde_in_path(path);
6645 attroff(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6647 /* Go to first entry */
6648 if (curscroll > 0) {
6650 #ifdef ICONS_ENABLED
6651 addstr(ICON_ARROW_UP);
6657 if (g_state.oldcolor) {
6658 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6659 g_state.dircolor = 1;
6662 onscreen = MIN(onscreen + curscroll, ndents);
6664 ncols = adjust_cols(ncols);
6666 int len = scanselforpath(path, FALSE);
6669 for (i = curscroll; i < onscreen; ++i) {
6673 findmarkentry(len, &pdents[i]);
6675 printent(&pdents[i], ncols, i == cur);
6678 /* Must reset e.g. no files in dir */
6679 if (g_state.dircolor) {
6680 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6681 g_state.dircolor = 0;
6684 /* Go to last entry */
6685 if (onscreen < ndents) {
6686 move(xlines - 2, 0);
6687 #ifdef ICONS_ENABLED
6688 addstr(ICON_ARROW_DOWN);
6697 static bool cdprep(char *lastdir, char *lastname, char *path, char *newpath)
6702 /* Save last working directory */
6703 xstrsncpy(lastdir, path, PATH_MAX);
6705 /* Save the newly opted dir in path */
6706 xstrsncpy(path, newpath, PATH_MAX);
6710 return cfg.filtermode;
6713 static void showselsize(const char *path)
6716 int len = scanselforpath(path, FALSE);
6718 for (int r = 0, selcount = nselected; (r < ndents) && selcount; ++r)
6719 if (findinsel(findselpos, len + xstrsncpy(g_sel + len, pdents[r].name, pdents[r].nlen))) {
6720 sz += cfg.blkorder ? pdents[r].blocks : pdents[r].size;
6724 printmsg(coolsize(cfg.blkorder ? sz << blk_shift : sz));
6727 static bool browse(char *ipath, const char *session, int pkey)
6729 alignas(max_align_t) char newpath[PATH_MAX];
6730 alignas(max_align_t) char runfile[NAME_MAX + 1];
6731 char *path, *lastdir, *lastname, *dir, *tmp;
6735 int r = -1, presel, selstartid = 0, selendid = 0;
6736 const uchar_t opener_flags = (cfg.cliopener ? F_CLI : (F_NOTRACE | F_NOSTDIN | F_NOWAIT));
6737 bool watch = FALSE, cd = TRUE;
6742 struct timespec mousetimings[2] = {{.tv_sec = 0, .tv_nsec = 0}, {.tv_sec = 0, .tv_nsec = 0}};
6743 int mousedent[2] = {-1, -1};
6744 bool currentmouse = 1, rightclicksel = 0;
6749 getmaxyx(stdscr, xlines, xcols);
6752 /* set-up first context */
6753 if (!session || !load_session(session, &path, &lastdir, &lastname, FALSE)) {
6757 g_ctx[0].c_last[0] = '\0';
6758 lastdir = g_ctx[0].c_last; /* last visited directory */
6760 if (g_state.initfile) {
6761 xstrsncpy(g_ctx[0].c_name, xbasename(ipath), sizeof(g_ctx[0].c_name));
6764 g_ctx[0].c_name[0] = '\0';
6766 lastname = g_ctx[0].c_name; /* last visited file name */
6768 xstrsncpy(g_ctx[0].c_path, ipath, PATH_MAX);
6769 /* If the initial path is a file, retain a way to return to start dir */
6770 if (g_state.initfile) {
6772 initpath = ipath = getcwd(NULL, 0);
6774 path = g_ctx[0].c_path; /* current directory */
6776 g_ctx[0].c_fltr[0] = g_ctx[0].c_fltr[1] = '\0';
6777 g_ctx[0].c_cfg = cfg; /* current configuration */
6782 newpath[0] = runfile[0] = '\0';
6784 presel = pkey ? ((pkey == CREATE_NEW_KEY) ? 'n' : ';') : ((cfg.filtermode
6785 || (session && (g_ctx[cfg.curctx].c_fltr[0] == FILTER
6786 || g_ctx[cfg.curctx].c_fltr[0] == RFILTER)
6787 && g_ctx[cfg.curctx].c_fltr[1])) ? FILTER : 0);
6789 pdents = xrealloc(pdents, total_dents * sizeof(struct entry));
6793 /* Allocate buffer to hold names */
6794 pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
6798 /* The following call is added to handle a broken window at start */
6799 if (presel == FILTER)
6800 handle_key_resize();
6804 * Can fail when permissions change while browsing.
6805 * It's assumed that path IS a directory when we are here.
6807 if (chdir(path) == -1) {
6808 DPRINTF_S("directory inaccessible");
6809 valid_parent(path, lastname);
6817 #ifdef LINUX_INOTIFY
6818 if ((presel == FILTER || watch) && inotify_wd >= 0) {
6819 inotify_rm_watch(inotify_fd, inotify_wd);
6823 #elif defined(BSD_KQUEUE)
6824 if ((presel == FILTER || watch) && event_fd >= 0) {
6829 #elif defined(HAIKU_NM)
6830 if ((presel == FILTER || watch) && haiku_hnd != NULL) {
6831 haiku_stop_watch(haiku_hnd);
6832 haiku_nm_active = FALSE;
6838 if (cfgsort[cfg.curctx] != '0') {
6839 if (cfgsort[cfg.curctx] == 'z')
6840 set_sort_flags('c');
6841 if ((!cfgsort[cfg.curctx] || (cfgsort[cfg.curctx] == 'c'))
6842 && ((r = get_kv_key(order, path, maxorder, NNN_ORDER)) > 0)) { // NOLINT
6844 cfgsort[cfg.curctx] = 'z';
6847 cfgsort[cfg.curctx] = cfgsort[CTX_MAX];
6851 populate(path, lastname);
6852 if (g_state.interrupt) {
6853 g_state.interrupt = cfg.apparentsz = cfg.blkorder = 0;
6854 blk_shift = BLK_SHIFT_512;
6855 presel = CONTROL('L');
6858 #ifdef LINUX_INOTIFY
6859 if (presel != FILTER && inotify_wd == -1)
6860 inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
6861 #elif defined(BSD_KQUEUE)
6862 if (presel != FILTER && event_fd == -1) {
6863 #if defined(O_EVTONLY)
6864 event_fd = open(path, O_EVTONLY);
6866 event_fd = open(path, O_RDONLY);
6869 EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
6870 EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
6872 #elif defined(HAIKU_NM)
6873 haiku_nm_active = haiku_watch_dir(haiku_hnd, path) == EXIT_SUCCESS;
6877 /* Do not do a double redraw in filterentries */
6878 if ((presel != FILTER) || !filterset()) {
6884 /* Exit if parent has exited */
6886 _exit(EXIT_FAILURE);
6888 /* If CWD is deleted or moved or perms changed, find an accessible parent */
6889 if (chdir(path) == -1)
6892 /* If STDIN is no longer a tty (closed) we should exit */
6893 if (!isatty(STDIN_FILENO) && !g_state.picker)
6894 return EXIT_FAILURE;
6896 sel = nextsel(presel);
6903 if (getmouse(&event) != OK)
6906 /* Handle clicking on a context at the top */
6907 if (event.bstate == BUTTON1_PRESSED && event.y == 0) {
6908 /* Get context from: "[1 2 3 4]..." */
6911 /* If clicked after contexts, go to parent */
6914 else if (r >= 0 && r != cfg.curctx) {
6915 savecurctx(path, ndents ? pdents[cur].name : NULL, r);
6917 /* Reset the pointers */
6918 path = g_ctx[r].c_path;
6919 lastdir = g_ctx[r].c_last;
6920 lastname = g_ctx[r].c_name;
6930 if (sel == SEL_BACK) {
6932 dir = visit_parent(path, newpath, &presel);
6937 xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
6939 cdprep(lastdir, NULL, path, dir) ? (presel = FILTER) : (watch = TRUE);
6946 /* Middle click action */
6947 if (event.bstate == BUTTON2_PRESSED) {
6948 presel = middle_click_key;
6951 #if NCURSES_MOUSE_VERSION > 1
6953 if (event.bstate == BUTTON4_PRESSED && ndents && (cfg.rollover || cur)) {
6954 move_cursor((!cfg.rollover && cur < scroll_lines
6955 ? 0 : (cur + ndents - scroll_lines) % ndents), 0);
6960 if (event.bstate == BUTTON5_PRESSED && ndents
6961 && (cfg.rollover || (cur != ndents - 1))) {
6962 move_cursor((!cfg.rollover && cur >= ndents - scroll_lines)
6963 ? (ndents - 1) : ((cur + scroll_lines) % ndents), 0);
6968 /* Toggle filter mode on left click on last 2 lines */
6969 if (event.y >= xlines - 2 && event.bstate == BUTTON1_PRESSED) {
6971 cfg.filtermode ^= 1;
6972 if (cfg.filtermode) {
6977 /* Start watching the directory */
6984 /* Handle clicking on a file */
6985 if (event.y >= 2 && event.y <= ndents + 1 &&
6986 (event.bstate == BUTTON1_PRESSED ||
6987 event.bstate == BUTTON3_PRESSED)) {
6988 r = curscroll + (event.y - 2);
6992 else if ((event.bstate == BUTTON1_PRESSED) && !g_state.fifomode)
6993 notify_fifo(TRUE); /* Send clicked path to NNN_FIFO */
6995 /* Handle right click selection */
6996 if (event.bstate == BUTTON3_PRESSED) {
7004 #if defined(CLOCK_MONOTONIC_RAW)
7005 CLOCK_MONOTONIC_RAW,
7006 #elif defined(CLOCK_MONOTONIC)
7011 &mousetimings[currentmouse]);
7012 mousedent[currentmouse] = cur;
7014 /* Single click just selects, double click falls through to SEL_OPEN */
7015 if ((mousedent[0] != mousedent[1]) ||
7016 (((_ABSSUB(mousetimings[0].tv_sec, mousetimings[1].tv_sec) << 30)
7017 + (_ABSSUB(mousetimings[0].tv_nsec, mousetimings[1].tv_nsec)))
7018 > DBLCLK_INTERVAL_NS))
7021 mousetimings[currentmouse].tv_sec = 0;
7022 mousedent[currentmouse] = -1;
7025 if (cfg.filtermode || filterset())
7032 case SEL_NAV_IN: // fallthrough
7034 /* Cannot descend in empty directories */
7037 g_state.selbm = g_state.runplugin = 0;
7041 pent = &pdents[cur];
7042 if (!g_state.selbm || !(S_ISLNK(pent->mode) &&
7043 realpath(pent->name, newpath) &&
7044 xstrsncpy(path, lastdir, PATH_MAX)))
7045 mkpath(path, pent->name, newpath);
7049 /* Visit directory */
7050 if (pent->flags & DIR_OR_DIRLNK) {
7051 if (chdir(newpath) == -1) {
7056 cdprep(lastdir, lastname, path, newpath) ? (presel = FILTER) : (watch = TRUE);
7060 /* Cannot use stale data in entry, file may be missing by now */
7061 if (stat(newpath, &sb) == -1) {
7065 DPRINTF_U(sb.st_mode);
7067 /* Do not open non-regular files */
7068 if (!S_ISREG(sb.st_mode)) {
7069 printwait(messages[MSG_UNSUPPORTED], &presel);
7073 /* Handle plugin selection mode */
7074 if (g_state.runplugin) {
7075 g_state.runplugin = 0;
7076 /* Must be in plugin dir and same context to select plugin */
7077 if ((g_state.runctx == cfg.curctx) && !strcmp(path, plgpath)) {
7078 endselection(FALSE);
7079 /* Copy path so we can return back to earlier dir */
7080 xstrsncpy(path, lastdir, PATH_MAX);
7083 if (chdir(path) == -1
7084 || !run_plugin(&path, pent->name, runfile, &lastname, &lastdir)) {
7085 DPRINTF_S("plugin failed!");
7089 return EXIT_SUCCESS;
7092 xstrsncpy(lastname, runfile, NAME_MAX + 1);
7101 if (g_state.fifomode && (sel == SEL_OPEN)) {
7102 send_to_explorer(&presel); /* Write selection to explorer fifo */
7106 /* If opened as vim plugin and Enter/^M pressed, pick */
7107 if (g_state.picker && (sel == SEL_OPEN)) {
7108 if (nselected == 0) /* Pick if none selected */
7109 appendfpath(newpath, mkpath(path, pent->name, newpath));
7110 return EXIT_SUCCESS;
7113 if (sel == SEL_NAV_IN) {
7114 /* If in listing dir, go to target on `l` or Right on symlink */
7115 if (listpath && S_ISLNK(pent->mode)
7116 && is_prefix(path, listpath, xstrlen(listpath))) {
7117 if (!realpath(pent->name, newpath)) {
7124 if (chdir(newpath) == -1) {
7129 cdprep(lastdir, NULL, path, newpath)
7130 ? (presel = FILTER) : (watch = TRUE);
7131 xstrsncpy(lastname, pent->name, NAME_MAX + 1);
7135 /* Open file disabled on right arrow or `l` */
7141 printwait(messages[MSG_EMPTY_FILE], &presel);
7146 #ifdef FILE_MIME_OPTS
7147 && get_output("file", FILE_MIME_OPTS, newpath, -1, FALSE)
7148 && is_prefix(g_buf, "text/", 5)
7150 /* no MIME option; guess from description instead */
7151 && get_output("file", "-bL", newpath, -1, FALSE)
7152 && strstr(g_buf, "text")
7155 spawn(editor, newpath, NULL, NULL, F_CLI);
7156 if (cfg.filtermode) {
7163 /* Get the extension for regex match */
7164 tmp = xextension(pent->name, pent->nlen - 1);
7166 if (tmp && !pcre_exec(archive_pcre, NULL, tmp,
7167 pent->nlen - (tmp - pent->name) - 1, 0, 0, NULL, 0)) {
7169 if (tmp && !regexec(&archive_re, tmp, 0, NULL, 0)) {
7171 r = get_input(messages[MSG_ARCHIVE_OPTS]);
7174 if (r == 'l' || r == 'x') {
7175 mkpath(path, pent->name, newpath);
7176 if (!handle_archive(newpath, r)) {
7186 if ((r == 'm') && !archive_mount(newpath)) {
7191 if (r == 'x' || r == 'm') {
7193 set_smart_ctx('+', newpath, &path,
7194 ndents ? pdents[cur].name : NULL,
7195 &lastname, &lastdir);
7203 printwait(messages[MSG_INVALID_KEY], &presel);
7208 /* Invoke desktop opener as last resort */
7209 spawn(opener, newpath, NULL, NULL, opener_flags);
7211 /* Move cursor to the next entry if not the last entry */
7212 if (g_state.autonext && cur != ndents - 1)
7213 move_cursor((cur + 1) % ndents, 0);
7214 if (cfg.filtermode) {
7219 case SEL_NEXT: // fallthrough
7220 case SEL_PREV: // fallthrough
7221 case SEL_PGDN: // fallthrough
7222 case SEL_CTRL_D: // fallthrough
7223 case SEL_PGUP: // fallthrough
7224 case SEL_CTRL_U: // fallthrough
7225 case SEL_HOME: // fallthrough
7226 case SEL_END: // fallthrough
7227 case SEL_FIRST: // fallthrough
7228 case SEL_JUMP: // fallthrough
7232 handle_screen_move(sel);
7235 case SEL_CDHOME: // fallthrough
7236 case SEL_CDBEGIN: // fallthrough
7237 case SEL_CDLAST: // fallthrough
7239 dir = (sel == SEL_CDHOME) ? home
7240 : ((sel == SEL_CDBEGIN) ? ipath
7241 : ((sel == SEL_CDLAST) ? lastdir
7242 : "/" /* SEL_CDROOT */));
7244 if (!dir || !*dir) {
7245 printwait(messages[MSG_NOT_SET], &presel);
7250 if (strcmp(path, dir) == 0) {
7256 dir = lastdir; /* Go to last dir on home/root key repeat */
7259 if (chdir(dir) == -1) {
7264 /* SEL_CDLAST: dir pointing to lastdir */
7265 xstrsncpy(newpath, dir, PATH_MAX); // fallthrough
7267 if (sel == SEL_BMOPEN) {
7268 r = (int)handle_bookmark(mark, newpath);
7270 printwait(messages[r], &presel);
7274 if (g_state.selbm == 1) /* Allow filtering in bookmarks directory */
7276 if (strcmp(path, newpath) == 0)
7280 /* In list mode, retain the last file name to highlight it, if possible */
7281 cdprep(lastdir, listpath && sel == SEL_CDLAST ? NULL : lastname, path, newpath)
7282 ? (presel = FILTER) : (watch = TRUE);
7285 if ((sel == SEL_REMOTE) && !remote_mount(newpath)) {
7290 set_smart_ctx('+', newpath, &path,
7291 ndents ? pdents[cur].name : NULL, &lastname, &lastdir);
7294 case SEL_CYCLE: // fallthrough
7295 case SEL_CYCLER: // fallthrough
7296 case SEL_CTX1: // fallthrough
7297 case SEL_CTX2: // fallthrough
7298 case SEL_CTX3: // fallthrough
7306 r = handle_context_switch(sel);
7309 savecurctx(path, ndents ? pdents[cur].name : NULL, r);
7311 /* Reset the pointers */
7312 path = g_ctx[r].c_path;
7313 lastdir = g_ctx[r].c_last;
7314 lastname = g_ctx[r].c_name;
7315 tmp = g_ctx[r].c_fltr;
7317 if (cfg.filtermode || ((tmp[0] == FILTER || tmp[0] == RFILTER) && tmp[1]))
7325 mark = xstrdup(path);
7326 printwait(mark, &presel);
7329 add_bookmark(path, newpath, &presel);
7332 /* Unwatch dir if we are still in a filtered view */
7333 #ifdef LINUX_INOTIFY
7334 if (inotify_wd >= 0) {
7335 inotify_rm_watch(inotify_fd, inotify_wd);
7338 #elif defined(BSD_KQUEUE)
7339 if (event_fd >= 0) {
7343 #elif defined(HAIKU_NM)
7344 if (haiku_nm_active) {
7345 haiku_stop_watch(haiku_hnd);
7346 haiku_nm_active = FALSE;
7349 presel = filterentries(path, lastname);
7350 if (presel == ESC) {
7354 if (presel == FILTER) { /* Refresh dir and filter again */
7359 case SEL_MFLTR: // fallthrough
7360 case SEL_HIDDEN: // fallthrough
7361 case SEL_DETAIL: // fallthrough
7365 cfg.filtermode ^= 1;
7366 if (cfg.filtermode) {
7372 watch = TRUE; // fallthrough
7374 if (sel == SEL_HIDDEN) {
7375 cfg.showhidden ^= 1;
7384 cfg.showdetail ^= 1;
7387 default: /* SEL_SORT */
7388 r = set_sort_flags(get_input(messages[MSG_ORDER]));
7390 printwait(messages[MSG_INVALID_KEY], &presel);
7395 if (cfg.filtermode || filterset())
7401 if (r == 'd' || r == 'a') {
7406 ENTSORT(pdents, ndents, entrycmpfn);
7407 move_cursor(ndents ? dentfind(lastname, ndents) : 0, 0);
7410 case SEL_STATS: // fallthrough
7413 tmp = (listpath && xstrcmp(path, listpath) == 0) ? listroot : path;
7414 mkpath(tmp, pdents[cur].name, newpath);
7416 if ((sel == SEL_STATS && !show_stats(newpath))
7417 || (lstat(newpath, &sb) == -1)
7418 || (sel == SEL_CHMODX && !xchmod(newpath, &sb.st_mode))) {
7423 if (sel == SEL_CHMODX)
7424 pdents[cur].mode = sb.st_mode;
7427 case SEL_REDRAW: // fallthrough
7428 case SEL_RENAMEMUL: // fallthrough
7429 case SEL_HELP: // fallthrough
7430 case SEL_AUTONEXT: // fallthrough
7431 case SEL_EDIT: // fallthrough
7434 bool refresh = FALSE;
7437 mkpath(path, pdents[cur].name, newpath);
7438 else if (sel == SEL_EDIT) /* Avoid trying to edit a non-existing file */
7447 setenv("NNN_INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
7448 setenv("NNN_PREFER_SELECTION", xitoa(cfg.prefersel), 1);
7449 setenv("NNN_LIST", listpath ? listroot : "", 1);
7451 if (!(getutil(utils[UTIL_BASH])
7452 && plugscript(utils[UTIL_NMV], F_CLI))
7457 printwait(messages[MSG_FAILED], &presel);
7464 show_help(path); // fallthrough
7466 if (sel == SEL_AUTONEXT)
7467 g_state.autonext ^= 1;
7473 if (!(g_state.picker || g_state.fifomode))
7474 spawn(editor, newpath, NULL, NULL, F_CLI);
7476 default: /* SEL_LOCK */
7481 /* In case of successful operation, reload contents */
7483 /* Continue in type-to-nav mode, if enabled */
7484 if ((cfg.filtermode || filterset()) && !refresh) {
7491 /* Repopulate as directory content may have changed */
7500 if (g_state.rangesel)
7501 g_state.rangesel = 0;
7503 /* Toggle selection status */
7504 pdents[cur].flags ^= FILE_SELECTED;
7506 if (pdents[cur].flags & FILE_SELECTED) {
7508 appendfpath(newpath, mkpath(path, pdents[cur].name, newpath));
7509 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
7512 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
7517 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7524 /* move cursor to the next entry if this is not the last entry */
7525 if (!g_state.stayonsel && (cur != ndents - 1))
7526 move_cursor((cur + 1) % ndents, 0);
7533 g_state.rangesel ^= 1;
7535 if (stat(path, &sb) == -1) {
7540 if (g_state.rangesel) { /* Range selection started */
7546 if (inode != sb.st_ino) {
7547 printwait(messages[MSG_DIR_CHANGED], &presel);
7551 if (cur < selstartid) {
7552 selendid = selstartid;
7557 /* Clear selection on repeat on same file */
7558 if (selstartid == selendid) {
7563 case SEL_SELALL: // fallthrough
7565 if (sel == SEL_SELALL || sel == SEL_SELINV) {
7570 if (g_state.rangesel)
7571 g_state.rangesel = 0;
7574 selendid = ndents - 1;
7577 if ((nselected > LARGESEL) || (nselected && (ndents > LARGESEL))) {
7578 printmsg("processing...");
7582 r = scanselforpath(path, TRUE); /* Get path length suffixed by '/' */
7583 ((sel == SEL_SELINV) && findselpos)
7584 ? invertselbuf(r) : addtoselbuf(r, selstartid, selendid);
7588 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7592 r = editselection();
7594 r = !r ? MSG_0_SELECTED : MSG_FAILED;
7595 printwait(messages[r], &presel);
7599 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7601 cfg.filtermode ? presel = FILTER : statusbar(path);
7604 case SEL_CP: // fallthrough
7605 case SEL_MV: // fallthrough
7606 case SEL_CPMVAS: // fallthrough
7609 if (sel == SEL_RM) {
7610 r = get_cur_or_sel();
7617 tmp = (listpath && xstrcmp(path, listpath) == 0)
7619 mkpath(tmp, pdents[cur].name, newpath);
7623 xrmfromsel(tmp, newpath);
7625 copynextname(lastname);
7627 if (cfg.filtermode || filterset())
7634 (nselected == 1 && (sel == SEL_CP || sel == SEL_MV))
7635 ? mkpath(path, xbasename(pselbuf), newpath)
7636 : (newpath[0] = '\0');
7640 if (!cpmvrm_selection(sel, path)) {
7650 /* Show notification on operation complete */
7652 plugscript(utils[UTIL_NTFY], F_NOWAIT | F_NOTRACE);
7655 if (newpath[0] && !access(newpath, F_OK))
7656 xstrsncpy(lastname, xbasename(newpath), NAME_MAX+1);
7662 case SEL_ARCHIVE: // fallthrough
7663 case SEL_OPENWITH: // fallthrough
7664 case SEL_NEW: // fallthrough
7670 if (!ndents && (sel == SEL_OPENWITH || sel == SEL_RENAME))
7673 if (sel != SEL_OPENWITH)
7678 r = get_cur_or_sel();
7692 tmp = pdents[cur].name;
7694 tmp = xreadline(tmp, messages[MSG_ARCHIVE_NAME]);
7698 if (g_state.picker) {
7700 tmp = xreadline(NULL, messages[MSG_OPEN_WITH]);
7703 tmp = getreadline(messages[MSG_OPEN_WITH]);
7708 r = get_input(messages[MSG_NEW_OPTS]);
7714 tmp = g_ctx[0].c_name;
7718 if (r == 'f' || r == 'd')
7719 tmp = xreadline(tmp, messages[MSG_NEW_PATH]);
7720 else if (r == 's' || r == 'h')
7721 tmp = xreadline((nselected == 1 && cfg.prefersel) ? xbasename(pselbuf) : NULL,
7722 messages[nselected <= 1 ? MSG_NEW_PATH : MSG_LINK_PREFIX]);
7726 default: /* SEL_RENAME */
7727 tmp = xreadline(pdents[cur].name, "");
7731 if (!tmp || !*tmp || is_bad_len_or_dir(tmp))
7736 if (r == 'c' && strcmp(tmp, pdents[cur].name) == 0)
7737 continue; /* Cannot overwrite the hovered file */
7739 tmp = abspath(tmp, NULL, newpath);
7742 if (access(tmp, F_OK) == 0) {
7743 if (!xconfirm(get_input(messages[MSG_OVERWRITE]))) {
7749 (r == 's') ? archive_selection(get_archive_cmd(tmp), tmp)
7750 : spawn(get_archive_cmd(tmp), tmp, pdents[cur].name,
7751 NULL, F_CLI | F_CONFIRM);
7753 if (tmp && (access(tmp, F_OK) == 0)) { /* File created */
7755 clearselection(); /* Archive operation complete */
7757 /* Check if any entry is created in the current directory */
7758 tmp = get_cwd_entry(path, tmp, &len);
7760 xstrsncpy(lastname, tmp, len + 1);
7761 clearfilter(); /* Archive name may not match */
7762 } if (cfg.filtermode)
7769 handle_openwith(path, pdents[cur].name, newpath, tmp);
7771 cfg.filtermode ? presel = FILTER : statusbar(path);
7776 /* Skip renaming to same name */
7777 if (strcmp(tmp, pdents[cur].name) == 0) {
7778 tmp = xreadline(pdents[cur].name, messages[MSG_COPY_NAME]);
7779 if (!tmp || !tmp[0] || is_bad_len_or_dir(tmp)
7780 || !strcmp(tmp, pdents[cur].name)) {
7781 cfg.filtermode ? presel = FILTER : statusbar(path);
7788 default: /* SEL_NEW */
7792 if (!(r == 's' || r == 'h')) {
7793 tmp = abspath(tmp, NULL, newpath);
7800 /* Check if another file with same name exists */
7801 if (lstat(tmp, &sb) == 0) {
7802 if ((sel == SEL_RENAME) || ((r == 'f') && (S_ISREG(sb.st_mode)))) {
7803 /* Overwrite file with same name? */
7804 if (!xconfirm(get_input(messages[MSG_OVERWRITE])))
7807 /* Do nothing for SEL_NEW if a non-regular entry exists */
7808 printwait(messages[MSG_EXISTS], &presel);
7813 if (sel == SEL_RENAME) {
7814 /* Rename the file */
7816 spawn("cp -rp", pdents[cur].name, tmp, NULL, F_SILENT);
7817 else if (rename(pdents[cur].name, tmp) != 0) {
7822 /* Check if any entry is created in the current directory */
7823 tmp = get_cwd_entry(path, tmp, &len);
7825 xstrsncpy(lastname, tmp, len + 1);
7826 /* Directory must be reloeaded for rename case */
7827 } else { /* SEL_NEW */
7830 /* Check if it's a dir or file */
7831 if (r == 'f' || r == 'd') {
7832 ret = xmktree(tmp, r == 'f' ? FALSE : TRUE);
7833 } else if (r == 's' || r == 'h') {
7834 if (nselected > 1 && tmp[0] == '@' && tmp[1] == '\0')
7836 ret = xlink(tmp, path, (ndents ? pdents[cur].name : NULL), newpath, r);
7845 if (r == 'f' || r == 'd') {
7846 tmp = get_cwd_entry(path, tmp, &len);
7848 xstrsncpy(lastname, tmp, len + 1);
7850 continue; /* No change in directory */
7851 } else if (ndents) {
7863 /* Check if directory is accessible */
7864 if (!xdiraccess(plgpath)) {
7870 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
7871 printkeys(plug, g_buf + r - 1, maxplug);
7873 r = get_input(NULL);
7880 endselection(FALSE);
7881 tmp = get_kv_val(plug, NULL, r, maxplug, NNN_PLUG);
7883 printwait(messages[MSG_INVALID_KEY], &presel);
7887 if (tmp[0] == '-' && tmp[1]) {
7889 r = FALSE; /* Do not refresh dir after completion */
7893 if (!run_plugin(&path, tmp, (ndents ? pdents[cur].name : NULL),
7894 &lastname, &lastdir)) {
7895 printwait(messages[MSG_FAILED], &presel);
7900 return EXIT_SUCCESS;
7905 cfg.filtermode ? presel = FILTER : statusbar(path);
7908 } else { /* 'Return/Enter' enters the plugin directory */
7909 g_state.runplugin ^= 1;
7910 if (!g_state.runplugin) {
7912 * If toggled, and still in the plugin dir,
7913 * switch to original directory
7915 if (strcmp(path, plgpath) == 0) {
7916 xstrsncpy(path, lastdir, PATH_MAX);
7917 xstrsncpy(lastname, runfile, NAME_MAX + 1);
7923 /* Otherwise, initiate choosing plugin again */
7924 g_state.runplugin = 1;
7927 xstrsncpy(lastdir, path, PATH_MAX);
7928 xstrsncpy(path, plgpath, PATH_MAX);
7930 xstrsncpy(runfile, pdents[cur].name, NAME_MAX);
7931 g_state.runctx = cfg.curctx;
7936 if (g_state.runplugin == 1) /* Allow filtering in plugins directory */
7942 case SEL_SHELL: // fallthrough
7943 case SEL_LAUNCH: // fallthrough
7945 r = handle_cmd(sel, newpath);
7947 /* Continue in type-to-nav mode, if enabled */
7957 /* Repopulate as directory content may have changed */
7962 if (!unmount((ndents ? pdents[cur].name : NULL), newpath, &presel, path)) {
7963 if (presel == MSG_ZERO)
7968 /* Dir removed, go to next entry */
7969 copynextname(lastname);
7974 r = get_input(messages[MSG_SSN_OPTS]);
7977 tmp = xreadline(NULL, messages[MSG_SSN_NAME]);
7979 save_session(tmp, &presel);
7980 } else if (r == 'l' || r == 'r') {
7981 if (load_session(NULL, &path, &lastdir, &lastname, r == 'r')) {
7992 cfg.filtermode ? presel = FILTER : statusbar(path);
7995 if (!set_time_type(&presel))
7999 case SEL_QUITCTX: // fallthrough
8000 case SEL_QUITCD: // fallthrough
8003 if (sel == SEL_QUITCTX) {
8004 int ctx = cfg.curctx;
8006 for (r = (ctx - 1) & (CTX_MAX - 1);
8007 (r != ctx) && !g_ctx[r].c_cfg.ctxactive;
8008 r = ((r - 1) & (CTX_MAX - 1))) {
8012 g_ctx[ctx].c_cfg.ctxactive = 0;
8014 /* Switch to next active context */
8015 path = g_ctx[r].c_path;
8016 lastdir = g_ctx[r].c_last;
8017 lastname = g_ctx[r].c_name;
8019 cfg = g_ctx[r].c_cfg;
8025 } else if (!g_state.forcequit) {
8026 for (r = 0; r < CTX_MAX; ++r)
8027 if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
8028 r = get_input(messages[MSG_QUIT_ALL]);
8032 if (!(r == CTX_MAX || xconfirm(r)))
8033 break; // fallthrough
8037 tmp = getenv("NNN_TMPFILE");
8038 if ((sel == SEL_QUITCD) || tmp) {
8039 write_lastdir(path, tmp);
8040 /* ^G is a way to quit picker mode without picking anything */
8041 if ((sel == SEL_QUITCD) && g_state.picker)
8045 if (sel != SEL_QUITERR)
8046 return EXIT_SUCCESS;
8048 if (selbufpos && !g_state.picker) {
8049 /* Pick files to stdout and exit */
8053 return EXIT_SUCCESS;
8056 return EXIT_FAILURE;
8058 if (xlines != LINES || xcols != COLS)
8061 if (idletimeout && idle == idletimeout) {
8062 lock_terminal(); /* Locker */
8068 } /* switch (sel) */
8072 static char *make_tmp_tree(char **paths, ssize_t entries, const char *prefix)
8074 /* tmpdir holds the full path */
8075 /* tmp holds the path without the tmp dir prefix */
8079 ssize_t len = xstrlen(prefix);
8080 char *tmpdir = malloc(PATH_MAX);
8083 DPRINTF_S(strerror(errno));
8087 tmp = tmpdir + tmpfplen - 1;
8088 xstrsncpy(tmpdir, g_tmpfpath, tmpfplen);
8089 xstrsncpy(tmp, "/nnnXXXXXX", 11);
8091 /* Points right after the base tmp dir */
8094 /* handle the case where files are directly under / */
8095 if (!prefix[1] && (prefix[0] == '/'))
8098 if (!mkdtemp(tmpdir)) {
8101 DPRINTF_S(strerror(errno));
8107 for (ssize_t i = 0; i < entries; ++i) {
8111 err = stat(paths[i], &sb);
8112 if (err && errno == ENOENT)
8115 /* Don't copy the common prefix */
8116 xstrsncpy(tmp, paths[i] + len, xstrlen(paths[i]) - len + 1);
8118 /* Get the dir containing the path */
8119 slash = xmemrchr((uchar_t *)tmp, '/', xstrlen(paths[i]) - len);
8123 if (access(tmpdir, F_OK)) /* Create directory if it doesn't exist */
8124 xmktree(tmpdir, TRUE);
8129 if (symlink(paths[i], tmpdir)) {
8130 DPRINTF_S(paths[i]);
8131 DPRINTF_S(strerror(errno));
8135 /* Get the dir in which to start */
8140 static char *load_input(int fd, const char *path)
8142 size_t i, chunk_count = 1, chunk = 512UL * 1024 /* 512 KiB chunk size */, entries = 0;
8143 char *input = malloc(sizeof(char) * chunk), *tmpdir = NULL;
8144 char cwd[PATH_MAX], *next;
8145 size_t offsets[LIST_FILES_MAX];
8146 char **paths = NULL;
8147 ssize_t input_read, total_read = 0, off = 0;
8151 DPRINTF_S(strerror(errno));
8156 if (!getcwd(cwd, PATH_MAX)) {
8161 xstrsncpy(cwd, path, PATH_MAX);
8163 while (chunk_count < LIST_INPUT_MAX / chunk && !msgnum) {
8164 input_read = read(fd, input + total_read, chunk);
8165 if (input_read < 0) {
8169 DPRINTF_S(strerror(errno));
8173 if (input_read == 0)
8176 total_read += input_read;
8178 while (off < total_read) {
8179 next = memchr(input + off, '\0', total_read - off);
8184 if (next - input == off + 1) {
8189 if (entries == LIST_FILES_MAX) {
8190 msgnum = MSG_FILE_LIMIT;
8194 offsets[entries++] = off;
8198 /* We don't need to allocate another chunk */
8199 if (chunk_count > (total_read + chunk - 1) / chunk)
8202 /* We can never need more than one additional chunk */
8204 if (chunk_count > LIST_INPUT_MAX / chunk) {
8205 msgnum = MSG_SIZE_LIMIT;
8209 input = xrealloc(input, chunk_count * chunk);
8214 /* We close fd outside this function. Any extra data is left to the kernel to handle */
8216 if (off != total_read) {
8217 if (entries == LIST_FILES_MAX)
8218 msgnum = MSG_FILE_LIMIT;
8220 offsets[entries++] = off;
8224 DPRINTF_D(total_read);
8225 DPRINTF_D(chunk_count);
8228 msgnum = MSG_0_ENTRIES;
8232 input[total_read] = '\0';
8234 paths = malloc(entries * sizeof(char *));
8238 for (i = 0; i < entries; ++i)
8239 paths[i] = input + offsets[i];
8241 listroot = malloc(sizeof(char) * PATH_MAX);
8246 DPRINTF_S(paths[0]);
8248 for (i = 0; i < entries; ++i) {
8249 if (paths[i][0] == '\n' || selforparent(paths[i])) {
8254 paths[i] = abspath(paths[i], cwd, NULL);
8256 entries = i; // free from the previous entry
8260 DPRINTF_S(paths[i]);
8262 xstrsncpy(g_buf, paths[i], PATH_MAX);
8263 if (!common_prefix(xdirname(g_buf), listroot)) {
8264 entries = i + 1; // free from the current entry
8268 DPRINTF_S(listroot);
8271 DPRINTF_S(listroot);
8274 tmpdir = make_tmp_tree(paths, entries, listroot);
8277 for (i = 0; i < entries; ++i)
8280 if (msgnum) { /* Check if we are past init stage and show msg */
8282 printmsg(messages[msgnum]);
8283 xdelay(XDELAY_INTERVAL_MS << 2);
8285 msg(messages[msgnum]);
8286 usleep(XDELAY_INTERVAL_MS << 2);
8295 static void check_key_collision(void)
8298 bool bitmap[KEY_MAX] = {FALSE};
8300 for (ullong_t i = 0; i < ELEMENTS(bindings); ++i) {
8301 key = bindings[i].sym;
8304 dprintf(STDERR_FILENO, "key collision! [%s]\n", keyname(key));
8310 static void usage(void)
8312 dprintf(STDOUT_FILENO,
8313 "%s: nnn [OPTIONS] [PATH]\n\n"
8314 "The unorthodox terminal file manager.\n\n"
8315 "positional args:\n"
8316 " PATH start dir/file [default: .]\n\n"
8319 " -a auto NNN_FIFO\n"
8321 " -A no dir auto-enter during filter\n"
8322 " -b key open bookmark key (trumps -s/S)\n"
8323 " -B use bsdtar for archives\n"
8324 " -c cli-only NNN_OPENER (trumps -e)\n"
8325 " -C 8-color scheme\n"
8327 " -D dirs in context color\n"
8328 " -e text in $VISUAL/$EDITOR/vi\n"
8329 " -E internal edits in EDITOR\n"
8331 " -f use readline history file\n"
8334 " -F val fifo mode [0:preview 1:explore]\n"
8336 " -g regex filters\n"
8337 " -H show hidden files\n"
8338 " -i show current file info\n"
8339 " -J no auto-advance on selection\n"
8340 " -K detect key collision and exit\n"
8341 " -l val set scroll lines\n"
8342 " -n type-to-nav mode\n"
8343 " -o open files only on Enter\n"
8344 " -p file selection file [-:stdout]\n"
8345 " -P key run plugin key\n"
8346 " -Q no quit confirmation\n"
8347 " -r use advcpmv patched cp, mv\n"
8348 " -R no rollover at edges\n"
8350 " -s name load session by name\n"
8351 " -S persistent session\n"
8353 " -t secs timeout to lock\n"
8354 " -T key sort order [a/d/e/r/s/t/v]\n"
8355 " -u use selection (no prompt)\n"
8357 " -U show user and group\n"
8359 " -V show version\n"
8361 " -x notis, selection sync, xterm title\n"
8364 "v%s\n%s\n", __func__, VERSION, GENERAL_INFO);
8367 static bool setup_config(void)
8370 char *xdgcfg = getenv("XDG_CONFIG_HOME");
8373 /* Set up configuration file paths */
8374 if (xdgcfg && xdgcfg[0]) {
8376 if (tilde_is_home(xdgcfg)) {
8377 r = xstrsncpy(g_buf, home, PATH_MAX);
8378 xstrsncpy(g_buf + r - 1, xdgcfg + 1, PATH_MAX);
8383 if (!xdiraccess(xdgcfg)) {
8388 len = xstrlen(xdgcfg) + xstrlen("/nnn/bookmarks") + 1;
8393 len = xstrlen(home) + xstrlen("/.config/nnn/bookmarks") + 1;
8395 cfgpath = (char *)malloc(len);
8396 plgpath = (char *)malloc(len);
8397 if (!cfgpath || !plgpath) {
8403 xstrsncpy(cfgpath, xdgcfg, len);
8404 r = len - xstrlen("/nnn/bookmarks");
8406 r = xstrsncpy(cfgpath, home, len);
8408 /* Create ~/.config */
8409 xstrsncpy(cfgpath + r - 1, "/.config", len - r);
8411 r += 8; /* length of "/.config" */
8414 /* Create ~/.config/nnn */
8415 xstrsncpy(cfgpath + r - 1, "/nnn", len - r);
8418 /* Create bookmarks, sessions, mounts and plugins directories */
8419 for (r = 0; r < ELEMENTS(toks); ++r) {
8420 mkpath(cfgpath, toks[r], plgpath);
8421 /* The dirs are created on first run, check if they already exist */
8422 if (access(plgpath, F_OK) && !xmktree(plgpath, TRUE)) {
8429 /* Set selection file path */
8430 if (!g_state.picker) {
8431 char *env_sel = xgetenv(env_cfg[NNN_SEL], NULL);
8433 selpath = env_sel ? xstrdup(env_sel)
8434 : (char *)malloc(len + 3); /* Length of "/.config/nnn/.selection" */
8442 r = xstrsncpy(selpath, cfgpath, len + 3);
8443 xstrsncpy(selpath + r - 1, "/.selection", 12);
8451 static bool set_tmp_path(void)
8454 char *path = xdiraccess(tmp) ? tmp : getenv("TMPDIR");
8461 tmpfplen = (uchar_t)xstrsncpy(g_tmpfpath, path, TMP_LEN_MAX);
8462 DPRINTF_S(g_tmpfpath);
8463 DPRINTF_U(tmpfplen);
8468 static void cleanup(void)
8471 if (cfg.x11 && !g_state.picker) {
8472 printf("\033[23;0t"); /* reset terminal window title */
8488 if (g_state.autofifo)
8491 if (g_state.pluginit)
8498 int main(int argc, char *argv[])
8501 char *session = NULL;
8502 int fd, opt, sort = 0, pkey = '\0'; /* Plugin key */
8505 char *middle_click_env = xgetenv(env_cfg[NNN_MCLICK], "\0");
8507 middle_click_key = (middle_click_env[0] == '^' && middle_click_env[1])
8508 ? CONTROL(middle_click_env[1])
8509 : (uchar_t)middle_click_env[0];
8512 const char * const env_opts = xgetenv(env_cfg[NNN_OPTS], NULL);
8513 int env_opts_id = env_opts ? (int)xstrlen(env_opts) : -1;
8515 bool rlhist = FALSE;
8518 while ((opt = (env_opts_id > 0
8519 ? env_opts[--env_opts_id]
8520 : getopt(argc, argv, "aAb:BcCdDeEfF:gHiJKl:nop:P:QrRs:St:T:uUVxh"))) != -1) {
8524 g_state.autofifo = 1;
8531 if (env_opts_id < 0)
8535 g_state.usebsdtar = 1;
8541 g_state.oldcolor = 1;
8562 if (env_opts_id < 0) {
8564 if ((fd < 0) || (fd > 1))
8565 return EXIT_FAILURE;
8566 g_state.fifomode = fd;
8572 filterfn = &visible_re;
8581 g_state.stayonsel = 1;
8584 check_key_collision();
8585 return EXIT_SUCCESS;
8587 if (env_opts_id < 0)
8588 scroll_lines = atoi(optarg);
8597 if (env_opts_id >= 0)
8601 if (!(optarg[0] == '-' && optarg[1] == '\0')) {
8602 fd = open(optarg, O_WRONLY | O_CREAT, 0600);
8605 return EXIT_FAILURE;
8609 selpath = abspath(optarg, NULL, NULL);
8614 if (env_opts_id < 0 && !optarg[1])
8615 pkey = (uchar_t)optarg[0];
8618 g_state.forcequit = 1;
8622 memcpy(cp, PROGRESS_CP, sizeof PROGRESS_CP);
8623 memcpy(mv, PROGRESS_MV, sizeof PROGRESS_MV);
8631 if (env_opts_id < 0)
8635 g_state.prstssn = 1;
8636 if (!session) /* Support named persistent sessions */
8641 if (env_opts_id < 0)
8642 idletimeout = atoi(optarg);
8645 if (env_opts_id < 0)
8646 sort = (uchar_t)optarg[0];
8655 dprintf(STDOUT_FILENO, "%s\n", VERSION);
8656 return EXIT_SUCCESS;
8662 return EXIT_SUCCESS;
8665 return EXIT_FAILURE;
8667 if (env_opts_id == 0)
8676 /* Prefix for temporary files */
8677 if (!set_tmp_path())
8678 return EXIT_FAILURE;
8682 /* Check if we are in path list mode */
8683 if (!isatty(STDIN_FILENO)) {
8684 /* This is the same as listpath */
8685 initpath = load_input(STDIN_FILENO, NULL);
8687 return EXIT_FAILURE;
8689 /* We return to tty */
8690 if (!isatty(STDOUT_FILENO)) {
8691 fd = open(ctermid(NULL), O_RDONLY, 0400);
8692 dup2(fd, STDIN_FILENO);
8695 dup2(STDOUT_FILENO, STDIN_FILENO);
8701 home = getenv("HOME");
8704 return EXIT_FAILURE;
8707 homelen = (uchar_t)xstrlen(home);
8709 if (!setup_config())
8710 return EXIT_FAILURE;
8712 /* Get custom opener, if set */
8713 opener = xgetenv(env_cfg[NNN_OPENER], utils[UTIL_OPENER]);
8716 /* Parse bookmarks string */
8717 if (!parsekvpair(&bookmark, &bmstr, NNN_BMS, &maxbm)) {
8718 msg(env_cfg[NNN_BMS]);
8719 return EXIT_FAILURE;
8722 /* Parse plugins string */
8723 if (!parsekvpair(&plug, &pluginstr, NNN_PLUG, &maxplug)) {
8724 msg(env_cfg[NNN_PLUG]);
8725 return EXIT_FAILURE;
8728 /* Parse order string */
8729 if (!parsekvpair(&order, &orderstr, NNN_ORDER, &maxorder)) {
8730 msg(env_cfg[NNN_ORDER]);
8731 return EXIT_FAILURE;
8735 if (arg) { /* Open a bookmark directly */
8736 if (!arg[1]) /* Bookmarks keys are single char */
8737 initpath = get_kv_val(bookmark, NULL, *arg, maxbm, NNN_BMS);
8740 msg(messages[MSG_INVALID_KEY]);
8741 return EXIT_FAILURE;
8746 } else if (argc == optind) {
8747 /* Start in the current directory */
8748 char *startpath = getenv("PWD");
8750 initpath = (startpath && *startpath) ? xstrdup(startpath) : getcwd(NULL, 0);
8753 } else { /* Open a file */
8756 size_t len = xstrlen(arg);
8758 if (len > 7 && is_prefix(arg, "file://", 7)) {
8762 initpath = abspath(arg, NULL, NULL);
8763 DPRINTF_S(initpath);
8766 return EXIT_FAILURE;
8769 /* If the file is hidden, enable hidden option */
8770 if (*xbasename(initpath) == '.')
8774 * If nnn is set as the file manager, applications may try to open
8775 * files by invoking nnn. In that case pass the file path to the
8776 * desktop opener and exit.
8780 if (stat(initpath, &sb) == -1) {
8781 bool dir = (arg[len - 1] == '/');
8784 arg = xbasename(initpath);
8785 initpath = xdirname(initpath);
8787 pkey = CREATE_NEW_KEY; /* Override plugin key */
8788 g_state.initfile = 1;
8790 if (dir || (arg != initpath)) { /* We have a directory */
8791 if (!xdiraccess(initpath) && !xmktree(initpath, TRUE)) {
8792 xerror(); /* Fail if directory cannot be created */
8793 return EXIT_FAILURE;
8795 if (!dir) /* Restore the complete path */
8798 } else if (!S_ISDIR(sb.st_mode))
8799 g_state.initfile = 1;
8806 /* Set archive handling (enveditor used as tmp var) */
8807 enveditor = getenv(env_cfg[NNN_ARCHIVE]);
8809 if (setfilter(&archive_pcre, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8811 if (setfilter(&archive_re, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8813 msg(messages[MSG_INVALID_REG]);
8814 return EXIT_FAILURE;
8817 /* An all-CLI opener overrides option -e) */
8821 /* Get VISUAL/EDITOR */
8822 enveditor = xgetenv(envs[ENV_EDITOR], utils[UTIL_VI]);
8823 editor = xgetenv(envs[ENV_VISUAL], enveditor);
8824 DPRINTF_S(getenv(envs[ENV_VISUAL]));
8825 DPRINTF_S(getenv(envs[ENV_EDITOR]));
8829 pager = xgetenv(envs[ENV_PAGER], utils[UTIL_LESS]);
8833 shell = xgetenv(envs[ENV_SHELL], utils[UTIL_SH]);
8836 DPRINTF_S(getenv("PWD"));
8840 if (g_state.autofifo) {
8841 g_tmpfpath[tmpfplen - 1] = '\0';
8843 size_t r = mkpath(g_tmpfpath, "nnn-fifo.", g_buf);
8845 xstrsncpy(g_buf + r - 1, xitoa(getpid()), PATH_MAX - r);
8846 setenv("NNN_FIFO", g_buf, TRUE);
8849 fifopath = xgetenv("NNN_FIFO", NULL);
8851 if (mkfifo(fifopath, 0600) != 0 && !(errno == EEXIST && access(fifopath, W_OK) == 0)) {
8853 return EXIT_FAILURE;
8856 sigaction(SIGPIPE, &(struct sigaction){.sa_handler = SIG_IGN}, NULL);
8860 #ifdef LINUX_INOTIFY
8861 /* Initialize inotify */
8862 inotify_fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
8863 if (inotify_fd < 0) {
8865 return EXIT_FAILURE;
8867 #elif defined(BSD_KQUEUE)
8871 return EXIT_FAILURE;
8873 #elif defined(HAIKU_NM)
8874 haiku_hnd = haiku_init_nm();
8877 return EXIT_FAILURE;
8881 /* Configure trash preference */
8882 opt = xgetenv_val(env_cfg[NNN_TRASH]);
8883 if (opt && opt <= 2)
8884 g_state.trash = opt;
8886 /* Ignore/handle certain signals */
8887 struct sigaction act = {.sa_handler = sigint_handler};
8889 if (sigaction(SIGINT, &act, NULL) < 0) {
8891 return EXIT_FAILURE;
8894 act.sa_handler = clean_exit_sighandler;
8896 if (sigaction(SIGTERM, &act, NULL) < 0 || sigaction(SIGHUP, &act, NULL) < 0) {
8898 return EXIT_FAILURE;
8901 act.sa_handler = SIG_IGN;
8903 if (sigaction(SIGQUIT, &act, NULL) < 0) {
8905 return EXIT_FAILURE;
8910 setlocale(LC_ALL, "");
8912 tables = pcre_maketables();
8917 #if RL_READLINE_VERSION >= 0x0603
8918 /* readline would overwrite the WINCH signal hook */
8919 rl_change_environment = 0;
8921 /* Bind TAB to cycling */
8922 rl_variable_bind("completion-ignore-case", "on");
8924 rl_bind_key('\t', rl_menu_complete);
8926 rl_bind_key('\t', rl_complete);
8929 mkpath(cfgpath, ".history", g_buf);
8930 read_history(g_buf);
8935 if (cfg.x11 && !g_state.picker) {
8936 /* Save terminal window title */
8937 printf("\033[22;0t");
8939 gethostname(hostname, sizeof(hostname));
8940 hostname[sizeof(hostname) - 1] = '\0';
8945 if (!initcurses(&mask))
8947 if (!initcurses(NULL))
8949 return EXIT_FAILURE;
8952 set_sort_flags(sort);
8954 opt = browse(initpath, session, pkey);
8957 if (session && g_state.prstssn)
8958 save_session(session, NULL);
8962 mousemask(mask, NULL);
8969 mkpath(cfgpath, ".history", g_buf);
8970 write_history(g_buf);
8974 if (g_state.picker) {
8976 fd = selpath ? open(selpath, O_WRONLY | O_CREAT | O_TRUNC, 0600) : STDOUT_FILENO;
8977 if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
8986 /* Remove tmp dir in list mode */
8989 /* Free the regex */
8991 pcre_free(archive_pcre);
8993 regfree(&archive_re);
8996 /* Free the selection buffer */
8999 #ifdef LINUX_INOTIFY
9000 /* Shutdown inotify */
9001 if (inotify_wd >= 0)
9002 inotify_rm_watch(inotify_fd, inotify_wd);
9004 #elif defined(BSD_KQUEUE)
9008 #elif defined(HAIKU_NM)
9009 haiku_close_nm(haiku_hnd);
9013 if (!g_state.fifomode)