3 # Default system startup file for Tcl-based applications. Defines
4 # "unknown" procedure and auto-load facilities.
6 # RCS: @(#) $Id: init.tcl,v 1.104.2.7 2008/10/10 18:16:48 dgp Exp $
8 # Copyright (c) 1991-1993 The Regents of the University of California.
9 # Copyright (c) 1994-1996 Sun Microsystems, Inc.
10 # Copyright (c) 1998-1999 Scriptics Corporation.
11 # Copyright (c) 2004 by Kevin B. Kenny. All rights reserved.
13 # See the file "license.terms" for information on usage and redistribution
14 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
17 if {[info commands
package] == ""} {
18 error "version mismatch: library\nscripts expect Tcl version 7.5b1 or later but the loaded version is\nonly [info patchlevel]"
20 package require
-exact Tcl 8.5.5
22 # Compute the auto path to use in this interpreter.
23 # The values on the path come from several locations:
25 # The environment variable TCLLIBPATH
27 # tcl_library, which is the directory containing this init.tcl script.
28 # [tclInit] (Tcl_Init()) searches around for the directory containing this
29 # init.tcl and defines tcl_library to that location before sourcing it.
31 # The parent directory of tcl_library. Adding the parent
32 # means that packages in peer directories will be found automatically.
34 # Also add the directory ../lib relative to the directory where the
35 # executable is located. This is meant to find binary packages for the
36 # same architecture as the current executable.
38 # tcl_pkgPath, which is set by the platform-specific initialization routines
39 # On UNIX it is compiled in
40 # On Windows, it is not used
42 if {![info exists auto_path
]} {
43 if {[info exists env
(TCLLIBPATH
)]} {
44 set auto_path
$env(TCLLIBPATH
)
51 foreach Dir
[list $::tcl_library [file dirname
$::tcl_library]] {
52 if {$Dir ni
$::auto_path} {
53 lappend ::auto_path $Dir
56 set Dir
[file join [file dirname
[file dirname
\
57 [info nameofexecutable
]]] lib
]
58 if {$Dir ni
$::auto_path} {
59 lappend ::auto_path $Dir
62 foreach Dir
$::tcl_pkgPath {
63 if {$Dir ni
$::auto_path} {
64 lappend ::auto_path $Dir
69 if {![interp issafe
]} {
70 variable Path
[encoding dirs
]
71 set Dir
[file join $::tcl_library encoding]
78 # TIP #255 min and max functions
79 namespace eval mathfunc
{
81 if {[llength $args] == 0} {
83 "too few arguments to math function \"min\""
87 # This will handle forcing the numeric value without
88 # ruining the internal type of a numeric object
89 if {[catch {expr {double
($arg)}} err
]} {
90 return -code error $err
92 if {$arg < $val} { set val
$arg }
97 if {[llength $args] == 0} {
99 "too few arguments to math function \"max\""
103 # This will handle forcing the numeric value without
104 # ruining the internal type of a numeric object
105 if {[catch {expr {double
($arg)}} err
]} {
106 return -code error $err
108 if {$arg > $val} { set val
$arg }
112 namespace export min max
116 # Windows specific end of initialization
118 if {(![interp issafe
]) && ($tcl_platform(platform
) eq
"windows")} {
120 proc EnvTraceProc
{lo n1 n2 op
} {
123 set ::env([string toupper
$lo]) $x
126 global env tcl_platform
127 foreach p
[array names env
] {
128 set u
[string toupper
$p]
133 if {![info exists env
($u)]} {
136 trace add
variable env
($p) write
\
137 [namespace code
[list EnvTraceProc
$p]]
138 trace add
variable env
($u) write
\
139 [namespace code
[list EnvTraceProc
$p]]
144 if {![info exists env
(COMSPEC
)]} {
145 if {$tcl_platform(os
) eq
"Windows NT"} {
146 set env
(COMSPEC
) cmd.exe
148 set env
(COMSPEC
) command.com
156 # Setup the unknown package handler
159 if {[interp issafe
]} {
160 package unknown {::tcl::tm::UnknownHandler ::tclPkgUnknown}
162 # Set up search for Tcl Modules (TIP #189).
163 # and setup platform specific unknown package handlers
164 if {$::tcl_platform(os
) eq
"Darwin"
165 && $::tcl_platform(platform
) eq
"unix"} {
166 package unknown {::tcl::tm::UnknownHandler \
167 {::tcl::MacOSXPkgUnknown ::tclPkgUnknown}}
169 package unknown {::tcl::tm::UnknownHandler ::tclPkgUnknown}
172 # Set up the 'clock' ensemble
174 namespace eval ::tcl::clock [list variable TclLibDir
$::tcl_library]
177 namespace eval ::tcl::clock [list namespace ensemble create
-command \
178 [uplevel 1 [list namespace origin
[lindex [info level
0] 0]]] \
180 add clicks
format microseconds milliseconds
scan seconds
183 # Auto-loading stubs for 'clock.tcl'
185 foreach cmd
{add
format scan} {
186 proc ::tcl::clock::$cmd args
{
188 source -encoding utf-8
[file join $TclLibDir clock.tcl
]
189 return [uplevel 1 [info level
0]]
193 return [uplevel 1 [info level
0]]
197 # Conditionalize for presence of exec.
199 if {[namespace which
-command exec] eq
""} {
201 # Some machines do not have exec. Also, on all
202 # platforms, safe interpreters do not have exec.
207 # Define a log command (which can be overwitten to log errors
208 # differently, specially when stderr is not available)
210 if {[namespace which
-command tclLog
] eq
""} {
211 proc tclLog
{string} {
212 catch {puts stderr
$string}
217 # This procedure is called when a Tcl command is invoked that doesn't
218 # exist in the interpreter. It takes the following steps to make the
221 # 1. See if the command has the form "namespace inscope ns cmd" and
222 # if so, concatenate its arguments onto the end and evaluate it.
223 # 2. See if the autoload facility can locate the command in a
224 # Tcl script file. If so, load it and execute it.
225 # 3. If the command was invoked interactively at top-level:
226 # (a) see if the command exists as an executable UNIX program.
227 # If so, "exec" the command.
228 # (b) see if the command requests csh-like history substitution
229 # in one of the common forms !!, !<number>, or ^old^new. If
230 # so, emulate csh's history substitution.
231 # (c) see if the command is a unique abbreviation for another
232 # command. If so, invoke the command.
235 # args - A list whose elements are the words of the original
236 # command, including the command name.
239 variable ::tcl::UnknownPending
240 global auto_noexec auto_noload env tcl_interactive
242 # If the command word has the form "namespace inscope ns cmd"
243 # then concatenate its arguments onto the end and evaluate it.
245 set cmd
[lindex $args 0]
246 if {[regexp "^:*namespace\[ \t\n\]+inscope" $cmd] && [llength $cmd] == 4} {
247 #return -code error "You need an {*}"
248 set arglist
[lrange $args 1 end
]
249 set ret
[catch {uplevel 1 ::$cmd $arglist} result opts
]
250 dict
unset opts
-errorinfo
251 dict
incr opts
-level
252 return -options $opts $result
255 catch {set savedErrorInfo
$::errorInfo}
256 catch {set savedErrorCode
$::errorCode}
258 if {![info exists auto_noload
]} {
260 # Make sure we're not trying to load the same proc twice.
262 if {[info exists UnknownPending
($name)]} {
263 return -code error "self-referential recursion\
264 in \"unknown\" for command \"$name\"";
266 set UnknownPending
($name) pending
;
268 auto_load $name [uplevel 1 {::namespace current
}]
270 unset UnknownPending
($name);
272 dict
append opts
-errorinfo "\n (autoloading \"$name\")"
273 return -options $opts $msg
275 if {![array size UnknownPending
]} {
279 catch {set ::errorCode $savedErrorCode}
280 catch {set ::errorInfo $savedErrorInfo}
281 set code
[catch {uplevel 1 $args} msg opts
]
284 # Compute stack trace contribution from the [uplevel].
285 # Note the dependence on how Tcl_AddErrorInfo, etc.
286 # construct the stack trace.
288 set errorInfo
[dict get
$opts -errorinfo]
289 set errorCode
[dict get
$opts -errorcode]
291 if {[string bytelength
$cinfo] > 150} {
292 set cinfo
[string range
$cinfo 0 150]
293 while {[string bytelength
$cinfo] > 150} {
294 set cinfo
[string range
$cinfo 0 end-1
]
298 append cinfo
"\"\n (\"uplevel\" body line 1)"
299 append cinfo
"\n invoked from within"
300 append cinfo
"\n\"uplevel 1 \$args\""
302 # Try each possible form of the stack trace
303 # and trim the extra contribution from the matching case
305 set expect
"$msg\n while executing\n\"$cinfo"
306 if {$errorInfo eq
$expect} {
308 # The stack has only the eval from the expanded command
309 # Do not generate any stack trace here.
311 dict
unset opts
-errorinfo
312 dict
incr opts
-level
313 return -options $opts $msg
316 # Stack trace is nested, trim off just the contribution
317 # from the extra "eval" of $args due to the "catch" above.
319 set expect
"\n invoked from within\n\"$cinfo"
320 set exlen
[string length
$expect]
321 set eilen
[string length
$errorInfo]
322 set i
[expr {$eilen - $exlen - 1}]
323 set einfo
[string range
$errorInfo 0 $i]
325 # For now verify that $errorInfo consists of what we are about
326 # to return plus what we expected to trim off.
328 if {$errorInfo ne
"$einfo$expect"} {
329 error "Tcl bug: unexpected stack trace in \"unknown\"" {} \
330 [list CORE UNKNOWN BADTRACE
$einfo $expect $errorInfo]
332 return -code error -errorcode $errorCode \
333 -errorinfo $einfo $msg
335 dict
incr opts
-level
336 return -options $opts $msg
341 if {([info level
] == 1) && ([info script
] eq
"") \
342 && [info exists tcl_interactive
] && $tcl_interactive} {
343 if {![info exists auto_noexec
]} {
344 set new
[auto_execok $name]
347 if {[namespace which
-command console] eq
""} {
348 set redir
">&@stdout <@stdin"
350 uplevel 1 [list ::catch \
351 [concat exec $redir $new [lrange $args 1 end
]] \
352 ::tcl::UnknownResult ::tcl::UnknownOptions]
353 dict
incr ::tcl::UnknownOptions -level
354 return -options $::tcl::UnknownOptions $::tcl::UnknownResult
358 set newcmd
[history event]
359 } elseif
{[regexp {^
!(.
+)$} $name -> event]} {
360 set newcmd
[history event $event]
361 } elseif
{[regexp {^
\^
([^^
]*)\^
([^^
]*)\^?
$} $name -> old new
]} {
362 set newcmd
[history event -1]
363 catch {regsub -all -- $old $newcmd $new newcmd
}
365 if {[info exists newcmd
]} {
367 history change
$newcmd 0
368 uplevel 1 [list ::catch $newcmd \
369 ::tcl::UnknownResult ::tcl::UnknownOptions]
370 dict
incr ::tcl::UnknownOptions -level
371 return -options $::tcl::UnknownOptions $::tcl::UnknownResult
374 set ret
[catch {set candidates
[info commands
$name*]} msg
]
379 dict
append opts
-errorinfo \
380 "\n (expanding command prefix \"$name\" in unknown)"
381 return -options $opts $msg
383 # Filter out bogus matches when $name contained
384 # a glob-special char [Bug 946952]
386 # Handle empty $name separately due to strangeness
387 # in [string first] (See RFE 1243354)
391 foreach x
$candidates {
392 if {[string first
$name $x] == 0} {
397 if {[llength $cmds] == 1} {
398 uplevel 1 [list ::catch [lreplace $args 0 0 [lindex $cmds 0]] \
399 ::tcl::UnknownResult ::tcl::UnknownOptions]
400 dict
incr ::tcl::UnknownOptions -level
401 return -options $::tcl::UnknownOptions $::tcl::UnknownResult
403 if {[llength $cmds]} {
404 return -code error "ambiguous command name \"$name\": [lsort $cmds]"
407 return -code error "invalid command name \"$name\""
411 # Checks a collection of library directories to see if a procedure
412 # is defined in one of them. If so, it sources the appropriate
413 # library file to create the procedure. Returns 1 if it successfully
414 # loaded the procedure, 0 otherwise.
417 # cmd - Name of the command to find and load.
418 # namespace (optional) The namespace where the command is being used - must be
419 # a canonical namespace as returned [namespace current]
420 # for instance. If not given, namespace current is used.
422 proc auto_load {cmd
{namespace {}}} {
423 global auto_index auto_path
425 if {$namespace eq
""} {
426 set namespace [uplevel 1 [list ::namespace current
]]
428 set nameList
[auto_qualify $cmd $namespace]
429 # workaround non canonical auto_index entries that might be around
430 # from older auto_mkindex versions
431 lappend nameList
$cmd
432 foreach name
$nameList {
433 if {[info exists auto_index
($name)]} {
434 namespace eval :: $auto_index($name)
435 # There's a couple of ways to look for a command of a given
436 # name. One is to use
437 # info commands $name
438 # Unfortunately, if the name has glob-magic chars in it like *
439 # or [], it may not match. For our purposes here, a better
441 # namespace which -command $name
442 if {[namespace which
-command $name] ne
""} {
447 if {![info exists auto_path
]} {
451 if {![auto_load_index
]} {
454 foreach name
$nameList {
455 if {[info exists auto_index
($name)]} {
456 namespace eval :: $auto_index($name)
457 if {[namespace which
-command $name] ne
""} {
466 # Loads the contents of tclIndex files on the auto_path directory
467 # list. This is usually invoked within auto_load to load the index
468 # of available commands. Returns 1 if the index is loaded, and 0 if
469 # the index is already loaded and up to date.
474 proc auto_load_index
{} {
475 variable ::tcl::auto_oldpath
476 global auto_index auto_path
478 if {[info exists auto_oldpath
] && ($auto_oldpath eq
$auto_path)} {
481 set auto_oldpath
$auto_path
483 # Check if we are a safe interpreter. In that case, we support only
484 # newer format tclIndex files.
486 set issafe
[interp issafe
]
487 for {set i
[expr {[llength $auto_path] - 1}]} {$i >= 0} {incr i
-1} {
488 set dir
[lindex $auto_path $i]
491 catch {source [file join $dir tclIndex
]}
492 } elseif
{[catch {set f
[open [file join $dir tclIndex
]]}]} {
497 if {$id eq
"# Tcl autoload index file, version 2.0"} {
499 } elseif
{$id eq
"# Tcl autoload index file: each line identifies a Tcl"} {
500 while {[gets $f line
] >= 0} {
501 if {([string index
$line 0] eq
"#") \
502 ||
([llength $line] != 2)} {
505 set name
[lindex $line 0]
506 set auto_index
($name) \
507 "source [file join $dir [lindex $line 1]]"
510 error "[file join $dir tclIndex] isn't a proper Tcl index file"
517 return -options $opts $msg
526 # Compute a fully qualified names list for use in the auto_index array.
527 # For historical reasons, commands in the global namespace do not have leading
528 # :: in the index key. The list has two elements when the command name is
529 # relative (no leading ::) and the namespace is not the global one. Otherwise
530 # only one name is returned (and searched in the auto_index).
533 # cmd The command name. Can be any name accepted for command
534 # invocations (Like "foo::::bar").
535 # namespace The namespace where the command is being used - must be
536 # a canonical namespace as returned by [namespace current]
539 proc auto_qualify {cmd
namespace} {
541 # count separators and clean them up
542 # (making sure that foo:::::bar will be treated as foo::bar)
543 set n
[regsub -all {::+} $cmd :: cmd
]
545 # Ignore namespace if the name starts with ::
546 # Handle special case of only leading ::
548 # Before each return case we give an example of which category it is
549 # with the following form :
550 # ( inputCmd, inputNameSpace) -> output
552 if {[string match
::* $cmd]} {
554 # ( ::foo::bar , * ) -> ::foo::bar
557 # ( ::global , * ) -> global
558 return [list [string range
$cmd 2 end
]]
562 # Potentially returning 2 elements to try :
563 # (if the current namespace is not the global one)
566 if {$namespace eq
"::"} {
567 # ( nocolons , :: ) -> nocolons
570 # ( nocolons , ::sub ) -> ::sub::nocolons nocolons
571 return [list ${namespace}::$cmd $cmd]
573 } elseif
{$namespace eq
"::"} {
574 # ( foo::bar , :: ) -> ::foo::bar
577 # ( foo::bar , ::sub ) -> ::sub::foo::bar ::foo::bar
578 return [list ${namespace}::$cmd ::$cmd]
584 # Invoked during "namespace import" to make see if the imported commands
585 # reside in an autoloaded library. If so, the commands are loaded so
586 # that they will be available for the import links. If not, then this
587 # procedure does nothing.
590 # pattern The pattern of commands being imported (like "foo::*")
591 # a canonical namespace as returned by [namespace current]
593 proc auto_import {pattern
} {
596 # If no namespace is specified, this will be an error case
598 if {![string match
*::* $pattern]} {
602 set ns
[uplevel 1 [list ::namespace current
]]
603 set patternList
[auto_qualify $pattern $ns]
607 foreach pattern
$patternList {
608 foreach name
[array names auto_index
$pattern] {
609 if {([namespace which
-command $name] eq
"")
610 && ([namespace qualifiers
$pattern] eq
[namespace qualifiers
$name])} {
611 namespace eval :: $auto_index($name)
619 # Returns string that indicates name of program to execute if
620 # name corresponds to a shell builtin or an executable in the
621 # Windows search path, or "" otherwise. Builds an associative
622 # array auto_execs that caches information about previous checks,
626 # name - Name of a command.
628 if {$tcl_platform(platform
) eq
"windows"} {
631 # Note that info executable doesn't work under Windows, so we have to
632 # look for files with .exe, .com, or .bat extensions. Also, the path
633 # may be in the Path or PATH environment variables, and path
634 # components are separated with semicolons, not colons as under Unix.
636 proc auto_execok name
{
637 global auto_execs env tcl_platform
639 if {[info exists auto_execs
($name)]} {
640 return $auto_execs($name)
642 set auto_execs
($name) ""
644 set shellBuiltins
[list cls copy date del erase dir echo mkdir
\
645 md
rename ren rmdir rd
time type ver vol
]
646 if {$tcl_platform(os
) eq
"Windows NT"} {
647 # NT includes the 'start' built-in
648 lappend shellBuiltins
"start"
650 if {[info exists env
(PATHEXT
)]} {
651 # Add an initial ; to have the {} extension check first.
652 set execExtensions
[split ";$env(PATHEXT)" ";"]
654 set execExtensions
[list {} .com .exe .bat
]
657 if {$name in
$shellBuiltins} {
658 # When this is command.com for some reason on Win2K, Tcl won't
659 # exec it unless the case is right, which this corrects. COMSPEC
660 # may not point to a real file, so do the check.
661 set cmd
$env(COMSPEC
)
662 if {[file exists
$cmd]} {
663 set cmd
[file attributes
$cmd -shortname]
665 return [set auto_execs
($name) [list $cmd /c
$name]]
668 if {[llength [file split $name]] != 1} {
669 foreach ext
$execExtensions {
670 set file ${name
}${ext
}
671 if {[file exists
$file] && ![file isdirectory
$file]} {
672 return [set auto_execs
($name) [list $file]]
678 set path
"[file dirname [info nameof]];.;"
679 if {[info exists env
(WINDIR
)]} {
680 set windir
$env(WINDIR
)
682 if {[info exists windir
]} {
683 if {$tcl_platform(os
) eq
"Windows NT"} {
684 append path
"$windir/system32;"
686 append path
"$windir/system;$windir;"
689 foreach var
{PATH Path path
} {
690 if {[info exists env
($var)]} {
691 append path
";$env($var)"
695 foreach dir
[split $path {;}] {
696 # Skip already checked directories
697 if {[info exists checked
($dir)] ||
($dir eq
{})} { continue }
699 foreach ext
$execExtensions {
700 set file [file join $dir ${name
}${ext
}]
701 if {[file exists
$file] && ![file isdirectory
$file]} {
702 return [set auto_execs
($name) [list $file]]
712 proc auto_execok name
{
713 global auto_execs env
715 if {[info exists auto_execs
($name)]} {
716 return $auto_execs($name)
718 set auto_execs
($name) ""
719 if {[llength [file split $name]] != 1} {
720 if {[file executable
$name] && ![file isdirectory
$name]} {
721 set auto_execs
($name) [list $name]
723 return $auto_execs($name)
725 foreach dir
[split $env(PATH
) :] {
729 set file [file join $dir $name]
730 if {[file executable
$file] && ![file isdirectory
$file]} {
731 set auto_execs
($name) [list $file]
732 return $auto_execs($name)
740 # ::tcl::CopyDirectory --
742 # This procedure is called by Tcl's core when attempts to call the
743 # filesystem's copydirectory function fail. The semantics of the call
744 # are that 'dest' does not yet exist, i.e. dest should become the exact
745 # image of src. If dest does exist, we throw an error.
747 # Note that making changes to this procedure can change the results
748 # of running Tcl's tests.
751 # action - "renaming" or "copying"
752 # src - source directory
753 # dest - destination directory
754 proc tcl
::CopyDirectory {action src dest
} {
755 set nsrc
[file normalize
$src]
756 set ndest
[file normalize
$dest]
758 if {$action eq
"renaming"} {
759 # Can't rename volumes. We could give a more precise
760 # error message here, but that would break the test suite.
761 if {$nsrc in
[file volumes
]} {
762 return -code error "error $action \"$src\" to\
763 \"$dest\": trying to rename a volume or move a directory\
767 if {[file exists
$dest]} {
768 if {$nsrc eq
$ndest} {
769 return -code error "error $action \"$src\" to\
770 \"$dest\": trying to rename a volume or move a directory\
773 if {$action eq
"copying"} {
774 # We used to throw an error here, but, looking more closely
775 # at the core copy code in tclFCmd.c, if the destination
776 # exists, then we should only call this function if -force
777 # is true, which means we just want to over-write. So,
778 # the following code is now commented out.
780 # return -code error "error $action \"$src\" to\
781 # \"$dest\": file already exists"
783 # Depending on the platform, and on the current
784 # working directory, the directories '.', '..'
785 # can be returned in various combinations. Anyway,
786 # if any other file is returned, we must signal an error.
787 set existing
[glob -nocomplain -directory $dest * .
*]
788 lappend existing
{*}[glob -nocomplain -directory $dest \
790 foreach s
$existing {
791 if {([file tail
$s] ne
".") && ([file tail
$s] ne
"..")} {
792 return -code error "error $action \"$src\" to\
793 \"$dest\": file already exists"
798 if {[string first
$nsrc $ndest] != -1} {
799 set srclen
[expr {[llength [file split $nsrc]] -1}]
800 set ndest
[lindex [file split $ndest] $srclen]
801 if {$ndest eq
[file tail
$nsrc]} {
802 return -code error "error $action \"$src\" to\
803 \"$dest\": trying to rename a volume or move a directory\
809 # Have to be careful to capture both visible and hidden files.
810 # We will also be more generous to the file system and not
811 # assume the hidden and non-hidden lists are non-overlapping.
813 # On Unix 'hidden' files begin with '.'. On other platforms
814 # or filesystems hidden files may have other interpretations.
815 set filelist
[concat [glob -nocomplain -directory $src *] \
816 [glob -nocomplain -directory $src -types hidden
*]]
818 foreach s
[lsort -unique $filelist] {
819 if {([file tail
$s] ne
".") && ([file tail
$s] ne
"..")} {
820 file copy
-force $s [file join $dest [file tail
$s]]