### Install @sanity/diff-match-patch
Source: https://github.com/sanity-io/diff-match-patch/blob/main/README.md
Install the library using npm.
```bash
npm install --save @sanity/diff-match-patch
```
--------------------------------
### Applying Patches (Detailed)
Source: https://github.com/sanity-io/diff-match-patch/blob/main/README.md
Provides a more detailed example of applying patches and analyzing the results.
```APIDOC
## Applying Patches
### Description
Applies a list of patches to a source text and returns the modified text along with results indicating successful matches and misses.
### Method
N/A (This is a library usage example)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```ts
import {applyPatches} from '@sanity/diff-match-patch'
const [newValue, results] = applyPatches(patch, 'source text')
const matches = results.filter((matched) => matched === true).length
const misses = results.length - matches
console.log('Patch applied with %d matches and %d misses', matches, misses)
console.log('New value: %s', newValue)
```
### Response
#### Success Response (200)
N/A (This is a library usage example)
#### Response Example
N/A
```
--------------------------------
### Utilize Diff Type Constants with makeDiff
Source: https://context7.com/sanity-io/diff-match-patch/llms.txt
The library exports constants DIFF_DELETE (-1), DIFF_INSERT (1), and DIFF_EQUAL (0) to represent diff operation types. These are used in diff tuples returned by functions like makeDiff. The example demonstrates processing diffs and converting them to HTML for visualization.
```typescript
import {
makeDiff,
DIFF_DELETE,
DIFF_INSERT,
DIFF_EQUAL,
type Diff,
type DiffType
} from '@sanity/diff-match-patch'
const diffs: Diff[] = makeDiff('Hello World', 'Hello Beautiful World')
// Process diffs with type checking
diffs.forEach(([type, text]: Diff) => {
switch (type) {
case DIFF_DELETE:
console.log(`- ${text}`) // Removed
break
case DIFF_INSERT:
console.log(`+ ${text}`) // Added
break
case DIFF_EQUAL:
console.log(` ${text}`) // Unchanged
break
}
})
// Create HTML diff view
function diffToHtml(diffs: Diff[]): string {
return diffs.map(([type, text]) => {
const escaped = text
.replace(/&/g, '&')
.replace(//g, '>')
switch (type) {
case DIFF_DELETE:
return `${escaped}`
case DIFF_INSERT:
return `${escaped}`
default:
return `${escaped}`
}
}).join('')
}
const html = diffToHtml(makeDiff('old text', 'new text'))
console.log(html)
```
--------------------------------
### Creating and Applying Patches
Source: https://github.com/sanity-io/diff-match-patch/blob/main/README.md
Demonstrates how to create internal array-based patches, convert them to unidiff format, and apply them to text.
```APIDOC
## Creating and Applying Patches
### Description
This section shows how to generate patches from two strings, convert them to a string format, and then apply them back to the original text.
### Method
N/A (This is a library usage example)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```ts
import {makePatches, applyPatches, stringifyPatches, parsePatches} from '@sanity/diff-match-patch'
// Make array of diffs in internal array format, eg tuples of `[DiffType, string]`
const patches = makePatches('from this', 'to this')
// Make unidiff-formatted (string) patch
const patch = stringifyPatches(patches)
// Apply the patch (array representation)
const [newValue] = applyPatches(patches, 'from this')
// Apply the patch (unidiff-formatted)
const [alsoNewValue] = applyPatches(parsePatch(patch), 'from this')
```
### Response
#### Success Response (200)
N/A (This is a library usage example)
#### Response Example
N/A
```
--------------------------------
### Migrate: Make Patches
Source: https://github.com/sanity-io/diff-match-patch/blob/main/README.md
Compare the patch creation API between the original `diff-match-patch` library and `@sanity/diff-match-patch`.
```diff
-import {diff_match_patch as DiffMatchPatch} from 'diff-match-patch'
-const dmp = new DiffMatchPatch()
-const rawPatch = dmp.patch_make('from this', 'to this')
-const patch = rawPatch.map(p => p.toString()).join('')
+import {makePatches, stringifyPatches} from '@sanity/diff-match-patch'
+const patch = stringifyPatches(makePatches('from this', 'to this'))
```
--------------------------------
### Migrate: Apply Patches
Source: https://github.com/sanity-io/diff-match-patch/blob/main/README.md
Compare the patch application API between the original `diff-match-patch` library and `@sanity/diff-match-patch`.
```diff
-import {diff_match_patch as DiffMatchPatch} from 'diff-match-patch'
-const dmp = new DiffMatchPatch()
-const patch = dmp.patch_fromText('some-text-patch')
-const [newValue] = dmp.patch_apply(patch, 'source text')
+import {applyPatches, parsePatch} from '@sanity/diff-match-patch'
+const [newValue] = applyPatches(parsePatch('some-text-patch'), 'source text')
```
--------------------------------
### Migrate: Create Diffs
Source: https://github.com/sanity-io/diff-match-patch/blob/main/README.md
Compare the diff creation API between the original `diff-match-patch` library and `@sanity/diff-match-patch`.
```diff
-import {diff_match_patch as DiffMatchPatch} from 'diff-match-patch'
-const dmp = new DiffMatchPatch()
-const diffs = dmp.diff_main('from this', 'to this')
-dmp.diff_cleanupSemantic(diffs)
+import {makeDiff, cleanupSemantic} from '@sanity/diff-match-patch'
+const diffs = cleanupSemantic(makeDiff('from this', 'to this'))
```
--------------------------------
### Creating Diffs
Source: https://github.com/sanity-io/diff-match-patch/blob/main/README.md
Illustrates how to generate an array of differences between two strings.
```APIDOC
## Creating Diffs
### Description
Generates an array of diff tuples, where each tuple represents a change between two strings.
### Method
N/A (This is a library usage example)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```ts
import {makeDiff} from '@sanity/diff-match-patch'
// Make an array of diff tuples, eg `[DiffType, string]`
const diff = makeDiff('from this', 'to this')
```
### Response
#### Success Response (200)
N/A (This is a library usage example)
#### Response Example
N/A
```
--------------------------------
### Migration from `diff-match-patch`
Source: https://github.com/sanity-io/diff-match-patch/blob/main/README.md
Highlights the API differences when migrating from the original `diff-match-patch` library to `@sanity/diff-match-patch`.
```APIDOC
## Migrating from `diff-match-patch`
### Description
This section details the API changes required when migrating from the original `diff-match-patch` library to `@sanity/diff-match-patch`.
### Method
N/A (This is a migration guide)
### Endpoint
N/A
### Parameters
N/A
### Request Example
#### Creating diffs
```diff
-import {diff_match_patch as DiffMatchPatch} from 'diff-match-patch'
-const dmp = new DiffMatchPatch()
-const diffs = dmp.diff_main('from this', 'to this')
-dmp.diff_cleanupSemantic(diffs)
+import {makeDiff, cleanupSemantic} from '@sanity/diff-match-patch'
+const diffs = cleanupSemantic(makeDiff('from this', 'to this'))
```
#### Make patches
```diff
-import {diff_match_patch as DiffMatchPatch} from 'diff-match-patch'
-const dmp = new DiffMatchPatch()
-const rawPatch = dmp.patch_make('from this', 'to this')
-const patch = rawPatch.map(p => p.toString()).join('')
+import {makePatches, stringifyPatches} from '@sanity/diff-match-patch'
+const patch = stringifyPatches(makePatches('from this', 'to this'))
```
#### Apply patches
```diff
-import {diff_match_patch as DiffMatchPatch} from 'diff-match-patch'
-const dmp = new DiffMatchPatch()
-const patch = dmp.patch_fromText('some-text-patch')
-const [newValue] = dmp.patch_apply(patch, 'source text')
+import {applyPatches, parsePatch} from '@sanity/diff-match-patch'
+const [newValue] = applyPatches(parsePatch('some-text-patch'), 'source text')
```
### Response
#### Success Response (200)
N/A (This is a migration guide)
#### Response Example
N/A
```
--------------------------------
### Matching Text
Source: https://github.com/sanity-io/diff-match-patch/blob/main/README.md
Shows how to find the best fuzzy match for a pattern within a block of text.
```APIDOC
## Matching Text
### Description
Finds the best fuzzy match for a given pattern within a larger text, considering accuracy and location.
### Method
N/A (This is a library usage example)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```ts
import {match} from '@sanity/diff-match-patch'
// Find position in text for the given pattern, at the approximate location given
const position = match('some text to match against', 'match', 9)
```
### Response
#### Success Response (200)
N/A (This is a library usage example)
#### Response Example
N/A
```
--------------------------------
### applyPatches - Apply Patches to Text
Source: https://context7.com/sanity-io/diff-match-patch/llms.txt
Merges a set of patches onto text, returning both the new text and an array of booleans indicating which patches were successfully applied. It uses fuzzy matching to apply patches even when the underlying text has changed slightly.
```APIDOC
## applyPatches
### Description
Merges a set of patches onto text, returning both the new text and an array of booleans indicating which patches were successfully applied. It uses fuzzy matching to apply patches even when the underlying text has changed slightly.
### Method
`applyPatches`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```typescript
import { makePatches, applyPatches } from '@sanity/diff-match-patch'
const original = 'The quick brown fox jumps over the lazy dog.'
const target = 'The slow brown cat leaps over the happy dog.'
const patches = makePatches(original, target)
// Apply to original text (perfect match)
const [newText, results] = applyPatches(patches, original)
console.log('New text:', newText)
console.log('All patches applied:', results.every(r => r)) // true
// Apply with options
const [resultWithOptions] = applyPatches(patches, original, {
margin: 4,
deleteThreshold: 0.4,
allowExceedingIndices: false
})
```
### Response
#### Success Response (200)
- **newText** (string) - The text after applying the patches.
- **results** (Array) - An array of booleans indicating whether each patch was successfully applied.
#### Response Example
```json
[
"The slow brown cat leaps over the happy dog.",
[true, true, ...]
]
```
```
--------------------------------
### Optimize for Patch Generation with cleanupEfficiency
Source: https://context7.com/sanity-io/diff-match-patch/llms.txt
Reduces the number of edits by eliminating operationally trivial equalities, optimizing for efficient patch generation. Use this when the primary goal is patching, not human readability. An optional edit cost parameter can be provided.
```typescript
import { makeDiff, cleanupEfficiency } from '@sanity/diff-match-patch'
// Create diffs optimized for patching
const diffs = makeDiff(
'abcdefghij',
'abcXdefghYij'
)
// Default edit cost of 4
const efficientDiffs = cleanupEfficiency(diffs)
console.log(efficientDiffs)
// Custom edit cost (lower = more aggressive cleanup)
const aggressiveDiffs = cleanupEfficiency(diffs, 2)
console.log(aggressiveDiffs)
```
```typescript
// Combine with semantic cleanup for best results
import { cleanupSemantic } from '@sanity/diff-match-patch'
const optimizedDiffs = cleanupEfficiency(cleanupSemantic(makeDiff(oldText, newText)))
```
--------------------------------
### cleanupEfficiency - Optimize for Patch Generation
Source: https://context7.com/sanity-io/diff-match-patch/llms.txt
Reduces the number of edits by eliminating operationally trivial equalities, optimizing the diff for efficient patch generation.
```APIDOC
## cleanupEfficiency - Optimize for Patch Generation
### Description
Reduces the number of edits by eliminating operationally trivial equalities, optimizing the diff for efficient patch generation rather than human readability. It uses an edit cost parameter to determine when small equalities should be eliminated.
### Method
POST
### Endpoint
`/api/diff/cleanup/efficiency` (Conceptual - this is a library function, not a REST endpoint)
### Parameters
#### Query Parameters
- **diffs** (array) - Required - The array of diff tuples generated by `makeDiff`.
- **editCost** (number) - Optional - The cost parameter for determining trivial equalities. Defaults to 4. Lower values result in more aggressive cleanup.
### Request Example
```typescript
import { makeDiff, cleanupEfficiency } from '@sanity/diff-match-patch'
// Create diffs optimized for patching
const diffs = makeDiff(
'abcdefghij',
'abcXdefghYij'
)
// Default edit cost of 4
const efficientDiffs = cleanupEfficiency(diffs)
console.log(efficientDiffs)
// Custom edit cost (lower = more aggressive cleanup)
const aggressiveDiffs = cleanupEfficiency(diffs, 2)
console.log(aggressiveDiffs)
// Combine with semantic cleanup for best results
import { cleanupSemantic } from '@sanity/diff-match-patch'
const optimizedDiffs = cleanupEfficiency(cleanupSemantic(makeDiff(oldText, newText)))
```
### Response
#### Success Response (200)
- **efficientDiffs** (array) - An array of diff tuples, optimized for patch generation efficiency.
#### Response Example
```json
[
[0, 'abc'],
[1, 'X'],
[0, 'defgh'],
[1, 'Y'],
[0, 'ij']
]
```
```
--------------------------------
### Create and Apply Patches
Source: https://github.com/sanity-io/diff-match-patch/blob/main/README.md
Generate patches from two strings and apply them. Supports both internal array format and unidiff string format.
```typescript
import {makePatches, applyPatches, stringifyPatches, parsePatches} from '@sanity/diff-match-patch'
// Make array of diffs in internal array format, eg tuples of `[DiffType, string]`
const patches = makePatches('from this', 'to this')
// Make unidiff-formatted (string) patch
const patch = stringifyPatches(patches)
// Apply the patch (array representation)
const [newValue] = applyPatches(patches, 'from this')
// Apply the patch (unidiff-formatted)
const [alsoNewValue] = applyPatches(parsePatch(patch), 'from this')
```
--------------------------------
### makeDiff - Compare Two Text Strings
Source: https://context7.com/sanity-io/diff-match-patch/llms.txt
Compares two strings and returns an array of diff tuples representing the differences. Supports Unicode surrogate pairs, configurable timeout, and line-mode options.
```APIDOC
## makeDiff - Compare Two Text Strings
### Description
Compares two strings and returns an array of diff tuples representing the differences between them. Each tuple contains a diff type constant (`DIFF_DELETE`, `DIFF_INSERT`, or `DIFF_EQUAL`) and the corresponding text segment. The function handles Unicode surrogate pairs correctly and supports configurable timeout and line-mode options.
### Method
POST
### Endpoint
`/api/diff` (Conceptual - this is a library function, not a REST endpoint)
### Parameters
#### Query Parameters
- **text1** (string) - Required - The first string to compare.
- **text2** (string) - Required - The second string to compare.
- **options** (object) - Optional - Configuration options.
- **timeout** (number) - Optional - Maximum time in seconds to perform the diff.
- **checkLines** (boolean) - Optional - If true, diffs will be performed line by line.
### Request Example
```typescript
import { makeDiff, DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL } from '@sanity/diff-match-patch'
// Basic diff between two strings
const diffs = makeDiff('Hello World', 'Hello Beautiful World')
console.log(diffs)
// Diff with options
const diffsWithTimeout = makeDiff(
'The quick brown fox jumps over the lazy dog',
'The slow brown cat jumps over the happy dog',
{ timeout: 2, checkLines: true }
)
// Process diff results
diffsWithTimeout.forEach(([type, text]) => {
if (type === DIFF_DELETE) console.log(`Removed: "${text}"`)
if (type === DIFF_INSERT) console.log(`Added: "${text}"`)
if (type === DIFF_EQUAL) console.log(`Unchanged: "${text}"`)
})
```
### Response
#### Success Response (200)
- **diffs** (array) - An array of diff tuples. Each tuple is `[type, text]`, where `type` is one of `DIFF_DELETE` (-1), `DIFF_INSERT` (1), or `DIFF_EQUAL` (0), and `text` is the corresponding string segment.
#### Response Example
```json
[
[0, 'Hello '], // DIFF_EQUAL
[1, 'Beautiful '], // DIFF_INSERT
[0, 'World'] // DIFF_EQUAL
]
```
```
--------------------------------
### Apply Patches with Results
Source: https://github.com/sanity-io/diff-match-patch/blob/main/README.md
Apply a patch to source text and receive the new value along with results indicating match or miss for each patch operation.
```typescript
import {applyPatches} from '@sanity/diff-match-patch'
const [newValue, results] = applyPatches(patch, 'source text')
const matches = results.filter((matched) => matched === true).length
const misses = results.length - matches
console.log('Patch applied with %d matches and %d misses', matches, misses)
console.log('New value: %s', newValue)
```
--------------------------------
### parsePatch - Parse Text to Patch Objects
Source: https://context7.com/sanity-io/diff-match-patch/llms.txt
Converts a unidiff-formatted string back into an array of patch objects. This is useful for storing patches as strings and reconstructing them later.
```APIDOC
## parsePatch
### Description
Converts a unidiff-formatted string back into an array of patch objects that can be applied to text. This enables storing patches as strings and reconstructing them later.
### Method
`parsePatch`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```typescript
import { parsePatch } from '@sanity/diff-match-patch'
const patchText = `@@ -1,11 +1,13 @@
Hello
+World
there`
const patches = parsePatch(patchText)
console.log('Parsed patches:', patches.length)
```
### Response
#### Success Response (200)
- **patches** (Array) - An array of patch objects.
#### Response Example
```json
[
{
"diffs": [
{ "operation": "insert", "text": "\nWorld" },
{ "operation": "equal", "text": "\n there" }
],
"start1": 1,
"length1": 11,
"start2": 1,
"length2": 13
}
]
```
```
--------------------------------
### cleanupSemantic - Improve Diff Readability
Source: https://context7.com/sanity-io/diff-match-patch/llms.txt
Reduces the number of edits by eliminating semantically trivial equalities, aligning edit boundaries to word boundaries for improved human readability.
```APIDOC
## cleanupSemantic - Improve Diff Readability
### Description
Reduces the number of edits by eliminating semantically trivial equalities. It shifts edit boundaries to align with word boundaries and language structure, producing diffs that are easier for humans to read and understand.
### Method
POST
### Endpoint
`/api/diff/cleanup/semantic` (Conceptual - this is a library function, not a REST endpoint)
### Parameters
#### Query Parameters
- **diffs** (array) - Required - The array of diff tuples generated by `makeDiff`.
### Request Example
```typescript
import { makeDiff, cleanupSemantic } from '@sanity/diff-match-patch'
// Raw diff can produce fragmented results
const rawDiffs = makeDiff('The cat sat on the mat.', 'The dog sat on the rug.')
console.log('Raw diffs:', rawDiffs)
// Clean up for better readability
const cleanDiffs = cleanupSemantic(rawDiffs)
console.log('Semantic diffs:', cleanDiffs)
// Combine for common use case
const humanReadableDiff = cleanupSemantic(makeDiff(
'function calculateTotal(items) { return items.reduce((a, b) => a + b, 0); }',
'function computeSum(items) { return items.reduce((sum, item) => sum + item, 0); }'
))
```
### Response
#### Success Response (200)
- **cleanDiffs** (array) - An array of diff tuples, optimized for semantic readability.
#### Response Example
```json
[
[0, 'The '],
[-1, 'cat'],
[1, 'dog'],
[0, ' sat on the '],
[-1, 'mat'],
[1, 'rug'],
[0, '.']
]
```
```
--------------------------------
### Compare Two Text Strings with makeDiff
Source: https://context7.com/sanity-io/diff-match-patch/llms.txt
Compares two strings and returns an array of diff tuples. Handles Unicode surrogate pairs correctly and supports configurable timeout and line-mode options. Use this for basic text comparison.
```typescript
import { makeDiff, DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL } from '@sanity/diff-match-patch'
// Basic diff between two strings
const diffs = makeDiff('Hello World', 'Hello Beautiful World')
console.log(diffs)
// Output: [
// [0, 'Hello '], // DIFF_EQUAL
// [1, 'Beautiful '], // DIFF_INSERT
// [0, 'World'] // DIFF_EQUAL
// ]
```
```typescript
// Diff with options
const diffsWithTimeout = makeDiff(
'The quick brown fox jumps over the lazy dog',
'The slow brown cat jumps over the happy dog',
{ timeout: 2, checkLines: true }
)
// Process diff results
diffsWithTimeout.forEach(([type, text]) => {
if (type === DIFF_DELETE) console.log(`Removed: "${text}"`)
if (type === DIFF_INSERT) console.log(`Added: "${text}"`)
if (type === DIFF_EQUAL) console.log(`Unchanged: "${text}"`)
})
// Output:
// Unchanged: "The "
// Removed: "quick"
// Added: "slow"
// Unchanged: " brown "
// Removed: "fox"
// Added: "cat"
// Unchanged: " jumps over the "
// Removed: "lazy"
// Added: "happy"
// Unchanged: " dog"
```
--------------------------------
### Convert Patches to Unidiff String
Source: https://context7.com/sanity-io/diff-match-patch/llms.txt
Use `stringifyPatches` to convert an array of patch objects into a unidiff-formatted string. `stringifyPatch` converts a single patch. This format is useful for storage and transmission.
```typescript
import { makePatches, stringifyPatches, stringifyPatch } from '@sanity/diff-match-patch'
const patches = makePatches(
'Line one\nLine two\nLine three',
'Line one\nLine 2\nLine three\nLine four'
)
// Convert all patches to string
const patchText = stringifyPatches(patches)
console.log(patchText)
// Output:
// @@ -1,28 +1,38 @@
// Line one%0A
// -Line two
// +Line 2
// %0ALine three
// +%0ALine four
// Convert single patch
const singlePatchText = stringifyPatch(patches[0])
console.log(singlePatchText)
// Store and retrieve patches
const storedPatch = stringifyPatches(patches)
localStorage.setItem('documentPatch', storedPatch)
// Later...
const retrievedPatch = localStorage.getItem('documentPatch')
```
--------------------------------
### Create Patches with `makePatches`
Source: https://context7.com/sanity-io/diff-match-patch/llms.txt
The `makePatches` function generates patch objects to transform text. It can accept two strings, diff tuples, or source text with diffs. Custom context size (margin) can be specified.
```typescript
import { makePatches, stringifyPatches } from '@sanity/diff-match-patch'
// Create patches from two strings
const patches = makePatches(
'The quick brown fox jumps over the lazy dog.',
'The slow brown cat leaps over the happy dog.'
)
console.log('Number of patches:', patches.length)
// Create patches with custom margin (context size)
const patchesWithMargin = makePatches(
'Hello World',
'Hello Beautiful World',
{ margin: 8 } // Larger context for better matching
)
// Create patches from pre-computed diffs
import { makeDiff, cleanupSemantic, cleanupEfficiency } from '@sanity/diff-match-patch'
const diffs = cleanupEfficiency(cleanupSemantic(makeDiff(oldText, newText)))
const patchesFromDiffs = makePatches(diffs)
// Create patches with original text and diffs
const patchesWithText = makePatches(originalText, diffs)
// Convert to unidiff format for storage or transmission
const unidiff = stringifyPatches(patches)
console.log(unidiff)
// Output:
// @@ -1,15 +1,14 @@
// The
// -quick
// +slow
// brown
// -fox jumps
// +cat leaps
// over the
// -lazy
// +happy
// dog.
```
--------------------------------
### Match Text
Source: https://github.com/sanity-io/diff-match-patch/blob/main/README.md
Find the best fuzzy match for a pattern within a block of text at an approximate location.
```typescript
import {match} from '@sanity/diff-match-patch'
// Find position in text for the given pattern, at the approximate location given
const position = match('some text to match against', 'match', 9)
```
--------------------------------
### Map Position Between Texts
Source: https://context7.com/sanity-io/diff-match-patch/llms.txt
Use `xIndex` with diff results to map a location from one text version to another. This is essential for updating cursor positions or selection ranges during collaborative editing.
```typescript
import { makeDiff, xIndex } from '@sanity/diff-match-patch'
const textA = 'The cat sat'
const textB = 'The big cat sat'
const diffs = makeDiff(textA, textB)
// Map position from textA to textB
console.log('Position 0 maps to:', xIndex(diffs, 0)) // 0 ("T")
console.log('Position 4 maps to:', xIndex(diffs, 4)) // 8 ("c" in "cat")
console.log('Position 7 maps to:', xIndex(diffs, 7)) // 11 ("s" in "sat")
```
```typescript
// Practical example: maintain cursor position during collaborative edit
function updateCursorPosition(
oldText: string,
newText: string,
oldCursorPos: number
): number {
const diffs = makeDiff(oldText, newText)
return xIndex(diffs, oldCursorPos)
}
const oldCursor = 5
const newCursor = updateCursorPosition(textA, textB, oldCursor)
console.log(`Cursor moved from ${oldCursor} to ${newCursor}`)
```
```typescript
// Map selection range
function updateSelectionRange(
oldText: string,
newText: string,
start: number,
end: number
): { start: number; end: number } {
const diffs = makeDiff(oldText, newText)
return {
start: xIndex(diffs, start),
end: xIndex(diffs, end)
}
}
```
--------------------------------
### Apply Patches to Text
Source: https://context7.com/sanity-io/diff-match-patch/llms.txt
The `applyPatches` function merges patches onto text, supporting fuzzy matching for slight text variations. It returns the modified text and a boolean array indicating patch success.
```typescript
import { makePatches, applyPatches, parsePatch } from '@sanity/diff-match-patch'
// Create and apply patches
const original = 'The quick brown fox jumps over the lazy dog.'
const target = 'The slow brown cat leaps over the happy dog.'
const patches = makePatches(original, target)
// Apply to original text (perfect match)
const [newText, results] = applyPatches(patches, original)
console.log('New text:', newText)
console.log('All patches applied:', results.every(r => r)) // true
```
```typescript
// Apply to slightly modified text (fuzzy matching)
const modifiedOriginal = 'The quick brown fox jumps over the sleepy dog.'
const [fuzzyResult, fuzzyResults] = applyPatches(patches, modifiedOriginal)
console.log('Fuzzy result:', fuzzyResult)
console.log('Patch results:', fuzzyResults) // [true, true, ...] or some false
```
```typescript
// Apply with options
const [resultWithOptions] = applyPatches(patches, original, {
margin: 4, // Context size for matching
deleteThreshold: 0.4, // How close content must match (0.0 = perfect, 1.0 = loose)
allowExceedingIndices: false // Handle edge cases with surrogate pairs
})
```
```typescript
// Track partial success
const patches2 = makePatches('Hello World', 'Hello Beautiful World')
const [text, applied] = applyPatches(patches2, 'Hello World')
const successCount = applied.filter(Boolean).length
const failCount = applied.length - successCount
console.log(`Applied ${successCount}/${applied.length} patches (${failCount} failed)`)
```
```typescript
// Full workflow with error handling
function synchronizeDocument(baseText: string, patchString: string): {
text: string
fullyApplied: boolean
appliedCount: number
} {
const patches = parsePatch(patchString)
const [newText, results] = applyPatches(patches, baseText)
return {
text: newText,
fullyApplied: results.every(r => r),
appliedCount: results.filter(Boolean).length
}
}
```
--------------------------------
### Create Diffs
Source: https://github.com/sanity-io/diff-match-patch/blob/main/README.md
Generate an array of diff tuples representing the differences between two strings.
```typescript
import {makeDiff} from '@sanity/diff-match-patch'
// Make an array of diff tuples, eg `[DiffType, string]`
const diff = makeDiff('from this', 'to this')
```
--------------------------------
### Improve Diff Readability with cleanupSemantic
Source: https://context7.com/sanity-io/diff-match-patch/llms.txt
Reduces the number of edits by eliminating semantically trivial equalities and aligning boundaries to words. Use this for human-readable diffs.
```typescript
import { makeDiff, cleanupSemantic } from '@sanity/diff-match-patch'
// Raw diff can produce fragmented results
const rawDiffs = makeDiff('The cat sat on the mat.', 'The dog sat on the rug.')
console.log('Raw diffs:', rawDiffs)
// Clean up for better readability
const cleanDiffs = cleanupSemantic(rawDiffs)
console.log('Semantic diffs:', cleanDiffs)
// Output produces cleaner word-boundary aligned diffs:
// [
// [0, 'The '],
// [-1, 'cat'],
// [1, 'dog'],
// [0, ' sat on the '],
// [-1, 'mat'],
// [1, 'rug'],
// [0, '.']
// ]
```
```typescript
// Combine for common use case
const humanReadableDiff = cleanupSemantic(makeDiff(
'function calculateTotal(items) { return items.reduce((a, b) => a + b, 0); }',
'function computeSum(items) { return items.reduce((sum, item) => sum + item, 0); }'
))
```
--------------------------------
### Fuzzy Text Search with `match`
Source: https://context7.com/sanity-io/diff-match-patch/llms.txt
Use the `match` function for fuzzy text searching. It finds the best pattern instance near a specified location, supporting custom thresholds and search distances. Returns -1 if no match meets the criteria.
```typescript
import { match } from '@sanity/diff-match-patch'
const text = 'The quick brown fox jumps over the lazy dog'
// Exact match near location
const exactPos = match(text, 'fox', 10)
console.log('Found "fox" at:', exactPos) // Output: 16
// Fuzzy match with typo
const fuzzyPos = match(text, 'fax', 10)
console.log('Found fuzzy "fax" at:', fuzzyPos) // Output: 16 (matches "fox")
// Match with custom options
const position = match(
'The quick brown fox jumps over the lazy dog',
'jump',
0,
{
threshold: 0.5, // 0.0 = perfect match required, 1.0 = very loose
distance: 1000 // How far to search from expected location
}
)
console.log('Found "jump" at:', position) // Output: 20
// No match found returns -1
const noMatch = match(text, 'elephant', 0, { threshold: 0.3 })
console.log('No match:', noMatch) // Output: -1
// Search near end of text
const nearEnd = match(text, 'dog', 40)
console.log('Found "dog" at:', nearEnd) // Output: 40
```
--------------------------------
### xIndex - Map Position Between Texts
Source: https://context7.com/sanity-io/diff-match-patch/llms.txt
Computes the equivalent location in textB given a location in textA, using diff results. This is useful for translating cursor positions or selection ranges when text has been modified.
```APIDOC
## xIndex
### Description
Computes the equivalent location in textB given a location in textA, using diff results. This is useful for translating cursor positions or selection ranges when text has been modified.
### Method
`xIndex`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```typescript
import { makeDiff, xIndex } from '@sanity/diff-match-patch'
const textA = 'The cat sat'
const textB = 'The big cat sat'
const diffs = makeDiff(textA, textB)
// Map position from textA to textB
console.log('Position 0 maps to:', xIndex(diffs, 0)) // 0 ("T")
console.log('Position 4 maps to:', xIndex(diffs, 4)) // 8 ("c" in "cat")
console.log('Position 7 maps to:', xIndex(diffs, 7)) // 11 ("s" in "sat")
// Practical example: maintain cursor position during collaborative edit
function updateCursorPosition(
oldText: string,
newText: string,
oldCursorPos: number
): number {
const diffs = makeDiff(oldText, newText)
return xIndex(diffs, oldCursorPos)
}
const oldCursor = 5
const newCursor = updateCursorPosition(textA, textB, oldCursor)
console.log(`Cursor moved from ${oldCursor} to ${newCursor}`)
```
### Response
#### Success Response (200)
- **mappedIndex** (number) - The equivalent index in textB.
#### Response Example
```json
8
```
```
--------------------------------
### Parse Unidiff Patch String
Source: https://context7.com/sanity-io/diff-match-patch/llms.txt
Use `parsePatch` to convert a unidiff-formatted string into an array of patch objects. This is useful for storing and reconstructing patches.
```typescript
import { parsePatch, applyPatches, stringifyPatches, makePatches } from '@sanity/diff-match-patch'
// Parse a unidiff-formatted patch string
const patchText = `@@ -1,11 +1,13 @@
Hello
+World
there`
const patches = parsePatch(patchText)
console.log('Parsed patches:', patches.length)
```
```typescript
// Round-trip: create -> stringify -> parse -> apply
const original = 'The quick brown fox'
const modified = 'The slow brown cat'
const patches1 = makePatches(original, modified)
const patchString = stringifyPatches(patches1)
const patches2 = parsePatch(patchString)
const [result] = applyPatches(patches2, original)
console.log(result) // Output: "The slow brown cat"
```
```typescript
// Parse patches from external source
async function applyRemotePatch(documentId: string, text: string) {
const response = await fetch(`/api/patches/${documentId}`)
const patchText = await response.text()
const patches = parsePatch(patchText)
const [newText, results] = applyPatches(patches, text)
return { newText, success: results.every(r => r) }
}
```
--------------------------------
### Adjust Indices from UTF-8 to UCS-2 with adjustIndiciesToUcs2
Source: https://context7.com/sanity-io/diff-match-patch/llms.txt
Converts patch indices from UTF-8 byte offsets to JavaScript's UCS-2 string indices. Use this when applying patches to text containing characters outside the Basic Multilingual Plane, such as emojis. Configure 'allowExceedingIndices' to control error handling for mismatched indices.
```typescript
import { adjustIndiciesToUcs2, makePatches, parsePatch } from '@sanity/diff-match-patch'
// When applying patches to text with emoji or special characters
const text = 'Hello 👋 World'
const patchString = '@@ -1,12 +1,14 @@\n Hello %F0%9F%91%8B \n+Beautiful \n World'
const patches = parsePatch(patchString)
// Adjust indices for correct UCS-2 positioning
const adjustedPatches = adjustIndiciesToUcs2(patches, text, {
allowExceedingIndices: false // Throw error if indices don't align
})
console.log('Original start:', patches[0].start1)
console.log('Adjusted start:', adjustedPatches[0].start1)
// With allowExceedingIndices for resilient parsing
const resilientPatches = adjustIndiciesToUcs2(patches, text, {
allowExceedingIndices: true // Handle mismatched text gracefully
})
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.