chestozo
chestozo

Reputation: 1301

How to get current list of decorations OR handle decoration position change in VSCode Extension?

Lets take this example into account.
I have a file with contents:

  1: one
  2: two
  3: three

and I create a line decoration for line "two":

const position = new vscode.Position(1, 0);
const range = new vscode.Range(position, position);

const decoration = vscode.window.createTextEditorDecorationType({
  gutterIconPath: context.asAbsolutePath('images/icon.svg')
});

vscode.window.activeTextEditor?.setDecorations(decoration, [range]);

that gives me

  1: one
* 2: two
  3: three

Next step: I am changing file contents by adding a new line before line "two".
After that file looks like this:

  1: one
  2: 
* 3: two
  4: three

As you can see VSCode has updated my line decoration and now it is positioned on line 3 (instead of 2) which is totally correct and I've expected that.

And now the question: how can I get this current updated position of my line decoration? If I hold the range reference - it is still pointing to line 2.

What is the right way to handle this decoration changes?

Either of these 2 options would satisfy me:

  1. a way to query all the current decoration positions displayed for currently open file
  2. a way to subscribe to decoration / range changes so that I can handle those manually.

Maybe I am totally wrong and it should be done in another way.
Please advise!

Upvotes: 3

Views: 1603

Answers (1)

chestozo
chestozo

Reputation: 1301

So apparently there is no way to get all the current decorations for open file in VSCode. Here is an old issue without clear plans to be resolved https://github.com/microsoft/vscode/issues/54147.

I've found an internal method getLineDecorations - https://github.com/microsoft/vscode/blob/master/src/vs/editor/browser/widget/codeEditorWidget.ts#L1118 - and I was trying to reach to it via

vscode.window.activeTextEditor?._proxy
vscode.window.activeTextEditor?._runOnProxy

but I did not succeed.

So for now probably the only option that we have mentioned here https://github.com/microsoft/vscode/issues/54147#issuecomment-439177546 is:

  • to store a copy of all decoration positions
  • to update it manually on each text update via vscode.workspace.onDidChangeTextDocument handler

It is doable but very annoying that we have to do this stuff manually. ¯_(ツ)_/¯
Also very error prone )

Upvotes: 2

Related Questions