Visual Studio 扩展:如何处理多个插入符号?

微积分高手

我正在为涉及更改插入符号位置的工作开发 Visual Studio 扩展/VSIX 包。当然,处理单个插入符号很容易:

/// Get the Host of current active view
private async Task<IWpfTextViewHost> GetCurrentViewHostAsync()
{
    // First get the active view:
    var txtManager = (IVsTextManager)await ServiceProvider.GetServiceAsync(typeof(SVsTextManager));
    Assumes.Present(txtManager);
    IVsTextView vTextView = null;
    const int mustHaveFocus = 1;
    textManager.GetActiveView(mustHaveFocus, null, out vTextView);

    if (vTextView is IVsUserData userData)
    {
        // Get host
        IWpfTextViewHost viewHost;
        object holder;
        Guid guidViewHost = DefGuidList.guidWpfTextViewHost;
        userData.GetData(ref guidViewHost, out holder);
        viewHost = (IWpfTextViewHost)holder;

        return viewHost;
    }

    return null;
}

// Later:
private async void ExecCommand(object sender, EventArgs e)
{
    IWpfTextViewHost host = await GetCurrentViewHostAsync();

    // Access single caret
    host.TextView.Caret.MoveTo(/* New position here */);
}

但是假设我使用“插入下一个匹配插入符”命令插入另一个插入符,所以我现在有两个不同的插入符。使用上述方法移动插入符号将删除第二个插入符号,据我所知,IVsTextView只有一个插入符号属性。

我的下一个想法是,我应该访问其他光标与其他IVsTextManager的界面host,但我能找到的最接近的是它的EnumViews(IVsTextBuffer, IVsEnumTextViews)方法,它总是返回一些消极的,非S_OK价值和树叶的IVsEnumTextViews项目作为null类似的事情发生在EnumIndependentViews方法上。

我这样做对吗?“多个插入符号”是如何工作的?我找不到任何关于它的文档。API 甚至让我这样做吗?

微积分高手

事实证明,您必须使用ITextView2's (Not ITextView)MultiSelectionBroker属性,该属性只能通过 TextView 的GetMultiSelectionBrokerExtension 方法访问有关它的更多详细信息,请参阅文档

private async void ExecCommand(object sender, EventArgs e)
{
    // ConfigureAwait(true) is just to silence warnings about adding ConfigureAwait(false)
    // "false" will cause this to not function properly. (Carets won't update).
    IWpfTextViewHost host = await GetCurrentViewHostAsync().ConfigureAwait(true);

    // Because TextView is only ITextView and not ITextView2, 
    //  we can only access the MultiSelectionBroker property with the extension method:
    IMultiSelectionBroker selectionBroker = host.TextView.GetMultiSelectionBroker();
    foreach (var selection in selectionBroker.AllSelections)
    {
        var nextPoint = GetSomePointHere(host, selection);
        selectionBroker.TryPerformActionOnSelection(
            selection,
            t => t.MoveTo(nextPoint, false, PositionAffinity.Successor),
            out Selection after
        );
    }
}

不知道为什么,但是ITextView2当我写这个问题时,我一定完全错过了文档

注意:默认Microsoft.VisualStudio.Text.UI.dll不会包含这个方法,因为它是一个扩展方法。您可以从解决方案中删除 dll 引用并重新添加正确的引用(在扩展下)以解决此问题。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章