Class: Yatte::IncrementalSearch

Inherits:
Object
  • Object
show all
Defined in:
lib/yatte/incremental_search.rb

Overview

Interactive Ctrl+F search: reads keys, moves the cursor to matches, and reports status back to the editor via a ‘status:` callback.

Instance Method Summary collapse

Constructor Details

#initialize(buffer:, cursor:, input:, status:) ⇒ IncrementalSearch

Returns a new instance of IncrementalSearch.



7
8
9
10
11
12
# File 'lib/yatte/incremental_search.rb', line 7

def initialize(buffer:, cursor:, input:, status:)
  @buffer = buffer
  @cursor = cursor
  @input = input
  @status = status
end

Instance Method Details

#runObject



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
48
49
50
51
52
53
54
# File 'lib/yatte/incremental_search.rb', line 14

def run
  saved_row = @cursor.row
  saved_col = @cursor.col
  query = +""

  loop do
    @status.call("Search: #{query} (ESC to cancel)")

    key = @input.read_keypress
    case key
    when :enter
      @status.call("")
      return
    when :escape
      @cursor.set(saved_row, saved_col)
      @status.call("")
      return
    when :backspace
      query.chop! unless query.empty?
    when :arrow_down, :ctrl_n
      seek_next(query) if query.length > 0
      next
    when :arrow_up, :ctrl_p
      seek_prev(query) if query.length > 0
      next
    when String
      query << key
    else
      next
    end

    if query.length > 0
      match = @buffer.find(query, 0, 0)
      if match
        @cursor.set(match[0], match[1])
      else
        @status.call("Search: #{query} (not found)")
      end
    end
  end
end