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
3条答案
按热度按时间iaqfqrcu1#
可以定义
gf
命令的自定义变体,如果光标下的文件不存在,则打开新的缓冲区:其中
:e
命令可以用:tabe
(以在单独的选项卡中打开新文件的缓冲区)或另一个文件打开命令替换。也可以只在光标下创建一个名称为的文件,而不打开它;请看我对类似问题“Create a file under the cursor in Vim”的回答。
rjee0c152#
gf->在新选项卡中打开文件
cf->创建文件(如果不存在)并在新选项卡中打开
ftf50wuq3#