Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim: `cd` to path stored in variable

Tags:

vim

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

like image 476
Tony S Yu Avatar asked Jan 04 '11 18:01

Tony S Yu


2 Answers

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).

like image 161
ZyX Avatar answered Nov 11 '22 12:11

ZyX


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
like image 6
DrAl Avatar answered Nov 11 '22 10:11

DrAl