numToStr / FTerm.nvim

:fire: No-nonsense floating terminal plugin for neovim :fire:
MIT License
721 stars 24 forks source link

feat: allow `on_open` to be configured #68

Closed matthewswitzer closed 1 year ago

matthewswitzer commented 1 year ago

Hello! Wanting to see if it’s possible to merge in these changes to add the ability for users to define an on_open callback that will be executed when a terminal is first opened.

Example use case:

When using lazygit, normally you can press q to quit or <Esc> to “go back” after doing something like staging individual lines in a separate window. I only want these keymaps to apply to the specific buffer/terminal that was created for lazygit though (since I have <Esc> mapped to <C-\\><C-n> normally). Having this on_open callback will allow me to define these once the terminal and buffer/window are created and only apply it to that buffer since I will have access to the terminal instance as the first parameter and can get the buf number for it.

Here’s an example configuration of the above scenario:


local Term = require 'FTerm'
local lazygit = Term:new {
    cmd = ‘lazygit’,
    border = 'rounded',
    dimensions = {
        height = 0.9,
        width = 0.9,
    },
    on_open = function(term)
        vim.api.nvim_buf_set_keymap(
            term.buf,
            'n',
            'q',
            '<Cmd>close<CR>',
            { noremap = true, silent = true }
        )
        vim.api.nvim_buf_set_keymap(
            term.buf,
            't',
            '<Esc>',
            '<Esc>',
            { noremap = true, silent = true }
        )
    end,
}
numToStr commented 1 year ago

Why not use TermOpen autocmd?

matthewswitzer commented 1 year ago

Forgive me if I’m wrong, but I only want these certain keymaps to apply to the “lazygit” terminal that was created. I’m not sure how I would would limit it using TermOpen to only define it on that one terminal instance.

numToStr commented 1 year ago

This should work. The main thing is to set (or use default) config.ft value and check for that in TermOpen autocmd.


local ft = 'fterm.lazygit'
local lazygit = require('FTerm'):new({
    ft = ft, -- default is `FTerm` for all the terminals
    cmd = 'lazygit',
    border = 'rounded',
    dimensions = {
        height = 0.9,
        width = 0.9,
    },
})

vim.api.nvim_create_autocmd('TermOpen', {
    group = vim.api.nvim_create_augroup('FTERM', { clear = true }),
    callback = function(data)
        local buf = data.buf
        if vim.bo[buf].filetype == ft then
            vim.keymap.set('n', 'q', '<Cmd>close<CR>', { buffer = buf })
            vim.keymap.set('t', '<Esc>', '<Esc>', { buffer = buf })
        end
    end,
})
matthewswitzer commented 1 year ago

Got it, thanks! I’ll try to work with that instead.