#
# CommandLineEditor.rb
#
#   $Author: hiroya $
#   $Date: 2000/11/23 01:53:10 $
#   Copyright (C) 2000 Hiroya KUBO
#

require "RReadline"
require "BuiltInExecutables"

=begin
 
=end
class CommandLineEditor < RReadline
  include BuiltInExecutables

  def initialize
    super
    @executables = Hash.new
    @executables.update(getBuiltInExecutables)
    @argv_delim = '\s+'
  end

  def setExecutables(executables)
    @executables = executables
  end

  alias executables= setExecutables

  def getExecutables
    return @executables
  end

  def getArgvDelimiter
    return @argv_delim
  end

  def setArgvDelimiter(delim)
    @argv_delim = delim
  end

  # -- loop --

  def doit
    begin
      loop
    rescue ExitCommandLineEditor
      exit
    rescue 
      print $!
      exit
    end
  end

  def loop
    while(true)
      if((command = readline(true)) != "")
	execCommand(command)
      end
    end
  end

  def getArgv(value = @line.getValue)
    if(@argv_delim != nil)
      return eval "value.split(/#{@argv_delim}/)"
    else
      return [value]
    end
  end

  def execCommand(value)
    argv = getArgv(value)
    command = nil
    while(argv.size > 0)
      command = argv.shift
      if(command != nil && command != "" )
	break
      end
    end

    if ((function = @executables[command]) != nil)
      if(function.instance_of?(Proc))
	function.call(argv)
	return
      elsif(function.instance_of?(String))
	eval function
	return
      end
    end
    if(command != nil)
      print(command+": Command not found.\n")
    end
  end

end

