1

I have a custom python readline completer function, in the completer function I call readline.get_line_buffer() which gives me the current text input so that I can complete the current word in a context-sensitive way.

What I am missing now is the possibility to get the current cursor position. For example, the position is required to determine the preceding command if possible arguments are to be completed.

In the python readline module documentation, I haven't found a way to determine the position, so how is it done?

Binabik
  • 1,013
  • 11
  • 24
  • I have the same question. I'm using pyreadline on Windows and didn't see anything simple in rlmain.py in the pyreadline source code. I wonder if before = readline.get_line_buffer(), readline.insert_text("t"), after = readline.get_line_buffer(), readline.insert_text("\b") would work. Then you could diff before and after to see where they first differ. Depends on if the backspace ("\b") works. – Samuel Dec 31 '20 at 00:45
  • Another idea is to use the text variable in the tab_complete hook. I tested and you can get your current position in the line buffer, as long as the cursor's at the end of a word and not preceded by whitespace, and there isn't any duplicate text on the line :|. – Samuel Dec 31 '20 at 17:37

1 Answers1

-1

I downloaded the pyreadline source code and figured this out. The following works in pyreadline (Windows port of readline) on Python 2.7:

from pyreadline import Readline
readline = Readline()
cursor = readline.mode.l_buffer.point

Note that this works in pyreadline (Windows), but not in GNU readline (per Binabik's comment below).

Samuel
  • 8,063
  • 8
  • 45
  • 41
  • 2
    I am on GNU/Linux with Python 3.9 where I am importing 'readline' instead of 'pyreadline' like you do. The 'readline' module does not offer the 'mode' attribute so just copying your code fails with the following exception: module 'readline' has no attribute 'mode' – Binabik May 14 '21 at 07:57