Skip to content

Commit

Permalink
fix(inflow.py): recursively process paragraphs
Browse files Browse the repository at this point in the history
  • Loading branch information
stephen-huan committed Jan 20, 2024
1 parent ad7f842 commit 2651502
Showing 1 changed file with 23 additions and 13 deletions.
36 changes: 23 additions & 13 deletions inflow.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import sys

Block = tuple[list[str], int, str]

# characters allowed to be in a prefix
PREFIX = set(" >:-*|#$%'\"")

Expand Down Expand Up @@ -54,7 +56,7 @@ def vardp(
def process(par: list[str], width: int, prefix: str) -> str:
"""Takes in a paragraph and returns a string with a new line width."""
if len(par) == 0:
return ""
return prefix
assert max(map(len, par)) <= width, "line too long"

lines = get_lines(par, width)
Expand Down Expand Up @@ -84,8 +86,8 @@ def process(par: list[str], width: int, prefix: str) -> str:
return "\n".join(map(lambda x: prefix + x, out[::-1]))


def parse_prefix(lines: list[str]) -> tuple[list[str], str]:
"""Parses lines into a list of tokens, taking into account prefixes."""
def get_prefix(lines: list[str]) -> str:
"""Finds the common prefix for the lines."""
# find prefix, where a prefix is defined as a series
# of the same character, if the character is in PREFIX
prefix = []
Expand All @@ -98,30 +100,38 @@ def parse_prefix(lines: list[str]) -> tuple[list[str], str]:
prefix.append(lines[0][ch])
continue
break
prefix = "".join(prefix)
return "".join(prefix)

par = []
for line in lines:
par += line[len(prefix) :].split()

return par, prefix
def parse_prefix(lines: list[str], width: int) -> list[Block]:
"""Parses lines into a list of tokens, taking into account prefixes."""
prefix = get_prefix(lines)
if len(prefix) == 0:
par = []
for line in lines:
par += line.split()
return [(par, width, prefix)]
else:
lines = [line[len(prefix) :] for line in lines]
return [
(par, width, prefix)
for par, width, _ in parse_lines(lines, width - len(prefix))
]


def parse_lines(lines, width: int) -> list[tuple[list[str], int, str]]:
def parse_lines(lines, width: int) -> list[Block]:
"""Read input lines into paragraphs, making empty lines []."""
pars, par = [], []
for line in lines:
if line != "\n":
par.append(line)
else:
if len(par) > 0:
par, prefix = parse_prefix(par)
pars.append((par, width - len(prefix), prefix))
pars += parse_prefix(par, width)
pars.append(([], width, ""))
par, par = [], []
if len(par) > 0:
par, prefix = parse_prefix(par)
pars.append((par, width - len(prefix), prefix))
pars += parse_prefix(par, width)
return pars


Expand Down

0 comments on commit 2651502

Please sign in to comment.