3 # Default system startup file for Tcl-based applications. Defines
4 # "unknown" procedure and auto-load facilities.
6 # RCS: @(#) $Id: init.tcl,v 1.96 2007/10/26 15:17:56 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.5b2
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 # Set up the 'chan' ensemble (TIP #208).
80 # TIP #219. Added methods: create, postevent.
81 # TIP 287. Added method: pending.
82 namespace ensemble create
-command ::chan -map {
83 blocked
::tcl::chan::blocked
84 close ::tcl::chan::close
85 configure
::tcl::chan::configure
86 copy
::tcl::chan::copy
87 create
::tcl::chan::rCreate
89 event ::tcl::chan::event
90 flush ::tcl::chan::flush
91 gets ::tcl::chan::gets
92 names
{::file channels
}
93 pending
::tcl::chan::Pending
94 postevent
::tcl::chan::rPostevent
95 puts ::tcl::chan::puts
96 read ::tcl::chan::read
97 seek ::tcl::chan::seek
98 tell ::tcl::chan::tell
99 truncate
::tcl::chan::Truncate
103 # TIP #255 min and max functions
104 namespace eval mathfunc
{
106 if {[llength $args] == 0} {
108 "too few arguments to math function \"min\""
112 # This will handle forcing the numeric value without
113 # ruining the internal type of a numeric object
114 if {[catch {expr {double
($arg)}} err
]} {
115 return -code error $err
117 if {$arg < $val} { set val
$arg }
122 if {[llength $args] == 0} {
124 "too few arguments to math function \"max\""
128 # This will handle forcing the numeric value without
129 # ruining the internal type of a numeric object
130 if {[catch {expr {double
($arg)}} err
]} {
131 return -code error $err
133 if {$arg > $val} { set val
$arg }
140 # Windows specific end of initialization
142 if {(![interp issafe
]) && ($tcl_platform(platform
) eq
"windows")} {
144 proc EnvTraceProc
{lo n1 n2 op
} {
147 set ::env([string toupper
$lo]) $x
150 global env tcl_platform
151 foreach p
[array names env
] {
152 set u
[string toupper
$p]
157 if {![info exists env
($u)]} {
160 trace add
variable env
($p) write
\
161 [namespace code
[list EnvTraceProc
$p]]
162 trace add
variable env
($u) write
\
163 [namespace code
[list EnvTraceProc
$p]]
168 if {![info exists env
(COMSPEC
)]} {
169 if {$tcl_platform(os
) eq
"Windows NT"} {
170 set env
(COMSPEC
) cmd.exe
172 set env
(COMSPEC
) command.com
180 # Setup the unknown package handler
183 if {[interp issafe
]} {
184 package unknown ::tclPkgUnknown
186 # Set up search for Tcl Modules (TIP #189).
187 # and setup platform specific unknown package handlers
188 if {$::tcl_platform(os
) eq
"Darwin"
189 && $::tcl_platform(platform
) eq
"unix"} {
190 package unknown {::tcl::tm::UnknownHandler \
191 {::tcl::MacOSXPkgUnknown ::tclPkgUnknown}}
193 package unknown {::tcl::tm::UnknownHandler ::tclPkgUnknown}
196 # Set up the 'clock' ensemble
198 namespace eval ::tcl::clock [list variable TclLibDir
$::tcl_library]
201 namespace eval ::tcl::clock [list namespace ensemble create
-command \
202 [uplevel 1 [list namespace origin
[lindex [info level
0] 0]]] \
204 add clicks
format microseconds milliseconds
scan seconds
207 # Auto-loading stubs for 'clock.tcl'
209 foreach cmd
{add
format scan} {
210 proc ::tcl::clock::$cmd args
{
212 source -encoding utf-8
[file join $TclLibDir clock.tcl
]
213 return [uplevel 1 [info level
0]]
217 return [uplevel 1 [info level
0]]
221 # Conditionalize for presence of exec.
223 if {[namespace which
-command exec] eq
""} {
225 # Some machines do not have exec. Also, on all
226 # platforms, safe interpreters do not have exec.
231 # Define a log command (which can be overwitten to log errors
232 # differently, specially when stderr is not available)
234 if {[namespace which
-command tclLog
] eq
""} {
235 proc tclLog
{string} {
236 catch {puts stderr
$string}
241 # This procedure is called when a Tcl command is invoked that doesn't
242 # exist in the interpreter. It takes the following steps to make the
245 # 1. See if the command has the form "namespace inscope ns cmd" and
246 # if so, concatenate its arguments onto the end and evaluate it.
247 # 2. See if the autoload facility can locate the command in a
248 # Tcl script file. If so, load it and execute it.
249 # 3. If the command was invoked interactively at top-level:
250 # (a) see if the command exists as an executable UNIX program.
251 # If so, "exec" the command.
252 # (b) see if the command requests csh-like history substitution
253 # in one of the common forms !!, !<number>, or ^old^new. If
254 # so, emulate csh's history substitution.
255 # (c) see if the command is a unique abbreviation for another
256 # command. If so, invoke the command.
259 # args - A list whose elements are the words of the original
260 # command, including the command name.
263 variable ::tcl::UnknownPending
264 global auto_noexec auto_noload env tcl_interactive
266 # If the command word has the form "namespace inscope ns cmd"
267 # then concatenate its arguments onto the end and evaluate it.
269 set cmd
[lindex $args 0]
270 if {[regexp "^:*namespace\[ \t\n\]+inscope" $cmd] && [llength $cmd] == 4} {
271 #return -code error "You need an {*}"
272 set arglist
[lrange $args 1 end
]
273 set ret
[catch {uplevel 1 ::$cmd $arglist} result opts
]
274 dict
unset opts
-errorinfo
275 dict
incr opts
-level
276 return -options $opts $result
279 catch {set savedErrorInfo
$::errorInfo}
280 catch {set savedErrorCode
$::errorCode}
282 if {![info exists auto_noload
]} {
284 # Make sure we're not trying to load the same proc twice.
286 if {[info exists UnknownPending
($name)]} {
287 return -code error "self-referential recursion\
288 in \"unknown\" for command \"$name\"";
290 set UnknownPending
($name) pending
;
292 auto_load $name [uplevel 1 {::namespace current
}]
294 unset UnknownPending
($name);
296 dict
append opts
-errorinfo "\n (autoloading \"$name\")"
297 return -options $opts $msg
299 if {![array size UnknownPending
]} {
303 catch {set ::errorCode $savedErrorCode}
304 catch {set ::errorInfo $savedErrorInfo}
305 set code
[catch {uplevel 1 $args} msg opts
]
308 # Compute stack trace contribution from the [uplevel].
309 # Note the dependence on how Tcl_AddErrorInfo, etc.
310 # construct the stack trace.
312 set errorInfo
[dict get
$opts -errorinfo]
313 set errorCode
[dict get
$opts -errorcode]
315 if {[string bytelength
$cinfo] > 150} {
316 set cinfo
[string range
$cinfo 0 150]
317 while {[string bytelength
$cinfo] > 150} {
318 set cinfo
[string range
$cinfo 0 end-1
]
322 append cinfo
"\"\n (\"uplevel\" body line 1)"
323 append cinfo
"\n invoked from within"
324 append cinfo
"\n\"uplevel 1 \$args\""
326 # Try each possible form of the stack trace
327 # and trim the extra contribution from the matching case
329 set expect
"$msg\n while executing\n\"$cinfo"
330 if {$errorInfo eq
$expect} {
332 # The stack has only the eval from the expanded command
333 # Do not generate any stack trace here.
335 dict
unset opts
-errorinfo
336 dict
incr opts
-level
337 return -options $opts $msg
340 # Stack trace is nested, trim off just the contribution
341 # from the extra "eval" of $args due to the "catch" above.
343 set expect
"\n invoked from within\n\"$cinfo"
344 set exlen
[string length
$expect]
345 set eilen
[string length
$errorInfo]
346 set i
[expr {$eilen - $exlen - 1}]
347 set einfo
[string range
$errorInfo 0 $i]
349 # For now verify that $errorInfo consists of what we are about
350 # to return plus what we expected to trim off.
352 if {$errorInfo ne
"$einfo$expect"} {
353 error "Tcl bug: unexpected stack trace in \"unknown\"" {} \
354 [list CORE UNKNOWN BADTRACE
$einfo $expect $errorInfo]
356 return -code error -errorcode $errorCode \
357 -errorinfo $einfo $msg
359 dict
incr opts
-level
360 return -options $opts $msg
365 if {([info level
] == 1) && ([info script
] eq
"") \
366 && [info exists tcl_interactive
] && $tcl_interactive} {
367 if {![info exists auto_noexec
]} {
368 set new
[auto_execok $name]
371 if {[namespace which
-command console] eq
""} {
372 set redir
">&@stdout <@stdin"
374 uplevel 1 [list ::catch \
375 [concat exec $redir $new [lrange $args 1 end
]] \
376 ::tcl::UnknownResult ::tcl::UnknownOptions]
377 dict
incr ::tcl::UnknownOptions -level
378 return -options $::tcl::UnknownOptions $::tcl::UnknownResult
382 set newcmd
[history event]
383 } elseif
{[regexp {^
!(.
+)$} $name -> event]} {
384 set newcmd
[history event $event]
385 } elseif
{[regexp {^
\^
([^^
]*)\^
([^^
]*)\^?
$} $name -> old new
]} {
386 set newcmd
[history event -1]
387 catch {regsub -all -- $old $newcmd $new newcmd
}
389 if {[info exists newcmd
]} {
391 history change
$newcmd 0
392 uplevel 1 [list ::catch $newcmd \
393 ::tcl::UnknownResult ::tcl::UnknownOptions]
394 dict
incr ::tcl::UnknownOptions -level
395 return -options $::tcl::UnknownOptions $::tcl::UnknownResult
398 set ret
[catch {set candidates
[info commands
$name*]} msg
]
403 dict
append opts
-errorinfo \
404 "\n (expanding command prefix \"$name\" in unknown)"
405 return -options $opts $msg
407 # Filter out bogus matches when $name contained
408 # a glob-special char [Bug 946952]
410 # Handle empty $name separately due to strangeness
411 # in [string first] (See RFE 1243354)
415 foreach x
$candidates {
416 if {[string first
$name $x] == 0} {
421 if {[llength $cmds] == 1} {
422 uplevel 1 [list ::catch [lreplace $args 0 0 [lindex $cmds 0]] \
423 ::tcl::UnknownResult ::tcl::UnknownOptions]
424 dict
incr ::tcl::UnknownOptions -level
425 return -options $::tcl::UnknownOptions $::tcl::UnknownResult
427 if {[llength $cmds]} {
428 return -code error "ambiguous command name \"$name\": [lsort $cmds]"
431 return -code error "invalid command name \"$name\""
435 # Checks a collection of library directories to see if a procedure
436 # is defined in one of them. If so, it sources the appropriate
437 # library file to create the procedure. Returns 1 if it successfully
438 # loaded the procedure, 0 otherwise.
441 # cmd - Name of the command to find and load.
442 # namespace (optional) The namespace where the command is being used - must be
443 # a canonical namespace as returned [namespace current]
444 # for instance. If not given, namespace current is used.
446 proc auto_load {cmd
{namespace {}}} {
447 global auto_index auto_path
449 if {$namespace eq
""} {
450 set namespace [uplevel 1 [list ::namespace current
]]
452 set nameList
[auto_qualify $cmd $namespace]
453 # workaround non canonical auto_index entries that might be around
454 # from older auto_mkindex versions
455 lappend nameList
$cmd
456 foreach name
$nameList {
457 if {[info exists auto_index
($name)]} {
458 namespace eval :: $auto_index($name)
459 # There's a couple of ways to look for a command of a given
460 # name. One is to use
461 # info commands $name
462 # Unfortunately, if the name has glob-magic chars in it like *
463 # or [], it may not match. For our purposes here, a better
465 # namespace which -command $name
466 if {[namespace which
-command $name] ne
""} {
471 if {![info exists auto_path
]} {
475 if {![auto_load_index
]} {
478 foreach name
$nameList {
479 if {[info exists auto_index
($name)]} {
480 namespace eval :: $auto_index($name)
481 if {[namespace which
-command $name] ne
""} {
490 # Loads the contents of tclIndex files on the auto_path directory
491 # list. This is usually invoked within auto_load to load the index
492 # of available commands. Returns 1 if the index is loaded, and 0 if
493 # the index is already loaded and up to date.
498 proc auto_load_index
{} {
499 variable ::tcl::auto_oldpath
500 global auto_index auto_path
502 if {[info exists auto_oldpath
] && ($auto_oldpath eq
$auto_path)} {
505 set auto_oldpath
$auto_path
507 # Check if we are a safe interpreter. In that case, we support only
508 # newer format tclIndex files.
510 set issafe
[interp issafe
]
511 for {set i
[expr {[llength $auto_path] - 1}]} {$i >= 0} {incr i
-1} {
512 set dir
[lindex $auto_path $i]
515 catch {source [file join $dir tclIndex
]}
516 } elseif
{[catch {set f
[open [file join $dir tclIndex
]]}]} {
521 if {$id eq
"# Tcl autoload index file, version 2.0"} {
523 } elseif
{$id eq
"# Tcl autoload index file: each line identifies a Tcl"} {
524 while {[gets $f line
] >= 0} {
525 if {([string index
$line 0] eq
"#") \
526 ||
([llength $line] != 2)} {
529 set name
[lindex $line 0]
530 set auto_index
($name) \
531 "source [file join $dir [lindex $line 1]]"
534 error "[file join $dir tclIndex] isn't a proper Tcl index file"
541 return -options $opts $msg
550 # Compute a fully qualified names list for use in the auto_index array.
551 # For historical reasons, commands in the global namespace do not have leading
552 # :: in the index key. The list has two elements when the command name is
553 # relative (no leading ::) and the namespace is not the global one. Otherwise
554 # only one name is returned (and searched in the auto_index).
557 # cmd The command name. Can be any name accepted for command
558 # invocations (Like "foo::::bar").
559 # namespace The namespace where the command is being used - must be
560 # a canonical namespace as returned by [namespace current]
563 proc auto_qualify {cmd
namespace} {
565 # count separators and clean them up
566 # (making sure that foo:::::bar will be treated as foo::bar)
567 set n
[regsub -all {::+} $cmd :: cmd
]
569 # Ignore namespace if the name starts with ::
570 # Handle special case of only leading ::
572 # Before each return case we give an example of which category it is
573 # with the following form :
574 # ( inputCmd, inputNameSpace) -> output
576 if {[string match
::* $cmd]} {
578 # ( ::foo::bar , * ) -> ::foo::bar
581 # ( ::global , * ) -> global
582 return [list [string range
$cmd 2 end
]]
586 # Potentially returning 2 elements to try :
587 # (if the current namespace is not the global one)
590 if {$namespace eq
"::"} {
591 # ( nocolons , :: ) -> nocolons
594 # ( nocolons , ::sub ) -> ::sub::nocolons nocolons
595 return [list ${namespace}::$cmd $cmd]
597 } elseif
{$namespace eq
"::"} {
598 # ( foo::bar , :: ) -> ::foo::bar
601 # ( foo::bar , ::sub ) -> ::sub::foo::bar ::foo::bar
602 return [list ${namespace}::$cmd ::$cmd]
608 # Invoked during "namespace import" to make see if the imported commands
609 # reside in an autoloaded library. If so, the commands are loaded so
610 # that they will be available for the import links. If not, then this
611 # procedure does nothing.
614 # pattern The pattern of commands being imported (like "foo::*")
615 # a canonical namespace as returned by [namespace current]
617 proc auto_import {pattern
} {
620 # If no namespace is specified, this will be an error case
622 if {![string match
*::* $pattern]} {
626 set ns
[uplevel 1 [list ::namespace current
]]
627 set patternList
[auto_qualify $pattern $ns]
631 foreach pattern
$patternList {
632 foreach name
[array names auto_index
$pattern] {
633 if {([namespace which
-command $name] eq
"")
634 && ([namespace qualifiers
$pattern] eq
[namespace qualifiers
$name])} {
635 namespace eval :: $auto_index($name)
643 # Returns string that indicates name of program to execute if
644 # name corresponds to a shell builtin or an executable in the
645 # Windows search path, or "" otherwise. Builds an associative
646 # array auto_execs that caches information about previous checks,
650 # name - Name of a command.
652 if {$tcl_platform(platform
) eq
"windows"} {
655 # Note that info executable doesn't work under Windows, so we have to
656 # look for files with .exe, .com, or .bat extensions. Also, the path
657 # may be in the Path or PATH environment variables, and path
658 # components are separated with semicolons, not colons as under Unix.
660 proc auto_execok name
{
661 global auto_execs env tcl_platform
663 if {[info exists auto_execs
($name)]} {
664 return $auto_execs($name)
666 set auto_execs
($name) ""
668 set shellBuiltins
[list cls copy date del erase dir echo mkdir
\
669 md
rename ren rmdir rd
time type ver vol
]
670 if {$tcl_platform(os
) eq
"Windows NT"} {
671 # NT includes the 'start' built-in
672 lappend shellBuiltins
"start"
674 if {[info exists env
(PATHEXT
)]} {
675 # Add an initial ; to have the {} extension check first.
676 set execExtensions
[split ";$env(PATHEXT)" ";"]
678 set execExtensions
[list {} .com .exe .bat
]
681 if {$name in
$shellBuiltins} {
682 # When this is command.com for some reason on Win2K, Tcl won't
683 # exec it unless the case is right, which this corrects. COMSPEC
684 # may not point to a real file, so do the check.
685 set cmd
$env(COMSPEC
)
686 if {[file exists
$cmd]} {
687 set cmd
[file attributes
$cmd -shortname]
689 return [set auto_execs
($name) [list $cmd /c
$name]]
692 if {[llength [file split $name]] != 1} {
693 foreach ext
$execExtensions {
694 set file ${name
}${ext
}
695 if {[file exists
$file] && ![file isdirectory
$file]} {
696 return [set auto_execs
($name) [list $file]]
702 set path
"[file dirname [info nameof]];.;"
703 if {[info exists env
(WINDIR
)]} {
704 set windir
$env(WINDIR
)
706 if {[info exists windir
]} {
707 if {$tcl_platform(os
) eq
"Windows NT"} {
708 append path
"$windir/system32;"
710 append path
"$windir/system;$windir;"
713 foreach var
{PATH Path path
} {
714 if {[info exists env
($var)]} {
715 append path
";$env($var)"
719 foreach dir
[split $path {;}] {
720 # Skip already checked directories
721 if {[info exists checked
($dir)] ||
($dir eq
{})} { continue }
723 foreach ext
$execExtensions {
724 set file [file join $dir ${name
}${ext
}]
725 if {[file exists
$file] && ![file isdirectory
$file]} {
726 return [set auto_execs
($name) [list $file]]
736 proc auto_execok name
{
737 global auto_execs env
739 if {[info exists auto_execs
($name)]} {
740 return $auto_execs($name)
742 set auto_execs
($name) ""
743 if {[llength [file split $name]] != 1} {
744 if {[file executable
$name] && ![file isdirectory
$name]} {
745 set auto_execs
($name) [list $name]
747 return $auto_execs($name)
749 foreach dir
[split $env(PATH
) :] {
753 set file [file join $dir $name]
754 if {[file executable
$file] && ![file isdirectory
$file]} {
755 set auto_execs
($name) [list $file]
756 return $auto_execs($name)
764 # ::tcl::CopyDirectory --
766 # This procedure is called by Tcl's core when attempts to call the
767 # filesystem's copydirectory function fail. The semantics of the call
768 # are that 'dest' does not yet exist, i.e. dest should become the exact
769 # image of src. If dest does exist, we throw an error.
771 # Note that making changes to this procedure can change the results
772 # of running Tcl's tests.
775 # action - "renaming" or "copying"
776 # src - source directory
777 # dest - destination directory
778 proc tcl
::CopyDirectory {action src dest
} {
779 set nsrc
[file normalize
$src]
780 set ndest
[file normalize
$dest]
782 if {$action eq
"renaming"} {
783 # Can't rename volumes. We could give a more precise
784 # error message here, but that would break the test suite.
785 if {$nsrc in
[file volumes
]} {
786 return -code error "error $action \"$src\" to\
787 \"$dest\": trying to rename a volume or move a directory\
791 if {[file exists
$dest]} {
792 if {$nsrc eq
$ndest} {
793 return -code error "error $action \"$src\" to\
794 \"$dest\": trying to rename a volume or move a directory\
797 if {$action eq
"copying"} {
798 # We used to throw an error here, but, looking more closely
799 # at the core copy code in tclFCmd.c, if the destination
800 # exists, then we should only call this function if -force
801 # is true, which means we just want to over-write. So,
802 # the following code is now commented out.
804 # return -code error "error $action \"$src\" to\
805 # \"$dest\": file already exists"
807 # Depending on the platform, and on the current
808 # working directory, the directories '.', '..'
809 # can be returned in various combinations. Anyway,
810 # if any other file is returned, we must signal an error.
811 set existing
[glob -nocomplain -directory $dest * .
*]
812 lappend existing
{*}[glob -nocomplain -directory $dest \
814 foreach s
$existing {
815 if {([file tail
$s] ne
".") && ([file tail
$s] ne
"..")} {
816 return -code error "error $action \"$src\" to\
817 \"$dest\": file already exists"
822 if {[string first
$nsrc $ndest] != -1} {
823 set srclen
[expr {[llength [file split $nsrc]] -1}]
824 set ndest
[lindex [file split $ndest] $srclen]
825 if {$ndest eq
[file tail
$nsrc]} {
826 return -code error "error $action \"$src\" to\
827 \"$dest\": trying to rename a volume or move a directory\
833 # Have to be careful to capture both visible and hidden files.
834 # We will also be more generous to the file system and not
835 # assume the hidden and non-hidden lists are non-overlapping.
837 # On Unix 'hidden' files begin with '.'. On other platforms
838 # or filesystems hidden files may have other interpretations.
839 set filelist
[concat [glob -nocomplain -directory $src *] \
840 [glob -nocomplain -directory $src -types hidden
*]]
842 foreach s
[lsort -unique $filelist] {
843 if {([file tail
$s] ne
".") && ([file tail
$s] ne
"..")} {
844 file copy
-force $s [file join $dest [file tail
$s]]