From dc84e1e107495e28d29e266705f5486e0a9d14b9 Mon Sep 17 00:00:00 2001 From: Bruce Hill Date: Fri, 27 Oct 2017 14:54:47 -0700 Subject: [PATCH] Fixed some questionable newline printing behavior and added support for passing in arbitrary tables instead of strings. --- diff.lua | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/diff.lua b/diff.lua index 5404a1b..0c218cc 100644 --- a/diff.lua +++ b/diff.lua @@ -63,7 +63,7 @@ local function print_diff(d, options) end end if not (options and options.context == 0) then - io.write((old:gsub("[^\n]*\n?", " %1"))) + io.write((old:gsub("([^\n]*)\n?", " %1\n"))) end else -- Changed @@ -72,18 +72,17 @@ local function print_diff(d, options) print(colors.underscore..colors.bright..colors.red.. ("Old line %d-%d:"):format(chunk.old_line, chunk.old_line_end)..colors.reset) end - io.write(colors.red..(chunk.old:gsub("[^\n]*\n?", "- %1"))..colors.reset) + io.write(colors.red..(chunk.old:gsub("([^\n]*)\n?", "- %1\n"))..colors.reset) end if #chunk.new > 0 then if line_numbers then print(colors.underscore..colors.bright..colors.green.. ("New line %d-%d:"):format(chunk.new_line, chunk.new_line_end)..colors.reset) end - io.write(colors.green..(chunk.new:gsub("[^\n]*\n?", "+ %1"))..colors.reset) + io.write(colors.green..(chunk.new:gsub("([^\n]*)\n?", "+ %1\n"))..colors.reset) end end end - io.write('\n') end local diff_mt = {__index={print=print_diff}} @@ -95,9 +94,15 @@ local function diff(old, new) local insert, concat = table.insert, table.concat -- Split into lines - local A, B = {}, {} - for c in old:gmatch("[^\n]*\n?") do insert(A, c) end - for c in new:gmatch("[^\n]*\n?") do insert(B, c) end + local A, B = old, new + if type(A) ~= 'table' then + A = {} + for c in old:gmatch("[^\n]*\n?") do insert(A, c) end + end + if type(B) ~= 'table' then + B = {} + for c in new:gmatch("[^\n]*\n?") do insert(B, c) end + end -- Find the longest common subsequence between A[a_min..a_max] and B[b_min..b_max] (inclusive), -- and return (the starting position in a), (the starting position in b), (the length)