3 # Default system startup file for Tcl-based applications. Defines
4 # "unknown" procedure and auto-load facilities.
6 # Copyright (c) 1991-1993 The Regents of the University of California.
7 # Copyright (c) 1994-1996 Sun Microsystems, Inc.
8 # Copyright (c) 1998-1999 Scriptics Corporation.
9 # Copyright (c) 2004 by Kevin B. Kenny. All rights reserved.
11 # See the file "license.terms" for information on usage and redistribution
12 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
15 if {[info commands
package] == ""} {
16 error "version mismatch: library\nscripts expect Tcl version 7.5b1 or later but the loaded version is\nonly [info patchlevel]"
18 package require
-exact Tcl 8.5.13
20 # Compute the auto path to use in this interpreter.
21 # The values on the path come from several locations:
23 # The environment variable TCLLIBPATH
25 # tcl_library, which is the directory containing this init.tcl script.
26 # [tclInit] (Tcl_Init()) searches around for the directory containing this
27 # init.tcl and defines tcl_library to that location before sourcing it.
29 # The parent directory of tcl_library. Adding the parent
30 # means that packages in peer directories will be found automatically.
32 # Also add the directory ../lib relative to the directory where the
33 # executable is located. This is meant to find binary packages for the
34 # same architecture as the current executable.
36 # tcl_pkgPath, which is set by the platform-specific initialization routines
37 # On UNIX it is compiled in
38 # On Windows, it is not used
40 if {![info exists auto_path
]} {
41 if {[info exists env
(TCLLIBPATH
)]} {
42 set auto_path
$env(TCLLIBPATH
)
49 foreach Dir
[list $::tcl_library [file dirname
$::tcl_library]] {
50 if {$Dir ni
$::auto_path} {
51 lappend ::auto_path $Dir
54 set Dir
[file join [file dirname
[file dirname
\
55 [info nameofexecutable
]]] lib
]
56 if {$Dir ni
$::auto_path} {
57 lappend ::auto_path $Dir
60 foreach Dir
$::tcl_pkgPath {
61 if {$Dir ni
$::auto_path} {
62 lappend ::auto_path $Dir
67 if {![interp issafe
]} {
68 variable Path
[encoding dirs
]
69 set Dir
[file join $::tcl_library encoding]
76 # TIP #255 min and max functions
77 namespace eval mathfunc
{
79 if {[llength $args] == 0} {
81 "too few arguments to math function \"min\""
85 # This will handle forcing the numeric value without
86 # ruining the internal type of a numeric object
87 if {[catch {expr {double
($arg)}} err
]} {
88 return -code error $err
90 if {$arg < $val} { set val
$arg }
95 if {[llength $args] == 0} {
97 "too few arguments to math function \"max\""
101 # This will handle forcing the numeric value without
102 # ruining the internal type of a numeric object
103 if {[catch {expr {double
($arg)}} err
]} {
104 return -code error $err
106 if {$arg > $val} { set val
$arg }
110 namespace export min max
114 # Windows specific end of initialization
116 if {(![interp issafe
]) && ($tcl_platform(platform
) eq
"windows")} {
118 proc EnvTraceProc
{lo n1 n2 op
} {
121 set ::env([string toupper
$lo]) $x
124 global env tcl_platform
125 foreach p
[array names env
] {
126 set u
[string toupper
$p]
131 if {![info exists env
($u)]} {
134 trace add
variable env
($p) write
\
135 [namespace code
[list EnvTraceProc
$p]]
136 trace add
variable env
($u) write
\
137 [namespace code
[list EnvTraceProc
$p]]
142 if {![info exists env
(COMSPEC
)]} {
143 if {$tcl_platform(os
) eq
"Windows NT"} {
144 set env
(COMSPEC
) cmd.exe
146 set env
(COMSPEC
) command.com
154 # Setup the unknown package handler
157 if {[interp issafe
]} {
158 package unknown {::tcl::tm::UnknownHandler ::tclPkgUnknown}
160 # Set up search for Tcl Modules (TIP #189).
161 # and setup platform specific unknown package handlers
162 if {$::tcl_platform(os
) eq
"Darwin"
163 && $::tcl_platform(platform
) eq
"unix"} {
164 package unknown {::tcl::tm::UnknownHandler \
165 {::tcl::MacOSXPkgUnknown ::tclPkgUnknown}}
167 package unknown {::tcl::tm::UnknownHandler ::tclPkgUnknown}
170 # Set up the 'clock' ensemble
172 namespace eval ::tcl::clock [list variable TclLibDir
$::tcl_library]
175 namespace eval ::tcl::clock [list namespace ensemble create
-command \
176 [uplevel 1 [list namespace origin
[lindex [info level
0] 0]]] \
178 add clicks
format microseconds milliseconds
scan seconds
181 # Auto-loading stubs for 'clock.tcl'
183 foreach cmd
{add
format scan} {
184 proc ::tcl::clock::$cmd args
{
186 source -encoding utf-8
[file join $TclLibDir clock.tcl
]
187 return [uplevel 1 [info level
0]]
191 return [uplevel 1 [info level
0]]
195 # Conditionalize for presence of exec.
197 if {[namespace which
-command exec] eq
""} {
199 # Some machines do not have exec. Also, on all
200 # platforms, safe interpreters do not have exec.
205 # Define a log command (which can be overwitten to log errors
206 # differently, specially when stderr is not available)
208 if {[namespace which
-command tclLog
] eq
""} {
209 proc tclLog
{string} {
210 catch {puts stderr
$string}
215 # This procedure is called when a Tcl command is invoked that doesn't
216 # exist in the interpreter. It takes the following steps to make the
219 # 1. See if the command has the form "namespace inscope ns cmd" and
220 # if so, concatenate its arguments onto the end and evaluate it.
221 # 2. See if the autoload facility can locate the command in a
222 # Tcl script file. If so, load it and execute it.
223 # 3. If the command was invoked interactively at top-level:
224 # (a) see if the command exists as an executable UNIX program.
225 # If so, "exec" the command.
226 # (b) see if the command requests csh-like history substitution
227 # in one of the common forms !!, !<number>, or ^old^new. If
228 # so, emulate csh's history substitution.
229 # (c) see if the command is a unique abbreviation for another
230 # command. If so, invoke the command.
233 # args - A list whose elements are the words of the original
234 # command, including the command name.
237 variable ::tcl::UnknownPending
238 global auto_noexec auto_noload env tcl_interactive
240 # If the command word has the form "namespace inscope ns cmd"
241 # then concatenate its arguments onto the end and evaluate it.
243 set cmd
[lindex $args 0]
244 if {[regexp "^:*namespace\[ \t\n\]+inscope" $cmd] && [llength $cmd] == 4} {
245 #return -code error "You need an {*}"
246 set arglist
[lrange $args 1 end
]
247 set ret
[catch {uplevel 1 ::$cmd $arglist} result opts
]
248 dict
unset opts
-errorinfo
249 dict
incr opts
-level
250 return -options $opts $result
253 catch {set savedErrorInfo
$::errorInfo}
254 catch {set savedErrorCode
$::errorCode}
256 if {![info exists auto_noload
]} {
258 # Make sure we're not trying to load the same proc twice.
260 if {[info exists UnknownPending
($name)]} {
261 return -code error "self-referential recursion\
262 in \"unknown\" for command \"$name\"";
264 set UnknownPending
($name) pending
;
266 auto_load $name [uplevel 1 {::namespace current
}]
268 unset UnknownPending
($name);
270 dict
append opts
-errorinfo "\n (autoloading \"$name\")"
271 return -options $opts $msg
273 if {![array size UnknownPending
]} {
277 if {[info exists savedErrorCode
]} {
278 set ::errorCode $savedErrorCode
280 unset -nocomplain ::errorCode
282 if {[info exists savedErrorInfo
]} {
283 set ::errorInfo $savedErrorInfo
285 unset -nocomplain ::errorInfo
287 set code
[catch {uplevel 1 $args} msg opts
]
290 # Compute stack trace contribution from the [uplevel].
291 # Note the dependence on how Tcl_AddErrorInfo, etc.
292 # construct the stack trace.
294 set errorInfo
[dict get
$opts -errorinfo]
295 set errorCode
[dict get
$opts -errorcode]
297 if {[string bytelength
$cinfo] > 150} {
298 set cinfo
[string range
$cinfo 0 150]
299 while {[string bytelength
$cinfo] > 150} {
300 set cinfo
[string range
$cinfo 0 end-1
]
304 append cinfo
"\"\n (\"uplevel\" body line 1)"
305 append cinfo
"\n invoked from within"
306 append cinfo
"\n\"uplevel 1 \$args\""
308 # Try each possible form of the stack trace
309 # and trim the extra contribution from the matching case
311 set expect
"$msg\n while executing\n\"$cinfo"
312 if {$errorInfo eq
$expect} {
314 # The stack has only the eval from the expanded command
315 # Do not generate any stack trace here.
317 dict
unset opts
-errorinfo
318 dict
incr opts
-level
319 return -options $opts $msg
322 # Stack trace is nested, trim off just the contribution
323 # from the extra "eval" of $args due to the "catch" above.
325 set expect
"\n invoked from within\n\"$cinfo"
326 set exlen
[string length
$expect]
327 set eilen
[string length
$errorInfo]
328 set i
[expr {$eilen - $exlen - 1}]
329 set einfo
[string range
$errorInfo 0 $i]
331 # For now verify that $errorInfo consists of what we are about
332 # to return plus what we expected to trim off.
334 if {$errorInfo ne
"$einfo$expect"} {
335 error "Tcl bug: unexpected stack trace in \"unknown\"" {} \
336 [list CORE UNKNOWN BADTRACE
$einfo $expect $errorInfo]
338 return -code error -errorcode $errorCode \
339 -errorinfo $einfo $msg
341 dict
incr opts
-level
342 return -options $opts $msg
347 if {([info level
] == 1) && ([info script
] eq
"") \
348 && [info exists tcl_interactive
] && $tcl_interactive} {
349 if {![info exists auto_noexec
]} {
350 set new
[auto_execok $name]
353 if {[namespace which
-command console] eq
""} {
354 set redir
">&@stdout <@stdin"
356 uplevel 1 [list ::catch \
357 [concat exec $redir $new [lrange $args 1 end
]] \
358 ::tcl::UnknownResult ::tcl::UnknownOptions]
359 dict
incr ::tcl::UnknownOptions -level
360 return -options $::tcl::UnknownOptions $::tcl::UnknownResult
364 set newcmd
[history event]
365 } elseif
{[regexp {^
!(.
+)$} $name -> event]} {
366 set newcmd
[history event $event]
367 } elseif
{[regexp {^
\^
([^^
]*)\^
([^^
]*)\^?
$} $name -> old new
]} {
368 set newcmd
[history event -1]
369 catch {regsub -all -- $old $newcmd $new newcmd
}
371 if {[info exists newcmd
]} {
373 history change
$newcmd 0
374 uplevel 1 [list ::catch $newcmd \
375 ::tcl::UnknownResult ::tcl::UnknownOptions]
376 dict
incr ::tcl::UnknownOptions -level
377 return -options $::tcl::UnknownOptions $::tcl::UnknownResult
380 set ret
[catch {set candidates
[info commands
$name*]} msg
]
385 dict
append opts
-errorinfo \
386 "\n (expanding command prefix \"$name\" in unknown)"
387 return -options $opts $msg
389 # Filter out bogus matches when $name contained
390 # a glob-special char [Bug 946952]
392 # Handle empty $name separately due to strangeness
393 # in [string first] (See RFE 1243354)
397 foreach x
$candidates {
398 if {[string first
$name $x] == 0} {
403 if {[llength $cmds] == 1} {
404 uplevel 1 [list ::catch [lreplace $args 0 0 [lindex $cmds 0]] \
405 ::tcl::UnknownResult ::tcl::UnknownOptions]
406 dict
incr ::tcl::UnknownOptions -level
407 return -options $::tcl::UnknownOptions $::tcl::UnknownResult
409 if {[llength $cmds]} {
410 return -code error "ambiguous command name \"$name\": [lsort $cmds]"
413 return -code error "invalid command name \"$name\""
417 # Checks a collection of library directories to see if a procedure
418 # is defined in one of them. If so, it sources the appropriate
419 # library file to create the procedure. Returns 1 if it successfully
420 # loaded the procedure, 0 otherwise.
423 # cmd - Name of the command to find and load.
424 # namespace (optional) The namespace where the command is being used - must be
425 # a canonical namespace as returned [namespace current]
426 # for instance. If not given, namespace current is used.
428 proc auto_load {cmd
{namespace {}}} {
429 global auto_index auto_path
431 if {$namespace eq
""} {
432 set namespace [uplevel 1 [list ::namespace current
]]
434 set nameList
[auto_qualify $cmd $namespace]
435 # workaround non canonical auto_index entries that might be around
436 # from older auto_mkindex versions
437 lappend nameList
$cmd
438 foreach name
$nameList {
439 if {[info exists auto_index
($name)]} {
440 namespace eval :: $auto_index($name)
441 # There's a couple of ways to look for a command of a given
442 # name. One is to use
443 # info commands $name
444 # Unfortunately, if the name has glob-magic chars in it like *
445 # or [], it may not match. For our purposes here, a better
447 # namespace which -command $name
448 if {[namespace which
-command $name] ne
""} {
453 if {![info exists auto_path
]} {
457 if {![auto_load_index
]} {
460 foreach name
$nameList {
461 if {[info exists auto_index
($name)]} {
462 namespace eval :: $auto_index($name)
463 if {[namespace which
-command $name] ne
""} {
472 # Loads the contents of tclIndex files on the auto_path directory
473 # list. This is usually invoked within auto_load to load the index
474 # of available commands. Returns 1 if the index is loaded, and 0 if
475 # the index is already loaded and up to date.
480 proc auto_load_index
{} {
481 variable ::tcl::auto_oldpath
482 global auto_index auto_path
484 if {[info exists auto_oldpath
] && ($auto_oldpath eq
$auto_path)} {
487 set auto_oldpath
$auto_path
489 # Check if we are a safe interpreter. In that case, we support only
490 # newer format tclIndex files.
492 set issafe
[interp issafe
]
493 for {set i
[expr {[llength $auto_path] - 1}]} {$i >= 0} {incr i
-1} {
494 set dir
[lindex $auto_path $i]
497 catch {source [file join $dir tclIndex
]}
498 } elseif
{[catch {set f
[open [file join $dir tclIndex
]]}]} {
503 if {$id eq
"# Tcl autoload index file, version 2.0"} {
505 } elseif
{$id eq
"# Tcl autoload index file: each line identifies a Tcl"} {
506 while {[gets $f line
] >= 0} {
507 if {([string index
$line 0] eq
"#") \
508 ||
([llength $line] != 2)} {
511 set name
[lindex $line 0]
512 set auto_index
($name) \
513 "source [file join $dir [lindex $line 1]]"
516 error "[file join $dir tclIndex] isn't a proper Tcl index file"
523 return -options $opts $msg
532 # Compute a fully qualified names list for use in the auto_index array.
533 # For historical reasons, commands in the global namespace do not have leading
534 # :: in the index key. The list has two elements when the command name is
535 # relative (no leading ::) and the namespace is not the global one. Otherwise
536 # only one name is returned (and searched in the auto_index).
539 # cmd The command name. Can be any name accepted for command
540 # invocations (Like "foo::::bar").
541 # namespace The namespace where the command is being used - must be
542 # a canonical namespace as returned by [namespace current]
545 proc auto_qualify {cmd
namespace} {
547 # count separators and clean them up
548 # (making sure that foo:::::bar will be treated as foo::bar)
549 set n
[regsub -all {::+} $cmd :: cmd
]
551 # Ignore namespace if the name starts with ::
552 # Handle special case of only leading ::
554 # Before each return case we give an example of which category it is
555 # with the following form :
556 # ( inputCmd, inputNameSpace) -> output
558 if {[string match
::* $cmd]} {
560 # ( ::foo::bar , * ) -> ::foo::bar
563 # ( ::global , * ) -> global
564 return [list [string range
$cmd 2 end
]]
568 # Potentially returning 2 elements to try :
569 # (if the current namespace is not the global one)
572 if {$namespace eq
"::"} {
573 # ( nocolons , :: ) -> nocolons
576 # ( nocolons , ::sub ) -> ::sub::nocolons nocolons
577 return [list ${namespace}::$cmd $cmd]
579 } elseif
{$namespace eq
"::"} {
580 # ( foo::bar , :: ) -> ::foo::bar
583 # ( foo::bar , ::sub ) -> ::sub::foo::bar ::foo::bar
584 return [list ${namespace}::$cmd ::$cmd]
590 # Invoked during "namespace import" to make see if the imported commands
591 # reside in an autoloaded library. If so, the commands are loaded so
592 # that they will be available for the import links. If not, then this
593 # procedure does nothing.
596 # pattern The pattern of commands being imported (like "foo::*")
597 # a canonical namespace as returned by [namespace current]
599 proc auto_import {pattern
} {
602 # If no namespace is specified, this will be an error case
604 if {![string match
*::* $pattern]} {
608 set ns
[uplevel 1 [list ::namespace current
]]
609 set patternList
[auto_qualify $pattern $ns]
613 foreach pattern
$patternList {
614 foreach name
[array names auto_index
$pattern] {
615 if {([namespace which
-command $name] eq
"")
616 && ([namespace qualifiers
$pattern] eq
[namespace qualifiers
$name])} {
617 namespace eval :: $auto_index($name)
625 # Returns string that indicates name of program to execute if
626 # name corresponds to a shell builtin or an executable in the
627 # Windows search path, or "" otherwise. Builds an associative
628 # array auto_execs that caches information about previous checks,
632 # name - Name of a command.
634 if {$tcl_platform(platform
) eq
"windows"} {
637 # Note that info executable doesn't work under Windows, so we have to
638 # look for files with .exe, .com, or .bat extensions. Also, the path
639 # may be in the Path or PATH environment variables, and path
640 # components are separated with semicolons, not colons as under Unix.
642 proc auto_execok name
{
643 global auto_execs env tcl_platform
645 if {[info exists auto_execs
($name)]} {
646 return $auto_execs($name)
648 set auto_execs
($name) ""
650 set shellBuiltins
[list cls copy date del erase dir echo mkdir
\
651 md
rename ren rmdir rd
time type ver vol
]
652 if {$tcl_platform(os
) eq
"Windows NT"} {
653 # NT includes the 'start' built-in
654 lappend shellBuiltins
"start"
656 if {[info exists env
(PATHEXT
)]} {
657 # Add an initial ; to have the {} extension check first.
658 set execExtensions
[split ";$env(PATHEXT)" ";"]
660 set execExtensions
[list {} .com .exe .bat .cmd
]
663 if {[string tolower
$name] in
$shellBuiltins} {
664 # When this is command.com for some reason on Win2K, Tcl won't
665 # exec it unless the case is right, which this corrects. COMSPEC
666 # may not point to a real file, so do the check.
667 set cmd
$env(COMSPEC
)
668 if {[file exists
$cmd]} {
669 set cmd
[file attributes
$cmd -shortname]
671 return [set auto_execs
($name) [list $cmd /c
$name]]
674 if {[llength [file split $name]] != 1} {
675 foreach ext
$execExtensions {
676 set file ${name
}${ext
}
677 if {[file exists
$file] && ![file isdirectory
$file]} {
678 return [set auto_execs
($name) [list $file]]
684 set path
"[file dirname [info nameof]];.;"
685 if {[info exists env
(WINDIR
)]} {
686 set windir
$env(WINDIR
)
688 if {[info exists windir
]} {
689 if {$tcl_platform(os
) eq
"Windows NT"} {
690 append path
"$windir/system32;"
692 append path
"$windir/system;$windir;"
695 foreach var
{PATH Path path
} {
696 if {[info exists env
($var)]} {
697 append path
";$env($var)"
701 foreach ext
$execExtensions {
702 unset -nocomplain checked
703 foreach dir
[split $path {;}] {
704 # Skip already checked directories
705 if {[info exists checked
($dir)] ||
($dir eq
{})} {
709 set file [file join $dir ${name
}${ext
}]
710 if {[file exists
$file] && ![file isdirectory
$file]} {
711 return [set auto_execs
($name) [list $file]]
721 proc auto_execok name
{
722 global auto_execs env
724 if {[info exists auto_execs
($name)]} {
725 return $auto_execs($name)
727 set auto_execs
($name) ""
728 if {[llength [file split $name]] != 1} {
729 if {[file executable
$name] && ![file isdirectory
$name]} {
730 set auto_execs
($name) [list $name]
732 return $auto_execs($name)
734 foreach dir
[split $env(PATH
) :] {
738 set file [file join $dir $name]
739 if {[file executable
$file] && ![file isdirectory
$file]} {
740 set auto_execs
($name) [list $file]
741 return $auto_execs($name)
749 # ::tcl::CopyDirectory --
751 # This procedure is called by Tcl's core when attempts to call the
752 # filesystem's copydirectory function fail. The semantics of the call
753 # are that 'dest' does not yet exist, i.e. dest should become the exact
754 # image of src. If dest does exist, we throw an error.
756 # Note that making changes to this procedure can change the results
757 # of running Tcl's tests.
760 # action - "renaming" or "copying"
761 # src - source directory
762 # dest - destination directory
763 proc tcl
::CopyDirectory {action src dest
} {
764 set nsrc
[file normalize
$src]
765 set ndest
[file normalize
$dest]
767 if {$action eq
"renaming"} {
768 # Can't rename volumes. We could give a more precise
769 # error message here, but that would break the test suite.
770 if {$nsrc in
[file volumes
]} {
771 return -code error "error $action \"$src\" to\
772 \"$dest\": trying to rename a volume or move a directory\
776 if {[file exists
$dest]} {
777 if {$nsrc eq
$ndest} {
778 return -code error "error $action \"$src\" to\
779 \"$dest\": trying to rename a volume or move a directory\
782 if {$action eq
"copying"} {
783 # We used to throw an error here, but, looking more closely
784 # at the core copy code in tclFCmd.c, if the destination
785 # exists, then we should only call this function if -force
786 # is true, which means we just want to over-write. So,
787 # the following code is now commented out.
789 # return -code error "error $action \"$src\" to\
790 # \"$dest\": file already exists"
792 # Depending on the platform, and on the current
793 # working directory, the directories '.', '..'
794 # can be returned in various combinations. Anyway,
795 # if any other file is returned, we must signal an error.
796 set existing
[glob -nocomplain -directory $dest * .
*]
797 lappend existing
{*}[glob -nocomplain -directory $dest \
799 foreach s
$existing {
800 if {([file tail
$s] ne
".") && ([file tail
$s] ne
"..")} {
801 return -code error "error $action \"$src\" to\
802 \"$dest\": file already exists"
807 if {[string first
$nsrc $ndest] != -1} {
808 set srclen
[expr {[llength [file split $nsrc]] -1}]
809 set ndest
[lindex [file split $ndest] $srclen]
810 if {$ndest eq
[file tail
$nsrc]} {
811 return -code error "error $action \"$src\" to\
812 \"$dest\": trying to rename a volume or move a directory\
818 # Have to be careful to capture both visible and hidden files.
819 # We will also be more generous to the file system and not
820 # assume the hidden and non-hidden lists are non-overlapping.
822 # On Unix 'hidden' files begin with '.'. On other platforms
823 # or filesystems hidden files may have other interpretations.
824 set filelist
[concat [glob -nocomplain -directory $src *] \
825 [glob -nocomplain -directory $src -types hidden
*]]
827 foreach s
[lsort -unique $filelist] {
828 if {([file tail
$s] ne
".") && ([file tail
$s] ne
"..")} {
829 file copy
-force $s [file join $dest [file tail
$s]]