vim使用NERDTree之后打开目录出现两个目录树窗口

5,136 阅读1分钟

版本号:

VIM - Vi IMproved 8.2 (2019 Dec 12, compiled Sep 24 2021 14:13:28)
macOS version - x86_64

截图:

22222.png

原因:

vim有自带的 Netrw 文件浏览器,打开目录的时候默认会开启该窗口;因为只有Netrw支持打开远程文件,所以需要处理 NERDTree 和Netrw 的兼容问题。

解决:

NERDTree本身有兼容 Netrw 的方法: NERDTree README

0zm6p120009l6vfyv135E.png

但其中会有一个问题:使用这种方式会导致用vim命令创建新文件时无法设置文件名:

问题issue

通过修改NERDTree提供的.vimrc来暂时解决这个问题:

" Function to open the file or NERDTree or netrw.
"   Returns: 1 if either file explorer was opened; otherwise, 0.
function! s:OpenFileOrExplorer(...)
    if a:0 == 0 || a:1 == ''
        NERDTree
    elseif filereadable(a:1)
"        execute 'edit '.a:1
        return 0
    elseif a:1 =~? '^\(scp\|ftp\)://' " Add other protocols as needed.
        execute 'Vexplore '.a:1
	return 1
    elseif isdirectory(a:1)
        execute 'NERDTree '.a:1
        return 1
    else
        NERDTree
    endif
    return 0
endfunction

" Auto commands to handle OS commandline arguments
autocmd StdinReadPre * let s:std_in=1
autocmd VimEnter * if argc()==1 && !exists('s:std_in') | if <SID>OpenFileOrExplorer(argv()[0]) | wincmd p | enew | wincmd p | endif | endif

" Command to call the OpenFileOrExplorer function.
command! -n=? -complete=file -bar Edit :call <SID>OpenFileOrExplorer('<args>')

" Command-mode abbreviation to replace the :edit Vim command.
cnoreabbrev e Edit