Blob


1 /* needed for some ncurses stuff */
2 #define _XOPEN_SOURCE_EXTENDED
3 #define _FILE_OFFSET_BITS 64
5 #include <sys/stat.h>
6 #include <sys/types.h>
7 #include <sys/wait.h>
9 #include <assert.h>
10 #include <ctype.h>
11 #include <curses.h>
12 #include <dirent.h>
13 #include <err.h>
14 #include <errno.h>
15 #include <fcntl.h>
16 #include <getopt.h>
17 #include <libgen.h>
18 #include <limits.h>
19 #include <locale.h>
20 #include <signal.h>
21 #include <stdarg.h>
22 #include <stdint.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <wchar.h>
28 #include <wctype.h>
30 #ifndef FM_SHELL
31 #define FM_SHELL "/bin/sh"
32 #endif
34 #ifndef FM_PAGER
35 #define FM_PAGER "/usr/bin/less"
36 #endif
38 #ifndef FM_ED
39 #define FM_ED "/bin/ed"
40 #endif
42 #ifndef FM_OPENER
43 #define FM_OPENER "xdg-open"
44 #endif
46 #include "config.h"
48 struct option opts[] = {
49 {"help", no_argument, NULL, 'h'},
50 {"version", no_argument, NULL, 'v'},
51 {NULL, 0, NULL, 0}
52 };
54 static char clipboard[PATH_MAX];
56 /* String buffers. */
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. */
79 #define BULK_INIT 5
80 #define BULK_THRESH 256
82 /* Information associated to each entry in listing. */
83 struct row {
84 char *name;
85 off_t size;
86 mode_t mode;
87 int islink;
88 int marked;
89 };
91 /* Dynamic array of marked entries. */
92 struct marks {
93 char dirpath[PATH_MAX];
94 int bulk;
95 int nentries;
96 char **entries;
97 };
99 /* Line editing state. */
100 struct edit {
101 wchar_t buffer[BUFLEN + 1];
102 int left, right;
103 };
105 /* Each tab only stores the following information. */
106 struct tab {
107 int scroll;
108 int esel;
109 uint8_t flags;
110 char cwd[PATH_MAX];
111 };
113 struct prog {
114 off_t partial;
115 off_t total;
116 const char *msg;
117 };
119 /* Global state. */
120 static struct state {
121 int tab;
122 int nfiles;
123 struct row *rows;
124 WINDOW *window;
125 struct marks marks;
126 struct edit edit;
127 int edit_scroll;
128 volatile sig_atomic_t pending_usr1;
129 volatile sig_atomic_t pending_winch;
130 struct prog prog;
131 struct tab tabs[10];
132 } fm;
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
145 /* Helpers. */
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);
168 #ifndef __dead
169 #define __dead __attribute__((noreturn))
170 #endif
172 static inline __dead void
173 quit(const char *reason)
175 int saved_errno;
177 saved_errno = errno;
178 endwin();
179 nocbreak();
180 fflush(stderr);
181 errno = saved_errno;
182 err(1, "%s", reason);
185 static inline void *
186 xmalloc(size_t size)
188 void *d;
190 if ((d = malloc(size)) == NULL)
191 quit("malloc");
192 return d;
195 static inline void *
196 xcalloc(size_t nmemb, size_t size)
198 void *d;
200 if ((d = calloc(nmemb, size)) == NULL)
201 quit("calloc");
202 return d;
205 static inline void *
206 xrealloc(void *p, size_t size)
208 void *d;
210 if ((d = realloc(p, size)) == NULL)
211 quit("realloc");
212 return d;
215 static void
216 init_marks(struct marks *marks)
218 strcpy(marks->dirpath, "");
219 marks->bulk = BULK_INIT;
220 marks->nentries = 0;
221 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
224 /* Unmark all entries. */
225 static void
226 mark_none(struct marks *marks)
228 int i;
230 strcpy(marks->dirpath, "");
231 for (i = 0; i < marks->bulk && marks->nentries; i++)
232 if (marks->entries[i]) {
233 free(marks->entries[i]);
234 marks->entries[i] = NULL;
235 marks->nentries--;
237 if (marks->bulk > BULK_THRESH) {
238 /* Reset bulk to free some memory. */
239 free(marks->entries);
240 marks->bulk = BULK_INIT;
241 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
245 static void
246 add_mark(struct marks *marks, char *dirpath, char *entry)
248 int i;
250 if (!strcmp(marks->dirpath, dirpath)) {
251 /* Append mark to directory. */
252 if (marks->nentries == marks->bulk) {
253 /* Expand bulk to accomodate new entry. */
254 int extra = marks->bulk / 2;
255 marks->bulk += extra; /* bulk *= 1.5; */
256 marks->entries = xrealloc(marks->entries,
257 marks->bulk * sizeof(*marks->entries));
258 memset(&marks->entries[marks->nentries], 0,
259 extra * sizeof(*marks->entries));
260 i = marks->nentries;
261 } else {
262 /* Search for empty slot (there must be one). */
263 for (i = 0; i < marks->bulk; i++)
264 if (!marks->entries[i])
265 break;
267 } else {
268 /* Directory changed. Discard old marks. */
269 mark_none(marks);
270 strcpy(marks->dirpath, dirpath);
271 i = 0;
273 marks->entries[i] = xmalloc(strlen(entry) + 1);
274 strcpy(marks->entries[i], entry);
275 marks->nentries++;
278 static void
279 del_mark(struct marks *marks, char *entry)
281 int i;
283 if (marks->nentries > 1) {
284 for (i = 0; i < marks->bulk; i++)
285 if (marks->entries[i] &&
286 !strcmp(marks->entries[i], entry))
287 break;
288 free(marks->entries[i]);
289 marks->entries[i] = NULL;
290 marks->nentries--;
291 } else
292 mark_none(marks);
295 static void
296 free_marks(struct marks *marks)
298 int i;
300 for (i = 0; i < marks->bulk && marks->nentries; i++)
301 if (marks->entries[i]) {
302 free(marks->entries[i]);
303 marks->nentries--;
305 free(marks->entries);
308 static void
309 handle_usr1(int sig)
311 fm.pending_usr1 = 1;
314 static void
315 handle_winch(int sig)
317 fm.pending_winch = 1;
320 static void
321 enable_handlers(void)
323 struct sigaction sa;
325 memset(&sa, 0, sizeof(struct sigaction));
326 sa.sa_handler = handle_usr1;
327 sigaction(SIGUSR1, &sa, NULL);
328 sa.sa_handler = handle_winch;
329 sigaction(SIGWINCH, &sa, NULL);
332 static void
333 disable_handlers(void)
335 struct sigaction sa;
337 memset(&sa, 0, sizeof(struct sigaction));
338 sa.sa_handler = SIG_DFL;
339 sigaction(SIGUSR1, &sa, NULL);
340 sigaction(SIGWINCH, &sa, NULL);
343 static void reload(void);
344 static void update_view(void);
346 /* Handle any signals received since last call. */
347 static void
348 sync_signals(void)
350 if (fm.pending_usr1) {
351 /* SIGUSR1 received: refresh directory listing. */
352 reload();
353 fm.pending_usr1 = 0;
355 if (fm.pending_winch) {
356 /* SIGWINCH received: resize application accordingly. */
357 delwin(fm.window);
358 endwin();
359 refresh();
360 clear();
361 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
362 if (HEIGHT < fm.nfiles && SCROLL + HEIGHT > fm.nfiles)
363 SCROLL = ESEL - HEIGHT;
364 update_view();
365 fm.pending_winch = 0;
369 /*
370 * This function must be used in place of getch(). It handles signals
371 * while waiting for user input.
372 */
373 static int
374 fm_getch()
376 int ch;
378 while ((ch = getch()) == ERR)
379 sync_signals();
380 return ch;
383 /*
384 * This function must be used in place of get_wch(). It handles
385 * signals while waiting for user input.
386 */
387 static int
388 fm_get_wch(wint_t *wch)
390 wint_t ret;
392 while ((ret = get_wch(wch)) == (wint_t)ERR)
393 sync_signals();
394 return ret;
397 /* Get user programs from the environment. */
399 #define FM_ENV(dst, src) if ((dst = getenv("FM_" #src)) == NULL) \
400 dst = getenv(#src);
402 static void
403 get_user_programs()
405 FM_ENV(user_shell, SHELL);
406 FM_ENV(user_pager, PAGER);
407 FM_ENV(user_editor, VISUAL);
408 if (!user_editor)
409 FM_ENV(user_editor, EDITOR);
410 FM_ENV(user_open, OPEN);
413 /* Do a fork-exec to external program (e.g. $EDITOR). */
414 static void
415 spawn(const char *argv0, ...)
417 pid_t pid;
418 int status;
419 size_t i;
420 const char *argv[16], *last;
421 va_list ap;
423 memset(argv, 0, sizeof(argv));
425 va_start(ap, argv0);
426 argv[0] = argv0;
427 for (i = 1; i < nitems(argv); ++i) {
428 last = va_arg(ap, const char *);
429 if (last == NULL)
430 break;
431 argv[i] = last;
433 va_end(ap);
435 if (last != NULL)
436 abort();
438 disable_handlers();
439 endwin();
441 switch (pid = fork()) {
442 case -1:
443 quit("fork");
444 case 0: /* child */
445 setenv("RVSEL", fm.nfiles ? ENAME(ESEL) : "", 1);
446 execvp(argv[0], (char *const *)argv);
447 quit("execvp");
448 default:
449 waitpid(pid, &status, 0);
450 enable_handlers();
451 kill(getpid(), SIGWINCH);
455 static void
456 shell_escaped_cat(char *buf, char *str, size_t n)
458 char *p = buf + strlen(buf);
459 *p++ = '\'';
460 for (n--; n; n--, str++) {
461 switch (*str) {
462 case '\'':
463 if (n < 4)
464 goto done;
465 strcpy(p, "'\\''");
466 n -= 4;
467 p += 4;
468 break;
469 case '\0':
470 goto done;
471 default:
472 *p = *str;
473 p++;
476 done:
477 strncat(p, "'", n);
480 static int
481 open_with_env(char *program, char *path)
483 if (program) {
484 #ifdef RV_SHELL
485 strncpy(BUF1, program, BUFLEN - 1);
486 strncat(BUF1, " ", BUFLEN - strlen(program) - 1);
487 shell_escaped_cat(BUF1, path, BUFLEN - strlen(program) - 2);
488 spawn(RV_SHELL, "-c", BUF1, NULL );
489 #else
490 spawn(program, path, NULL);
491 #endif
492 return 1;
494 return 0;
497 /* Curses setup. */
498 static void
499 init_term()
501 setlocale(LC_ALL, "");
502 initscr();
503 raw();
504 timeout(100); /* For getch(). */
505 noecho();
506 nonl(); /* No NL->CR/NL on output. */
507 intrflush(stdscr, FALSE);
508 keypad(stdscr, TRUE);
509 curs_set(FALSE); /* Hide blinking cursor. */
510 if (has_colors()) {
511 short bg;
512 start_color();
513 #ifdef NCURSES_EXT_FUNCS
514 use_default_colors();
515 bg = -1;
516 #else
517 bg = COLOR_BLACK;
518 #endif
519 init_pair(RED, COLOR_RED, bg);
520 init_pair(GREEN, COLOR_GREEN, bg);
521 init_pair(YELLOW, COLOR_YELLOW, bg);
522 init_pair(BLUE, COLOR_BLUE, bg);
523 init_pair(CYAN, COLOR_CYAN, bg);
524 init_pair(MAGENTA, COLOR_MAGENTA, bg);
525 init_pair(WHITE, COLOR_WHITE, bg);
526 init_pair(BLACK, COLOR_BLACK, bg);
528 atexit((void (*)(void))endwin);
529 enable_handlers();
532 /* Update the listing view. */
533 static void
534 update_view()
536 int i, j;
537 int numsize;
538 int ishidden;
539 int marking;
541 mvhline(0, 0, ' ', COLS);
542 attr_on(A_BOLD, NULL);
543 color_set(RVC_TABNUM, NULL);
544 mvaddch(0, COLS - 2, fm.tab + '0');
545 attr_off(A_BOLD, NULL);
546 if (fm.marks.nentries) {
547 numsize = snprintf(BUF1, BUFLEN, "%d", fm.marks.nentries);
548 color_set(RVC_MARKS, NULL);
549 mvaddstr(0, COLS - 3 - numsize, BUF1);
550 } else
551 numsize = -1;
552 color_set(RVC_CWD, NULL);
553 mbstowcs(WBUF, CWD, PATH_MAX);
554 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
555 wcolor_set(fm.window, RVC_BORDER, NULL);
556 wborder(fm.window, 0, 0, 0, 0, 0, 0, 0, 0);
557 ESEL = MAX(MIN(ESEL, fm.nfiles - 1), 0);
559 /*
560 * Selection might not be visible, due to cursor wrapping or
561 * window shrinking. In that case, the scroll must be moved to
562 * make it visible.
563 */
564 if (fm.nfiles > HEIGHT) {
565 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
566 SCROLL = MIN(MAX(SCROLL, 0), fm.nfiles - HEIGHT);
567 } else
568 SCROLL = 0;
569 marking = !strcmp(CWD, fm.marks.dirpath);
570 for (i = 0, j = SCROLL; i < HEIGHT && j < fm.nfiles; i++, j++) {
571 ishidden = ENAME(j)[0] == '.';
572 if (j == ESEL)
573 wattr_on(fm.window, A_REVERSE, NULL);
574 if (ISLINK(j))
575 wcolor_set(fm.window, RVC_LINK, NULL);
576 else if (ishidden)
577 wcolor_set(fm.window, RVC_HIDDEN, NULL);
578 else if (S_ISREG(EMODE(j))) {
579 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
580 wcolor_set(fm.window, RVC_EXEC, NULL);
581 else
582 wcolor_set(fm.window, RVC_REG, NULL);
583 } else if (S_ISDIR(EMODE(j)))
584 wcolor_set(fm.window, RVC_DIR, NULL);
585 else if (S_ISCHR(EMODE(j)))
586 wcolor_set(fm.window, RVC_CHR, NULL);
587 else if (S_ISBLK(EMODE(j)))
588 wcolor_set(fm.window, RVC_BLK, NULL);
589 else if (S_ISFIFO(EMODE(j)))
590 wcolor_set(fm.window, RVC_FIFO, NULL);
591 else if (S_ISSOCK(EMODE(j)))
592 wcolor_set(fm.window, RVC_SOCK, NULL);
593 if (S_ISDIR(EMODE(j))) {
594 mbstowcs(WBUF, ENAME(j), PATH_MAX);
595 if (ISLINK(j))
596 wcscat(WBUF, L"/");
597 } else {
598 const char *suffix, *suffixes = "BKMGTPEZY";
599 off_t human_size = ESIZE(j) * 10;
600 int length = mbstowcs(WBUF, ENAME(j), PATH_MAX);
601 int namecols = wcswidth(WBUF, length);
602 for (suffix = suffixes; human_size >= 10240; suffix++)
603 human_size = (human_size + 512) / 1024;
604 if (*suffix == 'B')
605 swprintf(WBUF + length, PATH_MAX - length,
606 L"%*d %c",
607 (int)(COLS - namecols - 6),
608 (int)human_size / 10, *suffix);
609 else
610 swprintf(WBUF + length, PATH_MAX - length,
611 L"%*d.%d %c",
612 (int)(COLS - namecols - 8),
613 (int)human_size / 10,
614 (int)human_size % 10, *suffix);
616 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
617 mvwaddnwstr(fm.window, i + 1, 2, WBUF, COLS - 4);
618 if (marking && MARKED(j)) {
619 wcolor_set(fm.window, RVC_MARKS, NULL);
620 mvwaddch(fm.window, i + 1, 1, RVS_MARK);
621 } else
622 mvwaddch(fm.window, i + 1, 1, ' ');
623 if (j == ESEL)
624 wattr_off(fm.window, A_REVERSE, NULL);
626 for (; i < HEIGHT; i++)
627 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
628 if (fm.nfiles > HEIGHT) {
629 int center, height;
630 center = (SCROLL + HEIGHT / 2) * HEIGHT / fm.nfiles;
631 height = (HEIGHT - 1) * HEIGHT / fm.nfiles;
632 if (!height)
633 height = 1;
634 wcolor_set(fm.window, RVC_SCROLLBAR, NULL);
635 mvwvline(fm.window, center - height/2 + 1, COLS - 1,
636 RVS_SCROLLBAR, height);
638 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
639 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
640 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
641 if (!fm.nfiles)
642 strcpy(BUF2, "0/0");
643 else
644 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, fm.nfiles);
645 snprintf(BUF1 + 3, BUFLEN - 3, "%12s", BUF2);
646 color_set(RVC_STATUS, NULL);
647 mvaddstr(LINES - 1, STATUSPOS, BUF1);
648 wrefresh(fm.window);
651 /* Show a message on the status bar. */
652 static void __attribute__((format(printf, 2, 3)))
653 message(enum color c, const char *fmt, ...)
655 int len, pos;
656 va_list args;
658 va_start(args, fmt);
659 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
660 va_end(args);
661 len = strlen(BUF1);
662 pos = (STATUSPOS - len) / 2;
663 attr_on(A_BOLD, NULL);
664 color_set(c, NULL);
665 mvaddstr(LINES - 1, pos, BUF1);
666 color_set(DEFAULT, NULL);
667 attr_off(A_BOLD, NULL);
670 /* Clear message area, leaving only status info. */
671 static void
672 clear_message()
674 mvhline(LINES - 1, 0, ' ', STATUSPOS);
677 /* Comparison used to sort listing entries. */
678 static int
679 rowcmp(const void *a, const void *b)
681 int isdir1, isdir2, cmpdir;
682 const struct row *r1 = a;
683 const struct row *r2 = b;
684 isdir1 = S_ISDIR(r1->mode);
685 isdir2 = S_ISDIR(r2->mode);
686 cmpdir = isdir2 - isdir1;
687 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
690 /* Get all entries in current working directory. */
691 static int
692 ls(struct row **rowsp, uint8_t flags)
694 DIR *dp;
695 struct dirent *ep;
696 struct stat statbuf;
697 struct row *rows;
698 int i, n;
700 if (!(dp = opendir(".")))
701 return -1;
702 n = -2; /* We don't want the entries "." and "..". */
703 while (readdir(dp))
704 n++;
705 if (n == 0) {
706 closedir(dp);
707 return 0;
709 rewinddir(dp);
710 rows = xmalloc(n * sizeof(*rows));
711 i = 0;
712 while ((ep = readdir(dp))) {
713 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
714 continue;
715 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
716 continue;
717 lstat(ep->d_name, &statbuf);
718 rows[i].islink = S_ISLNK(statbuf.st_mode);
719 stat(ep->d_name, &statbuf);
720 if (S_ISDIR(statbuf.st_mode)) {
721 if (flags & SHOW_DIRS) {
722 rows[i].name = xmalloc(strlen(ep->d_name) + 2);
723 strcpy(rows[i].name, ep->d_name);
724 if (!rows[i].islink)
725 strcat(rows[i].name, "/");
726 rows[i].mode = statbuf.st_mode;
727 i++;
729 } else if (flags & SHOW_FILES) {
730 rows[i].name = xmalloc(strlen(ep->d_name) + 1);
731 strcpy(rows[i].name, ep->d_name);
732 rows[i].size = statbuf.st_size;
733 rows[i].mode = statbuf.st_mode;
734 i++;
737 n = i; /* Ignore unused space in array caused by filters. */
738 qsort(rows, n, sizeof(*rows), rowcmp);
739 closedir(dp);
740 *rowsp = rows;
741 return n;
744 static void
745 free_rows(struct row **rowsp, int nfiles)
747 int i;
749 for (i = 0; i < nfiles; i++)
750 free((*rowsp)[i].name);
751 free(*rowsp);
752 *rowsp = NULL;
755 /* Change working directory to the path in CWD. */
756 static void
757 cd(int reset)
759 int i, j;
761 message(CYAN, "Loading \"%s\"...", CWD);
762 refresh();
763 if (chdir(CWD) == -1) {
764 getcwd(CWD, PATH_MAX - 1);
765 if (CWD[strlen(CWD) - 1] != '/')
766 strcat(CWD, "/");
767 goto done;
769 if (reset)
770 ESEL = SCROLL = 0;
771 if (fm.nfiles)
772 free_rows(&fm.rows, fm.nfiles);
773 fm.nfiles = ls(&fm.rows, FLAGS);
774 if (!strcmp(CWD, fm.marks.dirpath)) {
775 for (i = 0; i < fm.nfiles; i++) {
776 for (j = 0; j < fm.marks.bulk; j++)
777 if (fm.marks.entries[j] &&
778 !strcmp(fm.marks.entries[j], ENAME(i)))
779 break;
780 MARKED(i) = j < fm.marks.bulk;
782 } else
783 for (i = 0; i < fm.nfiles; i++)
784 MARKED(i) = 0;
785 done:
786 clear_message();
787 update_view();
790 /* Select a target entry, if it is present. */
791 static void
792 try_to_sel(const char *target)
794 ESEL = 0;
795 if (!ISDIR(target))
796 while ((ESEL + 1) < fm.nfiles && S_ISDIR(EMODE(ESEL)))
797 ESEL++;
798 while ((ESEL + 1) < fm.nfiles && strcoll(ENAME(ESEL), target) < 0)
799 ESEL++;
802 /* Reload CWD, but try to keep selection. */
803 static void
804 reload()
806 if (fm.nfiles) {
807 strcpy(INPUT, ENAME(ESEL));
808 cd(0);
809 try_to_sel(INPUT);
810 update_view();
811 } else
812 cd(1);
815 static off_t
816 count_dir(const char *path)
818 DIR *dp;
819 struct dirent *ep;
820 struct stat statbuf;
821 char subpath[PATH_MAX];
822 off_t total;
824 if (!(dp = opendir(path)))
825 return 0;
826 total = 0;
827 while ((ep = readdir(dp))) {
828 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
829 continue;
830 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
831 lstat(subpath, &statbuf);
832 if (S_ISDIR(statbuf.st_mode)) {
833 strcat(subpath, "/");
834 total += count_dir(subpath);
835 } else
836 total += statbuf.st_size;
838 closedir(dp);
839 return total;
842 static off_t
843 count_marked()
845 int i;
846 char *entry;
847 off_t total;
848 struct stat statbuf;
850 total = 0;
851 chdir(fm.marks.dirpath);
852 for (i = 0; i < fm.marks.bulk; i++) {
853 entry = fm.marks.entries[i];
854 if (entry) {
855 if (ISDIR(entry)) {
856 total += count_dir(entry);
857 } else {
858 lstat(entry, &statbuf);
859 total += statbuf.st_size;
863 chdir(CWD);
864 return total;
867 /*
868 * Recursively process a source directory using CWD as destination
869 * root. For each node (i.e. directory), do the following:
871 * 1. call pre(destination);
872 * 2. call proc() on every child leaf (i.e. files);
873 * 3. recurse into every child node;
874 * 4. call pos(source).
876 * E.g. to move directory /src/ (and all its contents) inside /dst/:
877 * strcpy(CWD, "/dst/");
878 * process_dir(adddir, movfile, deldir, "/src/");
879 */
880 static int
881 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
883 int ret;
884 DIR *dp;
885 struct dirent *ep;
886 struct stat statbuf;
887 char subpath[PATH_MAX];
889 ret = 0;
890 if (pre) {
891 char dstpath[PATH_MAX];
892 strcpy(dstpath, CWD);
893 strcat(dstpath, path + strlen(fm . marks . dirpath));
894 ret |= pre(dstpath);
896 if (!(dp = opendir(path)))
897 return -1;
898 while ((ep = readdir(dp))) {
899 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
900 continue;
901 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
902 lstat(subpath, &statbuf);
903 if (S_ISDIR(statbuf.st_mode)) {
904 strcat(subpath, "/");
905 ret |= process_dir(pre, proc, pos, subpath);
906 } else
907 ret |= proc(subpath);
909 closedir(dp);
910 if (pos)
911 ret |= pos(path);
912 return ret;
915 /*
916 * Process all marked entries using CWD as destination root. All
917 * marked entries that are directories will be recursively processed.
918 * See process_dir() for details on the parameters.
919 */
920 static void
921 process_marked(PROCESS pre, PROCESS proc, PROCESS pos, const char *msg_doing,
922 const char *msg_done)
924 int i, ret;
925 char *entry;
926 char path[PATH_MAX];
928 clear_message();
929 message(CYAN, "%s...", msg_doing);
930 refresh();
931 fm.prog = (struct prog){0, count_marked(), msg_doing};
932 for (i = 0; i < fm.marks.bulk; i++) {
933 entry = fm.marks.entries[i];
934 if (entry) {
935 ret = 0;
936 snprintf(path, PATH_MAX, "%s%s", fm.marks.dirpath,
937 entry);
938 if (ISDIR(entry)) {
939 if (!strncmp(path, CWD, strlen(path)))
940 ret = -1;
941 else
942 ret = process_dir(pre, proc, pos, path);
943 } else
944 ret = proc(path);
945 if (!ret) {
946 del_mark(&fm.marks, entry);
947 reload();
951 fm.prog.total = 0;
952 reload();
953 if (!fm.marks.nentries)
954 message(GREEN, "%s all marked entries.", msg_done);
955 else
956 message(RED, "Some errors occured while %s.", msg_doing);
957 RV_ALERT();
960 static void
961 update_progress(off_t delta)
963 int percent;
965 if (!fm.prog.total)
966 return;
967 fm.prog.partial += delta;
968 percent = (int)(fm.prog.partial * 100 / fm.prog.total);
969 message(CYAN, "%s...%d%%", fm.prog.msg, percent);
970 refresh();
973 /* Wrappers for file operations. */
974 static int
975 delfile(const char *path)
977 int ret;
978 struct stat st;
980 ret = lstat(path, &st);
981 if (ret < 0)
982 return ret;
983 update_progress(st.st_size);
984 return unlink(path);
987 static int
988 addfile(const char *path)
990 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
991 int ret;
993 ret = creat(path, 0644);
994 if (ret < 0)
995 return ret;
996 return close(ret);
999 static int
1000 cpyfile(const char *srcpath)
1002 int src, dst, ret;
1003 size_t size;
1004 struct stat st;
1005 char buf[BUFSIZ];
1006 char dstpath[PATH_MAX];
1008 strcpy(dstpath, CWD);
1009 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
1010 ret = lstat(srcpath, &st);
1011 if (ret < 0)
1012 return ret;
1013 if (S_ISLNK(st.st_mode)) {
1014 ret = readlink(srcpath, BUF1, BUFLEN - 1);
1015 if (ret < 0)
1016 return ret;
1017 BUF1[ret] = '\0';
1018 ret = symlink(BUF1, dstpath);
1019 } else {
1020 ret = src = open(srcpath, O_RDONLY);
1021 if (ret < 0)
1022 return ret;
1023 ret = dst = creat(dstpath, st.st_mode);
1024 if (ret < 0)
1025 return ret;
1026 while ((size = read(src, buf, BUFSIZ)) > 0) {
1027 write(dst, buf, size);
1028 update_progress(size);
1029 sync_signals();
1031 close(src);
1032 close(dst);
1033 ret = 0;
1035 return ret;
1038 static int
1039 adddir(const char *path)
1041 int ret;
1042 struct stat st;
1044 ret = stat(CWD, &st);
1045 if (ret < 0)
1046 return ret;
1047 return mkdir(path, st.st_mode);
1050 static int
1051 movfile(const char *srcpath)
1053 int ret;
1054 struct stat st;
1055 char dstpath[PATH_MAX];
1057 strcpy(dstpath, CWD);
1058 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
1059 ret = rename(srcpath, dstpath);
1060 if (ret == 0) {
1061 ret = lstat(dstpath, &st);
1062 if (ret < 0)
1063 return ret;
1064 update_progress(st.st_size);
1065 } else if (errno == EXDEV) {
1066 ret = cpyfile(srcpath);
1067 if (ret < 0)
1068 return ret;
1069 ret = unlink(srcpath);
1071 return ret;
1074 static void
1075 start_line_edit(const char *init_input)
1077 curs_set(TRUE);
1078 strncpy(INPUT, init_input, BUFLEN);
1079 fm.edit.left = mbstowcs(fm.edit.buffer, init_input, BUFLEN);
1080 fm.edit.right = BUFLEN - 1;
1081 fm.edit.buffer[BUFLEN] = L'\0';
1082 fm.edit_scroll = 0;
1085 /* Read input and change editing state accordingly. */
1086 static enum editstate
1087 get_line_edit()
1089 wchar_t eraser, killer, wch;
1090 int ret, length;
1092 ret = fm_get_wch((wint_t *)&wch);
1093 erasewchar(&eraser);
1094 killwchar(&killer);
1095 if (ret == KEY_CODE_YES) {
1096 if (wch == KEY_ENTER) {
1097 curs_set(FALSE);
1098 return CONFIRM;
1099 } else if (wch == KEY_LEFT) {
1100 if (EDIT_CAN_LEFT(fm.edit))
1101 EDIT_LEFT(fm.edit);
1102 } else if (wch == KEY_RIGHT) {
1103 if (EDIT_CAN_RIGHT(fm.edit))
1104 EDIT_RIGHT(fm.edit);
1105 } else if (wch == KEY_UP) {
1106 while (EDIT_CAN_LEFT(fm.edit))
1107 EDIT_LEFT(fm.edit);
1108 } else if (wch == KEY_DOWN) {
1109 while (EDIT_CAN_RIGHT(fm.edit))
1110 EDIT_RIGHT(fm.edit);
1111 } else if (wch == KEY_BACKSPACE) {
1112 if (EDIT_CAN_LEFT(fm.edit))
1113 EDIT_BACKSPACE(fm.edit);
1114 } else if (wch == KEY_DC) {
1115 if (EDIT_CAN_RIGHT(fm.edit))
1116 EDIT_DELETE(fm.edit);
1118 } else {
1119 if (wch == L'\r' || wch == L'\n') {
1120 curs_set(FALSE);
1121 return CONFIRM;
1122 } else if (wch == L'\t') {
1123 curs_set(FALSE);
1124 return CANCEL;
1125 } else if (wch == eraser) {
1126 if (EDIT_CAN_LEFT(fm.edit))
1127 EDIT_BACKSPACE(fm.edit);
1128 } else if (wch == killer) {
1129 EDIT_CLEAR(fm.edit);
1130 clear_message();
1131 } else if (iswprint(wch)) {
1132 if (!EDIT_FULL(fm.edit))
1133 EDIT_INSERT(fm.edit, wch);
1136 /* Encode edit contents in INPUT. */
1137 fm.edit.buffer[fm.edit.left] = L'\0';
1138 length = wcstombs(INPUT, fm.edit.buffer, BUFLEN);
1139 wcstombs(&INPUT[length], &fm.edit.buffer[fm.edit.right + 1],
1140 BUFLEN - length);
1141 return CONTINUE;
1144 /* Update line input on the screen. */
1145 static void
1146 update_input(const char *prompt, enum color c)
1148 int plen, ilen, maxlen;
1150 plen = strlen(prompt);
1151 ilen = mbstowcs(NULL, INPUT, 0);
1152 maxlen = STATUSPOS - plen - 2;
1153 if (ilen - fm.edit_scroll < maxlen)
1154 fm.edit_scroll = MAX(ilen - maxlen, 0);
1155 else if (fm.edit.left > fm.edit_scroll + maxlen - 1)
1156 fm.edit_scroll = fm.edit.left - maxlen;
1157 else if (fm.edit.left < fm.edit_scroll)
1158 fm.edit_scroll = MAX(fm.edit.left - maxlen, 0);
1159 color_set(RVC_PROMPT, NULL);
1160 mvaddstr(LINES - 1, 0, prompt);
1161 color_set(c, NULL);
1162 mbstowcs(WBUF, INPUT, COLS);
1163 mvaddnwstr(LINES - 1, plen, &WBUF[fm.edit_scroll], maxlen);
1164 mvaddch(LINES - 1, plen + MIN(ilen - fm.edit_scroll, maxlen + 1),
1165 ' ');
1166 color_set(DEFAULT, NULL);
1167 if (fm.edit_scroll)
1168 mvaddch(LINES - 1, plen - 1, '<');
1169 if (ilen > fm.edit_scroll + maxlen)
1170 mvaddch(LINES - 1, plen + maxlen, '>');
1171 move(LINES - 1, plen + fm.edit.left - fm.edit_scroll);
1174 static void
1175 cmd_down(void)
1177 if (fm.nfiles)
1178 ESEL = MIN(ESEL + 1, fm.nfiles - 1);
1181 static void
1182 cmd_up(void)
1184 if (fm.nfiles)
1185 ESEL = MAX(ESEL - 1, 0);
1188 static void
1189 cmd_scroll_down(void)
1191 if (!fm.nfiles)
1192 return;
1193 ESEL = MIN(ESEL + HEIGHT, fm.nfiles - 1);
1194 if (fm.nfiles > HEIGHT)
1195 SCROLL = MIN(SCROLL + HEIGHT, fm.nfiles - HEIGHT);
1198 static void
1199 cmd_scroll_up(void)
1201 if (!fm.nfiles)
1202 return;
1203 ESEL = MAX(ESEL - HEIGHT, 0);
1204 SCROLL = MAX(SCROLL - HEIGHT, 0);
1207 static void
1208 cmd_man(void)
1210 spawn("man", "fm", NULL);
1213 static void
1214 cmd_jump_top(void)
1216 if (fm.nfiles)
1217 ESEL = 0;
1220 static void
1221 cmd_jump_bottom(void)
1223 if (fm.nfiles)
1224 ESEL = fm.nfiles - 1;
1227 static void
1228 cmd_cd_down(void)
1230 if (!fm.nfiles || !S_ISDIR(EMODE(ESEL)))
1231 return;
1232 if (chdir(ENAME(ESEL)) == -1) {
1233 message(RED, "cd: %s: %s", ENAME(ESEL), strerror(errno));
1234 return;
1236 strlcat(CWD, ENAME(ESEL), sizeof(CWD));
1237 cd(1);
1240 static void
1241 cmd_cd_up(void)
1243 char *dirname, first;
1245 if (!strcmp(CWD, "/"))
1246 return;
1248 /* dirname(3) basically */
1249 dirname = strrchr(CWD, '/');
1250 *dirname-- = '\0';
1251 dirname = strrchr(CWD, '/') + 1;
1253 first = dirname[0];
1254 dirname[0] = '\0';
1255 cd(1);
1256 dirname[0] = first;
1257 strlcat(dirname, "/", sizeof(dirname));
1258 try_to_sel(dirname);
1259 dirname[0] = '\0';
1260 if (fm.nfiles > HEIGHT)
1261 SCROLL = ESEL - HEIGHT / 2;
1264 static void
1265 cmd_home(void)
1267 const char *home;
1269 if ((home = getenv("HOME")) == NULL) {
1270 message(RED, "HOME is not defined!");
1271 return;
1274 strlcpy(CWD, home, sizeof(CWD));
1275 if (*CWD != '\0' && CWD[strlen(CWD) - 1] != '/')
1276 strlcat(CWD, "/", sizeof(CWD));
1277 cd(1);
1280 static void
1281 cmd_copy_path(void)
1283 const char *path;
1284 FILE *f;
1286 if ((path = getenv("CLIP")) == NULL ||
1287 (f = fopen(path, "w")) == NULL) {
1288 /* use internal clipboard */
1289 strlcpy(clipboard, CWD, sizeof(clipboard));
1290 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1291 return;
1294 fprintf(f, "%s%s", CWD, ENAME(ESEL));
1295 fputc('\0', f);
1296 fclose(f);
1299 static void
1300 cmd_paste_path(void)
1302 ssize_t r;
1303 const char *path;
1304 char *nl;
1305 FILE *f;
1306 char p[PATH_MAX];
1308 if ((path = getenv("CLIP")) != NULL &&
1309 (f = fopen(path, "w")) != NULL) {
1310 r = fread(clipboard, 1, sizeof(clipboard)-1, f);
1311 fclose(f);
1312 if (r == -1 || r == 0)
1313 goto err;
1314 if ((nl = memmem(clipboard, r, "", 1)) == NULL)
1315 goto err;
1318 strlcpy(p, clipboard, sizeof(p));
1319 strlcpy(CWD, clipboard, sizeof(CWD));
1320 if ((nl = strrchr(CWD, '/')) != NULL) {
1321 *nl = '\0';
1322 nl = strrchr(p, '/');
1323 assert(nl != NULL);
1325 if (strcmp(CWD, "/") != 0)
1326 strlcat(CWD, "/", sizeof(CWD));
1327 cd(1);
1328 try_to_sel(nl+1);
1329 return;
1331 err:
1332 memset(clipboard, 0, sizeof(clipboard));
1335 static void
1336 cmd_reload(void)
1338 reload();
1341 static void
1342 cmd_shell(void)
1344 const char *shell;
1346 if ((shell = getenv("SHELL")) == NULL)
1347 shell = FM_SHELL;
1348 spawn(shell, NULL);
1351 static void
1352 cmd_view(void)
1354 const char *pager;
1356 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1357 return;
1359 if ((pager = getenv("PAGER")) == NULL)
1360 pager = FM_PAGER;
1361 spawn(pager, ENAME(ESEL), NULL);
1364 static void
1365 cmd_edit(void)
1367 const char *editor;
1369 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1370 return;
1372 if ((editor = getenv("VISUAL")) == NULL ||
1373 (editor = getenv("EDITOR")) == NULL)
1374 editor = FM_ED;
1376 spawn(editor, ENAME(ESEL), NULL);
1379 static void
1380 cmd_open(void)
1382 const char *opener;
1384 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1385 return;
1387 if ((opener = getenv("OPENER")) == NULL)
1388 opener = FM_OPENER;
1390 spawn(opener, ENAME(ESEL), NULL);
1393 static void
1394 cmd_mark(void)
1396 if (MARKED(ESEL))
1397 del_mark(&fm.marks, ENAME(ESEL));
1398 else
1399 add_mark(&fm.marks, CWD, ENAME(ESEL));
1401 MARKED(ESEL) = !MARKED(ESEL);
1402 ESEL = (ESEL + 1) % fm.nfiles;
1405 static void
1406 cmd_toggle_mark(void)
1408 int i;
1410 for (i = 0; i < fm.nfiles; ++i) {
1411 if (MARKED(i))
1412 del_mark(&fm.marks, ENAME(i));
1413 else
1414 add_mark(&fm.marks, CWD, ENAME(ESEL));
1415 MARKED(i) = !MARKED(i);
1419 static void
1420 cmd_mark_all(void)
1422 int i;
1424 for (i = 0; i < fm.nfiles; ++i)
1425 if (!MARKED(i)) {
1426 add_mark(&fm.marks, CWD, ENAME(ESEL));
1427 MARKED(i) = 1;
1431 static void
1432 loop(void)
1434 int meta, ch, c;
1435 struct binding {
1436 int ch;
1437 #define K_META 1
1438 #define K_CTRL 2
1439 int chflags;
1440 void (*fn)(void);
1441 #define X_UPDV 1
1442 #define X_QUIT 2
1443 int flags;
1444 } bindings[] = {
1445 {'<', K_META, cmd_jump_top, X_UPDV},
1446 {'>', K_META, cmd_jump_bottom, X_UPDV},
1447 {'?', 0, cmd_man, 0},
1448 {'G', 0, cmd_jump_bottom, X_UPDV},
1449 {'H', 0, cmd_home, X_UPDV},
1450 {'J', 0, cmd_scroll_down, X_UPDV},
1451 {'K', 0, cmd_scroll_up, X_UPDV},
1452 {'M', 0, cmd_mark_all, X_UPDV},
1453 {'P', 0, cmd_paste_path, X_UPDV},
1454 {'V', K_CTRL, cmd_scroll_down, X_UPDV},
1455 {'Y', 0, cmd_copy_path, X_UPDV},
1456 {'^', 0, cmd_cd_up, X_UPDV},
1457 {'b', 0, cmd_cd_up, X_UPDV},
1458 {'e', 0, cmd_edit, X_UPDV},
1459 {'f', 0, cmd_cd_down, X_UPDV},
1460 {'g', 0, cmd_jump_top, X_UPDV},
1461 {'g', K_CTRL, NULL, X_UPDV},
1462 {'h', 0, cmd_cd_up, X_UPDV},
1463 {'j', 0, cmd_down, X_UPDV},
1464 {'k', 0, cmd_up, X_UPDV},
1465 {'l', 0, cmd_cd_down, X_UPDV},
1466 {'l', K_CTRL, cmd_reload, X_UPDV},
1467 {'n', 0, cmd_down, X_UPDV},
1468 {'n', K_CTRL, cmd_down, X_UPDV},
1469 {'m', 0, cmd_mark, X_UPDV},
1470 {'m', K_CTRL, cmd_shell, X_UPDV},
1471 {'o', 0, cmd_open, X_UPDV},
1472 {'p', 0, cmd_up, X_UPDV},
1473 {'p', K_CTRL, cmd_up, X_UPDV},
1474 {'q', 0, NULL, X_QUIT},
1475 {'t', 0, cmd_toggle_mark, X_UPDV},
1476 {'v', 0, cmd_view, X_UPDV},
1477 {'v', K_META, cmd_scroll_up, X_UPDV},
1478 {KEY_DOWN, 0, cmd_scroll_down, X_UPDV},
1479 {KEY_NPAGE, 0, cmd_scroll_down, X_UPDV},
1480 {KEY_PPAGE, 0, cmd_scroll_up, X_UPDV},
1481 {KEY_RESIZE, 0, NULL, X_UPDV},
1482 {KEY_RESIZE, K_META, NULL, X_UPDV},
1483 {KEY_UP, 0, cmd_scroll_up, X_UPDV},
1484 }, *b;
1485 size_t i;
1487 for (;;) {
1488 again:
1489 meta = 0;
1490 ch = fm_getch();
1491 if (ch == '\e') {
1492 meta = 1;
1493 if ((ch = fm_getch()) == '\e') {
1494 meta = 0;
1495 ch = '\e';
1499 clear_message();
1501 for (i = 0; i < nitems(bindings); ++i) {
1502 b = &bindings[i];
1503 c = b->ch;
1504 if (b->chflags & K_CTRL)
1505 c = CTRL(c);
1506 if ((!meta && b->chflags & K_META) || ch != c)
1507 continue;
1509 if (b->flags & X_QUIT)
1510 return;
1511 if (b->fn != NULL)
1512 b->fn();
1513 if (b->flags & X_UPDV)
1514 update_view();
1516 goto again;
1519 message(RED, "%s%s is undefined",
1520 meta ? "M-": "", keyname(ch));
1521 refresh();
1525 int
1526 main(int argc, char *argv[])
1528 int i, ch;
1529 char *entry;
1530 DIR *d;
1531 FILE *save_cwd_file = NULL;
1532 FILE *save_marks_file = NULL;
1534 while ((ch = getopt_long(argc, argv, "d:hm:v", opts, NULL)) != -1) {
1535 switch (ch) {
1536 case 'd':
1537 if ((save_cwd_file = fopen(optarg, "w")) == NULL)
1538 err(1, "open %s", optarg);
1539 break;
1540 case 'h':
1541 printf(""
1542 "Usage: fm [-hv] [-d file] [-m file] [dirs...]\n"
1543 "Browse current directory or the ones specified.\n"
1544 "\n"
1545 "See fm(1) for more information.\n"
1546 "fm homepage <https://github.com/omar-polo/fm>\n");
1547 return 0;
1548 case 'm':
1549 if ((save_marks_file = fopen(optarg, "a")) == NULL)
1550 err(1, "open %s", optarg);
1551 break;
1552 case 'v':
1553 printf("version: fm %s\n", RV_VERSION);
1554 return 0;
1558 if (pledge("stdio rpath wpath cpath tty proc exec", NULL) == -1)
1559 err(1, "pledge");
1561 get_user_programs();
1562 init_term();
1563 fm.nfiles = 0;
1564 for (i = 0; i < 10; i++) {
1565 fm.tabs[i].esel = fm.tabs[i].scroll = 0;
1566 fm.tabs[i].flags = RV_FLAGS;
1568 strcpy(fm.tabs[0].cwd, getenv("HOME"));
1569 for (i = 1; i < argc && i < 10; i++) {
1570 if ((d = opendir(argv[i]))) {
1571 realpath(argv[i], fm.tabs[i].cwd);
1572 closedir(d);
1573 } else
1574 strcpy(fm.tabs[i].cwd, fm.tabs[0].cwd);
1576 getcwd(fm.tabs[i].cwd, PATH_MAX);
1577 for (i++; i < 10; i++)
1578 strcpy(fm.tabs[i].cwd, fm.tabs[i - 1].cwd);
1579 for (i = 0; i < 10; i++)
1580 if (fm.tabs[i].cwd[strlen(fm.tabs[i].cwd) - 1] != '/')
1581 strcat(fm.tabs[i].cwd, "/");
1582 fm.tab = 1;
1583 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
1584 init_marks(&fm.marks);
1585 cd(1);
1586 strlcpy(clipboard, CWD, sizeof(clipboard));
1587 if (fm.nfiles > 0)
1588 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1590 loop();
1592 if (fm.nfiles)
1593 free_rows(&fm.rows, fm.nfiles);
1594 delwin(fm.window);
1595 if (save_cwd_file != NULL) {
1596 fputs(CWD, save_cwd_file);
1597 fclose(save_cwd_file);
1599 if (save_marks_file != NULL) {
1600 for (i = 0; i < fm.marks.bulk; i++) {
1601 entry = fm.marks.entries[i];
1602 if (entry)
1603 fprintf(save_marks_file, "%s%s\n",
1604 fm.marks.dirpath, entry);
1606 fclose(save_marks_file);
1608 free_marks(&fm.marks);
1609 return 0;