Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Open documents, read their content, and subscribe to lifecycle events (open, save, close, rename).
Note
This guide uses the VisualStudio.Extensibility SDK. See Choose the right extensibility model for model comparison.
Related sample
The samples repo doesn't currently include a standalone IDocumentEventsListener sample. The closest related sample listens for text view open, change, and close events on matching documents:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DocumentSelectorSample;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Extensibility;
using Microsoft.VisualStudio.Extensibility.Documents;
using Microsoft.VisualStudio.Extensibility.Editor;
/// <summary>
/// A sample demonstrating how to define an editor extension that is only applicable to files matching a file path pattern.
/// This text view event listener monitors users opening/modifying/closing C# files in "tests" folder and emulates running
/// unit tests in these files.
/// </summary>
[VisualStudioContribution]
internal class UnitTestRunner : ExtensionPart, ITextViewOpenClosedListener, ITextViewChangedListener
{
private readonly TextViewChangesAggregator textViewChangesAggregator;
private OutputChannel? outputChannel;
/// <summary>
/// Initializes a new instance of the <see cref="UnitTestRunner"/> class.
/// </summary>
/// <param name="extension">Extension instance.</param>
/// <param name="extensibility">Extensibility object.</param>
public UnitTestRunner(Extension extension, VisualStudioExtensibility extensibility)
: base(extension, extensibility)
{
this.textViewChangesAggregator = new((beforeTextView, afterTextView, cancellationToken) => this.RunUnitTestsAfterDelayAsync(afterTextView, cancellationToken));
}
/// <inheritdoc />
public TextViewExtensionConfiguration TextViewExtensionConfiguration => new()
{
AppliesTo = [DocumentFilter.FromGlobPattern("**/tests/*.cs", relativePath: false)],
};
/// <inheritdoc />
public Task TextViewChangedAsync(TextViewChangedArgs args, CancellationToken cancellationToken)
{
return this.textViewChangesAggregator.TextViewChangedAsync(args, cancellationToken);
}
/// <inheritdoc />
public Task TextViewOpenedAsync(ITextViewSnapshot textView, CancellationToken cancellationToken)
{
return this.RunUnitTestsAfterDelayAsync(textView, cancellationToken);
}
/// <inheritdoc />
public Task TextViewClosedAsync(ITextViewSnapshot textView, CancellationToken cancellationToken)
{
return this.StopUnitTestsAsync(textView, cancellationToken);
}
/// <inheritdoc />
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (isDisposing)
{
this.outputChannel?.Dispose();
this.textViewChangesAggregator.Dispose();
}
}
private async Task RunUnitTestsAfterDelayAsync(ITextViewSnapshot textViewSnapshot, CancellationToken cancellationToken)
{
await Task.Delay(500, cancellationToken);
await this.WriteToOutputWindowAsync($"Running unit tests in {textViewSnapshot.Document.Uri.LocalPath}", cancellationToken);
}
private async Task StopUnitTestsAsync(ITextViewSnapshot textViewSnapshot, CancellationToken cancellationToken)
{
await this.WriteToOutputWindowAsync($"Stop running unit tests in {textViewSnapshot.Document.Uri.LocalPath}", cancellationToken);
}
private async Task WriteToOutputWindowAsync(string message, CancellationToken cancellationToken)
{
this.outputChannel ??= await this.Extensibility.Views().Output.CreateOutputChannelAsync(
Resources.OutputWindowPaneName,
cancellationToken);
await this.outputChannel.WriteLineAsync(message);
}
}
Tip
See the related sample: DocumentSelectorSample ↗ — it demonstrates document filtering and text view lifecycle events rather than document open/save/rename events.
Related concepts: Editor concepts — document types and text view lifecycle
Understand the example
Open a document
DocumentsExtensibility documents = this.Extensibility.Documents();
Uri uri = new Uri(@"C:\path\to\Class1.cs", UriKind.Absolute);
DocumentSnapshot document = await documents.OpenDocumentAsync(uri, cancellationToken);
Read document text
ITextDocumentSnapshot snapshot = await document.AsTextDocumentAsync(
this.Extensibility, cancellationToken);
string allText = snapshot.Text.CopyToString();
Get the active document
var textView = await context.GetActiveTextViewAsync(cancellationToken);
if (textView is not null)
{
var document = textView.Document;
// Work with document.Uri, document.Text.CopyToString(), etc.
}
Subscribe to document events
Implement IDocumentEventsListener and subscribe with Documents().SubscribeAsync():
public class MyDocumentListener : IDocumentEventsListener
{
public Task OpenedAsync(DocumentEventArgs e, CancellationToken ct)
{
// React to document open
return Task.CompletedTask;
}
public Task SavedAsync(DocumentEventArgs e, CancellationToken ct)
{
// React to document save
return Task.CompletedTask;
}
public Task ClosedAsync(DocumentEventArgs e, CancellationToken ct) => Task.CompletedTask;
public Task RenamedAsync(RenamedDocumentEventArgs e, CancellationToken ct) => Task.CompletedTask;
public Task SavingAsync(DocumentEventArgs e, CancellationToken ct) => Task.CompletedTask;
public Task ShownAsync(DocumentEventArgs e, CancellationToken ct) => Task.CompletedTask;
public Task HiddenAsync(DocumentEventArgs e, CancellationToken ct) => Task.CompletedTask;
}
// Subscribe (returns IDisposable — dispose to unsubscribe)
var listener = new MyDocumentListener();
IDisposable subscription = await this.Extensibility.Documents()
.SubscribeAsync(listener, filterRegex: null, cancellationToken);
Tips
✅ DO
- Dispose the subscription when you no longer need events
- Use
filterRegexparameter to limit events to specific file patterns - Use
AsTextDocumentAsyncto access text content from aDocumentSnapshot - Handle all
IDocumentEventsListenermethods (even if just returningTask.CompletedTask)
❌ DON'T
- Don't hold
DocumentSnapshotreferences long-term — they represent a point-in-time state - Don't forget to dispose event subscriptions (causes memory leaks)
- Don't assume a document is a text document — call
AsTextDocumentAsyncand check for null
🔧 Troubleshooting
| Symptom | Fix |
|---|---|
| Events not firing | Ensure SubscribeAsync completed; check filterRegex isn't filtering too aggressively |
| Document content is stale | Get a fresh snapshot — DocumentSnapshot is immutable |
| NullReferenceException on text | Use AsTextDocumentAsync — not all documents have text content |
Next steps
- Read and edit text — for editing document content
- Output window — log document events
- Add a command — trigger document operations
- Extension anatomy — understand the extension lifecycle