---
title: "Diffing"
description: "Compare the segments of a file before and after a change, and compare sentences within a segment."
canonical_url: "https://diglot.sh/core/diffing"
---
# Diffing

> Compare the segments of a file before and after a change, and compare sentences within a segment.

## Segment diff

`diffSegments(before, after, options?)` compares the segments of one file, given as lists in document order.

```ts
import { diffSegments, sentenceDiff } from '@diglot/core'

const { unchanged, added, removed, modified } = diffSegments(before, after)
for (const { before, after, similarity, ambiguous } of modified)
  console.log(sentenceDiff(before.skeleton, after.skeleton).changed)
```

Equal hashes count as unchanged, compared as a multiset. The remaining removed and added segments are paired by skeleton similarity, and pairs below the threshold stay added and removed. The rules are described in [keeping in sync](https://diglot.sh/guide/concepts/keeping-in-sync).

<table>
<thead>
  <tr>
    <th>
      Option
    </th>
    
    <th>
      Default
    </th>
    
    <th>
      Description
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        threshold
      </code>
    </td>
    
    <td>
      <code>
        0.5
      </code>
    </td>
    
    <td>
      The minimum similarity for a removed and an added segment to count as one modified segment
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        margin
      </code>
    </td>
    
    <td>
      <code>
        0.1
      </code>
    </td>
    
    <td>
      The score margin within which a rival pairing makes a match ambiguous
    </td>
  </tr>
</tbody>
</table>

Each entry of `modified` has `before` (the predecessor), `after`, `similarity` (0 to 1) and `ambiguous`. The functions accept any objects with a `hash`, `kind`, `format` and `skeleton`, so manifest entries work as well as full segments.

`similarity(a, b)` is the normalised Levenshtein similarity of two strings, from 0 to 1.

## Sentence diff

`splitSentences(text, locale = 'en')` splits text into trimmed sentences with `Intl.Segmenter`. `sentenceDiff(before, after, locale?)` finds the longest common subsequence of sentences and returns `before`, `after`, `changed` (indexes into `after` of sentences that aren't in `before`) and `dropped` (indexes into `before` of sentences that aren't in `after`).

[`updateTranslation`](https://diglot.sh/machine-translation/update-translation) uses it to tell which sentences of an updated translation are new, and `diglot diff` prints how many sentences of a modified segment changed.


## Sitemap

See the full [sitemap](https://diglot.sh/sitemap.md) for all pages.
