3 # Default system startup file for Tcl-based applications. Defines
4 # "unknown" procedure and auto-load facilities.
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.5a6
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 # Handle empty $name separately due to strangeness in [string first]
409 if {[llength $candidates] != 1} {
410 return -code error "empty command name \"\""
412 # It's not really possible to reach here.
413 return [uplevel 1 [lreplace $args 0 0 [lindex $candidates 0]]]
415 # Filter out bogus matches when $name contained
416 # a glob-special char [Bug 946952]
418 foreach x
$candidates {
419 if {[string first
$name $x] == 0} {
423 if {[llength $cmds] == 1} {
424 uplevel 1 [list ::catch [lreplace $args 0 0 [lindex $cmds 0]] \
425 ::tcl::UnknownResult ::tcl::UnknownOptions]
426 dict
incr ::tcl::UnknownOptions -level
427 return -options $::tcl::UnknownOptions $::tcl::UnknownResult
429 if {[llength $cmds]} {
430 return -code error "ambiguous command name \"$name\": [lsort $cmds]"
433 return -code error "invalid command name \"$name\""
437 # Checks a collection of library directories to see if a procedure
438 # is defined in one of them. If so, it sources the appropriate
439 # library file to create the procedure. Returns 1 if it successfully
440 # loaded the procedure, 0 otherwise.
443 # cmd - Name of the command to find and load.
444 # namespace (optional) The namespace where the command is being used - must be
445 # a canonical namespace as returned [namespace current]
446 # for instance. If not given, namespace current is used.
448 proc auto_load {cmd
{namespace {}}} {
449 global auto_index auto_path
451 if {$namespace eq
""} {
452 set namespace [uplevel 1 [list ::namespace current
]]
454 set nameList
[auto_qualify $cmd $namespace]
455 # workaround non canonical auto_index entries that might be around
456 # from older auto_mkindex versions
457 lappend nameList
$cmd
458 foreach name
$nameList {
459 if {[info exists auto_index
($name)]} {
460 namespace eval :: $auto_index($name)
461 # There's a couple of ways to look for a command of a given
462 # name. One is to use
463 # info commands $name
464 # Unfortunately, if the name has glob-magic chars in it like *
465 # or [], it may not match. For our purposes here, a better
467 # namespace which -command $name
468 if {[namespace which
-command $name] ne
""} {
473 if {![info exists auto_path
]} {
477 if {![auto_load_index
]} {
480 foreach name
$nameList {
481 if {[info exists auto_index
($name)]} {
482 namespace eval :: $auto_index($name)
483 if {[namespace which
-command $name] ne
""} {
492 # Loads the contents of tclIndex files on the auto_path directory
493 # list. This is usually invoked within auto_load to load the index
494 # of available commands. Returns 1 if the index is loaded, and 0 if
495 # the index is already loaded and up to date.
500 proc auto_load_index
{} {
501 variable ::tcl::auto_oldpath
502 global auto_index auto_path
504 if {[info exists auto_oldpath
] && ($auto_oldpath eq
$auto_path)} {
507 set auto_oldpath
$auto_path
509 # Check if we are a safe interpreter. In that case, we support only
510 # newer format tclIndex files.
512 set issafe
[interp issafe
]
513 for {set i
[expr {[llength $auto_path] - 1}]} {$i >= 0} {incr i
-1} {
514 set dir
[lindex $auto_path $i]
517 catch {source [file join $dir tclIndex
]}
518 } elseif
{[catch {set f
[open [file join $dir tclIndex
]]}]} {
523 if {$id eq
"# Tcl autoload index file, version 2.0"} {
525 } elseif
{$id eq
"# Tcl autoload index file: each line identifies a Tcl"]} {
526 while {[gets $f line
] >= 0} {
527 if {([string index
$line 0] eq
"#") \
528 ||
([llength $line] != 2)} {
531 set name
[lindex $line 0]
532 set auto_index
($name) \
533 "source [file join $dir [lindex $line 1]]"
536 error "[file join $dir tclIndex] isn't a proper Tcl index file"
543 return -options $opts $msg
552 # Compute a fully qualified names list for use in the auto_index array.
553 # For historical reasons, commands in the global namespace do not have leading
554 # :: in the index key. The list has two elements when the command name is
555 # relative (no leading ::) and the namespace is not the global one. Otherwise
556 # only one name is returned (and searched in the auto_index).
559 # cmd The command name. Can be any name accepted for command
560 # invocations (Like "foo::::bar").
561 # namespace The namespace where the command is being used - must be
562 # a canonical namespace as returned by [namespace current]
565 proc auto_qualify {cmd
namespace} {
567 # count separators and clean them up
568 # (making sure that foo:::::bar will be treated as foo::bar)
569 set n
[regsub -all {::+} $cmd :: cmd
]
571 # Ignore namespace if the name starts with ::
572 # Handle special case of only leading ::
574 # Before each return case we give an example of which category it is
575 # with the following form :
576 # ( inputCmd, inputNameSpace) -> output
578 if {[string match
::* $cmd]} {
580 # ( ::foo::bar , * ) -> ::foo::bar
583 # ( ::global , * ) -> global
584 return [list [string range
$cmd 2 end
]]
588 # Potentially returning 2 elements to try :
589 # (if the current namespace is not the global one)
592 if {$namespace eq
"::"} {
593 # ( nocolons , :: ) -> nocolons
596 # ( nocolons , ::sub ) -> ::sub::nocolons nocolons
597 return [list ${namespace}::$cmd $cmd]
599 } elseif
{$namespace eq
"::"} {
600 # ( foo::bar , :: ) -> ::foo::bar
603 # ( foo::bar , ::sub ) -> ::sub::foo::bar ::foo::bar
604 return [list ${namespace}::$cmd ::$cmd]
610 # Invoked during "namespace import" to make see if the imported commands
611 # reside in an autoloaded library. If so, the commands are loaded so
612 # that they will be available for the import links. If not, then this
613 # procedure does nothing.
616 # pattern The pattern of commands being imported (like "foo::*")
617 # a canonical namespace as returned by [namespace current]
619 proc auto_import {pattern
} {
622 # If no namespace is specified, this will be an error case
624 if {![string match
*::* $pattern]} {
628 set ns
[uplevel 1 [list ::namespace current
]]
629 set patternList
[auto_qualify $pattern $ns]
633 foreach pattern
$patternList {
634 foreach name
[array names auto_index
$pattern] {
635 if {([namespace which
-command $name] eq
"")
636 && ([namespace qualifiers
$pattern] eq
[namespace qualifiers
$name])} {
637 namespace eval :: $auto_index($name)
645 # Returns string that indicates name of program to execute if
646 # name corresponds to a shell builtin or an executable in the
647 # Windows search path, or "" otherwise. Builds an associative
648 # array auto_execs that caches information about previous checks,
652 # name - Name of a command.
654 if {$tcl_platform(platform
) eq
"windows"} {
657 # Note that info executable doesn't work under Windows, so we have to
658 # look for files with .exe, .com, or .bat extensions. Also, the path
659 # may be in the Path or PATH environment variables, and path
660 # components are separated with semicolons, not colons as under Unix.
662 proc auto_execok name
{
663 global auto_execs env tcl_platform
665 if {[info exists auto_execs
($name)]} {
666 return $auto_execs($name)
668 set auto_execs
($name) ""
670 set shellBuiltins
[list cls copy date del erase dir echo mkdir
\
671 md
rename ren rmdir rd
time type ver vol
]
672 if {$tcl_platform(os
) eq
"Windows NT"} {
673 # NT includes the 'start' built-in
674 lappend shellBuiltins
"start"
676 if {[info exists env
(PATHEXT
)]} {
677 # Add an initial ; to have the {} extension check first.
678 set execExtensions
[split ";$env(PATHEXT)" ";"]
680 set execExtensions
[list {} .com .exe .bat
]
683 if {$name in
$shellBuiltins} {
684 # When this is command.com for some reason on Win2K, Tcl won't
685 # exec it unless the case is right, which this corrects. COMSPEC
686 # may not point to a real file, so do the check.
687 set cmd
$env(COMSPEC
)
688 if {[file exists
$cmd]} {
689 set cmd
[file attributes
$cmd -shortname]
691 return [set auto_execs
($name) [list $cmd /c
$name]]
694 if {[llength [file split $name]] != 1} {
695 foreach ext
$execExtensions {
696 set file ${name
}${ext
}
697 if {[file exists
$file] && ![file isdirectory
$file]} {
698 return [set auto_execs
($name) [list $file]]
704 set path
"[file dirname [info nameof]];.;"
705 if {[info exists env
(WINDIR
)]} {
706 set windir
$env(WINDIR
)
708 if {[info exists windir
]} {
709 if {$tcl_platform(os
) eq
"Windows NT"} {
710 append path
"$windir/system32;"
712 append path
"$windir/system;$windir;"
715 foreach var
{PATH Path path
} {
716 if {[info exists env
($var)]} {
717 append path
";$env($var)"
721 foreach dir
[split $path {;}] {
722 # Skip already checked directories
723 if {[info exists checked
($dir)] ||
($dir eq
{})} { continue }
725 foreach ext
$execExtensions {
726 set file [file join $dir ${name
}${ext
}]
727 if {[file exists
$file] && ![file isdirectory
$file]} {
728 return [set auto_execs
($name) [list $file]]
738 proc auto_execok name
{
739 global auto_execs env
741 if {[info exists auto_execs
($name)]} {
742 return $auto_execs($name)
744 set auto_execs
($name) ""
745 if {[llength [file split $name]] != 1} {
746 if {[file executable
$name] && ![file isdirectory
$name]} {
747 set auto_execs
($name) [list $name]
749 return $auto_execs($name)
751 foreach dir
[split $env(PATH
) :] {
755 set file [file join $dir $name]
756 if {[file executable
$file] && ![file isdirectory
$file]} {
757 set auto_execs
($name) [list $file]
758 return $auto_execs($name)
766 # ::tcl::CopyDirectory --
768 # This procedure is called by Tcl's core when attempts to call the
769 # filesystem's copydirectory function fail. The semantics of the call
770 # are that 'dest' does not yet exist, i.e. dest should become the exact
771 # image of src. If dest does exist, we throw an error.
773 # Note that making changes to this procedure can change the results
774 # of running Tcl's tests.
777 # action - "renaming" or "copying"
778 # src - source directory
779 # dest - destination directory
780 proc tcl
::CopyDirectory {action src dest
} {
781 set nsrc
[file normalize
$src]
782 set ndest
[file normalize
$dest]
784 if {$action eq
"renaming"} {
785 # Can't rename volumes. We could give a more precise
786 # error message here, but that would break the test suite.
787 if {$nsrc in
[file volumes
]} {
788 return -code error "error $action \"$src\" to\
789 \"$dest\": trying to rename a volume or move a directory\
793 if {[file exists
$dest]} {
794 if {$nsrc eq
$ndest} {
795 return -code error "error $action \"$src\" to\
796 \"$dest\": trying to rename a volume or move a directory\
799 if {$action eq
"copying"} {
800 # We used to throw an error here, but, looking more closely
801 # at the core copy code in tclFCmd.c, if the destination
802 # exists, then we should only call this function if -force
803 # is true, which means we just want to over-write. So,
804 # the following code is now commented out.
806 # return -code error "error $action \"$src\" to\
807 # \"$dest\": file already exists"
809 # Depending on the platform, and on the current
810 # working directory, the directories '.', '..'
811 # can be returned in various combinations. Anyway,
812 # if any other file is returned, we must signal an error.
813 set existing
[glob -nocomplain -directory $dest * .
*]
814 lappend existing
{*}[glob -nocomplain -directory $dest \
816 foreach s
$existing {
817 if {([file tail
$s] ne
".") && ([file tail
$s] ne
"..")} {
818 return -code error "error $action \"$src\" to\
819 \"$dest\": file already exists"
824 if {[string first
$nsrc $ndest] != -1} {
825 set srclen
[expr {[llength [file split $nsrc]] -1}]
826 set ndest
[lindex [file split $ndest] $srclen]
827 if {$ndest eq
[file tail
$nsrc]} {
828 return -code error "error $action \"$src\" to\
829 \"$dest\": trying to rename a volume or move a directory\
835 # Have to be careful to capture both visible and hidden files.
836 # We will also be more generous to the file system and not
837 # assume the hidden and non-hidden lists are non-overlapping.
839 # On Unix 'hidden' files begin with '.'. On other platforms
840 # or filesystems hidden files may have other interpretations.
841 set filelist
[concat [glob -nocomplain -directory $src *] \
842 [glob -nocomplain -directory $src -types hidden
*]]
844 foreach s
[lsort -unique $filelist] {
845 if {([file tail
$s] ne
".") && ([file tail
$s] ne
"..")} {
846 file copy
-force $s [file join $dest [file tail
$s]]