Skip to content

Commit e7daa54

Browse files
committed
feat(cli): support hyperlinks
1 parent cd453f9 commit e7daa54

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

cli.py

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,32 @@ def _write_markdown(path: str, query: str, result, *, stdout: bool = False) -> N
8888
f.write(content)
8989

9090

91+
def _add_hyperlink(paragraph, url: str, text: str):
92+
"""Add a clickable hyperlink to a python-docx paragraph."""
93+
from docx.oxml.ns import qn
94+
from docx.oxml import OxmlElement
95+
96+
part = paragraph.part
97+
r_id = part.relate_to(url, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink", is_external=True)
98+
99+
hyperlink = OxmlElement("w:hyperlink")
100+
hyperlink.set(qn("r:id"), r_id)
101+
102+
r = OxmlElement("w:r")
103+
rPr = OxmlElement("w:rPr")
104+
rStyle = OxmlElement("w:rStyle")
105+
rStyle.set(qn("w:val"), "Hyperlink")
106+
rPr.append(rStyle)
107+
r.append(rPr)
108+
109+
t = OxmlElement("w:t")
110+
t.text = text
111+
r.append(t)
112+
hyperlink.append(r)
113+
paragraph._p.append(hyperlink)
114+
return hyperlink
115+
116+
91117
def _write_docx(path: str, query: str, result, **_kwargs) -> None:
92118
"""Convert the markdown essay into a formatted DOCX document."""
93119
from docx import Document
@@ -129,7 +155,8 @@ def _write_docx(path: str, query: str, result, **_kwargs) -> None:
129155
doc.add_heading("Sources", level=1)
130156
for i, r in enumerate(result.results, 1):
131157
title = r.title or r.url
132-
doc.add_paragraph(f"{i}. {title}\n {r.url}", style="List Number")
158+
para = doc.add_paragraph(f"{i}. ", style="List Number")
159+
_add_hyperlink(para, r.url, title)
133160

134161
doc.save(path)
135162

0 commit comments

Comments
 (0)