19 proc reformat {tclcode {pad 2}} {
21 set lines [
split $tclcode \n]
25 set line [
lindex $lines 0]
26 set indent [
expr {([string length $line]-[string length [string trimleft $line \ \t]])/$pad}]
27 set padst [
string repeat " " $pad]
30 if {$lineindex>1} {
append out \n}
31 set newline [
string trimleft $orig]
32 if {$newline==""} continue
34 set is_continued $ncont
35 if {[
string index $orig end] eq "\\"} {
40 if { [
string index $newline 0]=="#" } {
43 set npad [
expr {$indent * $pad}]
44 set line [
string repeat $padst $indent]$newline
45 set i [
set ns [
set nl [
set nr [
set body 0]]]]
46 for {
set n [
string length $newline]} {$i<$n} {
incr i} {
47 set ch [
string index $newline $i]
49 set ns [
expr {[incr ns] % 2}]
52 set nquot [
expr {[incr nquot] % 2}]
56 if {[
string range $newline $i $i+2]=="\{\"\}"} {
73 set nbbraces [
expr {$nl - $nr}]
74 incr totalbraces $nbbraces
76 error "Line $lineindex: unbalanced braces!"
79 if {$nbbraces==0} {
set nbbraces $body}
80 if {$is_quoted || $is_continued} {
83 set np [
expr {- $nbbraces * $pad}]
87 set line [
string range $line $np end]
96 switch -- $::tcl_platform(platform) {
100 default {error "no such platform: $::tc_platform(platform)"}
104 proc count {string char} {
106 while {[
set idx [
string first $char $string]]>=0} {
109 while {[string equal [string index $string [incr nidx -1]] \\]} {
112 if {$backslashes % 2 == 0} {
115 set string [
string range $string [
incr idx] end]
121 if {[
catch {
package require cmdline} ERROR]} {
122 puts "$ERROR\n If you are running this script on tclsh, you can fix this by installing 'tcllib'"
127 {tab_width.arg 2 "Width of the indentation tabs. Default: "}
130 set usage "- USAGE: $::argv0 \[OPTIONS\] <tcl_file> \n. Options:"
132 set path [
file normalize "[
file dirname [
info script]]/.."]
135 if {[
catch {
array set options [
cmdline::getoptions ::argv $parameters $usage]}] || [
llength $argv] < 1 } {
139 set indent $options(tab_width)
143 set permissions [
file attributes $argv -permissions]
145 set filename "$argv.tmp"
146 set f [open $filename w]
148 puts -nonewline $f [
reformat [
string map [list [
eol] \n] $data] $indent]
150 file copy -force $filename $argv
151 file delete -force $filename
152 file attributes $argv -permissions $permissions