#!/usr/bin/env python
#
# Provides readline tools, including:
#  - 'tab' completion
#  - 'scroll' access to history across python sessions
#
# to activate, run the following in your command shell:
#   export PYTHONSTARTUP=$HOME/.python
#   export PYTHONHISTORY=$HOME/.pyhistory
#   cp ./pythonstartup $PYTHONSTARTUP
#
# Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
# Copyright (c) 1997-2016 California Institute of Technology.
# Copyright (c) 2016-2025 The Uncertainty Quantification Foundation.
# License: 3-clause BSD.  The full license text is available at:
#  - https://github.com/uqfoundation/pox/blob/master/LICENSE

try:
  import readline
except ImportError:
  print ("Module readline not available.")
else:
  import rlcompleter
  if readline.__doc__ and 'libedit' in readline.__doc__:
    readline.parse_and_bind("bind ^I rl_complete")
  else:
    readline.parse_and_bind("tab: complete")
  import os
  import atexit
  import sys

  _version = 1  # {0: 'all-in-one', 1: 'different-major', 2: 'different-minor'}
  _version = ".".join(str(i) for i in sys.version_info[:_version])

  try:
    historyPath = os.environ["PYTHONHISTORY"] + _version
  except KeyError:
    historyPath = os.path.expanduser("~"+os.sep+".pyhistory" + _version)
    print ("Imported history from: '%s'" % historyPath)
    print ("Set history file with PYTHONHISTORY.")
  else:
    pass

  try:
    if os.path.exists(historyPath):
      readline.read_history_file(historyPath)
  except IOError:
    print ("Error reading: '%s'" % historyPath)
    print ("Skipping history.")

  def save_history(historyPath=historyPath):
    import readline
    readline.write_history_file(historyPath)

  atexit.register(save_history)

  del _version
  del os, sys, atexit, readline, rlcompleter, save_history, historyPath
