如何修改Linux下的vimrc函数使其适配Windows10 Cygwin环境
Cygwin环境适配Screen下Vim重复打开文件检测函数
失效原因
原函数在Cygwin下无法运行是三个问题导致的:
- Cygwin默认不预装
lsof工具,原命令直接执行失败 - Cygwin的/proc文件系统中进程环境变量存储格式和标准Linux发行版有差异,原命令用
xargs -0 echo拼接环境变量时会丢失WINDOW字段 - 部分场景下Cygwin的路径映射会导致swp文件匹配失效,原逻辑没有兜底查询能力
适配方案
- 先安装依赖:运行Cygwin安装程序
setup-x86_64.exe,搜索并安装lsof包,安装完成后在Cygwin终端执行which lsof,返回/usr/bin/lsof即为安装成功。 - 将.vimrc中原有的
PrintScreenWindow相关配置替换为以下适配版本:
""""""""""""""""""""""""""""""""""""""""""""""""""" " for screen use " opened in another screen? lets not play where's waldo anymore! " this will politely tell me which screen's window it is open in so that I may " go close it if I want, but still provide me the normal options " Cygwin适配版,同时兼容Linux各发行版 augroup NoSimultaneousEdits autocmd! autocmd SwapExists * :call PrintScreenWindow() augroup END function! PrintScreenWindow () let fname = expand("%:p") let fname = fnamemodify(fname, ':t') let fpath = expand("%:p:h") let all = fpath . "/." . fname " 自动识别lsof路径,无需手动配置 let lsof_bin = exepath('lsof') let my_command = lsof_bin . " | grep '" . fname . ".swp' | grep " . $USER . " | sed -n 's/^vim\\? \\+\\([0-9]\\+\\).*$/\\1/p' " let result = substitute(system(my_command), '\n','','') if result " 适配Cygwin的/proc环境变量读取逻辑,用tr替换xargs避免空值 let my_cmd2 = "cat /proc/" . result . "/environ | tr '\\0' '\\n' | grep '^WINDOW=' | cut -d= -f2" let res2 = substitute(system(my_cmd2), '\n','','') if res2 != '' || res2 == '0' echo 'This file is already opened in window: ' . res2 else " 兜底逻辑:直接查询screen窗口列表匹配对应文件 let current_screen = substitute(system('echo $STY | cut -d. -f1'), '\n', '', '') let fallback_cmd = "screen -S " . current_screen . " -Q windows | tr ' ' '\\n' | grep -B1 '" . fname . "' | head -n1 | tr -cd '0-9'" let res2_fb = substitute(system(fallback_cmd), '\n','','') if res2_fb != '' || res2_fb == '0' echo 'This file is already opened in window: ' . res2_fb else echo 'This file is already opened in another vim instance, PID: ' . result endif endif endif endfunction """""""""""""""""""""""""""""""""""""""""""""""""""
验证方式
- 打开screen会话,在0号窗口用vim打开任意测试文件,保持运行不退出
- 切换到其他screen窗口,再次用vim打开同一个文件,vim底部会直接提示文件所在的窗口编号,直接按
Ctrl+a 对应编号就能跳转到对应窗口 - 如果提示lsof不存在,重新运行Cygwin安装程序确认lsof包已安装到当前Cygwin环境即可,不需要额外配置路径。
内容的提问来源于stack exchange,提问作者PyTis
相关产品推荐
相关产品推荐

