Tony S Yu
Tony S Yu

Reputation: 3183

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 described 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?)

Upvotes: 20

Views: 6490

Answers (3)

ZyX
ZyX

Reputation: 53674

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 =pathname will make 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).

Upvotes: 31

Luc Hermitte
Luc Hermitte

Reputation: 32966

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.

Upvotes: 0

DrAl
DrAl

Reputation: 72726

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

Upvotes: 6

Related Questions