From 9542b7317da36f366545803f77e250036b168318 Mon Sep 17 00:00:00 2001 From: mrsdizzie Date: Thu, 16 Jul 2020 09:58:54 -0400 Subject: Fix Syntax highlight for token change in added/deleted code (#12238) * Fix Syntax highlight for token change in added/deleted code For diffs we first syntax highlight the before and after line then use a 3rd party diff library to find the difference in them and create a substring based on that, which we then highlight a 2nd time to show the specific difference within a line that has changed. In a specific case if the diffrence also changes the chroma class it will split in the middle of the attr and cause broken HTML: ``` oldtext var newtext ``` Will then split on ``` nx"oldtext --- services/gitdiff/gitdiff.go | 43 +++++++++++++++++++++++++++++++++++++--- services/gitdiff/gitdiff_test.go | 8 ++++++++ 2 files changed, 48 insertions(+), 3 deletions(-) (limited to 'services') diff --git a/services/gitdiff/gitdiff.go b/services/gitdiff/gitdiff.go index 7d08f63eb7..09a826500b 100644 --- a/services/gitdiff/gitdiff.go +++ b/services/gitdiff/gitdiff.go @@ -183,19 +183,56 @@ var ( func diffToHTML(fileName string, diffs []diffmatchpatch.Diff, lineType DiffLineType) template.HTML { buf := bytes.NewBuffer(nil) - + var addSpan bool for i := range diffs { switch { + case diffs[i].Type == diffmatchpatch.DiffEqual: + // Looking for the case where our 3rd party diff library previously detected a string difference + // in the middle of a span class because we highlight them first. This happens when added/deleted code + // also changes the chroma class name. If found, just move the openining span code forward into the next section + if addSpan { + diffs[i].Text = "") { + buf.WriteString("") + diffs[i].Text = strings.TrimPrefix(diffs[i].Text, "") + } + if strings.HasSuffix(diffs[i].Text, "") { + buf.WriteString("") + diffs[i].Text = strings.TrimPrefix(diffs[i].Text, "") + } + if strings.HasSuffix(diffs[i].Text, "if !nohl && (lexer != nil || r.GuessLanguage) {", diffToHTML("", []dmp.Diff{ + {Type: dmp.DiffEqual, Text: "if !nohl && (lexer != nil"}, + {Type: dmp.DiffInsert, Text: " || r.GuessLanguage)"}, + {Type: dmp.DiffEqual, Text: " {"}, + }, DiffLineAdd)) } func TestParsePatch(t *testing.T) { -- cgit v1.2.3