2 * fm.c was written by Omar Polo <op@omarpolo.com>, based on the work
3 * of Marcel Rodrigues, and is placed in the public domain. The author
4 * hereby disclaims copyright to this source code.
7 /* needed for some ncurses stuff */
8 #define _XOPEN_SOURCE_EXTENDED
9 #define _FILE_OFFSET_BITS 64
12 #include <sys/types.h>
37 #define FM_SHELL "/bin/sh"
41 #define FM_PAGER "/usr/bin/less"
45 #define FM_ED "/bin/ed"
49 #define FM_OPENER "xdg-open"
54 struct option opts[] = {
55 {"help", no_argument, NULL, 'h'},
56 {"version", no_argument, NULL, 'v'},
60 static char clipboard[PATH_MAX];
63 #define BUFLEN PATH_MAX
64 static char BUF1[BUFLEN];
65 static char BUF2[BUFLEN];
66 static char INPUT[BUFLEN];
67 static wchar_t WBUF[BUFLEN];
69 /* Paths to external programs. */
70 static char *user_shell;
71 static char *user_pager;
72 static char *user_editor;
73 static char *user_open;
75 /* Listing view parameters. */
76 #define HEIGHT (LINES-4)
77 #define STATUSPOS (COLS-16)
79 /* Listing view flags. */
80 #define SHOW_FILES 0x01u
81 #define SHOW_DIRS 0x02u
82 #define SHOW_HIDDEN 0x04u
84 /* Marks parameters. */
86 #define BULK_THRESH 256
88 /* Information associated to each entry in listing. */
97 /* Dynamic array of marked entries. */
99 char dirpath[PATH_MAX];
105 /* Line editing state. */
107 wchar_t buffer[BUFLEN + 1];
111 /* Each tab only stores the following information. */
126 static struct state {
134 volatile sig_atomic_t pending_usr1;
135 volatile sig_atomic_t pending_winch;
140 /* Macros for accessing global state. */
141 #define ENAME(I) fm.rows[I].name
142 #define ESIZE(I) fm.rows[I].size
143 #define EMODE(I) fm.rows[I].mode
144 #define ISLINK(I) fm.rows[I].islink
145 #define MARKED(I) fm.rows[I].marked
146 #define SCROLL fm.tabs[fm.tab].scroll
147 #define ESEL fm.tabs[fm.tab].esel
148 #define FLAGS fm.tabs[fm.tab].flags
149 #define CWD fm.tabs[fm.tab].cwd
152 #define MIN(A, B) ((A) < (B) ? (A) : (B))
153 #define MAX(A, B) ((A) > (B) ? (A) : (B))
154 #define ISDIR(E) (strchr((E), '/') != NULL)
155 #define CTRL(x) ((x) & 0x1f)
156 #define nitems(a) (sizeof(a)/sizeof(a[0]))
158 /* Line Editing Macros. */
159 #define EDIT_FULL(E) ((E).left == (E).right)
160 #define EDIT_CAN_LEFT(E) ((E).left)
161 #define EDIT_CAN_RIGHT(E) ((E).right < BUFLEN-1)
162 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
163 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
164 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
165 #define EDIT_BACKSPACE(E) (E).left--
166 #define EDIT_DELETE(E) (E).right++
167 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = BUFLEN-1; } while(0)
169 enum editstate { CONTINUE, CONFIRM, CANCEL };
170 enum color { DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE, BLACK };
172 typedef int (*PROCESS)(const char *path);
175 #define __dead __attribute__((noreturn))
178 static inline __dead void
179 quit(const char *reason)
188 err(1, "%s", reason);
192 xcalloc(size_t nmemb, size_t size)
196 if ((d = calloc(nmemb, size)) == NULL)
202 xrealloc(void *p, size_t size)
206 if ((d = realloc(p, size)) == NULL)
212 xasprintf(char **ret, const char *fmt, ...)
218 r = vasprintf(ret, fmt, ap);
231 if ((s = strdup(str)) == NULL)
237 init_marks(struct marks *marks)
239 strlcpy(marks->dirpath, "", sizeof(marks->dirpath));
240 marks->bulk = BULK_INIT;
242 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
245 /* Unmark all entries. */
247 mark_none(struct marks *marks)
251 strlcpy(marks->dirpath, "", sizeof(marks->dirpath));
252 for (i = 0; i < marks->bulk && marks->nentries; i++)
253 if (marks->entries[i]) {
254 free(marks->entries[i]);
255 marks->entries[i] = NULL;
258 if (marks->bulk > BULK_THRESH) {
259 /* Reset bulk to free some memory. */
260 free(marks->entries);
261 marks->bulk = BULK_INIT;
262 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
267 add_mark(struct marks *marks, char *dirpath, char *entry)
271 if (!strcmp(marks->dirpath, dirpath)) {
272 /* Append mark to directory. */
273 if (marks->nentries == marks->bulk) {
274 /* Expand bulk to accomodate new entry. */
275 int extra = marks->bulk / 2;
276 marks->bulk += extra; /* bulk *= 1.5; */
277 marks->entries = xrealloc(marks->entries,
278 marks->bulk * sizeof(*marks->entries));
279 memset(&marks->entries[marks->nentries], 0,
280 extra * sizeof(*marks->entries));
283 /* Search for empty slot (there must be one). */
284 for (i = 0; i < marks->bulk; i++)
285 if (!marks->entries[i])
289 /* Directory changed. Discard old marks. */
291 strlcpy(marks->dirpath, dirpath, sizeof(marks->dirpath));
294 marks->entries[i] = xstrdup(entry);
299 del_mark(struct marks *marks, char *entry)
303 if (marks->nentries > 1) {
304 for (i = 0; i < marks->bulk; i++)
305 if (marks->entries[i] &&
306 !strcmp(marks->entries[i], entry))
308 free(marks->entries[i]);
309 marks->entries[i] = NULL;
316 free_marks(struct marks *marks)
320 for (i = 0; i < marks->bulk && marks->nentries; i++)
321 if (marks->entries[i]) {
322 free(marks->entries[i]);
325 free(marks->entries);
335 handle_winch(int sig)
337 fm.pending_winch = 1;
341 enable_handlers(void)
345 memset(&sa, 0, sizeof(struct sigaction));
346 sa.sa_handler = handle_usr1;
347 sigaction(SIGUSR1, &sa, NULL);
348 sa.sa_handler = handle_winch;
349 sigaction(SIGWINCH, &sa, NULL);
353 disable_handlers(void)
357 memset(&sa, 0, sizeof(struct sigaction));
358 sa.sa_handler = SIG_DFL;
359 sigaction(SIGUSR1, &sa, NULL);
360 sigaction(SIGWINCH, &sa, NULL);
363 static void reload(void);
364 static void update_view(void);
366 /* Handle any signals received since last call. */
370 if (fm.pending_usr1) {
371 /* SIGUSR1 received: refresh directory listing. */
375 if (fm.pending_winch) {
376 /* SIGWINCH received: resize application accordingly. */
381 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
382 if (HEIGHT < fm.nfiles && SCROLL + HEIGHT > fm.nfiles)
383 SCROLL = ESEL - HEIGHT;
385 fm.pending_winch = 0;
390 * This function must be used in place of getch(). It handles signals
391 * while waiting for user input.
398 while ((ch = getch()) == ERR)
404 * This function must be used in place of get_wch(). It handles
405 * signals while waiting for user input.
408 fm_get_wch(wint_t *wch)
412 while ((ret = get_wch(wch)) == (wint_t)ERR)
417 /* Get user programs from the environment. */
419 #define FM_ENV(dst, src) if ((dst = getenv("FM_" #src)) == NULL) \
425 FM_ENV(user_shell, SHELL);
426 FM_ENV(user_pager, PAGER);
427 FM_ENV(user_editor, VISUAL);
429 FM_ENV(user_editor, EDITOR);
430 FM_ENV(user_open, OPEN);
433 /* Do a fork-exec to external program (e.g. $EDITOR). */
435 spawn(const char *argv0, ...)
440 const char *argv[16], *last;
443 memset(argv, 0, sizeof(argv));
447 for (i = 1; i < nitems(argv); ++i) {
448 last = va_arg(ap, const char *);
461 switch (pid = fork()) {
465 setenv("RVSEL", fm.nfiles ? ENAME(ESEL) : "", 1);
466 execvp(argv[0], (char *const *)argv);
469 waitpid(pid, &status, 0);
471 kill(getpid(), SIGWINCH);
476 shell_escaped_cat(char *buf, char *str, size_t n)
478 char *p = buf + strlen(buf);
480 for (n--; n; n--, str++) {
485 strlcpy(p, "'\\''", n);
501 open_with_env(char *program, char *path)
505 strncpy(BUF1, program, BUFLEN - 1);
506 strncat(BUF1, " ", BUFLEN - strlen(program) - 1);
507 shell_escaped_cat(BUF1, path, BUFLEN - strlen(program) - 2);
508 spawn(RV_SHELL, "-c", BUF1, NULL );
510 spawn(program, path, NULL);
521 setlocale(LC_ALL, "");
524 timeout(100); /* For getch(). */
526 nonl(); /* No NL->CR/NL on output. */
527 intrflush(stdscr, FALSE);
528 keypad(stdscr, TRUE);
529 curs_set(FALSE); /* Hide blinking cursor. */
533 #ifdef NCURSES_EXT_FUNCS
534 use_default_colors();
539 init_pair(RED, COLOR_RED, bg);
540 init_pair(GREEN, COLOR_GREEN, bg);
541 init_pair(YELLOW, COLOR_YELLOW, bg);
542 init_pair(BLUE, COLOR_BLUE, bg);
543 init_pair(CYAN, COLOR_CYAN, bg);
544 init_pair(MAGENTA, COLOR_MAGENTA, bg);
545 init_pair(WHITE, COLOR_WHITE, bg);
546 init_pair(BLACK, COLOR_BLACK, bg);
548 atexit((void (*)(void))endwin);
552 /* Update the listing view. */
561 mvhline(0, 0, ' ', COLS);
562 attr_on(A_BOLD, NULL);
563 color_set(RVC_TABNUM, NULL);
564 mvaddch(0, COLS - 2, fm.tab + '0');
565 attr_off(A_BOLD, NULL);
566 if (fm.marks.nentries) {
567 numsize = snprintf(BUF1, BUFLEN, "%d", fm.marks.nentries);
568 color_set(RVC_MARKS, NULL);
569 mvaddstr(0, COLS - 3 - numsize, BUF1);
572 color_set(RVC_CWD, NULL);
573 mbstowcs(WBUF, CWD, PATH_MAX);
574 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
575 wcolor_set(fm.window, RVC_BORDER, NULL);
576 wborder(fm.window, 0, 0, 0, 0, 0, 0, 0, 0);
577 ESEL = MAX(MIN(ESEL, fm.nfiles - 1), 0);
580 * Selection might not be visible, due to cursor wrapping or
581 * window shrinking. In that case, the scroll must be moved to
584 if (fm.nfiles > HEIGHT) {
585 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
586 SCROLL = MIN(MAX(SCROLL, 0), fm.nfiles - HEIGHT);
589 marking = !strcmp(CWD, fm.marks.dirpath);
590 for (i = 0, j = SCROLL; i < HEIGHT && j < fm.nfiles; i++, j++) {
591 ishidden = ENAME(j)[0] == '.';
593 wattr_on(fm.window, A_REVERSE, NULL);
595 wcolor_set(fm.window, RVC_LINK, NULL);
597 wcolor_set(fm.window, RVC_HIDDEN, NULL);
598 else if (S_ISREG(EMODE(j))) {
599 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
600 wcolor_set(fm.window, RVC_EXEC, NULL);
602 wcolor_set(fm.window, RVC_REG, NULL);
603 } else if (S_ISDIR(EMODE(j)))
604 wcolor_set(fm.window, RVC_DIR, NULL);
605 else if (S_ISCHR(EMODE(j)))
606 wcolor_set(fm.window, RVC_CHR, NULL);
607 else if (S_ISBLK(EMODE(j)))
608 wcolor_set(fm.window, RVC_BLK, NULL);
609 else if (S_ISFIFO(EMODE(j)))
610 wcolor_set(fm.window, RVC_FIFO, NULL);
611 else if (S_ISSOCK(EMODE(j)))
612 wcolor_set(fm.window, RVC_SOCK, NULL);
613 if (S_ISDIR(EMODE(j))) {
614 mbstowcs(WBUF, ENAME(j), PATH_MAX);
616 wcslcat(WBUF, L"/", sizeof(WBUF));
618 const char *suffix, *suffixes = "BKMGTPEZY";
619 off_t human_size = ESIZE(j) * 10;
620 int length = mbstowcs(WBUF, ENAME(j), PATH_MAX);
621 int namecols = wcswidth(WBUF, length);
622 for (suffix = suffixes; human_size >= 10240; suffix++)
623 human_size = (human_size + 512) / 1024;
625 swprintf(WBUF + length, PATH_MAX - length,
627 (int)(COLS - namecols - 6),
628 (int)human_size / 10, *suffix);
630 swprintf(WBUF + length, PATH_MAX - length,
632 (int)(COLS - namecols - 8),
633 (int)human_size / 10,
634 (int)human_size % 10, *suffix);
636 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
637 mvwaddnwstr(fm.window, i + 1, 2, WBUF, COLS - 4);
638 if (marking && MARKED(j)) {
639 wcolor_set(fm.window, RVC_MARKS, NULL);
640 mvwaddch(fm.window, i + 1, 1, RVS_MARK);
642 mvwaddch(fm.window, i + 1, 1, ' ');
644 wattr_off(fm.window, A_REVERSE, NULL);
646 for (; i < HEIGHT; i++)
647 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
648 if (fm.nfiles > HEIGHT) {
650 center = (SCROLL + HEIGHT / 2) * HEIGHT / fm.nfiles;
651 height = (HEIGHT - 1) * HEIGHT / fm.nfiles;
654 wcolor_set(fm.window, RVC_SCROLLBAR, NULL);
655 mvwvline(fm.window, center - height/2 + 1, COLS - 1,
656 RVS_SCROLLBAR, height);
658 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
659 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
660 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
662 strlcpy(BUF2, "0/0", sizeof(BUF2));
664 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, fm.nfiles);
665 snprintf(BUF1 + 3, BUFLEN - 3, "%12s", BUF2);
666 color_set(RVC_STATUS, NULL);
667 mvaddstr(LINES - 1, STATUSPOS, BUF1);
671 /* Show a message on the status bar. */
672 static void __attribute__((format(printf, 2, 3)))
673 message(enum color c, const char *fmt, ...)
679 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
682 pos = (STATUSPOS - len) / 2;
683 attr_on(A_BOLD, NULL);
685 mvaddstr(LINES - 1, pos, BUF1);
686 color_set(DEFAULT, NULL);
687 attr_off(A_BOLD, NULL);
690 /* Clear message area, leaving only status info. */
694 mvhline(LINES - 1, 0, ' ', STATUSPOS);
697 /* Comparison used to sort listing entries. */
699 rowcmp(const void *a, const void *b)
701 int isdir1, isdir2, cmpdir;
702 const struct row *r1 = a;
703 const struct row *r2 = b;
704 isdir1 = S_ISDIR(r1->mode);
705 isdir2 = S_ISDIR(r2->mode);
706 cmpdir = isdir2 - isdir1;
707 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
710 /* Get all entries in current working directory. */
712 ls(struct row **rowsp, uint8_t flags)
720 if (!(dp = opendir(".")))
722 n = -2; /* We don't want the entries "." and "..". */
730 rows = xcalloc(n, sizeof(*rows));
732 while ((ep = readdir(dp))) {
733 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
735 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
737 lstat(ep->d_name, &statbuf);
738 rows[i].islink = S_ISLNK(statbuf.st_mode);
739 stat(ep->d_name, &statbuf);
740 if (S_ISDIR(statbuf.st_mode)) {
741 if (flags & SHOW_DIRS) {
742 xasprintf(&rows[i].name, "%s%s",
743 ep->d_name, rows[i].islink ? "" : "/");
744 rows[i].mode = statbuf.st_mode;
747 } else if (flags & SHOW_FILES) {
748 rows[i].name = xstrdup(ep->d_name);
749 rows[i].size = statbuf.st_size;
750 rows[i].mode = statbuf.st_mode;
754 n = i; /* Ignore unused space in array caused by filters. */
755 qsort(rows, n, sizeof(*rows), rowcmp);
762 free_rows(struct row **rowsp, int nfiles)
766 for (i = 0; i < nfiles; i++)
767 free((*rowsp)[i].name);
772 /* Change working directory to the path in CWD. */
778 message(CYAN, "Loading \"%s\"...", CWD);
780 if (chdir(CWD) == -1) {
781 getcwd(CWD, PATH_MAX - 1);
782 if (CWD[strlen(CWD) - 1] != '/')
783 strlcat(CWD, "/", sizeof(CWD));
789 free_rows(&fm.rows, fm.nfiles);
790 fm.nfiles = ls(&fm.rows, FLAGS);
791 if (!strcmp(CWD, fm.marks.dirpath)) {
792 for (i = 0; i < fm.nfiles; i++) {
793 for (j = 0; j < fm.marks.bulk; j++)
794 if (fm.marks.entries[j] &&
795 !strcmp(fm.marks.entries[j], ENAME(i)))
797 MARKED(i) = j < fm.marks.bulk;
800 for (i = 0; i < fm.nfiles; i++)
807 /* Select a target entry, if it is present. */
809 try_to_sel(const char *target)
813 while ((ESEL + 1) < fm.nfiles && S_ISDIR(EMODE(ESEL)))
815 while ((ESEL + 1) < fm.nfiles && strcoll(ENAME(ESEL), target) < 0)
819 /* Reload CWD, but try to keep selection. */
824 strlcpy(INPUT, ENAME(ESEL), sizeof(INPUT));
833 count_dir(const char *path)
838 char subpath[PATH_MAX];
841 if (!(dp = opendir(path)))
844 while ((ep = readdir(dp))) {
845 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
847 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
848 lstat(subpath, &statbuf);
849 if (S_ISDIR(statbuf.st_mode)) {
850 strlcat(subpath, "/", sizeof(subpath));
851 total += count_dir(subpath);
853 total += statbuf.st_size;
868 chdir(fm.marks.dirpath);
869 for (i = 0; i < fm.marks.bulk; i++) {
870 entry = fm.marks.entries[i];
873 total += count_dir(entry);
875 lstat(entry, &statbuf);
876 total += statbuf.st_size;
885 * Recursively process a source directory using CWD as destination
886 * root. For each node (i.e. directory), do the following:
888 * 1. call pre(destination);
889 * 2. call proc() on every child leaf (i.e. files);
890 * 3. recurse into every child node;
891 * 4. call pos(source).
893 * E.g. to move directory /src/ (and all its contents) inside /dst/:
894 * strlcpy(CWD, "/dst/", sizeof(CWD));
895 * process_dir(adddir, movfile, deldir, "/src/");
898 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
904 char subpath[PATH_MAX];
908 char dstpath[PATH_MAX];
909 strlcpy(dstpath, CWD, sizeof(dstpath));
910 strlcat(dstpath, path + strlen(fm.marks.dirpath),
914 if (!(dp = opendir(path)))
916 while ((ep = readdir(dp))) {
917 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
919 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
920 lstat(subpath, &statbuf);
921 if (S_ISDIR(statbuf.st_mode)) {
922 strcat(subpath, "/");
923 ret |= process_dir(pre, proc, pos, subpath);
925 ret |= proc(subpath);
934 * Process all marked entries using CWD as destination root. All
935 * marked entries that are directories will be recursively processed.
936 * See process_dir() for details on the parameters.
939 process_marked(PROCESS pre, PROCESS proc, PROCESS pos, const char *msg_doing,
940 const char *msg_done)
947 message(CYAN, "%s...", msg_doing);
949 fm.prog = (struct prog){0, count_marked(), msg_doing};
950 for (i = 0; i < fm.marks.bulk; i++) {
951 entry = fm.marks.entries[i];
954 snprintf(path, PATH_MAX, "%s%s", fm.marks.dirpath,
957 if (!strncmp(path, CWD, strlen(path)))
960 ret = process_dir(pre, proc, pos, path);
964 del_mark(&fm.marks, entry);
971 if (!fm.marks.nentries)
972 message(GREEN, "%s all marked entries.", msg_done);
974 message(RED, "Some errors occured while %s.", msg_doing);
979 update_progress(off_t delta)
985 fm.prog.partial += delta;
986 percent = (int)(fm.prog.partial * 100 / fm.prog.total);
987 message(CYAN, "%s...%d%%", fm.prog.msg, percent);
991 /* Wrappers for file operations. */
993 delfile(const char *path)
998 ret = lstat(path, &st);
1001 update_progress(st.st_size);
1002 return unlink(path);
1006 addfile(const char *path)
1008 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
1011 ret = creat(path, 0644);
1018 cpyfile(const char *srcpath)
1024 char dstpath[PATH_MAX];
1026 strlcpy(dstpath, CWD, sizeof(dstpath));
1027 strlcat(dstpath, srcpath + strlen(fm.marks.dirpath), sizeof(dstpath));
1028 ret = lstat(srcpath, &st);
1031 if (S_ISLNK(st.st_mode)) {
1032 ret = readlink(srcpath, BUF1, BUFLEN - 1);
1036 ret = symlink(BUF1, dstpath);
1038 ret = src = open(srcpath, O_RDONLY);
1041 ret = dst = creat(dstpath, st.st_mode);
1044 while ((size = read(src, buf, BUFSIZ)) > 0) {
1045 write(dst, buf, size);
1046 update_progress(size);
1057 adddir(const char *path)
1062 ret = stat(CWD, &st);
1065 return mkdir(path, st.st_mode);
1069 movfile(const char *srcpath)
1073 char dstpath[PATH_MAX];
1075 strlcpy(dstpath, CWD, sizeof(dstpath));
1076 strlcat(dstpath, srcpath + strlen(fm.marks.dirpath), sizeof(dstpath));
1077 ret = rename(srcpath, dstpath);
1079 ret = lstat(dstpath, &st);
1082 update_progress(st.st_size);
1083 } else if (errno == EXDEV) {
1084 ret = cpyfile(srcpath);
1087 ret = unlink(srcpath);
1093 start_line_edit(const char *init_input)
1096 strncpy(INPUT, init_input, BUFLEN);
1097 fm.edit.left = mbstowcs(fm.edit.buffer, init_input, BUFLEN);
1098 fm.edit.right = BUFLEN - 1;
1099 fm.edit.buffer[BUFLEN] = L'\0';
1103 /* Read input and change editing state accordingly. */
1104 static enum editstate
1107 wchar_t eraser, killer, wch;
1110 ret = fm_get_wch((wint_t *)&wch);
1111 erasewchar(&eraser);
1113 if (ret == KEY_CODE_YES) {
1114 if (wch == KEY_ENTER) {
1117 } else if (wch == KEY_LEFT) {
1118 if (EDIT_CAN_LEFT(fm.edit))
1120 } else if (wch == KEY_RIGHT) {
1121 if (EDIT_CAN_RIGHT(fm.edit))
1122 EDIT_RIGHT(fm.edit);
1123 } else if (wch == KEY_UP) {
1124 while (EDIT_CAN_LEFT(fm.edit))
1126 } else if (wch == KEY_DOWN) {
1127 while (EDIT_CAN_RIGHT(fm.edit))
1128 EDIT_RIGHT(fm.edit);
1129 } else if (wch == KEY_BACKSPACE) {
1130 if (EDIT_CAN_LEFT(fm.edit))
1131 EDIT_BACKSPACE(fm.edit);
1132 } else if (wch == KEY_DC) {
1133 if (EDIT_CAN_RIGHT(fm.edit))
1134 EDIT_DELETE(fm.edit);
1137 if (wch == L'\r' || wch == L'\n') {
1140 } else if (wch == L'\t') {
1143 } else if (wch == eraser) {
1144 if (EDIT_CAN_LEFT(fm.edit))
1145 EDIT_BACKSPACE(fm.edit);
1146 } else if (wch == killer) {
1147 EDIT_CLEAR(fm.edit);
1149 } else if (iswprint(wch)) {
1150 if (!EDIT_FULL(fm.edit))
1151 EDIT_INSERT(fm.edit, wch);
1154 /* Encode edit contents in INPUT. */
1155 fm.edit.buffer[fm.edit.left] = L'\0';
1156 length = wcstombs(INPUT, fm.edit.buffer, BUFLEN);
1157 wcstombs(&INPUT[length], &fm.edit.buffer[fm.edit.right + 1],
1162 /* Update line input on the screen. */
1164 update_input(const char *prompt, enum color c)
1166 int plen, ilen, maxlen;
1168 plen = strlen(prompt);
1169 ilen = mbstowcs(NULL, INPUT, 0);
1170 maxlen = STATUSPOS - plen - 2;
1171 if (ilen - fm.edit_scroll < maxlen)
1172 fm.edit_scroll = MAX(ilen - maxlen, 0);
1173 else if (fm.edit.left > fm.edit_scroll + maxlen - 1)
1174 fm.edit_scroll = fm.edit.left - maxlen;
1175 else if (fm.edit.left < fm.edit_scroll)
1176 fm.edit_scroll = MAX(fm.edit.left - maxlen, 0);
1177 color_set(RVC_PROMPT, NULL);
1178 mvaddstr(LINES - 1, 0, prompt);
1180 mbstowcs(WBUF, INPUT, COLS);
1181 mvaddnwstr(LINES - 1, plen, &WBUF[fm.edit_scroll], maxlen);
1182 mvaddch(LINES - 1, plen + MIN(ilen - fm.edit_scroll, maxlen + 1),
1184 color_set(DEFAULT, NULL);
1186 mvaddch(LINES - 1, plen - 1, '<');
1187 if (ilen > fm.edit_scroll + maxlen)
1188 mvaddch(LINES - 1, plen + maxlen, '>');
1189 move(LINES - 1, plen + fm.edit.left - fm.edit_scroll);
1196 ESEL = MIN(ESEL + 1, fm.nfiles - 1);
1203 ESEL = MAX(ESEL - 1, 0);
1207 cmd_scroll_down(void)
1211 ESEL = MIN(ESEL + HEIGHT, fm.nfiles - 1);
1212 if (fm.nfiles > HEIGHT)
1213 SCROLL = MIN(SCROLL + HEIGHT, fm.nfiles - HEIGHT);
1221 ESEL = MAX(ESEL - HEIGHT, 0);
1222 SCROLL = MAX(SCROLL - HEIGHT, 0);
1228 spawn("man", "fm", NULL);
1239 cmd_jump_bottom(void)
1242 ESEL = fm.nfiles - 1;
1248 if (!fm.nfiles || !S_ISDIR(EMODE(ESEL)))
1250 if (chdir(ENAME(ESEL)) == -1) {
1251 message(RED, "cd: %s: %s", ENAME(ESEL), strerror(errno));
1254 strlcat(CWD, ENAME(ESEL), sizeof(CWD));
1261 char *dirname, first;
1263 if (!strcmp(CWD, "/"))
1266 /* dirname(3) basically */
1267 dirname = strrchr(CWD, '/');
1269 dirname = strrchr(CWD, '/') + 1;
1275 strlcat(dirname, "/", sizeof(dirname));
1276 try_to_sel(dirname);
1278 if (fm.nfiles > HEIGHT)
1279 SCROLL = ESEL - HEIGHT / 2;
1287 if ((home = getenv("HOME")) == NULL) {
1288 message(RED, "HOME is not defined!");
1292 strlcpy(CWD, home, sizeof(CWD));
1293 if (*CWD != '\0' && CWD[strlen(CWD) - 1] != '/')
1294 strlcat(CWD, "/", sizeof(CWD));
1304 if ((path = getenv("CLIP")) == NULL ||
1305 (f = fopen(path, "w")) == NULL) {
1306 /* use internal clipboard */
1307 strlcpy(clipboard, CWD, sizeof(clipboard));
1308 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1312 fprintf(f, "%s%s", CWD, ENAME(ESEL));
1318 cmd_paste_path(void)
1326 if ((path = getenv("CLIP")) != NULL &&
1327 (f = fopen(path, "w")) != NULL) {
1328 r = fread(clipboard, 1, sizeof(clipboard)-1, f);
1330 if (r == -1 || r == 0)
1332 if ((nl = memmem(clipboard, r, "", 1)) == NULL)
1336 strlcpy(p, clipboard, sizeof(p));
1337 strlcpy(CWD, clipboard, sizeof(CWD));
1338 if ((nl = strrchr(CWD, '/')) != NULL) {
1340 nl = strrchr(p, '/');
1343 if (strcmp(CWD, "/") != 0)
1344 strlcat(CWD, "/", sizeof(CWD));
1350 memset(clipboard, 0, sizeof(clipboard));
1364 if ((shell = getenv("SHELL")) == NULL)
1374 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1377 if ((pager = getenv("PAGER")) == NULL)
1379 spawn(pager, ENAME(ESEL), NULL);
1387 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1390 if ((editor = getenv("VISUAL")) == NULL ||
1391 (editor = getenv("EDITOR")) == NULL)
1394 spawn(editor, ENAME(ESEL), NULL);
1402 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1405 if ((opener = getenv("OPENER")) == NULL)
1408 spawn(opener, ENAME(ESEL), NULL);
1415 del_mark(&fm.marks, ENAME(ESEL));
1417 add_mark(&fm.marks, CWD, ENAME(ESEL));
1419 MARKED(ESEL) = !MARKED(ESEL);
1420 ESEL = (ESEL + 1) % fm.nfiles;
1424 cmd_toggle_mark(void)
1428 for (i = 0; i < fm.nfiles; ++i) {
1430 del_mark(&fm.marks, ENAME(i));
1432 add_mark(&fm.marks, CWD, ENAME(ESEL));
1433 MARKED(i) = !MARKED(i);
1442 for (i = 0; i < fm.nfiles; ++i)
1444 add_mark(&fm.marks, CWD, ENAME(ESEL));
1463 {'<', K_META, cmd_jump_top, X_UPDV},
1464 {'>', K_META, cmd_jump_bottom, X_UPDV},
1465 {'?', 0, cmd_man, 0},
1466 {'G', 0, cmd_jump_bottom, X_UPDV},
1467 {'H', 0, cmd_home, X_UPDV},
1468 {'J', 0, cmd_scroll_down, X_UPDV},
1469 {'K', 0, cmd_scroll_up, X_UPDV},
1470 {'M', 0, cmd_mark_all, X_UPDV},
1471 {'P', 0, cmd_paste_path, X_UPDV},
1472 {'V', K_CTRL, cmd_scroll_down, X_UPDV},
1473 {'Y', 0, cmd_copy_path, X_UPDV},
1474 {'^', 0, cmd_cd_up, X_UPDV},
1475 {'b', 0, cmd_cd_up, X_UPDV},
1476 {'e', 0, cmd_edit, X_UPDV},
1477 {'f', 0, cmd_cd_down, X_UPDV},
1478 {'g', 0, cmd_jump_top, X_UPDV},
1479 {'g', K_CTRL, NULL, X_UPDV},
1480 {'h', 0, cmd_cd_up, X_UPDV},
1481 {'j', 0, cmd_down, X_UPDV},
1482 {'k', 0, cmd_up, X_UPDV},
1483 {'l', 0, cmd_cd_down, X_UPDV},
1484 {'l', K_CTRL, cmd_reload, X_UPDV},
1485 {'n', 0, cmd_down, X_UPDV},
1486 {'n', K_CTRL, cmd_down, X_UPDV},
1487 {'m', 0, cmd_mark, X_UPDV},
1488 {'m', K_CTRL, cmd_shell, X_UPDV},
1489 {'o', 0, cmd_open, X_UPDV},
1490 {'p', 0, cmd_up, X_UPDV},
1491 {'p', K_CTRL, cmd_up, X_UPDV},
1492 {'q', 0, NULL, X_QUIT},
1493 {'t', 0, cmd_toggle_mark, X_UPDV},
1494 {'v', 0, cmd_view, X_UPDV},
1495 {'v', K_META, cmd_scroll_up, X_UPDV},
1496 {KEY_DOWN, 0, cmd_scroll_down, X_UPDV},
1497 {KEY_NPAGE, 0, cmd_scroll_down, X_UPDV},
1498 {KEY_PPAGE, 0, cmd_scroll_up, X_UPDV},
1499 {KEY_RESIZE, 0, NULL, X_UPDV},
1500 {KEY_RESIZE, K_META, NULL, X_UPDV},
1501 {KEY_UP, 0, cmd_scroll_up, X_UPDV},
1511 if ((ch = fm_getch()) == '\e') {
1519 for (i = 0; i < nitems(bindings); ++i) {
1522 if (b->chflags & K_CTRL)
1524 if ((!meta && b->chflags & K_META) || ch != c)
1527 if (b->flags & X_QUIT)
1531 if (b->flags & X_UPDV)
1537 message(RED, "%s%s is undefined",
1538 meta ? "M-": "", keyname(ch));
1546 fprintf(stderr, "usage: %s [-hv] [-d file] [-m file] [dirs ...]\n",
1548 fprintf(stderr, "version: %s\n", RV_VERSION);
1553 main(int argc, char *argv[])
1558 FILE *save_cwd_file = NULL;
1559 FILE *save_marks_file = NULL;
1561 if (pledge("stdio rpath wpath cpath tty proc exec", NULL) == -1)
1564 while ((ch = getopt_long(argc, argv, "d:hm:v", opts, NULL)) != -1) {
1567 if ((save_cwd_file = fopen(optarg, "w")) == NULL)
1568 err(1, "open %s", optarg);
1574 if ((save_marks_file = fopen(optarg, "a")) == NULL)
1575 err(1, "open %s", optarg);
1578 printf("version: fm %s\n", RV_VERSION);
1585 get_user_programs();
1588 for (i = 0; i < 10; i++) {
1589 fm.tabs[i].esel = fm.tabs[i].scroll = 0;
1590 fm.tabs[i].flags = RV_FLAGS;
1592 strlcpy(fm.tabs[0].cwd, getenv("HOME"), sizeof(fm.tabs[0].cwd));
1593 for (i = 1; i < argc && i < 10; i++) {
1594 if ((d = opendir(argv[i]))) {
1595 realpath(argv[i], fm.tabs[i].cwd);
1598 strlcpy(fm.tabs[i].cwd, fm.tabs[0].cwd,
1599 sizeof(fm.tabs[i].cwd));
1602 getcwd(fm.tabs[i].cwd, PATH_MAX);
1603 for (i++; i < 10; i++)
1604 strlcpy(fm.tabs[i].cwd, fm.tabs[i - 1].cwd,
1605 sizeof(fm.tabs[i].cwd));
1606 for (i = 0; i < 10; i++)
1607 if (fm.tabs[i].cwd[strlen(fm.tabs[i].cwd) - 1] != '/')
1608 strlcat(fm.tabs[i].cwd, "/", sizeof(fm.tabs[i].cwd));
1610 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
1611 init_marks(&fm.marks);
1613 strlcpy(clipboard, CWD, sizeof(clipboard));
1615 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1620 free_rows(&fm.rows, fm.nfiles);
1622 if (save_cwd_file != NULL) {
1623 fputs(CWD, save_cwd_file);
1624 fclose(save_cwd_file);
1626 if (save_marks_file != NULL) {
1627 for (i = 0; i < fm.marks.bulk; i++) {
1628 entry = fm.marks.entries[i];
1630 fprintf(save_marks_file, "%s%s\n",
1631 fm.marks.dirpath, entry);
1633 fclose(save_marks_file);
1635 free_marks(&fm.marks);