A Closer Look At :e With Path Doesn't Expand
Fixing Vim's File Expansion Issue: :e with Path
Understanding the Problem
When using the :e command in Vim to edit a file with a path, you might face an issue where the path isn't expanded correctly. This can lead to unexpected behavior when trying to save the file. Let's dive into this problem and find a solution.
The Issue in Detail
Consider you're in the directory dir/a and you want to edit a file located at ../b/file.txt. When you use the command :e ../b/file.txt, Vim opens the file as expected. However, when you try to save the file, Vim includes the full path in the filename, saving it as dir/a/../b/file.txt in the current working directory instead of the actual file location.
Why This Happens
Vim doesn't interpret the path relative to the current working directory like a shell does. Instead, it takes the path literally, which leads to this unexpected behavior.
The Solution
To fix this, you can use the :cd command to change Vim's current directory to the location of the file before editing it. Here's how you can do it:
:cd %:h
:e %
The :cd %:h command changes the current directory to the head (directory) of the current filename. The :e % command then edits the current file.
Integrating with the Shell
To integrate this process with the shell, you can create a mapping or a function in your .vimrc file. Here's an example of a function:
function EditWithPath()
let file = expand('<afile>')
let dir = fnamemodify(file, ':h')
execute 'cd' A:dir
edit A:file
endfunction
nnoremap <leader>e :call EditWithPath()<CR>
Now, you can use the leader key (by default, ") followed by e` to edit a file with its path correctly.
Conclusion
Understanding Vim's file expansion behavior is crucial to work around its limitations. By using the :cd command or creating a custom function, you can edit files with paths seamlessly in Vim.