diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 22311ec..c4e81bd 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -6,7 +6,9 @@ on: pull_request: jobs: - # All tests against the installed package. Without sclang, the SCDoc tests are skipped. + # All tests against the installed package. Without sclang, the SCDoc tests are skipped. The citation tests run + # with the pandoc of Ubuntu; the comparison of whole files is skipped if it is not the version in + # tests/schelp/PANDOC_VERSION. python: runs-on: ubuntu-24.04 strategy: @@ -17,6 +19,7 @@ jobs: - uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} + - run: sudo apt-get update && sudo apt-get install --yes --no-install-recommends pandoc - run: python -m pip install ".[test]" # From another folder, so that the tests import the installed package and not the checkout - name: Test the installed package @@ -32,9 +35,10 @@ jobs: container: debian:forky env: MD2MISC_REQUIRE_SCLANG: "1" + MD2MISC_REQUIRE_PANDOC: "1" QT_QPA_PLATFORM: offscreen steps: - uses: actions/checkout@v4 - - run: apt-get update && apt-get install --yes --no-install-recommends python3 python3-venv supercollider-language + - run: apt-get update && apt-get install --yes --no-install-recommends python3 python3-venv supercollider-language pandoc - run: python3 -m venv /opt/venv && /opt/venv/bin/python -m pip install ".[test]" - run: /opt/venv/bin/python -m pytest -k schelp -rs diff --git a/CLAUDE.md b/CLAUDE.md index b620faa..d0f95e7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,8 @@ Markdown to TeX (the same output as md2tex) and to SuperCollider help (schelp). - The SCDoc tests need `sclang`; they are skipped without it. The host `sclang` (3.14.1, the version in `tests/schelp/SCLANG_VERSION`) is on `PATH` in the container. GitHub Actions (`.github/workflows/tests.yml`) runs the tests against the installed package, and the SCDoc tests in a `debian:forky` container, for `sclang` 3.14 (Ubuntu 24.04 has 3.13, which does not know `math::` and `subsubsection::`). - `tests/fixtures/*.tex` is the output of md2tex f90f23b. It is the reference. Never run `tests/battery.py build` against changed converter code. Change a `.tex` file only if the TeX output is meant to change. - The fixtures test article-numbered TeX and the heading variants only. After a change in the converters, also compare with the old code on edge cases. -- After a schelp change, run `.venv/bin/python tests/schelp_fixtures.py update` in the container (needs `sclang`) and read the diff. It also writes the `sclang` version to `tests/schelp/SCLANG_VERSION`. +- The citation tests need `pandoc`. It is not on the host or in the container: give a Nix store path with `PANDOC`. Get the path on the host with `nix build nixpkgs#pandoc --no-link --print-out-paths` (the program is `/bin/pandoc`), then `distrobox enter dev -- fish -lc 'cd ~/gp/md2misc; and env PANDOC=/bin/pandoc .venv/bin/python -m pytest'`. +- After a schelp change, run `.venv/bin/python tests/schelp_fixtures.py update` in the container (needs `sclang`, and `pandoc` through `PANDOC`) and read the diff. It also writes the versions to `tests/schelp/SCLANG_VERSION` and `tests/schelp/PANDOC_VERSION`. ## Design diff --git a/README.md b/README.md index 1371415..b625428 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ Each output format is a *backend*: ## Installation -`md2misc` needs Python 3.10 or later. It uses only the Python standard library. +`md2misc` needs Python 3.10 or later. It uses only the Python standard library. The citations of the schelp backend need the program [`pandoc`](https://pandoc.org) (see [docs/schelp.md](docs/schelp.md#citations)). ```bash pip install git+https://github.com/aeskildsen/md2misc diff --git a/docs/development.md b/docs/development.md index 470ef80..80a7711 100644 --- a/docs/development.md +++ b/docs/development.md @@ -16,7 +16,9 @@ The tests of the SCDoc output run headless `sclang` (SuperCollider). They are sk Each version of `sclang` from 3.14 must parse the schelp output with no error and give the expected parts of the pages. The `.html` files hold whole pages of the SuperCollider version in `tests/schelp/SCLANG_VERSION`. The tests compare whole pages only with that version. -GitHub Actions (`.github/workflows/tests.yml`) runs all tests against the installed package with several Python versions. It runs the SCDoc tests with the SuperCollider of Debian forky (Ubuntu 24.04 has 3.13). +The tests of the citations run `pandoc`. They are skipped if `pandoc` is not on `PATH` or in the `PANDOC` environment variable. With `MD2MISC_REQUIRE_PANDOC=1`, a missing `pandoc` is an error. The text of a citation can change between versions of Pandoc: the tests compare the files of the fixtures with a bibliography only with the version in `tests/schelp/PANDOC_VERSION`. + +GitHub Actions (`.github/workflows/tests.yml`) runs all tests against the installed package with several Python versions. It runs the SCDoc tests with the SuperCollider of Debian forky (Ubuntu 24.04 has 3.13). Both jobs install the `pandoc` of the distribution. ## Test files @@ -26,14 +28,16 @@ GitHub Actions (`.github/workflows/tests.yml`) runs all tests against the instal - `tests/test_schelp_errors.py`: the constructs without a schelp form stop the conversion with the file, line and construct, and look-alikes in code are accepted. - `tests/test_schelp_writer.py`: the writers of the schelp backend stop at the constructs too, when the check of the source does not find them. - `tests/test_schelp_behavior.py`: the output of single cases. -- `tests/test_schelp_methods.py`: the class methods section: method headings, the forms of the argument table, the cells and the return value. +- `tests/test_schelp_methods.py`: the methods sections: method headings, the forms of the argument table, the cells, the return value and the discussion. +- `tests/test_schelp_tables.py`: the tables outside the methods sections. +- `tests/test_schelp_citations.py`: the citations, with the bibliography `tests/schelp/citations.bib`. - `tests/test_tables.py`: the rows of a pipe table (`md2misc/tables.py`): which lines are a table, the cells and the end of the table. The expected values are those of cmark-gfm, the GFM parser of GitHub, where a comment does not say otherwise. - `tests/test_tex_library.py`: the arguments of `convert`, the default template, the warnings and the errors of the TeX backend, and that the package needs only the standard library. ## Fixture tools - `python3 tests/battery.py build` makes the TeX fixtures. It needs `pip install -e ".[battery]"` and private checkouts of the book that the fixtures come from, so contributors do not run it. The `.tex` files are the frozen reference (the output of `md2tex`). -- `python3 tests/schelp_fixtures.py update` makes the `.schelp` and `.html` files and `SCLANG_VERSION`. Read the diff afterwards. After an update of SuperCollider, the HTML can change: make the files again and read the diff. +- `python3 tests/schelp_fixtures.py update` makes the `.schelp` and `.html` files, `SCLANG_VERSION` and `PANDOC_VERSION`. It needs `sclang` and `pandoc`. Read the diff afterwards. After an update of SuperCollider or Pandoc, the output can change: make the files again and read the diff. The files in `tests/schelp/images` are next to the schelp files when SCDoc renders them. ## Releases diff --git a/docs/schelp.md b/docs/schelp.md index 0fe5a20..4e290c6 100644 --- a/docs/schelp.md +++ b/docs/schelp.md @@ -3,7 +3,7 @@ ```python from md2misc import convert_schelp -schelp = convert_schelp(markdown, metadata=None, insertions=None) +schelp = convert_schelp(markdown, metadata=None, insertions=None, bibliography=None) ``` `convert_schelp` returns a SuperCollider help document: the markup that SCDoc renders to HTML. @@ -12,6 +12,7 @@ schelp = convert_schelp(markdown, metadata=None, insertions=None) |---|---| | `metadata` | A dict of header values. A value here replaces the front matter value with the same key. | | `insertions` | A dict that maps the name of an insertion point to the schelp text that takes its place. | +| `bibliography` | The path of a bibliography file for the citations (BibTeX, BibLaTeX, CSL JSON or CSL YAML). See [Citations](#citations). | The output needs SuperCollider 3.14 or later. SCDoc 3.13 does not know the `MATH::` and `SUBSUBSECTION::` tags, which `md2misc` writes for math and for headings of level 4 and lower, and stops with a syntax error. @@ -31,15 +32,15 @@ A file with no front matter, no level 1 heading and no metadata gives the body o ## Special sections and insertion points -A level 2 heading `## Description` gives `DESCRIPTION::`, and `## Examples` gives `EXAMPLES::`. Any other level 2 heading gives `SECTION::`. +A level 2 heading `## Description` gives `DESCRIPTION::`, `## Class methods` gives `CLASSMETHODS::`, `## Instance methods` gives `INSTANCEMETHODS::`, and `## Examples` gives `EXAMPLES::`. Any other level 2 heading gives `SECTION::`. A line `` is an insertion point. Markdown viewers do not show the comment. The `insertions` argument puts the schelp text in its place, as it is. A program that writes the `CLASSMETHODS::` section can use this to put it between the description and the examples. An insertion point with no text gives nothing. Text for a name that the file does not have stops the conversion. -## Class methods +## Methods -A level 2 heading `## Class methods` gives `CLASSMETHODS::`. In this section, md2misc writes the methods, their arguments and their return values from Markdown that GitHub shows as it is: +In the two methods sections, `## Class methods` and `## Instance methods`, md2misc writes the methods, their arguments, their return values and their discussions from Markdown that GitHub shows as it is: ```markdown ## Class methods @@ -75,16 +76,17 @@ Range: seconds returns::two channels. ``` -- A level 3 heading `### *name` starts a method. More names share one entry: `### *ar, *kr`. In the section, every level 3 heading must be a method, and deeper headings stop the conversion. +- A level 3 heading starts a method: `### *name` in the class methods section, `### -name` in the instance methods section. These are the marks of SCDoc's anchors (`*ar`, `-play`). More names share one entry: `### *ar, *kr`. In a methods section, every level 3 heading must be a method. - The text after the method heading is the text of the method. - The argument table follows the text. Each row is an argument. The first column is the name, plain or as code (`` `bufnum` ``). The last column is the text of the argument. Each column between them adds a line `heading: value` to the text, if its cell is not empty. The text of the header row of the first and last columns is not used. - A paragraph that starts with `Returns:` gives `returns::`. It can follow the table, or the text if the method has no arguments. +- A level 4 heading `#### Discussion` gives `discussion::`. The text after it, to the next method or section, is the discussion: more text and examples. Any Markdown with a schelp form can be in it, except a table. Other level 4 headings in a method stop the conversion. -SCDoc puts all text after an argument into that argument, and all text after `returns::` into the return value. Thus a method has its parts in this order: text, table, `Returns:` paragraph. Text after the table (other than `Returns:`), or after the `Returns:` paragraph, stops the conversion. +SCDoc puts all text after an argument into that argument, and all text after `returns::` into the return value. Thus a method has its parts in this order: text, table, `Returns:` paragraph, discussion. Text after the table or after the `Returns:` paragraph stops the conversion, if a `#### Discussion` heading does not come before it. -The section ends at the next level 2 heading. Outside a method of this section, a `Returns:` paragraph is text, and a table stops the conversion. +A methods section ends at the next level 2 heading. Outside a method, a `Returns:` paragraph is text. In a methods section, a table outside a method stops the conversion. -An insertion point can also hold a `CLASSMETHODS::` section that a program writes (see above). Use either the insertion point or the `## Class methods` section, not both. +An insertion point can also hold a `CLASSMETHODS::` or `INSTANCEMETHODS::` section that a program writes (see above). Use either the insertion point or the Markdown section, not both. ### The argument table @@ -108,6 +110,83 @@ Where Markdown renderers do not agree, or where GitHub does not show what md2mis - an argument name that is not a name (letters, digits and `_`, not a digit first), a name twice in one table, an argument without text - a second table in a method, or a table after `Returns:` +## Tables + +Outside the methods sections, a pipe table gives `table::`. The rules of GFM and the checks are the same as for the argument table (see above). The cells can hold bold and italic text, code, links, math and footnotes. + +SCDoc has no header row. The header row is the first row, in bold. A header cell that is empty stays empty. A header row with only empty cells gives no row: this is the form for a table without a header. Bold text cannot hold other tags in SCDoc, thus code, math, links, footnotes, citations, and bold or italic text in the header row stop the conversion. The alignment of the columns is not used. + +```markdown +| Parameter | Range | +|---|---| +| `freq` | 20 to 20000 | +``` + +gives + +``` +table:: +## strong::Parameter:: || strong::Range:: +## code::freq:: || 20 to 20000 +:: +``` + +## Images + +An image alone in a paragraph, `![caption](path)`, gives `image::path#caption::`. With no caption, it gives `image::path::`. SCDoc shows the caption below the image. + +The path is relative to the schelp file. SCDoc copies the files in the `HelpSource` folder that are not schelp files to the help folder, thus put the image file next to the schelp file (for example in `HelpSource/Classes/images/`). md2misc does not copy files. + +These stop the conversion: an image in a line of text, a URL or an absolute path, a `#` in the caption or the path (SCDoc splits the tag at `#`), and markup in the caption. A width (`{ width="50%" }`) is not used. + +## Block quotes + +SCDoc has no tag for a block quote. A block quote that is not an alert gives its paragraphs in italics, with quotation marks at the start of the first paragraph and at the end of the last one, as in the JITLib overview of SuperCollider. A line with `>` alone separates the paragraphs. + +```markdown +> The first paragraph. +> +> The second paragraph. +``` + +gives + +``` +emphasis::"The first paragraph.:: + +emphasis::The second paragraph.":: +``` + +Italic text cannot hold other tags in SCDoc: thus code, math, links, footnotes, citations, bold or italic text, lists, headings, code blocks and block quotes in a block quote stop the conversion. The source of a quote is not part of the quote: write it after the block quote, as a paragraph or a footnote. + +## Footnotes + +`[^1]` and `[^1]: text` give `footnote::text::` at the place of the mark. SCDoc puts the footnotes at the end of the page. A footnote can have more than one line and more than one paragraph: the lines of a later paragraph have an indent of 4 spaces or a tab. A list, a code block or another block in a footnote stops the conversion. + +A footnote directly after a word gets a space before its tag (see [Escapes](#escapes)). SCDoc removes this space from the page. + +## Citations + +With the `bibliography` argument, a citation gives a footnote, in the manner of Wikipedia. md2misc runs the program `pandoc` to write the citations, with Pandoc's built-in style (Chicago author-date). `pandoc` must be on the `PATH`, or the environment variable `PANDOC` must give its path. A text without citations does not run `pandoc`. + +| Markdown | The footnote | +|---|---| +| `[@doe1999]`, the first citation of the source | `Doe, Jane. 1999. emphasis::Sound and Wood::. Acme.` | +| `[@doe1999, 30]` | `Doe, Jane. 1999. …, p. 30.` | +| `[@doe1999, 30-35]` | `Doe, Jane. 1999. …, pp. 30–35.` | +| `[@doe1999, p. 31]`, a later citation of the source | `Doe 1999, 31.` | +| `[@doe1999; @smith2000]` | the parts of the two sources, separated by `;` | + +- The first citation of a source gives its reference entry, with the locator. A later citation gives the short form. There is no list of references: SCDoc puts the footnotes at the end of the page. +- A locator that is not a page or pages is written as it is: `[@doe1999, chap. 2]`. +- `[-@doe1999]` is the same as `[@doe1999]`: a footnote does not name the author in the text. +- A citation in a footnote gives the short form in parentheses: `(Doe 1999, 30)`. SCDoc cannot put a footnote in a footnote. +- If the bibliography has two works of one author and year, the style tells them apart: `1999a`, `1999b`. + +These stop the conversion: a citation without a `bibliography` (write the citation as text, or give a bibliography), a key that is not in the bibliography, and a citation in another form. A citation in a heading, in bold or italic text, in a block quote or in the header row of a table also stops the conversion. + +The TeX backend writes the same citations as `\parencite` (biblatex), with no `pandoc`. + ## The body | Markdown | schelp | @@ -125,7 +204,11 @@ Where Markdown renderers do not agree, or where GitHub does not show what md2mis | `Term` and `: definition` | `DEFINITIONLIST::` with `## term` and `\|\| definition` | | `[text](https://example.com)` | `link::https://example.com##text::` | | `[text](sc:Classes/SinOsc)`, `[text](sc:Classes/SinOsc#*ar)` | `link::Classes/SinOsc##text::`, `link::Classes/SinOsc#*ar#text::` (no label if the text is the name of the page) | -| `[^1]` and `[^1]: note` | `footnote::note::` at the place of the mark | +| `[^1]` and `[^1]: note` | `footnote::note::` at the place of the mark (see [Footnotes](#footnotes)) | +| `[@key]` and a `bibliography` | `footnote::` with the reference (see [Citations](#citations)) | +| a pipe table | `table::` (see [Tables](#tables)) | +| `![caption](path)` alone in a paragraph | `image::path#caption::` (see [Images](#images)) | +| `> text` | `emphasis::"text"::` (see [Block quotes](#block-quotes)) | | `$x$` | `math::x::` | | `$$` block `$$` | `math::` block | | `> [!NOTE]` and the lines after it | `note::` block (`TIP` and `IMPORTANT` too) | @@ -139,6 +222,8 @@ In text, `::`, `##` and `||` get a backslash, because SCDoc takes them as markup If the text of an inline tag (bold, italic, inline code, a link, inline math, a footnote) ends with `:` or `\`, a space comes before the end-tag `::`, because SCDoc takes the character as part of the end-tag. SCDoc does not show the space. +SCDoc takes letters directly before `::` as the name of a tag: in `wordstrong::bold::`, the tag is `wordstrong`, which is an error. Thus an inline tag directly after a letter (`word**bold**`) gets a word joiner (U+2060) before it: `word⁠strong::bold::`. The word joiner is not visible and does not let a line break between the word and the tag. It stays in the HTML. A footnote gets a space in place of the word joiner, because SCDoc removes the space before a footnote mark. + ### Differences from the TeX backend Three rules of the schelp backend are those of CommonMark and Pandoc, not those of the TeX backend: @@ -150,13 +235,23 @@ Three rules of the schelp backend are those of CommonMark and Pandoc, not those ## Constructs that stop the conversion - a second level 1 heading, and a heading underlined with `=` or `-` -- block quotes that are not alerts +- alerts of a kind that is not known (`> [!FOO]`), and markup or blocks in a block quote (see [Block quotes](#block-quotes)) - links that are not `http` URLs or `sc:` links, links in `<` and `>`, a `#` in the text of a link (SCDoc splits a link at each `#`; a link without a label, where the text is the address or the name of the page, is fine), and more than one `#` in the address of a link -- citations, images and audio files, HTML tags and HTML comments (other than insertion points), `
` tags -- tables, other than the argument table of a method in the class methods section (see [Class methods](#class-methods), also for the rules of that section) +- citations without a bibliography (see [Citations](#citations)), audio files, HTML tags and HTML comments (other than insertion points), `
` tags +- images that are not alone in a paragraph, or not at a relative path (see [Images](#images)) +- tables that GFM renderers read in different ways, markup in the header row of a table, and tables in a methods section that are not the argument table of a method (see [Methods](#methods) and [Tables](#tables)) - horizontal rules (`---`, `***`, `___`) - lists with `*` or `+` marks, and numbered lists with `1)` -- a footnote with more than one line +- a list, a code block or another block in a footnote - a title or highlighted lines in a code block -- bold or italic text, code, math, a link or a footnote in a heading -- bold or italic text that holds code, math, a link, a footnote or other bold or italic text +- bold or italic text, code, math, a link, a footnote or a citation in a heading +- bold or italic text that holds code, math, a link, a footnote, a citation or other bold or italic text + +## Limits of SCDoc + +SCDoc writes HTML, but its markup has no tag for some elements of HTML: + +- a horizontal rule (`
`): `---`, `***` and `___` stop the conversion. +- a block quote (`
`): md2misc writes the quote in italics (see [Block quotes](#block-quotes)). +- the header row of a table (``): md2misc writes the header row in bold (see [Tables](#tables)). +- the width of an image. diff --git a/md2misc/backends/base.py b/md2misc/backends/base.py index 011d24c..22eb230 100644 --- a/md2misc/backends/base.py +++ b/md2misc/backends/base.py @@ -36,6 +36,12 @@ def unsupported(self, construct: str, line: int = None): heading_regex = syntax.HEADING inline_math_regex = syntax.INLINE_MATH + # whether the citations are written before the footnotes. the default is the order of md2tex + citations_before_footnotes = False + + # the form of a block quote: its lines start with `>`. md2tex takes a line with `>` alone as the end of the quote + block_quote_regex = r"^((>.+(\n|$))+)" + # whether the quote marks (`>`) are removed from the lines of a code block in a block quote. # md2tex keeps them in the code strip_quote_marks_in_code = False diff --git a/md2misc/backends/schelp.py b/md2misc/backends/schelp.py index f7f117d..a7cdb0c 100644 --- a/md2misc/backends/schelp.py +++ b/md2misc/backends/schelp.py @@ -2,7 +2,7 @@ from itertools import chain from .base import Backend -from .. import syntax, tables +from .. import citations, syntax, tables from ..errors_warnings import DocumentError, UnsupportedConstruct @@ -46,14 +46,25 @@ class SchelpBackend(Backend): tag_regex = r"\w::" # the sections that SCDoc tells apart from other sections, by the text of a level 2 heading - special_sections = {"description": "DESCRIPTION", "examples": "EXAMPLES", "class methods": "CLASSMETHODS"} + special_sections = {"description": "DESCRIPTION", "examples": "EXAMPLES", "class methods": "CLASSMETHODS", + "instance methods": "INSTANCEMETHODS"} - # the section whose methods and argument tables the converters write as `METHOD::` and `ARGUMENT::` - methods_section = "class methods" + # the sections whose methods and argument tables the converters write as `METHOD::` and `ARGUMENT::`, and the + # mark before the name of each method in a method heading. SCDoc uses the same marks in the anchors of methods + methods_sections = {"class methods": "*", "instance methods": "-"} supports_methods = True - # a class method heading in the class methods section: `### *ar`, or `### *ar, *kr` for more names - method_heading_regex = r"^#{3}[ \t]+(\*[A-Za-z_]\w*([ \t]*,[ \t]*\*[A-Za-z_]\w*)*)[ \t]*$" + # a heading that starts the discussion of a method, after its arguments and its return value + discussion_heading_regex = r"^#{4}[ \t]+[Dd]iscussion[ \t]*$" + + @staticmethod + def method_heading_regex(mark: str) -> str: + """ + the form of a method heading in a methods section: `### *ar`, or `### *ar, *kr` for more names. `mark` is + the mark of the section (`*` or `-`). + """ + name = re.escape(mark) + r"[A-Za-z_]\w*" + return r"^#{3}[ \t]+(" + name + r"([ \t]*,[ \t]*" + name + r")*)[ \t]*$" # the name of an argument in the first cell of an argument table: a name, or a name in code argument_name_regex = r"(`?)([A-Za-z_]\w*)\1" @@ -65,7 +76,8 @@ class SchelpBackend(Backend): header_keys = ["class", "title", "summary", "related", "categories"] list_keys = ["related", "categories"] - def __init__(self, insertions: dict = None): + def __init__(self, insertions: dict = None, bibliography=None): + self.bibliography = bibliography # the path of the bibliography file for the citations, or None self.stash = {} self.insertions = dict(insertions or {}) self.used_insertions = set() @@ -184,6 +196,12 @@ def check_insertions(self): # the Markdown constructs that only `check_source()` finds list_item_regex = r"[ \t]*([-*+]|\d+[.)])[ \t]" + alert_mark_regex = r">\s*\[!(\w+)\]\s*$" + # a source in a citation: `@key`, with an optional locator after a comma. `-@key` is the form that does not + # name the author in the text, which has no use in a footnote: the `-` is ignored + citation_item_regex = r"\s*-?@([^\s,;@\]]+)(?:\s*,\s*([^;@]*?))?\s*" + markup_in_quote_construct = ("code, math, a link, a footnote, a citation, or bold or italic text in a block " + "quote (the quote is in italics)") footnote_definition_regex = r"\[\^\d+\]:" footnote_mark_regex = r"\[\^\d+\]" thematic_break_regex = r" {0,3}([-*_])([ \t]*\1){2,}[ \t]*$" @@ -205,21 +223,33 @@ def _check_heading_source(self, text: str, line: int): if (self.code_token[0] in text or re.search(r"\*[^*\n]+\*", text) or re.search(syntax.INLINE_MATH_STRICT, text)): self.unsupported("bold, italic text, code or math in a heading", line) - if re.search(syntax.LINK, text) or re.search(self.footnote_mark_regex, text): - self.unsupported("link or footnote in a heading", line) + if (re.search(syntax.LINK, text) or re.search(self.footnote_mark_regex, text) + or re.search(syntax.CITATION, text)): + self.unsupported("link, footnote or citation in a heading", line) + + def _check_citation(self, citation: str, line: int = None): + """ + check a citation: the text between `[` and `]`. a citation is one source or more, separated by `;`. each + source is a key with `@` before it, and an optional locator after a comma: `@doe1999, p. 30`. + """ + if not self.bibliography: + self.unsupported("citation (give a bibliography to the conversion, or write the citation as text)", + line) + for item in citation.split(";"): + if not re.fullmatch(self.citation_item_regex, item): + self.unsupported(f"citation `[{citation}]` (the forms are `[@key]`, `[@key, p. 30]` and " + "`[@key; @other]`)", line) def _check_table(self, lines: list, number: int, in_methods: bool, in_method: bool) -> int: """ - check the table whose header row is `lines[number]`. a table is only possible as the argument table of a - method in the class methods section. the first column is the argument name, the last column its text; - the columns between them add `heading: value` to the text. + check the table whose header row is `lines[number]`. in a methods section, a table is only possible as the + argument table of a method: the first column is the argument name, the last column its text, and the + columns between them add `heading: value` to the text. outside the methods sections, a table gives + `table::`, with the header row in bold. :return: the index after the last row of the table """ header_line = number + 1 - if not in_methods: - self.unsupported("table (only the argument table of a method in the `## Class methods` section)", - header_line) - if not in_method: + if in_methods and not in_method: self.unsupported("table outside a method (put a heading like `### *ar` before it)", header_line) end = tables.table_end(lines, number) for index in range(number, end): @@ -233,21 +263,41 @@ def _check_table(self, lines: list, number: int, in_methods: bool, in_method: bo if len(tables.split_row(lines[number + 1])) != len(header): self.unsupported("table whose delimiter row has another number of cells than its header row", header_line + 1) - if len(header) < 2: - self.unsupported("argument table with one column (the first column is the name, the last the text)", - header_line) - if not all(header[1:-1]): - self.unsupported("argument table column without a heading", header_line) if end == number + 2: self.unsupported("table without rows", header_line) - names = set() for index in range(number + 2, end): row = lines[index] if not tables.has_pipe(row): self.unsupported("line without `|` after a table (put an empty line before it)", index + 1) - cells = tables.split_row(row) - if len(cells) > len(header): + if len(tables.split_row(row)) > len(header): self.unsupported("table row with more cells than the header row", index + 1) + if in_methods: + self._check_argument_table(lines, number, end) + else: + for cell in header: + # the header row is bold, and SCDoc's `strong::` cannot hold other tags + if ("`" in cell or "*" in cell or re.search(syntax.INLINE_MATH_STRICT, cell) + or re.search(syntax.LINK, cell) or re.search(self.footnote_mark_regex, cell) + or re.search(syntax.CITATION, cell)): + self.unsupported("code, math, a link, a footnote, a citation, or bold or italic text in the " + "header row of a table (the header row is bold)", header_line) + return end + + def _check_argument_table(self, lines: list, number: int, end: int): + """ + check the columns and the rows of the argument table from `lines[number]` (the header row) to + `lines[end]`. + """ + header_line = number + 1 + header = tables.split_row(lines[number]) + if len(header) < 2: + self.unsupported("argument table with one column (the first column is the name, the last the text)", + header_line) + if not all(header[1:-1]): + self.unsupported("argument table column without a heading", header_line) + names = set() + for index in range(number + 2, end): + cells = tables.split_row(lines[index]) name = re.fullmatch(self.argument_name_regex, cells[0]) if not name: self.unsupported(f"argument name `{cells[0]}` (a name, or a name in code)", index + 1) @@ -256,28 +306,119 @@ def _check_table(self, lines: list, number: int, in_methods: bool, in_method: bo names.add(name[2]) if len(cells) < len(header) or not cells[-1]: self.unsupported(f"argument `{name[2]}` without text", index + 1) - return end + + def _check_image(self, image, text: str, previous: str, following: str, line: int): + """ + check an image `![caption](path)`. SCDoc shows an image as a block, thus the image must be alone in its + paragraph. the path is relative to the schelp file. + """ + if text.strip() != image[0] or self._is_paragraph_line(previous) or self._is_paragraph_line(following): + self.unsupported("image in a line of text (put the image alone in a paragraph)", line) + problem = self.image_problem(image[1], image[2]) + if problem: + self.unsupported(problem, line) + + @classmethod + def image_problem(cls, caption: str, path: str): + """ + the construct that SCDoc cannot write in an image with `caption` and `path`, or `None`. SCDoc splits the + tag at each `#`: path, caption, link. + """ + if not path.strip() or re.match(r"[A-Za-z][A-Za-z0-9+.-]*:|/", path): + return "image that is not a relative path (put the image file next to the schelp file)" + if "#" in path or "#" in caption: + return "`#` in the caption or the path of an image" + # SCDoc shows the caption as plain text + if (cls.code_token[0] in caption or "`" in caption or "*" in caption + or re.search(syntax.INLINE_MATH_STRICT, caption) or re.search(syntax.MATH_TOKEN_REGEX, caption) + or re.search(r"\[[^\]]*\]", caption)): + return "code, math, a link, a footnote, or bold or italic text in the caption of an image" + return None + + def _check_quote_line(self, text: str, line: int): + """ + check a line of a block quote that is not an alert. the quote is in italics, and SCDoc's `emphasis::` cannot + hold other tags or blocks. + """ + content = re.sub(r"^>[ \t]?", "", text) + if content.lstrip().startswith(">"): + self.unsupported("block quote in a block quote", line) + if re.match(self.list_item_regex, content): + self.unsupported("list in a block quote", line) + if re.match(syntax.HEADING_STRICT, content): + self.unsupported("heading in a block quote", line) + if (self.code_token[0] in content or "*" in content or re.search(syntax.INLINE_MATH_STRICT, content) + or re.search(syntax.LINK, content) or re.search(self.footnote_mark_regex, content) + or re.search(syntax.CITATION, content)): + self.unsupported(self.markup_in_quote_construct, line) + + indented_regex = r"( {4}|\t)\S" + + def footnote_paragraphs(self, lines: list, number: int) -> list: + """ + the paragraphs of the footnote whose definition (`[^1]: text`) is `lines[number]`, as lists of line + indexes. the lines of a paragraph follow each other; the lines of a later paragraph have an indent of + 4 spaces or a tab, and empty lines come before it. + """ + paragraphs = [[number]] + index = number + 1 + while index < len(lines): + line = lines[index] + if not line.strip(): + following = next((i for i in range(index + 1, len(lines)) if lines[i].strip()), None) + if following is None or not re.match(self.indented_regex, lines[following]): + break + paragraphs.append([following]) + index = following + 1 + continue + if re.match(self.footnote_definition_regex, line) or not ( + self._is_paragraph_line(line) or re.match(self.indented_regex, line)): + break + paragraphs[-1].append(index) + index += 1 + return paragraphs + + def join_footnotes(self, string: str) -> str: + """ + put each footnote definition on one line, with a paragraph mark between its paragraphs, because the + converters take the first line of a footnote definition as its text. `footnote()` writes the paragraphs. + """ + lines = string.split("\n") + out = [] + number = 0 + while number < len(lines): + if not re.match(self.footnote_definition_regex, lines[number]): + out.append(lines[number]) + number += 1 + continue + paragraphs = self.footnote_paragraphs(lines, number) + out.append(self.footnote_paragraph_mark.join(" ".join(lines[i].strip() for i in paragraph) + for paragraph in paragraphs)) + number = paragraphs[-1][-1] + 1 + return "\n".join(out) def _check_method_part(self, lines: list, number: int, in_methods: bool, part): """ - check a line of a method in the class methods section, after the method heading, and give the part of the - method that the line is in. the parts of a method are its text, its argument table and its return value, - in this order. SCDoc puts all text after an argument into that argument, and all text after `returns::` - into the return value: thus only a `Returns:` paragraph can follow the table, and nothing can follow it. - headings and tables are checked in `check_source()`. + check a line of a method in a methods section, after the method heading, and give the part of the + method that the line is in. the parts of a method are its text, its argument table, its return value and + its discussion, in this order. SCDoc puts all text after an argument into that argument, and all text after + `returns::` into the return value: thus only a `Returns:` paragraph or a `#### Discussion` heading can + follow the table, and only the heading can follow the `Returns:` paragraph. headings and tables are + checked in `check_source()`. """ line = lines[number] - if (not in_methods or part is None or not line.strip() or re.match(syntax.HEADING_STRICT, line) - or tables.starts_table(lines, number)): + if (not in_methods or part in (None, "discussion") or not line.strip() + or re.match(syntax.HEADING_STRICT, line) or tables.starts_table(lines, number)): return part paragraph_start = number == 0 or not lines[number - 1].strip() if paragraph_start and line.startswith(self.returns_mark) and part != "returns": return "returns" if part == "table": - self.unsupported("text after the argument table of a method (only a `Returns:` paragraph can follow it)", - number + 1) + self.unsupported("text after the argument table of a method (only a `Returns:` paragraph or a " + "`#### Discussion` heading can follow it)", number + 1) if part == "returns" and paragraph_start: - self.unsupported("text after the `Returns:` paragraph of a method", number + 1) + self.unsupported("text after the `Returns:` paragraph of a method (put a `#### Discussion` heading " + "before it)", number + 1) return part def check_source(self, markdown: str): @@ -292,9 +433,11 @@ def check_source(self, markdown: str): in_code = False previous_is_quote = False - # the class methods section: in a method, the parts after the text are the argument table and then the - # return value. `method_part` is the last part: None (no method), "text", "table" or "returns" - in_methods = False + plain_quote = False # whether the block quote of the last quote line is a quote, not an alert + # a methods section: in a method, the parts after the text are the argument table, the return value and the + # discussion. `method_part` is the last part: None (no method), "text", "table", "returns" or "discussion". + # `methods_mark` is the mark of the method names of the section (`*` or `-`), or None + methods_mark = None method_part = None table_end = 0 # the index after the last row of the last table delimiter_rows = set() @@ -304,6 +447,7 @@ def check_source(self, markdown: str): fences = line.count(syntax.CODE_FENCE) if number in delimiter_rows: continue + in_methods = methods_mark is not None if not in_code and number >= table_end: method_part = self._check_method_part(lines, number, in_methods, method_part) if in_code: @@ -318,10 +462,10 @@ def check_source(self, markdown: str): self.unsupported("code block title", line_number) if re.search(r'hl_lines="', info): self.unsupported("highlighted lines in a code block", line_number) - # a code block can be in an admonition, not at the start of a block quote + # a code block can be in an alert, not in a quote: the quote is in italics is_quote = line.startswith(">") - if is_quote and not previous_is_quote: - self.unsupported("block quote", line_number) + if is_quote and (plain_quote or not previous_is_quote): + self.unsupported("code block in a block quote", line_number) previous_is_quote = is_quote continue @@ -337,16 +481,23 @@ def check_source(self, markdown: str): if level_1_headings > 1: self.unsupported("second level 1 heading (the first one is the title of the document: use level 2 for sections)", line_number) if level == 2: - in_methods = heading[3].strip().lower() == self.methods_section + methods_mark = self.methods_sections.get(heading[3].strip().lower()) method_part = None - if in_methods and level == 3 and re.match(self.method_heading_regex, line): + if methods_mark and level == 3 and re.match(self.method_heading_regex(methods_mark), line): method_part = "text" - elif in_methods and level >= 3: - self.unsupported("heading in the class methods section that is not a method " - "(a method heading is like `### *ar` or `### *ar, *kr`)", line_number) + elif (methods_mark and method_part not in (None, "discussion") + and re.match(self.discussion_heading_regex, line)): + method_part = "discussion" + elif methods_mark and level >= 3: + self.unsupported(f"heading in a methods section that is not a method or the discussion of a " + f"method (a method heading is like `### {methods_mark}ar` or " + f"`### {methods_mark}ar, {methods_mark}kr`; one `#### Discussion` heading " + f"can follow it)", line_number) else: self._check_heading_source(heading[3], line_number) if number >= table_end and tables.starts_table(lines, number): + if method_part == "discussion": + self.unsupported("table in the discussion of a method", line_number) table_end = self._check_table(lines, number, in_methods, method_part is not None) delimiter_rows.add(number + 1) if method_part in ("table", "returns"): @@ -365,10 +516,11 @@ def check_source(self, markdown: str): self.unsupported("line break tag", line_number) if re.search(syntax.AUDIO, text): self.unsupported("audio file", line_number) - if re.search(syntax.IMAGE, text): - self.unsupported("image", line_number) - if re.search(syntax.CITATION, text): - self.unsupported("citation", line_number) + for image in re.finditer(syntax.IMAGE, text): + self._check_image(image, text, previous, lines[number + 1] if number + 1 < len(lines) else "", + line_number) + for citation in re.finditer(syntax.CITATION, text): + self._check_citation(citation[1], line_number) if re.search(self.autolink_regex, prose): self.unsupported("link in `<` and `>` (write the URL alone, or use `[text](URL)`)", line_number) if "` in the text) to the schelp text that takes its place + :param bibliography: the path of a bibliography file for the citations (`[@key]`). the program `pandoc` + writes the citations, which become footnotes. without a bibliography, a citation stops the + conversion :return: The converted schelp markup """ - backend = SchelpBackend(insertions) + backend = SchelpBackend(insertions, bibliography) front_matter, data = backend.take_front_matter(data) body = run_pipeline(data, backend) backend.check_insertions() @@ -77,6 +80,7 @@ def run_pipeline(data, backend): # by `prepare_markdown()` data = MDMethods.mark(data, backend) # argument tables: after code blocks, and before inline code, # because a `\|` in inline code in a cell is a `|` + data = MDTable.mark(data, backend) # the other tables, for the same reason data = MDCode.inline_code(data, backend) data = MDInsertion.apply(data, backend) # text of the caller is not changed, either data, mathdict = MDMath.stash_math(data, backend) @@ -89,12 +93,16 @@ def run_pipeline(data, backend): data = MDQuote.block_quote(data, backend) data = MDList.unordered_l(data, backend) data = MDList.ordered_l(data, backend) + if backend.citations_before_footnotes: + data = MDReference.citation(data, backend) data = MDReference.footnote(data, backend) data = MDReference.hyperlink(data, backend) - data = MDReference.citation(data, backend) + if not backend.citations_before_footnotes: + data = MDReference.citation(data, backend) data = MDList.definition_l(data, backend) data = MDHeader.convert(data, backend) data = MDMethods.convert(data, backend) + data = MDTable.convert(data, backend) # "simple" replacements: bold, italics and the like data = MDSimple.convert(data, backend) diff --git a/tests/conftest.py b/tests/conftest.py index 0d71d0f..81bcee3 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -32,3 +32,23 @@ def rendered_pages(sclang): return schelp_fixtures.render_all(sclang) except schelp_fixtures.RenderError as error: pytest.fail(str(error), pytrace=False) + + +@pytest.fixture(scope="session") +def pandoc(): + """The path of pandoc. Tests that need it are skipped if it is not there.""" + path = schelp_fixtures.find_pandoc() + if not path: + message = "pandoc not found (put it on PATH or set PANDOC)" + if os.environ.get("MD2MISC_REQUIRE_PANDOC"): + pytest.fail(message) # a check must not pass without these tests + pytest.skip(message) + return path + + +@pytest.fixture(scope="session") +def same_pandoc_as_fixtures(pandoc): + """Skip a test that compares the text of citations if pandoc is not the version that made the fixtures.""" + version, expected = schelp_fixtures.pandoc_version(pandoc), schelp_fixtures.fixture_pandoc_version() + if version != expected: + pytest.skip(f"the fixtures with citations are from pandoc {expected}, this is pandoc {version}") diff --git a/tests/schelp/PANDOC_VERSION b/tests/schelp/PANDOC_VERSION new file mode 100644 index 0000000..40479ad --- /dev/null +++ b/tests/schelp/PANDOC_VERSION @@ -0,0 +1 @@ +3.7.0.2 diff --git a/tests/schelp/citations.bib b/tests/schelp/citations.bib new file mode 100644 index 0000000..be4ba8c --- /dev/null +++ b/tests/schelp/citations.bib @@ -0,0 +1,31 @@ +@book{doe1999, + author = {Doe, Jane}, + title = {Sound and Wood}, + publisher = {Acme}, + year = {1999} +} + +@book{doe1999b, + author = {Doe, Jane}, + title = {More Wood}, + publisher = {Acme}, + year = {1999} +} + +@article{smith2000, + author = {Smith, John and Lee, Ann}, + title = {Bars and Rods: A Study of Modes}, + journal = {Journal of Acoustics}, + volume = {3}, + pages = {1--9}, + year = {2000}, + doi = {10.1000/xyz} +} + +@inproceedings{fontana2007, + author = {Fontana, Federico}, + title = {Preserving the Digital Structure of the {Moog} {VCF}}, + booktitle = {Proceedings of the International Computer Music Conference}, + address = {Copenhagen}, + year = {2007} +} diff --git a/tests/schelp/citations.html b/tests/schelp/citations.html new file mode 100644 index 0000000..80dc925 --- /dev/null +++ b/tests/schelp/citations.html @@ -0,0 +1,16 @@ +
+
+Reference (extension) + | Tests +

Md2miscTestCitations
ExtensionExtension

+
md2misc test page
+
+
+
+

Description

+ +

Wooden bars ring for a long time1 , and rods too2 . The filter follows a known design 3 . +

The decay depends on the wood4 . Two sources in one citation give one footnote 5 . +

A footnote of the author can cite a source too.6

+
[1] - Doe, Jane. 1999b. Sound and Wood. Acme, p. 30.
[2] - Smith, John, and Ann Lee. 2000. “Bars and Rods: A Study of Modes.” Journal of Acoustics 3: 1–9. https://doi.org/10.1000/xyz.
[3] - Fontana, Federico. 2007. “Preserving the Digital Structure of the Moog VCF.” In Proceedings of the International Computer Music Conference. Copenhagen, pp. 12–14.
[4] - Doe 1999b, 31.
[5] - Doe, Jane. 1999a. More Wood. Acme; Smith and Lee 2000.
[6] - As described by (Doe 1999b, 30). +

The second paragraph of the footnote (Smith and Lee 2000).

diff --git a/tests/schelp/citations.json b/tests/schelp/citations.json new file mode 100644 index 0000000..3ebff32 --- /dev/null +++ b/tests/schelp/citations.json @@ -0,0 +1 @@ +{"bibliography": "citations.bib"} diff --git a/tests/schelp/citations.md b/tests/schelp/citations.md new file mode 100644 index 0000000..920bb9e --- /dev/null +++ b/tests/schelp/citations.md @@ -0,0 +1,13 @@ +## Description + +Wooden bars ring for a long time [@doe1999, p. 30], and rods too [@smith2000]. The filter follows a known design +[@fontana2007, 12-14]. + +The decay depends on the wood [@doe1999, 31]. Two sources in one citation give one footnote +[-@doe1999b; @smith2000]. + +A footnote of the author can cite a source too.[^1] + +[^1]: As described by [@doe1999, 30]. + + The second paragraph of the footnote [@smith2000]. diff --git a/tests/schelp/citations.schelp b/tests/schelp/citations.schelp new file mode 100644 index 0000000..ba8194c --- /dev/null +++ b/tests/schelp/citations.schelp @@ -0,0 +1,11 @@ +DESCRIPTION:: + +Wooden bars ring for a long time footnote::Doe, Jane. 1999b. emphasis::Sound and Wood::. Acme, p. 30.::, and rods too footnote::Smith, John, and Ann Lee. 2000. “Bars and Rods: A Study of Modes.” emphasis::Journal of Acoustics:: 3: 1–9. link::https://doi.org/10.1000/xyz::.::. The filter follows a known design +footnote::Fontana, Federico. 2007. “Preserving the Digital Structure of the Moog VCF.” In emphasis::Proceedings of the International Computer Music Conference::. Copenhagen, pp. 12–14.::. + +The decay depends on the wood footnote::Doe 1999b, 31.::. Two sources in one citation give one footnote +footnote::Doe, Jane. 1999a. emphasis::More Wood::. Acme; Smith and Lee 2000.::. + +A footnote of the author can cite a source too.footnote::As described by (Doe 1999b, 30). + +The second paragraph of the footnote (Smith and Lee 2000).:: diff --git a/tests/schelp/footnotes.html b/tests/schelp/footnotes.html index f654434..8e9afa9 100644 --- a/tests/schelp/footnotes.html +++ b/tests/schelp/footnotes.html @@ -9,5 +9,7 @@

Footnotes

-

A sentence with a footnote.1 Another sentence, with a second footnote.2

-
[1] - The first note, with bold text and a link to a class.
[2] - The second note.
+

A sentence with a footnote.1 Another sentence, with a second footnote.2 +

A note of more paragraphs.3

+
[1] - The first note, with bold text and a link to a class.
[2] - The second note.
[3] - The first paragraph of the note, on two lines. +

The second paragraph of the note.

diff --git a/tests/schelp/footnotes.md b/tests/schelp/footnotes.md index 5f17840..fcf70dc 100644 --- a/tests/schelp/footnotes.md +++ b/tests/schelp/footnotes.md @@ -2,5 +2,11 @@ A sentence with a footnote.[^1] Another sentence, with a second footnote.[^2] +A note of more paragraphs.[^3] + [^1]: The first note, with **bold** text and a link to [a class](sc:Classes/Pbind). [^2]: The second note. +[^3]: The first paragraph of the note, + on two lines. + + The second paragraph of the note. diff --git a/tests/schelp/footnotes.schelp b/tests/schelp/footnotes.schelp index 6034869..3fc6407 100644 --- a/tests/schelp/footnotes.schelp +++ b/tests/schelp/footnotes.schelp @@ -1,3 +1,7 @@ SECTION::Footnotes A sentence with a footnote.footnote::The first note, with strong::bold:: text and a link to link::Classes/Pbind##a class::.:: Another sentence, with a second footnote.footnote::The second note.:: + +A note of more paragraphs.footnote::The first paragraph of the note, on two lines. + +The second paragraph of the note.:: diff --git a/tests/schelp/images.html b/tests/schelp/images.html new file mode 100644 index 0000000..e304fb4 --- /dev/null +++ b/tests/schelp/images.html @@ -0,0 +1,17 @@ +
+
+Reference (extension) + | Tests +

Md2miscTestImages
ExtensionExtension

+
md2misc test page
+
+
+
+

Description

+ +

An image with a caption:


A test image: one red pixel
+ +

An image without a caption, after a heading:

A heading

+
+ +

diff --git a/tests/schelp/images.md b/tests/schelp/images.md new file mode 100644 index 0000000..f57b386 --- /dev/null +++ b/tests/schelp/images.md @@ -0,0 +1,11 @@ +## Description + +An image with a caption: + +![A test image: one red pixel](images/md2misc-test.png) + +An image without a caption, after a heading: + +### A heading + +![](images/md2misc-test.png) diff --git a/tests/schelp/images.schelp b/tests/schelp/images.schelp new file mode 100644 index 0000000..2594117 --- /dev/null +++ b/tests/schelp/images.schelp @@ -0,0 +1,11 @@ +DESCRIPTION:: + +An image with a caption: + +image::images/md2misc-test.png#A test image: one red pixel:: + +An image without a caption, after a heading: + +SUBSECTION::A heading + +image::images/md2misc-test.png:: diff --git a/tests/schelp/images/md2misc-test.png b/tests/schelp/images/md2misc-test.png new file mode 100644 index 0000000..62a5f8f Binary files /dev/null and b/tests/schelp/images/md2misc-test.png differ diff --git a/tests/schelp/methods.html b/tests/schelp/methods.html index 961fef9..20c4b05 100644 --- a/tests/schelp/methods.html +++ b/tests/schelp/methods.html @@ -3,7 +3,7 @@ Classes (extension) | Tests

Md2miscTestMethods
ExtensionExtension

-
The class methods section, with argument tables
+
The methods sections, with argument tables and discussions
Location: NOT INSTALLED!
@@ -27,9 +27,23 @@

.

Makes an instance.

Returns:

-

a new instance.

Inherited class methods

+

a new instance.

Discussion:

+ +

The instance plays nothing until play is called.

Inherited class methods

Instance Methods

-

Inherited instance methods

+

.play

+

.stop

+
+

Starts or stops the grains.

Arguments:

+ +
fadeTime +

The time of the fade, in seconds.

Returns:

+
+

this.

Discussion:

+ +

A fade time of 0 starts at once.

+
+

Inherited instance methods

Examples

diff --git a/tests/schelp/methods.md b/tests/schelp/methods.md index 8db8bcf..9e8e25c 100644 --- a/tests/schelp/methods.md +++ b/tests/schelp/methods.md @@ -1,5 +1,5 @@ --- -summary: The class methods section, with argument tables +summary: The methods sections, with argument tables and discussions categories: Tests --- @@ -30,6 +30,30 @@ Makes an instance. Returns: a new instance. +#### Discussion + +The instance plays nothing until `play` is called. + +## Instance methods + +### -play, -stop + +Starts or stops the grains. + +| Argument | What it does | +|---|---| +| `fadeTime` | The time of the fade, in seconds. | + +Returns: this. + +#### Discussion + +A fade time of 0 starts at once. + +```supercollider +Md2miscTestMethods.new.play(0.1); +``` + ## Examples ```supercollider diff --git a/tests/schelp/methods.schelp b/tests/schelp/methods.schelp index 61f54e8..7c35ad3 100644 --- a/tests/schelp/methods.schelp +++ b/tests/schelp/methods.schelp @@ -1,5 +1,5 @@ CLASS::Md2miscTestMethods -SUMMARY::The class methods section, with argument tables +SUMMARY::The methods sections, with argument tables and discussions CATEGORIES::Tests DESCRIPTION:: @@ -37,6 +37,29 @@ Makes an instance. returns::a new instance. +discussion:: + +The instance plays nothing until code::play:: is called. + +INSTANCEMETHODS:: + +METHOD::play, stop + +Starts or stops the grains. + +ARGUMENT::fadeTime +The time of the fade, in seconds. + +returns::this. + +discussion:: + +A fade time of 0 starts at once. + +code:: +Md2miscTestMethods.new.play(0.1); +:: + EXAMPLES:: code:: diff --git a/tests/schelp/quotes.html b/tests/schelp/quotes.html new file mode 100644 index 0000000..e70ae9d --- /dev/null +++ b/tests/schelp/quotes.html @@ -0,0 +1,21 @@ +
+
+Reference (extension) + | Tests +

Md2miscTestQuotes
ExtensionExtension

+
md2misc test page
+
+
+
+

Description

+ +

A quote of one paragraph: +

"Passenger to taxi driver: take me to number 37. I'll give you the street name when we are there." +

An Austrian math teacher's joke. +

A quote of more paragraphs, with "quotation marks" in it: +

"The first paragraph, on two lines. +

The second paragraph. +

The last one: it ends with a colon:" +

An alert after a quote:

NOTE: A note of two paragraphs. +

The second paragraph of the note.

+

diff --git a/tests/schelp/quotes.md b/tests/schelp/quotes.md new file mode 100644 index 0000000..fc2c231 --- /dev/null +++ b/tests/schelp/quotes.md @@ -0,0 +1,23 @@ +## Description + +A quote of one paragraph: + +> Passenger to taxi driver: take me to number 37. I'll give you the street name when we are there. + +An Austrian math teacher's joke. + +A quote of more paragraphs, with "quotation marks" in it: + +> The first paragraph, +> on two lines. +> +> The second paragraph. +> +> The last one: it ends with a colon: + +An alert after a quote: + +> [!NOTE] +> A note of two paragraphs. +> +> The second paragraph of the note. diff --git a/tests/schelp/quotes.schelp b/tests/schelp/quotes.schelp new file mode 100644 index 0000000..0c936e4 --- /dev/null +++ b/tests/schelp/quotes.schelp @@ -0,0 +1,25 @@ +DESCRIPTION:: + +A quote of one paragraph: + +emphasis::"Passenger to taxi driver: take me to number 37. I'll give you the street name when we are there.":: + +An Austrian math teacher's joke. + +A quote of more paragraphs, with "quotation marks" in it: + +emphasis::"The first paragraph, +on two lines.:: + +emphasis::The second paragraph.:: + +emphasis::The last one: it ends with a colon:":: + +An alert after a quote: + +note:: +A note of two paragraphs. + +The second paragraph of the note. + +:: diff --git a/tests/schelp/tables.html b/tests/schelp/tables.html new file mode 100644 index 0000000..553f1bc --- /dev/null +++ b/tests/schelp/tables.html @@ -0,0 +1,17 @@ +

+
+Reference (extension) + | Tests +

Md2miscTestTables
ExtensionExtension

+
md2misc test page
+
+
+
+

Description

+ +

A table with a header row, markup in the cells and a short row: +
ParameterRangeEffect
freq20 to 20000The frequency, see SinOsc.
Q0.1 to 100Sharp with a high value.
mode0 | 1Two || bars in text.
gain
+A table without a header row: +
ab
cd
+ +

diff --git a/tests/schelp/tables.md b/tests/schelp/tables.md new file mode 100644 index 0000000..2b8db17 --- /dev/null +++ b/tests/schelp/tables.md @@ -0,0 +1,17 @@ +## Description + +A table with a header row, markup in the cells and a short row: + +| Parameter | Range | Effect | +|:---|:---:|---:| +| `freq` | 20 to 20000 | The frequency, see [SinOsc](sc:Classes/SinOsc). | +| *Q* | 0.1 to 100 | **Sharp** with a high value. | +| mode | `0` \| `1` | Two \|\| bars in text. | +| gain | | + +A table without a header row: + +| | | +|---|---| +| a | b | +| c | d | diff --git a/tests/schelp/tables.schelp b/tests/schelp/tables.schelp new file mode 100644 index 0000000..0853e2b --- /dev/null +++ b/tests/schelp/tables.schelp @@ -0,0 +1,18 @@ +DESCRIPTION:: + +A table with a header row, markup in the cells and a short row: + +table:: +## strong::Parameter:: || strong::Range:: || strong::Effect:: +## code::freq:: || 20 to 20000 || The frequency, see link::Classes/SinOsc::. +## emphasis::Q:: || 0.1 to 100 || strong::Sharp:: with a high value. +## mode || code::0:: | code::1:: || Two \|| bars in text. +## gain || || +:: + +A table without a header row: + +table:: +## a || b +## c || d +:: diff --git a/tests/schelp_cases.py b/tests/schelp_cases.py index 131af4a..5bd68b4 100644 --- a/tests/schelp_cases.py +++ b/tests/schelp_cases.py @@ -6,32 +6,45 @@ UNSUPPORTED = [ ("# One\n\nText.\n\n# Two\n", "second level 1 heading", 5), ("# Heading with *italics*\n", "heading", 1), - ("---\nsummary: A\n---\n\n## Section\n\n> Not an alert.\n", "block quote", 7), ("---\nsummary: A\nauthor: Me\n---\n", "front matter key `author`", 3), ("---\nsummary: [A, B]\n---\n", "front matter key `summary` with a list", 2), ("---\nsummary A\n---\n", "front matter line", 2), ("## Heading with *italics*\n", "heading", 1), ("Text.\n\n## Heading with `code`\n", "heading", 3), ("## Heading with $x$\n", "heading", 1), - ("Text.\n\n> A block quote\n", "block quote", 3), - ("> [!NOTE]\n> Fine.\n\n> Not fine.\n", "block quote", 4), ("Text with [a page](other.md).\n", "link that is not an http URL", 1), ("Text.\n\nSee [@doe1999].\n", "citation", 3), - ("![An image](image.png)\n", "image", 1), + ("![An image](https://example.com/image.png)\n", "image that is not a relative path", 1), + ("![An image](/home/image.png)\n", "image that is not a relative path", 1), + ("![An image]()\n", "image that is not a relative path", 1), + ("![Figure #1](image.png)\n", "`#` in the caption or the path of an image", 1), + ("![An image](image.png#x)\n", "`#` in the caption or the path of an image", 1), + ("![An `image`](image.png)\n", "in the caption of an image", 1), + ("![An *image*](image.png)\n", "in the caption of an image", 1), + ("![An image[^1]](image.png)\n\n[^1]: A note.\n", "in the caption of an image", 1), ("![type:audio](sound.wav)\n", "audio file", 1), ("Above.\n\n---\n\nBelow.\n", "horizontal rule", 3), ("Text.\n\n```supercollider title=\"Example\"\nx = 1;\n```\n", "code block title", 3), ("```sc hl_lines=\"1\"\nx = 1;\n```\n", "highlighted lines", 1), ("Use **`code` in bold**.\n", "code inside bold or italic text", 1), ("A line
break.\n", "line break", 1), - ("Text.\n\n```\n# Fine in code\n> Fine in code\n```\n\n> Not in code.\n", "block quote", 8), - ("> [!FOO]\n> An alert that is not known.\n", "block quote", 1), - ("> ```\n> x = 1;\n> ```\n", "block quote", 1), - ("Text **see [a page](https://a.org)** here.\n", "link or footnote inside bold or italic text", 1), - ("Text *with a note[^1]* here.\n\n[^1]: The note.\n", "link or footnote inside bold or italic text", 1), - ("Text.\n\n## See [a page](https://a.org)\n", "link or footnote in a heading", 3), - ("## A heading[^1]\n\n[^1]: The note.\n", "link or footnote in a heading", 1), - ("# A title with [a link](sc:Classes/SinOsc)\n", "link or footnote in a heading", 1), + ("> [!FOO]\n> An alert that is not known.\n", "alert of a kind that is not known", 1), + ("Text.\n\n> A quote with `code`.\n", "in a block quote (the quote is in italics)", 3), + ("> A quote\n> with *italics*.\n", "in a block quote (the quote is in italics)", 2), + ("> A quote with **bold**.\n", "in a block quote (the quote is in italics)", 1), + ("> A quote with $x$.\n", "in a block quote (the quote is in italics)", 1), + ("> A quote with [a link](https://a.org).\n", "in a block quote (the quote is in italics)", 1), + ("> A quote.[^1]\n\n[^1]: A note.\n", "in a block quote (the quote is in italics)", 1), + ("> A quote\n>\n> - with a list\n", "list in a block quote", 3), + ("> A quote\n> ## with a heading\n", "heading in a block quote", 2), + ("> A quote\n> > in a quote\n", "block quote in a block quote", 2), + ("> A quote\n> ```\n> x = 1;\n> ```\n", "code block in a block quote", 2), + ("> ```\n> x = 1;\n> ```\n", "code block in a block quote", 1), + ("Text **see [a page](https://a.org)** here.\n", "link, footnote or citation inside bold or italic text", 1), + ("Text *with a note[^1]* here.\n\n[^1]: The note.\n", "link, footnote or citation inside bold or italic text", 1), + ("Text.\n\n## See [a page](https://a.org)\n", "link, footnote or citation in a heading", 3), + ("## A heading[^1]\n\n[^1]: The note.\n", "link, footnote or citation in a heading", 1), + ("# A title with [a link](sc:Classes/SinOsc)\n", "link, footnote or citation in a heading", 1), ("See [the C# guide](https://example.com).\n", "`#` in the text of a link", 1), ("See [a part](https://example.com/a#b#c).\n", "link with more than one `#`", 1), ("See [a method](sc:Classes/SinOsc#a#b).\n", "link with more than one `#`", 1), @@ -49,12 +62,23 @@ ("Above.\n\n_ _ _\n\nBelow.\n", "horizontal rule", 3), ("A title\n=======\n\nText.\n", "heading underlined with `=` or `-`", 2), ("Text.\n\nA title\n-------\n", "heading underlined with `=` or `-`", 4), - ("Text.\n\n| a | b |\n|---|---|\n| 1 | 2 |\n", "table", 3), + ("Text with ![an image](image.png) in it.\n", "image in a line of text", 1), + ("Text.\n![An image](image.png)\n", "image in a line of text", 2), + ("![An image](image.png)\nText.\n", "image in a line of text", 1), + ("Text.\n\n| a | b |\n|---|\n| 1 | 2 |\n", "delimiter row has another number of cells", 4), + ("Text.\n\n| a | b |\n|---|---|\n| 1 | 2 | 3 |\n", "more cells than the header", 5), + ("Text.\n\n| a | b |\n|---|---|\n| 1 | `a|b` |\n", "`|` in code in a table", 5), + ("Text.\n\n| a | b |\n|---|---|\n| 1 | a \\\\| b |\n", "`\\\\|` in a table row", 5), + ("Text.\n\n| a | b |\n|---|---|\n| 1 | 2 |\nMore text.\n", "line without `|` after a table", 6), + ("Text.\n\n| a | b |\n|---|---|\n", "table without rows", 3), + ("| `a` | b |\n|---|---|\n| 1 | 2 |\n", "in the header row of a table", 1), + ("| *a* | b |\n|---|---|\n| 1 | 2 |\n", "in the header row of a table", 1), + ("| a | [b](https://a.org) |\n|---|---|\n| 1 | 2 |\n", "in the header row of a table", 1), + ("| a | $x$ |\n|---|---|\n| 1 | 2 |\n", "in the header row of a table", 1), ] + [(M + markdown, construct, line + 2) for markdown, construct, line in [ # the class methods section (M is its heading): the markdown starts at line 3 ("| a | b |\n|---|---|\n| x | y |\n", "table outside a method", 1), ("Intro.\n\n| a | b |\n|---|---|\n| x | y |\n", "table outside a method", 3), - ("### *ar\n\nText.\n\n## Examples\n\n| a | b |\n|---|---|\n| x | y |\n", "table (only the argument table", 7), ("### *ar\n\n| a | b |\n|---|\n| x | y |\n", "delimiter row has another number of cells", 4), ("### *ar\n\n| a | b |\n|---|---|---|\n| x | y |\n", "delimiter row has another number of cells", 4), ("### *ar\n\n| a |\n|---|\n| x |\n", "argument table with one column", 3), @@ -85,17 +109,29 @@ ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n\n> [!NOTE]\n> A note.\n", "text after the argument table", 7), ("### *ar\n\nReturns: x.\n\nMore text.\n", "text after the `Returns:` paragraph", 5), ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n\nReturns: x.\n\nReturns: y.\n", "text after the `Returns:`", 9), - ("### Arguments\n\nText.\n", "heading in the class methods section that is not a method", 1), - ("### ar\n\nText.\n", "heading in the class methods section that is not a method", 1), - ("### *ar *kr\n\nText.\n", "heading in the class methods section that is not a method", 1), - ("### *ar\n\n#### Details\n\nText.\n", "heading in the class methods section that is not a method", 3), + ("### Arguments\n\nText.\n", "heading in a methods section that is not a method", 1), + ("### ar\n\nText.\n", "heading in a methods section that is not a method", 1), + ("### *ar *kr\n\nText.\n", "heading in a methods section that is not a method", 1), + ("### *ar\n\n#### Details\n\nText.\n", "heading in a methods section that is not a method", 3), + ("### -ar\n\nText.\n", "heading in a methods section that is not a method", 1), + ("#### Discussion\n\nText.\n", "heading in a methods section that is not a method", 1), + ("### *ar\n\n#### Discussion\n\nA.\n\n#### Discussion\n\nB.\n", "heading in a methods section", 7), + ("### *ar\n\n#### Discussion\n\n| a | b |\n|---|---|\n| x | y |\n", "table in the discussion", 5), + ("### *ar\n\n#### Discussion\n\nA.\n\n##### More\n\nB.\n", "heading in a methods section", 7), ]] + [ + # the instance methods section: the markdown starts at line 3 + ("## Instance methods\n\n" + markdown, construct, line + 2) for markdown, construct, line in [ + ("### *ar\n\nText.\n", "a method heading is like `### -ar`", 1), + ("### -play\n\n| a | b |\n|---|---|\n| x | y |\n\nMore text.\n", "text after the argument table", 7), + ("### -play\n\nReturns: x.\n\nMore text.\n", "put a `#### Discussion` heading before it", 5), + ] +] + [ ("See .\n", "link in `<` and `>`", 1), ("Mail .\n", "link in `<` and `>`", 1), ("Press Ctrl.\n", "HTML tag", 1), ("Text.\n\n\n", "HTML comment", 3), - ("Text.[^1]\n\n[^1]: Line one\n and line two.\n", "footnote with more than one line", 3), - ("Text.[^1]\n\n[^1]: Paragraph one.\n\n Paragraph two.\n", "footnote with more than one line", 3), + ("Text.[^1]\n\n[^1]: Paragraph one.\n\n - A list.\n", "list, code block or other block in a footnote", 5), + ("Text.[^1]\n\n[^1]: Paragraph one.\n > A quote.\n", "list, code block or other block in a footnote", 4), ] # Markdown that only the writers of the backend stop at, thus the error has no line. @@ -142,6 +178,12 @@ "## Class methods\n\n### *ar\n\n| a | b |\n|---|---|\n| x | y |\n## Examples\n\nText.\n", "## Class methods\n\n### *ar\n\n| a | b |\n|---|---|\n| x | Code `a \\| b`. |\n", "## Class methods\n\n### *ar\n\n```\n| a | b |\n```\n\n| a | b |\n|---|---|\n| x | y |\n", + "## Class methods\n\n### *ar\n\nText.\n\n## Examples\n\n| a | b |\n|---|---|\n| x | y |\n", + "| a | b |\n|---|---|\n| 1 |\n", + "---\ntitle: A\nsummary: B\n---\n\n## Section\n\n> A quote.\n", + "> [!NOTE]\n> An alert.\n\n> A quote.\n", + "Text.\n\n```\n# Fine in code\n> Fine in code\n```\n\n> A quote.\n", + "> A quote with a < b, \"quotation marks\" and C#.\n", ] # Markdown, and the parts of the HTML page that SCDoc must make from the schelp output. The cases of SUPPORTED are @@ -155,6 +197,25 @@ ("Math $a:$ here.\n", ["a: here."]), ("Text.[^1]\n\n[^1]: A note that ends with a colon:\n", ["A note that ends with a colon:"]), ("**Two colons::** here.\n", ["Two colons:: here."]), + ("Text.\n\n![A caption: with a colon](images/a.png)\n\nAfter.\n", + ["


A caption: with a colon
"]), + ("![](a.png)\n", ["
"]), + ("Text.\n\n> A quote.\n\nAfter.\n", ['

"A quote."\n

After.']), + ("> One\n> line.\n>\n> Two.\n>\n> Three:\n\n- A list after it.\n", + ['

"One line.\n

Two.\n

Three:"']), + ("> [!NOTE]\n> One.\n>\n> Two.\n", ["One.\n

Two."]), + # a tag directly after a letter: SCDoc needs a character between them that is not a letter + ("A word**bold**, a word*italic*, a word`code`, a word[link](https://example.com) and a word$x$.\n", + ["A word\u2060bold, a word\u2060italic, a word\u2060code, " + 'a word\u2060link and a word\u2060x.']), + ("Café**bold** and x_**bold** and 2**bold**.\n", + ["Café\u2060bold and x_bold and 2bold."]), + ("A word[^1] and a word [^2].\n\n[^1]: One.\n[^2]: Two.\n", + ["

A word[1] - Line one and line two."]), + ("Text.[^1] After.\n\n[^1]: Paragraph one,\n still one.\n\n Paragraph two.\n\n\tThree.\n\nNot in the note.\n", + ["] - Paragraph one, still one.\n

Paragraph two.\n

Three.", "

Not in the note."]), ("# A::B\n\nText.\n", ["

A::B"]), ("> [!NOTE]\n> Try this:\n> ```\n> x = 1;\n> ```\n> And then this.\n", ["", "And then this."]), @@ -165,4 +226,8 @@ ("Use `a::b` and `x\\` here.\n", ["a::b", "x\\ here."]), ("## Section: with a colon\n\nText.\n", ["

Section: with a colon

"]), ("Term:\n: A definition that ends with a colon:\n\nAfter.\n", ["
Term:
A definition that ends with a colon:"]), + ("| A | B |\n|---|---|\n| 1 | 2 |\n", ["\n
AB
12
"]), + ("| | |\n|---|---|\n| 1 | 2 |\n", ["\n
12
"]), + ("| A | |\n|---|---|\n| a \\|\\| b | `x \\| y` |\n", + ["Aa || bx | y"]), ] diff --git a/tests/schelp_fixtures.py b/tests/schelp_fixtures.py index 40fc676..101d3d9 100644 --- a/tests/schelp_fixtures.py +++ b/tests/schelp_fixtures.py @@ -2,14 +2,17 @@ """ The schelp fixtures, and what is needed to test with them. -A fixture is tests/schelp/NAME.md. NAME.json is optional: {"metadata": {...}, "insertions": {...}} are the -values that the caller of the conversion gives. Next to it are the files that the tests compare with: +A fixture is tests/schelp/NAME.md. The files in tests/schelp/images are next to the schelp files when SCDoc renders +them, as in a HelpSource folder. NAME.json is optional: {"metadata": {...}, "insertions": {...}} are the +values that the caller of the conversion gives, and {"bibliography": "NAME.bib"} is the bibliography of the +citations, relative to tests/schelp. A fixture with a bibliography needs the program pandoc. Next to it are the files that the tests compare with: NAME.schelp the output of the converter NAME.html the body of the page that SCDoc (headless sclang) renders from the output The HTML of a page changes with the version of SuperCollider. SCLANG_VERSION holds the version that made the .html -files; the tests compare a page with its .html file only with that version. +files; the tests compare a page with its .html file only with that version. The text of a citation can change with +the version of Pandoc: PANDOC_VERSION holds the version that made the files of the fixtures with a bibliography. The tests are in test_schelp_*.py. This file is also a tool: it writes the .schelp and .html files again from the current converter. Look at the diff afterwards. @@ -30,7 +33,9 @@ HERE = Path(__file__).resolve().parent REPO = HERE.parent FIXTURES = HERE / "schelp" +IMAGES = FIXTURES / "images" VERSION_FILE = FIXTURES / "SCLANG_VERSION" +PANDOC_VERSION_FILE = FIXTURES / "PANDOC_VERSION" class RenderError(Exception): @@ -50,13 +55,34 @@ def options_of(md_path: Path) -> dict: return json.loads(options_path.read_text()) if options_path.exists() else {} +def needs_pandoc(md_path: Path) -> bool: + return "bibliography" in options_of(md_path) + + def convert(md_path: Path) -> str: options = options_of(md_path) + bibliography = FIXTURES / options["bibliography"] if "bibliography" in options else None return importlib.import_module("md2misc").convert_schelp( - md_path.read_text(), options.get("metadata"), options.get("insertions") + md_path.read_text(), options.get("metadata"), options.get("insertions"), bibliography ) +def find_pandoc(): + """The path of pandoc, or `None`.""" + return os.environ.get("PANDOC") or shutil.which("pandoc") + + +def pandoc_version(pandoc: str) -> str: + """The version of pandoc, for example `3.7.0.2`.""" + done = subprocess.run([pandoc, "--version"], capture_output=True, text=True, timeout=60) + return done.stdout.split("\n", 1)[0].split()[-1] + + +def fixture_pandoc_version() -> str: + """The version of pandoc that made the files of the fixtures with a bibliography.""" + return PANDOC_VERSION_FILE.read_text().strip() + + def body_of(html: str) -> str: """The text of the page from its header to the link to the source, without things that change.""" start = html.index("
") @@ -87,11 +113,13 @@ def fixture_version() -> str: return VERSION_FILE.read_text().strip() -def render_texts(sclang: str, texts: dict, timeout: int = 180) -> dict: +def render_texts(sclang: str, texts: dict, timeout: int = 180, copied: list = None) -> dict: """ Render schelp texts with SCDoc, in one run of sclang. `texts` maps a name (letters, digits and `-`) to a schelp text. A text without a header gets a test header. Return, by name, the body of the HTML page, or a `RenderError` with the errors of SCDoc for that text. + The files of tests/schelp/images are in the folder `images` next to the schelp files. If `copied` is a list, it + gets the paths of these files that SCDoc put next to the HTML pages. """ results = {} with tempfile.TemporaryDirectory(prefix="md2misc-scdoc-") as tmp: @@ -99,6 +127,7 @@ def render_texts(sclang: str, texts: dict, timeout: int = 180) -> dict: data = tmp / "data" source = data / "SuperCollider/Extensions/md2misc-tests/HelpSource/Reference" source.mkdir(parents=True) + shutil.copytree(IMAGES, source / "images") (tmp / "home").mkdir() keys = {} # the key of the page in SCDoc, by name for name, text in texts.items(): @@ -151,12 +180,20 @@ def render_texts(sclang: str, texts: dict, timeout: int = 180) -> dict: results[name] = RenderError(f"SCDoc wrote no page for {name}\n" + done.stdout[-2000:]) else: results[name] = body_of(html_path.read_text()) + if copied is not None: + help_images = data / "SuperCollider/Help/Reference/images" + copied += sorted(str(p.relative_to(help_images.parent)) for p in help_images.rglob("*") if p.is_file()) return results def render_all(sclang: str, timeout: int = 180) -> dict: - """Render every fixture with SCDoc. Return the body of each HTML page, by fixture name.""" - results = render_texts(sclang, {md_path.stem: convert(md_path) for md_path in fixtures()}, timeout) + """ + Render every fixture with SCDoc. Return the body of each HTML page, by fixture name. Without pandoc, the + fixtures with a bibliography are not rendered. + """ + with_pandoc = find_pandoc() is not None + results = render_texts(sclang, {md_path.stem: convert(md_path) for md_path in fixtures() + if with_pandoc or not needs_pandoc(md_path)}, timeout) errors = [f"{name}: {result}" for name, result in results.items() if isinstance(result, RenderError)] if errors: raise RenderError("\n".join(errors)) @@ -169,11 +206,15 @@ def update(args): sclang = find_sclang(args.sclang) if not sclang: raise SystemExit("sclang not found. Put it on PATH, set SCLANG or use --sclang.") + pandoc = find_pandoc() + if not pandoc: + raise SystemExit("pandoc not found. Put it on PATH or set PANDOC.") for md_path in fixtures(): md_path.with_suffix(".schelp").write_text(convert(md_path)) for stem, body in render_all(sclang).items(): (FIXTURES / f"{stem}.html").write_text(body) VERSION_FILE.write_text(sclang_version(sclang) + "\n") + PANDOC_VERSION_FILE.write_text(pandoc_version(pandoc) + "\n") print("written; look at the diff") diff --git a/tests/test_schelp_behavior.py b/tests/test_schelp_behavior.py index f36bb38..4fc6617 100644 --- a/tests/test_schelp_behavior.py +++ b/tests/test_schelp_behavior.py @@ -87,7 +87,7 @@ def test_front_matter_without_an_end_is_text(): def test_front_matter_keeps_the_line_numbers(): with pytest.raises(UnsupportedConstruct) as error: - convert_schelp("---\ntitle: T\nsummary: S\n---\n\nText.\n\n> A block quote.\n") + convert_schelp("---\ntitle: T\nsummary: S\n---\n\nText.\n\nA tag.\n") assert error.value.line == 8 @@ -266,3 +266,18 @@ def test_hash_without_a_space_after_it_is_text(): def test_quotation_marks_stay(): assert convert_schelp("He said \"it is 'fine' now\".\n") == "He said \"it is 'fine' now\".\n" + + +@pytest.mark.parametrize("markdown, schelp", [ + ("A word**bold**.\n", "A word\u2060strong::bold::.\n"), + ("A word*italic*.\n", "A word\u2060emphasis::italic::.\n"), + ("A word`code`.\n", "A word\u2060code::code::.\n"), + ("A word[link](https://example.com).\n", "A word\u2060link::https://example.com##link::.\n"), + ("A word$x$.\n", "A word\u2060math::x::.\n"), + ("A word[^1].\n\n[^1]: A note.\n", "A word footnote::A note.::.\n"), + ("A word **bold** and 2**bold**.\n", "A word strong::bold:: and 2strong::bold::.\n"), +], ids=["bold", "italic", "code", "link", "math", "footnote", "no letter before"]) +def test_tag_directly_after_a_letter(markdown, schelp): + # SCDoc takes letters directly before `::` as the name of a tag: a word joiner (U+2060), or a space before a + # footnote, keeps the word and the tag apart + assert convert_schelp(markdown) == schelp diff --git a/tests/test_schelp_citations.py b/tests/test_schelp_citations.py new file mode 100644 index 0000000..8b1ce7b --- /dev/null +++ b/tests/test_schelp_citations.py @@ -0,0 +1,107 @@ +""" +Citations in the schelp output: with a bibliography, pandoc writes each citation (`[@key]`), and the citation +becomes a footnote. The first citation of a source gives its reference entry, later citations the short form. +A citation in a footnote gives the short form in parentheses. The tests that run pandoc are skipped without it. +""" +from pathlib import Path + +import pytest + +from md2misc import DocumentError, UnsupportedConstruct, convert, convert_schelp + +BIBLIOGRAPHY = Path(__file__).parent / "schelp" / "citations.bib" +DOE = "Doe, Jane. 1999. emphasis::Sound and Wood::. Acme" +SMITH = ("Smith, John, and Ann Lee. 2000. “Bars and Rods: A Study of Modes.” emphasis::Journal of Acoustics:: 3: " + "1–9. link::https://doi.org/10.1000/xyz::") + + +def schelp(markdown: str) -> str: + return convert_schelp(markdown, bibliography=BIBLIOGRAPHY) + + +@pytest.mark.parametrize("citation, footnote", [ + ("[@doe1999]", DOE + "."), + ("[@doe1999, p. 30]", DOE + ", p. 30."), + ("[@doe1999, 30]", DOE + ", p. 30."), + ("[@doe1999, 30-35]", DOE + ", pp. 30–35."), + ("[@doe1999, chap. 2]", DOE + ", chap. 2."), + ("[-@doe1999]", DOE + "."), + ("[@doe1999; @smith2000]", DOE + "; " + SMITH + "."), +], ids=["key", "page", "page number", "pages", "other locator", "no author", "two sources"]) +def test_first_citation_gives_the_reference_entry(citation, footnote, pandoc): + assert schelp(f"A text {citation}.\n") == f"A text footnote::{footnote}::.\n" + + +def test_later_citation_gives_the_short_form(pandoc): + out = schelp("One [@doe1999]. Two [@doe1999, 31]. Three [@smith2000; @doe1999].\n") + assert out == (f"One footnote::{DOE}.::. Two footnote::Doe 1999, 31.::. " + f"Three footnote::{SMITH}; Doe 1999.::.\n") + + +def test_works_of_one_author_and_year_are_told_apart(pandoc): + out = schelp("One [@doe1999]. Two [@doe1999b]. Again [@doe1999b].\n") + assert out == ("One footnote::Doe, Jane. 1999b. emphasis::Sound and Wood::. Acme.::. " + # the style writes `———` for the second work of an author in a list; a footnote names the + # author again + "Two footnote::Doe, Jane. 1999a. emphasis::More Wood::. Acme.::. Again footnote::Doe 1999a.::.\n") + + +def test_citation_in_a_footnote_gives_the_short_form_in_parentheses(pandoc): + out = schelp("Text.[^1] More [@smith2000].\n\n[^1]: As in [@doe1999, 30].\n\n And [@smith2000].\n") + assert out == ("Text.footnote::As in (Doe 1999, 30).\n\nAnd (Smith and Lee 2000).:: " + f"More footnote::{SMITH}.::.\n") + + +def test_citation_directly_after_a_word(pandoc): + # SCDoc does not find a tag directly after a letter; it removes the space before a footnote mark + assert schelp("A text[@doe1999].\n") == f"A text footnote::{DOE}.::.\n" + + +def test_citation_at_the_start_of_a_line(pandoc): + assert schelp("A text\n[@doe1999].\n") == f"A text\nfootnote::{DOE}.::.\n" + + +def test_text_in_brackets_with_an_at_sign_later_is_text(): + # as in the TeX output: a citation starts with `@` or `-@` + assert schelp("A text [see @doe1999].\n") == "A text [see @doe1999].\n" + + +def test_citation_in_code_is_code(): + assert schelp("Code `[@doe1999]`.\n") == "Code code::[@doe1999]::.\n" + + +def test_missing_key_stops_the_conversion(pandoc): + with pytest.raises(DocumentError, match="no entry for: nobody"): + schelp("A text [@nobody].\n") + + +def test_bibliography_that_is_not_a_file(): + with pytest.raises(DocumentError, match="is not a file"): + convert_schelp("A text [@doe1999].\n", bibliography="no-such-file.bib") + + +def test_pandoc_that_cannot_run(monkeypatch): + monkeypatch.setenv("PANDOC", "/no/such/pandoc") + with pytest.raises(DocumentError, match="could not run pandoc"): + schelp("A text [@doe1999].\n") + + +@pytest.mark.parametrize("citation", ["[@doe1999; smith]", "[@doe1999 @smith2000]", "[@doe1999, p. 3; see]"]) +def test_other_forms_of_a_citation_stop_the_conversion(citation): + with pytest.raises(UnsupportedConstruct, match="the forms are"): + schelp(f"A text {citation}.\n") + + +def test_text_without_citations_does_not_need_the_bibliography(monkeypatch): + monkeypatch.setenv("PANDOC", "/no/such/pandoc") + assert schelp("A text.\n") == "A text.\n" + + +def test_citation_without_a_bibliography_names_the_choices(): + with pytest.raises(UnsupportedConstruct, match="give a bibliography to the conversion, or write the citation " + "as text"): + convert_schelp("A text [@doe1999].\n") + + +def test_tex_output_does_not_change(): + assert convert("A text [@doe1999, 30].\n").strip() == "A text \\parencite[p. 30]{doe1999}." diff --git a/tests/test_schelp_errors.py b/tests/test_schelp_errors.py index 489e24a..9108ec4 100644 --- a/tests/test_schelp_errors.py +++ b/tests/test_schelp_errors.py @@ -23,10 +23,10 @@ def test_unsupported_construct_stops_the_conversion(markdown, construct, line): def test_error_names_the_file_and_the_line(): with pytest.raises(UnsupportedConstruct) as error: - convert_schelp("Text.\n\n> A quote.\n") - assert str(error.value) == "line 3: the schelp output cannot write this Markdown construct: block quote" + convert_schelp("Text.\n\n---\n") + assert str(error.value) == "line 3: the schelp output cannot write this Markdown construct: horizontal rule" assert error.value.describe("page.md") == \ - "page.md:3: the schelp output cannot write this Markdown construct: block quote" + "page.md:3: the schelp output cannot write this Markdown construct: horizontal rule" @pytest.mark.parametrize("markdown, metadata, insertions, message", DOCUMENT_ERRORS, diff --git a/tests/test_schelp_golden.py b/tests/test_schelp_golden.py index 2a768f5..f941cdc 100644 --- a/tests/test_schelp_golden.py +++ b/tests/test_schelp_golden.py @@ -4,11 +4,13 @@ """ import pytest -from schelp_fixtures import convert, fixtures +from schelp_fixtures import convert, fixtures, needs_pandoc FIXTURE_FILES = fixtures() @pytest.mark.parametrize("md_path", FIXTURE_FILES, ids=[p.stem for p in FIXTURE_FILES]) -def test_schelp_output_is_unchanged(md_path): +def test_schelp_output_is_unchanged(md_path, request): + if needs_pandoc(md_path): + request.getfixturevalue("same_pandoc_as_fixtures") assert convert(md_path) == md_path.with_suffix(".schelp").read_text() diff --git a/tests/test_schelp_methods.py b/tests/test_schelp_methods.py index 35030df..3c1a01c 100644 --- a/tests/test_schelp_methods.py +++ b/tests/test_schelp_methods.py @@ -186,6 +186,50 @@ def test_returns_that_is_text(markdown): assert "Returns:" in out +# ---------------------------------------------------------- the instance methods + + +def test_instance_methods_section(): + out = convert_schelp("## Instance methods\n\n### -play, -stop\n\nPlays it.\n\n" + TABLE + + "\nReturns: this.\n") + assert out == ("INSTANCEMETHODS::\n\nMETHOD::play, stop\n\nPlays it.\n\n" + "ARGUMENT::freq\nThe frequency.\n\nARGUMENT::amp\nThe level.\n\nreturns::this.\n") + + +def test_both_methods_sections(): + out = convert_schelp("## Class methods\n\n### *new\n\nMakes one.\n\n" + "## Instance methods\n\n### -free\n\nFrees it.\n") + assert out == ("CLASSMETHODS::\n\nMETHOD::new\n\nMakes one.\n\n" + "INSTANCEMETHODS::\n\nMETHOD::free\n\nFrees it.\n") + + +def test_instance_method_heading_outside_a_methods_section_is_a_heading(): + assert "SUBSECTION::-play" in convert_schelp("## Section\n\n### -play\n\nText.\n") + + +# ------------------------------------------------------------------ the discussion + + +@pytest.mark.parametrize("before", ["", TABLE + "\n", "Returns: x.\n\n", TABLE + "\nReturns: x.\n\n"], + ids=["after the text", "after the table", "after the return value", "after both"]) +def test_discussion(before): + out = methods("### *ar\n\nText.\n\n" + before + "#### Discussion\n\nMore text.\n\n```\nx = 1;\n```\n") + assert out.endswith("discussion::\n\nMore text.\n\ncode::\nx = 1;\n::\n") + assert "SUBSUBSECTION" not in out + + +def test_discussion_can_hold_any_text(): + out = methods("### *ar\n\n" + TABLE + "\n#### discussion\n\nReturns: text here.\n\n- A list.\n\n" + "> [!NOTE]\n> A note.\n\n### *kr\n\nText.\n") + assert "discussion::\n\nReturns: text here.\n\nLIST::\n## A list.\n::" in out + assert out.count("returns::") == 0 + assert "METHOD::kr" in out + + +def test_discussion_heading_outside_a_methods_section_is_a_heading(): + assert "SUBSUBSECTION::Discussion" in convert_schelp("## Section\n\n#### Discussion\n\nText.\n") + + # ------------------------------------------------------------ the other backend diff --git a/tests/test_schelp_render.py b/tests/test_schelp_render.py index ae6d2be..17d6b16 100644 --- a/tests/test_schelp_render.py +++ b/tests/test_schelp_render.py @@ -11,7 +11,7 @@ from md2misc import convert_schelp from schelp_cases import RENDERS, SUPPORTED -from schelp_fixtures import FIXTURES, RenderError, fixtures, render_texts +from schelp_fixtures import FIXTURES, IMAGES, RenderError, fixtures, needs_pandoc, render_texts FIXTURE_FILES = fixtures() @@ -28,13 +28,17 @@ @pytest.mark.parametrize("stem", [p.stem for p in FIXTURE_FILES]) -def test_fixture_renders_without_error(stem, rendered_pages): +def test_fixture_renders_without_error(stem, rendered_pages, request): + if needs_pandoc(FIXTURES / f"{stem}.md"): + request.getfixturevalue("pandoc") # `rendered_pages` fails if SCDoc reports an error for a fixture assert stem in rendered_pages @pytest.mark.parametrize("stem", [p.stem for p in FIXTURE_FILES]) -def test_page_is_as_expected(stem, rendered_pages, same_version_as_fixtures): +def test_page_is_as_expected(stem, rendered_pages, same_version_as_fixtures, request): + if needs_pandoc(FIXTURES / f"{stem}.md"): + request.getfixturevalue("same_pandoc_as_fixtures") assert rendered_pages[stem] == (FIXTURES / f"{stem}.html").read_text() @@ -64,3 +68,10 @@ def test_case_renders(markdown, parts, rendered_cases): raise page for part in parts: assert part in page + + +def test_scdoc_puts_the_image_next_to_the_page(sclang): + copied = [] + pages = render_texts(sclang, {"image": convert_schelp("![A caption](images/md2misc-test.png)\n")}, copied=copied) + assert "
A caption" in pages["image"] + assert copied == ["images/" + p.name for p in sorted(IMAGES.iterdir())] diff --git a/tests/test_schelp_tables.py b/tests/test_schelp_tables.py new file mode 100644 index 0000000..98cd168 --- /dev/null +++ b/tests/test_schelp_tables.py @@ -0,0 +1,49 @@ +""" +Tables outside the methods sections: a pipe table of GitHub Flavored Markdown gives `table::`. SCDoc has no header +row, thus the header row is a first row in bold. The checks that stop the conversion are in schelp_cases.py. +""" +import pytest + +from md2misc import convert, convert_schelp + + +@pytest.mark.parametrize("markdown, schelp", [ + ("| A | B |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n", + "table::\n## strong::A:: || strong::B::\n## 1 || 2\n## 3 || 4\n::\n"), + ("| | |\n|---|---|\n| 1 | 2 |\n", "table::\n## 1 || 2\n::\n"), + ("| A | |\n|---|---|\n| 1 | 2 |\n", "table::\n## strong::A:: ||\n## 1 || 2\n::\n"), + ("| A | B |\n|---|---|\n| 1 |\n", "table::\n## strong::A:: || strong::B::\n## 1 ||\n::\n"), + ("A | B\n:-:|--:\n1 | 2\n", "table::\n## strong::A:: || strong::B::\n## 1 || 2\n::\n"), + ("| A |\n|---|\n| 1 |\n", "table::\n## strong::A::\n## 1\n::\n"), +], ids=["header and rows", "empty header row", "empty header cell", "short row", "no outer pipes and alignment", + "one column"]) +def test_table(markdown, schelp): + assert convert_schelp(markdown) == schelp + + +@pytest.mark.parametrize("cell, text", [ + ("Uses `In.ar`.", "Uses code::In.ar::."), + ("A **loud** sound.", "A strong::loud:: sound."), + ("See [SinOsc](sc:Classes/SinOsc).", "See link::Classes/SinOsc::."), + ("One \\| two.", "One | two."), + ("Code `a \\| b`.", "Code code::a | b::."), + ("A \\|\\| B and ## C.", "A \\|| B and \\## C."), + ("Math $x^2$.", "Math math::x^2::."), +], ids=["code", "bold", "link", "escaped pipe", "escaped pipe in code", "schelp marks", "math"]) +def test_markup_in_a_cell(cell, text): + assert convert_schelp(f"| A |\n|---|\n| {cell} |\n") == f"table::\n## strong::A::\n## {text}\n::\n" + + +def test_table_between_paragraphs(): + out = convert_schelp("## Section\n\nBefore.\n\n| A |\n|---|\n| 1 |\n\nAfter.\n") + assert out == "SECTION::Section\n\nBefore.\n\ntable::\n## strong::A::\n## 1\n::\n\nAfter.\n" + + +def test_table_in_the_examples_section_of_a_class(): + out = convert_schelp("## Class methods\n\n### *ar\n\nText.\n\n## Examples\n\n| A |\n|---|\n| 1 |\n") + assert out.endswith("EXAMPLES::\n\ntable::\n## strong::A::\n## 1\n::\n") + + +def test_tex_output_does_not_change(): + tex = convert("| A | B |\n|---|---|\n| 1 | 2 |\n") + assert "table" not in tex and "| A | B |" in tex diff --git a/tests/test_schelp_writer.py b/tests/test_schelp_writer.py index ccd6e20..a8fa76a 100644 --- a/tests/test_schelp_writer.py +++ b/tests/test_schelp_writer.py @@ -12,10 +12,6 @@ # the front matter errors come from the reading of the front matter, not from the writers FROM_THE_WRITERS = [case for case in UNSUPPORTED if not case[1].startswith("front matter")] -# the construct that the writers name, if it is not the one that the check of the source names: the converter -# takes an audio file for an image, as the audio syntax is the one of an image -NAMED_BY_THE_WRITERS = {"audio file": "image"} - @pytest.fixture def no_source_check(monkeypatch): @@ -28,7 +24,7 @@ def no_source_check(monkeypatch): def test_writer_stops_at_the_construct(no_source_check, markdown, construct, line): with pytest.raises(UnsupportedConstruct) as error: convert_schelp(markdown) - assert NAMED_BY_THE_WRITERS.get(construct, construct) in error.value.message + assert construct in error.value.message assert error.value.line is None