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"
44 struct option opts[] = {
45 {"help", no_argument, NULL, 'h'},
46 {"version", no_argument, NULL, 'v'},
50 static char clipboard[PATH_MAX];
53 #define BUFLEN PATH_MAX
54 static char BUF1[BUFLEN];
55 static char BUF2[BUFLEN];
56 static char INPUT[BUFLEN];
57 static wchar_t WBUF[BUFLEN];
59 /* Paths to external programs. */
60 static char *user_shell;
61 static char *user_pager;
62 static char *user_editor;
63 static char *user_open;
65 /* Listing view parameters. */
66 #define HEIGHT (LINES-4)
67 #define STATUSPOS (COLS-16)
69 /* Listing view flags. */
70 #define SHOW_FILES 0x01u
71 #define SHOW_DIRS 0x02u
72 #define SHOW_HIDDEN 0x04u
74 /* Marks parameters. */
76 #define BULK_THRESH 256
78 /* Information associated to each entry in listing. */
87 /* Dynamic array of marked entries. */
89 char dirpath[PATH_MAX];
95 /* Line editing state. */
97 wchar_t buffer[BUFLEN + 1];
101 /* Each tab only stores the following information. */
116 static struct state {
124 volatile sig_atomic_t pending_usr1;
125 volatile sig_atomic_t pending_winch;
130 /* Macros for accessing global state. */
131 #define ENAME(I) fm.rows[I].name
132 #define ESIZE(I) fm.rows[I].size
133 #define EMODE(I) fm.rows[I].mode
134 #define ISLINK(I) fm.rows[I].islink
135 #define MARKED(I) fm.rows[I].marked
136 #define SCROLL fm.tabs[fm.tab].scroll
137 #define ESEL fm.tabs[fm.tab].esel
138 #define FLAGS fm.tabs[fm.tab].flags
139 #define CWD fm.tabs[fm.tab].cwd
142 #define MIN(A, B) ((A) < (B) ? (A) : (B))
143 #define MAX(A, B) ((A) > (B) ? (A) : (B))
144 #define ISDIR(E) (strchr((E), '/') != NULL)
145 #define CTRL(x) ((x) & 0x1f)
146 #define nitems(a) (sizeof(a)/sizeof(a[0]))
148 /* Line Editing Macros. */
149 #define EDIT_FULL(E) ((E).left == (E).right)
150 #define EDIT_CAN_LEFT(E) ((E).left)
151 #define EDIT_CAN_RIGHT(E) ((E).right < BUFLEN-1)
152 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
153 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
154 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
155 #define EDIT_BACKSPACE(E) (E).left--
156 #define EDIT_DELETE(E) (E).right++
157 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = BUFLEN-1; } while(0)
159 enum editstate { CONTINUE, CONFIRM, CANCEL };
160 enum color { DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE, BLACK };
162 typedef int (*PROCESS)(const char *path);
165 #define __dead __attribute__((noreturn))
168 static inline __dead void
169 quit(const char *reason)
178 err(1, "%s", reason);
186 if ((d = malloc(size)) == NULL)
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 init_marks(struct marks *marks)
214 strcpy(marks->dirpath, "");
215 marks->bulk = BULK_INIT;
217 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
220 /* Unmark all entries. */
222 mark_none(struct marks *marks)
226 strcpy(marks->dirpath, "");
227 for (i = 0; i < marks->bulk && marks->nentries; i++)
228 if (marks->entries[i]) {
229 free(marks->entries[i]);
230 marks->entries[i] = NULL;
233 if (marks->bulk > BULK_THRESH) {
234 /* Reset bulk to free some memory. */
235 free(marks->entries);
236 marks->bulk = BULK_INIT;
237 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
242 add_mark(struct marks *marks, char *dirpath, char *entry)
246 if (!strcmp(marks->dirpath, dirpath)) {
247 /* Append mark to directory. */
248 if (marks->nentries == marks->bulk) {
249 /* Expand bulk to accomodate new entry. */
250 int extra = marks->bulk / 2;
251 marks->bulk += extra; /* bulk *= 1.5; */
252 marks->entries = xrealloc(marks->entries,
253 marks->bulk * sizeof(*marks->entries));
254 memset(&marks->entries[marks->nentries], 0,
255 extra * sizeof(*marks->entries));
258 /* Search for empty slot (there must be one). */
259 for (i = 0; i < marks->bulk; i++)
260 if (!marks->entries[i])
264 /* Directory changed. Discard old marks. */
266 strcpy(marks->dirpath, dirpath);
269 marks->entries[i] = xmalloc(strlen(entry) + 1);
270 strcpy(marks->entries[i], entry);
275 del_mark(struct marks *marks, char *entry)
279 if (marks->nentries > 1) {
280 for (i = 0; i < marks->bulk; i++)
281 if (marks->entries[i] &&
282 !strcmp(marks->entries[i], entry))
284 free(marks->entries[i]);
285 marks->entries[i] = NULL;
292 free_marks(struct marks *marks)
296 for (i = 0; i < marks->bulk && marks->nentries; i++)
297 if (marks->entries[i]) {
298 free(marks->entries[i]);
301 free(marks->entries);
311 handle_winch(int sig)
313 fm.pending_winch = 1;
317 enable_handlers(void)
321 memset(&sa, 0, sizeof(struct sigaction));
322 sa.sa_handler = handle_usr1;
323 sigaction(SIGUSR1, &sa, NULL);
324 sa.sa_handler = handle_winch;
325 sigaction(SIGWINCH, &sa, NULL);
329 disable_handlers(void)
333 memset(&sa, 0, sizeof(struct sigaction));
334 sa.sa_handler = SIG_DFL;
335 sigaction(SIGUSR1, &sa, NULL);
336 sigaction(SIGWINCH, &sa, NULL);
339 static void reload(void);
340 static void update_view(void);
342 /* Handle any signals received since last call. */
346 if (fm.pending_usr1) {
347 /* SIGUSR1 received: refresh directory listing. */
351 if (fm.pending_winch) {
352 /* SIGWINCH received: resize application accordingly. */
357 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
358 if (HEIGHT < fm.nfiles && SCROLL + HEIGHT > fm.nfiles)
359 SCROLL = ESEL - HEIGHT;
361 fm.pending_winch = 0;
366 * This function must be used in place of getch(). It handles signals
367 * while waiting for user input.
374 while ((ch = getch()) == ERR)
380 * This function must be used in place of get_wch(). It handles
381 * signals while waiting for user input.
384 fm_get_wch(wint_t *wch)
388 while ((ret = get_wch(wch)) == (wint_t)ERR)
393 /* Get user programs from the environment. */
395 #define FM_ENV(dst, src) if ((dst = getenv("FM_" #src)) == NULL) \
401 FM_ENV(user_shell, SHELL);
402 FM_ENV(user_pager, PAGER);
403 FM_ENV(user_editor, VISUAL);
405 FM_ENV(user_editor, EDITOR);
406 FM_ENV(user_open, OPEN);
409 /* Do a fork-exec to external program (e.g. $EDITOR). */
411 spawn(const char *argv0, ...)
416 const char *argv[16], *last;
419 memset(argv, 0, sizeof(argv));
423 for (i = 1; i < nitems(argv); ++i) {
424 last = va_arg(ap, const char *);
437 switch (pid = fork()) {
441 setenv("RVSEL", fm.nfiles ? ENAME(ESEL) : "", 1);
442 execvp(argv[0], (char *const *)argv);
445 waitpid(pid, &status, 0);
447 kill(getpid(), SIGWINCH);
452 shell_escaped_cat(char *buf, char *str, size_t n)
454 char *p = buf + strlen(buf);
456 for (n--; n; n--, str++) {
477 open_with_env(char *program, char *path)
481 strncpy(BUF1, program, BUFLEN - 1);
482 strncat(BUF1, " ", BUFLEN - strlen(program) - 1);
483 shell_escaped_cat(BUF1, path, BUFLEN - strlen(program) - 2);
484 spawn(RV_SHELL, "-c", BUF1, NULL );
486 spawn(program, path, NULL);
497 setlocale(LC_ALL, "");
500 timeout(100); /* For getch(). */
502 nonl(); /* No NL->CR/NL on output. */
503 intrflush(stdscr, FALSE);
504 keypad(stdscr, TRUE);
505 curs_set(FALSE); /* Hide blinking cursor. */
509 #ifdef NCURSES_EXT_FUNCS
510 use_default_colors();
515 init_pair(RED, COLOR_RED, bg);
516 init_pair(GREEN, COLOR_GREEN, bg);
517 init_pair(YELLOW, COLOR_YELLOW, bg);
518 init_pair(BLUE, COLOR_BLUE, bg);
519 init_pair(CYAN, COLOR_CYAN, bg);
520 init_pair(MAGENTA, COLOR_MAGENTA, bg);
521 init_pair(WHITE, COLOR_WHITE, bg);
522 init_pair(BLACK, COLOR_BLACK, bg);
524 atexit((void (*)(void))endwin);
528 /* Update the listing view. */
537 mvhline(0, 0, ' ', COLS);
538 attr_on(A_BOLD, NULL);
539 color_set(RVC_TABNUM, NULL);
540 mvaddch(0, COLS - 2, fm.tab + '0');
541 attr_off(A_BOLD, NULL);
542 if (fm.marks.nentries) {
543 numsize = snprintf(BUF1, BUFLEN, "%d", fm.marks.nentries);
544 color_set(RVC_MARKS, NULL);
545 mvaddstr(0, COLS - 3 - numsize, BUF1);
548 color_set(RVC_CWD, NULL);
549 mbstowcs(WBUF, CWD, PATH_MAX);
550 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
551 wcolor_set(fm.window, RVC_BORDER, NULL);
552 wborder(fm.window, 0, 0, 0, 0, 0, 0, 0, 0);
553 ESEL = MAX(MIN(ESEL, fm.nfiles - 1), 0);
556 * Selection might not be visible, due to cursor wrapping or
557 * window shrinking. In that case, the scroll must be moved to
560 if (fm.nfiles > HEIGHT) {
561 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
562 SCROLL = MIN(MAX(SCROLL, 0), fm.nfiles - HEIGHT);
565 marking = !strcmp(CWD, fm.marks.dirpath);
566 for (i = 0, j = SCROLL; i < HEIGHT && j < fm.nfiles; i++, j++) {
567 ishidden = ENAME(j)[0] == '.';
569 wattr_on(fm.window, A_REVERSE, NULL);
571 wcolor_set(fm.window, RVC_LINK, NULL);
573 wcolor_set(fm.window, RVC_HIDDEN, NULL);
574 else if (S_ISREG(EMODE(j))) {
575 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
576 wcolor_set(fm.window, RVC_EXEC, NULL);
578 wcolor_set(fm.window, RVC_REG, NULL);
579 } else if (S_ISDIR(EMODE(j)))
580 wcolor_set(fm.window, RVC_DIR, NULL);
581 else if (S_ISCHR(EMODE(j)))
582 wcolor_set(fm.window, RVC_CHR, NULL);
583 else if (S_ISBLK(EMODE(j)))
584 wcolor_set(fm.window, RVC_BLK, NULL);
585 else if (S_ISFIFO(EMODE(j)))
586 wcolor_set(fm.window, RVC_FIFO, NULL);
587 else if (S_ISSOCK(EMODE(j)))
588 wcolor_set(fm.window, RVC_SOCK, NULL);
589 if (S_ISDIR(EMODE(j))) {
590 mbstowcs(WBUF, ENAME(j), PATH_MAX);
594 const char *suffix, *suffixes = "BKMGTPEZY";
595 off_t human_size = ESIZE(j) * 10;
596 int length = mbstowcs(WBUF, ENAME(j), PATH_MAX);
597 int namecols = wcswidth(WBUF, length);
598 for (suffix = suffixes; human_size >= 10240; suffix++)
599 human_size = (human_size + 512) / 1024;
601 swprintf(WBUF + length, PATH_MAX - length,
603 (int)(COLS - namecols - 6),
604 (int)human_size / 10, *suffix);
606 swprintf(WBUF + length, PATH_MAX - length,
608 (int)(COLS - namecols - 8),
609 (int)human_size / 10,
610 (int)human_size % 10, *suffix);
612 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
613 mvwaddnwstr(fm.window, i + 1, 2, WBUF, COLS - 4);
614 if (marking && MARKED(j)) {
615 wcolor_set(fm.window, RVC_MARKS, NULL);
616 mvwaddch(fm.window, i + 1, 1, RVS_MARK);
618 mvwaddch(fm.window, i + 1, 1, ' ');
620 wattr_off(fm.window, A_REVERSE, NULL);
622 for (; i < HEIGHT; i++)
623 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
624 if (fm.nfiles > HEIGHT) {
626 center = (SCROLL + HEIGHT / 2) * HEIGHT / fm.nfiles;
627 height = (HEIGHT - 1) * HEIGHT / fm.nfiles;
630 wcolor_set(fm.window, RVC_SCROLLBAR, NULL);
631 mvwvline(fm.window, center - height/2 + 1, COLS - 1,
632 RVS_SCROLLBAR, height);
634 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
635 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
636 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
640 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, fm.nfiles);
641 snprintf(BUF1 + 3, BUFLEN - 3, "%12s", BUF2);
642 color_set(RVC_STATUS, NULL);
643 mvaddstr(LINES - 1, STATUSPOS, BUF1);
647 /* Show a message on the status bar. */
648 static void __attribute__((format(printf, 2, 3)))
649 message(enum color c, const char *fmt, ...)
655 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
658 pos = (STATUSPOS - len) / 2;
659 attr_on(A_BOLD, NULL);
661 mvaddstr(LINES - 1, pos, BUF1);
662 color_set(DEFAULT, NULL);
663 attr_off(A_BOLD, NULL);
666 /* Clear message area, leaving only status info. */
670 mvhline(LINES - 1, 0, ' ', STATUSPOS);
673 /* Comparison used to sort listing entries. */
675 rowcmp(const void *a, const void *b)
677 int isdir1, isdir2, cmpdir;
678 const struct row *r1 = a;
679 const struct row *r2 = b;
680 isdir1 = S_ISDIR(r1->mode);
681 isdir2 = S_ISDIR(r2->mode);
682 cmpdir = isdir2 - isdir1;
683 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
686 /* Get all entries in current working directory. */
688 ls(struct row **rowsp, uint8_t flags)
696 if (!(dp = opendir(".")))
698 n = -2; /* We don't want the entries "." and "..". */
706 rows = xmalloc(n * sizeof(*rows));
708 while ((ep = readdir(dp))) {
709 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
711 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
713 lstat(ep->d_name, &statbuf);
714 rows[i].islink = S_ISLNK(statbuf.st_mode);
715 stat(ep->d_name, &statbuf);
716 if (S_ISDIR(statbuf.st_mode)) {
717 if (flags & SHOW_DIRS) {
718 rows[i].name = xmalloc(strlen(ep->d_name) + 2);
719 strcpy(rows[i].name, ep->d_name);
721 strcat(rows[i].name, "/");
722 rows[i].mode = statbuf.st_mode;
725 } else if (flags & SHOW_FILES) {
726 rows[i].name = xmalloc(strlen(ep->d_name) + 1);
727 strcpy(rows[i].name, ep->d_name);
728 rows[i].size = statbuf.st_size;
729 rows[i].mode = statbuf.st_mode;
733 n = i; /* Ignore unused space in array caused by filters. */
734 qsort(rows, n, sizeof(*rows), rowcmp);
741 free_rows(struct row **rowsp, int nfiles)
745 for (i = 0; i < nfiles; i++)
746 free((*rowsp)[i].name);
751 /* Change working directory to the path in CWD. */
757 message(CYAN, "Loading \"%s\"...", CWD);
759 if (chdir(CWD) == -1) {
760 getcwd(CWD, PATH_MAX - 1);
761 if (CWD[strlen(CWD) - 1] != '/')
768 free_rows(&fm.rows, fm.nfiles);
769 fm.nfiles = ls(&fm.rows, FLAGS);
770 if (!strcmp(CWD, fm.marks.dirpath)) {
771 for (i = 0; i < fm.nfiles; i++) {
772 for (j = 0; j < fm.marks.bulk; j++)
773 if (fm.marks.entries[j] &&
774 !strcmp(fm.marks.entries[j], ENAME(i)))
776 MARKED(i) = j < fm.marks.bulk;
779 for (i = 0; i < fm.nfiles; i++)
786 /* Select a target entry, if it is present. */
788 try_to_sel(const char *target)
792 while ((ESEL + 1) < fm.nfiles && S_ISDIR(EMODE(ESEL)))
794 while ((ESEL + 1) < fm.nfiles && strcoll(ENAME(ESEL), target) < 0)
798 /* Reload CWD, but try to keep selection. */
803 strcpy(INPUT, ENAME(ESEL));
812 count_dir(const char *path)
817 char subpath[PATH_MAX];
820 if (!(dp = opendir(path)))
823 while ((ep = readdir(dp))) {
824 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
826 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
827 lstat(subpath, &statbuf);
828 if (S_ISDIR(statbuf.st_mode)) {
829 strcat(subpath, "/");
830 total += count_dir(subpath);
832 total += statbuf.st_size;
847 chdir(fm.marks.dirpath);
848 for (i = 0; i < fm.marks.bulk; i++) {
849 entry = fm.marks.entries[i];
852 total += count_dir(entry);
854 lstat(entry, &statbuf);
855 total += statbuf.st_size;
864 * Recursively process a source directory using CWD as destination
865 * root. For each node (i.e. directory), do the following:
867 * 1. call pre(destination);
868 * 2. call proc() on every child leaf (i.e. files);
869 * 3. recurse into every child node;
870 * 4. call pos(source).
872 * E.g. to move directory /src/ (and all its contents) inside /dst/:
873 * strcpy(CWD, "/dst/");
874 * process_dir(adddir, movfile, deldir, "/src/");
877 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
883 char subpath[PATH_MAX];
887 char dstpath[PATH_MAX];
888 strcpy(dstpath, CWD);
889 strcat(dstpath, path + strlen(fm . marks . dirpath));
892 if (!(dp = opendir(path)))
894 while ((ep = readdir(dp))) {
895 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
897 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
898 lstat(subpath, &statbuf);
899 if (S_ISDIR(statbuf.st_mode)) {
900 strcat(subpath, "/");
901 ret |= process_dir(pre, proc, pos, subpath);
903 ret |= proc(subpath);
912 * Process all marked entries using CWD as destination root. All
913 * marked entries that are directories will be recursively processed.
914 * See process_dir() for details on the parameters.
917 process_marked(PROCESS pre, PROCESS proc, PROCESS pos, const char *msg_doing,
918 const char *msg_done)
925 message(CYAN, "%s...", msg_doing);
927 fm.prog = (struct prog){0, count_marked(), msg_doing};
928 for (i = 0; i < fm.marks.bulk; i++) {
929 entry = fm.marks.entries[i];
932 snprintf(path, PATH_MAX, "%s%s", fm.marks.dirpath,
935 if (!strncmp(path, CWD, strlen(path)))
938 ret = process_dir(pre, proc, pos, path);
942 del_mark(&fm.marks, entry);
949 if (!fm.marks.nentries)
950 message(GREEN, "%s all marked entries.", msg_done);
952 message(RED, "Some errors occured while %s.", msg_doing);
957 update_progress(off_t delta)
963 fm.prog.partial += delta;
964 percent = (int)(fm.prog.partial * 100 / fm.prog.total);
965 message(CYAN, "%s...%d%%", fm.prog.msg, percent);
969 /* Wrappers for file operations. */
971 delfile(const char *path)
976 ret = lstat(path, &st);
979 update_progress(st.st_size);
983 static PROCESS deldir = rmdir;
985 addfile(const char *path)
987 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
990 ret = creat(path, 0644);
997 cpyfile(const char *srcpath)
1003 char dstpath[PATH_MAX];
1005 strcpy(dstpath, CWD);
1006 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
1007 ret = lstat(srcpath, &st);
1010 if (S_ISLNK(st.st_mode)) {
1011 ret = readlink(srcpath, BUF1, BUFLEN - 1);
1015 ret = symlink(BUF1, dstpath);
1017 ret = src = open(srcpath, O_RDONLY);
1020 ret = dst = creat(dstpath, st.st_mode);
1023 while ((size = read(src, buf, BUFSIZ)) > 0) {
1024 write(dst, buf, size);
1025 update_progress(size);
1036 adddir(const char *path)
1041 ret = stat(CWD, &st);
1044 return mkdir(path, st.st_mode);
1048 movfile(const char *srcpath)
1052 char dstpath[PATH_MAX];
1054 strcpy(dstpath, CWD);
1055 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
1056 ret = rename(srcpath, dstpath);
1058 ret = lstat(dstpath, &st);
1061 update_progress(st.st_size);
1062 } else if (errno == EXDEV) {
1063 ret = cpyfile(srcpath);
1066 ret = unlink(srcpath);
1072 start_line_edit(const char *init_input)
1075 strncpy(INPUT, init_input, BUFLEN);
1076 fm.edit.left = mbstowcs(fm.edit.buffer, init_input, BUFLEN);
1077 fm.edit.right = BUFLEN - 1;
1078 fm.edit.buffer[BUFLEN] = L'\0';
1082 /* Read input and change editing state accordingly. */
1083 static enum editstate
1086 wchar_t eraser, killer, wch;
1089 ret = fm_get_wch((wint_t *)&wch);
1090 erasewchar(&eraser);
1092 if (ret == KEY_CODE_YES) {
1093 if (wch == KEY_ENTER) {
1096 } else if (wch == KEY_LEFT) {
1097 if (EDIT_CAN_LEFT(fm.edit))
1099 } else if (wch == KEY_RIGHT) {
1100 if (EDIT_CAN_RIGHT(fm.edit))
1101 EDIT_RIGHT(fm.edit);
1102 } else if (wch == KEY_UP) {
1103 while (EDIT_CAN_LEFT(fm.edit))
1105 } else if (wch == KEY_DOWN) {
1106 while (EDIT_CAN_RIGHT(fm.edit))
1107 EDIT_RIGHT(fm.edit);
1108 } else if (wch == KEY_BACKSPACE) {
1109 if (EDIT_CAN_LEFT(fm.edit))
1110 EDIT_BACKSPACE(fm.edit);
1111 } else if (wch == KEY_DC) {
1112 if (EDIT_CAN_RIGHT(fm.edit))
1113 EDIT_DELETE(fm.edit);
1116 if (wch == L'\r' || wch == L'\n') {
1119 } else if (wch == L'\t') {
1122 } else if (wch == eraser) {
1123 if (EDIT_CAN_LEFT(fm.edit))
1124 EDIT_BACKSPACE(fm.edit);
1125 } else if (wch == killer) {
1126 EDIT_CLEAR(fm.edit);
1128 } else if (iswprint(wch)) {
1129 if (!EDIT_FULL(fm.edit))
1130 EDIT_INSERT(fm.edit, wch);
1133 /* Encode edit contents in INPUT. */
1134 fm.edit.buffer[fm.edit.left] = L'\0';
1135 length = wcstombs(INPUT, fm.edit.buffer, BUFLEN);
1136 wcstombs(&INPUT[length], &fm.edit.buffer[fm.edit.right + 1],
1141 /* Update line input on the screen. */
1143 update_input(const char *prompt, enum color c)
1145 int plen, ilen, maxlen;
1147 plen = strlen(prompt);
1148 ilen = mbstowcs(NULL, INPUT, 0);
1149 maxlen = STATUSPOS - plen - 2;
1150 if (ilen - fm.edit_scroll < maxlen)
1151 fm.edit_scroll = MAX(ilen - maxlen, 0);
1152 else if (fm.edit.left > fm.edit_scroll + maxlen - 1)
1153 fm.edit_scroll = fm.edit.left - maxlen;
1154 else if (fm.edit.left < fm.edit_scroll)
1155 fm.edit_scroll = MAX(fm.edit.left - maxlen, 0);
1156 color_set(RVC_PROMPT, NULL);
1157 mvaddstr(LINES - 1, 0, prompt);
1159 mbstowcs(WBUF, INPUT, COLS);
1160 mvaddnwstr(LINES - 1, plen, &WBUF[fm.edit_scroll], maxlen);
1161 mvaddch(LINES - 1, plen + MIN(ilen - fm.edit_scroll, maxlen + 1),
1163 color_set(DEFAULT, NULL);
1165 mvaddch(LINES - 1, plen - 1, '<');
1166 if (ilen > fm.edit_scroll + maxlen)
1167 mvaddch(LINES - 1, plen + maxlen, '>');
1168 move(LINES - 1, plen + fm.edit.left - fm.edit_scroll);
1175 ESEL = MIN(ESEL + 1, fm.nfiles - 1);
1182 ESEL = MAX(ESEL - 1, 0);
1186 cmd_scroll_down(void)
1190 ESEL = MIN(ESEL + HEIGHT, fm.nfiles - 1);
1191 if (fm.nfiles > HEIGHT)
1192 SCROLL = MIN(SCROLL + HEIGHT, fm.nfiles - HEIGHT);
1200 ESEL = MAX(ESEL - HEIGHT, 0);
1201 SCROLL = MAX(SCROLL - HEIGHT, 0);
1207 spawn("man", "fm", NULL);
1218 cmd_jump_bottom(void)
1221 ESEL = fm.nfiles - 1;
1227 if (!fm.nfiles || !S_ISDIR(EMODE(ESEL)))
1229 if (chdir(ENAME(ESEL)) == -1) {
1230 message(RED, "cd: %s: %s", ENAME(ESEL), strerror(errno));
1233 strlcat(CWD, ENAME(ESEL), sizeof(CWD));
1240 char *dirname, first;
1242 if (!strcmp(CWD, "/"))
1245 /* dirname(3) basically */
1246 dirname = strrchr(CWD, '/');
1248 dirname = strrchr(CWD, '/') + 1;
1254 strlcat(dirname, "/", sizeof(dirname));
1255 try_to_sel(dirname);
1257 if (fm.nfiles > HEIGHT)
1258 SCROLL = ESEL - HEIGHT / 2;
1266 if ((home = getenv("HOME")) == NULL) {
1267 message(RED, "HOME is not defined!");
1271 strlcpy(CWD, home, sizeof(CWD));
1272 if (*CWD != '\0' && CWD[strlen(CWD) - 1] != '/')
1273 strlcat(CWD, "/", sizeof(CWD));
1283 if ((path = getenv("CLIP")) == NULL ||
1284 (f = fopen(path, "w")) == NULL) {
1285 /* use internal clipboard */
1286 strlcpy(clipboard, CWD, sizeof(clipboard));
1287 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1291 fprintf(f, "%s%s", CWD, ENAME(ESEL));
1297 cmd_paste_path(void)
1305 if ((path = getenv("CLIP")) != NULL &&
1306 (f = fopen(path, "w")) != NULL) {
1307 r = fread(clipboard, 1, sizeof(clipboard)-1, f);
1309 if (r == -1 || r == 0)
1311 if ((nl = memmem(clipboard, r, "", 1)) == NULL)
1315 strlcpy(p, clipboard, sizeof(p));
1316 strlcpy(CWD, clipboard, sizeof(CWD));
1317 if ((nl = strrchr(CWD, '/')) != NULL) {
1319 nl = strrchr(p, '/');
1322 if (strcmp(CWD, "/") != 0)
1323 strlcat(CWD, "/", sizeof(CWD));
1329 memset(clipboard, 0, sizeof(clipboard));
1343 if ((shell = getenv("SHELL")) == NULL)
1353 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1356 if ((pager = getenv("PAGER")) == NULL)
1358 spawn(pager, ENAME(ESEL), NULL);
1366 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1369 if ((editor = getenv("VISUAL")) == NULL ||
1370 (editor = getenv("EDITOR")) == NULL)
1373 spawn(editor, ENAME(ESEL), NULL);
1390 {'<', K_META, cmd_jump_top, X_UPDV},
1391 {'>', K_META, cmd_jump_bottom, X_UPDV},
1392 {'?', 0, cmd_man, 0},
1393 {'G', 0, cmd_jump_bottom, X_UPDV},
1394 {'H', 0, cmd_home, X_UPDV},
1395 {'J', 0, cmd_scroll_down, X_UPDV},
1396 {'K', 0, cmd_scroll_up, X_UPDV},
1397 {'P', 0, cmd_paste_path, X_UPDV},
1398 {'V', K_CTRL, cmd_scroll_down, X_UPDV},
1399 {'Y', 0, cmd_copy_path, X_UPDV},
1400 {'^', 0, cmd_cd_up, X_UPDV},
1401 {'b', 0, cmd_cd_up, X_UPDV},
1402 {'e', 0, cmd_edit, X_UPDV},
1403 {'f', 0, cmd_cd_down, X_UPDV},
1404 {'g', 0, cmd_jump_top, X_UPDV},
1405 {'g', K_CTRL, NULL, X_UPDV},
1406 {'h', 0, cmd_cd_up, X_UPDV},
1407 {'j', 0, cmd_down, X_UPDV},
1408 {'k', 0, cmd_up, X_UPDV},
1409 {'l', 0, cmd_cd_down, X_UPDV},
1410 {'l', K_CTRL, cmd_reload, X_UPDV},
1411 {'n', 0, cmd_down, X_UPDV},
1412 {'n', K_CTRL, cmd_down, X_UPDV},
1413 {'m', K_CTRL, cmd_shell, X_UPDV},
1414 {'p', 0, cmd_up, X_UPDV},
1415 {'p', K_CTRL, cmd_up, X_UPDV},
1416 {'q', 0, NULL, X_QUIT},
1417 {'v', 0, cmd_view, X_UPDV},
1418 {'v', K_META, cmd_scroll_up, X_UPDV},
1419 {KEY_DOWN, 0, cmd_scroll_down, X_UPDV},
1420 {KEY_NPAGE, 0, cmd_scroll_down, X_UPDV},
1421 {KEY_PPAGE, 0, cmd_scroll_up, X_UPDV},
1422 {KEY_RESIZE, 0, NULL, X_UPDV},
1423 {KEY_RESIZE, K_META, NULL, X_UPDV},
1424 {KEY_UP, 0, cmd_scroll_up, X_UPDV},
1434 if ((ch = fm_getch()) == '\e') {
1442 for (i = 0; i < nitems(bindings); ++i) {
1445 if (b->chflags & K_CTRL)
1447 if ((!meta && b->chflags & K_META) || ch != c)
1450 if (b->flags & X_QUIT)
1454 if (b->flags & X_UPDV)
1460 message(RED, "%s%s is undefined",
1461 meta ? "M-": "", keyname(ch));
1467 main(int argc, char *argv[])
1473 const char *clip_path;
1475 enum editstate edit_stat;
1476 FILE *save_cwd_file = NULL;
1477 FILE *save_marks_file = NULL;
1480 while ((ch = getopt_long(argc, argv, "d:hm:v", opts, NULL)) != -1) {
1483 if ((save_cwd_file = fopen(optarg, "w")) == NULL)
1484 err(1, "open %s", optarg);
1488 "Usage: fm [-hv] [-d file] [-m file] [dirs...]\n"
1489 "Browse current directory or the ones specified.\n"
1491 "See fm(1) for more information.\n"
1492 "fm homepage <https://github.com/omar-polo/fm>\n");
1495 if ((save_marks_file = fopen(optarg, "a")) == NULL)
1496 err(1, "open %s", optarg);
1499 printf("version: fm %s\n", RV_VERSION);
1504 if (pledge("stdio rpath wpath cpath tty proc exec", NULL) == -1)
1507 get_user_programs();
1510 for (i = 0; i < 10; i++) {
1511 fm.tabs[i].esel = fm.tabs[i].scroll = 0;
1512 fm.tabs[i].flags = RV_FLAGS;
1514 strcpy(fm.tabs[0].cwd, getenv("HOME"));
1515 for (i = 1; i < argc && i < 10; i++) {
1516 if ((d = opendir(argv[i]))) {
1517 realpath(argv[i], fm.tabs[i].cwd);
1520 strcpy(fm.tabs[i].cwd, fm.tabs[0].cwd);
1522 getcwd(fm.tabs[i].cwd, PATH_MAX);
1523 for (i++; i < 10; i++)
1524 strcpy(fm.tabs[i].cwd, fm.tabs[i - 1].cwd);
1525 for (i = 0; i < 10; i++)
1526 if (fm.tabs[i].cwd[strlen(fm.tabs[i].cwd) - 1] != '/')
1527 strcat(fm.tabs[i].cwd, "/");
1529 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
1530 init_marks(&fm.marks);
1532 strlcpy(clipboard, CWD, sizeof(clipboard));
1534 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1539 free_rows(&fm.rows, fm.nfiles);
1541 if (save_cwd_file != NULL) {
1542 fputs(CWD, save_cwd_file);
1543 fclose(save_cwd_file);
1545 if (save_marks_file != NULL) {
1546 for (i = 0; i < fm.marks.bulk; i++) {
1547 entry = fm.marks.entries[i];
1549 fprintf(save_marks_file, "%s%s\n",
1550 fm.marks.dirpath, entry);
1552 fclose(save_marks_file);
1554 free_marks(&fm.marks);