0

Requirement:

Get the CodeElement (Function/Class etc) from the current cursor position in C++ source and Header files in Visual Studio using Automation Model EnvDTE.

Problem:

When the cursor is in a header file and I iterate the code elements from that header file for getting their position, I get the corresponding elements position in its source file. Because of which I am getting "Value does not fall within specified range" exception.

Example: This is the code snippet

 private CodeElement GetCodeElementAtTextPoint(vsCMElement eRequestedCodeElementKind, CodeElements codeElements, TextPoint objCursorTextPoint)
            {
                CodeElement objResultCodeElement = null;
                CodeElements colCodeElementMembers;
                CodeElement objMemberCodeElement;

                if (codeElements != null)
                {
                    foreach (CodeElement objCodeElement in codeElements)
                    {
                        if (objCodeElement.Kind == vsCMElement.vsCMElementFunction)
                        {
                            var infoLoc = objCodeElement as CodeType;
                        }

                        if (objCodeElement.StartPoint.GreaterThan(objCursorTextPoint))
                        {
                        }
                        else if (objCodeElement.EndPoint.LessThan(objCursorTextPoint))
                        {
                        }
                        else
    ..

In the above code snippet objCodeElement.StartPoint gives me the start point of that CodeElement in source file and hence I am getting the exception at that line

e.g. Suppose in a header file function fun() is declared at line 20 and defined at line 901 in the source file. If I clicked on line 20 then during iteration I get the line number 901 for function fun() which is clearly not is range of header file.

Note: I have tried using CodeElementFromPoint method in FileCodeModel and VCFileCodeModel but it is not reliable.

Did anybody encounter such issue? Please help. Or please suggest me the correct approach to satisfy my requirement.

Thanks in advance.

Hemant
  • 767
  • 6
  • 20

1 Answers1

0

Figured it out myself

The property StartPoint in "objCodeElement.StartPoint" by default gives a position of the element definition.

So instead of using property I used function get_StartPointOf on CodeElement. This function takes two parameters first 'Part of the element' and second 'element from where' (declaration or definition). So giving the second argument as a declaration will give start position of the element declaration in its header file.

e.g.

startPoint = objCodeElement.get_StartPointOf(vsCMPart.vsCMPartWholeWithAttributes, vsCMWhere.vsCMWhereDeclaration);
                        endPoint = objCodeElement.get_EndPointOf(vsCMPart.vsCMPartWholeWithAttributes, vsCMWhere.vsCMWhereDeclaration);
Hemant
  • 767
  • 6
  • 20