注意
本文最后更新于 2024-06-26,文中内容可能已过时。
有时我们需要临时配置或者修改文件,一般的做法是进入 visual
模式然后使用命令 gf
打开当前文件。这样的做法其实有点冗余,特别是当我们在线上排查问题时,希望能快速打开光标下的文件。
为此,我们可以定义一个函数,然后绑定快捷键即可迅速打开文件了
-
定义一个函数 JumpOrCreateFile
- 可以自动识别文件路径
- 如果文件不存在,则提醒我们是否需要创建
-
绑定快捷键 gf
方便操作
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
36
37
38
39
40
41
42
43
44
45
46
|
vim.cmd([[
nnoremap <silent> gf :call JumpOrCreateFile()<CR>
function! JumpOrCreateFile()
" Get the filename under the cursor
let filename = expand("<cfile>")
"--------------------------------------------------------------------------
" split to get filename path
if filename =~# ':'
let expanded_filename = expand(split(filename, ":")[1])
elseif filename =~# ','
let expanded_filename = expand(split(filename, ",")[1])
elseif filename =~# '='
let expanded_filename = expand(split(filename, "=")[1])
else
let expanded_filename = expand(filename)
endif
"--------------------------------------------------------------------------
" 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'
execute 'edit ' . expanded_filename
endif
endfunction
]])
|