I would like to create a Visual Studio addin which can identify if the caret currently is inside a method, class or namespace block, i.e. if the caret moves, the addin should be able to note down the status that the caret is currently inside so-and-so element.
If this can be extended to any C# block enclosed in curly braces, e.g. properties, that would be excellent.
Although I have checked for similar questions, please let me know if this is a repeat question so I can mark it accordingly. If other VS Addin-related questions are obviously helpful here, please let me know that too.
Basically, I would like to know what techniques we can use and how this can be accomplished.
EDIT: I guess the short answer to get started is:
- Get Visual Studio 2010 SDK SP1
- Probably use the "Extensibility" project template "Editor Text Adornment" or some other such template.
Actually, I think the first thing you need to do is to judge how many methods or properties in your class and what's the position of them. After you obtain those information. The next step you need to do is to judge what's the current cursor position now. Then you can do a compare with those methods information you obtained. Until now, you can get which method that your cursor in. This is a ballpark solution that I find.
Let's talk about some technical details:
1.How to get the positions of methods and properties?
you can use NRefacotry or CSParser to do this (I use NRefactory to finish my requirement)
2.How to get cursor position?
there is a method named "GetCaretPos" in IVsTextView. You can get ActiveTextView through TextManager. Then you could use "GetCaretPos" method. Here are some codes may help you.
public static IVsTextManager TextManager
{
get
{
if (textManager == null)
{
Object obj = Package.GetGlobalService(typeof(SVsTextManager));
if (obj == null)
{
throw new ArgumentException("get textmanager failed in VSTextView");
}
textManager = obj as IVsTextManager;
}
return textManager;
}
}
public static IVsTextView ActiveTextView
{
get
{
IVsTextView activeView = null;
if (TextManager != null)
{
TextManager.GetActiveView(1, activeTextBuffer, out activeView);
}
return activeView;
}
}
来源:https://stackoverflow.com/questions/8688258/find-out-if-cursor-is-inside-a-method-class-or-namespace-block