Sub topic 10
Where the next edit goes and how it is shown as a diff
This chapter assumes you know what a next edit suggestion (NES) is and why recent edits are used as context. It also assumes you can read a unified diff and write basic Python. It covers two questions. How does the system decide which place in the file to change? How does it present that change so you can judge it in a second?
Two predictions, not one
An inline completion answers one question: what text goes at the cursor? A next edit suggestion must answer two questions in order:
- Where will the next change happen? This is the location.
- What will replace the text there? This is the content.
The location can be the cursor line, a line a few lines away, or a line in another part of the file. It can also be a pure insertion or a deletion. Because of this, the output is an edit: a range in the current document plus the text that replaces it. An insertion is an edit with an empty range. A deletion is an edit with empty replacement text.
How a model picks a location
Models usually receive these inputs:
- The current file, or a window of it around the cursor.
- The cursor position.
- A short list of recent edits, each stored as a before and after pair.
- Sometimes diagnostics, such as compiler errors or lint warnings.
The model infers a pattern from the edit history. If you renamed w to width in a function signature, the unchanged lines that still use w are candidates. If you added a field to a class, the constructor and serializer are candidates. The model has no rule engine. It predicts a change that is consistent with the pattern in the history.
There are two common ways to express the answer.
- Window rewrite. The prompt marks an editable region, for example 10 to 30 lines around the cursor. The model returns a rewritten version of that whole region. The location is implicit. You find it by comparing the old and new regions.
- Explicit location. The model first outputs a line number or a range, then the replacement. Some systems use two stages, with a cheap model proposing locations and a stronger one writing content.
Window rewrite is simple and keeps the model grounded in real text. Its cost is that the model must copy every unchanged line. This adds latency and gives it chances to change something by accident. Explicit locations are cheaper to generate. Their cost is that a wrong line number produces a suggestion that applies in the wrong place.
Turning model output into a diff
If the model returns a rewritten region, the editor has to find what changed. A line-level diff is the standard approach. It works on lists of lines, and the algorithm finds the longest matching blocks and reports everything else as insert, delete or replace operations.
The Python standard library does this with difflib.SequenceMatcher. The function below turns an old and a new text into a list of hunks. Each hunk carries the start line, the old lines and the new lines.
import difflib
def edit_hunks(old: str, new: str) -> list[dict]:
old_lines = old.splitlines()
new_lines = new.splitlines()
matcher = difflib.SequenceMatcher(a=old_lines, b=new_lines, autojunk=False)
hunks = []
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
if tag == "equal":
continue
hunks.append(
{
"kind": tag, # "replace", "delete" or "insert"
"start_line": i1 + 1, # 1-based line in the old text
"old": old_lines[i1:i2],
"new": new_lines[j1:j2],
}
)
return hunks
old = "def area(w, h):\n return w * h\n\ndef describe():\n return area(w=2, h=3)\n"
new = "def area(width, height):\n return width * height\n\ndef describe():\n return area(width=2, height=3)\n"
for hunk in edit_hunks(old, new):
print(hunk)Running it prints two replace hunks: one starting at line 1 that covers the signature and the return line, and one starting at line 5 that covers the call site. The first hunk is where you typed. The second is the suggestion. The editor can show the first as already done and offer only the second.
autojunk=False matters. By default SequenceMatcher treats very frequent items as junk when a sequence has 200 or more items. In source code, blank lines and lone braces are frequent, so the default can produce odd matches on larger windows.
The diff for this example looks like this:
--- a/geometry.py
+++ b/geometry.py
@@ -1,6 +1,6 @@
-def area(w, h):
- return w * h
+def area(width, height):
+ return width * height
def describe():
- return area(w=2, h=3)
+ return area(width=2, height=3)Granularity: lines, words and characters
A line diff says that the whole line changed. That is too coarse for a one-word change. Editors therefore refine each replaced line with a second, finer diff at word or character level. They highlight only w to width instead of the full line. This is the difference between a suggestion you accept at a glance and one you have to read.
Presentation also depends on the shape of the edit.
| Edit shape | Typical display |
|---|---|
| Insertion at the cursor | Ghost text, as in an inline completion |
| Small change on a nearby line | Inline highlight of removed and added words |
| Change on a distant line | Gutter arrow that moves the cursor there first, then a diff preview |
| Multi-line replacement | Side-by-side or stacked removed and added lines |
| Pure deletion | Struck-through or highlighted text |
Many editors use a two-step interaction for distant edits. The first Tab jumps the cursor to the target. The second Tab applies the change. This keeps you from accepting an edit you cannot see.
Keeping the suggestion valid
A suggestion is computed from a snapshot. You keep typing while the request is in flight, so the buffer can differ from the snapshot when the response arrives. Applying the edit blindly can corrupt text. A defensive editor checks the range before showing or applying the suggestion.
def still_applies(current_lines: list[str], start: int, expected_old: list[str]) -> bool:
"""start is a 0-based line index. True if the buffer still holds the text the edit replaces."""
return current_lines[start : start + len(expected_old)] == expected_old
buffer = ["def area(width, height):", " return width * height", "", "def describe():", " return area(w=2, h=3)"]
print(still_applies(buffer, 4, [" return area(w=2, h=3)"])) # True
buffer[4] = " return area(w=5, h=3)"
print(still_applies(buffer, 4, [" return area(w=2, h=3)"])) # FalseTypical rules, in order:
- Discard the suggestion if the text in its range has changed since the snapshot.
- Discard it if applying it would produce text identical to the buffer. A no-op suggestion is noise.
- Discard it if you have already made that edit yourself.
- Shift line numbers when edits above the range add or remove lines, or recompute the suggestion.
Edge cases
- Overlapping hunks. Two suggested changes can touch adjacent lines. Merge them into one hunk, or the preview will look like two separate edits that really need to be accepted together.
- Whitespace-only changes. A diff made only of indentation or trailing space is usually not worth interrupting you. Many systems filter these out unless they fix a syntax problem, as in Python.
- Large rewrites. If the diff touches most of the window, the model probably lost the pattern. A common filter is a cap on the fraction of changed lines.
- Reverts. If the model proposes undoing your last edit, drop it. This often happens when the history is misread as a pattern.
- Location far away. Jumping to another file or a distant line costs attention. Systems often require higher confidence before moving the cursor than before showing a nearby edit.
- Multiple candidates. When several locations look plausible, show the one closest to the cursor first. After you accept, the next suggestion can chain from that new edit.
What to check when you review a diff
Read the removed lines first. They tell you whether the system found the place you meant. Then read the added lines. Check that every unchanged line in the hunk is really unchanged. In window-rewrite systems, a quiet change in a line the diff shows as equal is impossible, but a change the diff shows as a replacement can hide a subtle edit, such as a flipped comparison next to the renamed variable.
Exercise
A model returns a rewritten 20-line window. The editor shows a diff with one hunk at line 14, but you were editing line 3. Name two reasons this can be a correct suggestion and one check the editor should run before showing it.
Show answer
Correct reasons: the edit you made on line 3 (for example a rename or a new parameter) needs a matching change at line 14, and the model inferred this from your recent edit history. Line 3 itself may already be complete, so the diff has no hunk there. The editor should compare the expected old text of the hunk with the live buffer at line 14. If the text has changed since the snapshot, or if the replacement equals the existing text, it should discard the suggestion.
Exercise
Why does the code in this chapter pass autojunk=False to SequenceMatcher, and what could go wrong without it?
Show answer
With the default autojunk=True, items that appear very often in a sequence of 200 or more items are treated as junk and ignored when finding matching blocks. Source code has many repeated lines such as blank lines and closing braces. Ignoring them can make the matcher miss real matches and report larger or misplaced hunks, so the diff shown to the user would be wrong or noisy.