如何在visual studio扩展中的选择之前获取文本 [英] How to get the text before a selection in visual studio extension
问题描述
我编写了一个扩展程序,可以在当前光标处插入代码.现在我想根据光标前面的内容成为文本.
I have written an extension that inserts code at the current cursor. Now I want to be the text depending on what is in front of the cursor.
案例 1:
// Some comment {insert text here}
这里我想插入没有//"的文本(因为它已经存在了)
Here I want to insert text without the "//" (because its already there)
情况 2:
some Code {insert comment here}
这里我想插入带有//"的文本.
Here I want to insert the text with the "//".
/// <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()} : ";
}
问题
这适用于大多数情况.只有两个问题:
The problem
This works for most cases. There are only 2 problems:
在我看来,移动选择并不是一个好习惯.
In my opinion its not good practice to move the selection around.
选择文本时会丢失选择,代码运行后选择为空.
When selecting text it will lose the selection and the selection will be empty after the code ran.
如果我能在我的选择所在行的开头得到一个点,我想我可以得到我想要的.然后我可以把这一点放在
I think I could to what I want if I could get a point thats at the start of the line in which my selection is. Then I could put this point in
var text = activeDoc.CreateEditPoint(objSel.TopPoint).GetText(offset);
而不是 objSel.TopPoint.
instead of objSel.TopPoint.
实现我想做的事情的最佳方法是什么?
What is the best way to achieve what I want to do?
推荐答案
我找到了解决方案:
/// <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 之间的文本
with this I can create a new point which I will then move to the start of the line and get the text between it and the selections TopPoint
这篇关于如何在visual studio扩展中的选择之前获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!