Vim: `cd` to path stored in variable
I'm pretty new to vim, and I'm having a hard time understanding some subtleties with vim scripting. Specifically, I'm having trouble working with commands that expect an unquoted-string (is there a name for this?). For example
cd some/unquoted/string/path
The problem is that I'd like to pass a variable, but calling
let pathname = 'some/path'
cd pathname
will try to change the current directory to 'pathname' instead of 'some/path'. One way around this is to use
let cmd = 'cd ' . pathname
execute cmd
but this seems a bit roundabout. This StackOverflow question actually uses cd
with a variable, but it doesn't work on my system ("a:path" is treated as the path as describe开发者_StackOverflow社区d above).
I'm using cd
as a specific example, but this behavior isn't unique to cd
; for example, the edit
command also behaves this way. (Is there a name for this type of command?)
TL;DR: use execute 'cd' fnameescape(pathname)
Explanation: Lots of basic commands that take filenames as an argument support backtick syntax:
command `shell command`
or
command `=vim_expression`
so your example may be written as
cd `=pathname`
if you are running this in a controlled environment. You must not use this variant in plugins because a) there is &wildignore
setting that may step in your way: set wildignore=*|cd
will make =pathname
cd
fail regardless of what is stored in the pathname
and b) if pathname contains newlines it will be split into two or more directories. Thus what you should use for any piece of code you intend to share is
execute 'cd' fnameescape(pathname)
Note that you must not use execute "cd" pathname
because it does not care about special characters in pathname (for example, space).
The basic commands in Vim never do any processing of variables (how would it know that you didn't mean to change to the pathname directory instead of the some/path one?). You don't have to be quite as roundabout as you suggested, you can just do:
exe 'cd' pathname
Note that exe
concatenates arguments with a space automatically, so you don't have to do:
exe 'cd ' . pathname
A lot time ago I wrote this plugin (function FixPathName()
in order to solve this kind of issues. Now vim has some new functions like shellescape()
when the path need to be used with external commands.
精彩评论