"""The text edits behind the markdown plan: filing an item in todo.md, changing one and removing one. Each returns new text; ranking.rank then orders the table and details and writes the derived cells.""" import re from plan.todo_table import cells, detail_heading, DETAILS, item_details, items_table, Table, tagline_text from failure import Failure from plan_store.plans import no_item from plan.ranking import stated # A line that would end ## Details (##) or could open another item's detail (###). HEADING = re.compile(r"^#{2,3} ", re.M) def added(todo: str, named: dict[str, str], detail: str, label: str) -> tuple[int, str] | Failure: """todo with an item filed under Next ID, and that ID; named holds its cells by column name, its Item cell the tagline, bold or not.""" next_id = stated(todo, "Next ID") if isinstance(next_id, Failure): return next_id if not next_id.isdigit(): return Failure(f"Next ID {next_id!r} is not a whole number") tagline = plain(named["Item"]) if unfit := unfit_text(tagline, detail): return unfit id_ = int(next_id) lines = re.sub(r"^`Next ID = [0-9]+`$", f"`Next ID = {id_ + 1}`", todo, count=1, flags=re.M).split("\n") table = held_table(lines, label) if isinstance(table, Failure): return table row = {**named, "ID": str(id_), "Item": bold_cell(tagline)} lines.insert(table.start + len(table.rows), "| " + " | ".join(row.get(column, "") for column in table.columns) + " |") return id_, with_detail("\n".join(lines), id_, tagline, detail) def edited(todo: str, id_: int, named: dict[str, str], detail: str | None, label: str) -> str | Failure: """todo with item id_'s cells set from named, which holds each new value by its column's name, and its detail set to detail unless None; an empty detail removes it. label is what a message calls the file.""" lines = todo.split("\n") table = held_table(lines, label) if isinstance(table, Failure): return table at = row_index(table, id_, label) if isinstance(at, Failure): return at if absent := [column for column in named if column not in table.columns]: return Failure(f"{label}'s items table has no {', '.join(absent)} column") held = cells(lines[at], len(table.columns)) details = item_details(todo) if isinstance(held, Failure): return held if isinstance(details, Failure): return details row = dict(zip(table.columns, held)) tagline = plain(named["Item"]) if "Item" in named else tagline_text(row["Item"]) kept = details.get(id_, "") if detail is None else detail if unfit := unfit_text(tagline, "" if detail is None else detail): return unfit row |= {**named, "Item": bold_cell(tagline)} lines[at] = "| " + " | ".join(row[column] for column in table.columns) + " |" return with_detail(without_detail("\n".join(lines), id_), id_, tagline, kept) def finished(todo: str, id_: int, label: str) -> str | Failure: """todo without item id_'s row and its detail.""" lines = todo.split("\n") table = held_table(lines, label) if isinstance(table, Failure): return table at = row_index(table, id_, label) if isinstance(at, Failure): return at del lines[at] return without_detail("\n".join(lines), id_) def plain(tagline: str) -> str: return tagline.strip().removeprefix("**").removesuffix("**") def bold_cell(tagline: str) -> str: """tagline as the Item cell holds it: bold, each | escaped.""" return "**" + re.sub(r"(? Failure | None: if "\n" in tagline: return Failure("the tagline holds a line break; keep it on one line") if HEADING.search(detail): return Failure("the detail holds a ## or ### heading, which would split ## Details; use #### or drop the #s") return None def with_detail(text: str, id_: int, tagline: str, detail: str) -> str: """text with detail first under ## Details, headed by id_ and tagline; text itself where detail is blank.""" if not detail.strip(): return text entry = f"{detail_heading(id_, tagline)}\n\n{detail.strip()}\n" section = DETAILS.search(text) if section is None: return text.rstrip("\n") + f"\n\n## Details\n\n{entry}" return text[:section.start(1)] + f"\n{entry}" + text[section.start(1):] def without_detail(text: str, id_: int) -> str: section = DETAILS.search(text) if section is None: return text body = re.sub(rf"^### {id_}\. .*?(?=^### \d+\. |\Z)", "", section.group(1), count=1, flags=re.M | re.S) return text[:section.start(1)] + body + text[section.end(1):] def row_index(table: Table, id_: int, label: str) -> int | Failure: """The index in the file's lines of item id_'s row.""" for at, row in enumerate(table.rows, table.start): found = cells(row, len(table.columns)) if isinstance(found, Failure): return found if found[0] == str(id_): return at return Failure(no_item(label, id_)) def held_table(lines: list[str], label: str) -> Table | Failure: table = items_table(lines) return Failure(f"{label} holds no items table; rank_todo.py --help shows one") if table is None else table