---
title: Text diffs
description: Line and word differences between plain-text sources.
order: 3d
---
[`diff_lines`](diff.md#diff_lines) pairs similar changed lines and identifies the words removed or inserted. Renderers can consume the same structured spans for terminal output or HTML. [`source_diff`](diff.md#source_diff) returns an ordinary unified diff with missing-final-newline markers.

## Structured changes

### diff\_lines

```python
def diff_lines(
    old, # Original source string
    new, # New source string
    context:int=3, # Unchanged lines shown either side of a change; None shows the full source
    final_newline:bool=True, # Distinguish a missing final newline (unnecessary for notebook cells)?
    min_ratio:float=0.5, # Minimum shared-word similarity for refining a changed line pair
):
```

*Line diffs with word-level replacements for similar changed lines.*

Each row is a `(marker, spans)` pair. Row markers are `' '` for unchanged context, `'-'` for a deleted line, `'+'` for an added line, `'!'` for a refined replacement, and `'@'` for a hunk header. Prepending the row marker to its spans reconstructs an ordinary unified-diff line; replacement spans combine old and new text.

Spans use `' '` for unchanged text, `'-'` for removed text, and `'+'` for inserted text. When a paired line gains or loses its final newline, that change is a separate `('+', '\n')` or `('-', '\n')` span. Span strings contain no display markup. Pass `final_newline=False` to ignore missing final newlines in notebook cells.

```python
rows = diff_lines('x=1\ny=2\nz=3\nk=4', 'x = 100\ny=2\nw=5\nq=6', context=None, final_newline=False)
assert [kind for kind, _ in rows] == ['@', '!', ' ', '-', '-', '+', '+']
mixed = diff_lines('apple\nx = 1', 'pear\nx = 2\nextra', final_newline=False)[1:]
assert [kind for kind, _ in mixed] == ['-', '+', '!', '+']
assert diff_lines('hello\n', 'hello')[1:] == [('!', [(' ', 'hello'), ('-', '\n')])]
assert diff_lines('hello', 'hello\n')[1:] == [('!', [(' ', 'hello'), ('+', '\n')])]
assert diff_lines('hello\n', 'hello', final_newline=False) == []
```

A line pair is refined when its shared-word similarity reaches `min_ratio` (default `MIN_RATIO = 0.5`). Unrelated lines and lines exceeding 1000 tokens remain separate deletions and additions. Words, punctuation, and whitespace are tokenized separately, and whitespace never anchors a match. Short coincidental matches inside a larger rewrite are absorbed into the replaced phrase; longer unchanged text separates independent edits.

```python
before = 'selects the fields, shown by the vectors'
after = 'reverses the coordinates, arranged in two columns'
suffix = '. Dragging either point redraws both points.'
phrase = diff_lines('The model '+before+suffix, 'The model '+after+suffix, final_newline=False)[1]
assert phrase == ('!', [(' ', 'The model '), ('-', before), ('+', after), (' ', suffix)])

shared = ' while both points retain their positions '
separate = diff_lines('We select fields'+shared+'using the old formula.',
    'We reverse coordinates'+shared+'using the new expression.', final_newline=False)[1]
assert separate == ('!', [(' ', 'We '), ('-', 'select fields'), ('+', 'reverse coordinates'),
    (' ', shared+'using the '), ('-', 'old formula'), ('+', 'new expression'), (' ', '.')])
```

## Unified text

### source\_diff

```python
def source_diff(
    old_source, # Original source string
    new_source, # New source string
    context:int=3, # Unchanged lines shown either side of a change
    final_newline:bool=True, # Distinguish a missing final newline (unnecessary for notebook cells)?
):
```

*Unified source diff, including missing-final-newline markers.*

Returns an ordinary unified diff rather than inline word spans. Marks a missing final newline with `\ No newline at end of file`; pass `final_newline=False` to ignore that distinction for notebook cells.

```python
patch = source_diff('hello\n', 'hello')
assert r'\ No newline at end of file' in patch
assert source_diff('hello\n', 'hello', final_newline=False) == ''
```
