Use rich instead of ansiwrap to wrap text (#1693)

This commit is contained in:
Micah Jerome Ellison 2023-07-29 14:36:43 -07:00 committed by GitHub
parent 525cce3e92
commit cb69bb474c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 22 additions and 58 deletions

View file

@ -7,10 +7,9 @@ import os
import re
from typing import TYPE_CHECKING
import ansiwrap
from jrnl.color import colorize
from jrnl.color import highlight_tags_with_background_color
from jrnl.output import wrap_with_ansi_colors
if TYPE_CHECKING:
from .Journal import Journal
@ -129,7 +128,7 @@ class Entry:
columns = 79
# Color date / title and bold title
title = ansiwrap.fill(
title = wrap_with_ansi_colors(
date_str
+ " "
+ highlight_tags_with_background_color(
@ -143,35 +142,17 @@ class Entry:
body = highlight_tags_with_background_color(
self, self.body.rstrip(" \n"), self.journal.config["colors"]["body"]
)
body_text = [
colorize(
ansiwrap.fill(
line,
columns,
initial_indent=indent,
subsequent_indent=indent,
drop_whitespace=True,
),
self.journal.config["colors"]["body"],
)
or indent
for line in body.rstrip(" \n").splitlines()
]
# ansiwrap doesn't handle lines with only the "\n" character and some
# ANSI escapes properly, so we have this hack here to make sure the
# beginning of each line has the indent character and it's colored
# properly. textwrap doesn't have this issue, however, it doesn't wrap
# the strings properly as it counts ANSI escapes as literal characters.
# TL;DR: I'm sorry.
body = "\n".join(
[
body = wrap_with_ansi_colors(body, columns - len(indent))
if indent:
# Without explicitly colorizing the indent character, it will lose its
# color after a tag appears.
body = "\n".join(
colorize(indent, self.journal.config["colors"]["body"]) + line
if not ansiwrap.strip_color(line).startswith(indent)
else line
for line in body_text
]
)
for line in body.splitlines()
)
body = colorize(body, self.journal.config["colors"]["body"])
else:
title = (
date_str

View file

@ -131,3 +131,12 @@ def format_msg_text(msg: Message) -> Text:
text = textwrap.dedent(text)
text = text.strip()
return Text(text)
def wrap_with_ansi_colors(text: str, width: int) -> str:
richtext = Text.from_ansi(text, no_wrap=False, tab_size=None)
console = Console(width=width)
with console.capture() as capture:
console.print(richtext, sep="", end="")
return capture.get()