IAstNode StartOffset and EndOffset properties not reliable ?

SyntaxEditor .NET Languages Add-on for WPF Forum

Posted 7 years ago by 7Alpha7
Version: 12.1.0560
Avatar

Hello,

I want to replace part of C# code in a string like this :

public partial class SomeClass {
        //Comment.
        #region Some region
        [Attribute("", "", "", "", "", "", "", "")]
        public string Name{get;set;}
        #endregion
}

 

First I get the AST tree of the code I have say in the Content string;

//Say I have a C# ISyntaxLanguage instance in the Language property
return ((DotNetParseData)Language.Parse(Content)).Ast;

 From this AST I search the IAstNode I want to replace; once located I use the StartOffset and EndOffset property to replace the string part :

 

//Say the REPLACED string is in the replace string
Content = Content.Substring(0, astNode.StartOffset.Value) + replace + 
 sourceFile.Content.Substring(astNode.EndOffset.Value);

 

I my example I retrieve the IAstNode with value "Attribute" but it does'nt work, because if the Content string has formatted code, with breaklines or tabs the StartOffset and EndOffset property are wrong, and the replaced string is in the wrong position. I got this result :

 

public partial class SomeClass {
        //Comment.
        #region Some region
      REPLACED"")]
        public string Name{get;set;}
        #endregion
}

 

Like this I suppose it is a bug.

[Modified 7 years ago]

Comments (2)

Posted 7 years ago by 7Alpha7
Avatar

Well, wenting deeper into the documentation it appears that dealing with a CodeDocument especially created for the purpose I can do what I want if I perform the change operation with the ReplaceText method passing it a TextRange built from the start and end offsets of the IAstNode.

This is a very intricated way to obtain the desired effect, and I cannot understand why the offsets cannot be applied straight to the original string. This is a mystery you'll certainly be able to explain.

Answer - Posted 7 years ago by Actipro Software Support - Cleveland, OH, USA
Avatar

Hello, remember that our offsets are all based on linefeed-only line terminators which we use for our documents.  Whereas if you are doing a string replace external to our document, you'd have to probably adjust the offsets to account for each line terminator being CR/LF instead of just LF.


Actipro Software Support

The latest build of this product (v2018.1 build 0675) was released 1 month ago, which was after the last post in this thread.

Add Comment

Please log in to a validated account to post comments.