Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Vim, how can I save a file to a path stored in a variable?

Tags:

vim

This is inside a script:

:let s:submission_path = expand("%:p:h") . '\submissions\test_submission.csv'
:echo s:submission_path
:write s:submission_path

The script raises an error "can't open file for writing", because I'm on windows and ':' is not a valid filename character. If I name the variable 'submission_path' a file with that name is written (edit: and the contents of the file are as I expect, the contents of the buffer the script is editing).

I don't understand this. The echo command before the write does what I expect it to, output the full path to the file I want to write. But write seems to ignore the variable value and use its name instead? Do I need to dereference it somehow?

like image 942
Stassa Patsantzis Avatar asked Sep 07 '25 07:09

Stassa Patsantzis


2 Answers

vim has very screwy evaluation rules (and you just need to learn them). write does not take an expression it takes a string so s:submission_path is treated literally for write. However echo does evaluate its arguments so s:submission_path is evaluated.

To do what you want you need to use the execute command.

exec 'write' s:submission_path
like image 152
FDinoff Avatar answered Sep 09 '25 16:09

FDinoff


Try this:

:let s:submission_path = expand("%:p:h") . '\submissions\test_submission.csv'
:echo s:submission_path
:execute "write " . s:submission_path

Execute will allow you to compose an ex command with string operations and then execute it.

like image 27
Codie CodeMonkey Avatar answered Sep 09 '25 15:09

Codie CodeMonkey