We have methods on the surface for converting between source and nwe offsets so should be a case of re-implementing the method form jquery.textSelection.
I've started working on this, and then realized that we should be able to implement $.textSelection's encapsulateSelection in terms of the other $.textSelection functions. This way we won't have to duplicate this 100-line monster in every custom wikitext editor.
On second thought, I'm not sure if that was the best idea… This now essentially works by replacing the entire contents of the editor, which a) sometimes causes the scroll position to jump and b) generates inefficient transactions. I might have to come back to this, and do it the boring way.
(NB there is another textSelection implementation in CodeMirror that is 90% encapsulateSelection that could be replaced with a single line codeMirror.doc.replaceSelection( insertText );)