Skip to content

Commit da85a1b

Browse files
committed
Use relative path for find-file-relative
If the parent dir is relative to cwd, use a relative path when finding a relative file.
1 parent fa991d1 commit da85a1b

1 file changed

Lines changed: 22 additions & 24 deletions

File tree

src/main/cmds.c

Lines changed: 22 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -636,16 +636,13 @@ int32_t find_file_relative(struct command_ctx ctx, int argc,
636636
const char *path =
637637
b->associated_path != NULL ? b->associated_path : b->filename;
638638

639-
char *filename = strdup(path);
640-
char *dir = filename;
641-
642-
// if we used the filename, get the directory of the file,
643-
// not the file itself
644-
if (b->associated_path == NULL) {
645-
dir = dirname(filename);
639+
struct s8 dir = s8new(path, strlen(path));
640+
if (!is_dir(dir)) {
641+
struct s8 file = dir;
642+
dir = parent(file);
643+
s8delete(file);
646644
}
647645

648-
size_t dirlen = strlen(dir);
649646
if (argc == 0) {
650647
minibuffer_clear();
651648
struct completion_provider providers[] = {
@@ -654,29 +651,30 @@ int32_t find_file_relative(struct command_ctx ctx, int argc,
654651

655652
ctx.self = &find_file_command;
656653

657-
char *dir_with_slash = (char *)malloc(dirlen + 2);
658-
memcpy(dir_with_slash, dir, dirlen);
659-
dir_with_slash[dirlen] = '/';
660-
dir_with_slash[dirlen + 1] = '\0';
661-
minibuffer_prompt_initial(ctx, dir_with_slash, "find file: ");
662-
free(filename);
663-
free(dir_with_slash);
654+
struct s8 cwd = working_dir();
655+
struct s8 reldir = relative_to(dir, cwd);
656+
s8delete(dir);
657+
s8delete(cwd);
658+
659+
struct s8 dir_with_slash = s8from_fmt("%s/", s8ascstr(reldir));
660+
minibuffer_prompt_initial(ctx, s8ascstr(dir_with_slash), "find file: ");
661+
662+
s8delete(reldir);
663+
s8delete(dir_with_slash);
664664

665665
complete(minibuffer_buffer(), buffer_end(minibuffer_buffer()));
666666

667667
return 0;
668668
}
669669

670+
// this is called when invoking `find-file-relative` with
671+
// an argument.
670672
disable_completion(minibuffer_buffer());
671-
size_t plen = strlen(argv[0]);
672-
char *pth = (char *)malloc(dirlen + plen + 2);
673-
memcpy(pth, dir, dirlen);
674-
pth[dirlen] = '/';
675-
memcpy(pth + dirlen + 1, argv[0], plen);
676-
pth[dirlen + plen + 1] = '\0';
677-
open_file(ctx, pth);
678-
679-
free(filename);
673+
struct s8 arg = s8(argv[0]);
674+
struct s8 pth = join_path(dir, arg);
675+
open_file(ctx, s8ascstr(pth));
676+
677+
s8delete(pth);
680678
return 0;
681679
}
682680

0 commit comments

Comments
 (0)