Skip to content
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

Fix highlighting issue when printing JSON that isn't indented #2038

Merged
merged 8 commits into from
Mar 8, 2022
Prev Previous commit
Some improvements on JSON highlighting
  • Loading branch information
darrenburns committed Mar 8, 2022
commit 94a10747c1e8e8e49791e862d3fe5c77e35871d3
11 changes: 6 additions & 5 deletions rich/highlighter.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ class JSONHighlighter(RegexHighlighter):

# Captures the start and end of JSON strings, handling escaped quotes
JSON_STR = r"(?<![\\\w])(?P<str>b?\".*?(?<!\\)\")"
JSON_WHITESPACE = {" ", "\n", "\r", "\t"}

base_style = "json."
highlights = [
Expand All @@ -125,18 +126,18 @@ def highlight(self, text: Text) -> None:
# Additional work to handle highlighting JSON keys
plain = text.plain
append = text.spans.append
whitespace = self.JSON_WHITESPACE
for match in re.finditer(self.JSON_STR, plain):
start, end = match.span()
cursor = end
while cursor < len(plain):
char = plain[cursor]
cursor += 1
if char in string.whitespace:
continue
elif char == ":":
if char == ":":
append(Span(start, end, "json.key"))
else:
break
elif char in whitespace:
continue
break


if __name__ == "__main__": # pragma: no cover
Expand Down