How do I move the selection / cursor / caret in the editor?

I just rolled my own COrrect TWo INitial CApitals because the built-in doesn't work for me but the cursor is moved to the end of the segment on UpdateSegmentPair which is not always appropriate. I would like to move it back where it was but I can't find any method / property to move the Document.Selection. All relevant properties seem to be read-only.

There has to be something ... but where?

3 Replies Latest Replies: 12 Apr 2018 11:11 AM by Angela Sigee
  • Through unforeseen channels Hoon Kim reached out to me and hinted at using the IContentSelection interface. Thanks Hoon Kim, I got it working.

    As explained here you can get an IContentSelection instance only through reflection - a route I didn't want to take but in the end was forced to.

    However, I never got IContentSelection.MoveTo to work which by the looks of it should bring the desired result. Apparently the underlying nodes change completely after UpdateSegmentPair. So instead I ended up using a combination of IContentSelection.Moves (to start of segment and then iterating by words and finally by characters and counting the progress until the desired position is reached) it is possible to implement a working albeit inefficient method.

    In the end I settled for something different: Through reflection (GetTargetSegmentContainerNode / GetSourceSegmentContainerNode) I get hold of the ISegmentContainerNode which I then can use to instantiate a ContentNodeIterator to find the relevant ITextNode - a lot less enumerators and iterations.

     
    public void MoveCursorTo(IContentSelection cs, int pos, bool target=true, bool extend=false)
    {
        ISegmentContainerNode segmentNode = GetActiveSegmentContainerNode(target);
        if (segmentNode != null)
        {
            ITextNode textNode = null;
            
            ContentNodeIterator contentNodeIterator = new ContentNodeIterator(segmentNode.StartNode);
            while (contentNodeIterator.Next())
            {
                textNode = contentNodeIterator.CurrentNode as ITextNode;
                if (textNode != null)
                {
                    int length = textNode.Text.Properties.Text.Length;
                    if (pos <= length)
                    {
                        cs.MoveTo(new Position(textNode, pos), extend);
                        return;
                    }
                    pos -= length;
                }
            }
        }
    }
    
  • In reply to Angela Sigee:

    'pos' should be the problem if you have any Tags.
  • In reply to Hoon Kim:

    no, because I handle ITextNodes only

Related