zyedidia / micro

A modern and intuitive terminal-based text editor
https://micro-editor.github.io
MIT License
25.24k stars 1.18k forks source link

File opened in multiple tabs #3507

Open RichardFevrier opened 1 month ago

RichardFevrier commented 1 month ago

Hi everyone 👋

Probably a skill issue but I can't find a way to prevent a file to be opened multiple times in different tabs and switch to the tab instead.

Thank you.

dmaluka commented 1 month ago

You can implement a custom command in lua for that. Add e.g. something like this to your init.lua:

local micro = import("micro")
local config = import("micro/config")
local filepath = import("filepath")

function switchCmd(bp, args)
    if #args < 1 then
        return
    end
    local abspath = filepath.Abs(args[1])
    local tabs = micro.Tabs()
    if tabs ~= nil then
        for i, t in tabs.List() do
            for j, p in t.Panes() do
                if p.Buf.Path ~= "" and p.Buf.AbsPath == abspath then
                    tabs:SetActive(i-1)
                    t:SetActive(j-1)
                    return
                end
            end
        end
    end
    bp:NewTabCmd(args)
end

function init()
    config.MakeCommand("switch", switchCmd, config.FileComplete)
end
RichardFevrier commented 1 month ago

Thanks for your smart answer 🙏

Unfortunately doing so you don't change the behavior of NewTabCmd (applies probably to OpenCmd too) meanings that any other call, from plugins for ex. will not beneficiate this functionality.

And that's specifically my case now, I've done a plugin last week that you can find here (pull requeted in the plugin-channel (let me dream 😅)) to integrate Yazi with Micro.

Andriamanitra commented 1 month ago

@RichardFevrier maybe you could use preOpenFile Lua callback?

RichardFevrier commented 1 month ago

Can't make it work with NewTabCmd from a plugin. With binded action no problem otherwise. Can you @Andriamanitra ?

Andriamanitra commented 1 month ago

I think BufPane.NewTabCmd method does not trigger OpenFile action because it creates a buffer directly (a bug?) but there is also AddTab action that you could hook into. Or you could add a check in your plugin before calling bp:NewTabCmd.

RichardFevrier commented 4 weeks ago

Sorry I didn't mention yesterday that I tried AddTab, OpenTab and so on.. without success.

IMO the last option is a big no, because the idea is to not ask every plugins developer to implement such check, it as to be backed into micro.

But your initial idea of using a callback was cleaver, it just doesn't work in this case (maybe I did implement it wrong, totally possible).