-
-
Notifications
You must be signed in to change notification settings - Fork 761
/
nnn.c
9054 lines (7698 loc) · 202 KB
/
nnn.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* BSD 2-Clause License
*
* Copyright (C) 2014-2016, Lazaros Koromilas <lostd@2f30.org>
* Copyright (C) 2014-2016, Dimitris Papastamos <sin@2f30.org>
* Copyright (C) 2016-2023, Arun Prakash Jana <engineerarun@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define _FILE_OFFSET_BITS 64 /* Support large files on 32-bit glibc */
#if defined(__linux__) || defined(MINGW) || defined(__MINGW32__) \
|| defined(__MINGW64__) || defined(__CYGWIN__)
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#if defined(__linux__)
#include <sys/inotify.h>
#define LINUX_INOTIFY
#endif
#if !defined(__GLIBC__)
#include <sys/types.h>
#endif
#endif
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#define BSD_KQUEUE
#elif defined(__HAIKU__)
#include "../misc/haiku/haiku_interop.h"
#define HAIKU_NM
#else
#include <sys/sysmacros.h>
#endif
#include <sys/wait.h>
#ifdef __linux__ /* Fix failure due to mvaddnwstr() */
#ifndef NCURSES_WIDECHAR
#define NCURSES_WIDECHAR 1
#endif
#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
|| defined(__APPLE__) || defined(__sun)
#ifndef _XOPEN_SOURCE_EXTENDED
#define _XOPEN_SOURCE_EXTENDED
#endif
#endif
#ifndef __USE_XOPEN /* Fix wcswidth() failure, ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
#define __USE_XOPEN
#endif
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <fts.h>
#include <libgen.h>
#include <limits.h>
#ifndef NOLC
#include <locale.h>
#endif
#include <pthread.h>
#include <stdio.h>
#ifndef NORL
#include <readline/history.h>
#include <readline/readline.h>
#endif
#ifdef PCRE
#include <pcre.h>
#else
#include <regex.h>
#endif
#include <signal.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>
#include <stddef.h>
#include <stdalign.h>
#ifndef __USE_XOPEN_EXTENDED
#define __USE_XOPEN_EXTENDED 1
#endif
#include <ftw.h>
#include <pwd.h>
#include <grp.h>
#ifdef MACOS_BELOW_1012
#include "../misc/macos-legacy/mach_gettime.h"
#endif
#if !defined(alloca) && defined(__GNUC__)
/*
* GCC doesn't expand alloca() to __builtin_alloca() in standards mode
* (-std=...) and not all standard libraries do or supply it, e.g.
* NetBSD/arm64 so explicitly use the builtin.
*/
#define alloca(size) __builtin_alloca(size)
#endif
#include "nnn.h"
#include "dbg.h"
#if defined(ICONS_IN_TERM) || defined(NERD) || defined(EMOJI)
#define ICONS_ENABLED
#include ICONS_INCLUDE
#include "icons-hash.c"
#include "icons.h"
#endif
#if defined(ICONS_ENABLED) && defined(__APPLE__)
/*
* For some reason, wcswidth returns 2 for certain icons on macOS
* leading to duplicated first characters in filenames when navigating.
* https://github.com/jarun/nnn/issues/1692
* There might be a better way to fix it without requiring a refresh.
*/
#define macos_icons_hack() do { clrtoeol(); refresh(); } while(0)
#else
#define macos_icons_hack()
#endif
#ifdef TOURBIN_QSORT
#include "qsort.h"
#endif
/* Macro definitions */
#define VERSION "4.9"
#define GENERAL_INFO "BSD 2-Clause\nhttps://github.com/jarun/nnn"
#ifndef NOSSN
#define SESSIONS_VERSION 1
#endif
#ifndef S_BLKSIZE
#define S_BLKSIZE 512 /* S_BLKSIZE is missing on Android NDK (Termux) */
#endif
/*
* NAME_MAX and PATH_MAX may not exist, e.g. with dirent.c_name being a
* flexible array on Illumos. Use somewhat accommodating fallback values.
*/
#ifndef NAME_MAX
#define NAME_MAX 255
#endif
#ifndef PATH_MAX
#define PATH_MAX 4096
#endif
#define _ABSSUB(N, M) (((N) <= (M)) ? ((M) - (N)) : ((N) - (M)))
#define ELEMENTS(x) (sizeof(x) / sizeof(*(x)))
#undef MIN
#define MIN(x, y) ((x) < (y) ? (x) : (y))
#undef MAX
#define MAX(x, y) ((x) > (y) ? (x) : (y))
#define ISODD(x) ((x) & 1)
#define ISBLANK(x) ((x) == ' ' || (x) == '\t')
#define TOUPPER(ch) (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
#define TOLOWER(ch) (((ch) >= 'A' && (ch) <= 'Z') ? ((ch) - 'A' + 'a') : (ch))
#define ISUPPER_(ch) ((ch) >= 'A' && (ch) <= 'Z')
#define ISLOWER_(ch) ((ch) >= 'a' && (ch) <= 'z')
#define CMD_LEN_MAX (PATH_MAX + ((NAME_MAX + 1) << 1))
#define ALIGN_UP(x, A) ((((x) + (A) - 1) / (A)) * (A))
#define READLINE_MAX 256
#define FILTER '/'
#define RFILTER '\\'
#define CASE ':'
#define MSGWAIT '$'
#define SELECT ' '
#define PROMPT ">>> "
#define REGEX_MAX 48
#define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
#define NAMEBUF_INCR 0x800 /* 64 dir entries at once, avg. 32 chars per file name = 64*32B = 2KB */
#define DESCRIPTOR_LEN 32
#define _ALIGNMENT 0x10 /* 16-byte alignment */
#define _ALIGNMENT_MASK 0xF
#define TMP_LEN_MAX 64
#define DOT_FILTER_LEN 7
#define ASCII_MAX 128
#define EXEC_ARGS_MAX 10
#define LIST_FILES_MAX (1 << 14) /* Support listing 16K files */
#define LIST_INPUT_MAX ((size_t)LIST_FILES_MAX * PATH_MAX)
#define SCROLLOFF 3
#define COLOR_256 256
#define CREATE_NEW_KEY (-1)
/* Time intervals */
#define DBLCLK_INTERVAL_NS (400000000)
#define XDELAY_INTERVAL_MS (350000) /* 350 ms delay */
#ifndef CTX8
#define CTX_MAX 4
#else
#define CTX_MAX 8
#endif
#ifndef SED
/* BSDs or Solaris or SunOS */
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) || defined(sun) || defined(__sun)
#define SED "gsed"
#else
#define SED "sed"
#endif
#endif
/* Large selection threshold */
#ifndef LARGESEL
#define LARGESEL 1000
#endif
#define MIN_DISPLAY_COL (CTX_MAX * 2)
#define ARCHIVE_CMD_LEN 16
#define BLK_SHIFT_512 9
/* Detect hardlinks in du */
#define HASH_BITS (0xFFFFFF)
#define HASH_OCTETS (HASH_BITS >> 6) /* 2^6 = 64 */
/* Entry flags */
#define DIR_OR_DIRLNK 0x01
#define HARD_LINK 0x02
#define SYM_ORPHAN 0x04
#define FILE_MISSING 0x08
#define FILE_SELECTED 0x10
#define FILE_SCANNED 0x20
#define FILE_YOUNG 0x40
/* Macros to define process spawn behaviour as flags */
#define F_NONE 0x00 /* no flag set */
#define F_MULTI 0x01 /* first arg can be combination of args; to be used with F_NORMAL */
#define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
#define F_NOTRACE 0x04 /* suppress stdout and stderr (no traces) */
#define F_NORMAL 0x08 /* spawn child process in non-curses regular CLI mode */
#define F_CONFIRM 0x10 /* run command - show results before exit (must have F_NORMAL) */
#define F_CHKRTN 0x20 /* wait for user prompt if cmd returns failure status */
#define F_NOSTDIN 0x40 /* suppress stdin */
#define F_PAGE 0x80 /* page output in run-cmd-as-plugin mode */
#define F_TTY 0x100 /* Force stdout to go to tty if redirected to a non-tty */
#define F_CLI (F_NORMAL | F_MULTI)
#define F_SILENT (F_CLI | F_NOTRACE)
/* Version compare macros */
/*
* states: S_N: normal, S_I: comparing integral part, S_F: comparing
* fractional parts, S_Z: idem but with leading Zeroes only
*/
#define S_N 0x0
#define S_I 0x3
#define S_F 0x6
#define S_Z 0x9
/* result_type: VCMP: return diff; VLEN: compare using len_diff/diff */
#define VCMP 2
#define VLEN 3
/* Volume info */
#define VFS_AVAIL 0
#define VFS_USED 1
#define VFS_SIZE 2
/* TYPE DEFINITIONS */
typedef unsigned int uint_t;
typedef unsigned char uchar_t;
typedef unsigned short ushort_t;
typedef unsigned long long ullong_t;
/* STRUCTURES */
/* Directory entry */
typedef struct entry {
char *name; /* 8 bytes */
time_t sec; /* 8 bytes */
uint_t nsec; /* 4 bytes (enough to store nanosec) */
mode_t mode; /* 4 bytes */
off_t size; /* 8 bytes */
struct {
ullong_t blocks : 40; /* 5 bytes (enough for 512 TiB in 512B blocks allocated) */
ullong_t nlen : 16; /* 2 bytes (length of file name) */
ullong_t flags : 8; /* 1 byte (flags specific to the file) */
};
#ifndef NOUG
uid_t uid; /* 4 bytes */
gid_t gid; /* 4 bytes */
#endif
} *pEntry;
/* Selection marker */
typedef struct {
char *startpos;
size_t len;
} selmark;
/* Key-value pairs from env */
typedef struct {
int key;
int off;
} kv;
typedef struct {
#ifdef PCRE
const pcre *pcrex;
#else
const regex_t *regex;
#endif
const char *str;
} fltrexp_t;
/*
* Settings
*/
typedef struct {
uint_t filtermode : 1; /* Set to enter filter mode */
uint_t timeorder : 1; /* Set to sort by time */
uint_t sizeorder : 1; /* Set to sort by file size */
uint_t apparentsz : 1; /* Set to sort by apparent size (disk usage) */
uint_t blkorder : 1; /* Set to sort by blocks used (disk usage) */
uint_t extnorder : 1; /* Order by extension */
uint_t showhidden : 1; /* Set to show hidden files */
uint_t reserved0 : 1;
uint_t showdetail : 1; /* Clear to show lesser file info */
uint_t ctxactive : 1; /* Context active or not */
uint_t reverse : 1; /* Reverse sort */
uint_t version : 1; /* Version sort */
uint_t reserved1 : 1;
/* The following settings are global */
uint_t curctx : 3; /* Current context number */
uint_t prefersel : 1; /* Prefer selection over current, if exists */
uint_t fileinfo : 1; /* Show file information on hover */
uint_t nonavopen : 1; /* Open file on right arrow or `l` */
uint_t autoenter : 1; /* auto-enter dir in type-to-nav mode */
uint_t reserved2 : 1;
uint_t useeditor : 1; /* Use VISUAL to open text files */
uint_t reserved3 : 3;
uint_t regex : 1; /* Use regex filters */
uint_t x11 : 1; /* Copy to system clipboard, show notis, xterm title */
uint_t timetype : 2; /* Time sort type (0: access, 1: change, 2: modification) */
uint_t cliopener : 1; /* All-CLI app opener */
uint_t waitedit : 1; /* For ops that can't be detached, used EDITOR */
uint_t rollover : 1; /* Roll over at edges */
} settings;
/* Non-persistent program-internal states (alphabeical order) */
typedef struct {
uint_t autofifo : 1; /* Auto-create NNN_FIFO */
uint_t autonext : 1; /* Auto-advance on file open */
uint_t dircolor : 1; /* Current status of dir color */
uint_t dirctx : 1; /* Show dirs in context color */
uint_t duinit : 1; /* Initialize disk usage */
uint_t fifomode : 1; /* FIFO notify mode: 0: preview, 1: explorer */
uint_t forcequit : 1; /* Do not prompt on quit */
uint_t initfile : 1; /* Positional arg is a file */
uint_t interrupt : 1; /* Program received an interrupt */
uint_t move : 1; /* Move operation */
uint_t oldcolor : 1; /* Use older colorscheme */
uint_t picked : 1; /* Plugin has picked files */
uint_t picker : 1; /* Write selection to user-specified file */
uint_t pluginit : 1; /* Plugin framework initialized */
uint_t prstssn : 1; /* Persistent session */
uint_t rangesel : 1; /* Range selection on */
uint_t runctx : 3; /* The context in which plugin is to be run */
uint_t runplugin : 1; /* Choose plugin mode */
uint_t selbm : 1; /* Select a bookmark from bookmarks directory */
uint_t selmode : 1; /* Set when selecting files */
uint_t stayonsel : 1; /* Disable auto-advance on selection */
uint_t trash : 2; /* Trash method 0: rm -rf, 1: trash-cli, 2: gio trash */
uint_t uidgid : 1; /* Show owner and group info */
uint_t usebsdtar : 1; /* Use bsdtar as default archive utility */
uint_t xprompt : 1; /* Use native prompt instead of readline prompt */
uint_t reserved : 4; /* Adjust when adding/removing a field */
} runstate;
/* Contexts or workspaces */
typedef struct {
char c_path[PATH_MAX]; /* Current dir */
char c_last[PATH_MAX]; /* Last visited dir */
char c_name[NAME_MAX + 1]; /* Current file name */
char c_fltr[REGEX_MAX]; /* Current filter */
settings c_cfg; /* Current configuration */
uint_t color; /* Color code for directories */
} context;
#ifndef NOSSN
typedef struct {
size_t ver;
size_t pathln[CTX_MAX];
size_t lastln[CTX_MAX];
size_t nameln[CTX_MAX];
size_t fltrln[CTX_MAX];
} session_header_t;
#endif
/* GLOBALS */
/* Configuration, contexts */
static settings cfg = {
.ctxactive = 1,
.autoenter = 1,
.timetype = 2, /* T_MOD */
.rollover = 1,
};
alignas(max_align_t) static context g_ctx[CTX_MAX];
static int ndents, cur, last, curscroll, last_curscroll, total_dents = ENTRY_INCR, scroll_lines = 1;
static int nselected;
#ifndef NOFIFO
static int fifofd = -1;
#endif
static time_t gtimesecs;
static uint_t idletimeout, selbufpos, selbuflen;
static ushort_t xlines, xcols;
static ushort_t idle;
static uchar_t maxbm, maxplug, maxorder;
static uchar_t cfgsort[CTX_MAX + 1];
static char *bmstr;
static char *pluginstr;
static char *orderstr;
static char *opener;
static char *editor;
static char *enveditor;
static char *pager;
static char *shell;
static char *home;
static char *initpath;
static char *cfgpath;
static char *selpath;
static char *listpath;
static char *listroot;
static char *plgpath;
static char *pnamebuf, *pselbuf, *findselpos;
static char *mark;
#ifndef NOX11
static char hostname[_POSIX_HOST_NAME_MAX + 1];
#endif
#ifndef NOFIFO
static char *fifopath;
#endif
static char *lastcmd;
static ullong_t *ihashbmp;
static struct entry *pdents;
static blkcnt_t dir_blocks;
static kv *bookmark;
static kv *plug;
static kv *order;
static uchar_t tmpfplen, homelen;
static uchar_t blk_shift = BLK_SHIFT_512;
#ifndef NOMOUSE
static int middle_click_key;
#endif
#ifdef PCRE
static pcre *archive_pcre;
#else
static regex_t archive_re;
#endif
/* pthread related */
#define NUM_DU_THREADS (4) /* Can use sysconf(_SC_NPROCESSORS_ONLN) */
#define DU_TEST (((node->fts_info & FTS_F) && \
(sb->st_nlink <= 1 || test_set_bit((uint_t)sb->st_ino))) || node->fts_info & FTS_DP)
static int threadbmp = -1; /* Has 1 in the bit position for idle threads */
static volatile int active_threads;
static pthread_mutex_t running_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t hardlink_mutex = PTHREAD_MUTEX_INITIALIZER;
static ullong_t *core_files;
static blkcnt_t *core_blocks;
static ullong_t num_files;
typedef struct {
char path[PATH_MAX];
int entnum;
ushort_t core;
bool mntpoint;
} thread_data;
static thread_data *core_data;
/* Retain old signal handlers */
static struct sigaction oldsighup;
static struct sigaction oldsigtstp;
static struct sigaction oldsigwinch;
/* For use in functions which are isolated and don't return the buffer */
alignas(max_align_t) static char g_buf[CMD_LEN_MAX];
/* For use as a scratch buffer in selection manipulation */
alignas(max_align_t) static char g_sel[PATH_MAX];
/* Buffer to store tmp file path to show selection, file stats and help */
alignas(max_align_t) static char g_tmpfpath[TMP_LEN_MAX];
/* Buffer to store plugins control pipe location */
alignas(max_align_t) static char g_pipepath[TMP_LEN_MAX];
/* Non-persistent runtime states */
static runstate g_state;
/* Options to identify file MIME */
#if defined(__APPLE__)
#define FILE_MIME_OPTS "-bIL"
#elif !defined(__sun) /* no MIME option for 'file' */
#define FILE_MIME_OPTS "-biL"
#endif
/* Macros for utilities */
#define UTIL_OPENER 0
#define UTIL_ATOOL 1
#define UTIL_BSDTAR 2
#define UTIL_UNZIP 3
#define UTIL_TAR 4
#define UTIL_LOCKER 5
#define UTIL_LAUNCH 6
#define UTIL_SH_EXEC 7
#define UTIL_BASH 8
#define UTIL_SSHFS 9
#define UTIL_RCLONE 10
#define UTIL_VI 11
#define UTIL_LESS 12
#define UTIL_SH 13
#define UTIL_FZF 14
#define UTIL_NTFY 15
#define UTIL_CBCP 16
#define UTIL_NMV 17
#define UTIL_TRASH_CLI 18
#define UTIL_GIO_TRASH 19
#define UTIL_RM_RF 20
#define UTIL_ARCHMNT 21
/* Utilities to open files, run actions */
static char * const utils[] = {
#ifdef __APPLE__
"/usr/bin/open",
#elif defined __CYGWIN__
"cygstart",
#elif defined __HAIKU__
"open",
#else
"xdg-open",
#endif
"atool",
"bsdtar",
"unzip",
"tar",
#ifdef __APPLE__
"bashlock",
#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
"lock",
#elif defined __HAIKU__
"peaclock",
#else
"vlock",
#endif
"launch",
"sh -c",
"bash",
"sshfs",
"rclone",
"vi",
"less",
"sh",
"fzf",
".ntfy",
".cbcp",
".nmv",
"trash-put",
"gio trash",
"rm -rf",
"archivemount",
};
/* Common strings */
#define MSG_ZERO 0 /* Unused */
#define MSG_0_ENTRIES 1
#define STR_TMPFILE 2
#define MSG_0_SELECTED 3
#define MSG_CANCEL 4
#define MSG_FAILED 5
#define MSG_SSN_NAME 6
#define MSG_CP_MV_AS 7
#define MSG_CUR_SEL_OPTS 8
#define MSG_FORCE_RM 9
#define MSG_SIZE_LIMIT 10
#define MSG_NEW_OPTS 11
#define MSG_CLI_MODE 12
#define MSG_OVERWRITE 13
#define MSG_SSN_OPTS 14
#define MSG_QUIT_ALL 15
#define MSG_HOSTNAME 16
#define MSG_ARCHIVE_NAME 17
#define MSG_OPEN_WITH 18
#define MSG_NEW_PATH 19
#define MSG_LINK_PREFIX 20
#define MSG_COPY_NAME 21
#define MSG_ENTER 22
#define MSG_SEL_MISSING 23
#define MSG_ACCESS 24
#define MSG_EMPTY_FILE 25
#define MSG_UNSUPPORTED 26
#define MSG_NOT_SET 27
#define MSG_EXISTS 28
#define MSG_FEW_COLUMNS 29
#define MSG_REMOTE_OPTS 30
#define MSG_RCLONE_DELAY 31
#define MSG_APP_NAME 32
#define MSG_ARCHIVE_OPTS 33
#define MSG_KEYS 34
#define MSG_INVALID_REG 35
#define MSG_ORDER 36
#define MSG_LAZY 37
#define MSG_FIRST 38
#define MSG_RM_TMP 39
#define MSG_INVALID_KEY 40
#define MSG_NOCHANGE 41
#define MSG_DIR_CHANGED 42
#define MSG_BM_NAME 43
#define MSG_FILE_LIMIT 44
static const char * const messages[] = {
"",
"0 entries",
"/.nnnXXXXXX",
"0 selected",
"cancelled",
"failed!",
"session name: ",
"'c'p/'m'v as?",
"'c'urrent/'s'el?",
"%s %s? [Esc cancels]",
"size limit exceeded",
"['f'ile]/'d'ir/'s'ym/'h'ard?",
"['g'ui]/'c'li?",
"overwrite?",
"'s'ave/'l'oad/'r'estore?",
"Quit all contexts?",
"remote name (- for hovered): ",
"archive [path/]name: ",
"open with: ",
"[path/]name: ",
"link prefix [@ for none]: ",
"copy [path/]name: ",
"\n'Enter' to continue",
"open failed",
"dir inaccessible",
"empty! edit/open with",
"?",
"not set",
"entry exists",
"too few cols!",
"'s'shfs/'r'clone?",
"refresh if slow",
"app: ",
"['l's]/'o'pen/e'x'tract/'m'nt?",
"keys:",
"invalid regex",
"'a'u/'d'u/'e'xt/'r'ev/'s'z/'t'm/'v'er/'c'lr/'^T'?",
"unmount failed! try lazy?",
"first file (\')/char?",
"remove tmp file?",
"invalid key",
"unchanged",
"dir changed, range sel off",
"name: ",
"file limit exceeded",
};
/* Supported configuration environment variables */
#define NNN_OPTS 0
#define NNN_BMS 1
#define NNN_PLUG 2
#define NNN_OPENER 3
#define NNN_COLORS 4
#define NNN_FCOLORS 5
#define NNNLVL 6
#define NNN_PIPE 7
#define NNN_MCLICK 8
#define NNN_SEL 9
#define NNN_ARCHIVE 10
#define NNN_ORDER 11
#define NNN_HELP 12 /* strings end here */
#define NNN_TRASH 13 /* flags begin here */
static const char * const env_cfg[] = {
"NNN_OPTS",
"NNN_BMS",
"NNN_PLUG",
"NNN_OPENER",
"NNN_COLORS",
"NNN_FCOLORS",
"NNNLVL",
"NNN_PIPE",
"NNN_MCLICK",
"NNN_SEL",
"NNN_ARCHIVE",
"NNN_ORDER",
"NNN_HELP",
"NNN_TRASH",
};
/* Required environment variables */
#define ENV_SHELL 0
#define ENV_VISUAL 1
#define ENV_EDITOR 2
#define ENV_PAGER 3
#define ENV_NCUR 4
static const char * const envs[] = {
"SHELL",
"VISUAL",
"EDITOR",
"PAGER",
"nnn",
};
/* Time type used */
#define T_ACCESS 0
#define T_CHANGE 1
#define T_MOD 2
#define PROGRESS_CP "cpg -giRp"
#define PROGRESS_MV "mvg -gi"
static char cp[sizeof PROGRESS_CP] = "cp -iRp";
static char mv[sizeof PROGRESS_MV] = "mv -i";
/* Archive commands */
static char * const archive_cmd[] = {"atool -a", "bsdtar -acvf", "zip -r", "tar -acvf"};
/* Tokens used for path creation */
#define TOK_BM 0
#define TOK_SSN 1
#define TOK_MNT 2
#define TOK_PLG 3
static const char * const toks[] = {
"bookmarks",
"sessions",
"mounts",
"plugins", /* must be the last entry */
};
/* Patterns */
#define P_CPMVFMT 0
#define P_CPMVRNM 1
#define P_ARCHIVE 2
#define P_REPLACE 3
#define P_ARCHIVE_CMD 4
static const char * const patterns[] = {
SED" -i 's|^\\(\\(.*/\\)\\(.*\\)$\\)|#\\1\\n\\3|' %s",
SED" 's|^\\([^#/][^/]\\?.*\\)$|%s/\\1|;s|^#\\(/.*\\)$|\\1|' "
"%s | tr '\\n' '\\0' | xargs -0 -n2 sh -c '%s \"$0\" \"$@\" < /dev/tty'",
"\\.(bz|bz2|gz|tar|taz|tbz|tbz2|tgz|z|zip)$", /* Basic formats that don't need external tools */
SED" -i 's|^%s\\(.*\\)$|%s\\1|' %s",
"xargs -0 %s %s < '%s'",
};
/* Colors */
#define C_BLK (CTX_MAX + 1) /* Block device: DarkSeaGreen1 */
#define C_CHR (C_BLK + 1) /* Character device: Yellow1 */
#define C_DIR (C_CHR + 1) /* Directory: DeepSkyBlue1 */
#define C_EXE (C_DIR + 1) /* Executable file: Green1 */
#define C_FIL (C_EXE + 1) /* Regular file: Normal */
#define C_HRD (C_FIL + 1) /* Hard link: Plum4 */
#define C_LNK (C_HRD + 1) /* Symbolic link: Cyan1 */
#define C_MIS (C_LNK + 1) /* Missing file OR file details: Grey62 */
#define C_ORP (C_MIS + 1) /* Orphaned symlink: DeepPink1 */
#define C_PIP (C_ORP + 1) /* Named pipe (FIFO): Orange1 */
#define C_SOC (C_PIP + 1) /* Socket: MediumOrchid1 */
#define C_UND (C_SOC + 1) /* Unknown OR 0B regular/exe file: Red1 */
static char gcolors[] = "c1e2272e006033f7c6d6abc4";
static uint_t fcolors[C_UND + 1] = {0};
/* Event handling */
#ifdef LINUX_INOTIFY
#define NUM_EVENT_SLOTS 32 /* Make room for 32 events */
#define EVENT_SIZE (sizeof(struct inotify_event))
#define EVENT_BUF_LEN (EVENT_SIZE * NUM_EVENT_SLOTS)
static int inotify_fd, inotify_wd = -1;
static uint_t INOTIFY_MASK = /* IN_ATTRIB | */ IN_CREATE | IN_DELETE | IN_DELETE_SELF
| IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
#elif defined(BSD_KQUEUE)
#define NUM_EVENT_SLOTS 1
#define NUM_EVENT_FDS 1
static int kq, event_fd = -1;
static struct kevent events_to_monitor[NUM_EVENT_FDS];
static uint_t KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK
| NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
static struct timespec gtimeout;
#elif defined(HAIKU_NM)
static bool haiku_nm_active = FALSE;
static haiku_nm_h haiku_hnd;
#endif
/* Function macros */
#define tolastln() move(xlines - 1, 0)
#define tocursor() move(cur + 2 - curscroll, 0)
#define exitcurses() endwin()
#define printwarn(presel) printwait(strerror(errno), presel)
#define istopdir(path) ((path)[1] == '\0' && (path)[0] == '/')
#define copycurname() xstrsncpy(lastname, ndents ? pdents[cur].name : "\0", NAME_MAX + 1)
#define settimeout() timeout(1000)
#define cleartimeout() timeout(-1)
#define errexit() printerr(__LINE__)
#define setdirwatch() (cfg.filtermode ? (presel = FILTER) : (watch = TRUE))
#define filterset() (g_ctx[cfg.curctx].c_fltr[1])
/* We don't care about the return value from strcmp() */
#define xstrcmp(a, b) (*(a) != *(b) ? -1 : strcmp((a), (b)))
/* A faster version of xisdigit */
#define xisdigit(c) ((unsigned int) (c) - '0' <= 9)
#define xerror() perror(xitoa(__LINE__))
#ifdef TOURBIN_QSORT
#define ENTLESS(i, j) (entrycmpfn(pdents + (i), pdents + (j)) < 0)
#define ENTSWAP(i, j) (swap_ent((i), (j)))
#define ENTSORT(pdents, ndents, entrycmpfn) QSORT((ndents), ENTLESS, ENTSWAP)
#else
#define ENTSORT(pdents, ndents, entrycmpfn) qsort((pdents), (ndents), sizeof(*(pdents)), (entrycmpfn))
#endif
/* Forward declarations */
static void redraw(char *path);
static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag);
static void move_cursor(int target, int ignore_scrolloff);
static char *load_input(int fd, const char *path);
static int set_sort_flags(int r);
static void statusbar(char *path);
static bool get_output(char *file, char *arg1, char *arg2, int fdout, bool page);
#ifndef NOFIFO
static void notify_fifo(bool force);
#endif
/* Functions */
static void sigint_handler(int sig)
{
(void) sig;
g_state.interrupt = 1;
}
static void clean_exit_sighandler(int sig)
{
(void) sig;
exitcurses();
/* This triggers cleanup() thanks to atexit() */
exit(EXIT_SUCCESS);
}
static char *xitoa(uint_t val)
{
static char dst[32] = {'\0'};
static const char digits[201] =
"0001020304050607080910111213141516171819"
"2021222324252627282930313233343536373839"
"4041424344454647484950515253545556575859"
"6061626364656667686970717273747576777879"
"8081828384858687888990919293949596979899";
uint_t next = 30, quo, i;
while (val >= 100) {
quo = val / 100;
i = (val - (quo * 100)) * 2;
val = quo;
dst[next] = digits[i + 1];
dst[--next] = digits[i];
--next;
}
/* Handle last 1-2 digits */
if (val < 10)
dst[next] = '0' + val;
else {
i = val * 2;
dst[next] = digits[i + 1];
dst[--next] = digits[i];
}
return &dst[next];
}
/* Return the integer value of a char representing HEX */
static uchar_t xchartohex(uchar_t c)
{
if (xisdigit(c))
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return c;
}
/*
* Source: https://elixir.bootlin.com/linux/latest/source/arch/alpha/include/asm/bitops.h
*/
static bool test_set_bit(uint_t nr)
{
nr &= HASH_BITS;
pthread_mutex_lock(&hardlink_mutex);
ullong_t *m = ((ullong_t *)ihashbmp) + (nr >> 6);
if (*m & (1 << (nr & 63))) {
pthread_mutex_unlock(&hardlink_mutex);
return FALSE;
}
*m |= 1 << (nr & 63);
pthread_mutex_unlock(&hardlink_mutex);
return TRUE;
}
#ifndef __APPLE__
/* Increase the limit on open file descriptors, if possible */
static void max_openfds(void)
{
struct rlimit rl;
if (!getrlimit(RLIMIT_NOFILE, &rl))
if (rl.rlim_cur < rl.rlim_max) {
rl.rlim_cur = rl.rlim_max;
setrlimit(RLIMIT_NOFILE, &rl);
}
}
#endif
/*
* Wrapper to realloc()
* Frees current memory if realloc() fails and returns NULL.
*
* The *alloc() family returns aligned address: https://man7.org/linux/man-pages/man3/malloc.3.html
*/
static void *xrealloc(void *pcur, size_t len)
{
void *pmem = realloc(pcur, len);
if (!pmem)
free(pcur);
return pmem;
}
/*
* Just a safe strncpy(3)
* Always null ('\0') terminates if both src and dest are valid pointers.
* Returns the number of bytes copied including terminating null byte.
*/
static size_t xstrsncpy(char *restrict dst, const char *restrict src, size_t n)
{
char *end = memccpy(dst, src, '\0', n);
if (!end) {
dst[n - 1] = '\0'; // NOLINT
end = dst + n; /* If we return n here, binary size increases due to auto-inlining */
}
return end - dst;
}
static inline size_t xstrlen(const char *restrict s)
{
#if !defined(__GLIBC__)
return strlen(s); // NOLINT
#else
return (char *)rawmemchr(s, '\0') - s; // NOLINT
#endif
}
static char *xstrdup(const char *restrict s)
{
size_t len = xstrlen(s) + 1;
char *ptr = malloc(len);
return ptr ? memcpy(ptr, s, len) : NULL;