Skip to content

HTML.format specifiers #1566

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions prompt_toolkit/formatted_text/html.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import xml.dom.minidom as minidom
from string import Formatter
from typing import Any, List, Tuple, Union

from .base import FormattedText, StyleAndTextTuples
Expand Down Expand Up @@ -107,11 +108,7 @@ def format(self, *args: object, **kwargs: object) -> "HTML":
Like `str.format`, but make sure that the arguments are properly
escaped.
"""
# Escape all the arguments.
escaped_args = [html_escape(a) for a in args]
escaped_kwargs = {k: html_escape(v) for k, v in kwargs.items()}

return HTML(self.value.format(*escaped_args, **escaped_kwargs))
return HTML(FORMATTER.vformat(self.value, args, kwargs))

def __mod__(self, value: Union[object, Tuple[object, ...]]) -> "HTML":
"""
Expand All @@ -124,6 +121,11 @@ def __mod__(self, value: Union[object, Tuple[object, ...]]) -> "HTML":
return HTML(self.value % value)


class HTMLFormatter(Formatter):
def format_field(self, value: object, format_spec: str) -> str:
return html_escape(format(value, format_spec))


def html_escape(text: object) -> str:
# The string interpolation functions also take integers and other types.
# Convert to string first.
Expand All @@ -136,3 +138,6 @@ def html_escape(text: object) -> str:
.replace(">", ">")
.replace('"', """)
)


FORMATTER = HTMLFormatter()
3 changes: 3 additions & 0 deletions tests/test_formatted_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,9 @@ def test_html_interpolation():
value = HTML("<b>{a}</b><u>{b}</u>").format(a="hello", b="world")
assert to_formatted_text(value) == [("class:b", "hello"), ("class:u", "world")]

value = HTML("<b>{:02d}</b><u>{:.3f}</u>").format(3, 3.14159)
assert to_formatted_text(value) == [("class:b", "03"), ("class:u", "3.142")]


def test_merge_formatted_text():
html1 = HTML("<u>hello</u>")
Expand Down