1 /* needed for some ncurses stuff */
2 #define _XOPEN_SOURCE_EXTENDED
3 #define _FILE_OFFSET_BITS 64
31 #define FM_SHELL "/bin/sh"
36 struct option opts[] = {
37 {"help", no_argument, NULL, 'h'},
38 {"version", no_argument, NULL, 'v'},
42 static char clipboard[PATH_MAX];
45 #define BUFLEN PATH_MAX
46 static char BUF1[BUFLEN];
47 static char BUF2[BUFLEN];
48 static char INPUT[BUFLEN];
49 static wchar_t WBUF[BUFLEN];
51 /* Paths to external programs. */
52 static char *user_shell;
53 static char *user_pager;
54 static char *user_editor;
55 static char *user_open;
57 /* Listing view parameters. */
58 #define HEIGHT (LINES-4)
59 #define STATUSPOS (COLS-16)
61 /* Listing view flags. */
62 #define SHOW_FILES 0x01u
63 #define SHOW_DIRS 0x02u
64 #define SHOW_HIDDEN 0x04u
66 /* Marks parameters. */
68 #define BULK_THRESH 256
70 /* Information associated to each entry in listing. */
79 /* Dynamic array of marked entries. */
81 char dirpath[PATH_MAX];
87 /* Line editing state. */
89 wchar_t buffer[BUFLEN + 1];
93 /* Each tab only stores the following information. */
108 static struct state {
116 volatile sig_atomic_t pending_usr1;
117 volatile sig_atomic_t pending_winch;
122 /* Macros for accessing global state. */
123 #define ENAME(I) fm.rows[I].name
124 #define ESIZE(I) fm.rows[I].size
125 #define EMODE(I) fm.rows[I].mode
126 #define ISLINK(I) fm.rows[I].islink
127 #define MARKED(I) fm.rows[I].marked
128 #define SCROLL fm.tabs[fm.tab].scroll
129 #define ESEL fm.tabs[fm.tab].esel
130 #define FLAGS fm.tabs[fm.tab].flags
131 #define CWD fm.tabs[fm.tab].cwd
134 #define MIN(A, B) ((A) < (B) ? (A) : (B))
135 #define MAX(A, B) ((A) > (B) ? (A) : (B))
136 #define ISDIR(E) (strchr((E), '/') != NULL)
137 #define CTRL(x) ((x) & 0x1f)
138 #define nitems(a) (sizeof(a)/sizeof(a[0]))
140 /* Line Editing Macros. */
141 #define EDIT_FULL(E) ((E).left == (E).right)
142 #define EDIT_CAN_LEFT(E) ((E).left)
143 #define EDIT_CAN_RIGHT(E) ((E).right < BUFLEN-1)
144 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
145 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
146 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
147 #define EDIT_BACKSPACE(E) (E).left--
148 #define EDIT_DELETE(E) (E).right++
149 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = BUFLEN-1; } while(0)
151 enum editstate { CONTINUE, CONFIRM, CANCEL };
152 enum color { DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE, BLACK };
154 typedef int (*PROCESS)(const char *path);
157 #define __dead __attribute__((noreturn))
160 static inline __dead void
161 quit(const char *reason)
170 err(1, "%s", reason);
178 if ((d = malloc(size)) == NULL)
184 xcalloc(size_t nmemb, size_t size)
188 if ((d = calloc(nmemb, size)) == NULL)
194 xrealloc(void *p, size_t size)
198 if ((d = realloc(p, size)) == NULL)
204 init_marks(struct marks *marks)
206 strcpy(marks->dirpath, "");
207 marks->bulk = BULK_INIT;
209 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
212 /* Unmark all entries. */
214 mark_none(struct marks *marks)
218 strcpy(marks->dirpath, "");
219 for (i = 0; i < marks->bulk && marks->nentries; i++)
220 if (marks->entries[i]) {
221 free(marks->entries[i]);
222 marks->entries[i] = NULL;
225 if (marks->bulk > BULK_THRESH) {
226 /* Reset bulk to free some memory. */
227 free(marks->entries);
228 marks->bulk = BULK_INIT;
229 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
234 add_mark(struct marks *marks, char *dirpath, char *entry)
238 if (!strcmp(marks->dirpath, dirpath)) {
239 /* Append mark to directory. */
240 if (marks->nentries == marks->bulk) {
241 /* Expand bulk to accomodate new entry. */
242 int extra = marks->bulk / 2;
243 marks->bulk += extra; /* bulk *= 1.5; */
244 marks->entries = xrealloc(marks->entries,
245 marks->bulk * sizeof(*marks->entries));
246 memset(&marks->entries[marks->nentries], 0,
247 extra * sizeof(*marks->entries));
250 /* Search for empty slot (there must be one). */
251 for (i = 0; i < marks->bulk; i++)
252 if (!marks->entries[i])
256 /* Directory changed. Discard old marks. */
258 strcpy(marks->dirpath, dirpath);
261 marks->entries[i] = xmalloc(strlen(entry) + 1);
262 strcpy(marks->entries[i], entry);
267 del_mark(struct marks *marks, char *entry)
271 if (marks->nentries > 1) {
272 for (i = 0; i < marks->bulk; i++)
273 if (marks->entries[i] &&
274 !strcmp(marks->entries[i], entry))
276 free(marks->entries[i]);
277 marks->entries[i] = NULL;
284 free_marks(struct marks *marks)
288 for (i = 0; i < marks->bulk && marks->nentries; i++)
289 if (marks->entries[i]) {
290 free(marks->entries[i]);
293 free(marks->entries);
303 handle_winch(int sig)
305 fm.pending_winch = 1;
309 enable_handlers(void)
313 memset(&sa, 0, sizeof(struct sigaction));
314 sa.sa_handler = handle_usr1;
315 sigaction(SIGUSR1, &sa, NULL);
316 sa.sa_handler = handle_winch;
317 sigaction(SIGWINCH, &sa, NULL);
321 disable_handlers(void)
325 memset(&sa, 0, sizeof(struct sigaction));
326 sa.sa_handler = SIG_DFL;
327 sigaction(SIGUSR1, &sa, NULL);
328 sigaction(SIGWINCH, &sa, NULL);
331 static void reload(void);
332 static void update_view(void);
334 /* Handle any signals received since last call. */
338 if (fm.pending_usr1) {
339 /* SIGUSR1 received: refresh directory listing. */
343 if (fm.pending_winch) {
344 /* SIGWINCH received: resize application accordingly. */
349 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
350 if (HEIGHT < fm.nfiles && SCROLL + HEIGHT > fm.nfiles)
351 SCROLL = ESEL - HEIGHT;
353 fm.pending_winch = 0;
358 * This function must be used in place of getch(). It handles signals
359 * while waiting for user input.
366 while ((ch = getch()) == ERR)
372 * This function must be used in place of get_wch(). It handles
373 * signals while waiting for user input.
376 fm_get_wch(wint_t *wch)
380 while ((ret = get_wch(wch)) == (wint_t)ERR)
385 /* Get user programs from the environment. */
387 #define FM_ENV(dst, src) if ((dst = getenv("FM_" #src)) == NULL) \
393 FM_ENV(user_shell, SHELL);
394 FM_ENV(user_pager, PAGER);
395 FM_ENV(user_editor, VISUAL);
397 FM_ENV(user_editor, EDITOR);
398 FM_ENV(user_open, OPEN);
401 /* Do a fork-exec to external program (e.g. $EDITOR). */
403 spawn(const char *argv0, ...)
408 const char *argv[16], *last;
411 memset(argv, 0, sizeof(argv));
415 for (i = 1; i < nitems(argv); ++i) {
416 last = va_arg(ap, const char *);
429 switch (pid = fork()) {
433 setenv("RVSEL", fm.nfiles ? ENAME(ESEL) : "", 1);
434 execvp(argv[0], (char *const *)argv);
437 waitpid(pid, &status, 0);
439 kill(getpid(), SIGWINCH);
444 shell_escaped_cat(char *buf, char *str, size_t n)
446 char *p = buf + strlen(buf);
448 for (n--; n; n--, str++) {
469 open_with_env(char *program, char *path)
473 strncpy(BUF1, program, BUFLEN - 1);
474 strncat(BUF1, " ", BUFLEN - strlen(program) - 1);
475 shell_escaped_cat(BUF1, path, BUFLEN - strlen(program) - 2);
476 spawn(RV_SHELL, "-c", BUF1, NULL );
478 spawn(program, path, NULL);
489 setlocale(LC_ALL, "");
492 timeout(100); /* For getch(). */
494 nonl(); /* No NL->CR/NL on output. */
495 intrflush(stdscr, FALSE);
496 keypad(stdscr, TRUE);
497 curs_set(FALSE); /* Hide blinking cursor. */
501 #ifdef NCURSES_EXT_FUNCS
502 use_default_colors();
507 init_pair(RED, COLOR_RED, bg);
508 init_pair(GREEN, COLOR_GREEN, bg);
509 init_pair(YELLOW, COLOR_YELLOW, bg);
510 init_pair(BLUE, COLOR_BLUE, bg);
511 init_pair(CYAN, COLOR_CYAN, bg);
512 init_pair(MAGENTA, COLOR_MAGENTA, bg);
513 init_pair(WHITE, COLOR_WHITE, bg);
514 init_pair(BLACK, COLOR_BLACK, bg);
516 atexit((void (*)(void))endwin);
520 /* Update the listing view. */
529 mvhline(0, 0, ' ', COLS);
530 attr_on(A_BOLD, NULL);
531 color_set(RVC_TABNUM, NULL);
532 mvaddch(0, COLS - 2, fm.tab + '0');
533 attr_off(A_BOLD, NULL);
534 if (fm.marks.nentries) {
535 numsize = snprintf(BUF1, BUFLEN, "%d", fm.marks.nentries);
536 color_set(RVC_MARKS, NULL);
537 mvaddstr(0, COLS - 3 - numsize, BUF1);
540 color_set(RVC_CWD, NULL);
541 mbstowcs(WBUF, CWD, PATH_MAX);
542 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
543 wcolor_set(fm.window, RVC_BORDER, NULL);
544 wborder(fm.window, 0, 0, 0, 0, 0, 0, 0, 0);
545 ESEL = MAX(MIN(ESEL, fm.nfiles - 1), 0);
548 * Selection might not be visible, due to cursor wrapping or
549 * window shrinking. In that case, the scroll must be moved to
552 if (fm.nfiles > HEIGHT) {
553 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
554 SCROLL = MIN(MAX(SCROLL, 0), fm.nfiles - HEIGHT);
557 marking = !strcmp(CWD, fm.marks.dirpath);
558 for (i = 0, j = SCROLL; i < HEIGHT && j < fm.nfiles; i++, j++) {
559 ishidden = ENAME(j)[0] == '.';
561 wattr_on(fm.window, A_REVERSE, NULL);
563 wcolor_set(fm.window, RVC_LINK, NULL);
565 wcolor_set(fm.window, RVC_HIDDEN, NULL);
566 else if (S_ISREG(EMODE(j))) {
567 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
568 wcolor_set(fm.window, RVC_EXEC, NULL);
570 wcolor_set(fm.window, RVC_REG, NULL);
571 } else if (S_ISDIR(EMODE(j)))
572 wcolor_set(fm.window, RVC_DIR, NULL);
573 else if (S_ISCHR(EMODE(j)))
574 wcolor_set(fm.window, RVC_CHR, NULL);
575 else if (S_ISBLK(EMODE(j)))
576 wcolor_set(fm.window, RVC_BLK, NULL);
577 else if (S_ISFIFO(EMODE(j)))
578 wcolor_set(fm.window, RVC_FIFO, NULL);
579 else if (S_ISSOCK(EMODE(j)))
580 wcolor_set(fm.window, RVC_SOCK, NULL);
581 if (S_ISDIR(EMODE(j))) {
582 mbstowcs(WBUF, ENAME(j), PATH_MAX);
586 const char *suffix, *suffixes = "BKMGTPEZY";
587 off_t human_size = ESIZE(j) * 10;
588 int length = mbstowcs(WBUF, ENAME(j), PATH_MAX);
589 int namecols = wcswidth(WBUF, length);
590 for (suffix = suffixes; human_size >= 10240; suffix++)
591 human_size = (human_size + 512) / 1024;
593 swprintf(WBUF + length, PATH_MAX - length,
595 (int)(COLS - namecols - 6),
596 (int)human_size / 10, *suffix);
598 swprintf(WBUF + length, PATH_MAX - length,
600 (int)(COLS - namecols - 8),
601 (int)human_size / 10,
602 (int)human_size % 10, *suffix);
604 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
605 mvwaddnwstr(fm.window, i + 1, 2, WBUF, COLS - 4);
606 if (marking && MARKED(j)) {
607 wcolor_set(fm.window, RVC_MARKS, NULL);
608 mvwaddch(fm.window, i + 1, 1, RVS_MARK);
610 mvwaddch(fm.window, i + 1, 1, ' ');
612 wattr_off(fm.window, A_REVERSE, NULL);
614 for (; i < HEIGHT; i++)
615 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
616 if (fm.nfiles > HEIGHT) {
618 center = (SCROLL + HEIGHT / 2) * HEIGHT / fm.nfiles;
619 height = (HEIGHT - 1) * HEIGHT / fm.nfiles;
622 wcolor_set(fm.window, RVC_SCROLLBAR, NULL);
623 mvwvline(fm.window, center - height/2 + 1, COLS - 1,
624 RVS_SCROLLBAR, height);
626 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
627 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
628 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
632 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, fm.nfiles);
633 snprintf(BUF1 + 3, BUFLEN - 3, "%12s", BUF2);
634 color_set(RVC_STATUS, NULL);
635 mvaddstr(LINES - 1, STATUSPOS, BUF1);
639 /* Show a message on the status bar. */
640 static void __attribute__((format(printf, 2, 3)))
641 message(enum color c, const char *fmt, ...)
647 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
650 pos = (STATUSPOS - len) / 2;
651 attr_on(A_BOLD, NULL);
653 mvaddstr(LINES - 1, pos, BUF1);
654 color_set(DEFAULT, NULL);
655 attr_off(A_BOLD, NULL);
658 /* Clear message area, leaving only status info. */
662 mvhline(LINES - 1, 0, ' ', STATUSPOS);
665 /* Comparison used to sort listing entries. */
667 rowcmp(const void *a, const void *b)
669 int isdir1, isdir2, cmpdir;
670 const struct row *r1 = a;
671 const struct row *r2 = b;
672 isdir1 = S_ISDIR(r1->mode);
673 isdir2 = S_ISDIR(r2->mode);
674 cmpdir = isdir2 - isdir1;
675 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
678 /* Get all entries in current working directory. */
680 ls(struct row **rowsp, uint8_t flags)
688 if (!(dp = opendir(".")))
690 n = -2; /* We don't want the entries "." and "..". */
698 rows = xmalloc(n * sizeof(*rows));
700 while ((ep = readdir(dp))) {
701 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
703 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
705 lstat(ep->d_name, &statbuf);
706 rows[i].islink = S_ISLNK(statbuf.st_mode);
707 stat(ep->d_name, &statbuf);
708 if (S_ISDIR(statbuf.st_mode)) {
709 if (flags & SHOW_DIRS) {
710 rows[i].name = xmalloc(strlen(ep->d_name) + 2);
711 strcpy(rows[i].name, ep->d_name);
713 strcat(rows[i].name, "/");
714 rows[i].mode = statbuf.st_mode;
717 } else if (flags & SHOW_FILES) {
718 rows[i].name = xmalloc(strlen(ep->d_name) + 1);
719 strcpy(rows[i].name, ep->d_name);
720 rows[i].size = statbuf.st_size;
721 rows[i].mode = statbuf.st_mode;
725 n = i; /* Ignore unused space in array caused by filters. */
726 qsort(rows, n, sizeof(*rows), rowcmp);
733 free_rows(struct row **rowsp, int nfiles)
737 for (i = 0; i < nfiles; i++)
738 free((*rowsp)[i].name);
743 /* Change working directory to the path in CWD. */
749 message(CYAN, "Loading \"%s\"...", CWD);
751 if (chdir(CWD) == -1) {
752 getcwd(CWD, PATH_MAX - 1);
753 if (CWD[strlen(CWD) - 1] != '/')
760 free_rows(&fm.rows, fm.nfiles);
761 fm.nfiles = ls(&fm.rows, FLAGS);
762 if (!strcmp(CWD, fm.marks.dirpath)) {
763 for (i = 0; i < fm.nfiles; i++) {
764 for (j = 0; j < fm.marks.bulk; j++)
765 if (fm.marks.entries[j] &&
766 !strcmp(fm.marks.entries[j], ENAME(i)))
768 MARKED(i) = j < fm.marks.bulk;
771 for (i = 0; i < fm.nfiles; i++)
778 /* Select a target entry, if it is present. */
780 try_to_sel(const char *target)
784 while ((ESEL + 1) < fm.nfiles && S_ISDIR(EMODE(ESEL)))
786 while ((ESEL + 1) < fm.nfiles && strcoll(ENAME(ESEL), target) < 0)
790 /* Reload CWD, but try to keep selection. */
795 strcpy(INPUT, ENAME(ESEL));
804 count_dir(const char *path)
809 char subpath[PATH_MAX];
812 if (!(dp = opendir(path)))
815 while ((ep = readdir(dp))) {
816 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
818 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
819 lstat(subpath, &statbuf);
820 if (S_ISDIR(statbuf.st_mode)) {
821 strcat(subpath, "/");
822 total += count_dir(subpath);
824 total += statbuf.st_size;
839 chdir(fm.marks.dirpath);
840 for (i = 0; i < fm.marks.bulk; i++) {
841 entry = fm.marks.entries[i];
844 total += count_dir(entry);
846 lstat(entry, &statbuf);
847 total += statbuf.st_size;
856 * Recursively process a source directory using CWD as destination
857 * root. For each node (i.e. directory), do the following:
859 * 1. call pre(destination);
860 * 2. call proc() on every child leaf (i.e. files);
861 * 3. recurse into every child node;
862 * 4. call pos(source).
864 * E.g. to move directory /src/ (and all its contents) inside /dst/:
865 * strcpy(CWD, "/dst/");
866 * process_dir(adddir, movfile, deldir, "/src/");
869 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
875 char subpath[PATH_MAX];
879 char dstpath[PATH_MAX];
880 strcpy(dstpath, CWD);
881 strcat(dstpath, path + strlen(fm . marks . dirpath));
884 if (!(dp = opendir(path)))
886 while ((ep = readdir(dp))) {
887 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
889 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
890 lstat(subpath, &statbuf);
891 if (S_ISDIR(statbuf.st_mode)) {
892 strcat(subpath, "/");
893 ret |= process_dir(pre, proc, pos, subpath);
895 ret |= proc(subpath);
904 * Process all marked entries using CWD as destination root. All
905 * marked entries that are directories will be recursively processed.
906 * See process_dir() for details on the parameters.
909 process_marked(PROCESS pre, PROCESS proc, PROCESS pos, const char *msg_doing,
910 const char *msg_done)
917 message(CYAN, "%s...", msg_doing);
919 fm.prog = (struct prog){0, count_marked(), msg_doing};
920 for (i = 0; i < fm.marks.bulk; i++) {
921 entry = fm.marks.entries[i];
924 snprintf(path, PATH_MAX, "%s%s", fm.marks.dirpath,
927 if (!strncmp(path, CWD, strlen(path)))
930 ret = process_dir(pre, proc, pos, path);
934 del_mark(&fm.marks, entry);
941 if (!fm.marks.nentries)
942 message(GREEN, "%s all marked entries.", msg_done);
944 message(RED, "Some errors occured while %s.", msg_doing);
949 update_progress(off_t delta)
955 fm.prog.partial += delta;
956 percent = (int)(fm.prog.partial * 100 / fm.prog.total);
957 message(CYAN, "%s...%d%%", fm.prog.msg, percent);
961 /* Wrappers for file operations. */
963 delfile(const char *path)
968 ret = lstat(path, &st);
971 update_progress(st.st_size);
975 static PROCESS deldir = rmdir;
977 addfile(const char *path)
979 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
982 ret = creat(path, 0644);
989 cpyfile(const char *srcpath)
995 char dstpath[PATH_MAX];
997 strcpy(dstpath, CWD);
998 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
999 ret = lstat(srcpath, &st);
1002 if (S_ISLNK(st.st_mode)) {
1003 ret = readlink(srcpath, BUF1, BUFLEN - 1);
1007 ret = symlink(BUF1, dstpath);
1009 ret = src = open(srcpath, O_RDONLY);
1012 ret = dst = creat(dstpath, st.st_mode);
1015 while ((size = read(src, buf, BUFSIZ)) > 0) {
1016 write(dst, buf, size);
1017 update_progress(size);
1028 adddir(const char *path)
1033 ret = stat(CWD, &st);
1036 return mkdir(path, st.st_mode);
1040 movfile(const char *srcpath)
1044 char dstpath[PATH_MAX];
1046 strcpy(dstpath, CWD);
1047 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
1048 ret = rename(srcpath, dstpath);
1050 ret = lstat(dstpath, &st);
1053 update_progress(st.st_size);
1054 } else if (errno == EXDEV) {
1055 ret = cpyfile(srcpath);
1058 ret = unlink(srcpath);
1064 start_line_edit(const char *init_input)
1067 strncpy(INPUT, init_input, BUFLEN);
1068 fm.edit.left = mbstowcs(fm.edit.buffer, init_input, BUFLEN);
1069 fm.edit.right = BUFLEN - 1;
1070 fm.edit.buffer[BUFLEN] = L'\0';
1074 /* Read input and change editing state accordingly. */
1075 static enum editstate
1078 wchar_t eraser, killer, wch;
1081 ret = fm_get_wch((wint_t *)&wch);
1082 erasewchar(&eraser);
1084 if (ret == KEY_CODE_YES) {
1085 if (wch == KEY_ENTER) {
1088 } else if (wch == KEY_LEFT) {
1089 if (EDIT_CAN_LEFT(fm.edit))
1091 } else if (wch == KEY_RIGHT) {
1092 if (EDIT_CAN_RIGHT(fm.edit))
1093 EDIT_RIGHT(fm.edit);
1094 } else if (wch == KEY_UP) {
1095 while (EDIT_CAN_LEFT(fm.edit))
1097 } else if (wch == KEY_DOWN) {
1098 while (EDIT_CAN_RIGHT(fm.edit))
1099 EDIT_RIGHT(fm.edit);
1100 } else if (wch == KEY_BACKSPACE) {
1101 if (EDIT_CAN_LEFT(fm.edit))
1102 EDIT_BACKSPACE(fm.edit);
1103 } else if (wch == KEY_DC) {
1104 if (EDIT_CAN_RIGHT(fm.edit))
1105 EDIT_DELETE(fm.edit);
1108 if (wch == L'\r' || wch == L'\n') {
1111 } else if (wch == L'\t') {
1114 } else if (wch == eraser) {
1115 if (EDIT_CAN_LEFT(fm.edit))
1116 EDIT_BACKSPACE(fm.edit);
1117 } else if (wch == killer) {
1118 EDIT_CLEAR(fm.edit);
1120 } else if (iswprint(wch)) {
1121 if (!EDIT_FULL(fm.edit))
1122 EDIT_INSERT(fm.edit, wch);
1125 /* Encode edit contents in INPUT. */
1126 fm.edit.buffer[fm.edit.left] = L'\0';
1127 length = wcstombs(INPUT, fm.edit.buffer, BUFLEN);
1128 wcstombs(&INPUT[length], &fm.edit.buffer[fm.edit.right + 1],
1133 /* Update line input on the screen. */
1135 update_input(const char *prompt, enum color c)
1137 int plen, ilen, maxlen;
1139 plen = strlen(prompt);
1140 ilen = mbstowcs(NULL, INPUT, 0);
1141 maxlen = STATUSPOS - plen - 2;
1142 if (ilen - fm.edit_scroll < maxlen)
1143 fm.edit_scroll = MAX(ilen - maxlen, 0);
1144 else if (fm.edit.left > fm.edit_scroll + maxlen - 1)
1145 fm.edit_scroll = fm.edit.left - maxlen;
1146 else if (fm.edit.left < fm.edit_scroll)
1147 fm.edit_scroll = MAX(fm.edit.left - maxlen, 0);
1148 color_set(RVC_PROMPT, NULL);
1149 mvaddstr(LINES - 1, 0, prompt);
1151 mbstowcs(WBUF, INPUT, COLS);
1152 mvaddnwstr(LINES - 1, plen, &WBUF[fm.edit_scroll], maxlen);
1153 mvaddch(LINES - 1, plen + MIN(ilen - fm.edit_scroll, maxlen + 1),
1155 color_set(DEFAULT, NULL);
1157 mvaddch(LINES - 1, plen - 1, '<');
1158 if (ilen > fm.edit_scroll + maxlen)
1159 mvaddch(LINES - 1, plen + maxlen, '>');
1160 move(LINES - 1, plen + fm.edit.left - fm.edit_scroll);
1167 ESEL = MIN(ESEL + 1, fm.nfiles - 1);
1174 ESEL = MAX(ESEL - 1, 0);
1178 cmd_scroll_down(void)
1182 ESEL = MIN(ESEL + HEIGHT, fm.nfiles - 1);
1183 if (fm.nfiles > HEIGHT)
1184 SCROLL = MIN(SCROLL + HEIGHT, fm.nfiles - HEIGHT);
1192 ESEL = MAX(ESEL - HEIGHT, 0);
1193 SCROLL = MAX(SCROLL - HEIGHT, 0);
1199 spawn("man", "fm", NULL);
1210 cmd_jump_bottom(void)
1213 ESEL = fm.nfiles - 1;
1219 if (!fm.nfiles || !S_ISDIR(EMODE(ESEL)))
1221 if (chdir(ENAME(ESEL)) == -1) {
1222 message(RED, "cd: %s: %s", ENAME(ESEL), strerror(errno));
1225 strlcat(CWD, ENAME(ESEL), sizeof(CWD));
1232 char *dirname, first;
1234 if (!strcmp(CWD, "/"))
1237 /* dirname(3) basically */
1238 dirname = strrchr(CWD, '/');
1240 dirname = strrchr(CWD, '/') + 1;
1246 strlcat(dirname, "/", sizeof(dirname));
1247 try_to_sel(dirname);
1249 if (fm.nfiles > HEIGHT)
1250 SCROLL = ESEL - HEIGHT / 2;
1258 if ((home = getenv("HOME")) == NULL) {
1259 message(RED, "HOME is not defined!");
1263 strlcpy(CWD, home, sizeof(CWD));
1264 if (*CWD != '\0' && CWD[strlen(CWD) - 1] != '/')
1265 strlcat(CWD, "/", sizeof(CWD));
1275 if ((path = getenv("CLIP")) == NULL ||
1276 (f = fopen(path, "w")) == NULL) {
1277 /* use internal clipboard */
1278 strlcpy(clipboard, CWD, sizeof(clipboard));
1279 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1283 fprintf(f, "%s%s", CWD, ENAME(ESEL));
1289 cmd_paste_path(void)
1297 if ((path = getenv("CLIP")) != NULL &&
1298 (f = fopen(path, "w")) != NULL) {
1299 r = fread(clipboard, 1, sizeof(clipboard)-1, f);
1301 if (r == -1 || r == 0)
1303 if ((nl = memmem(clipboard, r, "", 1)) == NULL)
1307 strlcpy(p, clipboard, sizeof(p));
1308 strlcpy(CWD, clipboard, sizeof(CWD));
1309 if ((nl = strrchr(CWD, '/')) != NULL) {
1311 nl = strrchr(p, '/');
1314 if (strcmp(CWD, "/") != 0)
1315 strlcat(CWD, "/", sizeof(CWD));
1321 memset(clipboard, 0, sizeof(clipboard));
1335 if ((shell = getenv("SHELL")) == NULL)
1354 {'<', K_META, cmd_jump_top, X_UPDV},
1355 {'>', K_META, cmd_jump_bottom, X_UPDV},
1356 {'?', 0, cmd_man, 0},
1357 {'G', 0, cmd_jump_bottom, X_UPDV},
1358 {'H', 0, cmd_home, X_UPDV},
1359 {'J', 0, cmd_scroll_down, X_UPDV},
1360 {'K', 0, cmd_scroll_up, X_UPDV},
1361 {'P', 0, cmd_paste_path, X_UPDV},
1362 {'V', K_CTRL, cmd_scroll_down, X_UPDV},
1363 {'Y', 0, cmd_copy_path, X_UPDV},
1364 {'^', 0, cmd_cd_up, X_UPDV},
1365 {'b', 0, cmd_cd_up, X_UPDV},
1366 {'f', 0, cmd_cd_down, X_UPDV},
1367 {'g', 0, cmd_jump_top, X_UPDV},
1368 {'g', K_CTRL, NULL, X_UPDV},
1369 {'h', 0, cmd_cd_up, X_UPDV},
1370 {'j', 0, cmd_down, X_UPDV},
1371 {'k', 0, cmd_up, X_UPDV},
1372 {'l', 0, cmd_cd_down, X_UPDV},
1373 {'l', K_CTRL, cmd_reload, X_UPDV},
1374 {'n', 0, cmd_down, X_UPDV},
1375 {'n', K_CTRL, cmd_down, X_UPDV},
1376 {'m', K_CTRL, cmd_shell, X_UPDV},
1377 {'p', 0, cmd_up, X_UPDV},
1378 {'p', K_CTRL, cmd_up, X_UPDV},
1379 {'q', 0, NULL, X_QUIT},
1380 {'v', K_META, cmd_scroll_up, X_UPDV},
1381 {KEY_DOWN, 0, cmd_scroll_down, X_UPDV},
1382 {KEY_NPAGE, 0, cmd_scroll_down, X_UPDV},
1383 {KEY_PPAGE, 0, cmd_scroll_up, X_UPDV},
1384 {KEY_RESIZE, 0, NULL, X_UPDV},
1385 {KEY_RESIZE, K_META, NULL, X_UPDV},
1386 {KEY_UP, 0, cmd_scroll_up, X_UPDV},
1396 if ((ch = fm_getch()) == '\e') {
1404 for (i = 0; i < nitems(bindings); ++i) {
1407 if (b->chflags & K_CTRL)
1409 if ((!meta && b->chflags & K_META) || ch != c)
1412 if (b->flags & X_QUIT)
1416 if (b->flags & X_UPDV)
1422 message(RED, "%s%s is undefined",
1423 meta ? "M-": "", keyname(ch));
1429 main(int argc, char *argv[])
1435 const char *clip_path;
1437 enum editstate edit_stat;
1438 FILE *save_cwd_file = NULL;
1439 FILE *save_marks_file = NULL;
1442 while ((ch = getopt_long(argc, argv, "d:hm:v", opts, NULL)) != -1) {
1445 if ((save_cwd_file = fopen(optarg, "w")) == NULL)
1446 err(1, "open %s", optarg);
1450 "Usage: fm [-hv] [-d file] [-m file] [dirs...]\n"
1451 "Browse current directory or the ones specified.\n"
1453 "See fm(1) for more information.\n"
1454 "fm homepage <https://github.com/omar-polo/fm>\n");
1457 if ((save_marks_file = fopen(optarg, "a")) == NULL)
1458 err(1, "open %s", optarg);
1461 printf("version: fm %s\n", RV_VERSION);
1466 if (pledge("stdio rpath wpath cpath tty proc exec", NULL) == -1)
1469 get_user_programs();
1472 for (i = 0; i < 10; i++) {
1473 fm.tabs[i].esel = fm.tabs[i].scroll = 0;
1474 fm.tabs[i].flags = RV_FLAGS;
1476 strcpy(fm.tabs[0].cwd, getenv("HOME"));
1477 for (i = 1; i < argc && i < 10; i++) {
1478 if ((d = opendir(argv[i]))) {
1479 realpath(argv[i], fm.tabs[i].cwd);
1482 strcpy(fm.tabs[i].cwd, fm.tabs[0].cwd);
1484 getcwd(fm.tabs[i].cwd, PATH_MAX);
1485 for (i++; i < 10; i++)
1486 strcpy(fm.tabs[i].cwd, fm.tabs[i - 1].cwd);
1487 for (i = 0; i < 10; i++)
1488 if (fm.tabs[i].cwd[strlen(fm.tabs[i].cwd) - 1] != '/')
1489 strcat(fm.tabs[i].cwd, "/");
1491 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
1492 init_marks(&fm.marks);
1494 strlcpy(clipboard, CWD, sizeof(clipboard));
1496 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1501 free_rows(&fm.rows, fm.nfiles);
1503 if (save_cwd_file != NULL) {
1504 fputs(CWD, save_cwd_file);
1505 fclose(save_cwd_file);
1507 if (save_marks_file != NULL) {
1508 for (i = 0; i < fm.marks.bulk; i++) {
1509 entry = fm.marks.entries[i];
1511 fprintf(save_marks_file, "%s%s\n",
1512 fm.marks.dirpath, entry);
1514 fclose(save_marks_file);
1516 free_marks(&fm.marks);