如何在visual studio扩展中选择之前获取文本

时间:2018-03-08 14:06:41

标签: c# visual-studio-2015 visual-studio-extensions

我想做什么

我编写了一个在当前光标处插入代码的扩展名。现在我希望成为文本,取决于光标前面的内容。

实施例

案例1:

// Some comment {insert text here}

这里我想插入没有" //"的文字。 (因为它已经存在)

案例2:

some Code {insert comment here}

这里我想用" //"。

插入文本

我目前拥有什么

    /// <summary>
    /// Generates the text for an inline comment
    /// </summary>
    /// <returns>The text for an inline comment</returns>
    public string Comment()
    {
        //Get Selection
        var objSel = (TextSelection)_dte2.ActiveDocument.Selection;
        //Save offset
        var offset = objSel.TopPoint.LineCharOffset;
        //move selection to start of line
        objSel.StartOfLine();

        //Get active document
        var activeDoc = _dte2.ActiveDocument.Object() as TextDocument;
        //Get text between selection and offset
        var text = activeDoc.CreateEditPoint(objSel.TopPoint).GetText(offset);

        //move selection back to where it was
        objSel.MoveToLineAndOffset(objSel.TopLine,offset);

        //return text
        return text.Contains("//") ? $@" {GetText()} : " : $"// {GetText()} : ";

    }

问题

这适用于大多数情况。只有两个问题:

  1. 在我看来,选择这个选择是不好的做法。

  2. 选择文字时,它将失去选择,代码运行后选择将为空。

  3. 我认为如果我能在我的选择所在的行的开头得到一个点,我可以达到我想要的。然后我可以把这一点放在

    var text = activeDoc.CreateEditPoint(objSel.TopPoint).GetText(offset);
    

    而不是objSel.TopPoint。

    我的问题

    实现我想要做的最好方法是什么?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案:

    /// <summary>
    /// Generates the text for an inline comment
    /// </summary>
    /// <returns>The text for an inline comment</returns>
    public string Comment()
    {
        //Get Selection
        var objSel = (TextSelection)_dte2.ActiveDocument.Selection;

        //Create EditPoint
        var editPoint = objSel.TopPoint.CreateEditPoint();
        editPoint.StartOfLine();

        //Get active document
        var activeDoc = _dte2.ActiveDocument.Object() as TextDocument;

        //Get text between EditPoint and Selection
        var text = activeDoc.CreateEditPoint(editPoint).GetText(objSel.TopPoint);

        //return text
        return text.Contains("//") ? $" {GetText()} : " : $"// {GetText()} : ";
    }

关键是行

var editPoint = objSel.TopPoint.CreateEditPoint();
editPoint.StartOfLine();

有了这个,我可以创建一个新点,然后我将移动到该行的开头并获取它与选择TopPoint之间的文本