Question

What tcl command returns last evaluated command? I think it should have something like bash history.

I have tried this, but it prints empty string.

set aaa bbb
puts [history info]

I have c++ program which create Tcl Interpreter and evaluates commands using it. In a specific moment I need to know what is last evaluated command. Is it possible using Tcl or C interfaces?

set a bbb
set b ccc
puts eee
set hh [history redo 1]

Now am getting error

event "1" hasn't occured yet
    while executing
"HistIndex $event"
    (procedure "tcl::HistRedo" line 6)
    invoked from within
"tcl::HistRedo [lindex $args 1]"
    (procedure "history" line 109)
    invoked from within
"history redo 1"
    invoked from within
"set hh [history redo 1]"
    (file "./a.itcl" line 17)
Was it helpful?

Solution

Review and manipulation of previously entered commands is available in tclsh using the history command. This lets you review the previous command list and redo events.

In an interactive tclsh, there is also a !! or !N shortcut to history redo N to redo the last entered command or redo command N (where N is the event number).

It is not bound to up-arrow or ctrl-p or anything normal though. For that, you probably want some wrapper like rlwrap or socat READLINE to give readline-style line editing. If you have an X Windows session, then tkcon is more use and provides reasonable command line editing. On Windows, the tclsh gets to use the builting line editing from the cmd.exe prompt - including use of uparrow to get to previous commands.

In my test session:

% info pa
8.5.13
% history z
bad option "z": must be add, change, clear, event, info, keep, nextid, or redo
% history info
     1  info pa
     2  history z
     3  history info
% history redo 1
8.5.13
% exit

Followup

Additional comments from the original poster state that the code is not running in a standard tclsh interpreter. The history functionality is implemented in generic/tclHistory.c and the library/history.tcl library script. As noted in the C file header comment:

This module and the Tcl library file history.tcl together implement Tcl command history. Tcl_RecordAndEval(Obj) can be called to record commands ("events") before they are executed. Commands defined in history.tcl may be used to perform history substitutions.

so we can deduce that the custom interpreter must use the Tcl_RecordAndEval API call when evaluating commands that we want entered into the history. Presumably the current custom implementation is just using Tcl_Eval or one of the related functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top