How to create a TextRange from a line number?

Given an IProjectFile instance and a line number in that file, what is the "right" way to create a TextRange for that line, suitable for passing to Navigator.NavigateTextRange()?  Right now I'm opening the file and reading it, counting the character length of all lines until my line number, and passing that sum to the TextRange ctor.  But when I navigate to the location it's often short a couple lines.  I'm guessing that perhaps my count is off due to line ending characters, and I could code for that, but perhaps there exists a better way?

Heres where I compute the TextRange parameter.

class Block {
        public TextRange TextRange
        {
            get
            {
                using (TextReader tr = new StreamReader(ProjectFile.CreateReadStream()))
                {
                    int position = 0;
                    int char_count = 0;
                    string line;
                    while (position++ < StartLineNumber && (line = tr.ReadLine()) != null)
                    {
                        char_count += line.Length + 1;
                    }
                    textRange = new TextRange(char_count);
                }

                return textRange;
            }
        }
...
}

And here's how I use it.

        public override bool Navigate(TreeModelNode node, bool transferFocus)
        {
            if (node != null && node.DataValue is IBlock)
            {
                IBlock block = (IBlock)node.DataValue;

                // TODO! Navigation has some off by one errors or something.
                Navigator.NavigateTextRange(block.ProjectFile, block.TextRange, transferFocus);
                return true;
            }
            return false;
        }




Thanks
Josh

2 comments

I found IDocument.GetLineStartOffset().  Here's some sample code.

DocumentManager documentManager = DocumentManager.GetInstance(solution);
IDocument document = documentManager.GetDocument(projectFile);

int startOffset = document.GetLineStartOffset(startLineNumber-1);
int endOffset = document.GetLineEndOffset(endLineNumber-1);

TextRange tr = new TextRange(startOffset, endOffset);

0

That's right

--
Eugene Pasynkov
ReSharper Technical Lead
JetBrains, Inc.
http://www.jetbrains.com
"Develop with pleasure!"


"jbuedel" <no_reply@jetbrains.com> wrote in message
news:5768356.7341232821029158.JavaMail.clearspace@app4.labs.intellij.net...
>I found IDocument.GetLineStartOffset(). Here's some sample code.

 DocumentManager.GetInstance(solution);
> IDocument document = documentManager.GetDocument(projectFile);
>
> int startOffset = document.GetLineStartOffset(startLineNumber-1);
> int endOffset = document.GetLineEndOffset(endLineNumber-1);
>
> TextRange tr = new TextRange(startOffset, endOffset);]]>

>
>

---
Original message URL:
http://www.jetbrains.net/devnet/message/5230777#5230777



0

Please sign in to leave a comment.