I just wrote an Add-on that helps to resize parts of the text in the cards. Therefore you can select a text, press the button, done. But I still got one problem to solve. How can I get the cursor index, to identifiy the exact part that I selected? I need this, because if I select a Text, that occures multiple times, right now only the first occurence got modified.
It’s not exactly clear, what case is described here, but in general, information about webview selection ranges can be accessed via getSelection() method. If you are working with multiple ranges, each can be accessed as selection_object.getRangeAt(range_index), which will contain cursor positions as startOffset and endOffset properties.
To run JS that processes webview content and returns the results to Python, use editor.web.evalWithCallback.
For example I have three lines with the text “test”. I want to resize the second and third line. That’s currently not possible because of the way I’m searching for the text:
selected = editor.web.selectedText() field_index = editor.currentField html = editor.note.fields[field_index] pattern = re.compile( rf"<span[^>]font-size:\s(\d+)%[^>]*>({selected})", re.IGNORECASE ) match = patter.search(html)
This gives me the first occurence of the selected text, lines one and two instead of two and three.
I tried what you said, but I’m not quite sure how it works.
def getSelection(): js = """ const sel = window.getSelection(); if (sel.rangeCount > 0) { const range = sel.getRangeAt(0); return { start: range.startOffset, end: range.endOffset }; } else { return null; } """ def callback(value): if value is not None: try: if isinstance(value, str): import json value = json.loads(value)
Untested, but this should return the offset. At this point I’m a bit insecure if the startOffset and endOffset is correct because I’m searching in a html-text. Also I don’t see a possibility to use these variables with pattern.search().
alts_format function does a similar thing to what you seem to be trying to achieve. It wraps a selection in an active field into a <div> with an .alt class, and can probably be adapted to style the selected text any other way you want.
I understand your approach of the alts_format function. Maybe this can work for me as well. I try it when I find the time. Unfortunately my JS knowledge isn’t that deep. Is there an possibility to log the JS approach, so that I can debug my results?