Search code examples
visual-studio-codevscode-extensions

How do I get all the tabs in a Visual Studio Code window as an array of filenames?


I am currently looking to find the call that will allow me to see all the tabs in a Visual Studio Code editor (1.txt, 2.txt, 3.txt) being returned back in an array for example.


Solution

  • const tabArray = vscode.window.tabGroups.all;
    

    will return an array of editor groups. And then within each editor group (or "tabGroup") you can get an array of its tabs with:

    const firstGroupOfTabs = tabArray[0].tabs;
    
    const firstTabName = firstGroupOfTabs[0].label;
    
    or 
    
    const firstTabUri = firstGroupOfTabs[0].input.uri;  // gives you a uri if you need the full path - for most, but not all, editor types
    

    So you will have to do a loop through the tabGroups.all to get all the fileNames. One example of doing so:

    const tabArray = tabGroupArray.flatMap(group => group.tabs.map(tab => tab.label));
    

    To make this more typescript-friendly, try this:

      const tabArray: ReadonlyArray<vscode.TabGroup> = vscode.window.tabGroups.all;
      const firstGroupOfTabs: ReadonlyArray<vscode.Tab> = tabArray[0].tabs;
      
      let firstTabUri: vscode.Uri;  
      if (firstGroupOfTabs[0].input instanceof vscode.TabInputText) firstTabUri = firstGroupOfTabs[0].input.uri;
    

    Here I narrowed the input to vscode.TabInputText because some of the Tab.input's for editors don't even have a uri member. If you are interested in other Tab.input's you can narrow for those or possibly make a union type to simplify it.