2009/04/02

輕輕鬆鬆寫VIM plugin: 流程控制 condition

IF
跟一般常見的語法一樣,請看下例:
:if &term == "xterm"
: " Do stuff for xterm
:elseif &term == "vt100"
: " Do stuff for a vt100 terminal
:else
: " Do something for other terminals
:endif


VIM最基本的判別式有以下這幾種:
a == b equal to
a != b not equal to
a > b greater than
a >= b greater than or equal to
a < b less than
a <= b less than or equal to


正常來說不論數字或字串比較,a及b的型態最好都相同,但若不同時可以直接看下例:
:if 0 == "one"
: echo "yes"
:endif


這個例子最後會輸出yes,當數字與字串比較時,字串會轉型為數字。由於one的第一個字元即不為數字所以它被直接翻成0,使得判別式成真。

VIM另外還有針對字串的判別方式,如下:
a =~ b matches with
a !~ b does not match with


左邊變數a會被成字串,右邊變數則會作為pattern,下面有個例子:

:if str =~ " "
: echo "str contains a space"
:endif
:if str !~ '\.$'
: echo "str does not end in a full stop"
:endif


此外,關於不分大小寫比對的話,在VIM裡可就複雜了一些,VIM有個option ignorecase來設定大小寫比對,有些時候可能我們不想設定這個值則可以直接從比對的算符來設定,想知道的人自己看一下[這個表格]。

while and for

VIM的while迴圈大概長底下這樣,它跟一般的語言一樣也有continue及break關鍵字。
:while counter < 40
: call do_something()
: if skip_flag
: continue
: endif
: if finished_flag
: break
: endif
: sleep 50m
:endwhile


VIM的for迴圈,通常是跟著list及dictionary這兩種型態一起使用,所以for迴圈我就留到那時候再講唄。

Exception
VIM跟C++ or Java一樣也有例外處理,用法跟他們都頗像,大概的用法就是try...cache...finally這三個關鍵字,請見以下範例:

:try
: read ~/templates/pascal.tmpl
:catch /E484:/
: echo "Sorry, the Pascal template file cannot be found."
:endtry


當檔案不存在時便會發生exception,在這個例子中是只catch E484:開頭的例外,當然,你也可以不要寫/E484:/,它就會抓所有的exception。

底下是個有finally的例子,finally在不論try的程式片段成功執行與否皆會執行finally後的程式片段。

:let tmp = tempname()
:try
: exe ".,$write " . tmp
: exe "!filter " . tmp
: .,$delete
: exe "$read " . tmp
:finally
: call delete(tmp)
:endtry