Python : Error in the example file capitalise.py

Creating a macro - Writing a Script - Using the API (OpenOffice Basic, Python, BeanShell, JavaScript)
Post Reply
User avatar
jeanmi2403
Posts: 30
Joined: Tue Jan 29, 2008 12:37 pm
Location: Sucy en Brie (France)

Python : Error in the example file capitalise.py

Post by jeanmi2403 »

Hello,
I have just detected (and perhaps fixed) an old error that has been lurking (for a very long time?) in the `capitalise.py` example file in OpenOffice (4.1.16) and persists in LibreOffice (26.2).
The macro crashes if there is a multiple selection. I admit I didn't quite understand why.
On a day of extreme heat, I decided not to take the bike out...
In the code, we find:

Code: Select all

xModel = XSCRIPTCONTEXT.getDocument()  # NOQA
    xSelectionSupplier = xModel.getCurrentController()
    xIndexAccess = xSelectionSupplier.getSelection()
    count = xIndexAccess.getCount()
While poking around the `xIndexAccess` in question using Xray, I noticed something surprising:
with no words selected or just one, `count` equals 1, but with two words selected, `count` equals 3!
And with N selections, `count` is N+1... naturally.
With 0 or one word, the selection is obtained via `xIndexAccess.getByIndex(0)` (a single element).
Otherwise, it is obtained via `xIndexAccess.getByIndex(i)` where 0 < i < count, with the first element being empty (a mystery?).
Next, we find:

Code: Select all

if count >= 1:  # ie we have a selection
        i = 0
    while i < count:
        xTextRange = xIndexAccess.getByIndex(i)
        theString = xTextRange.getString()
        if len(theString)==0 # This is where the ambiguity lies.
This works well with a single selection or no selection, but not with multiple selections, because it is impossible to tell why the string is empty: is it the first item in a list, or is there no selection?
Indeed, following these instructions, if there is no selection, the macro selects the word under the cursor and applies the capitalization to it.
In the case of multiple selections, expanding the selection to the word at the cursor disrupts the rest of the macro.
Therefore, simply replace the ambiguous line with:

Code: Select all

if len(theString)==0 and count == 1: # no sélection
And the extension to the current word will only occur if there is no selection.
I am not quite sure whom to send this fix to; it has been outstanding for years and does not reflect well on Python programming.
I am also posting this on the French-language forum.
Have a great summer, everyone.
P.S.: As a bonus, here is a document to test the macro.
Exemple-Capitalise-en.odt
(34.69 KiB) Not downloaded yet
Jean-Michel
LibO 26.2 and AOO 4.1.16 on Windows 11 & Ubuntu 22.04
LibO 26.8 on OpenSuse & Linux MX
Post Reply