Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vs2010 automation : Get the text value of a EnvDTE.CodeElement

So I'm playing around with EnvDTE, and the EnvDTE.CodeModel API, And I was wondering if there was a way to get the text value represented by a CodeElement.

Let's say I have an CodeAttribute, is there some way to get a string of what the CodeAttribute represents, i.e.[MyAttribute(value="myvalue")].

I know it's possible to reconstruct the code using the various properties of the CodeElement, at least in some scenarios, but for some things it seems it would be easier to just get the text.

Thanks!

like image 804
Master Morality Avatar asked Oct 29 '10 15:10

Master Morality


3 Answers

The CodeElement interface has the properties StartPoint and EndPoint which represent the start and end of the element within the buffer. These contain the Line Number / Column which can be passed to methods like IVsTextLines.GetLineText and give you back the value you're looking for.

To get the IVsTextLines for a given CodeElement you can do the following

CodeElement ce = ...;
TextDocument td = ce.StartPoint.Parent;
IVsTextLines lines = td as IVsTextLines;
like image 83
JaredPar Avatar answered Nov 17 '22 16:11

JaredPar


  void WriteMapping(CodeProperty codeProperty)
 {
   WriteLine("");
   WriteLine("///CodeProperty");
   WriteLine("///<summary>");
   WriteLine("///"+codeProperty.FullName);
   WriteLine("///</summary>");
   if(codeProperty.Getter==null && codeProperty.Setter==null)
       return;
   if(codeProperty.Attributes!=null){
       foreach(CodeAttribute a in codeProperty.Attributes)
        {
            Write("["+a.FullName);
            if(a.Children!=null && a.Children.Count>0)
            {
                var start=a.Children.Cast<CodeElement>().First().GetStartPoint();
                var finish= a.GetEndPoint();
                string allArguments=start.CreateEditPoint().GetText(finish);

                Write("("+allArguments);
            }
    WriteLine("]");
        }
        }
   Write("public "+GetFullName(codeProperty.Type) +" "+codeProperty.Prototype);

    Write(" {");
    //if(codeProperty.Getter!=null && codeProperty.Getter.Access!=vsCMAccess.vsCMAccessPrivate)
        Write("get;");
    //if(codeProperty.Setter!=null)
        Write("set;");
    WriteLine("}");

   }
like image 3
Maslow Avatar answered Nov 17 '22 16:11

Maslow


In addition to the answer by @JaredPar, an alternative approach would be:

public string GetText(CodeAttribute attribute)
{
    return attribute.StartPoint.CreateEditPoint().GetText(attribute.EndPoint);
} 

That's it!! (Thanks @JaredPar for the pointers)

Source: http://msdn.microsoft.com/en-us/library/envdte.editpoint.gettext.aspx

like image 2
Alfero Chingono Avatar answered Nov 17 '22 18:11

Alfero Chingono