2

Does anyone know how I can get the directory name of the CWD without the preceding path?

I'm trying to build a titlestring like this one:

{cwd_dirname_without_path}/{file_path_relative_to_cwd}

I think %f would suffice for the second part of the title, but the first part seems tricky.

1
  • Look up :h ::. and the expand() function
    – muru
    Jan 31, 2018 at 10:23

1 Answer 1

13

There are several possibilities:

  • Use an substitute: :echo substitute(getcwd(), '^.*/', '', '') (which basically means, cut off anything from the beginning until the latest /, note this needs to be adjusted on Windows because the \ is path separator there).

  • Using fnamemodify(), something like this should do it: :echo fnamemodify(getcwd(), ':t') (which basically means, return the tail path of the current working directory).

See also the help at :help getcwd() :help fnamemodify() :help getcwd() :help substitute() and :help filename-modifiers

4
  • Works like a charm! Thanks! I have been struggling with this since your answer to my last question :p
    – Rotareti
    Jan 31, 2018 at 10:37
  • @ChristianBrabandt, @Rotareti: I tried to use this solution just now, and it didn't work for me (neither option did). Is it because I'm using NeoVim? I tried both :set titlestring=%{fnamemodify(getcwd(), ':t')} (vim says E518: Unknown option: ':t')}) and :set titlestring=%{substitute(getcwd(), '^.*/', '', '')} (vim says E518: Unknown option: '^.*/',). When I do the echo commands within vim they work perfectly, so clearly the problem is how I am inserting these functions into the title-setting command. Any idea what I am doing wrong here? Oct 30, 2023 at 12:00
  • 1
    are you using this from some modeline? It looks like your vim chokes on the spaces, so you can try to remove those, not sure if this will help. Also, try to debug this starting from vim --clean Oct 30, 2023 at 12:21
  • I am using these commands from within vim (e.g., in Normal mode, I type : and then the rest of the command). I tried it with vim --clean and got the same result. But then I tried :set titlestring=%{substitute(getcwd(),'^.*/','','')} in my full nvim configuration without the spaces and it worked! Thank you Oct 30, 2023 at 12:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.