Ask, and it shall be given # 13

How to post on this page

Please do not edit this part, it is meant as a guide!

This page runs the risk of being deleted and corrupted. Please be very careful when editing it. If you inadvertently delete it, immediately revert your edit using the History link on the left side of this page.

Do NOT attempt to restore it by copying and pasting the text from a previous revision, or all page formatting will be lost!

Please put new questions at the TOP of the page, below this section, so that as the page grows longer, new questions are seen first.

Also please put a section header on top of every question and put two stars in the beginning of the title and two stars in the end. This will make your question's section easily editable.

Once you have received a satisfactory answer, please cut your question and answer directly on an appropriate page of the wiki. If you cannot find an existing page, create a new one.

You might also simply want to put a hyperlink leading to a page of the wiki where your question is included. This will save you the trouble of cutting your question to an existing page afterwards.

Put your question below. Thanks!


Did the [exec] semantics on MS Windows change between Version 8.6.8 and 8.6.9?

A rarely used feature in one of my applications relies on an external commandline tool started from Tcl and running inside an MS Windows command window, and I'm using an environment variable to pass some of the data needed there. I guess I must've been using Tcl version 8.6.6 for way to long, but now that I've gone to 8.6.12, this doesn't work as expected any more.

I think that some strange tinkering must have happened to the quoting of the individual command arguments somewhere between 8.6.8 and 8.6.9, because this tcl command which I managed to boil my problem down to

exec cmd /c start /belownormal cmd /k for %x in ( %PATH% ) do echo %x &

still gives me, as it always did, a command window which shows each individual PATH entry in a separate line on 8.6.8, but I don't even see a command window appear whenever I try to use 8.6.9 or above (I tested using several different Tclkits found on Ashok Nadkarni's TWAPI repository).

And if I simply try to do

exec cmd /c start /belownormal cmd /k echo %PATH%

on 8.6.9 and above, then I get a command window showing the strangely quoted output ""%"PATH"%"" instead of the PATH variable's value.

This suggests to me that someone must've explicitly added quoting to prevent the accidental use of Windows variables. If that's true, then which local fix might allow me to access these variables now, without resorting to external batch files - and why was no extra command option added to switch back to the old behavior? I always prefer to keep the code managing one single thing in one single place, and furthermore, I'm accessing my Tcl sources from a network path which the Windows console isn't prepared to deal with, and thus I might need to go at some lengths to come up with a new general infrastructure.


I'm trying to create a Tcl Client for neovim, which should be pretty simple.

I use these packages:

* *

The code is pretty straightforward:

package require msgpack                                                                                                                                                                                                                     
package require unix_sockets  

set sockname $::env(NVIM_LISTEN_ADDRESS)

proc on_reply {id} {                                                                                                                                                                                                                        
  # {{{
  set p_result [gets $id]                                                                                                                                                                                                                   
  #puts "receive: $p_result"

  set u [msgpack::unpacker new]
  set result [$u unpack_string $p_result]
  puts "received: $result"                                                                                                                                                                                                                  
  $u destroy                                                                                                                                                                                                                                

  set ::complete true
  # }}}                                                                                                                                                                                                                                     

proc debugMsg {p} {
  # {{{
  set u [msgpack::unpacker new]                                                                                                                                                                                                             
  puts [$u unpack_string [$p data]]                                                                                                                                                                                                         
  $u destroy
  # }}}

proc callNvimCommand {sock} {                                                                                                                                                                                                               
  # {{{
  set p [msgpack::packer new]
  $p pack array 4
  $p pack int32 0 ;# type
  $p pack int32 [clock clicks] ;# msgid
  $p pack str {nvim_command} ;# method
  $p pack list str [list {echo 'Hello World!' }]
  #set data [$p data]
  debugMsg $p

  puts $sock [$p data]
  chan flush $sock
  $p destroy
  # }}}

proc getApiInfo {sock} {
  # {{{
  set p [msgpack::packer new]
  $p pack array 4
  $p pack int32 0 ;# type
  $p pack int32 [clock clicks] ;# msgid
  $p pack str {nvim_get_api_info} ;# method
  $p pack array 0

  debugMsg $p

  puts $sock [$p data]
  $p destroy
  chan flush $sock
  # }}}

set sock [unix_sockets::connect $sockname]
chan configure $sock -blocking 1 -buffering none -translation binary -encoding binary

chan event $sock readable [list on_reply $sock]

#getApiInfo $sock
callNvimCommand $sock

puts "--- wating for reply --"

vwait complete

You can copy the code e.g. to hello-nvim.tcl, open it in nvim and execute it with


Calling "getApiInfo" returns a valid result, calling "callNvimCommand" on the other hand returns this error message:

{array {{integer 1} {integer 0} {array {{integer 1} {str {Message is not an array}}}} nil}}

Has anybody succeeded in creating a Tcl client for neovim or has anybody any clue, what might be wrong with my code?

Closed out. Is tcllib library in Sep2021 ActiveTCL most recent copy??

This item is being surfaced with friendly and quality support at

gold9/22/2021 I recently installed ActiveState TCL or ActiveTCL on Windows10. I have been working with ticket additions to tcllib math files. Maybe I am wrong, but the ActiveState installer from the ActiveState website (9/22/2021} installs the old Tcllilb content (Tcllib (tcllib-1.18) of three years ago in 2019. I tried installing the current library content from the plus . It looks like the new content Tcllib tcllib-1.20 is present now, on my local ActiveTCL copy. This installation is very tricky for a 70+ year old novice with bad eyes. And I am not sure that I installed tcllib-1.20 right. Thank You

gold9/22/2022. PS. I double checked this morning and fresh reloaded the ActiveTCL on 9/22/2021 The old library (Tcllib (tcllib-1.18) is still there in a fresh download of ActiveTCL.

  • PS. References. 9/24/2021 I noted the new content tcllib-1.20::math in Tcllib distribution has modules. My local ActiveTCL seems to be pulling the Tcllib:math routines, that I normally use. But my local ActiveTCL copy and setup is not a shakedown cruise on the whole Tcllib deck and TCL core, which is very large with noted modules. Refer to TIP 189: Tcl Modules, Tcl Modules, [L1 ]

gold Closed out on 9/29/2021. "New" Prime number functions working now in local copy of Windows10 ActiveTCL >> Tcllib::new_math. I guess that the interested TCL'ers have seen the Tcllib::new_math filing for their info. Thanks

::math::numtheory::lcm 500 900 ;# returns 4500
numberPrimesGauss 8            ;# returns 3.8471867757039027

Closed out. Suggest Category on Windows_Examples

gold 9/19/2021. Would a wiki category on Windows_Examples_PC, Windows_Specific, or Windows_Console be worthwhile? As separate from Windows Operating system? I really like some opinions. I worked 15 years on Sun Sparcs Unix, so familiar with UNIX, but am a retired engineer now. Curious about the percentage of Unix users vs PC users vs Apple on TCL wiki. Thank You. [L2 ]& [L3 ] & [L4 ]

gold Closed out on 9/29/2021. I guess that the interested TCL'ers have seen the suggestion for their info. Thanks

Closed out. forwarded offsite request, convert image scan to numbers

gold 9/15/2021. forwarded request to TCL WIKI from offsite, convert image scan to numbers.

Verbatim question: Hi, is it possible to convert image to numbers in tcl tk please provide your support.This is not a question is i want identify zero and non zero value on the images.. (supplied photo below)

gold 9/15/2021. Reply. following. XX will not let me post links to the TCL WIKI. But I believe the TCL WIKI has links and "knowing" people to such problems. I worked on some code for graphics program Pixane, which accepted TCL commands.Captioning Photo Image under Pixane Example. Point is, ImageMagick and Pixane are big free graphics programs under TCL commands, which have a learning curve, to be sure. Updated one of my pages on TCL WIKI, but XX will not let me furnish a hard link. Try google search <TCL WIKI image scan barcode> There are hundreds of files related to images on wiki. I will forward request to TCL Wiki request page ASK 13 and see if any fish in basket. Best Wishes

Offsite Member, Thank you. I am using numpy for converting number in python.Is it any similer option in tcl?

gold 9/18/2021. closing out request. Here are the best references on TCL WIKI for your project. If you know how to work numpy on Python, that Python numpy probably is the best option for your project. As you must know, there is a learning curve on any computer language, including Python and TCL, for that matter. There is a massive open source mathematics project SageMath (college doctor level) underscoring TCL and other math languages in Europe, somewhat similar in concept to Mathematica, Matlab, and WolframAlpha But I have limited access to European links under current USA strictures and internet drop outs. The online SageMath commands access in batch mode and have unbelievable wait times, cobwebs and ice cubes develop on brain. Hope you have time to join us on TCL WIKI, reporting on your project. We like to learn things, and if monkey see, monkey do with TCL. Since a few days have passed of the original request, I suppose the TCL'ers have seen your request for their consumption and support, closing out request. Best Wishes

Reference wiki pages on TCL WIKI, --- References

ps, "Scan an EAN-13 barcode from an image" looks similar to your request. What is your application... barcodes??? Please narrow down your search.Go to TCL WIKI and enter your TCL WIKI search engine with your queries. XX does not like long lines of raw code.

Added PS. Check out Blaise Montandon uniquename on . This is a most sophisticated user on TCL WIKI and TCL (free open source, I mean). Montandon offers generous open source files and gui graphical user interfaces on website But there is a high learning curve, if one can catch up to Montandon?

gold Repeat. One has not named the use and application of your image scan. Bar_Code? Code_Steganography? OCR? Please name your application and narrow down your search. I left my mind reading plugs at home.


Solved and Closed out, old edit copy on screen.

gold 9/12/2021

When I come in as unsigned-in , the very first edit on Sep11 comes up on screen. Collatz_Sequences (3*N+1) in Console Example Demo for TCL V2. HE and I have made a bunch of changes to file. Is there some way to update page to latest edit copy, 43 or so. Thank you.

gold 9/27/2021. Closed out. I found out the trick by myself. If one picks Save button, copy goes into holding pattern or possibly quality control. If one picks Save as Minor as Minor Edit Button, the ones current edited copy is updated and appears in current in the current files.


Screen on 9/14/2021, Collatz_Sequences_not_updated_since_9_11, see date tag on bottom


Solved, Early shutdown in while loop.

gold 9/12/2021

Can someone check or proof read while loop in new wiki page Collatz_Sequences (3*N+1) in Console Example Demo for TCL V2. I wish to set variable $iteration as shutdown or early preempt in proc collatz_sequence {number iteration} {} to avoid repeating integers at end of Collatz_Sequences. Otherwise, proc is halfway working with correct Collatz_Sequences. Thank you

HE 2021-09-12: You can find, how I would change your proc collatz_sequence, in the discussion paragraph of Collatz_Sequences (3*N+1) in Console Example Demo for TCL V2. This should cover iteration check and no repeating integers at the end for all numbers ( tested up to today by all people of this world). An error is raised in the very rare case that you found a positive integer not ending up in the sequence 1 4 2 1 4 2 1 ... More likely the number of iterations is set to small if this error happens. There are also some other changes which, I think, would be an improvement.

gold 2021-09-13. Solved problem. The proc collatz_sequence was substantially rewritten by HE and I replaced in the main deck and good feedback comments, which I will have to chew on. Many thanks to [HE}. I checked the proc collatz_sequence in small test suite and proc looks good, so I will pass ticket on to TCLLIB math. I have loaded the ticket e035b93f363dc62153375b77ad3bcf339a68d407 Title: Collatz_Sequence, modified_Collatz_Sequence, posiitve & negative logic test for integers. ---

Solved, odd-even logic tests on positive numbers

gold 9/9/2021

Solved. Can someone provide logic tests for even - odd of positive numbers. Are these logic tests in TCLLIB or reference? if N odd, return 1, if N not odd, return 0. if N even, return 1. If N not even return 0. Thank you

what about :

proc isOdd {int} {
    if {![string is int $int]} {
        error "must be integer"
    if {$int < 0} {
        error "must be positive"
    return [expr $int % 2]

gold Closed out, thanks

Best_Practice? on floating point rounding

gold 7/15/2021

I borrowed some floating point rounding statements circa 2004 from AM in wiki page Floating-point formatting &Rounding in Tcl to write the proc precisionx in Blood+Glucose in 20aug2020 [L5 ]. The TCL language is changing so fast, can someone look this floating point rounding over in proc precisionx? Best_Practice? Thank you

        # proc precisionx used to round off floating point numbers
        set precision 5.
        set float      3.000000000001
        set test_float_2 3.999999999997
        set x [ expr {round( 10 ** $precision * $float) / (10.0 ** $precision)} ]  ;# <AM>
        proc rnd_floating_pt {precision float} { expr {round( 10 ** $precision * $float) / (10.0 ** $precision)}}  ;# <AM>
        proc precisionx {precision float }  {
            #  tcl:wiki:Floating-point formatting, <AM>
            # select numbers only, not used on every number.
            set x [ expr {round( 10 ** $precision * $float) / (10.0 ** $precision)} ]
            #  rounded or clipped to nearest 5ird significant figure
            set x [ format "%#.5g" $x ]
            return $x

reply from 印诚信 off wiki, if you wanna see money-tcl [L6 ]. Its old but still works.

Solved and Closed out, , trouble in saving edits

gold 7/9/2021.Maybe text is non-unix from windows or wrong text in file. Another similar issue on editing, Titius Bode Modeling Planetary Distances using Titius-Bode Law and and TCL demo example calculator, numerical analysis V2 does not seem to be updating over several days. Sorry, I can't understand why Titius-Bode is not being updated in a reasonable day or so, unless there is some security lock on page? My other pages like gold seem to work. thanks.

gold 7/14/20021 , Solved and Closed out,

PARTLY SOLVED: tcc4tcl using tk: tcc: error: undefined symbol 'Tk_FindPhoto'

MiR 07/02/2021 I used Roy Keenes Kitcreator to build a win32 custom 8.6.6 version of tcltk with tcc4tcl included. I'm actually trying to get tcc4tcl to compile some code from photo image equality in Critcl. First I found, that tk.h and all dependencies from tk866 where not automatically in the tclkit, so I put them into vfs and sdx it into a new exe. Sample-Code without tk compiles as exepected, but as soon it comes to Tk things won't work...

Now tcc complains about undefined symbols... any clue what I can do here? Meanwhile I tracked this down a bit. If I manually define USE_TKSTUBS and after that manualy include tk.h ... it stills says undefined symbol tkStubsPtr (though this is defined in tkDecls.h as extern const TkStubs *tkStubsPtr;)

MiR 07/30/2021: Solution (maybe, not sure about any sideeffects...) Solution to me was NOT to link against any tkStubs but include all TK-Headerfiles PLUS tkStubsLib.c, containing a version of Tk_InitStubs... After defining USE_TK_STUBS, adjusting some inlude_paths and calling Tk_InitStubs on the actual interp it magically worked, I now am able to call TK-Routines as expected. Don't know if this is a proper solution, but it's seems to work.

Solved on 7/01/2021. Quadratic equations using TCLLIB

gold 6/29/2021. I am working on wiki page { ]. Can someone point me to a quadratic solution command or proc in TCLLIB? or TCL core. Understand, I have access to Quadratic solution procs in TCL or could write one. But I am looking at the files in TCLLIB math and don't recognize the quadratic solution proc section. Thank you.

AM There is none, if you mean to solve a second-degree equation. The references to "quadratic" in the math module are all for very different entities.

gold 7/2/2012. I'll write a small proc to solve quadratic equations and put a ticket in the TCLLIB que. There was an interesting note on the quadratic equation in [L7 ] & [L8 ] Thank you.

TCLLIB ticket 5af6381a8be0d5a87505d7e28203fe69fa2b3019 in que, dated 7/3/2021
Title:        Quadratic Equation Solution, 2 reals from Muller's method

Reference [L9 ]

Windows specific - run a single instance of script, pin window on the screen?

Wurzelsepp 2021-Jun-19 Hi, I have made an "info window" type script for windows. Is there any way to

a) ensure a second click on its start icon just brings the running copy to front rather than starting a fresh copy

b) pin the window on screen so that covering its window and then closing / minimizing the cover would leave the script in place

Continue script eval at point after error?

JJS 2020-Feb-02 I'm using a safe interp to parse config files; they're user-prepared so they can't be trusted. They consist of commands, some of which may be bad in the sense that they throw errors. I'd like to ignore the bad commands, but continue evaluating any following good commands. I tried variations of this, both in the master and the slave interp, but couldn't get what I want:

try {$interp eval $script} on error {res opt} { ;# or try $script ...
    return -code continue -level 0 ;# tried all combos of -code ok/continue and -level 0/1

Nothing I tried would continue with the eval. My bgerror handler never fired. I finally used a variation of the Verbose Evaluation code at eval. It works pretty well, but fails for scripts like {good; bad; good} with multiple commands on one line. Is there a way to ignore errors in a script *and* continue evaluating it?

P.S. I've taken to "Ask, and it shall be given" because I no longer have work access to chat or c.l.t.

Solved on 10/02/2020. Query: Script taking a long time, maybe Threads in TCL 8.5?

9/25/2020 Forwarding offline request. Will take me some time to find references, but maybe our other members have something to say.

Q. Question? One of my scripts is taking a long time. I need help in going parallelism. it should be tcl8.5. I need help in using TCL tk threas, who can help me here in tcl8.5 version?

A. Answer. gold 9/25/2020 We believe that TCL tk threas = TCL threads??? Suggest upgrade to latest TCL version 8.6, at least. I will compile some references in a bit for you. Program subject is unknown here, suggest check if invoking TCLLIB in subject areas will save about 1/3 time on average. Suggest check on TCL Wiki search engine and search for TCL threads. See list of TCLLIB sections [L10 ] See [L11 ] wiki.tcl

gold 10/26/2020. I have collected some tips on faster code for you. I have not seen your code. But Reposted Tips from AMG & GWM & Wiki and Continuing Reposted Tips from Wiki in [L12 ] may be of help. One would almost have to do a time analysis of individual subroutines and individual lines to find the "core hogs" with the time command. It is sometimes advantageous to write the script into smaller subroutine chunks and organized and structured code subsections for easier detection of "core hogs". A "core hog" in a heap of straw and spaghetti code is more difficult to find, from experience here.

gold 10/02/2020. Forwarded your query to the TCL Wiki on ASK 13 page . This TCL Wiki on ASK 13 page is easier <for me> to type and format an answer.

Solved >> Query on <for loop> ???

gold 10/3/2020 Forwarding offline request.

gold 10/7/2020, Individual could not be contacted and/or answer for further feedback. Loaded available contributions in Parametric Equation Model Vaporware TCL Calculator. Further wiki contributions welcomed on new page, but believe the abundant references on wiki are suitable, if applied.

Solved on 10/02/2020. Query from Russia. Who used small basic interpreters?

Question from AV in Russia. So small basic interpreter... Query. Who used small basic interpreters?

gold 9/25/2020 Forwarding offline request. Will take me some time to find references, but maybe our other members have something to say.

gold 10/02/2020 A. The original tiny basic was distributed in assembler code for the Altair and the 8080 circuit board. Essentially, tiny_basic is a historic legacy of mankind. The original Altair BASIC was about 150 dollars each. Some USA programmers in the 1970s gave away tiny_basic free to break the monopoly. tiny_basic was the first freeware or free software package widely given to the masses (circa 1970). In Russian terms, tiny_basic is the Battleship_Potemkin of computer geeks. Have added wiki page on this issue. [L13 ]

Solved on 9/25/2020. Query: Redirecting tcl output to xls?

gold 09/25/2020. Forwarding offline request. Will take me some time to find references, but maybe our other members have something to say.

 Q. Question. Do you have any proc for redirecting tcl output to xls? I was not able to find proper solution online.

A. gold 9/25/2020 For my hobby work, i usually output to comma delimited format <CVS format > and then use an excel clone to load or change a CVS file into an excel format . I will compile some references in a bit for you. CAWT is a TCL utility package at SourceForge net. This is a high quality package for windows spreadsheets etc, and open source. Suggest check on TCL Wiki search engine and search for excel spreadsheet. See [L14 ] wiki.tcl

A. gold 9/25/2020, CAWT is a TCL utility package at SourceForge net. This is a high quality package for windows spreadsheets etc, and open source.Search Keywords <TCL TK xval CLI generators> This XLS spreadsheet automatically generates TCL/TK command line interfaces for both UNIX and Windows environments. Originally written for xval the program . it generates button and clickbox select front ends for various different command line tools. Blocks of code are then generated from a simple spreadsheet format. The attached powerpoint explains which parts of the Excel spreadsheet generate which bits of TK front end. The generated TK front..CAWT is a utility package based on Twapi to script Microsoft Windows® applications with Tcl. It provides high level procedures for automation via the COM interface.

Currently modules for Excel, Word, PowerPoint, Outlook, Internet Explorer, Office Document Imaging, Matlab, and Google Earth are available.Suggest check on TCL Wiki search engine and search for excel/cvs spreadsheet,[L15 ] & [L16 ] . The sense from a quick survey on internet is that most TCL'ers are ouputting to a CVS format file because CVS is an easier and not a designedly, everchanging format. Also there is a library of TCLLIB commands for CVS. But maybe other members have something to say.

gold 10/02/2020. Forwarded your query to the TCL Wiki on ASK 13 page . This TCL Wiki on ASK 13 page is easier <for me> to type and format an answer.

Solved, Query: Would you so kind to give the TCL Club link?

gold Found on discussion comment in one of my Wiki pages.

aplsimple - 2018-10-08 05:26:38

Would you so kind to give the TCL Club link?

gold . You may be interested in file "Free TCL books and docs from Facebook TCL Club.odt" on TCL Club file system. However, I am not sure this file format is sufficiently clean and presentable for the TCL WIKI.

gold 7/15/2020. end of file.

Suggest link Ask help window on tcl wiki masthead.

gold 10/01/2020. subject. Suggest link Ask help window on tcl wiki masthead. Let me suggest a permanent link to Ask13 or Ask system under the help window on TCL Wiki masthead. The Ask13 pages were a very popular feature of the older wiki format. And newcomers like me learned a lot from either reading the answers of the veteran programmers or attempting to answer the Ask questions themselves. From other TCL forums, I believe a write in user help would pull in some new members. Also,, as one looking to the future of TCl/TK, the subject areas of the questions were interesting to me in how current users were attempting to use TCL. A note in the account of Don Libes on the history of TCL/Expect indicates that Libes was almost shocked by the headwind of users behind TCL/Expect in the early years. I known that the older members are aware of the Ask System, but it occurs to me that some newer members might not . Best Wishes

  • this Ask13 page [L17 ]
  • Don Libes Wikipedia [L18 ]
  • Expect language, Wikipedia [L19 ]
  • Fisher essay [L20 ]
  • Don Libes, Joseph in 7 Years [L21 ]
  • Writing a Tcl Extension in Only ... 7 Years" ,1997

Maybe partially solved, Can Someone can suggest a book and video for learning Tcl_Tk in French???

gold 7/16/2020, Received Query on USA web board, forwarding Report so far. Query:: I was visiting and I like TCL I can make effort even so I'm not fluent in English. Can Someone can suggest a book (and video) for learning Tcl_Tk in French???

gold7/16/2020, There is a version of the TCL WIKI in France. Believe contact with the French TCL WIKI on the "mother ship" would help. Best Wishes-


There are pages of free TCL references, books and docs on the TCL WIKI. There are web search engines for free TCL books and papers that can search on language choice like French, Arabic, Chinese, Hindu, and ones native language, etc. There are automated translators that can translate an English or French book into other languages. Sample from TCL WIKI france. google < wiki tcl francophone >


Tcl en français Extremely good & in French!forum/fr.comp.lang.tcl

(fr) Bernard Desgraupes, Tcl/Tk - Apprentissage et Référence, 2e édition, Vuibert, (ISBN 978-2-7117-4878-5), 2009. Daniel Roche, L'écriture d'interface graphique en Tcl/Tk, GNU Linux Magazine France n°2, Décembre 1998. David Zolli, Découvrez Tclkit, les starkits et les starpacks, GNU Linux Magazine France n°60, avril 2004, pp66-69.7 archive Xavier Garreau, Tcl Avancé, GNU Linux Magazine France n°95, juin 2007, pp82-91. Gérard Sookahet, Les nouveautés de Tcl/Tk 8.6, GNU Linux Magazine France n°165, novembre 2013, pp4-11 8 archive.

gold end of file.

Maybe partially solved, trouble accessing the TCL WIKI from USA on some restaurant WIFI's?

gold 08Jul2020. Don't know if other members of TCL Club have this problem, but the author is having great difficulty in accessing this TCL WIKI from USA on some restaurant WIFI. The TCL WIKI and some other download TCL programming sites on public WIFI are blocked in the USA.

gold8/14/2020. in coordination with ActiveState Support [email protected]. Putting lengthy correspondence on homepage. many thanks for help.

Solved, Invoke TCLLIB library for choose function?

gold 8/4/2020. Statements working to invoke TCLLIB library on ActiveState 8.6.

Solved::math::mean revolts on $lister

gold 8/21/2020. I uploaded program Timing Equivalent One Liners V2 at bottom of Oneliner's Pie in the Sky. Can someone help me with statement? proc ::math::mean is not accepting the list $lister and has to be hard wired with written out list. < proc ::math::mean $lister> calls error out as "expecting floating point", but 3 other one liners are doing fine on list $lister ??? thanks, g

  puts "&|$i | ::math::mean  [::math::mean  1  2  4  5  6  7  8  9  10 [* $i [pie]]] |  $lister | proc timer [ time { set qq    [ ::math::mean  1  2  4  5  6  7  8  9  10 [* $i [pie]] ]}  ]  |&

Solved. Name change on page title?

gold 9/10/2020. Subject: Name change on page title? Body: Can someone change name of wiki page Oneliner's Pie in the Sky to "One Liners Programs Pie in the Sky". Thanks.

gold Solved. 10/19/2020. Just a note. To delete a page, replace its entire contents with a single space. Obviously, feel free to delete this comment when you read it. AM ah, I had forgotten about that feature. {gold] Maybe, to change a page name, add new page with desired name and copy old contents under it. Then in a few days of new page history, zip the old page?

90 second delay deleting file on unix

JJS 2019-Nov-12 Background: I have a Starpack that invokes itself for self-test purposes. On Windows the mounted VFS only shadows the application binary from Tcl's point of view, not in the actual underlying filesystem, so [exec [info nameofexecutable]] or even [exec [file dirname $argv0]] works. Interestingly, the same approach also works in a Red Hat VM under Oracle VirtualBox on a Windows host with file sharing enabled. But in Ubuntu under Windows Subsystem for Linux (WSL) the mounted VFS actually shadows the application binary, so I adapted the clonerun technique to temporarily unmount the VFS so I can make a copy that I can then execute:

proc clone {del args} {
    set testcopy testcopy.exe ;# works for windows or unix
    # Unmount the VFS so the app is exposed in the native filesystem.
    # Adapted from <>.
    set me [info nameofexecutable]
    set info [vfs::filesystem info $me]
    vfs::filesystem unmount $me; puts "unmounted"
    catch {file copy -force $me $testcopy; puts "copied"}
    vfs::filesystem mount $me $info; puts "remounted"
    if {[file exists $testcopy] && [file executable $testcopy]} {
        puts "running"; exec $testcopy {*}$args
        if {$del} {puts "deleting"; time {file delete -force $testcopy}}

That code unmounts the VFS, copies the binary, remounts the VFS, invokes the copy with optional arguments, waits for it to complete, then optionally deletes it. If I run a clone without deleting it, then as soon as the prompt returns I can delete it right away; the delete command was staged on the clipboard so it could be entered very quickly:

(tst) 7 % clone 0 final
(tst) 8 % puts "deleting"; time {file delete -force testcopy.exe}
1097152 microseconds per iteration

As you can see, it took about 1 second to delete the copy, only 1 or 2 seconds after it completed. But if I run a clone and delete it within the clone call, then it takes 88 seconds or so to delete:

(tst) 9 % clone 1 final
88498207 microseconds per iteration

There are a lot of moving parts here: Starpack, VFS, Windows vs. Linux, and TkCon, to name a few, but I can't put my finger on any of them. I've tried things like [update] or [update idletasks] before the delete; delaying it with [after idle], etc., but nothing works reliably. While debugging this problem and trying various fixes, I sometimes get into a situation where deleting the copy from within [clone] goes fast, but I can never tell what triggers it, and it doesn't last through restarting the debugging environment! I especially don't understand why returning to the prompt allows the delete to proceed immediately, but nothing else does. What could be going on here?

MacOS tk send question

Wurzelsepp 2019-Oct-14

I have Activestate tcl installed on a Mac. I tried to use the "rmt" remote commander, but the only app it shows is just itself.

Is there anything special that tcl/tk apps need to be visible

Odd tcom problem

robertlipman 2019-Jul-11 I have a program that I wrap with Tcl Dev Kit. Two Windows versions of the program are created, one with Tk that has a user interface and the other with Tcl that is run from a command prompt. tcom is used to create an object with

set objIFCsvr [::tcom::ref createobject IFCsvr.R300] 

When the object is created, some startup text is generated by IFCsvr.R300 that is displayed in the command prompt window version. I'd like to capture that text in a variable so that it can be processed or suppressed. In the GUI version, I don't know where that startup text from IFCsvr.R300 goes. Again, I'd like to capture it in a variable and process it.

How do I do that?

Windows auto_execok search path irregularity

Duoas 2019-Jul-05 I just had to debug a surprising behavior by auto_execok on Windows: apparently it injects the following paths (if available) to the head of the search path:

  • [info nameof]
  • .
  • %WINDIR%/system32
  • %WINDIR%/system
  • %WINDIR%

This is not correct! Especially injecting the interpreter’s directory before the current working directory in the search path! According to Windows documentation , the correct search path is [pwd] + %PATH%. All those Windows directory additions are also unnecessary; they should normally be in the user's PATH; if they are not it is either a conscious user choice or a user error; being Windows does not justify jumping the path to prefer a Windows program over a user program. This is especially irksome to anyone who (rightly) presumes to control his environment by controlling the PATH!

How long has this been an issue? Can it be corrected? Would something break if the core were corrected? (As it is, I have to code an alternate auto_execok so that my application does not violate the Principle of Least Surprise for my users.)

The offending code is somewhere around lines 670-680 in tcl8.6.7/library/init.tcl, and could be corrected by replacing that section with just

    set path ".;"

It is not unreasonable to find multiple copies of a same-named executable in the path. The path exists to control which one of those executables is loaded when asked, given ambiguity.

open a command pipeline

Wurzelsepp These examples work:

  set f [open "| ls existing_file" r]
  set f [open "| ls missing_file" r]

However, when I try

  set f [open "| ls &" r]

I just find out that there is no "&" file... So, how could I open a slow command in the background? I cannot use exec here. Thanks

EMJ 01 Jun 2019 : Neither exec nor open (with pipeline) use any external shell to process the command, Tcl does that itself. So exec checks for an & as the last element of the command, but open does not because it does not need to - the pipeline is run asynchronously anyway, in one or more separate processes - you can get the process id(s) with the pid command. You might want to look at How to run external script from Tk and make it throw output to the console? - if not using Tk you'll need vwait to get your own event loop if you go with using fileevent. There's also async.

Wurzelsepp Hi, many thanks for the prompt response. The open (or rather its associated close) seems to wait...

  set f [open "|tclsh" w]
  puts $f "exec sleep 100; puts done"
  close $f; ## waits until sleep is over

(EMJ As the close man page says,

If channelId is a blocking channel for a command pipeline then close waits for the child processes to complete.

so you would have to make it non-blocking.)

I tried something I found on the exec manual page, near "reflected channels", using chan pipe (EMJ - exec Wiki page presumably, the exec manual page doesn't mention reflected channels). This seems to do what I want

  lassign [chan pipe] rdc wrc
  exec tclsh <@ $rdc &
  puts $wrc "exec sleep 100; puts done"
  close $wrc; ## returns at once

BTW, this is meant to be called from wish, and I assume that Linux, Win and Mac systems will run a tclsh that matches the active wish - EMJ Under normal circumstances, yes.

Solved. flowchart_text_extraction

gold26Dec2018. Can someone point some refs or post some freeware TCL code on <flowchart_text_extraction> or automated outline of nodes and procs from TCL program, for loading flowchart nodes/outline into the TKpaint.tcl or wheelDiagram.tcl uniquename? An alternate method would be loading a <flowchart_text_extraction> from TCL program into spreadsheet charting tool (OpenOffice.odp? for VU-graphs). I have been using the TKpaint.tcl (freeware) for about ten years for displays and vu-graphs on this TCL-WIKI. TKpaint.tcl has the advantage of saving VU-graph in postscript, readable TCL format, and restarting from a saved chart in TCL format. Possibly, the <flowchart text extraction> could be readable as a saved chart in TKpaint.tcl. I have made 1st test chart from the ASED.tcl editor, 2nd homebrew freehand chart, and both are pretty close to where I would like to start. In opinion, my current wiki pages of guis etc would be more understandable with a flowchart. Thanks.

gold 4Jan2019. Follow-on code to <flowchart_text_extraction>

    # wish to grab title of proc and entries of proc into a list(S) < proc geoseries> and <argumemts aa bb cc >to
    # code into flowchart diagram. but not good on regexp topic. Can one break on the braces?
    # need to get rid of braces in print out
set item { proc geoseries1 {aa bb cc} { if {$bb <= -1||$bb >= 1} { return 0} ;return [ expr $aa / ( 1 - $bb ) ]};  } 
    regexp {proc((.??.*)\})(.*)}  $matched matched2 sub1 sub2 sub3
    puts $matched        
    puts $sub1          
    puts $sub2          
    puts $sub3   
    proc geoseries1 {aa bb cc}
 geoseries1 {aa bb cc}
 geoseries1 {aa bb cc
# need to get rid of braces in print out

old wiki content

gold 1dec2018. Is the link for the old wiki content , still active? If not, what date was it closed? I am clumsy on the browser, but i can not find the old content link. thank you.

Unwanted border around ttk::label

Duoas 2018-10-22 Hello again. I can't figure out how to get rid of a border around a ttk::label. Steps to reproduce:

set image [image create photo]
$image put green -to 0 0 20 20
ttk::label .i -compound image -image $image -background red
place .i -x 10 -y 10

Is there any way to get rid of that red?

Duoas 2018-10-22 19:54Z Heh, always after asking questions you figure out an answer... Gotta configure the layout to get rid of it.

ttk::style layout TMyImageLabel {Label.label -sticky nswe}
.i configure -style TMyImageLabel

All better. :O)

Intercept/Observe command-line -geometry

Duoas 2018-10-16 Hey there. Is there any way to intercept/observe the processing of -geometry arguments at the command line when wish (tclkit) starts, not involving binary extensions or hacking the core?

I would like to permit multiple -geometry options to manage multiple windows (order/matching windows does not matter — they appear as clones). I can query the last supplied geometry with $::geometry, of course. I’ve tried both traces and pkgIndex.tcl trickery, but the Initialize() function in ~/generic/tkWindow.c appears to get called before any kind of user code gets a chance. Is this correct? Am I out of luck here?

If it makes any difference I am packaging in a starkit.

bll 2018-10-16 I think you will have to have the user put the -geometry arguments on the command line after a -- argument and process them yourself. There's no way to have wish do unusual things with its command line arguments.

Duoas 2018-10-22 I have always thought that wish’s gobbling of command-line arguments without any hook for application intervention to be unusual. Only now that I am looking at this again (after many years) do I remember that I had, in fact, looked at this before. And no, there is no escape, so bll’s commentary is correct. The only options are:

  • modify Tk sources and recompile
  • start the application using a loader, which massages the command-line arguments into something Tk won’t gobble.


<<Selection>> event for entry

Hi, has anyone written a script to add selection events like those for text widget to a one-line entry? (Or should I simply create a 1-line text instead?)

Hex String to Double

beware Hi all, I'm trying to decode some files. One of the values I need is stored as a double in hex. Example - "3fb999999999999a" -> "0.1". The double conversion here gets the correct result: currently my code just has the hex stored as a string (as in "set hexstr 3fb999999999999a"). How do I replicate the conversion done on that site?

Martyn Smith The TCL command is binary, you need to convert the hexadecimal string to a binary string with binary format then extract the big endian double from the binary string as follows

  binary scan [binary format H* $hexstr] Q floatValue

The Q is the format code for forced big endian double.

Google Photos

Has anyone written a tcl library that interfaces with Google Photos to allow one to download a "table of contents" of URLs to images and the albums to which they belong?

Image Scaling

MiR 2018-06-28:

On topic image scaling...

I was wondering, if Tk would in the future implement at least a robust image scaling alogrithm like in TkImageTools from (reference see Shrinking an image)? It's just to avoid having to deploy an externel dynamic library just to have an image resized...

AMG I did this just yesterday, but I'm probably not allowed to share the code though. I used libsamplerate [L22 ] to do it. The interface works like this:

[imgscale sourcePhoto targetPhoto ?method?]

sourcePhoto and targetPhoto can be one-, three-, or five-element lists:

operate on full extents of photo
photoName width height
explicit width and height, top left defaults to (0,0)
photoName left top width height
explicit width, height, and top left coordinates

targetPhoto will be expanded (if possible) to accommodate the explicit width and height. Otherwise, the width and height are clipped to the photos' actual width and height. It is an error for left or top to be negative, or for width or height to be non-positive.

method can be sinc, linear, or point, corresponding to libsamplerate's SRC_SINC_FASTEST, SRC_LINEAR, and SRC_ZERO_ORDER_HOLD modes, respectively. (The other two SINC modes are significantly slower and actually look comparatively poor on images.) The default is linear.

Implementation guidelines:

  • Use the Simple API [L23 ] which consists of only the src_simple() function. The more complicated APIs offer no benefit in this application because the image data is all available in advance.
  • Work on one channel (R, G, B, A) at a time. This requires less temporary space and offers better performance due to improved locality of reference and ability to use more optimized single-channel code within libsamplerate.
  • Step 1: Loop over each row of input R, G, B, or A bytes.
  • Step 1a: Convert the input row into a linear buffer of floats.
  • Step 1b: Rescale the width and store into an intermediate float buffer large enough to hold the whole channel.
  • Step 2: Transpose the intermediate buffer so that each column is contiguous in memory.
  • Step 3: Loop over each column of intermediate floats.
  • Step 3a: Rescale the height and store into a linear buffer of floats.
  • Step 3b: Convert the scaled column back into pixel bytes, storing into a pixel buffer large enough for the whole image.
  • Step 4: Use Tk_PhotoPutBlock() to write the pixel buffer to the target photo.

Regarding step 4: The pixel buffer will be divided into separate planes, each of which is transposed. This means the Tk_PhotoImageBlock will have to be arranged as follows:

pitch = 1
pixelSize = height
offset[n] = n * height * width

One other tip. I statically linked libsamplerate into my extension. Another possibility is to incorporate a subset of the source code, removing the unused SINC modes, to avoid their large coefficient tables. (BSD 2-clause license, by the way.)

Duoas 2018-10-19 Actually, was just working on a small binary extension to do the same thing, photo-resample.kit. Permits scaling using nearest neighbor, linear, cubic, box, and hqx algorithms, plus mirror and rotate, plus a few other resampling goodies like sharpen, gaussian blur, colorizing, desaturating, inverting an image, splitting and combining channels and alpha channel manipulations, and origin tracking, all with a very simple interface.

filker0 2019-01-04 Is Duoas's photo-resample.kit available for download? I'm kind of out of touch, and maybe it's a well known location.

VP Trees and nearest neighbor problem

I'm actually thinking about perceptual hashes for images and similarity search. Most implementation point towards using 64bit pHashes and organize them in a so called VP tree (Vantage Point tree), where it would be easy to search for nearest neighbors... Actually, I found a proper algo for pHash and was able to implement it into my program, but since I'm just an amateur coder I thought asking for help from the community with the search implementation. Has anyone ever investigated how to implement VP trees in TCL? I understand the basic function principle but am unable to find a starting point for coding... 2020-10-16 Michael

Tcl_FSOpenFileChannel and fdopen its native FILE* fails with Bad File Descriptor

I played around a bit with Tcl_FSOpenFileChannel and fdopen and found no way, to get a valid filechanel back. Consider following code sample, wich always yields fdopen 176 Bad file descriptor, while Tcl_Read gives back the content of test.txt. What is going on here? Is it me, is it Tcl8.6 or is it soemwhere else to look for the failure? 2022-07-16 MiR

    int _tclfsopen (Tcl_Interp* interp, char* filename)
        char buf[1024];
        int native_fd;
        Tcl_Obj* path = Tcl_NewStringObj(filename,-1);
        Tcl_Channel chan = Tcl_FSOpenFileChannel(interp,path, buf, 0);
        if(chan==NULL) {
            Tcl_AppendResult(interp,"invalid filename",NULL);
            return TCL_ERROR;
        int tcl_ret = Tcl_GetChannelHandle(chan, TCL_READABLE, (void*)&native_fd);
        FILE* f=fdopen(native_fd,"r");
        sprintf(buf,"fdopen %d %s\n",native_fd,strerror(errno));
        int ll=Tcl_Read(chan, buf, 256);
        Tcl_AppendResult(interp,"result of tcl_read\n",NULL);
        return TCL_ERROR;

Answering myself, after some hours on the net... Because you're on Windows, an under win32 Tcl_getChannelHandle doesn't give you a file descriptor. On W32 systems the returned file descriptor is a system handle and not a libc low level I/O file descriptor. Thus applications need to use _open_osfhandle before they can pass this descriptor to standard functions like fdopen or dup.

        int tcl_ret = Tcl_GetChannelHandle(chan, TCL_READABLE, (void*)&native_fd);
#ifdef _WIN32
        FILE* f=fdopen(native_fd,"r");

2023-02-08 MiR TCL bindings for cinvoke anyone? I'm looking for a simple solution to invoke compiled c funtions from tcl. I know about ffidl and cffi, but I'm looking for a more leightweight solution and now stumbled upon wich seems rather dated. Has anyone here worked with cinvoke already? I'll experiment a bit over the next weeks and see, if it fulfills my needs and eventually report back :-) Glad to hear any feedback from the community on this!