2012-09-07 46 views
1

在這種情況下(默認行爲),我必須使用哪些關鍵部件來獲取foo()函數將緩衝區寫入磁盤?尤其是vim的一部分,可以通過vim.eval()vim.command()或其他。BufWriteCmd處理程序

au BufWriteCmd * exec :python foo() 

foo()

def foo(): 
    abuf = vim.eval("expand('<abuf>')" 
+0

第一行代碼中的「exec」是什麼? – ZyX

回答

2
au BufWriteCmd * :python foo() 

python << EOF 
import vim, os 
def foo(): 
    abuf=int(vim.eval('expand("<abuf>")'))-1 
    amatch=vim.eval('expand("<amatch>")') 
    abang=bool(int(vim.eval('v:cmdbang'))) 
    cmdarg=vim.eval('v:cmdarg') 

    if os.path.isdir(amatch): 
     raise ValueError('Cannot write to directory {0}'.format(amatch)) 
    if not os.path.isdir(os.path.dirname(amatch)): 
     raise ValueError('Directory {0} does not exist'.format(amatch)) 

    encoding=vim.eval('&encoding') 

    opts={l[0] : l[1] if len(l)>1 else True 
      for l in [s[2:].split('=') 
        for s in cmdarg.split()]} 
    if 'ff' not in opts: 
     opts['ff']=vim.eval('getbufvar({0}, "&fileformat")'.format(abuf)) 
     if not opts['ff']: 
      opts['ff']='unix' 
    if 'enc' not in opts: 
     opts['enc']=vim.eval('getbufvar({0}, "&fileencoding")'.format(abuf)) 
     if not opts['enc']: 
      opts['enc']=encoding 
    if 'nobin' in opts: 
     opts['bin']=False 
    elif 'bin' not in opts: 
     opts['bin']=vim.eval('getbufvar({0}, "&binary")'.format(abuf)) 

    if opts['bin']: 
     opts['ff']='unix' 
     eol=bool(int(vim.eval('getbufvar({0}, "&endofline")'.format(abuf)))) 
    else: 
     eol=True 

    eolbytes={'unix': '\n', 'dos': '\r\n', 'mac': '\r'}[opts['ff']] 

    buf=vim.buffers[abuf] 
    f=open(amatch, 'wb') 
    first=True 
    for line in buf: 
     if opts['enc']!=encoding: 
      # Does not handle invalid bytes. 
      line=line.decode(encoding).encode(opts['enc']) 
     if not first: 
      f.write(eolbytes) 
     else: 
      first=False 
     f.write(line) 
    if eol: 
     f.write(eolbytes) 
    f.close() 
EOF 

與上面的代碼,你將有標準:w smth行爲幾乎完全仿真。

+0

在迭代緩衝區中的行並在第一行之後追加新行的循環中,這是否是一個錯誤?無論如何,我已經明白了,只有在「eol」爲真(文件只能包含一行)時,'eolbytes'必須添加到文件末尾。非常好的答案,謝謝。 – Flavius

+0

@Flavius不,這不是一個錯誤:我首先做'f.write(eolbytes)'然後'f.write(line)'。我添加新行,不追加它,因爲它更容易實現,然後檢查作爲最後一行的處理行。儘管您可能會將其稱爲「在上一行之後添加」。 – ZyX

+0

哦,我錯過了那個部分('不是','不是')。 – Flavius