4

gf runs fine with absolute or relative path.
Is it possible to open a file with variable in the path?

For example, in a tcl file:

...
set FILE_ROOT /user/abc
...   
read_file ${FILE_ROOT}/some/path/abc.txt

How to open ${FILE_ROOT}/some/path/abc.txt inside vim?

3
  • With :exe -- I'm quite sure it has been answered more than once. Commented Mar 21, 2018 at 11:54
  • @LucHermitte You mean manually add g:filepath variable and :exe "0read" g:filePath? Wondering if there is a more easy way.
    – Fisher
    Commented Mar 21, 2018 at 12:03
  • Yep. You can also use backtick+equal depending on your version of vim -- sorry I haven't found how to type it in the comments. Commented Mar 21, 2018 at 12:07

1 Answer 1

1

Overview

  • Vim user Fisher wishes to use gf to open a file path with an embedded variable

Quick Answer (TL;DR)

  • Use :execute and :expand together to run a command with embedded variables
  • (eg) :let @m='/my/file/path/uu137fisher1666889936.txt' | :execute(':edit '. expand(@m))

Detailed Answer

Context

  • Vim version 7.4
  • file editing command gf

Problem

  • Use-case scenario: Developer wishes to use gf to edit a text file in vim

Solution

  • Use :execute and :expand together to run a command with embedded variables
  • (optional) create a vim function that runs the relevant commands and attach a keybinding for a custom-made gf variant

Example

populate a variable or register with the desired path

  • :let @m='/my/file/path/uu137fisher1666889936.txt'

access that variable or register with execute() and expand()

  • :execute(':edit '. expand(@m))

create a special keybinding with custom gf variant

  • :noremap <leader>gf :call My_special_gf_variant()<CR>

Pitfalls

  • the gf command is generally designed to work with literal paths, with some support for wildcard characters
  • the exact use-case of interpolating or expanding variables is not depicted in :help gf for the Vim version referenced in this answer
  • the example in this answer demonstrates how to read from a vim register instead of a vim variable, but the same basic principle applies to both contexts
  • the answer will change depending on what context is responsible for resolving the relevant variable in use
  • for example:
    • is it a MSFT Windows environment variable?
    • is it a BASH shell variable?
    • is it a variable declared in init.vim or some other vimscript file?
    • if declared in vimscript, has the relevant vimscript been included? (eg) :source foobar.vim

See also

  • websearch://uu137fisher1666889936
  • Vim :help expand
  • Vim :help gf
  • Vim :help netrw-gx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.