Search code examples
vim

How to create and open for editing a nonexistent file whose path is under the cursor in Vim?


I’m trying Vim for the first couple of hours with Ruby on Rails, and I’m loving it so far.

Specifically, the gf command is great, but I miss something: If the file under the cursor does not exist yet, gf returns an error.

Is there a command to actually create and open the file if it does not exist? Or, what is the most straightforward way to create it?


Solution

  • One can define a custom variant of the gf command that opens a new buffer if the file under the cursor does not exist:

    :noremap <leader>gf :e <cfile><cr>
    

    where the :e command could be replaced with :tabe (to open the buffer for the new file in a separate tab) or another file-opening command.

    It is also possible to just create a file with the name under the cursor without opening it; see my answer to a similar question “Create a file under the cursor in Vim”.