diff options
| author | xvzc <me@xvzc.dev> | 2025-10-24 09:34:12 +0900 |
|---|---|---|
| committer | github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> | 2025-10-24 01:14:30 +0000 |
| commit | 0e1c83fae2dfe8565fc4b23e2352ad3a1c66bd7a (patch) | |
| tree | 232eb7c8439d4e5f8b2bff8914cd44a9670d5363 /runtime | |
| parent | 169dc60a448ce33499f5c634f236164fc3e33d5b (diff) | |
fix(filetype): handle invalid `bufnr` in _getlines(), _getline() #36272
**Problem:**
`vim.filetype.match({ filename = 'a.sh' })` returns `nil` because
an invalid buffer ID is passed to `vim.api.nvim_buf_get_lines()`.
For filetypes like `csh`, `txt`, or any other extensions that call
`_getlines()` or `_getline()` to detect their filetypes, the same
issue occurs.
When only the `filename` argument is passed, an error is raised
inside a `pcall()` that wraps the filetype detection function,
causing it to return no value without showing any error message.
**Solution:**
Validate the `bufnr` value in `_getlines()` and `_getline()`.
(cherry picked from commit 095b9f98f3e37b53520c766a12cb413dd0589028)
Diffstat (limited to 'runtime')
| -rw-r--r-- | runtime/lua/vim/filetype.lua | 8 |
1 files changed, 8 insertions, 0 deletions
diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua index 5ca0c38c2a..3734d31205 100644 --- a/runtime/lua/vim/filetype.lua +++ b/runtime/lua/vim/filetype.lua @@ -47,6 +47,10 @@ end ---@param end_lnum integer|nil The line number of the last line (inclusive, 1-based) ---@return string[] # Array of lines function M._getlines(bufnr, start_lnum, end_lnum) + if not bufnr or bufnr < 0 then + return {} + end + if start_lnum then return api.nvim_buf_get_lines(bufnr, start_lnum - 1, end_lnum or start_lnum, false) end @@ -61,6 +65,10 @@ end ---@param start_lnum integer The line number of the first line (inclusive, 1-based) ---@return string function M._getline(bufnr, start_lnum) + if not bufnr or bufnr < 0 then + return '' + end + -- Return a single line return api.nvim_buf_get_lines(bufnr, start_lnum - 1, start_lnum, false)[1] or '' end |
