I have noticed that you are using the Location property of the caret position in order to create new document positions. The document position class has a constructor that accepts another document position as an argument. It is more suitable for this scenario as it does not translate the location to a position.
Another thing I have noticed is that the document positions are not disposed
after beeing used. Please dispose of the positions as they will keep a reference to its owner document and this is considered a memory leak.
Also, you are getting the span and paragraph boxes from the current inline box. The document position has methods called GetCurrentSpanLayoutBox and GetCurrentParagraphBox that will return the correct box if the position is in such box.
Please have in mind that the document positions should be anchored after its creation and restored from that anchor before executing an action with them. Because the document could be modified after the creation of the position and with thus the position became invalid.
I have prepared a simple demo application with some modification to reflect my comments. You can find it as an attachment.
if you have further questions I will be happy to assist.
Telerik by Progress
Do you need help with upgrading your AJAX, WPF or WinForms project? Check the Telerik API Analyzer
and share your thoughts.