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?

Fisher
  • 1,086
  • 2
  • 13
  • 28

1 Answers1

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
dreftymac
  • 121
  • 5