summaryrefslogtreecommitdiff
path: root/lib/irb/command/history.rb
blob: a47a8795ddc3f0b5abd1a15cbaf097bb64ed133f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# frozen_string_literal: true

require "stringio"

require_relative "../pager"

module IRB
  # :stopdoc:

  module Command
    class History < Base
      category "IRB"
      description "Shows the input history. `-g [query]` or `-G [query]` allows you to filter the output."

      def self.transform_args(args)
        match = args&.match(/(-g|-G)\s+(?<grep>.+)\s*\n\z/)
        return unless match

        "grep: #{Regexp.new(match[:grep]).inspect}"
      end

      def execute(grep: nil)
        formatted_inputs = irb_context.io.class::HISTORY.each_with_index.reverse_each.filter_map do |input, index|
          next if grep && !input.match?(grep)

          header = "#{index}: "

          first_line, *other_lines = input.split("\n")
          first_line = "#{header}#{first_line}"

          truncated_lines = other_lines.slice!(1..) # Show 1 additional line (2 total)
          other_lines << "..." if truncated_lines&.any?

          other_lines.map! do |line|
            " " * header.length + line
          end

          [first_line, *other_lines].join("\n") + "\n"
        end

        Pager.page_content(formatted_inputs.join)
      end
    end
  end

  # :startdoc:
end