diff

package
v0.0.0-...-7b21f04 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package diff provides word-level diff visualization with context-aware hunk merging.

This package is a wrapper around github.com/sergi/go-diff/diffmatchpatch that enhances the diff output by:

  • Tokenizing text into words, whitespace, and punctuation
  • Adding configurable context around changes
  • Merging nearby changes into unified hunks
  • Rendering diffs as HTML (with <del>/<ins> tags) or colored terminal output

Index

Constants

View Source
const (
	// DelBgColor is the ANSI escape code for deleted text background.
	DelBgColor = "\033[48;2;255;200;200m"

	// InsBgColor is the ANSI escape code for inserted text background.
	InsBgColor = "\033[48;2;200;255;200m"

	// ResetBgColor is the ANSI escape code to reset all formatting to default.
	ResetBgColor = "\033[0m"
)

Variables

View Source
var ContextWordsDefault = 20

ContextWordsDefault is the default number of words to show around each change.

Functions

This section is empty.

Types

type Diff

type Diff struct {
	Text1, Text2 string
	ContextWords int
	Diff         []diffmatchpatch.Diff
}

Diff represents a computed difference between two texts with rendering capabilities.

func Compute

func Compute(text1, text2 string, contextWordsOpt ...int) *Diff

Compute calculates the difference between two texts and returns a diff object. The optional ContextWords parameter controls how many words of context to show around each change. If not provided, ContextWordsDefault is used.

Usage:

diffHTML := diff.Compute("old text", "new text").HTML()
diffString := diff.Compute("old text", "new text", 5).String() // custom context size

func ComputeFromPatch

func ComputeFromPatch(text1, patch string, contextWordsOpt ...int) (*Diff, error)

ComputeFromPatch applies a patch to text1 and computes the difference.

func (*Diff) HTML

func (d *Diff) HTML() string

HTML returns an HTML representation of the diff with <del> and <ins> tags. Multiple hunks are separated by <hr/> tags. Returns empty string if texts are identical.

Example output:

You w<del>o</del><ins>a</ins>nt to contribute

func (*Diff) String

func (d *Diff) String() string

String returns a colored terminal representation of the diff using ANSI colors. Deletes are shown with red background, inserts with green background. Multiple hunks are separated by ~~~ markers. Returns empty string if texts are identical.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL