diff.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  1. package diff
  2. import (
  3. "bytes"
  4. "fmt"
  5. "image/color"
  6. "io"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. "github.com/alecthomas/chroma/v2"
  11. "github.com/alecthomas/chroma/v2/formatters"
  12. "github.com/alecthomas/chroma/v2/lexers"
  13. "github.com/alecthomas/chroma/v2/styles"
  14. "github.com/charmbracelet/lipgloss/v2"
  15. "github.com/charmbracelet/lipgloss/v2/compat"
  16. "github.com/charmbracelet/x/ansi"
  17. "github.com/sergi/go-diff/diffmatchpatch"
  18. stylesi "github.com/sst/opencode/internal/styles"
  19. "github.com/sst/opencode/internal/theme"
  20. )
  21. // -------------------------------------------------------------------------
  22. // Core Types
  23. // -------------------------------------------------------------------------
  24. // LineType represents the kind of line in a diff.
  25. type LineType int
  26. const (
  27. LineContext LineType = iota // Line exists in both files
  28. LineAdded // Line added in the new file
  29. LineRemoved // Line removed from the old file
  30. )
  31. // Segment represents a portion of a line for intra-line highlighting
  32. type Segment struct {
  33. Start int
  34. End int
  35. Type LineType
  36. Text string
  37. }
  38. // DiffLine represents a single line in a diff
  39. type DiffLine struct {
  40. OldLineNo int // Line number in old file (0 for added lines)
  41. NewLineNo int // Line number in new file (0 for removed lines)
  42. Kind LineType // Type of line (added, removed, context)
  43. Content string // Content of the line
  44. Segments []Segment // Segments for intraline highlighting
  45. }
  46. // Hunk represents a section of changes in a diff
  47. type Hunk struct {
  48. Header string
  49. Lines []DiffLine
  50. }
  51. // DiffResult contains the parsed result of a diff
  52. type DiffResult struct {
  53. OldFile string
  54. NewFile string
  55. Hunks []Hunk
  56. }
  57. // linePair represents a pair of lines for side-by-side display
  58. type linePair struct {
  59. left *DiffLine
  60. right *DiffLine
  61. }
  62. // -------------------------------------------------------------------------
  63. // Side-by-Side Configuration
  64. // -------------------------------------------------------------------------
  65. // SideBySideConfig configures the rendering of side-by-side diffs
  66. type SideBySideConfig struct {
  67. TotalWidth int
  68. }
  69. // SideBySideOption modifies a SideBySideConfig
  70. type SideBySideOption func(*SideBySideConfig)
  71. // NewSideBySideConfig creates a SideBySideConfig with default values
  72. func NewSideBySideConfig(opts ...SideBySideOption) SideBySideConfig {
  73. config := SideBySideConfig{
  74. TotalWidth: 160, // Default width for side-by-side view
  75. }
  76. for _, opt := range opts {
  77. opt(&config)
  78. }
  79. return config
  80. }
  81. // WithTotalWidth sets the total width for side-by-side view
  82. func WithTotalWidth(width int) SideBySideOption {
  83. return func(s *SideBySideConfig) {
  84. if width > 0 {
  85. s.TotalWidth = width
  86. }
  87. }
  88. }
  89. // -------------------------------------------------------------------------
  90. // Unified Configuration
  91. // -------------------------------------------------------------------------
  92. // UnifiedConfig configures the rendering of unified diffs
  93. type UnifiedConfig struct {
  94. Width int
  95. }
  96. // UnifiedOption modifies a UnifiedConfig
  97. type UnifiedOption func(*UnifiedConfig)
  98. // NewUnifiedConfig creates a UnifiedConfig with default values
  99. func NewUnifiedConfig(opts ...UnifiedOption) UnifiedConfig {
  100. config := UnifiedConfig{
  101. Width: 80, // Default width for unified view
  102. }
  103. for _, opt := range opts {
  104. opt(&config)
  105. }
  106. return config
  107. }
  108. // WithWidth sets the width for unified view
  109. func WithWidth(width int) UnifiedOption {
  110. return func(u *UnifiedConfig) {
  111. if width > 0 {
  112. u.Width = width
  113. }
  114. }
  115. }
  116. // -------------------------------------------------------------------------
  117. // Diff Parsing
  118. // -------------------------------------------------------------------------
  119. // ParseUnifiedDiff parses a unified diff format string into structured data
  120. func ParseUnifiedDiff(diff string) (DiffResult, error) {
  121. var result DiffResult
  122. var currentHunk *Hunk
  123. hunkHeaderRe := regexp.MustCompile(`^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@`)
  124. lines := strings.Split(diff, "\n")
  125. var oldLine, newLine int
  126. inFileHeader := true
  127. for _, line := range lines {
  128. // Parse file headers
  129. if inFileHeader {
  130. if strings.HasPrefix(line, "--- a/") {
  131. result.OldFile = strings.TrimPrefix(line, "--- a/")
  132. continue
  133. }
  134. if strings.HasPrefix(line, "+++ b/") {
  135. result.NewFile = strings.TrimPrefix(line, "+++ b/")
  136. inFileHeader = false
  137. continue
  138. }
  139. }
  140. // Parse hunk headers
  141. if matches := hunkHeaderRe.FindStringSubmatch(line); matches != nil {
  142. if currentHunk != nil {
  143. result.Hunks = append(result.Hunks, *currentHunk)
  144. }
  145. currentHunk = &Hunk{
  146. Header: line,
  147. Lines: []DiffLine{},
  148. }
  149. oldStart, _ := strconv.Atoi(matches[1])
  150. newStart, _ := strconv.Atoi(matches[3])
  151. oldLine = oldStart
  152. newLine = newStart
  153. continue
  154. }
  155. // Ignore "No newline at end of file" markers
  156. if strings.HasPrefix(line, "\\ No newline at end of file") {
  157. continue
  158. }
  159. if currentHunk == nil {
  160. continue
  161. }
  162. // Process the line based on its prefix
  163. if len(line) > 0 {
  164. switch line[0] {
  165. case '+':
  166. currentHunk.Lines = append(currentHunk.Lines, DiffLine{
  167. OldLineNo: 0,
  168. NewLineNo: newLine,
  169. Kind: LineAdded,
  170. Content: line[1:],
  171. })
  172. newLine++
  173. case '-':
  174. currentHunk.Lines = append(currentHunk.Lines, DiffLine{
  175. OldLineNo: oldLine,
  176. NewLineNo: 0,
  177. Kind: LineRemoved,
  178. Content: line[1:],
  179. })
  180. oldLine++
  181. default:
  182. currentHunk.Lines = append(currentHunk.Lines, DiffLine{
  183. OldLineNo: oldLine,
  184. NewLineNo: newLine,
  185. Kind: LineContext,
  186. Content: line,
  187. })
  188. oldLine++
  189. newLine++
  190. }
  191. } else {
  192. // Handle empty lines
  193. currentHunk.Lines = append(currentHunk.Lines, DiffLine{
  194. OldLineNo: oldLine,
  195. NewLineNo: newLine,
  196. Kind: LineContext,
  197. Content: "",
  198. })
  199. oldLine++
  200. newLine++
  201. }
  202. }
  203. // Add the last hunk if there is one
  204. if currentHunk != nil {
  205. result.Hunks = append(result.Hunks, *currentHunk)
  206. }
  207. return result, nil
  208. }
  209. // HighlightIntralineChanges updates lines in a hunk to show character-level differences
  210. func HighlightIntralineChanges(h *Hunk) {
  211. var updated []DiffLine
  212. dmp := diffmatchpatch.New()
  213. for i := 0; i < len(h.Lines); i++ {
  214. // Look for removed line followed by added line
  215. if i+1 < len(h.Lines) &&
  216. h.Lines[i].Kind == LineRemoved &&
  217. h.Lines[i+1].Kind == LineAdded {
  218. oldLine := h.Lines[i]
  219. newLine := h.Lines[i+1]
  220. // Find character-level differences
  221. patches := dmp.DiffMain(oldLine.Content, newLine.Content, false)
  222. patches = dmp.DiffCleanupSemantic(patches)
  223. patches = dmp.DiffCleanupMerge(patches)
  224. patches = dmp.DiffCleanupEfficiency(patches)
  225. segments := make([]Segment, 0)
  226. removeStart := 0
  227. addStart := 0
  228. for _, patch := range patches {
  229. switch patch.Type {
  230. case diffmatchpatch.DiffDelete:
  231. segments = append(segments, Segment{
  232. Start: removeStart,
  233. End: removeStart + len(patch.Text),
  234. Type: LineRemoved,
  235. Text: patch.Text,
  236. })
  237. removeStart += len(patch.Text)
  238. case diffmatchpatch.DiffInsert:
  239. segments = append(segments, Segment{
  240. Start: addStart,
  241. End: addStart + len(patch.Text),
  242. Type: LineAdded,
  243. Text: patch.Text,
  244. })
  245. addStart += len(patch.Text)
  246. default:
  247. // Context text, no highlighting needed
  248. removeStart += len(patch.Text)
  249. addStart += len(patch.Text)
  250. }
  251. }
  252. oldLine.Segments = segments
  253. newLine.Segments = segments
  254. updated = append(updated, oldLine, newLine)
  255. i++ // Skip the next line as we've already processed it
  256. } else {
  257. updated = append(updated, h.Lines[i])
  258. }
  259. }
  260. h.Lines = updated
  261. }
  262. // pairLines converts a flat list of diff lines to pairs for side-by-side display
  263. func pairLines(lines []DiffLine) []linePair {
  264. var pairs []linePair
  265. i := 0
  266. for i < len(lines) {
  267. switch lines[i].Kind {
  268. case LineRemoved:
  269. // Check if the next line is an addition, if so pair them
  270. if i+1 < len(lines) && lines[i+1].Kind == LineAdded {
  271. pairs = append(pairs, linePair{left: &lines[i], right: &lines[i+1]})
  272. i += 2
  273. } else {
  274. pairs = append(pairs, linePair{left: &lines[i], right: nil})
  275. i++
  276. }
  277. case LineAdded:
  278. pairs = append(pairs, linePair{left: nil, right: &lines[i]})
  279. i++
  280. case LineContext:
  281. pairs = append(pairs, linePair{left: &lines[i], right: &lines[i]})
  282. i++
  283. }
  284. }
  285. return pairs
  286. }
  287. // -------------------------------------------------------------------------
  288. // Syntax Highlighting
  289. // -------------------------------------------------------------------------
  290. // SyntaxHighlight applies syntax highlighting to text based on file extension
  291. func SyntaxHighlight(w io.Writer, source, fileName, formatter string, bg color.Color) error {
  292. t := theme.CurrentTheme()
  293. // Determine the language lexer to use
  294. l := lexers.Match(fileName)
  295. if l == nil {
  296. l = lexers.Analyse(source)
  297. }
  298. if l == nil {
  299. l = lexers.Fallback
  300. }
  301. l = chroma.Coalesce(l)
  302. // Get the formatter
  303. f := formatters.Get(formatter)
  304. if f == nil {
  305. f = formatters.Fallback
  306. }
  307. // Dynamic theme based on current theme values
  308. syntaxThemeXml := fmt.Sprintf(`
  309. <style name="opencode-theme">
  310. <!-- Base colors -->
  311. <entry type="Background" style="bg:%s"/>
  312. <entry type="Text" style="%s"/>
  313. <entry type="Other" style="%s"/>
  314. <entry type="Error" style="%s"/>
  315. <!-- Keywords -->
  316. <entry type="Keyword" style="%s"/>
  317. <entry type="KeywordConstant" style="%s"/>
  318. <entry type="KeywordDeclaration" style="%s"/>
  319. <entry type="KeywordNamespace" style="%s"/>
  320. <entry type="KeywordPseudo" style="%s"/>
  321. <entry type="KeywordReserved" style="%s"/>
  322. <entry type="KeywordType" style="%s"/>
  323. <!-- Names -->
  324. <entry type="Name" style="%s"/>
  325. <entry type="NameAttribute" style="%s"/>
  326. <entry type="NameBuiltin" style="%s"/>
  327. <entry type="NameBuiltinPseudo" style="%s"/>
  328. <entry type="NameClass" style="%s"/>
  329. <entry type="NameConstant" style="%s"/>
  330. <entry type="NameDecorator" style="%s"/>
  331. <entry type="NameEntity" style="%s"/>
  332. <entry type="NameException" style="%s"/>
  333. <entry type="NameFunction" style="%s"/>
  334. <entry type="NameLabel" style="%s"/>
  335. <entry type="NameNamespace" style="%s"/>
  336. <entry type="NameOther" style="%s"/>
  337. <entry type="NameTag" style="%s"/>
  338. <entry type="NameVariable" style="%s"/>
  339. <entry type="NameVariableClass" style="%s"/>
  340. <entry type="NameVariableGlobal" style="%s"/>
  341. <entry type="NameVariableInstance" style="%s"/>
  342. <!-- Literals -->
  343. <entry type="Literal" style="%s"/>
  344. <entry type="LiteralDate" style="%s"/>
  345. <entry type="LiteralString" style="%s"/>
  346. <entry type="LiteralStringBacktick" style="%s"/>
  347. <entry type="LiteralStringChar" style="%s"/>
  348. <entry type="LiteralStringDoc" style="%s"/>
  349. <entry type="LiteralStringDouble" style="%s"/>
  350. <entry type="LiteralStringEscape" style="%s"/>
  351. <entry type="LiteralStringHeredoc" style="%s"/>
  352. <entry type="LiteralStringInterpol" style="%s"/>
  353. <entry type="LiteralStringOther" style="%s"/>
  354. <entry type="LiteralStringRegex" style="%s"/>
  355. <entry type="LiteralStringSingle" style="%s"/>
  356. <entry type="LiteralStringSymbol" style="%s"/>
  357. <!-- Numbers -->
  358. <entry type="LiteralNumber" style="%s"/>
  359. <entry type="LiteralNumberBin" style="%s"/>
  360. <entry type="LiteralNumberFloat" style="%s"/>
  361. <entry type="LiteralNumberHex" style="%s"/>
  362. <entry type="LiteralNumberInteger" style="%s"/>
  363. <entry type="LiteralNumberIntegerLong" style="%s"/>
  364. <entry type="LiteralNumberOct" style="%s"/>
  365. <!-- Operators -->
  366. <entry type="Operator" style="%s"/>
  367. <entry type="OperatorWord" style="%s"/>
  368. <entry type="Punctuation" style="%s"/>
  369. <!-- Comments -->
  370. <entry type="Comment" style="%s"/>
  371. <entry type="CommentHashbang" style="%s"/>
  372. <entry type="CommentMultiline" style="%s"/>
  373. <entry type="CommentSingle" style="%s"/>
  374. <entry type="CommentSpecial" style="%s"/>
  375. <entry type="CommentPreproc" style="%s"/>
  376. <!-- Generic styles -->
  377. <entry type="Generic" style="%s"/>
  378. <entry type="GenericDeleted" style="%s"/>
  379. <entry type="GenericEmph" style="italic %s"/>
  380. <entry type="GenericError" style="%s"/>
  381. <entry type="GenericHeading" style="bold %s"/>
  382. <entry type="GenericInserted" style="%s"/>
  383. <entry type="GenericOutput" style="%s"/>
  384. <entry type="GenericPrompt" style="%s"/>
  385. <entry type="GenericStrong" style="bold %s"/>
  386. <entry type="GenericSubheading" style="bold %s"/>
  387. <entry type="GenericTraceback" style="%s"/>
  388. <entry type="GenericUnderline" style="underline"/>
  389. <entry type="TextWhitespace" style="%s"/>
  390. </style>
  391. `,
  392. getChromaColor(t.BackgroundPanel()), // Background
  393. getChromaColor(t.Text()), // Text
  394. getChromaColor(t.Text()), // Other
  395. getChromaColor(t.Error()), // Error
  396. getChromaColor(t.SyntaxKeyword()), // Keyword
  397. getChromaColor(t.SyntaxKeyword()), // KeywordConstant
  398. getChromaColor(t.SyntaxKeyword()), // KeywordDeclaration
  399. getChromaColor(t.SyntaxKeyword()), // KeywordNamespace
  400. getChromaColor(t.SyntaxKeyword()), // KeywordPseudo
  401. getChromaColor(t.SyntaxKeyword()), // KeywordReserved
  402. getChromaColor(t.SyntaxType()), // KeywordType
  403. getChromaColor(t.Text()), // Name
  404. getChromaColor(t.SyntaxVariable()), // NameAttribute
  405. getChromaColor(t.SyntaxType()), // NameBuiltin
  406. getChromaColor(t.SyntaxVariable()), // NameBuiltinPseudo
  407. getChromaColor(t.SyntaxType()), // NameClass
  408. getChromaColor(t.SyntaxVariable()), // NameConstant
  409. getChromaColor(t.SyntaxFunction()), // NameDecorator
  410. getChromaColor(t.SyntaxVariable()), // NameEntity
  411. getChromaColor(t.SyntaxType()), // NameException
  412. getChromaColor(t.SyntaxFunction()), // NameFunction
  413. getChromaColor(t.Text()), // NameLabel
  414. getChromaColor(t.SyntaxType()), // NameNamespace
  415. getChromaColor(t.SyntaxVariable()), // NameOther
  416. getChromaColor(t.SyntaxKeyword()), // NameTag
  417. getChromaColor(t.SyntaxVariable()), // NameVariable
  418. getChromaColor(t.SyntaxVariable()), // NameVariableClass
  419. getChromaColor(t.SyntaxVariable()), // NameVariableGlobal
  420. getChromaColor(t.SyntaxVariable()), // NameVariableInstance
  421. getChromaColor(t.SyntaxString()), // Literal
  422. getChromaColor(t.SyntaxString()), // LiteralDate
  423. getChromaColor(t.SyntaxString()), // LiteralString
  424. getChromaColor(t.SyntaxString()), // LiteralStringBacktick
  425. getChromaColor(t.SyntaxString()), // LiteralStringChar
  426. getChromaColor(t.SyntaxString()), // LiteralStringDoc
  427. getChromaColor(t.SyntaxString()), // LiteralStringDouble
  428. getChromaColor(t.SyntaxString()), // LiteralStringEscape
  429. getChromaColor(t.SyntaxString()), // LiteralStringHeredoc
  430. getChromaColor(t.SyntaxString()), // LiteralStringInterpol
  431. getChromaColor(t.SyntaxString()), // LiteralStringOther
  432. getChromaColor(t.SyntaxString()), // LiteralStringRegex
  433. getChromaColor(t.SyntaxString()), // LiteralStringSingle
  434. getChromaColor(t.SyntaxString()), // LiteralStringSymbol
  435. getChromaColor(t.SyntaxNumber()), // LiteralNumber
  436. getChromaColor(t.SyntaxNumber()), // LiteralNumberBin
  437. getChromaColor(t.SyntaxNumber()), // LiteralNumberFloat
  438. getChromaColor(t.SyntaxNumber()), // LiteralNumberHex
  439. getChromaColor(t.SyntaxNumber()), // LiteralNumberInteger
  440. getChromaColor(t.SyntaxNumber()), // LiteralNumberIntegerLong
  441. getChromaColor(t.SyntaxNumber()), // LiteralNumberOct
  442. getChromaColor(t.SyntaxOperator()), // Operator
  443. getChromaColor(t.SyntaxKeyword()), // OperatorWord
  444. getChromaColor(t.SyntaxPunctuation()), // Punctuation
  445. getChromaColor(t.SyntaxComment()), // Comment
  446. getChromaColor(t.SyntaxComment()), // CommentHashbang
  447. getChromaColor(t.SyntaxComment()), // CommentMultiline
  448. getChromaColor(t.SyntaxComment()), // CommentSingle
  449. getChromaColor(t.SyntaxComment()), // CommentSpecial
  450. getChromaColor(t.SyntaxKeyword()), // CommentPreproc
  451. getChromaColor(t.Text()), // Generic
  452. getChromaColor(t.Error()), // GenericDeleted
  453. getChromaColor(t.Text()), // GenericEmph
  454. getChromaColor(t.Error()), // GenericError
  455. getChromaColor(t.Text()), // GenericHeading
  456. getChromaColor(t.Success()), // GenericInserted
  457. getChromaColor(t.TextMuted()), // GenericOutput
  458. getChromaColor(t.Text()), // GenericPrompt
  459. getChromaColor(t.Text()), // GenericStrong
  460. getChromaColor(t.Text()), // GenericSubheading
  461. getChromaColor(t.Error()), // GenericTraceback
  462. getChromaColor(t.Text()), // TextWhitespace
  463. )
  464. r := strings.NewReader(syntaxThemeXml)
  465. style := chroma.MustNewXMLStyle(r)
  466. // Modify the style to use the provided background
  467. s, err := style.Builder().Transform(
  468. func(t chroma.StyleEntry) chroma.StyleEntry {
  469. if _, ok := bg.(lipgloss.NoColor); ok {
  470. return t
  471. }
  472. r, g, b, _ := bg.RGBA()
  473. t.Background = chroma.NewColour(uint8(r>>8), uint8(g>>8), uint8(b>>8))
  474. return t
  475. },
  476. ).Build()
  477. if err != nil {
  478. s = styles.Fallback
  479. }
  480. // Tokenize and format
  481. it, err := l.Tokenise(nil, source)
  482. if err != nil {
  483. return err
  484. }
  485. return f.Format(w, s, it)
  486. }
  487. // getColor returns the appropriate hex color string based on terminal background
  488. func getColor(adaptiveColor compat.AdaptiveColor) *string {
  489. return stylesi.AdaptiveColorToString(adaptiveColor)
  490. }
  491. func getChromaColor(adaptiveColor compat.AdaptiveColor) string {
  492. color := stylesi.AdaptiveColorToString(adaptiveColor)
  493. if color == nil {
  494. return ""
  495. }
  496. return *color
  497. }
  498. // highlightLine applies syntax highlighting to a single line
  499. func highlightLine(fileName string, line string, bg color.Color) string {
  500. var buf bytes.Buffer
  501. err := SyntaxHighlight(&buf, line, fileName, "terminal16m", bg)
  502. if err != nil {
  503. return line
  504. }
  505. return buf.String()
  506. }
  507. // createStyles generates the lipgloss styles needed for rendering diffs
  508. func createStyles(t theme.Theme) (removedLineStyle, addedLineStyle, contextLineStyle, lineNumberStyle stylesi.Style) {
  509. removedLineStyle = stylesi.NewStyle().Background(t.DiffRemovedBg())
  510. addedLineStyle = stylesi.NewStyle().Background(t.DiffAddedBg())
  511. contextLineStyle = stylesi.NewStyle().Background(t.DiffContextBg())
  512. lineNumberStyle = stylesi.NewStyle().Foreground(t.TextMuted()).Background(t.DiffLineNumber())
  513. return
  514. }
  515. // -------------------------------------------------------------------------
  516. // Rendering Functions
  517. // -------------------------------------------------------------------------
  518. // applyHighlighting applies intra-line highlighting to a piece of text
  519. func applyHighlighting(content string, segments []Segment, segmentType LineType, highlightBg compat.AdaptiveColor) string {
  520. // Find all ANSI sequences in the content
  521. ansiRegex := regexp.MustCompile(`\x1b(?:[@-Z\\-_]|\[[0-9?]*(?:;[0-9?]*)*[@-~])`)
  522. ansiMatches := ansiRegex.FindAllStringIndex(content, -1)
  523. // Build a mapping of visible character positions to their actual indices
  524. visibleIdx := 0
  525. ansiSequences := make(map[int]string)
  526. lastAnsiSeq := "\x1b[0m" // Default reset sequence
  527. for i := 0; i < len(content); {
  528. isAnsi := false
  529. for _, match := range ansiMatches {
  530. if match[0] == i {
  531. ansiSequences[visibleIdx] = content[match[0]:match[1]]
  532. lastAnsiSeq = content[match[0]:match[1]]
  533. i = match[1]
  534. isAnsi = true
  535. break
  536. }
  537. }
  538. if isAnsi {
  539. continue
  540. }
  541. // For non-ANSI positions, store the last ANSI sequence
  542. if _, exists := ansiSequences[visibleIdx]; !exists {
  543. ansiSequences[visibleIdx] = lastAnsiSeq
  544. }
  545. visibleIdx++
  546. i++
  547. }
  548. // Apply highlighting
  549. var sb strings.Builder
  550. inSelection := false
  551. currentPos := 0
  552. // Get the appropriate color based on terminal background
  553. bg := getColor(highlightBg)
  554. fg := getColor(theme.CurrentTheme().BackgroundPanel())
  555. var bgColor color.Color
  556. var fgColor color.Color
  557. if bg != nil {
  558. bgColor = lipgloss.Color(*bg)
  559. }
  560. if fg != nil {
  561. fgColor = lipgloss.Color(*fg)
  562. }
  563. for i := 0; i < len(content); {
  564. // Check if we're at an ANSI sequence
  565. isAnsi := false
  566. for _, match := range ansiMatches {
  567. if match[0] == i {
  568. sb.WriteString(content[match[0]:match[1]]) // Preserve ANSI sequence
  569. i = match[1]
  570. isAnsi = true
  571. break
  572. }
  573. }
  574. if isAnsi {
  575. continue
  576. }
  577. // Check for segment boundaries
  578. for _, seg := range segments {
  579. if seg.Type == segmentType {
  580. if currentPos == seg.Start {
  581. inSelection = true
  582. }
  583. if currentPos == seg.End {
  584. inSelection = false
  585. }
  586. }
  587. }
  588. // Get current character
  589. char := string(content[i])
  590. if inSelection {
  591. // Get the current styling
  592. currentStyle := ansiSequences[currentPos]
  593. // Apply foreground and background highlight
  594. if fgColor != nil {
  595. sb.WriteString("\x1b[38;2;")
  596. r, g, b, _ := fgColor.RGBA()
  597. sb.WriteString(fmt.Sprintf("%d;%d;%dm", r>>8, g>>8, b>>8))
  598. } else {
  599. sb.WriteString("\x1b[49m")
  600. }
  601. if bgColor != nil {
  602. sb.WriteString("\x1b[48;2;")
  603. r, g, b, _ := bgColor.RGBA()
  604. sb.WriteString(fmt.Sprintf("%d;%d;%dm", r>>8, g>>8, b>>8))
  605. } else {
  606. sb.WriteString("\x1b[39m")
  607. }
  608. sb.WriteString(char)
  609. // Full reset of all attributes to ensure clean state
  610. sb.WriteString("\x1b[0m")
  611. // Reapply the original ANSI sequence
  612. sb.WriteString(currentStyle)
  613. } else {
  614. // Not in selection, just copy the character
  615. sb.WriteString(char)
  616. }
  617. currentPos++
  618. i++
  619. }
  620. return sb.String()
  621. }
  622. // renderLinePrefix renders the line number and marker prefix for a diff line
  623. func renderLinePrefix(dl DiffLine, lineNum string, marker string, lineNumberStyle stylesi.Style, t theme.Theme) string {
  624. // Style the marker based on line type
  625. var styledMarker string
  626. switch dl.Kind {
  627. case LineRemoved:
  628. styledMarker = stylesi.NewStyle().Foreground(t.DiffRemoved()).Background(t.DiffRemovedBg()).Render(marker)
  629. case LineAdded:
  630. styledMarker = stylesi.NewStyle().Foreground(t.DiffAdded()).Background(t.DiffAddedBg()).Render(marker)
  631. case LineContext:
  632. styledMarker = stylesi.NewStyle().Foreground(t.TextMuted()).Background(t.DiffContextBg()).Render(marker)
  633. default:
  634. styledMarker = marker
  635. }
  636. return lineNumberStyle.Render(lineNum + " " + styledMarker)
  637. }
  638. // renderLineContent renders the content of a diff line with syntax and intra-line highlighting
  639. func renderLineContent(fileName string, dl DiffLine, bgStyle stylesi.Style, highlightColor compat.AdaptiveColor, width int) string {
  640. // Apply syntax highlighting
  641. content := highlightLine(fileName, dl.Content, bgStyle.GetBackground())
  642. // Apply intra-line highlighting if needed
  643. if len(dl.Segments) > 0 && (dl.Kind == LineRemoved || dl.Kind == LineAdded) {
  644. content = applyHighlighting(content, dl.Segments, dl.Kind, highlightColor)
  645. }
  646. // Add a padding space for added/removed lines
  647. if dl.Kind == LineRemoved || dl.Kind == LineAdded {
  648. content = bgStyle.Render(" ") + content
  649. }
  650. // Create the final line and truncate if needed
  651. return bgStyle.MaxHeight(1).Width(width).Render(
  652. ansi.Truncate(
  653. content,
  654. width,
  655. "...",
  656. // stylesi.NewStyleWithColors(t.TextMuted(), bgStyle.GetBackground()).Render("..."),
  657. // stylesi.WithForeground(stylesi.NewStyle().Background(bgStyle.GetBackground()), t.TextMuted()).Render("..."),
  658. ),
  659. )
  660. }
  661. // renderUnifiedLine renders a single line in unified diff format
  662. func renderUnifiedLine(fileName string, dl DiffLine, width int, t theme.Theme) string {
  663. removedLineStyle, addedLineStyle, contextLineStyle, lineNumberStyle := createStyles(t)
  664. // Determine line style and marker based on line type
  665. var marker string
  666. var bgStyle stylesi.Style
  667. var lineNum string
  668. var highlightColor compat.AdaptiveColor
  669. switch dl.Kind {
  670. case LineRemoved:
  671. marker = "-"
  672. bgStyle = removedLineStyle
  673. lineNumberStyle = lineNumberStyle.Background(t.DiffRemovedLineNumberBg()).Foreground(t.DiffRemoved())
  674. highlightColor = t.DiffHighlightRemoved() // TODO: handle "none"
  675. if dl.OldLineNo > 0 {
  676. lineNum = fmt.Sprintf("%6d ", dl.OldLineNo)
  677. } else {
  678. lineNum = " "
  679. }
  680. case LineAdded:
  681. marker = "+"
  682. bgStyle = addedLineStyle
  683. lineNumberStyle = lineNumberStyle.Background(t.DiffAddedLineNumberBg()).Foreground(t.DiffAdded())
  684. highlightColor = t.DiffHighlightAdded() // TODO: handle "none"
  685. if dl.NewLineNo > 0 {
  686. lineNum = fmt.Sprintf(" %7d", dl.NewLineNo)
  687. } else {
  688. lineNum = " "
  689. }
  690. case LineContext:
  691. marker = " "
  692. bgStyle = contextLineStyle
  693. if dl.OldLineNo > 0 && dl.NewLineNo > 0 {
  694. lineNum = fmt.Sprintf("%6d %6d", dl.OldLineNo, dl.NewLineNo)
  695. } else {
  696. lineNum = " "
  697. }
  698. }
  699. // Create the line prefix
  700. prefix := renderLinePrefix(dl, lineNum, marker, lineNumberStyle, t)
  701. // Render the content
  702. prefixWidth := ansi.StringWidth(prefix)
  703. contentWidth := width - prefixWidth
  704. content := renderLineContent(fileName, dl, bgStyle, highlightColor, contentWidth)
  705. return prefix + content
  706. }
  707. // renderDiffColumnLine is a helper function that handles the common logic for rendering diff columns
  708. func renderDiffColumnLine(
  709. fileName string,
  710. dl *DiffLine,
  711. colWidth int,
  712. isLeftColumn bool,
  713. t theme.Theme,
  714. ) string {
  715. if dl == nil {
  716. contextLineStyle := stylesi.NewStyle().Background(t.DiffContextBg())
  717. return contextLineStyle.Width(colWidth).Render("")
  718. }
  719. removedLineStyle, addedLineStyle, contextLineStyle, lineNumberStyle := createStyles(t)
  720. // Determine line style based on line type and column
  721. var marker string
  722. var bgStyle stylesi.Style
  723. var lineNum string
  724. var highlightColor compat.AdaptiveColor
  725. if isLeftColumn {
  726. // Left column logic
  727. switch dl.Kind {
  728. case LineRemoved:
  729. marker = "-"
  730. bgStyle = removedLineStyle
  731. lineNumberStyle = lineNumberStyle.Background(t.DiffRemovedLineNumberBg()).Foreground(t.DiffRemoved())
  732. highlightColor = t.DiffHighlightRemoved() // TODO: handle "none"
  733. case LineAdded:
  734. marker = "?"
  735. bgStyle = contextLineStyle
  736. case LineContext:
  737. marker = " "
  738. bgStyle = contextLineStyle
  739. }
  740. // Format line number for left column
  741. if dl.OldLineNo > 0 {
  742. lineNum = fmt.Sprintf("%6d", dl.OldLineNo)
  743. }
  744. } else {
  745. // Right column logic
  746. switch dl.Kind {
  747. case LineAdded:
  748. marker = "+"
  749. bgStyle = addedLineStyle
  750. lineNumberStyle = lineNumberStyle.Background(t.DiffAddedLineNumberBg()).Foreground(t.DiffAdded())
  751. highlightColor = t.DiffHighlightAdded()
  752. case LineRemoved:
  753. marker = "?"
  754. bgStyle = contextLineStyle
  755. case LineContext:
  756. marker = " "
  757. bgStyle = contextLineStyle
  758. }
  759. // Format line number for right column
  760. if dl.NewLineNo > 0 {
  761. lineNum = fmt.Sprintf("%6d", dl.NewLineNo)
  762. }
  763. }
  764. // Create the line prefix
  765. prefix := renderLinePrefix(*dl, lineNum, marker, lineNumberStyle, t)
  766. // Determine if we should render content
  767. shouldRenderContent := (dl.Kind == LineRemoved && isLeftColumn) ||
  768. (dl.Kind == LineAdded && !isLeftColumn) ||
  769. dl.Kind == LineContext
  770. if !shouldRenderContent {
  771. return bgStyle.Width(colWidth).Render("")
  772. }
  773. // Render the content
  774. prefixWidth := ansi.StringWidth(prefix)
  775. contentWidth := colWidth - prefixWidth
  776. content := renderLineContent(fileName, *dl, bgStyle, highlightColor, contentWidth)
  777. return prefix + content
  778. }
  779. // renderLeftColumn formats the left side of a side-by-side diff
  780. func renderLeftColumn(fileName string, dl *DiffLine, colWidth int) string {
  781. return renderDiffColumnLine(fileName, dl, colWidth, true, theme.CurrentTheme())
  782. }
  783. // renderRightColumn formats the right side of a side-by-side diff
  784. func renderRightColumn(fileName string, dl *DiffLine, colWidth int) string {
  785. return renderDiffColumnLine(fileName, dl, colWidth, false, theme.CurrentTheme())
  786. }
  787. // -------------------------------------------------------------------------
  788. // Public API
  789. // -------------------------------------------------------------------------
  790. // RenderUnifiedHunk formats a hunk for unified display
  791. func RenderUnifiedHunk(fileName string, h Hunk, opts ...UnifiedOption) string {
  792. // Apply options to create the configuration
  793. config := NewUnifiedConfig(opts...)
  794. // Make a copy of the hunk so we don't modify the original
  795. hunkCopy := Hunk{Lines: make([]DiffLine, len(h.Lines))}
  796. copy(hunkCopy.Lines, h.Lines)
  797. // Highlight changes within lines
  798. HighlightIntralineChanges(&hunkCopy)
  799. var sb strings.Builder
  800. for _, line := range hunkCopy.Lines {
  801. sb.WriteString(renderUnifiedLine(fileName, line, config.Width, theme.CurrentTheme()))
  802. sb.WriteString("\n")
  803. }
  804. return sb.String()
  805. }
  806. // RenderSideBySideHunk formats a hunk for side-by-side display
  807. func RenderSideBySideHunk(fileName string, h Hunk, opts ...SideBySideOption) string {
  808. // Apply options to create the configuration
  809. config := NewSideBySideConfig(opts...)
  810. // Make a copy of the hunk so we don't modify the original
  811. hunkCopy := Hunk{Lines: make([]DiffLine, len(h.Lines))}
  812. copy(hunkCopy.Lines, h.Lines)
  813. // Highlight changes within lines
  814. HighlightIntralineChanges(&hunkCopy)
  815. // Pair lines for side-by-side display
  816. pairs := pairLines(hunkCopy.Lines)
  817. // Calculate column width
  818. colWidth := config.TotalWidth / 2
  819. leftWidth := colWidth
  820. rightWidth := config.TotalWidth - colWidth
  821. var sb strings.Builder
  822. for _, p := range pairs {
  823. leftStr := renderLeftColumn(fileName, p.left, leftWidth)
  824. rightStr := renderRightColumn(fileName, p.right, rightWidth)
  825. sb.WriteString(leftStr + rightStr + "\n")
  826. }
  827. return sb.String()
  828. }
  829. // FormatUnifiedDiff creates a unified formatted view of a diff
  830. func FormatUnifiedDiff(filename string, diffText string, opts ...UnifiedOption) (string, error) {
  831. diffResult, err := ParseUnifiedDiff(diffText)
  832. if err != nil {
  833. return "", err
  834. }
  835. var sb strings.Builder
  836. for _, h := range diffResult.Hunks {
  837. sb.WriteString(RenderUnifiedHunk(filename, h, opts...))
  838. }
  839. return sb.String(), nil
  840. }
  841. // FormatDiff creates a side-by-side formatted view of a diff
  842. func FormatDiff(filename string, diffText string, opts ...SideBySideOption) (string, error) {
  843. // t := theme.CurrentTheme()
  844. diffResult, err := ParseUnifiedDiff(diffText)
  845. if err != nil {
  846. return "", err
  847. }
  848. var sb strings.Builder
  849. // config := NewSideBySideConfig(opts...)
  850. for _, h := range diffResult.Hunks {
  851. // sb.WriteString(
  852. // lipgloss.NewStyle().
  853. // Background(t.DiffHunkHeader()).
  854. // Foreground(t.Background()).
  855. // Width(config.TotalWidth).
  856. // Render(h.Header) + "\n",
  857. // )
  858. sb.WriteString(RenderSideBySideHunk(filename, h, opts...))
  859. }
  860. return sb.String(), nil
  861. }