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!
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;
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("}");
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With