开发者

Vim: most efficient way to test for pattern at cursor?

I have a problem with matching text in Vim buffers. I have a specific form of dates in my text and often need to test whether the text at cursor matches the date pattern.

Here are some examples of the formatted dates, which may be preceded or followed by other text on the same line:

<2011-10-13 Wed>
[2011-10-13 Wed]
<2011-10-13 Wed +1>
[2011-10-13 Wed +1]
<2011-10-13 开发者_高级运维Wed 10:30>
[2011-10-13 Wed 10:30]
<2011-10-13 Wed 10:30-11:30>
[2011-10-13 Wed 10:30-11:30]
<2011-10-13 Wed 10:30 +1w>
[2011-10-13 Wed 10:30 +1w]

I have some code that tests at cursor position to see whether cursor is on a date, and if so what the date text is, but what I'm doing seems kind of clumsy.

Any comments on what most efficient function for returning the date under cursor (or empty string if not on a date)? (I would post my code but will refrain for now both (1) out of embarrassment and (2) to avoid polluting your minds by suggesting a particular approach to the problem.)

Thanks for any tips.


function! CheckDate(expr)
    let date_pattern = '[\[<]'      " The first < or [
                \.'\d\{4\}-\d\{2\}-\d\{2\}' " YYYY-MM-DD
                \.' \(Mon\|Tue\|Wed\|Thu\|Fri\|Sat\|Sun\)' " Week day
                \.'\( \d\{2\}:\d\{2\}\(-\d\{2\}:\d\{2\}\)\?\)\?'
                                    " Optional time or range
                \.'\( +\dw\?\)\?'   " Optional + digit with optional 'w'
                \.'\([\]>]\)'     " The closing > or ]
    return match(a:expr, date_pattern) != -1
endfunction

function! IsOverDate()
    call setreg('a','')
    call setreg('b','')
    normal! "aya>
    let expr1 = getreg('a')
    normal! "bya]
    let expr2 = getreg('b')
    if CheckDate(expr1)
        return expr1
    elseif CheckDate(expr2)
        return expr2
    endif
    return ''
endfunction

The function IsOverDate() clears the registers a and b and stores in the respective registers the text under the cursor which is inside < and > and < and >, including the brackets. Then, it gets the value from the registers a and b and sends it to the function CheckDate() which checks if the expression matches the date pattern (I have based myself in your samples and made some assumptions to build the pattern).

The CheckDate() function returns true only if the expression matches the date pattern. The function IsOverDate() returns the date under the cursor (with the brackets) or an empty string if the cursor is not over a date.

I hope it suits.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜