2015-11-06 47 views
1

我想寫一個Tcl腳本對準我的TCL腳本正確的縮進。例如,如果我有一個像代碼:Tcl腳本來執行壓痕

proc calc { } { 
set a 5 
set b 10 
if {a < b} { 
puts "b Greater" 
} 
} 

我需要改變,如:

proc calc { } { 
    set a 5 
    set b 10 
    if {a < b} { 
     puts "b Greater" 
    } 
} 

可以ü傢伙幫助這一點。

+1

你可能想看看'frink',這是過時的,但它可能是你OK:HTTP: //wiki.tcl.tk/2611 –

+0

除了'frink'和'naglfar'這是什麼?沒有人使用他們的tcl代碼的漂亮打印?他們只是一直寫得很好? – Thufir

回答

0

編寫用於處理您的例子很簡單的壓頭。一個可以處理大多數Tcl腳本的完整壓縮器將會非常龐大​​而且非常複雜。一個可以處理任何Tcl腳本的壓縮器必須包含一個完整的Tcl解釋器。

這是因爲Tcl源代碼是非常動態的:一方面你不能總是隻看代碼,並知道哪些部分正在執行代碼,哪些部分是數據。另一件事是用戶定義的控制結構,這可能會改變代碼的查看方式。下面的例子通過計算大括號來實現,但是它沒有試圖區分應該增加縮進的引號括號和不應該引用的大括號。

這個例子是一個非常簡單的壓頭。據嚴重限制不應該被用來嚴重的實現。

proc indent code { 
    set res {} 
    set ind 0 
    foreach line [split [string trim $code] \n] { 
     set line [string trim $line] 
     # find out if the line starts with a closing brace 
     set clb [string match \}* $line] 
     # indent the line, with one less level if it starts with a closing brace 
     append res [string repeat { } [expr {$ind - $clb}]]$line\n 
     # look through the line to find out the indentation level of the next line 
     foreach c [split $line {}] { 
      if {$c eq "\{"} {incr ind} 
      if {$c eq "\}"} {incr ind -1} 
     } 
    } 
    return $res 
} 

這會將您的第一個代碼示例轉換爲第二個代碼示例。儘管在代碼中要添加一個大括號作爲縮進的數據,並且縮進將關閉。

文檔:appendexprforeachifincrprocreturnsetsplitstring