我發現了一種在vimscript中使用python的方法。使用python,我能夠從vim.buffers[i].name
獲得所有緩衝區的名稱,並使用os.path
和os.sep
來處理切換到哪個緩衝區。
最後,我決定,如果它被要求切換到的緩衝區模糊不清,它會拒絕做任何事情會更有幫助。
這就是:
"Given a file, full path, or partial path, this will try to change to the
"buffer which may match that file. If no buffers match, it returns 1. If
"multiple buffers match, it returns 2. It returns 0 on success
function s:GotoBuffer(buf)
python << EOF
import vim, os
buf = vim.eval("a:buf")
#split the paths into lists of their components and reverse.
#e.g. foo/bar/baz.py becomes ['foo', 'bar', 'baz.py']
buf_path = os.path.normpath(buf).split(os.sep)[::-1]
buffers = [os.path.normpath(b.name).split(os.sep)[::-1] for b in vim.buffers]
possible_buffers = range(len(buffers))
#start eliminating incorrect buffers by their filenames and paths
for component in xrange(len(buf_path)):
for b in buffers:
if len(b)-1 >= component and b[component] != buf_path[component]:
#This buffer doesn't match. Eliminate it as a posibility.
i = buffers.index(b)
if i in possible_buffers: possible_buffers.remove(i)
if len(possible_buffers) > 1: vim.command("return 2")
#delete the next line to allow ambiguous switching
elif not possible_buffers: vim.command("return 1")
else:
vim.command("buffer " + str(possible_buffers[-1] + 1))
EOF
endfunction
編輯:上面的代碼似乎有一些錯誤。我不打算修復它們,因爲還有另一個更好的答案。
*扭曲的笑容*我知道VIM將有一個函數來做到這一點。謝謝。 –