答案1
如果你
:set autochdir
您将获得所需的行为。但是,如果您需要保留工作目录(例如,为了轻松打开其他项目文件),则必须使用自动命令保存/恢复 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>
,离开插入模式时则返回到上一个目录。