Wansmer / treesj

Neovim plugin for splitting/joining blocks of code
MIT License
1.04k stars 29 forks source link

Fallback to `mini.splitjoin` #143

Closed savchenko closed 9 months ago

savchenko commented 9 months ago

It would make sense to fall back onto mini.splitjoin if TreeSitter isn't configured for a buffer or split operation fails.

For example, trying to split a long string in Bash returns:

[TreeSJ]: Node "string_content" for lang "bash" is not configured

...while the same line can be perfectly split by mini.splitjoin.

Wansmer commented 9 months ago

To add fallback for specific nodes, use the fallback option in the node preset (example of usage).

Another way to add fallback to mini.splitjoin is how I personally use it.

Since both solutions depend on a third-party plugin, I will not to add this to the default configuration. API methods will do.

savchenko commented 9 months ago

Here is a code snippet if anyone stumbles upon the same issue in future:

local function get_pos_lang(node)
    local c = vim.api.nvim_win_get_cursor(0)
    local range = { c[1] - 1, c[2], c[1] - 1, c[2] }
    local buf = vim.api.nvim_get_current_buf()
    local ok, parser = pcall(
        vim.treesitter.get_parser,
        buf,
        vim.treesitter.language.get_lang(vim.bo[buf].ft)
    )
    if not ok then
        return ""
    end
    local current_tree = parser:language_for_range(range)
    return current_tree:lang()
end

vim.keymap.set({ 'n', 'v' }, "<leader>m", function()
    local tsj_langs = require("treesj.langs")["presets"]
    local lang = get_pos_lang()
    if lang ~= "" and tsj_langs[lang] then
        require("treesj").toggle()
    else
        require("mini.splitjoin").toggle()
    end
end)