summaryrefslogtreecommitdiff
path: root/lib/syntax_suggest/capture/falling_indent_lines.rb
blob: 1e046b2ba5770929f5911e9a78d5e2e105a32fd6 (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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# frozen_string_literal: true

module SyntaxSuggest
  module Capture
    # Shows the context around code provided by "falling" indentation
    #
    # If this is the original code lines:
    #
    #   class OH
    #     def hello
    #       it "foo" do
    #     end
    #   end
    #
    # And this is the line that is captured
    #
    #       it "foo" do
    #
    # It will yield its surrounding context:
    #
    #   class OH
    #     def hello
    #     end
    #   end
    #
    # Example:
    #
    #   FallingIndentLines.new(
    #       block: block,
    #       code_lines: @code_lines
    #   ).call do |line|
    #     @lines_to_output << line
    #   end
    #
    class FallingIndentLines
      def initialize(code_lines:, block:)
        @lines = nil
        @scanner = ScanHistory.new(code_lines: code_lines, block: block)
        @original_indent = block.current_indent
      end

      def call(&yieldable)
        last_indent_up = @original_indent
        last_indent_down = @original_indent

        @scanner.commit_if_changed
        @scanner.scan(
          up: ->(line, _, _) {
            next true if line.empty?

            if line.indent < last_indent_up
              yieldable.call(line)
              last_indent_up = line.indent
            end
            true
          },
          down: ->(line, _, _) {
            next true if line.empty?

            if line.indent < last_indent_down
              yieldable.call(line)
              last_indent_down = line.indent
            end
            true
          }
        )
        @scanner.stash_changes
      end
    end
  end
end