Macro: remove blank lines at beginning or end of selection

I have made a macro which cannot work correctly if blank lines are selected at the beginning or end of the selection. Line breaks are expected in the middle of the selection, however.

Since LibreOffice’s string searching and manipulation abilities are pitiful, I can’t just do a nice regex search like “^\n+|\n+$” to remove blank lines at the start or end. I can test if the first or last character is chr(13) and then trim it out, but if there is more than one blank line selected, I would have to have to right some crazy loop to keep checking for blank lines until they are all gone. Surely there must be some better way.

I considered converting the selection to an enumeration using createEnumeration, and then I can check each paragraph to see if it is empty, but I don’t know how to move the start of the selection forward, or the end of the selection backwards.

Doesn’t the normal regex search for empty paragraph (see "^$ Finds an empty paragraph") work for you?

I am talking about searching a string in a macro.

@lomacar: f you insist in not distinguishing lines and paragraphs there will be no progress. Handling paragraphs is not done by searching strings. There are lots of properties “hosted” by the paragraph e.g.
You may start with reading about the API. And there is LibreOffice: XText Interface Reference e.g.
Well, I know it’s not easy to find what you need. It’s not easy for me, too.

A demo

Sub demo()
theSel = ThisComponent.CurrentSelection
If theSel.Count>1 Then 
 MsgBox("Tis is made for a single-TextRange selection.")
 Exit Sub
End If
theRg = theSel(0)
theParEnum = theRg.CreateEnumeration
ThisComponent.UndoManager.EnterUndoContext("thisDemo")
Do While theParEnum.HasMoreElements
 onePar = theParEnum.NextElement
 If onePar.String="" Then onePar.Text.removeTextContent(onePar)
Loop
ThisComponent.UndoManager.LeaveUndoContext()
End Sub

Thanks. I don’t want to delete paragraphs though. Actually, the best thing to do would be to deselect those blank lines, because in the end I want to replace the selected text and I don’t want people accidentally selecting empty lines and having empty lines replaced. But I am not sure how to make a selection smaller. I only see how to make a selection larger.