Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

visual studio code - VSCode Extension API - event for "text document became dirty/unsaved"

I am creating a small VSCode Extension. I found a event that emits when the document is changed:

    vscode.workspace.onDidChangeTextDocument(function(e) {
        console.log('changed.');
        console.log(e.document.isDirty);
    });

However I only want to fire my code if this change turns the document dirty/unsaved. The onDidChangeTextDocument event fire for every change. There doesn't appear to be a onWillChangeTextDocument event.

Is there a way to ONLY detect the "first" change that changes the document's state from isDirty: false to isDirty: true?

question from:https://stackoverflow.com/questions/65934171/vscode-extension-api-event-for-text-document-became-dirty-unsaved

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I made the functionality myself by keeping an array of files changed:

var isDirty = [];

function activate(context) {
    console.log('activated.');
    
    vscode.workspace.onDidChangeTextDocument(function(e) {
        console.log('Changed.');
        
        if (!isDirty.includes(e.document.uri.path)) {
            console.log('This is the change that made this file "dirty".');
            
            isDirty.push(e.document.uri.path);
            
            // Place code that you only want to run on the first change (that makes a document dirty) here...
        }
    });
    
    vscode.workspace.onDidSaveTextDocument(function(e) {
        console.log('Saved!');
        
        const index = isDirty.indexOf(e.uri.path);
        
        if (index > -1) {
            isDirty.splice(index, 1);
        }
    });
    
}
exports.activate = activate;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...