4 * Copyright (C) 2014-2016, Lazaros Koromilas <lostd@2f30.org>
5 * Copyright (C) 2014-2016, Dimitris Papastamos <sin@2f30.org>
6 * Copyright (C) 2016-2023, Arun Prakash Jana <engineerarun@gmail.com>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
12 * * Redistributions of source code must retain the above copyright notice, this
13 * list of conditions and the following disclaimer.
15 * * Redistributions in binary form must reproduce the above copyright notice,
16 * this list of conditions and the following disclaimer in the documentation
17 * and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #define _FILE_OFFSET_BITS 64 /* Support large files on 32-bit glibc */
33 #if defined(__linux__) || defined(MINGW) || defined(__MINGW32__) \
34 || defined(__MINGW64__) || defined(__CYGWIN__)
38 #if defined(__linux__)
39 #include <sys/inotify.h>
42 #if !defined(__GLIBC__)
43 #include <sys/types.h>
46 #include <sys/resource.h>
48 #include <sys/statvfs.h>
49 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
50 #include <sys/types.h>
51 #include <sys/event.h>
54 #elif defined(__HAIKU__)
55 #include "../misc/haiku/haiku_interop.h"
58 #include <sys/sysmacros.h>
62 #ifdef __linux__ /* Fix failure due to mvaddnwstr() */
63 #ifndef NCURSES_WIDECHAR
64 #define NCURSES_WIDECHAR 1
66 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
67 || defined(__APPLE__) || defined(__sun)
68 #ifndef _XOPEN_SOURCE_EXTENDED
69 #define _XOPEN_SOURCE_EXTENDED
72 #ifndef __USE_XOPEN /* Fix wcswidth() failure, ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
87 #include <readline/history.h>
88 #include <readline/readline.h>
103 #include <stdalign.h>
104 #ifndef __USE_XOPEN_EXTENDED
105 #define __USE_XOPEN_EXTENDED 1
111 #ifdef MACOS_BELOW_1012
112 #include "../misc/macos-legacy/mach_gettime.h"
115 #if !defined(alloca) && defined(__GNUC__)
117 * GCC doesn't expand alloca() to __builtin_alloca() in standards mode
118 * (-std=...) and not all standard libraries do or supply it, e.g.
119 * NetBSD/arm64 so explicitly use the builtin.
121 #define alloca(size) __builtin_alloca(size)
127 #if defined(ICONS_IN_TERM) || defined(NERD) || defined(EMOJI)
128 #define ICONS_ENABLED
129 #include ICONS_INCLUDE
130 #include "icons-hash.c"
134 #if defined(ICONS_ENABLED) && defined(__APPLE__)
136 * For some reason, wcswidth returns 2 for certain icons on macOS
137 * leading to duplicated first characters in filenames when navigating.
138 * https://github.com/jarun/nnn/issues/1692
139 * There might be a better way to fix it without requiring a refresh.
141 #define macos_icons_hack() do { clrtoeol(); refresh(); } while(0)
143 #define macos_icons_hack()
150 /* Macro definitions */
151 #define VERSION "4.9"
152 #define GENERAL_INFO "BSD 2-Clause\nhttps://github.com/jarun/nnn"
155 #define SESSIONS_VERSION 1
159 #define S_BLKSIZE 512 /* S_BLKSIZE is missing on Android NDK (Termux) */
163 * NAME_MAX and PATH_MAX may not exist, e.g. with dirent.c_name being a
164 * flexible array on Illumos. Use somewhat accommodating fallback values.
171 #define PATH_MAX 4096
174 #define _ABSSUB(N, M) (((N) <= (M)) ? ((M) - (N)) : ((N) - (M)))
175 #define ELEMENTS(x) (sizeof(x) / sizeof(*(x)))
177 #define MIN(x, y) ((x) < (y) ? (x) : (y))
179 #define MAX(x, y) ((x) > (y) ? (x) : (y))
180 #define ISODD(x) ((x) & 1)
181 #define ISBLANK(x) ((x) == ' ' || (x) == '\t')
182 #define TOUPPER(ch) (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
183 #define TOLOWER(ch) (((ch) >= 'A' && (ch) <= 'Z') ? ((ch) - 'A' + 'a') : (ch))
184 #define ISUPPER_(ch) ((ch) >= 'A' && (ch) <= 'Z')
185 #define ISLOWER_(ch) ((ch) >= 'a' && (ch) <= 'z')
186 #define CMD_LEN_MAX (PATH_MAX + ((NAME_MAX + 1) << 1))
187 #define ALIGN_UP(x, A) ((((x) + (A) - 1) / (A)) * (A))
188 #define READLINE_MAX 256
194 #define PROMPT ">>> "
196 #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
197 #define NAMEBUF_INCR 0x800 /* 64 dir entries at once, avg. 32 chars per file name = 64*32B = 2KB */
198 #define DESCRIPTOR_LEN 32
199 #define _ALIGNMENT 0x10 /* 16-byte alignment */
200 #define _ALIGNMENT_MASK 0xF
201 #define TMP_LEN_MAX 64
202 #define DOT_FILTER_LEN 7
203 #define ASCII_MAX 128
204 #define EXEC_ARGS_MAX 10
205 #define LIST_FILES_MAX (1 << 14) /* Support listing 16K files */
206 #define LIST_INPUT_MAX ((size_t)LIST_FILES_MAX * PATH_MAX)
208 #define COLOR_256 256
209 #define CREATE_NEW_KEY (-1)
212 #define DBLCLK_INTERVAL_NS (400000000)
213 #define XDELAY_INTERVAL_MS (350000) /* 350 ms delay */
222 /* BSDs or Solaris or SunOS */
223 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) || defined(sun) || defined(__sun)
230 /* Large selection threshold */
232 #define LARGESEL 1000
235 #define MIN_DISPLAY_COL (CTX_MAX * 2)
236 #define ARCHIVE_CMD_LEN 16
237 #define BLK_SHIFT_512 9
239 /* Detect hardlinks in du */
240 #define HASH_BITS (0xFFFFFF)
241 #define HASH_OCTETS (HASH_BITS >> 6) /* 2^6 = 64 */
244 #define DIR_OR_DIRLNK 0x01
245 #define HARD_LINK 0x02
246 #define SYM_ORPHAN 0x04
247 #define FILE_MISSING 0x08
248 #define FILE_SELECTED 0x10
249 #define FILE_SCANNED 0x20
250 #define FILE_YOUNG 0x40
252 /* Macros to define process spawn behaviour as flags */
253 #define F_NONE 0x00 /* no flag set */
254 #define F_MULTI 0x01 /* first arg can be combination of args; to be used with F_NORMAL */
255 #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
256 #define F_NOTRACE 0x04 /* suppress stdout and stderr (no traces) */
257 #define F_NORMAL 0x08 /* spawn child process in non-curses regular CLI mode */
258 #define F_CONFIRM 0x10 /* run command - show results before exit (must have F_NORMAL) */
259 #define F_CHKRTN 0x20 /* wait for user prompt if cmd returns failure status */
260 #define F_NOSTDIN 0x40 /* suppress stdin */
261 #define F_PAGE 0x80 /* page output in run-cmd-as-plugin mode */
262 #define F_TTY 0x100 /* Force stdout to go to tty if redirected to a non-tty */
263 #define F_CLI (F_NORMAL | F_MULTI)
264 #define F_SILENT (F_CLI | F_NOTRACE)
266 /* Version compare macros */
268 * states: S_N: normal, S_I: comparing integral part, S_F: comparing
269 * fractional parts, S_Z: idem but with leading Zeroes only
276 /* result_type: VCMP: return diff; VLEN: compare using len_diff/diff */
285 /* TYPE DEFINITIONS */
286 typedef unsigned int uint_t;
287 typedef unsigned char uchar_t;
288 typedef unsigned short ushort_t;
289 typedef unsigned long long ullong_t;
293 /* Directory entry */
294 typedef struct entry {
295 char *name; /* 8 bytes */
296 time_t sec; /* 8 bytes */
297 uint_t nsec; /* 4 bytes (enough to store nanosec) */
298 mode_t mode; /* 4 bytes */
299 off_t size; /* 8 bytes */
301 ullong_t blocks : 40; /* 5 bytes (enough for 512 TiB in 512B blocks allocated) */
302 ullong_t nlen : 16; /* 2 bytes (length of file name) */
303 ullong_t flags : 8; /* 1 byte (flags specific to the file) */
306 uid_t uid; /* 4 bytes */
307 gid_t gid; /* 4 bytes */
311 /* Selection marker */
317 /* Key-value pairs from env */
327 const regex_t *regex;
336 uint_t filtermode : 1; /* Set to enter filter mode */
337 uint_t timeorder : 1; /* Set to sort by time */
338 uint_t sizeorder : 1; /* Set to sort by file size */
339 uint_t apparentsz : 1; /* Set to sort by apparent size (disk usage) */
340 uint_t blkorder : 1; /* Set to sort by blocks used (disk usage) */
341 uint_t extnorder : 1; /* Order by extension */
342 uint_t showhidden : 1; /* Set to show hidden files */
343 uint_t reserved0 : 1;
344 uint_t showdetail : 1; /* Clear to show lesser file info */
345 uint_t ctxactive : 1; /* Context active or not */
346 uint_t reverse : 1; /* Reverse sort */
347 uint_t version : 1; /* Version sort */
348 uint_t reserved1 : 1;
349 /* The following settings are global */
350 uint_t curctx : 3; /* Current context number */
351 uint_t prefersel : 1; /* Prefer selection over current, if exists */
352 uint_t fileinfo : 1; /* Show file information on hover */
353 uint_t nonavopen : 1; /* Open file on right arrow or `l` */
354 uint_t autoenter : 1; /* auto-enter dir in type-to-nav mode */
355 uint_t reserved2 : 1;
356 uint_t useeditor : 1; /* Use VISUAL to open text files */
357 uint_t reserved3 : 3;
358 uint_t regex : 1; /* Use regex filters */
359 uint_t x11 : 1; /* Copy to system clipboard, show notis, xterm title */
360 uint_t timetype : 2; /* Time sort type (0: access, 1: change, 2: modification) */
361 uint_t cliopener : 1; /* All-CLI app opener */
362 uint_t waitedit : 1; /* For ops that can't be detached, used EDITOR */
363 uint_t rollover : 1; /* Roll over at edges */
366 /* Non-persistent program-internal states (alphabeical order) */
368 uint_t autofifo : 1; /* Auto-create NNN_FIFO */
369 uint_t autonext : 1; /* Auto-advance on file open */
370 uint_t dircolor : 1; /* Current status of dir color */
371 uint_t dirctx : 1; /* Show dirs in context color */
372 uint_t duinit : 1; /* Initialize disk usage */
373 uint_t fifomode : 1; /* FIFO notify mode: 0: preview, 1: explorer */
374 uint_t forcequit : 1; /* Do not prompt on quit */
375 uint_t initfile : 1; /* Positional arg is a file */
376 uint_t interrupt : 1; /* Program received an interrupt */
377 uint_t move : 1; /* Move operation */
378 uint_t oldcolor : 1; /* Use older colorscheme */
379 uint_t picked : 1; /* Plugin has picked files */
380 uint_t picker : 1; /* Write selection to user-specified file */
381 uint_t pluginit : 1; /* Plugin framework initialized */
382 uint_t prstssn : 1; /* Persistent session */
383 uint_t rangesel : 1; /* Range selection on */
384 uint_t runctx : 3; /* The context in which plugin is to be run */
385 uint_t runplugin : 1; /* Choose plugin mode */
386 uint_t selbm : 1; /* Select a bookmark from bookmarks directory */
387 uint_t selmode : 1; /* Set when selecting files */
388 uint_t stayonsel : 1; /* Disable auto-advance on selection */
389 uint_t trash : 2; /* Trash method 0: rm -rf, 1: trash-cli, 2: gio trash */
390 uint_t uidgid : 1; /* Show owner and group info */
391 uint_t usebsdtar : 1; /* Use bsdtar as default archive utility */
392 uint_t xprompt : 1; /* Use native prompt instead of readline prompt */
393 uint_t reserved : 4; /* Adjust when adding/removing a field */
396 /* Contexts or workspaces */
398 char c_path[PATH_MAX]; /* Current dir */
399 char c_last[PATH_MAX]; /* Last visited dir */
400 char c_name[NAME_MAX + 1]; /* Current file name */
401 char c_fltr[REGEX_MAX]; /* Current filter */
402 settings c_cfg; /* Current configuration */
403 uint_t color; /* Color code for directories */
409 size_t pathln[CTX_MAX];
410 size_t lastln[CTX_MAX];
411 size_t nameln[CTX_MAX];
412 size_t fltrln[CTX_MAX];
418 /* Configuration, contexts */
419 static settings cfg = {
422 .timetype = 2, /* T_MOD */
426 alignas(max_align_t) static context g_ctx[CTX_MAX];
428 static int ndents, cur, last, curscroll, last_curscroll, total_dents = ENTRY_INCR, scroll_lines = 1;
429 static int nselected;
431 static int fifofd = -1;
433 static time_t gtimesecs;
434 static uint_t idletimeout, selbufpos, selbuflen;
435 static ushort_t xlines, xcols;
436 static ushort_t idle;
437 static uchar_t maxbm, maxplug, maxorder;
438 static uchar_t cfgsort[CTX_MAX + 1];
440 static char *pluginstr;
441 static char *orderstr;
444 static char *enveditor;
448 static char *initpath;
449 static char *cfgpath;
450 static char *selpath;
451 static char *listpath;
452 static char *listroot;
453 static char *plgpath;
454 static char *pnamebuf, *pselbuf, *findselpos;
457 static char hostname[_POSIX_HOST_NAME_MAX + 1];
460 static char *fifopath;
462 static char *lastcmd;
463 static ullong_t *ihashbmp;
464 static struct entry *pdents;
465 static blkcnt_t dir_blocks;
469 static uchar_t tmpfplen, homelen;
470 static uchar_t blk_shift = BLK_SHIFT_512;
472 static int middle_click_key;
475 static pcre *archive_pcre;
477 static regex_t archive_re;
480 /* pthread related */
481 #define NUM_DU_THREADS (4) /* Can use sysconf(_SC_NPROCESSORS_ONLN) */
482 #define DU_TEST (((node->fts_info & FTS_F) && \
483 (sb->st_nlink <= 1 || test_set_bit((uint_t)sb->st_ino))) || node->fts_info & FTS_DP)
485 static int threadbmp = -1; /* Has 1 in the bit position for idle threads */
486 static volatile int active_threads;
487 static pthread_mutex_t running_mutex = PTHREAD_MUTEX_INITIALIZER;
488 static pthread_mutex_t hardlink_mutex = PTHREAD_MUTEX_INITIALIZER;
489 static ullong_t *core_files;
490 static blkcnt_t *core_blocks;
491 static ullong_t num_files;
500 static thread_data *core_data;
502 /* Retain old signal handlers */
503 static struct sigaction oldsighup;
504 static struct sigaction oldsigtstp;
505 static struct sigaction oldsigwinch;
507 /* For use in functions which are isolated and don't return the buffer */
508 alignas(max_align_t) static char g_buf[CMD_LEN_MAX];
510 /* For use as a scratch buffer in selection manipulation */
511 alignas(max_align_t) static char g_sel[PATH_MAX];
513 /* Buffer to store tmp file path to show selection, file stats and help */
514 alignas(max_align_t) static char g_tmpfpath[TMP_LEN_MAX];
516 /* Buffer to store plugins control pipe location */
517 alignas(max_align_t) static char g_pipepath[TMP_LEN_MAX];
519 /* Non-persistent runtime states */
520 static runstate g_state;
522 /* Options to identify file MIME */
523 #if defined(__APPLE__)
524 #define FILE_MIME_OPTS "-bIL"
525 #elif !defined(__sun) /* no MIME option for 'file' */
526 #define FILE_MIME_OPTS "-biL"
529 /* Macros for utilities */
530 #define UTIL_OPENER 0
532 #define UTIL_BSDTAR 2
535 #define UTIL_LOCKER 5
536 #define UTIL_LAUNCH 6
537 #define UTIL_SH_EXEC 7
540 #define UTIL_RCLONE 10
548 #define UTIL_TRASH_CLI 18
549 #define UTIL_GIO_TRASH 19
550 #define UTIL_RM_RF 20
551 #define UTIL_ARCHMNT 21
553 /* Utilities to open files, run actions */
554 static char * const utils[] = {
557 #elif defined __CYGWIN__
559 #elif defined __HAIKU__
570 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
572 #elif defined __HAIKU__
596 #define MSG_ZERO 0 /* Unused */
597 #define MSG_0_ENTRIES 1
598 #define STR_TMPFILE 2
599 #define MSG_0_SELECTED 3
602 #define MSG_SSN_NAME 6
603 #define MSG_CP_MV_AS 7
604 #define MSG_CUR_SEL_OPTS 8
605 #define MSG_FORCE_RM 9
606 #define MSG_SIZE_LIMIT 10
607 #define MSG_NEW_OPTS 11
608 #define MSG_CLI_MODE 12
609 #define MSG_OVERWRITE 13
610 #define MSG_SSN_OPTS 14
611 #define MSG_QUIT_ALL 15
612 #define MSG_HOSTNAME 16
613 #define MSG_ARCHIVE_NAME 17
614 #define MSG_OPEN_WITH 18
615 #define MSG_NEW_PATH 19
616 #define MSG_LINK_PREFIX 20
617 #define MSG_COPY_NAME 21
619 #define MSG_SEL_MISSING 23
620 #define MSG_ACCESS 24
621 #define MSG_EMPTY_FILE 25
622 #define MSG_UNSUPPORTED 26
623 #define MSG_NOT_SET 27
624 #define MSG_EXISTS 28
625 #define MSG_FEW_COLUMNS 29
626 #define MSG_REMOTE_OPTS 30
627 #define MSG_RCLONE_DELAY 31
628 #define MSG_APP_NAME 32
629 #define MSG_ARCHIVE_OPTS 33
631 #define MSG_INVALID_REG 35
635 #define MSG_RM_TMP 39
636 #define MSG_INVALID_KEY 40
637 #define MSG_NOCHANGE 41
638 #define MSG_DIR_CHANGED 42
639 #define MSG_BM_NAME 43
640 #define MSG_FILE_LIMIT 44
642 static const char * const messages[] = {
652 "%s %s? [Esc cancels]",
653 "size limit exceeded",
654 "['f'ile]/'d'ir/'s'ym/'h'ard?",
657 "'s'ave/'l'oad/'r'estore?",
658 "Quit all contexts?",
659 "remote name (- for hovered): ",
660 "archive [path/]name: ",
663 "link prefix [@ for none]: ",
664 "copy [path/]name: ",
665 "\n'Enter' to continue",
668 "empty! edit/open with",
676 "['l's]/'o'pen/e'x'tract/'m'nt?",
679 "'a'u/'d'u/'e'xt/'r'ev/'s'z/'t'm/'v'er/'c'lr/'^T'?",
680 "unmount failed! try lazy?",
681 "first file (\')/char?",
685 "dir changed, range sel off",
687 "file limit exceeded",
690 /* Supported configuration environment variables */
696 #define NNN_FCOLORS 5
701 #define NNN_ARCHIVE 10
703 #define NNN_HELP 12 /* strings end here */
704 #define NNN_TRASH 13 /* flags begin here */
706 static const char * const env_cfg[] = {
723 /* Required environment variables */
730 static const char * const envs[] = {
743 #define PROGRESS_CP "cpg -giRp"
744 #define PROGRESS_MV "mvg -gi"
745 static char cp[sizeof PROGRESS_CP] = "cp -iRp";
746 static char mv[sizeof PROGRESS_MV] = "mv -i";
748 /* Archive commands */
749 static char * const archive_cmd[] = {"atool -a", "bsdtar -acvf", "zip -r", "tar -acvf"};
751 /* Tokens used for path creation */
757 static const char * const toks[] = {
761 "plugins", /* must be the last entry */
769 #define P_ARCHIVE_CMD 4
771 static const char * const patterns[] = {
772 SED" -i 's|^\\(\\(.*/\\)\\(.*\\)$\\)|#\\1\\n\\3|' %s",
773 SED" 's|^\\([^#/][^/]\\?.*\\)$|%s/\\1|;s|^#\\(/.*\\)$|\\1|' "
774 "%s | tr '\\n' '\\0' | xargs -0 -n2 sh -c '%s \"$0\" \"$@\" < /dev/tty'",
775 "\\.(bz|bz2|gz|tar|taz|tbz|tbz2|tgz|z|zip)$", /* Basic formats that don't need external tools */
776 SED" -i 's|^%s\\(.*\\)$|%s\\1|' %s",
777 "xargs -0 %s %s < '%s'",
781 #define C_BLK (CTX_MAX + 1) /* Block device: DarkSeaGreen1 */
782 #define C_CHR (C_BLK + 1) /* Character device: Yellow1 */
783 #define C_DIR (C_CHR + 1) /* Directory: DeepSkyBlue1 */
784 #define C_EXE (C_DIR + 1) /* Executable file: Green1 */
785 #define C_FIL (C_EXE + 1) /* Regular file: Normal */
786 #define C_HRD (C_FIL + 1) /* Hard link: Plum4 */
787 #define C_LNK (C_HRD + 1) /* Symbolic link: Cyan1 */
788 #define C_MIS (C_LNK + 1) /* Missing file OR file details: Grey62 */
789 #define C_ORP (C_MIS + 1) /* Orphaned symlink: DeepPink1 */
790 #define C_PIP (C_ORP + 1) /* Named pipe (FIFO): Orange1 */
791 #define C_SOC (C_PIP + 1) /* Socket: MediumOrchid1 */
792 #define C_UND (C_SOC + 1) /* Unknown OR 0B regular/exe file: Red1 */
794 static char gcolors[] = "c1e2272e006033f7c6d6abc4";
795 static uint_t fcolors[C_UND + 1] = {0};
799 #define NUM_EVENT_SLOTS 32 /* Make room for 32 events */
800 #define EVENT_SIZE (sizeof(struct inotify_event))
801 #define EVENT_BUF_LEN (EVENT_SIZE * NUM_EVENT_SLOTS)
802 static int inotify_fd, inotify_wd = -1;
803 static uint_t INOTIFY_MASK = /* IN_ATTRIB | */ IN_CREATE | IN_DELETE | IN_DELETE_SELF
804 | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
805 #elif defined(BSD_KQUEUE)
806 #define NUM_EVENT_SLOTS 1
807 #define NUM_EVENT_FDS 1
808 static int kq, event_fd = -1;
809 static struct kevent events_to_monitor[NUM_EVENT_FDS];
810 static uint_t KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK
811 | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
812 static struct timespec gtimeout;
813 #elif defined(HAIKU_NM)
814 static bool haiku_nm_active = FALSE;
815 static haiku_nm_h haiku_hnd;
818 /* Function macros */
819 #define tolastln() move(xlines - 1, 0)
820 #define tocursor() move(cur + 2 - curscroll, 0)
821 #define exitcurses() endwin()
822 #define printwarn(presel) printwait(strerror(errno), presel)
823 #define istopdir(path) ((path)[1] == '\0' && (path)[0] == '/')
824 #define copycurname() xstrsncpy(lastname, ndents ? pdents[cur].name : "\0", NAME_MAX + 1)
825 #define settimeout() timeout(1000)
826 #define cleartimeout() timeout(-1)
827 #define errexit() printerr(__LINE__)
828 #define setdirwatch() (cfg.filtermode ? (presel = FILTER) : (watch = TRUE))
829 #define filterset() (g_ctx[cfg.curctx].c_fltr[1])
830 /* We don't care about the return value from strcmp() */
831 #define xstrcmp(a, b) (*(a) != *(b) ? -1 : strcmp((a), (b)))
832 /* A faster version of xisdigit */
833 #define xisdigit(c) ((unsigned int) (c) - '0' <= 9)
834 #define xerror() perror(xitoa(__LINE__))
837 #define ENTLESS(i, j) (entrycmpfn(pdents + (i), pdents + (j)) < 0)
838 #define ENTSWAP(i, j) (swap_ent((i), (j)))
839 #define ENTSORT(pdents, ndents, entrycmpfn) QSORT((ndents), ENTLESS, ENTSWAP)
841 #define ENTSORT(pdents, ndents, entrycmpfn) qsort((pdents), (ndents), sizeof(*(pdents)), (entrycmpfn))
844 /* Forward declarations */
845 static void redraw(char *path);
846 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag);
847 static void move_cursor(int target, int ignore_scrolloff);
848 static char *load_input(int fd, const char *path);
849 static int set_sort_flags(int r);
850 static void statusbar(char *path);
851 static bool get_output(char *file, char *arg1, char *arg2, int fdout, bool page);
853 static void notify_fifo(bool force);
858 static void sigint_handler(int sig)
861 g_state.interrupt = 1;
864 static void clean_exit_sighandler(int sig)
868 /* This triggers cleanup() thanks to atexit() */
872 static char *xitoa(uint_t val)
874 static char dst[32] = {'\0'};
875 static const char digits[201] =
876 "0001020304050607080910111213141516171819"
877 "2021222324252627282930313233343536373839"
878 "4041424344454647484950515253545556575859"
879 "6061626364656667686970717273747576777879"
880 "8081828384858687888990919293949596979899";
881 uint_t next = 30, quo, i;
885 i = (val - (quo * 100)) * 2;
887 dst[next] = digits[i + 1];
888 dst[--next] = digits[i];
892 /* Handle last 1-2 digits */
894 dst[next] = '0' + val;
897 dst[next] = digits[i + 1];
898 dst[--next] = digits[i];
904 /* Return the integer value of a char representing HEX */
905 static uchar_t xchartohex(uchar_t c)
910 if (c >= 'a' && c <= 'f')
913 if (c >= 'A' && c <= 'F')
920 * Source: https://elixir.bootlin.com/linux/latest/source/arch/alpha/include/asm/bitops.h
922 static bool test_set_bit(uint_t nr)
926 pthread_mutex_lock(&hardlink_mutex);
927 ullong_t *m = ((ullong_t *)ihashbmp) + (nr >> 6);
929 if (*m & (1 << (nr & 63))) {
930 pthread_mutex_unlock(&hardlink_mutex);
934 *m |= 1 << (nr & 63);
935 pthread_mutex_unlock(&hardlink_mutex);
941 /* Increase the limit on open file descriptors, if possible */
942 static void max_openfds(void)
946 if (!getrlimit(RLIMIT_NOFILE, &rl))
947 if (rl.rlim_cur < rl.rlim_max) {
948 rl.rlim_cur = rl.rlim_max;
949 setrlimit(RLIMIT_NOFILE, &rl);
955 * Wrapper to realloc()
956 * Frees current memory if realloc() fails and returns NULL.
958 * The *alloc() family returns aligned address: https://man7.org/linux/man-pages/man3/malloc.3.html
960 static void *xrealloc(void *pcur, size_t len)
962 void *pmem = realloc(pcur, len);
971 * Just a safe strncpy(3)
972 * Always null ('\0') terminates if both src and dest are valid pointers.
973 * Returns the number of bytes copied including terminating null byte.
975 static size_t xstrsncpy(char *restrict dst, const char *restrict src, size_t n)
977 char *end = memccpy(dst, src, '\0', n);
980 dst[n - 1] = '\0'; // NOLINT
981 end = dst + n; /* If we return n here, binary size increases due to auto-inlining */
987 static inline size_t xstrlen(const char *restrict s)
989 #if !defined(__GLIBC__)
990 return strlen(s); // NOLINT
992 return (char *)rawmemchr(s, '\0') - s; // NOLINT
996 static char *xstrdup(const char *restrict s)
998 size_t len = xstrlen(s) + 1;
999 char *ptr = malloc(len);
1000 return ptr ? memcpy(ptr, s, len) : NULL;
1003 static bool is_suffix(const char *restrict str, const char *restrict suffix)
1005 if (!str || !suffix)
1008 size_t lenstr = xstrlen(str);
1009 size_t lensuffix = xstrlen(suffix);
1011 if (lensuffix > lenstr)
1014 return (xstrcmp(str + (lenstr - lensuffix), suffix) == 0);
1017 static inline bool is_prefix(const char *restrict str, const char *restrict prefix, size_t len)
1019 return !strncmp(str, prefix, len);
1022 static inline bool is_bad_len_or_dir(const char *restrict path)
1024 size_t len = xstrlen(path);
1026 return ((len >= PATH_MAX) || (path[len - 1] == '/'));
1029 static char *get_cwd_entry(const char *restrict cwdpath, char *entrypath, size_t *tokenlen)
1031 size_t len = xstrlen(cwdpath);
1034 if (!is_prefix(entrypath, cwdpath, len))
1037 entrypath += len + 1; /* Add 1 for trailing / */
1038 end = strchr(entrypath, '/');
1040 *tokenlen = end - entrypath;
1042 *tokenlen = xstrlen(entrypath);
1043 DPRINTF_U(*tokenlen);
1049 * The poor man's implementation of memrchr(3).
1050 * We are only looking for '/' and '.' in this program.
1051 * And we are NOT expecting a '/' at the end.
1052 * Ideally 0 < n <= xstrlen(s).
1054 static void *xmemrchr(uchar_t *restrict s, uchar_t ch, size_t n)
1056 #if defined(__GLIBC__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
1057 return memrchr(s, ch, n);
1063 uchar_t *ptr = s + n;
1074 /* A very simplified implementation, changes path */
1075 static char *xdirname(char *path)
1077 char *base = xmemrchr((uchar_t *)path, '/', xstrlen(path));
1087 static char *xbasename(char *path)
1089 char *base = xmemrchr((uchar_t *)path, '/', xstrlen(path)); // NOLINT
1091 return base ? base + 1 : path;
1094 static inline char *xextension(const char *fname, size_t len)
1096 return xmemrchr((uchar_t *)fname, '.', len);
1101 * One-shot cache for getpwuid/getgrgid. Returns the cached name if the
1102 * provided uid is the same as the previous uid. Returns xitoa(guid) if
1103 * the guid is not found in the password database.
1105 static char *getpwname(uid_t uid)
1107 static uint_t uidcache = UINT_MAX;
1108 static char *namecache;
1110 if (uidcache != uid) {
1111 struct passwd *pw = getpwuid(uid);
1114 namecache = pw ? pw->pw_name : NULL;
1117 return namecache ? namecache : xitoa(uid);
1120 static char *getgrname(gid_t gid)
1122 static uint_t gidcache = UINT_MAX;
1123 static char *grpcache;
1125 if (gidcache != gid) {
1126 struct group *gr = getgrgid(gid);
1129 grpcache = gr ? gr->gr_name : NULL;
1132 return grpcache ? grpcache : xitoa(gid);
1136 static inline bool getutil(char *util)
1138 return spawn("which", util, NULL, NULL, F_NORMAL | F_NOTRACE) == 0;
1141 static inline bool tilde_is_home(const char *s)
1143 return s[0] == '~' && (s[1] == '\0' || s[1] == '/');
1146 static inline bool tilde_is_home_strict(const char *s)
1148 return s[0] == '~' && s[1] == '/';
1152 * Updates out with "dir/name or "/name"
1153 * Returns the number of bytes copied including the terminating NULL byte
1155 * Note: dir and out must be PATH_MAX in length to avoid macOS fault
1157 static size_t mkpath(const char *dir, const char *name, char *out)
1161 /* same rational for being strict as abspath() */
1162 if (tilde_is_home_strict(name)) { //NOLINT
1163 len = xstrsncpy(out, home, PATH_MAX);
1166 } else if (name[0] != '/') { // NOLINT
1167 /* Handle root case */
1168 len = istopdir(dir) ? 1 : xstrsncpy(out, dir, PATH_MAX);
1169 out[len - 1] = '/'; // NOLINT
1171 return (xstrsncpy(out + len, name, PATH_MAX - len) + len);
1174 /* Assumes both the paths passed are directories */
1175 static char *common_prefix(const char *path, char *prefix)
1177 const char *x = path, *y = prefix;
1180 if (!path || !*path || !prefix)
1184 xstrsncpy(prefix, path, PATH_MAX);
1188 while (*x && *y && (*x == *y))
1191 /* Strings are same */
1195 /* Path is shorter */
1196 if (!*x && *y == '/') {
1197 xstrsncpy(prefix, path, y - path);
1201 /* Prefix is shorter */
1202 if (!*y && *x == '/')
1205 /* Shorten prefix */
1206 prefix[y - prefix] = '\0';
1208 sep = xmemrchr((uchar_t *)prefix, '/', y - prefix);
1218 * The library function realpath() resolves symlinks.
1219 * If there's a symlink in file list we want to show the symlink not what it's points to.
1220 * Resolves ./../~ in filepath
1222 static char *abspath(const char *filepath, char *cwd, char *buf)
1224 const char *path = filepath;
1225 bool allocated = FALSE;
1230 /* when dealing with tilde, we need to be strict.
1231 * otherwise a file named "~" can end up expanding to
1232 * $HOME and causing disaster */
1233 if (tilde_is_home_strict(path)) {
1235 path += 2; /* advance 2 bytes past the "~/" */
1236 } else if ((path[0] != '/') && !cwd) {
1237 cwd = getcwd(NULL, 0);
1243 size_t dst_size = 0, src_size = xstrlen(path), cwd_size = cwd ? xstrlen(cwd) : 0;
1244 size_t len = src_size;
1248 * We need to add 2 chars at the end as relative paths may start with:
1250 * no separator (fd .): this needs an additional char for '/'
1252 char *resolved_path = buf ? buf : malloc(src_size + cwd_size + 2);
1254 if (!resolved_path) {
1260 /* Turn relative paths into absolute */
1261 if (path[0] != '/') {
1264 free(resolved_path);
1267 dst_size = xstrsncpy(resolved_path, cwd, cwd_size + 1) - 1;
1271 resolved_path[0] = '\0';
1274 dst = resolved_path + dst_size;
1275 for (const char *next = NULL; next != path + src_size;) {
1276 next = memchr(src, '/', len);
1278 next = path + src_size;
1280 if (next - src == 2 && src[0] == '.' && src[1] == '.') {
1281 if (dst - resolved_path) {
1282 dst = xmemrchr((uchar_t *)resolved_path, '/', dst - resolved_path);
1285 } else if (next - src == 1 && src[0] == '.') {
1287 } else if (next - src) {
1289 xstrsncpy(dst, src, next - src + 1);
1294 len = src_size - (src - path);
1297 if (*resolved_path == '\0') {
1298 resolved_path[0] = '/';
1299 resolved_path[1] = '\0';
1302 if (xstrlen(resolved_path) >= PATH_MAX) {
1304 free(resolved_path);
1310 return resolved_path;
1313 /* wraps the argument in single quotes so it can be safely fed to shell */
1314 static bool shell_escape(char *output, size_t outlen, const char *s)
1316 size_t n = xstrlen(s), w = 0;
1319 DPRINTF_S("s == output");
1323 output[w++] = '\''; /* begin single quote */
1324 for (size_t r = 0; r < n; ++r) {
1325 /* potentially too big: 4 for the single quote case, 2 from
1326 * outside the loop */
1327 if (w + 6 >= outlen)
1331 /* the only thing that has special meaning inside single
1332 * quotes are single quotes themselves. */
1334 output[w++] = '\''; /* end single quote */
1335 output[w++] = '\\'; /* put \' so it's treated as literal single quote */
1337 output[w++] = '\''; /* start single quoting again */
1344 output[w++] = '\''; /* end single quote */
1345 output[w++] = '\0'; /* nul terminator */
1349 static bool set_tilde_in_path(char *path)
1351 if (is_prefix(path, home, homelen)) {
1352 home[homelen] = path[homelen - 1];
1353 path[homelen - 1] = '~';
1360 static void reset_tilde_in_path(char *path)
1362 path[homelen - 1] = home[homelen];
1363 home[homelen] = '\0';
1367 static void xterm_cfg(char *path)
1369 if (cfg.x11 && !g_state.picker) {
1370 /* Signal CWD change to terminal */
1371 printf("\033]7;file://%s%s\033\\", hostname, path);
1373 /* Set terminal window title */
1374 bool r = set_tilde_in_path(path);
1376 printf("\033]2;%s\007", r ? &path[homelen - 1] : path);
1380 reset_tilde_in_path(path);
1385 static bool convert_tilde(const char *path, char *buf)
1387 if (tilde_is_home(path)) {
1388 ssize_t len = xstrlen(home);
1389 ssize_t loclen = xstrlen(path);
1391 xstrsncpy(buf, home, len + 1);
1392 xstrsncpy(buf + len, path + 1, loclen);
1398 static int create_tmp_file(void)
1400 xstrsncpy(g_tmpfpath + tmpfplen - 1, messages[STR_TMPFILE], TMP_LEN_MAX - tmpfplen);
1402 int fd = mkstemp(g_tmpfpath);
1405 DPRINTF_S(strerror(errno));
1411 static void msg(const char *message)
1413 dprintf(STDERR_FILENO, "%s\n", message);
1417 static void handle_key_resize(void)
1423 /* Clear the old prompt */
1424 static void clearoldprompt(void)
1427 move(xlines - 2, 0);
1432 handle_key_resize();
1436 /* Messages show up at the bottom */
1437 static inline void printmsg_nc(const char *msg)
1444 static void printmsg(const char *msg)
1446 attron(COLOR_PAIR(cfg.curctx + 1));
1448 attroff(COLOR_PAIR(cfg.curctx + 1));
1451 static void printwait(const char *msg, int *presel)
1457 xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
1461 /* Kill curses and display error before exiting */
1462 static void printerr(int linenum)
1465 perror(xitoa(linenum));
1466 if (!g_state.picker && selpath)
1472 static inline bool xconfirm(int c)
1474 return (c == 'y' || c == 'Y');
1477 static int get_input(const char *prompt)
1488 while (*ch == KEY_RESIZE) {
1502 static bool isselfileempty(void)
1506 return (stat(selpath, &sb) == -1) || (!sb.st_size);
1509 static int get_cur_or_sel(void)
1511 bool sel = (selbufpos || !isselfileempty());
1513 /* Check both local buffer and selection file for external selection */
1514 if (sel && ndents) {
1515 /* If selection is preferred and we have a local selection, return selection.
1516 * Always show the prompt in case of an external selection.
1518 if (cfg.prefersel && selbufpos)
1521 int choice = get_input(messages[MSG_CUR_SEL_OPTS]);
1523 return ((choice == 'c' || choice == 's') ? choice : 0);
1535 static void xdelay(useconds_t delay)
1541 static char confirm_force(bool selection)
1545 snprintf(str, 64, messages[MSG_FORCE_RM],
1546 g_state.trash ? utils[UTIL_GIO_TRASH] + 4 : utils[UTIL_RM_RF],
1547 (selection ? "selected" : "hovered"));
1549 int r = get_input(str);
1552 return '\0'; /* cancel */
1553 if (r == 'y' || r == 'Y')
1554 return 'f'; /* forceful for rm */
1555 return (g_state.trash ? '\0' : 'i'); /* interactive for rm */
1558 /* Writes buflen char(s) from buf to a file */
1559 static void writesel(const char *buf, const size_t buflen)
1564 int fd = open(selpath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
1567 if (write(fd, buf, buflen) != (ssize_t)buflen)
1574 static void appendfpath(const char *path, const size_t len)
1576 if ((selbufpos >= selbuflen) || ((len + 3) > (selbuflen - selbufpos))) {
1577 selbuflen += PATH_MAX;
1578 pselbuf = xrealloc(pselbuf, selbuflen);
1583 selbufpos += xstrsncpy(pselbuf + selbufpos, path, len);
1586 static void selbufrealloc(const size_t alloclen)
1588 if ((selbufpos + alloclen) > selbuflen) {
1589 selbuflen = ALIGN_UP(selbufpos + alloclen, PATH_MAX);
1590 pselbuf = xrealloc(pselbuf, selbuflen);
1596 /* Write selected file paths to fd, linefeed separated */
1597 static size_t seltofile(int fd, uint_t *pcount)
1599 uint_t lastpos, count = 0;
1600 char *pbuf = pselbuf;
1602 ssize_t len, prefixlen = 0, initlen = 0;
1610 lastpos = selbufpos - 1;
1613 prefixlen = (ssize_t)xstrlen(listroot);
1614 initlen = (ssize_t)xstrlen(listpath);
1617 while (pos <= lastpos) {
1619 len = (ssize_t)xstrlen(pbuf);
1621 if (!listpath || !is_prefix(pbuf, listpath, initlen)) {
1622 if (write(fd, pbuf, len) != len)
1625 if (write(fd, listroot, prefixlen) != prefixlen)
1627 if (write(fd, pbuf + initlen, len - initlen) != (len - initlen))
1632 if (pos <= lastpos) {
1633 if (write(fd, "\n", 1) != 1)
1647 /* List selection from selection file (another instance) */
1648 static bool listselfile(void)
1650 if (isselfileempty())
1653 snprintf(g_buf, CMD_LEN_MAX, "tr \'\\0\' \'\\n\' < %s", selpath);
1654 spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CONFIRM);
1659 /* Reset selection indicators */
1660 static void resetselind(void)
1662 for (int r = 0; r < ndents; ++r)
1663 if (pdents[r].flags & FILE_SELECTED)
1664 pdents[r].flags &= ~FILE_SELECTED;
1667 static void startselection(void)
1669 if (!g_state.selmode) {
1670 g_state.selmode = 1;
1681 static void clearselection(void)
1685 g_state.selmode = 0;
1689 static char *findinsel(char *startpos, int len)
1697 char *found = startpos;
1698 size_t buflen = selbufpos - (startpos - pselbuf);
1701 /* memmem(3): not specified in POSIX.1, but present on a number of other systems. */
1702 found = memmem(found, buflen - (found - startpos), g_sel, len);
1705 if (found == startpos || *(found - 1) == '\0')
1707 found += len; /* We found g_sel as a substring of a path, move forward */
1708 if (found >= startpos + buflen)
1713 static int markcmp(const void *va, const void *vb)
1715 const selmark *ma = (selmark*)va;
1716 const selmark *mb = (selmark*)vb;
1718 return ma->startpos - mb->startpos;
1721 /* scanselforpath() must be called before calling this */
1722 static inline void findmarkentry(size_t len, struct entry *dentp)
1724 if (!(dentp->flags & FILE_SCANNED)) {
1725 if (findinsel(findselpos, len + xstrsncpy(g_sel + len, dentp->name, dentp->nlen)))
1726 dentp->flags |= FILE_SELECTED;
1727 dentp->flags |= FILE_SCANNED;
1732 * scanselforpath() must be called before calling this
1733 * pathlen = length of path + 1 (+1 for trailing slash)
1735 static void invertselbuf(const int pathlen)
1737 size_t len, endpos, shrinklen = 0, alloclen = 0;
1738 char * const pbuf = g_sel + pathlen;
1740 int i, nmarked = 0, prev = 0;
1741 struct entry *dentp;
1743 selmark *marked = malloc(nselected * sizeof(selmark));
1750 /* First pass: inversion */
1751 for (i = 0; i < ndents; ++i) {
1754 if (dentp->flags & FILE_SCANNED) {
1755 if (dentp->flags & FILE_SELECTED) {
1756 dentp->flags ^= FILE_SELECTED; /* Clear selection status */
1759 dentp->flags |= FILE_SELECTED;
1760 alloclen += pathlen + dentp->nlen;
1763 dentp->flags |= FILE_SCANNED;
1768 len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1769 found = findinsel(findselpos, len);
1771 if (findselpos == found)
1774 if (nmarked && (found
1775 == (marked[nmarked - 1].startpos + marked[nmarked - 1].len)))
1776 marked[nmarked - 1].len += len;
1778 marked[nmarked].startpos = found;
1779 marked[nmarked].len = len;
1784 shrinklen += len; /* buffer size adjustment */
1786 dentp->flags |= FILE_SELECTED;
1787 alloclen += pathlen + dentp->nlen;
1794 * Files marked for deselection could be found in arbitrary order.
1795 * Sort by appearance in selection buffer.
1796 * With entries sorted we can merge adjacent ones allowing us to
1797 * move them in a single go.
1799 qsort(marked, nmarked, sizeof(selmark), &markcmp);
1801 /* Some files might be adjacent. Merge them into a single entry */
1802 for (i = 1; i < nmarked; ++i) {
1803 if (marked[i].startpos == marked[prev].startpos + marked[prev].len)
1804 marked[prev].len += marked[i].len;
1807 marked[prev].startpos = marked[i].startpos;
1808 marked[prev].len = marked[i].len;
1813 * Number of entries is increased by encountering a non-adjacent entry
1814 * After we finish the loop we should increment it once more.
1817 if (nmarked) /* Make sure there is something to deselect */
1820 /* Using merged entries remove unselected chunks from selection buffer */
1821 for (i = 0; i < nmarked; ++i) {
1823 * found: points to where the current block starts
1824 * variable is recycled from previous for readability
1825 * endpos: points to where the the next block starts
1826 * area between the end of current block (found + len)
1827 * and endpos is selected entries. This is what we are
1830 found = marked[i].startpos;
1831 endpos = (i + 1 == nmarked ? selbufpos : marked[i + 1].startpos - pselbuf);
1832 len = marked[i].len;
1834 /* Move back only selected entries. No selected memory is moved twice */
1835 memmove(found, found + len, endpos - (found + len - pselbuf));
1840 /* Buffer size adjustment */
1841 selbufpos -= shrinklen;
1843 selbufrealloc(alloclen);
1845 /* Second pass: append newly selected to buffer */
1846 for (i = 0; i < ndents; ++i) {
1847 if (pdents[i].flags & FILE_SELECTED) {
1848 len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1849 appendfpath(g_sel, len);
1854 nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1858 * scanselforpath() must be called before calling this
1859 * pathlen = length of path + 1 (+1 for trailing slash)
1861 static void addtoselbuf(const int pathlen, int startid, int endid)
1864 size_t len, alloclen = 0;
1865 struct entry *dentp;
1867 char * const pbuf = g_sel + pathlen;
1869 /* Remember current selection buffer position */
1870 for (i = startid; i <= endid; ++i) {
1874 len = pathlen + xstrsncpy(pbuf, dentp->name, NAME_MAX);
1875 found = findinsel(findselpos, len);
1877 dentp->flags |= (FILE_SCANNED | FILE_SELECTED);
1878 if (found == findselpos) {
1880 if (findselpos == (pselbuf + selbufpos))
1884 alloclen += pathlen + dentp->nlen;
1886 alloclen += pathlen + dentp->nlen;
1889 selbufrealloc(alloclen);
1891 for (i = startid; i <= endid; ++i) {
1892 if (!(pdents[i].flags & FILE_SELECTED)) {
1893 len = pathlen + xstrsncpy(pbuf, pdents[i].name, NAME_MAX);
1894 appendfpath(g_sel, len);
1896 pdents[i].flags |= (FILE_SCANNED | FILE_SELECTED);
1900 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
1903 /* Removes g_sel from selbuf */
1904 static void rmfromselbuf(size_t len)
1906 char *found = findinsel(findselpos, len);
1910 memmove(found, found + len, selbufpos - (found + len - pselbuf));
1913 nselected ? writesel(pselbuf, selbufpos - 1) : clearselection();
1916 static int scanselforpath(const char *path, bool getsize)
1918 if (!path[1]) { /* path should always be at least two bytes (including NULL) */
1920 findselpos = pselbuf;
1921 return 1; /* Length of '/' is 1 */
1924 size_t off = xstrsncpy(g_sel, path, PATH_MAX);
1926 g_sel[off - 1] = '/';
1928 * We set findselpos only here. Directories can be listed in arbitrary order.
1929 * This is the best best we can do for remembering position.
1931 findselpos = findinsel(NULL, off);
1935 return (findselpos ? off : 0);
1938 /* Finish selection procedure before an operation */
1939 static void endselection(bool endselmode)
1943 char buf[sizeof(patterns[P_REPLACE]) + PATH_MAX + (TMP_LEN_MAX << 1)];
1945 if (endselmode && g_state.selmode)
1946 g_state.selmode = 0;
1948 /* The code below is only for listing mode */
1949 if (!listpath || !selbufpos)
1952 fd = create_tmp_file();
1954 DPRINTF_S("couldn't create tmp file");
1958 seltofile(fd, NULL);
1960 DPRINTF_S(strerror(errno));
1965 snprintf(buf, sizeof(buf), patterns[P_REPLACE], listpath, listroot, g_tmpfpath);
1966 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
1968 fd = open(g_tmpfpath, O_RDONLY);
1970 DPRINTF_S(strerror(errno));
1972 if (unlink(g_tmpfpath)) {
1973 DPRINTF_S(strerror(errno));
1979 count = read(fd, pselbuf, selbuflen);
1981 DPRINTF_S(strerror(errno));
1983 if (close(fd) || unlink(g_tmpfpath)) {
1984 DPRINTF_S(strerror(errno));
1989 if (close(fd) || unlink(g_tmpfpath)) {
1990 DPRINTF_S(strerror(errno));
1996 pselbuf[--count] = '\0';
1997 for (--count; count > 0; --count)
1998 if (pselbuf[count] == '\n' && pselbuf[count+1] == '/')
1999 pselbuf[count] = '\0';
2001 writesel(pselbuf, selbufpos - 1);
2004 /* Returns: 1 - success, 0 - none selected, -1 - other failure */
2005 static int editselection(void)
2013 if (!selbufpos) /* External selection is only editable at source */
2014 return listselfile();
2016 fd = create_tmp_file();
2018 DPRINTF_S("couldn't create tmp file");
2022 seltofile(fd, NULL);
2024 DPRINTF_S(strerror(errno));
2028 /* Save the last modification time */
2029 if (stat(g_tmpfpath, &sb)) {
2030 DPRINTF_S(strerror(errno));
2034 mtime = sb.st_mtime;
2036 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2038 fd = open(g_tmpfpath, O_RDONLY);
2040 DPRINTF_S(strerror(errno));
2047 if (mtime == sb.st_mtime) {
2048 DPRINTF_S("selection is not modified");
2053 if (sb.st_size > selbufpos) {
2054 DPRINTF_S("edited buffer larger than previous");
2059 count = read(fd, pselbuf, selbuflen);
2061 DPRINTF_S(strerror(errno));
2063 if (close(fd) || unlink(g_tmpfpath)) {
2064 DPRINTF_S(strerror(errno));
2070 if (close(fd) || unlink(g_tmpfpath)) {
2071 DPRINTF_S(strerror(errno));
2083 /* The last character should be '\n' */
2084 pselbuf[--count] = '\0';
2085 for (--count; count > 0; --count) {
2086 /* Replace every '\n' that separates two paths */
2087 if (pselbuf[count] == '\n' && pselbuf[count + 1] == '/') {
2089 pselbuf[count] = '\0';
2093 /* Add a line for the last file */
2096 if (lines > nselected) {
2097 DPRINTF_S("files added to selection");
2102 writesel(pselbuf, selbufpos - 1);
2112 static bool selsafe(void)
2114 /* Fail if selection file path not generated */
2116 printmsg(messages[MSG_SEL_MISSING]);
2120 /* Fail if selection file path isn't accessible */
2121 if (access(selpath, R_OK | W_OK) == -1) {
2122 errno == ENOENT ? printmsg(messages[MSG_0_SELECTED]) : printwarn(NULL);
2129 static void export_file_list(void)
2134 struct entry *pdent = pdents;
2135 int fd = create_tmp_file();
2138 DPRINTF_S(strerror(errno));
2142 for (int r = 0; r < ndents; ++pdent, ++r) {
2143 if (write(fd, pdent->name, pdent->nlen - 1) != (pdent->nlen - 1))
2146 if ((r != ndents - 1) && (write(fd, "\n", 1) != 1))
2151 DPRINTF_S(strerror(errno));
2154 spawn(editor, g_tmpfpath, NULL, NULL, F_CLI);
2156 if (xconfirm(get_input(messages[MSG_RM_TMP])))
2160 static bool init_fcolors(void)
2162 char *f_colors = getenv(env_cfg[NNN_FCOLORS]);
2164 if (!f_colors || !*f_colors)
2167 for (uchar_t id = C_BLK; *f_colors && id <= C_UND; ++id) {
2168 fcolors[id] = xchartohex(*f_colors) << 4;
2170 fcolors[id] += xchartohex(*f_colors);
2172 init_pair(id, fcolors[id], -1);
2181 /* Initialize curses mode */
2182 static bool initcurses(void *oldmask)
2188 if (g_state.picker) {
2189 if (!newterm(NULL, stderr, stdin)) {
2193 } else if (!initscr()) {
2195 DPRINTF_S(getenv("TERM"));
2202 //intrflush(stdscr, FALSE);
2203 keypad(stdscr, TRUE);
2205 #if NCURSES_MOUSE_VERSION <= 1
2206 mousemask(BUTTON1_PRESSED | BUTTON1_DOUBLE_CLICKED | BUTTON2_PRESSED | BUTTON3_PRESSED,
2207 (mmask_t *)oldmask);
2209 mousemask(BUTTON1_PRESSED | BUTTON2_PRESSED | BUTTON3_PRESSED | BUTTON4_PRESSED
2210 | BUTTON5_PRESSED, (mmask_t *)oldmask);
2214 curs_set(FALSE); /* Hide cursor */
2216 char *colors = getenv(env_cfg[NNN_COLORS]);
2218 if (colors || !getenv("NO_COLOR")) {
2223 use_default_colors();
2225 /* Initialize file colors */
2226 if (COLORS >= COLOR_256) {
2227 if (!(g_state.oldcolor || init_fcolors())) {
2229 msg(env_cfg[NNN_FCOLORS]);
2233 g_state.oldcolor = 1;
2236 DPRINTF_D(COLOR_PAIRS);
2238 if (colors && *colors == '#') {
2239 char *sep = strchr(colors, ';');
2241 if (!g_state.oldcolor && COLORS >= COLOR_256) {
2246 * If fallback colors are specified, set the separator
2247 * to NULL so we don't interpret separator and fallback
2248 * if fewer than CTX_MAX xterm 256 colors are specified.
2253 colors = sep; /* Detect if 8 colors fallback is appended */
2259 /* Get and set the context colors */
2260 for (uchar_t i = 0; i < CTX_MAX; ++i) {
2261 pcode = &g_ctx[i].color;
2263 if (colors && *colors) {
2265 *pcode = xchartohex(*colors) << 4;
2267 fcolors[i + 1] = *pcode += xchartohex(*colors);
2268 else { /* Each color code must be 2 hex symbols */
2270 msg(env_cfg[NNN_COLORS]);
2274 *pcode = (*colors < '0' || *colors > '7') ? 4 : *colors - '0';
2279 init_pair(i + 1, *pcode, -1);
2282 #ifdef ICONS_ENABLED
2283 if (!g_state.oldcolor) {
2284 for (uint_t i = 0; i < ELEMENTS(init_colors); ++i)
2285 init_pair(C_UND + 1 + init_colors[i], init_colors[i], -1);
2289 settimeout(); /* One second */
2294 /* No NULL check here as spawn() guards against it */
2295 static char *parseargs(char *cmd, char **argv, int *pindex)
2298 size_t len = xstrlen(cmd) + 1;
2299 char *line = (char *)malloc(len);
2302 DPRINTF_S("malloc()!");
2306 xstrsncpy(line, cmd, len);
2307 argv[count++] = line;
2310 while (*line) { // NOLINT
2311 if (ISBLANK(*line)) {
2314 if (!*line) // NOLINT
2317 argv[count++] = line;
2318 if (count == EXEC_ARGS_MAX) {
2327 if (count == -1 || count > (EXEC_ARGS_MAX - 4)) { /* 3 args and last NULL */
2330 DPRINTF_S("NULL or too many args");
2337 static void enable_signals(void)
2339 struct sigaction dfl_act = {.sa_handler = SIG_DFL};
2341 sigaction(SIGHUP, &dfl_act, NULL);
2342 sigaction(SIGINT, &dfl_act, NULL);
2343 sigaction(SIGQUIT, &dfl_act, NULL);
2344 sigaction(SIGTSTP, &dfl_act, NULL);
2345 sigaction(SIGWINCH, &dfl_act, NULL);
2348 static pid_t xfork(uchar_t flag)
2353 /* the parent ignores the interrupt, quit and hangup signals */
2354 sigaction(SIGHUP, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsighup);
2355 sigaction(SIGTSTP, &(struct sigaction){.sa_handler = SIG_DFL}, &oldsigtstp);
2356 sigaction(SIGWINCH, &(struct sigaction){.sa_handler = SIG_IGN}, &oldsigwinch);
2357 } else if (p == 0) {
2358 /* We create a grandchild to detach */
2359 if (flag & F_NOWAIT) {
2363 _exit(EXIT_SUCCESS);
2371 _exit(EXIT_FAILURE);
2374 /* So they can be used to stop the child */
2378 /* This is the parent waiting for the child to create grandchild */
2379 if (flag & F_NOWAIT)
2380 waitpid(p, NULL, 0);
2387 static int join(pid_t p, uchar_t flag)
2389 int status = 0xFFFF;
2391 if (!(flag & F_NOWAIT)) {
2392 /* wait for the child to exit */
2394 } while (waitpid(p, &status, 0) == -1);
2396 if (WIFEXITED(status)) {
2397 status = WEXITSTATUS(status);
2402 /* restore parent's signal handling */
2403 sigaction(SIGHUP, &oldsighup, NULL);
2404 sigaction(SIGTSTP, &oldsigtstp, NULL);
2405 sigaction(SIGWINCH, &oldsigwinch, NULL);
2411 * Spawns a child process. Behaviour can be controlled using flag.
2412 * Limited to 3 arguments to a program, flag works on bit set.
2414 static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag)
2417 int status = 0, retstatus = 0xFFFF;
2418 char *argv[EXEC_ARGS_MAX] = {0};
2421 if (!file || !*file)
2424 /* Swap args if the first arg is NULL and the other 2 aren't */
2425 if (!arg1 && arg2) {
2434 if (flag & F_MULTI) {
2435 cmd = parseargs(file, argv, &status);
2439 argv[status++] = file;
2441 argv[status] = arg1;
2442 argv[++status] = arg2;
2443 argv[++status] = arg3;
2445 if (flag & F_NORMAL)
2450 /* Suppress stdout and stderr */
2451 if (flag & F_NOTRACE) {
2452 int fd = open("/dev/null", O_WRONLY, 0200);
2454 if (flag & F_NOSTDIN)
2455 dup2(fd, STDIN_FILENO);
2456 dup2(fd, STDOUT_FILENO);
2457 dup2(fd, STDERR_FILENO);
2459 } else if (flag & F_TTY) {
2460 /* If stdout has been redirected to a non-tty, force output to tty */
2461 if (!isatty(STDOUT_FILENO)) {
2462 int fd = open(ctermid(NULL), O_WRONLY, 0200);
2463 dup2(fd, STDOUT_FILENO);
2468 execvp(*argv, argv);
2469 _exit(EXIT_SUCCESS);
2471 retstatus = join(pid, flag);
2474 if ((flag & F_CONFIRM) || ((flag & F_CHKRTN) && retstatus)) {
2475 status = write(STDOUT_FILENO, messages[MSG_ENTER], xstrlen(messages[MSG_ENTER]));
2477 while ((read(STDIN_FILENO, &status, 1) > 0) && (status != '\n'));
2480 if (flag & F_NORMAL)
2489 /* Get program name from env var, else return fallback program */
2490 static char *xgetenv(const char * const name, char *fallback)
2492 char *value = getenv(name);
2494 return value && value[0] ? value : fallback;
2497 /* Checks if an env variable is set to 1 */
2498 static inline uint_t xgetenv_val(const char *name)
2500 char *str = getenv(name);
2508 /* Check if a dir exists, IS a dir, and is readable */
2509 static bool xdiraccess(const char *path)
2511 DIR *dirp = opendir(path);
2522 static bool plugscript(const char *plugin, uchar_t flags)
2524 mkpath(plgpath, plugin, g_buf);
2525 if (!access(g_buf, X_OK)) {
2526 spawn(g_buf, NULL, NULL, NULL, flags);
2533 static void opstr(char *buf, char *op)
2535 snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c '%s \"$0\" \"$@\" . < /dev/tty' < %s", op, selpath);
2538 static bool rmmulstr(char *buf)
2540 char r = confirm_force(TRUE);
2545 snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c 'rm -%cr \"$0\" \"$@\" < /dev/tty' < %s",
2548 snprintf(buf, CMD_LEN_MAX, "xargs -0 %s < %s",
2549 utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH], selpath);
2554 /* Returns TRUE if file is removed, else FALSE */
2555 static bool xrm(char * const fpath)
2557 char r = confirm_force(FALSE);
2561 if (!g_state.trash) {
2562 char rm_opts[] = "-ir";
2565 spawn("rm", rm_opts, fpath, NULL, F_NORMAL | F_CHKRTN);
2567 spawn(utils[(g_state.trash == 1) ? UTIL_TRASH_CLI : UTIL_GIO_TRASH],
2568 fpath, NULL, NULL, F_NORMAL | F_MULTI);
2570 return (access(fpath, F_OK) == -1); /* File is removed */
2573 static void xrmfromsel(char *path, char *fpath)
2576 bool selected = TRUE;
2579 if ((pdents[cur].flags & DIR_OR_DIRLNK) && scanselforpath(fpath, FALSE))
2581 else if (pdents[cur].flags & FILE_SELECTED) {
2583 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
2589 if (selected && cfg.x11)
2590 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
2594 static uint_t lines_in_file(int fd, char *buf, size_t buflen)
2599 while ((len = read(fd, buf, buflen)) > 0)
2601 count += (buf[--len] == '\n');
2603 /* For all use cases 0 linecount is considered as error */
2604 return ((len < 0) ? 0 : count);
2607 static bool cpmv_rename(int choice, const char *path)
2610 uint_t count = 0, lines = 0;
2612 char *cmd = (choice == 'c' ? cp : mv);
2613 char buf[sizeof(patterns[P_CPMVRNM]) + (MAX(sizeof(cp), sizeof(mv))) + (PATH_MAX << 1)];
2615 fd = create_tmp_file();
2619 /* selsafe() returned TRUE for this to be called */
2621 snprintf(buf, sizeof(buf), "tr '\\0' '\\n' < %s > %s", selpath, g_tmpfpath);
2622 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2624 count = lines_in_file(fd, buf, sizeof(buf));
2628 seltofile(fd, &count);
2632 snprintf(buf, sizeof(buf), patterns[P_CPMVFMT], g_tmpfpath);
2633 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2635 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2637 fd = open(g_tmpfpath, O_RDONLY);
2641 lines = lines_in_file(fd, buf, sizeof(buf));
2644 if (!lines || (2 * count != lines)) {
2645 DPRINTF_S("num mismatch");
2649 snprintf(buf, sizeof(buf), patterns[P_CPMVRNM], path, g_tmpfpath, cmd);
2650 if (!spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CHKRTN))
2659 static bool cpmvrm_selection(enum action sel, char *path)
2663 if (isselfileempty()) {
2666 printmsg(messages[MSG_0_SELECTED]);
2681 r = get_input(messages[MSG_CP_MV_AS]);
2682 if (r != 'c' && r != 'm') {
2683 printmsg(messages[MSG_INVALID_KEY]);
2687 if (!cpmv_rename(r, path)) {
2688 printmsg(messages[MSG_FAILED]);
2692 default: /* SEL_RM */
2693 if (!rmmulstr(g_buf)) {
2694 printmsg(messages[MSG_CANCEL]);
2699 if (sel != SEL_CPMVAS && spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CHKRTN)) {
2700 printmsg(messages[MSG_FAILED]);
2704 /* Clear selection */
2711 static bool batch_rename(void)
2714 uint_t count = 0, lines = 0;
2715 bool dir = FALSE, ret = FALSE;
2716 char foriginal[TMP_LEN_MAX] = {0};
2717 static const char batchrenamecmd[] = "paste -d'\n' %s %s | "SED" 'N; /^\\(.*\\)\\n\\1$/!p;d' | "
2718 "tr '\n' '\\0' | xargs -0 -n2 sh -c 'mv -i \"$0\" \"$@\" <"
2720 char buf[sizeof(batchrenamecmd) + (PATH_MAX << 1)];
2721 int i = get_cur_or_sel();
2726 if (i == 'c') { /* Rename entries in current dir */
2731 fd1 = create_tmp_file();
2735 xstrsncpy(foriginal, g_tmpfpath, xstrlen(g_tmpfpath) + 1);
2737 fd2 = create_tmp_file();
2745 for (i = 0; i < ndents; ++i)
2746 appendfpath(pdents[i].name, NAME_MAX);
2748 seltofile(fd1, &count);
2749 seltofile(fd2, NULL);
2752 if (dir) /* Don't retain dir entries in selection */
2755 spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
2757 /* Reopen file descriptor to get updated contents */
2758 fd2 = open(g_tmpfpath, O_RDONLY);
2762 lines = lines_in_file(fd2, buf, sizeof(buf));
2765 if (!lines || (count != lines)) {
2766 DPRINTF_S("cannot delete files");
2770 snprintf(buf, sizeof(buf), batchrenamecmd, foriginal, g_tmpfpath);
2771 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
2787 static char *get_archive_cmd(const char *archive)
2791 if (!g_state.usebsdtar && getutil(utils[UTIL_ATOOL]))
2793 else if (getutil(utils[UTIL_BSDTAR]))
2795 else if (is_suffix(archive, ".zip"))
2799 return archive_cmd[i];
2802 static void archive_selection(const char *cmd, const char *archive)
2804 char *buf = malloc((xstrlen(patterns[P_ARCHIVE_CMD]) + xstrlen(cmd) + xstrlen(archive)
2805 + xstrlen(selpath)) * sizeof(char));
2807 DPRINTF_S(strerror(errno));
2812 snprintf(buf, CMD_LEN_MAX, patterns[P_ARCHIVE_CMD], cmd, archive, selpath);
2813 spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI | F_CONFIRM);
2817 static void write_lastdir(const char *curpath, const char *outfile)
2821 xstrsncpy(cfgpath + xstrlen(cfgpath), "/.lastd", 8);
2823 tilde = convert_tilde(outfile, g_buf);
2825 int fd = open(outfile
2826 ? (tilde ? g_buf : outfile)
2827 : cfgpath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
2829 if (fd != -1 && shell_escape(g_buf, sizeof(g_buf), curpath)) {
2830 dprintf(fd, "cd %s", g_buf);
2836 * We assume none of the strings are NULL.
2838 * Let's have the logic to sort numeric names in numeric order.
2839 * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
2841 * If the absolute numeric values are same, we fallback to alphasort.
2843 static int xstricmp(const char * const s1, const char * const s2)
2847 long long v1 = strtoll(s1, &p1, 10);
2848 long long v2 = strtoll(s2, &p2, 10);
2850 /* Check if at least 1 string is numeric */
2851 if (s1 != p1 || s2 != p2) {
2852 /* Handle both pure numeric */
2853 if (s1 != p1 && s2 != p2) {
2861 /* Only first string non-numeric */
2865 /* Only second string non-numeric */
2870 /* Handle 1. all non-numeric and 2. both same numeric value cases */
2872 return strcoll(s1, s2);
2874 return strcasecmp(s1, s2);
2879 * Version comparison
2881 * The code for version compare is a modified version of the GLIBC
2882 * and uClibc implementation of strverscmp(). The source is here:
2883 * https://elixir.bootlin.com/uclibc-ng/latest/source/libc/string/strverscmp.c
2887 * Compare S1 and S2 as strings holding indices/version numbers,
2888 * returning less than, equal to or greater than zero if S1 is less than,
2889 * equal to or greater than S2 (for more info, see the texinfo doc).
2893 static int xstrverscasecmp(const char * const s1, const char * const s2)
2895 const uchar_t *p1 = (const uchar_t *)s1;
2896 const uchar_t *p2 = (const uchar_t *)s2;
2901 * Symbol(s) 0 [1-9] others
2902 * Transition (10) 0 (01) d (00) x
2904 static const uint8_t next_state[] = {
2906 /* S_N */ S_N, S_I, S_Z,
2907 /* S_I */ S_N, S_I, S_I,
2908 /* S_F */ S_N, S_F, S_F,
2909 /* S_Z */ S_N, S_F, S_Z
2912 alignas(max_align_t) static const int8_t result_type[] = {
2913 /* state x/x x/d x/0 d/x d/d d/0 0/x 0/d 0/0 */
2915 /* S_N */ VCMP, VCMP, VCMP, VCMP, VLEN, VCMP, VCMP, VCMP, VCMP,
2916 /* S_I */ VCMP, -1, -1, 1, VLEN, VLEN, 1, VLEN, VLEN,
2917 /* S_F */ VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP,
2918 /* S_Z */ VCMP, 1, 1, -1, VCMP, VCMP, -1, VCMP, VCMP
2929 /* Hint: '0' is a digit too. */
2930 state = S_N + ((c1 == '0') + (xisdigit(c1) != 0));
2932 while ((diff = c1 - c2) == 0) {
2936 state = next_state[state];
2941 state += (c1 == '0') + (xisdigit(c1) != 0);
2944 state = result_type[state * 3 + (((c2 == '0') + (xisdigit(c2) != 0)))]; // NOLINT
2950 while (xisdigit(*p1++))
2951 if (!xisdigit(*p2++))
2953 return xisdigit(*p2) ? -1 : diff;
2959 static int (*namecmpfn)(const char * const s1, const char * const s2) = &xstricmp;
2961 static char * (*fnstrstr)(const char *haystack, const char *needle) = &strcasestr;
2963 static const unsigned char *tables;
2964 static int pcreflags = PCRE_NO_AUTO_CAPTURE | PCRE_EXTENDED | PCRE_CASELESS | PCRE_UTF8;
2966 static int regflags = REG_NOSUB | REG_EXTENDED | REG_ICASE;
2970 static int setfilter(pcre **pcrex, const char *filter)
2972 const char *errstr = NULL;
2975 *pcrex = pcre_compile(filter, pcreflags, &errstr, &erroffset, tables);
2977 return errstr ? -1 : 0;
2980 static int setfilter(regex_t *regex, const char *filter)
2982 return regcomp(regex, filter, regflags);
2986 static int visible_re(const fltrexp_t *fltrexp, const char *fname)
2989 return pcre_exec(fltrexp->pcrex, NULL, fname, xstrlen(fname), 0, 0, NULL, 0) == 0;
2991 return regexec(fltrexp->regex, fname, 0, NULL, 0) == 0;
2995 static int visible_str(const fltrexp_t *fltrexp, const char *fname)
2997 return fnstrstr(fname, fltrexp->str) != NULL;
3000 static int (*filterfn)(const fltrexp_t *fltr, const char *fname) = &visible_str;
3002 static void clearfilter(void)
3004 char * const fltr = g_ctx[cfg.curctx].c_fltr;
3007 fltr[REGEX_MAX - 1] = fltr[1];
3012 static int entrycmp(const void *va, const void *vb)
3014 const struct entry *pa = (pEntry)va;
3015 const struct entry *pb = (pEntry)vb;
3017 if ((pb->flags & DIR_OR_DIRLNK) != (pa->flags & DIR_OR_DIRLNK)) {
3018 if (pb->flags & DIR_OR_DIRLNK)
3023 /* Sort based on specified order */
3024 if (cfg.timeorder) {
3025 if (pb->sec > pa->sec)
3027 if (pb->sec < pa->sec)
3029 /* If sec matches, comare nsec */
3030 if (pb->nsec > pa->nsec)
3032 if (pb->nsec < pa->nsec)
3034 } else if (cfg.sizeorder) {
3035 if (pb->size > pa->size)
3037 if (pb->size < pa->size)
3039 } else if (cfg.blkorder) {
3040 if (pb->blocks > pa->blocks)
3042 if (pb->blocks < pa->blocks)
3044 } else if (cfg.extnorder && !(pb->flags & DIR_OR_DIRLNK)) {
3045 char *extna = xextension(pa->name, pa->nlen - 1);
3046 char *extnb = xextension(pb->name, pb->nlen - 1);
3048 if (extna || extnb) {
3055 int ret = strcasecmp(extna, extnb);
3062 return namecmpfn(pa->name, pb->name);
3065 static int reventrycmp(const void *va, const void *vb)
3067 if ((((pEntry)vb)->flags & DIR_OR_DIRLNK)
3068 != (((pEntry)va)->flags & DIR_OR_DIRLNK)) {
3069 if (((pEntry)vb)->flags & DIR_OR_DIRLNK)
3074 return -entrycmp(va, vb);
3077 static int (*entrycmpfn)(const void *va, const void *vb) = &entrycmp;
3079 /* In case of an error, resets *wch to Esc */
3080 static int handle_alt_key(wint_t *wch)
3084 int r = get_wch(wch);
3093 static inline int handle_event(void)
3095 if (nselected && isselfileempty())
3097 return CONTROL('L');
3101 * Returns SEL_* if key is bound and 0 otherwise.
3102 * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
3103 * The next keyboard input can be simulated by presel.
3105 static int nextsel(int presel)
3112 bool escaped = FALSE;
3114 if (c == 0 || c == MSGWAIT) {
3118 //DPRINTF_S(keyname(c));
3121 if (c == KEY_RESIZE)
3122 handle_key_resize();
3125 /* Handle Alt+key */
3137 } else if (escaped) {
3142 if (!g_state.fifomode)
3143 notify_fifo(TRUE); /* Send hovered path to NNN_FIFO */
3151 if (i == ERR && presel == MSGWAIT)
3152 c = (cfg.filtermode || filterset()) ? FILTER : CONTROL('L');
3153 else if (c == FILTER || c == CONTROL('L'))
3154 /* Clear previous filter when manually starting */
3162 * Do not check for directory changes in du mode.
3163 * A redraw forces du calculation.
3164 * Check for changes every odd second.
3166 #ifdef LINUX_INOTIFY
3167 if (!cfg.blkorder && inotify_wd >= 0 && (idle & 1)) {
3168 struct inotify_event *event;
3169 char inotify_buf[EVENT_BUF_LEN] = {0};
3171 i = read(inotify_fd, inotify_buf, EVENT_BUF_LEN);
3173 for (char *ptr = inotify_buf;
3174 ptr + ((struct inotify_event *)ptr)->len < inotify_buf + i;
3175 ptr += sizeof(struct inotify_event) + event->len) {
3176 event = (struct inotify_event *)ptr;
3177 DPRINTF_D(event->wd);
3178 DPRINTF_D(event->mask);
3182 if (event->mask & INOTIFY_MASK) {
3187 DPRINTF_S("inotify read done");
3190 #elif defined(BSD_KQUEUE)
3191 if (!cfg.blkorder && event_fd >= 0 && (idle & 1)) {
3192 struct kevent event_data[NUM_EVENT_SLOTS] = {0};
3194 if (kevent(kq, events_to_monitor, NUM_EVENT_SLOTS,
3195 event_data, NUM_EVENT_FDS, >imeout) > 0)
3198 #elif defined(HAIKU_NM)
3199 if (!cfg.blkorder && haiku_nm_active && (idle & 1) && haiku_is_update_needed(haiku_hnd))
3205 for (i = 0; i < (int)ELEMENTS(bindings); ++i)
3206 if (c == bindings[i].sym)
3207 return bindings[i].act;
3212 static int getorderstr(char *sort)
3220 sort[i++] = (cfg.timetype == T_MOD) ? 'M' : ((cfg.timetype == T_ACCESS) ? 'A' : 'C');
3221 else if (cfg.sizeorder)
3223 else if (cfg.extnorder)
3226 if (entrycmpfn == &reventrycmp)
3229 if (namecmpfn == &xstrverscasecmp)
3238 static void showfilterinfo(void)
3241 char info[REGEX_MAX] = "\0\0\0\0\0";
3243 i = getorderstr(info);
3245 if (cfg.fileinfo && ndents && get_output("file", "-b", pdents[cur].name, -1, FALSE))
3246 mvaddstr(xlines - 2, 2, g_buf);
3248 snprintf(info + i, REGEX_MAX - i - 1, " %s [/], %4s [:]",
3249 (cfg.regex ? "reg" : "str"),
3250 ((fnstrstr == &strcasestr) ? "ic" : "noic"));
3253 mvaddstr(xlines - 2, xcols - xstrlen(info), info);
3256 static void showfilter(char *str)
3258 attron(COLOR_PAIR(cfg.curctx + 1));
3261 // printmsg calls attroff()
3264 static inline void swap_ent(int id1, int id2)
3266 struct entry _dent, *pdent1 = &pdents[id1], *pdent2 = &pdents[id2];
3268 *(&_dent) = *pdent1;
3270 *pdent2 = *(&_dent);
3274 static int fill(const char *fltr, pcre *pcrex)
3276 static int fill(const char *fltr, regex_t *re)
3280 fltrexp_t fltrexp = { .pcrex = pcrex, .str = fltr };
3282 fltrexp_t fltrexp = { .regex = re, .str = fltr };
3285 for (int count = 0; count < ndents; ++count) {
3286 if (filterfn(&fltrexp, pdents[count].name) == 0) {
3287 if (count != --ndents) {
3288 swap_ent(count, ndents);
3299 static int matches(const char *fltr)
3305 if (cfg.regex && setfilter(&pcrex, fltr))
3308 ndents = fill(fltr, pcrex);
3316 if (cfg.regex && setfilter(&re, fltr))
3319 ndents = fill(fltr, &re);
3325 ENTSORT(pdents, ndents, entrycmpfn);
3331 * Return the position of the matching entry or 0 otherwise
3332 * Note there's no NULL check for fname
3334 static int dentfind(const char *fname, int n)
3336 for (int i = 0; i < n; ++i)
3337 if (xstrcmp(fname, pdents[i].name) == 0)
3343 static int filterentries(char *path, char *lastname)
3345 alignas(max_align_t) wchar_t wln[REGEX_MAX];
3346 char *ln = g_ctx[cfg.curctx].c_fltr;
3348 int r, total = ndents, len;
3349 char *pln = g_ctx[cfg.curctx].c_fltr + 1;
3351 DPRINTF_S(__func__);
3353 if (ndents && (ln[0] == FILTER || ln[0] == RFILTER) && *pln) {
3354 if (matches(pln) != -1) {
3355 move_cursor(dentfind(lastname, ndents), 0);
3359 if (!cfg.filtermode) {
3364 len = mbstowcs(wln, ln, REGEX_MAX);
3366 ln[0] = wln[0] = cfg.regex ? RFILTER : FILTER;
3367 ln[1] = wln[1] = '\0';
3375 while ((r = get_wch(ch)) != ERR) {
3377 //DPRINTF_S(keyname(*ch));
3381 case 0: // fallthrough
3388 case KEY_DC: // fallthrough
3389 case KEY_BACKSPACE: // fallthrough
3390 case '\b': // fallthrough
3391 case DEL: /* handle DEL */
3394 wcstombs(ln, wln, REGEX_MAX);
3402 if (*ch == CONTROL('L')) {
3404 ln[REGEX_MAX - 1] = ln[1];
3405 ln[1] = wln[1] = '\0';
3408 } else if (ln[REGEX_MAX - 1]) { /* Show the previous filter */
3409 ln[1] = ln[REGEX_MAX - 1];
3410 ln[REGEX_MAX - 1] = '\0';
3411 len = mbstowcs(wln, ln, REGEX_MAX);
3416 /* Go to the top, we don't know if the hovered file will match the filter */
3419 if (matches(pln) != -1)
3429 if (handle_alt_key(ch) != ERR) {
3430 if (*ch == ESC) /* Handle Alt+Esc */
3431 *ch = 'q'; /* Quit context */
3434 *ch = ';'; /* Run plugin */
3440 if (r != OK) /* Handle Fn keys in main loop */
3443 /* Handle all control chars in main loop */
3444 if (*ch < ASCII_MAX && keyname(*ch)[0] == '^' && *ch != '^')
3448 if (*ch == '?') /* Help and config key, '?' is an invalid regex */
3451 if (cfg.filtermode) {
3453 case '\'': // fallthrough /* Go to first non-dir file */
3454 case '+': // fallthrough /* Toggle file selection */
3455 case ',': // fallthrough /* Mark CWD */
3456 case '-': // fallthrough /* Visit last visited dir */
3457 case '.': // fallthrough /* Show hidden files */
3458 case ';': // fallthrough /* Run plugin key */
3459 case '=': // fallthrough /* Launch app */
3460 case '>': // fallthrough /* Export file list */
3461 case '@': // fallthrough /* Visit start dir */
3462 case ']': // fallthorugh /* Prompt key */
3463 case '`': // fallthrough /* Visit / */
3464 case '~': /* Go HOME */
3469 /* Toggle case-sensitivity */
3471 fnstrstr = (fnstrstr == &strcasestr) ? &strstr : &strcasestr;
3473 pcreflags ^= PCRE_CASELESS;
3475 regflags ^= REG_ICASE;
3481 /* Toggle string or regex filter */
3482 if (*ch == FILTER) {
3483 ln[0] = (ln[0] == FILTER) ? RFILTER : FILTER;
3484 wln[0] = (uchar_t)ln[0];
3486 filterfn = cfg.regex ? &visible_re : &visible_str;
3491 /* Reset cur in case it's a repeat search */
3493 } else if (len == REGEX_MAX - 1)
3496 wln[len] = (wchar_t)*ch;
3498 wcstombs(ln, wln, REGEX_MAX);
3500 /* Forward-filtering optimization:
3501 * - new matches can only be a subset of current matches.
3503 /* ndents = total; */
3507 !r ? unget_wch(KEY_BACKSPACE) : showfilter(ln);
3509 if (matches(pln) == -1) {
3515 /* If the only match is a dir, auto-enter and cd into it */
3516 if ((ndents == 1) && cfg.autoenter && (pdents[0].flags & DIR_OR_DIRLNK)) {
3523 * redraw() should be above the auto-enter optimization, for
3524 * the case where there's an issue with dir auto-enter, say,
3525 * due to a permission problem. The transition is _jumpy_ in
3526 * case of such an error. However, we optimize for successful
3527 * cases where the dir has permissions. This skips a redraw().
3534 /* Save last working filter in-filter */
3536 ln[REGEX_MAX - 1] = ln[1];
3544 /* Return keys for navigation etc. */
3548 /* Show a prompt with input string and return the changes */
3549 static char *xreadline(const char *prefill, const char *prompt)
3553 const int WCHAR_T_WIDTH = sizeof(wchar_t);
3555 wchar_t * const buf = malloc(sizeof(wchar_t) * READLINE_MAX);
3565 len = pos = mbstowcs(buf, prefill, READLINE_MAX);
3569 if (len == (size_t)-1) {
3574 x = getcurx(stdscr);
3579 attron(COLOR_PAIR(cfg.curctx + 1));
3580 if (pos > (size_t)(xcols - x)) {
3581 mvaddnwstr(xlines - 1, x, buf + (pos - (xcols - x) + 1), xcols - x);
3582 move(xlines - 1, xcols - 1);
3584 mvaddnwstr(xlines - 1, x, buf, len + 1);
3585 move(xlines - 1, x + wcswidth(buf, pos));
3587 attroff(COLOR_PAIR(cfg.curctx + 1));
3595 case KEY_ENTER: // fallthrough
3596 case '\n': // fallthrough
3602 else if (!(pos || len)) { /* Exit on ^D at empty prompt */
3608 case DEL: // fallthrough
3609 case '\b': /* rhel25 sends '\b' for backspace */
3611 memmove(buf + pos - 1, buf + pos,
3612 (len - pos) * WCHAR_T_WIDTH);
3617 if (!(len || pos) && ndents)
3618 len = pos = mbstowcs(buf, pdents[cur].name, READLINE_MAX);
3633 memmove(buf + pos - 1, buf + pos,
3634 (len - pos) * WCHAR_T_WIDTH);
3636 } while (buf[pos - 1] != ' ' && buf[pos - 1] != '/'); // NOLINT
3654 memmove(buf, buf + pos, (len - pos) * WCHAR_T_WIDTH);
3658 case ESC: /* Exit prompt on Esc, but just filter out Alt+key */
3659 if (handle_alt_key(ch) != ERR)
3666 /* Filter out all other control chars */
3667 if (*ch < ASCII_MAX && keyname(*ch)[0] == '^')
3670 if (pos < READLINE_MAX - 1) {
3671 memmove(buf + pos + 1, buf + pos,
3672 (len - pos) * WCHAR_T_WIDTH);
3696 memmove(buf + pos - 1, buf + pos,
3697 (len - pos) * WCHAR_T_WIDTH);
3703 memmove(buf + pos, buf + pos + 1,
3704 (len - pos - 1) * WCHAR_T_WIDTH);
3714 case KEY_UP: // fallthrough
3716 if (prompt && lastcmd && (xstrcmp(prompt, PROMPT) == 0)) {
3718 len = pos = mbstowcs(buf, lastcmd, READLINE_MAX); // fallthrough
3733 pos = wcstombs(g_buf, buf, READLINE_MAX - 1);
3734 if (pos >= READLINE_MAX - 1)
3735 g_buf[READLINE_MAX - 1] = '\0';
3743 * Caller should check the value of presel to confirm if it needs to wait to show warning
3745 static char *getreadline(const char *prompt)
3749 char *input = readline(prompt);
3753 if (input && input[0]) {
3755 xstrsncpy(g_buf, input, CMD_LEN_MAX);
3766 * Create symbolic/hard link(s) to file(s) in selection list
3767 * Returns the number of links created, -1 on error
3769 static int xlink(char *prefix, char *path, char *curfname, char *buf, int type)
3771 int count = 0, choice;
3772 char *psel = pselbuf, *fname;
3773 size_t pos = 0, len, r;
3774 int (*link_fn)(const char *, const char *) = NULL;
3775 char lnpath[PATH_MAX];
3777 choice = get_cur_or_sel();
3781 if (type == 's') /* symbolic link */
3783 else /* hard link */
3786 if (choice == 'c' || (nselected == 1)) {
3787 prefix = abspath(prefix, path, lnpath); /* Generate link path */
3792 mkpath(path, curfname, buf); /* Generate target file path */
3794 if (!link_fn((choice == 'c') ? buf : pselbuf, lnpath)) {
3797 return 1; /* One link created */
3802 r = xstrsncpy(buf, prefix, NAME_MAX + 1); /* Copy prefix */
3804 while (pos < selbufpos) {
3805 len = xstrlen(psel);
3806 fname = xbasename(psel);
3808 xstrsncpy(buf + r - 1, fname, NAME_MAX - r); /* Suffix target file name */
3809 mkpath(path, buf, lnpath); /* Generate link path */
3811 if (!link_fn(psel, lnpath))
3818 if (count == nselected) /* Clear selection if all links are generated */
3823 static bool parsekvpair(kv **arr, char **envcpy, const uchar_t id, uchar_t *items)
3826 const uchar_t INCR = 8;
3829 char *ptr = getenv(env_cfg[id]);
3834 *envcpy = xstrdup(ptr);
3842 while (*ptr && i < 100) {
3844 if (!(i & (INCR - 1))) {
3845 kvarr = xrealloc(kvarr, sizeof(kv) * (i + INCR));
3851 memset(kvarr + i, 0, sizeof(kv) * INCR);
3853 kvarr[i].key = (uchar_t)*ptr;
3854 if (*++ptr != ':' || *++ptr == '\0' || *ptr == ';')
3856 kvarr[i].off = ptr - *envcpy;
3875 * Get the value corresponding to a key
3877 * NULL is returned in case of no match, path resolution failure etc.
3878 * buf would be modified, so check return value before access
3880 static char *get_kv_val(kv *kvarr, char *buf, int key, uchar_t max, uchar_t id)
3887 for (int r = 0; r < max && kvarr[r].key; ++r) {
3888 if (kvarr[r].key == key) {
3889 /* Do not allocate new memory for plugin */
3891 return pluginstr + kvarr[r].off;
3893 val = bmstr + kvarr[r].off;
3894 bool tilde = convert_tilde(val, g_buf);
3895 return abspath((tilde ? g_buf : val), NULL, buf);
3899 DPRINTF_S("Invalid key");
3903 static int get_kv_key(kv *kvarr, char *val, uchar_t max, uchar_t id)
3908 if (id != NNN_ORDER) /* For now this function supports only order string */
3911 for (int r = 0; r < max && kvarr[r].key; ++r) {
3912 if (xstrcmp((orderstr + kvarr[r].off), val) == 0)
3913 return kvarr[r].key;
3919 static void resetdircolor(int flags)
3921 /* Directories are always shown on top, clear the color when moving to first file */
3922 if (g_state.dircolor && !(flags & DIR_OR_DIRLNK)) {
3923 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
3924 g_state.dircolor = 0;
3929 * Replace escape characters in a string with '?'
3930 * Adjust string length to maxcols if > 0;
3931 * Max supported str length: NAME_MAX;
3934 static char *unescape(const char *str, uint_t maxcols)
3936 char * const wbuf = g_buf;
3939 xstrsncpy(wbuf, str, maxcols);
3941 static wchar_t *unescape(const char *str, uint_t maxcols)
3943 wchar_t * const wbuf = (wchar_t *)g_buf;
3944 wchar_t *buf = wbuf;
3945 size_t len = mbstowcs(wbuf, str, maxcols); /* Convert multi-byte to wide char */
3947 len = wcswidth(wbuf, len);
3949 if (len >= maxcols) {
3950 size_t lencount = maxcols;
3952 while (len > maxcols) /* Reduce wide chars one by one till it fits */
3953 len = wcswidth(wbuf, --lencount);
3955 wbuf[lencount] = L'\0';
3960 if (*buf <= '\x1f' || *buf == '\x7f')
3969 static off_t get_size(off_t size, off_t *pval, int comp)
3972 off_t quo = rem / 10;
3974 if ((rem - (quo * 10)) >= 5) {
3987 static char *coolsize(off_t size)
3989 const char * const U = "BKMGTPEZY";
3990 static char size_buf[12]; /* Buffer to hold human readable size */
3995 while (size >= 1024) {
3996 rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
4002 rem = (rem * 1000) >> 10;
4004 size = get_size(size, &rem, 10);
4005 } else if (i == 2) {
4006 rem = (rem * 1000) >> 10;
4007 size = get_size(size, &rem, 100);
4009 rem = (rem * 10000) >> 10;
4010 size = get_size(size, &rem, 1000);
4013 if (i > 0 && i < 6 && rem) {
4014 ret = xstrsncpy(size_buf, xitoa(size), 12);
4015 size_buf[ret - 1] = '.';
4017 char *frac = xitoa(rem);
4018 size_t toprint = i > 3 ? 3 : i;
4019 size_t len = xstrlen(frac);
4021 if (len < toprint) {
4022 size_buf[ret] = size_buf[ret + 1] = size_buf[ret + 2] = '0';
4023 xstrsncpy(size_buf + ret + (toprint - len), frac, len + 1);
4025 xstrsncpy(size_buf + ret, frac, toprint + 1);
4029 ret = xstrsncpy(size_buf, size ? xitoa(size) : "0", 12);
4033 size_buf[ret] = U[i];
4034 size_buf[ret + 1] = '\0';
4039 /* Convert a mode field into "ls -l" type perms field. */
4040 static char *get_lsperms(mode_t mode)
4042 static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
4043 static char bits[11] = {'\0'};
4045 switch (mode & S_IFMT) {
4072 xstrsncpy(&bits[1], rwx[(mode >> 6) & 7], 4);
4073 xstrsncpy(&bits[4], rwx[(mode >> 3) & 7], 4);
4074 xstrsncpy(&bits[7], rwx[(mode & 7)], 4);
4077 bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
4079 bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
4081 bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
4086 #ifdef ICONS_ENABLED
4087 static struct icon get_icon(const struct entry *ent)
4089 for (size_t i = 0; i < ELEMENTS(icons_name); ++i)
4090 if (strcasecmp(ent->name, icons_name[i].match) == 0)
4091 return (struct icon){ icons_name[i].icon, icons_name[i].color };
4093 if (ent->flags & DIR_OR_DIRLNK)
4096 char *tmp = xextension(ent->name, ent->nlen);
4099 uint16_t z, k, h = icon_ext_hash(++tmp); /* ++tmp to skip '.' */
4100 for (k = 0; k < ICONS_PROBE_MAX; ++k) {
4101 z = (h + k) % ELEMENTS(icons_ext);
4102 if (strcasecmp(tmp, icons_ext[z].match) == 0)
4103 return (struct icon){ icons_ext_uniq[icons_ext[z].idx], icons_ext[z].color };
4107 /* If there's no match and the file is executable, icon that */
4108 if (ent->mode & 0100)
4113 static void print_icon(const struct entry *ent, const int attrs)
4115 const struct icon icon = get_icon(ent);
4116 addstr(ICON_PADDING_LEFT);
4118 attron(COLOR_PAIR(C_UND + 1 + icon.color));
4123 attroff(COLOR_PAIR(C_UND + 1 + icon.color));
4126 addstr(ICON_PADDING_RIGHT);
4130 static void print_time(const time_t *timep, const uchar_t flags)
4134 /* Highlight timestamp for entries 5 minutes young */
4135 if (flags & FILE_YOUNG)
4138 localtime_r(timep, &t);
4139 printw("%s-%02d-%02d %02d:%02d",
4140 xitoa(t.tm_year + 1900), t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min);
4142 if (flags & FILE_YOUNG)
4146 static char get_detail_ind(const mode_t mode)
4148 switch (mode & S_IFMT) {
4149 case S_IFDIR: // fallthrough
4150 case S_IFREG: return ' ';
4151 case S_IFLNK: return '@';
4152 case S_IFSOCK: return '=';
4153 case S_IFIFO: return '|';
4154 case S_IFBLK: return 'b';
4155 case S_IFCHR: return 'c';
4160 /* Note: attribute and indicator values must be initialized to 0 */
4161 static uchar_t get_color_pair_name_ind(const struct entry *ent, char *pind, int *pattr)
4163 switch (ent->mode & S_IFMT) {
4166 if (ent->mode & 0100)
4170 if (ent->flags & HARD_LINK) {
4171 if (ent->mode & 0100)
4175 if (ent->mode & 0100) {
4182 if (g_state.oldcolor)
4185 return g_state.dirctx ? cfg.curctx + 1 : C_DIR;
4187 if (ent->flags & DIR_OR_DIRLNK) {
4189 *pattr |= g_state.oldcolor ? A_DIM : A_BOLD;
4192 if (g_state.oldcolor)
4195 if (!g_state.oldcolor || cfg.showdetail)
4196 return (ent->flags & SYM_ORPHAN) ? C_ORP : C_LNK;
4214 static void printent(const struct entry *ent, uint_t namecols, bool sel)
4219 if (cfg.showdetail) {
4220 int type = ent->mode & S_IFMT;
4221 char perms[6] = {' ', ' ', (char)('0' + ((ent->mode >> 6) & 7)),
4222 (char)('0' + ((ent->mode >> 3) & 7)),
4223 (char)('0' + (ent->mode & 7)), '\0'};
4226 attrs = g_state.oldcolor ? (resetdircolor(ent->flags), A_DIM)
4227 : (fcolors[C_MIS] ? COLOR_PAIR(C_MIS) : 0);
4232 print_time(&ent->sec, ent->flags);
4234 printw("%s%9s ", perms, (type == S_IFREG || type == S_IFDIR)
4235 ? coolsize(cfg.blkorder ? (blkcnt_t)ent->blocks << blk_shift : ent->size)
4236 : (type = (uchar_t)get_detail_ind(ent->mode), (char *)&type));
4244 uchar_t color_pair = get_color_pair_name_ind(ent, &ind, &attrs);
4246 addch((ent->flags & FILE_SELECTED) ? '+' | A_REVERSE | A_BOLD : ' ');
4248 if (g_state.oldcolor)
4249 resetdircolor(ent->flags);
4251 if (ent->flags & FILE_MISSING)
4253 if (color_pair && fcolors[color_pair])
4254 attrs |= COLOR_PAIR(color_pair);
4255 #ifdef ICONS_ENABLED
4256 print_icon(ent, attrs);
4268 addwstr(unescape(ent->name, namecols));
4270 addstr(unescape(ent->name, MIN(namecols, ent->nlen) + 1));
4280 * Sets the global cfg variable and restores related state to match the new
4283 static void setcfg(settings newcfg)
4286 /* Synchronize the global function pointers to match the new cfg. */
4287 entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
4288 namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
4291 static void savecurctx(char *path, char *curname, int nextctx)
4293 settings tmpcfg = cfg;
4294 context *ctxr = &g_ctx[nextctx];
4296 /* Save current context */
4298 xstrsncpy(g_ctx[tmpcfg.curctx].c_name, curname, NAME_MAX + 1);
4300 g_ctx[tmpcfg.curctx].c_name[0] = '\0';
4302 g_ctx[tmpcfg.curctx].c_cfg = tmpcfg;
4304 if (ctxr->c_cfg.ctxactive) { /* Switch to saved context */
4305 tmpcfg = ctxr->c_cfg;
4306 /* Skip ordering an open context */
4308 cfgsort[CTX_MAX] = cfgsort[nextctx];
4309 cfgsort[nextctx] = '0';
4311 } else { /* Set up a new context from current context */
4312 ctxr->c_cfg.ctxactive = 1;
4313 xstrsncpy(ctxr->c_path, path, PATH_MAX);
4314 ctxr->c_last[0] = ctxr->c_name[0] = ctxr->c_fltr[0] = ctxr->c_fltr[1] = '\0';
4315 ctxr->c_cfg = tmpcfg;
4316 /* If already in an ordered dir, clear ordering for the new context and let it order */
4317 if (cfgsort[cfg.curctx] == 'z')
4318 cfgsort[nextctx] = 'z';
4321 tmpcfg.curctx = nextctx;
4326 static void save_session(const char *sname, int *presel)
4329 session_header_t header = {0};
4330 bool status = FALSE;
4331 char ssnpath[PATH_MAX];
4332 char spath[PATH_MAX];
4334 header.ver = SESSIONS_VERSION;
4336 for (i = 0; i < CTX_MAX; ++i) {
4337 if (g_ctx[i].c_cfg.ctxactive) {
4338 if (cfg.curctx == i && ndents)
4339 /* Update current file name, arrows don't update it */
4340 xstrsncpy(g_ctx[i].c_name, pdents[cur].name, NAME_MAX + 1);
4341 header.pathln[i] = MIN(xstrlen(g_ctx[i].c_path), PATH_MAX) + 1;
4342 header.lastln[i] = MIN(xstrlen(g_ctx[i].c_last), PATH_MAX) + 1;
4343 header.nameln[i] = MIN(xstrlen(g_ctx[i].c_name), NAME_MAX) + 1;
4344 header.fltrln[i] = REGEX_MAX;
4348 mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4349 mkpath(ssnpath, sname, spath);
4351 fd = open(spath, O_CREAT | O_WRONLY | O_TRUNC, S_IWUSR | S_IRUSR);
4353 printwait(messages[MSG_SEL_MISSING], presel);
4357 if ((write(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4358 || (write(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4361 for (i = 0; i < CTX_MAX; ++i)
4362 if ((write(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4363 || (write(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4364 || (header.nameln[i] > 0
4365 && write(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4366 || (header.lastln[i] > 0
4367 && write(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4368 || (header.fltrln[i] > 0
4369 && write(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4370 || (header.pathln[i] > 0
4371 && write(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4380 printwait(messages[MSG_FAILED], presel);
4383 static bool load_session(const char *sname, char **path, char **lastdir, char **lastname, bool restore)
4386 session_header_t header;
4387 bool has_loaded_dynamically = !(sname || restore);
4388 bool status = (sname && g_state.picker); /* Picker mode with session program option */
4389 char ssnpath[PATH_MAX];
4390 char spath[PATH_MAX];
4392 mkpath(cfgpath, toks[TOK_SSN], ssnpath);
4395 sname = sname ? sname : xreadline(NULL, messages[MSG_SSN_NAME]);
4399 mkpath(ssnpath, sname, spath);
4401 /* If user is explicitly loading the "last session", skip auto-save */
4402 if ((sname[0] == '@') && !sname[1])
4403 has_loaded_dynamically = FALSE;
4405 mkpath(ssnpath, "@", spath);
4407 if (has_loaded_dynamically)
4408 save_session("@", NULL);
4410 fd = open(spath, O_RDONLY, S_IWUSR | S_IRUSR);
4413 printmsg(messages[MSG_SEL_MISSING]);
4414 xdelay(XDELAY_INTERVAL_MS);
4421 if ((read(fd, &header, sizeof(header)) != (ssize_t)sizeof(header))
4422 || (header.ver != SESSIONS_VERSION)
4423 || (read(fd, &cfg, sizeof(cfg)) != (ssize_t)sizeof(cfg)))
4426 g_ctx[cfg.curctx].c_name[0] = g_ctx[cfg.curctx].c_last[0]
4427 = g_ctx[cfg.curctx].c_fltr[0] = g_ctx[cfg.curctx].c_fltr[1] = '\0';
4429 for (; i < CTX_MAX; ++i)
4430 if ((read(fd, &g_ctx[i].c_cfg, sizeof(settings)) != (ssize_t)sizeof(settings))
4431 || (read(fd, &g_ctx[i].color, sizeof(uint_t)) != (ssize_t)sizeof(uint_t))
4432 || (header.nameln[i] > 0
4433 && read(fd, g_ctx[i].c_name, header.nameln[i]) != (ssize_t)header.nameln[i])
4434 || (header.lastln[i] > 0
4435 && read(fd, g_ctx[i].c_last, header.lastln[i]) != (ssize_t)header.lastln[i])
4436 || (header.fltrln[i] > 0
4437 && read(fd, g_ctx[i].c_fltr, header.fltrln[i]) != (ssize_t)header.fltrln[i])
4438 || (header.pathln[i] > 0
4439 && read(fd, g_ctx[i].c_path, header.pathln[i]) != (ssize_t)header.pathln[i]))
4442 *path = g_ctx[cfg.curctx].c_path;
4443 *lastdir = g_ctx[cfg.curctx].c_last;
4444 *lastname = g_ctx[cfg.curctx].c_name;
4445 set_sort_flags('\0'); /* Set correct sort options */
4452 printmsg(messages[MSG_FAILED]);
4453 xdelay(XDELAY_INTERVAL_MS);
4461 static uchar_t get_free_ctx(void)
4463 uchar_t r = cfg.curctx;
4466 r = (r + 1) & ~CTX_MAX;
4467 while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
4472 /* ctx is absolute: 1 to 4, + for smart context */
4473 static void set_smart_ctx(int ctx, char *nextpath, char **path, char *file, char **lastname, char **lastdir)
4475 if (ctx == '+') /* Get smart context */
4476 ctx = (int)(get_free_ctx() + 1);
4478 if (ctx == 0 || ctx == cfg.curctx + 1) { /* Same context */
4480 xstrsncpy(*lastdir, *path, PATH_MAX);
4481 xstrsncpy(*path, nextpath, PATH_MAX);
4482 } else { /* New context */
4484 /* Deactivate the new context and build from scratch */
4485 g_ctx[ctx].c_cfg.ctxactive = 0;
4486 DPRINTF_S(nextpath);
4487 savecurctx(nextpath, file, ctx);
4488 *path = g_ctx[ctx].c_path;
4489 *lastdir = g_ctx[ctx].c_last;
4490 *lastname = g_ctx[ctx].c_name;
4495 * This function does one of the following depending on the values of `fdout` and `page`:
4496 * 1) fdout == -1 && !page: Write up to CMD_LEN_MAX bytes of command output into g_buf
4497 * 2) fdout == -1 && page: Create a temp file, write full command output into it and show in pager.
4498 * 3) fdout != -1 && !page: Write full command output into the provided file.
4499 * 4) fdout != -1 && page: Don't use! Returns FALSE.
4501 * g_buf is modified only in case 1.
4502 * g_tmpfpath is modified only in case 2.
4504 static bool get_output(char *file, char *arg1, char *arg2, int fdout, bool page)
4508 int index = 0, flags;
4510 bool have_file = fdout != -1;
4512 int cmd_out_fd = -1;
4516 * In this case the logic of the function dictates that we should write the output of the command
4517 * to `fd` and show it in the pager. But since we didn't open the file descriptor we have no right
4518 * to close it, the caller must do it. We don't even know the path to pass to the pager and
4519 * it's a real hassle to get it. In general this just invites problems so we are blocking it.
4521 if (have_file && page) {
4522 DPRINTF_S("invalid get_ouptput() call");
4526 /* Setup file descriptors for child command */
4527 if (!have_file && page) {
4529 fdout = create_tmp_file();
4533 cmd_in_fd = STDIN_FILENO;
4535 } else if (have_file) {
4537 cmd_in_fd = STDIN_FILENO;
4541 if (pipe(pipefd) == -1)
4544 for (index = 0; index < 2; ++index) {
4545 /* Get previous flags */
4546 flags = fcntl(pipefd[index], F_GETFL, 0);
4548 /* Set bit for non-blocking flag */
4549 flags |= O_NONBLOCK;
4551 /* Change flags on fd */
4552 fcntl(pipefd[index], F_SETFL, flags);
4555 cmd_in_fd = pipefd[0];
4556 cmd_out_fd = pipefd[1];
4563 dup2(cmd_out_fd, STDOUT_FILENO);
4564 dup2(cmd_out_fd, STDERR_FILENO);
4567 spawn(file, arg1, arg2, NULL, F_MULTI);
4568 _exit(EXIT_SUCCESS);
4572 waitpid(pid, NULL, 0);
4574 /* Do what each case should do */
4575 if (!have_file && page) {
4579 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4590 len = read(pipefd[0], g_buf, CMD_LEN_MAX - 1);
4600 * Follows the stat(1) output closely
4602 static bool show_stats(char *fpath)
4604 static char * const cmds[] = {
4605 #ifdef FILE_MIME_OPTS
4606 ("file " FILE_MIME_OPTS),
4609 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
4616 size_t r = ELEMENTS(cmds);
4617 int fd = create_tmp_file();
4622 get_output(cmds[--r], fpath, NULL, fd, FALSE);
4626 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
4631 static bool xchmod(const char *fpath, mode_t *mode)
4633 /* (Un)set (S_IXUSR | S_IXGRP | S_IXOTH) */
4634 (0100 & *mode) ? (*mode &= ~0111) : (*mode |= 0111);
4636 return (chmod(fpath, *mode) == 0);
4639 static size_t get_fs_info(const char *path, uchar_t type)
4643 if (statvfs(path, &svb) == -1)
4646 if (type == VFS_AVAIL)
4647 return (size_t)svb.f_bavail << ffs((int)(svb.f_frsize >> 1));
4649 if (type == VFS_USED)
4650 return ((size_t)svb.f_blocks - (size_t)svb.f_bfree) << ffs((int)(svb.f_frsize >> 1));
4652 return (size_t)svb.f_blocks << ffs((int)(svb.f_frsize >> 1)); /* VFS_SIZE */
4655 /* Create non-existent parents and a file or dir */
4656 static bool xmktree(char *path, bool dir)
4664 /* Skip the first '/' */
4667 while (*p != '\0') {
4676 /* Create folder from path to '\0' inserted at p */
4677 if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4679 // XDG_CONFIG_HOME contains a directory
4680 // that is read-only, but the full path
4682 // Try to continue and see what happens.
4683 // TODO: Find a more robust solution.
4684 if (errno == B_READ_ONLY_DEVICE)
4687 DPRINTF_S("mkdir1!");
4688 DPRINTF_S(strerror(errno));
4702 if (mkdir(path, 0777) == -1 && errno != EEXIST) {
4703 DPRINTF_S("mkdir2!");
4704 DPRINTF_S(strerror(errno));
4708 int fd = open(path, O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR); /* Forced create mode for files */
4710 if (fd == -1 && errno != EEXIST) {
4712 DPRINTF_S(strerror(errno));
4722 /* List or extract archive */
4723 static bool handle_archive(char *fpath /* in-out param */, char op)
4725 char arg[] = "-tvf"; /* options for tar/bsdtar to list files */
4726 char *util, *outdir = NULL;
4728 bool is_atool = (!g_state.usebsdtar && getutil(utils[UTIL_ATOOL]));
4731 outdir = xreadline(is_atool ? "." : xbasename(fpath), messages[MSG_NEW_PATH]);
4732 if (!outdir || !*outdir) { /* Cancelled */
4733 printwait(messages[MSG_CANCEL], NULL);
4736 /* Do not create smart context for current dir */
4737 if (!(*outdir == '.' && outdir[1] == '\0')) {
4738 if (!xmktree(outdir, TRUE) || (chdir(outdir) == -1)) {
4742 /* Copy the new dir path to open it in smart context */
4743 outdir = getcwd(NULL, 0);
4749 util = utils[UTIL_ATOOL];
4752 } else if (getutil(utils[UTIL_BSDTAR])) {
4753 util = utils[UTIL_BSDTAR];
4756 } else if (is_suffix(fpath, ".zip")) {
4757 util = utils[UTIL_UNZIP];
4758 arg[1] = (op == 'l') ? 'v' /* verbose listing */ : '\0';
4761 util = utils[UTIL_TAR];
4766 if (op == 'x') /* extract */
4767 spawn(util, arg, fpath, NULL, F_NORMAL | F_MULTI);
4769 get_output(util, arg, fpath, -1, TRUE);
4772 if (chdir(xdirname(fpath)) == -1) {
4777 xstrsncpy(fpath, outdir, PATH_MAX);
4779 } else if (op == 'x')
4785 static char *visit_parent(char *path, char *newpath, int *presel)
4789 /* There is no going back */
4790 if (istopdir(path)) {
4791 /* Continue in type-to-nav mode, if enabled */
4792 if (cfg.filtermode && presel)
4797 /* Use a copy as xdirname() may change the string passed */
4799 xstrsncpy(newpath, path, PATH_MAX);
4803 dir = xdirname(newpath);
4804 if (chdir(dir) == -1) {
4812 static void valid_parent(char *path, char *lastname)
4815 xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
4817 while (!istopdir(path))
4818 if (visit_parent(path, NULL, NULL))
4822 xdelay(XDELAY_INTERVAL_MS);
4825 static bool archive_mount(char *newpath)
4827 char *dir, *cmd = xgetenv("NNN_ARCHMNT", utils[UTIL_ARCHMNT]);
4828 char *name = pdents[cur].name;
4829 size_t len = pdents[cur].nlen;
4830 char mntpath[PATH_MAX];
4832 if (!getutil(cmd)) {
4833 printmsg("install utility");
4837 dir = xstrdup(name);
4839 printmsg(messages[MSG_FAILED]);
4844 if (dir[--len] == '.') {
4851 /* Create the mount point */
4852 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4853 mkpath(mntpath, dir, newpath);
4856 if (!xmktree(newpath, TRUE)) {
4864 if (spawn(cmd, name, newpath, NULL, F_NORMAL)) {
4865 printmsg(messages[MSG_FAILED]);
4872 static bool remote_mount(char *newpath)
4874 uchar_t flag = F_CLI;
4877 bool r = getutil(utils[UTIL_RCLONE]), s = getutil(utils[UTIL_SSHFS]);
4878 char mntpath[PATH_MAX];
4881 printmsg("install sshfs/rclone");
4886 opt = get_input(messages[MSG_REMOTE_OPTS]);
4888 opt = (!s) ? 'r' : 's';
4891 env = xgetenv("NNN_SSHFS", utils[UTIL_SSHFS]);
4892 else if (opt == 'r') {
4893 flag |= F_NOWAIT | F_NOTRACE;
4894 env = xgetenv("NNN_RCLONE", "rclone mount");
4896 printmsg(messages[MSG_INVALID_KEY]);
4900 tmp = xreadline(NULL, "host[:dir] > ");
4902 printmsg(messages[MSG_CANCEL]);
4906 char *div = strchr(tmp, ':');
4911 /* Create the mount point */
4912 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4913 mkpath(mntpath, tmp, newpath);
4914 if (!xmktree(newpath, TRUE)) {
4919 if (!div) { /* Convert "host" to "host:" */
4920 size_t len = xstrlen(tmp);
4923 tmp[len + 1] = '\0';
4927 /* Connect to remote */
4929 if (spawn(env, tmp, newpath, NULL, flag)) {
4930 printmsg(messages[MSG_FAILED]);
4934 spawn(env, tmp, newpath, NULL, flag);
4935 printmsg(messages[MSG_RCLONE_DELAY]);
4936 xdelay(XDELAY_INTERVAL_MS << 2); /* Set 4 times the usual delay */
4943 * Unmounts if the directory represented by name is a mount point.
4944 * Otherwise, asks for hostname
4945 * Returns TRUE if directory needs to be refreshed *.
4947 static bool unmount(char *name, char *newpath, int *presel, char *currentpath)
4949 #if defined(__APPLE__) || defined(__FreeBSD__)
4950 static char cmd[] = "umount";
4952 static char cmd[] = "fusermount3"; /* Arch Linux utility */
4953 static bool found = FALSE;
4956 struct stat sb, psb;
4958 bool parent = FALSE;
4959 bool hovered = FALSE;
4960 char mntpath[PATH_MAX];
4962 #if !defined(__APPLE__) && !defined(__FreeBSD__)
4963 /* On Ubuntu it's fusermount */
4964 if (!found && !getutil(cmd)) {
4970 mkpath(cfgpath, toks[TOK_MNT], mntpath);
4972 if (tmp && strcmp(mntpath, currentpath) == 0) {
4973 mkpath(mntpath, tmp, newpath);
4974 child = lstat(newpath, &sb) != -1;
4975 parent = lstat(xdirname(newpath), &psb) != -1;
4976 if (!child && !parent) {
4982 if (!tmp || !child || !S_ISDIR(sb.st_mode) || (child && parent && sb.st_dev == psb.st_dev)) {
4983 tmp = xreadline(NULL, messages[MSG_HOSTNAME]);
4986 if (name && (tmp[0] == '-') && (tmp[1] == '\0')) {
4987 mkpath(currentpath, name, newpath);
4993 mkpath(mntpath, tmp, newpath);
4995 if (!xdiraccess(newpath)) {
5000 #if defined(__APPLE__) || defined(__FreeBSD__)
5001 if (spawn(cmd, newpath, NULL, NULL, F_NORMAL)) {
5003 if (spawn(cmd, "-qu", newpath, NULL, F_NORMAL)) {
5005 if (!xconfirm(get_input(messages[MSG_LAZY])))
5009 if (spawn(cmd, "-l", newpath, NULL, F_NORMAL)) {
5010 #elif defined(__FreeBSD__)
5011 if (spawn(cmd, "-f", newpath, NULL, F_NORMAL)) {
5013 if (spawn(cmd, "-quz", newpath, NULL, F_NORMAL)) {
5015 printwait(messages[MSG_FAILED], presel);
5020 if (rmdir(newpath) == -1) {
5028 static void lock_terminal(void)
5030 spawn(xgetenv("NNN_LOCKER", utils[UTIL_LOCKER]), NULL, NULL, NULL, F_CLI);
5033 static void printkv(kv *kvarr, int fd, uchar_t max, uchar_t id)
5035 char *val = (id == NNN_BMS) ? bmstr : pluginstr;
5037 for (uchar_t i = 0; i < max && kvarr[i].key; ++i)
5038 dprintf(fd, " %c: %s\n", (char)kvarr[i].key, val + kvarr[i].off);
5041 static void printkeys(kv *kvarr, char *buf, uchar_t max)
5045 for (; i < max && kvarr[i].key; ++i) {
5047 buf[(i << 1) + 1] = kvarr[i].key;
5053 static size_t handle_bookmark(const char *bmark, char *newpath)
5058 if (maxbm || bmark) {
5059 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
5061 if (bmark) { /* There is a marked directory */
5067 printkeys(bookmark, g_buf + r - 1, maxbm);
5069 fd = get_input(NULL);
5073 if (fd == ',') /* Visit marked directory */
5074 bmark ? xstrsncpy(newpath, bmark, PATH_MAX) : (r = MSG_NOT_SET);
5075 else if (fd == '\r') { /* Visit bookmarks directory */
5076 mkpath(cfgpath, toks[TOK_BM], newpath);
5078 } else if (!get_kv_val(bookmark, newpath, fd, maxbm, NNN_BMS))
5079 r = MSG_INVALID_KEY;
5081 if (!r && chdir(newpath) == -1) {
5090 static void add_bookmark(char *path, char *newpath, int *presel)
5092 char *dir = xbasename(path);
5094 dir = xreadline(dir[0] ? dir : NULL, messages[MSG_BM_NAME]);
5096 size_t r = mkpath(cfgpath, toks[TOK_BM], newpath);
5098 newpath[r - 1] = '/';
5099 xstrsncpy(newpath + r, dir, PATH_MAX - r);
5100 printwait((symlink(path, newpath) == -1) ? strerror(errno) : newpath, presel);
5102 printwait(messages[MSG_CANCEL], presel);
5106 * The help string tokens (each line) start with a HEX value which indicates
5107 * the number of spaces to print before the particular token. In the middle,
5108 * %NN can be used to insert a run of spaces, e.g %10 will print 10 spaces.
5109 * %NN MUST be 2 characters long, e.g %05 for 5 spaces.
5111 * This method was chosen instead of a flat string because the number of bytes
5112 * in help was increasing the binary size by around a hundred bytes. This would
5113 * only have increased as we keep adding new options.
5115 static void show_help(const char *path)
5117 static const char helpstr[] = {
5125 "9Up k Up%16PgUp ^U Page up\n"
5126 "9Dn j Down%14PgDn ^D Page down\n"
5127 "9Lt h Parent%12~ ` @ - ~, /, start, prev\n"
5128 "5Ret Rt l Open%20' First file/match\n"
5129 "9g ^A Top%21J Jump to entry/offset\n"
5130 "9G ^E End%20^J Toggle auto-advance on open\n"
5131 "8B (,) Book(mark)%11b ^/ Select bookmark\n"
5132 "a1-4 Context%11(Sh)Tab Cycle/new context\n"
5133 "62Esc ^Q Quit%19^y Next young\n"
5134 "b^G QuitCD%18Q Pick/err, quit\n"
5137 "1FILTER & PROMPT\n"
5138 "c/ Filter%17^N Toggle type-to-nav\n"
5139 "aEsc Exit prompt%12^L Toggle last filter\n"
5140 "c. Toggle hidden%05Alt+Esc Unfilter, quit context\n"
5143 "9o ^O Open with%15n Create new/link\n"
5144 "9f ^F File stats%14d Detail mode toggle\n"
5145 "b^R Rename/dup%14r Batch rename\n"
5146 "cz Archive%17e Edit file\n"
5147 "c* Toggle exe%14> Export list\n"
5148 "6Space + (Un)select%12m-m Select range/clear\n"
5149 "ca Select all%14A Invert sel\n"
5150 "9p ^P Copy here%12w ^W Cp/mv sel as\n"
5151 "9v ^V Move here%15E Edit sel list\n"
5152 "9x ^X Delete%18S Listed sel size\n"
5153 "aEsc Send to FIFO\n"
5156 "8Alt ; Select plugin%11= Launch app\n"
5157 "9! ^] Shell%19] Cmd prompt\n"
5158 "cc Connect remote%10u Unmount remote/archive\n"
5159 "9t ^T Sort toggles%12s Manage session\n"
5160 "cT Set time type%110 Lock\n"
5161 "b^L Redraw%18? Help, conf\n"
5164 int fd = create_tmp_file();
5168 char *prog = xgetenv(env_cfg[NNN_HELP], NULL);
5170 get_output(prog, NULL, NULL, fd, FALSE);
5174 const char *end = helpstr + (sizeof helpstr - 1);
5175 for (const char *s = helpstr; s < end; ++s) {
5177 for (int k = 0, n = xchartohex(*s); k < n; ++k) *w++ = ' ';
5178 } else if (*s == '%') {
5179 int n = ((s[1] - '0') * 10) + (s[2] - '0');
5180 for (int k = 0; k < n; ++k) *w++ = ' ';
5187 if (write(fd, g_buf, w - g_buf)) {} // silence warning
5189 dprintf(fd, "\nLOCATIONS\n");
5190 for (uchar_t i = 0; i < CTX_MAX; ++i)
5191 if (g_ctx[i].c_cfg.ctxactive)
5192 dprintf(fd, " %u: %s\n", i + 1, g_ctx[i].c_path);
5194 dprintf(fd, "\nVOLUME: avail:%s ", coolsize(get_fs_info(path, VFS_AVAIL)));
5195 dprintf(fd, "used:%s ", coolsize(get_fs_info(path, VFS_USED)));
5196 dprintf(fd, "size:%s\n\n", coolsize(get_fs_info(path, VFS_SIZE)));
5199 dprintf(fd, "BOOKMARKS\n");
5200 printkv(bookmark, fd, maxbm, NNN_BMS);
5205 dprintf(fd, "PLUGIN KEYS\n");
5206 printkv(plug, fd, maxplug, NNN_PLUG);
5210 for (uchar_t i = NNN_OPENER; i <= NNN_TRASH; ++i) {
5211 char *s = getenv(env_cfg[i]);
5213 dprintf(fd, "%s: %s\n", env_cfg[i], s);
5217 dprintf(fd, "SELECTION FILE: %s\n", selpath);
5219 dprintf(fd, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
5222 spawn(pager, g_tmpfpath, NULL, NULL, F_CLI | F_TTY);
5226 static void setexports(void)
5232 setenv(envs[ENV_NCUR], pdents[cur].name, 1);
5233 xstrsncpy(g_ctx[cfg.curctx].c_name, pdents[cur].name, NAME_MAX + 1);
5234 } else if (g_ctx[cfg.curctx].c_name[0])
5235 g_ctx[cfg.curctx].c_name[0] = '\0';
5237 for (uchar_t i = 0; i < CTX_MAX; ++i) {
5238 if (g_ctx[i].c_cfg.ctxactive) {
5239 dvar[1] = fvar[1] = '1' + i;
5240 setenv(dvar, g_ctx[i].c_path, 1);
5242 if (g_ctx[i].c_name[0]) {
5243 mkpath(g_ctx[i].c_path, g_ctx[i].c_name, g_buf);
5244 setenv(fvar, g_buf, 1);
5248 setenv("NNN_INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
5249 setenv("NNN_PREFER_SELECTION", xitoa(cfg.prefersel), 1);
5252 static void run_cmd_as_plugin(const char *file, uchar_t flags)
5256 xstrsncpy(g_buf, file, PATH_MAX);
5258 len = xstrlen(g_buf);
5259 if (len > 1 && g_buf[len - 1] == '*') {
5260 flags &= ~F_CONFIRM; /* Skip user confirmation */
5261 g_buf[len - 1] = '\0'; /* Get rid of trailing no confirmation symbol */
5266 get_output(utils[UTIL_SH_EXEC], g_buf, NULL, -1, TRUE);
5268 spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, flags);
5271 static bool plctrl_init(void)
5275 /* g_tmpfpath is used to generate tmp file names */
5276 g_tmpfpath[tmpfplen - 1] = '\0';
5277 len = xstrsncpy(g_pipepath, g_tmpfpath, TMP_LEN_MAX);
5278 g_pipepath[len - 1] = '/';
5279 len = xstrsncpy(g_pipepath + len, "nnn-pipe.", TMP_LEN_MAX - len) + len;
5280 xstrsncpy(g_pipepath + len - 1, xitoa(getpid()), TMP_LEN_MAX - len);
5281 setenv(env_cfg[NNN_PIPE], g_pipepath, TRUE);
5283 return EXIT_SUCCESS;
5286 static void rmlistpath(void)
5289 DPRINTF_S(__func__);
5290 DPRINTF_S(listpath);
5291 spawn(utils[UTIL_RM_RF], listpath, NULL, NULL, F_NOTRACE | F_MULTI);
5292 /* Do not free if program was started in list mode */
5293 if (listpath != initpath)
5299 static ssize_t read_nointr(int fd, void *buf, size_t count)
5304 len = read(fd, buf, count);
5305 while (len == -1 && errno == EINTR);
5310 static char *readpipe(int fd, char *ctxnum, char **path)
5312 char ctx, *nextpath = NULL;
5314 if (read_nointr(fd, g_buf, 1) != 1)
5317 if (g_buf[0] == '-') { /* Clear selection on '-' */
5319 if (read_nointr(fd, g_buf, 1) != 1)
5323 if (g_buf[0] == '+')
5324 ctx = (char)(get_free_ctx() + 1);
5325 else if (g_buf[0] < '0')
5328 ctx = g_buf[0] - '0';
5333 if (read_nointr(fd, g_buf, 1) != 1)
5339 ssize_t len = read_nointr(fd, g_buf, PATH_MAX);
5344 g_buf[len] = '\0'; /* Terminate the path read */
5345 if (g_buf[0] == '/') {
5347 len = xstrlen(g_buf);
5348 while (--len && (g_buf[len] == '/')) /* Trim all trailing '/' */
5351 } else if (op == 'l') {
5352 rmlistpath(); /* Remove last list mode path, if any */
5353 nextpath = load_input(fd, *path);
5354 } else if (op == 'p') {
5367 static bool run_plugin(char **path, const char *file, char *runfile, char **lastname, char **lastdir)
5372 bool cmd_as_plugin = FALSE;
5375 if (!g_state.pluginit) {
5377 g_state.pluginit = 1;
5382 /* Check for run-cmd-as-plugin mode */
5384 flags = F_MULTI | F_CONFIRM;
5387 if (*file == '|') { /* Check if output should be paged */
5390 } else if (*file == '&') { /* Check if GUI flags are to be used */
5391 flags = F_MULTI | F_NOTRACE | F_NOWAIT;
5398 if ((flags & F_NOTRACE) || (flags & F_PAGE)) {
5399 run_cmd_as_plugin(file, flags);
5403 cmd_as_plugin = TRUE;
5406 if (mkfifo(g_pipepath, 0600) != 0)
5413 if (!p) { // In child
5414 int wfd = open(g_pipepath, O_WRONLY | O_CLOEXEC);
5417 _exit(EXIT_FAILURE);
5419 if (!cmd_as_plugin) {
5423 /* Generate absolute path to plugin */
5424 mkpath(plgpath, file, g_buf);
5427 sel = selpath ? selpath : std;
5429 if (runfile && runfile[0]) {
5430 xstrsncpy(*lastname, runfile, NAME_MAX);
5431 spawn(g_buf, *lastname, *path, sel, 0);
5433 spawn(g_buf, NULL, *path, sel, 0);
5435 run_cmd_as_plugin(file, flags);
5438 _exit(EXIT_SUCCESS);
5444 rfd = open(g_pipepath, O_RDONLY);
5445 while (rfd == -1 && errno == EINTR);
5447 nextpath = readpipe(rfd, &ctx, path);
5449 set_smart_ctx(ctx, nextpath, path, runfile, lastname, lastdir);
5453 /* wait for the child to finish. no zombies allowed */
5454 waitpid(p, NULL, 0);
5463 static bool launch_app(char *newpath)
5466 char *tmp = newpath;
5468 mkpath(plgpath, utils[UTIL_LAUNCH], newpath);
5470 if (!getutil(utils[UTIL_FZF]) || access(newpath, X_OK) < 0) {
5471 tmp = xreadline(NULL, messages[MSG_APP_NAME]);
5472 r = F_NOWAIT | F_NOTRACE | F_MULTI;
5475 if (tmp && *tmp) // NOLINT
5476 spawn(tmp, (r == F_NORMAL) ? "0" : NULL, NULL, NULL, r);
5481 /* Returns TRUE if at least one command was run */
5482 static bool prompt_run(void)
5485 char *cmdline, *next;
5486 int cnt_j, cnt_J, cmd_ret;
5489 const char *xargs_j = "xargs -0 -I{} %s < %s";
5490 const char *xargs_J = "xargs -0 %s < %s";
5491 char cmd[CMD_LEN_MAX + 32]; // 32 for xargs format strings
5495 if (g_state.picker || g_state.xprompt) {
5497 cmdline = xreadline(NULL, PROMPT);
5500 cmdline = getreadline("\n"PROMPT);
5502 // Check for an empty command
5503 if (!cmdline || !cmdline[0])
5507 lastcmd = xstrdup(cmdline);
5510 len = xstrlen(cmdline);
5514 while ((next = strstr(next, "%j"))) {
5517 // replace %j with {} for xargs later
5526 while ((next = strstr(next, "%J"))) {
5529 // %J should be the last thing in the command
5530 if (next == cmdline + len - 2) {
5531 cmdline[len - 2] = '\0';
5537 // We can't handle both %j and %J in a single command
5542 snprintf(cmd, CMD_LEN_MAX + 32, xargs_j, cmdline, selpath);
5544 snprintf(cmd, CMD_LEN_MAX + 32, xargs_J, cmdline, selpath);
5546 cmd_ret = spawn(shell, "-c", (cnt_j || cnt_J) ? cmd : cmdline, NULL, F_CLI | F_CONFIRM);
5547 if ((cnt_j || cnt_J) && cmd_ret == 0)
5554 static bool handle_cmd(enum action sel, char *newpath)
5556 endselection(FALSE);
5558 if (sel == SEL_LAUNCH)
5559 return launch_app(newpath);
5563 if (sel == SEL_PROMPT)
5564 return prompt_run();
5566 /* Set nnn nesting level */
5567 char *tmp = getenv(env_cfg[NNNLVL]);
5568 int r = tmp ? atoi(tmp) : 0;
5570 setenv(env_cfg[NNNLVL], xitoa(r + 1), 1);
5571 spawn(shell, NULL, NULL, NULL, F_CLI);
5572 setenv(env_cfg[NNNLVL], xitoa(r), 1);
5576 static void dentfree(void)
5582 /* Thread data cleanup */
5588 static void *du_thread(void *p_data)
5590 thread_data *pdata = (thread_data *)p_data;
5591 char *path[2] = {pdata->path, NULL};
5592 ullong_t tfiles = 0;
5593 blkcnt_t tblocks = 0;
5595 FTS *tree = fts_open(path, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR, 0);
5598 while ((node = fts_read(tree))) {
5599 if (node->fts_info & FTS_D) {
5600 if (g_state.interrupt)
5605 sb = node->fts_statp;
5607 if (cfg.apparentsz) {
5608 if (sb->st_size && DU_TEST)
5609 tblocks += sb->st_size;
5610 } else if (sb->st_blocks && DU_TEST)
5611 tblocks += sb->st_blocks;
5618 if (pdata->entnum >= 0)
5619 pdents[pdata->entnum].blocks = tblocks;
5621 if (!pdata->mntpoint) {
5622 core_blocks[pdata->core] += tblocks;
5623 core_files[pdata->core] += tfiles;
5625 core_files[pdata->core] += 1;
5627 pthread_mutex_lock(&running_mutex);
5628 threadbmp |= (1 << pdata->core);
5630 pthread_mutex_unlock(&running_mutex);
5635 static void dirwalk(char *path, int entnum, bool mountpoint)
5637 /* Loop till any core is free */
5638 while (active_threads == NUM_DU_THREADS);
5640 if (g_state.interrupt)
5643 pthread_mutex_lock(&running_mutex);
5644 int core = ffs(threadbmp) - 1;
5646 threadbmp &= ~(1 << core);
5648 pthread_mutex_unlock(&running_mutex);
5650 xstrsncpy(core_data[core].path, path, PATH_MAX);
5651 core_data[core].entnum = entnum;
5652 core_data[core].core = (ushort_t)core;
5653 core_data[core].mntpoint = mountpoint;
5657 pthread_create(&tid, NULL, du_thread, (void *)&(core_data[core]));
5660 addstr(xbasename(path));
5661 addstr(" [^C aborts]\n");
5665 static bool prep_threads(void)
5667 if (!g_state.duinit) {
5669 threadbmp >>= (32 - NUM_DU_THREADS);
5672 core_blocks = calloc(NUM_DU_THREADS, sizeof(blkcnt_t));
5674 core_data = calloc(NUM_DU_THREADS, sizeof(thread_data));
5676 core_files = calloc(NUM_DU_THREADS, sizeof(ullong_t));
5678 if (!core_blocks || !core_data || !core_files) {
5683 /* Increase current open file descriptor limit */
5686 g_state.duinit = TRUE;
5688 memset(core_blocks, 0, NUM_DU_THREADS * sizeof(blkcnt_t));
5689 memset(core_data, 0, NUM_DU_THREADS * sizeof(thread_data));
5690 memset(core_files, 0, NUM_DU_THREADS * sizeof(ullong_t));
5695 /* Skip self and parent */
5696 static inline bool selforparent(const char *path)
5698 return path[0] == '.' && (path[1] == '\0' || (path[1] == '.' && path[2] == '\0'));
5701 static int dentfill(char *path, struct entry **ppdents)
5703 uchar_t entflags = 0;
5706 char *namep, *pnb, *buf;
5707 struct entry *dentp;
5708 size_t off = 0, namebuflen = NAMEBUF_INCR;
5709 struct stat sb_path, sb;
5710 DIR *dirp = opendir(path);
5713 gtimesecs = time(NULL);
5715 DPRINTF_S(__func__);
5720 int fd = dirfd(dirp);
5727 if (fstatat(fd, path, &sb_path, 0) == -1)
5731 ihashbmp = calloc(1, HASH_OCTETS << 3);
5735 memset(ihashbmp, 0, HASH_OCTETS << 3);
5737 if (!prep_threads())
5740 attron(COLOR_PAIR(cfg.curctx + 1));
5743 #if _POSIX_C_SOURCE >= 200112L
5744 posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
5751 #if defined(__sun) || defined(__HAIKU__)
5752 flags = AT_SYMLINK_NOFOLLOW; /* no d_type */
5754 if (cfg.blkorder || dp->d_type == DT_UNKNOWN) {
5756 * Optimization added for filesystems which support dirent.d_type
5759 * - the symlink size is set to 0
5760 * - the modification time of the symlink is set to that of the target file
5762 flags = AT_SYMLINK_NOFOLLOW;
5769 if (selforparent(namep))
5772 if (!cfg.showhidden && namep[0] == '.') {
5776 if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
5779 if (S_ISDIR(sb.st_mode)) {
5780 if (sb_path.st_dev == sb.st_dev) { // NOLINT
5781 mkpath(path, namep, buf); // NOLINT
5782 dirwalk(buf, -1, FALSE);
5784 if (g_state.interrupt)
5788 /* Do not recount hard links */
5789 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5790 dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5797 if (fstatat(fd, namep, &sb, flags) == -1) {
5798 if (flags || (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)) {
5803 DPRINTF_S(strerror(errno));
5806 entflags = FILE_MISSING;
5807 memset(&sb, 0, sizeof(struct stat));
5808 } else /* Orphaned symlink */
5809 entflags = SYM_ORPHAN;
5812 if (ndents == total_dents) {
5814 while (active_threads);
5816 total_dents += ENTRY_INCR;
5817 *ppdents = xrealloc(*ppdents, total_dents * sizeof(**ppdents));
5823 DPRINTF_P(*ppdents);
5826 /* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
5827 if (namebuflen - off < NAME_MAX + 1) {
5828 namebuflen += NAMEBUF_INCR;
5831 pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
5837 DPRINTF_P(pnamebuf);
5839 /* realloc() may result in memory move, we must re-adjust if that happens */
5840 if (pnb != pnamebuf) {
5842 dentp->name = pnamebuf;
5844 for (int count = 1; count < ndents; ++dentp, ++count)
5845 /* Current file name starts at last file name start + length */
5846 (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
5850 dentp = *ppdents + ndents;
5852 /* Selection file name */
5853 dentp->name = (char *)((size_t)pnamebuf + off);
5854 dentp->nlen = xstrsncpy(dentp->name, namep, NAME_MAX + 1);
5857 /* Copy other fields */
5858 if (cfg.timetype == T_MOD) {
5859 dentp->sec = sb.st_mtime;
5861 dentp->nsec = (uint_t)sb.st_mtimespec.tv_nsec;
5863 dentp->nsec = (uint_t)sb.st_mtim.tv_nsec;
5865 } else if (cfg.timetype == T_ACCESS) {
5866 dentp->sec = sb.st_atime;
5868 dentp->nsec = (uint_t)sb.st_atimespec.tv_nsec;
5870 dentp->nsec = (uint_t)sb.st_atim.tv_nsec;
5873 dentp->sec = sb.st_ctime;
5875 dentp->nsec = (uint_t)sb.st_ctimespec.tv_nsec;
5877 dentp->nsec = (uint_t)sb.st_ctim.tv_nsec;
5881 if ((gtimesecs - sb.st_mtime <= 300) || (gtimesecs - sb.st_ctime <= 300))
5882 entflags |= FILE_YOUNG;
5884 #if !(defined(__sun) || defined(__HAIKU__))
5885 if (!flags && dp->d_type == DT_LNK) {
5886 /* Do not add sizes for links */
5887 dentp->mode = (sb.st_mode & ~S_IFMT) | S_IFLNK;
5888 dentp->size = listpath ? sb.st_size : 0;
5890 dentp->mode = sb.st_mode;
5891 dentp->size = sb.st_size;
5894 dentp->mode = sb.st_mode;
5895 dentp->size = sb.st_size;
5899 dentp->uid = sb.st_uid;
5900 dentp->gid = sb.st_gid;
5903 dentp->flags = S_ISDIR(sb.st_mode) ? 0 : ((sb.st_nlink > 1) ? HARD_LINK : 0);
5905 dentp->flags |= entflags;
5910 if (S_ISDIR(sb.st_mode)) {
5911 mkpath(path, namep, buf); // NOLINT
5913 /* Need to show the disk usage of this dir */
5914 dirwalk(buf, ndents, (sb_path.st_dev != sb.st_dev)); // NOLINT
5916 if (g_state.interrupt)
5919 dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
5920 /* Do not recount hard links */
5921 if (sb.st_nlink <= 1 || test_set_bit((uint_t)sb.st_ino))
5922 dir_blocks += dentp->blocks;
5928 /* Flag if this is a dir or symlink to a dir */
5929 if (S_ISLNK(sb.st_mode)) {
5931 fstatat(fd, namep, &sb, 0);
5934 if (S_ISDIR(sb.st_mode))
5935 dentp->flags |= DIR_OR_DIRLNK;
5936 #if !(defined(__sun) || defined(__HAIKU__)) /* no d_type */
5937 } else if (dp->d_type == DT_DIR || ((dp->d_type == DT_LNK
5938 || dp->d_type == DT_UNKNOWN) && S_ISDIR(sb.st_mode))) {
5939 dentp->flags |= DIR_OR_DIRLNK;
5944 } while ((dp = readdir(dirp)));
5947 if (g_state.duinit && cfg.blkorder) {
5948 while (active_threads);
5950 attroff(COLOR_PAIR(cfg.curctx + 1));
5951 for (int i = 0; i < NUM_DU_THREADS; ++i) {
5952 num_files += core_files[i];
5953 dir_blocks += core_blocks[i];
5957 /* Should never be null */
5958 if (closedir(dirp) == -1)
5964 static void populate(char *path, char *lastname)
5967 struct timespec ts1, ts2;
5969 clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
5972 ndents = dentfill(path, &pdents);
5977 ENTSORT(pdents, ndents, entrycmpfn);
5981 clock_gettime(CLOCK_REALTIME, &ts2);
5982 DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
5985 /* Find cur from history */
5986 /* No NULL check for lastname, always points to an array */
5987 move_cursor(*lastname ? dentfind(lastname, ndents) : 0, 0);
5989 // Force full redraw
5990 last_curscroll = -1;
5994 static void notify_fifo(bool force)
6000 fifofd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC);
6003 /* Unexpected error, the FIFO file might have been removed */
6004 /* We give up FIFO notification */
6010 static struct entry lastentry;
6012 if (!force && !memcmp(&lastentry, &pdents[cur], sizeof(struct entry))) // NOLINT
6015 lastentry = pdents[cur];
6017 char path[PATH_MAX];
6018 size_t len = mkpath(g_ctx[cfg.curctx].c_path, ndents ? pdents[cur].name : "", path);
6020 path[len - 1] = '\n';
6022 ssize_t ret = write(fifofd, path, len);
6024 if (ret != (ssize_t)len && !(ret == -1 && (errno == EAGAIN || errno == EPIPE))) {
6025 DPRINTF_S(strerror(errno));
6029 static void send_to_explorer(int *presel)
6032 int fd = open(fifopath, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0600);
6033 if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
6042 notify_fifo(TRUE); /* Send opened path to NNN_FIFO */
6046 static void move_cursor(int target, int ignore_scrolloff)
6048 int onscreen = xlines - 4; /* Leave top 2 and bottom 2 lines */
6050 target = MAX(0, MIN(ndents - 1, target));
6051 last_curscroll = curscroll;
6055 if (!ignore_scrolloff) {
6056 int delta = target - last;
6057 int scrolloff = MIN(SCROLLOFF, onscreen >> 1);
6060 * When ignore_scrolloff is 1, the cursor can jump into the scrolloff
6061 * margin area, but when ignore_scrolloff is 0, act like a boa
6062 * constrictor and squeeze the cursor towards the middle region of the
6063 * screen by allowing it to move inward and disallowing it to move
6064 * outward (deeper into the scrolloff margin area).
6066 if (((cur < (curscroll + scrolloff)) && delta < 0)
6067 || ((cur > (curscroll + onscreen - scrolloff - 1)) && delta > 0))
6070 curscroll = MIN(curscroll, MIN(cur, ndents - onscreen));
6071 curscroll = MAX(curscroll, MAX(cur - (onscreen - 1), 0));
6074 if (!g_state.fifomode)
6075 notify_fifo(FALSE); /* Send hovered path to NNN_FIFO */
6079 static void handle_screen_move(enum action sel)
6085 if (cfg.rollover || (cur != ndents - 1))
6086 move_cursor((cur + 1) % ndents, 0);
6089 if (cfg.rollover || cur)
6090 move_cursor((cur + ndents - 1) % ndents, 0);
6093 onscreen = xlines - 4;
6094 move_cursor(curscroll + (onscreen - 1), 1);
6095 curscroll += onscreen - 1;
6098 onscreen = xlines - 4;
6099 move_cursor(curscroll + (onscreen - 1), 1);
6100 curscroll += onscreen >> 1;
6103 onscreen = xlines - 4;
6104 move_cursor(curscroll, 1);
6105 curscroll -= onscreen - 1;
6108 onscreen = xlines - 4;
6109 move_cursor(curscroll, 1);
6110 curscroll -= onscreen >> 1;
6114 char *input = xreadline(NULL, "jump (+n/-n/n): ");
6116 if (!input || !*input)
6118 if (input[0] == '-') {
6119 cur -= atoi(input + 1);
6122 } else if (input[0] == '+') {
6123 cur += atoi(input + 1);
6127 int index = atoi(input);
6129 if ((index < 1) || (index > ndents))
6133 onscreen = xlines - 4;
6134 move_cursor(cur, 1);
6135 curscroll -= onscreen >> 1;
6142 move_cursor(ndents - 1, 1);
6146 for (int r = cur;;) {
6151 if (pdents[r].flags & FILE_YOUNG) {
6158 default: /* case SEL_FIRST */
6160 int c = get_input(messages[MSG_FIRST]);
6167 int r = (c == TOUPPER(*pdents[cur].name)) ? (cur + 1) : 0;
6169 for (; r < ndents; ++r) {
6170 if (((c == '\'') && !(pdents[r].flags & DIR_OR_DIRLNK))
6171 || (c == TOUPPER(*pdents[r].name))) {
6172 move_cursor((r) % ndents, 0);
6181 static void handle_openwith(const char *path, const char *name, char *newpath, char *tmp)
6183 /* Confirm if app is CLI or GUI */
6184 int r = get_input(messages[MSG_CLI_MODE]);
6186 r = (r == 'c' ? F_CLI :
6187 ((r == 'g' || r == '\r') ? (F_NOWAIT | F_NOTRACE | F_MULTI) : 0));
6189 mkpath(path, name, newpath);
6190 spawn(tmp, newpath, NULL, NULL, r);
6194 static void copynextname(char *lastname)
6197 cur += (cur != (ndents - 1)) ? 1 : -1;
6203 static int handle_context_switch(enum action sel)
6208 case SEL_CYCLE: // fallthrough
6210 /* visit next and previous contexts */
6212 if (sel == SEL_CYCLE)
6214 r = (r + 1) & ~CTX_MAX;
6215 while (!g_ctx[r].c_cfg.ctxactive);
6217 do /* Attempt to create a new context */
6218 r = (r + 1) & ~CTX_MAX;
6219 while (g_ctx[r].c_cfg.ctxactive && (r != cfg.curctx));
6221 if (r == cfg.curctx) /* If all contexts are active, reverse cycle */
6223 r = (r + (CTX_MAX - 1)) & (CTX_MAX - 1);
6224 while (!g_ctx[r].c_cfg.ctxactive);
6226 default: /* SEL_CTXN */
6227 if (sel >= SEL_CTX1) /* CYCLE keys are lesser in value */
6228 r = sel - SEL_CTX1; /* Save the next context id */
6230 if (cfg.curctx == r) {
6231 if (sel == SEL_CYCLE)
6232 (r == CTX_MAX - 1) ? (r = 0) : ++r;
6233 else if (sel == SEL_CYCLER)
6234 (r == 0) ? (r = CTX_MAX - 1) : --r;
6243 static int set_sort_flags(int r)
6245 bool session = (r == '\0');
6246 bool reverse = FALSE;
6248 if (ISUPPER_(r) && (r != 'R') && (r != 'C')) {
6253 /* Set the correct input in case of a session load */
6255 if (cfg.apparentsz) {
6258 } else if (cfg.blkorder) {
6263 /* Ensure function pointers are in sync with cfg. */
6264 entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
6265 namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
6266 } else if (r == CONTROL('T')) {
6267 /* Cycling order: clear -> size -> time -> clear */
6270 else if (cfg.sizeorder)
6277 case 'a': /* Apparent du */
6278 cfg.apparentsz ^= 1;
6279 if (cfg.apparentsz) {
6285 case 'd': /* Disk usage */
6287 if (!cfg.apparentsz)
6290 blk_shift = ffs(S_BLKSIZE) - 1;
6300 entrycmpfn = &entrycmp;
6302 endselection(TRUE); /* We are going to reload dir */
6312 entrycmpfn = &entrycmp;
6313 namecmpfn = &xstricmp;
6315 case 'e': /* File extension */
6322 entrycmpfn = &entrycmp;
6324 case 'r': /* Reverse sort */
6326 entrycmpfn = cfg.reverse ? &reventrycmp : &entrycmp;
6328 case 's': /* File size */
6335 entrycmpfn = &entrycmp;
6337 case 't': /* Time */
6344 entrycmpfn = &entrycmp;
6346 case 'v': /* Version */
6348 namecmpfn = cfg.version ? &xstrverscasecmp : &xstricmp;
6361 entrycmpfn = &reventrycmp;
6364 cfgsort[cfg.curctx] = (uchar_t)r;
6369 static bool set_time_type(int *presel)
6372 char buf[] = "'a'ccess / 'c'hange / 'm'od [ ]";
6374 buf[sizeof(buf) - 3] = cfg.timetype == T_MOD ? 'm' : (cfg.timetype == T_ACCESS ? 'a' : 'c');
6376 int r = get_input(buf);
6378 if (r == 'a' || r == 'c' || r == 'm') {
6379 r = (r == 'm') ? T_MOD : ((r == 'a') ? T_ACCESS : T_CHANGE);
6380 if (cfg.timetype != r) {
6383 if (cfg.filtermode || g_ctx[cfg.curctx].c_fltr[1])
6390 r = MSG_INVALID_KEY;
6393 printwait(messages[r], presel);
6398 static void statusbar(char *path)
6402 pEntry pent = &pdents[cur];
6409 /* Get the file extension for regular files */
6410 if (S_ISREG(pent->mode)) {
6411 i = (int)(pent->nlen - 1);
6412 ptr = xextension(pent->name, i);
6414 len = i - (ptr - pent->name);
6415 if (!ptr || len > 5 || len < 2)
6420 attron(COLOR_PAIR(cfg.curctx + 1));
6422 if (cfg.fileinfo && get_output("file", "-b", pdents[cur].name, -1, FALSE))
6423 mvaddstr(xlines - 2, 2, g_buf);
6427 printw("%d/%s ", cur + 1, xitoa(ndents));
6429 if (g_state.selmode || nselected) {
6432 if (g_state.rangesel)
6434 else if (g_state.selmode)
6437 addstr(xitoa(nselected));
6443 if (cfg.blkorder) { /* du mode */
6446 xstrsncpy(buf, coolsize(dir_blocks << blk_shift), 12);
6448 printw("%cu:%s avail:%s files:%llu %lluB %s\n",
6449 (cfg.apparentsz ? 'a' : 'd'), buf, coolsize(get_fs_info(path, VFS_AVAIL)),
6450 num_files, (ullong_t)pent->blocks << blk_shift, ptr);
6451 } else { /* light or detail mode */
6452 char sort[] = "\0\0\0\0\0";
6454 if (getorderstr(sort))
6458 print_time(&pent->sec, pent->flags);
6461 addstr(get_lsperms(pent->mode));
6464 if (g_state.uidgid) {
6465 addstr(getpwname(pent->uid));
6467 addstr(getgrname(pent->gid));
6471 if (S_ISLNK(pent->mode)) {
6472 if (!cfg.fileinfo) {
6473 i = readlink(pent->name, g_buf, PATH_MAX);
6474 addstr(coolsize(i >= 0 ? i : pent->size)); /* Show symlink size */
6475 if (i > 1) { /* Show symlink target */
6479 getyx(stdscr, len, y);
6480 i = MIN(i, xcols - y);
6486 addstr(coolsize(pent->size));
6489 if (pent->flags & HARD_LINK) {
6492 if (stat(pent->name, &sb) != -1) {
6494 addstr(xitoa((int)sb.st_nlink)); /* Show number of links */
6496 addstr(xitoa((int)sb.st_ino)); /* Show inode number */
6503 attroff(COLOR_PAIR(cfg.curctx + 1));
6504 /* Place HW cursor on current for Braille systems */
6508 static inline void markhovered(void)
6510 if (cfg.showdetail && ndents) { /* Bold forward arrowhead */
6512 addch('>' | A_BOLD);
6516 static int adjust_cols(int n)
6518 /* Calculate the number of cols available to print entry name */
6519 #ifdef ICONS_ENABLED
6520 n -= (g_state.oldcolor ? 0 : ICON_SIZE + ICON_PADDING_LEFT_LEN + ICON_PADDING_RIGHT_LEN);
6522 if (cfg.showdetail) {
6523 /* Fallback to light mode if less than 35 columns */
6525 cfg.showdetail ^= 1;
6526 else /* 2 more accounted for below */
6530 /* 2 columns for preceding space and indicator */
6534 static void draw_line(int ncols)
6538 ncols = adjust_cols(ncols);
6540 if (g_state.oldcolor && (pdents[last].flags & DIR_OR_DIRLNK)) {
6541 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6545 move(2 + last - curscroll, 0);
6547 printent(&pdents[last], ncols, FALSE);
6549 if (g_state.oldcolor && (pdents[cur].flags & DIR_OR_DIRLNK)) {
6550 if (!dir) {/* First file is not a directory */
6551 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6554 } else if (dir) { /* Second file is not a directory */
6555 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6559 move(2 + cur - curscroll, 0);
6561 printent(&pdents[cur], ncols, TRUE);
6563 /* Must reset e.g. no files in dir */
6565 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6570 static void redraw(char *path)
6572 getmaxyx(stdscr, xlines, xcols);
6574 int ncols = (xcols <= PATH_MAX) ? xcols : PATH_MAX;
6575 int onscreen = xlines - 4;
6582 if (ndents && (last_curscroll == curscroll))
6583 return draw_line(ncols);
6586 DPRINTF_S(__func__);
6591 /* Enforce scroll/cursor invariants */
6592 move_cursor(cur, 1);
6594 /* Fail redraw if < than 10 columns, context info prints 10 chars */
6595 if (ncols <= MIN_DISPLAY_COL) {
6596 printmsg(messages[MSG_FEW_COLUMNS]);
6603 for (i = 0; i < CTX_MAX; ++i) { /* 8 chars printed for contexts - "1 2 3 4 " */
6604 if (!g_ctx[i].c_cfg.ctxactive)
6607 addch((i + '1') | (COLOR_PAIR(i + 1) | A_BOLD
6608 /* active: underline, current: reverse */
6609 | ((cfg.curctx != i) ? A_UNDERLINE : A_REVERSE)));
6614 attron(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6617 bool in_home = set_tilde_in_path(path);
6618 char *ptr = in_home ? &path[homelen - 1] : path;
6620 i = (int)xstrlen(ptr);
6621 if ((i + MIN_DISPLAY_COL) <= ncols)
6622 addnstr(ptr, ncols - MIN_DISPLAY_COL);
6624 char *base = xmemrchr((uchar_t *)ptr, '/', i);
6633 if (ptr && (base != ptr)) {
6634 while (ptr < base) {
6636 i += 2; /* 2 characters added */
6637 if (ncols < i + MIN_DISPLAY_COL) {
6638 base = NULL; /* Can't print more characters */
6650 addnstr(base, ncols - (MIN_DISPLAY_COL + i));
6654 reset_tilde_in_path(path);
6656 attroff(A_UNDERLINE | COLOR_PAIR(cfg.curctx + 1));
6658 /* Go to first entry */
6659 if (curscroll > 0) {
6661 #ifdef ICONS_ENABLED
6662 addstr(ICON_ARROW_UP);
6668 if (g_state.oldcolor) {
6669 attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6670 g_state.dircolor = 1;
6673 onscreen = MIN(onscreen + curscroll, ndents);
6675 ncols = adjust_cols(ncols);
6677 int len = scanselforpath(path, FALSE);
6680 for (i = curscroll; i < onscreen; ++i) {
6684 findmarkentry(len, &pdents[i]);
6686 printent(&pdents[i], ncols, i == cur);
6689 /* Must reset e.g. no files in dir */
6690 if (g_state.dircolor) {
6691 attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
6692 g_state.dircolor = 0;
6695 /* Go to last entry */
6696 if (onscreen < ndents) {
6697 move(xlines - 2, 0);
6698 #ifdef ICONS_ENABLED
6699 addstr(ICON_ARROW_DOWN);
6708 static bool cdprep(char *lastdir, char *lastname, char *path, char *newpath)
6713 /* Save last working directory */
6714 xstrsncpy(lastdir, path, PATH_MAX);
6716 /* Save the newly opted dir in path */
6717 xstrsncpy(path, newpath, PATH_MAX);
6721 return cfg.filtermode;
6724 static void showselsize(const char *path)
6727 int len = scanselforpath(path, FALSE);
6729 for (int r = 0, selcount = nselected; (r < ndents) && selcount; ++r)
6730 if (findinsel(findselpos, len + xstrsncpy(g_sel + len, pdents[r].name, pdents[r].nlen))) {
6731 sz += cfg.blkorder ? pdents[r].blocks : pdents[r].size;
6735 printmsg(coolsize(cfg.blkorder ? sz << blk_shift : sz));
6738 static bool browse(char *ipath, const char *session, int pkey)
6740 alignas(max_align_t) char newpath[PATH_MAX];
6741 alignas(max_align_t) char runfile[NAME_MAX + 1];
6742 char *path, *lastdir, *lastname, *dir, *tmp;
6746 int r = -1, presel, selstartid = 0, selendid = 0;
6747 const uchar_t opener_flags = (cfg.cliopener ? F_CLI : (F_NOTRACE | F_NOSTDIN | F_NOWAIT));
6748 bool watch = FALSE, cd = TRUE;
6753 struct timespec mousetimings[2] = {{.tv_sec = 0, .tv_nsec = 0}, {.tv_sec = 0, .tv_nsec = 0}};
6754 int mousedent[2] = {-1, -1};
6755 bool currentmouse = 1, rightclicksel = 0;
6760 getmaxyx(stdscr, xlines, xcols);
6763 /* set-up first context */
6764 if (!session || !load_session(session, &path, &lastdir, &lastname, FALSE)) {
6768 g_ctx[0].c_last[0] = '\0';
6769 lastdir = g_ctx[0].c_last; /* last visited directory */
6771 if (g_state.initfile) {
6772 xstrsncpy(g_ctx[0].c_name, xbasename(ipath), sizeof(g_ctx[0].c_name));
6775 g_ctx[0].c_name[0] = '\0';
6777 lastname = g_ctx[0].c_name; /* last visited file name */
6779 xstrsncpy(g_ctx[0].c_path, ipath, PATH_MAX);
6780 /* If the initial path is a file, retain a way to return to start dir */
6781 if (g_state.initfile) {
6783 initpath = ipath = getcwd(NULL, 0);
6785 path = g_ctx[0].c_path; /* current directory */
6787 g_ctx[0].c_fltr[0] = g_ctx[0].c_fltr[1] = '\0';
6788 g_ctx[0].c_cfg = cfg; /* current configuration */
6793 newpath[0] = runfile[0] = '\0';
6795 presel = pkey ? ((pkey == CREATE_NEW_KEY) ? 'n' : ';') : ((cfg.filtermode
6796 || (session && (g_ctx[cfg.curctx].c_fltr[0] == FILTER
6797 || g_ctx[cfg.curctx].c_fltr[0] == RFILTER)
6798 && g_ctx[cfg.curctx].c_fltr[1])) ? FILTER : 0);
6800 pdents = xrealloc(pdents, total_dents * sizeof(struct entry));
6804 /* Allocate buffer to hold names */
6805 pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
6809 /* The following call is added to handle a broken window at start */
6810 if (presel == FILTER)
6811 handle_key_resize();
6815 * Can fail when permissions change while browsing.
6816 * It's assumed that path IS a directory when we are here.
6818 if (chdir(path) == -1) {
6819 DPRINTF_S("directory inaccessible");
6820 valid_parent(path, lastname);
6828 #ifdef LINUX_INOTIFY
6829 if ((presel == FILTER || watch) && inotify_wd >= 0) {
6830 inotify_rm_watch(inotify_fd, inotify_wd);
6834 #elif defined(BSD_KQUEUE)
6835 if ((presel == FILTER || watch) && event_fd >= 0) {
6840 #elif defined(HAIKU_NM)
6841 if ((presel == FILTER || watch) && haiku_hnd != NULL) {
6842 haiku_stop_watch(haiku_hnd);
6843 haiku_nm_active = FALSE;
6849 if (cfgsort[cfg.curctx] != '0') {
6850 if (cfgsort[cfg.curctx] == 'z')
6851 set_sort_flags('c');
6852 if ((!cfgsort[cfg.curctx] || (cfgsort[cfg.curctx] == 'c'))
6853 && ((r = get_kv_key(order, path, maxorder, NNN_ORDER)) > 0)) { // NOLINT
6855 cfgsort[cfg.curctx] = 'z';
6858 cfgsort[cfg.curctx] = cfgsort[CTX_MAX];
6862 populate(path, lastname);
6863 if (g_state.interrupt) {
6864 g_state.interrupt = cfg.apparentsz = cfg.blkorder = 0;
6865 blk_shift = BLK_SHIFT_512;
6866 presel = CONTROL('L');
6869 #ifdef LINUX_INOTIFY
6870 if (presel != FILTER && inotify_wd == -1)
6871 inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
6872 #elif defined(BSD_KQUEUE)
6873 if (presel != FILTER && event_fd == -1) {
6874 #if defined(O_EVTONLY)
6875 event_fd = open(path, O_EVTONLY);
6877 event_fd = open(path, O_RDONLY);
6880 EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
6881 EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
6883 #elif defined(HAIKU_NM)
6884 haiku_nm_active = haiku_watch_dir(haiku_hnd, path) == EXIT_SUCCESS;
6888 /* Do not do a double redraw in filterentries */
6889 if ((presel != FILTER) || !filterset()) {
6895 /* Exit if parent has exited */
6897 _exit(EXIT_FAILURE);
6899 /* If CWD is deleted or moved or perms changed, find an accessible parent */
6900 if (chdir(path) == -1)
6903 /* If STDIN is no longer a tty (closed) we should exit */
6904 if (!isatty(STDIN_FILENO) && !g_state.picker)
6905 return EXIT_FAILURE;
6907 sel = nextsel(presel);
6914 if (getmouse(&event) != OK)
6917 /* Handle clicking on a context at the top */
6918 if (event.bstate == BUTTON1_PRESSED && event.y == 0) {
6919 /* Get context from: "[1 2 3 4]..." */
6922 /* If clicked after contexts, go to parent */
6925 else if (r >= 0 && r != cfg.curctx) {
6926 savecurctx(path, ndents ? pdents[cur].name : NULL, r);
6928 /* Reset the pointers */
6929 path = g_ctx[r].c_path;
6930 lastdir = g_ctx[r].c_last;
6931 lastname = g_ctx[r].c_name;
6941 if (sel == SEL_BACK) {
6943 dir = visit_parent(path, newpath, &presel);
6948 xstrsncpy(lastname, xbasename(path), NAME_MAX + 1);
6950 cdprep(lastdir, NULL, path, dir) ? (presel = FILTER) : (watch = TRUE);
6957 /* Middle click action */
6958 if (event.bstate == BUTTON2_PRESSED) {
6959 presel = middle_click_key;
6962 #if NCURSES_MOUSE_VERSION > 1
6964 if (event.bstate == BUTTON4_PRESSED && ndents && (cfg.rollover || cur)) {
6965 move_cursor((!cfg.rollover && cur < scroll_lines
6966 ? 0 : (cur + ndents - scroll_lines) % ndents), 0);
6971 if (event.bstate == BUTTON5_PRESSED && ndents
6972 && (cfg.rollover || (cur != ndents - 1))) {
6973 move_cursor((!cfg.rollover && cur >= ndents - scroll_lines)
6974 ? (ndents - 1) : ((cur + scroll_lines) % ndents), 0);
6979 /* Toggle filter mode on left click on last 2 lines */
6980 if (event.y >= xlines - 2 && event.bstate == BUTTON1_PRESSED) {
6982 cfg.filtermode ^= 1;
6983 if (cfg.filtermode) {
6988 /* Start watching the directory */
6995 /* Handle clicking on a file */
6996 if (event.y >= 2 && event.y <= ndents + 1 &&
6997 (event.bstate == BUTTON1_PRESSED ||
6998 event.bstate == BUTTON3_PRESSED)) {
6999 r = curscroll + (event.y - 2);
7003 else if ((event.bstate == BUTTON1_PRESSED) && !g_state.fifomode)
7004 notify_fifo(TRUE); /* Send clicked path to NNN_FIFO */
7006 /* Handle right click selection */
7007 if (event.bstate == BUTTON3_PRESSED) {
7015 #if defined(CLOCK_MONOTONIC_RAW)
7016 CLOCK_MONOTONIC_RAW,
7017 #elif defined(CLOCK_MONOTONIC)
7022 &mousetimings[currentmouse]);
7023 mousedent[currentmouse] = cur;
7025 /* Single click just selects, double click falls through to SEL_OPEN */
7026 if ((mousedent[0] != mousedent[1]) ||
7027 (((_ABSSUB(mousetimings[0].tv_sec, mousetimings[1].tv_sec) << 30)
7028 + (_ABSSUB(mousetimings[0].tv_nsec, mousetimings[1].tv_nsec)))
7029 > DBLCLK_INTERVAL_NS))
7032 mousetimings[currentmouse].tv_sec = 0;
7033 mousedent[currentmouse] = -1;
7036 if (cfg.filtermode || filterset())
7043 case SEL_NAV_IN: // fallthrough
7045 /* Cannot descend in empty directories */
7048 g_state.selbm = g_state.runplugin = 0;
7052 pent = &pdents[cur];
7053 if (!g_state.selbm || !(S_ISLNK(pent->mode) &&
7054 realpath(pent->name, newpath) &&
7055 xstrsncpy(path, lastdir, PATH_MAX)))
7056 mkpath(path, pent->name, newpath);
7060 /* Visit directory */
7061 if (pent->flags & DIR_OR_DIRLNK) {
7062 if (chdir(newpath) == -1) {
7067 cdprep(lastdir, lastname, path, newpath) ? (presel = FILTER) : (watch = TRUE);
7071 /* Cannot use stale data in entry, file may be missing by now */
7072 if (stat(newpath, &sb) == -1) {
7076 DPRINTF_U(sb.st_mode);
7078 /* Do not open non-regular files */
7079 if (!S_ISREG(sb.st_mode)) {
7080 printwait(messages[MSG_UNSUPPORTED], &presel);
7084 /* Handle plugin selection mode */
7085 if (g_state.runplugin) {
7086 g_state.runplugin = 0;
7087 /* Must be in plugin dir and same context to select plugin */
7088 if ((g_state.runctx == cfg.curctx) && !strcmp(path, plgpath)) {
7089 endselection(FALSE);
7090 /* Copy path so we can return back to earlier dir */
7091 xstrsncpy(path, lastdir, PATH_MAX);
7094 if (chdir(path) == -1
7095 || !run_plugin(&path, pent->name, runfile, &lastname, &lastdir)) {
7096 DPRINTF_S("plugin failed!");
7100 return EXIT_SUCCESS;
7103 xstrsncpy(lastname, runfile, NAME_MAX + 1);
7112 if (g_state.fifomode && (sel == SEL_OPEN)) {
7113 send_to_explorer(&presel); /* Write selection to explorer fifo */
7117 /* If opened as vim plugin and Enter/^M pressed, pick */
7118 if (g_state.picker && (sel == SEL_OPEN)) {
7119 if (nselected == 0) /* Pick if none selected */
7120 appendfpath(newpath, mkpath(path, pent->name, newpath));
7121 return EXIT_SUCCESS;
7124 if (sel == SEL_NAV_IN) {
7125 /* If in listing dir, go to target on `l` or Right on symlink */
7126 if (listpath && S_ISLNK(pent->mode)
7127 && is_prefix(path, listpath, xstrlen(listpath))) {
7128 if (!realpath(pent->name, newpath)) {
7135 if (chdir(newpath) == -1) {
7140 cdprep(lastdir, NULL, path, newpath)
7141 ? (presel = FILTER) : (watch = TRUE);
7142 xstrsncpy(lastname, pent->name, NAME_MAX + 1);
7146 /* Open file disabled on right arrow or `l` */
7152 printwait(messages[MSG_EMPTY_FILE], &presel);
7157 #ifdef FILE_MIME_OPTS
7158 && get_output("file", FILE_MIME_OPTS, newpath, -1, FALSE)
7159 && is_prefix(g_buf, "text/", 5)
7161 /* no MIME option; guess from description instead */
7162 && get_output("file", "-bL", newpath, -1, FALSE)
7163 && strstr(g_buf, "text")
7166 spawn(editor, newpath, NULL, NULL, F_CLI);
7167 if (cfg.filtermode) {
7174 /* Get the extension for regex match */
7175 tmp = xextension(pent->name, pent->nlen - 1);
7177 if (tmp && !pcre_exec(archive_pcre, NULL, tmp,
7178 pent->nlen - (tmp - pent->name) - 1, 0, 0, NULL, 0)) {
7180 if (tmp && !regexec(&archive_re, tmp, 0, NULL, 0)) {
7182 r = get_input(messages[MSG_ARCHIVE_OPTS]);
7185 if (r == 'l' || r == 'x') {
7186 mkpath(path, pent->name, newpath);
7187 if (!handle_archive(newpath, r)) {
7197 if ((r == 'm') && !archive_mount(newpath)) {
7202 if (r == 'x' || r == 'm') {
7204 set_smart_ctx('+', newpath, &path,
7205 ndents ? pdents[cur].name : NULL,
7206 &lastname, &lastdir);
7214 printwait(messages[MSG_INVALID_KEY], &presel);
7219 /* Invoke desktop opener as last resort */
7220 spawn(opener, newpath, NULL, NULL, opener_flags);
7222 /* Move cursor to the next entry if not the last entry */
7223 if (g_state.autonext && cur != ndents - 1)
7224 move_cursor((cur + 1) % ndents, 0);
7225 if (cfg.filtermode) {
7230 case SEL_NEXT: // fallthrough
7231 case SEL_PREV: // fallthrough
7232 case SEL_PGDN: // fallthrough
7233 case SEL_CTRL_D: // fallthrough
7234 case SEL_PGUP: // fallthrough
7235 case SEL_CTRL_U: // fallthrough
7236 case SEL_HOME: // fallthrough
7237 case SEL_END: // fallthrough
7238 case SEL_FIRST: // fallthrough
7239 case SEL_JUMP: // fallthrough
7243 handle_screen_move(sel);
7246 case SEL_CDHOME: // fallthrough
7247 case SEL_CDBEGIN: // fallthrough
7248 case SEL_CDLAST: // fallthrough
7250 dir = (sel == SEL_CDHOME) ? home
7251 : ((sel == SEL_CDBEGIN) ? ipath
7252 : ((sel == SEL_CDLAST) ? lastdir
7253 : "/" /* SEL_CDROOT */));
7255 if (!dir || !*dir) {
7256 printwait(messages[MSG_NOT_SET], &presel);
7261 if (strcmp(path, dir) == 0) {
7267 dir = lastdir; /* Go to last dir on home/root key repeat */
7270 if (chdir(dir) == -1) {
7275 /* SEL_CDLAST: dir pointing to lastdir */
7276 xstrsncpy(newpath, dir, PATH_MAX); // fallthrough
7278 if (sel == SEL_BMOPEN) {
7279 r = (int)handle_bookmark(mark, newpath);
7281 printwait(messages[r], &presel);
7285 if (g_state.selbm == 1) /* Allow filtering in bookmarks directory */
7287 if (strcmp(path, newpath) == 0)
7291 /* In list mode, retain the last file name to highlight it, if possible */
7292 cdprep(lastdir, listpath && sel == SEL_CDLAST ? NULL : lastname, path, newpath)
7293 ? (presel = FILTER) : (watch = TRUE);
7296 if ((sel == SEL_REMOTE) && !remote_mount(newpath)) {
7301 set_smart_ctx('+', newpath, &path,
7302 ndents ? pdents[cur].name : NULL, &lastname, &lastdir);
7305 case SEL_CYCLE: // fallthrough
7306 case SEL_CYCLER: // fallthrough
7307 case SEL_CTX1: // fallthrough
7308 case SEL_CTX2: // fallthrough
7309 case SEL_CTX3: // fallthrough
7317 r = handle_context_switch(sel);
7320 savecurctx(path, ndents ? pdents[cur].name : NULL, r);
7322 /* Reset the pointers */
7323 path = g_ctx[r].c_path;
7324 lastdir = g_ctx[r].c_last;
7325 lastname = g_ctx[r].c_name;
7326 tmp = g_ctx[r].c_fltr;
7328 if (cfg.filtermode || ((tmp[0] == FILTER || tmp[0] == RFILTER) && tmp[1]))
7336 mark = xstrdup(path);
7337 printwait(mark, &presel);
7340 add_bookmark(path, newpath, &presel);
7343 /* Unwatch dir if we are still in a filtered view */
7344 #ifdef LINUX_INOTIFY
7345 if (inotify_wd >= 0) {
7346 inotify_rm_watch(inotify_fd, inotify_wd);
7349 #elif defined(BSD_KQUEUE)
7350 if (event_fd >= 0) {
7354 #elif defined(HAIKU_NM)
7355 if (haiku_nm_active) {
7356 haiku_stop_watch(haiku_hnd);
7357 haiku_nm_active = FALSE;
7360 presel = filterentries(path, lastname);
7361 if (presel == ESC) {
7365 if (presel == FILTER) { /* Refresh dir and filter again */
7370 case SEL_MFLTR: // fallthrough
7371 case SEL_HIDDEN: // fallthrough
7372 case SEL_DETAIL: // fallthrough
7376 cfg.filtermode ^= 1;
7377 if (cfg.filtermode) {
7383 watch = TRUE; // fallthrough
7385 if (sel == SEL_HIDDEN) {
7386 cfg.showhidden ^= 1;
7395 cfg.showdetail ^= 1;
7398 default: /* SEL_SORT */
7399 r = set_sort_flags(get_input(messages[MSG_ORDER]));
7401 printwait(messages[MSG_INVALID_KEY], &presel);
7406 if (cfg.filtermode || filterset())
7412 if (r == 'd' || r == 'a') {
7417 ENTSORT(pdents, ndents, entrycmpfn);
7418 move_cursor(ndents ? dentfind(lastname, ndents) : 0, 0);
7421 case SEL_STATS: // fallthrough
7424 tmp = (listpath && xstrcmp(path, listpath) == 0) ? listroot : path;
7425 mkpath(tmp, pdents[cur].name, newpath);
7427 if ((sel == SEL_STATS && !show_stats(newpath))
7428 || (lstat(newpath, &sb) == -1)
7429 || (sel == SEL_CHMODX && !xchmod(newpath, &sb.st_mode))) {
7434 if (sel == SEL_CHMODX)
7435 pdents[cur].mode = sb.st_mode;
7438 case SEL_REDRAW: // fallthrough
7439 case SEL_RENAMEMUL: // fallthrough
7440 case SEL_HELP: // fallthrough
7441 case SEL_AUTONEXT: // fallthrough
7442 case SEL_EDIT: // fallthrough
7445 bool refresh = FALSE;
7448 mkpath(path, pdents[cur].name, newpath);
7449 else if (sel == SEL_EDIT) /* Avoid trying to edit a non-existing file */
7458 setenv("NNN_INCLUDE_HIDDEN", xitoa(cfg.showhidden), 1);
7459 setenv("NNN_PREFER_SELECTION", xitoa(cfg.prefersel), 1);
7460 setenv("NNN_LIST", listpath ? listroot : "", 1);
7462 if (!(getutil(utils[UTIL_BASH])
7463 && plugscript(utils[UTIL_NMV], F_CLI))
7468 printwait(messages[MSG_FAILED], &presel);
7475 show_help(path); // fallthrough
7477 if (sel == SEL_AUTONEXT)
7478 g_state.autonext ^= 1;
7484 if (!(g_state.picker || g_state.fifomode))
7485 spawn(editor, newpath, NULL, NULL, F_CLI);
7487 default: /* SEL_LOCK */
7492 /* In case of successful operation, reload contents */
7494 /* Continue in type-to-nav mode, if enabled */
7495 if ((cfg.filtermode || filterset()) && !refresh) {
7502 /* Repopulate as directory content may have changed */
7511 if (g_state.rangesel)
7512 g_state.rangesel = 0;
7514 /* Toggle selection status */
7515 pdents[cur].flags ^= FILE_SELECTED;
7517 if (pdents[cur].flags & FILE_SELECTED) {
7519 appendfpath(newpath, mkpath(path, pdents[cur].name, newpath));
7520 writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
7523 rmfromselbuf(mkpath(path, pdents[cur].name, g_sel));
7528 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7535 /* move cursor to the next entry if this is not the last entry */
7536 if (!g_state.stayonsel && (cur != ndents - 1))
7537 move_cursor((cur + 1) % ndents, 0);
7544 g_state.rangesel ^= 1;
7546 if (stat(path, &sb) == -1) {
7551 if (g_state.rangesel) { /* Range selection started */
7557 if (inode != sb.st_ino) {
7558 printwait(messages[MSG_DIR_CHANGED], &presel);
7562 if (cur < selstartid) {
7563 selendid = selstartid;
7568 /* Clear selection on repeat on same file */
7569 if (selstartid == selendid) {
7574 case SEL_SELALL: // fallthrough
7576 if (sel == SEL_SELALL || sel == SEL_SELINV) {
7581 if (g_state.rangesel)
7582 g_state.rangesel = 0;
7585 selendid = ndents - 1;
7588 if ((nselected > LARGESEL) || (nselected && (ndents > LARGESEL))) {
7589 printmsg("processing...");
7593 r = scanselforpath(path, TRUE); /* Get path length suffixed by '/' */
7594 ((sel == SEL_SELINV) && findselpos)
7595 ? invertselbuf(r) : addtoselbuf(r, selstartid, selendid);
7599 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7603 r = editselection();
7605 r = !r ? MSG_0_SELECTED : MSG_FAILED;
7606 printwait(messages[r], &presel);
7610 plugscript(utils[UTIL_CBCP], F_NOWAIT | F_NOTRACE);
7612 cfg.filtermode ? presel = FILTER : statusbar(path);
7615 case SEL_CP: // fallthrough
7616 case SEL_MV: // fallthrough
7617 case SEL_CPMVAS: // fallthrough
7620 if (sel == SEL_RM) {
7621 r = get_cur_or_sel();
7628 tmp = (listpath && xstrcmp(path, listpath) == 0)
7630 mkpath(tmp, pdents[cur].name, newpath);
7634 xrmfromsel(tmp, newpath);
7636 copynextname(lastname);
7638 if (cfg.filtermode || filterset())
7645 (nselected == 1 && (sel == SEL_CP || sel == SEL_MV))
7646 ? mkpath(path, xbasename(pselbuf), newpath)
7647 : (newpath[0] = '\0');
7651 if (!cpmvrm_selection(sel, path)) {
7661 /* Show notification on operation complete */
7663 plugscript(utils[UTIL_NTFY], F_NOWAIT | F_NOTRACE);
7666 if (newpath[0] && !access(newpath, F_OK))
7667 xstrsncpy(lastname, xbasename(newpath), NAME_MAX+1);
7673 case SEL_ARCHIVE: // fallthrough
7674 case SEL_OPENWITH: // fallthrough
7675 case SEL_NEW: // fallthrough
7681 if (!ndents && (sel == SEL_OPENWITH || sel == SEL_RENAME))
7684 if (sel != SEL_OPENWITH)
7689 r = get_cur_or_sel();
7703 tmp = pdents[cur].name;
7705 tmp = xreadline(tmp, messages[MSG_ARCHIVE_NAME]);
7709 if (g_state.picker || g_state.xprompt) {
7711 tmp = xreadline(NULL, messages[MSG_OPEN_WITH]);
7714 tmp = getreadline(messages[MSG_OPEN_WITH]);
7719 r = get_input(messages[MSG_NEW_OPTS]);
7725 tmp = g_ctx[0].c_name;
7729 if (r == 'f' || r == 'd')
7730 tmp = xreadline(tmp, messages[MSG_NEW_PATH]);
7731 else if (r == 's' || r == 'h')
7732 tmp = xreadline((nselected == 1 && cfg.prefersel) ? xbasename(pselbuf) : NULL,
7733 messages[nselected <= 1 ? MSG_NEW_PATH : MSG_LINK_PREFIX]);
7737 default: /* SEL_RENAME */
7738 tmp = xreadline(pdents[cur].name, "");
7742 if (!tmp || !*tmp || is_bad_len_or_dir(tmp))
7747 if (r == 'c' && strcmp(tmp, pdents[cur].name) == 0)
7748 continue; /* Cannot overwrite the hovered file */
7750 tmp = abspath(tmp, NULL, newpath);
7753 if (access(tmp, F_OK) == 0) {
7754 if (!xconfirm(get_input(messages[MSG_OVERWRITE]))) {
7760 (r == 's') ? archive_selection(get_archive_cmd(tmp), tmp)
7761 : spawn(get_archive_cmd(tmp), tmp, pdents[cur].name,
7762 NULL, F_CLI | F_CONFIRM);
7764 if (tmp && (access(tmp, F_OK) == 0)) { /* File created */
7766 clearselection(); /* Archive operation complete */
7768 /* Check if any entry is created in the current directory */
7769 tmp = get_cwd_entry(path, tmp, &len);
7771 xstrsncpy(lastname, tmp, len + 1);
7772 clearfilter(); /* Archive name may not match */
7773 } if (cfg.filtermode)
7780 handle_openwith(path, pdents[cur].name, newpath, tmp);
7782 cfg.filtermode ? presel = FILTER : statusbar(path);
7787 /* Skip renaming to same name */
7788 if (strcmp(tmp, pdents[cur].name) == 0) {
7789 tmp = xreadline(pdents[cur].name, messages[MSG_COPY_NAME]);
7790 if (!tmp || !tmp[0] || is_bad_len_or_dir(tmp)
7791 || !strcmp(tmp, pdents[cur].name)) {
7792 cfg.filtermode ? presel = FILTER : statusbar(path);
7799 default: /* SEL_NEW */
7803 if (!(r == 's' || r == 'h')) {
7804 tmp = abspath(tmp, NULL, newpath);
7811 /* Check if another file with same name exists */
7812 if (lstat(tmp, &sb) == 0) {
7813 if ((sel == SEL_RENAME) || ((r == 'f') && (S_ISREG(sb.st_mode)))) {
7814 /* Overwrite file with same name? */
7815 if (!xconfirm(get_input(messages[MSG_OVERWRITE])))
7818 /* Do nothing for SEL_NEW if a non-regular entry exists */
7819 printwait(messages[MSG_EXISTS], &presel);
7824 if (sel == SEL_RENAME) {
7825 /* Rename the file */
7827 spawn("cp -rp", pdents[cur].name, tmp, NULL, F_SILENT);
7828 else if (rename(pdents[cur].name, tmp) != 0) {
7833 /* Check if any entry is created in the current directory */
7834 tmp = get_cwd_entry(path, tmp, &len);
7836 xstrsncpy(lastname, tmp, len + 1);
7837 /* Directory must be reloeaded for rename case */
7838 } else { /* SEL_NEW */
7841 /* Check if it's a dir or file */
7842 if (r == 'f' || r == 'd') {
7843 ret = xmktree(tmp, r == 'f' ? FALSE : TRUE);
7844 } else if (r == 's' || r == 'h') {
7845 if (nselected > 1 && tmp[0] == '@' && tmp[1] == '\0')
7847 ret = xlink(tmp, path, (ndents ? pdents[cur].name : NULL), newpath, r);
7856 if (r == 'f' || r == 'd') {
7857 tmp = get_cwd_entry(path, tmp, &len);
7859 xstrsncpy(lastname, tmp, len + 1);
7861 continue; /* No change in directory */
7862 } else if (ndents) {
7874 /* Check if directory is accessible */
7875 if (!xdiraccess(plgpath)) {
7881 r = xstrsncpy(g_buf, messages[MSG_KEYS], CMD_LEN_MAX);
7882 printkeys(plug, g_buf + r - 1, maxplug);
7884 r = get_input(NULL);
7891 endselection(FALSE);
7892 tmp = get_kv_val(plug, NULL, r, maxplug, NNN_PLUG);
7894 printwait(messages[MSG_INVALID_KEY], &presel);
7898 if (tmp[0] == '-' && tmp[1]) {
7900 r = FALSE; /* Do not refresh dir after completion */
7904 if (!run_plugin(&path, tmp, (ndents ? pdents[cur].name : NULL),
7905 &lastname, &lastdir)) {
7906 printwait(messages[MSG_FAILED], &presel);
7911 return EXIT_SUCCESS;
7916 cfg.filtermode ? presel = FILTER : statusbar(path);
7919 } else { /* 'Return/Enter' enters the plugin directory */
7920 g_state.runplugin ^= 1;
7921 if (!g_state.runplugin) {
7923 * If toggled, and still in the plugin dir,
7924 * switch to original directory
7926 if (strcmp(path, plgpath) == 0) {
7927 xstrsncpy(path, lastdir, PATH_MAX);
7928 xstrsncpy(lastname, runfile, NAME_MAX + 1);
7934 /* Otherwise, initiate choosing plugin again */
7935 g_state.runplugin = 1;
7938 xstrsncpy(lastdir, path, PATH_MAX);
7939 xstrsncpy(path, plgpath, PATH_MAX);
7941 xstrsncpy(runfile, pdents[cur].name, NAME_MAX);
7942 g_state.runctx = cfg.curctx;
7947 if (g_state.runplugin == 1) /* Allow filtering in plugins directory */
7953 case SEL_SHELL: // fallthrough
7954 case SEL_LAUNCH: // fallthrough
7956 r = handle_cmd(sel, newpath);
7958 /* Continue in type-to-nav mode, if enabled */
7968 /* Repopulate as directory content may have changed */
7973 if (!unmount((ndents ? pdents[cur].name : NULL), newpath, &presel, path)) {
7974 if (presel == MSG_ZERO)
7979 /* Dir removed, go to next entry */
7980 copynextname(lastname);
7985 r = get_input(messages[MSG_SSN_OPTS]);
7988 tmp = xreadline(NULL, messages[MSG_SSN_NAME]);
7990 save_session(tmp, &presel);
7991 } else if (r == 'l' || r == 'r') {
7992 if (load_session(NULL, &path, &lastdir, &lastname, r == 'r')) {
8003 cfg.filtermode ? presel = FILTER : statusbar(path);
8006 if (!set_time_type(&presel))
8010 case SEL_QUITCTX: // fallthrough
8011 case SEL_QUITCD: // fallthrough
8014 if (sel == SEL_QUITCTX) {
8015 int ctx = cfg.curctx;
8017 for (r = (ctx - 1) & (CTX_MAX - 1);
8018 (r != ctx) && !g_ctx[r].c_cfg.ctxactive;
8019 r = ((r - 1) & (CTX_MAX - 1))) {
8023 g_ctx[ctx].c_cfg.ctxactive = 0;
8025 /* Switch to next active context */
8026 path = g_ctx[r].c_path;
8027 lastdir = g_ctx[r].c_last;
8028 lastname = g_ctx[r].c_name;
8030 g_ctx[r].c_cfg.curctx = r;
8031 setcfg(g_ctx[r].c_cfg);
8036 } else if (!g_state.forcequit) {
8037 for (r = 0; r < CTX_MAX; ++r)
8038 if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
8039 r = get_input(messages[MSG_QUIT_ALL]);
8043 if (!(r == CTX_MAX || xconfirm(r)))
8044 break; // fallthrough
8048 tmp = getenv("NNN_TMPFILE");
8049 if ((sel == SEL_QUITCD) || tmp) {
8050 write_lastdir(path, tmp);
8051 /* ^G is a way to quit picker mode without picking anything */
8052 if ((sel == SEL_QUITCD) && g_state.picker)
8056 if (sel != SEL_QUITERR)
8057 return EXIT_SUCCESS;
8059 if (selbufpos && !g_state.picker) {
8060 /* Pick files to stdout and exit */
8064 return EXIT_SUCCESS;
8067 return EXIT_FAILURE;
8069 if (xlines != LINES || xcols != COLS)
8072 if (idletimeout && idle == idletimeout) {
8073 lock_terminal(); /* Locker */
8079 } /* switch (sel) */
8083 static char *make_tmp_tree(char **paths, ssize_t entries, const char *prefix)
8085 /* tmpdir holds the full path */
8086 /* tmp holds the path without the tmp dir prefix */
8090 ssize_t len = xstrlen(prefix);
8091 char *tmpdir = malloc(PATH_MAX);
8094 DPRINTF_S(strerror(errno));
8098 tmp = tmpdir + tmpfplen - 1;
8099 xstrsncpy(tmpdir, g_tmpfpath, tmpfplen);
8100 xstrsncpy(tmp, "/nnnXXXXXX", 11);
8102 /* Points right after the base tmp dir */
8105 /* handle the case where files are directly under / */
8106 if (!prefix[1] && (prefix[0] == '/'))
8109 if (!mkdtemp(tmpdir)) {
8112 DPRINTF_S(strerror(errno));
8118 for (ssize_t i = 0; i < entries; ++i) {
8122 err = stat(paths[i], &sb);
8123 if (err && errno == ENOENT)
8126 /* Don't copy the common prefix */
8127 xstrsncpy(tmp, paths[i] + len, xstrlen(paths[i]) - len + 1);
8129 /* Get the dir containing the path */
8130 slash = xmemrchr((uchar_t *)tmp, '/', xstrlen(paths[i]) - len);
8134 if (access(tmpdir, F_OK)) /* Create directory if it doesn't exist */
8135 xmktree(tmpdir, TRUE);
8140 if (symlink(paths[i], tmpdir)) {
8141 DPRINTF_S(paths[i]);
8142 DPRINTF_S(strerror(errno));
8146 /* Get the dir in which to start */
8151 static char *load_input(int fd, const char *path)
8153 size_t i, chunk_count = 1, chunk = 512UL * 1024 /* 512 KiB chunk size */, entries = 0;
8154 char *input = malloc(sizeof(char) * chunk), *tmpdir = NULL;
8155 char cwd[PATH_MAX], *next;
8156 size_t offsets[LIST_FILES_MAX];
8157 char **paths = NULL;
8158 ssize_t input_read, total_read = 0, off = 0;
8162 DPRINTF_S(strerror(errno));
8167 if (!getcwd(cwd, PATH_MAX)) {
8172 xstrsncpy(cwd, path, PATH_MAX);
8174 while (chunk_count < LIST_INPUT_MAX / chunk && !msgnum) {
8175 input_read = read(fd, input + total_read, chunk);
8176 if (input_read < 0) {
8180 DPRINTF_S(strerror(errno));
8184 if (input_read == 0)
8187 total_read += input_read;
8189 while (off < total_read) {
8190 next = memchr(input + off, '\0', total_read - off);
8195 if (next - input == off + 1) {
8200 if (entries == LIST_FILES_MAX) {
8201 msgnum = MSG_FILE_LIMIT;
8205 offsets[entries++] = off;
8209 /* We don't need to allocate another chunk */
8210 if (chunk_count > (total_read + chunk - 1) / chunk)
8213 /* We can never need more than one additional chunk */
8215 if (chunk_count > LIST_INPUT_MAX / chunk) {
8216 msgnum = MSG_SIZE_LIMIT;
8220 input = xrealloc(input, chunk_count * chunk);
8225 /* We close fd outside this function. Any extra data is left to the kernel to handle */
8227 if (off != total_read) {
8228 if (entries == LIST_FILES_MAX)
8229 msgnum = MSG_FILE_LIMIT;
8231 offsets[entries++] = off;
8235 DPRINTF_D(total_read);
8236 DPRINTF_D(chunk_count);
8239 msgnum = MSG_0_ENTRIES;
8243 input[total_read] = '\0';
8245 paths = malloc(entries * sizeof(char *));
8249 for (i = 0; i < entries; ++i)
8250 paths[i] = input + offsets[i];
8252 listroot = malloc(sizeof(char) * PATH_MAX);
8257 DPRINTF_S(paths[0]);
8259 for (i = 0; i < entries; ++i) {
8260 if (paths[i][0] == '\n' || selforparent(paths[i])) {
8265 paths[i] = abspath(paths[i], cwd, NULL);
8267 entries = i; // free from the previous entry
8271 DPRINTF_S(paths[i]);
8273 xstrsncpy(g_buf, paths[i], PATH_MAX);
8274 if (!common_prefix(xdirname(g_buf), listroot)) {
8275 entries = i + 1; // free from the current entry
8279 DPRINTF_S(listroot);
8282 DPRINTF_S(listroot);
8285 tmpdir = make_tmp_tree(paths, entries, listroot);
8288 for (i = 0; i < entries; ++i)
8291 if (msgnum) { /* Check if we are past init stage and show msg */
8293 printmsg(messages[msgnum]);
8294 xdelay(XDELAY_INTERVAL_MS << 2);
8296 msg(messages[msgnum]);
8297 usleep(XDELAY_INTERVAL_MS << 2);
8306 static void check_key_collision(void)
8309 bool bitmap[KEY_MAX] = {FALSE};
8311 for (ullong_t i = 0; i < ELEMENTS(bindings); ++i) {
8312 key = bindings[i].sym;
8315 dprintf(STDERR_FILENO, "key collision! [%s]\n", keyname(key));
8321 static void usage(void)
8323 dprintf(STDOUT_FILENO,
8324 "%s: nnn [OPTIONS] [PATH]\n\n"
8325 "The unorthodox terminal file manager.\n\n"
8326 "positional args:\n"
8327 " PATH start dir/file [default: .]\n\n"
8330 " -a auto NNN_FIFO\n"
8332 " -A no dir auto-enter during filter\n"
8333 " -b key open bookmark key (trumps -s/S)\n"
8334 " -B use bsdtar for archives\n"
8335 " -c cli-only NNN_OPENER (trumps -e)\n"
8336 " -C 8-color scheme\n"
8338 " -D dirs in context color\n"
8339 " -e text in $VISUAL/$EDITOR/vi\n"
8340 " -E internal edits in EDITOR\n"
8342 " -f use readline history file\n"
8345 " -F val fifo mode [0:preview 1:explore]\n"
8347 " -g regex filters\n"
8348 " -H show hidden files\n"
8349 " -i show current file info\n"
8350 " -J no auto-advance on selection\n"
8351 " -K detect key collision and exit\n"
8352 " -l val set scroll lines\n"
8353 " -n type-to-nav mode\n"
8355 " -N use native prompt\n"
8357 " -o open files only on Enter\n"
8358 " -p file selection file [-:stdout]\n"
8359 " -P key run plugin key\n"
8360 " -Q no quit confirmation\n"
8361 " -r use advcpmv patched cp, mv\n"
8362 " -R no rollover at edges\n"
8364 " -s name load session by name\n"
8365 " -S persistent session\n"
8367 " -t secs timeout to lock\n"
8368 " -T key sort order [a/d/e/r/s/t/v]\n"
8369 " -u use selection (no prompt)\n"
8371 " -U show user and group\n"
8373 " -V show version\n"
8375 " -x notis, selection sync, xterm title\n"
8378 "v%s\n%s\n", __func__, VERSION, GENERAL_INFO);
8381 static bool setup_config(void)
8384 char *xdgcfg = getenv("XDG_CONFIG_HOME");
8387 /* Set up configuration file paths */
8388 if (xdgcfg && xdgcfg[0]) {
8390 if (tilde_is_home(xdgcfg)) {
8391 r = xstrsncpy(g_buf, home, PATH_MAX);
8392 xstrsncpy(g_buf + r - 1, xdgcfg + 1, PATH_MAX);
8397 if (!xdiraccess(xdgcfg)) {
8402 len = xstrlen(xdgcfg) + xstrlen("/nnn/bookmarks") + 1;
8407 len = xstrlen(home) + xstrlen("/.config/nnn/bookmarks") + 1;
8409 cfgpath = (char *)malloc(len);
8410 plgpath = (char *)malloc(len);
8411 if (!cfgpath || !plgpath) {
8417 xstrsncpy(cfgpath, xdgcfg, len);
8418 r = len - xstrlen("/nnn/bookmarks");
8420 r = xstrsncpy(cfgpath, home, len);
8422 /* Create ~/.config */
8423 xstrsncpy(cfgpath + r - 1, "/.config", len - r);
8425 r += 8; /* length of "/.config" */
8428 /* Create ~/.config/nnn */
8429 xstrsncpy(cfgpath + r - 1, "/nnn", len - r);
8432 /* Create bookmarks, sessions, mounts and plugins directories */
8433 for (r = 0; r < ELEMENTS(toks); ++r) {
8434 mkpath(cfgpath, toks[r], plgpath);
8435 /* The dirs are created on first run, check if they already exist */
8436 if (access(plgpath, F_OK) && !xmktree(plgpath, TRUE)) {
8443 /* Set selection file path */
8444 if (!g_state.picker) {
8445 char *env_sel = xgetenv(env_cfg[NNN_SEL], NULL);
8447 selpath = env_sel ? xstrdup(env_sel)
8448 : (char *)malloc(len + 3); /* Length of "/.config/nnn/.selection" */
8456 r = xstrsncpy(selpath, cfgpath, len + 3);
8457 xstrsncpy(selpath + r - 1, "/.selection", 12);
8465 static bool set_tmp_path(void)
8468 char *path = xdiraccess(tmp) ? tmp : getenv("TMPDIR");
8475 tmpfplen = (uchar_t)xstrsncpy(g_tmpfpath, path, TMP_LEN_MAX);
8476 DPRINTF_S(g_tmpfpath);
8477 DPRINTF_U(tmpfplen);
8482 static void cleanup(void)
8485 if (cfg.x11 && !g_state.picker) {
8486 printf("\033[23;0t"); /* reset terminal window title */
8502 if (g_state.autofifo)
8505 if (g_state.pluginit)
8512 int main(int argc, char *argv[])
8515 char *session = NULL;
8516 int fd, opt, sort = 0, pkey = '\0'; /* Plugin key */
8519 char *middle_click_env = xgetenv(env_cfg[NNN_MCLICK], "\0");
8521 middle_click_key = (middle_click_env[0] == '^' && middle_click_env[1])
8522 ? CONTROL(middle_click_env[1])
8523 : (uchar_t)middle_click_env[0];
8526 const char * const env_opts = xgetenv(env_cfg[NNN_OPTS], NULL);
8527 int env_opts_id = env_opts ? (int)xstrlen(env_opts) : -1;
8529 bool rlhist = FALSE;
8532 while ((opt = (env_opts_id > 0
8533 ? env_opts[--env_opts_id]
8534 : getopt(argc, argv, "aAb:BcCdDeEfF:gHiJKl:nNop:P:QrRs:St:T:uUVxh"))) != -1) {
8538 g_state.autofifo = 1;
8545 if (env_opts_id < 0)
8549 g_state.usebsdtar = 1;
8555 g_state.oldcolor = 1;
8576 if (env_opts_id < 0) {
8578 if ((fd < 0) || (fd > 1))
8579 return EXIT_FAILURE;
8580 g_state.fifomode = fd;
8586 filterfn = &visible_re;
8595 g_state.stayonsel = 1;
8598 check_key_collision();
8599 return EXIT_SUCCESS;
8601 if (env_opts_id < 0)
8602 scroll_lines = atoi(optarg);
8609 g_state.xprompt = 1;
8616 if (env_opts_id >= 0)
8620 if (!(optarg[0] == '-' && optarg[1] == '\0')) {
8621 fd = open(optarg, O_WRONLY | O_CREAT, 0600);
8624 return EXIT_FAILURE;
8628 selpath = abspath(optarg, NULL, NULL);
8633 if (env_opts_id < 0 && !optarg[1])
8634 pkey = (uchar_t)optarg[0];
8637 g_state.forcequit = 1;
8641 memcpy(cp, PROGRESS_CP, sizeof PROGRESS_CP);
8642 memcpy(mv, PROGRESS_MV, sizeof PROGRESS_MV);
8650 if (env_opts_id < 0)
8654 g_state.prstssn = 1;
8655 if (!session) /* Support named persistent sessions */
8660 if (env_opts_id < 0)
8661 idletimeout = atoi(optarg);
8664 if (env_opts_id < 0)
8665 sort = (uchar_t)optarg[0];
8674 dprintf(STDOUT_FILENO, "%s\n", VERSION);
8675 return EXIT_SUCCESS;
8681 return EXIT_SUCCESS;
8684 return EXIT_FAILURE;
8686 if (env_opts_id == 0)
8695 /* Prefix for temporary files */
8696 if (!set_tmp_path())
8697 return EXIT_FAILURE;
8701 /* Check if we are in path list mode */
8702 if (!isatty(STDIN_FILENO)) {
8703 /* This is the same as listpath */
8704 initpath = load_input(STDIN_FILENO, NULL);
8706 return EXIT_FAILURE;
8708 /* We return to tty */
8709 if (!isatty(STDOUT_FILENO)) {
8710 fd = open(ctermid(NULL), O_RDONLY, 0400);
8711 dup2(fd, STDIN_FILENO);
8714 dup2(STDOUT_FILENO, STDIN_FILENO);
8720 home = getenv("HOME");
8723 return EXIT_FAILURE;
8726 homelen = (uchar_t)xstrlen(home);
8728 if (!setup_config())
8729 return EXIT_FAILURE;
8731 /* Get custom opener, if set */
8732 opener = xgetenv(env_cfg[NNN_OPENER], utils[UTIL_OPENER]);
8735 /* Parse bookmarks string */
8736 if (!parsekvpair(&bookmark, &bmstr, NNN_BMS, &maxbm)) {
8737 msg(env_cfg[NNN_BMS]);
8738 return EXIT_FAILURE;
8741 /* Parse plugins string */
8742 if (!parsekvpair(&plug, &pluginstr, NNN_PLUG, &maxplug)) {
8743 msg(env_cfg[NNN_PLUG]);
8744 return EXIT_FAILURE;
8747 /* Parse order string */
8748 if (!parsekvpair(&order, &orderstr, NNN_ORDER, &maxorder)) {
8749 msg(env_cfg[NNN_ORDER]);
8750 return EXIT_FAILURE;
8754 if (arg) { /* Open a bookmark directly */
8755 if (!arg[1]) /* Bookmarks keys are single char */
8756 initpath = get_kv_val(bookmark, NULL, *arg, maxbm, NNN_BMS);
8759 msg(messages[MSG_INVALID_KEY]);
8760 return EXIT_FAILURE;
8765 } else if (argc == optind) {
8766 /* Start in the current directory */
8767 char *startpath = getenv("PWD");
8769 initpath = (startpath && *startpath) ? xstrdup(startpath) : getcwd(NULL, 0);
8772 } else { /* Open a file */
8775 size_t len = xstrlen(arg);
8777 if (len > 7 && is_prefix(arg, "file://", 7)) {
8781 initpath = abspath(arg, NULL, NULL);
8782 DPRINTF_S(initpath);
8785 return EXIT_FAILURE;
8788 /* If the file is hidden, enable hidden option */
8789 if (*xbasename(initpath) == '.')
8793 * If nnn is set as the file manager, applications may try to open
8794 * files by invoking nnn. In that case pass the file path to the
8795 * desktop opener and exit.
8799 if (stat(initpath, &sb) == -1) {
8800 bool dir = (arg[len - 1] == '/');
8803 arg = xbasename(initpath);
8804 initpath = xdirname(initpath);
8806 pkey = CREATE_NEW_KEY; /* Override plugin key */
8807 g_state.initfile = 1;
8809 if (dir || (arg != initpath)) { /* We have a directory */
8810 if (!xdiraccess(initpath) && !xmktree(initpath, TRUE)) {
8811 xerror(); /* Fail if directory cannot be created */
8812 return EXIT_FAILURE;
8814 if (!dir) /* Restore the complete path */
8817 } else if (!S_ISDIR(sb.st_mode))
8818 g_state.initfile = 1;
8825 /* Set archive handling (enveditor used as tmp var) */
8826 enveditor = getenv(env_cfg[NNN_ARCHIVE]);
8828 if (setfilter(&archive_pcre, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8830 if (setfilter(&archive_re, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
8832 msg(messages[MSG_INVALID_REG]);
8833 return EXIT_FAILURE;
8836 /* An all-CLI opener overrides option -e) */
8840 /* Get VISUAL/EDITOR */
8841 enveditor = xgetenv(envs[ENV_EDITOR], utils[UTIL_VI]);
8842 editor = xgetenv(envs[ENV_VISUAL], enveditor);
8843 DPRINTF_S(getenv(envs[ENV_VISUAL]));
8844 DPRINTF_S(getenv(envs[ENV_EDITOR]));
8848 pager = xgetenv(envs[ENV_PAGER], utils[UTIL_LESS]);
8852 shell = xgetenv(envs[ENV_SHELL], utils[UTIL_SH]);
8855 DPRINTF_S(getenv("PWD"));
8859 if (g_state.autofifo) {
8860 g_tmpfpath[tmpfplen - 1] = '\0';
8862 size_t r = mkpath(g_tmpfpath, "nnn-fifo.", g_buf);
8864 xstrsncpy(g_buf + r - 1, xitoa(getpid()), PATH_MAX - r);
8865 setenv("NNN_FIFO", g_buf, TRUE);
8868 fifopath = xgetenv("NNN_FIFO", NULL);
8870 if (mkfifo(fifopath, 0600) != 0 && !(errno == EEXIST && access(fifopath, W_OK) == 0)) {
8872 return EXIT_FAILURE;
8875 sigaction(SIGPIPE, &(struct sigaction){.sa_handler = SIG_IGN}, NULL);
8879 #ifdef LINUX_INOTIFY
8880 /* Initialize inotify */
8881 inotify_fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
8882 if (inotify_fd < 0) {
8884 return EXIT_FAILURE;
8886 #elif defined(BSD_KQUEUE)
8890 return EXIT_FAILURE;
8892 #elif defined(HAIKU_NM)
8893 haiku_hnd = haiku_init_nm();
8896 return EXIT_FAILURE;
8900 /* Configure trash preference */
8901 opt = xgetenv_val(env_cfg[NNN_TRASH]);
8902 if (opt && opt <= 2)
8903 g_state.trash = opt;
8905 /* Ignore/handle certain signals */
8906 struct sigaction act = {.sa_handler = sigint_handler};
8908 if (sigaction(SIGINT, &act, NULL) < 0) {
8910 return EXIT_FAILURE;
8913 act.sa_handler = clean_exit_sighandler;
8915 if (sigaction(SIGTERM, &act, NULL) < 0 || sigaction(SIGHUP, &act, NULL) < 0) {
8917 return EXIT_FAILURE;
8920 act.sa_handler = SIG_IGN;
8922 if (sigaction(SIGQUIT, &act, NULL) < 0) {
8924 return EXIT_FAILURE;
8929 setlocale(LC_ALL, "");
8931 tables = pcre_maketables();
8936 #if RL_READLINE_VERSION >= 0x0603
8937 /* readline would overwrite the WINCH signal hook */
8938 rl_change_environment = 0;
8940 /* Bind TAB to cycling */
8941 rl_variable_bind("completion-ignore-case", "on");
8943 rl_bind_key('\t', rl_menu_complete);
8945 rl_bind_key('\t', rl_complete);
8948 mkpath(cfgpath, ".history", g_buf);
8949 read_history(g_buf);
8954 if (cfg.x11 && !g_state.picker) {
8955 /* Save terminal window title */
8956 printf("\033[22;0t");
8958 gethostname(hostname, sizeof(hostname));
8959 hostname[sizeof(hostname) - 1] = '\0';
8964 if (!initcurses(&mask))
8966 if (!initcurses(NULL))
8968 return EXIT_FAILURE;
8971 set_sort_flags(sort);
8973 opt = browse(initpath, session, pkey);
8976 if (session && g_state.prstssn)
8977 save_session(session, NULL);
8981 mousemask(mask, NULL);
8987 if (rlhist && !g_state.xprompt) {
8988 mkpath(cfgpath, ".history", g_buf);
8989 write_history(g_buf);
8993 if (g_state.picker) {
8995 fd = selpath ? open(selpath, O_WRONLY | O_CREAT | O_TRUNC, 0600) : STDOUT_FILENO;
8996 if ((fd == -1) || (seltofile(fd, NULL) != (size_t)(selbufpos)))
9005 /* Remove tmp dir in list mode */
9008 /* Free the regex */
9010 pcre_free(archive_pcre);
9012 regfree(&archive_re);
9015 /* Free the selection buffer */
9018 #ifdef LINUX_INOTIFY
9019 /* Shutdown inotify */
9020 if (inotify_wd >= 0)
9021 inotify_rm_watch(inotify_fd, inotify_wd);
9023 #elif defined(BSD_KQUEUE)
9027 #elif defined(HAIKU_NM)
9028 haiku_close_nm(haiku_hnd);
9032 if (!g_state.fifomode)