Module: PrettyDiff::WordDiffFinder

Extended by:
WordDiffFinder
Included in:
WordDiffFinder
Defined in:
lib/pretty_diff/word_diff_finder.rb

Constant Summary collapse

WDIFF_INSERTED_START =
"\x01"
WDIFF_INSERTED_END =
"\x02"
WDIFF_DELETED_START =
"\x03"
WDIFF_DELETED_END =
"\x04"

Instance Method Summary collapse

Instance Method Details

#find_word_diffs(lines) ⇒ Object



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
# File 'lib/pretty_diff/word_diff_finder.rb', line 13

def find_word_diffs(lines)
  dmp = DiffMatchPatch.new
  result = []
  added_next_line_already = false

  lines.each_with_index do |line, idx|
    if added_next_line_already
      added_next_line_already = false
      next
    end

    previous_line = idx > 0 ? lines[idx - 1] : nil
    stripped_line = strip(line)
    next_line = lines[idx + 1]
    stripped_next_line = strip(next_line || '')
    after_next_line = idx < lines.size ? lines[idx + 2] : nil

    # only show word diffing when change was a single line
    if changed_line?(line, next_line) && !changed_block?(previous_line, line, next_line, after_next_line) && similiar_lines?(stripped_line, stripped_next_line)
      diffs = dmp.diff_cleanup_semantic!(dmp.diff_main(stripped_line, stripped_next_line, true))
      replacement, next_replacement = join_diffs(diffs)

      if line.include?(replacement.first)
        # String#gsub in the form gsub(exp,replacement) has odd quirks
        # affecting the replacement string which sometimes require
        # lots of escaping slashes. Ruby users are frequently directed
        # to use the block form instead.
        # See: http://stackoverflow.com/a/13818467/204927
        line.gsub!(replacement.first) { replacement.last }
      else # it has to come form next_line
        next_line.gsub!(replacement.first) { replacement.last }
        added_next_line_already = true
      end

      if next_line && next_replacement
        next_line.gsub!(next_replacement.first) { next_replacement.last }
        added_next_line_already = true
      end
    end

    result << line

    if added_next_line_already
      result << next_line
    end
  end

  result
end