Limit number of open tabs

Is it possible to restrict the number of open tabs in a DOpus pane? Set,say, to a maximum of 3 with a fourth then reusing one of the existing ones?

A script add-in can close the surplus tabs after opening a new one.

function OnInit(initData) {
    initData.name = 'LimitTabCount';
    initData.version = '2022-07-16';
    initData.url = 'https://resource.dopus.com/t/numbers-of-open-tabs/41730';
    initData.desc = 'Limit number of open tabs';
    initData.default_enable = true;
    initData.min_version = '12.0';
}

function OnOpenTab(openTabData) {
    var tab = openTabData.tab;
    var tabs = tab.right ? tab.lister.tabsright : tab.lister.tabsleft;

    if (tabs.count < 4) return;

    var cmd = DOpus.Create().Command();
    cmd.SetSourceTab(tab);
    cmd.Clear();
    
    for (var i = tabs.count; i > 3; --i) {
        cmd.AddLine('Go TABCLOSE TABPOS=0');
    }

    cmd.Run();
}

EventLimitTabCount.js.txt


Some of the Tab Locking modes may also help. See near the bottom of https://www.gpsoft.com.au/help/opus12/index.html#!Documents/Tabs.htm

Script does the job beautifully! Thanks

Thanks for the script--very helpful. There is a problem with it, however: it always closes the first tab opened instead of the newly opened tab.

Fixed by replacing the line:

cmd.AddLine('Go TABCLOSE TABPOS=0');

with

cmd.AddLine('Go TABCLOSE TABPOS=${i}');

EDIT: I see now that that was the effect the OP desired, so the script actually works as intended. I wanted it to limit it to 3 tabs and force me to use one of the already opened ones; my edit above will give the script that effect.