Skip to content

Commit 14f4718

Browse files
committed
Better formatting for >>> in docstrings, fixes #49, fixes #163
1 parent 81db324 commit 14f4718

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

crates/zuban_python/src/name.rs

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -340,7 +340,7 @@ impl<'db, 'x> Name<'db, 'x> {
340340
debug_assert!(!name.file().is_stub());
341341
return name.documentation();
342342
}
343-
result
343+
docstr_to_markdown(result)
344344
}
345345

346346
pub fn class_symbols(&self) -> Option<impl ExactSizeIterator<Item = NameSymbol<'db>>> {
@@ -564,3 +564,32 @@ impl<'db> NameSymbol<'db> {
564564
})
565565
}
566566
}
567+
568+
fn docstr_to_markdown(s: Cow<str>) -> Cow<str> {
569+
if !s.contains(">>>") {
570+
return s;
571+
}
572+
let mut out_parts = vec![];
573+
let mut in_block = false;
574+
575+
for line in s.split_inclusive('\n') {
576+
if line.starts_with(">>>") {
577+
if !in_block {
578+
out_parts.push("```python\n");
579+
in_block = true;
580+
}
581+
} else if in_block && line.trim().is_empty() {
582+
out_parts.push("```\n");
583+
in_block = false;
584+
}
585+
out_parts.push(line);
586+
}
587+
588+
if in_block {
589+
if !out_parts.last().unwrap().ends_with('\n') {
590+
out_parts.push("\n");
591+
}
592+
out_parts.push("```\n");
593+
}
594+
Cow::Owned(out_parts.join(""))
595+
}

crates/zuban_python/tests/mypylike/tests/documentation.test

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,3 +235,23 @@ D
235235
__main__.py:12:documentation -> "```python\n(class) A(a, *, a2: str) -> A\n```\n---\na doc"
236236
__main__.py:14:documentation -> "```python\n(class) B() -> B\n```"
237237
__main__.py:16:documentation -> "```python\n(class) D(x: int, y: str = ...) -> D\n```"
238+
239+
[case documentation_doctests_formatting]
240+
def f() -> None:
241+
"""
242+
asdf
243+
>>> bla
244+
foo
245+
>>> 1
246+
bar
247+
248+
x
249+
250+
>>> hello
251+
"""
252+
253+
#? documentation
254+
f
255+
256+
[out]
257+
__main__.py:15:documentation -> "```python\n(function) def f() -> None\n```\n---\nasdf\n```python\n>>> bla\nfoo\n>>> 1\nbar\n```\n\nx\n\n```python\n>>> hello\n```\n"

0 commit comments

Comments
 (0)