Mark
Mark

Reputation: 215

Vim script to browse for a directory and retrieve the directory name

I'm attempting to write a plugin to ease my personal workflow. I'd like to be able to configure/reconfigure the plugin to refer to different directories (containing program outputs) - but without changing the vim working directory. In order to do I'd like that whenever I need to point my plugin at a different directory, e.g. by calling the a "reconfigure" function, a convenient interface pops up which allow me to browse through the filesystem and pick the directory using some shortcuts.

My first thought was to use netrw, configured to hide non-directories, but once I'm inside a directory how can I then obtain the current netrw directory path for use in my script? Is there a better way of doing this?

What if I want to pick a file instead of a directory? Is there an easy way to change the Enter key in netrw so that it changes into directories but when the selected item is a file it will call my custom callback function (for example).

Is there a better way of prompting the user for a file directory?

Upvotes: 1

Views: 505

Answers (2)

user21497
user21497

Reputation: 1181

The current netrw directory path is in the variable

b:netrw_curdir

Note that it will track vim's current directory if g:netrw_keepdir is zero.

Upvotes: 0

Ingo Karkat
Ingo Karkat

Reputation: 172758

Without knowing the exact background, I would recommend triggering your Vim script via a custom command, and pass the file / directory as a command argument. If you define the command like this:

:command -nargs=1 -complete=file MyCommand call MyFunction(<q-args>)

you'll get Vim's file / directory (cp. :help :command-complete) completion in the command line for free.


There's :browse built-in, but it only works for file-related commands like :edit or :write; you cannot put the value into a variable.


There's inputdialog(), which allows you to query for any string; unfortunately, without (file-) completion.


It would be possible to hook into plugins like netrw, overriding the plugin's mappings for file selection (e.g. :nnoremap <buffer> <CR> ..., but this will entangle your plugin deeply with it.

Summary

Don't forget, Vim is a text editor, so excessive passing of filenames / directories should not be necessary. Depending on your use case, this might be better handled by an external tool (invoked by Vim).

Upvotes: 3

Related Questions