Module: RelinePac::Packages::History::Methods

Defined in:
lib/reline_pac/packages/history.rb

Overview

Methods adds fzf history search to Reline::LineEditor.

Instance Method Summary collapse

Instance Method Details

#fzf_history(_key) ⇒ Object

rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity



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
# File 'lib/reline_pac/packages/history.rb', line 10

def fzf_history(_key)
  all_history = Reline::HISTORY.to_a
  return if all_history.empty?

  seen = {}
  filtered = all_history.reverse.filter_map do |h|
    stripped = h.strip
    next if stripped.empty? || seen[stripped]

    seen[stripped] = true
    h
  end

  display = filtered.map { |h| h.gsub("\n", '') }

  selected_index = nil
  ::IO.popen("fzf --reverse --border --query='#{line}' --with-nth=1 --delimiter=$'\\t'", 'r+') do |io|
    display.each_with_index { |d, i| io.puts "#{d}\t#{i}" }
    io.close_write
    result = io.read.strip
    selected_index = result.split("\t").last.to_i unless result.empty?
  end

  selected_text = selected_index ? filtered[selected_index] : whole_buffer
  reset_line
  insert_multiline_text(selected_text)
  $stdout.write prompt_list.last
  if selected_text.include?("\n")
    $stdout.write selected_text.split("\n").last
  else
    $stdout.write line
  end
end