diff --git a/CHANGELOG.md b/CHANGELOG.md index fb086b4..e10bef1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## [Unreleased] +### Added + +- Add the `quarto-definition-list` description list format (`DescribeFormat::QuartoDefinitionList`), which writes Quarto's `::: {.definition-list}` div. Quarto 1.11.7+ and q2 render it as a definition list. + - **Breaking:** `DescribeFormat` gains the `QuartoDefinitionList` variant, and `WriterOptions` gains a `definition_list_syntax` field (`DefinitionListSyntax::Pandoc` by default). Exhaustive matches and struct literals must handle them, for example with `..Default::default()`. + ### Changed - **Breaking:** Rename the default description list format to `pandoc-definition-list` (`DescribeFormat::PandocDefinitionList`), naming it after the syntax it uses. @@ -12,6 +17,7 @@ ### Fixed +- A list item whose first block is a nested list now writes the nested list on the marker line (`- - a`). q2 rejected the previous form, an empty marker line followed by the list. - Bare brace groups in Rd text (for example `{ a, b } text`) no longer drop their content. The group is now rendered in place without the braces, as R does. Braces inside `\code{}`, `\verb{}` and `\preformatted{}` are unchanged. - Arguments cells that start with a code block or display equation now render validly in the `list-table` and `list` formats. Previously the `list-table` form failed to parse in Quarto 2. - Remove a spurious blank line before the closing fence of code blocks in `grid-table` Arguments cells. diff --git a/README.md b/README.md index c976b3d..522fa25 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,7 @@ rd2qmd convert man/ -o docs/ -j4 | `--no-frontmatter` | Disable YAML frontmatter; use this for a visible body `# Title` in Markdown consumers that do not render YAML titles | | `--no-pagetitle` | Skip pkgdown-style `pagetitle` metadata (`" — <name>"`) | | `--quarto-code-blocks <BOOL>` | Use `{r}` code blocks (auto-set based on format) | -| `--describe-format <FORMAT>` | Description list format: `pandoc-definition-list` (default), `list`, or `headings` (CommonMark/GFM) | +| `--describe-format <FORMAT>` | Description list format: `pandoc-definition-list` (default), `quarto-definition-list` (Quarto 1.11.7+ / q2), `list`, or `headings` (CommonMark/GFM) | | `--arguments-format <FORMAT>` | Arguments format: `list-table` (default), `grid-table`, `pipe-table`, or `list` | | `--input-format <FORMAT>` | Input format: `rd` (default) or `ast` (see [AST JSON I/O](#ast-json-io)) | | `-v, --verbose` | Verbose output | @@ -411,6 +411,11 @@ representation, including nested descriptions: `definition-list` still selects this format, with a deprecation warning. It will select the Quarto `.definition-list` format in a future release, so use `pandoc-definition-list` to keep the current output. +- `quarto-definition-list`: Quarto's `::: {.definition-list}` div holding a + bullet list, which Quarto 1.11.7+ and q2 render as a definition list. Each + item is the term followed by a one-item bullet list with its description; + an empty description becomes a zero-width space (`​`). Older Quarto + versions show it as a nested bullet list. - `list`: ordinary Markdown bullet lists with bold terms. Preserves paragraphs, inline formatting, links, code examples, and nested lists in CommonMark/GFM. - `headings`: terms become headings one level below their enclosing section diff --git a/crates/rd2qmd-cli/schema/rd2qmd.schema.json b/crates/rd2qmd-cli/schema/rd2qmd.schema.json index 1923215..5f0d159 100644 --- a/crates/rd2qmd-cli/schema/rd2qmd.schema.json +++ b/crates/rd2qmd-cli/schema/rd2qmd.schema.json @@ -82,6 +82,11 @@ "type": "string", "const": "pandoc-definition-list" }, + { + "description": "Quarto definition-list div - requires Quarto 1.11.7+ or q2", + "type": "string", + "const": "quarto-definition-list" + }, { "description": "Markdown bullet list - supports CommonMark and GFM, including nested descriptions", "type": "string", diff --git a/crates/rd2qmd-cli/src/cli.rs b/crates/rd2qmd-cli/src/cli.rs index 9e4c67e..d2e1a1f 100644 --- a/crates/rd2qmd-cli/src/cli.rs +++ b/crates/rd2qmd-cli/src/cli.rs @@ -206,7 +206,7 @@ pub(crate) struct ConvertArgs { #[arg(long, value_enum)] pub(crate) arguments_format: Option<CliArgumentsFormat>, - /// Output format for \describe lists, including nested descriptions: pandoc-definition-list (default), list, or headings (CommonMark/GFM). Independent of --arguments-format + /// Output format for \describe lists, including nested descriptions: pandoc-definition-list (default), quarto-definition-list (Quarto 1.11.7+ / q2), list, or headings (CommonMark/GFM). Independent of --arguments-format #[arg(long, value_enum)] pub(crate) describe_format: Option<CliDescribeFormat>, diff --git a/crates/rd2qmd-cli/src/config.rs b/crates/rd2qmd-cli/src/config.rs index 766c475..ac5959c 100644 --- a/crates/rd2qmd-cli/src/config.rs +++ b/crates/rd2qmd-cli/src/config.rs @@ -34,6 +34,8 @@ pub enum DescribeFormat { /// Pandoc definition list (default) - requires definition-list support #[default] PandocDefinitionList, + /// Quarto definition-list div - requires Quarto 1.11.7+ or q2 + QuartoDefinitionList, /// Markdown bullet list - supports CommonMark and GFM, including nested descriptions List, /// Terms become headings below their enclosing section; beyond H6, use bullet lists @@ -479,6 +481,7 @@ mod describe_format_tests { fn describe_only_config_survives_serialization() { for format in [ DescribeFormat::PandocDefinitionList, + DescribeFormat::QuartoDefinitionList, DescribeFormat::List, DescribeFormat::Headings, ] { diff --git a/crates/rd2qmd-cli/src/config_merge.rs b/crates/rd2qmd-cli/src/config_merge.rs index 7517493..609bc90 100644 --- a/crates/rd2qmd-cli/src/config_merge.rs +++ b/crates/rd2qmd-cli/src/config_merge.rs @@ -118,6 +118,7 @@ pub(crate) fn merge_describe_format(args: &ConvertArgs, config: &Config) -> Desc CliDescribeFormat::PandocDefinitionList | CliDescribeFormat::DefinitionList => { DescribeFormat::PandocDefinitionList } + CliDescribeFormat::QuartoDefinitionList => DescribeFormat::QuartoDefinitionList, CliDescribeFormat::List => DescribeFormat::List, CliDescribeFormat::Headings => DescribeFormat::Headings, } diff --git a/crates/rd2qmd-cli/tests/describe_format.rs b/crates/rd2qmd-cli/tests/describe_format.rs index e480423..4634f42 100644 --- a/crates/rd2qmd-cli/tests/describe_format.rs +++ b/crates/rd2qmd-cli/tests/describe_format.rs @@ -245,7 +245,12 @@ fn describe_format_snapshots() { include_str!("fixtures/describe_code_blocks.Rd"), ) .unwrap(); - for format in ["pandoc-definition-list", "list", "headings"] { + for format in [ + "pandoc-definition-list", + "quarto-definition-list", + "list", + "headings", + ] { for extension in ["md", "qmd"] { let filename = format!("output.{extension}"); run_cli( diff --git a/crates/rd2qmd-cli/tests/snapshots/describe_format__describe_quarto_definition_list_md.snap b/crates/rd2qmd-cli/tests/snapshots/describe_format__describe_quarto_definition_list_md.snap new file mode 100644 index 0000000..6a73f27 --- /dev/null +++ b/crates/rd2qmd-cli/tests/snapshots/describe_format__describe_quarto_definition_list_md.snap @@ -0,0 +1,63 @@ +--- +source: crates/rd2qmd-cli/tests/describe_format.rs +expression: output +--- +# Describe Blocks With Roxygen Code Fences + +## Description + +Demonstrates the Pandoc definition-list writer's handling of multi-line block children -- roxygen2 fenced code blocks, a nested definition list, and a bulleted list item that itself contains a fenced code block -- inside definition-list item descriptions. Rd authors reach this layout by embedding raw markup in a free-text roxygen2 field, as ggplot2 does when documenting its extensible base classes. + +## Methods + +::: {.definition-list} + +- `compute()` + + - **Usage** + + ```r + compute(a, b) + compute(a, b, extra = TRUE) + combine(a, b) + ``` + + **Arguments** + + ::: {.definition-list} + + - `a` + + - The first value. + + - `b` + + - The second value. + + ::: + + **Examples** + + - Basic usage: + + ``` + compute(1, 2) + #> [1] 3 + ``` + + - Advanced usage returns invisibly. + + **Ordered examples** + + 1. Basic usage: + + ``` + compute(1, 2) + #> [1] 3 + ``` + + 2. Advanced usage returns invisibly. + + That covers the `compute()` method. + +::: diff --git a/crates/rd2qmd-cli/tests/snapshots/describe_format__describe_quarto_definition_list_qmd.snap b/crates/rd2qmd-cli/tests/snapshots/describe_format__describe_quarto_definition_list_qmd.snap new file mode 100644 index 0000000..6a73f27 --- /dev/null +++ b/crates/rd2qmd-cli/tests/snapshots/describe_format__describe_quarto_definition_list_qmd.snap @@ -0,0 +1,63 @@ +--- +source: crates/rd2qmd-cli/tests/describe_format.rs +expression: output +--- +# Describe Blocks With Roxygen Code Fences + +## Description + +Demonstrates the Pandoc definition-list writer's handling of multi-line block children -- roxygen2 fenced code blocks, a nested definition list, and a bulleted list item that itself contains a fenced code block -- inside definition-list item descriptions. Rd authors reach this layout by embedding raw markup in a free-text roxygen2 field, as ggplot2 does when documenting its extensible base classes. + +## Methods + +::: {.definition-list} + +- `compute()` + + - **Usage** + + ```r + compute(a, b) + compute(a, b, extra = TRUE) + combine(a, b) + ``` + + **Arguments** + + ::: {.definition-list} + + - `a` + + - The first value. + + - `b` + + - The second value. + + ::: + + **Examples** + + - Basic usage: + + ``` + compute(1, 2) + #> [1] 3 + ``` + + - Advanced usage returns invisibly. + + **Ordered examples** + + 1. Basic usage: + + ``` + compute(1, 2) + #> [1] 3 + ``` + + 2. Advanced usage returns invisibly. + + That covers the `compute()` method. + +::: diff --git a/crates/rd2qmd-cli/tests/snapshots/integration__init_schema_json.snap b/crates/rd2qmd-cli/tests/snapshots/integration__init_schema_json.snap index dfde2d4..493848e 100644 --- a/crates/rd2qmd-cli/tests/snapshots/integration__init_schema_json.snap +++ b/crates/rd2qmd-cli/tests/snapshots/integration__init_schema_json.snap @@ -86,6 +86,11 @@ expression: schema "type": "string", "const": "pandoc-definition-list" }, + { + "description": "Quarto definition-list div - requires Quarto 1.11.7+ or q2", + "type": "string", + "const": "quarto-definition-list" + }, { "description": "Markdown bullet list - supports CommonMark and GFM, including nested descriptions", "type": "string", diff --git a/crates/rd2qmd-core/src/convert_ast/assembly.rs b/crates/rd2qmd-core/src/convert_ast/assembly.rs index 6213fe3..bc5aa73 100644 --- a/crates/rd2qmd-core/src/convert_ast/assembly.rs +++ b/crates/rd2qmd-core/src/convert_ast/assembly.rs @@ -137,6 +137,7 @@ mod tests { &WriterOptions { frontmatter: None, quarto_code_blocks: options.quarto_code_blocks, + ..Default::default() }, ) } diff --git a/crates/rd2qmd-core/src/convert_ast/blocks/cell.rs b/crates/rd2qmd-core/src/convert_ast/blocks/cell.rs index 6129c98..9034430 100644 --- a/crates/rd2qmd-core/src/convert_ast/blocks/cell.rs +++ b/crates/rd2qmd-core/src/convert_ast/blocks/cell.rs @@ -5,29 +5,45 @@ //! construct, so the nodes are prepared, rendered with //! [`render_blocks_fragment`], and re-indented under the construct's marker. -use rd2qmd_mdast::{Node, WriterOptions, normalize_inline_boundaries, render_blocks_fragment}; +use rd2qmd_mdast::{ + DefinitionListSyntax, Node, WriterOptions, normalize_inline_boundaries, render_blocks_fragment, +}; /// Serialize one node through the real writer. +/// +/// Used only for nodes flattened into pipe-table cells (code, math, +/// headings), which never contain a definition list. pub(super) fn node_to_markdown_string(node: &Node) -> String { - render_blocks_fragment(std::slice::from_ref(node), &writer_options()) + render_blocks_fragment( + std::slice::from_ref(node), + &writer_options(DefinitionListSyntax::default()), + ) } -fn writer_options() -> WriterOptions { +fn writer_options(definition_list_syntax: DefinitionListSyntax) -> WriterOptions { WriterOptions { frontmatter: None, // The migration context has no writer-format option yet. Preserve the // legacy call site's default until the document converter is wired. quarto_code_blocks: true, + definition_list_syntax, } } /// Render block nodes as a cell body whose continuation lines are indented by /// `indent` spaces. The first line is not indented: the caller places it after /// its own marker. Empty content yields an empty string. -pub(super) fn render_cell(nodes: &[Node], indent: usize) -> String { +/// +/// Cells are rendered during conversion, before the document writer runs, so +/// the definition list syntax must match the one the document uses. +pub(super) fn render_cell( + nodes: &[Node], + indent: usize, + definition_list_syntax: DefinitionListSyntax, +) -> String { let mut nodes = normalize_inline_boundaries(nodes); prepare_blocks(&mut nodes, true); - let rendered = render_blocks_fragment(&nodes, &writer_options()); + let rendered = render_blocks_fragment(&nodes, &writer_options(definition_list_syntax)); indent_continuation(&rendered, indent) } diff --git a/crates/rd2qmd-core/src/convert_ast/blocks/mod.rs b/crates/rd2qmd-core/src/convert_ast/blocks/mod.rs index 83f325a..c5869e3 100644 --- a/crates/rd2qmd-core/src/convert_ast/blocks/mod.rs +++ b/crates/rd2qmd-core/src/convert_ast/blocks/mod.rs @@ -187,7 +187,11 @@ fn convert_arguments_grid( let term_text = argument_name(argument, context); let arg_text = rd2qmd_mdast::format_inline_code(term_text.trim(), false); let desc_nodes = convert_block_content_ref(argument.description_ref(), context); - let desc_text = render_cell(&desc_nodes, 0); + let desc_text = render_cell( + &desc_nodes, + 0, + context.describe_format.definition_list_syntax(), + ); builder.push_record([arg_text, desc_text]); } @@ -220,7 +224,11 @@ fn convert_arguments_list_table( let term_text = argument_name(argument, context); let arg_text = rd2qmd_mdast::format_inline_code(term_text.trim(), false); let desc_nodes = convert_block_content_ref(argument.description_ref(), context); - let desc_text = render_cell(&desc_nodes, 4); + let desc_text = render_cell( + &desc_nodes, + 4, + context.describe_format.definition_list_syntax(), + ); (arg_text, desc_text) }) .collect(); @@ -258,7 +266,11 @@ fn convert_arguments_list( let term_text = argument_name(argument, context); let arg_code = rd2qmd_mdast::format_inline_code(term_text.trim(), false); let desc_nodes = convert_block_content_ref(argument.description_ref(), context); - let desc_text = render_cell(&desc_nodes, 2); + let desc_text = render_cell( + &desc_nodes, + 2, + context.describe_format.definition_list_syntax(), + ); (arg_code, desc_text) }) .collect(); diff --git a/crates/rd2qmd-core/src/convert_ast/blocks/tag_conversion.rs b/crates/rd2qmd-core/src/convert_ast/blocks/tag_conversion.rs index 812f8ea..55f8e4b 100644 --- a/crates/rd2qmd-core/src/convert_ast/blocks/tag_conversion.rs +++ b/crates/rd2qmd-core/src/convert_ast/blocks/tag_conversion.rs @@ -96,7 +96,8 @@ pub(super) fn convert_block( let label = inline::convert_inline_nodes_ref(item.label_ref(), &context.inline); let body = super::convert_block_content_ref(item.body_ref(), &body_context); match format { - crate::DescribeFormat::PandocDefinitionList => { + crate::DescribeFormat::PandocDefinitionList + | crate::DescribeFormat::QuartoDefinitionList => { children.push(Node::definition_term(label)); children.push(Node::definition_description(body)); } @@ -115,7 +116,8 @@ pub(super) fn convert_block( } match format { crate::DescribeFormat::Headings => children, - crate::DescribeFormat::PandocDefinitionList => { + crate::DescribeFormat::PandocDefinitionList + | crate::DescribeFormat::QuartoDefinitionList => { vec![Node::definition_list(children)] } crate::DescribeFormat::List => vec![Node::list(false, children)], diff --git a/crates/rd2qmd-core/src/convert_ast/blocks/tests.rs b/crates/rd2qmd-core/src/convert_ast/blocks/tests.rs index f85dd97..cbd8cc2 100644 --- a/crates/rd2qmd-core/src/convert_ast/blocks/tests.rs +++ b/crates/rd2qmd-core/src/convert_ast/blocks/tests.rs @@ -18,6 +18,7 @@ fn inline_nodes_to_markdown(nodes: &[Node]) -> String { &WriterOptions { frontmatter: None, quarto_code_blocks: true, + ..Default::default() }, ) } @@ -29,6 +30,7 @@ fn convert_to_markdown_text(content: &[RdNode], context: &BlockConversionContext &WriterOptions { frontmatter: None, quarto_code_blocks: true, + ..Default::default() }, ) } @@ -415,6 +417,7 @@ fn converts_tabular_multiline_ascii_equation_to_single_line_inline_code() { &WriterOptions { frontmatter: None, quarto_code_blocks: true, + ..Default::default() }, ); let row = markdown @@ -449,6 +452,7 @@ fn converts_multiline_out_in_tabular_cell_to_one_pipe_table_row() { &WriterOptions { frontmatter: None, quarto_code_blocks: true, + ..Default::default() }, ); let rows: Vec<_> = markdown @@ -791,6 +795,7 @@ fn pipe_table_flattens_and_escapes_nested_conditional_paragraphs() { &WriterOptions { frontmatter: None, quarto_code_blocks: true, + ..Default::default() }, ); let row_line = markdown @@ -839,6 +844,7 @@ fn pipe_table_collapses_multiline_argument_names_through_real_writer() { &WriterOptions { frontmatter: None, quarto_code_blocks: true, + ..Default::default() }, ); @@ -1023,6 +1029,7 @@ fn pipe_table_preserves_describe_tabular_and_preformatted_content() { &WriterOptions { frontmatter: None, quarto_code_blocks: true, + ..Default::default() }, ); let row = markdown @@ -1064,6 +1071,7 @@ fn pipe_table_preserves_both_paragraphs_of_a_multi_paragraph_list_item() { &WriterOptions { frontmatter: None, quarto_code_blocks: true, + ..Default::default() }, ); let row = markdown @@ -1175,6 +1183,7 @@ fn pipe_table_nested_tabular_pipe_is_not_double_escaped() { &WriterOptions { frontmatter: None, quarto_code_blocks: true, + ..Default::default() }, ); let row = markdown @@ -1242,6 +1251,7 @@ fn pipe_table_tabular_nested_in_describe_pipe_is_not_double_escaped() { &WriterOptions { frontmatter: None, quarto_code_blocks: true, + ..Default::default() }, ); let row = markdown @@ -1281,6 +1291,7 @@ fn pipe_table_preformatted_pipe_preserves_backslash() { &WriterOptions { frontmatter: None, quarto_code_blocks: true, + ..Default::default() }, ); @@ -1305,6 +1316,7 @@ fn pipe_table_math_pipe_preserves_backslash() { &WriterOptions { frontmatter: None, quarto_code_blocks: true, + ..Default::default() }, ); diff --git a/crates/rd2qmd-core/src/convert_ast/blocks/tests_arguments.rs b/crates/rd2qmd-core/src/convert_ast/blocks/tests_arguments.rs index ca777a7..0c997d0 100644 --- a/crates/rd2qmd-core/src/convert_ast/blocks/tests_arguments.rs +++ b/crates/rd2qmd-core/src/convert_ast/blocks/tests_arguments.rs @@ -61,12 +61,20 @@ fn equation(tag: RdTag, latex: &str) -> RdNode { /// Render a one-argument Arguments section in the given format and return the /// raw output string. fn render_arguments(format: ArgumentsFormat, description: Vec<RdNode>) -> String { + render_arguments_in(format, description, &context()) +} + +fn render_arguments_in( + format: ArgumentsFormat, + description: Vec<RdNode>, + context: &BlockConversionContext<'_>, +) -> String { let document = RdDocument::new(vec![tagged( RdTag::Arguments, vec![described_item(vec![text("value")], description)], )]); let arguments: Vec<_> = document.arguments_lossy().collect(); - let converted = convert_arguments(&arguments, format, &context()); + let converted = convert_arguments(&arguments, format, context); match converted.as_slice() { [Node::Html(html)] => html.value.clone(), // Pipe tables are returned as a structured table and serialized by @@ -76,6 +84,7 @@ fn render_arguments(format: ArgumentsFormat, description: Vec<RdNode>) -> String &WriterOptions { frontmatter: None, quarto_code_blocks: true, + ..Default::default() }, ), other => panic!("expected one raw output or table node, got {other:?}"), @@ -787,3 +796,83 @@ fn cell_grid_table_cases() { +----------+-------------+ "); } + +/// Cells are rendered during conversion, so a describe inside them must use +/// the same definition list syntax as the rest of the document. Pipe-table +/// cells flatten it as for the Pandoc form. +#[test] +fn cell_nested_describe_quarto() { + let describe = tagged( + RdTag::Describe, + vec![ + described_item(vec![text("a")], vec![text("Use method A.")]), + described_item(vec![text("b")], vec![]), + ], + ); + let context = BlockConversionContext { + describe_format: crate::DescribeFormat::QuartoDefinitionList, + ..context() + }; + let output = [ + ("pipe-table", ArgumentsFormat::PipeTable), + ("list-table", ArgumentsFormat::ListTable), + ("list", ArgumentsFormat::List), + ] + .into_iter() + .map(|(name, format)| { + let body = render_arguments_in( + format, + vec![text("Method:\n\n"), describe.clone()], + &context, + ); + format!("=== {name} ===\n{body}") + }) + .collect::<Vec<_>>() + .join("\n"); + insta::assert_snapshot!(output, @" + === pipe-table === + | Argument | Description | + |:---|:---| + | `value` | Method: <br>a: Use method A. <br>b: | + + === list-table === + ::: {.list-table header-rows=1} + + - - Argument + - Description + + - - `value` + - Method: + + ::: {.definition-list} + + - a + + - Use method A. + + - b + + - ​ + + ::: + + ::: + + === list === + - **`value`** + + Method: + + ::: {.definition-list} + + - a + + - Use method A. + + - b + + - ​ + + ::: + "); +} diff --git a/crates/rd2qmd-core/src/convert_ast/inline.rs b/crates/rd2qmd-core/src/convert_ast/inline.rs index 339e33c..3a56806 100644 --- a/crates/rd2qmd-core/src/convert_ast/inline.rs +++ b/crates/rd2qmd-core/src/convert_ast/inline.rs @@ -582,6 +582,7 @@ mod tests { &WriterOptions { frontmatter: None, quarto_code_blocks: false, + ..Default::default() }, ) } diff --git a/crates/rd2qmd-core/src/convert_ast/roxygen.rs b/crates/rd2qmd-core/src/convert_ast/roxygen.rs index 0712246..43ab251 100644 --- a/crates/rd2qmd-core/src/convert_ast/roxygen.rs +++ b/crates/rd2qmd-core/src/convert_ast/roxygen.rs @@ -227,6 +227,7 @@ mod tests { &WriterOptions { frontmatter: None, quarto_code_blocks: false, + ..Default::default() } ), "```r\nx <- 1 + 2\n```\n" diff --git a/crates/rd2qmd-core/src/lib.rs b/crates/rd2qmd-core/src/lib.rs index bb02f44..5240f31 100644 --- a/crates/rd2qmd-core/src/lib.rs +++ b/crates/rd2qmd-core/src/lib.rs @@ -17,7 +17,9 @@ mod source_parse; pub use ast_io::{AST_FORMAT_VERSION, AstIoError, RdAstEnvelope}; pub use options::{ArgumentsFormat, DescribeFormat, RdToMdastOptions}; pub use rd_ast::{RdDocument, RdNode}; -pub use rd2qmd_mdast::{Frontmatter, RdMetadata, WriterOptions, mdast_to_qmd}; +pub use rd2qmd_mdast::{ + DefinitionListSyntax, Frontmatter, RdMetadata, WriterOptions, mdast_to_qmd, +}; /// Frontmatter output options. #[derive(Debug, Clone, Default)] @@ -217,6 +219,7 @@ pub fn convert_rd_document(doc: &RdDocument, options: &RdConvertOptions) -> Stri metadata: Some(metadata), }), quarto_code_blocks: options.code.quarto_code_blocks, + definition_list_syntax: options.describe_format.definition_list_syntax(), }; mdast_to_qmd(&mdast, &writer_options) } diff --git a/crates/rd2qmd-core/src/options.rs b/crates/rd2qmd-core/src/options.rs index 875c4f8..26ecadf 100644 --- a/crates/rd2qmd-core/src/options.rs +++ b/crates/rd2qmd-core/src/options.rs @@ -47,6 +47,9 @@ pub enum DescribeFormat { /// Pandoc's `definition_lists` extension. #[default] PandocDefinitionList, + /// Quarto `::: {.definition-list}` div holding a bullet list, rendered as + /// a definition list by Quarto 1.11.7+ and q2. + QuartoDefinitionList, /// CommonMark-compatible bullet list with emphasized terms. List, /// Terms become headings below their enclosing section; beyond H6, use lists. @@ -54,6 +57,18 @@ pub enum DescribeFormat { Headings, } +impl DescribeFormat { + /// Writer syntax for the definition lists this format produces. + pub fn definition_list_syntax(self) -> rd2qmd_mdast::DefinitionListSyntax { + match self { + Self::QuartoDefinitionList => rd2qmd_mdast::DefinitionListSyntax::QuartoDiv, + Self::PandocDefinitionList | Self::List | Self::Headings => { + rd2qmd_mdast::DefinitionListSyntax::Pandoc + } + } + } +} + /// Options for converting an Rd document to mdast. #[derive(Debug, Clone)] pub struct RdToMdastOptions { diff --git a/crates/rd2qmd-mdast/README.md b/crates/rd2qmd-mdast/README.md index ebda409..dbc07c4 100644 --- a/crates/rd2qmd-mdast/README.md +++ b/crates/rd2qmd-mdast/README.md @@ -46,7 +46,7 @@ It does **not** implement: | Node Type | Description | Output | |-----------|-------------|--------| -| `DefinitionList`, `DefinitionTerm`, `DefinitionDescription` | Definition lists | Pandoc `: ` syntax | +| `DefinitionList`, `DefinitionTerm`, `DefinitionDescription` | Definition lists | Pandoc `: ` syntax, or a Quarto `::: {.definition-list}` div with `WriterOptions::definition_list_syntax` | | `Math`, `InlineMath` | LaTeX math | `$$...$$` / `$...$` | ## Usage @@ -92,6 +92,7 @@ let options = WriterOptions { }), // Use {r} for executable R code blocks (requires meta: "executable") quarto_code_blocks: true, + ..Default::default() }; ``` diff --git a/crates/rd2qmd-mdast/src/lib.rs b/crates/rd2qmd-mdast/src/lib.rs index 81f3f24..21d0507 100644 --- a/crates/rd2qmd-mdast/src/lib.rs +++ b/crates/rd2qmd-mdast/src/lib.rs @@ -30,8 +30,8 @@ pub use mdast::{ Root, Strong, Table, TableCell, TableRow, Text, }; pub use writer::{ - Frontmatter, RdMetadata, WriterOptions, escape_link_title, format_link_destination, - mdast_to_qmd, render_blocks_fragment, + DefinitionListSyntax, Frontmatter, RdMetadata, WriterOptions, escape_link_title, + format_link_destination, mdast_to_qmd, render_blocks_fragment, }; /// Format an inline code value as a Markdown code span, with safe backtick fencing. diff --git a/crates/rd2qmd-mdast/src/writer/block.rs b/crates/rd2qmd-mdast/src/writer/block.rs index a05a5c5..f615e14 100644 --- a/crates/rd2qmd-mdast/src/writer/block.rs +++ b/crates/rd2qmd-mdast/src/writer/block.rs @@ -1,6 +1,6 @@ //! Block-level node writers. -use super::Writer; +use super::{DefinitionListSyntax, Writer}; use crate::mdast::Align; use crate::mdast::Node; @@ -109,13 +109,15 @@ impl<'a> Writer<'a> { // they stay inside the list item. let prefix = if i > 0 { item_indent_str.as_str() - } else if !flow || matches!(item_child, Node::List(_)) { - // A nested list, and in descriptions any block, starts - // on the line after the marker. + } else if !flow { + // In descriptions any block starts on the line after + // the marker. self.write_terminator(); item_indent_str.as_str() } else { - // The marker is the first line's prefix. + // The marker is the first line's prefix, also for a + // nested list (`- - a`): q2 rejects an empty marker + // line followed by the list. "" }; self.write_nested_block(prefix, item_indent, |w| { @@ -240,6 +242,10 @@ impl<'a> Writer<'a> { } pub(super) fn write_definition_list(&mut self, dl: &crate::mdast::DefinitionList) { + if self.options.definition_list_syntax == DefinitionListSyntax::QuartoDiv { + self.write_quarto_definition_list(dl); + return; + } self.ensure_newline(); let mut i = 0; @@ -279,6 +285,57 @@ impl<'a> Writer<'a> { self.at_line_start = true; } + /// Write a definition list as a Quarto `::: {.definition-list}` div. + /// + /// The div holds a bullet list; each item is the term as a paragraph, + /// followed by a bullet list with one item per description. An empty or + /// missing description becomes a zero-width character reference, since + /// Quarto needs both blocks to recognize the item. A list without terms + /// writes nothing. + fn write_quarto_definition_list(&mut self, dl: &crate::mdast::DefinitionList) { + let mut items = Vec::new(); + let mut children = dl.children.iter().peekable(); + while let Some(child) = children.next() { + let Node::DefinitionTerm(term) = child else { + continue; + }; + let placeholder = || vec![Node::paragraph(vec![Node::html("​")])]; + let mut descriptions = Vec::new(); + while let Some(Node::DefinitionDescription(dd)) = children.peek() { + let blocks = if dd.children.is_empty() { + placeholder() + } else { + dd.children.clone() + }; + descriptions.push(Node::list_item(blocks)); + children.next(); + } + if descriptions.is_empty() { + descriptions.push(Node::list_item(placeholder())); + } + items.push(Node::list_item(vec![ + Node::paragraph(term.children.clone()), + Node::list(false, descriptions), + ])); + } + if items.is_empty() { + return; + } + + self.ensure_newline(); + self.output.push_str("::: {.definition-list}\n"); + self.write_separator(); + self.write_list(&crate::mdast::List { + ordered: false, + start: None, + spread: false, + children: items, + }); + self.write_separator(); + self.output.push_str(":::\n"); + self.at_line_start = true; + } + /// Write one `: ` description, ending with its terminator. Returns /// whether it was written in the multi-block form. fn write_definition_description(&mut self, dd: &crate::mdast::DefinitionDescription) -> bool { diff --git a/crates/rd2qmd-mdast/src/writer/mod.rs b/crates/rd2qmd-mdast/src/writer/mod.rs index 15df6d5..15253f0 100644 --- a/crates/rd2qmd-mdast/src/writer/mod.rs +++ b/crates/rd2qmd-mdast/src/writer/mod.rs @@ -20,6 +20,8 @@ mod tests_emphasis; #[cfg(test)] mod tests_fragment; #[cfg(test)] +mod tests_quarto_dl; +#[cfg(test)] mod tests_structure; /// Options for the QMD writer @@ -29,6 +31,24 @@ pub struct WriterOptions { pub frontmatter: Option<Frontmatter>, /// Use {r} instead of r for R code blocks pub quarto_code_blocks: bool, + /// Syntax for [`Node::DefinitionList`] + pub definition_list_syntax: DefinitionListSyntax, +} + +/// Markdown syntax used to write a definition list. +/// +/// Both forms carry the same structure; they differ in which renderers +/// understand them. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum DefinitionListSyntax { + /// Pandoc's `definition_lists` extension: the term on its own line, then + /// each description after a `: ` marker. + #[default] + Pandoc, + /// Quarto's `::: {.definition-list}` div. It holds a bullet list whose + /// items are a term followed by a bullet list with one item per + /// description. + QuartoDiv, } /// YAML frontmatter content diff --git a/crates/rd2qmd-mdast/src/writer/tests_boundary.rs b/crates/rd2qmd-mdast/src/writer/tests_boundary.rs index 37cd199..f4cde9f 100644 --- a/crates/rd2qmd-mdast/src/writer/tests_boundary.rs +++ b/crates/rd2qmd-mdast/src/writer/tests_boundary.rs @@ -336,6 +336,20 @@ fn opaque_children_inside_containers() { )], "- \n- b\n", ), + ( + "nested list as first block of an item", + vec![Node::list( + false, + vec![ + item(vec![Node::list( + false, + vec![item(vec![para("a")]), item(vec![para("b")])], + )]), + item(vec![para("c")]), + ], + )], + "- - a\n - b\n- c\n", + ), ( "empty nested list item, then item", vec![Node::list( diff --git a/crates/rd2qmd-mdast/src/writer/tests_fragment.rs b/crates/rd2qmd-mdast/src/writer/tests_fragment.rs index 9496f59..ce9d0d3 100644 --- a/crates/rd2qmd-mdast/src/writer/tests_fragment.rs +++ b/crates/rd2qmd-mdast/src/writer/tests_fragment.rs @@ -32,6 +32,7 @@ fn ignores_frontmatter() { ..Default::default() }), quarto_code_blocks: false, + ..Default::default() }; let out = render_blocks_fragment(&[Node::paragraph(vec![Node::text("a")])], &options); assert_eq!(out, "a"); @@ -46,6 +47,7 @@ fn honors_quarto_code_blocks_and_empty_input() { let on = WriterOptions { frontmatter: None, quarto_code_blocks: true, + ..Default::default() }; assert_eq!( render_blocks_fragment(&[code.clone()], &on), diff --git a/crates/rd2qmd-mdast/src/writer/tests_quarto_dl.rs b/crates/rd2qmd-mdast/src/writer/tests_quarto_dl.rs new file mode 100644 index 0000000..a07bcbe --- /dev/null +++ b/crates/rd2qmd-mdast/src/writer/tests_quarto_dl.rs @@ -0,0 +1,131 @@ +//! Definition lists written as Quarto `::: {.definition-list}` divs. +use super::*; +use crate::mdast::*; + +fn render(nodes: Vec<Node>) -> String { + mdast_to_qmd( + &Root::new(nodes), + &WriterOptions { + definition_list_syntax: DefinitionListSyntax::QuartoDiv, + ..Default::default() + }, + ) +} + +fn para(t: &str) -> Node { + Node::paragraph(vec![Node::text(t)]) +} + +fn term(t: &str) -> Node { + Node::definition_term(vec![Node::text(t)]) +} + +fn def(children: Vec<Node>) -> Node { + Node::definition_description(children) +} + +#[test] +fn quarto_definition_lists() { + let cases: Vec<(&str, Vec<Node>, &str)> = vec![ + ( + "two terms, then paragraph", + vec![ + Node::definition_list(vec![ + term("T1"), + def(vec![para("D1")]), + term("T2"), + def(vec![para("D2")]), + ]), + para("B"), + ], + "::: {.definition-list}\n\n- T1\n\n - D1\n\n- T2\n\n - D2\n\n:::\n\nB\n", + ), + ( + "multi-block description", + vec![Node::definition_list(vec![ + term("T"), + def(vec![para("P1"), Node::code(None, "x"), para("P2")]), + ])], + "::: {.definition-list}\n\n- T\n\n - P1\n\n ```\n x\n ```\n\n P2\n\n:::\n", + ), + ( + "description holding only a list", + vec![Node::definition_list(vec![ + term("T"), + def(vec![Node::list( + false, + vec![ + Node::list_item(vec![para("a")]), + Node::list_item(vec![para("b")]), + ], + )]), + ])], + "::: {.definition-list}\n\n- T\n\n - - a\n - b\n\n:::\n", + ), + // Quarto needs both the term and the description block to recognize + // an item, so an empty description gets a zero-width placeholder. + ( + "empty description", + vec![Node::definition_list(vec![term("T"), def(vec![])])], + "::: {.definition-list}\n\n- T\n\n - ​\n\n:::\n", + ), + ( + "term without description", + vec![Node::definition_list(vec![term("T")])], + "::: {.definition-list}\n\n- T\n\n - ​\n\n:::\n", + ), + // Each description is its own nested item, which Quarto and q2 + // render as separate `<dd>` elements. + ( + "two descriptions", + vec![Node::definition_list(vec![ + term("T"), + def(vec![para("D1")]), + def(vec![para("D2")]), + ])], + "::: {.definition-list}\n\n- T\n\n - D1\n - D2\n\n:::\n", + ), + ( + "empty description among others", + vec![Node::definition_list(vec![ + term("T"), + def(vec![]), + def(vec![para("D2"), para("D3")]), + ])], + "::: {.definition-list}\n\n- T\n\n - ​\n\n - D2\n\n D3\n\n:::\n", + ), + ( + "nested definition list", + vec![Node::definition_list(vec![ + term("T"), + def(vec![ + para("D"), + Node::definition_list(vec![term("U"), def(vec![para("E")])]), + ]), + ])], + "::: {.definition-list}\n\n- T\n\n - D\n\n ::: {.definition-list}\n\n - U\n\n - E\n\n :::\n\n:::\n", + ), + ( + "inside a list item", + vec![Node::list( + false, + vec![ + Node::list_item(vec![Node::definition_list(vec![ + term("T"), + def(vec![para("D")]), + ])]), + Node::list_item(vec![para("c")]), + ], + )], + "- ::: {.definition-list}\n\n - T\n\n - D\n\n :::\n- c\n", + ), + ( + "without terms writes nothing", + vec![para("A"), Node::definition_list(vec![]), para("B")], + "A\n\nB\n", + ), + ]; + for (label, nodes, expected) in cases { + assert_eq!(render(nodes), expected, "output for {label}"); + } +} diff --git a/crates/rd2qmd-package/src/convert.rs b/crates/rd2qmd-package/src/convert.rs index ee10345..1714fb8 100644 --- a/crates/rd2qmd-package/src/convert.rs +++ b/crates/rd2qmd-package/src/convert.rs @@ -430,6 +430,7 @@ pub(crate) fn convert_single_file( None }, quarto_code_blocks: options.quarto_code_blocks, + definition_list_syntax: options.describe_format.definition_list_syntax(), }; // Convert to QMD string