Search code examples
pythonpython-3.xreadline

Python : correct use of set_completion_display_matches_hook


I'm trying to write a function to display a custom view when users press the tab button. Apparently "set_completion_display_matches_hook" function is what I need, I can display a custom view, but the problem is that I have to press Enter to get a prompt again.

The solution in Python2 seems to be that (solution here):

def match_display_hook(self, substitution, matches, longest_match_length):
    print ''
    for match in matches:
        print match
    print self.prompt.rstrip(),
    print readline.get_line_buffer(),
    readline.redisplay()

But it doesn't work with Python3. I made these syntax changes :

def match_display_hook(self, substitution, matches, longest_match_length):
        print('\n----------------------------------------------\n')
        for match in matches:
            print(match)
        print(self.prompt.rstrip() + readline.get_line_buffer())
        readline.redisplay()

Any ideas please ?


Solution

  • First, the Python 2 code uses commas to leave the line unfinished. In Python 3, it's done using end keyword:

    print(self.prompt.rstrip(), readline.get_line_buffer(), sep='', end='')
    

    Then, a flush is required to actually display the unfinished line (due to line buffering):

    sys.stdout.flush()
    

    The redisplay() call does not seem to be needed.

    The final code:

    def match_display_hook(self, substitution, matches, longest_match_length):
        print()
        for match in matches:
            print(match)
        print(self.prompt.rstrip(), readline.get_line_buffer(), sep='', end='')
        sys.stdout.flush()