@@ -279,21 +279,46 @@ local function indentexpr(linenr, bufnr)
279279 local block_ft = vim .treesitter .get_node_text (block_parameters [1 ], bufnr )
280280
281281 if block_ft and block_ft ~= vim .bo .filetype then
282- local curr_indentexpr = vim .filetype .get_option (block_ft , ' indentexpr' ) --[[ @as string]]
283-
284- if curr_indentexpr and curr_indentexpr ~= ' ' then
285- curr_indentexpr = curr_indentexpr :gsub (' %(%)$' , ' ' )
286-
287- local buf_shiftwidth = vim .bo .shiftwidth
288- vim .bo .shiftwidth = vim .filetype .get_option (block_ft , ' shiftwidth' )
289- local ok , block_ft_indent = pcall (function ()
290- return vim .fn [curr_indentexpr ]()
291- end )
292- if ok then
293- new_indent = math.max (block_ft_indent , vim .fn .indent (match .line_nr ))
282+ local block_header_indent = vim .fn .indent (match .line_nr )
283+ local got_indent = false
284+
285+ -- Try treesitter indent via the injected parser first
286+ local ts_ok , ts_indent_mod = pcall (require , ' nvim-treesitter.indent' )
287+ if ts_ok then
288+ local parser_ok , parser = pcall (vim .treesitter .get_parser , bufnr )
289+ if parser_ok and parser then
290+ local lang = parser :language_for_range ({ linenr - 1 , 0 , linenr - 1 , 0 })
291+ if lang and lang ~= ' org' then
292+ local buf_shiftwidth = vim .bo .shiftwidth
293+ vim .bo .shiftwidth = vim .filetype .get_option (block_ft , ' shiftwidth' ) or buf_shiftwidth
294+ local indent_ok , ts_indent = pcall (ts_indent_mod .get_indent , linenr )
295+ vim .bo .shiftwidth = buf_shiftwidth
296+ if indent_ok and ts_indent and ts_indent >= 0 then
297+ new_indent = math.max (ts_indent , block_header_indent )
298+ got_indent = true
299+ end
300+ end
294301 end
302+ end
303+
304+ -- Fall back to the filetype's indentexpr
305+ if not got_indent then
306+ local curr_indentexpr = vim .filetype .get_option (block_ft , ' indentexpr' ) --[[ @as string]]
307+
308+ if curr_indentexpr and curr_indentexpr ~= ' ' then
309+ curr_indentexpr = curr_indentexpr :gsub (' %(%)$' , ' ' )
295310
296- vim .bo .shiftwidth = buf_shiftwidth
311+ local buf_shiftwidth = vim .bo .shiftwidth
312+ vim .bo .shiftwidth = vim .filetype .get_option (block_ft , ' shiftwidth' )
313+ local ok , block_ft_indent = pcall (function ()
314+ return vim .fn [curr_indentexpr ]()
315+ end )
316+ if ok then
317+ new_indent = math.max (block_ft_indent , block_header_indent )
318+ end
319+
320+ vim .bo .shiftwidth = buf_shiftwidth
321+ end
297322 end
298323 end
299324 end
0 commit comments