From 2c70130f2386e7d79a60113fb4e5376ab736f45f Mon Sep 17 00:00:00 2001 From: Zhang Yanpo Date: Sun, 22 Feb 2026 20:01:48 +0800 Subject: [PATCH] refactor: deduplicate tex_to_zhihu and tex_to_zhihu_url Extract shared logic (tex_to_zhihu_compatible call, align computation) into _zhihu_tex_params helper so changes to align logic only need to be made in one place. Co-Authored-By: Claude Opus 4.6 --- down2.py | 45 +++++++++++++-------------------------------- 1 file changed, 13 insertions(+), 32 deletions(-) diff --git a/down2.py b/down2.py index 506ee65..d0cbef5 100755 --- a/down2.py +++ b/down2.py @@ -88,6 +88,15 @@ def tex_to_zhihu_compatible(tex: str) -> tuple[str, str]: return tex, texurl +def _zhihu_tex_params(tex: str, block: bool) -> dict[str, str]: + """Prepare shared parameters for zhihu equation formatting.""" + tex, texurl = tex_to_zhihu_compatible(tex) + # zhihu uses double backslash to center-align a block equation. + align = "%5C%5C" if block else "" + altalign = "\\\\" if block else "" + return {"tex": tex, "texurl": texurl, "align": align, "altalign": altalign} + + def tex_to_zhihu_url(tex: str, block: bool) -> str: """ Convert tex source to a url linking to a svg on zhihu. @@ -103,20 +112,8 @@ def tex_to_zhihu_url(tex: str, block: bool) -> str: string of a ```` tag. """ - tex, texurl = tex_to_zhihu_compatible(tex) - - if block: - # zhihu use double back slash to center-align an equation. - align = "%5C%5C" - else: - align = "" - - url = zhihu_equation_url_fmt.format( - texurl=texurl, - align=align, - ) - - return url + p = _zhihu_tex_params(tex, block) + return zhihu_equation_url_fmt.format(texurl=p["texurl"], align=p["align"]) def tex_to_zhihu(tex: str, block: bool) -> str: @@ -134,24 +131,8 @@ def tex_to_zhihu(tex: str, block: bool) -> str: string of a ```` tag. """ - tex, texurl = tex_to_zhihu_compatible(tex) - - if block: - # zhihu use double back slash to center-align an equation. - align = "%5C%5C" - altalign = "\\\\" - else: - align = "" - altalign = "" - - url = zhihu_equation_fmt.format( - tex=tex, - texurl=texurl, - align=align, - altalign=altalign, - ) - - return url + p = _zhihu_tex_params(tex, block) + return zhihu_equation_fmt.format(**p) superscripts = {