我想编写一个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"
}
}
你们可以帮忙解决这个问题。
答案 0 :(得分: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
}
这会将您的第一个代码示例转换为第二个代码示例。尽管如此,在代码中的某处仍然会添加一个大括号作为数据,并且缩进将会关闭。