2017-04-25 41 views
1

我使用vim進行會計分類賬。我希望能夠在這樣一個行的開頭輸入一個日期:如何將縮短日期擴展爲完整日期?

4/3

,然後按space後,有它的自動擴展成:

2017/04/03

在vim中完成此操作的最佳方法是什麼?

+0

Vim的維基上的如何[插入*當前*日期]幾個技巧(http://vim.wikia.com /維基/ Insert_current_date_or_time)。 –

回答

3

inoremap <expr>是你在找什麼。而printfsubstitute可以幫助您構建日期時間格式。把它們放在一起:

inoremap <expr> <space> match(getline('.'), '\v^\d\d?/\d\d?') == -1? " ": '<Esc>v0s'.substitute(getline('.'), '\v^(\d\d?)/(\d\d?)', "\\=printf('%s/%.2d/%.2d',strftime('%Y'),submatch(1),submatch(2))","") 

小演示:

enter image description here

+0

...還有更好的方法... –

2

也許是更好的方式存在,但下面的查找和替換會做的伎倆(你可以隨時爲它創建一個映射)

:%s#\v^(\d{1,2})/(\d{1,2})#\=printf('%4s/%1.2d/%2.2d', strftime('%Y'), submatch(1), submatch(2) 

擊穿(編輯:工藤的羅蘭)

%s#    
    - Starts a find and replace. Use # as separator 

\v^(\d{1,2})/(\d{1,2}) 
    - Search from the start of the line for one or two digits, folowed by a /, followed by a one or two digits. 

\=printf('%4s/%1.2d/%2.2d', strftime('%Y'), submatch(1), submatch(2)) 
    - Replace matched items using a formatstring, padding zero's if necessary. Insert the current year with `strftime`. 
+1

我想知道用數字代替'* {1,2}'而不是'*'會更好嗎? –

+0

@羅蘭史密斯 - 是的,offcourse :)。如果您有任何其他提示,請隨時改進答案。 –

+1

使用'strftime'插入當前年份。我認爲,這與使用簡單的正則表達式一樣好。人們可以編寫一個驗證月份和日期的vimscript函數,並在正則表達式中使用它,但這可能是矯枉過正的。 –