# Read file from vimscript variable

I can run this snippit of code within a vimscript block:

0read /home/user/.vim/bundle/vim-lorum/lorums/lorum.js


As expected, it puts the contents of "lorum.js" into the current buffer

But, I need to make this a little more dynamic. If I try something like:

let g:filePath="/home/user/.vim/bundle/vim-lorum/lorums/lorum.js"


I get this error message:

E484: Can't open file g:filePath


I tried wrapping g:filePath in expand and glob but I get similar errors. Any ideas?

This is because vim does not evaluate variable names or functions with most commands. In your case, vim thinks you literally want to read the contents of a file called g:filePath into the buffer. What you want can be accomplished with the :execute command. This command takes a string as an argument, and will then run that string as a command. In your case, this is how it would look:

:let g:filePath="/home/user/.vim/bundle/vim-lorum/lorums/lorum.js"


The fnameescape part is just to ensure that all special characters are escaped properly (see :help fnameescape()). For more on how to use :execute, read :help :execute. Also note that . is vim's string concatenation operator.

• Perhaps add a space after 0read? Also wrap g:filePath in a fnameescape()? – Sato Katsura Jul 21 '15 at 17:04

The solution to this type of problem is the :execute command:

:execute '0read' g:filepath


See

:help :execute


Commands like read don't evaluate your variables, it takes the argument to be a literal (a file named g:filePath). The execute command, however, takes string arguments, concatenates them and executes the result as if it were a command invocation. You can therefore 'wrap' your command: turn the read command into a string and pass is together with the variable as arguments to execute.

:exe "0read" g:filePath

• I wonder what is the 0 in 0read, the particularities. – Sergio Abreu Jan 6 '17 at 23:57
• @SergioAbreu read inserts below the cursor, {range}read inserts below the specified line. Using 0 as the {range} inserts at the top of the buffer. – jjaderberg Jan 9 '17 at 12:23
• And \$read to the end :) I got it. Thanks. – Sergio Abreu Jan 9 '17 at 22:12