Search code examples
openoffice.orglibreofficebasic

Macro to find paragraphs in text selection in Open/Libre/Neo Office


I am trying to enumerate the paragraphs selected by the user in (Neo|Libre|Open)Office.

When I use the code below, modified version from here,

Sub CheckForSelection
    Dim oDoc as Object
    Dim oText

    oDoc = ThisComponent
    oText = oDoc.Text

    if not IsAnythingSelected(oDoc) then
        msgbox("No text selected!")
        Exit Sub
    end if

    oSelections = oDoc.getCurrentSelection() 
    oSel = oSelections.getByIndex(0)    

    ' Info box
    'MsgBox oSel.getString(), 64, "Your Selection"

    oPE = oSel.Text.createEnumeration()
    nPars = 0
    Do While oPE.hasMoreElements()
        oPar = oPE.nextElement()
        REM The returned paragraph will be a paragraph or a text table
        If oPar.supportsService("com.sun.star.text.Paragraph") Then 
            nPars = nPars + 1
        ElseIf oPar.supportsService("com.sun.star.text.TextTable") Then 
            nTables = nTables + 1
        end if
    Loop

    ' Info box
    MsgBox "You selection has " & nPars & " paragraphs.", 64

end Sub

it finds ALL the paragraphs in the document, not just in the selection. Google has failed me. Any thoughts on how to find individual paragraphs in the selection?


Solution

  • The oSel.Text is a shortcut for oSel.getText() which "Returns the text interface in which the text position is contained." https://www.openoffice.org/api/docs/common/ref/com/sun/star/text/XTextRange.html#getText

    So to get a ParagraphEnumeration only from the Selection, you should use oPE = oSel.createEnumeration() instead of oPE = oSel.Text.createEnumeration().