Sacchan
Sacchan

Reputation: 377

Use the current directory in Vim commands

For my Haskell programs, I know that the executable's name in the path is the same as my current directory's name. Now I want to create a mapping like so:

:map <leader>rr :!curdir()<cr>

However, the only command I know of is getcwd(), which gives me the whole path instead of just the directory's name.

Is there an easy way to extract only the directory's name?

Upvotes: 8

Views: 4377

Answers (2)

ZyX
ZyX

Reputation: 53604

Use

fnamemodify(getcwd(), ':t')

or

fnamemodify('.', ':p:h:t')

. :h in the second case is necessary because :p emits trailing path separator (thus last path component selected by :t is now empty string).

To move this into your mapping use

:noremap \rr :!<C-r>=shellescape(fnamemodify('.', ':p:h:t'), 1)<CR><CR>

. For the description of why you should not ever use :map see here.

Upvotes: 14

taro
taro

Reputation: 5832

You could use something like:

split(getcwd(), "/")[-1]

Upvotes: 0

Related Questions