Ejemplo n.º 1
0
    def create_application(self):

        # Default key bindings.
        open_in_editor_bindings = load_open_in_editor_bindings()
        prompt_bindings = create_prompt_bindings()

        self.app = Application(
            layout=self.create_layout(),
            style=merge_styles([
                default_style(),
                DynamicStyle(lambda: self.style),
            ]),
            key_bindings=merge_key_bindings([
                merge_key_bindings([
                    ConditionalKeyBindings(
                        open_in_editor_bindings,
                        to_filter(self.enable_open_in_editor)
                        & has_focus(DEFAULT_BUFFER)), prompt_bindings
                ]),
                DynamicKeyBindings(lambda: self.extra_key_bindings),
            ]),
            editing_mode=self.editing_mode,
            reverse_vi_search_direction=True,
            on_render=self.on_render,
            input=self.input,
            output=self.output)

        self.app.mp = self
Ejemplo n.º 2
0
    def __init__(self,
                 source_field,
                 source_type: "Type",
                 target_type: "Type" = None):
        self.source_field = source_field
        self.source_type = source_type
        self.target_type = target_type
        # common part of every preview
        self.samples = source_field.get_samples(supposed_type=source_type,
                                                target_type=target_type)

        # define key self.bindings
        self.session = self.reset_session()
        self.bindings = KeyBindings()

        # cancel on control-c (escape inaccessible, waits for another keystroke)
        @self.bindings.add('c-c')
        def _(_):
            get_app().exit("")

        # exit on control+d (because the default exit command alt-enter seems unintuitive) (control+enter unacessible)
        @self.bindings.add('c-d')
        def _(_):
            get_app().exit(self.session.layout.current_buffer.text)

        # define styling
        self.style = merge_styles([reg_style, bottom_plain_style])

        # Init variables that may be used in methods
        self.get_toolbar_row = self.search = self.replace = self.phase = self.chosen_type = None
Ejemplo n.º 3
0
 def print_color(self, string, end="\n", **kwargs):
     """Prints a color string using prompt-toolkit color management."""
     if isinstance(string, str):
         tokens = partial_color_tokenize(string)
     else:
         # assume this is a list of (Token, str) tuples and just print
         tokens = string
     tokens = PygmentsTokens(tokens)
     env = XSH.env
     style_overrides_env = env.get("XONSH_STYLE_OVERRIDES", {})
     if HAS_PYGMENTS:
         self.styler.style_name = env.get("XONSH_COLOR_STYLE")
         self.styler.override(style_overrides_env)
         proxy_style = _style_from_pygments_cls(
             pyghooks.xonsh_style_proxy(self.styler))
     else:
         proxy_style = merge_styles([
             _style_from_pygments_dict(DEFAULT_STYLE_DICT),
             _style_from_pygments_dict(style_overrides_env),
         ])
     ptk_print(
         tokens,
         style=proxy_style,
         end=end,
         include_default_pygments_style=False,
         **kwargs,
     )
Ejemplo n.º 4
0
    def style_factory(self, style_name):
        """Retrieve the specified pygments style.

        If the specified style is not found, the vim style is returned.

        :type style_name: str
        :param style_name: The pygments style name.

        :rtype: :class:`pygments.style.StyleMeta`
        :return: Pygments style info.
        """
        # try:
        #     style = get_style_by_name(style_name)
        # except ClassNotFound:
        #     style = get_style_by_name('vim')
        #
        # # Create a style dictionary.
        # styles = {}
        # styles.update(style.styles)
        # styles.update(default_style_extensions)
        # t = Token
        # styles.update({
        #     t.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
        #     t.Menu.Completions.Completion: 'bg:#008888 #ffffff',
        #     t.Menu.Completions.Meta.Current: 'bg:#00aaaa #000000',
        #     t.Menu.Completions.Meta: 'bg:#00aaaa #ffffff',
        #     t.Scrollbar.Button: 'bg:#003333',
        #     t.Scrollbar: 'bg:#00aaaa',
        #     t.Toolbar: 'bg:#222222 #cccccc',
        #     t.Toolbar.Off: 'bg:#222222 #696969',
        #     t.Toolbar.On: 'bg:#222222 #ffffff',
        #     t.Toolbar.Search: 'noinherit bold',
        #     t.Toolbar.Search.Text: 'nobold',
        #     t.Toolbar.System: 'noinherit bold',
        #     t.Toolbar.Arg: 'noinherit bold',
        #     t.Toolbar.Arg.Text: 'nobold'
        # })

        #return style_from_dict(styles)
        return merge_styles([
            style_from_pygments_cls(DefaultStyle),
            Style.from_dict({
                # User input (default text).
                # '': '#ff0066',

                # Prompt.
                # 'username': '******',
                # 'at': '#00aa00',
                # 'colon': '#0000aa',
                # 'pound': '#00aa00',
                # 'host': '#00ffff bg:#444400',
                # 'path': 'ansicyan underline',
                # 'prompt': '#0000aa bold',
                # 'state': '#00aa00 bold',
                # 'danger': '#aa0000 bold',
                'prompt': 'fg:ansiblue bold',
                'state': 'fg:ansigreen bold',
                'danger': 'fg:ansired bold'
            }),
        ])
Ejemplo n.º 5
0
def style_factory(name, cli_style):
    try:
        style = pygments.styles.get_style_by_name(name)
    except ClassNotFound:
        style = pygments.styles.get_style_by_name("native")

    prompt_styles = []
    # prompt-toolkit used pygments tokens for styling before, switched to style
    # names in 2.0. Convert old token types to new style names, for backwards compatibility.
    for token in cli_style:
        if token.startswith("Token."):
            # treat as pygments token (1.0)
            token_type, style_value = parse_pygments_style(
                token, style, cli_style)
            if token_type in TOKEN_TO_PROMPT_STYLE:
                prompt_style = TOKEN_TO_PROMPT_STYLE[token_type]
                prompt_styles.append((prompt_style, style_value))
            else:
                # we don't want to support tokens anymore
                logger.error("Unhandled style / class name: %s", token)
        else:
            # treat as prompt style name (2.0). See default style names here:
            # https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/styles/defaults.py
            prompt_styles.append((token, cli_style[token]))

    override_style = Style([("bottom-toolbar", "noreverse")])
    return merge_styles(
        [style_from_pygments_cls(style), override_style,
         Style(prompt_styles)])
Ejemplo n.º 6
0
def style_factory(name, cli_style):
    try:
        style = pygments.styles.get_style_by_name(name)
    except ClassNotFound:
        style = pygments.styles.get_style_by_name('native')

    prompt_styles = []
    # prompt-toolkit used pygments tokens for styling before, switched to style
    # names in 2.0. Convert old token types to new style names, for backwards compatibility.
    for token in cli_style:
        if token.startswith('Token.'):
            # treat as pygments token (1.0)
            token_type, style_value = parse_pygments_style(
                token, style, cli_style)
            if token_type in TOKEN_TO_PROMPT_STYLE:
                prompt_style = TOKEN_TO_PROMPT_STYLE[token_type]
                prompt_styles.append((prompt_style, style_value))
            else:
                # we don't want to support tokens anymore
                logger.error('Unhandled style / class name: %s', token)
        else:
            # treat as prompt style name (2.0). See default style names here:
            # https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/styles/defaults.py
            prompt_styles.append((token, cli_style[token]))

    override_style = Style([('bottom-toolbar', 'noreverse')])
    return merge_styles([
        style_from_pygments_cls(style),
        override_style,
        Style(prompt_styles)
    ])
Ejemplo n.º 7
0
        def xstyle():
            elem = [ 
                    ('completion-menu.completion.current', 'bg:#ffffff #000000'),
                    ('completion-menu.completion', 'bg:#008888 #ffffff'),
                    ('completion-menu.meta.completion.current', 'bg:#44aaaa #000000'),
                    ('completion-menu.meta.completion', 'bg:#448888 #ffffff'),
                    ('completion-menu.multi-column-meta', 'bg:#aaffff #000000'),
                    ('scrollbar.arrow', 'bg:#003333'),
                    ('scrollbar', 'bg:#00aaaa'),
                    ('selected', '#ffffff bg:#6666aa'),
                    ('search', '#ffffff bg:#4444aa'),
                    ('output.header', '#00ff5f bold'),
                    ('output.odd-row', ''),
                    ('output.even-row', ''),
                    ('output.null', '#808080'),
                    ('search.current', '#ffffff bg:#44aa44'),
                    ('bottom-toolbar', 'bg:#222222 #aaaaaa'),
                    ('bottom-toolbar.off', 'bg:#222222 #888888'),
                    ('bottom-toolbar.on', 'bg:#222222 #ffffff'),
                    ('bottom-toolbar.transaction.valid', 'bg:#222222 #00ff5f bold'),
                    ('bottom-toolbar.transaction.failed', 'bg:#222222 #ff005f bold'),
                    ('search-toolbar', 'noinherit bold'),
                    ('search-toolbar.text', 'nobold'),
                    ('system-toolbar', 'noinherit bold'),
                    ('arg-toolbar', 'noinherit bold')]

            style = pygments.styles.get_style_by_name('default')
            override_style = Style([('bottom-toolbar', 'noreverse')])
            
            return merge_styles([style_from_pygments_cls(style),
                              override_style,
                              Style(elem)])
Ejemplo n.º 8
0
 def style(self):
     return merge_styles(
         [
             Style(BaseCommitizen.default_style_config),
             Style(self.config.settings["style"]),
         ]
     )
Ejemplo n.º 9
0
    def setup_prompt(self):
        """This needs to happen after __init__ when the database is fully
        initialized."""

        history = DatabaseHistory(self.manager)
        completer = CommandCompleter(self.manager, self.commands)
        lexer = PygmentsLexer(CommandLexer.build(self.commands))
        style = style_from_pygments_cls(get_style_by_name("monokai"))
        auto_suggest = AutoSuggestFromHistory()
        bindings = KeyBindings()

        @bindings.add("c-q")
        def _(event):
            """Exit interactive mode"""

            get_app().exit(exception=pwncat.manager.InteractiveExit())

        self.prompt = PromptSession(
            [
                ("fg:ansiyellow bold", "(local) "),
                ("fg:ansimagenta bold", "pwncat"),
                ("", "$ "),
            ],
            completer=completer,
            lexer=lexer,
            style=merge_styles([
                style,
                Style.from_dict({"bottom-toolbar": "#333333 bg:#ffffff"})
            ]),
            auto_suggest=auto_suggest,
            complete_while_typing=False,
            history=history,
            bottom_toolbar=self._render_toolbar,
            key_bindings=bindings,
        )
Ejemplo n.º 10
0
 def initialize_pygments(self):
     prompt_style = {'prompt': "#85678f", 'extras': "#b294bb bold"}
     merged_style = merge_styles(
         [
             style_from_pygments_cls(get_style_by_name("monokai")),
             Style.from_dict(prompt_style),
         ]
     )
     self.style = merged_style
Ejemplo n.º 11
0
def generate_style(python_style, ui_style):
    """
    Generate Pygments Style class from two dictionaries
    containing style rules.
    """
    return merge_styles([
        python_style,
        ui_style
    ])
Ejemplo n.º 12
0
    def to_style(self):
        styles = []
        for component in self.rules:
            styles.extend(component.to_style())

        if self.dialog_style:
            styles.extend(self.dialog_style.to_style())

        return merge_styles([default_ui_style(), Style(styles)])
Ejemplo n.º 13
0
    def __init__(self, uri=None, **settings):
        self.output_file = settings.pop("file", None)
        verbose = settings.pop("verbose", False)
        connection_data = get_connection_data(uri, **settings)
        try:
            self.graph = Graph(uri, **settings)
        except ServiceUnavailable as error:
            raise ConsoleError("Could not connect to {} -- {}".format(
                connection_data["uri"], error))
        try:
            makedirs(HISTORY_FILE_DIR)
        except OSError:
            pass
        self.history = FileHistory(path_join(HISTORY_FILE_DIR, HISTORY_FILE))
        self.prompt_args = {
            "history":
            self.history,
            "lexer":
            PygmentsLexer(CypherLexer),
            "style":
            merge_styles([
                style_from_pygments_cls(NativeStyle),
                style_from_pygments_dict({
                    Token.Prompt:
                    "#ansi{}".format(self.prompt_colour.replace(
                        "cyan", "teal")),
                    Token.TxCounter:
                    "#ansi{} bold".format(
                        self.tx_colour.replace("cyan", "teal")),
                })
            ])
        }
        self.lexer = CypherLexer()
        self.result_writer = Table.write
        if verbose:
            from neobolt.diagnostics import watch
            self.watcher = watch("neo4j.%s" % connection_data["scheme"])

        self.commands = {
            "//": self.set_multi_line,
            "/e": self.edit,
            "/?": self.help,
            "/h": self.help,
            "/help": self.help,
            "/x": self.exit,
            "/exit": self.exit,
            "/play": self.play,
            "/csv": self.set_csv_result_writer,
            "/table": self.set_tabular_result_writer,
            "/tsv": self.set_tsv_result_writer,
            "/config": self.config,
            "/kernel": self.kernel,
        }
        self.tx = None
        self.tx_counter = 0
Ejemplo n.º 14
0
def _create_merged_style(style: Optional[BaseStyle],
                         include_default_pygments_style: bool) -> BaseStyle:
    """
    Merge user defined style with built-in style.
    """
    styles = [default_ui_style()]
    if include_default_pygments_style:
        styles.append(default_pygments_style())
    if style:
        styles.append(style)

    return merge_styles(styles)
Ejemplo n.º 15
0
    def get_prompt_style(self):
        env = XSH.env

        style_overrides_env = env.get("PTK_STYLE_OVERRIDES", {}).copy()
        if (
            len(style_overrides_env) > 0
            and not self._overrides_deprecation_warning_shown
        ):
            print_warning(
                "$PTK_STYLE_OVERRIDES is deprecated, use $XONSH_STYLE_OVERRIDES instead!"
            )
            self._overrides_deprecation_warning_shown = True
        style_overrides_env.update(env.get("XONSH_STYLE_OVERRIDES", {}))

        if HAS_PYGMENTS:
            style = _style_from_pygments_cls(pyghooks.xonsh_style_proxy(self.styler))
            if len(self.styler.non_pygments_rules) > 0:
                try:
                    style = merge_styles(
                        [
                            style,
                            _style_from_pygments_dict(self.styler.non_pygments_rules),
                        ]
                    )
                except (AttributeError, TypeError, ValueError) as style_exception:
                    print_warning(
                        f"Error applying style override!\n{style_exception}\n"
                    )

        else:
            style = _style_from_pygments_dict(DEFAULT_STYLE_DICT)

        if len(style_overrides_env) > 0:
            try:
                style = merge_styles(
                    [style, _style_from_pygments_dict(style_overrides_env)]
                )
            except (AttributeError, TypeError, ValueError) as style_exception:
                print_warning(f"Error applying style override!\n{style_exception}\n")
        return style
Ejemplo n.º 16
0
def text(message: Text,
         default: Text = "",
         validate: Union[Type[Validator],
                         Callable[[Text], bool],
                         None] = None,  # noqa
         qmark: Text = DEFAULT_QUESTION_PREFIX,
         style: Optional[Style] = None,
         **kwargs: Any) -> Question:
    """Prompt the user to enter a free text message.

       This question type can be used to prompt the user for some text input.

       Args:
           message: Question text

           default: Default value will be returned if the user just hits
                    enter.

           validate: Require the entered value to pass a validation. The
                     value can not be submited until the validator accepts
                     it (e.g. to check minimum password length).

                     This can either be a function accepting the input and
                     returning a boolean, or an class reference to a
                     subclass of the prompt toolkit Validator class.

           qmark: Question prefix displayed in front of the question.
                  By default this is a `?`

           style: A custom color and style for the question parts. You can
                  configure colors as well as font types for different elements.

       Returns:
           Question: Question instance, ready to be prompted (using `.ask()`).
    """

    merged_style = merge_styles([DEFAULT_STYLE, style])

    validator = build_validator(validate)

    def get_prompt_tokens():
        return [("class:qmark", qmark),
                ("class:question", ' {} '.format(message))]

    p = PromptSession(get_prompt_tokens,
                      style=merged_style,
                      validator=validator,
                      **kwargs)
    p.default_buffer.reset(Document(default))

    return Question(p.app)
Ejemplo n.º 17
0
def get_editor_style_by_name(name):
    """
    Get Style class.
    This raises `pygments.util.ClassNotFound` when there is no style with this
    name.
    """
    if name == 'vim':
        vim_style = Style.from_dict(default_vim_style)
    else:
        vim_style = style_from_pygments_cls(get_style_by_name(name))

    return merge_styles([
        vim_style,
        Style.from_dict(style_extensions),
    ])
Ejemplo n.º 18
0
def style_factory(name, cli_style):
    try:
        style = pygments.styles.get_style_by_name(name)
    except ClassNotFound:
        style = pygments.styles.get_style_by_name("native")

    prompt_styles = []

    for token in cli_style:
        # treat as prompt style name (2.0). See default style names here:
        # https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/styles/defaults.py
        prompt_styles.append((token, cli_style[token]))

    override_style = Style([("bottom-toolbar", "noreverse")])
    return merge_styles([style_from_pygments_cls(style), override_style, Style(prompt_styles)])
Ejemplo n.º 19
0
Archivo: cmd.py Proyecto: Nykakin/ifsql
    def __init__(self, root):
        self._database = database.Database()
        self._parser = parser.Parser()
        self._path_id_cache = {}
        self._last_error = ""

        self.prompt_session = PromptSession(
            lexer=PygmentsLexer(IfsqlLexer),
            completer=IfsqlCompleter,
            style=merge_styles(
                [CompletionMenuStyle,
                 style_from_pygments_cls(SQLSyntaxStyle)]),
        )

        analyse.walk(root, self._database, self._path_id_cache)
Ejemplo n.º 20
0
    def __init__(self,
                 config,
                 engine,
                 PtPromptSession,
                 pt_print=print_formatted_text):
        self.config = config
        self.engine = engine
        self.pt_print = pt_print
        bindings = self.setup_key_bindings()
        lexer = PygmentsLexer(PtgHaskellLexer)
        history = ThreadedHistory(
            FileHistory(os.path.expanduser(config.history_path)))
        pg_style = style_from_pygments_cls(get_style_by_name(config.style))
        bottom_toolbar_style = Style.from_dict({
            'bottom-toolbar':
            config.type_bar_style,
            'bottom-toolbar.text':
            config.type_bar_text_style
        })
        style = merge_styles([pg_style, bottom_toolbar_style])

        self._psession = PtPromptSession(
            ":",
            lexer=lexer,
            vi_mode=config.vi_mode,
            multiline=True,
            # enable_open_in_editor=True, # Handle this manually
            key_bindings=bindings,
            history=history,
            tempfile_suffix=".hs",
            style=style,
            complete_while_typing=False,
            completer=completer.make_completer(engine, config),
            enable_suspend=True,
            prompt_continuation=default_continuation,
            bottom_toolbar=self.bottom_toolbar
            if config.type_bar_enabled else None)
        self._psession.message = self.in_prompt_message

        if config.vi_mode:
            vimcursor.setup_vim_cursor()

        self._cur_lineno = 1  #len(self._psession.history.get_strings())+1

        self.threadpool = ThreadPool(processes=1)
        self.bottom_text = None
        self.last_cursor_word = None
Ejemplo n.º 21
0
    def read(self):
        prompt_args = {
            "history":
            self.history,
            "lexer":
            PygmentsLexer(CypherLexer),
            "style":
            merge_styles([
                style_from_pygments_cls(NativeStyle),
                style_from_pygments_dict({
                    Token.Prompt.User: "******",
                    Token.Prompt.At: "#ansigreen",
                    Token.Prompt.Host: "#ansigreen",
                    Token.Prompt.Slash: "#ansigreen",
                    Token.Prompt.Graph: "#ansiblue",
                    Token.Prompt.QID: "#ansiyellow",
                    Token.Prompt.Arrow: "#808080",
                })
            ])
        }

        if self.multi_line:
            self.multi_line = False
            return prompt(u"", multiline=True, **prompt_args)

        def get_prompt_tokens():
            graph_name = "~" if self.graph_name is None else self.graph_name
            tokens = [
                ("class:pygments.prompt.user", self.profile.user),
                ("class:pygments.prompt.at", "@"),
                ("class:pygments.prompt.host", self.profile.host),
                ("class:pygments.prompt.slash", "/"),
                ("class:pygments.prompt.graph", graph_name),
            ]
            if self.tx is None:
                tokens.append(("class:pygments.prompt.arrow", " -> "))
            else:
                tokens.append(("class:pygments.prompt.arrow", " "))
                tokens.append(("class:pygments.prompt.qid", str(self.qid)))
                tokens.append(("class:pygments.prompt.arrow", "> "))
            return tokens

        return prompt(get_prompt_tokens, **prompt_args)
Ejemplo n.º 22
0
    def setup_prompt(self):
        self.style = merge_styles([
            style_from_pygments_cls(RainbowDashStyle),

            Style.from_dict({
                'username': '******',
                'punctuation': '#090908',
                'host': '#8dc3fc',
                'database': '#aa83fc'
            })
        ])

        self.message = [
            ('class:username', self.database.database_url.username),
            ('class:punctuation', '@'),
            ('class:host', self.database.database_url.host),
            ('class:punctuation', ':'),
            ('class:database', self.database.get_current_db()),
            ('class:punctuation', '> '),
        ]
    def _create_merged_style(self, include_default_pygments_style: Filter) -> BaseStyle:
        """
        Create a `Style` object that merges the default UI style, the default
        pygments style, and the custom user style.
        """
        dummy_style = DummyStyle()
        pygments_style = default_pygments_style()

        @DynamicStyle
        def conditional_pygments_style() -> BaseStyle:
            if include_default_pygments_style():
                return pygments_style
            else:
                return dummy_style

        return merge_styles([
            default_ui_style(),
            conditional_pygments_style,
            DynamicStyle(lambda: self.style),
        ])
Ejemplo n.º 24
0
    def _create_merged_style(self, include_default_pygments_style):
        """
        Create a `Style` object that merges the default UI style, the default
        pygments style, and the custom user style.
        """
        dummy_style = DummyStyle()
        pygments_style = default_pygments_style()

        @DynamicStyle
        def conditional_pygments_style():
            if include_default_pygments_style():
                return pygments_style
            else:
                return dummy_style

        return merge_styles([
            default_ui_style(),
            conditional_pygments_style,
            DynamicStyle(lambda: self.style),
        ])
Ejemplo n.º 25
0
def style_factory(name, cli_style):
    try:
        style = pygments.styles.get_style_by_name(name)
    except ClassNotFound:
        style = pygments.styles.get_style_by_name("native")

    prompt_styles = []
    # prompt-toolkit used pygments tokens for styling before, switched to style
    # names in 2.0. Convert old token types to new style names, for backwards compatibility.
    for token in cli_style:
        if token.startswith("Token."):
            start_with_token()
        else:
            # treat as prompt style name (2.0). See default style names here:
            # https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/styles/defaults.py
            prompt_styles.append((token, cli_style[token]))

    override_style = Style([("bottom-toolbar", "noreverse")])
    return merge_styles(
        [style_from_pygments_cls(style), override_style, Style(prompt_styles)]
    )
Ejemplo n.º 26
0
    def style_factory(self, style_name):
        """Retrieve the specified pygments style.

        If the specified style is not found, the vim style is returned.

        :type style_name: str
        :param style_name: The pygments style name.

        :rtype: :class:`pygments.style.StyleMeta`
        :return: Pygments style info.
        """

        return merge_styles([
            style_from_pygments_cls(DefaultStyle),
            Style.from_dict({
                'path': 'ansicyan underline',
                'prompt': 'fg:ansiblue bold',
                'state': 'fg:ansigreen bold',
                'danger': 'fg:ansired bold',
            })
        ])
Ejemplo n.º 27
0
def mystyle():
    style1 = Style.from_dict({
        "completion-menu.completion": "bg:#008888 #ffffff",
        "completion-menu.completion.current": "bg:#00aaaa #000000",
        "scrollbar.background": "bg:#88aaaa",
        "scrollbar.button": "bg:#222222",
        # 'bottom-toolbar': 'bg:#096f9e #0a8dc9',
        # Prompt
        "language": "ansicyan bold",
        "arrow": "#9BD55C",
    })

    dialog_style = Style.from_dict({
        "dialog": "bg:#88ff88",
        "dialog frame.label": "bg:#ffffff #000000",
        "dialog.body": "bg:#000000 #00ff00",
        "dialog shadow": "bg:#00aa00",
    })

    style = merge_styles([style1, dialog_style])

    # style = style_from_pygments_cls(get_style_by_name("monokai"))

    return style
Ejemplo n.º 28
0
    def _make_style_from_name_or_cls(self, name_or_cls):
        """
        Small wrapper that make an IPython compatible style from a style name

        We need that to add style for prompt ... etc.
        """
        style_overrides = {}
        if name_or_cls == 'legacy':
            legacy = self.colors.lower()
            if legacy == 'linux':
                style_cls = get_style_by_name('monokai')
                style_overrides = _style_overrides_linux
            elif legacy == 'lightbg':
                style_overrides = _style_overrides_light_bg
                style_cls = get_style_by_name('pastie')
            elif legacy == 'neutral':
                # The default theme needs to be visible on both a dark background
                # and a light background, because we can't tell what the terminal
                # looks like. These tweaks to the default theme help with that.
                style_cls = get_style_by_name('default')
                style_overrides.update({
                    Token.Number:
                    '#007700',
                    Token.Operator:
                    'noinherit',
                    Token.String:
                    '#BB6622',
                    Token.Name.Function:
                    '#2080D0',
                    Token.Name.Class:
                    'bold #2080D0',
                    Token.Name.Namespace:
                    'bold #2080D0',
                    Token.Prompt:
                    '#009900',
                    Token.PromptNum:
                    '#ansibrightgreen bold',
                    Token.OutPrompt:
                    '#990000',
                    Token.OutPromptNum:
                    '#ansibrightred bold',
                })

                # Hack: Due to limited color support on the Windows console
                # the prompt colors will be wrong without this
                if os.name == 'nt':
                    style_overrides.update({
                        Token.Prompt: '#ansidarkgreen',
                        Token.PromptNum: '#ansigreen bold',
                        Token.OutPrompt: '#ansidarkred',
                        Token.OutPromptNum: '#ansired bold',
                    })
            elif legacy == 'nocolor':
                style_cls = _NoStyle
                style_overrides = {}
            else:
                raise ValueError('Got unknown colors: ', legacy)
        else:
            if isinstance(name_or_cls, str):
                style_cls = get_style_by_name(name_or_cls)
            else:
                style_cls = name_or_cls
            style_overrides = {
                Token.Prompt: '#009900',
                Token.PromptNum: '#ansibrightgreen bold',
                Token.OutPrompt: '#990000',
                Token.OutPromptNum: '#ansibrightred bold',
            }
        style_overrides.update(self.highlighting_style_overrides)
        style = merge_styles([
            style_from_pygments_cls(style_cls),
            style_from_pygments_dict(style_overrides),
        ])

        return style
Ejemplo n.º 29
0
def checkbox(message: Text,
             choices: List[Union[Text, Choice, Dict[Text, Any]]],
             default: Optional[Text] = None,
             qmark: Text = DEFAULT_QUESTION_PREFIX,
             style: Optional[Style] = None,
             use_pointer: bool = True,
             **kwargs: Any) -> Question:
    """Ask the user to select from a list of items.

    This is a multiselect, the user can choose one, none or many of the
    items.

    Args:
        message: Question text

        choices: Items shown in the selection, this can contain `Choice` or
                 or `Separator` objects or simple items as strings. Passing
                 `Choice` objects, allows you to configure the item more
                 (e.g. preselecting it or disabeling it).

        default: Default return value (single value). If you want to preselect
                 multiple items, use `Choice("foo", checked=True)` instead.

        qmark: Question prefix displayed in front of the question.
               By default this is a `?`

        style: A custom color and style for the question parts. You can
               configure colors as well as font types for different elements.

        use_pointer: Flag to enable the pointer in front of the currently
                     highlighted element.

    Returns:
        Question: Question instance, ready to be prompted (using `.ask()`).
    """

    merged_style = merge_styles([DEFAULT_STYLE, style])

    ic = InquirerControl(choices, default, use_pointer=use_pointer)

    def get_prompt_tokens():
        tokens = []

        tokens.append(("class:qmark", qmark))
        tokens.append(("class:question", ' {} '.format(message)))
        if ic.is_answered:
            nbr_selected = len(ic.selected_options)
            if nbr_selected == 0:
                tokens.append(("class:answer", ' hecho'))
            elif nbr_selected == 1:
                if isinstance(ic.get_selected_values()[0].title, list):
                    tokens.append(("class:answer", "".join([
                        token[1] for token in ic.get_selected_values()[0].title
                    ])))
                else:
                    tokens.append(
                        ("class:answer",
                         ' [{}]'.format(ic.get_selected_values()[0].title)))
            else:
                tokens.append(("class:answer",
                               ' hecho ({} selecciones)'.format(nbr_selected)))
        else:
            tokens.append(("class:instruction",
                           ' \n (Usa las teclas de flechas para mover, '
                           '<space> seleccionar, '
                           '<a> alternar, '
                           '<i> invertir)'))
        return tokens

    layout = common.create_inquirer_layout(ic, get_prompt_tokens, **kwargs)

    bindings = KeyBindings()

    @bindings.add(Keys.ControlQ, eager=True)
    @bindings.add(Keys.ControlC, eager=True)
    def _(event):
        event.app.exit(exception=KeyboardInterrupt, style='class:aborting')

    @bindings.add(' ', eager=True)
    def toggle(event):
        pointed_choice = ic.get_pointed_at().value
        if pointed_choice in ic.selected_options:
            ic.selected_options.remove(pointed_choice)
        else:
            ic.selected_options.append(pointed_choice)

    @bindings.add('i', eager=True)
    def invert(event):
        inverted_selection = [
            c.value for c in ic.choices if not isinstance(c, Separator)
            and c.value not in ic.selected_options and not c.disabled
        ]
        ic.selected_options = inverted_selection

    @bindings.add('a', eager=True)
    def all(event):
        all_selected = True  # all choices have been selected
        for c in ic.choices:
            if (not isinstance(c, Separator)
                    and c.value not in ic.selected_options and not c.disabled):
                # add missing ones
                ic.selected_options.append(c.value)
                all_selected = False
        if all_selected:
            ic.selected_options = []

    @bindings.add(Keys.Down, eager=True)
    @bindings.add("j", eager=True)
    def move_cursor_down(event):
        ic.select_next()
        while not ic.is_selection_valid():
            ic.select_next()

    @bindings.add(Keys.Up, eager=True)
    @bindings.add("k", eager=True)
    def move_cursor_up(event):
        ic.select_previous()
        while not ic.is_selection_valid():
            ic.select_previous()

    @bindings.add(Keys.ControlM, eager=True)
    def set_answer(event):
        ic.is_answered = True
        event.app.exit(result=[c.value for c in ic.get_selected_values()])

    @bindings.add(Keys.Any)
    def other(event):
        """Disallow inserting other text. """
        pass

    return Question(
        Application(layout=layout,
                    key_bindings=bindings,
                    style=merged_style,
                    **kwargs))
Ejemplo n.º 30
0
    def singleline(self,
                   auto_suggest=None,
                   enable_history_search=True,
                   multiline=True,
                   **kwargs):
        """Reads a single line of input from the shell. The store_in_history
        kwarg flags whether the input should be stored in PTK's in-memory
        history.
        """
        events.on_pre_prompt.fire()
        env = builtins.__xonsh__.env
        mouse_support = env.get("MOUSE_SUPPORT")
        auto_suggest = auto_suggest if env.get("AUTO_SUGGEST") else None
        completions_display = env.get("COMPLETIONS_DISPLAY")
        complete_style = self.completion_displays_to_styles[
            completions_display]

        complete_while_typing = env.get("UPDATE_COMPLETIONS_ON_KEYPRESS")
        if complete_while_typing:
            # PTK requires history search to be none when completing while typing
            enable_history_search = False
        if HAS_PYGMENTS:
            self.styler.style_name = env.get("XONSH_COLOR_STYLE")
        completer = None if completions_display == "none" else self.pt_completer

        if env.get("UPDATE_PROMPT_ON_KEYPRESS"):
            get_prompt_tokens = self.prompt_tokens
            get_rprompt_tokens = self.rprompt_tokens
            get_bottom_toolbar_tokens = self.bottom_toolbar_tokens
        else:
            get_prompt_tokens = self.prompt_tokens()
            get_rprompt_tokens = self.rprompt_tokens()
            get_bottom_toolbar_tokens = self.bottom_toolbar_tokens()

        if env.get("VI_MODE"):
            editing_mode = EditingMode.VI
        else:
            editing_mode = EditingMode.EMACS

        if env.get("XONSH_HISTORY_MATCH_ANYWHERE"):
            self.prompter.default_buffer._history_matches = MethodType(
                _cust_history_matches, self.prompter.default_buffer)
        elif (self.prompter.default_buffer._history_matches
              is not self._history_matches_orig):
            self.prompter.default_buffer._history_matches = self._history_matches_orig

        prompt_args = {
            "mouse_support": mouse_support,
            "auto_suggest": auto_suggest,
            "message": get_prompt_tokens,
            "rprompt": get_rprompt_tokens,
            "bottom_toolbar": get_bottom_toolbar_tokens,
            "completer": completer,
            "multiline": multiline,
            "editing_mode": editing_mode,
            "prompt_continuation": self.continuation_tokens,
            "enable_history_search": enable_history_search,
            "reserve_space_for_menu": 10,
            "key_bindings": self.key_bindings,
            "complete_style": complete_style,
            "complete_while_typing": complete_while_typing,
            "include_default_pygments_style": False,
        }
        if builtins.__xonsh__.env.get("COLOR_INPUT"):
            style = style_from_pygments_dict(DEFAULT_STYLE_DICT)

            prompt_args["style"] = style

            style_overrides_env = env.get("PTK_STYLE_OVERRIDES")
            if style_overrides_env:
                try:
                    style_overrides = Style.from_dict(style_overrides_env)
                    prompt_args["style"] = merge_styles(
                        [style, style_overrides])
                except (AttributeError, TypeError, ValueError):
                    print_exception()

        line = self.prompter.prompt(**prompt_args)
        events.on_post_prompt.fire()
        return line
Ejemplo n.º 31
0
    def init_prompt_toolkit_cli(self):
        if self.simple_prompt or ('JUPYTER_CONSOLE_TEST' in os.environ):
            # Simple restricted interface for tests so we can find prompts with
            # pexpect. Multi-line input not supported.
            async def prompt():
                prompt = 'In [%d]: ' % self.execution_count
                raw = await async_input(prompt)
                return raw

            self.prompt_for_code = prompt
            self.print_out_prompt = \
                lambda: print('Out[%d]: ' % self.execution_count, end='')
            return

        kb = KeyBindings()
        insert_mode = vi_insert_mode | emacs_insert_mode

        @kb.add("enter",
                filter=(has_focus(DEFAULT_BUFFER)
                        & ~has_selection
                        & insert_mode))
        def _(event):
            b = event.current_buffer
            d = b.document
            if not (d.on_last_line or d.cursor_position_row >=
                    d.line_count - d.empty_line_count_at_the_end()):
                b.newline()
                return

            # Pressing enter flushes any pending display. This also ensures
            # the displayed execution_count is correct.
            self.handle_iopub()

            more, indent = self.check_complete(d.text)

            if (not more) and b.accept_handler:
                b.validate_and_handle()
            else:
                b.insert_text('\n' + indent)

        @kb.add("c-c", filter=has_focus(DEFAULT_BUFFER))
        def _(event):
            event.current_buffer.reset()

        @kb.add("c-\\", filter=has_focus(DEFAULT_BUFFER))
        def _(event):
            raise EOFError

        @kb.add("c-z",
                filter=Condition(lambda: suspend_to_background_supported()))
        def _(event):
            event.cli.suspend_to_background()

        @kb.add("c-o", filter=(has_focus(DEFAULT_BUFFER) & emacs_insert_mode))
        def _(event):
            event.current_buffer.insert_text("\n")

        # Pre-populate history from IPython's history database
        history = InMemoryHistory()
        last_cell = u""
        for _, _, cell in self.history_manager.get_tail(
                self.history_load_length, include_latest=True):
            # Ignore blank lines and consecutive duplicates
            cell = cell.rstrip()
            if cell and (cell != last_cell):
                history.append_string(cell)

        style_overrides = {
            Token.Prompt: '#009900',
            Token.PromptNum: '#00ff00 bold',
            Token.OutPrompt: '#ff2200',
            Token.OutPromptNum: '#ff0000 bold',
            Token.RemotePrompt: '#999900',
        }
        if self.highlighting_style:
            style_cls = get_style_by_name(self.highlighting_style)
        else:
            style_cls = get_style_by_name('default')
            # The default theme needs to be visible on both a dark background
            # and a light background, because we can't tell what the terminal
            # looks like. These tweaks to the default theme help with that.
            style_overrides.update({
                Token.Number: '#007700',
                Token.Operator: 'noinherit',
                Token.String: '#BB6622',
                Token.Name.Function: '#2080D0',
                Token.Name.Class: 'bold #2080D0',
                Token.Name.Namespace: 'bold #2080D0',
            })
        style_overrides.update(self.highlighting_style_overrides)
        style = merge_styles([
            style_from_pygments_cls(style_cls),
            style_from_pygments_dict(style_overrides),
        ])

        editing_mode = getattr(EditingMode, self.editing_mode.upper())
        langinfo = self.kernel_info.get('language_info', {})
        lexer = langinfo.get('pygments_lexer', langinfo.get('name', 'text'))

        # If enabled in the settings, highlight matching brackets
        # when the DEFAULT_BUFFER has the focus
        input_processors = [
            ConditionalProcessor(
                processor=HighlightMatchingBracketProcessor(chars='[](){}'),
                filter=has_focus(DEFAULT_BUFFER) & ~is_done
                & Condition(lambda: self.highlight_matching_brackets))
        ]

        # Tell prompt_toolkit to use the asyncio event loop.
        # Obsolete in prompt_toolkit.v3
        if not PTK3:
            use_asyncio_event_loop()

        self.pt_cli = PromptSession(
            message=(lambda: PygmentsTokens(self.get_prompt_tokens())),
            multiline=True,
            complete_style=self.pt_complete_style,
            editing_mode=editing_mode,
            lexer=PygmentsLexer(get_pygments_lexer(lexer)),
            prompt_continuation=(
                lambda width, lineno, is_soft_wrap: PygmentsTokens(
                    self.get_continuation_tokens(width))),
            key_bindings=kb,
            history=history,
            completer=JupyterPTCompleter(self.Completer),
            enable_history_search=True,
            style=style,
            input_processors=input_processors,
            color_depth=(ColorDepth.TRUE_COLOR if self.true_color else None),
        )
Ejemplo n.º 32
0
def generate_style(python_style, ui_style):
    """
    Generate Pygments Style class from two dictionaries
    containing style rules.
    """
    return merge_styles([python_style, ui_style])
Ejemplo n.º 33
0
def select(message: Text,
           choices: List[Union[Text, Choice, Dict[Text, Any]]],
           default: Optional[Text] = None,
           qmark: Text = DEFAULT_QUESTION_PREFIX,
           style: Optional[Style] = None,
           use_shortcuts: bool = False,
           use_indicator: bool = False,
           **kwargs: Any) -> Question:
    """Prompt the user to select one item from the list of choices.

    The user can only select one option.

    Args:
        message: Question text

        choices: Items shown in the selection, this can contain `Choice` or
                 or `Separator` objects or simple items as strings. Passing
                 `Choice` objects, allows you to configure the item more
                 (e.g. preselecting it or disabeling it).

        default: Default return value (single value).

        qmark: Question prefix displayed in front of the question.
               By default this is a `?`

        style: A custom color and style for the question parts. You can
               configure colors as well as font types for different elements.

        use_indicator: Flag to enable the small indicator in front of the
                       list highlighting the current location of the selection
                       cursor.

        use_shortcuts: Allow the user to select items from the list using
                       shortcuts. The shortcuts will be displayed in front of
                       the list items.
    Returns:
        Question: Question instance, ready to be prompted (using `.ask()`).
    """
    if choices is None or len(choices) == 0:
        raise ValueError('A list of choices needs to be provided.')

    if use_shortcuts and len(choices) > len(InquirerControl.SHORTCUT_KEYS):
        raise ValueError('A list with shortcuts supports a maximum of {} '
                         'choices as this is the maximum number '
                         'of keyboard shortcuts that are available. You'
                         'provided {} choices!'
                         ''.format(len(InquirerControl.SHORTCUT_KEYS),
                                   len(choices)))

    merged_style = merge_styles([DEFAULT_STYLE, style])

    ic = InquirerControl(choices,
                         default,
                         use_indicator=use_indicator,
                         use_shortcuts=use_shortcuts)

    def get_prompt_tokens():
        # noinspection PyListCreation
        tokens = [("class:qmark", qmark),
                  ("class:question", ' {} '.format(message))]

        if ic.is_answered:
            tokens.append(("class:answer", ' ' + ic.get_pointed_at().title))
        else:
            if use_shortcuts:
                tokens.append(("class:instruction", ' (Use shortcuts)'))
            else:
                tokens.append(("class:instruction", ' (Use arrow keys)'))

        return tokens

    layout = common.create_inquirer_layout(ic, get_prompt_tokens, **kwargs)

    bindings = KeyBindings()

    @bindings.add(Keys.ControlQ, eager=True)
    @bindings.add(Keys.ControlC, eager=True)
    def _(event):
        event.app.exit(exception=KeyboardInterrupt, style='class:aborting')

    if use_shortcuts:
        # add key bindings for choices
        for i, c in enumerate(ic.choices):
            if isinstance(c, Separator):
                continue

            # noinspection PyShadowingNames
            def _reg_binding(i, keys):
                # trick out late evaluation with a "function factory":
                # https://stackoverflow.com/a/3431699
                @bindings.add(keys, eager=True)
                def select_choice(event):
                    ic.pointed_at = i

            _reg_binding(i, c.shortcut_key)
    else:

        @bindings.add(Keys.Down, eager=True)
        @bindings.add("j", eager=True)
        def move_cursor_down(event):
            ic.select_next()
            while not ic.is_selection_valid():
                ic.select_next()

        @bindings.add(Keys.Up, eager=True)
        @bindings.add("k", eager=True)
        def move_cursor_up(event):
            ic.select_previous()
            while not ic.is_selection_valid():
                ic.select_previous()

    @bindings.add(Keys.ControlM, eager=True)
    def set_answer(event):
        ic.is_answered = True
        event.app.exit(result=ic.get_pointed_at().value)

    @bindings.add(Keys.Any)
    def other(event):
        """Disallow inserting other text. """
        pass

    return Question(
        Application(layout=layout,
                    key_bindings=bindings,
                    style=merged_style,
                    **kwargs))
Ejemplo n.º 34
0
    def init_prompt_toolkit_cli(self):
        if self.simple_prompt or ('JUPYTER_CONSOLE_TEST' in os.environ):
            # Simple restricted interface for tests so we can find prompts with
            # pexpect. Multi-line input not supported.
            def prompt():
                return cast_unicode_py2(input('In [%d]: ' % self.execution_count))
            self.prompt_for_code = prompt
            self.print_out_prompt = \
                lambda: print('Out[%d]: ' % self.execution_count, end='')
            return

        kb = KeyBindings()
        insert_mode = vi_insert_mode | emacs_insert_mode

        @kb.add("enter", filter=(has_focus(DEFAULT_BUFFER)
                                 & ~has_selection
                                 & insert_mode
                                 ))
        def _(event):
            b = event.current_buffer
            d = b.document
            if not (d.on_last_line or d.cursor_position_row >= d.line_count
                                           - d.empty_line_count_at_the_end()):
                b.newline()
                return

            # Pressing enter flushes any pending display. This also ensures
            # the displayed execution_count is correct.
            self.handle_iopub()

            more, indent = self.check_complete(d.text)

            if (not more) and b.accept_handler:
                b.validate_and_handle()
            else:
                b.insert_text('\n' + indent)

        @kb.add("c-c", filter=has_focus(DEFAULT_BUFFER))
        def _(event):
            event.current_buffer.reset()

        @kb.add("c-\\", filter=has_focus(DEFAULT_BUFFER))
        def _(event):
            raise EOFError

        @kb.add("c-z", filter=Condition(lambda: suspend_to_background_supported()))
        def _(event):
            event.cli.suspend_to_background()

        # Pre-populate history from IPython's history database
        history = InMemoryHistory()
        last_cell = u""
        for _, _, cell in self.history_manager.get_tail(self.history_load_length,
                                                        include_latest=True):
            # Ignore blank lines and consecutive duplicates
            cell = cast_unicode_py2(cell.rstrip())
            if cell and (cell != last_cell):
                history.append_string(cell)

        style_overrides = {
            Token.Prompt: '#009900',
            Token.PromptNum: '#00ff00 bold',
            Token.OutPrompt: '#ff2200',
            Token.OutPromptNum: '#ff0000 bold',
        }
        if self.highlighting_style:
            style_cls = get_style_by_name(self.highlighting_style)
        else:
            style_cls = get_style_by_name('default')
            # The default theme needs to be visible on both a dark background
            # and a light background, because we can't tell what the terminal
            # looks like. These tweaks to the default theme help with that.
            style_overrides.update({
                Token.Number: '#007700',
                Token.Operator: 'noinherit',
                Token.String: '#BB6622',
                Token.Name.Function: '#2080D0',
                Token.Name.Class: 'bold #2080D0',
                Token.Name.Namespace: 'bold #2080D0',
            })
        style_overrides.update(self.highlighting_style_overrides)
        style = merge_styles([
            style_from_pygments_cls(style_cls),
            style_from_pygments_dict(style_overrides),
        ])

        editing_mode = getattr(EditingMode, self.editing_mode.upper())
        langinfo = self.kernel_info.get('language_info', {})
        lexer = langinfo.get('pygments_lexer', langinfo.get('name', 'text'))

        # If enabled in the settings, highlight matching brackets
        # when the DEFAULT_BUFFER has the focus
        input_processors = [ConditionalProcessor(
            processor=HighlightMatchingBracketProcessor(chars='[](){}'),
            filter=has_focus(DEFAULT_BUFFER) & ~is_done &
            Condition(lambda: self.highlight_matching_brackets))
        ]

        self.pt_cli = PromptSession(
            message=(lambda: PygmentsTokens(self.get_prompt_tokens())),
            multiline=True,
            editing_mode=editing_mode,
            lexer=PygmentsLexer(get_pygments_lexer(lexer)),
            prompt_continuation=(
                lambda width, lineno, is_soft_wrap:
                PygmentsTokens(self.get_continuation_tokens(width))
            ),
            key_bindings=kb,
            history=history,
            completer=JupyterPTCompleter(self.Completer),
            enable_history_search=True,
            style=style,
            input_processors=input_processors,
            color_depth=(ColorDepth.TRUE_COLOR if self.true_color else None),

        )
Ejemplo n.º 35
0
    def singleline(
        self, auto_suggest=None, enable_history_search=True, multiline=True, **kwargs
    ):
        """Reads a single line of input from the shell. The store_in_history
        kwarg flags whether the input should be stored in PTK's in-memory
        history.
        """
        events.on_pre_prompt.fire()
        env = builtins.__xonsh__.env
        mouse_support = env.get("MOUSE_SUPPORT")
        auto_suggest = auto_suggest if env.get("AUTO_SUGGEST") else None
        completions_display = env.get("COMPLETIONS_DISPLAY")
        complete_style = self.completion_displays_to_styles[completions_display]

        complete_while_typing = env.get("UPDATE_COMPLETIONS_ON_KEYPRESS")
        if complete_while_typing:
            # PTK requires history search to be none when completing while typing
            enable_history_search = False
        if HAS_PYGMENTS:
            self.styler.style_name = env.get("XONSH_COLOR_STYLE")
        completer = None if completions_display == "none" else self.pt_completer

        if env.get("UPDATE_PROMPT_ON_KEYPRESS"):
            get_prompt_tokens = self.prompt_tokens
            get_rprompt_tokens = self.rprompt_tokens
            get_bottom_toolbar_tokens = self.bottom_toolbar_tokens
        else:
            get_prompt_tokens = self.prompt_tokens()
            get_rprompt_tokens = self.rprompt_tokens()
            get_bottom_toolbar_tokens = self.bottom_toolbar_tokens()

        if env.get("VI_MODE"):
            editing_mode = EditingMode.VI
        else:
            editing_mode = EditingMode.EMACS

        if env.get("XONSH_HISTORY_MATCH_ANYWHERE"):
            self.prompter.default_buffer._history_matches = MethodType(
                _cust_history_matches, self.prompter.default_buffer
            )
        elif (
            self.prompter.default_buffer._history_matches
            is not self._history_matches_orig
        ):
            self.prompter.default_buffer._history_matches = self._history_matches_orig

        prompt_args = {
            "mouse_support": mouse_support,
            "auto_suggest": auto_suggest,
            "message": get_prompt_tokens,
            "rprompt": get_rprompt_tokens,
            "bottom_toolbar": get_bottom_toolbar_tokens,
            "completer": completer,
            "multiline": multiline,
            "editing_mode": editing_mode,
            "prompt_continuation": self.continuation_tokens,
            "enable_history_search": enable_history_search,
            "reserve_space_for_menu": 0,
            "key_bindings": self.key_bindings,
            "complete_style": complete_style,
            "complete_while_typing": complete_while_typing,
            "include_default_pygments_style": False,
        }
        if builtins.__xonsh__.env.get("COLOR_INPUT"):
            if HAS_PYGMENTS:
                prompt_args["lexer"] = PygmentsLexer(pyghooks.XonshLexer)
                style = style_from_pygments_cls(pyghooks.xonsh_style_proxy(self.styler))
            else:
                style = style_from_pygments_dict(DEFAULT_STYLE_DICT)

            prompt_args["style"] = style

            style_overrides_env = env.get("PTK_STYLE_OVERRIDES")
            if style_overrides_env:
                try:
                    style_overrides = Style.from_dict(style_overrides_env)
                    prompt_args["style"] = merge_styles([style, style_overrides])
                except (AttributeError, TypeError, ValueError):
                    print_exception()

        line = self.prompter.prompt(**prompt_args)
        events.on_post_prompt.fire()
        return line
    def _make_style_from_name_or_cls(self, name_or_cls):
        """
        Small wrapper that make an IPython compatible style from a style name

        We need that to add style for prompt ... etc.
        """
        style_overrides = {}
        if name_or_cls == 'legacy':
            legacy = self.colors.lower()
            if legacy == 'linux':
                style_cls = get_style_by_name('monokai')
                style_overrides = _style_overrides_linux
            elif legacy == 'lightbg':
                style_overrides = _style_overrides_light_bg
                style_cls = get_style_by_name('pastie')
            elif legacy == 'neutral':
                # The default theme needs to be visible on both a dark background
                # and a light background, because we can't tell what the terminal
                # looks like. These tweaks to the default theme help with that.
                style_cls = get_style_by_name('default')
                style_overrides.update({
                    Token.Number: '#007700',
                    Token.Operator: 'noinherit',
                    Token.String: '#BB6622',
                    Token.Name.Function: '#2080D0',
                    Token.Name.Class: 'bold #2080D0',
                    Token.Name.Namespace: 'bold #2080D0',
                    Token.Prompt: '#009900',
                    Token.PromptNum: '#ansibrightgreen bold',
                    Token.OutPrompt: '#990000',
                    Token.OutPromptNum: '#ansibrightred bold',
                })

                # Hack: Due to limited color support on the Windows console
                # the prompt colors will be wrong without this
                if os.name == 'nt':
                    style_overrides.update({
                        Token.Prompt: '#ansidarkgreen',
                        Token.PromptNum: '#ansigreen bold',
                        Token.OutPrompt: '#ansidarkred',
                        Token.OutPromptNum: '#ansired bold',
                    })
            elif legacy =='nocolor':
                style_cls=_NoStyle
                style_overrides = {}
            else :
                raise ValueError('Got unknown colors: ', legacy)
        else :
            if isinstance(name_or_cls, str):
                style_cls = get_style_by_name(name_or_cls)
            else:
                style_cls = name_or_cls
            style_overrides = {
                Token.Prompt: '#009900',
                Token.PromptNum: '#ansibrightgreen bold',
                Token.OutPrompt: '#990000',
                Token.OutPromptNum: '#ansibrightred bold',
            }
        style_overrides.update(self.highlighting_style_overrides)
        style = merge_styles([
            style_from_pygments_cls(style_cls),
            style_from_pygments_dict(style_overrides),
        ])

        return style
Ejemplo n.º 37
0
def print_formatted_text(
        *values: Any,
        sep: str = ' ',
        end: str = '\n',
        file: Optional[TextIO] = None,
        flush: bool = False,
        style: Optional[BaseStyle] = None,
        output: Optional[Output] = None,
        color_depth: Optional[ColorDepth] = None,
        style_transformation: Optional[StyleTransformation] = None,
        include_default_pygments_style: bool = True) -> None:
    """
    ::

        print_formatted_text(*values, sep=' ', end='\\n', file=None, flush=False, style=None, output=None)

    Print text to stdout. This is supposed to be compatible with Python's print
    function, but supports printing of formatted text. You can pass a
    :class:`~prompt_toolkit.formatted_text.FormattedText`,
    :class:`~prompt_toolkit.formatted_text.HTML` or
    :class:`~prompt_toolkit.formatted_text.ANSI` object to print formatted
    text.

    * Print HTML as follows::

        print_formatted_text(HTML('<i>Some italic text</i> <ansired>This is red!</ansired>'))

        style = Style.from_dict({
            'hello': '#ff0066',
            'world': '#884444 italic',
        })
        print_formatted_text(HTML('<hello>Hello</hello> <world>world</world>!'), style=style)

    * Print a list of (style_str, text) tuples in the given style to the
      output.  E.g.::

        style = Style.from_dict({
            'hello': '#ff0066',
            'world': '#884444 italic',
        })
        fragments = FormattedText([
            ('class:hello', 'Hello'),
            ('class:world', 'World'),
        ])
        print_formatted_text(fragments, style=style)

    If you want to print a list of Pygments tokens, wrap it in
    :class:`~prompt_toolkit.formatted_text.PygmentsTokens` to do the
    conversion.

    :param values: Any kind of printable object, or formatted string.
    :param sep: String inserted between values, default a space.
    :param end: String appended after the last value, default a newline.
    :param style: :class:`.Style` instance for the color scheme.
    :param include_default_pygments_style: `bool`. Include the default Pygments
        style when set to `True` (the default).
    """
    assert not (output and file)

    # Build/merge style.
    styles = [default_ui_style()]
    if include_default_pygments_style:
        styles.append(default_pygments_style())
    if style:
        styles.append(style)

    merged_style = merge_styles(styles)

    # Create Output object.
    if output is None:
        if file:
            output = create_output(stdout=file)
        else:
            output = get_app_session().output

    assert isinstance(output, Output)

    # Get color depth.
    color_depth = color_depth or ColorDepth.default()

    # Merges values.
    def to_text(val: Any) -> StyleAndTextTuples:
        # Normal lists which are not instances of `FormattedText` are
        # considered plain text.
        if isinstance(val, list) and not isinstance(val, FormattedText):
            return to_formatted_text('{0}'.format(val))
        return to_formatted_text(val, auto_convert=True)

    fragments = []
    for i, value in enumerate(values):
        fragments.extend(to_text(value))

        if sep and i != len(values) - 1:
            fragments.extend(to_text(sep))

    fragments.extend(to_text(end))

    # Print output.
    renderer_print_formatted_text(
        output, fragments, merged_style, color_depth=color_depth,
        style_transformation=style_transformation)

    # Flush the output stream.
    if flush:
        output.flush()