demental
demental

Reputation: 1484

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?

Upvotes: 25

Views: 6433

Answers (3)

ZK_
ZK_

Reputation: 564

nnoremap <silent> gf :call JumpOrCreateFile()<CR>


function! JumpOrCreateFile()
 " Get the filename under the cursor
 let filename = expand("<cfile>")

 " Expand the tilde in the file path
 let expanded_filename = expand(filename)

 " Check if the file path starts with "./"
 if expanded_filename =~# '^\.\/'
   " Get the current directory of the editing file
   let current_directory = expand('%:p:h')

   " Create the full path by appending the relative file path
   let expanded_filename = current_directory . '/' . expanded_filename
 endif

 " Check if the file exists
 if !filereadable(expanded_filename)
   " Prompt the user for file creation with the full path
   let choice = confirm('File does not exist. Create "' . expanded_filename . '"?', "&Yes\n&No", 1)

   " Handle the user's choice
   if choice == 1
     " Create the file and open it
     execute 'edit ' . expanded_filename
   endif
 else
   " File exists, perform normal gf behavior
   execute 'normal! gf'
 endif
endfunction

Upvotes: 2

alnavegante
alnavegante

Reputation: 21

gf -> opens the file in a new tab

cf -> creates the file (if it doesn't exist) and opens it in new tab

nnoremap gf <C-W>gf 
noremap <leader>cf :call CreateFile(expand("<cfile>"))<CR>
function! CreateFile(tfilename)

    " complete filepath from the file where this is called
    let newfilepath=expand('%:p:h') .'/'. expand(a:tfilename)

    if filereadable(newfilepath)
       echo "File already exists"
       :norm gf
    else
        :execute "!touch ". expand(newfilepath)
        echom "File created: ". expand(newfilepath)
        :norm gf
    endif

endfunction

Upvotes: 2

ib.
ib.

Reputation: 29014

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”.

Upvotes: 25

Related Questions