Python prompt_toolkit.styles.Style() Examples

The following are 20 code examples of prompt_toolkit.styles.Style(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module prompt_toolkit.styles , or try the search function .
Example #1
Source File: pgstyle.py    From pgcli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def style_factory_output(name, cli_style):
    try:
        style = pygments.styles.get_style_by_name(name).styles
    except ClassNotFound:
        style = pygments.styles.get_style_by_name("native").styles

    for token in cli_style:
        if token.startswith("Token."):
            token_type, style_value = parse_pygments_style(token, style, cli_style)
            style.update({token_type: style_value})
        elif token in PROMPT_STYLE_TO_TOKEN:
            token_type = PROMPT_STYLE_TO_TOKEN[token]
            style.update({token_type: cli_style[token]})
        else:
            # TODO: cli helpers will have to switch to ptk.Style
            logger.error("Unhandled style / class name: %s", token)

    class OutputStyle(PygmentsStyle):
        default_style = ""
        styles = style

    return OutputStyle 
Example #2
Source File: renderer.py    From android_universal with MIT License 6 votes vote down vote up
def __init__(self, style, output, use_alternate_screen=False, mouse_support=False):
        assert isinstance(style, Style)
        assert isinstance(output, Output)

        self.style = style
        self.output = output
        self.use_alternate_screen = use_alternate_screen
        self.mouse_support = to_cli_filter(mouse_support)

        self._in_alternate_screen = False
        self._mouse_support_enabled = False
        self._bracketed_paste_enabled = False

        # Waiting for CPR flag. True when we send the request, but didn't got a
        # response.
        self.waiting_for_cpr = False

        self.reset(_scroll=True) 
Example #3
Source File: mssqlstyle.py    From mssql-cli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def style_factory_output(name, cli_style):
    try:
        style = pygments.styles.get_style_by_name(name).styles
    except ClassNotFound:
        style = pygments.styles.get_style_by_name('native').styles

    for token in cli_style:
        if token.startswith('Token.'):
            token_type, style_value = parse_pygments_style(
                token, style, cli_style)
            style.update({token_type: style_value})
        elif token in PROMPT_STYLE_TO_TOKEN:
            token_type = PROMPT_STYLE_TO_TOKEN[token]
            style.update({token_type: cli_style[token]})
        else:
            # TODO: cli helpers will have to switch to ptk.Style
            logger.error('Unhandled style / class name: %s', token)

    class OutputStyle(PygmentsStyle):   # pylint: disable=too-few-public-methods
        default_style = ""
        styles = style

    return OutputStyle 
Example #4
Source File: clistyle.py    From litecli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def style_factory_output(name, cli_style):
    try:
        style = pygments.styles.get_style_by_name(name).styles
    except ClassNotFound:
        style = pygments.styles.get_style_by_name("native").styles

    for token in cli_style:
        if token.startswith("Token."):
            token_type, style_value = parse_pygments_style(token, style, cli_style)
            style.update({token_type: style_value})
        elif token in PROMPT_STYLE_TO_TOKEN:
            token_type = PROMPT_STYLE_TO_TOKEN[token]
            style.update({token_type: cli_style[token]})
        else:
            # TODO: cli helpers will have to switch to ptk.Style
            logger.error("Unhandled style / class name: %s", token)

    class OutputStyle(PygmentsStyle):
        default_style = ""
        styles = style

    return OutputStyle 
Example #5
Source File: clistyle.py    From athenacli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def style_factory_output(name, cli_style):
    try:
        style = pygments.styles.get_style_by_name(name).styles
    except ClassNotFound:
        style = pygments.styles.get_style_by_name('native').styles

    for token in cli_style:
        if token.startswith('Token.'):
            token_type, style_value = parse_pygments_style(
                token, style, cli_style)
            style.update({token_type: style_value})
        elif token in PROMPT_STYLE_TO_TOKEN:
            token_type = PROMPT_STYLE_TO_TOKEN[token]
            style.update({token_type: cli_style[token]})
        else:
            # TODO: cli helpers will have to switch to ptk.Style
            logger.error('Unhandled style / class name: %s', token)
        
        class OutputStyle(PygmentsStyle):
            default_style = ""
            styles = style
        
        return OutputStyle 
Example #6
Source File: clistyle.py    From athenacli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def parse_pygments_style(token_name, style_object, style_dict):
    """Parse token type and style string.
    :param token_name: str name of Pygments token. Example: "Token.String"
    :param style_object: pygments.style.Style instance to use as base
    :param style_dict: dict of token names and their styles, customized to this cli
    """
    token_type = string_to_tokentype(token_name)
    try:
        other_token_type = string_to_tokentype(style_dict[token_name])
        return token_type, style_object.styles[other_token_type]
    except AttributeError as err:
        return token_type, style_dict[token_name] 
Example #7
Source File: renderer.py    From android_universal with MIT License 5 votes vote down vote up
def print_tokens(output, tokens, style):
    """
    Print a list of (Token, text) tuples in the given style to the output.
    """
    assert isinstance(output, Output)
    assert isinstance(style, Style)

    # Reset first.
    output.reset_attributes()
    output.enable_autowrap()

    # Print all (token, text) tuples.
    attrs_for_token = _TokenToAttrsCache(style.get_attrs_for_token)

    for token, text in tokens:
        attrs = attrs_for_token[token]

        if attrs:
            output.set_attributes(attrs)
        else:
            output.reset_attributes()

        output.write(text)

    # Reset again.
    output.reset_attributes()
    output.flush() 
Example #8
Source File: mssqlstyle.py    From mssql-cli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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)
    ]) 
Example #9
Source File: mssqlstyle.py    From mssql-cli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def parse_pygments_style(token_name, style_object, style_dict):
    """Parse token type and style string.
    :param token_name: str name of Pygments token. Example: "Token.String"
    :param style_object: pygments.style.Style instance to use as base
    :param style_dict: dict of token names and their styles, customized to this cli
    """
    token_type = string_to_tokentype(token_name)
    try:
        other_token_type = string_to_tokentype(style_dict[token_name])
        return token_type, style_object.styles[other_token_type]
    except AttributeError:
        return token_type, style_dict[token_name] 
Example #10
Source File: console.py    From rasa-for-botfront with Apache License 2.0 5 votes vote down vote up
def get_user_input(button_question: questionary.Question) -> Optional[Text]:
    if button_question is not None:
        response = cli_utils.payload_from_button_question(button_question)
        if response == cli_utils.FREE_TEXT_INPUT_PROMPT:
            # Re-prompt user with a free text input
            response = get_user_input(None)
    else:
        response = questionary.text(
            "",
            qmark="Your input ->",
            style=Style([("qmark", "#b373d6"), ("", "#b373d6")]),
        ).ask()
    return response.strip() if response is not None else None 
Example #11
Source File: console.py    From rasa-for-botfront with Apache License 2.0 5 votes vote down vote up
def print_bot_output(
    message: Dict[Text, Any], color=cli_utils.bcolors.OKBLUE
) -> Optional[questionary.Question]:
    if ("text" in message) and not ("buttons" in message):
        cli_utils.print_color(message.get("text"), color=color)

    if "image" in message:
        cli_utils.print_color("Image: " + message.get("image"), color=color)

    if "attachment" in message:
        cli_utils.print_color("Attachment: " + message.get("attachment"), color=color)

    if "buttons" in message:
        choices = cli_utils.button_choices_from_message_data(
            message, allow_free_text_input=True
        )

        question = questionary.select(
            message.get("text"),
            choices,
            style=Style([("qmark", "#6d91d3"), ("", "#6d91d3"), ("answer", "#b373d6")]),
        )
        return question

    if "elements" in message:
        cli_utils.print_color("Elements:", color=color)
        for idx, element in enumerate(message.get("elements")):
            cli_utils.print_color(
                cli_utils.element_to_string(element, idx), color=color
            )

    if "quick_replies" in message:
        cli_utils.print_color("Quick Replies:", color=color)
        for idx, element in enumerate(message.get("quick_replies")):
            cli_utils.print_color(cli_utils.button_to_string(element, idx), color=color)

    if "custom" in message:
        cli_utils.print_color("Custom json:", color=color)
        cli_utils.print_color(json.dumps(message.get("custom"), indent=2), color=color) 
Example #12
Source File: clistyle.py    From athenacli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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)
    ]) 
Example #13
Source File: pgstyle.py    From pgcli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def parse_pygments_style(token_name, style_object, style_dict):
    """Parse token type and style string.

    :param token_name: str name of Pygments token. Example: "Token.String"
    :param style_object: pygments.style.Style instance to use as base
    :param style_dict: dict of token names and their styles, customized to this cli

    """
    token_type = string_to_tokentype(token_name)
    try:
        other_token_type = string_to_tokentype(style_dict[token_name])
        return token_type, style_object.styles[other_token_type]
    except AttributeError:
        return token_type, style_dict[token_name] 
Example #14
Source File: clistyle.py    From litecli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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)]
    ) 
Example #15
Source File: clistyle.py    From litecli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def parse_pygments_style(token_name, style_object, style_dict):
    """Parse token type and style string.

    :param token_name: str name of Pygments token. Example: "Token.String"
    :param style_object: pygments.style.Style instance to use as base
    :param style_dict: dict of token names and their styles, customized to this cli

    """
    token_type = string_to_tokentype(token_name)
    try:
        other_token_type = string_to_tokentype(style_dict[token_name])
        return token_type, style_object.styles[other_token_type]
    except AttributeError as err:
        return token_type, style_dict[token_name] 
Example #16
Source File: console.py    From rasa_core with Apache License 2.0 5 votes vote down vote up
def get_cmd_input():
    response = questionary.text("",
                                qmark="Your input ->",
                                style=Style([('qmark', '#b373d6'),
                                             ('', '#b373d6')])).ask()
    if response is not None:
        return response.strip()
    else:
        return None 
Example #17
Source File: rawselect.py    From questionary with MIT License 5 votes vote down vote up
def rawselect(
    message: Text,
    choices: List[Union[Text, Choice, Dict[Text, Any]]],
    default: Optional[Text] = None,
    qmark: Text = DEFAULT_QUESTION_PREFIX,
    style: Optional[Style] = None,
    **kwargs: Any
) -> Question:
    """Ask the user to select one item from a list of choices using shortcuts.

       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.

       Returns:
           Question: Question instance, ready to be prompted (using `.ask()`).
       """
    return select.select(
        message, choices, default, qmark, style, use_shortcuts=True, **kwargs
    ) 
Example #18
Source File: password.py    From questionary with MIT License 5 votes vote down vote up
def password(
    message: Text,
    default: Text = "",
    validate: Any = None,
    qmark: Text = DEFAULT_QUESTION_PREFIX,
    style: Optional[Style] = None,
    **kwargs: Any
) -> Question:
    """Question the user to enter a secret text not displayed in the prompt.

       This question type can be used to prompt the user for information
       that should not be shown in the command line. The typed text will be
       replaced with `*`.

       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()`).
    """

    return text.text(
        message, default, validate, qmark, style, is_password=True, **kwargs
    ) 
Example #19
Source File: pgstyle.py    From pgcli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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)]
    ) 
Example #20
Source File: text.py    From questionary with MIT License 4 votes vote down vote up
def text(
    message: Text,
    default: Text = "",
    validate: Any = None,
    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() -> List[Tuple[Text, Text]]:
        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)