如何创建并打开一个不存在的文件,其路径在Vim中的光标下?

mrzz3bfm  于 2023-05-29  发布在  其他
关注(0)|答案(3)|浏览(148)

我在Ruby on Rails的前几个小时尝试了Vim,到目前为止我很喜欢它。
具体来说,gf命令很棒,但我错过了一些东西:如果光标下的文件还不存在,gf将返回错误。
如果文件不存在,是否有命令来实际创建并打开该文件?或者,创建它的最简单的方法是什么?

iaqfqrcu

iaqfqrcu1#

可以定义gf命令的自定义变体,如果光标下的文件不存在,则打开新的缓冲区:

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

其中:e命令可以用:tabe(以在单独的选项卡中打开新文件的缓冲区)或另一个文件打开命令替换。
也可以只在光标下创建一个名称为的文件,而不打开它;请看我对类似问题“Create a file under the cursor in Vim”的回答。

rjee0c15

rjee0c152#

gf->在新选项卡中打开文件
cf->创建文件(如果不存在)并在新选项卡中打开

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
ftf50wuq

ftf50wuq3#

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

相关问题