def get_completers(cls):
     commands = [
         c.get_completer()
         for c in {cmd
                   for k, cmd in cls._supported_commands.items() if k}
     ]
     return merge_completers(commands)
def main():
    completer = merge_completers([animal_completer, color_completer])

    text = prompt('Give some animals: ',
                  completer=completer,
                  complete_while_typing=False)
    print('You said: %s' % text)
Exemple #3
0
 def create_completer(deduplicate: bool):
     return merge_completers(
         [
             WordCompleter(["hello", "world", "abc", "def"]),
             WordCompleter(["xyz", "xyz", "abc", "def"]),
         ],
         deduplicate=deduplicate,
     )
Exemple #4
0
def prepare_completers(commands):
    completer_commands = WordCompleter(commands)
    repos = [str(r.parts[-1:][0]) for r in list_all_repos()]
    completer_repos = WordCompleter(repos)
    completer_files = PathCompleter(
        file_filter=lambda filename: str(filename).endswith('.csv'),
        min_input_len=0,
        get_paths=lambda: [current_path])
    return merge_completers(
        [completer_commands, completer_repos, completer_files])
Exemple #5
0
 def _maybe_complete_for_type(
     self,
     annotation: Any,
     document: Document,
     complete_event: CompleteEvent
 ) -> Iterable[Completion]:
     for _type, completers in self._app.type_completer_mapping.items():
         if is_matching_type(_type, annotation):
             yield from merge_completers(completers).get_completions(
                 document, complete_event
             )
Exemple #6
0
def getCommandCompleter() -> prompt_toolkit.completion.Completer:
    from prompt_toolkit.completion import WordCompleter, merge_completers
    cmdLists = list(builtinCmdLists)
    man = shared.getManager()
    if man:
        cmdLists += man.importedCommand.keys()
    else:
        cmdLists += defaultData.importedCommand
    wc = WordCompleter(cmdLists, ignore_case=True)
    pc = ui.PathCompleter()
    return merge_completers([wc, pc])
        def direct_completers() -> Completer:
            def allowed_arg(arg_info: ArgInfo) -> bool:
                group = arg_info.option_group
                return group is None or not any(a.arg.name in parts
                                                for a in self.args.values()
                                                if a.arg.option_group == group)

            d = [
                a.completer for a in self.direct if a.completer
                if allowed_arg(a.arg)
            ]
            return merge_completers(d)
Exemple #8
0
def main(script, debug, vi, multiline, record):
    """A gnuplot shell
    """

    logging.basicConfig(level=logging.WARNING)
    logger = logging.getLogger(__name__)
    if debug:
        logger.setLevel(logging.DEBUG)
        logger.debug("Enabled debug output")

    print('''
    If you press Control-x Control-e, the prompt will open in $EDITOR.
    Auto-suggestion accept pressing right arrow.
    Auto completion using TAB
    Exit by pressing Control-d
    ''')

    config_file = os.path.expanduser('~/.ignuplotrc.py')
    if os.path.exists(config_file):
        logger.debug('Executinb configuration file {0}'.format(config_file))
        with open(config_file) as fd:
            exec(fd.read())
    logger.debug('Using gnuplot binary in {0}'.format(
        ignuplot.config.GNUPLOT_BINARY))

    pathcompleter = PathCompleter(expanduser=True)
    completer = merge_completers([pathcompleter, gnuplot_keyword_completer])
    style = ignuplot.style.ignuplot_style

    repl = ignuplot.repl.Shell(vi_mode=vi,
                               multiline=multiline,
                               style=style,
                               completer=completer)

    if script is not None and os.path.exists(script):
        with open(script) as fd:
            text = fd.read()
            repl.lines = [text]
            repl.history.append_string(text)
            repl.digest()

    returncode = repl.run()
    if record:
        with open(script, 'a+') as fd:
            for line in repl.lines:
                fd.write('{0}\n'.format(line))

    return returncode
 def __init__(self,
              kinds: List[str],
              props: List[str],
              with_as: bool = True) -> None:
     super().__init__(kinds, props)
     self.comma_var_completer = FuzzyWordCompleter(
         [","],
         meta_dict=({
             ",": "define another variable"
         }),
     )
     self.props_completer = self.property_names_completer
     self.group_after_name = (merge_completers([
         self.as_completer, self.comma_var_completer
     ]) if with_as else self.comma_var_completer)
     self.after_group = self.comma_var_completer
Exemple #10
0
    def get_completions(self, document: Document,
                        complete_event: CompleteEvent) -> Iterable[Completion]:
        # Split document.
        text = document.text_before_cursor.lstrip()
        stripped_len = len(document.text_before_cursor) - len(text)

        # If there is a space, check for the first term, and use a
        # subcompleter.
        if " " in text:
            first_term = text.split()[0]
            command = self.description.get(first_term)

            # If we have a sub completer, use this for the completions.
            if command is not None:
                options = [k for k in command if k != "positional"]
                terms = text.split(" ")

                if len(terms) > 2:
                    prev_term = terms[-2]
                else:
                    prev_term = None

                if prev_term in options:
                    completer = command[prev_term]
                else:
                    positionals = command.get("positional", [])
                    completer = merge_completers(
                        [WordCompleter(options, ignore_case=False)] +
                        positionals)

                for c in completer.get_completions(document, complete_event):
                    yield c

        # No space in the input: behave exactly like `WordCompleter`.
        else:
            completer = WordCompleter(list(self.description.keys()),
                                      ignore_case=False)
            for c in completer.get_completions(document, complete_event):
                yield c
 def __init__(self, kinds: List[str], props: List[str]) -> None:
     super().__init__(kinds, props)
     self.aggregate_fns = ["sum(", "min(", "max(", "avg("]
     self.aggregate_fn_completer = FuzzyWordCompleter(
         self.aggregate_fns,
         meta_dict={
             "sum(": "sum over all occurrences",
             "min(": "use the smallest occurrence",
             "max(": "use the biggest occurrence",
             "avg(": "average over all occurrences",
         },
     )
     self.as_completer = FuzzyWordCompleter(["as"],
                                            meta_dict=({
                                                "as":
                                                "rename this result"
                                            }))
     self.colon_completer = FuzzyWordCompleter(
         [":"],
         meta_dict=({
             ":": "to define functions for this group"
         }),
     )
     self.comma_var_completer = FuzzyWordCompleter(
         [","],
         meta_dict=({
             ",": "define another group variable"
         }),
     )
     self.comma_fn_completer = FuzzyWordCompleter(
         [","],
         meta_dict=({
             ",": "define another group function"
         }),
     )
     self.props_completer = FuzzyWordCompleter(
         props + [
             "/ancestors.", "/reported.", "/desired.", "/metadata.",
             "/descendants."
         ],
         meta_dict=({
             "/reported.": "absolute path in reported section",
             "/desired.": "absolute path in desired section",
             "/metadata.": "absolute path in metadata section",
             "/ancestors.": "on ancestor properties",
             "/descendants.": "on descendant properties",
             **{p: "aggregate property"
                for p in self.props},
         }),
     )
     self.group_with_value_completer = merge_completers([
         HintCompleter("1", "Static value to count", "1"),
         self.props_completer
     ])
     self.group_after_name = merge_completers([
         self.as_completer, self.colon_completer, self.comma_var_completer
     ])
     self.fn_after_name = merge_completers(
         [self.as_completer, self.comma_fn_completer])
     self.after_group = merge_completers(
         [self.comma_var_completer, self.colon_completer])
     self.after_fn_completer = merge_completers(
         [self.as_completer, self.comma_fn_completer])
     self.hint_completer = HintCompleter(
         "Example",
         "aggregation example",
         "kind, volume_type as type: sum(volume_size) as volume_size",
     )
     self.with_hint_completer = merge_completers([
         self.hint_completer, self.props_completer,
         self.aggregate_fn_completer
     ])
     self.value_hint_completer = HintCompleter("<name>",
                                               "name of this result")
Exemple #12
0
                    # (We don't add them to the `completion`. Users can type it
                    # to trigger the autocompletion themselves.)
                    filename += '/'
                elif self.only_directories:
                    continue

                if not self.file_filter(full_name):
                    continue

                yield Completion(completion, 0, display=filename)
        except OSError:
            pass


pathcompleter = PathCompleter(expanduser=False)
completer = merge_completers([pathcompleter, wordcompleter])

style = style_from_pygments_cls(MyGpStyle)


def prompt_info(text):
    print_formatted_text(HTML('<green>{0}</green>').format(text))


def prompt_error(text):
    print_formatted_text(HTML('<red>{0}</red>').format(text))


def gnuplot(lines):
    import subprocess
    proc = subprocess.Popen(
Exemple #13
0
def main():
    global fire_obj
    last_command = []

    args = parse_args(sys.argv[1:])
    args_data = args.data

    if args.recipe:
        print(Chepy(*args_data).load_recipe(args.recipe).o)
    else:
        args_data.append("-")

        history_file = config.history_path
        session = PromptSession(
            history=FileHistory(history_file),
            style=get_style(),
            wrap_lines=True,
            auto_suggest=AutoSuggestFromHistory(),
        )
        try:
            while True:
                prompt = session.prompt(
                    prompt_message(fire_obj=fire_obj),
                    bottom_toolbar=bottom_toolbar(fire_obj),
                    completer=FuzzyCompleter(
                        merge_completers([CustomCompleter(), chepy_cli.CliCompleter()])
                    ),
                    validator=CustomValidator(),
                    rprompt=get_current_type(fire_obj),
                )

                # check and output any commands that start with cli_
                if re.match(r"^\!", prompt):
                    print(magenta(subprocess.getoutput(re.sub(r"^\!\s?", "", prompt))))
                # check if line is a comment
                elif re.match(r"^#", prompt):
                    print(cyan(prompt))
                # get help for a method
                elif re.match(r"^\?", prompt):
                    _method_name = re.match(r"^\?(\s?)+([\w_]+)", prompt).group(2)
                    chepy_cli.get_doc(_method_name)
                # check if method called is a cli method
                elif re.search(r"^cli_.+", prompt):
                    cli_method = prompt.split()[0]
                    cli_args = re.search(r"--(\w+)\s([\w\W]+)", prompt)
                    # Show errors encountered
                    if cli_method == "cli_show_errors":
                        getattr(chepy_cli, "cli_show_errors")(errors)
                    # show the current plugin path
                    elif cli_method == "cli_plugin_path":
                        getattr(chepy_cli, "cli_plugin_path")(config)
                    # Edit the current state
                    elif cli_method == "cli_edit_state":
                        try:
                            getattr(chepy_cli, "cli_edit_state")(fire_obj, args_data)
                            args_data = args_data[0 : args_data.index("-")] + ["-"]
                        except:
                            e_type, e_msg, e_traceback = sys.exc_info()
                            print(red(e_type.__name__), yellow("Could not edit state"))
                    # Go back one step
                    elif cli_method == "cli_go_back":
                        args_data = args_data[: -len(last_command + ["-"])]
                        print(cyan("Go back: {}".format(last_command)))
                    # Delete the cli history file
                    elif cli_method == "cli_delete_history":
                        Path(config.history_path).unlink()
                    elif cli_args:
                        getattr(chepy_cli, cli_method)(
                            fire_obj, **{cli_args.group(1): cli_args.group(2)}
                        )
                    else:
                        getattr(chepy_cli, cli_method)(fire_obj)

                else:
                    for method in chepy:
                        if not method.startswith("_") and not isinstance(
                            getattr(Chepy, method), property
                        ):
                            fire.decorators._SetMetadata(
                                getattr(Chepy, method),
                                fire.decorators.ACCEPTS_POSITIONAL_ARGS,
                                False,
                            )
                    args_data += prompt.split()
                    if args_data[-1] != "-":
                        args_data.append("-")
                    try:
                        last_command = prompt.split() + ["-"]
                        fire_obj = fire.Fire(Chepy, command=args_data)
                    # handle required args for methods
                    except fire.core.FireExit:
                        args_data = args_data[: -len(last_command)]
                    except TypeError as e:
                        print(red(e.message))
                    except SystemExit:
                        sys.exit()
                    except:
                        # go back to last working arg
                        e_type, e_msg, e_traceback = sys.exc_info()
                        print(red(e_type.__name__), yellow(e_msg.__str__()))
                        args_data = args_data[: -len(last_command)]
                        continue
        except KeyboardInterrupt:
            print(green("\nOKBye"))
            sys.exit()
Exemple #14
0
    "name": dict(history=InMemoryHistory()),
    "action_template_id": dict(history=InMemoryHistory(), completer=action_completer),
    "stop_on_error": dict(validator=v.Bool, converter=c.Bool, history=InMemoryHistory()),
    "stop_undo_on_error": dict(validator=v.Bool, converter=c.Bool, history=InMemoryHistory()),
    "undo_on_error": dict(validator=v.Bool, converter=c.Bool, history=InMemoryHistory()),
    "action_type": dict(validator=v.Choice([at.name for at in ActionType if at.name != 'NATIVE']),
                        history=InMemoryHistory()),
    "code": dict(edit=code_extension, history=InMemoryHistory(), converter=c.MultiLine),
    "expected_stdout": dict(multiline=True, mouse_support=True, history=InMemoryHistory(), converter=c.MultiLine),
    "expected_stderr": dict(multiline=True, mouse_support=True, history=InMemoryHistory(), converter=c.MultiLine),
    "expected_rc": dict(validator=v.Int(), converter=c.Int, history=InMemoryHistory()),
    "schema": dict(edit='.yaml', validator=v.JSON, history=InMemoryHistory(), converter=c.Yaml),
    "system_kwargs": dict(edit='.yaml', validator=v.JSON, history=InMemoryHistory(), converter=c.Yaml),
    "pre_process": dict(edit='.py', history=InMemoryHistory(), converter=c.MultiLine),
    "post_process": dict(edit='.py', history=InMemoryHistory(), converter=c.MultiLine),
    "target": dict(completer=merge_completers([granule_completer, server_name_completer]), history=InMemoryHistory()),
    "parent_step_ids": dict(validator=v.List(','), converter=c.List(','))
}

parser = ArgumentParserRaise(allow_abbrev=False, prog='')
subparser = parser.add_subparsers(dest='cmd')
preview_parser = subparser.add_parser('preview')
subpreview_parser = preview_parser.add_subparsers(dest='subcmd')
subpreview_parser.add_parser('action')
set_parser = subparser.add_parser('set')
set_parser.add_argument('parameter', help=', '.join(form.keys()))
delete_parser = subparser.add_parser('delete')
delete_parser.add_argument('parameter', help=', '.join(form.keys()))
save_parser = subparser.add_parser('save')
exit_parser = subparser.add_parser('exit')
def main():
    completer = merge_completers([animal_completer, color_completer])

    text = prompt('Give some animals: ', completer=completer,
                  complete_while_typing=False)
    print('You said: %s' % text)
Exemple #16
0
    def get_completions(self, document: Document,
                        complete_event: CompleteEvent) -> Iterable[Completion]:
        """ Get a list of completions for the given document """

        text = document.text_before_cursor.lstrip()
        try:
            args = shlex.split(text)
        except ValueError:
            try:
                args = shlex.split(text + '"')
            except ValueError:
                args = shlex.split(text + "'")

        # We haven't finished typing the command. Use our word completer for
        # commands
        if text == "" or (len(args) == 1 and not text.endswith(" ")):
            yield from self.completer.get_completions(document, complete_event)
            return

        # Not in a known command, can't autocomplete
        if args[0] not in self.layers:
            return

        command = self.layers[args[0]]
        args = args[1:]
        next_completer = command[0]
        this_completer = command[0]
        positional = 0
        # state = "options", completing options next
        # state = "arguments", completing arguments to options next
        state = "options"

        for arg in args:
            if state == "options":
                # Flag options
                if arg.startswith("-"):
                    # Exact match, with a sub-completer
                    if arg in command[2] and command[2][arg] is not None:
                        # Completer for next argument
                        next_completer = command[2][arg]
                        state = "arguments"
                    # Exact match, with no arguments
                    elif arg in command[2]:
                        # Command has no argument, next completer is options
                        # completer
                        next_completer = command[0]
                        state = "options"
                        this_completer = command[0]
                    # Non-exact match
                    else:
                        next_completer = command[0]
                        this_completer = command[0]
                        state = "options"
                # Appears to be a positional argument, grab next positional
                # completer and increment positional count
                else:
                    if positional < len(command[1]):
                        this_completer = command[1][positional]
                        next_completer = command[0]
                        state = "options"
                        positional += 1
                    else:
                        this_completer = command[0]
                        next_completer = command[0]
                        state = "options"
            else:
                # Completing an argument to a option/switch. We can't verify
                # it's legitimacy, so we assume it's right, and reset to a
                # default state.
                state = "options"
                this_completer = next_completer
                next_completer = command[0]

        # We are completing the first argument. This could be
        # any option argument or the first positional argument.
        # We need to merge them.
        if not args and text.endswith(" ") and command[1]:
            completer = command[1][0]
            if isinstance(completer, tuple) and completer[0] == "choices":
                completer = WordCompleter(completer[1], WORD=True)
            next_completer = merge_completers([next_completer, completer])

        if isinstance(this_completer,
                      tuple) and this_completer[0] == "choices":
            this_completer = WordCompleter(this_completer[1], WORD=True)
        if isinstance(next_completer,
                      tuple) and next_completer[0] == "choices":
            next_completer = WordCompleter(next_completer[1], WORD=True)

        if text.endswith(" ") and next_completer is not None:
            yield from next_completer.get_completions(document, complete_event)
        elif this_completer is not None:
            yield from this_completer.get_completions(document, complete_event)
Exemple #17
0
def main():
    global fire_obj
    last_command = []

    args = parse_args(sys.argv[1:])
    args_data = args.data

    args_data.append("-")

    history_file = config.history_path
    session = PromptSession(
        history=FileHistory(history_file),
        style=get_style(),
        wrap_lines=True,
        auto_suggest=AutoSuggestFromHistory(),
    )
    try:
        while True:
            prompt = session.prompt(
                prompt_message(fire_obj=fire_obj),
                bottom_toolbar=bottom_toolbar(fire_obj),
                completer=FuzzyCompleter(
                    merge_completers([CustomCompleter(), chepy_cli.CliCompleter()])
                ),
                validator=CustomValidator(),
                rprompt=get_current_type(fire_obj),
            )

            # check and output any commands that start with cli_
            if re.match(r"^\!", prompt):
                print(subprocess.getoutput(re.sub(r"^\!\s?", "", prompt)))
            elif re.search(r"^cli_.+", prompt):
                cli_method = prompt.split()[0]
                cli_args = re.search(r"--(\w+)\s(\w+)", prompt)
                if cli_method == "cli_show_errors":
                    getattr(chepy_cli, "cli_show_errors")(errors)
                elif cli_method == "cli_go_back":
                    args_data = args_data[: -len(last_command + ["-"])]
                    print(cyan("Go back: {}".format(last_command)))
                elif cli_method == "cli_delete_history":
                    Path(config.history_path).unlink()
                elif cli_args:
                    getattr(chepy_cli, cli_method)(
                        fire_obj, **{cli_args.group(1): cli_args.group(2)}
                    )
                else:
                    getattr(chepy_cli, cli_method)(fire_obj)

            else:
                for method in chepy:
                    if not method.startswith("_") and not isinstance(
                        getattr(Chepy, method), property
                    ):
                        fire.decorators._SetMetadata(
                            getattr(Chepy, method),
                            fire.decorators.ACCEPTS_POSITIONAL_ARGS,
                            False,
                        )
                args_data += prompt.split()
                if args_data[-1] != "-":
                    args_data.append("-")
                try:
                    last_command = prompt.split() + ["-"]
                    fire_obj = fire.Fire(Chepy, command=args_data)
                except:
                    # go back to last working arg
                    e_type, e_msg, e_traceback = sys.exc_info()
                    print(red(e_type.__name__), yellow(e_msg.__str__()))
                    args_data = args_data[: -len(last_command)]
                    continue
    except KeyboardInterrupt:
        print("OKBye")
        sys.exit()
Exemple #18
0
IfsqlCompleter = merge_completers([
    WordCompleter(
        [
            "select",
            "distinct",
            "all",
            "from",
            "collate",
            "asc",
            "desc",
            "order",
            "by",
            "limit",
            "offset",
            "where",
            "group",
            "having"
            "as",
            "not",
            "like",
            "glob",
            "regexp",
            "match",
            "escape",
            "isnull",
            "notnull",
            "not null",
            "not",
            "and",
            "or",
            "is",
            "in",
            "between",
            "case",
            "when",
            "then",
            "else",
            "end",
            "raise",
            "ignore",
            "rollback",
            "abort",
            "fail",
            "null",
        ],
        ignore_case=True,
    ),
    WordCompleter(database.fields(), ignore_case=True),
])
Exemple #19
0
    def __init__(self, verbose=False):
        try:
            if args.directory:
                os.chdir(args.directory)
        except:
            pass

        self.config = cfg.Config(verbose=verbose, colored=True)
        self.config.load()
        self.config.fallback = {
            "aliases": {},
            "colored": True,
            "prompt": "<base>┏━━(</base><user>${USER}</user> <base>at</base> <user>${DOMAIN}</user><base>)━[</base><path>${PATH}</path><base>]━[</base><style fg='${green-yellow}'>${REPO}</style><base>]━[</base><style fg='yellow'>${TIME}</style><base>]\n┗━</base><pointer>${ROOT}</pointer> ",
            "style": {
                # Default style
                "": "",

                # Specific style
                "base": "#1a8cff",
                "pointer": "#ff4500",
                "path": "aqua",
                "user": "******",

                # Completer
                "completion-menu.completion": "bg:#000000 #ffffff",
                "completion-menu.completion.current": "bg:#00aaaa #000000",
                "scrollbar.background": "bg:#88aaaa",
                "scrollbar.button": "bg:#222222"
            },
            "dialog_style": {
                "dialog": "bg:#88ff88",
                "dialog frame-label": "bg:#ffffff #000000",
                "dialog.body": "bg:#000000 #00ff00",
                "dialog shadow": "bg:#00aa00",
            }
        }
        self.config.colored = self.config["colored"]
        self.style = Style.from_dict(self.config["style"])
        self.dialog_style = Style.from_dict(self.config["dialog_style"])
        self.manager = manager
        self.file = None
        self.mode = None
        self.userInput = None

        if platform.system() == "Windows":
            self.histfile = os.environ["userprofile"] + \
                r"\.voidhistory"  # Rename this
        else:
            # Rename this ... alternative for linux or Unix based systems
            self.histfile = os.path.expanduser("~")+r"/.voidhistory"

        self.history = FileHistory(self.histfile)

        if not args.command:
            function_completer = NestedCompleter.from_nested_dict(
                dict.fromkeys(functions))
            pth_completer = path_completer.PathCompleter(expanduser=True)
            environ_completer = env_completer.EnvCompleter(
                file_filter=filter)
            merged_completers = merge_completers(
                [function_completer, pth_completer, environ_completer])
            self.completer = ThreadedCompleter(merged_completers)
        else:
            self.completer = None

        super().__init__(completer=self.completer,
                         complete_while_typing=False,
                         auto_suggest=AutoSuggestFromHistory(),
                         search_ignore_case=True,
                         refresh_interval=0,
                         color_depth=ColorDepth.TRUE_COLOR,
                         editing_mode=EditingMode.VI,
                         style=self.style,
                         history=self.history)
Exemple #20
0
    def __init__(
        self,
        get_globals: Optional[_GetNamespace] = None,
        get_locals: Optional[_GetNamespace] = None,
        history_filename: Optional[str] = None,
        vi_mode: bool = False,
        color_depth: Optional[ColorDepth] = None,
        # Input/output.
        input: Optional[Input] = None,
        output: Optional[Output] = None,
        # For internal use.
        extra_key_bindings: Optional[KeyBindings] = None,
        _completer: Optional[Completer] = None,
        _validator: Optional[Validator] = None,
        _lexer: Optional[Lexer] = None,
        _extra_buffer_processors=None,
        _extra_layout_body=None,
        _extra_toolbars=None,
        _input_buffer_height=None,
    ) -> None:

        self.get_globals: _GetNamespace = get_globals or (lambda: {})
        self.get_locals: _GetNamespace = get_locals or self.get_globals

        self.completer = _completer or PythonCompleter(
            self.get_globals,
            self.get_locals,
            lambda: self.enable_dictionary_completion,
        )

        self._completer = HidePrivateCompleter(
            # If fuzzy is enabled, first do fuzzy completion, but always add
            # the non-fuzzy completions, if somehow the fuzzy completer didn't
            # find them. (Due to the way the cursor position is moved in the
            # fuzzy completer, some completions will not always be found by the
            # fuzzy completer, but will be found with the normal completer.)
            merge_completers(
                [
                    ConditionalCompleter(
                        FuzzyCompleter(
                            DynamicCompleter(lambda: self.completer)),
                        Condition(lambda: self.enable_fuzzy_completion),
                    ),
                    DynamicCompleter(lambda: self.completer),
                ],
                deduplicate=True,
            ),
            lambda: self.complete_private_attributes,
        )
        self._validator = _validator or PythonValidator(
            self.get_compiler_flags)
        self._lexer = PtpythonLexer(_lexer)

        self.history: History
        if history_filename:
            self.history = ThreadedHistory(FileHistory(history_filename))
        else:
            self.history = InMemoryHistory()

        self._input_buffer_height = _input_buffer_height
        self._extra_layout_body = _extra_layout_body or []
        self._extra_toolbars = _extra_toolbars or []
        self._extra_buffer_processors = _extra_buffer_processors or []

        self.extra_key_bindings = extra_key_bindings or KeyBindings()

        # Settings.
        self.title: AnyFormattedText = ""
        self.show_signature: bool = False
        self.show_docstring: bool = False
        self.show_meta_enter_message: bool = True
        self.completion_visualisation: CompletionVisualisation = (
            CompletionVisualisation.MULTI_COLUMN)
        self.completion_menu_scroll_offset: int = 1

        self.show_line_numbers: bool = False
        self.show_status_bar: bool = True
        self.wrap_lines: bool = True
        self.complete_while_typing: bool = True
        self.paste_mode: bool = (
            False  # When True, don't insert whitespace after newline.
        )
        self.confirm_exit: bool = (
            True  # Ask for confirmation when Control-D is pressed.
        )
        self.accept_input_on_enter: int = 2  # Accept when pressing Enter 'n' times.
        # 'None' means that meta-enter is always required.
        self.enable_open_in_editor: bool = True
        self.enable_system_bindings: bool = True
        self.enable_input_validation: bool = True
        self.enable_auto_suggest: bool = False
        self.enable_mouse_support: bool = False
        self.enable_history_search: bool = False  # When True, like readline, going
        # back in history will filter the
        # history on the records starting
        # with the current input.

        self.enable_syntax_highlighting: bool = True
        self.enable_fuzzy_completion: bool = False
        self.enable_dictionary_completion: bool = False  # Also eval-based completion.
        self.complete_private_attributes: CompletePrivateAttributes = (
            CompletePrivateAttributes.ALWAYS)
        self.swap_light_and_dark: bool = False
        self.highlight_matching_parenthesis: bool = False
        self.show_sidebar: bool = False  # Currently show the sidebar.

        # Pager.
        self.enable_output_formatting: bool = False
        self.enable_pager: bool = False
        self.show_locals: bool = True

        # When the sidebar is visible, also show the help text.
        self.show_sidebar_help: bool = True

        # Currently show 'Do you really want to exit?'
        self.show_exit_confirmation: bool = False

        # The title to be displayed in the terminal. (None or string.)
        self.terminal_title: Optional[str] = None

        self.exit_message: str = "Do you really want to exit?"
        self.insert_blank_line_after_output: bool = True  # (For the REPL.)
        self.insert_blank_line_after_input: bool = False  # (For the REPL.)

        # The buffers.
        self.default_buffer = self._create_buffer()
        self.search_buffer: Buffer = Buffer()
        self.docstring_buffer: Buffer = Buffer(read_only=True)

        # Tokens to be shown at the prompt.
        self.prompt_style: str = "classic"  # The currently active style.

        # Styles selectable from the menu.
        self.all_prompt_styles: Dict[str, PromptStyle] = {
            "ipython": IPythonPrompt(self),
            "classic": ClassicPrompt(),
        }

        self.get_input_prompt = lambda: self.all_prompt_styles[
            self.prompt_style].in_prompt()

        self.get_output_prompt = lambda: self.all_prompt_styles[
            self.prompt_style].out_prompt()

        #: Load styles.
        self.code_styles: Dict[str, BaseStyle] = get_all_code_styles()
        self.ui_styles = get_all_ui_styles()
        self._current_code_style_name: str = "default"
        self._current_ui_style_name: str = "default"

        if is_windows():
            self._current_code_style_name = "win32"

        self._current_style = self._generate_style()
        self.color_depth: ColorDepth = color_depth or ColorDepth.default()

        self.max_brightness: float = 1.0
        self.min_brightness: float = 0.0

        # Options to be configurable from the sidebar.
        self.options = self._create_options()
        self.selected_option_index: int = 0

        #: Incremeting integer counting the current statement.
        self.current_statement_index: int = 1

        # Code signatures. (This is set asynchronously after a timeout.)
        self.signatures: List[Signature] = []

        # Boolean indicating whether we have a signatures thread running.
        # (Never run more than one at the same time.)
        self._get_signatures_thread_running: bool = False

        # Get into Vi navigation mode at startup
        self.vi_start_in_navigation_mode: bool = False

        # Preserve last used Vi input mode between main loop iterations
        self.vi_keep_last_used_mode: bool = False

        self.style_transformation = merge_style_transformations([
            ConditionalStyleTransformation(
                SwapLightAndDarkStyleTransformation(),
                filter=Condition(lambda: self.swap_light_and_dark),
            ),
            AdjustBrightnessStyleTransformation(lambda: self.min_brightness,
                                                lambda: self.max_brightness),
        ])
        self.ptpython_layout = PtPythonLayout(
            self,
            lexer=DynamicLexer(lambda: self._lexer if self.
                               enable_syntax_highlighting else SimpleLexer()),
            input_buffer_height=self._input_buffer_height,
            extra_buffer_processors=self._extra_buffer_processors,
            extra_body=self._extra_layout_body,
            extra_toolbars=self._extra_toolbars,
        )

        self.app = self._create_application(input, output)

        if vi_mode:
            self.app.editing_mode = EditingMode.VI
Exemple #21
0
              action_list
              ],
     'create': [{'argument': 'name'},
                {'argument': 'action_type', 'choices': [at.name for at in ActionType if at.name != 'NATIVE']},
                {'argument': '--prompt', 'action': "store_true",
                 'help': 'prompts for every action parameter to be set by user'},
                action_create],
     'copy': [{'argument': 'action_template_id', 'completer': action_completer},
              action_copy],
     'load': [{'argument': 'file', 'type': argparse.FileType('r')},
              action_load],
 },
 'cmd': [{'argument': 'command', 'nargs': '*'},
         {'argument': '--shell', 'action': 'store_true'},
         {'argument': '--target', 'action': ExtendAction, 'nargs': "+",
          'completer': merge_completers([server_completer, granule_completer])},
         {'argument': '--timeout', 'type': int, 'help': 'timeout in seconds to wait for command to terminate'},
         {'argument': '--input'},
         cmd],
 "env": {
     "list": [env_list],
     "get": [{'argument': 'key', 'completer': DshellWordCompleter(environ._environ.keys())},
             env_get],
     "set": [{'argument': 'key', 'completer': DshellWordCompleter(environ._environ.keys())},
             {'argument': 'value', 'nargs': '*'},
             env_set]},
 'exec': {
     'list': [{'argument': '--orch', 'completer': orch_completer},
              {'argument': '--id', 'dest': 'execution_id'},
              {'argument': '--server', 'completer': server_completer},
              {'argument': '--last', 'metavar': 'N', 'type': int, 'help': "shows last N orchestrations"},
Exemple #22
0
        cfg["packet"].dest, cfg["packet"].dport,
    )
    return text

cmd_completer = WordCompleter([
    'load-dir', 'load-iptables', 'load-ipaddrs', 'load-iproutes', 'load-ipsets',
    'set-source', 'set-dest', 'set-sport', 'set-dport',
    'run-incomming-packet', 'run-localgen-packet', 'exit',
], ignore_case=True)

session = PromptSession()

if __name__ == '__main__':
    init(autoreset=True)
    while True:
        input = session.prompt('> ', bottom_toolbar=bottom_statusbar, completer=merge_completers([PathCompleter(min_input_len=1), cmd_completer]))
        if not input.split():
            continue
        if input.split()[0] == "exit":
            break
        if input.split()[0] == "load-localhost":
            print("not implemented")
            continue
        if input.split()[0] == "load-dir":
            try:
                cfg["iptables"] = ParseIPTables(input.split()[1] + r"/iptables.txt")
                cfg["ipaddrs"], cfg["non_local_ip"] = ParseIPAddrs(input.split()[1] + r"/ipaddrs.txt")
                cfg["iproutes"] = ParseIPRoutes(input.split()[1] + r"/iproutes.txt")
                cfg["ipsets"] = ParseIPSets(input.split()[1] + r"/ipsets.txt")
            except Exception as e:
                print("load config failed. " + str(e))
Exemple #23
0
def make_completer(engine, config):
    return merge_completers([
        WordCompleter(magic.command_list(config), WORD=True),
        GhciCompleter(engine),
        WordCompleter(keywords)])