diff --git a/Makefile b/Makefile index 3a1212983..b54b2079a 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ help: ## Show this help message @echo 'Usage: make [target]' @echo '' @echo 'Available targets:' - @awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf " %-20s %s\n", $$1, $$2}' $(MAKEFILE_LIST) + @awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z0-9_-]+:.*?## / {printf " %-20s %s\n", $$1, $$2}' $(MAKEFILE_LIST) .PHONY: test test: ## Run core tests (fast, no package builds) @@ -243,3 +243,104 @@ hub-deploy: ## Trigger GDG hub deployment to GitHub Pages (requires gh CLI) @gh workflow run deploy.yml --repo posit-dev/gdg \ -f great_docs_ref=$$(git rev-parse --abbrev-ref HEAD) && \ echo "Deployment triggered. Watch at: https://github.com/posit-dev/gdg/actions" + +# ── Quarto 2 (experimental) ────────────────────────────────────────────────── +# Q2 names the q2 binary: a path, or a command on PATH. The default is the first +# that exists of the one `make q2-install` puts in the project's environment, the +# one `make q2-upgrade` installs, a release build in a sibling checkout of +# quarto-dev/q2 (Q2_SRC), and `q2` on PATH. The Quarto 2 Gauntlet +# builds into its own directory, so it leaves the Quarto 1 build in +# test-packages/_rendered. +Q2_INSTALL_DIR ?= $(HOME)/.local/bin +Q2_SRC ?= ../q2 +Q2 ?= $(firstword $(wildcard $(dir $(PYTHON))q2 $(Q2_INSTALL_DIR)/q2 $(Q2_SRC)/target/release/q2) q2) +Q2_BIN = $(if $(findstring /,$(Q2)),$(abspath $(Q2)),$(Q2)) +Q2_RENDERED := test-packages/_rendered_q2 +Q2_PORT ?= 3334 +Q2_ENV = GREAT_DOCS_QUARTO="$(Q2_BIN)" GDG_RENDERED_DIR="$(CURDIR)/$(Q2_RENDERED)" \ + PATH="$(abspath $(dir $(PYTHON))):$$PATH" + +# Tests that render real projects with Quarto. Under Quarto 2 they run the +# bundled extensions and post-render scripts against q2's output. +Q2_RENDER_TESTS := \ + tests/test_markdown_pages_filter.py \ + tests/test_page_url_filter.py \ + tests/test_description_render.py \ + tests/test_metadata_partial_render.py \ + tests/test_social_cards_render.py \ + tests/test_shared_sidebar.py \ + tests/test_term_transcript.py \ + tests/test_term_bundle.py \ + tests/test_parallel_render.py + +.PHONY: q2-check +q2-check: ## Check that the Quarto 2 binary runs (override with Q2=path/to/q2) + @command -v "$(Q2_BIN)" > /dev/null 2>&1 || \ + (echo "Quarto 2 not found at $(Q2). Install it with 'make q2-install', or pass Q2=path/to/q2." && exit 1) + @echo "Quarto 2: $(Q2_BIN) ($$("$(Q2_BIN)" --version))" + +# Run q2's installer with the given options. Downloading it first, rather than +# piping curl into bash, makes a failed download fail the target. +Q2_INSTALLER := https://raw.githubusercontent.com/quarto-dev/q2/main/install.sh +q2_install = tmp=$$(mktemp) && trap 'rm -f "$$tmp"' EXIT && \ + curl -fsSL $(Q2_INSTALLER) -o "$$tmp" && bash "$$tmp" --dest "$(Q2_INSTALL_DIR)" $(1) + +.PHONY: q2-install +q2-install: ## Install or upgrade Quarto 2 from PyPI (the quarto2 package) in the project's environment + @uv pip install --python "$(PYTHON)" --upgrade quarto2 + +.PHONY: q2-upgrade +q2-upgrade: ## Install or upgrade Quarto 2 to the latest release in ~/.local/bin (Q2_VERSION=vX.Y.Z pins one; needs minisign) + @$(call q2_install,$(if $(Q2_VERSION),--version $(Q2_VERSION))) + +.PHONY: q2-upgrade-nightly +q2-upgrade-nightly: ## Install or upgrade Quarto 2 to the latest nightly build from main, in ~/.local/bin + @$(call q2_install,--nightly) + +.PHONY: q2-version +q2-version: ## Show the Quarto 2 in use, and the latest release, nightly build and commit on main + @echo "In use: $(Q2_BIN) ($$("$(Q2_BIN)" --version 2>/dev/null || echo not found))" + @if [ -d "$(Q2_SRC)/.git" ]; then \ + echo "Source checkout: $(Q2_SRC) at $$(git -C "$(Q2_SRC)" log -1 --format='%h (%cs)')"; \ + fi + @if command -v gh > /dev/null 2>&1; then \ + tag=$$(gh release view -R quarto-dev/q2 --json tagName --jq .tagName) && \ + echo "Latest release: $$tag ($$(gh api repos/quarto-dev/q2/commits/$$tag --jq '.sha[:9] + ", " + .commit.committer.date[:10]'))" && \ + echo "Latest nightly: $$(gh release view nightly -R quarto-dev/q2 --json name --jq '.name | sub("^q2 nightly "; "")')" && \ + echo "Latest on main: $$(gh api repos/quarto-dev/q2/commits/main --jq '.sha[:9] + " (" + .commit.committer.date[:10] + ") " + (.commit.message | split("\n")[0])')"; \ + else \ + echo "Install the gh CLI to see the latest release, nightly build and commit on main."; \ + fi + +.PHONY: q2-test +q2-test: q2-check ## Run the Quarto 2 unit tests, then the tests that render with Quarto, using Quarto 2 + @$(PYTHON) -m pytest tests/test_quarto_check.py tests/test_quarto_yml.py -q + @$(Q2_ENV) $(PYTHON) -m pytest $(Q2_RENDER_TESTS) -n auto -o faulthandler_timeout=120 $(Q2_TEST_ARGS) + +.PHONY: q2-test-gdg +q2-test-gdg: ## Run the GDG rendered-output tests against the Quarto 2 build (after q2-hub-build) + @test -d $(Q2_RENDERED) || (echo "No Quarto 2 GDG build found. Run 'make q2-hub-build' first." && exit 1) + @$(Q2_ENV) $(PYTHON) -m pytest tests/test_gdg_rendered.py -n auto $(Q2_TEST_ARGS) + +.PHONY: q2-hub-build +q2-hub-build: q2-check ## Full build of the Great Docs Gauntlet with Quarto 2, into test-packages/_rendered_q2 + @$(Q2_ENV) $(PYTHON) test-packages/render_all.py --build + +.PHONY: q2-hub-resume +q2-hub-resume: q2-check ## Resume an interrupted Quarto 2 GDG build (skip already-ok packages) + @$(Q2_ENV) $(PYTHON) test-packages/render_all.py --build --skip-ok + +.PHONY: q2-hub-rebuild +q2-hub-rebuild: q2-check ## Selective Quarto 2 GDG rebuild: make q2-hub-rebuild PKG="gdtest_minimal gdtest_github_icon" + @test -n "$(PKG)" || (echo "Usage: make q2-hub-rebuild PKG=\"name1 name2\"" && exit 1) + @$(Q2_ENV) $(PYTHON) test-packages/render_all.py --build --only $(PKG) + +.PHONY: q2-hub-serve +q2-hub-serve: ## Serve the Quarto 2 Great Docs Gauntlet locally (port 3334, or Q2_PORT) + @GDG_RENDERED_DIR="$(CURDIR)/$(Q2_RENDERED)" $(PYTHON) test-packages/render_all.py --serve --port $(Q2_PORT) + +.PHONY: q2-hub-open +q2-hub-open: ## Open the Quarto 2 Great Docs Gauntlet in the default browser + @open $(Q2_RENDERED)/_hub/index.html 2>/dev/null || \ + xdg-open $(Q2_RENDERED)/_hub/index.html 2>/dev/null || \ + echo "GDG page: $(Q2_RENDERED)/_hub/index.html" diff --git a/docs/user_guide/03-authoring-qmd-files.qmd b/docs/user_guide/03-authoring-qmd-files.qmd index 9c799588f..3532ccc88 100644 --- a/docs/user_guide/03-authoring-qmd-files.qmd +++ b/docs/user_guide/03-authoring-qmd-files.qmd @@ -199,7 +199,7 @@ Markdown provides several ways to emphasize text. Here's the syntax alongside wh |--------|--------|---------| | `*italic*` or `_italic_` | *italic* | Introducing terms, emphasis | | `**bold**` or `__bold__` | **bold** | Strong emphasis, important terms | -| `***bold italic***` | ***bold italic*** | Rare, combined emphasis | +| `***bold italic***` | **_bold italic_** | Rare, combined emphasis | | `` `code` `` | `code` | Function names, variables, file paths | | `~~strikethrough~~` | ~~strikethrough~~ | Deprecated or removed content | @@ -1034,7 +1034,7 @@ Write the path relative to the page's source file. A user guide page at When the `include` shortcode references a code file (anything other than `.qmd` or `.md`), Great Docs automatically wraps the file contents in a syntax-highlighted code block: -```markdown{shortcodes=false} +```{.markdown shortcodes=false} {{{< include src/mypackage/examples/demo.py >}}} ``` @@ -1055,7 +1055,7 @@ Generally, include shortcodes should not be enclosed in code blocks, as the form If your library already has runnable examples, tests, or configuration files that you want to showcase in the documentation, point `include` at them directly: -```markdown{shortcodes=false} +```{.markdown shortcodes=false} {{{< include src/mypackage/examples/usage.py >}}} {{{< include tests/test_core.py lines="12-30" >}}} {{{< include pyproject.toml >}}} diff --git a/docs/user_guide/04-writing-docstrings.qmd b/docs/user_guide/04-writing-docstrings.qmd index 57da1f990..d13ed0f2d 100644 --- a/docs/user_guide/04-writing-docstrings.qmd +++ b/docs/user_guide/04-writing-docstrings.qmd @@ -495,7 +495,7 @@ actual backend connection count. A mutable module-level variable is documented the same way as a constant, but its docstring should emphasize valid values, defaults, and what happens when a user changes it: -```python +````python timeout: int = 30 """Seconds to wait before abandoning a request. @@ -506,13 +506,14 @@ may want 120 or more. Examples -------- -```{python} +```{{python}} #| eval: false import mypackage mypackage.timeout = 60 # generous timeout for batch jobs -""" ``` +""" +```` ### Type Aliases diff --git a/docs/user_guide/12-cross-referencing.qmd b/docs/user_guide/12-cross-referencing.qmd index d8a1c4459..1731564fe 100644 --- a/docs/user_guide/12-cross-referencing.qmd +++ b/docs/user_guide/12-cross-referencing.qmd @@ -103,6 +103,12 @@ You can reference an object by a short name, writing `` [](`Cache`) `` rather th neither claims it: the reference renders unlinked rather than pointing at whichever object came first. Qualify the reference to fix it. +In a docstring, a reference that does not resolve on its own is also tried in the scope of the +documented object, nearest first. In the docstring of `mypkg.Frame.write`, `` [](`flush`) `` links +to `mypkg.Frame.flush` even when `mypkg.Cache.flush` also claims `flush`, so a See Also section +can name sibling methods as NumPy-style docstrings do. Code spans are not tried this way, since a +parameter often shares a method's name. + A name your package re-exports from a submodule outranks the other claims on it. If `mypkg/__init__.py` imports `findinds` from `mypkg.maths`, then `` [](`findinds`) `` links to that function even when a method `Frame.findinds` also claims the name, and the method stays reachable diff --git a/docs/user_guide/26-page-tags.qmd b/docs/user_guide/26-page-tags.qmd index 68b602f5a..2708ca6b5 100644 --- a/docs/user_guide/26-page-tags.qmd +++ b/docs/user_guide/26-page-tags.qmd @@ -17,6 +17,7 @@ Great Docs lets you categorize pages with tags for improved discoverability. Add guide, recipe, or custom section page via frontmatter, and Great Docs will generate a tags index page, render tag pills above page titles, and support hierarchical tag organization. +```{=html} +``` Tags are disabled by default. To enable them, add a `tags` section to `great-docs.yml`: diff --git a/docs/user_guide/27-page-status-badges.qmd b/docs/user_guide/27-page-status-badges.qmd index 6cae8fe36..866836f1a 100644 --- a/docs/user_guide/27-page-status-badges.qmd +++ b/docs/user_guide/27-page-status-badges.qmd @@ -61,6 +61,7 @@ color, and description: Here is how these five statuses look as page-level badges: +```{=html} +```
` element
+
+ Quarto 2 warns about each HTML tag in Markdown text (experimental), so for it the tags
+ are written as raw HTML inlines, which Pandoc reads as the same raw HTML.
+
+ Parameters
+ ----------
+ content
+ The Markdown text inside the element.
+
+ Returns
+ -------
+ :
+ The text between `` and `` tags.
+ """
+ if not _is_q2():
+ return Code(content).html
+ return f"``{{=html}}{content}``{{=html}}"
+
+
+_CODE_FENCE_RE = re.compile(r"^ {0,3}(`{3,}|~{3,})")
+# A list item or a definition, whose indented lines continue it
+_LIST_ITEM_RE = re.compile(r"^ {0,3}(?:[-*+:]|\d+[.)])(?:[ \t]|$)")
+
+
+def _code_blocks(lines: list[str]) -> list[tuple[int, int, bool]]:
+ """
+ Find the code blocks of docstring Markdown, as the start and end of their lines
+
+ A run of lines indented by four or more spaces is a code block when it follows a blank
+ line and does not continue a list item or a definition. Each block is returned with
+ whether it is indented; an indented block ends at its last non-blank line, and a fenced
+ block includes its fences.
+ """
+ blocks: list[tuple[int, int, bool]] = []
+ fence: str | None = None
+ start = 0
+ in_list = False
+ i = 0
+ while i < len(lines):
+ line = lines[i]
+ if fence is not None:
+ if line.strip().startswith(fence) and not line.strip().lstrip(fence[0]):
+ fence = None
+ blocks.append((start, i + 1, False))
+ i += 1
+ continue
+ opening = _CODE_FENCE_RE.match(line)
+ if opening is not None:
+ fence = opening.group(1)
+ start = i
+ i += 1
+ continue
+ indented = line.startswith((" ", "\t"))
+ after_blank = i == 0 or not lines[i - 1].strip()
+ if indented and line.strip() and after_blank and not in_list:
+ end = i
+ while end < len(lines) and (
+ not lines[end].strip() or lines[end].startswith((" ", "\t"))
+ ):
+ end += 1
+ while not lines[end - 1].strip():
+ end -= 1
+ blocks.append((i, end, True))
+ i = end
+ continue
+ if _LIST_ITEM_RE.match(line):
+ in_list = True
+ elif line.strip() and not line[0].isspace() and after_blank:
+ in_list = False
+ i += 1
+ # A fence that never closes runs to the end of the text
+ if fence is not None:
+ blocks.append((start, len(lines), False))
+ return blocks
+
+
+def fence_indented_code(s: str) -> str:
+ """
+ Rewrite the indented code blocks of docstring Markdown as fenced code blocks
+
+ Quarto 2 reads no indented code blocks, and reports an error for the Markdown inside one,
+ such as the formula under an RST `.. math::` directive (experimental). Pandoc reads both
+ forms as the same code block, so for Quarto 1 the text is returned unchanged. A run of
+ lines indented by four or more spaces is a code block when it follows a blank line and
+ does not continue a list item or a definition.
+ """
+ if not _is_q2():
+ return s
+ lines = s.split("\n")
+ output: list[str] = []
+ pos = 0
+ for start, end, indented in _code_blocks(lines):
+ if not indented:
+ continue
+ output.extend(lines[pos:start])
+ block = [row[1:] if row.startswith("\t") else row[4:] for row in lines[start:end]]
+ longest = max((len(run) for run in re.findall(r"`+", "\n".join(block))), default=0)
+ marker = "`" * max(3, longest + 1)
+ output.extend([marker, *block, marker])
+ pos = end
+ output.extend(lines[pos:])
+ return "\n".join(output)
+
+
+# The tag-like text that `escape_placeholders` escapes, and the text it copies unchanged:
+# backslash escapes, code spans, math, comments and shortcodes
+_PLACEHOLDER_RE = re.compile(
+ r"(?P\\[\s\S]"
+ r"|(?`+)(?!`)[\s\S]*?(?"
+ r"|\{\{<[\s\S]*?>\}\})"
+ r"|<(?P/?[A-Za-z][A-Za-z0-9_]*)>"
+)
+# The elements a browser renders, so that a tag naming one is HTML the docstring means
+_HTML_ELEMENTS = frozenset(
+ "a abbr acronym address applet area article aside audio b base basefont bdi bdo big "
+ "blink blockquote body br button canvas caption center cite code col colgroup data "
+ "datalist dd del details dfn dialog dir div dl dt em embed fieldset figcaption figure "
+ "font footer form frame frameset h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe "
+ "img input ins kbd label legend li link main map mark marquee math menu menuitem meta "
+ "meter nav nobr noframes noscript object ol optgroup option output p param picture pre "
+ "progress q rp rt ruby s samp script search section select slot small source span "
+ "strike strong style sub summary sup svg table tbody td template textarea tfoot th "
+ "thead time title tr track tt u ul var video wbr".split()
+)
+
+
+def escape_placeholders(s: str) -> str:
+ """
+ Escape the placeholders in docstring Markdown that read as HTML tags
+
+ A docstring may write a placeholder as `az:///` or a type as
+ `List`. Markdown reads `` as an HTML tag, and the browser shows nothing
+ for an element it doesn't know. The `<` of a tag without attributes is escaped when its
+ name is no HTML element and, having no hyphen, no custom element either. Fenced and
+ indented code, code spans, math, comments and shortcodes are unchanged. Applies to
+ Quarto 1 and Quarto 2.
+
+ Parameters
+ ----------
+ s
+ Docstring Markdown.
+
+ Returns
+ -------
+ :
+ The Markdown with a backslash before each placeholder's `<`.
+ """
+ if "<" not in s:
+ return s
+
+ def escape(match: re.Match[str]) -> str:
+ name = match.group("name")
+ if name is None or name.lstrip("/").lower() in _HTML_ELEMENTS:
+ return match.group(0)
+ return "\\" + match.group(0)
+
+ lines = s.split("\n")
+ output: list[str] = []
+ pos = 0
+ for start, end, _ in [*_code_blocks(lines), (len(lines), len(lines), False)]:
+ if start > pos:
+ output.append(_PLACEHOLDER_RE.sub(escape, "\n".join(lines[pos:start])))
+ if end > start:
+ output.append("\n".join(lines[start:end]))
+ pos = end
+ return "\n".join(output)
+
+
+def docstring_markdown(s: str) -> str:
+ """
+ Prepare docstring Markdown for the page
+
+ Fence indented code for Quarto 2 (experimental), escape placeholders that read as HTML
+ tags, as `escape_placeholders` does, then escape what Quarto 2 rejects or reads
+ differently from Pandoc, as `escape_prose` does.
+ """
+ return escape_prose(escape_placeholders(fence_indented_code(s)))
+
+
+# Text that `escape_prose` copies unchanged: backslash escapes, shortcodes, code spans,
+# math, HTML tags and comments, autolinks, link destinations, attribute blocks after a
+# span, link or code span, and attribute blocks that end a line, as on a heading
+_PROSE_KEEP_RE = re.compile(
+ r"\\[!-/:-@\[-`{-~]"
+ r"|\{\{<[\s\S]*?>\}\}"
+ r"|(?`+)(?!`)[\s\S]*?(?"
+ r"|<(?:https?|ftp|mailto):[^\s<>]+>"
+ r"|?[A-Za-z][A-Za-z0-9-]*(?:\s[^<>]*)?/?>"
+ r"|(?<=\])\([^\s()]*(?:\([^\s()]*\)[^\s()]*)*(?:\s+\"[^\"]*\")?\)"
+ r"|(?<=[\]\)`])\{[^{}\n]*\}"
+ r"|\{[#.][\w-][^{}\n]*\}(?=[ \t]*(?:\n|$))"
+)
+# A line that starts a block of its own: a list item, a definition, a heading or a div fence
+_BLOCK_START_RE = re.compile(r"^[ \t]*(?:(?:[-*+:]|\d+[.)])(?:[ \t]|$)|#{1,6}[ \t]|:::)")
+_DIV_FENCE_RE = re.compile(r"^[ \t]*:::")
+_PUNCTUATION = frozenset("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~")
+# Punctuation that Quarto 2 lets an apostrophe follow, as in `b.'s` and `` `x`'s ``
+_APOSTROPHE_AFTER = frozenset('!"-.?`')
+
+
+def escape_prose(s: str) -> str:
+ """
+ Escape the docstring Markdown that Quarto 2 rejects or reads differently (experimental)
+
+ Quarto 2 reports an error for an unclosed emphasis such as `*args`, an unpaired double
+ quote, a single quote it reads as opening a quotation, as in `(b)'s`, a lone `$` or a
+ brace outside attribute syntax, and reads a bracketed `[x]` with
+ no link as a span, dropping its brackets. Pandoc reads all of these as text. Escape them,
+ and an unmatched backtick, in each paragraph, list item and heading outside fenced code,
+ code spans, math, HTML tags, shortcodes and attribute blocks. For Quarto 1 the text is
+ returned unchanged.
+ """
+ if not _is_q2():
+ return s
+ output: list[str] = []
+ block: list[str] = []
+ fence: str | None = None
+
+ def flush() -> None:
+ if block:
+ output.append(_escape_prose_block("\n".join(block)))
+ block.clear()
+
+ for line in s.split("\n"):
+ if fence is not None:
+ if line.strip().startswith(fence) and not line.strip().lstrip(fence[0]):
+ fence = None
+ output.append(line)
+ continue
+ opening = _CODE_FENCE_RE.match(line)
+ if opening is not None or _DIV_FENCE_RE.match(line) or not line.strip():
+ flush()
+ fence = opening.group(1) if opening is not None else None
+ output.append(line)
+ continue
+ if _BLOCK_START_RE.match(line):
+ flush()
+ block.append(line)
+ flush()
+ return "\n".join(output)
+
+
+def _escape_prose_block(text: str) -> str:
+ """Escape the Markdown that Quarto 2 rejects in one paragraph, list item or heading"""
+ kept = [False] * len(text)
+ for match in _PROSE_KEEP_RE.finditer(text):
+ kept[match.start() : match.end()] = [True] * (match.end() - match.start())
+ free = [i for i, char in enumerate(text) if not kept[i]]
+ escape: set[int] = set()
+
+ # Brackets that are not a link, image, span, footnote or citation
+ stack: list[int] = []
+ for i in free:
+ if text[i] == "[":
+ stack.append(i)
+ elif text[i] == "]":
+ if not stack:
+ escape.add(i)
+ continue
+ start = stack.pop()
+ after = text[i + 1 : i + 2]
+ before = text[start - 1 : start] if start else ""
+ first = text[start + 1 : start + 2]
+ if not (after in ("(", "{", "[") or before == "!" or first in ("^", "@")):
+ escape.update((start, i))
+ escape.update(stack)
+
+ # Braces and dollar signs outside attribute blocks and math, and unmatched backticks
+ escape.update(i for i in free if text[i] in "{}$`")
+
+ # Double quotes, all of them when any cannot open or close a quotation
+ quotes = [i for i in free if text[i] == '"']
+ is_open = unpaired = False
+ for i in quotes:
+ before = text[i - 1] if i else " "
+ after = text[i + 1] if i + 1 < len(text) else " "
+ if not is_open and not after.isspace() and (before.isspace() or before in _PUNCTUATION):
+ is_open = True
+ elif is_open and not before.isspace():
+ is_open = False
+ else:
+ unpaired = True
+ break
+ if unpaired or is_open:
+ escape.update(quotes)
+
+ # Single quotes after other punctuation, as in `(b)'s`, all of them when any cannot
+ # open or close a quotation. One after a letter is an apostrophe that may close one.
+ quotes = []
+ is_open = unpaired = False
+ for i in free:
+ if text[i] != "'":
+ continue
+ before = text[i - 1] if i else " "
+ after = text[i + 1] if i + 1 < len(text) else " "
+ if before.isalnum() or before in _APOSTROPHE_AFTER:
+ if is_open and (after.isspace() or after in _PUNCTUATION):
+ is_open = False
+ continue
+ quotes.append(i)
+ if not is_open and not after.isspace():
+ is_open = True
+ elif is_open and not before.isspace():
+ is_open = False
+ else:
+ unpaired = True
+ if unpaired or is_open:
+ escape.update(quotes)
+
+ # Emphasis delimiters that open but are never closed
+ escape.update(_unclosed_emphasis(text, free))
+
+ return "".join(f"\\{char}" if i in escape else char for i, char in enumerate(text))
+
+
+def _unclosed_emphasis(text: str, free: list[int]) -> set[int]:
+ """Return the positions of `*` and `_` runs that can open emphasis but are never closed"""
+ runs: list[tuple[int, int]] = []
+ for i in free:
+ if text[i] in "*_" and runs and runs[-1][1] == i and text[runs[-1][0]] == text[i]:
+ runs[-1] = (runs[-1][0], i + 1)
+ elif text[i] in "*_":
+ runs.append((i, i + 1))
+
+ openers: list[tuple[int, int]] = []
+ for start, end in runs:
+ char = text[start]
+ before = text[start - 1] if start else " "
+ after = text[end] if end < len(text) else " "
+ left = not after.isspace() and (
+ after not in _PUNCTUATION or before.isspace() or before in _PUNCTUATION
+ )
+ right = not before.isspace() and (
+ before not in _PUNCTUATION or after.isspace() or after in _PUNCTUATION
+ )
+ if char == "_":
+ left, right = left and not before.isalnum(), right and not after.isalnum()
+ same = [k for k, (opener, _) in enumerate(openers) if text[opener] == char]
+ if right and same:
+ del openers[same[-1] :]
+ elif left:
+ openers.append((start, end))
+ return {i for start, end in openers for i in range(start, end)}
+
+
+def _is_q2() -> bool:
+ from .._build import quarto
+
+ return quarto.is_q2()
+
+
+def _escape_doubled_braces(s: str) -> str:
+ """
+ Write runs of braces as character references, for Quarto 2 (experimental)
+
+ Quarto 2 rejects `{{` and `}}` in Markdown.
+ """
+ if not _is_q2():
+ return s
+ s = re.sub(r"\{\{+", lambda m: "{" * len(m.group()), s)
+ return re.sub(r"\}\}+", lambda m: "}" * len(m.group()), s)
+
+
def _highlight_func(m: re.Match[str]) -> str:
"""
Wrap the matched group in a `Span` for a string
@@ -353,7 +746,7 @@ def pretty_code(s: str) -> str:
The dedented code with highlighted values, ` ` indents, `
` line
breaks and escaped quotes.
"""
- return escape_quotes(escape_indents(highlight_repr_value(dedent(s))))
+ return escape_quotes(escape_indents(highlight_repr_value(_escape_doubled_braces(dedent(s)))))
def render_formatted_expr(el: gf.Expr) -> str:
@@ -375,7 +768,7 @@ def render_formatted_expr(el: gf.Expr) -> str:
newlines with the `
` tag.
"""
el_str = format_str(str(el))
- return pretty_code(el_str)
+ return pretty_code(escape_code_text(el_str))
@lru_cache(1)
@@ -456,4 +849,4 @@ def format_value(value: str | gf.Expr | None = None) -> str:
Escaped and highlighted markdown represenation of the value.
It is not markedup as code.
"""
- return pretty_code(repr_obj(value))
+ return pretty_code(escape_code_text(repr_obj(value)))
diff --git a/great_docs/_apiref/_rendering/attributes.py b/great_docs/_apiref/_rendering/attributes.py
index 7681bbd4a..b6e48a3f6 100644
--- a/great_docs/_apiref/_rendering/attributes.py
+++ b/great_docs/_apiref/_rendering/attributes.py
@@ -13,8 +13,8 @@
from great_docs.pandoc.blocks import Blocks, Div
from great_docs.pandoc.components import Attr
-from great_docs.pandoc.inlines import Code
+from .._format import code_html
from ._context import _RenderingPurpose
from .objects import ObjectRenderer
@@ -62,7 +62,7 @@ def render_signature(self) -> BlockContent:
term = self.render_variable_definition(name, annotation, default)
return Div(
- Code(str(term)).html,
+ code_html(str(term)),
Attr(classes=["doc-signature", f"doc-{self.kind_slug}"]),
)
diff --git a/great_docs/_apiref/_rendering/objects.py b/great_docs/_apiref/_rendering/objects.py
index 9ad547868..beac68970 100644
--- a/great_docs/_apiref/_rendering/objects.py
+++ b/great_docs/_apiref/_rendering/objects.py
@@ -31,7 +31,7 @@
Para,
)
from great_docs.pandoc.components import Attr
-from great_docs.pandoc.inlines import Code, Inline, Inlines, Inlines0, Link, Span
+from great_docs.pandoc.inlines import Inline, Inlines, Inlines0, Link, Span
from .. import content
from .._docstring_sections import (
@@ -46,6 +46,10 @@
from .._docstring_summary import summary_lines
from .._format import (
HAS_RUFF,
+ code_html,
+ docstring_markdown,
+ escape_code_text,
+ escape_prose,
format_name,
format_see_also,
format_value,
@@ -352,7 +356,9 @@ def _render(ann: Annotation | None) -> str:
if ann is None:
return ""
elif isinstance(ann, str):
- return repr_obj(ann)
+ # The syntax and literals between names, such as the `*` of `*Ts`
+ # and the brackets of `list[str]`
+ return escape_code_text(repr_obj(ann))
elif isinstance(ann, gf.ExprName):
return markdown_escape(ann.name)
else:
@@ -393,7 +399,9 @@ def render_variable_definition(
items: list[InlineContentItem] = []
if name:
- items.append(Span(name, Attr(classes=["doc-parameter-name"])))
+ # Escape `**kwargs`, `global_` and the brackets of `Alias[T]`: Quarto 2 reads
+ # them as unclosed emphasis and as a span
+ items.append(Span(escape_code_text(name), Attr(classes=["doc-parameter-name"])))
if annotation:
if isinstance(annotation, gf.Expr):
@@ -404,6 +412,9 @@ def render_variable_definition(
if HAS_RUFF and len(str(annotation)) > 79
else self.render_annotation(annotation)
)
+ else:
+ # A docstring's type text, such as `a {str:DataType} dict`, is Markdown
+ annotation = escape_prose(annotation)
items.extend(
[
@@ -698,9 +709,9 @@ def render_text_section(self, el: gf.DocstringSectionText) -> BlockContent:
Returns
-------
:
- The text as written in the docstring.
+ The text as written in the docstring, prepared for Quarto 2 by `docstring_markdown`.
"""
- return el.value
+ return docstring_markdown(el.value)
def render_examples_section(self, el: gf.DocstringSectionExamples) -> BlockContent:
"""
@@ -737,7 +748,7 @@ def _render_example_fragment(self, fragment: object) -> BlockContent:
if isinstance(el, ExampleCode):
return CodeBlock(el.value, Attr(classes=["python"]))
if isinstance(el, ExampleText):
- return el.value
+ return docstring_markdown(el.value)
return ""
def render_deprecated_section(self, el: gf.DocstringSectionDeprecated) -> BlockContent:
@@ -784,9 +795,9 @@ def render_admonition_section(self, el: gf.DocstringSectionAdmonition) -> BlockC
Returns
-------
:
- The section's description.
+ The section's description, prepared for Quarto 2 by `docstring_markdown`.
"""
- return el.value.description
+ return docstring_markdown(el.value.description)
def render_warnings_section(self, el: DocstringSectionWarnings) -> BlockContent:
"""
@@ -800,9 +811,9 @@ def render_warnings_section(self, el: DocstringSectionWarnings) -> BlockContent:
Returns
-------
:
- The text as written in the docstring.
+ The text as written in the docstring, prepared for Quarto 2 by `docstring_markdown`.
"""
- return el.value
+ return docstring_markdown(el.value)
def render_notes_section(self, el: DocstringSectionNotes) -> BlockContent:
"""
@@ -816,9 +827,9 @@ def render_notes_section(self, el: DocstringSectionNotes) -> BlockContent:
Returns
-------
:
- The text as written in the docstring.
+ The text as written in the docstring, prepared for Quarto 2 by `docstring_markdown`.
"""
- return el.value
+ return docstring_markdown(el.value)
def render_see_also_section(self, el: DocstringSectionSeeAlso) -> BlockContent:
"""
@@ -909,8 +920,8 @@ def render_section_item(el: DocstringDefinitionType) -> DefinitionItem:
# references can be processed. Pandoc does not process any markup
# within backquotes `...`, but it does if the markup is within
# html code tags.
- desc = el.description or ""
- return Code(str(term)).html, desc
+ desc = docstring_markdown(el.description or "")
+ return code_html(str(term)), desc
# For Returns/Yields/Receives, merge consecutive unnamed items that
# share the same annotation (griffe splits continuation paragraphs
diff --git a/great_docs/_apiref/_rendering/type_aliases.py b/great_docs/_apiref/_rendering/type_aliases.py
index b4afba71c..97c9d6d22 100644
--- a/great_docs/_apiref/_rendering/type_aliases.py
+++ b/great_docs/_apiref/_rendering/type_aliases.py
@@ -14,9 +14,9 @@
from great_docs.pandoc.blocks import Blocks, Div
from great_docs.pandoc.components import Attr
-from great_docs.pandoc.inlines import Code, Inlines0, Span
+from great_docs.pandoc.inlines import Inlines0, Span
-from .._format import HAS_RUFF, format_value, render_formatted_expr
+from .._format import HAS_RUFF, code_html, format_value, markdown_escape, render_formatted_expr
from ._type_parameters import render_type_parameters
from .objects import ObjectRenderer
@@ -81,7 +81,8 @@ def render_signature(self) -> BlockContent:
items: list[InlineContentItem] = [
Span("type", Attr(classes=[f"doc-{self.kind_slug}-keyword", "kw"])),
" ",
- Span(declared, Attr(classes=["doc-parameter-name"])),
+ # Escape `*Ts` and `**P`: Quarto 2 reads them as unclosed emphasis
+ Span(markdown_escape(declared), Attr(classes=["doc-parameter-name"])),
]
value = self.obj.value
@@ -96,7 +97,7 @@ def render_signature(self) -> BlockContent:
)
return Div(
- Code(str(Inlines0(items))).html,
+ code_html(str(Inlines0(items))),
Attr(classes=["doc-signature", f"doc-{self.kind_slug}"]),
)
diff --git a/great_docs/_apiref/_signature.py b/great_docs/_apiref/_signature.py
index e53445f97..c9f45d5c4 100644
--- a/great_docs/_apiref/_signature.py
+++ b/great_docs/_apiref/_signature.py
@@ -9,9 +9,10 @@
from great_docs.pandoc.blocks import CodeBlock, Div
from great_docs.pandoc.components import Attr
-from great_docs.pandoc.inlines import Code, Span
+from great_docs.pandoc.inlines import Span
-from ._format import escape_indents, escape_quotes, highlight_repr_value
+from ._format import code_html, escape_indents, escape_quotes, highlight_repr_value
+from ._signature_spans import signature_spans
if TYPE_CHECKING:
from great_docs.pandoc.blocks import BlockContent
@@ -280,9 +281,15 @@ def render_signature_block(
# by `_mark_parameter`, and `highlight_repr_value`'s string pattern is
# unanchored, so running it again over the whole signature would match
# the quotes already inside that markup and wrap them a second time.
- return Div(Code(escape_quotes(escape_indents(marked))).html, attr)
+ return Div(code_html(escape_quotes(escape_indents(marked))), attr)
+
+ from .._build import quarto
text = "\n".join(text for text, _ in lines)
# Quarto highlights `pythonsignature` with the grammar the build supplies,
- # which marks callable names apart from parameter names.
- return Div(CodeBlock(text, Attr(classes=["pythonsignature"])), attr)
+ # which marks callable names apart from parameter names. Quarto 2
+ # (experimental) reads no grammars, so the block lists its spans instead.
+ attributes: dict[str, str] = {}
+ if quarto.is_q2():
+ attributes["data-hl-spans"] = signature_spans(text).replace('"', '\\"')
+ return Div(CodeBlock(text, Attr(classes=["pythonsignature"], attributes=attributes)), attr)
diff --git a/great_docs/_apiref/_signature_spans.py b/great_docs/_apiref/_signature_spans.py
new file mode 100644
index 000000000..0dcfcfc11
--- /dev/null
+++ b/great_docs/_apiref/_signature_spans.py
@@ -0,0 +1,224 @@
+"""
+The highlight spans of a `pythonsignature` block, for Quarto 2 (experimental)
+
+Quarto 1 highlights `pythonsignature` blocks with the grammar in `pythonsignature.xml`. Quarto 2
+reads no such grammars, but it highlights a code block whose `data-hl-spans` attribute lists
+the spans, as `[start, end, capture]` triples with byte offsets into the code. It writes each
+span as ``, with any `.` in the capture written as `-`. This module
+applies the grammar's rules, so that a signature has the same tokens under both Quartos.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import xml.etree.ElementTree as ET
+from functools import cache
+from pathlib import Path
+
+__all__ = ["LINE_CAPTURE", "signature_spans"]
+
+_GRAMMAR = Path(__file__).parents[1] / "assets" / "pythonsignature.xml"
+
+LINE_CAPTURE = "signature.line"
+"""The capture of the span around each line, standing in for Quarto 1's line `span`"""
+
+# The capture for each of the grammar's attributes. Where Quarto 2 has a capture for the
+# skylighting token that Quarto 1 gives an attribute, the span uses it, so Quarto 2's
+# translation of the highlight style colours the span as Quarto 1 does.
+_CAPTURES = {
+ "Name": "function",
+ "Class": "type",
+ "Variable": "variable",
+ "Builtin": "function.builtin",
+ "Exception": "extension",
+ "StringPrefix": "extension",
+ "Keyword": "keyword",
+ "None": "constant",
+ "Bool": "boolean",
+ "Int": "number",
+ "Float": "number",
+ "String": "string",
+ "Operator": "operator",
+}
+
+# The grammar's word lists, in the order its rules try them
+_WORD_LISTS = (
+ ("nones", "None"),
+ ("bools", "Bool"),
+ ("builtins", "Builtin"),
+ ("exceptions", "Exception"),
+ ("keywords", "Keyword"),
+ ("wordops", "Operator"),
+)
+
+# Skylighting's default keyword delimiters. A listed word matches only when it begins after
+# one of them, or at the start of a line, and ends before one.
+_DELIMITERS = frozenset(" \t.():!+,-<=>%&*/;?[]^{|}~\\")
+
+_IDENT = r"[^\W\d]\w*"
+_CLASS_RE = re.compile(rf"{_IDENT}(?=\.{_IDENT}(\(|$))")
+_NAME_RE = re.compile(rf"{_IDENT}(?=\(|$)")
+_IDENT_RE = re.compile(_IDENT)
+_PREFIX_RE = re.compile(r"[bBrRuUfF]{1,2}(?=[\"'])")
+_FLOAT_RE = re.compile(r"(\d+\.\d*|\.\d+)([eE][+-]?\d+)?|\d+[eE][+-]?\d+")
+_INT_RE = re.compile(r"\d+")
+# Skylighting's `HlCStringChar`: a C escape sequence
+_ESCAPE_RE = re.compile(r"\\(?:[abefnrtv\"'?\\]|x[0-9A-Fa-f]+|[0-7]{1,3})")
+_OPERATORS = frozenset("=*/|-+.<>%&^~@!")
+
+
+@cache
+def _word_lists() -> tuple[tuple[frozenset[str], str], ...]:
+ """
+ Read the grammar's word lists, each with the attribute its rule gives
+
+ Returns
+ -------
+ :
+ One pair for each list, in the order the grammar's rules try them.
+ """
+ root = ET.parse(_GRAMMAR).getroot()
+ lists = {
+ element.get("name"): frozenset(item.text or "" for item in element.iter("item"))
+ for element in root.iter("list")
+ }
+ return tuple((lists[name], attribute) for name, attribute in _WORD_LISTS)
+
+
+def _listed_word(line: str, pos: int) -> tuple[int, str] | None:
+ """
+ Match a word from one of the grammar's lists at a position in a line
+
+ Parameters
+ ----------
+ line
+ A line of the signature.
+ pos
+ The position of the word's first character.
+
+ Returns
+ -------
+ :
+ The end of the word and its attribute, or `None` when no listed word begins there.
+ """
+ if pos > 0 and line[pos - 1] not in _DELIMITERS:
+ return None
+ end = pos
+ while end < len(line) and line[end] not in _DELIMITERS:
+ end += 1
+ word = line[pos:end]
+ for words, attribute in _word_lists():
+ if word in words:
+ return end, attribute
+ return None
+
+
+def _line_tokens(line: str) -> list[tuple[int, int, str]]:
+ """
+ Split a line of a signature into the grammar's tokens
+
+ Parameters
+ ----------
+ line
+ A line of the signature, without its line break.
+
+ Returns
+ -------
+ :
+ The start, end and attribute of each token, as character positions in the line.
+ Adjacent tokens with the same attribute are one token, and text without an
+ attribute has no token.
+ """
+ tokens: list[tuple[int, int, str]] = []
+
+ def add(start: int, end: int, attribute: str) -> int:
+ if tokens and tokens[-1][2] == attribute and tokens[-1][1] == start:
+ tokens[-1] = (tokens[-1][0], end, attribute)
+ else:
+ tokens.append((start, end, attribute))
+ return end
+
+ pos = 0
+ context = "Start"
+ quote = ""
+ while pos < len(line):
+ char = line[pos]
+ if context == "String":
+ escape = _ESCAPE_RE.match(line, pos)
+ end = escape.end() if escape else pos + 1
+ if not escape and char == quote:
+ context = "Start"
+ pos = add(pos, end, "String")
+ continue
+ if context == "Qualified":
+ name = _IDENT_RE.match(line, pos)
+ if char == ".":
+ pos = add(pos, pos + 1, "Operator")
+ elif name:
+ context = "Start"
+ pos = add(pos, name.end(), "Name")
+ else:
+ pos += 1
+ continue
+ if pos == 0 and (match := _CLASS_RE.match(line)):
+ context = "Qualified"
+ pos = add(pos, match.end(), "Class")
+ continue
+ if pos == 0 and (match := _NAME_RE.match(line)):
+ pos = add(pos, match.end(), "Name")
+ continue
+ if listed := _listed_word(line, pos):
+ pos = add(pos, *listed)
+ continue
+ for pattern, attribute in (
+ (_PREFIX_RE, "StringPrefix"),
+ (_IDENT_RE, "Variable"),
+ (_FLOAT_RE, "Float"),
+ (_INT_RE, "Int"),
+ ):
+ if match := pattern.match(line, pos):
+ pos = add(pos, match.end(), attribute)
+ break
+ else:
+ if char in "\"'":
+ context = "String"
+ quote = char
+ pos = add(pos, pos + 1, "String")
+ elif char in _OPERATORS:
+ pos = add(pos, pos + 1, "Operator")
+ else:
+ pos += 1
+ return tokens
+
+
+def signature_spans(text: str) -> str:
+ """
+ Build the `data-hl-spans` value that highlights a signature as Quarto 1 does
+
+ Parameters
+ ----------
+ text
+ The signature, one line per `@overload` variant or wrapped parameter.
+
+ Returns
+ -------
+ :
+ The spans as JSON: each token's span, then a `LINE_CAPTURE` span around its line.
+ """
+ spans: list[tuple[int, int, str]] = []
+ offset = 0
+ for line in text.split("\n"):
+ # Byte offsets into the UTF-8 code, at each character of the line
+ positions = [offset]
+ for char in line:
+ positions.append(positions[-1] + len(char.encode()))
+ spans.extend(
+ (positions[start], positions[end], _CAPTURES[attribute])
+ for start, end, attribute in _line_tokens(line)
+ )
+ # The span around the line, which the stylesheet's overload gap selects
+ if line:
+ spans.append((positions[0], positions[-1], LINE_CAPTURE))
+ offset = positions[-1] + 1
+ return json.dumps([list(span) for span in spans], separators=(",", ":"))
diff --git a/great_docs/_build/freeze.py b/great_docs/_build/freeze.py
index f99277176..f23cc91c4 100644
--- a/great_docs/_build/freeze.py
+++ b/great_docs/_build/freeze.py
@@ -341,7 +341,7 @@ def render_page(config: Config, build_dir: Path, page: Path) -> subprocess.Compl
Quarto's exit status and captured output.
"""
return subprocess.run(
- ["quarto", "render", str(page.relative_to(build_dir))],
+ [quarto.executable(), "render", str(page.relative_to(build_dir))],
cwd=build_dir,
env=quarto.environment(config),
capture_output=True,
diff --git a/great_docs/_build/quarto.py b/great_docs/_build/quarto.py
index d4eb94eb4..be179fb03 100644
--- a/great_docs/_build/quarto.py
+++ b/great_docs/_build/quarto.py
@@ -4,6 +4,10 @@
Every command that runs Quarto first calls `ensure_installed`. A render runs in the Quarto
project's directory with the environment from `environment`, and reports the pages Quarto
starts, its warnings and how long each page took.
+
+Setting `GREAT_DOCS_QUARTO` to `q2`, or to the path of a `q2` binary, renders and previews
+with Quarto 2 instead (experimental). Quarto 2 reports no per-page progress, so a render
+reports its pages when it ends.
"""
from __future__ import annotations
@@ -11,6 +15,7 @@
import os
import re
import shutil
+import signal
import subprocess
import sys
import threading
@@ -28,6 +33,7 @@
from ..config import Config
__all__ = [
+ "EXECUTABLE_ENV",
"MIN_VERSION",
"Progress",
"QuartoNotFoundError",
@@ -36,17 +42,29 @@
"RenderResult",
"ensure_installed",
"environment",
+ "executable",
"installed_version",
+ "is_q2",
"is_transient_error",
"page_timings",
"parse_progress",
"render",
]
+EXECUTABLE_ENV = "GREAT_DOCS_QUARTO"
+"""The environment variable that names the Quarto command, `quarto` when unset"""
+
# The bundled extensions set the stage at which their filters run, which
# Quarto's extension schema accepts from this release
MIN_VERSION = (1, 9, 18)
+# Quarto 2 has its own version numbers. No release is known to render a great-docs
+# site completely; 0.48.0 is the first to keep a page's named `sidebar`, write the card
+# tags, the navbar's `.menu-text` spans and the content's top padding, fire
+# `quarto-hrChanged`, caption an unlabelled cell's plot and copy the files a dependency's
+# stylesheet refers to.
+Q2_MIN_VERSION = (0, 48, 0)
+
# Quarto can fail while copying output in large projects when one process renames
# a file as another removes it. A retry can succeed after the filesystem race ends.
_TRANSIENT_ERRORS = ("No such file or directory", "renameSync", "os error 2")
@@ -58,6 +76,18 @@
_WARNING_HEADING = re.compile(r"WARN(?:ING)?(?:\s+\(.*\))?\s*:?")
_OTHER_MESSAGE = re.compile(r"^(?:(?:error|fatal|info|debug|trace)\s*[:(]|Running script )", re.I)
+# Quarto 2 prints `q2 (quarto 2) 0.45.0`; with `-v` it logs each output once rendering
+# ends, and closes with `Rendered 3 of 4 files to ...`
+_Q2_VERSION = re.compile(r"\(quarto 2\)\s*(\d+(?:\.\d+)*)", re.IGNORECASE)
+_Q2_OUTPUT = re.compile(r"\bINFO\b.*\bOutput: (.+)$")
+_Q2_RENDERED = re.compile(r"^Rendered (\d+) of (\d+) files")
+# Warnings read `Warning [Q-11-7]: ...`, or `Warning: ...` without a code
+_Q2_WARNING = re.compile(r"^Warning:?\s*(?:\[(Q-[\d-]+)\])?:?\s*(.*)$")
+# `signal.SIGKILL` is missing on Windows
+_SIGKILL = 9
+# A Lua filter's `quarto.log.warning` reads `(W) interlinks: no match for x`
+_Q2_LUA_WARNING = re.compile(r"^\(W\)\s*(.*)$")
+
class QuartoNotFoundError(BuildError):
"""A missing Quarto CLI"""
@@ -67,18 +97,44 @@ class QuartoVersionError(BuildError):
"""An installed Quarto CLI older than great-docs supports"""
+def executable() -> str:
+ """
+ Return the Quarto command that renders and previews sites
+
+ Returns
+ -------
+ :
+ The value of `GREAT_DOCS_QUARTO`, or `quarto` when it is unset or empty.
+ """
+ return os.environ.get(EXECUTABLE_ENV, "").strip() or "quarto"
+
+
+def is_q2() -> bool:
+ """
+ Whether great-docs renders with Quarto 2
+
+ Returns
+ -------
+ :
+ Whether the Quarto command is a `q2` binary, by its file name.
+ """
+ name = os.path.basename(executable()).lower()
+ return name == "q2" or name.startswith(("q2.", "q2-"))
+
+
def installed_version() -> tuple[int, ...] | None:
"""
- Read the version of the Quarto CLI on the `PATH`
+ Read the version of the Quarto CLI that great-docs runs
Returns
-------
:
The version components, or `None` if Quarto fails to report a recognisable version.
+ Quarto 2 reports its own version numbers, which start at 0.
"""
try:
proc = subprocess.run(
- ["quarto", "--version"],
+ [executable(), "--version"],
capture_output=True,
timeout=30,
check=True,
@@ -86,7 +142,7 @@ def installed_version() -> tuple[int, ...] | None:
)
except (OSError, subprocess.SubprocessError):
return None
- match = re.match(r"\s*(\d+(?:\.\d+)*)", proc.stdout)
+ match = _Q2_VERSION.search(proc.stdout) or re.match(r"\s*(\d+(?:\.\d+)*)", proc.stdout)
return tuple(int(part) for part in match.group(1).split(".")) if match else None
@@ -101,9 +157,15 @@ def ensure_installed() -> None:
QuartoNotFoundError
If Quarto is not on the `PATH`.
QuartoVersionError
- If Quarto is older than `MIN_VERSION`.
+ If Quarto is older than `MIN_VERSION`, or Quarto 2 older than `Q2_MIN_VERSION`.
"""
- if shutil.which("quarto") is None:
+ if shutil.which(executable()) is None:
+ if is_q2():
+ raise QuartoNotFoundError(
+ f"Quarto 2 was not found: {EXECUTABLE_ENV} is {executable()!r}, which is not "
+ "an executable on the PATH. Set it to the path of a q2 binary, or unset it "
+ "to render with Quarto 1."
+ )
raise QuartoNotFoundError(
"Quarto was not found on your system. Quarto is a system-level "
"dependency of great-docs and is not bundled with the Python package.\n\n"
@@ -112,11 +174,12 @@ def ensure_installed() -> None:
"Or fetch the binary programmatically by using your OS package (brew, yum, winget)."
)
version = installed_version()
- if version is not None and version < MIN_VERSION:
+ minimum, product = (Q2_MIN_VERSION, "Quarto 2") if is_q2() else (MIN_VERSION, "Quarto")
+ if version is not None and version < minimum:
found = ".".join(map(str, version))
- required = ".".join(map(str, MIN_VERSION))
+ required = ".".join(map(str, minimum))
raise QuartoVersionError(
- f"great-docs requires Quarto {required} or later, but found Quarto {found}. "
+ f"great-docs requires {product} {required} or later, but found {product} {found}. "
"Upgrade Quarto from https://quarto.org/docs/get-started/"
)
@@ -162,6 +225,12 @@ def environment(config: Config) -> dict[str, str]:
env["PYTHONPATH"] = os.pathsep.join([*package_dirs, existing] if existing else package_dirs)
_ = env.setdefault("PYTHONUTF8", "1")
+
+ # Quarto 2 ignores `QUARTO_PYTHON` and runs whichever `jupyter` and `python3` the
+ # `PATH` finds first, so put the chosen Python's scripts directory first
+ if is_q2():
+ scripts = os.path.dirname(env["QUARTO_PYTHON"])
+ env["PATH"] = os.pathsep.join([scripts, env.get("PATH", "")])
return env
@@ -332,6 +401,39 @@ def is_transient_error(stderr: str) -> bool:
return any(pattern in stderr for pattern in _TRANSIENT_ERRORS)
+def failure_message(returncode: int) -> str:
+ """
+ Describe a failed render from Quarto's exit status
+
+ A process stopped by a signal has a negative status, or `128 + 9` when a shell started it
+ and the signal was `SIGKILL`. Quarto then writes no error of its own, so name the signal.
+ A system that runs out of memory stops its largest process with `SIGKILL`.
+
+ Parameters
+ ----------
+ returncode
+ Quarto's exit status.
+
+ Returns
+ -------
+ :
+ The failure line for the build log.
+ """
+ number = -returncode if returncode < 0 else 0
+ if returncode == 128 + _SIGKILL:
+ number = _SIGKILL
+ if not number:
+ return "Quarto render failed"
+ try:
+ name = signal.Signals(number).name
+ except ValueError:
+ name = f"signal {number}"
+ message = f"Quarto render failed: Quarto was stopped by {name}"
+ if number == _SIGKILL:
+ message += " (the system may have run out of memory)"
+ return message
+
+
@dataclass(frozen=True)
class RenderResult:
"""The outcome of one `quarto render`"""
@@ -367,7 +469,13 @@ def render(
Report page starts and multiline warnings through callbacks, and discard other output.
Keep standard error in the result. Page callbacks can run on either output thread.
- Warning callbacks run after the process output has been read.
+ Warning callbacks run after the process output has been read. Quarto's standard input
+ is empty.
+
+ Quarto 2 names its pages only once it has rendered them all, so `on_page` then runs for
+ every page at the end and the result has no page timings. Its warnings reach
+ `on_warning` once per warning code, with a count, and a Lua filter's warnings once
+ per filter.
Parameters
----------
@@ -393,12 +501,21 @@ def render(
OSError
If Quarto cannot be started.
"""
- command = ["quarto", "render"]
+ q2 = is_q2()
+ command = [executable(), "render"]
+ if q2:
+ from .._website import quarto2
+
+ quarto2.prepare_pages(project)
+ command += ["-v", "--color", "never"]
if no_execute:
command.append("--no-execute")
+ # Quarto 2 runs Lua filters in its own process, so a shortcode's helper inherits its
+ # standard input, and the colour swatch helper reads one that isn't a terminal
process = subprocess.Popen(
command,
cwd=project,
+ stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env,
@@ -407,6 +524,35 @@ def render(
)
stamps: list[tuple[str, float]] = []
stderr: list[str] = []
+ reported_output = False
+ q2_outputs: list[str] = []
+ q2_warnings: dict[str, list[str]] = {}
+
+ def report_q2_warnings() -> None:
+ if on_warning is not None:
+ for warnings in q2_warnings.values():
+ more = f" (and {len(warnings) - 1} more like it)" if len(warnings) > 1 else ""
+ on_warning(f"WARN {warnings[0]}{more}")
+ q2_warnings.clear()
+
+ def handle_q2(line: str) -> None:
+ nonlocal reported_output
+ plain = _ANSI.sub("", line).strip()
+ output = _Q2_OUTPUT.search(plain)
+ if output is not None:
+ reported_output = True
+ q2_outputs.append(os.path.relpath(output.group(1).strip(), project))
+ elif warning := _Q2_WARNING.match(plain):
+ code, message = warning.group(1) or "", warning.group(2).strip()
+ q2_warnings.setdefault(code, []).append(f"[{code}] {message}" if code else message)
+ elif lua_warning := _Q2_LUA_WARNING.match(plain):
+ # Group a filter's warnings by the filter name that starts them
+ message = lua_warning.group(1).strip()
+ q2_warnings.setdefault(f"lua:{message.split(':', 1)[0]}", []).append(message)
+ elif _Q2_RENDERED.match(plain):
+ for current, page in enumerate(q2_outputs, 1):
+ if on_page is not None:
+ on_page(Progress(current, len(q2_outputs), page))
def record_page(progress: Progress) -> None:
stamps.append((progress.page, time.monotonic()))
@@ -415,23 +561,32 @@ def record_page(progress: Progress) -> None:
output = RenderOutput(record_page, on_warning)
+ def handle(line: str, stream: str) -> None:
+ if q2:
+ handle_q2(line)
+ else:
+ output.feed(line, stream=stream)
+
def read_stderr() -> None:
assert process.stderr is not None
for line in process.stderr:
stderr.append(line)
- output.feed(line, stream="stderr")
+ handle(line, "stderr")
reader = threading.Thread(target=read_stderr, daemon=True)
reader.start()
assert process.stdout is not None
for line in process.stdout:
- output.feed(line, stream="stdout")
+ handle(line, "stdout")
_ = process.wait()
reader.join(timeout=5)
- output.finish()
+ if q2:
+ report_q2_warnings()
+ else:
+ output.finish()
return RenderResult(
process.returncode,
"".join(stderr),
page_timings(stamps, time.monotonic()),
- output.output_file is not None,
+ reported_output or output.output_file is not None,
)
diff --git a/great_docs/_build/render.py b/great_docs/_build/render.py
index 295a752c9..f6b156c56 100644
--- a/great_docs/_build/render.py
+++ b/great_docs/_build/render.py
@@ -111,6 +111,10 @@ def site(
env = quarto.environment(config)
result: quarto.RenderResult | parallel_render.RenderResult | None = None
render_stats: dict[str, object] | None = None
+ if jobs > 1 and quarto.is_q2():
+ # Quarto 2 renders pages in parallel itself, and has no `inspect` to plan a split
+ log.detail("Rendering in one process: Quarto 2 renders pages in parallel itself")
+ jobs = 1
if jobs > 1:
# Experimental: split the pages among several Quarto processes
bar = log.progress("Rendering pages", 1)
@@ -162,7 +166,7 @@ def on_page(_page: str) -> None:
)
if result.returncode != 0:
- raise StepError("Quarto render failed", detail=result.stderr)
+ raise StepError(quarto.failure_message(result.returncode), detail=result.stderr)
# Quarto omits progress for one-page sites and omits the summary when its logs are muted.
if (
isinstance(result, quarto.RenderResult)
diff --git a/great_docs/_build/watch.py b/great_docs/_build/watch.py
index 58acb4700..c0b19b0c2 100644
--- a/great_docs/_build/watch.py
+++ b/great_docs/_build/watch.py
@@ -30,6 +30,7 @@
import watchfiles
from .._project.layout import Layout
+from . import quarto
from .steps import BuildError
if TYPE_CHECKING:
@@ -355,9 +356,11 @@ def serve(
If the user stops watching with Ctrl+C.
"""
staging = stage(layout)
+ if quarto.is_q2():
+ _prepare_for_q2(layout.build_dir)
published = _digests(layout.build_dir)
stopped = threading.Event()
- command = ["quarto", "preview", "--no-browser"]
+ command = [quarto.executable(), "preview", "--no-browser"]
if port is not None:
command.extend(["--port", str(port)])
if no_execute:
@@ -381,6 +384,8 @@ def wait_for_preview() -> None:
except ValueError as error:
print(f"Error: {error}\nThe preview keeps the last successful build.")
else:
+ if quarto.is_q2():
+ _prepare_for_q2(staging.build_dir)
published = sync(staging.build_dir, layout.build_dir, published)
if rebuilt.get("project") != quarto_config.get("project"):
print(
@@ -400,6 +405,13 @@ def wait_for_preview() -> None:
raise BuildError(message)
+def _prepare_for_q2(build_dir: Path) -> None:
+ """Change a build directory's pages for Quarto 2 (experimental)"""
+ from .._website import quarto2
+
+ quarto2.prepare_pages(build_dir)
+
+
def source_changes(
layout: Layout,
package: Path | None,
diff --git a/great_docs/_builtin/directives/_rst_directives.py b/great_docs/_builtin/directives/_rst_directives.py
index 3ddf5be97..15744c210 100644
--- a/great_docs/_builtin/directives/_rst_directives.py
+++ b/great_docs/_builtin/directives/_rst_directives.py
@@ -17,8 +17,10 @@
from great_docs.pandoc.blocks import Div
from great_docs.pandoc.components import Attr
-_SPECIAL_DIRECTIVES = frozenset({"math", "seealso", "todo"})
-_RST_DIRECTIVES = CALLOUT_DIRECTIVES | _SPECIAL_DIRECTIVES
+_CODE_DIRECTIVES = frozenset({"code", "code-block"})
+# Directives whose output means the same in any docstring style
+_PORTABLE_DIRECTIVES = CALLOUT_DIRECTIVES | _CODE_DIRECTIVES | {"math"}
+_RST_DIRECTIVES = _PORTABLE_DIRECTIVES | {"seealso", "todo"}
_DIRECTIVE_NAME_PATTERN = "|".join(
re.escape(name) for name in sorted(_RST_DIRECTIVES, key=len, reverse=True)
)
@@ -34,9 +36,9 @@ def add_rst_directives(obj: gf.Object | gf.Alias) -> gf.Object | gf.Alias:
Replace RST directives in an object's docstring value with Quarto markup
Convert every supported directive in Sphinx docstrings. For NumPy and Google
- docstrings, continue to convert callout and version directives so existing
- docstrings retain their rendered output. `%` directives are the documented
- parser-independent form.
+ docstrings, convert the callout, version, `math` and `code-block` directives,
+ which NumPy-style docstrings written for Sphinx commonly use. `%` directives
+ are the documented parser-independent form.
Parameters
----------
@@ -55,7 +57,7 @@ def add_rst_directives(obj: gf.Object | gf.Alias) -> gf.Object | gf.Alias:
if docstring.parser == gf.Parser.sphinx:
directives = _RST_DIRECTIVES
elif docstring.parser in (gf.Parser.numpy, gf.Parser.google):
- directives = CALLOUT_DIRECTIVES
+ directives = _PORTABLE_DIRECTIVES
else:
return obj
@@ -111,6 +113,10 @@ def convert_rst_directives(text: str, directives: frozenset[str] = _RST_DIRECTIV
name = match.group("name")
if name == "math":
replacement = f"$$\n{content.strip()}\n$$"
+ elif name in _CODE_DIRECTIVES:
+ # The directive line names the language; the body is the code
+ code = body.strip("\n")
+ replacement = f"```{inline.strip()}\n{code}\n```"
elif name == "seealso":
replacement = f"See Also\n--------\n{content.strip()}"
elif name == "todo":
@@ -125,6 +131,8 @@ def convert_rst_directives(text: str, directives: frozenset[str] = _RST_DIRECTIV
)
else:
replacement = render_callout(name, body, inline)
- converted.extend(replacement.splitlines())
+ # Keep a directive nested in a parameter's description inside it
+ indent = match.group("indent")
+ converted.extend(indent + part if part else part for part in replacement.splitlines())
return "\n".join(converted)
diff --git a/great_docs/_builtin/normalization/_sphinx.py b/great_docs/_builtin/normalization/_sphinx.py
index 0468218b0..843663d6d 100644
--- a/great_docs/_builtin/normalization/_sphinx.py
+++ b/great_docs/_builtin/normalization/_sphinx.py
@@ -3,11 +3,15 @@
from __future__ import annotations
import re
+from typing import TYPE_CHECKING
import griffe as gf
from great_docs.hooks import on_object_resolved
+if TYPE_CHECKING:
+ from collections.abc import Callable
+
_RST_CODE_BLOCK_RE = re.compile(
r"^(.*?)::[ ]*\n"
r"(\n)"
@@ -26,6 +30,51 @@
_CALLABLE_RST_ROLES = frozenset({"func", "meth"})
_SPHINX_ROLE_NAMES = "exc|class|func|meth|attr|const|mod|obj|data|type"
_SPHINX_ROLE_RE = re.compile(rf":(?:py:)?(?P{_SPHINX_ROLE_NAMES}):`(?P[^`]+)`")
+# A hyperlink target, `.. _name: url`, or an internal one, `.. _name:`
+_RST_TARGET_RE = re.compile(r"^[ \t]*\.\.[ \t]+_(?P[^:`]+|`[^`]+`):[ \t]*(?P\S*)[ \t]*$")
+# Inline literals and code spans, which a reference never starts inside, or a
+# reference: `text `_, ``_, `name`_, or their anonymous `__` forms
+_RST_REFERENCE_RE = re.compile(
+ r"(?P``[\s\S]*?``)"
+ r"|(?[^`]+)`__?(?![\w`])"
+ r"|(?P`[^`]+`)"
+)
+_RST_EMBEDDED_URL_RE = re.compile(r"(?P