1 /* needed for some ncurses stuff */
2 #define _XOPEN_SOURCE_EXTENDED
3 #define _FILE_OFFSET_BITS 64
32 struct option opts[] = {
33 {"help", no_argument, NULL, 'h'},
34 {"version", no_argument, NULL, 'v'},
38 static char clipboard[PATH_MAX];
41 #define BUFLEN PATH_MAX
42 static char BUF1[BUFLEN];
43 static char BUF2[BUFLEN];
44 static char INPUT[BUFLEN];
45 static wchar_t WBUF[BUFLEN];
47 /* Paths to external programs. */
48 static char *user_shell;
49 static char *user_pager;
50 static char *user_editor;
51 static char *user_open;
53 /* Listing view parameters. */
54 #define HEIGHT (LINES-4)
55 #define STATUSPOS (COLS-16)
57 /* Listing view flags. */
58 #define SHOW_FILES 0x01u
59 #define SHOW_DIRS 0x02u
60 #define SHOW_HIDDEN 0x04u
62 /* Marks parameters. */
64 #define BULK_THRESH 256
66 /* Information associated to each entry in listing. */
75 /* Dynamic array of marked entries. */
77 char dirpath[PATH_MAX];
83 /* Line editing state. */
85 wchar_t buffer[BUFLEN + 1];
89 /* Each tab only stores the following information. */
104 static struct state {
112 volatile sig_atomic_t pending_usr1;
113 volatile sig_atomic_t pending_winch;
118 /* Macros for accessing global state. */
119 #define ENAME(I) fm.rows[I].name
120 #define ESIZE(I) fm.rows[I].size
121 #define EMODE(I) fm.rows[I].mode
122 #define ISLINK(I) fm.rows[I].islink
123 #define MARKED(I) fm.rows[I].marked
124 #define SCROLL fm.tabs[fm.tab].scroll
125 #define ESEL fm.tabs[fm.tab].esel
126 #define FLAGS fm.tabs[fm.tab].flags
127 #define CWD fm.tabs[fm.tab].cwd
130 #define MIN(A, B) ((A) < (B) ? (A) : (B))
131 #define MAX(A, B) ((A) > (B) ? (A) : (B))
132 #define ISDIR(E) (strchr((E), '/') != NULL)
133 #define CTRL(x) ((x) & 0x1f)
134 #define nitems(a) (sizeof(a)/sizeof(a[0]))
136 /* Line Editing Macros. */
137 #define EDIT_FULL(E) ((E).left == (E).right)
138 #define EDIT_CAN_LEFT(E) ((E).left)
139 #define EDIT_CAN_RIGHT(E) ((E).right < BUFLEN-1)
140 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
141 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
142 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
143 #define EDIT_BACKSPACE(E) (E).left--
144 #define EDIT_DELETE(E) (E).right++
145 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = BUFLEN-1; } while(0)
147 enum editstate { CONTINUE, CONFIRM, CANCEL };
148 enum color { DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE, BLACK };
150 typedef int (*PROCESS)(const char *path);
153 #define __dead __attribute__((noreturn))
156 static inline __dead void
157 quit(const char *reason)
166 err(1, "%s", reason);
174 if ((d = malloc(size)) == NULL)
180 xcalloc(size_t nmemb, size_t size)
184 if ((d = calloc(nmemb, size)) == NULL)
190 xrealloc(void *p, size_t size)
194 if ((d = realloc(p, size)) == NULL)
200 init_marks(struct marks *marks)
202 strcpy(marks->dirpath, "");
203 marks->bulk = BULK_INIT;
205 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
208 /* Unmark all entries. */
210 mark_none(struct marks *marks)
214 strcpy(marks->dirpath, "");
215 for (i = 0; i < marks->bulk && marks->nentries; i++)
216 if (marks->entries[i]) {
217 free(marks->entries[i]);
218 marks->entries[i] = NULL;
221 if (marks->bulk > BULK_THRESH) {
222 /* Reset bulk to free some memory. */
223 free(marks->entries);
224 marks->bulk = BULK_INIT;
225 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
230 add_mark(struct marks *marks, char *dirpath, char *entry)
234 if (!strcmp(marks->dirpath, dirpath)) {
235 /* Append mark to directory. */
236 if (marks->nentries == marks->bulk) {
237 /* Expand bulk to accomodate new entry. */
238 int extra = marks->bulk / 2;
239 marks->bulk += extra; /* bulk *= 1.5; */
240 marks->entries = xrealloc(marks->entries,
241 marks->bulk * sizeof(*marks->entries));
242 memset(&marks->entries[marks->nentries], 0,
243 extra * sizeof(*marks->entries));
246 /* Search for empty slot (there must be one). */
247 for (i = 0; i < marks->bulk; i++)
248 if (!marks->entries[i])
252 /* Directory changed. Discard old marks. */
254 strcpy(marks->dirpath, dirpath);
257 marks->entries[i] = xmalloc(strlen(entry) + 1);
258 strcpy(marks->entries[i], entry);
263 del_mark(struct marks *marks, char *entry)
267 if (marks->nentries > 1) {
268 for (i = 0; i < marks->bulk; i++)
269 if (marks->entries[i] &&
270 !strcmp(marks->entries[i], entry))
272 free(marks->entries[i]);
273 marks->entries[i] = NULL;
280 free_marks(struct marks *marks)
284 for (i = 0; i < marks->bulk && marks->nentries; i++)
285 if (marks->entries[i]) {
286 free(marks->entries[i]);
289 free(marks->entries);
299 handle_winch(int sig)
301 fm.pending_winch = 1;
305 enable_handlers(void)
309 memset(&sa, 0, sizeof(struct sigaction));
310 sa.sa_handler = handle_usr1;
311 sigaction(SIGUSR1, &sa, NULL);
312 sa.sa_handler = handle_winch;
313 sigaction(SIGWINCH, &sa, NULL);
317 disable_handlers(void)
321 memset(&sa, 0, sizeof(struct sigaction));
322 sa.sa_handler = SIG_DFL;
323 sigaction(SIGUSR1, &sa, NULL);
324 sigaction(SIGWINCH, &sa, NULL);
327 static void reload(void);
328 static void update_view(void);
330 /* Handle any signals received since last call. */
334 if (fm.pending_usr1) {
335 /* SIGUSR1 received: refresh directory listing. */
339 if (fm.pending_winch) {
340 /* SIGWINCH received: resize application accordingly. */
345 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
346 if (HEIGHT < fm.nfiles && SCROLL + HEIGHT > fm.nfiles)
347 SCROLL = ESEL - HEIGHT;
349 fm.pending_winch = 0;
354 * This function must be used in place of getch(). It handles signals
355 * while waiting for user input.
362 while ((ch = getch()) == ERR)
368 * This function must be used in place of get_wch(). It handles
369 * signals while waiting for user input.
372 fm_get_wch(wint_t *wch)
376 while ((ret = get_wch(wch)) == (wint_t)ERR)
381 /* Get user programs from the environment. */
383 #define FM_ENV(dst, src) if ((dst = getenv("FM_" #src)) == NULL) \
389 FM_ENV(user_shell, SHELL);
390 FM_ENV(user_pager, PAGER);
391 FM_ENV(user_editor, VISUAL);
393 FM_ENV(user_editor, EDITOR);
394 FM_ENV(user_open, OPEN);
397 /* Do a fork-exec to external program (e.g. $EDITOR). */
399 spawn(const char *argv0, ...)
404 const char *argv[16], *last;
407 memset(argv, 0, sizeof(argv));
411 for (i = 1; i < nitems(argv); ++i) {
412 last = va_arg(ap, const char *);
425 switch (pid = fork()) {
429 setenv("RVSEL", fm.nfiles ? ENAME(ESEL) : "", 1);
430 execvp(argv[0], (char *const *)argv);
433 waitpid(pid, &status, 0);
435 kill(getpid(), SIGWINCH);
440 shell_escaped_cat(char *buf, char *str, size_t n)
442 char *p = buf + strlen(buf);
444 for (n--; n; n--, str++) {
465 open_with_env(char *program, char *path)
469 strncpy(BUF1, program, BUFLEN - 1);
470 strncat(BUF1, " ", BUFLEN - strlen(program) - 1);
471 shell_escaped_cat(BUF1, path, BUFLEN - strlen(program) - 2);
472 spawn(RV_SHELL, "-c", BUF1, NULL );
474 spawn(program, path, NULL);
485 setlocale(LC_ALL, "");
488 timeout(100); /* For getch(). */
490 nonl(); /* No NL->CR/NL on output. */
491 intrflush(stdscr, FALSE);
492 keypad(stdscr, TRUE);
493 curs_set(FALSE); /* Hide blinking cursor. */
497 #ifdef NCURSES_EXT_FUNCS
498 use_default_colors();
503 init_pair(RED, COLOR_RED, bg);
504 init_pair(GREEN, COLOR_GREEN, bg);
505 init_pair(YELLOW, COLOR_YELLOW, bg);
506 init_pair(BLUE, COLOR_BLUE, bg);
507 init_pair(CYAN, COLOR_CYAN, bg);
508 init_pair(MAGENTA, COLOR_MAGENTA, bg);
509 init_pair(WHITE, COLOR_WHITE, bg);
510 init_pair(BLACK, COLOR_BLACK, bg);
512 atexit((void (*)(void))endwin);
516 /* Update the listing view. */
525 mvhline(0, 0, ' ', COLS);
526 attr_on(A_BOLD, NULL);
527 color_set(RVC_TABNUM, NULL);
528 mvaddch(0, COLS - 2, fm.tab + '0');
529 attr_off(A_BOLD, NULL);
530 if (fm.marks.nentries) {
531 numsize = snprintf(BUF1, BUFLEN, "%d", fm.marks.nentries);
532 color_set(RVC_MARKS, NULL);
533 mvaddstr(0, COLS - 3 - numsize, BUF1);
536 color_set(RVC_CWD, NULL);
537 mbstowcs(WBUF, CWD, PATH_MAX);
538 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
539 wcolor_set(fm.window, RVC_BORDER, NULL);
540 wborder(fm.window, 0, 0, 0, 0, 0, 0, 0, 0);
541 ESEL = MAX(MIN(ESEL, fm.nfiles - 1), 0);
544 * Selection might not be visible, due to cursor wrapping or
545 * window shrinking. In that case, the scroll must be moved to
548 if (fm.nfiles > HEIGHT) {
549 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
550 SCROLL = MIN(MAX(SCROLL, 0), fm.nfiles - HEIGHT);
553 marking = !strcmp(CWD, fm.marks.dirpath);
554 for (i = 0, j = SCROLL; i < HEIGHT && j < fm.nfiles; i++, j++) {
555 ishidden = ENAME(j)[0] == '.';
557 wattr_on(fm.window, A_REVERSE, NULL);
559 wcolor_set(fm.window, RVC_LINK, NULL);
561 wcolor_set(fm.window, RVC_HIDDEN, NULL);
562 else if (S_ISREG(EMODE(j))) {
563 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
564 wcolor_set(fm.window, RVC_EXEC, NULL);
566 wcolor_set(fm.window, RVC_REG, NULL);
567 } else if (S_ISDIR(EMODE(j)))
568 wcolor_set(fm.window, RVC_DIR, NULL);
569 else if (S_ISCHR(EMODE(j)))
570 wcolor_set(fm.window, RVC_CHR, NULL);
571 else if (S_ISBLK(EMODE(j)))
572 wcolor_set(fm.window, RVC_BLK, NULL);
573 else if (S_ISFIFO(EMODE(j)))
574 wcolor_set(fm.window, RVC_FIFO, NULL);
575 else if (S_ISSOCK(EMODE(j)))
576 wcolor_set(fm.window, RVC_SOCK, NULL);
577 if (S_ISDIR(EMODE(j))) {
578 mbstowcs(WBUF, ENAME(j), PATH_MAX);
582 const char *suffix, *suffixes = "BKMGTPEZY";
583 off_t human_size = ESIZE(j) * 10;
584 int length = mbstowcs(WBUF, ENAME(j), PATH_MAX);
585 int namecols = wcswidth(WBUF, length);
586 for (suffix = suffixes; human_size >= 10240; suffix++)
587 human_size = (human_size + 512) / 1024;
589 swprintf(WBUF + length, PATH_MAX - length,
591 (int)(COLS - namecols - 6),
592 (int)human_size / 10, *suffix);
594 swprintf(WBUF + length, PATH_MAX - length,
596 (int)(COLS - namecols - 8),
597 (int)human_size / 10,
598 (int)human_size % 10, *suffix);
600 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
601 mvwaddnwstr(fm.window, i + 1, 2, WBUF, COLS - 4);
602 if (marking && MARKED(j)) {
603 wcolor_set(fm.window, RVC_MARKS, NULL);
604 mvwaddch(fm.window, i + 1, 1, RVS_MARK);
606 mvwaddch(fm.window, i + 1, 1, ' ');
608 wattr_off(fm.window, A_REVERSE, NULL);
610 for (; i < HEIGHT; i++)
611 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
612 if (fm.nfiles > HEIGHT) {
614 center = (SCROLL + HEIGHT / 2) * HEIGHT / fm.nfiles;
615 height = (HEIGHT - 1) * HEIGHT / fm.nfiles;
618 wcolor_set(fm.window, RVC_SCROLLBAR, NULL);
619 mvwvline(fm.window, center - height/2 + 1, COLS - 1,
620 RVS_SCROLLBAR, height);
622 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
623 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
624 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
628 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, fm.nfiles);
629 snprintf(BUF1 + 3, BUFLEN - 3, "%12s", BUF2);
630 color_set(RVC_STATUS, NULL);
631 mvaddstr(LINES - 1, STATUSPOS, BUF1);
635 /* Show a message on the status bar. */
636 static void __attribute__((format(printf, 2, 3)))
637 message(enum color c, const char *fmt, ...)
643 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
646 pos = (STATUSPOS - len) / 2;
647 attr_on(A_BOLD, NULL);
649 mvaddstr(LINES - 1, pos, BUF1);
650 color_set(DEFAULT, NULL);
651 attr_off(A_BOLD, NULL);
654 /* Clear message area, leaving only status info. */
658 mvhline(LINES - 1, 0, ' ', STATUSPOS);
661 /* Comparison used to sort listing entries. */
663 rowcmp(const void *a, const void *b)
665 int isdir1, isdir2, cmpdir;
666 const struct row *r1 = a;
667 const struct row *r2 = b;
668 isdir1 = S_ISDIR(r1->mode);
669 isdir2 = S_ISDIR(r2->mode);
670 cmpdir = isdir2 - isdir1;
671 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
674 /* Get all entries in current working directory. */
676 ls(struct row **rowsp, uint8_t flags)
684 if (!(dp = opendir(".")))
686 n = -2; /* We don't want the entries "." and "..". */
694 rows = xmalloc(n * sizeof(*rows));
696 while ((ep = readdir(dp))) {
697 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
699 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
701 lstat(ep->d_name, &statbuf);
702 rows[i].islink = S_ISLNK(statbuf.st_mode);
703 stat(ep->d_name, &statbuf);
704 if (S_ISDIR(statbuf.st_mode)) {
705 if (flags & SHOW_DIRS) {
706 rows[i].name = xmalloc(strlen(ep->d_name) + 2);
707 strcpy(rows[i].name, ep->d_name);
709 strcat(rows[i].name, "/");
710 rows[i].mode = statbuf.st_mode;
713 } else if (flags & SHOW_FILES) {
714 rows[i].name = xmalloc(strlen(ep->d_name) + 1);
715 strcpy(rows[i].name, ep->d_name);
716 rows[i].size = statbuf.st_size;
717 rows[i].mode = statbuf.st_mode;
721 n = i; /* Ignore unused space in array caused by filters. */
722 qsort(rows, n, sizeof(*rows), rowcmp);
729 free_rows(struct row **rowsp, int nfiles)
733 for (i = 0; i < nfiles; i++)
734 free((*rowsp)[i].name);
739 /* Change working directory to the path in CWD. */
745 message(CYAN, "Loading \"%s\"...", CWD);
747 if (chdir(CWD) == -1) {
748 getcwd(CWD, PATH_MAX - 1);
749 if (CWD[strlen(CWD) - 1] != '/')
756 free_rows(&fm.rows, fm.nfiles);
757 fm.nfiles = ls(&fm.rows, FLAGS);
758 if (!strcmp(CWD, fm.marks.dirpath)) {
759 for (i = 0; i < fm.nfiles; i++) {
760 for (j = 0; j < fm.marks.bulk; j++)
761 if (fm.marks.entries[j] &&
762 !strcmp(fm.marks.entries[j], ENAME(i)))
764 MARKED(i) = j < fm.marks.bulk;
767 for (i = 0; i < fm.nfiles; i++)
774 /* Select a target entry, if it is present. */
776 try_to_sel(const char *target)
780 while ((ESEL + 1) < fm.nfiles && S_ISDIR(EMODE(ESEL)))
782 while ((ESEL + 1) < fm.nfiles && strcoll(ENAME(ESEL), target) < 0)
786 /* Reload CWD, but try to keep selection. */
791 strcpy(INPUT, ENAME(ESEL));
800 count_dir(const char *path)
805 char subpath[PATH_MAX];
808 if (!(dp = opendir(path)))
811 while ((ep = readdir(dp))) {
812 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
814 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
815 lstat(subpath, &statbuf);
816 if (S_ISDIR(statbuf.st_mode)) {
817 strcat(subpath, "/");
818 total += count_dir(subpath);
820 total += statbuf.st_size;
835 chdir(fm.marks.dirpath);
836 for (i = 0; i < fm.marks.bulk; i++) {
837 entry = fm.marks.entries[i];
840 total += count_dir(entry);
842 lstat(entry, &statbuf);
843 total += statbuf.st_size;
852 * Recursively process a source directory using CWD as destination
853 * root. For each node (i.e. directory), do the following:
855 * 1. call pre(destination);
856 * 2. call proc() on every child leaf (i.e. files);
857 * 3. recurse into every child node;
858 * 4. call pos(source).
860 * E.g. to move directory /src/ (and all its contents) inside /dst/:
861 * strcpy(CWD, "/dst/");
862 * process_dir(adddir, movfile, deldir, "/src/");
865 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
871 char subpath[PATH_MAX];
875 char dstpath[PATH_MAX];
876 strcpy(dstpath, CWD);
877 strcat(dstpath, path + strlen(fm . marks . dirpath));
880 if (!(dp = opendir(path)))
882 while ((ep = readdir(dp))) {
883 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
885 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
886 lstat(subpath, &statbuf);
887 if (S_ISDIR(statbuf.st_mode)) {
888 strcat(subpath, "/");
889 ret |= process_dir(pre, proc, pos, subpath);
891 ret |= proc(subpath);
900 * Process all marked entries using CWD as destination root. All
901 * marked entries that are directories will be recursively processed.
902 * See process_dir() for details on the parameters.
905 process_marked(PROCESS pre, PROCESS proc, PROCESS pos, const char *msg_doing,
906 const char *msg_done)
913 message(CYAN, "%s...", msg_doing);
915 fm.prog = (struct prog){0, count_marked(), msg_doing};
916 for (i = 0; i < fm.marks.bulk; i++) {
917 entry = fm.marks.entries[i];
920 snprintf(path, PATH_MAX, "%s%s", fm.marks.dirpath,
923 if (!strncmp(path, CWD, strlen(path)))
926 ret = process_dir(pre, proc, pos, path);
930 del_mark(&fm.marks, entry);
937 if (!fm.marks.nentries)
938 message(GREEN, "%s all marked entries.", msg_done);
940 message(RED, "Some errors occured while %s.", msg_doing);
945 update_progress(off_t delta)
951 fm.prog.partial += delta;
952 percent = (int)(fm.prog.partial * 100 / fm.prog.total);
953 message(CYAN, "%s...%d%%", fm.prog.msg, percent);
957 /* Wrappers for file operations. */
959 delfile(const char *path)
964 ret = lstat(path, &st);
967 update_progress(st.st_size);
971 static PROCESS deldir = rmdir;
973 addfile(const char *path)
975 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
978 ret = creat(path, 0644);
985 cpyfile(const char *srcpath)
991 char dstpath[PATH_MAX];
993 strcpy(dstpath, CWD);
994 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
995 ret = lstat(srcpath, &st);
998 if (S_ISLNK(st.st_mode)) {
999 ret = readlink(srcpath, BUF1, BUFLEN - 1);
1003 ret = symlink(BUF1, dstpath);
1005 ret = src = open(srcpath, O_RDONLY);
1008 ret = dst = creat(dstpath, st.st_mode);
1011 while ((size = read(src, buf, BUFSIZ)) > 0) {
1012 write(dst, buf, size);
1013 update_progress(size);
1024 adddir(const char *path)
1029 ret = stat(CWD, &st);
1032 return mkdir(path, st.st_mode);
1036 movfile(const char *srcpath)
1040 char dstpath[PATH_MAX];
1042 strcpy(dstpath, CWD);
1043 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
1044 ret = rename(srcpath, dstpath);
1046 ret = lstat(dstpath, &st);
1049 update_progress(st.st_size);
1050 } else if (errno == EXDEV) {
1051 ret = cpyfile(srcpath);
1054 ret = unlink(srcpath);
1060 start_line_edit(const char *init_input)
1063 strncpy(INPUT, init_input, BUFLEN);
1064 fm.edit.left = mbstowcs(fm.edit.buffer, init_input, BUFLEN);
1065 fm.edit.right = BUFLEN - 1;
1066 fm.edit.buffer[BUFLEN] = L'\0';
1070 /* Read input and change editing state accordingly. */
1071 static enum editstate
1074 wchar_t eraser, killer, wch;
1077 ret = fm_get_wch((wint_t *)&wch);
1078 erasewchar(&eraser);
1080 if (ret == KEY_CODE_YES) {
1081 if (wch == KEY_ENTER) {
1084 } else if (wch == KEY_LEFT) {
1085 if (EDIT_CAN_LEFT(fm.edit))
1087 } else if (wch == KEY_RIGHT) {
1088 if (EDIT_CAN_RIGHT(fm.edit))
1089 EDIT_RIGHT(fm.edit);
1090 } else if (wch == KEY_UP) {
1091 while (EDIT_CAN_LEFT(fm.edit))
1093 } else if (wch == KEY_DOWN) {
1094 while (EDIT_CAN_RIGHT(fm.edit))
1095 EDIT_RIGHT(fm.edit);
1096 } else if (wch == KEY_BACKSPACE) {
1097 if (EDIT_CAN_LEFT(fm.edit))
1098 EDIT_BACKSPACE(fm.edit);
1099 } else if (wch == KEY_DC) {
1100 if (EDIT_CAN_RIGHT(fm.edit))
1101 EDIT_DELETE(fm.edit);
1104 if (wch == L'\r' || wch == L'\n') {
1107 } else if (wch == L'\t') {
1110 } else if (wch == eraser) {
1111 if (EDIT_CAN_LEFT(fm.edit))
1112 EDIT_BACKSPACE(fm.edit);
1113 } else if (wch == killer) {
1114 EDIT_CLEAR(fm.edit);
1116 } else if (iswprint(wch)) {
1117 if (!EDIT_FULL(fm.edit))
1118 EDIT_INSERT(fm.edit, wch);
1121 /* Encode edit contents in INPUT. */
1122 fm.edit.buffer[fm.edit.left] = L'\0';
1123 length = wcstombs(INPUT, fm.edit.buffer, BUFLEN);
1124 wcstombs(&INPUT[length], &fm.edit.buffer[fm.edit.right + 1],
1129 /* Update line input on the screen. */
1131 update_input(const char *prompt, enum color c)
1133 int plen, ilen, maxlen;
1135 plen = strlen(prompt);
1136 ilen = mbstowcs(NULL, INPUT, 0);
1137 maxlen = STATUSPOS - plen - 2;
1138 if (ilen - fm.edit_scroll < maxlen)
1139 fm.edit_scroll = MAX(ilen - maxlen, 0);
1140 else if (fm.edit.left > fm.edit_scroll + maxlen - 1)
1141 fm.edit_scroll = fm.edit.left - maxlen;
1142 else if (fm.edit.left < fm.edit_scroll)
1143 fm.edit_scroll = MAX(fm.edit.left - maxlen, 0);
1144 color_set(RVC_PROMPT, NULL);
1145 mvaddstr(LINES - 1, 0, prompt);
1147 mbstowcs(WBUF, INPUT, COLS);
1148 mvaddnwstr(LINES - 1, plen, &WBUF[fm.edit_scroll], maxlen);
1149 mvaddch(LINES - 1, plen + MIN(ilen - fm.edit_scroll, maxlen + 1),
1151 color_set(DEFAULT, NULL);
1153 mvaddch(LINES - 1, plen - 1, '<');
1154 if (ilen > fm.edit_scroll + maxlen)
1155 mvaddch(LINES - 1, plen + maxlen, '>');
1156 move(LINES - 1, plen + fm.edit.left - fm.edit_scroll);
1163 ESEL = MIN(ESEL + 1, fm.nfiles - 1);
1170 ESEL = MAX(ESEL - 1, 0);
1174 cmd_scroll_down(void)
1178 ESEL = MIN(ESEL + HEIGHT, fm.nfiles - 1);
1179 if (fm.nfiles > HEIGHT)
1180 SCROLL = MIN(SCROLL + HEIGHT, fm.nfiles - HEIGHT);
1188 ESEL = MAX(ESEL - HEIGHT, 0);
1189 SCROLL = MAX(SCROLL - HEIGHT, 0);
1195 spawn("man", "fm", NULL);
1206 cmd_jump_bottom(void)
1209 ESEL = fm.nfiles - 1;
1215 if (!fm.nfiles || !S_ISDIR(EMODE(ESEL)))
1217 if (chdir(ENAME(ESEL)) == -1) {
1218 message(RED, "cd: %s: %s", ENAME(ESEL), strerror(errno));
1221 strlcat(CWD, ENAME(ESEL), sizeof(CWD));
1228 char *dirname, first;
1230 if (!strcmp(CWD, "/"))
1233 /* dirname(3) basically */
1234 dirname = strrchr(CWD, '/');
1236 dirname = strrchr(CWD, '/') + 1;
1242 strlcat(dirname, "/", sizeof(dirname));
1243 try_to_sel(dirname);
1245 if (fm.nfiles > HEIGHT)
1246 SCROLL = ESEL - HEIGHT / 2;
1254 if ((home = getenv("HOME")) == NULL) {
1255 message(RED, "HOME is not defined!");
1259 strlcpy(CWD, home, sizeof(CWD));
1260 if (*CWD != '\0' && CWD[strlen(CWD) - 1] != '/')
1261 strlcat(CWD, "/", sizeof(CWD));
1271 if ((path = getenv("CLIP")) == NULL ||
1272 (f = fopen(path, "w")) == NULL) {
1273 /* use internal clipboard */
1274 strlcpy(clipboard, CWD, sizeof(clipboard));
1275 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1279 fprintf(f, "%s%s", CWD, ENAME(ESEL));
1285 cmd_paste_path(void)
1293 if ((path = getenv("CLIP")) != NULL &&
1294 (f = fopen(path, "w")) != NULL) {
1295 r = fread(clipboard, 1, sizeof(clipboard)-1, f);
1297 if (r == -1 || r == 0)
1299 if ((nl = memmem(clipboard, r, "", 1)) == NULL)
1303 strlcpy(p, clipboard, sizeof(p));
1304 strlcpy(CWD, clipboard, sizeof(CWD));
1305 if ((nl = strrchr(CWD, '/')) != NULL) {
1307 nl = strrchr(p, '/');
1310 if (strcmp(CWD, "/") != 0)
1311 strlcat(CWD, "/", sizeof(CWD));
1317 memset(clipboard, 0, sizeof(clipboard));
1340 {'^', 0, cmd_cd_up, X_UPDV},
1341 {'h', 0, cmd_cd_up, X_UPDV},
1342 {'b', 0, cmd_cd_up, X_UPDV},
1343 {'l', 0, cmd_cd_down, X_UPDV},
1344 {'l', K_CTRL, cmd_reload, X_UPDV},
1345 {'f', 0, cmd_cd_down, X_UPDV},
1346 {'<', K_META, cmd_jump_top, X_UPDV},
1347 {'>', K_META, cmd_jump_bottom, X_UPDV},
1348 {'?', 0, cmd_man, 0},
1349 {'G', 0, cmd_jump_bottom, X_UPDV},
1350 {'H', 0, cmd_home, X_UPDV},
1351 {'J', 0, cmd_scroll_down, X_UPDV},
1352 {'K', 0, cmd_scroll_up, X_UPDV},
1353 {'V', K_CTRL, cmd_scroll_down, X_UPDV},
1354 {'g', 0, cmd_jump_top, X_UPDV},
1355 {'g', K_CTRL, NULL, X_UPDV},
1356 {'j', 0, cmd_down, X_UPDV},
1357 {'k', 0, cmd_up, X_UPDV},
1358 {'n', 0, cmd_down, X_UPDV},
1359 {'n', K_CTRL, cmd_down, X_UPDV},
1360 {'P', 0, cmd_paste_path, X_UPDV},
1361 {'p', 0, cmd_up, X_UPDV},
1362 {'p', K_CTRL, cmd_up, X_UPDV},
1363 {'q', 0, NULL, X_QUIT},
1364 {'v', K_META, cmd_scroll_up, X_UPDV},
1365 {'Y', 0, cmd_copy_path, X_UPDV},
1366 {KEY_DOWN, 0, cmd_scroll_down, X_UPDV},
1367 {KEY_NPAGE, 0, cmd_scroll_down, X_UPDV},
1368 {KEY_PPAGE, 0, cmd_scroll_up, X_UPDV},
1369 {KEY_RESIZE, 0, NULL, X_UPDV},
1370 {KEY_RESIZE, K_META, NULL, X_UPDV},
1371 {KEY_UP, 0, cmd_scroll_up, X_UPDV},
1381 if ((ch = fm_getch()) == '\e') {
1389 for (i = 0; i < nitems(bindings); ++i) {
1392 if (b->chflags & K_CTRL)
1394 if ((!meta && b->chflags & K_META) || ch != c)
1397 if (b->flags & X_QUIT)
1401 if (b->flags & X_UPDV)
1407 message(RED, "%s%s is undefined",
1408 meta ? "M-": "", keyname(ch));
1414 main(int argc, char *argv[])
1420 const char *clip_path;
1422 enum editstate edit_stat;
1423 FILE *save_cwd_file = NULL;
1424 FILE *save_marks_file = NULL;
1427 while ((ch = getopt_long(argc, argv, "d:hm:v", opts, NULL)) != -1) {
1430 if ((save_cwd_file = fopen(optarg, "w")) == NULL)
1431 err(1, "open %s", optarg);
1435 "Usage: fm [-hv] [-d file] [-m file] [dirs...]\n"
1436 "Browse current directory or the ones specified.\n"
1438 "See fm(1) for more information.\n"
1439 "fm homepage <https://github.com/omar-polo/fm>\n");
1442 if ((save_marks_file = fopen(optarg, "a")) == NULL)
1443 err(1, "open %s", optarg);
1446 printf("version: fm %s\n", RV_VERSION);
1451 if (pledge("stdio rpath wpath cpath tty proc exec", NULL) == -1)
1454 get_user_programs();
1457 for (i = 0; i < 10; i++) {
1458 fm.tabs[i].esel = fm.tabs[i].scroll = 0;
1459 fm.tabs[i].flags = RV_FLAGS;
1461 strcpy(fm.tabs[0].cwd, getenv("HOME"));
1462 for (i = 1; i < argc && i < 10; i++) {
1463 if ((d = opendir(argv[i]))) {
1464 realpath(argv[i], fm.tabs[i].cwd);
1467 strcpy(fm.tabs[i].cwd, fm.tabs[0].cwd);
1469 getcwd(fm.tabs[i].cwd, PATH_MAX);
1470 for (i++; i < 10; i++)
1471 strcpy(fm.tabs[i].cwd, fm.tabs[i - 1].cwd);
1472 for (i = 0; i < 10; i++)
1473 if (fm.tabs[i].cwd[strlen(fm.tabs[i].cwd) - 1] != '/')
1474 strcat(fm.tabs[i].cwd, "/");
1476 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
1477 init_marks(&fm.marks);
1479 strlcpy(clipboard, CWD, sizeof(clipboard));
1481 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1486 free_rows(&fm.rows, fm.nfiles);
1488 if (save_cwd_file != NULL) {
1489 fputs(CWD, save_cwd_file);
1490 fclose(save_cwd_file);
1492 if (save_marks_file != NULL) {
1493 for (i = 0; i < fm.marks.bulk; i++) {
1494 entry = fm.marks.entries[i];
1496 fprintf(save_marks_file, "%s%s\n",
1497 fm.marks.dirpath, entry);
1499 fclose(save_marks_file);
1501 free_marks(&fm.marks);