1
$\begingroup$

Further to my previous question (print number and index of selected lines in text editor), i'd like to know if it's possible to detect if characters are selected in text editor.

$\endgroup$

1 Answer 1

2
$\begingroup$

The selection spans from line current_line_index beginning at current_character to select_line ending at select_end_character.

If these coincide, there is no character selected.

So given you know the line and column of your character you can check yourself.

However current_character and select_end_character are byte offsets. Python uses unicode points. So unless you are using pure ASCII you need to convert the char position to byte offset.

See https://en.wikipedia.org/wiki/UTF-8

The conversion is a bit cumbersome. Something like

from itertools import islice

txt_line = "\u03A0\u2764\u2600\u2602This is a Test" 
col = 9
print(txt_line)

ubounds = [0x80, 0x800, 0x10000, 0x110000]
offset = 0

#char is actually an immutable newly created string...
for char in islice(txt_line, 0, col): 
    code_point = ord(char)
    for size, ub in enumerate(ubounds):
        if code_point < ub:
            offset += size + 1
            break

print(
    "byte at %d: %d - char: %d" % (
        offset,
        bytes(txt_line, 'utf-8')[offset],
        ord(txt_line[col])
    )
)
$\endgroup$
1
  • $\begingroup$ Thank you for these explanations, thanks to you I managed to make what I wished. Thank you very much. $\endgroup$
    – pistiwique
    Commented Jul 16, 2015 at 21:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .