1

For some reason, some times the command expand("%") gives me a full path of a file rather than the relative path as expected. If I check the pwd it says I'm on the project folder. However, going to NvimTree, navigating to the root of the folder and executing the CD mapping makes this problem go away.

Can this be related to my session loading plugin? How can I debug it?

2
  • 1
    Why do you expect expand("%") to give you a relative path?
    – romainl
    Commented Jan 14, 2023 at 9:30
  • because that is what it usually gives you unless you couple it with path modifiers
    – Danielo515
    Commented Jan 14, 2023 at 17:56

1 Answer 1

3

Out of the box, % gives you a downward-relative path:

  • if the file is relative to the working directory,
  • and if it was edited with a downward-relative path.

So expecting expand('%') to always return a downward-relative path is a bit unreasonable.

Example:

$ cd /path/to/project
$ vim
:edit README.md
:echo expand('%')
README.md
:edit /path/to/project/CONTRIBUTING.md
:echo expand('%')
/path/to/project/CONTRIBUTING.md
:edit ../project/LICENSE
:echo expand('%')
../project/LICENSE

But, supposing that you never knowingly edit a file with an absolute or upward-relative path, who knows what your navigation habits and/or your plugins do to them under the hood?

To always get a downward-relative path for files located under the working directory, no matter how you edited them, you would have to be more defensive:

expand('%:.')

See :help filename-modifiers.

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.