How to determine in Visual Studio that the current

2019-07-18 07:56发布

Is there a way to determine programmatically in a Visual Studio code editor ( C/C++ or C# ) that the current caret position is within a comment block ( after "//" or between /* */ )? I tried to use IContentType like this:

if ( m_textView.TextBuffer.ContentType.TypeName == "comment" ) 

but it seems that ContentType.BaseTypes contain only more general content types (like "text", "code", "C/C++") relating to the whole file.

2条回答
霸刀☆藐视天下
2楼-- · 2019-07-18 08:26

The ContentType property refers to the content of the ITextBuffer instance. This is typically C#, text, code, etc ... It doesn't hold semantic information like comment or keyword

Unfortunately there is currently no good API that exposes this information. Comments are a language specific construct and the only general purpose language API in Visual Studio at the moment is the Code Model and I don't believe it supports comments.

In the future APIs like Roslyn will provide the information you are looking for. This won't be available until at least the release after Visual Studio 2013

EDIT

There's been some speculation as to whether or not IClassificationType could be used to get information about comments. At a high level this could indeed be used although it is probably something I would avoid doing. I've been bitten in the past several times trying to grab information from classifiers on demand. There are a lot of subtle perf issues you can run into.

查看更多
爷、活的狠高调
3楼-- · 2019-07-18 08:27

You should be able to use the IClassifierAggregatorService to access the classifications used for syntax highlighting in the editor. If you don't beat me to it, I'll post a more complete example this evening showing the extraction of the IClassificationType of the text under the caret.

查看更多
登录 后发表回答