1 /* needed for some ncurses stuff */
2 #define _XOPEN_SOURCE_EXTENDED
3 #define _FILE_OFFSET_BITS 64
31 #define FM_SHELL "/bin/sh"
35 #define FM_PAGER "/usr/bin/less"
40 struct option opts[] = {
41 {"help", no_argument, NULL, 'h'},
42 {"version", no_argument, NULL, 'v'},
46 static char clipboard[PATH_MAX];
49 #define BUFLEN PATH_MAX
50 static char BUF1[BUFLEN];
51 static char BUF2[BUFLEN];
52 static char INPUT[BUFLEN];
53 static wchar_t WBUF[BUFLEN];
55 /* Paths to external programs. */
56 static char *user_shell;
57 static char *user_pager;
58 static char *user_editor;
59 static char *user_open;
61 /* Listing view parameters. */
62 #define HEIGHT (LINES-4)
63 #define STATUSPOS (COLS-16)
65 /* Listing view flags. */
66 #define SHOW_FILES 0x01u
67 #define SHOW_DIRS 0x02u
68 #define SHOW_HIDDEN 0x04u
70 /* Marks parameters. */
72 #define BULK_THRESH 256
74 /* Information associated to each entry in listing. */
83 /* Dynamic array of marked entries. */
85 char dirpath[PATH_MAX];
91 /* Line editing state. */
93 wchar_t buffer[BUFLEN + 1];
97 /* Each tab only stores the following information. */
112 static struct state {
120 volatile sig_atomic_t pending_usr1;
121 volatile sig_atomic_t pending_winch;
126 /* Macros for accessing global state. */
127 #define ENAME(I) fm.rows[I].name
128 #define ESIZE(I) fm.rows[I].size
129 #define EMODE(I) fm.rows[I].mode
130 #define ISLINK(I) fm.rows[I].islink
131 #define MARKED(I) fm.rows[I].marked
132 #define SCROLL fm.tabs[fm.tab].scroll
133 #define ESEL fm.tabs[fm.tab].esel
134 #define FLAGS fm.tabs[fm.tab].flags
135 #define CWD fm.tabs[fm.tab].cwd
138 #define MIN(A, B) ((A) < (B) ? (A) : (B))
139 #define MAX(A, B) ((A) > (B) ? (A) : (B))
140 #define ISDIR(E) (strchr((E), '/') != NULL)
141 #define CTRL(x) ((x) & 0x1f)
142 #define nitems(a) (sizeof(a)/sizeof(a[0]))
144 /* Line Editing Macros. */
145 #define EDIT_FULL(E) ((E).left == (E).right)
146 #define EDIT_CAN_LEFT(E) ((E).left)
147 #define EDIT_CAN_RIGHT(E) ((E).right < BUFLEN-1)
148 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
149 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
150 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
151 #define EDIT_BACKSPACE(E) (E).left--
152 #define EDIT_DELETE(E) (E).right++
153 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = BUFLEN-1; } while(0)
155 enum editstate { CONTINUE, CONFIRM, CANCEL };
156 enum color { DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE, BLACK };
158 typedef int (*PROCESS)(const char *path);
161 #define __dead __attribute__((noreturn))
164 static inline __dead void
165 quit(const char *reason)
174 err(1, "%s", reason);
182 if ((d = malloc(size)) == NULL)
188 xcalloc(size_t nmemb, size_t size)
192 if ((d = calloc(nmemb, size)) == NULL)
198 xrealloc(void *p, size_t size)
202 if ((d = realloc(p, size)) == NULL)
208 init_marks(struct marks *marks)
210 strcpy(marks->dirpath, "");
211 marks->bulk = BULK_INIT;
213 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
216 /* Unmark all entries. */
218 mark_none(struct marks *marks)
222 strcpy(marks->dirpath, "");
223 for (i = 0; i < marks->bulk && marks->nentries; i++)
224 if (marks->entries[i]) {
225 free(marks->entries[i]);
226 marks->entries[i] = NULL;
229 if (marks->bulk > BULK_THRESH) {
230 /* Reset bulk to free some memory. */
231 free(marks->entries);
232 marks->bulk = BULK_INIT;
233 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
238 add_mark(struct marks *marks, char *dirpath, char *entry)
242 if (!strcmp(marks->dirpath, dirpath)) {
243 /* Append mark to directory. */
244 if (marks->nentries == marks->bulk) {
245 /* Expand bulk to accomodate new entry. */
246 int extra = marks->bulk / 2;
247 marks->bulk += extra; /* bulk *= 1.5; */
248 marks->entries = xrealloc(marks->entries,
249 marks->bulk * sizeof(*marks->entries));
250 memset(&marks->entries[marks->nentries], 0,
251 extra * sizeof(*marks->entries));
254 /* Search for empty slot (there must be one). */
255 for (i = 0; i < marks->bulk; i++)
256 if (!marks->entries[i])
260 /* Directory changed. Discard old marks. */
262 strcpy(marks->dirpath, dirpath);
265 marks->entries[i] = xmalloc(strlen(entry) + 1);
266 strcpy(marks->entries[i], entry);
271 del_mark(struct marks *marks, char *entry)
275 if (marks->nentries > 1) {
276 for (i = 0; i < marks->bulk; i++)
277 if (marks->entries[i] &&
278 !strcmp(marks->entries[i], entry))
280 free(marks->entries[i]);
281 marks->entries[i] = NULL;
288 free_marks(struct marks *marks)
292 for (i = 0; i < marks->bulk && marks->nentries; i++)
293 if (marks->entries[i]) {
294 free(marks->entries[i]);
297 free(marks->entries);
307 handle_winch(int sig)
309 fm.pending_winch = 1;
313 enable_handlers(void)
317 memset(&sa, 0, sizeof(struct sigaction));
318 sa.sa_handler = handle_usr1;
319 sigaction(SIGUSR1, &sa, NULL);
320 sa.sa_handler = handle_winch;
321 sigaction(SIGWINCH, &sa, NULL);
325 disable_handlers(void)
329 memset(&sa, 0, sizeof(struct sigaction));
330 sa.sa_handler = SIG_DFL;
331 sigaction(SIGUSR1, &sa, NULL);
332 sigaction(SIGWINCH, &sa, NULL);
335 static void reload(void);
336 static void update_view(void);
338 /* Handle any signals received since last call. */
342 if (fm.pending_usr1) {
343 /* SIGUSR1 received: refresh directory listing. */
347 if (fm.pending_winch) {
348 /* SIGWINCH received: resize application accordingly. */
353 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
354 if (HEIGHT < fm.nfiles && SCROLL + HEIGHT > fm.nfiles)
355 SCROLL = ESEL - HEIGHT;
357 fm.pending_winch = 0;
362 * This function must be used in place of getch(). It handles signals
363 * while waiting for user input.
370 while ((ch = getch()) == ERR)
376 * This function must be used in place of get_wch(). It handles
377 * signals while waiting for user input.
380 fm_get_wch(wint_t *wch)
384 while ((ret = get_wch(wch)) == (wint_t)ERR)
389 /* Get user programs from the environment. */
391 #define FM_ENV(dst, src) if ((dst = getenv("FM_" #src)) == NULL) \
397 FM_ENV(user_shell, SHELL);
398 FM_ENV(user_pager, PAGER);
399 FM_ENV(user_editor, VISUAL);
401 FM_ENV(user_editor, EDITOR);
402 FM_ENV(user_open, OPEN);
405 /* Do a fork-exec to external program (e.g. $EDITOR). */
407 spawn(const char *argv0, ...)
412 const char *argv[16], *last;
415 memset(argv, 0, sizeof(argv));
419 for (i = 1; i < nitems(argv); ++i) {
420 last = va_arg(ap, const char *);
433 switch (pid = fork()) {
437 setenv("RVSEL", fm.nfiles ? ENAME(ESEL) : "", 1);
438 execvp(argv[0], (char *const *)argv);
441 waitpid(pid, &status, 0);
443 kill(getpid(), SIGWINCH);
448 shell_escaped_cat(char *buf, char *str, size_t n)
450 char *p = buf + strlen(buf);
452 for (n--; n; n--, str++) {
473 open_with_env(char *program, char *path)
477 strncpy(BUF1, program, BUFLEN - 1);
478 strncat(BUF1, " ", BUFLEN - strlen(program) - 1);
479 shell_escaped_cat(BUF1, path, BUFLEN - strlen(program) - 2);
480 spawn(RV_SHELL, "-c", BUF1, NULL );
482 spawn(program, path, NULL);
493 setlocale(LC_ALL, "");
496 timeout(100); /* For getch(). */
498 nonl(); /* No NL->CR/NL on output. */
499 intrflush(stdscr, FALSE);
500 keypad(stdscr, TRUE);
501 curs_set(FALSE); /* Hide blinking cursor. */
505 #ifdef NCURSES_EXT_FUNCS
506 use_default_colors();
511 init_pair(RED, COLOR_RED, bg);
512 init_pair(GREEN, COLOR_GREEN, bg);
513 init_pair(YELLOW, COLOR_YELLOW, bg);
514 init_pair(BLUE, COLOR_BLUE, bg);
515 init_pair(CYAN, COLOR_CYAN, bg);
516 init_pair(MAGENTA, COLOR_MAGENTA, bg);
517 init_pair(WHITE, COLOR_WHITE, bg);
518 init_pair(BLACK, COLOR_BLACK, bg);
520 atexit((void (*)(void))endwin);
524 /* Update the listing view. */
533 mvhline(0, 0, ' ', COLS);
534 attr_on(A_BOLD, NULL);
535 color_set(RVC_TABNUM, NULL);
536 mvaddch(0, COLS - 2, fm.tab + '0');
537 attr_off(A_BOLD, NULL);
538 if (fm.marks.nentries) {
539 numsize = snprintf(BUF1, BUFLEN, "%d", fm.marks.nentries);
540 color_set(RVC_MARKS, NULL);
541 mvaddstr(0, COLS - 3 - numsize, BUF1);
544 color_set(RVC_CWD, NULL);
545 mbstowcs(WBUF, CWD, PATH_MAX);
546 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
547 wcolor_set(fm.window, RVC_BORDER, NULL);
548 wborder(fm.window, 0, 0, 0, 0, 0, 0, 0, 0);
549 ESEL = MAX(MIN(ESEL, fm.nfiles - 1), 0);
552 * Selection might not be visible, due to cursor wrapping or
553 * window shrinking. In that case, the scroll must be moved to
556 if (fm.nfiles > HEIGHT) {
557 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
558 SCROLL = MIN(MAX(SCROLL, 0), fm.nfiles - HEIGHT);
561 marking = !strcmp(CWD, fm.marks.dirpath);
562 for (i = 0, j = SCROLL; i < HEIGHT && j < fm.nfiles; i++, j++) {
563 ishidden = ENAME(j)[0] == '.';
565 wattr_on(fm.window, A_REVERSE, NULL);
567 wcolor_set(fm.window, RVC_LINK, NULL);
569 wcolor_set(fm.window, RVC_HIDDEN, NULL);
570 else if (S_ISREG(EMODE(j))) {
571 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
572 wcolor_set(fm.window, RVC_EXEC, NULL);
574 wcolor_set(fm.window, RVC_REG, NULL);
575 } else if (S_ISDIR(EMODE(j)))
576 wcolor_set(fm.window, RVC_DIR, NULL);
577 else if (S_ISCHR(EMODE(j)))
578 wcolor_set(fm.window, RVC_CHR, NULL);
579 else if (S_ISBLK(EMODE(j)))
580 wcolor_set(fm.window, RVC_BLK, NULL);
581 else if (S_ISFIFO(EMODE(j)))
582 wcolor_set(fm.window, RVC_FIFO, NULL);
583 else if (S_ISSOCK(EMODE(j)))
584 wcolor_set(fm.window, RVC_SOCK, NULL);
585 if (S_ISDIR(EMODE(j))) {
586 mbstowcs(WBUF, ENAME(j), PATH_MAX);
590 const char *suffix, *suffixes = "BKMGTPEZY";
591 off_t human_size = ESIZE(j) * 10;
592 int length = mbstowcs(WBUF, ENAME(j), PATH_MAX);
593 int namecols = wcswidth(WBUF, length);
594 for (suffix = suffixes; human_size >= 10240; suffix++)
595 human_size = (human_size + 512) / 1024;
597 swprintf(WBUF + length, PATH_MAX - length,
599 (int)(COLS - namecols - 6),
600 (int)human_size / 10, *suffix);
602 swprintf(WBUF + length, PATH_MAX - length,
604 (int)(COLS - namecols - 8),
605 (int)human_size / 10,
606 (int)human_size % 10, *suffix);
608 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
609 mvwaddnwstr(fm.window, i + 1, 2, WBUF, COLS - 4);
610 if (marking && MARKED(j)) {
611 wcolor_set(fm.window, RVC_MARKS, NULL);
612 mvwaddch(fm.window, i + 1, 1, RVS_MARK);
614 mvwaddch(fm.window, i + 1, 1, ' ');
616 wattr_off(fm.window, A_REVERSE, NULL);
618 for (; i < HEIGHT; i++)
619 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
620 if (fm.nfiles > HEIGHT) {
622 center = (SCROLL + HEIGHT / 2) * HEIGHT / fm.nfiles;
623 height = (HEIGHT - 1) * HEIGHT / fm.nfiles;
626 wcolor_set(fm.window, RVC_SCROLLBAR, NULL);
627 mvwvline(fm.window, center - height/2 + 1, COLS - 1,
628 RVS_SCROLLBAR, height);
630 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
631 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
632 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
636 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, fm.nfiles);
637 snprintf(BUF1 + 3, BUFLEN - 3, "%12s", BUF2);
638 color_set(RVC_STATUS, NULL);
639 mvaddstr(LINES - 1, STATUSPOS, BUF1);
643 /* Show a message on the status bar. */
644 static void __attribute__((format(printf, 2, 3)))
645 message(enum color c, const char *fmt, ...)
651 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
654 pos = (STATUSPOS - len) / 2;
655 attr_on(A_BOLD, NULL);
657 mvaddstr(LINES - 1, pos, BUF1);
658 color_set(DEFAULT, NULL);
659 attr_off(A_BOLD, NULL);
662 /* Clear message area, leaving only status info. */
666 mvhline(LINES - 1, 0, ' ', STATUSPOS);
669 /* Comparison used to sort listing entries. */
671 rowcmp(const void *a, const void *b)
673 int isdir1, isdir2, cmpdir;
674 const struct row *r1 = a;
675 const struct row *r2 = b;
676 isdir1 = S_ISDIR(r1->mode);
677 isdir2 = S_ISDIR(r2->mode);
678 cmpdir = isdir2 - isdir1;
679 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
682 /* Get all entries in current working directory. */
684 ls(struct row **rowsp, uint8_t flags)
692 if (!(dp = opendir(".")))
694 n = -2; /* We don't want the entries "." and "..". */
702 rows = xmalloc(n * sizeof(*rows));
704 while ((ep = readdir(dp))) {
705 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
707 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
709 lstat(ep->d_name, &statbuf);
710 rows[i].islink = S_ISLNK(statbuf.st_mode);
711 stat(ep->d_name, &statbuf);
712 if (S_ISDIR(statbuf.st_mode)) {
713 if (flags & SHOW_DIRS) {
714 rows[i].name = xmalloc(strlen(ep->d_name) + 2);
715 strcpy(rows[i].name, ep->d_name);
717 strcat(rows[i].name, "/");
718 rows[i].mode = statbuf.st_mode;
721 } else if (flags & SHOW_FILES) {
722 rows[i].name = xmalloc(strlen(ep->d_name) + 1);
723 strcpy(rows[i].name, ep->d_name);
724 rows[i].size = statbuf.st_size;
725 rows[i].mode = statbuf.st_mode;
729 n = i; /* Ignore unused space in array caused by filters. */
730 qsort(rows, n, sizeof(*rows), rowcmp);
737 free_rows(struct row **rowsp, int nfiles)
741 for (i = 0; i < nfiles; i++)
742 free((*rowsp)[i].name);
747 /* Change working directory to the path in CWD. */
753 message(CYAN, "Loading \"%s\"...", CWD);
755 if (chdir(CWD) == -1) {
756 getcwd(CWD, PATH_MAX - 1);
757 if (CWD[strlen(CWD) - 1] != '/')
764 free_rows(&fm.rows, fm.nfiles);
765 fm.nfiles = ls(&fm.rows, FLAGS);
766 if (!strcmp(CWD, fm.marks.dirpath)) {
767 for (i = 0; i < fm.nfiles; i++) {
768 for (j = 0; j < fm.marks.bulk; j++)
769 if (fm.marks.entries[j] &&
770 !strcmp(fm.marks.entries[j], ENAME(i)))
772 MARKED(i) = j < fm.marks.bulk;
775 for (i = 0; i < fm.nfiles; i++)
782 /* Select a target entry, if it is present. */
784 try_to_sel(const char *target)
788 while ((ESEL + 1) < fm.nfiles && S_ISDIR(EMODE(ESEL)))
790 while ((ESEL + 1) < fm.nfiles && strcoll(ENAME(ESEL), target) < 0)
794 /* Reload CWD, but try to keep selection. */
799 strcpy(INPUT, ENAME(ESEL));
808 count_dir(const char *path)
813 char subpath[PATH_MAX];
816 if (!(dp = opendir(path)))
819 while ((ep = readdir(dp))) {
820 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
822 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
823 lstat(subpath, &statbuf);
824 if (S_ISDIR(statbuf.st_mode)) {
825 strcat(subpath, "/");
826 total += count_dir(subpath);
828 total += statbuf.st_size;
843 chdir(fm.marks.dirpath);
844 for (i = 0; i < fm.marks.bulk; i++) {
845 entry = fm.marks.entries[i];
848 total += count_dir(entry);
850 lstat(entry, &statbuf);
851 total += statbuf.st_size;
860 * Recursively process a source directory using CWD as destination
861 * root. For each node (i.e. directory), do the following:
863 * 1. call pre(destination);
864 * 2. call proc() on every child leaf (i.e. files);
865 * 3. recurse into every child node;
866 * 4. call pos(source).
868 * E.g. to move directory /src/ (and all its contents) inside /dst/:
869 * strcpy(CWD, "/dst/");
870 * process_dir(adddir, movfile, deldir, "/src/");
873 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
879 char subpath[PATH_MAX];
883 char dstpath[PATH_MAX];
884 strcpy(dstpath, CWD);
885 strcat(dstpath, path + strlen(fm . marks . dirpath));
888 if (!(dp = opendir(path)))
890 while ((ep = readdir(dp))) {
891 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
893 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
894 lstat(subpath, &statbuf);
895 if (S_ISDIR(statbuf.st_mode)) {
896 strcat(subpath, "/");
897 ret |= process_dir(pre, proc, pos, subpath);
899 ret |= proc(subpath);
908 * Process all marked entries using CWD as destination root. All
909 * marked entries that are directories will be recursively processed.
910 * See process_dir() for details on the parameters.
913 process_marked(PROCESS pre, PROCESS proc, PROCESS pos, const char *msg_doing,
914 const char *msg_done)
921 message(CYAN, "%s...", msg_doing);
923 fm.prog = (struct prog){0, count_marked(), msg_doing};
924 for (i = 0; i < fm.marks.bulk; i++) {
925 entry = fm.marks.entries[i];
928 snprintf(path, PATH_MAX, "%s%s", fm.marks.dirpath,
931 if (!strncmp(path, CWD, strlen(path)))
934 ret = process_dir(pre, proc, pos, path);
938 del_mark(&fm.marks, entry);
945 if (!fm.marks.nentries)
946 message(GREEN, "%s all marked entries.", msg_done);
948 message(RED, "Some errors occured while %s.", msg_doing);
953 update_progress(off_t delta)
959 fm.prog.partial += delta;
960 percent = (int)(fm.prog.partial * 100 / fm.prog.total);
961 message(CYAN, "%s...%d%%", fm.prog.msg, percent);
965 /* Wrappers for file operations. */
967 delfile(const char *path)
972 ret = lstat(path, &st);
975 update_progress(st.st_size);
979 static PROCESS deldir = rmdir;
981 addfile(const char *path)
983 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
986 ret = creat(path, 0644);
993 cpyfile(const char *srcpath)
999 char dstpath[PATH_MAX];
1001 strcpy(dstpath, CWD);
1002 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
1003 ret = lstat(srcpath, &st);
1006 if (S_ISLNK(st.st_mode)) {
1007 ret = readlink(srcpath, BUF1, BUFLEN - 1);
1011 ret = symlink(BUF1, dstpath);
1013 ret = src = open(srcpath, O_RDONLY);
1016 ret = dst = creat(dstpath, st.st_mode);
1019 while ((size = read(src, buf, BUFSIZ)) > 0) {
1020 write(dst, buf, size);
1021 update_progress(size);
1032 adddir(const char *path)
1037 ret = stat(CWD, &st);
1040 return mkdir(path, st.st_mode);
1044 movfile(const char *srcpath)
1048 char dstpath[PATH_MAX];
1050 strcpy(dstpath, CWD);
1051 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
1052 ret = rename(srcpath, dstpath);
1054 ret = lstat(dstpath, &st);
1057 update_progress(st.st_size);
1058 } else if (errno == EXDEV) {
1059 ret = cpyfile(srcpath);
1062 ret = unlink(srcpath);
1068 start_line_edit(const char *init_input)
1071 strncpy(INPUT, init_input, BUFLEN);
1072 fm.edit.left = mbstowcs(fm.edit.buffer, init_input, BUFLEN);
1073 fm.edit.right = BUFLEN - 1;
1074 fm.edit.buffer[BUFLEN] = L'\0';
1078 /* Read input and change editing state accordingly. */
1079 static enum editstate
1082 wchar_t eraser, killer, wch;
1085 ret = fm_get_wch((wint_t *)&wch);
1086 erasewchar(&eraser);
1088 if (ret == KEY_CODE_YES) {
1089 if (wch == KEY_ENTER) {
1092 } else if (wch == KEY_LEFT) {
1093 if (EDIT_CAN_LEFT(fm.edit))
1095 } else if (wch == KEY_RIGHT) {
1096 if (EDIT_CAN_RIGHT(fm.edit))
1097 EDIT_RIGHT(fm.edit);
1098 } else if (wch == KEY_UP) {
1099 while (EDIT_CAN_LEFT(fm.edit))
1101 } else if (wch == KEY_DOWN) {
1102 while (EDIT_CAN_RIGHT(fm.edit))
1103 EDIT_RIGHT(fm.edit);
1104 } else if (wch == KEY_BACKSPACE) {
1105 if (EDIT_CAN_LEFT(fm.edit))
1106 EDIT_BACKSPACE(fm.edit);
1107 } else if (wch == KEY_DC) {
1108 if (EDIT_CAN_RIGHT(fm.edit))
1109 EDIT_DELETE(fm.edit);
1112 if (wch == L'\r' || wch == L'\n') {
1115 } else if (wch == L'\t') {
1118 } else if (wch == eraser) {
1119 if (EDIT_CAN_LEFT(fm.edit))
1120 EDIT_BACKSPACE(fm.edit);
1121 } else if (wch == killer) {
1122 EDIT_CLEAR(fm.edit);
1124 } else if (iswprint(wch)) {
1125 if (!EDIT_FULL(fm.edit))
1126 EDIT_INSERT(fm.edit, wch);
1129 /* Encode edit contents in INPUT. */
1130 fm.edit.buffer[fm.edit.left] = L'\0';
1131 length = wcstombs(INPUT, fm.edit.buffer, BUFLEN);
1132 wcstombs(&INPUT[length], &fm.edit.buffer[fm.edit.right + 1],
1137 /* Update line input on the screen. */
1139 update_input(const char *prompt, enum color c)
1141 int plen, ilen, maxlen;
1143 plen = strlen(prompt);
1144 ilen = mbstowcs(NULL, INPUT, 0);
1145 maxlen = STATUSPOS - plen - 2;
1146 if (ilen - fm.edit_scroll < maxlen)
1147 fm.edit_scroll = MAX(ilen - maxlen, 0);
1148 else if (fm.edit.left > fm.edit_scroll + maxlen - 1)
1149 fm.edit_scroll = fm.edit.left - maxlen;
1150 else if (fm.edit.left < fm.edit_scroll)
1151 fm.edit_scroll = MAX(fm.edit.left - maxlen, 0);
1152 color_set(RVC_PROMPT, NULL);
1153 mvaddstr(LINES - 1, 0, prompt);
1155 mbstowcs(WBUF, INPUT, COLS);
1156 mvaddnwstr(LINES - 1, plen, &WBUF[fm.edit_scroll], maxlen);
1157 mvaddch(LINES - 1, plen + MIN(ilen - fm.edit_scroll, maxlen + 1),
1159 color_set(DEFAULT, NULL);
1161 mvaddch(LINES - 1, plen - 1, '<');
1162 if (ilen > fm.edit_scroll + maxlen)
1163 mvaddch(LINES - 1, plen + maxlen, '>');
1164 move(LINES - 1, plen + fm.edit.left - fm.edit_scroll);
1171 ESEL = MIN(ESEL + 1, fm.nfiles - 1);
1178 ESEL = MAX(ESEL - 1, 0);
1182 cmd_scroll_down(void)
1186 ESEL = MIN(ESEL + HEIGHT, fm.nfiles - 1);
1187 if (fm.nfiles > HEIGHT)
1188 SCROLL = MIN(SCROLL + HEIGHT, fm.nfiles - HEIGHT);
1196 ESEL = MAX(ESEL - HEIGHT, 0);
1197 SCROLL = MAX(SCROLL - HEIGHT, 0);
1203 spawn("man", "fm", NULL);
1214 cmd_jump_bottom(void)
1217 ESEL = fm.nfiles - 1;
1223 if (!fm.nfiles || !S_ISDIR(EMODE(ESEL)))
1225 if (chdir(ENAME(ESEL)) == -1) {
1226 message(RED, "cd: %s: %s", ENAME(ESEL), strerror(errno));
1229 strlcat(CWD, ENAME(ESEL), sizeof(CWD));
1236 char *dirname, first;
1238 if (!strcmp(CWD, "/"))
1241 /* dirname(3) basically */
1242 dirname = strrchr(CWD, '/');
1244 dirname = strrchr(CWD, '/') + 1;
1250 strlcat(dirname, "/", sizeof(dirname));
1251 try_to_sel(dirname);
1253 if (fm.nfiles > HEIGHT)
1254 SCROLL = ESEL - HEIGHT / 2;
1262 if ((home = getenv("HOME")) == NULL) {
1263 message(RED, "HOME is not defined!");
1267 strlcpy(CWD, home, sizeof(CWD));
1268 if (*CWD != '\0' && CWD[strlen(CWD) - 1] != '/')
1269 strlcat(CWD, "/", sizeof(CWD));
1279 if ((path = getenv("CLIP")) == NULL ||
1280 (f = fopen(path, "w")) == NULL) {
1281 /* use internal clipboard */
1282 strlcpy(clipboard, CWD, sizeof(clipboard));
1283 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1287 fprintf(f, "%s%s", CWD, ENAME(ESEL));
1293 cmd_paste_path(void)
1301 if ((path = getenv("CLIP")) != NULL &&
1302 (f = fopen(path, "w")) != NULL) {
1303 r = fread(clipboard, 1, sizeof(clipboard)-1, f);
1305 if (r == -1 || r == 0)
1307 if ((nl = memmem(clipboard, r, "", 1)) == NULL)
1311 strlcpy(p, clipboard, sizeof(p));
1312 strlcpy(CWD, clipboard, sizeof(CWD));
1313 if ((nl = strrchr(CWD, '/')) != NULL) {
1315 nl = strrchr(p, '/');
1318 if (strcmp(CWD, "/") != 0)
1319 strlcat(CWD, "/", sizeof(CWD));
1325 memset(clipboard, 0, sizeof(clipboard));
1339 if ((shell = getenv("SHELL")) == NULL)
1349 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1352 if ((pager = getenv("PAGER")) == NULL)
1354 spawn(pager, ENAME(ESEL), NULL);
1371 {'<', K_META, cmd_jump_top, X_UPDV},
1372 {'>', K_META, cmd_jump_bottom, X_UPDV},
1373 {'?', 0, cmd_man, 0},
1374 {'G', 0, cmd_jump_bottom, X_UPDV},
1375 {'H', 0, cmd_home, X_UPDV},
1376 {'J', 0, cmd_scroll_down, X_UPDV},
1377 {'K', 0, cmd_scroll_up, X_UPDV},
1378 {'P', 0, cmd_paste_path, X_UPDV},
1379 {'V', K_CTRL, cmd_scroll_down, X_UPDV},
1380 {'Y', 0, cmd_copy_path, X_UPDV},
1381 {'^', 0, cmd_cd_up, X_UPDV},
1382 {'b', 0, cmd_cd_up, X_UPDV},
1383 {'f', 0, cmd_cd_down, X_UPDV},
1384 {'g', 0, cmd_jump_top, X_UPDV},
1385 {'g', K_CTRL, NULL, X_UPDV},
1386 {'h', 0, cmd_cd_up, X_UPDV},
1387 {'j', 0, cmd_down, X_UPDV},
1388 {'k', 0, cmd_up, X_UPDV},
1389 {'l', 0, cmd_cd_down, X_UPDV},
1390 {'l', K_CTRL, cmd_reload, X_UPDV},
1391 {'n', 0, cmd_down, X_UPDV},
1392 {'n', K_CTRL, cmd_down, X_UPDV},
1393 {'m', K_CTRL, cmd_shell, X_UPDV},
1394 {'p', 0, cmd_up, X_UPDV},
1395 {'p', K_CTRL, cmd_up, X_UPDV},
1396 {'q', 0, NULL, X_QUIT},
1397 {'v', 0, cmd_view, X_UPDV},
1398 {'v', K_META, cmd_scroll_up, X_UPDV},
1399 {KEY_DOWN, 0, cmd_scroll_down, X_UPDV},
1400 {KEY_NPAGE, 0, cmd_scroll_down, X_UPDV},
1401 {KEY_PPAGE, 0, cmd_scroll_up, X_UPDV},
1402 {KEY_RESIZE, 0, NULL, X_UPDV},
1403 {KEY_RESIZE, K_META, NULL, X_UPDV},
1404 {KEY_UP, 0, cmd_scroll_up, X_UPDV},
1414 if ((ch = fm_getch()) == '\e') {
1422 for (i = 0; i < nitems(bindings); ++i) {
1425 if (b->chflags & K_CTRL)
1427 if ((!meta && b->chflags & K_META) || ch != c)
1430 if (b->flags & X_QUIT)
1434 if (b->flags & X_UPDV)
1440 message(RED, "%s%s is undefined",
1441 meta ? "M-": "", keyname(ch));
1447 main(int argc, char *argv[])
1453 const char *clip_path;
1455 enum editstate edit_stat;
1456 FILE *save_cwd_file = NULL;
1457 FILE *save_marks_file = NULL;
1460 while ((ch = getopt_long(argc, argv, "d:hm:v", opts, NULL)) != -1) {
1463 if ((save_cwd_file = fopen(optarg, "w")) == NULL)
1464 err(1, "open %s", optarg);
1468 "Usage: fm [-hv] [-d file] [-m file] [dirs...]\n"
1469 "Browse current directory or the ones specified.\n"
1471 "See fm(1) for more information.\n"
1472 "fm homepage <https://github.com/omar-polo/fm>\n");
1475 if ((save_marks_file = fopen(optarg, "a")) == NULL)
1476 err(1, "open %s", optarg);
1479 printf("version: fm %s\n", RV_VERSION);
1484 if (pledge("stdio rpath wpath cpath tty proc exec", NULL) == -1)
1487 get_user_programs();
1490 for (i = 0; i < 10; i++) {
1491 fm.tabs[i].esel = fm.tabs[i].scroll = 0;
1492 fm.tabs[i].flags = RV_FLAGS;
1494 strcpy(fm.tabs[0].cwd, getenv("HOME"));
1495 for (i = 1; i < argc && i < 10; i++) {
1496 if ((d = opendir(argv[i]))) {
1497 realpath(argv[i], fm.tabs[i].cwd);
1500 strcpy(fm.tabs[i].cwd, fm.tabs[0].cwd);
1502 getcwd(fm.tabs[i].cwd, PATH_MAX);
1503 for (i++; i < 10; i++)
1504 strcpy(fm.tabs[i].cwd, fm.tabs[i - 1].cwd);
1505 for (i = 0; i < 10; i++)
1506 if (fm.tabs[i].cwd[strlen(fm.tabs[i].cwd) - 1] != '/')
1507 strcat(fm.tabs[i].cwd, "/");
1509 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
1510 init_marks(&fm.marks);
1512 strlcpy(clipboard, CWD, sizeof(clipboard));
1514 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1519 free_rows(&fm.rows, fm.nfiles);
1521 if (save_cwd_file != NULL) {
1522 fputs(CWD, save_cwd_file);
1523 fclose(save_cwd_file);
1525 if (save_marks_file != NULL) {
1526 for (i = 0; i < fm.marks.bulk; i++) {
1527 entry = fm.marks.entries[i];
1529 fprintf(save_marks_file, "%s%s\n",
1530 fm.marks.dirpath, entry);
1532 fclose(save_marks_file);
1534 free_marks(&fm.marks);