#
# history for irb
#
# Copyright (c) 2001,2002 akira yamada <akira@ruby-lang.org>
# You can redistribute it and/or modify it under the same term as Ruby.
#
# Version 0.0.0.3.
#
# Special Thanks:
#   * Satoru Takabayashi <satoru@namazu.org>
#     An idea and some comments.
#

begin
  require 'readline'
  module IRB
    HISTORY_FILE = '~/.irb-history'
    MAX_HISTORY_LINES = 50000

    module IRB_HISTORY
      def save_history(history, history_file, max_lines = MAX_HISTORY_LINES)
	proc do
	  skip_history = 0
	  if history.length > max_lines
	    skip_history = history.length - max_lines
	  end
	  open(history_file, 'w') do |io|
	    io.flock(File::LOCK_EX)
	    history.each do |x|
	      if skip_history > 0
		skip_history -= 1
		next
	      end
	      io.puts x
	    end
	    io.truncate(io.pos)
	  end
	end
      end
      module_function :save_history
    end

    IRB_HISTORY_RC = proc do |context|
      if  context.io.kind_of?(IRB::ReadlineInputMethod)
      	unless IRB.conf[:MAIN_CONTEXT]
	  context.io.instance_eval <<-E
	    history_file = File.expand_path(HISTORY_FILE) 
    
	    begin
	      open(history_file) {|io|
	     	io.flock(File::LOCK_EX)
	      	io.each {|line|
	  	  @line << line
	  	  HISTORY << line.chomp
	   	}
	      }
	      @line_no = @line.size

	    rescue Errno::ENOENT
	    end

	    ObjectSpace.define_finalizer(self, IRB::IRB_HISTORY::save_history(HISTORY, history_file))
	  E
       	end
      end
    end
  end

  IRB.conf[:IRB_RC] = IRB::IRB_HISTORY_RC

rescue LoadError
end
