Hello.
I am trying to write a Python macro in LibreOffice Writer to search for and highlight specific Unicode characters (such as ZWSP, RLM, BOM, etc.) in the document. However, I keep encountering error:
Version: 25.2.5.2 (X86_64) / LibreOffice Community
Build ID: 520(Build:2)
CPU threads: 2; OS: Linux 6.8; UI render: default; VCL: gtk3
Locale: fa-IR (en_US.UTF-8); UI: en-US
Ubuntu package version: 4:25.2.5~rc2-0ubuntu0.24.04.1~lo1
Calc: threaded
Error:
import uno
from com.sun.star.beans import PropertyValue
def highlight_fake_nonbreaking_spaces():
"""Highlights fake non-breaking spaces in Writer by setting their background color to yellow."""
doc = XSCRIPTCONTEXT.getDocument()
text = doc.Text
cursor = text.createTextCursor()
# List of special characters to search for
fake_chars = [
"\u00AD", # Soft Hyphen
"\u00AC", # Not Sign
"\u200F", # RLM
"\u2005", # Four-Per-Em Space
"\uFEFF", # BOM / ZWNBSP
"\u200B", # ZWSP
"\u200D", # ZWJ
]
# Create SearchDescriptor via ServiceManager
ctx = XSCRIPTCONTEXT.getComponentContext()
smgr = ctx.getServiceManager()
try:
search_desc = smgr.createInstanceWithContext("com.sun.star.text.SearchDescriptor", ctx)
except Exception as e:
print(f"Error creating SearchDescriptor: {e}")
return
search_desc.setSearchString("")
search_desc.setSearchBackwards(False)
search_desc.setSearchAll(True)
for char in fake_chars:
search_desc.setSearchString(char)
found = search_desc.execute()
if not found:
continue
while found:
start = search_desc.getStart()
end = search_desc.getEnd()
cursor.gotoRange(start, False)
cursor.gotoRange(end, True)
cursor.CharBackColor = 16776960 # Yellow
found = search_desc.execute()