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"
39 #define FM_ED "/bin/ed"
43 #define FM_OPENER "xdg-open"
48 struct option opts[] = {
49 {"help", no_argument, NULL, 'h'},
50 {"version", no_argument, NULL, 'v'},
54 static char clipboard[PATH_MAX];
57 #define BUFLEN PATH_MAX
58 static char BUF1[BUFLEN];
59 static char BUF2[BUFLEN];
60 static char INPUT[BUFLEN];
61 static wchar_t WBUF[BUFLEN];
63 /* Paths to external programs. */
64 static char *user_shell;
65 static char *user_pager;
66 static char *user_editor;
67 static char *user_open;
69 /* Listing view parameters. */
70 #define HEIGHT (LINES-4)
71 #define STATUSPOS (COLS-16)
73 /* Listing view flags. */
74 #define SHOW_FILES 0x01u
75 #define SHOW_DIRS 0x02u
76 #define SHOW_HIDDEN 0x04u
78 /* Marks parameters. */
80 #define BULK_THRESH 256
82 /* Information associated to each entry in listing. */
91 /* Dynamic array of marked entries. */
93 char dirpath[PATH_MAX];
99 /* Line editing state. */
101 wchar_t buffer[BUFLEN + 1];
105 /* Each tab only stores the following information. */
120 static struct state {
128 volatile sig_atomic_t pending_usr1;
129 volatile sig_atomic_t pending_winch;
134 /* Macros for accessing global state. */
135 #define ENAME(I) fm.rows[I].name
136 #define ESIZE(I) fm.rows[I].size
137 #define EMODE(I) fm.rows[I].mode
138 #define ISLINK(I) fm.rows[I].islink
139 #define MARKED(I) fm.rows[I].marked
140 #define SCROLL fm.tabs[fm.tab].scroll
141 #define ESEL fm.tabs[fm.tab].esel
142 #define FLAGS fm.tabs[fm.tab].flags
143 #define CWD fm.tabs[fm.tab].cwd
146 #define MIN(A, B) ((A) < (B) ? (A) : (B))
147 #define MAX(A, B) ((A) > (B) ? (A) : (B))
148 #define ISDIR(E) (strchr((E), '/') != NULL)
149 #define CTRL(x) ((x) & 0x1f)
150 #define nitems(a) (sizeof(a)/sizeof(a[0]))
152 /* Line Editing Macros. */
153 #define EDIT_FULL(E) ((E).left == (E).right)
154 #define EDIT_CAN_LEFT(E) ((E).left)
155 #define EDIT_CAN_RIGHT(E) ((E).right < BUFLEN-1)
156 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
157 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
158 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
159 #define EDIT_BACKSPACE(E) (E).left--
160 #define EDIT_DELETE(E) (E).right++
161 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = BUFLEN-1; } while(0)
163 enum editstate { CONTINUE, CONFIRM, CANCEL };
164 enum color { DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE, BLACK };
166 typedef int (*PROCESS)(const char *path);
169 #define __dead __attribute__((noreturn))
172 static inline __dead void
173 quit(const char *reason)
182 err(1, "%s", reason);
190 if ((d = malloc(size)) == NULL)
196 xcalloc(size_t nmemb, size_t size)
200 if ((d = calloc(nmemb, size)) == NULL)
206 xrealloc(void *p, size_t size)
210 if ((d = realloc(p, size)) == NULL)
216 xasprintf(char **ret, const char *fmt, ...)
222 r = vasprintf(ret, fmt, ap);
235 if ((s = strdup(str)) == NULL)
241 init_marks(struct marks *marks)
243 strlcpy(marks->dirpath, "", sizeof(marks->dirpath));
244 marks->bulk = BULK_INIT;
246 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
249 /* Unmark all entries. */
251 mark_none(struct marks *marks)
255 strlcpy(marks->dirpath, "", sizeof(marks->dirpath));
256 for (i = 0; i < marks->bulk && marks->nentries; i++)
257 if (marks->entries[i]) {
258 free(marks->entries[i]);
259 marks->entries[i] = NULL;
262 if (marks->bulk > BULK_THRESH) {
263 /* Reset bulk to free some memory. */
264 free(marks->entries);
265 marks->bulk = BULK_INIT;
266 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
271 add_mark(struct marks *marks, char *dirpath, char *entry)
275 if (!strcmp(marks->dirpath, dirpath)) {
276 /* Append mark to directory. */
277 if (marks->nentries == marks->bulk) {
278 /* Expand bulk to accomodate new entry. */
279 int extra = marks->bulk / 2;
280 marks->bulk += extra; /* bulk *= 1.5; */
281 marks->entries = xrealloc(marks->entries,
282 marks->bulk * sizeof(*marks->entries));
283 memset(&marks->entries[marks->nentries], 0,
284 extra * sizeof(*marks->entries));
287 /* Search for empty slot (there must be one). */
288 for (i = 0; i < marks->bulk; i++)
289 if (!marks->entries[i])
293 /* Directory changed. Discard old marks. */
295 strlcpy(marks->dirpath, dirpath, sizeof(marks->dirpath));
298 marks->entries[i] = xstrdup(entry);
303 del_mark(struct marks *marks, char *entry)
307 if (marks->nentries > 1) {
308 for (i = 0; i < marks->bulk; i++)
309 if (marks->entries[i] &&
310 !strcmp(marks->entries[i], entry))
312 free(marks->entries[i]);
313 marks->entries[i] = NULL;
320 free_marks(struct marks *marks)
324 for (i = 0; i < marks->bulk && marks->nentries; i++)
325 if (marks->entries[i]) {
326 free(marks->entries[i]);
329 free(marks->entries);
339 handle_winch(int sig)
341 fm.pending_winch = 1;
345 enable_handlers(void)
349 memset(&sa, 0, sizeof(struct sigaction));
350 sa.sa_handler = handle_usr1;
351 sigaction(SIGUSR1, &sa, NULL);
352 sa.sa_handler = handle_winch;
353 sigaction(SIGWINCH, &sa, NULL);
357 disable_handlers(void)
361 memset(&sa, 0, sizeof(struct sigaction));
362 sa.sa_handler = SIG_DFL;
363 sigaction(SIGUSR1, &sa, NULL);
364 sigaction(SIGWINCH, &sa, NULL);
367 static void reload(void);
368 static void update_view(void);
370 /* Handle any signals received since last call. */
374 if (fm.pending_usr1) {
375 /* SIGUSR1 received: refresh directory listing. */
379 if (fm.pending_winch) {
380 /* SIGWINCH received: resize application accordingly. */
385 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
386 if (HEIGHT < fm.nfiles && SCROLL + HEIGHT > fm.nfiles)
387 SCROLL = ESEL - HEIGHT;
389 fm.pending_winch = 0;
394 * This function must be used in place of getch(). It handles signals
395 * while waiting for user input.
402 while ((ch = getch()) == ERR)
408 * This function must be used in place of get_wch(). It handles
409 * signals while waiting for user input.
412 fm_get_wch(wint_t *wch)
416 while ((ret = get_wch(wch)) == (wint_t)ERR)
421 /* Get user programs from the environment. */
423 #define FM_ENV(dst, src) if ((dst = getenv("FM_" #src)) == NULL) \
429 FM_ENV(user_shell, SHELL);
430 FM_ENV(user_pager, PAGER);
431 FM_ENV(user_editor, VISUAL);
433 FM_ENV(user_editor, EDITOR);
434 FM_ENV(user_open, OPEN);
437 /* Do a fork-exec to external program (e.g. $EDITOR). */
439 spawn(const char *argv0, ...)
444 const char *argv[16], *last;
447 memset(argv, 0, sizeof(argv));
451 for (i = 1; i < nitems(argv); ++i) {
452 last = va_arg(ap, const char *);
465 switch (pid = fork()) {
469 setenv("RVSEL", fm.nfiles ? ENAME(ESEL) : "", 1);
470 execvp(argv[0], (char *const *)argv);
473 waitpid(pid, &status, 0);
475 kill(getpid(), SIGWINCH);
480 shell_escaped_cat(char *buf, char *str, size_t n)
482 char *p = buf + strlen(buf);
484 for (n--; n; n--, str++) {
489 strlcpy(p, "'\\''", n);
505 open_with_env(char *program, char *path)
509 strncpy(BUF1, program, BUFLEN - 1);
510 strncat(BUF1, " ", BUFLEN - strlen(program) - 1);
511 shell_escaped_cat(BUF1, path, BUFLEN - strlen(program) - 2);
512 spawn(RV_SHELL, "-c", BUF1, NULL );
514 spawn(program, path, NULL);
525 setlocale(LC_ALL, "");
528 timeout(100); /* For getch(). */
530 nonl(); /* No NL->CR/NL on output. */
531 intrflush(stdscr, FALSE);
532 keypad(stdscr, TRUE);
533 curs_set(FALSE); /* Hide blinking cursor. */
537 #ifdef NCURSES_EXT_FUNCS
538 use_default_colors();
543 init_pair(RED, COLOR_RED, bg);
544 init_pair(GREEN, COLOR_GREEN, bg);
545 init_pair(YELLOW, COLOR_YELLOW, bg);
546 init_pair(BLUE, COLOR_BLUE, bg);
547 init_pair(CYAN, COLOR_CYAN, bg);
548 init_pair(MAGENTA, COLOR_MAGENTA, bg);
549 init_pair(WHITE, COLOR_WHITE, bg);
550 init_pair(BLACK, COLOR_BLACK, bg);
552 atexit((void (*)(void))endwin);
556 /* Update the listing view. */
565 mvhline(0, 0, ' ', COLS);
566 attr_on(A_BOLD, NULL);
567 color_set(RVC_TABNUM, NULL);
568 mvaddch(0, COLS - 2, fm.tab + '0');
569 attr_off(A_BOLD, NULL);
570 if (fm.marks.nentries) {
571 numsize = snprintf(BUF1, BUFLEN, "%d", fm.marks.nentries);
572 color_set(RVC_MARKS, NULL);
573 mvaddstr(0, COLS - 3 - numsize, BUF1);
576 color_set(RVC_CWD, NULL);
577 mbstowcs(WBUF, CWD, PATH_MAX);
578 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
579 wcolor_set(fm.window, RVC_BORDER, NULL);
580 wborder(fm.window, 0, 0, 0, 0, 0, 0, 0, 0);
581 ESEL = MAX(MIN(ESEL, fm.nfiles - 1), 0);
584 * Selection might not be visible, due to cursor wrapping or
585 * window shrinking. In that case, the scroll must be moved to
588 if (fm.nfiles > HEIGHT) {
589 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
590 SCROLL = MIN(MAX(SCROLL, 0), fm.nfiles - HEIGHT);
593 marking = !strcmp(CWD, fm.marks.dirpath);
594 for (i = 0, j = SCROLL; i < HEIGHT && j < fm.nfiles; i++, j++) {
595 ishidden = ENAME(j)[0] == '.';
597 wattr_on(fm.window, A_REVERSE, NULL);
599 wcolor_set(fm.window, RVC_LINK, NULL);
601 wcolor_set(fm.window, RVC_HIDDEN, NULL);
602 else if (S_ISREG(EMODE(j))) {
603 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
604 wcolor_set(fm.window, RVC_EXEC, NULL);
606 wcolor_set(fm.window, RVC_REG, NULL);
607 } else if (S_ISDIR(EMODE(j)))
608 wcolor_set(fm.window, RVC_DIR, NULL);
609 else if (S_ISCHR(EMODE(j)))
610 wcolor_set(fm.window, RVC_CHR, NULL);
611 else if (S_ISBLK(EMODE(j)))
612 wcolor_set(fm.window, RVC_BLK, NULL);
613 else if (S_ISFIFO(EMODE(j)))
614 wcolor_set(fm.window, RVC_FIFO, NULL);
615 else if (S_ISSOCK(EMODE(j)))
616 wcolor_set(fm.window, RVC_SOCK, NULL);
617 if (S_ISDIR(EMODE(j))) {
618 mbstowcs(WBUF, ENAME(j), PATH_MAX);
620 wcslcat(WBUF, L"/", sizeof(WBUF));
622 const char *suffix, *suffixes = "BKMGTPEZY";
623 off_t human_size = ESIZE(j) * 10;
624 int length = mbstowcs(WBUF, ENAME(j), PATH_MAX);
625 int namecols = wcswidth(WBUF, length);
626 for (suffix = suffixes; human_size >= 10240; suffix++)
627 human_size = (human_size + 512) / 1024;
629 swprintf(WBUF + length, PATH_MAX - length,
631 (int)(COLS - namecols - 6),
632 (int)human_size / 10, *suffix);
634 swprintf(WBUF + length, PATH_MAX - length,
636 (int)(COLS - namecols - 8),
637 (int)human_size / 10,
638 (int)human_size % 10, *suffix);
640 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
641 mvwaddnwstr(fm.window, i + 1, 2, WBUF, COLS - 4);
642 if (marking && MARKED(j)) {
643 wcolor_set(fm.window, RVC_MARKS, NULL);
644 mvwaddch(fm.window, i + 1, 1, RVS_MARK);
646 mvwaddch(fm.window, i + 1, 1, ' ');
648 wattr_off(fm.window, A_REVERSE, NULL);
650 for (; i < HEIGHT; i++)
651 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
652 if (fm.nfiles > HEIGHT) {
654 center = (SCROLL + HEIGHT / 2) * HEIGHT / fm.nfiles;
655 height = (HEIGHT - 1) * HEIGHT / fm.nfiles;
658 wcolor_set(fm.window, RVC_SCROLLBAR, NULL);
659 mvwvline(fm.window, center - height/2 + 1, COLS - 1,
660 RVS_SCROLLBAR, height);
662 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
663 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
664 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
666 strlcpy(BUF2, "0/0", sizeof(BUF2));
668 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, fm.nfiles);
669 snprintf(BUF1 + 3, BUFLEN - 3, "%12s", BUF2);
670 color_set(RVC_STATUS, NULL);
671 mvaddstr(LINES - 1, STATUSPOS, BUF1);
675 /* Show a message on the status bar. */
676 static void __attribute__((format(printf, 2, 3)))
677 message(enum color c, const char *fmt, ...)
683 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
686 pos = (STATUSPOS - len) / 2;
687 attr_on(A_BOLD, NULL);
689 mvaddstr(LINES - 1, pos, BUF1);
690 color_set(DEFAULT, NULL);
691 attr_off(A_BOLD, NULL);
694 /* Clear message area, leaving only status info. */
698 mvhline(LINES - 1, 0, ' ', STATUSPOS);
701 /* Comparison used to sort listing entries. */
703 rowcmp(const void *a, const void *b)
705 int isdir1, isdir2, cmpdir;
706 const struct row *r1 = a;
707 const struct row *r2 = b;
708 isdir1 = S_ISDIR(r1->mode);
709 isdir2 = S_ISDIR(r2->mode);
710 cmpdir = isdir2 - isdir1;
711 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
714 /* Get all entries in current working directory. */
716 ls(struct row **rowsp, uint8_t flags)
724 if (!(dp = opendir(".")))
726 n = -2; /* We don't want the entries "." and "..". */
734 rows = xmalloc(n * sizeof(*rows));
736 while ((ep = readdir(dp))) {
737 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
739 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
741 lstat(ep->d_name, &statbuf);
742 rows[i].islink = S_ISLNK(statbuf.st_mode);
743 stat(ep->d_name, &statbuf);
744 if (S_ISDIR(statbuf.st_mode)) {
745 if (flags & SHOW_DIRS) {
746 xasprintf(&rows[i].name, "%s%s",
747 ep->d_name, rows[i].islink ? "" : "/");
748 rows[i].mode = statbuf.st_mode;
751 } else if (flags & SHOW_FILES) {
752 rows[i].name = xstrdup(ep->d_name);
753 rows[i].size = statbuf.st_size;
754 rows[i].mode = statbuf.st_mode;
758 n = i; /* Ignore unused space in array caused by filters. */
759 qsort(rows, n, sizeof(*rows), rowcmp);
766 free_rows(struct row **rowsp, int nfiles)
770 for (i = 0; i < nfiles; i++)
771 free((*rowsp)[i].name);
776 /* Change working directory to the path in CWD. */
782 message(CYAN, "Loading \"%s\"...", CWD);
784 if (chdir(CWD) == -1) {
785 getcwd(CWD, PATH_MAX - 1);
786 if (CWD[strlen(CWD) - 1] != '/')
787 strlcat(CWD, "/", sizeof(CWD));
793 free_rows(&fm.rows, fm.nfiles);
794 fm.nfiles = ls(&fm.rows, FLAGS);
795 if (!strcmp(CWD, fm.marks.dirpath)) {
796 for (i = 0; i < fm.nfiles; i++) {
797 for (j = 0; j < fm.marks.bulk; j++)
798 if (fm.marks.entries[j] &&
799 !strcmp(fm.marks.entries[j], ENAME(i)))
801 MARKED(i) = j < fm.marks.bulk;
804 for (i = 0; i < fm.nfiles; i++)
811 /* Select a target entry, if it is present. */
813 try_to_sel(const char *target)
817 while ((ESEL + 1) < fm.nfiles && S_ISDIR(EMODE(ESEL)))
819 while ((ESEL + 1) < fm.nfiles && strcoll(ENAME(ESEL), target) < 0)
823 /* Reload CWD, but try to keep selection. */
828 strlcpy(INPUT, ENAME(ESEL), sizeof(INPUT));
837 count_dir(const char *path)
842 char subpath[PATH_MAX];
845 if (!(dp = opendir(path)))
848 while ((ep = readdir(dp))) {
849 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
851 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
852 lstat(subpath, &statbuf);
853 if (S_ISDIR(statbuf.st_mode)) {
854 strlcat(subpath, "/", sizeof(subpath));
855 total += count_dir(subpath);
857 total += statbuf.st_size;
872 chdir(fm.marks.dirpath);
873 for (i = 0; i < fm.marks.bulk; i++) {
874 entry = fm.marks.entries[i];
877 total += count_dir(entry);
879 lstat(entry, &statbuf);
880 total += statbuf.st_size;
889 * Recursively process a source directory using CWD as destination
890 * root. For each node (i.e. directory), do the following:
892 * 1. call pre(destination);
893 * 2. call proc() on every child leaf (i.e. files);
894 * 3. recurse into every child node;
895 * 4. call pos(source).
897 * E.g. to move directory /src/ (and all its contents) inside /dst/:
898 * strlcpy(CWD, "/dst/", sizeof(CWD));
899 * process_dir(adddir, movfile, deldir, "/src/");
902 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
908 char subpath[PATH_MAX];
912 char dstpath[PATH_MAX];
913 strlcpy(dstpath, CWD, sizeof(dstpath));
914 strlcat(dstpath, path + strlen(fm.marks.dirpath),
918 if (!(dp = opendir(path)))
920 while ((ep = readdir(dp))) {
921 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
923 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
924 lstat(subpath, &statbuf);
925 if (S_ISDIR(statbuf.st_mode)) {
926 strcat(subpath, "/");
927 ret |= process_dir(pre, proc, pos, subpath);
929 ret |= proc(subpath);
938 * Process all marked entries using CWD as destination root. All
939 * marked entries that are directories will be recursively processed.
940 * See process_dir() for details on the parameters.
943 process_marked(PROCESS pre, PROCESS proc, PROCESS pos, const char *msg_doing,
944 const char *msg_done)
951 message(CYAN, "%s...", msg_doing);
953 fm.prog = (struct prog){0, count_marked(), msg_doing};
954 for (i = 0; i < fm.marks.bulk; i++) {
955 entry = fm.marks.entries[i];
958 snprintf(path, PATH_MAX, "%s%s", fm.marks.dirpath,
961 if (!strncmp(path, CWD, strlen(path)))
964 ret = process_dir(pre, proc, pos, path);
968 del_mark(&fm.marks, entry);
975 if (!fm.marks.nentries)
976 message(GREEN, "%s all marked entries.", msg_done);
978 message(RED, "Some errors occured while %s.", msg_doing);
983 update_progress(off_t delta)
989 fm.prog.partial += delta;
990 percent = (int)(fm.prog.partial * 100 / fm.prog.total);
991 message(CYAN, "%s...%d%%", fm.prog.msg, percent);
995 /* Wrappers for file operations. */
997 delfile(const char *path)
1002 ret = lstat(path, &st);
1005 update_progress(st.st_size);
1006 return unlink(path);
1010 addfile(const char *path)
1012 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
1015 ret = creat(path, 0644);
1022 cpyfile(const char *srcpath)
1028 char dstpath[PATH_MAX];
1030 strlcpy(dstpath, CWD, sizeof(dstpath));
1031 strlcat(dstpath, srcpath + strlen(fm.marks.dirpath), sizeof(dstpath));
1032 ret = lstat(srcpath, &st);
1035 if (S_ISLNK(st.st_mode)) {
1036 ret = readlink(srcpath, BUF1, BUFLEN - 1);
1040 ret = symlink(BUF1, dstpath);
1042 ret = src = open(srcpath, O_RDONLY);
1045 ret = dst = creat(dstpath, st.st_mode);
1048 while ((size = read(src, buf, BUFSIZ)) > 0) {
1049 write(dst, buf, size);
1050 update_progress(size);
1061 adddir(const char *path)
1066 ret = stat(CWD, &st);
1069 return mkdir(path, st.st_mode);
1073 movfile(const char *srcpath)
1077 char dstpath[PATH_MAX];
1079 strlcpy(dstpath, CWD, sizeof(dstpath));
1080 strlcat(dstpath, srcpath + strlen(fm.marks.dirpath), sizeof(dstpath));
1081 ret = rename(srcpath, dstpath);
1083 ret = lstat(dstpath, &st);
1086 update_progress(st.st_size);
1087 } else if (errno == EXDEV) {
1088 ret = cpyfile(srcpath);
1091 ret = unlink(srcpath);
1097 start_line_edit(const char *init_input)
1100 strncpy(INPUT, init_input, BUFLEN);
1101 fm.edit.left = mbstowcs(fm.edit.buffer, init_input, BUFLEN);
1102 fm.edit.right = BUFLEN - 1;
1103 fm.edit.buffer[BUFLEN] = L'\0';
1107 /* Read input and change editing state accordingly. */
1108 static enum editstate
1111 wchar_t eraser, killer, wch;
1114 ret = fm_get_wch((wint_t *)&wch);
1115 erasewchar(&eraser);
1117 if (ret == KEY_CODE_YES) {
1118 if (wch == KEY_ENTER) {
1121 } else if (wch == KEY_LEFT) {
1122 if (EDIT_CAN_LEFT(fm.edit))
1124 } else if (wch == KEY_RIGHT) {
1125 if (EDIT_CAN_RIGHT(fm.edit))
1126 EDIT_RIGHT(fm.edit);
1127 } else if (wch == KEY_UP) {
1128 while (EDIT_CAN_LEFT(fm.edit))
1130 } else if (wch == KEY_DOWN) {
1131 while (EDIT_CAN_RIGHT(fm.edit))
1132 EDIT_RIGHT(fm.edit);
1133 } else if (wch == KEY_BACKSPACE) {
1134 if (EDIT_CAN_LEFT(fm.edit))
1135 EDIT_BACKSPACE(fm.edit);
1136 } else if (wch == KEY_DC) {
1137 if (EDIT_CAN_RIGHT(fm.edit))
1138 EDIT_DELETE(fm.edit);
1141 if (wch == L'\r' || wch == L'\n') {
1144 } else if (wch == L'\t') {
1147 } else if (wch == eraser) {
1148 if (EDIT_CAN_LEFT(fm.edit))
1149 EDIT_BACKSPACE(fm.edit);
1150 } else if (wch == killer) {
1151 EDIT_CLEAR(fm.edit);
1153 } else if (iswprint(wch)) {
1154 if (!EDIT_FULL(fm.edit))
1155 EDIT_INSERT(fm.edit, wch);
1158 /* Encode edit contents in INPUT. */
1159 fm.edit.buffer[fm.edit.left] = L'\0';
1160 length = wcstombs(INPUT, fm.edit.buffer, BUFLEN);
1161 wcstombs(&INPUT[length], &fm.edit.buffer[fm.edit.right + 1],
1166 /* Update line input on the screen. */
1168 update_input(const char *prompt, enum color c)
1170 int plen, ilen, maxlen;
1172 plen = strlen(prompt);
1173 ilen = mbstowcs(NULL, INPUT, 0);
1174 maxlen = STATUSPOS - plen - 2;
1175 if (ilen - fm.edit_scroll < maxlen)
1176 fm.edit_scroll = MAX(ilen - maxlen, 0);
1177 else if (fm.edit.left > fm.edit_scroll + maxlen - 1)
1178 fm.edit_scroll = fm.edit.left - maxlen;
1179 else if (fm.edit.left < fm.edit_scroll)
1180 fm.edit_scroll = MAX(fm.edit.left - maxlen, 0);
1181 color_set(RVC_PROMPT, NULL);
1182 mvaddstr(LINES - 1, 0, prompt);
1184 mbstowcs(WBUF, INPUT, COLS);
1185 mvaddnwstr(LINES - 1, plen, &WBUF[fm.edit_scroll], maxlen);
1186 mvaddch(LINES - 1, plen + MIN(ilen - fm.edit_scroll, maxlen + 1),
1188 color_set(DEFAULT, NULL);
1190 mvaddch(LINES - 1, plen - 1, '<');
1191 if (ilen > fm.edit_scroll + maxlen)
1192 mvaddch(LINES - 1, plen + maxlen, '>');
1193 move(LINES - 1, plen + fm.edit.left - fm.edit_scroll);
1200 ESEL = MIN(ESEL + 1, fm.nfiles - 1);
1207 ESEL = MAX(ESEL - 1, 0);
1211 cmd_scroll_down(void)
1215 ESEL = MIN(ESEL + HEIGHT, fm.nfiles - 1);
1216 if (fm.nfiles > HEIGHT)
1217 SCROLL = MIN(SCROLL + HEIGHT, fm.nfiles - HEIGHT);
1225 ESEL = MAX(ESEL - HEIGHT, 0);
1226 SCROLL = MAX(SCROLL - HEIGHT, 0);
1232 spawn("man", "fm", NULL);
1243 cmd_jump_bottom(void)
1246 ESEL = fm.nfiles - 1;
1252 if (!fm.nfiles || !S_ISDIR(EMODE(ESEL)))
1254 if (chdir(ENAME(ESEL)) == -1) {
1255 message(RED, "cd: %s: %s", ENAME(ESEL), strerror(errno));
1258 strlcat(CWD, ENAME(ESEL), sizeof(CWD));
1265 char *dirname, first;
1267 if (!strcmp(CWD, "/"))
1270 /* dirname(3) basically */
1271 dirname = strrchr(CWD, '/');
1273 dirname = strrchr(CWD, '/') + 1;
1279 strlcat(dirname, "/", sizeof(dirname));
1280 try_to_sel(dirname);
1282 if (fm.nfiles > HEIGHT)
1283 SCROLL = ESEL - HEIGHT / 2;
1291 if ((home = getenv("HOME")) == NULL) {
1292 message(RED, "HOME is not defined!");
1296 strlcpy(CWD, home, sizeof(CWD));
1297 if (*CWD != '\0' && CWD[strlen(CWD) - 1] != '/')
1298 strlcat(CWD, "/", sizeof(CWD));
1308 if ((path = getenv("CLIP")) == NULL ||
1309 (f = fopen(path, "w")) == NULL) {
1310 /* use internal clipboard */
1311 strlcpy(clipboard, CWD, sizeof(clipboard));
1312 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1316 fprintf(f, "%s%s", CWD, ENAME(ESEL));
1322 cmd_paste_path(void)
1330 if ((path = getenv("CLIP")) != NULL &&
1331 (f = fopen(path, "w")) != NULL) {
1332 r = fread(clipboard, 1, sizeof(clipboard)-1, f);
1334 if (r == -1 || r == 0)
1336 if ((nl = memmem(clipboard, r, "", 1)) == NULL)
1340 strlcpy(p, clipboard, sizeof(p));
1341 strlcpy(CWD, clipboard, sizeof(CWD));
1342 if ((nl = strrchr(CWD, '/')) != NULL) {
1344 nl = strrchr(p, '/');
1347 if (strcmp(CWD, "/") != 0)
1348 strlcat(CWD, "/", sizeof(CWD));
1354 memset(clipboard, 0, sizeof(clipboard));
1368 if ((shell = getenv("SHELL")) == NULL)
1378 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1381 if ((pager = getenv("PAGER")) == NULL)
1383 spawn(pager, ENAME(ESEL), NULL);
1391 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1394 if ((editor = getenv("VISUAL")) == NULL ||
1395 (editor = getenv("EDITOR")) == NULL)
1398 spawn(editor, ENAME(ESEL), NULL);
1406 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1409 if ((opener = getenv("OPENER")) == NULL)
1412 spawn(opener, ENAME(ESEL), NULL);
1419 del_mark(&fm.marks, ENAME(ESEL));
1421 add_mark(&fm.marks, CWD, ENAME(ESEL));
1423 MARKED(ESEL) = !MARKED(ESEL);
1424 ESEL = (ESEL + 1) % fm.nfiles;
1428 cmd_toggle_mark(void)
1432 for (i = 0; i < fm.nfiles; ++i) {
1434 del_mark(&fm.marks, ENAME(i));
1436 add_mark(&fm.marks, CWD, ENAME(ESEL));
1437 MARKED(i) = !MARKED(i);
1446 for (i = 0; i < fm.nfiles; ++i)
1448 add_mark(&fm.marks, CWD, ENAME(ESEL));
1467 {'<', K_META, cmd_jump_top, X_UPDV},
1468 {'>', K_META, cmd_jump_bottom, X_UPDV},
1469 {'?', 0, cmd_man, 0},
1470 {'G', 0, cmd_jump_bottom, X_UPDV},
1471 {'H', 0, cmd_home, X_UPDV},
1472 {'J', 0, cmd_scroll_down, X_UPDV},
1473 {'K', 0, cmd_scroll_up, X_UPDV},
1474 {'M', 0, cmd_mark_all, X_UPDV},
1475 {'P', 0, cmd_paste_path, X_UPDV},
1476 {'V', K_CTRL, cmd_scroll_down, X_UPDV},
1477 {'Y', 0, cmd_copy_path, X_UPDV},
1478 {'^', 0, cmd_cd_up, X_UPDV},
1479 {'b', 0, cmd_cd_up, X_UPDV},
1480 {'e', 0, cmd_edit, X_UPDV},
1481 {'f', 0, cmd_cd_down, X_UPDV},
1482 {'g', 0, cmd_jump_top, X_UPDV},
1483 {'g', K_CTRL, NULL, X_UPDV},
1484 {'h', 0, cmd_cd_up, X_UPDV},
1485 {'j', 0, cmd_down, X_UPDV},
1486 {'k', 0, cmd_up, X_UPDV},
1487 {'l', 0, cmd_cd_down, X_UPDV},
1488 {'l', K_CTRL, cmd_reload, X_UPDV},
1489 {'n', 0, cmd_down, X_UPDV},
1490 {'n', K_CTRL, cmd_down, X_UPDV},
1491 {'m', 0, cmd_mark, X_UPDV},
1492 {'m', K_CTRL, cmd_shell, X_UPDV},
1493 {'o', 0, cmd_open, X_UPDV},
1494 {'p', 0, cmd_up, X_UPDV},
1495 {'p', K_CTRL, cmd_up, X_UPDV},
1496 {'q', 0, NULL, X_QUIT},
1497 {'t', 0, cmd_toggle_mark, X_UPDV},
1498 {'v', 0, cmd_view, X_UPDV},
1499 {'v', K_META, cmd_scroll_up, X_UPDV},
1500 {KEY_DOWN, 0, cmd_scroll_down, X_UPDV},
1501 {KEY_NPAGE, 0, cmd_scroll_down, X_UPDV},
1502 {KEY_PPAGE, 0, cmd_scroll_up, X_UPDV},
1503 {KEY_RESIZE, 0, NULL, X_UPDV},
1504 {KEY_RESIZE, K_META, NULL, X_UPDV},
1505 {KEY_UP, 0, cmd_scroll_up, X_UPDV},
1515 if ((ch = fm_getch()) == '\e') {
1523 for (i = 0; i < nitems(bindings); ++i) {
1526 if (b->chflags & K_CTRL)
1528 if ((!meta && b->chflags & K_META) || ch != c)
1531 if (b->flags & X_QUIT)
1535 if (b->flags & X_UPDV)
1541 message(RED, "%s%s is undefined",
1542 meta ? "M-": "", keyname(ch));
1550 fprintf(stderr, "usage: %s [-hv] [-d file] [-m file] [dirs ...]\n",
1552 fprintf(stderr, "version: %s\n", RV_VERSION);
1557 main(int argc, char *argv[])
1562 FILE *save_cwd_file = NULL;
1563 FILE *save_marks_file = NULL;
1565 if (pledge("stdio rpath wpath cpath tty proc exec", NULL) == -1)
1568 while ((ch = getopt_long(argc, argv, "d:hm:v", opts, NULL)) != -1) {
1571 if ((save_cwd_file = fopen(optarg, "w")) == NULL)
1572 err(1, "open %s", optarg);
1578 if ((save_marks_file = fopen(optarg, "a")) == NULL)
1579 err(1, "open %s", optarg);
1582 printf("version: fm %s\n", RV_VERSION);
1589 get_user_programs();
1592 for (i = 0; i < 10; i++) {
1593 fm.tabs[i].esel = fm.tabs[i].scroll = 0;
1594 fm.tabs[i].flags = RV_FLAGS;
1596 strlcpy(fm.tabs[0].cwd, getenv("HOME"), sizeof(fm.tabs[0].cwd));
1597 for (i = 1; i < argc && i < 10; i++) {
1598 if ((d = opendir(argv[i]))) {
1599 realpath(argv[i], fm.tabs[i].cwd);
1602 strlcpy(fm.tabs[i].cwd, fm.tabs[0].cwd,
1603 sizeof(fm.tabs[i].cwd));
1606 getcwd(fm.tabs[i].cwd, PATH_MAX);
1607 for (i++; i < 10; i++)
1608 strlcpy(fm.tabs[i].cwd, fm.tabs[i - 1].cwd,
1609 sizeof(fm.tabs[i].cwd));
1610 for (i = 0; i < 10; i++)
1611 if (fm.tabs[i].cwd[strlen(fm.tabs[i].cwd) - 1] != '/')
1612 strlcat(fm.tabs[i].cwd, "/", sizeof(fm.tabs[i].cwd));
1614 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
1615 init_marks(&fm.marks);
1617 strlcpy(clipboard, CWD, sizeof(clipboard));
1619 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1624 free_rows(&fm.rows, fm.nfiles);
1626 if (save_cwd_file != NULL) {
1627 fputs(CWD, save_cwd_file);
1628 fclose(save_cwd_file);
1630 if (save_marks_file != NULL) {
1631 for (i = 0; i < fm.marks.bulk; i++) {
1632 entry = fm.marks.entries[i];
1634 fprintf(save_marks_file, "%s%s\n",
1635 fm.marks.dirpath, entry);
1637 fclose(save_marks_file);
1639 free_marks(&fm.marks);