Export from REPL history to julia script?

I found Base.active_repl.interface.modes[1].hist.history, which provides the REPL history.
It is initialized with the history file, but after those entries, there is no crosstalk between sessions.

In addition, there is start_idx, which marks the first new entry.
So here is a solution that looks good to me.

"""
Get commands of the current REPL session as an array of strings
"""
function get_REPL_as_history()
          history = Base.active_repl.interface.modes[1].hist
          history.history[history.start_idx+1:end]
end
"""
Save REPL commands of this session to a file

file: Path to a file
"""
function save_REPL_history(file)
           isfile(file) && error("file already exists")
           open(file,"w") do io
                      txt = join(get_REPL_as_history(),"\n")
                      write(io,txt)
           end
end

One thing that does not work is tracking repeated commands.
So when you enter print("123") and then another print("123") the history only tracks one.

REPL example
julia> """
       Get commands of the current REPL session as an array of strings
       """
       function get_REPL_as_history()
                 history = Base.active_repl.interface.modes[1].hist
                 history.history[history.start_idx+1:end]
       end
get_REPL_as_history

julia> """
       Save REPL commands of this session to a file

       file: Path to a file
       """
       function save_REPL_history(file)
                  isfile(file) && error("file already exists")
                  open(file,"w") do io
                             txt = join(get_REPL_as_history(),"\n")
                             write(io,txt)
                  end
       end
save_REPL_history

julia> print("123")
123
julia> print("321")
321
julia> print("123")
123
julia> print("123")
123
julia> print("bye")
bye
julia> get_REPL_as_history()
8-element Vector{String}:
 "\"\"\"\nGet commands of the current" ⋯ 155 bytes ⋯ "ory[history.start_idx:end]\nend"
 "\"\"\"\nSave REPL commands of this " ⋯ 250 bytes ⋯ "ite(io,txt)\n           end\nend"
 "print(\"123\")"
 "print(\"321\")"
 "print(\"123\")"
 "print(\"bye\")"
 "get_REPL_as_history()"
julia> save_REPL_history("/tmp/record.jl")
660

5 Likes