Error python macro

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:

ask

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()

AI ? :confused:

LibreOffice: SearchDescriptor Service Reference

I rewrote and modified my code based on the documentation provided in this link:

While the code executes without any errors, it fails to find and highlight the target Unicode characters in the document. Below is the updated code I am using:

import uno
from com.sun.star.beans import PropertyValue

def highlight_fake_nonbreaking_spaces():
    """Finds and highlights fake non-breaking spaces in Writer text with a yellow background."""
    # Access the document, text, and create a cursor
    doc = XSCRIPTCONTEXT.getDocument()
    text = doc.Text
    cursor = text.createTextCursor()

    # List of special characters to search for (Unicode)
    fake_chars = [
        r"\x{00AD}",  # Soft Hyphen
        r"\x{00AC}",  # Not Sign
        r"\x{200F}",  # RLM
        r"\x{2005}",  # Four-Per-Em Space
        r"\x{FEFF}",  # BOM / ZWNBSP
        r"\x{200B}",  # ZWSP
        r"\x{200D}",  # ZWJ
    ]

    # Create SearchDescriptor using ServiceManager
    ctx = XSCRIPTCONTEXT.getComponentContext()
    smgr = ctx.getServiceManager()
    
    try:
        # Attempt to create the SearchDescriptor instance
        search_desc = smgr.createInstanceWithContext("com.sun.star.util.SearchDescriptor", ctx)
        if search_desc is None:
            print("Error: SearchDescriptor could not be created.")
            return
    except Exception as e:
        # Handle errors during SearchDescriptor creation
        print(f"Error creating SearchDescriptor: {e}")
        return

    # Configure search settings
    search_desc.setPropertyValue("SearchRegularExpression", True)  # Enable regular expressions
    search_desc.setPropertyValue("SearchCaseSensitive", False)    # Case-insensitive search
    search_desc.setPropertyValue("SearchBackwards", False)        # Search forward

    # Loop through each special character
    for char in fake_chars:
        # Set the search string (using Unicode escape format for regex)
        search_desc.setSearchString(char)

        # Perform the search
        found = doc.findFirst(search_desc)
        while found:
            start = found.getStart()  # Get the start position of the found match
            end = found.getEnd()      # Get the end position of the found match

            # Move the cursor to the found range
            cursor.gotoRange(start, False)
            cursor.gotoRange(end, True)

            # Highlight the background color to yellow
            cursor.CharBackColor = 16776960  # Yellow

            # Search for the next occurrence
            found = doc.findNext(found.getEnd(), search_desc)

glad it was useful.


question still: AI ?

:thinking:

Yes, I used AI.

not knowing your background, nor what time you plan to invest, I would recommend you get rather inspired by resources like Libreoffice writer Macro searching document - #2 by PYS
Scan string for unicode character

hm

def highlight_fake_nonbreaking_spaces():
    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
    ]
    
    search_desc = doc.createSearchDescriptor()
    search_desc.setSearchString(r"|".join(fake_chars)) ###!!!!
    search_desc.SearchBackwards = False
    search_desc.SearchAll = True
    search_desc.SearchBackwards = False
    search_desc.SearchCaseSensitive = False
    search_desc.SearchRegularExpression = True
       
    found = doc.findAll(search_desc)
    if found.Count: 
        print(found.Count)
        for needle in found:
            start = needle.getStart()
            end = needle.getEnd()
        
            cursor.gotoRange(start, False)
            cursor.gotoRange(end, True)
            cursor.goRight(5, True)
        
            cursor.CharBackColor = int("ff0000",16)  # RED

use mri.oxt instead