I am trying to create a simple extension. This extension displays some text on an active text editor as ghost text only when the editor is empty, i.e., there is no text typed into the editor. But the moment something is typed in the editor, the ghost text must disappear and once again reappear when anything that has been typed is deleted out.
I do not have an extensive knowledge on ways to achieve this, so I used text decoration to achieve this. For this, I wrote the below code inside the activate() function:
const placeholderText='Hi! The extension is working!nn This should be the third linen And this the fourthnAnd this the fifthnBye bye!nnThis text will automatically disappear as you start typing!';
const placeholderDecorationType = vscode.window.createTextEditorDecorationType({
after: { contentText: placeholderText, color: new vscode.ThemeColor('editorCodeLens.foreground') },
});
const updatePlaceholderDecorations = () => {
vscode.window.visibleTextEditors.forEach((editor) => {
const decorations: vscode.DecorationOptions[] = [];
if (editor.document.getText().trim().length === 0) {
decorations.push({ range: new vscode.Range(0, 0, 0, 0) });
}
editor.setDecorations(placeholderDecorationType, decorations);
});
};
const disposable1 = vscode.window.onDidChangeVisibleTextEditors(updatePlaceholderDecorations);
const disposable2 = vscode.workspace.onDidChangeTextDocument((event) => {
if (event.contentChanges.length > 0) {
updatePlaceholderDecorations();
}
});
context.subscriptions.push(disposable1, disposable2);
I am expecting the text to appear over multiple lines but the final output seems to appear only in the first line as shown below:
And this text disappears on typing anything as expected and returns when the typed text is removed as shown below:
The font style and colour and everything is just as I want it to be but I just want the text to appear over multiple lines. I have demonstrated the expected result below by manually typing it but I want this to appear in the way it looks in the previous screenshots attached above:
So, please let me know the following:
- What modification do I need to make in order to get the text decoration over multiple lines instead of a single line?
- Or, is there a better way to achieve this same functionality by a different method. If so, please let me know how.
- Also, I noticed that the decoration text does not appear until I actually kill the integrated terminal that automatically appears? Closing the terminal alone is not enough and I have to kill the terminal for the text to appear. Is there a way to solve this?