Skip to content

Commit

Permalink
Merge pull request #35 from Chitaoji/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
Chitaoji authored Aug 14, 2024
2 parents 3f2a917 + 62603f7 commit 5c0b9f6
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 20 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,9 @@ examples/myfile.py:34: ' print(<book>.content)'
This project falls under the BSD 3-Clause License.

## History
### v0.1.28
* Fixed issue: can not display HTML entities as plain text in `*._repr_mimebundle_()`.

### v0.1.27
* New gloabal parameters: `tree_style=`, `table_style=`, `use_mimebundle=`, and `skip_line_numbers=`; find them under `tx.display_params`.
* Defined `display_params.defaults()` for users to get the default values of the parameters.
Expand Down
2 changes: 1 addition & 1 deletion src/__version__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""Version file."""

VERSION = (0, 1, 27)
VERSION = (0, 1, 28)

__version__ = ".".join(map(str, VERSION))
52 changes: 37 additions & 15 deletions src/interaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
import pandas as pd
from typing_extensions import Self

from .utils.re_extensions import smart_sub
from .utils.re_extensions import real_findall, smart_split, smart_sub
from .utils.validator import SimpleValidator

if TYPE_CHECKING:
Expand Down Expand Up @@ -208,7 +208,11 @@ def to_styler(self) -> "Styler":
df.iloc[i, 0] += ":" + make_ahref(
f"{t.execpath}:{n}", str(n), color="inherit"
)
df.iloc[i, 1] = smart_sub(p, partial(self.stylfunc, res), _line)
splits = smart_split(p, _line)
text = ""
for j, x in enumerate(real_findall(p, _line)):
text += make_plain_text(splits[j]) + self.stylfunc(res, x)
df.iloc[i, 1] = text + make_plain_text(splits[-1])
return df.style.hide(axis=0).set_table_styles(
[
{"selector": "th", "props": [("text-align", "center")]},
Expand All @@ -217,7 +221,7 @@ def to_styler(self) -> "Styler":
)

def to_html(self) -> str:
"""Return an html string for representation."""
"""Return an HTML string for representation."""
html_maker = HTMLTableMaker(
index=range(len(self.res)), columns=["source", "match"]
)
Expand All @@ -230,7 +234,11 @@ def to_html(self) -> str:
html_maker[i, 0] += ":" + make_ahref(
f"{t.execpath}:{n}", str(n), color="inherit"
)
html_maker[i, 1] = smart_sub(p, partial(self.stylfunc, res), _line)
splits = smart_split(p, _line)
text = ""
for j, x in enumerate(real_findall(p, _line)):
text += make_plain_text(splits[j]) + self.stylfunc(res, x)
html_maker[i, 1] = text + make_plain_text(splits[-1])
return html_maker.make()

@staticmethod
Expand All @@ -256,7 +264,7 @@ def __style_match(r: TextFinding, m: "Match[str]", /) -> str:
if m.group() == ""
else make_ahref(
f"{r.obj.execpath}:{r.nline}:{1+r.obj.spaces+m.start()}",
m.group(),
make_plain_text(m.group()),
color="#cccccc",
bg_color=get_bg_colors()[0],
)
Expand All @@ -266,7 +274,7 @@ def __style_match(r: TextFinding, m: "Match[str]", /) -> str:
@dataclass
class HTMLTableMaker:
"""
Make an html table.
Make an HTML table.
Parameters
----------
Expand All @@ -292,7 +300,7 @@ def __setitem__(self, __key: Tuple[int, int], __value: str) -> None:
self.data[__key[0]][__key[1]] = __value

def make(self) -> str:
"""Make a string of the html table."""
"""Make a string of the HTML table."""
tclass = display_params.table_style
if tclass == "classic":
tstyle = """<style type="text/css">
Expand Down Expand Up @@ -464,7 +472,7 @@ def __bool__(self) -> bool:
return bool(self.editors)

def to_html(self) -> str:
"""Return an html string for representation."""
"""Return an HTML string for representation."""
return self.__find_text_result.to_html()

def append(self, editor: FileEditor) -> None:
Expand Down Expand Up @@ -573,13 +581,17 @@ def __style(self, r: TextFinding, m: "Match[str]", /) -> str:
before = (
""
if m.group() == ""
else make_ahref(url, m.group(), color="#cccccc", bg_color=bgc[1])
else make_ahref(
url, make_plain_text(m.group()), color="#cccccc", bg_color=bgc[1]
)
)
if (new := self.editors[r.order].counted_repl(m)) == "":
return before
if display_params.color_scheme == "no-color" and before != "":
new = "/" + new
return before + make_ahref(url, new, color="#cccccc", bg_color=bgc[2])
return before + make_ahref(
url, make_plain_text(new), color="#cccccc", bg_color=bgc[2]
)

def __repr(self, r: TextFinding, m: "Match[str]", /) -> str:
new = self.editors[r.order].counted_repl(m)
Expand All @@ -604,7 +616,7 @@ def __find_text_result(self) -> FindTextResult:

def make_html_tree(pytext: "PyText") -> str:
"""
Make an html file-tree.
Make an HTML tree.
Parameters
----------
Expand Down Expand Up @@ -724,8 +736,8 @@ def __get_li(pytext: "PyText", main: bool = True) -> str:
if pytext.is_dir() and pytext.children:
tchidren = "\n".join(__get_li(x) for x in pytext.children)
return (
f'<li class="m"><details><summary>{triangle}{pytext.name}</summary>\n'
f'<ul class="m">\n{tchidren}\n</ul>\n</details></li>'
f'<li class="m"><details><summary>{triangle}{make_plain_text(pytext.name)}'
f'</summary>\n<ul class="m">\n{tchidren}\n</ul>\n</details></li>'
)

li_class = "m" if main else "s"
Expand All @@ -738,12 +750,12 @@ def __get_li(pytext: "PyText", main: bool = True) -> str:
if x.name != NULL and __is_public(x.name)
)
if tchidren:
name = pytext.name + (".py" if pytext.is_file() else "")
name = make_plain_text(pytext.name) + (".py" if pytext.is_file() else "")
return (
f'<li class="{li_class}"><details><summary>{triangle}{name}</summary>'
f'\n<ul class="{ul_class}">\n{tchidren}\n</ul>\n</details></li>'
)
name = pytext.name + (".py" if pytext.is_file() else "")
name = make_plain_text(pytext.name) + (".py" if pytext.is_file() else "")
return f'<li class="{li_class}"><span>{name}</span></li>'


Expand Down Expand Up @@ -782,6 +794,16 @@ def make_ahref(
return f'<a {href}style="{style}">{text}</a>'


def make_plain_text(text: str) -> str:
"""Turn HTML entities into plain text."""
return (
text.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace('"', "&quot;")
)


def get_bg_colors() -> Tuple[str, str, str]:
"""
Get background colors.
Expand Down
23 changes: 19 additions & 4 deletions src/utils/re_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,9 @@ class SmartPattern(Generic[AnyStr]):
By default "{}" is used to mark where the pattern should be ignored, or
you can customize it by specifying `mark_ignore=`.
NOTE: All the groups in the pattern are combined into one group in
this case.
Examples
--------
* When ignore="()", pattern "a{}b" can match the string "ab" or "a(c)b",
Expand Down Expand Up @@ -705,8 +708,11 @@ def rsplit(
) -> List[str]:
"""
Split the string by the occurrences of the pattern. Differences to
`smart_split()` that all groups in the pattern are also returned, each
connected with the substring on its right.
`smart_split()` that the matched substrings are also returned, each
connected with the unmatched substring on its right.
NOTE: All the groups in the pattern are combined into one group in
this case.
Parameters
----------
Expand Down Expand Up @@ -758,8 +764,11 @@ def lsplit(
) -> List[str]:
"""
Split the string by the occurrences of the pattern. Differences to
`smart_split()` that all groups in the pattern are also returned, each
connected with the substring on its left.
`smart_split()` that the matched substrings are also returned, each
connected with the unmatched substring on its left.
NOTE: All the groups in the pattern are combined into one group in
this case.
Parameters
----------
Expand Down Expand Up @@ -814,6 +823,9 @@ def line_findall(
`smart_findall()` that it returns a list of 2-tuples containing (nline,
substring); nline is the line number of the matched substring.
NOTE: All the groups in the pattern are combined into one group in
this case.
Parameters
----------
pattern : Union[str, Pattern[str], SmartPattern[str]]
Expand Down Expand Up @@ -871,6 +883,9 @@ def real_findall(pattern: "PatternType", string: str, flags=0, linemode=False):
`smart_findall()` or `line_findall()` that it returns match objects
instead of matched substrings.
NOTE: All the groups in the pattern are combined into one group in
this case.
Parameters
----------
pattern : Union[str, Pattern[str], SmartPattern[str]]
Expand Down

0 comments on commit 5c0b9f6

Please sign in to comment.