### Install HTMLDiff
Source: https://context7.com/myobie/htmldiff/llms.txt
Add the gem to your Gemfile or install it directly via command line.
```ruby
# Add to your Gemfile
gem 'htmldiff'
# Then run bundle install
# Or install directly: gem install htmldiff
```
--------------------------------
### Install HTMLDiff Gem
Source: https://github.com/myobie/htmldiff/blob/master/README.md
Add the gem to your application's Gemfile.
```ruby
gem 'htmldiff'
```
--------------------------------
### Custom Tokenizer Example
Source: https://github.com/myobie/htmldiff/blob/master/README.md
Implement a custom tokenizer to control how text is split into diff tokens. The tokenizer must respond to a `#tokenize` method and return an Array of Strings. Whitespace tokens should be included to ensure the output can be joined to match the original string.
```ruby
module MyCustomTokenizer
def self.tokenize(string)
string.split(/(\b|\s)/).reject(&:empty?)
end
end
```
```ruby
test = MyCustomTokenizer.tokenize("Hello, world!") #=> ["Hello", ",", " ", "world", "!"]
test.join #=> "Hello, world!"
```
```ruby
diff = HTMLDiff.diff(old_text, new_text, tokenizer: MyCustomTokenizer)
```
--------------------------------
### Default Merge Threshold Example
Source: https://github.com/myobie/htmldiff/blob/master/README.md
Demonstrates the default behavior of HTMLDiff with the `:merge_threshold` option set to 5. Unchanged words adjacent to changes within the threshold are included in the diff segments.
```ruby
old_text = "The quick fox jumped over the dog."
new_text = "The slow fox hopped over the dog."
diff = HTMLDiff.diff(old_text, new_text)
diff == "The quick fox jumpedslow fox hopped over the dog."
```
--------------------------------
### Custom Output Formatter Example
Source: https://github.com/myobie/htmldiff/blob/master/README.md
Define a custom formatter module to control the output format of HTMLDiff changes. The formatter should respond to a `#format` method and can return any object type, typically a String.
```ruby
module MyCustomFormatter
def self.format(changes)
changes.each_with_object(+'') do |(action, old_string, new_string), content|
case action
when '=' # equal
content << new_string if new_string
when '-' # remove
content << %(#{old_string}) if old_string
when '+' # add
content << %(#{new_string}) if new_string
when '!' # replace
content << %(#{old_string}) if old_string
content << %(#{new_string}) if new_string
end
end
end
end
```
```ruby
example_changes = [
['=', 'The ', 'The '],
['+', nil, 'quick '],
['=', 'red fox ', 'red fox '],
['!', 'jumped', 'hopped'],
['=', ' over the ', ' over the '],
['-', 'lazy ', nil],
['=', 'dog.', 'dog.']
]
MyCustomFormatter.format(example_changes)
```
```ruby
#=> "The quick red fox jumped" \
# "hopped over the lazy dog."
```
```ruby
diff = HTMLDiff.diff(old_text, new_text, formatter: MyCustomFormatter)
```
--------------------------------
### Customize HTML Format Options
Source: https://context7.com/myobie/htmldiff/llms.txt
Configure the output tags and CSS classes for insertions, deletions, replacements, and unchanged text using the html_format parameter.
```ruby
require 'htmldiff'
old_text = "The quick red fox jumped over the dog."
new_text = "The red fox hopped over the lazy dog."
# Use span tags with custom CSS classes
diff = HTMLDiff.diff(old_text, new_text, html_format: {
tag: 'span',
class_delete: 'highlight removed',
class_insert: 'highlight added'
})
# => "The quick red fox jumpedhopped over the lazy dog."
# Wrap unchanged text in tags as well
diff = HTMLDiff.diff(old_text, new_text, html_format: {
tag_unchanged: 'span',
class_unchanged: 'unchanged',
tag: 'span',
class_delete: 'deleted',
class_insert: 'inserted'
})
# => "The quick red fox ..."
# Special handling for replacements (when text is both deleted and inserted)
diff = HTMLDiff.diff(old_text, new_text, html_format: {
tag_delete: 'span',
tag_insert: 'div',
tag_replace: 'mark',
class_delete: 'deleted',
class_insert: 'inserted',
class_replace_delete: 'replaced deleted',
class_replace_insert: 'replaced inserted'
})
# => "The quick red fox jumpedhopped over the
lazy
dog."
# Available html_format options:
# :tag - Base HTML tag for all change nodes (default: none)
# :tag_delete - HTML tag for deleted content (default: "del")
# :tag_insert - HTML tag for inserted content (default: "ins")
# :tag_replace - HTML tag for replaced content
# :tag_replace_delete - HTML tag for deleted part of replacements
# :tag_replace_insert - HTML tag for inserted part of replacements
# :tag_unchanged - HTML tag for unchanged content (optional)
# :class - Base CSS class for all change nodes
# :class_delete - CSS class for deleted content
# :class_insert - CSS class for inserted content
# :class_replace - CSS class for replaced content
# :class_replace_delete - CSS class for deleted part of replacements
# :class_replace_insert - CSS class for inserted part of replacements
# :class_unchanged - CSS class for unchanged content
```
--------------------------------
### Compare Strings with Legacy HTML Classes
Source: https://github.com/myobie/htmldiff/blob/master/UPGRADING.md
Compares two strings and outputs the differences using custom HTML classes for insertion, deletion, and modification, replicating legacy behavior.
```ruby
html_format = { class_insert: 'diffins', class_delete: 'diffdel', class_replace: 'diffmod' }
HTMLDiff.diff(old_text, new_text, html_format: html_format)
```
--------------------------------
### Custom HTML Formatting with Options
Source: https://context7.com/myobie/htmldiff/llms.txt
Customize the HTML output by specifying tags and CSS classes for deletions, insertions, and replacements. This allows for fine-grained control over the visual presentation of diffs.
```ruby
# Custom formatting with options
html = HTMLDiff::HtmlFormatter.format(changes,
tag: 'span',
class_delete: 'removed',
class_insert: 'added',
class_replace_delete: 'old-text',
class_replace_insert: 'new-text'
)
# => "The quickslow fox jumped over the"
```
--------------------------------
### Generate Basic HTML Diff
Source: https://github.com/myobie/htmldiff/blob/master/README.md
Use the HTMLDiff.diff method to compare two strings and generate HTML output.
```ruby
require 'htmldiff'
old_text = "The quick red fox jumped over the dog."
new_text = "The red fox hopped over the lazy dog."
diff = HTMLDiff.diff(old_text, new_text)
```
```html
The quick fox jumpedhopped over the lazy dog.
```
--------------------------------
### Customize HTML Output Formatting
Source: https://github.com/myobie/htmldiff/blob/master/README.md
Use the html_format option to specify custom tags and CSS classes for diff elements.
```ruby
old_text = "The quick red fox jumped over the dog."
new_text = "The red fox hopped over the lazy dog."
diff = HTMLDiff.diff(old_text, new_text, html_format: {
tag: 'span',
class_delete: 'highlight removed',
class_insert: 'highlight added'
})
```
```html
The quick red fox jumpedhopped over the lazy dog.
```
--------------------------------
### Define Custom Tokenizer
Source: https://context7.com/myobie/htmldiff/llms.txt
Create a custom tokenizer with a tokenize method to control how text is split into units for comparison.
```ruby
require 'htmldiff'
# Character-level tokenizer for fine-grained diffs
module CharacterTokenizer
def self.tokenize(string)
string.chars
end
end
old_text = "Hello"
new_text = "Help"
# Character-level diff shows exact character changes
diff = HTMLDiff.diff(old_text, new_text, tokenizer: CharacterTokenizer)
# => "Hellop"
# Word-boundary tokenizer
module WordBoundaryTokenizer
def self.tokenize(string)
string.split(/(\b|\s)/).reject(&:empty?)
end
end
# Verify tokenizer output can be joined to match original
tokens = WordBoundaryTokenizer.tokenize("Hello, world!")
# => ["Hello", ",", " ", "world", "!"]
tokens.join
# => "Hello, world!"
diff = HTMLDiff.diff("Hello, world!", "Hi, world!", tokenizer: WordBoundaryTokenizer)
# => "HelloHi, world!"
# Sentence-level tokenizer for paragraph comparisons
module SentenceTokenizer
def self.tokenize(string)
string.scan(/[^.!?]+[.!?]+\s*|\S+/)
end
end
old_paragraph = "First sentence. Second sentence. Third one."
new_paragraph = "First sentence. Modified sentence. Third one."
diff = HTMLDiff.diff(old_paragraph, new_paragraph, tokenizer: SentenceTokenizer)
# Treats entire sentences as atomic units
```
--------------------------------
### Implement Custom Formatter
Source: https://context7.com/myobie/htmldiff/llms.txt
Define a custom formatter class with a format method to transform change tuples into alternative structures like XML or JSON.
```ruby
require 'htmldiff'
# Custom formatter for XML-style output
module XmlDiffFormatter
def self.format(changes)
changes.each_with_object(+'') do |(action, old_string, new_string), content|
case action
when '=' # unchanged
content << new_string if new_string
when '-' # delete
content << %(#{old_string}) if old_string
when '+' # insert
content << %(#{new_string}) if new_string
when '!' # replace
content << %(#{old_string}) if old_string
content << %(#{new_string}) if new_string
end
end
end
end
old_text = "The quick fox"
new_text = "The slow fox jumped"
diff = HTMLDiff.diff(old_text, new_text, formatter: XmlDiffFormatter)
# => "The quickslow fox jumped"
# Custom formatter that returns a data structure instead of string
module JsonDiffFormatter
def self.format(changes)
changes.map do |(action, old_string, new_string)|
case action
when '=' then { type: 'unchanged', text: new_string }
when '-' then { type: 'delete', text: old_string }
when '+' then { type: 'insert', text: new_string }
when '!' then { type: 'replace', old: old_string, new: new_string }
end
end.compact
end
end
diff = HTMLDiff.diff(old_text, new_text, formatter: JsonDiffFormatter)
# => [
# { type: 'unchanged', text: 'The ' },
# { type: 'replace', old: 'quick', new: 'slow' },
# { type: 'unchanged', text: ' fox' },
# { type: 'insert', text: ' jumped' }
# ]
# Change action codes in the changes array:
# '=' - unchanged content (old_string == new_string)
# '-' - deleted content (old_string present, new_string nil)
# '+' - inserted content (old_string nil, new_string present)
# '!' - replaced content (both old_string and new_string present but different)
```
--------------------------------
### HTML Format Options - Customize Output Tags and Classes
Source: https://context7.com/myobie/htmldiff/llms.txt
Customize the HTML output using the `html_format` parameter to specify tags and CSS classes for different diff operations (delete, insert, replace, unchanged).
```APIDOC
## HTML Format Options - Customize Output Tags and Classes
### Description
Allows customization of HTML tags and CSS classes used for representing deletions, insertions, replacements, and unchanged text in the diff output.
### Method
POST
### Endpoint
/htmldiff
### Parameters
#### Query Parameters
- **old_text** (string) - Required - The original text string.
- **new_text** (string) - Required - The modified text string.
- **html_format** (object) - Required - An object containing options to customize the HTML output.
- **tag** (string) - Optional - Base HTML tag for all change nodes (default: none).
- **tag_delete** (string) - Optional - HTML tag for deleted content (default: "del").
- **tag_insert** (string) - Optional - HTML tag for inserted content (default: "ins").
- **tag_replace** (string) - Optional - HTML tag for replaced content.
- **tag_replace_delete** (string) - Optional - HTML tag for the deleted part of replacements.
- **tag_replace_insert** (string) - Optional - HTML tag for the inserted part of replacements.
- **tag_unchanged** (string) - Optional - HTML tag for unchanged content.
- **class** (string) - Optional - Base CSS class for all change nodes.
- **class_delete** (string) - Optional - CSS class for deleted content.
- **class_insert** (string) - Optional - CSS class for inserted content.
- **class_replace** (string) - Optional - CSS class for replaced content.
- **class_replace_delete** (string) - Optional - CSS class for the deleted part of replacements.
- **class_replace_insert** (string) - Optional - CSS class for the inserted part of replacements.
- **class_unchanged** (string) - Optional - CSS class for unchanged content.
### Request Example
```ruby
require 'htmldiff'
old_text = "The quick red fox jumped over the dog."
new_text = "The red fox hopped over the lazy dog."
diff = HTMLDiff.diff(old_text, new_text, html_format: {
tag: 'span',
class_delete: 'highlight removed',
class_insert: 'highlight added'
})
puts diff
```
### Response
#### Success Response (200)
- **diff_html** (string) - The HTML-formatted string with customized tags and classes representing the differences.
#### Response Example
```html
"The quick red fox jumpedhopped over the lazy dog."
```
```
--------------------------------
### Tokenize Text with URLs and Email Addresses
Source: https://context7.com/myobie/htmldiff/llms.txt
Special patterns like URLs and email addresses are recognized and tokenized as single units. This ensures that these distinct elements are treated as atomic parts of the text.
```ruby
# URLs preserved as single tokens
tokens = HTMLDiff::Tokenizer.tokenize("Visit https://example.com/path?q=1")
# => ["Visit", " ", "https://example.com/path?q=1"]
```
```ruby
# Email addresses preserved as single tokens
tokens = HTMLDiff::Tokenizer.tokenize("Contact user@example.com today")
# => ["Contact", " ", "user@example.com", " ", "today"]
```
--------------------------------
### Tokenize Plain Text with HTMLDiff
Source: https://context7.com/myobie/htmldiff/llms.txt
Use HTMLDiff::Tokenizer.tokenize to break down plain text into tokens, preserving whitespace. This is the basic usage for text processing.
```ruby
require 'htmldiff'
# Tokenize plain text
tokens = HTMLDiff::Tokenizer.tokenize("Hello world!")
# => ["Hello", " ", "world", "!"]
tokens.join == "Hello world!"
# => true
```
--------------------------------
### Replace Deprecated DiffBuilder with HTMLDiff.diff
Source: https://github.com/myobie/htmldiff/blob/master/UPGRADING.md
Replaces the usage of the deprecated `HTMLDiff::DiffBuilder` class with the current `HTMLDiff.diff` method for building differences.
```ruby
# Old
HTMLDiff::DiffBuilder.new(a, b).build
# Replace with
HTMLDiff.diff(a, b)
```
--------------------------------
### Compare Strings with Default HTML Tags
Source: https://github.com/myobie/htmldiff/blob/master/UPGRADING.md
Compares two strings and outputs the differences using default `` and `` tags. This is the new default behavior in version 1.0.0.
```ruby
HTMLDiff.diff('Sad', 'Happy')
# Old output
'SadHappy'
# New output
'SadHappy'
```
--------------------------------
### Tokenize Numbers with Formatting
Source: https://context7.com/myobie/htmldiff/llms.txt
The tokenizer preserves formatting in numbers, such as currency symbols and commas. This ensures that numerical values are treated as complete units.
```ruby
# Numbers with formatting preserved
tokens = HTMLDiff::Tokenizer.tokenize("Price: $1,234.56")
# => ["Price", ":", " ", "$", "1,234.56"]
```
--------------------------------
### Special Handling for Replacements
Source: https://github.com/myobie/htmldiff/blob/master/README.md
Customize HTMLDiff to use specific tags and classes for deleted, inserted, and replaced text segments. This allows for fine-grained control over the appearance of replacements.
```ruby
diff = HTMLDiff.diff(old_text, new_text, html_format: {
tag_delete: 'span',
tag_insert: 'div',
tag_replace: 'mark',
class_delete: 'deleted',
class_insert: 'inserted',
class_replace_delete: 'replaced deleted',
class_replace_insert: 'replaced inserted'
})
```
--------------------------------
### Include Unchanged Content in HTML Output
Source: https://context7.com/myobie/htmldiff/llms.txt
Configure the HTML formatter to include unchanged text segments in the output, applying specified tags and classes. This is useful for maintaining the full context of the document.
```ruby
# Include unchanged content in output
html = HTMLDiff::HtmlFormatter.format(changes,
tag_unchanged: 'span',
class_unchanged: 'same'
)
# => "The quickslow fox ..."
```
--------------------------------
### Generate Granular HTML Diff
Source: https://github.com/myobie/htmldiff/blob/master/README.md
Use `HTMLDiff.diff` with `merge_threshold: 0` for granular differences, merging only whitespace. Set to `false` or `-1` to disable merging across whitespace.
```ruby
diff = HTMLDiff.diff(old_text, new_text, merge_threshold: 0)
diff == "The quickslow fox jumpedhopped over the dog."
```
--------------------------------
### Format Changes to HTML with HTMLDiff::HtmlFormatter
Source: https://context7.com/myobie/htmldiff/llms.txt
The HTMLDiff::HtmlFormatter.format method converts change tuples into HTML strings. By default, it uses `` and `` tags to highlight differences.
```ruby
require 'htmldiff'
# Format changes into HTML
changes = [
['=', 'The ', 'The '],
['!', 'quick', 'slow'],
['=', ' fox ', ' fox '],
['+', nil, 'jumped '],
['=', 'over', 'over'],
['-', ' the', nil]
]
# Default formatting uses and tags
html = HTMLDiff::HtmlFormatter.format(changes)
# => "The quickslow fox jumped over the"
```
--------------------------------
### Tokenize Multi-language Text
Source: https://context7.com/myobie/htmldiff/llms.txt
HTMLDiff supports tokenizing text in various languages, correctly identifying words and spaces. This allows for diffing content across different linguistic scripts.
```ruby
# Multi-language support
tokens = HTMLDiff::Tokenizer.tokenize("Привет мир") # Russian
# => ["Привет", " ", "мир"]
```
```ruby
tokens = HTMLDiff::Tokenizer.tokenize("Γειά σου κόσμε") # Greek
# => ["Γειά", " ", "σου", " ", "κόσμε"]
```
--------------------------------
### Configure Merge Threshold
Source: https://context7.com/myobie/htmldiff/llms.txt
Adjust the merge_threshold option to control the granularity of diff segments. Higher values result in chunkier diffs, while lower values or false provide more granular output.
```ruby
require 'htmldiff'
old_text = "The quick fox jumped over the dog."
new_text = "The slow fox hopped over the dog."
# Default merge_threshold is 5
# Words like " fox " (5 chars) are merged into the change
diff = HTMLDiff.diff(old_text, new_text)
# => "The quick fox jumpedslow fox hopped over the dog."
# merge_threshold: 0 - Only merge whitespace, more granular output
diff = HTMLDiff.diff(old_text, new_text, merge_threshold: 0)
# => "The quickslow fox jumpedhopped over the dog."
# merge_threshold: false or -1 - Disable merging entirely
diff = HTMLDiff.diff(old_text, new_text, merge_threshold: false)
# => "The quickslow fox jumpedhopped over the dog."
# merge_threshold: 10 - More aggressive merging for chunkier diffs
diff = HTMLDiff.diff(old_text, new_text, merge_threshold: 10)
# => "The quick fox jumpedslow fox hopped over the dog."
```
--------------------------------
### HTMLDiff::Tokenizer.tokenize
Source: https://context7.com/myobie/htmldiff/llms.txt
Tokenizes plain text, preserving whitespace and special elements like HTML tags, entities, URLs, and email addresses as single tokens.
```APIDOC
## HTMLDiff::Tokenizer.tokenize - Built-in Tokenizer
### Description
The built-in tokenizer handles special cases like HTML tags, HTML entities, URLs, email addresses, and multi-language text. It returns tokens that preserve whitespace when joined.
### Usage Examples
```ruby
require 'htmldiff'
# Tokenize plain text
tokens = HTMLDiff::Tokenizer.tokenize("Hello world!")
# => ["Hello", " ", "world", "!"]
tokens.join == "Hello world!"
# => true
# HTML tags are preserved as single tokens
tokens = HTMLDiff::Tokenizer.tokenize("Click here now")
# => ["Click", " ", "", "here", "", " ", "now"]
# HTML entities preserved as single tokens
tokens = HTMLDiff::Tokenizer.tokenize("5 > 3 & 2 < 4")
# => ["5", " ", ">", " ", "3", " ", "&", " ", "2", " ", "<", " ", "4"]
# URLs preserved as single tokens
tokens = HTMLDiff::Tokenizer.tokenize("Visit https://example.com/path?q=1")
# => ["Visit", " ", "https://example.com/path?q=1"]
# Email addresses preserved as single tokens
tokens = HTMLDiff::Tokenizer.tokenize("Contact user@example.com today")
# => ["Contact", " ", "user@example.com", " ", "today"]
# Numbers with formatting preserved
tokens = HTMLDiff::Tokenizer.tokenize("Price: $1,234.56")
# => ["Price", ":", " ", "$", "1,234.56"]
# Multi-language support
tokens = HTMLDiff::Tokenizer.tokenize("Привет мир") # Russian
# => ["Привет", " ", "мир"]
tokens = HTMLDiff::Tokenizer.tokenize("Γειά σου κόσμε") # Greek
# => ["Γειά", " ", "σου", " ", "κόσμε"]
```
```
--------------------------------
### HTMLDiff::HtmlFormatter.format
Source: https://context7.com/myobie/htmldiff/llms.txt
Converts an array of change tuples into an HTML string, with options for customizing tags and CSS classes.
```APIDOC
## HTMLDiff::HtmlFormatter.format - HTML Rendering
### Description
The HtmlFormatter module converts change tuples into HTML strings. Can be used directly for custom pipelines or to understand the formatting behavior.
### Method Signature
```ruby
HTMLDiff::HtmlFormatter.format(changes, options = {})
```
### Parameters
- **changes** (Array) - An array of change tuples generated by `HTMLDiff::Differ.diff`.
- **options** (Hash, optional) - A hash of options to customize the HTML output.
- **tag** (String): The tag to use for insertions and deletions (default: 'del' for deletions, 'ins' for insertions).
- **class_delete** (String): CSS class for deleted elements.
- **class_insert** (String): CSS class for inserted elements.
- **class_replace_delete** (String): CSS class for the deleted part of a replacement.
- **class_replace_insert** (String): CSS class for the inserted part of a replacement.
- **tag_unchanged** (String): Tag to use for unchanged text.
- **class_unchanged** (String): CSS class for unchanged text.
### Return Value
A string containing the HTML representation of the differences.
### Usage Examples
```ruby
require 'htmldiff'
# Format changes into HTML
changes = [
['=', 'The ', 'The '],
['!', 'quick', 'slow'],
['=', ' fox ', ' fox '],
['+', nil, 'jumped '],
['=', 'over', 'over'],
['-', ' the', nil]
]
# Default formatting uses and tags
html = HTMLDiff::HtmlFormatter.format(changes)
# => "The quickslow fox jumped over the"
# Custom formatting with options
html = HTMLDiff::HtmlFormatter.format(changes,
tag: 'span',
class_delete: 'removed',
class_insert: 'added',
class_replace_delete: 'old-text',
class_replace_insert: 'new-text'
)
# => "The quickslow fox jumped over the"
# Include unchanged content in output
html = HTMLDiff::HtmlFormatter.format(changes,
tag_unchanged: 'span',
class_unchanged: 'same'
)
# => "The quickslow fox ..."
```
```
--------------------------------
### Tokenize Text with HTML Tags and Entities
Source: https://context7.com/myobie/htmldiff/llms.txt
The built-in tokenizer handles HTML tags and entities as single tokens, ensuring they are not broken down further. This is useful for preserving HTML structure during diffing.
```ruby
# HTML tags are preserved as single tokens
tokens = HTMLDiff::Tokenizer.tokenize("Click here now")
# => ["Click", " ", "", "here", "", " ", "now"]
```
```ruby
# HTML entities preserved as single tokens
tokens = HTMLDiff::Tokenizer.tokenize("5 > 3 & 2 < 4")
# => ["5", " ", ">", " ", "3", " ", "&", " ", "2", " ", "<", " ", "4"]
```
--------------------------------
### Generate Low-Level Diff with HTMLDiff::Differ
Source: https://context7.com/myobie/htmldiff/llms.txt
The HTMLDiff::Differ.diff method computes differences between two token arrays using the Longest Common Subsequence (LCS) algorithm. It returns an array of change tuples representing insertions, deletions, and replacements.
```ruby
require 'htmldiff'
old_tokens = ["The", " ", "quick", " ", "fox"]
new_tokens = ["The", " ", "slow", " ", "fox", " ", "jumped"]
changes = HTMLDiff::Differ.diff(old_tokens, new_tokens)
# => [
# ["=", "The ", "The "], # unchanged
# ["!", "quick", "slow"], # replaced
# ["=", " fox", " fox"], # unchanged
# ["+", nil, " jumped"] # inserted
# ]
# Each change tuple: [action, old_string, new_string]
# Actions:
# '=' - unchanged (old_string == new_string)
# '-' - deleted (new_string is nil)
# '+' - inserted (old_string is nil)
# '!' - replaced (both present, different)
```
--------------------------------
### HTMLDiff.diff - Generate HTML Diff
Source: https://context7.com/myobie/htmldiff/llms.txt
The primary method for generating HTML diffs between two text strings. It returns an HTML string with insertions and deletions marked using configurable HTML tags.
```APIDOC
## HTMLDiff.diff - Generate HTML Diff
### Description
Generates HTML-formatted diffs between two text strings, marking insertions and deletions with configurable HTML tags.
### Method
POST
### Endpoint
/htmldiff
### Parameters
#### Query Parameters
- **old_text** (string) - Required - The original text string.
- **new_text** (string) - Required - The modified text string.
- **html_format** (object) - Optional - An object to customize HTML output tags and CSS classes for diff operations.
### Request Example
```ruby
require 'htmldiff'
old_text = "The quick red fox jumped over the dog."
new_text = "The red fox hopped over the lazy dog."
diff = HTMLDiff.diff(old_text, new_text)
puts diff
```
### Response
#### Success Response (200)
- **diff_html** (string) - The HTML-formatted string representing the differences between the two input texts.
#### Response Example
```html
"The quick red fox jumpedhopped over the lazy dog."
```
```
--------------------------------
### HTMLDiff::Differ.diff
Source: https://context7.com/myobie/htmldiff/llms.txt
Computes differences between two arrays of tokens using the Longest Common Subsequence (LCS) algorithm, returning an array of change tuples.
```APIDOC
## HTMLDiff::Differ.diff - Low-Level Diff Generation
### Description
The Differ module computes differences between token arrays using the LCS algorithm. Returns an array of change tuples that can be processed by any formatter.
### Method Signature
```ruby
HTMLDiff::Differ.diff(old_tokens, new_tokens, merge_threshold: nil)
```
### Parameters
- **old_tokens** (Array) - The array of tokens from the old version of the text.
- **new_tokens** (Array) - The array of tokens from the new version of the text.
- **merge_threshold** (Integer or Boolean, optional) - Controls merging behavior. `0` for more granular changes, `false` for no merging.
### Return Value
An array of change tuples. Each tuple is in the format `[action, old_string, new_string]`.
- **'='**: Unchanged (old_string == new_string)
- **'-'**: Deleted (new_string is nil)
- **'+'**: Inserted (old_string is nil)
- **'!'**: Replaced (both present, different)
### Usage Examples
```ruby
require 'htmldiff'
old_tokens = ["The", " ", "quick", " ", "fox"]
new_tokens = ["The", " ", "slow", " ", "fox", " ", "jumped"]
changes = HTMLDiff::Differ.diff(old_tokens, new_tokens)
# => [
# ["=", "The ", "The "], # unchanged
# ["!", "quick", "slow"], # replaced
# ["=", " fox", " fox"], # unchanged
# ["+", nil, " jumped"] # inserted
# ]
# Control merging behavior
changes = HTMLDiff::Differ.diff(old_tokens, new_tokens, merge_threshold: 0)
# More granular changes, only whitespace merged
changes = HTMLDiff::Differ.diff(old_tokens, new_tokens, merge_threshold: false)
# No merging at all
```
```
--------------------------------
### Wrap Unchanged Text in Tags
Source: https://github.com/myobie/htmldiff/blob/master/README.md
Configure HTMLDiff to wrap unchanged text in specified HTML tags and classes. This is useful for styling or identifying unchanged portions of the diff.
```ruby
diff = HTMLDiff.diff(old_text, new_text, html_format: {
tag_unchanged: 'span',
class_unchanged: 'unchanged',
tag: 'span',
class_delete: 'deleted',
class_insert: 'inserted'
})
```
--------------------------------
### Control Merging Behavior in Diff Generation
Source: https://context7.com/myobie/htmldiff/llms.txt
The `merge_threshold` option in `HTMLDiff::Differ.diff` controls how adjacent changes are merged. Setting it to 0 allows for more granular changes, while `false` disables merging entirely.
```ruby
# Control merging behavior
changes = HTMLDiff::Differ.diff(old_tokens, new_tokens, merge_threshold: 0)
# More granular changes, only whitespace merged
changes = HTMLDiff::Differ.diff(old_tokens, new_tokens, merge_threshold: false)
# No merging at all
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.