10 "github.com/aymanbagabas/go-udiff"
11 "github.com/charmbracelet/crush/internal/config"
12 "github.com/charmbracelet/crush/internal/highlight"
13 "github.com/charmbracelet/crush/internal/tui/styles"
14 "github.com/charmbracelet/lipgloss/v2"
15 "github.com/charmbracelet/x/ansi"
16 "github.com/sergi/go-diff/diffmatchpatch"
19// -------------------------------------------------------------------------
21// -------------------------------------------------------------------------
23// LineType represents the kind of line in a diff.
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
32// Segment represents a portion of a line for intra-line highlighting
40// DiffLine represents a single line in a diff
42 OldLineNo int // Line number in old file (0 for added lines)
43 NewLineNo int // Line number in new file (0 for removed lines)
44 Kind LineType // Type of line (added, removed, context)
45 Content string // Content of the line
46 Segments []Segment // Segments for intraline highlighting
49// Hunk represents a section of changes in a diff
55// DiffResult contains the parsed result of a diff
56type DiffResult struct {
62// linePair represents a pair of lines for side-by-side display
68// -------------------------------------------------------------------------
70// -------------------------------------------------------------------------
72// ParseConfig configures the behavior of diff parsing
73type ParseConfig struct {
74 ContextSize int // Number of context lines to include
77// ParseOption modifies a ParseConfig
78type ParseOption func(*ParseConfig)
80// WithContextSize sets the number of context lines to include
81func WithContextSize(size int) ParseOption {
82 return func(p *ParseConfig) {
89// -------------------------------------------------------------------------
90// Side-by-Side Configuration
91// -------------------------------------------------------------------------
93// SideBySideConfig configures the rendering of side-by-side diffs
94type SideBySideConfig struct {
98// SideBySideOption modifies a SideBySideConfig
99type SideBySideOption func(*SideBySideConfig)
101// NewSideBySideConfig creates a SideBySideConfig with default values
102func NewSideBySideConfig(opts ...SideBySideOption) SideBySideConfig {
103 config := SideBySideConfig{
104 TotalWidth: 160, // Default width for side-by-side view
107 for _, opt := range opts {
114// WithTotalWidth sets the total width for side-by-side view
115func WithTotalWidth(width int) SideBySideOption {
116 return func(s *SideBySideConfig) {
123// -------------------------------------------------------------------------
125// -------------------------------------------------------------------------
127// ParseUnifiedDiff parses a unified diff format string into structured data
128func ParseUnifiedDiff(diff string) (DiffResult, error) {
129 var result DiffResult
130 var currentHunk *Hunk
132 hunkHeaderRe := regexp.MustCompile(`^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@`)
133 lines := strings.Split(diff, "\n")
135 var oldLine, newLine int
138 for _, line := range lines {
139 // Parse file headers
141 if strings.HasPrefix(line, "--- a/") {
142 result.OldFile = strings.TrimPrefix(line, "--- a/")
145 if strings.HasPrefix(line, "+++ b/") {
146 result.NewFile = strings.TrimPrefix(line, "+++ b/")
152 // Parse hunk headers
153 if matches := hunkHeaderRe.FindStringSubmatch(line); matches != nil {
154 if currentHunk != nil {
155 result.Hunks = append(result.Hunks, *currentHunk)
162 oldStart, _ := strconv.Atoi(matches[1])
163 newStart, _ := strconv.Atoi(matches[3])
169 // Ignore "No newline at end of file" markers
170 if strings.HasPrefix(line, "\\ No newline at end of file") {
174 if currentHunk == nil {
178 // Process the line based on its prefix
182 currentHunk.Lines = append(currentHunk.Lines, DiffLine{
190 currentHunk.Lines = append(currentHunk.Lines, DiffLine{
198 currentHunk.Lines = append(currentHunk.Lines, DiffLine{
208 // Handle empty lines
209 currentHunk.Lines = append(currentHunk.Lines, DiffLine{
220 // Add the last hunk if there is one
221 if currentHunk != nil {
222 result.Hunks = append(result.Hunks, *currentHunk)
228// HighlightIntralineChanges updates lines in a hunk to show character-level differences
229func HighlightIntralineChanges(h *Hunk) {
230 var updated []DiffLine
231 dmp := diffmatchpatch.New()
233 for i := 0; i < len(h.Lines); i++ {
234 // Look for removed line followed by added line
235 if i+1 < len(h.Lines) && h.Lines[i].Kind == LineRemoved && h.Lines[i+1].Kind == LineAdded {
236 oldLine := h.Lines[i]
237 newLine := h.Lines[i+1]
239 // Find character-level differences
240 patches := dmp.DiffMain(oldLine.Content, newLine.Content, false)
241 patches = dmp.DiffCleanupSemantic(patches)
242 patches = dmp.DiffCleanupMerge(patches)
243 patches = dmp.DiffCleanupEfficiency(patches)
245 segments := make([]Segment, 0)
249 for _, patch := range patches {
251 case diffmatchpatch.DiffDelete:
252 segments = append(segments, Segment{
254 End: removeStart + len(patch.Text),
258 removeStart += len(patch.Text)
259 case diffmatchpatch.DiffInsert:
260 segments = append(segments, Segment{
262 End: addStart + len(patch.Text),
266 addStart += len(patch.Text)
268 // Context text, no highlighting needed
269 removeStart += len(patch.Text)
270 addStart += len(patch.Text)
273 oldLine.Segments = segments
274 newLine.Segments = segments
276 updated = append(updated, oldLine, newLine)
277 i++ // Skip the next line as we've already processed it
279 updated = append(updated, h.Lines[i])
286// pairLines converts a flat list of diff lines to pairs for side-by-side display
287func pairLines(lines []DiffLine) []linePair {
292 switch lines[i].Kind {
294 // Check if the next line is an addition, if so pair them
295 if i+1 < len(lines) && lines[i+1].Kind == LineAdded {
296 pairs = append(pairs, linePair{left: &lines[i], right: &lines[i+1]})
299 pairs = append(pairs, linePair{left: &lines[i], right: nil})
303 pairs = append(pairs, linePair{left: nil, right: &lines[i]})
306 pairs = append(pairs, linePair{left: &lines[i], right: &lines[i]})
314// -------------------------------------------------------------------------
315// Syntax Highlighting
316// -------------------------------------------------------------------------
317func getColor(c color.Color) string {
318 rgba := color.RGBAModel.Convert(c).(color.RGBA)
319 return fmt.Sprintf("#%02x%02x%02x", rgba.R, rgba.G, rgba.B)
322// highlightLine applies syntax highlighting to a single line
323func highlightLine(fileName string, line string, bg color.Color) string {
324 highlighted, err := highlight.SyntaxHighlight(line, fileName, bg)
331// createStyles generates the lipgloss styles needed for rendering diffs
332func createStyles(t *styles.Theme) (removedLineStyle, addedLineStyle, contextLineStyle, lineNumberStyle lipgloss.Style) {
333 removedLineStyle = lipgloss.NewStyle().Background(t.S().Diff.RemovedBg)
334 addedLineStyle = lipgloss.NewStyle().Background(t.S().Diff.AddedBg)
335 contextLineStyle = lipgloss.NewStyle().Background(t.S().Diff.ContextBg)
336 lineNumberStyle = lipgloss.NewStyle().Foreground(t.S().Diff.LineNumber)
340// -------------------------------------------------------------------------
341// Rendering Functions
342// -------------------------------------------------------------------------
344// applyHighlighting applies intra-line highlighting to a piece of text
345func applyHighlighting(content string, segments []Segment, segmentType LineType, highlightBg color.Color) string {
346 // Find all ANSI sequences in the content
347 ansiRegex := regexp.MustCompile(`\x1b(?:[@-Z\\-_]|\[[0-9?]*(?:;[0-9?]*)*[@-~])`)
348 ansiMatches := ansiRegex.FindAllStringIndex(content, -1)
350 // Build a mapping of visible character positions to their actual indices
352 ansiSequences := make(map[int]string)
353 lastAnsiSeq := "\x1b[0m" // Default reset sequence
355 for i := 0; i < len(content); {
357 for _, match := range ansiMatches {
359 ansiSequences[visibleIdx] = content[match[0]:match[1]]
360 lastAnsiSeq = content[match[0]:match[1]]
370 // For non-ANSI positions, store the last ANSI sequence
371 if _, exists := ansiSequences[visibleIdx]; !exists {
372 ansiSequences[visibleIdx] = lastAnsiSeq
378 // Apply highlighting
379 var sb strings.Builder
383 // Get the appropriate color based on terminal background
384 bgColor := lipgloss.Color(getColor(highlightBg))
385 // fgColor := lipgloss.Color(getColor(theme.CurrentTheme().Background()))
387 for i := 0; i < len(content); {
388 // Check if we're at an ANSI sequence
390 for _, match := range ansiMatches {
392 sb.WriteString(content[match[0]:match[1]]) // Preserve ANSI sequence
402 // Check for segment boundaries
403 for _, seg := range segments {
404 if seg.Type == segmentType {
405 if currentPos == seg.Start {
408 if currentPos == seg.End {
414 // Get current character
415 char := string(content[i])
418 // Get the current styling
419 currentStyle := ansiSequences[currentPos]
421 // Apply foreground and background highlight
422 // sb.WriteString("\x1b[38;2;")
423 // r, g, b, _ := fgColor.RGBA()
424 // sb.WriteString(fmt.Sprintf("%d;%d;%dm", r>>8, g>>8, b>>8))
425 sb.WriteString("\x1b[48;2;")
426 r, g, b, _ := bgColor.RGBA()
427 sb.WriteString(fmt.Sprintf("%d;%d;%dm", r>>8, g>>8, b>>8))
429 // Reset foreground and background
430 // sb.WriteString("\x1b[39m")
432 // Reapply the original ANSI sequence
433 sb.WriteString(currentStyle)
435 // Not in selection, just copy the character
446// renderLeftColumn formats the left side of a side-by-side diff
447func renderLeftColumn(fileName string, dl *DiffLine, colWidth int) string {
448 t := styles.CurrentTheme()
451 contextLineStyle := t.S().Base.Background(t.S().Diff.ContextBg)
452 return contextLineStyle.Width(colWidth).Render("")
455 removedLineStyle, _, contextLineStyle, lineNumberStyle := createStyles(t)
457 // Determine line style based on line type
459 var bgStyle lipgloss.Style
462 marker = removedLineStyle.Foreground(t.S().Diff.Removed).Render("-")
463 bgStyle = removedLineStyle
464 lineNumberStyle = lineNumberStyle.Foreground(t.S().Diff.Removed).Background(t.S().Diff.RemovedLineNumberBg)
467 bgStyle = contextLineStyle
469 marker = contextLineStyle.Render(" ")
470 bgStyle = contextLineStyle
473 // Format line number
475 if dl.OldLineNo > 0 {
476 lineNum = fmt.Sprintf("%6d", dl.OldLineNo)
479 // Create the line prefix
480 prefix := lineNumberStyle.Render(lineNum + " " + marker)
482 // Apply syntax highlighting
483 content := highlightLine(fileName, dl.Content, bgStyle.GetBackground())
485 // Apply intra-line highlighting for removed lines
486 if dl.Kind == LineRemoved && len(dl.Segments) > 0 {
487 content = applyHighlighting(content, dl.Segments, LineRemoved, t.S().Diff.HighlightRemoved)
490 // Add a padding space for removed lines
491 if dl.Kind == LineRemoved {
492 content = bgStyle.Render(" ") + content
495 // Create the final line and truncate if needed
496 lineText := prefix + content
497 return bgStyle.MaxHeight(1).Width(colWidth).Render(
501 lipgloss.NewStyle().Background(bgStyle.GetBackground()).Foreground(t.FgMuted).Render("..."),
506// renderRightColumn formats the right side of a side-by-side diff
507func renderRightColumn(fileName string, dl *DiffLine, colWidth int) string {
508 t := styles.CurrentTheme()
511 contextLineStyle := lipgloss.NewStyle().Background(t.S().Diff.ContextBg)
512 return contextLineStyle.Width(colWidth).Render("")
515 _, addedLineStyle, contextLineStyle, lineNumberStyle := createStyles(t)
517 // Determine line style based on line type
519 var bgStyle lipgloss.Style
522 marker = addedLineStyle.Foreground(t.S().Diff.Added).Render("+")
523 bgStyle = addedLineStyle
524 lineNumberStyle = lineNumberStyle.Foreground(t.S().Diff.Added).Background(t.S().Diff.AddedLineNumberBg)
527 bgStyle = contextLineStyle
529 marker = contextLineStyle.Render(" ")
530 bgStyle = contextLineStyle
533 // Format line number
535 if dl.NewLineNo > 0 {
536 lineNum = fmt.Sprintf("%6d", dl.NewLineNo)
539 // Create the line prefix
540 prefix := lineNumberStyle.Render(lineNum + " " + marker)
542 // Apply syntax highlighting
543 content := highlightLine(fileName, dl.Content, bgStyle.GetBackground())
545 // Apply intra-line highlighting for added lines
546 if dl.Kind == LineAdded && len(dl.Segments) > 0 {
547 content = applyHighlighting(content, dl.Segments, LineAdded, t.S().Diff.HighlightAdded)
550 // Add a padding space for added lines
551 if dl.Kind == LineAdded {
552 content = bgStyle.Render(" ") + content
555 // Create the final line and truncate if needed
556 lineText := prefix + content
557 return bgStyle.MaxHeight(1).Width(colWidth).Render(
561 lipgloss.NewStyle().Background(bgStyle.GetBackground()).Foreground(t.FgMuted).Render("..."),
566// -------------------------------------------------------------------------
568// -------------------------------------------------------------------------
570// RenderSideBySideHunk formats a hunk for side-by-side display
571func RenderSideBySideHunk(fileName string, h Hunk, opts ...SideBySideOption) string {
572 // Apply options to create the configuration
573 config := NewSideBySideConfig(opts...)
575 // Make a copy of the hunk so we don't modify the original
576 hunkCopy := Hunk{Lines: make([]DiffLine, len(h.Lines))}
577 copy(hunkCopy.Lines, h.Lines)
579 // Highlight changes within lines
580 HighlightIntralineChanges(&hunkCopy)
582 // Pair lines for side-by-side display
583 pairs := pairLines(hunkCopy.Lines)
585 // Calculate column width
586 colWidth := config.TotalWidth / 2
588 leftWidth := colWidth
589 rightWidth := config.TotalWidth - colWidth
590 var sb strings.Builder
591 for _, p := range pairs {
592 leftStr := renderLeftColumn(fileName, p.left, leftWidth)
593 rightStr := renderRightColumn(fileName, p.right, rightWidth)
594 sb.WriteString(leftStr + rightStr + "\n")
600// FormatDiff creates a side-by-side formatted view of a diff
601func FormatDiff(diffText string, opts ...SideBySideOption) (string, error) {
602 diffResult, err := ParseUnifiedDiff(diffText)
607 var sb strings.Builder
608 for _, h := range diffResult.Hunks {
609 sb.WriteString(RenderSideBySideHunk(diffResult.OldFile, h, opts...))
612 return sb.String(), nil
615// GenerateDiff creates a unified diff from two file contents
616func GenerateDiff(beforeContent, afterContent, fileName string) (string, int, int) {
617 // remove the cwd prefix and ensure consistent path format
618 // this prevents issues with absolute paths in different environments
619 cwd := config.WorkingDirectory()
620 fileName = strings.TrimPrefix(fileName, cwd)
621 fileName = strings.TrimPrefix(fileName, "/")
624 unified = udiff.Unified("a/"+fileName, "b/"+fileName, beforeContent, afterContent)
629 lines := strings.SplitSeq(unified, "\n")
630 for line := range lines {
631 if strings.HasPrefix(line, "+") && !strings.HasPrefix(line, "+++") {
633 } else if strings.HasPrefix(line, "-") && !strings.HasPrefix(line, "---") {
638 return unified, additions, removals
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list