zed-industries/zed · error

could not locate hunk context in text

Error message

could not locate hunk context in text

What it means

Raised while applying a unified diff patch when the hunk's context lines cannot be located in the target text (searched forward from the previous hunk's position). The context the patch expects does not match the actual buffer content, so the hunk cannot be applied and the patch application fails.

Source

Thrown at crates/zeta_prompt/src/zeta_prompt.rs:4462

        // edits expressed as byte ranges within that context plus replacement
        // text.
        let hunks = parse_hunks(patch);
        if hunks.is_empty() {
            return Ok(String::new());
        }

        // Apply each hunk by finding its old_context in the text and
        // performing the edits. We search forward from where the previous
        // hunk ended so that hunks are applied in order.
        let mut new_text = old_text.to_string();
        let mut search_from: usize = 0;
        let mut first_hunk_pos: Option<usize> = None;

        for hunk in &hunks {
            let context_pos = new_text[search_from..]
                .find(&hunk.old_context)
                .map(|pos| pos + search_from)
                .ok_or_else(|| anyhow::anyhow!("could not locate hunk context in text"))?;

            if first_hunk_pos.is_none() {
                first_hunk_pos = Some(context_pos);
            }

            // Apply edits in reverse order so byte offsets remain valid.
            for edit in hunk.edits.iter().rev() {
                let abs_start = context_pos + edit.range.start;
                let abs_end = context_pos + edit.range.end;
                new_text.replace_range(abs_start..abs_end, &edit.text);
            }

            // Advance past this hunk's region in the (now modified) text.
            let new_region_len: usize =
                hunk.edits.iter().fold(hunk.old_context.len(), |len, edit| {
                    len + edit.text.len() - (edit.range.end - edit.range.start)
                });
            search_from = context_pos + new_region_len;

View on GitHub (pinned to f4178619ac)

Solutions

  1. Regenerate the patch against the current text and retry
  2. Search the whole text instead of only forward from the last hunk when strict ordering fails
  3. Skip the unresolvable hunk and report which edit could not be applied
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at crates/zeta_prompt/src/zeta_prompt.rs:4462 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of zed-industries/zed@f4178619ac (2026-08-20). Data as JSON: /api/errors/327a993e9879dcf3. Report an issue: GitHub.