Every paragraph has an id no so a text paragraph's textrange position will be that ID plus the character offset from the start of the paragraph.
Below example gets the paragraph ID and character positions of the selection (viewcursor), clears that selection, then restores it using that information. Select some text in a document, run main.
Tested on OO only, may not work with something more complicated than just text paragraphs.
- Code: Select all Expand viewCollapse view
Sub Main
dim paraID1 as string,charNO1 as string,paraID2 as string,charNO2 as string
'get paraID and charno representation of viewcursor start and end of textranges
tc =thiscomponent.text.createtextcursorbyrange(thiscomponent.currentcontroller.viewcursor.getstart)
getTextRangeParaIDAndCharNo(tc,paraID1,charNO1)
tc =thiscomponent.text.createtextcursorbyrange(thiscomponent.currentcontroller.viewcursor.getend)
getTextRangeParaIDAndCharNo(tc,paraID2,charNO2)
thiscomponent.currentcontroller.select(thiscomponent.text.getstart) 'clear selection by moving viewcursor to start
msgbox paraID1 & "," & charno1 & chr(10) & paraID2 & "," & charno2
'restore selection from paraIDs and charno
tc3 = setTextRangeFromParaIDAndCharNo(thiscomponent,paraID1,charno1)
tc4 = setTextRangeFromParaIDAndCharNo(thiscomponent,paraID2,charno2)
tc3.gotorange(tc4,true)
thiscomponent.currentcontroller.select(tc3,false)
end sub
sub getTextRangeParaIDAndCharNo(tc,byref paraID as string,byref charNo as string)
tc.gotostartofparagraph(true)
cno= len(tc.string)
en = tc.createenumeration
do until en.hasmoreelements = false
p =en.nextelement
paraID =endval( p.localname)
charNo = cno
exit do
loop
End sub
function setTextRangeFromParaIDAndCharNo(componentv,paraID as string,charNo as string)
lenno = len(paraID)
en = componentv.text.createenumeration
do until en.hasmoreelements = false
p =en.nextelement
if right (p.localname,lenno) = paraID then
tc =componentV.text.createtextcursorbyrange(p)
tc.gotoStartOfParagraph(false)
tc.goright(val(charNO),false)
setTextRangeFromParaIDAndCharNo=tc
exit do
end if
loop
End function
Function EndVal(st As String) As Long
Dim i As Long, a As Integer, s As String, res As String
res = ""
s = ""
For i = Len(st) To 1 Step -1
s = Mid(st, i, 1)
a = Asc(s)
If a >= 48 And a <= 57 Then
res = s & res
Else
Exit For
End If
Next
EndVal = Val(res)
End Function
Edit: didn't include the endval function to get the number at the end of a string - added.