How to traverse text nodes left and right

Let’s say I have this text H[el][lo w]|[o]rld. Square brackets are marks. el has bold and “custom” marks, lo w has italic and “custom” marks, o has only “custom” mark. “custom” is a type of mark. Vertical line is my caret. So I have a position. What I want to end up with is a string ello wo. Basically take all marks of type “custom” left and right from the caret, until I first meet a node without such mark.

Can’t really wrap my head around this. I’m trying to use resolved positions and nodesBetween and some while loops, but it just doesn’t seem to work. Maybe there is some obvious method I’m missing?

You can call .index() on a resolved position to get the index of the pointed-to node in the parent node, and scan both forward and backward from there, using .parent.child(n) to access siblings as long as n >= 0 / n < parent.childCount and mark.isInSet(parent.child(n).marks), building up a string of content in the process (though make sure you also handle the case where one of the marked nodes isn’t a text node).