import readline


def create_list_completer(compl_list):
    """
    from: https://gist.github.com/iamatypeofwalrus/5637895
    This is a closure that creates a method that autocompletes from
    the given list.

    Since the autocomplete function can't be given a list to complete from
    a closure is used to create the listCompleter function with a list to complete
    from.
    """
    def list_completer(text, state):
        """
        from set_completer doc:
        The completer function is called as function(text, state), for state in
        0, 1, 2, …, until it returns a non-string value. It should return the
        next possible completion starting with text.
        """
        line = readline.get_line_buffer()

        if not line:
            return [item + " " for item in compl_list][state]

        else:
            return [item + " " for item in compl_list if item.startswith(line)][state]

    return list_completer