From a4d9ca356ce1f662620a62b8e16c43f33a5cd29f Mon Sep 17 00:00:00 2001 From: Steven Arcangeli Date: Tue, 22 Oct 2024 14:19:45 -0700 Subject: [PATCH] fix: crash in error handling for function formatters (#554) --- lua/conform/formatters/injected.lua | 5 +++++ lua/conform/runner.lua | 17 ++++++++++++----- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/lua/conform/formatters/injected.lua b/lua/conform/formatters/injected.lua index 427e8cc505d..c186a1e67b1 100644 --- a/lua/conform/formatters/injected.lua +++ b/lua/conform/formatters/injected.lua @@ -137,6 +137,11 @@ return { -- (defaults to the value from formatters_by_ft) lang_to_formatters = {}, }, + condition = function(self, ctx) + local buf_lang = vim.treesitter.language.get_lang(vim.bo[ctx.buf].filetype) + local ok = pcall(vim.treesitter.get_string_parser, "", buf_lang) + return ok + end, format = function(self, ctx, lines, callback) local conform = require("conform") local errors = require("conform.errors") diff --git a/lua/conform/runner.lua b/lua/conform/runner.lua index 029d6ee201f..d69d25a2258 100644 --- a/lua/conform/runner.lua +++ b/lua/conform/runner.lua @@ -309,13 +309,20 @@ local function run_formatter(bufnr, formatter, config, ctx, input_lines, opts, c end end) if config.format then + local err_string_cb = function(err, ...) + if err then + callback({ + code = errors.ERROR_CODE.RUNTIME, + message = err, + }, ...) + else + callback(nil, ...) + end + end ---@cast config conform.LuaFormatterConfig - local ok, err = pcall(config.format, config, ctx, input_lines, callback) + local ok, err = pcall(config.format, config, ctx, input_lines, err_string_cb) if not ok then - callback({ - code = errors.ERROR_CODE.RUNTIME, - message = string.format("Formatter '%s' error: %s", formatter.name, err), - }) + err_string_cb(string.format("Formatter '%s' error: %s", formatter.name, err)) end return end