From 8f641157c617a5372c473b1cc6d879a3546a22a4 Mon Sep 17 00:00:00 2001 From: Stefan VanBuren Date: Mon, 31 Aug 2026 09:17:36 -0400 Subject: [PATCH] fix(injected): clamp injected regions that run to the end of the file Treesitter reports a region that extends to EOF as ending at (line count, col 0), which is one row past the last line. That end row is used directly as a buffer index, so merge_ranges_with_prefix hits nvim_buf_get_lines' strict indexing and the whole format call fails with "Index out of bounds", leaving the buffer unformatted. Fenced languages hide this: a closing ``` ends the region before EOF. Delimiter-less blocks do not, so a YAML block scalar as the last thing in the file reproduces it every time, as does an unclosed markdown fence. Clamp the end of such a region to the end of the final line. Fixes #452 --- lua/conform/formatters/injected.lua | 7 +++++++ tests/injected/eof.md | 5 +++++ tests/injected/eof.md.formatted | 5 +++++ 3 files changed, 17 insertions(+) create mode 100644 tests/injected/eof.md create mode 100644 tests/injected/eof.md.formatted diff --git a/lua/conform/formatters/injected.lua b/lua/conform/formatters/injected.lua index 6f0cecb4..7a1b3999 100644 --- a/lua/conform/formatters/injected.lua +++ b/lua/conform/formatters/injected.lua @@ -256,6 +256,13 @@ return { -- The types are wrong. included_regions should be Range[][] not integer[][] ---@diagnostic disable-next-line: param-type-mismatch local start_row, start_col, _, end_row, end_col, _ = unpack(region) + -- Treesitter reports a region that runs to the end of the file as ending at + -- (line count, col 0), one row past the last line. Left alone that overruns + -- every buffer index below. Clamp it to the end of the final line. + if end_row >= #lines then + end_row = #lines - 1 + end_col = #(lines[#lines] or "") + end accum_range(regions, { lang, start_row + 1, start_col, end_row + 1, end_col }) end end diff --git a/tests/injected/eof.md b/tests/injected/eof.md new file mode 100644 index 00000000..1e2f8693 --- /dev/null +++ b/tests/injected/eof.md @@ -0,0 +1,5 @@ +text + +```lua +local foo = "bar" +local bar = 2 diff --git a/tests/injected/eof.md.formatted b/tests/injected/eof.md.formatted new file mode 100644 index 00000000..ad75c1bf --- /dev/null +++ b/tests/injected/eof.md.formatted @@ -0,0 +1,5 @@ +text + +```lua +>local foo = "bar" +local bar = 2<