In a VisualStudio.Extensibility Extension project (VS2022), in order to modify the currently edited Document from a Command it's enough to execute:
public override async Task ExecuteCommandAsync(IClientContext context, CancellationToken cancellationToken)
{
using var textView = await context.GetActiveTextViewAsync(cancellationToken);
await Extensibility.Editor().EditAsync(batch =>
{
var doc = textView.Document.AsEditable(batch);
...
}
}
where context.GetActiveTextViewAsync(cancellationToken) wraps a call to:
context.Extensibility.Editor().GetActiveTextViewAsync(context, cancellationToken);
If I try doing the same from a ITextViewChangedListener.TextViewChangedAsync event, I don't have access to any context; at least I didn't find any.
However I can modify the Document content by executing:
Task ITextViewChangedListener.TextViewChangedAsync(TextViewChangedArgs args, CancellationToken cancellationToken)
{
return Extensibility.Editor().EditAsync(batch =>
{
var doc = args.AfterTextView.Document.AsEditable(batch);
...
}
}
My question if it's safe modifying the Document content this way and, if not, where to find the object implementing IClientContext?