gpt4 book ai didi

bash - 在 vim 中打开某些文件类型之前如何发出警告?

转载 作者:行者123 更新时间:2023-11-29 09:26:57 24 4
gpt4 key购买 nike

依赖命令行自动完成时,很容易不小心用 vim 打开一个大的二进制文件或数据文件。

是否可以在 vim 中打开某些文件类型时添加交互式警告?

例如,我想在打开没有扩展名的文件时添加警告:

> vim someBinary
Edit someBinary? [y/N]

或者也许:

> vim someBinary
# vim buffer opens and displays warning about filetype,
# giving user a chance to quit before loading the file

这可以应用于一系列扩展,例如 .pdf.so.o.a ,没有扩展等

preventing vim from opening binary files 上有一个相关问题, 但它主要是关于修改自动完成以防止首先意外打开文件。

最佳答案

下面是我想出的解决方案,使用 vim 自动命令和 BufReadCmd 事件。它有很多 vimscript,但它非常健壮。如果打开的文件是非 ascii 文件或具有列入黑名单的扩展名(本例中为 .csv.tsv),它会发出警告:

augroup bigfiles
" Clear the bigfiles group in case defined elsewhere
autocmd!
" Set autocommand to run before reading buffer
autocmd BufReadCmd * silent call PromptFileEdit()
augroup end



" Prompt user input if editing an existing file before reading
function! PromptFileEdit()
" Current file
let file = expand("%")
" Whether or not we should continue to open the file
let continue = 1

" Skip if file has an extension or is not readable
if filereadable(file) && (IsNonAsciiFile(file) || IsBlacklistedFile())
" Get response from user
let response = input('Are you sure you want to open "' . file . '"? [y/n]')

" Bail if response is a 'n' or contains a 'q'
if response ==? "n" || response =~ "q"
let continue = 0
if (winnr("$") == 1)
" Quit if it was the only buffer open
quit
else
" Close buffer if other buffers open
bdelete
endif
endif
endif

if continue == 1
" Edit the file
execute "e" file
" Run the remaining autocommands for the file
execute "doautocmd BufReadPost" file
endif

endfunction

" Return 1 if file is a non-ascii file, otherwise 0
function! IsNonAsciiFile(file)
let ret = 1
let fileResult = system('file ' . a:file)
" Check if file contains ascii or is empty
if fileResult =~ "ASCII" || fileResult =~ "empty" || fileResult =~ "UTF"
let ret = 0
endif
return ret
endfunction

" Return 1 if file is blacklisted, otherwise 0
function! IsBlacklistedFile()
let ret = 0
let extension = expand('%:e')

" List contains ASCII files that we don't want to open by accident
let blacklistExtensions = ['csv', 'tsv']

" Check if we even have an extension
if strlen(extension) == 0
let ret = 0
" Check if our extension is in the blacklisted extensions
elseif index(blacklistExtensions, extension) >= 0
let ret = 1
endif

return ret
endfunction

要在启用语法高亮的情况下阅读,请参阅 gist .

也许不是特别优雅,但我很享受学习 vimscript 的过程。

我对 vimscript 不太熟悉,所以我确信还有改进的余地——欢迎提出建议和替代解决方案。

注意:由于调用 file,预计这不会在 WSL 或 Cygwin 之外的 Windows 系统上运行。

关于bash - 在 vim 中打开某些文件类型之前如何发出警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57673814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com