Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persist information for a vscode extension?

I'm planning to write a Visual Studio Code extension and it need to save some information for example a counter. The user can press a shortcut to increase or decrease the counter and the value of the counter will be saved some where. Next time when the user starts Visual Studio Code, the extension can load the counter's last value. My question is, where is the proper place to store this info?

like image 394
Just a learner Avatar asked Aug 13 '18 12:08

Just a learner


2 Answers

When you have a global state that you want to see across all your VSCODE windows, you can use the globalState from the extension's context.

I used this code in my extension to store a string:


async function activate (context) {
  const state = stateManager(context)
  
  const {
    lastPaletteTitleApplied
  } = state.read()

  await state.write({
    lastPaletteTitleApplied: 'foo bar'
  })

}


function stateManager (context) {
  return {
    read,
    write
  }

  function read () {
    return {
      lastPaletteTitleApplied: context.globalState.get('lastPaletteApplied')
    }
  }

  async function write (newState) {
    await context.globalState.update('lastPaletteApplied', newState.lastPaletteTitleApplied)
  }
}

like image 57
Manuel Spigolon Avatar answered Oct 23 '22 14:10

Manuel Spigolon


You're probably looking for the Memento API. The ExtensionContext has two different memento instances you can access:

  • workspaceState

    A memento object that stores state in the context of the currently opened workspace.

  • globalState

    A memento object that stores state independent of the current opened workspace.

Both survive VSCode updates to my knowledge.

like image 33
Gama11 Avatar answered Oct 23 '22 14:10

Gama11