Version 6 of Command completion

Updated 2005-08-15 21:29:45

Richard Suchenwirth 2002-07-29 - The behavior of some shells (even including cmd.exe!) to complete commands or filenames on <Tab> is occasionally asked from Tcl too. Here is a quick shot of a mini-console with an entry, that does command completion, a label where multiple alternatives are shown, and a text widget where the command and its result (or error message) are displayed when <Return> was hit:


 proc complete {varName infoName} {
     upvar 1 $varName var
     upvar 1 $infoName info
     if {[llength $var]==1} {
         set cmds [info commands $var*]
         if {[llength $cmds]==1} {
             set var "$cmds " ;# added complementary blank
         } elseif {[llength $cmds]>1} {
             set info [lsort $cmds] ;# make choices available for display
             set var [longestCommonPrefix $cmds] ;# partial completion (1)
         } else bell
     }
 }

# (1): longestCommonPrefix is available on Additional string functions

 entry .e -textvar entry
 bind .e <Tab> {complete entry info; %W icursor end; break}
 bind .e <Return> {catch $entry res; .t insert end "%% $entry\n$res\n"}
 label .info -textvar info -anchor w -width 60
 text .t
 pack .e .info  -fill x
 pack .t        -fill both -expand 1 

Further extensions that one could add:

  • try subcommands for well-known commands like string, package, info, ...
  • if a word starts with $, check [info vars] of the rest of string
  • try glob on other than first word

tkcon has routines for expanding pathnames, command names and variable names (::tkcon::Expand* in the code). These have also been carried over into the updated console of the Tcl core.


Command completion in the iFile console


Arts and crafts of Tcl-Tk programming