## Small LCS-based line diff. Good enough for typical script-sized files; ## intentionally skips huge files rather than doing an O(n*m) DP table on ## them (see MAX_DIFF_LINES). class_name ClaudeGodotDiff extends RefCounted const MAX_DIFF_LINES := 2000 ## Returns [] if either side is too large to diff cheaply, otherwise an ## ordered Array of {"op": "eq"|"add"|"del", "text": String}. static func diff_lines(old_text: String, new_text: String) -> Array: if old_text == new_text: return _all_eq(old_text) var a := old_text.split("\n") var b := new_text.split("\n") if a.size() > MAX_DIFF_LINES or b.size() > MAX_DIFF_LINES: return [] var n := a.size() var m := b.size() var lcs: Array = [] for _i in range(n + 1): var row: Array = [] row.resize(m + 1) row.fill(0) lcs.append(row) for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): if a[i] == b[j]: lcs[i][j] = lcs[i + 1][j + 1] + 1 else: lcs[i][j] = max(lcs[i + 1][j], lcs[i][j + 1]) var ops: Array = [] var i := 0 var j := 0 while i < n and j < m: if a[i] == b[j]: ops.append({"op": "eq", "text": a[i]}) i += 1 j += 1 elif lcs[i + 1][j] >= lcs[i][j + 1]: ops.append({"op": "del", "text": a[i]}) i += 1 else: ops.append({"op": "add", "text": b[j]}) j += 1 while i < n: ops.append({"op": "del", "text": a[i]}) i += 1 while j < m: ops.append({"op": "add", "text": b[j]}) j += 1 return ops static func _all_eq(text: String) -> Array: var ops: Array = [] for l in text.split("\n"): ops.append({"op": "eq", "text": l}) return ops ## Plain +/- text, meant to go back to the model as part of a tool result. static func to_unified_text(ops: Array) -> String: var lines: Array = [] for op in ops: match op["op"]: "eq": lines.append(" " + op["text"]) "add": lines.append("+ " + op["text"]) "del": lines.append("- " + op["text"]) return "\n".join(lines) ## Colored BBCode for the chat dock's RichTextLabel, styled like a fenced ## code block (see syntax_highlight.gd) rather than [code]/[codeblock] — ## those tags disable BBCode parsing for their contents, which would make ## the per-line [color] tags below render as literal text instead of color. static func to_bbcode(ops: Array) -> String: var out: Array = [] for op in ops: var text: String = str(op["text"]).replace("[", "[lb]") match op["op"]: "eq": out.append("[color=gray] %s[/color]" % text) "add": out.append("[color=#4caf50]+ %s[/color]" % text) "del": out.append("[color=#f44336]- %s[/color]" % text) return "[bgcolor=#1e1e1e]" + "\n".join(out) + "[/bgcolor]"