答案1
如果你
:set autochdir
你會得到你想要的行為。但是,如果您需要保留工作目錄(例如,為了輕鬆開啟其他專案檔案),則必須使用 autocmds 儲存/復原 CWD:
:autocmd InsertEnter * let save_cwd = getcwd() | set autochdir
:autocmd InsertLeave * set noautochdir | execute 'cd' fnameescape(save_cwd)
答案2
答案3
我的.vimrc
:
" [relative autocomplete]
" ==============================================================================
" Vim's file autocomplete (C-X C-F) works only in an absolute path (using the
" current working directory) as base. But in most languages, you want to use
" relative imports, and file autocomplete doesn't work there. For that, I use
" <C-X><C-X><C-F>:
function! s:EnableRelativeAutocomplete() abort
let b:relative_autocomplete_cleanup_pending = 1
lcd %:p:h
endfunction
function! s:DisableRelativeAutocomplete() abort
if exists('b:relative_autocomplete_cleanup_pending') && b:relative_autocomplete_cleanup_pending
lcd -
let b:relative_autocomplete_cleanup_pending = 0
endif
endfunction
inoremap <C-x><C-x><C-f> <C-o>:call <SID>EnableRelativeAutocomplete()<CR><C-x><C-f>
augroup relative_file_autocomplete
autocmd!
autocmd InsertLeave * call s:DisableRelativeAutocomplete()
augroup END
如果需要,它會在使用時將工作目錄變更為目前檔案的工作目錄<C-x><C-x><C-f>
,並在離開插入模式時返回先前的目錄。