I’m trying to write a Python macro that adds a hyperlink to the current selection in a Writer document, and I can’t puzzle out how to do it. I’ve used the Object Inspector to determine where the hyperlink goes, and I have working Python code that obtains the current selection. But I can’t figure out how the Object Inspector’s data model maps to the Python UNO model, and haven’t found any documentation that explains it.
In a Writer document with one contiguous region of text selected, the Object Inspector shows the following. (I’ve excluded dozens of properties that didn’t seem relevant, reordered sibling properties for clarity, and formatted each property as “PropertyName : type = value”.)
Current selection = class SwXTextRanges
ElementType : type = com.sun.star.text.XTextRange
ImplementationName : string = "SwXTextRanges"
SupportedServiceNames : string[1] = { "com.sun.star.text.TextRanges" }
@0 : css.text.XTextRange= <Object@SwXTextRange>
AvailableServiceNames : string[1] = { "com.sun.star.text.TextContent" }
SupportedServiceNames : string[7] = { "com.sun.star.text.TextRange", ... }
ElementType : type = com.sun.star.text.XTextRange
HyperlinkURL : string = ""
ImplementationName : string = "SwXTextRange"
String : string = "my selected text"
Based on what the Object Inspector showed me, I expected to use Python code that looked something like this:
doc = XSCRIPTCONTEXT.getDocument()
sel = doc.getCurrentSelection()
sel0 = sel[0]
selText = sel0.String # just a test to see if the property exists
sel0.HyperlinkURL = "www.foobar.com"
When I try to read or assign the HyperlinkURL property, I get an “AttributeError”. I’ve tried this both in a Python script and interactively in the APSO console.
While in the APSO console, I discovered that both sel and sel0 are of class “pyuno”, not some variant of [X]TextRange[s] as I expected. I explored the LibreOffice UNO API reference in search of enlightenment, but came away more confused than ever. I searched the API reference for “hyperlinkurl”, and found it in three places: com.sun.star.report.XReportControlFormat, com.sun.star.style.CharacterProperties, and com.sun.star.text.BaseFrameProperties. The API reference claims that CharacterProperties are available from a TextRange, but it didn’t work in Python.
I’m at my wit’s end. Could someone please provide some guidance?
Why do I want to do this? Because I have a long list of LO macros that I want to write, some of which manipulate hyperlinks, and I need to learn how the various tools and APIs fit together. I’ve been developing software for decades, but this is my first attempt to write an LO Python macro that does something useful.
Why Python and not Basic? I had my fill of Basic during the many years I used MS Office, and now that I’ve finally abandoned it in favor of LibreOffice, I’m going to use a “real” language for macros.
Version: LibreOffice 7.2.5.2 (x64) on Windows 10.0.18362.959
Thank you,
– Ed