frontend: typeset the LaTeX, and let a sentence start a new line

Two things a paper needs that the paragraph model could not express.

**Formulas.** A sentence stores the LaTeX the writer typed — `$\ell$`,
`$$ … \tag{1} $$` — because that is the editable form, and it was being printed
as source. `src/utils/math.ts` now splits a sentence into text and formulas,
gives the formulas to KaTeX and escapes everything else; `math-error` in red
when KaTeX cannot read one, rather than an exception that blanks the paragraph
(the paper in the database has 106 sentences with formulas, 29 of them
display). Four delimiters are recognised — `$$…$$`, `\[…\]`, `$…$`, `\(…\)` —
and an unmatched `$` is left alone instead of swallowing the rest of the
paragraph. A display formula is a block, so it takes its own line and centres
itself without any flagging; text goes through `v-html` escaped, and KaTeX runs
with trust off.

**Line breaks.** A paragraph is its sentences run together, which is right for
prose and wrong for a display formula, a list of items or an author line.
`paper_sentence.line_break_before` is that request: a flag rather than a
newline inside `content`, because content folds its whitespace on purpose (a
sentence really is one line) and because a break hidden in a string is one
nobody can see or remove. It prints a `<br>`, it is a checkbox on the
sentence's row in the editor, and it *replaces* the separator rather than
adding to it — the new line already separates, and a space as well would indent
the line by a blank.

Verified against the real paper in the browser: 214 inline formulas and 29
display formulas typeset with zero failures and no `$$` left on the page; a
sentence flagged for a break lands on its own line while its neighbour stays
inline; the display formula centres on a line of its own and the sentence after
it starts below. 54 paper checks (2 new), 61 reference checks and 76 MCP checks
pass, with `vue-tsc` and the build clean.

Also: `.pnpm-store/` is ignored — pnpm put its content-addressed store in the
project root rather than the home directory.
This commit is contained in:
2026-09-23 11:30:29 +08:00
parent b97aab6f30
commit 960450f744
14 changed files with 406 additions and 22 deletions
@@ -0,0 +1,48 @@
"""give a sentence the option to start a new line
A paragraph is its sentences concatenated, which is right for prose and wrong
for the things a paper also puts inside a paragraph: a display formula, a list
of items, an author line. Those want a line break between them, and until now
there was nowhere to say so — text pasted with newlines was folded onto one line
on purpose, so the writer had no way to ask for one.
So the sentence carries the request: ``line_break_before`` prints a break before
this sentence and nothing else. It is a property of the sentence rather than a
character in its content because the content is a sentence — folding whitespace
is what keeps it one — and because a break the writer cannot see cannot be
removed.
Existing rows default to 0: today's documents render exactly as they did.
Revision ID: f8c2d5a73b91
Revises: 063f6def01fa
Create Date: 2026-09-22
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "f8c2d5a73b91"
down_revision: str | None = "063f6def01fa"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def upgrade() -> None:
op.add_column(
"paper_sentence",
sa.Column(
"line_break_before",
sa.Boolean(),
server_default=sa.text("0"),
nullable=False,
),
)
def downgrade() -> None:
op.drop_column("paper_sentence", "line_break_before")
+11 -1
View File
@@ -419,7 +419,13 @@ def build_document(db: Session, paper: Paper) -> PaperDocumentRead:
# than by whoever prints them, so a reader, an export and a preview
# cannot each invent their own spacing.
for earlier, later in zip(sentences, sentences[1:]):
later.separator_before = sentence_separator(earlier.content, later.content)
later.separator_before = (
""
if later.line_break_before
# A line break already separates the two, and printing a space
# as well would indent the new line by one blank.
else sentence_separator(earlier.content, later.content)
)
paragraph = ParagraphRead(
paper_template_filed_sort=position,
@@ -678,6 +684,7 @@ def replace_paragraph(
paper_template_filed_sort=target,
sort=item.sort if item.sort is not None else base + offset,
content=item.content,
line_break_before=item.line_break_before,
citations=_build_citations(item.citations),
)
)
@@ -700,6 +707,7 @@ def append_sentence(db: Session, paper: Paper, data: SentenceCreate) -> PaperSen
paper_template_filed_sort=data.paper_template_filed_sort,
sort=sort,
content=data.content,
line_break_before=data.line_break_before,
citations=_build_citations(data.citations),
)
db.add(sentence)
@@ -729,6 +737,8 @@ def update_sentence(
sentence.paper_template_filed_sort = data.paper_template_filed_sort
if data.content is not None:
sentence.content = data.content
if data.line_break_before is not None:
sentence.line_break_before = data.line_break_before
if data.citations is not None:
sentence.citations.clear()
db.flush()
+16 -1
View File
@@ -31,7 +31,7 @@ is assembled on read from the paper's template plus these rows. See
from typing import TYPE_CHECKING
from sqlalchemy import ForeignKey, Index, Integer, Text
from sqlalchemy import Boolean, ForeignKey, Index, Integer, Text, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.db.base import Base
@@ -86,6 +86,21 @@ class PaperSentence(TimestampMixin, Base):
#: placeholder and renders as a blank line rather than disappearing.
content: Mapped[str] = mapped_column(Text, nullable=False, default="")
#: Print a line break before this sentence.
#:
#: A paragraph is its sentences concatenated, which is right for prose and
#: wrong for what else a paper puts inside one: a display formula, a list of
#: items, an author line. The break is a flag rather than a newline in
#: ``content`` for two reasons — content folds its whitespace so a sentence
#: really is one line, and a break hidden in a string is a break the writer
#: cannot see or remove.
line_break_before: Mapped[bool] = mapped_column(
Boolean,
nullable=False,
default=False,
server_default=text("0"),
)
paper: Mapped["Paper"] = relationship(back_populates="sentences")
#: References quoted by this sentence, in citation order. Eager-loaded
+6
View File
@@ -97,6 +97,8 @@ class SentenceInput(BaseModel):
sort: int | None = Field(default=None, ge=-1_000_000, le=1_000_000)
content: str = ""
#: Start a new line at this sentence rather than running on from the last.
line_break_before: bool = False
citations: list[CitationInput] = Field(default_factory=list)
@field_validator("content")
@@ -135,6 +137,7 @@ class SentenceUpdate(BaseModel):
default=None, ge=-1_000_000, le=1_000_000
)
content: str | None = None
line_break_before: bool | None = None
citations: list[CitationInput] | None = None
@field_validator("content")
@@ -168,6 +171,9 @@ class SentenceRead(BaseModel):
paper_template_filed_sort: int
sort: int
content: str
#: Whether a line break prints before this sentence. See
#: :attr:`app.models.paper_sentence.PaperSentence.line_break_before`.
line_break_before: bool
citations: list[CitationRead]
#: Text to print before this sentence when the paragraph is put back
#: together — ``""`` or a single space, never anything else. Derived on
+44 -9
View File
@@ -267,7 +267,42 @@ def main() -> int:
# Clear it again so the counts asserted below stay meaningful.
call("PUT", f"/papers/{paper['id']}/paragraphs/{second_sort}", {"sentences": []})
print("8. reject a citation with no quote")
print("8. a sentence can ask for a line break")
# The flag replaces the separator rather than adding to it: a break
# already separates the two, and a space as well would indent the new
# line by one blank.
broken = call(
"PUT",
f"/papers/{paper['id']}/paragraphs/{second_sort}",
{
"sentences": [
{"content": "连排的第一句。"},
{"content": "另起一行的一句。", "line_break_before": True},
{"content": "English runs on.", "line_break_before": True},
]
},
)
paragraph_breaks = next(
p
for p in broken["paragraphs"]
if p["paper_template_filed_sort"] == second_sort
)
check(
"the flag is stored per sentence",
[s["line_break_before"] for s in paragraph_breaks["sentences"]]
== [False, True, True],
str([s["line_break_before"] for s in paragraph_breaks["sentences"]]),
)
check(
"it also survives a read back",
all(
s["line_break_before"] is False or s["separator_before"] == ""
for s in paragraph_breaks["sentences"]
),
)
call("PUT", f"/papers/{paper['id']}/paragraphs/{second_sort}", {"sentences": []})
print("9. reject a citation with no quote")
bad = call(
"PUT",
f"/papers/{paper['id']}/paragraphs/{first_sort}",
@@ -285,7 +320,7 @@ def main() -> int:
)
check("citation without content refused", "detail" in bad)
print("9. a sentence with no paragraph in the template survives a switch")
print("10. a sentence with no paragraph in the template survives a switch")
# A position neither template defines, so the check means the same
# thing before and after the switch below.
orphan_sort = (
@@ -313,7 +348,7 @@ def main() -> int:
p for p in document["paragraphs"] if p["paper_template_filed_sort"] == orphan_sort
)["name"] is None)
print("10. switch the template")
print("11. switch the template")
switched = call("PATCH", f"/papers/{paper['id']}", {"template_id": narrow["id"]})
check("template changed", switched["template_id"] == narrow["id"])
document = call("GET", f"/papers/{paper['id']}/document")
@@ -343,7 +378,7 @@ def main() -> int:
),
)
print("11. move one paragraph onto another position")
print("12. move one paragraph onto another position")
document = call(
"PUT",
f"/papers/{paper['id']}/paragraphs/{orphan_sort}",
@@ -358,18 +393,18 @@ def main() -> int:
all(p["paper_template_filed_sort"] != orphan_sort for p in document["paragraphs"]),
)
print("12. paper list reports progress")
print("13. paper list reports progress")
listing = call("GET", f"/papers?keyword=冒烟&status=writing")
check("found by keyword and status", listing["total"] == 1, str(listing["total"]))
row = listing["items"][0]
check("paragraph count", row["paragraph_count"] == 1, str(row["paragraph_count"]))
check("sentence count", row["sentence_count"] == 3, str(row["sentence_count"]))
print("13. a template in use cannot be deleted")
print("14. a template in use cannot be deleted")
conflict = call("DELETE", f"/templates/{narrow['id']}", expect=409)
check("template delete refused", "正被论文使用" in conflict["detail"], conflict["detail"])
print("14. single sentence edit and delete")
print("15. single sentence edit and delete")
sentence_id = target["sentences"][0]["id"]
updated = call(
"PATCH",
@@ -385,7 +420,7 @@ def main() -> int:
sum(len(p["sentences"]) for p in document["paragraphs"]) == 2,
)
print("15. a paper with no template still works")
print("16. a paper with no template still works")
bare = call(
"POST",
"/papers",
@@ -408,7 +443,7 @@ def main() -> int:
call("DELETE", f"/papers/{bare['id']}", expect=204)
created_papers.remove(bare["id"])
print("16. delete the paper")
print("17. delete the paper")
call("DELETE", f"/papers/{paper['id']}", expect=204)
created_papers.clear()
for reference_id in created_references: