Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make python autocompletion display matches?

I have kind of a completer class with an autocompletion function. Simple version:

class Completer:
    def __init__(self):
        self.words = ["mkdir","mktbl", "help"]
        self.prefix = None

    def complete(self, prefix, index):
        if prefix != self.prefix:
            self.matching_words = [w for w in self.words if w.startswith(prefix)]
            self.prefix = prefix
        else:
            pass                
        try:
            return self.matching_words[index]
        except IndexError:
            return None

And execute something like this to get auto-completion with readline:

import readline
readline.parse_and_bind("tab: complete")

completer = Completer()
readline.set_completer(completer.complete)
user_input =raw_input("> ")

So, there are 3 words for auto-completion ["help", "mkdir","mktbl"] in the example.

if a user executes:
> he<tab>
the user gets:
> help

but if the user executes
> mk<tab>
nothing is happening because there are not a single match (mkdir and mktbl)

How to display options in case there are several matches? Like the Bash do with a file names autocompletion?

Thus user whold get something like:
> mk<tab>
mktbl mkdir
> mk<cursor>


P.S. I have tried to put
_readline.insert_text(...)_
and
print ...
into completer function but it brakes the insertion, so a user gets something like this:
> mk<tab>
> mkmktbl mkdir <cursor>

P.P.S I need a linux solution.

like image 648
MajesticRa Avatar asked Feb 01 '11 23:02

MajesticRa


People also ask

How do you autofill in Python?

(In Python Shell window, you can use TAB key besides the key combination of 'CTRL' and 'space' to invoke the built-in auto-completion feature.) Alternatively, you can choose the "Show Completions" in the main Edit menu to achieve the same as well.

How do I turn on suggestions in Python?

Simply hit the “Tab” key while writing code. This will open a menu with suggestions. Hit “Enter” to choose the suggestion.

How do I get idle suggestions in Python?

As it says in the settings of IDLE, you can trigger the autocomplete with "Control + Space", e.g. after a "QtGui.". Then a menu opens where you can arrow-scroll through the entries.

How do I show suggestions in PyCharm?

Press Ctrl+Alt+S to open the IDE settings and select Editor | General | Code Completion. The suggestion list will look as follows with the icons marking reordered and the most relevant items.


1 Answers

Set the readline option

set show-all-if-ambiguous on

if you want completions after the first <tab>. Otherwise just hit <tab> twice.

Reference: http://caliban.org/bash/, Section readline Tips and Tricks

PS. Tested your code on OS X and Linux, it works well (on my machines ;)

like image 122
miku Avatar answered Sep 21 '22 15:09

miku