nvim 直接打开当前光标下的文件

警告
本文最后更新于 2024-03-18,文中内容可能已过时。

nvim 可以利用跳转功能,直接在当前光标下打开文件。如果该文件不存在,则新建一个。

我配置的快捷键是 gf(go file)。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
vim.cmd([[
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
            echohl WarningMsg | echo 'Created New File: ' . expanded_filename | echohl None
            execute 'edit ' . expanded_filename
        endif
    else
        " File exists, perform normal gf behavior
        echohl ModeMsg | echo 'Open File: ' . expanded_filename | echohl None
        execute 'normal! gf'
    endif
endfunction
]])

相关内容

william 支付宝支付宝
william 微信微信
0%