2013-12-11 54 views
2

我想要生成連續的文件名,從當前緩衝區的名稱中取最後的2+位數 ,並從那裏開始向上計數。像這樣: 08a01 > 08a02 > 08a03 > ...Vim:函數中如何從「01」到「02」(而不是「01」>「2」)計數?

我使用的片段(thanks for initial advice,英戈Karkat!)省去了零, 像08a01 > 08a2 > 08a3 > ...生產序列。

if b:current_buffer_name =~ '\d\+$' 
    let lastDigit = matchstr(b:current_buffer_name, '\d\+$') 
    let newDigit = lastDigit + 1 
    let s:new_file_name = substitute(b:current_buffer_name, '\d\+$', newDigit, '') 
else 
    let s:new_file_name = b:current_buffer_name . '01' 

我怎麼能告訴Vim,它應該向上計數「與 零」的功能?我試圖加之前 如果條件(建議here),但沒有奏效。

感謝您的任何解釋!

回答

3

試試這個:

改變這一行:

let newDigit = lastDigit + 1 

到:

let newDigit = printf("%02d", str2nr(lastDigit) + 1) 

沒有測試,但是通過閱讀你的代碼,它應該工作。

它硬編碼2,如果你的字符串是foobar0000001,它將不起作用。在這種情況下,您需要獲得len(lastDigit)並以printf格式使用它。

+0

我嘗試這個解決辦法,但我althought刪除''從選項nrformats'價值octal' ,它使用它進行計算。嘗試使用像foobar004562這樣的文件名。 – Birei

+0

@Birei哦,thx,我忽略了八進制的東西!增加一個'str2nr()'將會修復它。答案已更新。 – Kent

+1

順便說一句,該選項是'c-a/x',不會影響'+'表達式。 @Birei – Kent

1

我不知道如何避免在沒有vim時考慮到數字不是octal且前導零。我嘗試了set nrformats-=octal,但都沒有成功。這是我的解決方法由對方提取兩個部分,零由一側和從前導零的其他數字的數目並計算其長度使用printf()

let last_digits = matchlist(bufname('%'), '\(0\+\)\?\(\d\+\)$') 
echo printf('%0' . (len(last_digits[1]) + len(last_digits[2])) . 'd', last_digits[2] + 1) 

一些測試:

隨着緩衝命名爲08a004562last_digits將是一個清單,如:

['004562', '00', '4562', '', '', '', '', '', '', ''] 

,其結果將是:

004563 

並與一個叫8a9緩衝,last_digits將是:

['9', '', '9', '', '', '', '', '', '', ''] 

和結果:

10 
+0

謝謝!我會使用@ Kent的解決方案,因爲它更短。但是,由於我最初試圖找出類似的解決方法(分別提取零和其他數字),所以您的教育是有教育意義的。 – marttt

相關問題